From 0dcfc1f067beacebc02090ecd0cba4a438acae6f Mon Sep 17 00:00:00 2001 From: Shivanee Persaud Date: Fri, 1 May 2026 16:39:18 -0700 Subject: [PATCH 1/2] feat: natively format generated TS client libraries with Prettier --- .../gapic-generator-typescript/BUILD.bazel | 1 + .../asset-esm/esm/src/index.ts.baseline | 6 +- .../src/v1/asset_service_client.ts.baseline | 1607 ++- .../asset-esm/esm/src/v1/index.ts.baseline | 2 +- .../fixtures/sample/src/index.ts.baseline | 2 +- .../esm/system-test/install.ts.baseline | 27 +- .../test/gapic_asset_service_v1.ts.baseline | 2400 ++-- .../baselines/asset/src/index.ts.baseline | 6 +- .../src/v1/asset_service_client.ts.baseline | 1597 ++- .../baselines/asset/src/v1/index.ts.baseline | 2 +- .../fixtures/sample/src/index.ts.baseline | 2 +- .../asset/system-test/install.ts.baseline | 24 +- .../test/gapic_asset_service_v1.ts.baseline | 2388 ++-- .../esm/src/index.ts.baseline | 6 +- .../big_query_storage_client.ts.baseline | 1162 +- .../esm/src/v1beta1/index.ts.baseline | 2 +- .../fixtures/sample/src/index.ts.baseline | 2 +- .../esm/system-test/install.ts.baseline | 27 +- ...apic_big_query_storage_v1beta1.ts.baseline | 1915 +-- .../bigquery-storage/src/index.ts.baseline | 6 +- .../big_query_storage_client.ts.baseline | 1150 +- .../src/v1beta1/index.ts.baseline | 2 +- .../fixtures/sample/src/index.ts.baseline | 2 +- .../system-test/install.ts.baseline | 24 +- ...apic_big_query_storage_v1beta1.ts.baseline | 1907 +-- .../bigquery-v2-esm/esm/src/index.ts.baseline | 24 +- .../src/v2/dataset_service_client.ts.baseline | 1676 ++- .../esm/src/v2/index.ts.baseline | 14 +- .../esm/src/v2/job_service_client.ts.baseline | 1782 +-- .../src/v2/model_service_client.ts.baseline | 1058 +- .../src/v2/project_service_client.ts.baseline | 333 +- .../src/v2/routine_service_client.ts.baseline | 1449 ++- ...w_access_policy_service_client.ts.baseline | 523 +- .../src/v2/table_service_client.ts.baseline | 1482 ++- .../fixtures/sample/src/index.ts.baseline | 14 +- .../esm/system-test/install.ts.baseline | 27 +- .../test/gapic_dataset_service_v2.ts.baseline | 2548 ++-- .../esm/test/gapic_job_service_v2.ts.baseline | 2486 ++-- .../test/gapic_model_service_v2.ts.baseline | 1913 +-- .../test/gapic_project_service_v2.ts.baseline | 586 +- .../test/gapic_routine_service_v2.ts.baseline | 2328 ++-- ...c_row_access_policy_service_v2.ts.baseline | 1144 +- .../test/gapic_table_service_v2.ts.baseline | 2496 ++-- .../bigquery-v2/src/index.ts.baseline | 24 +- .../src/v2/dataset_service_client.ts.baseline | 1662 ++- .../bigquery-v2/src/v2/index.ts.baseline | 14 +- .../src/v2/job_service_client.ts.baseline | 1768 +-- .../src/v2/model_service_client.ts.baseline | 1041 +- .../src/v2/project_service_client.ts.baseline | 318 +- .../src/v2/routine_service_client.ts.baseline | 1434 +- ...w_access_policy_service_client.ts.baseline | 507 +- .../src/v2/table_service_client.ts.baseline | 1467 ++- .../fixtures/sample/src/index.ts.baseline | 14 +- .../system-test/install.ts.baseline | 24 +- .../test/gapic_dataset_service_v2.ts.baseline | 2542 ++-- .../test/gapic_job_service_v2.ts.baseline | 2480 ++-- .../test/gapic_model_service_v2.ts.baseline | 1907 +-- .../test/gapic_project_service_v2.ts.baseline | 580 +- .../test/gapic_routine_service_v2.ts.baseline | 2322 ++-- ...c_row_access_policy_service_v2.ts.baseline | 1138 +- .../test/gapic_table_service_v2.ts.baseline | 2490 ++-- .../compute-esm/esm/src/index.ts.baseline | 6 +- .../esm/src/v1/addresses_client.ts.baseline | 1102 +- .../compute-esm/esm/src/v1/index.ts.baseline | 4 +- .../v1/region_operations_client.ts.baseline | 543 +- .../fixtures/sample/src/index.ts.baseline | 2 +- .../esm/system-test/install.ts.baseline | 27 +- .../esm/test/gapic_addresses_v1.ts.baseline | 1753 +-- .../gapic_region_operations_v1.ts.baseline | 936 +- .../baselines/compute/src/index.ts.baseline | 6 +- .../src/v1/addresses_client.ts.baseline | 1084 +- .../compute/src/v1/index.ts.baseline | 4 +- .../v1/region_operations_client.ts.baseline | 529 +- .../fixtures/sample/src/index.ts.baseline | 2 +- .../compute/system-test/install.ts.baseline | 24 +- .../test/gapic_addresses_v1.ts.baseline | 1747 +-- .../gapic_region_operations_v1.ts.baseline | 930 +- .../esm/src/index.ts.baseline | 6 +- .../v1/deprecated_service_client.ts.baseline | 494 +- .../esm/src/v1/index.ts.baseline | 2 +- .../fixtures/sample/src/index.ts.baseline | 2 +- .../esm/system-test/install.ts.baseline | 27 +- .../deprecatedtest/src/index.ts.baseline | 6 +- .../v1/deprecated_service_client.ts.baseline | 480 +- .../deprecatedtest/src/v1/index.ts.baseline | 2 +- .../fixtures/sample/src/index.ts.baseline | 2 +- .../system-test/install.ts.baseline | 24 +- .../esm/src/index.ts.baseline | 22 +- .../src/v1beta1/compliance_client.ts.baseline | 2172 ++-- .../esm/src/v1beta1/echo_client.ts.baseline | 1808 ++- .../src/v1beta1/identity_client.ts.baseline | 1249 +- .../esm/src/v1beta1/index.ts.baseline | 12 +- .../src/v1beta1/messaging_client.ts.baseline | 2742 ++-- .../sequence_service_client.ts.baseline | 798 +- .../src/v1beta1/testing_client.ts.baseline | 1908 +-- .../test/gapic_compliance_v1beta1.ts.baseline | 3339 ++--- .../esm/test/gapic_echo_v1beta1.ts.baseline | 3231 +++-- .../test/gapic_identity_v1beta1.ts.baseline | 2541 ++-- .../test/gapic_messaging_v1beta1.ts.baseline | 5052 ++++---- ...gapic_sequence_service_v1beta1.ts.baseline | 1861 +-- .../test/gapic_testing_v1beta1.ts.baseline | 3524 ++--- .../src/index.ts.baseline | 22 +- .../src/v1beta1/compliance_client.ts.baseline | 2166 ++-- .../src/v1beta1/echo_client.ts.baseline | 1794 ++- .../src/v1beta1/identity_client.ts.baseline | 1235 +- .../src/v1beta1/index.ts.baseline | 12 +- .../src/v1beta1/messaging_client.ts.baseline | 2732 ++-- .../sequence_service_client.ts.baseline | 785 +- .../src/v1beta1/testing_client.ts.baseline | 1896 +-- .../test/gapic_compliance_v1beta1.ts.baseline | 3311 ++--- .../test/gapic_echo_v1beta1.ts.baseline | 3205 +++-- .../test/gapic_identity_v1beta1.ts.baseline | 2513 ++-- .../test/gapic_messaging_v1beta1.ts.baseline | 5026 +++---- ...gapic_sequence_service_v1beta1.ts.baseline | 1833 +-- .../test/gapic_testing_v1beta1.ts.baseline | 3496 ++--- .../dlp-esm/esm/src/index.ts.baseline | 6 +- .../esm/src/v2/dlp_service_client.ts.baseline | 7869 ++++++----- .../dlp-esm/esm/src/v2/index.ts.baseline | 2 +- .../fixtures/sample/src/index.ts.baseline | 2 +- .../esm/system-test/install.ts.baseline | 27 +- .../esm/test/gapic_dlp_service_v2.ts.baseline | 10784 +++++++++------- .../baselines/dlp/src/index.ts.baseline | 6 +- .../dlp/src/v2/dlp_service_client.ts.baseline | 7879 ++++++----- .../baselines/dlp/src/v2/index.ts.baseline | 2 +- .../fixtures/sample/src/index.ts.baseline | 2 +- .../dlp/system-test/install.ts.baseline | 24 +- .../dlp/test/gapic_dlp_service_v2.ts.baseline | 10758 ++++++++------- .../esm/src/index.ts.baseline | 6 +- ...te_methods_test_service_client.ts.baseline | 1022 +- .../esm/src/v1/index.ts.baseline | 2 +- .../fixtures/sample/src/index.ts.baseline | 13 +- .../esm/system-test/install.ts.baseline | 27 +- ...licate_methods_test_service_v1.ts.baseline | 2055 +-- .../src/index.ts.baseline | 6 +- ...te_methods_test_service_client.ts.baseline | 1008 +- .../src/v1/index.ts.baseline | 2 +- .../fixtures/sample/src/index.ts.baseline | 13 +- .../system-test/install.ts.baseline | 24 +- ...licate_methods_test_service_v1.ts.baseline | 2049 +-- .../kms-esm/esm/src/index.ts.baseline | 6 +- .../kms-esm/esm/src/v1/index.ts.baseline | 2 +- .../key_management_service_client.ts.baseline | 5378 ++++---- .../fixtures/sample/src/index.ts.baseline | 6 +- .../esm/system-test/install.ts.baseline | 27 +- ...apic_key_management_service_v1.ts.baseline | 8006 +++++++----- .../baselines/kms/src/index.ts.baseline | 6 +- .../baselines/kms/src/v1/index.ts.baseline | 2 +- .../key_management_service_client.ts.baseline | 5381 ++++---- .../fixtures/sample/src/index.ts.baseline | 6 +- .../kms/system-test/install.ts.baseline | 24 +- ...apic_key_management_service_v1.ts.baseline | 8000 +++++++----- .../logging-esm/esm/src/index.ts.baseline | 16 +- .../v2/config_service_v2_client.ts.baseline | 6710 ++++++---- .../logging-esm/esm/src/v2/index.ts.baseline | 6 +- .../v2/logging_service_v2_client.ts.baseline | 2530 ++-- .../v2/metrics_service_v2_client.ts.baseline | 1752 ++- .../fixtures/sample/src/index.ts.baseline | 6 +- .../esm/system-test/install.ts.baseline | 27 +- .../gapic_config_service_v2_v2.ts.baseline | 10751 ++++++++------- .../gapic_logging_service_v2_v2.ts.baseline | 5224 +++++--- .../gapic_metrics_service_v2_v2.ts.baseline | 4874 ++++--- .../baselines/logging/src/index.ts.baseline | 16 +- .../v2/config_service_v2_client.ts.baseline | 6715 ++++++---- .../logging/src/v2/index.ts.baseline | 6 +- .../v2/logging_service_v2_client.ts.baseline | 2516 ++-- .../v2/metrics_service_v2_client.ts.baseline | 1740 ++- .../fixtures/sample/src/index.ts.baseline | 6 +- .../logging/system-test/install.ts.baseline | 24 +- .../gapic_config_service_v2_v2.ts.baseline | 10683 ++++++++------- .../gapic_logging_service_v2_v2.ts.baseline | 5158 +++++--- .../gapic_metrics_service_v2_v2.ts.baseline | 4808 ++++--- .../monitoring-esm/esm/src/index.ts.baseline | 22 +- .../alert_policy_service_client.ts.baseline | 1962 +-- .../src/v3/group_service_client.ts.baseline | 2261 ++-- .../esm/src/v3/index.ts.baseline | 12 +- .../src/v3/metric_service_client.ts.baseline | 3146 +++-- ...ication_channel_service_client.ts.baseline | 3238 +++-- ...vice_monitoring_service_client.ts.baseline | 3019 +++-- .../uptime_check_service_client.ts.baseline | 2183 ++-- .../fixtures/sample/src/index.ts.baseline | 20 +- .../esm/system-test/install.ts.baseline | 27 +- .../gapic_alert_policy_service_v3.ts.baseline | 4464 ++++--- .../test/gapic_group_service_v3.ts.baseline | 4999 ++++--- .../test/gapic_metric_service_v3.ts.baseline | 6473 ++++++---- ...otification_channel_service_v3.ts.baseline | 6352 +++++---- ..._service_monitoring_service_v3.ts.baseline | 6248 +++++---- .../gapic_uptime_check_service_v3.ts.baseline | 4917 ++++--- .../monitoring/src/index.ts.baseline | 22 +- .../alert_policy_service_client.ts.baseline | 1950 +-- .../src/v3/group_service_client.ts.baseline | 2249 ++-- .../monitoring/src/v3/index.ts.baseline | 12 +- .../src/v3/metric_service_client.ts.baseline | 3135 +++-- ...ication_channel_service_client.ts.baseline | 3230 +++-- ...vice_monitoring_service_client.ts.baseline | 3011 +++-- .../uptime_check_service_client.ts.baseline | 2171 ++-- .../fixtures/sample/src/index.ts.baseline | 20 +- .../system-test/install.ts.baseline | 24 +- .../gapic_alert_policy_service_v3.ts.baseline | 4410 ++++--- .../test/gapic_group_service_v3.ts.baseline | 4945 ++++--- .../test/gapic_metric_service_v3.ts.baseline | 6407 +++++---- ...otification_channel_service_v3.ts.baseline | 6298 +++++---- ..._service_monitoring_service_v3.ts.baseline | 6194 +++++---- .../gapic_uptime_check_service_v3.ts.baseline | 4863 ++++--- .../naming-esm/esm/src/index.ts.baseline | 6 +- .../esm/src/v1beta1/index.ts.baseline | 2 +- .../esm/src/v1beta1/naming_client.ts.baseline | 2353 ++-- .../fixtures/sample/src/index.ts.baseline | 2 +- .../esm/system-test/install.ts.baseline | 27 +- .../esm/test/gapic_naming_v1beta1.ts.baseline | 2787 ++-- .../baselines/naming/src/index.ts.baseline | 6 +- .../naming/src/v1beta1/index.ts.baseline | 2 +- .../src/v1beta1/naming_client.ts.baseline | 2346 ++-- .../fixtures/sample/src/index.ts.baseline | 2 +- .../naming/system-test/install.ts.baseline | 24 +- .../test/gapic_naming_v1beta1.ts.baseline | 2777 ++-- .../redis-esm/esm/src/index.ts.baseline | 6 +- .../v1beta1/cloud_redis_client.ts.baseline | 2374 ++-- .../esm/src/v1beta1/index.ts.baseline | 2 +- .../fixtures/sample/src/index.ts.baseline | 2 +- .../esm/system-test/install.ts.baseline | 27 +- .../gapic_cloud_redis_v1beta1.ts.baseline | 4050 +++--- .../baselines/redis/src/index.ts.baseline | 6 +- .../v1beta1/cloud_redis_client.ts.baseline | 2359 ++-- .../redis/src/v1beta1/index.ts.baseline | 2 +- .../fixtures/sample/src/index.ts.baseline | 2 +- .../redis/system-test/install.ts.baseline | 24 +- .../gapic_cloud_redis_v1beta1.ts.baseline | 4040 +++--- .../retail-esm/esm/src/index.ts.baseline | 52 +- .../analytics_service_client.ts.baseline | 635 +- .../v2alpha/branch_service_client.ts.baseline | 690 +- .../catalog_service_client.ts.baseline | 3065 +++-- .../completion_service_client.ts.baseline | 961 +- .../control_service_client.ts.baseline | 1449 ++- ...sational_search_service_client.ts.baseline | 503 +- ...rative_question_service_client.ts.baseline | 1319 +- .../esm/src/v2alpha/index.ts.baseline | 30 +- ...er_account_link_service_client.ts.baseline | 1036 +- .../v2alpha/model_service_client.ts.baseline | 2048 +-- .../prediction_service_client.ts.baseline | 727 +- .../product_service_client.ts.baseline | 5000 ++++--- .../project_service_client.ts.baseline | 1937 ++- .../v2alpha/search_service_client.ts.baseline | 2408 ++-- .../serving_config_service_client.ts.baseline | 1826 ++- .../user_event_service_client.ts.baseline | 1920 +-- .../fixtures/sample/src/index.ts.baseline | 48 +- .../esm/system-test/install.ts.baseline | 27 +- ...apic_analytics_service_v2alpha.ts.baseline | 2095 +-- .../gapic_branch_service_v2alpha.ts.baseline | 2181 ++-- .../gapic_catalog_service_v2alpha.ts.baseline | 5060 ++++---- ...pic_completion_service_v2alpha.ts.baseline | 2313 ++-- .../gapic_control_service_v2alpha.ts.baseline | 3279 +++-- ...ational_search_service_v2alpha.ts.baseline | 2124 +-- ...ative_question_service_v2alpha.ts.baseline | 3056 +++-- ...r_account_link_service_v2alpha.ts.baseline | 2687 ++-- .../gapic_model_service_v2alpha.ts.baseline | 4229 +++--- ...pic_prediction_service_v2alpha.ts.baseline | 1940 +-- .../gapic_product_service_v2alpha.ts.baseline | 6034 +++++---- .../gapic_project_service_v2alpha.ts.baseline | 3813 +++--- .../gapic_search_service_v2alpha.ts.baseline | 2507 ++-- ...serving_config_service_v2alpha.ts.baseline | 3746 +++--- ...pic_user_event_service_v2alpha.ts.baseline | 3570 ++--- .../baselines/retail/src/index.ts.baseline | 52 +- .../analytics_service_client.ts.baseline | 619 +- .../v2alpha/branch_service_client.ts.baseline | 676 +- .../catalog_service_client.ts.baseline | 3060 +++-- .../completion_service_client.ts.baseline | 946 +- .../control_service_client.ts.baseline | 1437 +- ...sational_search_service_client.ts.baseline | 487 +- ...rative_question_service_client.ts.baseline | 1308 +- .../retail/src/v2alpha/index.ts.baseline | 30 +- ...er_account_link_service_client.ts.baseline | 1022 +- .../v2alpha/model_service_client.ts.baseline | 2037 +-- .../prediction_service_client.ts.baseline | 712 +- .../product_service_client.ts.baseline | 4988 ++++--- .../project_service_client.ts.baseline | 1928 ++- .../v2alpha/search_service_client.ts.baseline | 2392 ++-- .../serving_config_service_client.ts.baseline | 1816 ++- .../user_event_service_client.ts.baseline | 1906 ++- .../fixtures/sample/src/index.ts.baseline | 48 +- .../retail/system-test/install.ts.baseline | 24 +- ...apic_analytics_service_v2alpha.ts.baseline | 2065 +-- .../gapic_branch_service_v2alpha.ts.baseline | 2151 +-- .../gapic_catalog_service_v2alpha.ts.baseline | 5028 +++---- ...pic_completion_service_v2alpha.ts.baseline | 2283 ++-- .../gapic_control_service_v2alpha.ts.baseline | 3249 +++-- ...ational_search_service_v2alpha.ts.baseline | 2096 +-- ...ative_question_service_v2alpha.ts.baseline | 3026 +++-- ...r_account_link_service_v2alpha.ts.baseline | 2657 ++-- .../gapic_model_service_v2alpha.ts.baseline | 4199 +++--- ...pic_prediction_service_v2alpha.ts.baseline | 1910 +-- .../gapic_product_service_v2alpha.ts.baseline | 6004 +++++---- .../gapic_project_service_v2alpha.ts.baseline | 3781 +++--- .../gapic_search_service_v2alpha.ts.baseline | 2475 ++-- ...serving_config_service_v2alpha.ts.baseline | 3716 +++--- ...pic_user_event_service_v2alpha.ts.baseline | 3540 ++--- .../routingtest-esm/esm/src/index.ts.baseline | 6 +- .../esm/src/v1/index.ts.baseline | 2 +- .../src/v1/test_service_client.ts.baseline | 719 +- .../fixtures/sample/src/index.ts.baseline | 2 +- .../esm/system-test/install.ts.baseline | 27 +- .../test/gapic_test_service_v1.ts.baseline | 917 +- .../routingtest/src/index.ts.baseline | 6 +- .../routingtest/src/v1/index.ts.baseline | 2 +- .../src/v1/test_service_client.ts.baseline | 706 +- .../fixtures/sample/src/index.ts.baseline | 2 +- .../system-test/install.ts.baseline | 24 +- .../test/gapic_test_service_v1.ts.baseline | 911 +- .../showcase-esm/esm/src/index.ts.baseline | 22 +- .../src/v1beta1/compliance_client.ts.baseline | 2172 ++-- .../esm/src/v1beta1/echo_client.ts.baseline | 1879 ++- .../src/v1beta1/identity_client.ts.baseline | 1249 +- .../esm/src/v1beta1/index.ts.baseline | 12 +- .../src/v1beta1/messaging_client.ts.baseline | 2813 ++-- .../sequence_service_client.ts.baseline | 798 +- .../src/v1beta1/testing_client.ts.baseline | 1908 +-- .../fixtures/sample/src/index.ts.baseline | 9 +- .../esm/system-test/install.ts.baseline | 27 +- .../test/gapic_compliance_v1beta1.ts.baseline | 3339 ++--- .../esm/test/gapic_echo_v1beta1.ts.baseline | 3249 +++-- .../test/gapic_identity_v1beta1.ts.baseline | 2541 ++-- .../test/gapic_messaging_v1beta1.ts.baseline | 5052 ++++---- ...gapic_sequence_service_v1beta1.ts.baseline | 1861 +-- .../test/gapic_testing_v1beta1.ts.baseline | 3524 ++--- .../esm/src/index.ts.baseline | 6 +- .../esm/src/v1beta1/echo_client.ts.baseline | 1600 ++- .../esm/src/v1beta1/index.ts.baseline | 2 +- .../fixtures/sample/src/index.ts.baseline | 2 +- .../esm/system-test/install.ts.baseline | 27 +- .../esm/test/gapic_echo_v1beta1.ts.baseline | 2236 ++-- .../showcase-legacy/src/index.ts.baseline | 6 +- .../src/v1beta1/echo_client.ts.baseline | 1593 ++- .../src/v1beta1/index.ts.baseline | 2 +- .../fixtures/sample/src/index.ts.baseline | 2 +- .../system-test/install.ts.baseline | 24 +- .../test/gapic_echo_v1beta1.ts.baseline | 2238 ++-- .../baselines/showcase/src/index.ts.baseline | 22 +- .../src/v1beta1/compliance_client.ts.baseline | 2166 ++-- .../src/v1beta1/echo_client.ts.baseline | 1867 ++- .../src/v1beta1/identity_client.ts.baseline | 1235 +- .../showcase/src/v1beta1/index.ts.baseline | 12 +- .../src/v1beta1/messaging_client.ts.baseline | 2803 ++-- .../sequence_service_client.ts.baseline | 785 +- .../src/v1beta1/testing_client.ts.baseline | 1896 +-- .../fixtures/sample/src/index.ts.baseline | 9 +- .../showcase/system-test/install.ts.baseline | 24 +- .../test/gapic_compliance_v1beta1.ts.baseline | 3311 ++--- .../test/gapic_echo_v1beta1.ts.baseline | 3223 +++-- .../test/gapic_identity_v1beta1.ts.baseline | 2513 ++-- .../test/gapic_messaging_v1beta1.ts.baseline | 5026 +++---- ...gapic_sequence_service_v1beta1.ts.baseline | 1833 +-- .../test/gapic_testing_v1beta1.ts.baseline | 3496 ++--- .../tasks-esm/esm/src/index.ts.baseline | 6 +- .../esm/src/v2/cloud_tasks_client.ts.baseline | 3921 +++--- .../tasks-esm/esm/src/v2/index.ts.baseline | 2 +- .../fixtures/sample/src/index.ts.baseline | 2 +- .../esm/system-test/install.ts.baseline | 27 +- .../esm/test/gapic_cloud_tasks_v2.ts.baseline | 5002 +++---- .../baselines/tasks/src/index.ts.baseline | 6 +- .../src/v2/cloud_tasks_client.ts.baseline | 3919 +++--- .../baselines/tasks/src/v2/index.ts.baseline | 2 +- .../fixtures/sample/src/index.ts.baseline | 2 +- .../tasks/system-test/install.ts.baseline | 24 +- .../test/gapic_cloud_tasks_v2.ts.baseline | 4992 +++---- .../esm/src/index.ts.baseline | 6 +- .../esm/src/v1/index.ts.baseline | 2 +- .../src/v1/text_to_speech_client.ts.baseline | 515 +- .../fixtures/sample/src/index.ts.baseline | 2 +- .../esm/system-test/install.ts.baseline | 27 +- .../test/gapic_text_to_speech_v1.ts.baseline | 659 +- .../texttospeech/src/index.ts.baseline | 6 +- .../texttospeech/src/v1/index.ts.baseline | 2 +- .../src/v1/text_to_speech_client.ts.baseline | 501 +- .../fixtures/sample/src/index.ts.baseline | 2 +- .../system-test/install.ts.baseline | 24 +- .../test/gapic_text_to_speech_v1.ts.baseline | 653 +- .../translate-esm/esm/src/index.ts.baseline | 6 +- .../esm/src/v3beta1/index.ts.baseline | 2 +- .../translation_service_client.ts.baseline | 2351 ++-- .../fixtures/sample/src/index.ts.baseline | 2 +- .../esm/system-test/install.ts.baseline | 27 +- ...ic_translation_service_v3beta1.ts.baseline | 3159 +++-- .../baselines/translate/src/index.ts.baseline | 6 +- .../translate/src/v3beta1/index.ts.baseline | 2 +- .../translation_service_client.ts.baseline | 2339 ++-- .../fixtures/sample/src/index.ts.baseline | 2 +- .../translate/system-test/install.ts.baseline | 24 +- ...ic_translation_service_v3beta1.ts.baseline | 3149 +++-- .../esm/src/index.ts.baseline | 6 +- .../esm/src/v1/index.ts.baseline | 2 +- ...eo_intelligence_service_client.ts.baseline | 462 +- .../fixtures/sample/src/index.ts.baseline | 6 +- .../esm/system-test/install.ts.baseline | 27 +- ..._video_intelligence_service_v1.ts.baseline | 626 +- .../videointelligence/src/index.ts.baseline | 6 +- .../src/v1/index.ts.baseline | 2 +- ...eo_intelligence_service_client.ts.baseline | 446 +- .../fixtures/sample/src/index.ts.baseline | 6 +- .../system-test/install.ts.baseline | 24 +- ..._video_intelligence_service_v1.ts.baseline | 620 +- .../gapic-generator-typescript/package.json | 1 + .../typescript/src/templater.ts | 29 +- 401 files changed, 370926 insertions(+), 265856 deletions(-) diff --git a/core/generator/gapic-generator-typescript/BUILD.bazel b/core/generator/gapic-generator-typescript/BUILD.bazel index 1d3ebfabd8dc..7dd7d11f5525 100644 --- a/core/generator/gapic-generator-typescript/BUILD.bazel +++ b/core/generator/gapic-generator-typescript/BUILD.bazel @@ -39,6 +39,7 @@ npm_runtime_dependencies = [ "//:node_modules/proto3-json-serializer", "//:node_modules/yargs", "//:node_modules/google-gax", + "//:node_modules/prettier", ] npm_test_dependencies = npm_runtime_dependencies + [ diff --git a/core/generator/gapic-generator-typescript/baselines/asset-esm/esm/src/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/asset-esm/esm/src/index.ts.baseline index 0cf6954ad4d0..f195db21dcd8 100644 --- a/core/generator/gapic-generator-typescript/baselines/asset-esm/esm/src/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/asset-esm/esm/src/index.ts.baseline @@ -19,8 +19,8 @@ import * as v1 from './v1/index.js'; const AssetServiceClient = v1.AssetServiceClient; type AssetServiceClient = v1.AssetServiceClient; -export {v1, AssetServiceClient}; -export default {v1, AssetServiceClient}; +export { v1, AssetServiceClient }; +export default { v1, AssetServiceClient }; // @ts-ignore import * as protos from '../../protos/protos.js'; -export {protos} +export { protos }; diff --git a/core/generator/gapic-generator-typescript/baselines/asset-esm/esm/src/v1/asset_service_client.ts.baseline b/core/generator/gapic-generator-typescript/baselines/asset-esm/esm/src/v1/asset_service_client.ts.baseline index 2a0014fe8f34..eb3c93427674 100644 --- a/core/generator/gapic-generator-typescript/baselines/asset-esm/esm/src/v1/asset_service_client.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/asset-esm/esm/src/v1/asset_service_client.ts.baseline @@ -18,15 +18,22 @@ /* global window */ import * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions, GrpcClientOptions, LROperation} from 'google-gax'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + GrpcClientOptions, + LROperation, +} from 'google-gax'; // @ts-ignore import type * as protos from '../../../protos/protos.js'; import * as asset_service_client_config from './asset_service_client_config.json'; import fs from 'fs'; import path from 'path'; -import {fileURLToPath} from 'url'; -import {getJSON} from '../json-helper.cjs'; +import { fileURLToPath } from 'url'; +import { getJSON } from '../json-helper.cjs'; // @ts-ignore const dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -36,15 +43,15 @@ const dirname = path.dirname(fileURLToPath(import.meta.url)); * This file defines retry strategy and timeouts for all API methods in this library. */ const gapicConfig = getJSON( - path.join(dirname, 'asset_service_client_config.json') + path.join(dirname, 'asset_service_client_config.json'), ); const jsonProtos = getJSON( - path.join(dirname, '..', '..', '..', 'protos/protos.json') + path.join(dirname, '..', '..', '..', 'protos/protos.json'), ); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; const version = getJSON( - path.join(dirname, '..', '..', '..', '..', 'package.json') + path.join(dirname, '..', '..', '..', '..', 'package.json'), ).version; /** @@ -59,7 +66,7 @@ export class AssetServiceClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('asset'); @@ -71,10 +78,10 @@ export class AssetServiceClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; operationsClient: gax.OperationsClient; - assetServiceStub?: Promise<{[name: string]: Function}>; + assetServiceStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of AssetServiceClient. @@ -116,21 +123,42 @@ export class AssetServiceClient { * const client = new AssetServiceClient({fallback: 'rest'}, gax); * ``` */ - constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { // Ensure that options include all the required fields. const staticMembers = this.constructor as typeof AssetServiceClient; - if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { - throw new Error('Please set either universe_domain or universeDomain, but not both.'); + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); } - const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; - this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; this._servicePath = 'cloudasset.' + this._universeDomain; - const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; - const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. if (servicePath !== this._servicePath && !('scopes' in opts)) { @@ -152,7 +180,7 @@ export class AssetServiceClient { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; @@ -169,10 +197,7 @@ export class AssetServiceClient { const isEsm = true; const isEsmString = isEsm ? '-esm' : '-cjs'; // Determine the client header string. - const clientHeader = [ - `gax/${this._gaxModule.version}`, - `gapic/${version}`, - ]; + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/{process.versions.node}${isEsmString}`); } else { @@ -180,7 +205,7 @@ export class AssetServiceClient { } if (!opts.fallback) { clientHeader.push(`grpc/${this._gaxGrpc.grpcVersion}`); - } else if (opts.fallback === 'rest' ) { + } else if (opts.fallback === 'rest') { clientHeader.push(`rest/${this._gaxGrpc.grpcVersion}`); } if (opts.libName && opts.libVersion) { @@ -188,20 +213,22 @@ export class AssetServiceClient { } // Load the applicable protos. - this._protos = this._gaxGrpc.loadProtoJSON(jsonProtos as gax.protobuf.INamespace); + this._protos = this._gaxGrpc.loadProtoJSON( + jsonProtos as gax.protobuf.INamespace, + ); // This API contains "path templates"; forward-slash-separated // identifiers to uniquely identify resources within the API. // Create useful helper objects for these. this.pathTemplates = { folderFeedPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/feeds/{feed}' + 'folders/{folder}/feeds/{feed}', ), organizationFeedPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/feeds/{feed}' + 'organizations/{organization}/feeds/{feed}', ), projectFeedPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/feeds/{feed}' + 'projects/{project}/feeds/{feed}', ), }; @@ -211,29 +238,37 @@ export class AssetServiceClient { // rather than holding a request open. const lroOptions: GrpcClientOptions = { auth: this.auth, - grpc: 'grpc' in this._gaxGrpc ? this._gaxGrpc.grpc : undefined + grpc: 'grpc' in this._gaxGrpc ? this._gaxGrpc.grpc : undefined, }; if (opts.fallback === 'rest') { lroOptions.protoJson = protoFilesRoot; lroOptions.httpRules = []; } - this.operationsClient = this._gaxModule.lro(lroOptions).operationsClient(opts); + this.operationsClient = this._gaxModule + .lro(lroOptions) + .operationsClient(opts); const exportAssetsResponse = protoFilesRoot.lookup( - '.google.cloud.asset.v1.ExportAssetsResponse') as gax.protobuf.Type; + '.google.cloud.asset.v1.ExportAssetsResponse', + ) as gax.protobuf.Type; const exportAssetsMetadata = protoFilesRoot.lookup( - '.google.cloud.asset.v1.ExportAssetsRequest') as gax.protobuf.Type; + '.google.cloud.asset.v1.ExportAssetsRequest', + ) as gax.protobuf.Type; this.descriptors.longrunning = { exportAssets: new this._gaxModule.LongrunningDescriptor( this.operationsClient, exportAssetsResponse.decode.bind(exportAssetsResponse), - exportAssetsMetadata.decode.bind(exportAssetsMetadata)) + exportAssetsMetadata.decode.bind(exportAssetsMetadata), + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.cloud.asset.v1.AssetService', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.cloud.asset.v1.AssetService', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + { 'x-goog-api-client': clientHeader.join(' ') }, + ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -264,37 +299,48 @@ export class AssetServiceClient { // Put together the "service stub" for // google.cloud.asset.v1.AssetService. this.assetServiceStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.cloud.asset.v1.AssetService') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.cloud.asset.v1.AssetService', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.cloud.asset.v1.AssetService, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts, + this._providedCustomServicePath, + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const assetServiceStubMethods = - ['exportAssets', 'batchGetAssetsHistory', 'createFeed', 'getFeed', 'listFeeds', 'updateFeed', 'deleteFeed']; + const assetServiceStubMethods = [ + 'exportAssets', + 'batchGetAssetsHistory', + 'createFeed', + 'getFeed', + 'listFeeds', + 'updateFeed', + 'deleteFeed', + ]; for (const methodName of assetServiceStubMethods) { const callPromise = this.assetServiceStub.then( - stub => (...args: Array<{}>) => { - if (this._terminated) { - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error|null|undefined) => () => { + (stub) => + (...args: Array<{}>) => { + if (this._terminated) { + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { throw err; - }); + }, + ); - const descriptor = - this.descriptors.longrunning[methodName] || - undefined; + const descriptor = this.descriptors.longrunning[methodName] || undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -309,8 +355,14 @@ export class AssetServiceClient { * @returns {string} The DNS address for this service. */ static get servicePath() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'cloudasset.googleapis.com'; } @@ -322,8 +374,14 @@ export class AssetServiceClient { * @returns {string} The DNS address for this service. */ static get apiEndpoint() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'cloudasset.googleapis.com'; } @@ -354,9 +412,7 @@ export class AssetServiceClient { * @returns {string[]} List of default scopes. */ static get scopes() { - return [ - 'https://www.googleapis.com/auth/cloud-platform' - ]; + return ['https://www.googleapis.com/auth/cloud-platform']; } getProjectId(): Promise; @@ -365,8 +421,9 @@ export class AssetServiceClient { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId(callback?: Callback): - Promise|void { + getProjectId( + callback?: Callback, + ): Promise | void { if (callback) { this.auth.getProjectId(callback); return; @@ -377,753 +434,1014 @@ export class AssetServiceClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Batch gets the update history of assets that overlap a time window. - * For RESOURCE content, this API outputs history with asset in both - * non-delete or deleted status. - * For IAM_POLICY content, this API outputs history when the asset and its - * attached IAM POLICY both exist. This can create gaps in the output history. - * If a specified asset does not exist, this API returns an INVALID_ARGUMENT - * error. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The relative name of the root asset. It can only be an - * organization number (such as "organizations/123"), a project ID (such as - * "projects/my-project-id")", or a project number (such as "projects/12345"). - * @param {string[]} request.assetNames - * A list of the full names of the assets. For example: - * `//compute.googleapis.com/projects/my_project_123/zones/zone1/instances/instance1`. - * See [Resource - * Names](https://cloud.google.com/apis/design/resource_names#full_resource_name) - * and [Resource Name - * Format](https://cloud.google.com/asset-inventory/docs/resource-name-format) - * for more info. - * - * The request becomes a no-op if the asset name list is empty, and the max - * size of the asset name list is 100 in one request. - * @param {google.cloud.asset.v1.ContentType} [request.contentType] - * Optional. The content type. - * @param {google.cloud.asset.v1.TimeWindow} [request.readTimeWindow] - * Optional. The time window for the asset history. Both start_time and - * end_time are optional and if set, it must be after the current time minus - * 35 days. If end_time is not set, it is default to current timestamp. - * If start_time is not set, the snapshot of the assets at end_time will be - * returned. The returned results contain all temporal assets whose time - * window overlap with read_time_window. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.asset.v1.BatchGetAssetsHistoryResponse|BatchGetAssetsHistoryResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1/asset_service.batch_get_assets_history.js - * region_tag:cloudasset_v1_generated_AssetService_BatchGetAssetsHistory_async - */ + /** + * Batch gets the update history of assets that overlap a time window. + * For RESOURCE content, this API outputs history with asset in both + * non-delete or deleted status. + * For IAM_POLICY content, this API outputs history when the asset and its + * attached IAM POLICY both exist. This can create gaps in the output history. + * If a specified asset does not exist, this API returns an INVALID_ARGUMENT + * error. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The relative name of the root asset. It can only be an + * organization number (such as "organizations/123"), a project ID (such as + * "projects/my-project-id")", or a project number (such as "projects/12345"). + * @param {string[]} request.assetNames + * A list of the full names of the assets. For example: + * `//compute.googleapis.com/projects/my_project_123/zones/zone1/instances/instance1`. + * See [Resource + * Names](https://cloud.google.com/apis/design/resource_names#full_resource_name) + * and [Resource Name + * Format](https://cloud.google.com/asset-inventory/docs/resource-name-format) + * for more info. + * + * The request becomes a no-op if the asset name list is empty, and the max + * size of the asset name list is 100 in one request. + * @param {google.cloud.asset.v1.ContentType} [request.contentType] + * Optional. The content type. + * @param {google.cloud.asset.v1.TimeWindow} [request.readTimeWindow] + * Optional. The time window for the asset history. Both start_time and + * end_time are optional and if set, it must be after the current time minus + * 35 days. If end_time is not set, it is default to current timestamp. + * If start_time is not set, the snapshot of the assets at end_time will be + * returned. The returned results contain all temporal assets whose time + * window overlap with read_time_window. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.asset.v1.BatchGetAssetsHistoryResponse|BatchGetAssetsHistoryResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/asset_service.batch_get_assets_history.js + * region_tag:cloudasset_v1_generated_AssetService_BatchGetAssetsHistory_async + */ batchGetAssetsHistory( - request?: protos.google.cloud.asset.v1.IBatchGetAssetsHistoryRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.asset.v1.IBatchGetAssetsHistoryResponse, - protos.google.cloud.asset.v1.IBatchGetAssetsHistoryRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.asset.v1.IBatchGetAssetsHistoryRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.asset.v1.IBatchGetAssetsHistoryResponse, + protos.google.cloud.asset.v1.IBatchGetAssetsHistoryRequest | undefined, + {} | undefined, + ] + >; batchGetAssetsHistory( - request: protos.google.cloud.asset.v1.IBatchGetAssetsHistoryRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.asset.v1.IBatchGetAssetsHistoryResponse, - protos.google.cloud.asset.v1.IBatchGetAssetsHistoryRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.asset.v1.IBatchGetAssetsHistoryRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.asset.v1.IBatchGetAssetsHistoryResponse, + | protos.google.cloud.asset.v1.IBatchGetAssetsHistoryRequest + | null + | undefined, + {} | null | undefined + >, + ): void; batchGetAssetsHistory( - request: protos.google.cloud.asset.v1.IBatchGetAssetsHistoryRequest, - callback: Callback< - protos.google.cloud.asset.v1.IBatchGetAssetsHistoryResponse, - protos.google.cloud.asset.v1.IBatchGetAssetsHistoryRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.asset.v1.IBatchGetAssetsHistoryRequest, + callback: Callback< + protos.google.cloud.asset.v1.IBatchGetAssetsHistoryResponse, + | protos.google.cloud.asset.v1.IBatchGetAssetsHistoryRequest + | null + | undefined, + {} | null | undefined + >, + ): void; batchGetAssetsHistory( - request?: protos.google.cloud.asset.v1.IBatchGetAssetsHistoryRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.asset.v1.IBatchGetAssetsHistoryResponse, - protos.google.cloud.asset.v1.IBatchGetAssetsHistoryRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.asset.v1.IBatchGetAssetsHistoryRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.asset.v1.IBatchGetAssetsHistoryResponse, - protos.google.cloud.asset.v1.IBatchGetAssetsHistoryRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.asset.v1.IBatchGetAssetsHistoryResponse, - protos.google.cloud.asset.v1.IBatchGetAssetsHistoryRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.asset.v1.IBatchGetAssetsHistoryRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.asset.v1.IBatchGetAssetsHistoryResponse, + | protos.google.cloud.asset.v1.IBatchGetAssetsHistoryRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.asset.v1.IBatchGetAssetsHistoryResponse, + protos.google.cloud.asset.v1.IBatchGetAssetsHistoryRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('batchGetAssetsHistory request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.asset.v1.IBatchGetAssetsHistoryResponse, - protos.google.cloud.asset.v1.IBatchGetAssetsHistoryRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.asset.v1.IBatchGetAssetsHistoryResponse, + | protos.google.cloud.asset.v1.IBatchGetAssetsHistoryRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('batchGetAssetsHistory response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.batchGetAssetsHistory(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.asset.v1.IBatchGetAssetsHistoryResponse, - protos.google.cloud.asset.v1.IBatchGetAssetsHistoryRequest|undefined, {}|undefined - ]) => { - this._log.info('batchGetAssetsHistory response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .batchGetAssetsHistory(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.asset.v1.IBatchGetAssetsHistoryResponse, + ( + | protos.google.cloud.asset.v1.IBatchGetAssetsHistoryRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('batchGetAssetsHistory response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Creates a feed in a parent project/folder/organization to listen to its - * asset updates. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The name of the project/folder/organization where this feed - * should be created in. It can only be an organization number (such as - * "organizations/123"), a folder number (such as "folders/123"), a project ID - * (such as "projects/my-project-id")", or a project number (such as - * "projects/12345"). - * @param {string} request.feedId - * Required. This is the client-assigned asset feed identifier and it needs to - * be unique under a specific parent project/folder/organization. - * @param {google.cloud.asset.v1.Feed} request.feed - * Required. The feed details. The field `name` must be empty and it will be generated - * in the format of: - * projects/project_number/feeds/feed_id - * folders/folder_number/feeds/feed_id - * organizations/organization_number/feeds/feed_id - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.asset.v1.Feed|Feed}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1/asset_service.create_feed.js - * region_tag:cloudasset_v1_generated_AssetService_CreateFeed_async - */ + /** + * Creates a feed in a parent project/folder/organization to listen to its + * asset updates. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The name of the project/folder/organization where this feed + * should be created in. It can only be an organization number (such as + * "organizations/123"), a folder number (such as "folders/123"), a project ID + * (such as "projects/my-project-id")", or a project number (such as + * "projects/12345"). + * @param {string} request.feedId + * Required. This is the client-assigned asset feed identifier and it needs to + * be unique under a specific parent project/folder/organization. + * @param {google.cloud.asset.v1.Feed} request.feed + * Required. The feed details. The field `name` must be empty and it will be generated + * in the format of: + * projects/project_number/feeds/feed_id + * folders/folder_number/feeds/feed_id + * organizations/organization_number/feeds/feed_id + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.asset.v1.Feed|Feed}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/asset_service.create_feed.js + * region_tag:cloudasset_v1_generated_AssetService_CreateFeed_async + */ createFeed( - request?: protos.google.cloud.asset.v1.ICreateFeedRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.asset.v1.IFeed, - protos.google.cloud.asset.v1.ICreateFeedRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.asset.v1.ICreateFeedRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.asset.v1.IFeed, + protos.google.cloud.asset.v1.ICreateFeedRequest | undefined, + {} | undefined, + ] + >; createFeed( - request: protos.google.cloud.asset.v1.ICreateFeedRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.asset.v1.IFeed, - protos.google.cloud.asset.v1.ICreateFeedRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.asset.v1.ICreateFeedRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.asset.v1.IFeed, + protos.google.cloud.asset.v1.ICreateFeedRequest | null | undefined, + {} | null | undefined + >, + ): void; createFeed( - request: protos.google.cloud.asset.v1.ICreateFeedRequest, - callback: Callback< - protos.google.cloud.asset.v1.IFeed, - protos.google.cloud.asset.v1.ICreateFeedRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.asset.v1.ICreateFeedRequest, + callback: Callback< + protos.google.cloud.asset.v1.IFeed, + protos.google.cloud.asset.v1.ICreateFeedRequest | null | undefined, + {} | null | undefined + >, + ): void; createFeed( - request?: protos.google.cloud.asset.v1.ICreateFeedRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.asset.v1.IFeed, - protos.google.cloud.asset.v1.ICreateFeedRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.asset.v1.ICreateFeedRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.asset.v1.IFeed, - protos.google.cloud.asset.v1.ICreateFeedRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.asset.v1.IFeed, - protos.google.cloud.asset.v1.ICreateFeedRequest|undefined, {}|undefined - ]>|void { + protos.google.cloud.asset.v1.ICreateFeedRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.asset.v1.IFeed, + protos.google.cloud.asset.v1.ICreateFeedRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.asset.v1.IFeed, + protos.google.cloud.asset.v1.ICreateFeedRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('createFeed request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.asset.v1.IFeed, - protos.google.cloud.asset.v1.ICreateFeedRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.asset.v1.IFeed, + protos.google.cloud.asset.v1.ICreateFeedRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createFeed response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.createFeed(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.asset.v1.IFeed, - protos.google.cloud.asset.v1.ICreateFeedRequest|undefined, {}|undefined - ]) => { - this._log.info('createFeed response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createFeed(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.asset.v1.IFeed, + protos.google.cloud.asset.v1.ICreateFeedRequest | undefined, + {} | undefined, + ]) => { + this._log.info('createFeed response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Gets details about an asset feed. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The name of the Feed and it must be in the format of: - * projects/project_number/feeds/feed_id - * folders/folder_number/feeds/feed_id - * organizations/organization_number/feeds/feed_id - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.asset.v1.Feed|Feed}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1/asset_service.get_feed.js - * region_tag:cloudasset_v1_generated_AssetService_GetFeed_async - */ + /** + * Gets details about an asset feed. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The name of the Feed and it must be in the format of: + * projects/project_number/feeds/feed_id + * folders/folder_number/feeds/feed_id + * organizations/organization_number/feeds/feed_id + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.asset.v1.Feed|Feed}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/asset_service.get_feed.js + * region_tag:cloudasset_v1_generated_AssetService_GetFeed_async + */ getFeed( - request?: protos.google.cloud.asset.v1.IGetFeedRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.asset.v1.IFeed, - protos.google.cloud.asset.v1.IGetFeedRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.asset.v1.IGetFeedRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.asset.v1.IFeed, + protos.google.cloud.asset.v1.IGetFeedRequest | undefined, + {} | undefined, + ] + >; getFeed( - request: protos.google.cloud.asset.v1.IGetFeedRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.asset.v1.IFeed, - protos.google.cloud.asset.v1.IGetFeedRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.asset.v1.IGetFeedRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.asset.v1.IFeed, + protos.google.cloud.asset.v1.IGetFeedRequest | null | undefined, + {} | null | undefined + >, + ): void; getFeed( - request: protos.google.cloud.asset.v1.IGetFeedRequest, - callback: Callback< - protos.google.cloud.asset.v1.IFeed, - protos.google.cloud.asset.v1.IGetFeedRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.asset.v1.IGetFeedRequest, + callback: Callback< + protos.google.cloud.asset.v1.IFeed, + protos.google.cloud.asset.v1.IGetFeedRequest | null | undefined, + {} | null | undefined + >, + ): void; getFeed( - request?: protos.google.cloud.asset.v1.IGetFeedRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.asset.v1.IFeed, - protos.google.cloud.asset.v1.IGetFeedRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.asset.v1.IGetFeedRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.asset.v1.IFeed, - protos.google.cloud.asset.v1.IGetFeedRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.asset.v1.IFeed, - protos.google.cloud.asset.v1.IGetFeedRequest|undefined, {}|undefined - ]>|void { + protos.google.cloud.asset.v1.IGetFeedRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.asset.v1.IFeed, + protos.google.cloud.asset.v1.IGetFeedRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.asset.v1.IFeed, + protos.google.cloud.asset.v1.IGetFeedRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getFeed request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.asset.v1.IFeed, - protos.google.cloud.asset.v1.IGetFeedRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.asset.v1.IFeed, + protos.google.cloud.asset.v1.IGetFeedRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getFeed response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.getFeed(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.asset.v1.IFeed, - protos.google.cloud.asset.v1.IGetFeedRequest|undefined, {}|undefined - ]) => { - this._log.info('getFeed response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getFeed(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.asset.v1.IFeed, + protos.google.cloud.asset.v1.IGetFeedRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getFeed response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Lists all asset feeds in a parent project/folder/organization. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent project/folder/organization whose feeds are to be - * listed. It can only be using project/folder/organization number (such as - * "folders/12345")", or a project ID (such as "projects/my-project-id"). - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.asset.v1.ListFeedsResponse|ListFeedsResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1/asset_service.list_feeds.js - * region_tag:cloudasset_v1_generated_AssetService_ListFeeds_async - */ + /** + * Lists all asset feeds in a parent project/folder/organization. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent project/folder/organization whose feeds are to be + * listed. It can only be using project/folder/organization number (such as + * "folders/12345")", or a project ID (such as "projects/my-project-id"). + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.asset.v1.ListFeedsResponse|ListFeedsResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/asset_service.list_feeds.js + * region_tag:cloudasset_v1_generated_AssetService_ListFeeds_async + */ listFeeds( - request?: protos.google.cloud.asset.v1.IListFeedsRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.asset.v1.IListFeedsResponse, - protos.google.cloud.asset.v1.IListFeedsRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.asset.v1.IListFeedsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.asset.v1.IListFeedsResponse, + protos.google.cloud.asset.v1.IListFeedsRequest | undefined, + {} | undefined, + ] + >; listFeeds( - request: protos.google.cloud.asset.v1.IListFeedsRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.asset.v1.IListFeedsResponse, - protos.google.cloud.asset.v1.IListFeedsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.asset.v1.IListFeedsRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.asset.v1.IListFeedsResponse, + protos.google.cloud.asset.v1.IListFeedsRequest | null | undefined, + {} | null | undefined + >, + ): void; listFeeds( - request: protos.google.cloud.asset.v1.IListFeedsRequest, - callback: Callback< - protos.google.cloud.asset.v1.IListFeedsResponse, - protos.google.cloud.asset.v1.IListFeedsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.asset.v1.IListFeedsRequest, + callback: Callback< + protos.google.cloud.asset.v1.IListFeedsResponse, + protos.google.cloud.asset.v1.IListFeedsRequest | null | undefined, + {} | null | undefined + >, + ): void; listFeeds( - request?: protos.google.cloud.asset.v1.IListFeedsRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.cloud.asset.v1.IListFeedsRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.asset.v1.IListFeedsResponse, - protos.google.cloud.asset.v1.IListFeedsRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.cloud.asset.v1.IListFeedsResponse, - protos.google.cloud.asset.v1.IListFeedsRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.asset.v1.IListFeedsResponse, - protos.google.cloud.asset.v1.IListFeedsRequest|undefined, {}|undefined - ]>|void { + protos.google.cloud.asset.v1.IListFeedsRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.asset.v1.IListFeedsResponse, + protos.google.cloud.asset.v1.IListFeedsRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.asset.v1.IListFeedsResponse, + protos.google.cloud.asset.v1.IListFeedsRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('listFeeds request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.asset.v1.IListFeedsResponse, - protos.google.cloud.asset.v1.IListFeedsRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.asset.v1.IListFeedsResponse, + protos.google.cloud.asset.v1.IListFeedsRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('listFeeds response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.listFeeds(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.asset.v1.IListFeedsResponse, - protos.google.cloud.asset.v1.IListFeedsRequest|undefined, {}|undefined - ]) => { - this._log.info('listFeeds response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .listFeeds(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.asset.v1.IListFeedsResponse, + protos.google.cloud.asset.v1.IListFeedsRequest | undefined, + {} | undefined, + ]) => { + this._log.info('listFeeds response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Updates an asset feed configuration. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.cloud.asset.v1.Feed} request.feed - * Required. The new values of feed details. It must match an existing feed and the - * field `name` must be in the format of: - * projects/project_number/feeds/feed_id or - * folders/folder_number/feeds/feed_id or - * organizations/organization_number/feeds/feed_id. - * @param {google.protobuf.FieldMask} request.updateMask - * Required. Only updates the `feed` fields indicated by this mask. - * The field mask must not be empty, and it must not contain fields that - * are immutable or only set by the server. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.asset.v1.Feed|Feed}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1/asset_service.update_feed.js - * region_tag:cloudasset_v1_generated_AssetService_UpdateFeed_async - */ + /** + * Updates an asset feed configuration. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.cloud.asset.v1.Feed} request.feed + * Required. The new values of feed details. It must match an existing feed and the + * field `name` must be in the format of: + * projects/project_number/feeds/feed_id or + * folders/folder_number/feeds/feed_id or + * organizations/organization_number/feeds/feed_id. + * @param {google.protobuf.FieldMask} request.updateMask + * Required. Only updates the `feed` fields indicated by this mask. + * The field mask must not be empty, and it must not contain fields that + * are immutable or only set by the server. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.asset.v1.Feed|Feed}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/asset_service.update_feed.js + * region_tag:cloudasset_v1_generated_AssetService_UpdateFeed_async + */ updateFeed( - request?: protos.google.cloud.asset.v1.IUpdateFeedRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.asset.v1.IFeed, - protos.google.cloud.asset.v1.IUpdateFeedRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.asset.v1.IUpdateFeedRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.asset.v1.IFeed, + protos.google.cloud.asset.v1.IUpdateFeedRequest | undefined, + {} | undefined, + ] + >; updateFeed( - request: protos.google.cloud.asset.v1.IUpdateFeedRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.asset.v1.IFeed, - protos.google.cloud.asset.v1.IUpdateFeedRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.asset.v1.IUpdateFeedRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.asset.v1.IFeed, + protos.google.cloud.asset.v1.IUpdateFeedRequest | null | undefined, + {} | null | undefined + >, + ): void; updateFeed( - request: protos.google.cloud.asset.v1.IUpdateFeedRequest, - callback: Callback< - protos.google.cloud.asset.v1.IFeed, - protos.google.cloud.asset.v1.IUpdateFeedRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.asset.v1.IUpdateFeedRequest, + callback: Callback< + protos.google.cloud.asset.v1.IFeed, + protos.google.cloud.asset.v1.IUpdateFeedRequest | null | undefined, + {} | null | undefined + >, + ): void; updateFeed( - request?: protos.google.cloud.asset.v1.IUpdateFeedRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.cloud.asset.v1.IUpdateFeedRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.asset.v1.IFeed, - protos.google.cloud.asset.v1.IUpdateFeedRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.cloud.asset.v1.IFeed, - protos.google.cloud.asset.v1.IUpdateFeedRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.asset.v1.IFeed, - protos.google.cloud.asset.v1.IUpdateFeedRequest|undefined, {}|undefined - ]>|void { + protos.google.cloud.asset.v1.IUpdateFeedRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.asset.v1.IFeed, + protos.google.cloud.asset.v1.IUpdateFeedRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.asset.v1.IFeed, + protos.google.cloud.asset.v1.IUpdateFeedRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'feed.name': request.feed!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'feed.name': request.feed!.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateFeed request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.asset.v1.IFeed, - protos.google.cloud.asset.v1.IUpdateFeedRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.asset.v1.IFeed, + protos.google.cloud.asset.v1.IUpdateFeedRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateFeed response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.updateFeed(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.asset.v1.IFeed, - protos.google.cloud.asset.v1.IUpdateFeedRequest|undefined, {}|undefined - ]) => { - this._log.info('updateFeed response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateFeed(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.asset.v1.IFeed, + protos.google.cloud.asset.v1.IUpdateFeedRequest | undefined, + {} | undefined, + ]) => { + this._log.info('updateFeed response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Deletes an asset feed. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The name of the feed and it must be in the format of: - * projects/project_number/feeds/feed_id - * folders/folder_number/feeds/feed_id - * organizations/organization_number/feeds/feed_id - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1/asset_service.delete_feed.js - * region_tag:cloudasset_v1_generated_AssetService_DeleteFeed_async - */ + /** + * Deletes an asset feed. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The name of the feed and it must be in the format of: + * projects/project_number/feeds/feed_id + * folders/folder_number/feeds/feed_id + * organizations/organization_number/feeds/feed_id + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/asset_service.delete_feed.js + * region_tag:cloudasset_v1_generated_AssetService_DeleteFeed_async + */ deleteFeed( - request?: protos.google.cloud.asset.v1.IDeleteFeedRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.cloud.asset.v1.IDeleteFeedRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.asset.v1.IDeleteFeedRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.cloud.asset.v1.IDeleteFeedRequest | undefined, + {} | undefined, + ] + >; deleteFeed( - request: protos.google.cloud.asset.v1.IDeleteFeedRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.cloud.asset.v1.IDeleteFeedRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.asset.v1.IDeleteFeedRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.cloud.asset.v1.IDeleteFeedRequest | null | undefined, + {} | null | undefined + >, + ): void; deleteFeed( - request: protos.google.cloud.asset.v1.IDeleteFeedRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.cloud.asset.v1.IDeleteFeedRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.asset.v1.IDeleteFeedRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.cloud.asset.v1.IDeleteFeedRequest | null | undefined, + {} | null | undefined + >, + ): void; deleteFeed( - request?: protos.google.cloud.asset.v1.IDeleteFeedRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.cloud.asset.v1.IDeleteFeedRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.cloud.asset.v1.IDeleteFeedRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.protobuf.IEmpty, - protos.google.cloud.asset.v1.IDeleteFeedRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.cloud.asset.v1.IDeleteFeedRequest|undefined, {}|undefined - ]>|void { + protos.google.cloud.asset.v1.IDeleteFeedRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + protos.google.cloud.asset.v1.IDeleteFeedRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.cloud.asset.v1.IDeleteFeedRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('deleteFeed request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.cloud.asset.v1.IDeleteFeedRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + protos.google.cloud.asset.v1.IDeleteFeedRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteFeed response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.deleteFeed(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.cloud.asset.v1.IDeleteFeedRequest|undefined, {}|undefined - ]) => { - this._log.info('deleteFeed response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteFeed(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.cloud.asset.v1.IDeleteFeedRequest | undefined, + {} | undefined, + ]) => { + this._log.info('deleteFeed response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Exports assets with time and resource types to a given Cloud Storage - * location. The output format is newline-delimited JSON. - * This API implements the {@link protos.google.longrunning.Operation|google.longrunning.Operation} API allowing you - * to keep track of the export. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The relative name of the root asset. This can only be an - * organization number (such as "organizations/123"), a project ID (such as - * "projects/my-project-id"), or a project number (such as "projects/12345"), - * or a folder number (such as "folders/123"). - * @param {google.protobuf.Timestamp} request.readTime - * Timestamp to take an asset snapshot. This can only be set to a timestamp - * between the current time and the current time minus 35 days (inclusive). - * If not specified, the current time will be used. Due to delays in resource - * data collection and indexing, there is a volatile window during which - * running the same query may get different results. - * @param {string[]} request.assetTypes - * A list of asset types of which to take a snapshot for. For example: - * "compute.googleapis.com/Disk". If specified, only matching assets will be - * returned. See [Introduction to Cloud Asset - * Inventory](https://cloud.google.com/asset-inventory/docs/overview) - * for all supported asset types. - * @param {google.cloud.asset.v1.ContentType} request.contentType - * Asset content type. If not specified, no content but the asset name will be - * returned. - * @param {google.cloud.asset.v1.OutputConfig} request.outputConfig - * Required. Output configuration indicating where the results will be output - * to. All results will be in newline delimited JSON format. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing - * a long running operation. Its `promise()` method returns a promise - * you can `await` for. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v1/asset_service.export_assets.js - * region_tag:cloudasset_v1_generated_AssetService_ExportAssets_async - */ + /** + * Exports assets with time and resource types to a given Cloud Storage + * location. The output format is newline-delimited JSON. + * This API implements the {@link protos.google.longrunning.Operation|google.longrunning.Operation} API allowing you + * to keep track of the export. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The relative name of the root asset. This can only be an + * organization number (such as "organizations/123"), a project ID (such as + * "projects/my-project-id"), or a project number (such as "projects/12345"), + * or a folder number (such as "folders/123"). + * @param {google.protobuf.Timestamp} request.readTime + * Timestamp to take an asset snapshot. This can only be set to a timestamp + * between the current time and the current time minus 35 days (inclusive). + * If not specified, the current time will be used. Due to delays in resource + * data collection and indexing, there is a volatile window during which + * running the same query may get different results. + * @param {string[]} request.assetTypes + * A list of asset types of which to take a snapshot for. For example: + * "compute.googleapis.com/Disk". If specified, only matching assets will be + * returned. See [Introduction to Cloud Asset + * Inventory](https://cloud.google.com/asset-inventory/docs/overview) + * for all supported asset types. + * @param {google.cloud.asset.v1.ContentType} request.contentType + * Asset content type. If not specified, no content but the asset name will be + * returned. + * @param {google.cloud.asset.v1.OutputConfig} request.outputConfig + * Required. Output configuration indicating where the results will be output + * to. All results will be in newline delimited JSON format. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v1/asset_service.export_assets.js + * region_tag:cloudasset_v1_generated_AssetService_ExportAssets_async + */ exportAssets( - request?: protos.google.cloud.asset.v1.IExportAssetsRequest, - options?: CallOptions): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>; + request?: protos.google.cloud.asset.v1.IExportAssetsRequest, + options?: CallOptions, + ): Promise< + [ + LROperation< + protos.google.cloud.asset.v1.IExportAssetsResponse, + protos.google.cloud.asset.v1.IExportAssetsRequest + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; exportAssets( - request: protos.google.cloud.asset.v1.IExportAssetsRequest, - options: CallOptions, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.asset.v1.IExportAssetsRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.cloud.asset.v1.IExportAssetsResponse, + protos.google.cloud.asset.v1.IExportAssetsRequest + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; exportAssets( - request: protos.google.cloud.asset.v1.IExportAssetsRequest, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.asset.v1.IExportAssetsRequest, + callback: Callback< + LROperation< + protos.google.cloud.asset.v1.IExportAssetsResponse, + protos.google.cloud.asset.v1.IExportAssetsRequest + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; exportAssets( - request?: protos.google.cloud.asset.v1.IExportAssetsRequest, - optionsOrCallback?: CallOptions|Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>, - callback?: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>|void { + request?: protos.google.cloud.asset.v1.IExportAssetsRequest, + optionsOrCallback?: + | CallOptions + | Callback< + LROperation< + protos.google.cloud.asset.v1.IExportAssetsResponse, + protos.google.cloud.asset.v1.IExportAssetsRequest + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + callback?: Callback< + LROperation< + protos.google.cloud.asset.v1.IExportAssetsResponse, + protos.google.cloud.asset.v1.IExportAssetsRequest + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + LROperation< + protos.google.cloud.asset.v1.IExportAssetsResponse, + protos.google.cloud.asset.v1.IExportAssetsRequest + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + LROperation< + protos.google.cloud.asset.v1.IExportAssetsResponse, + protos.google.cloud.asset.v1.IExportAssetsRequest + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, rawResponse, _) => { this._log.info('exportAssets response %j', rawResponse); callback!(error, response, rawResponse, _); // We verified `callback` above. } : undefined; this._log.info('exportAssets request %j', request); - return this.innerApiCalls.exportAssets(request, options, wrappedCallback) - ?.then(([response, rawResponse, _]: [ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]) => { - this._log.info('exportAssets response %j', rawResponse); - return [response, rawResponse, _]; - }); + return this.innerApiCalls + .exportAssets(request, options, wrappedCallback) + ?.then( + ([response, rawResponse, _]: [ + LROperation< + protos.google.cloud.asset.v1.IExportAssetsResponse, + protos.google.cloud.asset.v1.IExportAssetsRequest + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ]) => { + this._log.info('exportAssets response %j', rawResponse); + return [response, rawResponse, _]; + }, + ); } -/** - * Check the status of the long running operation returned by `exportAssets()`. - * @param {String} name - * The operation name that will be passed. - * @returns {Promise} - The promise which resolves to an object. - * The decoded operation object has result and metadata field to get information from. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v1/asset_service.export_assets.js - * region_tag:cloudasset_v1_generated_AssetService_ExportAssets_async - */ - async checkExportAssetsProgress(name: string): Promise>{ + /** + * Check the status of the long running operation returned by `exportAssets()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v1/asset_service.export_assets.js + * region_tag:cloudasset_v1_generated_AssetService_ExportAssets_async + */ + async checkExportAssetsProgress( + name: string, + ): Promise< + LROperation< + protos.google.cloud.asset.v1.ExportAssetsResponse, + protos.google.cloud.asset.v1.ExportAssetsRequest + > + > { this._log.info('exportAssets long-running'); - const request = new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest({name}); + const request = + new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( + { name }, + ); const [operation] = await this.operationsClient.getOperation(request); - const decodeOperation = new this._gaxModule.Operation(operation, this.descriptors.longrunning.exportAssets, this._gaxModule.createDefaultBackoffSettings()); - return decodeOperation as LROperation; + const decodeOperation = new this._gaxModule.Operation( + operation, + this.descriptors.longrunning.exportAssets, + this._gaxModule.createDefaultBackoffSettings(), + ); + return decodeOperation as LROperation< + protos.google.cloud.asset.v1.ExportAssetsResponse, + protos.google.cloud.asset.v1.ExportAssetsRequest + >; } // -------------------- // -- Path templates -- @@ -1136,7 +1454,7 @@ export class AssetServiceClient { * @param {string} feed * @returns {string} Resource name string. */ - folderFeedPath(folder:string,feed:string) { + folderFeedPath(folder: string, feed: string) { return this.pathTemplates.folderFeedPathTemplate.render({ folder: folder, feed: feed, @@ -1151,7 +1469,8 @@ export class AssetServiceClient { * @returns {string} A string representing the folder. */ matchFolderFromFolderFeedName(folderFeedName: string) { - return this.pathTemplates.folderFeedPathTemplate.match(folderFeedName).folder; + return this.pathTemplates.folderFeedPathTemplate.match(folderFeedName) + .folder; } /** @@ -1172,7 +1491,7 @@ export class AssetServiceClient { * @param {string} feed * @returns {string} Resource name string. */ - organizationFeedPath(organization:string,feed:string) { + organizationFeedPath(organization: string, feed: string) { return this.pathTemplates.organizationFeedPathTemplate.render({ organization: organization, feed: feed, @@ -1187,7 +1506,9 @@ export class AssetServiceClient { * @returns {string} A string representing the organization. */ matchOrganizationFromOrganizationFeedName(organizationFeedName: string) { - return this.pathTemplates.organizationFeedPathTemplate.match(organizationFeedName).organization; + return this.pathTemplates.organizationFeedPathTemplate.match( + organizationFeedName, + ).organization; } /** @@ -1198,7 +1519,9 @@ export class AssetServiceClient { * @returns {string} A string representing the feed. */ matchFeedFromOrganizationFeedName(organizationFeedName: string) { - return this.pathTemplates.organizationFeedPathTemplate.match(organizationFeedName).feed; + return this.pathTemplates.organizationFeedPathTemplate.match( + organizationFeedName, + ).feed; } /** @@ -1208,7 +1531,7 @@ export class AssetServiceClient { * @param {string} feed * @returns {string} Resource name string. */ - projectFeedPath(project:string,feed:string) { + projectFeedPath(project: string, feed: string) { return this.pathTemplates.projectFeedPathTemplate.render({ project: project, feed: feed, @@ -1223,7 +1546,8 @@ export class AssetServiceClient { * @returns {string} A string representing the project. */ matchProjectFromProjectFeedName(projectFeedName: string) { - return this.pathTemplates.projectFeedPathTemplate.match(projectFeedName).project; + return this.pathTemplates.projectFeedPathTemplate.match(projectFeedName) + .project; } /** @@ -1234,7 +1558,8 @@ export class AssetServiceClient { * @returns {string} A string representing the feed. */ matchFeedFromProjectFeedName(projectFeedName: string) { - return this.pathTemplates.projectFeedPathTemplate.match(projectFeedName).feed; + return this.pathTemplates.projectFeedPathTemplate.match(projectFeedName) + .feed; } /** @@ -1245,7 +1570,7 @@ export class AssetServiceClient { */ close(): Promise { if (this.assetServiceStub && !this._terminated) { - return this.assetServiceStub.then(stub => { + return this.assetServiceStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -1254,4 +1579,4 @@ export class AssetServiceClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/core/generator/gapic-generator-typescript/baselines/asset-esm/esm/src/v1/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/asset-esm/esm/src/v1/index.ts.baseline index 05391a84280a..fa71f389919a 100644 --- a/core/generator/gapic-generator-typescript/baselines/asset-esm/esm/src/v1/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/asset-esm/esm/src/v1/index.ts.baseline @@ -16,4 +16,4 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -export {AssetServiceClient} from './asset_service_client.js'; +export { AssetServiceClient } from './asset_service_client.js'; diff --git a/core/generator/gapic-generator-typescript/baselines/asset-esm/esm/system-test/fixtures/sample/src/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/asset-esm/esm/system-test/fixtures/sample/src/index.ts.baseline index 40aa52c8666e..f93f7caf8b50 100644 --- a/core/generator/gapic-generator-typescript/baselines/asset-esm/esm/system-test/fixtures/sample/src/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/asset-esm/esm/system-test/fixtures/sample/src/index.ts.baseline @@ -17,7 +17,7 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -import {AssetServiceClient} from '@google-cloud/asset'; +import { AssetServiceClient } from '@google-cloud/asset'; // check that the client class type name can be used function doStuffWithAssetServiceClient(client: AssetServiceClient) { diff --git a/core/generator/gapic-generator-typescript/baselines/asset-esm/esm/system-test/install.ts.baseline b/core/generator/gapic-generator-typescript/baselines/asset-esm/esm/system-test/install.ts.baseline index e079c4fa1101..d109fdd8c97f 100644 --- a/core/generator/gapic-generator-typescript/baselines/asset-esm/esm/system-test/install.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/asset-esm/esm/system-test/install.ts.baseline @@ -16,40 +16,45 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -import {packNTest} from 'pack-n-play'; -import {readFileSync} from 'fs'; -import {describe, it} from 'mocha'; +import { packNTest } from 'pack-n-play'; +import { readFileSync } from 'fs'; +import { describe, it } from 'mocha'; describe('📦 pack-n-play test', () => { - it('TypeScript', async function() { + it('TypeScript', async function () { this.timeout(300000); await packNTest({ packageDir: process.cwd(), sample: { description: 'TypeScript user can use the type definitions', - ts: readFileSync('./esm/system-test/fixtures/sample/src/index.ts').toString() - } + ts: readFileSync( + './esm/system-test/fixtures/sample/src/index.ts', + ).toString(), + }, }); }); - it('ESM module', async function() { + it('ESM module', async function () { this.timeout(300000); await packNTest({ sample: { description: 'Should be able to import using ESM', - esm: readFileSync('./esm/system-test/fixtures/sample/src/index.js').toString(), + esm: readFileSync( + './esm/system-test/fixtures/sample/src/index.js', + ).toString(), }, }); }); - it('CJS module', async function() { + it('CJS module', async function () { this.timeout(300000); await packNTest({ sample: { description: 'Should be able to import using CJS', - cjs: readFileSync('./esm/system-test/fixtures/sample/src/index.cjs').toString(), + cjs: readFileSync( + './esm/system-test/fixtures/sample/src/index.cjs', + ).toString(), }, }); }); - }); diff --git a/core/generator/gapic-generator-typescript/baselines/asset-esm/esm/test/gapic_asset_service_v1.ts.baseline b/core/generator/gapic-generator-typescript/baselines/asset-esm/esm/test/gapic_asset_service_v1.ts.baseline index 685a59b84d45..ff1485921067 100644 --- a/core/generator/gapic-generator-typescript/baselines/asset-esm/esm/test/gapic_asset_service_v1.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/asset-esm/esm/test/gapic_asset_service_v1.ts.baseline @@ -20,14 +20,14 @@ import * as protos from '../../protos/protos.js'; import assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as assetserviceModule from '../src/index.js'; -import {protobuf, LROperation, operationsProtos} from 'google-gax'; +import { protobuf, LROperation, operationsProtos } from 'google-gax'; import fs from 'fs'; import path from 'path'; -import {fileURLToPath} from 'url'; +import { fileURLToPath } from 'url'; // @ts-ignore const dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -35,1128 +35,1414 @@ const dirname = path.dirname(fileURLToPath(import.meta.url)); // to fill in default values for request objects const root = protobuf.Root.fromJSON( JSON.parse( - fs.readFileSync(path.join(dirname, '..', '..', 'protos/protos.json'), 'utf8') - )) + fs.readFileSync( + path.join(dirname, '..', '..', 'protos/protos.json'), + 'utf8', + ), + ), +); // eslint-disable-next-line @typescript-eslint/no-unused-vars function getTypeDefaultValue(typeName: string, fields: string[]) { - let type = root.lookupType(typeName) as protobuf.Type; - for (const field of fields.slice(0, -1)) { - type = type?.fields[field]?.resolvedType as protobuf.Type; - } - return type?.fields[fields[fields.length - 1]]?.defaultValue ?? null; + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type?.fields[field]?.resolvedType as protobuf.Type; + } + return type?.fields[fields[fields.length - 1]]?.defaultValue ?? null; } function generateSampleMessage(instance: T) { - const filledObject = (instance.constructor as typeof protobuf.Message) - .toObject(instance as protobuf.Message, {defaults: true}); - return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, { defaults: true }); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; } function stubSimpleCall(response?: ResponseType, error?: Error) { - return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); } -function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { - return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +function stubSimpleCallWithCallback( + response?: ResponseType, + error?: Error, +) { + return error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); } -function stubLongRunningCall(response?: ResponseType, callError?: Error, lroError?: Error) { - const innerStub = lroError ? sinon.stub().rejects(lroError) : sinon.stub().resolves([response]); - const mockOperation = { - promise: innerStub, - }; - return callError ? sinon.stub().rejects(callError) : sinon.stub().resolves([mockOperation]); +function stubLongRunningCall( + response?: ResponseType, + callError?: Error, + lroError?: Error, +) { + const innerStub = lroError + ? sinon.stub().rejects(lroError) + : sinon.stub().resolves([response]); + const mockOperation = { + promise: innerStub, + }; + return callError + ? sinon.stub().rejects(callError) + : sinon.stub().resolves([mockOperation]); } -function stubLongRunningCallWithCallback(response?: ResponseType, callError?: Error, lroError?: Error) { - const innerStub = lroError ? sinon.stub().rejects(lroError) : sinon.stub().resolves([response]); - const mockOperation = { - promise: innerStub, - }; - return callError ? sinon.stub().callsArgWith(2, callError) : sinon.stub().callsArgWith(2, null, mockOperation); +function stubLongRunningCallWithCallback( + response?: ResponseType, + callError?: Error, + lroError?: Error, +) { + const innerStub = lroError + ? sinon.stub().rejects(lroError) + : sinon.stub().resolves([response]); + const mockOperation = { + promise: innerStub, + }; + return callError + ? sinon.stub().callsArgWith(2, callError) + : sinon.stub().callsArgWith(2, null, mockOperation); } describe('v1.AssetServiceClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new assetserviceModule.v1.AssetServiceClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'cloudasset.googleapis.com'); - }); - - it('has universeDomain', () => { - const client = new assetserviceModule.v1.AssetServiceClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); - - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - it('throws DeprecationWarning if static servicePath is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const servicePath = assetserviceModule.v1.AssetServiceClient.servicePath; - assert.strictEqual(servicePath, 'cloudasset.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = assetserviceModule.v1.AssetServiceClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'cloudasset.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new assetserviceModule.v1.AssetServiceClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'cloudasset.example.com'); - }); - - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new assetserviceModule.v1.AssetServiceClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'cloudasset.example.com'); - }); - - if (typeof process === 'object' && 'env' in process) { - describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { - it('sets apiEndpoint from environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new assetserviceModule.v1.AssetServiceClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'cloudasset.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - - it('value configured in code has priority over environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new assetserviceModule.v1.AssetServiceClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'cloudasset.configured.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { new assetserviceModule.v1.AssetServiceClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); - - it('has port', () => { - const port = assetserviceModule.v1.AssetServiceClient.port; - assert(port); - assert(typeof port === 'number'); - }); - - it('should create a client with no option', () => { - const client = new assetserviceModule.v1.AssetServiceClient(); - assert(client); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new assetserviceModule.v1.AssetServiceClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'cloudasset.googleapis.com'); + }); - it('should create a client with gRPC fallback', () => { - const client = new assetserviceModule.v1.AssetServiceClient({ - fallback: true, - }); - assert(client); - }); + it('has universeDomain', () => { + const client = new assetserviceModule.v1.AssetServiceClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - it('has initialize method and supports deferred initialization', async () => { - const client = new assetserviceModule.v1.AssetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.assetServiceStub, undefined); - await client.initialize(); - assert(client.assetServiceStub); - }); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = + assetserviceModule.v1.AssetServiceClient.servicePath; + assert.strictEqual(servicePath, 'cloudasset.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + assetserviceModule.v1.AssetServiceClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'cloudasset.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = new assetserviceModule.v1.AssetServiceClient({ + universeDomain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'cloudasset.example.com'); + }); - it('has close method for the initialized client', done => { - const client = new assetserviceModule.v1.AssetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.assetServiceStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = new assetserviceModule.v1.AssetServiceClient({ + universe_domain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'cloudasset.example.com'); + }); - it('has close method for the non-initialized client', done => { - const client = new assetserviceModule.v1.AssetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.assetServiceStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); + if (typeof process === 'object' && 'env' in process) { + describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { + it('sets apiEndpoint from environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new assetserviceModule.v1.AssetServiceClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'cloudasset.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new assetserviceModule.v1.AssetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + it('value configured in code has priority over environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new assetserviceModule.v1.AssetServiceClient({ + universeDomain: 'configured.example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'cloudasset.configured.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new assetserviceModule.v1.AssetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId((err?: Error|null, projectId?: string|null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } - }); - }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new assetserviceModule.v1.AssetServiceClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); }); - describe('batchGetAssetsHistory', () => { - it('invokes batchGetAssetsHistory without error', async () => { - const client = new assetserviceModule.v1.AssetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.asset.v1.BatchGetAssetsHistoryRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.asset.v1.BatchGetAssetsHistoryRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.asset.v1.BatchGetAssetsHistoryResponse() - ); - client.innerApiCalls.batchGetAssetsHistory = stubSimpleCall(expectedResponse); - const [response] = await client.batchGetAssetsHistory(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.batchGetAssetsHistory as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.batchGetAssetsHistory as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has port', () => { + const port = assetserviceModule.v1.AssetServiceClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('invokes batchGetAssetsHistory without error using callback', async () => { - const client = new assetserviceModule.v1.AssetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.asset.v1.BatchGetAssetsHistoryRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.asset.v1.BatchGetAssetsHistoryRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.asset.v1.BatchGetAssetsHistoryResponse() - ); - client.innerApiCalls.batchGetAssetsHistory = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.batchGetAssetsHistory( - request, - (err?: Error|null, result?: protos.google.cloud.asset.v1.IBatchGetAssetsHistoryResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.batchGetAssetsHistory as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.batchGetAssetsHistory as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('should create a client with no option', () => { + const client = new assetserviceModule.v1.AssetServiceClient(); + assert(client); + }); - it('invokes batchGetAssetsHistory with error', async () => { - const client = new assetserviceModule.v1.AssetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.asset.v1.BatchGetAssetsHistoryRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.asset.v1.BatchGetAssetsHistoryRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.batchGetAssetsHistory = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.batchGetAssetsHistory(request), expectedError); - const actualRequest = (client.innerApiCalls.batchGetAssetsHistory as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.batchGetAssetsHistory as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('should create a client with gRPC fallback', () => { + const client = new assetserviceModule.v1.AssetServiceClient({ + fallback: true, + }); + assert(client); + }); - it('invokes batchGetAssetsHistory with closed client', async () => { - const client = new assetserviceModule.v1.AssetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.asset.v1.BatchGetAssetsHistoryRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.asset.v1.BatchGetAssetsHistoryRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.batchGetAssetsHistory(request), expectedError); - }); + it('has initialize method and supports deferred initialization', async () => { + const client = new assetserviceModule.v1.AssetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.assetServiceStub, undefined); + await client.initialize(); + assert(client.assetServiceStub); }); - describe('createFeed', () => { - it('invokes createFeed without error', async () => { - const client = new assetserviceModule.v1.AssetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.asset.v1.CreateFeedRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.asset.v1.CreateFeedRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.asset.v1.Feed() - ); - client.innerApiCalls.createFeed = stubSimpleCall(expectedResponse); - const [response] = await client.createFeed(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createFeed as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createFeed as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('has close method for the initialized client', (done) => { + const client = new assetserviceModule.v1.AssetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.assetServiceStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes createFeed without error using callback', async () => { - const client = new assetserviceModule.v1.AssetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.asset.v1.CreateFeedRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.asset.v1.CreateFeedRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.asset.v1.Feed() - ); - client.innerApiCalls.createFeed = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createFeed( - request, - (err?: Error|null, result?: protos.google.cloud.asset.v1.IFeed|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createFeed as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createFeed as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('has close method for the non-initialized client', (done) => { + const client = new assetserviceModule.v1.AssetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.assetServiceStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes createFeed with error', async () => { - const client = new assetserviceModule.v1.AssetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.asset.v1.CreateFeedRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.asset.v1.CreateFeedRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createFeed = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createFeed(request), expectedError); - const actualRequest = (client.innerApiCalls.createFeed as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createFeed as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new assetserviceModule.v1.AssetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + }); - it('invokes createFeed with closed client', async () => { - const client = new assetserviceModule.v1.AssetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.asset.v1.CreateFeedRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.asset.v1.CreateFeedRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createFeed(request), expectedError); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new assetserviceModule.v1.AssetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + }); + + describe('batchGetAssetsHistory', () => { + it('invokes batchGetAssetsHistory without error', async () => { + const client = new assetserviceModule.v1.AssetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.asset.v1.BatchGetAssetsHistoryRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.asset.v1.BatchGetAssetsHistoryRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.asset.v1.BatchGetAssetsHistoryResponse(), + ); + client.innerApiCalls.batchGetAssetsHistory = + stubSimpleCall(expectedResponse); + const [response] = await client.batchGetAssetsHistory(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.batchGetAssetsHistory as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.batchGetAssetsHistory as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('getFeed', () => { - it('invokes getFeed without error', async () => { - const client = new assetserviceModule.v1.AssetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.asset.v1.GetFeedRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.asset.v1.GetFeedRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.asset.v1.Feed() - ); - client.innerApiCalls.getFeed = stubSimpleCall(expectedResponse); - const [response] = await client.getFeed(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getFeed as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getFeed as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes batchGetAssetsHistory without error using callback', async () => { + const client = new assetserviceModule.v1.AssetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.asset.v1.BatchGetAssetsHistoryRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.asset.v1.BatchGetAssetsHistoryRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.asset.v1.BatchGetAssetsHistoryResponse(), + ); + client.innerApiCalls.batchGetAssetsHistory = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.batchGetAssetsHistory( + request, + ( + err?: Error | null, + result?: protos.google.cloud.asset.v1.IBatchGetAssetsHistoryResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.batchGetAssetsHistory as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.batchGetAssetsHistory as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getFeed without error using callback', async () => { - const client = new assetserviceModule.v1.AssetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.asset.v1.GetFeedRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.asset.v1.GetFeedRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.asset.v1.Feed() - ); - client.innerApiCalls.getFeed = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getFeed( - request, - (err?: Error|null, result?: protos.google.cloud.asset.v1.IFeed|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getFeed as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getFeed as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes batchGetAssetsHistory with error', async () => { + const client = new assetserviceModule.v1.AssetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.asset.v1.BatchGetAssetsHistoryRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.asset.v1.BatchGetAssetsHistoryRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.batchGetAssetsHistory = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.batchGetAssetsHistory(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.batchGetAssetsHistory as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.batchGetAssetsHistory as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getFeed with error', async () => { - const client = new assetserviceModule.v1.AssetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.asset.v1.GetFeedRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.asset.v1.GetFeedRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getFeed = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getFeed(request), expectedError); - const actualRequest = (client.innerApiCalls.getFeed as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getFeed as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes batchGetAssetsHistory with closed client', async () => { + const client = new assetserviceModule.v1.AssetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.asset.v1.BatchGetAssetsHistoryRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.asset.v1.BatchGetAssetsHistoryRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.batchGetAssetsHistory(request), + expectedError, + ); + }); + }); + + describe('createFeed', () => { + it('invokes createFeed without error', async () => { + const client = new assetserviceModule.v1.AssetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.asset.v1.CreateFeedRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.asset.v1.CreateFeedRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.asset.v1.Feed(), + ); + client.innerApiCalls.createFeed = stubSimpleCall(expectedResponse); + const [response] = await client.createFeed(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createFeed as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createFeed as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getFeed with closed client', async () => { - const client = new assetserviceModule.v1.AssetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.asset.v1.GetFeedRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.asset.v1.GetFeedRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getFeed(request), expectedError); - }); + it('invokes createFeed without error using callback', async () => { + const client = new assetserviceModule.v1.AssetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.asset.v1.CreateFeedRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.asset.v1.CreateFeedRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.asset.v1.Feed(), + ); + client.innerApiCalls.createFeed = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createFeed( + request, + ( + err?: Error | null, + result?: protos.google.cloud.asset.v1.IFeed | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createFeed as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createFeed as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('listFeeds', () => { - it('invokes listFeeds without error', async () => { - const client = new assetserviceModule.v1.AssetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.asset.v1.ListFeedsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.asset.v1.ListFeedsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.asset.v1.ListFeedsResponse() - ); - client.innerApiCalls.listFeeds = stubSimpleCall(expectedResponse); - const [response] = await client.listFeeds(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listFeeds as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listFeeds as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createFeed with error', async () => { + const client = new assetserviceModule.v1.AssetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.asset.v1.CreateFeedRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.asset.v1.CreateFeedRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createFeed = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.createFeed(request), expectedError); + const actualRequest = ( + client.innerApiCalls.createFeed as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createFeed as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listFeeds without error using callback', async () => { - const client = new assetserviceModule.v1.AssetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.asset.v1.ListFeedsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.asset.v1.ListFeedsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.asset.v1.ListFeedsResponse() - ); - client.innerApiCalls.listFeeds = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listFeeds( - request, - (err?: Error|null, result?: protos.google.cloud.asset.v1.IListFeedsResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listFeeds as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listFeeds as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createFeed with closed client', async () => { + const client = new assetserviceModule.v1.AssetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.asset.v1.CreateFeedRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.asset.v1.CreateFeedRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.createFeed(request), expectedError); + }); + }); + + describe('getFeed', () => { + it('invokes getFeed without error', async () => { + const client = new assetserviceModule.v1.AssetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.asset.v1.GetFeedRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.asset.v1.GetFeedRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.asset.v1.Feed(), + ); + client.innerApiCalls.getFeed = stubSimpleCall(expectedResponse); + const [response] = await client.getFeed(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.getFeed as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getFeed as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listFeeds with error', async () => { - const client = new assetserviceModule.v1.AssetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.asset.v1.ListFeedsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.asset.v1.ListFeedsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listFeeds = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listFeeds(request), expectedError); - const actualRequest = (client.innerApiCalls.listFeeds as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listFeeds as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getFeed without error using callback', async () => { + const client = new assetserviceModule.v1.AssetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.asset.v1.GetFeedRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.asset.v1.GetFeedRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.asset.v1.Feed(), + ); + client.innerApiCalls.getFeed = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getFeed( + request, + ( + err?: Error | null, + result?: protos.google.cloud.asset.v1.IFeed | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.getFeed as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getFeed as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listFeeds with closed client', async () => { - const client = new assetserviceModule.v1.AssetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.asset.v1.ListFeedsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.asset.v1.ListFeedsRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.listFeeds(request), expectedError); - }); + it('invokes getFeed with error', async () => { + const client = new assetserviceModule.v1.AssetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.asset.v1.GetFeedRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.asset.v1.GetFeedRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getFeed = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.getFeed(request), expectedError); + const actualRequest = (client.innerApiCalls.getFeed as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getFeed as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('updateFeed', () => { - it('invokes updateFeed without error', async () => { - const client = new assetserviceModule.v1.AssetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.asset.v1.UpdateFeedRequest() - ); - request.feed ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.asset.v1.UpdateFeedRequest', ['feed', 'name']); - request.feed.name = defaultValue1; - const expectedHeaderRequestParams = `feed.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.asset.v1.Feed() - ); - client.innerApiCalls.updateFeed = stubSimpleCall(expectedResponse); - const [response] = await client.updateFeed(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateFeed as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateFeed as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getFeed with closed client', async () => { + const client = new assetserviceModule.v1.AssetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.asset.v1.GetFeedRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.asset.v1.GetFeedRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getFeed(request), expectedError); + }); + }); + + describe('listFeeds', () => { + it('invokes listFeeds without error', async () => { + const client = new assetserviceModule.v1.AssetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.asset.v1.ListFeedsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.asset.v1.ListFeedsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.asset.v1.ListFeedsResponse(), + ); + client.innerApiCalls.listFeeds = stubSimpleCall(expectedResponse); + const [response] = await client.listFeeds(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listFeeds as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listFeeds as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateFeed without error using callback', async () => { - const client = new assetserviceModule.v1.AssetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.asset.v1.UpdateFeedRequest() - ); - request.feed ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.asset.v1.UpdateFeedRequest', ['feed', 'name']); - request.feed.name = defaultValue1; - const expectedHeaderRequestParams = `feed.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.asset.v1.Feed() - ); - client.innerApiCalls.updateFeed = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateFeed( - request, - (err?: Error|null, result?: protos.google.cloud.asset.v1.IFeed|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateFeed as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateFeed as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listFeeds without error using callback', async () => { + const client = new assetserviceModule.v1.AssetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.asset.v1.ListFeedsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.asset.v1.ListFeedsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.asset.v1.ListFeedsResponse(), + ); + client.innerApiCalls.listFeeds = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listFeeds( + request, + ( + err?: Error | null, + result?: protos.google.cloud.asset.v1.IListFeedsResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listFeeds as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listFeeds as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateFeed with error', async () => { - const client = new assetserviceModule.v1.AssetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.asset.v1.UpdateFeedRequest() - ); - request.feed ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.asset.v1.UpdateFeedRequest', ['feed', 'name']); - request.feed.name = defaultValue1; - const expectedHeaderRequestParams = `feed.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateFeed = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateFeed(request), expectedError); - const actualRequest = (client.innerApiCalls.updateFeed as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateFeed as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listFeeds with error', async () => { + const client = new assetserviceModule.v1.AssetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.asset.v1.ListFeedsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.asset.v1.ListFeedsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listFeeds = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.listFeeds(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listFeeds as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listFeeds as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateFeed with closed client', async () => { - const client = new assetserviceModule.v1.AssetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.asset.v1.UpdateFeedRequest() - ); - request.feed ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.asset.v1.UpdateFeedRequest', ['feed', 'name']); - request.feed.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateFeed(request), expectedError); - }); + it('invokes listFeeds with closed client', async () => { + const client = new assetserviceModule.v1.AssetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.asset.v1.ListFeedsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.asset.v1.ListFeedsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.listFeeds(request), expectedError); + }); + }); + + describe('updateFeed', () => { + it('invokes updateFeed without error', async () => { + const client = new assetserviceModule.v1.AssetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.asset.v1.UpdateFeedRequest(), + ); + request.feed ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.asset.v1.UpdateFeedRequest', + ['feed', 'name'], + ); + request.feed.name = defaultValue1; + const expectedHeaderRequestParams = `feed.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.asset.v1.Feed(), + ); + client.innerApiCalls.updateFeed = stubSimpleCall(expectedResponse); + const [response] = await client.updateFeed(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateFeed as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateFeed as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('deleteFeed', () => { - it('invokes deleteFeed without error', async () => { - const client = new assetserviceModule.v1.AssetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.asset.v1.DeleteFeedRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.asset.v1.DeleteFeedRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteFeed = stubSimpleCall(expectedResponse); - const [response] = await client.deleteFeed(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteFeed as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteFeed as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateFeed without error using callback', async () => { + const client = new assetserviceModule.v1.AssetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.asset.v1.UpdateFeedRequest(), + ); + request.feed ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.asset.v1.UpdateFeedRequest', + ['feed', 'name'], + ); + request.feed.name = defaultValue1; + const expectedHeaderRequestParams = `feed.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.asset.v1.Feed(), + ); + client.innerApiCalls.updateFeed = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateFeed( + request, + ( + err?: Error | null, + result?: protos.google.cloud.asset.v1.IFeed | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateFeed as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateFeed as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteFeed without error using callback', async () => { - const client = new assetserviceModule.v1.AssetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.asset.v1.DeleteFeedRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.asset.v1.DeleteFeedRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteFeed = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteFeed( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteFeed as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteFeed as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateFeed with error', async () => { + const client = new assetserviceModule.v1.AssetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.asset.v1.UpdateFeedRequest(), + ); + request.feed ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.asset.v1.UpdateFeedRequest', + ['feed', 'name'], + ); + request.feed.name = defaultValue1; + const expectedHeaderRequestParams = `feed.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateFeed = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.updateFeed(request), expectedError); + const actualRequest = ( + client.innerApiCalls.updateFeed as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateFeed as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteFeed with error', async () => { - const client = new assetserviceModule.v1.AssetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.asset.v1.DeleteFeedRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.asset.v1.DeleteFeedRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteFeed = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteFeed(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteFeed as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteFeed as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateFeed with closed client', async () => { + const client = new assetserviceModule.v1.AssetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.asset.v1.UpdateFeedRequest(), + ); + request.feed ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.asset.v1.UpdateFeedRequest', + ['feed', 'name'], + ); + request.feed.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.updateFeed(request), expectedError); + }); + }); + + describe('deleteFeed', () => { + it('invokes deleteFeed without error', async () => { + const client = new assetserviceModule.v1.AssetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.asset.v1.DeleteFeedRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.asset.v1.DeleteFeedRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteFeed = stubSimpleCall(expectedResponse); + const [response] = await client.deleteFeed(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteFeed as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteFeed as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteFeed with closed client', async () => { - const client = new assetserviceModule.v1.AssetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.asset.v1.DeleteFeedRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.asset.v1.DeleteFeedRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteFeed(request), expectedError); - }); + it('invokes deleteFeed without error using callback', async () => { + const client = new assetserviceModule.v1.AssetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.asset.v1.DeleteFeedRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.asset.v1.DeleteFeedRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteFeed = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteFeed( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteFeed as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteFeed as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('exportAssets', () => { - it('invokes exportAssets without error', async () => { - const client = new assetserviceModule.v1.AssetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.asset.v1.ExportAssetsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.asset.v1.ExportAssetsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.exportAssets = stubLongRunningCall(expectedResponse); - const [operation] = await client.exportAssets(request); - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.exportAssets as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.exportAssets as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteFeed with error', async () => { + const client = new assetserviceModule.v1.AssetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.asset.v1.DeleteFeedRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.asset.v1.DeleteFeedRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteFeed = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.deleteFeed(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteFeed as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteFeed as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes exportAssets without error using callback', async () => { - const client = new assetserviceModule.v1.AssetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.asset.v1.ExportAssetsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.asset.v1.ExportAssetsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.exportAssets = stubLongRunningCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.exportAssets( - request, - (err?: Error|null, - result?: LROperation|null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const operation = await promise as LROperation; - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.exportAssets as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.exportAssets as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteFeed with closed client', async () => { + const client = new assetserviceModule.v1.AssetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.asset.v1.DeleteFeedRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.asset.v1.DeleteFeedRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.deleteFeed(request), expectedError); + }); + }); + + describe('exportAssets', () => { + it('invokes exportAssets without error', async () => { + const client = new assetserviceModule.v1.AssetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.asset.v1.ExportAssetsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.asset.v1.ExportAssetsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.exportAssets = stubLongRunningCall(expectedResponse); + const [operation] = await client.exportAssets(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.exportAssets as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.exportAssets as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes exportAssets with call error', async () => { - const client = new assetserviceModule.v1.AssetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.asset.v1.ExportAssetsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.asset.v1.ExportAssetsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.exportAssets = stubLongRunningCall(undefined, expectedError); - await assert.rejects(client.exportAssets(request), expectedError); - const actualRequest = (client.innerApiCalls.exportAssets as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.exportAssets as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes exportAssets without error using callback', async () => { + const client = new assetserviceModule.v1.AssetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.asset.v1.ExportAssetsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.asset.v1.ExportAssetsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.exportAssets = + stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.exportAssets( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.cloud.asset.v1.IExportAssetsResponse, + protos.google.cloud.asset.v1.IExportAssetsRequest + > | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const operation = (await promise) as LROperation< + protos.google.cloud.asset.v1.IExportAssetsResponse, + protos.google.cloud.asset.v1.IExportAssetsRequest + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.exportAssets as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.exportAssets as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes exportAssets with LRO error', async () => { - const client = new assetserviceModule.v1.AssetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.asset.v1.ExportAssetsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.asset.v1.ExportAssetsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.exportAssets = stubLongRunningCall(undefined, undefined, expectedError); - const [operation] = await client.exportAssets(request); - await assert.rejects(operation.promise(), expectedError); - const actualRequest = (client.innerApiCalls.exportAssets as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.exportAssets as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes exportAssets with call error', async () => { + const client = new assetserviceModule.v1.AssetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.asset.v1.ExportAssetsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.asset.v1.ExportAssetsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.exportAssets = stubLongRunningCall( + undefined, + expectedError, + ); + await assert.rejects(client.exportAssets(request), expectedError); + const actualRequest = ( + client.innerApiCalls.exportAssets as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.exportAssets as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkExportAssetsProgress without error', async () => { - const client = new assetserviceModule.v1.AssetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedResponse = generateSampleMessage( - new operationsProtos.google.longrunning.Operation() - ); - expectedResponse.name = 'test'; - expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; - expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')} - - client.operationsClient.getOperation = stubSimpleCall(expectedResponse); - const decodedOperation = await client.checkExportAssetsProgress(expectedResponse.name); - assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); - assert(decodedOperation.metadata); - assert((client.operationsClient.getOperation as SinonStub).getCall(0)); - }); + it('invokes exportAssets with LRO error', async () => { + const client = new assetserviceModule.v1.AssetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.asset.v1.ExportAssetsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.asset.v1.ExportAssetsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.exportAssets = stubLongRunningCall( + undefined, + undefined, + expectedError, + ); + const [operation] = await client.exportAssets(request); + await assert.rejects(operation.promise(), expectedError); + const actualRequest = ( + client.innerApiCalls.exportAssets as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.exportAssets as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkExportAssetsProgress with error', async () => { - const client = new assetserviceModule.v1.AssetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedError = new Error('expected'); - - client.operationsClient.getOperation = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.checkExportAssetsProgress(''), expectedError); - assert((client.operationsClient.getOperation as SinonStub) - .getCall(0)); - }); + it('invokes checkExportAssetsProgress without error', async () => { + const client = new assetserviceModule.v1.AssetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation(), + ); + expectedResponse.name = 'test'; + expectedResponse.response = { type_url: 'url', value: Buffer.from('') }; + expectedResponse.metadata = { type_url: 'url', value: Buffer.from('') }; + + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const decodedOperation = await client.checkExportAssetsProgress( + expectedResponse.name, + ); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); }); - describe('Path templates', () => { - - describe('folderFeed', () => { - const fakePath = "/rendered/path/folderFeed"; - const expectedParameters = { - folder: "folderValue", - feed: "feedValue", - }; - const client = new assetserviceModule.v1.AssetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.folderFeedPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderFeedPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderFeedPath', () => { - const result = client.folderFeedPath("folderValue", "feedValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderFeedPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderFeedName', () => { - const result = client.matchFolderFromFolderFeedName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderFeedPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchFeedFromFolderFeedName', () => { - const result = client.matchFeedFromFolderFeedName(fakePath); - assert.strictEqual(result, "feedValue"); - assert((client.pathTemplates.folderFeedPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('invokes checkExportAssetsProgress with error', async () => { + const client = new assetserviceModule.v1.AssetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const expectedError = new Error('expected'); + + client.operationsClient.getOperation = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.checkExportAssetsProgress(''), expectedError); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + }); + + describe('Path templates', () => { + describe('folderFeed', () => { + const fakePath = '/rendered/path/folderFeed'; + const expectedParameters = { + folder: 'folderValue', + feed: 'feedValue', + }; + const client = new assetserviceModule.v1.AssetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.folderFeedPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderFeedPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderFeedPath', () => { + const result = client.folderFeedPath('folderValue', 'feedValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.folderFeedPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderFeedName', () => { + const result = client.matchFolderFromFolderFeedName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + (client.pathTemplates.folderFeedPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchFeedFromFolderFeedName', () => { + const result = client.matchFeedFromFolderFeedName(fakePath); + assert.strictEqual(result, 'feedValue'); + assert( + (client.pathTemplates.folderFeedPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('organizationFeed', () => { - const fakePath = "/rendered/path/organizationFeed"; - const expectedParameters = { - organization: "organizationValue", - feed: "feedValue", - }; - const client = new assetserviceModule.v1.AssetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.organizationFeedPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationFeedPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationFeedPath', () => { - const result = client.organizationFeedPath("organizationValue", "feedValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationFeedPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationFeedName', () => { - const result = client.matchOrganizationFromOrganizationFeedName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationFeedPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchFeedFromOrganizationFeedName', () => { - const result = client.matchFeedFromOrganizationFeedName(fakePath); - assert.strictEqual(result, "feedValue"); - assert((client.pathTemplates.organizationFeedPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('organizationFeed', () => { + const fakePath = '/rendered/path/organizationFeed'; + const expectedParameters = { + organization: 'organizationValue', + feed: 'feedValue', + }; + const client = new assetserviceModule.v1.AssetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.organizationFeedPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.organizationFeedPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('organizationFeedPath', () => { + const result = client.organizationFeedPath( + 'organizationValue', + 'feedValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationFeedPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationFeedName', () => { + const result = + client.matchOrganizationFromOrganizationFeedName(fakePath); + assert.strictEqual(result, 'organizationValue'); + assert( + (client.pathTemplates.organizationFeedPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchFeedFromOrganizationFeedName', () => { + const result = client.matchFeedFromOrganizationFeedName(fakePath); + assert.strictEqual(result, 'feedValue'); + assert( + (client.pathTemplates.organizationFeedPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectFeed', () => { - const fakePath = "/rendered/path/projectFeed"; - const expectedParameters = { - project: "projectValue", - feed: "feedValue", - }; - const client = new assetserviceModule.v1.AssetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.projectFeedPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectFeedPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectFeedPath', () => { - const result = client.projectFeedPath("projectValue", "feedValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectFeedPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectFeedName', () => { - const result = client.matchProjectFromProjectFeedName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectFeedPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchFeedFromProjectFeedName', () => { - const result = client.matchFeedFromProjectFeedName(fakePath); - assert.strictEqual(result, "feedValue"); - assert((client.pathTemplates.projectFeedPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectFeed', () => { + const fakePath = '/rendered/path/projectFeed'; + const expectedParameters = { + project: 'projectValue', + feed: 'feedValue', + }; + const client = new assetserviceModule.v1.AssetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.projectFeedPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectFeedPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectFeedPath', () => { + const result = client.projectFeedPath('projectValue', 'feedValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.projectFeedPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectFeedName', () => { + const result = client.matchProjectFromProjectFeedName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.projectFeedPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchFeedFromProjectFeedName', () => { + const result = client.matchFeedFromProjectFeedName(fakePath); + assert.strictEqual(result, 'feedValue'); + assert( + (client.pathTemplates.projectFeedPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/core/generator/gapic-generator-typescript/baselines/asset/src/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/asset/src/index.ts.baseline index b4c33139479d..415a9769cc8e 100644 --- a/core/generator/gapic-generator-typescript/baselines/asset/src/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/asset/src/index.ts.baseline @@ -19,7 +19,7 @@ import * as v1 from './v1'; const AssetServiceClient = v1.AssetServiceClient; type AssetServiceClient = v1.AssetServiceClient; -export {v1, AssetServiceClient}; -export default {v1, AssetServiceClient}; +export { v1, AssetServiceClient }; +export default { v1, AssetServiceClient }; import * as protos from '../protos/protos'; -export {protos} +export { protos }; diff --git a/core/generator/gapic-generator-typescript/baselines/asset/src/v1/asset_service_client.ts.baseline b/core/generator/gapic-generator-typescript/baselines/asset/src/v1/asset_service_client.ts.baseline index d46166abe2d8..9fba65d2805a 100644 --- a/core/generator/gapic-generator-typescript/baselines/asset/src/v1/asset_service_client.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/asset/src/v1/asset_service_client.ts.baseline @@ -18,11 +18,18 @@ /* global window */ import type * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions, GrpcClientOptions, LROperation} from 'google-gax'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + GrpcClientOptions, + LROperation, +} from 'google-gax'; import * as protos from '../../protos/protos'; import jsonProtos = require('../../protos/protos.json'); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; /** * Client JSON configuration object, loaded from @@ -44,7 +51,7 @@ export class AssetServiceClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('asset'); @@ -57,10 +64,10 @@ export class AssetServiceClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; operationsClient: gax.OperationsClient; - assetServiceStub?: Promise<{[name: string]: Function}>; + assetServiceStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of AssetServiceClient. @@ -101,21 +108,42 @@ export class AssetServiceClient { * const client = new AssetServiceClient({fallback: true}, gax); * ``` */ - constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { // Ensure that options include all the required fields. const staticMembers = this.constructor as typeof AssetServiceClient; - if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { - throw new Error('Please set either universe_domain or universeDomain, but not both.'); + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); } - const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; - this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; this._servicePath = 'cloudasset.' + this._universeDomain; - const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; - const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. if (servicePath !== this._servicePath && !('scopes' in opts)) { @@ -137,7 +165,7 @@ export class AssetServiceClient { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; @@ -151,10 +179,7 @@ export class AssetServiceClient { } // Determine the client header string. - const clientHeader = [ - `gax/${this._gaxModule.version}`, - `gapic/${version}`, - ]; + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/${process.versions.node}`); } else { @@ -176,13 +201,13 @@ export class AssetServiceClient { // Create useful helper objects for these. this.pathTemplates = { folderFeedPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/feeds/{feed}' + 'folders/{folder}/feeds/{feed}', ), organizationFeedPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/feeds/{feed}' + 'organizations/{organization}/feeds/{feed}', ), projectFeedPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/feeds/{feed}' + 'projects/{project}/feeds/{feed}', ), }; @@ -192,29 +217,37 @@ export class AssetServiceClient { // rather than holding a request open. const lroOptions: GrpcClientOptions = { auth: this.auth, - grpc: 'grpc' in this._gaxGrpc ? this._gaxGrpc.grpc : undefined + grpc: 'grpc' in this._gaxGrpc ? this._gaxGrpc.grpc : undefined, }; if (opts.fallback) { lroOptions.protoJson = protoFilesRoot; lroOptions.httpRules = []; } - this.operationsClient = this._gaxModule.lro(lroOptions).operationsClient(opts); + this.operationsClient = this._gaxModule + .lro(lroOptions) + .operationsClient(opts); const exportAssetsResponse = protoFilesRoot.lookup( - '.google.cloud.asset.v1.ExportAssetsResponse') as gax.protobuf.Type; + '.google.cloud.asset.v1.ExportAssetsResponse', + ) as gax.protobuf.Type; const exportAssetsMetadata = protoFilesRoot.lookup( - '.google.cloud.asset.v1.ExportAssetsRequest') as gax.protobuf.Type; + '.google.cloud.asset.v1.ExportAssetsRequest', + ) as gax.protobuf.Type; this.descriptors.longrunning = { exportAssets: new this._gaxModule.LongrunningDescriptor( this.operationsClient, exportAssetsResponse.decode.bind(exportAssetsResponse), - exportAssetsMetadata.decode.bind(exportAssetsMetadata)) + exportAssetsMetadata.decode.bind(exportAssetsMetadata), + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.cloud.asset.v1.AssetService', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.cloud.asset.v1.AssetService', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + { 'x-goog-api-client': clientHeader.join(' ') }, + ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -245,37 +278,48 @@ export class AssetServiceClient { // Put together the "service stub" for // google.cloud.asset.v1.AssetService. this.assetServiceStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.cloud.asset.v1.AssetService') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.cloud.asset.v1.AssetService', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.cloud.asset.v1.AssetService, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts, + this._providedCustomServicePath, + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const assetServiceStubMethods = - ['exportAssets', 'batchGetAssetsHistory', 'createFeed', 'getFeed', 'listFeeds', 'updateFeed', 'deleteFeed']; + const assetServiceStubMethods = [ + 'exportAssets', + 'batchGetAssetsHistory', + 'createFeed', + 'getFeed', + 'listFeeds', + 'updateFeed', + 'deleteFeed', + ]; for (const methodName of assetServiceStubMethods) { const callPromise = this.assetServiceStub.then( - stub => (...args: Array<{}>) => { - if (this._terminated) { - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error|null|undefined) => () => { + (stub) => + (...args: Array<{}>) => { + if (this._terminated) { + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { throw err; - }); + }, + ); - const descriptor = - this.descriptors.longrunning[methodName] || - undefined; + const descriptor = this.descriptors.longrunning[methodName] || undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -290,8 +334,14 @@ export class AssetServiceClient { * @returns {string} The DNS address for this service. */ static get servicePath() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'cloudasset.googleapis.com'; } @@ -302,8 +352,14 @@ export class AssetServiceClient { * @returns {string} The DNS address for this service. */ static get apiEndpoint() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'cloudasset.googleapis.com'; } @@ -334,9 +390,7 @@ export class AssetServiceClient { * @returns {string[]} List of default scopes. */ static get scopes() { - return [ - 'https://www.googleapis.com/auth/cloud-platform' - ]; + return ['https://www.googleapis.com/auth/cloud-platform']; } getProjectId(): Promise; @@ -345,8 +399,9 @@ export class AssetServiceClient { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId(callback?: Callback): - Promise|void { + getProjectId( + callback?: Callback, + ): Promise | void { if (callback) { this.auth.getProjectId(callback); return; @@ -357,759 +412,1014 @@ export class AssetServiceClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Batch gets the update history of assets that overlap a time window. - * For RESOURCE content, this API outputs history with asset in both - * non-delete or deleted status. - * For IAM_POLICY content, this API outputs history when the asset and its - * attached IAM POLICY both exist. This can create gaps in the output history. - * If a specified asset does not exist, this API returns an INVALID_ARGUMENT - * error. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The relative name of the root asset. It can only be an - * organization number (such as "organizations/123"), a project ID (such as - * "projects/my-project-id")", or a project number (such as "projects/12345"). - * @param {string[]} request.assetNames - * A list of the full names of the assets. For example: - * `//compute.googleapis.com/projects/my_project_123/zones/zone1/instances/instance1`. - * See [Resource - * Names](https://cloud.google.com/apis/design/resource_names#full_resource_name) - * and [Resource Name - * Format](https://cloud.google.com/asset-inventory/docs/resource-name-format) - * for more info. - * - * The request becomes a no-op if the asset name list is empty, and the max - * size of the asset name list is 100 in one request. - * @param {google.cloud.asset.v1.ContentType} [request.contentType] - * Optional. The content type. - * @param {google.cloud.asset.v1.TimeWindow} [request.readTimeWindow] - * Optional. The time window for the asset history. Both start_time and - * end_time are optional and if set, it must be after the current time minus - * 35 days. If end_time is not set, it is default to current timestamp. - * If start_time is not set, the snapshot of the assets at end_time will be - * returned. The returned results contain all temporal assets whose time - * window overlap with read_time_window. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.asset.v1.BatchGetAssetsHistoryResponse|BatchGetAssetsHistoryResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1/asset_service.batch_get_assets_history.js - * region_tag:cloudasset_v1_generated_AssetService_BatchGetAssetsHistory_async - */ + /** + * Batch gets the update history of assets that overlap a time window. + * For RESOURCE content, this API outputs history with asset in both + * non-delete or deleted status. + * For IAM_POLICY content, this API outputs history when the asset and its + * attached IAM POLICY both exist. This can create gaps in the output history. + * If a specified asset does not exist, this API returns an INVALID_ARGUMENT + * error. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The relative name of the root asset. It can only be an + * organization number (such as "organizations/123"), a project ID (such as + * "projects/my-project-id")", or a project number (such as "projects/12345"). + * @param {string[]} request.assetNames + * A list of the full names of the assets. For example: + * `//compute.googleapis.com/projects/my_project_123/zones/zone1/instances/instance1`. + * See [Resource + * Names](https://cloud.google.com/apis/design/resource_names#full_resource_name) + * and [Resource Name + * Format](https://cloud.google.com/asset-inventory/docs/resource-name-format) + * for more info. + * + * The request becomes a no-op if the asset name list is empty, and the max + * size of the asset name list is 100 in one request. + * @param {google.cloud.asset.v1.ContentType} [request.contentType] + * Optional. The content type. + * @param {google.cloud.asset.v1.TimeWindow} [request.readTimeWindow] + * Optional. The time window for the asset history. Both start_time and + * end_time are optional and if set, it must be after the current time minus + * 35 days. If end_time is not set, it is default to current timestamp. + * If start_time is not set, the snapshot of the assets at end_time will be + * returned. The returned results contain all temporal assets whose time + * window overlap with read_time_window. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.asset.v1.BatchGetAssetsHistoryResponse|BatchGetAssetsHistoryResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/asset_service.batch_get_assets_history.js + * region_tag:cloudasset_v1_generated_AssetService_BatchGetAssetsHistory_async + */ batchGetAssetsHistory( - request?: protos.google.cloud.asset.v1.IBatchGetAssetsHistoryRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.asset.v1.IBatchGetAssetsHistoryResponse, - protos.google.cloud.asset.v1.IBatchGetAssetsHistoryRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.asset.v1.IBatchGetAssetsHistoryRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.asset.v1.IBatchGetAssetsHistoryResponse, + protos.google.cloud.asset.v1.IBatchGetAssetsHistoryRequest | undefined, + {} | undefined, + ] + >; batchGetAssetsHistory( - request: protos.google.cloud.asset.v1.IBatchGetAssetsHistoryRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.asset.v1.IBatchGetAssetsHistoryResponse, - protos.google.cloud.asset.v1.IBatchGetAssetsHistoryRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.asset.v1.IBatchGetAssetsHistoryRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.asset.v1.IBatchGetAssetsHistoryResponse, + | protos.google.cloud.asset.v1.IBatchGetAssetsHistoryRequest + | null + | undefined, + {} | null | undefined + >, + ): void; batchGetAssetsHistory( - request: protos.google.cloud.asset.v1.IBatchGetAssetsHistoryRequest, - callback: Callback< - protos.google.cloud.asset.v1.IBatchGetAssetsHistoryResponse, - protos.google.cloud.asset.v1.IBatchGetAssetsHistoryRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.asset.v1.IBatchGetAssetsHistoryRequest, + callback: Callback< + protos.google.cloud.asset.v1.IBatchGetAssetsHistoryResponse, + | protos.google.cloud.asset.v1.IBatchGetAssetsHistoryRequest + | null + | undefined, + {} | null | undefined + >, + ): void; batchGetAssetsHistory( - request?: protos.google.cloud.asset.v1.IBatchGetAssetsHistoryRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.asset.v1.IBatchGetAssetsHistoryResponse, - protos.google.cloud.asset.v1.IBatchGetAssetsHistoryRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.asset.v1.IBatchGetAssetsHistoryRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.asset.v1.IBatchGetAssetsHistoryResponse, - protos.google.cloud.asset.v1.IBatchGetAssetsHistoryRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.asset.v1.IBatchGetAssetsHistoryResponse, - protos.google.cloud.asset.v1.IBatchGetAssetsHistoryRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.asset.v1.IBatchGetAssetsHistoryRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.asset.v1.IBatchGetAssetsHistoryResponse, + | protos.google.cloud.asset.v1.IBatchGetAssetsHistoryRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.asset.v1.IBatchGetAssetsHistoryResponse, + protos.google.cloud.asset.v1.IBatchGetAssetsHistoryRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('batchGetAssetsHistory request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.asset.v1.IBatchGetAssetsHistoryResponse, - protos.google.cloud.asset.v1.IBatchGetAssetsHistoryRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.asset.v1.IBatchGetAssetsHistoryResponse, + | protos.google.cloud.asset.v1.IBatchGetAssetsHistoryRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('batchGetAssetsHistory response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.batchGetAssetsHistory(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.asset.v1.IBatchGetAssetsHistoryResponse, - protos.google.cloud.asset.v1.IBatchGetAssetsHistoryRequest|undefined, - {}|undefined - ]) => { - this._log.info('batchGetAssetsHistory response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .batchGetAssetsHistory(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.asset.v1.IBatchGetAssetsHistoryResponse, + ( + | protos.google.cloud.asset.v1.IBatchGetAssetsHistoryRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('batchGetAssetsHistory response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Creates a feed in a parent project/folder/organization to listen to its - * asset updates. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The name of the project/folder/organization where this feed - * should be created in. It can only be an organization number (such as - * "organizations/123"), a folder number (such as "folders/123"), a project ID - * (such as "projects/my-project-id")", or a project number (such as - * "projects/12345"). - * @param {string} request.feedId - * Required. This is the client-assigned asset feed identifier and it needs to - * be unique under a specific parent project/folder/organization. - * @param {google.cloud.asset.v1.Feed} request.feed - * Required. The feed details. The field `name` must be empty and it will be generated - * in the format of: - * projects/project_number/feeds/feed_id - * folders/folder_number/feeds/feed_id - * organizations/organization_number/feeds/feed_id - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.asset.v1.Feed|Feed}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1/asset_service.create_feed.js - * region_tag:cloudasset_v1_generated_AssetService_CreateFeed_async - */ + /** + * Creates a feed in a parent project/folder/organization to listen to its + * asset updates. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The name of the project/folder/organization where this feed + * should be created in. It can only be an organization number (such as + * "organizations/123"), a folder number (such as "folders/123"), a project ID + * (such as "projects/my-project-id")", or a project number (such as + * "projects/12345"). + * @param {string} request.feedId + * Required. This is the client-assigned asset feed identifier and it needs to + * be unique under a specific parent project/folder/organization. + * @param {google.cloud.asset.v1.Feed} request.feed + * Required. The feed details. The field `name` must be empty and it will be generated + * in the format of: + * projects/project_number/feeds/feed_id + * folders/folder_number/feeds/feed_id + * organizations/organization_number/feeds/feed_id + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.asset.v1.Feed|Feed}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/asset_service.create_feed.js + * region_tag:cloudasset_v1_generated_AssetService_CreateFeed_async + */ createFeed( - request?: protos.google.cloud.asset.v1.ICreateFeedRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.asset.v1.IFeed, - protos.google.cloud.asset.v1.ICreateFeedRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.asset.v1.ICreateFeedRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.asset.v1.IFeed, + protos.google.cloud.asset.v1.ICreateFeedRequest | undefined, + {} | undefined, + ] + >; createFeed( - request: protos.google.cloud.asset.v1.ICreateFeedRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.asset.v1.IFeed, - protos.google.cloud.asset.v1.ICreateFeedRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.asset.v1.ICreateFeedRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.asset.v1.IFeed, + protos.google.cloud.asset.v1.ICreateFeedRequest | null | undefined, + {} | null | undefined + >, + ): void; createFeed( - request: protos.google.cloud.asset.v1.ICreateFeedRequest, - callback: Callback< - protos.google.cloud.asset.v1.IFeed, - protos.google.cloud.asset.v1.ICreateFeedRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.asset.v1.ICreateFeedRequest, + callback: Callback< + protos.google.cloud.asset.v1.IFeed, + protos.google.cloud.asset.v1.ICreateFeedRequest | null | undefined, + {} | null | undefined + >, + ): void; createFeed( - request?: protos.google.cloud.asset.v1.ICreateFeedRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.asset.v1.IFeed, - protos.google.cloud.asset.v1.ICreateFeedRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.asset.v1.ICreateFeedRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.asset.v1.IFeed, - protos.google.cloud.asset.v1.ICreateFeedRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.asset.v1.IFeed, - protos.google.cloud.asset.v1.ICreateFeedRequest|undefined, {}|undefined - ]>|void { + protos.google.cloud.asset.v1.ICreateFeedRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.asset.v1.IFeed, + protos.google.cloud.asset.v1.ICreateFeedRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.asset.v1.IFeed, + protos.google.cloud.asset.v1.ICreateFeedRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('createFeed request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.asset.v1.IFeed, - protos.google.cloud.asset.v1.ICreateFeedRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.asset.v1.IFeed, + protos.google.cloud.asset.v1.ICreateFeedRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createFeed response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.createFeed(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.asset.v1.IFeed, - protos.google.cloud.asset.v1.ICreateFeedRequest|undefined, - {}|undefined - ]) => { - this._log.info('createFeed response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createFeed(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.asset.v1.IFeed, + protos.google.cloud.asset.v1.ICreateFeedRequest | undefined, + {} | undefined, + ]) => { + this._log.info('createFeed response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Gets details about an asset feed. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The name of the Feed and it must be in the format of: - * projects/project_number/feeds/feed_id - * folders/folder_number/feeds/feed_id - * organizations/organization_number/feeds/feed_id - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.asset.v1.Feed|Feed}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1/asset_service.get_feed.js - * region_tag:cloudasset_v1_generated_AssetService_GetFeed_async - */ + /** + * Gets details about an asset feed. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The name of the Feed and it must be in the format of: + * projects/project_number/feeds/feed_id + * folders/folder_number/feeds/feed_id + * organizations/organization_number/feeds/feed_id + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.asset.v1.Feed|Feed}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/asset_service.get_feed.js + * region_tag:cloudasset_v1_generated_AssetService_GetFeed_async + */ getFeed( - request?: protos.google.cloud.asset.v1.IGetFeedRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.asset.v1.IFeed, - protos.google.cloud.asset.v1.IGetFeedRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.asset.v1.IGetFeedRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.asset.v1.IFeed, + protos.google.cloud.asset.v1.IGetFeedRequest | undefined, + {} | undefined, + ] + >; getFeed( - request: protos.google.cloud.asset.v1.IGetFeedRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.asset.v1.IFeed, - protos.google.cloud.asset.v1.IGetFeedRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.asset.v1.IGetFeedRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.asset.v1.IFeed, + protos.google.cloud.asset.v1.IGetFeedRequest | null | undefined, + {} | null | undefined + >, + ): void; getFeed( - request: protos.google.cloud.asset.v1.IGetFeedRequest, - callback: Callback< - protos.google.cloud.asset.v1.IFeed, - protos.google.cloud.asset.v1.IGetFeedRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.asset.v1.IGetFeedRequest, + callback: Callback< + protos.google.cloud.asset.v1.IFeed, + protos.google.cloud.asset.v1.IGetFeedRequest | null | undefined, + {} | null | undefined + >, + ): void; getFeed( - request?: protos.google.cloud.asset.v1.IGetFeedRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.asset.v1.IFeed, - protos.google.cloud.asset.v1.IGetFeedRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.asset.v1.IGetFeedRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.asset.v1.IFeed, - protos.google.cloud.asset.v1.IGetFeedRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.asset.v1.IFeed, - protos.google.cloud.asset.v1.IGetFeedRequest|undefined, {}|undefined - ]>|void { + protos.google.cloud.asset.v1.IGetFeedRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.asset.v1.IFeed, + protos.google.cloud.asset.v1.IGetFeedRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.asset.v1.IFeed, + protos.google.cloud.asset.v1.IGetFeedRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getFeed request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.asset.v1.IFeed, - protos.google.cloud.asset.v1.IGetFeedRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.asset.v1.IFeed, + protos.google.cloud.asset.v1.IGetFeedRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getFeed response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getFeed(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.asset.v1.IFeed, - protos.google.cloud.asset.v1.IGetFeedRequest|undefined, - {}|undefined - ]) => { - this._log.info('getFeed response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getFeed(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.asset.v1.IFeed, + protos.google.cloud.asset.v1.IGetFeedRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getFeed response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Lists all asset feeds in a parent project/folder/organization. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent project/folder/organization whose feeds are to be - * listed. It can only be using project/folder/organization number (such as - * "folders/12345")", or a project ID (such as "projects/my-project-id"). - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.asset.v1.ListFeedsResponse|ListFeedsResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1/asset_service.list_feeds.js - * region_tag:cloudasset_v1_generated_AssetService_ListFeeds_async - */ + /** + * Lists all asset feeds in a parent project/folder/organization. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent project/folder/organization whose feeds are to be + * listed. It can only be using project/folder/organization number (such as + * "folders/12345")", or a project ID (such as "projects/my-project-id"). + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.asset.v1.ListFeedsResponse|ListFeedsResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/asset_service.list_feeds.js + * region_tag:cloudasset_v1_generated_AssetService_ListFeeds_async + */ listFeeds( - request?: protos.google.cloud.asset.v1.IListFeedsRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.asset.v1.IListFeedsResponse, - protos.google.cloud.asset.v1.IListFeedsRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.asset.v1.IListFeedsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.asset.v1.IListFeedsResponse, + protos.google.cloud.asset.v1.IListFeedsRequest | undefined, + {} | undefined, + ] + >; listFeeds( - request: protos.google.cloud.asset.v1.IListFeedsRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.asset.v1.IListFeedsResponse, - protos.google.cloud.asset.v1.IListFeedsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.asset.v1.IListFeedsRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.asset.v1.IListFeedsResponse, + protos.google.cloud.asset.v1.IListFeedsRequest | null | undefined, + {} | null | undefined + >, + ): void; listFeeds( - request: protos.google.cloud.asset.v1.IListFeedsRequest, - callback: Callback< - protos.google.cloud.asset.v1.IListFeedsResponse, - protos.google.cloud.asset.v1.IListFeedsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.asset.v1.IListFeedsRequest, + callback: Callback< + protos.google.cloud.asset.v1.IListFeedsResponse, + protos.google.cloud.asset.v1.IListFeedsRequest | null | undefined, + {} | null | undefined + >, + ): void; listFeeds( - request?: protos.google.cloud.asset.v1.IListFeedsRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.cloud.asset.v1.IListFeedsRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.asset.v1.IListFeedsResponse, - protos.google.cloud.asset.v1.IListFeedsRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.cloud.asset.v1.IListFeedsResponse, - protos.google.cloud.asset.v1.IListFeedsRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.asset.v1.IListFeedsResponse, - protos.google.cloud.asset.v1.IListFeedsRequest|undefined, {}|undefined - ]>|void { + protos.google.cloud.asset.v1.IListFeedsRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.asset.v1.IListFeedsResponse, + protos.google.cloud.asset.v1.IListFeedsRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.asset.v1.IListFeedsResponse, + protos.google.cloud.asset.v1.IListFeedsRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('listFeeds request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.asset.v1.IListFeedsResponse, - protos.google.cloud.asset.v1.IListFeedsRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.asset.v1.IListFeedsResponse, + protos.google.cloud.asset.v1.IListFeedsRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('listFeeds response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.listFeeds(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.asset.v1.IListFeedsResponse, - protos.google.cloud.asset.v1.IListFeedsRequest|undefined, - {}|undefined - ]) => { - this._log.info('listFeeds response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .listFeeds(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.asset.v1.IListFeedsResponse, + protos.google.cloud.asset.v1.IListFeedsRequest | undefined, + {} | undefined, + ]) => { + this._log.info('listFeeds response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Updates an asset feed configuration. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.cloud.asset.v1.Feed} request.feed - * Required. The new values of feed details. It must match an existing feed and the - * field `name` must be in the format of: - * projects/project_number/feeds/feed_id or - * folders/folder_number/feeds/feed_id or - * organizations/organization_number/feeds/feed_id. - * @param {google.protobuf.FieldMask} request.updateMask - * Required. Only updates the `feed` fields indicated by this mask. - * The field mask must not be empty, and it must not contain fields that - * are immutable or only set by the server. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.asset.v1.Feed|Feed}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1/asset_service.update_feed.js - * region_tag:cloudasset_v1_generated_AssetService_UpdateFeed_async - */ + /** + * Updates an asset feed configuration. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.cloud.asset.v1.Feed} request.feed + * Required. The new values of feed details. It must match an existing feed and the + * field `name` must be in the format of: + * projects/project_number/feeds/feed_id or + * folders/folder_number/feeds/feed_id or + * organizations/organization_number/feeds/feed_id. + * @param {google.protobuf.FieldMask} request.updateMask + * Required. Only updates the `feed` fields indicated by this mask. + * The field mask must not be empty, and it must not contain fields that + * are immutable or only set by the server. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.asset.v1.Feed|Feed}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/asset_service.update_feed.js + * region_tag:cloudasset_v1_generated_AssetService_UpdateFeed_async + */ updateFeed( - request?: protos.google.cloud.asset.v1.IUpdateFeedRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.asset.v1.IFeed, - protos.google.cloud.asset.v1.IUpdateFeedRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.asset.v1.IUpdateFeedRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.asset.v1.IFeed, + protos.google.cloud.asset.v1.IUpdateFeedRequest | undefined, + {} | undefined, + ] + >; updateFeed( - request: protos.google.cloud.asset.v1.IUpdateFeedRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.asset.v1.IFeed, - protos.google.cloud.asset.v1.IUpdateFeedRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.asset.v1.IUpdateFeedRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.asset.v1.IFeed, + protos.google.cloud.asset.v1.IUpdateFeedRequest | null | undefined, + {} | null | undefined + >, + ): void; updateFeed( - request: protos.google.cloud.asset.v1.IUpdateFeedRequest, - callback: Callback< - protos.google.cloud.asset.v1.IFeed, - protos.google.cloud.asset.v1.IUpdateFeedRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.asset.v1.IUpdateFeedRequest, + callback: Callback< + protos.google.cloud.asset.v1.IFeed, + protos.google.cloud.asset.v1.IUpdateFeedRequest | null | undefined, + {} | null | undefined + >, + ): void; updateFeed( - request?: protos.google.cloud.asset.v1.IUpdateFeedRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.cloud.asset.v1.IUpdateFeedRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.asset.v1.IFeed, - protos.google.cloud.asset.v1.IUpdateFeedRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.cloud.asset.v1.IFeed, - protos.google.cloud.asset.v1.IUpdateFeedRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.asset.v1.IFeed, - protos.google.cloud.asset.v1.IUpdateFeedRequest|undefined, {}|undefined - ]>|void { + protos.google.cloud.asset.v1.IUpdateFeedRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.asset.v1.IFeed, + protos.google.cloud.asset.v1.IUpdateFeedRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.asset.v1.IFeed, + protos.google.cloud.asset.v1.IUpdateFeedRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'feed.name': request.feed!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'feed.name': request.feed!.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateFeed request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.asset.v1.IFeed, - protos.google.cloud.asset.v1.IUpdateFeedRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.asset.v1.IFeed, + protos.google.cloud.asset.v1.IUpdateFeedRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateFeed response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.updateFeed(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.asset.v1.IFeed, - protos.google.cloud.asset.v1.IUpdateFeedRequest|undefined, - {}|undefined - ]) => { - this._log.info('updateFeed response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateFeed(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.asset.v1.IFeed, + protos.google.cloud.asset.v1.IUpdateFeedRequest | undefined, + {} | undefined, + ]) => { + this._log.info('updateFeed response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Deletes an asset feed. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The name of the feed and it must be in the format of: - * projects/project_number/feeds/feed_id - * folders/folder_number/feeds/feed_id - * organizations/organization_number/feeds/feed_id - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1/asset_service.delete_feed.js - * region_tag:cloudasset_v1_generated_AssetService_DeleteFeed_async - */ + /** + * Deletes an asset feed. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The name of the feed and it must be in the format of: + * projects/project_number/feeds/feed_id + * folders/folder_number/feeds/feed_id + * organizations/organization_number/feeds/feed_id + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/asset_service.delete_feed.js + * region_tag:cloudasset_v1_generated_AssetService_DeleteFeed_async + */ deleteFeed( - request?: protos.google.cloud.asset.v1.IDeleteFeedRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.cloud.asset.v1.IDeleteFeedRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.asset.v1.IDeleteFeedRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.cloud.asset.v1.IDeleteFeedRequest | undefined, + {} | undefined, + ] + >; deleteFeed( - request: protos.google.cloud.asset.v1.IDeleteFeedRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.cloud.asset.v1.IDeleteFeedRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.asset.v1.IDeleteFeedRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.cloud.asset.v1.IDeleteFeedRequest | null | undefined, + {} | null | undefined + >, + ): void; deleteFeed( - request: protos.google.cloud.asset.v1.IDeleteFeedRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.cloud.asset.v1.IDeleteFeedRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.asset.v1.IDeleteFeedRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.cloud.asset.v1.IDeleteFeedRequest | null | undefined, + {} | null | undefined + >, + ): void; deleteFeed( - request?: protos.google.cloud.asset.v1.IDeleteFeedRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.cloud.asset.v1.IDeleteFeedRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.cloud.asset.v1.IDeleteFeedRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.protobuf.IEmpty, - protos.google.cloud.asset.v1.IDeleteFeedRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.cloud.asset.v1.IDeleteFeedRequest|undefined, {}|undefined - ]>|void { + protos.google.cloud.asset.v1.IDeleteFeedRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + protos.google.cloud.asset.v1.IDeleteFeedRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.cloud.asset.v1.IDeleteFeedRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('deleteFeed request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.cloud.asset.v1.IDeleteFeedRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + protos.google.cloud.asset.v1.IDeleteFeedRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteFeed response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.deleteFeed(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.cloud.asset.v1.IDeleteFeedRequest|undefined, - {}|undefined - ]) => { - this._log.info('deleteFeed response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteFeed(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.cloud.asset.v1.IDeleteFeedRequest | undefined, + {} | undefined, + ]) => { + this._log.info('deleteFeed response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Exports assets with time and resource types to a given Cloud Storage - * location. The output format is newline-delimited JSON. - * This API implements the {@link protos.google.longrunning.Operation|google.longrunning.Operation} API allowing you - * to keep track of the export. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The relative name of the root asset. This can only be an - * organization number (such as "organizations/123"), a project ID (such as - * "projects/my-project-id"), or a project number (such as "projects/12345"), - * or a folder number (such as "folders/123"). - * @param {google.protobuf.Timestamp} request.readTime - * Timestamp to take an asset snapshot. This can only be set to a timestamp - * between the current time and the current time minus 35 days (inclusive). - * If not specified, the current time will be used. Due to delays in resource - * data collection and indexing, there is a volatile window during which - * running the same query may get different results. - * @param {string[]} request.assetTypes - * A list of asset types of which to take a snapshot for. For example: - * "compute.googleapis.com/Disk". If specified, only matching assets will be - * returned. See [Introduction to Cloud Asset - * Inventory](https://cloud.google.com/asset-inventory/docs/overview) - * for all supported asset types. - * @param {google.cloud.asset.v1.ContentType} request.contentType - * Asset content type. If not specified, no content but the asset name will be - * returned. - * @param {google.cloud.asset.v1.OutputConfig} request.outputConfig - * Required. Output configuration indicating where the results will be output - * to. All results will be in newline delimited JSON format. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing - * a long running operation. Its `promise()` method returns a promise - * you can `await` for. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v1/asset_service.export_assets.js - * region_tag:cloudasset_v1_generated_AssetService_ExportAssets_async - */ + /** + * Exports assets with time and resource types to a given Cloud Storage + * location. The output format is newline-delimited JSON. + * This API implements the {@link protos.google.longrunning.Operation|google.longrunning.Operation} API allowing you + * to keep track of the export. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The relative name of the root asset. This can only be an + * organization number (such as "organizations/123"), a project ID (such as + * "projects/my-project-id"), or a project number (such as "projects/12345"), + * or a folder number (such as "folders/123"). + * @param {google.protobuf.Timestamp} request.readTime + * Timestamp to take an asset snapshot. This can only be set to a timestamp + * between the current time and the current time minus 35 days (inclusive). + * If not specified, the current time will be used. Due to delays in resource + * data collection and indexing, there is a volatile window during which + * running the same query may get different results. + * @param {string[]} request.assetTypes + * A list of asset types of which to take a snapshot for. For example: + * "compute.googleapis.com/Disk". If specified, only matching assets will be + * returned. See [Introduction to Cloud Asset + * Inventory](https://cloud.google.com/asset-inventory/docs/overview) + * for all supported asset types. + * @param {google.cloud.asset.v1.ContentType} request.contentType + * Asset content type. If not specified, no content but the asset name will be + * returned. + * @param {google.cloud.asset.v1.OutputConfig} request.outputConfig + * Required. Output configuration indicating where the results will be output + * to. All results will be in newline delimited JSON format. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v1/asset_service.export_assets.js + * region_tag:cloudasset_v1_generated_AssetService_ExportAssets_async + */ exportAssets( - request?: protos.google.cloud.asset.v1.IExportAssetsRequest, - options?: CallOptions): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>; + request?: protos.google.cloud.asset.v1.IExportAssetsRequest, + options?: CallOptions, + ): Promise< + [ + LROperation< + protos.google.cloud.asset.v1.IExportAssetsResponse, + protos.google.cloud.asset.v1.IExportAssetsRequest + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; exportAssets( - request: protos.google.cloud.asset.v1.IExportAssetsRequest, - options: CallOptions, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.asset.v1.IExportAssetsRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.cloud.asset.v1.IExportAssetsResponse, + protos.google.cloud.asset.v1.IExportAssetsRequest + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; exportAssets( - request: protos.google.cloud.asset.v1.IExportAssetsRequest, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.asset.v1.IExportAssetsRequest, + callback: Callback< + LROperation< + protos.google.cloud.asset.v1.IExportAssetsResponse, + protos.google.cloud.asset.v1.IExportAssetsRequest + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; exportAssets( - request?: protos.google.cloud.asset.v1.IExportAssetsRequest, - optionsOrCallback?: CallOptions|Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>, - callback?: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>|void { + request?: protos.google.cloud.asset.v1.IExportAssetsRequest, + optionsOrCallback?: + | CallOptions + | Callback< + LROperation< + protos.google.cloud.asset.v1.IExportAssetsResponse, + protos.google.cloud.asset.v1.IExportAssetsRequest + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + callback?: Callback< + LROperation< + protos.google.cloud.asset.v1.IExportAssetsResponse, + protos.google.cloud.asset.v1.IExportAssetsRequest + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + LROperation< + protos.google.cloud.asset.v1.IExportAssetsResponse, + protos.google.cloud.asset.v1.IExportAssetsRequest + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + LROperation< + protos.google.cloud.asset.v1.IExportAssetsResponse, + protos.google.cloud.asset.v1.IExportAssetsRequest + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, rawResponse, _) => { this._log.info('exportAssets response %j', rawResponse); callback!(error, response, rawResponse, _); // We verified callback above. } : undefined; this._log.info('exportAssets request %j', request); - return this.innerApiCalls.exportAssets(request, options, wrappedCallback) - ?.then(([response, rawResponse, _]: [ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]) => { - this._log.info('exportAssets response %j', rawResponse); - return [response, rawResponse, _]; - }); + return this.innerApiCalls + .exportAssets(request, options, wrappedCallback) + ?.then( + ([response, rawResponse, _]: [ + LROperation< + protos.google.cloud.asset.v1.IExportAssetsResponse, + protos.google.cloud.asset.v1.IExportAssetsRequest + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ]) => { + this._log.info('exportAssets response %j', rawResponse); + return [response, rawResponse, _]; + }, + ); } -/** - * Check the status of the long running operation returned by `exportAssets()`. - * @param {String} name - * The operation name that will be passed. - * @returns {Promise} - The promise which resolves to an object. - * The decoded operation object has result and metadata field to get information from. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v1/asset_service.export_assets.js - * region_tag:cloudasset_v1_generated_AssetService_ExportAssets_async - */ - async checkExportAssetsProgress(name: string): Promise>{ + /** + * Check the status of the long running operation returned by `exportAssets()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v1/asset_service.export_assets.js + * region_tag:cloudasset_v1_generated_AssetService_ExportAssets_async + */ + async checkExportAssetsProgress( + name: string, + ): Promise< + LROperation< + protos.google.cloud.asset.v1.ExportAssetsResponse, + protos.google.cloud.asset.v1.ExportAssetsRequest + > + > { this._log.info('exportAssets long-running'); - const request = new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest({name}); + const request = + new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( + { name }, + ); const [operation] = await this.operationsClient.getOperation(request); - const decodeOperation = new this._gaxModule.Operation(operation, this.descriptors.longrunning.exportAssets, this._gaxModule.createDefaultBackoffSettings()); - return decodeOperation as LROperation; + const decodeOperation = new this._gaxModule.Operation( + operation, + this.descriptors.longrunning.exportAssets, + this._gaxModule.createDefaultBackoffSettings(), + ); + return decodeOperation as LROperation< + protos.google.cloud.asset.v1.ExportAssetsResponse, + protos.google.cloud.asset.v1.ExportAssetsRequest + >; } // -------------------- // -- Path templates -- @@ -1122,7 +1432,7 @@ export class AssetServiceClient { * @param {string} feed * @returns {string} Resource name string. */ - folderFeedPath(folder:string,feed:string) { + folderFeedPath(folder: string, feed: string) { return this.pathTemplates.folderFeedPathTemplate.render({ folder: folder, feed: feed, @@ -1137,7 +1447,8 @@ export class AssetServiceClient { * @returns {string} A string representing the folder. */ matchFolderFromFolderFeedName(folderFeedName: string) { - return this.pathTemplates.folderFeedPathTemplate.match(folderFeedName).folder; + return this.pathTemplates.folderFeedPathTemplate.match(folderFeedName) + .folder; } /** @@ -1158,7 +1469,7 @@ export class AssetServiceClient { * @param {string} feed * @returns {string} Resource name string. */ - organizationFeedPath(organization:string,feed:string) { + organizationFeedPath(organization: string, feed: string) { return this.pathTemplates.organizationFeedPathTemplate.render({ organization: organization, feed: feed, @@ -1173,7 +1484,9 @@ export class AssetServiceClient { * @returns {string} A string representing the organization. */ matchOrganizationFromOrganizationFeedName(organizationFeedName: string) { - return this.pathTemplates.organizationFeedPathTemplate.match(organizationFeedName).organization; + return this.pathTemplates.organizationFeedPathTemplate.match( + organizationFeedName, + ).organization; } /** @@ -1184,7 +1497,9 @@ export class AssetServiceClient { * @returns {string} A string representing the feed. */ matchFeedFromOrganizationFeedName(organizationFeedName: string) { - return this.pathTemplates.organizationFeedPathTemplate.match(organizationFeedName).feed; + return this.pathTemplates.organizationFeedPathTemplate.match( + organizationFeedName, + ).feed; } /** @@ -1194,7 +1509,7 @@ export class AssetServiceClient { * @param {string} feed * @returns {string} Resource name string. */ - projectFeedPath(project:string,feed:string) { + projectFeedPath(project: string, feed: string) { return this.pathTemplates.projectFeedPathTemplate.render({ project: project, feed: feed, @@ -1209,7 +1524,8 @@ export class AssetServiceClient { * @returns {string} A string representing the project. */ matchProjectFromProjectFeedName(projectFeedName: string) { - return this.pathTemplates.projectFeedPathTemplate.match(projectFeedName).project; + return this.pathTemplates.projectFeedPathTemplate.match(projectFeedName) + .project; } /** @@ -1220,7 +1536,8 @@ export class AssetServiceClient { * @returns {string} A string representing the feed. */ matchFeedFromProjectFeedName(projectFeedName: string) { - return this.pathTemplates.projectFeedPathTemplate.match(projectFeedName).feed; + return this.pathTemplates.projectFeedPathTemplate.match(projectFeedName) + .feed; } /** @@ -1231,7 +1548,7 @@ export class AssetServiceClient { */ close(): Promise { if (this.assetServiceStub && !this._terminated) { - return this.assetServiceStub.then(stub => { + return this.assetServiceStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -1240,4 +1557,4 @@ export class AssetServiceClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/core/generator/gapic-generator-typescript/baselines/asset/src/v1/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/asset/src/v1/index.ts.baseline index a104b4e29681..43a33ec89fd9 100644 --- a/core/generator/gapic-generator-typescript/baselines/asset/src/v1/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/asset/src/v1/index.ts.baseline @@ -16,4 +16,4 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -export {AssetServiceClient} from './asset_service_client'; +export { AssetServiceClient } from './asset_service_client'; diff --git a/core/generator/gapic-generator-typescript/baselines/asset/system-test/fixtures/sample/src/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/asset/system-test/fixtures/sample/src/index.ts.baseline index 9e97334ff46b..01f8c50342f7 100644 --- a/core/generator/gapic-generator-typescript/baselines/asset/system-test/fixtures/sample/src/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/asset/system-test/fixtures/sample/src/index.ts.baseline @@ -16,7 +16,7 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -import {AssetServiceClient} from '@google-cloud/asset'; +import { AssetServiceClient } from '@google-cloud/asset'; // check that the client class type name can be used function doStuffWithAssetServiceClient(client: AssetServiceClient) { diff --git a/core/generator/gapic-generator-typescript/baselines/asset/system-test/install.ts.baseline b/core/generator/gapic-generator-typescript/baselines/asset/system-test/install.ts.baseline index f66069aa3940..ccf167042d2e 100644 --- a/core/generator/gapic-generator-typescript/baselines/asset/system-test/install.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/asset/system-test/install.ts.baseline @@ -16,34 +16,36 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -import {packNTest} from 'pack-n-play'; -import {readFileSync} from 'fs'; -import {describe, it} from 'mocha'; +import { packNTest } from 'pack-n-play'; +import { readFileSync } from 'fs'; +import { describe, it } from 'mocha'; describe('📦 pack-n-play test', () => { - - it('TypeScript code', async function() { + it('TypeScript code', async function () { this.timeout(300000); const options = { packageDir: process.cwd(), sample: { description: 'TypeScript user can use the type definitions', - ts: readFileSync('./system-test/fixtures/sample/src/index.ts').toString() - } + ts: readFileSync( + './system-test/fixtures/sample/src/index.ts', + ).toString(), + }, }; await packNTest(options); }); - it('JavaScript code', async function() { + it('JavaScript code', async function () { this.timeout(300000); const options = { packageDir: process.cwd(), sample: { description: 'JavaScript user can use the library', - cjs: readFileSync('./system-test/fixtures/sample/src/index.js').toString() - } + cjs: readFileSync( + './system-test/fixtures/sample/src/index.js', + ).toString(), + }, }; await packNTest(options); }); - }); diff --git a/core/generator/gapic-generator-typescript/baselines/asset/test/gapic_asset_service_v1.ts.baseline b/core/generator/gapic-generator-typescript/baselines/asset/test/gapic_asset_service_v1.ts.baseline index 3116b196c337..a881916998d0 100644 --- a/core/generator/gapic-generator-typescript/baselines/asset/test/gapic_asset_service_v1.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/asset/test/gapic_asset_service_v1.ts.baseline @@ -19,1135 +19,1413 @@ import * as protos from '../protos/protos'; import * as assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as assetserviceModule from '../src'; -import {protobuf, LROperation, operationsProtos} from 'google-gax'; +import { protobuf, LROperation, operationsProtos } from 'google-gax'; // Dynamically loaded proto JSON is needed to get the type information // to fill in default values for request objects -const root = protobuf.Root.fromJSON(require('../protos/protos.json')).resolveAll(); +const root = protobuf.Root.fromJSON( + require('../protos/protos.json'), +).resolveAll(); // eslint-disable-next-line @typescript-eslint/no-unused-vars function getTypeDefaultValue(typeName: string, fields: string[]) { - let type = root.lookupType(typeName) as protobuf.Type; - for (const field of fields.slice(0, -1)) { - type = type.fields[field]?.resolvedType as protobuf.Type; - } - return type.fields[fields[fields.length - 1]]?.defaultValue; + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type.fields[field]?.resolvedType as protobuf.Type; + } + return type.fields[fields[fields.length - 1]]?.defaultValue; } function generateSampleMessage(instance: T) { - const filledObject = (instance.constructor as typeof protobuf.Message) - .toObject(instance as protobuf.Message, {defaults: true}); - return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, { defaults: true }); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; } function stubSimpleCall(response?: ResponseType, error?: Error) { - return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); } -function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { - return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +function stubSimpleCallWithCallback( + response?: ResponseType, + error?: Error, +) { + return error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); } -function stubLongRunningCall(response?: ResponseType, callError?: Error, lroError?: Error) { - const innerStub = lroError ? sinon.stub().rejects(lroError) : sinon.stub().resolves([response]); - const mockOperation = { - promise: innerStub, - }; - return callError ? sinon.stub().rejects(callError) : sinon.stub().resolves([mockOperation]); +function stubLongRunningCall( + response?: ResponseType, + callError?: Error, + lroError?: Error, +) { + const innerStub = lroError + ? sinon.stub().rejects(lroError) + : sinon.stub().resolves([response]); + const mockOperation = { + promise: innerStub, + }; + return callError + ? sinon.stub().rejects(callError) + : sinon.stub().resolves([mockOperation]); } -function stubLongRunningCallWithCallback(response?: ResponseType, callError?: Error, lroError?: Error) { - const innerStub = lroError ? sinon.stub().rejects(lroError) : sinon.stub().resolves([response]); - const mockOperation = { - promise: innerStub, - }; - return callError ? sinon.stub().callsArgWith(2, callError) : sinon.stub().callsArgWith(2, null, mockOperation); +function stubLongRunningCallWithCallback( + response?: ResponseType, + callError?: Error, + lroError?: Error, +) { + const innerStub = lroError + ? sinon.stub().rejects(lroError) + : sinon.stub().resolves([response]); + const mockOperation = { + promise: innerStub, + }; + return callError + ? sinon.stub().callsArgWith(2, callError) + : sinon.stub().callsArgWith(2, null, mockOperation); } describe('v1.AssetServiceClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new assetserviceModule.v1.AssetServiceClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'cloudasset.googleapis.com'); - }); - - it('has universeDomain', () => { - const client = new assetserviceModule.v1.AssetServiceClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); - - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - it('throws DeprecationWarning if static servicePath is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const servicePath = assetserviceModule.v1.AssetServiceClient.servicePath; - assert.strictEqual(servicePath, 'cloudasset.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = assetserviceModule.v1.AssetServiceClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'cloudasset.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new assetserviceModule.v1.AssetServiceClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'cloudasset.example.com'); - }); - - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new assetserviceModule.v1.AssetServiceClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'cloudasset.example.com'); - }); - - if (typeof process === 'object' && 'env' in process) { - describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { - it('sets apiEndpoint from environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new assetserviceModule.v1.AssetServiceClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'cloudasset.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - - it('value configured in code has priority over environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new assetserviceModule.v1.AssetServiceClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'cloudasset.configured.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { new assetserviceModule.v1.AssetServiceClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); - - it('has port', () => { - const port = assetserviceModule.v1.AssetServiceClient.port; - assert(port); - assert(typeof port === 'number'); - }); - - it('should create a client with no option', () => { - const client = new assetserviceModule.v1.AssetServiceClient(); - assert(client); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new assetserviceModule.v1.AssetServiceClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'cloudasset.googleapis.com'); + }); - it('should create a client with gRPC fallback', () => { - const client = new assetserviceModule.v1.AssetServiceClient({ - fallback: true, - }); - assert(client); - }); + it('has universeDomain', () => { + const client = new assetserviceModule.v1.AssetServiceClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - it('has initialize method and supports deferred initialization', async () => { - const client = new assetserviceModule.v1.AssetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.assetServiceStub, undefined); - await client.initialize(); - assert(client.assetServiceStub); - }); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = + assetserviceModule.v1.AssetServiceClient.servicePath; + assert.strictEqual(servicePath, 'cloudasset.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + assetserviceModule.v1.AssetServiceClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'cloudasset.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = new assetserviceModule.v1.AssetServiceClient({ + universeDomain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'cloudasset.example.com'); + }); - it('has close method for the initialized client', done => { - const client = new assetserviceModule.v1.AssetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.assetServiceStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = new assetserviceModule.v1.AssetServiceClient({ + universe_domain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'cloudasset.example.com'); + }); - it('has close method for the non-initialized client', done => { - const client = new assetserviceModule.v1.AssetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.assetServiceStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); + if (typeof process === 'object' && 'env' in process) { + describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { + it('sets apiEndpoint from environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new assetserviceModule.v1.AssetServiceClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'cloudasset.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new assetserviceModule.v1.AssetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + it('value configured in code has priority over environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new assetserviceModule.v1.AssetServiceClient({ + universeDomain: 'configured.example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'cloudasset.configured.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new assetserviceModule.v1.AssetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId((err?: Error|null, projectId?: string|null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } - }); - }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new assetserviceModule.v1.AssetServiceClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); }); - describe('batchGetAssetsHistory', () => { - it('invokes batchGetAssetsHistory without error', async () => { - const client = new assetserviceModule.v1.AssetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.asset.v1.BatchGetAssetsHistoryRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.asset.v1.BatchGetAssetsHistoryRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.asset.v1.BatchGetAssetsHistoryResponse() - ); - client.innerApiCalls.batchGetAssetsHistory = stubSimpleCall(expectedResponse); - const [response] = await client.batchGetAssetsHistory(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.batchGetAssetsHistory as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.batchGetAssetsHistory as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has port', () => { + const port = assetserviceModule.v1.AssetServiceClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('invokes batchGetAssetsHistory without error using callback', async () => { - const client = new assetserviceModule.v1.AssetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.asset.v1.BatchGetAssetsHistoryRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.asset.v1.BatchGetAssetsHistoryRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.asset.v1.BatchGetAssetsHistoryResponse() - ); - client.innerApiCalls.batchGetAssetsHistory = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.batchGetAssetsHistory( - request, - (err?: Error|null, result?: protos.google.cloud.asset.v1.IBatchGetAssetsHistoryResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.batchGetAssetsHistory as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.batchGetAssetsHistory as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('should create a client with no option', () => { + const client = new assetserviceModule.v1.AssetServiceClient(); + assert(client); + }); - it('invokes batchGetAssetsHistory with error', async () => { - const client = new assetserviceModule.v1.AssetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.asset.v1.BatchGetAssetsHistoryRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.asset.v1.BatchGetAssetsHistoryRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.batchGetAssetsHistory = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.batchGetAssetsHistory(request), expectedError); - const actualRequest = (client.innerApiCalls.batchGetAssetsHistory as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.batchGetAssetsHistory as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('should create a client with gRPC fallback', () => { + const client = new assetserviceModule.v1.AssetServiceClient({ + fallback: true, + }); + assert(client); + }); - it('invokes batchGetAssetsHistory with closed client', async () => { - const client = new assetserviceModule.v1.AssetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.asset.v1.BatchGetAssetsHistoryRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.asset.v1.BatchGetAssetsHistoryRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.batchGetAssetsHistory(request), expectedError); - }); + it('has initialize method and supports deferred initialization', async () => { + const client = new assetserviceModule.v1.AssetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.assetServiceStub, undefined); + await client.initialize(); + assert(client.assetServiceStub); }); - describe('createFeed', () => { - it('invokes createFeed without error', async () => { - const client = new assetserviceModule.v1.AssetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.asset.v1.CreateFeedRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.asset.v1.CreateFeedRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.asset.v1.Feed() - ); - client.innerApiCalls.createFeed = stubSimpleCall(expectedResponse); - const [response] = await client.createFeed(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createFeed as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createFeed as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('has close method for the initialized client', (done) => { + const client = new assetserviceModule.v1.AssetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.assetServiceStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes createFeed without error using callback', async () => { - const client = new assetserviceModule.v1.AssetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.asset.v1.CreateFeedRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.asset.v1.CreateFeedRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.asset.v1.Feed() - ); - client.innerApiCalls.createFeed = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createFeed( - request, - (err?: Error|null, result?: protos.google.cloud.asset.v1.IFeed|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createFeed as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createFeed as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('has close method for the non-initialized client', (done) => { + const client = new assetserviceModule.v1.AssetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.assetServiceStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes createFeed with error', async () => { - const client = new assetserviceModule.v1.AssetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.asset.v1.CreateFeedRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.asset.v1.CreateFeedRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createFeed = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createFeed(request), expectedError); - const actualRequest = (client.innerApiCalls.createFeed as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createFeed as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new assetserviceModule.v1.AssetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + }); - it('invokes createFeed with closed client', async () => { - const client = new assetserviceModule.v1.AssetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.asset.v1.CreateFeedRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.asset.v1.CreateFeedRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createFeed(request), expectedError); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new assetserviceModule.v1.AssetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + }); + + describe('batchGetAssetsHistory', () => { + it('invokes batchGetAssetsHistory without error', async () => { + const client = new assetserviceModule.v1.AssetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.asset.v1.BatchGetAssetsHistoryRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.asset.v1.BatchGetAssetsHistoryRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.asset.v1.BatchGetAssetsHistoryResponse(), + ); + client.innerApiCalls.batchGetAssetsHistory = + stubSimpleCall(expectedResponse); + const [response] = await client.batchGetAssetsHistory(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.batchGetAssetsHistory as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.batchGetAssetsHistory as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('getFeed', () => { - it('invokes getFeed without error', async () => { - const client = new assetserviceModule.v1.AssetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.asset.v1.GetFeedRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.asset.v1.GetFeedRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.asset.v1.Feed() - ); - client.innerApiCalls.getFeed = stubSimpleCall(expectedResponse); - const [response] = await client.getFeed(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getFeed as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getFeed as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes batchGetAssetsHistory without error using callback', async () => { + const client = new assetserviceModule.v1.AssetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.asset.v1.BatchGetAssetsHistoryRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.asset.v1.BatchGetAssetsHistoryRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.asset.v1.BatchGetAssetsHistoryResponse(), + ); + client.innerApiCalls.batchGetAssetsHistory = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.batchGetAssetsHistory( + request, + ( + err?: Error | null, + result?: protos.google.cloud.asset.v1.IBatchGetAssetsHistoryResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.batchGetAssetsHistory as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.batchGetAssetsHistory as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getFeed without error using callback', async () => { - const client = new assetserviceModule.v1.AssetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.asset.v1.GetFeedRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.asset.v1.GetFeedRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.asset.v1.Feed() - ); - client.innerApiCalls.getFeed = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getFeed( - request, - (err?: Error|null, result?: protos.google.cloud.asset.v1.IFeed|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getFeed as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getFeed as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes batchGetAssetsHistory with error', async () => { + const client = new assetserviceModule.v1.AssetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.asset.v1.BatchGetAssetsHistoryRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.asset.v1.BatchGetAssetsHistoryRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.batchGetAssetsHistory = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.batchGetAssetsHistory(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.batchGetAssetsHistory as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.batchGetAssetsHistory as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getFeed with error', async () => { - const client = new assetserviceModule.v1.AssetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.asset.v1.GetFeedRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.asset.v1.GetFeedRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getFeed = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getFeed(request), expectedError); - const actualRequest = (client.innerApiCalls.getFeed as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getFeed as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes batchGetAssetsHistory with closed client', async () => { + const client = new assetserviceModule.v1.AssetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.asset.v1.BatchGetAssetsHistoryRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.asset.v1.BatchGetAssetsHistoryRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.batchGetAssetsHistory(request), + expectedError, + ); + }); + }); + + describe('createFeed', () => { + it('invokes createFeed without error', async () => { + const client = new assetserviceModule.v1.AssetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.asset.v1.CreateFeedRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.asset.v1.CreateFeedRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.asset.v1.Feed(), + ); + client.innerApiCalls.createFeed = stubSimpleCall(expectedResponse); + const [response] = await client.createFeed(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createFeed as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createFeed as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getFeed with closed client', async () => { - const client = new assetserviceModule.v1.AssetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.asset.v1.GetFeedRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.asset.v1.GetFeedRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getFeed(request), expectedError); - }); + it('invokes createFeed without error using callback', async () => { + const client = new assetserviceModule.v1.AssetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.asset.v1.CreateFeedRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.asset.v1.CreateFeedRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.asset.v1.Feed(), + ); + client.innerApiCalls.createFeed = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createFeed( + request, + ( + err?: Error | null, + result?: protos.google.cloud.asset.v1.IFeed | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createFeed as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createFeed as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('listFeeds', () => { - it('invokes listFeeds without error', async () => { - const client = new assetserviceModule.v1.AssetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.asset.v1.ListFeedsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.asset.v1.ListFeedsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.asset.v1.ListFeedsResponse() - ); - client.innerApiCalls.listFeeds = stubSimpleCall(expectedResponse); - const [response] = await client.listFeeds(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listFeeds as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listFeeds as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createFeed with error', async () => { + const client = new assetserviceModule.v1.AssetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.asset.v1.CreateFeedRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.asset.v1.CreateFeedRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createFeed = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.createFeed(request), expectedError); + const actualRequest = ( + client.innerApiCalls.createFeed as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createFeed as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listFeeds without error using callback', async () => { - const client = new assetserviceModule.v1.AssetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.asset.v1.ListFeedsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.asset.v1.ListFeedsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.asset.v1.ListFeedsResponse() - ); - client.innerApiCalls.listFeeds = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listFeeds( - request, - (err?: Error|null, result?: protos.google.cloud.asset.v1.IListFeedsResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listFeeds as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listFeeds as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createFeed with closed client', async () => { + const client = new assetserviceModule.v1.AssetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.asset.v1.CreateFeedRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.asset.v1.CreateFeedRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.createFeed(request), expectedError); + }); + }); + + describe('getFeed', () => { + it('invokes getFeed without error', async () => { + const client = new assetserviceModule.v1.AssetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.asset.v1.GetFeedRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.asset.v1.GetFeedRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.asset.v1.Feed(), + ); + client.innerApiCalls.getFeed = stubSimpleCall(expectedResponse); + const [response] = await client.getFeed(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.getFeed as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getFeed as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listFeeds with error', async () => { - const client = new assetserviceModule.v1.AssetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.asset.v1.ListFeedsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.asset.v1.ListFeedsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listFeeds = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listFeeds(request), expectedError); - const actualRequest = (client.innerApiCalls.listFeeds as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listFeeds as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getFeed without error using callback', async () => { + const client = new assetserviceModule.v1.AssetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.asset.v1.GetFeedRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.asset.v1.GetFeedRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.asset.v1.Feed(), + ); + client.innerApiCalls.getFeed = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getFeed( + request, + ( + err?: Error | null, + result?: protos.google.cloud.asset.v1.IFeed | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.getFeed as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getFeed as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listFeeds with closed client', async () => { - const client = new assetserviceModule.v1.AssetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.asset.v1.ListFeedsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.asset.v1.ListFeedsRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.listFeeds(request), expectedError); - }); + it('invokes getFeed with error', async () => { + const client = new assetserviceModule.v1.AssetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.asset.v1.GetFeedRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.asset.v1.GetFeedRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getFeed = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.getFeed(request), expectedError); + const actualRequest = (client.innerApiCalls.getFeed as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getFeed as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('updateFeed', () => { - it('invokes updateFeed without error', async () => { - const client = new assetserviceModule.v1.AssetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.asset.v1.UpdateFeedRequest() - ); - request.feed ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.asset.v1.UpdateFeedRequest', ['feed', 'name']); - request.feed.name = defaultValue1; - const expectedHeaderRequestParams = `feed.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.asset.v1.Feed() - ); - client.innerApiCalls.updateFeed = stubSimpleCall(expectedResponse); - const [response] = await client.updateFeed(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateFeed as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateFeed as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getFeed with closed client', async () => { + const client = new assetserviceModule.v1.AssetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.asset.v1.GetFeedRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.asset.v1.GetFeedRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getFeed(request), expectedError); + }); + }); + + describe('listFeeds', () => { + it('invokes listFeeds without error', async () => { + const client = new assetserviceModule.v1.AssetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.asset.v1.ListFeedsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.asset.v1.ListFeedsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.asset.v1.ListFeedsResponse(), + ); + client.innerApiCalls.listFeeds = stubSimpleCall(expectedResponse); + const [response] = await client.listFeeds(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listFeeds as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listFeeds as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateFeed without error using callback', async () => { - const client = new assetserviceModule.v1.AssetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.asset.v1.UpdateFeedRequest() - ); - request.feed ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.asset.v1.UpdateFeedRequest', ['feed', 'name']); - request.feed.name = defaultValue1; - const expectedHeaderRequestParams = `feed.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.asset.v1.Feed() - ); - client.innerApiCalls.updateFeed = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateFeed( - request, - (err?: Error|null, result?: protos.google.cloud.asset.v1.IFeed|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateFeed as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateFeed as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listFeeds without error using callback', async () => { + const client = new assetserviceModule.v1.AssetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.asset.v1.ListFeedsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.asset.v1.ListFeedsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.asset.v1.ListFeedsResponse(), + ); + client.innerApiCalls.listFeeds = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listFeeds( + request, + ( + err?: Error | null, + result?: protos.google.cloud.asset.v1.IListFeedsResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listFeeds as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listFeeds as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateFeed with error', async () => { - const client = new assetserviceModule.v1.AssetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.asset.v1.UpdateFeedRequest() - ); - request.feed ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.asset.v1.UpdateFeedRequest', ['feed', 'name']); - request.feed.name = defaultValue1; - const expectedHeaderRequestParams = `feed.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateFeed = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateFeed(request), expectedError); - const actualRequest = (client.innerApiCalls.updateFeed as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateFeed as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listFeeds with error', async () => { + const client = new assetserviceModule.v1.AssetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.asset.v1.ListFeedsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.asset.v1.ListFeedsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listFeeds = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.listFeeds(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listFeeds as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listFeeds as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateFeed with closed client', async () => { - const client = new assetserviceModule.v1.AssetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.asset.v1.UpdateFeedRequest() - ); - request.feed ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.asset.v1.UpdateFeedRequest', ['feed', 'name']); - request.feed.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateFeed(request), expectedError); - }); + it('invokes listFeeds with closed client', async () => { + const client = new assetserviceModule.v1.AssetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.asset.v1.ListFeedsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.asset.v1.ListFeedsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.listFeeds(request), expectedError); + }); + }); + + describe('updateFeed', () => { + it('invokes updateFeed without error', async () => { + const client = new assetserviceModule.v1.AssetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.asset.v1.UpdateFeedRequest(), + ); + request.feed ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.asset.v1.UpdateFeedRequest', + ['feed', 'name'], + ); + request.feed.name = defaultValue1; + const expectedHeaderRequestParams = `feed.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.asset.v1.Feed(), + ); + client.innerApiCalls.updateFeed = stubSimpleCall(expectedResponse); + const [response] = await client.updateFeed(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateFeed as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateFeed as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('deleteFeed', () => { - it('invokes deleteFeed without error', async () => { - const client = new assetserviceModule.v1.AssetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.asset.v1.DeleteFeedRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.asset.v1.DeleteFeedRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteFeed = stubSimpleCall(expectedResponse); - const [response] = await client.deleteFeed(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteFeed as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteFeed as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateFeed without error using callback', async () => { + const client = new assetserviceModule.v1.AssetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.asset.v1.UpdateFeedRequest(), + ); + request.feed ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.asset.v1.UpdateFeedRequest', + ['feed', 'name'], + ); + request.feed.name = defaultValue1; + const expectedHeaderRequestParams = `feed.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.asset.v1.Feed(), + ); + client.innerApiCalls.updateFeed = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateFeed( + request, + ( + err?: Error | null, + result?: protos.google.cloud.asset.v1.IFeed | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateFeed as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateFeed as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteFeed without error using callback', async () => { - const client = new assetserviceModule.v1.AssetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.asset.v1.DeleteFeedRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.asset.v1.DeleteFeedRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteFeed = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteFeed( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteFeed as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteFeed as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateFeed with error', async () => { + const client = new assetserviceModule.v1.AssetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.asset.v1.UpdateFeedRequest(), + ); + request.feed ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.asset.v1.UpdateFeedRequest', + ['feed', 'name'], + ); + request.feed.name = defaultValue1; + const expectedHeaderRequestParams = `feed.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateFeed = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.updateFeed(request), expectedError); + const actualRequest = ( + client.innerApiCalls.updateFeed as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateFeed as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteFeed with error', async () => { - const client = new assetserviceModule.v1.AssetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.asset.v1.DeleteFeedRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.asset.v1.DeleteFeedRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteFeed = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteFeed(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteFeed as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteFeed as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateFeed with closed client', async () => { + const client = new assetserviceModule.v1.AssetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.asset.v1.UpdateFeedRequest(), + ); + request.feed ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.asset.v1.UpdateFeedRequest', + ['feed', 'name'], + ); + request.feed.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.updateFeed(request), expectedError); + }); + }); + + describe('deleteFeed', () => { + it('invokes deleteFeed without error', async () => { + const client = new assetserviceModule.v1.AssetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.asset.v1.DeleteFeedRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.asset.v1.DeleteFeedRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteFeed = stubSimpleCall(expectedResponse); + const [response] = await client.deleteFeed(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteFeed as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteFeed as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteFeed with closed client', async () => { - const client = new assetserviceModule.v1.AssetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.asset.v1.DeleteFeedRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.asset.v1.DeleteFeedRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteFeed(request), expectedError); - }); + it('invokes deleteFeed without error using callback', async () => { + const client = new assetserviceModule.v1.AssetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.asset.v1.DeleteFeedRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.asset.v1.DeleteFeedRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteFeed = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteFeed( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteFeed as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteFeed as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('exportAssets', () => { - it('invokes exportAssets without error', async () => { - const client = new assetserviceModule.v1.AssetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.asset.v1.ExportAssetsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.asset.v1.ExportAssetsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.exportAssets = stubLongRunningCall(expectedResponse); - const [operation] = await client.exportAssets(request); - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.exportAssets as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.exportAssets as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteFeed with error', async () => { + const client = new assetserviceModule.v1.AssetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.asset.v1.DeleteFeedRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.asset.v1.DeleteFeedRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteFeed = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.deleteFeed(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteFeed as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteFeed as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes exportAssets without error using callback', async () => { - const client = new assetserviceModule.v1.AssetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.asset.v1.ExportAssetsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.asset.v1.ExportAssetsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.exportAssets = stubLongRunningCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.exportAssets( - request, - (err?: Error|null, - result?: LROperation|null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const operation = await promise as LROperation; - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.exportAssets as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.exportAssets as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteFeed with closed client', async () => { + const client = new assetserviceModule.v1.AssetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.asset.v1.DeleteFeedRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.asset.v1.DeleteFeedRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.deleteFeed(request), expectedError); + }); + }); + + describe('exportAssets', () => { + it('invokes exportAssets without error', async () => { + const client = new assetserviceModule.v1.AssetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.asset.v1.ExportAssetsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.asset.v1.ExportAssetsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.exportAssets = stubLongRunningCall(expectedResponse); + const [operation] = await client.exportAssets(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.exportAssets as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.exportAssets as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes exportAssets with call error', async () => { - const client = new assetserviceModule.v1.AssetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.asset.v1.ExportAssetsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.asset.v1.ExportAssetsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.exportAssets = stubLongRunningCall(undefined, expectedError); - await assert.rejects(client.exportAssets(request), expectedError); - const actualRequest = (client.innerApiCalls.exportAssets as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.exportAssets as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes exportAssets without error using callback', async () => { + const client = new assetserviceModule.v1.AssetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.asset.v1.ExportAssetsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.asset.v1.ExportAssetsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.exportAssets = + stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.exportAssets( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.cloud.asset.v1.IExportAssetsResponse, + protos.google.cloud.asset.v1.IExportAssetsRequest + > | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const operation = (await promise) as LROperation< + protos.google.cloud.asset.v1.IExportAssetsResponse, + protos.google.cloud.asset.v1.IExportAssetsRequest + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.exportAssets as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.exportAssets as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes exportAssets with LRO error', async () => { - const client = new assetserviceModule.v1.AssetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.asset.v1.ExportAssetsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.asset.v1.ExportAssetsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.exportAssets = stubLongRunningCall(undefined, undefined, expectedError); - const [operation] = await client.exportAssets(request); - await assert.rejects(operation.promise(), expectedError); - const actualRequest = (client.innerApiCalls.exportAssets as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.exportAssets as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes exportAssets with call error', async () => { + const client = new assetserviceModule.v1.AssetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.asset.v1.ExportAssetsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.asset.v1.ExportAssetsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.exportAssets = stubLongRunningCall( + undefined, + expectedError, + ); + await assert.rejects(client.exportAssets(request), expectedError); + const actualRequest = ( + client.innerApiCalls.exportAssets as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.exportAssets as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkExportAssetsProgress without error', async () => { - const client = new assetserviceModule.v1.AssetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedResponse = generateSampleMessage( - new operationsProtos.google.longrunning.Operation() - ); - expectedResponse.name = 'test'; - expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; - expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')} - - client.operationsClient.getOperation = stubSimpleCall(expectedResponse); - const decodedOperation = await client.checkExportAssetsProgress(expectedResponse.name); - assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); - assert(decodedOperation.metadata); - assert((client.operationsClient.getOperation as SinonStub).getCall(0)); - }); + it('invokes exportAssets with LRO error', async () => { + const client = new assetserviceModule.v1.AssetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.asset.v1.ExportAssetsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.asset.v1.ExportAssetsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.exportAssets = stubLongRunningCall( + undefined, + undefined, + expectedError, + ); + const [operation] = await client.exportAssets(request); + await assert.rejects(operation.promise(), expectedError); + const actualRequest = ( + client.innerApiCalls.exportAssets as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.exportAssets as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkExportAssetsProgress with error', async () => { - const client = new assetserviceModule.v1.AssetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedError = new Error('expected'); - - client.operationsClient.getOperation = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.checkExportAssetsProgress(''), expectedError); - assert((client.operationsClient.getOperation as SinonStub) - .getCall(0)); - }); + it('invokes checkExportAssetsProgress without error', async () => { + const client = new assetserviceModule.v1.AssetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation(), + ); + expectedResponse.name = 'test'; + expectedResponse.response = { type_url: 'url', value: Buffer.from('') }; + expectedResponse.metadata = { type_url: 'url', value: Buffer.from('') }; + + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const decodedOperation = await client.checkExportAssetsProgress( + expectedResponse.name, + ); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); }); - describe('Path templates', () => { - - describe('folderFeed', async () => { - const fakePath = "/rendered/path/folderFeed"; - const expectedParameters = { - folder: "folderValue", - feed: "feedValue", - }; - const client = new assetserviceModule.v1.AssetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.folderFeedPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderFeedPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderFeedPath', () => { - const result = client.folderFeedPath("folderValue", "feedValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderFeedPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderFeedName', () => { - const result = client.matchFolderFromFolderFeedName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderFeedPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchFeedFromFolderFeedName', () => { - const result = client.matchFeedFromFolderFeedName(fakePath); - assert.strictEqual(result, "feedValue"); - assert((client.pathTemplates.folderFeedPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('invokes checkExportAssetsProgress with error', async () => { + const client = new assetserviceModule.v1.AssetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const expectedError = new Error('expected'); + + client.operationsClient.getOperation = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.checkExportAssetsProgress(''), expectedError); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + }); + + describe('Path templates', () => { + describe('folderFeed', async () => { + const fakePath = '/rendered/path/folderFeed'; + const expectedParameters = { + folder: 'folderValue', + feed: 'feedValue', + }; + const client = new assetserviceModule.v1.AssetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.folderFeedPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderFeedPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderFeedPath', () => { + const result = client.folderFeedPath('folderValue', 'feedValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.folderFeedPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderFeedName', () => { + const result = client.matchFolderFromFolderFeedName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + (client.pathTemplates.folderFeedPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchFeedFromFolderFeedName', () => { + const result = client.matchFeedFromFolderFeedName(fakePath); + assert.strictEqual(result, 'feedValue'); + assert( + (client.pathTemplates.folderFeedPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('organizationFeed', async () => { - const fakePath = "/rendered/path/organizationFeed"; - const expectedParameters = { - organization: "organizationValue", - feed: "feedValue", - }; - const client = new assetserviceModule.v1.AssetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.organizationFeedPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationFeedPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationFeedPath', () => { - const result = client.organizationFeedPath("organizationValue", "feedValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationFeedPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationFeedName', () => { - const result = client.matchOrganizationFromOrganizationFeedName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationFeedPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchFeedFromOrganizationFeedName', () => { - const result = client.matchFeedFromOrganizationFeedName(fakePath); - assert.strictEqual(result, "feedValue"); - assert((client.pathTemplates.organizationFeedPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('organizationFeed', async () => { + const fakePath = '/rendered/path/organizationFeed'; + const expectedParameters = { + organization: 'organizationValue', + feed: 'feedValue', + }; + const client = new assetserviceModule.v1.AssetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.organizationFeedPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.organizationFeedPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('organizationFeedPath', () => { + const result = client.organizationFeedPath( + 'organizationValue', + 'feedValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationFeedPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationFeedName', () => { + const result = + client.matchOrganizationFromOrganizationFeedName(fakePath); + assert.strictEqual(result, 'organizationValue'); + assert( + (client.pathTemplates.organizationFeedPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchFeedFromOrganizationFeedName', () => { + const result = client.matchFeedFromOrganizationFeedName(fakePath); + assert.strictEqual(result, 'feedValue'); + assert( + (client.pathTemplates.organizationFeedPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectFeed', async () => { - const fakePath = "/rendered/path/projectFeed"; - const expectedParameters = { - project: "projectValue", - feed: "feedValue", - }; - const client = new assetserviceModule.v1.AssetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.projectFeedPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectFeedPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectFeedPath', () => { - const result = client.projectFeedPath("projectValue", "feedValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectFeedPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectFeedName', () => { - const result = client.matchProjectFromProjectFeedName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectFeedPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchFeedFromProjectFeedName', () => { - const result = client.matchFeedFromProjectFeedName(fakePath); - assert.strictEqual(result, "feedValue"); - assert((client.pathTemplates.projectFeedPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectFeed', async () => { + const fakePath = '/rendered/path/projectFeed'; + const expectedParameters = { + project: 'projectValue', + feed: 'feedValue', + }; + const client = new assetserviceModule.v1.AssetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.projectFeedPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectFeedPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectFeedPath', () => { + const result = client.projectFeedPath('projectValue', 'feedValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.projectFeedPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectFeedName', () => { + const result = client.matchProjectFromProjectFeedName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.projectFeedPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchFeedFromProjectFeedName', () => { + const result = client.matchFeedFromProjectFeedName(fakePath); + assert.strictEqual(result, 'feedValue'); + assert( + (client.pathTemplates.projectFeedPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/core/generator/gapic-generator-typescript/baselines/bigquery-storage-esm/esm/src/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/bigquery-storage-esm/esm/src/index.ts.baseline index 7d8a13d909b7..706ba13757f2 100644 --- a/core/generator/gapic-generator-typescript/baselines/bigquery-storage-esm/esm/src/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/bigquery-storage-esm/esm/src/index.ts.baseline @@ -19,8 +19,8 @@ import * as v1beta1 from './v1beta1/index.js'; const BigQueryStorageClient = v1beta1.BigQueryStorageClient; type BigQueryStorageClient = v1beta1.BigQueryStorageClient; -export {v1beta1, BigQueryStorageClient}; -export default {v1beta1, BigQueryStorageClient}; +export { v1beta1, BigQueryStorageClient }; +export default { v1beta1, BigQueryStorageClient }; // @ts-ignore import * as protos from '../../protos/protos.js'; -export {protos} +export { protos }; diff --git a/core/generator/gapic-generator-typescript/baselines/bigquery-storage-esm/esm/src/v1beta1/big_query_storage_client.ts.baseline b/core/generator/gapic-generator-typescript/baselines/bigquery-storage-esm/esm/src/v1beta1/big_query_storage_client.ts.baseline index 1cad4002c11d..9df4e0434984 100644 --- a/core/generator/gapic-generator-typescript/baselines/bigquery-storage-esm/esm/src/v1beta1/big_query_storage_client.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/bigquery-storage-esm/esm/src/v1beta1/big_query_storage_client.ts.baseline @@ -18,15 +18,20 @@ /* global window */ import * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions} from 'google-gax'; -import {PassThrough} from 'stream'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, +} from 'google-gax'; +import { PassThrough } from 'stream'; // @ts-ignore import type * as protos from '../../../protos/protos.js'; import * as big_query_storage_client_config from './big_query_storage_client_config.json'; import fs from 'fs'; import path from 'path'; -import {fileURLToPath} from 'url'; -import {getJSON} from '../json-helper.cjs'; +import { fileURLToPath } from 'url'; +import { getJSON } from '../json-helper.cjs'; // @ts-ignore const dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -36,15 +41,15 @@ const dirname = path.dirname(fileURLToPath(import.meta.url)); * This file defines retry strategy and timeouts for all API methods in this library. */ const gapicConfig = getJSON( - path.join(dirname, 'big_query_storage_client_config.json') + path.join(dirname, 'big_query_storage_client_config.json'), ); const jsonProtos = getJSON( - path.join(dirname, '..', '..', '..', 'protos/protos.json') + path.join(dirname, '..', '..', '..', 'protos/protos.json'), ); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; const version = getJSON( - path.join(dirname, '..', '..', '..', '..', 'package.json') + path.join(dirname, '..', '..', '..', '..', 'package.json'), ).version; /** @@ -61,7 +66,7 @@ export class BigQueryStorageClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('storage'); @@ -73,9 +78,9 @@ export class BigQueryStorageClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; - bigQueryStorageStub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; + bigQueryStorageStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of BigQueryStorageClient. @@ -117,21 +122,42 @@ export class BigQueryStorageClient { * const client = new BigQueryStorageClient({fallback: 'rest'}, gax); * ``` */ - constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { // Ensure that options include all the required fields. const staticMembers = this.constructor as typeof BigQueryStorageClient; - if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { - throw new Error('Please set either universe_domain or universeDomain, but not both.'); + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); } - const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; - this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; this._servicePath = 'bigquerystorage.' + this._universeDomain; - const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; - const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. if (servicePath !== this._servicePath && !('scopes' in opts)) { @@ -153,7 +179,7 @@ export class BigQueryStorageClient { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; @@ -170,10 +196,7 @@ export class BigQueryStorageClient { const isEsm = true; const isEsmString = isEsm ? '-esm' : '-cjs'; // Determine the client header string. - const clientHeader = [ - `gax/${this._gaxModule.version}`, - `gapic/${version}`, - ]; + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/{process.versions.node}${isEsmString}`); } else { @@ -181,7 +204,7 @@ export class BigQueryStorageClient { } if (!opts.fallback) { clientHeader.push(`grpc/${this._gaxGrpc.grpcVersion}`); - } else if (opts.fallback === 'rest' ) { + } else if (opts.fallback === 'rest') { clientHeader.push(`rest/${this._gaxGrpc.grpcVersion}`); } if (opts.libName && opts.libVersion) { @@ -189,30 +212,39 @@ export class BigQueryStorageClient { } // Load the applicable protos. - this._protos = this._gaxGrpc.loadProtoJSON(jsonProtos as gax.protobuf.INamespace); + this._protos = this._gaxGrpc.loadProtoJSON( + jsonProtos as gax.protobuf.INamespace, + ); // This API contains "path templates"; forward-slash-separated // identifiers to uniquely identify resources within the API. // Create useful helper objects for these. this.pathTemplates = { readSessionPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/sessions/{session}' + 'projects/{project}/locations/{location}/sessions/{session}', ), streamPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/streams/{stream}' + 'projects/{project}/locations/{location}/streams/{stream}', ), }; // Some of the methods on this service provide streaming responses. // Provide descriptors for these. this.descriptors.stream = { - readRows: new this._gaxModule.StreamDescriptor(this._gaxModule.StreamType.SERVER_STREAMING, !!opts.fallback, !!opts.gaxServerStreamingRetries) + readRows: new this._gaxModule.StreamDescriptor( + this._gaxModule.StreamType.SERVER_STREAMING, + !!opts.fallback, + !!opts.gaxServerStreamingRetries, + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.cloud.bigquery.storage.v1beta1.BigQueryStorage', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.cloud.bigquery.storage.v1beta1.BigQueryStorage', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + { 'x-goog-api-client': clientHeader.join(' ') }, + ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -243,44 +275,59 @@ export class BigQueryStorageClient { // Put together the "service stub" for // google.cloud.bigquery.storage.v1beta1.BigQueryStorage. this.bigQueryStorageStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.cloud.bigquery.storage.v1beta1.BigQueryStorage') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any - (this._protos as any).google.cloud.bigquery.storage.v1beta1.BigQueryStorage, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.cloud.bigquery.storage.v1beta1.BigQueryStorage', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any + (this._protos as any).google.cloud.bigquery.storage.v1beta1 + .BigQueryStorage, + this._opts, + this._providedCustomServicePath, + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const bigQueryStorageStubMethods = - ['createReadSession', 'readRows', 'batchCreateReadSessionStreams', 'finalizeStream', 'splitReadStream']; + const bigQueryStorageStubMethods = [ + 'createReadSession', + 'readRows', + 'batchCreateReadSessionStreams', + 'finalizeStream', + 'splitReadStream', + ]; for (const methodName of bigQueryStorageStubMethods) { const callPromise = this.bigQueryStorageStub.then( - stub => (...args: Array<{}>) => { - if (this._terminated) { - if (methodName in this.descriptors.stream) { - const stream = new PassThrough({objectMode: true}); - setImmediate(() => { - stream.emit('error', new this._gaxModule.GoogleError('The client has already been closed.')); - }); - return stream; + (stub) => + (...args: Array<{}>) => { + if (this._terminated) { + if (methodName in this.descriptors.stream) { + const stream = new PassThrough({ objectMode: true }); + setImmediate(() => { + stream.emit( + 'error', + new this._gaxModule.GoogleError( + 'The client has already been closed.', + ), + ); + }); + return stream; + } + return Promise.reject('The client has already been closed.'); } - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error|null|undefined) => () => { + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { throw err; - }); + }, + ); - const descriptor = - this.descriptors.stream[methodName] || - undefined; + const descriptor = this.descriptors.stream[methodName] || undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -295,8 +342,14 @@ export class BigQueryStorageClient { * @returns {string} The DNS address for this service. */ static get servicePath() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'bigquerystorage.googleapis.com'; } @@ -308,8 +361,14 @@ export class BigQueryStorageClient { * @returns {string} The DNS address for this service. */ static get apiEndpoint() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'bigquerystorage.googleapis.com'; } @@ -343,7 +402,7 @@ export class BigQueryStorageClient { return [ 'https://www.googleapis.com/auth/bigquery', 'https://www.googleapis.com/auth/bigquery.readonly', - 'https://www.googleapis.com/auth/cloud-platform' + 'https://www.googleapis.com/auth/cloud-platform', ]; } @@ -353,8 +412,9 @@ export class BigQueryStorageClient { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId(callback?: Callback): - Promise|void { + getProjectId( + callback?: Callback, + ): Promise | void { if (callback) { this.auth.getProjectId(callback); return; @@ -365,492 +425,695 @@ export class BigQueryStorageClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Creates a new read session. A read session divides the contents of a - * BigQuery table into one or more streams, which can then be used to read - * data from the table. The read session also specifies properties of the - * data to be read, such as a list of columns or a push-down filter describing - * the rows to be returned. - * - * A particular row can be read by at most one stream. When the caller has - * reached the end of each stream in the session, then all the data in the - * table has been read. - * - * Read sessions automatically expire 24 hours after they are created and do - * not require manual clean-up by the caller. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.cloud.bigquery.storage.v1beta1.TableReference} request.tableReference - * Required. Reference to the table to read. - * @param {string} request.parent - * Required. String of the form `projects/{project_id}` indicating the - * project this ReadSession is associated with. This is the project that will - * be billed for usage. - * @param {google.cloud.bigquery.storage.v1beta1.TableModifiers} request.tableModifiers - * Any modifiers to the Table (e.g. snapshot timestamp). - * @param {number} request.requestedStreams - * Initial number of streams. If unset or 0, we will - * provide a value of streams so as to produce reasonable throughput. Must be - * non-negative. The number of streams may be lower than the requested number, - * depending on the amount parallelism that is reasonable for the table and - * the maximum amount of parallelism allowed by the system. - * - * Streams must be read starting from offset 0. - * @param {google.cloud.bigquery.storage.v1beta1.TableReadOptions} request.readOptions - * Read options for this session (e.g. column selection, filters). - * @param {google.cloud.bigquery.storage.v1beta1.DataFormat} request.format - * Data output format. Currently default to Avro. - * @param {google.cloud.bigquery.storage.v1beta1.ShardingStrategy} request.shardingStrategy - * The strategy to use for distributing data among multiple streams. Currently - * defaults to liquid sharding. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.bigquery.storage.v1beta1.ReadSession|ReadSession}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/big_query_storage.create_read_session.js - * region_tag:bigquerystorage_v1beta1_generated_BigQueryStorage_CreateReadSession_async - */ + /** + * Creates a new read session. A read session divides the contents of a + * BigQuery table into one or more streams, which can then be used to read + * data from the table. The read session also specifies properties of the + * data to be read, such as a list of columns or a push-down filter describing + * the rows to be returned. + * + * A particular row can be read by at most one stream. When the caller has + * reached the end of each stream in the session, then all the data in the + * table has been read. + * + * Read sessions automatically expire 24 hours after they are created and do + * not require manual clean-up by the caller. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.cloud.bigquery.storage.v1beta1.TableReference} request.tableReference + * Required. Reference to the table to read. + * @param {string} request.parent + * Required. String of the form `projects/{project_id}` indicating the + * project this ReadSession is associated with. This is the project that will + * be billed for usage. + * @param {google.cloud.bigquery.storage.v1beta1.TableModifiers} request.tableModifiers + * Any modifiers to the Table (e.g. snapshot timestamp). + * @param {number} request.requestedStreams + * Initial number of streams. If unset or 0, we will + * provide a value of streams so as to produce reasonable throughput. Must be + * non-negative. The number of streams may be lower than the requested number, + * depending on the amount parallelism that is reasonable for the table and + * the maximum amount of parallelism allowed by the system. + * + * Streams must be read starting from offset 0. + * @param {google.cloud.bigquery.storage.v1beta1.TableReadOptions} request.readOptions + * Read options for this session (e.g. column selection, filters). + * @param {google.cloud.bigquery.storage.v1beta1.DataFormat} request.format + * Data output format. Currently default to Avro. + * @param {google.cloud.bigquery.storage.v1beta1.ShardingStrategy} request.shardingStrategy + * The strategy to use for distributing data among multiple streams. Currently + * defaults to liquid sharding. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.bigquery.storage.v1beta1.ReadSession|ReadSession}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/big_query_storage.create_read_session.js + * region_tag:bigquerystorage_v1beta1_generated_BigQueryStorage_CreateReadSession_async + */ createReadSession( - request?: protos.google.cloud.bigquery.storage.v1beta1.ICreateReadSessionRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.bigquery.storage.v1beta1.IReadSession, - protos.google.cloud.bigquery.storage.v1beta1.ICreateReadSessionRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.bigquery.storage.v1beta1.ICreateReadSessionRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.bigquery.storage.v1beta1.IReadSession, + ( + | protos.google.cloud.bigquery.storage.v1beta1.ICreateReadSessionRequest + | undefined + ), + {} | undefined, + ] + >; createReadSession( - request: protos.google.cloud.bigquery.storage.v1beta1.ICreateReadSessionRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.bigquery.storage.v1beta1.IReadSession, - protos.google.cloud.bigquery.storage.v1beta1.ICreateReadSessionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.bigquery.storage.v1beta1.ICreateReadSessionRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.bigquery.storage.v1beta1.IReadSession, + | protos.google.cloud.bigquery.storage.v1beta1.ICreateReadSessionRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createReadSession( - request: protos.google.cloud.bigquery.storage.v1beta1.ICreateReadSessionRequest, - callback: Callback< - protos.google.cloud.bigquery.storage.v1beta1.IReadSession, - protos.google.cloud.bigquery.storage.v1beta1.ICreateReadSessionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.bigquery.storage.v1beta1.ICreateReadSessionRequest, + callback: Callback< + protos.google.cloud.bigquery.storage.v1beta1.IReadSession, + | protos.google.cloud.bigquery.storage.v1beta1.ICreateReadSessionRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createReadSession( - request?: protos.google.cloud.bigquery.storage.v1beta1.ICreateReadSessionRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.bigquery.storage.v1beta1.IReadSession, - protos.google.cloud.bigquery.storage.v1beta1.ICreateReadSessionRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.bigquery.storage.v1beta1.ICreateReadSessionRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.bigquery.storage.v1beta1.IReadSession, - protos.google.cloud.bigquery.storage.v1beta1.ICreateReadSessionRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.bigquery.storage.v1beta1.IReadSession, - protos.google.cloud.bigquery.storage.v1beta1.ICreateReadSessionRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.bigquery.storage.v1beta1.ICreateReadSessionRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.bigquery.storage.v1beta1.IReadSession, + | protos.google.cloud.bigquery.storage.v1beta1.ICreateReadSessionRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.bigquery.storage.v1beta1.IReadSession, + ( + | protos.google.cloud.bigquery.storage.v1beta1.ICreateReadSessionRequest + | undefined + ), + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'table_reference.project_id': request.tableReference!.projectId?.toString() ?? '', - 'table_reference.dataset_id': request.tableReference!.datasetId?.toString() ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'table_reference.project_id': + request.tableReference!.projectId?.toString() ?? '', + 'table_reference.dataset_id': + request.tableReference!.datasetId?.toString() ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('createReadSession request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.bigquery.storage.v1beta1.IReadSession, - protos.google.cloud.bigquery.storage.v1beta1.ICreateReadSessionRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.bigquery.storage.v1beta1.IReadSession, + | protos.google.cloud.bigquery.storage.v1beta1.ICreateReadSessionRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createReadSession response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.createReadSession(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.bigquery.storage.v1beta1.IReadSession, - protos.google.cloud.bigquery.storage.v1beta1.ICreateReadSessionRequest|undefined, {}|undefined - ]) => { - this._log.info('createReadSession response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createReadSession(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.bigquery.storage.v1beta1.IReadSession, + ( + | protos.google.cloud.bigquery.storage.v1beta1.ICreateReadSessionRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('createReadSession response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Creates additional streams for a ReadSession. This API can be used to - * dynamically adjust the parallelism of a batch processing task upwards by - * adding additional workers. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.cloud.bigquery.storage.v1beta1.ReadSession} request.session - * Required. Must be a non-expired session obtained from a call to - * CreateReadSession. Only the name field needs to be set. - * @param {number} request.requestedStreams - * Required. Number of new streams requested. Must be positive. - * Number of added streams may be less than this, see CreateReadSessionRequest - * for more information. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.bigquery.storage.v1beta1.BatchCreateReadSessionStreamsResponse|BatchCreateReadSessionStreamsResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/big_query_storage.batch_create_read_session_streams.js - * region_tag:bigquerystorage_v1beta1_generated_BigQueryStorage_BatchCreateReadSessionStreams_async - */ + /** + * Creates additional streams for a ReadSession. This API can be used to + * dynamically adjust the parallelism of a batch processing task upwards by + * adding additional workers. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.cloud.bigquery.storage.v1beta1.ReadSession} request.session + * Required. Must be a non-expired session obtained from a call to + * CreateReadSession. Only the name field needs to be set. + * @param {number} request.requestedStreams + * Required. Number of new streams requested. Must be positive. + * Number of added streams may be less than this, see CreateReadSessionRequest + * for more information. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.bigquery.storage.v1beta1.BatchCreateReadSessionStreamsResponse|BatchCreateReadSessionStreamsResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/big_query_storage.batch_create_read_session_streams.js + * region_tag:bigquerystorage_v1beta1_generated_BigQueryStorage_BatchCreateReadSessionStreams_async + */ batchCreateReadSessionStreams( - request?: protos.google.cloud.bigquery.storage.v1beta1.IBatchCreateReadSessionStreamsRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.bigquery.storage.v1beta1.IBatchCreateReadSessionStreamsResponse, - protos.google.cloud.bigquery.storage.v1beta1.IBatchCreateReadSessionStreamsRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.bigquery.storage.v1beta1.IBatchCreateReadSessionStreamsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.bigquery.storage.v1beta1.IBatchCreateReadSessionStreamsResponse, + ( + | protos.google.cloud.bigquery.storage.v1beta1.IBatchCreateReadSessionStreamsRequest + | undefined + ), + {} | undefined, + ] + >; batchCreateReadSessionStreams( - request: protos.google.cloud.bigquery.storage.v1beta1.IBatchCreateReadSessionStreamsRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.bigquery.storage.v1beta1.IBatchCreateReadSessionStreamsResponse, - protos.google.cloud.bigquery.storage.v1beta1.IBatchCreateReadSessionStreamsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.bigquery.storage.v1beta1.IBatchCreateReadSessionStreamsRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.bigquery.storage.v1beta1.IBatchCreateReadSessionStreamsResponse, + | protos.google.cloud.bigquery.storage.v1beta1.IBatchCreateReadSessionStreamsRequest + | null + | undefined, + {} | null | undefined + >, + ): void; batchCreateReadSessionStreams( - request: protos.google.cloud.bigquery.storage.v1beta1.IBatchCreateReadSessionStreamsRequest, - callback: Callback< - protos.google.cloud.bigquery.storage.v1beta1.IBatchCreateReadSessionStreamsResponse, - protos.google.cloud.bigquery.storage.v1beta1.IBatchCreateReadSessionStreamsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.bigquery.storage.v1beta1.IBatchCreateReadSessionStreamsRequest, + callback: Callback< + protos.google.cloud.bigquery.storage.v1beta1.IBatchCreateReadSessionStreamsResponse, + | protos.google.cloud.bigquery.storage.v1beta1.IBatchCreateReadSessionStreamsRequest + | null + | undefined, + {} | null | undefined + >, + ): void; batchCreateReadSessionStreams( - request?: protos.google.cloud.bigquery.storage.v1beta1.IBatchCreateReadSessionStreamsRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.bigquery.storage.v1beta1.IBatchCreateReadSessionStreamsResponse, - protos.google.cloud.bigquery.storage.v1beta1.IBatchCreateReadSessionStreamsRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.bigquery.storage.v1beta1.IBatchCreateReadSessionStreamsRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.bigquery.storage.v1beta1.IBatchCreateReadSessionStreamsResponse, - protos.google.cloud.bigquery.storage.v1beta1.IBatchCreateReadSessionStreamsRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.bigquery.storage.v1beta1.IBatchCreateReadSessionStreamsResponse, - protos.google.cloud.bigquery.storage.v1beta1.IBatchCreateReadSessionStreamsRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.bigquery.storage.v1beta1.IBatchCreateReadSessionStreamsRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.bigquery.storage.v1beta1.IBatchCreateReadSessionStreamsResponse, + | protos.google.cloud.bigquery.storage.v1beta1.IBatchCreateReadSessionStreamsRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.bigquery.storage.v1beta1.IBatchCreateReadSessionStreamsResponse, + ( + | protos.google.cloud.bigquery.storage.v1beta1.IBatchCreateReadSessionStreamsRequest + | undefined + ), + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'session.name': request.session!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'session.name': request.session!.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('batchCreateReadSessionStreams request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.bigquery.storage.v1beta1.IBatchCreateReadSessionStreamsResponse, - protos.google.cloud.bigquery.storage.v1beta1.IBatchCreateReadSessionStreamsRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.bigquery.storage.v1beta1.IBatchCreateReadSessionStreamsResponse, + | protos.google.cloud.bigquery.storage.v1beta1.IBatchCreateReadSessionStreamsRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('batchCreateReadSessionStreams response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.batchCreateReadSessionStreams(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.bigquery.storage.v1beta1.IBatchCreateReadSessionStreamsResponse, - protos.google.cloud.bigquery.storage.v1beta1.IBatchCreateReadSessionStreamsRequest|undefined, {}|undefined - ]) => { - this._log.info('batchCreateReadSessionStreams response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .batchCreateReadSessionStreams(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.bigquery.storage.v1beta1.IBatchCreateReadSessionStreamsResponse, + ( + | protos.google.cloud.bigquery.storage.v1beta1.IBatchCreateReadSessionStreamsRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('batchCreateReadSessionStreams response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Triggers the graceful termination of a single stream in a ReadSession. This - * API can be used to dynamically adjust the parallelism of a batch processing - * task downwards without losing data. - * - * This API does not delete the stream -- it remains visible in the - * ReadSession, and any data processed by the stream is not released to other - * streams. However, no additional data will be assigned to the stream once - * this call completes. Callers must continue reading data on the stream until - * the end of the stream is reached so that data which has already been - * assigned to the stream will be processed. - * - * This method will return an error if there are no other live streams - * in the Session, or if SplitReadStream() has been called on the given - * Stream. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.cloud.bigquery.storage.v1beta1.Stream} request.stream - * Stream to finalize. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/big_query_storage.finalize_stream.js - * region_tag:bigquerystorage_v1beta1_generated_BigQueryStorage_FinalizeStream_async - */ + /** + * Triggers the graceful termination of a single stream in a ReadSession. This + * API can be used to dynamically adjust the parallelism of a batch processing + * task downwards without losing data. + * + * This API does not delete the stream -- it remains visible in the + * ReadSession, and any data processed by the stream is not released to other + * streams. However, no additional data will be assigned to the stream once + * this call completes. Callers must continue reading data on the stream until + * the end of the stream is reached so that data which has already been + * assigned to the stream will be processed. + * + * This method will return an error if there are no other live streams + * in the Session, or if SplitReadStream() has been called on the given + * Stream. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.cloud.bigquery.storage.v1beta1.Stream} request.stream + * Stream to finalize. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/big_query_storage.finalize_stream.js + * region_tag:bigquerystorage_v1beta1_generated_BigQueryStorage_FinalizeStream_async + */ finalizeStream( - request?: protos.google.cloud.bigquery.storage.v1beta1.IFinalizeStreamRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.cloud.bigquery.storage.v1beta1.IFinalizeStreamRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.bigquery.storage.v1beta1.IFinalizeStreamRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.cloud.bigquery.storage.v1beta1.IFinalizeStreamRequest + | undefined + ), + {} | undefined, + ] + >; finalizeStream( - request: protos.google.cloud.bigquery.storage.v1beta1.IFinalizeStreamRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.cloud.bigquery.storage.v1beta1.IFinalizeStreamRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.bigquery.storage.v1beta1.IFinalizeStreamRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.cloud.bigquery.storage.v1beta1.IFinalizeStreamRequest + | null + | undefined, + {} | null | undefined + >, + ): void; finalizeStream( - request: protos.google.cloud.bigquery.storage.v1beta1.IFinalizeStreamRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.cloud.bigquery.storage.v1beta1.IFinalizeStreamRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.bigquery.storage.v1beta1.IFinalizeStreamRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.cloud.bigquery.storage.v1beta1.IFinalizeStreamRequest + | null + | undefined, + {} | null | undefined + >, + ): void; finalizeStream( - request?: protos.google.cloud.bigquery.storage.v1beta1.IFinalizeStreamRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.protobuf.IEmpty, - protos.google.cloud.bigquery.storage.v1beta1.IFinalizeStreamRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.bigquery.storage.v1beta1.IFinalizeStreamRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.cloud.bigquery.storage.v1beta1.IFinalizeStreamRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.cloud.bigquery.storage.v1beta1.IFinalizeStreamRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.bigquery.storage.v1beta1.IFinalizeStreamRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + | protos.google.cloud.bigquery.storage.v1beta1.IFinalizeStreamRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.cloud.bigquery.storage.v1beta1.IFinalizeStreamRequest + | undefined + ), + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'stream.name': request.stream!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'stream.name': request.stream!.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('finalizeStream request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.cloud.bigquery.storage.v1beta1.IFinalizeStreamRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.cloud.bigquery.storage.v1beta1.IFinalizeStreamRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('finalizeStream response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.finalizeStream(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.cloud.bigquery.storage.v1beta1.IFinalizeStreamRequest|undefined, {}|undefined - ]) => { - this._log.info('finalizeStream response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .finalizeStream(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + ( + | protos.google.cloud.bigquery.storage.v1beta1.IFinalizeStreamRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('finalizeStream response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Splits a given read stream into two Streams. These streams are referred to - * as the primary and the residual of the split. The original stream can still - * be read from in the same manner as before. Both of the returned streams can - * also be read from, and the total rows return by both child streams will be - * the same as the rows read from the original stream. - * - * Moreover, the two child streams will be allocated back to back in the - * original Stream. Concretely, it is guaranteed that for streams Original, - * Primary, and Residual, that Original[0-j] = Primary[0-j] and - * Original[j-n] = Residual[0-m] once the streams have been read to - * completion. - * - * This method is guaranteed to be idempotent. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.cloud.bigquery.storage.v1beta1.Stream} request.originalStream - * Stream to split. - * @param {number} request.fraction - * A value in the range (0.0, 1.0) that specifies the fractional point at - * which the original stream should be split. The actual split point is - * evaluated on pre-filtered rows, so if a filter is provided, then there is - * no guarantee that the division of the rows between the new child streams - * will be proportional to this fractional value. Additionally, because the - * server-side unit for assigning data is collections of rows, this fraction - * will always map to to a data storage boundary on the server side. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.bigquery.storage.v1beta1.SplitReadStreamResponse|SplitReadStreamResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/big_query_storage.split_read_stream.js - * region_tag:bigquerystorage_v1beta1_generated_BigQueryStorage_SplitReadStream_async - */ + /** + * Splits a given read stream into two Streams. These streams are referred to + * as the primary and the residual of the split. The original stream can still + * be read from in the same manner as before. Both of the returned streams can + * also be read from, and the total rows return by both child streams will be + * the same as the rows read from the original stream. + * + * Moreover, the two child streams will be allocated back to back in the + * original Stream. Concretely, it is guaranteed that for streams Original, + * Primary, and Residual, that Original[0-j] = Primary[0-j] and + * Original[j-n] = Residual[0-m] once the streams have been read to + * completion. + * + * This method is guaranteed to be idempotent. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.cloud.bigquery.storage.v1beta1.Stream} request.originalStream + * Stream to split. + * @param {number} request.fraction + * A value in the range (0.0, 1.0) that specifies the fractional point at + * which the original stream should be split. The actual split point is + * evaluated on pre-filtered rows, so if a filter is provided, then there is + * no guarantee that the division of the rows between the new child streams + * will be proportional to this fractional value. Additionally, because the + * server-side unit for assigning data is collections of rows, this fraction + * will always map to to a data storage boundary on the server side. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.bigquery.storage.v1beta1.SplitReadStreamResponse|SplitReadStreamResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/big_query_storage.split_read_stream.js + * region_tag:bigquerystorage_v1beta1_generated_BigQueryStorage_SplitReadStream_async + */ splitReadStream( - request?: protos.google.cloud.bigquery.storage.v1beta1.ISplitReadStreamRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.bigquery.storage.v1beta1.ISplitReadStreamResponse, - protos.google.cloud.bigquery.storage.v1beta1.ISplitReadStreamRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.bigquery.storage.v1beta1.ISplitReadStreamRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.bigquery.storage.v1beta1.ISplitReadStreamResponse, + ( + | protos.google.cloud.bigquery.storage.v1beta1.ISplitReadStreamRequest + | undefined + ), + {} | undefined, + ] + >; splitReadStream( - request: protos.google.cloud.bigquery.storage.v1beta1.ISplitReadStreamRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.bigquery.storage.v1beta1.ISplitReadStreamResponse, - protos.google.cloud.bigquery.storage.v1beta1.ISplitReadStreamRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.bigquery.storage.v1beta1.ISplitReadStreamRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.bigquery.storage.v1beta1.ISplitReadStreamResponse, + | protos.google.cloud.bigquery.storage.v1beta1.ISplitReadStreamRequest + | null + | undefined, + {} | null | undefined + >, + ): void; splitReadStream( - request: protos.google.cloud.bigquery.storage.v1beta1.ISplitReadStreamRequest, - callback: Callback< - protos.google.cloud.bigquery.storage.v1beta1.ISplitReadStreamResponse, - protos.google.cloud.bigquery.storage.v1beta1.ISplitReadStreamRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.bigquery.storage.v1beta1.ISplitReadStreamRequest, + callback: Callback< + protos.google.cloud.bigquery.storage.v1beta1.ISplitReadStreamResponse, + | protos.google.cloud.bigquery.storage.v1beta1.ISplitReadStreamRequest + | null + | undefined, + {} | null | undefined + >, + ): void; splitReadStream( - request?: protos.google.cloud.bigquery.storage.v1beta1.ISplitReadStreamRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.bigquery.storage.v1beta1.ISplitReadStreamResponse, - protos.google.cloud.bigquery.storage.v1beta1.ISplitReadStreamRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.bigquery.storage.v1beta1.ISplitReadStreamRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.bigquery.storage.v1beta1.ISplitReadStreamResponse, - protos.google.cloud.bigquery.storage.v1beta1.ISplitReadStreamRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.bigquery.storage.v1beta1.ISplitReadStreamResponse, - protos.google.cloud.bigquery.storage.v1beta1.ISplitReadStreamRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.bigquery.storage.v1beta1.ISplitReadStreamRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.bigquery.storage.v1beta1.ISplitReadStreamResponse, + | protos.google.cloud.bigquery.storage.v1beta1.ISplitReadStreamRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.bigquery.storage.v1beta1.ISplitReadStreamResponse, + ( + | protos.google.cloud.bigquery.storage.v1beta1.ISplitReadStreamRequest + | undefined + ), + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'original_stream.name': request.originalStream!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'original_stream.name': request.originalStream!.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('splitReadStream request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.bigquery.storage.v1beta1.ISplitReadStreamResponse, - protos.google.cloud.bigquery.storage.v1beta1.ISplitReadStreamRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.bigquery.storage.v1beta1.ISplitReadStreamResponse, + | protos.google.cloud.bigquery.storage.v1beta1.ISplitReadStreamRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('splitReadStream response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.splitReadStream(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.bigquery.storage.v1beta1.ISplitReadStreamResponse, - protos.google.cloud.bigquery.storage.v1beta1.ISplitReadStreamRequest|undefined, {}|undefined - ]) => { - this._log.info('splitReadStream response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .splitReadStream(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.bigquery.storage.v1beta1.ISplitReadStreamResponse, + ( + | protos.google.cloud.bigquery.storage.v1beta1.ISplitReadStreamRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('splitReadStream response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Reads rows from the table in the format prescribed by the read session. - * Each response contains one or more table rows, up to a maximum of 10 MiB - * per response; read requests which attempt to read individual rows larger - * than this will fail. - * - * Each request also returns a set of stream statistics reflecting the - * estimated total number of rows in the read stream. This number is computed - * based on the total table size and the number of active streams in the read - * session, and may change as other streams continue to read data. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.cloud.bigquery.storage.v1beta1.StreamPosition} request.readPosition - * Required. Identifier of the position in the stream to start reading from. - * The offset requested must be less than the last row read from ReadRows. - * Requesting a larger offset is undefined. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits {@link protos.google.cloud.bigquery.storage.v1beta1.ReadRowsResponse|ReadRowsResponse} on 'data' event. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#server-streaming | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/big_query_storage.read_rows.js - * region_tag:bigquerystorage_v1beta1_generated_BigQueryStorage_ReadRows_async - */ + /** + * Reads rows from the table in the format prescribed by the read session. + * Each response contains one or more table rows, up to a maximum of 10 MiB + * per response; read requests which attempt to read individual rows larger + * than this will fail. + * + * Each request also returns a set of stream statistics reflecting the + * estimated total number of rows in the read stream. This number is computed + * based on the total table size and the number of active streams in the read + * session, and may change as other streams continue to read data. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.cloud.bigquery.storage.v1beta1.StreamPosition} request.readPosition + * Required. Identifier of the position in the stream to start reading from. + * The offset requested must be less than the last row read from ReadRows. + * Requesting a larger offset is undefined. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits {@link protos.google.cloud.bigquery.storage.v1beta1.ReadRowsResponse|ReadRowsResponse} on 'data' event. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#server-streaming | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/big_query_storage.read_rows.js + * region_tag:bigquerystorage_v1beta1_generated_BigQueryStorage_ReadRows_async + */ readRows( - request?: protos.google.cloud.bigquery.storage.v1beta1.IReadRowsRequest, - options?: CallOptions): - gax.CancellableStream{ + request?: protos.google.cloud.bigquery.storage.v1beta1.IReadRowsRequest, + options?: CallOptions, + ): gax.CancellableStream { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'read_position.stream.name': request.readPosition!.stream!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'read_position.stream.name': request.readPosition!.stream!.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('readRows stream %j', options); return this.innerApiCalls.readRows(request, options); } @@ -867,7 +1130,7 @@ export class BigQueryStorageClient { * @param {string} session * @returns {string} Resource name string. */ - readSessionPath(project:string,location:string,session:string) { + readSessionPath(project: string, location: string, session: string) { return this.pathTemplates.readSessionPathTemplate.render({ project: project, location: location, @@ -883,7 +1146,8 @@ export class BigQueryStorageClient { * @returns {string} A string representing the project. */ matchProjectFromReadSessionName(readSessionName: string) { - return this.pathTemplates.readSessionPathTemplate.match(readSessionName).project; + return this.pathTemplates.readSessionPathTemplate.match(readSessionName) + .project; } /** @@ -894,7 +1158,8 @@ export class BigQueryStorageClient { * @returns {string} A string representing the location. */ matchLocationFromReadSessionName(readSessionName: string) { - return this.pathTemplates.readSessionPathTemplate.match(readSessionName).location; + return this.pathTemplates.readSessionPathTemplate.match(readSessionName) + .location; } /** @@ -905,7 +1170,8 @@ export class BigQueryStorageClient { * @returns {string} A string representing the session. */ matchSessionFromReadSessionName(readSessionName: string) { - return this.pathTemplates.readSessionPathTemplate.match(readSessionName).session; + return this.pathTemplates.readSessionPathTemplate.match(readSessionName) + .session; } /** @@ -916,7 +1182,7 @@ export class BigQueryStorageClient { * @param {string} stream * @returns {string} Resource name string. */ - streamPath(project:string,location:string,stream:string) { + streamPath(project: string, location: string, stream: string) { return this.pathTemplates.streamPathTemplate.render({ project: project, location: location, @@ -965,7 +1231,7 @@ export class BigQueryStorageClient { */ close(): Promise { if (this.bigQueryStorageStub && !this._terminated) { - return this.bigQueryStorageStub.then(stub => { + return this.bigQueryStorageStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -973,4 +1239,4 @@ export class BigQueryStorageClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/core/generator/gapic-generator-typescript/baselines/bigquery-storage-esm/esm/src/v1beta1/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/bigquery-storage-esm/esm/src/v1beta1/index.ts.baseline index 79017d9fb87b..7b2d6d572595 100644 --- a/core/generator/gapic-generator-typescript/baselines/bigquery-storage-esm/esm/src/v1beta1/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/bigquery-storage-esm/esm/src/v1beta1/index.ts.baseline @@ -16,4 +16,4 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -export {BigQueryStorageClient} from './big_query_storage_client.js'; +export { BigQueryStorageClient } from './big_query_storage_client.js'; diff --git a/core/generator/gapic-generator-typescript/baselines/bigquery-storage-esm/esm/system-test/fixtures/sample/src/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/bigquery-storage-esm/esm/system-test/fixtures/sample/src/index.ts.baseline index 3e74dfdae58d..fc2954be7de5 100644 --- a/core/generator/gapic-generator-typescript/baselines/bigquery-storage-esm/esm/system-test/fixtures/sample/src/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/bigquery-storage-esm/esm/system-test/fixtures/sample/src/index.ts.baseline @@ -17,7 +17,7 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -import {BigQueryStorageClient} from 'storage'; +import { BigQueryStorageClient } from 'storage'; // check that the client class type name can be used function doStuffWithBigQueryStorageClient(client: BigQueryStorageClient) { diff --git a/core/generator/gapic-generator-typescript/baselines/bigquery-storage-esm/esm/system-test/install.ts.baseline b/core/generator/gapic-generator-typescript/baselines/bigquery-storage-esm/esm/system-test/install.ts.baseline index e079c4fa1101..d109fdd8c97f 100644 --- a/core/generator/gapic-generator-typescript/baselines/bigquery-storage-esm/esm/system-test/install.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/bigquery-storage-esm/esm/system-test/install.ts.baseline @@ -16,40 +16,45 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -import {packNTest} from 'pack-n-play'; -import {readFileSync} from 'fs'; -import {describe, it} from 'mocha'; +import { packNTest } from 'pack-n-play'; +import { readFileSync } from 'fs'; +import { describe, it } from 'mocha'; describe('📦 pack-n-play test', () => { - it('TypeScript', async function() { + it('TypeScript', async function () { this.timeout(300000); await packNTest({ packageDir: process.cwd(), sample: { description: 'TypeScript user can use the type definitions', - ts: readFileSync('./esm/system-test/fixtures/sample/src/index.ts').toString() - } + ts: readFileSync( + './esm/system-test/fixtures/sample/src/index.ts', + ).toString(), + }, }); }); - it('ESM module', async function() { + it('ESM module', async function () { this.timeout(300000); await packNTest({ sample: { description: 'Should be able to import using ESM', - esm: readFileSync('./esm/system-test/fixtures/sample/src/index.js').toString(), + esm: readFileSync( + './esm/system-test/fixtures/sample/src/index.js', + ).toString(), }, }); }); - it('CJS module', async function() { + it('CJS module', async function () { this.timeout(300000); await packNTest({ sample: { description: 'Should be able to import using CJS', - cjs: readFileSync('./esm/system-test/fixtures/sample/src/index.cjs').toString(), + cjs: readFileSync( + './esm/system-test/fixtures/sample/src/index.cjs', + ).toString(), }, }); }); - }); diff --git a/core/generator/gapic-generator-typescript/baselines/bigquery-storage-esm/esm/test/gapic_big_query_storage_v1beta1.ts.baseline b/core/generator/gapic-generator-typescript/baselines/bigquery-storage-esm/esm/test/gapic_big_query_storage_v1beta1.ts.baseline index 3a822fcad5ad..ca4ab728d050 100644 --- a/core/generator/gapic-generator-typescript/baselines/bigquery-storage-esm/esm/test/gapic_big_query_storage_v1beta1.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/bigquery-storage-esm/esm/test/gapic_big_query_storage_v1beta1.ts.baseline @@ -20,16 +20,16 @@ import * as protos from '../../protos/protos.js'; import assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as bigquerystorageModule from '../src/index.js'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; -import {protobuf} from 'google-gax'; +import { protobuf } from 'google-gax'; import fs from 'fs'; import path from 'path'; -import {fileURLToPath} from 'url'; +import { fileURLToPath } from 'url'; // @ts-ignore const dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -37,907 +37,1156 @@ const dirname = path.dirname(fileURLToPath(import.meta.url)); // to fill in default values for request objects const root = protobuf.Root.fromJSON( JSON.parse( - fs.readFileSync(path.join(dirname, '..', '..', 'protos/protos.json'), 'utf8') - )) + fs.readFileSync( + path.join(dirname, '..', '..', 'protos/protos.json'), + 'utf8', + ), + ), +); // eslint-disable-next-line @typescript-eslint/no-unused-vars function getTypeDefaultValue(typeName: string, fields: string[]) { - let type = root.lookupType(typeName) as protobuf.Type; - for (const field of fields.slice(0, -1)) { - type = type?.fields[field]?.resolvedType as protobuf.Type; - } - return type?.fields[fields[fields.length - 1]]?.defaultValue ?? null; + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type?.fields[field]?.resolvedType as protobuf.Type; + } + return type?.fields[fields[fields.length - 1]]?.defaultValue ?? null; } function generateSampleMessage(instance: T) { - const filledObject = (instance.constructor as typeof protobuf.Message) - .toObject(instance as protobuf.Message, {defaults: true}); - return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, { defaults: true }); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; } function stubSimpleCall(response?: ResponseType, error?: Error) { - return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); } -function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { - return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +function stubSimpleCallWithCallback( + response?: ResponseType, + error?: Error, +) { + return error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); } -function stubServerStreamingCall(response?: ResponseType, error?: Error) { - const transformStub = error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); - const mockStream = new PassThrough({ - objectMode: true, - transform: transformStub, - }); - // write something to the stream to trigger transformStub and send the response back to the client - setImmediate(() => { mockStream.write({}); }); - setImmediate(() => { mockStream.end(); }); - return sinon.stub().returns(mockStream); +function stubServerStreamingCall( + response?: ResponseType, + error?: Error, +) { + const transformStub = error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + // write something to the stream to trigger transformStub and send the response back to the client + setImmediate(() => { + mockStream.write({}); + }); + setImmediate(() => { + mockStream.end(); + }); + return sinon.stub().returns(mockStream); } describe('v1beta1.BigQueryStorageClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'bigquerystorage.googleapis.com'); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'bigquerystorage.googleapis.com'); + }); - it('has universeDomain', () => { - const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); + it('has universeDomain', () => { + const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - it('throws DeprecationWarning if static servicePath is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const servicePath = bigquerystorageModule.v1beta1.BigQueryStorageClient.servicePath; - assert.strictEqual(servicePath, 'bigquerystorage.googleapis.com'); - assert(stub.called); - stub.restore(); - }); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = + bigquerystorageModule.v1beta1.BigQueryStorageClient.servicePath; + assert.strictEqual(servicePath, 'bigquerystorage.googleapis.com'); + assert(stub.called); + stub.restore(); + }); - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = bigquerystorageModule.v1beta1.BigQueryStorageClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'bigquerystorage.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'bigquerystorage.example.com'); - }); + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + bigquerystorageModule.v1beta1.BigQueryStorageClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'bigquerystorage.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ + universeDomain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'bigquerystorage.example.com'); + }); - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'bigquerystorage.example.com'); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ + universe_domain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'bigquerystorage.example.com'); + }); + + if (typeof process === 'object' && 'env' in process) { + describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { + it('sets apiEndpoint from environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = + new bigquerystorageModule.v1beta1.BigQueryStorageClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'bigquerystorage.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - if (typeof process === 'object' && 'env' in process) { - describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { - it('sets apiEndpoint from environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'bigquerystorage.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - - it('value configured in code has priority over environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'bigquerystorage.configured.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); + it('value configured in code has priority over environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = + new bigquerystorageModule.v1beta1.BigQueryStorageClient({ + universeDomain: 'configured.example.com', }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { new bigquerystorageModule.v1beta1.BigQueryStorageClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); + const servicePath = client.apiEndpoint; + assert.strictEqual( + servicePath, + 'bigquerystorage.configured.example.com', + ); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - - it('has port', () => { - const port = bigquerystorageModule.v1beta1.BigQueryStorageClient.port; - assert(port); - assert(typeof port === 'number'); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new bigquerystorageModule.v1beta1.BigQueryStorageClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); + }); - it('should create a client with no option', () => { - const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient(); - assert(client); - }); + it('has port', () => { + const port = bigquerystorageModule.v1beta1.BigQueryStorageClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('should create a client with gRPC fallback', () => { - const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ - fallback: true, - }); - assert(client); - }); + it('should create a client with no option', () => { + const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient(); + assert(client); + }); - it('has initialize method and supports deferred initialization', async () => { - const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.bigQueryStorageStub, undefined); - await client.initialize(); - assert(client.bigQueryStorageStub); - }); + it('should create a client with gRPC fallback', () => { + const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ + fallback: true, + }); + assert(client); + }); - it('has close method for the initialized client', done => { - const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.bigQueryStorageStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('has initialize method and supports deferred initialization', async () => { + const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.bigQueryStorageStub, undefined); + await client.initialize(); + assert(client.bigQueryStorageStub); + }); - it('has close method for the non-initialized client', done => { - const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.bigQueryStorageStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); + it('has close method for the initialized client', (done) => { + const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.bigQueryStorageStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + it('has close method for the non-initialized client', (done) => { + const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.bigQueryStorageStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId((err?: Error|null, projectId?: string|null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } - }); - }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); - }); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); }); - describe('createReadSession', () => { - it('invokes createReadSession without error', async () => { - const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.storage.v1beta1.CreateReadSessionRequest() - ); - request.tableReference ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.storage.v1beta1.CreateReadSessionRequest', ['tableReference', 'projectId']); - request.tableReference.projectId = defaultValue1; - request.tableReference ??= {}; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.storage.v1beta1.CreateReadSessionRequest', ['tableReference', 'datasetId']); - request.tableReference.datasetId = defaultValue2; - const expectedHeaderRequestParams = `table_reference.project_id=${defaultValue1 ?? '' }&table_reference.dataset_id=${defaultValue2 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.bigquery.storage.v1beta1.ReadSession() - ); - client.innerApiCalls.createReadSession = stubSimpleCall(expectedResponse); - const [response] = await client.createReadSession(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createReadSession as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createReadSession as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + }); - it('invokes createReadSession without error using callback', async () => { - const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.storage.v1beta1.CreateReadSessionRequest() - ); - request.tableReference ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.storage.v1beta1.CreateReadSessionRequest', ['tableReference', 'projectId']); - request.tableReference.projectId = defaultValue1; - request.tableReference ??= {}; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.storage.v1beta1.CreateReadSessionRequest', ['tableReference', 'datasetId']); - request.tableReference.datasetId = defaultValue2; - const expectedHeaderRequestParams = `table_reference.project_id=${defaultValue1 ?? '' }&table_reference.dataset_id=${defaultValue2 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.bigquery.storage.v1beta1.ReadSession() - ); - client.innerApiCalls.createReadSession = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createReadSession( - request, - (err?: Error|null, result?: protos.google.cloud.bigquery.storage.v1beta1.IReadSession|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createReadSession as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createReadSession as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + describe('createReadSession', () => { + it('invokes createReadSession without error', async () => { + const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.storage.v1beta1.CreateReadSessionRequest(), + ); + request.tableReference ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.storage.v1beta1.CreateReadSessionRequest', + ['tableReference', 'projectId'], + ); + request.tableReference.projectId = defaultValue1; + request.tableReference ??= {}; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.storage.v1beta1.CreateReadSessionRequest', + ['tableReference', 'datasetId'], + ); + request.tableReference.datasetId = defaultValue2; + const expectedHeaderRequestParams = `table_reference.project_id=${defaultValue1 ?? ''}&table_reference.dataset_id=${defaultValue2 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.bigquery.storage.v1beta1.ReadSession(), + ); + client.innerApiCalls.createReadSession = stubSimpleCall(expectedResponse); + const [response] = await client.createReadSession(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createReadSession as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createReadSession as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createReadSession with error', async () => { - const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.storage.v1beta1.CreateReadSessionRequest() - ); - request.tableReference ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.storage.v1beta1.CreateReadSessionRequest', ['tableReference', 'projectId']); - request.tableReference.projectId = defaultValue1; - request.tableReference ??= {}; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.storage.v1beta1.CreateReadSessionRequest', ['tableReference', 'datasetId']); - request.tableReference.datasetId = defaultValue2; - const expectedHeaderRequestParams = `table_reference.project_id=${defaultValue1 ?? '' }&table_reference.dataset_id=${defaultValue2 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createReadSession = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createReadSession(request), expectedError); - const actualRequest = (client.innerApiCalls.createReadSession as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createReadSession as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createReadSession without error using callback', async () => { + const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.storage.v1beta1.CreateReadSessionRequest(), + ); + request.tableReference ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.storage.v1beta1.CreateReadSessionRequest', + ['tableReference', 'projectId'], + ); + request.tableReference.projectId = defaultValue1; + request.tableReference ??= {}; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.storage.v1beta1.CreateReadSessionRequest', + ['tableReference', 'datasetId'], + ); + request.tableReference.datasetId = defaultValue2; + const expectedHeaderRequestParams = `table_reference.project_id=${defaultValue1 ?? ''}&table_reference.dataset_id=${defaultValue2 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.bigquery.storage.v1beta1.ReadSession(), + ); + client.innerApiCalls.createReadSession = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createReadSession( + request, + ( + err?: Error | null, + result?: protos.google.cloud.bigquery.storage.v1beta1.IReadSession | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createReadSession as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createReadSession as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createReadSession with closed client', async () => { - const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.storage.v1beta1.CreateReadSessionRequest() - ); - request.tableReference ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.storage.v1beta1.CreateReadSessionRequest', ['tableReference', 'projectId']); - request.tableReference.projectId = defaultValue1; - request.tableReference ??= {}; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.storage.v1beta1.CreateReadSessionRequest', ['tableReference', 'datasetId']); - request.tableReference.datasetId = defaultValue2; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createReadSession(request), expectedError); - }); + it('invokes createReadSession with error', async () => { + const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.storage.v1beta1.CreateReadSessionRequest(), + ); + request.tableReference ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.storage.v1beta1.CreateReadSessionRequest', + ['tableReference', 'projectId'], + ); + request.tableReference.projectId = defaultValue1; + request.tableReference ??= {}; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.storage.v1beta1.CreateReadSessionRequest', + ['tableReference', 'datasetId'], + ); + request.tableReference.datasetId = defaultValue2; + const expectedHeaderRequestParams = `table_reference.project_id=${defaultValue1 ?? ''}&table_reference.dataset_id=${defaultValue2 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createReadSession = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.createReadSession(request), expectedError); + const actualRequest = ( + client.innerApiCalls.createReadSession as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createReadSession as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('batchCreateReadSessionStreams', () => { - it('invokes batchCreateReadSessionStreams without error', async () => { - const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.storage.v1beta1.BatchCreateReadSessionStreamsRequest() - ); - request.session ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.storage.v1beta1.BatchCreateReadSessionStreamsRequest', ['session', 'name']); - request.session.name = defaultValue1; - const expectedHeaderRequestParams = `session.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.bigquery.storage.v1beta1.BatchCreateReadSessionStreamsResponse() - ); - client.innerApiCalls.batchCreateReadSessionStreams = stubSimpleCall(expectedResponse); - const [response] = await client.batchCreateReadSessionStreams(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.batchCreateReadSessionStreams as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.batchCreateReadSessionStreams as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createReadSession with closed client', async () => { + const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.storage.v1beta1.CreateReadSessionRequest(), + ); + request.tableReference ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.storage.v1beta1.CreateReadSessionRequest', + ['tableReference', 'projectId'], + ); + request.tableReference.projectId = defaultValue1; + request.tableReference ??= {}; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.storage.v1beta1.CreateReadSessionRequest', + ['tableReference', 'datasetId'], + ); + request.tableReference.datasetId = defaultValue2; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.createReadSession(request), expectedError); + }); + }); - it('invokes batchCreateReadSessionStreams without error using callback', async () => { - const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.storage.v1beta1.BatchCreateReadSessionStreamsRequest() - ); - request.session ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.storage.v1beta1.BatchCreateReadSessionStreamsRequest', ['session', 'name']); - request.session.name = defaultValue1; - const expectedHeaderRequestParams = `session.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.bigquery.storage.v1beta1.BatchCreateReadSessionStreamsResponse() - ); - client.innerApiCalls.batchCreateReadSessionStreams = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.batchCreateReadSessionStreams( - request, - (err?: Error|null, result?: protos.google.cloud.bigquery.storage.v1beta1.IBatchCreateReadSessionStreamsResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.batchCreateReadSessionStreams as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.batchCreateReadSessionStreams as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + describe('batchCreateReadSessionStreams', () => { + it('invokes batchCreateReadSessionStreams without error', async () => { + const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.storage.v1beta1.BatchCreateReadSessionStreamsRequest(), + ); + request.session ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.storage.v1beta1.BatchCreateReadSessionStreamsRequest', + ['session', 'name'], + ); + request.session.name = defaultValue1; + const expectedHeaderRequestParams = `session.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.bigquery.storage.v1beta1.BatchCreateReadSessionStreamsResponse(), + ); + client.innerApiCalls.batchCreateReadSessionStreams = + stubSimpleCall(expectedResponse); + const [response] = await client.batchCreateReadSessionStreams(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.batchCreateReadSessionStreams as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.batchCreateReadSessionStreams as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes batchCreateReadSessionStreams with error', async () => { - const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.storage.v1beta1.BatchCreateReadSessionStreamsRequest() - ); - request.session ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.storage.v1beta1.BatchCreateReadSessionStreamsRequest', ['session', 'name']); - request.session.name = defaultValue1; - const expectedHeaderRequestParams = `session.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.batchCreateReadSessionStreams = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.batchCreateReadSessionStreams(request), expectedError); - const actualRequest = (client.innerApiCalls.batchCreateReadSessionStreams as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.batchCreateReadSessionStreams as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes batchCreateReadSessionStreams without error using callback', async () => { + const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.storage.v1beta1.BatchCreateReadSessionStreamsRequest(), + ); + request.session ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.storage.v1beta1.BatchCreateReadSessionStreamsRequest', + ['session', 'name'], + ); + request.session.name = defaultValue1; + const expectedHeaderRequestParams = `session.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.bigquery.storage.v1beta1.BatchCreateReadSessionStreamsResponse(), + ); + client.innerApiCalls.batchCreateReadSessionStreams = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.batchCreateReadSessionStreams( + request, + ( + err?: Error | null, + result?: protos.google.cloud.bigquery.storage.v1beta1.IBatchCreateReadSessionStreamsResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.batchCreateReadSessionStreams as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.batchCreateReadSessionStreams as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes batchCreateReadSessionStreams with closed client', async () => { - const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.storage.v1beta1.BatchCreateReadSessionStreamsRequest() - ); - request.session ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.storage.v1beta1.BatchCreateReadSessionStreamsRequest', ['session', 'name']); - request.session.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.batchCreateReadSessionStreams(request), expectedError); - }); + it('invokes batchCreateReadSessionStreams with error', async () => { + const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.storage.v1beta1.BatchCreateReadSessionStreamsRequest(), + ); + request.session ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.storage.v1beta1.BatchCreateReadSessionStreamsRequest', + ['session', 'name'], + ); + request.session.name = defaultValue1; + const expectedHeaderRequestParams = `session.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.batchCreateReadSessionStreams = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.batchCreateReadSessionStreams(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.batchCreateReadSessionStreams as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.batchCreateReadSessionStreams as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('finalizeStream', () => { - it('invokes finalizeStream without error', async () => { - const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.storage.v1beta1.FinalizeStreamRequest() - ); - request.stream ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.storage.v1beta1.FinalizeStreamRequest', ['stream', 'name']); - request.stream.name = defaultValue1; - const expectedHeaderRequestParams = `stream.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.finalizeStream = stubSimpleCall(expectedResponse); - const [response] = await client.finalizeStream(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.finalizeStream as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.finalizeStream as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes batchCreateReadSessionStreams with closed client', async () => { + const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.storage.v1beta1.BatchCreateReadSessionStreamsRequest(), + ); + request.session ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.storage.v1beta1.BatchCreateReadSessionStreamsRequest', + ['session', 'name'], + ); + request.session.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.batchCreateReadSessionStreams(request), + expectedError, + ); + }); + }); - it('invokes finalizeStream without error using callback', async () => { - const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.storage.v1beta1.FinalizeStreamRequest() - ); - request.stream ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.storage.v1beta1.FinalizeStreamRequest', ['stream', 'name']); - request.stream.name = defaultValue1; - const expectedHeaderRequestParams = `stream.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.finalizeStream = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.finalizeStream( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.finalizeStream as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.finalizeStream as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + describe('finalizeStream', () => { + it('invokes finalizeStream without error', async () => { + const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.storage.v1beta1.FinalizeStreamRequest(), + ); + request.stream ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.storage.v1beta1.FinalizeStreamRequest', + ['stream', 'name'], + ); + request.stream.name = defaultValue1; + const expectedHeaderRequestParams = `stream.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.finalizeStream = stubSimpleCall(expectedResponse); + const [response] = await client.finalizeStream(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.finalizeStream as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.finalizeStream as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes finalizeStream with error', async () => { - const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.storage.v1beta1.FinalizeStreamRequest() - ); - request.stream ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.storage.v1beta1.FinalizeStreamRequest', ['stream', 'name']); - request.stream.name = defaultValue1; - const expectedHeaderRequestParams = `stream.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.finalizeStream = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.finalizeStream(request), expectedError); - const actualRequest = (client.innerApiCalls.finalizeStream as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.finalizeStream as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes finalizeStream without error using callback', async () => { + const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.storage.v1beta1.FinalizeStreamRequest(), + ); + request.stream ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.storage.v1beta1.FinalizeStreamRequest', + ['stream', 'name'], + ); + request.stream.name = defaultValue1; + const expectedHeaderRequestParams = `stream.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.finalizeStream = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.finalizeStream( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.finalizeStream as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.finalizeStream as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes finalizeStream with closed client', async () => { - const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.storage.v1beta1.FinalizeStreamRequest() - ); - request.stream ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.storage.v1beta1.FinalizeStreamRequest', ['stream', 'name']); - request.stream.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.finalizeStream(request), expectedError); - }); + it('invokes finalizeStream with error', async () => { + const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.storage.v1beta1.FinalizeStreamRequest(), + ); + request.stream ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.storage.v1beta1.FinalizeStreamRequest', + ['stream', 'name'], + ); + request.stream.name = defaultValue1; + const expectedHeaderRequestParams = `stream.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.finalizeStream = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.finalizeStream(request), expectedError); + const actualRequest = ( + client.innerApiCalls.finalizeStream as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.finalizeStream as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('splitReadStream', () => { - it('invokes splitReadStream without error', async () => { - const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.storage.v1beta1.SplitReadStreamRequest() - ); - request.originalStream ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.storage.v1beta1.SplitReadStreamRequest', ['originalStream', 'name']); - request.originalStream.name = defaultValue1; - const expectedHeaderRequestParams = `original_stream.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.bigquery.storage.v1beta1.SplitReadStreamResponse() - ); - client.innerApiCalls.splitReadStream = stubSimpleCall(expectedResponse); - const [response] = await client.splitReadStream(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.splitReadStream as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.splitReadStream as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes finalizeStream with closed client', async () => { + const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.storage.v1beta1.FinalizeStreamRequest(), + ); + request.stream ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.storage.v1beta1.FinalizeStreamRequest', + ['stream', 'name'], + ); + request.stream.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.finalizeStream(request), expectedError); + }); + }); - it('invokes splitReadStream without error using callback', async () => { - const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.storage.v1beta1.SplitReadStreamRequest() - ); - request.originalStream ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.storage.v1beta1.SplitReadStreamRequest', ['originalStream', 'name']); - request.originalStream.name = defaultValue1; - const expectedHeaderRequestParams = `original_stream.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.bigquery.storage.v1beta1.SplitReadStreamResponse() - ); - client.innerApiCalls.splitReadStream = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.splitReadStream( - request, - (err?: Error|null, result?: protos.google.cloud.bigquery.storage.v1beta1.ISplitReadStreamResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.splitReadStream as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.splitReadStream as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + describe('splitReadStream', () => { + it('invokes splitReadStream without error', async () => { + const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.storage.v1beta1.SplitReadStreamRequest(), + ); + request.originalStream ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.storage.v1beta1.SplitReadStreamRequest', + ['originalStream', 'name'], + ); + request.originalStream.name = defaultValue1; + const expectedHeaderRequestParams = `original_stream.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.bigquery.storage.v1beta1.SplitReadStreamResponse(), + ); + client.innerApiCalls.splitReadStream = stubSimpleCall(expectedResponse); + const [response] = await client.splitReadStream(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.splitReadStream as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.splitReadStream as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes splitReadStream with error', async () => { - const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.storage.v1beta1.SplitReadStreamRequest() - ); - request.originalStream ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.storage.v1beta1.SplitReadStreamRequest', ['originalStream', 'name']); - request.originalStream.name = defaultValue1; - const expectedHeaderRequestParams = `original_stream.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.splitReadStream = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.splitReadStream(request), expectedError); - const actualRequest = (client.innerApiCalls.splitReadStream as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.splitReadStream as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes splitReadStream without error using callback', async () => { + const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.storage.v1beta1.SplitReadStreamRequest(), + ); + request.originalStream ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.storage.v1beta1.SplitReadStreamRequest', + ['originalStream', 'name'], + ); + request.originalStream.name = defaultValue1; + const expectedHeaderRequestParams = `original_stream.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.bigquery.storage.v1beta1.SplitReadStreamResponse(), + ); + client.innerApiCalls.splitReadStream = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.splitReadStream( + request, + ( + err?: Error | null, + result?: protos.google.cloud.bigquery.storage.v1beta1.ISplitReadStreamResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.splitReadStream as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.splitReadStream as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes splitReadStream with closed client', async () => { - const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.storage.v1beta1.SplitReadStreamRequest() - ); - request.originalStream ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.storage.v1beta1.SplitReadStreamRequest', ['originalStream', 'name']); - request.originalStream.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.splitReadStream(request), expectedError); - }); + it('invokes splitReadStream with error', async () => { + const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.storage.v1beta1.SplitReadStreamRequest(), + ); + request.originalStream ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.storage.v1beta1.SplitReadStreamRequest', + ['originalStream', 'name'], + ); + request.originalStream.name = defaultValue1; + const expectedHeaderRequestParams = `original_stream.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.splitReadStream = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.splitReadStream(request), expectedError); + const actualRequest = ( + client.innerApiCalls.splitReadStream as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.splitReadStream as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('readRows', () => { - it('invokes readRows without error', async () => { - const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.storage.v1beta1.ReadRowsRequest() - ); - request.readPosition ??= {}; - request.readPosition.stream ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.storage.v1beta1.ReadRowsRequest', ['readPosition', 'stream', 'name']); - request.readPosition.stream.name = defaultValue1; - const expectedHeaderRequestParams = `read_position.stream.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.bigquery.storage.v1beta1.ReadRowsResponse() - ); - client.innerApiCalls.readRows = stubServerStreamingCall(expectedResponse); - const stream = client.readRows(request); - const promise = new Promise((resolve, reject) => { - stream.on('data', (response: protos.google.cloud.bigquery.storage.v1beta1.ReadRowsResponse) => { - resolve(response); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.readRows as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.readRows as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes splitReadStream with closed client', async () => { + const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.storage.v1beta1.SplitReadStreamRequest(), + ); + request.originalStream ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.storage.v1beta1.SplitReadStreamRequest', + ['originalStream', 'name'], + ); + request.originalStream.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.splitReadStream(request), expectedError); + }); + }); - it('invokes readRows without error and gaxServerStreamingRetries enabled', async () => { - const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.storage.v1beta1.ReadRowsRequest() - ); - request.readPosition ??= {}; - request.readPosition.stream ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.storage.v1beta1.ReadRowsRequest', ['readPosition', 'stream', 'name']); - request.readPosition.stream.name = defaultValue1; - const expectedHeaderRequestParams = `read_position.stream.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.bigquery.storage.v1beta1.ReadRowsResponse() - ); - client.innerApiCalls.readRows = stubServerStreamingCall(expectedResponse); - const stream = client.readRows(request); - const promise = new Promise((resolve, reject) => { - stream.on('data', (response: protos.google.cloud.bigquery.storage.v1beta1.ReadRowsResponse) => { - resolve(response); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.readRows as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.readRows as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + describe('readRows', () => { + it('invokes readRows without error', async () => { + const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.storage.v1beta1.ReadRowsRequest(), + ); + request.readPosition ??= {}; + request.readPosition.stream ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.storage.v1beta1.ReadRowsRequest', + ['readPosition', 'stream', 'name'], + ); + request.readPosition.stream.name = defaultValue1; + const expectedHeaderRequestParams = `read_position.stream.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.bigquery.storage.v1beta1.ReadRowsResponse(), + ); + client.innerApiCalls.readRows = stubServerStreamingCall(expectedResponse); + const stream = client.readRows(request); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + ( + response: protos.google.cloud.bigquery.storage.v1beta1.ReadRowsResponse, + ) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.readRows as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.readRows as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes readRows with error', async () => { - const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.storage.v1beta1.ReadRowsRequest() - ); - request.readPosition ??= {}; - request.readPosition.stream ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.storage.v1beta1.ReadRowsRequest', ['readPosition', 'stream', 'name']); - request.readPosition.stream.name = defaultValue1; - const expectedHeaderRequestParams = `read_position.stream.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.readRows = stubServerStreamingCall(undefined, expectedError); - const stream = client.readRows(request); - const promise = new Promise((resolve, reject) => { - stream.on('data', (response: protos.google.cloud.bigquery.storage.v1beta1.ReadRowsResponse) => { - resolve(response); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - const actualRequest = (client.innerApiCalls.readRows as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.readRows as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes readRows without error and gaxServerStreamingRetries enabled', async () => { + const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.storage.v1beta1.ReadRowsRequest(), + ); + request.readPosition ??= {}; + request.readPosition.stream ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.storage.v1beta1.ReadRowsRequest', + ['readPosition', 'stream', 'name'], + ); + request.readPosition.stream.name = defaultValue1; + const expectedHeaderRequestParams = `read_position.stream.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.bigquery.storage.v1beta1.ReadRowsResponse(), + ); + client.innerApiCalls.readRows = stubServerStreamingCall(expectedResponse); + const stream = client.readRows(request); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + ( + response: protos.google.cloud.bigquery.storage.v1beta1.ReadRowsResponse, + ) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.readRows as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.readRows as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes readRows with closed client', async () => { - const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.storage.v1beta1.ReadRowsRequest() - ); - request.readPosition ??= {}; - request.readPosition.stream ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.storage.v1beta1.ReadRowsRequest', ['readPosition', 'stream', 'name']); - request.readPosition.stream.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - const stream = client.readRows(request, {retryRequestOptions: {noResponseRetries: 0}}); - const promise = new Promise((resolve, reject) => { - stream.on('data', (response: protos.google.cloud.bigquery.storage.v1beta1.ReadRowsResponse) => { - resolve(response); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); + it('invokes readRows with error', async () => { + const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.storage.v1beta1.ReadRowsRequest(), + ); + request.readPosition ??= {}; + request.readPosition.stream ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.storage.v1beta1.ReadRowsRequest', + ['readPosition', 'stream', 'name'], + ); + request.readPosition.stream.name = defaultValue1; + const expectedHeaderRequestParams = `read_position.stream.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.readRows = stubServerStreamingCall( + undefined, + expectedError, + ); + const stream = client.readRows(request); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + ( + response: protos.google.cloud.bigquery.storage.v1beta1.ReadRowsResponse, + ) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); }); - it('should create a client with gaxServerStreamingRetries enabled', () => { - const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ - gaxServerStreamingRetries: true, - }); - assert(client); + }); + await assert.rejects(promise, expectedError); + const actualRequest = ( + client.innerApiCalls.readRows as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.readRows as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes readRows with closed client', async () => { + const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.storage.v1beta1.ReadRowsRequest(), + ); + request.readPosition ??= {}; + request.readPosition.stream ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.storage.v1beta1.ReadRowsRequest', + ['readPosition', 'stream', 'name'], + ); + request.readPosition.stream.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + const stream = client.readRows(request, { + retryRequestOptions: { noResponseRetries: 0 }, + }); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + ( + response: protos.google.cloud.bigquery.storage.v1beta1.ReadRowsResponse, + ) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); }); + }); + await assert.rejects(promise, expectedError); + }); + it('should create a client with gaxServerStreamingRetries enabled', () => { + const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ + gaxServerStreamingRetries: true, + }); + assert(client); }); + }); - describe('Path templates', () => { + describe('Path templates', () => { + describe('readSession', () => { + const fakePath = '/rendered/path/readSession'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + session: 'sessionValue', + }; + const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.readSessionPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.readSessionPathTemplate.match = sinon + .stub() + .returns(expectedParameters); - describe('readSession', () => { - const fakePath = "/rendered/path/readSession"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - session: "sessionValue", - }; - const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.readSessionPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.readSessionPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('readSessionPath', () => { - const result = client.readSessionPath("projectValue", "locationValue", "sessionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.readSessionPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + it('readSessionPath', () => { + const result = client.readSessionPath( + 'projectValue', + 'locationValue', + 'sessionValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.readSessionPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); - it('matchProjectFromReadSessionName', () => { - const result = client.matchProjectFromReadSessionName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.readSessionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('matchProjectFromReadSessionName', () => { + const result = client.matchProjectFromReadSessionName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.readSessionPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); - it('matchLocationFromReadSessionName', () => { - const result = client.matchLocationFromReadSessionName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.readSessionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('matchLocationFromReadSessionName', () => { + const result = client.matchLocationFromReadSessionName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.readSessionPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); - it('matchSessionFromReadSessionName', () => { - const result = client.matchSessionFromReadSessionName(fakePath); - assert.strictEqual(result, "sessionValue"); - assert((client.pathTemplates.readSessionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('matchSessionFromReadSessionName', () => { + const result = client.matchSessionFromReadSessionName(fakePath); + assert.strictEqual(result, 'sessionValue'); + assert( + (client.pathTemplates.readSessionPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('stream', () => { - const fakePath = "/rendered/path/stream"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - stream: "streamValue", - }; - const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.streamPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.streamPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('streamPath', () => { - const result = client.streamPath("projectValue", "locationValue", "streamValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.streamPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + describe('stream', () => { + const fakePath = '/rendered/path/stream'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + stream: 'streamValue', + }; + const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.streamPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.streamPathTemplate.match = sinon + .stub() + .returns(expectedParameters); - it('matchProjectFromStreamName', () => { - const result = client.matchProjectFromStreamName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.streamPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('streamPath', () => { + const result = client.streamPath( + 'projectValue', + 'locationValue', + 'streamValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.streamPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); - it('matchLocationFromStreamName', () => { - const result = client.matchLocationFromStreamName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.streamPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('matchProjectFromStreamName', () => { + const result = client.matchProjectFromStreamName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.streamPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); - it('matchStreamFromStreamName', () => { - const result = client.matchStreamFromStreamName(fakePath); - assert.strictEqual(result, "streamValue"); - assert((client.pathTemplates.streamPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('matchLocationFromStreamName', () => { + const result = client.matchLocationFromStreamName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.streamPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchStreamFromStreamName', () => { + const result = client.matchStreamFromStreamName(fakePath); + assert.strictEqual(result, 'streamValue'); + assert( + (client.pathTemplates.streamPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/core/generator/gapic-generator-typescript/baselines/bigquery-storage/src/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/bigquery-storage/src/index.ts.baseline index 8f4ed7aeba75..0ee0fdcb3ea0 100644 --- a/core/generator/gapic-generator-typescript/baselines/bigquery-storage/src/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/bigquery-storage/src/index.ts.baseline @@ -19,7 +19,7 @@ import * as v1beta1 from './v1beta1'; const BigQueryStorageClient = v1beta1.BigQueryStorageClient; type BigQueryStorageClient = v1beta1.BigQueryStorageClient; -export {v1beta1, BigQueryStorageClient}; -export default {v1beta1, BigQueryStorageClient}; +export { v1beta1, BigQueryStorageClient }; +export default { v1beta1, BigQueryStorageClient }; import * as protos from '../protos/protos'; -export {protos} +export { protos }; diff --git a/core/generator/gapic-generator-typescript/baselines/bigquery-storage/src/v1beta1/big_query_storage_client.ts.baseline b/core/generator/gapic-generator-typescript/baselines/bigquery-storage/src/v1beta1/big_query_storage_client.ts.baseline index 4b8aca2e3545..bcc150902a58 100644 --- a/core/generator/gapic-generator-typescript/baselines/bigquery-storage/src/v1beta1/big_query_storage_client.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/bigquery-storage/src/v1beta1/big_query_storage_client.ts.baseline @@ -18,11 +18,16 @@ /* global window */ import type * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions} from 'google-gax'; -import {PassThrough} from 'stream'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, +} from 'google-gax'; +import { PassThrough } from 'stream'; import * as protos from '../../protos/protos'; import jsonProtos = require('../../protos/protos.json'); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; /** * Client JSON configuration object, loaded from @@ -46,7 +51,7 @@ export class BigQueryStorageClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('storage'); @@ -59,9 +64,9 @@ export class BigQueryStorageClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; - bigQueryStorageStub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; + bigQueryStorageStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of BigQueryStorageClient. @@ -102,21 +107,42 @@ export class BigQueryStorageClient { * const client = new BigQueryStorageClient({fallback: true}, gax); * ``` */ - constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { // Ensure that options include all the required fields. const staticMembers = this.constructor as typeof BigQueryStorageClient; - if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { - throw new Error('Please set either universe_domain or universeDomain, but not both.'); + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); } - const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; - this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; this._servicePath = 'bigquerystorage.' + this._universeDomain; - const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; - const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. if (servicePath !== this._servicePath && !('scopes' in opts)) { @@ -138,7 +164,7 @@ export class BigQueryStorageClient { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; @@ -152,10 +178,7 @@ export class BigQueryStorageClient { } // Determine the client header string. - const clientHeader = [ - `gax/${this._gaxModule.version}`, - `gapic/${version}`, - ]; + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/${process.versions.node}`); } else { @@ -177,23 +200,30 @@ export class BigQueryStorageClient { // Create useful helper objects for these. this.pathTemplates = { readSessionPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/sessions/{session}' + 'projects/{project}/locations/{location}/sessions/{session}', ), streamPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/streams/{stream}' + 'projects/{project}/locations/{location}/streams/{stream}', ), }; // Some of the methods on this service provide streaming responses. // Provide descriptors for these. this.descriptors.stream = { - readRows: new this._gaxModule.StreamDescriptor(this._gaxModule.StreamType.SERVER_STREAMING, !!opts.fallback, !!opts.gaxServerStreamingRetries) + readRows: new this._gaxModule.StreamDescriptor( + this._gaxModule.StreamType.SERVER_STREAMING, + !!opts.fallback, + !!opts.gaxServerStreamingRetries, + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.cloud.bigquery.storage.v1beta1.BigQueryStorage', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.cloud.bigquery.storage.v1beta1.BigQueryStorage', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + { 'x-goog-api-client': clientHeader.join(' ') }, + ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -224,44 +254,59 @@ export class BigQueryStorageClient { // Put together the "service stub" for // google.cloud.bigquery.storage.v1beta1.BigQueryStorage. this.bigQueryStorageStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.cloud.bigquery.storage.v1beta1.BigQueryStorage') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any - (this._protos as any).google.cloud.bigquery.storage.v1beta1.BigQueryStorage, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.cloud.bigquery.storage.v1beta1.BigQueryStorage', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any + (this._protos as any).google.cloud.bigquery.storage.v1beta1 + .BigQueryStorage, + this._opts, + this._providedCustomServicePath, + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const bigQueryStorageStubMethods = - ['createReadSession', 'readRows', 'batchCreateReadSessionStreams', 'finalizeStream', 'splitReadStream']; + const bigQueryStorageStubMethods = [ + 'createReadSession', + 'readRows', + 'batchCreateReadSessionStreams', + 'finalizeStream', + 'splitReadStream', + ]; for (const methodName of bigQueryStorageStubMethods) { const callPromise = this.bigQueryStorageStub.then( - stub => (...args: Array<{}>) => { - if (this._terminated) { - if (methodName in this.descriptors.stream) { - const stream = new PassThrough({objectMode: true}); - setImmediate(() => { - stream.emit('error', new this._gaxModule.GoogleError('The client has already been closed.')); - }); - return stream; + (stub) => + (...args: Array<{}>) => { + if (this._terminated) { + if (methodName in this.descriptors.stream) { + const stream = new PassThrough({ objectMode: true }); + setImmediate(() => { + stream.emit( + 'error', + new this._gaxModule.GoogleError( + 'The client has already been closed.', + ), + ); + }); + return stream; + } + return Promise.reject('The client has already been closed.'); } - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error|null|undefined) => () => { + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { throw err; - }); + }, + ); - const descriptor = - this.descriptors.stream[methodName] || - undefined; + const descriptor = this.descriptors.stream[methodName] || undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -276,8 +321,14 @@ export class BigQueryStorageClient { * @returns {string} The DNS address for this service. */ static get servicePath() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'bigquerystorage.googleapis.com'; } @@ -288,8 +339,14 @@ export class BigQueryStorageClient { * @returns {string} The DNS address for this service. */ static get apiEndpoint() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'bigquerystorage.googleapis.com'; } @@ -323,7 +380,7 @@ export class BigQueryStorageClient { return [ 'https://www.googleapis.com/auth/bigquery', 'https://www.googleapis.com/auth/bigquery.readonly', - 'https://www.googleapis.com/auth/cloud-platform' + 'https://www.googleapis.com/auth/cloud-platform', ]; } @@ -333,8 +390,9 @@ export class BigQueryStorageClient { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId(callback?: Callback): - Promise|void { + getProjectId( + callback?: Callback, + ): Promise | void { if (callback) { this.auth.getProjectId(callback); return; @@ -345,496 +403,695 @@ export class BigQueryStorageClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Creates a new read session. A read session divides the contents of a - * BigQuery table into one or more streams, which can then be used to read - * data from the table. The read session also specifies properties of the - * data to be read, such as a list of columns or a push-down filter describing - * the rows to be returned. - * - * A particular row can be read by at most one stream. When the caller has - * reached the end of each stream in the session, then all the data in the - * table has been read. - * - * Read sessions automatically expire 24 hours after they are created and do - * not require manual clean-up by the caller. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.cloud.bigquery.storage.v1beta1.TableReference} request.tableReference - * Required. Reference to the table to read. - * @param {string} request.parent - * Required. String of the form `projects/{project_id}` indicating the - * project this ReadSession is associated with. This is the project that will - * be billed for usage. - * @param {google.cloud.bigquery.storage.v1beta1.TableModifiers} request.tableModifiers - * Any modifiers to the Table (e.g. snapshot timestamp). - * @param {number} request.requestedStreams - * Initial number of streams. If unset or 0, we will - * provide a value of streams so as to produce reasonable throughput. Must be - * non-negative. The number of streams may be lower than the requested number, - * depending on the amount parallelism that is reasonable for the table and - * the maximum amount of parallelism allowed by the system. - * - * Streams must be read starting from offset 0. - * @param {google.cloud.bigquery.storage.v1beta1.TableReadOptions} request.readOptions - * Read options for this session (e.g. column selection, filters). - * @param {google.cloud.bigquery.storage.v1beta1.DataFormat} request.format - * Data output format. Currently default to Avro. - * @param {google.cloud.bigquery.storage.v1beta1.ShardingStrategy} request.shardingStrategy - * The strategy to use for distributing data among multiple streams. Currently - * defaults to liquid sharding. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.bigquery.storage.v1beta1.ReadSession|ReadSession}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/big_query_storage.create_read_session.js - * region_tag:bigquerystorage_v1beta1_generated_BigQueryStorage_CreateReadSession_async - */ + /** + * Creates a new read session. A read session divides the contents of a + * BigQuery table into one or more streams, which can then be used to read + * data from the table. The read session also specifies properties of the + * data to be read, such as a list of columns or a push-down filter describing + * the rows to be returned. + * + * A particular row can be read by at most one stream. When the caller has + * reached the end of each stream in the session, then all the data in the + * table has been read. + * + * Read sessions automatically expire 24 hours after they are created and do + * not require manual clean-up by the caller. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.cloud.bigquery.storage.v1beta1.TableReference} request.tableReference + * Required. Reference to the table to read. + * @param {string} request.parent + * Required. String of the form `projects/{project_id}` indicating the + * project this ReadSession is associated with. This is the project that will + * be billed for usage. + * @param {google.cloud.bigquery.storage.v1beta1.TableModifiers} request.tableModifiers + * Any modifiers to the Table (e.g. snapshot timestamp). + * @param {number} request.requestedStreams + * Initial number of streams. If unset or 0, we will + * provide a value of streams so as to produce reasonable throughput. Must be + * non-negative. The number of streams may be lower than the requested number, + * depending on the amount parallelism that is reasonable for the table and + * the maximum amount of parallelism allowed by the system. + * + * Streams must be read starting from offset 0. + * @param {google.cloud.bigquery.storage.v1beta1.TableReadOptions} request.readOptions + * Read options for this session (e.g. column selection, filters). + * @param {google.cloud.bigquery.storage.v1beta1.DataFormat} request.format + * Data output format. Currently default to Avro. + * @param {google.cloud.bigquery.storage.v1beta1.ShardingStrategy} request.shardingStrategy + * The strategy to use for distributing data among multiple streams. Currently + * defaults to liquid sharding. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.bigquery.storage.v1beta1.ReadSession|ReadSession}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/big_query_storage.create_read_session.js + * region_tag:bigquerystorage_v1beta1_generated_BigQueryStorage_CreateReadSession_async + */ createReadSession( - request?: protos.google.cloud.bigquery.storage.v1beta1.ICreateReadSessionRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.bigquery.storage.v1beta1.IReadSession, - protos.google.cloud.bigquery.storage.v1beta1.ICreateReadSessionRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.bigquery.storage.v1beta1.ICreateReadSessionRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.bigquery.storage.v1beta1.IReadSession, + ( + | protos.google.cloud.bigquery.storage.v1beta1.ICreateReadSessionRequest + | undefined + ), + {} | undefined, + ] + >; createReadSession( - request: protos.google.cloud.bigquery.storage.v1beta1.ICreateReadSessionRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.bigquery.storage.v1beta1.IReadSession, - protos.google.cloud.bigquery.storage.v1beta1.ICreateReadSessionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.bigquery.storage.v1beta1.ICreateReadSessionRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.bigquery.storage.v1beta1.IReadSession, + | protos.google.cloud.bigquery.storage.v1beta1.ICreateReadSessionRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createReadSession( - request: protos.google.cloud.bigquery.storage.v1beta1.ICreateReadSessionRequest, - callback: Callback< - protos.google.cloud.bigquery.storage.v1beta1.IReadSession, - protos.google.cloud.bigquery.storage.v1beta1.ICreateReadSessionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.bigquery.storage.v1beta1.ICreateReadSessionRequest, + callback: Callback< + protos.google.cloud.bigquery.storage.v1beta1.IReadSession, + | protos.google.cloud.bigquery.storage.v1beta1.ICreateReadSessionRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createReadSession( - request?: protos.google.cloud.bigquery.storage.v1beta1.ICreateReadSessionRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.bigquery.storage.v1beta1.IReadSession, - protos.google.cloud.bigquery.storage.v1beta1.ICreateReadSessionRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.bigquery.storage.v1beta1.ICreateReadSessionRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.bigquery.storage.v1beta1.IReadSession, - protos.google.cloud.bigquery.storage.v1beta1.ICreateReadSessionRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.bigquery.storage.v1beta1.IReadSession, - protos.google.cloud.bigquery.storage.v1beta1.ICreateReadSessionRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.bigquery.storage.v1beta1.ICreateReadSessionRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.bigquery.storage.v1beta1.IReadSession, + | protos.google.cloud.bigquery.storage.v1beta1.ICreateReadSessionRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.bigquery.storage.v1beta1.IReadSession, + ( + | protos.google.cloud.bigquery.storage.v1beta1.ICreateReadSessionRequest + | undefined + ), + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'table_reference.project_id': request.tableReference!.projectId?.toString() ?? '', - 'table_reference.dataset_id': request.tableReference!.datasetId?.toString() ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'table_reference.project_id': + request.tableReference!.projectId?.toString() ?? '', + 'table_reference.dataset_id': + request.tableReference!.datasetId?.toString() ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('createReadSession request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.bigquery.storage.v1beta1.IReadSession, - protos.google.cloud.bigquery.storage.v1beta1.ICreateReadSessionRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.bigquery.storage.v1beta1.IReadSession, + | protos.google.cloud.bigquery.storage.v1beta1.ICreateReadSessionRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createReadSession response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.createReadSession(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.bigquery.storage.v1beta1.IReadSession, - protos.google.cloud.bigquery.storage.v1beta1.ICreateReadSessionRequest|undefined, - {}|undefined - ]) => { - this._log.info('createReadSession response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createReadSession(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.bigquery.storage.v1beta1.IReadSession, + ( + | protos.google.cloud.bigquery.storage.v1beta1.ICreateReadSessionRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('createReadSession response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Creates additional streams for a ReadSession. This API can be used to - * dynamically adjust the parallelism of a batch processing task upwards by - * adding additional workers. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.cloud.bigquery.storage.v1beta1.ReadSession} request.session - * Required. Must be a non-expired session obtained from a call to - * CreateReadSession. Only the name field needs to be set. - * @param {number} request.requestedStreams - * Required. Number of new streams requested. Must be positive. - * Number of added streams may be less than this, see CreateReadSessionRequest - * for more information. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.bigquery.storage.v1beta1.BatchCreateReadSessionStreamsResponse|BatchCreateReadSessionStreamsResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/big_query_storage.batch_create_read_session_streams.js - * region_tag:bigquerystorage_v1beta1_generated_BigQueryStorage_BatchCreateReadSessionStreams_async - */ + /** + * Creates additional streams for a ReadSession. This API can be used to + * dynamically adjust the parallelism of a batch processing task upwards by + * adding additional workers. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.cloud.bigquery.storage.v1beta1.ReadSession} request.session + * Required. Must be a non-expired session obtained from a call to + * CreateReadSession. Only the name field needs to be set. + * @param {number} request.requestedStreams + * Required. Number of new streams requested. Must be positive. + * Number of added streams may be less than this, see CreateReadSessionRequest + * for more information. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.bigquery.storage.v1beta1.BatchCreateReadSessionStreamsResponse|BatchCreateReadSessionStreamsResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/big_query_storage.batch_create_read_session_streams.js + * region_tag:bigquerystorage_v1beta1_generated_BigQueryStorage_BatchCreateReadSessionStreams_async + */ batchCreateReadSessionStreams( - request?: protos.google.cloud.bigquery.storage.v1beta1.IBatchCreateReadSessionStreamsRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.bigquery.storage.v1beta1.IBatchCreateReadSessionStreamsResponse, - protos.google.cloud.bigquery.storage.v1beta1.IBatchCreateReadSessionStreamsRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.bigquery.storage.v1beta1.IBatchCreateReadSessionStreamsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.bigquery.storage.v1beta1.IBatchCreateReadSessionStreamsResponse, + ( + | protos.google.cloud.bigquery.storage.v1beta1.IBatchCreateReadSessionStreamsRequest + | undefined + ), + {} | undefined, + ] + >; batchCreateReadSessionStreams( - request: protos.google.cloud.bigquery.storage.v1beta1.IBatchCreateReadSessionStreamsRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.bigquery.storage.v1beta1.IBatchCreateReadSessionStreamsResponse, - protos.google.cloud.bigquery.storage.v1beta1.IBatchCreateReadSessionStreamsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.bigquery.storage.v1beta1.IBatchCreateReadSessionStreamsRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.bigquery.storage.v1beta1.IBatchCreateReadSessionStreamsResponse, + | protos.google.cloud.bigquery.storage.v1beta1.IBatchCreateReadSessionStreamsRequest + | null + | undefined, + {} | null | undefined + >, + ): void; batchCreateReadSessionStreams( - request: protos.google.cloud.bigquery.storage.v1beta1.IBatchCreateReadSessionStreamsRequest, - callback: Callback< - protos.google.cloud.bigquery.storage.v1beta1.IBatchCreateReadSessionStreamsResponse, - protos.google.cloud.bigquery.storage.v1beta1.IBatchCreateReadSessionStreamsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.bigquery.storage.v1beta1.IBatchCreateReadSessionStreamsRequest, + callback: Callback< + protos.google.cloud.bigquery.storage.v1beta1.IBatchCreateReadSessionStreamsResponse, + | protos.google.cloud.bigquery.storage.v1beta1.IBatchCreateReadSessionStreamsRequest + | null + | undefined, + {} | null | undefined + >, + ): void; batchCreateReadSessionStreams( - request?: protos.google.cloud.bigquery.storage.v1beta1.IBatchCreateReadSessionStreamsRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.bigquery.storage.v1beta1.IBatchCreateReadSessionStreamsResponse, - protos.google.cloud.bigquery.storage.v1beta1.IBatchCreateReadSessionStreamsRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.bigquery.storage.v1beta1.IBatchCreateReadSessionStreamsRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.bigquery.storage.v1beta1.IBatchCreateReadSessionStreamsResponse, - protos.google.cloud.bigquery.storage.v1beta1.IBatchCreateReadSessionStreamsRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.bigquery.storage.v1beta1.IBatchCreateReadSessionStreamsResponse, - protos.google.cloud.bigquery.storage.v1beta1.IBatchCreateReadSessionStreamsRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.bigquery.storage.v1beta1.IBatchCreateReadSessionStreamsRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.bigquery.storage.v1beta1.IBatchCreateReadSessionStreamsResponse, + | protos.google.cloud.bigquery.storage.v1beta1.IBatchCreateReadSessionStreamsRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.bigquery.storage.v1beta1.IBatchCreateReadSessionStreamsResponse, + ( + | protos.google.cloud.bigquery.storage.v1beta1.IBatchCreateReadSessionStreamsRequest + | undefined + ), + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'session.name': request.session!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'session.name': request.session!.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('batchCreateReadSessionStreams request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.bigquery.storage.v1beta1.IBatchCreateReadSessionStreamsResponse, - protos.google.cloud.bigquery.storage.v1beta1.IBatchCreateReadSessionStreamsRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.bigquery.storage.v1beta1.IBatchCreateReadSessionStreamsResponse, + | protos.google.cloud.bigquery.storage.v1beta1.IBatchCreateReadSessionStreamsRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('batchCreateReadSessionStreams response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.batchCreateReadSessionStreams(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.bigquery.storage.v1beta1.IBatchCreateReadSessionStreamsResponse, - protos.google.cloud.bigquery.storage.v1beta1.IBatchCreateReadSessionStreamsRequest|undefined, - {}|undefined - ]) => { - this._log.info('batchCreateReadSessionStreams response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .batchCreateReadSessionStreams(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.bigquery.storage.v1beta1.IBatchCreateReadSessionStreamsResponse, + ( + | protos.google.cloud.bigquery.storage.v1beta1.IBatchCreateReadSessionStreamsRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('batchCreateReadSessionStreams response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Triggers the graceful termination of a single stream in a ReadSession. This - * API can be used to dynamically adjust the parallelism of a batch processing - * task downwards without losing data. - * - * This API does not delete the stream -- it remains visible in the - * ReadSession, and any data processed by the stream is not released to other - * streams. However, no additional data will be assigned to the stream once - * this call completes. Callers must continue reading data on the stream until - * the end of the stream is reached so that data which has already been - * assigned to the stream will be processed. - * - * This method will return an error if there are no other live streams - * in the Session, or if SplitReadStream() has been called on the given - * Stream. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.cloud.bigquery.storage.v1beta1.Stream} request.stream - * Stream to finalize. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/big_query_storage.finalize_stream.js - * region_tag:bigquerystorage_v1beta1_generated_BigQueryStorage_FinalizeStream_async - */ + /** + * Triggers the graceful termination of a single stream in a ReadSession. This + * API can be used to dynamically adjust the parallelism of a batch processing + * task downwards without losing data. + * + * This API does not delete the stream -- it remains visible in the + * ReadSession, and any data processed by the stream is not released to other + * streams. However, no additional data will be assigned to the stream once + * this call completes. Callers must continue reading data on the stream until + * the end of the stream is reached so that data which has already been + * assigned to the stream will be processed. + * + * This method will return an error if there are no other live streams + * in the Session, or if SplitReadStream() has been called on the given + * Stream. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.cloud.bigquery.storage.v1beta1.Stream} request.stream + * Stream to finalize. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/big_query_storage.finalize_stream.js + * region_tag:bigquerystorage_v1beta1_generated_BigQueryStorage_FinalizeStream_async + */ finalizeStream( - request?: protos.google.cloud.bigquery.storage.v1beta1.IFinalizeStreamRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.cloud.bigquery.storage.v1beta1.IFinalizeStreamRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.bigquery.storage.v1beta1.IFinalizeStreamRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.cloud.bigquery.storage.v1beta1.IFinalizeStreamRequest + | undefined + ), + {} | undefined, + ] + >; finalizeStream( - request: protos.google.cloud.bigquery.storage.v1beta1.IFinalizeStreamRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.cloud.bigquery.storage.v1beta1.IFinalizeStreamRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.bigquery.storage.v1beta1.IFinalizeStreamRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.cloud.bigquery.storage.v1beta1.IFinalizeStreamRequest + | null + | undefined, + {} | null | undefined + >, + ): void; finalizeStream( - request: protos.google.cloud.bigquery.storage.v1beta1.IFinalizeStreamRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.cloud.bigquery.storage.v1beta1.IFinalizeStreamRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.bigquery.storage.v1beta1.IFinalizeStreamRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.cloud.bigquery.storage.v1beta1.IFinalizeStreamRequest + | null + | undefined, + {} | null | undefined + >, + ): void; finalizeStream( - request?: protos.google.cloud.bigquery.storage.v1beta1.IFinalizeStreamRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.protobuf.IEmpty, - protos.google.cloud.bigquery.storage.v1beta1.IFinalizeStreamRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.bigquery.storage.v1beta1.IFinalizeStreamRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.cloud.bigquery.storage.v1beta1.IFinalizeStreamRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.cloud.bigquery.storage.v1beta1.IFinalizeStreamRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.bigquery.storage.v1beta1.IFinalizeStreamRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + | protos.google.cloud.bigquery.storage.v1beta1.IFinalizeStreamRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.cloud.bigquery.storage.v1beta1.IFinalizeStreamRequest + | undefined + ), + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'stream.name': request.stream!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'stream.name': request.stream!.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('finalizeStream request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.cloud.bigquery.storage.v1beta1.IFinalizeStreamRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.cloud.bigquery.storage.v1beta1.IFinalizeStreamRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('finalizeStream response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.finalizeStream(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.cloud.bigquery.storage.v1beta1.IFinalizeStreamRequest|undefined, - {}|undefined - ]) => { - this._log.info('finalizeStream response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .finalizeStream(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + ( + | protos.google.cloud.bigquery.storage.v1beta1.IFinalizeStreamRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('finalizeStream response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Splits a given read stream into two Streams. These streams are referred to - * as the primary and the residual of the split. The original stream can still - * be read from in the same manner as before. Both of the returned streams can - * also be read from, and the total rows return by both child streams will be - * the same as the rows read from the original stream. - * - * Moreover, the two child streams will be allocated back to back in the - * original Stream. Concretely, it is guaranteed that for streams Original, - * Primary, and Residual, that Original[0-j] = Primary[0-j] and - * Original[j-n] = Residual[0-m] once the streams have been read to - * completion. - * - * This method is guaranteed to be idempotent. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.cloud.bigquery.storage.v1beta1.Stream} request.originalStream - * Stream to split. - * @param {number} request.fraction - * A value in the range (0.0, 1.0) that specifies the fractional point at - * which the original stream should be split. The actual split point is - * evaluated on pre-filtered rows, so if a filter is provided, then there is - * no guarantee that the division of the rows between the new child streams - * will be proportional to this fractional value. Additionally, because the - * server-side unit for assigning data is collections of rows, this fraction - * will always map to to a data storage boundary on the server side. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.bigquery.storage.v1beta1.SplitReadStreamResponse|SplitReadStreamResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/big_query_storage.split_read_stream.js - * region_tag:bigquerystorage_v1beta1_generated_BigQueryStorage_SplitReadStream_async - */ + /** + * Splits a given read stream into two Streams. These streams are referred to + * as the primary and the residual of the split. The original stream can still + * be read from in the same manner as before. Both of the returned streams can + * also be read from, and the total rows return by both child streams will be + * the same as the rows read from the original stream. + * + * Moreover, the two child streams will be allocated back to back in the + * original Stream. Concretely, it is guaranteed that for streams Original, + * Primary, and Residual, that Original[0-j] = Primary[0-j] and + * Original[j-n] = Residual[0-m] once the streams have been read to + * completion. + * + * This method is guaranteed to be idempotent. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.cloud.bigquery.storage.v1beta1.Stream} request.originalStream + * Stream to split. + * @param {number} request.fraction + * A value in the range (0.0, 1.0) that specifies the fractional point at + * which the original stream should be split. The actual split point is + * evaluated on pre-filtered rows, so if a filter is provided, then there is + * no guarantee that the division of the rows between the new child streams + * will be proportional to this fractional value. Additionally, because the + * server-side unit for assigning data is collections of rows, this fraction + * will always map to to a data storage boundary on the server side. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.bigquery.storage.v1beta1.SplitReadStreamResponse|SplitReadStreamResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/big_query_storage.split_read_stream.js + * region_tag:bigquerystorage_v1beta1_generated_BigQueryStorage_SplitReadStream_async + */ splitReadStream( - request?: protos.google.cloud.bigquery.storage.v1beta1.ISplitReadStreamRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.bigquery.storage.v1beta1.ISplitReadStreamResponse, - protos.google.cloud.bigquery.storage.v1beta1.ISplitReadStreamRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.bigquery.storage.v1beta1.ISplitReadStreamRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.bigquery.storage.v1beta1.ISplitReadStreamResponse, + ( + | protos.google.cloud.bigquery.storage.v1beta1.ISplitReadStreamRequest + | undefined + ), + {} | undefined, + ] + >; splitReadStream( - request: protos.google.cloud.bigquery.storage.v1beta1.ISplitReadStreamRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.bigquery.storage.v1beta1.ISplitReadStreamResponse, - protos.google.cloud.bigquery.storage.v1beta1.ISplitReadStreamRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.bigquery.storage.v1beta1.ISplitReadStreamRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.bigquery.storage.v1beta1.ISplitReadStreamResponse, + | protos.google.cloud.bigquery.storage.v1beta1.ISplitReadStreamRequest + | null + | undefined, + {} | null | undefined + >, + ): void; splitReadStream( - request: protos.google.cloud.bigquery.storage.v1beta1.ISplitReadStreamRequest, - callback: Callback< - protos.google.cloud.bigquery.storage.v1beta1.ISplitReadStreamResponse, - protos.google.cloud.bigquery.storage.v1beta1.ISplitReadStreamRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.bigquery.storage.v1beta1.ISplitReadStreamRequest, + callback: Callback< + protos.google.cloud.bigquery.storage.v1beta1.ISplitReadStreamResponse, + | protos.google.cloud.bigquery.storage.v1beta1.ISplitReadStreamRequest + | null + | undefined, + {} | null | undefined + >, + ): void; splitReadStream( - request?: protos.google.cloud.bigquery.storage.v1beta1.ISplitReadStreamRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.bigquery.storage.v1beta1.ISplitReadStreamResponse, - protos.google.cloud.bigquery.storage.v1beta1.ISplitReadStreamRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.bigquery.storage.v1beta1.ISplitReadStreamRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.bigquery.storage.v1beta1.ISplitReadStreamResponse, - protos.google.cloud.bigquery.storage.v1beta1.ISplitReadStreamRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.bigquery.storage.v1beta1.ISplitReadStreamResponse, - protos.google.cloud.bigquery.storage.v1beta1.ISplitReadStreamRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.bigquery.storage.v1beta1.ISplitReadStreamRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.bigquery.storage.v1beta1.ISplitReadStreamResponse, + | protos.google.cloud.bigquery.storage.v1beta1.ISplitReadStreamRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.bigquery.storage.v1beta1.ISplitReadStreamResponse, + ( + | protos.google.cloud.bigquery.storage.v1beta1.ISplitReadStreamRequest + | undefined + ), + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'original_stream.name': request.originalStream!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'original_stream.name': request.originalStream!.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('splitReadStream request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.bigquery.storage.v1beta1.ISplitReadStreamResponse, - protos.google.cloud.bigquery.storage.v1beta1.ISplitReadStreamRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.bigquery.storage.v1beta1.ISplitReadStreamResponse, + | protos.google.cloud.bigquery.storage.v1beta1.ISplitReadStreamRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('splitReadStream response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.splitReadStream(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.bigquery.storage.v1beta1.ISplitReadStreamResponse, - protos.google.cloud.bigquery.storage.v1beta1.ISplitReadStreamRequest|undefined, - {}|undefined - ]) => { - this._log.info('splitReadStream response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .splitReadStream(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.bigquery.storage.v1beta1.ISplitReadStreamResponse, + ( + | protos.google.cloud.bigquery.storage.v1beta1.ISplitReadStreamRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('splitReadStream response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Reads rows from the table in the format prescribed by the read session. - * Each response contains one or more table rows, up to a maximum of 10 MiB - * per response; read requests which attempt to read individual rows larger - * than this will fail. - * - * Each request also returns a set of stream statistics reflecting the - * estimated total number of rows in the read stream. This number is computed - * based on the total table size and the number of active streams in the read - * session, and may change as other streams continue to read data. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.cloud.bigquery.storage.v1beta1.StreamPosition} request.readPosition - * Required. Identifier of the position in the stream to start reading from. - * The offset requested must be less than the last row read from ReadRows. - * Requesting a larger offset is undefined. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits {@link protos.google.cloud.bigquery.storage.v1beta1.ReadRowsResponse|ReadRowsResponse} on 'data' event. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#server-streaming | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/big_query_storage.read_rows.js - * region_tag:bigquerystorage_v1beta1_generated_BigQueryStorage_ReadRows_async - */ + /** + * Reads rows from the table in the format prescribed by the read session. + * Each response contains one or more table rows, up to a maximum of 10 MiB + * per response; read requests which attempt to read individual rows larger + * than this will fail. + * + * Each request also returns a set of stream statistics reflecting the + * estimated total number of rows in the read stream. This number is computed + * based on the total table size and the number of active streams in the read + * session, and may change as other streams continue to read data. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.cloud.bigquery.storage.v1beta1.StreamPosition} request.readPosition + * Required. Identifier of the position in the stream to start reading from. + * The offset requested must be less than the last row read from ReadRows. + * Requesting a larger offset is undefined. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits {@link protos.google.cloud.bigquery.storage.v1beta1.ReadRowsResponse|ReadRowsResponse} on 'data' event. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#server-streaming | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/big_query_storage.read_rows.js + * region_tag:bigquerystorage_v1beta1_generated_BigQueryStorage_ReadRows_async + */ readRows( - request?: protos.google.cloud.bigquery.storage.v1beta1.IReadRowsRequest, - options?: CallOptions): - gax.CancellableStream{ + request?: protos.google.cloud.bigquery.storage.v1beta1.IReadRowsRequest, + options?: CallOptions, + ): gax.CancellableStream { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'read_position.stream.name': request.readPosition!.stream!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'read_position.stream.name': request.readPosition!.stream!.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('readRows stream %j', options); return this.innerApiCalls.readRows(request, options); } @@ -851,7 +1108,7 @@ export class BigQueryStorageClient { * @param {string} session * @returns {string} Resource name string. */ - readSessionPath(project:string,location:string,session:string) { + readSessionPath(project: string, location: string, session: string) { return this.pathTemplates.readSessionPathTemplate.render({ project: project, location: location, @@ -867,7 +1124,8 @@ export class BigQueryStorageClient { * @returns {string} A string representing the project. */ matchProjectFromReadSessionName(readSessionName: string) { - return this.pathTemplates.readSessionPathTemplate.match(readSessionName).project; + return this.pathTemplates.readSessionPathTemplate.match(readSessionName) + .project; } /** @@ -878,7 +1136,8 @@ export class BigQueryStorageClient { * @returns {string} A string representing the location. */ matchLocationFromReadSessionName(readSessionName: string) { - return this.pathTemplates.readSessionPathTemplate.match(readSessionName).location; + return this.pathTemplates.readSessionPathTemplate.match(readSessionName) + .location; } /** @@ -889,7 +1148,8 @@ export class BigQueryStorageClient { * @returns {string} A string representing the session. */ matchSessionFromReadSessionName(readSessionName: string) { - return this.pathTemplates.readSessionPathTemplate.match(readSessionName).session; + return this.pathTemplates.readSessionPathTemplate.match(readSessionName) + .session; } /** @@ -900,7 +1160,7 @@ export class BigQueryStorageClient { * @param {string} stream * @returns {string} Resource name string. */ - streamPath(project:string,location:string,stream:string) { + streamPath(project: string, location: string, stream: string) { return this.pathTemplates.streamPathTemplate.render({ project: project, location: location, @@ -949,7 +1209,7 @@ export class BigQueryStorageClient { */ close(): Promise { if (this.bigQueryStorageStub && !this._terminated) { - return this.bigQueryStorageStub.then(stub => { + return this.bigQueryStorageStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -957,4 +1217,4 @@ export class BigQueryStorageClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/core/generator/gapic-generator-typescript/baselines/bigquery-storage/src/v1beta1/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/bigquery-storage/src/v1beta1/index.ts.baseline index 37968a0737d7..9a6dba62856b 100644 --- a/core/generator/gapic-generator-typescript/baselines/bigquery-storage/src/v1beta1/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/bigquery-storage/src/v1beta1/index.ts.baseline @@ -16,4 +16,4 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -export {BigQueryStorageClient} from './big_query_storage_client'; +export { BigQueryStorageClient } from './big_query_storage_client'; diff --git a/core/generator/gapic-generator-typescript/baselines/bigquery-storage/system-test/fixtures/sample/src/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/bigquery-storage/system-test/fixtures/sample/src/index.ts.baseline index fc714d834fb5..e7918f99efb5 100644 --- a/core/generator/gapic-generator-typescript/baselines/bigquery-storage/system-test/fixtures/sample/src/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/bigquery-storage/system-test/fixtures/sample/src/index.ts.baseline @@ -16,7 +16,7 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -import {BigQueryStorageClient} from 'storage'; +import { BigQueryStorageClient } from 'storage'; // check that the client class type name can be used function doStuffWithBigQueryStorageClient(client: BigQueryStorageClient) { diff --git a/core/generator/gapic-generator-typescript/baselines/bigquery-storage/system-test/install.ts.baseline b/core/generator/gapic-generator-typescript/baselines/bigquery-storage/system-test/install.ts.baseline index f66069aa3940..ccf167042d2e 100644 --- a/core/generator/gapic-generator-typescript/baselines/bigquery-storage/system-test/install.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/bigquery-storage/system-test/install.ts.baseline @@ -16,34 +16,36 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -import {packNTest} from 'pack-n-play'; -import {readFileSync} from 'fs'; -import {describe, it} from 'mocha'; +import { packNTest } from 'pack-n-play'; +import { readFileSync } from 'fs'; +import { describe, it } from 'mocha'; describe('📦 pack-n-play test', () => { - - it('TypeScript code', async function() { + it('TypeScript code', async function () { this.timeout(300000); const options = { packageDir: process.cwd(), sample: { description: 'TypeScript user can use the type definitions', - ts: readFileSync('./system-test/fixtures/sample/src/index.ts').toString() - } + ts: readFileSync( + './system-test/fixtures/sample/src/index.ts', + ).toString(), + }, }; await packNTest(options); }); - it('JavaScript code', async function() { + it('JavaScript code', async function () { this.timeout(300000); const options = { packageDir: process.cwd(), sample: { description: 'JavaScript user can use the library', - cjs: readFileSync('./system-test/fixtures/sample/src/index.js').toString() - } + cjs: readFileSync( + './system-test/fixtures/sample/src/index.js', + ).toString(), + }, }; await packNTest(options); }); - }); diff --git a/core/generator/gapic-generator-typescript/baselines/bigquery-storage/test/gapic_big_query_storage_v1beta1.ts.baseline b/core/generator/gapic-generator-typescript/baselines/bigquery-storage/test/gapic_big_query_storage_v1beta1.ts.baseline index 8e2bfb3d9e70..5cde5a4ec2e4 100644 --- a/core/generator/gapic-generator-typescript/baselines/bigquery-storage/test/gapic_big_query_storage_v1beta1.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/bigquery-storage/test/gapic_big_query_storage_v1beta1.ts.baseline @@ -19,917 +19,1160 @@ import * as protos from '../protos/protos'; import * as assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as bigquerystorageModule from '../src'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; -import {protobuf} from 'google-gax'; +import { protobuf } from 'google-gax'; // Dynamically loaded proto JSON is needed to get the type information // to fill in default values for request objects -const root = protobuf.Root.fromJSON(require('../protos/protos.json')).resolveAll(); +const root = protobuf.Root.fromJSON( + require('../protos/protos.json'), +).resolveAll(); // eslint-disable-next-line @typescript-eslint/no-unused-vars function getTypeDefaultValue(typeName: string, fields: string[]) { - let type = root.lookupType(typeName) as protobuf.Type; - for (const field of fields.slice(0, -1)) { - type = type.fields[field]?.resolvedType as protobuf.Type; - } - return type.fields[fields[fields.length - 1]]?.defaultValue; + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type.fields[field]?.resolvedType as protobuf.Type; + } + return type.fields[fields[fields.length - 1]]?.defaultValue; } function generateSampleMessage(instance: T) { - const filledObject = (instance.constructor as typeof protobuf.Message) - .toObject(instance as protobuf.Message, {defaults: true}); - return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, { defaults: true }); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; } function stubSimpleCall(response?: ResponseType, error?: Error) { - return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); } -function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { - return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +function stubSimpleCallWithCallback( + response?: ResponseType, + error?: Error, +) { + return error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); } -function stubServerStreamingCall(response?: ResponseType, error?: Error) { - const transformStub = error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); - const mockStream = new PassThrough({ - objectMode: true, - transform: transformStub, - }); - // write something to the stream to trigger transformStub and send the response back to the client - setImmediate(() => { mockStream.write({}); }); - setImmediate(() => { mockStream.end(); }); - return sinon.stub().returns(mockStream); +function stubServerStreamingCall( + response?: ResponseType, + error?: Error, +) { + const transformStub = error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + // write something to the stream to trigger transformStub and send the response back to the client + setImmediate(() => { + mockStream.write({}); + }); + setImmediate(() => { + mockStream.end(); + }); + return sinon.stub().returns(mockStream); } describe('v1beta1.BigQueryStorageClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'bigquerystorage.googleapis.com'); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'bigquerystorage.googleapis.com'); + }); - it('has universeDomain', () => { - const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); + it('has universeDomain', () => { + const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - it('throws DeprecationWarning if static servicePath is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const servicePath = bigquerystorageModule.v1beta1.BigQueryStorageClient.servicePath; - assert.strictEqual(servicePath, 'bigquerystorage.googleapis.com'); - assert(stub.called); - stub.restore(); - }); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = + bigquerystorageModule.v1beta1.BigQueryStorageClient.servicePath; + assert.strictEqual(servicePath, 'bigquerystorage.googleapis.com'); + assert(stub.called); + stub.restore(); + }); - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = bigquerystorageModule.v1beta1.BigQueryStorageClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'bigquerystorage.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'bigquerystorage.example.com'); - }); + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + bigquerystorageModule.v1beta1.BigQueryStorageClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'bigquerystorage.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ + universeDomain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'bigquerystorage.example.com'); + }); - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'bigquerystorage.example.com'); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ + universe_domain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'bigquerystorage.example.com'); + }); + + if (typeof process === 'object' && 'env' in process) { + describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { + it('sets apiEndpoint from environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = + new bigquerystorageModule.v1beta1.BigQueryStorageClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'bigquerystorage.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - if (typeof process === 'object' && 'env' in process) { - describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { - it('sets apiEndpoint from environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'bigquerystorage.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - - it('value configured in code has priority over environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'bigquerystorage.configured.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); + it('value configured in code has priority over environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = + new bigquerystorageModule.v1beta1.BigQueryStorageClient({ + universeDomain: 'configured.example.com', }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { new bigquerystorageModule.v1beta1.BigQueryStorageClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); + const servicePath = client.apiEndpoint; + assert.strictEqual( + servicePath, + 'bigquerystorage.configured.example.com', + ); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - - it('has port', () => { - const port = bigquerystorageModule.v1beta1.BigQueryStorageClient.port; - assert(port); - assert(typeof port === 'number'); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new bigquerystorageModule.v1beta1.BigQueryStorageClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); + }); - it('should create a client with no option', () => { - const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient(); - assert(client); - }); + it('has port', () => { + const port = bigquerystorageModule.v1beta1.BigQueryStorageClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('should create a client with gRPC fallback', () => { - const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ - fallback: true, - }); - assert(client); - }); + it('should create a client with no option', () => { + const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient(); + assert(client); + }); - it('has initialize method and supports deferred initialization', async () => { - const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.bigQueryStorageStub, undefined); - await client.initialize(); - assert(client.bigQueryStorageStub); - }); + it('should create a client with gRPC fallback', () => { + const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ + fallback: true, + }); + assert(client); + }); - it('has close method for the initialized client', done => { - const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.bigQueryStorageStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('has initialize method and supports deferred initialization', async () => { + const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.bigQueryStorageStub, undefined); + await client.initialize(); + assert(client.bigQueryStorageStub); + }); - it('has close method for the non-initialized client', done => { - const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.bigQueryStorageStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); + it('has close method for the initialized client', (done) => { + const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.bigQueryStorageStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + it('has close method for the non-initialized client', (done) => { + const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.bigQueryStorageStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId((err?: Error|null, projectId?: string|null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } - }); - }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); - }); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); }); - describe('createReadSession', () => { - it('invokes createReadSession without error', async () => { - const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.storage.v1beta1.CreateReadSessionRequest() - ); - request.tableReference ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.storage.v1beta1.CreateReadSessionRequest', ['tableReference', 'projectId']); - request.tableReference.projectId = defaultValue1; - request.tableReference ??= {}; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.storage.v1beta1.CreateReadSessionRequest', ['tableReference', 'datasetId']); - request.tableReference.datasetId = defaultValue2; - const expectedHeaderRequestParams = `table_reference.project_id=${defaultValue1 ?? '' }&table_reference.dataset_id=${defaultValue2 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.bigquery.storage.v1beta1.ReadSession() - ); - client.innerApiCalls.createReadSession = stubSimpleCall(expectedResponse); - const [response] = await client.createReadSession(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createReadSession as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createReadSession as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + }); - it('invokes createReadSession without error using callback', async () => { - const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.storage.v1beta1.CreateReadSessionRequest() - ); - request.tableReference ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.storage.v1beta1.CreateReadSessionRequest', ['tableReference', 'projectId']); - request.tableReference.projectId = defaultValue1; - request.tableReference ??= {}; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.storage.v1beta1.CreateReadSessionRequest', ['tableReference', 'datasetId']); - request.tableReference.datasetId = defaultValue2; - const expectedHeaderRequestParams = `table_reference.project_id=${defaultValue1 ?? '' }&table_reference.dataset_id=${defaultValue2 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.bigquery.storage.v1beta1.ReadSession() - ); - client.innerApiCalls.createReadSession = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createReadSession( - request, - (err?: Error|null, result?: protos.google.cloud.bigquery.storage.v1beta1.IReadSession|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createReadSession as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createReadSession as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + describe('createReadSession', () => { + it('invokes createReadSession without error', async () => { + const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.storage.v1beta1.CreateReadSessionRequest(), + ); + request.tableReference ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.storage.v1beta1.CreateReadSessionRequest', + ['tableReference', 'projectId'], + ); + request.tableReference.projectId = defaultValue1; + request.tableReference ??= {}; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.storage.v1beta1.CreateReadSessionRequest', + ['tableReference', 'datasetId'], + ); + request.tableReference.datasetId = defaultValue2; + const expectedHeaderRequestParams = `table_reference.project_id=${defaultValue1 ?? ''}&table_reference.dataset_id=${defaultValue2 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.bigquery.storage.v1beta1.ReadSession(), + ); + client.innerApiCalls.createReadSession = stubSimpleCall(expectedResponse); + const [response] = await client.createReadSession(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createReadSession as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createReadSession as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createReadSession with error', async () => { - const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.storage.v1beta1.CreateReadSessionRequest() - ); - request.tableReference ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.storage.v1beta1.CreateReadSessionRequest', ['tableReference', 'projectId']); - request.tableReference.projectId = defaultValue1; - request.tableReference ??= {}; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.storage.v1beta1.CreateReadSessionRequest', ['tableReference', 'datasetId']); - request.tableReference.datasetId = defaultValue2; - const expectedHeaderRequestParams = `table_reference.project_id=${defaultValue1 ?? '' }&table_reference.dataset_id=${defaultValue2 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createReadSession = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createReadSession(request), expectedError); - const actualRequest = (client.innerApiCalls.createReadSession as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createReadSession as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createReadSession without error using callback', async () => { + const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.storage.v1beta1.CreateReadSessionRequest(), + ); + request.tableReference ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.storage.v1beta1.CreateReadSessionRequest', + ['tableReference', 'projectId'], + ); + request.tableReference.projectId = defaultValue1; + request.tableReference ??= {}; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.storage.v1beta1.CreateReadSessionRequest', + ['tableReference', 'datasetId'], + ); + request.tableReference.datasetId = defaultValue2; + const expectedHeaderRequestParams = `table_reference.project_id=${defaultValue1 ?? ''}&table_reference.dataset_id=${defaultValue2 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.bigquery.storage.v1beta1.ReadSession(), + ); + client.innerApiCalls.createReadSession = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createReadSession( + request, + ( + err?: Error | null, + result?: protos.google.cloud.bigquery.storage.v1beta1.IReadSession | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createReadSession as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createReadSession as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createReadSession with closed client', async () => { - const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.storage.v1beta1.CreateReadSessionRequest() - ); - request.tableReference ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.storage.v1beta1.CreateReadSessionRequest', ['tableReference', 'projectId']); - request.tableReference.projectId = defaultValue1; - request.tableReference ??= {}; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.storage.v1beta1.CreateReadSessionRequest', ['tableReference', 'datasetId']); - request.tableReference.datasetId = defaultValue2; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createReadSession(request), expectedError); - }); + it('invokes createReadSession with error', async () => { + const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.storage.v1beta1.CreateReadSessionRequest(), + ); + request.tableReference ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.storage.v1beta1.CreateReadSessionRequest', + ['tableReference', 'projectId'], + ); + request.tableReference.projectId = defaultValue1; + request.tableReference ??= {}; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.storage.v1beta1.CreateReadSessionRequest', + ['tableReference', 'datasetId'], + ); + request.tableReference.datasetId = defaultValue2; + const expectedHeaderRequestParams = `table_reference.project_id=${defaultValue1 ?? ''}&table_reference.dataset_id=${defaultValue2 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createReadSession = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.createReadSession(request), expectedError); + const actualRequest = ( + client.innerApiCalls.createReadSession as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createReadSession as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('batchCreateReadSessionStreams', () => { - it('invokes batchCreateReadSessionStreams without error', async () => { - const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.storage.v1beta1.BatchCreateReadSessionStreamsRequest() - ); - request.session ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.storage.v1beta1.BatchCreateReadSessionStreamsRequest', ['session', 'name']); - request.session.name = defaultValue1; - const expectedHeaderRequestParams = `session.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.bigquery.storage.v1beta1.BatchCreateReadSessionStreamsResponse() - ); - client.innerApiCalls.batchCreateReadSessionStreams = stubSimpleCall(expectedResponse); - const [response] = await client.batchCreateReadSessionStreams(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.batchCreateReadSessionStreams as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.batchCreateReadSessionStreams as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createReadSession with closed client', async () => { + const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.storage.v1beta1.CreateReadSessionRequest(), + ); + request.tableReference ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.storage.v1beta1.CreateReadSessionRequest', + ['tableReference', 'projectId'], + ); + request.tableReference.projectId = defaultValue1; + request.tableReference ??= {}; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.storage.v1beta1.CreateReadSessionRequest', + ['tableReference', 'datasetId'], + ); + request.tableReference.datasetId = defaultValue2; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.createReadSession(request), expectedError); + }); + }); - it('invokes batchCreateReadSessionStreams without error using callback', async () => { - const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.storage.v1beta1.BatchCreateReadSessionStreamsRequest() - ); - request.session ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.storage.v1beta1.BatchCreateReadSessionStreamsRequest', ['session', 'name']); - request.session.name = defaultValue1; - const expectedHeaderRequestParams = `session.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.bigquery.storage.v1beta1.BatchCreateReadSessionStreamsResponse() - ); - client.innerApiCalls.batchCreateReadSessionStreams = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.batchCreateReadSessionStreams( - request, - (err?: Error|null, result?: protos.google.cloud.bigquery.storage.v1beta1.IBatchCreateReadSessionStreamsResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.batchCreateReadSessionStreams as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.batchCreateReadSessionStreams as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + describe('batchCreateReadSessionStreams', () => { + it('invokes batchCreateReadSessionStreams without error', async () => { + const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.storage.v1beta1.BatchCreateReadSessionStreamsRequest(), + ); + request.session ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.storage.v1beta1.BatchCreateReadSessionStreamsRequest', + ['session', 'name'], + ); + request.session.name = defaultValue1; + const expectedHeaderRequestParams = `session.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.bigquery.storage.v1beta1.BatchCreateReadSessionStreamsResponse(), + ); + client.innerApiCalls.batchCreateReadSessionStreams = + stubSimpleCall(expectedResponse); + const [response] = await client.batchCreateReadSessionStreams(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.batchCreateReadSessionStreams as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.batchCreateReadSessionStreams as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes batchCreateReadSessionStreams with error', async () => { - const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.storage.v1beta1.BatchCreateReadSessionStreamsRequest() - ); - request.session ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.storage.v1beta1.BatchCreateReadSessionStreamsRequest', ['session', 'name']); - request.session.name = defaultValue1; - const expectedHeaderRequestParams = `session.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.batchCreateReadSessionStreams = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.batchCreateReadSessionStreams(request), expectedError); - const actualRequest = (client.innerApiCalls.batchCreateReadSessionStreams as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.batchCreateReadSessionStreams as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes batchCreateReadSessionStreams without error using callback', async () => { + const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.storage.v1beta1.BatchCreateReadSessionStreamsRequest(), + ); + request.session ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.storage.v1beta1.BatchCreateReadSessionStreamsRequest', + ['session', 'name'], + ); + request.session.name = defaultValue1; + const expectedHeaderRequestParams = `session.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.bigquery.storage.v1beta1.BatchCreateReadSessionStreamsResponse(), + ); + client.innerApiCalls.batchCreateReadSessionStreams = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.batchCreateReadSessionStreams( + request, + ( + err?: Error | null, + result?: protos.google.cloud.bigquery.storage.v1beta1.IBatchCreateReadSessionStreamsResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.batchCreateReadSessionStreams as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.batchCreateReadSessionStreams as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes batchCreateReadSessionStreams with closed client', async () => { - const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.storage.v1beta1.BatchCreateReadSessionStreamsRequest() - ); - request.session ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.storage.v1beta1.BatchCreateReadSessionStreamsRequest', ['session', 'name']); - request.session.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.batchCreateReadSessionStreams(request), expectedError); - }); + it('invokes batchCreateReadSessionStreams with error', async () => { + const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.storage.v1beta1.BatchCreateReadSessionStreamsRequest(), + ); + request.session ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.storage.v1beta1.BatchCreateReadSessionStreamsRequest', + ['session', 'name'], + ); + request.session.name = defaultValue1; + const expectedHeaderRequestParams = `session.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.batchCreateReadSessionStreams = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.batchCreateReadSessionStreams(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.batchCreateReadSessionStreams as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.batchCreateReadSessionStreams as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('finalizeStream', () => { - it('invokes finalizeStream without error', async () => { - const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.storage.v1beta1.FinalizeStreamRequest() - ); - request.stream ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.storage.v1beta1.FinalizeStreamRequest', ['stream', 'name']); - request.stream.name = defaultValue1; - const expectedHeaderRequestParams = `stream.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.finalizeStream = stubSimpleCall(expectedResponse); - const [response] = await client.finalizeStream(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.finalizeStream as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.finalizeStream as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes batchCreateReadSessionStreams with closed client', async () => { + const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.storage.v1beta1.BatchCreateReadSessionStreamsRequest(), + ); + request.session ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.storage.v1beta1.BatchCreateReadSessionStreamsRequest', + ['session', 'name'], + ); + request.session.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.batchCreateReadSessionStreams(request), + expectedError, + ); + }); + }); - it('invokes finalizeStream without error using callback', async () => { - const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.storage.v1beta1.FinalizeStreamRequest() - ); - request.stream ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.storage.v1beta1.FinalizeStreamRequest', ['stream', 'name']); - request.stream.name = defaultValue1; - const expectedHeaderRequestParams = `stream.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.finalizeStream = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.finalizeStream( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.finalizeStream as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.finalizeStream as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + describe('finalizeStream', () => { + it('invokes finalizeStream without error', async () => { + const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.storage.v1beta1.FinalizeStreamRequest(), + ); + request.stream ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.storage.v1beta1.FinalizeStreamRequest', + ['stream', 'name'], + ); + request.stream.name = defaultValue1; + const expectedHeaderRequestParams = `stream.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.finalizeStream = stubSimpleCall(expectedResponse); + const [response] = await client.finalizeStream(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.finalizeStream as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.finalizeStream as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes finalizeStream with error', async () => { - const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.storage.v1beta1.FinalizeStreamRequest() - ); - request.stream ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.storage.v1beta1.FinalizeStreamRequest', ['stream', 'name']); - request.stream.name = defaultValue1; - const expectedHeaderRequestParams = `stream.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.finalizeStream = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.finalizeStream(request), expectedError); - const actualRequest = (client.innerApiCalls.finalizeStream as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.finalizeStream as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes finalizeStream without error using callback', async () => { + const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.storage.v1beta1.FinalizeStreamRequest(), + ); + request.stream ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.storage.v1beta1.FinalizeStreamRequest', + ['stream', 'name'], + ); + request.stream.name = defaultValue1; + const expectedHeaderRequestParams = `stream.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.finalizeStream = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.finalizeStream( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.finalizeStream as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.finalizeStream as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes finalizeStream with closed client', async () => { - const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.storage.v1beta1.FinalizeStreamRequest() - ); - request.stream ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.storage.v1beta1.FinalizeStreamRequest', ['stream', 'name']); - request.stream.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.finalizeStream(request), expectedError); - }); + it('invokes finalizeStream with error', async () => { + const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.storage.v1beta1.FinalizeStreamRequest(), + ); + request.stream ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.storage.v1beta1.FinalizeStreamRequest', + ['stream', 'name'], + ); + request.stream.name = defaultValue1; + const expectedHeaderRequestParams = `stream.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.finalizeStream = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.finalizeStream(request), expectedError); + const actualRequest = ( + client.innerApiCalls.finalizeStream as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.finalizeStream as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('splitReadStream', () => { - it('invokes splitReadStream without error', async () => { - const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.storage.v1beta1.SplitReadStreamRequest() - ); - request.originalStream ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.storage.v1beta1.SplitReadStreamRequest', ['originalStream', 'name']); - request.originalStream.name = defaultValue1; - const expectedHeaderRequestParams = `original_stream.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.bigquery.storage.v1beta1.SplitReadStreamResponse() - ); - client.innerApiCalls.splitReadStream = stubSimpleCall(expectedResponse); - const [response] = await client.splitReadStream(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.splitReadStream as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.splitReadStream as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes finalizeStream with closed client', async () => { + const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.storage.v1beta1.FinalizeStreamRequest(), + ); + request.stream ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.storage.v1beta1.FinalizeStreamRequest', + ['stream', 'name'], + ); + request.stream.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.finalizeStream(request), expectedError); + }); + }); - it('invokes splitReadStream without error using callback', async () => { - const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.storage.v1beta1.SplitReadStreamRequest() - ); - request.originalStream ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.storage.v1beta1.SplitReadStreamRequest', ['originalStream', 'name']); - request.originalStream.name = defaultValue1; - const expectedHeaderRequestParams = `original_stream.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.bigquery.storage.v1beta1.SplitReadStreamResponse() - ); - client.innerApiCalls.splitReadStream = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.splitReadStream( - request, - (err?: Error|null, result?: protos.google.cloud.bigquery.storage.v1beta1.ISplitReadStreamResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.splitReadStream as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.splitReadStream as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + describe('splitReadStream', () => { + it('invokes splitReadStream without error', async () => { + const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.storage.v1beta1.SplitReadStreamRequest(), + ); + request.originalStream ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.storage.v1beta1.SplitReadStreamRequest', + ['originalStream', 'name'], + ); + request.originalStream.name = defaultValue1; + const expectedHeaderRequestParams = `original_stream.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.bigquery.storage.v1beta1.SplitReadStreamResponse(), + ); + client.innerApiCalls.splitReadStream = stubSimpleCall(expectedResponse); + const [response] = await client.splitReadStream(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.splitReadStream as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.splitReadStream as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes splitReadStream with error', async () => { - const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.storage.v1beta1.SplitReadStreamRequest() - ); - request.originalStream ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.storage.v1beta1.SplitReadStreamRequest', ['originalStream', 'name']); - request.originalStream.name = defaultValue1; - const expectedHeaderRequestParams = `original_stream.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.splitReadStream = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.splitReadStream(request), expectedError); - const actualRequest = (client.innerApiCalls.splitReadStream as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.splitReadStream as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes splitReadStream without error using callback', async () => { + const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.storage.v1beta1.SplitReadStreamRequest(), + ); + request.originalStream ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.storage.v1beta1.SplitReadStreamRequest', + ['originalStream', 'name'], + ); + request.originalStream.name = defaultValue1; + const expectedHeaderRequestParams = `original_stream.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.bigquery.storage.v1beta1.SplitReadStreamResponse(), + ); + client.innerApiCalls.splitReadStream = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.splitReadStream( + request, + ( + err?: Error | null, + result?: protos.google.cloud.bigquery.storage.v1beta1.ISplitReadStreamResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.splitReadStream as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.splitReadStream as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes splitReadStream with closed client', async () => { - const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.storage.v1beta1.SplitReadStreamRequest() - ); - request.originalStream ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.storage.v1beta1.SplitReadStreamRequest', ['originalStream', 'name']); - request.originalStream.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.splitReadStream(request), expectedError); - }); + it('invokes splitReadStream with error', async () => { + const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.storage.v1beta1.SplitReadStreamRequest(), + ); + request.originalStream ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.storage.v1beta1.SplitReadStreamRequest', + ['originalStream', 'name'], + ); + request.originalStream.name = defaultValue1; + const expectedHeaderRequestParams = `original_stream.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.splitReadStream = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.splitReadStream(request), expectedError); + const actualRequest = ( + client.innerApiCalls.splitReadStream as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.splitReadStream as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('readRows', () => { - it('invokes readRows without error', async () => { - const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.storage.v1beta1.ReadRowsRequest() - ); - request.readPosition ??= {}; - request.readPosition.stream ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.storage.v1beta1.ReadRowsRequest', ['readPosition', 'stream', 'name']); - request.readPosition.stream.name = defaultValue1; - const expectedHeaderRequestParams = `read_position.stream.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.bigquery.storage.v1beta1.ReadRowsResponse() - ); - client.innerApiCalls.readRows = stubServerStreamingCall(expectedResponse); - const stream = client.readRows(request); - const promise = new Promise((resolve, reject) => { - stream.on('data', (response: protos.google.cloud.bigquery.storage.v1beta1.ReadRowsResponse) => { - resolve(response); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.readRows as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.readRows as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes splitReadStream with closed client', async () => { + const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.storage.v1beta1.SplitReadStreamRequest(), + ); + request.originalStream ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.storage.v1beta1.SplitReadStreamRequest', + ['originalStream', 'name'], + ); + request.originalStream.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.splitReadStream(request), expectedError); + }); + }); - it('invokes readRows without error and gaxServerStreamingRetries enabled', async () => { - const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - gaxServerStreamingRetries: true - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.storage.v1beta1.ReadRowsRequest() - ); - request.readPosition ??= {}; - request.readPosition.stream ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.storage.v1beta1.ReadRowsRequest', ['readPosition', 'stream', 'name']); - request.readPosition.stream.name = defaultValue1; - const expectedHeaderRequestParams = `read_position.stream.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.bigquery.storage.v1beta1.ReadRowsResponse() - ); - client.innerApiCalls.readRows = stubServerStreamingCall(expectedResponse); - const stream = client.readRows(request); - const promise = new Promise((resolve, reject) => { - stream.on('data', (response: protos.google.cloud.bigquery.storage.v1beta1.ReadRowsResponse) => { - resolve(response); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.readRows as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.readRows as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + describe('readRows', () => { + it('invokes readRows without error', async () => { + const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.storage.v1beta1.ReadRowsRequest(), + ); + request.readPosition ??= {}; + request.readPosition.stream ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.storage.v1beta1.ReadRowsRequest', + ['readPosition', 'stream', 'name'], + ); + request.readPosition.stream.name = defaultValue1; + const expectedHeaderRequestParams = `read_position.stream.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.bigquery.storage.v1beta1.ReadRowsResponse(), + ); + client.innerApiCalls.readRows = stubServerStreamingCall(expectedResponse); + const stream = client.readRows(request); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + ( + response: protos.google.cloud.bigquery.storage.v1beta1.ReadRowsResponse, + ) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.readRows as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.readRows as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes readRows with error', async () => { - const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.storage.v1beta1.ReadRowsRequest() - ); - request.readPosition ??= {}; - request.readPosition.stream ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.storage.v1beta1.ReadRowsRequest', ['readPosition', 'stream', 'name']); - request.readPosition.stream.name = defaultValue1; - const expectedHeaderRequestParams = `read_position.stream.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.readRows = stubServerStreamingCall(undefined, expectedError); - const stream = client.readRows(request); - const promise = new Promise((resolve, reject) => { - stream.on('data', (response: protos.google.cloud.bigquery.storage.v1beta1.ReadRowsResponse) => { - resolve(response); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - const actualRequest = (client.innerApiCalls.readRows as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.readRows as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes readRows without error and gaxServerStreamingRetries enabled', async () => { + const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + gaxServerStreamingRetries: true, + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.storage.v1beta1.ReadRowsRequest(), + ); + request.readPosition ??= {}; + request.readPosition.stream ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.storage.v1beta1.ReadRowsRequest', + ['readPosition', 'stream', 'name'], + ); + request.readPosition.stream.name = defaultValue1; + const expectedHeaderRequestParams = `read_position.stream.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.bigquery.storage.v1beta1.ReadRowsResponse(), + ); + client.innerApiCalls.readRows = stubServerStreamingCall(expectedResponse); + const stream = client.readRows(request); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + ( + response: protos.google.cloud.bigquery.storage.v1beta1.ReadRowsResponse, + ) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.readRows as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.readRows as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes readRows with closed client', async () => { - const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.storage.v1beta1.ReadRowsRequest() - ); - request.readPosition ??= {}; - request.readPosition.stream ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.storage.v1beta1.ReadRowsRequest', ['readPosition', 'stream', 'name']); - request.readPosition.stream.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - const stream = client.readRows(request, {retryRequestOptions: {noResponseRetries: 0}}); - const promise = new Promise((resolve, reject) => { - stream.on('data', (response: protos.google.cloud.bigquery.storage.v1beta1.ReadRowsResponse) => { - resolve(response); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); + it('invokes readRows with error', async () => { + const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.storage.v1beta1.ReadRowsRequest(), + ); + request.readPosition ??= {}; + request.readPosition.stream ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.storage.v1beta1.ReadRowsRequest', + ['readPosition', 'stream', 'name'], + ); + request.readPosition.stream.name = defaultValue1; + const expectedHeaderRequestParams = `read_position.stream.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.readRows = stubServerStreamingCall( + undefined, + expectedError, + ); + const stream = client.readRows(request); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + ( + response: protos.google.cloud.bigquery.storage.v1beta1.ReadRowsResponse, + ) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); }); - it('should create a client with gaxServerStreamingRetries enabled', () => { - const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ - gaxServerStreamingRetries: true, - }); - assert(client); + }); + await assert.rejects(promise, expectedError); + const actualRequest = ( + client.innerApiCalls.readRows as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.readRows as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes readRows with closed client', async () => { + const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.storage.v1beta1.ReadRowsRequest(), + ); + request.readPosition ??= {}; + request.readPosition.stream ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.storage.v1beta1.ReadRowsRequest', + ['readPosition', 'stream', 'name'], + ); + request.readPosition.stream.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + const stream = client.readRows(request, { + retryRequestOptions: { noResponseRetries: 0 }, + }); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + ( + response: protos.google.cloud.bigquery.storage.v1beta1.ReadRowsResponse, + ) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); }); + }); + await assert.rejects(promise, expectedError); + }); + it('should create a client with gaxServerStreamingRetries enabled', () => { + const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ + gaxServerStreamingRetries: true, + }); + assert(client); }); + }); - describe('Path templates', () => { + describe('Path templates', () => { + describe('readSession', async () => { + const fakePath = '/rendered/path/readSession'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + session: 'sessionValue', + }; + const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.readSessionPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.readSessionPathTemplate.match = sinon + .stub() + .returns(expectedParameters); - describe('readSession', async () => { - const fakePath = "/rendered/path/readSession"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - session: "sessionValue", - }; - const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.readSessionPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.readSessionPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('readSessionPath', () => { - const result = client.readSessionPath("projectValue", "locationValue", "sessionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.readSessionPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + it('readSessionPath', () => { + const result = client.readSessionPath( + 'projectValue', + 'locationValue', + 'sessionValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.readSessionPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); - it('matchProjectFromReadSessionName', () => { - const result = client.matchProjectFromReadSessionName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.readSessionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('matchProjectFromReadSessionName', () => { + const result = client.matchProjectFromReadSessionName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.readSessionPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); - it('matchLocationFromReadSessionName', () => { - const result = client.matchLocationFromReadSessionName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.readSessionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('matchLocationFromReadSessionName', () => { + const result = client.matchLocationFromReadSessionName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.readSessionPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); - it('matchSessionFromReadSessionName', () => { - const result = client.matchSessionFromReadSessionName(fakePath); - assert.strictEqual(result, "sessionValue"); - assert((client.pathTemplates.readSessionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('matchSessionFromReadSessionName', () => { + const result = client.matchSessionFromReadSessionName(fakePath); + assert.strictEqual(result, 'sessionValue'); + assert( + (client.pathTemplates.readSessionPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('stream', async () => { - const fakePath = "/rendered/path/stream"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - stream: "streamValue", - }; - const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.streamPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.streamPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('streamPath', () => { - const result = client.streamPath("projectValue", "locationValue", "streamValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.streamPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + describe('stream', async () => { + const fakePath = '/rendered/path/stream'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + stream: 'streamValue', + }; + const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.streamPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.streamPathTemplate.match = sinon + .stub() + .returns(expectedParameters); - it('matchProjectFromStreamName', () => { - const result = client.matchProjectFromStreamName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.streamPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('streamPath', () => { + const result = client.streamPath( + 'projectValue', + 'locationValue', + 'streamValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.streamPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); - it('matchLocationFromStreamName', () => { - const result = client.matchLocationFromStreamName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.streamPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('matchProjectFromStreamName', () => { + const result = client.matchProjectFromStreamName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.streamPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); - it('matchStreamFromStreamName', () => { - const result = client.matchStreamFromStreamName(fakePath); - assert.strictEqual(result, "streamValue"); - assert((client.pathTemplates.streamPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('matchLocationFromStreamName', () => { + const result = client.matchLocationFromStreamName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.streamPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchStreamFromStreamName', () => { + const result = client.matchStreamFromStreamName(fakePath); + assert.strictEqual(result, 'streamValue'); + assert( + (client.pathTemplates.streamPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/core/generator/gapic-generator-typescript/baselines/bigquery-v2-esm/esm/src/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/bigquery-v2-esm/esm/src/index.ts.baseline index 8bd334b4ebcb..1db478e47c54 100644 --- a/core/generator/gapic-generator-typescript/baselines/bigquery-v2-esm/esm/src/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/bigquery-v2-esm/esm/src/index.ts.baseline @@ -31,8 +31,26 @@ const RowAccessPolicyServiceClient = v2.RowAccessPolicyServiceClient; type RowAccessPolicyServiceClient = v2.RowAccessPolicyServiceClient; const TableServiceClient = v2.TableServiceClient; type TableServiceClient = v2.TableServiceClient; -export {v2, DatasetServiceClient, JobServiceClient, ModelServiceClient, ProjectServiceClient, RoutineServiceClient, RowAccessPolicyServiceClient, TableServiceClient}; -export default {v2, DatasetServiceClient, JobServiceClient, ModelServiceClient, ProjectServiceClient, RoutineServiceClient, RowAccessPolicyServiceClient, TableServiceClient}; +export { + v2, + DatasetServiceClient, + JobServiceClient, + ModelServiceClient, + ProjectServiceClient, + RoutineServiceClient, + RowAccessPolicyServiceClient, + TableServiceClient, +}; +export default { + v2, + DatasetServiceClient, + JobServiceClient, + ModelServiceClient, + ProjectServiceClient, + RoutineServiceClient, + RowAccessPolicyServiceClient, + TableServiceClient, +}; // @ts-ignore import * as protos from '../../protos/protos.js'; -export {protos} +export { protos }; diff --git a/core/generator/gapic-generator-typescript/baselines/bigquery-v2-esm/esm/src/v2/dataset_service_client.ts.baseline b/core/generator/gapic-generator-typescript/baselines/bigquery-v2-esm/esm/src/v2/dataset_service_client.ts.baseline index c04f9dce7bcb..fe2f55021fd5 100644 --- a/core/generator/gapic-generator-typescript/baselines/bigquery-v2-esm/esm/src/v2/dataset_service_client.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/bigquery-v2-esm/esm/src/v2/dataset_service_client.ts.baseline @@ -18,15 +18,22 @@ /* global window */ import * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions, PaginationCallback, GaxCall} from 'google-gax'; -import {Transform} from 'stream'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + PaginationCallback, + GaxCall, +} from 'google-gax'; +import { Transform } from 'stream'; // @ts-ignore import type * as protos from '../../../protos/protos.js'; import * as dataset_service_client_config from './dataset_service_client_config.json'; import fs from 'fs'; import path from 'path'; -import {fileURLToPath} from 'url'; -import {getJSON} from '../json-helper.cjs'; +import { fileURLToPath } from 'url'; +import { getJSON } from '../json-helper.cjs'; // @ts-ignore const dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -36,15 +43,15 @@ const dirname = path.dirname(fileURLToPath(import.meta.url)); * This file defines retry strategy and timeouts for all API methods in this library. */ const gapicConfig = getJSON( - path.join(dirname, 'dataset_service_client_config.json') + path.join(dirname, 'dataset_service_client_config.json'), ); const jsonProtos = getJSON( - path.join(dirname, '..', '..', '..', 'protos/protos.json') + path.join(dirname, '..', '..', '..', 'protos/protos.json'), ); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; const version = getJSON( - path.join(dirname, '..', '..', '..', '..', 'package.json') + path.join(dirname, '..', '..', '..', '..', 'package.json'), ).version; /** @@ -62,7 +69,7 @@ export class DatasetServiceClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('bigquery'); @@ -74,8 +81,8 @@ export class DatasetServiceClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - datasetServiceStub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + datasetServiceStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of DatasetServiceClient. @@ -117,21 +124,42 @@ export class DatasetServiceClient { * const client = new DatasetServiceClient({fallback: 'rest'}, gax); * ``` */ - constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { // Ensure that options include all the required fields. const staticMembers = this.constructor as typeof DatasetServiceClient; - if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { - throw new Error('Please set either universe_domain or universeDomain, but not both.'); + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); } - const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; - this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; this._servicePath = 'bigquery.' + this._universeDomain; - const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; - const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. if (servicePath !== this._servicePath && !('scopes' in opts)) { @@ -153,7 +181,7 @@ export class DatasetServiceClient { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; @@ -170,10 +198,7 @@ export class DatasetServiceClient { const isEsm = true; const isEsmString = isEsm ? '-esm' : '-cjs'; // Determine the client header string. - const clientHeader = [ - `gax/${this._gaxModule.version}`, - `gapic/${version}`, - ]; + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/{process.versions.node}${isEsmString}`); } else { @@ -181,7 +206,7 @@ export class DatasetServiceClient { } if (!opts.fallback) { clientHeader.push(`grpc/${this._gaxGrpc.grpcVersion}`); - } else if (opts.fallback === 'rest' ) { + } else if (opts.fallback === 'rest') { clientHeader.push(`rest/${this._gaxGrpc.grpcVersion}`); } if (opts.libName && opts.libVersion) { @@ -189,20 +214,28 @@ export class DatasetServiceClient { } // Load the applicable protos. - this._protos = this._gaxGrpc.loadProtoJSON(jsonProtos as gax.protobuf.INamespace); + this._protos = this._gaxGrpc.loadProtoJSON( + jsonProtos as gax.protobuf.INamespace, + ); // Some of the methods on this service return "paged" results, // (e.g. 50 results at a time, with tokens to get subsequent // pages). Denote the keys used for pagination and results. this.descriptors.page = { - listDatasets: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'datasets') + listDatasets: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'datasets', + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.cloud.bigquery.v2.DatasetService', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.cloud.bigquery.v2.DatasetService', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + { 'x-goog-api-client': clientHeader.join(' ') }, + ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -233,37 +266,48 @@ export class DatasetServiceClient { // Put together the "service stub" for // google.cloud.bigquery.v2.DatasetService. this.datasetServiceStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.cloud.bigquery.v2.DatasetService') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.cloud.bigquery.v2.DatasetService', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.cloud.bigquery.v2.DatasetService, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts, + this._providedCustomServicePath, + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const datasetServiceStubMethods = - ['getDataset', 'insertDataset', 'patchDataset', 'updateDataset', 'deleteDataset', 'listDatasets', 'undeleteDataset']; + const datasetServiceStubMethods = [ + 'getDataset', + 'insertDataset', + 'patchDataset', + 'updateDataset', + 'deleteDataset', + 'listDatasets', + 'undeleteDataset', + ]; for (const methodName of datasetServiceStubMethods) { const callPromise = this.datasetServiceStub.then( - stub => (...args: Array<{}>) => { - if (this._terminated) { - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error|null|undefined) => () => { + (stub) => + (...args: Array<{}>) => { + if (this._terminated) { + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { throw err; - }); + }, + ); - const descriptor = - this.descriptors.page[methodName] || - undefined; + const descriptor = this.descriptors.page[methodName] || undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -278,8 +322,14 @@ export class DatasetServiceClient { * @returns {string} The DNS address for this service. */ static get servicePath() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'bigquery.googleapis.com'; } @@ -291,8 +341,14 @@ export class DatasetServiceClient { * @returns {string} The DNS address for this service. */ static get apiEndpoint() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'bigquery.googleapis.com'; } @@ -326,7 +382,7 @@ export class DatasetServiceClient { return [ 'https://www.googleapis.com/auth/bigquery', 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloud-platform.read-only' + 'https://www.googleapis.com/auth/cloud-platform.read-only', ]; } @@ -336,8 +392,9 @@ export class DatasetServiceClient { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId(callback?: Callback): - Promise|void { + getProjectId( + callback?: Callback, + ): Promise | void { if (callback) { this.auth.getProjectId(callback); return; @@ -348,708 +405,953 @@ export class DatasetServiceClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Returns the dataset specified by datasetID. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.projectId - * Required. Project ID of the requested dataset - * @param {string} request.datasetId - * Required. Dataset ID of the requested dataset - * @param {google.cloud.bigquery.v2.GetDatasetRequest.DatasetView} [request.datasetView] - * Optional. Specifies the view that determines which dataset information is - * returned. By default, metadata and ACL information are returned. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.bigquery.v2.Dataset|Dataset}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/dataset_service.get_dataset.js - * region_tag:bigquery_v2_generated_DatasetService_GetDataset_async - */ + /** + * Returns the dataset specified by datasetID. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.projectId + * Required. Project ID of the requested dataset + * @param {string} request.datasetId + * Required. Dataset ID of the requested dataset + * @param {google.cloud.bigquery.v2.GetDatasetRequest.DatasetView} [request.datasetView] + * Optional. Specifies the view that determines which dataset information is + * returned. By default, metadata and ACL information are returned. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.bigquery.v2.Dataset|Dataset}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/dataset_service.get_dataset.js + * region_tag:bigquery_v2_generated_DatasetService_GetDataset_async + */ getDataset( - request?: protos.google.cloud.bigquery.v2.IGetDatasetRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.bigquery.v2.IDataset, - protos.google.cloud.bigquery.v2.IGetDatasetRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.bigquery.v2.IGetDatasetRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.bigquery.v2.IDataset, + protos.google.cloud.bigquery.v2.IGetDatasetRequest | undefined, + {} | undefined, + ] + >; getDataset( - request: protos.google.cloud.bigquery.v2.IGetDatasetRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.bigquery.v2.IDataset, - protos.google.cloud.bigquery.v2.IGetDatasetRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.bigquery.v2.IGetDatasetRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.bigquery.v2.IDataset, + protos.google.cloud.bigquery.v2.IGetDatasetRequest | null | undefined, + {} | null | undefined + >, + ): void; getDataset( - request: protos.google.cloud.bigquery.v2.IGetDatasetRequest, - callback: Callback< - protos.google.cloud.bigquery.v2.IDataset, - protos.google.cloud.bigquery.v2.IGetDatasetRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.bigquery.v2.IGetDatasetRequest, + callback: Callback< + protos.google.cloud.bigquery.v2.IDataset, + protos.google.cloud.bigquery.v2.IGetDatasetRequest | null | undefined, + {} | null | undefined + >, + ): void; getDataset( - request?: protos.google.cloud.bigquery.v2.IGetDatasetRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.cloud.bigquery.v2.IGetDatasetRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.bigquery.v2.IDataset, - protos.google.cloud.bigquery.v2.IGetDatasetRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.cloud.bigquery.v2.IDataset, - protos.google.cloud.bigquery.v2.IGetDatasetRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.bigquery.v2.IDataset, - protos.google.cloud.bigquery.v2.IGetDatasetRequest|undefined, {}|undefined - ]>|void { + protos.google.cloud.bigquery.v2.IGetDatasetRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.bigquery.v2.IDataset, + protos.google.cloud.bigquery.v2.IGetDatasetRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.bigquery.v2.IDataset, + protos.google.cloud.bigquery.v2.IGetDatasetRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'project_id': request.projectId?.toString() ?? '', - 'dataset_id': request.datasetId?.toString() ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + project_id: request.projectId?.toString() ?? '', + dataset_id: request.datasetId?.toString() ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getDataset request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.bigquery.v2.IDataset, - protos.google.cloud.bigquery.v2.IGetDatasetRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.bigquery.v2.IDataset, + protos.google.cloud.bigquery.v2.IGetDatasetRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getDataset response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.getDataset(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.bigquery.v2.IDataset, - protos.google.cloud.bigquery.v2.IGetDatasetRequest|undefined, {}|undefined - ]) => { - this._log.info('getDataset response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getDataset(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.bigquery.v2.IDataset, + protos.google.cloud.bigquery.v2.IGetDatasetRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getDataset response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Creates a new empty dataset. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.projectId - * Required. Project ID of the new dataset - * @param {google.cloud.bigquery.v2.Dataset} request.dataset - * Required. Datasets resource to use for the new dataset - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.bigquery.v2.Dataset|Dataset}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/dataset_service.insert_dataset.js - * region_tag:bigquery_v2_generated_DatasetService_InsertDataset_async - */ + /** + * Creates a new empty dataset. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.projectId + * Required. Project ID of the new dataset + * @param {google.cloud.bigquery.v2.Dataset} request.dataset + * Required. Datasets resource to use for the new dataset + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.bigquery.v2.Dataset|Dataset}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/dataset_service.insert_dataset.js + * region_tag:bigquery_v2_generated_DatasetService_InsertDataset_async + */ insertDataset( - request?: protos.google.cloud.bigquery.v2.IInsertDatasetRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.bigquery.v2.IDataset, - protos.google.cloud.bigquery.v2.IInsertDatasetRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.bigquery.v2.IInsertDatasetRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.bigquery.v2.IDataset, + protos.google.cloud.bigquery.v2.IInsertDatasetRequest | undefined, + {} | undefined, + ] + >; insertDataset( - request: protos.google.cloud.bigquery.v2.IInsertDatasetRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.bigquery.v2.IDataset, - protos.google.cloud.bigquery.v2.IInsertDatasetRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.bigquery.v2.IInsertDatasetRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.bigquery.v2.IDataset, + protos.google.cloud.bigquery.v2.IInsertDatasetRequest | null | undefined, + {} | null | undefined + >, + ): void; insertDataset( - request: protos.google.cloud.bigquery.v2.IInsertDatasetRequest, - callback: Callback< - protos.google.cloud.bigquery.v2.IDataset, - protos.google.cloud.bigquery.v2.IInsertDatasetRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.bigquery.v2.IInsertDatasetRequest, + callback: Callback< + protos.google.cloud.bigquery.v2.IDataset, + protos.google.cloud.bigquery.v2.IInsertDatasetRequest | null | undefined, + {} | null | undefined + >, + ): void; insertDataset( - request?: protos.google.cloud.bigquery.v2.IInsertDatasetRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.cloud.bigquery.v2.IInsertDatasetRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.bigquery.v2.IDataset, - protos.google.cloud.bigquery.v2.IInsertDatasetRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.cloud.bigquery.v2.IDataset, - protos.google.cloud.bigquery.v2.IInsertDatasetRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.bigquery.v2.IDataset, - protos.google.cloud.bigquery.v2.IInsertDatasetRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.bigquery.v2.IInsertDatasetRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.bigquery.v2.IDataset, + protos.google.cloud.bigquery.v2.IInsertDatasetRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.bigquery.v2.IDataset, + protos.google.cloud.bigquery.v2.IInsertDatasetRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'project_id': request.projectId?.toString() ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + project_id: request.projectId?.toString() ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('insertDataset request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.bigquery.v2.IDataset, - protos.google.cloud.bigquery.v2.IInsertDatasetRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.bigquery.v2.IDataset, + | protos.google.cloud.bigquery.v2.IInsertDatasetRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('insertDataset response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.insertDataset(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.bigquery.v2.IDataset, - protos.google.cloud.bigquery.v2.IInsertDatasetRequest|undefined, {}|undefined - ]) => { - this._log.info('insertDataset response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .insertDataset(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.bigquery.v2.IDataset, + protos.google.cloud.bigquery.v2.IInsertDatasetRequest | undefined, + {} | undefined, + ]) => { + this._log.info('insertDataset response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Updates information in an existing dataset. The update method replaces the - * entire dataset resource, whereas the patch method only replaces fields that - * are provided in the submitted dataset resource. - * This method supports RFC5789 patch semantics. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.projectId - * Required. Project ID of the dataset being updated - * @param {string} request.datasetId - * Required. Dataset ID of the dataset being updated - * @param {google.cloud.bigquery.v2.Dataset} request.dataset - * Required. Datasets resource which will replace or patch the specified - * dataset. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.bigquery.v2.Dataset|Dataset}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/dataset_service.patch_dataset.js - * region_tag:bigquery_v2_generated_DatasetService_PatchDataset_async - */ + /** + * Updates information in an existing dataset. The update method replaces the + * entire dataset resource, whereas the patch method only replaces fields that + * are provided in the submitted dataset resource. + * This method supports RFC5789 patch semantics. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.projectId + * Required. Project ID of the dataset being updated + * @param {string} request.datasetId + * Required. Dataset ID of the dataset being updated + * @param {google.cloud.bigquery.v2.Dataset} request.dataset + * Required. Datasets resource which will replace or patch the specified + * dataset. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.bigquery.v2.Dataset|Dataset}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/dataset_service.patch_dataset.js + * region_tag:bigquery_v2_generated_DatasetService_PatchDataset_async + */ patchDataset( - request?: protos.google.cloud.bigquery.v2.IUpdateOrPatchDatasetRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.bigquery.v2.IDataset, - protos.google.cloud.bigquery.v2.IUpdateOrPatchDatasetRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.bigquery.v2.IUpdateOrPatchDatasetRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.bigquery.v2.IDataset, + protos.google.cloud.bigquery.v2.IUpdateOrPatchDatasetRequest | undefined, + {} | undefined, + ] + >; patchDataset( - request: protos.google.cloud.bigquery.v2.IUpdateOrPatchDatasetRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.bigquery.v2.IDataset, - protos.google.cloud.bigquery.v2.IUpdateOrPatchDatasetRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.bigquery.v2.IUpdateOrPatchDatasetRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.bigquery.v2.IDataset, + | protos.google.cloud.bigquery.v2.IUpdateOrPatchDatasetRequest + | null + | undefined, + {} | null | undefined + >, + ): void; patchDataset( - request: protos.google.cloud.bigquery.v2.IUpdateOrPatchDatasetRequest, - callback: Callback< - protos.google.cloud.bigquery.v2.IDataset, - protos.google.cloud.bigquery.v2.IUpdateOrPatchDatasetRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.bigquery.v2.IUpdateOrPatchDatasetRequest, + callback: Callback< + protos.google.cloud.bigquery.v2.IDataset, + | protos.google.cloud.bigquery.v2.IUpdateOrPatchDatasetRequest + | null + | undefined, + {} | null | undefined + >, + ): void; patchDataset( - request?: protos.google.cloud.bigquery.v2.IUpdateOrPatchDatasetRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.cloud.bigquery.v2.IUpdateOrPatchDatasetRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.bigquery.v2.IDataset, - protos.google.cloud.bigquery.v2.IUpdateOrPatchDatasetRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.cloud.bigquery.v2.IDataset, - protos.google.cloud.bigquery.v2.IUpdateOrPatchDatasetRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.bigquery.v2.IDataset, - protos.google.cloud.bigquery.v2.IUpdateOrPatchDatasetRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.bigquery.v2.IUpdateOrPatchDatasetRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.bigquery.v2.IDataset, + | protos.google.cloud.bigquery.v2.IUpdateOrPatchDatasetRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.bigquery.v2.IDataset, + protos.google.cloud.bigquery.v2.IUpdateOrPatchDatasetRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'project_id': request.projectId?.toString() ?? '', - 'dataset_id': request.datasetId?.toString() ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + project_id: request.projectId?.toString() ?? '', + dataset_id: request.datasetId?.toString() ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('patchDataset request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.bigquery.v2.IDataset, - protos.google.cloud.bigquery.v2.IUpdateOrPatchDatasetRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.bigquery.v2.IDataset, + | protos.google.cloud.bigquery.v2.IUpdateOrPatchDatasetRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('patchDataset response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.patchDataset(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.bigquery.v2.IDataset, - protos.google.cloud.bigquery.v2.IUpdateOrPatchDatasetRequest|undefined, {}|undefined - ]) => { - this._log.info('patchDataset response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .patchDataset(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.bigquery.v2.IDataset, + ( + | protos.google.cloud.bigquery.v2.IUpdateOrPatchDatasetRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('patchDataset response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Updates information in an existing dataset. The update method replaces the - * entire dataset resource, whereas the patch method only replaces fields that - * are provided in the submitted dataset resource. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.projectId - * Required. Project ID of the dataset being updated - * @param {string} request.datasetId - * Required. Dataset ID of the dataset being updated - * @param {google.cloud.bigquery.v2.Dataset} request.dataset - * Required. Datasets resource which will replace or patch the specified - * dataset. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.bigquery.v2.Dataset|Dataset}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/dataset_service.update_dataset.js - * region_tag:bigquery_v2_generated_DatasetService_UpdateDataset_async - */ + /** + * Updates information in an existing dataset. The update method replaces the + * entire dataset resource, whereas the patch method only replaces fields that + * are provided in the submitted dataset resource. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.projectId + * Required. Project ID of the dataset being updated + * @param {string} request.datasetId + * Required. Dataset ID of the dataset being updated + * @param {google.cloud.bigquery.v2.Dataset} request.dataset + * Required. Datasets resource which will replace or patch the specified + * dataset. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.bigquery.v2.Dataset|Dataset}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/dataset_service.update_dataset.js + * region_tag:bigquery_v2_generated_DatasetService_UpdateDataset_async + */ updateDataset( - request?: protos.google.cloud.bigquery.v2.IUpdateOrPatchDatasetRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.bigquery.v2.IDataset, - protos.google.cloud.bigquery.v2.IUpdateOrPatchDatasetRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.bigquery.v2.IUpdateOrPatchDatasetRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.bigquery.v2.IDataset, + protos.google.cloud.bigquery.v2.IUpdateOrPatchDatasetRequest | undefined, + {} | undefined, + ] + >; updateDataset( - request: protos.google.cloud.bigquery.v2.IUpdateOrPatchDatasetRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.bigquery.v2.IDataset, - protos.google.cloud.bigquery.v2.IUpdateOrPatchDatasetRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.bigquery.v2.IUpdateOrPatchDatasetRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.bigquery.v2.IDataset, + | protos.google.cloud.bigquery.v2.IUpdateOrPatchDatasetRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateDataset( - request: protos.google.cloud.bigquery.v2.IUpdateOrPatchDatasetRequest, - callback: Callback< - protos.google.cloud.bigquery.v2.IDataset, - protos.google.cloud.bigquery.v2.IUpdateOrPatchDatasetRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.bigquery.v2.IUpdateOrPatchDatasetRequest, + callback: Callback< + protos.google.cloud.bigquery.v2.IDataset, + | protos.google.cloud.bigquery.v2.IUpdateOrPatchDatasetRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateDataset( - request?: protos.google.cloud.bigquery.v2.IUpdateOrPatchDatasetRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.bigquery.v2.IDataset, - protos.google.cloud.bigquery.v2.IUpdateOrPatchDatasetRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.bigquery.v2.IUpdateOrPatchDatasetRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.bigquery.v2.IDataset, - protos.google.cloud.bigquery.v2.IUpdateOrPatchDatasetRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.bigquery.v2.IDataset, - protos.google.cloud.bigquery.v2.IUpdateOrPatchDatasetRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.bigquery.v2.IUpdateOrPatchDatasetRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.bigquery.v2.IDataset, + | protos.google.cloud.bigquery.v2.IUpdateOrPatchDatasetRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.bigquery.v2.IDataset, + protos.google.cloud.bigquery.v2.IUpdateOrPatchDatasetRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'project_id': request.projectId?.toString() ?? '', - 'dataset_id': request.datasetId?.toString() ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + project_id: request.projectId?.toString() ?? '', + dataset_id: request.datasetId?.toString() ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateDataset request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.bigquery.v2.IDataset, - protos.google.cloud.bigquery.v2.IUpdateOrPatchDatasetRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.bigquery.v2.IDataset, + | protos.google.cloud.bigquery.v2.IUpdateOrPatchDatasetRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateDataset response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.updateDataset(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.bigquery.v2.IDataset, - protos.google.cloud.bigquery.v2.IUpdateOrPatchDatasetRequest|undefined, {}|undefined - ]) => { - this._log.info('updateDataset response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateDataset(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.bigquery.v2.IDataset, + ( + | protos.google.cloud.bigquery.v2.IUpdateOrPatchDatasetRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('updateDataset response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Deletes the dataset specified by the datasetId value. Before you can delete - * a dataset, you must delete all its tables, either manually or by specifying - * deleteContents. Immediately after deletion, you can create another dataset - * with the same name. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.projectId - * Required. Project ID of the dataset being deleted - * @param {string} request.datasetId - * Required. Dataset ID of dataset being deleted - * @param {boolean} request.deleteContents - * If True, delete all the tables in the dataset. - * If False and the dataset contains tables, the request will fail. - * Default is False - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/dataset_service.delete_dataset.js - * region_tag:bigquery_v2_generated_DatasetService_DeleteDataset_async - */ + /** + * Deletes the dataset specified by the datasetId value. Before you can delete + * a dataset, you must delete all its tables, either manually or by specifying + * deleteContents. Immediately after deletion, you can create another dataset + * with the same name. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.projectId + * Required. Project ID of the dataset being deleted + * @param {string} request.datasetId + * Required. Dataset ID of dataset being deleted + * @param {boolean} request.deleteContents + * If True, delete all the tables in the dataset. + * If False and the dataset contains tables, the request will fail. + * Default is False + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/dataset_service.delete_dataset.js + * region_tag:bigquery_v2_generated_DatasetService_DeleteDataset_async + */ deleteDataset( - request?: protos.google.cloud.bigquery.v2.IDeleteDatasetRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.cloud.bigquery.v2.IDeleteDatasetRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.bigquery.v2.IDeleteDatasetRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.cloud.bigquery.v2.IDeleteDatasetRequest | undefined, + {} | undefined, + ] + >; deleteDataset( - request: protos.google.cloud.bigquery.v2.IDeleteDatasetRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.cloud.bigquery.v2.IDeleteDatasetRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.bigquery.v2.IDeleteDatasetRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.cloud.bigquery.v2.IDeleteDatasetRequest | null | undefined, + {} | null | undefined + >, + ): void; deleteDataset( - request: protos.google.cloud.bigquery.v2.IDeleteDatasetRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.cloud.bigquery.v2.IDeleteDatasetRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.bigquery.v2.IDeleteDatasetRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.cloud.bigquery.v2.IDeleteDatasetRequest | null | undefined, + {} | null | undefined + >, + ): void; deleteDataset( - request?: protos.google.cloud.bigquery.v2.IDeleteDatasetRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.protobuf.IEmpty, - protos.google.cloud.bigquery.v2.IDeleteDatasetRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.bigquery.v2.IDeleteDatasetRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.cloud.bigquery.v2.IDeleteDatasetRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.cloud.bigquery.v2.IDeleteDatasetRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.bigquery.v2.IDeleteDatasetRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + protos.google.cloud.bigquery.v2.IDeleteDatasetRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.cloud.bigquery.v2.IDeleteDatasetRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'project_id': request.projectId?.toString() ?? '', - 'dataset_id': request.datasetId?.toString() ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + project_id: request.projectId?.toString() ?? '', + dataset_id: request.datasetId?.toString() ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('deleteDataset request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.cloud.bigquery.v2.IDeleteDatasetRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.cloud.bigquery.v2.IDeleteDatasetRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteDataset response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.deleteDataset(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.cloud.bigquery.v2.IDeleteDatasetRequest|undefined, {}|undefined - ]) => { - this._log.info('deleteDataset response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteDataset(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.cloud.bigquery.v2.IDeleteDatasetRequest | undefined, + {} | undefined, + ]) => { + this._log.info('deleteDataset response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Undeletes a dataset which is within time travel window based on datasetId. - * If a time is specified, the dataset version deleted at that time is - * undeleted, else the last live version is undeleted. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.projectId - * Required. Project ID of the dataset to be undeleted - * @param {string} request.datasetId - * Required. Dataset ID of dataset being deleted - * @param {google.protobuf.Timestamp} [request.deletionTime] - * Optional. The exact time when the dataset was deleted. If not specified, - * the most recently deleted version is undeleted. Undeleting a dataset - * using deletion time is not supported. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.bigquery.v2.Dataset|Dataset}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/dataset_service.undelete_dataset.js - * region_tag:bigquery_v2_generated_DatasetService_UndeleteDataset_async - */ + /** + * Undeletes a dataset which is within time travel window based on datasetId. + * If a time is specified, the dataset version deleted at that time is + * undeleted, else the last live version is undeleted. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.projectId + * Required. Project ID of the dataset to be undeleted + * @param {string} request.datasetId + * Required. Dataset ID of dataset being deleted + * @param {google.protobuf.Timestamp} [request.deletionTime] + * Optional. The exact time when the dataset was deleted. If not specified, + * the most recently deleted version is undeleted. Undeleting a dataset + * using deletion time is not supported. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.bigquery.v2.Dataset|Dataset}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/dataset_service.undelete_dataset.js + * region_tag:bigquery_v2_generated_DatasetService_UndeleteDataset_async + */ undeleteDataset( - request?: protos.google.cloud.bigquery.v2.IUndeleteDatasetRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.bigquery.v2.IDataset, - protos.google.cloud.bigquery.v2.IUndeleteDatasetRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.bigquery.v2.IUndeleteDatasetRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.bigquery.v2.IDataset, + protos.google.cloud.bigquery.v2.IUndeleteDatasetRequest | undefined, + {} | undefined, + ] + >; undeleteDataset( - request: protos.google.cloud.bigquery.v2.IUndeleteDatasetRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.bigquery.v2.IDataset, - protos.google.cloud.bigquery.v2.IUndeleteDatasetRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.bigquery.v2.IUndeleteDatasetRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.bigquery.v2.IDataset, + | protos.google.cloud.bigquery.v2.IUndeleteDatasetRequest + | null + | undefined, + {} | null | undefined + >, + ): void; undeleteDataset( - request: protos.google.cloud.bigquery.v2.IUndeleteDatasetRequest, - callback: Callback< - protos.google.cloud.bigquery.v2.IDataset, - protos.google.cloud.bigquery.v2.IUndeleteDatasetRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.bigquery.v2.IUndeleteDatasetRequest, + callback: Callback< + protos.google.cloud.bigquery.v2.IDataset, + | protos.google.cloud.bigquery.v2.IUndeleteDatasetRequest + | null + | undefined, + {} | null | undefined + >, + ): void; undeleteDataset( - request?: protos.google.cloud.bigquery.v2.IUndeleteDatasetRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.cloud.bigquery.v2.IUndeleteDatasetRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.bigquery.v2.IDataset, - protos.google.cloud.bigquery.v2.IUndeleteDatasetRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.cloud.bigquery.v2.IDataset, - protos.google.cloud.bigquery.v2.IUndeleteDatasetRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.bigquery.v2.IDataset, - protos.google.cloud.bigquery.v2.IUndeleteDatasetRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.bigquery.v2.IUndeleteDatasetRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.bigquery.v2.IDataset, + | protos.google.cloud.bigquery.v2.IUndeleteDatasetRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.bigquery.v2.IDataset, + protos.google.cloud.bigquery.v2.IUndeleteDatasetRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'project_id': request.projectId?.toString() ?? '', - 'dataset_id': request.datasetId?.toString() ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + project_id: request.projectId?.toString() ?? '', + dataset_id: request.datasetId?.toString() ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('undeleteDataset request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.bigquery.v2.IDataset, - protos.google.cloud.bigquery.v2.IUndeleteDatasetRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.bigquery.v2.IDataset, + | protos.google.cloud.bigquery.v2.IUndeleteDatasetRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('undeleteDataset response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.undeleteDataset(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.bigquery.v2.IDataset, - protos.google.cloud.bigquery.v2.IUndeleteDatasetRequest|undefined, {}|undefined - ]) => { - this._log.info('undeleteDataset response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .undeleteDataset(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.bigquery.v2.IDataset, + protos.google.cloud.bigquery.v2.IUndeleteDatasetRequest | undefined, + {} | undefined, + ]) => { + this._log.info('undeleteDataset response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } - /** - * Lists all datasets in the specified project to which the user has been - * granted the READER dataset role. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.projectId - * Required. Project ID of the datasets to be listed - * @param {google.protobuf.UInt32Value| number } request.maxResults - * The maximum number of results to return in a single response page. - * Leverage the page tokens to iterate through the entire collection. - * @param {string} request.pageToken - * Page token, returned by a previous call, to request the next page of - * results - * @param {boolean} request.all - * Whether to list all datasets, including hidden ones - * @param {string} request.filter - * An expression for filtering the results of the request by label. - * The syntax is `labels.[:]`. - * Multiple filters can be ANDed together by connecting with a space. - * Example: `labels.department:receiving labels.active`. - * See [Filtering datasets using - * labels](https://cloud.google.com/bigquery/docs/filtering-labels#filtering_datasets_using_labels) - * for details. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.cloud.bigquery.v2.ListFormatDataset|ListFormatDataset}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `listDatasetsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Lists all datasets in the specified project to which the user has been + * granted the READER dataset role. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.projectId + * Required. Project ID of the datasets to be listed + * @param {google.protobuf.UInt32Value| number } request.maxResults + * The maximum number of results to return in a single response page. + * Leverage the page tokens to iterate through the entire collection. + * @param {string} request.pageToken + * Page token, returned by a previous call, to request the next page of + * results + * @param {boolean} request.all + * Whether to list all datasets, including hidden ones + * @param {string} request.filter + * An expression for filtering the results of the request by label. + * The syntax is `labels.[:]`. + * Multiple filters can be ANDed together by connecting with a space. + * Example: `labels.department:receiving labels.active`. + * See [Filtering datasets using + * labels](https://cloud.google.com/bigquery/docs/filtering-labels#filtering_datasets_using_labels) + * for details. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.cloud.bigquery.v2.ListFormatDataset|ListFormatDataset}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listDatasetsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listDatasets( - request?: protos.google.cloud.bigquery.v2.IListDatasetsRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.bigquery.v2.IListFormatDataset[], - protos.google.cloud.bigquery.v2.IListDatasetsRequest|null, - protos.google.cloud.bigquery.v2.IDatasetList - ]>; + request?: protos.google.cloud.bigquery.v2.IListDatasetsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.bigquery.v2.IListFormatDataset[], + protos.google.cloud.bigquery.v2.IListDatasetsRequest | null, + protos.google.cloud.bigquery.v2.IDatasetList, + ] + >; listDatasets( - request: protos.google.cloud.bigquery.v2.IListDatasetsRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.cloud.bigquery.v2.IListDatasetsRequest, - protos.google.cloud.bigquery.v2.IDatasetList|null|undefined, - protos.google.cloud.bigquery.v2.IListFormatDataset>): void; + request: protos.google.cloud.bigquery.v2.IListDatasetsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.cloud.bigquery.v2.IListDatasetsRequest, + protos.google.cloud.bigquery.v2.IDatasetList | null | undefined, + protos.google.cloud.bigquery.v2.IListFormatDataset + >, + ): void; listDatasets( - request: protos.google.cloud.bigquery.v2.IListDatasetsRequest, - callback: PaginationCallback< - protos.google.cloud.bigquery.v2.IListDatasetsRequest, - protos.google.cloud.bigquery.v2.IDatasetList|null|undefined, - protos.google.cloud.bigquery.v2.IListFormatDataset>): void; + request: protos.google.cloud.bigquery.v2.IListDatasetsRequest, + callback: PaginationCallback< + protos.google.cloud.bigquery.v2.IListDatasetsRequest, + protos.google.cloud.bigquery.v2.IDatasetList | null | undefined, + protos.google.cloud.bigquery.v2.IListFormatDataset + >, + ): void; listDatasets( - request?: protos.google.cloud.bigquery.v2.IListDatasetsRequest, - optionsOrCallback?: CallOptions|PaginationCallback< - protos.google.cloud.bigquery.v2.IListDatasetsRequest, - protos.google.cloud.bigquery.v2.IDatasetList|null|undefined, - protos.google.cloud.bigquery.v2.IListFormatDataset>, - callback?: PaginationCallback< + request?: protos.google.cloud.bigquery.v2.IListDatasetsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.cloud.bigquery.v2.IListDatasetsRequest, - protos.google.cloud.bigquery.v2.IDatasetList|null|undefined, - protos.google.cloud.bigquery.v2.IListFormatDataset>): - Promise<[ - protos.google.cloud.bigquery.v2.IListFormatDataset[], - protos.google.cloud.bigquery.v2.IListDatasetsRequest|null, - protos.google.cloud.bigquery.v2.IDatasetList - ]>|void { + protos.google.cloud.bigquery.v2.IDatasetList | null | undefined, + protos.google.cloud.bigquery.v2.IListFormatDataset + >, + callback?: PaginationCallback< + protos.google.cloud.bigquery.v2.IListDatasetsRequest, + protos.google.cloud.bigquery.v2.IDatasetList | null | undefined, + protos.google.cloud.bigquery.v2.IListFormatDataset + >, + ): Promise< + [ + protos.google.cloud.bigquery.v2.IListFormatDataset[], + protos.google.cloud.bigquery.v2.IListDatasetsRequest | null, + protos.google.cloud.bigquery.v2.IDatasetList, + ] + > | void { request = request || {}; - // Converts number to Unit32 or Int32 value for non-compliant APIs. - if(request.maxResults && typeof request.maxResults === "number"){ - const maxResultsObject = {"value": request.maxResults} - request.maxResults = maxResultsObject - } + // Converts number to Unit32 or Int32 value for non-compliant APIs. + if (request.maxResults && typeof request.maxResults === 'number') { + const maxResultsObject = { value: request.maxResults }; + request.maxResults = maxResultsObject; + } let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'project_id': request.projectId?.toString() ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + project_id: request.projectId?.toString() ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.cloud.bigquery.v2.IListDatasetsRequest, - protos.google.cloud.bigquery.v2.IDatasetList|null|undefined, - protos.google.cloud.bigquery.v2.IListFormatDataset>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.cloud.bigquery.v2.IListDatasetsRequest, + protos.google.cloud.bigquery.v2.IDatasetList | null | undefined, + protos.google.cloud.bigquery.v2.IListFormatDataset + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listDatasets values %j', values); callback!(error, values, nextPageRequest, rawResponse); @@ -1058,130 +1360,134 @@ export class DatasetServiceClient { this._log.info('listDatasets request %j', request); return this.innerApiCalls .listDatasets(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.cloud.bigquery.v2.IListFormatDataset[], - protos.google.cloud.bigquery.v2.IListDatasetsRequest|null, - protos.google.cloud.bigquery.v2.IDatasetList - ]) => { - this._log.info('listDatasets values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.cloud.bigquery.v2.IListFormatDataset[], + protos.google.cloud.bigquery.v2.IListDatasetsRequest | null, + protos.google.cloud.bigquery.v2.IDatasetList, + ]) => { + this._log.info('listDatasets values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listDatasets`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.projectId - * Required. Project ID of the datasets to be listed - * @param {google.protobuf.UInt32Value} request.maxResults - * The maximum number of results to return in a single response page. - * Leverage the page tokens to iterate through the entire collection. - * @param {string} request.pageToken - * Page token, returned by a previous call, to request the next page of - * results - * @param {boolean} request.all - * Whether to list all datasets, including hidden ones - * @param {string} request.filter - * An expression for filtering the results of the request by label. - * The syntax is `labels.[:]`. - * Multiple filters can be ANDed together by connecting with a space. - * Example: `labels.department:receiving labels.active`. - * See [Filtering datasets using - * labels](https://cloud.google.com/bigquery/docs/filtering-labels#filtering_datasets_using_labels) - * for details. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.cloud.bigquery.v2.ListFormatDataset|ListFormatDataset} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `listDatasetsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `listDatasets`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.projectId + * Required. Project ID of the datasets to be listed + * @param {google.protobuf.UInt32Value} request.maxResults + * The maximum number of results to return in a single response page. + * Leverage the page tokens to iterate through the entire collection. + * @param {string} request.pageToken + * Page token, returned by a previous call, to request the next page of + * results + * @param {boolean} request.all + * Whether to list all datasets, including hidden ones + * @param {string} request.filter + * An expression for filtering the results of the request by label. + * The syntax is `labels.[:]`. + * Multiple filters can be ANDed together by connecting with a space. + * Example: `labels.department:receiving labels.active`. + * See [Filtering datasets using + * labels](https://cloud.google.com/bigquery/docs/filtering-labels#filtering_datasets_using_labels) + * for details. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.cloud.bigquery.v2.ListFormatDataset|ListFormatDataset} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listDatasetsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listDatasetsStream( - request?: protos.google.cloud.bigquery.v2.IListDatasetsRequest, - options?: CallOptions): - Transform{ + request?: protos.google.cloud.bigquery.v2.IListDatasetsRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'project_id': request.projectId?.toString() ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + project_id: request.projectId?.toString() ?? '', + }); const defaultCallSettings = this._defaults['listDatasets']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listDatasets stream %j', request); return this.descriptors.page.listDatasets.createStream( this.innerApiCalls.listDatasets as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listDatasets`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.projectId - * Required. Project ID of the datasets to be listed - * @param {google.protobuf.UInt32Value} request.maxResults - * The maximum number of results to return in a single response page. - * Leverage the page tokens to iterate through the entire collection. - * @param {string} request.pageToken - * Page token, returned by a previous call, to request the next page of - * results - * @param {boolean} request.all - * Whether to list all datasets, including hidden ones - * @param {string} request.filter - * An expression for filtering the results of the request by label. - * The syntax is `labels.[:]`. - * Multiple filters can be ANDed together by connecting with a space. - * Example: `labels.department:receiving labels.active`. - * See [Filtering datasets using - * labels](https://cloud.google.com/bigquery/docs/filtering-labels#filtering_datasets_using_labels) - * for details. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.cloud.bigquery.v2.ListFormatDataset|ListFormatDataset}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v2/dataset_service.list_datasets.js - * region_tag:bigquery_v2_generated_DatasetService_ListDatasets_async - */ + /** + * Equivalent to `listDatasets`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.projectId + * Required. Project ID of the datasets to be listed + * @param {google.protobuf.UInt32Value} request.maxResults + * The maximum number of results to return in a single response page. + * Leverage the page tokens to iterate through the entire collection. + * @param {string} request.pageToken + * Page token, returned by a previous call, to request the next page of + * results + * @param {boolean} request.all + * Whether to list all datasets, including hidden ones + * @param {string} request.filter + * An expression for filtering the results of the request by label. + * The syntax is `labels.[:]`. + * Multiple filters can be ANDed together by connecting with a space. + * Example: `labels.department:receiving labels.active`. + * See [Filtering datasets using + * labels](https://cloud.google.com/bigquery/docs/filtering-labels#filtering_datasets_using_labels) + * for details. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.cloud.bigquery.v2.ListFormatDataset|ListFormatDataset}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v2/dataset_service.list_datasets.js + * region_tag:bigquery_v2_generated_DatasetService_ListDatasets_async + */ listDatasetsAsync( - request?: protos.google.cloud.bigquery.v2.IListDatasetsRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.cloud.bigquery.v2.IListDatasetsRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'project_id': request.projectId?.toString() ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + project_id: request.projectId?.toString() ?? '', + }); const defaultCallSettings = this._defaults['listDatasets']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listDatasets iterate %j', request); return this.descriptors.page.listDatasets.asyncIterate( this.innerApiCalls['listDatasets'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } @@ -1193,7 +1499,7 @@ export class DatasetServiceClient { */ close(): Promise { if (this.datasetServiceStub && !this._terminated) { - return this.datasetServiceStub.then(stub => { + return this.datasetServiceStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -1201,4 +1507,4 @@ export class DatasetServiceClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/core/generator/gapic-generator-typescript/baselines/bigquery-v2-esm/esm/src/v2/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/bigquery-v2-esm/esm/src/v2/index.ts.baseline index 8c9358de394f..d320a4a539bc 100644 --- a/core/generator/gapic-generator-typescript/baselines/bigquery-v2-esm/esm/src/v2/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/bigquery-v2-esm/esm/src/v2/index.ts.baseline @@ -16,10 +16,10 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -export {DatasetServiceClient} from './dataset_service_client.js'; -export {JobServiceClient} from './job_service_client.js'; -export {ModelServiceClient} from './model_service_client.js'; -export {ProjectServiceClient} from './project_service_client.js'; -export {RoutineServiceClient} from './routine_service_client.js'; -export {RowAccessPolicyServiceClient} from './row_access_policy_service_client.js'; -export {TableServiceClient} from './table_service_client.js'; +export { DatasetServiceClient } from './dataset_service_client.js'; +export { JobServiceClient } from './job_service_client.js'; +export { ModelServiceClient } from './model_service_client.js'; +export { ProjectServiceClient } from './project_service_client.js'; +export { RoutineServiceClient } from './routine_service_client.js'; +export { RowAccessPolicyServiceClient } from './row_access_policy_service_client.js'; +export { TableServiceClient } from './table_service_client.js'; diff --git a/core/generator/gapic-generator-typescript/baselines/bigquery-v2-esm/esm/src/v2/job_service_client.ts.baseline b/core/generator/gapic-generator-typescript/baselines/bigquery-v2-esm/esm/src/v2/job_service_client.ts.baseline index c47ff0af5f57..e95a33814e3b 100644 --- a/core/generator/gapic-generator-typescript/baselines/bigquery-v2-esm/esm/src/v2/job_service_client.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/bigquery-v2-esm/esm/src/v2/job_service_client.ts.baseline @@ -18,15 +18,22 @@ /* global window */ import * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions, PaginationCallback, GaxCall} from 'google-gax'; -import {Transform} from 'stream'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + PaginationCallback, + GaxCall, +} from 'google-gax'; +import { Transform } from 'stream'; // @ts-ignore import type * as protos from '../../../protos/protos.js'; import * as job_service_client_config from './job_service_client_config.json'; import fs from 'fs'; import path from 'path'; -import {fileURLToPath} from 'url'; -import {getJSON} from '../json-helper.cjs'; +import { fileURLToPath } from 'url'; +import { getJSON } from '../json-helper.cjs'; // @ts-ignore const dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -36,15 +43,15 @@ const dirname = path.dirname(fileURLToPath(import.meta.url)); * This file defines retry strategy and timeouts for all API methods in this library. */ const gapicConfig = getJSON( - path.join(dirname, 'job_service_client_config.json') + path.join(dirname, 'job_service_client_config.json'), ); const jsonProtos = getJSON( - path.join(dirname, '..', '..', '..', 'protos/protos.json') + path.join(dirname, '..', '..', '..', 'protos/protos.json'), ); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; const version = getJSON( - path.join(dirname, '..', '..', '..', '..', 'package.json') + path.join(dirname, '..', '..', '..', '..', 'package.json'), ).version; /** @@ -62,7 +69,7 @@ export class JobServiceClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('bigquery'); @@ -74,8 +81,8 @@ export class JobServiceClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - jobServiceStub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + jobServiceStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of JobServiceClient. @@ -117,21 +124,42 @@ export class JobServiceClient { * const client = new JobServiceClient({fallback: 'rest'}, gax); * ``` */ - constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { // Ensure that options include all the required fields. const staticMembers = this.constructor as typeof JobServiceClient; - if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { - throw new Error('Please set either universe_domain or universeDomain, but not both.'); + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); } - const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; - this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; this._servicePath = 'bigquery.' + this._universeDomain; - const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; - const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. if (servicePath !== this._servicePath && !('scopes' in opts)) { @@ -153,7 +181,7 @@ export class JobServiceClient { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; @@ -170,10 +198,7 @@ export class JobServiceClient { const isEsm = true; const isEsmString = isEsm ? '-esm' : '-cjs'; // Determine the client header string. - const clientHeader = [ - `gax/${this._gaxModule.version}`, - `gapic/${version}`, - ]; + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/{process.versions.node}${isEsmString}`); } else { @@ -181,7 +206,7 @@ export class JobServiceClient { } if (!opts.fallback) { clientHeader.push(`grpc/${this._gaxGrpc.grpcVersion}`); - } else if (opts.fallback === 'rest' ) { + } else if (opts.fallback === 'rest') { clientHeader.push(`rest/${this._gaxGrpc.grpcVersion}`); } if (opts.libName && opts.libVersion) { @@ -189,20 +214,28 @@ export class JobServiceClient { } // Load the applicable protos. - this._protos = this._gaxGrpc.loadProtoJSON(jsonProtos as gax.protobuf.INamespace); + this._protos = this._gaxGrpc.loadProtoJSON( + jsonProtos as gax.protobuf.INamespace, + ); // Some of the methods on this service return "paged" results, // (e.g. 50 results at a time, with tokens to get subsequent // pages). Denote the keys used for pagination and results. this.descriptors.page = { - listJobs: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'jobs') + listJobs: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'jobs', + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.cloud.bigquery.v2.JobService', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.cloud.bigquery.v2.JobService', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + { 'x-goog-api-client': clientHeader.join(' ') }, + ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -233,37 +266,48 @@ export class JobServiceClient { // Put together the "service stub" for // google.cloud.bigquery.v2.JobService. this.jobServiceStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.cloud.bigquery.v2.JobService') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.cloud.bigquery.v2.JobService', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.cloud.bigquery.v2.JobService, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts, + this._providedCustomServicePath, + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const jobServiceStubMethods = - ['cancelJob', 'getJob', 'insertJob', 'deleteJob', 'listJobs', 'getQueryResults', 'query']; + const jobServiceStubMethods = [ + 'cancelJob', + 'getJob', + 'insertJob', + 'deleteJob', + 'listJobs', + 'getQueryResults', + 'query', + ]; for (const methodName of jobServiceStubMethods) { const callPromise = this.jobServiceStub.then( - stub => (...args: Array<{}>) => { - if (this._terminated) { - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error|null|undefined) => () => { + (stub) => + (...args: Array<{}>) => { + if (this._terminated) { + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { throw err; - }); + }, + ); - const descriptor = - this.descriptors.page[methodName] || - undefined; + const descriptor = this.descriptors.page[methodName] || undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -278,8 +322,14 @@ export class JobServiceClient { * @returns {string} The DNS address for this service. */ static get servicePath() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'bigquery.googleapis.com'; } @@ -291,8 +341,14 @@ export class JobServiceClient { * @returns {string} The DNS address for this service. */ static get apiEndpoint() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'bigquery.googleapis.com'; } @@ -329,7 +385,7 @@ export class JobServiceClient { 'https://www.googleapis.com/auth/cloud-platform.read-only', 'https://www.googleapis.com/auth/devstorage.full_control', 'https://www.googleapis.com/auth/devstorage.read_only', - 'https://www.googleapis.com/auth/devstorage.read_write' + 'https://www.googleapis.com/auth/devstorage.read_write', ]; } @@ -339,8 +395,9 @@ export class JobServiceClient { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId(callback?: Callback): - Promise|void { + getProjectId( + callback?: Callback, + ): Promise | void { if (callback) { this.auth.getProjectId(callback); return; @@ -351,768 +408,979 @@ export class JobServiceClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Requests that a job be cancelled. This call will return immediately, and - * the client will need to poll for the job status to see if the cancel - * completed successfully. Cancelled jobs may still incur costs. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.projectId - * Required. Project ID of the job to cancel - * @param {string} request.jobId - * Required. Job ID of the job to cancel - * @param {string} request.location - * The geographic location of the job. You must specify the location to run - * the job for the following scenarios: - * - * * If the location to run a job is not in the `us` or - * the `eu` multi-regional location - * * If the job's location is in a single region (for example, - * `us-central1`) - * - * For more information, see - * https://cloud.google.com/bigquery/docs/locations#specifying_your_location. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.bigquery.v2.JobCancelResponse|JobCancelResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/job_service.cancel_job.js - * region_tag:bigquery_v2_generated_JobService_CancelJob_async - */ + /** + * Requests that a job be cancelled. This call will return immediately, and + * the client will need to poll for the job status to see if the cancel + * completed successfully. Cancelled jobs may still incur costs. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.projectId + * Required. Project ID of the job to cancel + * @param {string} request.jobId + * Required. Job ID of the job to cancel + * @param {string} request.location + * The geographic location of the job. You must specify the location to run + * the job for the following scenarios: + * + * * If the location to run a job is not in the `us` or + * the `eu` multi-regional location + * * If the job's location is in a single region (for example, + * `us-central1`) + * + * For more information, see + * https://cloud.google.com/bigquery/docs/locations#specifying_your_location. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.bigquery.v2.JobCancelResponse|JobCancelResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/job_service.cancel_job.js + * region_tag:bigquery_v2_generated_JobService_CancelJob_async + */ cancelJob( - request?: protos.google.cloud.bigquery.v2.ICancelJobRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.bigquery.v2.IJobCancelResponse, - protos.google.cloud.bigquery.v2.ICancelJobRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.bigquery.v2.ICancelJobRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.bigquery.v2.IJobCancelResponse, + protos.google.cloud.bigquery.v2.ICancelJobRequest | undefined, + {} | undefined, + ] + >; cancelJob( - request: protos.google.cloud.bigquery.v2.ICancelJobRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.bigquery.v2.IJobCancelResponse, - protos.google.cloud.bigquery.v2.ICancelJobRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.bigquery.v2.ICancelJobRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.bigquery.v2.IJobCancelResponse, + protos.google.cloud.bigquery.v2.ICancelJobRequest | null | undefined, + {} | null | undefined + >, + ): void; cancelJob( - request: protos.google.cloud.bigquery.v2.ICancelJobRequest, - callback: Callback< - protos.google.cloud.bigquery.v2.IJobCancelResponse, - protos.google.cloud.bigquery.v2.ICancelJobRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.bigquery.v2.ICancelJobRequest, + callback: Callback< + protos.google.cloud.bigquery.v2.IJobCancelResponse, + protos.google.cloud.bigquery.v2.ICancelJobRequest | null | undefined, + {} | null | undefined + >, + ): void; cancelJob( - request?: protos.google.cloud.bigquery.v2.ICancelJobRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.bigquery.v2.IJobCancelResponse, - protos.google.cloud.bigquery.v2.ICancelJobRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.bigquery.v2.ICancelJobRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.bigquery.v2.IJobCancelResponse, - protos.google.cloud.bigquery.v2.ICancelJobRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.bigquery.v2.IJobCancelResponse, - protos.google.cloud.bigquery.v2.ICancelJobRequest|undefined, {}|undefined - ]>|void { + protos.google.cloud.bigquery.v2.ICancelJobRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.bigquery.v2.IJobCancelResponse, + protos.google.cloud.bigquery.v2.ICancelJobRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.bigquery.v2.IJobCancelResponse, + protos.google.cloud.bigquery.v2.ICancelJobRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'project_id': request.projectId?.toString() ?? '', - 'job_id': request.jobId?.toString() ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + project_id: request.projectId?.toString() ?? '', + job_id: request.jobId?.toString() ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('cancelJob request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.bigquery.v2.IJobCancelResponse, - protos.google.cloud.bigquery.v2.ICancelJobRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.bigquery.v2.IJobCancelResponse, + protos.google.cloud.bigquery.v2.ICancelJobRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('cancelJob response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.cancelJob(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.bigquery.v2.IJobCancelResponse, - protos.google.cloud.bigquery.v2.ICancelJobRequest|undefined, {}|undefined - ]) => { - this._log.info('cancelJob response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .cancelJob(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.bigquery.v2.IJobCancelResponse, + protos.google.cloud.bigquery.v2.ICancelJobRequest | undefined, + {} | undefined, + ]) => { + this._log.info('cancelJob response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Returns information about a specific job. Job information is available for - * a six month period after creation. Requires that you're the person who ran - * the job, or have the Is Owner project role. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.projectId - * Required. Project ID of the requested job. - * @param {string} request.jobId - * Required. Job ID of the requested job. - * @param {string} request.location - * The geographic location of the job. You must specify the location to run - * the job for the following scenarios: - * - * * If the location to run a job is not in the `us` or - * the `eu` multi-regional location - * * If the job's location is in a single region (for example, - * `us-central1`) - * - * For more information, see - * https://cloud.google.com/bigquery/docs/locations#specifying_your_location. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.bigquery.v2.Job|Job}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/job_service.get_job.js - * region_tag:bigquery_v2_generated_JobService_GetJob_async - */ + /** + * Returns information about a specific job. Job information is available for + * a six month period after creation. Requires that you're the person who ran + * the job, or have the Is Owner project role. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.projectId + * Required. Project ID of the requested job. + * @param {string} request.jobId + * Required. Job ID of the requested job. + * @param {string} request.location + * The geographic location of the job. You must specify the location to run + * the job for the following scenarios: + * + * * If the location to run a job is not in the `us` or + * the `eu` multi-regional location + * * If the job's location is in a single region (for example, + * `us-central1`) + * + * For more information, see + * https://cloud.google.com/bigquery/docs/locations#specifying_your_location. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.bigquery.v2.Job|Job}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/job_service.get_job.js + * region_tag:bigquery_v2_generated_JobService_GetJob_async + */ getJob( - request?: protos.google.cloud.bigquery.v2.IGetJobRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.bigquery.v2.IJob, - protos.google.cloud.bigquery.v2.IGetJobRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.bigquery.v2.IGetJobRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.bigquery.v2.IJob, + protos.google.cloud.bigquery.v2.IGetJobRequest | undefined, + {} | undefined, + ] + >; getJob( - request: protos.google.cloud.bigquery.v2.IGetJobRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.bigquery.v2.IJob, - protos.google.cloud.bigquery.v2.IGetJobRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.bigquery.v2.IGetJobRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.bigquery.v2.IJob, + protos.google.cloud.bigquery.v2.IGetJobRequest | null | undefined, + {} | null | undefined + >, + ): void; getJob( - request: protos.google.cloud.bigquery.v2.IGetJobRequest, - callback: Callback< - protos.google.cloud.bigquery.v2.IJob, - protos.google.cloud.bigquery.v2.IGetJobRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.bigquery.v2.IGetJobRequest, + callback: Callback< + protos.google.cloud.bigquery.v2.IJob, + protos.google.cloud.bigquery.v2.IGetJobRequest | null | undefined, + {} | null | undefined + >, + ): void; getJob( - request?: protos.google.cloud.bigquery.v2.IGetJobRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.bigquery.v2.IJob, - protos.google.cloud.bigquery.v2.IGetJobRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.bigquery.v2.IGetJobRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.bigquery.v2.IJob, - protos.google.cloud.bigquery.v2.IGetJobRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.bigquery.v2.IJob, - protos.google.cloud.bigquery.v2.IGetJobRequest|undefined, {}|undefined - ]>|void { + protos.google.cloud.bigquery.v2.IGetJobRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.bigquery.v2.IJob, + protos.google.cloud.bigquery.v2.IGetJobRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.bigquery.v2.IJob, + protos.google.cloud.bigquery.v2.IGetJobRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'project_id': request.projectId?.toString() ?? '', - 'job_id': request.jobId?.toString() ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + project_id: request.projectId?.toString() ?? '', + job_id: request.jobId?.toString() ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getJob request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.bigquery.v2.IJob, - protos.google.cloud.bigquery.v2.IGetJobRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.bigquery.v2.IJob, + protos.google.cloud.bigquery.v2.IGetJobRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getJob response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.getJob(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.bigquery.v2.IJob, - protos.google.cloud.bigquery.v2.IGetJobRequest|undefined, {}|undefined - ]) => { - this._log.info('getJob response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getJob(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.bigquery.v2.IJob, + protos.google.cloud.bigquery.v2.IGetJobRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getJob response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Starts a new asynchronous job. - * - * This API has two different kinds of endpoint URIs, as this method supports - * a variety of use cases. - * - * * The *Metadata* URI is used for most interactions, as it accepts the job - * configuration directly. - * * The *Upload* URI is ONLY for the case when you're sending both a load job - * configuration and a data stream together. In this case, the Upload URI - * accepts the job configuration and the data as two distinct multipart MIME - * parts. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.projectId - * Project ID of project that will be billed for the job. - * @param {google.cloud.bigquery.v2.Job} request.job - * Jobs resource to insert. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.bigquery.v2.Job|Job}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/job_service.insert_job.js - * region_tag:bigquery_v2_generated_JobService_InsertJob_async - */ + /** + * Starts a new asynchronous job. + * + * This API has two different kinds of endpoint URIs, as this method supports + * a variety of use cases. + * + * * The *Metadata* URI is used for most interactions, as it accepts the job + * configuration directly. + * * The *Upload* URI is ONLY for the case when you're sending both a load job + * configuration and a data stream together. In this case, the Upload URI + * accepts the job configuration and the data as two distinct multipart MIME + * parts. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.projectId + * Project ID of project that will be billed for the job. + * @param {google.cloud.bigquery.v2.Job} request.job + * Jobs resource to insert. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.bigquery.v2.Job|Job}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/job_service.insert_job.js + * region_tag:bigquery_v2_generated_JobService_InsertJob_async + */ insertJob( - request?: protos.google.cloud.bigquery.v2.IInsertJobRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.bigquery.v2.IJob, - protos.google.cloud.bigquery.v2.IInsertJobRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.bigquery.v2.IInsertJobRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.bigquery.v2.IJob, + protos.google.cloud.bigquery.v2.IInsertJobRequest | undefined, + {} | undefined, + ] + >; insertJob( - request: protos.google.cloud.bigquery.v2.IInsertJobRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.bigquery.v2.IJob, - protos.google.cloud.bigquery.v2.IInsertJobRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.bigquery.v2.IInsertJobRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.bigquery.v2.IJob, + protos.google.cloud.bigquery.v2.IInsertJobRequest | null | undefined, + {} | null | undefined + >, + ): void; insertJob( - request: protos.google.cloud.bigquery.v2.IInsertJobRequest, - callback: Callback< - protos.google.cloud.bigquery.v2.IJob, - protos.google.cloud.bigquery.v2.IInsertJobRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.bigquery.v2.IInsertJobRequest, + callback: Callback< + protos.google.cloud.bigquery.v2.IJob, + protos.google.cloud.bigquery.v2.IInsertJobRequest | null | undefined, + {} | null | undefined + >, + ): void; insertJob( - request?: protos.google.cloud.bigquery.v2.IInsertJobRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.bigquery.v2.IJob, - protos.google.cloud.bigquery.v2.IInsertJobRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.bigquery.v2.IInsertJobRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.bigquery.v2.IJob, - protos.google.cloud.bigquery.v2.IInsertJobRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.bigquery.v2.IJob, - protos.google.cloud.bigquery.v2.IInsertJobRequest|undefined, {}|undefined - ]>|void { + protos.google.cloud.bigquery.v2.IInsertJobRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.bigquery.v2.IJob, + protos.google.cloud.bigquery.v2.IInsertJobRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.bigquery.v2.IJob, + protos.google.cloud.bigquery.v2.IInsertJobRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'project_id': request.projectId?.toString() ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + project_id: request.projectId?.toString() ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('insertJob request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.bigquery.v2.IJob, - protos.google.cloud.bigquery.v2.IInsertJobRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.bigquery.v2.IJob, + protos.google.cloud.bigquery.v2.IInsertJobRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('insertJob response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.insertJob(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.bigquery.v2.IJob, - protos.google.cloud.bigquery.v2.IInsertJobRequest|undefined, {}|undefined - ]) => { - this._log.info('insertJob response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .insertJob(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.bigquery.v2.IJob, + protos.google.cloud.bigquery.v2.IInsertJobRequest | undefined, + {} | undefined, + ]) => { + this._log.info('insertJob response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Requests the deletion of the metadata of a job. This call returns when the - * job's metadata is deleted. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.projectId - * Required. Project ID of the job for which metadata is to be deleted. - * @param {string} request.jobId - * Required. Job ID of the job for which metadata is to be deleted. If this is - * a parent job which has child jobs, the metadata from all child jobs will be - * deleted as well. Direct deletion of the metadata of child jobs is not - * allowed. - * @param {string} request.location - * The geographic location of the job. Required. - * See details at: - * https://cloud.google.com/bigquery/docs/locations#specifying_your_location. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/job_service.delete_job.js - * region_tag:bigquery_v2_generated_JobService_DeleteJob_async - */ + /** + * Requests the deletion of the metadata of a job. This call returns when the + * job's metadata is deleted. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.projectId + * Required. Project ID of the job for which metadata is to be deleted. + * @param {string} request.jobId + * Required. Job ID of the job for which metadata is to be deleted. If this is + * a parent job which has child jobs, the metadata from all child jobs will be + * deleted as well. Direct deletion of the metadata of child jobs is not + * allowed. + * @param {string} request.location + * The geographic location of the job. Required. + * See details at: + * https://cloud.google.com/bigquery/docs/locations#specifying_your_location. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/job_service.delete_job.js + * region_tag:bigquery_v2_generated_JobService_DeleteJob_async + */ deleteJob( - request?: protos.google.cloud.bigquery.v2.IDeleteJobRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.cloud.bigquery.v2.IDeleteJobRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.bigquery.v2.IDeleteJobRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.cloud.bigquery.v2.IDeleteJobRequest | undefined, + {} | undefined, + ] + >; deleteJob( - request: protos.google.cloud.bigquery.v2.IDeleteJobRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.cloud.bigquery.v2.IDeleteJobRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.bigquery.v2.IDeleteJobRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.cloud.bigquery.v2.IDeleteJobRequest | null | undefined, + {} | null | undefined + >, + ): void; deleteJob( - request: protos.google.cloud.bigquery.v2.IDeleteJobRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.cloud.bigquery.v2.IDeleteJobRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.bigquery.v2.IDeleteJobRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.cloud.bigquery.v2.IDeleteJobRequest | null | undefined, + {} | null | undefined + >, + ): void; deleteJob( - request?: protos.google.cloud.bigquery.v2.IDeleteJobRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.protobuf.IEmpty, - protos.google.cloud.bigquery.v2.IDeleteJobRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.bigquery.v2.IDeleteJobRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.cloud.bigquery.v2.IDeleteJobRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.cloud.bigquery.v2.IDeleteJobRequest|undefined, {}|undefined - ]>|void { + protos.google.cloud.bigquery.v2.IDeleteJobRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + protos.google.cloud.bigquery.v2.IDeleteJobRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.cloud.bigquery.v2.IDeleteJobRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'project_id': request.projectId?.toString() ?? '', - 'job_id': request.jobId?.toString() ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + project_id: request.projectId?.toString() ?? '', + job_id: request.jobId?.toString() ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('deleteJob request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.cloud.bigquery.v2.IDeleteJobRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + protos.google.cloud.bigquery.v2.IDeleteJobRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteJob response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.deleteJob(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.cloud.bigquery.v2.IDeleteJobRequest|undefined, {}|undefined - ]) => { - this._log.info('deleteJob response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteJob(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.cloud.bigquery.v2.IDeleteJobRequest | undefined, + {} | undefined, + ]) => { + this._log.info('deleteJob response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * RPC to get the results of a query job. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.projectId - * Required. Project ID of the query job. - * @param {string} request.jobId - * Required. Job ID of the query job. - * @param {google.protobuf.UInt64Value} request.startIndex - * Zero-based index of the starting row. - * @param {string} request.pageToken - * Page token, returned by a previous call, to request the next page of - * results. - * @param {google.protobuf.UInt32Value} request.maxResults - * Maximum number of results to read. - * @param {google.protobuf.UInt32Value} request.timeoutMs - * Optional: Specifies the maximum amount of time, in milliseconds, that the - * client is willing to wait for the query to complete. By default, this limit - * is 10 seconds (10,000 milliseconds). If the query is complete, the - * jobComplete field in the response is true. If the query has not yet - * completed, jobComplete is false. - * - * You can request a longer timeout period in the timeoutMs field. However, - * the call is not guaranteed to wait for the specified timeout; it typically - * returns after around 200 seconds (200,000 milliseconds), even if the query - * is not complete. - * - * If jobComplete is false, you can continue to wait for the query to complete - * by calling the getQueryResults method until the jobComplete field in the - * getQueryResults response is true. - * @param {string} request.location - * The geographic location of the job. You must specify the location to run - * the job for the following scenarios: - * - * * If the location to run a job is not in the `us` or - * the `eu` multi-regional location - * * If the job's location is in a single region (for example, - * `us-central1`) - * - * For more information, see - * https://cloud.google.com/bigquery/docs/locations#specifying_your_location. - * @param {google.cloud.bigquery.v2.DataFormatOptions} [request.formatOptions] - * Optional. Output format adjustments. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.bigquery.v2.GetQueryResultsResponse|GetQueryResultsResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/job_service.get_query_results.js - * region_tag:bigquery_v2_generated_JobService_GetQueryResults_async - */ + /** + * RPC to get the results of a query job. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.projectId + * Required. Project ID of the query job. + * @param {string} request.jobId + * Required. Job ID of the query job. + * @param {google.protobuf.UInt64Value} request.startIndex + * Zero-based index of the starting row. + * @param {string} request.pageToken + * Page token, returned by a previous call, to request the next page of + * results. + * @param {google.protobuf.UInt32Value} request.maxResults + * Maximum number of results to read. + * @param {google.protobuf.UInt32Value} request.timeoutMs + * Optional: Specifies the maximum amount of time, in milliseconds, that the + * client is willing to wait for the query to complete. By default, this limit + * is 10 seconds (10,000 milliseconds). If the query is complete, the + * jobComplete field in the response is true. If the query has not yet + * completed, jobComplete is false. + * + * You can request a longer timeout period in the timeoutMs field. However, + * the call is not guaranteed to wait for the specified timeout; it typically + * returns after around 200 seconds (200,000 milliseconds), even if the query + * is not complete. + * + * If jobComplete is false, you can continue to wait for the query to complete + * by calling the getQueryResults method until the jobComplete field in the + * getQueryResults response is true. + * @param {string} request.location + * The geographic location of the job. You must specify the location to run + * the job for the following scenarios: + * + * * If the location to run a job is not in the `us` or + * the `eu` multi-regional location + * * If the job's location is in a single region (for example, + * `us-central1`) + * + * For more information, see + * https://cloud.google.com/bigquery/docs/locations#specifying_your_location. + * @param {google.cloud.bigquery.v2.DataFormatOptions} [request.formatOptions] + * Optional. Output format adjustments. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.bigquery.v2.GetQueryResultsResponse|GetQueryResultsResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/job_service.get_query_results.js + * region_tag:bigquery_v2_generated_JobService_GetQueryResults_async + */ getQueryResults( - request?: protos.google.cloud.bigquery.v2.IGetQueryResultsRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.bigquery.v2.IGetQueryResultsResponse, - protos.google.cloud.bigquery.v2.IGetQueryResultsRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.bigquery.v2.IGetQueryResultsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.bigquery.v2.IGetQueryResultsResponse, + protos.google.cloud.bigquery.v2.IGetQueryResultsRequest | undefined, + {} | undefined, + ] + >; getQueryResults( - request: protos.google.cloud.bigquery.v2.IGetQueryResultsRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.bigquery.v2.IGetQueryResultsResponse, - protos.google.cloud.bigquery.v2.IGetQueryResultsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.bigquery.v2.IGetQueryResultsRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.bigquery.v2.IGetQueryResultsResponse, + | protos.google.cloud.bigquery.v2.IGetQueryResultsRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getQueryResults( - request: protos.google.cloud.bigquery.v2.IGetQueryResultsRequest, - callback: Callback< - protos.google.cloud.bigquery.v2.IGetQueryResultsResponse, - protos.google.cloud.bigquery.v2.IGetQueryResultsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.bigquery.v2.IGetQueryResultsRequest, + callback: Callback< + protos.google.cloud.bigquery.v2.IGetQueryResultsResponse, + | protos.google.cloud.bigquery.v2.IGetQueryResultsRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getQueryResults( - request?: protos.google.cloud.bigquery.v2.IGetQueryResultsRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.cloud.bigquery.v2.IGetQueryResultsRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.bigquery.v2.IGetQueryResultsResponse, - protos.google.cloud.bigquery.v2.IGetQueryResultsRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.cloud.bigquery.v2.IGetQueryResultsResponse, - protos.google.cloud.bigquery.v2.IGetQueryResultsRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.bigquery.v2.IGetQueryResultsResponse, - protos.google.cloud.bigquery.v2.IGetQueryResultsRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.bigquery.v2.IGetQueryResultsRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.bigquery.v2.IGetQueryResultsResponse, + | protos.google.cloud.bigquery.v2.IGetQueryResultsRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.bigquery.v2.IGetQueryResultsResponse, + protos.google.cloud.bigquery.v2.IGetQueryResultsRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'project_id': request.projectId?.toString() ?? '', - 'job_id': request.jobId?.toString() ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + project_id: request.projectId?.toString() ?? '', + job_id: request.jobId?.toString() ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getQueryResults request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.bigquery.v2.IGetQueryResultsResponse, - protos.google.cloud.bigquery.v2.IGetQueryResultsRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.bigquery.v2.IGetQueryResultsResponse, + | protos.google.cloud.bigquery.v2.IGetQueryResultsRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getQueryResults response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.getQueryResults(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.bigquery.v2.IGetQueryResultsResponse, - protos.google.cloud.bigquery.v2.IGetQueryResultsRequest|undefined, {}|undefined - ]) => { - this._log.info('getQueryResults response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getQueryResults(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.bigquery.v2.IGetQueryResultsResponse, + protos.google.cloud.bigquery.v2.IGetQueryResultsRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getQueryResults response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Runs a BigQuery SQL query synchronously and returns query results if the - * query completes within a specified timeout. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.projectId - * Required. Project ID of the query request. - * @param {google.cloud.bigquery.v2.QueryRequest} request.queryRequest - * The query request body. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.bigquery.v2.QueryResponse|QueryResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/job_service.query.js - * region_tag:bigquery_v2_generated_JobService_Query_async - */ + /** + * Runs a BigQuery SQL query synchronously and returns query results if the + * query completes within a specified timeout. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.projectId + * Required. Project ID of the query request. + * @param {google.cloud.bigquery.v2.QueryRequest} request.queryRequest + * The query request body. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.bigquery.v2.QueryResponse|QueryResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/job_service.query.js + * region_tag:bigquery_v2_generated_JobService_Query_async + */ query( - request?: protos.google.cloud.bigquery.v2.IPostQueryRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.bigquery.v2.IQueryResponse, - protos.google.cloud.bigquery.v2.IPostQueryRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.bigquery.v2.IPostQueryRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.bigquery.v2.IQueryResponse, + protos.google.cloud.bigquery.v2.IPostQueryRequest | undefined, + {} | undefined, + ] + >; query( - request: protos.google.cloud.bigquery.v2.IPostQueryRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.bigquery.v2.IQueryResponse, - protos.google.cloud.bigquery.v2.IPostQueryRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.bigquery.v2.IPostQueryRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.bigquery.v2.IQueryResponse, + protos.google.cloud.bigquery.v2.IPostQueryRequest | null | undefined, + {} | null | undefined + >, + ): void; query( - request: protos.google.cloud.bigquery.v2.IPostQueryRequest, - callback: Callback< - protos.google.cloud.bigquery.v2.IQueryResponse, - protos.google.cloud.bigquery.v2.IPostQueryRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.bigquery.v2.IPostQueryRequest, + callback: Callback< + protos.google.cloud.bigquery.v2.IQueryResponse, + protos.google.cloud.bigquery.v2.IPostQueryRequest | null | undefined, + {} | null | undefined + >, + ): void; query( - request?: protos.google.cloud.bigquery.v2.IPostQueryRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.bigquery.v2.IQueryResponse, - protos.google.cloud.bigquery.v2.IPostQueryRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.bigquery.v2.IPostQueryRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.bigquery.v2.IQueryResponse, - protos.google.cloud.bigquery.v2.IPostQueryRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.bigquery.v2.IQueryResponse, - protos.google.cloud.bigquery.v2.IPostQueryRequest|undefined, {}|undefined - ]>|void { + protos.google.cloud.bigquery.v2.IPostQueryRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.bigquery.v2.IQueryResponse, + protos.google.cloud.bigquery.v2.IPostQueryRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.bigquery.v2.IQueryResponse, + protos.google.cloud.bigquery.v2.IPostQueryRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'project_id': request.projectId?.toString() ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + project_id: request.projectId?.toString() ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('query request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.bigquery.v2.IQueryResponse, - protos.google.cloud.bigquery.v2.IPostQueryRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.bigquery.v2.IQueryResponse, + protos.google.cloud.bigquery.v2.IPostQueryRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('query response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.query(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.bigquery.v2.IQueryResponse, - protos.google.cloud.bigquery.v2.IPostQueryRequest|undefined, {}|undefined - ]) => { - this._log.info('query response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .query(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.bigquery.v2.IQueryResponse, + protos.google.cloud.bigquery.v2.IPostQueryRequest | undefined, + {} | undefined, + ]) => { + this._log.info('query response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } - /** - * Lists all jobs that you started in the specified project. Job information - * is available for a six month period after creation. The job list is sorted - * in reverse chronological order, by job creation time. Requires the Can View - * project role, or the Is Owner project role if you set the allUsers - * property. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.projectId - * Project ID of the jobs to list. - * @param {boolean} request.allUsers - * Whether to display jobs owned by all users in the project. Default False. - * @param {google.protobuf.Int32Value| number } request.maxResults - * The maximum number of results to return in a single response page. - * Leverage the page tokens to iterate through the entire collection. - * @param {number} request.minCreationTime - * Min value for job creation time, in milliseconds since the POSIX epoch. - * If set, only jobs created after or at this timestamp are returned. - * @param {google.protobuf.UInt64Value} request.maxCreationTime - * Max value for job creation time, in milliseconds since the POSIX epoch. - * If set, only jobs created before or at this timestamp are returned. - * @param {string} request.pageToken - * Page token, returned by a previous call, to request the next page of - * results. - * @param {google.cloud.bigquery.v2.ListJobsRequest.Projection} request.projection - * Restrict information returned to a set of selected fields - * @param {number[]} request.stateFilter - * Filter for job state - * @param {string} request.parentJobId - * If set, show only child jobs of the specified parent. Otherwise, show all - * top-level jobs. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.cloud.bigquery.v2.ListFormatJob|ListFormatJob}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `listJobsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Lists all jobs that you started in the specified project. Job information + * is available for a six month period after creation. The job list is sorted + * in reverse chronological order, by job creation time. Requires the Can View + * project role, or the Is Owner project role if you set the allUsers + * property. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.projectId + * Project ID of the jobs to list. + * @param {boolean} request.allUsers + * Whether to display jobs owned by all users in the project. Default False. + * @param {google.protobuf.Int32Value| number } request.maxResults + * The maximum number of results to return in a single response page. + * Leverage the page tokens to iterate through the entire collection. + * @param {number} request.minCreationTime + * Min value for job creation time, in milliseconds since the POSIX epoch. + * If set, only jobs created after or at this timestamp are returned. + * @param {google.protobuf.UInt64Value} request.maxCreationTime + * Max value for job creation time, in milliseconds since the POSIX epoch. + * If set, only jobs created before or at this timestamp are returned. + * @param {string} request.pageToken + * Page token, returned by a previous call, to request the next page of + * results. + * @param {google.cloud.bigquery.v2.ListJobsRequest.Projection} request.projection + * Restrict information returned to a set of selected fields + * @param {number[]} request.stateFilter + * Filter for job state + * @param {string} request.parentJobId + * If set, show only child jobs of the specified parent. Otherwise, show all + * top-level jobs. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.cloud.bigquery.v2.ListFormatJob|ListFormatJob}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listJobsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listJobs( - request?: protos.google.cloud.bigquery.v2.IListJobsRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.bigquery.v2.IListFormatJob[], - protos.google.cloud.bigquery.v2.IListJobsRequest|null, - protos.google.cloud.bigquery.v2.IJobList - ]>; + request?: protos.google.cloud.bigquery.v2.IListJobsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.bigquery.v2.IListFormatJob[], + protos.google.cloud.bigquery.v2.IListJobsRequest | null, + protos.google.cloud.bigquery.v2.IJobList, + ] + >; listJobs( - request: protos.google.cloud.bigquery.v2.IListJobsRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.cloud.bigquery.v2.IListJobsRequest, - protos.google.cloud.bigquery.v2.IJobList|null|undefined, - protos.google.cloud.bigquery.v2.IListFormatJob>): void; + request: protos.google.cloud.bigquery.v2.IListJobsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.cloud.bigquery.v2.IListJobsRequest, + protos.google.cloud.bigquery.v2.IJobList | null | undefined, + protos.google.cloud.bigquery.v2.IListFormatJob + >, + ): void; listJobs( - request: protos.google.cloud.bigquery.v2.IListJobsRequest, - callback: PaginationCallback< - protos.google.cloud.bigquery.v2.IListJobsRequest, - protos.google.cloud.bigquery.v2.IJobList|null|undefined, - protos.google.cloud.bigquery.v2.IListFormatJob>): void; + request: protos.google.cloud.bigquery.v2.IListJobsRequest, + callback: PaginationCallback< + protos.google.cloud.bigquery.v2.IListJobsRequest, + protos.google.cloud.bigquery.v2.IJobList | null | undefined, + protos.google.cloud.bigquery.v2.IListFormatJob + >, + ): void; listJobs( - request?: protos.google.cloud.bigquery.v2.IListJobsRequest, - optionsOrCallback?: CallOptions|PaginationCallback< + request?: protos.google.cloud.bigquery.v2.IListJobsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.cloud.bigquery.v2.IListJobsRequest, - protos.google.cloud.bigquery.v2.IJobList|null|undefined, - protos.google.cloud.bigquery.v2.IListFormatJob>, - callback?: PaginationCallback< - protos.google.cloud.bigquery.v2.IListJobsRequest, - protos.google.cloud.bigquery.v2.IJobList|null|undefined, - protos.google.cloud.bigquery.v2.IListFormatJob>): - Promise<[ - protos.google.cloud.bigquery.v2.IListFormatJob[], - protos.google.cloud.bigquery.v2.IListJobsRequest|null, - protos.google.cloud.bigquery.v2.IJobList - ]>|void { + protos.google.cloud.bigquery.v2.IJobList | null | undefined, + protos.google.cloud.bigquery.v2.IListFormatJob + >, + callback?: PaginationCallback< + protos.google.cloud.bigquery.v2.IListJobsRequest, + protos.google.cloud.bigquery.v2.IJobList | null | undefined, + protos.google.cloud.bigquery.v2.IListFormatJob + >, + ): Promise< + [ + protos.google.cloud.bigquery.v2.IListFormatJob[], + protos.google.cloud.bigquery.v2.IListJobsRequest | null, + protos.google.cloud.bigquery.v2.IJobList, + ] + > | void { request = request || {}; - // Converts number to Unit32 or Int32 value for non-compliant APIs. - if(request.maxResults && typeof request.maxResults === "number"){ - const maxResultsObject = {"value": request.maxResults} - request.maxResults = maxResultsObject - } + // Converts number to Unit32 or Int32 value for non-compliant APIs. + if (request.maxResults && typeof request.maxResults === 'number') { + const maxResultsObject = { value: request.maxResults }; + request.maxResults = maxResultsObject; + } let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'project_id': request.projectId?.toString() ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + project_id: request.projectId?.toString() ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.cloud.bigquery.v2.IListJobsRequest, - protos.google.cloud.bigquery.v2.IJobList|null|undefined, - protos.google.cloud.bigquery.v2.IListFormatJob>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.cloud.bigquery.v2.IListJobsRequest, + protos.google.cloud.bigquery.v2.IJobList | null | undefined, + protos.google.cloud.bigquery.v2.IListFormatJob + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listJobs values %j', values); callback!(error, values, nextPageRequest, rawResponse); @@ -1121,140 +1389,144 @@ export class JobServiceClient { this._log.info('listJobs request %j', request); return this.innerApiCalls .listJobs(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.cloud.bigquery.v2.IListFormatJob[], - protos.google.cloud.bigquery.v2.IListJobsRequest|null, - protos.google.cloud.bigquery.v2.IJobList - ]) => { - this._log.info('listJobs values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.cloud.bigquery.v2.IListFormatJob[], + protos.google.cloud.bigquery.v2.IListJobsRequest | null, + protos.google.cloud.bigquery.v2.IJobList, + ]) => { + this._log.info('listJobs values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listJobs`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.projectId - * Project ID of the jobs to list. - * @param {boolean} request.allUsers - * Whether to display jobs owned by all users in the project. Default False. - * @param {google.protobuf.Int32Value} request.maxResults - * The maximum number of results to return in a single response page. - * Leverage the page tokens to iterate through the entire collection. - * @param {number} request.minCreationTime - * Min value for job creation time, in milliseconds since the POSIX epoch. - * If set, only jobs created after or at this timestamp are returned. - * @param {google.protobuf.UInt64Value} request.maxCreationTime - * Max value for job creation time, in milliseconds since the POSIX epoch. - * If set, only jobs created before or at this timestamp are returned. - * @param {string} request.pageToken - * Page token, returned by a previous call, to request the next page of - * results. - * @param {google.cloud.bigquery.v2.ListJobsRequest.Projection} request.projection - * Restrict information returned to a set of selected fields - * @param {number[]} request.stateFilter - * Filter for job state - * @param {string} request.parentJobId - * If set, show only child jobs of the specified parent. Otherwise, show all - * top-level jobs. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.cloud.bigquery.v2.ListFormatJob|ListFormatJob} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `listJobsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `listJobs`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.projectId + * Project ID of the jobs to list. + * @param {boolean} request.allUsers + * Whether to display jobs owned by all users in the project. Default False. + * @param {google.protobuf.Int32Value} request.maxResults + * The maximum number of results to return in a single response page. + * Leverage the page tokens to iterate through the entire collection. + * @param {number} request.minCreationTime + * Min value for job creation time, in milliseconds since the POSIX epoch. + * If set, only jobs created after or at this timestamp are returned. + * @param {google.protobuf.UInt64Value} request.maxCreationTime + * Max value for job creation time, in milliseconds since the POSIX epoch. + * If set, only jobs created before or at this timestamp are returned. + * @param {string} request.pageToken + * Page token, returned by a previous call, to request the next page of + * results. + * @param {google.cloud.bigquery.v2.ListJobsRequest.Projection} request.projection + * Restrict information returned to a set of selected fields + * @param {number[]} request.stateFilter + * Filter for job state + * @param {string} request.parentJobId + * If set, show only child jobs of the specified parent. Otherwise, show all + * top-level jobs. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.cloud.bigquery.v2.ListFormatJob|ListFormatJob} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listJobsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listJobsStream( - request?: protos.google.cloud.bigquery.v2.IListJobsRequest, - options?: CallOptions): - Transform{ + request?: protos.google.cloud.bigquery.v2.IListJobsRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'project_id': request.projectId?.toString() ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + project_id: request.projectId?.toString() ?? '', + }); const defaultCallSettings = this._defaults['listJobs']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listJobs stream %j', request); return this.descriptors.page.listJobs.createStream( this.innerApiCalls.listJobs as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listJobs`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.projectId - * Project ID of the jobs to list. - * @param {boolean} request.allUsers - * Whether to display jobs owned by all users in the project. Default False. - * @param {google.protobuf.Int32Value} request.maxResults - * The maximum number of results to return in a single response page. - * Leverage the page tokens to iterate through the entire collection. - * @param {number} request.minCreationTime - * Min value for job creation time, in milliseconds since the POSIX epoch. - * If set, only jobs created after or at this timestamp are returned. - * @param {google.protobuf.UInt64Value} request.maxCreationTime - * Max value for job creation time, in milliseconds since the POSIX epoch. - * If set, only jobs created before or at this timestamp are returned. - * @param {string} request.pageToken - * Page token, returned by a previous call, to request the next page of - * results. - * @param {google.cloud.bigquery.v2.ListJobsRequest.Projection} request.projection - * Restrict information returned to a set of selected fields - * @param {number[]} request.stateFilter - * Filter for job state - * @param {string} request.parentJobId - * If set, show only child jobs of the specified parent. Otherwise, show all - * top-level jobs. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.cloud.bigquery.v2.ListFormatJob|ListFormatJob}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v2/job_service.list_jobs.js - * region_tag:bigquery_v2_generated_JobService_ListJobs_async - */ + /** + * Equivalent to `listJobs`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.projectId + * Project ID of the jobs to list. + * @param {boolean} request.allUsers + * Whether to display jobs owned by all users in the project. Default False. + * @param {google.protobuf.Int32Value} request.maxResults + * The maximum number of results to return in a single response page. + * Leverage the page tokens to iterate through the entire collection. + * @param {number} request.minCreationTime + * Min value for job creation time, in milliseconds since the POSIX epoch. + * If set, only jobs created after or at this timestamp are returned. + * @param {google.protobuf.UInt64Value} request.maxCreationTime + * Max value for job creation time, in milliseconds since the POSIX epoch. + * If set, only jobs created before or at this timestamp are returned. + * @param {string} request.pageToken + * Page token, returned by a previous call, to request the next page of + * results. + * @param {google.cloud.bigquery.v2.ListJobsRequest.Projection} request.projection + * Restrict information returned to a set of selected fields + * @param {number[]} request.stateFilter + * Filter for job state + * @param {string} request.parentJobId + * If set, show only child jobs of the specified parent. Otherwise, show all + * top-level jobs. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.cloud.bigquery.v2.ListFormatJob|ListFormatJob}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v2/job_service.list_jobs.js + * region_tag:bigquery_v2_generated_JobService_ListJobs_async + */ listJobsAsync( - request?: protos.google.cloud.bigquery.v2.IListJobsRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.cloud.bigquery.v2.IListJobsRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'project_id': request.projectId?.toString() ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + project_id: request.projectId?.toString() ?? '', + }); const defaultCallSettings = this._defaults['listJobs']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listJobs iterate %j', request); return this.descriptors.page.listJobs.asyncIterate( this.innerApiCalls['listJobs'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } @@ -1266,7 +1538,7 @@ export class JobServiceClient { */ close(): Promise { if (this.jobServiceStub && !this._terminated) { - return this.jobServiceStub.then(stub => { + return this.jobServiceStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -1274,4 +1546,4 @@ export class JobServiceClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/core/generator/gapic-generator-typescript/baselines/bigquery-v2-esm/esm/src/v2/model_service_client.ts.baseline b/core/generator/gapic-generator-typescript/baselines/bigquery-v2-esm/esm/src/v2/model_service_client.ts.baseline index d8f7e8e28493..4f4983065330 100644 --- a/core/generator/gapic-generator-typescript/baselines/bigquery-v2-esm/esm/src/v2/model_service_client.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/bigquery-v2-esm/esm/src/v2/model_service_client.ts.baseline @@ -18,15 +18,22 @@ /* global window */ import * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions, PaginationCallback, GaxCall} from 'google-gax'; -import {Transform} from 'stream'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + PaginationCallback, + GaxCall, +} from 'google-gax'; +import { Transform } from 'stream'; // @ts-ignore import type * as protos from '../../../protos/protos.js'; import * as model_service_client_config from './model_service_client_config.json'; import fs from 'fs'; import path from 'path'; -import {fileURLToPath} from 'url'; -import {getJSON} from '../json-helper.cjs'; +import { fileURLToPath } from 'url'; +import { getJSON } from '../json-helper.cjs'; // @ts-ignore const dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -36,15 +43,15 @@ const dirname = path.dirname(fileURLToPath(import.meta.url)); * This file defines retry strategy and timeouts for all API methods in this library. */ const gapicConfig = getJSON( - path.join(dirname, 'model_service_client_config.json') + path.join(dirname, 'model_service_client_config.json'), ); const jsonProtos = getJSON( - path.join(dirname, '..', '..', '..', 'protos/protos.json') + path.join(dirname, '..', '..', '..', 'protos/protos.json'), ); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; const version = getJSON( - path.join(dirname, '..', '..', '..', '..', 'package.json') + path.join(dirname, '..', '..', '..', '..', 'package.json'), ).version; /** @@ -62,7 +69,7 @@ export class ModelServiceClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('bigquery'); @@ -74,8 +81,8 @@ export class ModelServiceClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - modelServiceStub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + modelServiceStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of ModelServiceClient. @@ -117,21 +124,42 @@ export class ModelServiceClient { * const client = new ModelServiceClient({fallback: 'rest'}, gax); * ``` */ - constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { // Ensure that options include all the required fields. const staticMembers = this.constructor as typeof ModelServiceClient; - if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { - throw new Error('Please set either universe_domain or universeDomain, but not both.'); + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); } - const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; - this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; this._servicePath = 'bigquery.' + this._universeDomain; - const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; - const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. if (servicePath !== this._servicePath && !('scopes' in opts)) { @@ -153,7 +181,7 @@ export class ModelServiceClient { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; @@ -170,10 +198,7 @@ export class ModelServiceClient { const isEsm = true; const isEsmString = isEsm ? '-esm' : '-cjs'; // Determine the client header string. - const clientHeader = [ - `gax/${this._gaxModule.version}`, - `gapic/${version}`, - ]; + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/{process.versions.node}${isEsmString}`); } else { @@ -181,7 +206,7 @@ export class ModelServiceClient { } if (!opts.fallback) { clientHeader.push(`grpc/${this._gaxGrpc.grpcVersion}`); - } else if (opts.fallback === 'rest' ) { + } else if (opts.fallback === 'rest') { clientHeader.push(`rest/${this._gaxGrpc.grpcVersion}`); } if (opts.libName && opts.libVersion) { @@ -189,20 +214,28 @@ export class ModelServiceClient { } // Load the applicable protos. - this._protos = this._gaxGrpc.loadProtoJSON(jsonProtos as gax.protobuf.INamespace); + this._protos = this._gaxGrpc.loadProtoJSON( + jsonProtos as gax.protobuf.INamespace, + ); // Some of the methods on this service return "paged" results, // (e.g. 50 results at a time, with tokens to get subsequent // pages). Denote the keys used for pagination and results. this.descriptors.page = { - listModels: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'models') + listModels: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'models', + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.cloud.bigquery.v2.ModelService', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.cloud.bigquery.v2.ModelService', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + { 'x-goog-api-client': clientHeader.join(' ') }, + ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -233,37 +266,45 @@ export class ModelServiceClient { // Put together the "service stub" for // google.cloud.bigquery.v2.ModelService. this.modelServiceStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.cloud.bigquery.v2.ModelService') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.cloud.bigquery.v2.ModelService', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.cloud.bigquery.v2.ModelService, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts, + this._providedCustomServicePath, + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const modelServiceStubMethods = - ['getModel', 'listModels', 'patchModel', 'deleteModel']; + const modelServiceStubMethods = [ + 'getModel', + 'listModels', + 'patchModel', + 'deleteModel', + ]; for (const methodName of modelServiceStubMethods) { const callPromise = this.modelServiceStub.then( - stub => (...args: Array<{}>) => { - if (this._terminated) { - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error|null|undefined) => () => { + (stub) => + (...args: Array<{}>) => { + if (this._terminated) { + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { throw err; - }); + }, + ); - const descriptor = - this.descriptors.page[methodName] || - undefined; + const descriptor = this.descriptors.page[methodName] || undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -278,8 +319,14 @@ export class ModelServiceClient { * @returns {string} The DNS address for this service. */ static get servicePath() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'bigquery.googleapis.com'; } @@ -291,8 +338,14 @@ export class ModelServiceClient { * @returns {string} The DNS address for this service. */ static get apiEndpoint() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'bigquery.googleapis.com'; } @@ -326,7 +379,7 @@ export class ModelServiceClient { return [ 'https://www.googleapis.com/auth/bigquery', 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloud-platform.read-only' + 'https://www.googleapis.com/auth/cloud-platform.read-only', ]; } @@ -336,8 +389,9 @@ export class ModelServiceClient { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId(callback?: Callback): - Promise|void { + getProjectId( + callback?: Callback, + ): Promise | void { if (callback) { this.auth.getProjectId(callback); return; @@ -348,401 +402,517 @@ export class ModelServiceClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Gets the specified model resource by model ID. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.projectId - * Required. Project ID of the requested model. - * @param {string} request.datasetId - * Required. Dataset ID of the requested model. - * @param {string} request.modelId - * Required. Model ID of the requested model. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.bigquery.v2.Model|Model}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/model_service.get_model.js - * region_tag:bigquery_v2_generated_ModelService_GetModel_async - */ + /** + * Gets the specified model resource by model ID. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.projectId + * Required. Project ID of the requested model. + * @param {string} request.datasetId + * Required. Dataset ID of the requested model. + * @param {string} request.modelId + * Required. Model ID of the requested model. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.bigquery.v2.Model|Model}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/model_service.get_model.js + * region_tag:bigquery_v2_generated_ModelService_GetModel_async + */ getModel( - request?: protos.google.cloud.bigquery.v2.IGetModelRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.bigquery.v2.IModel, - protos.google.cloud.bigquery.v2.IGetModelRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.bigquery.v2.IGetModelRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.bigquery.v2.IModel, + protos.google.cloud.bigquery.v2.IGetModelRequest | undefined, + {} | undefined, + ] + >; getModel( - request: protos.google.cloud.bigquery.v2.IGetModelRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.bigquery.v2.IModel, - protos.google.cloud.bigquery.v2.IGetModelRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.bigquery.v2.IGetModelRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.bigquery.v2.IModel, + protos.google.cloud.bigquery.v2.IGetModelRequest | null | undefined, + {} | null | undefined + >, + ): void; getModel( - request: protos.google.cloud.bigquery.v2.IGetModelRequest, - callback: Callback< - protos.google.cloud.bigquery.v2.IModel, - protos.google.cloud.bigquery.v2.IGetModelRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.bigquery.v2.IGetModelRequest, + callback: Callback< + protos.google.cloud.bigquery.v2.IModel, + protos.google.cloud.bigquery.v2.IGetModelRequest | null | undefined, + {} | null | undefined + >, + ): void; getModel( - request?: protos.google.cloud.bigquery.v2.IGetModelRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.cloud.bigquery.v2.IGetModelRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.bigquery.v2.IModel, - protos.google.cloud.bigquery.v2.IGetModelRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.cloud.bigquery.v2.IModel, - protos.google.cloud.bigquery.v2.IGetModelRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.bigquery.v2.IModel, - protos.google.cloud.bigquery.v2.IGetModelRequest|undefined, {}|undefined - ]>|void { + protos.google.cloud.bigquery.v2.IGetModelRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.bigquery.v2.IModel, + protos.google.cloud.bigquery.v2.IGetModelRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.bigquery.v2.IModel, + protos.google.cloud.bigquery.v2.IGetModelRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'project_id': request.projectId?.toString() ?? '', - 'dataset_id': request.datasetId?.toString() ?? '', - 'model_id': request.modelId?.toString() ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + project_id: request.projectId?.toString() ?? '', + dataset_id: request.datasetId?.toString() ?? '', + model_id: request.modelId?.toString() ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getModel request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.bigquery.v2.IModel, - protos.google.cloud.bigquery.v2.IGetModelRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.bigquery.v2.IModel, + protos.google.cloud.bigquery.v2.IGetModelRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getModel response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.getModel(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.bigquery.v2.IModel, - protos.google.cloud.bigquery.v2.IGetModelRequest|undefined, {}|undefined - ]) => { - this._log.info('getModel response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getModel(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.bigquery.v2.IModel, + protos.google.cloud.bigquery.v2.IGetModelRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getModel response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Patch specific fields in the specified model. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.projectId - * Required. Project ID of the model to patch. - * @param {string} request.datasetId - * Required. Dataset ID of the model to patch. - * @param {string} request.modelId - * Required. Model ID of the model to patch. - * @param {google.cloud.bigquery.v2.Model} request.model - * Required. Patched model. - * Follows RFC5789 patch semantics. Missing fields are not updated. - * To clear a field, explicitly set to default value. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.bigquery.v2.Model|Model}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/model_service.patch_model.js - * region_tag:bigquery_v2_generated_ModelService_PatchModel_async - */ + /** + * Patch specific fields in the specified model. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.projectId + * Required. Project ID of the model to patch. + * @param {string} request.datasetId + * Required. Dataset ID of the model to patch. + * @param {string} request.modelId + * Required. Model ID of the model to patch. + * @param {google.cloud.bigquery.v2.Model} request.model + * Required. Patched model. + * Follows RFC5789 patch semantics. Missing fields are not updated. + * To clear a field, explicitly set to default value. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.bigquery.v2.Model|Model}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/model_service.patch_model.js + * region_tag:bigquery_v2_generated_ModelService_PatchModel_async + */ patchModel( - request?: protos.google.cloud.bigquery.v2.IPatchModelRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.bigquery.v2.IModel, - protos.google.cloud.bigquery.v2.IPatchModelRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.bigquery.v2.IPatchModelRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.bigquery.v2.IModel, + protos.google.cloud.bigquery.v2.IPatchModelRequest | undefined, + {} | undefined, + ] + >; patchModel( - request: protos.google.cloud.bigquery.v2.IPatchModelRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.bigquery.v2.IModel, - protos.google.cloud.bigquery.v2.IPatchModelRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.bigquery.v2.IPatchModelRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.bigquery.v2.IModel, + protos.google.cloud.bigquery.v2.IPatchModelRequest | null | undefined, + {} | null | undefined + >, + ): void; patchModel( - request: protos.google.cloud.bigquery.v2.IPatchModelRequest, - callback: Callback< - protos.google.cloud.bigquery.v2.IModel, - protos.google.cloud.bigquery.v2.IPatchModelRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.bigquery.v2.IPatchModelRequest, + callback: Callback< + protos.google.cloud.bigquery.v2.IModel, + protos.google.cloud.bigquery.v2.IPatchModelRequest | null | undefined, + {} | null | undefined + >, + ): void; patchModel( - request?: protos.google.cloud.bigquery.v2.IPatchModelRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.bigquery.v2.IModel, - protos.google.cloud.bigquery.v2.IPatchModelRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.bigquery.v2.IPatchModelRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.bigquery.v2.IModel, - protos.google.cloud.bigquery.v2.IPatchModelRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.bigquery.v2.IModel, - protos.google.cloud.bigquery.v2.IPatchModelRequest|undefined, {}|undefined - ]>|void { + protos.google.cloud.bigquery.v2.IPatchModelRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.bigquery.v2.IModel, + protos.google.cloud.bigquery.v2.IPatchModelRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.bigquery.v2.IModel, + protos.google.cloud.bigquery.v2.IPatchModelRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'project_id': request.projectId?.toString() ?? '', - 'dataset_id': request.datasetId?.toString() ?? '', - 'model_id': request.modelId?.toString() ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + project_id: request.projectId?.toString() ?? '', + dataset_id: request.datasetId?.toString() ?? '', + model_id: request.modelId?.toString() ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('patchModel request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.bigquery.v2.IModel, - protos.google.cloud.bigquery.v2.IPatchModelRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.bigquery.v2.IModel, + protos.google.cloud.bigquery.v2.IPatchModelRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('patchModel response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.patchModel(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.bigquery.v2.IModel, - protos.google.cloud.bigquery.v2.IPatchModelRequest|undefined, {}|undefined - ]) => { - this._log.info('patchModel response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .patchModel(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.bigquery.v2.IModel, + protos.google.cloud.bigquery.v2.IPatchModelRequest | undefined, + {} | undefined, + ]) => { + this._log.info('patchModel response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Deletes the model specified by modelId from the dataset. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.projectId - * Required. Project ID of the model to delete. - * @param {string} request.datasetId - * Required. Dataset ID of the model to delete. - * @param {string} request.modelId - * Required. Model ID of the model to delete. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/model_service.delete_model.js - * region_tag:bigquery_v2_generated_ModelService_DeleteModel_async - */ + /** + * Deletes the model specified by modelId from the dataset. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.projectId + * Required. Project ID of the model to delete. + * @param {string} request.datasetId + * Required. Dataset ID of the model to delete. + * @param {string} request.modelId + * Required. Model ID of the model to delete. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/model_service.delete_model.js + * region_tag:bigquery_v2_generated_ModelService_DeleteModel_async + */ deleteModel( - request?: protos.google.cloud.bigquery.v2.IDeleteModelRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.cloud.bigquery.v2.IDeleteModelRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.bigquery.v2.IDeleteModelRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.cloud.bigquery.v2.IDeleteModelRequest | undefined, + {} | undefined, + ] + >; deleteModel( - request: protos.google.cloud.bigquery.v2.IDeleteModelRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.cloud.bigquery.v2.IDeleteModelRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.bigquery.v2.IDeleteModelRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.cloud.bigquery.v2.IDeleteModelRequest | null | undefined, + {} | null | undefined + >, + ): void; deleteModel( - request: protos.google.cloud.bigquery.v2.IDeleteModelRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.cloud.bigquery.v2.IDeleteModelRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.bigquery.v2.IDeleteModelRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.cloud.bigquery.v2.IDeleteModelRequest | null | undefined, + {} | null | undefined + >, + ): void; deleteModel( - request?: protos.google.cloud.bigquery.v2.IDeleteModelRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.protobuf.IEmpty, - protos.google.cloud.bigquery.v2.IDeleteModelRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.bigquery.v2.IDeleteModelRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.cloud.bigquery.v2.IDeleteModelRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.cloud.bigquery.v2.IDeleteModelRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.bigquery.v2.IDeleteModelRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + protos.google.cloud.bigquery.v2.IDeleteModelRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.cloud.bigquery.v2.IDeleteModelRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'project_id': request.projectId?.toString() ?? '', - 'dataset_id': request.datasetId?.toString() ?? '', - 'model_id': request.modelId?.toString() ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + project_id: request.projectId?.toString() ?? '', + dataset_id: request.datasetId?.toString() ?? '', + model_id: request.modelId?.toString() ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('deleteModel request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.cloud.bigquery.v2.IDeleteModelRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.cloud.bigquery.v2.IDeleteModelRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteModel response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.deleteModel(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.cloud.bigquery.v2.IDeleteModelRequest|undefined, {}|undefined - ]) => { - this._log.info('deleteModel response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteModel(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.cloud.bigquery.v2.IDeleteModelRequest | undefined, + {} | undefined, + ]) => { + this._log.info('deleteModel response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } - /** - * Lists all models in the specified dataset. Requires the READER dataset - * role. After retrieving the list of models, you can get information about a - * particular model by calling the models.get method. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.projectId - * Required. Project ID of the models to list. - * @param {string} request.datasetId - * Required. Dataset ID of the models to list. - * @param {google.protobuf.UInt32Value| number } request.maxResults - * The maximum number of results to return in a single response page. - * Leverage the page tokens to iterate through the entire collection. - * @param {string} request.pageToken - * Page token, returned by a previous call to request the next page of - * results - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.cloud.bigquery.v2.Model|Model}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `listModelsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Lists all models in the specified dataset. Requires the READER dataset + * role. After retrieving the list of models, you can get information about a + * particular model by calling the models.get method. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.projectId + * Required. Project ID of the models to list. + * @param {string} request.datasetId + * Required. Dataset ID of the models to list. + * @param {google.protobuf.UInt32Value| number } request.maxResults + * The maximum number of results to return in a single response page. + * Leverage the page tokens to iterate through the entire collection. + * @param {string} request.pageToken + * Page token, returned by a previous call to request the next page of + * results + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.cloud.bigquery.v2.Model|Model}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listModelsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listModels( - request?: protos.google.cloud.bigquery.v2.IListModelsRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.bigquery.v2.IModel[], - protos.google.cloud.bigquery.v2.IListModelsRequest|null, - protos.google.cloud.bigquery.v2.IListModelsResponse - ]>; + request?: protos.google.cloud.bigquery.v2.IListModelsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.bigquery.v2.IModel[], + protos.google.cloud.bigquery.v2.IListModelsRequest | null, + protos.google.cloud.bigquery.v2.IListModelsResponse, + ] + >; listModels( - request: protos.google.cloud.bigquery.v2.IListModelsRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.cloud.bigquery.v2.IListModelsRequest, - protos.google.cloud.bigquery.v2.IListModelsResponse|null|undefined, - protos.google.cloud.bigquery.v2.IModel>): void; + request: protos.google.cloud.bigquery.v2.IListModelsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.cloud.bigquery.v2.IListModelsRequest, + protos.google.cloud.bigquery.v2.IListModelsResponse | null | undefined, + protos.google.cloud.bigquery.v2.IModel + >, + ): void; listModels( - request: protos.google.cloud.bigquery.v2.IListModelsRequest, - callback: PaginationCallback< - protos.google.cloud.bigquery.v2.IListModelsRequest, - protos.google.cloud.bigquery.v2.IListModelsResponse|null|undefined, - protos.google.cloud.bigquery.v2.IModel>): void; + request: protos.google.cloud.bigquery.v2.IListModelsRequest, + callback: PaginationCallback< + protos.google.cloud.bigquery.v2.IListModelsRequest, + protos.google.cloud.bigquery.v2.IListModelsResponse | null | undefined, + protos.google.cloud.bigquery.v2.IModel + >, + ): void; listModels( - request?: protos.google.cloud.bigquery.v2.IListModelsRequest, - optionsOrCallback?: CallOptions|PaginationCallback< - protos.google.cloud.bigquery.v2.IListModelsRequest, - protos.google.cloud.bigquery.v2.IListModelsResponse|null|undefined, - protos.google.cloud.bigquery.v2.IModel>, - callback?: PaginationCallback< + request?: protos.google.cloud.bigquery.v2.IListModelsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.cloud.bigquery.v2.IListModelsRequest, - protos.google.cloud.bigquery.v2.IListModelsResponse|null|undefined, - protos.google.cloud.bigquery.v2.IModel>): - Promise<[ - protos.google.cloud.bigquery.v2.IModel[], - protos.google.cloud.bigquery.v2.IListModelsRequest|null, - protos.google.cloud.bigquery.v2.IListModelsResponse - ]>|void { + | protos.google.cloud.bigquery.v2.IListModelsResponse + | null + | undefined, + protos.google.cloud.bigquery.v2.IModel + >, + callback?: PaginationCallback< + protos.google.cloud.bigquery.v2.IListModelsRequest, + protos.google.cloud.bigquery.v2.IListModelsResponse | null | undefined, + protos.google.cloud.bigquery.v2.IModel + >, + ): Promise< + [ + protos.google.cloud.bigquery.v2.IModel[], + protos.google.cloud.bigquery.v2.IListModelsRequest | null, + protos.google.cloud.bigquery.v2.IListModelsResponse, + ] + > | void { request = request || {}; - // Converts number to Unit32 or Int32 value for non-compliant APIs. - if(request.maxResults && typeof request.maxResults === "number"){ - const maxResultsObject = {"value": request.maxResults} - request.maxResults = maxResultsObject - } + // Converts number to Unit32 or Int32 value for non-compliant APIs. + if (request.maxResults && typeof request.maxResults === 'number') { + const maxResultsObject = { value: request.maxResults }; + request.maxResults = maxResultsObject; + } let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'project_id': request.projectId?.toString() ?? '', - 'dataset_id': request.datasetId?.toString() ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + project_id: request.projectId?.toString() ?? '', + dataset_id: request.datasetId?.toString() ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.cloud.bigquery.v2.IListModelsRequest, - protos.google.cloud.bigquery.v2.IListModelsResponse|null|undefined, - protos.google.cloud.bigquery.v2.IModel>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.cloud.bigquery.v2.IListModelsRequest, + | protos.google.cloud.bigquery.v2.IListModelsResponse + | null + | undefined, + protos.google.cloud.bigquery.v2.IModel + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listModels values %j', values); callback!(error, values, nextPageRequest, rawResponse); @@ -751,116 +921,120 @@ export class ModelServiceClient { this._log.info('listModels request %j', request); return this.innerApiCalls .listModels(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.cloud.bigquery.v2.IModel[], - protos.google.cloud.bigquery.v2.IListModelsRequest|null, - protos.google.cloud.bigquery.v2.IListModelsResponse - ]) => { - this._log.info('listModels values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.cloud.bigquery.v2.IModel[], + protos.google.cloud.bigquery.v2.IListModelsRequest | null, + protos.google.cloud.bigquery.v2.IListModelsResponse, + ]) => { + this._log.info('listModels values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listModels`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.projectId - * Required. Project ID of the models to list. - * @param {string} request.datasetId - * Required. Dataset ID of the models to list. - * @param {google.protobuf.UInt32Value} request.maxResults - * The maximum number of results to return in a single response page. - * Leverage the page tokens to iterate through the entire collection. - * @param {string} request.pageToken - * Page token, returned by a previous call to request the next page of - * results - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.cloud.bigquery.v2.Model|Model} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `listModelsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `listModels`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.projectId + * Required. Project ID of the models to list. + * @param {string} request.datasetId + * Required. Dataset ID of the models to list. + * @param {google.protobuf.UInt32Value} request.maxResults + * The maximum number of results to return in a single response page. + * Leverage the page tokens to iterate through the entire collection. + * @param {string} request.pageToken + * Page token, returned by a previous call to request the next page of + * results + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.cloud.bigquery.v2.Model|Model} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listModelsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listModelsStream( - request?: protos.google.cloud.bigquery.v2.IListModelsRequest, - options?: CallOptions): - Transform{ + request?: protos.google.cloud.bigquery.v2.IListModelsRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'project_id': request.projectId?.toString() ?? '', - 'dataset_id': request.datasetId?.toString() ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + project_id: request.projectId?.toString() ?? '', + dataset_id: request.datasetId?.toString() ?? '', + }); const defaultCallSettings = this._defaults['listModels']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listModels stream %j', request); return this.descriptors.page.listModels.createStream( this.innerApiCalls.listModels as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listModels`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.projectId - * Required. Project ID of the models to list. - * @param {string} request.datasetId - * Required. Dataset ID of the models to list. - * @param {google.protobuf.UInt32Value} request.maxResults - * The maximum number of results to return in a single response page. - * Leverage the page tokens to iterate through the entire collection. - * @param {string} request.pageToken - * Page token, returned by a previous call to request the next page of - * results - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.cloud.bigquery.v2.Model|Model}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v2/model_service.list_models.js - * region_tag:bigquery_v2_generated_ModelService_ListModels_async - */ + /** + * Equivalent to `listModels`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.projectId + * Required. Project ID of the models to list. + * @param {string} request.datasetId + * Required. Dataset ID of the models to list. + * @param {google.protobuf.UInt32Value} request.maxResults + * The maximum number of results to return in a single response page. + * Leverage the page tokens to iterate through the entire collection. + * @param {string} request.pageToken + * Page token, returned by a previous call to request the next page of + * results + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.cloud.bigquery.v2.Model|Model}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v2/model_service.list_models.js + * region_tag:bigquery_v2_generated_ModelService_ListModels_async + */ listModelsAsync( - request?: protos.google.cloud.bigquery.v2.IListModelsRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.cloud.bigquery.v2.IListModelsRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'project_id': request.projectId?.toString() ?? '', - 'dataset_id': request.datasetId?.toString() ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + project_id: request.projectId?.toString() ?? '', + dataset_id: request.datasetId?.toString() ?? '', + }); const defaultCallSettings = this._defaults['listModels']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listModels iterate %j', request); return this.descriptors.page.listModels.asyncIterate( this.innerApiCalls['listModels'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } @@ -872,7 +1046,7 @@ export class ModelServiceClient { */ close(): Promise { if (this.modelServiceStub && !this._terminated) { - return this.modelServiceStub.then(stub => { + return this.modelServiceStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -880,4 +1054,4 @@ export class ModelServiceClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/core/generator/gapic-generator-typescript/baselines/bigquery-v2-esm/esm/src/v2/project_service_client.ts.baseline b/core/generator/gapic-generator-typescript/baselines/bigquery-v2-esm/esm/src/v2/project_service_client.ts.baseline index c02db6c4f4d5..2265e700f366 100644 --- a/core/generator/gapic-generator-typescript/baselines/bigquery-v2-esm/esm/src/v2/project_service_client.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/bigquery-v2-esm/esm/src/v2/project_service_client.ts.baseline @@ -18,15 +18,20 @@ /* global window */ import * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions} from 'google-gax'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, +} from 'google-gax'; // @ts-ignore import type * as protos from '../../../protos/protos.js'; import * as project_service_client_config from './project_service_client_config.json'; import fs from 'fs'; import path from 'path'; -import {fileURLToPath} from 'url'; -import {getJSON} from '../json-helper.cjs'; +import { fileURLToPath } from 'url'; +import { getJSON } from '../json-helper.cjs'; // @ts-ignore const dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -36,15 +41,15 @@ const dirname = path.dirname(fileURLToPath(import.meta.url)); * This file defines retry strategy and timeouts for all API methods in this library. */ const gapicConfig = getJSON( - path.join(dirname, 'project_service_client_config.json') + path.join(dirname, 'project_service_client_config.json'), ); const jsonProtos = getJSON( - path.join(dirname, '..', '..', '..', 'protos/protos.json') + path.join(dirname, '..', '..', '..', 'protos/protos.json'), ); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; const version = getJSON( - path.join(dirname, '..', '..', '..', '..', 'package.json') + path.join(dirname, '..', '..', '..', '..', 'package.json'), ).version; /** @@ -62,7 +67,7 @@ export class ProjectServiceClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('bigquery'); @@ -74,8 +79,8 @@ export class ProjectServiceClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - projectServiceStub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + projectServiceStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of ProjectServiceClient. @@ -117,21 +122,42 @@ export class ProjectServiceClient { * const client = new ProjectServiceClient({fallback: 'rest'}, gax); * ``` */ - constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { // Ensure that options include all the required fields. const staticMembers = this.constructor as typeof ProjectServiceClient; - if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { - throw new Error('Please set either universe_domain or universeDomain, but not both.'); + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); } - const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; - this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; this._servicePath = 'bigquery.' + this._universeDomain; - const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; - const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. if (servicePath !== this._servicePath && !('scopes' in opts)) { @@ -153,7 +179,7 @@ export class ProjectServiceClient { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; @@ -170,10 +196,7 @@ export class ProjectServiceClient { const isEsm = true; const isEsmString = isEsm ? '-esm' : '-cjs'; // Determine the client header string. - const clientHeader = [ - `gax/${this._gaxModule.version}`, - `gapic/${version}`, - ]; + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/{process.versions.node}${isEsmString}`); } else { @@ -181,7 +204,7 @@ export class ProjectServiceClient { } if (!opts.fallback) { clientHeader.push(`grpc/${this._gaxGrpc.grpcVersion}`); - } else if (opts.fallback === 'rest' ) { + } else if (opts.fallback === 'rest') { clientHeader.push(`rest/${this._gaxGrpc.grpcVersion}`); } if (opts.libName && opts.libVersion) { @@ -189,12 +212,17 @@ export class ProjectServiceClient { } // Load the applicable protos. - this._protos = this._gaxGrpc.loadProtoJSON(jsonProtos as gax.protobuf.INamespace); + this._protos = this._gaxGrpc.loadProtoJSON( + jsonProtos as gax.protobuf.INamespace, + ); // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.cloud.bigquery.v2.ProjectService', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.cloud.bigquery.v2.ProjectService', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + { 'x-goog-api-client': clientHeader.join(' ') }, + ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -225,36 +253,40 @@ export class ProjectServiceClient { // Put together the "service stub" for // google.cloud.bigquery.v2.ProjectService. this.projectServiceStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.cloud.bigquery.v2.ProjectService') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.cloud.bigquery.v2.ProjectService', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.cloud.bigquery.v2.ProjectService, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts, + this._providedCustomServicePath, + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const projectServiceStubMethods = - ['getServiceAccount']; + const projectServiceStubMethods = ['getServiceAccount']; for (const methodName of projectServiceStubMethods) { const callPromise = this.projectServiceStub.then( - stub => (...args: Array<{}>) => { - if (this._terminated) { - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error|null|undefined) => () => { + (stub) => + (...args: Array<{}>) => { + if (this._terminated) { + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { throw err; - }); + }, + ); - const descriptor = - undefined; + const descriptor = undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -269,8 +301,14 @@ export class ProjectServiceClient { * @returns {string} The DNS address for this service. */ static get servicePath() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'bigquery.googleapis.com'; } @@ -282,8 +320,14 @@ export class ProjectServiceClient { * @returns {string} The DNS address for this service. */ static get apiEndpoint() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'bigquery.googleapis.com'; } @@ -317,7 +361,7 @@ export class ProjectServiceClient { return [ 'https://www.googleapis.com/auth/bigquery', 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloud-platform.read-only' + 'https://www.googleapis.com/auth/cloud-platform.read-only', ]; } @@ -327,8 +371,9 @@ export class ProjectServiceClient { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId(callback?: Callback): - Promise|void { + getProjectId( + callback?: Callback, + ): Promise | void { if (callback) { this.auth.getProjectId(callback); return; @@ -339,102 +384,142 @@ export class ProjectServiceClient { // ------------------- // -- Service calls -- // ------------------- -/** - * RPC to get the service account for a project used for interactions with - * Google Cloud KMS - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.projectId - * Required. ID of the project. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.bigquery.v2.GetServiceAccountResponse|GetServiceAccountResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/project_service.get_service_account.js - * region_tag:bigquery_v2_generated_ProjectService_GetServiceAccount_async - */ + /** + * RPC to get the service account for a project used for interactions with + * Google Cloud KMS + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.projectId + * Required. ID of the project. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.bigquery.v2.GetServiceAccountResponse|GetServiceAccountResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/project_service.get_service_account.js + * region_tag:bigquery_v2_generated_ProjectService_GetServiceAccount_async + */ getServiceAccount( - request?: protos.google.cloud.bigquery.v2.IGetServiceAccountRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.bigquery.v2.IGetServiceAccountResponse, - protos.google.cloud.bigquery.v2.IGetServiceAccountRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.bigquery.v2.IGetServiceAccountRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.bigquery.v2.IGetServiceAccountResponse, + protos.google.cloud.bigquery.v2.IGetServiceAccountRequest | undefined, + {} | undefined, + ] + >; getServiceAccount( - request: protos.google.cloud.bigquery.v2.IGetServiceAccountRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.bigquery.v2.IGetServiceAccountResponse, - protos.google.cloud.bigquery.v2.IGetServiceAccountRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.bigquery.v2.IGetServiceAccountRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.bigquery.v2.IGetServiceAccountResponse, + | protos.google.cloud.bigquery.v2.IGetServiceAccountRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getServiceAccount( - request: protos.google.cloud.bigquery.v2.IGetServiceAccountRequest, - callback: Callback< - protos.google.cloud.bigquery.v2.IGetServiceAccountResponse, - protos.google.cloud.bigquery.v2.IGetServiceAccountRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.bigquery.v2.IGetServiceAccountRequest, + callback: Callback< + protos.google.cloud.bigquery.v2.IGetServiceAccountResponse, + | protos.google.cloud.bigquery.v2.IGetServiceAccountRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getServiceAccount( - request?: protos.google.cloud.bigquery.v2.IGetServiceAccountRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.cloud.bigquery.v2.IGetServiceAccountRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.bigquery.v2.IGetServiceAccountResponse, - protos.google.cloud.bigquery.v2.IGetServiceAccountRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.cloud.bigquery.v2.IGetServiceAccountResponse, - protos.google.cloud.bigquery.v2.IGetServiceAccountRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.bigquery.v2.IGetServiceAccountResponse, - protos.google.cloud.bigquery.v2.IGetServiceAccountRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.bigquery.v2.IGetServiceAccountRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.bigquery.v2.IGetServiceAccountResponse, + | protos.google.cloud.bigquery.v2.IGetServiceAccountRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.bigquery.v2.IGetServiceAccountResponse, + protos.google.cloud.bigquery.v2.IGetServiceAccountRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'project_id': request.projectId?.toString() ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + project_id: request.projectId?.toString() ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getServiceAccount request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.bigquery.v2.IGetServiceAccountResponse, - protos.google.cloud.bigquery.v2.IGetServiceAccountRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.bigquery.v2.IGetServiceAccountResponse, + | protos.google.cloud.bigquery.v2.IGetServiceAccountRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getServiceAccount response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.getServiceAccount(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.bigquery.v2.IGetServiceAccountResponse, - protos.google.cloud.bigquery.v2.IGetServiceAccountRequest|undefined, {}|undefined - ]) => { - this._log.info('getServiceAccount response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getServiceAccount(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.bigquery.v2.IGetServiceAccountResponse, + protos.google.cloud.bigquery.v2.IGetServiceAccountRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getServiceAccount response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } - /** * Terminate the gRPC channel and close the client. * @@ -443,7 +528,7 @@ export class ProjectServiceClient { */ close(): Promise { if (this.projectServiceStub && !this._terminated) { - return this.projectServiceStub.then(stub => { + return this.projectServiceStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -451,4 +536,4 @@ export class ProjectServiceClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/core/generator/gapic-generator-typescript/baselines/bigquery-v2-esm/esm/src/v2/routine_service_client.ts.baseline b/core/generator/gapic-generator-typescript/baselines/bigquery-v2-esm/esm/src/v2/routine_service_client.ts.baseline index fce182d04f3c..8f3331063213 100644 --- a/core/generator/gapic-generator-typescript/baselines/bigquery-v2-esm/esm/src/v2/routine_service_client.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/bigquery-v2-esm/esm/src/v2/routine_service_client.ts.baseline @@ -18,15 +18,22 @@ /* global window */ import * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions, PaginationCallback, GaxCall} from 'google-gax'; -import {Transform} from 'stream'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + PaginationCallback, + GaxCall, +} from 'google-gax'; +import { Transform } from 'stream'; // @ts-ignore import type * as protos from '../../../protos/protos.js'; import * as routine_service_client_config from './routine_service_client_config.json'; import fs from 'fs'; import path from 'path'; -import {fileURLToPath} from 'url'; -import {getJSON} from '../json-helper.cjs'; +import { fileURLToPath } from 'url'; +import { getJSON } from '../json-helper.cjs'; // @ts-ignore const dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -36,15 +43,15 @@ const dirname = path.dirname(fileURLToPath(import.meta.url)); * This file defines retry strategy and timeouts for all API methods in this library. */ const gapicConfig = getJSON( - path.join(dirname, 'routine_service_client_config.json') + path.join(dirname, 'routine_service_client_config.json'), ); const jsonProtos = getJSON( - path.join(dirname, '..', '..', '..', 'protos/protos.json') + path.join(dirname, '..', '..', '..', 'protos/protos.json'), ); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; const version = getJSON( - path.join(dirname, '..', '..', '..', '..', 'package.json') + path.join(dirname, '..', '..', '..', '..', 'package.json'), ).version; /** @@ -62,7 +69,7 @@ export class RoutineServiceClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('bigquery'); @@ -74,8 +81,8 @@ export class RoutineServiceClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - routineServiceStub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + routineServiceStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of RoutineServiceClient. @@ -117,21 +124,42 @@ export class RoutineServiceClient { * const client = new RoutineServiceClient({fallback: 'rest'}, gax); * ``` */ - constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { // Ensure that options include all the required fields. const staticMembers = this.constructor as typeof RoutineServiceClient; - if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { - throw new Error('Please set either universe_domain or universeDomain, but not both.'); + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); } - const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; - this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; this._servicePath = 'bigquery.' + this._universeDomain; - const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; - const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. if (servicePath !== this._servicePath && !('scopes' in opts)) { @@ -153,7 +181,7 @@ export class RoutineServiceClient { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; @@ -170,10 +198,7 @@ export class RoutineServiceClient { const isEsm = true; const isEsmString = isEsm ? '-esm' : '-cjs'; // Determine the client header string. - const clientHeader = [ - `gax/${this._gaxModule.version}`, - `gapic/${version}`, - ]; + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/{process.versions.node}${isEsmString}`); } else { @@ -181,7 +206,7 @@ export class RoutineServiceClient { } if (!opts.fallback) { clientHeader.push(`grpc/${this._gaxGrpc.grpcVersion}`); - } else if (opts.fallback === 'rest' ) { + } else if (opts.fallback === 'rest') { clientHeader.push(`rest/${this._gaxGrpc.grpcVersion}`); } if (opts.libName && opts.libVersion) { @@ -189,20 +214,28 @@ export class RoutineServiceClient { } // Load the applicable protos. - this._protos = this._gaxGrpc.loadProtoJSON(jsonProtos as gax.protobuf.INamespace); + this._protos = this._gaxGrpc.loadProtoJSON( + jsonProtos as gax.protobuf.INamespace, + ); // Some of the methods on this service return "paged" results, // (e.g. 50 results at a time, with tokens to get subsequent // pages). Denote the keys used for pagination and results. this.descriptors.page = { - listRoutines: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'routines') + listRoutines: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'routines', + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.cloud.bigquery.v2.RoutineService', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.cloud.bigquery.v2.RoutineService', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + { 'x-goog-api-client': clientHeader.join(' ') }, + ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -233,37 +266,47 @@ export class RoutineServiceClient { // Put together the "service stub" for // google.cloud.bigquery.v2.RoutineService. this.routineServiceStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.cloud.bigquery.v2.RoutineService') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.cloud.bigquery.v2.RoutineService', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.cloud.bigquery.v2.RoutineService, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts, + this._providedCustomServicePath, + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const routineServiceStubMethods = - ['getRoutine', 'insertRoutine', 'updateRoutine', 'patchRoutine', 'deleteRoutine', 'listRoutines']; + const routineServiceStubMethods = [ + 'getRoutine', + 'insertRoutine', + 'updateRoutine', + 'patchRoutine', + 'deleteRoutine', + 'listRoutines', + ]; for (const methodName of routineServiceStubMethods) { const callPromise = this.routineServiceStub.then( - stub => (...args: Array<{}>) => { - if (this._terminated) { - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error|null|undefined) => () => { + (stub) => + (...args: Array<{}>) => { + if (this._terminated) { + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { throw err; - }); + }, + ); - const descriptor = - this.descriptors.page[methodName] || - undefined; + const descriptor = this.descriptors.page[methodName] || undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -278,8 +321,14 @@ export class RoutineServiceClient { * @returns {string} The DNS address for this service. */ static get servicePath() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'bigquery.googleapis.com'; } @@ -291,8 +340,14 @@ export class RoutineServiceClient { * @returns {string} The DNS address for this service. */ static get apiEndpoint() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'bigquery.googleapis.com'; } @@ -326,7 +381,7 @@ export class RoutineServiceClient { return [ 'https://www.googleapis.com/auth/bigquery', 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloud-platform.read-only' + 'https://www.googleapis.com/auth/cloud-platform.read-only', ]; } @@ -336,8 +391,9 @@ export class RoutineServiceClient { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId(callback?: Callback): - Promise|void { + getProjectId( + callback?: Callback, + ): Promise | void { if (callback) { this.auth.getProjectId(callback); return; @@ -348,601 +404,792 @@ export class RoutineServiceClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Gets the specified routine resource by routine ID. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.projectId - * Required. Project ID of the requested routine - * @param {string} request.datasetId - * Required. Dataset ID of the requested routine - * @param {string} request.routineId - * Required. Routine ID of the requested routine - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.bigquery.v2.Routine|Routine}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/routine_service.get_routine.js - * region_tag:bigquery_v2_generated_RoutineService_GetRoutine_async - */ + /** + * Gets the specified routine resource by routine ID. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.projectId + * Required. Project ID of the requested routine + * @param {string} request.datasetId + * Required. Dataset ID of the requested routine + * @param {string} request.routineId + * Required. Routine ID of the requested routine + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.bigquery.v2.Routine|Routine}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/routine_service.get_routine.js + * region_tag:bigquery_v2_generated_RoutineService_GetRoutine_async + */ getRoutine( - request?: protos.google.cloud.bigquery.v2.IGetRoutineRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.bigquery.v2.IRoutine, - protos.google.cloud.bigquery.v2.IGetRoutineRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.bigquery.v2.IGetRoutineRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.bigquery.v2.IRoutine, + protos.google.cloud.bigquery.v2.IGetRoutineRequest | undefined, + {} | undefined, + ] + >; getRoutine( - request: protos.google.cloud.bigquery.v2.IGetRoutineRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.bigquery.v2.IRoutine, - protos.google.cloud.bigquery.v2.IGetRoutineRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.bigquery.v2.IGetRoutineRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.bigquery.v2.IRoutine, + protos.google.cloud.bigquery.v2.IGetRoutineRequest | null | undefined, + {} | null | undefined + >, + ): void; getRoutine( - request: protos.google.cloud.bigquery.v2.IGetRoutineRequest, - callback: Callback< - protos.google.cloud.bigquery.v2.IRoutine, - protos.google.cloud.bigquery.v2.IGetRoutineRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.bigquery.v2.IGetRoutineRequest, + callback: Callback< + protos.google.cloud.bigquery.v2.IRoutine, + protos.google.cloud.bigquery.v2.IGetRoutineRequest | null | undefined, + {} | null | undefined + >, + ): void; getRoutine( - request?: protos.google.cloud.bigquery.v2.IGetRoutineRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.bigquery.v2.IRoutine, - protos.google.cloud.bigquery.v2.IGetRoutineRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.bigquery.v2.IGetRoutineRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.bigquery.v2.IRoutine, - protos.google.cloud.bigquery.v2.IGetRoutineRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.bigquery.v2.IRoutine, - protos.google.cloud.bigquery.v2.IGetRoutineRequest|undefined, {}|undefined - ]>|void { + protos.google.cloud.bigquery.v2.IGetRoutineRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.bigquery.v2.IRoutine, + protos.google.cloud.bigquery.v2.IGetRoutineRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.bigquery.v2.IRoutine, + protos.google.cloud.bigquery.v2.IGetRoutineRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'project_id': request.projectId?.toString() ?? '', - 'dataset_id': request.datasetId?.toString() ?? '', - 'routine_id': request.routineId?.toString() ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + project_id: request.projectId?.toString() ?? '', + dataset_id: request.datasetId?.toString() ?? '', + routine_id: request.routineId?.toString() ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getRoutine request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.bigquery.v2.IRoutine, - protos.google.cloud.bigquery.v2.IGetRoutineRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.bigquery.v2.IRoutine, + protos.google.cloud.bigquery.v2.IGetRoutineRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getRoutine response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.getRoutine(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.bigquery.v2.IRoutine, - protos.google.cloud.bigquery.v2.IGetRoutineRequest|undefined, {}|undefined - ]) => { - this._log.info('getRoutine response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getRoutine(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.bigquery.v2.IRoutine, + protos.google.cloud.bigquery.v2.IGetRoutineRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getRoutine response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Creates a new routine in the dataset. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.projectId - * Required. Project ID of the new routine - * @param {string} request.datasetId - * Required. Dataset ID of the new routine - * @param {google.cloud.bigquery.v2.Routine} request.routine - * Required. A routine resource to insert - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.bigquery.v2.Routine|Routine}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/routine_service.insert_routine.js - * region_tag:bigquery_v2_generated_RoutineService_InsertRoutine_async - */ + /** + * Creates a new routine in the dataset. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.projectId + * Required. Project ID of the new routine + * @param {string} request.datasetId + * Required. Dataset ID of the new routine + * @param {google.cloud.bigquery.v2.Routine} request.routine + * Required. A routine resource to insert + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.bigquery.v2.Routine|Routine}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/routine_service.insert_routine.js + * region_tag:bigquery_v2_generated_RoutineService_InsertRoutine_async + */ insertRoutine( - request?: protos.google.cloud.bigquery.v2.IInsertRoutineRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.bigquery.v2.IRoutine, - protos.google.cloud.bigquery.v2.IInsertRoutineRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.bigquery.v2.IInsertRoutineRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.bigquery.v2.IRoutine, + protos.google.cloud.bigquery.v2.IInsertRoutineRequest | undefined, + {} | undefined, + ] + >; insertRoutine( - request: protos.google.cloud.bigquery.v2.IInsertRoutineRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.bigquery.v2.IRoutine, - protos.google.cloud.bigquery.v2.IInsertRoutineRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.bigquery.v2.IInsertRoutineRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.bigquery.v2.IRoutine, + protos.google.cloud.bigquery.v2.IInsertRoutineRequest | null | undefined, + {} | null | undefined + >, + ): void; insertRoutine( - request: protos.google.cloud.bigquery.v2.IInsertRoutineRequest, - callback: Callback< - protos.google.cloud.bigquery.v2.IRoutine, - protos.google.cloud.bigquery.v2.IInsertRoutineRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.bigquery.v2.IInsertRoutineRequest, + callback: Callback< + protos.google.cloud.bigquery.v2.IRoutine, + protos.google.cloud.bigquery.v2.IInsertRoutineRequest | null | undefined, + {} | null | undefined + >, + ): void; insertRoutine( - request?: protos.google.cloud.bigquery.v2.IInsertRoutineRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.bigquery.v2.IRoutine, - protos.google.cloud.bigquery.v2.IInsertRoutineRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.bigquery.v2.IInsertRoutineRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.bigquery.v2.IRoutine, - protos.google.cloud.bigquery.v2.IInsertRoutineRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.bigquery.v2.IRoutine, - protos.google.cloud.bigquery.v2.IInsertRoutineRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.bigquery.v2.IInsertRoutineRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.bigquery.v2.IRoutine, + protos.google.cloud.bigquery.v2.IInsertRoutineRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.bigquery.v2.IRoutine, + protos.google.cloud.bigquery.v2.IInsertRoutineRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'project_id': request.projectId?.toString() ?? '', - 'dataset_id': request.datasetId?.toString() ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + project_id: request.projectId?.toString() ?? '', + dataset_id: request.datasetId?.toString() ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('insertRoutine request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.bigquery.v2.IRoutine, - protos.google.cloud.bigquery.v2.IInsertRoutineRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.bigquery.v2.IRoutine, + | protos.google.cloud.bigquery.v2.IInsertRoutineRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('insertRoutine response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.insertRoutine(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.bigquery.v2.IRoutine, - protos.google.cloud.bigquery.v2.IInsertRoutineRequest|undefined, {}|undefined - ]) => { - this._log.info('insertRoutine response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .insertRoutine(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.bigquery.v2.IRoutine, + protos.google.cloud.bigquery.v2.IInsertRoutineRequest | undefined, + {} | undefined, + ]) => { + this._log.info('insertRoutine response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Updates information in an existing routine. The update method replaces the - * entire Routine resource. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.projectId - * Required. Project ID of the routine to update - * @param {string} request.datasetId - * Required. Dataset ID of the routine to update - * @param {string} request.routineId - * Required. Routine ID of the routine to update - * @param {google.cloud.bigquery.v2.Routine} request.routine - * Required. A routine resource which will replace the specified routine - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.bigquery.v2.Routine|Routine}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/routine_service.update_routine.js - * region_tag:bigquery_v2_generated_RoutineService_UpdateRoutine_async - */ + /** + * Updates information in an existing routine. The update method replaces the + * entire Routine resource. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.projectId + * Required. Project ID of the routine to update + * @param {string} request.datasetId + * Required. Dataset ID of the routine to update + * @param {string} request.routineId + * Required. Routine ID of the routine to update + * @param {google.cloud.bigquery.v2.Routine} request.routine + * Required. A routine resource which will replace the specified routine + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.bigquery.v2.Routine|Routine}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/routine_service.update_routine.js + * region_tag:bigquery_v2_generated_RoutineService_UpdateRoutine_async + */ updateRoutine( - request?: protos.google.cloud.bigquery.v2.IUpdateRoutineRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.bigquery.v2.IRoutine, - protos.google.cloud.bigquery.v2.IUpdateRoutineRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.bigquery.v2.IUpdateRoutineRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.bigquery.v2.IRoutine, + protos.google.cloud.bigquery.v2.IUpdateRoutineRequest | undefined, + {} | undefined, + ] + >; updateRoutine( - request: protos.google.cloud.bigquery.v2.IUpdateRoutineRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.bigquery.v2.IRoutine, - protos.google.cloud.bigquery.v2.IUpdateRoutineRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.bigquery.v2.IUpdateRoutineRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.bigquery.v2.IRoutine, + protos.google.cloud.bigquery.v2.IUpdateRoutineRequest | null | undefined, + {} | null | undefined + >, + ): void; updateRoutine( - request: protos.google.cloud.bigquery.v2.IUpdateRoutineRequest, - callback: Callback< - protos.google.cloud.bigquery.v2.IRoutine, - protos.google.cloud.bigquery.v2.IUpdateRoutineRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.bigquery.v2.IUpdateRoutineRequest, + callback: Callback< + protos.google.cloud.bigquery.v2.IRoutine, + protos.google.cloud.bigquery.v2.IUpdateRoutineRequest | null | undefined, + {} | null | undefined + >, + ): void; updateRoutine( - request?: protos.google.cloud.bigquery.v2.IUpdateRoutineRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.cloud.bigquery.v2.IUpdateRoutineRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.bigquery.v2.IRoutine, - protos.google.cloud.bigquery.v2.IUpdateRoutineRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.cloud.bigquery.v2.IRoutine, - protos.google.cloud.bigquery.v2.IUpdateRoutineRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.bigquery.v2.IRoutine, - protos.google.cloud.bigquery.v2.IUpdateRoutineRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.bigquery.v2.IUpdateRoutineRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.bigquery.v2.IRoutine, + protos.google.cloud.bigquery.v2.IUpdateRoutineRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.bigquery.v2.IRoutine, + protos.google.cloud.bigquery.v2.IUpdateRoutineRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'project_id': request.projectId?.toString() ?? '', - 'dataset_id': request.datasetId?.toString() ?? '', - 'routine_id': request.routineId?.toString() ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + project_id: request.projectId?.toString() ?? '', + dataset_id: request.datasetId?.toString() ?? '', + routine_id: request.routineId?.toString() ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateRoutine request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.bigquery.v2.IRoutine, - protos.google.cloud.bigquery.v2.IUpdateRoutineRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.bigquery.v2.IRoutine, + | protos.google.cloud.bigquery.v2.IUpdateRoutineRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateRoutine response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.updateRoutine(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.bigquery.v2.IRoutine, - protos.google.cloud.bigquery.v2.IUpdateRoutineRequest|undefined, {}|undefined - ]) => { - this._log.info('updateRoutine response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateRoutine(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.bigquery.v2.IRoutine, + protos.google.cloud.bigquery.v2.IUpdateRoutineRequest | undefined, + {} | undefined, + ]) => { + this._log.info('updateRoutine response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Patches information in an existing routine. The patch method does a partial - * update to an existing Routine resource. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.projectId - * Required. Project ID of the routine to update - * @param {string} request.datasetId - * Required. Dataset ID of the routine to update - * @param {string} request.routineId - * Required. Routine ID of the routine to update - * @param {google.cloud.bigquery.v2.Routine} request.routine - * Required. A routine resource which will be used to partially - * update the specified routine - * @param {google.protobuf.FieldMask} request.fieldMask - * Only the Routine fields in the field mask are updated - * by the given routine. Repeated routine fields will be fully replaced - * if contained in the field mask. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.bigquery.v2.Routine|Routine}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/routine_service.patch_routine.js - * region_tag:bigquery_v2_generated_RoutineService_PatchRoutine_async - */ + /** + * Patches information in an existing routine. The patch method does a partial + * update to an existing Routine resource. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.projectId + * Required. Project ID of the routine to update + * @param {string} request.datasetId + * Required. Dataset ID of the routine to update + * @param {string} request.routineId + * Required. Routine ID of the routine to update + * @param {google.cloud.bigquery.v2.Routine} request.routine + * Required. A routine resource which will be used to partially + * update the specified routine + * @param {google.protobuf.FieldMask} request.fieldMask + * Only the Routine fields in the field mask are updated + * by the given routine. Repeated routine fields will be fully replaced + * if contained in the field mask. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.bigquery.v2.Routine|Routine}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/routine_service.patch_routine.js + * region_tag:bigquery_v2_generated_RoutineService_PatchRoutine_async + */ patchRoutine( - request?: protos.google.cloud.bigquery.v2.IPatchRoutineRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.bigquery.v2.IRoutine, - protos.google.cloud.bigquery.v2.IPatchRoutineRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.bigquery.v2.IPatchRoutineRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.bigquery.v2.IRoutine, + protos.google.cloud.bigquery.v2.IPatchRoutineRequest | undefined, + {} | undefined, + ] + >; patchRoutine( - request: protos.google.cloud.bigquery.v2.IPatchRoutineRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.bigquery.v2.IRoutine, - protos.google.cloud.bigquery.v2.IPatchRoutineRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.bigquery.v2.IPatchRoutineRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.bigquery.v2.IRoutine, + protos.google.cloud.bigquery.v2.IPatchRoutineRequest | null | undefined, + {} | null | undefined + >, + ): void; patchRoutine( - request: protos.google.cloud.bigquery.v2.IPatchRoutineRequest, - callback: Callback< - protos.google.cloud.bigquery.v2.IRoutine, - protos.google.cloud.bigquery.v2.IPatchRoutineRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.bigquery.v2.IPatchRoutineRequest, + callback: Callback< + protos.google.cloud.bigquery.v2.IRoutine, + protos.google.cloud.bigquery.v2.IPatchRoutineRequest | null | undefined, + {} | null | undefined + >, + ): void; patchRoutine( - request?: protos.google.cloud.bigquery.v2.IPatchRoutineRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.cloud.bigquery.v2.IPatchRoutineRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.bigquery.v2.IRoutine, - protos.google.cloud.bigquery.v2.IPatchRoutineRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.cloud.bigquery.v2.IRoutine, - protos.google.cloud.bigquery.v2.IPatchRoutineRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.bigquery.v2.IRoutine, - protos.google.cloud.bigquery.v2.IPatchRoutineRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.bigquery.v2.IPatchRoutineRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.bigquery.v2.IRoutine, + protos.google.cloud.bigquery.v2.IPatchRoutineRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.bigquery.v2.IRoutine, + protos.google.cloud.bigquery.v2.IPatchRoutineRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('patchRoutine request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.bigquery.v2.IRoutine, - protos.google.cloud.bigquery.v2.IPatchRoutineRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.bigquery.v2.IRoutine, + | protos.google.cloud.bigquery.v2.IPatchRoutineRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('patchRoutine response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.patchRoutine(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.bigquery.v2.IRoutine, - protos.google.cloud.bigquery.v2.IPatchRoutineRequest|undefined, {}|undefined - ]) => { - this._log.info('patchRoutine response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .patchRoutine(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.bigquery.v2.IRoutine, + protos.google.cloud.bigquery.v2.IPatchRoutineRequest | undefined, + {} | undefined, + ]) => { + this._log.info('patchRoutine response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Deletes the routine specified by routineId from the dataset. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.projectId - * Required. Project ID of the routine to delete - * @param {string} request.datasetId - * Required. Dataset ID of the routine to delete - * @param {string} request.routineId - * Required. Routine ID of the routine to delete - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/routine_service.delete_routine.js - * region_tag:bigquery_v2_generated_RoutineService_DeleteRoutine_async - */ + /** + * Deletes the routine specified by routineId from the dataset. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.projectId + * Required. Project ID of the routine to delete + * @param {string} request.datasetId + * Required. Dataset ID of the routine to delete + * @param {string} request.routineId + * Required. Routine ID of the routine to delete + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/routine_service.delete_routine.js + * region_tag:bigquery_v2_generated_RoutineService_DeleteRoutine_async + */ deleteRoutine( - request?: protos.google.cloud.bigquery.v2.IDeleteRoutineRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.cloud.bigquery.v2.IDeleteRoutineRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.bigquery.v2.IDeleteRoutineRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.cloud.bigquery.v2.IDeleteRoutineRequest | undefined, + {} | undefined, + ] + >; deleteRoutine( - request: protos.google.cloud.bigquery.v2.IDeleteRoutineRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.cloud.bigquery.v2.IDeleteRoutineRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.bigquery.v2.IDeleteRoutineRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.cloud.bigquery.v2.IDeleteRoutineRequest | null | undefined, + {} | null | undefined + >, + ): void; deleteRoutine( - request: protos.google.cloud.bigquery.v2.IDeleteRoutineRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.cloud.bigquery.v2.IDeleteRoutineRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.bigquery.v2.IDeleteRoutineRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.cloud.bigquery.v2.IDeleteRoutineRequest | null | undefined, + {} | null | undefined + >, + ): void; deleteRoutine( - request?: protos.google.cloud.bigquery.v2.IDeleteRoutineRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.protobuf.IEmpty, - protos.google.cloud.bigquery.v2.IDeleteRoutineRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.bigquery.v2.IDeleteRoutineRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.cloud.bigquery.v2.IDeleteRoutineRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.cloud.bigquery.v2.IDeleteRoutineRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.bigquery.v2.IDeleteRoutineRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + protos.google.cloud.bigquery.v2.IDeleteRoutineRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.cloud.bigquery.v2.IDeleteRoutineRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'project_id': request.projectId?.toString() ?? '', - 'dataset_id': request.datasetId?.toString() ?? '', - 'routine_id': request.routineId?.toString() ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + project_id: request.projectId?.toString() ?? '', + dataset_id: request.datasetId?.toString() ?? '', + routine_id: request.routineId?.toString() ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('deleteRoutine request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.cloud.bigquery.v2.IDeleteRoutineRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.cloud.bigquery.v2.IDeleteRoutineRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteRoutine response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.deleteRoutine(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.cloud.bigquery.v2.IDeleteRoutineRequest|undefined, {}|undefined - ]) => { - this._log.info('deleteRoutine response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteRoutine(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.cloud.bigquery.v2.IDeleteRoutineRequest | undefined, + {} | undefined, + ]) => { + this._log.info('deleteRoutine response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } - /** - * Lists all routines in the specified dataset. Requires the READER dataset - * role. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.projectId - * Required. Project ID of the routines to list - * @param {string} request.datasetId - * Required. Dataset ID of the routines to list - * @param {google.protobuf.UInt32Value| number } request.maxResults - * The maximum number of results to return in a single response page. - * Leverage the page tokens to iterate through the entire collection. - * @param {string} request.pageToken - * Page token, returned by a previous call, to request the next page of - * results - * @param {string} request.filter - * If set, then only the Routines matching this filter are returned. - * The supported format is `routineType:{RoutineType}`, where `{RoutineType}` - * is a RoutineType enum. For example: `routineType:SCALAR_FUNCTION`. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.cloud.bigquery.v2.Routine|Routine}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `listRoutinesAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Lists all routines in the specified dataset. Requires the READER dataset + * role. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.projectId + * Required. Project ID of the routines to list + * @param {string} request.datasetId + * Required. Dataset ID of the routines to list + * @param {google.protobuf.UInt32Value| number } request.maxResults + * The maximum number of results to return in a single response page. + * Leverage the page tokens to iterate through the entire collection. + * @param {string} request.pageToken + * Page token, returned by a previous call, to request the next page of + * results + * @param {string} request.filter + * If set, then only the Routines matching this filter are returned. + * The supported format is `routineType:{RoutineType}`, where `{RoutineType}` + * is a RoutineType enum. For example: `routineType:SCALAR_FUNCTION`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.cloud.bigquery.v2.Routine|Routine}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listRoutinesAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listRoutines( - request?: protos.google.cloud.bigquery.v2.IListRoutinesRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.bigquery.v2.IRoutine[], - protos.google.cloud.bigquery.v2.IListRoutinesRequest|null, - protos.google.cloud.bigquery.v2.IListRoutinesResponse - ]>; + request?: protos.google.cloud.bigquery.v2.IListRoutinesRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.bigquery.v2.IRoutine[], + protos.google.cloud.bigquery.v2.IListRoutinesRequest | null, + protos.google.cloud.bigquery.v2.IListRoutinesResponse, + ] + >; listRoutines( - request: protos.google.cloud.bigquery.v2.IListRoutinesRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.cloud.bigquery.v2.IListRoutinesRequest, - protos.google.cloud.bigquery.v2.IListRoutinesResponse|null|undefined, - protos.google.cloud.bigquery.v2.IRoutine>): void; + request: protos.google.cloud.bigquery.v2.IListRoutinesRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.cloud.bigquery.v2.IListRoutinesRequest, + protos.google.cloud.bigquery.v2.IListRoutinesResponse | null | undefined, + protos.google.cloud.bigquery.v2.IRoutine + >, + ): void; listRoutines( - request: protos.google.cloud.bigquery.v2.IListRoutinesRequest, - callback: PaginationCallback< - protos.google.cloud.bigquery.v2.IListRoutinesRequest, - protos.google.cloud.bigquery.v2.IListRoutinesResponse|null|undefined, - protos.google.cloud.bigquery.v2.IRoutine>): void; + request: protos.google.cloud.bigquery.v2.IListRoutinesRequest, + callback: PaginationCallback< + protos.google.cloud.bigquery.v2.IListRoutinesRequest, + protos.google.cloud.bigquery.v2.IListRoutinesResponse | null | undefined, + protos.google.cloud.bigquery.v2.IRoutine + >, + ): void; listRoutines( - request?: protos.google.cloud.bigquery.v2.IListRoutinesRequest, - optionsOrCallback?: CallOptions|PaginationCallback< + request?: protos.google.cloud.bigquery.v2.IListRoutinesRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.cloud.bigquery.v2.IListRoutinesRequest, - protos.google.cloud.bigquery.v2.IListRoutinesResponse|null|undefined, - protos.google.cloud.bigquery.v2.IRoutine>, - callback?: PaginationCallback< - protos.google.cloud.bigquery.v2.IListRoutinesRequest, - protos.google.cloud.bigquery.v2.IListRoutinesResponse|null|undefined, - protos.google.cloud.bigquery.v2.IRoutine>): - Promise<[ - protos.google.cloud.bigquery.v2.IRoutine[], - protos.google.cloud.bigquery.v2.IListRoutinesRequest|null, - protos.google.cloud.bigquery.v2.IListRoutinesResponse - ]>|void { + | protos.google.cloud.bigquery.v2.IListRoutinesResponse + | null + | undefined, + protos.google.cloud.bigquery.v2.IRoutine + >, + callback?: PaginationCallback< + protos.google.cloud.bigquery.v2.IListRoutinesRequest, + protos.google.cloud.bigquery.v2.IListRoutinesResponse | null | undefined, + protos.google.cloud.bigquery.v2.IRoutine + >, + ): Promise< + [ + protos.google.cloud.bigquery.v2.IRoutine[], + protos.google.cloud.bigquery.v2.IListRoutinesRequest | null, + protos.google.cloud.bigquery.v2.IListRoutinesResponse, + ] + > | void { request = request || {}; - // Converts number to Unit32 or Int32 value for non-compliant APIs. - if(request.maxResults && typeof request.maxResults === "number"){ - const maxResultsObject = {"value": request.maxResults} - request.maxResults = maxResultsObject - } + // Converts number to Unit32 or Int32 value for non-compliant APIs. + if (request.maxResults && typeof request.maxResults === 'number') { + const maxResultsObject = { value: request.maxResults }; + request.maxResults = maxResultsObject; + } let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'project_id': request.projectId?.toString() ?? '', - 'dataset_id': request.datasetId?.toString() ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + project_id: request.projectId?.toString() ?? '', + dataset_id: request.datasetId?.toString() ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.cloud.bigquery.v2.IListRoutinesRequest, - protos.google.cloud.bigquery.v2.IListRoutinesResponse|null|undefined, - protos.google.cloud.bigquery.v2.IRoutine>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.cloud.bigquery.v2.IListRoutinesRequest, + | protos.google.cloud.bigquery.v2.IListRoutinesResponse + | null + | undefined, + protos.google.cloud.bigquery.v2.IRoutine + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listRoutines values %j', values); callback!(error, values, nextPageRequest, rawResponse); @@ -951,124 +1198,128 @@ export class RoutineServiceClient { this._log.info('listRoutines request %j', request); return this.innerApiCalls .listRoutines(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.cloud.bigquery.v2.IRoutine[], - protos.google.cloud.bigquery.v2.IListRoutinesRequest|null, - protos.google.cloud.bigquery.v2.IListRoutinesResponse - ]) => { - this._log.info('listRoutines values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.cloud.bigquery.v2.IRoutine[], + protos.google.cloud.bigquery.v2.IListRoutinesRequest | null, + protos.google.cloud.bigquery.v2.IListRoutinesResponse, + ]) => { + this._log.info('listRoutines values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listRoutines`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.projectId - * Required. Project ID of the routines to list - * @param {string} request.datasetId - * Required. Dataset ID of the routines to list - * @param {google.protobuf.UInt32Value} request.maxResults - * The maximum number of results to return in a single response page. - * Leverage the page tokens to iterate through the entire collection. - * @param {string} request.pageToken - * Page token, returned by a previous call, to request the next page of - * results - * @param {string} request.filter - * If set, then only the Routines matching this filter are returned. - * The supported format is `routineType:{RoutineType}`, where `{RoutineType}` - * is a RoutineType enum. For example: `routineType:SCALAR_FUNCTION`. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.cloud.bigquery.v2.Routine|Routine} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `listRoutinesAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `listRoutines`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.projectId + * Required. Project ID of the routines to list + * @param {string} request.datasetId + * Required. Dataset ID of the routines to list + * @param {google.protobuf.UInt32Value} request.maxResults + * The maximum number of results to return in a single response page. + * Leverage the page tokens to iterate through the entire collection. + * @param {string} request.pageToken + * Page token, returned by a previous call, to request the next page of + * results + * @param {string} request.filter + * If set, then only the Routines matching this filter are returned. + * The supported format is `routineType:{RoutineType}`, where `{RoutineType}` + * is a RoutineType enum. For example: `routineType:SCALAR_FUNCTION`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.cloud.bigquery.v2.Routine|Routine} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listRoutinesAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listRoutinesStream( - request?: protos.google.cloud.bigquery.v2.IListRoutinesRequest, - options?: CallOptions): - Transform{ + request?: protos.google.cloud.bigquery.v2.IListRoutinesRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'project_id': request.projectId?.toString() ?? '', - 'dataset_id': request.datasetId?.toString() ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + project_id: request.projectId?.toString() ?? '', + dataset_id: request.datasetId?.toString() ?? '', + }); const defaultCallSettings = this._defaults['listRoutines']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listRoutines stream %j', request); return this.descriptors.page.listRoutines.createStream( this.innerApiCalls.listRoutines as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listRoutines`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.projectId - * Required. Project ID of the routines to list - * @param {string} request.datasetId - * Required. Dataset ID of the routines to list - * @param {google.protobuf.UInt32Value} request.maxResults - * The maximum number of results to return in a single response page. - * Leverage the page tokens to iterate through the entire collection. - * @param {string} request.pageToken - * Page token, returned by a previous call, to request the next page of - * results - * @param {string} request.filter - * If set, then only the Routines matching this filter are returned. - * The supported format is `routineType:{RoutineType}`, where `{RoutineType}` - * is a RoutineType enum. For example: `routineType:SCALAR_FUNCTION`. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.cloud.bigquery.v2.Routine|Routine}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v2/routine_service.list_routines.js - * region_tag:bigquery_v2_generated_RoutineService_ListRoutines_async - */ + /** + * Equivalent to `listRoutines`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.projectId + * Required. Project ID of the routines to list + * @param {string} request.datasetId + * Required. Dataset ID of the routines to list + * @param {google.protobuf.UInt32Value} request.maxResults + * The maximum number of results to return in a single response page. + * Leverage the page tokens to iterate through the entire collection. + * @param {string} request.pageToken + * Page token, returned by a previous call, to request the next page of + * results + * @param {string} request.filter + * If set, then only the Routines matching this filter are returned. + * The supported format is `routineType:{RoutineType}`, where `{RoutineType}` + * is a RoutineType enum. For example: `routineType:SCALAR_FUNCTION`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.cloud.bigquery.v2.Routine|Routine}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v2/routine_service.list_routines.js + * region_tag:bigquery_v2_generated_RoutineService_ListRoutines_async + */ listRoutinesAsync( - request?: protos.google.cloud.bigquery.v2.IListRoutinesRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.cloud.bigquery.v2.IListRoutinesRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'project_id': request.projectId?.toString() ?? '', - 'dataset_id': request.datasetId?.toString() ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + project_id: request.projectId?.toString() ?? '', + dataset_id: request.datasetId?.toString() ?? '', + }); const defaultCallSettings = this._defaults['listRoutines']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listRoutines iterate %j', request); return this.descriptors.page.listRoutines.asyncIterate( this.innerApiCalls['listRoutines'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } @@ -1080,7 +1331,7 @@ export class RoutineServiceClient { */ close(): Promise { if (this.routineServiceStub && !this._terminated) { - return this.routineServiceStub.then(stub => { + return this.routineServiceStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -1088,4 +1339,4 @@ export class RoutineServiceClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/core/generator/gapic-generator-typescript/baselines/bigquery-v2-esm/esm/src/v2/row_access_policy_service_client.ts.baseline b/core/generator/gapic-generator-typescript/baselines/bigquery-v2-esm/esm/src/v2/row_access_policy_service_client.ts.baseline index 580b23c30333..27544532bf3c 100644 --- a/core/generator/gapic-generator-typescript/baselines/bigquery-v2-esm/esm/src/v2/row_access_policy_service_client.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/bigquery-v2-esm/esm/src/v2/row_access_policy_service_client.ts.baseline @@ -18,15 +18,22 @@ /* global window */ import * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions, PaginationCallback, GaxCall} from 'google-gax'; -import {Transform} from 'stream'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + PaginationCallback, + GaxCall, +} from 'google-gax'; +import { Transform } from 'stream'; // @ts-ignore import type * as protos from '../../../protos/protos.js'; import * as row_access_policy_service_client_config from './row_access_policy_service_client_config.json'; import fs from 'fs'; import path from 'path'; -import {fileURLToPath} from 'url'; -import {getJSON} from '../json-helper.cjs'; +import { fileURLToPath } from 'url'; +import { getJSON } from '../json-helper.cjs'; // @ts-ignore const dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -36,15 +43,15 @@ const dirname = path.dirname(fileURLToPath(import.meta.url)); * This file defines retry strategy and timeouts for all API methods in this library. */ const gapicConfig = getJSON( - path.join(dirname, 'row_access_policy_service_client_config.json') + path.join(dirname, 'row_access_policy_service_client_config.json'), ); const jsonProtos = getJSON( - path.join(dirname, '..', '..', '..', 'protos/protos.json') + path.join(dirname, '..', '..', '..', 'protos/protos.json'), ); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; const version = getJSON( - path.join(dirname, '..', '..', '..', '..', 'package.json') + path.join(dirname, '..', '..', '..', '..', 'package.json'), ).version; /** @@ -59,7 +66,7 @@ export class RowAccessPolicyServiceClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('bigquery'); @@ -71,8 +78,8 @@ export class RowAccessPolicyServiceClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - rowAccessPolicyServiceStub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + rowAccessPolicyServiceStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of RowAccessPolicyServiceClient. @@ -114,21 +121,43 @@ export class RowAccessPolicyServiceClient { * const client = new RowAccessPolicyServiceClient({fallback: 'rest'}, gax); * ``` */ - constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { // Ensure that options include all the required fields. - const staticMembers = this.constructor as typeof RowAccessPolicyServiceClient; - if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { - throw new Error('Please set either universe_domain or universeDomain, but not both.'); + const staticMembers = this + .constructor as typeof RowAccessPolicyServiceClient; + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); } - const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; - this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; this._servicePath = 'bigquery.' + this._universeDomain; - const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; - const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. if (servicePath !== this._servicePath && !('scopes' in opts)) { @@ -150,7 +179,7 @@ export class RowAccessPolicyServiceClient { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; @@ -167,10 +196,7 @@ export class RowAccessPolicyServiceClient { const isEsm = true; const isEsmString = isEsm ? '-esm' : '-cjs'; // Determine the client header string. - const clientHeader = [ - `gax/${this._gaxModule.version}`, - `gapic/${version}`, - ]; + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/{process.versions.node}${isEsmString}`); } else { @@ -178,7 +204,7 @@ export class RowAccessPolicyServiceClient { } if (!opts.fallback) { clientHeader.push(`grpc/${this._gaxGrpc.grpcVersion}`); - } else if (opts.fallback === 'rest' ) { + } else if (opts.fallback === 'rest') { clientHeader.push(`rest/${this._gaxGrpc.grpcVersion}`); } if (opts.libName && opts.libVersion) { @@ -186,20 +212,28 @@ export class RowAccessPolicyServiceClient { } // Load the applicable protos. - this._protos = this._gaxGrpc.loadProtoJSON(jsonProtos as gax.protobuf.INamespace); + this._protos = this._gaxGrpc.loadProtoJSON( + jsonProtos as gax.protobuf.INamespace, + ); // Some of the methods on this service return "paged" results, // (e.g. 50 results at a time, with tokens to get subsequent // pages). Denote the keys used for pagination and results. this.descriptors.page = { - listRowAccessPolicies: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'rowAccessPolicies') + listRowAccessPolicies: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'rowAccessPolicies', + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.cloud.bigquery.v2.RowAccessPolicyService', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.cloud.bigquery.v2.RowAccessPolicyService', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + { 'x-goog-api-client': clientHeader.join(' ') }, + ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -230,37 +264,40 @@ export class RowAccessPolicyServiceClient { // Put together the "service stub" for // google.cloud.bigquery.v2.RowAccessPolicyService. this.rowAccessPolicyServiceStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.cloud.bigquery.v2.RowAccessPolicyService') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.cloud.bigquery.v2.RowAccessPolicyService', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.cloud.bigquery.v2.RowAccessPolicyService, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts, + this._providedCustomServicePath, + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const rowAccessPolicyServiceStubMethods = - ['listRowAccessPolicies']; + const rowAccessPolicyServiceStubMethods = ['listRowAccessPolicies']; for (const methodName of rowAccessPolicyServiceStubMethods) { const callPromise = this.rowAccessPolicyServiceStub.then( - stub => (...args: Array<{}>) => { - if (this._terminated) { - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error|null|undefined) => () => { + (stub) => + (...args: Array<{}>) => { + if (this._terminated) { + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { throw err; - }); + }, + ); - const descriptor = - this.descriptors.page[methodName] || - undefined; + const descriptor = this.descriptors.page[methodName] || undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -275,8 +312,14 @@ export class RowAccessPolicyServiceClient { * @returns {string} The DNS address for this service. */ static get servicePath() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'bigquery.googleapis.com'; } @@ -288,8 +331,14 @@ export class RowAccessPolicyServiceClient { * @returns {string} The DNS address for this service. */ static get apiEndpoint() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'bigquery.googleapis.com'; } @@ -323,7 +372,7 @@ export class RowAccessPolicyServiceClient { return [ 'https://www.googleapis.com/auth/bigquery', 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloud-platform.read-only' + 'https://www.googleapis.com/auth/cloud-platform.read-only', ]; } @@ -333,8 +382,9 @@ export class RowAccessPolicyServiceClient { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId(callback?: Callback): - Promise|void { + getProjectId( + callback?: Callback, + ): Promise | void { if (callback) { this.auth.getProjectId(callback); return; @@ -346,95 +396,120 @@ export class RowAccessPolicyServiceClient { // -- Service calls -- // ------------------- - /** - * Lists all row access policies on the specified table. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.projectId - * Required. Project ID of the row access policies to list. - * @param {string} request.datasetId - * Required. Dataset ID of row access policies to list. - * @param {string} request.tableId - * Required. Table ID of the table to list row access policies. - * @param {string} request.pageToken - * Page token, returned by a previous call, to request the next page of - * results. - * @param {number} request.pageSize - * The maximum number of results to return in a single response page. Leverage - * the page tokens to iterate through the entire collection. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.cloud.bigquery.v2.RowAccessPolicy|RowAccessPolicy}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `listRowAccessPoliciesAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Lists all row access policies on the specified table. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.projectId + * Required. Project ID of the row access policies to list. + * @param {string} request.datasetId + * Required. Dataset ID of row access policies to list. + * @param {string} request.tableId + * Required. Table ID of the table to list row access policies. + * @param {string} request.pageToken + * Page token, returned by a previous call, to request the next page of + * results. + * @param {number} request.pageSize + * The maximum number of results to return in a single response page. Leverage + * the page tokens to iterate through the entire collection. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.cloud.bigquery.v2.RowAccessPolicy|RowAccessPolicy}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listRowAccessPoliciesAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listRowAccessPolicies( - request?: protos.google.cloud.bigquery.v2.IListRowAccessPoliciesRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.bigquery.v2.IRowAccessPolicy[], - protos.google.cloud.bigquery.v2.IListRowAccessPoliciesRequest|null, - protos.google.cloud.bigquery.v2.IListRowAccessPoliciesResponse - ]>; + request?: protos.google.cloud.bigquery.v2.IListRowAccessPoliciesRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.bigquery.v2.IRowAccessPolicy[], + protos.google.cloud.bigquery.v2.IListRowAccessPoliciesRequest | null, + protos.google.cloud.bigquery.v2.IListRowAccessPoliciesResponse, + ] + >; listRowAccessPolicies( - request: protos.google.cloud.bigquery.v2.IListRowAccessPoliciesRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.cloud.bigquery.v2.IListRowAccessPoliciesRequest, - protos.google.cloud.bigquery.v2.IListRowAccessPoliciesResponse|null|undefined, - protos.google.cloud.bigquery.v2.IRowAccessPolicy>): void; + request: protos.google.cloud.bigquery.v2.IListRowAccessPoliciesRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.cloud.bigquery.v2.IListRowAccessPoliciesRequest, + | protos.google.cloud.bigquery.v2.IListRowAccessPoliciesResponse + | null + | undefined, + protos.google.cloud.bigquery.v2.IRowAccessPolicy + >, + ): void; listRowAccessPolicies( - request: protos.google.cloud.bigquery.v2.IListRowAccessPoliciesRequest, - callback: PaginationCallback< - protos.google.cloud.bigquery.v2.IListRowAccessPoliciesRequest, - protos.google.cloud.bigquery.v2.IListRowAccessPoliciesResponse|null|undefined, - protos.google.cloud.bigquery.v2.IRowAccessPolicy>): void; + request: protos.google.cloud.bigquery.v2.IListRowAccessPoliciesRequest, + callback: PaginationCallback< + protos.google.cloud.bigquery.v2.IListRowAccessPoliciesRequest, + | protos.google.cloud.bigquery.v2.IListRowAccessPoliciesResponse + | null + | undefined, + protos.google.cloud.bigquery.v2.IRowAccessPolicy + >, + ): void; listRowAccessPolicies( - request?: protos.google.cloud.bigquery.v2.IListRowAccessPoliciesRequest, - optionsOrCallback?: CallOptions|PaginationCallback< - protos.google.cloud.bigquery.v2.IListRowAccessPoliciesRequest, - protos.google.cloud.bigquery.v2.IListRowAccessPoliciesResponse|null|undefined, - protos.google.cloud.bigquery.v2.IRowAccessPolicy>, - callback?: PaginationCallback< + request?: protos.google.cloud.bigquery.v2.IListRowAccessPoliciesRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.cloud.bigquery.v2.IListRowAccessPoliciesRequest, - protos.google.cloud.bigquery.v2.IListRowAccessPoliciesResponse|null|undefined, - protos.google.cloud.bigquery.v2.IRowAccessPolicy>): - Promise<[ - protos.google.cloud.bigquery.v2.IRowAccessPolicy[], - protos.google.cloud.bigquery.v2.IListRowAccessPoliciesRequest|null, - protos.google.cloud.bigquery.v2.IListRowAccessPoliciesResponse - ]>|void { + | protos.google.cloud.bigquery.v2.IListRowAccessPoliciesResponse + | null + | undefined, + protos.google.cloud.bigquery.v2.IRowAccessPolicy + >, + callback?: PaginationCallback< + protos.google.cloud.bigquery.v2.IListRowAccessPoliciesRequest, + | protos.google.cloud.bigquery.v2.IListRowAccessPoliciesResponse + | null + | undefined, + protos.google.cloud.bigquery.v2.IRowAccessPolicy + >, + ): Promise< + [ + protos.google.cloud.bigquery.v2.IRowAccessPolicy[], + protos.google.cloud.bigquery.v2.IListRowAccessPoliciesRequest | null, + protos.google.cloud.bigquery.v2.IListRowAccessPoliciesResponse, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'project_id': request.projectId?.toString() ?? '', - 'dataset_id': request.datasetId?.toString() ?? '', - 'table_id': request.tableId?.toString() ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + project_id: request.projectId?.toString() ?? '', + dataset_id: request.datasetId?.toString() ?? '', + table_id: request.tableId?.toString() ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.cloud.bigquery.v2.IListRowAccessPoliciesRequest, - protos.google.cloud.bigquery.v2.IListRowAccessPoliciesResponse|null|undefined, - protos.google.cloud.bigquery.v2.IRowAccessPolicy>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.cloud.bigquery.v2.IListRowAccessPoliciesRequest, + | protos.google.cloud.bigquery.v2.IListRowAccessPoliciesResponse + | null + | undefined, + protos.google.cloud.bigquery.v2.IRowAccessPolicy + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listRowAccessPolicies values %j', values); callback!(error, values, nextPageRequest, rawResponse); @@ -443,122 +518,126 @@ export class RowAccessPolicyServiceClient { this._log.info('listRowAccessPolicies request %j', request); return this.innerApiCalls .listRowAccessPolicies(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.cloud.bigquery.v2.IRowAccessPolicy[], - protos.google.cloud.bigquery.v2.IListRowAccessPoliciesRequest|null, - protos.google.cloud.bigquery.v2.IListRowAccessPoliciesResponse - ]) => { - this._log.info('listRowAccessPolicies values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.cloud.bigquery.v2.IRowAccessPolicy[], + protos.google.cloud.bigquery.v2.IListRowAccessPoliciesRequest | null, + protos.google.cloud.bigquery.v2.IListRowAccessPoliciesResponse, + ]) => { + this._log.info('listRowAccessPolicies values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listRowAccessPolicies`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.projectId - * Required. Project ID of the row access policies to list. - * @param {string} request.datasetId - * Required. Dataset ID of row access policies to list. - * @param {string} request.tableId - * Required. Table ID of the table to list row access policies. - * @param {string} request.pageToken - * Page token, returned by a previous call, to request the next page of - * results. - * @param {number} request.pageSize - * The maximum number of results to return in a single response page. Leverage - * the page tokens to iterate through the entire collection. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.cloud.bigquery.v2.RowAccessPolicy|RowAccessPolicy} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `listRowAccessPoliciesAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `listRowAccessPolicies`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.projectId + * Required. Project ID of the row access policies to list. + * @param {string} request.datasetId + * Required. Dataset ID of row access policies to list. + * @param {string} request.tableId + * Required. Table ID of the table to list row access policies. + * @param {string} request.pageToken + * Page token, returned by a previous call, to request the next page of + * results. + * @param {number} request.pageSize + * The maximum number of results to return in a single response page. Leverage + * the page tokens to iterate through the entire collection. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.cloud.bigquery.v2.RowAccessPolicy|RowAccessPolicy} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listRowAccessPoliciesAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listRowAccessPoliciesStream( - request?: protos.google.cloud.bigquery.v2.IListRowAccessPoliciesRequest, - options?: CallOptions): - Transform{ + request?: protos.google.cloud.bigquery.v2.IListRowAccessPoliciesRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'project_id': request.projectId?.toString() ?? '', - 'dataset_id': request.datasetId?.toString() ?? '', - 'table_id': request.tableId?.toString() ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + project_id: request.projectId?.toString() ?? '', + dataset_id: request.datasetId?.toString() ?? '', + table_id: request.tableId?.toString() ?? '', + }); const defaultCallSettings = this._defaults['listRowAccessPolicies']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listRowAccessPolicies stream %j', request); return this.descriptors.page.listRowAccessPolicies.createStream( this.innerApiCalls.listRowAccessPolicies as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listRowAccessPolicies`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.projectId - * Required. Project ID of the row access policies to list. - * @param {string} request.datasetId - * Required. Dataset ID of row access policies to list. - * @param {string} request.tableId - * Required. Table ID of the table to list row access policies. - * @param {string} request.pageToken - * Page token, returned by a previous call, to request the next page of - * results. - * @param {number} request.pageSize - * The maximum number of results to return in a single response page. Leverage - * the page tokens to iterate through the entire collection. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.cloud.bigquery.v2.RowAccessPolicy|RowAccessPolicy}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v2/row_access_policy_service.list_row_access_policies.js - * region_tag:bigquery_v2_generated_RowAccessPolicyService_ListRowAccessPolicies_async - */ + /** + * Equivalent to `listRowAccessPolicies`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.projectId + * Required. Project ID of the row access policies to list. + * @param {string} request.datasetId + * Required. Dataset ID of row access policies to list. + * @param {string} request.tableId + * Required. Table ID of the table to list row access policies. + * @param {string} request.pageToken + * Page token, returned by a previous call, to request the next page of + * results. + * @param {number} request.pageSize + * The maximum number of results to return in a single response page. Leverage + * the page tokens to iterate through the entire collection. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.cloud.bigquery.v2.RowAccessPolicy|RowAccessPolicy}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v2/row_access_policy_service.list_row_access_policies.js + * region_tag:bigquery_v2_generated_RowAccessPolicyService_ListRowAccessPolicies_async + */ listRowAccessPoliciesAsync( - request?: protos.google.cloud.bigquery.v2.IListRowAccessPoliciesRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.cloud.bigquery.v2.IListRowAccessPoliciesRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'project_id': request.projectId?.toString() ?? '', - 'dataset_id': request.datasetId?.toString() ?? '', - 'table_id': request.tableId?.toString() ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + project_id: request.projectId?.toString() ?? '', + dataset_id: request.datasetId?.toString() ?? '', + table_id: request.tableId?.toString() ?? '', + }); const defaultCallSettings = this._defaults['listRowAccessPolicies']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listRowAccessPolicies iterate %j', request); return this.descriptors.page.listRowAccessPolicies.asyncIterate( this.innerApiCalls['listRowAccessPolicies'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } @@ -570,7 +649,7 @@ export class RowAccessPolicyServiceClient { */ close(): Promise { if (this.rowAccessPolicyServiceStub && !this._terminated) { - return this.rowAccessPolicyServiceStub.then(stub => { + return this.rowAccessPolicyServiceStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -578,4 +657,4 @@ export class RowAccessPolicyServiceClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/core/generator/gapic-generator-typescript/baselines/bigquery-v2-esm/esm/src/v2/table_service_client.ts.baseline b/core/generator/gapic-generator-typescript/baselines/bigquery-v2-esm/esm/src/v2/table_service_client.ts.baseline index 3b8d5a6ed0d2..67f9d559de64 100644 --- a/core/generator/gapic-generator-typescript/baselines/bigquery-v2-esm/esm/src/v2/table_service_client.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/bigquery-v2-esm/esm/src/v2/table_service_client.ts.baseline @@ -18,15 +18,22 @@ /* global window */ import * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions, PaginationCallback, GaxCall} from 'google-gax'; -import {Transform} from 'stream'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + PaginationCallback, + GaxCall, +} from 'google-gax'; +import { Transform } from 'stream'; // @ts-ignore import type * as protos from '../../../protos/protos.js'; import * as table_service_client_config from './table_service_client_config.json'; import fs from 'fs'; import path from 'path'; -import {fileURLToPath} from 'url'; -import {getJSON} from '../json-helper.cjs'; +import { fileURLToPath } from 'url'; +import { getJSON } from '../json-helper.cjs'; // @ts-ignore const dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -36,15 +43,15 @@ const dirname = path.dirname(fileURLToPath(import.meta.url)); * This file defines retry strategy and timeouts for all API methods in this library. */ const gapicConfig = getJSON( - path.join(dirname, 'table_service_client_config.json') + path.join(dirname, 'table_service_client_config.json'), ); const jsonProtos = getJSON( - path.join(dirname, '..', '..', '..', 'protos/protos.json') + path.join(dirname, '..', '..', '..', 'protos/protos.json'), ); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; const version = getJSON( - path.join(dirname, '..', '..', '..', '..', 'package.json') + path.join(dirname, '..', '..', '..', '..', 'package.json'), ).version; /** @@ -62,7 +69,7 @@ export class TableServiceClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('bigquery'); @@ -74,8 +81,8 @@ export class TableServiceClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - tableServiceStub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + tableServiceStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of TableServiceClient. @@ -117,21 +124,42 @@ export class TableServiceClient { * const client = new TableServiceClient({fallback: 'rest'}, gax); * ``` */ - constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { // Ensure that options include all the required fields. const staticMembers = this.constructor as typeof TableServiceClient; - if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { - throw new Error('Please set either universe_domain or universeDomain, but not both.'); + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); } - const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; - this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; this._servicePath = 'bigquery.' + this._universeDomain; - const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; - const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. if (servicePath !== this._servicePath && !('scopes' in opts)) { @@ -153,7 +181,7 @@ export class TableServiceClient { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; @@ -170,10 +198,7 @@ export class TableServiceClient { const isEsm = true; const isEsmString = isEsm ? '-esm' : '-cjs'; // Determine the client header string. - const clientHeader = [ - `gax/${this._gaxModule.version}`, - `gapic/${version}`, - ]; + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/{process.versions.node}${isEsmString}`); } else { @@ -181,7 +206,7 @@ export class TableServiceClient { } if (!opts.fallback) { clientHeader.push(`grpc/${this._gaxGrpc.grpcVersion}`); - } else if (opts.fallback === 'rest' ) { + } else if (opts.fallback === 'rest') { clientHeader.push(`rest/${this._gaxGrpc.grpcVersion}`); } if (opts.libName && opts.libVersion) { @@ -189,20 +214,28 @@ export class TableServiceClient { } // Load the applicable protos. - this._protos = this._gaxGrpc.loadProtoJSON(jsonProtos as gax.protobuf.INamespace); + this._protos = this._gaxGrpc.loadProtoJSON( + jsonProtos as gax.protobuf.INamespace, + ); // Some of the methods on this service return "paged" results, // (e.g. 50 results at a time, with tokens to get subsequent // pages). Denote the keys used for pagination and results. this.descriptors.page = { - listTables: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'tables') + listTables: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'tables', + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.cloud.bigquery.v2.TableService', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.cloud.bigquery.v2.TableService', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + { 'x-goog-api-client': clientHeader.join(' ') }, + ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -233,37 +266,47 @@ export class TableServiceClient { // Put together the "service stub" for // google.cloud.bigquery.v2.TableService. this.tableServiceStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.cloud.bigquery.v2.TableService') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.cloud.bigquery.v2.TableService', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.cloud.bigquery.v2.TableService, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts, + this._providedCustomServicePath, + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const tableServiceStubMethods = - ['getTable', 'insertTable', 'patchTable', 'updateTable', 'deleteTable', 'listTables']; + const tableServiceStubMethods = [ + 'getTable', + 'insertTable', + 'patchTable', + 'updateTable', + 'deleteTable', + 'listTables', + ]; for (const methodName of tableServiceStubMethods) { const callPromise = this.tableServiceStub.then( - stub => (...args: Array<{}>) => { - if (this._terminated) { - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error|null|undefined) => () => { + (stub) => + (...args: Array<{}>) => { + if (this._terminated) { + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { throw err; - }); + }, + ); - const descriptor = - this.descriptors.page[methodName] || - undefined; + const descriptor = this.descriptors.page[methodName] || undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -278,8 +321,14 @@ export class TableServiceClient { * @returns {string} The DNS address for this service. */ static get servicePath() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'bigquery.googleapis.com'; } @@ -291,8 +340,14 @@ export class TableServiceClient { * @returns {string} The DNS address for this service. */ static get apiEndpoint() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'bigquery.googleapis.com'; } @@ -326,7 +381,7 @@ export class TableServiceClient { return [ 'https://www.googleapis.com/auth/bigquery', 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloud-platform.read-only' + 'https://www.googleapis.com/auth/cloud-platform.read-only', ]; } @@ -336,8 +391,9 @@ export class TableServiceClient { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId(callback?: Callback): - Promise|void { + getProjectId( + callback?: Callback, + ): Promise | void { if (callback) { this.auth.getProjectId(callback); return; @@ -348,620 +404,824 @@ export class TableServiceClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Gets the specified table resource by table ID. - * This method does not return the data in the table, it only returns the - * table resource, which describes the structure of this table. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.projectId - * Required. Project ID of the requested table - * @param {string} request.datasetId - * Required. Dataset ID of the requested table - * @param {string} request.tableId - * Required. Table ID of the requested table - * @param {string} request.selectedFields - * List of table schema fields to return (comma-separated). - * If unspecified, all fields are returned. - * A fieldMask cannot be used here because the fields will automatically be - * converted from camelCase to snake_case and the conversion will fail if - * there are underscores. Since these are fields in BigQuery table schemas, - * underscores are allowed. - * @param {google.cloud.bigquery.v2.GetTableRequest.TableMetadataView} [request.view] - * Optional. Specifies the view that determines which table information is - * returned. By default, basic table information and storage statistics - * (STORAGE_STATS) are returned. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.bigquery.v2.Table|Table}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/table_service.get_table.js - * region_tag:bigquery_v2_generated_TableService_GetTable_async - */ + /** + * Gets the specified table resource by table ID. + * This method does not return the data in the table, it only returns the + * table resource, which describes the structure of this table. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.projectId + * Required. Project ID of the requested table + * @param {string} request.datasetId + * Required. Dataset ID of the requested table + * @param {string} request.tableId + * Required. Table ID of the requested table + * @param {string} request.selectedFields + * List of table schema fields to return (comma-separated). + * If unspecified, all fields are returned. + * A fieldMask cannot be used here because the fields will automatically be + * converted from camelCase to snake_case and the conversion will fail if + * there are underscores. Since these are fields in BigQuery table schemas, + * underscores are allowed. + * @param {google.cloud.bigquery.v2.GetTableRequest.TableMetadataView} [request.view] + * Optional. Specifies the view that determines which table information is + * returned. By default, basic table information and storage statistics + * (STORAGE_STATS) are returned. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.bigquery.v2.Table|Table}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/table_service.get_table.js + * region_tag:bigquery_v2_generated_TableService_GetTable_async + */ getTable( - request?: protos.google.cloud.bigquery.v2.IGetTableRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.bigquery.v2.ITable, - protos.google.cloud.bigquery.v2.IGetTableRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.bigquery.v2.IGetTableRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.bigquery.v2.ITable, + protos.google.cloud.bigquery.v2.IGetTableRequest | undefined, + {} | undefined, + ] + >; getTable( - request: protos.google.cloud.bigquery.v2.IGetTableRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.bigquery.v2.ITable, - protos.google.cloud.bigquery.v2.IGetTableRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.bigquery.v2.IGetTableRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.bigquery.v2.ITable, + protos.google.cloud.bigquery.v2.IGetTableRequest | null | undefined, + {} | null | undefined + >, + ): void; getTable( - request: protos.google.cloud.bigquery.v2.IGetTableRequest, - callback: Callback< - protos.google.cloud.bigquery.v2.ITable, - protos.google.cloud.bigquery.v2.IGetTableRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.bigquery.v2.IGetTableRequest, + callback: Callback< + protos.google.cloud.bigquery.v2.ITable, + protos.google.cloud.bigquery.v2.IGetTableRequest | null | undefined, + {} | null | undefined + >, + ): void; getTable( - request?: protos.google.cloud.bigquery.v2.IGetTableRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.bigquery.v2.ITable, - protos.google.cloud.bigquery.v2.IGetTableRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.bigquery.v2.IGetTableRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.bigquery.v2.ITable, - protos.google.cloud.bigquery.v2.IGetTableRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.bigquery.v2.ITable, - protos.google.cloud.bigquery.v2.IGetTableRequest|undefined, {}|undefined - ]>|void { + protos.google.cloud.bigquery.v2.IGetTableRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.bigquery.v2.ITable, + protos.google.cloud.bigquery.v2.IGetTableRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.bigquery.v2.ITable, + protos.google.cloud.bigquery.v2.IGetTableRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'project_id': request.projectId?.toString() ?? '', - 'dataset_id': request.datasetId?.toString() ?? '', - 'table_id': request.tableId?.toString() ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + project_id: request.projectId?.toString() ?? '', + dataset_id: request.datasetId?.toString() ?? '', + table_id: request.tableId?.toString() ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getTable request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.bigquery.v2.ITable, - protos.google.cloud.bigquery.v2.IGetTableRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.bigquery.v2.ITable, + protos.google.cloud.bigquery.v2.IGetTableRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getTable response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.getTable(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.bigquery.v2.ITable, - protos.google.cloud.bigquery.v2.IGetTableRequest|undefined, {}|undefined - ]) => { - this._log.info('getTable response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getTable(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.bigquery.v2.ITable, + protos.google.cloud.bigquery.v2.IGetTableRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getTable response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Creates a new, empty table in the dataset. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.projectId - * Required. Project ID of the new table - * @param {string} request.datasetId - * Required. Dataset ID of the new table - * @param {google.cloud.bigquery.v2.Table} request.table - * Required. A tables resource to insert - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.bigquery.v2.Table|Table}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/table_service.insert_table.js - * region_tag:bigquery_v2_generated_TableService_InsertTable_async - */ + /** + * Creates a new, empty table in the dataset. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.projectId + * Required. Project ID of the new table + * @param {string} request.datasetId + * Required. Dataset ID of the new table + * @param {google.cloud.bigquery.v2.Table} request.table + * Required. A tables resource to insert + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.bigquery.v2.Table|Table}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/table_service.insert_table.js + * region_tag:bigquery_v2_generated_TableService_InsertTable_async + */ insertTable( - request?: protos.google.cloud.bigquery.v2.IInsertTableRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.bigquery.v2.ITable, - protos.google.cloud.bigquery.v2.IInsertTableRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.bigquery.v2.IInsertTableRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.bigquery.v2.ITable, + protos.google.cloud.bigquery.v2.IInsertTableRequest | undefined, + {} | undefined, + ] + >; insertTable( - request: protos.google.cloud.bigquery.v2.IInsertTableRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.bigquery.v2.ITable, - protos.google.cloud.bigquery.v2.IInsertTableRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.bigquery.v2.IInsertTableRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.bigquery.v2.ITable, + protos.google.cloud.bigquery.v2.IInsertTableRequest | null | undefined, + {} | null | undefined + >, + ): void; insertTable( - request: protos.google.cloud.bigquery.v2.IInsertTableRequest, - callback: Callback< - protos.google.cloud.bigquery.v2.ITable, - protos.google.cloud.bigquery.v2.IInsertTableRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.bigquery.v2.IInsertTableRequest, + callback: Callback< + protos.google.cloud.bigquery.v2.ITable, + protos.google.cloud.bigquery.v2.IInsertTableRequest | null | undefined, + {} | null | undefined + >, + ): void; insertTable( - request?: protos.google.cloud.bigquery.v2.IInsertTableRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.bigquery.v2.ITable, - protos.google.cloud.bigquery.v2.IInsertTableRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.bigquery.v2.IInsertTableRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.bigquery.v2.ITable, - protos.google.cloud.bigquery.v2.IInsertTableRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.bigquery.v2.ITable, - protos.google.cloud.bigquery.v2.IInsertTableRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.bigquery.v2.IInsertTableRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.bigquery.v2.ITable, + protos.google.cloud.bigquery.v2.IInsertTableRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.bigquery.v2.ITable, + protos.google.cloud.bigquery.v2.IInsertTableRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'project_id': request.projectId?.toString() ?? '', - 'dataset_id': request.datasetId?.toString() ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + project_id: request.projectId?.toString() ?? '', + dataset_id: request.datasetId?.toString() ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('insertTable request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.bigquery.v2.ITable, - protos.google.cloud.bigquery.v2.IInsertTableRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.bigquery.v2.ITable, + | protos.google.cloud.bigquery.v2.IInsertTableRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('insertTable response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.insertTable(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.bigquery.v2.ITable, - protos.google.cloud.bigquery.v2.IInsertTableRequest|undefined, {}|undefined - ]) => { - this._log.info('insertTable response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .insertTable(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.bigquery.v2.ITable, + protos.google.cloud.bigquery.v2.IInsertTableRequest | undefined, + {} | undefined, + ]) => { + this._log.info('insertTable response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Updates information in an existing table. The update method replaces the - * entire table resource, whereas the patch method only replaces fields that - * are provided in the submitted table resource. - * This method supports RFC5789 patch semantics. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.projectId - * Required. Project ID of the table to update - * @param {string} request.datasetId - * Required. Dataset ID of the table to update - * @param {string} request.tableId - * Required. Table ID of the table to update - * @param {google.cloud.bigquery.v2.Table} request.table - * Required. A tables resource which will replace or patch the specified table - * @param {boolean} [request.autodetectSchema] - * Optional. When true will autodetect schema, else will keep original schema. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.bigquery.v2.Table|Table}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/table_service.patch_table.js - * region_tag:bigquery_v2_generated_TableService_PatchTable_async - */ + /** + * Updates information in an existing table. The update method replaces the + * entire table resource, whereas the patch method only replaces fields that + * are provided in the submitted table resource. + * This method supports RFC5789 patch semantics. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.projectId + * Required. Project ID of the table to update + * @param {string} request.datasetId + * Required. Dataset ID of the table to update + * @param {string} request.tableId + * Required. Table ID of the table to update + * @param {google.cloud.bigquery.v2.Table} request.table + * Required. A tables resource which will replace or patch the specified table + * @param {boolean} [request.autodetectSchema] + * Optional. When true will autodetect schema, else will keep original schema. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.bigquery.v2.Table|Table}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/table_service.patch_table.js + * region_tag:bigquery_v2_generated_TableService_PatchTable_async + */ patchTable( - request?: protos.google.cloud.bigquery.v2.IUpdateOrPatchTableRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.bigquery.v2.ITable, - protos.google.cloud.bigquery.v2.IUpdateOrPatchTableRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.bigquery.v2.IUpdateOrPatchTableRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.bigquery.v2.ITable, + protos.google.cloud.bigquery.v2.IUpdateOrPatchTableRequest | undefined, + {} | undefined, + ] + >; patchTable( - request: protos.google.cloud.bigquery.v2.IUpdateOrPatchTableRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.bigquery.v2.ITable, - protos.google.cloud.bigquery.v2.IUpdateOrPatchTableRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.bigquery.v2.IUpdateOrPatchTableRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.bigquery.v2.ITable, + | protos.google.cloud.bigquery.v2.IUpdateOrPatchTableRequest + | null + | undefined, + {} | null | undefined + >, + ): void; patchTable( - request: protos.google.cloud.bigquery.v2.IUpdateOrPatchTableRequest, - callback: Callback< - protos.google.cloud.bigquery.v2.ITable, - protos.google.cloud.bigquery.v2.IUpdateOrPatchTableRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.bigquery.v2.IUpdateOrPatchTableRequest, + callback: Callback< + protos.google.cloud.bigquery.v2.ITable, + | protos.google.cloud.bigquery.v2.IUpdateOrPatchTableRequest + | null + | undefined, + {} | null | undefined + >, + ): void; patchTable( - request?: protos.google.cloud.bigquery.v2.IUpdateOrPatchTableRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.cloud.bigquery.v2.IUpdateOrPatchTableRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.bigquery.v2.ITable, - protos.google.cloud.bigquery.v2.IUpdateOrPatchTableRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.cloud.bigquery.v2.ITable, - protos.google.cloud.bigquery.v2.IUpdateOrPatchTableRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.bigquery.v2.ITable, - protos.google.cloud.bigquery.v2.IUpdateOrPatchTableRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.bigquery.v2.IUpdateOrPatchTableRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.bigquery.v2.ITable, + | protos.google.cloud.bigquery.v2.IUpdateOrPatchTableRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.bigquery.v2.ITable, + protos.google.cloud.bigquery.v2.IUpdateOrPatchTableRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'project_id': request.projectId?.toString() ?? '', - 'dataset_id': request.datasetId?.toString() ?? '', - 'table_id': request.tableId?.toString() ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + project_id: request.projectId?.toString() ?? '', + dataset_id: request.datasetId?.toString() ?? '', + table_id: request.tableId?.toString() ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('patchTable request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.bigquery.v2.ITable, - protos.google.cloud.bigquery.v2.IUpdateOrPatchTableRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.bigquery.v2.ITable, + | protos.google.cloud.bigquery.v2.IUpdateOrPatchTableRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('patchTable response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.patchTable(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.bigquery.v2.ITable, - protos.google.cloud.bigquery.v2.IUpdateOrPatchTableRequest|undefined, {}|undefined - ]) => { - this._log.info('patchTable response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .patchTable(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.bigquery.v2.ITable, + ( + | protos.google.cloud.bigquery.v2.IUpdateOrPatchTableRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('patchTable response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Updates information in an existing table. The update method replaces the - * entire Table resource, whereas the patch method only replaces fields that - * are provided in the submitted Table resource. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.projectId - * Required. Project ID of the table to update - * @param {string} request.datasetId - * Required. Dataset ID of the table to update - * @param {string} request.tableId - * Required. Table ID of the table to update - * @param {google.cloud.bigquery.v2.Table} request.table - * Required. A tables resource which will replace or patch the specified table - * @param {boolean} [request.autodetectSchema] - * Optional. When true will autodetect schema, else will keep original schema. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.bigquery.v2.Table|Table}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/table_service.update_table.js - * region_tag:bigquery_v2_generated_TableService_UpdateTable_async - */ + /** + * Updates information in an existing table. The update method replaces the + * entire Table resource, whereas the patch method only replaces fields that + * are provided in the submitted Table resource. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.projectId + * Required. Project ID of the table to update + * @param {string} request.datasetId + * Required. Dataset ID of the table to update + * @param {string} request.tableId + * Required. Table ID of the table to update + * @param {google.cloud.bigquery.v2.Table} request.table + * Required. A tables resource which will replace or patch the specified table + * @param {boolean} [request.autodetectSchema] + * Optional. When true will autodetect schema, else will keep original schema. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.bigquery.v2.Table|Table}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/table_service.update_table.js + * region_tag:bigquery_v2_generated_TableService_UpdateTable_async + */ updateTable( - request?: protos.google.cloud.bigquery.v2.IUpdateOrPatchTableRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.bigquery.v2.ITable, - protos.google.cloud.bigquery.v2.IUpdateOrPatchTableRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.bigquery.v2.IUpdateOrPatchTableRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.bigquery.v2.ITable, + protos.google.cloud.bigquery.v2.IUpdateOrPatchTableRequest | undefined, + {} | undefined, + ] + >; updateTable( - request: protos.google.cloud.bigquery.v2.IUpdateOrPatchTableRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.bigquery.v2.ITable, - protos.google.cloud.bigquery.v2.IUpdateOrPatchTableRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.bigquery.v2.IUpdateOrPatchTableRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.bigquery.v2.ITable, + | protos.google.cloud.bigquery.v2.IUpdateOrPatchTableRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateTable( - request: protos.google.cloud.bigquery.v2.IUpdateOrPatchTableRequest, - callback: Callback< - protos.google.cloud.bigquery.v2.ITable, - protos.google.cloud.bigquery.v2.IUpdateOrPatchTableRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.bigquery.v2.IUpdateOrPatchTableRequest, + callback: Callback< + protos.google.cloud.bigquery.v2.ITable, + | protos.google.cloud.bigquery.v2.IUpdateOrPatchTableRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateTable( - request?: protos.google.cloud.bigquery.v2.IUpdateOrPatchTableRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.cloud.bigquery.v2.IUpdateOrPatchTableRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.bigquery.v2.ITable, - protos.google.cloud.bigquery.v2.IUpdateOrPatchTableRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.cloud.bigquery.v2.ITable, - protos.google.cloud.bigquery.v2.IUpdateOrPatchTableRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.bigquery.v2.ITable, - protos.google.cloud.bigquery.v2.IUpdateOrPatchTableRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.bigquery.v2.IUpdateOrPatchTableRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.bigquery.v2.ITable, + | protos.google.cloud.bigquery.v2.IUpdateOrPatchTableRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.bigquery.v2.ITable, + protos.google.cloud.bigquery.v2.IUpdateOrPatchTableRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'project_id': request.projectId?.toString() ?? '', - 'dataset_id': request.datasetId?.toString() ?? '', - 'table_id': request.tableId?.toString() ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + project_id: request.projectId?.toString() ?? '', + dataset_id: request.datasetId?.toString() ?? '', + table_id: request.tableId?.toString() ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateTable request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.bigquery.v2.ITable, - protos.google.cloud.bigquery.v2.IUpdateOrPatchTableRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.bigquery.v2.ITable, + | protos.google.cloud.bigquery.v2.IUpdateOrPatchTableRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateTable response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.updateTable(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.bigquery.v2.ITable, - protos.google.cloud.bigquery.v2.IUpdateOrPatchTableRequest|undefined, {}|undefined - ]) => { - this._log.info('updateTable response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateTable(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.bigquery.v2.ITable, + ( + | protos.google.cloud.bigquery.v2.IUpdateOrPatchTableRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('updateTable response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Deletes the table specified by tableId from the dataset. - * If the table contains data, all the data will be deleted. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.projectId - * Required. Project ID of the table to delete - * @param {string} request.datasetId - * Required. Dataset ID of the table to delete - * @param {string} request.tableId - * Required. Table ID of the table to delete - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/table_service.delete_table.js - * region_tag:bigquery_v2_generated_TableService_DeleteTable_async - */ + /** + * Deletes the table specified by tableId from the dataset. + * If the table contains data, all the data will be deleted. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.projectId + * Required. Project ID of the table to delete + * @param {string} request.datasetId + * Required. Dataset ID of the table to delete + * @param {string} request.tableId + * Required. Table ID of the table to delete + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/table_service.delete_table.js + * region_tag:bigquery_v2_generated_TableService_DeleteTable_async + */ deleteTable( - request?: protos.google.cloud.bigquery.v2.IDeleteTableRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.cloud.bigquery.v2.IDeleteTableRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.bigquery.v2.IDeleteTableRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.cloud.bigquery.v2.IDeleteTableRequest | undefined, + {} | undefined, + ] + >; deleteTable( - request: protos.google.cloud.bigquery.v2.IDeleteTableRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.cloud.bigquery.v2.IDeleteTableRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.bigquery.v2.IDeleteTableRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.cloud.bigquery.v2.IDeleteTableRequest | null | undefined, + {} | null | undefined + >, + ): void; deleteTable( - request: protos.google.cloud.bigquery.v2.IDeleteTableRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.cloud.bigquery.v2.IDeleteTableRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.bigquery.v2.IDeleteTableRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.cloud.bigquery.v2.IDeleteTableRequest | null | undefined, + {} | null | undefined + >, + ): void; deleteTable( - request?: protos.google.cloud.bigquery.v2.IDeleteTableRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.protobuf.IEmpty, - protos.google.cloud.bigquery.v2.IDeleteTableRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.bigquery.v2.IDeleteTableRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.cloud.bigquery.v2.IDeleteTableRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.cloud.bigquery.v2.IDeleteTableRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.bigquery.v2.IDeleteTableRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + protos.google.cloud.bigquery.v2.IDeleteTableRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.cloud.bigquery.v2.IDeleteTableRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'project_id': request.projectId?.toString() ?? '', - 'dataset_id': request.datasetId?.toString() ?? '', - 'table_id': request.tableId?.toString() ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + project_id: request.projectId?.toString() ?? '', + dataset_id: request.datasetId?.toString() ?? '', + table_id: request.tableId?.toString() ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('deleteTable request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.cloud.bigquery.v2.IDeleteTableRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.cloud.bigquery.v2.IDeleteTableRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteTable response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.deleteTable(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.cloud.bigquery.v2.IDeleteTableRequest|undefined, {}|undefined - ]) => { - this._log.info('deleteTable response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteTable(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.cloud.bigquery.v2.IDeleteTableRequest | undefined, + {} | undefined, + ]) => { + this._log.info('deleteTable response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } - /** - * Lists all tables in the specified dataset. Requires the READER dataset - * role. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.projectId - * Required. Project ID of the tables to list - * @param {string} request.datasetId - * Required. Dataset ID of the tables to list - * @param {google.protobuf.UInt32Value| number } request.maxResults - * The maximum number of results to return in a single response page. - * Leverage the page tokens to iterate through the entire collection. - * @param {string} request.pageToken - * Page token, returned by a previous call, to request the next page of - * results - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.cloud.bigquery.v2.ListFormatTable|ListFormatTable}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `listTablesAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Lists all tables in the specified dataset. Requires the READER dataset + * role. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.projectId + * Required. Project ID of the tables to list + * @param {string} request.datasetId + * Required. Dataset ID of the tables to list + * @param {google.protobuf.UInt32Value| number } request.maxResults + * The maximum number of results to return in a single response page. + * Leverage the page tokens to iterate through the entire collection. + * @param {string} request.pageToken + * Page token, returned by a previous call, to request the next page of + * results + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.cloud.bigquery.v2.ListFormatTable|ListFormatTable}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listTablesAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listTables( - request?: protos.google.cloud.bigquery.v2.IListTablesRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.bigquery.v2.IListFormatTable[], - protos.google.cloud.bigquery.v2.IListTablesRequest|null, - protos.google.cloud.bigquery.v2.ITableList - ]>; + request?: protos.google.cloud.bigquery.v2.IListTablesRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.bigquery.v2.IListFormatTable[], + protos.google.cloud.bigquery.v2.IListTablesRequest | null, + protos.google.cloud.bigquery.v2.ITableList, + ] + >; listTables( - request: protos.google.cloud.bigquery.v2.IListTablesRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.cloud.bigquery.v2.IListTablesRequest, - protos.google.cloud.bigquery.v2.ITableList|null|undefined, - protos.google.cloud.bigquery.v2.IListFormatTable>): void; + request: protos.google.cloud.bigquery.v2.IListTablesRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.cloud.bigquery.v2.IListTablesRequest, + protos.google.cloud.bigquery.v2.ITableList | null | undefined, + protos.google.cloud.bigquery.v2.IListFormatTable + >, + ): void; listTables( - request: protos.google.cloud.bigquery.v2.IListTablesRequest, - callback: PaginationCallback< - protos.google.cloud.bigquery.v2.IListTablesRequest, - protos.google.cloud.bigquery.v2.ITableList|null|undefined, - protos.google.cloud.bigquery.v2.IListFormatTable>): void; + request: protos.google.cloud.bigquery.v2.IListTablesRequest, + callback: PaginationCallback< + protos.google.cloud.bigquery.v2.IListTablesRequest, + protos.google.cloud.bigquery.v2.ITableList | null | undefined, + protos.google.cloud.bigquery.v2.IListFormatTable + >, + ): void; listTables( - request?: protos.google.cloud.bigquery.v2.IListTablesRequest, - optionsOrCallback?: CallOptions|PaginationCallback< + request?: protos.google.cloud.bigquery.v2.IListTablesRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.cloud.bigquery.v2.IListTablesRequest, - protos.google.cloud.bigquery.v2.ITableList|null|undefined, - protos.google.cloud.bigquery.v2.IListFormatTable>, - callback?: PaginationCallback< - protos.google.cloud.bigquery.v2.IListTablesRequest, - protos.google.cloud.bigquery.v2.ITableList|null|undefined, - protos.google.cloud.bigquery.v2.IListFormatTable>): - Promise<[ - protos.google.cloud.bigquery.v2.IListFormatTable[], - protos.google.cloud.bigquery.v2.IListTablesRequest|null, - protos.google.cloud.bigquery.v2.ITableList - ]>|void { + protos.google.cloud.bigquery.v2.ITableList | null | undefined, + protos.google.cloud.bigquery.v2.IListFormatTable + >, + callback?: PaginationCallback< + protos.google.cloud.bigquery.v2.IListTablesRequest, + protos.google.cloud.bigquery.v2.ITableList | null | undefined, + protos.google.cloud.bigquery.v2.IListFormatTable + >, + ): Promise< + [ + protos.google.cloud.bigquery.v2.IListFormatTable[], + protos.google.cloud.bigquery.v2.IListTablesRequest | null, + protos.google.cloud.bigquery.v2.ITableList, + ] + > | void { request = request || {}; - // Converts number to Unit32 or Int32 value for non-compliant APIs. - if(request.maxResults && typeof request.maxResults === "number"){ - const maxResultsObject = {"value": request.maxResults} - request.maxResults = maxResultsObject - } + // Converts number to Unit32 or Int32 value for non-compliant APIs. + if (request.maxResults && typeof request.maxResults === 'number') { + const maxResultsObject = { value: request.maxResults }; + request.maxResults = maxResultsObject; + } let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'project_id': request.projectId?.toString() ?? '', - 'dataset_id': request.datasetId?.toString() ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + project_id: request.projectId?.toString() ?? '', + dataset_id: request.datasetId?.toString() ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.cloud.bigquery.v2.IListTablesRequest, - protos.google.cloud.bigquery.v2.ITableList|null|undefined, - protos.google.cloud.bigquery.v2.IListFormatTable>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.cloud.bigquery.v2.IListTablesRequest, + protos.google.cloud.bigquery.v2.ITableList | null | undefined, + protos.google.cloud.bigquery.v2.IListFormatTable + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listTables values %j', values); callback!(error, values, nextPageRequest, rawResponse); @@ -970,116 +1230,120 @@ export class TableServiceClient { this._log.info('listTables request %j', request); return this.innerApiCalls .listTables(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.cloud.bigquery.v2.IListFormatTable[], - protos.google.cloud.bigquery.v2.IListTablesRequest|null, - protos.google.cloud.bigquery.v2.ITableList - ]) => { - this._log.info('listTables values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.cloud.bigquery.v2.IListFormatTable[], + protos.google.cloud.bigquery.v2.IListTablesRequest | null, + protos.google.cloud.bigquery.v2.ITableList, + ]) => { + this._log.info('listTables values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listTables`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.projectId - * Required. Project ID of the tables to list - * @param {string} request.datasetId - * Required. Dataset ID of the tables to list - * @param {google.protobuf.UInt32Value} request.maxResults - * The maximum number of results to return in a single response page. - * Leverage the page tokens to iterate through the entire collection. - * @param {string} request.pageToken - * Page token, returned by a previous call, to request the next page of - * results - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.cloud.bigquery.v2.ListFormatTable|ListFormatTable} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `listTablesAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `listTables`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.projectId + * Required. Project ID of the tables to list + * @param {string} request.datasetId + * Required. Dataset ID of the tables to list + * @param {google.protobuf.UInt32Value} request.maxResults + * The maximum number of results to return in a single response page. + * Leverage the page tokens to iterate through the entire collection. + * @param {string} request.pageToken + * Page token, returned by a previous call, to request the next page of + * results + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.cloud.bigquery.v2.ListFormatTable|ListFormatTable} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listTablesAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listTablesStream( - request?: protos.google.cloud.bigquery.v2.IListTablesRequest, - options?: CallOptions): - Transform{ + request?: protos.google.cloud.bigquery.v2.IListTablesRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'project_id': request.projectId?.toString() ?? '', - 'dataset_id': request.datasetId?.toString() ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + project_id: request.projectId?.toString() ?? '', + dataset_id: request.datasetId?.toString() ?? '', + }); const defaultCallSettings = this._defaults['listTables']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listTables stream %j', request); return this.descriptors.page.listTables.createStream( this.innerApiCalls.listTables as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listTables`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.projectId - * Required. Project ID of the tables to list - * @param {string} request.datasetId - * Required. Dataset ID of the tables to list - * @param {google.protobuf.UInt32Value} request.maxResults - * The maximum number of results to return in a single response page. - * Leverage the page tokens to iterate through the entire collection. - * @param {string} request.pageToken - * Page token, returned by a previous call, to request the next page of - * results - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.cloud.bigquery.v2.ListFormatTable|ListFormatTable}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v2/table_service.list_tables.js - * region_tag:bigquery_v2_generated_TableService_ListTables_async - */ + /** + * Equivalent to `listTables`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.projectId + * Required. Project ID of the tables to list + * @param {string} request.datasetId + * Required. Dataset ID of the tables to list + * @param {google.protobuf.UInt32Value} request.maxResults + * The maximum number of results to return in a single response page. + * Leverage the page tokens to iterate through the entire collection. + * @param {string} request.pageToken + * Page token, returned by a previous call, to request the next page of + * results + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.cloud.bigquery.v2.ListFormatTable|ListFormatTable}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v2/table_service.list_tables.js + * region_tag:bigquery_v2_generated_TableService_ListTables_async + */ listTablesAsync( - request?: protos.google.cloud.bigquery.v2.IListTablesRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.cloud.bigquery.v2.IListTablesRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'project_id': request.projectId?.toString() ?? '', - 'dataset_id': request.datasetId?.toString() ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + project_id: request.projectId?.toString() ?? '', + dataset_id: request.datasetId?.toString() ?? '', + }); const defaultCallSettings = this._defaults['listTables']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listTables iterate %j', request); return this.descriptors.page.listTables.asyncIterate( this.innerApiCalls['listTables'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } @@ -1091,7 +1355,7 @@ export class TableServiceClient { */ close(): Promise { if (this.tableServiceStub && !this._terminated) { - return this.tableServiceStub.then(stub => { + return this.tableServiceStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -1099,4 +1363,4 @@ export class TableServiceClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/core/generator/gapic-generator-typescript/baselines/bigquery-v2-esm/esm/system-test/fixtures/sample/src/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/bigquery-v2-esm/esm/system-test/fixtures/sample/src/index.ts.baseline index 029845840670..4a5ed24bc5b8 100644 --- a/core/generator/gapic-generator-typescript/baselines/bigquery-v2-esm/esm/system-test/fixtures/sample/src/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/bigquery-v2-esm/esm/system-test/fixtures/sample/src/index.ts.baseline @@ -17,7 +17,15 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -import {DatasetServiceClient, JobServiceClient, ModelServiceClient, ProjectServiceClient, RoutineServiceClient, RowAccessPolicyServiceClient, TableServiceClient} from 'bigquery'; +import { + DatasetServiceClient, + JobServiceClient, + ModelServiceClient, + ProjectServiceClient, + RoutineServiceClient, + RowAccessPolicyServiceClient, + TableServiceClient, +} from 'bigquery'; // check that the client class type name can be used function doStuffWithDatasetServiceClient(client: DatasetServiceClient) { @@ -35,7 +43,9 @@ function doStuffWithProjectServiceClient(client: ProjectServiceClient) { function doStuffWithRoutineServiceClient(client: RoutineServiceClient) { client.close(); } -function doStuffWithRowAccessPolicyServiceClient(client: RowAccessPolicyServiceClient) { +function doStuffWithRowAccessPolicyServiceClient( + client: RowAccessPolicyServiceClient, +) { client.close(); } function doStuffWithTableServiceClient(client: TableServiceClient) { diff --git a/core/generator/gapic-generator-typescript/baselines/bigquery-v2-esm/esm/system-test/install.ts.baseline b/core/generator/gapic-generator-typescript/baselines/bigquery-v2-esm/esm/system-test/install.ts.baseline index e079c4fa1101..d109fdd8c97f 100644 --- a/core/generator/gapic-generator-typescript/baselines/bigquery-v2-esm/esm/system-test/install.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/bigquery-v2-esm/esm/system-test/install.ts.baseline @@ -16,40 +16,45 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -import {packNTest} from 'pack-n-play'; -import {readFileSync} from 'fs'; -import {describe, it} from 'mocha'; +import { packNTest } from 'pack-n-play'; +import { readFileSync } from 'fs'; +import { describe, it } from 'mocha'; describe('📦 pack-n-play test', () => { - it('TypeScript', async function() { + it('TypeScript', async function () { this.timeout(300000); await packNTest({ packageDir: process.cwd(), sample: { description: 'TypeScript user can use the type definitions', - ts: readFileSync('./esm/system-test/fixtures/sample/src/index.ts').toString() - } + ts: readFileSync( + './esm/system-test/fixtures/sample/src/index.ts', + ).toString(), + }, }); }); - it('ESM module', async function() { + it('ESM module', async function () { this.timeout(300000); await packNTest({ sample: { description: 'Should be able to import using ESM', - esm: readFileSync('./esm/system-test/fixtures/sample/src/index.js').toString(), + esm: readFileSync( + './esm/system-test/fixtures/sample/src/index.js', + ).toString(), }, }); }); - it('CJS module', async function() { + it('CJS module', async function () { this.timeout(300000); await packNTest({ sample: { description: 'Should be able to import using CJS', - cjs: readFileSync('./esm/system-test/fixtures/sample/src/index.cjs').toString(), + cjs: readFileSync( + './esm/system-test/fixtures/sample/src/index.cjs', + ).toString(), }, }); }); - }); diff --git a/core/generator/gapic-generator-typescript/baselines/bigquery-v2-esm/esm/test/gapic_dataset_service_v2.ts.baseline b/core/generator/gapic-generator-typescript/baselines/bigquery-v2-esm/esm/test/gapic_dataset_service_v2.ts.baseline index acb509629be1..da41422ffcf7 100644 --- a/core/generator/gapic-generator-typescript/baselines/bigquery-v2-esm/esm/test/gapic_dataset_service_v2.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/bigquery-v2-esm/esm/test/gapic_dataset_service_v2.ts.baseline @@ -20,16 +20,16 @@ import * as protos from '../../protos/protos.js'; import assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as datasetserviceModule from '../src/index.js'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; -import {protobuf} from 'google-gax'; +import { protobuf } from 'google-gax'; import fs from 'fs'; import path from 'path'; -import {fileURLToPath} from 'url'; +import { fileURLToPath } from 'url'; // @ts-ignore const dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -37,1187 +37,1519 @@ const dirname = path.dirname(fileURLToPath(import.meta.url)); // to fill in default values for request objects const root = protobuf.Root.fromJSON( JSON.parse( - fs.readFileSync(path.join(dirname, '..', '..', 'protos/protos.json'), 'utf8') - )) + fs.readFileSync( + path.join(dirname, '..', '..', 'protos/protos.json'), + 'utf8', + ), + ), +); // eslint-disable-next-line @typescript-eslint/no-unused-vars function getTypeDefaultValue(typeName: string, fields: string[]) { - let type = root.lookupType(typeName) as protobuf.Type; - for (const field of fields.slice(0, -1)) { - type = type?.fields[field]?.resolvedType as protobuf.Type; - } - return type?.fields[fields[fields.length - 1]]?.defaultValue ?? null; + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type?.fields[field]?.resolvedType as protobuf.Type; + } + return type?.fields[fields[fields.length - 1]]?.defaultValue ?? null; } function generateSampleMessage(instance: T) { - const filledObject = (instance.constructor as typeof protobuf.Message) - .toObject(instance as protobuf.Message, {defaults: true}); - return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, { defaults: true }); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; } function stubSimpleCall(response?: ResponseType, error?: Error) { - return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); } -function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { - return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +function stubSimpleCallWithCallback( + response?: ResponseType, + error?: Error, +) { + return error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); } -function stubPageStreamingCall(responses?: ResponseType[], error?: Error) { - const pagingStub = sinon.stub(); - if (responses) { - for (let i = 0; i < responses.length; ++i) { - pagingStub.onCall(i).callsArgWith(2, null, responses[i]); - } +function stubPageStreamingCall( + responses?: ResponseType[], + error?: Error, +) { + const pagingStub = sinon.stub(); + if (responses) { + for (let i = 0; i < responses.length; ++i) { + pagingStub.onCall(i).callsArgWith(2, null, responses[i]); } - const transformStub = error ? sinon.stub().callsArgWith(2, error) : pagingStub; - const mockStream = new PassThrough({ - objectMode: true, - transform: transformStub, - }); - // trigger as many responses as needed - if (responses) { - for (let i = 0; i < responses.length; ++i) { - setImmediate(() => { mockStream.write({}); }); - } - setImmediate(() => { mockStream.end(); }); - } else { - setImmediate(() => { mockStream.write({}); }); - setImmediate(() => { mockStream.end(); }); + } + const transformStub = error + ? sinon.stub().callsArgWith(2, error) + : pagingStub; + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + // trigger as many responses as needed + if (responses) { + for (let i = 0; i < responses.length; ++i) { + setImmediate(() => { + mockStream.write({}); + }); } - return sinon.stub().returns(mockStream); + setImmediate(() => { + mockStream.end(); + }); + } else { + setImmediate(() => { + mockStream.write({}); + }); + setImmediate(() => { + mockStream.end(); + }); + } + return sinon.stub().returns(mockStream); } -function stubAsyncIterationCall(responses?: ResponseType[], error?: Error) { - let counter = 0; - const asyncIterable = { - [Symbol.asyncIterator]() { - return { - async next() { - if (error) { - return Promise.reject(error); - } - if (counter >= responses!.length) { - return Promise.resolve({done: true, value: undefined}); - } - return Promise.resolve({done: false, value: responses![counter++]}); - } - }; - } - }; - return sinon.stub().returns(asyncIterable); +function stubAsyncIterationCall( + responses?: ResponseType[], + error?: Error, +) { + let counter = 0; + const asyncIterable = { + [Symbol.asyncIterator]() { + return { + async next() { + if (error) { + return Promise.reject(error); + } + if (counter >= responses!.length) { + return Promise.resolve({ done: true, value: undefined }); + } + return Promise.resolve({ done: false, value: responses![counter++] }); + }, + }; + }, + }; + return sinon.stub().returns(asyncIterable); } describe('v2.DatasetServiceClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new datasetserviceModule.v2.DatasetServiceClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'bigquery.googleapis.com'); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new datasetserviceModule.v2.DatasetServiceClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'bigquery.googleapis.com'); + }); - it('has universeDomain', () => { - const client = new datasetserviceModule.v2.DatasetServiceClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); + it('has universeDomain', () => { + const client = new datasetserviceModule.v2.DatasetServiceClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - it('throws DeprecationWarning if static servicePath is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const servicePath = datasetserviceModule.v2.DatasetServiceClient.servicePath; - assert.strictEqual(servicePath, 'bigquery.googleapis.com'); - assert(stub.called); - stub.restore(); - }); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = + datasetserviceModule.v2.DatasetServiceClient.servicePath; + assert.strictEqual(servicePath, 'bigquery.googleapis.com'); + assert(stub.called); + stub.restore(); + }); - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = datasetserviceModule.v2.DatasetServiceClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'bigquery.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new datasetserviceModule.v2.DatasetServiceClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'bigquery.example.com'); + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + datasetserviceModule.v2.DatasetServiceClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'bigquery.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = new datasetserviceModule.v2.DatasetServiceClient({ + universeDomain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'bigquery.example.com'); + }); + + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = new datasetserviceModule.v2.DatasetServiceClient({ + universe_domain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'bigquery.example.com'); + }); + + if (typeof process === 'object' && 'env' in process) { + describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { + it('sets apiEndpoint from environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new datasetserviceModule.v2.DatasetServiceClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'bigquery.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new datasetserviceModule.v2.DatasetServiceClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'bigquery.example.com'); + it('value configured in code has priority over environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new datasetserviceModule.v2.DatasetServiceClient({ + universeDomain: 'configured.example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'bigquery.configured.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } + }); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new datasetserviceModule.v2.DatasetServiceClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); + }); - if (typeof process === 'object' && 'env' in process) { - describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { - it('sets apiEndpoint from environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new datasetserviceModule.v2.DatasetServiceClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'bigquery.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); + it('has port', () => { + const port = datasetserviceModule.v2.DatasetServiceClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('value configured in code has priority over environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new datasetserviceModule.v2.DatasetServiceClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'bigquery.configured.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { new datasetserviceModule.v2.DatasetServiceClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); + it('should create a client with no option', () => { + const client = new datasetserviceModule.v2.DatasetServiceClient(); + assert(client); + }); - it('has port', () => { - const port = datasetserviceModule.v2.DatasetServiceClient.port; - assert(port); - assert(typeof port === 'number'); - }); + it('should create a client with gRPC fallback', () => { + const client = new datasetserviceModule.v2.DatasetServiceClient({ + fallback: true, + }); + assert(client); + }); - it('should create a client with no option', () => { - const client = new datasetserviceModule.v2.DatasetServiceClient(); - assert(client); - }); + it('has initialize method and supports deferred initialization', async () => { + const client = new datasetserviceModule.v2.DatasetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.datasetServiceStub, undefined); + await client.initialize(); + assert(client.datasetServiceStub); + }); - it('should create a client with gRPC fallback', () => { - const client = new datasetserviceModule.v2.DatasetServiceClient({ - fallback: true, - }); - assert(client); + it('has close method for the initialized client', (done) => { + const client = new datasetserviceModule.v2.DatasetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.datasetServiceStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('has initialize method and supports deferred initialization', async () => { - const client = new datasetserviceModule.v2.DatasetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.datasetServiceStub, undefined); - await client.initialize(); - assert(client.datasetServiceStub); + it('has close method for the non-initialized client', (done) => { + const client = new datasetserviceModule.v2.DatasetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.datasetServiceStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('has close method for the initialized client', done => { - const client = new datasetserviceModule.v2.DatasetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.datasetServiceStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new datasetserviceModule.v2.DatasetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + }); - it('has close method for the non-initialized client', done => { - const client = new datasetserviceModule.v2.DatasetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.datasetServiceStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new datasetserviceModule.v2.DatasetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new datasetserviceModule.v2.DatasetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); - }); + describe('getDataset', () => { + it('invokes getDataset without error', async () => { + const client = new datasetserviceModule.v2.DatasetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.GetDatasetRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetDatasetRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetDatasetRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.bigquery.v2.Dataset(), + ); + client.innerApiCalls.getDataset = stubSimpleCall(expectedResponse); + const [response] = await client.getDataset(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getDataset as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getDataset as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new datasetserviceModule.v2.DatasetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId((err?: Error|null, projectId?: string|null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } - }); - }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); - }); + it('invokes getDataset without error using callback', async () => { + const client = new datasetserviceModule.v2.DatasetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.GetDatasetRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetDatasetRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetDatasetRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.bigquery.v2.Dataset(), + ); + client.innerApiCalls.getDataset = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getDataset( + request, + ( + err?: Error | null, + result?: protos.google.cloud.bigquery.v2.IDataset | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getDataset as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getDataset as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('getDataset', () => { - it('invokes getDataset without error', async () => { - const client = new datasetserviceModule.v2.DatasetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.GetDatasetRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetDatasetRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetDatasetRequest', ['datasetId']); - request.datasetId = defaultValue2; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.bigquery.v2.Dataset() - ); - client.innerApiCalls.getDataset = stubSimpleCall(expectedResponse); - const [response] = await client.getDataset(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getDataset as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getDataset as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getDataset with error', async () => { + const client = new datasetserviceModule.v2.DatasetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.GetDatasetRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetDatasetRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetDatasetRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getDataset = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getDataset(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getDataset as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getDataset as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getDataset without error using callback', async () => { - const client = new datasetserviceModule.v2.DatasetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.GetDatasetRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetDatasetRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetDatasetRequest', ['datasetId']); - request.datasetId = defaultValue2; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.bigquery.v2.Dataset() - ); - client.innerApiCalls.getDataset = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getDataset( - request, - (err?: Error|null, result?: protos.google.cloud.bigquery.v2.IDataset|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getDataset as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getDataset as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getDataset with closed client', async () => { + const client = new datasetserviceModule.v2.DatasetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.GetDatasetRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetDatasetRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetDatasetRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getDataset(request), expectedError); + }); + }); - it('invokes getDataset with error', async () => { - const client = new datasetserviceModule.v2.DatasetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.GetDatasetRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetDatasetRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetDatasetRequest', ['datasetId']); - request.datasetId = defaultValue2; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getDataset = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getDataset(request), expectedError); - const actualRequest = (client.innerApiCalls.getDataset as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getDataset as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + describe('insertDataset', () => { + it('invokes insertDataset without error', async () => { + const client = new datasetserviceModule.v2.DatasetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.InsertDatasetRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.InsertDatasetRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.bigquery.v2.Dataset(), + ); + client.innerApiCalls.insertDataset = stubSimpleCall(expectedResponse); + const [response] = await client.insertDataset(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.insertDataset as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.insertDataset as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getDataset with closed client', async () => { - const client = new datasetserviceModule.v2.DatasetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.GetDatasetRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetDatasetRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetDatasetRequest', ['datasetId']); - request.datasetId = defaultValue2; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getDataset(request), expectedError); - }); + it('invokes insertDataset without error using callback', async () => { + const client = new datasetserviceModule.v2.DatasetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.InsertDatasetRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.InsertDatasetRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.bigquery.v2.Dataset(), + ); + client.innerApiCalls.insertDataset = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.insertDataset( + request, + ( + err?: Error | null, + result?: protos.google.cloud.bigquery.v2.IDataset | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.insertDataset as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.insertDataset as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('insertDataset', () => { - it('invokes insertDataset without error', async () => { - const client = new datasetserviceModule.v2.DatasetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.InsertDatasetRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.InsertDatasetRequest', ['projectId']); - request.projectId = defaultValue1; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.bigquery.v2.Dataset() - ); - client.innerApiCalls.insertDataset = stubSimpleCall(expectedResponse); - const [response] = await client.insertDataset(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.insertDataset as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.insertDataset as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes insertDataset with error', async () => { + const client = new datasetserviceModule.v2.DatasetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.InsertDatasetRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.InsertDatasetRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.insertDataset = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.insertDataset(request), expectedError); + const actualRequest = ( + client.innerApiCalls.insertDataset as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.insertDataset as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes insertDataset without error using callback', async () => { - const client = new datasetserviceModule.v2.DatasetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.InsertDatasetRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.InsertDatasetRequest', ['projectId']); - request.projectId = defaultValue1; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.bigquery.v2.Dataset() - ); - client.innerApiCalls.insertDataset = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.insertDataset( - request, - (err?: Error|null, result?: protos.google.cloud.bigquery.v2.IDataset|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.insertDataset as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.insertDataset as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes insertDataset with closed client', async () => { + const client = new datasetserviceModule.v2.DatasetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.InsertDatasetRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.InsertDatasetRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.insertDataset(request), expectedError); + }); + }); - it('invokes insertDataset with error', async () => { - const client = new datasetserviceModule.v2.DatasetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.InsertDatasetRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.InsertDatasetRequest', ['projectId']); - request.projectId = defaultValue1; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.insertDataset = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.insertDataset(request), expectedError); - const actualRequest = (client.innerApiCalls.insertDataset as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.insertDataset as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + describe('patchDataset', () => { + it('invokes patchDataset without error', async () => { + const client = new datasetserviceModule.v2.DatasetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.UpdateOrPatchDatasetRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.UpdateOrPatchDatasetRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.UpdateOrPatchDatasetRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.bigquery.v2.Dataset(), + ); + client.innerApiCalls.patchDataset = stubSimpleCall(expectedResponse); + const [response] = await client.patchDataset(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.patchDataset as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.patchDataset as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes insertDataset with closed client', async () => { - const client = new datasetserviceModule.v2.DatasetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.InsertDatasetRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.InsertDatasetRequest', ['projectId']); - request.projectId = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.insertDataset(request), expectedError); - }); + it('invokes patchDataset without error using callback', async () => { + const client = new datasetserviceModule.v2.DatasetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.UpdateOrPatchDatasetRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.UpdateOrPatchDatasetRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.UpdateOrPatchDatasetRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.bigquery.v2.Dataset(), + ); + client.innerApiCalls.patchDataset = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.patchDataset( + request, + ( + err?: Error | null, + result?: protos.google.cloud.bigquery.v2.IDataset | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.patchDataset as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.patchDataset as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('patchDataset', () => { - it('invokes patchDataset without error', async () => { - const client = new datasetserviceModule.v2.DatasetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.UpdateOrPatchDatasetRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.UpdateOrPatchDatasetRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.UpdateOrPatchDatasetRequest', ['datasetId']); - request.datasetId = defaultValue2; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.bigquery.v2.Dataset() - ); - client.innerApiCalls.patchDataset = stubSimpleCall(expectedResponse); - const [response] = await client.patchDataset(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.patchDataset as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.patchDataset as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes patchDataset with error', async () => { + const client = new datasetserviceModule.v2.DatasetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.UpdateOrPatchDatasetRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.UpdateOrPatchDatasetRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.UpdateOrPatchDatasetRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.patchDataset = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.patchDataset(request), expectedError); + const actualRequest = ( + client.innerApiCalls.patchDataset as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.patchDataset as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes patchDataset without error using callback', async () => { - const client = new datasetserviceModule.v2.DatasetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.UpdateOrPatchDatasetRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.UpdateOrPatchDatasetRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.UpdateOrPatchDatasetRequest', ['datasetId']); - request.datasetId = defaultValue2; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.bigquery.v2.Dataset() - ); - client.innerApiCalls.patchDataset = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.patchDataset( - request, - (err?: Error|null, result?: protos.google.cloud.bigquery.v2.IDataset|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.patchDataset as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.patchDataset as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes patchDataset with closed client', async () => { + const client = new datasetserviceModule.v2.DatasetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.UpdateOrPatchDatasetRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.UpdateOrPatchDatasetRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.UpdateOrPatchDatasetRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.patchDataset(request), expectedError); + }); + }); - it('invokes patchDataset with error', async () => { - const client = new datasetserviceModule.v2.DatasetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.UpdateOrPatchDatasetRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.UpdateOrPatchDatasetRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.UpdateOrPatchDatasetRequest', ['datasetId']); - request.datasetId = defaultValue2; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.patchDataset = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.patchDataset(request), expectedError); - const actualRequest = (client.innerApiCalls.patchDataset as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.patchDataset as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + describe('updateDataset', () => { + it('invokes updateDataset without error', async () => { + const client = new datasetserviceModule.v2.DatasetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.UpdateOrPatchDatasetRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.UpdateOrPatchDatasetRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.UpdateOrPatchDatasetRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.bigquery.v2.Dataset(), + ); + client.innerApiCalls.updateDataset = stubSimpleCall(expectedResponse); + const [response] = await client.updateDataset(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateDataset as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateDataset as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes patchDataset with closed client', async () => { - const client = new datasetserviceModule.v2.DatasetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.UpdateOrPatchDatasetRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.UpdateOrPatchDatasetRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.UpdateOrPatchDatasetRequest', ['datasetId']); - request.datasetId = defaultValue2; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.patchDataset(request), expectedError); - }); + it('invokes updateDataset without error using callback', async () => { + const client = new datasetserviceModule.v2.DatasetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.UpdateOrPatchDatasetRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.UpdateOrPatchDatasetRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.UpdateOrPatchDatasetRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.bigquery.v2.Dataset(), + ); + client.innerApiCalls.updateDataset = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateDataset( + request, + ( + err?: Error | null, + result?: protos.google.cloud.bigquery.v2.IDataset | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateDataset as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateDataset as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('updateDataset', () => { - it('invokes updateDataset without error', async () => { - const client = new datasetserviceModule.v2.DatasetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.UpdateOrPatchDatasetRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.UpdateOrPatchDatasetRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.UpdateOrPatchDatasetRequest', ['datasetId']); - request.datasetId = defaultValue2; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.bigquery.v2.Dataset() - ); - client.innerApiCalls.updateDataset = stubSimpleCall(expectedResponse); - const [response] = await client.updateDataset(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateDataset as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateDataset as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateDataset with error', async () => { + const client = new datasetserviceModule.v2.DatasetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.UpdateOrPatchDatasetRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.UpdateOrPatchDatasetRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.UpdateOrPatchDatasetRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateDataset = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.updateDataset(request), expectedError); + const actualRequest = ( + client.innerApiCalls.updateDataset as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateDataset as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateDataset without error using callback', async () => { - const client = new datasetserviceModule.v2.DatasetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.UpdateOrPatchDatasetRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.UpdateOrPatchDatasetRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.UpdateOrPatchDatasetRequest', ['datasetId']); - request.datasetId = defaultValue2; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.bigquery.v2.Dataset() - ); - client.innerApiCalls.updateDataset = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateDataset( - request, - (err?: Error|null, result?: protos.google.cloud.bigquery.v2.IDataset|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateDataset as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateDataset as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateDataset with closed client', async () => { + const client = new datasetserviceModule.v2.DatasetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.UpdateOrPatchDatasetRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.UpdateOrPatchDatasetRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.UpdateOrPatchDatasetRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.updateDataset(request), expectedError); + }); + }); - it('invokes updateDataset with error', async () => { - const client = new datasetserviceModule.v2.DatasetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.UpdateOrPatchDatasetRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.UpdateOrPatchDatasetRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.UpdateOrPatchDatasetRequest', ['datasetId']); - request.datasetId = defaultValue2; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateDataset = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateDataset(request), expectedError); - const actualRequest = (client.innerApiCalls.updateDataset as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateDataset as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + describe('deleteDataset', () => { + it('invokes deleteDataset without error', async () => { + const client = new datasetserviceModule.v2.DatasetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.DeleteDatasetRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.DeleteDatasetRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.DeleteDatasetRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteDataset = stubSimpleCall(expectedResponse); + const [response] = await client.deleteDataset(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteDataset as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteDataset as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateDataset with closed client', async () => { - const client = new datasetserviceModule.v2.DatasetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.UpdateOrPatchDatasetRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.UpdateOrPatchDatasetRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.UpdateOrPatchDatasetRequest', ['datasetId']); - request.datasetId = defaultValue2; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateDataset(request), expectedError); - }); + it('invokes deleteDataset without error using callback', async () => { + const client = new datasetserviceModule.v2.DatasetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.DeleteDatasetRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.DeleteDatasetRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.DeleteDatasetRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteDataset = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteDataset( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteDataset as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteDataset as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('deleteDataset', () => { - it('invokes deleteDataset without error', async () => { - const client = new datasetserviceModule.v2.DatasetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.DeleteDatasetRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.DeleteDatasetRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.DeleteDatasetRequest', ['datasetId']); - request.datasetId = defaultValue2; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteDataset = stubSimpleCall(expectedResponse); - const [response] = await client.deleteDataset(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteDataset as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteDataset as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteDataset with error', async () => { + const client = new datasetserviceModule.v2.DatasetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.DeleteDatasetRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.DeleteDatasetRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.DeleteDatasetRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteDataset = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.deleteDataset(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteDataset as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteDataset as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteDataset without error using callback', async () => { - const client = new datasetserviceModule.v2.DatasetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.DeleteDatasetRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.DeleteDatasetRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.DeleteDatasetRequest', ['datasetId']); - request.datasetId = defaultValue2; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteDataset = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteDataset( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteDataset as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteDataset as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteDataset with closed client', async () => { + const client = new datasetserviceModule.v2.DatasetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.DeleteDatasetRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.DeleteDatasetRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.DeleteDatasetRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.deleteDataset(request), expectedError); + }); + }); - it('invokes deleteDataset with error', async () => { - const client = new datasetserviceModule.v2.DatasetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.DeleteDatasetRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.DeleteDatasetRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.DeleteDatasetRequest', ['datasetId']); - request.datasetId = defaultValue2; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteDataset = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteDataset(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteDataset as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteDataset as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + describe('undeleteDataset', () => { + it('invokes undeleteDataset without error', async () => { + const client = new datasetserviceModule.v2.DatasetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.UndeleteDatasetRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.UndeleteDatasetRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.UndeleteDatasetRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.bigquery.v2.Dataset(), + ); + client.innerApiCalls.undeleteDataset = stubSimpleCall(expectedResponse); + const [response] = await client.undeleteDataset(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.undeleteDataset as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.undeleteDataset as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteDataset with closed client', async () => { - const client = new datasetserviceModule.v2.DatasetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.DeleteDatasetRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.DeleteDatasetRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.DeleteDatasetRequest', ['datasetId']); - request.datasetId = defaultValue2; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteDataset(request), expectedError); - }); + it('invokes undeleteDataset without error using callback', async () => { + const client = new datasetserviceModule.v2.DatasetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.UndeleteDatasetRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.UndeleteDatasetRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.UndeleteDatasetRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.bigquery.v2.Dataset(), + ); + client.innerApiCalls.undeleteDataset = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.undeleteDataset( + request, + ( + err?: Error | null, + result?: protos.google.cloud.bigquery.v2.IDataset | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.undeleteDataset as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.undeleteDataset as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('undeleteDataset', () => { - it('invokes undeleteDataset without error', async () => { - const client = new datasetserviceModule.v2.DatasetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.UndeleteDatasetRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.UndeleteDatasetRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.UndeleteDatasetRequest', ['datasetId']); - request.datasetId = defaultValue2; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.bigquery.v2.Dataset() - ); - client.innerApiCalls.undeleteDataset = stubSimpleCall(expectedResponse); - const [response] = await client.undeleteDataset(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.undeleteDataset as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.undeleteDataset as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes undeleteDataset with error', async () => { + const client = new datasetserviceModule.v2.DatasetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.UndeleteDatasetRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.UndeleteDatasetRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.UndeleteDatasetRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.undeleteDataset = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.undeleteDataset(request), expectedError); + const actualRequest = ( + client.innerApiCalls.undeleteDataset as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.undeleteDataset as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes undeleteDataset without error using callback', async () => { - const client = new datasetserviceModule.v2.DatasetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.UndeleteDatasetRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.UndeleteDatasetRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.UndeleteDatasetRequest', ['datasetId']); - request.datasetId = defaultValue2; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.bigquery.v2.Dataset() - ); - client.innerApiCalls.undeleteDataset = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.undeleteDataset( - request, - (err?: Error|null, result?: protos.google.cloud.bigquery.v2.IDataset|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.undeleteDataset as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.undeleteDataset as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes undeleteDataset with closed client', async () => { + const client = new datasetserviceModule.v2.DatasetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.UndeleteDatasetRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.UndeleteDatasetRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.UndeleteDatasetRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.undeleteDataset(request), expectedError); + }); + }); - it('invokes undeleteDataset with error', async () => { - const client = new datasetserviceModule.v2.DatasetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.UndeleteDatasetRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.UndeleteDatasetRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.UndeleteDatasetRequest', ['datasetId']); - request.datasetId = defaultValue2; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.undeleteDataset = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.undeleteDataset(request), expectedError); - const actualRequest = (client.innerApiCalls.undeleteDataset as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.undeleteDataset as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + describe('listDatasets', () => { + it('invokes listDatasets without error', async () => { + const client = new datasetserviceModule.v2.DatasetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListDatasetsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListDatasetsRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListFormatDataset(), + ), + generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListFormatDataset(), + ), + generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListFormatDataset(), + ), + ]; + client.innerApiCalls.listDatasets = stubSimpleCall(expectedResponse); + const [response] = await client.listDatasets(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listDatasets as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listDatasets as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes undeleteDataset with closed client', async () => { - const client = new datasetserviceModule.v2.DatasetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.UndeleteDatasetRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.UndeleteDatasetRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.UndeleteDatasetRequest', ['datasetId']); - request.datasetId = defaultValue2; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.undeleteDataset(request), expectedError); - }); + it('invokes listDatasets without error using callback', async () => { + const client = new datasetserviceModule.v2.DatasetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListDatasetsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListDatasetsRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListFormatDataset(), + ), + generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListFormatDataset(), + ), + generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListFormatDataset(), + ), + ]; + client.innerApiCalls.listDatasets = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listDatasets( + request, + ( + err?: Error | null, + result?: + | protos.google.cloud.bigquery.v2.IListFormatDataset[] + | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listDatasets as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listDatasets as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('listDatasets', () => { - it('invokes listDatasets without error', async () => { - const client = new datasetserviceModule.v2.DatasetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.ListDatasetsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListDatasetsRequest', ['projectId']); - request.projectId = defaultValue1; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.bigquery.v2.ListFormatDataset()), - generateSampleMessage(new protos.google.cloud.bigquery.v2.ListFormatDataset()), - generateSampleMessage(new protos.google.cloud.bigquery.v2.ListFormatDataset()), - ]; - client.innerApiCalls.listDatasets = stubSimpleCall(expectedResponse); - const [response] = await client.listDatasets(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listDatasets as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listDatasets as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listDatasets with error', async () => { + const client = new datasetserviceModule.v2.DatasetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListDatasetsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListDatasetsRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listDatasets = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listDatasets(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listDatasets as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listDatasets as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listDatasets without error using callback', async () => { - const client = new datasetserviceModule.v2.DatasetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.ListDatasetsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListDatasetsRequest', ['projectId']); - request.projectId = defaultValue1; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.bigquery.v2.ListFormatDataset()), - generateSampleMessage(new protos.google.cloud.bigquery.v2.ListFormatDataset()), - generateSampleMessage(new protos.google.cloud.bigquery.v2.ListFormatDataset()), - ]; - client.innerApiCalls.listDatasets = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listDatasets( - request, - (err?: Error|null, result?: protos.google.cloud.bigquery.v2.IListFormatDataset[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listDatasets as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listDatasets as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes listDatasetsStream without error', async () => { + const client = new datasetserviceModule.v2.DatasetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListDatasetsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListDatasetsRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListFormatDataset(), + ), + generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListFormatDataset(), + ), + generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListFormatDataset(), + ), + ]; + client.descriptors.page.listDatasets.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listDatasetsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.cloud.bigquery.v2.ListFormatDataset[] = + []; + stream.on( + 'data', + (response: protos.google.cloud.bigquery.v2.ListFormatDataset) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); }); - - it('invokes listDatasets with error', async () => { - const client = new datasetserviceModule.v2.DatasetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.ListDatasetsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListDatasetsRequest', ['projectId']); - request.projectId = defaultValue1; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listDatasets = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listDatasets(request), expectedError); - const actualRequest = (client.innerApiCalls.listDatasets as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listDatasets as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + stream.on('error', (err: Error) => { + reject(err); }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listDatasets.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listDatasets, request), + ); + assert( + (client.descriptors.page.listDatasets.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('invokes listDatasetsStream without error', async () => { - const client = new datasetserviceModule.v2.DatasetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.ListDatasetsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListDatasetsRequest', ['projectId']); - request.projectId = defaultValue1; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.bigquery.v2.ListFormatDataset()), - generateSampleMessage(new protos.google.cloud.bigquery.v2.ListFormatDataset()), - generateSampleMessage(new protos.google.cloud.bigquery.v2.ListFormatDataset()), - ]; - client.descriptors.page.listDatasets.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listDatasetsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.cloud.bigquery.v2.ListFormatDataset[] = []; - stream.on('data', (response: protos.google.cloud.bigquery.v2.ListFormatDataset) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.listDatasets.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listDatasets, request)); - assert( - (client.descriptors.page.listDatasets.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); + it('invokes listDatasetsStream with error', async () => { + const client = new datasetserviceModule.v2.DatasetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListDatasetsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListDatasetsRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listDatasets.createStream = stubPageStreamingCall( + undefined, + expectedError, + ); + const stream = client.listDatasetsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.cloud.bigquery.v2.ListFormatDataset[] = + []; + stream.on( + 'data', + (response: protos.google.cloud.bigquery.v2.ListFormatDataset) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); }); - - it('invokes listDatasetsStream with error', async () => { - const client = new datasetserviceModule.v2.DatasetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.ListDatasetsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListDatasetsRequest', ['projectId']); - request.projectId = defaultValue1; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listDatasets.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listDatasetsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.cloud.bigquery.v2.ListFormatDataset[] = []; - stream.on('data', (response: protos.google.cloud.bigquery.v2.ListFormatDataset) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listDatasets.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listDatasets, request)); - assert( - (client.descriptors.page.listDatasets.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); + stream.on('error', (err: Error) => { + reject(err); }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listDatasets.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listDatasets, request), + ); + assert( + (client.descriptors.page.listDatasets.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('uses async iteration with listDatasets without error', async () => { - const client = new datasetserviceModule.v2.DatasetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.ListDatasetsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListDatasetsRequest', ['projectId']); - request.projectId = defaultValue1; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.bigquery.v2.ListFormatDataset()), - generateSampleMessage(new protos.google.cloud.bigquery.v2.ListFormatDataset()), - generateSampleMessage(new protos.google.cloud.bigquery.v2.ListFormatDataset()), - ]; - client.descriptors.page.listDatasets.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.cloud.bigquery.v2.IListFormatDataset[] = []; - const iterable = client.listDatasetsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listDatasets.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listDatasets.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listDatasets without error', async () => { + const client = new datasetserviceModule.v2.DatasetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListDatasetsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListDatasetsRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListFormatDataset(), + ), + generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListFormatDataset(), + ), + generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListFormatDataset(), + ), + ]; + client.descriptors.page.listDatasets.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.cloud.bigquery.v2.IListFormatDataset[] = + []; + const iterable = client.listDatasetsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listDatasets.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listDatasets.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('uses async iteration with listDatasets with error', async () => { - const client = new datasetserviceModule.v2.DatasetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.ListDatasetsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListDatasetsRequest', ['projectId']); - request.projectId = defaultValue1; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listDatasets.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listDatasetsAsync(request); - await assert.rejects(async () => { - const responses: protos.google.cloud.bigquery.v2.IListFormatDataset[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listDatasets.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listDatasets.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listDatasets with error', async () => { + const client = new datasetserviceModule.v2.DatasetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListDatasetsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListDatasetsRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listDatasets.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listDatasetsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.cloud.bigquery.v2.IListFormatDataset[] = + []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listDatasets.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listDatasets.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); }); + }); }); diff --git a/core/generator/gapic-generator-typescript/baselines/bigquery-v2-esm/esm/test/gapic_job_service_v2.ts.baseline b/core/generator/gapic-generator-typescript/baselines/bigquery-v2-esm/esm/test/gapic_job_service_v2.ts.baseline index 73f32ed3eed7..4fe0e0cea3fd 100644 --- a/core/generator/gapic-generator-typescript/baselines/bigquery-v2-esm/esm/test/gapic_job_service_v2.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/bigquery-v2-esm/esm/test/gapic_job_service_v2.ts.baseline @@ -20,16 +20,16 @@ import * as protos from '../../protos/protos.js'; import assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as jobserviceModule from '../src/index.js'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; -import {protobuf} from 'google-gax'; +import { protobuf } from 'google-gax'; import fs from 'fs'; import path from 'path'; -import {fileURLToPath} from 'url'; +import { fileURLToPath } from 'url'; // @ts-ignore const dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -37,1175 +37,1469 @@ const dirname = path.dirname(fileURLToPath(import.meta.url)); // to fill in default values for request objects const root = protobuf.Root.fromJSON( JSON.parse( - fs.readFileSync(path.join(dirname, '..', '..', 'protos/protos.json'), 'utf8') - )) + fs.readFileSync( + path.join(dirname, '..', '..', 'protos/protos.json'), + 'utf8', + ), + ), +); // eslint-disable-next-line @typescript-eslint/no-unused-vars function getTypeDefaultValue(typeName: string, fields: string[]) { - let type = root.lookupType(typeName) as protobuf.Type; - for (const field of fields.slice(0, -1)) { - type = type?.fields[field]?.resolvedType as protobuf.Type; - } - return type?.fields[fields[fields.length - 1]]?.defaultValue ?? null; + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type?.fields[field]?.resolvedType as protobuf.Type; + } + return type?.fields[fields[fields.length - 1]]?.defaultValue ?? null; } function generateSampleMessage(instance: T) { - const filledObject = (instance.constructor as typeof protobuf.Message) - .toObject(instance as protobuf.Message, {defaults: true}); - return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, { defaults: true }); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; } function stubSimpleCall(response?: ResponseType, error?: Error) { - return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); } -function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { - return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +function stubSimpleCallWithCallback( + response?: ResponseType, + error?: Error, +) { + return error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); } -function stubPageStreamingCall(responses?: ResponseType[], error?: Error) { - const pagingStub = sinon.stub(); - if (responses) { - for (let i = 0; i < responses.length; ++i) { - pagingStub.onCall(i).callsArgWith(2, null, responses[i]); - } +function stubPageStreamingCall( + responses?: ResponseType[], + error?: Error, +) { + const pagingStub = sinon.stub(); + if (responses) { + for (let i = 0; i < responses.length; ++i) { + pagingStub.onCall(i).callsArgWith(2, null, responses[i]); } - const transformStub = error ? sinon.stub().callsArgWith(2, error) : pagingStub; - const mockStream = new PassThrough({ - objectMode: true, - transform: transformStub, - }); - // trigger as many responses as needed - if (responses) { - for (let i = 0; i < responses.length; ++i) { - setImmediate(() => { mockStream.write({}); }); - } - setImmediate(() => { mockStream.end(); }); - } else { - setImmediate(() => { mockStream.write({}); }); - setImmediate(() => { mockStream.end(); }); + } + const transformStub = error + ? sinon.stub().callsArgWith(2, error) + : pagingStub; + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + // trigger as many responses as needed + if (responses) { + for (let i = 0; i < responses.length; ++i) { + setImmediate(() => { + mockStream.write({}); + }); } - return sinon.stub().returns(mockStream); + setImmediate(() => { + mockStream.end(); + }); + } else { + setImmediate(() => { + mockStream.write({}); + }); + setImmediate(() => { + mockStream.end(); + }); + } + return sinon.stub().returns(mockStream); } -function stubAsyncIterationCall(responses?: ResponseType[], error?: Error) { - let counter = 0; - const asyncIterable = { - [Symbol.asyncIterator]() { - return { - async next() { - if (error) { - return Promise.reject(error); - } - if (counter >= responses!.length) { - return Promise.resolve({done: true, value: undefined}); - } - return Promise.resolve({done: false, value: responses![counter++]}); - } - }; - } - }; - return sinon.stub().returns(asyncIterable); +function stubAsyncIterationCall( + responses?: ResponseType[], + error?: Error, +) { + let counter = 0; + const asyncIterable = { + [Symbol.asyncIterator]() { + return { + async next() { + if (error) { + return Promise.reject(error); + } + if (counter >= responses!.length) { + return Promise.resolve({ done: true, value: undefined }); + } + return Promise.resolve({ done: false, value: responses![counter++] }); + }, + }; + }, + }; + return sinon.stub().returns(asyncIterable); } describe('v2.JobServiceClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new jobserviceModule.v2.JobServiceClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'bigquery.googleapis.com'); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new jobserviceModule.v2.JobServiceClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'bigquery.googleapis.com'); + }); - it('has universeDomain', () => { - const client = new jobserviceModule.v2.JobServiceClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); + it('has universeDomain', () => { + const client = new jobserviceModule.v2.JobServiceClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - it('throws DeprecationWarning if static servicePath is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const servicePath = jobserviceModule.v2.JobServiceClient.servicePath; - assert.strictEqual(servicePath, 'bigquery.googleapis.com'); - assert(stub.called); - stub.restore(); - }); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = jobserviceModule.v2.JobServiceClient.servicePath; + assert.strictEqual(servicePath, 'bigquery.googleapis.com'); + assert(stub.called); + stub.restore(); + }); - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = jobserviceModule.v2.JobServiceClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'bigquery.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new jobserviceModule.v2.JobServiceClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'bigquery.example.com'); + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = jobserviceModule.v2.JobServiceClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'bigquery.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = new jobserviceModule.v2.JobServiceClient({ + universeDomain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'bigquery.example.com'); + }); + + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = new jobserviceModule.v2.JobServiceClient({ + universe_domain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'bigquery.example.com'); + }); + + if (typeof process === 'object' && 'env' in process) { + describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { + it('sets apiEndpoint from environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new jobserviceModule.v2.JobServiceClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'bigquery.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new jobserviceModule.v2.JobServiceClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'bigquery.example.com'); + it('value configured in code has priority over environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new jobserviceModule.v2.JobServiceClient({ + universeDomain: 'configured.example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'bigquery.configured.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } + }); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new jobserviceModule.v2.JobServiceClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); + }); - if (typeof process === 'object' && 'env' in process) { - describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { - it('sets apiEndpoint from environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new jobserviceModule.v2.JobServiceClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'bigquery.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); + it('has port', () => { + const port = jobserviceModule.v2.JobServiceClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('value configured in code has priority over environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new jobserviceModule.v2.JobServiceClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'bigquery.configured.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { new jobserviceModule.v2.JobServiceClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); + it('should create a client with no option', () => { + const client = new jobserviceModule.v2.JobServiceClient(); + assert(client); + }); - it('has port', () => { - const port = jobserviceModule.v2.JobServiceClient.port; - assert(port); - assert(typeof port === 'number'); - }); + it('should create a client with gRPC fallback', () => { + const client = new jobserviceModule.v2.JobServiceClient({ + fallback: true, + }); + assert(client); + }); - it('should create a client with no option', () => { - const client = new jobserviceModule.v2.JobServiceClient(); - assert(client); - }); + it('has initialize method and supports deferred initialization', async () => { + const client = new jobserviceModule.v2.JobServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.jobServiceStub, undefined); + await client.initialize(); + assert(client.jobServiceStub); + }); - it('should create a client with gRPC fallback', () => { - const client = new jobserviceModule.v2.JobServiceClient({ - fallback: true, - }); - assert(client); + it('has close method for the initialized client', (done) => { + const client = new jobserviceModule.v2.JobServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.jobServiceStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('has initialize method and supports deferred initialization', async () => { - const client = new jobserviceModule.v2.JobServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.jobServiceStub, undefined); - await client.initialize(); - assert(client.jobServiceStub); + it('has close method for the non-initialized client', (done) => { + const client = new jobserviceModule.v2.JobServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.jobServiceStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('has close method for the initialized client', done => { - const client = new jobserviceModule.v2.JobServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.jobServiceStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new jobserviceModule.v2.JobServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + }); - it('has close method for the non-initialized client', done => { - const client = new jobserviceModule.v2.JobServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.jobServiceStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new jobserviceModule.v2.JobServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new jobserviceModule.v2.JobServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); - }); + describe('cancelJob', () => { + it('invokes cancelJob without error', async () => { + const client = new jobserviceModule.v2.JobServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.CancelJobRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.CancelJobRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.CancelJobRequest', + ['jobId'], + ); + request.jobId = defaultValue2; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&job_id=${defaultValue2 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.bigquery.v2.JobCancelResponse(), + ); + client.innerApiCalls.cancelJob = stubSimpleCall(expectedResponse); + const [response] = await client.cancelJob(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.cancelJob as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.cancelJob as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new jobserviceModule.v2.JobServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId((err?: Error|null, projectId?: string|null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } - }); - }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); - }); + it('invokes cancelJob without error using callback', async () => { + const client = new jobserviceModule.v2.JobServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.CancelJobRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.CancelJobRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.CancelJobRequest', + ['jobId'], + ); + request.jobId = defaultValue2; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&job_id=${defaultValue2 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.bigquery.v2.JobCancelResponse(), + ); + client.innerApiCalls.cancelJob = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.cancelJob( + request, + ( + err?: Error | null, + result?: protos.google.cloud.bigquery.v2.IJobCancelResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.cancelJob as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.cancelJob as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('cancelJob', () => { - it('invokes cancelJob without error', async () => { - const client = new jobserviceModule.v2.JobServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.CancelJobRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.CancelJobRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.CancelJobRequest', ['jobId']); - request.jobId = defaultValue2; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&job_id=${defaultValue2 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.bigquery.v2.JobCancelResponse() - ); - client.innerApiCalls.cancelJob = stubSimpleCall(expectedResponse); - const [response] = await client.cancelJob(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.cancelJob as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.cancelJob as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes cancelJob with error', async () => { + const client = new jobserviceModule.v2.JobServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.CancelJobRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.CancelJobRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.CancelJobRequest', + ['jobId'], + ); + request.jobId = defaultValue2; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&job_id=${defaultValue2 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.cancelJob = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.cancelJob(request), expectedError); + const actualRequest = ( + client.innerApiCalls.cancelJob as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.cancelJob as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes cancelJob without error using callback', async () => { - const client = new jobserviceModule.v2.JobServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.CancelJobRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.CancelJobRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.CancelJobRequest', ['jobId']); - request.jobId = defaultValue2; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&job_id=${defaultValue2 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.bigquery.v2.JobCancelResponse() - ); - client.innerApiCalls.cancelJob = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.cancelJob( - request, - (err?: Error|null, result?: protos.google.cloud.bigquery.v2.IJobCancelResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.cancelJob as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.cancelJob as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes cancelJob with closed client', async () => { + const client = new jobserviceModule.v2.JobServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.CancelJobRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.CancelJobRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.CancelJobRequest', + ['jobId'], + ); + request.jobId = defaultValue2; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.cancelJob(request), expectedError); + }); + }); - it('invokes cancelJob with error', async () => { - const client = new jobserviceModule.v2.JobServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.CancelJobRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.CancelJobRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.CancelJobRequest', ['jobId']); - request.jobId = defaultValue2; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&job_id=${defaultValue2 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.cancelJob = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.cancelJob(request), expectedError); - const actualRequest = (client.innerApiCalls.cancelJob as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.cancelJob as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + describe('getJob', () => { + it('invokes getJob without error', async () => { + const client = new jobserviceModule.v2.JobServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.GetJobRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetJobRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetJobRequest', + ['jobId'], + ); + request.jobId = defaultValue2; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&job_id=${defaultValue2 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.bigquery.v2.Job(), + ); + client.innerApiCalls.getJob = stubSimpleCall(expectedResponse); + const [response] = await client.getJob(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.getJob as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getJob as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes cancelJob with closed client', async () => { - const client = new jobserviceModule.v2.JobServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.CancelJobRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.CancelJobRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.CancelJobRequest', ['jobId']); - request.jobId = defaultValue2; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.cancelJob(request), expectedError); - }); + it('invokes getJob without error using callback', async () => { + const client = new jobserviceModule.v2.JobServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.GetJobRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetJobRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetJobRequest', + ['jobId'], + ); + request.jobId = defaultValue2; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&job_id=${defaultValue2 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.bigquery.v2.Job(), + ); + client.innerApiCalls.getJob = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getJob( + request, + ( + err?: Error | null, + result?: protos.google.cloud.bigquery.v2.IJob | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.getJob as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getJob as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('getJob', () => { - it('invokes getJob without error', async () => { - const client = new jobserviceModule.v2.JobServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.GetJobRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetJobRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetJobRequest', ['jobId']); - request.jobId = defaultValue2; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&job_id=${defaultValue2 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.bigquery.v2.Job() - ); - client.innerApiCalls.getJob = stubSimpleCall(expectedResponse); - const [response] = await client.getJob(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getJob as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getJob as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getJob with error', async () => { + const client = new jobserviceModule.v2.JobServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.GetJobRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetJobRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetJobRequest', + ['jobId'], + ); + request.jobId = defaultValue2; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&job_id=${defaultValue2 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getJob = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.getJob(request), expectedError); + const actualRequest = (client.innerApiCalls.getJob as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getJob as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getJob without error using callback', async () => { - const client = new jobserviceModule.v2.JobServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.GetJobRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetJobRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetJobRequest', ['jobId']); - request.jobId = defaultValue2; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&job_id=${defaultValue2 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.bigquery.v2.Job() - ); - client.innerApiCalls.getJob = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getJob( - request, - (err?: Error|null, result?: protos.google.cloud.bigquery.v2.IJob|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getJob as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getJob as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getJob with closed client', async () => { + const client = new jobserviceModule.v2.JobServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.GetJobRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetJobRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetJobRequest', + ['jobId'], + ); + request.jobId = defaultValue2; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getJob(request), expectedError); + }); + }); - it('invokes getJob with error', async () => { - const client = new jobserviceModule.v2.JobServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.GetJobRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetJobRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetJobRequest', ['jobId']); - request.jobId = defaultValue2; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&job_id=${defaultValue2 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getJob = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getJob(request), expectedError); - const actualRequest = (client.innerApiCalls.getJob as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getJob as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + describe('insertJob', () => { + it('invokes insertJob without error', async () => { + const client = new jobserviceModule.v2.JobServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.InsertJobRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.InsertJobRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.bigquery.v2.Job(), + ); + client.innerApiCalls.insertJob = stubSimpleCall(expectedResponse); + const [response] = await client.insertJob(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.insertJob as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.insertJob as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getJob with closed client', async () => { - const client = new jobserviceModule.v2.JobServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.GetJobRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetJobRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetJobRequest', ['jobId']); - request.jobId = defaultValue2; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getJob(request), expectedError); - }); + it('invokes insertJob without error using callback', async () => { + const client = new jobserviceModule.v2.JobServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.InsertJobRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.InsertJobRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.bigquery.v2.Job(), + ); + client.innerApiCalls.insertJob = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.insertJob( + request, + ( + err?: Error | null, + result?: protos.google.cloud.bigquery.v2.IJob | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.insertJob as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.insertJob as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('insertJob', () => { - it('invokes insertJob without error', async () => { - const client = new jobserviceModule.v2.JobServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.InsertJobRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.InsertJobRequest', ['projectId']); - request.projectId = defaultValue1; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.bigquery.v2.Job() - ); - client.innerApiCalls.insertJob = stubSimpleCall(expectedResponse); - const [response] = await client.insertJob(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.insertJob as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.insertJob as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes insertJob with error', async () => { + const client = new jobserviceModule.v2.JobServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.InsertJobRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.InsertJobRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.insertJob = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.insertJob(request), expectedError); + const actualRequest = ( + client.innerApiCalls.insertJob as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.insertJob as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes insertJob without error using callback', async () => { - const client = new jobserviceModule.v2.JobServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.InsertJobRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.InsertJobRequest', ['projectId']); - request.projectId = defaultValue1; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.bigquery.v2.Job() - ); - client.innerApiCalls.insertJob = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.insertJob( - request, - (err?: Error|null, result?: protos.google.cloud.bigquery.v2.IJob|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.insertJob as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.insertJob as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes insertJob with closed client', async () => { + const client = new jobserviceModule.v2.JobServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.InsertJobRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.InsertJobRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.insertJob(request), expectedError); + }); + }); - it('invokes insertJob with error', async () => { - const client = new jobserviceModule.v2.JobServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.InsertJobRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.InsertJobRequest', ['projectId']); - request.projectId = defaultValue1; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.insertJob = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.insertJob(request), expectedError); - const actualRequest = (client.innerApiCalls.insertJob as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.insertJob as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + describe('deleteJob', () => { + it('invokes deleteJob without error', async () => { + const client = new jobserviceModule.v2.JobServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.DeleteJobRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.DeleteJobRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.DeleteJobRequest', + ['jobId'], + ); + request.jobId = defaultValue2; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&job_id=${defaultValue2 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteJob = stubSimpleCall(expectedResponse); + const [response] = await client.deleteJob(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteJob as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteJob as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes insertJob with closed client', async () => { - const client = new jobserviceModule.v2.JobServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.InsertJobRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.InsertJobRequest', ['projectId']); - request.projectId = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.insertJob(request), expectedError); - }); + it('invokes deleteJob without error using callback', async () => { + const client = new jobserviceModule.v2.JobServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.DeleteJobRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.DeleteJobRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.DeleteJobRequest', + ['jobId'], + ); + request.jobId = defaultValue2; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&job_id=${defaultValue2 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteJob = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteJob( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteJob as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteJob as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('deleteJob', () => { - it('invokes deleteJob without error', async () => { - const client = new jobserviceModule.v2.JobServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.DeleteJobRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.DeleteJobRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.DeleteJobRequest', ['jobId']); - request.jobId = defaultValue2; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&job_id=${defaultValue2 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteJob = stubSimpleCall(expectedResponse); - const [response] = await client.deleteJob(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteJob as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteJob as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteJob with error', async () => { + const client = new jobserviceModule.v2.JobServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.DeleteJobRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.DeleteJobRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.DeleteJobRequest', + ['jobId'], + ); + request.jobId = defaultValue2; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&job_id=${defaultValue2 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteJob = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.deleteJob(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteJob as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteJob as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteJob without error using callback', async () => { - const client = new jobserviceModule.v2.JobServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.DeleteJobRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.DeleteJobRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.DeleteJobRequest', ['jobId']); - request.jobId = defaultValue2; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&job_id=${defaultValue2 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteJob = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteJob( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteJob as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteJob as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteJob with closed client', async () => { + const client = new jobserviceModule.v2.JobServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.DeleteJobRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.DeleteJobRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.DeleteJobRequest', + ['jobId'], + ); + request.jobId = defaultValue2; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.deleteJob(request), expectedError); + }); + }); - it('invokes deleteJob with error', async () => { - const client = new jobserviceModule.v2.JobServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.DeleteJobRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.DeleteJobRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.DeleteJobRequest', ['jobId']); - request.jobId = defaultValue2; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&job_id=${defaultValue2 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteJob = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteJob(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteJob as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteJob as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + describe('getQueryResults', () => { + it('invokes getQueryResults without error', async () => { + const client = new jobserviceModule.v2.JobServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.GetQueryResultsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetQueryResultsRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetQueryResultsRequest', + ['jobId'], + ); + request.jobId = defaultValue2; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&job_id=${defaultValue2 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.bigquery.v2.GetQueryResultsResponse(), + ); + client.innerApiCalls.getQueryResults = stubSimpleCall(expectedResponse); + const [response] = await client.getQueryResults(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getQueryResults as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getQueryResults as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteJob with closed client', async () => { - const client = new jobserviceModule.v2.JobServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.DeleteJobRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.DeleteJobRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.DeleteJobRequest', ['jobId']); - request.jobId = defaultValue2; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteJob(request), expectedError); - }); + it('invokes getQueryResults without error using callback', async () => { + const client = new jobserviceModule.v2.JobServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.GetQueryResultsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetQueryResultsRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetQueryResultsRequest', + ['jobId'], + ); + request.jobId = defaultValue2; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&job_id=${defaultValue2 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.bigquery.v2.GetQueryResultsResponse(), + ); + client.innerApiCalls.getQueryResults = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getQueryResults( + request, + ( + err?: Error | null, + result?: protos.google.cloud.bigquery.v2.IGetQueryResultsResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getQueryResults as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getQueryResults as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('getQueryResults', () => { - it('invokes getQueryResults without error', async () => { - const client = new jobserviceModule.v2.JobServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.GetQueryResultsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetQueryResultsRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetQueryResultsRequest', ['jobId']); - request.jobId = defaultValue2; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&job_id=${defaultValue2 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.bigquery.v2.GetQueryResultsResponse() - ); - client.innerApiCalls.getQueryResults = stubSimpleCall(expectedResponse); - const [response] = await client.getQueryResults(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getQueryResults as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getQueryResults as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getQueryResults with error', async () => { + const client = new jobserviceModule.v2.JobServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.GetQueryResultsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetQueryResultsRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetQueryResultsRequest', + ['jobId'], + ); + request.jobId = defaultValue2; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&job_id=${defaultValue2 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getQueryResults = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getQueryResults(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getQueryResults as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getQueryResults as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getQueryResults without error using callback', async () => { - const client = new jobserviceModule.v2.JobServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.GetQueryResultsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetQueryResultsRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetQueryResultsRequest', ['jobId']); - request.jobId = defaultValue2; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&job_id=${defaultValue2 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.bigquery.v2.GetQueryResultsResponse() - ); - client.innerApiCalls.getQueryResults = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getQueryResults( - request, - (err?: Error|null, result?: protos.google.cloud.bigquery.v2.IGetQueryResultsResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getQueryResults as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getQueryResults as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getQueryResults with closed client', async () => { + const client = new jobserviceModule.v2.JobServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.GetQueryResultsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetQueryResultsRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetQueryResultsRequest', + ['jobId'], + ); + request.jobId = defaultValue2; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getQueryResults(request), expectedError); + }); + }); - it('invokes getQueryResults with error', async () => { - const client = new jobserviceModule.v2.JobServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.GetQueryResultsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetQueryResultsRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetQueryResultsRequest', ['jobId']); - request.jobId = defaultValue2; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&job_id=${defaultValue2 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getQueryResults = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getQueryResults(request), expectedError); - const actualRequest = (client.innerApiCalls.getQueryResults as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getQueryResults as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + describe('query', () => { + it('invokes query without error', async () => { + const client = new jobserviceModule.v2.JobServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.PostQueryRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.PostQueryRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.bigquery.v2.QueryResponse(), + ); + client.innerApiCalls.query = stubSimpleCall(expectedResponse); + const [response] = await client.query(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.query as SinonStub).getCall(0) + .args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.query as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getQueryResults with closed client', async () => { - const client = new jobserviceModule.v2.JobServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.GetQueryResultsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetQueryResultsRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetQueryResultsRequest', ['jobId']); - request.jobId = defaultValue2; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getQueryResults(request), expectedError); - }); + it('invokes query without error using callback', async () => { + const client = new jobserviceModule.v2.JobServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.PostQueryRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.PostQueryRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.bigquery.v2.QueryResponse(), + ); + client.innerApiCalls.query = stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.query( + request, + ( + err?: Error | null, + result?: protos.google.cloud.bigquery.v2.IQueryResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.query as SinonStub).getCall(0) + .args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.query as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('query', () => { - it('invokes query without error', async () => { - const client = new jobserviceModule.v2.JobServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.PostQueryRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.PostQueryRequest', ['projectId']); - request.projectId = defaultValue1; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.bigquery.v2.QueryResponse() - ); - client.innerApiCalls.query = stubSimpleCall(expectedResponse); - const [response] = await client.query(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.query as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.query as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes query with error', async () => { + const client = new jobserviceModule.v2.JobServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.PostQueryRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.PostQueryRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.query = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.query(request), expectedError); + const actualRequest = (client.innerApiCalls.query as SinonStub).getCall(0) + .args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.query as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes query without error using callback', async () => { - const client = new jobserviceModule.v2.JobServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.PostQueryRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.PostQueryRequest', ['projectId']); - request.projectId = defaultValue1; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.bigquery.v2.QueryResponse() - ); - client.innerApiCalls.query = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.query( - request, - (err?: Error|null, result?: protos.google.cloud.bigquery.v2.IQueryResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.query as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.query as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes query with closed client', async () => { + const client = new jobserviceModule.v2.JobServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.PostQueryRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.PostQueryRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.query(request), expectedError); + }); + }); - it('invokes query with error', async () => { - const client = new jobserviceModule.v2.JobServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.PostQueryRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.PostQueryRequest', ['projectId']); - request.projectId = defaultValue1; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.query = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.query(request), expectedError); - const actualRequest = (client.innerApiCalls.query as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.query as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + describe('listJobs', () => { + it('invokes listJobs without error', async () => { + const client = new jobserviceModule.v2.JobServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListJobsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListJobsRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListFormatJob(), + ), + generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListFormatJob(), + ), + generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListFormatJob(), + ), + ]; + client.innerApiCalls.listJobs = stubSimpleCall(expectedResponse); + const [response] = await client.listJobs(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listJobs as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listJobs as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes query with closed client', async () => { - const client = new jobserviceModule.v2.JobServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.PostQueryRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.PostQueryRequest', ['projectId']); - request.projectId = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.query(request), expectedError); - }); + it('invokes listJobs without error using callback', async () => { + const client = new jobserviceModule.v2.JobServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListJobsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListJobsRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListFormatJob(), + ), + generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListFormatJob(), + ), + generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListFormatJob(), + ), + ]; + client.innerApiCalls.listJobs = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listJobs( + request, + ( + err?: Error | null, + result?: protos.google.cloud.bigquery.v2.IListFormatJob[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listJobs as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listJobs as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('listJobs', () => { - it('invokes listJobs without error', async () => { - const client = new jobserviceModule.v2.JobServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.ListJobsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListJobsRequest', ['projectId']); - request.projectId = defaultValue1; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.bigquery.v2.ListFormatJob()), - generateSampleMessage(new protos.google.cloud.bigquery.v2.ListFormatJob()), - generateSampleMessage(new protos.google.cloud.bigquery.v2.ListFormatJob()), - ]; - client.innerApiCalls.listJobs = stubSimpleCall(expectedResponse); - const [response] = await client.listJobs(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listJobs as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listJobs as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listJobs with error', async () => { + const client = new jobserviceModule.v2.JobServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListJobsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListJobsRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listJobs = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.listJobs(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listJobs as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listJobs as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listJobs without error using callback', async () => { - const client = new jobserviceModule.v2.JobServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.ListJobsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListJobsRequest', ['projectId']); - request.projectId = defaultValue1; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.bigquery.v2.ListFormatJob()), - generateSampleMessage(new protos.google.cloud.bigquery.v2.ListFormatJob()), - generateSampleMessage(new protos.google.cloud.bigquery.v2.ListFormatJob()), - ]; - client.innerApiCalls.listJobs = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listJobs( - request, - (err?: Error|null, result?: protos.google.cloud.bigquery.v2.IListFormatJob[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listJobs as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listJobs as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes listJobsStream without error', async () => { + const client = new jobserviceModule.v2.JobServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListJobsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListJobsRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListFormatJob(), + ), + generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListFormatJob(), + ), + generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListFormatJob(), + ), + ]; + client.descriptors.page.listJobs.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listJobsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.cloud.bigquery.v2.ListFormatJob[] = []; + stream.on( + 'data', + (response: protos.google.cloud.bigquery.v2.ListFormatJob) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); }); - - it('invokes listJobs with error', async () => { - const client = new jobserviceModule.v2.JobServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.ListJobsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListJobsRequest', ['projectId']); - request.projectId = defaultValue1; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listJobs = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listJobs(request), expectedError); - const actualRequest = (client.innerApiCalls.listJobs as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listJobs as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + stream.on('error', (err: Error) => { + reject(err); }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listJobs.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listJobs, request), + ); + assert( + (client.descriptors.page.listJobs.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('invokes listJobsStream without error', async () => { - const client = new jobserviceModule.v2.JobServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.ListJobsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListJobsRequest', ['projectId']); - request.projectId = defaultValue1; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.bigquery.v2.ListFormatJob()), - generateSampleMessage(new protos.google.cloud.bigquery.v2.ListFormatJob()), - generateSampleMessage(new protos.google.cloud.bigquery.v2.ListFormatJob()), - ]; - client.descriptors.page.listJobs.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listJobsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.cloud.bigquery.v2.ListFormatJob[] = []; - stream.on('data', (response: protos.google.cloud.bigquery.v2.ListFormatJob) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.listJobs.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listJobs, request)); - assert( - (client.descriptors.page.listJobs.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); + it('invokes listJobsStream with error', async () => { + const client = new jobserviceModule.v2.JobServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListJobsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListJobsRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listJobs.createStream = stubPageStreamingCall( + undefined, + expectedError, + ); + const stream = client.listJobsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.cloud.bigquery.v2.ListFormatJob[] = []; + stream.on( + 'data', + (response: protos.google.cloud.bigquery.v2.ListFormatJob) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); }); - - it('invokes listJobsStream with error', async () => { - const client = new jobserviceModule.v2.JobServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.ListJobsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListJobsRequest', ['projectId']); - request.projectId = defaultValue1; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listJobs.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listJobsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.cloud.bigquery.v2.ListFormatJob[] = []; - stream.on('data', (response: protos.google.cloud.bigquery.v2.ListFormatJob) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listJobs.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listJobs, request)); - assert( - (client.descriptors.page.listJobs.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); + stream.on('error', (err: Error) => { + reject(err); }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listJobs.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listJobs, request), + ); + assert( + (client.descriptors.page.listJobs.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('uses async iteration with listJobs without error', async () => { - const client = new jobserviceModule.v2.JobServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.ListJobsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListJobsRequest', ['projectId']); - request.projectId = defaultValue1; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.bigquery.v2.ListFormatJob()), - generateSampleMessage(new protos.google.cloud.bigquery.v2.ListFormatJob()), - generateSampleMessage(new protos.google.cloud.bigquery.v2.ListFormatJob()), - ]; - client.descriptors.page.listJobs.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.cloud.bigquery.v2.IListFormatJob[] = []; - const iterable = client.listJobsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listJobs.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listJobs.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listJobs without error', async () => { + const client = new jobserviceModule.v2.JobServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListJobsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListJobsRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListFormatJob(), + ), + generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListFormatJob(), + ), + generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListFormatJob(), + ), + ]; + client.descriptors.page.listJobs.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.cloud.bigquery.v2.IListFormatJob[] = []; + const iterable = client.listJobsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + (client.descriptors.page.listJobs.asyncIterate as SinonStub).getCall(0) + .args[1], + request, + ); + assert( + (client.descriptors.page.listJobs.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('uses async iteration with listJobs with error', async () => { - const client = new jobserviceModule.v2.JobServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.ListJobsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListJobsRequest', ['projectId']); - request.projectId = defaultValue1; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listJobs.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listJobsAsync(request); - await assert.rejects(async () => { - const responses: protos.google.cloud.bigquery.v2.IListFormatJob[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listJobs.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listJobs.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listJobs with error', async () => { + const client = new jobserviceModule.v2.JobServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListJobsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListJobsRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listJobs.asyncIterate = stubAsyncIterationCall( + undefined, + expectedError, + ); + const iterable = client.listJobsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.cloud.bigquery.v2.IListFormatJob[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + (client.descriptors.page.listJobs.asyncIterate as SinonStub).getCall(0) + .args[1], + request, + ); + assert( + (client.descriptors.page.listJobs.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); }); + }); }); diff --git a/core/generator/gapic-generator-typescript/baselines/bigquery-v2-esm/esm/test/gapic_model_service_v2.ts.baseline b/core/generator/gapic-generator-typescript/baselines/bigquery-v2-esm/esm/test/gapic_model_service_v2.ts.baseline index 661cc4afcc9b..bb60d0d8db1d 100644 --- a/core/generator/gapic-generator-typescript/baselines/bigquery-v2-esm/esm/test/gapic_model_service_v2.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/bigquery-v2-esm/esm/test/gapic_model_service_v2.ts.baseline @@ -20,16 +20,16 @@ import * as protos from '../../protos/protos.js'; import assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as modelserviceModule from '../src/index.js'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; -import {protobuf} from 'google-gax'; +import { protobuf } from 'google-gax'; import fs from 'fs'; import path from 'path'; -import {fileURLToPath} from 'url'; +import { fileURLToPath } from 'url'; // @ts-ignore const dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -37,896 +37,1141 @@ const dirname = path.dirname(fileURLToPath(import.meta.url)); // to fill in default values for request objects const root = protobuf.Root.fromJSON( JSON.parse( - fs.readFileSync(path.join(dirname, '..', '..', 'protos/protos.json'), 'utf8') - )) + fs.readFileSync( + path.join(dirname, '..', '..', 'protos/protos.json'), + 'utf8', + ), + ), +); // eslint-disable-next-line @typescript-eslint/no-unused-vars function getTypeDefaultValue(typeName: string, fields: string[]) { - let type = root.lookupType(typeName) as protobuf.Type; - for (const field of fields.slice(0, -1)) { - type = type?.fields[field]?.resolvedType as protobuf.Type; - } - return type?.fields[fields[fields.length - 1]]?.defaultValue ?? null; + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type?.fields[field]?.resolvedType as protobuf.Type; + } + return type?.fields[fields[fields.length - 1]]?.defaultValue ?? null; } function generateSampleMessage(instance: T) { - const filledObject = (instance.constructor as typeof protobuf.Message) - .toObject(instance as protobuf.Message, {defaults: true}); - return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, { defaults: true }); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; } function stubSimpleCall(response?: ResponseType, error?: Error) { - return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); } -function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { - return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +function stubSimpleCallWithCallback( + response?: ResponseType, + error?: Error, +) { + return error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); } -function stubPageStreamingCall(responses?: ResponseType[], error?: Error) { - const pagingStub = sinon.stub(); - if (responses) { - for (let i = 0; i < responses.length; ++i) { - pagingStub.onCall(i).callsArgWith(2, null, responses[i]); - } +function stubPageStreamingCall( + responses?: ResponseType[], + error?: Error, +) { + const pagingStub = sinon.stub(); + if (responses) { + for (let i = 0; i < responses.length; ++i) { + pagingStub.onCall(i).callsArgWith(2, null, responses[i]); } - const transformStub = error ? sinon.stub().callsArgWith(2, error) : pagingStub; - const mockStream = new PassThrough({ - objectMode: true, - transform: transformStub, - }); - // trigger as many responses as needed - if (responses) { - for (let i = 0; i < responses.length; ++i) { - setImmediate(() => { mockStream.write({}); }); - } - setImmediate(() => { mockStream.end(); }); - } else { - setImmediate(() => { mockStream.write({}); }); - setImmediate(() => { mockStream.end(); }); + } + const transformStub = error + ? sinon.stub().callsArgWith(2, error) + : pagingStub; + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + // trigger as many responses as needed + if (responses) { + for (let i = 0; i < responses.length; ++i) { + setImmediate(() => { + mockStream.write({}); + }); } - return sinon.stub().returns(mockStream); + setImmediate(() => { + mockStream.end(); + }); + } else { + setImmediate(() => { + mockStream.write({}); + }); + setImmediate(() => { + mockStream.end(); + }); + } + return sinon.stub().returns(mockStream); } -function stubAsyncIterationCall(responses?: ResponseType[], error?: Error) { - let counter = 0; - const asyncIterable = { - [Symbol.asyncIterator]() { - return { - async next() { - if (error) { - return Promise.reject(error); - } - if (counter >= responses!.length) { - return Promise.resolve({done: true, value: undefined}); - } - return Promise.resolve({done: false, value: responses![counter++]}); - } - }; - } - }; - return sinon.stub().returns(asyncIterable); +function stubAsyncIterationCall( + responses?: ResponseType[], + error?: Error, +) { + let counter = 0; + const asyncIterable = { + [Symbol.asyncIterator]() { + return { + async next() { + if (error) { + return Promise.reject(error); + } + if (counter >= responses!.length) { + return Promise.resolve({ done: true, value: undefined }); + } + return Promise.resolve({ done: false, value: responses![counter++] }); + }, + }; + }, + }; + return sinon.stub().returns(asyncIterable); } describe('v2.ModelServiceClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new modelserviceModule.v2.ModelServiceClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'bigquery.googleapis.com'); - }); - - it('has universeDomain', () => { - const client = new modelserviceModule.v2.ModelServiceClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new modelserviceModule.v2.ModelServiceClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'bigquery.googleapis.com'); + }); - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - it('throws DeprecationWarning if static servicePath is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const servicePath = modelserviceModule.v2.ModelServiceClient.servicePath; - assert.strictEqual(servicePath, 'bigquery.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = modelserviceModule.v2.ModelServiceClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'bigquery.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new modelserviceModule.v2.ModelServiceClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'bigquery.example.com'); - }); + it('has universeDomain', () => { + const client = new modelserviceModule.v2.ModelServiceClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new modelserviceModule.v2.ModelServiceClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'bigquery.example.com'); - }); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = + modelserviceModule.v2.ModelServiceClient.servicePath; + assert.strictEqual(servicePath, 'bigquery.googleapis.com'); + assert(stub.called); + stub.restore(); + }); - if (typeof process === 'object' && 'env' in process) { - describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { - it('sets apiEndpoint from environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new modelserviceModule.v2.ModelServiceClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'bigquery.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - - it('value configured in code has priority over environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new modelserviceModule.v2.ModelServiceClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'bigquery.configured.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { new modelserviceModule.v2.ModelServiceClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + modelserviceModule.v2.ModelServiceClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'bigquery.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = new modelserviceModule.v2.ModelServiceClient({ + universeDomain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'bigquery.example.com'); + }); - it('has port', () => { - const port = modelserviceModule.v2.ModelServiceClient.port; - assert(port); - assert(typeof port === 'number'); - }); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = new modelserviceModule.v2.ModelServiceClient({ + universe_domain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'bigquery.example.com'); + }); - it('should create a client with no option', () => { - const client = new modelserviceModule.v2.ModelServiceClient(); - assert(client); + if (typeof process === 'object' && 'env' in process) { + describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { + it('sets apiEndpoint from environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new modelserviceModule.v2.ModelServiceClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'bigquery.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - it('should create a client with gRPC fallback', () => { - const client = new modelserviceModule.v2.ModelServiceClient({ - fallback: true, - }); - assert(client); + it('value configured in code has priority over environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new modelserviceModule.v2.ModelServiceClient({ + universeDomain: 'configured.example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'bigquery.configured.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - - it('has initialize method and supports deferred initialization', async () => { - const client = new modelserviceModule.v2.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.modelServiceStub, undefined); - await client.initialize(); - assert(client.modelServiceStub); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new modelserviceModule.v2.ModelServiceClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); + }); - it('has close method for the initialized client', done => { - const client = new modelserviceModule.v2.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.modelServiceStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('has port', () => { + const port = modelserviceModule.v2.ModelServiceClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('has close method for the non-initialized client', done => { - const client = new modelserviceModule.v2.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.modelServiceStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('should create a client with no option', () => { + const client = new modelserviceModule.v2.ModelServiceClient(); + assert(client); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new modelserviceModule.v2.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); - }); + it('should create a client with gRPC fallback', () => { + const client = new modelserviceModule.v2.ModelServiceClient({ + fallback: true, + }); + assert(client); + }); - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new modelserviceModule.v2.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId((err?: Error|null, projectId?: string|null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } - }); - }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); - }); + it('has initialize method and supports deferred initialization', async () => { + const client = new modelserviceModule.v2.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.modelServiceStub, undefined); + await client.initialize(); + assert(client.modelServiceStub); }); - describe('getModel', () => { - it('invokes getModel without error', async () => { - const client = new modelserviceModule.v2.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.GetModelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetModelRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetModelRequest', ['datasetId']); - request.datasetId = defaultValue2; - const defaultValue3 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetModelRequest', ['modelId']); - request.modelId = defaultValue3; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }&model_id=${defaultValue3 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.bigquery.v2.Model() - ); - client.innerApiCalls.getModel = stubSimpleCall(expectedResponse); - const [response] = await client.getModel(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getModel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getModel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('has close method for the initialized client', (done) => { + const client = new modelserviceModule.v2.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.modelServiceStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes getModel without error using callback', async () => { - const client = new modelserviceModule.v2.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.GetModelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetModelRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetModelRequest', ['datasetId']); - request.datasetId = defaultValue2; - const defaultValue3 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetModelRequest', ['modelId']); - request.modelId = defaultValue3; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }&model_id=${defaultValue3 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.bigquery.v2.Model() - ); - client.innerApiCalls.getModel = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getModel( - request, - (err?: Error|null, result?: protos.google.cloud.bigquery.v2.IModel|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getModel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getModel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('has close method for the non-initialized client', (done) => { + const client = new modelserviceModule.v2.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.modelServiceStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes getModel with error', async () => { - const client = new modelserviceModule.v2.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.GetModelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetModelRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetModelRequest', ['datasetId']); - request.datasetId = defaultValue2; - const defaultValue3 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetModelRequest', ['modelId']); - request.modelId = defaultValue3; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }&model_id=${defaultValue3 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getModel = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getModel(request), expectedError); - const actualRequest = (client.innerApiCalls.getModel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getModel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new modelserviceModule.v2.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + }); - it('invokes getModel with closed client', async () => { - const client = new modelserviceModule.v2.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.GetModelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetModelRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetModelRequest', ['datasetId']); - request.datasetId = defaultValue2; - const defaultValue3 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetModelRequest', ['modelId']); - request.modelId = defaultValue3; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getModel(request), expectedError); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new modelserviceModule.v2.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); }); + }); - describe('patchModel', () => { - it('invokes patchModel without error', async () => { - const client = new modelserviceModule.v2.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.PatchModelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.PatchModelRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.PatchModelRequest', ['datasetId']); - request.datasetId = defaultValue2; - const defaultValue3 = - getTypeDefaultValue('.google.cloud.bigquery.v2.PatchModelRequest', ['modelId']); - request.modelId = defaultValue3; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }&model_id=${defaultValue3 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.bigquery.v2.Model() - ); - client.innerApiCalls.patchModel = stubSimpleCall(expectedResponse); - const [response] = await client.patchModel(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.patchModel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.patchModel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + describe('getModel', () => { + it('invokes getModel without error', async () => { + const client = new modelserviceModule.v2.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.GetModelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetModelRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetModelRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const defaultValue3 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetModelRequest', + ['modelId'], + ); + request.modelId = defaultValue3; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}&model_id=${defaultValue3 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.bigquery.v2.Model(), + ); + client.innerApiCalls.getModel = stubSimpleCall(expectedResponse); + const [response] = await client.getModel(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getModel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getModel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes patchModel without error using callback', async () => { - const client = new modelserviceModule.v2.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.PatchModelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.PatchModelRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.PatchModelRequest', ['datasetId']); - request.datasetId = defaultValue2; - const defaultValue3 = - getTypeDefaultValue('.google.cloud.bigquery.v2.PatchModelRequest', ['modelId']); - request.modelId = defaultValue3; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }&model_id=${defaultValue3 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.bigquery.v2.Model() - ); - client.innerApiCalls.patchModel = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.patchModel( - request, - (err?: Error|null, result?: protos.google.cloud.bigquery.v2.IModel|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.patchModel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.patchModel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getModel without error using callback', async () => { + const client = new modelserviceModule.v2.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.GetModelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetModelRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetModelRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const defaultValue3 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetModelRequest', + ['modelId'], + ); + request.modelId = defaultValue3; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}&model_id=${defaultValue3 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.bigquery.v2.Model(), + ); + client.innerApiCalls.getModel = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getModel( + request, + ( + err?: Error | null, + result?: protos.google.cloud.bigquery.v2.IModel | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getModel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getModel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes patchModel with error', async () => { - const client = new modelserviceModule.v2.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.PatchModelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.PatchModelRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.PatchModelRequest', ['datasetId']); - request.datasetId = defaultValue2; - const defaultValue3 = - getTypeDefaultValue('.google.cloud.bigquery.v2.PatchModelRequest', ['modelId']); - request.modelId = defaultValue3; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }&model_id=${defaultValue3 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.patchModel = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.patchModel(request), expectedError); - const actualRequest = (client.innerApiCalls.patchModel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.patchModel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getModel with error', async () => { + const client = new modelserviceModule.v2.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.GetModelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetModelRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetModelRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const defaultValue3 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetModelRequest', + ['modelId'], + ); + request.modelId = defaultValue3; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}&model_id=${defaultValue3 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getModel = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.getModel(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getModel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getModel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes patchModel with closed client', async () => { - const client = new modelserviceModule.v2.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.PatchModelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.PatchModelRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.PatchModelRequest', ['datasetId']); - request.datasetId = defaultValue2; - const defaultValue3 = - getTypeDefaultValue('.google.cloud.bigquery.v2.PatchModelRequest', ['modelId']); - request.modelId = defaultValue3; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.patchModel(request), expectedError); - }); + it('invokes getModel with closed client', async () => { + const client = new modelserviceModule.v2.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.GetModelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetModelRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetModelRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const defaultValue3 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetModelRequest', + ['modelId'], + ); + request.modelId = defaultValue3; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getModel(request), expectedError); }); + }); - describe('deleteModel', () => { - it('invokes deleteModel without error', async () => { - const client = new modelserviceModule.v2.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.DeleteModelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.DeleteModelRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.DeleteModelRequest', ['datasetId']); - request.datasetId = defaultValue2; - const defaultValue3 = - getTypeDefaultValue('.google.cloud.bigquery.v2.DeleteModelRequest', ['modelId']); - request.modelId = defaultValue3; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }&model_id=${defaultValue3 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteModel = stubSimpleCall(expectedResponse); - const [response] = await client.deleteModel(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteModel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteModel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + describe('patchModel', () => { + it('invokes patchModel without error', async () => { + const client = new modelserviceModule.v2.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.PatchModelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.PatchModelRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.PatchModelRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const defaultValue3 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.PatchModelRequest', + ['modelId'], + ); + request.modelId = defaultValue3; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}&model_id=${defaultValue3 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.bigquery.v2.Model(), + ); + client.innerApiCalls.patchModel = stubSimpleCall(expectedResponse); + const [response] = await client.patchModel(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.patchModel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.patchModel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteModel without error using callback', async () => { - const client = new modelserviceModule.v2.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.DeleteModelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.DeleteModelRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.DeleteModelRequest', ['datasetId']); - request.datasetId = defaultValue2; - const defaultValue3 = - getTypeDefaultValue('.google.cloud.bigquery.v2.DeleteModelRequest', ['modelId']); - request.modelId = defaultValue3; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }&model_id=${defaultValue3 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteModel = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteModel( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteModel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteModel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes patchModel without error using callback', async () => { + const client = new modelserviceModule.v2.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.PatchModelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.PatchModelRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.PatchModelRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const defaultValue3 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.PatchModelRequest', + ['modelId'], + ); + request.modelId = defaultValue3; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}&model_id=${defaultValue3 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.bigquery.v2.Model(), + ); + client.innerApiCalls.patchModel = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.patchModel( + request, + ( + err?: Error | null, + result?: protos.google.cloud.bigquery.v2.IModel | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.patchModel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.patchModel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteModel with error', async () => { - const client = new modelserviceModule.v2.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.DeleteModelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.DeleteModelRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.DeleteModelRequest', ['datasetId']); - request.datasetId = defaultValue2; - const defaultValue3 = - getTypeDefaultValue('.google.cloud.bigquery.v2.DeleteModelRequest', ['modelId']); - request.modelId = defaultValue3; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }&model_id=${defaultValue3 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteModel = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteModel(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteModel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteModel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes patchModel with error', async () => { + const client = new modelserviceModule.v2.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.PatchModelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.PatchModelRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.PatchModelRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const defaultValue3 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.PatchModelRequest', + ['modelId'], + ); + request.modelId = defaultValue3; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}&model_id=${defaultValue3 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.patchModel = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.patchModel(request), expectedError); + const actualRequest = ( + client.innerApiCalls.patchModel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.patchModel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteModel with closed client', async () => { - const client = new modelserviceModule.v2.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.DeleteModelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.DeleteModelRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.DeleteModelRequest', ['datasetId']); - request.datasetId = defaultValue2; - const defaultValue3 = - getTypeDefaultValue('.google.cloud.bigquery.v2.DeleteModelRequest', ['modelId']); - request.modelId = defaultValue3; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteModel(request), expectedError); - }); + it('invokes patchModel with closed client', async () => { + const client = new modelserviceModule.v2.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.PatchModelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.PatchModelRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.PatchModelRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const defaultValue3 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.PatchModelRequest', + ['modelId'], + ); + request.modelId = defaultValue3; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.patchModel(request), expectedError); }); + }); - describe('listModels', () => { - it('invokes listModels without error', async () => { - const client = new modelserviceModule.v2.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.ListModelsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListModelsRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListModelsRequest', ['datasetId']); - request.datasetId = defaultValue2; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.bigquery.v2.Model()), - generateSampleMessage(new protos.google.cloud.bigquery.v2.Model()), - generateSampleMessage(new protos.google.cloud.bigquery.v2.Model()), - ]; - client.innerApiCalls.listModels = stubSimpleCall(expectedResponse); - const [response] = await client.listModels(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listModels as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listModels as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + describe('deleteModel', () => { + it('invokes deleteModel without error', async () => { + const client = new modelserviceModule.v2.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.DeleteModelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.DeleteModelRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.DeleteModelRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const defaultValue3 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.DeleteModelRequest', + ['modelId'], + ); + request.modelId = defaultValue3; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}&model_id=${defaultValue3 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteModel = stubSimpleCall(expectedResponse); + const [response] = await client.deleteModel(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteModel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteModel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listModels without error using callback', async () => { - const client = new modelserviceModule.v2.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.ListModelsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListModelsRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListModelsRequest', ['datasetId']); - request.datasetId = defaultValue2; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.bigquery.v2.Model()), - generateSampleMessage(new protos.google.cloud.bigquery.v2.Model()), - generateSampleMessage(new protos.google.cloud.bigquery.v2.Model()), - ]; - client.innerApiCalls.listModels = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listModels( - request, - (err?: Error|null, result?: protos.google.cloud.bigquery.v2.IModel[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listModels as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listModels as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteModel without error using callback', async () => { + const client = new modelserviceModule.v2.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.DeleteModelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.DeleteModelRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.DeleteModelRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const defaultValue3 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.DeleteModelRequest', + ['modelId'], + ); + request.modelId = defaultValue3; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}&model_id=${defaultValue3 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteModel = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteModel( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteModel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteModel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listModels with error', async () => { - const client = new modelserviceModule.v2.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.ListModelsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListModelsRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListModelsRequest', ['datasetId']); - request.datasetId = defaultValue2; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listModels = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listModels(request), expectedError); - const actualRequest = (client.innerApiCalls.listModels as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listModels as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteModel with error', async () => { + const client = new modelserviceModule.v2.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.DeleteModelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.DeleteModelRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.DeleteModelRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const defaultValue3 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.DeleteModelRequest', + ['modelId'], + ); + request.modelId = defaultValue3; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}&model_id=${defaultValue3 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteModel = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.deleteModel(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteModel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteModel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listModelsStream without error', async () => { - const client = new modelserviceModule.v2.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.ListModelsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListModelsRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListModelsRequest', ['datasetId']); - request.datasetId = defaultValue2; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.bigquery.v2.Model()), - generateSampleMessage(new protos.google.cloud.bigquery.v2.Model()), - generateSampleMessage(new protos.google.cloud.bigquery.v2.Model()), - ]; - client.descriptors.page.listModels.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listModelsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.cloud.bigquery.v2.Model[] = []; - stream.on('data', (response: protos.google.cloud.bigquery.v2.Model) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.listModels.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listModels, request)); - assert( - (client.descriptors.page.listModels.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes deleteModel with closed client', async () => { + const client = new modelserviceModule.v2.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.DeleteModelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.DeleteModelRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.DeleteModelRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const defaultValue3 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.DeleteModelRequest', + ['modelId'], + ); + request.modelId = defaultValue3; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.deleteModel(request), expectedError); + }); + }); - it('invokes listModelsStream with error', async () => { - const client = new modelserviceModule.v2.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.ListModelsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListModelsRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListModelsRequest', ['datasetId']); - request.datasetId = defaultValue2; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listModels.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listModelsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.cloud.bigquery.v2.Model[] = []; - stream.on('data', (response: protos.google.cloud.bigquery.v2.Model) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listModels.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listModels, request)); - assert( - (client.descriptors.page.listModels.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + describe('listModels', () => { + it('invokes listModels without error', async () => { + const client = new modelserviceModule.v2.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListModelsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListModelsRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListModelsRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.bigquery.v2.Model()), + generateSampleMessage(new protos.google.cloud.bigquery.v2.Model()), + generateSampleMessage(new protos.google.cloud.bigquery.v2.Model()), + ]; + client.innerApiCalls.listModels = stubSimpleCall(expectedResponse); + const [response] = await client.listModels(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listModels as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listModels as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('uses async iteration with listModels without error', async () => { - const client = new modelserviceModule.v2.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.ListModelsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListModelsRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListModelsRequest', ['datasetId']); - request.datasetId = defaultValue2; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.bigquery.v2.Model()), - generateSampleMessage(new protos.google.cloud.bigquery.v2.Model()), - generateSampleMessage(new protos.google.cloud.bigquery.v2.Model()), - ]; - client.descriptors.page.listModels.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.cloud.bigquery.v2.IModel[] = []; - const iterable = client.listModelsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); + it('invokes listModels without error using callback', async () => { + const client = new modelserviceModule.v2.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListModelsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListModelsRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListModelsRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.bigquery.v2.Model()), + generateSampleMessage(new protos.google.cloud.bigquery.v2.Model()), + generateSampleMessage(new protos.google.cloud.bigquery.v2.Model()), + ]; + client.innerApiCalls.listModels = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listModels( + request, + ( + err?: Error | null, + result?: protos.google.cloud.bigquery.v2.IModel[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listModels.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listModels.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listModels as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listModels as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listModels with error', async () => { + const client = new modelserviceModule.v2.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListModelsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListModelsRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListModelsRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listModels = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listModels(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listModels as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listModels as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listModelsStream without error', async () => { + const client = new modelserviceModule.v2.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListModelsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListModelsRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListModelsRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.bigquery.v2.Model()), + generateSampleMessage(new protos.google.cloud.bigquery.v2.Model()), + generateSampleMessage(new protos.google.cloud.bigquery.v2.Model()), + ]; + client.descriptors.page.listModels.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listModelsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.cloud.bigquery.v2.Model[] = []; + stream.on('data', (response: protos.google.cloud.bigquery.v2.Model) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listModels.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listModels, request), + ); + assert( + (client.descriptors.page.listModels.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('uses async iteration with listModels with error', async () => { - const client = new modelserviceModule.v2.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.ListModelsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListModelsRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListModelsRequest', ['datasetId']); - request.datasetId = defaultValue2; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listModels.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listModelsAsync(request); - await assert.rejects(async () => { - const responses: protos.google.cloud.bigquery.v2.IModel[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listModels.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listModels.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); + it('invokes listModelsStream with error', async () => { + const client = new modelserviceModule.v2.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListModelsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListModelsRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListModelsRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listModels.createStream = stubPageStreamingCall( + undefined, + expectedError, + ); + const stream = client.listModelsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.cloud.bigquery.v2.Model[] = []; + stream.on('data', (response: protos.google.cloud.bigquery.v2.Model) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listModels.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listModels, request), + ); + assert( + (client.descriptors.page.listModels.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + + it('uses async iteration with listModels without error', async () => { + const client = new modelserviceModule.v2.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListModelsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListModelsRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListModelsRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.bigquery.v2.Model()), + generateSampleMessage(new protos.google.cloud.bigquery.v2.Model()), + generateSampleMessage(new protos.google.cloud.bigquery.v2.Model()), + ]; + client.descriptors.page.listModels.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.cloud.bigquery.v2.IModel[] = []; + const iterable = client.listModelsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + (client.descriptors.page.listModels.asyncIterate as SinonStub).getCall( + 0, + ).args[1], + request, + ); + assert( + (client.descriptors.page.listModels.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + + it('uses async iteration with listModels with error', async () => { + const client = new modelserviceModule.v2.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListModelsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListModelsRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListModelsRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listModels.asyncIterate = stubAsyncIterationCall( + undefined, + expectedError, + ); + const iterable = client.listModelsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.cloud.bigquery.v2.IModel[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + (client.descriptors.page.listModels.asyncIterate as SinonStub).getCall( + 0, + ).args[1], + request, + ); + assert( + (client.descriptors.page.listModels.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); }); + }); }); diff --git a/core/generator/gapic-generator-typescript/baselines/bigquery-v2-esm/esm/test/gapic_project_service_v2.ts.baseline b/core/generator/gapic-generator-typescript/baselines/bigquery-v2-esm/esm/test/gapic_project_service_v2.ts.baseline index 1c8e45afa4b4..be652dbbb943 100644 --- a/core/generator/gapic-generator-typescript/baselines/bigquery-v2-esm/esm/test/gapic_project_service_v2.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/bigquery-v2-esm/esm/test/gapic_project_service_v2.ts.baseline @@ -20,14 +20,14 @@ import * as protos from '../../protos/protos.js'; import assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as projectserviceModule from '../src/index.js'; -import {protobuf} from 'google-gax'; +import { protobuf } from 'google-gax'; import fs from 'fs'; import path from 'path'; -import {fileURLToPath} from 'url'; +import { fileURLToPath } from 'url'; // @ts-ignore const dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -35,297 +35,365 @@ const dirname = path.dirname(fileURLToPath(import.meta.url)); // to fill in default values for request objects const root = protobuf.Root.fromJSON( JSON.parse( - fs.readFileSync(path.join(dirname, '..', '..', 'protos/protos.json'), 'utf8') - )) + fs.readFileSync( + path.join(dirname, '..', '..', 'protos/protos.json'), + 'utf8', + ), + ), +); // eslint-disable-next-line @typescript-eslint/no-unused-vars function getTypeDefaultValue(typeName: string, fields: string[]) { - let type = root.lookupType(typeName) as protobuf.Type; - for (const field of fields.slice(0, -1)) { - type = type?.fields[field]?.resolvedType as protobuf.Type; - } - return type?.fields[fields[fields.length - 1]]?.defaultValue ?? null; + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type?.fields[field]?.resolvedType as protobuf.Type; + } + return type?.fields[fields[fields.length - 1]]?.defaultValue ?? null; } function generateSampleMessage(instance: T) { - const filledObject = (instance.constructor as typeof protobuf.Message) - .toObject(instance as protobuf.Message, {defaults: true}); - return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, { defaults: true }); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; } function stubSimpleCall(response?: ResponseType, error?: Error) { - return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); } -function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { - return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +function stubSimpleCallWithCallback( + response?: ResponseType, + error?: Error, +) { + return error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); } describe('v2.ProjectServiceClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new projectserviceModule.v2.ProjectServiceClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'bigquery.googleapis.com'); - }); - - it('has universeDomain', () => { - const client = new projectserviceModule.v2.ProjectServiceClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new projectserviceModule.v2.ProjectServiceClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'bigquery.googleapis.com'); + }); - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - it('throws DeprecationWarning if static servicePath is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const servicePath = projectserviceModule.v2.ProjectServiceClient.servicePath; - assert.strictEqual(servicePath, 'bigquery.googleapis.com'); - assert(stub.called); - stub.restore(); - }); + it('has universeDomain', () => { + const client = new projectserviceModule.v2.ProjectServiceClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = projectserviceModule.v2.ProjectServiceClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'bigquery.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new projectserviceModule.v2.ProjectServiceClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'bigquery.example.com'); - }); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = + projectserviceModule.v2.ProjectServiceClient.servicePath; + assert.strictEqual(servicePath, 'bigquery.googleapis.com'); + assert(stub.called); + stub.restore(); + }); - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new projectserviceModule.v2.ProjectServiceClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'bigquery.example.com'); - }); + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + projectserviceModule.v2.ProjectServiceClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'bigquery.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = new projectserviceModule.v2.ProjectServiceClient({ + universeDomain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'bigquery.example.com'); + }); - if (typeof process === 'object' && 'env' in process) { - describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { - it('sets apiEndpoint from environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new projectserviceModule.v2.ProjectServiceClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'bigquery.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = new projectserviceModule.v2.ProjectServiceClient({ + universe_domain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'bigquery.example.com'); + }); - it('value configured in code has priority over environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new projectserviceModule.v2.ProjectServiceClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'bigquery.configured.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { new projectserviceModule.v2.ProjectServiceClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); + if (typeof process === 'object' && 'env' in process) { + describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { + it('sets apiEndpoint from environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new projectserviceModule.v2.ProjectServiceClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'bigquery.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - it('has port', () => { - const port = projectserviceModule.v2.ProjectServiceClient.port; - assert(port); - assert(typeof port === 'number'); + it('value configured in code has priority over environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new projectserviceModule.v2.ProjectServiceClient({ + universeDomain: 'configured.example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'bigquery.configured.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - - it('should create a client with no option', () => { - const client = new projectserviceModule.v2.ProjectServiceClient(); - assert(client); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new projectserviceModule.v2.ProjectServiceClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); + }); - it('should create a client with gRPC fallback', () => { - const client = new projectserviceModule.v2.ProjectServiceClient({ - fallback: true, - }); - assert(client); - }); + it('has port', () => { + const port = projectserviceModule.v2.ProjectServiceClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('has initialize method and supports deferred initialization', async () => { - const client = new projectserviceModule.v2.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.projectServiceStub, undefined); - await client.initialize(); - assert(client.projectServiceStub); - }); + it('should create a client with no option', () => { + const client = new projectserviceModule.v2.ProjectServiceClient(); + assert(client); + }); - it('has close method for the initialized client', done => { - const client = new projectserviceModule.v2.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.projectServiceStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('should create a client with gRPC fallback', () => { + const client = new projectserviceModule.v2.ProjectServiceClient({ + fallback: true, + }); + assert(client); + }); - it('has close method for the non-initialized client', done => { - const client = new projectserviceModule.v2.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.projectServiceStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('has initialize method and supports deferred initialization', async () => { + const client = new projectserviceModule.v2.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.projectServiceStub, undefined); + await client.initialize(); + assert(client.projectServiceStub); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new projectserviceModule.v2.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + it('has close method for the initialized client', (done) => { + const client = new projectserviceModule.v2.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.projectServiceStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new projectserviceModule.v2.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId((err?: Error|null, projectId?: string|null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } - }); - }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); + it('has close method for the non-initialized client', (done) => { + const client = new projectserviceModule.v2.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.projectServiceStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); }); - describe('getServiceAccount', () => { - it('invokes getServiceAccount without error', async () => { - const client = new projectserviceModule.v2.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.GetServiceAccountRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetServiceAccountRequest', ['projectId']); - request.projectId = defaultValue1; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.bigquery.v2.GetServiceAccountResponse() - ); - client.innerApiCalls.getServiceAccount = stubSimpleCall(expectedResponse); - const [response] = await client.getServiceAccount(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getServiceAccount as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getServiceAccount as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new projectserviceModule.v2.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + }); - it('invokes getServiceAccount without error using callback', async () => { - const client = new projectserviceModule.v2.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.GetServiceAccountRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetServiceAccountRequest', ['projectId']); - request.projectId = defaultValue1; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.bigquery.v2.GetServiceAccountResponse() - ); - client.innerApiCalls.getServiceAccount = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getServiceAccount( - request, - (err?: Error|null, result?: protos.google.cloud.bigquery.v2.IGetServiceAccountResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getServiceAccount as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getServiceAccount as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new projectserviceModule.v2.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + }); - it('invokes getServiceAccount with error', async () => { - const client = new projectserviceModule.v2.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.GetServiceAccountRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetServiceAccountRequest', ['projectId']); - request.projectId = defaultValue1; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getServiceAccount = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getServiceAccount(request), expectedError); - const actualRequest = (client.innerApiCalls.getServiceAccount as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getServiceAccount as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + describe('getServiceAccount', () => { + it('invokes getServiceAccount without error', async () => { + const client = new projectserviceModule.v2.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.GetServiceAccountRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetServiceAccountRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.bigquery.v2.GetServiceAccountResponse(), + ); + client.innerApiCalls.getServiceAccount = stubSimpleCall(expectedResponse); + const [response] = await client.getServiceAccount(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getServiceAccount as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getServiceAccount as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getServiceAccount with closed client', async () => { - const client = new projectserviceModule.v2.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.GetServiceAccountRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetServiceAccountRequest', ['projectId']); - request.projectId = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getServiceAccount(request), expectedError); - }); + it('invokes getServiceAccount without error using callback', async () => { + const client = new projectserviceModule.v2.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.GetServiceAccountRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetServiceAccountRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.bigquery.v2.GetServiceAccountResponse(), + ); + client.innerApiCalls.getServiceAccount = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getServiceAccount( + request, + ( + err?: Error | null, + result?: protos.google.cloud.bigquery.v2.IGetServiceAccountResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getServiceAccount as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getServiceAccount as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getServiceAccount with error', async () => { + const client = new projectserviceModule.v2.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.GetServiceAccountRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetServiceAccountRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getServiceAccount = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getServiceAccount(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getServiceAccount as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getServiceAccount as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getServiceAccount with closed client', async () => { + const client = new projectserviceModule.v2.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.GetServiceAccountRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetServiceAccountRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getServiceAccount(request), expectedError); }); + }); }); diff --git a/core/generator/gapic-generator-typescript/baselines/bigquery-v2-esm/esm/test/gapic_routine_service_v2.ts.baseline b/core/generator/gapic-generator-typescript/baselines/bigquery-v2-esm/esm/test/gapic_routine_service_v2.ts.baseline index d27f1fedb882..0fa216d4e419 100644 --- a/core/generator/gapic-generator-typescript/baselines/bigquery-v2-esm/esm/test/gapic_routine_service_v2.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/bigquery-v2-esm/esm/test/gapic_routine_service_v2.ts.baseline @@ -20,16 +20,16 @@ import * as protos from '../../protos/protos.js'; import assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as routineserviceModule from '../src/index.js'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; -import {protobuf} from 'google-gax'; +import { protobuf } from 'google-gax'; import fs from 'fs'; import path from 'path'; -import {fileURLToPath} from 'url'; +import { fileURLToPath } from 'url'; // @ts-ignore const dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -37,1091 +37,1385 @@ const dirname = path.dirname(fileURLToPath(import.meta.url)); // to fill in default values for request objects const root = protobuf.Root.fromJSON( JSON.parse( - fs.readFileSync(path.join(dirname, '..', '..', 'protos/protos.json'), 'utf8') - )) + fs.readFileSync( + path.join(dirname, '..', '..', 'protos/protos.json'), + 'utf8', + ), + ), +); // eslint-disable-next-line @typescript-eslint/no-unused-vars function getTypeDefaultValue(typeName: string, fields: string[]) { - let type = root.lookupType(typeName) as protobuf.Type; - for (const field of fields.slice(0, -1)) { - type = type?.fields[field]?.resolvedType as protobuf.Type; - } - return type?.fields[fields[fields.length - 1]]?.defaultValue ?? null; + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type?.fields[field]?.resolvedType as protobuf.Type; + } + return type?.fields[fields[fields.length - 1]]?.defaultValue ?? null; } function generateSampleMessage(instance: T) { - const filledObject = (instance.constructor as typeof protobuf.Message) - .toObject(instance as protobuf.Message, {defaults: true}); - return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, { defaults: true }); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; } function stubSimpleCall(response?: ResponseType, error?: Error) { - return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); } -function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { - return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +function stubSimpleCallWithCallback( + response?: ResponseType, + error?: Error, +) { + return error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); } -function stubPageStreamingCall(responses?: ResponseType[], error?: Error) { - const pagingStub = sinon.stub(); - if (responses) { - for (let i = 0; i < responses.length; ++i) { - pagingStub.onCall(i).callsArgWith(2, null, responses[i]); - } +function stubPageStreamingCall( + responses?: ResponseType[], + error?: Error, +) { + const pagingStub = sinon.stub(); + if (responses) { + for (let i = 0; i < responses.length; ++i) { + pagingStub.onCall(i).callsArgWith(2, null, responses[i]); } - const transformStub = error ? sinon.stub().callsArgWith(2, error) : pagingStub; - const mockStream = new PassThrough({ - objectMode: true, - transform: transformStub, - }); - // trigger as many responses as needed - if (responses) { - for (let i = 0; i < responses.length; ++i) { - setImmediate(() => { mockStream.write({}); }); - } - setImmediate(() => { mockStream.end(); }); - } else { - setImmediate(() => { mockStream.write({}); }); - setImmediate(() => { mockStream.end(); }); + } + const transformStub = error + ? sinon.stub().callsArgWith(2, error) + : pagingStub; + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + // trigger as many responses as needed + if (responses) { + for (let i = 0; i < responses.length; ++i) { + setImmediate(() => { + mockStream.write({}); + }); } - return sinon.stub().returns(mockStream); + setImmediate(() => { + mockStream.end(); + }); + } else { + setImmediate(() => { + mockStream.write({}); + }); + setImmediate(() => { + mockStream.end(); + }); + } + return sinon.stub().returns(mockStream); } -function stubAsyncIterationCall(responses?: ResponseType[], error?: Error) { - let counter = 0; - const asyncIterable = { - [Symbol.asyncIterator]() { - return { - async next() { - if (error) { - return Promise.reject(error); - } - if (counter >= responses!.length) { - return Promise.resolve({done: true, value: undefined}); - } - return Promise.resolve({done: false, value: responses![counter++]}); - } - }; - } - }; - return sinon.stub().returns(asyncIterable); +function stubAsyncIterationCall( + responses?: ResponseType[], + error?: Error, +) { + let counter = 0; + const asyncIterable = { + [Symbol.asyncIterator]() { + return { + async next() { + if (error) { + return Promise.reject(error); + } + if (counter >= responses!.length) { + return Promise.resolve({ done: true, value: undefined }); + } + return Promise.resolve({ done: false, value: responses![counter++] }); + }, + }; + }, + }; + return sinon.stub().returns(asyncIterable); } describe('v2.RoutineServiceClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new routineserviceModule.v2.RoutineServiceClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'bigquery.googleapis.com'); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new routineserviceModule.v2.RoutineServiceClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'bigquery.googleapis.com'); + }); - it('has universeDomain', () => { - const client = new routineserviceModule.v2.RoutineServiceClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); + it('has universeDomain', () => { + const client = new routineserviceModule.v2.RoutineServiceClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - it('throws DeprecationWarning if static servicePath is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const servicePath = routineserviceModule.v2.RoutineServiceClient.servicePath; - assert.strictEqual(servicePath, 'bigquery.googleapis.com'); - assert(stub.called); - stub.restore(); - }); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = + routineserviceModule.v2.RoutineServiceClient.servicePath; + assert.strictEqual(servicePath, 'bigquery.googleapis.com'); + assert(stub.called); + stub.restore(); + }); - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = routineserviceModule.v2.RoutineServiceClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'bigquery.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new routineserviceModule.v2.RoutineServiceClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'bigquery.example.com'); + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + routineserviceModule.v2.RoutineServiceClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'bigquery.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = new routineserviceModule.v2.RoutineServiceClient({ + universeDomain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'bigquery.example.com'); + }); + + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = new routineserviceModule.v2.RoutineServiceClient({ + universe_domain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'bigquery.example.com'); + }); + + if (typeof process === 'object' && 'env' in process) { + describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { + it('sets apiEndpoint from environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new routineserviceModule.v2.RoutineServiceClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'bigquery.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new routineserviceModule.v2.RoutineServiceClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'bigquery.example.com'); + it('value configured in code has priority over environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new routineserviceModule.v2.RoutineServiceClient({ + universeDomain: 'configured.example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'bigquery.configured.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new routineserviceModule.v2.RoutineServiceClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', + }); + }); + }); - if (typeof process === 'object' && 'env' in process) { - describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { - it('sets apiEndpoint from environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new routineserviceModule.v2.RoutineServiceClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'bigquery.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); + it('has port', () => { + const port = routineserviceModule.v2.RoutineServiceClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('value configured in code has priority over environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new routineserviceModule.v2.RoutineServiceClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'bigquery.configured.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { new routineserviceModule.v2.RoutineServiceClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); + it('should create a client with no option', () => { + const client = new routineserviceModule.v2.RoutineServiceClient(); + assert(client); + }); - it('has port', () => { - const port = routineserviceModule.v2.RoutineServiceClient.port; - assert(port); - assert(typeof port === 'number'); - }); + it('should create a client with gRPC fallback', () => { + const client = new routineserviceModule.v2.RoutineServiceClient({ + fallback: true, + }); + assert(client); + }); - it('should create a client with no option', () => { - const client = new routineserviceModule.v2.RoutineServiceClient(); - assert(client); - }); + it('has initialize method and supports deferred initialization', async () => { + const client = new routineserviceModule.v2.RoutineServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.routineServiceStub, undefined); + await client.initialize(); + assert(client.routineServiceStub); + }); - it('should create a client with gRPC fallback', () => { - const client = new routineserviceModule.v2.RoutineServiceClient({ - fallback: true, - }); - assert(client); + it('has close method for the initialized client', (done) => { + const client = new routineserviceModule.v2.RoutineServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.routineServiceStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('has initialize method and supports deferred initialization', async () => { - const client = new routineserviceModule.v2.RoutineServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.routineServiceStub, undefined); - await client.initialize(); - assert(client.routineServiceStub); + it('has close method for the non-initialized client', (done) => { + const client = new routineserviceModule.v2.RoutineServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.routineServiceStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('has close method for the initialized client', done => { - const client = new routineserviceModule.v2.RoutineServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.routineServiceStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new routineserviceModule.v2.RoutineServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + }); - it('has close method for the non-initialized client', done => { - const client = new routineserviceModule.v2.RoutineServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.routineServiceStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new routineserviceModule.v2.RoutineServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new routineserviceModule.v2.RoutineServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); - }); + describe('getRoutine', () => { + it('invokes getRoutine without error', async () => { + const client = new routineserviceModule.v2.RoutineServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.GetRoutineRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetRoutineRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetRoutineRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const defaultValue3 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetRoutineRequest', + ['routineId'], + ); + request.routineId = defaultValue3; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}&routine_id=${defaultValue3 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.bigquery.v2.Routine(), + ); + client.innerApiCalls.getRoutine = stubSimpleCall(expectedResponse); + const [response] = await client.getRoutine(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getRoutine as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getRoutine as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new routineserviceModule.v2.RoutineServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId((err?: Error|null, projectId?: string|null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } - }); - }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); - }); + it('invokes getRoutine without error using callback', async () => { + const client = new routineserviceModule.v2.RoutineServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.GetRoutineRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetRoutineRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetRoutineRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const defaultValue3 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetRoutineRequest', + ['routineId'], + ); + request.routineId = defaultValue3; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}&routine_id=${defaultValue3 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.bigquery.v2.Routine(), + ); + client.innerApiCalls.getRoutine = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getRoutine( + request, + ( + err?: Error | null, + result?: protos.google.cloud.bigquery.v2.IRoutine | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getRoutine as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getRoutine as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('getRoutine', () => { - it('invokes getRoutine without error', async () => { - const client = new routineserviceModule.v2.RoutineServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.GetRoutineRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetRoutineRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetRoutineRequest', ['datasetId']); - request.datasetId = defaultValue2; - const defaultValue3 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetRoutineRequest', ['routineId']); - request.routineId = defaultValue3; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }&routine_id=${defaultValue3 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.bigquery.v2.Routine() - ); - client.innerApiCalls.getRoutine = stubSimpleCall(expectedResponse); - const [response] = await client.getRoutine(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getRoutine as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getRoutine as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getRoutine with error', async () => { + const client = new routineserviceModule.v2.RoutineServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.GetRoutineRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetRoutineRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetRoutineRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const defaultValue3 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetRoutineRequest', + ['routineId'], + ); + request.routineId = defaultValue3; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}&routine_id=${defaultValue3 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getRoutine = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getRoutine(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getRoutine as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getRoutine as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getRoutine without error using callback', async () => { - const client = new routineserviceModule.v2.RoutineServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.GetRoutineRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetRoutineRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetRoutineRequest', ['datasetId']); - request.datasetId = defaultValue2; - const defaultValue3 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetRoutineRequest', ['routineId']); - request.routineId = defaultValue3; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }&routine_id=${defaultValue3 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.bigquery.v2.Routine() - ); - client.innerApiCalls.getRoutine = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getRoutine( - request, - (err?: Error|null, result?: protos.google.cloud.bigquery.v2.IRoutine|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getRoutine as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getRoutine as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getRoutine with closed client', async () => { + const client = new routineserviceModule.v2.RoutineServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.GetRoutineRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetRoutineRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetRoutineRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const defaultValue3 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetRoutineRequest', + ['routineId'], + ); + request.routineId = defaultValue3; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getRoutine(request), expectedError); + }); + }); - it('invokes getRoutine with error', async () => { - const client = new routineserviceModule.v2.RoutineServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.GetRoutineRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetRoutineRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetRoutineRequest', ['datasetId']); - request.datasetId = defaultValue2; - const defaultValue3 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetRoutineRequest', ['routineId']); - request.routineId = defaultValue3; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }&routine_id=${defaultValue3 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getRoutine = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getRoutine(request), expectedError); - const actualRequest = (client.innerApiCalls.getRoutine as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getRoutine as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + describe('insertRoutine', () => { + it('invokes insertRoutine without error', async () => { + const client = new routineserviceModule.v2.RoutineServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.InsertRoutineRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.InsertRoutineRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.InsertRoutineRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.bigquery.v2.Routine(), + ); + client.innerApiCalls.insertRoutine = stubSimpleCall(expectedResponse); + const [response] = await client.insertRoutine(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.insertRoutine as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.insertRoutine as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getRoutine with closed client', async () => { - const client = new routineserviceModule.v2.RoutineServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.GetRoutineRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetRoutineRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetRoutineRequest', ['datasetId']); - request.datasetId = defaultValue2; - const defaultValue3 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetRoutineRequest', ['routineId']); - request.routineId = defaultValue3; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getRoutine(request), expectedError); - }); + it('invokes insertRoutine without error using callback', async () => { + const client = new routineserviceModule.v2.RoutineServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.InsertRoutineRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.InsertRoutineRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.InsertRoutineRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.bigquery.v2.Routine(), + ); + client.innerApiCalls.insertRoutine = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.insertRoutine( + request, + ( + err?: Error | null, + result?: protos.google.cloud.bigquery.v2.IRoutine | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.insertRoutine as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.insertRoutine as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('insertRoutine', () => { - it('invokes insertRoutine without error', async () => { - const client = new routineserviceModule.v2.RoutineServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.InsertRoutineRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.InsertRoutineRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.InsertRoutineRequest', ['datasetId']); - request.datasetId = defaultValue2; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.bigquery.v2.Routine() - ); - client.innerApiCalls.insertRoutine = stubSimpleCall(expectedResponse); - const [response] = await client.insertRoutine(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.insertRoutine as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.insertRoutine as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes insertRoutine with error', async () => { + const client = new routineserviceModule.v2.RoutineServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.InsertRoutineRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.InsertRoutineRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.InsertRoutineRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.insertRoutine = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.insertRoutine(request), expectedError); + const actualRequest = ( + client.innerApiCalls.insertRoutine as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.insertRoutine as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes insertRoutine without error using callback', async () => { - const client = new routineserviceModule.v2.RoutineServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.InsertRoutineRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.InsertRoutineRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.InsertRoutineRequest', ['datasetId']); - request.datasetId = defaultValue2; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.bigquery.v2.Routine() - ); - client.innerApiCalls.insertRoutine = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.insertRoutine( - request, - (err?: Error|null, result?: protos.google.cloud.bigquery.v2.IRoutine|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.insertRoutine as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.insertRoutine as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes insertRoutine with closed client', async () => { + const client = new routineserviceModule.v2.RoutineServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.InsertRoutineRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.InsertRoutineRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.InsertRoutineRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.insertRoutine(request), expectedError); + }); + }); - it('invokes insertRoutine with error', async () => { - const client = new routineserviceModule.v2.RoutineServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.InsertRoutineRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.InsertRoutineRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.InsertRoutineRequest', ['datasetId']); - request.datasetId = defaultValue2; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.insertRoutine = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.insertRoutine(request), expectedError); - const actualRequest = (client.innerApiCalls.insertRoutine as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.insertRoutine as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + describe('updateRoutine', () => { + it('invokes updateRoutine without error', async () => { + const client = new routineserviceModule.v2.RoutineServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.UpdateRoutineRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.UpdateRoutineRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.UpdateRoutineRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const defaultValue3 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.UpdateRoutineRequest', + ['routineId'], + ); + request.routineId = defaultValue3; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}&routine_id=${defaultValue3 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.bigquery.v2.Routine(), + ); + client.innerApiCalls.updateRoutine = stubSimpleCall(expectedResponse); + const [response] = await client.updateRoutine(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateRoutine as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateRoutine as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes insertRoutine with closed client', async () => { - const client = new routineserviceModule.v2.RoutineServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.InsertRoutineRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.InsertRoutineRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.InsertRoutineRequest', ['datasetId']); - request.datasetId = defaultValue2; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.insertRoutine(request), expectedError); - }); + it('invokes updateRoutine without error using callback', async () => { + const client = new routineserviceModule.v2.RoutineServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.UpdateRoutineRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.UpdateRoutineRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.UpdateRoutineRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const defaultValue3 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.UpdateRoutineRequest', + ['routineId'], + ); + request.routineId = defaultValue3; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}&routine_id=${defaultValue3 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.bigquery.v2.Routine(), + ); + client.innerApiCalls.updateRoutine = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateRoutine( + request, + ( + err?: Error | null, + result?: protos.google.cloud.bigquery.v2.IRoutine | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateRoutine as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateRoutine as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('updateRoutine', () => { - it('invokes updateRoutine without error', async () => { - const client = new routineserviceModule.v2.RoutineServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.UpdateRoutineRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.UpdateRoutineRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.UpdateRoutineRequest', ['datasetId']); - request.datasetId = defaultValue2; - const defaultValue3 = - getTypeDefaultValue('.google.cloud.bigquery.v2.UpdateRoutineRequest', ['routineId']); - request.routineId = defaultValue3; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }&routine_id=${defaultValue3 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.bigquery.v2.Routine() - ); - client.innerApiCalls.updateRoutine = stubSimpleCall(expectedResponse); - const [response] = await client.updateRoutine(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateRoutine as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateRoutine as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateRoutine with error', async () => { + const client = new routineserviceModule.v2.RoutineServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.UpdateRoutineRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.UpdateRoutineRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.UpdateRoutineRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const defaultValue3 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.UpdateRoutineRequest', + ['routineId'], + ); + request.routineId = defaultValue3; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}&routine_id=${defaultValue3 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateRoutine = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.updateRoutine(request), expectedError); + const actualRequest = ( + client.innerApiCalls.updateRoutine as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateRoutine as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateRoutine without error using callback', async () => { - const client = new routineserviceModule.v2.RoutineServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.UpdateRoutineRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.UpdateRoutineRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.UpdateRoutineRequest', ['datasetId']); - request.datasetId = defaultValue2; - const defaultValue3 = - getTypeDefaultValue('.google.cloud.bigquery.v2.UpdateRoutineRequest', ['routineId']); - request.routineId = defaultValue3; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }&routine_id=${defaultValue3 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.bigquery.v2.Routine() - ); - client.innerApiCalls.updateRoutine = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateRoutine( - request, - (err?: Error|null, result?: protos.google.cloud.bigquery.v2.IRoutine|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateRoutine as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateRoutine as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateRoutine with closed client', async () => { + const client = new routineserviceModule.v2.RoutineServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.UpdateRoutineRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.UpdateRoutineRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.UpdateRoutineRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const defaultValue3 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.UpdateRoutineRequest', + ['routineId'], + ); + request.routineId = defaultValue3; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.updateRoutine(request), expectedError); + }); + }); - it('invokes updateRoutine with error', async () => { - const client = new routineserviceModule.v2.RoutineServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.UpdateRoutineRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.UpdateRoutineRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.UpdateRoutineRequest', ['datasetId']); - request.datasetId = defaultValue2; - const defaultValue3 = - getTypeDefaultValue('.google.cloud.bigquery.v2.UpdateRoutineRequest', ['routineId']); - request.routineId = defaultValue3; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }&routine_id=${defaultValue3 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateRoutine = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateRoutine(request), expectedError); - const actualRequest = (client.innerApiCalls.updateRoutine as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateRoutine as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + describe('patchRoutine', () => { + it('invokes patchRoutine without error', async () => { + const client = new routineserviceModule.v2.RoutineServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.PatchRoutineRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.cloud.bigquery.v2.Routine(), + ); + client.innerApiCalls.patchRoutine = stubSimpleCall(expectedResponse); + const [response] = await client.patchRoutine(request); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes updateRoutine with closed client', async () => { - const client = new routineserviceModule.v2.RoutineServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.UpdateRoutineRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.UpdateRoutineRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.UpdateRoutineRequest', ['datasetId']); - request.datasetId = defaultValue2; - const defaultValue3 = - getTypeDefaultValue('.google.cloud.bigquery.v2.UpdateRoutineRequest', ['routineId']); - request.routineId = defaultValue3; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateRoutine(request), expectedError); - }); + it('invokes patchRoutine without error using callback', async () => { + const client = new routineserviceModule.v2.RoutineServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.PatchRoutineRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.cloud.bigquery.v2.Routine(), + ); + client.innerApiCalls.patchRoutine = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.patchRoutine( + request, + ( + err?: Error | null, + result?: protos.google.cloud.bigquery.v2.IRoutine | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); }); - describe('patchRoutine', () => { - it('invokes patchRoutine without error', async () => { - const client = new routineserviceModule.v2.RoutineServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.PatchRoutineRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.cloud.bigquery.v2.Routine() - ); - client.innerApiCalls.patchRoutine = stubSimpleCall(expectedResponse); - const [response] = await client.patchRoutine(request); - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes patchRoutine with error', async () => { + const client = new routineserviceModule.v2.RoutineServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.PatchRoutineRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.patchRoutine = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.patchRoutine(request), expectedError); + }); - it('invokes patchRoutine without error using callback', async () => { - const client = new routineserviceModule.v2.RoutineServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.PatchRoutineRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.cloud.bigquery.v2.Routine() - ); - client.innerApiCalls.patchRoutine = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.patchRoutine( - request, - (err?: Error|null, result?: protos.google.cloud.bigquery.v2.IRoutine|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes patchRoutine with closed client', async () => { + const client = new routineserviceModule.v2.RoutineServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.PatchRoutineRequest(), + ); + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.patchRoutine(request), expectedError); + }); + }); - it('invokes patchRoutine with error', async () => { - const client = new routineserviceModule.v2.RoutineServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.PatchRoutineRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.patchRoutine = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.patchRoutine(request), expectedError); - }); + describe('deleteRoutine', () => { + it('invokes deleteRoutine without error', async () => { + const client = new routineserviceModule.v2.RoutineServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.DeleteRoutineRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.DeleteRoutineRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.DeleteRoutineRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const defaultValue3 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.DeleteRoutineRequest', + ['routineId'], + ); + request.routineId = defaultValue3; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}&routine_id=${defaultValue3 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteRoutine = stubSimpleCall(expectedResponse); + const [response] = await client.deleteRoutine(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteRoutine as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteRoutine as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes patchRoutine with closed client', async () => { - const client = new routineserviceModule.v2.RoutineServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.PatchRoutineRequest() - ); - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.patchRoutine(request), expectedError); - }); + it('invokes deleteRoutine without error using callback', async () => { + const client = new routineserviceModule.v2.RoutineServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.DeleteRoutineRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.DeleteRoutineRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.DeleteRoutineRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const defaultValue3 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.DeleteRoutineRequest', + ['routineId'], + ); + request.routineId = defaultValue3; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}&routine_id=${defaultValue3 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteRoutine = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteRoutine( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteRoutine as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteRoutine as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('deleteRoutine', () => { - it('invokes deleteRoutine without error', async () => { - const client = new routineserviceModule.v2.RoutineServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.DeleteRoutineRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.DeleteRoutineRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.DeleteRoutineRequest', ['datasetId']); - request.datasetId = defaultValue2; - const defaultValue3 = - getTypeDefaultValue('.google.cloud.bigquery.v2.DeleteRoutineRequest', ['routineId']); - request.routineId = defaultValue3; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }&routine_id=${defaultValue3 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteRoutine = stubSimpleCall(expectedResponse); - const [response] = await client.deleteRoutine(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteRoutine as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteRoutine as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteRoutine with error', async () => { + const client = new routineserviceModule.v2.RoutineServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.DeleteRoutineRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.DeleteRoutineRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.DeleteRoutineRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const defaultValue3 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.DeleteRoutineRequest', + ['routineId'], + ); + request.routineId = defaultValue3; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}&routine_id=${defaultValue3 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteRoutine = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.deleteRoutine(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteRoutine as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteRoutine as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteRoutine without error using callback', async () => { - const client = new routineserviceModule.v2.RoutineServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.DeleteRoutineRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.DeleteRoutineRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.DeleteRoutineRequest', ['datasetId']); - request.datasetId = defaultValue2; - const defaultValue3 = - getTypeDefaultValue('.google.cloud.bigquery.v2.DeleteRoutineRequest', ['routineId']); - request.routineId = defaultValue3; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }&routine_id=${defaultValue3 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteRoutine = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteRoutine( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteRoutine as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteRoutine as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteRoutine with closed client', async () => { + const client = new routineserviceModule.v2.RoutineServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.DeleteRoutineRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.DeleteRoutineRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.DeleteRoutineRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const defaultValue3 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.DeleteRoutineRequest', + ['routineId'], + ); + request.routineId = defaultValue3; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.deleteRoutine(request), expectedError); + }); + }); - it('invokes deleteRoutine with error', async () => { - const client = new routineserviceModule.v2.RoutineServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.DeleteRoutineRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.DeleteRoutineRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.DeleteRoutineRequest', ['datasetId']); - request.datasetId = defaultValue2; - const defaultValue3 = - getTypeDefaultValue('.google.cloud.bigquery.v2.DeleteRoutineRequest', ['routineId']); - request.routineId = defaultValue3; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }&routine_id=${defaultValue3 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteRoutine = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteRoutine(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteRoutine as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteRoutine as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + describe('listRoutines', () => { + it('invokes listRoutines without error', async () => { + const client = new routineserviceModule.v2.RoutineServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListRoutinesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListRoutinesRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListRoutinesRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.bigquery.v2.Routine()), + generateSampleMessage(new protos.google.cloud.bigquery.v2.Routine()), + generateSampleMessage(new protos.google.cloud.bigquery.v2.Routine()), + ]; + client.innerApiCalls.listRoutines = stubSimpleCall(expectedResponse); + const [response] = await client.listRoutines(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listRoutines as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listRoutines as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteRoutine with closed client', async () => { - const client = new routineserviceModule.v2.RoutineServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.DeleteRoutineRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.DeleteRoutineRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.DeleteRoutineRequest', ['datasetId']); - request.datasetId = defaultValue2; - const defaultValue3 = - getTypeDefaultValue('.google.cloud.bigquery.v2.DeleteRoutineRequest', ['routineId']); - request.routineId = defaultValue3; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteRoutine(request), expectedError); - }); + it('invokes listRoutines without error using callback', async () => { + const client = new routineserviceModule.v2.RoutineServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListRoutinesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListRoutinesRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListRoutinesRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.bigquery.v2.Routine()), + generateSampleMessage(new protos.google.cloud.bigquery.v2.Routine()), + generateSampleMessage(new protos.google.cloud.bigquery.v2.Routine()), + ]; + client.innerApiCalls.listRoutines = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listRoutines( + request, + ( + err?: Error | null, + result?: protos.google.cloud.bigquery.v2.IRoutine[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listRoutines as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listRoutines as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('listRoutines', () => { - it('invokes listRoutines without error', async () => { - const client = new routineserviceModule.v2.RoutineServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.ListRoutinesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListRoutinesRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListRoutinesRequest', ['datasetId']); - request.datasetId = defaultValue2; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.bigquery.v2.Routine()), - generateSampleMessage(new protos.google.cloud.bigquery.v2.Routine()), - generateSampleMessage(new protos.google.cloud.bigquery.v2.Routine()), - ]; - client.innerApiCalls.listRoutines = stubSimpleCall(expectedResponse); - const [response] = await client.listRoutines(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listRoutines as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listRoutines as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listRoutines with error', async () => { + const client = new routineserviceModule.v2.RoutineServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListRoutinesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListRoutinesRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListRoutinesRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listRoutines = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listRoutines(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listRoutines as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listRoutines as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listRoutines without error using callback', async () => { - const client = new routineserviceModule.v2.RoutineServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.ListRoutinesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListRoutinesRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListRoutinesRequest', ['datasetId']); - request.datasetId = defaultValue2; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.bigquery.v2.Routine()), - generateSampleMessage(new protos.google.cloud.bigquery.v2.Routine()), - generateSampleMessage(new protos.google.cloud.bigquery.v2.Routine()), - ]; - client.innerApiCalls.listRoutines = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listRoutines( - request, - (err?: Error|null, result?: protos.google.cloud.bigquery.v2.IRoutine[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listRoutines as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listRoutines as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes listRoutinesStream without error', async () => { + const client = new routineserviceModule.v2.RoutineServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListRoutinesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListRoutinesRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListRoutinesRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.bigquery.v2.Routine()), + generateSampleMessage(new protos.google.cloud.bigquery.v2.Routine()), + generateSampleMessage(new protos.google.cloud.bigquery.v2.Routine()), + ]; + client.descriptors.page.listRoutines.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listRoutinesStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.cloud.bigquery.v2.Routine[] = []; + stream.on( + 'data', + (response: protos.google.cloud.bigquery.v2.Routine) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); }); - - it('invokes listRoutines with error', async () => { - const client = new routineserviceModule.v2.RoutineServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.ListRoutinesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListRoutinesRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListRoutinesRequest', ['datasetId']); - request.datasetId = defaultValue2; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listRoutines = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listRoutines(request), expectedError); - const actualRequest = (client.innerApiCalls.listRoutines as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listRoutines as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + stream.on('error', (err: Error) => { + reject(err); }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listRoutines.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listRoutines, request), + ); + assert( + (client.descriptors.page.listRoutines.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('invokes listRoutinesStream without error', async () => { - const client = new routineserviceModule.v2.RoutineServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.ListRoutinesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListRoutinesRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListRoutinesRequest', ['datasetId']); - request.datasetId = defaultValue2; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.bigquery.v2.Routine()), - generateSampleMessage(new protos.google.cloud.bigquery.v2.Routine()), - generateSampleMessage(new protos.google.cloud.bigquery.v2.Routine()), - ]; - client.descriptors.page.listRoutines.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listRoutinesStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.cloud.bigquery.v2.Routine[] = []; - stream.on('data', (response: protos.google.cloud.bigquery.v2.Routine) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.listRoutines.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listRoutines, request)); - assert( - (client.descriptors.page.listRoutines.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); + it('invokes listRoutinesStream with error', async () => { + const client = new routineserviceModule.v2.RoutineServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListRoutinesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListRoutinesRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListRoutinesRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listRoutines.createStream = stubPageStreamingCall( + undefined, + expectedError, + ); + const stream = client.listRoutinesStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.cloud.bigquery.v2.Routine[] = []; + stream.on( + 'data', + (response: protos.google.cloud.bigquery.v2.Routine) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); }); - - it('invokes listRoutinesStream with error', async () => { - const client = new routineserviceModule.v2.RoutineServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.ListRoutinesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListRoutinesRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListRoutinesRequest', ['datasetId']); - request.datasetId = defaultValue2; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listRoutines.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listRoutinesStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.cloud.bigquery.v2.Routine[] = []; - stream.on('data', (response: protos.google.cloud.bigquery.v2.Routine) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listRoutines.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listRoutines, request)); - assert( - (client.descriptors.page.listRoutines.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); + stream.on('error', (err: Error) => { + reject(err); }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listRoutines.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listRoutines, request), + ); + assert( + (client.descriptors.page.listRoutines.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('uses async iteration with listRoutines without error', async () => { - const client = new routineserviceModule.v2.RoutineServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.ListRoutinesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListRoutinesRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListRoutinesRequest', ['datasetId']); - request.datasetId = defaultValue2; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.bigquery.v2.Routine()), - generateSampleMessage(new protos.google.cloud.bigquery.v2.Routine()), - generateSampleMessage(new protos.google.cloud.bigquery.v2.Routine()), - ]; - client.descriptors.page.listRoutines.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.cloud.bigquery.v2.IRoutine[] = []; - const iterable = client.listRoutinesAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listRoutines.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listRoutines.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listRoutines without error', async () => { + const client = new routineserviceModule.v2.RoutineServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListRoutinesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListRoutinesRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListRoutinesRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.bigquery.v2.Routine()), + generateSampleMessage(new protos.google.cloud.bigquery.v2.Routine()), + generateSampleMessage(new protos.google.cloud.bigquery.v2.Routine()), + ]; + client.descriptors.page.listRoutines.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.cloud.bigquery.v2.IRoutine[] = []; + const iterable = client.listRoutinesAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listRoutines.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listRoutines.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('uses async iteration with listRoutines with error', async () => { - const client = new routineserviceModule.v2.RoutineServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.ListRoutinesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListRoutinesRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListRoutinesRequest', ['datasetId']); - request.datasetId = defaultValue2; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listRoutines.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listRoutinesAsync(request); - await assert.rejects(async () => { - const responses: protos.google.cloud.bigquery.v2.IRoutine[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listRoutines.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listRoutines.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listRoutines with error', async () => { + const client = new routineserviceModule.v2.RoutineServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListRoutinesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListRoutinesRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListRoutinesRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listRoutines.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listRoutinesAsync(request); + await assert.rejects(async () => { + const responses: protos.google.cloud.bigquery.v2.IRoutine[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listRoutines.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listRoutines.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); }); + }); }); diff --git a/core/generator/gapic-generator-typescript/baselines/bigquery-v2-esm/esm/test/gapic_row_access_policy_service_v2.ts.baseline b/core/generator/gapic-generator-typescript/baselines/bigquery-v2-esm/esm/test/gapic_row_access_policy_service_v2.ts.baseline index 3691314bc19e..dff1c78209a5 100644 --- a/core/generator/gapic-generator-typescript/baselines/bigquery-v2-esm/esm/test/gapic_row_access_policy_service_v2.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/bigquery-v2-esm/esm/test/gapic_row_access_policy_service_v2.ts.baseline @@ -20,16 +20,16 @@ import * as protos from '../../protos/protos.js'; import assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as rowaccesspolicyserviceModule from '../src/index.js'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; -import {protobuf} from 'google-gax'; +import { protobuf } from 'google-gax'; import fs from 'fs'; import path from 'path'; -import {fileURLToPath} from 'url'; +import { fileURLToPath } from 'url'; // @ts-ignore const dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -37,521 +37,737 @@ const dirname = path.dirname(fileURLToPath(import.meta.url)); // to fill in default values for request objects const root = protobuf.Root.fromJSON( JSON.parse( - fs.readFileSync(path.join(dirname, '..', '..', 'protos/protos.json'), 'utf8') - )) + fs.readFileSync( + path.join(dirname, '..', '..', 'protos/protos.json'), + 'utf8', + ), + ), +); // eslint-disable-next-line @typescript-eslint/no-unused-vars function getTypeDefaultValue(typeName: string, fields: string[]) { - let type = root.lookupType(typeName) as protobuf.Type; - for (const field of fields.slice(0, -1)) { - type = type?.fields[field]?.resolvedType as protobuf.Type; - } - return type?.fields[fields[fields.length - 1]]?.defaultValue ?? null; + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type?.fields[field]?.resolvedType as protobuf.Type; + } + return type?.fields[fields[fields.length - 1]]?.defaultValue ?? null; } function generateSampleMessage(instance: T) { - const filledObject = (instance.constructor as typeof protobuf.Message) - .toObject(instance as protobuf.Message, {defaults: true}); - return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, { defaults: true }); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; } function stubSimpleCall(response?: ResponseType, error?: Error) { - return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); } -function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { - return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +function stubSimpleCallWithCallback( + response?: ResponseType, + error?: Error, +) { + return error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); } -function stubPageStreamingCall(responses?: ResponseType[], error?: Error) { - const pagingStub = sinon.stub(); - if (responses) { - for (let i = 0; i < responses.length; ++i) { - pagingStub.onCall(i).callsArgWith(2, null, responses[i]); - } +function stubPageStreamingCall( + responses?: ResponseType[], + error?: Error, +) { + const pagingStub = sinon.stub(); + if (responses) { + for (let i = 0; i < responses.length; ++i) { + pagingStub.onCall(i).callsArgWith(2, null, responses[i]); } - const transformStub = error ? sinon.stub().callsArgWith(2, error) : pagingStub; - const mockStream = new PassThrough({ - objectMode: true, - transform: transformStub, - }); - // trigger as many responses as needed - if (responses) { - for (let i = 0; i < responses.length; ++i) { - setImmediate(() => { mockStream.write({}); }); - } - setImmediate(() => { mockStream.end(); }); - } else { - setImmediate(() => { mockStream.write({}); }); - setImmediate(() => { mockStream.end(); }); + } + const transformStub = error + ? sinon.stub().callsArgWith(2, error) + : pagingStub; + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + // trigger as many responses as needed + if (responses) { + for (let i = 0; i < responses.length; ++i) { + setImmediate(() => { + mockStream.write({}); + }); } - return sinon.stub().returns(mockStream); + setImmediate(() => { + mockStream.end(); + }); + } else { + setImmediate(() => { + mockStream.write({}); + }); + setImmediate(() => { + mockStream.end(); + }); + } + return sinon.stub().returns(mockStream); } -function stubAsyncIterationCall(responses?: ResponseType[], error?: Error) { - let counter = 0; - const asyncIterable = { - [Symbol.asyncIterator]() { - return { - async next() { - if (error) { - return Promise.reject(error); - } - if (counter >= responses!.length) { - return Promise.resolve({done: true, value: undefined}); - } - return Promise.resolve({done: false, value: responses![counter++]}); - } - }; - } - }; - return sinon.stub().returns(asyncIterable); +function stubAsyncIterationCall( + responses?: ResponseType[], + error?: Error, +) { + let counter = 0; + const asyncIterable = { + [Symbol.asyncIterator]() { + return { + async next() { + if (error) { + return Promise.reject(error); + } + if (counter >= responses!.length) { + return Promise.resolve({ done: true, value: undefined }); + } + return Promise.resolve({ done: false, value: responses![counter++] }); + }, + }; + }, + }; + return sinon.stub().returns(asyncIterable); } describe('v2.RowAccessPolicyServiceClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new rowaccesspolicyserviceModule.v2.RowAccessPolicyServiceClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'bigquery.googleapis.com'); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = + new rowaccesspolicyserviceModule.v2.RowAccessPolicyServiceClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'bigquery.googleapis.com'); + }); - it('has universeDomain', () => { - const client = new rowaccesspolicyserviceModule.v2.RowAccessPolicyServiceClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); + it('has universeDomain', () => { + const client = + new rowaccesspolicyserviceModule.v2.RowAccessPolicyServiceClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - it('throws DeprecationWarning if static servicePath is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const servicePath = rowaccesspolicyserviceModule.v2.RowAccessPolicyServiceClient.servicePath; - assert.strictEqual(servicePath, 'bigquery.googleapis.com'); - assert(stub.called); - stub.restore(); - }); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = + rowaccesspolicyserviceModule.v2.RowAccessPolicyServiceClient + .servicePath; + assert.strictEqual(servicePath, 'bigquery.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + rowaccesspolicyserviceModule.v2.RowAccessPolicyServiceClient + .apiEndpoint; + assert.strictEqual(apiEndpoint, 'bigquery.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = + new rowaccesspolicyserviceModule.v2.RowAccessPolicyServiceClient({ + universeDomain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'bigquery.example.com'); + }); - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = rowaccesspolicyserviceModule.v2.RowAccessPolicyServiceClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'bigquery.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new rowaccesspolicyserviceModule.v2.RowAccessPolicyServiceClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'bigquery.example.com'); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = + new rowaccesspolicyserviceModule.v2.RowAccessPolicyServiceClient({ + universe_domain: 'example.com', }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'bigquery.example.com'); + }); - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new rowaccesspolicyserviceModule.v2.RowAccessPolicyServiceClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'bigquery.example.com'); + if (typeof process === 'object' && 'env' in process) { + describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { + it('sets apiEndpoint from environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = + new rowaccesspolicyserviceModule.v2.RowAccessPolicyServiceClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'bigquery.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - if (typeof process === 'object' && 'env' in process) { - describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { - it('sets apiEndpoint from environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new rowaccesspolicyserviceModule.v2.RowAccessPolicyServiceClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'bigquery.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - - it('value configured in code has priority over environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new rowaccesspolicyserviceModule.v2.RowAccessPolicyServiceClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'bigquery.configured.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); + it('value configured in code has priority over environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = + new rowaccesspolicyserviceModule.v2.RowAccessPolicyServiceClient({ + universeDomain: 'configured.example.com', }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { new rowaccesspolicyserviceModule.v2.RowAccessPolicyServiceClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'bigquery.configured.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - - it('has port', () => { - const port = rowaccesspolicyserviceModule.v2.RowAccessPolicyServiceClient.port; - assert(port); - assert(typeof port === 'number'); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new rowaccesspolicyserviceModule.v2.RowAccessPolicyServiceClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); + }); - it('should create a client with no option', () => { - const client = new rowaccesspolicyserviceModule.v2.RowAccessPolicyServiceClient(); - assert(client); - }); + it('has port', () => { + const port = + rowaccesspolicyserviceModule.v2.RowAccessPolicyServiceClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('should create a client with gRPC fallback', () => { - const client = new rowaccesspolicyserviceModule.v2.RowAccessPolicyServiceClient({ - fallback: true, - }); - assert(client); - }); + it('should create a client with no option', () => { + const client = + new rowaccesspolicyserviceModule.v2.RowAccessPolicyServiceClient(); + assert(client); + }); - it('has initialize method and supports deferred initialization', async () => { - const client = new rowaccesspolicyserviceModule.v2.RowAccessPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.rowAccessPolicyServiceStub, undefined); - await client.initialize(); - assert(client.rowAccessPolicyServiceStub); + it('should create a client with gRPC fallback', () => { + const client = + new rowaccesspolicyserviceModule.v2.RowAccessPolicyServiceClient({ + fallback: true, }); + assert(client); + }); - it('has close method for the initialized client', done => { - const client = new rowaccesspolicyserviceModule.v2.RowAccessPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.rowAccessPolicyServiceStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); + it('has initialize method and supports deferred initialization', async () => { + const client = + new rowaccesspolicyserviceModule.v2.RowAccessPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + assert.strictEqual(client.rowAccessPolicyServiceStub, undefined); + await client.initialize(); + assert(client.rowAccessPolicyServiceStub); + }); - it('has close method for the non-initialized client', done => { - const client = new rowaccesspolicyserviceModule.v2.RowAccessPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.rowAccessPolicyServiceStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); + it('has close method for the initialized client', (done) => { + const client = + new rowaccesspolicyserviceModule.v2.RowAccessPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.rowAccessPolicyServiceStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new rowaccesspolicyserviceModule.v2.RowAccessPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + it('has close method for the non-initialized client', (done) => { + const client = + new rowaccesspolicyserviceModule.v2.RowAccessPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.rowAccessPolicyServiceStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new rowaccesspolicyserviceModule.v2.RowAccessPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId((err?: Error|null, projectId?: string|null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } - }); - }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = + new rowaccesspolicyserviceModule.v2.RowAccessPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); }); - describe('listRowAccessPolicies', () => { - it('invokes listRowAccessPolicies without error', async () => { - const client = new rowaccesspolicyserviceModule.v2.RowAccessPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.ListRowAccessPoliciesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListRowAccessPoliciesRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListRowAccessPoliciesRequest', ['datasetId']); - request.datasetId = defaultValue2; - const defaultValue3 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListRowAccessPoliciesRequest', ['tableId']); - request.tableId = defaultValue3; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }&table_id=${defaultValue3 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.bigquery.v2.RowAccessPolicy()), - generateSampleMessage(new protos.google.cloud.bigquery.v2.RowAccessPolicy()), - generateSampleMessage(new protos.google.cloud.bigquery.v2.RowAccessPolicy()), - ]; - client.innerApiCalls.listRowAccessPolicies = stubSimpleCall(expectedResponse); - const [response] = await client.listRowAccessPolicies(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listRowAccessPolicies as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listRowAccessPolicies as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = + new rowaccesspolicyserviceModule.v2.RowAccessPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } + }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + }); + + describe('listRowAccessPolicies', () => { + it('invokes listRowAccessPolicies without error', async () => { + const client = + new rowaccesspolicyserviceModule.v2.RowAccessPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListRowAccessPoliciesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListRowAccessPoliciesRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListRowAccessPoliciesRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const defaultValue3 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListRowAccessPoliciesRequest', + ['tableId'], + ); + request.tableId = defaultValue3; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}&table_id=${defaultValue3 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.cloud.bigquery.v2.RowAccessPolicy(), + ), + generateSampleMessage( + new protos.google.cloud.bigquery.v2.RowAccessPolicy(), + ), + generateSampleMessage( + new protos.google.cloud.bigquery.v2.RowAccessPolicy(), + ), + ]; + client.innerApiCalls.listRowAccessPolicies = + stubSimpleCall(expectedResponse); + const [response] = await client.listRowAccessPolicies(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listRowAccessPolicies as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listRowAccessPolicies as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listRowAccessPolicies without error using callback', async () => { - const client = new rowaccesspolicyserviceModule.v2.RowAccessPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.ListRowAccessPoliciesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListRowAccessPoliciesRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListRowAccessPoliciesRequest', ['datasetId']); - request.datasetId = defaultValue2; - const defaultValue3 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListRowAccessPoliciesRequest', ['tableId']); - request.tableId = defaultValue3; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }&table_id=${defaultValue3 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.bigquery.v2.RowAccessPolicy()), - generateSampleMessage(new protos.google.cloud.bigquery.v2.RowAccessPolicy()), - generateSampleMessage(new protos.google.cloud.bigquery.v2.RowAccessPolicy()), - ]; - client.innerApiCalls.listRowAccessPolicies = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listRowAccessPolicies( - request, - (err?: Error|null, result?: protos.google.cloud.bigquery.v2.IRowAccessPolicy[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listRowAccessPolicies as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listRowAccessPolicies as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes listRowAccessPolicies without error using callback', async () => { + const client = + new rowaccesspolicyserviceModule.v2.RowAccessPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListRowAccessPoliciesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListRowAccessPoliciesRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListRowAccessPoliciesRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const defaultValue3 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListRowAccessPoliciesRequest', + ['tableId'], + ); + request.tableId = defaultValue3; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}&table_id=${defaultValue3 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.cloud.bigquery.v2.RowAccessPolicy(), + ), + generateSampleMessage( + new protos.google.cloud.bigquery.v2.RowAccessPolicy(), + ), + generateSampleMessage( + new protos.google.cloud.bigquery.v2.RowAccessPolicy(), + ), + ]; + client.innerApiCalls.listRowAccessPolicies = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listRowAccessPolicies( + request, + ( + err?: Error | null, + result?: protos.google.cloud.bigquery.v2.IRowAccessPolicy[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listRowAccessPolicies as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listRowAccessPolicies as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listRowAccessPolicies with error', async () => { - const client = new rowaccesspolicyserviceModule.v2.RowAccessPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.ListRowAccessPoliciesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListRowAccessPoliciesRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListRowAccessPoliciesRequest', ['datasetId']); - request.datasetId = defaultValue2; - const defaultValue3 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListRowAccessPoliciesRequest', ['tableId']); - request.tableId = defaultValue3; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }&table_id=${defaultValue3 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listRowAccessPolicies = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listRowAccessPolicies(request), expectedError); - const actualRequest = (client.innerApiCalls.listRowAccessPolicies as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listRowAccessPolicies as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes listRowAccessPolicies with error', async () => { + const client = + new rowaccesspolicyserviceModule.v2.RowAccessPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListRowAccessPoliciesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListRowAccessPoliciesRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListRowAccessPoliciesRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const defaultValue3 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListRowAccessPoliciesRequest', + ['tableId'], + ); + request.tableId = defaultValue3; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}&table_id=${defaultValue3 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listRowAccessPolicies = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.listRowAccessPolicies(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.listRowAccessPolicies as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listRowAccessPolicies as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listRowAccessPoliciesStream without error', async () => { - const client = new rowaccesspolicyserviceModule.v2.RowAccessPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.ListRowAccessPoliciesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListRowAccessPoliciesRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListRowAccessPoliciesRequest', ['datasetId']); - request.datasetId = defaultValue2; - const defaultValue3 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListRowAccessPoliciesRequest', ['tableId']); - request.tableId = defaultValue3; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }&table_id=${defaultValue3 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.bigquery.v2.RowAccessPolicy()), - generateSampleMessage(new protos.google.cloud.bigquery.v2.RowAccessPolicy()), - generateSampleMessage(new protos.google.cloud.bigquery.v2.RowAccessPolicy()), - ]; - client.descriptors.page.listRowAccessPolicies.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listRowAccessPoliciesStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.cloud.bigquery.v2.RowAccessPolicy[] = []; - stream.on('data', (response: protos.google.cloud.bigquery.v2.RowAccessPolicy) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.listRowAccessPolicies.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listRowAccessPolicies, request)); - assert( - (client.descriptors.page.listRowAccessPolicies.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); + it('invokes listRowAccessPoliciesStream without error', async () => { + const client = + new rowaccesspolicyserviceModule.v2.RowAccessPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListRowAccessPoliciesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListRowAccessPoliciesRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListRowAccessPoliciesRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const defaultValue3 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListRowAccessPoliciesRequest', + ['tableId'], + ); + request.tableId = defaultValue3; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}&table_id=${defaultValue3 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.cloud.bigquery.v2.RowAccessPolicy(), + ), + generateSampleMessage( + new protos.google.cloud.bigquery.v2.RowAccessPolicy(), + ), + generateSampleMessage( + new protos.google.cloud.bigquery.v2.RowAccessPolicy(), + ), + ]; + client.descriptors.page.listRowAccessPolicies.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listRowAccessPoliciesStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.cloud.bigquery.v2.RowAccessPolicy[] = []; + stream.on( + 'data', + (response: protos.google.cloud.bigquery.v2.RowAccessPolicy) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + ( + client.descriptors.page.listRowAccessPolicies + .createStream as SinonStub + ) + .getCall(0) + .calledWith(client.innerApiCalls.listRowAccessPolicies, request), + ); + assert( + ( + client.descriptors.page.listRowAccessPolicies + .createStream as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); - it('invokes listRowAccessPoliciesStream with error', async () => { - const client = new rowaccesspolicyserviceModule.v2.RowAccessPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.ListRowAccessPoliciesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListRowAccessPoliciesRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListRowAccessPoliciesRequest', ['datasetId']); - request.datasetId = defaultValue2; - const defaultValue3 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListRowAccessPoliciesRequest', ['tableId']); - request.tableId = defaultValue3; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }&table_id=${defaultValue3 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listRowAccessPolicies.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listRowAccessPoliciesStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.cloud.bigquery.v2.RowAccessPolicy[] = []; - stream.on('data', (response: protos.google.cloud.bigquery.v2.RowAccessPolicy) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listRowAccessPolicies.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listRowAccessPolicies, request)); - assert( - (client.descriptors.page.listRowAccessPolicies.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); + it('invokes listRowAccessPoliciesStream with error', async () => { + const client = + new rowaccesspolicyserviceModule.v2.RowAccessPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListRowAccessPoliciesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListRowAccessPoliciesRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListRowAccessPoliciesRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const defaultValue3 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListRowAccessPoliciesRequest', + ['tableId'], + ); + request.tableId = defaultValue3; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}&table_id=${defaultValue3 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listRowAccessPolicies.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listRowAccessPoliciesStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.cloud.bigquery.v2.RowAccessPolicy[] = []; + stream.on( + 'data', + (response: protos.google.cloud.bigquery.v2.RowAccessPolicy) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + ( + client.descriptors.page.listRowAccessPolicies + .createStream as SinonStub + ) + .getCall(0) + .calledWith(client.innerApiCalls.listRowAccessPolicies, request), + ); + assert( + ( + client.descriptors.page.listRowAccessPolicies + .createStream as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); - it('uses async iteration with listRowAccessPolicies without error', async () => { - const client = new rowaccesspolicyserviceModule.v2.RowAccessPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.ListRowAccessPoliciesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListRowAccessPoliciesRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListRowAccessPoliciesRequest', ['datasetId']); - request.datasetId = defaultValue2; - const defaultValue3 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListRowAccessPoliciesRequest', ['tableId']); - request.tableId = defaultValue3; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }&table_id=${defaultValue3 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.bigquery.v2.RowAccessPolicy()), - generateSampleMessage(new protos.google.cloud.bigquery.v2.RowAccessPolicy()), - generateSampleMessage(new protos.google.cloud.bigquery.v2.RowAccessPolicy()), - ]; - client.descriptors.page.listRowAccessPolicies.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.cloud.bigquery.v2.IRowAccessPolicy[] = []; - const iterable = client.listRowAccessPoliciesAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listRowAccessPolicies.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listRowAccessPolicies.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); + it('uses async iteration with listRowAccessPolicies without error', async () => { + const client = + new rowaccesspolicyserviceModule.v2.RowAccessPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListRowAccessPoliciesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListRowAccessPoliciesRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListRowAccessPoliciesRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const defaultValue3 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListRowAccessPoliciesRequest', + ['tableId'], + ); + request.tableId = defaultValue3; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}&table_id=${defaultValue3 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.cloud.bigquery.v2.RowAccessPolicy(), + ), + generateSampleMessage( + new protos.google.cloud.bigquery.v2.RowAccessPolicy(), + ), + generateSampleMessage( + new protos.google.cloud.bigquery.v2.RowAccessPolicy(), + ), + ]; + client.descriptors.page.listRowAccessPolicies.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.cloud.bigquery.v2.IRowAccessPolicy[] = []; + const iterable = client.listRowAccessPoliciesAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listRowAccessPolicies + .asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + ( + client.descriptors.page.listRowAccessPolicies + .asyncIterate as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); - it('uses async iteration with listRowAccessPolicies with error', async () => { - const client = new rowaccesspolicyserviceModule.v2.RowAccessPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.ListRowAccessPoliciesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListRowAccessPoliciesRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListRowAccessPoliciesRequest', ['datasetId']); - request.datasetId = defaultValue2; - const defaultValue3 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListRowAccessPoliciesRequest', ['tableId']); - request.tableId = defaultValue3; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }&table_id=${defaultValue3 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listRowAccessPolicies.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listRowAccessPoliciesAsync(request); - await assert.rejects(async () => { - const responses: protos.google.cloud.bigquery.v2.IRowAccessPolicy[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listRowAccessPolicies.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listRowAccessPolicies.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); + it('uses async iteration with listRowAccessPolicies with error', async () => { + const client = + new rowaccesspolicyserviceModule.v2.RowAccessPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListRowAccessPoliciesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListRowAccessPoliciesRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListRowAccessPoliciesRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const defaultValue3 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListRowAccessPoliciesRequest', + ['tableId'], + ); + request.tableId = defaultValue3; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}&table_id=${defaultValue3 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listRowAccessPolicies.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listRowAccessPoliciesAsync(request); + await assert.rejects(async () => { + const responses: protos.google.cloud.bigquery.v2.IRowAccessPolicy[] = + []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listRowAccessPolicies + .asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + ( + client.descriptors.page.listRowAccessPolicies + .asyncIterate as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); }); + }); }); diff --git a/core/generator/gapic-generator-typescript/baselines/bigquery-v2-esm/esm/test/gapic_table_service_v2.ts.baseline b/core/generator/gapic-generator-typescript/baselines/bigquery-v2-esm/esm/test/gapic_table_service_v2.ts.baseline index ee2194fd6ce1..4bd279973bfc 100644 --- a/core/generator/gapic-generator-typescript/baselines/bigquery-v2-esm/esm/test/gapic_table_service_v2.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/bigquery-v2-esm/esm/test/gapic_table_service_v2.ts.baseline @@ -20,16 +20,16 @@ import * as protos from '../../protos/protos.js'; import assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as tableserviceModule from '../src/index.js'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; -import {protobuf} from 'google-gax'; +import { protobuf } from 'google-gax'; import fs from 'fs'; import path from 'path'; -import {fileURLToPath} from 'url'; +import { fileURLToPath } from 'url'; // @ts-ignore const dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -37,1148 +37,1496 @@ const dirname = path.dirname(fileURLToPath(import.meta.url)); // to fill in default values for request objects const root = protobuf.Root.fromJSON( JSON.parse( - fs.readFileSync(path.join(dirname, '..', '..', 'protos/protos.json'), 'utf8') - )) + fs.readFileSync( + path.join(dirname, '..', '..', 'protos/protos.json'), + 'utf8', + ), + ), +); // eslint-disable-next-line @typescript-eslint/no-unused-vars function getTypeDefaultValue(typeName: string, fields: string[]) { - let type = root.lookupType(typeName) as protobuf.Type; - for (const field of fields.slice(0, -1)) { - type = type?.fields[field]?.resolvedType as protobuf.Type; - } - return type?.fields[fields[fields.length - 1]]?.defaultValue ?? null; + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type?.fields[field]?.resolvedType as protobuf.Type; + } + return type?.fields[fields[fields.length - 1]]?.defaultValue ?? null; } function generateSampleMessage(instance: T) { - const filledObject = (instance.constructor as typeof protobuf.Message) - .toObject(instance as protobuf.Message, {defaults: true}); - return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, { defaults: true }); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; } function stubSimpleCall(response?: ResponseType, error?: Error) { - return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); } -function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { - return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +function stubSimpleCallWithCallback( + response?: ResponseType, + error?: Error, +) { + return error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); } -function stubPageStreamingCall(responses?: ResponseType[], error?: Error) { - const pagingStub = sinon.stub(); - if (responses) { - for (let i = 0; i < responses.length; ++i) { - pagingStub.onCall(i).callsArgWith(2, null, responses[i]); - } +function stubPageStreamingCall( + responses?: ResponseType[], + error?: Error, +) { + const pagingStub = sinon.stub(); + if (responses) { + for (let i = 0; i < responses.length; ++i) { + pagingStub.onCall(i).callsArgWith(2, null, responses[i]); } - const transformStub = error ? sinon.stub().callsArgWith(2, error) : pagingStub; - const mockStream = new PassThrough({ - objectMode: true, - transform: transformStub, - }); - // trigger as many responses as needed - if (responses) { - for (let i = 0; i < responses.length; ++i) { - setImmediate(() => { mockStream.write({}); }); - } - setImmediate(() => { mockStream.end(); }); - } else { - setImmediate(() => { mockStream.write({}); }); - setImmediate(() => { mockStream.end(); }); + } + const transformStub = error + ? sinon.stub().callsArgWith(2, error) + : pagingStub; + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + // trigger as many responses as needed + if (responses) { + for (let i = 0; i < responses.length; ++i) { + setImmediate(() => { + mockStream.write({}); + }); } - return sinon.stub().returns(mockStream); + setImmediate(() => { + mockStream.end(); + }); + } else { + setImmediate(() => { + mockStream.write({}); + }); + setImmediate(() => { + mockStream.end(); + }); + } + return sinon.stub().returns(mockStream); } -function stubAsyncIterationCall(responses?: ResponseType[], error?: Error) { - let counter = 0; - const asyncIterable = { - [Symbol.asyncIterator]() { - return { - async next() { - if (error) { - return Promise.reject(error); - } - if (counter >= responses!.length) { - return Promise.resolve({done: true, value: undefined}); - } - return Promise.resolve({done: false, value: responses![counter++]}); - } - }; - } - }; - return sinon.stub().returns(asyncIterable); +function stubAsyncIterationCall( + responses?: ResponseType[], + error?: Error, +) { + let counter = 0; + const asyncIterable = { + [Symbol.asyncIterator]() { + return { + async next() { + if (error) { + return Promise.reject(error); + } + if (counter >= responses!.length) { + return Promise.resolve({ done: true, value: undefined }); + } + return Promise.resolve({ done: false, value: responses![counter++] }); + }, + }; + }, + }; + return sinon.stub().returns(asyncIterable); } describe('v2.TableServiceClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new tableserviceModule.v2.TableServiceClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'bigquery.googleapis.com'); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new tableserviceModule.v2.TableServiceClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'bigquery.googleapis.com'); + }); - it('has universeDomain', () => { - const client = new tableserviceModule.v2.TableServiceClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); + it('has universeDomain', () => { + const client = new tableserviceModule.v2.TableServiceClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - it('throws DeprecationWarning if static servicePath is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const servicePath = tableserviceModule.v2.TableServiceClient.servicePath; - assert.strictEqual(servicePath, 'bigquery.googleapis.com'); - assert(stub.called); - stub.restore(); - }); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = + tableserviceModule.v2.TableServiceClient.servicePath; + assert.strictEqual(servicePath, 'bigquery.googleapis.com'); + assert(stub.called); + stub.restore(); + }); - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = tableserviceModule.v2.TableServiceClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'bigquery.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new tableserviceModule.v2.TableServiceClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'bigquery.example.com'); + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + tableserviceModule.v2.TableServiceClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'bigquery.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = new tableserviceModule.v2.TableServiceClient({ + universeDomain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'bigquery.example.com'); + }); + + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = new tableserviceModule.v2.TableServiceClient({ + universe_domain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'bigquery.example.com'); + }); + + if (typeof process === 'object' && 'env' in process) { + describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { + it('sets apiEndpoint from environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new tableserviceModule.v2.TableServiceClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'bigquery.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new tableserviceModule.v2.TableServiceClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'bigquery.example.com'); + it('value configured in code has priority over environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new tableserviceModule.v2.TableServiceClient({ + universeDomain: 'configured.example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'bigquery.configured.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new tableserviceModule.v2.TableServiceClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', + }); + }); + }); - if (typeof process === 'object' && 'env' in process) { - describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { - it('sets apiEndpoint from environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new tableserviceModule.v2.TableServiceClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'bigquery.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); + it('has port', () => { + const port = tableserviceModule.v2.TableServiceClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('value configured in code has priority over environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new tableserviceModule.v2.TableServiceClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'bigquery.configured.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { new tableserviceModule.v2.TableServiceClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); + it('should create a client with no option', () => { + const client = new tableserviceModule.v2.TableServiceClient(); + assert(client); + }); - it('has port', () => { - const port = tableserviceModule.v2.TableServiceClient.port; - assert(port); - assert(typeof port === 'number'); - }); + it('should create a client with gRPC fallback', () => { + const client = new tableserviceModule.v2.TableServiceClient({ + fallback: true, + }); + assert(client); + }); - it('should create a client with no option', () => { - const client = new tableserviceModule.v2.TableServiceClient(); - assert(client); - }); + it('has initialize method and supports deferred initialization', async () => { + const client = new tableserviceModule.v2.TableServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.tableServiceStub, undefined); + await client.initialize(); + assert(client.tableServiceStub); + }); - it('should create a client with gRPC fallback', () => { - const client = new tableserviceModule.v2.TableServiceClient({ - fallback: true, - }); - assert(client); + it('has close method for the initialized client', (done) => { + const client = new tableserviceModule.v2.TableServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.tableServiceStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('has initialize method and supports deferred initialization', async () => { - const client = new tableserviceModule.v2.TableServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.tableServiceStub, undefined); - await client.initialize(); - assert(client.tableServiceStub); + it('has close method for the non-initialized client', (done) => { + const client = new tableserviceModule.v2.TableServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.tableServiceStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('has close method for the initialized client', done => { - const client = new tableserviceModule.v2.TableServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.tableServiceStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new tableserviceModule.v2.TableServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + }); - it('has close method for the non-initialized client', done => { - const client = new tableserviceModule.v2.TableServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.tableServiceStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new tableserviceModule.v2.TableServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new tableserviceModule.v2.TableServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); - }); + describe('getTable', () => { + it('invokes getTable without error', async () => { + const client = new tableserviceModule.v2.TableServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.GetTableRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetTableRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetTableRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const defaultValue3 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetTableRequest', + ['tableId'], + ); + request.tableId = defaultValue3; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}&table_id=${defaultValue3 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.bigquery.v2.Table(), + ); + client.innerApiCalls.getTable = stubSimpleCall(expectedResponse); + const [response] = await client.getTable(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getTable as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getTable as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new tableserviceModule.v2.TableServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId((err?: Error|null, projectId?: string|null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } - }); - }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); - }); + it('invokes getTable without error using callback', async () => { + const client = new tableserviceModule.v2.TableServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.GetTableRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetTableRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetTableRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const defaultValue3 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetTableRequest', + ['tableId'], + ); + request.tableId = defaultValue3; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}&table_id=${defaultValue3 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.bigquery.v2.Table(), + ); + client.innerApiCalls.getTable = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getTable( + request, + ( + err?: Error | null, + result?: protos.google.cloud.bigquery.v2.ITable | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getTable as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getTable as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('getTable', () => { - it('invokes getTable without error', async () => { - const client = new tableserviceModule.v2.TableServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.GetTableRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetTableRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetTableRequest', ['datasetId']); - request.datasetId = defaultValue2; - const defaultValue3 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetTableRequest', ['tableId']); - request.tableId = defaultValue3; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }&table_id=${defaultValue3 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.bigquery.v2.Table() - ); - client.innerApiCalls.getTable = stubSimpleCall(expectedResponse); - const [response] = await client.getTable(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getTable as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getTable as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getTable with error', async () => { + const client = new tableserviceModule.v2.TableServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.GetTableRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetTableRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetTableRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const defaultValue3 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetTableRequest', + ['tableId'], + ); + request.tableId = defaultValue3; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}&table_id=${defaultValue3 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getTable = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.getTable(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getTable as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getTable as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getTable without error using callback', async () => { - const client = new tableserviceModule.v2.TableServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.GetTableRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetTableRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetTableRequest', ['datasetId']); - request.datasetId = defaultValue2; - const defaultValue3 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetTableRequest', ['tableId']); - request.tableId = defaultValue3; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }&table_id=${defaultValue3 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.bigquery.v2.Table() - ); - client.innerApiCalls.getTable = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getTable( - request, - (err?: Error|null, result?: protos.google.cloud.bigquery.v2.ITable|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getTable as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getTable as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getTable with closed client', async () => { + const client = new tableserviceModule.v2.TableServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.GetTableRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetTableRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetTableRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const defaultValue3 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetTableRequest', + ['tableId'], + ); + request.tableId = defaultValue3; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getTable(request), expectedError); + }); + }); - it('invokes getTable with error', async () => { - const client = new tableserviceModule.v2.TableServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.GetTableRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetTableRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetTableRequest', ['datasetId']); - request.datasetId = defaultValue2; - const defaultValue3 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetTableRequest', ['tableId']); - request.tableId = defaultValue3; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }&table_id=${defaultValue3 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getTable = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getTable(request), expectedError); - const actualRequest = (client.innerApiCalls.getTable as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getTable as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + describe('insertTable', () => { + it('invokes insertTable without error', async () => { + const client = new tableserviceModule.v2.TableServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.InsertTableRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.InsertTableRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.InsertTableRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.bigquery.v2.Table(), + ); + client.innerApiCalls.insertTable = stubSimpleCall(expectedResponse); + const [response] = await client.insertTable(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.insertTable as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.insertTable as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getTable with closed client', async () => { - const client = new tableserviceModule.v2.TableServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.GetTableRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetTableRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetTableRequest', ['datasetId']); - request.datasetId = defaultValue2; - const defaultValue3 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetTableRequest', ['tableId']); - request.tableId = defaultValue3; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getTable(request), expectedError); - }); + it('invokes insertTable without error using callback', async () => { + const client = new tableserviceModule.v2.TableServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.InsertTableRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.InsertTableRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.InsertTableRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.bigquery.v2.Table(), + ); + client.innerApiCalls.insertTable = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.insertTable( + request, + ( + err?: Error | null, + result?: protos.google.cloud.bigquery.v2.ITable | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.insertTable as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.insertTable as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('insertTable', () => { - it('invokes insertTable without error', async () => { - const client = new tableserviceModule.v2.TableServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.InsertTableRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.InsertTableRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.InsertTableRequest', ['datasetId']); - request.datasetId = defaultValue2; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.bigquery.v2.Table() - ); - client.innerApiCalls.insertTable = stubSimpleCall(expectedResponse); - const [response] = await client.insertTable(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.insertTable as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.insertTable as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes insertTable with error', async () => { + const client = new tableserviceModule.v2.TableServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.InsertTableRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.InsertTableRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.InsertTableRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.insertTable = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.insertTable(request), expectedError); + const actualRequest = ( + client.innerApiCalls.insertTable as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.insertTable as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes insertTable without error using callback', async () => { - const client = new tableserviceModule.v2.TableServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.InsertTableRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.InsertTableRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.InsertTableRequest', ['datasetId']); - request.datasetId = defaultValue2; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.bigquery.v2.Table() - ); - client.innerApiCalls.insertTable = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.insertTable( - request, - (err?: Error|null, result?: protos.google.cloud.bigquery.v2.ITable|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.insertTable as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.insertTable as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes insertTable with closed client', async () => { + const client = new tableserviceModule.v2.TableServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.InsertTableRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.InsertTableRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.InsertTableRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.insertTable(request), expectedError); + }); + }); - it('invokes insertTable with error', async () => { - const client = new tableserviceModule.v2.TableServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.InsertTableRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.InsertTableRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.InsertTableRequest', ['datasetId']); - request.datasetId = defaultValue2; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.insertTable = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.insertTable(request), expectedError); - const actualRequest = (client.innerApiCalls.insertTable as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.insertTable as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + describe('patchTable', () => { + it('invokes patchTable without error', async () => { + const client = new tableserviceModule.v2.TableServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.UpdateOrPatchTableRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.UpdateOrPatchTableRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.UpdateOrPatchTableRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const defaultValue3 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.UpdateOrPatchTableRequest', + ['tableId'], + ); + request.tableId = defaultValue3; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}&table_id=${defaultValue3 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.bigquery.v2.Table(), + ); + client.innerApiCalls.patchTable = stubSimpleCall(expectedResponse); + const [response] = await client.patchTable(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.patchTable as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.patchTable as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes insertTable with closed client', async () => { - const client = new tableserviceModule.v2.TableServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.InsertTableRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.InsertTableRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.InsertTableRequest', ['datasetId']); - request.datasetId = defaultValue2; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.insertTable(request), expectedError); - }); + it('invokes patchTable without error using callback', async () => { + const client = new tableserviceModule.v2.TableServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.UpdateOrPatchTableRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.UpdateOrPatchTableRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.UpdateOrPatchTableRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const defaultValue3 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.UpdateOrPatchTableRequest', + ['tableId'], + ); + request.tableId = defaultValue3; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}&table_id=${defaultValue3 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.bigquery.v2.Table(), + ); + client.innerApiCalls.patchTable = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.patchTable( + request, + ( + err?: Error | null, + result?: protos.google.cloud.bigquery.v2.ITable | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.patchTable as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.patchTable as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('patchTable', () => { - it('invokes patchTable without error', async () => { - const client = new tableserviceModule.v2.TableServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.UpdateOrPatchTableRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.UpdateOrPatchTableRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.UpdateOrPatchTableRequest', ['datasetId']); - request.datasetId = defaultValue2; - const defaultValue3 = - getTypeDefaultValue('.google.cloud.bigquery.v2.UpdateOrPatchTableRequest', ['tableId']); - request.tableId = defaultValue3; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }&table_id=${defaultValue3 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.bigquery.v2.Table() - ); - client.innerApiCalls.patchTable = stubSimpleCall(expectedResponse); - const [response] = await client.patchTable(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.patchTable as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.patchTable as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes patchTable with error', async () => { + const client = new tableserviceModule.v2.TableServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.UpdateOrPatchTableRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.UpdateOrPatchTableRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.UpdateOrPatchTableRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const defaultValue3 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.UpdateOrPatchTableRequest', + ['tableId'], + ); + request.tableId = defaultValue3; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}&table_id=${defaultValue3 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.patchTable = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.patchTable(request), expectedError); + const actualRequest = ( + client.innerApiCalls.patchTable as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.patchTable as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes patchTable without error using callback', async () => { - const client = new tableserviceModule.v2.TableServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.UpdateOrPatchTableRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.UpdateOrPatchTableRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.UpdateOrPatchTableRequest', ['datasetId']); - request.datasetId = defaultValue2; - const defaultValue3 = - getTypeDefaultValue('.google.cloud.bigquery.v2.UpdateOrPatchTableRequest', ['tableId']); - request.tableId = defaultValue3; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }&table_id=${defaultValue3 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.bigquery.v2.Table() - ); - client.innerApiCalls.patchTable = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.patchTable( - request, - (err?: Error|null, result?: protos.google.cloud.bigquery.v2.ITable|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.patchTable as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.patchTable as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes patchTable with closed client', async () => { + const client = new tableserviceModule.v2.TableServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.UpdateOrPatchTableRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.UpdateOrPatchTableRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.UpdateOrPatchTableRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const defaultValue3 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.UpdateOrPatchTableRequest', + ['tableId'], + ); + request.tableId = defaultValue3; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.patchTable(request), expectedError); + }); + }); - it('invokes patchTable with error', async () => { - const client = new tableserviceModule.v2.TableServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.UpdateOrPatchTableRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.UpdateOrPatchTableRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.UpdateOrPatchTableRequest', ['datasetId']); - request.datasetId = defaultValue2; - const defaultValue3 = - getTypeDefaultValue('.google.cloud.bigquery.v2.UpdateOrPatchTableRequest', ['tableId']); - request.tableId = defaultValue3; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }&table_id=${defaultValue3 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.patchTable = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.patchTable(request), expectedError); - const actualRequest = (client.innerApiCalls.patchTable as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.patchTable as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + describe('updateTable', () => { + it('invokes updateTable without error', async () => { + const client = new tableserviceModule.v2.TableServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.UpdateOrPatchTableRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.UpdateOrPatchTableRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.UpdateOrPatchTableRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const defaultValue3 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.UpdateOrPatchTableRequest', + ['tableId'], + ); + request.tableId = defaultValue3; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}&table_id=${defaultValue3 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.bigquery.v2.Table(), + ); + client.innerApiCalls.updateTable = stubSimpleCall(expectedResponse); + const [response] = await client.updateTable(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateTable as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateTable as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes patchTable with closed client', async () => { - const client = new tableserviceModule.v2.TableServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.UpdateOrPatchTableRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.UpdateOrPatchTableRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.UpdateOrPatchTableRequest', ['datasetId']); - request.datasetId = defaultValue2; - const defaultValue3 = - getTypeDefaultValue('.google.cloud.bigquery.v2.UpdateOrPatchTableRequest', ['tableId']); - request.tableId = defaultValue3; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.patchTable(request), expectedError); - }); + it('invokes updateTable without error using callback', async () => { + const client = new tableserviceModule.v2.TableServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.UpdateOrPatchTableRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.UpdateOrPatchTableRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.UpdateOrPatchTableRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const defaultValue3 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.UpdateOrPatchTableRequest', + ['tableId'], + ); + request.tableId = defaultValue3; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}&table_id=${defaultValue3 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.bigquery.v2.Table(), + ); + client.innerApiCalls.updateTable = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateTable( + request, + ( + err?: Error | null, + result?: protos.google.cloud.bigquery.v2.ITable | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateTable as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateTable as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('updateTable', () => { - it('invokes updateTable without error', async () => { - const client = new tableserviceModule.v2.TableServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.UpdateOrPatchTableRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.UpdateOrPatchTableRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.UpdateOrPatchTableRequest', ['datasetId']); - request.datasetId = defaultValue2; - const defaultValue3 = - getTypeDefaultValue('.google.cloud.bigquery.v2.UpdateOrPatchTableRequest', ['tableId']); - request.tableId = defaultValue3; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }&table_id=${defaultValue3 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.bigquery.v2.Table() - ); - client.innerApiCalls.updateTable = stubSimpleCall(expectedResponse); - const [response] = await client.updateTable(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateTable as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateTable as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateTable with error', async () => { + const client = new tableserviceModule.v2.TableServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.UpdateOrPatchTableRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.UpdateOrPatchTableRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.UpdateOrPatchTableRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const defaultValue3 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.UpdateOrPatchTableRequest', + ['tableId'], + ); + request.tableId = defaultValue3; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}&table_id=${defaultValue3 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateTable = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.updateTable(request), expectedError); + const actualRequest = ( + client.innerApiCalls.updateTable as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateTable as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateTable without error using callback', async () => { - const client = new tableserviceModule.v2.TableServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.UpdateOrPatchTableRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.UpdateOrPatchTableRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.UpdateOrPatchTableRequest', ['datasetId']); - request.datasetId = defaultValue2; - const defaultValue3 = - getTypeDefaultValue('.google.cloud.bigquery.v2.UpdateOrPatchTableRequest', ['tableId']); - request.tableId = defaultValue3; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }&table_id=${defaultValue3 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.bigquery.v2.Table() - ); - client.innerApiCalls.updateTable = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateTable( - request, - (err?: Error|null, result?: protos.google.cloud.bigquery.v2.ITable|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateTable as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateTable as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateTable with closed client', async () => { + const client = new tableserviceModule.v2.TableServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.UpdateOrPatchTableRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.UpdateOrPatchTableRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.UpdateOrPatchTableRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const defaultValue3 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.UpdateOrPatchTableRequest', + ['tableId'], + ); + request.tableId = defaultValue3; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.updateTable(request), expectedError); + }); + }); - it('invokes updateTable with error', async () => { - const client = new tableserviceModule.v2.TableServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.UpdateOrPatchTableRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.UpdateOrPatchTableRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.UpdateOrPatchTableRequest', ['datasetId']); - request.datasetId = defaultValue2; - const defaultValue3 = - getTypeDefaultValue('.google.cloud.bigquery.v2.UpdateOrPatchTableRequest', ['tableId']); - request.tableId = defaultValue3; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }&table_id=${defaultValue3 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateTable = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateTable(request), expectedError); - const actualRequest = (client.innerApiCalls.updateTable as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateTable as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + describe('deleteTable', () => { + it('invokes deleteTable without error', async () => { + const client = new tableserviceModule.v2.TableServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.DeleteTableRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.DeleteTableRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.DeleteTableRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const defaultValue3 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.DeleteTableRequest', + ['tableId'], + ); + request.tableId = defaultValue3; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}&table_id=${defaultValue3 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteTable = stubSimpleCall(expectedResponse); + const [response] = await client.deleteTable(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteTable as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteTable as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateTable with closed client', async () => { - const client = new tableserviceModule.v2.TableServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.UpdateOrPatchTableRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.UpdateOrPatchTableRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.UpdateOrPatchTableRequest', ['datasetId']); - request.datasetId = defaultValue2; - const defaultValue3 = - getTypeDefaultValue('.google.cloud.bigquery.v2.UpdateOrPatchTableRequest', ['tableId']); - request.tableId = defaultValue3; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateTable(request), expectedError); - }); + it('invokes deleteTable without error using callback', async () => { + const client = new tableserviceModule.v2.TableServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.DeleteTableRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.DeleteTableRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.DeleteTableRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const defaultValue3 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.DeleteTableRequest', + ['tableId'], + ); + request.tableId = defaultValue3; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}&table_id=${defaultValue3 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteTable = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteTable( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteTable as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteTable as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('deleteTable', () => { - it('invokes deleteTable without error', async () => { - const client = new tableserviceModule.v2.TableServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.DeleteTableRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.DeleteTableRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.DeleteTableRequest', ['datasetId']); - request.datasetId = defaultValue2; - const defaultValue3 = - getTypeDefaultValue('.google.cloud.bigquery.v2.DeleteTableRequest', ['tableId']); - request.tableId = defaultValue3; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }&table_id=${defaultValue3 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteTable = stubSimpleCall(expectedResponse); - const [response] = await client.deleteTable(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteTable as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteTable as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteTable with error', async () => { + const client = new tableserviceModule.v2.TableServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.DeleteTableRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.DeleteTableRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.DeleteTableRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const defaultValue3 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.DeleteTableRequest', + ['tableId'], + ); + request.tableId = defaultValue3; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}&table_id=${defaultValue3 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteTable = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.deleteTable(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteTable as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteTable as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteTable without error using callback', async () => { - const client = new tableserviceModule.v2.TableServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.DeleteTableRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.DeleteTableRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.DeleteTableRequest', ['datasetId']); - request.datasetId = defaultValue2; - const defaultValue3 = - getTypeDefaultValue('.google.cloud.bigquery.v2.DeleteTableRequest', ['tableId']); - request.tableId = defaultValue3; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }&table_id=${defaultValue3 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteTable = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteTable( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteTable as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteTable as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteTable with closed client', async () => { + const client = new tableserviceModule.v2.TableServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.DeleteTableRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.DeleteTableRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.DeleteTableRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const defaultValue3 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.DeleteTableRequest', + ['tableId'], + ); + request.tableId = defaultValue3; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.deleteTable(request), expectedError); + }); + }); - it('invokes deleteTable with error', async () => { - const client = new tableserviceModule.v2.TableServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.DeleteTableRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.DeleteTableRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.DeleteTableRequest', ['datasetId']); - request.datasetId = defaultValue2; - const defaultValue3 = - getTypeDefaultValue('.google.cloud.bigquery.v2.DeleteTableRequest', ['tableId']); - request.tableId = defaultValue3; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }&table_id=${defaultValue3 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteTable = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteTable(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteTable as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteTable as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + describe('listTables', () => { + it('invokes listTables without error', async () => { + const client = new tableserviceModule.v2.TableServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListTablesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListTablesRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListTablesRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListFormatTable(), + ), + generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListFormatTable(), + ), + generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListFormatTable(), + ), + ]; + client.innerApiCalls.listTables = stubSimpleCall(expectedResponse); + const [response] = await client.listTables(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listTables as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listTables as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteTable with closed client', async () => { - const client = new tableserviceModule.v2.TableServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.DeleteTableRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.DeleteTableRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.DeleteTableRequest', ['datasetId']); - request.datasetId = defaultValue2; - const defaultValue3 = - getTypeDefaultValue('.google.cloud.bigquery.v2.DeleteTableRequest', ['tableId']); - request.tableId = defaultValue3; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteTable(request), expectedError); - }); + it('invokes listTables without error using callback', async () => { + const client = new tableserviceModule.v2.TableServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListTablesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListTablesRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListTablesRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListFormatTable(), + ), + generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListFormatTable(), + ), + generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListFormatTable(), + ), + ]; + client.innerApiCalls.listTables = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listTables( + request, + ( + err?: Error | null, + result?: protos.google.cloud.bigquery.v2.IListFormatTable[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listTables as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listTables as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('listTables', () => { - it('invokes listTables without error', async () => { - const client = new tableserviceModule.v2.TableServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.ListTablesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListTablesRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListTablesRequest', ['datasetId']); - request.datasetId = defaultValue2; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.bigquery.v2.ListFormatTable()), - generateSampleMessage(new protos.google.cloud.bigquery.v2.ListFormatTable()), - generateSampleMessage(new protos.google.cloud.bigquery.v2.ListFormatTable()), - ]; - client.innerApiCalls.listTables = stubSimpleCall(expectedResponse); - const [response] = await client.listTables(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listTables as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listTables as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listTables with error', async () => { + const client = new tableserviceModule.v2.TableServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListTablesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListTablesRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListTablesRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listTables = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listTables(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listTables as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listTables as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listTables without error using callback', async () => { - const client = new tableserviceModule.v2.TableServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.ListTablesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListTablesRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListTablesRequest', ['datasetId']); - request.datasetId = defaultValue2; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.bigquery.v2.ListFormatTable()), - generateSampleMessage(new protos.google.cloud.bigquery.v2.ListFormatTable()), - generateSampleMessage(new protos.google.cloud.bigquery.v2.ListFormatTable()), - ]; - client.innerApiCalls.listTables = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listTables( - request, - (err?: Error|null, result?: protos.google.cloud.bigquery.v2.IListFormatTable[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listTables as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listTables as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes listTablesStream without error', async () => { + const client = new tableserviceModule.v2.TableServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListTablesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListTablesRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListTablesRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListFormatTable(), + ), + generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListFormatTable(), + ), + generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListFormatTable(), + ), + ]; + client.descriptors.page.listTables.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listTablesStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.cloud.bigquery.v2.ListFormatTable[] = []; + stream.on( + 'data', + (response: protos.google.cloud.bigquery.v2.ListFormatTable) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); }); - - it('invokes listTables with error', async () => { - const client = new tableserviceModule.v2.TableServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.ListTablesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListTablesRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListTablesRequest', ['datasetId']); - request.datasetId = defaultValue2; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listTables = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listTables(request), expectedError); - const actualRequest = (client.innerApiCalls.listTables as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listTables as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + stream.on('error', (err: Error) => { + reject(err); }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listTables.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listTables, request), + ); + assert( + (client.descriptors.page.listTables.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('invokes listTablesStream without error', async () => { - const client = new tableserviceModule.v2.TableServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.ListTablesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListTablesRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListTablesRequest', ['datasetId']); - request.datasetId = defaultValue2; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.bigquery.v2.ListFormatTable()), - generateSampleMessage(new protos.google.cloud.bigquery.v2.ListFormatTable()), - generateSampleMessage(new protos.google.cloud.bigquery.v2.ListFormatTable()), - ]; - client.descriptors.page.listTables.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listTablesStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.cloud.bigquery.v2.ListFormatTable[] = []; - stream.on('data', (response: protos.google.cloud.bigquery.v2.ListFormatTable) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.listTables.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listTables, request)); - assert( - (client.descriptors.page.listTables.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); + it('invokes listTablesStream with error', async () => { + const client = new tableserviceModule.v2.TableServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListTablesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListTablesRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListTablesRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listTables.createStream = stubPageStreamingCall( + undefined, + expectedError, + ); + const stream = client.listTablesStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.cloud.bigquery.v2.ListFormatTable[] = []; + stream.on( + 'data', + (response: protos.google.cloud.bigquery.v2.ListFormatTable) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); }); - - it('invokes listTablesStream with error', async () => { - const client = new tableserviceModule.v2.TableServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.ListTablesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListTablesRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListTablesRequest', ['datasetId']); - request.datasetId = defaultValue2; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listTables.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listTablesStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.cloud.bigquery.v2.ListFormatTable[] = []; - stream.on('data', (response: protos.google.cloud.bigquery.v2.ListFormatTable) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listTables.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listTables, request)); - assert( - (client.descriptors.page.listTables.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); + stream.on('error', (err: Error) => { + reject(err); }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listTables.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listTables, request), + ); + assert( + (client.descriptors.page.listTables.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('uses async iteration with listTables without error', async () => { - const client = new tableserviceModule.v2.TableServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.ListTablesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListTablesRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListTablesRequest', ['datasetId']); - request.datasetId = defaultValue2; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.bigquery.v2.ListFormatTable()), - generateSampleMessage(new protos.google.cloud.bigquery.v2.ListFormatTable()), - generateSampleMessage(new protos.google.cloud.bigquery.v2.ListFormatTable()), - ]; - client.descriptors.page.listTables.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.cloud.bigquery.v2.IListFormatTable[] = []; - const iterable = client.listTablesAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listTables.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listTables.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listTables without error', async () => { + const client = new tableserviceModule.v2.TableServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListTablesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListTablesRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListTablesRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListFormatTable(), + ), + generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListFormatTable(), + ), + generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListFormatTable(), + ), + ]; + client.descriptors.page.listTables.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.cloud.bigquery.v2.IListFormatTable[] = []; + const iterable = client.listTablesAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + (client.descriptors.page.listTables.asyncIterate as SinonStub).getCall( + 0, + ).args[1], + request, + ); + assert( + (client.descriptors.page.listTables.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('uses async iteration with listTables with error', async () => { - const client = new tableserviceModule.v2.TableServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.ListTablesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListTablesRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListTablesRequest', ['datasetId']); - request.datasetId = defaultValue2; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listTables.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listTablesAsync(request); - await assert.rejects(async () => { - const responses: protos.google.cloud.bigquery.v2.IListFormatTable[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listTables.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listTables.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listTables with error', async () => { + const client = new tableserviceModule.v2.TableServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListTablesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListTablesRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListTablesRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listTables.asyncIterate = stubAsyncIterationCall( + undefined, + expectedError, + ); + const iterable = client.listTablesAsync(request); + await assert.rejects(async () => { + const responses: protos.google.cloud.bigquery.v2.IListFormatTable[] = + []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + (client.descriptors.page.listTables.asyncIterate as SinonStub).getCall( + 0, + ).args[1], + request, + ); + assert( + (client.descriptors.page.listTables.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); }); + }); }); diff --git a/core/generator/gapic-generator-typescript/baselines/bigquery-v2/src/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/bigquery-v2/src/index.ts.baseline index 9b89a10c9e7b..2d92cd30926c 100644 --- a/core/generator/gapic-generator-typescript/baselines/bigquery-v2/src/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/bigquery-v2/src/index.ts.baseline @@ -31,7 +31,25 @@ const RowAccessPolicyServiceClient = v2.RowAccessPolicyServiceClient; type RowAccessPolicyServiceClient = v2.RowAccessPolicyServiceClient; const TableServiceClient = v2.TableServiceClient; type TableServiceClient = v2.TableServiceClient; -export {v2, DatasetServiceClient, JobServiceClient, ModelServiceClient, ProjectServiceClient, RoutineServiceClient, RowAccessPolicyServiceClient, TableServiceClient}; -export default {v2, DatasetServiceClient, JobServiceClient, ModelServiceClient, ProjectServiceClient, RoutineServiceClient, RowAccessPolicyServiceClient, TableServiceClient}; +export { + v2, + DatasetServiceClient, + JobServiceClient, + ModelServiceClient, + ProjectServiceClient, + RoutineServiceClient, + RowAccessPolicyServiceClient, + TableServiceClient, +}; +export default { + v2, + DatasetServiceClient, + JobServiceClient, + ModelServiceClient, + ProjectServiceClient, + RoutineServiceClient, + RowAccessPolicyServiceClient, + TableServiceClient, +}; import * as protos from '../protos/protos'; -export {protos} +export { protos }; diff --git a/core/generator/gapic-generator-typescript/baselines/bigquery-v2/src/v2/dataset_service_client.ts.baseline b/core/generator/gapic-generator-typescript/baselines/bigquery-v2/src/v2/dataset_service_client.ts.baseline index f21d68556362..d3ee1b106bac 100644 --- a/core/generator/gapic-generator-typescript/baselines/bigquery-v2/src/v2/dataset_service_client.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/bigquery-v2/src/v2/dataset_service_client.ts.baseline @@ -18,11 +18,18 @@ /* global window */ import type * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions, PaginationCallback, GaxCall} from 'google-gax'; -import {Transform} from 'stream'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + PaginationCallback, + GaxCall, +} from 'google-gax'; +import { Transform } from 'stream'; import * as protos from '../../protos/protos'; import jsonProtos = require('../../protos/protos.json'); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; /** * Client JSON configuration object, loaded from @@ -47,7 +54,7 @@ export class DatasetServiceClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('bigquery'); @@ -60,8 +67,8 @@ export class DatasetServiceClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - datasetServiceStub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + datasetServiceStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of DatasetServiceClient. @@ -102,21 +109,42 @@ export class DatasetServiceClient { * const client = new DatasetServiceClient({fallback: true}, gax); * ``` */ - constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { // Ensure that options include all the required fields. const staticMembers = this.constructor as typeof DatasetServiceClient; - if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { - throw new Error('Please set either universe_domain or universeDomain, but not both.'); + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); } - const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; - this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; this._servicePath = 'bigquery.' + this._universeDomain; - const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; - const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. if (servicePath !== this._servicePath && !('scopes' in opts)) { @@ -138,7 +166,7 @@ export class DatasetServiceClient { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; @@ -152,10 +180,7 @@ export class DatasetServiceClient { } // Determine the client header string. - const clientHeader = [ - `gax/${this._gaxModule.version}`, - `gapic/${version}`, - ]; + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/${process.versions.node}`); } else { @@ -176,14 +201,20 @@ export class DatasetServiceClient { // (e.g. 50 results at a time, with tokens to get subsequent // pages). Denote the keys used for pagination and results. this.descriptors.page = { - listDatasets: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'datasets') + listDatasets: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'datasets', + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.cloud.bigquery.v2.DatasetService', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.cloud.bigquery.v2.DatasetService', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + { 'x-goog-api-client': clientHeader.join(' ') }, + ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -214,37 +245,48 @@ export class DatasetServiceClient { // Put together the "service stub" for // google.cloud.bigquery.v2.DatasetService. this.datasetServiceStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.cloud.bigquery.v2.DatasetService') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.cloud.bigquery.v2.DatasetService', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.cloud.bigquery.v2.DatasetService, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts, + this._providedCustomServicePath, + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const datasetServiceStubMethods = - ['getDataset', 'insertDataset', 'patchDataset', 'updateDataset', 'deleteDataset', 'listDatasets', 'undeleteDataset']; + const datasetServiceStubMethods = [ + 'getDataset', + 'insertDataset', + 'patchDataset', + 'updateDataset', + 'deleteDataset', + 'listDatasets', + 'undeleteDataset', + ]; for (const methodName of datasetServiceStubMethods) { const callPromise = this.datasetServiceStub.then( - stub => (...args: Array<{}>) => { - if (this._terminated) { - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error|null|undefined) => () => { + (stub) => + (...args: Array<{}>) => { + if (this._terminated) { + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { throw err; - }); + }, + ); - const descriptor = - this.descriptors.page[methodName] || - undefined; + const descriptor = this.descriptors.page[methodName] || undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -259,8 +301,14 @@ export class DatasetServiceClient { * @returns {string} The DNS address for this service. */ static get servicePath() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'bigquery.googleapis.com'; } @@ -271,8 +319,14 @@ export class DatasetServiceClient { * @returns {string} The DNS address for this service. */ static get apiEndpoint() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'bigquery.googleapis.com'; } @@ -306,7 +360,7 @@ export class DatasetServiceClient { return [ 'https://www.googleapis.com/auth/bigquery', 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloud-platform.read-only' + 'https://www.googleapis.com/auth/cloud-platform.read-only', ]; } @@ -316,8 +370,9 @@ export class DatasetServiceClient { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId(callback?: Callback): - Promise|void { + getProjectId( + callback?: Callback, + ): Promise | void { if (callback) { this.auth.getProjectId(callback); return; @@ -328,714 +383,953 @@ export class DatasetServiceClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Returns the dataset specified by datasetID. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.projectId - * Required. Project ID of the requested dataset - * @param {string} request.datasetId - * Required. Dataset ID of the requested dataset - * @param {google.cloud.bigquery.v2.GetDatasetRequest.DatasetView} [request.datasetView] - * Optional. Specifies the view that determines which dataset information is - * returned. By default, metadata and ACL information are returned. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.bigquery.v2.Dataset|Dataset}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/dataset_service.get_dataset.js - * region_tag:bigquery_v2_generated_DatasetService_GetDataset_async - */ + /** + * Returns the dataset specified by datasetID. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.projectId + * Required. Project ID of the requested dataset + * @param {string} request.datasetId + * Required. Dataset ID of the requested dataset + * @param {google.cloud.bigquery.v2.GetDatasetRequest.DatasetView} [request.datasetView] + * Optional. Specifies the view that determines which dataset information is + * returned. By default, metadata and ACL information are returned. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.bigquery.v2.Dataset|Dataset}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/dataset_service.get_dataset.js + * region_tag:bigquery_v2_generated_DatasetService_GetDataset_async + */ getDataset( - request?: protos.google.cloud.bigquery.v2.IGetDatasetRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.bigquery.v2.IDataset, - protos.google.cloud.bigquery.v2.IGetDatasetRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.bigquery.v2.IGetDatasetRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.bigquery.v2.IDataset, + protos.google.cloud.bigquery.v2.IGetDatasetRequest | undefined, + {} | undefined, + ] + >; getDataset( - request: protos.google.cloud.bigquery.v2.IGetDatasetRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.bigquery.v2.IDataset, - protos.google.cloud.bigquery.v2.IGetDatasetRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.bigquery.v2.IGetDatasetRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.bigquery.v2.IDataset, + protos.google.cloud.bigquery.v2.IGetDatasetRequest | null | undefined, + {} | null | undefined + >, + ): void; getDataset( - request: protos.google.cloud.bigquery.v2.IGetDatasetRequest, - callback: Callback< - protos.google.cloud.bigquery.v2.IDataset, - protos.google.cloud.bigquery.v2.IGetDatasetRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.bigquery.v2.IGetDatasetRequest, + callback: Callback< + protos.google.cloud.bigquery.v2.IDataset, + protos.google.cloud.bigquery.v2.IGetDatasetRequest | null | undefined, + {} | null | undefined + >, + ): void; getDataset( - request?: protos.google.cloud.bigquery.v2.IGetDatasetRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.bigquery.v2.IDataset, - protos.google.cloud.bigquery.v2.IGetDatasetRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.bigquery.v2.IGetDatasetRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.bigquery.v2.IDataset, - protos.google.cloud.bigquery.v2.IGetDatasetRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.bigquery.v2.IDataset, - protos.google.cloud.bigquery.v2.IGetDatasetRequest|undefined, {}|undefined - ]>|void { + protos.google.cloud.bigquery.v2.IGetDatasetRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.bigquery.v2.IDataset, + protos.google.cloud.bigquery.v2.IGetDatasetRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.bigquery.v2.IDataset, + protos.google.cloud.bigquery.v2.IGetDatasetRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'project_id': request.projectId?.toString() ?? '', - 'dataset_id': request.datasetId?.toString() ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + project_id: request.projectId?.toString() ?? '', + dataset_id: request.datasetId?.toString() ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getDataset request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.bigquery.v2.IDataset, - protos.google.cloud.bigquery.v2.IGetDatasetRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.bigquery.v2.IDataset, + protos.google.cloud.bigquery.v2.IGetDatasetRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getDataset response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getDataset(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.bigquery.v2.IDataset, - protos.google.cloud.bigquery.v2.IGetDatasetRequest|undefined, - {}|undefined - ]) => { - this._log.info('getDataset response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getDataset(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.bigquery.v2.IDataset, + protos.google.cloud.bigquery.v2.IGetDatasetRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getDataset response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Creates a new empty dataset. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.projectId - * Required. Project ID of the new dataset - * @param {google.cloud.bigquery.v2.Dataset} request.dataset - * Required. Datasets resource to use for the new dataset - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.bigquery.v2.Dataset|Dataset}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/dataset_service.insert_dataset.js - * region_tag:bigquery_v2_generated_DatasetService_InsertDataset_async - */ + /** + * Creates a new empty dataset. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.projectId + * Required. Project ID of the new dataset + * @param {google.cloud.bigquery.v2.Dataset} request.dataset + * Required. Datasets resource to use for the new dataset + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.bigquery.v2.Dataset|Dataset}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/dataset_service.insert_dataset.js + * region_tag:bigquery_v2_generated_DatasetService_InsertDataset_async + */ insertDataset( - request?: protos.google.cloud.bigquery.v2.IInsertDatasetRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.bigquery.v2.IDataset, - protos.google.cloud.bigquery.v2.IInsertDatasetRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.bigquery.v2.IInsertDatasetRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.bigquery.v2.IDataset, + protos.google.cloud.bigquery.v2.IInsertDatasetRequest | undefined, + {} | undefined, + ] + >; insertDataset( - request: protos.google.cloud.bigquery.v2.IInsertDatasetRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.bigquery.v2.IDataset, - protos.google.cloud.bigquery.v2.IInsertDatasetRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.bigquery.v2.IInsertDatasetRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.bigquery.v2.IDataset, + protos.google.cloud.bigquery.v2.IInsertDatasetRequest | null | undefined, + {} | null | undefined + >, + ): void; insertDataset( - request: protos.google.cloud.bigquery.v2.IInsertDatasetRequest, - callback: Callback< - protos.google.cloud.bigquery.v2.IDataset, - protos.google.cloud.bigquery.v2.IInsertDatasetRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.bigquery.v2.IInsertDatasetRequest, + callback: Callback< + protos.google.cloud.bigquery.v2.IDataset, + protos.google.cloud.bigquery.v2.IInsertDatasetRequest | null | undefined, + {} | null | undefined + >, + ): void; insertDataset( - request?: protos.google.cloud.bigquery.v2.IInsertDatasetRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.cloud.bigquery.v2.IInsertDatasetRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.bigquery.v2.IDataset, - protos.google.cloud.bigquery.v2.IInsertDatasetRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.cloud.bigquery.v2.IDataset, - protos.google.cloud.bigquery.v2.IInsertDatasetRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.bigquery.v2.IDataset, - protos.google.cloud.bigquery.v2.IInsertDatasetRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.bigquery.v2.IInsertDatasetRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.bigquery.v2.IDataset, + protos.google.cloud.bigquery.v2.IInsertDatasetRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.bigquery.v2.IDataset, + protos.google.cloud.bigquery.v2.IInsertDatasetRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'project_id': request.projectId?.toString() ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + project_id: request.projectId?.toString() ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('insertDataset request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.bigquery.v2.IDataset, - protos.google.cloud.bigquery.v2.IInsertDatasetRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.bigquery.v2.IDataset, + | protos.google.cloud.bigquery.v2.IInsertDatasetRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('insertDataset response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.insertDataset(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.bigquery.v2.IDataset, - protos.google.cloud.bigquery.v2.IInsertDatasetRequest|undefined, - {}|undefined - ]) => { - this._log.info('insertDataset response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .insertDataset(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.bigquery.v2.IDataset, + protos.google.cloud.bigquery.v2.IInsertDatasetRequest | undefined, + {} | undefined, + ]) => { + this._log.info('insertDataset response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Updates information in an existing dataset. The update method replaces the - * entire dataset resource, whereas the patch method only replaces fields that - * are provided in the submitted dataset resource. - * This method supports RFC5789 patch semantics. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.projectId - * Required. Project ID of the dataset being updated - * @param {string} request.datasetId - * Required. Dataset ID of the dataset being updated - * @param {google.cloud.bigquery.v2.Dataset} request.dataset - * Required. Datasets resource which will replace or patch the specified - * dataset. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.bigquery.v2.Dataset|Dataset}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/dataset_service.patch_dataset.js - * region_tag:bigquery_v2_generated_DatasetService_PatchDataset_async - */ + /** + * Updates information in an existing dataset. The update method replaces the + * entire dataset resource, whereas the patch method only replaces fields that + * are provided in the submitted dataset resource. + * This method supports RFC5789 patch semantics. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.projectId + * Required. Project ID of the dataset being updated + * @param {string} request.datasetId + * Required. Dataset ID of the dataset being updated + * @param {google.cloud.bigquery.v2.Dataset} request.dataset + * Required. Datasets resource which will replace or patch the specified + * dataset. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.bigquery.v2.Dataset|Dataset}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/dataset_service.patch_dataset.js + * region_tag:bigquery_v2_generated_DatasetService_PatchDataset_async + */ patchDataset( - request?: protos.google.cloud.bigquery.v2.IUpdateOrPatchDatasetRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.bigquery.v2.IDataset, - protos.google.cloud.bigquery.v2.IUpdateOrPatchDatasetRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.bigquery.v2.IUpdateOrPatchDatasetRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.bigquery.v2.IDataset, + protos.google.cloud.bigquery.v2.IUpdateOrPatchDatasetRequest | undefined, + {} | undefined, + ] + >; patchDataset( - request: protos.google.cloud.bigquery.v2.IUpdateOrPatchDatasetRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.bigquery.v2.IDataset, - protos.google.cloud.bigquery.v2.IUpdateOrPatchDatasetRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.bigquery.v2.IUpdateOrPatchDatasetRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.bigquery.v2.IDataset, + | protos.google.cloud.bigquery.v2.IUpdateOrPatchDatasetRequest + | null + | undefined, + {} | null | undefined + >, + ): void; patchDataset( - request: protos.google.cloud.bigquery.v2.IUpdateOrPatchDatasetRequest, - callback: Callback< - protos.google.cloud.bigquery.v2.IDataset, - protos.google.cloud.bigquery.v2.IUpdateOrPatchDatasetRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.bigquery.v2.IUpdateOrPatchDatasetRequest, + callback: Callback< + protos.google.cloud.bigquery.v2.IDataset, + | protos.google.cloud.bigquery.v2.IUpdateOrPatchDatasetRequest + | null + | undefined, + {} | null | undefined + >, + ): void; patchDataset( - request?: protos.google.cloud.bigquery.v2.IUpdateOrPatchDatasetRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.cloud.bigquery.v2.IUpdateOrPatchDatasetRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.bigquery.v2.IDataset, - protos.google.cloud.bigquery.v2.IUpdateOrPatchDatasetRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.cloud.bigquery.v2.IDataset, - protos.google.cloud.bigquery.v2.IUpdateOrPatchDatasetRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.bigquery.v2.IDataset, - protos.google.cloud.bigquery.v2.IUpdateOrPatchDatasetRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.bigquery.v2.IUpdateOrPatchDatasetRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.bigquery.v2.IDataset, + | protos.google.cloud.bigquery.v2.IUpdateOrPatchDatasetRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.bigquery.v2.IDataset, + protos.google.cloud.bigquery.v2.IUpdateOrPatchDatasetRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'project_id': request.projectId?.toString() ?? '', - 'dataset_id': request.datasetId?.toString() ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + project_id: request.projectId?.toString() ?? '', + dataset_id: request.datasetId?.toString() ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('patchDataset request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.bigquery.v2.IDataset, - protos.google.cloud.bigquery.v2.IUpdateOrPatchDatasetRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.bigquery.v2.IDataset, + | protos.google.cloud.bigquery.v2.IUpdateOrPatchDatasetRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('patchDataset response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.patchDataset(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.bigquery.v2.IDataset, - protos.google.cloud.bigquery.v2.IUpdateOrPatchDatasetRequest|undefined, - {}|undefined - ]) => { - this._log.info('patchDataset response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .patchDataset(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.bigquery.v2.IDataset, + ( + | protos.google.cloud.bigquery.v2.IUpdateOrPatchDatasetRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('patchDataset response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Updates information in an existing dataset. The update method replaces the - * entire dataset resource, whereas the patch method only replaces fields that - * are provided in the submitted dataset resource. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.projectId - * Required. Project ID of the dataset being updated - * @param {string} request.datasetId - * Required. Dataset ID of the dataset being updated - * @param {google.cloud.bigquery.v2.Dataset} request.dataset - * Required. Datasets resource which will replace or patch the specified - * dataset. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.bigquery.v2.Dataset|Dataset}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/dataset_service.update_dataset.js - * region_tag:bigquery_v2_generated_DatasetService_UpdateDataset_async - */ + /** + * Updates information in an existing dataset. The update method replaces the + * entire dataset resource, whereas the patch method only replaces fields that + * are provided in the submitted dataset resource. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.projectId + * Required. Project ID of the dataset being updated + * @param {string} request.datasetId + * Required. Dataset ID of the dataset being updated + * @param {google.cloud.bigquery.v2.Dataset} request.dataset + * Required. Datasets resource which will replace or patch the specified + * dataset. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.bigquery.v2.Dataset|Dataset}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/dataset_service.update_dataset.js + * region_tag:bigquery_v2_generated_DatasetService_UpdateDataset_async + */ updateDataset( - request?: protos.google.cloud.bigquery.v2.IUpdateOrPatchDatasetRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.bigquery.v2.IDataset, - protos.google.cloud.bigquery.v2.IUpdateOrPatchDatasetRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.bigquery.v2.IUpdateOrPatchDatasetRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.bigquery.v2.IDataset, + protos.google.cloud.bigquery.v2.IUpdateOrPatchDatasetRequest | undefined, + {} | undefined, + ] + >; updateDataset( - request: protos.google.cloud.bigquery.v2.IUpdateOrPatchDatasetRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.bigquery.v2.IDataset, - protos.google.cloud.bigquery.v2.IUpdateOrPatchDatasetRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.bigquery.v2.IUpdateOrPatchDatasetRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.bigquery.v2.IDataset, + | protos.google.cloud.bigquery.v2.IUpdateOrPatchDatasetRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateDataset( - request: protos.google.cloud.bigquery.v2.IUpdateOrPatchDatasetRequest, - callback: Callback< - protos.google.cloud.bigquery.v2.IDataset, - protos.google.cloud.bigquery.v2.IUpdateOrPatchDatasetRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.bigquery.v2.IUpdateOrPatchDatasetRequest, + callback: Callback< + protos.google.cloud.bigquery.v2.IDataset, + | protos.google.cloud.bigquery.v2.IUpdateOrPatchDatasetRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateDataset( - request?: protos.google.cloud.bigquery.v2.IUpdateOrPatchDatasetRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.bigquery.v2.IDataset, - protos.google.cloud.bigquery.v2.IUpdateOrPatchDatasetRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.bigquery.v2.IUpdateOrPatchDatasetRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.bigquery.v2.IDataset, - protos.google.cloud.bigquery.v2.IUpdateOrPatchDatasetRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.bigquery.v2.IDataset, - protos.google.cloud.bigquery.v2.IUpdateOrPatchDatasetRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.bigquery.v2.IUpdateOrPatchDatasetRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.bigquery.v2.IDataset, + | protos.google.cloud.bigquery.v2.IUpdateOrPatchDatasetRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.bigquery.v2.IDataset, + protos.google.cloud.bigquery.v2.IUpdateOrPatchDatasetRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'project_id': request.projectId?.toString() ?? '', - 'dataset_id': request.datasetId?.toString() ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + project_id: request.projectId?.toString() ?? '', + dataset_id: request.datasetId?.toString() ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateDataset request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.bigquery.v2.IDataset, - protos.google.cloud.bigquery.v2.IUpdateOrPatchDatasetRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.bigquery.v2.IDataset, + | protos.google.cloud.bigquery.v2.IUpdateOrPatchDatasetRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateDataset response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.updateDataset(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.bigquery.v2.IDataset, - protos.google.cloud.bigquery.v2.IUpdateOrPatchDatasetRequest|undefined, - {}|undefined - ]) => { - this._log.info('updateDataset response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateDataset(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.bigquery.v2.IDataset, + ( + | protos.google.cloud.bigquery.v2.IUpdateOrPatchDatasetRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('updateDataset response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Deletes the dataset specified by the datasetId value. Before you can delete - * a dataset, you must delete all its tables, either manually or by specifying - * deleteContents. Immediately after deletion, you can create another dataset - * with the same name. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.projectId - * Required. Project ID of the dataset being deleted - * @param {string} request.datasetId - * Required. Dataset ID of dataset being deleted - * @param {boolean} request.deleteContents - * If True, delete all the tables in the dataset. - * If False and the dataset contains tables, the request will fail. - * Default is False - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/dataset_service.delete_dataset.js - * region_tag:bigquery_v2_generated_DatasetService_DeleteDataset_async - */ + /** + * Deletes the dataset specified by the datasetId value. Before you can delete + * a dataset, you must delete all its tables, either manually or by specifying + * deleteContents. Immediately after deletion, you can create another dataset + * with the same name. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.projectId + * Required. Project ID of the dataset being deleted + * @param {string} request.datasetId + * Required. Dataset ID of dataset being deleted + * @param {boolean} request.deleteContents + * If True, delete all the tables in the dataset. + * If False and the dataset contains tables, the request will fail. + * Default is False + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/dataset_service.delete_dataset.js + * region_tag:bigquery_v2_generated_DatasetService_DeleteDataset_async + */ deleteDataset( - request?: protos.google.cloud.bigquery.v2.IDeleteDatasetRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.cloud.bigquery.v2.IDeleteDatasetRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.bigquery.v2.IDeleteDatasetRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.cloud.bigquery.v2.IDeleteDatasetRequest | undefined, + {} | undefined, + ] + >; deleteDataset( - request: protos.google.cloud.bigquery.v2.IDeleteDatasetRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.cloud.bigquery.v2.IDeleteDatasetRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.bigquery.v2.IDeleteDatasetRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.cloud.bigquery.v2.IDeleteDatasetRequest | null | undefined, + {} | null | undefined + >, + ): void; deleteDataset( - request: protos.google.cloud.bigquery.v2.IDeleteDatasetRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.cloud.bigquery.v2.IDeleteDatasetRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.bigquery.v2.IDeleteDatasetRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.cloud.bigquery.v2.IDeleteDatasetRequest | null | undefined, + {} | null | undefined + >, + ): void; deleteDataset( - request?: protos.google.cloud.bigquery.v2.IDeleteDatasetRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.protobuf.IEmpty, - protos.google.cloud.bigquery.v2.IDeleteDatasetRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.bigquery.v2.IDeleteDatasetRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.cloud.bigquery.v2.IDeleteDatasetRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.cloud.bigquery.v2.IDeleteDatasetRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.bigquery.v2.IDeleteDatasetRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + protos.google.cloud.bigquery.v2.IDeleteDatasetRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.cloud.bigquery.v2.IDeleteDatasetRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'project_id': request.projectId?.toString() ?? '', - 'dataset_id': request.datasetId?.toString() ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + project_id: request.projectId?.toString() ?? '', + dataset_id: request.datasetId?.toString() ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('deleteDataset request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.cloud.bigquery.v2.IDeleteDatasetRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.cloud.bigquery.v2.IDeleteDatasetRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteDataset response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.deleteDataset(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.cloud.bigquery.v2.IDeleteDatasetRequest|undefined, - {}|undefined - ]) => { - this._log.info('deleteDataset response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteDataset(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.cloud.bigquery.v2.IDeleteDatasetRequest | undefined, + {} | undefined, + ]) => { + this._log.info('deleteDataset response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Undeletes a dataset which is within time travel window based on datasetId. - * If a time is specified, the dataset version deleted at that time is - * undeleted, else the last live version is undeleted. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.projectId - * Required. Project ID of the dataset to be undeleted - * @param {string} request.datasetId - * Required. Dataset ID of dataset being deleted - * @param {google.protobuf.Timestamp} [request.deletionTime] - * Optional. The exact time when the dataset was deleted. If not specified, - * the most recently deleted version is undeleted. Undeleting a dataset - * using deletion time is not supported. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.bigquery.v2.Dataset|Dataset}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/dataset_service.undelete_dataset.js - * region_tag:bigquery_v2_generated_DatasetService_UndeleteDataset_async - */ + /** + * Undeletes a dataset which is within time travel window based on datasetId. + * If a time is specified, the dataset version deleted at that time is + * undeleted, else the last live version is undeleted. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.projectId + * Required. Project ID of the dataset to be undeleted + * @param {string} request.datasetId + * Required. Dataset ID of dataset being deleted + * @param {google.protobuf.Timestamp} [request.deletionTime] + * Optional. The exact time when the dataset was deleted. If not specified, + * the most recently deleted version is undeleted. Undeleting a dataset + * using deletion time is not supported. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.bigquery.v2.Dataset|Dataset}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/dataset_service.undelete_dataset.js + * region_tag:bigquery_v2_generated_DatasetService_UndeleteDataset_async + */ undeleteDataset( - request?: protos.google.cloud.bigquery.v2.IUndeleteDatasetRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.bigquery.v2.IDataset, - protos.google.cloud.bigquery.v2.IUndeleteDatasetRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.bigquery.v2.IUndeleteDatasetRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.bigquery.v2.IDataset, + protos.google.cloud.bigquery.v2.IUndeleteDatasetRequest | undefined, + {} | undefined, + ] + >; undeleteDataset( - request: protos.google.cloud.bigquery.v2.IUndeleteDatasetRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.bigquery.v2.IDataset, - protos.google.cloud.bigquery.v2.IUndeleteDatasetRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.bigquery.v2.IUndeleteDatasetRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.bigquery.v2.IDataset, + | protos.google.cloud.bigquery.v2.IUndeleteDatasetRequest + | null + | undefined, + {} | null | undefined + >, + ): void; undeleteDataset( - request: protos.google.cloud.bigquery.v2.IUndeleteDatasetRequest, - callback: Callback< - protos.google.cloud.bigquery.v2.IDataset, - protos.google.cloud.bigquery.v2.IUndeleteDatasetRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.bigquery.v2.IUndeleteDatasetRequest, + callback: Callback< + protos.google.cloud.bigquery.v2.IDataset, + | protos.google.cloud.bigquery.v2.IUndeleteDatasetRequest + | null + | undefined, + {} | null | undefined + >, + ): void; undeleteDataset( - request?: protos.google.cloud.bigquery.v2.IUndeleteDatasetRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.bigquery.v2.IDataset, - protos.google.cloud.bigquery.v2.IUndeleteDatasetRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.bigquery.v2.IUndeleteDatasetRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.bigquery.v2.IDataset, - protos.google.cloud.bigquery.v2.IUndeleteDatasetRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.bigquery.v2.IDataset, - protos.google.cloud.bigquery.v2.IUndeleteDatasetRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.bigquery.v2.IUndeleteDatasetRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.bigquery.v2.IDataset, + | protos.google.cloud.bigquery.v2.IUndeleteDatasetRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.bigquery.v2.IDataset, + protos.google.cloud.bigquery.v2.IUndeleteDatasetRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'project_id': request.projectId?.toString() ?? '', - 'dataset_id': request.datasetId?.toString() ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + project_id: request.projectId?.toString() ?? '', + dataset_id: request.datasetId?.toString() ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('undeleteDataset request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.bigquery.v2.IDataset, - protos.google.cloud.bigquery.v2.IUndeleteDatasetRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.bigquery.v2.IDataset, + | protos.google.cloud.bigquery.v2.IUndeleteDatasetRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('undeleteDataset response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.undeleteDataset(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.bigquery.v2.IDataset, - protos.google.cloud.bigquery.v2.IUndeleteDatasetRequest|undefined, - {}|undefined - ]) => { - this._log.info('undeleteDataset response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .undeleteDataset(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.bigquery.v2.IDataset, + protos.google.cloud.bigquery.v2.IUndeleteDatasetRequest | undefined, + {} | undefined, + ]) => { + this._log.info('undeleteDataset response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } - /** - * Lists all datasets in the specified project to which the user has been - * granted the READER dataset role. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.projectId - * Required. Project ID of the datasets to be listed - * @param {google.protobuf.UInt32Value| number } request.maxResults - * The maximum number of results to return in a single response page. - * Leverage the page tokens to iterate through the entire collection. - * @param {string} request.pageToken - * Page token, returned by a previous call, to request the next page of - * results - * @param {boolean} request.all - * Whether to list all datasets, including hidden ones - * @param {string} request.filter - * An expression for filtering the results of the request by label. - * The syntax is `labels.[:]`. - * Multiple filters can be ANDed together by connecting with a space. - * Example: `labels.department:receiving labels.active`. - * See [Filtering datasets using - * labels](https://cloud.google.com/bigquery/docs/filtering-labels#filtering_datasets_using_labels) - * for details. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.cloud.bigquery.v2.ListFormatDataset|ListFormatDataset}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `listDatasetsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Lists all datasets in the specified project to which the user has been + * granted the READER dataset role. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.projectId + * Required. Project ID of the datasets to be listed + * @param {google.protobuf.UInt32Value| number } request.maxResults + * The maximum number of results to return in a single response page. + * Leverage the page tokens to iterate through the entire collection. + * @param {string} request.pageToken + * Page token, returned by a previous call, to request the next page of + * results + * @param {boolean} request.all + * Whether to list all datasets, including hidden ones + * @param {string} request.filter + * An expression for filtering the results of the request by label. + * The syntax is `labels.[:]`. + * Multiple filters can be ANDed together by connecting with a space. + * Example: `labels.department:receiving labels.active`. + * See [Filtering datasets using + * labels](https://cloud.google.com/bigquery/docs/filtering-labels#filtering_datasets_using_labels) + * for details. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.cloud.bigquery.v2.ListFormatDataset|ListFormatDataset}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listDatasetsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listDatasets( - request?: protos.google.cloud.bigquery.v2.IListDatasetsRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.bigquery.v2.IListFormatDataset[], - protos.google.cloud.bigquery.v2.IListDatasetsRequest|null, - protos.google.cloud.bigquery.v2.IDatasetList - ]>; + request?: protos.google.cloud.bigquery.v2.IListDatasetsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.bigquery.v2.IListFormatDataset[], + protos.google.cloud.bigquery.v2.IListDatasetsRequest | null, + protos.google.cloud.bigquery.v2.IDatasetList, + ] + >; listDatasets( - request: protos.google.cloud.bigquery.v2.IListDatasetsRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.cloud.bigquery.v2.IListDatasetsRequest, - protos.google.cloud.bigquery.v2.IDatasetList|null|undefined, - protos.google.cloud.bigquery.v2.IListFormatDataset>): void; + request: protos.google.cloud.bigquery.v2.IListDatasetsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.cloud.bigquery.v2.IListDatasetsRequest, + protos.google.cloud.bigquery.v2.IDatasetList | null | undefined, + protos.google.cloud.bigquery.v2.IListFormatDataset + >, + ): void; listDatasets( - request: protos.google.cloud.bigquery.v2.IListDatasetsRequest, - callback: PaginationCallback< - protos.google.cloud.bigquery.v2.IListDatasetsRequest, - protos.google.cloud.bigquery.v2.IDatasetList|null|undefined, - protos.google.cloud.bigquery.v2.IListFormatDataset>): void; + request: protos.google.cloud.bigquery.v2.IListDatasetsRequest, + callback: PaginationCallback< + protos.google.cloud.bigquery.v2.IListDatasetsRequest, + protos.google.cloud.bigquery.v2.IDatasetList | null | undefined, + protos.google.cloud.bigquery.v2.IListFormatDataset + >, + ): void; listDatasets( - request?: protos.google.cloud.bigquery.v2.IListDatasetsRequest, - optionsOrCallback?: CallOptions|PaginationCallback< - protos.google.cloud.bigquery.v2.IListDatasetsRequest, - protos.google.cloud.bigquery.v2.IDatasetList|null|undefined, - protos.google.cloud.bigquery.v2.IListFormatDataset>, - callback?: PaginationCallback< + request?: protos.google.cloud.bigquery.v2.IListDatasetsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.cloud.bigquery.v2.IListDatasetsRequest, - protos.google.cloud.bigquery.v2.IDatasetList|null|undefined, - protos.google.cloud.bigquery.v2.IListFormatDataset>): - Promise<[ - protos.google.cloud.bigquery.v2.IListFormatDataset[], - protos.google.cloud.bigquery.v2.IListDatasetsRequest|null, - protos.google.cloud.bigquery.v2.IDatasetList - ]>|void { + protos.google.cloud.bigquery.v2.IDatasetList | null | undefined, + protos.google.cloud.bigquery.v2.IListFormatDataset + >, + callback?: PaginationCallback< + protos.google.cloud.bigquery.v2.IListDatasetsRequest, + protos.google.cloud.bigquery.v2.IDatasetList | null | undefined, + protos.google.cloud.bigquery.v2.IListFormatDataset + >, + ): Promise< + [ + protos.google.cloud.bigquery.v2.IListFormatDataset[], + protos.google.cloud.bigquery.v2.IListDatasetsRequest | null, + protos.google.cloud.bigquery.v2.IDatasetList, + ] + > | void { request = request || {}; // Converts number to Unit32 or Int32 value for non-compliant APIs. - if(request.maxResults && typeof request.maxResults === "number"){ - const maxResultsObject = {"value": request.maxResults} - request.maxResults = maxResultsObject + if (request.maxResults && typeof request.maxResults === 'number') { + const maxResultsObject = { value: request.maxResults }; + request.maxResults = maxResultsObject; } let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'project_id': request.projectId?.toString() ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + project_id: request.projectId?.toString() ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.cloud.bigquery.v2.IListDatasetsRequest, - protos.google.cloud.bigquery.v2.IDatasetList|null|undefined, - protos.google.cloud.bigquery.v2.IListFormatDataset>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.cloud.bigquery.v2.IListDatasetsRequest, + protos.google.cloud.bigquery.v2.IDatasetList | null | undefined, + protos.google.cloud.bigquery.v2.IListFormatDataset + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listDatasets values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -1044,130 +1338,134 @@ export class DatasetServiceClient { this._log.info('listDatasets request %j', request); return this.innerApiCalls .listDatasets(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.cloud.bigquery.v2.IListFormatDataset[], - protos.google.cloud.bigquery.v2.IListDatasetsRequest|null, - protos.google.cloud.bigquery.v2.IDatasetList - ]) => { - this._log.info('listDatasets values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.cloud.bigquery.v2.IListFormatDataset[], + protos.google.cloud.bigquery.v2.IListDatasetsRequest | null, + protos.google.cloud.bigquery.v2.IDatasetList, + ]) => { + this._log.info('listDatasets values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listDatasets`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.projectId - * Required. Project ID of the datasets to be listed - * @param {google.protobuf.UInt32Value} request.maxResults - * The maximum number of results to return in a single response page. - * Leverage the page tokens to iterate through the entire collection. - * @param {string} request.pageToken - * Page token, returned by a previous call, to request the next page of - * results - * @param {boolean} request.all - * Whether to list all datasets, including hidden ones - * @param {string} request.filter - * An expression for filtering the results of the request by label. - * The syntax is `labels.[:]`. - * Multiple filters can be ANDed together by connecting with a space. - * Example: `labels.department:receiving labels.active`. - * See [Filtering datasets using - * labels](https://cloud.google.com/bigquery/docs/filtering-labels#filtering_datasets_using_labels) - * for details. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.cloud.bigquery.v2.ListFormatDataset|ListFormatDataset} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `listDatasetsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `listDatasets`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.projectId + * Required. Project ID of the datasets to be listed + * @param {google.protobuf.UInt32Value} request.maxResults + * The maximum number of results to return in a single response page. + * Leverage the page tokens to iterate through the entire collection. + * @param {string} request.pageToken + * Page token, returned by a previous call, to request the next page of + * results + * @param {boolean} request.all + * Whether to list all datasets, including hidden ones + * @param {string} request.filter + * An expression for filtering the results of the request by label. + * The syntax is `labels.[:]`. + * Multiple filters can be ANDed together by connecting with a space. + * Example: `labels.department:receiving labels.active`. + * See [Filtering datasets using + * labels](https://cloud.google.com/bigquery/docs/filtering-labels#filtering_datasets_using_labels) + * for details. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.cloud.bigquery.v2.ListFormatDataset|ListFormatDataset} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listDatasetsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listDatasetsStream( - request?: protos.google.cloud.bigquery.v2.IListDatasetsRequest, - options?: CallOptions): - Transform{ + request?: protos.google.cloud.bigquery.v2.IListDatasetsRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'project_id': request.projectId?.toString() ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + project_id: request.projectId?.toString() ?? '', + }); const defaultCallSettings = this._defaults['listDatasets']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listDatasets stream %j', request); return this.descriptors.page.listDatasets.createStream( this.innerApiCalls.listDatasets as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listDatasets`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.projectId - * Required. Project ID of the datasets to be listed - * @param {google.protobuf.UInt32Value} request.maxResults - * The maximum number of results to return in a single response page. - * Leverage the page tokens to iterate through the entire collection. - * @param {string} request.pageToken - * Page token, returned by a previous call, to request the next page of - * results - * @param {boolean} request.all - * Whether to list all datasets, including hidden ones - * @param {string} request.filter - * An expression for filtering the results of the request by label. - * The syntax is `labels.[:]`. - * Multiple filters can be ANDed together by connecting with a space. - * Example: `labels.department:receiving labels.active`. - * See [Filtering datasets using - * labels](https://cloud.google.com/bigquery/docs/filtering-labels#filtering_datasets_using_labels) - * for details. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.cloud.bigquery.v2.ListFormatDataset|ListFormatDataset}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v2/dataset_service.list_datasets.js - * region_tag:bigquery_v2_generated_DatasetService_ListDatasets_async - */ + /** + * Equivalent to `listDatasets`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.projectId + * Required. Project ID of the datasets to be listed + * @param {google.protobuf.UInt32Value} request.maxResults + * The maximum number of results to return in a single response page. + * Leverage the page tokens to iterate through the entire collection. + * @param {string} request.pageToken + * Page token, returned by a previous call, to request the next page of + * results + * @param {boolean} request.all + * Whether to list all datasets, including hidden ones + * @param {string} request.filter + * An expression for filtering the results of the request by label. + * The syntax is `labels.[:]`. + * Multiple filters can be ANDed together by connecting with a space. + * Example: `labels.department:receiving labels.active`. + * See [Filtering datasets using + * labels](https://cloud.google.com/bigquery/docs/filtering-labels#filtering_datasets_using_labels) + * for details. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.cloud.bigquery.v2.ListFormatDataset|ListFormatDataset}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v2/dataset_service.list_datasets.js + * region_tag:bigquery_v2_generated_DatasetService_ListDatasets_async + */ listDatasetsAsync( - request?: protos.google.cloud.bigquery.v2.IListDatasetsRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.cloud.bigquery.v2.IListDatasetsRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'project_id': request.projectId?.toString() ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + project_id: request.projectId?.toString() ?? '', + }); const defaultCallSettings = this._defaults['listDatasets']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listDatasets iterate %j', request); return this.descriptors.page.listDatasets.asyncIterate( this.innerApiCalls['listDatasets'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } @@ -1179,7 +1477,7 @@ export class DatasetServiceClient { */ close(): Promise { if (this.datasetServiceStub && !this._terminated) { - return this.datasetServiceStub.then(stub => { + return this.datasetServiceStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -1187,4 +1485,4 @@ export class DatasetServiceClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/core/generator/gapic-generator-typescript/baselines/bigquery-v2/src/v2/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/bigquery-v2/src/v2/index.ts.baseline index f8f6d8ed6976..9049574b14cc 100644 --- a/core/generator/gapic-generator-typescript/baselines/bigquery-v2/src/v2/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/bigquery-v2/src/v2/index.ts.baseline @@ -16,10 +16,10 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -export {DatasetServiceClient} from './dataset_service_client'; -export {JobServiceClient} from './job_service_client'; -export {ModelServiceClient} from './model_service_client'; -export {ProjectServiceClient} from './project_service_client'; -export {RoutineServiceClient} from './routine_service_client'; -export {RowAccessPolicyServiceClient} from './row_access_policy_service_client'; -export {TableServiceClient} from './table_service_client'; +export { DatasetServiceClient } from './dataset_service_client'; +export { JobServiceClient } from './job_service_client'; +export { ModelServiceClient } from './model_service_client'; +export { ProjectServiceClient } from './project_service_client'; +export { RoutineServiceClient } from './routine_service_client'; +export { RowAccessPolicyServiceClient } from './row_access_policy_service_client'; +export { TableServiceClient } from './table_service_client'; diff --git a/core/generator/gapic-generator-typescript/baselines/bigquery-v2/src/v2/job_service_client.ts.baseline b/core/generator/gapic-generator-typescript/baselines/bigquery-v2/src/v2/job_service_client.ts.baseline index a8e75365e8d8..9b4f29c67fc6 100644 --- a/core/generator/gapic-generator-typescript/baselines/bigquery-v2/src/v2/job_service_client.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/bigquery-v2/src/v2/job_service_client.ts.baseline @@ -18,11 +18,18 @@ /* global window */ import type * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions, PaginationCallback, GaxCall} from 'google-gax'; -import {Transform} from 'stream'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + PaginationCallback, + GaxCall, +} from 'google-gax'; +import { Transform } from 'stream'; import * as protos from '../../protos/protos'; import jsonProtos = require('../../protos/protos.json'); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; /** * Client JSON configuration object, loaded from @@ -47,7 +54,7 @@ export class JobServiceClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('bigquery'); @@ -60,8 +67,8 @@ export class JobServiceClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - jobServiceStub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + jobServiceStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of JobServiceClient. @@ -102,21 +109,42 @@ export class JobServiceClient { * const client = new JobServiceClient({fallback: true}, gax); * ``` */ - constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { // Ensure that options include all the required fields. const staticMembers = this.constructor as typeof JobServiceClient; - if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { - throw new Error('Please set either universe_domain or universeDomain, but not both.'); + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); } - const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; - this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; this._servicePath = 'bigquery.' + this._universeDomain; - const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; - const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. if (servicePath !== this._servicePath && !('scopes' in opts)) { @@ -138,7 +166,7 @@ export class JobServiceClient { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; @@ -152,10 +180,7 @@ export class JobServiceClient { } // Determine the client header string. - const clientHeader = [ - `gax/${this._gaxModule.version}`, - `gapic/${version}`, - ]; + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/${process.versions.node}`); } else { @@ -176,14 +201,20 @@ export class JobServiceClient { // (e.g. 50 results at a time, with tokens to get subsequent // pages). Denote the keys used for pagination and results. this.descriptors.page = { - listJobs: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'jobs') + listJobs: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'jobs', + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.cloud.bigquery.v2.JobService', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.cloud.bigquery.v2.JobService', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + { 'x-goog-api-client': clientHeader.join(' ') }, + ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -214,37 +245,48 @@ export class JobServiceClient { // Put together the "service stub" for // google.cloud.bigquery.v2.JobService. this.jobServiceStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.cloud.bigquery.v2.JobService') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.cloud.bigquery.v2.JobService', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.cloud.bigquery.v2.JobService, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts, + this._providedCustomServicePath, + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const jobServiceStubMethods = - ['cancelJob', 'getJob', 'insertJob', 'deleteJob', 'listJobs', 'getQueryResults', 'query']; + const jobServiceStubMethods = [ + 'cancelJob', + 'getJob', + 'insertJob', + 'deleteJob', + 'listJobs', + 'getQueryResults', + 'query', + ]; for (const methodName of jobServiceStubMethods) { const callPromise = this.jobServiceStub.then( - stub => (...args: Array<{}>) => { - if (this._terminated) { - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error|null|undefined) => () => { + (stub) => + (...args: Array<{}>) => { + if (this._terminated) { + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { throw err; - }); + }, + ); - const descriptor = - this.descriptors.page[methodName] || - undefined; + const descriptor = this.descriptors.page[methodName] || undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -259,8 +301,14 @@ export class JobServiceClient { * @returns {string} The DNS address for this service. */ static get servicePath() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'bigquery.googleapis.com'; } @@ -271,8 +319,14 @@ export class JobServiceClient { * @returns {string} The DNS address for this service. */ static get apiEndpoint() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'bigquery.googleapis.com'; } @@ -309,7 +363,7 @@ export class JobServiceClient { 'https://www.googleapis.com/auth/cloud-platform.read-only', 'https://www.googleapis.com/auth/devstorage.full_control', 'https://www.googleapis.com/auth/devstorage.read_only', - 'https://www.googleapis.com/auth/devstorage.read_write' + 'https://www.googleapis.com/auth/devstorage.read_write', ]; } @@ -319,8 +373,9 @@ export class JobServiceClient { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId(callback?: Callback): - Promise|void { + getProjectId( + callback?: Callback, + ): Promise | void { if (callback) { this.auth.getProjectId(callback); return; @@ -331,774 +386,979 @@ export class JobServiceClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Requests that a job be cancelled. This call will return immediately, and - * the client will need to poll for the job status to see if the cancel - * completed successfully. Cancelled jobs may still incur costs. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.projectId - * Required. Project ID of the job to cancel - * @param {string} request.jobId - * Required. Job ID of the job to cancel - * @param {string} request.location - * The geographic location of the job. You must specify the location to run - * the job for the following scenarios: - * - * * If the location to run a job is not in the `us` or - * the `eu` multi-regional location - * * If the job's location is in a single region (for example, - * `us-central1`) - * - * For more information, see - * https://cloud.google.com/bigquery/docs/locations#specifying_your_location. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.bigquery.v2.JobCancelResponse|JobCancelResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/job_service.cancel_job.js - * region_tag:bigquery_v2_generated_JobService_CancelJob_async - */ + /** + * Requests that a job be cancelled. This call will return immediately, and + * the client will need to poll for the job status to see if the cancel + * completed successfully. Cancelled jobs may still incur costs. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.projectId + * Required. Project ID of the job to cancel + * @param {string} request.jobId + * Required. Job ID of the job to cancel + * @param {string} request.location + * The geographic location of the job. You must specify the location to run + * the job for the following scenarios: + * + * * If the location to run a job is not in the `us` or + * the `eu` multi-regional location + * * If the job's location is in a single region (for example, + * `us-central1`) + * + * For more information, see + * https://cloud.google.com/bigquery/docs/locations#specifying_your_location. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.bigquery.v2.JobCancelResponse|JobCancelResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/job_service.cancel_job.js + * region_tag:bigquery_v2_generated_JobService_CancelJob_async + */ cancelJob( - request?: protos.google.cloud.bigquery.v2.ICancelJobRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.bigquery.v2.IJobCancelResponse, - protos.google.cloud.bigquery.v2.ICancelJobRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.bigquery.v2.ICancelJobRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.bigquery.v2.IJobCancelResponse, + protos.google.cloud.bigquery.v2.ICancelJobRequest | undefined, + {} | undefined, + ] + >; cancelJob( - request: protos.google.cloud.bigquery.v2.ICancelJobRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.bigquery.v2.IJobCancelResponse, - protos.google.cloud.bigquery.v2.ICancelJobRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.bigquery.v2.ICancelJobRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.bigquery.v2.IJobCancelResponse, + protos.google.cloud.bigquery.v2.ICancelJobRequest | null | undefined, + {} | null | undefined + >, + ): void; cancelJob( - request: protos.google.cloud.bigquery.v2.ICancelJobRequest, - callback: Callback< - protos.google.cloud.bigquery.v2.IJobCancelResponse, - protos.google.cloud.bigquery.v2.ICancelJobRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.bigquery.v2.ICancelJobRequest, + callback: Callback< + protos.google.cloud.bigquery.v2.IJobCancelResponse, + protos.google.cloud.bigquery.v2.ICancelJobRequest | null | undefined, + {} | null | undefined + >, + ): void; cancelJob( - request?: protos.google.cloud.bigquery.v2.ICancelJobRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.bigquery.v2.IJobCancelResponse, - protos.google.cloud.bigquery.v2.ICancelJobRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.bigquery.v2.ICancelJobRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.bigquery.v2.IJobCancelResponse, - protos.google.cloud.bigquery.v2.ICancelJobRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.bigquery.v2.IJobCancelResponse, - protos.google.cloud.bigquery.v2.ICancelJobRequest|undefined, {}|undefined - ]>|void { + protos.google.cloud.bigquery.v2.ICancelJobRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.bigquery.v2.IJobCancelResponse, + protos.google.cloud.bigquery.v2.ICancelJobRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.bigquery.v2.IJobCancelResponse, + protos.google.cloud.bigquery.v2.ICancelJobRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'project_id': request.projectId?.toString() ?? '', - 'job_id': request.jobId?.toString() ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + project_id: request.projectId?.toString() ?? '', + job_id: request.jobId?.toString() ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('cancelJob request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.bigquery.v2.IJobCancelResponse, - protos.google.cloud.bigquery.v2.ICancelJobRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.bigquery.v2.IJobCancelResponse, + protos.google.cloud.bigquery.v2.ICancelJobRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('cancelJob response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.cancelJob(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.bigquery.v2.IJobCancelResponse, - protos.google.cloud.bigquery.v2.ICancelJobRequest|undefined, - {}|undefined - ]) => { - this._log.info('cancelJob response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .cancelJob(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.bigquery.v2.IJobCancelResponse, + protos.google.cloud.bigquery.v2.ICancelJobRequest | undefined, + {} | undefined, + ]) => { + this._log.info('cancelJob response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Returns information about a specific job. Job information is available for - * a six month period after creation. Requires that you're the person who ran - * the job, or have the Is Owner project role. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.projectId - * Required. Project ID of the requested job. - * @param {string} request.jobId - * Required. Job ID of the requested job. - * @param {string} request.location - * The geographic location of the job. You must specify the location to run - * the job for the following scenarios: - * - * * If the location to run a job is not in the `us` or - * the `eu` multi-regional location - * * If the job's location is in a single region (for example, - * `us-central1`) - * - * For more information, see - * https://cloud.google.com/bigquery/docs/locations#specifying_your_location. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.bigquery.v2.Job|Job}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/job_service.get_job.js - * region_tag:bigquery_v2_generated_JobService_GetJob_async - */ + /** + * Returns information about a specific job. Job information is available for + * a six month period after creation. Requires that you're the person who ran + * the job, or have the Is Owner project role. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.projectId + * Required. Project ID of the requested job. + * @param {string} request.jobId + * Required. Job ID of the requested job. + * @param {string} request.location + * The geographic location of the job. You must specify the location to run + * the job for the following scenarios: + * + * * If the location to run a job is not in the `us` or + * the `eu` multi-regional location + * * If the job's location is in a single region (for example, + * `us-central1`) + * + * For more information, see + * https://cloud.google.com/bigquery/docs/locations#specifying_your_location. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.bigquery.v2.Job|Job}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/job_service.get_job.js + * region_tag:bigquery_v2_generated_JobService_GetJob_async + */ getJob( - request?: protos.google.cloud.bigquery.v2.IGetJobRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.bigquery.v2.IJob, - protos.google.cloud.bigquery.v2.IGetJobRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.bigquery.v2.IGetJobRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.bigquery.v2.IJob, + protos.google.cloud.bigquery.v2.IGetJobRequest | undefined, + {} | undefined, + ] + >; getJob( - request: protos.google.cloud.bigquery.v2.IGetJobRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.bigquery.v2.IJob, - protos.google.cloud.bigquery.v2.IGetJobRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.bigquery.v2.IGetJobRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.bigquery.v2.IJob, + protos.google.cloud.bigquery.v2.IGetJobRequest | null | undefined, + {} | null | undefined + >, + ): void; getJob( - request: protos.google.cloud.bigquery.v2.IGetJobRequest, - callback: Callback< - protos.google.cloud.bigquery.v2.IJob, - protos.google.cloud.bigquery.v2.IGetJobRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.bigquery.v2.IGetJobRequest, + callback: Callback< + protos.google.cloud.bigquery.v2.IJob, + protos.google.cloud.bigquery.v2.IGetJobRequest | null | undefined, + {} | null | undefined + >, + ): void; getJob( - request?: protos.google.cloud.bigquery.v2.IGetJobRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.bigquery.v2.IJob, - protos.google.cloud.bigquery.v2.IGetJobRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.bigquery.v2.IGetJobRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.bigquery.v2.IJob, - protos.google.cloud.bigquery.v2.IGetJobRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.bigquery.v2.IJob, - protos.google.cloud.bigquery.v2.IGetJobRequest|undefined, {}|undefined - ]>|void { + protos.google.cloud.bigquery.v2.IGetJobRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.bigquery.v2.IJob, + protos.google.cloud.bigquery.v2.IGetJobRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.bigquery.v2.IJob, + protos.google.cloud.bigquery.v2.IGetJobRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'project_id': request.projectId?.toString() ?? '', - 'job_id': request.jobId?.toString() ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + project_id: request.projectId?.toString() ?? '', + job_id: request.jobId?.toString() ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getJob request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.bigquery.v2.IJob, - protos.google.cloud.bigquery.v2.IGetJobRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.bigquery.v2.IJob, + protos.google.cloud.bigquery.v2.IGetJobRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getJob response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getJob(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.bigquery.v2.IJob, - protos.google.cloud.bigquery.v2.IGetJobRequest|undefined, - {}|undefined - ]) => { - this._log.info('getJob response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getJob(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.bigquery.v2.IJob, + protos.google.cloud.bigquery.v2.IGetJobRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getJob response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Starts a new asynchronous job. - * - * This API has two different kinds of endpoint URIs, as this method supports - * a variety of use cases. - * - * * The *Metadata* URI is used for most interactions, as it accepts the job - * configuration directly. - * * The *Upload* URI is ONLY for the case when you're sending both a load job - * configuration and a data stream together. In this case, the Upload URI - * accepts the job configuration and the data as two distinct multipart MIME - * parts. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.projectId - * Project ID of project that will be billed for the job. - * @param {google.cloud.bigquery.v2.Job} request.job - * Jobs resource to insert. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.bigquery.v2.Job|Job}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/job_service.insert_job.js - * region_tag:bigquery_v2_generated_JobService_InsertJob_async - */ + /** + * Starts a new asynchronous job. + * + * This API has two different kinds of endpoint URIs, as this method supports + * a variety of use cases. + * + * * The *Metadata* URI is used for most interactions, as it accepts the job + * configuration directly. + * * The *Upload* URI is ONLY for the case when you're sending both a load job + * configuration and a data stream together. In this case, the Upload URI + * accepts the job configuration and the data as two distinct multipart MIME + * parts. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.projectId + * Project ID of project that will be billed for the job. + * @param {google.cloud.bigquery.v2.Job} request.job + * Jobs resource to insert. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.bigquery.v2.Job|Job}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/job_service.insert_job.js + * region_tag:bigquery_v2_generated_JobService_InsertJob_async + */ insertJob( - request?: protos.google.cloud.bigquery.v2.IInsertJobRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.bigquery.v2.IJob, - protos.google.cloud.bigquery.v2.IInsertJobRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.bigquery.v2.IInsertJobRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.bigquery.v2.IJob, + protos.google.cloud.bigquery.v2.IInsertJobRequest | undefined, + {} | undefined, + ] + >; insertJob( - request: protos.google.cloud.bigquery.v2.IInsertJobRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.bigquery.v2.IJob, - protos.google.cloud.bigquery.v2.IInsertJobRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.bigquery.v2.IInsertJobRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.bigquery.v2.IJob, + protos.google.cloud.bigquery.v2.IInsertJobRequest | null | undefined, + {} | null | undefined + >, + ): void; insertJob( - request: protos.google.cloud.bigquery.v2.IInsertJobRequest, - callback: Callback< - protos.google.cloud.bigquery.v2.IJob, - protos.google.cloud.bigquery.v2.IInsertJobRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.bigquery.v2.IInsertJobRequest, + callback: Callback< + protos.google.cloud.bigquery.v2.IJob, + protos.google.cloud.bigquery.v2.IInsertJobRequest | null | undefined, + {} | null | undefined + >, + ): void; insertJob( - request?: protos.google.cloud.bigquery.v2.IInsertJobRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.bigquery.v2.IJob, - protos.google.cloud.bigquery.v2.IInsertJobRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.bigquery.v2.IInsertJobRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.bigquery.v2.IJob, - protos.google.cloud.bigquery.v2.IInsertJobRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.bigquery.v2.IJob, - protos.google.cloud.bigquery.v2.IInsertJobRequest|undefined, {}|undefined - ]>|void { + protos.google.cloud.bigquery.v2.IInsertJobRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.bigquery.v2.IJob, + protos.google.cloud.bigquery.v2.IInsertJobRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.bigquery.v2.IJob, + protos.google.cloud.bigquery.v2.IInsertJobRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'project_id': request.projectId?.toString() ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + project_id: request.projectId?.toString() ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('insertJob request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.bigquery.v2.IJob, - protos.google.cloud.bigquery.v2.IInsertJobRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.bigquery.v2.IJob, + protos.google.cloud.bigquery.v2.IInsertJobRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('insertJob response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.insertJob(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.bigquery.v2.IJob, - protos.google.cloud.bigquery.v2.IInsertJobRequest|undefined, - {}|undefined - ]) => { - this._log.info('insertJob response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .insertJob(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.bigquery.v2.IJob, + protos.google.cloud.bigquery.v2.IInsertJobRequest | undefined, + {} | undefined, + ]) => { + this._log.info('insertJob response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Requests the deletion of the metadata of a job. This call returns when the - * job's metadata is deleted. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.projectId - * Required. Project ID of the job for which metadata is to be deleted. - * @param {string} request.jobId - * Required. Job ID of the job for which metadata is to be deleted. If this is - * a parent job which has child jobs, the metadata from all child jobs will be - * deleted as well. Direct deletion of the metadata of child jobs is not - * allowed. - * @param {string} request.location - * The geographic location of the job. Required. - * See details at: - * https://cloud.google.com/bigquery/docs/locations#specifying_your_location. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/job_service.delete_job.js - * region_tag:bigquery_v2_generated_JobService_DeleteJob_async - */ + /** + * Requests the deletion of the metadata of a job. This call returns when the + * job's metadata is deleted. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.projectId + * Required. Project ID of the job for which metadata is to be deleted. + * @param {string} request.jobId + * Required. Job ID of the job for which metadata is to be deleted. If this is + * a parent job which has child jobs, the metadata from all child jobs will be + * deleted as well. Direct deletion of the metadata of child jobs is not + * allowed. + * @param {string} request.location + * The geographic location of the job. Required. + * See details at: + * https://cloud.google.com/bigquery/docs/locations#specifying_your_location. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/job_service.delete_job.js + * region_tag:bigquery_v2_generated_JobService_DeleteJob_async + */ deleteJob( - request?: protos.google.cloud.bigquery.v2.IDeleteJobRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.cloud.bigquery.v2.IDeleteJobRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.bigquery.v2.IDeleteJobRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.cloud.bigquery.v2.IDeleteJobRequest | undefined, + {} | undefined, + ] + >; deleteJob( - request: protos.google.cloud.bigquery.v2.IDeleteJobRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.cloud.bigquery.v2.IDeleteJobRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.bigquery.v2.IDeleteJobRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.cloud.bigquery.v2.IDeleteJobRequest | null | undefined, + {} | null | undefined + >, + ): void; deleteJob( - request: protos.google.cloud.bigquery.v2.IDeleteJobRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.cloud.bigquery.v2.IDeleteJobRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.bigquery.v2.IDeleteJobRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.cloud.bigquery.v2.IDeleteJobRequest | null | undefined, + {} | null | undefined + >, + ): void; deleteJob( - request?: protos.google.cloud.bigquery.v2.IDeleteJobRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.protobuf.IEmpty, - protos.google.cloud.bigquery.v2.IDeleteJobRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.bigquery.v2.IDeleteJobRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.cloud.bigquery.v2.IDeleteJobRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.cloud.bigquery.v2.IDeleteJobRequest|undefined, {}|undefined - ]>|void { + protos.google.cloud.bigquery.v2.IDeleteJobRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + protos.google.cloud.bigquery.v2.IDeleteJobRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.cloud.bigquery.v2.IDeleteJobRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'project_id': request.projectId?.toString() ?? '', - 'job_id': request.jobId?.toString() ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + project_id: request.projectId?.toString() ?? '', + job_id: request.jobId?.toString() ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('deleteJob request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.cloud.bigquery.v2.IDeleteJobRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + protos.google.cloud.bigquery.v2.IDeleteJobRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteJob response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.deleteJob(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.cloud.bigquery.v2.IDeleteJobRequest|undefined, - {}|undefined - ]) => { - this._log.info('deleteJob response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteJob(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.cloud.bigquery.v2.IDeleteJobRequest | undefined, + {} | undefined, + ]) => { + this._log.info('deleteJob response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * RPC to get the results of a query job. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.projectId - * Required. Project ID of the query job. - * @param {string} request.jobId - * Required. Job ID of the query job. - * @param {google.protobuf.UInt64Value} request.startIndex - * Zero-based index of the starting row. - * @param {string} request.pageToken - * Page token, returned by a previous call, to request the next page of - * results. - * @param {google.protobuf.UInt32Value} request.maxResults - * Maximum number of results to read. - * @param {google.protobuf.UInt32Value} request.timeoutMs - * Optional: Specifies the maximum amount of time, in milliseconds, that the - * client is willing to wait for the query to complete. By default, this limit - * is 10 seconds (10,000 milliseconds). If the query is complete, the - * jobComplete field in the response is true. If the query has not yet - * completed, jobComplete is false. - * - * You can request a longer timeout period in the timeoutMs field. However, - * the call is not guaranteed to wait for the specified timeout; it typically - * returns after around 200 seconds (200,000 milliseconds), even if the query - * is not complete. - * - * If jobComplete is false, you can continue to wait for the query to complete - * by calling the getQueryResults method until the jobComplete field in the - * getQueryResults response is true. - * @param {string} request.location - * The geographic location of the job. You must specify the location to run - * the job for the following scenarios: - * - * * If the location to run a job is not in the `us` or - * the `eu` multi-regional location - * * If the job's location is in a single region (for example, - * `us-central1`) - * - * For more information, see - * https://cloud.google.com/bigquery/docs/locations#specifying_your_location. - * @param {google.cloud.bigquery.v2.DataFormatOptions} [request.formatOptions] - * Optional. Output format adjustments. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.bigquery.v2.GetQueryResultsResponse|GetQueryResultsResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/job_service.get_query_results.js - * region_tag:bigquery_v2_generated_JobService_GetQueryResults_async - */ + /** + * RPC to get the results of a query job. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.projectId + * Required. Project ID of the query job. + * @param {string} request.jobId + * Required. Job ID of the query job. + * @param {google.protobuf.UInt64Value} request.startIndex + * Zero-based index of the starting row. + * @param {string} request.pageToken + * Page token, returned by a previous call, to request the next page of + * results. + * @param {google.protobuf.UInt32Value} request.maxResults + * Maximum number of results to read. + * @param {google.protobuf.UInt32Value} request.timeoutMs + * Optional: Specifies the maximum amount of time, in milliseconds, that the + * client is willing to wait for the query to complete. By default, this limit + * is 10 seconds (10,000 milliseconds). If the query is complete, the + * jobComplete field in the response is true. If the query has not yet + * completed, jobComplete is false. + * + * You can request a longer timeout period in the timeoutMs field. However, + * the call is not guaranteed to wait for the specified timeout; it typically + * returns after around 200 seconds (200,000 milliseconds), even if the query + * is not complete. + * + * If jobComplete is false, you can continue to wait for the query to complete + * by calling the getQueryResults method until the jobComplete field in the + * getQueryResults response is true. + * @param {string} request.location + * The geographic location of the job. You must specify the location to run + * the job for the following scenarios: + * + * * If the location to run a job is not in the `us` or + * the `eu` multi-regional location + * * If the job's location is in a single region (for example, + * `us-central1`) + * + * For more information, see + * https://cloud.google.com/bigquery/docs/locations#specifying_your_location. + * @param {google.cloud.bigquery.v2.DataFormatOptions} [request.formatOptions] + * Optional. Output format adjustments. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.bigquery.v2.GetQueryResultsResponse|GetQueryResultsResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/job_service.get_query_results.js + * region_tag:bigquery_v2_generated_JobService_GetQueryResults_async + */ getQueryResults( - request?: protos.google.cloud.bigquery.v2.IGetQueryResultsRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.bigquery.v2.IGetQueryResultsResponse, - protos.google.cloud.bigquery.v2.IGetQueryResultsRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.bigquery.v2.IGetQueryResultsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.bigquery.v2.IGetQueryResultsResponse, + protos.google.cloud.bigquery.v2.IGetQueryResultsRequest | undefined, + {} | undefined, + ] + >; getQueryResults( - request: protos.google.cloud.bigquery.v2.IGetQueryResultsRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.bigquery.v2.IGetQueryResultsResponse, - protos.google.cloud.bigquery.v2.IGetQueryResultsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.bigquery.v2.IGetQueryResultsRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.bigquery.v2.IGetQueryResultsResponse, + | protos.google.cloud.bigquery.v2.IGetQueryResultsRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getQueryResults( - request: protos.google.cloud.bigquery.v2.IGetQueryResultsRequest, - callback: Callback< - protos.google.cloud.bigquery.v2.IGetQueryResultsResponse, - protos.google.cloud.bigquery.v2.IGetQueryResultsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.bigquery.v2.IGetQueryResultsRequest, + callback: Callback< + protos.google.cloud.bigquery.v2.IGetQueryResultsResponse, + | protos.google.cloud.bigquery.v2.IGetQueryResultsRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getQueryResults( - request?: protos.google.cloud.bigquery.v2.IGetQueryResultsRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.bigquery.v2.IGetQueryResultsResponse, - protos.google.cloud.bigquery.v2.IGetQueryResultsRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.bigquery.v2.IGetQueryResultsRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.bigquery.v2.IGetQueryResultsResponse, - protos.google.cloud.bigquery.v2.IGetQueryResultsRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.bigquery.v2.IGetQueryResultsResponse, - protos.google.cloud.bigquery.v2.IGetQueryResultsRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.bigquery.v2.IGetQueryResultsRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.bigquery.v2.IGetQueryResultsResponse, + | protos.google.cloud.bigquery.v2.IGetQueryResultsRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.bigquery.v2.IGetQueryResultsResponse, + protos.google.cloud.bigquery.v2.IGetQueryResultsRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'project_id': request.projectId?.toString() ?? '', - 'job_id': request.jobId?.toString() ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + project_id: request.projectId?.toString() ?? '', + job_id: request.jobId?.toString() ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getQueryResults request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.bigquery.v2.IGetQueryResultsResponse, - protos.google.cloud.bigquery.v2.IGetQueryResultsRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.bigquery.v2.IGetQueryResultsResponse, + | protos.google.cloud.bigquery.v2.IGetQueryResultsRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getQueryResults response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getQueryResults(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.bigquery.v2.IGetQueryResultsResponse, - protos.google.cloud.bigquery.v2.IGetQueryResultsRequest|undefined, - {}|undefined - ]) => { - this._log.info('getQueryResults response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getQueryResults(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.bigquery.v2.IGetQueryResultsResponse, + protos.google.cloud.bigquery.v2.IGetQueryResultsRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getQueryResults response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Runs a BigQuery SQL query synchronously and returns query results if the - * query completes within a specified timeout. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.projectId - * Required. Project ID of the query request. - * @param {google.cloud.bigquery.v2.QueryRequest} request.queryRequest - * The query request body. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.bigquery.v2.QueryResponse|QueryResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/job_service.query.js - * region_tag:bigquery_v2_generated_JobService_Query_async - */ + /** + * Runs a BigQuery SQL query synchronously and returns query results if the + * query completes within a specified timeout. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.projectId + * Required. Project ID of the query request. + * @param {google.cloud.bigquery.v2.QueryRequest} request.queryRequest + * The query request body. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.bigquery.v2.QueryResponse|QueryResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/job_service.query.js + * region_tag:bigquery_v2_generated_JobService_Query_async + */ query( - request?: protos.google.cloud.bigquery.v2.IPostQueryRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.bigquery.v2.IQueryResponse, - protos.google.cloud.bigquery.v2.IPostQueryRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.bigquery.v2.IPostQueryRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.bigquery.v2.IQueryResponse, + protos.google.cloud.bigquery.v2.IPostQueryRequest | undefined, + {} | undefined, + ] + >; query( - request: protos.google.cloud.bigquery.v2.IPostQueryRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.bigquery.v2.IQueryResponse, - protos.google.cloud.bigquery.v2.IPostQueryRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.bigquery.v2.IPostQueryRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.bigquery.v2.IQueryResponse, + protos.google.cloud.bigquery.v2.IPostQueryRequest | null | undefined, + {} | null | undefined + >, + ): void; query( - request: protos.google.cloud.bigquery.v2.IPostQueryRequest, - callback: Callback< - protos.google.cloud.bigquery.v2.IQueryResponse, - protos.google.cloud.bigquery.v2.IPostQueryRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.bigquery.v2.IPostQueryRequest, + callback: Callback< + protos.google.cloud.bigquery.v2.IQueryResponse, + protos.google.cloud.bigquery.v2.IPostQueryRequest | null | undefined, + {} | null | undefined + >, + ): void; query( - request?: protos.google.cloud.bigquery.v2.IPostQueryRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.bigquery.v2.IQueryResponse, - protos.google.cloud.bigquery.v2.IPostQueryRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.bigquery.v2.IPostQueryRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.bigquery.v2.IQueryResponse, - protos.google.cloud.bigquery.v2.IPostQueryRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.bigquery.v2.IQueryResponse, - protos.google.cloud.bigquery.v2.IPostQueryRequest|undefined, {}|undefined - ]>|void { + protos.google.cloud.bigquery.v2.IPostQueryRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.bigquery.v2.IQueryResponse, + protos.google.cloud.bigquery.v2.IPostQueryRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.bigquery.v2.IQueryResponse, + protos.google.cloud.bigquery.v2.IPostQueryRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'project_id': request.projectId?.toString() ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + project_id: request.projectId?.toString() ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('query request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.bigquery.v2.IQueryResponse, - protos.google.cloud.bigquery.v2.IPostQueryRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.bigquery.v2.IQueryResponse, + protos.google.cloud.bigquery.v2.IPostQueryRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('query response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.query(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.bigquery.v2.IQueryResponse, - protos.google.cloud.bigquery.v2.IPostQueryRequest|undefined, - {}|undefined - ]) => { - this._log.info('query response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .query(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.bigquery.v2.IQueryResponse, + protos.google.cloud.bigquery.v2.IPostQueryRequest | undefined, + {} | undefined, + ]) => { + this._log.info('query response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } - /** - * Lists all jobs that you started in the specified project. Job information - * is available for a six month period after creation. The job list is sorted - * in reverse chronological order, by job creation time. Requires the Can View - * project role, or the Is Owner project role if you set the allUsers - * property. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.projectId - * Project ID of the jobs to list. - * @param {boolean} request.allUsers - * Whether to display jobs owned by all users in the project. Default False. - * @param {google.protobuf.Int32Value| number } request.maxResults - * The maximum number of results to return in a single response page. - * Leverage the page tokens to iterate through the entire collection. - * @param {number} request.minCreationTime - * Min value for job creation time, in milliseconds since the POSIX epoch. - * If set, only jobs created after or at this timestamp are returned. - * @param {google.protobuf.UInt64Value} request.maxCreationTime - * Max value for job creation time, in milliseconds since the POSIX epoch. - * If set, only jobs created before or at this timestamp are returned. - * @param {string} request.pageToken - * Page token, returned by a previous call, to request the next page of - * results. - * @param {google.cloud.bigquery.v2.ListJobsRequest.Projection} request.projection - * Restrict information returned to a set of selected fields - * @param {number[]} request.stateFilter - * Filter for job state - * @param {string} request.parentJobId - * If set, show only child jobs of the specified parent. Otherwise, show all - * top-level jobs. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.cloud.bigquery.v2.ListFormatJob|ListFormatJob}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `listJobsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Lists all jobs that you started in the specified project. Job information + * is available for a six month period after creation. The job list is sorted + * in reverse chronological order, by job creation time. Requires the Can View + * project role, or the Is Owner project role if you set the allUsers + * property. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.projectId + * Project ID of the jobs to list. + * @param {boolean} request.allUsers + * Whether to display jobs owned by all users in the project. Default False. + * @param {google.protobuf.Int32Value| number } request.maxResults + * The maximum number of results to return in a single response page. + * Leverage the page tokens to iterate through the entire collection. + * @param {number} request.minCreationTime + * Min value for job creation time, in milliseconds since the POSIX epoch. + * If set, only jobs created after or at this timestamp are returned. + * @param {google.protobuf.UInt64Value} request.maxCreationTime + * Max value for job creation time, in milliseconds since the POSIX epoch. + * If set, only jobs created before or at this timestamp are returned. + * @param {string} request.pageToken + * Page token, returned by a previous call, to request the next page of + * results. + * @param {google.cloud.bigquery.v2.ListJobsRequest.Projection} request.projection + * Restrict information returned to a set of selected fields + * @param {number[]} request.stateFilter + * Filter for job state + * @param {string} request.parentJobId + * If set, show only child jobs of the specified parent. Otherwise, show all + * top-level jobs. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.cloud.bigquery.v2.ListFormatJob|ListFormatJob}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listJobsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listJobs( - request?: protos.google.cloud.bigquery.v2.IListJobsRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.bigquery.v2.IListFormatJob[], - protos.google.cloud.bigquery.v2.IListJobsRequest|null, - protos.google.cloud.bigquery.v2.IJobList - ]>; + request?: protos.google.cloud.bigquery.v2.IListJobsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.bigquery.v2.IListFormatJob[], + protos.google.cloud.bigquery.v2.IListJobsRequest | null, + protos.google.cloud.bigquery.v2.IJobList, + ] + >; listJobs( - request: protos.google.cloud.bigquery.v2.IListJobsRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.cloud.bigquery.v2.IListJobsRequest, - protos.google.cloud.bigquery.v2.IJobList|null|undefined, - protos.google.cloud.bigquery.v2.IListFormatJob>): void; + request: protos.google.cloud.bigquery.v2.IListJobsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.cloud.bigquery.v2.IListJobsRequest, + protos.google.cloud.bigquery.v2.IJobList | null | undefined, + protos.google.cloud.bigquery.v2.IListFormatJob + >, + ): void; listJobs( - request: protos.google.cloud.bigquery.v2.IListJobsRequest, - callback: PaginationCallback< - protos.google.cloud.bigquery.v2.IListJobsRequest, - protos.google.cloud.bigquery.v2.IJobList|null|undefined, - protos.google.cloud.bigquery.v2.IListFormatJob>): void; + request: protos.google.cloud.bigquery.v2.IListJobsRequest, + callback: PaginationCallback< + protos.google.cloud.bigquery.v2.IListJobsRequest, + protos.google.cloud.bigquery.v2.IJobList | null | undefined, + protos.google.cloud.bigquery.v2.IListFormatJob + >, + ): void; listJobs( - request?: protos.google.cloud.bigquery.v2.IListJobsRequest, - optionsOrCallback?: CallOptions|PaginationCallback< - protos.google.cloud.bigquery.v2.IListJobsRequest, - protos.google.cloud.bigquery.v2.IJobList|null|undefined, - protos.google.cloud.bigquery.v2.IListFormatJob>, - callback?: PaginationCallback< + request?: protos.google.cloud.bigquery.v2.IListJobsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.cloud.bigquery.v2.IListJobsRequest, - protos.google.cloud.bigquery.v2.IJobList|null|undefined, - protos.google.cloud.bigquery.v2.IListFormatJob>): - Promise<[ - protos.google.cloud.bigquery.v2.IListFormatJob[], - protos.google.cloud.bigquery.v2.IListJobsRequest|null, - protos.google.cloud.bigquery.v2.IJobList - ]>|void { + protos.google.cloud.bigquery.v2.IJobList | null | undefined, + protos.google.cloud.bigquery.v2.IListFormatJob + >, + callback?: PaginationCallback< + protos.google.cloud.bigquery.v2.IListJobsRequest, + protos.google.cloud.bigquery.v2.IJobList | null | undefined, + protos.google.cloud.bigquery.v2.IListFormatJob + >, + ): Promise< + [ + protos.google.cloud.bigquery.v2.IListFormatJob[], + protos.google.cloud.bigquery.v2.IListJobsRequest | null, + protos.google.cloud.bigquery.v2.IJobList, + ] + > | void { request = request || {}; // Converts number to Unit32 or Int32 value for non-compliant APIs. - if(request.maxResults && typeof request.maxResults === "number"){ - const maxResultsObject = {"value": request.maxResults} - request.maxResults = maxResultsObject + if (request.maxResults && typeof request.maxResults === 'number') { + const maxResultsObject = { value: request.maxResults }; + request.maxResults = maxResultsObject; } let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'project_id': request.projectId?.toString() ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + project_id: request.projectId?.toString() ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.cloud.bigquery.v2.IListJobsRequest, - protos.google.cloud.bigquery.v2.IJobList|null|undefined, - protos.google.cloud.bigquery.v2.IListFormatJob>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.cloud.bigquery.v2.IListJobsRequest, + protos.google.cloud.bigquery.v2.IJobList | null | undefined, + protos.google.cloud.bigquery.v2.IListFormatJob + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listJobs values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -1107,140 +1367,144 @@ export class JobServiceClient { this._log.info('listJobs request %j', request); return this.innerApiCalls .listJobs(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.cloud.bigquery.v2.IListFormatJob[], - protos.google.cloud.bigquery.v2.IListJobsRequest|null, - protos.google.cloud.bigquery.v2.IJobList - ]) => { - this._log.info('listJobs values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.cloud.bigquery.v2.IListFormatJob[], + protos.google.cloud.bigquery.v2.IListJobsRequest | null, + protos.google.cloud.bigquery.v2.IJobList, + ]) => { + this._log.info('listJobs values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listJobs`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.projectId - * Project ID of the jobs to list. - * @param {boolean} request.allUsers - * Whether to display jobs owned by all users in the project. Default False. - * @param {google.protobuf.Int32Value} request.maxResults - * The maximum number of results to return in a single response page. - * Leverage the page tokens to iterate through the entire collection. - * @param {number} request.minCreationTime - * Min value for job creation time, in milliseconds since the POSIX epoch. - * If set, only jobs created after or at this timestamp are returned. - * @param {google.protobuf.UInt64Value} request.maxCreationTime - * Max value for job creation time, in milliseconds since the POSIX epoch. - * If set, only jobs created before or at this timestamp are returned. - * @param {string} request.pageToken - * Page token, returned by a previous call, to request the next page of - * results. - * @param {google.cloud.bigquery.v2.ListJobsRequest.Projection} request.projection - * Restrict information returned to a set of selected fields - * @param {number[]} request.stateFilter - * Filter for job state - * @param {string} request.parentJobId - * If set, show only child jobs of the specified parent. Otherwise, show all - * top-level jobs. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.cloud.bigquery.v2.ListFormatJob|ListFormatJob} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `listJobsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `listJobs`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.projectId + * Project ID of the jobs to list. + * @param {boolean} request.allUsers + * Whether to display jobs owned by all users in the project. Default False. + * @param {google.protobuf.Int32Value} request.maxResults + * The maximum number of results to return in a single response page. + * Leverage the page tokens to iterate through the entire collection. + * @param {number} request.minCreationTime + * Min value for job creation time, in milliseconds since the POSIX epoch. + * If set, only jobs created after or at this timestamp are returned. + * @param {google.protobuf.UInt64Value} request.maxCreationTime + * Max value for job creation time, in milliseconds since the POSIX epoch. + * If set, only jobs created before or at this timestamp are returned. + * @param {string} request.pageToken + * Page token, returned by a previous call, to request the next page of + * results. + * @param {google.cloud.bigquery.v2.ListJobsRequest.Projection} request.projection + * Restrict information returned to a set of selected fields + * @param {number[]} request.stateFilter + * Filter for job state + * @param {string} request.parentJobId + * If set, show only child jobs of the specified parent. Otherwise, show all + * top-level jobs. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.cloud.bigquery.v2.ListFormatJob|ListFormatJob} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listJobsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listJobsStream( - request?: protos.google.cloud.bigquery.v2.IListJobsRequest, - options?: CallOptions): - Transform{ + request?: protos.google.cloud.bigquery.v2.IListJobsRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'project_id': request.projectId?.toString() ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + project_id: request.projectId?.toString() ?? '', + }); const defaultCallSettings = this._defaults['listJobs']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listJobs stream %j', request); return this.descriptors.page.listJobs.createStream( this.innerApiCalls.listJobs as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listJobs`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.projectId - * Project ID of the jobs to list. - * @param {boolean} request.allUsers - * Whether to display jobs owned by all users in the project. Default False. - * @param {google.protobuf.Int32Value} request.maxResults - * The maximum number of results to return in a single response page. - * Leverage the page tokens to iterate through the entire collection. - * @param {number} request.minCreationTime - * Min value for job creation time, in milliseconds since the POSIX epoch. - * If set, only jobs created after or at this timestamp are returned. - * @param {google.protobuf.UInt64Value} request.maxCreationTime - * Max value for job creation time, in milliseconds since the POSIX epoch. - * If set, only jobs created before or at this timestamp are returned. - * @param {string} request.pageToken - * Page token, returned by a previous call, to request the next page of - * results. - * @param {google.cloud.bigquery.v2.ListJobsRequest.Projection} request.projection - * Restrict information returned to a set of selected fields - * @param {number[]} request.stateFilter - * Filter for job state - * @param {string} request.parentJobId - * If set, show only child jobs of the specified parent. Otherwise, show all - * top-level jobs. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.cloud.bigquery.v2.ListFormatJob|ListFormatJob}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v2/job_service.list_jobs.js - * region_tag:bigquery_v2_generated_JobService_ListJobs_async - */ + /** + * Equivalent to `listJobs`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.projectId + * Project ID of the jobs to list. + * @param {boolean} request.allUsers + * Whether to display jobs owned by all users in the project. Default False. + * @param {google.protobuf.Int32Value} request.maxResults + * The maximum number of results to return in a single response page. + * Leverage the page tokens to iterate through the entire collection. + * @param {number} request.minCreationTime + * Min value for job creation time, in milliseconds since the POSIX epoch. + * If set, only jobs created after or at this timestamp are returned. + * @param {google.protobuf.UInt64Value} request.maxCreationTime + * Max value for job creation time, in milliseconds since the POSIX epoch. + * If set, only jobs created before or at this timestamp are returned. + * @param {string} request.pageToken + * Page token, returned by a previous call, to request the next page of + * results. + * @param {google.cloud.bigquery.v2.ListJobsRequest.Projection} request.projection + * Restrict information returned to a set of selected fields + * @param {number[]} request.stateFilter + * Filter for job state + * @param {string} request.parentJobId + * If set, show only child jobs of the specified parent. Otherwise, show all + * top-level jobs. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.cloud.bigquery.v2.ListFormatJob|ListFormatJob}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v2/job_service.list_jobs.js + * region_tag:bigquery_v2_generated_JobService_ListJobs_async + */ listJobsAsync( - request?: protos.google.cloud.bigquery.v2.IListJobsRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.cloud.bigquery.v2.IListJobsRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'project_id': request.projectId?.toString() ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + project_id: request.projectId?.toString() ?? '', + }); const defaultCallSettings = this._defaults['listJobs']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listJobs iterate %j', request); return this.descriptors.page.listJobs.asyncIterate( this.innerApiCalls['listJobs'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } @@ -1252,7 +1516,7 @@ export class JobServiceClient { */ close(): Promise { if (this.jobServiceStub && !this._terminated) { - return this.jobServiceStub.then(stub => { + return this.jobServiceStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -1260,4 +1524,4 @@ export class JobServiceClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/core/generator/gapic-generator-typescript/baselines/bigquery-v2/src/v2/model_service_client.ts.baseline b/core/generator/gapic-generator-typescript/baselines/bigquery-v2/src/v2/model_service_client.ts.baseline index a08285153dd7..ecbf81abba5a 100644 --- a/core/generator/gapic-generator-typescript/baselines/bigquery-v2/src/v2/model_service_client.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/bigquery-v2/src/v2/model_service_client.ts.baseline @@ -18,11 +18,18 @@ /* global window */ import type * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions, PaginationCallback, GaxCall} from 'google-gax'; -import {Transform} from 'stream'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + PaginationCallback, + GaxCall, +} from 'google-gax'; +import { Transform } from 'stream'; import * as protos from '../../protos/protos'; import jsonProtos = require('../../protos/protos.json'); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; /** * Client JSON configuration object, loaded from @@ -47,7 +54,7 @@ export class ModelServiceClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('bigquery'); @@ -60,8 +67,8 @@ export class ModelServiceClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - modelServiceStub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + modelServiceStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of ModelServiceClient. @@ -102,21 +109,42 @@ export class ModelServiceClient { * const client = new ModelServiceClient({fallback: true}, gax); * ``` */ - constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { // Ensure that options include all the required fields. const staticMembers = this.constructor as typeof ModelServiceClient; - if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { - throw new Error('Please set either universe_domain or universeDomain, but not both.'); + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); } - const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; - this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; this._servicePath = 'bigquery.' + this._universeDomain; - const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; - const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. if (servicePath !== this._servicePath && !('scopes' in opts)) { @@ -138,7 +166,7 @@ export class ModelServiceClient { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; @@ -152,10 +180,7 @@ export class ModelServiceClient { } // Determine the client header string. - const clientHeader = [ - `gax/${this._gaxModule.version}`, - `gapic/${version}`, - ]; + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/${process.versions.node}`); } else { @@ -176,14 +201,20 @@ export class ModelServiceClient { // (e.g. 50 results at a time, with tokens to get subsequent // pages). Denote the keys used for pagination and results. this.descriptors.page = { - listModels: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'models') + listModels: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'models', + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.cloud.bigquery.v2.ModelService', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.cloud.bigquery.v2.ModelService', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + { 'x-goog-api-client': clientHeader.join(' ') }, + ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -214,37 +245,45 @@ export class ModelServiceClient { // Put together the "service stub" for // google.cloud.bigquery.v2.ModelService. this.modelServiceStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.cloud.bigquery.v2.ModelService') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.cloud.bigquery.v2.ModelService', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.cloud.bigquery.v2.ModelService, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts, + this._providedCustomServicePath, + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const modelServiceStubMethods = - ['getModel', 'listModels', 'patchModel', 'deleteModel']; + const modelServiceStubMethods = [ + 'getModel', + 'listModels', + 'patchModel', + 'deleteModel', + ]; for (const methodName of modelServiceStubMethods) { const callPromise = this.modelServiceStub.then( - stub => (...args: Array<{}>) => { - if (this._terminated) { - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error|null|undefined) => () => { + (stub) => + (...args: Array<{}>) => { + if (this._terminated) { + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { throw err; - }); + }, + ); - const descriptor = - this.descriptors.page[methodName] || - undefined; + const descriptor = this.descriptors.page[methodName] || undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -259,8 +298,14 @@ export class ModelServiceClient { * @returns {string} The DNS address for this service. */ static get servicePath() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'bigquery.googleapis.com'; } @@ -271,8 +316,14 @@ export class ModelServiceClient { * @returns {string} The DNS address for this service. */ static get apiEndpoint() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'bigquery.googleapis.com'; } @@ -306,7 +357,7 @@ export class ModelServiceClient { return [ 'https://www.googleapis.com/auth/bigquery', 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloud-platform.read-only' + 'https://www.googleapis.com/auth/cloud-platform.read-only', ]; } @@ -316,8 +367,9 @@ export class ModelServiceClient { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId(callback?: Callback): - Promise|void { + getProjectId( + callback?: Callback, + ): Promise | void { if (callback) { this.auth.getProjectId(callback); return; @@ -328,404 +380,517 @@ export class ModelServiceClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Gets the specified model resource by model ID. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.projectId - * Required. Project ID of the requested model. - * @param {string} request.datasetId - * Required. Dataset ID of the requested model. - * @param {string} request.modelId - * Required. Model ID of the requested model. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.bigquery.v2.Model|Model}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/model_service.get_model.js - * region_tag:bigquery_v2_generated_ModelService_GetModel_async - */ + /** + * Gets the specified model resource by model ID. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.projectId + * Required. Project ID of the requested model. + * @param {string} request.datasetId + * Required. Dataset ID of the requested model. + * @param {string} request.modelId + * Required. Model ID of the requested model. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.bigquery.v2.Model|Model}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/model_service.get_model.js + * region_tag:bigquery_v2_generated_ModelService_GetModel_async + */ getModel( - request?: protos.google.cloud.bigquery.v2.IGetModelRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.bigquery.v2.IModel, - protos.google.cloud.bigquery.v2.IGetModelRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.bigquery.v2.IGetModelRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.bigquery.v2.IModel, + protos.google.cloud.bigquery.v2.IGetModelRequest | undefined, + {} | undefined, + ] + >; getModel( - request: protos.google.cloud.bigquery.v2.IGetModelRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.bigquery.v2.IModel, - protos.google.cloud.bigquery.v2.IGetModelRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.bigquery.v2.IGetModelRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.bigquery.v2.IModel, + protos.google.cloud.bigquery.v2.IGetModelRequest | null | undefined, + {} | null | undefined + >, + ): void; getModel( - request: protos.google.cloud.bigquery.v2.IGetModelRequest, - callback: Callback< - protos.google.cloud.bigquery.v2.IModel, - protos.google.cloud.bigquery.v2.IGetModelRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.bigquery.v2.IGetModelRequest, + callback: Callback< + protos.google.cloud.bigquery.v2.IModel, + protos.google.cloud.bigquery.v2.IGetModelRequest | null | undefined, + {} | null | undefined + >, + ): void; getModel( - request?: protos.google.cloud.bigquery.v2.IGetModelRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.cloud.bigquery.v2.IGetModelRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.bigquery.v2.IModel, - protos.google.cloud.bigquery.v2.IGetModelRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.cloud.bigquery.v2.IModel, - protos.google.cloud.bigquery.v2.IGetModelRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.bigquery.v2.IModel, - protos.google.cloud.bigquery.v2.IGetModelRequest|undefined, {}|undefined - ]>|void { + protos.google.cloud.bigquery.v2.IGetModelRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.bigquery.v2.IModel, + protos.google.cloud.bigquery.v2.IGetModelRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.bigquery.v2.IModel, + protos.google.cloud.bigquery.v2.IGetModelRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'project_id': request.projectId?.toString() ?? '', - 'dataset_id': request.datasetId?.toString() ?? '', - 'model_id': request.modelId?.toString() ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + project_id: request.projectId?.toString() ?? '', + dataset_id: request.datasetId?.toString() ?? '', + model_id: request.modelId?.toString() ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getModel request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.bigquery.v2.IModel, - protos.google.cloud.bigquery.v2.IGetModelRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.bigquery.v2.IModel, + protos.google.cloud.bigquery.v2.IGetModelRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getModel response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getModel(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.bigquery.v2.IModel, - protos.google.cloud.bigquery.v2.IGetModelRequest|undefined, - {}|undefined - ]) => { - this._log.info('getModel response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getModel(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.bigquery.v2.IModel, + protos.google.cloud.bigquery.v2.IGetModelRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getModel response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Patch specific fields in the specified model. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.projectId - * Required. Project ID of the model to patch. - * @param {string} request.datasetId - * Required. Dataset ID of the model to patch. - * @param {string} request.modelId - * Required. Model ID of the model to patch. - * @param {google.cloud.bigquery.v2.Model} request.model - * Required. Patched model. - * Follows RFC5789 patch semantics. Missing fields are not updated. - * To clear a field, explicitly set to default value. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.bigquery.v2.Model|Model}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/model_service.patch_model.js - * region_tag:bigquery_v2_generated_ModelService_PatchModel_async - */ + /** + * Patch specific fields in the specified model. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.projectId + * Required. Project ID of the model to patch. + * @param {string} request.datasetId + * Required. Dataset ID of the model to patch. + * @param {string} request.modelId + * Required. Model ID of the model to patch. + * @param {google.cloud.bigquery.v2.Model} request.model + * Required. Patched model. + * Follows RFC5789 patch semantics. Missing fields are not updated. + * To clear a field, explicitly set to default value. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.bigquery.v2.Model|Model}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/model_service.patch_model.js + * region_tag:bigquery_v2_generated_ModelService_PatchModel_async + */ patchModel( - request?: protos.google.cloud.bigquery.v2.IPatchModelRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.bigquery.v2.IModel, - protos.google.cloud.bigquery.v2.IPatchModelRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.bigquery.v2.IPatchModelRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.bigquery.v2.IModel, + protos.google.cloud.bigquery.v2.IPatchModelRequest | undefined, + {} | undefined, + ] + >; patchModel( - request: protos.google.cloud.bigquery.v2.IPatchModelRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.bigquery.v2.IModel, - protos.google.cloud.bigquery.v2.IPatchModelRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.bigquery.v2.IPatchModelRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.bigquery.v2.IModel, + protos.google.cloud.bigquery.v2.IPatchModelRequest | null | undefined, + {} | null | undefined + >, + ): void; patchModel( - request: protos.google.cloud.bigquery.v2.IPatchModelRequest, - callback: Callback< - protos.google.cloud.bigquery.v2.IModel, - protos.google.cloud.bigquery.v2.IPatchModelRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.bigquery.v2.IPatchModelRequest, + callback: Callback< + protos.google.cloud.bigquery.v2.IModel, + protos.google.cloud.bigquery.v2.IPatchModelRequest | null | undefined, + {} | null | undefined + >, + ): void; patchModel( - request?: protos.google.cloud.bigquery.v2.IPatchModelRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.bigquery.v2.IModel, - protos.google.cloud.bigquery.v2.IPatchModelRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.bigquery.v2.IPatchModelRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.bigquery.v2.IModel, - protos.google.cloud.bigquery.v2.IPatchModelRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.bigquery.v2.IModel, - protos.google.cloud.bigquery.v2.IPatchModelRequest|undefined, {}|undefined - ]>|void { + protos.google.cloud.bigquery.v2.IPatchModelRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.bigquery.v2.IModel, + protos.google.cloud.bigquery.v2.IPatchModelRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.bigquery.v2.IModel, + protos.google.cloud.bigquery.v2.IPatchModelRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'project_id': request.projectId?.toString() ?? '', - 'dataset_id': request.datasetId?.toString() ?? '', - 'model_id': request.modelId?.toString() ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + project_id: request.projectId?.toString() ?? '', + dataset_id: request.datasetId?.toString() ?? '', + model_id: request.modelId?.toString() ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('patchModel request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.bigquery.v2.IModel, - protos.google.cloud.bigquery.v2.IPatchModelRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.bigquery.v2.IModel, + protos.google.cloud.bigquery.v2.IPatchModelRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('patchModel response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.patchModel(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.bigquery.v2.IModel, - protos.google.cloud.bigquery.v2.IPatchModelRequest|undefined, - {}|undefined - ]) => { - this._log.info('patchModel response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .patchModel(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.bigquery.v2.IModel, + protos.google.cloud.bigquery.v2.IPatchModelRequest | undefined, + {} | undefined, + ]) => { + this._log.info('patchModel response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Deletes the model specified by modelId from the dataset. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.projectId - * Required. Project ID of the model to delete. - * @param {string} request.datasetId - * Required. Dataset ID of the model to delete. - * @param {string} request.modelId - * Required. Model ID of the model to delete. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/model_service.delete_model.js - * region_tag:bigquery_v2_generated_ModelService_DeleteModel_async - */ + /** + * Deletes the model specified by modelId from the dataset. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.projectId + * Required. Project ID of the model to delete. + * @param {string} request.datasetId + * Required. Dataset ID of the model to delete. + * @param {string} request.modelId + * Required. Model ID of the model to delete. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/model_service.delete_model.js + * region_tag:bigquery_v2_generated_ModelService_DeleteModel_async + */ deleteModel( - request?: protos.google.cloud.bigquery.v2.IDeleteModelRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.cloud.bigquery.v2.IDeleteModelRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.bigquery.v2.IDeleteModelRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.cloud.bigquery.v2.IDeleteModelRequest | undefined, + {} | undefined, + ] + >; deleteModel( - request: protos.google.cloud.bigquery.v2.IDeleteModelRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.cloud.bigquery.v2.IDeleteModelRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.bigquery.v2.IDeleteModelRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.cloud.bigquery.v2.IDeleteModelRequest | null | undefined, + {} | null | undefined + >, + ): void; deleteModel( - request: protos.google.cloud.bigquery.v2.IDeleteModelRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.cloud.bigquery.v2.IDeleteModelRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.bigquery.v2.IDeleteModelRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.cloud.bigquery.v2.IDeleteModelRequest | null | undefined, + {} | null | undefined + >, + ): void; deleteModel( - request?: protos.google.cloud.bigquery.v2.IDeleteModelRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.protobuf.IEmpty, - protos.google.cloud.bigquery.v2.IDeleteModelRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.bigquery.v2.IDeleteModelRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.cloud.bigquery.v2.IDeleteModelRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.cloud.bigquery.v2.IDeleteModelRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.bigquery.v2.IDeleteModelRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + protos.google.cloud.bigquery.v2.IDeleteModelRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.cloud.bigquery.v2.IDeleteModelRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'project_id': request.projectId?.toString() ?? '', - 'dataset_id': request.datasetId?.toString() ?? '', - 'model_id': request.modelId?.toString() ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + project_id: request.projectId?.toString() ?? '', + dataset_id: request.datasetId?.toString() ?? '', + model_id: request.modelId?.toString() ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('deleteModel request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.cloud.bigquery.v2.IDeleteModelRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.cloud.bigquery.v2.IDeleteModelRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteModel response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.deleteModel(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.cloud.bigquery.v2.IDeleteModelRequest|undefined, - {}|undefined - ]) => { - this._log.info('deleteModel response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteModel(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.cloud.bigquery.v2.IDeleteModelRequest | undefined, + {} | undefined, + ]) => { + this._log.info('deleteModel response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } - /** - * Lists all models in the specified dataset. Requires the READER dataset - * role. After retrieving the list of models, you can get information about a - * particular model by calling the models.get method. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.projectId - * Required. Project ID of the models to list. - * @param {string} request.datasetId - * Required. Dataset ID of the models to list. - * @param {google.protobuf.UInt32Value| number } request.maxResults - * The maximum number of results to return in a single response page. - * Leverage the page tokens to iterate through the entire collection. - * @param {string} request.pageToken - * Page token, returned by a previous call to request the next page of - * results - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.cloud.bigquery.v2.Model|Model}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `listModelsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Lists all models in the specified dataset. Requires the READER dataset + * role. After retrieving the list of models, you can get information about a + * particular model by calling the models.get method. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.projectId + * Required. Project ID of the models to list. + * @param {string} request.datasetId + * Required. Dataset ID of the models to list. + * @param {google.protobuf.UInt32Value| number } request.maxResults + * The maximum number of results to return in a single response page. + * Leverage the page tokens to iterate through the entire collection. + * @param {string} request.pageToken + * Page token, returned by a previous call to request the next page of + * results + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.cloud.bigquery.v2.Model|Model}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listModelsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listModels( - request?: protos.google.cloud.bigquery.v2.IListModelsRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.bigquery.v2.IModel[], - protos.google.cloud.bigquery.v2.IListModelsRequest|null, - protos.google.cloud.bigquery.v2.IListModelsResponse - ]>; + request?: protos.google.cloud.bigquery.v2.IListModelsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.bigquery.v2.IModel[], + protos.google.cloud.bigquery.v2.IListModelsRequest | null, + protos.google.cloud.bigquery.v2.IListModelsResponse, + ] + >; listModels( - request: protos.google.cloud.bigquery.v2.IListModelsRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.cloud.bigquery.v2.IListModelsRequest, - protos.google.cloud.bigquery.v2.IListModelsResponse|null|undefined, - protos.google.cloud.bigquery.v2.IModel>): void; + request: protos.google.cloud.bigquery.v2.IListModelsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.cloud.bigquery.v2.IListModelsRequest, + protos.google.cloud.bigquery.v2.IListModelsResponse | null | undefined, + protos.google.cloud.bigquery.v2.IModel + >, + ): void; listModels( - request: protos.google.cloud.bigquery.v2.IListModelsRequest, - callback: PaginationCallback< - protos.google.cloud.bigquery.v2.IListModelsRequest, - protos.google.cloud.bigquery.v2.IListModelsResponse|null|undefined, - protos.google.cloud.bigquery.v2.IModel>): void; + request: protos.google.cloud.bigquery.v2.IListModelsRequest, + callback: PaginationCallback< + protos.google.cloud.bigquery.v2.IListModelsRequest, + protos.google.cloud.bigquery.v2.IListModelsResponse | null | undefined, + protos.google.cloud.bigquery.v2.IModel + >, + ): void; listModels( - request?: protos.google.cloud.bigquery.v2.IListModelsRequest, - optionsOrCallback?: CallOptions|PaginationCallback< - protos.google.cloud.bigquery.v2.IListModelsRequest, - protos.google.cloud.bigquery.v2.IListModelsResponse|null|undefined, - protos.google.cloud.bigquery.v2.IModel>, - callback?: PaginationCallback< + request?: protos.google.cloud.bigquery.v2.IListModelsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.cloud.bigquery.v2.IListModelsRequest, - protos.google.cloud.bigquery.v2.IListModelsResponse|null|undefined, - protos.google.cloud.bigquery.v2.IModel>): - Promise<[ - protos.google.cloud.bigquery.v2.IModel[], - protos.google.cloud.bigquery.v2.IListModelsRequest|null, - protos.google.cloud.bigquery.v2.IListModelsResponse - ]>|void { + | protos.google.cloud.bigquery.v2.IListModelsResponse + | null + | undefined, + protos.google.cloud.bigquery.v2.IModel + >, + callback?: PaginationCallback< + protos.google.cloud.bigquery.v2.IListModelsRequest, + protos.google.cloud.bigquery.v2.IListModelsResponse | null | undefined, + protos.google.cloud.bigquery.v2.IModel + >, + ): Promise< + [ + protos.google.cloud.bigquery.v2.IModel[], + protos.google.cloud.bigquery.v2.IListModelsRequest | null, + protos.google.cloud.bigquery.v2.IListModelsResponse, + ] + > | void { request = request || {}; // Converts number to Unit32 or Int32 value for non-compliant APIs. - if(request.maxResults && typeof request.maxResults === "number"){ - const maxResultsObject = {"value": request.maxResults} - request.maxResults = maxResultsObject + if (request.maxResults && typeof request.maxResults === 'number') { + const maxResultsObject = { value: request.maxResults }; + request.maxResults = maxResultsObject; } let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'project_id': request.projectId?.toString() ?? '', - 'dataset_id': request.datasetId?.toString() ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + project_id: request.projectId?.toString() ?? '', + dataset_id: request.datasetId?.toString() ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.cloud.bigquery.v2.IListModelsRequest, - protos.google.cloud.bigquery.v2.IListModelsResponse|null|undefined, - protos.google.cloud.bigquery.v2.IModel>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.cloud.bigquery.v2.IListModelsRequest, + | protos.google.cloud.bigquery.v2.IListModelsResponse + | null + | undefined, + protos.google.cloud.bigquery.v2.IModel + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listModels values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -734,116 +899,120 @@ export class ModelServiceClient { this._log.info('listModels request %j', request); return this.innerApiCalls .listModels(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.cloud.bigquery.v2.IModel[], - protos.google.cloud.bigquery.v2.IListModelsRequest|null, - protos.google.cloud.bigquery.v2.IListModelsResponse - ]) => { - this._log.info('listModels values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.cloud.bigquery.v2.IModel[], + protos.google.cloud.bigquery.v2.IListModelsRequest | null, + protos.google.cloud.bigquery.v2.IListModelsResponse, + ]) => { + this._log.info('listModels values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listModels`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.projectId - * Required. Project ID of the models to list. - * @param {string} request.datasetId - * Required. Dataset ID of the models to list. - * @param {google.protobuf.UInt32Value} request.maxResults - * The maximum number of results to return in a single response page. - * Leverage the page tokens to iterate through the entire collection. - * @param {string} request.pageToken - * Page token, returned by a previous call to request the next page of - * results - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.cloud.bigquery.v2.Model|Model} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `listModelsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `listModels`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.projectId + * Required. Project ID of the models to list. + * @param {string} request.datasetId + * Required. Dataset ID of the models to list. + * @param {google.protobuf.UInt32Value} request.maxResults + * The maximum number of results to return in a single response page. + * Leverage the page tokens to iterate through the entire collection. + * @param {string} request.pageToken + * Page token, returned by a previous call to request the next page of + * results + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.cloud.bigquery.v2.Model|Model} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listModelsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listModelsStream( - request?: protos.google.cloud.bigquery.v2.IListModelsRequest, - options?: CallOptions): - Transform{ + request?: protos.google.cloud.bigquery.v2.IListModelsRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'project_id': request.projectId?.toString() ?? '', - 'dataset_id': request.datasetId?.toString() ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + project_id: request.projectId?.toString() ?? '', + dataset_id: request.datasetId?.toString() ?? '', + }); const defaultCallSettings = this._defaults['listModels']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listModels stream %j', request); return this.descriptors.page.listModels.createStream( this.innerApiCalls.listModels as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listModels`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.projectId - * Required. Project ID of the models to list. - * @param {string} request.datasetId - * Required. Dataset ID of the models to list. - * @param {google.protobuf.UInt32Value} request.maxResults - * The maximum number of results to return in a single response page. - * Leverage the page tokens to iterate through the entire collection. - * @param {string} request.pageToken - * Page token, returned by a previous call to request the next page of - * results - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.cloud.bigquery.v2.Model|Model}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v2/model_service.list_models.js - * region_tag:bigquery_v2_generated_ModelService_ListModels_async - */ + /** + * Equivalent to `listModels`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.projectId + * Required. Project ID of the models to list. + * @param {string} request.datasetId + * Required. Dataset ID of the models to list. + * @param {google.protobuf.UInt32Value} request.maxResults + * The maximum number of results to return in a single response page. + * Leverage the page tokens to iterate through the entire collection. + * @param {string} request.pageToken + * Page token, returned by a previous call to request the next page of + * results + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.cloud.bigquery.v2.Model|Model}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v2/model_service.list_models.js + * region_tag:bigquery_v2_generated_ModelService_ListModels_async + */ listModelsAsync( - request?: protos.google.cloud.bigquery.v2.IListModelsRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.cloud.bigquery.v2.IListModelsRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'project_id': request.projectId?.toString() ?? '', - 'dataset_id': request.datasetId?.toString() ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + project_id: request.projectId?.toString() ?? '', + dataset_id: request.datasetId?.toString() ?? '', + }); const defaultCallSettings = this._defaults['listModels']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listModels iterate %j', request); return this.descriptors.page.listModels.asyncIterate( this.innerApiCalls['listModels'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } @@ -855,7 +1024,7 @@ export class ModelServiceClient { */ close(): Promise { if (this.modelServiceStub && !this._terminated) { - return this.modelServiceStub.then(stub => { + return this.modelServiceStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -863,4 +1032,4 @@ export class ModelServiceClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/core/generator/gapic-generator-typescript/baselines/bigquery-v2/src/v2/project_service_client.ts.baseline b/core/generator/gapic-generator-typescript/baselines/bigquery-v2/src/v2/project_service_client.ts.baseline index ab6e7ff277a5..603bba1ba239 100644 --- a/core/generator/gapic-generator-typescript/baselines/bigquery-v2/src/v2/project_service_client.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/bigquery-v2/src/v2/project_service_client.ts.baseline @@ -18,11 +18,16 @@ /* global window */ import type * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions} from 'google-gax'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, +} from 'google-gax'; import * as protos from '../../protos/protos'; import jsonProtos = require('../../protos/protos.json'); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; /** * Client JSON configuration object, loaded from @@ -47,7 +52,7 @@ export class ProjectServiceClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('bigquery'); @@ -60,8 +65,8 @@ export class ProjectServiceClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - projectServiceStub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + projectServiceStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of ProjectServiceClient. @@ -102,21 +107,42 @@ export class ProjectServiceClient { * const client = new ProjectServiceClient({fallback: true}, gax); * ``` */ - constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { // Ensure that options include all the required fields. const staticMembers = this.constructor as typeof ProjectServiceClient; - if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { - throw new Error('Please set either universe_domain or universeDomain, but not both.'); + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); } - const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; - this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; this._servicePath = 'bigquery.' + this._universeDomain; - const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; - const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. if (servicePath !== this._servicePath && !('scopes' in opts)) { @@ -138,7 +164,7 @@ export class ProjectServiceClient { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; @@ -152,10 +178,7 @@ export class ProjectServiceClient { } // Determine the client header string. - const clientHeader = [ - `gax/${this._gaxModule.version}`, - `gapic/${version}`, - ]; + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/${process.versions.node}`); } else { @@ -174,8 +197,11 @@ export class ProjectServiceClient { // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.cloud.bigquery.v2.ProjectService', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.cloud.bigquery.v2.ProjectService', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + { 'x-goog-api-client': clientHeader.join(' ') }, + ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -206,36 +232,40 @@ export class ProjectServiceClient { // Put together the "service stub" for // google.cloud.bigquery.v2.ProjectService. this.projectServiceStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.cloud.bigquery.v2.ProjectService') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.cloud.bigquery.v2.ProjectService', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.cloud.bigquery.v2.ProjectService, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts, + this._providedCustomServicePath, + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const projectServiceStubMethods = - ['getServiceAccount']; + const projectServiceStubMethods = ['getServiceAccount']; for (const methodName of projectServiceStubMethods) { const callPromise = this.projectServiceStub.then( - stub => (...args: Array<{}>) => { - if (this._terminated) { - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error|null|undefined) => () => { + (stub) => + (...args: Array<{}>) => { + if (this._terminated) { + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { throw err; - }); + }, + ); - const descriptor = - undefined; + const descriptor = undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -250,8 +280,14 @@ export class ProjectServiceClient { * @returns {string} The DNS address for this service. */ static get servicePath() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'bigquery.googleapis.com'; } @@ -262,8 +298,14 @@ export class ProjectServiceClient { * @returns {string} The DNS address for this service. */ static get apiEndpoint() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'bigquery.googleapis.com'; } @@ -297,7 +339,7 @@ export class ProjectServiceClient { return [ 'https://www.googleapis.com/auth/bigquery', 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloud-platform.read-only' + 'https://www.googleapis.com/auth/cloud-platform.read-only', ]; } @@ -307,8 +349,9 @@ export class ProjectServiceClient { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId(callback?: Callback): - Promise|void { + getProjectId( + callback?: Callback, + ): Promise | void { if (callback) { this.auth.getProjectId(callback); return; @@ -319,103 +362,142 @@ export class ProjectServiceClient { // ------------------- // -- Service calls -- // ------------------- -/** - * RPC to get the service account for a project used for interactions with - * Google Cloud KMS - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.projectId - * Required. ID of the project. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.bigquery.v2.GetServiceAccountResponse|GetServiceAccountResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/project_service.get_service_account.js - * region_tag:bigquery_v2_generated_ProjectService_GetServiceAccount_async - */ + /** + * RPC to get the service account for a project used for interactions with + * Google Cloud KMS + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.projectId + * Required. ID of the project. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.bigquery.v2.GetServiceAccountResponse|GetServiceAccountResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/project_service.get_service_account.js + * region_tag:bigquery_v2_generated_ProjectService_GetServiceAccount_async + */ getServiceAccount( - request?: protos.google.cloud.bigquery.v2.IGetServiceAccountRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.bigquery.v2.IGetServiceAccountResponse, - protos.google.cloud.bigquery.v2.IGetServiceAccountRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.bigquery.v2.IGetServiceAccountRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.bigquery.v2.IGetServiceAccountResponse, + protos.google.cloud.bigquery.v2.IGetServiceAccountRequest | undefined, + {} | undefined, + ] + >; getServiceAccount( - request: protos.google.cloud.bigquery.v2.IGetServiceAccountRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.bigquery.v2.IGetServiceAccountResponse, - protos.google.cloud.bigquery.v2.IGetServiceAccountRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.bigquery.v2.IGetServiceAccountRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.bigquery.v2.IGetServiceAccountResponse, + | protos.google.cloud.bigquery.v2.IGetServiceAccountRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getServiceAccount( - request: protos.google.cloud.bigquery.v2.IGetServiceAccountRequest, - callback: Callback< - protos.google.cloud.bigquery.v2.IGetServiceAccountResponse, - protos.google.cloud.bigquery.v2.IGetServiceAccountRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.bigquery.v2.IGetServiceAccountRequest, + callback: Callback< + protos.google.cloud.bigquery.v2.IGetServiceAccountResponse, + | protos.google.cloud.bigquery.v2.IGetServiceAccountRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getServiceAccount( - request?: protos.google.cloud.bigquery.v2.IGetServiceAccountRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.cloud.bigquery.v2.IGetServiceAccountRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.bigquery.v2.IGetServiceAccountResponse, - protos.google.cloud.bigquery.v2.IGetServiceAccountRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.cloud.bigquery.v2.IGetServiceAccountResponse, - protos.google.cloud.bigquery.v2.IGetServiceAccountRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.bigquery.v2.IGetServiceAccountResponse, - protos.google.cloud.bigquery.v2.IGetServiceAccountRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.bigquery.v2.IGetServiceAccountRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.bigquery.v2.IGetServiceAccountResponse, + | protos.google.cloud.bigquery.v2.IGetServiceAccountRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.bigquery.v2.IGetServiceAccountResponse, + protos.google.cloud.bigquery.v2.IGetServiceAccountRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'project_id': request.projectId?.toString() ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + project_id: request.projectId?.toString() ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getServiceAccount request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.bigquery.v2.IGetServiceAccountResponse, - protos.google.cloud.bigquery.v2.IGetServiceAccountRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.bigquery.v2.IGetServiceAccountResponse, + | protos.google.cloud.bigquery.v2.IGetServiceAccountRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getServiceAccount response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getServiceAccount(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.bigquery.v2.IGetServiceAccountResponse, - protos.google.cloud.bigquery.v2.IGetServiceAccountRequest|undefined, - {}|undefined - ]) => { - this._log.info('getServiceAccount response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getServiceAccount(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.bigquery.v2.IGetServiceAccountResponse, + protos.google.cloud.bigquery.v2.IGetServiceAccountRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getServiceAccount response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } - /** * Terminate the gRPC channel and close the client. * @@ -424,7 +506,7 @@ export class ProjectServiceClient { */ close(): Promise { if (this.projectServiceStub && !this._terminated) { - return this.projectServiceStub.then(stub => { + return this.projectServiceStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -432,4 +514,4 @@ export class ProjectServiceClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/core/generator/gapic-generator-typescript/baselines/bigquery-v2/src/v2/routine_service_client.ts.baseline b/core/generator/gapic-generator-typescript/baselines/bigquery-v2/src/v2/routine_service_client.ts.baseline index db52c98a8164..cd2acdf489d1 100644 --- a/core/generator/gapic-generator-typescript/baselines/bigquery-v2/src/v2/routine_service_client.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/bigquery-v2/src/v2/routine_service_client.ts.baseline @@ -18,11 +18,18 @@ /* global window */ import type * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions, PaginationCallback, GaxCall} from 'google-gax'; -import {Transform} from 'stream'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + PaginationCallback, + GaxCall, +} from 'google-gax'; +import { Transform } from 'stream'; import * as protos from '../../protos/protos'; import jsonProtos = require('../../protos/protos.json'); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; /** * Client JSON configuration object, loaded from @@ -47,7 +54,7 @@ export class RoutineServiceClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('bigquery'); @@ -60,8 +67,8 @@ export class RoutineServiceClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - routineServiceStub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + routineServiceStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of RoutineServiceClient. @@ -102,21 +109,42 @@ export class RoutineServiceClient { * const client = new RoutineServiceClient({fallback: true}, gax); * ``` */ - constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { // Ensure that options include all the required fields. const staticMembers = this.constructor as typeof RoutineServiceClient; - if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { - throw new Error('Please set either universe_domain or universeDomain, but not both.'); + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); } - const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; - this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; this._servicePath = 'bigquery.' + this._universeDomain; - const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; - const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. if (servicePath !== this._servicePath && !('scopes' in opts)) { @@ -138,7 +166,7 @@ export class RoutineServiceClient { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; @@ -152,10 +180,7 @@ export class RoutineServiceClient { } // Determine the client header string. - const clientHeader = [ - `gax/${this._gaxModule.version}`, - `gapic/${version}`, - ]; + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/${process.versions.node}`); } else { @@ -176,14 +201,20 @@ export class RoutineServiceClient { // (e.g. 50 results at a time, with tokens to get subsequent // pages). Denote the keys used for pagination and results. this.descriptors.page = { - listRoutines: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'routines') + listRoutines: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'routines', + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.cloud.bigquery.v2.RoutineService', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.cloud.bigquery.v2.RoutineService', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + { 'x-goog-api-client': clientHeader.join(' ') }, + ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -214,37 +245,47 @@ export class RoutineServiceClient { // Put together the "service stub" for // google.cloud.bigquery.v2.RoutineService. this.routineServiceStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.cloud.bigquery.v2.RoutineService') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.cloud.bigquery.v2.RoutineService', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.cloud.bigquery.v2.RoutineService, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts, + this._providedCustomServicePath, + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const routineServiceStubMethods = - ['getRoutine', 'insertRoutine', 'updateRoutine', 'patchRoutine', 'deleteRoutine', 'listRoutines']; + const routineServiceStubMethods = [ + 'getRoutine', + 'insertRoutine', + 'updateRoutine', + 'patchRoutine', + 'deleteRoutine', + 'listRoutines', + ]; for (const methodName of routineServiceStubMethods) { const callPromise = this.routineServiceStub.then( - stub => (...args: Array<{}>) => { - if (this._terminated) { - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error|null|undefined) => () => { + (stub) => + (...args: Array<{}>) => { + if (this._terminated) { + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { throw err; - }); + }, + ); - const descriptor = - this.descriptors.page[methodName] || - undefined; + const descriptor = this.descriptors.page[methodName] || undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -259,8 +300,14 @@ export class RoutineServiceClient { * @returns {string} The DNS address for this service. */ static get servicePath() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'bigquery.googleapis.com'; } @@ -271,8 +318,14 @@ export class RoutineServiceClient { * @returns {string} The DNS address for this service. */ static get apiEndpoint() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'bigquery.googleapis.com'; } @@ -306,7 +359,7 @@ export class RoutineServiceClient { return [ 'https://www.googleapis.com/auth/bigquery', 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloud-platform.read-only' + 'https://www.googleapis.com/auth/cloud-platform.read-only', ]; } @@ -316,8 +369,9 @@ export class RoutineServiceClient { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId(callback?: Callback): - Promise|void { + getProjectId( + callback?: Callback, + ): Promise | void { if (callback) { this.auth.getProjectId(callback); return; @@ -328,606 +382,792 @@ export class RoutineServiceClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Gets the specified routine resource by routine ID. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.projectId - * Required. Project ID of the requested routine - * @param {string} request.datasetId - * Required. Dataset ID of the requested routine - * @param {string} request.routineId - * Required. Routine ID of the requested routine - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.bigquery.v2.Routine|Routine}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/routine_service.get_routine.js - * region_tag:bigquery_v2_generated_RoutineService_GetRoutine_async - */ + /** + * Gets the specified routine resource by routine ID. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.projectId + * Required. Project ID of the requested routine + * @param {string} request.datasetId + * Required. Dataset ID of the requested routine + * @param {string} request.routineId + * Required. Routine ID of the requested routine + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.bigquery.v2.Routine|Routine}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/routine_service.get_routine.js + * region_tag:bigquery_v2_generated_RoutineService_GetRoutine_async + */ getRoutine( - request?: protos.google.cloud.bigquery.v2.IGetRoutineRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.bigquery.v2.IRoutine, - protos.google.cloud.bigquery.v2.IGetRoutineRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.bigquery.v2.IGetRoutineRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.bigquery.v2.IRoutine, + protos.google.cloud.bigquery.v2.IGetRoutineRequest | undefined, + {} | undefined, + ] + >; getRoutine( - request: protos.google.cloud.bigquery.v2.IGetRoutineRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.bigquery.v2.IRoutine, - protos.google.cloud.bigquery.v2.IGetRoutineRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.bigquery.v2.IGetRoutineRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.bigquery.v2.IRoutine, + protos.google.cloud.bigquery.v2.IGetRoutineRequest | null | undefined, + {} | null | undefined + >, + ): void; getRoutine( - request: protos.google.cloud.bigquery.v2.IGetRoutineRequest, - callback: Callback< - protos.google.cloud.bigquery.v2.IRoutine, - protos.google.cloud.bigquery.v2.IGetRoutineRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.bigquery.v2.IGetRoutineRequest, + callback: Callback< + protos.google.cloud.bigquery.v2.IRoutine, + protos.google.cloud.bigquery.v2.IGetRoutineRequest | null | undefined, + {} | null | undefined + >, + ): void; getRoutine( - request?: protos.google.cloud.bigquery.v2.IGetRoutineRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.bigquery.v2.IRoutine, - protos.google.cloud.bigquery.v2.IGetRoutineRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.bigquery.v2.IGetRoutineRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.bigquery.v2.IRoutine, - protos.google.cloud.bigquery.v2.IGetRoutineRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.bigquery.v2.IRoutine, - protos.google.cloud.bigquery.v2.IGetRoutineRequest|undefined, {}|undefined - ]>|void { + protos.google.cloud.bigquery.v2.IGetRoutineRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.bigquery.v2.IRoutine, + protos.google.cloud.bigquery.v2.IGetRoutineRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.bigquery.v2.IRoutine, + protos.google.cloud.bigquery.v2.IGetRoutineRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'project_id': request.projectId?.toString() ?? '', - 'dataset_id': request.datasetId?.toString() ?? '', - 'routine_id': request.routineId?.toString() ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + project_id: request.projectId?.toString() ?? '', + dataset_id: request.datasetId?.toString() ?? '', + routine_id: request.routineId?.toString() ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getRoutine request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.bigquery.v2.IRoutine, - protos.google.cloud.bigquery.v2.IGetRoutineRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.bigquery.v2.IRoutine, + protos.google.cloud.bigquery.v2.IGetRoutineRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getRoutine response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getRoutine(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.bigquery.v2.IRoutine, - protos.google.cloud.bigquery.v2.IGetRoutineRequest|undefined, - {}|undefined - ]) => { - this._log.info('getRoutine response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getRoutine(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.bigquery.v2.IRoutine, + protos.google.cloud.bigquery.v2.IGetRoutineRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getRoutine response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Creates a new routine in the dataset. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.projectId - * Required. Project ID of the new routine - * @param {string} request.datasetId - * Required. Dataset ID of the new routine - * @param {google.cloud.bigquery.v2.Routine} request.routine - * Required. A routine resource to insert - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.bigquery.v2.Routine|Routine}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/routine_service.insert_routine.js - * region_tag:bigquery_v2_generated_RoutineService_InsertRoutine_async - */ + /** + * Creates a new routine in the dataset. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.projectId + * Required. Project ID of the new routine + * @param {string} request.datasetId + * Required. Dataset ID of the new routine + * @param {google.cloud.bigquery.v2.Routine} request.routine + * Required. A routine resource to insert + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.bigquery.v2.Routine|Routine}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/routine_service.insert_routine.js + * region_tag:bigquery_v2_generated_RoutineService_InsertRoutine_async + */ insertRoutine( - request?: protos.google.cloud.bigquery.v2.IInsertRoutineRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.bigquery.v2.IRoutine, - protos.google.cloud.bigquery.v2.IInsertRoutineRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.bigquery.v2.IInsertRoutineRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.bigquery.v2.IRoutine, + protos.google.cloud.bigquery.v2.IInsertRoutineRequest | undefined, + {} | undefined, + ] + >; insertRoutine( - request: protos.google.cloud.bigquery.v2.IInsertRoutineRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.bigquery.v2.IRoutine, - protos.google.cloud.bigquery.v2.IInsertRoutineRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.bigquery.v2.IInsertRoutineRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.bigquery.v2.IRoutine, + protos.google.cloud.bigquery.v2.IInsertRoutineRequest | null | undefined, + {} | null | undefined + >, + ): void; insertRoutine( - request: protos.google.cloud.bigquery.v2.IInsertRoutineRequest, - callback: Callback< - protos.google.cloud.bigquery.v2.IRoutine, - protos.google.cloud.bigquery.v2.IInsertRoutineRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.bigquery.v2.IInsertRoutineRequest, + callback: Callback< + protos.google.cloud.bigquery.v2.IRoutine, + protos.google.cloud.bigquery.v2.IInsertRoutineRequest | null | undefined, + {} | null | undefined + >, + ): void; insertRoutine( - request?: protos.google.cloud.bigquery.v2.IInsertRoutineRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.cloud.bigquery.v2.IInsertRoutineRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.bigquery.v2.IRoutine, - protos.google.cloud.bigquery.v2.IInsertRoutineRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.cloud.bigquery.v2.IRoutine, - protos.google.cloud.bigquery.v2.IInsertRoutineRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.bigquery.v2.IRoutine, - protos.google.cloud.bigquery.v2.IInsertRoutineRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.bigquery.v2.IInsertRoutineRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.bigquery.v2.IRoutine, + protos.google.cloud.bigquery.v2.IInsertRoutineRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.bigquery.v2.IRoutine, + protos.google.cloud.bigquery.v2.IInsertRoutineRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'project_id': request.projectId?.toString() ?? '', - 'dataset_id': request.datasetId?.toString() ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + project_id: request.projectId?.toString() ?? '', + dataset_id: request.datasetId?.toString() ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('insertRoutine request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.bigquery.v2.IRoutine, - protos.google.cloud.bigquery.v2.IInsertRoutineRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.bigquery.v2.IRoutine, + | protos.google.cloud.bigquery.v2.IInsertRoutineRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('insertRoutine response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.insertRoutine(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.bigquery.v2.IRoutine, - protos.google.cloud.bigquery.v2.IInsertRoutineRequest|undefined, - {}|undefined - ]) => { - this._log.info('insertRoutine response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .insertRoutine(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.bigquery.v2.IRoutine, + protos.google.cloud.bigquery.v2.IInsertRoutineRequest | undefined, + {} | undefined, + ]) => { + this._log.info('insertRoutine response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Updates information in an existing routine. The update method replaces the - * entire Routine resource. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.projectId - * Required. Project ID of the routine to update - * @param {string} request.datasetId - * Required. Dataset ID of the routine to update - * @param {string} request.routineId - * Required. Routine ID of the routine to update - * @param {google.cloud.bigquery.v2.Routine} request.routine - * Required. A routine resource which will replace the specified routine - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.bigquery.v2.Routine|Routine}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/routine_service.update_routine.js - * region_tag:bigquery_v2_generated_RoutineService_UpdateRoutine_async - */ + /** + * Updates information in an existing routine. The update method replaces the + * entire Routine resource. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.projectId + * Required. Project ID of the routine to update + * @param {string} request.datasetId + * Required. Dataset ID of the routine to update + * @param {string} request.routineId + * Required. Routine ID of the routine to update + * @param {google.cloud.bigquery.v2.Routine} request.routine + * Required. A routine resource which will replace the specified routine + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.bigquery.v2.Routine|Routine}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/routine_service.update_routine.js + * region_tag:bigquery_v2_generated_RoutineService_UpdateRoutine_async + */ updateRoutine( - request?: protos.google.cloud.bigquery.v2.IUpdateRoutineRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.bigquery.v2.IRoutine, - protos.google.cloud.bigquery.v2.IUpdateRoutineRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.bigquery.v2.IUpdateRoutineRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.bigquery.v2.IRoutine, + protos.google.cloud.bigquery.v2.IUpdateRoutineRequest | undefined, + {} | undefined, + ] + >; updateRoutine( - request: protos.google.cloud.bigquery.v2.IUpdateRoutineRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.bigquery.v2.IRoutine, - protos.google.cloud.bigquery.v2.IUpdateRoutineRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.bigquery.v2.IUpdateRoutineRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.bigquery.v2.IRoutine, + protos.google.cloud.bigquery.v2.IUpdateRoutineRequest | null | undefined, + {} | null | undefined + >, + ): void; updateRoutine( - request: protos.google.cloud.bigquery.v2.IUpdateRoutineRequest, - callback: Callback< - protos.google.cloud.bigquery.v2.IRoutine, - protos.google.cloud.bigquery.v2.IUpdateRoutineRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.bigquery.v2.IUpdateRoutineRequest, + callback: Callback< + protos.google.cloud.bigquery.v2.IRoutine, + protos.google.cloud.bigquery.v2.IUpdateRoutineRequest | null | undefined, + {} | null | undefined + >, + ): void; updateRoutine( - request?: protos.google.cloud.bigquery.v2.IUpdateRoutineRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.bigquery.v2.IRoutine, - protos.google.cloud.bigquery.v2.IUpdateRoutineRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.bigquery.v2.IUpdateRoutineRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.bigquery.v2.IRoutine, - protos.google.cloud.bigquery.v2.IUpdateRoutineRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.bigquery.v2.IRoutine, - protos.google.cloud.bigquery.v2.IUpdateRoutineRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.bigquery.v2.IUpdateRoutineRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.bigquery.v2.IRoutine, + protos.google.cloud.bigquery.v2.IUpdateRoutineRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.bigquery.v2.IRoutine, + protos.google.cloud.bigquery.v2.IUpdateRoutineRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'project_id': request.projectId?.toString() ?? '', - 'dataset_id': request.datasetId?.toString() ?? '', - 'routine_id': request.routineId?.toString() ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + project_id: request.projectId?.toString() ?? '', + dataset_id: request.datasetId?.toString() ?? '', + routine_id: request.routineId?.toString() ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateRoutine request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.bigquery.v2.IRoutine, - protos.google.cloud.bigquery.v2.IUpdateRoutineRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.bigquery.v2.IRoutine, + | protos.google.cloud.bigquery.v2.IUpdateRoutineRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateRoutine response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.updateRoutine(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.bigquery.v2.IRoutine, - protos.google.cloud.bigquery.v2.IUpdateRoutineRequest|undefined, - {}|undefined - ]) => { - this._log.info('updateRoutine response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateRoutine(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.bigquery.v2.IRoutine, + protos.google.cloud.bigquery.v2.IUpdateRoutineRequest | undefined, + {} | undefined, + ]) => { + this._log.info('updateRoutine response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Patches information in an existing routine. The patch method does a partial - * update to an existing Routine resource. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.projectId - * Required. Project ID of the routine to update - * @param {string} request.datasetId - * Required. Dataset ID of the routine to update - * @param {string} request.routineId - * Required. Routine ID of the routine to update - * @param {google.cloud.bigquery.v2.Routine} request.routine - * Required. A routine resource which will be used to partially - * update the specified routine - * @param {google.protobuf.FieldMask} request.fieldMask - * Only the Routine fields in the field mask are updated - * by the given routine. Repeated routine fields will be fully replaced - * if contained in the field mask. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.bigquery.v2.Routine|Routine}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/routine_service.patch_routine.js - * region_tag:bigquery_v2_generated_RoutineService_PatchRoutine_async - */ + /** + * Patches information in an existing routine. The patch method does a partial + * update to an existing Routine resource. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.projectId + * Required. Project ID of the routine to update + * @param {string} request.datasetId + * Required. Dataset ID of the routine to update + * @param {string} request.routineId + * Required. Routine ID of the routine to update + * @param {google.cloud.bigquery.v2.Routine} request.routine + * Required. A routine resource which will be used to partially + * update the specified routine + * @param {google.protobuf.FieldMask} request.fieldMask + * Only the Routine fields in the field mask are updated + * by the given routine. Repeated routine fields will be fully replaced + * if contained in the field mask. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.bigquery.v2.Routine|Routine}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/routine_service.patch_routine.js + * region_tag:bigquery_v2_generated_RoutineService_PatchRoutine_async + */ patchRoutine( - request?: protos.google.cloud.bigquery.v2.IPatchRoutineRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.bigquery.v2.IRoutine, - protos.google.cloud.bigquery.v2.IPatchRoutineRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.bigquery.v2.IPatchRoutineRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.bigquery.v2.IRoutine, + protos.google.cloud.bigquery.v2.IPatchRoutineRequest | undefined, + {} | undefined, + ] + >; patchRoutine( - request: protos.google.cloud.bigquery.v2.IPatchRoutineRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.bigquery.v2.IRoutine, - protos.google.cloud.bigquery.v2.IPatchRoutineRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.bigquery.v2.IPatchRoutineRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.bigquery.v2.IRoutine, + protos.google.cloud.bigquery.v2.IPatchRoutineRequest | null | undefined, + {} | null | undefined + >, + ): void; patchRoutine( - request: protos.google.cloud.bigquery.v2.IPatchRoutineRequest, - callback: Callback< - protos.google.cloud.bigquery.v2.IRoutine, - protos.google.cloud.bigquery.v2.IPatchRoutineRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.bigquery.v2.IPatchRoutineRequest, + callback: Callback< + protos.google.cloud.bigquery.v2.IRoutine, + protos.google.cloud.bigquery.v2.IPatchRoutineRequest | null | undefined, + {} | null | undefined + >, + ): void; patchRoutine( - request?: protos.google.cloud.bigquery.v2.IPatchRoutineRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.bigquery.v2.IRoutine, - protos.google.cloud.bigquery.v2.IPatchRoutineRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.bigquery.v2.IPatchRoutineRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.bigquery.v2.IRoutine, - protos.google.cloud.bigquery.v2.IPatchRoutineRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.bigquery.v2.IRoutine, - protos.google.cloud.bigquery.v2.IPatchRoutineRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.bigquery.v2.IPatchRoutineRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.bigquery.v2.IRoutine, + protos.google.cloud.bigquery.v2.IPatchRoutineRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.bigquery.v2.IRoutine, + protos.google.cloud.bigquery.v2.IPatchRoutineRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('patchRoutine request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.bigquery.v2.IRoutine, - protos.google.cloud.bigquery.v2.IPatchRoutineRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.bigquery.v2.IRoutine, + | protos.google.cloud.bigquery.v2.IPatchRoutineRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('patchRoutine response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.patchRoutine(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.bigquery.v2.IRoutine, - protos.google.cloud.bigquery.v2.IPatchRoutineRequest|undefined, - {}|undefined - ]) => { - this._log.info('patchRoutine response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .patchRoutine(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.bigquery.v2.IRoutine, + protos.google.cloud.bigquery.v2.IPatchRoutineRequest | undefined, + {} | undefined, + ]) => { + this._log.info('patchRoutine response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Deletes the routine specified by routineId from the dataset. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.projectId - * Required. Project ID of the routine to delete - * @param {string} request.datasetId - * Required. Dataset ID of the routine to delete - * @param {string} request.routineId - * Required. Routine ID of the routine to delete - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/routine_service.delete_routine.js - * region_tag:bigquery_v2_generated_RoutineService_DeleteRoutine_async - */ + /** + * Deletes the routine specified by routineId from the dataset. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.projectId + * Required. Project ID of the routine to delete + * @param {string} request.datasetId + * Required. Dataset ID of the routine to delete + * @param {string} request.routineId + * Required. Routine ID of the routine to delete + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/routine_service.delete_routine.js + * region_tag:bigquery_v2_generated_RoutineService_DeleteRoutine_async + */ deleteRoutine( - request?: protos.google.cloud.bigquery.v2.IDeleteRoutineRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.cloud.bigquery.v2.IDeleteRoutineRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.bigquery.v2.IDeleteRoutineRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.cloud.bigquery.v2.IDeleteRoutineRequest | undefined, + {} | undefined, + ] + >; deleteRoutine( - request: protos.google.cloud.bigquery.v2.IDeleteRoutineRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.cloud.bigquery.v2.IDeleteRoutineRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.bigquery.v2.IDeleteRoutineRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.cloud.bigquery.v2.IDeleteRoutineRequest | null | undefined, + {} | null | undefined + >, + ): void; deleteRoutine( - request: protos.google.cloud.bigquery.v2.IDeleteRoutineRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.cloud.bigquery.v2.IDeleteRoutineRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.bigquery.v2.IDeleteRoutineRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.cloud.bigquery.v2.IDeleteRoutineRequest | null | undefined, + {} | null | undefined + >, + ): void; deleteRoutine( - request?: protos.google.cloud.bigquery.v2.IDeleteRoutineRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.cloud.bigquery.v2.IDeleteRoutineRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.cloud.bigquery.v2.IDeleteRoutineRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.protobuf.IEmpty, - protos.google.cloud.bigquery.v2.IDeleteRoutineRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.cloud.bigquery.v2.IDeleteRoutineRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.bigquery.v2.IDeleteRoutineRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + protos.google.cloud.bigquery.v2.IDeleteRoutineRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.cloud.bigquery.v2.IDeleteRoutineRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'project_id': request.projectId?.toString() ?? '', - 'dataset_id': request.datasetId?.toString() ?? '', - 'routine_id': request.routineId?.toString() ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + project_id: request.projectId?.toString() ?? '', + dataset_id: request.datasetId?.toString() ?? '', + routine_id: request.routineId?.toString() ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('deleteRoutine request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.cloud.bigquery.v2.IDeleteRoutineRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.cloud.bigquery.v2.IDeleteRoutineRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteRoutine response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.deleteRoutine(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.cloud.bigquery.v2.IDeleteRoutineRequest|undefined, - {}|undefined - ]) => { - this._log.info('deleteRoutine response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteRoutine(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.cloud.bigquery.v2.IDeleteRoutineRequest | undefined, + {} | undefined, + ]) => { + this._log.info('deleteRoutine response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } - /** - * Lists all routines in the specified dataset. Requires the READER dataset - * role. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.projectId - * Required. Project ID of the routines to list - * @param {string} request.datasetId - * Required. Dataset ID of the routines to list - * @param {google.protobuf.UInt32Value| number } request.maxResults - * The maximum number of results to return in a single response page. - * Leverage the page tokens to iterate through the entire collection. - * @param {string} request.pageToken - * Page token, returned by a previous call, to request the next page of - * results - * @param {string} request.filter - * If set, then only the Routines matching this filter are returned. - * The supported format is `routineType:{RoutineType}`, where `{RoutineType}` - * is a RoutineType enum. For example: `routineType:SCALAR_FUNCTION`. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.cloud.bigquery.v2.Routine|Routine}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `listRoutinesAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Lists all routines in the specified dataset. Requires the READER dataset + * role. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.projectId + * Required. Project ID of the routines to list + * @param {string} request.datasetId + * Required. Dataset ID of the routines to list + * @param {google.protobuf.UInt32Value| number } request.maxResults + * The maximum number of results to return in a single response page. + * Leverage the page tokens to iterate through the entire collection. + * @param {string} request.pageToken + * Page token, returned by a previous call, to request the next page of + * results + * @param {string} request.filter + * If set, then only the Routines matching this filter are returned. + * The supported format is `routineType:{RoutineType}`, where `{RoutineType}` + * is a RoutineType enum. For example: `routineType:SCALAR_FUNCTION`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.cloud.bigquery.v2.Routine|Routine}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listRoutinesAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listRoutines( - request?: protos.google.cloud.bigquery.v2.IListRoutinesRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.bigquery.v2.IRoutine[], - protos.google.cloud.bigquery.v2.IListRoutinesRequest|null, - protos.google.cloud.bigquery.v2.IListRoutinesResponse - ]>; + request?: protos.google.cloud.bigquery.v2.IListRoutinesRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.bigquery.v2.IRoutine[], + protos.google.cloud.bigquery.v2.IListRoutinesRequest | null, + protos.google.cloud.bigquery.v2.IListRoutinesResponse, + ] + >; listRoutines( - request: protos.google.cloud.bigquery.v2.IListRoutinesRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.cloud.bigquery.v2.IListRoutinesRequest, - protos.google.cloud.bigquery.v2.IListRoutinesResponse|null|undefined, - protos.google.cloud.bigquery.v2.IRoutine>): void; + request: protos.google.cloud.bigquery.v2.IListRoutinesRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.cloud.bigquery.v2.IListRoutinesRequest, + protos.google.cloud.bigquery.v2.IListRoutinesResponse | null | undefined, + protos.google.cloud.bigquery.v2.IRoutine + >, + ): void; listRoutines( - request: protos.google.cloud.bigquery.v2.IListRoutinesRequest, - callback: PaginationCallback< - protos.google.cloud.bigquery.v2.IListRoutinesRequest, - protos.google.cloud.bigquery.v2.IListRoutinesResponse|null|undefined, - protos.google.cloud.bigquery.v2.IRoutine>): void; + request: protos.google.cloud.bigquery.v2.IListRoutinesRequest, + callback: PaginationCallback< + protos.google.cloud.bigquery.v2.IListRoutinesRequest, + protos.google.cloud.bigquery.v2.IListRoutinesResponse | null | undefined, + protos.google.cloud.bigquery.v2.IRoutine + >, + ): void; listRoutines( - request?: protos.google.cloud.bigquery.v2.IListRoutinesRequest, - optionsOrCallback?: CallOptions|PaginationCallback< + request?: protos.google.cloud.bigquery.v2.IListRoutinesRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.cloud.bigquery.v2.IListRoutinesRequest, - protos.google.cloud.bigquery.v2.IListRoutinesResponse|null|undefined, - protos.google.cloud.bigquery.v2.IRoutine>, - callback?: PaginationCallback< - protos.google.cloud.bigquery.v2.IListRoutinesRequest, - protos.google.cloud.bigquery.v2.IListRoutinesResponse|null|undefined, - protos.google.cloud.bigquery.v2.IRoutine>): - Promise<[ - protos.google.cloud.bigquery.v2.IRoutine[], - protos.google.cloud.bigquery.v2.IListRoutinesRequest|null, - protos.google.cloud.bigquery.v2.IListRoutinesResponse - ]>|void { + | protos.google.cloud.bigquery.v2.IListRoutinesResponse + | null + | undefined, + protos.google.cloud.bigquery.v2.IRoutine + >, + callback?: PaginationCallback< + protos.google.cloud.bigquery.v2.IListRoutinesRequest, + protos.google.cloud.bigquery.v2.IListRoutinesResponse | null | undefined, + protos.google.cloud.bigquery.v2.IRoutine + >, + ): Promise< + [ + protos.google.cloud.bigquery.v2.IRoutine[], + protos.google.cloud.bigquery.v2.IListRoutinesRequest | null, + protos.google.cloud.bigquery.v2.IListRoutinesResponse, + ] + > | void { request = request || {}; // Converts number to Unit32 or Int32 value for non-compliant APIs. - if(request.maxResults && typeof request.maxResults === "number"){ - const maxResultsObject = {"value": request.maxResults} - request.maxResults = maxResultsObject + if (request.maxResults && typeof request.maxResults === 'number') { + const maxResultsObject = { value: request.maxResults }; + request.maxResults = maxResultsObject; } let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'project_id': request.projectId?.toString() ?? '', - 'dataset_id': request.datasetId?.toString() ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + project_id: request.projectId?.toString() ?? '', + dataset_id: request.datasetId?.toString() ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.cloud.bigquery.v2.IListRoutinesRequest, - protos.google.cloud.bigquery.v2.IListRoutinesResponse|null|undefined, - protos.google.cloud.bigquery.v2.IRoutine>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.cloud.bigquery.v2.IListRoutinesRequest, + | protos.google.cloud.bigquery.v2.IListRoutinesResponse + | null + | undefined, + protos.google.cloud.bigquery.v2.IRoutine + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listRoutines values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -936,124 +1176,128 @@ export class RoutineServiceClient { this._log.info('listRoutines request %j', request); return this.innerApiCalls .listRoutines(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.cloud.bigquery.v2.IRoutine[], - protos.google.cloud.bigquery.v2.IListRoutinesRequest|null, - protos.google.cloud.bigquery.v2.IListRoutinesResponse - ]) => { - this._log.info('listRoutines values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.cloud.bigquery.v2.IRoutine[], + protos.google.cloud.bigquery.v2.IListRoutinesRequest | null, + protos.google.cloud.bigquery.v2.IListRoutinesResponse, + ]) => { + this._log.info('listRoutines values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listRoutines`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.projectId - * Required. Project ID of the routines to list - * @param {string} request.datasetId - * Required. Dataset ID of the routines to list - * @param {google.protobuf.UInt32Value} request.maxResults - * The maximum number of results to return in a single response page. - * Leverage the page tokens to iterate through the entire collection. - * @param {string} request.pageToken - * Page token, returned by a previous call, to request the next page of - * results - * @param {string} request.filter - * If set, then only the Routines matching this filter are returned. - * The supported format is `routineType:{RoutineType}`, where `{RoutineType}` - * is a RoutineType enum. For example: `routineType:SCALAR_FUNCTION`. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.cloud.bigquery.v2.Routine|Routine} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `listRoutinesAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `listRoutines`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.projectId + * Required. Project ID of the routines to list + * @param {string} request.datasetId + * Required. Dataset ID of the routines to list + * @param {google.protobuf.UInt32Value} request.maxResults + * The maximum number of results to return in a single response page. + * Leverage the page tokens to iterate through the entire collection. + * @param {string} request.pageToken + * Page token, returned by a previous call, to request the next page of + * results + * @param {string} request.filter + * If set, then only the Routines matching this filter are returned. + * The supported format is `routineType:{RoutineType}`, where `{RoutineType}` + * is a RoutineType enum. For example: `routineType:SCALAR_FUNCTION`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.cloud.bigquery.v2.Routine|Routine} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listRoutinesAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listRoutinesStream( - request?: protos.google.cloud.bigquery.v2.IListRoutinesRequest, - options?: CallOptions): - Transform{ + request?: protos.google.cloud.bigquery.v2.IListRoutinesRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'project_id': request.projectId?.toString() ?? '', - 'dataset_id': request.datasetId?.toString() ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + project_id: request.projectId?.toString() ?? '', + dataset_id: request.datasetId?.toString() ?? '', + }); const defaultCallSettings = this._defaults['listRoutines']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listRoutines stream %j', request); return this.descriptors.page.listRoutines.createStream( this.innerApiCalls.listRoutines as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listRoutines`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.projectId - * Required. Project ID of the routines to list - * @param {string} request.datasetId - * Required. Dataset ID of the routines to list - * @param {google.protobuf.UInt32Value} request.maxResults - * The maximum number of results to return in a single response page. - * Leverage the page tokens to iterate through the entire collection. - * @param {string} request.pageToken - * Page token, returned by a previous call, to request the next page of - * results - * @param {string} request.filter - * If set, then only the Routines matching this filter are returned. - * The supported format is `routineType:{RoutineType}`, where `{RoutineType}` - * is a RoutineType enum. For example: `routineType:SCALAR_FUNCTION`. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.cloud.bigquery.v2.Routine|Routine}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v2/routine_service.list_routines.js - * region_tag:bigquery_v2_generated_RoutineService_ListRoutines_async - */ + /** + * Equivalent to `listRoutines`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.projectId + * Required. Project ID of the routines to list + * @param {string} request.datasetId + * Required. Dataset ID of the routines to list + * @param {google.protobuf.UInt32Value} request.maxResults + * The maximum number of results to return in a single response page. + * Leverage the page tokens to iterate through the entire collection. + * @param {string} request.pageToken + * Page token, returned by a previous call, to request the next page of + * results + * @param {string} request.filter + * If set, then only the Routines matching this filter are returned. + * The supported format is `routineType:{RoutineType}`, where `{RoutineType}` + * is a RoutineType enum. For example: `routineType:SCALAR_FUNCTION`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.cloud.bigquery.v2.Routine|Routine}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v2/routine_service.list_routines.js + * region_tag:bigquery_v2_generated_RoutineService_ListRoutines_async + */ listRoutinesAsync( - request?: protos.google.cloud.bigquery.v2.IListRoutinesRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.cloud.bigquery.v2.IListRoutinesRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'project_id': request.projectId?.toString() ?? '', - 'dataset_id': request.datasetId?.toString() ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + project_id: request.projectId?.toString() ?? '', + dataset_id: request.datasetId?.toString() ?? '', + }); const defaultCallSettings = this._defaults['listRoutines']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listRoutines iterate %j', request); return this.descriptors.page.listRoutines.asyncIterate( this.innerApiCalls['listRoutines'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } @@ -1065,7 +1309,7 @@ export class RoutineServiceClient { */ close(): Promise { if (this.routineServiceStub && !this._terminated) { - return this.routineServiceStub.then(stub => { + return this.routineServiceStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -1073,4 +1317,4 @@ export class RoutineServiceClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/core/generator/gapic-generator-typescript/baselines/bigquery-v2/src/v2/row_access_policy_service_client.ts.baseline b/core/generator/gapic-generator-typescript/baselines/bigquery-v2/src/v2/row_access_policy_service_client.ts.baseline index 2c498b72ef0f..a47593001694 100644 --- a/core/generator/gapic-generator-typescript/baselines/bigquery-v2/src/v2/row_access_policy_service_client.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/bigquery-v2/src/v2/row_access_policy_service_client.ts.baseline @@ -18,11 +18,18 @@ /* global window */ import type * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions, PaginationCallback, GaxCall} from 'google-gax'; -import {Transform} from 'stream'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + PaginationCallback, + GaxCall, +} from 'google-gax'; +import { Transform } from 'stream'; import * as protos from '../../protos/protos'; import jsonProtos = require('../../protos/protos.json'); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; /** * Client JSON configuration object, loaded from @@ -44,7 +51,7 @@ export class RowAccessPolicyServiceClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('bigquery'); @@ -57,8 +64,8 @@ export class RowAccessPolicyServiceClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - rowAccessPolicyServiceStub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + rowAccessPolicyServiceStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of RowAccessPolicyServiceClient. @@ -99,21 +106,43 @@ export class RowAccessPolicyServiceClient { * const client = new RowAccessPolicyServiceClient({fallback: true}, gax); * ``` */ - constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { // Ensure that options include all the required fields. - const staticMembers = this.constructor as typeof RowAccessPolicyServiceClient; - if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { - throw new Error('Please set either universe_domain or universeDomain, but not both.'); + const staticMembers = this + .constructor as typeof RowAccessPolicyServiceClient; + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); } - const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; - this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; this._servicePath = 'bigquery.' + this._universeDomain; - const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; - const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. if (servicePath !== this._servicePath && !('scopes' in opts)) { @@ -135,7 +164,7 @@ export class RowAccessPolicyServiceClient { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; @@ -149,10 +178,7 @@ export class RowAccessPolicyServiceClient { } // Determine the client header string. - const clientHeader = [ - `gax/${this._gaxModule.version}`, - `gapic/${version}`, - ]; + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/${process.versions.node}`); } else { @@ -173,14 +199,20 @@ export class RowAccessPolicyServiceClient { // (e.g. 50 results at a time, with tokens to get subsequent // pages). Denote the keys used for pagination and results. this.descriptors.page = { - listRowAccessPolicies: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'rowAccessPolicies') + listRowAccessPolicies: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'rowAccessPolicies', + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.cloud.bigquery.v2.RowAccessPolicyService', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.cloud.bigquery.v2.RowAccessPolicyService', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + { 'x-goog-api-client': clientHeader.join(' ') }, + ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -211,37 +243,40 @@ export class RowAccessPolicyServiceClient { // Put together the "service stub" for // google.cloud.bigquery.v2.RowAccessPolicyService. this.rowAccessPolicyServiceStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.cloud.bigquery.v2.RowAccessPolicyService') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.cloud.bigquery.v2.RowAccessPolicyService', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.cloud.bigquery.v2.RowAccessPolicyService, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts, + this._providedCustomServicePath, + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const rowAccessPolicyServiceStubMethods = - ['listRowAccessPolicies']; + const rowAccessPolicyServiceStubMethods = ['listRowAccessPolicies']; for (const methodName of rowAccessPolicyServiceStubMethods) { const callPromise = this.rowAccessPolicyServiceStub.then( - stub => (...args: Array<{}>) => { - if (this._terminated) { - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error|null|undefined) => () => { + (stub) => + (...args: Array<{}>) => { + if (this._terminated) { + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { throw err; - }); + }, + ); - const descriptor = - this.descriptors.page[methodName] || - undefined; + const descriptor = this.descriptors.page[methodName] || undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -256,8 +291,14 @@ export class RowAccessPolicyServiceClient { * @returns {string} The DNS address for this service. */ static get servicePath() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'bigquery.googleapis.com'; } @@ -268,8 +309,14 @@ export class RowAccessPolicyServiceClient { * @returns {string} The DNS address for this service. */ static get apiEndpoint() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'bigquery.googleapis.com'; } @@ -303,7 +350,7 @@ export class RowAccessPolicyServiceClient { return [ 'https://www.googleapis.com/auth/bigquery', 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloud-platform.read-only' + 'https://www.googleapis.com/auth/cloud-platform.read-only', ]; } @@ -313,8 +360,9 @@ export class RowAccessPolicyServiceClient { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId(callback?: Callback): - Promise|void { + getProjectId( + callback?: Callback, + ): Promise | void { if (callback) { this.auth.getProjectId(callback); return; @@ -326,95 +374,120 @@ export class RowAccessPolicyServiceClient { // -- Service calls -- // ------------------- - /** - * Lists all row access policies on the specified table. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.projectId - * Required. Project ID of the row access policies to list. - * @param {string} request.datasetId - * Required. Dataset ID of row access policies to list. - * @param {string} request.tableId - * Required. Table ID of the table to list row access policies. - * @param {string} request.pageToken - * Page token, returned by a previous call, to request the next page of - * results. - * @param {number} request.pageSize - * The maximum number of results to return in a single response page. Leverage - * the page tokens to iterate through the entire collection. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.cloud.bigquery.v2.RowAccessPolicy|RowAccessPolicy}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `listRowAccessPoliciesAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Lists all row access policies on the specified table. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.projectId + * Required. Project ID of the row access policies to list. + * @param {string} request.datasetId + * Required. Dataset ID of row access policies to list. + * @param {string} request.tableId + * Required. Table ID of the table to list row access policies. + * @param {string} request.pageToken + * Page token, returned by a previous call, to request the next page of + * results. + * @param {number} request.pageSize + * The maximum number of results to return in a single response page. Leverage + * the page tokens to iterate through the entire collection. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.cloud.bigquery.v2.RowAccessPolicy|RowAccessPolicy}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listRowAccessPoliciesAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listRowAccessPolicies( - request?: protos.google.cloud.bigquery.v2.IListRowAccessPoliciesRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.bigquery.v2.IRowAccessPolicy[], - protos.google.cloud.bigquery.v2.IListRowAccessPoliciesRequest|null, - protos.google.cloud.bigquery.v2.IListRowAccessPoliciesResponse - ]>; + request?: protos.google.cloud.bigquery.v2.IListRowAccessPoliciesRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.bigquery.v2.IRowAccessPolicy[], + protos.google.cloud.bigquery.v2.IListRowAccessPoliciesRequest | null, + protos.google.cloud.bigquery.v2.IListRowAccessPoliciesResponse, + ] + >; listRowAccessPolicies( - request: protos.google.cloud.bigquery.v2.IListRowAccessPoliciesRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.cloud.bigquery.v2.IListRowAccessPoliciesRequest, - protos.google.cloud.bigquery.v2.IListRowAccessPoliciesResponse|null|undefined, - protos.google.cloud.bigquery.v2.IRowAccessPolicy>): void; + request: protos.google.cloud.bigquery.v2.IListRowAccessPoliciesRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.cloud.bigquery.v2.IListRowAccessPoliciesRequest, + | protos.google.cloud.bigquery.v2.IListRowAccessPoliciesResponse + | null + | undefined, + protos.google.cloud.bigquery.v2.IRowAccessPolicy + >, + ): void; listRowAccessPolicies( - request: protos.google.cloud.bigquery.v2.IListRowAccessPoliciesRequest, - callback: PaginationCallback< - protos.google.cloud.bigquery.v2.IListRowAccessPoliciesRequest, - protos.google.cloud.bigquery.v2.IListRowAccessPoliciesResponse|null|undefined, - protos.google.cloud.bigquery.v2.IRowAccessPolicy>): void; + request: protos.google.cloud.bigquery.v2.IListRowAccessPoliciesRequest, + callback: PaginationCallback< + protos.google.cloud.bigquery.v2.IListRowAccessPoliciesRequest, + | protos.google.cloud.bigquery.v2.IListRowAccessPoliciesResponse + | null + | undefined, + protos.google.cloud.bigquery.v2.IRowAccessPolicy + >, + ): void; listRowAccessPolicies( - request?: protos.google.cloud.bigquery.v2.IListRowAccessPoliciesRequest, - optionsOrCallback?: CallOptions|PaginationCallback< - protos.google.cloud.bigquery.v2.IListRowAccessPoliciesRequest, - protos.google.cloud.bigquery.v2.IListRowAccessPoliciesResponse|null|undefined, - protos.google.cloud.bigquery.v2.IRowAccessPolicy>, - callback?: PaginationCallback< + request?: protos.google.cloud.bigquery.v2.IListRowAccessPoliciesRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.cloud.bigquery.v2.IListRowAccessPoliciesRequest, - protos.google.cloud.bigquery.v2.IListRowAccessPoliciesResponse|null|undefined, - protos.google.cloud.bigquery.v2.IRowAccessPolicy>): - Promise<[ - protos.google.cloud.bigquery.v2.IRowAccessPolicy[], - protos.google.cloud.bigquery.v2.IListRowAccessPoliciesRequest|null, - protos.google.cloud.bigquery.v2.IListRowAccessPoliciesResponse - ]>|void { + | protos.google.cloud.bigquery.v2.IListRowAccessPoliciesResponse + | null + | undefined, + protos.google.cloud.bigquery.v2.IRowAccessPolicy + >, + callback?: PaginationCallback< + protos.google.cloud.bigquery.v2.IListRowAccessPoliciesRequest, + | protos.google.cloud.bigquery.v2.IListRowAccessPoliciesResponse + | null + | undefined, + protos.google.cloud.bigquery.v2.IRowAccessPolicy + >, + ): Promise< + [ + protos.google.cloud.bigquery.v2.IRowAccessPolicy[], + protos.google.cloud.bigquery.v2.IListRowAccessPoliciesRequest | null, + protos.google.cloud.bigquery.v2.IListRowAccessPoliciesResponse, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'project_id': request.projectId?.toString() ?? '', - 'dataset_id': request.datasetId?.toString() ?? '', - 'table_id': request.tableId?.toString() ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + project_id: request.projectId?.toString() ?? '', + dataset_id: request.datasetId?.toString() ?? '', + table_id: request.tableId?.toString() ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.cloud.bigquery.v2.IListRowAccessPoliciesRequest, - protos.google.cloud.bigquery.v2.IListRowAccessPoliciesResponse|null|undefined, - protos.google.cloud.bigquery.v2.IRowAccessPolicy>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.cloud.bigquery.v2.IListRowAccessPoliciesRequest, + | protos.google.cloud.bigquery.v2.IListRowAccessPoliciesResponse + | null + | undefined, + protos.google.cloud.bigquery.v2.IRowAccessPolicy + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listRowAccessPolicies values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -423,122 +496,126 @@ export class RowAccessPolicyServiceClient { this._log.info('listRowAccessPolicies request %j', request); return this.innerApiCalls .listRowAccessPolicies(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.cloud.bigquery.v2.IRowAccessPolicy[], - protos.google.cloud.bigquery.v2.IListRowAccessPoliciesRequest|null, - protos.google.cloud.bigquery.v2.IListRowAccessPoliciesResponse - ]) => { - this._log.info('listRowAccessPolicies values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.cloud.bigquery.v2.IRowAccessPolicy[], + protos.google.cloud.bigquery.v2.IListRowAccessPoliciesRequest | null, + protos.google.cloud.bigquery.v2.IListRowAccessPoliciesResponse, + ]) => { + this._log.info('listRowAccessPolicies values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listRowAccessPolicies`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.projectId - * Required. Project ID of the row access policies to list. - * @param {string} request.datasetId - * Required. Dataset ID of row access policies to list. - * @param {string} request.tableId - * Required. Table ID of the table to list row access policies. - * @param {string} request.pageToken - * Page token, returned by a previous call, to request the next page of - * results. - * @param {number} request.pageSize - * The maximum number of results to return in a single response page. Leverage - * the page tokens to iterate through the entire collection. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.cloud.bigquery.v2.RowAccessPolicy|RowAccessPolicy} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `listRowAccessPoliciesAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `listRowAccessPolicies`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.projectId + * Required. Project ID of the row access policies to list. + * @param {string} request.datasetId + * Required. Dataset ID of row access policies to list. + * @param {string} request.tableId + * Required. Table ID of the table to list row access policies. + * @param {string} request.pageToken + * Page token, returned by a previous call, to request the next page of + * results. + * @param {number} request.pageSize + * The maximum number of results to return in a single response page. Leverage + * the page tokens to iterate through the entire collection. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.cloud.bigquery.v2.RowAccessPolicy|RowAccessPolicy} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listRowAccessPoliciesAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listRowAccessPoliciesStream( - request?: protos.google.cloud.bigquery.v2.IListRowAccessPoliciesRequest, - options?: CallOptions): - Transform{ + request?: protos.google.cloud.bigquery.v2.IListRowAccessPoliciesRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'project_id': request.projectId?.toString() ?? '', - 'dataset_id': request.datasetId?.toString() ?? '', - 'table_id': request.tableId?.toString() ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + project_id: request.projectId?.toString() ?? '', + dataset_id: request.datasetId?.toString() ?? '', + table_id: request.tableId?.toString() ?? '', + }); const defaultCallSettings = this._defaults['listRowAccessPolicies']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listRowAccessPolicies stream %j', request); return this.descriptors.page.listRowAccessPolicies.createStream( this.innerApiCalls.listRowAccessPolicies as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listRowAccessPolicies`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.projectId - * Required. Project ID of the row access policies to list. - * @param {string} request.datasetId - * Required. Dataset ID of row access policies to list. - * @param {string} request.tableId - * Required. Table ID of the table to list row access policies. - * @param {string} request.pageToken - * Page token, returned by a previous call, to request the next page of - * results. - * @param {number} request.pageSize - * The maximum number of results to return in a single response page. Leverage - * the page tokens to iterate through the entire collection. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.cloud.bigquery.v2.RowAccessPolicy|RowAccessPolicy}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v2/row_access_policy_service.list_row_access_policies.js - * region_tag:bigquery_v2_generated_RowAccessPolicyService_ListRowAccessPolicies_async - */ + /** + * Equivalent to `listRowAccessPolicies`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.projectId + * Required. Project ID of the row access policies to list. + * @param {string} request.datasetId + * Required. Dataset ID of row access policies to list. + * @param {string} request.tableId + * Required. Table ID of the table to list row access policies. + * @param {string} request.pageToken + * Page token, returned by a previous call, to request the next page of + * results. + * @param {number} request.pageSize + * The maximum number of results to return in a single response page. Leverage + * the page tokens to iterate through the entire collection. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.cloud.bigquery.v2.RowAccessPolicy|RowAccessPolicy}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v2/row_access_policy_service.list_row_access_policies.js + * region_tag:bigquery_v2_generated_RowAccessPolicyService_ListRowAccessPolicies_async + */ listRowAccessPoliciesAsync( - request?: protos.google.cloud.bigquery.v2.IListRowAccessPoliciesRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.cloud.bigquery.v2.IListRowAccessPoliciesRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'project_id': request.projectId?.toString() ?? '', - 'dataset_id': request.datasetId?.toString() ?? '', - 'table_id': request.tableId?.toString() ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + project_id: request.projectId?.toString() ?? '', + dataset_id: request.datasetId?.toString() ?? '', + table_id: request.tableId?.toString() ?? '', + }); const defaultCallSettings = this._defaults['listRowAccessPolicies']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listRowAccessPolicies iterate %j', request); return this.descriptors.page.listRowAccessPolicies.asyncIterate( this.innerApiCalls['listRowAccessPolicies'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } @@ -550,7 +627,7 @@ export class RowAccessPolicyServiceClient { */ close(): Promise { if (this.rowAccessPolicyServiceStub && !this._terminated) { - return this.rowAccessPolicyServiceStub.then(stub => { + return this.rowAccessPolicyServiceStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -558,4 +635,4 @@ export class RowAccessPolicyServiceClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/core/generator/gapic-generator-typescript/baselines/bigquery-v2/src/v2/table_service_client.ts.baseline b/core/generator/gapic-generator-typescript/baselines/bigquery-v2/src/v2/table_service_client.ts.baseline index e28c6c1fc894..62b235b88c2d 100644 --- a/core/generator/gapic-generator-typescript/baselines/bigquery-v2/src/v2/table_service_client.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/bigquery-v2/src/v2/table_service_client.ts.baseline @@ -18,11 +18,18 @@ /* global window */ import type * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions, PaginationCallback, GaxCall} from 'google-gax'; -import {Transform} from 'stream'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + PaginationCallback, + GaxCall, +} from 'google-gax'; +import { Transform } from 'stream'; import * as protos from '../../protos/protos'; import jsonProtos = require('../../protos/protos.json'); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; /** * Client JSON configuration object, loaded from @@ -47,7 +54,7 @@ export class TableServiceClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('bigquery'); @@ -60,8 +67,8 @@ export class TableServiceClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - tableServiceStub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + tableServiceStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of TableServiceClient. @@ -102,21 +109,42 @@ export class TableServiceClient { * const client = new TableServiceClient({fallback: true}, gax); * ``` */ - constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { // Ensure that options include all the required fields. const staticMembers = this.constructor as typeof TableServiceClient; - if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { - throw new Error('Please set either universe_domain or universeDomain, but not both.'); + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); } - const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; - this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; this._servicePath = 'bigquery.' + this._universeDomain; - const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; - const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. if (servicePath !== this._servicePath && !('scopes' in opts)) { @@ -138,7 +166,7 @@ export class TableServiceClient { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; @@ -152,10 +180,7 @@ export class TableServiceClient { } // Determine the client header string. - const clientHeader = [ - `gax/${this._gaxModule.version}`, - `gapic/${version}`, - ]; + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/${process.versions.node}`); } else { @@ -176,14 +201,20 @@ export class TableServiceClient { // (e.g. 50 results at a time, with tokens to get subsequent // pages). Denote the keys used for pagination and results. this.descriptors.page = { - listTables: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'tables') + listTables: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'tables', + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.cloud.bigquery.v2.TableService', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.cloud.bigquery.v2.TableService', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + { 'x-goog-api-client': clientHeader.join(' ') }, + ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -214,37 +245,47 @@ export class TableServiceClient { // Put together the "service stub" for // google.cloud.bigquery.v2.TableService. this.tableServiceStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.cloud.bigquery.v2.TableService') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.cloud.bigquery.v2.TableService', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.cloud.bigquery.v2.TableService, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts, + this._providedCustomServicePath, + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const tableServiceStubMethods = - ['getTable', 'insertTable', 'patchTable', 'updateTable', 'deleteTable', 'listTables']; + const tableServiceStubMethods = [ + 'getTable', + 'insertTable', + 'patchTable', + 'updateTable', + 'deleteTable', + 'listTables', + ]; for (const methodName of tableServiceStubMethods) { const callPromise = this.tableServiceStub.then( - stub => (...args: Array<{}>) => { - if (this._terminated) { - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error|null|undefined) => () => { + (stub) => + (...args: Array<{}>) => { + if (this._terminated) { + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { throw err; - }); + }, + ); - const descriptor = - this.descriptors.page[methodName] || - undefined; + const descriptor = this.descriptors.page[methodName] || undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -259,8 +300,14 @@ export class TableServiceClient { * @returns {string} The DNS address for this service. */ static get servicePath() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'bigquery.googleapis.com'; } @@ -271,8 +318,14 @@ export class TableServiceClient { * @returns {string} The DNS address for this service. */ static get apiEndpoint() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'bigquery.googleapis.com'; } @@ -306,7 +359,7 @@ export class TableServiceClient { return [ 'https://www.googleapis.com/auth/bigquery', 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloud-platform.read-only' + 'https://www.googleapis.com/auth/cloud-platform.read-only', ]; } @@ -316,8 +369,9 @@ export class TableServiceClient { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId(callback?: Callback): - Promise|void { + getProjectId( + callback?: Callback, + ): Promise | void { if (callback) { this.auth.getProjectId(callback); return; @@ -328,625 +382,824 @@ export class TableServiceClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Gets the specified table resource by table ID. - * This method does not return the data in the table, it only returns the - * table resource, which describes the structure of this table. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.projectId - * Required. Project ID of the requested table - * @param {string} request.datasetId - * Required. Dataset ID of the requested table - * @param {string} request.tableId - * Required. Table ID of the requested table - * @param {string} request.selectedFields - * List of table schema fields to return (comma-separated). - * If unspecified, all fields are returned. - * A fieldMask cannot be used here because the fields will automatically be - * converted from camelCase to snake_case and the conversion will fail if - * there are underscores. Since these are fields in BigQuery table schemas, - * underscores are allowed. - * @param {google.cloud.bigquery.v2.GetTableRequest.TableMetadataView} [request.view] - * Optional. Specifies the view that determines which table information is - * returned. By default, basic table information and storage statistics - * (STORAGE_STATS) are returned. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.bigquery.v2.Table|Table}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/table_service.get_table.js - * region_tag:bigquery_v2_generated_TableService_GetTable_async - */ + /** + * Gets the specified table resource by table ID. + * This method does not return the data in the table, it only returns the + * table resource, which describes the structure of this table. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.projectId + * Required. Project ID of the requested table + * @param {string} request.datasetId + * Required. Dataset ID of the requested table + * @param {string} request.tableId + * Required. Table ID of the requested table + * @param {string} request.selectedFields + * List of table schema fields to return (comma-separated). + * If unspecified, all fields are returned. + * A fieldMask cannot be used here because the fields will automatically be + * converted from camelCase to snake_case and the conversion will fail if + * there are underscores. Since these are fields in BigQuery table schemas, + * underscores are allowed. + * @param {google.cloud.bigquery.v2.GetTableRequest.TableMetadataView} [request.view] + * Optional. Specifies the view that determines which table information is + * returned. By default, basic table information and storage statistics + * (STORAGE_STATS) are returned. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.bigquery.v2.Table|Table}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/table_service.get_table.js + * region_tag:bigquery_v2_generated_TableService_GetTable_async + */ getTable( - request?: protos.google.cloud.bigquery.v2.IGetTableRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.bigquery.v2.ITable, - protos.google.cloud.bigquery.v2.IGetTableRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.bigquery.v2.IGetTableRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.bigquery.v2.ITable, + protos.google.cloud.bigquery.v2.IGetTableRequest | undefined, + {} | undefined, + ] + >; getTable( - request: protos.google.cloud.bigquery.v2.IGetTableRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.bigquery.v2.ITable, - protos.google.cloud.bigquery.v2.IGetTableRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.bigquery.v2.IGetTableRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.bigquery.v2.ITable, + protos.google.cloud.bigquery.v2.IGetTableRequest | null | undefined, + {} | null | undefined + >, + ): void; getTable( - request: protos.google.cloud.bigquery.v2.IGetTableRequest, - callback: Callback< - protos.google.cloud.bigquery.v2.ITable, - protos.google.cloud.bigquery.v2.IGetTableRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.bigquery.v2.IGetTableRequest, + callback: Callback< + protos.google.cloud.bigquery.v2.ITable, + protos.google.cloud.bigquery.v2.IGetTableRequest | null | undefined, + {} | null | undefined + >, + ): void; getTable( - request?: protos.google.cloud.bigquery.v2.IGetTableRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.bigquery.v2.ITable, - protos.google.cloud.bigquery.v2.IGetTableRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.bigquery.v2.IGetTableRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.bigquery.v2.ITable, - protos.google.cloud.bigquery.v2.IGetTableRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.bigquery.v2.ITable, - protos.google.cloud.bigquery.v2.IGetTableRequest|undefined, {}|undefined - ]>|void { + protos.google.cloud.bigquery.v2.IGetTableRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.bigquery.v2.ITable, + protos.google.cloud.bigquery.v2.IGetTableRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.bigquery.v2.ITable, + protos.google.cloud.bigquery.v2.IGetTableRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'project_id': request.projectId?.toString() ?? '', - 'dataset_id': request.datasetId?.toString() ?? '', - 'table_id': request.tableId?.toString() ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + project_id: request.projectId?.toString() ?? '', + dataset_id: request.datasetId?.toString() ?? '', + table_id: request.tableId?.toString() ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getTable request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.bigquery.v2.ITable, - protos.google.cloud.bigquery.v2.IGetTableRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.bigquery.v2.ITable, + protos.google.cloud.bigquery.v2.IGetTableRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getTable response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getTable(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.bigquery.v2.ITable, - protos.google.cloud.bigquery.v2.IGetTableRequest|undefined, - {}|undefined - ]) => { - this._log.info('getTable response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getTable(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.bigquery.v2.ITable, + protos.google.cloud.bigquery.v2.IGetTableRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getTable response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Creates a new, empty table in the dataset. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.projectId - * Required. Project ID of the new table - * @param {string} request.datasetId - * Required. Dataset ID of the new table - * @param {google.cloud.bigquery.v2.Table} request.table - * Required. A tables resource to insert - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.bigquery.v2.Table|Table}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/table_service.insert_table.js - * region_tag:bigquery_v2_generated_TableService_InsertTable_async - */ + /** + * Creates a new, empty table in the dataset. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.projectId + * Required. Project ID of the new table + * @param {string} request.datasetId + * Required. Dataset ID of the new table + * @param {google.cloud.bigquery.v2.Table} request.table + * Required. A tables resource to insert + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.bigquery.v2.Table|Table}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/table_service.insert_table.js + * region_tag:bigquery_v2_generated_TableService_InsertTable_async + */ insertTable( - request?: protos.google.cloud.bigquery.v2.IInsertTableRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.bigquery.v2.ITable, - protos.google.cloud.bigquery.v2.IInsertTableRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.bigquery.v2.IInsertTableRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.bigquery.v2.ITable, + protos.google.cloud.bigquery.v2.IInsertTableRequest | undefined, + {} | undefined, + ] + >; insertTable( - request: protos.google.cloud.bigquery.v2.IInsertTableRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.bigquery.v2.ITable, - protos.google.cloud.bigquery.v2.IInsertTableRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.bigquery.v2.IInsertTableRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.bigquery.v2.ITable, + protos.google.cloud.bigquery.v2.IInsertTableRequest | null | undefined, + {} | null | undefined + >, + ): void; insertTable( - request: protos.google.cloud.bigquery.v2.IInsertTableRequest, - callback: Callback< - protos.google.cloud.bigquery.v2.ITable, - protos.google.cloud.bigquery.v2.IInsertTableRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.bigquery.v2.IInsertTableRequest, + callback: Callback< + protos.google.cloud.bigquery.v2.ITable, + protos.google.cloud.bigquery.v2.IInsertTableRequest | null | undefined, + {} | null | undefined + >, + ): void; insertTable( - request?: protos.google.cloud.bigquery.v2.IInsertTableRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.cloud.bigquery.v2.IInsertTableRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.bigquery.v2.ITable, - protos.google.cloud.bigquery.v2.IInsertTableRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.cloud.bigquery.v2.ITable, - protos.google.cloud.bigquery.v2.IInsertTableRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.bigquery.v2.ITable, - protos.google.cloud.bigquery.v2.IInsertTableRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.bigquery.v2.IInsertTableRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.bigquery.v2.ITable, + protos.google.cloud.bigquery.v2.IInsertTableRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.bigquery.v2.ITable, + protos.google.cloud.bigquery.v2.IInsertTableRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'project_id': request.projectId?.toString() ?? '', - 'dataset_id': request.datasetId?.toString() ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + project_id: request.projectId?.toString() ?? '', + dataset_id: request.datasetId?.toString() ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('insertTable request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.bigquery.v2.ITable, - protos.google.cloud.bigquery.v2.IInsertTableRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.bigquery.v2.ITable, + | protos.google.cloud.bigquery.v2.IInsertTableRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('insertTable response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.insertTable(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.bigquery.v2.ITable, - protos.google.cloud.bigquery.v2.IInsertTableRequest|undefined, - {}|undefined - ]) => { - this._log.info('insertTable response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .insertTable(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.bigquery.v2.ITable, + protos.google.cloud.bigquery.v2.IInsertTableRequest | undefined, + {} | undefined, + ]) => { + this._log.info('insertTable response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Updates information in an existing table. The update method replaces the - * entire table resource, whereas the patch method only replaces fields that - * are provided in the submitted table resource. - * This method supports RFC5789 patch semantics. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.projectId - * Required. Project ID of the table to update - * @param {string} request.datasetId - * Required. Dataset ID of the table to update - * @param {string} request.tableId - * Required. Table ID of the table to update - * @param {google.cloud.bigquery.v2.Table} request.table - * Required. A tables resource which will replace or patch the specified table - * @param {boolean} [request.autodetectSchema] - * Optional. When true will autodetect schema, else will keep original schema. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.bigquery.v2.Table|Table}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/table_service.patch_table.js - * region_tag:bigquery_v2_generated_TableService_PatchTable_async - */ + /** + * Updates information in an existing table. The update method replaces the + * entire table resource, whereas the patch method only replaces fields that + * are provided in the submitted table resource. + * This method supports RFC5789 patch semantics. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.projectId + * Required. Project ID of the table to update + * @param {string} request.datasetId + * Required. Dataset ID of the table to update + * @param {string} request.tableId + * Required. Table ID of the table to update + * @param {google.cloud.bigquery.v2.Table} request.table + * Required. A tables resource which will replace or patch the specified table + * @param {boolean} [request.autodetectSchema] + * Optional. When true will autodetect schema, else will keep original schema. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.bigquery.v2.Table|Table}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/table_service.patch_table.js + * region_tag:bigquery_v2_generated_TableService_PatchTable_async + */ patchTable( - request?: protos.google.cloud.bigquery.v2.IUpdateOrPatchTableRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.bigquery.v2.ITable, - protos.google.cloud.bigquery.v2.IUpdateOrPatchTableRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.bigquery.v2.IUpdateOrPatchTableRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.bigquery.v2.ITable, + protos.google.cloud.bigquery.v2.IUpdateOrPatchTableRequest | undefined, + {} | undefined, + ] + >; patchTable( - request: protos.google.cloud.bigquery.v2.IUpdateOrPatchTableRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.bigquery.v2.ITable, - protos.google.cloud.bigquery.v2.IUpdateOrPatchTableRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.bigquery.v2.IUpdateOrPatchTableRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.bigquery.v2.ITable, + | protos.google.cloud.bigquery.v2.IUpdateOrPatchTableRequest + | null + | undefined, + {} | null | undefined + >, + ): void; patchTable( - request: protos.google.cloud.bigquery.v2.IUpdateOrPatchTableRequest, - callback: Callback< - protos.google.cloud.bigquery.v2.ITable, - protos.google.cloud.bigquery.v2.IUpdateOrPatchTableRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.bigquery.v2.IUpdateOrPatchTableRequest, + callback: Callback< + protos.google.cloud.bigquery.v2.ITable, + | protos.google.cloud.bigquery.v2.IUpdateOrPatchTableRequest + | null + | undefined, + {} | null | undefined + >, + ): void; patchTable( - request?: protos.google.cloud.bigquery.v2.IUpdateOrPatchTableRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.bigquery.v2.ITable, - protos.google.cloud.bigquery.v2.IUpdateOrPatchTableRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.bigquery.v2.IUpdateOrPatchTableRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.bigquery.v2.ITable, - protos.google.cloud.bigquery.v2.IUpdateOrPatchTableRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.bigquery.v2.ITable, - protos.google.cloud.bigquery.v2.IUpdateOrPatchTableRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.bigquery.v2.IUpdateOrPatchTableRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.bigquery.v2.ITable, + | protos.google.cloud.bigquery.v2.IUpdateOrPatchTableRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.bigquery.v2.ITable, + protos.google.cloud.bigquery.v2.IUpdateOrPatchTableRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'project_id': request.projectId?.toString() ?? '', - 'dataset_id': request.datasetId?.toString() ?? '', - 'table_id': request.tableId?.toString() ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + project_id: request.projectId?.toString() ?? '', + dataset_id: request.datasetId?.toString() ?? '', + table_id: request.tableId?.toString() ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('patchTable request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.bigquery.v2.ITable, - protos.google.cloud.bigquery.v2.IUpdateOrPatchTableRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.bigquery.v2.ITable, + | protos.google.cloud.bigquery.v2.IUpdateOrPatchTableRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('patchTable response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.patchTable(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.bigquery.v2.ITable, - protos.google.cloud.bigquery.v2.IUpdateOrPatchTableRequest|undefined, - {}|undefined - ]) => { - this._log.info('patchTable response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .patchTable(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.bigquery.v2.ITable, + ( + | protos.google.cloud.bigquery.v2.IUpdateOrPatchTableRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('patchTable response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Updates information in an existing table. The update method replaces the - * entire Table resource, whereas the patch method only replaces fields that - * are provided in the submitted Table resource. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.projectId - * Required. Project ID of the table to update - * @param {string} request.datasetId - * Required. Dataset ID of the table to update - * @param {string} request.tableId - * Required. Table ID of the table to update - * @param {google.cloud.bigquery.v2.Table} request.table - * Required. A tables resource which will replace or patch the specified table - * @param {boolean} [request.autodetectSchema] - * Optional. When true will autodetect schema, else will keep original schema. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.bigquery.v2.Table|Table}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/table_service.update_table.js - * region_tag:bigquery_v2_generated_TableService_UpdateTable_async - */ + /** + * Updates information in an existing table. The update method replaces the + * entire Table resource, whereas the patch method only replaces fields that + * are provided in the submitted Table resource. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.projectId + * Required. Project ID of the table to update + * @param {string} request.datasetId + * Required. Dataset ID of the table to update + * @param {string} request.tableId + * Required. Table ID of the table to update + * @param {google.cloud.bigquery.v2.Table} request.table + * Required. A tables resource which will replace or patch the specified table + * @param {boolean} [request.autodetectSchema] + * Optional. When true will autodetect schema, else will keep original schema. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.bigquery.v2.Table|Table}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/table_service.update_table.js + * region_tag:bigquery_v2_generated_TableService_UpdateTable_async + */ updateTable( - request?: protos.google.cloud.bigquery.v2.IUpdateOrPatchTableRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.bigquery.v2.ITable, - protos.google.cloud.bigquery.v2.IUpdateOrPatchTableRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.bigquery.v2.IUpdateOrPatchTableRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.bigquery.v2.ITable, + protos.google.cloud.bigquery.v2.IUpdateOrPatchTableRequest | undefined, + {} | undefined, + ] + >; updateTable( - request: protos.google.cloud.bigquery.v2.IUpdateOrPatchTableRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.bigquery.v2.ITable, - protos.google.cloud.bigquery.v2.IUpdateOrPatchTableRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.bigquery.v2.IUpdateOrPatchTableRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.bigquery.v2.ITable, + | protos.google.cloud.bigquery.v2.IUpdateOrPatchTableRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateTable( - request: protos.google.cloud.bigquery.v2.IUpdateOrPatchTableRequest, - callback: Callback< - protos.google.cloud.bigquery.v2.ITable, - protos.google.cloud.bigquery.v2.IUpdateOrPatchTableRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.bigquery.v2.IUpdateOrPatchTableRequest, + callback: Callback< + protos.google.cloud.bigquery.v2.ITable, + | protos.google.cloud.bigquery.v2.IUpdateOrPatchTableRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateTable( - request?: protos.google.cloud.bigquery.v2.IUpdateOrPatchTableRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.bigquery.v2.ITable, - protos.google.cloud.bigquery.v2.IUpdateOrPatchTableRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.bigquery.v2.IUpdateOrPatchTableRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.bigquery.v2.ITable, - protos.google.cloud.bigquery.v2.IUpdateOrPatchTableRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.bigquery.v2.ITable, - protos.google.cloud.bigquery.v2.IUpdateOrPatchTableRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.bigquery.v2.IUpdateOrPatchTableRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.bigquery.v2.ITable, + | protos.google.cloud.bigquery.v2.IUpdateOrPatchTableRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.bigquery.v2.ITable, + protos.google.cloud.bigquery.v2.IUpdateOrPatchTableRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'project_id': request.projectId?.toString() ?? '', - 'dataset_id': request.datasetId?.toString() ?? '', - 'table_id': request.tableId?.toString() ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + project_id: request.projectId?.toString() ?? '', + dataset_id: request.datasetId?.toString() ?? '', + table_id: request.tableId?.toString() ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateTable request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.bigquery.v2.ITable, - protos.google.cloud.bigquery.v2.IUpdateOrPatchTableRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.bigquery.v2.ITable, + | protos.google.cloud.bigquery.v2.IUpdateOrPatchTableRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateTable response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.updateTable(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.bigquery.v2.ITable, - protos.google.cloud.bigquery.v2.IUpdateOrPatchTableRequest|undefined, - {}|undefined - ]) => { - this._log.info('updateTable response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateTable(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.bigquery.v2.ITable, + ( + | protos.google.cloud.bigquery.v2.IUpdateOrPatchTableRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('updateTable response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Deletes the table specified by tableId from the dataset. - * If the table contains data, all the data will be deleted. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.projectId - * Required. Project ID of the table to delete - * @param {string} request.datasetId - * Required. Dataset ID of the table to delete - * @param {string} request.tableId - * Required. Table ID of the table to delete - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/table_service.delete_table.js - * region_tag:bigquery_v2_generated_TableService_DeleteTable_async - */ + /** + * Deletes the table specified by tableId from the dataset. + * If the table contains data, all the data will be deleted. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.projectId + * Required. Project ID of the table to delete + * @param {string} request.datasetId + * Required. Dataset ID of the table to delete + * @param {string} request.tableId + * Required. Table ID of the table to delete + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/table_service.delete_table.js + * region_tag:bigquery_v2_generated_TableService_DeleteTable_async + */ deleteTable( - request?: protos.google.cloud.bigquery.v2.IDeleteTableRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.cloud.bigquery.v2.IDeleteTableRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.bigquery.v2.IDeleteTableRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.cloud.bigquery.v2.IDeleteTableRequest | undefined, + {} | undefined, + ] + >; deleteTable( - request: protos.google.cloud.bigquery.v2.IDeleteTableRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.cloud.bigquery.v2.IDeleteTableRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.bigquery.v2.IDeleteTableRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.cloud.bigquery.v2.IDeleteTableRequest | null | undefined, + {} | null | undefined + >, + ): void; deleteTable( - request: protos.google.cloud.bigquery.v2.IDeleteTableRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.cloud.bigquery.v2.IDeleteTableRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.bigquery.v2.IDeleteTableRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.cloud.bigquery.v2.IDeleteTableRequest | null | undefined, + {} | null | undefined + >, + ): void; deleteTable( - request?: protos.google.cloud.bigquery.v2.IDeleteTableRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.cloud.bigquery.v2.IDeleteTableRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.cloud.bigquery.v2.IDeleteTableRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.protobuf.IEmpty, - protos.google.cloud.bigquery.v2.IDeleteTableRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.cloud.bigquery.v2.IDeleteTableRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.bigquery.v2.IDeleteTableRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + protos.google.cloud.bigquery.v2.IDeleteTableRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.cloud.bigquery.v2.IDeleteTableRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'project_id': request.projectId?.toString() ?? '', - 'dataset_id': request.datasetId?.toString() ?? '', - 'table_id': request.tableId?.toString() ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + project_id: request.projectId?.toString() ?? '', + dataset_id: request.datasetId?.toString() ?? '', + table_id: request.tableId?.toString() ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('deleteTable request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.cloud.bigquery.v2.IDeleteTableRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.cloud.bigquery.v2.IDeleteTableRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteTable response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.deleteTable(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.cloud.bigquery.v2.IDeleteTableRequest|undefined, - {}|undefined - ]) => { - this._log.info('deleteTable response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteTable(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.cloud.bigquery.v2.IDeleteTableRequest | undefined, + {} | undefined, + ]) => { + this._log.info('deleteTable response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } - /** - * Lists all tables in the specified dataset. Requires the READER dataset - * role. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.projectId - * Required. Project ID of the tables to list - * @param {string} request.datasetId - * Required. Dataset ID of the tables to list - * @param {google.protobuf.UInt32Value| number } request.maxResults - * The maximum number of results to return in a single response page. - * Leverage the page tokens to iterate through the entire collection. - * @param {string} request.pageToken - * Page token, returned by a previous call, to request the next page of - * results - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.cloud.bigquery.v2.ListFormatTable|ListFormatTable}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `listTablesAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Lists all tables in the specified dataset. Requires the READER dataset + * role. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.projectId + * Required. Project ID of the tables to list + * @param {string} request.datasetId + * Required. Dataset ID of the tables to list + * @param {google.protobuf.UInt32Value| number } request.maxResults + * The maximum number of results to return in a single response page. + * Leverage the page tokens to iterate through the entire collection. + * @param {string} request.pageToken + * Page token, returned by a previous call, to request the next page of + * results + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.cloud.bigquery.v2.ListFormatTable|ListFormatTable}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listTablesAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listTables( - request?: protos.google.cloud.bigquery.v2.IListTablesRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.bigquery.v2.IListFormatTable[], - protos.google.cloud.bigquery.v2.IListTablesRequest|null, - protos.google.cloud.bigquery.v2.ITableList - ]>; + request?: protos.google.cloud.bigquery.v2.IListTablesRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.bigquery.v2.IListFormatTable[], + protos.google.cloud.bigquery.v2.IListTablesRequest | null, + protos.google.cloud.bigquery.v2.ITableList, + ] + >; listTables( - request: protos.google.cloud.bigquery.v2.IListTablesRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.cloud.bigquery.v2.IListTablesRequest, - protos.google.cloud.bigquery.v2.ITableList|null|undefined, - protos.google.cloud.bigquery.v2.IListFormatTable>): void; + request: protos.google.cloud.bigquery.v2.IListTablesRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.cloud.bigquery.v2.IListTablesRequest, + protos.google.cloud.bigquery.v2.ITableList | null | undefined, + protos.google.cloud.bigquery.v2.IListFormatTable + >, + ): void; listTables( - request: protos.google.cloud.bigquery.v2.IListTablesRequest, - callback: PaginationCallback< - protos.google.cloud.bigquery.v2.IListTablesRequest, - protos.google.cloud.bigquery.v2.ITableList|null|undefined, - protos.google.cloud.bigquery.v2.IListFormatTable>): void; + request: protos.google.cloud.bigquery.v2.IListTablesRequest, + callback: PaginationCallback< + protos.google.cloud.bigquery.v2.IListTablesRequest, + protos.google.cloud.bigquery.v2.ITableList | null | undefined, + protos.google.cloud.bigquery.v2.IListFormatTable + >, + ): void; listTables( - request?: protos.google.cloud.bigquery.v2.IListTablesRequest, - optionsOrCallback?: CallOptions|PaginationCallback< + request?: protos.google.cloud.bigquery.v2.IListTablesRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.cloud.bigquery.v2.IListTablesRequest, - protos.google.cloud.bigquery.v2.ITableList|null|undefined, - protos.google.cloud.bigquery.v2.IListFormatTable>, - callback?: PaginationCallback< - protos.google.cloud.bigquery.v2.IListTablesRequest, - protos.google.cloud.bigquery.v2.ITableList|null|undefined, - protos.google.cloud.bigquery.v2.IListFormatTable>): - Promise<[ - protos.google.cloud.bigquery.v2.IListFormatTable[], - protos.google.cloud.bigquery.v2.IListTablesRequest|null, - protos.google.cloud.bigquery.v2.ITableList - ]>|void { + protos.google.cloud.bigquery.v2.ITableList | null | undefined, + protos.google.cloud.bigquery.v2.IListFormatTable + >, + callback?: PaginationCallback< + protos.google.cloud.bigquery.v2.IListTablesRequest, + protos.google.cloud.bigquery.v2.ITableList | null | undefined, + protos.google.cloud.bigquery.v2.IListFormatTable + >, + ): Promise< + [ + protos.google.cloud.bigquery.v2.IListFormatTable[], + protos.google.cloud.bigquery.v2.IListTablesRequest | null, + protos.google.cloud.bigquery.v2.ITableList, + ] + > | void { request = request || {}; // Converts number to Unit32 or Int32 value for non-compliant APIs. - if(request.maxResults && typeof request.maxResults === "number"){ - const maxResultsObject = {"value": request.maxResults} - request.maxResults = maxResultsObject + if (request.maxResults && typeof request.maxResults === 'number') { + const maxResultsObject = { value: request.maxResults }; + request.maxResults = maxResultsObject; } let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'project_id': request.projectId?.toString() ?? '', - 'dataset_id': request.datasetId?.toString() ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + project_id: request.projectId?.toString() ?? '', + dataset_id: request.datasetId?.toString() ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.cloud.bigquery.v2.IListTablesRequest, - protos.google.cloud.bigquery.v2.ITableList|null|undefined, - protos.google.cloud.bigquery.v2.IListFormatTable>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.cloud.bigquery.v2.IListTablesRequest, + protos.google.cloud.bigquery.v2.ITableList | null | undefined, + protos.google.cloud.bigquery.v2.IListFormatTable + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listTables values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -955,116 +1208,120 @@ export class TableServiceClient { this._log.info('listTables request %j', request); return this.innerApiCalls .listTables(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.cloud.bigquery.v2.IListFormatTable[], - protos.google.cloud.bigquery.v2.IListTablesRequest|null, - protos.google.cloud.bigquery.v2.ITableList - ]) => { - this._log.info('listTables values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.cloud.bigquery.v2.IListFormatTable[], + protos.google.cloud.bigquery.v2.IListTablesRequest | null, + protos.google.cloud.bigquery.v2.ITableList, + ]) => { + this._log.info('listTables values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listTables`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.projectId - * Required. Project ID of the tables to list - * @param {string} request.datasetId - * Required. Dataset ID of the tables to list - * @param {google.protobuf.UInt32Value} request.maxResults - * The maximum number of results to return in a single response page. - * Leverage the page tokens to iterate through the entire collection. - * @param {string} request.pageToken - * Page token, returned by a previous call, to request the next page of - * results - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.cloud.bigquery.v2.ListFormatTable|ListFormatTable} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `listTablesAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `listTables`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.projectId + * Required. Project ID of the tables to list + * @param {string} request.datasetId + * Required. Dataset ID of the tables to list + * @param {google.protobuf.UInt32Value} request.maxResults + * The maximum number of results to return in a single response page. + * Leverage the page tokens to iterate through the entire collection. + * @param {string} request.pageToken + * Page token, returned by a previous call, to request the next page of + * results + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.cloud.bigquery.v2.ListFormatTable|ListFormatTable} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listTablesAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listTablesStream( - request?: protos.google.cloud.bigquery.v2.IListTablesRequest, - options?: CallOptions): - Transform{ + request?: protos.google.cloud.bigquery.v2.IListTablesRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'project_id': request.projectId?.toString() ?? '', - 'dataset_id': request.datasetId?.toString() ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + project_id: request.projectId?.toString() ?? '', + dataset_id: request.datasetId?.toString() ?? '', + }); const defaultCallSettings = this._defaults['listTables']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listTables stream %j', request); return this.descriptors.page.listTables.createStream( this.innerApiCalls.listTables as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listTables`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.projectId - * Required. Project ID of the tables to list - * @param {string} request.datasetId - * Required. Dataset ID of the tables to list - * @param {google.protobuf.UInt32Value} request.maxResults - * The maximum number of results to return in a single response page. - * Leverage the page tokens to iterate through the entire collection. - * @param {string} request.pageToken - * Page token, returned by a previous call, to request the next page of - * results - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.cloud.bigquery.v2.ListFormatTable|ListFormatTable}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v2/table_service.list_tables.js - * region_tag:bigquery_v2_generated_TableService_ListTables_async - */ + /** + * Equivalent to `listTables`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.projectId + * Required. Project ID of the tables to list + * @param {string} request.datasetId + * Required. Dataset ID of the tables to list + * @param {google.protobuf.UInt32Value} request.maxResults + * The maximum number of results to return in a single response page. + * Leverage the page tokens to iterate through the entire collection. + * @param {string} request.pageToken + * Page token, returned by a previous call, to request the next page of + * results + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.cloud.bigquery.v2.ListFormatTable|ListFormatTable}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v2/table_service.list_tables.js + * region_tag:bigquery_v2_generated_TableService_ListTables_async + */ listTablesAsync( - request?: protos.google.cloud.bigquery.v2.IListTablesRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.cloud.bigquery.v2.IListTablesRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'project_id': request.projectId?.toString() ?? '', - 'dataset_id': request.datasetId?.toString() ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + project_id: request.projectId?.toString() ?? '', + dataset_id: request.datasetId?.toString() ?? '', + }); const defaultCallSettings = this._defaults['listTables']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listTables iterate %j', request); return this.descriptors.page.listTables.asyncIterate( this.innerApiCalls['listTables'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } @@ -1076,7 +1333,7 @@ export class TableServiceClient { */ close(): Promise { if (this.tableServiceStub && !this._terminated) { - return this.tableServiceStub.then(stub => { + return this.tableServiceStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -1084,4 +1341,4 @@ export class TableServiceClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/core/generator/gapic-generator-typescript/baselines/bigquery-v2/system-test/fixtures/sample/src/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/bigquery-v2/system-test/fixtures/sample/src/index.ts.baseline index d6c84c7fbbec..7e717a185e2d 100644 --- a/core/generator/gapic-generator-typescript/baselines/bigquery-v2/system-test/fixtures/sample/src/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/bigquery-v2/system-test/fixtures/sample/src/index.ts.baseline @@ -16,7 +16,15 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -import {DatasetServiceClient, JobServiceClient, ModelServiceClient, ProjectServiceClient, RoutineServiceClient, RowAccessPolicyServiceClient, TableServiceClient} from 'bigquery'; +import { + DatasetServiceClient, + JobServiceClient, + ModelServiceClient, + ProjectServiceClient, + RoutineServiceClient, + RowAccessPolicyServiceClient, + TableServiceClient, +} from 'bigquery'; // check that the client class type name can be used function doStuffWithDatasetServiceClient(client: DatasetServiceClient) { @@ -34,7 +42,9 @@ function doStuffWithProjectServiceClient(client: ProjectServiceClient) { function doStuffWithRoutineServiceClient(client: RoutineServiceClient) { client.close(); } -function doStuffWithRowAccessPolicyServiceClient(client: RowAccessPolicyServiceClient) { +function doStuffWithRowAccessPolicyServiceClient( + client: RowAccessPolicyServiceClient, +) { client.close(); } function doStuffWithTableServiceClient(client: TableServiceClient) { diff --git a/core/generator/gapic-generator-typescript/baselines/bigquery-v2/system-test/install.ts.baseline b/core/generator/gapic-generator-typescript/baselines/bigquery-v2/system-test/install.ts.baseline index f66069aa3940..ccf167042d2e 100644 --- a/core/generator/gapic-generator-typescript/baselines/bigquery-v2/system-test/install.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/bigquery-v2/system-test/install.ts.baseline @@ -16,34 +16,36 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -import {packNTest} from 'pack-n-play'; -import {readFileSync} from 'fs'; -import {describe, it} from 'mocha'; +import { packNTest } from 'pack-n-play'; +import { readFileSync } from 'fs'; +import { describe, it } from 'mocha'; describe('📦 pack-n-play test', () => { - - it('TypeScript code', async function() { + it('TypeScript code', async function () { this.timeout(300000); const options = { packageDir: process.cwd(), sample: { description: 'TypeScript user can use the type definitions', - ts: readFileSync('./system-test/fixtures/sample/src/index.ts').toString() - } + ts: readFileSync( + './system-test/fixtures/sample/src/index.ts', + ).toString(), + }, }; await packNTest(options); }); - it('JavaScript code', async function() { + it('JavaScript code', async function () { this.timeout(300000); const options = { packageDir: process.cwd(), sample: { description: 'JavaScript user can use the library', - cjs: readFileSync('./system-test/fixtures/sample/src/index.js').toString() - } + cjs: readFileSync( + './system-test/fixtures/sample/src/index.js', + ).toString(), + }, }; await packNTest(options); }); - }); diff --git a/core/generator/gapic-generator-typescript/baselines/bigquery-v2/test/gapic_dataset_service_v2.ts.baseline b/core/generator/gapic-generator-typescript/baselines/bigquery-v2/test/gapic_dataset_service_v2.ts.baseline index be0cee887bc6..83588c244ed9 100644 --- a/core/generator/gapic-generator-typescript/baselines/bigquery-v2/test/gapic_dataset_service_v2.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/bigquery-v2/test/gapic_dataset_service_v2.ts.baseline @@ -19,1196 +19,1526 @@ import * as protos from '../protos/protos'; import * as assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as datasetserviceModule from '../src'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; -import {protobuf} from 'google-gax'; +import { protobuf } from 'google-gax'; // Dynamically loaded proto JSON is needed to get the type information // to fill in default values for request objects -const root = protobuf.Root.fromJSON(require('../protos/protos.json')).resolveAll(); +const root = protobuf.Root.fromJSON( + require('../protos/protos.json'), +).resolveAll(); // eslint-disable-next-line @typescript-eslint/no-unused-vars function getTypeDefaultValue(typeName: string, fields: string[]) { - let type = root.lookupType(typeName) as protobuf.Type; - for (const field of fields.slice(0, -1)) { - type = type.fields[field]?.resolvedType as protobuf.Type; - } - return type.fields[fields[fields.length - 1]]?.defaultValue; + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type.fields[field]?.resolvedType as protobuf.Type; + } + return type.fields[fields[fields.length - 1]]?.defaultValue; } function generateSampleMessage(instance: T) { - const filledObject = (instance.constructor as typeof protobuf.Message) - .toObject(instance as protobuf.Message, {defaults: true}); - return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, { defaults: true }); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; } function stubSimpleCall(response?: ResponseType, error?: Error) { - return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); } -function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { - return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +function stubSimpleCallWithCallback( + response?: ResponseType, + error?: Error, +) { + return error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); } -function stubPageStreamingCall(responses?: ResponseType[], error?: Error) { - const pagingStub = sinon.stub(); - if (responses) { - for (let i = 0; i < responses.length; ++i) { - pagingStub.onCall(i).callsArgWith(2, null, responses[i]); - } +function stubPageStreamingCall( + responses?: ResponseType[], + error?: Error, +) { + const pagingStub = sinon.stub(); + if (responses) { + for (let i = 0; i < responses.length; ++i) { + pagingStub.onCall(i).callsArgWith(2, null, responses[i]); } - const transformStub = error ? sinon.stub().callsArgWith(2, error) : pagingStub; - const mockStream = new PassThrough({ - objectMode: true, - transform: transformStub, - }); - // trigger as many responses as needed - if (responses) { - for (let i = 0; i < responses.length; ++i) { - setImmediate(() => { mockStream.write({}); }); - } - setImmediate(() => { mockStream.end(); }); - } else { - setImmediate(() => { mockStream.write({}); }); - setImmediate(() => { mockStream.end(); }); + } + const transformStub = error + ? sinon.stub().callsArgWith(2, error) + : pagingStub; + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + // trigger as many responses as needed + if (responses) { + for (let i = 0; i < responses.length; ++i) { + setImmediate(() => { + mockStream.write({}); + }); } - return sinon.stub().returns(mockStream); + setImmediate(() => { + mockStream.end(); + }); + } else { + setImmediate(() => { + mockStream.write({}); + }); + setImmediate(() => { + mockStream.end(); + }); + } + return sinon.stub().returns(mockStream); } -function stubAsyncIterationCall(responses?: ResponseType[], error?: Error) { - let counter = 0; - const asyncIterable = { - [Symbol.asyncIterator]() { - return { - async next() { - if (error) { - return Promise.reject(error); - } - if (counter >= responses!.length) { - return Promise.resolve({done: true, value: undefined}); - } - return Promise.resolve({done: false, value: responses![counter++]}); - } - }; - } - }; - return sinon.stub().returns(asyncIterable); +function stubAsyncIterationCall( + responses?: ResponseType[], + error?: Error, +) { + let counter = 0; + const asyncIterable = { + [Symbol.asyncIterator]() { + return { + async next() { + if (error) { + return Promise.reject(error); + } + if (counter >= responses!.length) { + return Promise.resolve({ done: true, value: undefined }); + } + return Promise.resolve({ done: false, value: responses![counter++] }); + }, + }; + }, + }; + return sinon.stub().returns(asyncIterable); } describe('v2.DatasetServiceClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new datasetserviceModule.v2.DatasetServiceClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'bigquery.googleapis.com'); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new datasetserviceModule.v2.DatasetServiceClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'bigquery.googleapis.com'); + }); - it('has universeDomain', () => { - const client = new datasetserviceModule.v2.DatasetServiceClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); + it('has universeDomain', () => { + const client = new datasetserviceModule.v2.DatasetServiceClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - it('throws DeprecationWarning if static servicePath is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const servicePath = datasetserviceModule.v2.DatasetServiceClient.servicePath; - assert.strictEqual(servicePath, 'bigquery.googleapis.com'); - assert(stub.called); - stub.restore(); - }); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = + datasetserviceModule.v2.DatasetServiceClient.servicePath; + assert.strictEqual(servicePath, 'bigquery.googleapis.com'); + assert(stub.called); + stub.restore(); + }); - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = datasetserviceModule.v2.DatasetServiceClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'bigquery.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new datasetserviceModule.v2.DatasetServiceClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'bigquery.example.com'); + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + datasetserviceModule.v2.DatasetServiceClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'bigquery.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = new datasetserviceModule.v2.DatasetServiceClient({ + universeDomain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'bigquery.example.com'); + }); + + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = new datasetserviceModule.v2.DatasetServiceClient({ + universe_domain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'bigquery.example.com'); + }); + + if (typeof process === 'object' && 'env' in process) { + describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { + it('sets apiEndpoint from environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new datasetserviceModule.v2.DatasetServiceClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'bigquery.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new datasetserviceModule.v2.DatasetServiceClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'bigquery.example.com'); + it('value configured in code has priority over environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new datasetserviceModule.v2.DatasetServiceClient({ + universeDomain: 'configured.example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'bigquery.configured.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } + }); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new datasetserviceModule.v2.DatasetServiceClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); + }); - if (typeof process === 'object' && 'env' in process) { - describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { - it('sets apiEndpoint from environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new datasetserviceModule.v2.DatasetServiceClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'bigquery.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); + it('has port', () => { + const port = datasetserviceModule.v2.DatasetServiceClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('value configured in code has priority over environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new datasetserviceModule.v2.DatasetServiceClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'bigquery.configured.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { new datasetserviceModule.v2.DatasetServiceClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); + it('should create a client with no option', () => { + const client = new datasetserviceModule.v2.DatasetServiceClient(); + assert(client); + }); - it('has port', () => { - const port = datasetserviceModule.v2.DatasetServiceClient.port; - assert(port); - assert(typeof port === 'number'); - }); + it('should create a client with gRPC fallback', () => { + const client = new datasetserviceModule.v2.DatasetServiceClient({ + fallback: true, + }); + assert(client); + }); - it('should create a client with no option', () => { - const client = new datasetserviceModule.v2.DatasetServiceClient(); - assert(client); - }); + it('has initialize method and supports deferred initialization', async () => { + const client = new datasetserviceModule.v2.DatasetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.datasetServiceStub, undefined); + await client.initialize(); + assert(client.datasetServiceStub); + }); - it('should create a client with gRPC fallback', () => { - const client = new datasetserviceModule.v2.DatasetServiceClient({ - fallback: true, - }); - assert(client); + it('has close method for the initialized client', (done) => { + const client = new datasetserviceModule.v2.DatasetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.datasetServiceStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('has initialize method and supports deferred initialization', async () => { - const client = new datasetserviceModule.v2.DatasetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.datasetServiceStub, undefined); - await client.initialize(); - assert(client.datasetServiceStub); + it('has close method for the non-initialized client', (done) => { + const client = new datasetserviceModule.v2.DatasetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.datasetServiceStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('has close method for the initialized client', done => { - const client = new datasetserviceModule.v2.DatasetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.datasetServiceStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new datasetserviceModule.v2.DatasetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + }); - it('has close method for the non-initialized client', done => { - const client = new datasetserviceModule.v2.DatasetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.datasetServiceStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new datasetserviceModule.v2.DatasetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new datasetserviceModule.v2.DatasetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); - }); + describe('getDataset', () => { + it('invokes getDataset without error', async () => { + const client = new datasetserviceModule.v2.DatasetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.GetDatasetRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetDatasetRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetDatasetRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.bigquery.v2.Dataset(), + ); + client.innerApiCalls.getDataset = stubSimpleCall(expectedResponse); + const [response] = await client.getDataset(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getDataset as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getDataset as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new datasetserviceModule.v2.DatasetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId((err?: Error|null, projectId?: string|null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } - }); - }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); - }); + it('invokes getDataset without error using callback', async () => { + const client = new datasetserviceModule.v2.DatasetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.GetDatasetRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetDatasetRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetDatasetRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.bigquery.v2.Dataset(), + ); + client.innerApiCalls.getDataset = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getDataset( + request, + ( + err?: Error | null, + result?: protos.google.cloud.bigquery.v2.IDataset | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getDataset as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getDataset as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('getDataset', () => { - it('invokes getDataset without error', async () => { - const client = new datasetserviceModule.v2.DatasetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.GetDatasetRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetDatasetRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetDatasetRequest', ['datasetId']); - request.datasetId = defaultValue2; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.bigquery.v2.Dataset() - ); - client.innerApiCalls.getDataset = stubSimpleCall(expectedResponse); - const [response] = await client.getDataset(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getDataset as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getDataset as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getDataset with error', async () => { + const client = new datasetserviceModule.v2.DatasetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.GetDatasetRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetDatasetRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetDatasetRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getDataset = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getDataset(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getDataset as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getDataset as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getDataset without error using callback', async () => { - const client = new datasetserviceModule.v2.DatasetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.GetDatasetRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetDatasetRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetDatasetRequest', ['datasetId']); - request.datasetId = defaultValue2; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.bigquery.v2.Dataset() - ); - client.innerApiCalls.getDataset = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getDataset( - request, - (err?: Error|null, result?: protos.google.cloud.bigquery.v2.IDataset|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getDataset as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getDataset as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getDataset with closed client', async () => { + const client = new datasetserviceModule.v2.DatasetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.GetDatasetRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetDatasetRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetDatasetRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getDataset(request), expectedError); + }); + }); - it('invokes getDataset with error', async () => { - const client = new datasetserviceModule.v2.DatasetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.GetDatasetRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetDatasetRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetDatasetRequest', ['datasetId']); - request.datasetId = defaultValue2; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getDataset = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getDataset(request), expectedError); - const actualRequest = (client.innerApiCalls.getDataset as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getDataset as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + describe('insertDataset', () => { + it('invokes insertDataset without error', async () => { + const client = new datasetserviceModule.v2.DatasetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.InsertDatasetRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.InsertDatasetRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.bigquery.v2.Dataset(), + ); + client.innerApiCalls.insertDataset = stubSimpleCall(expectedResponse); + const [response] = await client.insertDataset(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.insertDataset as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.insertDataset as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getDataset with closed client', async () => { - const client = new datasetserviceModule.v2.DatasetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.GetDatasetRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetDatasetRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetDatasetRequest', ['datasetId']); - request.datasetId = defaultValue2; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getDataset(request), expectedError); - }); + it('invokes insertDataset without error using callback', async () => { + const client = new datasetserviceModule.v2.DatasetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.InsertDatasetRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.InsertDatasetRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.bigquery.v2.Dataset(), + ); + client.innerApiCalls.insertDataset = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.insertDataset( + request, + ( + err?: Error | null, + result?: protos.google.cloud.bigquery.v2.IDataset | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.insertDataset as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.insertDataset as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('insertDataset', () => { - it('invokes insertDataset without error', async () => { - const client = new datasetserviceModule.v2.DatasetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.InsertDatasetRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.InsertDatasetRequest', ['projectId']); - request.projectId = defaultValue1; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.bigquery.v2.Dataset() - ); - client.innerApiCalls.insertDataset = stubSimpleCall(expectedResponse); - const [response] = await client.insertDataset(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.insertDataset as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.insertDataset as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes insertDataset with error', async () => { + const client = new datasetserviceModule.v2.DatasetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.InsertDatasetRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.InsertDatasetRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.insertDataset = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.insertDataset(request), expectedError); + const actualRequest = ( + client.innerApiCalls.insertDataset as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.insertDataset as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes insertDataset without error using callback', async () => { - const client = new datasetserviceModule.v2.DatasetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.InsertDatasetRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.InsertDatasetRequest', ['projectId']); - request.projectId = defaultValue1; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.bigquery.v2.Dataset() - ); - client.innerApiCalls.insertDataset = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.insertDataset( - request, - (err?: Error|null, result?: protos.google.cloud.bigquery.v2.IDataset|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.insertDataset as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.insertDataset as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes insertDataset with closed client', async () => { + const client = new datasetserviceModule.v2.DatasetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.InsertDatasetRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.InsertDatasetRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.insertDataset(request), expectedError); + }); + }); - it('invokes insertDataset with error', async () => { - const client = new datasetserviceModule.v2.DatasetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.InsertDatasetRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.InsertDatasetRequest', ['projectId']); - request.projectId = defaultValue1; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.insertDataset = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.insertDataset(request), expectedError); - const actualRequest = (client.innerApiCalls.insertDataset as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.insertDataset as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + describe('patchDataset', () => { + it('invokes patchDataset without error', async () => { + const client = new datasetserviceModule.v2.DatasetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.UpdateOrPatchDatasetRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.UpdateOrPatchDatasetRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.UpdateOrPatchDatasetRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.bigquery.v2.Dataset(), + ); + client.innerApiCalls.patchDataset = stubSimpleCall(expectedResponse); + const [response] = await client.patchDataset(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.patchDataset as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.patchDataset as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes insertDataset with closed client', async () => { - const client = new datasetserviceModule.v2.DatasetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.InsertDatasetRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.InsertDatasetRequest', ['projectId']); - request.projectId = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.insertDataset(request), expectedError); - }); + it('invokes patchDataset without error using callback', async () => { + const client = new datasetserviceModule.v2.DatasetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.UpdateOrPatchDatasetRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.UpdateOrPatchDatasetRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.UpdateOrPatchDatasetRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.bigquery.v2.Dataset(), + ); + client.innerApiCalls.patchDataset = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.patchDataset( + request, + ( + err?: Error | null, + result?: protos.google.cloud.bigquery.v2.IDataset | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.patchDataset as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.patchDataset as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('patchDataset', () => { - it('invokes patchDataset without error', async () => { - const client = new datasetserviceModule.v2.DatasetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.UpdateOrPatchDatasetRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.UpdateOrPatchDatasetRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.UpdateOrPatchDatasetRequest', ['datasetId']); - request.datasetId = defaultValue2; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.bigquery.v2.Dataset() - ); - client.innerApiCalls.patchDataset = stubSimpleCall(expectedResponse); - const [response] = await client.patchDataset(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.patchDataset as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.patchDataset as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes patchDataset with error', async () => { + const client = new datasetserviceModule.v2.DatasetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.UpdateOrPatchDatasetRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.UpdateOrPatchDatasetRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.UpdateOrPatchDatasetRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.patchDataset = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.patchDataset(request), expectedError); + const actualRequest = ( + client.innerApiCalls.patchDataset as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.patchDataset as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes patchDataset without error using callback', async () => { - const client = new datasetserviceModule.v2.DatasetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.UpdateOrPatchDatasetRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.UpdateOrPatchDatasetRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.UpdateOrPatchDatasetRequest', ['datasetId']); - request.datasetId = defaultValue2; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.bigquery.v2.Dataset() - ); - client.innerApiCalls.patchDataset = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.patchDataset( - request, - (err?: Error|null, result?: protos.google.cloud.bigquery.v2.IDataset|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.patchDataset as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.patchDataset as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes patchDataset with closed client', async () => { + const client = new datasetserviceModule.v2.DatasetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.UpdateOrPatchDatasetRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.UpdateOrPatchDatasetRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.UpdateOrPatchDatasetRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.patchDataset(request), expectedError); + }); + }); - it('invokes patchDataset with error', async () => { - const client = new datasetserviceModule.v2.DatasetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.UpdateOrPatchDatasetRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.UpdateOrPatchDatasetRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.UpdateOrPatchDatasetRequest', ['datasetId']); - request.datasetId = defaultValue2; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.patchDataset = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.patchDataset(request), expectedError); - const actualRequest = (client.innerApiCalls.patchDataset as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.patchDataset as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + describe('updateDataset', () => { + it('invokes updateDataset without error', async () => { + const client = new datasetserviceModule.v2.DatasetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.UpdateOrPatchDatasetRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.UpdateOrPatchDatasetRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.UpdateOrPatchDatasetRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.bigquery.v2.Dataset(), + ); + client.innerApiCalls.updateDataset = stubSimpleCall(expectedResponse); + const [response] = await client.updateDataset(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateDataset as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateDataset as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes patchDataset with closed client', async () => { - const client = new datasetserviceModule.v2.DatasetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.UpdateOrPatchDatasetRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.UpdateOrPatchDatasetRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.UpdateOrPatchDatasetRequest', ['datasetId']); - request.datasetId = defaultValue2; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.patchDataset(request), expectedError); - }); + it('invokes updateDataset without error using callback', async () => { + const client = new datasetserviceModule.v2.DatasetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.UpdateOrPatchDatasetRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.UpdateOrPatchDatasetRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.UpdateOrPatchDatasetRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.bigquery.v2.Dataset(), + ); + client.innerApiCalls.updateDataset = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateDataset( + request, + ( + err?: Error | null, + result?: protos.google.cloud.bigquery.v2.IDataset | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateDataset as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateDataset as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('updateDataset', () => { - it('invokes updateDataset without error', async () => { - const client = new datasetserviceModule.v2.DatasetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.UpdateOrPatchDatasetRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.UpdateOrPatchDatasetRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.UpdateOrPatchDatasetRequest', ['datasetId']); - request.datasetId = defaultValue2; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.bigquery.v2.Dataset() - ); - client.innerApiCalls.updateDataset = stubSimpleCall(expectedResponse); - const [response] = await client.updateDataset(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateDataset as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateDataset as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateDataset with error', async () => { + const client = new datasetserviceModule.v2.DatasetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.UpdateOrPatchDatasetRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.UpdateOrPatchDatasetRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.UpdateOrPatchDatasetRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateDataset = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.updateDataset(request), expectedError); + const actualRequest = ( + client.innerApiCalls.updateDataset as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateDataset as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateDataset without error using callback', async () => { - const client = new datasetserviceModule.v2.DatasetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.UpdateOrPatchDatasetRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.UpdateOrPatchDatasetRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.UpdateOrPatchDatasetRequest', ['datasetId']); - request.datasetId = defaultValue2; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.bigquery.v2.Dataset() - ); - client.innerApiCalls.updateDataset = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateDataset( - request, - (err?: Error|null, result?: protos.google.cloud.bigquery.v2.IDataset|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateDataset as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateDataset as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateDataset with closed client', async () => { + const client = new datasetserviceModule.v2.DatasetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.UpdateOrPatchDatasetRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.UpdateOrPatchDatasetRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.UpdateOrPatchDatasetRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.updateDataset(request), expectedError); + }); + }); - it('invokes updateDataset with error', async () => { - const client = new datasetserviceModule.v2.DatasetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.UpdateOrPatchDatasetRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.UpdateOrPatchDatasetRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.UpdateOrPatchDatasetRequest', ['datasetId']); - request.datasetId = defaultValue2; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateDataset = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateDataset(request), expectedError); - const actualRequest = (client.innerApiCalls.updateDataset as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateDataset as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + describe('deleteDataset', () => { + it('invokes deleteDataset without error', async () => { + const client = new datasetserviceModule.v2.DatasetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.DeleteDatasetRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.DeleteDatasetRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.DeleteDatasetRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteDataset = stubSimpleCall(expectedResponse); + const [response] = await client.deleteDataset(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteDataset as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteDataset as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateDataset with closed client', async () => { - const client = new datasetserviceModule.v2.DatasetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.UpdateOrPatchDatasetRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.UpdateOrPatchDatasetRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.UpdateOrPatchDatasetRequest', ['datasetId']); - request.datasetId = defaultValue2; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateDataset(request), expectedError); - }); + it('invokes deleteDataset without error using callback', async () => { + const client = new datasetserviceModule.v2.DatasetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.DeleteDatasetRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.DeleteDatasetRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.DeleteDatasetRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteDataset = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteDataset( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteDataset as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteDataset as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('deleteDataset', () => { - it('invokes deleteDataset without error', async () => { - const client = new datasetserviceModule.v2.DatasetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.DeleteDatasetRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.DeleteDatasetRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.DeleteDatasetRequest', ['datasetId']); - request.datasetId = defaultValue2; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteDataset = stubSimpleCall(expectedResponse); - const [response] = await client.deleteDataset(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteDataset as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteDataset as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteDataset with error', async () => { + const client = new datasetserviceModule.v2.DatasetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.DeleteDatasetRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.DeleteDatasetRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.DeleteDatasetRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteDataset = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.deleteDataset(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteDataset as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteDataset as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteDataset without error using callback', async () => { - const client = new datasetserviceModule.v2.DatasetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.DeleteDatasetRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.DeleteDatasetRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.DeleteDatasetRequest', ['datasetId']); - request.datasetId = defaultValue2; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteDataset = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteDataset( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteDataset as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteDataset as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteDataset with closed client', async () => { + const client = new datasetserviceModule.v2.DatasetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.DeleteDatasetRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.DeleteDatasetRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.DeleteDatasetRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.deleteDataset(request), expectedError); + }); + }); - it('invokes deleteDataset with error', async () => { - const client = new datasetserviceModule.v2.DatasetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.DeleteDatasetRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.DeleteDatasetRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.DeleteDatasetRequest', ['datasetId']); - request.datasetId = defaultValue2; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteDataset = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteDataset(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteDataset as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteDataset as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + describe('undeleteDataset', () => { + it('invokes undeleteDataset without error', async () => { + const client = new datasetserviceModule.v2.DatasetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.UndeleteDatasetRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.UndeleteDatasetRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.UndeleteDatasetRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.bigquery.v2.Dataset(), + ); + client.innerApiCalls.undeleteDataset = stubSimpleCall(expectedResponse); + const [response] = await client.undeleteDataset(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.undeleteDataset as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.undeleteDataset as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteDataset with closed client', async () => { - const client = new datasetserviceModule.v2.DatasetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.DeleteDatasetRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.DeleteDatasetRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.DeleteDatasetRequest', ['datasetId']); - request.datasetId = defaultValue2; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteDataset(request), expectedError); - }); + it('invokes undeleteDataset without error using callback', async () => { + const client = new datasetserviceModule.v2.DatasetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.UndeleteDatasetRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.UndeleteDatasetRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.UndeleteDatasetRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.bigquery.v2.Dataset(), + ); + client.innerApiCalls.undeleteDataset = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.undeleteDataset( + request, + ( + err?: Error | null, + result?: protos.google.cloud.bigquery.v2.IDataset | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.undeleteDataset as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.undeleteDataset as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('undeleteDataset', () => { - it('invokes undeleteDataset without error', async () => { - const client = new datasetserviceModule.v2.DatasetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.UndeleteDatasetRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.UndeleteDatasetRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.UndeleteDatasetRequest', ['datasetId']); - request.datasetId = defaultValue2; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.bigquery.v2.Dataset() - ); - client.innerApiCalls.undeleteDataset = stubSimpleCall(expectedResponse); - const [response] = await client.undeleteDataset(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.undeleteDataset as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.undeleteDataset as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes undeleteDataset with error', async () => { + const client = new datasetserviceModule.v2.DatasetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.UndeleteDatasetRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.UndeleteDatasetRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.UndeleteDatasetRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.undeleteDataset = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.undeleteDataset(request), expectedError); + const actualRequest = ( + client.innerApiCalls.undeleteDataset as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.undeleteDataset as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes undeleteDataset without error using callback', async () => { - const client = new datasetserviceModule.v2.DatasetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.UndeleteDatasetRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.UndeleteDatasetRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.UndeleteDatasetRequest', ['datasetId']); - request.datasetId = defaultValue2; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.bigquery.v2.Dataset() - ); - client.innerApiCalls.undeleteDataset = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.undeleteDataset( - request, - (err?: Error|null, result?: protos.google.cloud.bigquery.v2.IDataset|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.undeleteDataset as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.undeleteDataset as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes undeleteDataset with closed client', async () => { + const client = new datasetserviceModule.v2.DatasetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.UndeleteDatasetRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.UndeleteDatasetRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.UndeleteDatasetRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.undeleteDataset(request), expectedError); + }); + }); - it('invokes undeleteDataset with error', async () => { - const client = new datasetserviceModule.v2.DatasetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.UndeleteDatasetRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.UndeleteDatasetRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.UndeleteDatasetRequest', ['datasetId']); - request.datasetId = defaultValue2; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.undeleteDataset = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.undeleteDataset(request), expectedError); - const actualRequest = (client.innerApiCalls.undeleteDataset as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.undeleteDataset as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + describe('listDatasets', () => { + it('invokes listDatasets without error', async () => { + const client = new datasetserviceModule.v2.DatasetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListDatasetsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListDatasetsRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListFormatDataset(), + ), + generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListFormatDataset(), + ), + generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListFormatDataset(), + ), + ]; + client.innerApiCalls.listDatasets = stubSimpleCall(expectedResponse); + const [response] = await client.listDatasets(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listDatasets as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listDatasets as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes undeleteDataset with closed client', async () => { - const client = new datasetserviceModule.v2.DatasetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.UndeleteDatasetRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.UndeleteDatasetRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.UndeleteDatasetRequest', ['datasetId']); - request.datasetId = defaultValue2; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.undeleteDataset(request), expectedError); - }); + it('invokes listDatasets without error using callback', async () => { + const client = new datasetserviceModule.v2.DatasetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListDatasetsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListDatasetsRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListFormatDataset(), + ), + generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListFormatDataset(), + ), + generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListFormatDataset(), + ), + ]; + client.innerApiCalls.listDatasets = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listDatasets( + request, + ( + err?: Error | null, + result?: + | protos.google.cloud.bigquery.v2.IListFormatDataset[] + | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listDatasets as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listDatasets as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('listDatasets', () => { - it('invokes listDatasets without error', async () => { - const client = new datasetserviceModule.v2.DatasetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.ListDatasetsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListDatasetsRequest', ['projectId']); - request.projectId = defaultValue1; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.bigquery.v2.ListFormatDataset()), - generateSampleMessage(new protos.google.cloud.bigquery.v2.ListFormatDataset()), - generateSampleMessage(new protos.google.cloud.bigquery.v2.ListFormatDataset()), - ]; - client.innerApiCalls.listDatasets = stubSimpleCall(expectedResponse); - const [response] = await client.listDatasets(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listDatasets as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listDatasets as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listDatasets with error', async () => { + const client = new datasetserviceModule.v2.DatasetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListDatasetsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListDatasetsRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listDatasets = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listDatasets(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listDatasets as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listDatasets as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listDatasets without error using callback', async () => { - const client = new datasetserviceModule.v2.DatasetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.ListDatasetsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListDatasetsRequest', ['projectId']); - request.projectId = defaultValue1; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.bigquery.v2.ListFormatDataset()), - generateSampleMessage(new protos.google.cloud.bigquery.v2.ListFormatDataset()), - generateSampleMessage(new protos.google.cloud.bigquery.v2.ListFormatDataset()), - ]; - client.innerApiCalls.listDatasets = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listDatasets( - request, - (err?: Error|null, result?: protos.google.cloud.bigquery.v2.IListFormatDataset[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listDatasets as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listDatasets as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes listDatasetsStream without error', async () => { + const client = new datasetserviceModule.v2.DatasetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListDatasetsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListDatasetsRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListFormatDataset(), + ), + generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListFormatDataset(), + ), + generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListFormatDataset(), + ), + ]; + client.descriptors.page.listDatasets.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listDatasetsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.cloud.bigquery.v2.ListFormatDataset[] = + []; + stream.on( + 'data', + (response: protos.google.cloud.bigquery.v2.ListFormatDataset) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); }); - - it('invokes listDatasets with error', async () => { - const client = new datasetserviceModule.v2.DatasetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.ListDatasetsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListDatasetsRequest', ['projectId']); - request.projectId = defaultValue1; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listDatasets = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listDatasets(request), expectedError); - const actualRequest = (client.innerApiCalls.listDatasets as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listDatasets as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + stream.on('error', (err: Error) => { + reject(err); }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listDatasets.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listDatasets, request), + ); + assert( + (client.descriptors.page.listDatasets.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('invokes listDatasetsStream without error', async () => { - const client = new datasetserviceModule.v2.DatasetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.ListDatasetsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListDatasetsRequest', ['projectId']); - request.projectId = defaultValue1; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.bigquery.v2.ListFormatDataset()), - generateSampleMessage(new protos.google.cloud.bigquery.v2.ListFormatDataset()), - generateSampleMessage(new protos.google.cloud.bigquery.v2.ListFormatDataset()), - ]; - client.descriptors.page.listDatasets.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listDatasetsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.cloud.bigquery.v2.ListFormatDataset[] = []; - stream.on('data', (response: protos.google.cloud.bigquery.v2.ListFormatDataset) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.listDatasets.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listDatasets, request)); - assert( - (client.descriptors.page.listDatasets.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); + it('invokes listDatasetsStream with error', async () => { + const client = new datasetserviceModule.v2.DatasetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListDatasetsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListDatasetsRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listDatasets.createStream = stubPageStreamingCall( + undefined, + expectedError, + ); + const stream = client.listDatasetsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.cloud.bigquery.v2.ListFormatDataset[] = + []; + stream.on( + 'data', + (response: protos.google.cloud.bigquery.v2.ListFormatDataset) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); }); - - it('invokes listDatasetsStream with error', async () => { - const client = new datasetserviceModule.v2.DatasetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.ListDatasetsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListDatasetsRequest', ['projectId']); - request.projectId = defaultValue1; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listDatasets.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listDatasetsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.cloud.bigquery.v2.ListFormatDataset[] = []; - stream.on('data', (response: protos.google.cloud.bigquery.v2.ListFormatDataset) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listDatasets.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listDatasets, request)); - assert( - (client.descriptors.page.listDatasets.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); + stream.on('error', (err: Error) => { + reject(err); }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listDatasets.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listDatasets, request), + ); + assert( + (client.descriptors.page.listDatasets.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('uses async iteration with listDatasets without error', async () => { - const client = new datasetserviceModule.v2.DatasetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.ListDatasetsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListDatasetsRequest', ['projectId']); - request.projectId = defaultValue1; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.bigquery.v2.ListFormatDataset()), - generateSampleMessage(new protos.google.cloud.bigquery.v2.ListFormatDataset()), - generateSampleMessage(new protos.google.cloud.bigquery.v2.ListFormatDataset()), - ]; - client.descriptors.page.listDatasets.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.cloud.bigquery.v2.IListFormatDataset[] = []; - const iterable = client.listDatasetsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listDatasets.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listDatasets.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listDatasets without error', async () => { + const client = new datasetserviceModule.v2.DatasetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListDatasetsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListDatasetsRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListFormatDataset(), + ), + generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListFormatDataset(), + ), + generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListFormatDataset(), + ), + ]; + client.descriptors.page.listDatasets.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.cloud.bigquery.v2.IListFormatDataset[] = + []; + const iterable = client.listDatasetsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listDatasets.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listDatasets.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('uses async iteration with listDatasets with error', async () => { - const client = new datasetserviceModule.v2.DatasetServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.ListDatasetsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListDatasetsRequest', ['projectId']); - request.projectId = defaultValue1; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listDatasets.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listDatasetsAsync(request); - await assert.rejects(async () => { - const responses: protos.google.cloud.bigquery.v2.IListFormatDataset[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listDatasets.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listDatasets.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listDatasets with error', async () => { + const client = new datasetserviceModule.v2.DatasetServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListDatasetsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListDatasetsRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listDatasets.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listDatasetsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.cloud.bigquery.v2.IListFormatDataset[] = + []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listDatasets.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listDatasets.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); }); + }); }); diff --git a/core/generator/gapic-generator-typescript/baselines/bigquery-v2/test/gapic_job_service_v2.ts.baseline b/core/generator/gapic-generator-typescript/baselines/bigquery-v2/test/gapic_job_service_v2.ts.baseline index 0799090ee38c..e575dcb71d04 100644 --- a/core/generator/gapic-generator-typescript/baselines/bigquery-v2/test/gapic_job_service_v2.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/bigquery-v2/test/gapic_job_service_v2.ts.baseline @@ -19,1184 +19,1476 @@ import * as protos from '../protos/protos'; import * as assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as jobserviceModule from '../src'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; -import {protobuf} from 'google-gax'; +import { protobuf } from 'google-gax'; // Dynamically loaded proto JSON is needed to get the type information // to fill in default values for request objects -const root = protobuf.Root.fromJSON(require('../protos/protos.json')).resolveAll(); +const root = protobuf.Root.fromJSON( + require('../protos/protos.json'), +).resolveAll(); // eslint-disable-next-line @typescript-eslint/no-unused-vars function getTypeDefaultValue(typeName: string, fields: string[]) { - let type = root.lookupType(typeName) as protobuf.Type; - for (const field of fields.slice(0, -1)) { - type = type.fields[field]?.resolvedType as protobuf.Type; - } - return type.fields[fields[fields.length - 1]]?.defaultValue; + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type.fields[field]?.resolvedType as protobuf.Type; + } + return type.fields[fields[fields.length - 1]]?.defaultValue; } function generateSampleMessage(instance: T) { - const filledObject = (instance.constructor as typeof protobuf.Message) - .toObject(instance as protobuf.Message, {defaults: true}); - return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, { defaults: true }); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; } function stubSimpleCall(response?: ResponseType, error?: Error) { - return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); } -function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { - return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +function stubSimpleCallWithCallback( + response?: ResponseType, + error?: Error, +) { + return error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); } -function stubPageStreamingCall(responses?: ResponseType[], error?: Error) { - const pagingStub = sinon.stub(); - if (responses) { - for (let i = 0; i < responses.length; ++i) { - pagingStub.onCall(i).callsArgWith(2, null, responses[i]); - } +function stubPageStreamingCall( + responses?: ResponseType[], + error?: Error, +) { + const pagingStub = sinon.stub(); + if (responses) { + for (let i = 0; i < responses.length; ++i) { + pagingStub.onCall(i).callsArgWith(2, null, responses[i]); } - const transformStub = error ? sinon.stub().callsArgWith(2, error) : pagingStub; - const mockStream = new PassThrough({ - objectMode: true, - transform: transformStub, - }); - // trigger as many responses as needed - if (responses) { - for (let i = 0; i < responses.length; ++i) { - setImmediate(() => { mockStream.write({}); }); - } - setImmediate(() => { mockStream.end(); }); - } else { - setImmediate(() => { mockStream.write({}); }); - setImmediate(() => { mockStream.end(); }); + } + const transformStub = error + ? sinon.stub().callsArgWith(2, error) + : pagingStub; + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + // trigger as many responses as needed + if (responses) { + for (let i = 0; i < responses.length; ++i) { + setImmediate(() => { + mockStream.write({}); + }); } - return sinon.stub().returns(mockStream); + setImmediate(() => { + mockStream.end(); + }); + } else { + setImmediate(() => { + mockStream.write({}); + }); + setImmediate(() => { + mockStream.end(); + }); + } + return sinon.stub().returns(mockStream); } -function stubAsyncIterationCall(responses?: ResponseType[], error?: Error) { - let counter = 0; - const asyncIterable = { - [Symbol.asyncIterator]() { - return { - async next() { - if (error) { - return Promise.reject(error); - } - if (counter >= responses!.length) { - return Promise.resolve({done: true, value: undefined}); - } - return Promise.resolve({done: false, value: responses![counter++]}); - } - }; - } - }; - return sinon.stub().returns(asyncIterable); +function stubAsyncIterationCall( + responses?: ResponseType[], + error?: Error, +) { + let counter = 0; + const asyncIterable = { + [Symbol.asyncIterator]() { + return { + async next() { + if (error) { + return Promise.reject(error); + } + if (counter >= responses!.length) { + return Promise.resolve({ done: true, value: undefined }); + } + return Promise.resolve({ done: false, value: responses![counter++] }); + }, + }; + }, + }; + return sinon.stub().returns(asyncIterable); } describe('v2.JobServiceClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new jobserviceModule.v2.JobServiceClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'bigquery.googleapis.com'); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new jobserviceModule.v2.JobServiceClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'bigquery.googleapis.com'); + }); - it('has universeDomain', () => { - const client = new jobserviceModule.v2.JobServiceClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); + it('has universeDomain', () => { + const client = new jobserviceModule.v2.JobServiceClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - it('throws DeprecationWarning if static servicePath is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const servicePath = jobserviceModule.v2.JobServiceClient.servicePath; - assert.strictEqual(servicePath, 'bigquery.googleapis.com'); - assert(stub.called); - stub.restore(); - }); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = jobserviceModule.v2.JobServiceClient.servicePath; + assert.strictEqual(servicePath, 'bigquery.googleapis.com'); + assert(stub.called); + stub.restore(); + }); - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = jobserviceModule.v2.JobServiceClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'bigquery.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new jobserviceModule.v2.JobServiceClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'bigquery.example.com'); + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = jobserviceModule.v2.JobServiceClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'bigquery.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = new jobserviceModule.v2.JobServiceClient({ + universeDomain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'bigquery.example.com'); + }); + + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = new jobserviceModule.v2.JobServiceClient({ + universe_domain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'bigquery.example.com'); + }); + + if (typeof process === 'object' && 'env' in process) { + describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { + it('sets apiEndpoint from environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new jobserviceModule.v2.JobServiceClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'bigquery.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new jobserviceModule.v2.JobServiceClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'bigquery.example.com'); + it('value configured in code has priority over environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new jobserviceModule.v2.JobServiceClient({ + universeDomain: 'configured.example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'bigquery.configured.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } + }); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new jobserviceModule.v2.JobServiceClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); + }); - if (typeof process === 'object' && 'env' in process) { - describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { - it('sets apiEndpoint from environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new jobserviceModule.v2.JobServiceClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'bigquery.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); + it('has port', () => { + const port = jobserviceModule.v2.JobServiceClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('value configured in code has priority over environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new jobserviceModule.v2.JobServiceClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'bigquery.configured.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { new jobserviceModule.v2.JobServiceClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); + it('should create a client with no option', () => { + const client = new jobserviceModule.v2.JobServiceClient(); + assert(client); + }); - it('has port', () => { - const port = jobserviceModule.v2.JobServiceClient.port; - assert(port); - assert(typeof port === 'number'); - }); + it('should create a client with gRPC fallback', () => { + const client = new jobserviceModule.v2.JobServiceClient({ + fallback: true, + }); + assert(client); + }); - it('should create a client with no option', () => { - const client = new jobserviceModule.v2.JobServiceClient(); - assert(client); - }); + it('has initialize method and supports deferred initialization', async () => { + const client = new jobserviceModule.v2.JobServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.jobServiceStub, undefined); + await client.initialize(); + assert(client.jobServiceStub); + }); - it('should create a client with gRPC fallback', () => { - const client = new jobserviceModule.v2.JobServiceClient({ - fallback: true, - }); - assert(client); + it('has close method for the initialized client', (done) => { + const client = new jobserviceModule.v2.JobServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.jobServiceStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('has initialize method and supports deferred initialization', async () => { - const client = new jobserviceModule.v2.JobServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.jobServiceStub, undefined); - await client.initialize(); - assert(client.jobServiceStub); + it('has close method for the non-initialized client', (done) => { + const client = new jobserviceModule.v2.JobServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.jobServiceStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('has close method for the initialized client', done => { - const client = new jobserviceModule.v2.JobServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.jobServiceStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new jobserviceModule.v2.JobServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + }); - it('has close method for the non-initialized client', done => { - const client = new jobserviceModule.v2.JobServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.jobServiceStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new jobserviceModule.v2.JobServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new jobserviceModule.v2.JobServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); - }); + describe('cancelJob', () => { + it('invokes cancelJob without error', async () => { + const client = new jobserviceModule.v2.JobServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.CancelJobRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.CancelJobRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.CancelJobRequest', + ['jobId'], + ); + request.jobId = defaultValue2; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&job_id=${defaultValue2 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.bigquery.v2.JobCancelResponse(), + ); + client.innerApiCalls.cancelJob = stubSimpleCall(expectedResponse); + const [response] = await client.cancelJob(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.cancelJob as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.cancelJob as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new jobserviceModule.v2.JobServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId((err?: Error|null, projectId?: string|null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } - }); - }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); - }); + it('invokes cancelJob without error using callback', async () => { + const client = new jobserviceModule.v2.JobServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.CancelJobRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.CancelJobRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.CancelJobRequest', + ['jobId'], + ); + request.jobId = defaultValue2; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&job_id=${defaultValue2 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.bigquery.v2.JobCancelResponse(), + ); + client.innerApiCalls.cancelJob = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.cancelJob( + request, + ( + err?: Error | null, + result?: protos.google.cloud.bigquery.v2.IJobCancelResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.cancelJob as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.cancelJob as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('cancelJob', () => { - it('invokes cancelJob without error', async () => { - const client = new jobserviceModule.v2.JobServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.CancelJobRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.CancelJobRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.CancelJobRequest', ['jobId']); - request.jobId = defaultValue2; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&job_id=${defaultValue2 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.bigquery.v2.JobCancelResponse() - ); - client.innerApiCalls.cancelJob = stubSimpleCall(expectedResponse); - const [response] = await client.cancelJob(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.cancelJob as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.cancelJob as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes cancelJob with error', async () => { + const client = new jobserviceModule.v2.JobServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.CancelJobRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.CancelJobRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.CancelJobRequest', + ['jobId'], + ); + request.jobId = defaultValue2; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&job_id=${defaultValue2 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.cancelJob = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.cancelJob(request), expectedError); + const actualRequest = ( + client.innerApiCalls.cancelJob as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.cancelJob as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes cancelJob without error using callback', async () => { - const client = new jobserviceModule.v2.JobServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.CancelJobRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.CancelJobRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.CancelJobRequest', ['jobId']); - request.jobId = defaultValue2; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&job_id=${defaultValue2 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.bigquery.v2.JobCancelResponse() - ); - client.innerApiCalls.cancelJob = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.cancelJob( - request, - (err?: Error|null, result?: protos.google.cloud.bigquery.v2.IJobCancelResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.cancelJob as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.cancelJob as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes cancelJob with closed client', async () => { + const client = new jobserviceModule.v2.JobServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.CancelJobRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.CancelJobRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.CancelJobRequest', + ['jobId'], + ); + request.jobId = defaultValue2; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.cancelJob(request), expectedError); + }); + }); - it('invokes cancelJob with error', async () => { - const client = new jobserviceModule.v2.JobServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.CancelJobRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.CancelJobRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.CancelJobRequest', ['jobId']); - request.jobId = defaultValue2; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&job_id=${defaultValue2 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.cancelJob = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.cancelJob(request), expectedError); - const actualRequest = (client.innerApiCalls.cancelJob as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.cancelJob as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + describe('getJob', () => { + it('invokes getJob without error', async () => { + const client = new jobserviceModule.v2.JobServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.GetJobRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetJobRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetJobRequest', + ['jobId'], + ); + request.jobId = defaultValue2; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&job_id=${defaultValue2 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.bigquery.v2.Job(), + ); + client.innerApiCalls.getJob = stubSimpleCall(expectedResponse); + const [response] = await client.getJob(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.getJob as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getJob as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes cancelJob with closed client', async () => { - const client = new jobserviceModule.v2.JobServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.CancelJobRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.CancelJobRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.CancelJobRequest', ['jobId']); - request.jobId = defaultValue2; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.cancelJob(request), expectedError); - }); + it('invokes getJob without error using callback', async () => { + const client = new jobserviceModule.v2.JobServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.GetJobRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetJobRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetJobRequest', + ['jobId'], + ); + request.jobId = defaultValue2; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&job_id=${defaultValue2 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.bigquery.v2.Job(), + ); + client.innerApiCalls.getJob = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getJob( + request, + ( + err?: Error | null, + result?: protos.google.cloud.bigquery.v2.IJob | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.getJob as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getJob as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('getJob', () => { - it('invokes getJob without error', async () => { - const client = new jobserviceModule.v2.JobServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.GetJobRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetJobRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetJobRequest', ['jobId']); - request.jobId = defaultValue2; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&job_id=${defaultValue2 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.bigquery.v2.Job() - ); - client.innerApiCalls.getJob = stubSimpleCall(expectedResponse); - const [response] = await client.getJob(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getJob as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getJob as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getJob with error', async () => { + const client = new jobserviceModule.v2.JobServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.GetJobRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetJobRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetJobRequest', + ['jobId'], + ); + request.jobId = defaultValue2; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&job_id=${defaultValue2 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getJob = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.getJob(request), expectedError); + const actualRequest = (client.innerApiCalls.getJob as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getJob as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getJob without error using callback', async () => { - const client = new jobserviceModule.v2.JobServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.GetJobRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetJobRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetJobRequest', ['jobId']); - request.jobId = defaultValue2; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&job_id=${defaultValue2 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.bigquery.v2.Job() - ); - client.innerApiCalls.getJob = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getJob( - request, - (err?: Error|null, result?: protos.google.cloud.bigquery.v2.IJob|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getJob as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getJob as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getJob with closed client', async () => { + const client = new jobserviceModule.v2.JobServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.GetJobRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetJobRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetJobRequest', + ['jobId'], + ); + request.jobId = defaultValue2; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getJob(request), expectedError); + }); + }); - it('invokes getJob with error', async () => { - const client = new jobserviceModule.v2.JobServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.GetJobRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetJobRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetJobRequest', ['jobId']); - request.jobId = defaultValue2; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&job_id=${defaultValue2 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getJob = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getJob(request), expectedError); - const actualRequest = (client.innerApiCalls.getJob as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getJob as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + describe('insertJob', () => { + it('invokes insertJob without error', async () => { + const client = new jobserviceModule.v2.JobServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.InsertJobRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.InsertJobRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.bigquery.v2.Job(), + ); + client.innerApiCalls.insertJob = stubSimpleCall(expectedResponse); + const [response] = await client.insertJob(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.insertJob as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.insertJob as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getJob with closed client', async () => { - const client = new jobserviceModule.v2.JobServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.GetJobRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetJobRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetJobRequest', ['jobId']); - request.jobId = defaultValue2; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getJob(request), expectedError); - }); + it('invokes insertJob without error using callback', async () => { + const client = new jobserviceModule.v2.JobServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.InsertJobRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.InsertJobRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.bigquery.v2.Job(), + ); + client.innerApiCalls.insertJob = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.insertJob( + request, + ( + err?: Error | null, + result?: protos.google.cloud.bigquery.v2.IJob | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.insertJob as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.insertJob as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('insertJob', () => { - it('invokes insertJob without error', async () => { - const client = new jobserviceModule.v2.JobServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.InsertJobRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.InsertJobRequest', ['projectId']); - request.projectId = defaultValue1; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.bigquery.v2.Job() - ); - client.innerApiCalls.insertJob = stubSimpleCall(expectedResponse); - const [response] = await client.insertJob(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.insertJob as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.insertJob as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes insertJob with error', async () => { + const client = new jobserviceModule.v2.JobServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.InsertJobRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.InsertJobRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.insertJob = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.insertJob(request), expectedError); + const actualRequest = ( + client.innerApiCalls.insertJob as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.insertJob as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes insertJob without error using callback', async () => { - const client = new jobserviceModule.v2.JobServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.InsertJobRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.InsertJobRequest', ['projectId']); - request.projectId = defaultValue1; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.bigquery.v2.Job() - ); - client.innerApiCalls.insertJob = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.insertJob( - request, - (err?: Error|null, result?: protos.google.cloud.bigquery.v2.IJob|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.insertJob as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.insertJob as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes insertJob with closed client', async () => { + const client = new jobserviceModule.v2.JobServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.InsertJobRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.InsertJobRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.insertJob(request), expectedError); + }); + }); - it('invokes insertJob with error', async () => { - const client = new jobserviceModule.v2.JobServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.InsertJobRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.InsertJobRequest', ['projectId']); - request.projectId = defaultValue1; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.insertJob = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.insertJob(request), expectedError); - const actualRequest = (client.innerApiCalls.insertJob as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.insertJob as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + describe('deleteJob', () => { + it('invokes deleteJob without error', async () => { + const client = new jobserviceModule.v2.JobServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.DeleteJobRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.DeleteJobRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.DeleteJobRequest', + ['jobId'], + ); + request.jobId = defaultValue2; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&job_id=${defaultValue2 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteJob = stubSimpleCall(expectedResponse); + const [response] = await client.deleteJob(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteJob as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteJob as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes insertJob with closed client', async () => { - const client = new jobserviceModule.v2.JobServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.InsertJobRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.InsertJobRequest', ['projectId']); - request.projectId = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.insertJob(request), expectedError); - }); + it('invokes deleteJob without error using callback', async () => { + const client = new jobserviceModule.v2.JobServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.DeleteJobRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.DeleteJobRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.DeleteJobRequest', + ['jobId'], + ); + request.jobId = defaultValue2; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&job_id=${defaultValue2 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteJob = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteJob( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteJob as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteJob as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('deleteJob', () => { - it('invokes deleteJob without error', async () => { - const client = new jobserviceModule.v2.JobServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.DeleteJobRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.DeleteJobRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.DeleteJobRequest', ['jobId']); - request.jobId = defaultValue2; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&job_id=${defaultValue2 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteJob = stubSimpleCall(expectedResponse); - const [response] = await client.deleteJob(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteJob as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteJob as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteJob with error', async () => { + const client = new jobserviceModule.v2.JobServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.DeleteJobRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.DeleteJobRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.DeleteJobRequest', + ['jobId'], + ); + request.jobId = defaultValue2; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&job_id=${defaultValue2 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteJob = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.deleteJob(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteJob as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteJob as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteJob without error using callback', async () => { - const client = new jobserviceModule.v2.JobServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.DeleteJobRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.DeleteJobRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.DeleteJobRequest', ['jobId']); - request.jobId = defaultValue2; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&job_id=${defaultValue2 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteJob = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteJob( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteJob as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteJob as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteJob with closed client', async () => { + const client = new jobserviceModule.v2.JobServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.DeleteJobRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.DeleteJobRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.DeleteJobRequest', + ['jobId'], + ); + request.jobId = defaultValue2; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.deleteJob(request), expectedError); + }); + }); - it('invokes deleteJob with error', async () => { - const client = new jobserviceModule.v2.JobServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.DeleteJobRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.DeleteJobRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.DeleteJobRequest', ['jobId']); - request.jobId = defaultValue2; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&job_id=${defaultValue2 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteJob = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteJob(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteJob as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteJob as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + describe('getQueryResults', () => { + it('invokes getQueryResults without error', async () => { + const client = new jobserviceModule.v2.JobServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.GetQueryResultsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetQueryResultsRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetQueryResultsRequest', + ['jobId'], + ); + request.jobId = defaultValue2; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&job_id=${defaultValue2 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.bigquery.v2.GetQueryResultsResponse(), + ); + client.innerApiCalls.getQueryResults = stubSimpleCall(expectedResponse); + const [response] = await client.getQueryResults(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getQueryResults as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getQueryResults as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteJob with closed client', async () => { - const client = new jobserviceModule.v2.JobServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.DeleteJobRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.DeleteJobRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.DeleteJobRequest', ['jobId']); - request.jobId = defaultValue2; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteJob(request), expectedError); - }); + it('invokes getQueryResults without error using callback', async () => { + const client = new jobserviceModule.v2.JobServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.GetQueryResultsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetQueryResultsRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetQueryResultsRequest', + ['jobId'], + ); + request.jobId = defaultValue2; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&job_id=${defaultValue2 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.bigquery.v2.GetQueryResultsResponse(), + ); + client.innerApiCalls.getQueryResults = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getQueryResults( + request, + ( + err?: Error | null, + result?: protos.google.cloud.bigquery.v2.IGetQueryResultsResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getQueryResults as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getQueryResults as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('getQueryResults', () => { - it('invokes getQueryResults without error', async () => { - const client = new jobserviceModule.v2.JobServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.GetQueryResultsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetQueryResultsRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetQueryResultsRequest', ['jobId']); - request.jobId = defaultValue2; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&job_id=${defaultValue2 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.bigquery.v2.GetQueryResultsResponse() - ); - client.innerApiCalls.getQueryResults = stubSimpleCall(expectedResponse); - const [response] = await client.getQueryResults(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getQueryResults as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getQueryResults as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getQueryResults with error', async () => { + const client = new jobserviceModule.v2.JobServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.GetQueryResultsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetQueryResultsRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetQueryResultsRequest', + ['jobId'], + ); + request.jobId = defaultValue2; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&job_id=${defaultValue2 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getQueryResults = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getQueryResults(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getQueryResults as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getQueryResults as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getQueryResults without error using callback', async () => { - const client = new jobserviceModule.v2.JobServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.GetQueryResultsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetQueryResultsRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetQueryResultsRequest', ['jobId']); - request.jobId = defaultValue2; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&job_id=${defaultValue2 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.bigquery.v2.GetQueryResultsResponse() - ); - client.innerApiCalls.getQueryResults = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getQueryResults( - request, - (err?: Error|null, result?: protos.google.cloud.bigquery.v2.IGetQueryResultsResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getQueryResults as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getQueryResults as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getQueryResults with closed client', async () => { + const client = new jobserviceModule.v2.JobServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.GetQueryResultsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetQueryResultsRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetQueryResultsRequest', + ['jobId'], + ); + request.jobId = defaultValue2; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getQueryResults(request), expectedError); + }); + }); - it('invokes getQueryResults with error', async () => { - const client = new jobserviceModule.v2.JobServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.GetQueryResultsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetQueryResultsRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetQueryResultsRequest', ['jobId']); - request.jobId = defaultValue2; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&job_id=${defaultValue2 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getQueryResults = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getQueryResults(request), expectedError); - const actualRequest = (client.innerApiCalls.getQueryResults as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getQueryResults as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + describe('query', () => { + it('invokes query without error', async () => { + const client = new jobserviceModule.v2.JobServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.PostQueryRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.PostQueryRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.bigquery.v2.QueryResponse(), + ); + client.innerApiCalls.query = stubSimpleCall(expectedResponse); + const [response] = await client.query(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.query as SinonStub).getCall(0) + .args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.query as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getQueryResults with closed client', async () => { - const client = new jobserviceModule.v2.JobServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.GetQueryResultsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetQueryResultsRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetQueryResultsRequest', ['jobId']); - request.jobId = defaultValue2; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getQueryResults(request), expectedError); - }); + it('invokes query without error using callback', async () => { + const client = new jobserviceModule.v2.JobServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.PostQueryRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.PostQueryRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.bigquery.v2.QueryResponse(), + ); + client.innerApiCalls.query = stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.query( + request, + ( + err?: Error | null, + result?: protos.google.cloud.bigquery.v2.IQueryResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.query as SinonStub).getCall(0) + .args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.query as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('query', () => { - it('invokes query without error', async () => { - const client = new jobserviceModule.v2.JobServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.PostQueryRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.PostQueryRequest', ['projectId']); - request.projectId = defaultValue1; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.bigquery.v2.QueryResponse() - ); - client.innerApiCalls.query = stubSimpleCall(expectedResponse); - const [response] = await client.query(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.query as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.query as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes query with error', async () => { + const client = new jobserviceModule.v2.JobServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.PostQueryRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.PostQueryRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.query = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.query(request), expectedError); + const actualRequest = (client.innerApiCalls.query as SinonStub).getCall(0) + .args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.query as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes query without error using callback', async () => { - const client = new jobserviceModule.v2.JobServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.PostQueryRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.PostQueryRequest', ['projectId']); - request.projectId = defaultValue1; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.bigquery.v2.QueryResponse() - ); - client.innerApiCalls.query = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.query( - request, - (err?: Error|null, result?: protos.google.cloud.bigquery.v2.IQueryResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.query as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.query as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes query with closed client', async () => { + const client = new jobserviceModule.v2.JobServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.PostQueryRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.PostQueryRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.query(request), expectedError); + }); + }); - it('invokes query with error', async () => { - const client = new jobserviceModule.v2.JobServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.PostQueryRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.PostQueryRequest', ['projectId']); - request.projectId = defaultValue1; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.query = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.query(request), expectedError); - const actualRequest = (client.innerApiCalls.query as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.query as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + describe('listJobs', () => { + it('invokes listJobs without error', async () => { + const client = new jobserviceModule.v2.JobServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListJobsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListJobsRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListFormatJob(), + ), + generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListFormatJob(), + ), + generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListFormatJob(), + ), + ]; + client.innerApiCalls.listJobs = stubSimpleCall(expectedResponse); + const [response] = await client.listJobs(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listJobs as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listJobs as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes query with closed client', async () => { - const client = new jobserviceModule.v2.JobServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.PostQueryRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.PostQueryRequest', ['projectId']); - request.projectId = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.query(request), expectedError); - }); + it('invokes listJobs without error using callback', async () => { + const client = new jobserviceModule.v2.JobServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListJobsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListJobsRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListFormatJob(), + ), + generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListFormatJob(), + ), + generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListFormatJob(), + ), + ]; + client.innerApiCalls.listJobs = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listJobs( + request, + ( + err?: Error | null, + result?: protos.google.cloud.bigquery.v2.IListFormatJob[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listJobs as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listJobs as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('listJobs', () => { - it('invokes listJobs without error', async () => { - const client = new jobserviceModule.v2.JobServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.ListJobsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListJobsRequest', ['projectId']); - request.projectId = defaultValue1; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.bigquery.v2.ListFormatJob()), - generateSampleMessage(new protos.google.cloud.bigquery.v2.ListFormatJob()), - generateSampleMessage(new protos.google.cloud.bigquery.v2.ListFormatJob()), - ]; - client.innerApiCalls.listJobs = stubSimpleCall(expectedResponse); - const [response] = await client.listJobs(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listJobs as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listJobs as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listJobs with error', async () => { + const client = new jobserviceModule.v2.JobServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListJobsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListJobsRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listJobs = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.listJobs(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listJobs as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listJobs as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listJobs without error using callback', async () => { - const client = new jobserviceModule.v2.JobServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.ListJobsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListJobsRequest', ['projectId']); - request.projectId = defaultValue1; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.bigquery.v2.ListFormatJob()), - generateSampleMessage(new protos.google.cloud.bigquery.v2.ListFormatJob()), - generateSampleMessage(new protos.google.cloud.bigquery.v2.ListFormatJob()), - ]; - client.innerApiCalls.listJobs = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listJobs( - request, - (err?: Error|null, result?: protos.google.cloud.bigquery.v2.IListFormatJob[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listJobs as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listJobs as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes listJobsStream without error', async () => { + const client = new jobserviceModule.v2.JobServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListJobsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListJobsRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListFormatJob(), + ), + generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListFormatJob(), + ), + generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListFormatJob(), + ), + ]; + client.descriptors.page.listJobs.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listJobsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.cloud.bigquery.v2.ListFormatJob[] = []; + stream.on( + 'data', + (response: protos.google.cloud.bigquery.v2.ListFormatJob) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); }); - - it('invokes listJobs with error', async () => { - const client = new jobserviceModule.v2.JobServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.ListJobsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListJobsRequest', ['projectId']); - request.projectId = defaultValue1; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listJobs = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listJobs(request), expectedError); - const actualRequest = (client.innerApiCalls.listJobs as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listJobs as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + stream.on('error', (err: Error) => { + reject(err); }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listJobs.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listJobs, request), + ); + assert( + (client.descriptors.page.listJobs.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('invokes listJobsStream without error', async () => { - const client = new jobserviceModule.v2.JobServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.ListJobsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListJobsRequest', ['projectId']); - request.projectId = defaultValue1; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.bigquery.v2.ListFormatJob()), - generateSampleMessage(new protos.google.cloud.bigquery.v2.ListFormatJob()), - generateSampleMessage(new protos.google.cloud.bigquery.v2.ListFormatJob()), - ]; - client.descriptors.page.listJobs.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listJobsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.cloud.bigquery.v2.ListFormatJob[] = []; - stream.on('data', (response: protos.google.cloud.bigquery.v2.ListFormatJob) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.listJobs.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listJobs, request)); - assert( - (client.descriptors.page.listJobs.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); + it('invokes listJobsStream with error', async () => { + const client = new jobserviceModule.v2.JobServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListJobsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListJobsRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listJobs.createStream = stubPageStreamingCall( + undefined, + expectedError, + ); + const stream = client.listJobsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.cloud.bigquery.v2.ListFormatJob[] = []; + stream.on( + 'data', + (response: protos.google.cloud.bigquery.v2.ListFormatJob) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); }); - - it('invokes listJobsStream with error', async () => { - const client = new jobserviceModule.v2.JobServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.ListJobsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListJobsRequest', ['projectId']); - request.projectId = defaultValue1; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listJobs.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listJobsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.cloud.bigquery.v2.ListFormatJob[] = []; - stream.on('data', (response: protos.google.cloud.bigquery.v2.ListFormatJob) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listJobs.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listJobs, request)); - assert( - (client.descriptors.page.listJobs.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); + stream.on('error', (err: Error) => { + reject(err); }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listJobs.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listJobs, request), + ); + assert( + (client.descriptors.page.listJobs.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('uses async iteration with listJobs without error', async () => { - const client = new jobserviceModule.v2.JobServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.ListJobsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListJobsRequest', ['projectId']); - request.projectId = defaultValue1; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.bigquery.v2.ListFormatJob()), - generateSampleMessage(new protos.google.cloud.bigquery.v2.ListFormatJob()), - generateSampleMessage(new protos.google.cloud.bigquery.v2.ListFormatJob()), - ]; - client.descriptors.page.listJobs.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.cloud.bigquery.v2.IListFormatJob[] = []; - const iterable = client.listJobsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listJobs.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listJobs.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listJobs without error', async () => { + const client = new jobserviceModule.v2.JobServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListJobsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListJobsRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListFormatJob(), + ), + generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListFormatJob(), + ), + generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListFormatJob(), + ), + ]; + client.descriptors.page.listJobs.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.cloud.bigquery.v2.IListFormatJob[] = []; + const iterable = client.listJobsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + (client.descriptors.page.listJobs.asyncIterate as SinonStub).getCall(0) + .args[1], + request, + ); + assert( + (client.descriptors.page.listJobs.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('uses async iteration with listJobs with error', async () => { - const client = new jobserviceModule.v2.JobServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.ListJobsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListJobsRequest', ['projectId']); - request.projectId = defaultValue1; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listJobs.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listJobsAsync(request); - await assert.rejects(async () => { - const responses: protos.google.cloud.bigquery.v2.IListFormatJob[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listJobs.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listJobs.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listJobs with error', async () => { + const client = new jobserviceModule.v2.JobServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListJobsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListJobsRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listJobs.asyncIterate = stubAsyncIterationCall( + undefined, + expectedError, + ); + const iterable = client.listJobsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.cloud.bigquery.v2.IListFormatJob[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + (client.descriptors.page.listJobs.asyncIterate as SinonStub).getCall(0) + .args[1], + request, + ); + assert( + (client.descriptors.page.listJobs.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); }); + }); }); diff --git a/core/generator/gapic-generator-typescript/baselines/bigquery-v2/test/gapic_model_service_v2.ts.baseline b/core/generator/gapic-generator-typescript/baselines/bigquery-v2/test/gapic_model_service_v2.ts.baseline index 5450fa40562c..1fc19e777327 100644 --- a/core/generator/gapic-generator-typescript/baselines/bigquery-v2/test/gapic_model_service_v2.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/bigquery-v2/test/gapic_model_service_v2.ts.baseline @@ -19,905 +19,1148 @@ import * as protos from '../protos/protos'; import * as assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as modelserviceModule from '../src'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; -import {protobuf} from 'google-gax'; +import { protobuf } from 'google-gax'; // Dynamically loaded proto JSON is needed to get the type information // to fill in default values for request objects -const root = protobuf.Root.fromJSON(require('../protos/protos.json')).resolveAll(); +const root = protobuf.Root.fromJSON( + require('../protos/protos.json'), +).resolveAll(); // eslint-disable-next-line @typescript-eslint/no-unused-vars function getTypeDefaultValue(typeName: string, fields: string[]) { - let type = root.lookupType(typeName) as protobuf.Type; - for (const field of fields.slice(0, -1)) { - type = type.fields[field]?.resolvedType as protobuf.Type; - } - return type.fields[fields[fields.length - 1]]?.defaultValue; + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type.fields[field]?.resolvedType as protobuf.Type; + } + return type.fields[fields[fields.length - 1]]?.defaultValue; } function generateSampleMessage(instance: T) { - const filledObject = (instance.constructor as typeof protobuf.Message) - .toObject(instance as protobuf.Message, {defaults: true}); - return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, { defaults: true }); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; } function stubSimpleCall(response?: ResponseType, error?: Error) { - return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); } -function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { - return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +function stubSimpleCallWithCallback( + response?: ResponseType, + error?: Error, +) { + return error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); } -function stubPageStreamingCall(responses?: ResponseType[], error?: Error) { - const pagingStub = sinon.stub(); - if (responses) { - for (let i = 0; i < responses.length; ++i) { - pagingStub.onCall(i).callsArgWith(2, null, responses[i]); - } +function stubPageStreamingCall( + responses?: ResponseType[], + error?: Error, +) { + const pagingStub = sinon.stub(); + if (responses) { + for (let i = 0; i < responses.length; ++i) { + pagingStub.onCall(i).callsArgWith(2, null, responses[i]); } - const transformStub = error ? sinon.stub().callsArgWith(2, error) : pagingStub; - const mockStream = new PassThrough({ - objectMode: true, - transform: transformStub, - }); - // trigger as many responses as needed - if (responses) { - for (let i = 0; i < responses.length; ++i) { - setImmediate(() => { mockStream.write({}); }); - } - setImmediate(() => { mockStream.end(); }); - } else { - setImmediate(() => { mockStream.write({}); }); - setImmediate(() => { mockStream.end(); }); + } + const transformStub = error + ? sinon.stub().callsArgWith(2, error) + : pagingStub; + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + // trigger as many responses as needed + if (responses) { + for (let i = 0; i < responses.length; ++i) { + setImmediate(() => { + mockStream.write({}); + }); } - return sinon.stub().returns(mockStream); + setImmediate(() => { + mockStream.end(); + }); + } else { + setImmediate(() => { + mockStream.write({}); + }); + setImmediate(() => { + mockStream.end(); + }); + } + return sinon.stub().returns(mockStream); } -function stubAsyncIterationCall(responses?: ResponseType[], error?: Error) { - let counter = 0; - const asyncIterable = { - [Symbol.asyncIterator]() { - return { - async next() { - if (error) { - return Promise.reject(error); - } - if (counter >= responses!.length) { - return Promise.resolve({done: true, value: undefined}); - } - return Promise.resolve({done: false, value: responses![counter++]}); - } - }; - } - }; - return sinon.stub().returns(asyncIterable); +function stubAsyncIterationCall( + responses?: ResponseType[], + error?: Error, +) { + let counter = 0; + const asyncIterable = { + [Symbol.asyncIterator]() { + return { + async next() { + if (error) { + return Promise.reject(error); + } + if (counter >= responses!.length) { + return Promise.resolve({ done: true, value: undefined }); + } + return Promise.resolve({ done: false, value: responses![counter++] }); + }, + }; + }, + }; + return sinon.stub().returns(asyncIterable); } describe('v2.ModelServiceClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new modelserviceModule.v2.ModelServiceClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'bigquery.googleapis.com'); - }); - - it('has universeDomain', () => { - const client = new modelserviceModule.v2.ModelServiceClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new modelserviceModule.v2.ModelServiceClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'bigquery.googleapis.com'); + }); - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - it('throws DeprecationWarning if static servicePath is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const servicePath = modelserviceModule.v2.ModelServiceClient.servicePath; - assert.strictEqual(servicePath, 'bigquery.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = modelserviceModule.v2.ModelServiceClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'bigquery.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new modelserviceModule.v2.ModelServiceClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'bigquery.example.com'); - }); + it('has universeDomain', () => { + const client = new modelserviceModule.v2.ModelServiceClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new modelserviceModule.v2.ModelServiceClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'bigquery.example.com'); - }); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = + modelserviceModule.v2.ModelServiceClient.servicePath; + assert.strictEqual(servicePath, 'bigquery.googleapis.com'); + assert(stub.called); + stub.restore(); + }); - if (typeof process === 'object' && 'env' in process) { - describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { - it('sets apiEndpoint from environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new modelserviceModule.v2.ModelServiceClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'bigquery.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - - it('value configured in code has priority over environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new modelserviceModule.v2.ModelServiceClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'bigquery.configured.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { new modelserviceModule.v2.ModelServiceClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + modelserviceModule.v2.ModelServiceClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'bigquery.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = new modelserviceModule.v2.ModelServiceClient({ + universeDomain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'bigquery.example.com'); + }); - it('has port', () => { - const port = modelserviceModule.v2.ModelServiceClient.port; - assert(port); - assert(typeof port === 'number'); - }); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = new modelserviceModule.v2.ModelServiceClient({ + universe_domain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'bigquery.example.com'); + }); - it('should create a client with no option', () => { - const client = new modelserviceModule.v2.ModelServiceClient(); - assert(client); + if (typeof process === 'object' && 'env' in process) { + describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { + it('sets apiEndpoint from environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new modelserviceModule.v2.ModelServiceClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'bigquery.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - it('should create a client with gRPC fallback', () => { - const client = new modelserviceModule.v2.ModelServiceClient({ - fallback: true, - }); - assert(client); + it('value configured in code has priority over environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new modelserviceModule.v2.ModelServiceClient({ + universeDomain: 'configured.example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'bigquery.configured.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - - it('has initialize method and supports deferred initialization', async () => { - const client = new modelserviceModule.v2.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.modelServiceStub, undefined); - await client.initialize(); - assert(client.modelServiceStub); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new modelserviceModule.v2.ModelServiceClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); + }); - it('has close method for the initialized client', done => { - const client = new modelserviceModule.v2.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.modelServiceStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('has port', () => { + const port = modelserviceModule.v2.ModelServiceClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('has close method for the non-initialized client', done => { - const client = new modelserviceModule.v2.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.modelServiceStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('should create a client with no option', () => { + const client = new modelserviceModule.v2.ModelServiceClient(); + assert(client); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new modelserviceModule.v2.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); - }); + it('should create a client with gRPC fallback', () => { + const client = new modelserviceModule.v2.ModelServiceClient({ + fallback: true, + }); + assert(client); + }); - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new modelserviceModule.v2.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId((err?: Error|null, projectId?: string|null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } - }); - }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); - }); + it('has initialize method and supports deferred initialization', async () => { + const client = new modelserviceModule.v2.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.modelServiceStub, undefined); + await client.initialize(); + assert(client.modelServiceStub); }); - describe('getModel', () => { - it('invokes getModel without error', async () => { - const client = new modelserviceModule.v2.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.GetModelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetModelRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetModelRequest', ['datasetId']); - request.datasetId = defaultValue2; - const defaultValue3 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetModelRequest', ['modelId']); - request.modelId = defaultValue3; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }&model_id=${defaultValue3 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.bigquery.v2.Model() - ); - client.innerApiCalls.getModel = stubSimpleCall(expectedResponse); - const [response] = await client.getModel(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getModel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getModel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('has close method for the initialized client', (done) => { + const client = new modelserviceModule.v2.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.modelServiceStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes getModel without error using callback', async () => { - const client = new modelserviceModule.v2.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.GetModelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetModelRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetModelRequest', ['datasetId']); - request.datasetId = defaultValue2; - const defaultValue3 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetModelRequest', ['modelId']); - request.modelId = defaultValue3; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }&model_id=${defaultValue3 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.bigquery.v2.Model() - ); - client.innerApiCalls.getModel = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getModel( - request, - (err?: Error|null, result?: protos.google.cloud.bigquery.v2.IModel|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getModel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getModel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('has close method for the non-initialized client', (done) => { + const client = new modelserviceModule.v2.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.modelServiceStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes getModel with error', async () => { - const client = new modelserviceModule.v2.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.GetModelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetModelRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetModelRequest', ['datasetId']); - request.datasetId = defaultValue2; - const defaultValue3 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetModelRequest', ['modelId']); - request.modelId = defaultValue3; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }&model_id=${defaultValue3 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getModel = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getModel(request), expectedError); - const actualRequest = (client.innerApiCalls.getModel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getModel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new modelserviceModule.v2.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + }); - it('invokes getModel with closed client', async () => { - const client = new modelserviceModule.v2.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.GetModelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetModelRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetModelRequest', ['datasetId']); - request.datasetId = defaultValue2; - const defaultValue3 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetModelRequest', ['modelId']); - request.modelId = defaultValue3; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getModel(request), expectedError); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new modelserviceModule.v2.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); }); + }); - describe('patchModel', () => { - it('invokes patchModel without error', async () => { - const client = new modelserviceModule.v2.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.PatchModelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.PatchModelRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.PatchModelRequest', ['datasetId']); - request.datasetId = defaultValue2; - const defaultValue3 = - getTypeDefaultValue('.google.cloud.bigquery.v2.PatchModelRequest', ['modelId']); - request.modelId = defaultValue3; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }&model_id=${defaultValue3 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.bigquery.v2.Model() - ); - client.innerApiCalls.patchModel = stubSimpleCall(expectedResponse); - const [response] = await client.patchModel(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.patchModel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.patchModel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + describe('getModel', () => { + it('invokes getModel without error', async () => { + const client = new modelserviceModule.v2.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.GetModelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetModelRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetModelRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const defaultValue3 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetModelRequest', + ['modelId'], + ); + request.modelId = defaultValue3; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}&model_id=${defaultValue3 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.bigquery.v2.Model(), + ); + client.innerApiCalls.getModel = stubSimpleCall(expectedResponse); + const [response] = await client.getModel(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getModel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getModel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes patchModel without error using callback', async () => { - const client = new modelserviceModule.v2.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.PatchModelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.PatchModelRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.PatchModelRequest', ['datasetId']); - request.datasetId = defaultValue2; - const defaultValue3 = - getTypeDefaultValue('.google.cloud.bigquery.v2.PatchModelRequest', ['modelId']); - request.modelId = defaultValue3; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }&model_id=${defaultValue3 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.bigquery.v2.Model() - ); - client.innerApiCalls.patchModel = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.patchModel( - request, - (err?: Error|null, result?: protos.google.cloud.bigquery.v2.IModel|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.patchModel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.patchModel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getModel without error using callback', async () => { + const client = new modelserviceModule.v2.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.GetModelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetModelRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetModelRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const defaultValue3 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetModelRequest', + ['modelId'], + ); + request.modelId = defaultValue3; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}&model_id=${defaultValue3 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.bigquery.v2.Model(), + ); + client.innerApiCalls.getModel = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getModel( + request, + ( + err?: Error | null, + result?: protos.google.cloud.bigquery.v2.IModel | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getModel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getModel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes patchModel with error', async () => { - const client = new modelserviceModule.v2.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.PatchModelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.PatchModelRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.PatchModelRequest', ['datasetId']); - request.datasetId = defaultValue2; - const defaultValue3 = - getTypeDefaultValue('.google.cloud.bigquery.v2.PatchModelRequest', ['modelId']); - request.modelId = defaultValue3; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }&model_id=${defaultValue3 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.patchModel = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.patchModel(request), expectedError); - const actualRequest = (client.innerApiCalls.patchModel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.patchModel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getModel with error', async () => { + const client = new modelserviceModule.v2.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.GetModelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetModelRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetModelRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const defaultValue3 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetModelRequest', + ['modelId'], + ); + request.modelId = defaultValue3; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}&model_id=${defaultValue3 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getModel = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.getModel(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getModel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getModel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes patchModel with closed client', async () => { - const client = new modelserviceModule.v2.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.PatchModelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.PatchModelRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.PatchModelRequest', ['datasetId']); - request.datasetId = defaultValue2; - const defaultValue3 = - getTypeDefaultValue('.google.cloud.bigquery.v2.PatchModelRequest', ['modelId']); - request.modelId = defaultValue3; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.patchModel(request), expectedError); - }); + it('invokes getModel with closed client', async () => { + const client = new modelserviceModule.v2.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.GetModelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetModelRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetModelRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const defaultValue3 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetModelRequest', + ['modelId'], + ); + request.modelId = defaultValue3; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getModel(request), expectedError); }); + }); - describe('deleteModel', () => { - it('invokes deleteModel without error', async () => { - const client = new modelserviceModule.v2.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.DeleteModelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.DeleteModelRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.DeleteModelRequest', ['datasetId']); - request.datasetId = defaultValue2; - const defaultValue3 = - getTypeDefaultValue('.google.cloud.bigquery.v2.DeleteModelRequest', ['modelId']); - request.modelId = defaultValue3; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }&model_id=${defaultValue3 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteModel = stubSimpleCall(expectedResponse); - const [response] = await client.deleteModel(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteModel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteModel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + describe('patchModel', () => { + it('invokes patchModel without error', async () => { + const client = new modelserviceModule.v2.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.PatchModelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.PatchModelRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.PatchModelRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const defaultValue3 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.PatchModelRequest', + ['modelId'], + ); + request.modelId = defaultValue3; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}&model_id=${defaultValue3 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.bigquery.v2.Model(), + ); + client.innerApiCalls.patchModel = stubSimpleCall(expectedResponse); + const [response] = await client.patchModel(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.patchModel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.patchModel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteModel without error using callback', async () => { - const client = new modelserviceModule.v2.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.DeleteModelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.DeleteModelRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.DeleteModelRequest', ['datasetId']); - request.datasetId = defaultValue2; - const defaultValue3 = - getTypeDefaultValue('.google.cloud.bigquery.v2.DeleteModelRequest', ['modelId']); - request.modelId = defaultValue3; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }&model_id=${defaultValue3 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteModel = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteModel( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteModel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteModel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes patchModel without error using callback', async () => { + const client = new modelserviceModule.v2.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.PatchModelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.PatchModelRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.PatchModelRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const defaultValue3 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.PatchModelRequest', + ['modelId'], + ); + request.modelId = defaultValue3; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}&model_id=${defaultValue3 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.bigquery.v2.Model(), + ); + client.innerApiCalls.patchModel = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.patchModel( + request, + ( + err?: Error | null, + result?: protos.google.cloud.bigquery.v2.IModel | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.patchModel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.patchModel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteModel with error', async () => { - const client = new modelserviceModule.v2.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.DeleteModelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.DeleteModelRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.DeleteModelRequest', ['datasetId']); - request.datasetId = defaultValue2; - const defaultValue3 = - getTypeDefaultValue('.google.cloud.bigquery.v2.DeleteModelRequest', ['modelId']); - request.modelId = defaultValue3; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }&model_id=${defaultValue3 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteModel = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteModel(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteModel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteModel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes patchModel with error', async () => { + const client = new modelserviceModule.v2.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.PatchModelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.PatchModelRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.PatchModelRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const defaultValue3 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.PatchModelRequest', + ['modelId'], + ); + request.modelId = defaultValue3; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}&model_id=${defaultValue3 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.patchModel = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.patchModel(request), expectedError); + const actualRequest = ( + client.innerApiCalls.patchModel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.patchModel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteModel with closed client', async () => { - const client = new modelserviceModule.v2.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.DeleteModelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.DeleteModelRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.DeleteModelRequest', ['datasetId']); - request.datasetId = defaultValue2; - const defaultValue3 = - getTypeDefaultValue('.google.cloud.bigquery.v2.DeleteModelRequest', ['modelId']); - request.modelId = defaultValue3; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteModel(request), expectedError); - }); + it('invokes patchModel with closed client', async () => { + const client = new modelserviceModule.v2.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.PatchModelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.PatchModelRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.PatchModelRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const defaultValue3 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.PatchModelRequest', + ['modelId'], + ); + request.modelId = defaultValue3; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.patchModel(request), expectedError); }); + }); - describe('listModels', () => { - it('invokes listModels without error', async () => { - const client = new modelserviceModule.v2.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.ListModelsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListModelsRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListModelsRequest', ['datasetId']); - request.datasetId = defaultValue2; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.bigquery.v2.Model()), - generateSampleMessage(new protos.google.cloud.bigquery.v2.Model()), - generateSampleMessage(new protos.google.cloud.bigquery.v2.Model()), - ]; - client.innerApiCalls.listModels = stubSimpleCall(expectedResponse); - const [response] = await client.listModels(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listModels as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listModels as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + describe('deleteModel', () => { + it('invokes deleteModel without error', async () => { + const client = new modelserviceModule.v2.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.DeleteModelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.DeleteModelRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.DeleteModelRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const defaultValue3 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.DeleteModelRequest', + ['modelId'], + ); + request.modelId = defaultValue3; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}&model_id=${defaultValue3 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteModel = stubSimpleCall(expectedResponse); + const [response] = await client.deleteModel(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteModel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteModel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listModels without error using callback', async () => { - const client = new modelserviceModule.v2.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.ListModelsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListModelsRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListModelsRequest', ['datasetId']); - request.datasetId = defaultValue2; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.bigquery.v2.Model()), - generateSampleMessage(new protos.google.cloud.bigquery.v2.Model()), - generateSampleMessage(new protos.google.cloud.bigquery.v2.Model()), - ]; - client.innerApiCalls.listModels = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listModels( - request, - (err?: Error|null, result?: protos.google.cloud.bigquery.v2.IModel[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listModels as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listModels as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteModel without error using callback', async () => { + const client = new modelserviceModule.v2.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.DeleteModelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.DeleteModelRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.DeleteModelRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const defaultValue3 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.DeleteModelRequest', + ['modelId'], + ); + request.modelId = defaultValue3; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}&model_id=${defaultValue3 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteModel = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteModel( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteModel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteModel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listModels with error', async () => { - const client = new modelserviceModule.v2.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.ListModelsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListModelsRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListModelsRequest', ['datasetId']); - request.datasetId = defaultValue2; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listModels = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listModels(request), expectedError); - const actualRequest = (client.innerApiCalls.listModels as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listModels as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteModel with error', async () => { + const client = new modelserviceModule.v2.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.DeleteModelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.DeleteModelRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.DeleteModelRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const defaultValue3 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.DeleteModelRequest', + ['modelId'], + ); + request.modelId = defaultValue3; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}&model_id=${defaultValue3 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteModel = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.deleteModel(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteModel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteModel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listModelsStream without error', async () => { - const client = new modelserviceModule.v2.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.ListModelsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListModelsRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListModelsRequest', ['datasetId']); - request.datasetId = defaultValue2; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.bigquery.v2.Model()), - generateSampleMessage(new protos.google.cloud.bigquery.v2.Model()), - generateSampleMessage(new protos.google.cloud.bigquery.v2.Model()), - ]; - client.descriptors.page.listModels.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listModelsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.cloud.bigquery.v2.Model[] = []; - stream.on('data', (response: protos.google.cloud.bigquery.v2.Model) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.listModels.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listModels, request)); - assert( - (client.descriptors.page.listModels.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes deleteModel with closed client', async () => { + const client = new modelserviceModule.v2.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.DeleteModelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.DeleteModelRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.DeleteModelRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const defaultValue3 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.DeleteModelRequest', + ['modelId'], + ); + request.modelId = defaultValue3; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.deleteModel(request), expectedError); + }); + }); - it('invokes listModelsStream with error', async () => { - const client = new modelserviceModule.v2.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.ListModelsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListModelsRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListModelsRequest', ['datasetId']); - request.datasetId = defaultValue2; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listModels.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listModelsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.cloud.bigquery.v2.Model[] = []; - stream.on('data', (response: protos.google.cloud.bigquery.v2.Model) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listModels.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listModels, request)); - assert( - (client.descriptors.page.listModels.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + describe('listModels', () => { + it('invokes listModels without error', async () => { + const client = new modelserviceModule.v2.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListModelsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListModelsRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListModelsRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.bigquery.v2.Model()), + generateSampleMessage(new protos.google.cloud.bigquery.v2.Model()), + generateSampleMessage(new protos.google.cloud.bigquery.v2.Model()), + ]; + client.innerApiCalls.listModels = stubSimpleCall(expectedResponse); + const [response] = await client.listModels(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listModels as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listModels as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('uses async iteration with listModels without error', async () => { - const client = new modelserviceModule.v2.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.ListModelsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListModelsRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListModelsRequest', ['datasetId']); - request.datasetId = defaultValue2; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.bigquery.v2.Model()), - generateSampleMessage(new protos.google.cloud.bigquery.v2.Model()), - generateSampleMessage(new protos.google.cloud.bigquery.v2.Model()), - ]; - client.descriptors.page.listModels.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.cloud.bigquery.v2.IModel[] = []; - const iterable = client.listModelsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); + it('invokes listModels without error using callback', async () => { + const client = new modelserviceModule.v2.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListModelsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListModelsRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListModelsRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.bigquery.v2.Model()), + generateSampleMessage(new protos.google.cloud.bigquery.v2.Model()), + generateSampleMessage(new protos.google.cloud.bigquery.v2.Model()), + ]; + client.innerApiCalls.listModels = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listModels( + request, + ( + err?: Error | null, + result?: protos.google.cloud.bigquery.v2.IModel[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listModels.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listModels.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listModels as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listModels as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listModels with error', async () => { + const client = new modelserviceModule.v2.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListModelsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListModelsRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListModelsRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listModels = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listModels(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listModels as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listModels as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listModelsStream without error', async () => { + const client = new modelserviceModule.v2.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListModelsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListModelsRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListModelsRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.bigquery.v2.Model()), + generateSampleMessage(new protos.google.cloud.bigquery.v2.Model()), + generateSampleMessage(new protos.google.cloud.bigquery.v2.Model()), + ]; + client.descriptors.page.listModels.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listModelsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.cloud.bigquery.v2.Model[] = []; + stream.on('data', (response: protos.google.cloud.bigquery.v2.Model) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listModels.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listModels, request), + ); + assert( + (client.descriptors.page.listModels.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('uses async iteration with listModels with error', async () => { - const client = new modelserviceModule.v2.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.ListModelsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListModelsRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListModelsRequest', ['datasetId']); - request.datasetId = defaultValue2; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listModels.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listModelsAsync(request); - await assert.rejects(async () => { - const responses: protos.google.cloud.bigquery.v2.IModel[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listModels.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listModels.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); + it('invokes listModelsStream with error', async () => { + const client = new modelserviceModule.v2.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListModelsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListModelsRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListModelsRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listModels.createStream = stubPageStreamingCall( + undefined, + expectedError, + ); + const stream = client.listModelsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.cloud.bigquery.v2.Model[] = []; + stream.on('data', (response: protos.google.cloud.bigquery.v2.Model) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listModels.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listModels, request), + ); + assert( + (client.descriptors.page.listModels.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + + it('uses async iteration with listModels without error', async () => { + const client = new modelserviceModule.v2.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListModelsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListModelsRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListModelsRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.bigquery.v2.Model()), + generateSampleMessage(new protos.google.cloud.bigquery.v2.Model()), + generateSampleMessage(new protos.google.cloud.bigquery.v2.Model()), + ]; + client.descriptors.page.listModels.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.cloud.bigquery.v2.IModel[] = []; + const iterable = client.listModelsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + (client.descriptors.page.listModels.asyncIterate as SinonStub).getCall( + 0, + ).args[1], + request, + ); + assert( + (client.descriptors.page.listModels.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + + it('uses async iteration with listModels with error', async () => { + const client = new modelserviceModule.v2.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListModelsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListModelsRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListModelsRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listModels.asyncIterate = stubAsyncIterationCall( + undefined, + expectedError, + ); + const iterable = client.listModelsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.cloud.bigquery.v2.IModel[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + (client.descriptors.page.listModels.asyncIterate as SinonStub).getCall( + 0, + ).args[1], + request, + ); + assert( + (client.descriptors.page.listModels.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); }); + }); }); diff --git a/core/generator/gapic-generator-typescript/baselines/bigquery-v2/test/gapic_project_service_v2.ts.baseline b/core/generator/gapic-generator-typescript/baselines/bigquery-v2/test/gapic_project_service_v2.ts.baseline index 4db88866c85f..be27739032d5 100644 --- a/core/generator/gapic-generator-typescript/baselines/bigquery-v2/test/gapic_project_service_v2.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/bigquery-v2/test/gapic_project_service_v2.ts.baseline @@ -19,304 +19,370 @@ import * as protos from '../protos/protos'; import * as assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as projectserviceModule from '../src'; -import {protobuf} from 'google-gax'; +import { protobuf } from 'google-gax'; // Dynamically loaded proto JSON is needed to get the type information // to fill in default values for request objects -const root = protobuf.Root.fromJSON(require('../protos/protos.json')).resolveAll(); +const root = protobuf.Root.fromJSON( + require('../protos/protos.json'), +).resolveAll(); // eslint-disable-next-line @typescript-eslint/no-unused-vars function getTypeDefaultValue(typeName: string, fields: string[]) { - let type = root.lookupType(typeName) as protobuf.Type; - for (const field of fields.slice(0, -1)) { - type = type.fields[field]?.resolvedType as protobuf.Type; - } - return type.fields[fields[fields.length - 1]]?.defaultValue; + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type.fields[field]?.resolvedType as protobuf.Type; + } + return type.fields[fields[fields.length - 1]]?.defaultValue; } function generateSampleMessage(instance: T) { - const filledObject = (instance.constructor as typeof protobuf.Message) - .toObject(instance as protobuf.Message, {defaults: true}); - return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, { defaults: true }); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; } function stubSimpleCall(response?: ResponseType, error?: Error) { - return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); } -function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { - return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +function stubSimpleCallWithCallback( + response?: ResponseType, + error?: Error, +) { + return error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); } describe('v2.ProjectServiceClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new projectserviceModule.v2.ProjectServiceClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'bigquery.googleapis.com'); - }); - - it('has universeDomain', () => { - const client = new projectserviceModule.v2.ProjectServiceClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new projectserviceModule.v2.ProjectServiceClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'bigquery.googleapis.com'); + }); - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - it('throws DeprecationWarning if static servicePath is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const servicePath = projectserviceModule.v2.ProjectServiceClient.servicePath; - assert.strictEqual(servicePath, 'bigquery.googleapis.com'); - assert(stub.called); - stub.restore(); - }); + it('has universeDomain', () => { + const client = new projectserviceModule.v2.ProjectServiceClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = projectserviceModule.v2.ProjectServiceClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'bigquery.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new projectserviceModule.v2.ProjectServiceClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'bigquery.example.com'); - }); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = + projectserviceModule.v2.ProjectServiceClient.servicePath; + assert.strictEqual(servicePath, 'bigquery.googleapis.com'); + assert(stub.called); + stub.restore(); + }); - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new projectserviceModule.v2.ProjectServiceClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'bigquery.example.com'); - }); + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + projectserviceModule.v2.ProjectServiceClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'bigquery.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = new projectserviceModule.v2.ProjectServiceClient({ + universeDomain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'bigquery.example.com'); + }); - if (typeof process === 'object' && 'env' in process) { - describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { - it('sets apiEndpoint from environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new projectserviceModule.v2.ProjectServiceClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'bigquery.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = new projectserviceModule.v2.ProjectServiceClient({ + universe_domain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'bigquery.example.com'); + }); - it('value configured in code has priority over environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new projectserviceModule.v2.ProjectServiceClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'bigquery.configured.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { new projectserviceModule.v2.ProjectServiceClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); + if (typeof process === 'object' && 'env' in process) { + describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { + it('sets apiEndpoint from environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new projectserviceModule.v2.ProjectServiceClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'bigquery.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - it('has port', () => { - const port = projectserviceModule.v2.ProjectServiceClient.port; - assert(port); - assert(typeof port === 'number'); + it('value configured in code has priority over environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new projectserviceModule.v2.ProjectServiceClient({ + universeDomain: 'configured.example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'bigquery.configured.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - - it('should create a client with no option', () => { - const client = new projectserviceModule.v2.ProjectServiceClient(); - assert(client); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new projectserviceModule.v2.ProjectServiceClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); + }); - it('should create a client with gRPC fallback', () => { - const client = new projectserviceModule.v2.ProjectServiceClient({ - fallback: true, - }); - assert(client); - }); + it('has port', () => { + const port = projectserviceModule.v2.ProjectServiceClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('has initialize method and supports deferred initialization', async () => { - const client = new projectserviceModule.v2.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.projectServiceStub, undefined); - await client.initialize(); - assert(client.projectServiceStub); - }); + it('should create a client with no option', () => { + const client = new projectserviceModule.v2.ProjectServiceClient(); + assert(client); + }); - it('has close method for the initialized client', done => { - const client = new projectserviceModule.v2.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.projectServiceStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('should create a client with gRPC fallback', () => { + const client = new projectserviceModule.v2.ProjectServiceClient({ + fallback: true, + }); + assert(client); + }); - it('has close method for the non-initialized client', done => { - const client = new projectserviceModule.v2.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.projectServiceStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('has initialize method and supports deferred initialization', async () => { + const client = new projectserviceModule.v2.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.projectServiceStub, undefined); + await client.initialize(); + assert(client.projectServiceStub); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new projectserviceModule.v2.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + it('has close method for the initialized client', (done) => { + const client = new projectserviceModule.v2.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.projectServiceStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new projectserviceModule.v2.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId((err?: Error|null, projectId?: string|null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } - }); - }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); + it('has close method for the non-initialized client', (done) => { + const client = new projectserviceModule.v2.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.projectServiceStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); }); - describe('getServiceAccount', () => { - it('invokes getServiceAccount without error', async () => { - const client = new projectserviceModule.v2.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.GetServiceAccountRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetServiceAccountRequest', ['projectId']); - request.projectId = defaultValue1; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.bigquery.v2.GetServiceAccountResponse() - ); - client.innerApiCalls.getServiceAccount = stubSimpleCall(expectedResponse); - const [response] = await client.getServiceAccount(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getServiceAccount as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getServiceAccount as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new projectserviceModule.v2.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + }); - it('invokes getServiceAccount without error using callback', async () => { - const client = new projectserviceModule.v2.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.GetServiceAccountRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetServiceAccountRequest', ['projectId']); - request.projectId = defaultValue1; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.bigquery.v2.GetServiceAccountResponse() - ); - client.innerApiCalls.getServiceAccount = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getServiceAccount( - request, - (err?: Error|null, result?: protos.google.cloud.bigquery.v2.IGetServiceAccountResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getServiceAccount as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getServiceAccount as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new projectserviceModule.v2.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + }); - it('invokes getServiceAccount with error', async () => { - const client = new projectserviceModule.v2.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.GetServiceAccountRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetServiceAccountRequest', ['projectId']); - request.projectId = defaultValue1; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getServiceAccount = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getServiceAccount(request), expectedError); - const actualRequest = (client.innerApiCalls.getServiceAccount as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getServiceAccount as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + describe('getServiceAccount', () => { + it('invokes getServiceAccount without error', async () => { + const client = new projectserviceModule.v2.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.GetServiceAccountRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetServiceAccountRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.bigquery.v2.GetServiceAccountResponse(), + ); + client.innerApiCalls.getServiceAccount = stubSimpleCall(expectedResponse); + const [response] = await client.getServiceAccount(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getServiceAccount as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getServiceAccount as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getServiceAccount with closed client', async () => { - const client = new projectserviceModule.v2.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.GetServiceAccountRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetServiceAccountRequest', ['projectId']); - request.projectId = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getServiceAccount(request), expectedError); - }); + it('invokes getServiceAccount without error using callback', async () => { + const client = new projectserviceModule.v2.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.GetServiceAccountRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetServiceAccountRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.bigquery.v2.GetServiceAccountResponse(), + ); + client.innerApiCalls.getServiceAccount = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getServiceAccount( + request, + ( + err?: Error | null, + result?: protos.google.cloud.bigquery.v2.IGetServiceAccountResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getServiceAccount as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getServiceAccount as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getServiceAccount with error', async () => { + const client = new projectserviceModule.v2.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.GetServiceAccountRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetServiceAccountRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getServiceAccount = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getServiceAccount(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getServiceAccount as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getServiceAccount as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getServiceAccount with closed client', async () => { + const client = new projectserviceModule.v2.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.GetServiceAccountRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetServiceAccountRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getServiceAccount(request), expectedError); }); + }); }); diff --git a/core/generator/gapic-generator-typescript/baselines/bigquery-v2/test/gapic_routine_service_v2.ts.baseline b/core/generator/gapic-generator-typescript/baselines/bigquery-v2/test/gapic_routine_service_v2.ts.baseline index 20fc2d9d3f87..3db8bc458dad 100644 --- a/core/generator/gapic-generator-typescript/baselines/bigquery-v2/test/gapic_routine_service_v2.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/bigquery-v2/test/gapic_routine_service_v2.ts.baseline @@ -19,1100 +19,1392 @@ import * as protos from '../protos/protos'; import * as assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as routineserviceModule from '../src'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; -import {protobuf} from 'google-gax'; +import { protobuf } from 'google-gax'; // Dynamically loaded proto JSON is needed to get the type information // to fill in default values for request objects -const root = protobuf.Root.fromJSON(require('../protos/protos.json')).resolveAll(); +const root = protobuf.Root.fromJSON( + require('../protos/protos.json'), +).resolveAll(); // eslint-disable-next-line @typescript-eslint/no-unused-vars function getTypeDefaultValue(typeName: string, fields: string[]) { - let type = root.lookupType(typeName) as protobuf.Type; - for (const field of fields.slice(0, -1)) { - type = type.fields[field]?.resolvedType as protobuf.Type; - } - return type.fields[fields[fields.length - 1]]?.defaultValue; + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type.fields[field]?.resolvedType as protobuf.Type; + } + return type.fields[fields[fields.length - 1]]?.defaultValue; } function generateSampleMessage(instance: T) { - const filledObject = (instance.constructor as typeof protobuf.Message) - .toObject(instance as protobuf.Message, {defaults: true}); - return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, { defaults: true }); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; } function stubSimpleCall(response?: ResponseType, error?: Error) { - return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); } -function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { - return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +function stubSimpleCallWithCallback( + response?: ResponseType, + error?: Error, +) { + return error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); } -function stubPageStreamingCall(responses?: ResponseType[], error?: Error) { - const pagingStub = sinon.stub(); - if (responses) { - for (let i = 0; i < responses.length; ++i) { - pagingStub.onCall(i).callsArgWith(2, null, responses[i]); - } +function stubPageStreamingCall( + responses?: ResponseType[], + error?: Error, +) { + const pagingStub = sinon.stub(); + if (responses) { + for (let i = 0; i < responses.length; ++i) { + pagingStub.onCall(i).callsArgWith(2, null, responses[i]); } - const transformStub = error ? sinon.stub().callsArgWith(2, error) : pagingStub; - const mockStream = new PassThrough({ - objectMode: true, - transform: transformStub, - }); - // trigger as many responses as needed - if (responses) { - for (let i = 0; i < responses.length; ++i) { - setImmediate(() => { mockStream.write({}); }); - } - setImmediate(() => { mockStream.end(); }); - } else { - setImmediate(() => { mockStream.write({}); }); - setImmediate(() => { mockStream.end(); }); + } + const transformStub = error + ? sinon.stub().callsArgWith(2, error) + : pagingStub; + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + // trigger as many responses as needed + if (responses) { + for (let i = 0; i < responses.length; ++i) { + setImmediate(() => { + mockStream.write({}); + }); } - return sinon.stub().returns(mockStream); + setImmediate(() => { + mockStream.end(); + }); + } else { + setImmediate(() => { + mockStream.write({}); + }); + setImmediate(() => { + mockStream.end(); + }); + } + return sinon.stub().returns(mockStream); } -function stubAsyncIterationCall(responses?: ResponseType[], error?: Error) { - let counter = 0; - const asyncIterable = { - [Symbol.asyncIterator]() { - return { - async next() { - if (error) { - return Promise.reject(error); - } - if (counter >= responses!.length) { - return Promise.resolve({done: true, value: undefined}); - } - return Promise.resolve({done: false, value: responses![counter++]}); - } - }; - } - }; - return sinon.stub().returns(asyncIterable); +function stubAsyncIterationCall( + responses?: ResponseType[], + error?: Error, +) { + let counter = 0; + const asyncIterable = { + [Symbol.asyncIterator]() { + return { + async next() { + if (error) { + return Promise.reject(error); + } + if (counter >= responses!.length) { + return Promise.resolve({ done: true, value: undefined }); + } + return Promise.resolve({ done: false, value: responses![counter++] }); + }, + }; + }, + }; + return sinon.stub().returns(asyncIterable); } describe('v2.RoutineServiceClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new routineserviceModule.v2.RoutineServiceClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'bigquery.googleapis.com'); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new routineserviceModule.v2.RoutineServiceClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'bigquery.googleapis.com'); + }); - it('has universeDomain', () => { - const client = new routineserviceModule.v2.RoutineServiceClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); + it('has universeDomain', () => { + const client = new routineserviceModule.v2.RoutineServiceClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - it('throws DeprecationWarning if static servicePath is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const servicePath = routineserviceModule.v2.RoutineServiceClient.servicePath; - assert.strictEqual(servicePath, 'bigquery.googleapis.com'); - assert(stub.called); - stub.restore(); - }); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = + routineserviceModule.v2.RoutineServiceClient.servicePath; + assert.strictEqual(servicePath, 'bigquery.googleapis.com'); + assert(stub.called); + stub.restore(); + }); - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = routineserviceModule.v2.RoutineServiceClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'bigquery.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new routineserviceModule.v2.RoutineServiceClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'bigquery.example.com'); + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + routineserviceModule.v2.RoutineServiceClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'bigquery.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = new routineserviceModule.v2.RoutineServiceClient({ + universeDomain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'bigquery.example.com'); + }); + + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = new routineserviceModule.v2.RoutineServiceClient({ + universe_domain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'bigquery.example.com'); + }); + + if (typeof process === 'object' && 'env' in process) { + describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { + it('sets apiEndpoint from environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new routineserviceModule.v2.RoutineServiceClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'bigquery.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new routineserviceModule.v2.RoutineServiceClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'bigquery.example.com'); + it('value configured in code has priority over environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new routineserviceModule.v2.RoutineServiceClient({ + universeDomain: 'configured.example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'bigquery.configured.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new routineserviceModule.v2.RoutineServiceClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', + }); + }); + }); - if (typeof process === 'object' && 'env' in process) { - describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { - it('sets apiEndpoint from environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new routineserviceModule.v2.RoutineServiceClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'bigquery.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); + it('has port', () => { + const port = routineserviceModule.v2.RoutineServiceClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('value configured in code has priority over environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new routineserviceModule.v2.RoutineServiceClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'bigquery.configured.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { new routineserviceModule.v2.RoutineServiceClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); + it('should create a client with no option', () => { + const client = new routineserviceModule.v2.RoutineServiceClient(); + assert(client); + }); - it('has port', () => { - const port = routineserviceModule.v2.RoutineServiceClient.port; - assert(port); - assert(typeof port === 'number'); - }); + it('should create a client with gRPC fallback', () => { + const client = new routineserviceModule.v2.RoutineServiceClient({ + fallback: true, + }); + assert(client); + }); - it('should create a client with no option', () => { - const client = new routineserviceModule.v2.RoutineServiceClient(); - assert(client); - }); + it('has initialize method and supports deferred initialization', async () => { + const client = new routineserviceModule.v2.RoutineServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.routineServiceStub, undefined); + await client.initialize(); + assert(client.routineServiceStub); + }); - it('should create a client with gRPC fallback', () => { - const client = new routineserviceModule.v2.RoutineServiceClient({ - fallback: true, - }); - assert(client); + it('has close method for the initialized client', (done) => { + const client = new routineserviceModule.v2.RoutineServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.routineServiceStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('has initialize method and supports deferred initialization', async () => { - const client = new routineserviceModule.v2.RoutineServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.routineServiceStub, undefined); - await client.initialize(); - assert(client.routineServiceStub); + it('has close method for the non-initialized client', (done) => { + const client = new routineserviceModule.v2.RoutineServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.routineServiceStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('has close method for the initialized client', done => { - const client = new routineserviceModule.v2.RoutineServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.routineServiceStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new routineserviceModule.v2.RoutineServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + }); - it('has close method for the non-initialized client', done => { - const client = new routineserviceModule.v2.RoutineServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.routineServiceStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new routineserviceModule.v2.RoutineServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new routineserviceModule.v2.RoutineServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); - }); + describe('getRoutine', () => { + it('invokes getRoutine without error', async () => { + const client = new routineserviceModule.v2.RoutineServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.GetRoutineRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetRoutineRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetRoutineRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const defaultValue3 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetRoutineRequest', + ['routineId'], + ); + request.routineId = defaultValue3; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}&routine_id=${defaultValue3 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.bigquery.v2.Routine(), + ); + client.innerApiCalls.getRoutine = stubSimpleCall(expectedResponse); + const [response] = await client.getRoutine(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getRoutine as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getRoutine as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new routineserviceModule.v2.RoutineServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId((err?: Error|null, projectId?: string|null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } - }); - }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); - }); + it('invokes getRoutine without error using callback', async () => { + const client = new routineserviceModule.v2.RoutineServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.GetRoutineRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetRoutineRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetRoutineRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const defaultValue3 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetRoutineRequest', + ['routineId'], + ); + request.routineId = defaultValue3; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}&routine_id=${defaultValue3 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.bigquery.v2.Routine(), + ); + client.innerApiCalls.getRoutine = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getRoutine( + request, + ( + err?: Error | null, + result?: protos.google.cloud.bigquery.v2.IRoutine | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getRoutine as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getRoutine as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('getRoutine', () => { - it('invokes getRoutine without error', async () => { - const client = new routineserviceModule.v2.RoutineServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.GetRoutineRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetRoutineRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetRoutineRequest', ['datasetId']); - request.datasetId = defaultValue2; - const defaultValue3 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetRoutineRequest', ['routineId']); - request.routineId = defaultValue3; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }&routine_id=${defaultValue3 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.bigquery.v2.Routine() - ); - client.innerApiCalls.getRoutine = stubSimpleCall(expectedResponse); - const [response] = await client.getRoutine(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getRoutine as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getRoutine as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getRoutine with error', async () => { + const client = new routineserviceModule.v2.RoutineServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.GetRoutineRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetRoutineRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetRoutineRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const defaultValue3 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetRoutineRequest', + ['routineId'], + ); + request.routineId = defaultValue3; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}&routine_id=${defaultValue3 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getRoutine = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getRoutine(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getRoutine as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getRoutine as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getRoutine without error using callback', async () => { - const client = new routineserviceModule.v2.RoutineServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.GetRoutineRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetRoutineRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetRoutineRequest', ['datasetId']); - request.datasetId = defaultValue2; - const defaultValue3 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetRoutineRequest', ['routineId']); - request.routineId = defaultValue3; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }&routine_id=${defaultValue3 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.bigquery.v2.Routine() - ); - client.innerApiCalls.getRoutine = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getRoutine( - request, - (err?: Error|null, result?: protos.google.cloud.bigquery.v2.IRoutine|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getRoutine as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getRoutine as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getRoutine with closed client', async () => { + const client = new routineserviceModule.v2.RoutineServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.GetRoutineRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetRoutineRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetRoutineRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const defaultValue3 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetRoutineRequest', + ['routineId'], + ); + request.routineId = defaultValue3; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getRoutine(request), expectedError); + }); + }); - it('invokes getRoutine with error', async () => { - const client = new routineserviceModule.v2.RoutineServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.GetRoutineRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetRoutineRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetRoutineRequest', ['datasetId']); - request.datasetId = defaultValue2; - const defaultValue3 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetRoutineRequest', ['routineId']); - request.routineId = defaultValue3; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }&routine_id=${defaultValue3 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getRoutine = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getRoutine(request), expectedError); - const actualRequest = (client.innerApiCalls.getRoutine as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getRoutine as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + describe('insertRoutine', () => { + it('invokes insertRoutine without error', async () => { + const client = new routineserviceModule.v2.RoutineServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.InsertRoutineRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.InsertRoutineRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.InsertRoutineRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.bigquery.v2.Routine(), + ); + client.innerApiCalls.insertRoutine = stubSimpleCall(expectedResponse); + const [response] = await client.insertRoutine(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.insertRoutine as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.insertRoutine as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getRoutine with closed client', async () => { - const client = new routineserviceModule.v2.RoutineServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.GetRoutineRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetRoutineRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetRoutineRequest', ['datasetId']); - request.datasetId = defaultValue2; - const defaultValue3 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetRoutineRequest', ['routineId']); - request.routineId = defaultValue3; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getRoutine(request), expectedError); - }); + it('invokes insertRoutine without error using callback', async () => { + const client = new routineserviceModule.v2.RoutineServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.InsertRoutineRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.InsertRoutineRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.InsertRoutineRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.bigquery.v2.Routine(), + ); + client.innerApiCalls.insertRoutine = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.insertRoutine( + request, + ( + err?: Error | null, + result?: protos.google.cloud.bigquery.v2.IRoutine | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.insertRoutine as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.insertRoutine as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('insertRoutine', () => { - it('invokes insertRoutine without error', async () => { - const client = new routineserviceModule.v2.RoutineServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.InsertRoutineRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.InsertRoutineRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.InsertRoutineRequest', ['datasetId']); - request.datasetId = defaultValue2; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.bigquery.v2.Routine() - ); - client.innerApiCalls.insertRoutine = stubSimpleCall(expectedResponse); - const [response] = await client.insertRoutine(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.insertRoutine as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.insertRoutine as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes insertRoutine with error', async () => { + const client = new routineserviceModule.v2.RoutineServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.InsertRoutineRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.InsertRoutineRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.InsertRoutineRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.insertRoutine = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.insertRoutine(request), expectedError); + const actualRequest = ( + client.innerApiCalls.insertRoutine as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.insertRoutine as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes insertRoutine without error using callback', async () => { - const client = new routineserviceModule.v2.RoutineServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.InsertRoutineRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.InsertRoutineRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.InsertRoutineRequest', ['datasetId']); - request.datasetId = defaultValue2; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.bigquery.v2.Routine() - ); - client.innerApiCalls.insertRoutine = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.insertRoutine( - request, - (err?: Error|null, result?: protos.google.cloud.bigquery.v2.IRoutine|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.insertRoutine as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.insertRoutine as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes insertRoutine with closed client', async () => { + const client = new routineserviceModule.v2.RoutineServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.InsertRoutineRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.InsertRoutineRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.InsertRoutineRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.insertRoutine(request), expectedError); + }); + }); - it('invokes insertRoutine with error', async () => { - const client = new routineserviceModule.v2.RoutineServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.InsertRoutineRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.InsertRoutineRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.InsertRoutineRequest', ['datasetId']); - request.datasetId = defaultValue2; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.insertRoutine = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.insertRoutine(request), expectedError); - const actualRequest = (client.innerApiCalls.insertRoutine as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.insertRoutine as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + describe('updateRoutine', () => { + it('invokes updateRoutine without error', async () => { + const client = new routineserviceModule.v2.RoutineServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.UpdateRoutineRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.UpdateRoutineRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.UpdateRoutineRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const defaultValue3 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.UpdateRoutineRequest', + ['routineId'], + ); + request.routineId = defaultValue3; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}&routine_id=${defaultValue3 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.bigquery.v2.Routine(), + ); + client.innerApiCalls.updateRoutine = stubSimpleCall(expectedResponse); + const [response] = await client.updateRoutine(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateRoutine as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateRoutine as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes insertRoutine with closed client', async () => { - const client = new routineserviceModule.v2.RoutineServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.InsertRoutineRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.InsertRoutineRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.InsertRoutineRequest', ['datasetId']); - request.datasetId = defaultValue2; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.insertRoutine(request), expectedError); - }); + it('invokes updateRoutine without error using callback', async () => { + const client = new routineserviceModule.v2.RoutineServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.UpdateRoutineRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.UpdateRoutineRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.UpdateRoutineRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const defaultValue3 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.UpdateRoutineRequest', + ['routineId'], + ); + request.routineId = defaultValue3; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}&routine_id=${defaultValue3 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.bigquery.v2.Routine(), + ); + client.innerApiCalls.updateRoutine = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateRoutine( + request, + ( + err?: Error | null, + result?: protos.google.cloud.bigquery.v2.IRoutine | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateRoutine as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateRoutine as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('updateRoutine', () => { - it('invokes updateRoutine without error', async () => { - const client = new routineserviceModule.v2.RoutineServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.UpdateRoutineRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.UpdateRoutineRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.UpdateRoutineRequest', ['datasetId']); - request.datasetId = defaultValue2; - const defaultValue3 = - getTypeDefaultValue('.google.cloud.bigquery.v2.UpdateRoutineRequest', ['routineId']); - request.routineId = defaultValue3; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }&routine_id=${defaultValue3 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.bigquery.v2.Routine() - ); - client.innerApiCalls.updateRoutine = stubSimpleCall(expectedResponse); - const [response] = await client.updateRoutine(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateRoutine as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateRoutine as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateRoutine with error', async () => { + const client = new routineserviceModule.v2.RoutineServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.UpdateRoutineRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.UpdateRoutineRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.UpdateRoutineRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const defaultValue3 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.UpdateRoutineRequest', + ['routineId'], + ); + request.routineId = defaultValue3; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}&routine_id=${defaultValue3 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateRoutine = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.updateRoutine(request), expectedError); + const actualRequest = ( + client.innerApiCalls.updateRoutine as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateRoutine as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateRoutine without error using callback', async () => { - const client = new routineserviceModule.v2.RoutineServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.UpdateRoutineRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.UpdateRoutineRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.UpdateRoutineRequest', ['datasetId']); - request.datasetId = defaultValue2; - const defaultValue3 = - getTypeDefaultValue('.google.cloud.bigquery.v2.UpdateRoutineRequest', ['routineId']); - request.routineId = defaultValue3; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }&routine_id=${defaultValue3 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.bigquery.v2.Routine() - ); - client.innerApiCalls.updateRoutine = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateRoutine( - request, - (err?: Error|null, result?: protos.google.cloud.bigquery.v2.IRoutine|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateRoutine as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateRoutine as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateRoutine with closed client', async () => { + const client = new routineserviceModule.v2.RoutineServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.UpdateRoutineRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.UpdateRoutineRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.UpdateRoutineRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const defaultValue3 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.UpdateRoutineRequest', + ['routineId'], + ); + request.routineId = defaultValue3; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.updateRoutine(request), expectedError); + }); + }); - it('invokes updateRoutine with error', async () => { - const client = new routineserviceModule.v2.RoutineServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.UpdateRoutineRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.UpdateRoutineRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.UpdateRoutineRequest', ['datasetId']); - request.datasetId = defaultValue2; - const defaultValue3 = - getTypeDefaultValue('.google.cloud.bigquery.v2.UpdateRoutineRequest', ['routineId']); - request.routineId = defaultValue3; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }&routine_id=${defaultValue3 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateRoutine = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateRoutine(request), expectedError); - const actualRequest = (client.innerApiCalls.updateRoutine as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateRoutine as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + describe('patchRoutine', () => { + it('invokes patchRoutine without error', async () => { + const client = new routineserviceModule.v2.RoutineServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.PatchRoutineRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.cloud.bigquery.v2.Routine(), + ); + client.innerApiCalls.patchRoutine = stubSimpleCall(expectedResponse); + const [response] = await client.patchRoutine(request); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes updateRoutine with closed client', async () => { - const client = new routineserviceModule.v2.RoutineServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.UpdateRoutineRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.UpdateRoutineRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.UpdateRoutineRequest', ['datasetId']); - request.datasetId = defaultValue2; - const defaultValue3 = - getTypeDefaultValue('.google.cloud.bigquery.v2.UpdateRoutineRequest', ['routineId']); - request.routineId = defaultValue3; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateRoutine(request), expectedError); - }); + it('invokes patchRoutine without error using callback', async () => { + const client = new routineserviceModule.v2.RoutineServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.PatchRoutineRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.cloud.bigquery.v2.Routine(), + ); + client.innerApiCalls.patchRoutine = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.patchRoutine( + request, + ( + err?: Error | null, + result?: protos.google.cloud.bigquery.v2.IRoutine | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); }); - describe('patchRoutine', () => { - it('invokes patchRoutine without error', async () => { - const client = new routineserviceModule.v2.RoutineServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.PatchRoutineRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.cloud.bigquery.v2.Routine() - ); - client.innerApiCalls.patchRoutine = stubSimpleCall(expectedResponse); - const [response] = await client.patchRoutine(request); - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes patchRoutine with error', async () => { + const client = new routineserviceModule.v2.RoutineServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.PatchRoutineRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.patchRoutine = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.patchRoutine(request), expectedError); + }); - it('invokes patchRoutine without error using callback', async () => { - const client = new routineserviceModule.v2.RoutineServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.PatchRoutineRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.cloud.bigquery.v2.Routine() - ); - client.innerApiCalls.patchRoutine = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.patchRoutine( - request, - (err?: Error|null, result?: protos.google.cloud.bigquery.v2.IRoutine|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes patchRoutine with closed client', async () => { + const client = new routineserviceModule.v2.RoutineServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.PatchRoutineRequest(), + ); + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.patchRoutine(request), expectedError); + }); + }); - it('invokes patchRoutine with error', async () => { - const client = new routineserviceModule.v2.RoutineServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.PatchRoutineRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.patchRoutine = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.patchRoutine(request), expectedError); - }); + describe('deleteRoutine', () => { + it('invokes deleteRoutine without error', async () => { + const client = new routineserviceModule.v2.RoutineServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.DeleteRoutineRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.DeleteRoutineRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.DeleteRoutineRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const defaultValue3 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.DeleteRoutineRequest', + ['routineId'], + ); + request.routineId = defaultValue3; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}&routine_id=${defaultValue3 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteRoutine = stubSimpleCall(expectedResponse); + const [response] = await client.deleteRoutine(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteRoutine as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteRoutine as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes patchRoutine with closed client', async () => { - const client = new routineserviceModule.v2.RoutineServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.PatchRoutineRequest() - ); - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.patchRoutine(request), expectedError); - }); + it('invokes deleteRoutine without error using callback', async () => { + const client = new routineserviceModule.v2.RoutineServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.DeleteRoutineRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.DeleteRoutineRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.DeleteRoutineRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const defaultValue3 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.DeleteRoutineRequest', + ['routineId'], + ); + request.routineId = defaultValue3; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}&routine_id=${defaultValue3 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteRoutine = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteRoutine( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteRoutine as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteRoutine as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('deleteRoutine', () => { - it('invokes deleteRoutine without error', async () => { - const client = new routineserviceModule.v2.RoutineServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.DeleteRoutineRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.DeleteRoutineRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.DeleteRoutineRequest', ['datasetId']); - request.datasetId = defaultValue2; - const defaultValue3 = - getTypeDefaultValue('.google.cloud.bigquery.v2.DeleteRoutineRequest', ['routineId']); - request.routineId = defaultValue3; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }&routine_id=${defaultValue3 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteRoutine = stubSimpleCall(expectedResponse); - const [response] = await client.deleteRoutine(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteRoutine as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteRoutine as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteRoutine with error', async () => { + const client = new routineserviceModule.v2.RoutineServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.DeleteRoutineRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.DeleteRoutineRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.DeleteRoutineRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const defaultValue3 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.DeleteRoutineRequest', + ['routineId'], + ); + request.routineId = defaultValue3; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}&routine_id=${defaultValue3 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteRoutine = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.deleteRoutine(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteRoutine as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteRoutine as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteRoutine without error using callback', async () => { - const client = new routineserviceModule.v2.RoutineServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.DeleteRoutineRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.DeleteRoutineRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.DeleteRoutineRequest', ['datasetId']); - request.datasetId = defaultValue2; - const defaultValue3 = - getTypeDefaultValue('.google.cloud.bigquery.v2.DeleteRoutineRequest', ['routineId']); - request.routineId = defaultValue3; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }&routine_id=${defaultValue3 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteRoutine = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteRoutine( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteRoutine as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteRoutine as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteRoutine with closed client', async () => { + const client = new routineserviceModule.v2.RoutineServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.DeleteRoutineRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.DeleteRoutineRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.DeleteRoutineRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const defaultValue3 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.DeleteRoutineRequest', + ['routineId'], + ); + request.routineId = defaultValue3; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.deleteRoutine(request), expectedError); + }); + }); - it('invokes deleteRoutine with error', async () => { - const client = new routineserviceModule.v2.RoutineServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.DeleteRoutineRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.DeleteRoutineRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.DeleteRoutineRequest', ['datasetId']); - request.datasetId = defaultValue2; - const defaultValue3 = - getTypeDefaultValue('.google.cloud.bigquery.v2.DeleteRoutineRequest', ['routineId']); - request.routineId = defaultValue3; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }&routine_id=${defaultValue3 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteRoutine = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteRoutine(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteRoutine as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteRoutine as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + describe('listRoutines', () => { + it('invokes listRoutines without error', async () => { + const client = new routineserviceModule.v2.RoutineServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListRoutinesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListRoutinesRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListRoutinesRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.bigquery.v2.Routine()), + generateSampleMessage(new protos.google.cloud.bigquery.v2.Routine()), + generateSampleMessage(new protos.google.cloud.bigquery.v2.Routine()), + ]; + client.innerApiCalls.listRoutines = stubSimpleCall(expectedResponse); + const [response] = await client.listRoutines(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listRoutines as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listRoutines as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteRoutine with closed client', async () => { - const client = new routineserviceModule.v2.RoutineServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.DeleteRoutineRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.DeleteRoutineRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.DeleteRoutineRequest', ['datasetId']); - request.datasetId = defaultValue2; - const defaultValue3 = - getTypeDefaultValue('.google.cloud.bigquery.v2.DeleteRoutineRequest', ['routineId']); - request.routineId = defaultValue3; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteRoutine(request), expectedError); - }); + it('invokes listRoutines without error using callback', async () => { + const client = new routineserviceModule.v2.RoutineServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListRoutinesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListRoutinesRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListRoutinesRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.bigquery.v2.Routine()), + generateSampleMessage(new protos.google.cloud.bigquery.v2.Routine()), + generateSampleMessage(new protos.google.cloud.bigquery.v2.Routine()), + ]; + client.innerApiCalls.listRoutines = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listRoutines( + request, + ( + err?: Error | null, + result?: protos.google.cloud.bigquery.v2.IRoutine[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listRoutines as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listRoutines as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('listRoutines', () => { - it('invokes listRoutines without error', async () => { - const client = new routineserviceModule.v2.RoutineServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.ListRoutinesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListRoutinesRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListRoutinesRequest', ['datasetId']); - request.datasetId = defaultValue2; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.bigquery.v2.Routine()), - generateSampleMessage(new protos.google.cloud.bigquery.v2.Routine()), - generateSampleMessage(new protos.google.cloud.bigquery.v2.Routine()), - ]; - client.innerApiCalls.listRoutines = stubSimpleCall(expectedResponse); - const [response] = await client.listRoutines(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listRoutines as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listRoutines as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listRoutines with error', async () => { + const client = new routineserviceModule.v2.RoutineServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListRoutinesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListRoutinesRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListRoutinesRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listRoutines = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listRoutines(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listRoutines as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listRoutines as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listRoutines without error using callback', async () => { - const client = new routineserviceModule.v2.RoutineServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.ListRoutinesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListRoutinesRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListRoutinesRequest', ['datasetId']); - request.datasetId = defaultValue2; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.bigquery.v2.Routine()), - generateSampleMessage(new protos.google.cloud.bigquery.v2.Routine()), - generateSampleMessage(new protos.google.cloud.bigquery.v2.Routine()), - ]; - client.innerApiCalls.listRoutines = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listRoutines( - request, - (err?: Error|null, result?: protos.google.cloud.bigquery.v2.IRoutine[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listRoutines as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listRoutines as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes listRoutinesStream without error', async () => { + const client = new routineserviceModule.v2.RoutineServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListRoutinesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListRoutinesRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListRoutinesRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.bigquery.v2.Routine()), + generateSampleMessage(new protos.google.cloud.bigquery.v2.Routine()), + generateSampleMessage(new protos.google.cloud.bigquery.v2.Routine()), + ]; + client.descriptors.page.listRoutines.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listRoutinesStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.cloud.bigquery.v2.Routine[] = []; + stream.on( + 'data', + (response: protos.google.cloud.bigquery.v2.Routine) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); }); - - it('invokes listRoutines with error', async () => { - const client = new routineserviceModule.v2.RoutineServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.ListRoutinesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListRoutinesRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListRoutinesRequest', ['datasetId']); - request.datasetId = defaultValue2; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listRoutines = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listRoutines(request), expectedError); - const actualRequest = (client.innerApiCalls.listRoutines as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listRoutines as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + stream.on('error', (err: Error) => { + reject(err); }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listRoutines.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listRoutines, request), + ); + assert( + (client.descriptors.page.listRoutines.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('invokes listRoutinesStream without error', async () => { - const client = new routineserviceModule.v2.RoutineServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.ListRoutinesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListRoutinesRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListRoutinesRequest', ['datasetId']); - request.datasetId = defaultValue2; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.bigquery.v2.Routine()), - generateSampleMessage(new protos.google.cloud.bigquery.v2.Routine()), - generateSampleMessage(new protos.google.cloud.bigquery.v2.Routine()), - ]; - client.descriptors.page.listRoutines.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listRoutinesStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.cloud.bigquery.v2.Routine[] = []; - stream.on('data', (response: protos.google.cloud.bigquery.v2.Routine) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.listRoutines.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listRoutines, request)); - assert( - (client.descriptors.page.listRoutines.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); + it('invokes listRoutinesStream with error', async () => { + const client = new routineserviceModule.v2.RoutineServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListRoutinesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListRoutinesRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListRoutinesRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listRoutines.createStream = stubPageStreamingCall( + undefined, + expectedError, + ); + const stream = client.listRoutinesStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.cloud.bigquery.v2.Routine[] = []; + stream.on( + 'data', + (response: protos.google.cloud.bigquery.v2.Routine) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); }); - - it('invokes listRoutinesStream with error', async () => { - const client = new routineserviceModule.v2.RoutineServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.ListRoutinesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListRoutinesRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListRoutinesRequest', ['datasetId']); - request.datasetId = defaultValue2; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listRoutines.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listRoutinesStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.cloud.bigquery.v2.Routine[] = []; - stream.on('data', (response: protos.google.cloud.bigquery.v2.Routine) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listRoutines.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listRoutines, request)); - assert( - (client.descriptors.page.listRoutines.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); + stream.on('error', (err: Error) => { + reject(err); }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listRoutines.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listRoutines, request), + ); + assert( + (client.descriptors.page.listRoutines.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('uses async iteration with listRoutines without error', async () => { - const client = new routineserviceModule.v2.RoutineServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.ListRoutinesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListRoutinesRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListRoutinesRequest', ['datasetId']); - request.datasetId = defaultValue2; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.bigquery.v2.Routine()), - generateSampleMessage(new protos.google.cloud.bigquery.v2.Routine()), - generateSampleMessage(new protos.google.cloud.bigquery.v2.Routine()), - ]; - client.descriptors.page.listRoutines.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.cloud.bigquery.v2.IRoutine[] = []; - const iterable = client.listRoutinesAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listRoutines.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listRoutines.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listRoutines without error', async () => { + const client = new routineserviceModule.v2.RoutineServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListRoutinesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListRoutinesRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListRoutinesRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.bigquery.v2.Routine()), + generateSampleMessage(new protos.google.cloud.bigquery.v2.Routine()), + generateSampleMessage(new protos.google.cloud.bigquery.v2.Routine()), + ]; + client.descriptors.page.listRoutines.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.cloud.bigquery.v2.IRoutine[] = []; + const iterable = client.listRoutinesAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listRoutines.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listRoutines.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('uses async iteration with listRoutines with error', async () => { - const client = new routineserviceModule.v2.RoutineServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.ListRoutinesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListRoutinesRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListRoutinesRequest', ['datasetId']); - request.datasetId = defaultValue2; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listRoutines.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listRoutinesAsync(request); - await assert.rejects(async () => { - const responses: protos.google.cloud.bigquery.v2.IRoutine[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listRoutines.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listRoutines.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listRoutines with error', async () => { + const client = new routineserviceModule.v2.RoutineServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListRoutinesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListRoutinesRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListRoutinesRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listRoutines.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listRoutinesAsync(request); + await assert.rejects(async () => { + const responses: protos.google.cloud.bigquery.v2.IRoutine[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listRoutines.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listRoutines.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); }); + }); }); diff --git a/core/generator/gapic-generator-typescript/baselines/bigquery-v2/test/gapic_row_access_policy_service_v2.ts.baseline b/core/generator/gapic-generator-typescript/baselines/bigquery-v2/test/gapic_row_access_policy_service_v2.ts.baseline index a6bc8df9a403..dd5d7408c6be 100644 --- a/core/generator/gapic-generator-typescript/baselines/bigquery-v2/test/gapic_row_access_policy_service_v2.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/bigquery-v2/test/gapic_row_access_policy_service_v2.ts.baseline @@ -19,530 +19,744 @@ import * as protos from '../protos/protos'; import * as assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as rowaccesspolicyserviceModule from '../src'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; -import {protobuf} from 'google-gax'; +import { protobuf } from 'google-gax'; // Dynamically loaded proto JSON is needed to get the type information // to fill in default values for request objects -const root = protobuf.Root.fromJSON(require('../protos/protos.json')).resolveAll(); +const root = protobuf.Root.fromJSON( + require('../protos/protos.json'), +).resolveAll(); // eslint-disable-next-line @typescript-eslint/no-unused-vars function getTypeDefaultValue(typeName: string, fields: string[]) { - let type = root.lookupType(typeName) as protobuf.Type; - for (const field of fields.slice(0, -1)) { - type = type.fields[field]?.resolvedType as protobuf.Type; - } - return type.fields[fields[fields.length - 1]]?.defaultValue; + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type.fields[field]?.resolvedType as protobuf.Type; + } + return type.fields[fields[fields.length - 1]]?.defaultValue; } function generateSampleMessage(instance: T) { - const filledObject = (instance.constructor as typeof protobuf.Message) - .toObject(instance as protobuf.Message, {defaults: true}); - return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, { defaults: true }); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; } function stubSimpleCall(response?: ResponseType, error?: Error) { - return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); } -function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { - return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +function stubSimpleCallWithCallback( + response?: ResponseType, + error?: Error, +) { + return error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); } -function stubPageStreamingCall(responses?: ResponseType[], error?: Error) { - const pagingStub = sinon.stub(); - if (responses) { - for (let i = 0; i < responses.length; ++i) { - pagingStub.onCall(i).callsArgWith(2, null, responses[i]); - } +function stubPageStreamingCall( + responses?: ResponseType[], + error?: Error, +) { + const pagingStub = sinon.stub(); + if (responses) { + for (let i = 0; i < responses.length; ++i) { + pagingStub.onCall(i).callsArgWith(2, null, responses[i]); } - const transformStub = error ? sinon.stub().callsArgWith(2, error) : pagingStub; - const mockStream = new PassThrough({ - objectMode: true, - transform: transformStub, - }); - // trigger as many responses as needed - if (responses) { - for (let i = 0; i < responses.length; ++i) { - setImmediate(() => { mockStream.write({}); }); - } - setImmediate(() => { mockStream.end(); }); - } else { - setImmediate(() => { mockStream.write({}); }); - setImmediate(() => { mockStream.end(); }); + } + const transformStub = error + ? sinon.stub().callsArgWith(2, error) + : pagingStub; + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + // trigger as many responses as needed + if (responses) { + for (let i = 0; i < responses.length; ++i) { + setImmediate(() => { + mockStream.write({}); + }); } - return sinon.stub().returns(mockStream); + setImmediate(() => { + mockStream.end(); + }); + } else { + setImmediate(() => { + mockStream.write({}); + }); + setImmediate(() => { + mockStream.end(); + }); + } + return sinon.stub().returns(mockStream); } -function stubAsyncIterationCall(responses?: ResponseType[], error?: Error) { - let counter = 0; - const asyncIterable = { - [Symbol.asyncIterator]() { - return { - async next() { - if (error) { - return Promise.reject(error); - } - if (counter >= responses!.length) { - return Promise.resolve({done: true, value: undefined}); - } - return Promise.resolve({done: false, value: responses![counter++]}); - } - }; - } - }; - return sinon.stub().returns(asyncIterable); +function stubAsyncIterationCall( + responses?: ResponseType[], + error?: Error, +) { + let counter = 0; + const asyncIterable = { + [Symbol.asyncIterator]() { + return { + async next() { + if (error) { + return Promise.reject(error); + } + if (counter >= responses!.length) { + return Promise.resolve({ done: true, value: undefined }); + } + return Promise.resolve({ done: false, value: responses![counter++] }); + }, + }; + }, + }; + return sinon.stub().returns(asyncIterable); } describe('v2.RowAccessPolicyServiceClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new rowaccesspolicyserviceModule.v2.RowAccessPolicyServiceClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'bigquery.googleapis.com'); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = + new rowaccesspolicyserviceModule.v2.RowAccessPolicyServiceClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'bigquery.googleapis.com'); + }); - it('has universeDomain', () => { - const client = new rowaccesspolicyserviceModule.v2.RowAccessPolicyServiceClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); + it('has universeDomain', () => { + const client = + new rowaccesspolicyserviceModule.v2.RowAccessPolicyServiceClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - it('throws DeprecationWarning if static servicePath is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const servicePath = rowaccesspolicyserviceModule.v2.RowAccessPolicyServiceClient.servicePath; - assert.strictEqual(servicePath, 'bigquery.googleapis.com'); - assert(stub.called); - stub.restore(); - }); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = + rowaccesspolicyserviceModule.v2.RowAccessPolicyServiceClient + .servicePath; + assert.strictEqual(servicePath, 'bigquery.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + rowaccesspolicyserviceModule.v2.RowAccessPolicyServiceClient + .apiEndpoint; + assert.strictEqual(apiEndpoint, 'bigquery.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = + new rowaccesspolicyserviceModule.v2.RowAccessPolicyServiceClient({ + universeDomain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'bigquery.example.com'); + }); - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = rowaccesspolicyserviceModule.v2.RowAccessPolicyServiceClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'bigquery.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new rowaccesspolicyserviceModule.v2.RowAccessPolicyServiceClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'bigquery.example.com'); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = + new rowaccesspolicyserviceModule.v2.RowAccessPolicyServiceClient({ + universe_domain: 'example.com', }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'bigquery.example.com'); + }); - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new rowaccesspolicyserviceModule.v2.RowAccessPolicyServiceClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'bigquery.example.com'); + if (typeof process === 'object' && 'env' in process) { + describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { + it('sets apiEndpoint from environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = + new rowaccesspolicyserviceModule.v2.RowAccessPolicyServiceClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'bigquery.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - if (typeof process === 'object' && 'env' in process) { - describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { - it('sets apiEndpoint from environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new rowaccesspolicyserviceModule.v2.RowAccessPolicyServiceClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'bigquery.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - - it('value configured in code has priority over environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new rowaccesspolicyserviceModule.v2.RowAccessPolicyServiceClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'bigquery.configured.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); + it('value configured in code has priority over environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = + new rowaccesspolicyserviceModule.v2.RowAccessPolicyServiceClient({ + universeDomain: 'configured.example.com', }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { new rowaccesspolicyserviceModule.v2.RowAccessPolicyServiceClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'bigquery.configured.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - - it('has port', () => { - const port = rowaccesspolicyserviceModule.v2.RowAccessPolicyServiceClient.port; - assert(port); - assert(typeof port === 'number'); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new rowaccesspolicyserviceModule.v2.RowAccessPolicyServiceClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); + }); - it('should create a client with no option', () => { - const client = new rowaccesspolicyserviceModule.v2.RowAccessPolicyServiceClient(); - assert(client); - }); + it('has port', () => { + const port = + rowaccesspolicyserviceModule.v2.RowAccessPolicyServiceClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('should create a client with gRPC fallback', () => { - const client = new rowaccesspolicyserviceModule.v2.RowAccessPolicyServiceClient({ - fallback: true, - }); - assert(client); - }); + it('should create a client with no option', () => { + const client = + new rowaccesspolicyserviceModule.v2.RowAccessPolicyServiceClient(); + assert(client); + }); - it('has initialize method and supports deferred initialization', async () => { - const client = new rowaccesspolicyserviceModule.v2.RowAccessPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.rowAccessPolicyServiceStub, undefined); - await client.initialize(); - assert(client.rowAccessPolicyServiceStub); + it('should create a client with gRPC fallback', () => { + const client = + new rowaccesspolicyserviceModule.v2.RowAccessPolicyServiceClient({ + fallback: true, }); + assert(client); + }); - it('has close method for the initialized client', done => { - const client = new rowaccesspolicyserviceModule.v2.RowAccessPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.rowAccessPolicyServiceStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); + it('has initialize method and supports deferred initialization', async () => { + const client = + new rowaccesspolicyserviceModule.v2.RowAccessPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + assert.strictEqual(client.rowAccessPolicyServiceStub, undefined); + await client.initialize(); + assert(client.rowAccessPolicyServiceStub); + }); - it('has close method for the non-initialized client', done => { - const client = new rowaccesspolicyserviceModule.v2.RowAccessPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.rowAccessPolicyServiceStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); + it('has close method for the initialized client', (done) => { + const client = + new rowaccesspolicyserviceModule.v2.RowAccessPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.rowAccessPolicyServiceStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new rowaccesspolicyserviceModule.v2.RowAccessPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + it('has close method for the non-initialized client', (done) => { + const client = + new rowaccesspolicyserviceModule.v2.RowAccessPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.rowAccessPolicyServiceStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new rowaccesspolicyserviceModule.v2.RowAccessPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId((err?: Error|null, projectId?: string|null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } - }); - }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = + new rowaccesspolicyserviceModule.v2.RowAccessPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); }); - describe('listRowAccessPolicies', () => { - it('invokes listRowAccessPolicies without error', async () => { - const client = new rowaccesspolicyserviceModule.v2.RowAccessPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.ListRowAccessPoliciesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListRowAccessPoliciesRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListRowAccessPoliciesRequest', ['datasetId']); - request.datasetId = defaultValue2; - const defaultValue3 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListRowAccessPoliciesRequest', ['tableId']); - request.tableId = defaultValue3; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }&table_id=${defaultValue3 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.bigquery.v2.RowAccessPolicy()), - generateSampleMessage(new protos.google.cloud.bigquery.v2.RowAccessPolicy()), - generateSampleMessage(new protos.google.cloud.bigquery.v2.RowAccessPolicy()), - ]; - client.innerApiCalls.listRowAccessPolicies = stubSimpleCall(expectedResponse); - const [response] = await client.listRowAccessPolicies(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listRowAccessPolicies as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listRowAccessPolicies as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = + new rowaccesspolicyserviceModule.v2.RowAccessPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } + }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + }); + + describe('listRowAccessPolicies', () => { + it('invokes listRowAccessPolicies without error', async () => { + const client = + new rowaccesspolicyserviceModule.v2.RowAccessPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListRowAccessPoliciesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListRowAccessPoliciesRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListRowAccessPoliciesRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const defaultValue3 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListRowAccessPoliciesRequest', + ['tableId'], + ); + request.tableId = defaultValue3; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}&table_id=${defaultValue3 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.cloud.bigquery.v2.RowAccessPolicy(), + ), + generateSampleMessage( + new protos.google.cloud.bigquery.v2.RowAccessPolicy(), + ), + generateSampleMessage( + new protos.google.cloud.bigquery.v2.RowAccessPolicy(), + ), + ]; + client.innerApiCalls.listRowAccessPolicies = + stubSimpleCall(expectedResponse); + const [response] = await client.listRowAccessPolicies(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listRowAccessPolicies as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listRowAccessPolicies as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listRowAccessPolicies without error using callback', async () => { - const client = new rowaccesspolicyserviceModule.v2.RowAccessPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.ListRowAccessPoliciesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListRowAccessPoliciesRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListRowAccessPoliciesRequest', ['datasetId']); - request.datasetId = defaultValue2; - const defaultValue3 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListRowAccessPoliciesRequest', ['tableId']); - request.tableId = defaultValue3; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }&table_id=${defaultValue3 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.bigquery.v2.RowAccessPolicy()), - generateSampleMessage(new protos.google.cloud.bigquery.v2.RowAccessPolicy()), - generateSampleMessage(new protos.google.cloud.bigquery.v2.RowAccessPolicy()), - ]; - client.innerApiCalls.listRowAccessPolicies = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listRowAccessPolicies( - request, - (err?: Error|null, result?: protos.google.cloud.bigquery.v2.IRowAccessPolicy[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listRowAccessPolicies as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listRowAccessPolicies as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes listRowAccessPolicies without error using callback', async () => { + const client = + new rowaccesspolicyserviceModule.v2.RowAccessPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListRowAccessPoliciesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListRowAccessPoliciesRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListRowAccessPoliciesRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const defaultValue3 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListRowAccessPoliciesRequest', + ['tableId'], + ); + request.tableId = defaultValue3; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}&table_id=${defaultValue3 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.cloud.bigquery.v2.RowAccessPolicy(), + ), + generateSampleMessage( + new protos.google.cloud.bigquery.v2.RowAccessPolicy(), + ), + generateSampleMessage( + new protos.google.cloud.bigquery.v2.RowAccessPolicy(), + ), + ]; + client.innerApiCalls.listRowAccessPolicies = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listRowAccessPolicies( + request, + ( + err?: Error | null, + result?: protos.google.cloud.bigquery.v2.IRowAccessPolicy[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listRowAccessPolicies as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listRowAccessPolicies as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listRowAccessPolicies with error', async () => { - const client = new rowaccesspolicyserviceModule.v2.RowAccessPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.ListRowAccessPoliciesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListRowAccessPoliciesRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListRowAccessPoliciesRequest', ['datasetId']); - request.datasetId = defaultValue2; - const defaultValue3 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListRowAccessPoliciesRequest', ['tableId']); - request.tableId = defaultValue3; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }&table_id=${defaultValue3 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listRowAccessPolicies = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listRowAccessPolicies(request), expectedError); - const actualRequest = (client.innerApiCalls.listRowAccessPolicies as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listRowAccessPolicies as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes listRowAccessPolicies with error', async () => { + const client = + new rowaccesspolicyserviceModule.v2.RowAccessPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListRowAccessPoliciesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListRowAccessPoliciesRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListRowAccessPoliciesRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const defaultValue3 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListRowAccessPoliciesRequest', + ['tableId'], + ); + request.tableId = defaultValue3; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}&table_id=${defaultValue3 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listRowAccessPolicies = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.listRowAccessPolicies(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.listRowAccessPolicies as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listRowAccessPolicies as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listRowAccessPoliciesStream without error', async () => { - const client = new rowaccesspolicyserviceModule.v2.RowAccessPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.ListRowAccessPoliciesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListRowAccessPoliciesRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListRowAccessPoliciesRequest', ['datasetId']); - request.datasetId = defaultValue2; - const defaultValue3 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListRowAccessPoliciesRequest', ['tableId']); - request.tableId = defaultValue3; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }&table_id=${defaultValue3 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.bigquery.v2.RowAccessPolicy()), - generateSampleMessage(new protos.google.cloud.bigquery.v2.RowAccessPolicy()), - generateSampleMessage(new protos.google.cloud.bigquery.v2.RowAccessPolicy()), - ]; - client.descriptors.page.listRowAccessPolicies.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listRowAccessPoliciesStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.cloud.bigquery.v2.RowAccessPolicy[] = []; - stream.on('data', (response: protos.google.cloud.bigquery.v2.RowAccessPolicy) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.listRowAccessPolicies.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listRowAccessPolicies, request)); - assert( - (client.descriptors.page.listRowAccessPolicies.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); + it('invokes listRowAccessPoliciesStream without error', async () => { + const client = + new rowaccesspolicyserviceModule.v2.RowAccessPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListRowAccessPoliciesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListRowAccessPoliciesRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListRowAccessPoliciesRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const defaultValue3 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListRowAccessPoliciesRequest', + ['tableId'], + ); + request.tableId = defaultValue3; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}&table_id=${defaultValue3 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.cloud.bigquery.v2.RowAccessPolicy(), + ), + generateSampleMessage( + new protos.google.cloud.bigquery.v2.RowAccessPolicy(), + ), + generateSampleMessage( + new protos.google.cloud.bigquery.v2.RowAccessPolicy(), + ), + ]; + client.descriptors.page.listRowAccessPolicies.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listRowAccessPoliciesStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.cloud.bigquery.v2.RowAccessPolicy[] = []; + stream.on( + 'data', + (response: protos.google.cloud.bigquery.v2.RowAccessPolicy) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + ( + client.descriptors.page.listRowAccessPolicies + .createStream as SinonStub + ) + .getCall(0) + .calledWith(client.innerApiCalls.listRowAccessPolicies, request), + ); + assert( + ( + client.descriptors.page.listRowAccessPolicies + .createStream as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); - it('invokes listRowAccessPoliciesStream with error', async () => { - const client = new rowaccesspolicyserviceModule.v2.RowAccessPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.ListRowAccessPoliciesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListRowAccessPoliciesRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListRowAccessPoliciesRequest', ['datasetId']); - request.datasetId = defaultValue2; - const defaultValue3 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListRowAccessPoliciesRequest', ['tableId']); - request.tableId = defaultValue3; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }&table_id=${defaultValue3 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listRowAccessPolicies.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listRowAccessPoliciesStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.cloud.bigquery.v2.RowAccessPolicy[] = []; - stream.on('data', (response: protos.google.cloud.bigquery.v2.RowAccessPolicy) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listRowAccessPolicies.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listRowAccessPolicies, request)); - assert( - (client.descriptors.page.listRowAccessPolicies.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); + it('invokes listRowAccessPoliciesStream with error', async () => { + const client = + new rowaccesspolicyserviceModule.v2.RowAccessPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListRowAccessPoliciesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListRowAccessPoliciesRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListRowAccessPoliciesRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const defaultValue3 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListRowAccessPoliciesRequest', + ['tableId'], + ); + request.tableId = defaultValue3; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}&table_id=${defaultValue3 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listRowAccessPolicies.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listRowAccessPoliciesStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.cloud.bigquery.v2.RowAccessPolicy[] = []; + stream.on( + 'data', + (response: protos.google.cloud.bigquery.v2.RowAccessPolicy) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + ( + client.descriptors.page.listRowAccessPolicies + .createStream as SinonStub + ) + .getCall(0) + .calledWith(client.innerApiCalls.listRowAccessPolicies, request), + ); + assert( + ( + client.descriptors.page.listRowAccessPolicies + .createStream as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); - it('uses async iteration with listRowAccessPolicies without error', async () => { - const client = new rowaccesspolicyserviceModule.v2.RowAccessPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.ListRowAccessPoliciesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListRowAccessPoliciesRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListRowAccessPoliciesRequest', ['datasetId']); - request.datasetId = defaultValue2; - const defaultValue3 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListRowAccessPoliciesRequest', ['tableId']); - request.tableId = defaultValue3; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }&table_id=${defaultValue3 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.bigquery.v2.RowAccessPolicy()), - generateSampleMessage(new protos.google.cloud.bigquery.v2.RowAccessPolicy()), - generateSampleMessage(new protos.google.cloud.bigquery.v2.RowAccessPolicy()), - ]; - client.descriptors.page.listRowAccessPolicies.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.cloud.bigquery.v2.IRowAccessPolicy[] = []; - const iterable = client.listRowAccessPoliciesAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listRowAccessPolicies.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listRowAccessPolicies.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); + it('uses async iteration with listRowAccessPolicies without error', async () => { + const client = + new rowaccesspolicyserviceModule.v2.RowAccessPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListRowAccessPoliciesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListRowAccessPoliciesRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListRowAccessPoliciesRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const defaultValue3 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListRowAccessPoliciesRequest', + ['tableId'], + ); + request.tableId = defaultValue3; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}&table_id=${defaultValue3 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.cloud.bigquery.v2.RowAccessPolicy(), + ), + generateSampleMessage( + new protos.google.cloud.bigquery.v2.RowAccessPolicy(), + ), + generateSampleMessage( + new protos.google.cloud.bigquery.v2.RowAccessPolicy(), + ), + ]; + client.descriptors.page.listRowAccessPolicies.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.cloud.bigquery.v2.IRowAccessPolicy[] = []; + const iterable = client.listRowAccessPoliciesAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listRowAccessPolicies + .asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + ( + client.descriptors.page.listRowAccessPolicies + .asyncIterate as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); - it('uses async iteration with listRowAccessPolicies with error', async () => { - const client = new rowaccesspolicyserviceModule.v2.RowAccessPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.ListRowAccessPoliciesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListRowAccessPoliciesRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListRowAccessPoliciesRequest', ['datasetId']); - request.datasetId = defaultValue2; - const defaultValue3 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListRowAccessPoliciesRequest', ['tableId']); - request.tableId = defaultValue3; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }&table_id=${defaultValue3 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listRowAccessPolicies.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listRowAccessPoliciesAsync(request); - await assert.rejects(async () => { - const responses: protos.google.cloud.bigquery.v2.IRowAccessPolicy[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listRowAccessPolicies.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listRowAccessPolicies.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); + it('uses async iteration with listRowAccessPolicies with error', async () => { + const client = + new rowaccesspolicyserviceModule.v2.RowAccessPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListRowAccessPoliciesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListRowAccessPoliciesRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListRowAccessPoliciesRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const defaultValue3 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListRowAccessPoliciesRequest', + ['tableId'], + ); + request.tableId = defaultValue3; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}&table_id=${defaultValue3 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listRowAccessPolicies.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listRowAccessPoliciesAsync(request); + await assert.rejects(async () => { + const responses: protos.google.cloud.bigquery.v2.IRowAccessPolicy[] = + []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listRowAccessPolicies + .asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + ( + client.descriptors.page.listRowAccessPolicies + .asyncIterate as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); }); + }); }); diff --git a/core/generator/gapic-generator-typescript/baselines/bigquery-v2/test/gapic_table_service_v2.ts.baseline b/core/generator/gapic-generator-typescript/baselines/bigquery-v2/test/gapic_table_service_v2.ts.baseline index 1a1268a6e03e..51aa0c5ea2eb 100644 --- a/core/generator/gapic-generator-typescript/baselines/bigquery-v2/test/gapic_table_service_v2.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/bigquery-v2/test/gapic_table_service_v2.ts.baseline @@ -19,1157 +19,1503 @@ import * as protos from '../protos/protos'; import * as assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as tableserviceModule from '../src'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; -import {protobuf} from 'google-gax'; +import { protobuf } from 'google-gax'; // Dynamically loaded proto JSON is needed to get the type information // to fill in default values for request objects -const root = protobuf.Root.fromJSON(require('../protos/protos.json')).resolveAll(); +const root = protobuf.Root.fromJSON( + require('../protos/protos.json'), +).resolveAll(); // eslint-disable-next-line @typescript-eslint/no-unused-vars function getTypeDefaultValue(typeName: string, fields: string[]) { - let type = root.lookupType(typeName) as protobuf.Type; - for (const field of fields.slice(0, -1)) { - type = type.fields[field]?.resolvedType as protobuf.Type; - } - return type.fields[fields[fields.length - 1]]?.defaultValue; + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type.fields[field]?.resolvedType as protobuf.Type; + } + return type.fields[fields[fields.length - 1]]?.defaultValue; } function generateSampleMessage(instance: T) { - const filledObject = (instance.constructor as typeof protobuf.Message) - .toObject(instance as protobuf.Message, {defaults: true}); - return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, { defaults: true }); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; } function stubSimpleCall(response?: ResponseType, error?: Error) { - return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); } -function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { - return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +function stubSimpleCallWithCallback( + response?: ResponseType, + error?: Error, +) { + return error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); } -function stubPageStreamingCall(responses?: ResponseType[], error?: Error) { - const pagingStub = sinon.stub(); - if (responses) { - for (let i = 0; i < responses.length; ++i) { - pagingStub.onCall(i).callsArgWith(2, null, responses[i]); - } +function stubPageStreamingCall( + responses?: ResponseType[], + error?: Error, +) { + const pagingStub = sinon.stub(); + if (responses) { + for (let i = 0; i < responses.length; ++i) { + pagingStub.onCall(i).callsArgWith(2, null, responses[i]); } - const transformStub = error ? sinon.stub().callsArgWith(2, error) : pagingStub; - const mockStream = new PassThrough({ - objectMode: true, - transform: transformStub, - }); - // trigger as many responses as needed - if (responses) { - for (let i = 0; i < responses.length; ++i) { - setImmediate(() => { mockStream.write({}); }); - } - setImmediate(() => { mockStream.end(); }); - } else { - setImmediate(() => { mockStream.write({}); }); - setImmediate(() => { mockStream.end(); }); + } + const transformStub = error + ? sinon.stub().callsArgWith(2, error) + : pagingStub; + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + // trigger as many responses as needed + if (responses) { + for (let i = 0; i < responses.length; ++i) { + setImmediate(() => { + mockStream.write({}); + }); } - return sinon.stub().returns(mockStream); + setImmediate(() => { + mockStream.end(); + }); + } else { + setImmediate(() => { + mockStream.write({}); + }); + setImmediate(() => { + mockStream.end(); + }); + } + return sinon.stub().returns(mockStream); } -function stubAsyncIterationCall(responses?: ResponseType[], error?: Error) { - let counter = 0; - const asyncIterable = { - [Symbol.asyncIterator]() { - return { - async next() { - if (error) { - return Promise.reject(error); - } - if (counter >= responses!.length) { - return Promise.resolve({done: true, value: undefined}); - } - return Promise.resolve({done: false, value: responses![counter++]}); - } - }; - } - }; - return sinon.stub().returns(asyncIterable); +function stubAsyncIterationCall( + responses?: ResponseType[], + error?: Error, +) { + let counter = 0; + const asyncIterable = { + [Symbol.asyncIterator]() { + return { + async next() { + if (error) { + return Promise.reject(error); + } + if (counter >= responses!.length) { + return Promise.resolve({ done: true, value: undefined }); + } + return Promise.resolve({ done: false, value: responses![counter++] }); + }, + }; + }, + }; + return sinon.stub().returns(asyncIterable); } describe('v2.TableServiceClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new tableserviceModule.v2.TableServiceClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'bigquery.googleapis.com'); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new tableserviceModule.v2.TableServiceClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'bigquery.googleapis.com'); + }); - it('has universeDomain', () => { - const client = new tableserviceModule.v2.TableServiceClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); + it('has universeDomain', () => { + const client = new tableserviceModule.v2.TableServiceClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - it('throws DeprecationWarning if static servicePath is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const servicePath = tableserviceModule.v2.TableServiceClient.servicePath; - assert.strictEqual(servicePath, 'bigquery.googleapis.com'); - assert(stub.called); - stub.restore(); - }); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = + tableserviceModule.v2.TableServiceClient.servicePath; + assert.strictEqual(servicePath, 'bigquery.googleapis.com'); + assert(stub.called); + stub.restore(); + }); - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = tableserviceModule.v2.TableServiceClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'bigquery.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new tableserviceModule.v2.TableServiceClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'bigquery.example.com'); + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + tableserviceModule.v2.TableServiceClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'bigquery.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = new tableserviceModule.v2.TableServiceClient({ + universeDomain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'bigquery.example.com'); + }); + + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = new tableserviceModule.v2.TableServiceClient({ + universe_domain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'bigquery.example.com'); + }); + + if (typeof process === 'object' && 'env' in process) { + describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { + it('sets apiEndpoint from environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new tableserviceModule.v2.TableServiceClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'bigquery.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new tableserviceModule.v2.TableServiceClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'bigquery.example.com'); + it('value configured in code has priority over environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new tableserviceModule.v2.TableServiceClient({ + universeDomain: 'configured.example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'bigquery.configured.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new tableserviceModule.v2.TableServiceClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', + }); + }); + }); - if (typeof process === 'object' && 'env' in process) { - describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { - it('sets apiEndpoint from environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new tableserviceModule.v2.TableServiceClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'bigquery.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); + it('has port', () => { + const port = tableserviceModule.v2.TableServiceClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('value configured in code has priority over environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new tableserviceModule.v2.TableServiceClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'bigquery.configured.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { new tableserviceModule.v2.TableServiceClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); + it('should create a client with no option', () => { + const client = new tableserviceModule.v2.TableServiceClient(); + assert(client); + }); - it('has port', () => { - const port = tableserviceModule.v2.TableServiceClient.port; - assert(port); - assert(typeof port === 'number'); - }); + it('should create a client with gRPC fallback', () => { + const client = new tableserviceModule.v2.TableServiceClient({ + fallback: true, + }); + assert(client); + }); - it('should create a client with no option', () => { - const client = new tableserviceModule.v2.TableServiceClient(); - assert(client); - }); + it('has initialize method and supports deferred initialization', async () => { + const client = new tableserviceModule.v2.TableServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.tableServiceStub, undefined); + await client.initialize(); + assert(client.tableServiceStub); + }); - it('should create a client with gRPC fallback', () => { - const client = new tableserviceModule.v2.TableServiceClient({ - fallback: true, - }); - assert(client); + it('has close method for the initialized client', (done) => { + const client = new tableserviceModule.v2.TableServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.tableServiceStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('has initialize method and supports deferred initialization', async () => { - const client = new tableserviceModule.v2.TableServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.tableServiceStub, undefined); - await client.initialize(); - assert(client.tableServiceStub); + it('has close method for the non-initialized client', (done) => { + const client = new tableserviceModule.v2.TableServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.tableServiceStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('has close method for the initialized client', done => { - const client = new tableserviceModule.v2.TableServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.tableServiceStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new tableserviceModule.v2.TableServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + }); - it('has close method for the non-initialized client', done => { - const client = new tableserviceModule.v2.TableServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.tableServiceStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new tableserviceModule.v2.TableServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new tableserviceModule.v2.TableServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); - }); + describe('getTable', () => { + it('invokes getTable without error', async () => { + const client = new tableserviceModule.v2.TableServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.GetTableRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetTableRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetTableRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const defaultValue3 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetTableRequest', + ['tableId'], + ); + request.tableId = defaultValue3; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}&table_id=${defaultValue3 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.bigquery.v2.Table(), + ); + client.innerApiCalls.getTable = stubSimpleCall(expectedResponse); + const [response] = await client.getTable(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getTable as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getTable as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new tableserviceModule.v2.TableServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId((err?: Error|null, projectId?: string|null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } - }); - }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); - }); + it('invokes getTable without error using callback', async () => { + const client = new tableserviceModule.v2.TableServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.GetTableRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetTableRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetTableRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const defaultValue3 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetTableRequest', + ['tableId'], + ); + request.tableId = defaultValue3; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}&table_id=${defaultValue3 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.bigquery.v2.Table(), + ); + client.innerApiCalls.getTable = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getTable( + request, + ( + err?: Error | null, + result?: protos.google.cloud.bigquery.v2.ITable | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getTable as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getTable as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('getTable', () => { - it('invokes getTable without error', async () => { - const client = new tableserviceModule.v2.TableServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.GetTableRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetTableRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetTableRequest', ['datasetId']); - request.datasetId = defaultValue2; - const defaultValue3 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetTableRequest', ['tableId']); - request.tableId = defaultValue3; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }&table_id=${defaultValue3 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.bigquery.v2.Table() - ); - client.innerApiCalls.getTable = stubSimpleCall(expectedResponse); - const [response] = await client.getTable(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getTable as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getTable as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getTable with error', async () => { + const client = new tableserviceModule.v2.TableServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.GetTableRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetTableRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetTableRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const defaultValue3 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetTableRequest', + ['tableId'], + ); + request.tableId = defaultValue3; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}&table_id=${defaultValue3 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getTable = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.getTable(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getTable as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getTable as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getTable without error using callback', async () => { - const client = new tableserviceModule.v2.TableServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.GetTableRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetTableRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetTableRequest', ['datasetId']); - request.datasetId = defaultValue2; - const defaultValue3 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetTableRequest', ['tableId']); - request.tableId = defaultValue3; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }&table_id=${defaultValue3 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.bigquery.v2.Table() - ); - client.innerApiCalls.getTable = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getTable( - request, - (err?: Error|null, result?: protos.google.cloud.bigquery.v2.ITable|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getTable as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getTable as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getTable with closed client', async () => { + const client = new tableserviceModule.v2.TableServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.GetTableRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetTableRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetTableRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const defaultValue3 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.GetTableRequest', + ['tableId'], + ); + request.tableId = defaultValue3; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getTable(request), expectedError); + }); + }); - it('invokes getTable with error', async () => { - const client = new tableserviceModule.v2.TableServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.GetTableRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetTableRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetTableRequest', ['datasetId']); - request.datasetId = defaultValue2; - const defaultValue3 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetTableRequest', ['tableId']); - request.tableId = defaultValue3; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }&table_id=${defaultValue3 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getTable = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getTable(request), expectedError); - const actualRequest = (client.innerApiCalls.getTable as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getTable as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + describe('insertTable', () => { + it('invokes insertTable without error', async () => { + const client = new tableserviceModule.v2.TableServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.InsertTableRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.InsertTableRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.InsertTableRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.bigquery.v2.Table(), + ); + client.innerApiCalls.insertTable = stubSimpleCall(expectedResponse); + const [response] = await client.insertTable(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.insertTable as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.insertTable as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getTable with closed client', async () => { - const client = new tableserviceModule.v2.TableServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.GetTableRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetTableRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetTableRequest', ['datasetId']); - request.datasetId = defaultValue2; - const defaultValue3 = - getTypeDefaultValue('.google.cloud.bigquery.v2.GetTableRequest', ['tableId']); - request.tableId = defaultValue3; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getTable(request), expectedError); - }); + it('invokes insertTable without error using callback', async () => { + const client = new tableserviceModule.v2.TableServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.InsertTableRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.InsertTableRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.InsertTableRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.bigquery.v2.Table(), + ); + client.innerApiCalls.insertTable = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.insertTable( + request, + ( + err?: Error | null, + result?: protos.google.cloud.bigquery.v2.ITable | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.insertTable as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.insertTable as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('insertTable', () => { - it('invokes insertTable without error', async () => { - const client = new tableserviceModule.v2.TableServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.InsertTableRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.InsertTableRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.InsertTableRequest', ['datasetId']); - request.datasetId = defaultValue2; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.bigquery.v2.Table() - ); - client.innerApiCalls.insertTable = stubSimpleCall(expectedResponse); - const [response] = await client.insertTable(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.insertTable as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.insertTable as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes insertTable with error', async () => { + const client = new tableserviceModule.v2.TableServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.InsertTableRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.InsertTableRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.InsertTableRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.insertTable = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.insertTable(request), expectedError); + const actualRequest = ( + client.innerApiCalls.insertTable as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.insertTable as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes insertTable without error using callback', async () => { - const client = new tableserviceModule.v2.TableServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.InsertTableRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.InsertTableRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.InsertTableRequest', ['datasetId']); - request.datasetId = defaultValue2; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.bigquery.v2.Table() - ); - client.innerApiCalls.insertTable = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.insertTable( - request, - (err?: Error|null, result?: protos.google.cloud.bigquery.v2.ITable|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.insertTable as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.insertTable as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes insertTable with closed client', async () => { + const client = new tableserviceModule.v2.TableServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.InsertTableRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.InsertTableRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.InsertTableRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.insertTable(request), expectedError); + }); + }); - it('invokes insertTable with error', async () => { - const client = new tableserviceModule.v2.TableServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.InsertTableRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.InsertTableRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.InsertTableRequest', ['datasetId']); - request.datasetId = defaultValue2; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.insertTable = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.insertTable(request), expectedError); - const actualRequest = (client.innerApiCalls.insertTable as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.insertTable as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + describe('patchTable', () => { + it('invokes patchTable without error', async () => { + const client = new tableserviceModule.v2.TableServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.UpdateOrPatchTableRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.UpdateOrPatchTableRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.UpdateOrPatchTableRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const defaultValue3 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.UpdateOrPatchTableRequest', + ['tableId'], + ); + request.tableId = defaultValue3; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}&table_id=${defaultValue3 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.bigquery.v2.Table(), + ); + client.innerApiCalls.patchTable = stubSimpleCall(expectedResponse); + const [response] = await client.patchTable(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.patchTable as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.patchTable as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes insertTable with closed client', async () => { - const client = new tableserviceModule.v2.TableServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.InsertTableRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.InsertTableRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.InsertTableRequest', ['datasetId']); - request.datasetId = defaultValue2; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.insertTable(request), expectedError); - }); + it('invokes patchTable without error using callback', async () => { + const client = new tableserviceModule.v2.TableServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.UpdateOrPatchTableRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.UpdateOrPatchTableRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.UpdateOrPatchTableRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const defaultValue3 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.UpdateOrPatchTableRequest', + ['tableId'], + ); + request.tableId = defaultValue3; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}&table_id=${defaultValue3 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.bigquery.v2.Table(), + ); + client.innerApiCalls.patchTable = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.patchTable( + request, + ( + err?: Error | null, + result?: protos.google.cloud.bigquery.v2.ITable | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.patchTable as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.patchTable as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('patchTable', () => { - it('invokes patchTable without error', async () => { - const client = new tableserviceModule.v2.TableServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.UpdateOrPatchTableRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.UpdateOrPatchTableRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.UpdateOrPatchTableRequest', ['datasetId']); - request.datasetId = defaultValue2; - const defaultValue3 = - getTypeDefaultValue('.google.cloud.bigquery.v2.UpdateOrPatchTableRequest', ['tableId']); - request.tableId = defaultValue3; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }&table_id=${defaultValue3 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.bigquery.v2.Table() - ); - client.innerApiCalls.patchTable = stubSimpleCall(expectedResponse); - const [response] = await client.patchTable(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.patchTable as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.patchTable as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes patchTable with error', async () => { + const client = new tableserviceModule.v2.TableServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.UpdateOrPatchTableRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.UpdateOrPatchTableRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.UpdateOrPatchTableRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const defaultValue3 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.UpdateOrPatchTableRequest', + ['tableId'], + ); + request.tableId = defaultValue3; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}&table_id=${defaultValue3 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.patchTable = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.patchTable(request), expectedError); + const actualRequest = ( + client.innerApiCalls.patchTable as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.patchTable as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes patchTable without error using callback', async () => { - const client = new tableserviceModule.v2.TableServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.UpdateOrPatchTableRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.UpdateOrPatchTableRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.UpdateOrPatchTableRequest', ['datasetId']); - request.datasetId = defaultValue2; - const defaultValue3 = - getTypeDefaultValue('.google.cloud.bigquery.v2.UpdateOrPatchTableRequest', ['tableId']); - request.tableId = defaultValue3; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }&table_id=${defaultValue3 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.bigquery.v2.Table() - ); - client.innerApiCalls.patchTable = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.patchTable( - request, - (err?: Error|null, result?: protos.google.cloud.bigquery.v2.ITable|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.patchTable as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.patchTable as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes patchTable with closed client', async () => { + const client = new tableserviceModule.v2.TableServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.UpdateOrPatchTableRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.UpdateOrPatchTableRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.UpdateOrPatchTableRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const defaultValue3 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.UpdateOrPatchTableRequest', + ['tableId'], + ); + request.tableId = defaultValue3; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.patchTable(request), expectedError); + }); + }); - it('invokes patchTable with error', async () => { - const client = new tableserviceModule.v2.TableServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.UpdateOrPatchTableRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.UpdateOrPatchTableRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.UpdateOrPatchTableRequest', ['datasetId']); - request.datasetId = defaultValue2; - const defaultValue3 = - getTypeDefaultValue('.google.cloud.bigquery.v2.UpdateOrPatchTableRequest', ['tableId']); - request.tableId = defaultValue3; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }&table_id=${defaultValue3 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.patchTable = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.patchTable(request), expectedError); - const actualRequest = (client.innerApiCalls.patchTable as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.patchTable as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + describe('updateTable', () => { + it('invokes updateTable without error', async () => { + const client = new tableserviceModule.v2.TableServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.UpdateOrPatchTableRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.UpdateOrPatchTableRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.UpdateOrPatchTableRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const defaultValue3 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.UpdateOrPatchTableRequest', + ['tableId'], + ); + request.tableId = defaultValue3; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}&table_id=${defaultValue3 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.bigquery.v2.Table(), + ); + client.innerApiCalls.updateTable = stubSimpleCall(expectedResponse); + const [response] = await client.updateTable(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateTable as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateTable as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes patchTable with closed client', async () => { - const client = new tableserviceModule.v2.TableServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.UpdateOrPatchTableRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.UpdateOrPatchTableRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.UpdateOrPatchTableRequest', ['datasetId']); - request.datasetId = defaultValue2; - const defaultValue3 = - getTypeDefaultValue('.google.cloud.bigquery.v2.UpdateOrPatchTableRequest', ['tableId']); - request.tableId = defaultValue3; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.patchTable(request), expectedError); - }); + it('invokes updateTable without error using callback', async () => { + const client = new tableserviceModule.v2.TableServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.UpdateOrPatchTableRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.UpdateOrPatchTableRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.UpdateOrPatchTableRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const defaultValue3 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.UpdateOrPatchTableRequest', + ['tableId'], + ); + request.tableId = defaultValue3; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}&table_id=${defaultValue3 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.bigquery.v2.Table(), + ); + client.innerApiCalls.updateTable = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateTable( + request, + ( + err?: Error | null, + result?: protos.google.cloud.bigquery.v2.ITable | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateTable as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateTable as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('updateTable', () => { - it('invokes updateTable without error', async () => { - const client = new tableserviceModule.v2.TableServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.UpdateOrPatchTableRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.UpdateOrPatchTableRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.UpdateOrPatchTableRequest', ['datasetId']); - request.datasetId = defaultValue2; - const defaultValue3 = - getTypeDefaultValue('.google.cloud.bigquery.v2.UpdateOrPatchTableRequest', ['tableId']); - request.tableId = defaultValue3; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }&table_id=${defaultValue3 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.bigquery.v2.Table() - ); - client.innerApiCalls.updateTable = stubSimpleCall(expectedResponse); - const [response] = await client.updateTable(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateTable as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateTable as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateTable with error', async () => { + const client = new tableserviceModule.v2.TableServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.UpdateOrPatchTableRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.UpdateOrPatchTableRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.UpdateOrPatchTableRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const defaultValue3 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.UpdateOrPatchTableRequest', + ['tableId'], + ); + request.tableId = defaultValue3; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}&table_id=${defaultValue3 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateTable = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.updateTable(request), expectedError); + const actualRequest = ( + client.innerApiCalls.updateTable as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateTable as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateTable without error using callback', async () => { - const client = new tableserviceModule.v2.TableServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.UpdateOrPatchTableRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.UpdateOrPatchTableRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.UpdateOrPatchTableRequest', ['datasetId']); - request.datasetId = defaultValue2; - const defaultValue3 = - getTypeDefaultValue('.google.cloud.bigquery.v2.UpdateOrPatchTableRequest', ['tableId']); - request.tableId = defaultValue3; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }&table_id=${defaultValue3 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.bigquery.v2.Table() - ); - client.innerApiCalls.updateTable = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateTable( - request, - (err?: Error|null, result?: protos.google.cloud.bigquery.v2.ITable|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateTable as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateTable as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateTable with closed client', async () => { + const client = new tableserviceModule.v2.TableServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.UpdateOrPatchTableRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.UpdateOrPatchTableRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.UpdateOrPatchTableRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const defaultValue3 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.UpdateOrPatchTableRequest', + ['tableId'], + ); + request.tableId = defaultValue3; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.updateTable(request), expectedError); + }); + }); - it('invokes updateTable with error', async () => { - const client = new tableserviceModule.v2.TableServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.UpdateOrPatchTableRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.UpdateOrPatchTableRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.UpdateOrPatchTableRequest', ['datasetId']); - request.datasetId = defaultValue2; - const defaultValue3 = - getTypeDefaultValue('.google.cloud.bigquery.v2.UpdateOrPatchTableRequest', ['tableId']); - request.tableId = defaultValue3; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }&table_id=${defaultValue3 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateTable = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateTable(request), expectedError); - const actualRequest = (client.innerApiCalls.updateTable as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateTable as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + describe('deleteTable', () => { + it('invokes deleteTable without error', async () => { + const client = new tableserviceModule.v2.TableServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.DeleteTableRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.DeleteTableRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.DeleteTableRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const defaultValue3 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.DeleteTableRequest', + ['tableId'], + ); + request.tableId = defaultValue3; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}&table_id=${defaultValue3 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteTable = stubSimpleCall(expectedResponse); + const [response] = await client.deleteTable(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteTable as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteTable as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateTable with closed client', async () => { - const client = new tableserviceModule.v2.TableServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.UpdateOrPatchTableRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.UpdateOrPatchTableRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.UpdateOrPatchTableRequest', ['datasetId']); - request.datasetId = defaultValue2; - const defaultValue3 = - getTypeDefaultValue('.google.cloud.bigquery.v2.UpdateOrPatchTableRequest', ['tableId']); - request.tableId = defaultValue3; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateTable(request), expectedError); - }); + it('invokes deleteTable without error using callback', async () => { + const client = new tableserviceModule.v2.TableServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.DeleteTableRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.DeleteTableRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.DeleteTableRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const defaultValue3 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.DeleteTableRequest', + ['tableId'], + ); + request.tableId = defaultValue3; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}&table_id=${defaultValue3 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteTable = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteTable( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteTable as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteTable as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('deleteTable', () => { - it('invokes deleteTable without error', async () => { - const client = new tableserviceModule.v2.TableServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.DeleteTableRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.DeleteTableRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.DeleteTableRequest', ['datasetId']); - request.datasetId = defaultValue2; - const defaultValue3 = - getTypeDefaultValue('.google.cloud.bigquery.v2.DeleteTableRequest', ['tableId']); - request.tableId = defaultValue3; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }&table_id=${defaultValue3 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteTable = stubSimpleCall(expectedResponse); - const [response] = await client.deleteTable(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteTable as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteTable as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteTable with error', async () => { + const client = new tableserviceModule.v2.TableServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.DeleteTableRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.DeleteTableRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.DeleteTableRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const defaultValue3 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.DeleteTableRequest', + ['tableId'], + ); + request.tableId = defaultValue3; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}&table_id=${defaultValue3 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteTable = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.deleteTable(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteTable as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteTable as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteTable without error using callback', async () => { - const client = new tableserviceModule.v2.TableServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.DeleteTableRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.DeleteTableRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.DeleteTableRequest', ['datasetId']); - request.datasetId = defaultValue2; - const defaultValue3 = - getTypeDefaultValue('.google.cloud.bigquery.v2.DeleteTableRequest', ['tableId']); - request.tableId = defaultValue3; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }&table_id=${defaultValue3 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteTable = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteTable( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteTable as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteTable as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteTable with closed client', async () => { + const client = new tableserviceModule.v2.TableServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.DeleteTableRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.DeleteTableRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.DeleteTableRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const defaultValue3 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.DeleteTableRequest', + ['tableId'], + ); + request.tableId = defaultValue3; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.deleteTable(request), expectedError); + }); + }); - it('invokes deleteTable with error', async () => { - const client = new tableserviceModule.v2.TableServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.DeleteTableRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.DeleteTableRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.DeleteTableRequest', ['datasetId']); - request.datasetId = defaultValue2; - const defaultValue3 = - getTypeDefaultValue('.google.cloud.bigquery.v2.DeleteTableRequest', ['tableId']); - request.tableId = defaultValue3; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }&table_id=${defaultValue3 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteTable = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteTable(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteTable as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteTable as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + describe('listTables', () => { + it('invokes listTables without error', async () => { + const client = new tableserviceModule.v2.TableServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListTablesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListTablesRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListTablesRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListFormatTable(), + ), + generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListFormatTable(), + ), + generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListFormatTable(), + ), + ]; + client.innerApiCalls.listTables = stubSimpleCall(expectedResponse); + const [response] = await client.listTables(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listTables as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listTables as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteTable with closed client', async () => { - const client = new tableserviceModule.v2.TableServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.DeleteTableRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.DeleteTableRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.DeleteTableRequest', ['datasetId']); - request.datasetId = defaultValue2; - const defaultValue3 = - getTypeDefaultValue('.google.cloud.bigquery.v2.DeleteTableRequest', ['tableId']); - request.tableId = defaultValue3; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteTable(request), expectedError); - }); + it('invokes listTables without error using callback', async () => { + const client = new tableserviceModule.v2.TableServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListTablesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListTablesRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListTablesRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListFormatTable(), + ), + generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListFormatTable(), + ), + generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListFormatTable(), + ), + ]; + client.innerApiCalls.listTables = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listTables( + request, + ( + err?: Error | null, + result?: protos.google.cloud.bigquery.v2.IListFormatTable[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listTables as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listTables as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('listTables', () => { - it('invokes listTables without error', async () => { - const client = new tableserviceModule.v2.TableServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.ListTablesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListTablesRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListTablesRequest', ['datasetId']); - request.datasetId = defaultValue2; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.bigquery.v2.ListFormatTable()), - generateSampleMessage(new protos.google.cloud.bigquery.v2.ListFormatTable()), - generateSampleMessage(new protos.google.cloud.bigquery.v2.ListFormatTable()), - ]; - client.innerApiCalls.listTables = stubSimpleCall(expectedResponse); - const [response] = await client.listTables(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listTables as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listTables as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listTables with error', async () => { + const client = new tableserviceModule.v2.TableServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListTablesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListTablesRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListTablesRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listTables = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listTables(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listTables as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listTables as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listTables without error using callback', async () => { - const client = new tableserviceModule.v2.TableServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.ListTablesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListTablesRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListTablesRequest', ['datasetId']); - request.datasetId = defaultValue2; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.bigquery.v2.ListFormatTable()), - generateSampleMessage(new protos.google.cloud.bigquery.v2.ListFormatTable()), - generateSampleMessage(new protos.google.cloud.bigquery.v2.ListFormatTable()), - ]; - client.innerApiCalls.listTables = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listTables( - request, - (err?: Error|null, result?: protos.google.cloud.bigquery.v2.IListFormatTable[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listTables as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listTables as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes listTablesStream without error', async () => { + const client = new tableserviceModule.v2.TableServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListTablesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListTablesRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListTablesRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListFormatTable(), + ), + generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListFormatTable(), + ), + generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListFormatTable(), + ), + ]; + client.descriptors.page.listTables.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listTablesStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.cloud.bigquery.v2.ListFormatTable[] = []; + stream.on( + 'data', + (response: protos.google.cloud.bigquery.v2.ListFormatTable) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); }); - - it('invokes listTables with error', async () => { - const client = new tableserviceModule.v2.TableServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.ListTablesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListTablesRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListTablesRequest', ['datasetId']); - request.datasetId = defaultValue2; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listTables = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listTables(request), expectedError); - const actualRequest = (client.innerApiCalls.listTables as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listTables as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + stream.on('error', (err: Error) => { + reject(err); }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listTables.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listTables, request), + ); + assert( + (client.descriptors.page.listTables.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('invokes listTablesStream without error', async () => { - const client = new tableserviceModule.v2.TableServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.ListTablesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListTablesRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListTablesRequest', ['datasetId']); - request.datasetId = defaultValue2; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.bigquery.v2.ListFormatTable()), - generateSampleMessage(new protos.google.cloud.bigquery.v2.ListFormatTable()), - generateSampleMessage(new protos.google.cloud.bigquery.v2.ListFormatTable()), - ]; - client.descriptors.page.listTables.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listTablesStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.cloud.bigquery.v2.ListFormatTable[] = []; - stream.on('data', (response: protos.google.cloud.bigquery.v2.ListFormatTable) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.listTables.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listTables, request)); - assert( - (client.descriptors.page.listTables.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); + it('invokes listTablesStream with error', async () => { + const client = new tableserviceModule.v2.TableServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListTablesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListTablesRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListTablesRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listTables.createStream = stubPageStreamingCall( + undefined, + expectedError, + ); + const stream = client.listTablesStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.cloud.bigquery.v2.ListFormatTable[] = []; + stream.on( + 'data', + (response: protos.google.cloud.bigquery.v2.ListFormatTable) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); }); - - it('invokes listTablesStream with error', async () => { - const client = new tableserviceModule.v2.TableServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.ListTablesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListTablesRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListTablesRequest', ['datasetId']); - request.datasetId = defaultValue2; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listTables.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listTablesStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.cloud.bigquery.v2.ListFormatTable[] = []; - stream.on('data', (response: protos.google.cloud.bigquery.v2.ListFormatTable) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listTables.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listTables, request)); - assert( - (client.descriptors.page.listTables.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); + stream.on('error', (err: Error) => { + reject(err); }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listTables.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listTables, request), + ); + assert( + (client.descriptors.page.listTables.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('uses async iteration with listTables without error', async () => { - const client = new tableserviceModule.v2.TableServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.ListTablesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListTablesRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListTablesRequest', ['datasetId']); - request.datasetId = defaultValue2; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.bigquery.v2.ListFormatTable()), - generateSampleMessage(new protos.google.cloud.bigquery.v2.ListFormatTable()), - generateSampleMessage(new protos.google.cloud.bigquery.v2.ListFormatTable()), - ]; - client.descriptors.page.listTables.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.cloud.bigquery.v2.IListFormatTable[] = []; - const iterable = client.listTablesAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listTables.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listTables.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listTables without error', async () => { + const client = new tableserviceModule.v2.TableServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListTablesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListTablesRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListTablesRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListFormatTable(), + ), + generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListFormatTable(), + ), + generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListFormatTable(), + ), + ]; + client.descriptors.page.listTables.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.cloud.bigquery.v2.IListFormatTable[] = []; + const iterable = client.listTablesAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + (client.descriptors.page.listTables.asyncIterate as SinonStub).getCall( + 0, + ).args[1], + request, + ); + assert( + (client.descriptors.page.listTables.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('uses async iteration with listTables with error', async () => { - const client = new tableserviceModule.v2.TableServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.bigquery.v2.ListTablesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListTablesRequest', ['projectId']); - request.projectId = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.bigquery.v2.ListTablesRequest', ['datasetId']); - request.datasetId = defaultValue2; - const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? '' }&dataset_id=${defaultValue2 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listTables.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listTablesAsync(request); - await assert.rejects(async () => { - const responses: protos.google.cloud.bigquery.v2.IListFormatTable[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listTables.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listTables.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listTables with error', async () => { + const client = new tableserviceModule.v2.TableServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.v2.ListTablesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListTablesRequest', + ['projectId'], + ); + request.projectId = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.bigquery.v2.ListTablesRequest', + ['datasetId'], + ); + request.datasetId = defaultValue2; + const expectedHeaderRequestParams = `project_id=${defaultValue1 ?? ''}&dataset_id=${defaultValue2 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listTables.asyncIterate = stubAsyncIterationCall( + undefined, + expectedError, + ); + const iterable = client.listTablesAsync(request); + await assert.rejects(async () => { + const responses: protos.google.cloud.bigquery.v2.IListFormatTable[] = + []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + (client.descriptors.page.listTables.asyncIterate as SinonStub).getCall( + 0, + ).args[1], + request, + ); + assert( + (client.descriptors.page.listTables.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); }); + }); }); diff --git a/core/generator/gapic-generator-typescript/baselines/compute-esm/esm/src/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/compute-esm/esm/src/index.ts.baseline index 27c4c4a46fbc..7da3c8cd3c9a 100644 --- a/core/generator/gapic-generator-typescript/baselines/compute-esm/esm/src/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/compute-esm/esm/src/index.ts.baseline @@ -21,8 +21,8 @@ const AddressesClient = v1.AddressesClient; type AddressesClient = v1.AddressesClient; const RegionOperationsClient = v1.RegionOperationsClient; type RegionOperationsClient = v1.RegionOperationsClient; -export {v1, AddressesClient, RegionOperationsClient}; -export default {v1, AddressesClient, RegionOperationsClient}; +export { v1, AddressesClient, RegionOperationsClient }; +export default { v1, AddressesClient, RegionOperationsClient }; // @ts-ignore import * as protos from '../../protos/protos.js'; -export {protos} +export { protos }; diff --git a/core/generator/gapic-generator-typescript/baselines/compute-esm/esm/src/v1/addresses_client.ts.baseline b/core/generator/gapic-generator-typescript/baselines/compute-esm/esm/src/v1/addresses_client.ts.baseline index d66447fcd4a0..d6844ae95ba8 100644 --- a/core/generator/gapic-generator-typescript/baselines/compute-esm/esm/src/v1/addresses_client.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/compute-esm/esm/src/v1/addresses_client.ts.baseline @@ -18,15 +18,23 @@ /* global window */ import * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions, LROperation, PaginationCallback, GaxCall} from 'google-gax'; -import {Transform} from 'stream'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + LROperation, + PaginationCallback, + GaxCall, +} from 'google-gax'; +import { Transform } from 'stream'; // @ts-ignore import type * as protos from '../../../protos/protos.js'; import * as addresses_client_config from './addresses_client_config.json'; import fs from 'fs'; import path from 'path'; -import {fileURLToPath} from 'url'; -import {getJSON} from '../json-helper.cjs'; +import { fileURLToPath } from 'url'; +import { getJSON } from '../json-helper.cjs'; // @ts-ignore const dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -35,16 +43,14 @@ const dirname = path.dirname(fileURLToPath(import.meta.url)); * `src/v1/addresses_client_config.json`. * This file defines retry strategy and timeouts for all API methods in this library. */ -const gapicConfig = getJSON( - path.join(dirname, 'addresses_client_config.json') -); +const gapicConfig = getJSON(path.join(dirname, 'addresses_client_config.json')); const jsonProtos = getJSON( - path.join(dirname, '..', '..', '..', 'protos/protos.json') + path.join(dirname, '..', '..', '..', 'protos/protos.json'), ); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; const version = getJSON( - path.join(dirname, '..', '..', '..', '..', 'package.json') + path.join(dirname, '..', '..', '..', '..', 'package.json'), ).version; /** @@ -62,7 +68,7 @@ export class AddressesClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('compute'); @@ -74,8 +80,8 @@ export class AddressesClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - addressesStub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + addressesStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of AddressesClient. @@ -117,27 +123,48 @@ export class AddressesClient { * const client = new AddressesClient({fallback: 'rest'}, gax); * ``` */ - constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { // Ensure that options include all the required fields. const staticMembers = this.constructor as typeof AddressesClient; - if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { - throw new Error('Please set either universe_domain or universeDomain, but not both.'); + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); } - const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; - this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; this._servicePath = 'compute.' + this._universeDomain; - const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; // Implicitely set 'rest' value for the apis use rest as transport (eg. googleapis-discovery apis). if (!opts) { - opts = {fallback: 'rest'}; + opts = { fallback: 'rest' }; } else { opts.fallback = opts.fallback ?? 'rest'; } - const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. if (servicePath !== this._servicePath && !('scopes' in opts)) { @@ -159,7 +186,7 @@ export class AddressesClient { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set defaultServicePath on the auth object. this.auth.defaultServicePath = this._servicePath; @@ -173,10 +200,7 @@ export class AddressesClient { const isEsm = true; const isEsmString = isEsm ? '-esm' : '-cjs'; // Determine the client header string. - const clientHeader = [ - `gax/${this._gaxModule.version}`, - `gapic/${version}`, - ]; + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/{process.versions.node}${isEsmString}`); } else { @@ -184,7 +208,7 @@ export class AddressesClient { } if (!opts.fallback) { clientHeader.push(`grpc/${this._gaxGrpc.grpcVersion}`); - } else if (opts.fallback === 'rest' ) { + } else if (opts.fallback === 'rest') { clientHeader.push(`rest/${this._gaxGrpc.grpcVersion}`); } if (opts.libName && opts.libVersion) { @@ -192,22 +216,33 @@ export class AddressesClient { } // Load the applicable protos. - this._protos = this._gaxGrpc.loadProtoJSON(jsonProtos as gax.protobuf.INamespace); + this._protos = this._gaxGrpc.loadProtoJSON( + jsonProtos as gax.protobuf.INamespace, + ); // Some of the methods on this service return "paged" results, // (e.g. 50 results at a time, with tokens to get subsequent // pages). Denote the keys used for pagination and results. this.descriptors.page = { - aggregatedList: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'items'), - list: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'items') + aggregatedList: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'items', + ), + list: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'items', + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.cloud.compute.v1.Addresses', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.cloud.compute.v1.Addresses', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + { 'x-goog-api-client': clientHeader.join(' ') }, + ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -238,37 +273,40 @@ export class AddressesClient { // Put together the "service stub" for // google.cloud.compute.v1.Addresses. this.addressesStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.cloud.compute.v1.Addresses') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.cloud.compute.v1.Addresses', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.cloud.compute.v1.Addresses, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts, + this._providedCustomServicePath, + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const addressesStubMethods = - ['aggregatedList', 'delete', 'insert', 'list']; + const addressesStubMethods = ['aggregatedList', 'delete', 'insert', 'list']; for (const methodName of addressesStubMethods) { const callPromise = this.addressesStub.then( - stub => (...args: Array<{}>) => { - if (this._terminated) { - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error|null|undefined) => () => { + (stub) => + (...args: Array<{}>) => { + if (this._terminated) { + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { throw err; - }); + }, + ); - const descriptor = - this.descriptors.page[methodName] || - undefined; + const descriptor = this.descriptors.page[methodName] || undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -283,8 +321,14 @@ export class AddressesClient { * @returns {string} The DNS address for this service. */ static get servicePath() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'compute.googleapis.com'; } @@ -296,8 +340,14 @@ export class AddressesClient { * @returns {string} The DNS address for this service. */ static get apiEndpoint() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'compute.googleapis.com'; } @@ -330,7 +380,7 @@ export class AddressesClient { static get scopes() { return [ 'https://www.googleapis.com/auth/compute', - 'https://www.googleapis.com/auth/cloud-platform' + 'https://www.googleapis.com/auth/cloud-platform', ]; } @@ -340,8 +390,9 @@ export class AddressesClient { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId(callback?: Callback): - Promise|void { + getProjectId( + callback?: Callback, + ): Promise | void { if (callback) { this.auth.getProjectId(callback); return; @@ -352,388 +403,491 @@ export class AddressesClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Deletes the specified address resource. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.address - * Name of the address resource to delete. - * @param {string} request.project - * Project ID for this request. - * @param {string} request.region - * Name of the region for this request. - * @param {string} request.requestId - * An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. - * - * For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. - * - * The request ID must be a valid UUID with the exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000). - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing - * a long running operation. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * This method is considered to be in beta. This means while - * stable it is still a work-in-progress and under active development, - * and might get backwards-incompatible changes at any time. - * `.promise()` is not supported yet. - * @example include:samples/generated/v1/addresses.delete.js - * region_tag:compute_v1_generated_Addresses_Delete_async - */ + /** + * Deletes the specified address resource. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.address + * Name of the address resource to delete. + * @param {string} request.project + * Project ID for this request. + * @param {string} request.region + * Name of the region for this request. + * @param {string} request.requestId + * An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. + * + * For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. + * + * The request ID must be a valid UUID with the exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000). + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * This method is considered to be in beta. This means while + * stable it is still a work-in-progress and under active development, + * and might get backwards-incompatible changes at any time. + * `.promise()` is not supported yet. + * @example include:samples/generated/v1/addresses.delete.js + * region_tag:compute_v1_generated_Addresses_Delete_async + */ delete( - request?: protos.google.cloud.compute.v1.IDeleteAddressRequest, - options?: CallOptions): - Promise<[ - LROperation, - protos.google.cloud.compute.v1.IOperation|undefined, {}|undefined - ]>; + request?: protos.google.cloud.compute.v1.IDeleteAddressRequest, + options?: CallOptions, + ): Promise< + [ + LROperation, + protos.google.cloud.compute.v1.IOperation | undefined, + {} | undefined, + ] + >; delete( - request: protos.google.cloud.compute.v1.IDeleteAddressRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.compute.v1.IOperation, - protos.google.cloud.compute.v1.IDeleteAddressRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.compute.v1.IDeleteAddressRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.compute.v1.IOperation, + protos.google.cloud.compute.v1.IDeleteAddressRequest | null | undefined, + {} | null | undefined + >, + ): void; delete( - request: protos.google.cloud.compute.v1.IDeleteAddressRequest, - callback: Callback< - protos.google.cloud.compute.v1.IOperation, - protos.google.cloud.compute.v1.IDeleteAddressRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.compute.v1.IDeleteAddressRequest, + callback: Callback< + protos.google.cloud.compute.v1.IOperation, + protos.google.cloud.compute.v1.IDeleteAddressRequest | null | undefined, + {} | null | undefined + >, + ): void; delete( - request?: protos.google.cloud.compute.v1.IDeleteAddressRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.cloud.compute.v1.IDeleteAddressRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.compute.v1.IOperation, - protos.google.cloud.compute.v1.IDeleteAddressRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.cloud.compute.v1.IOperation, - protos.google.cloud.compute.v1.IDeleteAddressRequest|null|undefined, - {}|null|undefined>): - Promise<[ - LROperation, - protos.google.cloud.compute.v1.IOperation|undefined, {}|undefined - ]>|void { + | protos.google.cloud.compute.v1.IDeleteAddressRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.compute.v1.IOperation, + protos.google.cloud.compute.v1.IDeleteAddressRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + LROperation, + protos.google.cloud.compute.v1.IOperation | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'project': request.project ?? '', - 'region': request.region ?? '', - 'address': request.address ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + project: request.project ?? '', + region: request.region ?? '', + address: request.address ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('delete request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.compute.v1.IOperation, - protos.google.cloud.compute.v1.IDeleteAddressRequest|undefined, - {}|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.compute.v1.IOperation, + protos.google.cloud.compute.v1.IDeleteAddressRequest | undefined, + {} | undefined + > + | undefined = callback ? (error, response, nextRequest, rawResponse) => { this._log.info('delete response %j', rawResponse); callback!(error, response, nextRequest, rawResponse); // We verified `callback` above. } : undefined; - return this.innerApiCalls.delete(request, options, wrappedCallback) - ?.then(([response, operation, rawResponse]: [protos.google.cloud.compute.v1.IOperation, protos.google.cloud.compute.v1.IOperation, protos.google.cloud.compute.v1.IOperation]) => { - return [ - { latestResponse: response, done: false, name: response.id, metadata: null, result: {}}, - operation, - rawResponse - ]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .delete(request, options, wrappedCallback) + ?.then( + ([response, operation, rawResponse]: [ + protos.google.cloud.compute.v1.IOperation, + protos.google.cloud.compute.v1.IOperation, + protos.google.cloud.compute.v1.IOperation, + ]) => { + return [ + { + latestResponse: response, + done: false, + name: response.id, + metadata: null, + result: {}, + }, + operation, + rawResponse, + ]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Creates an address resource in the specified project by using the data included in the request. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.cloud.compute.v1.Address} request.addressResource - * The body resource for this request - * @param {string} request.project - * Project ID for this request. - * @param {string} request.region - * Name of the region for this request. - * @param {string} request.requestId - * An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. - * - * For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. - * - * The request ID must be a valid UUID with the exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000). - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing - * a long running operation. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * This method is considered to be in beta. This means while - * stable it is still a work-in-progress and under active development, - * and might get backwards-incompatible changes at any time. - * `.promise()` is not supported yet. - * @example include:samples/generated/v1/addresses.insert.js - * region_tag:compute_v1_generated_Addresses_Insert_async - */ + /** + * Creates an address resource in the specified project by using the data included in the request. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.cloud.compute.v1.Address} request.addressResource + * The body resource for this request + * @param {string} request.project + * Project ID for this request. + * @param {string} request.region + * Name of the region for this request. + * @param {string} request.requestId + * An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. + * + * For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. + * + * The request ID must be a valid UUID with the exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000). + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * This method is considered to be in beta. This means while + * stable it is still a work-in-progress and under active development, + * and might get backwards-incompatible changes at any time. + * `.promise()` is not supported yet. + * @example include:samples/generated/v1/addresses.insert.js + * region_tag:compute_v1_generated_Addresses_Insert_async + */ insert( - request?: protos.google.cloud.compute.v1.IInsertAddressRequest, - options?: CallOptions): - Promise<[ - LROperation, - protos.google.cloud.compute.v1.IOperation|undefined, {}|undefined - ]>; + request?: protos.google.cloud.compute.v1.IInsertAddressRequest, + options?: CallOptions, + ): Promise< + [ + LROperation, + protos.google.cloud.compute.v1.IOperation | undefined, + {} | undefined, + ] + >; insert( - request: protos.google.cloud.compute.v1.IInsertAddressRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.compute.v1.IOperation, - protos.google.cloud.compute.v1.IInsertAddressRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.compute.v1.IInsertAddressRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.compute.v1.IOperation, + protos.google.cloud.compute.v1.IInsertAddressRequest | null | undefined, + {} | null | undefined + >, + ): void; insert( - request: protos.google.cloud.compute.v1.IInsertAddressRequest, - callback: Callback< - protos.google.cloud.compute.v1.IOperation, - protos.google.cloud.compute.v1.IInsertAddressRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.compute.v1.IInsertAddressRequest, + callback: Callback< + protos.google.cloud.compute.v1.IOperation, + protos.google.cloud.compute.v1.IInsertAddressRequest | null | undefined, + {} | null | undefined + >, + ): void; insert( - request?: protos.google.cloud.compute.v1.IInsertAddressRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.compute.v1.IOperation, - protos.google.cloud.compute.v1.IInsertAddressRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.compute.v1.IInsertAddressRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.compute.v1.IOperation, - protos.google.cloud.compute.v1.IInsertAddressRequest|null|undefined, - {}|null|undefined>): - Promise<[ - LROperation, - protos.google.cloud.compute.v1.IOperation|undefined, {}|undefined - ]>|void { + | protos.google.cloud.compute.v1.IInsertAddressRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.compute.v1.IOperation, + protos.google.cloud.compute.v1.IInsertAddressRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + LROperation, + protos.google.cloud.compute.v1.IOperation | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'project': request.project ?? '', - 'region': request.region ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + project: request.project ?? '', + region: request.region ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('insert request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.compute.v1.IOperation, - protos.google.cloud.compute.v1.IInsertAddressRequest|undefined, - {}|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.compute.v1.IOperation, + protos.google.cloud.compute.v1.IInsertAddressRequest | undefined, + {} | undefined + > + | undefined = callback ? (error, response, nextRequest, rawResponse) => { this._log.info('insert response %j', rawResponse); callback!(error, response, nextRequest, rawResponse); // We verified `callback` above. } : undefined; - return this.innerApiCalls.insert(request, options, wrappedCallback) - ?.then(([response, operation, rawResponse]: [protos.google.cloud.compute.v1.IOperation, protos.google.cloud.compute.v1.IOperation, protos.google.cloud.compute.v1.IOperation]) => { - return [ - { latestResponse: response, done: false, name: response.id, metadata: null, result: {}}, - operation, - rawResponse - ]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .insert(request, options, wrappedCallback) + ?.then( + ([response, operation, rawResponse]: [ + protos.google.cloud.compute.v1.IOperation, + protos.google.cloud.compute.v1.IOperation, + protos.google.cloud.compute.v1.IOperation, + ]) => { + return [ + { + latestResponse: response, + done: false, + name: response.id, + metadata: null, + result: {}, + }, + operation, + rawResponse, + ]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } - -/** - * Retrieves an aggregated list of addresses. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.filter - * A filter expression that filters resources listed in the response. The expression must specify the field name, a comparison operator, and the value that you want to use for filtering. The value must be a string, a number, or a boolean. The comparison operator must be either `=`, `!=`, `>`, or `<`. - * - * For example, if you are filtering Compute Engine instances, you can exclude instances named `example-instance` by specifying `name != example-instance`. - * - * You can also filter nested fields. For example, you could specify `scheduling.automaticRestart = false` to include instances only if they are not scheduled for automatic restarts. You can use filtering on nested fields to filter based on resource labels. - * - * To filter on multiple expressions, provide each separate expression within parentheses. For example: ``` (scheduling.automaticRestart = true) (cpuPlatform = "Intel Skylake") ``` By default, each expression is an `AND` expression. However, you can include `AND` and `OR` expressions explicitly. For example: ``` (cpuPlatform = "Intel Skylake") OR (cpuPlatform = "Intel Broadwell") AND (scheduling.automaticRestart = true) ``` - * @param {boolean} request.includeAllScopes - * Indicates whether every visible scope for each scope type (zone, region, global) should be included in the response. For new resource types added after this field, the flag has no effect as new resource types will always include every visible scope for each scope type in response. For resource types which predate this field, if this flag is omitted or false, only scopes of the scope types where the resource type is expected to be found will be included. - * @param {number} request.maxResults - * The maximum number of results per page that should be returned. If the number of available results is larger than `maxResults`, Compute Engine returns a `nextPageToken` that can be used to get the next page of results in subsequent list requests. Acceptable values are `0` to `500`, inclusive. (Default: `500`) - * @param {string} request.orderBy - * Sorts list results by a certain order. By default, results are returned in alphanumerical order based on the resource name. - * - * You can also sort results in descending order based on the creation timestamp using `orderBy="creationTimestamp desc"`. This sorts results based on the `creationTimestamp` field in reverse chronological order (newest result first). Use this to sort resources like operations so that the newest operation is returned first. - * - * Currently, only sorting by `name` or `creationTimestamp desc` is supported. - * @param {string} request.pageToken - * Specifies a page token to use. Set `pageToken` to the `nextPageToken` returned by a previous list request to get the next page of results. - * @param {string} request.project - * Project ID for this request. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * as tuple [string, {@link protos.google.cloud.compute.v1.AddressesScopedList|AddressesScopedList}]. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v1/addresses.aggregated_list.js - * region_tag:compute_v1_generated_Addresses_AggregatedList_async - */ + /** + * Retrieves an aggregated list of addresses. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.filter + * A filter expression that filters resources listed in the response. The expression must specify the field name, a comparison operator, and the value that you want to use for filtering. The value must be a string, a number, or a boolean. The comparison operator must be either `=`, `!=`, `>`, or `<`. + * + * For example, if you are filtering Compute Engine instances, you can exclude instances named `example-instance` by specifying `name != example-instance`. + * + * You can also filter nested fields. For example, you could specify `scheduling.automaticRestart = false` to include instances only if they are not scheduled for automatic restarts. You can use filtering on nested fields to filter based on resource labels. + * + * To filter on multiple expressions, provide each separate expression within parentheses. For example: ``` (scheduling.automaticRestart = true) (cpuPlatform = "Intel Skylake") ``` By default, each expression is an `AND` expression. However, you can include `AND` and `OR` expressions explicitly. For example: ``` (cpuPlatform = "Intel Skylake") OR (cpuPlatform = "Intel Broadwell") AND (scheduling.automaticRestart = true) ``` + * @param {boolean} request.includeAllScopes + * Indicates whether every visible scope for each scope type (zone, region, global) should be included in the response. For new resource types added after this field, the flag has no effect as new resource types will always include every visible scope for each scope type in response. For resource types which predate this field, if this flag is omitted or false, only scopes of the scope types where the resource type is expected to be found will be included. + * @param {number} request.maxResults + * The maximum number of results per page that should be returned. If the number of available results is larger than `maxResults`, Compute Engine returns a `nextPageToken` that can be used to get the next page of results in subsequent list requests. Acceptable values are `0` to `500`, inclusive. (Default: `500`) + * @param {string} request.orderBy + * Sorts list results by a certain order. By default, results are returned in alphanumerical order based on the resource name. + * + * You can also sort results in descending order based on the creation timestamp using `orderBy="creationTimestamp desc"`. This sorts results based on the `creationTimestamp` field in reverse chronological order (newest result first). Use this to sort resources like operations so that the newest operation is returned first. + * + * Currently, only sorting by `name` or `creationTimestamp desc` is supported. + * @param {string} request.pageToken + * Specifies a page token to use. Set `pageToken` to the `nextPageToken` returned by a previous list request to get the next page of results. + * @param {string} request.project + * Project ID for this request. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * as tuple [string, {@link protos.google.cloud.compute.v1.AddressesScopedList|AddressesScopedList}]. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v1/addresses.aggregated_list.js + * region_tag:compute_v1_generated_Addresses_AggregatedList_async + */ aggregatedListAsync( - request?: protos.google.cloud.compute.v1.IAggregatedListAddressesRequest, - options?: CallOptions): - AsyncIterable<[string, protos.google.cloud.compute.v1.IAddressesScopedList]>{ + request?: protos.google.cloud.compute.v1.IAggregatedListAddressesRequest, + options?: CallOptions, + ): AsyncIterable< + [string, protos.google.cloud.compute.v1.IAddressesScopedList] + > { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'project': request.project ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + project: request.project ?? '', + }); const defaultCallSettings = this._defaults['aggregatedList']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('aggregatedList iterate %j', request); return this.descriptors.page.aggregatedList.asyncIterate( this.innerApiCalls['aggregatedList'] as GaxCall, request as {}, - callSettings - ) as AsyncIterable<[string, protos.google.cloud.compute.v1.IAddressesScopedList]>; + callSettings, + ) as AsyncIterable< + [string, protos.google.cloud.compute.v1.IAddressesScopedList] + >; } - /** - * Retrieves a list of addresses contained within the specified region. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.filter - * A filter expression that filters resources listed in the response. The expression must specify the field name, a comparison operator, and the value that you want to use for filtering. The value must be a string, a number, or a boolean. The comparison operator must be either =, !=, >, or <. - * - * For example, if you are filtering Compute Engine instances, you can exclude instances named example-instance by specifying name != example-instance. - * - * You can also filter nested fields. For example, you could specify scheduling.automaticRestart = false to include instances only if they are not scheduled for automatic restarts. You can use filtering on nested fields to filter based on resource labels. - * - * To filter on multiple expressions, provide each separate expression within parentheses. For example, (scheduling.automaticRestart = true) (cpuPlatform = "Intel Skylake"). By default, each expression is an AND expression. However, you can include AND and OR expressions explicitly. For example, (cpuPlatform = "Intel Skylake") OR (cpuPlatform = "Intel Broadwell") AND (scheduling.automaticRestart = true). - * @param {number} request.maxResults - * The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests. Acceptable values are 0 to 500, inclusive. (Default: 500) - * @param {string} request.orderBy - * Sorts list results by a certain order. By default, results are returned in alphanumerical order based on the resource name. - * - * You can also sort results in descending order based on the creation timestamp using orderBy="creationTimestamp desc". This sorts results based on the creationTimestamp field in reverse chronological order (newest result first). Use this to sort resources like operations so that the newest operation is returned first. - * - * Currently, only sorting by name or creationTimestamp desc is supported. - * @param {string} request.pageToken - * Specifies a page token to use. Set pageToken to the nextPageToken returned by a previous list request to get the next page of results. - * @param {string} request.project - * Project ID for this request. - * @param {string} request.region - * Name of the region for this request. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.cloud.compute.v1.Address|Address}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `listAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Retrieves a list of addresses contained within the specified region. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.filter + * A filter expression that filters resources listed in the response. The expression must specify the field name, a comparison operator, and the value that you want to use for filtering. The value must be a string, a number, or a boolean. The comparison operator must be either =, !=, >, or <. + * + * For example, if you are filtering Compute Engine instances, you can exclude instances named example-instance by specifying name != example-instance. + * + * You can also filter nested fields. For example, you could specify scheduling.automaticRestart = false to include instances only if they are not scheduled for automatic restarts. You can use filtering on nested fields to filter based on resource labels. + * + * To filter on multiple expressions, provide each separate expression within parentheses. For example, (scheduling.automaticRestart = true) (cpuPlatform = "Intel Skylake"). By default, each expression is an AND expression. However, you can include AND and OR expressions explicitly. For example, (cpuPlatform = "Intel Skylake") OR (cpuPlatform = "Intel Broadwell") AND (scheduling.automaticRestart = true). + * @param {number} request.maxResults + * The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests. Acceptable values are 0 to 500, inclusive. (Default: 500) + * @param {string} request.orderBy + * Sorts list results by a certain order. By default, results are returned in alphanumerical order based on the resource name. + * + * You can also sort results in descending order based on the creation timestamp using orderBy="creationTimestamp desc". This sorts results based on the creationTimestamp field in reverse chronological order (newest result first). Use this to sort resources like operations so that the newest operation is returned first. + * + * Currently, only sorting by name or creationTimestamp desc is supported. + * @param {string} request.pageToken + * Specifies a page token to use. Set pageToken to the nextPageToken returned by a previous list request to get the next page of results. + * @param {string} request.project + * Project ID for this request. + * @param {string} request.region + * Name of the region for this request. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.cloud.compute.v1.Address|Address}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ list( - request?: protos.google.cloud.compute.v1.IListAddressesRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.compute.v1.IAddress[], - protos.google.cloud.compute.v1.IListAddressesRequest|null, - protos.google.cloud.compute.v1.IAddressList - ]>; + request?: protos.google.cloud.compute.v1.IListAddressesRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.compute.v1.IAddress[], + protos.google.cloud.compute.v1.IListAddressesRequest | null, + protos.google.cloud.compute.v1.IAddressList, + ] + >; list( - request: protos.google.cloud.compute.v1.IListAddressesRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.cloud.compute.v1.IListAddressesRequest, - protos.google.cloud.compute.v1.IAddressList|null|undefined, - protos.google.cloud.compute.v1.IAddress>): void; + request: protos.google.cloud.compute.v1.IListAddressesRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.cloud.compute.v1.IListAddressesRequest, + protos.google.cloud.compute.v1.IAddressList | null | undefined, + protos.google.cloud.compute.v1.IAddress + >, + ): void; list( - request: protos.google.cloud.compute.v1.IListAddressesRequest, - callback: PaginationCallback< - protos.google.cloud.compute.v1.IListAddressesRequest, - protos.google.cloud.compute.v1.IAddressList|null|undefined, - protos.google.cloud.compute.v1.IAddress>): void; + request: protos.google.cloud.compute.v1.IListAddressesRequest, + callback: PaginationCallback< + protos.google.cloud.compute.v1.IListAddressesRequest, + protos.google.cloud.compute.v1.IAddressList | null | undefined, + protos.google.cloud.compute.v1.IAddress + >, + ): void; list( - request?: protos.google.cloud.compute.v1.IListAddressesRequest, - optionsOrCallback?: CallOptions|PaginationCallback< - protos.google.cloud.compute.v1.IListAddressesRequest, - protos.google.cloud.compute.v1.IAddressList|null|undefined, - protos.google.cloud.compute.v1.IAddress>, - callback?: PaginationCallback< + request?: protos.google.cloud.compute.v1.IListAddressesRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.cloud.compute.v1.IListAddressesRequest, - protos.google.cloud.compute.v1.IAddressList|null|undefined, - protos.google.cloud.compute.v1.IAddress>): - Promise<[ - protos.google.cloud.compute.v1.IAddress[], - protos.google.cloud.compute.v1.IListAddressesRequest|null, - protos.google.cloud.compute.v1.IAddressList - ]>|void { + protos.google.cloud.compute.v1.IAddressList | null | undefined, + protos.google.cloud.compute.v1.IAddress + >, + callback?: PaginationCallback< + protos.google.cloud.compute.v1.IListAddressesRequest, + protos.google.cloud.compute.v1.IAddressList | null | undefined, + protos.google.cloud.compute.v1.IAddress + >, + ): Promise< + [ + protos.google.cloud.compute.v1.IAddress[], + protos.google.cloud.compute.v1.IListAddressesRequest | null, + protos.google.cloud.compute.v1.IAddressList, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'project': request.project ?? '', - 'region': request.region ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + project: request.project ?? '', + region: request.region ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.cloud.compute.v1.IListAddressesRequest, - protos.google.cloud.compute.v1.IAddressList|null|undefined, - protos.google.cloud.compute.v1.IAddress>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.cloud.compute.v1.IListAddressesRequest, + protos.google.cloud.compute.v1.IAddressList | null | undefined, + protos.google.cloud.compute.v1.IAddress + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('list values %j', values); callback!(error, values, nextPageRequest, rawResponse); @@ -742,140 +896,144 @@ export class AddressesClient { this._log.info('list request %j', request); return this.innerApiCalls .list(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.cloud.compute.v1.IAddress[], - protos.google.cloud.compute.v1.IListAddressesRequest|null, - protos.google.cloud.compute.v1.IAddressList - ]) => { - this._log.info('list values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.cloud.compute.v1.IAddress[], + protos.google.cloud.compute.v1.IListAddressesRequest | null, + protos.google.cloud.compute.v1.IAddressList, + ]) => { + this._log.info('list values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `list`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.filter - * A filter expression that filters resources listed in the response. The expression must specify the field name, a comparison operator, and the value that you want to use for filtering. The value must be a string, a number, or a boolean. The comparison operator must be either =, !=, >, or <. - * - * For example, if you are filtering Compute Engine instances, you can exclude instances named example-instance by specifying name != example-instance. - * - * You can also filter nested fields. For example, you could specify scheduling.automaticRestart = false to include instances only if they are not scheduled for automatic restarts. You can use filtering on nested fields to filter based on resource labels. - * - * To filter on multiple expressions, provide each separate expression within parentheses. For example, (scheduling.automaticRestart = true) (cpuPlatform = "Intel Skylake"). By default, each expression is an AND expression. However, you can include AND and OR expressions explicitly. For example, (cpuPlatform = "Intel Skylake") OR (cpuPlatform = "Intel Broadwell") AND (scheduling.automaticRestart = true). - * @param {number} request.maxResults - * The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests. Acceptable values are 0 to 500, inclusive. (Default: 500) - * @param {string} request.orderBy - * Sorts list results by a certain order. By default, results are returned in alphanumerical order based on the resource name. - * - * You can also sort results in descending order based on the creation timestamp using orderBy="creationTimestamp desc". This sorts results based on the creationTimestamp field in reverse chronological order (newest result first). Use this to sort resources like operations so that the newest operation is returned first. - * - * Currently, only sorting by name or creationTimestamp desc is supported. - * @param {string} request.pageToken - * Specifies a page token to use. Set pageToken to the nextPageToken returned by a previous list request to get the next page of results. - * @param {string} request.project - * Project ID for this request. - * @param {string} request.region - * Name of the region for this request. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.cloud.compute.v1.Address|Address} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `listAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `list`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.filter + * A filter expression that filters resources listed in the response. The expression must specify the field name, a comparison operator, and the value that you want to use for filtering. The value must be a string, a number, or a boolean. The comparison operator must be either =, !=, >, or <. + * + * For example, if you are filtering Compute Engine instances, you can exclude instances named example-instance by specifying name != example-instance. + * + * You can also filter nested fields. For example, you could specify scheduling.automaticRestart = false to include instances only if they are not scheduled for automatic restarts. You can use filtering on nested fields to filter based on resource labels. + * + * To filter on multiple expressions, provide each separate expression within parentheses. For example, (scheduling.automaticRestart = true) (cpuPlatform = "Intel Skylake"). By default, each expression is an AND expression. However, you can include AND and OR expressions explicitly. For example, (cpuPlatform = "Intel Skylake") OR (cpuPlatform = "Intel Broadwell") AND (scheduling.automaticRestart = true). + * @param {number} request.maxResults + * The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests. Acceptable values are 0 to 500, inclusive. (Default: 500) + * @param {string} request.orderBy + * Sorts list results by a certain order. By default, results are returned in alphanumerical order based on the resource name. + * + * You can also sort results in descending order based on the creation timestamp using orderBy="creationTimestamp desc". This sorts results based on the creationTimestamp field in reverse chronological order (newest result first). Use this to sort resources like operations so that the newest operation is returned first. + * + * Currently, only sorting by name or creationTimestamp desc is supported. + * @param {string} request.pageToken + * Specifies a page token to use. Set pageToken to the nextPageToken returned by a previous list request to get the next page of results. + * @param {string} request.project + * Project ID for this request. + * @param {string} request.region + * Name of the region for this request. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.cloud.compute.v1.Address|Address} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listStream( - request?: protos.google.cloud.compute.v1.IListAddressesRequest, - options?: CallOptions): - Transform{ + request?: protos.google.cloud.compute.v1.IListAddressesRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'project': request.project ?? '', - 'region': request.region ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + project: request.project ?? '', + region: request.region ?? '', + }); const defaultCallSettings = this._defaults['list']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('list stream %j', request); return this.descriptors.page.list.createStream( this.innerApiCalls.list as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `list`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.filter - * A filter expression that filters resources listed in the response. The expression must specify the field name, a comparison operator, and the value that you want to use for filtering. The value must be a string, a number, or a boolean. The comparison operator must be either =, !=, >, or <. - * - * For example, if you are filtering Compute Engine instances, you can exclude instances named example-instance by specifying name != example-instance. - * - * You can also filter nested fields. For example, you could specify scheduling.automaticRestart = false to include instances only if they are not scheduled for automatic restarts. You can use filtering on nested fields to filter based on resource labels. - * - * To filter on multiple expressions, provide each separate expression within parentheses. For example, (scheduling.automaticRestart = true) (cpuPlatform = "Intel Skylake"). By default, each expression is an AND expression. However, you can include AND and OR expressions explicitly. For example, (cpuPlatform = "Intel Skylake") OR (cpuPlatform = "Intel Broadwell") AND (scheduling.automaticRestart = true). - * @param {number} request.maxResults - * The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests. Acceptable values are 0 to 500, inclusive. (Default: 500) - * @param {string} request.orderBy - * Sorts list results by a certain order. By default, results are returned in alphanumerical order based on the resource name. - * - * You can also sort results in descending order based on the creation timestamp using orderBy="creationTimestamp desc". This sorts results based on the creationTimestamp field in reverse chronological order (newest result first). Use this to sort resources like operations so that the newest operation is returned first. - * - * Currently, only sorting by name or creationTimestamp desc is supported. - * @param {string} request.pageToken - * Specifies a page token to use. Set pageToken to the nextPageToken returned by a previous list request to get the next page of results. - * @param {string} request.project - * Project ID for this request. - * @param {string} request.region - * Name of the region for this request. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.cloud.compute.v1.Address|Address}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v1/addresses.list.js - * region_tag:compute_v1_generated_Addresses_List_async - */ + /** + * Equivalent to `list`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.filter + * A filter expression that filters resources listed in the response. The expression must specify the field name, a comparison operator, and the value that you want to use for filtering. The value must be a string, a number, or a boolean. The comparison operator must be either =, !=, >, or <. + * + * For example, if you are filtering Compute Engine instances, you can exclude instances named example-instance by specifying name != example-instance. + * + * You can also filter nested fields. For example, you could specify scheduling.automaticRestart = false to include instances only if they are not scheduled for automatic restarts. You can use filtering on nested fields to filter based on resource labels. + * + * To filter on multiple expressions, provide each separate expression within parentheses. For example, (scheduling.automaticRestart = true) (cpuPlatform = "Intel Skylake"). By default, each expression is an AND expression. However, you can include AND and OR expressions explicitly. For example, (cpuPlatform = "Intel Skylake") OR (cpuPlatform = "Intel Broadwell") AND (scheduling.automaticRestart = true). + * @param {number} request.maxResults + * The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests. Acceptable values are 0 to 500, inclusive. (Default: 500) + * @param {string} request.orderBy + * Sorts list results by a certain order. By default, results are returned in alphanumerical order based on the resource name. + * + * You can also sort results in descending order based on the creation timestamp using orderBy="creationTimestamp desc". This sorts results based on the creationTimestamp field in reverse chronological order (newest result first). Use this to sort resources like operations so that the newest operation is returned first. + * + * Currently, only sorting by name or creationTimestamp desc is supported. + * @param {string} request.pageToken + * Specifies a page token to use. Set pageToken to the nextPageToken returned by a previous list request to get the next page of results. + * @param {string} request.project + * Project ID for this request. + * @param {string} request.region + * Name of the region for this request. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.cloud.compute.v1.Address|Address}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v1/addresses.list.js + * region_tag:compute_v1_generated_Addresses_List_async + */ listAsync( - request?: protos.google.cloud.compute.v1.IListAddressesRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.cloud.compute.v1.IListAddressesRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'project': request.project ?? '', - 'region': request.region ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + project: request.project ?? '', + region: request.region ?? '', + }); const defaultCallSettings = this._defaults['list']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('list iterate %j', request); return this.descriptors.page.list.asyncIterate( this.innerApiCalls['list'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } @@ -887,7 +1045,7 @@ export class AddressesClient { */ close(): Promise { if (this.addressesStub && !this._terminated) { - return this.addressesStub.then(stub => { + return this.addressesStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -895,4 +1053,4 @@ export class AddressesClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/core/generator/gapic-generator-typescript/baselines/compute-esm/esm/src/v1/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/compute-esm/esm/src/v1/index.ts.baseline index 023b44fd7f8e..e6457b8ed0a0 100644 --- a/core/generator/gapic-generator-typescript/baselines/compute-esm/esm/src/v1/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/compute-esm/esm/src/v1/index.ts.baseline @@ -16,5 +16,5 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -export {AddressesClient} from './addresses_client.js'; -export {RegionOperationsClient} from './region_operations_client.js'; +export { AddressesClient } from './addresses_client.js'; +export { RegionOperationsClient } from './region_operations_client.js'; diff --git a/core/generator/gapic-generator-typescript/baselines/compute-esm/esm/src/v1/region_operations_client.ts.baseline b/core/generator/gapic-generator-typescript/baselines/compute-esm/esm/src/v1/region_operations_client.ts.baseline index b19e1d149289..9058fd9f4803 100644 --- a/core/generator/gapic-generator-typescript/baselines/compute-esm/esm/src/v1/region_operations_client.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/compute-esm/esm/src/v1/region_operations_client.ts.baseline @@ -18,15 +18,20 @@ /* global window */ import * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions} from 'google-gax'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, +} from 'google-gax'; // @ts-ignore import type * as protos from '../../../protos/protos.js'; import * as region_operations_client_config from './region_operations_client_config.json'; import fs from 'fs'; import path from 'path'; -import {fileURLToPath} from 'url'; -import {getJSON} from '../json-helper.cjs'; +import { fileURLToPath } from 'url'; +import { getJSON } from '../json-helper.cjs'; // @ts-ignore const dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -36,15 +41,15 @@ const dirname = path.dirname(fileURLToPath(import.meta.url)); * This file defines retry strategy and timeouts for all API methods in this library. */ const gapicConfig = getJSON( - path.join(dirname, 'region_operations_client_config.json') + path.join(dirname, 'region_operations_client_config.json'), ); const jsonProtos = getJSON( - path.join(dirname, '..', '..', '..', 'protos/protos.json') + path.join(dirname, '..', '..', '..', 'protos/protos.json'), ); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; const version = getJSON( - path.join(dirname, '..', '..', '..', '..', 'package.json') + path.join(dirname, '..', '..', '..', '..', 'package.json'), ).version; /** @@ -59,7 +64,7 @@ export class RegionOperationsClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('compute'); @@ -71,8 +76,8 @@ export class RegionOperationsClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - regionOperationsStub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + regionOperationsStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of RegionOperationsClient. @@ -114,27 +119,48 @@ export class RegionOperationsClient { * const client = new RegionOperationsClient({fallback: 'rest'}, gax); * ``` */ - constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { // Ensure that options include all the required fields. const staticMembers = this.constructor as typeof RegionOperationsClient; - if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { - throw new Error('Please set either universe_domain or universeDomain, but not both.'); + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); } - const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; - this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; this._servicePath = 'compute.' + this._universeDomain; - const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; // Implicitely set 'rest' value for the apis use rest as transport (eg. googleapis-discovery apis). if (!opts) { - opts = {fallback: 'rest'}; + opts = { fallback: 'rest' }; } else { opts.fallback = opts.fallback ?? 'rest'; } - const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. if (servicePath !== this._servicePath && !('scopes' in opts)) { @@ -156,7 +182,7 @@ export class RegionOperationsClient { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set defaultServicePath on the auth object. this.auth.defaultServicePath = this._servicePath; @@ -170,10 +196,7 @@ export class RegionOperationsClient { const isEsm = true; const isEsmString = isEsm ? '-esm' : '-cjs'; // Determine the client header string. - const clientHeader = [ - `gax/${this._gaxModule.version}`, - `gapic/${version}`, - ]; + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/{process.versions.node}${isEsmString}`); } else { @@ -181,7 +204,7 @@ export class RegionOperationsClient { } if (!opts.fallback) { clientHeader.push(`grpc/${this._gaxGrpc.grpcVersion}`); - } else if (opts.fallback === 'rest' ) { + } else if (opts.fallback === 'rest') { clientHeader.push(`rest/${this._gaxGrpc.grpcVersion}`); } if (opts.libName && opts.libVersion) { @@ -189,12 +212,17 @@ export class RegionOperationsClient { } // Load the applicable protos. - this._protos = this._gaxGrpc.loadProtoJSON(jsonProtos as gax.protobuf.INamespace); + this._protos = this._gaxGrpc.loadProtoJSON( + jsonProtos as gax.protobuf.INamespace, + ); // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.cloud.compute.v1.RegionOperations', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.cloud.compute.v1.RegionOperations', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + { 'x-goog-api-client': clientHeader.join(' ') }, + ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -225,36 +253,40 @@ export class RegionOperationsClient { // Put together the "service stub" for // google.cloud.compute.v1.RegionOperations. this.regionOperationsStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.cloud.compute.v1.RegionOperations') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.cloud.compute.v1.RegionOperations', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.cloud.compute.v1.RegionOperations, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts, + this._providedCustomServicePath, + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const regionOperationsStubMethods = - ['get', 'wait']; + const regionOperationsStubMethods = ['get', 'wait']; for (const methodName of regionOperationsStubMethods) { const callPromise = this.regionOperationsStub.then( - stub => (...args: Array<{}>) => { - if (this._terminated) { - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error|null|undefined) => () => { + (stub) => + (...args: Array<{}>) => { + if (this._terminated) { + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { throw err; - }); + }, + ); - const descriptor = - undefined; + const descriptor = undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -269,8 +301,14 @@ export class RegionOperationsClient { * @returns {string} The DNS address for this service. */ static get servicePath() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'compute.googleapis.com'; } @@ -282,8 +320,14 @@ export class RegionOperationsClient { * @returns {string} The DNS address for this service. */ static get apiEndpoint() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'compute.googleapis.com'; } @@ -317,7 +361,7 @@ export class RegionOperationsClient { return [ 'https://www.googleapis.com/auth/compute.readonly', 'https://www.googleapis.com/auth/compute', - 'https://www.googleapis.com/auth/cloud-platform' + 'https://www.googleapis.com/auth/cloud-platform', ]; } @@ -327,8 +371,9 @@ export class RegionOperationsClient { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId(callback?: Callback): - Promise|void { + getProjectId( + callback?: Callback, + ): Promise | void { if (callback) { this.auth.getProjectId(callback); return; @@ -339,210 +384,294 @@ export class RegionOperationsClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Retrieves the specified region-specific Operations resource. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.operation - * Name of the Operations resource to return. - * @param {string} request.project - * Project ID for this request. - * @param {string} request.region - * Name of the region for this request. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.compute.v1.Operation|Operation}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1/region_operations.get.js - * region_tag:compute_v1_generated_RegionOperations_Get_async - */ + /** + * Retrieves the specified region-specific Operations resource. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.operation + * Name of the Operations resource to return. + * @param {string} request.project + * Project ID for this request. + * @param {string} request.region + * Name of the region for this request. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.compute.v1.Operation|Operation}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/region_operations.get.js + * region_tag:compute_v1_generated_RegionOperations_Get_async + */ get( - request?: protos.google.cloud.compute.v1.IGetRegionOperationRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.compute.v1.IOperation, - protos.google.cloud.compute.v1.IGetRegionOperationRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.compute.v1.IGetRegionOperationRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.compute.v1.IOperation, + protos.google.cloud.compute.v1.IGetRegionOperationRequest | undefined, + {} | undefined, + ] + >; get( - request: protos.google.cloud.compute.v1.IGetRegionOperationRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.compute.v1.IOperation, - protos.google.cloud.compute.v1.IGetRegionOperationRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.compute.v1.IGetRegionOperationRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.compute.v1.IOperation, + | protos.google.cloud.compute.v1.IGetRegionOperationRequest + | null + | undefined, + {} | null | undefined + >, + ): void; get( - request: protos.google.cloud.compute.v1.IGetRegionOperationRequest, - callback: Callback< - protos.google.cloud.compute.v1.IOperation, - protos.google.cloud.compute.v1.IGetRegionOperationRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.compute.v1.IGetRegionOperationRequest, + callback: Callback< + protos.google.cloud.compute.v1.IOperation, + | protos.google.cloud.compute.v1.IGetRegionOperationRequest + | null + | undefined, + {} | null | undefined + >, + ): void; get( - request?: protos.google.cloud.compute.v1.IGetRegionOperationRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.compute.v1.IOperation, - protos.google.cloud.compute.v1.IGetRegionOperationRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.compute.v1.IGetRegionOperationRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.compute.v1.IOperation, - protos.google.cloud.compute.v1.IGetRegionOperationRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.compute.v1.IOperation, - protos.google.cloud.compute.v1.IGetRegionOperationRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.compute.v1.IGetRegionOperationRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.compute.v1.IOperation, + | protos.google.cloud.compute.v1.IGetRegionOperationRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.compute.v1.IOperation, + protos.google.cloud.compute.v1.IGetRegionOperationRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'project': request.project ?? '', - 'region': request.region ?? '', - 'operation': request.operation ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + project: request.project ?? '', + region: request.region ?? '', + operation: request.operation ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('get request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.compute.v1.IOperation, - protos.google.cloud.compute.v1.IGetRegionOperationRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.compute.v1.IOperation, + | protos.google.cloud.compute.v1.IGetRegionOperationRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('get response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.get(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.compute.v1.IOperation, - protos.google.cloud.compute.v1.IGetRegionOperationRequest|undefined, {}|undefined - ]) => { - this._log.info('get response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .get(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.compute.v1.IOperation, + protos.google.cloud.compute.v1.IGetRegionOperationRequest | undefined, + {} | undefined, + ]) => { + this._log.info('get response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Waits for the specified Operation resource to return as `DONE` or for the request to approach the 2 minute deadline, and retrieves the specified Operation resource. This method differs from the `GET` method in that it waits for no more than the default deadline (2 minutes) and then returns the current state of the operation, which might be `DONE` or still in progress. - * - * This method is called on a best-effort basis. Specifically: - * - In uncommon cases, when the server is overloaded, the request might return before the default deadline is reached, or might return after zero seconds. - * - If the default deadline is reached, there is no guarantee that the operation is actually done when the method returns. Be prepared to retry if the operation is not `DONE`. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.operation - * Name of the Operations resource to return. - * @param {string} request.project - * Project ID for this request. - * @param {string} request.region - * Name of the region for this request. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.compute.v1.Operation|Operation}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1/region_operations.wait.js - * region_tag:compute_v1_generated_RegionOperations_Wait_async - */ + /** + * Waits for the specified Operation resource to return as `DONE` or for the request to approach the 2 minute deadline, and retrieves the specified Operation resource. This method differs from the `GET` method in that it waits for no more than the default deadline (2 minutes) and then returns the current state of the operation, which might be `DONE` or still in progress. + * + * This method is called on a best-effort basis. Specifically: + * - In uncommon cases, when the server is overloaded, the request might return before the default deadline is reached, or might return after zero seconds. + * - If the default deadline is reached, there is no guarantee that the operation is actually done when the method returns. Be prepared to retry if the operation is not `DONE`. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.operation + * Name of the Operations resource to return. + * @param {string} request.project + * Project ID for this request. + * @param {string} request.region + * Name of the region for this request. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.compute.v1.Operation|Operation}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/region_operations.wait.js + * region_tag:compute_v1_generated_RegionOperations_Wait_async + */ wait( - request?: protos.google.cloud.compute.v1.IWaitRegionOperationRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.compute.v1.IOperation, - protos.google.cloud.compute.v1.IWaitRegionOperationRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.compute.v1.IWaitRegionOperationRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.compute.v1.IOperation, + protos.google.cloud.compute.v1.IWaitRegionOperationRequest | undefined, + {} | undefined, + ] + >; wait( - request: protos.google.cloud.compute.v1.IWaitRegionOperationRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.compute.v1.IOperation, - protos.google.cloud.compute.v1.IWaitRegionOperationRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.compute.v1.IWaitRegionOperationRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.compute.v1.IOperation, + | protos.google.cloud.compute.v1.IWaitRegionOperationRequest + | null + | undefined, + {} | null | undefined + >, + ): void; wait( - request: protos.google.cloud.compute.v1.IWaitRegionOperationRequest, - callback: Callback< - protos.google.cloud.compute.v1.IOperation, - protos.google.cloud.compute.v1.IWaitRegionOperationRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.compute.v1.IWaitRegionOperationRequest, + callback: Callback< + protos.google.cloud.compute.v1.IOperation, + | protos.google.cloud.compute.v1.IWaitRegionOperationRequest + | null + | undefined, + {} | null | undefined + >, + ): void; wait( - request?: protos.google.cloud.compute.v1.IWaitRegionOperationRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.cloud.compute.v1.IWaitRegionOperationRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.compute.v1.IOperation, - protos.google.cloud.compute.v1.IWaitRegionOperationRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.cloud.compute.v1.IOperation, - protos.google.cloud.compute.v1.IWaitRegionOperationRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.compute.v1.IOperation, - protos.google.cloud.compute.v1.IWaitRegionOperationRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.compute.v1.IWaitRegionOperationRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.compute.v1.IOperation, + | protos.google.cloud.compute.v1.IWaitRegionOperationRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.compute.v1.IOperation, + protos.google.cloud.compute.v1.IWaitRegionOperationRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'project': request.project ?? '', - 'region': request.region ?? '', - 'operation': request.operation ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + project: request.project ?? '', + region: request.region ?? '', + operation: request.operation ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('wait request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.compute.v1.IOperation, - protos.google.cloud.compute.v1.IWaitRegionOperationRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.compute.v1.IOperation, + | protos.google.cloud.compute.v1.IWaitRegionOperationRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('wait response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.wait(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.compute.v1.IOperation, - protos.google.cloud.compute.v1.IWaitRegionOperationRequest|undefined, {}|undefined - ]) => { - this._log.info('wait response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .wait(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.compute.v1.IOperation, + ( + | protos.google.cloud.compute.v1.IWaitRegionOperationRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('wait response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } - /** * Terminate the gRPC channel and close the client. * @@ -551,7 +680,7 @@ export class RegionOperationsClient { */ close(): Promise { if (this.regionOperationsStub && !this._terminated) { - return this.regionOperationsStub.then(stub => { + return this.regionOperationsStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -559,4 +688,4 @@ export class RegionOperationsClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/core/generator/gapic-generator-typescript/baselines/compute-esm/esm/system-test/fixtures/sample/src/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/compute-esm/esm/system-test/fixtures/sample/src/index.ts.baseline index 8f000a23986d..fbf109db0a93 100644 --- a/core/generator/gapic-generator-typescript/baselines/compute-esm/esm/system-test/fixtures/sample/src/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/compute-esm/esm/system-test/fixtures/sample/src/index.ts.baseline @@ -17,7 +17,7 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -import {AddressesClient, RegionOperationsClient} from '@google-cloud/compute'; +import { AddressesClient, RegionOperationsClient } from '@google-cloud/compute'; // check that the client class type name can be used function doStuffWithAddressesClient(client: AddressesClient) { diff --git a/core/generator/gapic-generator-typescript/baselines/compute-esm/esm/system-test/install.ts.baseline b/core/generator/gapic-generator-typescript/baselines/compute-esm/esm/system-test/install.ts.baseline index e079c4fa1101..d109fdd8c97f 100644 --- a/core/generator/gapic-generator-typescript/baselines/compute-esm/esm/system-test/install.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/compute-esm/esm/system-test/install.ts.baseline @@ -16,40 +16,45 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -import {packNTest} from 'pack-n-play'; -import {readFileSync} from 'fs'; -import {describe, it} from 'mocha'; +import { packNTest } from 'pack-n-play'; +import { readFileSync } from 'fs'; +import { describe, it } from 'mocha'; describe('📦 pack-n-play test', () => { - it('TypeScript', async function() { + it('TypeScript', async function () { this.timeout(300000); await packNTest({ packageDir: process.cwd(), sample: { description: 'TypeScript user can use the type definitions', - ts: readFileSync('./esm/system-test/fixtures/sample/src/index.ts').toString() - } + ts: readFileSync( + './esm/system-test/fixtures/sample/src/index.ts', + ).toString(), + }, }); }); - it('ESM module', async function() { + it('ESM module', async function () { this.timeout(300000); await packNTest({ sample: { description: 'Should be able to import using ESM', - esm: readFileSync('./esm/system-test/fixtures/sample/src/index.js').toString(), + esm: readFileSync( + './esm/system-test/fixtures/sample/src/index.js', + ).toString(), }, }); }); - it('CJS module', async function() { + it('CJS module', async function () { this.timeout(300000); await packNTest({ sample: { description: 'Should be able to import using CJS', - cjs: readFileSync('./esm/system-test/fixtures/sample/src/index.cjs').toString(), + cjs: readFileSync( + './esm/system-test/fixtures/sample/src/index.cjs', + ).toString(), }, }); }); - }); diff --git a/core/generator/gapic-generator-typescript/baselines/compute-esm/esm/test/gapic_addresses_v1.ts.baseline b/core/generator/gapic-generator-typescript/baselines/compute-esm/esm/test/gapic_addresses_v1.ts.baseline index c09f37884264..3514d46ffeb8 100644 --- a/core/generator/gapic-generator-typescript/baselines/compute-esm/esm/test/gapic_addresses_v1.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/compute-esm/esm/test/gapic_addresses_v1.ts.baseline @@ -20,16 +20,16 @@ import * as protos from '../../protos/protos.js'; import assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it, beforeEach, afterEach} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it, beforeEach, afterEach } from 'mocha'; import * as addressesModule from '../src/index.js'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; -import {GoogleAuth, protobuf} from 'google-gax'; +import { GoogleAuth, protobuf } from 'google-gax'; import fs from 'fs'; import path from 'path'; -import {fileURLToPath} from 'url'; +import { fileURLToPath } from 'url'; // @ts-ignore const dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -37,75 +37,105 @@ const dirname = path.dirname(fileURLToPath(import.meta.url)); // to fill in default values for request objects const root = protobuf.Root.fromJSON( JSON.parse( - fs.readFileSync(path.join(dirname, '..', '..', 'protos/protos.json'), 'utf8') - )) + fs.readFileSync( + path.join(dirname, '..', '..', 'protos/protos.json'), + 'utf8', + ), + ), +); // eslint-disable-next-line @typescript-eslint/no-unused-vars function getTypeDefaultValue(typeName: string, fields: string[]) { - let type = root.lookupType(typeName) as protobuf.Type; - for (const field of fields.slice(0, -1)) { - type = type?.fields[field]?.resolvedType as protobuf.Type; - } - return type?.fields[fields[fields.length - 1]]?.defaultValue ?? null; + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type?.fields[field]?.resolvedType as protobuf.Type; + } + return type?.fields[fields[fields.length - 1]]?.defaultValue ?? null; } function generateSampleMessage(instance: T) { - const filledObject = (instance.constructor as typeof protobuf.Message) - .toObject(instance as protobuf.Message, {defaults: true}); - return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, { defaults: true }); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; } function stubSimpleCall(response?: ResponseType, error?: Error) { - return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); } -function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { - return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +function stubSimpleCallWithCallback( + response?: ResponseType, + error?: Error, +) { + return error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); } -function stubPageStreamingCall(responses?: ResponseType[], error?: Error) { - const pagingStub = sinon.stub(); - if (responses) { - for (let i = 0; i < responses.length; ++i) { - pagingStub.onCall(i).callsArgWith(2, null, responses[i]); - } +function stubPageStreamingCall( + responses?: ResponseType[], + error?: Error, +) { + const pagingStub = sinon.stub(); + if (responses) { + for (let i = 0; i < responses.length; ++i) { + pagingStub.onCall(i).callsArgWith(2, null, responses[i]); } - const transformStub = error ? sinon.stub().callsArgWith(2, error) : pagingStub; - const mockStream = new PassThrough({ - objectMode: true, - transform: transformStub, - }); - // trigger as many responses as needed - if (responses) { - for (let i = 0; i < responses.length; ++i) { - setImmediate(() => { mockStream.write({}); }); - } - setImmediate(() => { mockStream.end(); }); - } else { - setImmediate(() => { mockStream.write({}); }); - setImmediate(() => { mockStream.end(); }); + } + const transformStub = error + ? sinon.stub().callsArgWith(2, error) + : pagingStub; + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + // trigger as many responses as needed + if (responses) { + for (let i = 0; i < responses.length; ++i) { + setImmediate(() => { + mockStream.write({}); + }); } - return sinon.stub().returns(mockStream); + setImmediate(() => { + mockStream.end(); + }); + } else { + setImmediate(() => { + mockStream.write({}); + }); + setImmediate(() => { + mockStream.end(); + }); + } + return sinon.stub().returns(mockStream); } -function stubAsyncIterationCall(responses?: ResponseType[], error?: Error) { - let counter = 0; - const asyncIterable = { - [Symbol.asyncIterator]() { - return { - async next() { - if (error) { - return Promise.reject(error); - } - if (counter >= responses!.length) { - return Promise.resolve({done: true, value: undefined}); - } - return Promise.resolve({done: false, value: responses![counter++]}); - } - }; - } - }; - return sinon.stub().returns(asyncIterable); +function stubAsyncIterationCall( + responses?: ResponseType[], + error?: Error, +) { + let counter = 0; + const asyncIterable = { + [Symbol.asyncIterator]() { + return { + async next() { + if (error) { + return Promise.reject(error); + } + if (counter >= responses!.length) { + return Promise.resolve({ done: true, value: undefined }); + } + return Promise.resolve({ done: false, value: responses![counter++] }); + }, + }; + }, + }; + return sinon.stub().returns(asyncIterable); } describe('v1.AddressesClient', () => { @@ -113,759 +143,952 @@ describe('v1.AddressesClient', () => { beforeEach(() => { googleAuth = { getClient: sinon.stub().resolves({ - getRequestHeaders: sinon.stub().resolves({Authorization: 'Bearer SOME_TOKEN'}), - }) + getRequestHeaders: sinon + .stub() + .resolves({ Authorization: 'Bearer SOME_TOKEN' }), + }), } as unknown as GoogleAuth; }); afterEach(() => { sinon.restore(); }); - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new addressesModule.v1.AddressesClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'compute.googleapis.com'); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new addressesModule.v1.AddressesClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'compute.googleapis.com'); + }); - it('has universeDomain', () => { - const client = new addressesModule.v1.AddressesClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); + it('has universeDomain', () => { + const client = new addressesModule.v1.AddressesClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - it('throws DeprecationWarning if static servicePath is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const servicePath = addressesModule.v1.AddressesClient.servicePath; - assert.strictEqual(servicePath, 'compute.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = addressesModule.v1.AddressesClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'compute.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new addressesModule.v1.AddressesClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'compute.example.com'); - }); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = addressesModule.v1.AddressesClient.servicePath; + assert.strictEqual(servicePath, 'compute.googleapis.com'); + assert(stub.called); + stub.restore(); + }); - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new addressesModule.v1.AddressesClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'compute.example.com'); - }); + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = addressesModule.v1.AddressesClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'compute.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = new addressesModule.v1.AddressesClient({ + universeDomain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'compute.example.com'); + }); - if (typeof process === 'object' && 'env' in process) { - describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { - it('sets apiEndpoint from environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new addressesModule.v1.AddressesClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'compute.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - - it('value configured in code has priority over environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new addressesModule.v1.AddressesClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'compute.configured.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { new addressesModule.v1.AddressesClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = new addressesModule.v1.AddressesClient({ + universe_domain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'compute.example.com'); + }); - it('has port', () => { - const port = addressesModule.v1.AddressesClient.port; - assert(port); - assert(typeof port === 'number'); + if (typeof process === 'object' && 'env' in process) { + describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { + it('sets apiEndpoint from environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new addressesModule.v1.AddressesClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'compute.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - it('should create a client with no option', () => { - const client = new addressesModule.v1.AddressesClient(); - assert(client); + it('value configured in code has priority over environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new addressesModule.v1.AddressesClient({ + universeDomain: 'configured.example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'compute.configured.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - - it('should create a client with gRPC fallback', () => { - const client = new addressesModule.v1.AddressesClient({ - fallback: true, - }); - assert(client); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new addressesModule.v1.AddressesClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); + }); - it('has initialize method and supports deferred initialization', async () => { - const client = new addressesModule.v1.AddressesClient({ - auth: googleAuth, - projectId: 'bogus', - }); - assert.strictEqual(client.addressesStub, undefined); - await client.initialize(); - assert(client.addressesStub); - }); + it('has port', () => { + const port = addressesModule.v1.AddressesClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('has close method for the initialized client', done => { - const client = new addressesModule.v1.AddressesClient({ - auth: googleAuth, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.addressesStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('should create a client with no option', () => { + const client = new addressesModule.v1.AddressesClient(); + assert(client); + }); - it('has close method for the non-initialized client', done => { - const client = new addressesModule.v1.AddressesClient({ - auth: googleAuth, - projectId: 'bogus', - }); - assert.strictEqual(client.addressesStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('should create a client with gRPC fallback', () => { + const client = new addressesModule.v1.AddressesClient({ + fallback: true, + }); + assert(client); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new addressesModule.v1.AddressesClient({ - auth: googleAuth, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); - }); + it('has initialize method and supports deferred initialization', async () => { + const client = new addressesModule.v1.AddressesClient({ + auth: googleAuth, + projectId: 'bogus', + }); + assert.strictEqual(client.addressesStub, undefined); + await client.initialize(); + assert(client.addressesStub); + }); - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new addressesModule.v1.AddressesClient({ - auth: googleAuth, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId((err?: Error|null, projectId?: string|null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } - }); - }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); + it('has close method for the initialized client', (done) => { + const client = new addressesModule.v1.AddressesClient({ + auth: googleAuth, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.addressesStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); }); - describe('delete', () => { - it('invokes delete without error', async () => { - const client = new addressesModule.v1.AddressesClient({ - auth: googleAuth, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.compute.v1.DeleteAddressRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.compute.v1.DeleteAddressRequest', ['project']); - request.project = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.compute.v1.DeleteAddressRequest', ['region']); - request.region = defaultValue2; - const defaultValue3 = - getTypeDefaultValue('.google.cloud.compute.v1.DeleteAddressRequest', ['address']); - request.address = defaultValue3; - const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }®ion=${defaultValue2 ?? '' }&address=${defaultValue3 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.compute.v1.Operation() - ); - client.innerApiCalls.delete = stubSimpleCall(expectedResponse); - const [response] = await client.delete(request); - assert.deepStrictEqual(response.latestResponse, expectedResponse); - const actualRequest = (client.innerApiCalls.delete as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.delete as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('has close method for the non-initialized client', (done) => { + const client = new addressesModule.v1.AddressesClient({ + auth: googleAuth, + projectId: 'bogus', + }); + assert.strictEqual(client.addressesStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes delete without error using callback', async () => { - const client = new addressesModule.v1.AddressesClient({ - auth: googleAuth, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.compute.v1.DeleteAddressRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.compute.v1.DeleteAddressRequest', ['project']); - request.project = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.compute.v1.DeleteAddressRequest', ['region']); - request.region = defaultValue2; - const defaultValue3 = - getTypeDefaultValue('.google.cloud.compute.v1.DeleteAddressRequest', ['address']); - request.address = defaultValue3; - const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }®ion=${defaultValue2 ?? '' }&address=${defaultValue3 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.compute.v1.Operation() - ); - client.innerApiCalls.delete = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.delete( - request, - (err?: Error|null, result?: protos.google.cloud.compute.v1.IOperation|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.delete as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.delete as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new addressesModule.v1.AddressesClient({ + auth: googleAuth, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + }); - it('invokes delete with error', async () => { - const client = new addressesModule.v1.AddressesClient({ - auth: googleAuth, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.compute.v1.DeleteAddressRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.compute.v1.DeleteAddressRequest', ['project']); - request.project = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.compute.v1.DeleteAddressRequest', ['region']); - request.region = defaultValue2; - const defaultValue3 = - getTypeDefaultValue('.google.cloud.compute.v1.DeleteAddressRequest', ['address']); - request.address = defaultValue3; - const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }®ion=${defaultValue2 ?? '' }&address=${defaultValue3 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.delete = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.delete(request), expectedError); - const actualRequest = (client.innerApiCalls.delete as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.delete as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new addressesModule.v1.AddressesClient({ + auth: googleAuth, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + }); - it('invokes delete with closed client', async () => { - const client = new addressesModule.v1.AddressesClient({ - auth: googleAuth, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.compute.v1.DeleteAddressRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.compute.v1.DeleteAddressRequest', ['project']); - request.project = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.compute.v1.DeleteAddressRequest', ['region']); - request.region = defaultValue2; - const defaultValue3 = - getTypeDefaultValue('.google.cloud.compute.v1.DeleteAddressRequest', ['address']); - request.address = defaultValue3; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.delete(request), expectedError); - }); + describe('delete', () => { + it('invokes delete without error', async () => { + const client = new addressesModule.v1.AddressesClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1.DeleteAddressRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.compute.v1.DeleteAddressRequest', + ['project'], + ); + request.project = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.compute.v1.DeleteAddressRequest', + ['region'], + ); + request.region = defaultValue2; + const defaultValue3 = getTypeDefaultValue( + '.google.cloud.compute.v1.DeleteAddressRequest', + ['address'], + ); + request.address = defaultValue3; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? ''}®ion=${defaultValue2 ?? ''}&address=${defaultValue3 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.compute.v1.Operation(), + ); + client.innerApiCalls.delete = stubSimpleCall(expectedResponse); + const [response] = await client.delete(request); + assert.deepStrictEqual(response.latestResponse, expectedResponse); + const actualRequest = (client.innerApiCalls.delete as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.delete as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('insert', () => { - it('invokes insert without error', async () => { - const client = new addressesModule.v1.AddressesClient({ - auth: googleAuth, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.compute.v1.InsertAddressRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.compute.v1.InsertAddressRequest', ['project']); - request.project = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.compute.v1.InsertAddressRequest', ['region']); - request.region = defaultValue2; - const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }®ion=${defaultValue2 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.compute.v1.Operation() - ); - client.innerApiCalls.insert = stubSimpleCall(expectedResponse); - const [response] = await client.insert(request); - assert.deepStrictEqual(response.latestResponse, expectedResponse); - const actualRequest = (client.innerApiCalls.insert as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.insert as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes delete without error using callback', async () => { + const client = new addressesModule.v1.AddressesClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1.DeleteAddressRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.compute.v1.DeleteAddressRequest', + ['project'], + ); + request.project = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.compute.v1.DeleteAddressRequest', + ['region'], + ); + request.region = defaultValue2; + const defaultValue3 = getTypeDefaultValue( + '.google.cloud.compute.v1.DeleteAddressRequest', + ['address'], + ); + request.address = defaultValue3; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? ''}®ion=${defaultValue2 ?? ''}&address=${defaultValue3 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.compute.v1.Operation(), + ); + client.innerApiCalls.delete = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.delete( + request, + ( + err?: Error | null, + result?: protos.google.cloud.compute.v1.IOperation | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.delete as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.delete as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes insert without error using callback', async () => { - const client = new addressesModule.v1.AddressesClient({ - auth: googleAuth, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.compute.v1.InsertAddressRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.compute.v1.InsertAddressRequest', ['project']); - request.project = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.compute.v1.InsertAddressRequest', ['region']); - request.region = defaultValue2; - const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }®ion=${defaultValue2 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.compute.v1.Operation() - ); - client.innerApiCalls.insert = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.insert( - request, - (err?: Error|null, result?: protos.google.cloud.compute.v1.IOperation|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.insert as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.insert as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes delete with error', async () => { + const client = new addressesModule.v1.AddressesClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1.DeleteAddressRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.compute.v1.DeleteAddressRequest', + ['project'], + ); + request.project = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.compute.v1.DeleteAddressRequest', + ['region'], + ); + request.region = defaultValue2; + const defaultValue3 = getTypeDefaultValue( + '.google.cloud.compute.v1.DeleteAddressRequest', + ['address'], + ); + request.address = defaultValue3; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? ''}®ion=${defaultValue2 ?? ''}&address=${defaultValue3 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.delete = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.delete(request), expectedError); + const actualRequest = (client.innerApiCalls.delete as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.delete as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes insert with error', async () => { - const client = new addressesModule.v1.AddressesClient({ - auth: googleAuth, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.compute.v1.InsertAddressRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.compute.v1.InsertAddressRequest', ['project']); - request.project = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.compute.v1.InsertAddressRequest', ['region']); - request.region = defaultValue2; - const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }®ion=${defaultValue2 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.insert = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.insert(request), expectedError); - const actualRequest = (client.innerApiCalls.insert as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.insert as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes delete with closed client', async () => { + const client = new addressesModule.v1.AddressesClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1.DeleteAddressRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.compute.v1.DeleteAddressRequest', + ['project'], + ); + request.project = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.compute.v1.DeleteAddressRequest', + ['region'], + ); + request.region = defaultValue2; + const defaultValue3 = getTypeDefaultValue( + '.google.cloud.compute.v1.DeleteAddressRequest', + ['address'], + ); + request.address = defaultValue3; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.delete(request), expectedError); + }); + }); - it('invokes insert with closed client', async () => { - const client = new addressesModule.v1.AddressesClient({ - auth: googleAuth, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.compute.v1.InsertAddressRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.compute.v1.InsertAddressRequest', ['project']); - request.project = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.compute.v1.InsertAddressRequest', ['region']); - request.region = defaultValue2; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.insert(request), expectedError); - }); + describe('insert', () => { + it('invokes insert without error', async () => { + const client = new addressesModule.v1.AddressesClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1.InsertAddressRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.compute.v1.InsertAddressRequest', + ['project'], + ); + request.project = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.compute.v1.InsertAddressRequest', + ['region'], + ); + request.region = defaultValue2; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? ''}®ion=${defaultValue2 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.compute.v1.Operation(), + ); + client.innerApiCalls.insert = stubSimpleCall(expectedResponse); + const [response] = await client.insert(request); + assert.deepStrictEqual(response.latestResponse, expectedResponse); + const actualRequest = (client.innerApiCalls.insert as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.insert as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('aggregatedList', () => { - - it('uses async iteration with aggregatedList without error', async () => { - const client = new addressesModule.v1.AddressesClient({ - auth: googleAuth, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.compute.v1.AggregatedListAddressesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.compute.v1.AggregatedListAddressesRequest', ['project']); - request.project = defaultValue1; - const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }`; - const expectedResponse = [ - ['tuple_key_1', generateSampleMessage(new protos.google.cloud.compute.v1.AddressesScopedList())], - ['tuple_key_2', generateSampleMessage(new protos.google.cloud.compute.v1.AddressesScopedList())], - ['tuple_key_3', generateSampleMessage(new protos.google.cloud.compute.v1.AddressesScopedList())], - ]; - client.descriptors.page.aggregatedList.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: Array<[string, protos.google.cloud.compute.v1.IAddressesScopedList]> = []; - const iterable = client.aggregatedListAsync(request); - for await (const resource of iterable) { - responses.push(resource!); + it('invokes insert without error using callback', async () => { + const client = new addressesModule.v1.AddressesClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1.InsertAddressRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.compute.v1.InsertAddressRequest', + ['project'], + ); + request.project = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.compute.v1.InsertAddressRequest', + ['region'], + ); + request.region = defaultValue2; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? ''}®ion=${defaultValue2 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.compute.v1.Operation(), + ); + client.innerApiCalls.insert = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.insert( + request, + ( + err?: Error | null, + result?: protos.google.cloud.compute.v1.IOperation | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.aggregatedList.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.aggregatedList.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); - - it('uses async iteration with aggregatedList with error', async () => { - const client = new addressesModule.v1.AddressesClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.compute.v1.AggregatedListAddressesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.compute.v1.AggregatedListAddressesRequest', ['project']); - request.project = defaultValue1; - const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.aggregatedList.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.aggregatedListAsync(request); - await assert.rejects(async () => { - const responses: Array<[string, protos.google.cloud.compute.v1.IAddressesScopedList]> = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.aggregatedList.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.aggregatedList.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.insert as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.insert as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('list', () => { - it('invokes list without error', async () => { - const client = new addressesModule.v1.AddressesClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.compute.v1.ListAddressesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.compute.v1.ListAddressesRequest', ['project']); - request.project = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.compute.v1.ListAddressesRequest', ['region']); - request.region = defaultValue2; - const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }®ion=${defaultValue2 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.compute.v1.Address()), - generateSampleMessage(new protos.google.cloud.compute.v1.Address()), - generateSampleMessage(new protos.google.cloud.compute.v1.Address()), - ]; - client.innerApiCalls.list = stubSimpleCall(expectedResponse); - const [response] = await client.list(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.list as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.list as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes insert with error', async () => { + const client = new addressesModule.v1.AddressesClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1.InsertAddressRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.compute.v1.InsertAddressRequest', + ['project'], + ); + request.project = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.compute.v1.InsertAddressRequest', + ['region'], + ); + request.region = defaultValue2; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? ''}®ion=${defaultValue2 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.insert = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.insert(request), expectedError); + const actualRequest = (client.innerApiCalls.insert as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.insert as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes list without error using callback', async () => { - const client = new addressesModule.v1.AddressesClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.compute.v1.ListAddressesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.compute.v1.ListAddressesRequest', ['project']); - request.project = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.compute.v1.ListAddressesRequest', ['region']); - request.region = defaultValue2; - const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }®ion=${defaultValue2 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.compute.v1.Address()), - generateSampleMessage(new protos.google.cloud.compute.v1.Address()), - generateSampleMessage(new protos.google.cloud.compute.v1.Address()), - ]; - client.innerApiCalls.list = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.list( - request, - (err?: Error|null, result?: protos.google.cloud.compute.v1.IAddress[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.list as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.list as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes insert with closed client', async () => { + const client = new addressesModule.v1.AddressesClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1.InsertAddressRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.compute.v1.InsertAddressRequest', + ['project'], + ); + request.project = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.compute.v1.InsertAddressRequest', + ['region'], + ); + request.region = defaultValue2; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.insert(request), expectedError); + }); + }); - it('invokes list with error', async () => { - const client = new addressesModule.v1.AddressesClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.compute.v1.ListAddressesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.compute.v1.ListAddressesRequest', ['project']); - request.project = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.compute.v1.ListAddressesRequest', ['region']); - request.region = defaultValue2; - const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }®ion=${defaultValue2 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.list = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.list(request), expectedError); - const actualRequest = (client.innerApiCalls.list as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.list as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + describe('aggregatedList', () => { + it('uses async iteration with aggregatedList without error', async () => { + const client = new addressesModule.v1.AddressesClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1.AggregatedListAddressesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.compute.v1.AggregatedListAddressesRequest', + ['project'], + ); + request.project = defaultValue1; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? ''}`; + const expectedResponse = [ + [ + 'tuple_key_1', + generateSampleMessage( + new protos.google.cloud.compute.v1.AddressesScopedList(), + ), + ], + [ + 'tuple_key_2', + generateSampleMessage( + new protos.google.cloud.compute.v1.AddressesScopedList(), + ), + ], + [ + 'tuple_key_3', + generateSampleMessage( + new protos.google.cloud.compute.v1.AddressesScopedList(), + ), + ], + ]; + client.descriptors.page.aggregatedList.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: Array< + [string, protos.google.cloud.compute.v1.IAddressesScopedList] + > = []; + const iterable = client.aggregatedListAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.aggregatedList.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.aggregatedList.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('invokes listStream without error', async () => { - const client = new addressesModule.v1.AddressesClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.compute.v1.ListAddressesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.compute.v1.ListAddressesRequest', ['project']); - request.project = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.compute.v1.ListAddressesRequest', ['region']); - request.region = defaultValue2; - const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }®ion=${defaultValue2 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.compute.v1.Address()), - generateSampleMessage(new protos.google.cloud.compute.v1.Address()), - generateSampleMessage(new protos.google.cloud.compute.v1.Address()), - ]; - client.descriptors.page.list.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.cloud.compute.v1.Address[] = []; - stream.on('data', (response: protos.google.cloud.compute.v1.Address) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.list.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.list, request)); - assert( - (client.descriptors.page.list.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with aggregatedList with error', async () => { + const client = new addressesModule.v1.AddressesClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1.AggregatedListAddressesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.compute.v1.AggregatedListAddressesRequest', + ['project'], + ); + request.project = defaultValue1; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.aggregatedList.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.aggregatedListAsync(request); + await assert.rejects(async () => { + const responses: Array< + [string, protos.google.cloud.compute.v1.IAddressesScopedList] + > = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.aggregatedList.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.aggregatedList.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + }); - it('invokes listStream with error', async () => { - const client = new addressesModule.v1.AddressesClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.compute.v1.ListAddressesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.compute.v1.ListAddressesRequest', ['project']); - request.project = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.compute.v1.ListAddressesRequest', ['region']); - request.region = defaultValue2; - const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }®ion=${defaultValue2 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.list.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.cloud.compute.v1.Address[] = []; - stream.on('data', (response: protos.google.cloud.compute.v1.Address) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.list.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.list, request)); - assert( - (client.descriptors.page.list.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + describe('list', () => { + it('invokes list without error', async () => { + const client = new addressesModule.v1.AddressesClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1.ListAddressesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.compute.v1.ListAddressesRequest', + ['project'], + ); + request.project = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.compute.v1.ListAddressesRequest', + ['region'], + ); + request.region = defaultValue2; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? ''}®ion=${defaultValue2 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.compute.v1.Address()), + generateSampleMessage(new protos.google.cloud.compute.v1.Address()), + generateSampleMessage(new protos.google.cloud.compute.v1.Address()), + ]; + client.innerApiCalls.list = stubSimpleCall(expectedResponse); + const [response] = await client.list(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.list as SinonStub).getCall(0) + .args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.list as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('uses async iteration with list without error', async () => { - const client = new addressesModule.v1.AddressesClient({ - auth: googleAuth, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.compute.v1.ListAddressesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.compute.v1.ListAddressesRequest', ['project']); - request.project = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.compute.v1.ListAddressesRequest', ['region']); - request.region = defaultValue2; - const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }®ion=${defaultValue2 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.compute.v1.Address()), - generateSampleMessage(new protos.google.cloud.compute.v1.Address()), - generateSampleMessage(new protos.google.cloud.compute.v1.Address()), - ]; - client.descriptors.page.list.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.cloud.compute.v1.IAddress[] = []; - const iterable = client.listAsync(request); - for await (const resource of iterable) { - responses.push(resource!); + it('invokes list without error using callback', async () => { + const client = new addressesModule.v1.AddressesClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1.ListAddressesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.compute.v1.ListAddressesRequest', + ['project'], + ); + request.project = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.compute.v1.ListAddressesRequest', + ['region'], + ); + request.region = defaultValue2; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? ''}®ion=${defaultValue2 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.compute.v1.Address()), + generateSampleMessage(new protos.google.cloud.compute.v1.Address()), + generateSampleMessage(new protos.google.cloud.compute.v1.Address()), + ]; + client.innerApiCalls.list = stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.list( + request, + ( + err?: Error | null, + result?: protos.google.cloud.compute.v1.IAddress[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.list.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.list.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.list as SinonStub).getCall(0) + .args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.list as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes list with error', async () => { + const client = new addressesModule.v1.AddressesClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1.ListAddressesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.compute.v1.ListAddressesRequest', + ['project'], + ); + request.project = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.compute.v1.ListAddressesRequest', + ['region'], + ); + request.region = defaultValue2; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? ''}®ion=${defaultValue2 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.list = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.list(request), expectedError); + const actualRequest = (client.innerApiCalls.list as SinonStub).getCall(0) + .args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.list as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listStream without error', async () => { + const client = new addressesModule.v1.AddressesClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1.ListAddressesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.compute.v1.ListAddressesRequest', + ['project'], + ); + request.project = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.compute.v1.ListAddressesRequest', + ['region'], + ); + request.region = defaultValue2; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? ''}®ion=${defaultValue2 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.compute.v1.Address()), + generateSampleMessage(new protos.google.cloud.compute.v1.Address()), + generateSampleMessage(new protos.google.cloud.compute.v1.Address()), + ]; + client.descriptors.page.list.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.cloud.compute.v1.Address[] = []; + stream.on( + 'data', + (response: protos.google.cloud.compute.v1.Address) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.list.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.list, request), + ); + assert( + (client.descriptors.page.list.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('uses async iteration with list with error', async () => { - const client = new addressesModule.v1.AddressesClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.compute.v1.ListAddressesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.compute.v1.ListAddressesRequest', ['project']); - request.project = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.compute.v1.ListAddressesRequest', ['region']); - request.region = defaultValue2; - const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }®ion=${defaultValue2 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.list.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listAsync(request); - await assert.rejects(async () => { - const responses: protos.google.cloud.compute.v1.IAddress[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.list.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.list.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); + it('invokes listStream with error', async () => { + const client = new addressesModule.v1.AddressesClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1.ListAddressesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.compute.v1.ListAddressesRequest', + ['project'], + ); + request.project = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.compute.v1.ListAddressesRequest', + ['region'], + ); + request.region = defaultValue2; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? ''}®ion=${defaultValue2 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.list.createStream = stubPageStreamingCall( + undefined, + expectedError, + ); + const stream = client.listStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.cloud.compute.v1.Address[] = []; + stream.on( + 'data', + (response: protos.google.cloud.compute.v1.Address) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.list.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.list, request), + ); + assert( + (client.descriptors.page.list.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + + it('uses async iteration with list without error', async () => { + const client = new addressesModule.v1.AddressesClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1.ListAddressesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.compute.v1.ListAddressesRequest', + ['project'], + ); + request.project = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.compute.v1.ListAddressesRequest', + ['region'], + ); + request.region = defaultValue2; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? ''}®ion=${defaultValue2 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.compute.v1.Address()), + generateSampleMessage(new protos.google.cloud.compute.v1.Address()), + generateSampleMessage(new protos.google.cloud.compute.v1.Address()), + ]; + client.descriptors.page.list.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.cloud.compute.v1.IAddress[] = []; + const iterable = client.listAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + (client.descriptors.page.list.asyncIterate as SinonStub).getCall(0) + .args[1], + request, + ); + assert( + (client.descriptors.page.list.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); }); + + it('uses async iteration with list with error', async () => { + const client = new addressesModule.v1.AddressesClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1.ListAddressesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.compute.v1.ListAddressesRequest', + ['project'], + ); + request.project = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.compute.v1.ListAddressesRequest', + ['region'], + ); + request.region = defaultValue2; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? ''}®ion=${defaultValue2 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.list.asyncIterate = stubAsyncIterationCall( + undefined, + expectedError, + ); + const iterable = client.listAsync(request); + await assert.rejects(async () => { + const responses: protos.google.cloud.compute.v1.IAddress[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + (client.descriptors.page.list.asyncIterate as SinonStub).getCall(0) + .args[1], + request, + ); + assert( + (client.descriptors.page.list.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + }); }); diff --git a/core/generator/gapic-generator-typescript/baselines/compute-esm/esm/test/gapic_region_operations_v1.ts.baseline b/core/generator/gapic-generator-typescript/baselines/compute-esm/esm/test/gapic_region_operations_v1.ts.baseline index 71f489ff7e31..ef19a68d6ecc 100644 --- a/core/generator/gapic-generator-typescript/baselines/compute-esm/esm/test/gapic_region_operations_v1.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/compute-esm/esm/test/gapic_region_operations_v1.ts.baseline @@ -20,14 +20,14 @@ import * as protos from '../../protos/protos.js'; import assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it, beforeEach, afterEach} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it, beforeEach, afterEach } from 'mocha'; import * as regionoperationsModule from '../src/index.js'; -import {GoogleAuth, protobuf} from 'google-gax'; +import { GoogleAuth, protobuf } from 'google-gax'; import fs from 'fs'; import path from 'path'; -import {fileURLToPath} from 'url'; +import { fileURLToPath } from 'url'; // @ts-ignore const dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -35,30 +35,44 @@ const dirname = path.dirname(fileURLToPath(import.meta.url)); // to fill in default values for request objects const root = protobuf.Root.fromJSON( JSON.parse( - fs.readFileSync(path.join(dirname, '..', '..', 'protos/protos.json'), 'utf8') - )) + fs.readFileSync( + path.join(dirname, '..', '..', 'protos/protos.json'), + 'utf8', + ), + ), +); // eslint-disable-next-line @typescript-eslint/no-unused-vars function getTypeDefaultValue(typeName: string, fields: string[]) { - let type = root.lookupType(typeName) as protobuf.Type; - for (const field of fields.slice(0, -1)) { - type = type?.fields[field]?.resolvedType as protobuf.Type; - } - return type?.fields[fields[fields.length - 1]]?.defaultValue ?? null; + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type?.fields[field]?.resolvedType as protobuf.Type; + } + return type?.fields[fields[fields.length - 1]]?.defaultValue ?? null; } function generateSampleMessage(instance: T) { - const filledObject = (instance.constructor as typeof protobuf.Message) - .toObject(instance as protobuf.Message, {defaults: true}); - return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, { defaults: true }); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; } function stubSimpleCall(response?: ResponseType, error?: Error) { - return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); } -function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { - return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +function stubSimpleCallWithCallback( + response?: ResponseType, + error?: Error, +) { + return error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); } describe('v1.RegionOperationsClient', () => { @@ -66,433 +80,531 @@ describe('v1.RegionOperationsClient', () => { beforeEach(() => { googleAuth = { getClient: sinon.stub().resolves({ - getRequestHeaders: sinon.stub().resolves({Authorization: 'Bearer SOME_TOKEN'}), - }) + getRequestHeaders: sinon + .stub() + .resolves({ Authorization: 'Bearer SOME_TOKEN' }), + }), } as unknown as GoogleAuth; }); afterEach(() => { sinon.restore(); }); - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new regionoperationsModule.v1.RegionOperationsClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'compute.googleapis.com'); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new regionoperationsModule.v1.RegionOperationsClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'compute.googleapis.com'); + }); - it('has universeDomain', () => { - const client = new regionoperationsModule.v1.RegionOperationsClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); + it('has universeDomain', () => { + const client = new regionoperationsModule.v1.RegionOperationsClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - it('throws DeprecationWarning if static servicePath is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const servicePath = regionoperationsModule.v1.RegionOperationsClient.servicePath; - assert.strictEqual(servicePath, 'compute.googleapis.com'); - assert(stub.called); - stub.restore(); - }); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = + regionoperationsModule.v1.RegionOperationsClient.servicePath; + assert.strictEqual(servicePath, 'compute.googleapis.com'); + assert(stub.called); + stub.restore(); + }); - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = regionoperationsModule.v1.RegionOperationsClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'compute.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new regionoperationsModule.v1.RegionOperationsClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'compute.example.com'); - }); - - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new regionoperationsModule.v1.RegionOperationsClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'compute.example.com'); - }); + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + regionoperationsModule.v1.RegionOperationsClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'compute.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = new regionoperationsModule.v1.RegionOperationsClient({ + universeDomain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'compute.example.com'); + }); - if (typeof process === 'object' && 'env' in process) { - describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { - it('sets apiEndpoint from environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new regionoperationsModule.v1.RegionOperationsClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'compute.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = new regionoperationsModule.v1.RegionOperationsClient({ + universe_domain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'compute.example.com'); + }); - it('value configured in code has priority over environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new regionoperationsModule.v1.RegionOperationsClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'compute.configured.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { new regionoperationsModule.v1.RegionOperationsClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); + if (typeof process === 'object' && 'env' in process) { + describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { + it('sets apiEndpoint from environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new regionoperationsModule.v1.RegionOperationsClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'compute.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - it('has port', () => { - const port = regionoperationsModule.v1.RegionOperationsClient.port; - assert(port); - assert(typeof port === 'number'); + it('value configured in code has priority over environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new regionoperationsModule.v1.RegionOperationsClient({ + universeDomain: 'configured.example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'compute.configured.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - - it('should create a client with no option', () => { - const client = new regionoperationsModule.v1.RegionOperationsClient(); - assert(client); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new regionoperationsModule.v1.RegionOperationsClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); + }); - it('should create a client with gRPC fallback', () => { - const client = new regionoperationsModule.v1.RegionOperationsClient({ - fallback: true, - }); - assert(client); - }); + it('has port', () => { + const port = regionoperationsModule.v1.RegionOperationsClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('has initialize method and supports deferred initialization', async () => { - const client = new regionoperationsModule.v1.RegionOperationsClient({ - auth: googleAuth, - projectId: 'bogus', - }); - assert.strictEqual(client.regionOperationsStub, undefined); - await client.initialize(); - assert(client.regionOperationsStub); - }); + it('should create a client with no option', () => { + const client = new regionoperationsModule.v1.RegionOperationsClient(); + assert(client); + }); - it('has close method for the initialized client', done => { - const client = new regionoperationsModule.v1.RegionOperationsClient({ - auth: googleAuth, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.regionOperationsStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('should create a client with gRPC fallback', () => { + const client = new regionoperationsModule.v1.RegionOperationsClient({ + fallback: true, + }); + assert(client); + }); - it('has close method for the non-initialized client', done => { - const client = new regionoperationsModule.v1.RegionOperationsClient({ - auth: googleAuth, - projectId: 'bogus', - }); - assert.strictEqual(client.regionOperationsStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('has initialize method and supports deferred initialization', async () => { + const client = new regionoperationsModule.v1.RegionOperationsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + assert.strictEqual(client.regionOperationsStub, undefined); + await client.initialize(); + assert(client.regionOperationsStub); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new regionoperationsModule.v1.RegionOperationsClient({ - auth: googleAuth, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + it('has close method for the initialized client', (done) => { + const client = new regionoperationsModule.v1.RegionOperationsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.regionOperationsStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new regionoperationsModule.v1.RegionOperationsClient({ - auth: googleAuth, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId((err?: Error|null, projectId?: string|null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } - }); - }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); + it('has close method for the non-initialized client', (done) => { + const client = new regionoperationsModule.v1.RegionOperationsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + assert.strictEqual(client.regionOperationsStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); }); - describe('get', () => { - it('invokes get without error', async () => { - const client = new regionoperationsModule.v1.RegionOperationsClient({ - auth: googleAuth, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.compute.v1.GetRegionOperationRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.compute.v1.GetRegionOperationRequest', ['project']); - request.project = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.compute.v1.GetRegionOperationRequest', ['region']); - request.region = defaultValue2; - const defaultValue3 = - getTypeDefaultValue('.google.cloud.compute.v1.GetRegionOperationRequest', ['operation']); - request.operation = defaultValue3; - const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }®ion=${defaultValue2 ?? '' }&operation=${defaultValue3 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.compute.v1.Operation() - ); - client.innerApiCalls.get = stubSimpleCall(expectedResponse); - const [response] = await client.get(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.get as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.get as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new regionoperationsModule.v1.RegionOperationsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + }); - it('invokes get without error using callback', async () => { - const client = new regionoperationsModule.v1.RegionOperationsClient({ - auth: googleAuth, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.compute.v1.GetRegionOperationRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.compute.v1.GetRegionOperationRequest', ['project']); - request.project = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.compute.v1.GetRegionOperationRequest', ['region']); - request.region = defaultValue2; - const defaultValue3 = - getTypeDefaultValue('.google.cloud.compute.v1.GetRegionOperationRequest', ['operation']); - request.operation = defaultValue3; - const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }®ion=${defaultValue2 ?? '' }&operation=${defaultValue3 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.compute.v1.Operation() - ); - client.innerApiCalls.get = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.get( - request, - (err?: Error|null, result?: protos.google.cloud.compute.v1.IOperation|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.get as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.get as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new regionoperationsModule.v1.RegionOperationsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + }); - it('invokes get with error', async () => { - const client = new regionoperationsModule.v1.RegionOperationsClient({ - auth: googleAuth, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.compute.v1.GetRegionOperationRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.compute.v1.GetRegionOperationRequest', ['project']); - request.project = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.compute.v1.GetRegionOperationRequest', ['region']); - request.region = defaultValue2; - const defaultValue3 = - getTypeDefaultValue('.google.cloud.compute.v1.GetRegionOperationRequest', ['operation']); - request.operation = defaultValue3; - const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }®ion=${defaultValue2 ?? '' }&operation=${defaultValue3 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.get = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.get(request), expectedError); - const actualRequest = (client.innerApiCalls.get as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.get as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + describe('get', () => { + it('invokes get without error', async () => { + const client = new regionoperationsModule.v1.RegionOperationsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1.GetRegionOperationRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.compute.v1.GetRegionOperationRequest', + ['project'], + ); + request.project = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.compute.v1.GetRegionOperationRequest', + ['region'], + ); + request.region = defaultValue2; + const defaultValue3 = getTypeDefaultValue( + '.google.cloud.compute.v1.GetRegionOperationRequest', + ['operation'], + ); + request.operation = defaultValue3; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? ''}®ion=${defaultValue2 ?? ''}&operation=${defaultValue3 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.compute.v1.Operation(), + ); + client.innerApiCalls.get = stubSimpleCall(expectedResponse); + const [response] = await client.get(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.get as SinonStub).getCall(0) + .args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.get as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes get with closed client', async () => { - const client = new regionoperationsModule.v1.RegionOperationsClient({ - auth: googleAuth, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.compute.v1.GetRegionOperationRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.compute.v1.GetRegionOperationRequest', ['project']); - request.project = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.compute.v1.GetRegionOperationRequest', ['region']); - request.region = defaultValue2; - const defaultValue3 = - getTypeDefaultValue('.google.cloud.compute.v1.GetRegionOperationRequest', ['operation']); - request.operation = defaultValue3; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.get(request), expectedError); - }); + it('invokes get without error using callback', async () => { + const client = new regionoperationsModule.v1.RegionOperationsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1.GetRegionOperationRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.compute.v1.GetRegionOperationRequest', + ['project'], + ); + request.project = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.compute.v1.GetRegionOperationRequest', + ['region'], + ); + request.region = defaultValue2; + const defaultValue3 = getTypeDefaultValue( + '.google.cloud.compute.v1.GetRegionOperationRequest', + ['operation'], + ); + request.operation = defaultValue3; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? ''}®ion=${defaultValue2 ?? ''}&operation=${defaultValue3 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.compute.v1.Operation(), + ); + client.innerApiCalls.get = stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.get( + request, + ( + err?: Error | null, + result?: protos.google.cloud.compute.v1.IOperation | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.get as SinonStub).getCall(0) + .args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.get as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('wait', () => { - it('invokes wait without error', async () => { - const client = new regionoperationsModule.v1.RegionOperationsClient({ - auth: googleAuth, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.compute.v1.WaitRegionOperationRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.compute.v1.WaitRegionOperationRequest', ['project']); - request.project = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.compute.v1.WaitRegionOperationRequest', ['region']); - request.region = defaultValue2; - const defaultValue3 = - getTypeDefaultValue('.google.cloud.compute.v1.WaitRegionOperationRequest', ['operation']); - request.operation = defaultValue3; - const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }®ion=${defaultValue2 ?? '' }&operation=${defaultValue3 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.compute.v1.Operation() - ); - client.innerApiCalls.wait = stubSimpleCall(expectedResponse); - const [response] = await client.wait(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.wait as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.wait as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes get with error', async () => { + const client = new regionoperationsModule.v1.RegionOperationsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1.GetRegionOperationRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.compute.v1.GetRegionOperationRequest', + ['project'], + ); + request.project = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.compute.v1.GetRegionOperationRequest', + ['region'], + ); + request.region = defaultValue2; + const defaultValue3 = getTypeDefaultValue( + '.google.cloud.compute.v1.GetRegionOperationRequest', + ['operation'], + ); + request.operation = defaultValue3; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? ''}®ion=${defaultValue2 ?? ''}&operation=${defaultValue3 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.get = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.get(request), expectedError); + const actualRequest = (client.innerApiCalls.get as SinonStub).getCall(0) + .args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.get as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes wait without error using callback', async () => { - const client = new regionoperationsModule.v1.RegionOperationsClient({ - auth: googleAuth, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.compute.v1.WaitRegionOperationRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.compute.v1.WaitRegionOperationRequest', ['project']); - request.project = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.compute.v1.WaitRegionOperationRequest', ['region']); - request.region = defaultValue2; - const defaultValue3 = - getTypeDefaultValue('.google.cloud.compute.v1.WaitRegionOperationRequest', ['operation']); - request.operation = defaultValue3; - const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }®ion=${defaultValue2 ?? '' }&operation=${defaultValue3 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.compute.v1.Operation() - ); - client.innerApiCalls.wait = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.wait( - request, - (err?: Error|null, result?: protos.google.cloud.compute.v1.IOperation|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.wait as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.wait as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes get with closed client', async () => { + const client = new regionoperationsModule.v1.RegionOperationsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1.GetRegionOperationRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.compute.v1.GetRegionOperationRequest', + ['project'], + ); + request.project = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.compute.v1.GetRegionOperationRequest', + ['region'], + ); + request.region = defaultValue2; + const defaultValue3 = getTypeDefaultValue( + '.google.cloud.compute.v1.GetRegionOperationRequest', + ['operation'], + ); + request.operation = defaultValue3; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.get(request), expectedError); + }); + }); - it('invokes wait with error', async () => { - const client = new regionoperationsModule.v1.RegionOperationsClient({ - auth: googleAuth, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.compute.v1.WaitRegionOperationRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.compute.v1.WaitRegionOperationRequest', ['project']); - request.project = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.compute.v1.WaitRegionOperationRequest', ['region']); - request.region = defaultValue2; - const defaultValue3 = - getTypeDefaultValue('.google.cloud.compute.v1.WaitRegionOperationRequest', ['operation']); - request.operation = defaultValue3; - const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }®ion=${defaultValue2 ?? '' }&operation=${defaultValue3 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.wait = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.wait(request), expectedError); - const actualRequest = (client.innerApiCalls.wait as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.wait as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + describe('wait', () => { + it('invokes wait without error', async () => { + const client = new regionoperationsModule.v1.RegionOperationsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1.WaitRegionOperationRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.compute.v1.WaitRegionOperationRequest', + ['project'], + ); + request.project = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.compute.v1.WaitRegionOperationRequest', + ['region'], + ); + request.region = defaultValue2; + const defaultValue3 = getTypeDefaultValue( + '.google.cloud.compute.v1.WaitRegionOperationRequest', + ['operation'], + ); + request.operation = defaultValue3; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? ''}®ion=${defaultValue2 ?? ''}&operation=${defaultValue3 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.compute.v1.Operation(), + ); + client.innerApiCalls.wait = stubSimpleCall(expectedResponse); + const [response] = await client.wait(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.wait as SinonStub).getCall(0) + .args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.wait as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes wait with closed client', async () => { - const client = new regionoperationsModule.v1.RegionOperationsClient({ - auth: googleAuth, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.compute.v1.WaitRegionOperationRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.compute.v1.WaitRegionOperationRequest', ['project']); - request.project = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.compute.v1.WaitRegionOperationRequest', ['region']); - request.region = defaultValue2; - const defaultValue3 = - getTypeDefaultValue('.google.cloud.compute.v1.WaitRegionOperationRequest', ['operation']); - request.operation = defaultValue3; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.wait(request), expectedError); - }); + it('invokes wait without error using callback', async () => { + const client = new regionoperationsModule.v1.RegionOperationsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1.WaitRegionOperationRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.compute.v1.WaitRegionOperationRequest', + ['project'], + ); + request.project = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.compute.v1.WaitRegionOperationRequest', + ['region'], + ); + request.region = defaultValue2; + const defaultValue3 = getTypeDefaultValue( + '.google.cloud.compute.v1.WaitRegionOperationRequest', + ['operation'], + ); + request.operation = defaultValue3; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? ''}®ion=${defaultValue2 ?? ''}&operation=${defaultValue3 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.compute.v1.Operation(), + ); + client.innerApiCalls.wait = stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.wait( + request, + ( + err?: Error | null, + result?: protos.google.cloud.compute.v1.IOperation | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.wait as SinonStub).getCall(0) + .args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.wait as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); + + it('invokes wait with error', async () => { + const client = new regionoperationsModule.v1.RegionOperationsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1.WaitRegionOperationRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.compute.v1.WaitRegionOperationRequest', + ['project'], + ); + request.project = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.compute.v1.WaitRegionOperationRequest', + ['region'], + ); + request.region = defaultValue2; + const defaultValue3 = getTypeDefaultValue( + '.google.cloud.compute.v1.WaitRegionOperationRequest', + ['operation'], + ); + request.operation = defaultValue3; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? ''}®ion=${defaultValue2 ?? ''}&operation=${defaultValue3 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.wait = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.wait(request), expectedError); + const actualRequest = (client.innerApiCalls.wait as SinonStub).getCall(0) + .args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.wait as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes wait with closed client', async () => { + const client = new regionoperationsModule.v1.RegionOperationsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1.WaitRegionOperationRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.compute.v1.WaitRegionOperationRequest', + ['project'], + ); + request.project = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.compute.v1.WaitRegionOperationRequest', + ['region'], + ); + request.region = defaultValue2; + const defaultValue3 = getTypeDefaultValue( + '.google.cloud.compute.v1.WaitRegionOperationRequest', + ['operation'], + ); + request.operation = defaultValue3; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.wait(request), expectedError); + }); + }); }); diff --git a/core/generator/gapic-generator-typescript/baselines/compute/src/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/compute/src/index.ts.baseline index 9a838f04175a..f88e0a386c9e 100644 --- a/core/generator/gapic-generator-typescript/baselines/compute/src/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/compute/src/index.ts.baseline @@ -21,7 +21,7 @@ const AddressesClient = v1.AddressesClient; type AddressesClient = v1.AddressesClient; const RegionOperationsClient = v1.RegionOperationsClient; type RegionOperationsClient = v1.RegionOperationsClient; -export {v1, AddressesClient, RegionOperationsClient}; -export default {v1, AddressesClient, RegionOperationsClient}; +export { v1, AddressesClient, RegionOperationsClient }; +export default { v1, AddressesClient, RegionOperationsClient }; import * as protos from '../protos/protos'; -export {protos} +export { protos }; diff --git a/core/generator/gapic-generator-typescript/baselines/compute/src/v1/addresses_client.ts.baseline b/core/generator/gapic-generator-typescript/baselines/compute/src/v1/addresses_client.ts.baseline index 9b25f024cd75..5713f0c33d4f 100644 --- a/core/generator/gapic-generator-typescript/baselines/compute/src/v1/addresses_client.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/compute/src/v1/addresses_client.ts.baseline @@ -18,11 +18,19 @@ /* global window */ import type * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions, LROperation, PaginationCallback, GaxCall} from 'google-gax'; -import {Transform} from 'stream'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + LROperation, + PaginationCallback, + GaxCall, +} from 'google-gax'; +import { Transform } from 'stream'; import * as protos from '../../protos/protos'; import jsonProtos = require('../../protos/protos.json'); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; /** * Client JSON configuration object, loaded from @@ -47,7 +55,7 @@ export class AddressesClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('compute'); @@ -60,8 +68,8 @@ export class AddressesClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - addressesStub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + addressesStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of AddressesClient. @@ -102,27 +110,48 @@ export class AddressesClient { * const client = new AddressesClient({fallback: true}, gax); * ``` */ - constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { // Ensure that options include all the required fields. const staticMembers = this.constructor as typeof AddressesClient; - if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { - throw new Error('Please set either universe_domain or universeDomain, but not both.'); + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); } - const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; - this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; this._servicePath = 'compute.' + this._universeDomain; - const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; // Implicitly enable HTTP transport for the APIs that use REST as transport (e.g. Google Cloud Compute). if (!opts) { - opts = {fallback: true}; + opts = { fallback: true }; } else { opts.fallback = opts.fallback ?? true; } - const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. if (servicePath !== this._servicePath && !('scopes' in opts)) { @@ -144,7 +173,7 @@ export class AddressesClient { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set defaultServicePath on the auth object. this.auth.defaultServicePath = this._servicePath; @@ -155,10 +184,7 @@ export class AddressesClient { } // Determine the client header string. - const clientHeader = [ - `gax/${this._gaxModule.version}`, - `gapic/${version}`, - ]; + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/${process.versions.node}`); } else { @@ -179,16 +205,25 @@ export class AddressesClient { // (e.g. 50 results at a time, with tokens to get subsequent // pages). Denote the keys used for pagination and results. this.descriptors.page = { - aggregatedList: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'items'), - list: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'items') + aggregatedList: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'items', + ), + list: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'items', + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.cloud.compute.v1.Addresses', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.cloud.compute.v1.Addresses', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + { 'x-goog-api-client': clientHeader.join(' ') }, + ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -219,37 +254,40 @@ export class AddressesClient { // Put together the "service stub" for // google.cloud.compute.v1.Addresses. this.addressesStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.cloud.compute.v1.Addresses') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.cloud.compute.v1.Addresses', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.cloud.compute.v1.Addresses, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts, + this._providedCustomServicePath, + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const addressesStubMethods = - ['aggregatedList', 'delete', 'insert', 'list']; + const addressesStubMethods = ['aggregatedList', 'delete', 'insert', 'list']; for (const methodName of addressesStubMethods) { const callPromise = this.addressesStub.then( - stub => (...args: Array<{}>) => { - if (this._terminated) { - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error|null|undefined) => () => { + (stub) => + (...args: Array<{}>) => { + if (this._terminated) { + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { throw err; - }); + }, + ); - const descriptor = - this.descriptors.page[methodName] || - undefined; + const descriptor = this.descriptors.page[methodName] || undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -264,8 +302,14 @@ export class AddressesClient { * @returns {string} The DNS address for this service. */ static get servicePath() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'compute.googleapis.com'; } @@ -276,8 +320,14 @@ export class AddressesClient { * @returns {string} The DNS address for this service. */ static get apiEndpoint() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'compute.googleapis.com'; } @@ -310,7 +360,7 @@ export class AddressesClient { static get scopes() { return [ 'https://www.googleapis.com/auth/compute', - 'https://www.googleapis.com/auth/cloud-platform' + 'https://www.googleapis.com/auth/cloud-platform', ]; } @@ -320,8 +370,9 @@ export class AddressesClient { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId(callback?: Callback): - Promise|void { + getProjectId( + callback?: Callback, + ): Promise | void { if (callback) { this.auth.getProjectId(callback); return; @@ -332,388 +383,495 @@ export class AddressesClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Deletes the specified address resource. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.address - * Name of the address resource to delete. - * @param {string} request.project - * Project ID for this request. - * @param {string} request.region - * Name of the region for this request. - * @param {string} request.requestId - * An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. - * - * For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. - * - * The request ID must be a valid UUID with the exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000). - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing - * a long running operation. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * This method is considered to be in beta. This means while - * stable it is still a work-in-progress and under active development, - * and might get backwards-incompatible changes at any time. - * `.promise()` is not supported yet. - * @example include:samples/generated/v1/addresses.delete.js - * region_tag:compute_v1_generated_Addresses_Delete_async - */ + /** + * Deletes the specified address resource. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.address + * Name of the address resource to delete. + * @param {string} request.project + * Project ID for this request. + * @param {string} request.region + * Name of the region for this request. + * @param {string} request.requestId + * An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. + * + * For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. + * + * The request ID must be a valid UUID with the exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000). + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * This method is considered to be in beta. This means while + * stable it is still a work-in-progress and under active development, + * and might get backwards-incompatible changes at any time. + * `.promise()` is not supported yet. + * @example include:samples/generated/v1/addresses.delete.js + * region_tag:compute_v1_generated_Addresses_Delete_async + */ delete( - request?: protos.google.cloud.compute.v1.IDeleteAddressRequest, - options?: CallOptions): - Promise<[ - LROperation, - protos.google.cloud.compute.v1.IOperation|undefined, {}|undefined - ]>; + request?: protos.google.cloud.compute.v1.IDeleteAddressRequest, + options?: CallOptions, + ): Promise< + [ + LROperation, + protos.google.cloud.compute.v1.IOperation | undefined, + {} | undefined, + ] + >; delete( - request: protos.google.cloud.compute.v1.IDeleteAddressRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.compute.v1.IOperation, - protos.google.cloud.compute.v1.IDeleteAddressRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.compute.v1.IDeleteAddressRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.compute.v1.IOperation, + protos.google.cloud.compute.v1.IDeleteAddressRequest | null | undefined, + {} | null | undefined + >, + ): void; delete( - request: protos.google.cloud.compute.v1.IDeleteAddressRequest, - callback: Callback< - protos.google.cloud.compute.v1.IOperation, - protos.google.cloud.compute.v1.IDeleteAddressRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.compute.v1.IDeleteAddressRequest, + callback: Callback< + protos.google.cloud.compute.v1.IOperation, + protos.google.cloud.compute.v1.IDeleteAddressRequest | null | undefined, + {} | null | undefined + >, + ): void; delete( - request?: protos.google.cloud.compute.v1.IDeleteAddressRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.compute.v1.IOperation, - protos.google.cloud.compute.v1.IDeleteAddressRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.compute.v1.IDeleteAddressRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.compute.v1.IOperation, - protos.google.cloud.compute.v1.IDeleteAddressRequest|null|undefined, - {}|null|undefined>): - Promise<[ - LROperation, - protos.google.cloud.compute.v1.IOperation|undefined, {}|undefined - ]>|void { + | protos.google.cloud.compute.v1.IDeleteAddressRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.compute.v1.IOperation, + protos.google.cloud.compute.v1.IDeleteAddressRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + LROperation, + protos.google.cloud.compute.v1.IOperation | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'project': request.project ?? '', - 'region': request.region ?? '', - 'address': request.address ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + project: request.project ?? '', + region: request.region ?? '', + address: request.address ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('delete request %j', request); - const wrappedCallback: Callback< + const wrappedCallback: + | Callback< protos.google.cloud.compute.v1.IOperation, - protos.google.cloud.compute.v1.IDeleteAddressRequest|null|undefined, - {}|null|undefined>|undefined = callback + | protos.google.cloud.compute.v1.IDeleteAddressRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, nextRequest, rawResponse) => { this._log.info('delete response %j', rawResponse); callback!(error, response, nextRequest, rawResponse); // We verified `callback` above. } : undefined; - return this.innerApiCalls.delete(request, options, wrappedCallback) - ?.then(([response, operation, rawResponse]: [protos.google.cloud.compute.v1.IOperation, protos.google.cloud.compute.v1.IOperation, protos.google.cloud.compute.v1.IOperation]) => { - return [ - { latestResponse: response, done: false, name: response.id, metadata: null, result: {}}, - operation, - rawResponse - ]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .delete(request, options, wrappedCallback) + ?.then( + ([response, operation, rawResponse]: [ + protos.google.cloud.compute.v1.IOperation, + protos.google.cloud.compute.v1.IOperation, + protos.google.cloud.compute.v1.IOperation, + ]) => { + return [ + { + latestResponse: response, + done: false, + name: response.id, + metadata: null, + result: {}, + }, + operation, + rawResponse, + ]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Creates an address resource in the specified project by using the data included in the request. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.cloud.compute.v1.Address} request.addressResource - * The body resource for this request - * @param {string} request.project - * Project ID for this request. - * @param {string} request.region - * Name of the region for this request. - * @param {string} request.requestId - * An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. - * - * For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. - * - * The request ID must be a valid UUID with the exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000). - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing - * a long running operation. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * This method is considered to be in beta. This means while - * stable it is still a work-in-progress and under active development, - * and might get backwards-incompatible changes at any time. - * `.promise()` is not supported yet. - * @example include:samples/generated/v1/addresses.insert.js - * region_tag:compute_v1_generated_Addresses_Insert_async - */ + /** + * Creates an address resource in the specified project by using the data included in the request. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.cloud.compute.v1.Address} request.addressResource + * The body resource for this request + * @param {string} request.project + * Project ID for this request. + * @param {string} request.region + * Name of the region for this request. + * @param {string} request.requestId + * An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. + * + * For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. + * + * The request ID must be a valid UUID with the exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000). + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * This method is considered to be in beta. This means while + * stable it is still a work-in-progress and under active development, + * and might get backwards-incompatible changes at any time. + * `.promise()` is not supported yet. + * @example include:samples/generated/v1/addresses.insert.js + * region_tag:compute_v1_generated_Addresses_Insert_async + */ insert( - request?: protos.google.cloud.compute.v1.IInsertAddressRequest, - options?: CallOptions): - Promise<[ - LROperation, - protos.google.cloud.compute.v1.IOperation|undefined, {}|undefined - ]>; + request?: protos.google.cloud.compute.v1.IInsertAddressRequest, + options?: CallOptions, + ): Promise< + [ + LROperation, + protos.google.cloud.compute.v1.IOperation | undefined, + {} | undefined, + ] + >; insert( - request: protos.google.cloud.compute.v1.IInsertAddressRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.compute.v1.IOperation, - protos.google.cloud.compute.v1.IInsertAddressRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.compute.v1.IInsertAddressRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.compute.v1.IOperation, + protos.google.cloud.compute.v1.IInsertAddressRequest | null | undefined, + {} | null | undefined + >, + ): void; insert( - request: protos.google.cloud.compute.v1.IInsertAddressRequest, - callback: Callback< - protos.google.cloud.compute.v1.IOperation, - protos.google.cloud.compute.v1.IInsertAddressRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.compute.v1.IInsertAddressRequest, + callback: Callback< + protos.google.cloud.compute.v1.IOperation, + protos.google.cloud.compute.v1.IInsertAddressRequest | null | undefined, + {} | null | undefined + >, + ): void; insert( - request?: protos.google.cloud.compute.v1.IInsertAddressRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.compute.v1.IOperation, - protos.google.cloud.compute.v1.IInsertAddressRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.compute.v1.IInsertAddressRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.compute.v1.IOperation, - protos.google.cloud.compute.v1.IInsertAddressRequest|null|undefined, - {}|null|undefined>): - Promise<[ - LROperation, - protos.google.cloud.compute.v1.IOperation|undefined, {}|undefined - ]>|void { + | protos.google.cloud.compute.v1.IInsertAddressRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.compute.v1.IOperation, + protos.google.cloud.compute.v1.IInsertAddressRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + LROperation, + protos.google.cloud.compute.v1.IOperation | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'project': request.project ?? '', - 'region': request.region ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + project: request.project ?? '', + region: request.region ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('insert request %j', request); - const wrappedCallback: Callback< + const wrappedCallback: + | Callback< protos.google.cloud.compute.v1.IOperation, - protos.google.cloud.compute.v1.IInsertAddressRequest|null|undefined, - {}|null|undefined>|undefined = callback + | protos.google.cloud.compute.v1.IInsertAddressRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, nextRequest, rawResponse) => { this._log.info('insert response %j', rawResponse); callback!(error, response, nextRequest, rawResponse); // We verified `callback` above. } : undefined; - return this.innerApiCalls.insert(request, options, wrappedCallback) - ?.then(([response, operation, rawResponse]: [protos.google.cloud.compute.v1.IOperation, protos.google.cloud.compute.v1.IOperation, protos.google.cloud.compute.v1.IOperation]) => { - return [ - { latestResponse: response, done: false, name: response.id, metadata: null, result: {}}, - operation, - rawResponse - ]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .insert(request, options, wrappedCallback) + ?.then( + ([response, operation, rawResponse]: [ + protos.google.cloud.compute.v1.IOperation, + protos.google.cloud.compute.v1.IOperation, + protos.google.cloud.compute.v1.IOperation, + ]) => { + return [ + { + latestResponse: response, + done: false, + name: response.id, + metadata: null, + result: {}, + }, + operation, + rawResponse, + ]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } - -/** - * Retrieves an aggregated list of addresses. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.filter - * A filter expression that filters resources listed in the response. The expression must specify the field name, a comparison operator, and the value that you want to use for filtering. The value must be a string, a number, or a boolean. The comparison operator must be either `=`, `!=`, `>`, or `<`. - * - * For example, if you are filtering Compute Engine instances, you can exclude instances named `example-instance` by specifying `name != example-instance`. - * - * You can also filter nested fields. For example, you could specify `scheduling.automaticRestart = false` to include instances only if they are not scheduled for automatic restarts. You can use filtering on nested fields to filter based on resource labels. - * - * To filter on multiple expressions, provide each separate expression within parentheses. For example: ``` (scheduling.automaticRestart = true) (cpuPlatform = "Intel Skylake") ``` By default, each expression is an `AND` expression. However, you can include `AND` and `OR` expressions explicitly. For example: ``` (cpuPlatform = "Intel Skylake") OR (cpuPlatform = "Intel Broadwell") AND (scheduling.automaticRestart = true) ``` - * @param {boolean} request.includeAllScopes - * Indicates whether every visible scope for each scope type (zone, region, global) should be included in the response. For new resource types added after this field, the flag has no effect as new resource types will always include every visible scope for each scope type in response. For resource types which predate this field, if this flag is omitted or false, only scopes of the scope types where the resource type is expected to be found will be included. - * @param {number} request.maxResults - * The maximum number of results per page that should be returned. If the number of available results is larger than `maxResults`, Compute Engine returns a `nextPageToken` that can be used to get the next page of results in subsequent list requests. Acceptable values are `0` to `500`, inclusive. (Default: `500`) - * @param {string} request.orderBy - * Sorts list results by a certain order. By default, results are returned in alphanumerical order based on the resource name. - * - * You can also sort results in descending order based on the creation timestamp using `orderBy="creationTimestamp desc"`. This sorts results based on the `creationTimestamp` field in reverse chronological order (newest result first). Use this to sort resources like operations so that the newest operation is returned first. - * - * Currently, only sorting by `name` or `creationTimestamp desc` is supported. - * @param {string} request.pageToken - * Specifies a page token to use. Set `pageToken` to the `nextPageToken` returned by a previous list request to get the next page of results. - * @param {string} request.project - * Project ID for this request. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * as tuple [string, {@link protos.google.cloud.compute.v1.AddressesScopedList|AddressesScopedList}]. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v1/addresses.aggregated_list.js - * region_tag:compute_v1_generated_Addresses_AggregatedList_async - */ + /** + * Retrieves an aggregated list of addresses. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.filter + * A filter expression that filters resources listed in the response. The expression must specify the field name, a comparison operator, and the value that you want to use for filtering. The value must be a string, a number, or a boolean. The comparison operator must be either `=`, `!=`, `>`, or `<`. + * + * For example, if you are filtering Compute Engine instances, you can exclude instances named `example-instance` by specifying `name != example-instance`. + * + * You can also filter nested fields. For example, you could specify `scheduling.automaticRestart = false` to include instances only if they are not scheduled for automatic restarts. You can use filtering on nested fields to filter based on resource labels. + * + * To filter on multiple expressions, provide each separate expression within parentheses. For example: ``` (scheduling.automaticRestart = true) (cpuPlatform = "Intel Skylake") ``` By default, each expression is an `AND` expression. However, you can include `AND` and `OR` expressions explicitly. For example: ``` (cpuPlatform = "Intel Skylake") OR (cpuPlatform = "Intel Broadwell") AND (scheduling.automaticRestart = true) ``` + * @param {boolean} request.includeAllScopes + * Indicates whether every visible scope for each scope type (zone, region, global) should be included in the response. For new resource types added after this field, the flag has no effect as new resource types will always include every visible scope for each scope type in response. For resource types which predate this field, if this flag is omitted or false, only scopes of the scope types where the resource type is expected to be found will be included. + * @param {number} request.maxResults + * The maximum number of results per page that should be returned. If the number of available results is larger than `maxResults`, Compute Engine returns a `nextPageToken` that can be used to get the next page of results in subsequent list requests. Acceptable values are `0` to `500`, inclusive. (Default: `500`) + * @param {string} request.orderBy + * Sorts list results by a certain order. By default, results are returned in alphanumerical order based on the resource name. + * + * You can also sort results in descending order based on the creation timestamp using `orderBy="creationTimestamp desc"`. This sorts results based on the `creationTimestamp` field in reverse chronological order (newest result first). Use this to sort resources like operations so that the newest operation is returned first. + * + * Currently, only sorting by `name` or `creationTimestamp desc` is supported. + * @param {string} request.pageToken + * Specifies a page token to use. Set `pageToken` to the `nextPageToken` returned by a previous list request to get the next page of results. + * @param {string} request.project + * Project ID for this request. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * as tuple [string, {@link protos.google.cloud.compute.v1.AddressesScopedList|AddressesScopedList}]. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v1/addresses.aggregated_list.js + * region_tag:compute_v1_generated_Addresses_AggregatedList_async + */ aggregatedListAsync( - request?: protos.google.cloud.compute.v1.IAggregatedListAddressesRequest, - options?: CallOptions): - AsyncIterable<[string, protos.google.cloud.compute.v1.IAddressesScopedList]>{ + request?: protos.google.cloud.compute.v1.IAggregatedListAddressesRequest, + options?: CallOptions, + ): AsyncIterable< + [string, protos.google.cloud.compute.v1.IAddressesScopedList] + > { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'project': request.project ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + project: request.project ?? '', + }); const defaultCallSettings = this._defaults['aggregatedList']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('aggregatedList iterate %j', request); return this.descriptors.page.aggregatedList.asyncIterate( this.innerApiCalls['aggregatedList'] as GaxCall, request as {}, - callSettings - ) as AsyncIterable<[string, protos.google.cloud.compute.v1.IAddressesScopedList]>; + callSettings, + ) as AsyncIterable< + [string, protos.google.cloud.compute.v1.IAddressesScopedList] + >; } - /** - * Retrieves a list of addresses contained within the specified region. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.filter - * A filter expression that filters resources listed in the response. The expression must specify the field name, a comparison operator, and the value that you want to use for filtering. The value must be a string, a number, or a boolean. The comparison operator must be either =, !=, >, or <. - * - * For example, if you are filtering Compute Engine instances, you can exclude instances named example-instance by specifying name != example-instance. - * - * You can also filter nested fields. For example, you could specify scheduling.automaticRestart = false to include instances only if they are not scheduled for automatic restarts. You can use filtering on nested fields to filter based on resource labels. - * - * To filter on multiple expressions, provide each separate expression within parentheses. For example, (scheduling.automaticRestart = true) (cpuPlatform = "Intel Skylake"). By default, each expression is an AND expression. However, you can include AND and OR expressions explicitly. For example, (cpuPlatform = "Intel Skylake") OR (cpuPlatform = "Intel Broadwell") AND (scheduling.automaticRestart = true). - * @param {number} request.maxResults - * The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests. Acceptable values are 0 to 500, inclusive. (Default: 500) - * @param {string} request.orderBy - * Sorts list results by a certain order. By default, results are returned in alphanumerical order based on the resource name. - * - * You can also sort results in descending order based on the creation timestamp using orderBy="creationTimestamp desc". This sorts results based on the creationTimestamp field in reverse chronological order (newest result first). Use this to sort resources like operations so that the newest operation is returned first. - * - * Currently, only sorting by name or creationTimestamp desc is supported. - * @param {string} request.pageToken - * Specifies a page token to use. Set pageToken to the nextPageToken returned by a previous list request to get the next page of results. - * @param {string} request.project - * Project ID for this request. - * @param {string} request.region - * Name of the region for this request. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.cloud.compute.v1.Address|Address}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `listAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Retrieves a list of addresses contained within the specified region. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.filter + * A filter expression that filters resources listed in the response. The expression must specify the field name, a comparison operator, and the value that you want to use for filtering. The value must be a string, a number, or a boolean. The comparison operator must be either =, !=, >, or <. + * + * For example, if you are filtering Compute Engine instances, you can exclude instances named example-instance by specifying name != example-instance. + * + * You can also filter nested fields. For example, you could specify scheduling.automaticRestart = false to include instances only if they are not scheduled for automatic restarts. You can use filtering on nested fields to filter based on resource labels. + * + * To filter on multiple expressions, provide each separate expression within parentheses. For example, (scheduling.automaticRestart = true) (cpuPlatform = "Intel Skylake"). By default, each expression is an AND expression. However, you can include AND and OR expressions explicitly. For example, (cpuPlatform = "Intel Skylake") OR (cpuPlatform = "Intel Broadwell") AND (scheduling.automaticRestart = true). + * @param {number} request.maxResults + * The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests. Acceptable values are 0 to 500, inclusive. (Default: 500) + * @param {string} request.orderBy + * Sorts list results by a certain order. By default, results are returned in alphanumerical order based on the resource name. + * + * You can also sort results in descending order based on the creation timestamp using orderBy="creationTimestamp desc". This sorts results based on the creationTimestamp field in reverse chronological order (newest result first). Use this to sort resources like operations so that the newest operation is returned first. + * + * Currently, only sorting by name or creationTimestamp desc is supported. + * @param {string} request.pageToken + * Specifies a page token to use. Set pageToken to the nextPageToken returned by a previous list request to get the next page of results. + * @param {string} request.project + * Project ID for this request. + * @param {string} request.region + * Name of the region for this request. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.cloud.compute.v1.Address|Address}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ list( - request?: protos.google.cloud.compute.v1.IListAddressesRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.compute.v1.IAddress[], - protos.google.cloud.compute.v1.IListAddressesRequest|null, - protos.google.cloud.compute.v1.IAddressList - ]>; + request?: protos.google.cloud.compute.v1.IListAddressesRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.compute.v1.IAddress[], + protos.google.cloud.compute.v1.IListAddressesRequest | null, + protos.google.cloud.compute.v1.IAddressList, + ] + >; list( - request: protos.google.cloud.compute.v1.IListAddressesRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.cloud.compute.v1.IListAddressesRequest, - protos.google.cloud.compute.v1.IAddressList|null|undefined, - protos.google.cloud.compute.v1.IAddress>): void; + request: protos.google.cloud.compute.v1.IListAddressesRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.cloud.compute.v1.IListAddressesRequest, + protos.google.cloud.compute.v1.IAddressList | null | undefined, + protos.google.cloud.compute.v1.IAddress + >, + ): void; list( - request: protos.google.cloud.compute.v1.IListAddressesRequest, - callback: PaginationCallback< - protos.google.cloud.compute.v1.IListAddressesRequest, - protos.google.cloud.compute.v1.IAddressList|null|undefined, - protos.google.cloud.compute.v1.IAddress>): void; + request: protos.google.cloud.compute.v1.IListAddressesRequest, + callback: PaginationCallback< + protos.google.cloud.compute.v1.IListAddressesRequest, + protos.google.cloud.compute.v1.IAddressList | null | undefined, + protos.google.cloud.compute.v1.IAddress + >, + ): void; list( - request?: protos.google.cloud.compute.v1.IListAddressesRequest, - optionsOrCallback?: CallOptions|PaginationCallback< + request?: protos.google.cloud.compute.v1.IListAddressesRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.cloud.compute.v1.IListAddressesRequest, - protos.google.cloud.compute.v1.IAddressList|null|undefined, - protos.google.cloud.compute.v1.IAddress>, - callback?: PaginationCallback< - protos.google.cloud.compute.v1.IListAddressesRequest, - protos.google.cloud.compute.v1.IAddressList|null|undefined, - protos.google.cloud.compute.v1.IAddress>): - Promise<[ - protos.google.cloud.compute.v1.IAddress[], - protos.google.cloud.compute.v1.IListAddressesRequest|null, - protos.google.cloud.compute.v1.IAddressList - ]>|void { + protos.google.cloud.compute.v1.IAddressList | null | undefined, + protos.google.cloud.compute.v1.IAddress + >, + callback?: PaginationCallback< + protos.google.cloud.compute.v1.IListAddressesRequest, + protos.google.cloud.compute.v1.IAddressList | null | undefined, + protos.google.cloud.compute.v1.IAddress + >, + ): Promise< + [ + protos.google.cloud.compute.v1.IAddress[], + protos.google.cloud.compute.v1.IListAddressesRequest | null, + protos.google.cloud.compute.v1.IAddressList, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'project': request.project ?? '', - 'region': request.region ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + project: request.project ?? '', + region: request.region ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.cloud.compute.v1.IListAddressesRequest, - protos.google.cloud.compute.v1.IAddressList|null|undefined, - protos.google.cloud.compute.v1.IAddress>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.cloud.compute.v1.IListAddressesRequest, + protos.google.cloud.compute.v1.IAddressList | null | undefined, + protos.google.cloud.compute.v1.IAddress + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('list values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -722,140 +880,144 @@ export class AddressesClient { this._log.info('list request %j', request); return this.innerApiCalls .list(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.cloud.compute.v1.IAddress[], - protos.google.cloud.compute.v1.IListAddressesRequest|null, - protos.google.cloud.compute.v1.IAddressList - ]) => { - this._log.info('list values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.cloud.compute.v1.IAddress[], + protos.google.cloud.compute.v1.IListAddressesRequest | null, + protos.google.cloud.compute.v1.IAddressList, + ]) => { + this._log.info('list values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `list`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.filter - * A filter expression that filters resources listed in the response. The expression must specify the field name, a comparison operator, and the value that you want to use for filtering. The value must be a string, a number, or a boolean. The comparison operator must be either =, !=, >, or <. - * - * For example, if you are filtering Compute Engine instances, you can exclude instances named example-instance by specifying name != example-instance. - * - * You can also filter nested fields. For example, you could specify scheduling.automaticRestart = false to include instances only if they are not scheduled for automatic restarts. You can use filtering on nested fields to filter based on resource labels. - * - * To filter on multiple expressions, provide each separate expression within parentheses. For example, (scheduling.automaticRestart = true) (cpuPlatform = "Intel Skylake"). By default, each expression is an AND expression. However, you can include AND and OR expressions explicitly. For example, (cpuPlatform = "Intel Skylake") OR (cpuPlatform = "Intel Broadwell") AND (scheduling.automaticRestart = true). - * @param {number} request.maxResults - * The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests. Acceptable values are 0 to 500, inclusive. (Default: 500) - * @param {string} request.orderBy - * Sorts list results by a certain order. By default, results are returned in alphanumerical order based on the resource name. - * - * You can also sort results in descending order based on the creation timestamp using orderBy="creationTimestamp desc". This sorts results based on the creationTimestamp field in reverse chronological order (newest result first). Use this to sort resources like operations so that the newest operation is returned first. - * - * Currently, only sorting by name or creationTimestamp desc is supported. - * @param {string} request.pageToken - * Specifies a page token to use. Set pageToken to the nextPageToken returned by a previous list request to get the next page of results. - * @param {string} request.project - * Project ID for this request. - * @param {string} request.region - * Name of the region for this request. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.cloud.compute.v1.Address|Address} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `listAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `list`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.filter + * A filter expression that filters resources listed in the response. The expression must specify the field name, a comparison operator, and the value that you want to use for filtering. The value must be a string, a number, or a boolean. The comparison operator must be either =, !=, >, or <. + * + * For example, if you are filtering Compute Engine instances, you can exclude instances named example-instance by specifying name != example-instance. + * + * You can also filter nested fields. For example, you could specify scheduling.automaticRestart = false to include instances only if they are not scheduled for automatic restarts. You can use filtering on nested fields to filter based on resource labels. + * + * To filter on multiple expressions, provide each separate expression within parentheses. For example, (scheduling.automaticRestart = true) (cpuPlatform = "Intel Skylake"). By default, each expression is an AND expression. However, you can include AND and OR expressions explicitly. For example, (cpuPlatform = "Intel Skylake") OR (cpuPlatform = "Intel Broadwell") AND (scheduling.automaticRestart = true). + * @param {number} request.maxResults + * The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests. Acceptable values are 0 to 500, inclusive. (Default: 500) + * @param {string} request.orderBy + * Sorts list results by a certain order. By default, results are returned in alphanumerical order based on the resource name. + * + * You can also sort results in descending order based on the creation timestamp using orderBy="creationTimestamp desc". This sorts results based on the creationTimestamp field in reverse chronological order (newest result first). Use this to sort resources like operations so that the newest operation is returned first. + * + * Currently, only sorting by name or creationTimestamp desc is supported. + * @param {string} request.pageToken + * Specifies a page token to use. Set pageToken to the nextPageToken returned by a previous list request to get the next page of results. + * @param {string} request.project + * Project ID for this request. + * @param {string} request.region + * Name of the region for this request. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.cloud.compute.v1.Address|Address} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listStream( - request?: protos.google.cloud.compute.v1.IListAddressesRequest, - options?: CallOptions): - Transform{ + request?: protos.google.cloud.compute.v1.IListAddressesRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'project': request.project ?? '', - 'region': request.region ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + project: request.project ?? '', + region: request.region ?? '', + }); const defaultCallSettings = this._defaults['list']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('list stream %j', request); return this.descriptors.page.list.createStream( this.innerApiCalls.list as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `list`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.filter - * A filter expression that filters resources listed in the response. The expression must specify the field name, a comparison operator, and the value that you want to use for filtering. The value must be a string, a number, or a boolean. The comparison operator must be either =, !=, >, or <. - * - * For example, if you are filtering Compute Engine instances, you can exclude instances named example-instance by specifying name != example-instance. - * - * You can also filter nested fields. For example, you could specify scheduling.automaticRestart = false to include instances only if they are not scheduled for automatic restarts. You can use filtering on nested fields to filter based on resource labels. - * - * To filter on multiple expressions, provide each separate expression within parentheses. For example, (scheduling.automaticRestart = true) (cpuPlatform = "Intel Skylake"). By default, each expression is an AND expression. However, you can include AND and OR expressions explicitly. For example, (cpuPlatform = "Intel Skylake") OR (cpuPlatform = "Intel Broadwell") AND (scheduling.automaticRestart = true). - * @param {number} request.maxResults - * The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests. Acceptable values are 0 to 500, inclusive. (Default: 500) - * @param {string} request.orderBy - * Sorts list results by a certain order. By default, results are returned in alphanumerical order based on the resource name. - * - * You can also sort results in descending order based on the creation timestamp using orderBy="creationTimestamp desc". This sorts results based on the creationTimestamp field in reverse chronological order (newest result first). Use this to sort resources like operations so that the newest operation is returned first. - * - * Currently, only sorting by name or creationTimestamp desc is supported. - * @param {string} request.pageToken - * Specifies a page token to use. Set pageToken to the nextPageToken returned by a previous list request to get the next page of results. - * @param {string} request.project - * Project ID for this request. - * @param {string} request.region - * Name of the region for this request. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.cloud.compute.v1.Address|Address}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v1/addresses.list.js - * region_tag:compute_v1_generated_Addresses_List_async - */ + /** + * Equivalent to `list`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.filter + * A filter expression that filters resources listed in the response. The expression must specify the field name, a comparison operator, and the value that you want to use for filtering. The value must be a string, a number, or a boolean. The comparison operator must be either =, !=, >, or <. + * + * For example, if you are filtering Compute Engine instances, you can exclude instances named example-instance by specifying name != example-instance. + * + * You can also filter nested fields. For example, you could specify scheduling.automaticRestart = false to include instances only if they are not scheduled for automatic restarts. You can use filtering on nested fields to filter based on resource labels. + * + * To filter on multiple expressions, provide each separate expression within parentheses. For example, (scheduling.automaticRestart = true) (cpuPlatform = "Intel Skylake"). By default, each expression is an AND expression. However, you can include AND and OR expressions explicitly. For example, (cpuPlatform = "Intel Skylake") OR (cpuPlatform = "Intel Broadwell") AND (scheduling.automaticRestart = true). + * @param {number} request.maxResults + * The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests. Acceptable values are 0 to 500, inclusive. (Default: 500) + * @param {string} request.orderBy + * Sorts list results by a certain order. By default, results are returned in alphanumerical order based on the resource name. + * + * You can also sort results in descending order based on the creation timestamp using orderBy="creationTimestamp desc". This sorts results based on the creationTimestamp field in reverse chronological order (newest result first). Use this to sort resources like operations so that the newest operation is returned first. + * + * Currently, only sorting by name or creationTimestamp desc is supported. + * @param {string} request.pageToken + * Specifies a page token to use. Set pageToken to the nextPageToken returned by a previous list request to get the next page of results. + * @param {string} request.project + * Project ID for this request. + * @param {string} request.region + * Name of the region for this request. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.cloud.compute.v1.Address|Address}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v1/addresses.list.js + * region_tag:compute_v1_generated_Addresses_List_async + */ listAsync( - request?: protos.google.cloud.compute.v1.IListAddressesRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.cloud.compute.v1.IListAddressesRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'project': request.project ?? '', - 'region': request.region ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + project: request.project ?? '', + region: request.region ?? '', + }); const defaultCallSettings = this._defaults['list']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('list iterate %j', request); return this.descriptors.page.list.asyncIterate( this.innerApiCalls['list'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } @@ -867,7 +1029,7 @@ export class AddressesClient { */ close(): Promise { if (this.addressesStub && !this._terminated) { - return this.addressesStub.then(stub => { + return this.addressesStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -875,4 +1037,4 @@ export class AddressesClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/core/generator/gapic-generator-typescript/baselines/compute/src/v1/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/compute/src/v1/index.ts.baseline index 89eedd6b8c95..cdfa041a2c7e 100644 --- a/core/generator/gapic-generator-typescript/baselines/compute/src/v1/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/compute/src/v1/index.ts.baseline @@ -16,5 +16,5 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -export {AddressesClient} from './addresses_client'; -export {RegionOperationsClient} from './region_operations_client'; +export { AddressesClient } from './addresses_client'; +export { RegionOperationsClient } from './region_operations_client'; diff --git a/core/generator/gapic-generator-typescript/baselines/compute/src/v1/region_operations_client.ts.baseline b/core/generator/gapic-generator-typescript/baselines/compute/src/v1/region_operations_client.ts.baseline index 7a51227dbe50..0185f1408b52 100644 --- a/core/generator/gapic-generator-typescript/baselines/compute/src/v1/region_operations_client.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/compute/src/v1/region_operations_client.ts.baseline @@ -18,11 +18,16 @@ /* global window */ import type * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions} from 'google-gax'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, +} from 'google-gax'; import * as protos from '../../protos/protos'; import jsonProtos = require('../../protos/protos.json'); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; /** * Client JSON configuration object, loaded from @@ -44,7 +49,7 @@ export class RegionOperationsClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('compute'); @@ -57,8 +62,8 @@ export class RegionOperationsClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - regionOperationsStub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + regionOperationsStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of RegionOperationsClient. @@ -99,27 +104,48 @@ export class RegionOperationsClient { * const client = new RegionOperationsClient({fallback: true}, gax); * ``` */ - constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { // Ensure that options include all the required fields. const staticMembers = this.constructor as typeof RegionOperationsClient; - if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { - throw new Error('Please set either universe_domain or universeDomain, but not both.'); + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); } - const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; - this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; this._servicePath = 'compute.' + this._universeDomain; - const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; // Implicitly enable HTTP transport for the APIs that use REST as transport (e.g. Google Cloud Compute). if (!opts) { - opts = {fallback: true}; + opts = { fallback: true }; } else { opts.fallback = opts.fallback ?? true; } - const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. if (servicePath !== this._servicePath && !('scopes' in opts)) { @@ -141,7 +167,7 @@ export class RegionOperationsClient { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set defaultServicePath on the auth object. this.auth.defaultServicePath = this._servicePath; @@ -152,10 +178,7 @@ export class RegionOperationsClient { } // Determine the client header string. - const clientHeader = [ - `gax/${this._gaxModule.version}`, - `gapic/${version}`, - ]; + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/${process.versions.node}`); } else { @@ -174,8 +197,11 @@ export class RegionOperationsClient { // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.cloud.compute.v1.RegionOperations', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.cloud.compute.v1.RegionOperations', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + { 'x-goog-api-client': clientHeader.join(' ') }, + ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -206,36 +232,40 @@ export class RegionOperationsClient { // Put together the "service stub" for // google.cloud.compute.v1.RegionOperations. this.regionOperationsStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.cloud.compute.v1.RegionOperations') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.cloud.compute.v1.RegionOperations', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.cloud.compute.v1.RegionOperations, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts, + this._providedCustomServicePath, + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const regionOperationsStubMethods = - ['get', 'wait']; + const regionOperationsStubMethods = ['get', 'wait']; for (const methodName of regionOperationsStubMethods) { const callPromise = this.regionOperationsStub.then( - stub => (...args: Array<{}>) => { - if (this._terminated) { - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error|null|undefined) => () => { + (stub) => + (...args: Array<{}>) => { + if (this._terminated) { + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { throw err; - }); + }, + ); - const descriptor = - undefined; + const descriptor = undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -250,8 +280,14 @@ export class RegionOperationsClient { * @returns {string} The DNS address for this service. */ static get servicePath() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'compute.googleapis.com'; } @@ -262,8 +298,14 @@ export class RegionOperationsClient { * @returns {string} The DNS address for this service. */ static get apiEndpoint() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'compute.googleapis.com'; } @@ -297,7 +339,7 @@ export class RegionOperationsClient { return [ 'https://www.googleapis.com/auth/compute.readonly', 'https://www.googleapis.com/auth/compute', - 'https://www.googleapis.com/auth/cloud-platform' + 'https://www.googleapis.com/auth/cloud-platform', ]; } @@ -307,8 +349,9 @@ export class RegionOperationsClient { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId(callback?: Callback): - Promise|void { + getProjectId( + callback?: Callback, + ): Promise | void { if (callback) { this.auth.getProjectId(callback); return; @@ -319,212 +362,294 @@ export class RegionOperationsClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Retrieves the specified region-specific Operations resource. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.operation - * Name of the Operations resource to return. - * @param {string} request.project - * Project ID for this request. - * @param {string} request.region - * Name of the region for this request. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.compute.v1.Operation|Operation}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1/region_operations.get.js - * region_tag:compute_v1_generated_RegionOperations_Get_async - */ + /** + * Retrieves the specified region-specific Operations resource. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.operation + * Name of the Operations resource to return. + * @param {string} request.project + * Project ID for this request. + * @param {string} request.region + * Name of the region for this request. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.compute.v1.Operation|Operation}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/region_operations.get.js + * region_tag:compute_v1_generated_RegionOperations_Get_async + */ get( - request?: protos.google.cloud.compute.v1.IGetRegionOperationRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.compute.v1.IOperation, - protos.google.cloud.compute.v1.IGetRegionOperationRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.compute.v1.IGetRegionOperationRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.compute.v1.IOperation, + protos.google.cloud.compute.v1.IGetRegionOperationRequest | undefined, + {} | undefined, + ] + >; get( - request: protos.google.cloud.compute.v1.IGetRegionOperationRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.compute.v1.IOperation, - protos.google.cloud.compute.v1.IGetRegionOperationRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.compute.v1.IGetRegionOperationRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.compute.v1.IOperation, + | protos.google.cloud.compute.v1.IGetRegionOperationRequest + | null + | undefined, + {} | null | undefined + >, + ): void; get( - request: protos.google.cloud.compute.v1.IGetRegionOperationRequest, - callback: Callback< - protos.google.cloud.compute.v1.IOperation, - protos.google.cloud.compute.v1.IGetRegionOperationRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.compute.v1.IGetRegionOperationRequest, + callback: Callback< + protos.google.cloud.compute.v1.IOperation, + | protos.google.cloud.compute.v1.IGetRegionOperationRequest + | null + | undefined, + {} | null | undefined + >, + ): void; get( - request?: protos.google.cloud.compute.v1.IGetRegionOperationRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.compute.v1.IOperation, - protos.google.cloud.compute.v1.IGetRegionOperationRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.compute.v1.IGetRegionOperationRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.compute.v1.IOperation, - protos.google.cloud.compute.v1.IGetRegionOperationRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.compute.v1.IOperation, - protos.google.cloud.compute.v1.IGetRegionOperationRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.compute.v1.IGetRegionOperationRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.compute.v1.IOperation, + | protos.google.cloud.compute.v1.IGetRegionOperationRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.compute.v1.IOperation, + protos.google.cloud.compute.v1.IGetRegionOperationRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'project': request.project ?? '', - 'region': request.region ?? '', - 'operation': request.operation ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + project: request.project ?? '', + region: request.region ?? '', + operation: request.operation ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('get request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.compute.v1.IOperation, - protos.google.cloud.compute.v1.IGetRegionOperationRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.compute.v1.IOperation, + | protos.google.cloud.compute.v1.IGetRegionOperationRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('get response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.get(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.compute.v1.IOperation, - protos.google.cloud.compute.v1.IGetRegionOperationRequest|undefined, - {}|undefined - ]) => { - this._log.info('get response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .get(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.compute.v1.IOperation, + protos.google.cloud.compute.v1.IGetRegionOperationRequest | undefined, + {} | undefined, + ]) => { + this._log.info('get response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Waits for the specified Operation resource to return as `DONE` or for the request to approach the 2 minute deadline, and retrieves the specified Operation resource. This method differs from the `GET` method in that it waits for no more than the default deadline (2 minutes) and then returns the current state of the operation, which might be `DONE` or still in progress. - * - * This method is called on a best-effort basis. Specifically: - * - In uncommon cases, when the server is overloaded, the request might return before the default deadline is reached, or might return after zero seconds. - * - If the default deadline is reached, there is no guarantee that the operation is actually done when the method returns. Be prepared to retry if the operation is not `DONE`. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.operation - * Name of the Operations resource to return. - * @param {string} request.project - * Project ID for this request. - * @param {string} request.region - * Name of the region for this request. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.compute.v1.Operation|Operation}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1/region_operations.wait.js - * region_tag:compute_v1_generated_RegionOperations_Wait_async - */ + /** + * Waits for the specified Operation resource to return as `DONE` or for the request to approach the 2 minute deadline, and retrieves the specified Operation resource. This method differs from the `GET` method in that it waits for no more than the default deadline (2 minutes) and then returns the current state of the operation, which might be `DONE` or still in progress. + * + * This method is called on a best-effort basis. Specifically: + * - In uncommon cases, when the server is overloaded, the request might return before the default deadline is reached, or might return after zero seconds. + * - If the default deadline is reached, there is no guarantee that the operation is actually done when the method returns. Be prepared to retry if the operation is not `DONE`. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.operation + * Name of the Operations resource to return. + * @param {string} request.project + * Project ID for this request. + * @param {string} request.region + * Name of the region for this request. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.compute.v1.Operation|Operation}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/region_operations.wait.js + * region_tag:compute_v1_generated_RegionOperations_Wait_async + */ wait( - request?: protos.google.cloud.compute.v1.IWaitRegionOperationRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.compute.v1.IOperation, - protos.google.cloud.compute.v1.IWaitRegionOperationRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.compute.v1.IWaitRegionOperationRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.compute.v1.IOperation, + protos.google.cloud.compute.v1.IWaitRegionOperationRequest | undefined, + {} | undefined, + ] + >; wait( - request: protos.google.cloud.compute.v1.IWaitRegionOperationRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.compute.v1.IOperation, - protos.google.cloud.compute.v1.IWaitRegionOperationRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.compute.v1.IWaitRegionOperationRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.compute.v1.IOperation, + | protos.google.cloud.compute.v1.IWaitRegionOperationRequest + | null + | undefined, + {} | null | undefined + >, + ): void; wait( - request: protos.google.cloud.compute.v1.IWaitRegionOperationRequest, - callback: Callback< - protos.google.cloud.compute.v1.IOperation, - protos.google.cloud.compute.v1.IWaitRegionOperationRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.compute.v1.IWaitRegionOperationRequest, + callback: Callback< + protos.google.cloud.compute.v1.IOperation, + | protos.google.cloud.compute.v1.IWaitRegionOperationRequest + | null + | undefined, + {} | null | undefined + >, + ): void; wait( - request?: protos.google.cloud.compute.v1.IWaitRegionOperationRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.cloud.compute.v1.IWaitRegionOperationRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.compute.v1.IOperation, - protos.google.cloud.compute.v1.IWaitRegionOperationRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.cloud.compute.v1.IOperation, - protos.google.cloud.compute.v1.IWaitRegionOperationRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.compute.v1.IOperation, - protos.google.cloud.compute.v1.IWaitRegionOperationRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.compute.v1.IWaitRegionOperationRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.compute.v1.IOperation, + | protos.google.cloud.compute.v1.IWaitRegionOperationRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.compute.v1.IOperation, + protos.google.cloud.compute.v1.IWaitRegionOperationRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'project': request.project ?? '', - 'region': request.region ?? '', - 'operation': request.operation ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + project: request.project ?? '', + region: request.region ?? '', + operation: request.operation ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('wait request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.compute.v1.IOperation, - protos.google.cloud.compute.v1.IWaitRegionOperationRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.compute.v1.IOperation, + | protos.google.cloud.compute.v1.IWaitRegionOperationRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('wait response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.wait(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.compute.v1.IOperation, - protos.google.cloud.compute.v1.IWaitRegionOperationRequest|undefined, - {}|undefined - ]) => { - this._log.info('wait response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .wait(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.compute.v1.IOperation, + ( + | protos.google.cloud.compute.v1.IWaitRegionOperationRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('wait response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } - /** * Terminate the gRPC channel and close the client. * @@ -533,7 +658,7 @@ export class RegionOperationsClient { */ close(): Promise { if (this.regionOperationsStub && !this._terminated) { - return this.regionOperationsStub.then(stub => { + return this.regionOperationsStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -541,4 +666,4 @@ export class RegionOperationsClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/core/generator/gapic-generator-typescript/baselines/compute/system-test/fixtures/sample/src/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/compute/system-test/fixtures/sample/src/index.ts.baseline index 33f6383ebf4c..2ec7913a305e 100644 --- a/core/generator/gapic-generator-typescript/baselines/compute/system-test/fixtures/sample/src/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/compute/system-test/fixtures/sample/src/index.ts.baseline @@ -16,7 +16,7 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -import {AddressesClient, RegionOperationsClient} from '@google-cloud/compute'; +import { AddressesClient, RegionOperationsClient } from '@google-cloud/compute'; // check that the client class type name can be used function doStuffWithAddressesClient(client: AddressesClient) { diff --git a/core/generator/gapic-generator-typescript/baselines/compute/system-test/install.ts.baseline b/core/generator/gapic-generator-typescript/baselines/compute/system-test/install.ts.baseline index f66069aa3940..ccf167042d2e 100644 --- a/core/generator/gapic-generator-typescript/baselines/compute/system-test/install.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/compute/system-test/install.ts.baseline @@ -16,34 +16,36 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -import {packNTest} from 'pack-n-play'; -import {readFileSync} from 'fs'; -import {describe, it} from 'mocha'; +import { packNTest } from 'pack-n-play'; +import { readFileSync } from 'fs'; +import { describe, it } from 'mocha'; describe('📦 pack-n-play test', () => { - - it('TypeScript code', async function() { + it('TypeScript code', async function () { this.timeout(300000); const options = { packageDir: process.cwd(), sample: { description: 'TypeScript user can use the type definitions', - ts: readFileSync('./system-test/fixtures/sample/src/index.ts').toString() - } + ts: readFileSync( + './system-test/fixtures/sample/src/index.ts', + ).toString(), + }, }; await packNTest(options); }); - it('JavaScript code', async function() { + it('JavaScript code', async function () { this.timeout(300000); const options = { packageDir: process.cwd(), sample: { description: 'JavaScript user can use the library', - cjs: readFileSync('./system-test/fixtures/sample/src/index.js').toString() - } + cjs: readFileSync( + './system-test/fixtures/sample/src/index.js', + ).toString(), + }, }; await packNTest(options); }); - }); diff --git a/core/generator/gapic-generator-typescript/baselines/compute/test/gapic_addresses_v1.ts.baseline b/core/generator/gapic-generator-typescript/baselines/compute/test/gapic_addresses_v1.ts.baseline index 730191a98310..544c13a0d318 100644 --- a/core/generator/gapic-generator-typescript/baselines/compute/test/gapic_addresses_v1.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/compute/test/gapic_addresses_v1.ts.baseline @@ -19,84 +19,112 @@ import * as protos from '../protos/protos'; import * as assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it, beforeEach, afterEach} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it, beforeEach, afterEach } from 'mocha'; import * as addressesModule from '../src'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; -import {GoogleAuth, protobuf} from 'google-gax'; +import { GoogleAuth, protobuf } from 'google-gax'; // Dynamically loaded proto JSON is needed to get the type information // to fill in default values for request objects -const root = protobuf.Root.fromJSON(require('../protos/protos.json')).resolveAll(); +const root = protobuf.Root.fromJSON( + require('../protos/protos.json'), +).resolveAll(); // eslint-disable-next-line @typescript-eslint/no-unused-vars function getTypeDefaultValue(typeName: string, fields: string[]) { - let type = root.lookupType(typeName) as protobuf.Type; - for (const field of fields.slice(0, -1)) { - type = type.fields[field]?.resolvedType as protobuf.Type; - } - return type.fields[fields[fields.length - 1]]?.defaultValue; + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type.fields[field]?.resolvedType as protobuf.Type; + } + return type.fields[fields[fields.length - 1]]?.defaultValue; } function generateSampleMessage(instance: T) { - const filledObject = (instance.constructor as typeof protobuf.Message) - .toObject(instance as protobuf.Message, {defaults: true}); - return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, { defaults: true }); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; } function stubSimpleCall(response?: ResponseType, error?: Error) { - return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); } -function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { - return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +function stubSimpleCallWithCallback( + response?: ResponseType, + error?: Error, +) { + return error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); } -function stubPageStreamingCall(responses?: ResponseType[], error?: Error) { - const pagingStub = sinon.stub(); - if (responses) { - for (let i = 0; i < responses.length; ++i) { - pagingStub.onCall(i).callsArgWith(2, null, responses[i]); - } +function stubPageStreamingCall( + responses?: ResponseType[], + error?: Error, +) { + const pagingStub = sinon.stub(); + if (responses) { + for (let i = 0; i < responses.length; ++i) { + pagingStub.onCall(i).callsArgWith(2, null, responses[i]); } - const transformStub = error ? sinon.stub().callsArgWith(2, error) : pagingStub; - const mockStream = new PassThrough({ - objectMode: true, - transform: transformStub, - }); - // trigger as many responses as needed - if (responses) { - for (let i = 0; i < responses.length; ++i) { - setImmediate(() => { mockStream.write({}); }); - } - setImmediate(() => { mockStream.end(); }); - } else { - setImmediate(() => { mockStream.write({}); }); - setImmediate(() => { mockStream.end(); }); + } + const transformStub = error + ? sinon.stub().callsArgWith(2, error) + : pagingStub; + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + // trigger as many responses as needed + if (responses) { + for (let i = 0; i < responses.length; ++i) { + setImmediate(() => { + mockStream.write({}); + }); } - return sinon.stub().returns(mockStream); + setImmediate(() => { + mockStream.end(); + }); + } else { + setImmediate(() => { + mockStream.write({}); + }); + setImmediate(() => { + mockStream.end(); + }); + } + return sinon.stub().returns(mockStream); } -function stubAsyncIterationCall(responses?: ResponseType[], error?: Error) { - let counter = 0; - const asyncIterable = { - [Symbol.asyncIterator]() { - return { - async next() { - if (error) { - return Promise.reject(error); - } - if (counter >= responses!.length) { - return Promise.resolve({done: true, value: undefined}); - } - return Promise.resolve({done: false, value: responses![counter++]}); - } - }; - } - }; - return sinon.stub().returns(asyncIterable); +function stubAsyncIterationCall( + responses?: ResponseType[], + error?: Error, +) { + let counter = 0; + const asyncIterable = { + [Symbol.asyncIterator]() { + return { + async next() { + if (error) { + return Promise.reject(error); + } + if (counter >= responses!.length) { + return Promise.resolve({ done: true, value: undefined }); + } + return Promise.resolve({ done: false, value: responses![counter++] }); + }, + }; + }, + }; + return sinon.stub().returns(asyncIterable); } describe('v1.AddressesClient', () => { @@ -104,759 +132,952 @@ describe('v1.AddressesClient', () => { beforeEach(() => { googleAuth = { getClient: sinon.stub().resolves({ - getRequestHeaders: sinon.stub().resolves({Authorization: 'Bearer SOME_TOKEN'}), - }) + getRequestHeaders: sinon + .stub() + .resolves({ Authorization: 'Bearer SOME_TOKEN' }), + }), } as unknown as GoogleAuth; }); afterEach(() => { sinon.restore(); }); - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new addressesModule.v1.AddressesClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'compute.googleapis.com'); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new addressesModule.v1.AddressesClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'compute.googleapis.com'); + }); - it('has universeDomain', () => { - const client = new addressesModule.v1.AddressesClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); + it('has universeDomain', () => { + const client = new addressesModule.v1.AddressesClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - it('throws DeprecationWarning if static servicePath is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const servicePath = addressesModule.v1.AddressesClient.servicePath; - assert.strictEqual(servicePath, 'compute.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = addressesModule.v1.AddressesClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'compute.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new addressesModule.v1.AddressesClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'compute.example.com'); - }); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = addressesModule.v1.AddressesClient.servicePath; + assert.strictEqual(servicePath, 'compute.googleapis.com'); + assert(stub.called); + stub.restore(); + }); - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new addressesModule.v1.AddressesClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'compute.example.com'); - }); + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = addressesModule.v1.AddressesClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'compute.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = new addressesModule.v1.AddressesClient({ + universeDomain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'compute.example.com'); + }); - if (typeof process === 'object' && 'env' in process) { - describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { - it('sets apiEndpoint from environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new addressesModule.v1.AddressesClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'compute.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - - it('value configured in code has priority over environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new addressesModule.v1.AddressesClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'compute.configured.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { new addressesModule.v1.AddressesClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = new addressesModule.v1.AddressesClient({ + universe_domain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'compute.example.com'); + }); - it('has port', () => { - const port = addressesModule.v1.AddressesClient.port; - assert(port); - assert(typeof port === 'number'); + if (typeof process === 'object' && 'env' in process) { + describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { + it('sets apiEndpoint from environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new addressesModule.v1.AddressesClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'compute.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - it('should create a client with no option', () => { - const client = new addressesModule.v1.AddressesClient(); - assert(client); + it('value configured in code has priority over environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new addressesModule.v1.AddressesClient({ + universeDomain: 'configured.example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'compute.configured.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - - it('should create a client with gRPC fallback', () => { - const client = new addressesModule.v1.AddressesClient({ - fallback: true, - }); - assert(client); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new addressesModule.v1.AddressesClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); + }); - it('has initialize method and supports deferred initialization', async () => { - const client = new addressesModule.v1.AddressesClient({ - auth: googleAuth, - projectId: 'bogus', - }); - assert.strictEqual(client.addressesStub, undefined); - await client.initialize(); - assert(client.addressesStub); - }); + it('has port', () => { + const port = addressesModule.v1.AddressesClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('has close method for the initialized client', done => { - const client = new addressesModule.v1.AddressesClient({ - auth: googleAuth, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.addressesStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('should create a client with no option', () => { + const client = new addressesModule.v1.AddressesClient(); + assert(client); + }); - it('has close method for the non-initialized client', done => { - const client = new addressesModule.v1.AddressesClient({ - auth: googleAuth, - projectId: 'bogus', - }); - assert.strictEqual(client.addressesStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('should create a client with gRPC fallback', () => { + const client = new addressesModule.v1.AddressesClient({ + fallback: true, + }); + assert(client); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new addressesModule.v1.AddressesClient({ - auth: googleAuth, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); - }); + it('has initialize method and supports deferred initialization', async () => { + const client = new addressesModule.v1.AddressesClient({ + auth: googleAuth, + projectId: 'bogus', + }); + assert.strictEqual(client.addressesStub, undefined); + await client.initialize(); + assert(client.addressesStub); + }); - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new addressesModule.v1.AddressesClient({ - auth: googleAuth, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId((err?: Error|null, projectId?: string|null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } - }); - }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); + it('has close method for the initialized client', (done) => { + const client = new addressesModule.v1.AddressesClient({ + auth: googleAuth, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.addressesStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); }); - describe('delete', () => { - it('invokes delete without error', async () => { - const client = new addressesModule.v1.AddressesClient({ - auth: googleAuth, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.compute.v1.DeleteAddressRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.compute.v1.DeleteAddressRequest', ['project']); - request.project = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.compute.v1.DeleteAddressRequest', ['region']); - request.region = defaultValue2; - const defaultValue3 = - getTypeDefaultValue('.google.cloud.compute.v1.DeleteAddressRequest', ['address']); - request.address = defaultValue3; - const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }®ion=${defaultValue2 ?? '' }&address=${defaultValue3 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.compute.v1.Operation() - ); - client.innerApiCalls.delete = stubSimpleCall(expectedResponse); - const [response] = await client.delete(request); - assert.deepStrictEqual(response.latestResponse, expectedResponse); - const actualRequest = (client.innerApiCalls.delete as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.delete as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('has close method for the non-initialized client', (done) => { + const client = new addressesModule.v1.AddressesClient({ + auth: googleAuth, + projectId: 'bogus', + }); + assert.strictEqual(client.addressesStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes delete without error using callback', async () => { - const client = new addressesModule.v1.AddressesClient({ - auth: googleAuth, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.compute.v1.DeleteAddressRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.compute.v1.DeleteAddressRequest', ['project']); - request.project = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.compute.v1.DeleteAddressRequest', ['region']); - request.region = defaultValue2; - const defaultValue3 = - getTypeDefaultValue('.google.cloud.compute.v1.DeleteAddressRequest', ['address']); - request.address = defaultValue3; - const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }®ion=${defaultValue2 ?? '' }&address=${defaultValue3 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.compute.v1.Operation() - ); - client.innerApiCalls.delete = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.delete( - request, - (err?: Error|null, result?: protos.google.cloud.compute.v1.IOperation|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.delete as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.delete as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new addressesModule.v1.AddressesClient({ + auth: googleAuth, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + }); - it('invokes delete with error', async () => { - const client = new addressesModule.v1.AddressesClient({ - auth: googleAuth, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.compute.v1.DeleteAddressRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.compute.v1.DeleteAddressRequest', ['project']); - request.project = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.compute.v1.DeleteAddressRequest', ['region']); - request.region = defaultValue2; - const defaultValue3 = - getTypeDefaultValue('.google.cloud.compute.v1.DeleteAddressRequest', ['address']); - request.address = defaultValue3; - const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }®ion=${defaultValue2 ?? '' }&address=${defaultValue3 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.delete = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.delete(request), expectedError); - const actualRequest = (client.innerApiCalls.delete as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.delete as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new addressesModule.v1.AddressesClient({ + auth: googleAuth, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + }); - it('invokes delete with closed client', async () => { - const client = new addressesModule.v1.AddressesClient({ - auth: googleAuth, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.compute.v1.DeleteAddressRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.compute.v1.DeleteAddressRequest', ['project']); - request.project = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.compute.v1.DeleteAddressRequest', ['region']); - request.region = defaultValue2; - const defaultValue3 = - getTypeDefaultValue('.google.cloud.compute.v1.DeleteAddressRequest', ['address']); - request.address = defaultValue3; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.delete(request), expectedError); - }); + describe('delete', () => { + it('invokes delete without error', async () => { + const client = new addressesModule.v1.AddressesClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1.DeleteAddressRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.compute.v1.DeleteAddressRequest', + ['project'], + ); + request.project = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.compute.v1.DeleteAddressRequest', + ['region'], + ); + request.region = defaultValue2; + const defaultValue3 = getTypeDefaultValue( + '.google.cloud.compute.v1.DeleteAddressRequest', + ['address'], + ); + request.address = defaultValue3; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? ''}®ion=${defaultValue2 ?? ''}&address=${defaultValue3 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.compute.v1.Operation(), + ); + client.innerApiCalls.delete = stubSimpleCall(expectedResponse); + const [response] = await client.delete(request); + assert.deepStrictEqual(response.latestResponse, expectedResponse); + const actualRequest = (client.innerApiCalls.delete as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.delete as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('insert', () => { - it('invokes insert without error', async () => { - const client = new addressesModule.v1.AddressesClient({ - auth: googleAuth, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.compute.v1.InsertAddressRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.compute.v1.InsertAddressRequest', ['project']); - request.project = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.compute.v1.InsertAddressRequest', ['region']); - request.region = defaultValue2; - const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }®ion=${defaultValue2 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.compute.v1.Operation() - ); - client.innerApiCalls.insert = stubSimpleCall(expectedResponse); - const [response] = await client.insert(request); - assert.deepStrictEqual(response.latestResponse, expectedResponse); - const actualRequest = (client.innerApiCalls.insert as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.insert as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes delete without error using callback', async () => { + const client = new addressesModule.v1.AddressesClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1.DeleteAddressRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.compute.v1.DeleteAddressRequest', + ['project'], + ); + request.project = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.compute.v1.DeleteAddressRequest', + ['region'], + ); + request.region = defaultValue2; + const defaultValue3 = getTypeDefaultValue( + '.google.cloud.compute.v1.DeleteAddressRequest', + ['address'], + ); + request.address = defaultValue3; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? ''}®ion=${defaultValue2 ?? ''}&address=${defaultValue3 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.compute.v1.Operation(), + ); + client.innerApiCalls.delete = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.delete( + request, + ( + err?: Error | null, + result?: protos.google.cloud.compute.v1.IOperation | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.delete as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.delete as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes insert without error using callback', async () => { - const client = new addressesModule.v1.AddressesClient({ - auth: googleAuth, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.compute.v1.InsertAddressRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.compute.v1.InsertAddressRequest', ['project']); - request.project = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.compute.v1.InsertAddressRequest', ['region']); - request.region = defaultValue2; - const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }®ion=${defaultValue2 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.compute.v1.Operation() - ); - client.innerApiCalls.insert = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.insert( - request, - (err?: Error|null, result?: protos.google.cloud.compute.v1.IOperation|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.insert as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.insert as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes delete with error', async () => { + const client = new addressesModule.v1.AddressesClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1.DeleteAddressRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.compute.v1.DeleteAddressRequest', + ['project'], + ); + request.project = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.compute.v1.DeleteAddressRequest', + ['region'], + ); + request.region = defaultValue2; + const defaultValue3 = getTypeDefaultValue( + '.google.cloud.compute.v1.DeleteAddressRequest', + ['address'], + ); + request.address = defaultValue3; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? ''}®ion=${defaultValue2 ?? ''}&address=${defaultValue3 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.delete = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.delete(request), expectedError); + const actualRequest = (client.innerApiCalls.delete as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.delete as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes insert with error', async () => { - const client = new addressesModule.v1.AddressesClient({ - auth: googleAuth, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.compute.v1.InsertAddressRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.compute.v1.InsertAddressRequest', ['project']); - request.project = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.compute.v1.InsertAddressRequest', ['region']); - request.region = defaultValue2; - const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }®ion=${defaultValue2 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.insert = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.insert(request), expectedError); - const actualRequest = (client.innerApiCalls.insert as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.insert as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes delete with closed client', async () => { + const client = new addressesModule.v1.AddressesClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1.DeleteAddressRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.compute.v1.DeleteAddressRequest', + ['project'], + ); + request.project = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.compute.v1.DeleteAddressRequest', + ['region'], + ); + request.region = defaultValue2; + const defaultValue3 = getTypeDefaultValue( + '.google.cloud.compute.v1.DeleteAddressRequest', + ['address'], + ); + request.address = defaultValue3; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.delete(request), expectedError); + }); + }); - it('invokes insert with closed client', async () => { - const client = new addressesModule.v1.AddressesClient({ - auth: googleAuth, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.compute.v1.InsertAddressRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.compute.v1.InsertAddressRequest', ['project']); - request.project = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.compute.v1.InsertAddressRequest', ['region']); - request.region = defaultValue2; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.insert(request), expectedError); - }); + describe('insert', () => { + it('invokes insert without error', async () => { + const client = new addressesModule.v1.AddressesClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1.InsertAddressRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.compute.v1.InsertAddressRequest', + ['project'], + ); + request.project = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.compute.v1.InsertAddressRequest', + ['region'], + ); + request.region = defaultValue2; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? ''}®ion=${defaultValue2 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.compute.v1.Operation(), + ); + client.innerApiCalls.insert = stubSimpleCall(expectedResponse); + const [response] = await client.insert(request); + assert.deepStrictEqual(response.latestResponse, expectedResponse); + const actualRequest = (client.innerApiCalls.insert as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.insert as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('aggregatedList', () => { - - it('uses async iteration with aggregatedList without error', async () => { - const client = new addressesModule.v1.AddressesClient({ - auth: googleAuth, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.compute.v1.AggregatedListAddressesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.compute.v1.AggregatedListAddressesRequest', ['project']); - request.project = defaultValue1; - const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }`; - const expectedResponse = [ - ['tuple_key_1', generateSampleMessage(new protos.google.cloud.compute.v1.AddressesScopedList())], - ['tuple_key_2', generateSampleMessage(new protos.google.cloud.compute.v1.AddressesScopedList())], - ['tuple_key_3', generateSampleMessage(new protos.google.cloud.compute.v1.AddressesScopedList())], - ]; - client.descriptors.page.aggregatedList.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: Array<[string, protos.google.cloud.compute.v1.IAddressesScopedList]> = []; - const iterable = client.aggregatedListAsync(request); - for await (const resource of iterable) { - responses.push(resource!); + it('invokes insert without error using callback', async () => { + const client = new addressesModule.v1.AddressesClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1.InsertAddressRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.compute.v1.InsertAddressRequest', + ['project'], + ); + request.project = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.compute.v1.InsertAddressRequest', + ['region'], + ); + request.region = defaultValue2; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? ''}®ion=${defaultValue2 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.compute.v1.Operation(), + ); + client.innerApiCalls.insert = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.insert( + request, + ( + err?: Error | null, + result?: protos.google.cloud.compute.v1.IOperation | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.aggregatedList.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.aggregatedList.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); - - it('uses async iteration with aggregatedList with error', async () => { - const client = new addressesModule.v1.AddressesClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.compute.v1.AggregatedListAddressesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.compute.v1.AggregatedListAddressesRequest', ['project']); - request.project = defaultValue1; - const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.aggregatedList.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.aggregatedListAsync(request); - await assert.rejects(async () => { - const responses: Array<[string, protos.google.cloud.compute.v1.IAddressesScopedList]> = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.aggregatedList.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.aggregatedList.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.insert as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.insert as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('list', () => { - it('invokes list without error', async () => { - const client = new addressesModule.v1.AddressesClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.compute.v1.ListAddressesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.compute.v1.ListAddressesRequest', ['project']); - request.project = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.compute.v1.ListAddressesRequest', ['region']); - request.region = defaultValue2; - const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }®ion=${defaultValue2 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.compute.v1.Address()), - generateSampleMessage(new protos.google.cloud.compute.v1.Address()), - generateSampleMessage(new protos.google.cloud.compute.v1.Address()), - ]; - client.innerApiCalls.list = stubSimpleCall(expectedResponse); - const [response] = await client.list(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.list as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.list as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes insert with error', async () => { + const client = new addressesModule.v1.AddressesClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1.InsertAddressRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.compute.v1.InsertAddressRequest', + ['project'], + ); + request.project = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.compute.v1.InsertAddressRequest', + ['region'], + ); + request.region = defaultValue2; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? ''}®ion=${defaultValue2 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.insert = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.insert(request), expectedError); + const actualRequest = (client.innerApiCalls.insert as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.insert as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes list without error using callback', async () => { - const client = new addressesModule.v1.AddressesClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.compute.v1.ListAddressesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.compute.v1.ListAddressesRequest', ['project']); - request.project = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.compute.v1.ListAddressesRequest', ['region']); - request.region = defaultValue2; - const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }®ion=${defaultValue2 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.compute.v1.Address()), - generateSampleMessage(new protos.google.cloud.compute.v1.Address()), - generateSampleMessage(new protos.google.cloud.compute.v1.Address()), - ]; - client.innerApiCalls.list = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.list( - request, - (err?: Error|null, result?: protos.google.cloud.compute.v1.IAddress[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.list as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.list as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes insert with closed client', async () => { + const client = new addressesModule.v1.AddressesClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1.InsertAddressRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.compute.v1.InsertAddressRequest', + ['project'], + ); + request.project = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.compute.v1.InsertAddressRequest', + ['region'], + ); + request.region = defaultValue2; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.insert(request), expectedError); + }); + }); - it('invokes list with error', async () => { - const client = new addressesModule.v1.AddressesClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.compute.v1.ListAddressesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.compute.v1.ListAddressesRequest', ['project']); - request.project = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.compute.v1.ListAddressesRequest', ['region']); - request.region = defaultValue2; - const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }®ion=${defaultValue2 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.list = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.list(request), expectedError); - const actualRequest = (client.innerApiCalls.list as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.list as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + describe('aggregatedList', () => { + it('uses async iteration with aggregatedList without error', async () => { + const client = new addressesModule.v1.AddressesClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1.AggregatedListAddressesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.compute.v1.AggregatedListAddressesRequest', + ['project'], + ); + request.project = defaultValue1; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? ''}`; + const expectedResponse = [ + [ + 'tuple_key_1', + generateSampleMessage( + new protos.google.cloud.compute.v1.AddressesScopedList(), + ), + ], + [ + 'tuple_key_2', + generateSampleMessage( + new protos.google.cloud.compute.v1.AddressesScopedList(), + ), + ], + [ + 'tuple_key_3', + generateSampleMessage( + new protos.google.cloud.compute.v1.AddressesScopedList(), + ), + ], + ]; + client.descriptors.page.aggregatedList.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: Array< + [string, protos.google.cloud.compute.v1.IAddressesScopedList] + > = []; + const iterable = client.aggregatedListAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.aggregatedList.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.aggregatedList.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('invokes listStream without error', async () => { - const client = new addressesModule.v1.AddressesClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.compute.v1.ListAddressesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.compute.v1.ListAddressesRequest', ['project']); - request.project = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.compute.v1.ListAddressesRequest', ['region']); - request.region = defaultValue2; - const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }®ion=${defaultValue2 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.compute.v1.Address()), - generateSampleMessage(new protos.google.cloud.compute.v1.Address()), - generateSampleMessage(new protos.google.cloud.compute.v1.Address()), - ]; - client.descriptors.page.list.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.cloud.compute.v1.Address[] = []; - stream.on('data', (response: protos.google.cloud.compute.v1.Address) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.list.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.list, request)); - assert( - (client.descriptors.page.list.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with aggregatedList with error', async () => { + const client = new addressesModule.v1.AddressesClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1.AggregatedListAddressesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.compute.v1.AggregatedListAddressesRequest', + ['project'], + ); + request.project = defaultValue1; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.aggregatedList.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.aggregatedListAsync(request); + await assert.rejects(async () => { + const responses: Array< + [string, protos.google.cloud.compute.v1.IAddressesScopedList] + > = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.aggregatedList.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.aggregatedList.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + }); - it('invokes listStream with error', async () => { - const client = new addressesModule.v1.AddressesClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.compute.v1.ListAddressesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.compute.v1.ListAddressesRequest', ['project']); - request.project = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.compute.v1.ListAddressesRequest', ['region']); - request.region = defaultValue2; - const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }®ion=${defaultValue2 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.list.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.cloud.compute.v1.Address[] = []; - stream.on('data', (response: protos.google.cloud.compute.v1.Address) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.list.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.list, request)); - assert( - (client.descriptors.page.list.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + describe('list', () => { + it('invokes list without error', async () => { + const client = new addressesModule.v1.AddressesClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1.ListAddressesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.compute.v1.ListAddressesRequest', + ['project'], + ); + request.project = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.compute.v1.ListAddressesRequest', + ['region'], + ); + request.region = defaultValue2; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? ''}®ion=${defaultValue2 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.compute.v1.Address()), + generateSampleMessage(new protos.google.cloud.compute.v1.Address()), + generateSampleMessage(new protos.google.cloud.compute.v1.Address()), + ]; + client.innerApiCalls.list = stubSimpleCall(expectedResponse); + const [response] = await client.list(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.list as SinonStub).getCall(0) + .args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.list as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('uses async iteration with list without error', async () => { - const client = new addressesModule.v1.AddressesClient({ - auth: googleAuth, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.compute.v1.ListAddressesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.compute.v1.ListAddressesRequest', ['project']); - request.project = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.compute.v1.ListAddressesRequest', ['region']); - request.region = defaultValue2; - const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }®ion=${defaultValue2 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.compute.v1.Address()), - generateSampleMessage(new protos.google.cloud.compute.v1.Address()), - generateSampleMessage(new protos.google.cloud.compute.v1.Address()), - ]; - client.descriptors.page.list.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.cloud.compute.v1.IAddress[] = []; - const iterable = client.listAsync(request); - for await (const resource of iterable) { - responses.push(resource!); + it('invokes list without error using callback', async () => { + const client = new addressesModule.v1.AddressesClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1.ListAddressesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.compute.v1.ListAddressesRequest', + ['project'], + ); + request.project = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.compute.v1.ListAddressesRequest', + ['region'], + ); + request.region = defaultValue2; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? ''}®ion=${defaultValue2 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.compute.v1.Address()), + generateSampleMessage(new protos.google.cloud.compute.v1.Address()), + generateSampleMessage(new protos.google.cloud.compute.v1.Address()), + ]; + client.innerApiCalls.list = stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.list( + request, + ( + err?: Error | null, + result?: protos.google.cloud.compute.v1.IAddress[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.list.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.list.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.list as SinonStub).getCall(0) + .args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.list as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes list with error', async () => { + const client = new addressesModule.v1.AddressesClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1.ListAddressesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.compute.v1.ListAddressesRequest', + ['project'], + ); + request.project = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.compute.v1.ListAddressesRequest', + ['region'], + ); + request.region = defaultValue2; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? ''}®ion=${defaultValue2 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.list = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.list(request), expectedError); + const actualRequest = (client.innerApiCalls.list as SinonStub).getCall(0) + .args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.list as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listStream without error', async () => { + const client = new addressesModule.v1.AddressesClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1.ListAddressesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.compute.v1.ListAddressesRequest', + ['project'], + ); + request.project = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.compute.v1.ListAddressesRequest', + ['region'], + ); + request.region = defaultValue2; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? ''}®ion=${defaultValue2 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.compute.v1.Address()), + generateSampleMessage(new protos.google.cloud.compute.v1.Address()), + generateSampleMessage(new protos.google.cloud.compute.v1.Address()), + ]; + client.descriptors.page.list.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.cloud.compute.v1.Address[] = []; + stream.on( + 'data', + (response: protos.google.cloud.compute.v1.Address) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.list.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.list, request), + ); + assert( + (client.descriptors.page.list.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('uses async iteration with list with error', async () => { - const client = new addressesModule.v1.AddressesClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.compute.v1.ListAddressesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.compute.v1.ListAddressesRequest', ['project']); - request.project = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.compute.v1.ListAddressesRequest', ['region']); - request.region = defaultValue2; - const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }®ion=${defaultValue2 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.list.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listAsync(request); - await assert.rejects(async () => { - const responses: protos.google.cloud.compute.v1.IAddress[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.list.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.list.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); + it('invokes listStream with error', async () => { + const client = new addressesModule.v1.AddressesClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1.ListAddressesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.compute.v1.ListAddressesRequest', + ['project'], + ); + request.project = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.compute.v1.ListAddressesRequest', + ['region'], + ); + request.region = defaultValue2; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? ''}®ion=${defaultValue2 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.list.createStream = stubPageStreamingCall( + undefined, + expectedError, + ); + const stream = client.listStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.cloud.compute.v1.Address[] = []; + stream.on( + 'data', + (response: protos.google.cloud.compute.v1.Address) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.list.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.list, request), + ); + assert( + (client.descriptors.page.list.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + + it('uses async iteration with list without error', async () => { + const client = new addressesModule.v1.AddressesClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1.ListAddressesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.compute.v1.ListAddressesRequest', + ['project'], + ); + request.project = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.compute.v1.ListAddressesRequest', + ['region'], + ); + request.region = defaultValue2; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? ''}®ion=${defaultValue2 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.compute.v1.Address()), + generateSampleMessage(new protos.google.cloud.compute.v1.Address()), + generateSampleMessage(new protos.google.cloud.compute.v1.Address()), + ]; + client.descriptors.page.list.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.cloud.compute.v1.IAddress[] = []; + const iterable = client.listAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + (client.descriptors.page.list.asyncIterate as SinonStub).getCall(0) + .args[1], + request, + ); + assert( + (client.descriptors.page.list.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); }); + + it('uses async iteration with list with error', async () => { + const client = new addressesModule.v1.AddressesClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1.ListAddressesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.compute.v1.ListAddressesRequest', + ['project'], + ); + request.project = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.compute.v1.ListAddressesRequest', + ['region'], + ); + request.region = defaultValue2; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? ''}®ion=${defaultValue2 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.list.asyncIterate = stubAsyncIterationCall( + undefined, + expectedError, + ); + const iterable = client.listAsync(request); + await assert.rejects(async () => { + const responses: protos.google.cloud.compute.v1.IAddress[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + (client.descriptors.page.list.asyncIterate as SinonStub).getCall(0) + .args[1], + request, + ); + assert( + (client.descriptors.page.list.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + }); }); diff --git a/core/generator/gapic-generator-typescript/baselines/compute/test/gapic_region_operations_v1.ts.baseline b/core/generator/gapic-generator-typescript/baselines/compute/test/gapic_region_operations_v1.ts.baseline index 1315afcae7c4..f4def01afc2a 100644 --- a/core/generator/gapic-generator-typescript/baselines/compute/test/gapic_region_operations_v1.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/compute/test/gapic_region_operations_v1.ts.baseline @@ -19,37 +19,49 @@ import * as protos from '../protos/protos'; import * as assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it, beforeEach, afterEach} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it, beforeEach, afterEach } from 'mocha'; import * as regionoperationsModule from '../src'; -import {GoogleAuth, protobuf} from 'google-gax'; +import { GoogleAuth, protobuf } from 'google-gax'; // Dynamically loaded proto JSON is needed to get the type information // to fill in default values for request objects -const root = protobuf.Root.fromJSON(require('../protos/protos.json')).resolveAll(); +const root = protobuf.Root.fromJSON( + require('../protos/protos.json'), +).resolveAll(); // eslint-disable-next-line @typescript-eslint/no-unused-vars function getTypeDefaultValue(typeName: string, fields: string[]) { - let type = root.lookupType(typeName) as protobuf.Type; - for (const field of fields.slice(0, -1)) { - type = type.fields[field]?.resolvedType as protobuf.Type; - } - return type.fields[fields[fields.length - 1]]?.defaultValue; + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type.fields[field]?.resolvedType as protobuf.Type; + } + return type.fields[fields[fields.length - 1]]?.defaultValue; } function generateSampleMessage(instance: T) { - const filledObject = (instance.constructor as typeof protobuf.Message) - .toObject(instance as protobuf.Message, {defaults: true}); - return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, { defaults: true }); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; } function stubSimpleCall(response?: ResponseType, error?: Error) { - return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); } -function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { - return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +function stubSimpleCallWithCallback( + response?: ResponseType, + error?: Error, +) { + return error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); } describe('v1.RegionOperationsClient', () => { @@ -57,433 +69,531 @@ describe('v1.RegionOperationsClient', () => { beforeEach(() => { googleAuth = { getClient: sinon.stub().resolves({ - getRequestHeaders: sinon.stub().resolves({Authorization: 'Bearer SOME_TOKEN'}), - }) + getRequestHeaders: sinon + .stub() + .resolves({ Authorization: 'Bearer SOME_TOKEN' }), + }), } as unknown as GoogleAuth; }); afterEach(() => { sinon.restore(); }); - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new regionoperationsModule.v1.RegionOperationsClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'compute.googleapis.com'); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new regionoperationsModule.v1.RegionOperationsClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'compute.googleapis.com'); + }); - it('has universeDomain', () => { - const client = new regionoperationsModule.v1.RegionOperationsClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); + it('has universeDomain', () => { + const client = new regionoperationsModule.v1.RegionOperationsClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - it('throws DeprecationWarning if static servicePath is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const servicePath = regionoperationsModule.v1.RegionOperationsClient.servicePath; - assert.strictEqual(servicePath, 'compute.googleapis.com'); - assert(stub.called); - stub.restore(); - }); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = + regionoperationsModule.v1.RegionOperationsClient.servicePath; + assert.strictEqual(servicePath, 'compute.googleapis.com'); + assert(stub.called); + stub.restore(); + }); - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = regionoperationsModule.v1.RegionOperationsClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'compute.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new regionoperationsModule.v1.RegionOperationsClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'compute.example.com'); - }); - - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new regionoperationsModule.v1.RegionOperationsClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'compute.example.com'); - }); + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + regionoperationsModule.v1.RegionOperationsClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'compute.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = new regionoperationsModule.v1.RegionOperationsClient({ + universeDomain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'compute.example.com'); + }); - if (typeof process === 'object' && 'env' in process) { - describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { - it('sets apiEndpoint from environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new regionoperationsModule.v1.RegionOperationsClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'compute.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = new regionoperationsModule.v1.RegionOperationsClient({ + universe_domain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'compute.example.com'); + }); - it('value configured in code has priority over environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new regionoperationsModule.v1.RegionOperationsClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'compute.configured.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { new regionoperationsModule.v1.RegionOperationsClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); + if (typeof process === 'object' && 'env' in process) { + describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { + it('sets apiEndpoint from environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new regionoperationsModule.v1.RegionOperationsClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'compute.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - it('has port', () => { - const port = regionoperationsModule.v1.RegionOperationsClient.port; - assert(port); - assert(typeof port === 'number'); + it('value configured in code has priority over environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new regionoperationsModule.v1.RegionOperationsClient({ + universeDomain: 'configured.example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'compute.configured.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - - it('should create a client with no option', () => { - const client = new regionoperationsModule.v1.RegionOperationsClient(); - assert(client); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new regionoperationsModule.v1.RegionOperationsClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); + }); - it('should create a client with gRPC fallback', () => { - const client = new regionoperationsModule.v1.RegionOperationsClient({ - fallback: true, - }); - assert(client); - }); + it('has port', () => { + const port = regionoperationsModule.v1.RegionOperationsClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('has initialize method and supports deferred initialization', async () => { - const client = new regionoperationsModule.v1.RegionOperationsClient({ - auth: googleAuth, - projectId: 'bogus', - }); - assert.strictEqual(client.regionOperationsStub, undefined); - await client.initialize(); - assert(client.regionOperationsStub); - }); + it('should create a client with no option', () => { + const client = new regionoperationsModule.v1.RegionOperationsClient(); + assert(client); + }); - it('has close method for the initialized client', done => { - const client = new regionoperationsModule.v1.RegionOperationsClient({ - auth: googleAuth, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.regionOperationsStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('should create a client with gRPC fallback', () => { + const client = new regionoperationsModule.v1.RegionOperationsClient({ + fallback: true, + }); + assert(client); + }); - it('has close method for the non-initialized client', done => { - const client = new regionoperationsModule.v1.RegionOperationsClient({ - auth: googleAuth, - projectId: 'bogus', - }); - assert.strictEqual(client.regionOperationsStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('has initialize method and supports deferred initialization', async () => { + const client = new regionoperationsModule.v1.RegionOperationsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + assert.strictEqual(client.regionOperationsStub, undefined); + await client.initialize(); + assert(client.regionOperationsStub); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new regionoperationsModule.v1.RegionOperationsClient({ - auth: googleAuth, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + it('has close method for the initialized client', (done) => { + const client = new regionoperationsModule.v1.RegionOperationsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.regionOperationsStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new regionoperationsModule.v1.RegionOperationsClient({ - auth: googleAuth, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId((err?: Error|null, projectId?: string|null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } - }); - }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); + it('has close method for the non-initialized client', (done) => { + const client = new regionoperationsModule.v1.RegionOperationsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + assert.strictEqual(client.regionOperationsStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); }); - describe('get', () => { - it('invokes get without error', async () => { - const client = new regionoperationsModule.v1.RegionOperationsClient({ - auth: googleAuth, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.compute.v1.GetRegionOperationRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.compute.v1.GetRegionOperationRequest', ['project']); - request.project = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.compute.v1.GetRegionOperationRequest', ['region']); - request.region = defaultValue2; - const defaultValue3 = - getTypeDefaultValue('.google.cloud.compute.v1.GetRegionOperationRequest', ['operation']); - request.operation = defaultValue3; - const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }®ion=${defaultValue2 ?? '' }&operation=${defaultValue3 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.compute.v1.Operation() - ); - client.innerApiCalls.get = stubSimpleCall(expectedResponse); - const [response] = await client.get(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.get as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.get as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new regionoperationsModule.v1.RegionOperationsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + }); - it('invokes get without error using callback', async () => { - const client = new regionoperationsModule.v1.RegionOperationsClient({ - auth: googleAuth, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.compute.v1.GetRegionOperationRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.compute.v1.GetRegionOperationRequest', ['project']); - request.project = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.compute.v1.GetRegionOperationRequest', ['region']); - request.region = defaultValue2; - const defaultValue3 = - getTypeDefaultValue('.google.cloud.compute.v1.GetRegionOperationRequest', ['operation']); - request.operation = defaultValue3; - const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }®ion=${defaultValue2 ?? '' }&operation=${defaultValue3 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.compute.v1.Operation() - ); - client.innerApiCalls.get = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.get( - request, - (err?: Error|null, result?: protos.google.cloud.compute.v1.IOperation|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.get as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.get as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new regionoperationsModule.v1.RegionOperationsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + }); - it('invokes get with error', async () => { - const client = new regionoperationsModule.v1.RegionOperationsClient({ - auth: googleAuth, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.compute.v1.GetRegionOperationRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.compute.v1.GetRegionOperationRequest', ['project']); - request.project = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.compute.v1.GetRegionOperationRequest', ['region']); - request.region = defaultValue2; - const defaultValue3 = - getTypeDefaultValue('.google.cloud.compute.v1.GetRegionOperationRequest', ['operation']); - request.operation = defaultValue3; - const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }®ion=${defaultValue2 ?? '' }&operation=${defaultValue3 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.get = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.get(request), expectedError); - const actualRequest = (client.innerApiCalls.get as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.get as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + describe('get', () => { + it('invokes get without error', async () => { + const client = new regionoperationsModule.v1.RegionOperationsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1.GetRegionOperationRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.compute.v1.GetRegionOperationRequest', + ['project'], + ); + request.project = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.compute.v1.GetRegionOperationRequest', + ['region'], + ); + request.region = defaultValue2; + const defaultValue3 = getTypeDefaultValue( + '.google.cloud.compute.v1.GetRegionOperationRequest', + ['operation'], + ); + request.operation = defaultValue3; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? ''}®ion=${defaultValue2 ?? ''}&operation=${defaultValue3 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.compute.v1.Operation(), + ); + client.innerApiCalls.get = stubSimpleCall(expectedResponse); + const [response] = await client.get(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.get as SinonStub).getCall(0) + .args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.get as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes get with closed client', async () => { - const client = new regionoperationsModule.v1.RegionOperationsClient({ - auth: googleAuth, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.compute.v1.GetRegionOperationRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.compute.v1.GetRegionOperationRequest', ['project']); - request.project = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.compute.v1.GetRegionOperationRequest', ['region']); - request.region = defaultValue2; - const defaultValue3 = - getTypeDefaultValue('.google.cloud.compute.v1.GetRegionOperationRequest', ['operation']); - request.operation = defaultValue3; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.get(request), expectedError); - }); + it('invokes get without error using callback', async () => { + const client = new regionoperationsModule.v1.RegionOperationsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1.GetRegionOperationRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.compute.v1.GetRegionOperationRequest', + ['project'], + ); + request.project = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.compute.v1.GetRegionOperationRequest', + ['region'], + ); + request.region = defaultValue2; + const defaultValue3 = getTypeDefaultValue( + '.google.cloud.compute.v1.GetRegionOperationRequest', + ['operation'], + ); + request.operation = defaultValue3; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? ''}®ion=${defaultValue2 ?? ''}&operation=${defaultValue3 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.compute.v1.Operation(), + ); + client.innerApiCalls.get = stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.get( + request, + ( + err?: Error | null, + result?: protos.google.cloud.compute.v1.IOperation | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.get as SinonStub).getCall(0) + .args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.get as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('wait', () => { - it('invokes wait without error', async () => { - const client = new regionoperationsModule.v1.RegionOperationsClient({ - auth: googleAuth, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.compute.v1.WaitRegionOperationRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.compute.v1.WaitRegionOperationRequest', ['project']); - request.project = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.compute.v1.WaitRegionOperationRequest', ['region']); - request.region = defaultValue2; - const defaultValue3 = - getTypeDefaultValue('.google.cloud.compute.v1.WaitRegionOperationRequest', ['operation']); - request.operation = defaultValue3; - const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }®ion=${defaultValue2 ?? '' }&operation=${defaultValue3 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.compute.v1.Operation() - ); - client.innerApiCalls.wait = stubSimpleCall(expectedResponse); - const [response] = await client.wait(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.wait as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.wait as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes get with error', async () => { + const client = new regionoperationsModule.v1.RegionOperationsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1.GetRegionOperationRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.compute.v1.GetRegionOperationRequest', + ['project'], + ); + request.project = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.compute.v1.GetRegionOperationRequest', + ['region'], + ); + request.region = defaultValue2; + const defaultValue3 = getTypeDefaultValue( + '.google.cloud.compute.v1.GetRegionOperationRequest', + ['operation'], + ); + request.operation = defaultValue3; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? ''}®ion=${defaultValue2 ?? ''}&operation=${defaultValue3 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.get = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.get(request), expectedError); + const actualRequest = (client.innerApiCalls.get as SinonStub).getCall(0) + .args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.get as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes wait without error using callback', async () => { - const client = new regionoperationsModule.v1.RegionOperationsClient({ - auth: googleAuth, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.compute.v1.WaitRegionOperationRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.compute.v1.WaitRegionOperationRequest', ['project']); - request.project = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.compute.v1.WaitRegionOperationRequest', ['region']); - request.region = defaultValue2; - const defaultValue3 = - getTypeDefaultValue('.google.cloud.compute.v1.WaitRegionOperationRequest', ['operation']); - request.operation = defaultValue3; - const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }®ion=${defaultValue2 ?? '' }&operation=${defaultValue3 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.compute.v1.Operation() - ); - client.innerApiCalls.wait = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.wait( - request, - (err?: Error|null, result?: protos.google.cloud.compute.v1.IOperation|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.wait as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.wait as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes get with closed client', async () => { + const client = new regionoperationsModule.v1.RegionOperationsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1.GetRegionOperationRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.compute.v1.GetRegionOperationRequest', + ['project'], + ); + request.project = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.compute.v1.GetRegionOperationRequest', + ['region'], + ); + request.region = defaultValue2; + const defaultValue3 = getTypeDefaultValue( + '.google.cloud.compute.v1.GetRegionOperationRequest', + ['operation'], + ); + request.operation = defaultValue3; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.get(request), expectedError); + }); + }); - it('invokes wait with error', async () => { - const client = new regionoperationsModule.v1.RegionOperationsClient({ - auth: googleAuth, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.compute.v1.WaitRegionOperationRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.compute.v1.WaitRegionOperationRequest', ['project']); - request.project = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.compute.v1.WaitRegionOperationRequest', ['region']); - request.region = defaultValue2; - const defaultValue3 = - getTypeDefaultValue('.google.cloud.compute.v1.WaitRegionOperationRequest', ['operation']); - request.operation = defaultValue3; - const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }®ion=${defaultValue2 ?? '' }&operation=${defaultValue3 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.wait = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.wait(request), expectedError); - const actualRequest = (client.innerApiCalls.wait as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.wait as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + describe('wait', () => { + it('invokes wait without error', async () => { + const client = new regionoperationsModule.v1.RegionOperationsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1.WaitRegionOperationRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.compute.v1.WaitRegionOperationRequest', + ['project'], + ); + request.project = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.compute.v1.WaitRegionOperationRequest', + ['region'], + ); + request.region = defaultValue2; + const defaultValue3 = getTypeDefaultValue( + '.google.cloud.compute.v1.WaitRegionOperationRequest', + ['operation'], + ); + request.operation = defaultValue3; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? ''}®ion=${defaultValue2 ?? ''}&operation=${defaultValue3 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.compute.v1.Operation(), + ); + client.innerApiCalls.wait = stubSimpleCall(expectedResponse); + const [response] = await client.wait(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.wait as SinonStub).getCall(0) + .args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.wait as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes wait with closed client', async () => { - const client = new regionoperationsModule.v1.RegionOperationsClient({ - auth: googleAuth, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.compute.v1.WaitRegionOperationRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.compute.v1.WaitRegionOperationRequest', ['project']); - request.project = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.cloud.compute.v1.WaitRegionOperationRequest', ['region']); - request.region = defaultValue2; - const defaultValue3 = - getTypeDefaultValue('.google.cloud.compute.v1.WaitRegionOperationRequest', ['operation']); - request.operation = defaultValue3; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.wait(request), expectedError); - }); + it('invokes wait without error using callback', async () => { + const client = new regionoperationsModule.v1.RegionOperationsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1.WaitRegionOperationRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.compute.v1.WaitRegionOperationRequest', + ['project'], + ); + request.project = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.compute.v1.WaitRegionOperationRequest', + ['region'], + ); + request.region = defaultValue2; + const defaultValue3 = getTypeDefaultValue( + '.google.cloud.compute.v1.WaitRegionOperationRequest', + ['operation'], + ); + request.operation = defaultValue3; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? ''}®ion=${defaultValue2 ?? ''}&operation=${defaultValue3 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.compute.v1.Operation(), + ); + client.innerApiCalls.wait = stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.wait( + request, + ( + err?: Error | null, + result?: protos.google.cloud.compute.v1.IOperation | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.wait as SinonStub).getCall(0) + .args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.wait as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); + + it('invokes wait with error', async () => { + const client = new regionoperationsModule.v1.RegionOperationsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1.WaitRegionOperationRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.compute.v1.WaitRegionOperationRequest', + ['project'], + ); + request.project = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.compute.v1.WaitRegionOperationRequest', + ['region'], + ); + request.region = defaultValue2; + const defaultValue3 = getTypeDefaultValue( + '.google.cloud.compute.v1.WaitRegionOperationRequest', + ['operation'], + ); + request.operation = defaultValue3; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? ''}®ion=${defaultValue2 ?? ''}&operation=${defaultValue3 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.wait = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.wait(request), expectedError); + const actualRequest = (client.innerApiCalls.wait as SinonStub).getCall(0) + .args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.wait as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes wait with closed client', async () => { + const client = new regionoperationsModule.v1.RegionOperationsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1.WaitRegionOperationRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.compute.v1.WaitRegionOperationRequest', + ['project'], + ); + request.project = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.cloud.compute.v1.WaitRegionOperationRequest', + ['region'], + ); + request.region = defaultValue2; + const defaultValue3 = getTypeDefaultValue( + '.google.cloud.compute.v1.WaitRegionOperationRequest', + ['operation'], + ); + request.operation = defaultValue3; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.wait(request), expectedError); + }); + }); }); diff --git a/core/generator/gapic-generator-typescript/baselines/deprecatedtest-esm/esm/src/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/deprecatedtest-esm/esm/src/index.ts.baseline index 3f8b8154d178..43fc9124896a 100644 --- a/core/generator/gapic-generator-typescript/baselines/deprecatedtest-esm/esm/src/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/deprecatedtest-esm/esm/src/index.ts.baseline @@ -19,8 +19,8 @@ import * as v1 from './v1/index.js'; const DeprecatedServiceClient = v1.DeprecatedServiceClient; type DeprecatedServiceClient = v1.DeprecatedServiceClient; -export {v1, DeprecatedServiceClient}; -export default {v1, DeprecatedServiceClient}; +export { v1, DeprecatedServiceClient }; +export default { v1, DeprecatedServiceClient }; // @ts-ignore import * as protos from '../../protos/protos.js'; -export {protos} +export { protos }; diff --git a/core/generator/gapic-generator-typescript/baselines/deprecatedtest-esm/esm/src/v1/deprecated_service_client.ts.baseline b/core/generator/gapic-generator-typescript/baselines/deprecatedtest-esm/esm/src/v1/deprecated_service_client.ts.baseline index abbf771ffe6c..a80d7b2efcc8 100644 --- a/core/generator/gapic-generator-typescript/baselines/deprecatedtest-esm/esm/src/v1/deprecated_service_client.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/deprecatedtest-esm/esm/src/v1/deprecated_service_client.ts.baseline @@ -18,15 +18,20 @@ /* global window */ import * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions} from 'google-gax'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, +} from 'google-gax'; // @ts-ignore import type * as protos from '../../../protos/protos.js'; import * as deprecated_service_client_config from './deprecated_service_client_config.json'; import fs from 'fs'; import path from 'path'; -import {fileURLToPath} from 'url'; -import {getJSON} from '../json-helper.cjs'; +import { fileURLToPath } from 'url'; +import { getJSON } from '../json-helper.cjs'; // @ts-ignore const dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -36,15 +41,15 @@ const dirname = path.dirname(fileURLToPath(import.meta.url)); * This file defines retry strategy and timeouts for all API methods in this library. */ const gapicConfig = getJSON( - path.join(dirname, 'deprecated_service_client_config.json') + path.join(dirname, 'deprecated_service_client_config.json'), ); const jsonProtos = getJSON( - path.join(dirname, '..', '..', '..', 'protos/protos.json') + path.join(dirname, '..', '..', '..', 'protos/protos.json'), ); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; const version = getJSON( - path.join(dirname, '..', '..', '..', '..', 'package.json') + path.join(dirname, '..', '..', '..', '..', 'package.json'), ).version; /** @@ -61,7 +66,7 @@ export class DeprecatedServiceClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('deprecatedtest'); @@ -73,8 +78,8 @@ export class DeprecatedServiceClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - deprecatedServiceStub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + deprecatedServiceStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of DeprecatedServiceClient. @@ -116,21 +121,42 @@ export class DeprecatedServiceClient { * const client = new DeprecatedServiceClient({fallback: 'rest'}, gax); * ``` */ - constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { // Ensure that options include all the required fields. const staticMembers = this.constructor as typeof DeprecatedServiceClient; - if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { - throw new Error('Please set either universe_domain or universeDomain, but not both.'); + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); } - const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; - this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; this._servicePath = 'localhost'; - const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; - const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. if (servicePath !== this._servicePath && !('scopes' in opts)) { @@ -152,7 +178,7 @@ export class DeprecatedServiceClient { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; @@ -169,10 +195,7 @@ export class DeprecatedServiceClient { const isEsm = true; const isEsmString = isEsm ? '-esm' : '-cjs'; // Determine the client header string. - const clientHeader = [ - `gax/${this._gaxModule.version}`, - `gapic/${version}`, - ]; + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/{process.versions.node}${isEsmString}`); } else { @@ -180,7 +203,7 @@ export class DeprecatedServiceClient { } if (!opts.fallback) { clientHeader.push(`grpc/${this._gaxGrpc.grpcVersion}`); - } else if (opts.fallback === 'rest' ) { + } else if (opts.fallback === 'rest') { clientHeader.push(`rest/${this._gaxGrpc.grpcVersion}`); } if (opts.libName && opts.libVersion) { @@ -188,12 +211,17 @@ export class DeprecatedServiceClient { } // Load the applicable protos. - this._protos = this._gaxGrpc.loadProtoJSON(jsonProtos as gax.protobuf.INamespace); + this._protos = this._gaxGrpc.loadProtoJSON( + jsonProtos as gax.protobuf.INamespace, + ); // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.deprecatedtest.v1.DeprecatedService', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.deprecatedtest.v1.DeprecatedService', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + { 'x-goog-api-client': clientHeader.join(' ') }, + ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -218,48 +246,60 @@ export class DeprecatedServiceClient { initialize() { // If the client stub promise is already initialized, return immediately. if (this.deprecatedServiceStub) { - this.warn('DEP$DeprecatedService', 'DeprecatedService is deprecated and may be removed in a future version.', 'DeprecationWarning'); + this.warn( + 'DEP$DeprecatedService', + 'DeprecatedService is deprecated and may be removed in a future version.', + 'DeprecationWarning', + ); return this.deprecatedServiceStub; } // Put together the "service stub" for // google.deprecatedtest.v1.DeprecatedService. this.deprecatedServiceStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.deprecatedtest.v1.DeprecatedService') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.deprecatedtest.v1.DeprecatedService', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.deprecatedtest.v1.DeprecatedService, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts, + this._providedCustomServicePath, + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const deprecatedServiceStubMethods = - ['fastFibonacci', 'slowFibonacci']; + const deprecatedServiceStubMethods = ['fastFibonacci', 'slowFibonacci']; for (const methodName of deprecatedServiceStubMethods) { const callPromise = this.deprecatedServiceStub.then( - stub => (...args: Array<{}>) => { - if (this._terminated) { - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error|null|undefined) => () => { + (stub) => + (...args: Array<{}>) => { + if (this._terminated) { + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { throw err; - }); + }, + ); - const descriptor = - undefined; + const descriptor = undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; } - this.warn('DEP$DeprecatedService', 'DeprecatedService is deprecated and may be removed in a future version.', 'DeprecationWarning'); + this.warn( + 'DEP$DeprecatedService', + 'DeprecatedService is deprecated and may be removed in a future version.', + 'DeprecationWarning', + ); return this.deprecatedServiceStub; } @@ -270,8 +310,14 @@ export class DeprecatedServiceClient { * @returns {string} The DNS address for this service. */ static get servicePath() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'localhost'; } @@ -283,8 +329,14 @@ export class DeprecatedServiceClient { * @returns {string} The DNS address for this service. */ static get apiEndpoint() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'localhost'; } @@ -315,9 +367,7 @@ export class DeprecatedServiceClient { * @returns {string[]} List of default scopes. */ static get scopes() { - return [ - 'https://www.googleapis.com/auth/cloud-platform' - ]; + return ['https://www.googleapis.com/auth/cloud-platform']; } getProjectId(): Promise; @@ -326,8 +376,9 @@ export class DeprecatedServiceClient { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId(callback?: Callback): - Promise|void { + getProjectId( + callback?: Callback, + ): Promise | void { if (callback) { this.auth.getProjectId(callback); return; @@ -338,186 +389,253 @@ export class DeprecatedServiceClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Calculates Fibonacci on the provided value, quickly. - * - * @param {Object} request - * The request object that will be sent. - * @param {number} request.value - * The nth term to retrieve in the Fibonacci sequence. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1/deprecated_service.fast_fibonacci.js - * region_tag:localhost_v1_generated_DeprecatedService_FastFibonacci_async - */ + /** + * Calculates Fibonacci on the provided value, quickly. + * + * @param {Object} request + * The request object that will be sent. + * @param {number} request.value + * The nth term to retrieve in the Fibonacci sequence. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/deprecated_service.fast_fibonacci.js + * region_tag:localhost_v1_generated_DeprecatedService_FastFibonacci_async + */ fastFibonacci( - request?: protos.google.deprecatedtest.v1.IFibonacciRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.deprecatedtest.v1.IFibonacciRequest|undefined, {}|undefined - ]>; + request?: protos.google.deprecatedtest.v1.IFibonacciRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.deprecatedtest.v1.IFibonacciRequest | undefined, + {} | undefined, + ] + >; fastFibonacci( - request: protos.google.deprecatedtest.v1.IFibonacciRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.deprecatedtest.v1.IFibonacciRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.deprecatedtest.v1.IFibonacciRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.deprecatedtest.v1.IFibonacciRequest | null | undefined, + {} | null | undefined + >, + ): void; fastFibonacci( - request: protos.google.deprecatedtest.v1.IFibonacciRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.deprecatedtest.v1.IFibonacciRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.deprecatedtest.v1.IFibonacciRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.deprecatedtest.v1.IFibonacciRequest | null | undefined, + {} | null | undefined + >, + ): void; fastFibonacci( - request?: protos.google.deprecatedtest.v1.IFibonacciRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.deprecatedtest.v1.IFibonacciRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.deprecatedtest.v1.IFibonacciRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.protobuf.IEmpty, - protos.google.deprecatedtest.v1.IFibonacciRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.deprecatedtest.v1.IFibonacciRequest|undefined, {}|undefined - ]>|void { + protos.google.deprecatedtest.v1.IFibonacciRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + protos.google.deprecatedtest.v1.IFibonacciRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.deprecatedtest.v1.IFibonacciRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('fastFibonacci request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.deprecatedtest.v1.IFibonacciRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + protos.google.deprecatedtest.v1.IFibonacciRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('fastFibonacci response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.fastFibonacci(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.deprecatedtest.v1.IFibonacciRequest|undefined, {}|undefined - ]) => { - this._log.info('fastFibonacci response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .fastFibonacci(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.deprecatedtest.v1.IFibonacciRequest | undefined, + {} | undefined, + ]) => { + this._log.info('fastFibonacci response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Calculates Fibonacci on the provided value, slowly. - * - * @param {Object} request - * The request object that will be sent. - * @param {number} request.value - * The nth term to retrieve in the Fibonacci sequence. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1/deprecated_service.slow_fibonacci.js - * region_tag:localhost_v1_generated_DeprecatedService_SlowFibonacci_async - * @deprecated SlowFibonacci is deprecated and may be removed in a future version. - */ + /** + * Calculates Fibonacci on the provided value, slowly. + * + * @param {Object} request + * The request object that will be sent. + * @param {number} request.value + * The nth term to retrieve in the Fibonacci sequence. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/deprecated_service.slow_fibonacci.js + * region_tag:localhost_v1_generated_DeprecatedService_SlowFibonacci_async + * @deprecated SlowFibonacci is deprecated and may be removed in a future version. + */ slowFibonacci( - request?: protos.google.deprecatedtest.v1.IFibonacciRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.deprecatedtest.v1.IFibonacciRequest|undefined, {}|undefined - ]>; + request?: protos.google.deprecatedtest.v1.IFibonacciRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.deprecatedtest.v1.IFibonacciRequest | undefined, + {} | undefined, + ] + >; slowFibonacci( - request: protos.google.deprecatedtest.v1.IFibonacciRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.deprecatedtest.v1.IFibonacciRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.deprecatedtest.v1.IFibonacciRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.deprecatedtest.v1.IFibonacciRequest | null | undefined, + {} | null | undefined + >, + ): void; slowFibonacci( - request: protos.google.deprecatedtest.v1.IFibonacciRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.deprecatedtest.v1.IFibonacciRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.deprecatedtest.v1.IFibonacciRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.deprecatedtest.v1.IFibonacciRequest | null | undefined, + {} | null | undefined + >, + ): void; slowFibonacci( - request?: protos.google.deprecatedtest.v1.IFibonacciRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.protobuf.IEmpty, - protos.google.deprecatedtest.v1.IFibonacciRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.deprecatedtest.v1.IFibonacciRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.deprecatedtest.v1.IFibonacciRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.deprecatedtest.v1.IFibonacciRequest|undefined, {}|undefined - ]>|void { + protos.google.deprecatedtest.v1.IFibonacciRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + protos.google.deprecatedtest.v1.IFibonacciRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.deprecatedtest.v1.IFibonacciRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize().catch(err => {throw err}); - this.warn('DEP$DeprecatedService-$SlowFibonacci','SlowFibonacci is deprecated and may be removed in a future version.', 'DeprecationWarning'); + this.initialize().catch((err) => { + throw err; + }); + this.warn( + 'DEP$DeprecatedService-$SlowFibonacci', + 'SlowFibonacci is deprecated and may be removed in a future version.', + 'DeprecationWarning', + ); this._log.info('slowFibonacci request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.deprecatedtest.v1.IFibonacciRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + protos.google.deprecatedtest.v1.IFibonacciRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('slowFibonacci response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.slowFibonacci(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.deprecatedtest.v1.IFibonacciRequest|undefined, {}|undefined - ]) => { - this._log.info('slowFibonacci response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .slowFibonacci(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.deprecatedtest.v1.IFibonacciRequest | undefined, + {} | undefined, + ]) => { + this._log.info('slowFibonacci response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } - /** * Terminate the gRPC channel and close the client. * @@ -526,7 +644,7 @@ export class DeprecatedServiceClient { */ close(): Promise { if (this.deprecatedServiceStub && !this._terminated) { - return this.deprecatedServiceStub.then(stub => { + return this.deprecatedServiceStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -534,4 +652,4 @@ export class DeprecatedServiceClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/core/generator/gapic-generator-typescript/baselines/deprecatedtest-esm/esm/src/v1/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/deprecatedtest-esm/esm/src/v1/index.ts.baseline index 91d195e31d85..8b7946fb1da7 100644 --- a/core/generator/gapic-generator-typescript/baselines/deprecatedtest-esm/esm/src/v1/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/deprecatedtest-esm/esm/src/v1/index.ts.baseline @@ -16,4 +16,4 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -export {DeprecatedServiceClient} from './deprecated_service_client.js'; +export { DeprecatedServiceClient } from './deprecated_service_client.js'; diff --git a/core/generator/gapic-generator-typescript/baselines/deprecatedtest-esm/esm/system-test/fixtures/sample/src/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/deprecatedtest-esm/esm/system-test/fixtures/sample/src/index.ts.baseline index 8ba7f01cacbd..fe377e8b3457 100644 --- a/core/generator/gapic-generator-typescript/baselines/deprecatedtest-esm/esm/system-test/fixtures/sample/src/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/deprecatedtest-esm/esm/system-test/fixtures/sample/src/index.ts.baseline @@ -17,7 +17,7 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -import {DeprecatedServiceClient} from 'deprecatedtest'; +import { DeprecatedServiceClient } from 'deprecatedtest'; // check that the client class type name can be used function doStuffWithDeprecatedServiceClient(client: DeprecatedServiceClient) { diff --git a/core/generator/gapic-generator-typescript/baselines/deprecatedtest-esm/esm/system-test/install.ts.baseline b/core/generator/gapic-generator-typescript/baselines/deprecatedtest-esm/esm/system-test/install.ts.baseline index e079c4fa1101..d109fdd8c97f 100644 --- a/core/generator/gapic-generator-typescript/baselines/deprecatedtest-esm/esm/system-test/install.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/deprecatedtest-esm/esm/system-test/install.ts.baseline @@ -16,40 +16,45 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -import {packNTest} from 'pack-n-play'; -import {readFileSync} from 'fs'; -import {describe, it} from 'mocha'; +import { packNTest } from 'pack-n-play'; +import { readFileSync } from 'fs'; +import { describe, it } from 'mocha'; describe('📦 pack-n-play test', () => { - it('TypeScript', async function() { + it('TypeScript', async function () { this.timeout(300000); await packNTest({ packageDir: process.cwd(), sample: { description: 'TypeScript user can use the type definitions', - ts: readFileSync('./esm/system-test/fixtures/sample/src/index.ts').toString() - } + ts: readFileSync( + './esm/system-test/fixtures/sample/src/index.ts', + ).toString(), + }, }); }); - it('ESM module', async function() { + it('ESM module', async function () { this.timeout(300000); await packNTest({ sample: { description: 'Should be able to import using ESM', - esm: readFileSync('./esm/system-test/fixtures/sample/src/index.js').toString(), + esm: readFileSync( + './esm/system-test/fixtures/sample/src/index.js', + ).toString(), }, }); }); - it('CJS module', async function() { + it('CJS module', async function () { this.timeout(300000); await packNTest({ sample: { description: 'Should be able to import using CJS', - cjs: readFileSync('./esm/system-test/fixtures/sample/src/index.cjs').toString(), + cjs: readFileSync( + './esm/system-test/fixtures/sample/src/index.cjs', + ).toString(), }, }); }); - }); diff --git a/core/generator/gapic-generator-typescript/baselines/deprecatedtest/src/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/deprecatedtest/src/index.ts.baseline index 304b2110ce96..8fc2e60df54f 100644 --- a/core/generator/gapic-generator-typescript/baselines/deprecatedtest/src/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/deprecatedtest/src/index.ts.baseline @@ -19,7 +19,7 @@ import * as v1 from './v1'; const DeprecatedServiceClient = v1.DeprecatedServiceClient; type DeprecatedServiceClient = v1.DeprecatedServiceClient; -export {v1, DeprecatedServiceClient}; -export default {v1, DeprecatedServiceClient}; +export { v1, DeprecatedServiceClient }; +export default { v1, DeprecatedServiceClient }; import * as protos from '../protos/protos'; -export {protos} +export { protos }; diff --git a/core/generator/gapic-generator-typescript/baselines/deprecatedtest/src/v1/deprecated_service_client.ts.baseline b/core/generator/gapic-generator-typescript/baselines/deprecatedtest/src/v1/deprecated_service_client.ts.baseline index 1592625448ab..af3cd8a56cea 100644 --- a/core/generator/gapic-generator-typescript/baselines/deprecatedtest/src/v1/deprecated_service_client.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/deprecatedtest/src/v1/deprecated_service_client.ts.baseline @@ -18,11 +18,16 @@ /* global window */ import type * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions} from 'google-gax'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, +} from 'google-gax'; import * as protos from '../../protos/protos'; import jsonProtos = require('../../protos/protos.json'); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; /** * Client JSON configuration object, loaded from @@ -46,7 +51,7 @@ export class DeprecatedServiceClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('deprecatedtest'); @@ -59,8 +64,8 @@ export class DeprecatedServiceClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - deprecatedServiceStub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + deprecatedServiceStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of DeprecatedServiceClient. @@ -101,21 +106,42 @@ export class DeprecatedServiceClient { * const client = new DeprecatedServiceClient({fallback: true}, gax); * ``` */ - constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { // Ensure that options include all the required fields. const staticMembers = this.constructor as typeof DeprecatedServiceClient; - if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { - throw new Error('Please set either universe_domain or universeDomain, but not both.'); + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); } - const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; - this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; this._servicePath = 'localhost'; - const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; - const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. if (servicePath !== this._servicePath && !('scopes' in opts)) { @@ -137,7 +163,7 @@ export class DeprecatedServiceClient { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; @@ -151,10 +177,7 @@ export class DeprecatedServiceClient { } // Determine the client header string. - const clientHeader = [ - `gax/${this._gaxModule.version}`, - `gapic/${version}`, - ]; + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/${process.versions.node}`); } else { @@ -173,8 +196,11 @@ export class DeprecatedServiceClient { // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.deprecatedtest.v1.DeprecatedService', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.deprecatedtest.v1.DeprecatedService', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + { 'x-goog-api-client': clientHeader.join(' ') }, + ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -199,48 +225,60 @@ export class DeprecatedServiceClient { initialize() { // If the client stub promise is already initialized, return immediately. if (this.deprecatedServiceStub) { - this.warn('DEP$DeprecatedService', 'DeprecatedService is deprecated and may be removed in a future version.', 'DeprecationWarning'); + this.warn( + 'DEP$DeprecatedService', + 'DeprecatedService is deprecated and may be removed in a future version.', + 'DeprecationWarning', + ); return this.deprecatedServiceStub; } // Put together the "service stub" for // google.deprecatedtest.v1.DeprecatedService. this.deprecatedServiceStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.deprecatedtest.v1.DeprecatedService') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.deprecatedtest.v1.DeprecatedService', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.deprecatedtest.v1.DeprecatedService, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts, + this._providedCustomServicePath, + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const deprecatedServiceStubMethods = - ['fastFibonacci', 'slowFibonacci']; + const deprecatedServiceStubMethods = ['fastFibonacci', 'slowFibonacci']; for (const methodName of deprecatedServiceStubMethods) { const callPromise = this.deprecatedServiceStub.then( - stub => (...args: Array<{}>) => { - if (this._terminated) { - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error|null|undefined) => () => { + (stub) => + (...args: Array<{}>) => { + if (this._terminated) { + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { throw err; - }); + }, + ); - const descriptor = - undefined; + const descriptor = undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; } - this.warn('DEP$DeprecatedService', 'DeprecatedService is deprecated and may be removed in a future version.', 'DeprecationWarning'); + this.warn( + 'DEP$DeprecatedService', + 'DeprecatedService is deprecated and may be removed in a future version.', + 'DeprecationWarning', + ); return this.deprecatedServiceStub; } @@ -251,8 +289,14 @@ export class DeprecatedServiceClient { * @returns {string} The DNS address for this service. */ static get servicePath() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'localhost'; } @@ -263,8 +307,14 @@ export class DeprecatedServiceClient { * @returns {string} The DNS address for this service. */ static get apiEndpoint() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'localhost'; } @@ -295,9 +345,7 @@ export class DeprecatedServiceClient { * @returns {string[]} List of default scopes. */ static get scopes() { - return [ - 'https://www.googleapis.com/auth/cloud-platform' - ]; + return ['https://www.googleapis.com/auth/cloud-platform']; } getProjectId(): Promise; @@ -306,8 +354,9 @@ export class DeprecatedServiceClient { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId(callback?: Callback): - Promise|void { + getProjectId( + callback?: Callback, + ): Promise | void { if (callback) { this.auth.getProjectId(callback); return; @@ -318,188 +367,253 @@ export class DeprecatedServiceClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Calculates Fibonacci on the provided value, quickly. - * - * @param {Object} request - * The request object that will be sent. - * @param {number} request.value - * The nth term to retrieve in the Fibonacci sequence. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1/deprecated_service.fast_fibonacci.js - * region_tag:localhost_v1_generated_DeprecatedService_FastFibonacci_async - */ + /** + * Calculates Fibonacci on the provided value, quickly. + * + * @param {Object} request + * The request object that will be sent. + * @param {number} request.value + * The nth term to retrieve in the Fibonacci sequence. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/deprecated_service.fast_fibonacci.js + * region_tag:localhost_v1_generated_DeprecatedService_FastFibonacci_async + */ fastFibonacci( - request?: protos.google.deprecatedtest.v1.IFibonacciRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.deprecatedtest.v1.IFibonacciRequest|undefined, {}|undefined - ]>; + request?: protos.google.deprecatedtest.v1.IFibonacciRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.deprecatedtest.v1.IFibonacciRequest | undefined, + {} | undefined, + ] + >; fastFibonacci( - request: protos.google.deprecatedtest.v1.IFibonacciRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.deprecatedtest.v1.IFibonacciRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.deprecatedtest.v1.IFibonacciRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.deprecatedtest.v1.IFibonacciRequest | null | undefined, + {} | null | undefined + >, + ): void; fastFibonacci( - request: protos.google.deprecatedtest.v1.IFibonacciRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.deprecatedtest.v1.IFibonacciRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.deprecatedtest.v1.IFibonacciRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.deprecatedtest.v1.IFibonacciRequest | null | undefined, + {} | null | undefined + >, + ): void; fastFibonacci( - request?: protos.google.deprecatedtest.v1.IFibonacciRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.deprecatedtest.v1.IFibonacciRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.deprecatedtest.v1.IFibonacciRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.protobuf.IEmpty, - protos.google.deprecatedtest.v1.IFibonacciRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.deprecatedtest.v1.IFibonacciRequest|undefined, {}|undefined - ]>|void { + protos.google.deprecatedtest.v1.IFibonacciRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + protos.google.deprecatedtest.v1.IFibonacciRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.deprecatedtest.v1.IFibonacciRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('fastFibonacci request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.deprecatedtest.v1.IFibonacciRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + protos.google.deprecatedtest.v1.IFibonacciRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('fastFibonacci response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.fastFibonacci(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.deprecatedtest.v1.IFibonacciRequest|undefined, - {}|undefined - ]) => { - this._log.info('fastFibonacci response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .fastFibonacci(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.deprecatedtest.v1.IFibonacciRequest | undefined, + {} | undefined, + ]) => { + this._log.info('fastFibonacci response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Calculates Fibonacci on the provided value, slowly. - * - * @param {Object} request - * The request object that will be sent. - * @param {number} request.value - * The nth term to retrieve in the Fibonacci sequence. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1/deprecated_service.slow_fibonacci.js - * region_tag:localhost_v1_generated_DeprecatedService_SlowFibonacci_async - * @deprecated SlowFibonacci is deprecated and may be removed in a future version. - */ + /** + * Calculates Fibonacci on the provided value, slowly. + * + * @param {Object} request + * The request object that will be sent. + * @param {number} request.value + * The nth term to retrieve in the Fibonacci sequence. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/deprecated_service.slow_fibonacci.js + * region_tag:localhost_v1_generated_DeprecatedService_SlowFibonacci_async + * @deprecated SlowFibonacci is deprecated and may be removed in a future version. + */ slowFibonacci( - request?: protos.google.deprecatedtest.v1.IFibonacciRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.deprecatedtest.v1.IFibonacciRequest|undefined, {}|undefined - ]>; + request?: protos.google.deprecatedtest.v1.IFibonacciRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.deprecatedtest.v1.IFibonacciRequest | undefined, + {} | undefined, + ] + >; slowFibonacci( - request: protos.google.deprecatedtest.v1.IFibonacciRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.deprecatedtest.v1.IFibonacciRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.deprecatedtest.v1.IFibonacciRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.deprecatedtest.v1.IFibonacciRequest | null | undefined, + {} | null | undefined + >, + ): void; slowFibonacci( - request: protos.google.deprecatedtest.v1.IFibonacciRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.deprecatedtest.v1.IFibonacciRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.deprecatedtest.v1.IFibonacciRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.deprecatedtest.v1.IFibonacciRequest | null | undefined, + {} | null | undefined + >, + ): void; slowFibonacci( - request?: protos.google.deprecatedtest.v1.IFibonacciRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.protobuf.IEmpty, - protos.google.deprecatedtest.v1.IFibonacciRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.deprecatedtest.v1.IFibonacciRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.deprecatedtest.v1.IFibonacciRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.deprecatedtest.v1.IFibonacciRequest|undefined, {}|undefined - ]>|void { + protos.google.deprecatedtest.v1.IFibonacciRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + protos.google.deprecatedtest.v1.IFibonacciRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.deprecatedtest.v1.IFibonacciRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize().catch(err => {throw err}); - this.warn('DEP$DeprecatedService-$SlowFibonacci','SlowFibonacci is deprecated and may be removed in a future version.', 'DeprecationWarning'); + this.initialize().catch((err) => { + throw err; + }); + this.warn( + 'DEP$DeprecatedService-$SlowFibonacci', + 'SlowFibonacci is deprecated and may be removed in a future version.', + 'DeprecationWarning', + ); this._log.info('slowFibonacci request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.deprecatedtest.v1.IFibonacciRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + protos.google.deprecatedtest.v1.IFibonacciRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('slowFibonacci response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.slowFibonacci(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.deprecatedtest.v1.IFibonacciRequest|undefined, - {}|undefined - ]) => { - this._log.info('slowFibonacci response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .slowFibonacci(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.deprecatedtest.v1.IFibonacciRequest | undefined, + {} | undefined, + ]) => { + this._log.info('slowFibonacci response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } - /** * Terminate the gRPC channel and close the client. * @@ -508,7 +622,7 @@ export class DeprecatedServiceClient { */ close(): Promise { if (this.deprecatedServiceStub && !this._terminated) { - return this.deprecatedServiceStub.then(stub => { + return this.deprecatedServiceStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -516,4 +630,4 @@ export class DeprecatedServiceClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/core/generator/gapic-generator-typescript/baselines/deprecatedtest/src/v1/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/deprecatedtest/src/v1/index.ts.baseline index ee2c326c95a3..077c19b5f95a 100644 --- a/core/generator/gapic-generator-typescript/baselines/deprecatedtest/src/v1/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/deprecatedtest/src/v1/index.ts.baseline @@ -16,4 +16,4 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -export {DeprecatedServiceClient} from './deprecated_service_client'; +export { DeprecatedServiceClient } from './deprecated_service_client'; diff --git a/core/generator/gapic-generator-typescript/baselines/deprecatedtest/system-test/fixtures/sample/src/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/deprecatedtest/system-test/fixtures/sample/src/index.ts.baseline index 4327167deaf7..95d75227ae2b 100644 --- a/core/generator/gapic-generator-typescript/baselines/deprecatedtest/system-test/fixtures/sample/src/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/deprecatedtest/system-test/fixtures/sample/src/index.ts.baseline @@ -16,7 +16,7 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -import {DeprecatedServiceClient} from 'deprecatedtest'; +import { DeprecatedServiceClient } from 'deprecatedtest'; // check that the client class type name can be used function doStuffWithDeprecatedServiceClient(client: DeprecatedServiceClient) { diff --git a/core/generator/gapic-generator-typescript/baselines/deprecatedtest/system-test/install.ts.baseline b/core/generator/gapic-generator-typescript/baselines/deprecatedtest/system-test/install.ts.baseline index f66069aa3940..ccf167042d2e 100644 --- a/core/generator/gapic-generator-typescript/baselines/deprecatedtest/system-test/install.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/deprecatedtest/system-test/install.ts.baseline @@ -16,34 +16,36 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -import {packNTest} from 'pack-n-play'; -import {readFileSync} from 'fs'; -import {describe, it} from 'mocha'; +import { packNTest } from 'pack-n-play'; +import { readFileSync } from 'fs'; +import { describe, it } from 'mocha'; describe('📦 pack-n-play test', () => { - - it('TypeScript code', async function() { + it('TypeScript code', async function () { this.timeout(300000); const options = { packageDir: process.cwd(), sample: { description: 'TypeScript user can use the type definitions', - ts: readFileSync('./system-test/fixtures/sample/src/index.ts').toString() - } + ts: readFileSync( + './system-test/fixtures/sample/src/index.ts', + ).toString(), + }, }; await packNTest(options); }); - it('JavaScript code', async function() { + it('JavaScript code', async function () { this.timeout(300000); const options = { packageDir: process.cwd(), sample: { description: 'JavaScript user can use the library', - cjs: readFileSync('./system-test/fixtures/sample/src/index.js').toString() - } + cjs: readFileSync( + './system-test/fixtures/sample/src/index.js', + ).toString(), + }, }; await packNTest(options); }); - }); diff --git a/core/generator/gapic-generator-typescript/baselines/disable-packing-test-esm/esm/src/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/disable-packing-test-esm/esm/src/index.ts.baseline index 485391ab99b2..8858d09869b8 100644 --- a/core/generator/gapic-generator-typescript/baselines/disable-packing-test-esm/esm/src/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/disable-packing-test-esm/esm/src/index.ts.baseline @@ -29,8 +29,24 @@ const SequenceServiceClient = v1beta1.SequenceServiceClient; type SequenceServiceClient = v1beta1.SequenceServiceClient; const TestingClient = v1beta1.TestingClient; type TestingClient = v1beta1.TestingClient; -export {v1beta1, ComplianceClient, EchoClient, IdentityClient, MessagingClient, SequenceServiceClient, TestingClient}; -export default {v1beta1, ComplianceClient, EchoClient, IdentityClient, MessagingClient, SequenceServiceClient, TestingClient}; +export { + v1beta1, + ComplianceClient, + EchoClient, + IdentityClient, + MessagingClient, + SequenceServiceClient, + TestingClient, +}; +export default { + v1beta1, + ComplianceClient, + EchoClient, + IdentityClient, + MessagingClient, + SequenceServiceClient, + TestingClient, +}; // @ts-ignore import * as protos from '../../protos/protos.js'; -export {protos} +export { protos }; diff --git a/core/generator/gapic-generator-typescript/baselines/disable-packing-test-esm/esm/src/v1beta1/compliance_client.ts.baseline b/core/generator/gapic-generator-typescript/baselines/disable-packing-test-esm/esm/src/v1beta1/compliance_client.ts.baseline index 30365083d88c..3862708e042f 100644 --- a/core/generator/gapic-generator-typescript/baselines/disable-packing-test-esm/esm/src/v1beta1/compliance_client.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/disable-packing-test-esm/esm/src/v1beta1/compliance_client.ts.baseline @@ -18,15 +18,20 @@ /* global window */ import * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions} from 'google-gax'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, +} from 'google-gax'; // @ts-ignore import type * as protos from '../../../protos/protos.js'; import * as compliance_client_config from './compliance_client_config.json'; import fs from 'fs'; import path from 'path'; -import {fileURLToPath} from 'url'; -import {getJSON} from '../json-helper.cjs'; +import { fileURLToPath } from 'url'; +import { getJSON } from '../json-helper.cjs'; // @ts-ignore const dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -36,15 +41,15 @@ const dirname = path.dirname(fileURLToPath(import.meta.url)); * This file defines retry strategy and timeouts for all API methods in this library. */ const gapicConfig = getJSON( - path.join(dirname, 'compliance_client_config.json') + path.join(dirname, 'compliance_client_config.json'), ); const jsonProtos = getJSON( - path.join(dirname, '..', '..', '..', 'protos/protos.json') + path.join(dirname, '..', '..', '..', 'protos/protos.json'), ); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; const version = getJSON( - path.join(dirname, '..', '..', '..', '..', 'package.json') + path.join(dirname, '..', '..', '..', '..', 'package.json'), ).version; /** @@ -61,7 +66,7 @@ export class ComplianceClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('showcase'); @@ -73,9 +78,9 @@ export class ComplianceClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; - complianceStub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; + complianceStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of ComplianceClient. @@ -117,21 +122,42 @@ export class ComplianceClient { * const client = new ComplianceClient({fallback: 'rest'}, gax); * ``` */ - constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { // Ensure that options include all the required fields. const staticMembers = this.constructor as typeof ComplianceClient; - if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { - throw new Error('Please set either universe_domain or universeDomain, but not both.'); + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); } - const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; - this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; this._servicePath = 'localhost'; - const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; - const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. if (servicePath !== this._servicePath && !('scopes' in opts)) { @@ -153,7 +179,7 @@ export class ComplianceClient { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; @@ -170,10 +196,7 @@ export class ComplianceClient { const isEsm = true; const isEsmString = isEsm ? '-esm' : '-cjs'; // Determine the client header string. - const clientHeader = [ - `gax/${this._gaxModule.version}`, - `gapic/${version}`, - ]; + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/{process.versions.node}${isEsmString}`); } else { @@ -181,7 +204,7 @@ export class ComplianceClient { } if (!opts.fallback) { clientHeader.push(`grpc/${this._gaxGrpc.grpcVersion}`); - } else if (opts.fallback === 'rest' ) { + } else if (opts.fallback === 'rest') { clientHeader.push(`rest/${this._gaxGrpc.grpcVersion}`); } if (opts.libName && opts.libVersion) { @@ -189,51 +212,53 @@ export class ComplianceClient { } // Load the applicable protos. - this._protos = this._gaxGrpc.loadProtoJSON(jsonProtos as gax.protobuf.INamespace); + this._protos = this._gaxGrpc.loadProtoJSON( + jsonProtos as gax.protobuf.INamespace, + ); // This API contains "path templates"; forward-slash-separated // identifiers to uniquely identify resources within the API. // Create useful helper objects for these. this.pathTemplates = { blueprintPathTemplate: new this._gaxModule.PathTemplate( - 'sessions/{session}/tests/{test}/blueprints/{blueprint}' - ), - roomPathTemplate: new this._gaxModule.PathTemplate( - 'rooms/{room}' + 'sessions/{session}/tests/{test}/blueprints/{blueprint}', ), + roomPathTemplate: new this._gaxModule.PathTemplate('rooms/{room}'), roomBlurbPathTemplate: new this._gaxModule.PathTemplate( - 'rooms/{room}/blurbs/{blurb}' + 'rooms/{room}/blurbs/{blurb}', ), roomBlurbsLegacyRoomBlurbPathTemplate: new this._gaxModule.PathTemplate( - 'rooms/{room}/blurbs/legacy/{legacy_room}.{blurb}' + 'rooms/{room}/blurbs/legacy/{legacy_room}.{blurb}', ), sequencePathTemplate: new this._gaxModule.PathTemplate( - 'sequences/{sequence}' + 'sequences/{sequence}', ), sequenceReportPathTemplate: new this._gaxModule.PathTemplate( - 'sequences/{sequence}/sequenceReport' + 'sequences/{sequence}/sequenceReport', ), sessionPathTemplate: new this._gaxModule.PathTemplate( - 'sessions/{session}' + 'sessions/{session}', ), testPathTemplate: new this._gaxModule.PathTemplate( - 'sessions/{session}/tests/{test}' - ), - userPathTemplate: new this._gaxModule.PathTemplate( - 'users/{user}' + 'sessions/{session}/tests/{test}', ), + userPathTemplate: new this._gaxModule.PathTemplate('users/{user}'), userProfileBlurbPathTemplate: new this._gaxModule.PathTemplate( - 'users/{user}/profile/blurbs/{blurb}' - ), - userProfileBlurbsLegacyUserBlurbPathTemplate: new this._gaxModule.PathTemplate( - 'users/{user}/profile/blurbs/legacy/{legacy_user}~{blurb}' + 'users/{user}/profile/blurbs/{blurb}', ), + userProfileBlurbsLegacyUserBlurbPathTemplate: + new this._gaxModule.PathTemplate( + 'users/{user}/profile/blurbs/legacy/{legacy_user}~{blurb}', + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.showcase.v1beta1.Compliance', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.showcase.v1beta1.Compliance', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + { 'x-goog-api-client': clientHeader.join(' ') }, + ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -264,36 +289,51 @@ export class ComplianceClient { // Put together the "service stub" for // google.showcase.v1beta1.Compliance. this.complianceStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.showcase.v1beta1.Compliance') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.showcase.v1beta1.Compliance', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.showcase.v1beta1.Compliance, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts, + this._providedCustomServicePath, + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const complianceStubMethods = - ['repeatDataBody', 'repeatDataBodyInfo', 'repeatDataQuery', 'repeatDataSimplePath', 'repeatDataPathResource', 'repeatDataPathTrailingResource', 'repeatDataBodyPut', 'repeatDataBodyPatch', 'getEnum', 'verifyEnum']; + const complianceStubMethods = [ + 'repeatDataBody', + 'repeatDataBodyInfo', + 'repeatDataQuery', + 'repeatDataSimplePath', + 'repeatDataPathResource', + 'repeatDataPathTrailingResource', + 'repeatDataBodyPut', + 'repeatDataBodyPatch', + 'getEnum', + 'verifyEnum', + ]; for (const methodName of complianceStubMethods) { const callPromise = this.complianceStub.then( - stub => (...args: Array<{}>) => { - if (this._terminated) { - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error|null|undefined) => () => { + (stub) => + (...args: Array<{}>) => { + if (this._terminated) { + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { throw err; - }); + }, + ); - const descriptor = - undefined; + const descriptor = undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -308,8 +348,14 @@ export class ComplianceClient { * @returns {string} The DNS address for this service. */ static get servicePath() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'localhost'; } @@ -321,8 +367,14 @@ export class ComplianceClient { * @returns {string} The DNS address for this service. */ static get apiEndpoint() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'localhost'; } @@ -362,8 +414,9 @@ export class ComplianceClient { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId(callback?: Callback): - Promise|void { + getProjectId( + callback?: Callback, + ): Promise | void { if (callback) { this.auth.getProjectId(callback); return; @@ -374,1026 +427,1349 @@ export class ComplianceClient { // ------------------- // -- Service calls -- // ------------------- -/** - * This method echoes the ComplianceData request. This method exercises - * sending the entire request object in the REST body. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * @param {google.showcase.v1beta1.ComplianceData} request.info - * @param {boolean} request.serverVerify - * If true, the server will verify that the received request matches - * the request with the same name in the compliance test suite. - * @param {string} request.intendedBindingUri - * The URI template this request is expected to be bound to server-side. - * @param {number} request.fInt32 - * Some top level fields, to test that these are encoded correctly - * in query params. - * @param {number} request.fInt64 - * @param {number} request.fDouble - * @param {number} request.pInt32 - * @param {number} request.pInt64 - * @param {number} request.pDouble - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.RepeatResponse|RepeatResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/compliance.repeat_data_body.js - * region_tag:localhost_v1beta1_generated_Compliance_RepeatDataBody_async - */ + /** + * This method echoes the ComplianceData request. This method exercises + * sending the entire request object in the REST body. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * @param {google.showcase.v1beta1.ComplianceData} request.info + * @param {boolean} request.serverVerify + * If true, the server will verify that the received request matches + * the request with the same name in the compliance test suite. + * @param {string} request.intendedBindingUri + * The URI template this request is expected to be bound to server-side. + * @param {number} request.fInt32 + * Some top level fields, to test that these are encoded correctly + * in query params. + * @param {number} request.fInt64 + * @param {number} request.fDouble + * @param {number} request.pInt32 + * @param {number} request.pInt64 + * @param {number} request.pDouble + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.RepeatResponse|RepeatResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/compliance.repeat_data_body.js + * region_tag:localhost_v1beta1_generated_Compliance_RepeatDataBody_async + */ repeatDataBody( - request?: protos.google.showcase.v1beta1.IRepeatRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IRepeatRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | undefined, + {} | undefined, + ] + >; repeatDataBody( - request: protos.google.showcase.v1beta1.IRepeatRequest, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IRepeatRequest, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + ): void; repeatDataBody( - request: protos.google.showcase.v1beta1.IRepeatRequest, - callback: Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IRepeatRequest, + callback: Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + ): void; repeatDataBody( - request?: protos.google.showcase.v1beta1.IRepeatRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.showcase.v1beta1.IRepeatRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|undefined, {}|undefined - ]>|void { + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('repeatDataBody request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('repeatDataBody response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.repeatDataBody(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|undefined, {}|undefined - ]) => { - this._log.info('repeatDataBody response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .repeatDataBody(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | undefined, + {} | undefined, + ]) => { + this._log.info('repeatDataBody response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * This method echoes the ComplianceData request. This method exercises - * sending the a message-type field in the REST body. Per AIP-127, only - * top-level, non-repeated fields can be sent this way. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * @param {google.showcase.v1beta1.ComplianceData} request.info - * @param {boolean} request.serverVerify - * If true, the server will verify that the received request matches - * the request with the same name in the compliance test suite. - * @param {string} request.intendedBindingUri - * The URI template this request is expected to be bound to server-side. - * @param {number} request.fInt32 - * Some top level fields, to test that these are encoded correctly - * in query params. - * @param {number} request.fInt64 - * @param {number} request.fDouble - * @param {number} request.pInt32 - * @param {number} request.pInt64 - * @param {number} request.pDouble - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.RepeatResponse|RepeatResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/compliance.repeat_data_body_info.js - * region_tag:localhost_v1beta1_generated_Compliance_RepeatDataBodyInfo_async - */ + /** + * This method echoes the ComplianceData request. This method exercises + * sending the a message-type field in the REST body. Per AIP-127, only + * top-level, non-repeated fields can be sent this way. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * @param {google.showcase.v1beta1.ComplianceData} request.info + * @param {boolean} request.serverVerify + * If true, the server will verify that the received request matches + * the request with the same name in the compliance test suite. + * @param {string} request.intendedBindingUri + * The URI template this request is expected to be bound to server-side. + * @param {number} request.fInt32 + * Some top level fields, to test that these are encoded correctly + * in query params. + * @param {number} request.fInt64 + * @param {number} request.fDouble + * @param {number} request.pInt32 + * @param {number} request.pInt64 + * @param {number} request.pDouble + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.RepeatResponse|RepeatResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/compliance.repeat_data_body_info.js + * region_tag:localhost_v1beta1_generated_Compliance_RepeatDataBodyInfo_async + */ repeatDataBodyInfo( - request?: protos.google.showcase.v1beta1.IRepeatRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IRepeatRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | undefined, + {} | undefined, + ] + >; repeatDataBodyInfo( - request: protos.google.showcase.v1beta1.IRepeatRequest, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IRepeatRequest, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + ): void; repeatDataBodyInfo( - request: protos.google.showcase.v1beta1.IRepeatRequest, - callback: Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IRepeatRequest, + callback: Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + ): void; repeatDataBodyInfo( - request?: protos.google.showcase.v1beta1.IRepeatRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.showcase.v1beta1.IRepeatRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|undefined, {}|undefined - ]>|void { + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('repeatDataBodyInfo request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('repeatDataBodyInfo response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.repeatDataBodyInfo(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|undefined, {}|undefined - ]) => { - this._log.info('repeatDataBodyInfo response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .repeatDataBodyInfo(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | undefined, + {} | undefined, + ]) => { + this._log.info('repeatDataBodyInfo response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * This method echoes the ComplianceData request. This method exercises - * sending all request fields as query parameters. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * @param {google.showcase.v1beta1.ComplianceData} request.info - * @param {boolean} request.serverVerify - * If true, the server will verify that the received request matches - * the request with the same name in the compliance test suite. - * @param {string} request.intendedBindingUri - * The URI template this request is expected to be bound to server-side. - * @param {number} request.fInt32 - * Some top level fields, to test that these are encoded correctly - * in query params. - * @param {number} request.fInt64 - * @param {number} request.fDouble - * @param {number} request.pInt32 - * @param {number} request.pInt64 - * @param {number} request.pDouble - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.RepeatResponse|RepeatResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/compliance.repeat_data_query.js - * region_tag:localhost_v1beta1_generated_Compliance_RepeatDataQuery_async - */ + /** + * This method echoes the ComplianceData request. This method exercises + * sending all request fields as query parameters. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * @param {google.showcase.v1beta1.ComplianceData} request.info + * @param {boolean} request.serverVerify + * If true, the server will verify that the received request matches + * the request with the same name in the compliance test suite. + * @param {string} request.intendedBindingUri + * The URI template this request is expected to be bound to server-side. + * @param {number} request.fInt32 + * Some top level fields, to test that these are encoded correctly + * in query params. + * @param {number} request.fInt64 + * @param {number} request.fDouble + * @param {number} request.pInt32 + * @param {number} request.pInt64 + * @param {number} request.pDouble + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.RepeatResponse|RepeatResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/compliance.repeat_data_query.js + * region_tag:localhost_v1beta1_generated_Compliance_RepeatDataQuery_async + */ repeatDataQuery( - request?: protos.google.showcase.v1beta1.IRepeatRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IRepeatRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | undefined, + {} | undefined, + ] + >; repeatDataQuery( - request: protos.google.showcase.v1beta1.IRepeatRequest, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IRepeatRequest, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + ): void; repeatDataQuery( - request: protos.google.showcase.v1beta1.IRepeatRequest, - callback: Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IRepeatRequest, + callback: Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + ): void; repeatDataQuery( - request?: protos.google.showcase.v1beta1.IRepeatRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.showcase.v1beta1.IRepeatRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|undefined, {}|undefined - ]>|void { + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('repeatDataQuery request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('repeatDataQuery response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.repeatDataQuery(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|undefined, {}|undefined - ]) => { - this._log.info('repeatDataQuery response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .repeatDataQuery(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | undefined, + {} | undefined, + ]) => { + this._log.info('repeatDataQuery response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * This method echoes the ComplianceData request. This method exercises - * sending some parameters as "simple" path variables (i.e., of the form - * "/bar/{foo}" rather than "/{foo=bar/*}"), and the rest as query parameters. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * @param {google.showcase.v1beta1.ComplianceData} request.info - * @param {boolean} request.serverVerify - * If true, the server will verify that the received request matches - * the request with the same name in the compliance test suite. - * @param {string} request.intendedBindingUri - * The URI template this request is expected to be bound to server-side. - * @param {number} request.fInt32 - * Some top level fields, to test that these are encoded correctly - * in query params. - * @param {number} request.fInt64 - * @param {number} request.fDouble - * @param {number} request.pInt32 - * @param {number} request.pInt64 - * @param {number} request.pDouble - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.RepeatResponse|RepeatResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/compliance.repeat_data_simple_path.js - * region_tag:localhost_v1beta1_generated_Compliance_RepeatDataSimplePath_async - */ + /** + * This method echoes the ComplianceData request. This method exercises + * sending some parameters as "simple" path variables (i.e., of the form + * "/bar/{foo}" rather than "/{foo=bar/*}"), and the rest as query parameters. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * @param {google.showcase.v1beta1.ComplianceData} request.info + * @param {boolean} request.serverVerify + * If true, the server will verify that the received request matches + * the request with the same name in the compliance test suite. + * @param {string} request.intendedBindingUri + * The URI template this request is expected to be bound to server-side. + * @param {number} request.fInt32 + * Some top level fields, to test that these are encoded correctly + * in query params. + * @param {number} request.fInt64 + * @param {number} request.fDouble + * @param {number} request.pInt32 + * @param {number} request.pInt64 + * @param {number} request.pDouble + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.RepeatResponse|RepeatResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/compliance.repeat_data_simple_path.js + * region_tag:localhost_v1beta1_generated_Compliance_RepeatDataSimplePath_async + */ repeatDataSimplePath( - request?: protos.google.showcase.v1beta1.IRepeatRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IRepeatRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | undefined, + {} | undefined, + ] + >; repeatDataSimplePath( - request: protos.google.showcase.v1beta1.IRepeatRequest, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IRepeatRequest, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + ): void; repeatDataSimplePath( - request: protos.google.showcase.v1beta1.IRepeatRequest, - callback: Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IRepeatRequest, + callback: Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + ): void; repeatDataSimplePath( - request?: protos.google.showcase.v1beta1.IRepeatRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.showcase.v1beta1.IRepeatRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|undefined, {}|undefined - ]>|void { + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'info.f_string': request.info!.fString ?? '', - 'info.f_int32': request.info!.fInt32 ?? '', - 'info.f_double': request.info!.fDouble ?? '', - 'info.f_bool': request.info!.fBool ?? '', - 'info.f_kingdom': request.info!.fKingdom ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'info.f_string': request.info!.fString ?? '', + 'info.f_int32': request.info!.fInt32 ?? '', + 'info.f_double': request.info!.fDouble ?? '', + 'info.f_bool': request.info!.fBool ?? '', + 'info.f_kingdom': request.info!.fKingdom ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('repeatDataSimplePath request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('repeatDataSimplePath response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.repeatDataSimplePath(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|undefined, {}|undefined - ]) => { - this._log.info('repeatDataSimplePath response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .repeatDataSimplePath(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | undefined, + {} | undefined, + ]) => { + this._log.info('repeatDataSimplePath response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Same as RepeatDataSimplePath, but with a path resource. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * @param {google.showcase.v1beta1.ComplianceData} request.info - * @param {boolean} request.serverVerify - * If true, the server will verify that the received request matches - * the request with the same name in the compliance test suite. - * @param {string} request.intendedBindingUri - * The URI template this request is expected to be bound to server-side. - * @param {number} request.fInt32 - * Some top level fields, to test that these are encoded correctly - * in query params. - * @param {number} request.fInt64 - * @param {number} request.fDouble - * @param {number} request.pInt32 - * @param {number} request.pInt64 - * @param {number} request.pDouble - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.RepeatResponse|RepeatResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/compliance.repeat_data_path_resource.js - * region_tag:localhost_v1beta1_generated_Compliance_RepeatDataPathResource_async - */ + /** + * Same as RepeatDataSimplePath, but with a path resource. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * @param {google.showcase.v1beta1.ComplianceData} request.info + * @param {boolean} request.serverVerify + * If true, the server will verify that the received request matches + * the request with the same name in the compliance test suite. + * @param {string} request.intendedBindingUri + * The URI template this request is expected to be bound to server-side. + * @param {number} request.fInt32 + * Some top level fields, to test that these are encoded correctly + * in query params. + * @param {number} request.fInt64 + * @param {number} request.fDouble + * @param {number} request.pInt32 + * @param {number} request.pInt64 + * @param {number} request.pDouble + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.RepeatResponse|RepeatResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/compliance.repeat_data_path_resource.js + * region_tag:localhost_v1beta1_generated_Compliance_RepeatDataPathResource_async + */ repeatDataPathResource( - request?: protos.google.showcase.v1beta1.IRepeatRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IRepeatRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | undefined, + {} | undefined, + ] + >; repeatDataPathResource( - request: protos.google.showcase.v1beta1.IRepeatRequest, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IRepeatRequest, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + ): void; repeatDataPathResource( - request: protos.google.showcase.v1beta1.IRepeatRequest, - callback: Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IRepeatRequest, + callback: Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + ): void; repeatDataPathResource( - request?: protos.google.showcase.v1beta1.IRepeatRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.showcase.v1beta1.IRepeatRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|undefined, {}|undefined - ]>|void { + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'info.f_string': request.info!.fString ?? '', - 'info.f_child.f_string': request.info!.fChild!.fString ?? '', - 'info.f_bool': request.info!.fBool ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'info.f_string': request.info!.fString ?? '', + 'info.f_child.f_string': request.info!.fChild!.fString ?? '', + 'info.f_bool': request.info!.fBool ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('repeatDataPathResource request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('repeatDataPathResource response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.repeatDataPathResource(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|undefined, {}|undefined - ]) => { - this._log.info('repeatDataPathResource response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .repeatDataPathResource(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | undefined, + {} | undefined, + ]) => { + this._log.info('repeatDataPathResource response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Same as RepeatDataSimplePath, but with a trailing resource. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * @param {google.showcase.v1beta1.ComplianceData} request.info - * @param {boolean} request.serverVerify - * If true, the server will verify that the received request matches - * the request with the same name in the compliance test suite. - * @param {string} request.intendedBindingUri - * The URI template this request is expected to be bound to server-side. - * @param {number} request.fInt32 - * Some top level fields, to test that these are encoded correctly - * in query params. - * @param {number} request.fInt64 - * @param {number} request.fDouble - * @param {number} request.pInt32 - * @param {number} request.pInt64 - * @param {number} request.pDouble - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.RepeatResponse|RepeatResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/compliance.repeat_data_path_trailing_resource.js - * region_tag:localhost_v1beta1_generated_Compliance_RepeatDataPathTrailingResource_async - */ + /** + * Same as RepeatDataSimplePath, but with a trailing resource. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * @param {google.showcase.v1beta1.ComplianceData} request.info + * @param {boolean} request.serverVerify + * If true, the server will verify that the received request matches + * the request with the same name in the compliance test suite. + * @param {string} request.intendedBindingUri + * The URI template this request is expected to be bound to server-side. + * @param {number} request.fInt32 + * Some top level fields, to test that these are encoded correctly + * in query params. + * @param {number} request.fInt64 + * @param {number} request.fDouble + * @param {number} request.pInt32 + * @param {number} request.pInt64 + * @param {number} request.pDouble + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.RepeatResponse|RepeatResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/compliance.repeat_data_path_trailing_resource.js + * region_tag:localhost_v1beta1_generated_Compliance_RepeatDataPathTrailingResource_async + */ repeatDataPathTrailingResource( - request?: protos.google.showcase.v1beta1.IRepeatRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IRepeatRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | undefined, + {} | undefined, + ] + >; repeatDataPathTrailingResource( - request: protos.google.showcase.v1beta1.IRepeatRequest, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IRepeatRequest, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + ): void; repeatDataPathTrailingResource( - request: protos.google.showcase.v1beta1.IRepeatRequest, - callback: Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IRepeatRequest, + callback: Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + ): void; repeatDataPathTrailingResource( - request?: protos.google.showcase.v1beta1.IRepeatRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.showcase.v1beta1.IRepeatRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|undefined, {}|undefined - ]>|void { + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'info.f_string': request.info!.fString ?? '', - 'info.f_child.f_string': request.info!.fChild!.fString ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'info.f_string': request.info!.fString ?? '', + 'info.f_child.f_string': request.info!.fChild!.fString ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('repeatDataPathTrailingResource request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { - this._log.info('repeatDataPathTrailingResource response %j', response); + this._log.info( + 'repeatDataPathTrailingResource response %j', + response, + ); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.repeatDataPathTrailingResource(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|undefined, {}|undefined - ]) => { - this._log.info('repeatDataPathTrailingResource response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .repeatDataPathTrailingResource(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | undefined, + {} | undefined, + ]) => { + this._log.info( + 'repeatDataPathTrailingResource response %j', + response, + ); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * This method echoes the ComplianceData request, using the HTTP PUT method. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * @param {google.showcase.v1beta1.ComplianceData} request.info - * @param {boolean} request.serverVerify - * If true, the server will verify that the received request matches - * the request with the same name in the compliance test suite. - * @param {string} request.intendedBindingUri - * The URI template this request is expected to be bound to server-side. - * @param {number} request.fInt32 - * Some top level fields, to test that these are encoded correctly - * in query params. - * @param {number} request.fInt64 - * @param {number} request.fDouble - * @param {number} request.pInt32 - * @param {number} request.pInt64 - * @param {number} request.pDouble - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.RepeatResponse|RepeatResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/compliance.repeat_data_body_put.js - * region_tag:localhost_v1beta1_generated_Compliance_RepeatDataBodyPut_async - */ + /** + * This method echoes the ComplianceData request, using the HTTP PUT method. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * @param {google.showcase.v1beta1.ComplianceData} request.info + * @param {boolean} request.serverVerify + * If true, the server will verify that the received request matches + * the request with the same name in the compliance test suite. + * @param {string} request.intendedBindingUri + * The URI template this request is expected to be bound to server-side. + * @param {number} request.fInt32 + * Some top level fields, to test that these are encoded correctly + * in query params. + * @param {number} request.fInt64 + * @param {number} request.fDouble + * @param {number} request.pInt32 + * @param {number} request.pInt64 + * @param {number} request.pDouble + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.RepeatResponse|RepeatResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/compliance.repeat_data_body_put.js + * region_tag:localhost_v1beta1_generated_Compliance_RepeatDataBodyPut_async + */ repeatDataBodyPut( - request?: protos.google.showcase.v1beta1.IRepeatRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IRepeatRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | undefined, + {} | undefined, + ] + >; repeatDataBodyPut( - request: protos.google.showcase.v1beta1.IRepeatRequest, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IRepeatRequest, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + ): void; repeatDataBodyPut( - request: protos.google.showcase.v1beta1.IRepeatRequest, - callback: Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IRepeatRequest, + callback: Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + ): void; repeatDataBodyPut( - request?: protos.google.showcase.v1beta1.IRepeatRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.showcase.v1beta1.IRepeatRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|undefined, {}|undefined - ]>|void { + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('repeatDataBodyPut request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('repeatDataBodyPut response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.repeatDataBodyPut(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|undefined, {}|undefined - ]) => { - this._log.info('repeatDataBodyPut response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .repeatDataBodyPut(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | undefined, + {} | undefined, + ]) => { + this._log.info('repeatDataBodyPut response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * This method echoes the ComplianceData request, using the HTTP PATCH method. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * @param {google.showcase.v1beta1.ComplianceData} request.info - * @param {boolean} request.serverVerify - * If true, the server will verify that the received request matches - * the request with the same name in the compliance test suite. - * @param {string} request.intendedBindingUri - * The URI template this request is expected to be bound to server-side. - * @param {number} request.fInt32 - * Some top level fields, to test that these are encoded correctly - * in query params. - * @param {number} request.fInt64 - * @param {number} request.fDouble - * @param {number} request.pInt32 - * @param {number} request.pInt64 - * @param {number} request.pDouble - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.RepeatResponse|RepeatResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/compliance.repeat_data_body_patch.js - * region_tag:localhost_v1beta1_generated_Compliance_RepeatDataBodyPatch_async - */ + /** + * This method echoes the ComplianceData request, using the HTTP PATCH method. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * @param {google.showcase.v1beta1.ComplianceData} request.info + * @param {boolean} request.serverVerify + * If true, the server will verify that the received request matches + * the request with the same name in the compliance test suite. + * @param {string} request.intendedBindingUri + * The URI template this request is expected to be bound to server-side. + * @param {number} request.fInt32 + * Some top level fields, to test that these are encoded correctly + * in query params. + * @param {number} request.fInt64 + * @param {number} request.fDouble + * @param {number} request.pInt32 + * @param {number} request.pInt64 + * @param {number} request.pDouble + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.RepeatResponse|RepeatResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/compliance.repeat_data_body_patch.js + * region_tag:localhost_v1beta1_generated_Compliance_RepeatDataBodyPatch_async + */ repeatDataBodyPatch( - request?: protos.google.showcase.v1beta1.IRepeatRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IRepeatRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | undefined, + {} | undefined, + ] + >; repeatDataBodyPatch( - request: protos.google.showcase.v1beta1.IRepeatRequest, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IRepeatRequest, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + ): void; repeatDataBodyPatch( - request: protos.google.showcase.v1beta1.IRepeatRequest, - callback: Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IRepeatRequest, + callback: Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + ): void; repeatDataBodyPatch( - request?: protos.google.showcase.v1beta1.IRepeatRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.showcase.v1beta1.IRepeatRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|undefined, {}|undefined - ]>|void { + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('repeatDataBodyPatch request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('repeatDataBodyPatch response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.repeatDataBodyPatch(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|undefined, {}|undefined - ]) => { - this._log.info('repeatDataBodyPatch response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .repeatDataBodyPatch(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | undefined, + {} | undefined, + ]) => { + this._log.info('repeatDataBodyPatch response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * This method requests an enum value from the server. Depending on the contents of EnumRequest, the enum value returned will be a known enum declared in the - * .proto file, or a made-up enum value the is unknown to the client. To verify that clients can round-trip unknown enum vaues they receive, use the - * response from this RPC as the request to VerifyEnum() - * - * The values of enums sent by the server when a known or unknown value is requested will be the same within a single Showcase server run (this is needed for - * VerifyEnum() to work) but are not guaranteed to be the same across separate Showcase server runs. - * - * @param {Object} request - * The request object that will be sent. - * @param {boolean} request.unknownEnum - * Whether the client is requesting a new, unknown enum value or a known enum value already declard in this proto file. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.EnumResponse|EnumResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/compliance.get_enum.js - * region_tag:localhost_v1beta1_generated_Compliance_GetEnum_async - */ + /** + * This method requests an enum value from the server. Depending on the contents of EnumRequest, the enum value returned will be a known enum declared in the + * .proto file, or a made-up enum value the is unknown to the client. To verify that clients can round-trip unknown enum vaues they receive, use the + * response from this RPC as the request to VerifyEnum() + * + * The values of enums sent by the server when a known or unknown value is requested will be the same within a single Showcase server run (this is needed for + * VerifyEnum() to work) but are not guaranteed to be the same across separate Showcase server runs. + * + * @param {Object} request + * The request object that will be sent. + * @param {boolean} request.unknownEnum + * Whether the client is requesting a new, unknown enum value or a known enum value already declard in this proto file. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.EnumResponse|EnumResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/compliance.get_enum.js + * region_tag:localhost_v1beta1_generated_Compliance_GetEnum_async + */ getEnum( - request?: protos.google.showcase.v1beta1.IEnumRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IEnumResponse, - protos.google.showcase.v1beta1.IEnumRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IEnumRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IEnumResponse, + protos.google.showcase.v1beta1.IEnumRequest | undefined, + {} | undefined, + ] + >; getEnum( - request: protos.google.showcase.v1beta1.IEnumRequest, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.IEnumResponse, - protos.google.showcase.v1beta1.IEnumRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IEnumRequest, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.IEnumResponse, + protos.google.showcase.v1beta1.IEnumRequest | null | undefined, + {} | null | undefined + >, + ): void; getEnum( - request: protos.google.showcase.v1beta1.IEnumRequest, - callback: Callback< - protos.google.showcase.v1beta1.IEnumResponse, - protos.google.showcase.v1beta1.IEnumRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IEnumRequest, + callback: Callback< + protos.google.showcase.v1beta1.IEnumResponse, + protos.google.showcase.v1beta1.IEnumRequest | null | undefined, + {} | null | undefined + >, + ): void; getEnum( - request?: protos.google.showcase.v1beta1.IEnumRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.showcase.v1beta1.IEnumRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.IEnumResponse, - protos.google.showcase.v1beta1.IEnumRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.showcase.v1beta1.IEnumResponse, - protos.google.showcase.v1beta1.IEnumRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.IEnumResponse, - protos.google.showcase.v1beta1.IEnumRequest|undefined, {}|undefined - ]>|void { + protos.google.showcase.v1beta1.IEnumRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.IEnumResponse, + protos.google.showcase.v1beta1.IEnumRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IEnumResponse, + protos.google.showcase.v1beta1.IEnumRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('getEnum request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.IEnumResponse, - protos.google.showcase.v1beta1.IEnumRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.IEnumResponse, + protos.google.showcase.v1beta1.IEnumRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getEnum response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.getEnum(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.IEnumResponse, - protos.google.showcase.v1beta1.IEnumRequest|undefined, {}|undefined - ]) => { - this._log.info('getEnum response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getEnum(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.IEnumResponse, + protos.google.showcase.v1beta1.IEnumRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getEnum response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * This method is used to verify that clients can round-trip enum values, which is particularly important for unknown enum values over REST. VerifyEnum() - * verifies that its request, which is presumably the response that the client previously got to a GetEnum(), contains the correct data. If so, it responds - * with the same EnumResponse; otherwise, the RPC errors. - * - * This works because the values of enums sent by the server when a known or unknown value is requested will be the same within a single Showcase server run, - * although they are not guaranteed to be the same across separate Showcase server runs. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.showcase.v1beta1.EnumRequest} request.request - * The original request for a known or unknown enum from the server. - * @param {google.showcase.v1beta1.Continent} request.continent - * The actual enum the server provided. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.EnumResponse|EnumResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/compliance.verify_enum.js - * region_tag:localhost_v1beta1_generated_Compliance_VerifyEnum_async - */ + /** + * This method is used to verify that clients can round-trip enum values, which is particularly important for unknown enum values over REST. VerifyEnum() + * verifies that its request, which is presumably the response that the client previously got to a GetEnum(), contains the correct data. If so, it responds + * with the same EnumResponse; otherwise, the RPC errors. + * + * This works because the values of enums sent by the server when a known or unknown value is requested will be the same within a single Showcase server run, + * although they are not guaranteed to be the same across separate Showcase server runs. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.showcase.v1beta1.EnumRequest} request.request + * The original request for a known or unknown enum from the server. + * @param {google.showcase.v1beta1.Continent} request.continent + * The actual enum the server provided. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.EnumResponse|EnumResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/compliance.verify_enum.js + * region_tag:localhost_v1beta1_generated_Compliance_VerifyEnum_async + */ verifyEnum( - request?: protos.google.showcase.v1beta1.IEnumResponse, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IEnumResponse, - protos.google.showcase.v1beta1.IEnumResponse|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IEnumResponse, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IEnumResponse, + protos.google.showcase.v1beta1.IEnumResponse | undefined, + {} | undefined, + ] + >; verifyEnum( - request: protos.google.showcase.v1beta1.IEnumResponse, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.IEnumResponse, - protos.google.showcase.v1beta1.IEnumResponse|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IEnumResponse, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.IEnumResponse, + protos.google.showcase.v1beta1.IEnumResponse | null | undefined, + {} | null | undefined + >, + ): void; verifyEnum( - request: protos.google.showcase.v1beta1.IEnumResponse, - callback: Callback< - protos.google.showcase.v1beta1.IEnumResponse, - protos.google.showcase.v1beta1.IEnumResponse|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IEnumResponse, + callback: Callback< + protos.google.showcase.v1beta1.IEnumResponse, + protos.google.showcase.v1beta1.IEnumResponse | null | undefined, + {} | null | undefined + >, + ): void; verifyEnum( - request?: protos.google.showcase.v1beta1.IEnumResponse, - optionsOrCallback?: CallOptions|Callback< - protos.google.showcase.v1beta1.IEnumResponse, - protos.google.showcase.v1beta1.IEnumResponse|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.showcase.v1beta1.IEnumResponse, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.IEnumResponse, - protos.google.showcase.v1beta1.IEnumResponse|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.IEnumResponse, - protos.google.showcase.v1beta1.IEnumResponse|undefined, {}|undefined - ]>|void { + protos.google.showcase.v1beta1.IEnumResponse | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.IEnumResponse, + protos.google.showcase.v1beta1.IEnumResponse | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IEnumResponse, + protos.google.showcase.v1beta1.IEnumResponse | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('verifyEnum request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.IEnumResponse, - protos.google.showcase.v1beta1.IEnumResponse|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.IEnumResponse, + protos.google.showcase.v1beta1.IEnumResponse | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('verifyEnum response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.verifyEnum(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.IEnumResponse, - protos.google.showcase.v1beta1.IEnumResponse|undefined, {}|undefined - ]) => { - this._log.info('verifyEnum response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .verifyEnum(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.IEnumResponse, + protos.google.showcase.v1beta1.IEnumResponse | undefined, + {} | undefined, + ]) => { + this._log.info('verifyEnum response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); @@ -1411,7 +1787,7 @@ export class ComplianceClient { * @param {string} blueprint * @returns {string} Resource name string. */ - blueprintPath(session:string,test:string,blueprint:string) { + blueprintPath(session: string, test: string, blueprint: string) { return this.pathTemplates.blueprintPathTemplate.render({ session: session, test: test, @@ -1427,7 +1803,8 @@ export class ComplianceClient { * @returns {string} A string representing the session. */ matchSessionFromBlueprintName(blueprintName: string) { - return this.pathTemplates.blueprintPathTemplate.match(blueprintName).session; + return this.pathTemplates.blueprintPathTemplate.match(blueprintName) + .session; } /** @@ -1449,7 +1826,8 @@ export class ComplianceClient { * @returns {string} A string representing the blueprint. */ matchBlueprintFromBlueprintName(blueprintName: string) { - return this.pathTemplates.blueprintPathTemplate.match(blueprintName).blueprint; + return this.pathTemplates.blueprintPathTemplate.match(blueprintName) + .blueprint; } /** @@ -1458,7 +1836,7 @@ export class ComplianceClient { * @param {string} room * @returns {string} Resource name string. */ - roomPath(room:string) { + roomPath(room: string) { return this.pathTemplates.roomPathTemplate.render({ room: room, }); @@ -1482,7 +1860,7 @@ export class ComplianceClient { * @param {string} blurb * @returns {string} Resource name string. */ - roomBlurbPath(room:string,blurb:string) { + roomBlurbPath(room: string, blurb: string) { return this.pathTemplates.roomBlurbPathTemplate.render({ room: room, blurb: blurb, @@ -1519,7 +1897,11 @@ export class ComplianceClient { * @param {string} blurb * @returns {string} Resource name string. */ - roomBlurbsLegacyRoomBlurbPath(room:string,legacyRoom:string,blurb:string) { + roomBlurbsLegacyRoomBlurbPath( + room: string, + legacyRoom: string, + blurb: string, + ) { return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.render({ room: room, legacy_room: legacyRoom, @@ -1534,8 +1916,12 @@ export class ComplianceClient { * A fully-qualified path representing room_blurbs_legacy_room_blurb resource. * @returns {string} A string representing the room. */ - matchRoomFromRoomBlurbsLegacyRoomBlurbName(roomBlurbsLegacyRoomBlurbName: string) { - return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match(roomBlurbsLegacyRoomBlurbName).room; + matchRoomFromRoomBlurbsLegacyRoomBlurbName( + roomBlurbsLegacyRoomBlurbName: string, + ) { + return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match( + roomBlurbsLegacyRoomBlurbName, + ).room; } /** @@ -1545,8 +1931,12 @@ export class ComplianceClient { * A fully-qualified path representing room_blurbs_legacy_room_blurb resource. * @returns {string} A string representing the legacy_room. */ - matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName(roomBlurbsLegacyRoomBlurbName: string) { - return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match(roomBlurbsLegacyRoomBlurbName).legacy_room; + matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName( + roomBlurbsLegacyRoomBlurbName: string, + ) { + return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match( + roomBlurbsLegacyRoomBlurbName, + ).legacy_room; } /** @@ -1556,8 +1946,12 @@ export class ComplianceClient { * A fully-qualified path representing room_blurbs_legacy_room_blurb resource. * @returns {string} A string representing the blurb. */ - matchBlurbFromRoomBlurbsLegacyRoomBlurbName(roomBlurbsLegacyRoomBlurbName: string) { - return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match(roomBlurbsLegacyRoomBlurbName).blurb; + matchBlurbFromRoomBlurbsLegacyRoomBlurbName( + roomBlurbsLegacyRoomBlurbName: string, + ) { + return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match( + roomBlurbsLegacyRoomBlurbName, + ).blurb; } /** @@ -1566,7 +1960,7 @@ export class ComplianceClient { * @param {string} sequence * @returns {string} Resource name string. */ - sequencePath(sequence:string) { + sequencePath(sequence: string) { return this.pathTemplates.sequencePathTemplate.render({ sequence: sequence, }); @@ -1589,7 +1983,7 @@ export class ComplianceClient { * @param {string} sequence * @returns {string} Resource name string. */ - sequenceReportPath(sequence:string) { + sequenceReportPath(sequence: string) { return this.pathTemplates.sequenceReportPathTemplate.render({ sequence: sequence, }); @@ -1603,7 +1997,9 @@ export class ComplianceClient { * @returns {string} A string representing the sequence. */ matchSequenceFromSequenceReportName(sequenceReportName: string) { - return this.pathTemplates.sequenceReportPathTemplate.match(sequenceReportName).sequence; + return this.pathTemplates.sequenceReportPathTemplate.match( + sequenceReportName, + ).sequence; } /** @@ -1612,7 +2008,7 @@ export class ComplianceClient { * @param {string} session * @returns {string} Resource name string. */ - sessionPath(session:string) { + sessionPath(session: string) { return this.pathTemplates.sessionPathTemplate.render({ session: session, }); @@ -1636,7 +2032,7 @@ export class ComplianceClient { * @param {string} test * @returns {string} Resource name string. */ - testPath(session:string,test:string) { + testPath(session: string, test: string) { return this.pathTemplates.testPathTemplate.render({ session: session, test: test, @@ -1671,7 +2067,7 @@ export class ComplianceClient { * @param {string} user * @returns {string} Resource name string. */ - userPath(user:string) { + userPath(user: string) { return this.pathTemplates.userPathTemplate.render({ user: user, }); @@ -1695,7 +2091,7 @@ export class ComplianceClient { * @param {string} blurb * @returns {string} Resource name string. */ - userProfileBlurbPath(user:string,blurb:string) { + userProfileBlurbPath(user: string, blurb: string) { return this.pathTemplates.userProfileBlurbPathTemplate.render({ user: user, blurb: blurb, @@ -1710,7 +2106,9 @@ export class ComplianceClient { * @returns {string} A string representing the user. */ matchUserFromUserProfileBlurbName(userProfileBlurbName: string) { - return this.pathTemplates.userProfileBlurbPathTemplate.match(userProfileBlurbName).user; + return this.pathTemplates.userProfileBlurbPathTemplate.match( + userProfileBlurbName, + ).user; } /** @@ -1721,7 +2119,9 @@ export class ComplianceClient { * @returns {string} A string representing the blurb. */ matchBlurbFromUserProfileBlurbName(userProfileBlurbName: string) { - return this.pathTemplates.userProfileBlurbPathTemplate.match(userProfileBlurbName).blurb; + return this.pathTemplates.userProfileBlurbPathTemplate.match( + userProfileBlurbName, + ).blurb; } /** @@ -1732,12 +2132,18 @@ export class ComplianceClient { * @param {string} blurb * @returns {string} Resource name string. */ - userProfileBlurbsLegacyUserBlurbPath(user:string,legacyUser:string,blurb:string) { - return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.render({ - user: user, - legacy_user: legacyUser, - blurb: blurb, - }); + userProfileBlurbsLegacyUserBlurbPath( + user: string, + legacyUser: string, + blurb: string, + ) { + return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.render( + { + user: user, + legacy_user: legacyUser, + blurb: blurb, + }, + ); } /** @@ -1747,8 +2153,12 @@ export class ComplianceClient { * A fully-qualified path representing user_profile_blurbs_legacy_user_blurb resource. * @returns {string} A string representing the user. */ - matchUserFromUserProfileBlurbsLegacyUserBlurbName(userProfileBlurbsLegacyUserBlurbName: string) { - return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match(userProfileBlurbsLegacyUserBlurbName).user; + matchUserFromUserProfileBlurbsLegacyUserBlurbName( + userProfileBlurbsLegacyUserBlurbName: string, + ) { + return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match( + userProfileBlurbsLegacyUserBlurbName, + ).user; } /** @@ -1758,8 +2168,12 @@ export class ComplianceClient { * A fully-qualified path representing user_profile_blurbs_legacy_user_blurb resource. * @returns {string} A string representing the legacy_user. */ - matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName(userProfileBlurbsLegacyUserBlurbName: string) { - return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match(userProfileBlurbsLegacyUserBlurbName).legacy_user; + matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName( + userProfileBlurbsLegacyUserBlurbName: string, + ) { + return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match( + userProfileBlurbsLegacyUserBlurbName, + ).legacy_user; } /** @@ -1769,8 +2183,12 @@ export class ComplianceClient { * A fully-qualified path representing user_profile_blurbs_legacy_user_blurb resource. * @returns {string} A string representing the blurb. */ - matchBlurbFromUserProfileBlurbsLegacyUserBlurbName(userProfileBlurbsLegacyUserBlurbName: string) { - return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match(userProfileBlurbsLegacyUserBlurbName).blurb; + matchBlurbFromUserProfileBlurbsLegacyUserBlurbName( + userProfileBlurbsLegacyUserBlurbName: string, + ) { + return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match( + userProfileBlurbsLegacyUserBlurbName, + ).blurb; } /** @@ -1781,7 +2199,7 @@ export class ComplianceClient { */ close(): Promise { if (this.complianceStub && !this._terminated) { - return this.complianceStub.then(stub => { + return this.complianceStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -1789,4 +2207,4 @@ export class ComplianceClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/core/generator/gapic-generator-typescript/baselines/disable-packing-test-esm/esm/src/v1beta1/echo_client.ts.baseline b/core/generator/gapic-generator-typescript/baselines/disable-packing-test-esm/esm/src/v1beta1/echo_client.ts.baseline index dda6cc472d0d..4f7c826ba552 100644 --- a/core/generator/gapic-generator-typescript/baselines/disable-packing-test-esm/esm/src/v1beta1/echo_client.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/disable-packing-test-esm/esm/src/v1beta1/echo_client.ts.baseline @@ -18,15 +18,24 @@ /* global window */ import * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions, GrpcClientOptions, LROperation, PaginationCallback, GaxCall} from 'google-gax'; -import {Transform, PassThrough} from 'stream'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + GrpcClientOptions, + LROperation, + PaginationCallback, + GaxCall, +} from 'google-gax'; +import { Transform, PassThrough } from 'stream'; // @ts-ignore import type * as protos from '../../../protos/protos.js'; import * as echo_client_config from './echo_client_config.json'; import fs from 'fs'; import path from 'path'; -import {fileURLToPath} from 'url'; -import {getJSON} from '../json-helper.cjs'; +import { fileURLToPath } from 'url'; +import { getJSON } from '../json-helper.cjs'; // @ts-ignore const dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -35,16 +44,14 @@ const dirname = path.dirname(fileURLToPath(import.meta.url)); * `src/v1beta1/echo_client_config.json`. * This file defines retry strategy and timeouts for all API methods in this library. */ -const gapicConfig = getJSON( - path.join(dirname, 'echo_client_config.json') -); +const gapicConfig = getJSON(path.join(dirname, 'echo_client_config.json')); const jsonProtos = getJSON( - path.join(dirname, '..', '..', '..', 'protos/protos.json') + path.join(dirname, '..', '..', '..', 'protos/protos.json'), ); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; const version = getJSON( - path.join(dirname, '..', '..', '..', '..', 'package.json') + path.join(dirname, '..', '..', '..', '..', 'package.json'), ).version; /** @@ -67,7 +74,7 @@ export class EchoClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('showcase'); @@ -79,10 +86,10 @@ export class EchoClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; operationsClient: gax.OperationsClient; - echoStub?: Promise<{[name: string]: Function}>; + echoStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of EchoClient. @@ -124,21 +131,42 @@ export class EchoClient { * const client = new EchoClient({fallback: 'rest'}, gax); * ``` */ - constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { // Ensure that options include all the required fields. const staticMembers = this.constructor as typeof EchoClient; - if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { - throw new Error('Please set either universe_domain or universeDomain, but not both.'); + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); } - const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; - this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; this._servicePath = 'localhost'; - const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; - const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. if (servicePath !== this._servicePath && !('scopes' in opts)) { @@ -160,7 +188,7 @@ export class EchoClient { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; @@ -177,10 +205,7 @@ export class EchoClient { const isEsm = true; const isEsmString = isEsm ? '-esm' : '-cjs'; // Determine the client header string. - const clientHeader = [ - `gax/${this._gaxModule.version}`, - `gapic/${version}`, - ]; + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/{process.versions.node}${isEsmString}`); } else { @@ -188,7 +213,7 @@ export class EchoClient { } if (!opts.fallback) { clientHeader.push(`grpc/${this._gaxGrpc.grpcVersion}`); - } else if (opts.fallback === 'rest' ) { + } else if (opts.fallback === 'rest') { clientHeader.push(`rest/${this._gaxGrpc.grpcVersion}`); } if (opts.libName && opts.libVersion) { @@ -196,61 +221,74 @@ export class EchoClient { } // Load the applicable protos. - this._protos = this._gaxGrpc.loadProtoJSON(jsonProtos as gax.protobuf.INamespace); + this._protos = this._gaxGrpc.loadProtoJSON( + jsonProtos as gax.protobuf.INamespace, + ); // This API contains "path templates"; forward-slash-separated // identifiers to uniquely identify resources within the API. // Create useful helper objects for these. this.pathTemplates = { blueprintPathTemplate: new this._gaxModule.PathTemplate( - 'sessions/{session}/tests/{test}/blueprints/{blueprint}' - ), - roomPathTemplate: new this._gaxModule.PathTemplate( - 'rooms/{room}' + 'sessions/{session}/tests/{test}/blueprints/{blueprint}', ), + roomPathTemplate: new this._gaxModule.PathTemplate('rooms/{room}'), roomBlurbPathTemplate: new this._gaxModule.PathTemplate( - 'rooms/{room}/blurbs/{blurb}' + 'rooms/{room}/blurbs/{blurb}', ), roomBlurbsLegacyRoomBlurbPathTemplate: new this._gaxModule.PathTemplate( - 'rooms/{room}/blurbs/legacy/{legacy_room}.{blurb}' + 'rooms/{room}/blurbs/legacy/{legacy_room}.{blurb}', ), sequencePathTemplate: new this._gaxModule.PathTemplate( - 'sequences/{sequence}' + 'sequences/{sequence}', ), sequenceReportPathTemplate: new this._gaxModule.PathTemplate( - 'sequences/{sequence}/sequenceReport' + 'sequences/{sequence}/sequenceReport', ), sessionPathTemplate: new this._gaxModule.PathTemplate( - 'sessions/{session}' + 'sessions/{session}', ), testPathTemplate: new this._gaxModule.PathTemplate( - 'sessions/{session}/tests/{test}' - ), - userPathTemplate: new this._gaxModule.PathTemplate( - 'users/{user}' + 'sessions/{session}/tests/{test}', ), + userPathTemplate: new this._gaxModule.PathTemplate('users/{user}'), userProfileBlurbPathTemplate: new this._gaxModule.PathTemplate( - 'users/{user}/profile/blurbs/{blurb}' - ), - userProfileBlurbsLegacyUserBlurbPathTemplate: new this._gaxModule.PathTemplate( - 'users/{user}/profile/blurbs/legacy/{legacy_user}~{blurb}' + 'users/{user}/profile/blurbs/{blurb}', ), + userProfileBlurbsLegacyUserBlurbPathTemplate: + new this._gaxModule.PathTemplate( + 'users/{user}/profile/blurbs/legacy/{legacy_user}~{blurb}', + ), }; // Some of the methods on this service return "paged" results, // (e.g. 50 results at a time, with tokens to get subsequent // pages). Denote the keys used for pagination and results. this.descriptors.page = { - pagedExpand: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'responses') + pagedExpand: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'responses', + ), }; // Some of the methods on this service provide streaming responses. // Provide descriptors for these. this.descriptors.stream = { - expand: new this._gaxModule.StreamDescriptor(this._gaxModule.StreamType.SERVER_STREAMING, !!opts.fallback, !!opts.gaxServerStreamingRetries), - collect: new this._gaxModule.StreamDescriptor(this._gaxModule.StreamType.CLIENT_STREAMING, !!opts.fallback), - chat: new this._gaxModule.StreamDescriptor(this._gaxModule.StreamType.BIDI_STREAMING, !!opts.fallback, !!opts.gaxServerStreamingRetries) + expand: new this._gaxModule.StreamDescriptor( + this._gaxModule.StreamType.SERVER_STREAMING, + !!opts.fallback, + !!opts.gaxServerStreamingRetries, + ), + collect: new this._gaxModule.StreamDescriptor( + this._gaxModule.StreamType.CLIENT_STREAMING, + !!opts.fallback, + ), + chat: new this._gaxModule.StreamDescriptor( + this._gaxModule.StreamType.BIDI_STREAMING, + !!opts.fallback, + !!opts.gaxServerStreamingRetries, + ), }; const protoFilesRoot = this._gaxModule.protobufFromJSON(jsonProtos); @@ -259,29 +297,40 @@ export class EchoClient { // rather than holding a request open. const lroOptions: GrpcClientOptions = { auth: this.auth, - grpc: 'grpc' in this._gaxGrpc ? this._gaxGrpc.grpc : undefined + grpc: 'grpc' in this._gaxGrpc ? this._gaxGrpc.grpc : undefined, }; if (opts.fallback === 'rest') { lroOptions.protoJson = protoFilesRoot; lroOptions.httpRules = []; } - this.operationsClient = this._gaxModule.lro(lroOptions).operationsClient(opts); + this.operationsClient = this._gaxModule + .lro(lroOptions) + .operationsClient(opts); const waitResponse = protoFilesRoot.lookup( - '.google.showcase.v1beta1.WaitResponse') as gax.protobuf.Type; + '.google.showcase.v1beta1.WaitResponse', + ) as gax.protobuf.Type; const waitMetadata = protoFilesRoot.lookup( - '.google.showcase.v1beta1.WaitMetadata') as gax.protobuf.Type; + '.google.showcase.v1beta1.WaitMetadata', + ) as gax.protobuf.Type; this.descriptors.longrunning = { wait: new this._gaxModule.LongrunningDescriptor( this.operationsClient, waitResponse.decode.bind(waitResponse), - waitMetadata.decode.bind(waitMetadata)) + waitMetadata.decode.bind(waitMetadata), + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.showcase.v1beta1.Echo', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' '), 'x-goog-api-version': 'v1_20240408'}); + 'google.showcase.v1beta1.Echo', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + { + 'x-goog-api-client': clientHeader.join(' '), + 'x-goog-api-version': 'v1_20240408', + }, + ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -312,35 +361,55 @@ export class EchoClient { // Put together the "service stub" for // google.showcase.v1beta1.Echo. this.echoStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.showcase.v1beta1.Echo') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.showcase.v1beta1.Echo', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.showcase.v1beta1.Echo, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts, + this._providedCustomServicePath, + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const echoStubMethods = - ['echo', 'echoErrorDetails', 'expand', 'collect', 'chat', 'pagedExpand', 'pagedExpandLegacy', 'wait', 'block']; + const echoStubMethods = [ + 'echo', + 'echoErrorDetails', + 'expand', + 'collect', + 'chat', + 'pagedExpand', + 'pagedExpandLegacy', + 'wait', + 'block', + ]; for (const methodName of echoStubMethods) { const callPromise = this.echoStub.then( - stub => (...args: Array<{}>) => { - if (this._terminated) { - if (methodName in this.descriptors.stream) { - const stream = new PassThrough({objectMode: true}); - setImmediate(() => { - stream.emit('error', new this._gaxModule.GoogleError('The client has already been closed.')); - }); - return stream; + (stub) => + (...args: Array<{}>) => { + if (this._terminated) { + if (methodName in this.descriptors.stream) { + const stream = new PassThrough({ objectMode: true }); + setImmediate(() => { + stream.emit( + 'error', + new this._gaxModule.GoogleError( + 'The client has already been closed.', + ), + ); + }); + return stream; + } + return Promise.reject('The client has already been closed.'); } - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error|null|undefined) => () => { + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { throw err; - }); + }, + ); const descriptor = this.descriptors.page[methodName] || @@ -351,7 +420,7 @@ export class EchoClient { callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -366,8 +435,14 @@ export class EchoClient { * @returns {string} The DNS address for this service. */ static get servicePath() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'localhost'; } @@ -379,8 +454,14 @@ export class EchoClient { * @returns {string} The DNS address for this service. */ static get apiEndpoint() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'localhost'; } @@ -420,8 +501,9 @@ export class EchoClient { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId(callback?: Callback): - Promise|void { + getProjectId( + callback?: Callback, + ): Promise | void { if (callback) { this.auth.getProjectId(callback); return; @@ -432,73 +514,86 @@ export class EchoClient { // ------------------- // -- Service calls -- // ------------------- -/** - * @param {Object} request - * The request object that will be sent. - * @param {string} request.content - * The content to be echoed by the server. - * @param {google.rpc.Status} request.error - * The error to be thrown by the server. - * @param {google.showcase.v1beta1.Severity} request.severity - * The severity to be echoed by the server. - * @param {string} request.header - * Optional. This field can be set to test the routing annotation on the Echo method. - * @param {string} request.otherHeader - * Optional. This field can be set to test the routing annotation on the Echo method. - * @param {string} request.requestId - * To facilitate testing of https://google.aip.dev/client-libraries/4235 - * @param {string} request.otherRequestId - * To facilitate testing of https://google.aip.dev/client-libraries/4235 - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.EchoResponse|EchoResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/echo.echo.js - * region_tag:localhost_v1beta1_generated_Echo_Echo_async - */ + /** + * @param {Object} request + * The request object that will be sent. + * @param {string} request.content + * The content to be echoed by the server. + * @param {google.rpc.Status} request.error + * The error to be thrown by the server. + * @param {google.showcase.v1beta1.Severity} request.severity + * The severity to be echoed by the server. + * @param {string} request.header + * Optional. This field can be set to test the routing annotation on the Echo method. + * @param {string} request.otherHeader + * Optional. This field can be set to test the routing annotation on the Echo method. + * @param {string} request.requestId + * To facilitate testing of https://google.aip.dev/client-libraries/4235 + * @param {string} request.otherRequestId + * To facilitate testing of https://google.aip.dev/client-libraries/4235 + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.EchoResponse|EchoResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/echo.echo.js + * region_tag:localhost_v1beta1_generated_Echo_Echo_async + */ echo( - request?: protos.google.showcase.v1beta1.IEchoRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IEchoResponse, - protos.google.showcase.v1beta1.IEchoRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IEchoRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IEchoResponse, + protos.google.showcase.v1beta1.IEchoRequest | undefined, + {} | undefined, + ] + >; echo( - request: protos.google.showcase.v1beta1.IEchoRequest, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.IEchoResponse, - protos.google.showcase.v1beta1.IEchoRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IEchoRequest, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.IEchoResponse, + protos.google.showcase.v1beta1.IEchoRequest | null | undefined, + {} | null | undefined + >, + ): void; echo( - request: protos.google.showcase.v1beta1.IEchoRequest, - callback: Callback< - protos.google.showcase.v1beta1.IEchoResponse, - protos.google.showcase.v1beta1.IEchoRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IEchoRequest, + callback: Callback< + protos.google.showcase.v1beta1.IEchoResponse, + protos.google.showcase.v1beta1.IEchoRequest | null | undefined, + {} | null | undefined + >, + ): void; echo( - request?: protos.google.showcase.v1beta1.IEchoRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.showcase.v1beta1.IEchoResponse, - protos.google.showcase.v1beta1.IEchoRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.showcase.v1beta1.IEchoRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.IEchoResponse, - protos.google.showcase.v1beta1.IEchoRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.IEchoResponse, - protos.google.showcase.v1beta1.IEchoRequest|undefined, {}|undefined - ]>|void { + protos.google.showcase.v1beta1.IEchoRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.IEchoResponse, + protos.google.showcase.v1beta1.IEchoRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IEchoResponse, + protos.google.showcase.v1beta1.IEchoRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; @@ -518,7 +613,9 @@ export class EchoClient { { const fieldValue = request.header; if (fieldValue !== undefined && fieldValue !== null) { - const match = fieldValue.toString().match(RegExp('(?(?:.*)?)')); + const match = fieldValue + .toString() + .match(RegExp('(?(?:.*)?)')); if (match) { const parameterValue = match.groups?.['routing_id'] ?? fieldValue; Object.assign(routingParameter, { routing_id: parameterValue }); @@ -528,7 +625,9 @@ export class EchoClient { { const fieldValue = request.header; if (fieldValue !== undefined && fieldValue !== null) { - const match = fieldValue.toString().match(RegExp('(?regions/[^/]+/zones/[^/]+(?:/.*)?)')); + const match = fieldValue + .toString() + .match(RegExp('(?regions/[^/]+/zones/[^/]+(?:/.*)?)')); if (match) { const parameterValue = match.groups?.['table_name'] ?? fieldValue; Object.assign(routingParameter, { table_name: parameterValue }); @@ -538,7 +637,9 @@ export class EchoClient { { const fieldValue = request.header; if (fieldValue !== undefined && fieldValue !== null) { - const match = fieldValue.toString().match(RegExp('(?projects/[^/]+)(?:/.*)?')); + const match = fieldValue + .toString() + .match(RegExp('(?projects/[^/]+)(?:/.*)?')); if (match) { const parameterValue = match.groups?.['super_id'] ?? fieldValue; Object.assign(routingParameter, { super_id: parameterValue }); @@ -548,7 +649,11 @@ export class EchoClient { { const fieldValue = request.header; if (fieldValue !== undefined && fieldValue !== null) { - const match = fieldValue.toString().match(RegExp('(?projects/[^/]+/instances/[^/]+(?:/.*)?)')); + const match = fieldValue + .toString() + .match( + RegExp('(?projects/[^/]+/instances/[^/]+(?:/.*)?)'), + ); if (match) { const parameterValue = match.groups?.['table_name'] ?? fieldValue; Object.assign(routingParameter, { table_name: parameterValue }); @@ -558,7 +663,11 @@ export class EchoClient { { const fieldValue = request.header; if (fieldValue !== undefined && fieldValue !== null) { - const match = fieldValue.toString().match(RegExp('projects/[^/]+/(?instances/[^/]+)(?:/.*)?')); + const match = fieldValue + .toString() + .match( + RegExp('projects/[^/]+/(?instances/[^/]+)(?:/.*)?'), + ); if (match) { const parameterValue = match.groups?.['instance_id'] ?? fieldValue; Object.assign(routingParameter, { instance_id: parameterValue }); @@ -578,625 +687,852 @@ export class EchoClient { { const fieldValue = request.otherHeader; if (fieldValue !== undefined && fieldValue !== null) { - const match = fieldValue.toString().match(RegExp('(?projects/[^/]+)(?:/.*)?')); + const match = fieldValue + .toString() + .match(RegExp('(?projects/[^/]+)(?:/.*)?')); if (match) { const parameterValue = match.groups?.['qux'] ?? fieldValue; Object.assign(routingParameter, { qux: parameterValue }); } } } - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams( - routingParameter - ); - this.initialize().catch(err => {throw err}); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams(routingParameter); + this.initialize().catch((err) => { + throw err; + }); this._log.info('echo request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.IEchoResponse, - protos.google.showcase.v1beta1.IEchoRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.IEchoResponse, + protos.google.showcase.v1beta1.IEchoRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('echo response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.echo(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.IEchoResponse, - protos.google.showcase.v1beta1.IEchoRequest|undefined, {}|undefined - ]) => { - this._log.info('echo response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .echo(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.IEchoResponse, + protos.google.showcase.v1beta1.IEchoRequest | undefined, + {} | undefined, + ]) => { + this._log.info('echo response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * This method returns error details in a repeated "google.protobuf.Any" - * field. This method showcases handling errors thus encoded, particularly - * over REST transport. Note that GAPICs only allow the type - * "google.protobuf.Any" for field paths ending in "error.details", and, at - * run-time, the actual types for these fields must be one of the types in - * google/rpc/error_details.proto. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.singleDetailText - * Content to return in a singular `*.error.details` field of type - * `google.protobuf.Any` - * @param {string[]} request.multiDetailText - * Content to return in a repeated `*.error.details` field of type - * `google.protobuf.Any` - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.EchoErrorDetailsResponse|EchoErrorDetailsResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/echo.echo_error_details.js - * region_tag:localhost_v1beta1_generated_Echo_EchoErrorDetails_async - */ + /** + * This method returns error details in a repeated "google.protobuf.Any" + * field. This method showcases handling errors thus encoded, particularly + * over REST transport. Note that GAPICs only allow the type + * "google.protobuf.Any" for field paths ending in "error.details", and, at + * run-time, the actual types for these fields must be one of the types in + * google/rpc/error_details.proto. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.singleDetailText + * Content to return in a singular `*.error.details` field of type + * `google.protobuf.Any` + * @param {string[]} request.multiDetailText + * Content to return in a repeated `*.error.details` field of type + * `google.protobuf.Any` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.EchoErrorDetailsResponse|EchoErrorDetailsResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/echo.echo_error_details.js + * region_tag:localhost_v1beta1_generated_Echo_EchoErrorDetails_async + */ echoErrorDetails( - request?: protos.google.showcase.v1beta1.IEchoErrorDetailsRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IEchoErrorDetailsResponse, - protos.google.showcase.v1beta1.IEchoErrorDetailsRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IEchoErrorDetailsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IEchoErrorDetailsResponse, + protos.google.showcase.v1beta1.IEchoErrorDetailsRequest | undefined, + {} | undefined, + ] + >; echoErrorDetails( - request: protos.google.showcase.v1beta1.IEchoErrorDetailsRequest, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.IEchoErrorDetailsResponse, - protos.google.showcase.v1beta1.IEchoErrorDetailsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IEchoErrorDetailsRequest, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.IEchoErrorDetailsResponse, + | protos.google.showcase.v1beta1.IEchoErrorDetailsRequest + | null + | undefined, + {} | null | undefined + >, + ): void; echoErrorDetails( - request: protos.google.showcase.v1beta1.IEchoErrorDetailsRequest, - callback: Callback< - protos.google.showcase.v1beta1.IEchoErrorDetailsResponse, - protos.google.showcase.v1beta1.IEchoErrorDetailsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IEchoErrorDetailsRequest, + callback: Callback< + protos.google.showcase.v1beta1.IEchoErrorDetailsResponse, + | protos.google.showcase.v1beta1.IEchoErrorDetailsRequest + | null + | undefined, + {} | null | undefined + >, + ): void; echoErrorDetails( - request?: protos.google.showcase.v1beta1.IEchoErrorDetailsRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.showcase.v1beta1.IEchoErrorDetailsResponse, - protos.google.showcase.v1beta1.IEchoErrorDetailsRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.showcase.v1beta1.IEchoErrorDetailsRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.IEchoErrorDetailsResponse, - protos.google.showcase.v1beta1.IEchoErrorDetailsRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.IEchoErrorDetailsResponse, - protos.google.showcase.v1beta1.IEchoErrorDetailsRequest|undefined, {}|undefined - ]>|void { + | protos.google.showcase.v1beta1.IEchoErrorDetailsRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.IEchoErrorDetailsResponse, + | protos.google.showcase.v1beta1.IEchoErrorDetailsRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IEchoErrorDetailsResponse, + protos.google.showcase.v1beta1.IEchoErrorDetailsRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('echoErrorDetails request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.IEchoErrorDetailsResponse, - protos.google.showcase.v1beta1.IEchoErrorDetailsRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.IEchoErrorDetailsResponse, + | protos.google.showcase.v1beta1.IEchoErrorDetailsRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('echoErrorDetails response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.echoErrorDetails(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.IEchoErrorDetailsResponse, - protos.google.showcase.v1beta1.IEchoErrorDetailsRequest|undefined, {}|undefined - ]) => { - this._log.info('echoErrorDetails response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .echoErrorDetails(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.IEchoErrorDetailsResponse, + protos.google.showcase.v1beta1.IEchoErrorDetailsRequest | undefined, + {} | undefined, + ]) => { + this._log.info('echoErrorDetails response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * This is similar to the PagedExpand except that it uses - * max_results instead of page_size, as some legacy APIs still - * do. New APIs should NOT use this pattern. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.content - * The string to expand. - * @param {number} request.maxResults - * The number of words to returned in each page. - * (-- aip.dev/not-precedent: This is a legacy, non-standard pattern that - * violates aip.dev/158. Ordinarily, this should be page_size. --) - * @param {string} request.pageToken - * The position of the page to be returned. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.PagedExpandResponse|PagedExpandResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/echo.paged_expand_legacy.js - * region_tag:localhost_v1beta1_generated_Echo_PagedExpandLegacy_async - */ + /** + * This is similar to the PagedExpand except that it uses + * max_results instead of page_size, as some legacy APIs still + * do. New APIs should NOT use this pattern. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.content + * The string to expand. + * @param {number} request.maxResults + * The number of words to returned in each page. + * (-- aip.dev/not-precedent: This is a legacy, non-standard pattern that + * violates aip.dev/158. Ordinarily, this should be page_size. --) + * @param {string} request.pageToken + * The position of the page to be returned. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.PagedExpandResponse|PagedExpandResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/echo.paged_expand_legacy.js + * region_tag:localhost_v1beta1_generated_Echo_PagedExpandLegacy_async + */ pagedExpandLegacy( - request?: protos.google.showcase.v1beta1.IPagedExpandLegacyRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IPagedExpandResponse, - protos.google.showcase.v1beta1.IPagedExpandLegacyRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IPagedExpandLegacyRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IPagedExpandResponse, + protos.google.showcase.v1beta1.IPagedExpandLegacyRequest | undefined, + {} | undefined, + ] + >; pagedExpandLegacy( - request: protos.google.showcase.v1beta1.IPagedExpandLegacyRequest, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.IPagedExpandResponse, - protos.google.showcase.v1beta1.IPagedExpandLegacyRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IPagedExpandLegacyRequest, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.IPagedExpandResponse, + | protos.google.showcase.v1beta1.IPagedExpandLegacyRequest + | null + | undefined, + {} | null | undefined + >, + ): void; pagedExpandLegacy( - request: protos.google.showcase.v1beta1.IPagedExpandLegacyRequest, - callback: Callback< - protos.google.showcase.v1beta1.IPagedExpandResponse, - protos.google.showcase.v1beta1.IPagedExpandLegacyRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IPagedExpandLegacyRequest, + callback: Callback< + protos.google.showcase.v1beta1.IPagedExpandResponse, + | protos.google.showcase.v1beta1.IPagedExpandLegacyRequest + | null + | undefined, + {} | null | undefined + >, + ): void; pagedExpandLegacy( - request?: protos.google.showcase.v1beta1.IPagedExpandLegacyRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.showcase.v1beta1.IPagedExpandLegacyRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.IPagedExpandResponse, - protos.google.showcase.v1beta1.IPagedExpandLegacyRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.showcase.v1beta1.IPagedExpandResponse, - protos.google.showcase.v1beta1.IPagedExpandLegacyRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.IPagedExpandResponse, - protos.google.showcase.v1beta1.IPagedExpandLegacyRequest|undefined, {}|undefined - ]>|void { + | protos.google.showcase.v1beta1.IPagedExpandLegacyRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.IPagedExpandResponse, + | protos.google.showcase.v1beta1.IPagedExpandLegacyRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IPagedExpandResponse, + protos.google.showcase.v1beta1.IPagedExpandLegacyRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('pagedExpandLegacy request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.IPagedExpandResponse, - protos.google.showcase.v1beta1.IPagedExpandLegacyRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.IPagedExpandResponse, + | protos.google.showcase.v1beta1.IPagedExpandLegacyRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('pagedExpandLegacy response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.pagedExpandLegacy(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.IPagedExpandResponse, - protos.google.showcase.v1beta1.IPagedExpandLegacyRequest|undefined, {}|undefined - ]) => { - this._log.info('pagedExpandLegacy response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .pagedExpandLegacy(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.IPagedExpandResponse, + protos.google.showcase.v1beta1.IPagedExpandLegacyRequest | undefined, + {} | undefined, + ]) => { + this._log.info('pagedExpandLegacy response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * This method will block (wait) for the requested amount of time - * and then return the response or error. - * This method showcases how a client handles delays or retries. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.protobuf.Duration} request.responseDelay - * The amount of time to block before returning a response. - * @param {google.rpc.Status} request.error - * The error that will be returned by the server. If this code is specified - * to be the OK rpc code, an empty response will be returned. - * @param {google.showcase.v1beta1.BlockResponse} request.success - * The response to be returned that will signify successful method call. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.BlockResponse|BlockResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/echo.block.js - * region_tag:localhost_v1beta1_generated_Echo_Block_async - */ + /** + * This method will block (wait) for the requested amount of time + * and then return the response or error. + * This method showcases how a client handles delays or retries. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.protobuf.Duration} request.responseDelay + * The amount of time to block before returning a response. + * @param {google.rpc.Status} request.error + * The error that will be returned by the server. If this code is specified + * to be the OK rpc code, an empty response will be returned. + * @param {google.showcase.v1beta1.BlockResponse} request.success + * The response to be returned that will signify successful method call. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.BlockResponse|BlockResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/echo.block.js + * region_tag:localhost_v1beta1_generated_Echo_Block_async + */ block( - request?: protos.google.showcase.v1beta1.IBlockRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IBlockResponse, - protos.google.showcase.v1beta1.IBlockRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IBlockRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IBlockResponse, + protos.google.showcase.v1beta1.IBlockRequest | undefined, + {} | undefined, + ] + >; block( - request: protos.google.showcase.v1beta1.IBlockRequest, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.IBlockResponse, - protos.google.showcase.v1beta1.IBlockRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IBlockRequest, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.IBlockResponse, + protos.google.showcase.v1beta1.IBlockRequest | null | undefined, + {} | null | undefined + >, + ): void; block( - request: protos.google.showcase.v1beta1.IBlockRequest, - callback: Callback< - protos.google.showcase.v1beta1.IBlockResponse, - protos.google.showcase.v1beta1.IBlockRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IBlockRequest, + callback: Callback< + protos.google.showcase.v1beta1.IBlockResponse, + protos.google.showcase.v1beta1.IBlockRequest | null | undefined, + {} | null | undefined + >, + ): void; block( - request?: protos.google.showcase.v1beta1.IBlockRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.showcase.v1beta1.IBlockRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.IBlockResponse, - protos.google.showcase.v1beta1.IBlockRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.showcase.v1beta1.IBlockResponse, - protos.google.showcase.v1beta1.IBlockRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.IBlockResponse, - protos.google.showcase.v1beta1.IBlockRequest|undefined, {}|undefined - ]>|void { + protos.google.showcase.v1beta1.IBlockRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.IBlockResponse, + protos.google.showcase.v1beta1.IBlockRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IBlockResponse, + protos.google.showcase.v1beta1.IBlockRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('block request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.IBlockResponse, - protos.google.showcase.v1beta1.IBlockRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.IBlockResponse, + protos.google.showcase.v1beta1.IBlockRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('block response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.block(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.IBlockResponse, - protos.google.showcase.v1beta1.IBlockRequest|undefined, {}|undefined - ]) => { - this._log.info('block response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .block(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.IBlockResponse, + protos.google.showcase.v1beta1.IBlockRequest | undefined, + {} | undefined, + ]) => { + this._log.info('block response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * This method splits the given content into words and will pass each word back - * through the stream. This method showcases server-side streaming RPCs. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.content - * The content that will be split into words and returned on the stream. - * @param {google.rpc.Status} request.error - * The error that is thrown after all words are sent on the stream. - * @param {google.protobuf.Duration} request.streamWaitTime - * The wait time between each server streaming messages - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits {@link protos.google.showcase.v1beta1.EchoResponse|EchoResponse} on 'data' event. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#server-streaming | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/echo.expand.js - * region_tag:localhost_v1beta1_generated_Echo_Expand_async - */ + /** + * This method splits the given content into words and will pass each word back + * through the stream. This method showcases server-side streaming RPCs. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.content + * The content that will be split into words and returned on the stream. + * @param {google.rpc.Status} request.error + * The error that is thrown after all words are sent on the stream. + * @param {google.protobuf.Duration} request.streamWaitTime + * The wait time between each server streaming messages + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits {@link protos.google.showcase.v1beta1.EchoResponse|EchoResponse} on 'data' event. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#server-streaming | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/echo.expand.js + * region_tag:localhost_v1beta1_generated_Echo_Expand_async + */ expand( - request?: protos.google.showcase.v1beta1.IExpandRequest, - options?: CallOptions): - gax.CancellableStream{ + request?: protos.google.showcase.v1beta1.IExpandRequest, + options?: CallOptions, + ): gax.CancellableStream { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('expand stream %j', options); return this.innerApiCalls.expand(request, options); } -/** - * This method will collect the words given to it. When the stream is closed - * by the client, this method will return the a concatenation of the strings - * passed to it. This method showcases client-side streaming RPCs. - * - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - A writable stream which accepts objects representing - * {@link protos.google.showcase.v1beta1.EchoRequest|EchoRequest}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#client-streaming | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/echo.collect.js - * region_tag:localhost_v1beta1_generated_Echo_Collect_async - */ + /** + * This method will collect the words given to it. When the stream is closed + * by the client, this method will return the a concatenation of the strings + * passed to it. This method showcases client-side streaming RPCs. + * + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} - A writable stream which accepts objects representing + * {@link protos.google.showcase.v1beta1.EchoRequest|EchoRequest}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#client-streaming | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/echo.collect.js + * region_tag:localhost_v1beta1_generated_Echo_Collect_async + */ collect( - options?: CallOptions, - callback?: Callback< - protos.google.showcase.v1beta1.IEchoResponse, - protos.google.showcase.v1beta1.IEchoRequest|null|undefined, - {}|null|undefined>): - gax.CancellableStream; + options?: CallOptions, + callback?: Callback< + protos.google.showcase.v1beta1.IEchoResponse, + protos.google.showcase.v1beta1.IEchoRequest | null | undefined, + {} | null | undefined + >, + ): gax.CancellableStream; collect( - callback?: Callback< - protos.google.showcase.v1beta1.IEchoResponse, - protos.google.showcase.v1beta1.IEchoRequest|null|undefined, - {}|null|undefined>): - gax.CancellableStream; + callback?: Callback< + protos.google.showcase.v1beta1.IEchoResponse, + protos.google.showcase.v1beta1.IEchoRequest | null | undefined, + {} | null | undefined + >, + ): gax.CancellableStream; collect( - optionsOrCallback?: CallOptions|Callback< - protos.google.showcase.v1beta1.IEchoResponse, - protos.google.showcase.v1beta1.IEchoRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.showcase.v1beta1.IEchoResponse, - protos.google.showcase.v1beta1.IEchoRequest|null|undefined, - {}|null|undefined>): - gax.CancellableStream { + optionsOrCallback?: + | CallOptions + | Callback< + protos.google.showcase.v1beta1.IEchoResponse, + protos.google.showcase.v1beta1.IEchoRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.IEchoResponse, + protos.google.showcase.v1beta1.IEchoRequest | null | undefined, + {} | null | undefined + >, + ): gax.CancellableStream { if (optionsOrCallback instanceof Function && callback === undefined) { - callback = optionsOrCallback; - optionsOrCallback = {}; + callback = optionsOrCallback; + optionsOrCallback = {}; } const options = optionsOrCallback as CallOptions; - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('collect stream %j', options); return this.innerApiCalls.collect(null, options, callback); } -/** - * This method, upon receiving a request on the stream, will pass the same - * content back on the stream. This method showcases bidirectional - * streaming RPCs. - * - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which is both readable and writable. It accepts objects - * representing {@link protos.google.showcase.v1beta1.EchoRequest|EchoRequest} for write() method, and - * will emit objects representing {@link protos.google.showcase.v1beta1.EchoResponse|EchoResponse} on 'data' event asynchronously. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#bi-directional-streaming | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/echo.chat.js - * region_tag:localhost_v1beta1_generated_Echo_Chat_async - */ - chat( - options?: CallOptions): - gax.CancellableStream { - this.initialize().catch(err => {throw err}); + /** + * This method, upon receiving a request on the stream, will pass the same + * content back on the stream. This method showcases bidirectional + * streaming RPCs. + * + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which is both readable and writable. It accepts objects + * representing {@link protos.google.showcase.v1beta1.EchoRequest|EchoRequest} for write() method, and + * will emit objects representing {@link protos.google.showcase.v1beta1.EchoResponse|EchoResponse} on 'data' event asynchronously. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#bi-directional-streaming | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/echo.chat.js + * region_tag:localhost_v1beta1_generated_Echo_Chat_async + */ + chat(options?: CallOptions): gax.CancellableStream { + this.initialize().catch((err) => { + throw err; + }); this._log.info('chat stream %j', options); return this.innerApiCalls.chat(null, options); } -/** - * This method will wait for the requested amount of time and then return. - * This method showcases how a client handles a request timeout. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.protobuf.Timestamp} request.endTime - * The time that this operation will complete. - * @param {google.protobuf.Duration} request.ttl - * The duration of this operation. - * @param {google.rpc.Status} request.error - * The error that will be returned by the server. If this code is specified - * to be the OK rpc code, an empty response will be returned. - * @param {google.showcase.v1beta1.WaitResponse} request.success - * The response to be returned on operation completion. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing - * a long running operation. Its `promise()` method returns a promise - * you can `await` for. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/echo.wait.js - * region_tag:localhost_v1beta1_generated_Echo_Wait_async - */ + /** + * This method will wait for the requested amount of time and then return. + * This method showcases how a client handles a request timeout. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.protobuf.Timestamp} request.endTime + * The time that this operation will complete. + * @param {google.protobuf.Duration} request.ttl + * The duration of this operation. + * @param {google.rpc.Status} request.error + * The error that will be returned by the server. If this code is specified + * to be the OK rpc code, an empty response will be returned. + * @param {google.showcase.v1beta1.WaitResponse} request.success + * The response to be returned on operation completion. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/echo.wait.js + * region_tag:localhost_v1beta1_generated_Echo_Wait_async + */ wait( - request?: protos.google.showcase.v1beta1.IWaitRequest, - options?: CallOptions): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IWaitRequest, + options?: CallOptions, + ): Promise< + [ + LROperation< + protos.google.showcase.v1beta1.IWaitResponse, + protos.google.showcase.v1beta1.IWaitMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; wait( - request: protos.google.showcase.v1beta1.IWaitRequest, - options: CallOptions, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IWaitRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.showcase.v1beta1.IWaitResponse, + protos.google.showcase.v1beta1.IWaitMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; wait( - request: protos.google.showcase.v1beta1.IWaitRequest, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IWaitRequest, + callback: Callback< + LROperation< + protos.google.showcase.v1beta1.IWaitResponse, + protos.google.showcase.v1beta1.IWaitMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; wait( - request?: protos.google.showcase.v1beta1.IWaitRequest, - optionsOrCallback?: CallOptions|Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>, - callback?: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>|void { + request?: protos.google.showcase.v1beta1.IWaitRequest, + optionsOrCallback?: + | CallOptions + | Callback< + LROperation< + protos.google.showcase.v1beta1.IWaitResponse, + protos.google.showcase.v1beta1.IWaitMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + callback?: Callback< + LROperation< + protos.google.showcase.v1beta1.IWaitResponse, + protos.google.showcase.v1beta1.IWaitMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + LROperation< + protos.google.showcase.v1beta1.IWaitResponse, + protos.google.showcase.v1beta1.IWaitMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize().catch(err => {throw err}); - const wrappedCallback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>|undefined = callback + this.initialize().catch((err) => { + throw err; + }); + const wrappedCallback: + | Callback< + LROperation< + protos.google.showcase.v1beta1.IWaitResponse, + protos.google.showcase.v1beta1.IWaitMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, rawResponse, _) => { this._log.info('wait response %j', rawResponse); callback!(error, response, rawResponse, _); // We verified `callback` above. } : undefined; this._log.info('wait request %j', request); - return this.innerApiCalls.wait(request, options, wrappedCallback) - ?.then(([response, rawResponse, _]: [ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]) => { - this._log.info('wait response %j', rawResponse); - return [response, rawResponse, _]; - }); + return this.innerApiCalls + .wait(request, options, wrappedCallback) + ?.then( + ([response, rawResponse, _]: [ + LROperation< + protos.google.showcase.v1beta1.IWaitResponse, + protos.google.showcase.v1beta1.IWaitMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ]) => { + this._log.info('wait response %j', rawResponse); + return [response, rawResponse, _]; + }, + ); } -/** - * Check the status of the long running operation returned by `wait()`. - * @param {String} name - * The operation name that will be passed. - * @returns {Promise} - The promise which resolves to an object. - * The decoded operation object has result and metadata field to get information from. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/echo.wait.js - * region_tag:localhost_v1beta1_generated_Echo_Wait_async - */ - async checkWaitProgress(name: string): Promise>{ + /** + * Check the status of the long running operation returned by `wait()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/echo.wait.js + * region_tag:localhost_v1beta1_generated_Echo_Wait_async + */ + async checkWaitProgress( + name: string, + ): Promise< + LROperation< + protos.google.showcase.v1beta1.WaitResponse, + protos.google.showcase.v1beta1.WaitMetadata + > + > { this._log.info('wait long-running'); - const request = new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest({name}); + const request = + new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( + { name }, + ); const [operation] = await this.operationsClient.getOperation(request); - const decodeOperation = new this._gaxModule.Operation(operation, this.descriptors.longrunning.wait, this._gaxModule.createDefaultBackoffSettings()); - return decodeOperation as LROperation; + const decodeOperation = new this._gaxModule.Operation( + operation, + this.descriptors.longrunning.wait, + this._gaxModule.createDefaultBackoffSettings(), + ); + return decodeOperation as LROperation< + protos.google.showcase.v1beta1.WaitResponse, + protos.google.showcase.v1beta1.WaitMetadata + >; } - /** - * This is similar to the Expand method but instead of returning a stream of - * expanded words, this method returns a paged list of expanded words. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.content - * The string to expand. - * @param {number} request.pageSize - * The number of words to returned in each page. - * @param {string} request.pageToken - * The position of the page to be returned. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.showcase.v1beta1.EchoResponse|EchoResponse}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `pagedExpandAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * This is similar to the Expand method but instead of returning a stream of + * expanded words, this method returns a paged list of expanded words. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.content + * The string to expand. + * @param {number} request.pageSize + * The number of words to returned in each page. + * @param {string} request.pageToken + * The position of the page to be returned. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.showcase.v1beta1.EchoResponse|EchoResponse}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `pagedExpandAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ pagedExpand( - request?: protos.google.showcase.v1beta1.IPagedExpandRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IEchoResponse[], - protos.google.showcase.v1beta1.IPagedExpandRequest|null, - protos.google.showcase.v1beta1.IPagedExpandResponse - ]>; + request?: protos.google.showcase.v1beta1.IPagedExpandRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IEchoResponse[], + protos.google.showcase.v1beta1.IPagedExpandRequest | null, + protos.google.showcase.v1beta1.IPagedExpandResponse, + ] + >; pagedExpand( - request: protos.google.showcase.v1beta1.IPagedExpandRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.showcase.v1beta1.IPagedExpandRequest, - protos.google.showcase.v1beta1.IPagedExpandResponse|null|undefined, - protos.google.showcase.v1beta1.IEchoResponse>): void; + request: protos.google.showcase.v1beta1.IPagedExpandRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.showcase.v1beta1.IPagedExpandRequest, + protos.google.showcase.v1beta1.IPagedExpandResponse | null | undefined, + protos.google.showcase.v1beta1.IEchoResponse + >, + ): void; pagedExpand( - request: protos.google.showcase.v1beta1.IPagedExpandRequest, - callback: PaginationCallback< - protos.google.showcase.v1beta1.IPagedExpandRequest, - protos.google.showcase.v1beta1.IPagedExpandResponse|null|undefined, - protos.google.showcase.v1beta1.IEchoResponse>): void; + request: protos.google.showcase.v1beta1.IPagedExpandRequest, + callback: PaginationCallback< + protos.google.showcase.v1beta1.IPagedExpandRequest, + protos.google.showcase.v1beta1.IPagedExpandResponse | null | undefined, + protos.google.showcase.v1beta1.IEchoResponse + >, + ): void; pagedExpand( - request?: protos.google.showcase.v1beta1.IPagedExpandRequest, - optionsOrCallback?: CallOptions|PaginationCallback< + request?: protos.google.showcase.v1beta1.IPagedExpandRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.showcase.v1beta1.IPagedExpandRequest, - protos.google.showcase.v1beta1.IPagedExpandResponse|null|undefined, - protos.google.showcase.v1beta1.IEchoResponse>, - callback?: PaginationCallback< - protos.google.showcase.v1beta1.IPagedExpandRequest, - protos.google.showcase.v1beta1.IPagedExpandResponse|null|undefined, - protos.google.showcase.v1beta1.IEchoResponse>): - Promise<[ - protos.google.showcase.v1beta1.IEchoResponse[], - protos.google.showcase.v1beta1.IPagedExpandRequest|null, - protos.google.showcase.v1beta1.IPagedExpandResponse - ]>|void { + | protos.google.showcase.v1beta1.IPagedExpandResponse + | null + | undefined, + protos.google.showcase.v1beta1.IEchoResponse + >, + callback?: PaginationCallback< + protos.google.showcase.v1beta1.IPagedExpandRequest, + protos.google.showcase.v1beta1.IPagedExpandResponse | null | undefined, + protos.google.showcase.v1beta1.IEchoResponse + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IEchoResponse[], + protos.google.showcase.v1beta1.IPagedExpandRequest | null, + protos.google.showcase.v1beta1.IPagedExpandResponse, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.showcase.v1beta1.IPagedExpandRequest, - protos.google.showcase.v1beta1.IPagedExpandResponse|null|undefined, - protos.google.showcase.v1beta1.IEchoResponse>|undefined = callback + this.initialize().catch((err) => { + throw err; + }); + const wrappedCallback: + | PaginationCallback< + protos.google.showcase.v1beta1.IPagedExpandRequest, + | protos.google.showcase.v1beta1.IPagedExpandResponse + | null + | undefined, + protos.google.showcase.v1beta1.IEchoResponse + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('pagedExpand values %j', values); callback!(error, values, nextPageRequest, rawResponse); @@ -1205,96 +1541,102 @@ export class EchoClient { this._log.info('pagedExpand request %j', request); return this.innerApiCalls .pagedExpand(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.showcase.v1beta1.IEchoResponse[], - protos.google.showcase.v1beta1.IPagedExpandRequest|null, - protos.google.showcase.v1beta1.IPagedExpandResponse - ]) => { - this._log.info('pagedExpand values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.showcase.v1beta1.IEchoResponse[], + protos.google.showcase.v1beta1.IPagedExpandRequest | null, + protos.google.showcase.v1beta1.IPagedExpandResponse, + ]) => { + this._log.info('pagedExpand values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `pagedExpand`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.content - * The string to expand. - * @param {number} request.pageSize - * The number of words to returned in each page. - * @param {string} request.pageToken - * The position of the page to be returned. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.showcase.v1beta1.EchoResponse|EchoResponse} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `pagedExpandAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `pagedExpand`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.content + * The string to expand. + * @param {number} request.pageSize + * The number of words to returned in each page. + * @param {string} request.pageToken + * The position of the page to be returned. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.showcase.v1beta1.EchoResponse|EchoResponse} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `pagedExpandAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ pagedExpandStream( - request?: protos.google.showcase.v1beta1.IPagedExpandRequest, - options?: CallOptions): - Transform{ + request?: protos.google.showcase.v1beta1.IPagedExpandRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; const defaultCallSettings = this._defaults['pagedExpand']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('pagedExpand stream %j', request); return this.descriptors.page.pagedExpand.createStream( this.innerApiCalls.pagedExpand as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `pagedExpand`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.content - * The string to expand. - * @param {number} request.pageSize - * The number of words to returned in each page. - * @param {string} request.pageToken - * The position of the page to be returned. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.showcase.v1beta1.EchoResponse|EchoResponse}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/echo.paged_expand.js - * region_tag:localhost_v1beta1_generated_Echo_PagedExpand_async - */ + /** + * Equivalent to `pagedExpand`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.content + * The string to expand. + * @param {number} request.pageSize + * The number of words to returned in each page. + * @param {string} request.pageToken + * The position of the page to be returned. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.showcase.v1beta1.EchoResponse|EchoResponse}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/echo.paged_expand.js + * region_tag:localhost_v1beta1_generated_Echo_PagedExpand_async + */ pagedExpandAsync( - request?: protos.google.showcase.v1beta1.IPagedExpandRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.showcase.v1beta1.IPagedExpandRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; const defaultCallSettings = this._defaults['pagedExpand']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('pagedExpand iterate %j', request); return this.descriptors.page.pagedExpand.asyncIterate( this.innerApiCalls['pagedExpand'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } // -------------------- @@ -1309,7 +1651,7 @@ export class EchoClient { * @param {string} blueprint * @returns {string} Resource name string. */ - blueprintPath(session:string,test:string,blueprint:string) { + blueprintPath(session: string, test: string, blueprint: string) { return this.pathTemplates.blueprintPathTemplate.render({ session: session, test: test, @@ -1325,7 +1667,8 @@ export class EchoClient { * @returns {string} A string representing the session. */ matchSessionFromBlueprintName(blueprintName: string) { - return this.pathTemplates.blueprintPathTemplate.match(blueprintName).session; + return this.pathTemplates.blueprintPathTemplate.match(blueprintName) + .session; } /** @@ -1347,7 +1690,8 @@ export class EchoClient { * @returns {string} A string representing the blueprint. */ matchBlueprintFromBlueprintName(blueprintName: string) { - return this.pathTemplates.blueprintPathTemplate.match(blueprintName).blueprint; + return this.pathTemplates.blueprintPathTemplate.match(blueprintName) + .blueprint; } /** @@ -1356,7 +1700,7 @@ export class EchoClient { * @param {string} room * @returns {string} Resource name string. */ - roomPath(room:string) { + roomPath(room: string) { return this.pathTemplates.roomPathTemplate.render({ room: room, }); @@ -1380,7 +1724,7 @@ export class EchoClient { * @param {string} blurb * @returns {string} Resource name string. */ - roomBlurbPath(room:string,blurb:string) { + roomBlurbPath(room: string, blurb: string) { return this.pathTemplates.roomBlurbPathTemplate.render({ room: room, blurb: blurb, @@ -1417,7 +1761,11 @@ export class EchoClient { * @param {string} blurb * @returns {string} Resource name string. */ - roomBlurbsLegacyRoomBlurbPath(room:string,legacyRoom:string,blurb:string) { + roomBlurbsLegacyRoomBlurbPath( + room: string, + legacyRoom: string, + blurb: string, + ) { return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.render({ room: room, legacy_room: legacyRoom, @@ -1432,8 +1780,12 @@ export class EchoClient { * A fully-qualified path representing room_blurbs_legacy_room_blurb resource. * @returns {string} A string representing the room. */ - matchRoomFromRoomBlurbsLegacyRoomBlurbName(roomBlurbsLegacyRoomBlurbName: string) { - return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match(roomBlurbsLegacyRoomBlurbName).room; + matchRoomFromRoomBlurbsLegacyRoomBlurbName( + roomBlurbsLegacyRoomBlurbName: string, + ) { + return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match( + roomBlurbsLegacyRoomBlurbName, + ).room; } /** @@ -1443,8 +1795,12 @@ export class EchoClient { * A fully-qualified path representing room_blurbs_legacy_room_blurb resource. * @returns {string} A string representing the legacy_room. */ - matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName(roomBlurbsLegacyRoomBlurbName: string) { - return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match(roomBlurbsLegacyRoomBlurbName).legacy_room; + matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName( + roomBlurbsLegacyRoomBlurbName: string, + ) { + return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match( + roomBlurbsLegacyRoomBlurbName, + ).legacy_room; } /** @@ -1454,8 +1810,12 @@ export class EchoClient { * A fully-qualified path representing room_blurbs_legacy_room_blurb resource. * @returns {string} A string representing the blurb. */ - matchBlurbFromRoomBlurbsLegacyRoomBlurbName(roomBlurbsLegacyRoomBlurbName: string) { - return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match(roomBlurbsLegacyRoomBlurbName).blurb; + matchBlurbFromRoomBlurbsLegacyRoomBlurbName( + roomBlurbsLegacyRoomBlurbName: string, + ) { + return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match( + roomBlurbsLegacyRoomBlurbName, + ).blurb; } /** @@ -1464,7 +1824,7 @@ export class EchoClient { * @param {string} sequence * @returns {string} Resource name string. */ - sequencePath(sequence:string) { + sequencePath(sequence: string) { return this.pathTemplates.sequencePathTemplate.render({ sequence: sequence, }); @@ -1487,7 +1847,7 @@ export class EchoClient { * @param {string} sequence * @returns {string} Resource name string. */ - sequenceReportPath(sequence:string) { + sequenceReportPath(sequence: string) { return this.pathTemplates.sequenceReportPathTemplate.render({ sequence: sequence, }); @@ -1501,7 +1861,9 @@ export class EchoClient { * @returns {string} A string representing the sequence. */ matchSequenceFromSequenceReportName(sequenceReportName: string) { - return this.pathTemplates.sequenceReportPathTemplate.match(sequenceReportName).sequence; + return this.pathTemplates.sequenceReportPathTemplate.match( + sequenceReportName, + ).sequence; } /** @@ -1510,7 +1872,7 @@ export class EchoClient { * @param {string} session * @returns {string} Resource name string. */ - sessionPath(session:string) { + sessionPath(session: string) { return this.pathTemplates.sessionPathTemplate.render({ session: session, }); @@ -1534,7 +1896,7 @@ export class EchoClient { * @param {string} test * @returns {string} Resource name string. */ - testPath(session:string,test:string) { + testPath(session: string, test: string) { return this.pathTemplates.testPathTemplate.render({ session: session, test: test, @@ -1569,7 +1931,7 @@ export class EchoClient { * @param {string} user * @returns {string} Resource name string. */ - userPath(user:string) { + userPath(user: string) { return this.pathTemplates.userPathTemplate.render({ user: user, }); @@ -1593,7 +1955,7 @@ export class EchoClient { * @param {string} blurb * @returns {string} Resource name string. */ - userProfileBlurbPath(user:string,blurb:string) { + userProfileBlurbPath(user: string, blurb: string) { return this.pathTemplates.userProfileBlurbPathTemplate.render({ user: user, blurb: blurb, @@ -1608,7 +1970,9 @@ export class EchoClient { * @returns {string} A string representing the user. */ matchUserFromUserProfileBlurbName(userProfileBlurbName: string) { - return this.pathTemplates.userProfileBlurbPathTemplate.match(userProfileBlurbName).user; + return this.pathTemplates.userProfileBlurbPathTemplate.match( + userProfileBlurbName, + ).user; } /** @@ -1619,7 +1983,9 @@ export class EchoClient { * @returns {string} A string representing the blurb. */ matchBlurbFromUserProfileBlurbName(userProfileBlurbName: string) { - return this.pathTemplates.userProfileBlurbPathTemplate.match(userProfileBlurbName).blurb; + return this.pathTemplates.userProfileBlurbPathTemplate.match( + userProfileBlurbName, + ).blurb; } /** @@ -1630,12 +1996,18 @@ export class EchoClient { * @param {string} blurb * @returns {string} Resource name string. */ - userProfileBlurbsLegacyUserBlurbPath(user:string,legacyUser:string,blurb:string) { - return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.render({ - user: user, - legacy_user: legacyUser, - blurb: blurb, - }); + userProfileBlurbsLegacyUserBlurbPath( + user: string, + legacyUser: string, + blurb: string, + ) { + return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.render( + { + user: user, + legacy_user: legacyUser, + blurb: blurb, + }, + ); } /** @@ -1645,8 +2017,12 @@ export class EchoClient { * A fully-qualified path representing user_profile_blurbs_legacy_user_blurb resource. * @returns {string} A string representing the user. */ - matchUserFromUserProfileBlurbsLegacyUserBlurbName(userProfileBlurbsLegacyUserBlurbName: string) { - return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match(userProfileBlurbsLegacyUserBlurbName).user; + matchUserFromUserProfileBlurbsLegacyUserBlurbName( + userProfileBlurbsLegacyUserBlurbName: string, + ) { + return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match( + userProfileBlurbsLegacyUserBlurbName, + ).user; } /** @@ -1656,8 +2032,12 @@ export class EchoClient { * A fully-qualified path representing user_profile_blurbs_legacy_user_blurb resource. * @returns {string} A string representing the legacy_user. */ - matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName(userProfileBlurbsLegacyUserBlurbName: string) { - return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match(userProfileBlurbsLegacyUserBlurbName).legacy_user; + matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName( + userProfileBlurbsLegacyUserBlurbName: string, + ) { + return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match( + userProfileBlurbsLegacyUserBlurbName, + ).legacy_user; } /** @@ -1667,8 +2047,12 @@ export class EchoClient { * A fully-qualified path representing user_profile_blurbs_legacy_user_blurb resource. * @returns {string} A string representing the blurb. */ - matchBlurbFromUserProfileBlurbsLegacyUserBlurbName(userProfileBlurbsLegacyUserBlurbName: string) { - return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match(userProfileBlurbsLegacyUserBlurbName).blurb; + matchBlurbFromUserProfileBlurbsLegacyUserBlurbName( + userProfileBlurbsLegacyUserBlurbName: string, + ) { + return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match( + userProfileBlurbsLegacyUserBlurbName, + ).blurb; } /** @@ -1679,7 +2063,7 @@ export class EchoClient { */ close(): Promise { if (this.echoStub && !this._terminated) { - return this.echoStub.then(stub => { + return this.echoStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -1688,4 +2072,4 @@ export class EchoClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/core/generator/gapic-generator-typescript/baselines/disable-packing-test-esm/esm/src/v1beta1/identity_client.ts.baseline b/core/generator/gapic-generator-typescript/baselines/disable-packing-test-esm/esm/src/v1beta1/identity_client.ts.baseline index 9f09510c537b..d08c50524540 100644 --- a/core/generator/gapic-generator-typescript/baselines/disable-packing-test-esm/esm/src/v1beta1/identity_client.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/disable-packing-test-esm/esm/src/v1beta1/identity_client.ts.baseline @@ -18,15 +18,22 @@ /* global window */ import * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions, PaginationCallback, GaxCall} from 'google-gax'; -import {Transform} from 'stream'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + PaginationCallback, + GaxCall, +} from 'google-gax'; +import { Transform } from 'stream'; // @ts-ignore import type * as protos from '../../../protos/protos.js'; import * as identity_client_config from './identity_client_config.json'; import fs from 'fs'; import path from 'path'; -import {fileURLToPath} from 'url'; -import {getJSON} from '../json-helper.cjs'; +import { fileURLToPath } from 'url'; +import { getJSON } from '../json-helper.cjs'; // @ts-ignore const dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -35,16 +42,14 @@ const dirname = path.dirname(fileURLToPath(import.meta.url)); * `src/v1beta1/identity_client_config.json`. * This file defines retry strategy and timeouts for all API methods in this library. */ -const gapicConfig = getJSON( - path.join(dirname, 'identity_client_config.json') -); +const gapicConfig = getJSON(path.join(dirname, 'identity_client_config.json')); const jsonProtos = getJSON( - path.join(dirname, '..', '..', '..', 'protos/protos.json') + path.join(dirname, '..', '..', '..', 'protos/protos.json'), ); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; const version = getJSON( - path.join(dirname, '..', '..', '..', '..', 'package.json') + path.join(dirname, '..', '..', '..', '..', 'package.json'), ).version; /** @@ -59,7 +64,7 @@ export class IdentityClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('showcase'); @@ -71,9 +76,9 @@ export class IdentityClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; - identityStub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; + identityStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of IdentityClient. @@ -115,21 +120,42 @@ export class IdentityClient { * const client = new IdentityClient({fallback: 'rest'}, gax); * ``` */ - constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { // Ensure that options include all the required fields. const staticMembers = this.constructor as typeof IdentityClient; - if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { - throw new Error('Please set either universe_domain or universeDomain, but not both.'); + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); } - const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; - this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; this._servicePath = 'localhost'; - const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; - const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. if (servicePath !== this._servicePath && !('scopes' in opts)) { @@ -151,7 +177,7 @@ export class IdentityClient { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; @@ -168,10 +194,7 @@ export class IdentityClient { const isEsm = true; const isEsmString = isEsm ? '-esm' : '-cjs'; // Determine the client header string. - const clientHeader = [ - `gax/${this._gaxModule.version}`, - `gapic/${version}`, - ]; + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/{process.versions.node}${isEsmString}`); } else { @@ -179,7 +202,7 @@ export class IdentityClient { } if (!opts.fallback) { clientHeader.push(`grpc/${this._gaxGrpc.grpcVersion}`); - } else if (opts.fallback === 'rest' ) { + } else if (opts.fallback === 'rest') { clientHeader.push(`rest/${this._gaxGrpc.grpcVersion}`); } if (opts.libName && opts.libVersion) { @@ -187,59 +210,64 @@ export class IdentityClient { } // Load the applicable protos. - this._protos = this._gaxGrpc.loadProtoJSON(jsonProtos as gax.protobuf.INamespace); + this._protos = this._gaxGrpc.loadProtoJSON( + jsonProtos as gax.protobuf.INamespace, + ); // This API contains "path templates"; forward-slash-separated // identifiers to uniquely identify resources within the API. // Create useful helper objects for these. this.pathTemplates = { blueprintPathTemplate: new this._gaxModule.PathTemplate( - 'sessions/{session}/tests/{test}/blueprints/{blueprint}' - ), - roomPathTemplate: new this._gaxModule.PathTemplate( - 'rooms/{room}' + 'sessions/{session}/tests/{test}/blueprints/{blueprint}', ), + roomPathTemplate: new this._gaxModule.PathTemplate('rooms/{room}'), roomBlurbPathTemplate: new this._gaxModule.PathTemplate( - 'rooms/{room}/blurbs/{blurb}' + 'rooms/{room}/blurbs/{blurb}', ), roomBlurbsLegacyRoomBlurbPathTemplate: new this._gaxModule.PathTemplate( - 'rooms/{room}/blurbs/legacy/{legacy_room}.{blurb}' + 'rooms/{room}/blurbs/legacy/{legacy_room}.{blurb}', ), sequencePathTemplate: new this._gaxModule.PathTemplate( - 'sequences/{sequence}' + 'sequences/{sequence}', ), sequenceReportPathTemplate: new this._gaxModule.PathTemplate( - 'sequences/{sequence}/sequenceReport' + 'sequences/{sequence}/sequenceReport', ), sessionPathTemplate: new this._gaxModule.PathTemplate( - 'sessions/{session}' + 'sessions/{session}', ), testPathTemplate: new this._gaxModule.PathTemplate( - 'sessions/{session}/tests/{test}' - ), - userPathTemplate: new this._gaxModule.PathTemplate( - 'users/{user}' + 'sessions/{session}/tests/{test}', ), + userPathTemplate: new this._gaxModule.PathTemplate('users/{user}'), userProfileBlurbPathTemplate: new this._gaxModule.PathTemplate( - 'users/{user}/profile/blurbs/{blurb}' - ), - userProfileBlurbsLegacyUserBlurbPathTemplate: new this._gaxModule.PathTemplate( - 'users/{user}/profile/blurbs/legacy/{legacy_user}~{blurb}' + 'users/{user}/profile/blurbs/{blurb}', ), + userProfileBlurbsLegacyUserBlurbPathTemplate: + new this._gaxModule.PathTemplate( + 'users/{user}/profile/blurbs/legacy/{legacy_user}~{blurb}', + ), }; // Some of the methods on this service return "paged" results, // (e.g. 50 results at a time, with tokens to get subsequent // pages). Denote the keys used for pagination and results. this.descriptors.page = { - listUsers: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'users') + listUsers: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'users', + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.showcase.v1beta1.Identity', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.showcase.v1beta1.Identity', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + { 'x-goog-api-client': clientHeader.join(' ') }, + ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -270,37 +298,46 @@ export class IdentityClient { // Put together the "service stub" for // google.showcase.v1beta1.Identity. this.identityStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.showcase.v1beta1.Identity') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.showcase.v1beta1.Identity', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.showcase.v1beta1.Identity, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts, + this._providedCustomServicePath, + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const identityStubMethods = - ['createUser', 'getUser', 'updateUser', 'deleteUser', 'listUsers']; + const identityStubMethods = [ + 'createUser', + 'getUser', + 'updateUser', + 'deleteUser', + 'listUsers', + ]; for (const methodName of identityStubMethods) { const callPromise = this.identityStub.then( - stub => (...args: Array<{}>) => { - if (this._terminated) { - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error|null|undefined) => () => { + (stub) => + (...args: Array<{}>) => { + if (this._terminated) { + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { throw err; - }); + }, + ); - const descriptor = - this.descriptors.page[methodName] || - undefined; + const descriptor = this.descriptors.page[methodName] || undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -315,8 +352,14 @@ export class IdentityClient { * @returns {string} The DNS address for this service. */ static get servicePath() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'localhost'; } @@ -328,8 +371,14 @@ export class IdentityClient { * @returns {string} The DNS address for this service. */ static get apiEndpoint() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'localhost'; } @@ -369,8 +418,9 @@ export class IdentityClient { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId(callback?: Callback): - Promise|void { + getProjectId( + callback?: Callback, + ): Promise | void { if (callback) { this.auth.getProjectId(callback); return; @@ -381,454 +431,595 @@ export class IdentityClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Creates a user. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.showcase.v1beta1.User} request.user - * The user to create. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.User|User}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/identity.create_user.js - * region_tag:localhost_v1beta1_generated_Identity_CreateUser_async - */ + /** + * Creates a user. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.showcase.v1beta1.User} request.user + * The user to create. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.User|User}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/identity.create_user.js + * region_tag:localhost_v1beta1_generated_Identity_CreateUser_async + */ createUser( - request?: protos.google.showcase.v1beta1.ICreateUserRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IUser, - protos.google.showcase.v1beta1.ICreateUserRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.ICreateUserRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IUser, + protos.google.showcase.v1beta1.ICreateUserRequest | undefined, + {} | undefined, + ] + >; createUser( - request: protos.google.showcase.v1beta1.ICreateUserRequest, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.IUser, - protos.google.showcase.v1beta1.ICreateUserRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.ICreateUserRequest, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.IUser, + protos.google.showcase.v1beta1.ICreateUserRequest | null | undefined, + {} | null | undefined + >, + ): void; createUser( - request: protos.google.showcase.v1beta1.ICreateUserRequest, - callback: Callback< - protos.google.showcase.v1beta1.IUser, - protos.google.showcase.v1beta1.ICreateUserRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.ICreateUserRequest, + callback: Callback< + protos.google.showcase.v1beta1.IUser, + protos.google.showcase.v1beta1.ICreateUserRequest | null | undefined, + {} | null | undefined + >, + ): void; createUser( - request?: protos.google.showcase.v1beta1.ICreateUserRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.showcase.v1beta1.IUser, - protos.google.showcase.v1beta1.ICreateUserRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.showcase.v1beta1.ICreateUserRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.IUser, - protos.google.showcase.v1beta1.ICreateUserRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.IUser, - protos.google.showcase.v1beta1.ICreateUserRequest|undefined, {}|undefined - ]>|void { + protos.google.showcase.v1beta1.ICreateUserRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.IUser, + protos.google.showcase.v1beta1.ICreateUserRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IUser, + protos.google.showcase.v1beta1.ICreateUserRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('createUser request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.IUser, - protos.google.showcase.v1beta1.ICreateUserRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.IUser, + protos.google.showcase.v1beta1.ICreateUserRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createUser response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.createUser(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.IUser, - protos.google.showcase.v1beta1.ICreateUserRequest|undefined, {}|undefined - ]) => { - this._log.info('createUser response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createUser(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.IUser, + protos.google.showcase.v1beta1.ICreateUserRequest | undefined, + {} | undefined, + ]) => { + this._log.info('createUser response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Retrieves the User with the given uri. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * The resource name of the requested user. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.User|User}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/identity.get_user.js - * region_tag:localhost_v1beta1_generated_Identity_GetUser_async - */ + /** + * Retrieves the User with the given uri. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * The resource name of the requested user. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.User|User}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/identity.get_user.js + * region_tag:localhost_v1beta1_generated_Identity_GetUser_async + */ getUser( - request?: protos.google.showcase.v1beta1.IGetUserRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IUser, - protos.google.showcase.v1beta1.IGetUserRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IGetUserRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IUser, + protos.google.showcase.v1beta1.IGetUserRequest | undefined, + {} | undefined, + ] + >; getUser( - request: protos.google.showcase.v1beta1.IGetUserRequest, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.IUser, - protos.google.showcase.v1beta1.IGetUserRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IGetUserRequest, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.IUser, + protos.google.showcase.v1beta1.IGetUserRequest | null | undefined, + {} | null | undefined + >, + ): void; getUser( - request: protos.google.showcase.v1beta1.IGetUserRequest, - callback: Callback< - protos.google.showcase.v1beta1.IUser, - protos.google.showcase.v1beta1.IGetUserRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IGetUserRequest, + callback: Callback< + protos.google.showcase.v1beta1.IUser, + protos.google.showcase.v1beta1.IGetUserRequest | null | undefined, + {} | null | undefined + >, + ): void; getUser( - request?: protos.google.showcase.v1beta1.IGetUserRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.showcase.v1beta1.IUser, - protos.google.showcase.v1beta1.IGetUserRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.showcase.v1beta1.IGetUserRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.IUser, - protos.google.showcase.v1beta1.IGetUserRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.IUser, - protos.google.showcase.v1beta1.IGetUserRequest|undefined, {}|undefined - ]>|void { + protos.google.showcase.v1beta1.IGetUserRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.IUser, + protos.google.showcase.v1beta1.IGetUserRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IUser, + protos.google.showcase.v1beta1.IGetUserRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getUser request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.IUser, - protos.google.showcase.v1beta1.IGetUserRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.IUser, + protos.google.showcase.v1beta1.IGetUserRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getUser response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.getUser(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.IUser, - protos.google.showcase.v1beta1.IGetUserRequest|undefined, {}|undefined - ]) => { - this._log.info('getUser response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getUser(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.IUser, + protos.google.showcase.v1beta1.IGetUserRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getUser response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Updates a user. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.showcase.v1beta1.User} request.user - * The user to update. - * @param {google.protobuf.FieldMask} request.updateMask - * The field mask to determine which fields are to be updated. If empty, the - * server will assume all fields are to be updated. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.User|User}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/identity.update_user.js - * region_tag:localhost_v1beta1_generated_Identity_UpdateUser_async - */ + /** + * Updates a user. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.showcase.v1beta1.User} request.user + * The user to update. + * @param {google.protobuf.FieldMask} request.updateMask + * The field mask to determine which fields are to be updated. If empty, the + * server will assume all fields are to be updated. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.User|User}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/identity.update_user.js + * region_tag:localhost_v1beta1_generated_Identity_UpdateUser_async + */ updateUser( - request?: protos.google.showcase.v1beta1.IUpdateUserRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IUser, - protos.google.showcase.v1beta1.IUpdateUserRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IUpdateUserRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IUser, + protos.google.showcase.v1beta1.IUpdateUserRequest | undefined, + {} | undefined, + ] + >; updateUser( - request: protos.google.showcase.v1beta1.IUpdateUserRequest, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.IUser, - protos.google.showcase.v1beta1.IUpdateUserRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IUpdateUserRequest, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.IUser, + protos.google.showcase.v1beta1.IUpdateUserRequest | null | undefined, + {} | null | undefined + >, + ): void; updateUser( - request: protos.google.showcase.v1beta1.IUpdateUserRequest, - callback: Callback< - protos.google.showcase.v1beta1.IUser, - protos.google.showcase.v1beta1.IUpdateUserRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IUpdateUserRequest, + callback: Callback< + protos.google.showcase.v1beta1.IUser, + protos.google.showcase.v1beta1.IUpdateUserRequest | null | undefined, + {} | null | undefined + >, + ): void; updateUser( - request?: protos.google.showcase.v1beta1.IUpdateUserRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.showcase.v1beta1.IUser, - protos.google.showcase.v1beta1.IUpdateUserRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.showcase.v1beta1.IUpdateUserRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.IUser, - protos.google.showcase.v1beta1.IUpdateUserRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.IUser, - protos.google.showcase.v1beta1.IUpdateUserRequest|undefined, {}|undefined - ]>|void { + protos.google.showcase.v1beta1.IUpdateUserRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.IUser, + protos.google.showcase.v1beta1.IUpdateUserRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IUser, + protos.google.showcase.v1beta1.IUpdateUserRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'user.name': request.user!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'user.name': request.user!.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateUser request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.IUser, - protos.google.showcase.v1beta1.IUpdateUserRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.IUser, + protos.google.showcase.v1beta1.IUpdateUserRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateUser response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.updateUser(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.IUser, - protos.google.showcase.v1beta1.IUpdateUserRequest|undefined, {}|undefined - ]) => { - this._log.info('updateUser response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateUser(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.IUser, + protos.google.showcase.v1beta1.IUpdateUserRequest | undefined, + {} | undefined, + ]) => { + this._log.info('updateUser response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Deletes a user, their profile, and all of their authored messages. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * The resource name of the user to delete. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/identity.delete_user.js - * region_tag:localhost_v1beta1_generated_Identity_DeleteUser_async - */ + /** + * Deletes a user, their profile, and all of their authored messages. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * The resource name of the user to delete. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/identity.delete_user.js + * region_tag:localhost_v1beta1_generated_Identity_DeleteUser_async + */ deleteUser( - request?: protos.google.showcase.v1beta1.IDeleteUserRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteUserRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IDeleteUserRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteUserRequest | undefined, + {} | undefined, + ] + >; deleteUser( - request: protos.google.showcase.v1beta1.IDeleteUserRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteUserRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IDeleteUserRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteUserRequest | null | undefined, + {} | null | undefined + >, + ): void; deleteUser( - request: protos.google.showcase.v1beta1.IDeleteUserRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteUserRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IDeleteUserRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteUserRequest | null | undefined, + {} | null | undefined + >, + ): void; deleteUser( - request?: protos.google.showcase.v1beta1.IDeleteUserRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.showcase.v1beta1.IDeleteUserRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteUserRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteUserRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteUserRequest|undefined, {}|undefined - ]>|void { + protos.google.showcase.v1beta1.IDeleteUserRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteUserRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteUserRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('deleteUser request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteUserRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteUserRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteUser response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.deleteUser(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteUserRequest|undefined, {}|undefined - ]) => { - this._log.info('deleteUser response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteUser(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteUserRequest | undefined, + {} | undefined, + ]) => { + this._log.info('deleteUser response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } - /** - * Lists all users. - * - * @param {Object} request - * The request object that will be sent. - * @param {number} request.pageSize - * The maximum number of users to return. Server may return fewer users - * than requested. If unspecified, server will pick an appropriate default. - * @param {string} request.pageToken - * The value of google.showcase.v1beta1.ListUsersResponse.next_page_token - * returned from the previous call to - * `google.showcase.v1beta1.Identity\ListUsers` method. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.showcase.v1beta1.User|User}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `listUsersAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Lists all users. + * + * @param {Object} request + * The request object that will be sent. + * @param {number} request.pageSize + * The maximum number of users to return. Server may return fewer users + * than requested. If unspecified, server will pick an appropriate default. + * @param {string} request.pageToken + * The value of google.showcase.v1beta1.ListUsersResponse.next_page_token + * returned from the previous call to + * `google.showcase.v1beta1.Identity\ListUsers` method. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.showcase.v1beta1.User|User}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listUsersAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listUsers( - request?: protos.google.showcase.v1beta1.IListUsersRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IUser[], - protos.google.showcase.v1beta1.IListUsersRequest|null, - protos.google.showcase.v1beta1.IListUsersResponse - ]>; + request?: protos.google.showcase.v1beta1.IListUsersRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IUser[], + protos.google.showcase.v1beta1.IListUsersRequest | null, + protos.google.showcase.v1beta1.IListUsersResponse, + ] + >; listUsers( - request: protos.google.showcase.v1beta1.IListUsersRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.showcase.v1beta1.IListUsersRequest, - protos.google.showcase.v1beta1.IListUsersResponse|null|undefined, - protos.google.showcase.v1beta1.IUser>): void; + request: protos.google.showcase.v1beta1.IListUsersRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.showcase.v1beta1.IListUsersRequest, + protos.google.showcase.v1beta1.IListUsersResponse | null | undefined, + protos.google.showcase.v1beta1.IUser + >, + ): void; listUsers( - request: protos.google.showcase.v1beta1.IListUsersRequest, - callback: PaginationCallback< - protos.google.showcase.v1beta1.IListUsersRequest, - protos.google.showcase.v1beta1.IListUsersResponse|null|undefined, - protos.google.showcase.v1beta1.IUser>): void; + request: protos.google.showcase.v1beta1.IListUsersRequest, + callback: PaginationCallback< + protos.google.showcase.v1beta1.IListUsersRequest, + protos.google.showcase.v1beta1.IListUsersResponse | null | undefined, + protos.google.showcase.v1beta1.IUser + >, + ): void; listUsers( - request?: protos.google.showcase.v1beta1.IListUsersRequest, - optionsOrCallback?: CallOptions|PaginationCallback< - protos.google.showcase.v1beta1.IListUsersRequest, - protos.google.showcase.v1beta1.IListUsersResponse|null|undefined, - protos.google.showcase.v1beta1.IUser>, - callback?: PaginationCallback< + request?: protos.google.showcase.v1beta1.IListUsersRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.showcase.v1beta1.IListUsersRequest, - protos.google.showcase.v1beta1.IListUsersResponse|null|undefined, - protos.google.showcase.v1beta1.IUser>): - Promise<[ - protos.google.showcase.v1beta1.IUser[], - protos.google.showcase.v1beta1.IListUsersRequest|null, - protos.google.showcase.v1beta1.IListUsersResponse - ]>|void { + protos.google.showcase.v1beta1.IListUsersResponse | null | undefined, + protos.google.showcase.v1beta1.IUser + >, + callback?: PaginationCallback< + protos.google.showcase.v1beta1.IListUsersRequest, + protos.google.showcase.v1beta1.IListUsersResponse | null | undefined, + protos.google.showcase.v1beta1.IUser + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IUser[], + protos.google.showcase.v1beta1.IListUsersRequest | null, + protos.google.showcase.v1beta1.IListUsersResponse, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.showcase.v1beta1.IListUsersRequest, - protos.google.showcase.v1beta1.IListUsersResponse|null|undefined, - protos.google.showcase.v1beta1.IUser>|undefined = callback + this.initialize().catch((err) => { + throw err; + }); + const wrappedCallback: + | PaginationCallback< + protos.google.showcase.v1beta1.IListUsersRequest, + protos.google.showcase.v1beta1.IListUsersResponse | null | undefined, + protos.google.showcase.v1beta1.IUser + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listUsers values %j', values); callback!(error, values, nextPageRequest, rawResponse); @@ -837,98 +1028,104 @@ export class IdentityClient { this._log.info('listUsers request %j', request); return this.innerApiCalls .listUsers(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.showcase.v1beta1.IUser[], - protos.google.showcase.v1beta1.IListUsersRequest|null, - protos.google.showcase.v1beta1.IListUsersResponse - ]) => { - this._log.info('listUsers values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.showcase.v1beta1.IUser[], + protos.google.showcase.v1beta1.IListUsersRequest | null, + protos.google.showcase.v1beta1.IListUsersResponse, + ]) => { + this._log.info('listUsers values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listUsers`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {number} request.pageSize - * The maximum number of users to return. Server may return fewer users - * than requested. If unspecified, server will pick an appropriate default. - * @param {string} request.pageToken - * The value of google.showcase.v1beta1.ListUsersResponse.next_page_token - * returned from the previous call to - * `google.showcase.v1beta1.Identity\ListUsers` method. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.showcase.v1beta1.User|User} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `listUsersAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `listUsers`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {number} request.pageSize + * The maximum number of users to return. Server may return fewer users + * than requested. If unspecified, server will pick an appropriate default. + * @param {string} request.pageToken + * The value of google.showcase.v1beta1.ListUsersResponse.next_page_token + * returned from the previous call to + * `google.showcase.v1beta1.Identity\ListUsers` method. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.showcase.v1beta1.User|User} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listUsersAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listUsersStream( - request?: protos.google.showcase.v1beta1.IListUsersRequest, - options?: CallOptions): - Transform{ + request?: protos.google.showcase.v1beta1.IListUsersRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; const defaultCallSettings = this._defaults['listUsers']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listUsers stream %j', request); return this.descriptors.page.listUsers.createStream( this.innerApiCalls.listUsers as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listUsers`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {number} request.pageSize - * The maximum number of users to return. Server may return fewer users - * than requested. If unspecified, server will pick an appropriate default. - * @param {string} request.pageToken - * The value of google.showcase.v1beta1.ListUsersResponse.next_page_token - * returned from the previous call to - * `google.showcase.v1beta1.Identity\ListUsers` method. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.showcase.v1beta1.User|User}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/identity.list_users.js - * region_tag:localhost_v1beta1_generated_Identity_ListUsers_async - */ + /** + * Equivalent to `listUsers`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {number} request.pageSize + * The maximum number of users to return. Server may return fewer users + * than requested. If unspecified, server will pick an appropriate default. + * @param {string} request.pageToken + * The value of google.showcase.v1beta1.ListUsersResponse.next_page_token + * returned from the previous call to + * `google.showcase.v1beta1.Identity\ListUsers` method. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.showcase.v1beta1.User|User}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/identity.list_users.js + * region_tag:localhost_v1beta1_generated_Identity_ListUsers_async + */ listUsersAsync( - request?: protos.google.showcase.v1beta1.IListUsersRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.showcase.v1beta1.IListUsersRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; const defaultCallSettings = this._defaults['listUsers']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listUsers iterate %j', request); return this.descriptors.page.listUsers.asyncIterate( this.innerApiCalls['listUsers'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } // -------------------- @@ -943,7 +1140,7 @@ export class IdentityClient { * @param {string} blueprint * @returns {string} Resource name string. */ - blueprintPath(session:string,test:string,blueprint:string) { + blueprintPath(session: string, test: string, blueprint: string) { return this.pathTemplates.blueprintPathTemplate.render({ session: session, test: test, @@ -959,7 +1156,8 @@ export class IdentityClient { * @returns {string} A string representing the session. */ matchSessionFromBlueprintName(blueprintName: string) { - return this.pathTemplates.blueprintPathTemplate.match(blueprintName).session; + return this.pathTemplates.blueprintPathTemplate.match(blueprintName) + .session; } /** @@ -981,7 +1179,8 @@ export class IdentityClient { * @returns {string} A string representing the blueprint. */ matchBlueprintFromBlueprintName(blueprintName: string) { - return this.pathTemplates.blueprintPathTemplate.match(blueprintName).blueprint; + return this.pathTemplates.blueprintPathTemplate.match(blueprintName) + .blueprint; } /** @@ -990,7 +1189,7 @@ export class IdentityClient { * @param {string} room * @returns {string} Resource name string. */ - roomPath(room:string) { + roomPath(room: string) { return this.pathTemplates.roomPathTemplate.render({ room: room, }); @@ -1014,7 +1213,7 @@ export class IdentityClient { * @param {string} blurb * @returns {string} Resource name string. */ - roomBlurbPath(room:string,blurb:string) { + roomBlurbPath(room: string, blurb: string) { return this.pathTemplates.roomBlurbPathTemplate.render({ room: room, blurb: blurb, @@ -1051,7 +1250,11 @@ export class IdentityClient { * @param {string} blurb * @returns {string} Resource name string. */ - roomBlurbsLegacyRoomBlurbPath(room:string,legacyRoom:string,blurb:string) { + roomBlurbsLegacyRoomBlurbPath( + room: string, + legacyRoom: string, + blurb: string, + ) { return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.render({ room: room, legacy_room: legacyRoom, @@ -1066,8 +1269,12 @@ export class IdentityClient { * A fully-qualified path representing room_blurbs_legacy_room_blurb resource. * @returns {string} A string representing the room. */ - matchRoomFromRoomBlurbsLegacyRoomBlurbName(roomBlurbsLegacyRoomBlurbName: string) { - return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match(roomBlurbsLegacyRoomBlurbName).room; + matchRoomFromRoomBlurbsLegacyRoomBlurbName( + roomBlurbsLegacyRoomBlurbName: string, + ) { + return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match( + roomBlurbsLegacyRoomBlurbName, + ).room; } /** @@ -1077,8 +1284,12 @@ export class IdentityClient { * A fully-qualified path representing room_blurbs_legacy_room_blurb resource. * @returns {string} A string representing the legacy_room. */ - matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName(roomBlurbsLegacyRoomBlurbName: string) { - return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match(roomBlurbsLegacyRoomBlurbName).legacy_room; + matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName( + roomBlurbsLegacyRoomBlurbName: string, + ) { + return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match( + roomBlurbsLegacyRoomBlurbName, + ).legacy_room; } /** @@ -1088,8 +1299,12 @@ export class IdentityClient { * A fully-qualified path representing room_blurbs_legacy_room_blurb resource. * @returns {string} A string representing the blurb. */ - matchBlurbFromRoomBlurbsLegacyRoomBlurbName(roomBlurbsLegacyRoomBlurbName: string) { - return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match(roomBlurbsLegacyRoomBlurbName).blurb; + matchBlurbFromRoomBlurbsLegacyRoomBlurbName( + roomBlurbsLegacyRoomBlurbName: string, + ) { + return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match( + roomBlurbsLegacyRoomBlurbName, + ).blurb; } /** @@ -1098,7 +1313,7 @@ export class IdentityClient { * @param {string} sequence * @returns {string} Resource name string. */ - sequencePath(sequence:string) { + sequencePath(sequence: string) { return this.pathTemplates.sequencePathTemplate.render({ sequence: sequence, }); @@ -1121,7 +1336,7 @@ export class IdentityClient { * @param {string} sequence * @returns {string} Resource name string. */ - sequenceReportPath(sequence:string) { + sequenceReportPath(sequence: string) { return this.pathTemplates.sequenceReportPathTemplate.render({ sequence: sequence, }); @@ -1135,7 +1350,9 @@ export class IdentityClient { * @returns {string} A string representing the sequence. */ matchSequenceFromSequenceReportName(sequenceReportName: string) { - return this.pathTemplates.sequenceReportPathTemplate.match(sequenceReportName).sequence; + return this.pathTemplates.sequenceReportPathTemplate.match( + sequenceReportName, + ).sequence; } /** @@ -1144,7 +1361,7 @@ export class IdentityClient { * @param {string} session * @returns {string} Resource name string. */ - sessionPath(session:string) { + sessionPath(session: string) { return this.pathTemplates.sessionPathTemplate.render({ session: session, }); @@ -1168,7 +1385,7 @@ export class IdentityClient { * @param {string} test * @returns {string} Resource name string. */ - testPath(session:string,test:string) { + testPath(session: string, test: string) { return this.pathTemplates.testPathTemplate.render({ session: session, test: test, @@ -1203,7 +1420,7 @@ export class IdentityClient { * @param {string} user * @returns {string} Resource name string. */ - userPath(user:string) { + userPath(user: string) { return this.pathTemplates.userPathTemplate.render({ user: user, }); @@ -1227,7 +1444,7 @@ export class IdentityClient { * @param {string} blurb * @returns {string} Resource name string. */ - userProfileBlurbPath(user:string,blurb:string) { + userProfileBlurbPath(user: string, blurb: string) { return this.pathTemplates.userProfileBlurbPathTemplate.render({ user: user, blurb: blurb, @@ -1242,7 +1459,9 @@ export class IdentityClient { * @returns {string} A string representing the user. */ matchUserFromUserProfileBlurbName(userProfileBlurbName: string) { - return this.pathTemplates.userProfileBlurbPathTemplate.match(userProfileBlurbName).user; + return this.pathTemplates.userProfileBlurbPathTemplate.match( + userProfileBlurbName, + ).user; } /** @@ -1253,7 +1472,9 @@ export class IdentityClient { * @returns {string} A string representing the blurb. */ matchBlurbFromUserProfileBlurbName(userProfileBlurbName: string) { - return this.pathTemplates.userProfileBlurbPathTemplate.match(userProfileBlurbName).blurb; + return this.pathTemplates.userProfileBlurbPathTemplate.match( + userProfileBlurbName, + ).blurb; } /** @@ -1264,12 +1485,18 @@ export class IdentityClient { * @param {string} blurb * @returns {string} Resource name string. */ - userProfileBlurbsLegacyUserBlurbPath(user:string,legacyUser:string,blurb:string) { - return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.render({ - user: user, - legacy_user: legacyUser, - blurb: blurb, - }); + userProfileBlurbsLegacyUserBlurbPath( + user: string, + legacyUser: string, + blurb: string, + ) { + return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.render( + { + user: user, + legacy_user: legacyUser, + blurb: blurb, + }, + ); } /** @@ -1279,8 +1506,12 @@ export class IdentityClient { * A fully-qualified path representing user_profile_blurbs_legacy_user_blurb resource. * @returns {string} A string representing the user. */ - matchUserFromUserProfileBlurbsLegacyUserBlurbName(userProfileBlurbsLegacyUserBlurbName: string) { - return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match(userProfileBlurbsLegacyUserBlurbName).user; + matchUserFromUserProfileBlurbsLegacyUserBlurbName( + userProfileBlurbsLegacyUserBlurbName: string, + ) { + return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match( + userProfileBlurbsLegacyUserBlurbName, + ).user; } /** @@ -1290,8 +1521,12 @@ export class IdentityClient { * A fully-qualified path representing user_profile_blurbs_legacy_user_blurb resource. * @returns {string} A string representing the legacy_user. */ - matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName(userProfileBlurbsLegacyUserBlurbName: string) { - return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match(userProfileBlurbsLegacyUserBlurbName).legacy_user; + matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName( + userProfileBlurbsLegacyUserBlurbName: string, + ) { + return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match( + userProfileBlurbsLegacyUserBlurbName, + ).legacy_user; } /** @@ -1301,8 +1536,12 @@ export class IdentityClient { * A fully-qualified path representing user_profile_blurbs_legacy_user_blurb resource. * @returns {string} A string representing the blurb. */ - matchBlurbFromUserProfileBlurbsLegacyUserBlurbName(userProfileBlurbsLegacyUserBlurbName: string) { - return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match(userProfileBlurbsLegacyUserBlurbName).blurb; + matchBlurbFromUserProfileBlurbsLegacyUserBlurbName( + userProfileBlurbsLegacyUserBlurbName: string, + ) { + return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match( + userProfileBlurbsLegacyUserBlurbName, + ).blurb; } /** @@ -1313,7 +1552,7 @@ export class IdentityClient { */ close(): Promise { if (this.identityStub && !this._terminated) { - return this.identityStub.then(stub => { + return this.identityStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -1321,4 +1560,4 @@ export class IdentityClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/core/generator/gapic-generator-typescript/baselines/disable-packing-test-esm/esm/src/v1beta1/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/disable-packing-test-esm/esm/src/v1beta1/index.ts.baseline index 3a94be5d9834..4470211c9331 100644 --- a/core/generator/gapic-generator-typescript/baselines/disable-packing-test-esm/esm/src/v1beta1/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/disable-packing-test-esm/esm/src/v1beta1/index.ts.baseline @@ -16,9 +16,9 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -export {ComplianceClient} from './compliance_client.js'; -export {EchoClient} from './echo_client.js'; -export {IdentityClient} from './identity_client.js'; -export {MessagingClient} from './messaging_client.js'; -export {SequenceServiceClient} from './sequence_service_client.js'; -export {TestingClient} from './testing_client.js'; +export { ComplianceClient } from './compliance_client.js'; +export { EchoClient } from './echo_client.js'; +export { IdentityClient } from './identity_client.js'; +export { MessagingClient } from './messaging_client.js'; +export { SequenceServiceClient } from './sequence_service_client.js'; +export { TestingClient } from './testing_client.js'; diff --git a/core/generator/gapic-generator-typescript/baselines/disable-packing-test-esm/esm/src/v1beta1/messaging_client.ts.baseline b/core/generator/gapic-generator-typescript/baselines/disable-packing-test-esm/esm/src/v1beta1/messaging_client.ts.baseline index cd0dce341068..f7f726872eaf 100644 --- a/core/generator/gapic-generator-typescript/baselines/disable-packing-test-esm/esm/src/v1beta1/messaging_client.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/disable-packing-test-esm/esm/src/v1beta1/messaging_client.ts.baseline @@ -18,15 +18,24 @@ /* global window */ import * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions, GrpcClientOptions, LROperation, PaginationCallback, GaxCall} from 'google-gax'; -import {Transform, PassThrough} from 'stream'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + GrpcClientOptions, + LROperation, + PaginationCallback, + GaxCall, +} from 'google-gax'; +import { Transform, PassThrough } from 'stream'; // @ts-ignore import type * as protos from '../../../protos/protos.js'; import * as messaging_client_config from './messaging_client_config.json'; import fs from 'fs'; import path from 'path'; -import {fileURLToPath} from 'url'; -import {getJSON} from '../json-helper.cjs'; +import { fileURLToPath } from 'url'; +import { getJSON } from '../json-helper.cjs'; // @ts-ignore const dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -35,16 +44,14 @@ const dirname = path.dirname(fileURLToPath(import.meta.url)); * `src/v1beta1/messaging_client_config.json`. * This file defines retry strategy and timeouts for all API methods in this library. */ -const gapicConfig = getJSON( - path.join(dirname, 'messaging_client_config.json') -); +const gapicConfig = getJSON(path.join(dirname, 'messaging_client_config.json')); const jsonProtos = getJSON( - path.join(dirname, '..', '..', '..', 'protos/protos.json') + path.join(dirname, '..', '..', '..', 'protos/protos.json'), ); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; const version = getJSON( - path.join(dirname, '..', '..', '..', '..', 'package.json') + path.join(dirname, '..', '..', '..', '..', 'package.json'), ).version; /** @@ -62,7 +69,7 @@ export class MessagingClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('showcase'); @@ -74,10 +81,10 @@ export class MessagingClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; operationsClient: gax.OperationsClient; - messagingStub?: Promise<{[name: string]: Function}>; + messagingStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of MessagingClient. @@ -119,21 +126,42 @@ export class MessagingClient { * const client = new MessagingClient({fallback: 'rest'}, gax); * ``` */ - constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { // Ensure that options include all the required fields. const staticMembers = this.constructor as typeof MessagingClient; - if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { - throw new Error('Please set either universe_domain or universeDomain, but not both.'); + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); } - const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; - this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; this._servicePath = 'localhost'; - const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; - const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. if (servicePath !== this._servicePath && !('scopes' in opts)) { @@ -155,7 +183,7 @@ export class MessagingClient { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; @@ -172,10 +200,7 @@ export class MessagingClient { const isEsm = true; const isEsmString = isEsm ? '-esm' : '-cjs'; // Determine the client header string. - const clientHeader = [ - `gax/${this._gaxModule.version}`, - `gapic/${version}`, - ]; + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/{process.versions.node}${isEsmString}`); } else { @@ -183,7 +208,7 @@ export class MessagingClient { } if (!opts.fallback) { clientHeader.push(`grpc/${this._gaxGrpc.grpcVersion}`); - } else if (opts.fallback === 'rest' ) { + } else if (opts.fallback === 'rest') { clientHeader.push(`rest/${this._gaxGrpc.grpcVersion}`); } if (opts.libName && opts.libVersion) { @@ -191,63 +216,79 @@ export class MessagingClient { } // Load the applicable protos. - this._protos = this._gaxGrpc.loadProtoJSON(jsonProtos as gax.protobuf.INamespace); + this._protos = this._gaxGrpc.loadProtoJSON( + jsonProtos as gax.protobuf.INamespace, + ); // This API contains "path templates"; forward-slash-separated // identifiers to uniquely identify resources within the API. // Create useful helper objects for these. this.pathTemplates = { blueprintPathTemplate: new this._gaxModule.PathTemplate( - 'sessions/{session}/tests/{test}/blueprints/{blueprint}' - ), - roomPathTemplate: new this._gaxModule.PathTemplate( - 'rooms/{room}' + 'sessions/{session}/tests/{test}/blueprints/{blueprint}', ), + roomPathTemplate: new this._gaxModule.PathTemplate('rooms/{room}'), roomBlurbPathTemplate: new this._gaxModule.PathTemplate( - 'rooms/{room}/blurbs/{blurb}' + 'rooms/{room}/blurbs/{blurb}', ), roomBlurbsLegacyRoomBlurbPathTemplate: new this._gaxModule.PathTemplate( - 'rooms/{room}/blurbs/legacy/{legacy_room}.{blurb}' + 'rooms/{room}/blurbs/legacy/{legacy_room}.{blurb}', ), sequencePathTemplate: new this._gaxModule.PathTemplate( - 'sequences/{sequence}' + 'sequences/{sequence}', ), sequenceReportPathTemplate: new this._gaxModule.PathTemplate( - 'sequences/{sequence}/sequenceReport' + 'sequences/{sequence}/sequenceReport', ), sessionPathTemplate: new this._gaxModule.PathTemplate( - 'sessions/{session}' + 'sessions/{session}', ), testPathTemplate: new this._gaxModule.PathTemplate( - 'sessions/{session}/tests/{test}' - ), - userPathTemplate: new this._gaxModule.PathTemplate( - 'users/{user}' + 'sessions/{session}/tests/{test}', ), + userPathTemplate: new this._gaxModule.PathTemplate('users/{user}'), userProfileBlurbPathTemplate: new this._gaxModule.PathTemplate( - 'users/{user}/profile/blurbs/{blurb}' - ), - userProfileBlurbsLegacyUserBlurbPathTemplate: new this._gaxModule.PathTemplate( - 'users/{user}/profile/blurbs/legacy/{legacy_user}~{blurb}' + 'users/{user}/profile/blurbs/{blurb}', ), + userProfileBlurbsLegacyUserBlurbPathTemplate: + new this._gaxModule.PathTemplate( + 'users/{user}/profile/blurbs/legacy/{legacy_user}~{blurb}', + ), }; // Some of the methods on this service return "paged" results, // (e.g. 50 results at a time, with tokens to get subsequent // pages). Denote the keys used for pagination and results. this.descriptors.page = { - listRooms: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'rooms'), - listBlurbs: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'blurbs') + listRooms: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'rooms', + ), + listBlurbs: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'blurbs', + ), }; // Some of the methods on this service provide streaming responses. // Provide descriptors for these. this.descriptors.stream = { - streamBlurbs: new this._gaxModule.StreamDescriptor(this._gaxModule.StreamType.SERVER_STREAMING, !!opts.fallback, !!opts.gaxServerStreamingRetries), - sendBlurbs: new this._gaxModule.StreamDescriptor(this._gaxModule.StreamType.CLIENT_STREAMING, !!opts.fallback), - connect: new this._gaxModule.StreamDescriptor(this._gaxModule.StreamType.BIDI_STREAMING, !!opts.fallback, !!opts.gaxServerStreamingRetries) + streamBlurbs: new this._gaxModule.StreamDescriptor( + this._gaxModule.StreamType.SERVER_STREAMING, + !!opts.fallback, + !!opts.gaxServerStreamingRetries, + ), + sendBlurbs: new this._gaxModule.StreamDescriptor( + this._gaxModule.StreamType.CLIENT_STREAMING, + !!opts.fallback, + ), + connect: new this._gaxModule.StreamDescriptor( + this._gaxModule.StreamType.BIDI_STREAMING, + !!opts.fallback, + !!opts.gaxServerStreamingRetries, + ), }; const protoFilesRoot = this._gaxModule.protobufFromJSON(jsonProtos); @@ -256,29 +297,37 @@ export class MessagingClient { // rather than holding a request open. const lroOptions: GrpcClientOptions = { auth: this.auth, - grpc: 'grpc' in this._gaxGrpc ? this._gaxGrpc.grpc : undefined + grpc: 'grpc' in this._gaxGrpc ? this._gaxGrpc.grpc : undefined, }; if (opts.fallback === 'rest') { lroOptions.protoJson = protoFilesRoot; lroOptions.httpRules = []; } - this.operationsClient = this._gaxModule.lro(lroOptions).operationsClient(opts); + this.operationsClient = this._gaxModule + .lro(lroOptions) + .operationsClient(opts); const searchBlurbsResponse = protoFilesRoot.lookup( - '.google.showcase.v1beta1.SearchBlurbsResponse') as gax.protobuf.Type; + '.google.showcase.v1beta1.SearchBlurbsResponse', + ) as gax.protobuf.Type; const searchBlurbsMetadata = protoFilesRoot.lookup( - '.google.showcase.v1beta1.SearchBlurbsMetadata') as gax.protobuf.Type; + '.google.showcase.v1beta1.SearchBlurbsMetadata', + ) as gax.protobuf.Type; this.descriptors.longrunning = { searchBlurbs: new this._gaxModule.LongrunningDescriptor( this.operationsClient, searchBlurbsResponse.decode.bind(searchBlurbsResponse), - searchBlurbsMetadata.decode.bind(searchBlurbsMetadata)) + searchBlurbsMetadata.decode.bind(searchBlurbsMetadata), + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.showcase.v1beta1.Messaging', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.showcase.v1beta1.Messaging', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + { 'x-goog-api-client': clientHeader.join(' ') }, + ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -309,35 +358,60 @@ export class MessagingClient { // Put together the "service stub" for // google.showcase.v1beta1.Messaging. this.messagingStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.showcase.v1beta1.Messaging') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.showcase.v1beta1.Messaging', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.showcase.v1beta1.Messaging, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts, + this._providedCustomServicePath, + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const messagingStubMethods = - ['createRoom', 'getRoom', 'updateRoom', 'deleteRoom', 'listRooms', 'createBlurb', 'getBlurb', 'updateBlurb', 'deleteBlurb', 'listBlurbs', 'searchBlurbs', 'streamBlurbs', 'sendBlurbs', 'connect']; + const messagingStubMethods = [ + 'createRoom', + 'getRoom', + 'updateRoom', + 'deleteRoom', + 'listRooms', + 'createBlurb', + 'getBlurb', + 'updateBlurb', + 'deleteBlurb', + 'listBlurbs', + 'searchBlurbs', + 'streamBlurbs', + 'sendBlurbs', + 'connect', + ]; for (const methodName of messagingStubMethods) { const callPromise = this.messagingStub.then( - stub => (...args: Array<{}>) => { - if (this._terminated) { - if (methodName in this.descriptors.stream) { - const stream = new PassThrough({objectMode: true}); - setImmediate(() => { - stream.emit('error', new this._gaxModule.GoogleError('The client has already been closed.')); - }); - return stream; + (stub) => + (...args: Array<{}>) => { + if (this._terminated) { + if (methodName in this.descriptors.stream) { + const stream = new PassThrough({ objectMode: true }); + setImmediate(() => { + stream.emit( + 'error', + new this._gaxModule.GoogleError( + 'The client has already been closed.', + ), + ); + }); + return stream; + } + return Promise.reject('The client has already been closed.'); } - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error|null|undefined) => () => { + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { throw err; - }); + }, + ); const descriptor = this.descriptors.page[methodName] || @@ -348,7 +422,7 @@ export class MessagingClient { callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -363,8 +437,14 @@ export class MessagingClient { * @returns {string} The DNS address for this service. */ static get servicePath() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'localhost'; } @@ -376,8 +456,14 @@ export class MessagingClient { * @returns {string} The DNS address for this service. */ static get apiEndpoint() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'localhost'; } @@ -417,8 +503,9 @@ export class MessagingClient { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId(callback?: Callback): - Promise|void { + getProjectId( + callback?: Callback, + ): Promise | void { if (callback) { this.auth.getProjectId(callback); return; @@ -429,1064 +516,1400 @@ export class MessagingClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Creates a room. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.showcase.v1beta1.Room} request.room - * The room to create. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.Room|Room}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/messaging.create_room.js - * region_tag:localhost_v1beta1_generated_Messaging_CreateRoom_async - */ + /** + * Creates a room. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.showcase.v1beta1.Room} request.room + * The room to create. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.Room|Room}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/messaging.create_room.js + * region_tag:localhost_v1beta1_generated_Messaging_CreateRoom_async + */ createRoom( - request?: protos.google.showcase.v1beta1.ICreateRoomRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IRoom, - protos.google.showcase.v1beta1.ICreateRoomRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.ICreateRoomRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IRoom, + protos.google.showcase.v1beta1.ICreateRoomRequest | undefined, + {} | undefined, + ] + >; createRoom( - request: protos.google.showcase.v1beta1.ICreateRoomRequest, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.IRoom, - protos.google.showcase.v1beta1.ICreateRoomRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.ICreateRoomRequest, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.IRoom, + protos.google.showcase.v1beta1.ICreateRoomRequest | null | undefined, + {} | null | undefined + >, + ): void; createRoom( - request: protos.google.showcase.v1beta1.ICreateRoomRequest, - callback: Callback< - protos.google.showcase.v1beta1.IRoom, - protos.google.showcase.v1beta1.ICreateRoomRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.ICreateRoomRequest, + callback: Callback< + protos.google.showcase.v1beta1.IRoom, + protos.google.showcase.v1beta1.ICreateRoomRequest | null | undefined, + {} | null | undefined + >, + ): void; createRoom( - request?: protos.google.showcase.v1beta1.ICreateRoomRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.showcase.v1beta1.IRoom, - protos.google.showcase.v1beta1.ICreateRoomRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.showcase.v1beta1.ICreateRoomRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.IRoom, - protos.google.showcase.v1beta1.ICreateRoomRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.IRoom, - protos.google.showcase.v1beta1.ICreateRoomRequest|undefined, {}|undefined - ]>|void { + protos.google.showcase.v1beta1.ICreateRoomRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.IRoom, + protos.google.showcase.v1beta1.ICreateRoomRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IRoom, + protos.google.showcase.v1beta1.ICreateRoomRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('createRoom request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.IRoom, - protos.google.showcase.v1beta1.ICreateRoomRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.IRoom, + protos.google.showcase.v1beta1.ICreateRoomRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createRoom response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.createRoom(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.IRoom, - protos.google.showcase.v1beta1.ICreateRoomRequest|undefined, {}|undefined - ]) => { - this._log.info('createRoom response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createRoom(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.IRoom, + protos.google.showcase.v1beta1.ICreateRoomRequest | undefined, + {} | undefined, + ]) => { + this._log.info('createRoom response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Retrieves the Room with the given resource name. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * The resource name of the requested room. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.Room|Room}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/messaging.get_room.js - * region_tag:localhost_v1beta1_generated_Messaging_GetRoom_async - */ + /** + * Retrieves the Room with the given resource name. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * The resource name of the requested room. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.Room|Room}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/messaging.get_room.js + * region_tag:localhost_v1beta1_generated_Messaging_GetRoom_async + */ getRoom( - request?: protos.google.showcase.v1beta1.IGetRoomRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IRoom, - protos.google.showcase.v1beta1.IGetRoomRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IGetRoomRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IRoom, + protos.google.showcase.v1beta1.IGetRoomRequest | undefined, + {} | undefined, + ] + >; getRoom( - request: protos.google.showcase.v1beta1.IGetRoomRequest, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.IRoom, - protos.google.showcase.v1beta1.IGetRoomRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IGetRoomRequest, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.IRoom, + protos.google.showcase.v1beta1.IGetRoomRequest | null | undefined, + {} | null | undefined + >, + ): void; getRoom( - request: protos.google.showcase.v1beta1.IGetRoomRequest, - callback: Callback< - protos.google.showcase.v1beta1.IRoom, - protos.google.showcase.v1beta1.IGetRoomRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IGetRoomRequest, + callback: Callback< + protos.google.showcase.v1beta1.IRoom, + protos.google.showcase.v1beta1.IGetRoomRequest | null | undefined, + {} | null | undefined + >, + ): void; getRoom( - request?: protos.google.showcase.v1beta1.IGetRoomRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.showcase.v1beta1.IRoom, - protos.google.showcase.v1beta1.IGetRoomRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.showcase.v1beta1.IGetRoomRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.IRoom, - protos.google.showcase.v1beta1.IGetRoomRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.IRoom, - protos.google.showcase.v1beta1.IGetRoomRequest|undefined, {}|undefined - ]>|void { + protos.google.showcase.v1beta1.IGetRoomRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.IRoom, + protos.google.showcase.v1beta1.IGetRoomRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IRoom, + protos.google.showcase.v1beta1.IGetRoomRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getRoom request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.IRoom, - protos.google.showcase.v1beta1.IGetRoomRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.IRoom, + protos.google.showcase.v1beta1.IGetRoomRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getRoom response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.getRoom(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.IRoom, - protos.google.showcase.v1beta1.IGetRoomRequest|undefined, {}|undefined - ]) => { - this._log.info('getRoom response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getRoom(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.IRoom, + protos.google.showcase.v1beta1.IGetRoomRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getRoom response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Updates a room. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.showcase.v1beta1.Room} request.room - * The room to update. - * @param {google.protobuf.FieldMask} request.updateMask - * The field mask to determine which fields are to be updated. If empty, the - * server will assume all fields are to be updated. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.Room|Room}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/messaging.update_room.js - * region_tag:localhost_v1beta1_generated_Messaging_UpdateRoom_async - */ + /** + * Updates a room. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.showcase.v1beta1.Room} request.room + * The room to update. + * @param {google.protobuf.FieldMask} request.updateMask + * The field mask to determine which fields are to be updated. If empty, the + * server will assume all fields are to be updated. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.Room|Room}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/messaging.update_room.js + * region_tag:localhost_v1beta1_generated_Messaging_UpdateRoom_async + */ updateRoom( - request?: protos.google.showcase.v1beta1.IUpdateRoomRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IRoom, - protos.google.showcase.v1beta1.IUpdateRoomRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IUpdateRoomRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IRoom, + protos.google.showcase.v1beta1.IUpdateRoomRequest | undefined, + {} | undefined, + ] + >; updateRoom( - request: protos.google.showcase.v1beta1.IUpdateRoomRequest, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.IRoom, - protos.google.showcase.v1beta1.IUpdateRoomRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IUpdateRoomRequest, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.IRoom, + protos.google.showcase.v1beta1.IUpdateRoomRequest | null | undefined, + {} | null | undefined + >, + ): void; updateRoom( - request: protos.google.showcase.v1beta1.IUpdateRoomRequest, - callback: Callback< - protos.google.showcase.v1beta1.IRoom, - protos.google.showcase.v1beta1.IUpdateRoomRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IUpdateRoomRequest, + callback: Callback< + protos.google.showcase.v1beta1.IRoom, + protos.google.showcase.v1beta1.IUpdateRoomRequest | null | undefined, + {} | null | undefined + >, + ): void; updateRoom( - request?: protos.google.showcase.v1beta1.IUpdateRoomRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.showcase.v1beta1.IRoom, - protos.google.showcase.v1beta1.IUpdateRoomRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.showcase.v1beta1.IUpdateRoomRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.IRoom, - protos.google.showcase.v1beta1.IUpdateRoomRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.IRoom, - protos.google.showcase.v1beta1.IUpdateRoomRequest|undefined, {}|undefined - ]>|void { + protos.google.showcase.v1beta1.IUpdateRoomRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.IRoom, + protos.google.showcase.v1beta1.IUpdateRoomRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IRoom, + protos.google.showcase.v1beta1.IUpdateRoomRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'room.name': request.room!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'room.name': request.room!.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateRoom request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.IRoom, - protos.google.showcase.v1beta1.IUpdateRoomRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.IRoom, + protos.google.showcase.v1beta1.IUpdateRoomRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateRoom response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.updateRoom(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.IRoom, - protos.google.showcase.v1beta1.IUpdateRoomRequest|undefined, {}|undefined - ]) => { - this._log.info('updateRoom response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateRoom(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.IRoom, + protos.google.showcase.v1beta1.IUpdateRoomRequest | undefined, + {} | undefined, + ]) => { + this._log.info('updateRoom response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Deletes a room and all of its blurbs. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * The resource name of the requested room. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/messaging.delete_room.js - * region_tag:localhost_v1beta1_generated_Messaging_DeleteRoom_async - */ + /** + * Deletes a room and all of its blurbs. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * The resource name of the requested room. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/messaging.delete_room.js + * region_tag:localhost_v1beta1_generated_Messaging_DeleteRoom_async + */ deleteRoom( - request?: protos.google.showcase.v1beta1.IDeleteRoomRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteRoomRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IDeleteRoomRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteRoomRequest | undefined, + {} | undefined, + ] + >; deleteRoom( - request: protos.google.showcase.v1beta1.IDeleteRoomRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteRoomRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IDeleteRoomRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteRoomRequest | null | undefined, + {} | null | undefined + >, + ): void; deleteRoom( - request: protos.google.showcase.v1beta1.IDeleteRoomRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteRoomRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IDeleteRoomRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteRoomRequest | null | undefined, + {} | null | undefined + >, + ): void; deleteRoom( - request?: protos.google.showcase.v1beta1.IDeleteRoomRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteRoomRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.showcase.v1beta1.IDeleteRoomRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteRoomRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteRoomRequest|undefined, {}|undefined - ]>|void { + protos.google.showcase.v1beta1.IDeleteRoomRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteRoomRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteRoomRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('deleteRoom request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteRoomRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteRoomRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteRoom response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.deleteRoom(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteRoomRequest|undefined, {}|undefined - ]) => { - this._log.info('deleteRoom response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteRoom(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteRoomRequest | undefined, + {} | undefined, + ]) => { + this._log.info('deleteRoom response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Creates a blurb. If the parent is a room, the blurb is understood to be a - * message in that room. If the parent is a profile, the blurb is understood - * to be a post on the profile. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * The resource name of the chat room or user profile that this blurb will - * be tied to. - * @param {google.showcase.v1beta1.Blurb} request.blurb - * The blurb to create. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.Blurb|Blurb}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/messaging.create_blurb.js - * region_tag:localhost_v1beta1_generated_Messaging_CreateBlurb_async - */ + /** + * Creates a blurb. If the parent is a room, the blurb is understood to be a + * message in that room. If the parent is a profile, the blurb is understood + * to be a post on the profile. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * The resource name of the chat room or user profile that this blurb will + * be tied to. + * @param {google.showcase.v1beta1.Blurb} request.blurb + * The blurb to create. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.Blurb|Blurb}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/messaging.create_blurb.js + * region_tag:localhost_v1beta1_generated_Messaging_CreateBlurb_async + */ createBlurb( - request?: protos.google.showcase.v1beta1.ICreateBlurbRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IBlurb, - protos.google.showcase.v1beta1.ICreateBlurbRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.ICreateBlurbRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IBlurb, + protos.google.showcase.v1beta1.ICreateBlurbRequest | undefined, + {} | undefined, + ] + >; createBlurb( - request: protos.google.showcase.v1beta1.ICreateBlurbRequest, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.IBlurb, - protos.google.showcase.v1beta1.ICreateBlurbRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.ICreateBlurbRequest, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.IBlurb, + protos.google.showcase.v1beta1.ICreateBlurbRequest | null | undefined, + {} | null | undefined + >, + ): void; createBlurb( - request: protos.google.showcase.v1beta1.ICreateBlurbRequest, - callback: Callback< - protos.google.showcase.v1beta1.IBlurb, - protos.google.showcase.v1beta1.ICreateBlurbRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.ICreateBlurbRequest, + callback: Callback< + protos.google.showcase.v1beta1.IBlurb, + protos.google.showcase.v1beta1.ICreateBlurbRequest | null | undefined, + {} | null | undefined + >, + ): void; createBlurb( - request?: protos.google.showcase.v1beta1.ICreateBlurbRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.showcase.v1beta1.IBlurb, - protos.google.showcase.v1beta1.ICreateBlurbRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.showcase.v1beta1.ICreateBlurbRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.IBlurb, - protos.google.showcase.v1beta1.ICreateBlurbRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.IBlurb, - protos.google.showcase.v1beta1.ICreateBlurbRequest|undefined, {}|undefined - ]>|void { + protos.google.showcase.v1beta1.ICreateBlurbRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.IBlurb, + protos.google.showcase.v1beta1.ICreateBlurbRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IBlurb, + protos.google.showcase.v1beta1.ICreateBlurbRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('createBlurb request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.IBlurb, - protos.google.showcase.v1beta1.ICreateBlurbRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.IBlurb, + protos.google.showcase.v1beta1.ICreateBlurbRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createBlurb response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.createBlurb(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.IBlurb, - protos.google.showcase.v1beta1.ICreateBlurbRequest|undefined, {}|undefined - ]) => { - this._log.info('createBlurb response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createBlurb(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.IBlurb, + protos.google.showcase.v1beta1.ICreateBlurbRequest | undefined, + {} | undefined, + ]) => { + this._log.info('createBlurb response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Retrieves the Blurb with the given resource name. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * The resource name of the requested blurb. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.Blurb|Blurb}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/messaging.get_blurb.js - * region_tag:localhost_v1beta1_generated_Messaging_GetBlurb_async - */ + /** + * Retrieves the Blurb with the given resource name. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * The resource name of the requested blurb. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.Blurb|Blurb}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/messaging.get_blurb.js + * region_tag:localhost_v1beta1_generated_Messaging_GetBlurb_async + */ getBlurb( - request?: protos.google.showcase.v1beta1.IGetBlurbRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IBlurb, - protos.google.showcase.v1beta1.IGetBlurbRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IGetBlurbRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IBlurb, + protos.google.showcase.v1beta1.IGetBlurbRequest | undefined, + {} | undefined, + ] + >; getBlurb( - request: protos.google.showcase.v1beta1.IGetBlurbRequest, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.IBlurb, - protos.google.showcase.v1beta1.IGetBlurbRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IGetBlurbRequest, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.IBlurb, + protos.google.showcase.v1beta1.IGetBlurbRequest | null | undefined, + {} | null | undefined + >, + ): void; getBlurb( - request: protos.google.showcase.v1beta1.IGetBlurbRequest, - callback: Callback< - protos.google.showcase.v1beta1.IBlurb, - protos.google.showcase.v1beta1.IGetBlurbRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IGetBlurbRequest, + callback: Callback< + protos.google.showcase.v1beta1.IBlurb, + protos.google.showcase.v1beta1.IGetBlurbRequest | null | undefined, + {} | null | undefined + >, + ): void; getBlurb( - request?: protos.google.showcase.v1beta1.IGetBlurbRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.showcase.v1beta1.IBlurb, - protos.google.showcase.v1beta1.IGetBlurbRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.showcase.v1beta1.IGetBlurbRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.IBlurb, - protos.google.showcase.v1beta1.IGetBlurbRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.IBlurb, - protos.google.showcase.v1beta1.IGetBlurbRequest|undefined, {}|undefined - ]>|void { + protos.google.showcase.v1beta1.IGetBlurbRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.IBlurb, + protos.google.showcase.v1beta1.IGetBlurbRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IBlurb, + protos.google.showcase.v1beta1.IGetBlurbRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getBlurb request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.IBlurb, - protos.google.showcase.v1beta1.IGetBlurbRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.IBlurb, + protos.google.showcase.v1beta1.IGetBlurbRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getBlurb response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.getBlurb(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.IBlurb, - protos.google.showcase.v1beta1.IGetBlurbRequest|undefined, {}|undefined - ]) => { - this._log.info('getBlurb response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getBlurb(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.IBlurb, + protos.google.showcase.v1beta1.IGetBlurbRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getBlurb response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Updates a blurb. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.showcase.v1beta1.Blurb} request.blurb - * The blurb to update. - * @param {google.protobuf.FieldMask} request.updateMask - * The field mask to determine wich fields are to be updated. If empty, the - * server will assume all fields are to be updated. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.Blurb|Blurb}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/messaging.update_blurb.js - * region_tag:localhost_v1beta1_generated_Messaging_UpdateBlurb_async - */ + /** + * Updates a blurb. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.showcase.v1beta1.Blurb} request.blurb + * The blurb to update. + * @param {google.protobuf.FieldMask} request.updateMask + * The field mask to determine wich fields are to be updated. If empty, the + * server will assume all fields are to be updated. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.Blurb|Blurb}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/messaging.update_blurb.js + * region_tag:localhost_v1beta1_generated_Messaging_UpdateBlurb_async + */ updateBlurb( - request?: protos.google.showcase.v1beta1.IUpdateBlurbRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IBlurb, - protos.google.showcase.v1beta1.IUpdateBlurbRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IUpdateBlurbRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IBlurb, + protos.google.showcase.v1beta1.IUpdateBlurbRequest | undefined, + {} | undefined, + ] + >; updateBlurb( - request: protos.google.showcase.v1beta1.IUpdateBlurbRequest, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.IBlurb, - protos.google.showcase.v1beta1.IUpdateBlurbRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IUpdateBlurbRequest, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.IBlurb, + protos.google.showcase.v1beta1.IUpdateBlurbRequest | null | undefined, + {} | null | undefined + >, + ): void; updateBlurb( - request: protos.google.showcase.v1beta1.IUpdateBlurbRequest, - callback: Callback< - protos.google.showcase.v1beta1.IBlurb, - protos.google.showcase.v1beta1.IUpdateBlurbRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IUpdateBlurbRequest, + callback: Callback< + protos.google.showcase.v1beta1.IBlurb, + protos.google.showcase.v1beta1.IUpdateBlurbRequest | null | undefined, + {} | null | undefined + >, + ): void; updateBlurb( - request?: protos.google.showcase.v1beta1.IUpdateBlurbRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.showcase.v1beta1.IUpdateBlurbRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.IBlurb, - protos.google.showcase.v1beta1.IUpdateBlurbRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.showcase.v1beta1.IBlurb, - protos.google.showcase.v1beta1.IUpdateBlurbRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.IBlurb, - protos.google.showcase.v1beta1.IUpdateBlurbRequest|undefined, {}|undefined - ]>|void { + protos.google.showcase.v1beta1.IUpdateBlurbRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.IBlurb, + protos.google.showcase.v1beta1.IUpdateBlurbRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IBlurb, + protos.google.showcase.v1beta1.IUpdateBlurbRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'blurb.name': request.blurb!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'blurb.name': request.blurb!.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateBlurb request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.IBlurb, - protos.google.showcase.v1beta1.IUpdateBlurbRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.IBlurb, + protos.google.showcase.v1beta1.IUpdateBlurbRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateBlurb response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.updateBlurb(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.IBlurb, - protos.google.showcase.v1beta1.IUpdateBlurbRequest|undefined, {}|undefined - ]) => { - this._log.info('updateBlurb response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateBlurb(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.IBlurb, + protos.google.showcase.v1beta1.IUpdateBlurbRequest | undefined, + {} | undefined, + ]) => { + this._log.info('updateBlurb response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Deletes a blurb. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * The resource name of the requested blurb. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/messaging.delete_blurb.js - * region_tag:localhost_v1beta1_generated_Messaging_DeleteBlurb_async - */ + /** + * Deletes a blurb. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * The resource name of the requested blurb. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/messaging.delete_blurb.js + * region_tag:localhost_v1beta1_generated_Messaging_DeleteBlurb_async + */ deleteBlurb( - request?: protos.google.showcase.v1beta1.IDeleteBlurbRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteBlurbRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IDeleteBlurbRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteBlurbRequest | undefined, + {} | undefined, + ] + >; deleteBlurb( - request: protos.google.showcase.v1beta1.IDeleteBlurbRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteBlurbRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IDeleteBlurbRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteBlurbRequest | null | undefined, + {} | null | undefined + >, + ): void; deleteBlurb( - request: protos.google.showcase.v1beta1.IDeleteBlurbRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteBlurbRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IDeleteBlurbRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteBlurbRequest | null | undefined, + {} | null | undefined + >, + ): void; deleteBlurb( - request?: protos.google.showcase.v1beta1.IDeleteBlurbRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.showcase.v1beta1.IDeleteBlurbRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteBlurbRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteBlurbRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteBlurbRequest|undefined, {}|undefined - ]>|void { + protos.google.showcase.v1beta1.IDeleteBlurbRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteBlurbRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteBlurbRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('deleteBlurb request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteBlurbRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteBlurbRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteBlurb response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.deleteBlurb(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteBlurbRequest|undefined, {}|undefined - ]) => { - this._log.info('deleteBlurb response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteBlurb(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteBlurbRequest | undefined, + {} | undefined, + ]) => { + this._log.info('deleteBlurb response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * This returns a stream that emits the blurbs that are created for a - * particular chat room or user profile. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * The resource name of a chat room or user profile whose blurbs to stream. - * @param {google.protobuf.Timestamp} request.expireTime - * The time at which this stream will close. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits {@link protos.google.showcase.v1beta1.StreamBlurbsResponse|StreamBlurbsResponse} on 'data' event. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#server-streaming | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/messaging.stream_blurbs.js - * region_tag:localhost_v1beta1_generated_Messaging_StreamBlurbs_async - */ + /** + * This returns a stream that emits the blurbs that are created for a + * particular chat room or user profile. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * The resource name of a chat room or user profile whose blurbs to stream. + * @param {google.protobuf.Timestamp} request.expireTime + * The time at which this stream will close. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits {@link protos.google.showcase.v1beta1.StreamBlurbsResponse|StreamBlurbsResponse} on 'data' event. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#server-streaming | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/messaging.stream_blurbs.js + * region_tag:localhost_v1beta1_generated_Messaging_StreamBlurbs_async + */ streamBlurbs( - request?: protos.google.showcase.v1beta1.IStreamBlurbsRequest, - options?: CallOptions): - gax.CancellableStream{ + request?: protos.google.showcase.v1beta1.IStreamBlurbsRequest, + options?: CallOptions, + ): gax.CancellableStream { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('streamBlurbs stream %j', options); return this.innerApiCalls.streamBlurbs(request, options); } -/** - * This is a stream to create multiple blurbs. If an invalid blurb is - * requested to be created, the stream will close with an error. - * - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - A writable stream which accepts objects representing - * {@link protos.google.showcase.v1beta1.CreateBlurbRequest|CreateBlurbRequest}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#client-streaming | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/messaging.send_blurbs.js - * region_tag:localhost_v1beta1_generated_Messaging_SendBlurbs_async - */ + /** + * This is a stream to create multiple blurbs. If an invalid blurb is + * requested to be created, the stream will close with an error. + * + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} - A writable stream which accepts objects representing + * {@link protos.google.showcase.v1beta1.CreateBlurbRequest|CreateBlurbRequest}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#client-streaming | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/messaging.send_blurbs.js + * region_tag:localhost_v1beta1_generated_Messaging_SendBlurbs_async + */ sendBlurbs( - options?: CallOptions, - callback?: Callback< - protos.google.showcase.v1beta1.ISendBlurbsResponse, - protos.google.showcase.v1beta1.ICreateBlurbRequest|null|undefined, - {}|null|undefined>): - gax.CancellableStream; + options?: CallOptions, + callback?: Callback< + protos.google.showcase.v1beta1.ISendBlurbsResponse, + protos.google.showcase.v1beta1.ICreateBlurbRequest | null | undefined, + {} | null | undefined + >, + ): gax.CancellableStream; sendBlurbs( - callback?: Callback< - protos.google.showcase.v1beta1.ISendBlurbsResponse, - protos.google.showcase.v1beta1.ICreateBlurbRequest|null|undefined, - {}|null|undefined>): - gax.CancellableStream; + callback?: Callback< + protos.google.showcase.v1beta1.ISendBlurbsResponse, + protos.google.showcase.v1beta1.ICreateBlurbRequest | null | undefined, + {} | null | undefined + >, + ): gax.CancellableStream; sendBlurbs( - optionsOrCallback?: CallOptions|Callback< - protos.google.showcase.v1beta1.ISendBlurbsResponse, - protos.google.showcase.v1beta1.ICreateBlurbRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.showcase.v1beta1.ISendBlurbsResponse, - protos.google.showcase.v1beta1.ICreateBlurbRequest|null|undefined, - {}|null|undefined>): - gax.CancellableStream { + optionsOrCallback?: + | CallOptions + | Callback< + protos.google.showcase.v1beta1.ISendBlurbsResponse, + protos.google.showcase.v1beta1.ICreateBlurbRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.ISendBlurbsResponse, + protos.google.showcase.v1beta1.ICreateBlurbRequest | null | undefined, + {} | null | undefined + >, + ): gax.CancellableStream { if (optionsOrCallback instanceof Function && callback === undefined) { - callback = optionsOrCallback; - optionsOrCallback = {}; + callback = optionsOrCallback; + optionsOrCallback = {}; } const options = optionsOrCallback as CallOptions; - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('sendBlurbs stream %j', options); return this.innerApiCalls.sendBlurbs(null, options, callback); } -/** - * This method starts a bidirectional stream that receives all blurbs that - * are being created after the stream has started and sends requests to create - * blurbs. If an invalid blurb is requested to be created, the stream will - * close with an error. - * - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which is both readable and writable. It accepts objects - * representing {@link protos.google.showcase.v1beta1.ConnectRequest|ConnectRequest} for write() method, and - * will emit objects representing {@link protos.google.showcase.v1beta1.StreamBlurbsResponse|StreamBlurbsResponse} on 'data' event asynchronously. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#bi-directional-streaming | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/messaging.connect.js - * region_tag:localhost_v1beta1_generated_Messaging_Connect_async - */ - connect( - options?: CallOptions): - gax.CancellableStream { - this.initialize().catch(err => {throw err}); + /** + * This method starts a bidirectional stream that receives all blurbs that + * are being created after the stream has started and sends requests to create + * blurbs. If an invalid blurb is requested to be created, the stream will + * close with an error. + * + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which is both readable and writable. It accepts objects + * representing {@link protos.google.showcase.v1beta1.ConnectRequest|ConnectRequest} for write() method, and + * will emit objects representing {@link protos.google.showcase.v1beta1.StreamBlurbsResponse|StreamBlurbsResponse} on 'data' event asynchronously. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#bi-directional-streaming | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/messaging.connect.js + * region_tag:localhost_v1beta1_generated_Messaging_Connect_async + */ + connect(options?: CallOptions): gax.CancellableStream { + this.initialize().catch((err) => { + throw err; + }); this._log.info('connect stream %j', options); return this.innerApiCalls.connect(null, options); } -/** - * This method searches through all blurbs across all rooms and profiles - * for blurbs containing to words found in the query. Only posts that - * contain an exact match of a queried word will be returned. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.query - * The query used to search for blurbs containing to words of this string. - * Only posts that contain an exact match of a queried word will be returned. - * @param {string} request.parent - * The rooms or profiles to search. If unset, `SearchBlurbs` will search all - * rooms and all profiles. - * @param {number} request.pageSize - * The maximum number of blurbs return. Server may return fewer - * blurbs than requested. If unspecified, server will pick an appropriate - * default. - * @param {string} request.pageToken - * The value of - * google.showcase.v1beta1.SearchBlurbsResponse.next_page_token - * returned from the previous call to - * `google.showcase.v1beta1.Messaging\SearchBlurbs` method. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing - * a long running operation. Its `promise()` method returns a promise - * you can `await` for. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/messaging.search_blurbs.js - * region_tag:localhost_v1beta1_generated_Messaging_SearchBlurbs_async - */ + /** + * This method searches through all blurbs across all rooms and profiles + * for blurbs containing to words found in the query. Only posts that + * contain an exact match of a queried word will be returned. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.query + * The query used to search for blurbs containing to words of this string. + * Only posts that contain an exact match of a queried word will be returned. + * @param {string} request.parent + * The rooms or profiles to search. If unset, `SearchBlurbs` will search all + * rooms and all profiles. + * @param {number} request.pageSize + * The maximum number of blurbs return. Server may return fewer + * blurbs than requested. If unspecified, server will pick an appropriate + * default. + * @param {string} request.pageToken + * The value of + * google.showcase.v1beta1.SearchBlurbsResponse.next_page_token + * returned from the previous call to + * `google.showcase.v1beta1.Messaging\SearchBlurbs` method. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/messaging.search_blurbs.js + * region_tag:localhost_v1beta1_generated_Messaging_SearchBlurbs_async + */ searchBlurbs( - request?: protos.google.showcase.v1beta1.ISearchBlurbsRequest, - options?: CallOptions): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.ISearchBlurbsRequest, + options?: CallOptions, + ): Promise< + [ + LROperation< + protos.google.showcase.v1beta1.ISearchBlurbsResponse, + protos.google.showcase.v1beta1.ISearchBlurbsMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; searchBlurbs( - request: protos.google.showcase.v1beta1.ISearchBlurbsRequest, - options: CallOptions, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.ISearchBlurbsRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.showcase.v1beta1.ISearchBlurbsResponse, + protos.google.showcase.v1beta1.ISearchBlurbsMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; searchBlurbs( - request: protos.google.showcase.v1beta1.ISearchBlurbsRequest, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.ISearchBlurbsRequest, + callback: Callback< + LROperation< + protos.google.showcase.v1beta1.ISearchBlurbsResponse, + protos.google.showcase.v1beta1.ISearchBlurbsMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; searchBlurbs( - request?: protos.google.showcase.v1beta1.ISearchBlurbsRequest, - optionsOrCallback?: CallOptions|Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>, - callback?: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>|void { + request?: protos.google.showcase.v1beta1.ISearchBlurbsRequest, + optionsOrCallback?: + | CallOptions + | Callback< + LROperation< + protos.google.showcase.v1beta1.ISearchBlurbsResponse, + protos.google.showcase.v1beta1.ISearchBlurbsMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + callback?: Callback< + LROperation< + protos.google.showcase.v1beta1.ISearchBlurbsResponse, + protos.google.showcase.v1beta1.ISearchBlurbsMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + LROperation< + protos.google.showcase.v1beta1.ISearchBlurbsResponse, + protos.google.showcase.v1beta1.ISearchBlurbsMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + LROperation< + protos.google.showcase.v1beta1.ISearchBlurbsResponse, + protos.google.showcase.v1beta1.ISearchBlurbsMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, rawResponse, _) => { this._log.info('searchBlurbs response %j', rawResponse); callback!(error, response, rawResponse, _); // We verified `callback` above. } : undefined; this._log.info('searchBlurbs request %j', request); - return this.innerApiCalls.searchBlurbs(request, options, wrappedCallback) - ?.then(([response, rawResponse, _]: [ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]) => { - this._log.info('searchBlurbs response %j', rawResponse); - return [response, rawResponse, _]; - }); + return this.innerApiCalls + .searchBlurbs(request, options, wrappedCallback) + ?.then( + ([response, rawResponse, _]: [ + LROperation< + protos.google.showcase.v1beta1.ISearchBlurbsResponse, + protos.google.showcase.v1beta1.ISearchBlurbsMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ]) => { + this._log.info('searchBlurbs response %j', rawResponse); + return [response, rawResponse, _]; + }, + ); } -/** - * Check the status of the long running operation returned by `searchBlurbs()`. - * @param {String} name - * The operation name that will be passed. - * @returns {Promise} - The promise which resolves to an object. - * The decoded operation object has result and metadata field to get information from. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/messaging.search_blurbs.js - * region_tag:localhost_v1beta1_generated_Messaging_SearchBlurbs_async - */ - async checkSearchBlurbsProgress(name: string): Promise>{ + /** + * Check the status of the long running operation returned by `searchBlurbs()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/messaging.search_blurbs.js + * region_tag:localhost_v1beta1_generated_Messaging_SearchBlurbs_async + */ + async checkSearchBlurbsProgress( + name: string, + ): Promise< + LROperation< + protos.google.showcase.v1beta1.SearchBlurbsResponse, + protos.google.showcase.v1beta1.SearchBlurbsMetadata + > + > { this._log.info('searchBlurbs long-running'); - const request = new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest({name}); + const request = + new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( + { name }, + ); const [operation] = await this.operationsClient.getOperation(request); - const decodeOperation = new this._gaxModule.Operation(operation, this.descriptors.longrunning.searchBlurbs, this._gaxModule.createDefaultBackoffSettings()); - return decodeOperation as LROperation; + const decodeOperation = new this._gaxModule.Operation( + operation, + this.descriptors.longrunning.searchBlurbs, + this._gaxModule.createDefaultBackoffSettings(), + ); + return decodeOperation as LROperation< + protos.google.showcase.v1beta1.SearchBlurbsResponse, + protos.google.showcase.v1beta1.SearchBlurbsMetadata + >; } - /** - * Lists all chat rooms. - * - * @param {Object} request - * The request object that will be sent. - * @param {number} request.pageSize - * The maximum number of rooms return. Server may return fewer rooms - * than requested. If unspecified, server will pick an appropriate default. - * @param {string} request.pageToken - * The value of google.showcase.v1beta1.ListRoomsResponse.next_page_token - * returned from the previous call to - * `google.showcase.v1beta1.Messaging\ListRooms` method. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.showcase.v1beta1.Room|Room}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `listRoomsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Lists all chat rooms. + * + * @param {Object} request + * The request object that will be sent. + * @param {number} request.pageSize + * The maximum number of rooms return. Server may return fewer rooms + * than requested. If unspecified, server will pick an appropriate default. + * @param {string} request.pageToken + * The value of google.showcase.v1beta1.ListRoomsResponse.next_page_token + * returned from the previous call to + * `google.showcase.v1beta1.Messaging\ListRooms` method. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.showcase.v1beta1.Room|Room}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listRoomsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listRooms( - request?: protos.google.showcase.v1beta1.IListRoomsRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IRoom[], - protos.google.showcase.v1beta1.IListRoomsRequest|null, - protos.google.showcase.v1beta1.IListRoomsResponse - ]>; + request?: protos.google.showcase.v1beta1.IListRoomsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IRoom[], + protos.google.showcase.v1beta1.IListRoomsRequest | null, + protos.google.showcase.v1beta1.IListRoomsResponse, + ] + >; listRooms( - request: protos.google.showcase.v1beta1.IListRoomsRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.showcase.v1beta1.IListRoomsRequest, - protos.google.showcase.v1beta1.IListRoomsResponse|null|undefined, - protos.google.showcase.v1beta1.IRoom>): void; + request: protos.google.showcase.v1beta1.IListRoomsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.showcase.v1beta1.IListRoomsRequest, + protos.google.showcase.v1beta1.IListRoomsResponse | null | undefined, + protos.google.showcase.v1beta1.IRoom + >, + ): void; listRooms( - request: protos.google.showcase.v1beta1.IListRoomsRequest, - callback: PaginationCallback< - protos.google.showcase.v1beta1.IListRoomsRequest, - protos.google.showcase.v1beta1.IListRoomsResponse|null|undefined, - protos.google.showcase.v1beta1.IRoom>): void; + request: protos.google.showcase.v1beta1.IListRoomsRequest, + callback: PaginationCallback< + protos.google.showcase.v1beta1.IListRoomsRequest, + protos.google.showcase.v1beta1.IListRoomsResponse | null | undefined, + protos.google.showcase.v1beta1.IRoom + >, + ): void; listRooms( - request?: protos.google.showcase.v1beta1.IListRoomsRequest, - optionsOrCallback?: CallOptions|PaginationCallback< - protos.google.showcase.v1beta1.IListRoomsRequest, - protos.google.showcase.v1beta1.IListRoomsResponse|null|undefined, - protos.google.showcase.v1beta1.IRoom>, - callback?: PaginationCallback< + request?: protos.google.showcase.v1beta1.IListRoomsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.showcase.v1beta1.IListRoomsRequest, - protos.google.showcase.v1beta1.IListRoomsResponse|null|undefined, - protos.google.showcase.v1beta1.IRoom>): - Promise<[ - protos.google.showcase.v1beta1.IRoom[], - protos.google.showcase.v1beta1.IListRoomsRequest|null, - protos.google.showcase.v1beta1.IListRoomsResponse - ]>|void { + protos.google.showcase.v1beta1.IListRoomsResponse | null | undefined, + protos.google.showcase.v1beta1.IRoom + >, + callback?: PaginationCallback< + protos.google.showcase.v1beta1.IListRoomsRequest, + protos.google.showcase.v1beta1.IListRoomsResponse | null | undefined, + protos.google.showcase.v1beta1.IRoom + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IRoom[], + protos.google.showcase.v1beta1.IListRoomsRequest | null, + protos.google.showcase.v1beta1.IListRoomsResponse, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.showcase.v1beta1.IListRoomsRequest, - protos.google.showcase.v1beta1.IListRoomsResponse|null|undefined, - protos.google.showcase.v1beta1.IRoom>|undefined = callback + this.initialize().catch((err) => { + throw err; + }); + const wrappedCallback: + | PaginationCallback< + protos.google.showcase.v1beta1.IListRoomsRequest, + protos.google.showcase.v1beta1.IListRoomsResponse | null | undefined, + protos.google.showcase.v1beta1.IRoom + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listRooms values %j', values); callback!(error, values, nextPageRequest, rawResponse); @@ -1495,186 +1918,207 @@ export class MessagingClient { this._log.info('listRooms request %j', request); return this.innerApiCalls .listRooms(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.showcase.v1beta1.IRoom[], - protos.google.showcase.v1beta1.IListRoomsRequest|null, - protos.google.showcase.v1beta1.IListRoomsResponse - ]) => { - this._log.info('listRooms values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.showcase.v1beta1.IRoom[], + protos.google.showcase.v1beta1.IListRoomsRequest | null, + protos.google.showcase.v1beta1.IListRoomsResponse, + ]) => { + this._log.info('listRooms values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listRooms`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {number} request.pageSize - * The maximum number of rooms return. Server may return fewer rooms - * than requested. If unspecified, server will pick an appropriate default. - * @param {string} request.pageToken - * The value of google.showcase.v1beta1.ListRoomsResponse.next_page_token - * returned from the previous call to - * `google.showcase.v1beta1.Messaging\ListRooms` method. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.showcase.v1beta1.Room|Room} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `listRoomsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `listRooms`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {number} request.pageSize + * The maximum number of rooms return. Server may return fewer rooms + * than requested. If unspecified, server will pick an appropriate default. + * @param {string} request.pageToken + * The value of google.showcase.v1beta1.ListRoomsResponse.next_page_token + * returned from the previous call to + * `google.showcase.v1beta1.Messaging\ListRooms` method. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.showcase.v1beta1.Room|Room} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listRoomsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listRoomsStream( - request?: protos.google.showcase.v1beta1.IListRoomsRequest, - options?: CallOptions): - Transform{ + request?: protos.google.showcase.v1beta1.IListRoomsRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; const defaultCallSettings = this._defaults['listRooms']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listRooms stream %j', request); return this.descriptors.page.listRooms.createStream( this.innerApiCalls.listRooms as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listRooms`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {number} request.pageSize - * The maximum number of rooms return. Server may return fewer rooms - * than requested. If unspecified, server will pick an appropriate default. - * @param {string} request.pageToken - * The value of google.showcase.v1beta1.ListRoomsResponse.next_page_token - * returned from the previous call to - * `google.showcase.v1beta1.Messaging\ListRooms` method. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.showcase.v1beta1.Room|Room}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/messaging.list_rooms.js - * region_tag:localhost_v1beta1_generated_Messaging_ListRooms_async - */ + /** + * Equivalent to `listRooms`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {number} request.pageSize + * The maximum number of rooms return. Server may return fewer rooms + * than requested. If unspecified, server will pick an appropriate default. + * @param {string} request.pageToken + * The value of google.showcase.v1beta1.ListRoomsResponse.next_page_token + * returned from the previous call to + * `google.showcase.v1beta1.Messaging\ListRooms` method. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.showcase.v1beta1.Room|Room}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/messaging.list_rooms.js + * region_tag:localhost_v1beta1_generated_Messaging_ListRooms_async + */ listRoomsAsync( - request?: protos.google.showcase.v1beta1.IListRoomsRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.showcase.v1beta1.IListRoomsRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; const defaultCallSettings = this._defaults['listRooms']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listRooms iterate %j', request); return this.descriptors.page.listRooms.asyncIterate( this.innerApiCalls['listRooms'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } - /** - * Lists blurbs for a specific chat room or user profile depending on the - * parent resource name. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * The resource name of the requested room or profile whos blurbs to list. - * @param {number} request.pageSize - * The maximum number of blurbs to return. Server may return fewer - * blurbs than requested. If unspecified, server will pick an appropriate - * default. - * @param {string} request.pageToken - * The value of google.showcase.v1beta1.ListBlurbsResponse.next_page_token - * returned from the previous call to - * `google.showcase.v1beta1.Messaging\ListBlurbs` method. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.showcase.v1beta1.Blurb|Blurb}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `listBlurbsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Lists blurbs for a specific chat room or user profile depending on the + * parent resource name. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * The resource name of the requested room or profile whos blurbs to list. + * @param {number} request.pageSize + * The maximum number of blurbs to return. Server may return fewer + * blurbs than requested. If unspecified, server will pick an appropriate + * default. + * @param {string} request.pageToken + * The value of google.showcase.v1beta1.ListBlurbsResponse.next_page_token + * returned from the previous call to + * `google.showcase.v1beta1.Messaging\ListBlurbs` method. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.showcase.v1beta1.Blurb|Blurb}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listBlurbsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listBlurbs( - request?: protos.google.showcase.v1beta1.IListBlurbsRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IBlurb[], - protos.google.showcase.v1beta1.IListBlurbsRequest|null, - protos.google.showcase.v1beta1.IListBlurbsResponse - ]>; + request?: protos.google.showcase.v1beta1.IListBlurbsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IBlurb[], + protos.google.showcase.v1beta1.IListBlurbsRequest | null, + protos.google.showcase.v1beta1.IListBlurbsResponse, + ] + >; listBlurbs( - request: protos.google.showcase.v1beta1.IListBlurbsRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.showcase.v1beta1.IListBlurbsRequest, - protos.google.showcase.v1beta1.IListBlurbsResponse|null|undefined, - protos.google.showcase.v1beta1.IBlurb>): void; + request: protos.google.showcase.v1beta1.IListBlurbsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.showcase.v1beta1.IListBlurbsRequest, + protos.google.showcase.v1beta1.IListBlurbsResponse | null | undefined, + protos.google.showcase.v1beta1.IBlurb + >, + ): void; listBlurbs( - request: protos.google.showcase.v1beta1.IListBlurbsRequest, - callback: PaginationCallback< - protos.google.showcase.v1beta1.IListBlurbsRequest, - protos.google.showcase.v1beta1.IListBlurbsResponse|null|undefined, - protos.google.showcase.v1beta1.IBlurb>): void; + request: protos.google.showcase.v1beta1.IListBlurbsRequest, + callback: PaginationCallback< + protos.google.showcase.v1beta1.IListBlurbsRequest, + protos.google.showcase.v1beta1.IListBlurbsResponse | null | undefined, + protos.google.showcase.v1beta1.IBlurb + >, + ): void; listBlurbs( - request?: protos.google.showcase.v1beta1.IListBlurbsRequest, - optionsOrCallback?: CallOptions|PaginationCallback< + request?: protos.google.showcase.v1beta1.IListBlurbsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.showcase.v1beta1.IListBlurbsRequest, - protos.google.showcase.v1beta1.IListBlurbsResponse|null|undefined, - protos.google.showcase.v1beta1.IBlurb>, - callback?: PaginationCallback< - protos.google.showcase.v1beta1.IListBlurbsRequest, - protos.google.showcase.v1beta1.IListBlurbsResponse|null|undefined, - protos.google.showcase.v1beta1.IBlurb>): - Promise<[ - protos.google.showcase.v1beta1.IBlurb[], - protos.google.showcase.v1beta1.IListBlurbsRequest|null, - protos.google.showcase.v1beta1.IListBlurbsResponse - ]>|void { + protos.google.showcase.v1beta1.IListBlurbsResponse | null | undefined, + protos.google.showcase.v1beta1.IBlurb + >, + callback?: PaginationCallback< + protos.google.showcase.v1beta1.IListBlurbsRequest, + protos.google.showcase.v1beta1.IListBlurbsResponse | null | undefined, + protos.google.showcase.v1beta1.IBlurb + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IBlurb[], + protos.google.showcase.v1beta1.IListBlurbsRequest | null, + protos.google.showcase.v1beta1.IListBlurbsResponse, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.showcase.v1beta1.IListBlurbsRequest, - protos.google.showcase.v1beta1.IListBlurbsResponse|null|undefined, - protos.google.showcase.v1beta1.IBlurb>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.showcase.v1beta1.IListBlurbsRequest, + protos.google.showcase.v1beta1.IListBlurbsResponse | null | undefined, + protos.google.showcase.v1beta1.IBlurb + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listBlurbs values %j', values); callback!(error, values, nextPageRequest, rawResponse); @@ -1683,114 +2127,118 @@ export class MessagingClient { this._log.info('listBlurbs request %j', request); return this.innerApiCalls .listBlurbs(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.showcase.v1beta1.IBlurb[], - protos.google.showcase.v1beta1.IListBlurbsRequest|null, - protos.google.showcase.v1beta1.IListBlurbsResponse - ]) => { - this._log.info('listBlurbs values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.showcase.v1beta1.IBlurb[], + protos.google.showcase.v1beta1.IListBlurbsRequest | null, + protos.google.showcase.v1beta1.IListBlurbsResponse, + ]) => { + this._log.info('listBlurbs values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listBlurbs`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * The resource name of the requested room or profile whos blurbs to list. - * @param {number} request.pageSize - * The maximum number of blurbs to return. Server may return fewer - * blurbs than requested. If unspecified, server will pick an appropriate - * default. - * @param {string} request.pageToken - * The value of google.showcase.v1beta1.ListBlurbsResponse.next_page_token - * returned from the previous call to - * `google.showcase.v1beta1.Messaging\ListBlurbs` method. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.showcase.v1beta1.Blurb|Blurb} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `listBlurbsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `listBlurbs`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * The resource name of the requested room or profile whos blurbs to list. + * @param {number} request.pageSize + * The maximum number of blurbs to return. Server may return fewer + * blurbs than requested. If unspecified, server will pick an appropriate + * default. + * @param {string} request.pageToken + * The value of google.showcase.v1beta1.ListBlurbsResponse.next_page_token + * returned from the previous call to + * `google.showcase.v1beta1.Messaging\ListBlurbs` method. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.showcase.v1beta1.Blurb|Blurb} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listBlurbsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listBlurbsStream( - request?: protos.google.showcase.v1beta1.IListBlurbsRequest, - options?: CallOptions): - Transform{ + request?: protos.google.showcase.v1beta1.IListBlurbsRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); const defaultCallSettings = this._defaults['listBlurbs']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listBlurbs stream %j', request); return this.descriptors.page.listBlurbs.createStream( this.innerApiCalls.listBlurbs as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listBlurbs`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * The resource name of the requested room or profile whos blurbs to list. - * @param {number} request.pageSize - * The maximum number of blurbs to return. Server may return fewer - * blurbs than requested. If unspecified, server will pick an appropriate - * default. - * @param {string} request.pageToken - * The value of google.showcase.v1beta1.ListBlurbsResponse.next_page_token - * returned from the previous call to - * `google.showcase.v1beta1.Messaging\ListBlurbs` method. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.showcase.v1beta1.Blurb|Blurb}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/messaging.list_blurbs.js - * region_tag:localhost_v1beta1_generated_Messaging_ListBlurbs_async - */ + /** + * Equivalent to `listBlurbs`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * The resource name of the requested room or profile whos blurbs to list. + * @param {number} request.pageSize + * The maximum number of blurbs to return. Server may return fewer + * blurbs than requested. If unspecified, server will pick an appropriate + * default. + * @param {string} request.pageToken + * The value of google.showcase.v1beta1.ListBlurbsResponse.next_page_token + * returned from the previous call to + * `google.showcase.v1beta1.Messaging\ListBlurbs` method. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.showcase.v1beta1.Blurb|Blurb}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/messaging.list_blurbs.js + * region_tag:localhost_v1beta1_generated_Messaging_ListBlurbs_async + */ listBlurbsAsync( - request?: protos.google.showcase.v1beta1.IListBlurbsRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.showcase.v1beta1.IListBlurbsRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); const defaultCallSettings = this._defaults['listBlurbs']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listBlurbs iterate %j', request); return this.descriptors.page.listBlurbs.asyncIterate( this.innerApiCalls['listBlurbs'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } // -------------------- @@ -1805,7 +2253,7 @@ export class MessagingClient { * @param {string} blueprint * @returns {string} Resource name string. */ - blueprintPath(session:string,test:string,blueprint:string) { + blueprintPath(session: string, test: string, blueprint: string) { return this.pathTemplates.blueprintPathTemplate.render({ session: session, test: test, @@ -1821,7 +2269,8 @@ export class MessagingClient { * @returns {string} A string representing the session. */ matchSessionFromBlueprintName(blueprintName: string) { - return this.pathTemplates.blueprintPathTemplate.match(blueprintName).session; + return this.pathTemplates.blueprintPathTemplate.match(blueprintName) + .session; } /** @@ -1843,7 +2292,8 @@ export class MessagingClient { * @returns {string} A string representing the blueprint. */ matchBlueprintFromBlueprintName(blueprintName: string) { - return this.pathTemplates.blueprintPathTemplate.match(blueprintName).blueprint; + return this.pathTemplates.blueprintPathTemplate.match(blueprintName) + .blueprint; } /** @@ -1852,7 +2302,7 @@ export class MessagingClient { * @param {string} room * @returns {string} Resource name string. */ - roomPath(room:string) { + roomPath(room: string) { return this.pathTemplates.roomPathTemplate.render({ room: room, }); @@ -1876,7 +2326,7 @@ export class MessagingClient { * @param {string} blurb * @returns {string} Resource name string. */ - roomBlurbPath(room:string,blurb:string) { + roomBlurbPath(room: string, blurb: string) { return this.pathTemplates.roomBlurbPathTemplate.render({ room: room, blurb: blurb, @@ -1913,7 +2363,11 @@ export class MessagingClient { * @param {string} blurb * @returns {string} Resource name string. */ - roomBlurbsLegacyRoomBlurbPath(room:string,legacyRoom:string,blurb:string) { + roomBlurbsLegacyRoomBlurbPath( + room: string, + legacyRoom: string, + blurb: string, + ) { return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.render({ room: room, legacy_room: legacyRoom, @@ -1928,8 +2382,12 @@ export class MessagingClient { * A fully-qualified path representing room_blurbs_legacy_room_blurb resource. * @returns {string} A string representing the room. */ - matchRoomFromRoomBlurbsLegacyRoomBlurbName(roomBlurbsLegacyRoomBlurbName: string) { - return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match(roomBlurbsLegacyRoomBlurbName).room; + matchRoomFromRoomBlurbsLegacyRoomBlurbName( + roomBlurbsLegacyRoomBlurbName: string, + ) { + return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match( + roomBlurbsLegacyRoomBlurbName, + ).room; } /** @@ -1939,8 +2397,12 @@ export class MessagingClient { * A fully-qualified path representing room_blurbs_legacy_room_blurb resource. * @returns {string} A string representing the legacy_room. */ - matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName(roomBlurbsLegacyRoomBlurbName: string) { - return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match(roomBlurbsLegacyRoomBlurbName).legacy_room; + matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName( + roomBlurbsLegacyRoomBlurbName: string, + ) { + return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match( + roomBlurbsLegacyRoomBlurbName, + ).legacy_room; } /** @@ -1950,8 +2412,12 @@ export class MessagingClient { * A fully-qualified path representing room_blurbs_legacy_room_blurb resource. * @returns {string} A string representing the blurb. */ - matchBlurbFromRoomBlurbsLegacyRoomBlurbName(roomBlurbsLegacyRoomBlurbName: string) { - return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match(roomBlurbsLegacyRoomBlurbName).blurb; + matchBlurbFromRoomBlurbsLegacyRoomBlurbName( + roomBlurbsLegacyRoomBlurbName: string, + ) { + return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match( + roomBlurbsLegacyRoomBlurbName, + ).blurb; } /** @@ -1960,7 +2426,7 @@ export class MessagingClient { * @param {string} sequence * @returns {string} Resource name string. */ - sequencePath(sequence:string) { + sequencePath(sequence: string) { return this.pathTemplates.sequencePathTemplate.render({ sequence: sequence, }); @@ -1983,7 +2449,7 @@ export class MessagingClient { * @param {string} sequence * @returns {string} Resource name string. */ - sequenceReportPath(sequence:string) { + sequenceReportPath(sequence: string) { return this.pathTemplates.sequenceReportPathTemplate.render({ sequence: sequence, }); @@ -1997,7 +2463,9 @@ export class MessagingClient { * @returns {string} A string representing the sequence. */ matchSequenceFromSequenceReportName(sequenceReportName: string) { - return this.pathTemplates.sequenceReportPathTemplate.match(sequenceReportName).sequence; + return this.pathTemplates.sequenceReportPathTemplate.match( + sequenceReportName, + ).sequence; } /** @@ -2006,7 +2474,7 @@ export class MessagingClient { * @param {string} session * @returns {string} Resource name string. */ - sessionPath(session:string) { + sessionPath(session: string) { return this.pathTemplates.sessionPathTemplate.render({ session: session, }); @@ -2030,7 +2498,7 @@ export class MessagingClient { * @param {string} test * @returns {string} Resource name string. */ - testPath(session:string,test:string) { + testPath(session: string, test: string) { return this.pathTemplates.testPathTemplate.render({ session: session, test: test, @@ -2065,7 +2533,7 @@ export class MessagingClient { * @param {string} user * @returns {string} Resource name string. */ - userPath(user:string) { + userPath(user: string) { return this.pathTemplates.userPathTemplate.render({ user: user, }); @@ -2089,7 +2557,7 @@ export class MessagingClient { * @param {string} blurb * @returns {string} Resource name string. */ - userProfileBlurbPath(user:string,blurb:string) { + userProfileBlurbPath(user: string, blurb: string) { return this.pathTemplates.userProfileBlurbPathTemplate.render({ user: user, blurb: blurb, @@ -2104,7 +2572,9 @@ export class MessagingClient { * @returns {string} A string representing the user. */ matchUserFromUserProfileBlurbName(userProfileBlurbName: string) { - return this.pathTemplates.userProfileBlurbPathTemplate.match(userProfileBlurbName).user; + return this.pathTemplates.userProfileBlurbPathTemplate.match( + userProfileBlurbName, + ).user; } /** @@ -2115,7 +2585,9 @@ export class MessagingClient { * @returns {string} A string representing the blurb. */ matchBlurbFromUserProfileBlurbName(userProfileBlurbName: string) { - return this.pathTemplates.userProfileBlurbPathTemplate.match(userProfileBlurbName).blurb; + return this.pathTemplates.userProfileBlurbPathTemplate.match( + userProfileBlurbName, + ).blurb; } /** @@ -2126,12 +2598,18 @@ export class MessagingClient { * @param {string} blurb * @returns {string} Resource name string. */ - userProfileBlurbsLegacyUserBlurbPath(user:string,legacyUser:string,blurb:string) { - return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.render({ - user: user, - legacy_user: legacyUser, - blurb: blurb, - }); + userProfileBlurbsLegacyUserBlurbPath( + user: string, + legacyUser: string, + blurb: string, + ) { + return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.render( + { + user: user, + legacy_user: legacyUser, + blurb: blurb, + }, + ); } /** @@ -2141,8 +2619,12 @@ export class MessagingClient { * A fully-qualified path representing user_profile_blurbs_legacy_user_blurb resource. * @returns {string} A string representing the user. */ - matchUserFromUserProfileBlurbsLegacyUserBlurbName(userProfileBlurbsLegacyUserBlurbName: string) { - return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match(userProfileBlurbsLegacyUserBlurbName).user; + matchUserFromUserProfileBlurbsLegacyUserBlurbName( + userProfileBlurbsLegacyUserBlurbName: string, + ) { + return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match( + userProfileBlurbsLegacyUserBlurbName, + ).user; } /** @@ -2152,8 +2634,12 @@ export class MessagingClient { * A fully-qualified path representing user_profile_blurbs_legacy_user_blurb resource. * @returns {string} A string representing the legacy_user. */ - matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName(userProfileBlurbsLegacyUserBlurbName: string) { - return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match(userProfileBlurbsLegacyUserBlurbName).legacy_user; + matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName( + userProfileBlurbsLegacyUserBlurbName: string, + ) { + return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match( + userProfileBlurbsLegacyUserBlurbName, + ).legacy_user; } /** @@ -2163,8 +2649,12 @@ export class MessagingClient { * A fully-qualified path representing user_profile_blurbs_legacy_user_blurb resource. * @returns {string} A string representing the blurb. */ - matchBlurbFromUserProfileBlurbsLegacyUserBlurbName(userProfileBlurbsLegacyUserBlurbName: string) { - return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match(userProfileBlurbsLegacyUserBlurbName).blurb; + matchBlurbFromUserProfileBlurbsLegacyUserBlurbName( + userProfileBlurbsLegacyUserBlurbName: string, + ) { + return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match( + userProfileBlurbsLegacyUserBlurbName, + ).blurb; } /** @@ -2175,7 +2665,7 @@ export class MessagingClient { */ close(): Promise { if (this.messagingStub && !this._terminated) { - return this.messagingStub.then(stub => { + return this.messagingStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -2184,4 +2674,4 @@ export class MessagingClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/core/generator/gapic-generator-typescript/baselines/disable-packing-test-esm/esm/src/v1beta1/sequence_service_client.ts.baseline b/core/generator/gapic-generator-typescript/baselines/disable-packing-test-esm/esm/src/v1beta1/sequence_service_client.ts.baseline index 548fa4288d27..8e3e6cbdd6e8 100644 --- a/core/generator/gapic-generator-typescript/baselines/disable-packing-test-esm/esm/src/v1beta1/sequence_service_client.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/disable-packing-test-esm/esm/src/v1beta1/sequence_service_client.ts.baseline @@ -18,15 +18,20 @@ /* global window */ import * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions} from 'google-gax'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, +} from 'google-gax'; // @ts-ignore import type * as protos from '../../../protos/protos.js'; import * as sequence_service_client_config from './sequence_service_client_config.json'; import fs from 'fs'; import path from 'path'; -import {fileURLToPath} from 'url'; -import {getJSON} from '../json-helper.cjs'; +import { fileURLToPath } from 'url'; +import { getJSON } from '../json-helper.cjs'; // @ts-ignore const dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -36,15 +41,15 @@ const dirname = path.dirname(fileURLToPath(import.meta.url)); * This file defines retry strategy and timeouts for all API methods in this library. */ const gapicConfig = getJSON( - path.join(dirname, 'sequence_service_client_config.json') + path.join(dirname, 'sequence_service_client_config.json'), ); const jsonProtos = getJSON( - path.join(dirname, '..', '..', '..', 'protos/protos.json') + path.join(dirname, '..', '..', '..', 'protos/protos.json'), ); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; const version = getJSON( - path.join(dirname, '..', '..', '..', '..', 'package.json') + path.join(dirname, '..', '..', '..', '..', 'package.json'), ).version; /** @@ -58,7 +63,7 @@ export class SequenceServiceClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('showcase'); @@ -70,9 +75,9 @@ export class SequenceServiceClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; - sequenceServiceStub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; + sequenceServiceStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of SequenceServiceClient. @@ -114,21 +119,42 @@ export class SequenceServiceClient { * const client = new SequenceServiceClient({fallback: 'rest'}, gax); * ``` */ - constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { // Ensure that options include all the required fields. const staticMembers = this.constructor as typeof SequenceServiceClient; - if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { - throw new Error('Please set either universe_domain or universeDomain, but not both.'); + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); } - const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; - this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; this._servicePath = 'localhost'; - const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; - const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. if (servicePath !== this._servicePath && !('scopes' in opts)) { @@ -150,7 +176,7 @@ export class SequenceServiceClient { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; @@ -167,10 +193,7 @@ export class SequenceServiceClient { const isEsm = true; const isEsmString = isEsm ? '-esm' : '-cjs'; // Determine the client header string. - const clientHeader = [ - `gax/${this._gaxModule.version}`, - `gapic/${version}`, - ]; + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/{process.versions.node}${isEsmString}`); } else { @@ -178,7 +201,7 @@ export class SequenceServiceClient { } if (!opts.fallback) { clientHeader.push(`grpc/${this._gaxGrpc.grpcVersion}`); - } else if (opts.fallback === 'rest' ) { + } else if (opts.fallback === 'rest') { clientHeader.push(`rest/${this._gaxGrpc.grpcVersion}`); } if (opts.libName && opts.libVersion) { @@ -186,51 +209,53 @@ export class SequenceServiceClient { } // Load the applicable protos. - this._protos = this._gaxGrpc.loadProtoJSON(jsonProtos as gax.protobuf.INamespace); + this._protos = this._gaxGrpc.loadProtoJSON( + jsonProtos as gax.protobuf.INamespace, + ); // This API contains "path templates"; forward-slash-separated // identifiers to uniquely identify resources within the API. // Create useful helper objects for these. this.pathTemplates = { blueprintPathTemplate: new this._gaxModule.PathTemplate( - 'sessions/{session}/tests/{test}/blueprints/{blueprint}' - ), - roomPathTemplate: new this._gaxModule.PathTemplate( - 'rooms/{room}' + 'sessions/{session}/tests/{test}/blueprints/{blueprint}', ), + roomPathTemplate: new this._gaxModule.PathTemplate('rooms/{room}'), roomBlurbPathTemplate: new this._gaxModule.PathTemplate( - 'rooms/{room}/blurbs/{blurb}' + 'rooms/{room}/blurbs/{blurb}', ), roomBlurbsLegacyRoomBlurbPathTemplate: new this._gaxModule.PathTemplate( - 'rooms/{room}/blurbs/legacy/{legacy_room}.{blurb}' + 'rooms/{room}/blurbs/legacy/{legacy_room}.{blurb}', ), sequencePathTemplate: new this._gaxModule.PathTemplate( - 'sequences/{sequence}' + 'sequences/{sequence}', ), sequenceReportPathTemplate: new this._gaxModule.PathTemplate( - 'sequences/{sequence}/sequenceReport' + 'sequences/{sequence}/sequenceReport', ), sessionPathTemplate: new this._gaxModule.PathTemplate( - 'sessions/{session}' + 'sessions/{session}', ), testPathTemplate: new this._gaxModule.PathTemplate( - 'sessions/{session}/tests/{test}' - ), - userPathTemplate: new this._gaxModule.PathTemplate( - 'users/{user}' + 'sessions/{session}/tests/{test}', ), + userPathTemplate: new this._gaxModule.PathTemplate('users/{user}'), userProfileBlurbPathTemplate: new this._gaxModule.PathTemplate( - 'users/{user}/profile/blurbs/{blurb}' - ), - userProfileBlurbsLegacyUserBlurbPathTemplate: new this._gaxModule.PathTemplate( - 'users/{user}/profile/blurbs/legacy/{legacy_user}~{blurb}' + 'users/{user}/profile/blurbs/{blurb}', ), + userProfileBlurbsLegacyUserBlurbPathTemplate: + new this._gaxModule.PathTemplate( + 'users/{user}/profile/blurbs/legacy/{legacy_user}~{blurb}', + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.showcase.v1beta1.SequenceService', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.showcase.v1beta1.SequenceService', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + { 'x-goog-api-client': clientHeader.join(' ') }, + ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -261,36 +286,44 @@ export class SequenceServiceClient { // Put together the "service stub" for // google.showcase.v1beta1.SequenceService. this.sequenceServiceStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.showcase.v1beta1.SequenceService') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.showcase.v1beta1.SequenceService', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.showcase.v1beta1.SequenceService, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts, + this._providedCustomServicePath, + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const sequenceServiceStubMethods = - ['createSequence', 'getSequenceReport', 'attemptSequence']; + const sequenceServiceStubMethods = [ + 'createSequence', + 'getSequenceReport', + 'attemptSequence', + ]; for (const methodName of sequenceServiceStubMethods) { const callPromise = this.sequenceServiceStub.then( - stub => (...args: Array<{}>) => { - if (this._terminated) { - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error|null|undefined) => () => { + (stub) => + (...args: Array<{}>) => { + if (this._terminated) { + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { throw err; - }); + }, + ); - const descriptor = - undefined; + const descriptor = undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -305,8 +338,14 @@ export class SequenceServiceClient { * @returns {string} The DNS address for this service. */ static get servicePath() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'localhost'; } @@ -318,8 +357,14 @@ export class SequenceServiceClient { * @returns {string} The DNS address for this service. */ static get apiEndpoint() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'localhost'; } @@ -359,8 +404,9 @@ export class SequenceServiceClient { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId(callback?: Callback): - Promise|void { + getProjectId( + callback?: Callback, + ): Promise | void { if (callback) { this.auth.getProjectId(callback); return; @@ -371,273 +417,385 @@ export class SequenceServiceClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Creates a sequence. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.showcase.v1beta1.Sequence} request.sequence - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.Sequence|Sequence}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/sequence_service.create_sequence.js - * region_tag:localhost_v1beta1_generated_SequenceService_CreateSequence_async - */ + /** + * Creates a sequence. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.showcase.v1beta1.Sequence} request.sequence + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.Sequence|Sequence}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/sequence_service.create_sequence.js + * region_tag:localhost_v1beta1_generated_SequenceService_CreateSequence_async + */ createSequence( - request?: protos.google.showcase.v1beta1.ICreateSequenceRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.ISequence, - protos.google.showcase.v1beta1.ICreateSequenceRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.ICreateSequenceRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.ISequence, + protos.google.showcase.v1beta1.ICreateSequenceRequest | undefined, + {} | undefined, + ] + >; createSequence( - request: protos.google.showcase.v1beta1.ICreateSequenceRequest, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.ISequence, - protos.google.showcase.v1beta1.ICreateSequenceRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.ICreateSequenceRequest, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.ISequence, + protos.google.showcase.v1beta1.ICreateSequenceRequest | null | undefined, + {} | null | undefined + >, + ): void; createSequence( - request: protos.google.showcase.v1beta1.ICreateSequenceRequest, - callback: Callback< - protos.google.showcase.v1beta1.ISequence, - protos.google.showcase.v1beta1.ICreateSequenceRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.ICreateSequenceRequest, + callback: Callback< + protos.google.showcase.v1beta1.ISequence, + protos.google.showcase.v1beta1.ICreateSequenceRequest | null | undefined, + {} | null | undefined + >, + ): void; createSequence( - request?: protos.google.showcase.v1beta1.ICreateSequenceRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.showcase.v1beta1.ISequence, - protos.google.showcase.v1beta1.ICreateSequenceRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.showcase.v1beta1.ICreateSequenceRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.ISequence, - protos.google.showcase.v1beta1.ICreateSequenceRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.ISequence, - protos.google.showcase.v1beta1.ICreateSequenceRequest|undefined, {}|undefined - ]>|void { + | protos.google.showcase.v1beta1.ICreateSequenceRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.ISequence, + protos.google.showcase.v1beta1.ICreateSequenceRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.ISequence, + protos.google.showcase.v1beta1.ICreateSequenceRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('createSequence request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.ISequence, - protos.google.showcase.v1beta1.ICreateSequenceRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.ISequence, + | protos.google.showcase.v1beta1.ICreateSequenceRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createSequence response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.createSequence(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.ISequence, - protos.google.showcase.v1beta1.ICreateSequenceRequest|undefined, {}|undefined - ]) => { - this._log.info('createSequence response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createSequence(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.ISequence, + protos.google.showcase.v1beta1.ICreateSequenceRequest | undefined, + {} | undefined, + ]) => { + this._log.info('createSequence response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Retrieves a sequence. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.SequenceReport|SequenceReport}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/sequence_service.get_sequence_report.js - * region_tag:localhost_v1beta1_generated_SequenceService_GetSequenceReport_async - */ + /** + * Retrieves a sequence. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.SequenceReport|SequenceReport}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/sequence_service.get_sequence_report.js + * region_tag:localhost_v1beta1_generated_SequenceService_GetSequenceReport_async + */ getSequenceReport( - request?: protos.google.showcase.v1beta1.IGetSequenceReportRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.ISequenceReport, - protos.google.showcase.v1beta1.IGetSequenceReportRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IGetSequenceReportRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.ISequenceReport, + protos.google.showcase.v1beta1.IGetSequenceReportRequest | undefined, + {} | undefined, + ] + >; getSequenceReport( - request: protos.google.showcase.v1beta1.IGetSequenceReportRequest, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.ISequenceReport, - protos.google.showcase.v1beta1.IGetSequenceReportRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IGetSequenceReportRequest, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.ISequenceReport, + | protos.google.showcase.v1beta1.IGetSequenceReportRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getSequenceReport( - request: protos.google.showcase.v1beta1.IGetSequenceReportRequest, - callback: Callback< - protos.google.showcase.v1beta1.ISequenceReport, - protos.google.showcase.v1beta1.IGetSequenceReportRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IGetSequenceReportRequest, + callback: Callback< + protos.google.showcase.v1beta1.ISequenceReport, + | protos.google.showcase.v1beta1.IGetSequenceReportRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getSequenceReport( - request?: protos.google.showcase.v1beta1.IGetSequenceReportRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.showcase.v1beta1.ISequenceReport, - protos.google.showcase.v1beta1.IGetSequenceReportRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.showcase.v1beta1.IGetSequenceReportRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.ISequenceReport, - protos.google.showcase.v1beta1.IGetSequenceReportRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.ISequenceReport, - protos.google.showcase.v1beta1.IGetSequenceReportRequest|undefined, {}|undefined - ]>|void { + | protos.google.showcase.v1beta1.IGetSequenceReportRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.ISequenceReport, + | protos.google.showcase.v1beta1.IGetSequenceReportRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.ISequenceReport, + protos.google.showcase.v1beta1.IGetSequenceReportRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getSequenceReport request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.ISequenceReport, - protos.google.showcase.v1beta1.IGetSequenceReportRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.ISequenceReport, + | protos.google.showcase.v1beta1.IGetSequenceReportRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getSequenceReport response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.getSequenceReport(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.ISequenceReport, - protos.google.showcase.v1beta1.IGetSequenceReportRequest|undefined, {}|undefined - ]) => { - this._log.info('getSequenceReport response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getSequenceReport(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.ISequenceReport, + protos.google.showcase.v1beta1.IGetSequenceReportRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getSequenceReport response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Attempts a sequence. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/sequence_service.attempt_sequence.js - * region_tag:localhost_v1beta1_generated_SequenceService_AttemptSequence_async - */ + /** + * Attempts a sequence. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/sequence_service.attempt_sequence.js + * region_tag:localhost_v1beta1_generated_SequenceService_AttemptSequence_async + */ attemptSequence( - request?: protos.google.showcase.v1beta1.IAttemptSequenceRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IAttemptSequenceRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IAttemptSequenceRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IAttemptSequenceRequest | undefined, + {} | undefined, + ] + >; attemptSequence( - request: protos.google.showcase.v1beta1.IAttemptSequenceRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IAttemptSequenceRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IAttemptSequenceRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IAttemptSequenceRequest | null | undefined, + {} | null | undefined + >, + ): void; attemptSequence( - request: protos.google.showcase.v1beta1.IAttemptSequenceRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IAttemptSequenceRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IAttemptSequenceRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IAttemptSequenceRequest | null | undefined, + {} | null | undefined + >, + ): void; attemptSequence( - request?: protos.google.showcase.v1beta1.IAttemptSequenceRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IAttemptSequenceRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.showcase.v1beta1.IAttemptSequenceRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IAttemptSequenceRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IAttemptSequenceRequest|undefined, {}|undefined - ]>|void { + | protos.google.showcase.v1beta1.IAttemptSequenceRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IAttemptSequenceRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IAttemptSequenceRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('attemptSequence request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IAttemptSequenceRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.showcase.v1beta1.IAttemptSequenceRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('attemptSequence response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.attemptSequence(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IAttemptSequenceRequest|undefined, {}|undefined - ]) => { - this._log.info('attemptSequence response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .attemptSequence(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IAttemptSequenceRequest | undefined, + {} | undefined, + ]) => { + this._log.info('attemptSequence response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); @@ -655,7 +813,7 @@ export class SequenceServiceClient { * @param {string} blueprint * @returns {string} Resource name string. */ - blueprintPath(session:string,test:string,blueprint:string) { + blueprintPath(session: string, test: string, blueprint: string) { return this.pathTemplates.blueprintPathTemplate.render({ session: session, test: test, @@ -671,7 +829,8 @@ export class SequenceServiceClient { * @returns {string} A string representing the session. */ matchSessionFromBlueprintName(blueprintName: string) { - return this.pathTemplates.blueprintPathTemplate.match(blueprintName).session; + return this.pathTemplates.blueprintPathTemplate.match(blueprintName) + .session; } /** @@ -693,7 +852,8 @@ export class SequenceServiceClient { * @returns {string} A string representing the blueprint. */ matchBlueprintFromBlueprintName(blueprintName: string) { - return this.pathTemplates.blueprintPathTemplate.match(blueprintName).blueprint; + return this.pathTemplates.blueprintPathTemplate.match(blueprintName) + .blueprint; } /** @@ -702,7 +862,7 @@ export class SequenceServiceClient { * @param {string} room * @returns {string} Resource name string. */ - roomPath(room:string) { + roomPath(room: string) { return this.pathTemplates.roomPathTemplate.render({ room: room, }); @@ -726,7 +886,7 @@ export class SequenceServiceClient { * @param {string} blurb * @returns {string} Resource name string. */ - roomBlurbPath(room:string,blurb:string) { + roomBlurbPath(room: string, blurb: string) { return this.pathTemplates.roomBlurbPathTemplate.render({ room: room, blurb: blurb, @@ -763,7 +923,11 @@ export class SequenceServiceClient { * @param {string} blurb * @returns {string} Resource name string. */ - roomBlurbsLegacyRoomBlurbPath(room:string,legacyRoom:string,blurb:string) { + roomBlurbsLegacyRoomBlurbPath( + room: string, + legacyRoom: string, + blurb: string, + ) { return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.render({ room: room, legacy_room: legacyRoom, @@ -778,8 +942,12 @@ export class SequenceServiceClient { * A fully-qualified path representing room_blurbs_legacy_room_blurb resource. * @returns {string} A string representing the room. */ - matchRoomFromRoomBlurbsLegacyRoomBlurbName(roomBlurbsLegacyRoomBlurbName: string) { - return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match(roomBlurbsLegacyRoomBlurbName).room; + matchRoomFromRoomBlurbsLegacyRoomBlurbName( + roomBlurbsLegacyRoomBlurbName: string, + ) { + return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match( + roomBlurbsLegacyRoomBlurbName, + ).room; } /** @@ -789,8 +957,12 @@ export class SequenceServiceClient { * A fully-qualified path representing room_blurbs_legacy_room_blurb resource. * @returns {string} A string representing the legacy_room. */ - matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName(roomBlurbsLegacyRoomBlurbName: string) { - return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match(roomBlurbsLegacyRoomBlurbName).legacy_room; + matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName( + roomBlurbsLegacyRoomBlurbName: string, + ) { + return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match( + roomBlurbsLegacyRoomBlurbName, + ).legacy_room; } /** @@ -800,8 +972,12 @@ export class SequenceServiceClient { * A fully-qualified path representing room_blurbs_legacy_room_blurb resource. * @returns {string} A string representing the blurb. */ - matchBlurbFromRoomBlurbsLegacyRoomBlurbName(roomBlurbsLegacyRoomBlurbName: string) { - return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match(roomBlurbsLegacyRoomBlurbName).blurb; + matchBlurbFromRoomBlurbsLegacyRoomBlurbName( + roomBlurbsLegacyRoomBlurbName: string, + ) { + return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match( + roomBlurbsLegacyRoomBlurbName, + ).blurb; } /** @@ -810,7 +986,7 @@ export class SequenceServiceClient { * @param {string} sequence * @returns {string} Resource name string. */ - sequencePath(sequence:string) { + sequencePath(sequence: string) { return this.pathTemplates.sequencePathTemplate.render({ sequence: sequence, }); @@ -833,7 +1009,7 @@ export class SequenceServiceClient { * @param {string} sequence * @returns {string} Resource name string. */ - sequenceReportPath(sequence:string) { + sequenceReportPath(sequence: string) { return this.pathTemplates.sequenceReportPathTemplate.render({ sequence: sequence, }); @@ -847,7 +1023,9 @@ export class SequenceServiceClient { * @returns {string} A string representing the sequence. */ matchSequenceFromSequenceReportName(sequenceReportName: string) { - return this.pathTemplates.sequenceReportPathTemplate.match(sequenceReportName).sequence; + return this.pathTemplates.sequenceReportPathTemplate.match( + sequenceReportName, + ).sequence; } /** @@ -856,7 +1034,7 @@ export class SequenceServiceClient { * @param {string} session * @returns {string} Resource name string. */ - sessionPath(session:string) { + sessionPath(session: string) { return this.pathTemplates.sessionPathTemplate.render({ session: session, }); @@ -880,7 +1058,7 @@ export class SequenceServiceClient { * @param {string} test * @returns {string} Resource name string. */ - testPath(session:string,test:string) { + testPath(session: string, test: string) { return this.pathTemplates.testPathTemplate.render({ session: session, test: test, @@ -915,7 +1093,7 @@ export class SequenceServiceClient { * @param {string} user * @returns {string} Resource name string. */ - userPath(user:string) { + userPath(user: string) { return this.pathTemplates.userPathTemplate.render({ user: user, }); @@ -939,7 +1117,7 @@ export class SequenceServiceClient { * @param {string} blurb * @returns {string} Resource name string. */ - userProfileBlurbPath(user:string,blurb:string) { + userProfileBlurbPath(user: string, blurb: string) { return this.pathTemplates.userProfileBlurbPathTemplate.render({ user: user, blurb: blurb, @@ -954,7 +1132,9 @@ export class SequenceServiceClient { * @returns {string} A string representing the user. */ matchUserFromUserProfileBlurbName(userProfileBlurbName: string) { - return this.pathTemplates.userProfileBlurbPathTemplate.match(userProfileBlurbName).user; + return this.pathTemplates.userProfileBlurbPathTemplate.match( + userProfileBlurbName, + ).user; } /** @@ -965,7 +1145,9 @@ export class SequenceServiceClient { * @returns {string} A string representing the blurb. */ matchBlurbFromUserProfileBlurbName(userProfileBlurbName: string) { - return this.pathTemplates.userProfileBlurbPathTemplate.match(userProfileBlurbName).blurb; + return this.pathTemplates.userProfileBlurbPathTemplate.match( + userProfileBlurbName, + ).blurb; } /** @@ -976,12 +1158,18 @@ export class SequenceServiceClient { * @param {string} blurb * @returns {string} Resource name string. */ - userProfileBlurbsLegacyUserBlurbPath(user:string,legacyUser:string,blurb:string) { - return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.render({ - user: user, - legacy_user: legacyUser, - blurb: blurb, - }); + userProfileBlurbsLegacyUserBlurbPath( + user: string, + legacyUser: string, + blurb: string, + ) { + return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.render( + { + user: user, + legacy_user: legacyUser, + blurb: blurb, + }, + ); } /** @@ -991,8 +1179,12 @@ export class SequenceServiceClient { * A fully-qualified path representing user_profile_blurbs_legacy_user_blurb resource. * @returns {string} A string representing the user. */ - matchUserFromUserProfileBlurbsLegacyUserBlurbName(userProfileBlurbsLegacyUserBlurbName: string) { - return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match(userProfileBlurbsLegacyUserBlurbName).user; + matchUserFromUserProfileBlurbsLegacyUserBlurbName( + userProfileBlurbsLegacyUserBlurbName: string, + ) { + return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match( + userProfileBlurbsLegacyUserBlurbName, + ).user; } /** @@ -1002,8 +1194,12 @@ export class SequenceServiceClient { * A fully-qualified path representing user_profile_blurbs_legacy_user_blurb resource. * @returns {string} A string representing the legacy_user. */ - matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName(userProfileBlurbsLegacyUserBlurbName: string) { - return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match(userProfileBlurbsLegacyUserBlurbName).legacy_user; + matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName( + userProfileBlurbsLegacyUserBlurbName: string, + ) { + return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match( + userProfileBlurbsLegacyUserBlurbName, + ).legacy_user; } /** @@ -1013,8 +1209,12 @@ export class SequenceServiceClient { * A fully-qualified path representing user_profile_blurbs_legacy_user_blurb resource. * @returns {string} A string representing the blurb. */ - matchBlurbFromUserProfileBlurbsLegacyUserBlurbName(userProfileBlurbsLegacyUserBlurbName: string) { - return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match(userProfileBlurbsLegacyUserBlurbName).blurb; + matchBlurbFromUserProfileBlurbsLegacyUserBlurbName( + userProfileBlurbsLegacyUserBlurbName: string, + ) { + return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match( + userProfileBlurbsLegacyUserBlurbName, + ).blurb; } /** @@ -1025,7 +1225,7 @@ export class SequenceServiceClient { */ close(): Promise { if (this.sequenceServiceStub && !this._terminated) { - return this.sequenceServiceStub.then(stub => { + return this.sequenceServiceStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -1033,4 +1233,4 @@ export class SequenceServiceClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/core/generator/gapic-generator-typescript/baselines/disable-packing-test-esm/esm/src/v1beta1/testing_client.ts.baseline b/core/generator/gapic-generator-typescript/baselines/disable-packing-test-esm/esm/src/v1beta1/testing_client.ts.baseline index 4861b537ba76..4e6bd730df3f 100644 --- a/core/generator/gapic-generator-typescript/baselines/disable-packing-test-esm/esm/src/v1beta1/testing_client.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/disable-packing-test-esm/esm/src/v1beta1/testing_client.ts.baseline @@ -18,15 +18,22 @@ /* global window */ import * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions, PaginationCallback, GaxCall} from 'google-gax'; -import {Transform} from 'stream'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + PaginationCallback, + GaxCall, +} from 'google-gax'; +import { Transform } from 'stream'; // @ts-ignore import type * as protos from '../../../protos/protos.js'; import * as testing_client_config from './testing_client_config.json'; import fs from 'fs'; import path from 'path'; -import {fileURLToPath} from 'url'; -import {getJSON} from '../json-helper.cjs'; +import { fileURLToPath } from 'url'; +import { getJSON } from '../json-helper.cjs'; // @ts-ignore const dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -35,16 +42,14 @@ const dirname = path.dirname(fileURLToPath(import.meta.url)); * `src/v1beta1/testing_client_config.json`. * This file defines retry strategy and timeouts for all API methods in this library. */ -const gapicConfig = getJSON( - path.join(dirname, 'testing_client_config.json') -); +const gapicConfig = getJSON(path.join(dirname, 'testing_client_config.json')); const jsonProtos = getJSON( - path.join(dirname, '..', '..', '..', 'protos/protos.json') + path.join(dirname, '..', '..', '..', 'protos/protos.json'), ); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; const version = getJSON( - path.join(dirname, '..', '..', '..', '..', 'package.json') + path.join(dirname, '..', '..', '..', '..', 'package.json'), ).version; /** @@ -60,7 +65,7 @@ export class TestingClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('showcase'); @@ -72,9 +77,9 @@ export class TestingClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; - testingStub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; + testingStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of TestingClient. @@ -116,21 +121,42 @@ export class TestingClient { * const client = new TestingClient({fallback: 'rest'}, gax); * ``` */ - constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { // Ensure that options include all the required fields. const staticMembers = this.constructor as typeof TestingClient; - if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { - throw new Error('Please set either universe_domain or universeDomain, but not both.'); + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); } - const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; - this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; this._servicePath = 'localhost'; - const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; - const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. if (servicePath !== this._servicePath && !('scopes' in opts)) { @@ -152,7 +178,7 @@ export class TestingClient { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; @@ -169,10 +195,7 @@ export class TestingClient { const isEsm = true; const isEsmString = isEsm ? '-esm' : '-cjs'; // Determine the client header string. - const clientHeader = [ - `gax/${this._gaxModule.version}`, - `gapic/${version}`, - ]; + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/{process.versions.node}${isEsmString}`); } else { @@ -180,7 +203,7 @@ export class TestingClient { } if (!opts.fallback) { clientHeader.push(`grpc/${this._gaxGrpc.grpcVersion}`); - } else if (opts.fallback === 'rest' ) { + } else if (opts.fallback === 'rest') { clientHeader.push(`rest/${this._gaxGrpc.grpcVersion}`); } if (opts.libName && opts.libVersion) { @@ -188,61 +211,69 @@ export class TestingClient { } // Load the applicable protos. - this._protos = this._gaxGrpc.loadProtoJSON(jsonProtos as gax.protobuf.INamespace); + this._protos = this._gaxGrpc.loadProtoJSON( + jsonProtos as gax.protobuf.INamespace, + ); // This API contains "path templates"; forward-slash-separated // identifiers to uniquely identify resources within the API. // Create useful helper objects for these. this.pathTemplates = { blueprintPathTemplate: new this._gaxModule.PathTemplate( - 'sessions/{session}/tests/{test}/blueprints/{blueprint}' - ), - roomPathTemplate: new this._gaxModule.PathTemplate( - 'rooms/{room}' + 'sessions/{session}/tests/{test}/blueprints/{blueprint}', ), + roomPathTemplate: new this._gaxModule.PathTemplate('rooms/{room}'), roomBlurbPathTemplate: new this._gaxModule.PathTemplate( - 'rooms/{room}/blurbs/{blurb}' + 'rooms/{room}/blurbs/{blurb}', ), roomBlurbsLegacyRoomBlurbPathTemplate: new this._gaxModule.PathTemplate( - 'rooms/{room}/blurbs/legacy/{legacy_room}.{blurb}' + 'rooms/{room}/blurbs/legacy/{legacy_room}.{blurb}', ), sequencePathTemplate: new this._gaxModule.PathTemplate( - 'sequences/{sequence}' + 'sequences/{sequence}', ), sequenceReportPathTemplate: new this._gaxModule.PathTemplate( - 'sequences/{sequence}/sequenceReport' + 'sequences/{sequence}/sequenceReport', ), sessionPathTemplate: new this._gaxModule.PathTemplate( - 'sessions/{session}' + 'sessions/{session}', ), testPathTemplate: new this._gaxModule.PathTemplate( - 'sessions/{session}/tests/{test}' - ), - userPathTemplate: new this._gaxModule.PathTemplate( - 'users/{user}' + 'sessions/{session}/tests/{test}', ), + userPathTemplate: new this._gaxModule.PathTemplate('users/{user}'), userProfileBlurbPathTemplate: new this._gaxModule.PathTemplate( - 'users/{user}/profile/blurbs/{blurb}' - ), - userProfileBlurbsLegacyUserBlurbPathTemplate: new this._gaxModule.PathTemplate( - 'users/{user}/profile/blurbs/legacy/{legacy_user}~{blurb}' + 'users/{user}/profile/blurbs/{blurb}', ), + userProfileBlurbsLegacyUserBlurbPathTemplate: + new this._gaxModule.PathTemplate( + 'users/{user}/profile/blurbs/legacy/{legacy_user}~{blurb}', + ), }; // Some of the methods on this service return "paged" results, // (e.g. 50 results at a time, with tokens to get subsequent // pages). Denote the keys used for pagination and results. this.descriptors.page = { - listSessions: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'sessions'), - listTests: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'tests') + listSessions: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'sessions', + ), + listTests: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'tests', + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.showcase.v1beta1.Testing', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.showcase.v1beta1.Testing', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + { 'x-goog-api-client': clientHeader.join(' ') }, + ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -273,37 +304,49 @@ export class TestingClient { // Put together the "service stub" for // google.showcase.v1beta1.Testing. this.testingStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.showcase.v1beta1.Testing') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.showcase.v1beta1.Testing', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.showcase.v1beta1.Testing, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts, + this._providedCustomServicePath, + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const testingStubMethods = - ['createSession', 'getSession', 'listSessions', 'deleteSession', 'reportSession', 'listTests', 'deleteTest', 'verifyTest']; + const testingStubMethods = [ + 'createSession', + 'getSession', + 'listSessions', + 'deleteSession', + 'reportSession', + 'listTests', + 'deleteTest', + 'verifyTest', + ]; for (const methodName of testingStubMethods) { const callPromise = this.testingStub.then( - stub => (...args: Array<{}>) => { - if (this._terminated) { - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error|null|undefined) => () => { + (stub) => + (...args: Array<{}>) => { + if (this._terminated) { + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { throw err; - }); + }, + ); - const descriptor = - this.descriptors.page[methodName] || - undefined; + const descriptor = this.descriptors.page[methodName] || undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -318,8 +361,14 @@ export class TestingClient { * @returns {string} The DNS address for this service. */ static get servicePath() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'localhost'; } @@ -331,8 +380,14 @@ export class TestingClient { * @returns {string} The DNS address for this service. */ static get apiEndpoint() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'localhost'; } @@ -372,8 +427,9 @@ export class TestingClient { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId(callback?: Callback): - Promise|void { + getProjectId( + callback?: Callback, + ): Promise | void { if (callback) { this.auth.getProjectId(callback); return; @@ -384,650 +440,869 @@ export class TestingClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Creates a new testing session. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.showcase.v1beta1.Session} request.session - * The session to be created. - * Sessions are immutable once they are created (although they can - * be deleted). - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.Session|Session}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/testing.create_session.js - * region_tag:localhost_v1beta1_generated_Testing_CreateSession_async - */ + /** + * Creates a new testing session. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.showcase.v1beta1.Session} request.session + * The session to be created. + * Sessions are immutable once they are created (although they can + * be deleted). + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.Session|Session}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/testing.create_session.js + * region_tag:localhost_v1beta1_generated_Testing_CreateSession_async + */ createSession( - request?: protos.google.showcase.v1beta1.ICreateSessionRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.ISession, - protos.google.showcase.v1beta1.ICreateSessionRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.ICreateSessionRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.ISession, + protos.google.showcase.v1beta1.ICreateSessionRequest | undefined, + {} | undefined, + ] + >; createSession( - request: protos.google.showcase.v1beta1.ICreateSessionRequest, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.ISession, - protos.google.showcase.v1beta1.ICreateSessionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.ICreateSessionRequest, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.ISession, + protos.google.showcase.v1beta1.ICreateSessionRequest | null | undefined, + {} | null | undefined + >, + ): void; createSession( - request: protos.google.showcase.v1beta1.ICreateSessionRequest, - callback: Callback< - protos.google.showcase.v1beta1.ISession, - protos.google.showcase.v1beta1.ICreateSessionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.ICreateSessionRequest, + callback: Callback< + protos.google.showcase.v1beta1.ISession, + protos.google.showcase.v1beta1.ICreateSessionRequest | null | undefined, + {} | null | undefined + >, + ): void; createSession( - request?: protos.google.showcase.v1beta1.ICreateSessionRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.showcase.v1beta1.ISession, - protos.google.showcase.v1beta1.ICreateSessionRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.showcase.v1beta1.ICreateSessionRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.ISession, - protos.google.showcase.v1beta1.ICreateSessionRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.ISession, - protos.google.showcase.v1beta1.ICreateSessionRequest|undefined, {}|undefined - ]>|void { + | protos.google.showcase.v1beta1.ICreateSessionRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.ISession, + protos.google.showcase.v1beta1.ICreateSessionRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.ISession, + protos.google.showcase.v1beta1.ICreateSessionRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('createSession request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.ISession, - protos.google.showcase.v1beta1.ICreateSessionRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.ISession, + | protos.google.showcase.v1beta1.ICreateSessionRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createSession response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.createSession(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.ISession, - protos.google.showcase.v1beta1.ICreateSessionRequest|undefined, {}|undefined - ]) => { - this._log.info('createSession response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createSession(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.ISession, + protos.google.showcase.v1beta1.ICreateSessionRequest | undefined, + {} | undefined, + ]) => { + this._log.info('createSession response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Gets a testing session. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * The session to be retrieved. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.Session|Session}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/testing.get_session.js - * region_tag:localhost_v1beta1_generated_Testing_GetSession_async - */ + /** + * Gets a testing session. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * The session to be retrieved. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.Session|Session}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/testing.get_session.js + * region_tag:localhost_v1beta1_generated_Testing_GetSession_async + */ getSession( - request?: protos.google.showcase.v1beta1.IGetSessionRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.ISession, - protos.google.showcase.v1beta1.IGetSessionRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IGetSessionRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.ISession, + protos.google.showcase.v1beta1.IGetSessionRequest | undefined, + {} | undefined, + ] + >; getSession( - request: protos.google.showcase.v1beta1.IGetSessionRequest, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.ISession, - protos.google.showcase.v1beta1.IGetSessionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IGetSessionRequest, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.ISession, + protos.google.showcase.v1beta1.IGetSessionRequest | null | undefined, + {} | null | undefined + >, + ): void; getSession( - request: protos.google.showcase.v1beta1.IGetSessionRequest, - callback: Callback< - protos.google.showcase.v1beta1.ISession, - protos.google.showcase.v1beta1.IGetSessionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IGetSessionRequest, + callback: Callback< + protos.google.showcase.v1beta1.ISession, + protos.google.showcase.v1beta1.IGetSessionRequest | null | undefined, + {} | null | undefined + >, + ): void; getSession( - request?: protos.google.showcase.v1beta1.IGetSessionRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.showcase.v1beta1.ISession, - protos.google.showcase.v1beta1.IGetSessionRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.showcase.v1beta1.IGetSessionRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.ISession, - protos.google.showcase.v1beta1.IGetSessionRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.ISession, - protos.google.showcase.v1beta1.IGetSessionRequest|undefined, {}|undefined - ]>|void { + protos.google.showcase.v1beta1.IGetSessionRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.ISession, + protos.google.showcase.v1beta1.IGetSessionRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.ISession, + protos.google.showcase.v1beta1.IGetSessionRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getSession request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.ISession, - protos.google.showcase.v1beta1.IGetSessionRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.ISession, + protos.google.showcase.v1beta1.IGetSessionRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getSession response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.getSession(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.ISession, - protos.google.showcase.v1beta1.IGetSessionRequest|undefined, {}|undefined - ]) => { - this._log.info('getSession response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getSession(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.ISession, + protos.google.showcase.v1beta1.IGetSessionRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getSession response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Delete a test session. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * The session to be deleted. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/testing.delete_session.js - * region_tag:localhost_v1beta1_generated_Testing_DeleteSession_async - */ + /** + * Delete a test session. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * The session to be deleted. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/testing.delete_session.js + * region_tag:localhost_v1beta1_generated_Testing_DeleteSession_async + */ deleteSession( - request?: protos.google.showcase.v1beta1.IDeleteSessionRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteSessionRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IDeleteSessionRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteSessionRequest | undefined, + {} | undefined, + ] + >; deleteSession( - request: protos.google.showcase.v1beta1.IDeleteSessionRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteSessionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IDeleteSessionRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteSessionRequest | null | undefined, + {} | null | undefined + >, + ): void; deleteSession( - request: protos.google.showcase.v1beta1.IDeleteSessionRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteSessionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IDeleteSessionRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteSessionRequest | null | undefined, + {} | null | undefined + >, + ): void; deleteSession( - request?: protos.google.showcase.v1beta1.IDeleteSessionRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteSessionRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.showcase.v1beta1.IDeleteSessionRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteSessionRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteSessionRequest|undefined, {}|undefined - ]>|void { + | protos.google.showcase.v1beta1.IDeleteSessionRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteSessionRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteSessionRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('deleteSession request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteSessionRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.showcase.v1beta1.IDeleteSessionRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteSession response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.deleteSession(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteSessionRequest|undefined, {}|undefined - ]) => { - this._log.info('deleteSession response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteSession(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteSessionRequest | undefined, + {} | undefined, + ]) => { + this._log.info('deleteSession response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Report on the status of a session. - * This generates a report detailing which tests have been completed, - * and an overall rollup. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * The session to be reported on. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.ReportSessionResponse|ReportSessionResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/testing.report_session.js - * region_tag:localhost_v1beta1_generated_Testing_ReportSession_async - */ + /** + * Report on the status of a session. + * This generates a report detailing which tests have been completed, + * and an overall rollup. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * The session to be reported on. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.ReportSessionResponse|ReportSessionResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/testing.report_session.js + * region_tag:localhost_v1beta1_generated_Testing_ReportSession_async + */ reportSession( - request?: protos.google.showcase.v1beta1.IReportSessionRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IReportSessionResponse, - protos.google.showcase.v1beta1.IReportSessionRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IReportSessionRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IReportSessionResponse, + protos.google.showcase.v1beta1.IReportSessionRequest | undefined, + {} | undefined, + ] + >; reportSession( - request: protos.google.showcase.v1beta1.IReportSessionRequest, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.IReportSessionResponse, - protos.google.showcase.v1beta1.IReportSessionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IReportSessionRequest, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.IReportSessionResponse, + protos.google.showcase.v1beta1.IReportSessionRequest | null | undefined, + {} | null | undefined + >, + ): void; reportSession( - request: protos.google.showcase.v1beta1.IReportSessionRequest, - callback: Callback< - protos.google.showcase.v1beta1.IReportSessionResponse, - protos.google.showcase.v1beta1.IReportSessionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IReportSessionRequest, + callback: Callback< + protos.google.showcase.v1beta1.IReportSessionResponse, + protos.google.showcase.v1beta1.IReportSessionRequest | null | undefined, + {} | null | undefined + >, + ): void; reportSession( - request?: protos.google.showcase.v1beta1.IReportSessionRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.showcase.v1beta1.IReportSessionRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.IReportSessionResponse, - protos.google.showcase.v1beta1.IReportSessionRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.showcase.v1beta1.IReportSessionResponse, - protos.google.showcase.v1beta1.IReportSessionRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.IReportSessionResponse, - protos.google.showcase.v1beta1.IReportSessionRequest|undefined, {}|undefined - ]>|void { + | protos.google.showcase.v1beta1.IReportSessionRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.IReportSessionResponse, + protos.google.showcase.v1beta1.IReportSessionRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IReportSessionResponse, + protos.google.showcase.v1beta1.IReportSessionRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('reportSession request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.IReportSessionResponse, - protos.google.showcase.v1beta1.IReportSessionRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.IReportSessionResponse, + | protos.google.showcase.v1beta1.IReportSessionRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('reportSession response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.reportSession(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.IReportSessionResponse, - protos.google.showcase.v1beta1.IReportSessionRequest|undefined, {}|undefined - ]) => { - this._log.info('reportSession response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .reportSession(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.IReportSessionResponse, + protos.google.showcase.v1beta1.IReportSessionRequest | undefined, + {} | undefined, + ]) => { + this._log.info('reportSession response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Explicitly decline to implement a test. - * - * This removes the test from subsequent `ListTests` calls, and - * attempting to do the test will error. - * - * This method will error if attempting to delete a required test. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * The test to be deleted. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/testing.delete_test.js - * region_tag:localhost_v1beta1_generated_Testing_DeleteTest_async - */ + /** + * Explicitly decline to implement a test. + * + * This removes the test from subsequent `ListTests` calls, and + * attempting to do the test will error. + * + * This method will error if attempting to delete a required test. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * The test to be deleted. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/testing.delete_test.js + * region_tag:localhost_v1beta1_generated_Testing_DeleteTest_async + */ deleteTest( - request?: protos.google.showcase.v1beta1.IDeleteTestRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteTestRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IDeleteTestRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteTestRequest | undefined, + {} | undefined, + ] + >; deleteTest( - request: protos.google.showcase.v1beta1.IDeleteTestRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteTestRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IDeleteTestRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteTestRequest | null | undefined, + {} | null | undefined + >, + ): void; deleteTest( - request: protos.google.showcase.v1beta1.IDeleteTestRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteTestRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IDeleteTestRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteTestRequest | null | undefined, + {} | null | undefined + >, + ): void; deleteTest( - request?: protos.google.showcase.v1beta1.IDeleteTestRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteTestRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.showcase.v1beta1.IDeleteTestRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteTestRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteTestRequest|undefined, {}|undefined - ]>|void { + protos.google.showcase.v1beta1.IDeleteTestRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteTestRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteTestRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('deleteTest request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteTestRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteTestRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteTest response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.deleteTest(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteTestRequest|undefined, {}|undefined - ]) => { - this._log.info('deleteTest response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteTest(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteTestRequest | undefined, + {} | undefined, + ]) => { + this._log.info('deleteTest response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Register a response to a test. - * - * In cases where a test involves registering a final answer at the - * end of the test, this method provides the means to do so. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * The test to have an answer registered to it. - * @param {Buffer} request.answer - * The answer from the test. - * @param {Buffer[]} request.answers - * The answers from the test if multiple are to be checked - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.VerifyTestResponse|VerifyTestResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/testing.verify_test.js - * region_tag:localhost_v1beta1_generated_Testing_VerifyTest_async - */ + /** + * Register a response to a test. + * + * In cases where a test involves registering a final answer at the + * end of the test, this method provides the means to do so. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * The test to have an answer registered to it. + * @param {Buffer} request.answer + * The answer from the test. + * @param {Buffer[]} request.answers + * The answers from the test if multiple are to be checked + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.VerifyTestResponse|VerifyTestResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/testing.verify_test.js + * region_tag:localhost_v1beta1_generated_Testing_VerifyTest_async + */ verifyTest( - request?: protos.google.showcase.v1beta1.IVerifyTestRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IVerifyTestResponse, - protos.google.showcase.v1beta1.IVerifyTestRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IVerifyTestRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IVerifyTestResponse, + protos.google.showcase.v1beta1.IVerifyTestRequest | undefined, + {} | undefined, + ] + >; verifyTest( - request: protos.google.showcase.v1beta1.IVerifyTestRequest, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.IVerifyTestResponse, - protos.google.showcase.v1beta1.IVerifyTestRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IVerifyTestRequest, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.IVerifyTestResponse, + protos.google.showcase.v1beta1.IVerifyTestRequest | null | undefined, + {} | null | undefined + >, + ): void; verifyTest( - request: protos.google.showcase.v1beta1.IVerifyTestRequest, - callback: Callback< - protos.google.showcase.v1beta1.IVerifyTestResponse, - protos.google.showcase.v1beta1.IVerifyTestRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IVerifyTestRequest, + callback: Callback< + protos.google.showcase.v1beta1.IVerifyTestResponse, + protos.google.showcase.v1beta1.IVerifyTestRequest | null | undefined, + {} | null | undefined + >, + ): void; verifyTest( - request?: protos.google.showcase.v1beta1.IVerifyTestRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.showcase.v1beta1.IVerifyTestResponse, - protos.google.showcase.v1beta1.IVerifyTestRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.showcase.v1beta1.IVerifyTestRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.IVerifyTestResponse, - protos.google.showcase.v1beta1.IVerifyTestRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.IVerifyTestResponse, - protos.google.showcase.v1beta1.IVerifyTestRequest|undefined, {}|undefined - ]>|void { + protos.google.showcase.v1beta1.IVerifyTestRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.IVerifyTestResponse, + protos.google.showcase.v1beta1.IVerifyTestRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IVerifyTestResponse, + protos.google.showcase.v1beta1.IVerifyTestRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('verifyTest request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.IVerifyTestResponse, - protos.google.showcase.v1beta1.IVerifyTestRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.IVerifyTestResponse, + protos.google.showcase.v1beta1.IVerifyTestRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('verifyTest response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.verifyTest(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.IVerifyTestResponse, - protos.google.showcase.v1beta1.IVerifyTestRequest|undefined, {}|undefined - ]) => { - this._log.info('verifyTest response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .verifyTest(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.IVerifyTestResponse, + protos.google.showcase.v1beta1.IVerifyTestRequest | undefined, + {} | undefined, + ]) => { + this._log.info('verifyTest response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } - /** - * Lists the current test sessions. - * - * @param {Object} request - * The request object that will be sent. - * @param {number} request.pageSize - * The maximum number of sessions to return per page. - * @param {string} request.pageToken - * The page token, for retrieving subsequent pages. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.showcase.v1beta1.Session|Session}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `listSessionsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Lists the current test sessions. + * + * @param {Object} request + * The request object that will be sent. + * @param {number} request.pageSize + * The maximum number of sessions to return per page. + * @param {string} request.pageToken + * The page token, for retrieving subsequent pages. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.showcase.v1beta1.Session|Session}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listSessionsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listSessions( - request?: protos.google.showcase.v1beta1.IListSessionsRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.ISession[], - protos.google.showcase.v1beta1.IListSessionsRequest|null, - protos.google.showcase.v1beta1.IListSessionsResponse - ]>; + request?: protos.google.showcase.v1beta1.IListSessionsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.ISession[], + protos.google.showcase.v1beta1.IListSessionsRequest | null, + protos.google.showcase.v1beta1.IListSessionsResponse, + ] + >; listSessions( - request: protos.google.showcase.v1beta1.IListSessionsRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.showcase.v1beta1.IListSessionsRequest, - protos.google.showcase.v1beta1.IListSessionsResponse|null|undefined, - protos.google.showcase.v1beta1.ISession>): void; + request: protos.google.showcase.v1beta1.IListSessionsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.showcase.v1beta1.IListSessionsRequest, + protos.google.showcase.v1beta1.IListSessionsResponse | null | undefined, + protos.google.showcase.v1beta1.ISession + >, + ): void; listSessions( - request: protos.google.showcase.v1beta1.IListSessionsRequest, - callback: PaginationCallback< - protos.google.showcase.v1beta1.IListSessionsRequest, - protos.google.showcase.v1beta1.IListSessionsResponse|null|undefined, - protos.google.showcase.v1beta1.ISession>): void; + request: protos.google.showcase.v1beta1.IListSessionsRequest, + callback: PaginationCallback< + protos.google.showcase.v1beta1.IListSessionsRequest, + protos.google.showcase.v1beta1.IListSessionsResponse | null | undefined, + protos.google.showcase.v1beta1.ISession + >, + ): void; listSessions( - request?: protos.google.showcase.v1beta1.IListSessionsRequest, - optionsOrCallback?: CallOptions|PaginationCallback< - protos.google.showcase.v1beta1.IListSessionsRequest, - protos.google.showcase.v1beta1.IListSessionsResponse|null|undefined, - protos.google.showcase.v1beta1.ISession>, - callback?: PaginationCallback< + request?: protos.google.showcase.v1beta1.IListSessionsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.showcase.v1beta1.IListSessionsRequest, - protos.google.showcase.v1beta1.IListSessionsResponse|null|undefined, - protos.google.showcase.v1beta1.ISession>): - Promise<[ - protos.google.showcase.v1beta1.ISession[], - protos.google.showcase.v1beta1.IListSessionsRequest|null, - protos.google.showcase.v1beta1.IListSessionsResponse - ]>|void { + | protos.google.showcase.v1beta1.IListSessionsResponse + | null + | undefined, + protos.google.showcase.v1beta1.ISession + >, + callback?: PaginationCallback< + protos.google.showcase.v1beta1.IListSessionsRequest, + protos.google.showcase.v1beta1.IListSessionsResponse | null | undefined, + protos.google.showcase.v1beta1.ISession + >, + ): Promise< + [ + protos.google.showcase.v1beta1.ISession[], + protos.google.showcase.v1beta1.IListSessionsRequest | null, + protos.google.showcase.v1beta1.IListSessionsResponse, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.showcase.v1beta1.IListSessionsRequest, - protos.google.showcase.v1beta1.IListSessionsResponse|null|undefined, - protos.google.showcase.v1beta1.ISession>|undefined = callback + this.initialize().catch((err) => { + throw err; + }); + const wrappedCallback: + | PaginationCallback< + protos.google.showcase.v1beta1.IListSessionsRequest, + | protos.google.showcase.v1beta1.IListSessionsResponse + | null + | undefined, + protos.google.showcase.v1beta1.ISession + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listSessions values %j', values); callback!(error, values, nextPageRequest, rawResponse); @@ -1036,175 +1311,196 @@ export class TestingClient { this._log.info('listSessions request %j', request); return this.innerApiCalls .listSessions(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.showcase.v1beta1.ISession[], - protos.google.showcase.v1beta1.IListSessionsRequest|null, - protos.google.showcase.v1beta1.IListSessionsResponse - ]) => { - this._log.info('listSessions values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.showcase.v1beta1.ISession[], + protos.google.showcase.v1beta1.IListSessionsRequest | null, + protos.google.showcase.v1beta1.IListSessionsResponse, + ]) => { + this._log.info('listSessions values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listSessions`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {number} request.pageSize - * The maximum number of sessions to return per page. - * @param {string} request.pageToken - * The page token, for retrieving subsequent pages. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.showcase.v1beta1.Session|Session} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `listSessionsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `listSessions`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {number} request.pageSize + * The maximum number of sessions to return per page. + * @param {string} request.pageToken + * The page token, for retrieving subsequent pages. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.showcase.v1beta1.Session|Session} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listSessionsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listSessionsStream( - request?: protos.google.showcase.v1beta1.IListSessionsRequest, - options?: CallOptions): - Transform{ + request?: protos.google.showcase.v1beta1.IListSessionsRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; const defaultCallSettings = this._defaults['listSessions']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listSessions stream %j', request); return this.descriptors.page.listSessions.createStream( this.innerApiCalls.listSessions as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listSessions`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {number} request.pageSize - * The maximum number of sessions to return per page. - * @param {string} request.pageToken - * The page token, for retrieving subsequent pages. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.showcase.v1beta1.Session|Session}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/testing.list_sessions.js - * region_tag:localhost_v1beta1_generated_Testing_ListSessions_async - */ + /** + * Equivalent to `listSessions`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {number} request.pageSize + * The maximum number of sessions to return per page. + * @param {string} request.pageToken + * The page token, for retrieving subsequent pages. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.showcase.v1beta1.Session|Session}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/testing.list_sessions.js + * region_tag:localhost_v1beta1_generated_Testing_ListSessions_async + */ listSessionsAsync( - request?: protos.google.showcase.v1beta1.IListSessionsRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.showcase.v1beta1.IListSessionsRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; const defaultCallSettings = this._defaults['listSessions']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listSessions iterate %j', request); return this.descriptors.page.listSessions.asyncIterate( this.innerApiCalls['listSessions'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } - /** - * List the tests of a sessesion. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * The session. - * @param {number} request.pageSize - * The maximum number of tests to return per page. - * @param {string} request.pageToken - * The page token, for retrieving subsequent pages. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.showcase.v1beta1.Test|Test}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `listTestsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * List the tests of a sessesion. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * The session. + * @param {number} request.pageSize + * The maximum number of tests to return per page. + * @param {string} request.pageToken + * The page token, for retrieving subsequent pages. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.showcase.v1beta1.Test|Test}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listTestsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listTests( - request?: protos.google.showcase.v1beta1.IListTestsRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.ITest[], - protos.google.showcase.v1beta1.IListTestsRequest|null, - protos.google.showcase.v1beta1.IListTestsResponse - ]>; + request?: protos.google.showcase.v1beta1.IListTestsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.ITest[], + protos.google.showcase.v1beta1.IListTestsRequest | null, + protos.google.showcase.v1beta1.IListTestsResponse, + ] + >; listTests( - request: protos.google.showcase.v1beta1.IListTestsRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.showcase.v1beta1.IListTestsRequest, - protos.google.showcase.v1beta1.IListTestsResponse|null|undefined, - protos.google.showcase.v1beta1.ITest>): void; + request: protos.google.showcase.v1beta1.IListTestsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.showcase.v1beta1.IListTestsRequest, + protos.google.showcase.v1beta1.IListTestsResponse | null | undefined, + protos.google.showcase.v1beta1.ITest + >, + ): void; listTests( - request: protos.google.showcase.v1beta1.IListTestsRequest, - callback: PaginationCallback< - protos.google.showcase.v1beta1.IListTestsRequest, - protos.google.showcase.v1beta1.IListTestsResponse|null|undefined, - protos.google.showcase.v1beta1.ITest>): void; + request: protos.google.showcase.v1beta1.IListTestsRequest, + callback: PaginationCallback< + protos.google.showcase.v1beta1.IListTestsRequest, + protos.google.showcase.v1beta1.IListTestsResponse | null | undefined, + protos.google.showcase.v1beta1.ITest + >, + ): void; listTests( - request?: protos.google.showcase.v1beta1.IListTestsRequest, - optionsOrCallback?: CallOptions|PaginationCallback< - protos.google.showcase.v1beta1.IListTestsRequest, - protos.google.showcase.v1beta1.IListTestsResponse|null|undefined, - protos.google.showcase.v1beta1.ITest>, - callback?: PaginationCallback< + request?: protos.google.showcase.v1beta1.IListTestsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.showcase.v1beta1.IListTestsRequest, - protos.google.showcase.v1beta1.IListTestsResponse|null|undefined, - protos.google.showcase.v1beta1.ITest>): - Promise<[ - protos.google.showcase.v1beta1.ITest[], - protos.google.showcase.v1beta1.IListTestsRequest|null, - protos.google.showcase.v1beta1.IListTestsResponse - ]>|void { + protos.google.showcase.v1beta1.IListTestsResponse | null | undefined, + protos.google.showcase.v1beta1.ITest + >, + callback?: PaginationCallback< + protos.google.showcase.v1beta1.IListTestsRequest, + protos.google.showcase.v1beta1.IListTestsResponse | null | undefined, + protos.google.showcase.v1beta1.ITest + >, + ): Promise< + [ + protos.google.showcase.v1beta1.ITest[], + protos.google.showcase.v1beta1.IListTestsRequest | null, + protos.google.showcase.v1beta1.IListTestsResponse, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.showcase.v1beta1.IListTestsRequest, - protos.google.showcase.v1beta1.IListTestsResponse|null|undefined, - protos.google.showcase.v1beta1.ITest>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.showcase.v1beta1.IListTestsRequest, + protos.google.showcase.v1beta1.IListTestsResponse | null | undefined, + protos.google.showcase.v1beta1.ITest + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listTests values %j', values); callback!(error, values, nextPageRequest, rawResponse); @@ -1213,106 +1509,110 @@ export class TestingClient { this._log.info('listTests request %j', request); return this.innerApiCalls .listTests(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.showcase.v1beta1.ITest[], - protos.google.showcase.v1beta1.IListTestsRequest|null, - protos.google.showcase.v1beta1.IListTestsResponse - ]) => { - this._log.info('listTests values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.showcase.v1beta1.ITest[], + protos.google.showcase.v1beta1.IListTestsRequest | null, + protos.google.showcase.v1beta1.IListTestsResponse, + ]) => { + this._log.info('listTests values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listTests`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * The session. - * @param {number} request.pageSize - * The maximum number of tests to return per page. - * @param {string} request.pageToken - * The page token, for retrieving subsequent pages. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.showcase.v1beta1.Test|Test} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `listTestsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `listTests`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * The session. + * @param {number} request.pageSize + * The maximum number of tests to return per page. + * @param {string} request.pageToken + * The page token, for retrieving subsequent pages. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.showcase.v1beta1.Test|Test} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listTestsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listTestsStream( - request?: protos.google.showcase.v1beta1.IListTestsRequest, - options?: CallOptions): - Transform{ + request?: protos.google.showcase.v1beta1.IListTestsRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); const defaultCallSettings = this._defaults['listTests']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listTests stream %j', request); return this.descriptors.page.listTests.createStream( this.innerApiCalls.listTests as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listTests`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * The session. - * @param {number} request.pageSize - * The maximum number of tests to return per page. - * @param {string} request.pageToken - * The page token, for retrieving subsequent pages. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.showcase.v1beta1.Test|Test}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/testing.list_tests.js - * region_tag:localhost_v1beta1_generated_Testing_ListTests_async - */ + /** + * Equivalent to `listTests`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * The session. + * @param {number} request.pageSize + * The maximum number of tests to return per page. + * @param {string} request.pageToken + * The page token, for retrieving subsequent pages. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.showcase.v1beta1.Test|Test}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/testing.list_tests.js + * region_tag:localhost_v1beta1_generated_Testing_ListTests_async + */ listTestsAsync( - request?: protos.google.showcase.v1beta1.IListTestsRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.showcase.v1beta1.IListTestsRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); const defaultCallSettings = this._defaults['listTests']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listTests iterate %j', request); return this.descriptors.page.listTests.asyncIterate( this.innerApiCalls['listTests'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } // -------------------- @@ -1327,7 +1627,7 @@ export class TestingClient { * @param {string} blueprint * @returns {string} Resource name string. */ - blueprintPath(session:string,test:string,blueprint:string) { + blueprintPath(session: string, test: string, blueprint: string) { return this.pathTemplates.blueprintPathTemplate.render({ session: session, test: test, @@ -1343,7 +1643,8 @@ export class TestingClient { * @returns {string} A string representing the session. */ matchSessionFromBlueprintName(blueprintName: string) { - return this.pathTemplates.blueprintPathTemplate.match(blueprintName).session; + return this.pathTemplates.blueprintPathTemplate.match(blueprintName) + .session; } /** @@ -1365,7 +1666,8 @@ export class TestingClient { * @returns {string} A string representing the blueprint. */ matchBlueprintFromBlueprintName(blueprintName: string) { - return this.pathTemplates.blueprintPathTemplate.match(blueprintName).blueprint; + return this.pathTemplates.blueprintPathTemplate.match(blueprintName) + .blueprint; } /** @@ -1374,7 +1676,7 @@ export class TestingClient { * @param {string} room * @returns {string} Resource name string. */ - roomPath(room:string) { + roomPath(room: string) { return this.pathTemplates.roomPathTemplate.render({ room: room, }); @@ -1398,7 +1700,7 @@ export class TestingClient { * @param {string} blurb * @returns {string} Resource name string. */ - roomBlurbPath(room:string,blurb:string) { + roomBlurbPath(room: string, blurb: string) { return this.pathTemplates.roomBlurbPathTemplate.render({ room: room, blurb: blurb, @@ -1435,7 +1737,11 @@ export class TestingClient { * @param {string} blurb * @returns {string} Resource name string. */ - roomBlurbsLegacyRoomBlurbPath(room:string,legacyRoom:string,blurb:string) { + roomBlurbsLegacyRoomBlurbPath( + room: string, + legacyRoom: string, + blurb: string, + ) { return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.render({ room: room, legacy_room: legacyRoom, @@ -1450,8 +1756,12 @@ export class TestingClient { * A fully-qualified path representing room_blurbs_legacy_room_blurb resource. * @returns {string} A string representing the room. */ - matchRoomFromRoomBlurbsLegacyRoomBlurbName(roomBlurbsLegacyRoomBlurbName: string) { - return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match(roomBlurbsLegacyRoomBlurbName).room; + matchRoomFromRoomBlurbsLegacyRoomBlurbName( + roomBlurbsLegacyRoomBlurbName: string, + ) { + return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match( + roomBlurbsLegacyRoomBlurbName, + ).room; } /** @@ -1461,8 +1771,12 @@ export class TestingClient { * A fully-qualified path representing room_blurbs_legacy_room_blurb resource. * @returns {string} A string representing the legacy_room. */ - matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName(roomBlurbsLegacyRoomBlurbName: string) { - return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match(roomBlurbsLegacyRoomBlurbName).legacy_room; + matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName( + roomBlurbsLegacyRoomBlurbName: string, + ) { + return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match( + roomBlurbsLegacyRoomBlurbName, + ).legacy_room; } /** @@ -1472,8 +1786,12 @@ export class TestingClient { * A fully-qualified path representing room_blurbs_legacy_room_blurb resource. * @returns {string} A string representing the blurb. */ - matchBlurbFromRoomBlurbsLegacyRoomBlurbName(roomBlurbsLegacyRoomBlurbName: string) { - return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match(roomBlurbsLegacyRoomBlurbName).blurb; + matchBlurbFromRoomBlurbsLegacyRoomBlurbName( + roomBlurbsLegacyRoomBlurbName: string, + ) { + return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match( + roomBlurbsLegacyRoomBlurbName, + ).blurb; } /** @@ -1482,7 +1800,7 @@ export class TestingClient { * @param {string} sequence * @returns {string} Resource name string. */ - sequencePath(sequence:string) { + sequencePath(sequence: string) { return this.pathTemplates.sequencePathTemplate.render({ sequence: sequence, }); @@ -1505,7 +1823,7 @@ export class TestingClient { * @param {string} sequence * @returns {string} Resource name string. */ - sequenceReportPath(sequence:string) { + sequenceReportPath(sequence: string) { return this.pathTemplates.sequenceReportPathTemplate.render({ sequence: sequence, }); @@ -1519,7 +1837,9 @@ export class TestingClient { * @returns {string} A string representing the sequence. */ matchSequenceFromSequenceReportName(sequenceReportName: string) { - return this.pathTemplates.sequenceReportPathTemplate.match(sequenceReportName).sequence; + return this.pathTemplates.sequenceReportPathTemplate.match( + sequenceReportName, + ).sequence; } /** @@ -1528,7 +1848,7 @@ export class TestingClient { * @param {string} session * @returns {string} Resource name string. */ - sessionPath(session:string) { + sessionPath(session: string) { return this.pathTemplates.sessionPathTemplate.render({ session: session, }); @@ -1552,7 +1872,7 @@ export class TestingClient { * @param {string} test * @returns {string} Resource name string. */ - testPath(session:string,test:string) { + testPath(session: string, test: string) { return this.pathTemplates.testPathTemplate.render({ session: session, test: test, @@ -1587,7 +1907,7 @@ export class TestingClient { * @param {string} user * @returns {string} Resource name string. */ - userPath(user:string) { + userPath(user: string) { return this.pathTemplates.userPathTemplate.render({ user: user, }); @@ -1611,7 +1931,7 @@ export class TestingClient { * @param {string} blurb * @returns {string} Resource name string. */ - userProfileBlurbPath(user:string,blurb:string) { + userProfileBlurbPath(user: string, blurb: string) { return this.pathTemplates.userProfileBlurbPathTemplate.render({ user: user, blurb: blurb, @@ -1626,7 +1946,9 @@ export class TestingClient { * @returns {string} A string representing the user. */ matchUserFromUserProfileBlurbName(userProfileBlurbName: string) { - return this.pathTemplates.userProfileBlurbPathTemplate.match(userProfileBlurbName).user; + return this.pathTemplates.userProfileBlurbPathTemplate.match( + userProfileBlurbName, + ).user; } /** @@ -1637,7 +1959,9 @@ export class TestingClient { * @returns {string} A string representing the blurb. */ matchBlurbFromUserProfileBlurbName(userProfileBlurbName: string) { - return this.pathTemplates.userProfileBlurbPathTemplate.match(userProfileBlurbName).blurb; + return this.pathTemplates.userProfileBlurbPathTemplate.match( + userProfileBlurbName, + ).blurb; } /** @@ -1648,12 +1972,18 @@ export class TestingClient { * @param {string} blurb * @returns {string} Resource name string. */ - userProfileBlurbsLegacyUserBlurbPath(user:string,legacyUser:string,blurb:string) { - return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.render({ - user: user, - legacy_user: legacyUser, - blurb: blurb, - }); + userProfileBlurbsLegacyUserBlurbPath( + user: string, + legacyUser: string, + blurb: string, + ) { + return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.render( + { + user: user, + legacy_user: legacyUser, + blurb: blurb, + }, + ); } /** @@ -1663,8 +1993,12 @@ export class TestingClient { * A fully-qualified path representing user_profile_blurbs_legacy_user_blurb resource. * @returns {string} A string representing the user. */ - matchUserFromUserProfileBlurbsLegacyUserBlurbName(userProfileBlurbsLegacyUserBlurbName: string) { - return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match(userProfileBlurbsLegacyUserBlurbName).user; + matchUserFromUserProfileBlurbsLegacyUserBlurbName( + userProfileBlurbsLegacyUserBlurbName: string, + ) { + return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match( + userProfileBlurbsLegacyUserBlurbName, + ).user; } /** @@ -1674,8 +2008,12 @@ export class TestingClient { * A fully-qualified path representing user_profile_blurbs_legacy_user_blurb resource. * @returns {string} A string representing the legacy_user. */ - matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName(userProfileBlurbsLegacyUserBlurbName: string) { - return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match(userProfileBlurbsLegacyUserBlurbName).legacy_user; + matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName( + userProfileBlurbsLegacyUserBlurbName: string, + ) { + return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match( + userProfileBlurbsLegacyUserBlurbName, + ).legacy_user; } /** @@ -1685,8 +2023,12 @@ export class TestingClient { * A fully-qualified path representing user_profile_blurbs_legacy_user_blurb resource. * @returns {string} A string representing the blurb. */ - matchBlurbFromUserProfileBlurbsLegacyUserBlurbName(userProfileBlurbsLegacyUserBlurbName: string) { - return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match(userProfileBlurbsLegacyUserBlurbName).blurb; + matchBlurbFromUserProfileBlurbsLegacyUserBlurbName( + userProfileBlurbsLegacyUserBlurbName: string, + ) { + return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match( + userProfileBlurbsLegacyUserBlurbName, + ).blurb; } /** @@ -1697,7 +2039,7 @@ export class TestingClient { */ close(): Promise { if (this.testingStub && !this._terminated) { - return this.testingStub.then(stub => { + return this.testingStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -1705,4 +2047,4 @@ export class TestingClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/core/generator/gapic-generator-typescript/baselines/disable-packing-test-esm/esm/test/gapic_compliance_v1beta1.ts.baseline b/core/generator/gapic-generator-typescript/baselines/disable-packing-test-esm/esm/test/gapic_compliance_v1beta1.ts.baseline index 7403c5712d59..2ce0a2340ee2 100644 --- a/core/generator/gapic-generator-typescript/baselines/disable-packing-test-esm/esm/test/gapic_compliance_v1beta1.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/disable-packing-test-esm/esm/test/gapic_compliance_v1beta1.ts.baseline @@ -20,14 +20,14 @@ import * as protos from '../../protos/protos.js'; import assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as complianceModule from '../src/index.js'; -import {protobuf} from 'google-gax'; +import { protobuf } from 'google-gax'; import fs from 'fs'; import path from 'path'; -import {fileURLToPath} from 'url'; +import { fileURLToPath } from 'url'; // @ts-ignore const dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -35,1534 +35,1965 @@ const dirname = path.dirname(fileURLToPath(import.meta.url)); // to fill in default values for request objects const root = protobuf.Root.fromJSON( JSON.parse( - fs.readFileSync(path.join(dirname, '..', '..', 'protos/protos.json'), 'utf8') - )) + fs.readFileSync( + path.join(dirname, '..', '..', 'protos/protos.json'), + 'utf8', + ), + ), +); // eslint-disable-next-line @typescript-eslint/no-unused-vars function getTypeDefaultValue(typeName: string, fields: string[]) { - let type = root.lookupType(typeName) as protobuf.Type; - for (const field of fields.slice(0, -1)) { - type = type?.fields[field]?.resolvedType as protobuf.Type; - } - return type?.fields[fields[fields.length - 1]]?.defaultValue ?? null; + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type?.fields[field]?.resolvedType as protobuf.Type; + } + return type?.fields[fields[fields.length - 1]]?.defaultValue ?? null; } function generateSampleMessage(instance: T) { - const filledObject = (instance.constructor as typeof protobuf.Message) - .toObject(instance as protobuf.Message, {defaults: true}); - return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, { defaults: true }); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; } function stubSimpleCall(response?: ResponseType, error?: Error) { - return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); } -function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { - return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +function stubSimpleCallWithCallback( + response?: ResponseType, + error?: Error, +) { + return error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); } describe('v1beta1.ComplianceClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new complianceModule.v1beta1.ComplianceClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'localhost'); - }); - - it('has universeDomain', () => { - const client = new complianceModule.v1beta1.ComplianceClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); - - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - it('throws DeprecationWarning if static servicePath is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const servicePath = complianceModule.v1beta1.ComplianceClient.servicePath; - assert.strictEqual(servicePath, 'localhost'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = complianceModule.v1beta1.ComplianceClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'localhost'); - assert(stub.called); - stub.restore(); - }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { new complianceModule.v1beta1.ComplianceClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); - - it('has port', () => { - const port = complianceModule.v1beta1.ComplianceClient.port; - assert(port); - assert(typeof port === 'number'); - }); - - it('should create a client with no option', () => { - const client = new complianceModule.v1beta1.ComplianceClient(); - assert(client); - }); - - it('should create a client with gRPC fallback', () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - fallback: true, - }); - assert(client); - }); - - it('has initialize method and supports deferred initialization', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.complianceStub, undefined); - await client.initialize(); - assert(client.complianceStub); - }); - - it('has close method for the initialized client', done => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.complianceStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); - - it('has close method for the non-initialized client', done => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.complianceStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); - - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); - }); - - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId((err?: Error|null, projectId?: string|null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } - }); - }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new complianceModule.v1beta1.ComplianceClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'localhost'); }); - describe('repeatDataBody', () => { - it('invokes repeatDataBody without error', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatResponse() - ); - client.innerApiCalls.repeatDataBody = stubSimpleCall(expectedResponse); - const [response] = await client.repeatDataBody(request); - assert.deepStrictEqual(response, expectedResponse); - }); - - it('invokes repeatDataBody without error using callback', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatResponse() - ); - client.innerApiCalls.repeatDataBody = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.repeatDataBody( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IRepeatResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); + it('has universeDomain', () => { + const client = new complianceModule.v1beta1.ComplianceClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - it('invokes repeatDataBody with error', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.repeatDataBody = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.repeatDataBody(request), expectedError); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = + complianceModule.v1beta1.ComplianceClient.servicePath; + assert.strictEqual(servicePath, 'localhost'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + complianceModule.v1beta1.ComplianceClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'localhost'); + assert(stub.called); + stub.restore(); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new complianceModule.v1beta1.ComplianceClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); + }); - it('invokes repeatDataBody with closed client', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.repeatDataBody(request), expectedError); - }); + it('has port', () => { + const port = complianceModule.v1beta1.ComplianceClient.port; + assert(port); + assert(typeof port === 'number'); }); - describe('repeatDataBodyInfo', () => { - it('invokes repeatDataBodyInfo without error', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatResponse() - ); - client.innerApiCalls.repeatDataBodyInfo = stubSimpleCall(expectedResponse); - const [response] = await client.repeatDataBodyInfo(request); - assert.deepStrictEqual(response, expectedResponse); - }); + it('should create a client with no option', () => { + const client = new complianceModule.v1beta1.ComplianceClient(); + assert(client); + }); - it('invokes repeatDataBodyInfo without error using callback', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatResponse() - ); - client.innerApiCalls.repeatDataBodyInfo = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.repeatDataBodyInfo( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IRepeatResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); + it('should create a client with gRPC fallback', () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + fallback: true, + }); + assert(client); + }); - it('invokes repeatDataBodyInfo with error', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.repeatDataBodyInfo = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.repeatDataBodyInfo(request), expectedError); - }); + it('has initialize method and supports deferred initialization', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.complianceStub, undefined); + await client.initialize(); + assert(client.complianceStub); + }); - it('invokes repeatDataBodyInfo with closed client', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.repeatDataBodyInfo(request), expectedError); + it('has close method for the initialized client', (done) => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.complianceStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); }); - describe('repeatDataQuery', () => { - it('invokes repeatDataQuery without error', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatResponse() - ); - client.innerApiCalls.repeatDataQuery = stubSimpleCall(expectedResponse); - const [response] = await client.repeatDataQuery(request); - assert.deepStrictEqual(response, expectedResponse); + it('has close method for the non-initialized client', (done) => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.complianceStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes repeatDataQuery without error using callback', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatResponse() - ); - client.innerApiCalls.repeatDataQuery = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.repeatDataQuery( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IRepeatResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + }); - it('invokes repeatDataQuery with error', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.repeatDataQuery = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.repeatDataQuery(request), expectedError); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + }); + + describe('repeatDataBody', () => { + it('invokes repeatDataBody without error', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatResponse(), + ); + client.innerApiCalls.repeatDataBody = stubSimpleCall(expectedResponse); + const [response] = await client.repeatDataBody(request); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes repeatDataQuery with closed client', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.repeatDataQuery(request), expectedError); - }); + it('invokes repeatDataBody without error using callback', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatResponse(), + ); + client.innerApiCalls.repeatDataBody = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.repeatDataBody( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IRepeatResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); }); - describe('repeatDataSimplePath', () => { - it('invokes repeatDataSimplePath without error', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - request.info ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fString']); - request.info.fString = defaultValue1; - request.info ??= {}; - const defaultValue2 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fInt32']); - request.info.fInt32 = defaultValue2; - request.info ??= {}; - const defaultValue3 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fDouble']); - request.info.fDouble = defaultValue3; - request.info ??= {}; - const defaultValue4 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fBool']); - request.info.fBool = defaultValue4; - request.info ??= {}; - const defaultValue5 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fKingdom']); - request.info.fKingdom = defaultValue5; - const expectedHeaderRequestParams = `info.f_string=${defaultValue1 ?? '' }&info.f_int32=${defaultValue2 ?? '' }&info.f_double=${defaultValue3 ?? '' }&info.f_bool=${defaultValue4 ?? '' }&info.f_kingdom=${defaultValue5 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatResponse() - ); - client.innerApiCalls.repeatDataSimplePath = stubSimpleCall(expectedResponse); - const [response] = await client.repeatDataSimplePath(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.repeatDataSimplePath as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.repeatDataSimplePath as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes repeatDataBody with error', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.repeatDataBody = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.repeatDataBody(request), expectedError); + }); - it('invokes repeatDataSimplePath without error using callback', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - request.info ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fString']); - request.info.fString = defaultValue1; - request.info ??= {}; - const defaultValue2 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fInt32']); - request.info.fInt32 = defaultValue2; - request.info ??= {}; - const defaultValue3 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fDouble']); - request.info.fDouble = defaultValue3; - request.info ??= {}; - const defaultValue4 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fBool']); - request.info.fBool = defaultValue4; - request.info ??= {}; - const defaultValue5 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fKingdom']); - request.info.fKingdom = defaultValue5; - const expectedHeaderRequestParams = `info.f_string=${defaultValue1 ?? '' }&info.f_int32=${defaultValue2 ?? '' }&info.f_double=${defaultValue3 ?? '' }&info.f_bool=${defaultValue4 ?? '' }&info.f_kingdom=${defaultValue5 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatResponse() - ); - client.innerApiCalls.repeatDataSimplePath = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.repeatDataSimplePath( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IRepeatResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.repeatDataSimplePath as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.repeatDataSimplePath as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes repeatDataBody with closed client', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.repeatDataBody(request), expectedError); + }); + }); + + describe('repeatDataBodyInfo', () => { + it('invokes repeatDataBodyInfo without error', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatResponse(), + ); + client.innerApiCalls.repeatDataBodyInfo = + stubSimpleCall(expectedResponse); + const [response] = await client.repeatDataBodyInfo(request); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes repeatDataSimplePath with error', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - request.info ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fString']); - request.info.fString = defaultValue1; - request.info ??= {}; - const defaultValue2 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fInt32']); - request.info.fInt32 = defaultValue2; - request.info ??= {}; - const defaultValue3 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fDouble']); - request.info.fDouble = defaultValue3; - request.info ??= {}; - const defaultValue4 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fBool']); - request.info.fBool = defaultValue4; - request.info ??= {}; - const defaultValue5 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fKingdom']); - request.info.fKingdom = defaultValue5; - const expectedHeaderRequestParams = `info.f_string=${defaultValue1 ?? '' }&info.f_int32=${defaultValue2 ?? '' }&info.f_double=${defaultValue3 ?? '' }&info.f_bool=${defaultValue4 ?? '' }&info.f_kingdom=${defaultValue5 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.repeatDataSimplePath = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.repeatDataSimplePath(request), expectedError); - const actualRequest = (client.innerApiCalls.repeatDataSimplePath as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.repeatDataSimplePath as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes repeatDataBodyInfo without error using callback', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatResponse(), + ); + client.innerApiCalls.repeatDataBodyInfo = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.repeatDataBodyInfo( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IRepeatResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes repeatDataSimplePath with closed client', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - request.info ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fString']); - request.info.fString = defaultValue1; - request.info ??= {}; - const defaultValue2 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fInt32']); - request.info.fInt32 = defaultValue2; - request.info ??= {}; - const defaultValue3 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fDouble']); - request.info.fDouble = defaultValue3; - request.info ??= {}; - const defaultValue4 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fBool']); - request.info.fBool = defaultValue4; - request.info ??= {}; - const defaultValue5 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fKingdom']); - request.info.fKingdom = defaultValue5; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.repeatDataSimplePath(request), expectedError); - }); + it('invokes repeatDataBodyInfo with error', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.repeatDataBodyInfo = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.repeatDataBodyInfo(request), expectedError); }); - describe('repeatDataPathResource', () => { - it('invokes repeatDataPathResource without error', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - request.info ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fString']); - request.info.fString = defaultValue1; - request.info ??= {}; - request.info.fChild ??= {}; - const defaultValue2 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fChild', 'fString']); - request.info.fChild.fString = defaultValue2; - request.info ??= {}; - const defaultValue3 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fBool']); - request.info.fBool = defaultValue3; - const expectedHeaderRequestParams = `info.f_string=${defaultValue1 ?? '' }&info.f_child.f_string=${defaultValue2 ?? '' }&info.f_bool=${defaultValue3 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatResponse() - ); - client.innerApiCalls.repeatDataPathResource = stubSimpleCall(expectedResponse); - const [response] = await client.repeatDataPathResource(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.repeatDataPathResource as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.repeatDataPathResource as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes repeatDataBodyInfo with closed client', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.repeatDataBodyInfo(request), expectedError); + }); + }); + + describe('repeatDataQuery', () => { + it('invokes repeatDataQuery without error', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatResponse(), + ); + client.innerApiCalls.repeatDataQuery = stubSimpleCall(expectedResponse); + const [response] = await client.repeatDataQuery(request); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes repeatDataPathResource without error using callback', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - request.info ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fString']); - request.info.fString = defaultValue1; - request.info ??= {}; - request.info.fChild ??= {}; - const defaultValue2 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fChild', 'fString']); - request.info.fChild.fString = defaultValue2; - request.info ??= {}; - const defaultValue3 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fBool']); - request.info.fBool = defaultValue3; - const expectedHeaderRequestParams = `info.f_string=${defaultValue1 ?? '' }&info.f_child.f_string=${defaultValue2 ?? '' }&info.f_bool=${defaultValue3 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatResponse() - ); - client.innerApiCalls.repeatDataPathResource = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.repeatDataPathResource( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IRepeatResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.repeatDataPathResource as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.repeatDataPathResource as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes repeatDataQuery without error using callback', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatResponse(), + ); + client.innerApiCalls.repeatDataQuery = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.repeatDataQuery( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IRepeatResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes repeatDataPathResource with error', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - request.info ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fString']); - request.info.fString = defaultValue1; - request.info ??= {}; - request.info.fChild ??= {}; - const defaultValue2 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fChild', 'fString']); - request.info.fChild.fString = defaultValue2; - request.info ??= {}; - const defaultValue3 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fBool']); - request.info.fBool = defaultValue3; - const expectedHeaderRequestParams = `info.f_string=${defaultValue1 ?? '' }&info.f_child.f_string=${defaultValue2 ?? '' }&info.f_bool=${defaultValue3 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.repeatDataPathResource = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.repeatDataPathResource(request), expectedError); - const actualRequest = (client.innerApiCalls.repeatDataPathResource as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.repeatDataPathResource as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes repeatDataQuery with error', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.repeatDataQuery = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.repeatDataQuery(request), expectedError); + }); - it('invokes repeatDataPathResource with closed client', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - request.info ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fString']); - request.info.fString = defaultValue1; - request.info ??= {}; - request.info.fChild ??= {}; - const defaultValue2 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fChild', 'fString']); - request.info.fChild.fString = defaultValue2; - request.info ??= {}; - const defaultValue3 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fBool']); - request.info.fBool = defaultValue3; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.repeatDataPathResource(request), expectedError); - }); + it('invokes repeatDataQuery with closed client', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.repeatDataQuery(request), expectedError); + }); + }); + + describe('repeatDataSimplePath', () => { + it('invokes repeatDataSimplePath without error', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + request.info ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fString'], + ); + request.info.fString = defaultValue1; + request.info ??= {}; + const defaultValue2 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fInt32'], + ); + request.info.fInt32 = defaultValue2; + request.info ??= {}; + const defaultValue3 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fDouble'], + ); + request.info.fDouble = defaultValue3; + request.info ??= {}; + const defaultValue4 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fBool'], + ); + request.info.fBool = defaultValue4; + request.info ??= {}; + const defaultValue5 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fKingdom'], + ); + request.info.fKingdom = defaultValue5; + const expectedHeaderRequestParams = `info.f_string=${defaultValue1 ?? ''}&info.f_int32=${defaultValue2 ?? ''}&info.f_double=${defaultValue3 ?? ''}&info.f_bool=${defaultValue4 ?? ''}&info.f_kingdom=${defaultValue5 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatResponse(), + ); + client.innerApiCalls.repeatDataSimplePath = + stubSimpleCall(expectedResponse); + const [response] = await client.repeatDataSimplePath(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.repeatDataSimplePath as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.repeatDataSimplePath as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('repeatDataPathTrailingResource', () => { - it('invokes repeatDataPathTrailingResource without error', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - request.info ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fString']); - request.info.fString = defaultValue1; - request.info ??= {}; - request.info.fChild ??= {}; - const defaultValue2 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fChild', 'fString']); - request.info.fChild.fString = defaultValue2; - const expectedHeaderRequestParams = `info.f_string=${defaultValue1 ?? '' }&info.f_child.f_string=${defaultValue2 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatResponse() - ); - client.innerApiCalls.repeatDataPathTrailingResource = stubSimpleCall(expectedResponse); - const [response] = await client.repeatDataPathTrailingResource(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.repeatDataPathTrailingResource as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.repeatDataPathTrailingResource as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes repeatDataSimplePath without error using callback', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + request.info ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fString'], + ); + request.info.fString = defaultValue1; + request.info ??= {}; + const defaultValue2 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fInt32'], + ); + request.info.fInt32 = defaultValue2; + request.info ??= {}; + const defaultValue3 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fDouble'], + ); + request.info.fDouble = defaultValue3; + request.info ??= {}; + const defaultValue4 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fBool'], + ); + request.info.fBool = defaultValue4; + request.info ??= {}; + const defaultValue5 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fKingdom'], + ); + request.info.fKingdom = defaultValue5; + const expectedHeaderRequestParams = `info.f_string=${defaultValue1 ?? ''}&info.f_int32=${defaultValue2 ?? ''}&info.f_double=${defaultValue3 ?? ''}&info.f_bool=${defaultValue4 ?? ''}&info.f_kingdom=${defaultValue5 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatResponse(), + ); + client.innerApiCalls.repeatDataSimplePath = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.repeatDataSimplePath( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IRepeatResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.repeatDataSimplePath as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.repeatDataSimplePath as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes repeatDataPathTrailingResource without error using callback', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - request.info ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fString']); - request.info.fString = defaultValue1; - request.info ??= {}; - request.info.fChild ??= {}; - const defaultValue2 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fChild', 'fString']); - request.info.fChild.fString = defaultValue2; - const expectedHeaderRequestParams = `info.f_string=${defaultValue1 ?? '' }&info.f_child.f_string=${defaultValue2 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatResponse() - ); - client.innerApiCalls.repeatDataPathTrailingResource = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.repeatDataPathTrailingResource( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IRepeatResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.repeatDataPathTrailingResource as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.repeatDataPathTrailingResource as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes repeatDataSimplePath with error', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + request.info ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fString'], + ); + request.info.fString = defaultValue1; + request.info ??= {}; + const defaultValue2 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fInt32'], + ); + request.info.fInt32 = defaultValue2; + request.info ??= {}; + const defaultValue3 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fDouble'], + ); + request.info.fDouble = defaultValue3; + request.info ??= {}; + const defaultValue4 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fBool'], + ); + request.info.fBool = defaultValue4; + request.info ??= {}; + const defaultValue5 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fKingdom'], + ); + request.info.fKingdom = defaultValue5; + const expectedHeaderRequestParams = `info.f_string=${defaultValue1 ?? ''}&info.f_int32=${defaultValue2 ?? ''}&info.f_double=${defaultValue3 ?? ''}&info.f_bool=${defaultValue4 ?? ''}&info.f_kingdom=${defaultValue5 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.repeatDataSimplePath = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.repeatDataSimplePath(request), expectedError); + const actualRequest = ( + client.innerApiCalls.repeatDataSimplePath as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.repeatDataSimplePath as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes repeatDataPathTrailingResource with error', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - request.info ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fString']); - request.info.fString = defaultValue1; - request.info ??= {}; - request.info.fChild ??= {}; - const defaultValue2 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fChild', 'fString']); - request.info.fChild.fString = defaultValue2; - const expectedHeaderRequestParams = `info.f_string=${defaultValue1 ?? '' }&info.f_child.f_string=${defaultValue2 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.repeatDataPathTrailingResource = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.repeatDataPathTrailingResource(request), expectedError); - const actualRequest = (client.innerApiCalls.repeatDataPathTrailingResource as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.repeatDataPathTrailingResource as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes repeatDataSimplePath with closed client', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + request.info ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fString'], + ); + request.info.fString = defaultValue1; + request.info ??= {}; + const defaultValue2 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fInt32'], + ); + request.info.fInt32 = defaultValue2; + request.info ??= {}; + const defaultValue3 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fDouble'], + ); + request.info.fDouble = defaultValue3; + request.info ??= {}; + const defaultValue4 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fBool'], + ); + request.info.fBool = defaultValue4; + request.info ??= {}; + const defaultValue5 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fKingdom'], + ); + request.info.fKingdom = defaultValue5; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.repeatDataSimplePath(request), expectedError); + }); + }); + + describe('repeatDataPathResource', () => { + it('invokes repeatDataPathResource without error', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + request.info ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fString'], + ); + request.info.fString = defaultValue1; + request.info ??= {}; + request.info.fChild ??= {}; + const defaultValue2 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fChild', 'fString'], + ); + request.info.fChild.fString = defaultValue2; + request.info ??= {}; + const defaultValue3 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fBool'], + ); + request.info.fBool = defaultValue3; + const expectedHeaderRequestParams = `info.f_string=${defaultValue1 ?? ''}&info.f_child.f_string=${defaultValue2 ?? ''}&info.f_bool=${defaultValue3 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatResponse(), + ); + client.innerApiCalls.repeatDataPathResource = + stubSimpleCall(expectedResponse); + const [response] = await client.repeatDataPathResource(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.repeatDataPathResource as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.repeatDataPathResource as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes repeatDataPathTrailingResource with closed client', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - request.info ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fString']); - request.info.fString = defaultValue1; - request.info ??= {}; - request.info.fChild ??= {}; - const defaultValue2 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fChild', 'fString']); - request.info.fChild.fString = defaultValue2; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.repeatDataPathTrailingResource(request), expectedError); - }); + it('invokes repeatDataPathResource without error using callback', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + request.info ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fString'], + ); + request.info.fString = defaultValue1; + request.info ??= {}; + request.info.fChild ??= {}; + const defaultValue2 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fChild', 'fString'], + ); + request.info.fChild.fString = defaultValue2; + request.info ??= {}; + const defaultValue3 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fBool'], + ); + request.info.fBool = defaultValue3; + const expectedHeaderRequestParams = `info.f_string=${defaultValue1 ?? ''}&info.f_child.f_string=${defaultValue2 ?? ''}&info.f_bool=${defaultValue3 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatResponse(), + ); + client.innerApiCalls.repeatDataPathResource = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.repeatDataPathResource( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IRepeatResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.repeatDataPathResource as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.repeatDataPathResource as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('repeatDataBodyPut', () => { - it('invokes repeatDataBodyPut without error', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatResponse() - ); - client.innerApiCalls.repeatDataBodyPut = stubSimpleCall(expectedResponse); - const [response] = await client.repeatDataBodyPut(request); - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes repeatDataPathResource with error', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + request.info ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fString'], + ); + request.info.fString = defaultValue1; + request.info ??= {}; + request.info.fChild ??= {}; + const defaultValue2 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fChild', 'fString'], + ); + request.info.fChild.fString = defaultValue2; + request.info ??= {}; + const defaultValue3 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fBool'], + ); + request.info.fBool = defaultValue3; + const expectedHeaderRequestParams = `info.f_string=${defaultValue1 ?? ''}&info.f_child.f_string=${defaultValue2 ?? ''}&info.f_bool=${defaultValue3 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.repeatDataPathResource = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.repeatDataPathResource(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.repeatDataPathResource as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.repeatDataPathResource as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes repeatDataBodyPut without error using callback', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatResponse() - ); - client.innerApiCalls.repeatDataBodyPut = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.repeatDataBodyPut( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IRepeatResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes repeatDataPathResource with closed client', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + request.info ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fString'], + ); + request.info.fString = defaultValue1; + request.info ??= {}; + request.info.fChild ??= {}; + const defaultValue2 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fChild', 'fString'], + ); + request.info.fChild.fString = defaultValue2; + request.info ??= {}; + const defaultValue3 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fBool'], + ); + request.info.fBool = defaultValue3; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.repeatDataPathResource(request), + expectedError, + ); + }); + }); + + describe('repeatDataPathTrailingResource', () => { + it('invokes repeatDataPathTrailingResource without error', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + request.info ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fString'], + ); + request.info.fString = defaultValue1; + request.info ??= {}; + request.info.fChild ??= {}; + const defaultValue2 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fChild', 'fString'], + ); + request.info.fChild.fString = defaultValue2; + const expectedHeaderRequestParams = `info.f_string=${defaultValue1 ?? ''}&info.f_child.f_string=${defaultValue2 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatResponse(), + ); + client.innerApiCalls.repeatDataPathTrailingResource = + stubSimpleCall(expectedResponse); + const [response] = await client.repeatDataPathTrailingResource(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.repeatDataPathTrailingResource as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.repeatDataPathTrailingResource as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes repeatDataBodyPut with error', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.repeatDataBodyPut = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.repeatDataBodyPut(request), expectedError); - }); + it('invokes repeatDataPathTrailingResource without error using callback', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + request.info ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fString'], + ); + request.info.fString = defaultValue1; + request.info ??= {}; + request.info.fChild ??= {}; + const defaultValue2 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fChild', 'fString'], + ); + request.info.fChild.fString = defaultValue2; + const expectedHeaderRequestParams = `info.f_string=${defaultValue1 ?? ''}&info.f_child.f_string=${defaultValue2 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatResponse(), + ); + client.innerApiCalls.repeatDataPathTrailingResource = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.repeatDataPathTrailingResource( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IRepeatResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.repeatDataPathTrailingResource as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.repeatDataPathTrailingResource as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes repeatDataBodyPut with closed client', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.repeatDataBodyPut(request), expectedError); - }); + it('invokes repeatDataPathTrailingResource with error', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + request.info ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fString'], + ); + request.info.fString = defaultValue1; + request.info ??= {}; + request.info.fChild ??= {}; + const defaultValue2 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fChild', 'fString'], + ); + request.info.fChild.fString = defaultValue2; + const expectedHeaderRequestParams = `info.f_string=${defaultValue1 ?? ''}&info.f_child.f_string=${defaultValue2 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.repeatDataPathTrailingResource = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.repeatDataPathTrailingResource(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.repeatDataPathTrailingResource as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.repeatDataPathTrailingResource as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('repeatDataBodyPatch', () => { - it('invokes repeatDataBodyPatch without error', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatResponse() - ); - client.innerApiCalls.repeatDataBodyPatch = stubSimpleCall(expectedResponse); - const [response] = await client.repeatDataBodyPatch(request); - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes repeatDataPathTrailingResource with closed client', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + request.info ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fString'], + ); + request.info.fString = defaultValue1; + request.info ??= {}; + request.info.fChild ??= {}; + const defaultValue2 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fChild', 'fString'], + ); + request.info.fChild.fString = defaultValue2; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.repeatDataPathTrailingResource(request), + expectedError, + ); + }); + }); + + describe('repeatDataBodyPut', () => { + it('invokes repeatDataBodyPut without error', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatResponse(), + ); + client.innerApiCalls.repeatDataBodyPut = stubSimpleCall(expectedResponse); + const [response] = await client.repeatDataBodyPut(request); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes repeatDataBodyPatch without error using callback', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatResponse() - ); - client.innerApiCalls.repeatDataBodyPatch = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.repeatDataBodyPatch( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IRepeatResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes repeatDataBodyPut without error using callback', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatResponse(), + ); + client.innerApiCalls.repeatDataBodyPut = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.repeatDataBodyPut( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IRepeatResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes repeatDataBodyPatch with error', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.repeatDataBodyPatch = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.repeatDataBodyPatch(request), expectedError); - }); + it('invokes repeatDataBodyPut with error', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.repeatDataBodyPut = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.repeatDataBodyPut(request), expectedError); + }); - it('invokes repeatDataBodyPatch with closed client', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.repeatDataBodyPatch(request), expectedError); - }); + it('invokes repeatDataBodyPut with closed client', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.repeatDataBodyPut(request), expectedError); + }); + }); + + describe('repeatDataBodyPatch', () => { + it('invokes repeatDataBodyPatch without error', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatResponse(), + ); + client.innerApiCalls.repeatDataBodyPatch = + stubSimpleCall(expectedResponse); + const [response] = await client.repeatDataBodyPatch(request); + assert.deepStrictEqual(response, expectedResponse); }); - describe('getEnum', () => { - it('invokes getEnum without error', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.EnumRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.EnumResponse() - ); - client.innerApiCalls.getEnum = stubSimpleCall(expectedResponse); - const [response] = await client.getEnum(request); - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes repeatDataBodyPatch without error using callback', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatResponse(), + ); + client.innerApiCalls.repeatDataBodyPatch = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.repeatDataBodyPatch( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IRepeatResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes getEnum without error using callback', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.EnumRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.EnumResponse() - ); - client.innerApiCalls.getEnum = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getEnum( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IEnumResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes repeatDataBodyPatch with error', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.repeatDataBodyPatch = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.repeatDataBodyPatch(request), expectedError); + }); - it('invokes getEnum with error', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.EnumRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.getEnum = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getEnum(request), expectedError); - }); + it('invokes repeatDataBodyPatch with closed client', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.repeatDataBodyPatch(request), expectedError); + }); + }); + + describe('getEnum', () => { + it('invokes getEnum without error', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.EnumRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.EnumResponse(), + ); + client.innerApiCalls.getEnum = stubSimpleCall(expectedResponse); + const [response] = await client.getEnum(request); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes getEnum with closed client', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.EnumRequest() - ); - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getEnum(request), expectedError); - }); + it('invokes getEnum without error using callback', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.EnumRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.EnumResponse(), + ); + client.innerApiCalls.getEnum = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getEnum( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IEnumResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); }); - describe('verifyEnum', () => { - it('invokes verifyEnum without error', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.EnumResponse() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.EnumResponse() - ); - client.innerApiCalls.verifyEnum = stubSimpleCall(expectedResponse); - const [response] = await client.verifyEnum(request); - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes getEnum with error', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.EnumRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.getEnum = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.getEnum(request), expectedError); + }); - it('invokes verifyEnum without error using callback', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.EnumResponse() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.EnumResponse() - ); - client.innerApiCalls.verifyEnum = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.verifyEnum( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IEnumResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes getEnum with closed client', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.EnumRequest(), + ); + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getEnum(request), expectedError); + }); + }); + + describe('verifyEnum', () => { + it('invokes verifyEnum without error', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.EnumResponse(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.EnumResponse(), + ); + client.innerApiCalls.verifyEnum = stubSimpleCall(expectedResponse); + const [response] = await client.verifyEnum(request); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes verifyEnum with error', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.EnumResponse() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.verifyEnum = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.verifyEnum(request), expectedError); - }); + it('invokes verifyEnum without error using callback', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.EnumResponse(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.EnumResponse(), + ); + client.innerApiCalls.verifyEnum = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.verifyEnum( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IEnumResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes verifyEnum with closed client', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.EnumResponse() - ); - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.verifyEnum(request), expectedError); - }); + it('invokes verifyEnum with error', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.EnumResponse(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.verifyEnum = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.verifyEnum(request), expectedError); }); - describe('Path templates', () => { - - describe('blueprint', () => { - const fakePath = "/rendered/path/blueprint"; - const expectedParameters = { - session: "sessionValue", - test: "testValue", - blueprint: "blueprintValue", - }; - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.blueprintPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.blueprintPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('blueprintPath', () => { - const result = client.blueprintPath("sessionValue", "testValue", "blueprintValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.blueprintPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchSessionFromBlueprintName', () => { - const result = client.matchSessionFromBlueprintName(fakePath); - assert.strictEqual(result, "sessionValue"); - assert((client.pathTemplates.blueprintPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchTestFromBlueprintName', () => { - const result = client.matchTestFromBlueprintName(fakePath); - assert.strictEqual(result, "testValue"); - assert((client.pathTemplates.blueprintPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBlueprintFromBlueprintName', () => { - const result = client.matchBlueprintFromBlueprintName(fakePath); - assert.strictEqual(result, "blueprintValue"); - assert((client.pathTemplates.blueprintPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('invokes verifyEnum with closed client', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.EnumResponse(), + ); + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.verifyEnum(request), expectedError); + }); + }); + + describe('Path templates', () => { + describe('blueprint', () => { + const fakePath = '/rendered/path/blueprint'; + const expectedParameters = { + session: 'sessionValue', + test: 'testValue', + blueprint: 'blueprintValue', + }; + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.blueprintPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.blueprintPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('blueprintPath', () => { + const result = client.blueprintPath( + 'sessionValue', + 'testValue', + 'blueprintValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.blueprintPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchSessionFromBlueprintName', () => { + const result = client.matchSessionFromBlueprintName(fakePath); + assert.strictEqual(result, 'sessionValue'); + assert( + (client.pathTemplates.blueprintPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchTestFromBlueprintName', () => { + const result = client.matchTestFromBlueprintName(fakePath); + assert.strictEqual(result, 'testValue'); + assert( + (client.pathTemplates.blueprintPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBlueprintFromBlueprintName', () => { + const result = client.matchBlueprintFromBlueprintName(fakePath); + assert.strictEqual(result, 'blueprintValue'); + assert( + (client.pathTemplates.blueprintPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('room', () => { - const fakePath = "/rendered/path/room"; - const expectedParameters = { - room: "roomValue", - }; - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.roomPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.roomPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('roomPath', () => { - const result = client.roomPath("roomValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.roomPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchRoomFromRoomName', () => { - const result = client.matchRoomFromRoomName(fakePath); - assert.strictEqual(result, "roomValue"); - assert((client.pathTemplates.roomPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('room', () => { + const fakePath = '/rendered/path/room'; + const expectedParameters = { + room: 'roomValue', + }; + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.roomPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.roomPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('roomPath', () => { + const result = client.roomPath('roomValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.roomPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchRoomFromRoomName', () => { + const result = client.matchRoomFromRoomName(fakePath); + assert.strictEqual(result, 'roomValue'); + assert( + (client.pathTemplates.roomPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('roomBlurb', () => { - const fakePath = "/rendered/path/roomBlurb"; - const expectedParameters = { - room: "roomValue", - blurb: "blurbValue", - }; - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.roomBlurbPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.roomBlurbPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('roomBlurbPath', () => { - const result = client.roomBlurbPath("roomValue", "blurbValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.roomBlurbPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchRoomFromRoomBlurbName', () => { - const result = client.matchRoomFromRoomBlurbName(fakePath); - assert.strictEqual(result, "roomValue"); - assert((client.pathTemplates.roomBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBlurbFromRoomBlurbName', () => { - const result = client.matchBlurbFromRoomBlurbName(fakePath); - assert.strictEqual(result, "blurbValue"); - assert((client.pathTemplates.roomBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('roomBlurb', () => { + const fakePath = '/rendered/path/roomBlurb'; + const expectedParameters = { + room: 'roomValue', + blurb: 'blurbValue', + }; + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.roomBlurbPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.roomBlurbPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('roomBlurbPath', () => { + const result = client.roomBlurbPath('roomValue', 'blurbValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.roomBlurbPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchRoomFromRoomBlurbName', () => { + const result = client.matchRoomFromRoomBlurbName(fakePath); + assert.strictEqual(result, 'roomValue'); + assert( + (client.pathTemplates.roomBlurbPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBlurbFromRoomBlurbName', () => { + const result = client.matchBlurbFromRoomBlurbName(fakePath); + assert.strictEqual(result, 'blurbValue'); + assert( + (client.pathTemplates.roomBlurbPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('roomBlurbsLegacyRoomBlurb', () => { - const fakePath = "/rendered/path/roomBlurbsLegacyRoomBlurb"; - const expectedParameters = { - room: "roomValue", - legacy_room: "legacyRoomValue", - blurb: "blurbValue", - }; - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('roomBlurbsLegacyRoomBlurbPath', () => { - const result = client.roomBlurbsLegacyRoomBlurbPath("roomValue", "legacyRoomValue", "blurbValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchRoomFromRoomBlurbsLegacyRoomBlurbName', () => { - const result = client.matchRoomFromRoomBlurbsLegacyRoomBlurbName(fakePath); - assert.strictEqual(result, "roomValue"); - assert((client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName', () => { - const result = client.matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName(fakePath); - assert.strictEqual(result, "legacyRoomValue"); - assert((client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBlurbFromRoomBlurbsLegacyRoomBlurbName', () => { - const result = client.matchBlurbFromRoomBlurbsLegacyRoomBlurbName(fakePath); - assert.strictEqual(result, "blurbValue"); - assert((client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('roomBlurbsLegacyRoomBlurb', () => { + const fakePath = '/rendered/path/roomBlurbsLegacyRoomBlurb'; + const expectedParameters = { + room: 'roomValue', + legacy_room: 'legacyRoomValue', + blurb: 'blurbValue', + }; + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('roomBlurbsLegacyRoomBlurbPath', () => { + const result = client.roomBlurbsLegacyRoomBlurbPath( + 'roomValue', + 'legacyRoomValue', + 'blurbValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchRoomFromRoomBlurbsLegacyRoomBlurbName', () => { + const result = + client.matchRoomFromRoomBlurbsLegacyRoomBlurbName(fakePath); + assert.strictEqual(result, 'roomValue'); + assert( + ( + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName', () => { + const result = + client.matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName(fakePath); + assert.strictEqual(result, 'legacyRoomValue'); + assert( + ( + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBlurbFromRoomBlurbsLegacyRoomBlurbName', () => { + const result = + client.matchBlurbFromRoomBlurbsLegacyRoomBlurbName(fakePath); + assert.strictEqual(result, 'blurbValue'); + assert( + ( + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('sequence', () => { - const fakePath = "/rendered/path/sequence"; - const expectedParameters = { - sequence: "sequenceValue", - }; - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.sequencePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.sequencePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('sequencePath', () => { - const result = client.sequencePath("sequenceValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.sequencePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchSequenceFromSequenceName', () => { - const result = client.matchSequenceFromSequenceName(fakePath); - assert.strictEqual(result, "sequenceValue"); - assert((client.pathTemplates.sequencePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('sequence', () => { + const fakePath = '/rendered/path/sequence'; + const expectedParameters = { + sequence: 'sequenceValue', + }; + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.sequencePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.sequencePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('sequencePath', () => { + const result = client.sequencePath('sequenceValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.sequencePathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchSequenceFromSequenceName', () => { + const result = client.matchSequenceFromSequenceName(fakePath); + assert.strictEqual(result, 'sequenceValue'); + assert( + (client.pathTemplates.sequencePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('sequenceReport', () => { - const fakePath = "/rendered/path/sequenceReport"; - const expectedParameters = { - sequence: "sequenceValue", - }; - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.sequenceReportPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.sequenceReportPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('sequenceReportPath', () => { - const result = client.sequenceReportPath("sequenceValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.sequenceReportPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchSequenceFromSequenceReportName', () => { - const result = client.matchSequenceFromSequenceReportName(fakePath); - assert.strictEqual(result, "sequenceValue"); - assert((client.pathTemplates.sequenceReportPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('sequenceReport', () => { + const fakePath = '/rendered/path/sequenceReport'; + const expectedParameters = { + sequence: 'sequenceValue', + }; + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.sequenceReportPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.sequenceReportPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('sequenceReportPath', () => { + const result = client.sequenceReportPath('sequenceValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.sequenceReportPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchSequenceFromSequenceReportName', () => { + const result = client.matchSequenceFromSequenceReportName(fakePath); + assert.strictEqual(result, 'sequenceValue'); + assert( + (client.pathTemplates.sequenceReportPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('session', () => { - const fakePath = "/rendered/path/session"; - const expectedParameters = { - session: "sessionValue", - }; - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.sessionPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.sessionPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('sessionPath', () => { - const result = client.sessionPath("sessionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.sessionPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchSessionFromSessionName', () => { - const result = client.matchSessionFromSessionName(fakePath); - assert.strictEqual(result, "sessionValue"); - assert((client.pathTemplates.sessionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('session', () => { + const fakePath = '/rendered/path/session'; + const expectedParameters = { + session: 'sessionValue', + }; + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.sessionPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.sessionPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('sessionPath', () => { + const result = client.sessionPath('sessionValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.sessionPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchSessionFromSessionName', () => { + const result = client.matchSessionFromSessionName(fakePath); + assert.strictEqual(result, 'sessionValue'); + assert( + (client.pathTemplates.sessionPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('test', () => { - const fakePath = "/rendered/path/test"; - const expectedParameters = { - session: "sessionValue", - test: "testValue", - }; - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.testPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.testPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('testPath', () => { - const result = client.testPath("sessionValue", "testValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.testPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchSessionFromTestName', () => { - const result = client.matchSessionFromTestName(fakePath); - assert.strictEqual(result, "sessionValue"); - assert((client.pathTemplates.testPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchTestFromTestName', () => { - const result = client.matchTestFromTestName(fakePath); - assert.strictEqual(result, "testValue"); - assert((client.pathTemplates.testPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('test', () => { + const fakePath = '/rendered/path/test'; + const expectedParameters = { + session: 'sessionValue', + test: 'testValue', + }; + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.testPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.testPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('testPath', () => { + const result = client.testPath('sessionValue', 'testValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.testPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchSessionFromTestName', () => { + const result = client.matchSessionFromTestName(fakePath); + assert.strictEqual(result, 'sessionValue'); + assert( + (client.pathTemplates.testPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchTestFromTestName', () => { + const result = client.matchTestFromTestName(fakePath); + assert.strictEqual(result, 'testValue'); + assert( + (client.pathTemplates.testPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('user', () => { - const fakePath = "/rendered/path/user"; - const expectedParameters = { - user: "userValue", - }; - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.userPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.userPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('userPath', () => { - const result = client.userPath("userValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.userPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchUserFromUserName', () => { - const result = client.matchUserFromUserName(fakePath); - assert.strictEqual(result, "userValue"); - assert((client.pathTemplates.userPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('user', () => { + const fakePath = '/rendered/path/user'; + const expectedParameters = { + user: 'userValue', + }; + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.userPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.userPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('userPath', () => { + const result = client.userPath('userValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.userPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchUserFromUserName', () => { + const result = client.matchUserFromUserName(fakePath); + assert.strictEqual(result, 'userValue'); + assert( + (client.pathTemplates.userPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('userProfileBlurb', () => { - const fakePath = "/rendered/path/userProfileBlurb"; - const expectedParameters = { - user: "userValue", - blurb: "blurbValue", - }; - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.userProfileBlurbPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.userProfileBlurbPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('userProfileBlurbPath', () => { - const result = client.userProfileBlurbPath("userValue", "blurbValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.userProfileBlurbPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchUserFromUserProfileBlurbName', () => { - const result = client.matchUserFromUserProfileBlurbName(fakePath); - assert.strictEqual(result, "userValue"); - assert((client.pathTemplates.userProfileBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBlurbFromUserProfileBlurbName', () => { - const result = client.matchBlurbFromUserProfileBlurbName(fakePath); - assert.strictEqual(result, "blurbValue"); - assert((client.pathTemplates.userProfileBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('userProfileBlurb', () => { + const fakePath = '/rendered/path/userProfileBlurb'; + const expectedParameters = { + user: 'userValue', + blurb: 'blurbValue', + }; + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.userProfileBlurbPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.userProfileBlurbPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('userProfileBlurbPath', () => { + const result = client.userProfileBlurbPath('userValue', 'blurbValue'); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.userProfileBlurbPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchUserFromUserProfileBlurbName', () => { + const result = client.matchUserFromUserProfileBlurbName(fakePath); + assert.strictEqual(result, 'userValue'); + assert( + (client.pathTemplates.userProfileBlurbPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBlurbFromUserProfileBlurbName', () => { + const result = client.matchBlurbFromUserProfileBlurbName(fakePath); + assert.strictEqual(result, 'blurbValue'); + assert( + (client.pathTemplates.userProfileBlurbPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('userProfileBlurbsLegacyUserBlurb', () => { - const fakePath = "/rendered/path/userProfileBlurbsLegacyUserBlurb"; - const expectedParameters = { - user: "userValue", - legacy_user: "legacyUserValue", - blurb: "blurbValue", - }; - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('userProfileBlurbsLegacyUserBlurbPath', () => { - const result = client.userProfileBlurbsLegacyUserBlurbPath("userValue", "legacyUserValue", "blurbValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchUserFromUserProfileBlurbsLegacyUserBlurbName', () => { - const result = client.matchUserFromUserProfileBlurbsLegacyUserBlurbName(fakePath); - assert.strictEqual(result, "userValue"); - assert((client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName', () => { - const result = client.matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName(fakePath); - assert.strictEqual(result, "legacyUserValue"); - assert((client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBlurbFromUserProfileBlurbsLegacyUserBlurbName', () => { - const result = client.matchBlurbFromUserProfileBlurbsLegacyUserBlurbName(fakePath); - assert.strictEqual(result, "blurbValue"); - assert((client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('userProfileBlurbsLegacyUserBlurb', () => { + const fakePath = '/rendered/path/userProfileBlurbsLegacyUserBlurb'; + const expectedParameters = { + user: 'userValue', + legacy_user: 'legacyUserValue', + blurb: 'blurbValue', + }; + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('userProfileBlurbsLegacyUserBlurbPath', () => { + const result = client.userProfileBlurbsLegacyUserBlurbPath( + 'userValue', + 'legacyUserValue', + 'blurbValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchUserFromUserProfileBlurbsLegacyUserBlurbName', () => { + const result = + client.matchUserFromUserProfileBlurbsLegacyUserBlurbName(fakePath); + assert.strictEqual(result, 'userValue'); + assert( + ( + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName', () => { + const result = + client.matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName( + fakePath, + ); + assert.strictEqual(result, 'legacyUserValue'); + assert( + ( + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBlurbFromUserProfileBlurbsLegacyUserBlurbName', () => { + const result = + client.matchBlurbFromUserProfileBlurbsLegacyUserBlurbName(fakePath); + assert.strictEqual(result, 'blurbValue'); + assert( + ( + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/core/generator/gapic-generator-typescript/baselines/disable-packing-test-esm/esm/test/gapic_echo_v1beta1.ts.baseline b/core/generator/gapic-generator-typescript/baselines/disable-packing-test-esm/esm/test/gapic_echo_v1beta1.ts.baseline index 20d0e7f6fb07..39461718602d 100644 --- a/core/generator/gapic-generator-typescript/baselines/disable-packing-test-esm/esm/test/gapic_echo_v1beta1.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/disable-packing-test-esm/esm/test/gapic_echo_v1beta1.ts.baseline @@ -20,16 +20,16 @@ import * as protos from '../../protos/protos.js'; import assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as echoModule from '../src/index.js'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; -import {protobuf, LROperation, operationsProtos} from 'google-gax'; +import { protobuf, LROperation, operationsProtos } from 'google-gax'; import fs from 'fs'; import path from 'path'; -import {fileURLToPath} from 'url'; +import { fileURLToPath } from 'url'; // @ts-ignore const dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -37,1501 +37,1934 @@ const dirname = path.dirname(fileURLToPath(import.meta.url)); // to fill in default values for request objects const root = protobuf.Root.fromJSON( JSON.parse( - fs.readFileSync(path.join(dirname, '..', '..', 'protos/protos.json'), 'utf8') - )) + fs.readFileSync( + path.join(dirname, '..', '..', 'protos/protos.json'), + 'utf8', + ), + ), +); // eslint-disable-next-line @typescript-eslint/no-unused-vars function getTypeDefaultValue(typeName: string, fields: string[]) { - let type = root.lookupType(typeName) as protobuf.Type; - for (const field of fields.slice(0, -1)) { - type = type?.fields[field]?.resolvedType as protobuf.Type; - } - return type?.fields[fields[fields.length - 1]]?.defaultValue ?? null; + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type?.fields[field]?.resolvedType as protobuf.Type; + } + return type?.fields[fields[fields.length - 1]]?.defaultValue ?? null; } function generateSampleMessage(instance: T) { - const filledObject = (instance.constructor as typeof protobuf.Message) - .toObject(instance as protobuf.Message, {defaults: true}); - return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, { defaults: true }); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; } function stubSimpleCall(response?: ResponseType, error?: Error) { - return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); } -function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { - return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +function stubSimpleCallWithCallback( + response?: ResponseType, + error?: Error, +) { + return error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); } -function stubServerStreamingCall(response?: ResponseType, error?: Error) { - const transformStub = error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); - const mockStream = new PassThrough({ - objectMode: true, - transform: transformStub, - }); - // write something to the stream to trigger transformStub and send the response back to the client - setImmediate(() => { mockStream.write({}); }); - setImmediate(() => { mockStream.end(); }); - return sinon.stub().returns(mockStream); +function stubServerStreamingCall( + response?: ResponseType, + error?: Error, +) { + const transformStub = error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + // write something to the stream to trigger transformStub and send the response back to the client + setImmediate(() => { + mockStream.write({}); + }); + setImmediate(() => { + mockStream.end(); + }); + return sinon.stub().returns(mockStream); } -function stubBidiStreamingCall(response?: ResponseType, error?: Error) { - const transformStub = error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); - const mockStream = new PassThrough({ - objectMode: true, - transform: transformStub, - }); - return sinon.stub().returns(mockStream); +function stubBidiStreamingCall( + response?: ResponseType, + error?: Error, +) { + const transformStub = error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + return sinon.stub().returns(mockStream); } -function stubClientStreamingCall(response?: ResponseType, error?: Error) { - if (error) { - return sinon.stub().callsArgWith(2, error); - } - const transformStub = sinon.stub(); - const mockStream = new PassThrough({ - objectMode: true, - transform: transformStub, - }); - return sinon.stub().returns(mockStream).callsArgWith(2, null, response); +function stubClientStreamingCall( + response?: ResponseType, + error?: Error, +) { + if (error) { + return sinon.stub().callsArgWith(2, error); + } + const transformStub = sinon.stub(); + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + return sinon.stub().returns(mockStream).callsArgWith(2, null, response); } -function stubLongRunningCall(response?: ResponseType, callError?: Error, lroError?: Error) { - const innerStub = lroError ? sinon.stub().rejects(lroError) : sinon.stub().resolves([response]); - const mockOperation = { - promise: innerStub, - }; - return callError ? sinon.stub().rejects(callError) : sinon.stub().resolves([mockOperation]); +function stubLongRunningCall( + response?: ResponseType, + callError?: Error, + lroError?: Error, +) { + const innerStub = lroError + ? sinon.stub().rejects(lroError) + : sinon.stub().resolves([response]); + const mockOperation = { + promise: innerStub, + }; + return callError + ? sinon.stub().rejects(callError) + : sinon.stub().resolves([mockOperation]); } -function stubLongRunningCallWithCallback(response?: ResponseType, callError?: Error, lroError?: Error) { - const innerStub = lroError ? sinon.stub().rejects(lroError) : sinon.stub().resolves([response]); - const mockOperation = { - promise: innerStub, - }; - return callError ? sinon.stub().callsArgWith(2, callError) : sinon.stub().callsArgWith(2, null, mockOperation); +function stubLongRunningCallWithCallback( + response?: ResponseType, + callError?: Error, + lroError?: Error, +) { + const innerStub = lroError + ? sinon.stub().rejects(lroError) + : sinon.stub().resolves([response]); + const mockOperation = { + promise: innerStub, + }; + return callError + ? sinon.stub().callsArgWith(2, callError) + : sinon.stub().callsArgWith(2, null, mockOperation); } -function stubPageStreamingCall(responses?: ResponseType[], error?: Error) { - const pagingStub = sinon.stub(); - if (responses) { - for (let i = 0; i < responses.length; ++i) { - pagingStub.onCall(i).callsArgWith(2, null, responses[i]); - } +function stubPageStreamingCall( + responses?: ResponseType[], + error?: Error, +) { + const pagingStub = sinon.stub(); + if (responses) { + for (let i = 0; i < responses.length; ++i) { + pagingStub.onCall(i).callsArgWith(2, null, responses[i]); } - const transformStub = error ? sinon.stub().callsArgWith(2, error) : pagingStub; - const mockStream = new PassThrough({ - objectMode: true, - transform: transformStub, - }); - // trigger as many responses as needed - if (responses) { - for (let i = 0; i < responses.length; ++i) { - setImmediate(() => { mockStream.write({}); }); - } - setImmediate(() => { mockStream.end(); }); - } else { - setImmediate(() => { mockStream.write({}); }); - setImmediate(() => { mockStream.end(); }); + } + const transformStub = error + ? sinon.stub().callsArgWith(2, error) + : pagingStub; + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + // trigger as many responses as needed + if (responses) { + for (let i = 0; i < responses.length; ++i) { + setImmediate(() => { + mockStream.write({}); + }); } - return sinon.stub().returns(mockStream); + setImmediate(() => { + mockStream.end(); + }); + } else { + setImmediate(() => { + mockStream.write({}); + }); + setImmediate(() => { + mockStream.end(); + }); + } + return sinon.stub().returns(mockStream); } -function stubAsyncIterationCall(responses?: ResponseType[], error?: Error) { - let counter = 0; - const asyncIterable = { - [Symbol.asyncIterator]() { - return { - async next() { - if (error) { - return Promise.reject(error); - } - if (counter >= responses!.length) { - return Promise.resolve({done: true, value: undefined}); - } - return Promise.resolve({done: false, value: responses![counter++]}); - } - }; - } - }; - return sinon.stub().returns(asyncIterable); +function stubAsyncIterationCall( + responses?: ResponseType[], + error?: Error, +) { + let counter = 0; + const asyncIterable = { + [Symbol.asyncIterator]() { + return { + async next() { + if (error) { + return Promise.reject(error); + } + if (counter >= responses!.length) { + return Promise.resolve({ done: true, value: undefined }); + } + return Promise.resolve({ done: false, value: responses![counter++] }); + }, + }; + }, + }; + return sinon.stub().returns(asyncIterable); } describe('v1beta1.EchoClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new echoModule.v1beta1.EchoClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'localhost'); - }); - - it('has universeDomain', () => { - const client = new echoModule.v1beta1.EchoClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); - - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - it('throws DeprecationWarning if static servicePath is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const servicePath = echoModule.v1beta1.EchoClient.servicePath; - assert.strictEqual(servicePath, 'localhost'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = echoModule.v1beta1.EchoClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'localhost'); - assert(stub.called); - stub.restore(); - }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { new echoModule.v1beta1.EchoClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); - - it('has port', () => { - const port = echoModule.v1beta1.EchoClient.port; - assert(port); - assert(typeof port === 'number'); - }); - - it('should create a client with no option', () => { - const client = new echoModule.v1beta1.EchoClient(); - assert(client); - }); - - it('should create a client with gRPC fallback', () => { - const client = new echoModule.v1beta1.EchoClient({ - fallback: true, - }); - assert(client); - }); - - it('has initialize method and supports deferred initialization', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.echoStub, undefined); - await client.initialize(); - assert(client.echoStub); - }); - - it('has close method for the initialized client', done => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.echoStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); - - it('has close method for the non-initialized client', done => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.echoStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new echoModule.v1beta1.EchoClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'localhost'); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); - }); + it('has universeDomain', () => { + const client = new echoModule.v1beta1.EchoClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId((err?: Error|null, projectId?: string|null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } - }); - }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = echoModule.v1beta1.EchoClient.servicePath; + assert.strictEqual(servicePath, 'localhost'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = echoModule.v1beta1.EchoClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'localhost'); + assert(stub.called); + stub.restore(); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new echoModule.v1beta1.EchoClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); }); - describe('echo', () => { - it('invokes echo without error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.EchoRequest() - ); - // path template: {qux=projects/*}/** - request.otherHeader = 'projects/value/value'; - const expectedHeaderRequestParams = 'qux=projects%2Fvalue'; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.EchoResponse() - ); - client.innerApiCalls.echo = stubSimpleCall(expectedResponse); - const [response] = await client.echo(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.echo as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.echo as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has port', () => { + const port = echoModule.v1beta1.EchoClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('invokes echo without error using callback', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.EchoRequest() - ); - // path template: {qux=projects/*}/** - request.otherHeader = 'projects/value/value'; - const expectedHeaderRequestParams = 'qux=projects%2Fvalue'; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.EchoResponse() - ); - client.innerApiCalls.echo = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.echo( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IEchoResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.echo as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.echo as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('should create a client with no option', () => { + const client = new echoModule.v1beta1.EchoClient(); + assert(client); + }); - it('invokes echo with error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.EchoRequest() - ); - // path template: {qux=projects/*}/** - request.otherHeader = 'projects/value/value'; - const expectedHeaderRequestParams = 'qux=projects%2Fvalue'; - const expectedError = new Error('expected'); - client.innerApiCalls.echo = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.echo(request), expectedError); - const actualRequest = (client.innerApiCalls.echo as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.echo as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('should create a client with gRPC fallback', () => { + const client = new echoModule.v1beta1.EchoClient({ + fallback: true, + }); + assert(client); + }); - it('invokes echo with closed client', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.EchoRequest() - ); - // path template: {qux=projects/*}/** - request.otherHeader = 'projects/value/value'; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.echo(request), expectedError); - }); + it('has initialize method and supports deferred initialization', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.echoStub, undefined); + await client.initialize(); + assert(client.echoStub); }); - describe('echoErrorDetails', () => { - it('invokes echoErrorDetails without error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.EchoErrorDetailsRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.EchoErrorDetailsResponse() - ); - client.innerApiCalls.echoErrorDetails = stubSimpleCall(expectedResponse); - const [response] = await client.echoErrorDetails(request); - assert.deepStrictEqual(response, expectedResponse); + it('has close method for the initialized client', (done) => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.echoStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes echoErrorDetails without error using callback', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.EchoErrorDetailsRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.EchoErrorDetailsResponse() - ); - client.innerApiCalls.echoErrorDetails = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.echoErrorDetails( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IEchoErrorDetailsResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); + it('has close method for the non-initialized client', (done) => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.echoStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes echoErrorDetails with error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.EchoErrorDetailsRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.echoErrorDetails = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.echoErrorDetails(request), expectedError); - }); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + }); - it('invokes echoErrorDetails with closed client', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.EchoErrorDetailsRequest() - ); - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.echoErrorDetails(request), expectedError); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + }); + + describe('echo', () => { + it('invokes echo without error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.EchoRequest(), + ); + // path template: {qux=projects/*}/** + request.otherHeader = 'projects/value/value'; + const expectedHeaderRequestParams = 'qux=projects%2Fvalue'; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.EchoResponse(), + ); + client.innerApiCalls.echo = stubSimpleCall(expectedResponse); + const [response] = await client.echo(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.echo as SinonStub).getCall(0) + .args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.echo as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('pagedExpandLegacy', () => { - it('invokes pagedExpandLegacy without error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.PagedExpandLegacyRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.PagedExpandResponse() - ); - client.innerApiCalls.pagedExpandLegacy = stubSimpleCall(expectedResponse); - const [response] = await client.pagedExpandLegacy(request); - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes echo without error using callback', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.EchoRequest(), + ); + // path template: {qux=projects/*}/** + request.otherHeader = 'projects/value/value'; + const expectedHeaderRequestParams = 'qux=projects%2Fvalue'; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.EchoResponse(), + ); + client.innerApiCalls.echo = stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.echo( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IEchoResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.echo as SinonStub).getCall(0) + .args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.echo as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes pagedExpandLegacy without error using callback', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.PagedExpandLegacyRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.PagedExpandResponse() - ); - client.innerApiCalls.pagedExpandLegacy = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.pagedExpandLegacy( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IPagedExpandResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes echo with error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.EchoRequest(), + ); + // path template: {qux=projects/*}/** + request.otherHeader = 'projects/value/value'; + const expectedHeaderRequestParams = 'qux=projects%2Fvalue'; + const expectedError = new Error('expected'); + client.innerApiCalls.echo = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.echo(request), expectedError); + const actualRequest = (client.innerApiCalls.echo as SinonStub).getCall(0) + .args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.echo as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes pagedExpandLegacy with error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.PagedExpandLegacyRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.pagedExpandLegacy = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.pagedExpandLegacy(request), expectedError); - }); + it('invokes echo with closed client', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.EchoRequest(), + ); + // path template: {qux=projects/*}/** + request.otherHeader = 'projects/value/value'; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.echo(request), expectedError); + }); + }); + + describe('echoErrorDetails', () => { + it('invokes echoErrorDetails without error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.EchoErrorDetailsRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.EchoErrorDetailsResponse(), + ); + client.innerApiCalls.echoErrorDetails = stubSimpleCall(expectedResponse); + const [response] = await client.echoErrorDetails(request); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes pagedExpandLegacy with closed client', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.PagedExpandLegacyRequest() - ); - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.pagedExpandLegacy(request), expectedError); - }); + it('invokes echoErrorDetails without error using callback', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.EchoErrorDetailsRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.EchoErrorDetailsResponse(), + ); + client.innerApiCalls.echoErrorDetails = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.echoErrorDetails( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IEchoErrorDetailsResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); }); - describe('block', () => { - it('invokes block without error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.BlockRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.BlockResponse() - ); - client.innerApiCalls.block = stubSimpleCall(expectedResponse); - const [response] = await client.block(request); - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes echoErrorDetails with error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.EchoErrorDetailsRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.echoErrorDetails = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.echoErrorDetails(request), expectedError); + }); - it('invokes block without error using callback', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.BlockRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.BlockResponse() - ); - client.innerApiCalls.block = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.block( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IBlockResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes echoErrorDetails with closed client', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.EchoErrorDetailsRequest(), + ); + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.echoErrorDetails(request), expectedError); + }); + }); + + describe('pagedExpandLegacy', () => { + it('invokes pagedExpandLegacy without error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.PagedExpandLegacyRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.PagedExpandResponse(), + ); + client.innerApiCalls.pagedExpandLegacy = stubSimpleCall(expectedResponse); + const [response] = await client.pagedExpandLegacy(request); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes block with error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.BlockRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.block = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.block(request), expectedError); - }); + it('invokes pagedExpandLegacy without error using callback', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.PagedExpandLegacyRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.PagedExpandResponse(), + ); + client.innerApiCalls.pagedExpandLegacy = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.pagedExpandLegacy( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IPagedExpandResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes block with closed client', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.BlockRequest() - ); - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.block(request), expectedError); - }); + it('invokes pagedExpandLegacy with error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.PagedExpandLegacyRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.pagedExpandLegacy = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.pagedExpandLegacy(request), expectedError); }); - describe('wait', () => { - it('invokes wait without error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.WaitRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.wait = stubLongRunningCall(expectedResponse); - const [operation] = await client.wait(request); - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes pagedExpandLegacy with closed client', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.PagedExpandLegacyRequest(), + ); + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.pagedExpandLegacy(request), expectedError); + }); + }); + + describe('block', () => { + it('invokes block without error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.BlockRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.BlockResponse(), + ); + client.innerApiCalls.block = stubSimpleCall(expectedResponse); + const [response] = await client.block(request); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes wait without error using callback', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.WaitRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.wait = stubLongRunningCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.wait( - request, - (err?: Error|null, - result?: LROperation|null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const operation = await promise as LROperation; - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes block without error using callback', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.BlockRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.BlockResponse(), + ); + client.innerApiCalls.block = stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.block( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IBlockResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes wait with call error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.WaitRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.wait = stubLongRunningCall(undefined, expectedError); - await assert.rejects(client.wait(request), expectedError); - }); + it('invokes block with error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.BlockRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.block = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.block(request), expectedError); + }); - it('invokes wait with LRO error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.WaitRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.wait = stubLongRunningCall(undefined, undefined, expectedError); - const [operation] = await client.wait(request); - await assert.rejects(operation.promise(), expectedError); - }); + it('invokes block with closed client', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.BlockRequest(), + ); + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.block(request), expectedError); + }); + }); + + describe('wait', () => { + it('invokes wait without error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.WaitRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.wait = stubLongRunningCall(expectedResponse); + const [operation] = await client.wait(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes checkWaitProgress without error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedResponse = generateSampleMessage( - new operationsProtos.google.longrunning.Operation() - ); - expectedResponse.name = 'test'; - expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; - expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')} - - client.operationsClient.getOperation = stubSimpleCall(expectedResponse); - const decodedOperation = await client.checkWaitProgress(expectedResponse.name); - assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); - assert(decodedOperation.metadata); - assert((client.operationsClient.getOperation as SinonStub).getCall(0)); - }); + it('invokes wait without error using callback', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.WaitRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.wait = + stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.wait( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.showcase.v1beta1.IWaitResponse, + protos.google.showcase.v1beta1.IWaitMetadata + > | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const operation = (await promise) as LROperation< + protos.google.showcase.v1beta1.IWaitResponse, + protos.google.showcase.v1beta1.IWaitMetadata + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes checkWaitProgress with error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedError = new Error('expected'); - - client.operationsClient.getOperation = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.checkWaitProgress(''), expectedError); - assert((client.operationsClient.getOperation as SinonStub) - .getCall(0)); - }); + it('invokes wait with call error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.WaitRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.wait = stubLongRunningCall(undefined, expectedError); + await assert.rejects(client.wait(request), expectedError); }); - describe('expand', () => { - it('invokes expand without error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ExpandRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.EchoResponse() - ); - client.innerApiCalls.expand = stubServerStreamingCall(expectedResponse); - const stream = client.expand(request); - const promise = new Promise((resolve, reject) => { - stream.on('data', (response: protos.google.showcase.v1beta1.EchoResponse) => { - resolve(response); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes wait with LRO error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.WaitRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.wait = stubLongRunningCall( + undefined, + undefined, + expectedError, + ); + const [operation] = await client.wait(request); + await assert.rejects(operation.promise(), expectedError); + }); - it('invokes expand without error and gaxServerStreamingRetries enabled', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ExpandRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.EchoResponse() - ); - client.innerApiCalls.expand = stubServerStreamingCall(expectedResponse); - const stream = client.expand(request); - const promise = new Promise((resolve, reject) => { - stream.on('data', (response: protos.google.showcase.v1beta1.EchoResponse) => { - resolve(response); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes checkWaitProgress without error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation(), + ); + expectedResponse.name = 'test'; + expectedResponse.response = { type_url: 'url', value: Buffer.from('') }; + expectedResponse.metadata = { type_url: 'url', value: Buffer.from('') }; + + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const decodedOperation = await client.checkWaitProgress( + expectedResponse.name, + ); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); - it('invokes expand with error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ExpandRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.expand = stubServerStreamingCall(undefined, expectedError); - const stream = client.expand(request); - const promise = new Promise((resolve, reject) => { - stream.on('data', (response: protos.google.showcase.v1beta1.EchoResponse) => { - resolve(response); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); + it('invokes checkWaitProgress with error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const expectedError = new Error('expected'); + + client.operationsClient.getOperation = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.checkWaitProgress(''), expectedError); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + }); + + describe('expand', () => { + it('invokes expand without error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ExpandRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.EchoResponse(), + ); + client.innerApiCalls.expand = stubServerStreamingCall(expectedResponse); + const stream = client.expand(request); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + (response: protos.google.showcase.v1beta1.EchoResponse) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes expand with closed client', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ExpandRequest() - ); - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - const stream = client.expand(request, {retryRequestOptions: {noResponseRetries: 0}}); - const promise = new Promise((resolve, reject) => { - stream.on('data', (response: protos.google.showcase.v1beta1.EchoResponse) => { - resolve(response); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - }); - it('should create a client with gaxServerStreamingRetries enabled', () => { - const client = new echoModule.v1beta1.EchoClient({ - gaxServerStreamingRetries: true, - }); - assert(client); + it('invokes expand without error and gaxServerStreamingRetries enabled', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ExpandRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.EchoResponse(), + ); + client.innerApiCalls.expand = stubServerStreamingCall(expectedResponse); + const stream = client.expand(request); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + (response: protos.google.showcase.v1beta1.EchoResponse) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); }); - describe('chat', () => { - it('invokes chat without error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.EchoRequest() - ); - - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.EchoResponse() - ); - client.innerApiCalls.chat = stubBidiStreamingCall(expectedResponse); - const stream = client.chat(); - const promise = new Promise((resolve, reject) => { - stream.on('data', (response: protos.google.showcase.v1beta1.EchoResponse) => { - resolve(response); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - stream.write(request); - stream.end(); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - assert((client.innerApiCalls.chat as SinonStub) - .getCall(0).calledWith(null)); - assert.deepStrictEqual(((stream as unknown as PassThrough) - ._transform as SinonStub).getCall(0).args[0], request); + it('invokes expand with error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ExpandRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.expand = stubServerStreamingCall( + undefined, + expectedError, + ); + const stream = client.expand(request); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + (response: protos.google.showcase.v1beta1.EchoResponse) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); }); + }); + await assert.rejects(promise, expectedError); + }); - it('invokes chat with error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.EchoRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.chat = stubBidiStreamingCall(undefined, expectedError); - const stream = client.chat(); - const promise = new Promise((resolve, reject) => { - stream.on('data', (response: protos.google.showcase.v1beta1.EchoResponse) => { - resolve(response); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - stream.write(request); - stream.end(); - }); - await assert.rejects(promise, expectedError); - assert((client.innerApiCalls.chat as SinonStub) - .getCall(0).calledWith(null)); - assert.deepStrictEqual(((stream as unknown as PassThrough) - ._transform as SinonStub).getCall(0).args[0], request); + it('invokes expand with closed client', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ExpandRequest(), + ); + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + const stream = client.expand(request, { + retryRequestOptions: { noResponseRetries: 0 }, + }); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + (response: protos.google.showcase.v1beta1.EchoResponse) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); }); + }); + await assert.rejects(promise, expectedError); }); - - describe('collect', () => { - it('invokes collect without error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.EchoRequest() - ); - - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.EchoResponse() - ); - client.innerApiCalls.collect = stubClientStreamingCall(expectedResponse); - let stream: PassThrough; - const promise = new Promise((resolve, reject) => { - stream = client.collect( - (err?: Error|null, result?: protos.google.showcase.v1beta1.IEchoResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }) as unknown as PassThrough; - stream.write(request); - stream.end(); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - assert((client.innerApiCalls.collect as SinonStub) - .getCall(0).calledWith(null, {} /*, callback defined above */)); - assert.deepStrictEqual((stream!._transform as SinonStub).getCall(0).args[0], request); + it('should create a client with gaxServerStreamingRetries enabled', () => { + const client = new echoModule.v1beta1.EchoClient({ + gaxServerStreamingRetries: true, + }); + assert(client); + }); + }); + + describe('chat', () => { + it('invokes chat without error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.EchoRequest(), + ); + + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.EchoResponse(), + ); + client.innerApiCalls.chat = stubBidiStreamingCall(expectedResponse); + const stream = client.chat(); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + (response: protos.google.showcase.v1beta1.EchoResponse) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); }); + stream.write(request); + stream.end(); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + assert( + (client.innerApiCalls.chat as SinonStub).getCall(0).calledWith(null), + ); + assert.deepStrictEqual( + ((stream as unknown as PassThrough)._transform as SinonStub).getCall(0) + .args[0], + request, + ); + }); - it('invokes collect with error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.EchoRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.collect = stubClientStreamingCall(undefined, expectedError); - let stream: PassThrough; - const promise = new Promise((resolve, reject) => { - stream = client.collect( - (err?: Error|null, result?: protos.google.showcase.v1beta1.IEchoResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }) as unknown as PassThrough; - stream.write(request); - stream.end(); - }); - await assert.rejects(promise, expectedError); - assert((client.innerApiCalls.collect as SinonStub) - .getCall(0).calledWith(null, {} /*, callback defined above */)); + it('invokes chat with error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.EchoRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.chat = stubBidiStreamingCall( + undefined, + expectedError, + ); + const stream = client.chat(); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + (response: protos.google.showcase.v1beta1.EchoResponse) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); }); + stream.write(request); + stream.end(); + }); + await assert.rejects(promise, expectedError); + assert( + (client.innerApiCalls.chat as SinonStub).getCall(0).calledWith(null), + ); + assert.deepStrictEqual( + ((stream as unknown as PassThrough)._transform as SinonStub).getCall(0) + .args[0], + request, + ); + }); + }); + + describe('collect', () => { + it('invokes collect without error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.EchoRequest(), + ); + + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.EchoResponse(), + ); + client.innerApiCalls.collect = stubClientStreamingCall(expectedResponse); + let stream: PassThrough; + const promise = new Promise((resolve, reject) => { + stream = client.collect( + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IEchoResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ) as unknown as PassThrough; + stream.write(request); + stream.end(); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + assert( + (client.innerApiCalls.collect as SinonStub) + .getCall(0) + .calledWith(null, {} /*, callback defined above */), + ); + assert.deepStrictEqual( + (stream!._transform as SinonStub).getCall(0).args[0], + request, + ); }); - describe('pagedExpand', () => { - it('invokes pagedExpand without error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.PagedExpandRequest() - );const expectedResponse = [ - generateSampleMessage(new protos.google.showcase.v1beta1.EchoResponse()), - generateSampleMessage(new protos.google.showcase.v1beta1.EchoResponse()), - generateSampleMessage(new protos.google.showcase.v1beta1.EchoResponse()), - ]; - client.innerApiCalls.pagedExpand = stubSimpleCall(expectedResponse); - const [response] = await client.pagedExpand(request); - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes collect with error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.EchoRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.collect = stubClientStreamingCall( + undefined, + expectedError, + ); + let stream: PassThrough; + const promise = new Promise((resolve, reject) => { + stream = client.collect( + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IEchoResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ) as unknown as PassThrough; + stream.write(request); + stream.end(); + }); + await assert.rejects(promise, expectedError); + assert( + (client.innerApiCalls.collect as SinonStub) + .getCall(0) + .calledWith(null, {} /*, callback defined above */), + ); + }); + }); + + describe('pagedExpand', () => { + it('invokes pagedExpand without error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.PagedExpandRequest(), + ); + const expectedResponse = [ + generateSampleMessage( + new protos.google.showcase.v1beta1.EchoResponse(), + ), + generateSampleMessage( + new protos.google.showcase.v1beta1.EchoResponse(), + ), + generateSampleMessage( + new protos.google.showcase.v1beta1.EchoResponse(), + ), + ]; + client.innerApiCalls.pagedExpand = stubSimpleCall(expectedResponse); + const [response] = await client.pagedExpand(request); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes pagedExpand without error using callback', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.PagedExpandRequest() - );const expectedResponse = [ - generateSampleMessage(new protos.google.showcase.v1beta1.EchoResponse()), - generateSampleMessage(new protos.google.showcase.v1beta1.EchoResponse()), - generateSampleMessage(new protos.google.showcase.v1beta1.EchoResponse()), - ]; - client.innerApiCalls.pagedExpand = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.pagedExpand( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IEchoResponse[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes pagedExpand without error using callback', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.PagedExpandRequest(), + ); + const expectedResponse = [ + generateSampleMessage( + new protos.google.showcase.v1beta1.EchoResponse(), + ), + generateSampleMessage( + new protos.google.showcase.v1beta1.EchoResponse(), + ), + generateSampleMessage( + new protos.google.showcase.v1beta1.EchoResponse(), + ), + ]; + client.innerApiCalls.pagedExpand = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.pagedExpand( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IEchoResponse[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes pagedExpand with error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.PagedExpandRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.pagedExpand = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.pagedExpand(request), expectedError); - }); + it('invokes pagedExpand with error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.PagedExpandRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.pagedExpand = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.pagedExpand(request), expectedError); + }); - it('invokes pagedExpandStream without error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.PagedExpandRequest() - ); - const expectedResponse = [ - generateSampleMessage(new protos.google.showcase.v1beta1.EchoResponse()), - generateSampleMessage(new protos.google.showcase.v1beta1.EchoResponse()), - generateSampleMessage(new protos.google.showcase.v1beta1.EchoResponse()), - ]; - client.descriptors.page.pagedExpand.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.pagedExpandStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.showcase.v1beta1.EchoResponse[] = []; - stream.on('data', (response: protos.google.showcase.v1beta1.EchoResponse) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.pagedExpand.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.pagedExpand, request)); + it('invokes pagedExpandStream without error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.PagedExpandRequest(), + ); + const expectedResponse = [ + generateSampleMessage( + new protos.google.showcase.v1beta1.EchoResponse(), + ), + generateSampleMessage( + new protos.google.showcase.v1beta1.EchoResponse(), + ), + generateSampleMessage( + new protos.google.showcase.v1beta1.EchoResponse(), + ), + ]; + client.descriptors.page.pagedExpand.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.pagedExpandStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.showcase.v1beta1.EchoResponse[] = []; + stream.on( + 'data', + (response: protos.google.showcase.v1beta1.EchoResponse) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); }); - - it('invokes pagedExpandStream with error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.PagedExpandRequest() - ); - const expectedError = new Error('expected'); - client.descriptors.page.pagedExpand.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.pagedExpandStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.showcase.v1beta1.EchoResponse[] = []; - stream.on('data', (response: protos.google.showcase.v1beta1.EchoResponse) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.pagedExpand.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.pagedExpand, request)); + stream.on('error', (err: Error) => { + reject(err); }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.pagedExpand.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.pagedExpand, request), + ); + }); - it('uses async iteration with pagedExpand without error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.PagedExpandRequest() - ); - const expectedResponse = [ - generateSampleMessage(new protos.google.showcase.v1beta1.EchoResponse()), - generateSampleMessage(new protos.google.showcase.v1beta1.EchoResponse()), - generateSampleMessage(new protos.google.showcase.v1beta1.EchoResponse()), - ]; - client.descriptors.page.pagedExpand.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.showcase.v1beta1.IEchoResponse[] = []; - const iterable = client.pagedExpandAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.pagedExpand.asyncIterate as SinonStub) - .getCall(0).args[1], request); + it('invokes pagedExpandStream with error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.PagedExpandRequest(), + ); + const expectedError = new Error('expected'); + client.descriptors.page.pagedExpand.createStream = stubPageStreamingCall( + undefined, + expectedError, + ); + const stream = client.pagedExpandStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.showcase.v1beta1.EchoResponse[] = []; + stream.on( + 'data', + (response: protos.google.showcase.v1beta1.EchoResponse) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); }); - - it('uses async iteration with pagedExpand with error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.PagedExpandRequest() - ); - const expectedError = new Error('expected'); - client.descriptors.page.pagedExpand.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.pagedExpandAsync(request); - await assert.rejects(async () => { - const responses: protos.google.showcase.v1beta1.IEchoResponse[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.pagedExpand.asyncIterate as SinonStub) - .getCall(0).args[1], request); + stream.on('error', (err: Error) => { + reject(err); }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.pagedExpand.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.pagedExpand, request), + ); }); + it('uses async iteration with pagedExpand without error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.PagedExpandRequest(), + ); + const expectedResponse = [ + generateSampleMessage( + new protos.google.showcase.v1beta1.EchoResponse(), + ), + generateSampleMessage( + new protos.google.showcase.v1beta1.EchoResponse(), + ), + generateSampleMessage( + new protos.google.showcase.v1beta1.EchoResponse(), + ), + ]; + client.descriptors.page.pagedExpand.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.showcase.v1beta1.IEchoResponse[] = []; + const iterable = client.pagedExpandAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + (client.descriptors.page.pagedExpand.asyncIterate as SinonStub).getCall( + 0, + ).args[1], + request, + ); + }); - describe('Path templates', () => { - - describe('blueprint', () => { - const fakePath = "/rendered/path/blueprint"; - const expectedParameters = { - session: "sessionValue", - test: "testValue", - blueprint: "blueprintValue", - }; - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.blueprintPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.blueprintPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('blueprintPath', () => { - const result = client.blueprintPath("sessionValue", "testValue", "blueprintValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.blueprintPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchSessionFromBlueprintName', () => { - const result = client.matchSessionFromBlueprintName(fakePath); - assert.strictEqual(result, "sessionValue"); - assert((client.pathTemplates.blueprintPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchTestFromBlueprintName', () => { - const result = client.matchTestFromBlueprintName(fakePath); - assert.strictEqual(result, "testValue"); - assert((client.pathTemplates.blueprintPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBlueprintFromBlueprintName', () => { - const result = client.matchBlueprintFromBlueprintName(fakePath); - assert.strictEqual(result, "blueprintValue"); - assert((client.pathTemplates.blueprintPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('uses async iteration with pagedExpand with error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.PagedExpandRequest(), + ); + const expectedError = new Error('expected'); + client.descriptors.page.pagedExpand.asyncIterate = stubAsyncIterationCall( + undefined, + expectedError, + ); + const iterable = client.pagedExpandAsync(request); + await assert.rejects(async () => { + const responses: protos.google.showcase.v1beta1.IEchoResponse[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + (client.descriptors.page.pagedExpand.asyncIterate as SinonStub).getCall( + 0, + ).args[1], + request, + ); + }); + }); + + describe('Path templates', () => { + describe('blueprint', () => { + const fakePath = '/rendered/path/blueprint'; + const expectedParameters = { + session: 'sessionValue', + test: 'testValue', + blueprint: 'blueprintValue', + }; + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.blueprintPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.blueprintPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('blueprintPath', () => { + const result = client.blueprintPath( + 'sessionValue', + 'testValue', + 'blueprintValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.blueprintPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchSessionFromBlueprintName', () => { + const result = client.matchSessionFromBlueprintName(fakePath); + assert.strictEqual(result, 'sessionValue'); + assert( + (client.pathTemplates.blueprintPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchTestFromBlueprintName', () => { + const result = client.matchTestFromBlueprintName(fakePath); + assert.strictEqual(result, 'testValue'); + assert( + (client.pathTemplates.blueprintPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBlueprintFromBlueprintName', () => { + const result = client.matchBlueprintFromBlueprintName(fakePath); + assert.strictEqual(result, 'blueprintValue'); + assert( + (client.pathTemplates.blueprintPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('room', () => { - const fakePath = "/rendered/path/room"; - const expectedParameters = { - room: "roomValue", - }; - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.roomPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.roomPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('roomPath', () => { - const result = client.roomPath("roomValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.roomPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchRoomFromRoomName', () => { - const result = client.matchRoomFromRoomName(fakePath); - assert.strictEqual(result, "roomValue"); - assert((client.pathTemplates.roomPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('room', () => { + const fakePath = '/rendered/path/room'; + const expectedParameters = { + room: 'roomValue', + }; + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.roomPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.roomPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('roomPath', () => { + const result = client.roomPath('roomValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.roomPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchRoomFromRoomName', () => { + const result = client.matchRoomFromRoomName(fakePath); + assert.strictEqual(result, 'roomValue'); + assert( + (client.pathTemplates.roomPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('roomBlurb', () => { - const fakePath = "/rendered/path/roomBlurb"; - const expectedParameters = { - room: "roomValue", - blurb: "blurbValue", - }; - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.roomBlurbPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.roomBlurbPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('roomBlurbPath', () => { - const result = client.roomBlurbPath("roomValue", "blurbValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.roomBlurbPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchRoomFromRoomBlurbName', () => { - const result = client.matchRoomFromRoomBlurbName(fakePath); - assert.strictEqual(result, "roomValue"); - assert((client.pathTemplates.roomBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBlurbFromRoomBlurbName', () => { - const result = client.matchBlurbFromRoomBlurbName(fakePath); - assert.strictEqual(result, "blurbValue"); - assert((client.pathTemplates.roomBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('roomBlurb', () => { + const fakePath = '/rendered/path/roomBlurb'; + const expectedParameters = { + room: 'roomValue', + blurb: 'blurbValue', + }; + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.roomBlurbPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.roomBlurbPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('roomBlurbPath', () => { + const result = client.roomBlurbPath('roomValue', 'blurbValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.roomBlurbPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchRoomFromRoomBlurbName', () => { + const result = client.matchRoomFromRoomBlurbName(fakePath); + assert.strictEqual(result, 'roomValue'); + assert( + (client.pathTemplates.roomBlurbPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBlurbFromRoomBlurbName', () => { + const result = client.matchBlurbFromRoomBlurbName(fakePath); + assert.strictEqual(result, 'blurbValue'); + assert( + (client.pathTemplates.roomBlurbPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('roomBlurbsLegacyRoomBlurb', () => { - const fakePath = "/rendered/path/roomBlurbsLegacyRoomBlurb"; - const expectedParameters = { - room: "roomValue", - legacy_room: "legacyRoomValue", - blurb: "blurbValue", - }; - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('roomBlurbsLegacyRoomBlurbPath', () => { - const result = client.roomBlurbsLegacyRoomBlurbPath("roomValue", "legacyRoomValue", "blurbValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchRoomFromRoomBlurbsLegacyRoomBlurbName', () => { - const result = client.matchRoomFromRoomBlurbsLegacyRoomBlurbName(fakePath); - assert.strictEqual(result, "roomValue"); - assert((client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName', () => { - const result = client.matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName(fakePath); - assert.strictEqual(result, "legacyRoomValue"); - assert((client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBlurbFromRoomBlurbsLegacyRoomBlurbName', () => { - const result = client.matchBlurbFromRoomBlurbsLegacyRoomBlurbName(fakePath); - assert.strictEqual(result, "blurbValue"); - assert((client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('roomBlurbsLegacyRoomBlurb', () => { + const fakePath = '/rendered/path/roomBlurbsLegacyRoomBlurb'; + const expectedParameters = { + room: 'roomValue', + legacy_room: 'legacyRoomValue', + blurb: 'blurbValue', + }; + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('roomBlurbsLegacyRoomBlurbPath', () => { + const result = client.roomBlurbsLegacyRoomBlurbPath( + 'roomValue', + 'legacyRoomValue', + 'blurbValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchRoomFromRoomBlurbsLegacyRoomBlurbName', () => { + const result = + client.matchRoomFromRoomBlurbsLegacyRoomBlurbName(fakePath); + assert.strictEqual(result, 'roomValue'); + assert( + ( + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName', () => { + const result = + client.matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName(fakePath); + assert.strictEqual(result, 'legacyRoomValue'); + assert( + ( + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBlurbFromRoomBlurbsLegacyRoomBlurbName', () => { + const result = + client.matchBlurbFromRoomBlurbsLegacyRoomBlurbName(fakePath); + assert.strictEqual(result, 'blurbValue'); + assert( + ( + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('sequence', () => { - const fakePath = "/rendered/path/sequence"; - const expectedParameters = { - sequence: "sequenceValue", - }; - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.sequencePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.sequencePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('sequencePath', () => { - const result = client.sequencePath("sequenceValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.sequencePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchSequenceFromSequenceName', () => { - const result = client.matchSequenceFromSequenceName(fakePath); - assert.strictEqual(result, "sequenceValue"); - assert((client.pathTemplates.sequencePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('sequence', () => { + const fakePath = '/rendered/path/sequence'; + const expectedParameters = { + sequence: 'sequenceValue', + }; + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.sequencePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.sequencePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('sequencePath', () => { + const result = client.sequencePath('sequenceValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.sequencePathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchSequenceFromSequenceName', () => { + const result = client.matchSequenceFromSequenceName(fakePath); + assert.strictEqual(result, 'sequenceValue'); + assert( + (client.pathTemplates.sequencePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('sequenceReport', () => { - const fakePath = "/rendered/path/sequenceReport"; - const expectedParameters = { - sequence: "sequenceValue", - }; - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.sequenceReportPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.sequenceReportPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('sequenceReportPath', () => { - const result = client.sequenceReportPath("sequenceValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.sequenceReportPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchSequenceFromSequenceReportName', () => { - const result = client.matchSequenceFromSequenceReportName(fakePath); - assert.strictEqual(result, "sequenceValue"); - assert((client.pathTemplates.sequenceReportPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('sequenceReport', () => { + const fakePath = '/rendered/path/sequenceReport'; + const expectedParameters = { + sequence: 'sequenceValue', + }; + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.sequenceReportPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.sequenceReportPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('sequenceReportPath', () => { + const result = client.sequenceReportPath('sequenceValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.sequenceReportPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchSequenceFromSequenceReportName', () => { + const result = client.matchSequenceFromSequenceReportName(fakePath); + assert.strictEqual(result, 'sequenceValue'); + assert( + (client.pathTemplates.sequenceReportPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('session', () => { - const fakePath = "/rendered/path/session"; - const expectedParameters = { - session: "sessionValue", - }; - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.sessionPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.sessionPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('sessionPath', () => { - const result = client.sessionPath("sessionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.sessionPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchSessionFromSessionName', () => { - const result = client.matchSessionFromSessionName(fakePath); - assert.strictEqual(result, "sessionValue"); - assert((client.pathTemplates.sessionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('session', () => { + const fakePath = '/rendered/path/session'; + const expectedParameters = { + session: 'sessionValue', + }; + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.sessionPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.sessionPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('sessionPath', () => { + const result = client.sessionPath('sessionValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.sessionPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchSessionFromSessionName', () => { + const result = client.matchSessionFromSessionName(fakePath); + assert.strictEqual(result, 'sessionValue'); + assert( + (client.pathTemplates.sessionPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('test', () => { - const fakePath = "/rendered/path/test"; - const expectedParameters = { - session: "sessionValue", - test: "testValue", - }; - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.testPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.testPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('testPath', () => { - const result = client.testPath("sessionValue", "testValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.testPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchSessionFromTestName', () => { - const result = client.matchSessionFromTestName(fakePath); - assert.strictEqual(result, "sessionValue"); - assert((client.pathTemplates.testPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchTestFromTestName', () => { - const result = client.matchTestFromTestName(fakePath); - assert.strictEqual(result, "testValue"); - assert((client.pathTemplates.testPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('test', () => { + const fakePath = '/rendered/path/test'; + const expectedParameters = { + session: 'sessionValue', + test: 'testValue', + }; + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.testPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.testPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('testPath', () => { + const result = client.testPath('sessionValue', 'testValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.testPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchSessionFromTestName', () => { + const result = client.matchSessionFromTestName(fakePath); + assert.strictEqual(result, 'sessionValue'); + assert( + (client.pathTemplates.testPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchTestFromTestName', () => { + const result = client.matchTestFromTestName(fakePath); + assert.strictEqual(result, 'testValue'); + assert( + (client.pathTemplates.testPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('user', () => { - const fakePath = "/rendered/path/user"; - const expectedParameters = { - user: "userValue", - }; - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.userPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.userPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('userPath', () => { - const result = client.userPath("userValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.userPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchUserFromUserName', () => { - const result = client.matchUserFromUserName(fakePath); - assert.strictEqual(result, "userValue"); - assert((client.pathTemplates.userPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('user', () => { + const fakePath = '/rendered/path/user'; + const expectedParameters = { + user: 'userValue', + }; + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.userPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.userPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('userPath', () => { + const result = client.userPath('userValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.userPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchUserFromUserName', () => { + const result = client.matchUserFromUserName(fakePath); + assert.strictEqual(result, 'userValue'); + assert( + (client.pathTemplates.userPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('userProfileBlurb', () => { - const fakePath = "/rendered/path/userProfileBlurb"; - const expectedParameters = { - user: "userValue", - blurb: "blurbValue", - }; - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.userProfileBlurbPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.userProfileBlurbPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('userProfileBlurbPath', () => { - const result = client.userProfileBlurbPath("userValue", "blurbValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.userProfileBlurbPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchUserFromUserProfileBlurbName', () => { - const result = client.matchUserFromUserProfileBlurbName(fakePath); - assert.strictEqual(result, "userValue"); - assert((client.pathTemplates.userProfileBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBlurbFromUserProfileBlurbName', () => { - const result = client.matchBlurbFromUserProfileBlurbName(fakePath); - assert.strictEqual(result, "blurbValue"); - assert((client.pathTemplates.userProfileBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('userProfileBlurb', () => { + const fakePath = '/rendered/path/userProfileBlurb'; + const expectedParameters = { + user: 'userValue', + blurb: 'blurbValue', + }; + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.userProfileBlurbPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.userProfileBlurbPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('userProfileBlurbPath', () => { + const result = client.userProfileBlurbPath('userValue', 'blurbValue'); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.userProfileBlurbPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchUserFromUserProfileBlurbName', () => { + const result = client.matchUserFromUserProfileBlurbName(fakePath); + assert.strictEqual(result, 'userValue'); + assert( + (client.pathTemplates.userProfileBlurbPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBlurbFromUserProfileBlurbName', () => { + const result = client.matchBlurbFromUserProfileBlurbName(fakePath); + assert.strictEqual(result, 'blurbValue'); + assert( + (client.pathTemplates.userProfileBlurbPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('userProfileBlurbsLegacyUserBlurb', () => { - const fakePath = "/rendered/path/userProfileBlurbsLegacyUserBlurb"; - const expectedParameters = { - user: "userValue", - legacy_user: "legacyUserValue", - blurb: "blurbValue", - }; - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('userProfileBlurbsLegacyUserBlurbPath', () => { - const result = client.userProfileBlurbsLegacyUserBlurbPath("userValue", "legacyUserValue", "blurbValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchUserFromUserProfileBlurbsLegacyUserBlurbName', () => { - const result = client.matchUserFromUserProfileBlurbsLegacyUserBlurbName(fakePath); - assert.strictEqual(result, "userValue"); - assert((client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName', () => { - const result = client.matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName(fakePath); - assert.strictEqual(result, "legacyUserValue"); - assert((client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBlurbFromUserProfileBlurbsLegacyUserBlurbName', () => { - const result = client.matchBlurbFromUserProfileBlurbsLegacyUserBlurbName(fakePath); - assert.strictEqual(result, "blurbValue"); - assert((client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('userProfileBlurbsLegacyUserBlurb', () => { + const fakePath = '/rendered/path/userProfileBlurbsLegacyUserBlurb'; + const expectedParameters = { + user: 'userValue', + legacy_user: 'legacyUserValue', + blurb: 'blurbValue', + }; + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('userProfileBlurbsLegacyUserBlurbPath', () => { + const result = client.userProfileBlurbsLegacyUserBlurbPath( + 'userValue', + 'legacyUserValue', + 'blurbValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchUserFromUserProfileBlurbsLegacyUserBlurbName', () => { + const result = + client.matchUserFromUserProfileBlurbsLegacyUserBlurbName(fakePath); + assert.strictEqual(result, 'userValue'); + assert( + ( + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName', () => { + const result = + client.matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName( + fakePath, + ); + assert.strictEqual(result, 'legacyUserValue'); + assert( + ( + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBlurbFromUserProfileBlurbsLegacyUserBlurbName', () => { + const result = + client.matchBlurbFromUserProfileBlurbsLegacyUserBlurbName(fakePath); + assert.strictEqual(result, 'blurbValue'); + assert( + ( + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/core/generator/gapic-generator-typescript/baselines/disable-packing-test-esm/esm/test/gapic_identity_v1beta1.ts.baseline b/core/generator/gapic-generator-typescript/baselines/disable-packing-test-esm/esm/test/gapic_identity_v1beta1.ts.baseline index 2da43f67b837..a23a82809616 100644 --- a/core/generator/gapic-generator-typescript/baselines/disable-packing-test-esm/esm/test/gapic_identity_v1beta1.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/disable-packing-test-esm/esm/test/gapic_identity_v1beta1.ts.baseline @@ -20,16 +20,16 @@ import * as protos from '../../protos/protos.js'; import assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as identityModule from '../src/index.js'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; -import {protobuf} from 'google-gax'; +import { protobuf } from 'google-gax'; import fs from 'fs'; import path from 'path'; -import {fileURLToPath} from 'url'; +import { fileURLToPath } from 'url'; // @ts-ignore const dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -37,1176 +37,1513 @@ const dirname = path.dirname(fileURLToPath(import.meta.url)); // to fill in default values for request objects const root = protobuf.Root.fromJSON( JSON.parse( - fs.readFileSync(path.join(dirname, '..', '..', 'protos/protos.json'), 'utf8') - )) + fs.readFileSync( + path.join(dirname, '..', '..', 'protos/protos.json'), + 'utf8', + ), + ), +); // eslint-disable-next-line @typescript-eslint/no-unused-vars function getTypeDefaultValue(typeName: string, fields: string[]) { - let type = root.lookupType(typeName) as protobuf.Type; - for (const field of fields.slice(0, -1)) { - type = type?.fields[field]?.resolvedType as protobuf.Type; - } - return type?.fields[fields[fields.length - 1]]?.defaultValue ?? null; + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type?.fields[field]?.resolvedType as protobuf.Type; + } + return type?.fields[fields[fields.length - 1]]?.defaultValue ?? null; } function generateSampleMessage(instance: T) { - const filledObject = (instance.constructor as typeof protobuf.Message) - .toObject(instance as protobuf.Message, {defaults: true}); - return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, { defaults: true }); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; } function stubSimpleCall(response?: ResponseType, error?: Error) { - return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); } -function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { - return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +function stubSimpleCallWithCallback( + response?: ResponseType, + error?: Error, +) { + return error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); } -function stubPageStreamingCall(responses?: ResponseType[], error?: Error) { - const pagingStub = sinon.stub(); - if (responses) { - for (let i = 0; i < responses.length; ++i) { - pagingStub.onCall(i).callsArgWith(2, null, responses[i]); - } +function stubPageStreamingCall( + responses?: ResponseType[], + error?: Error, +) { + const pagingStub = sinon.stub(); + if (responses) { + for (let i = 0; i < responses.length; ++i) { + pagingStub.onCall(i).callsArgWith(2, null, responses[i]); } - const transformStub = error ? sinon.stub().callsArgWith(2, error) : pagingStub; - const mockStream = new PassThrough({ - objectMode: true, - transform: transformStub, - }); - // trigger as many responses as needed - if (responses) { - for (let i = 0; i < responses.length; ++i) { - setImmediate(() => { mockStream.write({}); }); - } - setImmediate(() => { mockStream.end(); }); - } else { - setImmediate(() => { mockStream.write({}); }); - setImmediate(() => { mockStream.end(); }); + } + const transformStub = error + ? sinon.stub().callsArgWith(2, error) + : pagingStub; + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + // trigger as many responses as needed + if (responses) { + for (let i = 0; i < responses.length; ++i) { + setImmediate(() => { + mockStream.write({}); + }); } - return sinon.stub().returns(mockStream); + setImmediate(() => { + mockStream.end(); + }); + } else { + setImmediate(() => { + mockStream.write({}); + }); + setImmediate(() => { + mockStream.end(); + }); + } + return sinon.stub().returns(mockStream); } -function stubAsyncIterationCall(responses?: ResponseType[], error?: Error) { - let counter = 0; - const asyncIterable = { - [Symbol.asyncIterator]() { - return { - async next() { - if (error) { - return Promise.reject(error); - } - if (counter >= responses!.length) { - return Promise.resolve({done: true, value: undefined}); - } - return Promise.resolve({done: false, value: responses![counter++]}); - } - }; - } - }; - return sinon.stub().returns(asyncIterable); +function stubAsyncIterationCall( + responses?: ResponseType[], + error?: Error, +) { + let counter = 0; + const asyncIterable = { + [Symbol.asyncIterator]() { + return { + async next() { + if (error) { + return Promise.reject(error); + } + if (counter >= responses!.length) { + return Promise.resolve({ done: true, value: undefined }); + } + return Promise.resolve({ done: false, value: responses![counter++] }); + }, + }; + }, + }; + return sinon.stub().returns(asyncIterable); } describe('v1beta1.IdentityClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new identityModule.v1beta1.IdentityClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'localhost'); - }); - - it('has universeDomain', () => { - const client = new identityModule.v1beta1.IdentityClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); - - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - it('throws DeprecationWarning if static servicePath is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const servicePath = identityModule.v1beta1.IdentityClient.servicePath; - assert.strictEqual(servicePath, 'localhost'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = identityModule.v1beta1.IdentityClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'localhost'); - assert(stub.called); - stub.restore(); - }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { new identityModule.v1beta1.IdentityClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new identityModule.v1beta1.IdentityClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'localhost'); + }); - it('has port', () => { - const port = identityModule.v1beta1.IdentityClient.port; - assert(port); - assert(typeof port === 'number'); - }); + it('has universeDomain', () => { + const client = new identityModule.v1beta1.IdentityClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - it('should create a client with no option', () => { - const client = new identityModule.v1beta1.IdentityClient(); - assert(client); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = identityModule.v1beta1.IdentityClient.servicePath; + assert.strictEqual(servicePath, 'localhost'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = identityModule.v1beta1.IdentityClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'localhost'); + assert(stub.called); + stub.restore(); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new identityModule.v1beta1.IdentityClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); + }); - it('should create a client with gRPC fallback', () => { - const client = new identityModule.v1beta1.IdentityClient({ - fallback: true, - }); - assert(client); - }); + it('has port', () => { + const port = identityModule.v1beta1.IdentityClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('has initialize method and supports deferred initialization', async () => { - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.identityStub, undefined); - await client.initialize(); - assert(client.identityStub); - }); + it('should create a client with no option', () => { + const client = new identityModule.v1beta1.IdentityClient(); + assert(client); + }); - it('has close method for the initialized client', done => { - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.identityStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('should create a client with gRPC fallback', () => { + const client = new identityModule.v1beta1.IdentityClient({ + fallback: true, + }); + assert(client); + }); - it('has close method for the non-initialized client', done => { - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.identityStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('has initialize method and supports deferred initialization', async () => { + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.identityStub, undefined); + await client.initialize(); + assert(client.identityStub); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + it('has close method for the initialized client', (done) => { + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.identityStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId((err?: Error|null, projectId?: string|null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } - }); - }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); + it('has close method for the non-initialized client', (done) => { + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.identityStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); }); - describe('createUser', () => { - it('invokes createUser without error', async () => { - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.CreateUserRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.User() - ); - client.innerApiCalls.createUser = stubSimpleCall(expectedResponse); - const [response] = await client.createUser(request); - assert.deepStrictEqual(response, expectedResponse); - }); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + }); - it('invokes createUser without error using callback', async () => { - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.CreateUserRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.User() - ); - client.innerApiCalls.createUser = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createUser( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IUser|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + }); + + describe('createUser', () => { + it('invokes createUser without error', async () => { + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.CreateUserRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.User(), + ); + client.innerApiCalls.createUser = stubSimpleCall(expectedResponse); + const [response] = await client.createUser(request); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes createUser with error', async () => { - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.CreateUserRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.createUser = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createUser(request), expectedError); - }); + it('invokes createUser without error using callback', async () => { + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.CreateUserRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.User(), + ); + client.innerApiCalls.createUser = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createUser( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IUser | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes createUser with closed client', async () => { - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.CreateUserRequest() - ); - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createUser(request), expectedError); - }); + it('invokes createUser with error', async () => { + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.CreateUserRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.createUser = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.createUser(request), expectedError); }); - describe('getUser', () => { - it('invokes getUser without error', async () => { - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.GetUserRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.GetUserRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.User() - ); - client.innerApiCalls.getUser = stubSimpleCall(expectedResponse); - const [response] = await client.getUser(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getUser as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getUser as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createUser with closed client', async () => { + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.CreateUserRequest(), + ); + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.createUser(request), expectedError); + }); + }); + + describe('getUser', () => { + it('invokes getUser without error', async () => { + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.GetUserRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.GetUserRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.User(), + ); + client.innerApiCalls.getUser = stubSimpleCall(expectedResponse); + const [response] = await client.getUser(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.getUser as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getUser as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getUser without error using callback', async () => { - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.GetUserRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.GetUserRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.User() - ); - client.innerApiCalls.getUser = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getUser( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IUser|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getUser as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getUser as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getUser without error using callback', async () => { + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.GetUserRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.GetUserRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.User(), + ); + client.innerApiCalls.getUser = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getUser( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IUser | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.getUser as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getUser as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getUser with error', async () => { - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.GetUserRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.GetUserRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getUser = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getUser(request), expectedError); - const actualRequest = (client.innerApiCalls.getUser as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getUser as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getUser with error', async () => { + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.GetUserRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.GetUserRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getUser = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.getUser(request), expectedError); + const actualRequest = (client.innerApiCalls.getUser as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getUser as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getUser with closed client', async () => { - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.GetUserRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.GetUserRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getUser(request), expectedError); - }); + it('invokes getUser with closed client', async () => { + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.GetUserRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.GetUserRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getUser(request), expectedError); + }); + }); + + describe('updateUser', () => { + it('invokes updateUser without error', async () => { + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.UpdateUserRequest(), + ); + request.user ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.UpdateUserRequest', + ['user', 'name'], + ); + request.user.name = defaultValue1; + const expectedHeaderRequestParams = `user.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.User(), + ); + client.innerApiCalls.updateUser = stubSimpleCall(expectedResponse); + const [response] = await client.updateUser(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateUser as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateUser as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('updateUser', () => { - it('invokes updateUser without error', async () => { - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.UpdateUserRequest() - ); - request.user ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.UpdateUserRequest', ['user', 'name']); - request.user.name = defaultValue1; - const expectedHeaderRequestParams = `user.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.User() - ); - client.innerApiCalls.updateUser = stubSimpleCall(expectedResponse); - const [response] = await client.updateUser(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateUser as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateUser as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateUser without error using callback', async () => { + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.UpdateUserRequest(), + ); + request.user ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.UpdateUserRequest', + ['user', 'name'], + ); + request.user.name = defaultValue1; + const expectedHeaderRequestParams = `user.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.User(), + ); + client.innerApiCalls.updateUser = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateUser( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IUser | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateUser as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateUser as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateUser without error using callback', async () => { - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.UpdateUserRequest() - ); - request.user ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.UpdateUserRequest', ['user', 'name']); - request.user.name = defaultValue1; - const expectedHeaderRequestParams = `user.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.User() - ); - client.innerApiCalls.updateUser = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateUser( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IUser|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateUser as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateUser as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateUser with error', async () => { + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.UpdateUserRequest(), + ); + request.user ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.UpdateUserRequest', + ['user', 'name'], + ); + request.user.name = defaultValue1; + const expectedHeaderRequestParams = `user.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateUser = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.updateUser(request), expectedError); + const actualRequest = ( + client.innerApiCalls.updateUser as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateUser as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateUser with error', async () => { - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.UpdateUserRequest() - ); - request.user ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.UpdateUserRequest', ['user', 'name']); - request.user.name = defaultValue1; - const expectedHeaderRequestParams = `user.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateUser = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateUser(request), expectedError); - const actualRequest = (client.innerApiCalls.updateUser as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateUser as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateUser with closed client', async () => { + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.UpdateUserRequest(), + ); + request.user ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.UpdateUserRequest', + ['user', 'name'], + ); + request.user.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.updateUser(request), expectedError); + }); + }); + + describe('deleteUser', () => { + it('invokes deleteUser without error', async () => { + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.DeleteUserRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.DeleteUserRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteUser = stubSimpleCall(expectedResponse); + const [response] = await client.deleteUser(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteUser as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteUser as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateUser with closed client', async () => { - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.UpdateUserRequest() - ); - request.user ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.UpdateUserRequest', ['user', 'name']); - request.user.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateUser(request), expectedError); - }); + it('invokes deleteUser without error using callback', async () => { + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.DeleteUserRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.DeleteUserRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteUser = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteUser( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteUser as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteUser as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('deleteUser', () => { - it('invokes deleteUser without error', async () => { - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.DeleteUserRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.DeleteUserRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteUser = stubSimpleCall(expectedResponse); - const [response] = await client.deleteUser(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteUser as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteUser as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteUser with error', async () => { + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.DeleteUserRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.DeleteUserRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteUser = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.deleteUser(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteUser as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteUser as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteUser without error using callback', async () => { - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.DeleteUserRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.DeleteUserRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteUser = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteUser( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteUser as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteUser as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteUser with closed client', async () => { + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.DeleteUserRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.DeleteUserRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.deleteUser(request), expectedError); + }); + }); + + describe('listUsers', () => { + it('invokes listUsers without error', async () => { + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListUsersRequest(), + ); + const expectedResponse = [ + generateSampleMessage(new protos.google.showcase.v1beta1.User()), + generateSampleMessage(new protos.google.showcase.v1beta1.User()), + generateSampleMessage(new protos.google.showcase.v1beta1.User()), + ]; + client.innerApiCalls.listUsers = stubSimpleCall(expectedResponse); + const [response] = await client.listUsers(request); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes deleteUser with error', async () => { - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.DeleteUserRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.DeleteUserRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteUser = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteUser(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteUser as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteUser as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listUsers without error using callback', async () => { + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListUsersRequest(), + ); + const expectedResponse = [ + generateSampleMessage(new protos.google.showcase.v1beta1.User()), + generateSampleMessage(new protos.google.showcase.v1beta1.User()), + generateSampleMessage(new protos.google.showcase.v1beta1.User()), + ]; + client.innerApiCalls.listUsers = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listUsers( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IUser[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes deleteUser with closed client', async () => { - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.DeleteUserRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.DeleteUserRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteUser(request), expectedError); - }); + it('invokes listUsers with error', async () => { + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListUsersRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.listUsers = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.listUsers(request), expectedError); }); - describe('listUsers', () => { - it('invokes listUsers without error', async () => { - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListUsersRequest() - );const expectedResponse = [ - generateSampleMessage(new protos.google.showcase.v1beta1.User()), - generateSampleMessage(new protos.google.showcase.v1beta1.User()), - generateSampleMessage(new protos.google.showcase.v1beta1.User()), - ]; - client.innerApiCalls.listUsers = stubSimpleCall(expectedResponse); - const [response] = await client.listUsers(request); - assert.deepStrictEqual(response, expectedResponse); + it('invokes listUsersStream without error', async () => { + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListUsersRequest(), + ); + const expectedResponse = [ + generateSampleMessage(new protos.google.showcase.v1beta1.User()), + generateSampleMessage(new protos.google.showcase.v1beta1.User()), + generateSampleMessage(new protos.google.showcase.v1beta1.User()), + ]; + client.descriptors.page.listUsers.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listUsersStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.showcase.v1beta1.User[] = []; + stream.on('data', (response: protos.google.showcase.v1beta1.User) => { + responses.push(response); }); - - it('invokes listUsers without error using callback', async () => { - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListUsersRequest() - );const expectedResponse = [ - generateSampleMessage(new protos.google.showcase.v1beta1.User()), - generateSampleMessage(new protos.google.showcase.v1beta1.User()), - generateSampleMessage(new protos.google.showcase.v1beta1.User()), - ]; - client.innerApiCalls.listUsers = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listUsers( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IUser[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); + stream.on('end', () => { + resolve(responses); }); - - it('invokes listUsers with error', async () => { - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListUsersRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.listUsers = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listUsers(request), expectedError); + stream.on('error', (err: Error) => { + reject(err); }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listUsers.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listUsers, request), + ); + }); - it('invokes listUsersStream without error', async () => { - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListUsersRequest() - ); - const expectedResponse = [ - generateSampleMessage(new protos.google.showcase.v1beta1.User()), - generateSampleMessage(new protos.google.showcase.v1beta1.User()), - generateSampleMessage(new protos.google.showcase.v1beta1.User()), - ]; - client.descriptors.page.listUsers.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listUsersStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.showcase.v1beta1.User[] = []; - stream.on('data', (response: protos.google.showcase.v1beta1.User) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.listUsers.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listUsers, request)); + it('invokes listUsersStream with error', async () => { + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListUsersRequest(), + ); + const expectedError = new Error('expected'); + client.descriptors.page.listUsers.createStream = stubPageStreamingCall( + undefined, + expectedError, + ); + const stream = client.listUsersStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.showcase.v1beta1.User[] = []; + stream.on('data', (response: protos.google.showcase.v1beta1.User) => { + responses.push(response); }); - - it('invokes listUsersStream with error', async () => { - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListUsersRequest() - ); - const expectedError = new Error('expected'); - client.descriptors.page.listUsers.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listUsersStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.showcase.v1beta1.User[] = []; - stream.on('data', (response: protos.google.showcase.v1beta1.User) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listUsers.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listUsers, request)); + stream.on('end', () => { + resolve(responses); }); - - it('uses async iteration with listUsers without error', async () => { - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListUsersRequest() - ); - const expectedResponse = [ - generateSampleMessage(new protos.google.showcase.v1beta1.User()), - generateSampleMessage(new protos.google.showcase.v1beta1.User()), - generateSampleMessage(new protos.google.showcase.v1beta1.User()), - ]; - client.descriptors.page.listUsers.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.showcase.v1beta1.IUser[] = []; - const iterable = client.listUsersAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listUsers.asyncIterate as SinonStub) - .getCall(0).args[1], request); + stream.on('error', (err: Error) => { + reject(err); }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listUsers.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listUsers, request), + ); + }); - it('uses async iteration with listUsers with error', async () => { - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListUsersRequest() - ); - const expectedError = new Error('expected'); - client.descriptors.page.listUsers.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listUsersAsync(request); - await assert.rejects(async () => { - const responses: protos.google.showcase.v1beta1.IUser[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listUsers.asyncIterate as SinonStub) - .getCall(0).args[1], request); - }); + it('uses async iteration with listUsers without error', async () => { + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListUsersRequest(), + ); + const expectedResponse = [ + generateSampleMessage(new protos.google.showcase.v1beta1.User()), + generateSampleMessage(new protos.google.showcase.v1beta1.User()), + generateSampleMessage(new protos.google.showcase.v1beta1.User()), + ]; + client.descriptors.page.listUsers.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.showcase.v1beta1.IUser[] = []; + const iterable = client.listUsersAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + (client.descriptors.page.listUsers.asyncIterate as SinonStub).getCall(0) + .args[1], + request, + ); }); - describe('Path templates', () => { - - describe('blueprint', () => { - const fakePath = "/rendered/path/blueprint"; - const expectedParameters = { - session: "sessionValue", - test: "testValue", - blueprint: "blueprintValue", - }; - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.blueprintPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.blueprintPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('blueprintPath', () => { - const result = client.blueprintPath("sessionValue", "testValue", "blueprintValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.blueprintPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchSessionFromBlueprintName', () => { - const result = client.matchSessionFromBlueprintName(fakePath); - assert.strictEqual(result, "sessionValue"); - assert((client.pathTemplates.blueprintPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchTestFromBlueprintName', () => { - const result = client.matchTestFromBlueprintName(fakePath); - assert.strictEqual(result, "testValue"); - assert((client.pathTemplates.blueprintPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBlueprintFromBlueprintName', () => { - const result = client.matchBlueprintFromBlueprintName(fakePath); - assert.strictEqual(result, "blueprintValue"); - assert((client.pathTemplates.blueprintPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('uses async iteration with listUsers with error', async () => { + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListUsersRequest(), + ); + const expectedError = new Error('expected'); + client.descriptors.page.listUsers.asyncIterate = stubAsyncIterationCall( + undefined, + expectedError, + ); + const iterable = client.listUsersAsync(request); + await assert.rejects(async () => { + const responses: protos.google.showcase.v1beta1.IUser[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + (client.descriptors.page.listUsers.asyncIterate as SinonStub).getCall(0) + .args[1], + request, + ); + }); + }); + + describe('Path templates', () => { + describe('blueprint', () => { + const fakePath = '/rendered/path/blueprint'; + const expectedParameters = { + session: 'sessionValue', + test: 'testValue', + blueprint: 'blueprintValue', + }; + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.blueprintPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.blueprintPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('blueprintPath', () => { + const result = client.blueprintPath( + 'sessionValue', + 'testValue', + 'blueprintValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.blueprintPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchSessionFromBlueprintName', () => { + const result = client.matchSessionFromBlueprintName(fakePath); + assert.strictEqual(result, 'sessionValue'); + assert( + (client.pathTemplates.blueprintPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchTestFromBlueprintName', () => { + const result = client.matchTestFromBlueprintName(fakePath); + assert.strictEqual(result, 'testValue'); + assert( + (client.pathTemplates.blueprintPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBlueprintFromBlueprintName', () => { + const result = client.matchBlueprintFromBlueprintName(fakePath); + assert.strictEqual(result, 'blueprintValue'); + assert( + (client.pathTemplates.blueprintPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('room', () => { - const fakePath = "/rendered/path/room"; - const expectedParameters = { - room: "roomValue", - }; - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.roomPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.roomPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('roomPath', () => { - const result = client.roomPath("roomValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.roomPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchRoomFromRoomName', () => { - const result = client.matchRoomFromRoomName(fakePath); - assert.strictEqual(result, "roomValue"); - assert((client.pathTemplates.roomPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('room', () => { + const fakePath = '/rendered/path/room'; + const expectedParameters = { + room: 'roomValue', + }; + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.roomPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.roomPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('roomPath', () => { + const result = client.roomPath('roomValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.roomPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchRoomFromRoomName', () => { + const result = client.matchRoomFromRoomName(fakePath); + assert.strictEqual(result, 'roomValue'); + assert( + (client.pathTemplates.roomPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('roomBlurb', () => { - const fakePath = "/rendered/path/roomBlurb"; - const expectedParameters = { - room: "roomValue", - blurb: "blurbValue", - }; - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.roomBlurbPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.roomBlurbPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('roomBlurbPath', () => { - const result = client.roomBlurbPath("roomValue", "blurbValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.roomBlurbPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchRoomFromRoomBlurbName', () => { - const result = client.matchRoomFromRoomBlurbName(fakePath); - assert.strictEqual(result, "roomValue"); - assert((client.pathTemplates.roomBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBlurbFromRoomBlurbName', () => { - const result = client.matchBlurbFromRoomBlurbName(fakePath); - assert.strictEqual(result, "blurbValue"); - assert((client.pathTemplates.roomBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('roomBlurb', () => { + const fakePath = '/rendered/path/roomBlurb'; + const expectedParameters = { + room: 'roomValue', + blurb: 'blurbValue', + }; + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.roomBlurbPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.roomBlurbPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('roomBlurbPath', () => { + const result = client.roomBlurbPath('roomValue', 'blurbValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.roomBlurbPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchRoomFromRoomBlurbName', () => { + const result = client.matchRoomFromRoomBlurbName(fakePath); + assert.strictEqual(result, 'roomValue'); + assert( + (client.pathTemplates.roomBlurbPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBlurbFromRoomBlurbName', () => { + const result = client.matchBlurbFromRoomBlurbName(fakePath); + assert.strictEqual(result, 'blurbValue'); + assert( + (client.pathTemplates.roomBlurbPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('roomBlurbsLegacyRoomBlurb', () => { - const fakePath = "/rendered/path/roomBlurbsLegacyRoomBlurb"; - const expectedParameters = { - room: "roomValue", - legacy_room: "legacyRoomValue", - blurb: "blurbValue", - }; - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('roomBlurbsLegacyRoomBlurbPath', () => { - const result = client.roomBlurbsLegacyRoomBlurbPath("roomValue", "legacyRoomValue", "blurbValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchRoomFromRoomBlurbsLegacyRoomBlurbName', () => { - const result = client.matchRoomFromRoomBlurbsLegacyRoomBlurbName(fakePath); - assert.strictEqual(result, "roomValue"); - assert((client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName', () => { - const result = client.matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName(fakePath); - assert.strictEqual(result, "legacyRoomValue"); - assert((client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBlurbFromRoomBlurbsLegacyRoomBlurbName', () => { - const result = client.matchBlurbFromRoomBlurbsLegacyRoomBlurbName(fakePath); - assert.strictEqual(result, "blurbValue"); - assert((client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('roomBlurbsLegacyRoomBlurb', () => { + const fakePath = '/rendered/path/roomBlurbsLegacyRoomBlurb'; + const expectedParameters = { + room: 'roomValue', + legacy_room: 'legacyRoomValue', + blurb: 'blurbValue', + }; + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('roomBlurbsLegacyRoomBlurbPath', () => { + const result = client.roomBlurbsLegacyRoomBlurbPath( + 'roomValue', + 'legacyRoomValue', + 'blurbValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchRoomFromRoomBlurbsLegacyRoomBlurbName', () => { + const result = + client.matchRoomFromRoomBlurbsLegacyRoomBlurbName(fakePath); + assert.strictEqual(result, 'roomValue'); + assert( + ( + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName', () => { + const result = + client.matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName(fakePath); + assert.strictEqual(result, 'legacyRoomValue'); + assert( + ( + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBlurbFromRoomBlurbsLegacyRoomBlurbName', () => { + const result = + client.matchBlurbFromRoomBlurbsLegacyRoomBlurbName(fakePath); + assert.strictEqual(result, 'blurbValue'); + assert( + ( + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('sequence', () => { - const fakePath = "/rendered/path/sequence"; - const expectedParameters = { - sequence: "sequenceValue", - }; - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.sequencePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.sequencePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('sequencePath', () => { - const result = client.sequencePath("sequenceValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.sequencePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchSequenceFromSequenceName', () => { - const result = client.matchSequenceFromSequenceName(fakePath); - assert.strictEqual(result, "sequenceValue"); - assert((client.pathTemplates.sequencePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('sequence', () => { + const fakePath = '/rendered/path/sequence'; + const expectedParameters = { + sequence: 'sequenceValue', + }; + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.sequencePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.sequencePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('sequencePath', () => { + const result = client.sequencePath('sequenceValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.sequencePathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchSequenceFromSequenceName', () => { + const result = client.matchSequenceFromSequenceName(fakePath); + assert.strictEqual(result, 'sequenceValue'); + assert( + (client.pathTemplates.sequencePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('sequenceReport', () => { - const fakePath = "/rendered/path/sequenceReport"; - const expectedParameters = { - sequence: "sequenceValue", - }; - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.sequenceReportPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.sequenceReportPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('sequenceReportPath', () => { - const result = client.sequenceReportPath("sequenceValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.sequenceReportPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchSequenceFromSequenceReportName', () => { - const result = client.matchSequenceFromSequenceReportName(fakePath); - assert.strictEqual(result, "sequenceValue"); - assert((client.pathTemplates.sequenceReportPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('sequenceReport', () => { + const fakePath = '/rendered/path/sequenceReport'; + const expectedParameters = { + sequence: 'sequenceValue', + }; + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.sequenceReportPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.sequenceReportPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('sequenceReportPath', () => { + const result = client.sequenceReportPath('sequenceValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.sequenceReportPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchSequenceFromSequenceReportName', () => { + const result = client.matchSequenceFromSequenceReportName(fakePath); + assert.strictEqual(result, 'sequenceValue'); + assert( + (client.pathTemplates.sequenceReportPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('session', () => { - const fakePath = "/rendered/path/session"; - const expectedParameters = { - session: "sessionValue", - }; - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.sessionPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.sessionPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('sessionPath', () => { - const result = client.sessionPath("sessionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.sessionPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchSessionFromSessionName', () => { - const result = client.matchSessionFromSessionName(fakePath); - assert.strictEqual(result, "sessionValue"); - assert((client.pathTemplates.sessionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('session', () => { + const fakePath = '/rendered/path/session'; + const expectedParameters = { + session: 'sessionValue', + }; + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.sessionPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.sessionPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('sessionPath', () => { + const result = client.sessionPath('sessionValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.sessionPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchSessionFromSessionName', () => { + const result = client.matchSessionFromSessionName(fakePath); + assert.strictEqual(result, 'sessionValue'); + assert( + (client.pathTemplates.sessionPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('test', () => { - const fakePath = "/rendered/path/test"; - const expectedParameters = { - session: "sessionValue", - test: "testValue", - }; - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.testPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.testPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('testPath', () => { - const result = client.testPath("sessionValue", "testValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.testPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchSessionFromTestName', () => { - const result = client.matchSessionFromTestName(fakePath); - assert.strictEqual(result, "sessionValue"); - assert((client.pathTemplates.testPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchTestFromTestName', () => { - const result = client.matchTestFromTestName(fakePath); - assert.strictEqual(result, "testValue"); - assert((client.pathTemplates.testPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('test', () => { + const fakePath = '/rendered/path/test'; + const expectedParameters = { + session: 'sessionValue', + test: 'testValue', + }; + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.testPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.testPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('testPath', () => { + const result = client.testPath('sessionValue', 'testValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.testPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchSessionFromTestName', () => { + const result = client.matchSessionFromTestName(fakePath); + assert.strictEqual(result, 'sessionValue'); + assert( + (client.pathTemplates.testPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchTestFromTestName', () => { + const result = client.matchTestFromTestName(fakePath); + assert.strictEqual(result, 'testValue'); + assert( + (client.pathTemplates.testPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('user', () => { - const fakePath = "/rendered/path/user"; - const expectedParameters = { - user: "userValue", - }; - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.userPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.userPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('userPath', () => { - const result = client.userPath("userValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.userPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchUserFromUserName', () => { - const result = client.matchUserFromUserName(fakePath); - assert.strictEqual(result, "userValue"); - assert((client.pathTemplates.userPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('user', () => { + const fakePath = '/rendered/path/user'; + const expectedParameters = { + user: 'userValue', + }; + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.userPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.userPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('userPath', () => { + const result = client.userPath('userValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.userPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchUserFromUserName', () => { + const result = client.matchUserFromUserName(fakePath); + assert.strictEqual(result, 'userValue'); + assert( + (client.pathTemplates.userPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('userProfileBlurb', () => { - const fakePath = "/rendered/path/userProfileBlurb"; - const expectedParameters = { - user: "userValue", - blurb: "blurbValue", - }; - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.userProfileBlurbPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.userProfileBlurbPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('userProfileBlurbPath', () => { - const result = client.userProfileBlurbPath("userValue", "blurbValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.userProfileBlurbPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchUserFromUserProfileBlurbName', () => { - const result = client.matchUserFromUserProfileBlurbName(fakePath); - assert.strictEqual(result, "userValue"); - assert((client.pathTemplates.userProfileBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBlurbFromUserProfileBlurbName', () => { - const result = client.matchBlurbFromUserProfileBlurbName(fakePath); - assert.strictEqual(result, "blurbValue"); - assert((client.pathTemplates.userProfileBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('userProfileBlurb', () => { + const fakePath = '/rendered/path/userProfileBlurb'; + const expectedParameters = { + user: 'userValue', + blurb: 'blurbValue', + }; + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.userProfileBlurbPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.userProfileBlurbPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('userProfileBlurbPath', () => { + const result = client.userProfileBlurbPath('userValue', 'blurbValue'); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.userProfileBlurbPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchUserFromUserProfileBlurbName', () => { + const result = client.matchUserFromUserProfileBlurbName(fakePath); + assert.strictEqual(result, 'userValue'); + assert( + (client.pathTemplates.userProfileBlurbPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBlurbFromUserProfileBlurbName', () => { + const result = client.matchBlurbFromUserProfileBlurbName(fakePath); + assert.strictEqual(result, 'blurbValue'); + assert( + (client.pathTemplates.userProfileBlurbPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('userProfileBlurbsLegacyUserBlurb', () => { - const fakePath = "/rendered/path/userProfileBlurbsLegacyUserBlurb"; - const expectedParameters = { - user: "userValue", - legacy_user: "legacyUserValue", - blurb: "blurbValue", - }; - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('userProfileBlurbsLegacyUserBlurbPath', () => { - const result = client.userProfileBlurbsLegacyUserBlurbPath("userValue", "legacyUserValue", "blurbValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchUserFromUserProfileBlurbsLegacyUserBlurbName', () => { - const result = client.matchUserFromUserProfileBlurbsLegacyUserBlurbName(fakePath); - assert.strictEqual(result, "userValue"); - assert((client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName', () => { - const result = client.matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName(fakePath); - assert.strictEqual(result, "legacyUserValue"); - assert((client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBlurbFromUserProfileBlurbsLegacyUserBlurbName', () => { - const result = client.matchBlurbFromUserProfileBlurbsLegacyUserBlurbName(fakePath); - assert.strictEqual(result, "blurbValue"); - assert((client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('userProfileBlurbsLegacyUserBlurb', () => { + const fakePath = '/rendered/path/userProfileBlurbsLegacyUserBlurb'; + const expectedParameters = { + user: 'userValue', + legacy_user: 'legacyUserValue', + blurb: 'blurbValue', + }; + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('userProfileBlurbsLegacyUserBlurbPath', () => { + const result = client.userProfileBlurbsLegacyUserBlurbPath( + 'userValue', + 'legacyUserValue', + 'blurbValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchUserFromUserProfileBlurbsLegacyUserBlurbName', () => { + const result = + client.matchUserFromUserProfileBlurbsLegacyUserBlurbName(fakePath); + assert.strictEqual(result, 'userValue'); + assert( + ( + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName', () => { + const result = + client.matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName( + fakePath, + ); + assert.strictEqual(result, 'legacyUserValue'); + assert( + ( + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBlurbFromUserProfileBlurbsLegacyUserBlurbName', () => { + const result = + client.matchBlurbFromUserProfileBlurbsLegacyUserBlurbName(fakePath); + assert.strictEqual(result, 'blurbValue'); + assert( + ( + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/core/generator/gapic-generator-typescript/baselines/disable-packing-test-esm/esm/test/gapic_messaging_v1beta1.ts.baseline b/core/generator/gapic-generator-typescript/baselines/disable-packing-test-esm/esm/test/gapic_messaging_v1beta1.ts.baseline index e65f87dfaf42..9c254f7eedbd 100644 --- a/core/generator/gapic-generator-typescript/baselines/disable-packing-test-esm/esm/test/gapic_messaging_v1beta1.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/disable-packing-test-esm/esm/test/gapic_messaging_v1beta1.ts.baseline @@ -20,16 +20,16 @@ import * as protos from '../../protos/protos.js'; import assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as messagingModule from '../src/index.js'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; -import {protobuf, LROperation, operationsProtos} from 'google-gax'; +import { protobuf, LROperation, operationsProtos } from 'google-gax'; import fs from 'fs'; import path from 'path'; -import {fileURLToPath} from 'url'; +import { fileURLToPath } from 'url'; // @ts-ignore const dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -37,2328 +37,2954 @@ const dirname = path.dirname(fileURLToPath(import.meta.url)); // to fill in default values for request objects const root = protobuf.Root.fromJSON( JSON.parse( - fs.readFileSync(path.join(dirname, '..', '..', 'protos/protos.json'), 'utf8') - )) + fs.readFileSync( + path.join(dirname, '..', '..', 'protos/protos.json'), + 'utf8', + ), + ), +); // eslint-disable-next-line @typescript-eslint/no-unused-vars function getTypeDefaultValue(typeName: string, fields: string[]) { - let type = root.lookupType(typeName) as protobuf.Type; - for (const field of fields.slice(0, -1)) { - type = type?.fields[field]?.resolvedType as protobuf.Type; - } - return type?.fields[fields[fields.length - 1]]?.defaultValue ?? null; + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type?.fields[field]?.resolvedType as protobuf.Type; + } + return type?.fields[fields[fields.length - 1]]?.defaultValue ?? null; } function generateSampleMessage(instance: T) { - const filledObject = (instance.constructor as typeof protobuf.Message) - .toObject(instance as protobuf.Message, {defaults: true}); - return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, { defaults: true }); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; } function stubSimpleCall(response?: ResponseType, error?: Error) { - return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); } -function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { - return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +function stubSimpleCallWithCallback( + response?: ResponseType, + error?: Error, +) { + return error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); } -function stubServerStreamingCall(response?: ResponseType, error?: Error) { - const transformStub = error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); - const mockStream = new PassThrough({ - objectMode: true, - transform: transformStub, - }); - // write something to the stream to trigger transformStub and send the response back to the client - setImmediate(() => { mockStream.write({}); }); - setImmediate(() => { mockStream.end(); }); - return sinon.stub().returns(mockStream); +function stubServerStreamingCall( + response?: ResponseType, + error?: Error, +) { + const transformStub = error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + // write something to the stream to trigger transformStub and send the response back to the client + setImmediate(() => { + mockStream.write({}); + }); + setImmediate(() => { + mockStream.end(); + }); + return sinon.stub().returns(mockStream); } -function stubBidiStreamingCall(response?: ResponseType, error?: Error) { - const transformStub = error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); - const mockStream = new PassThrough({ - objectMode: true, - transform: transformStub, - }); - return sinon.stub().returns(mockStream); +function stubBidiStreamingCall( + response?: ResponseType, + error?: Error, +) { + const transformStub = error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + return sinon.stub().returns(mockStream); } -function stubClientStreamingCall(response?: ResponseType, error?: Error) { - if (error) { - return sinon.stub().callsArgWith(2, error); - } - const transformStub = sinon.stub(); - const mockStream = new PassThrough({ - objectMode: true, - transform: transformStub, - }); - return sinon.stub().returns(mockStream).callsArgWith(2, null, response); +function stubClientStreamingCall( + response?: ResponseType, + error?: Error, +) { + if (error) { + return sinon.stub().callsArgWith(2, error); + } + const transformStub = sinon.stub(); + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + return sinon.stub().returns(mockStream).callsArgWith(2, null, response); } -function stubLongRunningCall(response?: ResponseType, callError?: Error, lroError?: Error) { - const innerStub = lroError ? sinon.stub().rejects(lroError) : sinon.stub().resolves([response]); - const mockOperation = { - promise: innerStub, - }; - return callError ? sinon.stub().rejects(callError) : sinon.stub().resolves([mockOperation]); +function stubLongRunningCall( + response?: ResponseType, + callError?: Error, + lroError?: Error, +) { + const innerStub = lroError + ? sinon.stub().rejects(lroError) + : sinon.stub().resolves([response]); + const mockOperation = { + promise: innerStub, + }; + return callError + ? sinon.stub().rejects(callError) + : sinon.stub().resolves([mockOperation]); } -function stubLongRunningCallWithCallback(response?: ResponseType, callError?: Error, lroError?: Error) { - const innerStub = lroError ? sinon.stub().rejects(lroError) : sinon.stub().resolves([response]); - const mockOperation = { - promise: innerStub, - }; - return callError ? sinon.stub().callsArgWith(2, callError) : sinon.stub().callsArgWith(2, null, mockOperation); +function stubLongRunningCallWithCallback( + response?: ResponseType, + callError?: Error, + lroError?: Error, +) { + const innerStub = lroError + ? sinon.stub().rejects(lroError) + : sinon.stub().resolves([response]); + const mockOperation = { + promise: innerStub, + }; + return callError + ? sinon.stub().callsArgWith(2, callError) + : sinon.stub().callsArgWith(2, null, mockOperation); } -function stubPageStreamingCall(responses?: ResponseType[], error?: Error) { - const pagingStub = sinon.stub(); - if (responses) { - for (let i = 0; i < responses.length; ++i) { - pagingStub.onCall(i).callsArgWith(2, null, responses[i]); - } +function stubPageStreamingCall( + responses?: ResponseType[], + error?: Error, +) { + const pagingStub = sinon.stub(); + if (responses) { + for (let i = 0; i < responses.length; ++i) { + pagingStub.onCall(i).callsArgWith(2, null, responses[i]); } - const transformStub = error ? sinon.stub().callsArgWith(2, error) : pagingStub; - const mockStream = new PassThrough({ - objectMode: true, - transform: transformStub, - }); - // trigger as many responses as needed - if (responses) { - for (let i = 0; i < responses.length; ++i) { - setImmediate(() => { mockStream.write({}); }); - } - setImmediate(() => { mockStream.end(); }); - } else { - setImmediate(() => { mockStream.write({}); }); - setImmediate(() => { mockStream.end(); }); + } + const transformStub = error + ? sinon.stub().callsArgWith(2, error) + : pagingStub; + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + // trigger as many responses as needed + if (responses) { + for (let i = 0; i < responses.length; ++i) { + setImmediate(() => { + mockStream.write({}); + }); } - return sinon.stub().returns(mockStream); + setImmediate(() => { + mockStream.end(); + }); + } else { + setImmediate(() => { + mockStream.write({}); + }); + setImmediate(() => { + mockStream.end(); + }); + } + return sinon.stub().returns(mockStream); } -function stubAsyncIterationCall(responses?: ResponseType[], error?: Error) { - let counter = 0; - const asyncIterable = { - [Symbol.asyncIterator]() { - return { - async next() { - if (error) { - return Promise.reject(error); - } - if (counter >= responses!.length) { - return Promise.resolve({done: true, value: undefined}); - } - return Promise.resolve({done: false, value: responses![counter++]}); - } - }; - } - }; - return sinon.stub().returns(asyncIterable); +function stubAsyncIterationCall( + responses?: ResponseType[], + error?: Error, +) { + let counter = 0; + const asyncIterable = { + [Symbol.asyncIterator]() { + return { + async next() { + if (error) { + return Promise.reject(error); + } + if (counter >= responses!.length) { + return Promise.resolve({ done: true, value: undefined }); + } + return Promise.resolve({ done: false, value: responses![counter++] }); + }, + }; + }, + }; + return sinon.stub().returns(asyncIterable); } describe('v1beta1.MessagingClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new messagingModule.v1beta1.MessagingClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'localhost'); - }); - - it('has universeDomain', () => { - const client = new messagingModule.v1beta1.MessagingClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); - - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - it('throws DeprecationWarning if static servicePath is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const servicePath = messagingModule.v1beta1.MessagingClient.servicePath; - assert.strictEqual(servicePath, 'localhost'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = messagingModule.v1beta1.MessagingClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'localhost'); - assert(stub.called); - stub.restore(); - }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { new messagingModule.v1beta1.MessagingClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); - - it('has port', () => { - const port = messagingModule.v1beta1.MessagingClient.port; - assert(port); - assert(typeof port === 'number'); - }); - - it('should create a client with no option', () => { - const client = new messagingModule.v1beta1.MessagingClient(); - assert(client); - }); - - it('should create a client with gRPC fallback', () => { - const client = new messagingModule.v1beta1.MessagingClient({ - fallback: true, - }); - assert(client); - }); - - it('has initialize method and supports deferred initialization', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.messagingStub, undefined); - await client.initialize(); - assert(client.messagingStub); - }); - - it('has close method for the initialized client', done => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.messagingStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); - - it('has close method for the non-initialized client', done => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.messagingStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); - - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); - }); - - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId((err?: Error|null, projectId?: string|null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } - }); - }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new messagingModule.v1beta1.MessagingClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'localhost'); }); - describe('createRoom', () => { - it('invokes createRoom without error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.CreateRoomRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.Room() - ); - client.innerApiCalls.createRoom = stubSimpleCall(expectedResponse); - const [response] = await client.createRoom(request); - assert.deepStrictEqual(response, expectedResponse); - }); - - it('invokes createRoom without error using callback', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.CreateRoomRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.Room() - ); - client.innerApiCalls.createRoom = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createRoom( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IRoom|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); + it('has universeDomain', () => { + const client = new messagingModule.v1beta1.MessagingClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - it('invokes createRoom with error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.CreateRoomRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.createRoom = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createRoom(request), expectedError); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = messagingModule.v1beta1.MessagingClient.servicePath; + assert.strictEqual(servicePath, 'localhost'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = messagingModule.v1beta1.MessagingClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'localhost'); + assert(stub.called); + stub.restore(); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new messagingModule.v1beta1.MessagingClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); + }); - it('invokes createRoom with closed client', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.CreateRoomRequest() - ); - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createRoom(request), expectedError); - }); + it('has port', () => { + const port = messagingModule.v1beta1.MessagingClient.port; + assert(port); + assert(typeof port === 'number'); }); - describe('getRoom', () => { - it('invokes getRoom without error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.GetRoomRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.GetRoomRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.Room() - ); - client.innerApiCalls.getRoom = stubSimpleCall(expectedResponse); - const [response] = await client.getRoom(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getRoom as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getRoom as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('should create a client with no option', () => { + const client = new messagingModule.v1beta1.MessagingClient(); + assert(client); + }); - it('invokes getRoom without error using callback', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.GetRoomRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.GetRoomRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.Room() - ); - client.innerApiCalls.getRoom = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getRoom( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IRoom|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getRoom as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getRoom as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('should create a client with gRPC fallback', () => { + const client = new messagingModule.v1beta1.MessagingClient({ + fallback: true, + }); + assert(client); + }); - it('invokes getRoom with error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.GetRoomRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.GetRoomRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getRoom = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getRoom(request), expectedError); - const actualRequest = (client.innerApiCalls.getRoom as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getRoom as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has initialize method and supports deferred initialization', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.messagingStub, undefined); + await client.initialize(); + assert(client.messagingStub); + }); - it('invokes getRoom with closed client', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.GetRoomRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.GetRoomRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getRoom(request), expectedError); + it('has close method for the initialized client', (done) => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.messagingStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); }); - describe('updateRoom', () => { - it('invokes updateRoom without error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.UpdateRoomRequest() - ); - request.room ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.UpdateRoomRequest', ['room', 'name']); - request.room.name = defaultValue1; - const expectedHeaderRequestParams = `room.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.Room() - ); - client.innerApiCalls.updateRoom = stubSimpleCall(expectedResponse); - const [response] = await client.updateRoom(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateRoom as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateRoom as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('has close method for the non-initialized client', (done) => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.messagingStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes updateRoom without error using callback', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.UpdateRoomRequest() - ); - request.room ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.UpdateRoomRequest', ['room', 'name']); - request.room.name = defaultValue1; - const expectedHeaderRequestParams = `room.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.Room() - ); - client.innerApiCalls.updateRoom = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateRoom( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IRoom|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateRoom as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateRoom as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + }); - it('invokes updateRoom with error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.UpdateRoomRequest() - ); - request.room ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.UpdateRoomRequest', ['room', 'name']); - request.room.name = defaultValue1; - const expectedHeaderRequestParams = `room.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateRoom = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateRoom(request), expectedError); - const actualRequest = (client.innerApiCalls.updateRoom as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateRoom as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } + }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + }); + + describe('createRoom', () => { + it('invokes createRoom without error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.CreateRoomRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.Room(), + ); + client.innerApiCalls.createRoom = stubSimpleCall(expectedResponse); + const [response] = await client.createRoom(request); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes updateRoom with closed client', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.UpdateRoomRequest() - ); - request.room ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.UpdateRoomRequest', ['room', 'name']); - request.room.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateRoom(request), expectedError); - }); + it('invokes createRoom without error using callback', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.CreateRoomRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.Room(), + ); + client.innerApiCalls.createRoom = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createRoom( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IRoom | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); }); - describe('deleteRoom', () => { - it('invokes deleteRoom without error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.DeleteRoomRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.DeleteRoomRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteRoom = stubSimpleCall(expectedResponse); - const [response] = await client.deleteRoom(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteRoom as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteRoom as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createRoom with error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.CreateRoomRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.createRoom = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.createRoom(request), expectedError); + }); - it('invokes deleteRoom without error using callback', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.DeleteRoomRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.DeleteRoomRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteRoom = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteRoom( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteRoom as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteRoom as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createRoom with closed client', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.CreateRoomRequest(), + ); + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.createRoom(request), expectedError); + }); + }); + + describe('getRoom', () => { + it('invokes getRoom without error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.GetRoomRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.GetRoomRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.Room(), + ); + client.innerApiCalls.getRoom = stubSimpleCall(expectedResponse); + const [response] = await client.getRoom(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.getRoom as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getRoom as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteRoom with error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.DeleteRoomRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.DeleteRoomRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteRoom = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteRoom(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteRoom as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteRoom as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getRoom without error using callback', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.GetRoomRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.GetRoomRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.Room(), + ); + client.innerApiCalls.getRoom = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getRoom( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IRoom | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.getRoom as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getRoom as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteRoom with closed client', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.DeleteRoomRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.DeleteRoomRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteRoom(request), expectedError); - }); + it('invokes getRoom with error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.GetRoomRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.GetRoomRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getRoom = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.getRoom(request), expectedError); + const actualRequest = (client.innerApiCalls.getRoom as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getRoom as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('createBlurb', () => { - it('invokes createBlurb without error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.CreateBlurbRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.CreateBlurbRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.Blurb() - ); - client.innerApiCalls.createBlurb = stubSimpleCall(expectedResponse); - const [response] = await client.createBlurb(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createBlurb as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createBlurb as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getRoom with closed client', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.GetRoomRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.GetRoomRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getRoom(request), expectedError); + }); + }); + + describe('updateRoom', () => { + it('invokes updateRoom without error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.UpdateRoomRequest(), + ); + request.room ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.UpdateRoomRequest', + ['room', 'name'], + ); + request.room.name = defaultValue1; + const expectedHeaderRequestParams = `room.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.Room(), + ); + client.innerApiCalls.updateRoom = stubSimpleCall(expectedResponse); + const [response] = await client.updateRoom(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateRoom as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateRoom as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createBlurb without error using callback', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.CreateBlurbRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.CreateBlurbRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.Blurb() - ); - client.innerApiCalls.createBlurb = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createBlurb( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IBlurb|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createBlurb as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createBlurb as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateRoom without error using callback', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.UpdateRoomRequest(), + ); + request.room ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.UpdateRoomRequest', + ['room', 'name'], + ); + request.room.name = defaultValue1; + const expectedHeaderRequestParams = `room.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.Room(), + ); + client.innerApiCalls.updateRoom = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateRoom( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IRoom | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateRoom as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateRoom as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createBlurb with error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.CreateBlurbRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.CreateBlurbRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createBlurb = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createBlurb(request), expectedError); - const actualRequest = (client.innerApiCalls.createBlurb as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createBlurb as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateRoom with error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.UpdateRoomRequest(), + ); + request.room ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.UpdateRoomRequest', + ['room', 'name'], + ); + request.room.name = defaultValue1; + const expectedHeaderRequestParams = `room.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateRoom = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.updateRoom(request), expectedError); + const actualRequest = ( + client.innerApiCalls.updateRoom as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateRoom as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createBlurb with closed client', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.CreateBlurbRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.CreateBlurbRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createBlurb(request), expectedError); - }); + it('invokes updateRoom with closed client', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.UpdateRoomRequest(), + ); + request.room ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.UpdateRoomRequest', + ['room', 'name'], + ); + request.room.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.updateRoom(request), expectedError); + }); + }); + + describe('deleteRoom', () => { + it('invokes deleteRoom without error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.DeleteRoomRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.DeleteRoomRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteRoom = stubSimpleCall(expectedResponse); + const [response] = await client.deleteRoom(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteRoom as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteRoom as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('getBlurb', () => { - it('invokes getBlurb without error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.GetBlurbRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.GetBlurbRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.Blurb() - ); - client.innerApiCalls.getBlurb = stubSimpleCall(expectedResponse); - const [response] = await client.getBlurb(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getBlurb as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getBlurb as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteRoom without error using callback', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.DeleteRoomRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.DeleteRoomRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteRoom = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteRoom( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteRoom as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteRoom as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getBlurb without error using callback', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.GetBlurbRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.GetBlurbRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.Blurb() - ); - client.innerApiCalls.getBlurb = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getBlurb( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IBlurb|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getBlurb as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getBlurb as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteRoom with error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.DeleteRoomRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.DeleteRoomRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteRoom = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.deleteRoom(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteRoom as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteRoom as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getBlurb with error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.GetBlurbRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.GetBlurbRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getBlurb = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getBlurb(request), expectedError); - const actualRequest = (client.innerApiCalls.getBlurb as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getBlurb as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteRoom with closed client', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.DeleteRoomRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.DeleteRoomRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.deleteRoom(request), expectedError); + }); + }); + + describe('createBlurb', () => { + it('invokes createBlurb without error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.CreateBlurbRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.CreateBlurbRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.Blurb(), + ); + client.innerApiCalls.createBlurb = stubSimpleCall(expectedResponse); + const [response] = await client.createBlurb(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createBlurb as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createBlurb as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getBlurb with closed client', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.GetBlurbRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.GetBlurbRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getBlurb(request), expectedError); - }); + it('invokes createBlurb without error using callback', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.CreateBlurbRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.CreateBlurbRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.Blurb(), + ); + client.innerApiCalls.createBlurb = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createBlurb( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IBlurb | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createBlurb as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createBlurb as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('updateBlurb', () => { - it('invokes updateBlurb without error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.UpdateBlurbRequest() - ); - request.blurb ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.UpdateBlurbRequest', ['blurb', 'name']); - request.blurb.name = defaultValue1; - const expectedHeaderRequestParams = `blurb.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.Blurb() - ); - client.innerApiCalls.updateBlurb = stubSimpleCall(expectedResponse); - const [response] = await client.updateBlurb(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateBlurb as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateBlurb as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createBlurb with error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.CreateBlurbRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.CreateBlurbRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createBlurb = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.createBlurb(request), expectedError); + const actualRequest = ( + client.innerApiCalls.createBlurb as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createBlurb as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateBlurb without error using callback', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.UpdateBlurbRequest() - ); - request.blurb ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.UpdateBlurbRequest', ['blurb', 'name']); - request.blurb.name = defaultValue1; - const expectedHeaderRequestParams = `blurb.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.Blurb() - ); - client.innerApiCalls.updateBlurb = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateBlurb( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IBlurb|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateBlurb as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateBlurb as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createBlurb with closed client', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.CreateBlurbRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.CreateBlurbRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.createBlurb(request), expectedError); + }); + }); + + describe('getBlurb', () => { + it('invokes getBlurb without error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.GetBlurbRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.GetBlurbRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.Blurb(), + ); + client.innerApiCalls.getBlurb = stubSimpleCall(expectedResponse); + const [response] = await client.getBlurb(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getBlurb as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getBlurb as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateBlurb with error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.UpdateBlurbRequest() - ); - request.blurb ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.UpdateBlurbRequest', ['blurb', 'name']); - request.blurb.name = defaultValue1; - const expectedHeaderRequestParams = `blurb.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateBlurb = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateBlurb(request), expectedError); - const actualRequest = (client.innerApiCalls.updateBlurb as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateBlurb as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getBlurb without error using callback', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.GetBlurbRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.GetBlurbRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.Blurb(), + ); + client.innerApiCalls.getBlurb = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getBlurb( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IBlurb | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getBlurb as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getBlurb as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateBlurb with closed client', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.UpdateBlurbRequest() - ); - request.blurb ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.UpdateBlurbRequest', ['blurb', 'name']); - request.blurb.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateBlurb(request), expectedError); - }); + it('invokes getBlurb with error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.GetBlurbRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.GetBlurbRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getBlurb = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.getBlurb(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getBlurb as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getBlurb as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('deleteBlurb', () => { - it('invokes deleteBlurb without error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.DeleteBlurbRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.DeleteBlurbRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteBlurb = stubSimpleCall(expectedResponse); - const [response] = await client.deleteBlurb(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteBlurb as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteBlurb as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getBlurb with closed client', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.GetBlurbRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.GetBlurbRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getBlurb(request), expectedError); + }); + }); + + describe('updateBlurb', () => { + it('invokes updateBlurb without error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.UpdateBlurbRequest(), + ); + request.blurb ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.UpdateBlurbRequest', + ['blurb', 'name'], + ); + request.blurb.name = defaultValue1; + const expectedHeaderRequestParams = `blurb.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.Blurb(), + ); + client.innerApiCalls.updateBlurb = stubSimpleCall(expectedResponse); + const [response] = await client.updateBlurb(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateBlurb as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateBlurb as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteBlurb without error using callback', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.DeleteBlurbRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.DeleteBlurbRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteBlurb = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteBlurb( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteBlurb as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteBlurb as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateBlurb without error using callback', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.UpdateBlurbRequest(), + ); + request.blurb ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.UpdateBlurbRequest', + ['blurb', 'name'], + ); + request.blurb.name = defaultValue1; + const expectedHeaderRequestParams = `blurb.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.Blurb(), + ); + client.innerApiCalls.updateBlurb = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateBlurb( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IBlurb | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateBlurb as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateBlurb as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteBlurb with error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.DeleteBlurbRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.DeleteBlurbRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteBlurb = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteBlurb(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteBlurb as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteBlurb as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateBlurb with error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.UpdateBlurbRequest(), + ); + request.blurb ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.UpdateBlurbRequest', + ['blurb', 'name'], + ); + request.blurb.name = defaultValue1; + const expectedHeaderRequestParams = `blurb.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateBlurb = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.updateBlurb(request), expectedError); + const actualRequest = ( + client.innerApiCalls.updateBlurb as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateBlurb as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteBlurb with closed client', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.DeleteBlurbRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.DeleteBlurbRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteBlurb(request), expectedError); - }); + it('invokes updateBlurb with closed client', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.UpdateBlurbRequest(), + ); + request.blurb ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.UpdateBlurbRequest', + ['blurb', 'name'], + ); + request.blurb.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.updateBlurb(request), expectedError); + }); + }); + + describe('deleteBlurb', () => { + it('invokes deleteBlurb without error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.DeleteBlurbRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.DeleteBlurbRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteBlurb = stubSimpleCall(expectedResponse); + const [response] = await client.deleteBlurb(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteBlurb as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteBlurb as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('searchBlurbs', () => { - it('invokes searchBlurbs without error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.SearchBlurbsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.SearchBlurbsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.searchBlurbs = stubLongRunningCall(expectedResponse); - const [operation] = await client.searchBlurbs(request); - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.searchBlurbs as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.searchBlurbs as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteBlurb without error using callback', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.DeleteBlurbRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.DeleteBlurbRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteBlurb = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteBlurb( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteBlurb as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteBlurb as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes searchBlurbs without error using callback', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.SearchBlurbsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.SearchBlurbsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.searchBlurbs = stubLongRunningCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.searchBlurbs( - request, - (err?: Error|null, - result?: LROperation|null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const operation = await promise as LROperation; - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.searchBlurbs as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.searchBlurbs as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteBlurb with error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.DeleteBlurbRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.DeleteBlurbRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteBlurb = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.deleteBlurb(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteBlurb as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteBlurb as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes searchBlurbs with call error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.SearchBlurbsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.SearchBlurbsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.searchBlurbs = stubLongRunningCall(undefined, expectedError); - await assert.rejects(client.searchBlurbs(request), expectedError); - const actualRequest = (client.innerApiCalls.searchBlurbs as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.searchBlurbs as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteBlurb with closed client', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.DeleteBlurbRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.DeleteBlurbRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.deleteBlurb(request), expectedError); + }); + }); + + describe('searchBlurbs', () => { + it('invokes searchBlurbs without error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.SearchBlurbsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.SearchBlurbsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.searchBlurbs = stubLongRunningCall(expectedResponse); + const [operation] = await client.searchBlurbs(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.searchBlurbs as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.searchBlurbs as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes searchBlurbs with LRO error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.SearchBlurbsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.SearchBlurbsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.searchBlurbs = stubLongRunningCall(undefined, undefined, expectedError); - const [operation] = await client.searchBlurbs(request); - await assert.rejects(operation.promise(), expectedError); - const actualRequest = (client.innerApiCalls.searchBlurbs as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.searchBlurbs as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes searchBlurbs without error using callback', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.SearchBlurbsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.SearchBlurbsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.searchBlurbs = + stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.searchBlurbs( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.showcase.v1beta1.ISearchBlurbsResponse, + protos.google.showcase.v1beta1.ISearchBlurbsMetadata + > | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const operation = (await promise) as LROperation< + protos.google.showcase.v1beta1.ISearchBlurbsResponse, + protos.google.showcase.v1beta1.ISearchBlurbsMetadata + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.searchBlurbs as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.searchBlurbs as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkSearchBlurbsProgress without error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedResponse = generateSampleMessage( - new operationsProtos.google.longrunning.Operation() - ); - expectedResponse.name = 'test'; - expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; - expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')} - - client.operationsClient.getOperation = stubSimpleCall(expectedResponse); - const decodedOperation = await client.checkSearchBlurbsProgress(expectedResponse.name); - assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); - assert(decodedOperation.metadata); - assert((client.operationsClient.getOperation as SinonStub).getCall(0)); - }); + it('invokes searchBlurbs with call error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.SearchBlurbsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.SearchBlurbsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.searchBlurbs = stubLongRunningCall( + undefined, + expectedError, + ); + await assert.rejects(client.searchBlurbs(request), expectedError); + const actualRequest = ( + client.innerApiCalls.searchBlurbs as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.searchBlurbs as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkSearchBlurbsProgress with error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedError = new Error('expected'); - - client.operationsClient.getOperation = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.checkSearchBlurbsProgress(''), expectedError); - assert((client.operationsClient.getOperation as SinonStub) - .getCall(0)); - }); + it('invokes searchBlurbs with LRO error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.SearchBlurbsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.SearchBlurbsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.searchBlurbs = stubLongRunningCall( + undefined, + undefined, + expectedError, + ); + const [operation] = await client.searchBlurbs(request); + await assert.rejects(operation.promise(), expectedError); + const actualRequest = ( + client.innerApiCalls.searchBlurbs as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.searchBlurbs as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('streamBlurbs', () => { - it('invokes streamBlurbs without error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.StreamBlurbsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.StreamBlurbsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.StreamBlurbsResponse() - ); - client.innerApiCalls.streamBlurbs = stubServerStreamingCall(expectedResponse); - const stream = client.streamBlurbs(request); - const promise = new Promise((resolve, reject) => { - stream.on('data', (response: protos.google.showcase.v1beta1.StreamBlurbsResponse) => { - resolve(response); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.streamBlurbs as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.streamBlurbs as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes checkSearchBlurbsProgress without error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation(), + ); + expectedResponse.name = 'test'; + expectedResponse.response = { type_url: 'url', value: Buffer.from('') }; + expectedResponse.metadata = { type_url: 'url', value: Buffer.from('') }; + + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const decodedOperation = await client.checkSearchBlurbsProgress( + expectedResponse.name, + ); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); - it('invokes streamBlurbs without error and gaxServerStreamingRetries enabled', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.StreamBlurbsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.StreamBlurbsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.StreamBlurbsResponse() - ); - client.innerApiCalls.streamBlurbs = stubServerStreamingCall(expectedResponse); - const stream = client.streamBlurbs(request); - const promise = new Promise((resolve, reject) => { - stream.on('data', (response: protos.google.showcase.v1beta1.StreamBlurbsResponse) => { - resolve(response); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.streamBlurbs as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.streamBlurbs as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes checkSearchBlurbsProgress with error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const expectedError = new Error('expected'); + + client.operationsClient.getOperation = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.checkSearchBlurbsProgress(''), expectedError); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + }); + + describe('streamBlurbs', () => { + it('invokes streamBlurbs without error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.StreamBlurbsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.StreamBlurbsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.StreamBlurbsResponse(), + ); + client.innerApiCalls.streamBlurbs = + stubServerStreamingCall(expectedResponse); + const stream = client.streamBlurbs(request); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + (response: protos.google.showcase.v1beta1.StreamBlurbsResponse) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.streamBlurbs as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.streamBlurbs as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes streamBlurbs with error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.StreamBlurbsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.StreamBlurbsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.streamBlurbs = stubServerStreamingCall(undefined, expectedError); - const stream = client.streamBlurbs(request); - const promise = new Promise((resolve, reject) => { - stream.on('data', (response: protos.google.showcase.v1beta1.StreamBlurbsResponse) => { - resolve(response); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - const actualRequest = (client.innerApiCalls.streamBlurbs as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.streamBlurbs as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes streamBlurbs without error and gaxServerStreamingRetries enabled', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.StreamBlurbsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.StreamBlurbsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.StreamBlurbsResponse(), + ); + client.innerApiCalls.streamBlurbs = + stubServerStreamingCall(expectedResponse); + const stream = client.streamBlurbs(request); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + (response: protos.google.showcase.v1beta1.StreamBlurbsResponse) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.streamBlurbs as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.streamBlurbs as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes streamBlurbs with closed client', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.StreamBlurbsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.StreamBlurbsRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - const stream = client.streamBlurbs(request, {retryRequestOptions: {noResponseRetries: 0}}); - const promise = new Promise((resolve, reject) => { - stream.on('data', (response: protos.google.showcase.v1beta1.StreamBlurbsResponse) => { - resolve(response); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - }); - it('should create a client with gaxServerStreamingRetries enabled', () => { - const client = new messagingModule.v1beta1.MessagingClient({ - gaxServerStreamingRetries: true, - }); - assert(client); - }); + it('invokes streamBlurbs with error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.StreamBlurbsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.StreamBlurbsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.streamBlurbs = stubServerStreamingCall( + undefined, + expectedError, + ); + const stream = client.streamBlurbs(request); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + (response: protos.google.showcase.v1beta1.StreamBlurbsResponse) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + const actualRequest = ( + client.innerApiCalls.streamBlurbs as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.streamBlurbs as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('connect', () => { - it('invokes connect without error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ConnectRequest() - ); - - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.StreamBlurbsResponse() - ); - client.innerApiCalls.connect = stubBidiStreamingCall(expectedResponse); - const stream = client.connect(); - const promise = new Promise((resolve, reject) => { - stream.on('data', (response: protos.google.showcase.v1beta1.StreamBlurbsResponse) => { - resolve(response); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - stream.write(request); - stream.end(); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - assert((client.innerApiCalls.connect as SinonStub) - .getCall(0).calledWith(null)); - assert.deepStrictEqual(((stream as unknown as PassThrough) - ._transform as SinonStub).getCall(0).args[0], request); - }); + it('invokes streamBlurbs with closed client', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.StreamBlurbsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.StreamBlurbsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + const stream = client.streamBlurbs(request, { + retryRequestOptions: { noResponseRetries: 0 }, + }); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + (response: protos.google.showcase.v1beta1.StreamBlurbsResponse) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + }); + it('should create a client with gaxServerStreamingRetries enabled', () => { + const client = new messagingModule.v1beta1.MessagingClient({ + gaxServerStreamingRetries: true, + }); + assert(client); + }); + }); + + describe('connect', () => { + it('invokes connect without error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ConnectRequest(), + ); + + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.StreamBlurbsResponse(), + ); + client.innerApiCalls.connect = stubBidiStreamingCall(expectedResponse); + const stream = client.connect(); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + (response: protos.google.showcase.v1beta1.StreamBlurbsResponse) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); + }); + stream.write(request); + stream.end(); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + assert( + (client.innerApiCalls.connect as SinonStub).getCall(0).calledWith(null), + ); + assert.deepStrictEqual( + ((stream as unknown as PassThrough)._transform as SinonStub).getCall(0) + .args[0], + request, + ); + }); - it('invokes connect with error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ConnectRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.connect = stubBidiStreamingCall(undefined, expectedError); - const stream = client.connect(); - const promise = new Promise((resolve, reject) => { - stream.on('data', (response: protos.google.showcase.v1beta1.StreamBlurbsResponse) => { - resolve(response); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - stream.write(request); - stream.end(); - }); - await assert.rejects(promise, expectedError); - assert((client.innerApiCalls.connect as SinonStub) - .getCall(0).calledWith(null)); - assert.deepStrictEqual(((stream as unknown as PassThrough) - ._transform as SinonStub).getCall(0).args[0], request); - }); + it('invokes connect with error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ConnectRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.connect = stubBidiStreamingCall( + undefined, + expectedError, + ); + const stream = client.connect(); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + (response: protos.google.showcase.v1beta1.StreamBlurbsResponse) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); + }); + stream.write(request); + stream.end(); + }); + await assert.rejects(promise, expectedError); + assert( + (client.innerApiCalls.connect as SinonStub).getCall(0).calledWith(null), + ); + assert.deepStrictEqual( + ((stream as unknown as PassThrough)._transform as SinonStub).getCall(0) + .args[0], + request, + ); + }); + }); + + describe('sendBlurbs', () => { + it('invokes sendBlurbs without error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.CreateBlurbRequest(), + ); + + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.SendBlurbsResponse(), + ); + client.innerApiCalls.sendBlurbs = + stubClientStreamingCall(expectedResponse); + let stream: PassThrough; + const promise = new Promise((resolve, reject) => { + stream = client.sendBlurbs( + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.ISendBlurbsResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ) as unknown as PassThrough; + stream.write(request); + stream.end(); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + assert( + (client.innerApiCalls.sendBlurbs as SinonStub) + .getCall(0) + .calledWith(null, {} /*, callback defined above */), + ); + assert.deepStrictEqual( + (stream!._transform as SinonStub).getCall(0).args[0], + request, + ); }); - describe('sendBlurbs', () => { - it('invokes sendBlurbs without error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.CreateBlurbRequest() - ); - - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.SendBlurbsResponse() - ); - client.innerApiCalls.sendBlurbs = stubClientStreamingCall(expectedResponse); - let stream: PassThrough; - const promise = new Promise((resolve, reject) => { - stream = client.sendBlurbs( - (err?: Error|null, result?: protos.google.showcase.v1beta1.ISendBlurbsResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }) as unknown as PassThrough; - stream.write(request); - stream.end(); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - assert((client.innerApiCalls.sendBlurbs as SinonStub) - .getCall(0).calledWith(null, {} /*, callback defined above */)); - assert.deepStrictEqual((stream!._transform as SinonStub).getCall(0).args[0], request); - }); + it('invokes sendBlurbs with error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.CreateBlurbRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.sendBlurbs = stubClientStreamingCall( + undefined, + expectedError, + ); + let stream: PassThrough; + const promise = new Promise((resolve, reject) => { + stream = client.sendBlurbs( + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.ISendBlurbsResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ) as unknown as PassThrough; + stream.write(request); + stream.end(); + }); + await assert.rejects(promise, expectedError); + assert( + (client.innerApiCalls.sendBlurbs as SinonStub) + .getCall(0) + .calledWith(null, {} /*, callback defined above */), + ); + }); + }); + + describe('listRooms', () => { + it('invokes listRooms without error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListRoomsRequest(), + ); + const expectedResponse = [ + generateSampleMessage(new protos.google.showcase.v1beta1.Room()), + generateSampleMessage(new protos.google.showcase.v1beta1.Room()), + generateSampleMessage(new protos.google.showcase.v1beta1.Room()), + ]; + client.innerApiCalls.listRooms = stubSimpleCall(expectedResponse); + const [response] = await client.listRooms(request); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes sendBlurbs with error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.CreateBlurbRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.sendBlurbs = stubClientStreamingCall(undefined, expectedError); - let stream: PassThrough; - const promise = new Promise((resolve, reject) => { - stream = client.sendBlurbs( - (err?: Error|null, result?: protos.google.showcase.v1beta1.ISendBlurbsResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }) as unknown as PassThrough; - stream.write(request); - stream.end(); - }); - await assert.rejects(promise, expectedError); - assert((client.innerApiCalls.sendBlurbs as SinonStub) - .getCall(0).calledWith(null, {} /*, callback defined above */)); - }); + it('invokes listRooms without error using callback', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListRoomsRequest(), + ); + const expectedResponse = [ + generateSampleMessage(new protos.google.showcase.v1beta1.Room()), + generateSampleMessage(new protos.google.showcase.v1beta1.Room()), + generateSampleMessage(new protos.google.showcase.v1beta1.Room()), + ]; + client.innerApiCalls.listRooms = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listRooms( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IRoom[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); }); - describe('listRooms', () => { - it('invokes listRooms without error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListRoomsRequest() - );const expectedResponse = [ - generateSampleMessage(new protos.google.showcase.v1beta1.Room()), - generateSampleMessage(new protos.google.showcase.v1beta1.Room()), - generateSampleMessage(new protos.google.showcase.v1beta1.Room()), - ]; - client.innerApiCalls.listRooms = stubSimpleCall(expectedResponse); - const [response] = await client.listRooms(request); - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes listRooms with error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListRoomsRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.listRooms = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.listRooms(request), expectedError); + }); - it('invokes listRooms without error using callback', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListRoomsRequest() - );const expectedResponse = [ - generateSampleMessage(new protos.google.showcase.v1beta1.Room()), - generateSampleMessage(new protos.google.showcase.v1beta1.Room()), - generateSampleMessage(new protos.google.showcase.v1beta1.Room()), - ]; - client.innerApiCalls.listRooms = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listRooms( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IRoom[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes listRoomsStream without error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListRoomsRequest(), + ); + const expectedResponse = [ + generateSampleMessage(new protos.google.showcase.v1beta1.Room()), + generateSampleMessage(new protos.google.showcase.v1beta1.Room()), + generateSampleMessage(new protos.google.showcase.v1beta1.Room()), + ]; + client.descriptors.page.listRooms.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listRoomsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.showcase.v1beta1.Room[] = []; + stream.on('data', (response: protos.google.showcase.v1beta1.Room) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listRooms.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listRooms, request), + ); + }); - it('invokes listRooms with error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListRoomsRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.listRooms = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listRooms(request), expectedError); - }); + it('invokes listRoomsStream with error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListRoomsRequest(), + ); + const expectedError = new Error('expected'); + client.descriptors.page.listRooms.createStream = stubPageStreamingCall( + undefined, + expectedError, + ); + const stream = client.listRoomsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.showcase.v1beta1.Room[] = []; + stream.on('data', (response: protos.google.showcase.v1beta1.Room) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listRooms.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listRooms, request), + ); + }); - it('invokes listRoomsStream without error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListRoomsRequest() - ); - const expectedResponse = [ - generateSampleMessage(new protos.google.showcase.v1beta1.Room()), - generateSampleMessage(new protos.google.showcase.v1beta1.Room()), - generateSampleMessage(new protos.google.showcase.v1beta1.Room()), - ]; - client.descriptors.page.listRooms.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listRoomsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.showcase.v1beta1.Room[] = []; - stream.on('data', (response: protos.google.showcase.v1beta1.Room) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.listRooms.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listRooms, request)); - }); + it('uses async iteration with listRooms without error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListRoomsRequest(), + ); + const expectedResponse = [ + generateSampleMessage(new protos.google.showcase.v1beta1.Room()), + generateSampleMessage(new protos.google.showcase.v1beta1.Room()), + generateSampleMessage(new protos.google.showcase.v1beta1.Room()), + ]; + client.descriptors.page.listRooms.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.showcase.v1beta1.IRoom[] = []; + const iterable = client.listRoomsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + (client.descriptors.page.listRooms.asyncIterate as SinonStub).getCall(0) + .args[1], + request, + ); + }); - it('invokes listRoomsStream with error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListRoomsRequest() - ); - const expectedError = new Error('expected'); - client.descriptors.page.listRooms.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listRoomsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.showcase.v1beta1.Room[] = []; - stream.on('data', (response: protos.google.showcase.v1beta1.Room) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listRooms.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listRooms, request)); - }); + it('uses async iteration with listRooms with error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListRoomsRequest(), + ); + const expectedError = new Error('expected'); + client.descriptors.page.listRooms.asyncIterate = stubAsyncIterationCall( + undefined, + expectedError, + ); + const iterable = client.listRoomsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.showcase.v1beta1.IRoom[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + (client.descriptors.page.listRooms.asyncIterate as SinonStub).getCall(0) + .args[1], + request, + ); + }); + }); + + describe('listBlurbs', () => { + it('invokes listBlurbs without error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListBlurbsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.ListBlurbsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.showcase.v1beta1.Blurb()), + generateSampleMessage(new protos.google.showcase.v1beta1.Blurb()), + generateSampleMessage(new protos.google.showcase.v1beta1.Blurb()), + ]; + client.innerApiCalls.listBlurbs = stubSimpleCall(expectedResponse); + const [response] = await client.listBlurbs(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listBlurbs as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listBlurbs as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('uses async iteration with listRooms without error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListRoomsRequest() - ); - const expectedResponse = [ - generateSampleMessage(new protos.google.showcase.v1beta1.Room()), - generateSampleMessage(new protos.google.showcase.v1beta1.Room()), - generateSampleMessage(new protos.google.showcase.v1beta1.Room()), - ]; - client.descriptors.page.listRooms.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.showcase.v1beta1.IRoom[] = []; - const iterable = client.listRoomsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); + it('invokes listBlurbs without error using callback', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListBlurbsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.ListBlurbsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.showcase.v1beta1.Blurb()), + generateSampleMessage(new protos.google.showcase.v1beta1.Blurb()), + generateSampleMessage(new protos.google.showcase.v1beta1.Blurb()), + ]; + client.innerApiCalls.listBlurbs = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listBlurbs( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IBlurb[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listRooms.asyncIterate as SinonStub) - .getCall(0).args[1], request); - }); - - it('uses async iteration with listRooms with error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListRoomsRequest() - ); - const expectedError = new Error('expected'); - client.descriptors.page.listRooms.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listRoomsAsync(request); - await assert.rejects(async () => { - const responses: protos.google.showcase.v1beta1.IRoom[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listRooms.asyncIterate as SinonStub) - .getCall(0).args[1], request); - }); + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listBlurbs as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listBlurbs as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('listBlurbs', () => { - it('invokes listBlurbs without error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListBlurbsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.ListBlurbsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.showcase.v1beta1.Blurb()), - generateSampleMessage(new protos.google.showcase.v1beta1.Blurb()), - generateSampleMessage(new protos.google.showcase.v1beta1.Blurb()), - ]; - client.innerApiCalls.listBlurbs = stubSimpleCall(expectedResponse); - const [response] = await client.listBlurbs(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listBlurbs as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listBlurbs as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listBlurbs without error using callback', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListBlurbsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.ListBlurbsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.showcase.v1beta1.Blurb()), - generateSampleMessage(new protos.google.showcase.v1beta1.Blurb()), - generateSampleMessage(new protos.google.showcase.v1beta1.Blurb()), - ]; - client.innerApiCalls.listBlurbs = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listBlurbs( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IBlurb[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listBlurbs as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listBlurbs as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listBlurbs with error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListBlurbsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.ListBlurbsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listBlurbs = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listBlurbs(request), expectedError); - const actualRequest = (client.innerApiCalls.listBlurbs as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listBlurbs as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listBlurbsStream without error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListBlurbsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.ListBlurbsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.showcase.v1beta1.Blurb()), - generateSampleMessage(new protos.google.showcase.v1beta1.Blurb()), - generateSampleMessage(new protos.google.showcase.v1beta1.Blurb()), - ]; - client.descriptors.page.listBlurbs.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listBlurbsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.showcase.v1beta1.Blurb[] = []; - stream.on('data', (response: protos.google.showcase.v1beta1.Blurb) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.listBlurbs.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listBlurbs, request)); - assert( - (client.descriptors.page.listBlurbs.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listBlurbs with error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListBlurbsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.ListBlurbsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listBlurbs = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listBlurbs(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listBlurbs as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listBlurbs as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listBlurbsStream with error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListBlurbsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.ListBlurbsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listBlurbs.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listBlurbsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.showcase.v1beta1.Blurb[] = []; - stream.on('data', (response: protos.google.showcase.v1beta1.Blurb) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listBlurbs.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listBlurbs, request)); - assert( - (client.descriptors.page.listBlurbs.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listBlurbsStream without error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListBlurbsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.ListBlurbsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.showcase.v1beta1.Blurb()), + generateSampleMessage(new protos.google.showcase.v1beta1.Blurb()), + generateSampleMessage(new protos.google.showcase.v1beta1.Blurb()), + ]; + client.descriptors.page.listBlurbs.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listBlurbsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.showcase.v1beta1.Blurb[] = []; + stream.on('data', (response: protos.google.showcase.v1beta1.Blurb) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listBlurbs.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listBlurbs, request), + ); + assert( + (client.descriptors.page.listBlurbs.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('uses async iteration with listBlurbs without error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListBlurbsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.ListBlurbsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.showcase.v1beta1.Blurb()), - generateSampleMessage(new protos.google.showcase.v1beta1.Blurb()), - generateSampleMessage(new protos.google.showcase.v1beta1.Blurb()), - ]; - client.descriptors.page.listBlurbs.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.showcase.v1beta1.IBlurb[] = []; - const iterable = client.listBlurbsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listBlurbs.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listBlurbs.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listBlurbsStream with error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListBlurbsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.ListBlurbsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listBlurbs.createStream = stubPageStreamingCall( + undefined, + expectedError, + ); + const stream = client.listBlurbsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.showcase.v1beta1.Blurb[] = []; + stream.on('data', (response: protos.google.showcase.v1beta1.Blurb) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listBlurbs.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listBlurbs, request), + ); + assert( + (client.descriptors.page.listBlurbs.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('uses async iteration with listBlurbs with error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListBlurbsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.ListBlurbsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listBlurbs.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listBlurbsAsync(request); - await assert.rejects(async () => { - const responses: protos.google.showcase.v1beta1.IBlurb[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listBlurbs.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listBlurbs.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listBlurbs without error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListBlurbsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.ListBlurbsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.showcase.v1beta1.Blurb()), + generateSampleMessage(new protos.google.showcase.v1beta1.Blurb()), + generateSampleMessage(new protos.google.showcase.v1beta1.Blurb()), + ]; + client.descriptors.page.listBlurbs.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.showcase.v1beta1.IBlurb[] = []; + const iterable = client.listBlurbsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + (client.descriptors.page.listBlurbs.asyncIterate as SinonStub).getCall( + 0, + ).args[1], + request, + ); + assert( + (client.descriptors.page.listBlurbs.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); }); - describe('Path templates', () => { - - describe('blueprint', () => { - const fakePath = "/rendered/path/blueprint"; - const expectedParameters = { - session: "sessionValue", - test: "testValue", - blueprint: "blueprintValue", - }; - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.blueprintPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.blueprintPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('blueprintPath', () => { - const result = client.blueprintPath("sessionValue", "testValue", "blueprintValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.blueprintPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchSessionFromBlueprintName', () => { - const result = client.matchSessionFromBlueprintName(fakePath); - assert.strictEqual(result, "sessionValue"); - assert((client.pathTemplates.blueprintPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchTestFromBlueprintName', () => { - const result = client.matchTestFromBlueprintName(fakePath); - assert.strictEqual(result, "testValue"); - assert((client.pathTemplates.blueprintPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBlueprintFromBlueprintName', () => { - const result = client.matchBlueprintFromBlueprintName(fakePath); - assert.strictEqual(result, "blueprintValue"); - assert((client.pathTemplates.blueprintPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('uses async iteration with listBlurbs with error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListBlurbsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.ListBlurbsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listBlurbs.asyncIterate = stubAsyncIterationCall( + undefined, + expectedError, + ); + const iterable = client.listBlurbsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.showcase.v1beta1.IBlurb[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + (client.descriptors.page.listBlurbs.asyncIterate as SinonStub).getCall( + 0, + ).args[1], + request, + ); + assert( + (client.descriptors.page.listBlurbs.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + }); + + describe('Path templates', () => { + describe('blueprint', () => { + const fakePath = '/rendered/path/blueprint'; + const expectedParameters = { + session: 'sessionValue', + test: 'testValue', + blueprint: 'blueprintValue', + }; + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.blueprintPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.blueprintPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('blueprintPath', () => { + const result = client.blueprintPath( + 'sessionValue', + 'testValue', + 'blueprintValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.blueprintPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchSessionFromBlueprintName', () => { + const result = client.matchSessionFromBlueprintName(fakePath); + assert.strictEqual(result, 'sessionValue'); + assert( + (client.pathTemplates.blueprintPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchTestFromBlueprintName', () => { + const result = client.matchTestFromBlueprintName(fakePath); + assert.strictEqual(result, 'testValue'); + assert( + (client.pathTemplates.blueprintPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBlueprintFromBlueprintName', () => { + const result = client.matchBlueprintFromBlueprintName(fakePath); + assert.strictEqual(result, 'blueprintValue'); + assert( + (client.pathTemplates.blueprintPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('room', () => { - const fakePath = "/rendered/path/room"; - const expectedParameters = { - room: "roomValue", - }; - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.roomPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.roomPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('roomPath', () => { - const result = client.roomPath("roomValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.roomPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchRoomFromRoomName', () => { - const result = client.matchRoomFromRoomName(fakePath); - assert.strictEqual(result, "roomValue"); - assert((client.pathTemplates.roomPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('room', () => { + const fakePath = '/rendered/path/room'; + const expectedParameters = { + room: 'roomValue', + }; + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.roomPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.roomPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('roomPath', () => { + const result = client.roomPath('roomValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.roomPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchRoomFromRoomName', () => { + const result = client.matchRoomFromRoomName(fakePath); + assert.strictEqual(result, 'roomValue'); + assert( + (client.pathTemplates.roomPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('roomBlurb', () => { - const fakePath = "/rendered/path/roomBlurb"; - const expectedParameters = { - room: "roomValue", - blurb: "blurbValue", - }; - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.roomBlurbPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.roomBlurbPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('roomBlurbPath', () => { - const result = client.roomBlurbPath("roomValue", "blurbValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.roomBlurbPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchRoomFromRoomBlurbName', () => { - const result = client.matchRoomFromRoomBlurbName(fakePath); - assert.strictEqual(result, "roomValue"); - assert((client.pathTemplates.roomBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBlurbFromRoomBlurbName', () => { - const result = client.matchBlurbFromRoomBlurbName(fakePath); - assert.strictEqual(result, "blurbValue"); - assert((client.pathTemplates.roomBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('roomBlurb', () => { + const fakePath = '/rendered/path/roomBlurb'; + const expectedParameters = { + room: 'roomValue', + blurb: 'blurbValue', + }; + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.roomBlurbPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.roomBlurbPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('roomBlurbPath', () => { + const result = client.roomBlurbPath('roomValue', 'blurbValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.roomBlurbPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchRoomFromRoomBlurbName', () => { + const result = client.matchRoomFromRoomBlurbName(fakePath); + assert.strictEqual(result, 'roomValue'); + assert( + (client.pathTemplates.roomBlurbPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBlurbFromRoomBlurbName', () => { + const result = client.matchBlurbFromRoomBlurbName(fakePath); + assert.strictEqual(result, 'blurbValue'); + assert( + (client.pathTemplates.roomBlurbPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('roomBlurbsLegacyRoomBlurb', () => { - const fakePath = "/rendered/path/roomBlurbsLegacyRoomBlurb"; - const expectedParameters = { - room: "roomValue", - legacy_room: "legacyRoomValue", - blurb: "blurbValue", - }; - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('roomBlurbsLegacyRoomBlurbPath', () => { - const result = client.roomBlurbsLegacyRoomBlurbPath("roomValue", "legacyRoomValue", "blurbValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchRoomFromRoomBlurbsLegacyRoomBlurbName', () => { - const result = client.matchRoomFromRoomBlurbsLegacyRoomBlurbName(fakePath); - assert.strictEqual(result, "roomValue"); - assert((client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName', () => { - const result = client.matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName(fakePath); - assert.strictEqual(result, "legacyRoomValue"); - assert((client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBlurbFromRoomBlurbsLegacyRoomBlurbName', () => { - const result = client.matchBlurbFromRoomBlurbsLegacyRoomBlurbName(fakePath); - assert.strictEqual(result, "blurbValue"); - assert((client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('roomBlurbsLegacyRoomBlurb', () => { + const fakePath = '/rendered/path/roomBlurbsLegacyRoomBlurb'; + const expectedParameters = { + room: 'roomValue', + legacy_room: 'legacyRoomValue', + blurb: 'blurbValue', + }; + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('roomBlurbsLegacyRoomBlurbPath', () => { + const result = client.roomBlurbsLegacyRoomBlurbPath( + 'roomValue', + 'legacyRoomValue', + 'blurbValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchRoomFromRoomBlurbsLegacyRoomBlurbName', () => { + const result = + client.matchRoomFromRoomBlurbsLegacyRoomBlurbName(fakePath); + assert.strictEqual(result, 'roomValue'); + assert( + ( + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName', () => { + const result = + client.matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName(fakePath); + assert.strictEqual(result, 'legacyRoomValue'); + assert( + ( + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBlurbFromRoomBlurbsLegacyRoomBlurbName', () => { + const result = + client.matchBlurbFromRoomBlurbsLegacyRoomBlurbName(fakePath); + assert.strictEqual(result, 'blurbValue'); + assert( + ( + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('sequence', () => { - const fakePath = "/rendered/path/sequence"; - const expectedParameters = { - sequence: "sequenceValue", - }; - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.sequencePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.sequencePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('sequencePath', () => { - const result = client.sequencePath("sequenceValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.sequencePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchSequenceFromSequenceName', () => { - const result = client.matchSequenceFromSequenceName(fakePath); - assert.strictEqual(result, "sequenceValue"); - assert((client.pathTemplates.sequencePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('sequence', () => { + const fakePath = '/rendered/path/sequence'; + const expectedParameters = { + sequence: 'sequenceValue', + }; + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.sequencePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.sequencePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('sequencePath', () => { + const result = client.sequencePath('sequenceValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.sequencePathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchSequenceFromSequenceName', () => { + const result = client.matchSequenceFromSequenceName(fakePath); + assert.strictEqual(result, 'sequenceValue'); + assert( + (client.pathTemplates.sequencePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('sequenceReport', () => { - const fakePath = "/rendered/path/sequenceReport"; - const expectedParameters = { - sequence: "sequenceValue", - }; - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.sequenceReportPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.sequenceReportPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('sequenceReportPath', () => { - const result = client.sequenceReportPath("sequenceValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.sequenceReportPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchSequenceFromSequenceReportName', () => { - const result = client.matchSequenceFromSequenceReportName(fakePath); - assert.strictEqual(result, "sequenceValue"); - assert((client.pathTemplates.sequenceReportPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('sequenceReport', () => { + const fakePath = '/rendered/path/sequenceReport'; + const expectedParameters = { + sequence: 'sequenceValue', + }; + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.sequenceReportPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.sequenceReportPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('sequenceReportPath', () => { + const result = client.sequenceReportPath('sequenceValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.sequenceReportPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchSequenceFromSequenceReportName', () => { + const result = client.matchSequenceFromSequenceReportName(fakePath); + assert.strictEqual(result, 'sequenceValue'); + assert( + (client.pathTemplates.sequenceReportPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('session', () => { - const fakePath = "/rendered/path/session"; - const expectedParameters = { - session: "sessionValue", - }; - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.sessionPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.sessionPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('sessionPath', () => { - const result = client.sessionPath("sessionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.sessionPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchSessionFromSessionName', () => { - const result = client.matchSessionFromSessionName(fakePath); - assert.strictEqual(result, "sessionValue"); - assert((client.pathTemplates.sessionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('session', () => { + const fakePath = '/rendered/path/session'; + const expectedParameters = { + session: 'sessionValue', + }; + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.sessionPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.sessionPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('sessionPath', () => { + const result = client.sessionPath('sessionValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.sessionPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchSessionFromSessionName', () => { + const result = client.matchSessionFromSessionName(fakePath); + assert.strictEqual(result, 'sessionValue'); + assert( + (client.pathTemplates.sessionPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('test', () => { - const fakePath = "/rendered/path/test"; - const expectedParameters = { - session: "sessionValue", - test: "testValue", - }; - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.testPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.testPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('testPath', () => { - const result = client.testPath("sessionValue", "testValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.testPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchSessionFromTestName', () => { - const result = client.matchSessionFromTestName(fakePath); - assert.strictEqual(result, "sessionValue"); - assert((client.pathTemplates.testPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchTestFromTestName', () => { - const result = client.matchTestFromTestName(fakePath); - assert.strictEqual(result, "testValue"); - assert((client.pathTemplates.testPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('test', () => { + const fakePath = '/rendered/path/test'; + const expectedParameters = { + session: 'sessionValue', + test: 'testValue', + }; + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.testPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.testPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('testPath', () => { + const result = client.testPath('sessionValue', 'testValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.testPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchSessionFromTestName', () => { + const result = client.matchSessionFromTestName(fakePath); + assert.strictEqual(result, 'sessionValue'); + assert( + (client.pathTemplates.testPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchTestFromTestName', () => { + const result = client.matchTestFromTestName(fakePath); + assert.strictEqual(result, 'testValue'); + assert( + (client.pathTemplates.testPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('user', () => { - const fakePath = "/rendered/path/user"; - const expectedParameters = { - user: "userValue", - }; - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.userPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.userPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('userPath', () => { - const result = client.userPath("userValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.userPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchUserFromUserName', () => { - const result = client.matchUserFromUserName(fakePath); - assert.strictEqual(result, "userValue"); - assert((client.pathTemplates.userPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('user', () => { + const fakePath = '/rendered/path/user'; + const expectedParameters = { + user: 'userValue', + }; + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.userPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.userPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('userPath', () => { + const result = client.userPath('userValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.userPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchUserFromUserName', () => { + const result = client.matchUserFromUserName(fakePath); + assert.strictEqual(result, 'userValue'); + assert( + (client.pathTemplates.userPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('userProfileBlurb', () => { - const fakePath = "/rendered/path/userProfileBlurb"; - const expectedParameters = { - user: "userValue", - blurb: "blurbValue", - }; - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.userProfileBlurbPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.userProfileBlurbPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('userProfileBlurbPath', () => { - const result = client.userProfileBlurbPath("userValue", "blurbValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.userProfileBlurbPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchUserFromUserProfileBlurbName', () => { - const result = client.matchUserFromUserProfileBlurbName(fakePath); - assert.strictEqual(result, "userValue"); - assert((client.pathTemplates.userProfileBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBlurbFromUserProfileBlurbName', () => { - const result = client.matchBlurbFromUserProfileBlurbName(fakePath); - assert.strictEqual(result, "blurbValue"); - assert((client.pathTemplates.userProfileBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('userProfileBlurb', () => { + const fakePath = '/rendered/path/userProfileBlurb'; + const expectedParameters = { + user: 'userValue', + blurb: 'blurbValue', + }; + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.userProfileBlurbPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.userProfileBlurbPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('userProfileBlurbPath', () => { + const result = client.userProfileBlurbPath('userValue', 'blurbValue'); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.userProfileBlurbPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchUserFromUserProfileBlurbName', () => { + const result = client.matchUserFromUserProfileBlurbName(fakePath); + assert.strictEqual(result, 'userValue'); + assert( + (client.pathTemplates.userProfileBlurbPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBlurbFromUserProfileBlurbName', () => { + const result = client.matchBlurbFromUserProfileBlurbName(fakePath); + assert.strictEqual(result, 'blurbValue'); + assert( + (client.pathTemplates.userProfileBlurbPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('userProfileBlurbsLegacyUserBlurb', () => { - const fakePath = "/rendered/path/userProfileBlurbsLegacyUserBlurb"; - const expectedParameters = { - user: "userValue", - legacy_user: "legacyUserValue", - blurb: "blurbValue", - }; - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('userProfileBlurbsLegacyUserBlurbPath', () => { - const result = client.userProfileBlurbsLegacyUserBlurbPath("userValue", "legacyUserValue", "blurbValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchUserFromUserProfileBlurbsLegacyUserBlurbName', () => { - const result = client.matchUserFromUserProfileBlurbsLegacyUserBlurbName(fakePath); - assert.strictEqual(result, "userValue"); - assert((client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName', () => { - const result = client.matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName(fakePath); - assert.strictEqual(result, "legacyUserValue"); - assert((client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBlurbFromUserProfileBlurbsLegacyUserBlurbName', () => { - const result = client.matchBlurbFromUserProfileBlurbsLegacyUserBlurbName(fakePath); - assert.strictEqual(result, "blurbValue"); - assert((client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('userProfileBlurbsLegacyUserBlurb', () => { + const fakePath = '/rendered/path/userProfileBlurbsLegacyUserBlurb'; + const expectedParameters = { + user: 'userValue', + legacy_user: 'legacyUserValue', + blurb: 'blurbValue', + }; + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('userProfileBlurbsLegacyUserBlurbPath', () => { + const result = client.userProfileBlurbsLegacyUserBlurbPath( + 'userValue', + 'legacyUserValue', + 'blurbValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchUserFromUserProfileBlurbsLegacyUserBlurbName', () => { + const result = + client.matchUserFromUserProfileBlurbsLegacyUserBlurbName(fakePath); + assert.strictEqual(result, 'userValue'); + assert( + ( + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName', () => { + const result = + client.matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName( + fakePath, + ); + assert.strictEqual(result, 'legacyUserValue'); + assert( + ( + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBlurbFromUserProfileBlurbsLegacyUserBlurbName', () => { + const result = + client.matchBlurbFromUserProfileBlurbsLegacyUserBlurbName(fakePath); + assert.strictEqual(result, 'blurbValue'); + assert( + ( + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/core/generator/gapic-generator-typescript/baselines/disable-packing-test-esm/esm/test/gapic_sequence_service_v1beta1.ts.baseline b/core/generator/gapic-generator-typescript/baselines/disable-packing-test-esm/esm/test/gapic_sequence_service_v1beta1.ts.baseline index 6ad653d66ad9..5546d302702c 100644 --- a/core/generator/gapic-generator-typescript/baselines/disable-packing-test-esm/esm/test/gapic_sequence_service_v1beta1.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/disable-packing-test-esm/esm/test/gapic_sequence_service_v1beta1.ts.baseline @@ -20,14 +20,14 @@ import * as protos from '../../protos/protos.js'; import assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as sequenceserviceModule from '../src/index.js'; -import {protobuf} from 'google-gax'; +import { protobuf } from 'google-gax'; import fs from 'fs'; import path from 'path'; -import {fileURLToPath} from 'url'; +import { fileURLToPath } from 'url'; // @ts-ignore const dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -35,844 +35,1121 @@ const dirname = path.dirname(fileURLToPath(import.meta.url)); // to fill in default values for request objects const root = protobuf.Root.fromJSON( JSON.parse( - fs.readFileSync(path.join(dirname, '..', '..', 'protos/protos.json'), 'utf8') - )) + fs.readFileSync( + path.join(dirname, '..', '..', 'protos/protos.json'), + 'utf8', + ), + ), +); // eslint-disable-next-line @typescript-eslint/no-unused-vars function getTypeDefaultValue(typeName: string, fields: string[]) { - let type = root.lookupType(typeName) as protobuf.Type; - for (const field of fields.slice(0, -1)) { - type = type?.fields[field]?.resolvedType as protobuf.Type; - } - return type?.fields[fields[fields.length - 1]]?.defaultValue ?? null; + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type?.fields[field]?.resolvedType as protobuf.Type; + } + return type?.fields[fields[fields.length - 1]]?.defaultValue ?? null; } function generateSampleMessage(instance: T) { - const filledObject = (instance.constructor as typeof protobuf.Message) - .toObject(instance as protobuf.Message, {defaults: true}); - return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, { defaults: true }); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; } function stubSimpleCall(response?: ResponseType, error?: Error) { - return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); } -function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { - return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +function stubSimpleCallWithCallback( + response?: ResponseType, + error?: Error, +) { + return error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); } describe('v1beta1.SequenceServiceClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'localhost'); - }); - - it('has universeDomain', () => { - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); - - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - it('throws DeprecationWarning if static servicePath is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const servicePath = sequenceserviceModule.v1beta1.SequenceServiceClient.servicePath; - assert.strictEqual(servicePath, 'localhost'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = sequenceserviceModule.v1beta1.SequenceServiceClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'localhost'); - assert(stub.called); - stub.restore(); - }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { new sequenceserviceModule.v1beta1.SequenceServiceClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); - - it('has port', () => { - const port = sequenceserviceModule.v1beta1.SequenceServiceClient.port; - assert(port); - assert(typeof port === 'number'); - }); - - it('should create a client with no option', () => { - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient(); - assert(client); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'localhost'); + }); - it('should create a client with gRPC fallback', () => { - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ - fallback: true, - }); - assert(client); - }); + it('has universeDomain', () => { + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - it('has initialize method and supports deferred initialization', async () => { - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.sequenceServiceStub, undefined); - await client.initialize(); - assert(client.sequenceServiceStub); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = + sequenceserviceModule.v1beta1.SequenceServiceClient.servicePath; + assert.strictEqual(servicePath, 'localhost'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + sequenceserviceModule.v1beta1.SequenceServiceClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'localhost'); + assert(stub.called); + stub.restore(); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new sequenceserviceModule.v1beta1.SequenceServiceClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); + }); - it('has close method for the initialized client', done => { - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.sequenceServiceStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('has port', () => { + const port = sequenceserviceModule.v1beta1.SequenceServiceClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('has close method for the non-initialized client', done => { - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.sequenceServiceStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('should create a client with no option', () => { + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient(); + assert(client); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); - }); + it('should create a client with gRPC fallback', () => { + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ + fallback: true, + }); + assert(client); + }); - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId((err?: Error|null, projectId?: string|null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } - }); - }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); - }); + it('has initialize method and supports deferred initialization', async () => { + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.sequenceServiceStub, undefined); + await client.initialize(); + assert(client.sequenceServiceStub); }); - describe('createSequence', () => { - it('invokes createSequence without error', async () => { - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.CreateSequenceRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.Sequence() - ); - client.innerApiCalls.createSequence = stubSimpleCall(expectedResponse); - const [response] = await client.createSequence(request); - assert.deepStrictEqual(response, expectedResponse); + it('has close method for the initialized client', (done) => { + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.sequenceServiceStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes createSequence without error using callback', async () => { - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.CreateSequenceRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.Sequence() - ); - client.innerApiCalls.createSequence = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createSequence( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.ISequence|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); + it('has close method for the non-initialized client', (done) => { + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.sequenceServiceStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes createSequence with error', async () => { - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.CreateSequenceRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.createSequence = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createSequence(request), expectedError); - }); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + }); - it('invokes createSequence with closed client', async () => { - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.CreateSequenceRequest() - ); - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createSequence(request), expectedError); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + }); + + describe('createSequence', () => { + it('invokes createSequence without error', async () => { + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.CreateSequenceRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.Sequence(), + ); + client.innerApiCalls.createSequence = stubSimpleCall(expectedResponse); + const [response] = await client.createSequence(request); + assert.deepStrictEqual(response, expectedResponse); }); - describe('getSequenceReport', () => { - it('invokes getSequenceReport without error', async () => { - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.GetSequenceReportRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.GetSequenceReportRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.SequenceReport() - ); - client.innerApiCalls.getSequenceReport = stubSimpleCall(expectedResponse); - const [response] = await client.getSequenceReport(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getSequenceReport as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getSequenceReport as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createSequence without error using callback', async () => { + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.CreateSequenceRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.Sequence(), + ); + client.innerApiCalls.createSequence = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createSequence( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.ISequence | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes getSequenceReport without error using callback', async () => { - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.GetSequenceReportRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.GetSequenceReportRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.SequenceReport() - ); - client.innerApiCalls.getSequenceReport = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getSequenceReport( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.ISequenceReport|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getSequenceReport as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getSequenceReport as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createSequence with error', async () => { + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.CreateSequenceRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.createSequence = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.createSequence(request), expectedError); + }); - it('invokes getSequenceReport with error', async () => { - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.GetSequenceReportRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.GetSequenceReportRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getSequenceReport = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getSequenceReport(request), expectedError); - const actualRequest = (client.innerApiCalls.getSequenceReport as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getSequenceReport as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createSequence with closed client', async () => { + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.CreateSequenceRequest(), + ); + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.createSequence(request), expectedError); + }); + }); + + describe('getSequenceReport', () => { + it('invokes getSequenceReport without error', async () => { + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.GetSequenceReportRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.GetSequenceReportRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.SequenceReport(), + ); + client.innerApiCalls.getSequenceReport = stubSimpleCall(expectedResponse); + const [response] = await client.getSequenceReport(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getSequenceReport as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getSequenceReport as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getSequenceReport with closed client', async () => { - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.GetSequenceReportRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.GetSequenceReportRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getSequenceReport(request), expectedError); - }); + it('invokes getSequenceReport without error using callback', async () => { + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.GetSequenceReportRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.GetSequenceReportRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.SequenceReport(), + ); + client.innerApiCalls.getSequenceReport = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getSequenceReport( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.ISequenceReport | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getSequenceReport as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getSequenceReport as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('attemptSequence', () => { - it('invokes attemptSequence without error', async () => { - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.AttemptSequenceRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.AttemptSequenceRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.attemptSequence = stubSimpleCall(expectedResponse); - const [response] = await client.attemptSequence(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.attemptSequence as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.attemptSequence as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getSequenceReport with error', async () => { + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.GetSequenceReportRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.GetSequenceReportRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getSequenceReport = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getSequenceReport(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getSequenceReport as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getSequenceReport as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes attemptSequence without error using callback', async () => { - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.AttemptSequenceRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.AttemptSequenceRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.attemptSequence = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.attemptSequence( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.attemptSequence as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.attemptSequence as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getSequenceReport with closed client', async () => { + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.GetSequenceReportRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.GetSequenceReportRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getSequenceReport(request), expectedError); + }); + }); + + describe('attemptSequence', () => { + it('invokes attemptSequence without error', async () => { + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.AttemptSequenceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.AttemptSequenceRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.attemptSequence = stubSimpleCall(expectedResponse); + const [response] = await client.attemptSequence(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.attemptSequence as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.attemptSequence as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes attemptSequence with error', async () => { - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.AttemptSequenceRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.AttemptSequenceRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.attemptSequence = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.attemptSequence(request), expectedError); - const actualRequest = (client.innerApiCalls.attemptSequence as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.attemptSequence as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes attemptSequence without error using callback', async () => { + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.AttemptSequenceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.AttemptSequenceRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.attemptSequence = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.attemptSequence( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.attemptSequence as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.attemptSequence as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes attemptSequence with closed client', async () => { - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.AttemptSequenceRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.AttemptSequenceRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.attemptSequence(request), expectedError); - }); + it('invokes attemptSequence with error', async () => { + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.AttemptSequenceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.AttemptSequenceRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.attemptSequence = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.attemptSequence(request), expectedError); + const actualRequest = ( + client.innerApiCalls.attemptSequence as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.attemptSequence as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('Path templates', () => { - - describe('blueprint', () => { - const fakePath = "/rendered/path/blueprint"; - const expectedParameters = { - session: "sessionValue", - test: "testValue", - blueprint: "blueprintValue", - }; - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.blueprintPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.blueprintPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('blueprintPath', () => { - const result = client.blueprintPath("sessionValue", "testValue", "blueprintValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.blueprintPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchSessionFromBlueprintName', () => { - const result = client.matchSessionFromBlueprintName(fakePath); - assert.strictEqual(result, "sessionValue"); - assert((client.pathTemplates.blueprintPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchTestFromBlueprintName', () => { - const result = client.matchTestFromBlueprintName(fakePath); - assert.strictEqual(result, "testValue"); - assert((client.pathTemplates.blueprintPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBlueprintFromBlueprintName', () => { - const result = client.matchBlueprintFromBlueprintName(fakePath); - assert.strictEqual(result, "blueprintValue"); - assert((client.pathTemplates.blueprintPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('invokes attemptSequence with closed client', async () => { + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.AttemptSequenceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.AttemptSequenceRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.attemptSequence(request), expectedError); + }); + }); + + describe('Path templates', () => { + describe('blueprint', () => { + const fakePath = '/rendered/path/blueprint'; + const expectedParameters = { + session: 'sessionValue', + test: 'testValue', + blueprint: 'blueprintValue', + }; + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.blueprintPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.blueprintPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('blueprintPath', () => { + const result = client.blueprintPath( + 'sessionValue', + 'testValue', + 'blueprintValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.blueprintPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchSessionFromBlueprintName', () => { + const result = client.matchSessionFromBlueprintName(fakePath); + assert.strictEqual(result, 'sessionValue'); + assert( + (client.pathTemplates.blueprintPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchTestFromBlueprintName', () => { + const result = client.matchTestFromBlueprintName(fakePath); + assert.strictEqual(result, 'testValue'); + assert( + (client.pathTemplates.blueprintPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBlueprintFromBlueprintName', () => { + const result = client.matchBlueprintFromBlueprintName(fakePath); + assert.strictEqual(result, 'blueprintValue'); + assert( + (client.pathTemplates.blueprintPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('room', () => { - const fakePath = "/rendered/path/room"; - const expectedParameters = { - room: "roomValue", - }; - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.roomPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.roomPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('roomPath', () => { - const result = client.roomPath("roomValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.roomPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchRoomFromRoomName', () => { - const result = client.matchRoomFromRoomName(fakePath); - assert.strictEqual(result, "roomValue"); - assert((client.pathTemplates.roomPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('room', () => { + const fakePath = '/rendered/path/room'; + const expectedParameters = { + room: 'roomValue', + }; + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.roomPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.roomPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('roomPath', () => { + const result = client.roomPath('roomValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.roomPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchRoomFromRoomName', () => { + const result = client.matchRoomFromRoomName(fakePath); + assert.strictEqual(result, 'roomValue'); + assert( + (client.pathTemplates.roomPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('roomBlurb', () => { - const fakePath = "/rendered/path/roomBlurb"; - const expectedParameters = { - room: "roomValue", - blurb: "blurbValue", - }; - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.roomBlurbPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.roomBlurbPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('roomBlurbPath', () => { - const result = client.roomBlurbPath("roomValue", "blurbValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.roomBlurbPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchRoomFromRoomBlurbName', () => { - const result = client.matchRoomFromRoomBlurbName(fakePath); - assert.strictEqual(result, "roomValue"); - assert((client.pathTemplates.roomBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBlurbFromRoomBlurbName', () => { - const result = client.matchBlurbFromRoomBlurbName(fakePath); - assert.strictEqual(result, "blurbValue"); - assert((client.pathTemplates.roomBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('roomBlurb', () => { + const fakePath = '/rendered/path/roomBlurb'; + const expectedParameters = { + room: 'roomValue', + blurb: 'blurbValue', + }; + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.roomBlurbPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.roomBlurbPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('roomBlurbPath', () => { + const result = client.roomBlurbPath('roomValue', 'blurbValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.roomBlurbPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchRoomFromRoomBlurbName', () => { + const result = client.matchRoomFromRoomBlurbName(fakePath); + assert.strictEqual(result, 'roomValue'); + assert( + (client.pathTemplates.roomBlurbPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBlurbFromRoomBlurbName', () => { + const result = client.matchBlurbFromRoomBlurbName(fakePath); + assert.strictEqual(result, 'blurbValue'); + assert( + (client.pathTemplates.roomBlurbPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('roomBlurbsLegacyRoomBlurb', () => { - const fakePath = "/rendered/path/roomBlurbsLegacyRoomBlurb"; - const expectedParameters = { - room: "roomValue", - legacy_room: "legacyRoomValue", - blurb: "blurbValue", - }; - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('roomBlurbsLegacyRoomBlurbPath', () => { - const result = client.roomBlurbsLegacyRoomBlurbPath("roomValue", "legacyRoomValue", "blurbValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchRoomFromRoomBlurbsLegacyRoomBlurbName', () => { - const result = client.matchRoomFromRoomBlurbsLegacyRoomBlurbName(fakePath); - assert.strictEqual(result, "roomValue"); - assert((client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName', () => { - const result = client.matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName(fakePath); - assert.strictEqual(result, "legacyRoomValue"); - assert((client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBlurbFromRoomBlurbsLegacyRoomBlurbName', () => { - const result = client.matchBlurbFromRoomBlurbsLegacyRoomBlurbName(fakePath); - assert.strictEqual(result, "blurbValue"); - assert((client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('roomBlurbsLegacyRoomBlurb', () => { + const fakePath = '/rendered/path/roomBlurbsLegacyRoomBlurb'; + const expectedParameters = { + room: 'roomValue', + legacy_room: 'legacyRoomValue', + blurb: 'blurbValue', + }; + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('roomBlurbsLegacyRoomBlurbPath', () => { + const result = client.roomBlurbsLegacyRoomBlurbPath( + 'roomValue', + 'legacyRoomValue', + 'blurbValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchRoomFromRoomBlurbsLegacyRoomBlurbName', () => { + const result = + client.matchRoomFromRoomBlurbsLegacyRoomBlurbName(fakePath); + assert.strictEqual(result, 'roomValue'); + assert( + ( + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName', () => { + const result = + client.matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName(fakePath); + assert.strictEqual(result, 'legacyRoomValue'); + assert( + ( + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBlurbFromRoomBlurbsLegacyRoomBlurbName', () => { + const result = + client.matchBlurbFromRoomBlurbsLegacyRoomBlurbName(fakePath); + assert.strictEqual(result, 'blurbValue'); + assert( + ( + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('sequence', () => { - const fakePath = "/rendered/path/sequence"; - const expectedParameters = { - sequence: "sequenceValue", - }; - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.sequencePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.sequencePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('sequencePath', () => { - const result = client.sequencePath("sequenceValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.sequencePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchSequenceFromSequenceName', () => { - const result = client.matchSequenceFromSequenceName(fakePath); - assert.strictEqual(result, "sequenceValue"); - assert((client.pathTemplates.sequencePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('sequence', () => { + const fakePath = '/rendered/path/sequence'; + const expectedParameters = { + sequence: 'sequenceValue', + }; + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.sequencePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.sequencePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('sequencePath', () => { + const result = client.sequencePath('sequenceValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.sequencePathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchSequenceFromSequenceName', () => { + const result = client.matchSequenceFromSequenceName(fakePath); + assert.strictEqual(result, 'sequenceValue'); + assert( + (client.pathTemplates.sequencePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('sequenceReport', () => { - const fakePath = "/rendered/path/sequenceReport"; - const expectedParameters = { - sequence: "sequenceValue", - }; - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.sequenceReportPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.sequenceReportPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('sequenceReportPath', () => { - const result = client.sequenceReportPath("sequenceValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.sequenceReportPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchSequenceFromSequenceReportName', () => { - const result = client.matchSequenceFromSequenceReportName(fakePath); - assert.strictEqual(result, "sequenceValue"); - assert((client.pathTemplates.sequenceReportPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('sequenceReport', () => { + const fakePath = '/rendered/path/sequenceReport'; + const expectedParameters = { + sequence: 'sequenceValue', + }; + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.sequenceReportPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.sequenceReportPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('sequenceReportPath', () => { + const result = client.sequenceReportPath('sequenceValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.sequenceReportPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchSequenceFromSequenceReportName', () => { + const result = client.matchSequenceFromSequenceReportName(fakePath); + assert.strictEqual(result, 'sequenceValue'); + assert( + (client.pathTemplates.sequenceReportPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('session', () => { - const fakePath = "/rendered/path/session"; - const expectedParameters = { - session: "sessionValue", - }; - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.sessionPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.sessionPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('sessionPath', () => { - const result = client.sessionPath("sessionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.sessionPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchSessionFromSessionName', () => { - const result = client.matchSessionFromSessionName(fakePath); - assert.strictEqual(result, "sessionValue"); - assert((client.pathTemplates.sessionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('session', () => { + const fakePath = '/rendered/path/session'; + const expectedParameters = { + session: 'sessionValue', + }; + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.sessionPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.sessionPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('sessionPath', () => { + const result = client.sessionPath('sessionValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.sessionPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchSessionFromSessionName', () => { + const result = client.matchSessionFromSessionName(fakePath); + assert.strictEqual(result, 'sessionValue'); + assert( + (client.pathTemplates.sessionPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('test', () => { - const fakePath = "/rendered/path/test"; - const expectedParameters = { - session: "sessionValue", - test: "testValue", - }; - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.testPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.testPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('testPath', () => { - const result = client.testPath("sessionValue", "testValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.testPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchSessionFromTestName', () => { - const result = client.matchSessionFromTestName(fakePath); - assert.strictEqual(result, "sessionValue"); - assert((client.pathTemplates.testPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchTestFromTestName', () => { - const result = client.matchTestFromTestName(fakePath); - assert.strictEqual(result, "testValue"); - assert((client.pathTemplates.testPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('test', () => { + const fakePath = '/rendered/path/test'; + const expectedParameters = { + session: 'sessionValue', + test: 'testValue', + }; + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.testPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.testPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('testPath', () => { + const result = client.testPath('sessionValue', 'testValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.testPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchSessionFromTestName', () => { + const result = client.matchSessionFromTestName(fakePath); + assert.strictEqual(result, 'sessionValue'); + assert( + (client.pathTemplates.testPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchTestFromTestName', () => { + const result = client.matchTestFromTestName(fakePath); + assert.strictEqual(result, 'testValue'); + assert( + (client.pathTemplates.testPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('user', () => { - const fakePath = "/rendered/path/user"; - const expectedParameters = { - user: "userValue", - }; - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.userPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.userPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('userPath', () => { - const result = client.userPath("userValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.userPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchUserFromUserName', () => { - const result = client.matchUserFromUserName(fakePath); - assert.strictEqual(result, "userValue"); - assert((client.pathTemplates.userPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('user', () => { + const fakePath = '/rendered/path/user'; + const expectedParameters = { + user: 'userValue', + }; + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.userPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.userPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('userPath', () => { + const result = client.userPath('userValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.userPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchUserFromUserName', () => { + const result = client.matchUserFromUserName(fakePath); + assert.strictEqual(result, 'userValue'); + assert( + (client.pathTemplates.userPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('userProfileBlurb', () => { - const fakePath = "/rendered/path/userProfileBlurb"; - const expectedParameters = { - user: "userValue", - blurb: "blurbValue", - }; - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.userProfileBlurbPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.userProfileBlurbPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('userProfileBlurbPath', () => { - const result = client.userProfileBlurbPath("userValue", "blurbValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.userProfileBlurbPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchUserFromUserProfileBlurbName', () => { - const result = client.matchUserFromUserProfileBlurbName(fakePath); - assert.strictEqual(result, "userValue"); - assert((client.pathTemplates.userProfileBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBlurbFromUserProfileBlurbName', () => { - const result = client.matchBlurbFromUserProfileBlurbName(fakePath); - assert.strictEqual(result, "blurbValue"); - assert((client.pathTemplates.userProfileBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('userProfileBlurb', () => { + const fakePath = '/rendered/path/userProfileBlurb'; + const expectedParameters = { + user: 'userValue', + blurb: 'blurbValue', + }; + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.userProfileBlurbPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.userProfileBlurbPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('userProfileBlurbPath', () => { + const result = client.userProfileBlurbPath('userValue', 'blurbValue'); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.userProfileBlurbPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchUserFromUserProfileBlurbName', () => { + const result = client.matchUserFromUserProfileBlurbName(fakePath); + assert.strictEqual(result, 'userValue'); + assert( + (client.pathTemplates.userProfileBlurbPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBlurbFromUserProfileBlurbName', () => { + const result = client.matchBlurbFromUserProfileBlurbName(fakePath); + assert.strictEqual(result, 'blurbValue'); + assert( + (client.pathTemplates.userProfileBlurbPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('userProfileBlurbsLegacyUserBlurb', () => { - const fakePath = "/rendered/path/userProfileBlurbsLegacyUserBlurb"; - const expectedParameters = { - user: "userValue", - legacy_user: "legacyUserValue", - blurb: "blurbValue", - }; - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('userProfileBlurbsLegacyUserBlurbPath', () => { - const result = client.userProfileBlurbsLegacyUserBlurbPath("userValue", "legacyUserValue", "blurbValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchUserFromUserProfileBlurbsLegacyUserBlurbName', () => { - const result = client.matchUserFromUserProfileBlurbsLegacyUserBlurbName(fakePath); - assert.strictEqual(result, "userValue"); - assert((client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName', () => { - const result = client.matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName(fakePath); - assert.strictEqual(result, "legacyUserValue"); - assert((client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBlurbFromUserProfileBlurbsLegacyUserBlurbName', () => { - const result = client.matchBlurbFromUserProfileBlurbsLegacyUserBlurbName(fakePath); - assert.strictEqual(result, "blurbValue"); - assert((client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('userProfileBlurbsLegacyUserBlurb', () => { + const fakePath = '/rendered/path/userProfileBlurbsLegacyUserBlurb'; + const expectedParameters = { + user: 'userValue', + legacy_user: 'legacyUserValue', + blurb: 'blurbValue', + }; + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('userProfileBlurbsLegacyUserBlurbPath', () => { + const result = client.userProfileBlurbsLegacyUserBlurbPath( + 'userValue', + 'legacyUserValue', + 'blurbValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchUserFromUserProfileBlurbsLegacyUserBlurbName', () => { + const result = + client.matchUserFromUserProfileBlurbsLegacyUserBlurbName(fakePath); + assert.strictEqual(result, 'userValue'); + assert( + ( + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName', () => { + const result = + client.matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName( + fakePath, + ); + assert.strictEqual(result, 'legacyUserValue'); + assert( + ( + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBlurbFromUserProfileBlurbsLegacyUserBlurbName', () => { + const result = + client.matchBlurbFromUserProfileBlurbsLegacyUserBlurbName(fakePath); + assert.strictEqual(result, 'blurbValue'); + assert( + ( + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/core/generator/gapic-generator-typescript/baselines/disable-packing-test-esm/esm/test/gapic_testing_v1beta1.ts.baseline b/core/generator/gapic-generator-typescript/baselines/disable-packing-test-esm/esm/test/gapic_testing_v1beta1.ts.baseline index f19fcdb3cbb3..f0662335f974 100644 --- a/core/generator/gapic-generator-typescript/baselines/disable-packing-test-esm/esm/test/gapic_testing_v1beta1.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/disable-packing-test-esm/esm/test/gapic_testing_v1beta1.ts.baseline @@ -20,16 +20,16 @@ import * as protos from '../../protos/protos.js'; import assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as testingModule from '../src/index.js'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; -import {protobuf} from 'google-gax'; +import { protobuf } from 'google-gax'; import fs from 'fs'; import path from 'path'; -import {fileURLToPath} from 'url'; +import { fileURLToPath } from 'url'; // @ts-ignore const dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -37,1633 +37,2079 @@ const dirname = path.dirname(fileURLToPath(import.meta.url)); // to fill in default values for request objects const root = protobuf.Root.fromJSON( JSON.parse( - fs.readFileSync(path.join(dirname, '..', '..', 'protos/protos.json'), 'utf8') - )) + fs.readFileSync( + path.join(dirname, '..', '..', 'protos/protos.json'), + 'utf8', + ), + ), +); // eslint-disable-next-line @typescript-eslint/no-unused-vars function getTypeDefaultValue(typeName: string, fields: string[]) { - let type = root.lookupType(typeName) as protobuf.Type; - for (const field of fields.slice(0, -1)) { - type = type?.fields[field]?.resolvedType as protobuf.Type; - } - return type?.fields[fields[fields.length - 1]]?.defaultValue ?? null; + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type?.fields[field]?.resolvedType as protobuf.Type; + } + return type?.fields[fields[fields.length - 1]]?.defaultValue ?? null; } function generateSampleMessage(instance: T) { - const filledObject = (instance.constructor as typeof protobuf.Message) - .toObject(instance as protobuf.Message, {defaults: true}); - return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, { defaults: true }); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; } function stubSimpleCall(response?: ResponseType, error?: Error) { - return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); } -function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { - return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +function stubSimpleCallWithCallback( + response?: ResponseType, + error?: Error, +) { + return error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); } -function stubPageStreamingCall(responses?: ResponseType[], error?: Error) { - const pagingStub = sinon.stub(); - if (responses) { - for (let i = 0; i < responses.length; ++i) { - pagingStub.onCall(i).callsArgWith(2, null, responses[i]); - } +function stubPageStreamingCall( + responses?: ResponseType[], + error?: Error, +) { + const pagingStub = sinon.stub(); + if (responses) { + for (let i = 0; i < responses.length; ++i) { + pagingStub.onCall(i).callsArgWith(2, null, responses[i]); } - const transformStub = error ? sinon.stub().callsArgWith(2, error) : pagingStub; - const mockStream = new PassThrough({ - objectMode: true, - transform: transformStub, - }); - // trigger as many responses as needed - if (responses) { - for (let i = 0; i < responses.length; ++i) { - setImmediate(() => { mockStream.write({}); }); - } - setImmediate(() => { mockStream.end(); }); - } else { - setImmediate(() => { mockStream.write({}); }); - setImmediate(() => { mockStream.end(); }); + } + const transformStub = error + ? sinon.stub().callsArgWith(2, error) + : pagingStub; + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + // trigger as many responses as needed + if (responses) { + for (let i = 0; i < responses.length; ++i) { + setImmediate(() => { + mockStream.write({}); + }); } - return sinon.stub().returns(mockStream); + setImmediate(() => { + mockStream.end(); + }); + } else { + setImmediate(() => { + mockStream.write({}); + }); + setImmediate(() => { + mockStream.end(); + }); + } + return sinon.stub().returns(mockStream); } -function stubAsyncIterationCall(responses?: ResponseType[], error?: Error) { - let counter = 0; - const asyncIterable = { - [Symbol.asyncIterator]() { - return { - async next() { - if (error) { - return Promise.reject(error); - } - if (counter >= responses!.length) { - return Promise.resolve({done: true, value: undefined}); - } - return Promise.resolve({done: false, value: responses![counter++]}); - } - }; - } - }; - return sinon.stub().returns(asyncIterable); +function stubAsyncIterationCall( + responses?: ResponseType[], + error?: Error, +) { + let counter = 0; + const asyncIterable = { + [Symbol.asyncIterator]() { + return { + async next() { + if (error) { + return Promise.reject(error); + } + if (counter >= responses!.length) { + return Promise.resolve({ done: true, value: undefined }); + } + return Promise.resolve({ done: false, value: responses![counter++] }); + }, + }; + }, + }; + return sinon.stub().returns(asyncIterable); } describe('v1beta1.TestingClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new testingModule.v1beta1.TestingClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'localhost'); - }); - - it('has universeDomain', () => { - const client = new testingModule.v1beta1.TestingClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); - - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - it('throws DeprecationWarning if static servicePath is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const servicePath = testingModule.v1beta1.TestingClient.servicePath; - assert.strictEqual(servicePath, 'localhost'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = testingModule.v1beta1.TestingClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'localhost'); - assert(stub.called); - stub.restore(); - }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { new testingModule.v1beta1.TestingClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new testingModule.v1beta1.TestingClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'localhost'); + }); - it('has port', () => { - const port = testingModule.v1beta1.TestingClient.port; - assert(port); - assert(typeof port === 'number'); - }); + it('has universeDomain', () => { + const client = new testingModule.v1beta1.TestingClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - it('should create a client with no option', () => { - const client = new testingModule.v1beta1.TestingClient(); - assert(client); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = testingModule.v1beta1.TestingClient.servicePath; + assert.strictEqual(servicePath, 'localhost'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = testingModule.v1beta1.TestingClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'localhost'); + assert(stub.called); + stub.restore(); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new testingModule.v1beta1.TestingClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); + }); - it('should create a client with gRPC fallback', () => { - const client = new testingModule.v1beta1.TestingClient({ - fallback: true, - }); - assert(client); - }); + it('has port', () => { + const port = testingModule.v1beta1.TestingClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('has initialize method and supports deferred initialization', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.testingStub, undefined); - await client.initialize(); - assert(client.testingStub); - }); + it('should create a client with no option', () => { + const client = new testingModule.v1beta1.TestingClient(); + assert(client); + }); - it('has close method for the initialized client', done => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.testingStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('should create a client with gRPC fallback', () => { + const client = new testingModule.v1beta1.TestingClient({ + fallback: true, + }); + assert(client); + }); - it('has close method for the non-initialized client', done => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.testingStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('has initialize method and supports deferred initialization', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.testingStub, undefined); + await client.initialize(); + assert(client.testingStub); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + it('has close method for the initialized client', (done) => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.testingStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId((err?: Error|null, projectId?: string|null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } - }); - }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); + it('has close method for the non-initialized client', (done) => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.testingStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); }); - describe('createSession', () => { - it('invokes createSession without error', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.CreateSessionRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.Session() - ); - client.innerApiCalls.createSession = stubSimpleCall(expectedResponse); - const [response] = await client.createSession(request); - assert.deepStrictEqual(response, expectedResponse); - }); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + }); - it('invokes createSession without error using callback', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.CreateSessionRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.Session() - ); - client.innerApiCalls.createSession = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createSession( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.ISession|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + }); + + describe('createSession', () => { + it('invokes createSession without error', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.CreateSessionRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.Session(), + ); + client.innerApiCalls.createSession = stubSimpleCall(expectedResponse); + const [response] = await client.createSession(request); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes createSession with error', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.CreateSessionRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.createSession = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createSession(request), expectedError); - }); + it('invokes createSession without error using callback', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.CreateSessionRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.Session(), + ); + client.innerApiCalls.createSession = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createSession( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.ISession | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes createSession with closed client', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.CreateSessionRequest() - ); - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createSession(request), expectedError); - }); + it('invokes createSession with error', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.CreateSessionRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.createSession = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.createSession(request), expectedError); }); - describe('getSession', () => { - it('invokes getSession without error', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.GetSessionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.GetSessionRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.Session() - ); - client.innerApiCalls.getSession = stubSimpleCall(expectedResponse); - const [response] = await client.getSession(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getSession as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getSession as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createSession with closed client', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.CreateSessionRequest(), + ); + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.createSession(request), expectedError); + }); + }); + + describe('getSession', () => { + it('invokes getSession without error', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.GetSessionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.GetSessionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.Session(), + ); + client.innerApiCalls.getSession = stubSimpleCall(expectedResponse); + const [response] = await client.getSession(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getSession as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getSession as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getSession without error using callback', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.GetSessionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.GetSessionRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.Session() - ); - client.innerApiCalls.getSession = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getSession( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.ISession|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getSession as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getSession as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getSession without error using callback', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.GetSessionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.GetSessionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.Session(), + ); + client.innerApiCalls.getSession = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getSession( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.ISession | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getSession as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getSession as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getSession with error', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.GetSessionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.GetSessionRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getSession = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getSession(request), expectedError); - const actualRequest = (client.innerApiCalls.getSession as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getSession as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getSession with error', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.GetSessionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.GetSessionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getSession = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getSession(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getSession as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getSession as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getSession with closed client', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.GetSessionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.GetSessionRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getSession(request), expectedError); - }); + it('invokes getSession with closed client', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.GetSessionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.GetSessionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getSession(request), expectedError); + }); + }); + + describe('deleteSession', () => { + it('invokes deleteSession without error', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.DeleteSessionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.DeleteSessionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteSession = stubSimpleCall(expectedResponse); + const [response] = await client.deleteSession(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteSession as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteSession as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('deleteSession', () => { - it('invokes deleteSession without error', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.DeleteSessionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.DeleteSessionRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteSession = stubSimpleCall(expectedResponse); - const [response] = await client.deleteSession(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteSession as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteSession as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteSession without error using callback', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.DeleteSessionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.DeleteSessionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteSession = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteSession( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteSession as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteSession as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteSession without error using callback', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.DeleteSessionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.DeleteSessionRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteSession = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteSession( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteSession as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteSession as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteSession with error', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.DeleteSessionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.DeleteSessionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteSession = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.deleteSession(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteSession as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteSession as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteSession with error', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.DeleteSessionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.DeleteSessionRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteSession = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteSession(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteSession as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteSession as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteSession with closed client', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.DeleteSessionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.DeleteSessionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.deleteSession(request), expectedError); + }); + }); + + describe('reportSession', () => { + it('invokes reportSession without error', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ReportSessionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.ReportSessionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.ReportSessionResponse(), + ); + client.innerApiCalls.reportSession = stubSimpleCall(expectedResponse); + const [response] = await client.reportSession(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.reportSession as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.reportSession as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteSession with closed client', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.DeleteSessionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.DeleteSessionRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteSession(request), expectedError); - }); + it('invokes reportSession without error using callback', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ReportSessionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.ReportSessionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.ReportSessionResponse(), + ); + client.innerApiCalls.reportSession = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.reportSession( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IReportSessionResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.reportSession as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.reportSession as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('reportSession', () => { - it('invokes reportSession without error', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ReportSessionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.ReportSessionRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.ReportSessionResponse() - ); - client.innerApiCalls.reportSession = stubSimpleCall(expectedResponse); - const [response] = await client.reportSession(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.reportSession as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.reportSession as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes reportSession with error', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ReportSessionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.ReportSessionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.reportSession = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.reportSession(request), expectedError); + const actualRequest = ( + client.innerApiCalls.reportSession as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.reportSession as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes reportSession without error using callback', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ReportSessionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.ReportSessionRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.ReportSessionResponse() - ); - client.innerApiCalls.reportSession = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.reportSession( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IReportSessionResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.reportSession as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.reportSession as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes reportSession with closed client', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ReportSessionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.ReportSessionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.reportSession(request), expectedError); + }); + }); + + describe('deleteTest', () => { + it('invokes deleteTest without error', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.DeleteTestRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.DeleteTestRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteTest = stubSimpleCall(expectedResponse); + const [response] = await client.deleteTest(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteTest as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteTest as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes reportSession with error', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ReportSessionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.ReportSessionRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.reportSession = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.reportSession(request), expectedError); - const actualRequest = (client.innerApiCalls.reportSession as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.reportSession as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteTest without error using callback', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.DeleteTestRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.DeleteTestRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteTest = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteTest( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteTest as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteTest as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes reportSession with closed client', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ReportSessionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.ReportSessionRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.reportSession(request), expectedError); - }); + it('invokes deleteTest with error', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.DeleteTestRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.DeleteTestRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteTest = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.deleteTest(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteTest as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteTest as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('deleteTest', () => { - it('invokes deleteTest without error', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.DeleteTestRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.DeleteTestRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteTest = stubSimpleCall(expectedResponse); - const [response] = await client.deleteTest(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteTest as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteTest as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteTest with closed client', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.DeleteTestRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.DeleteTestRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.deleteTest(request), expectedError); + }); + }); + + describe('verifyTest', () => { + it('invokes verifyTest without error', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.VerifyTestRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.VerifyTestRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.VerifyTestResponse(), + ); + client.innerApiCalls.verifyTest = stubSimpleCall(expectedResponse); + const [response] = await client.verifyTest(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.verifyTest as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.verifyTest as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteTest without error using callback', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.DeleteTestRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.DeleteTestRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteTest = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteTest( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteTest as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteTest as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes verifyTest without error using callback', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.VerifyTestRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.VerifyTestRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.VerifyTestResponse(), + ); + client.innerApiCalls.verifyTest = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.verifyTest( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IVerifyTestResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.verifyTest as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.verifyTest as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteTest with error', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.DeleteTestRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.DeleteTestRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteTest = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteTest(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteTest as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteTest as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes verifyTest with error', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.VerifyTestRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.VerifyTestRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.verifyTest = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.verifyTest(request), expectedError); + const actualRequest = ( + client.innerApiCalls.verifyTest as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.verifyTest as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteTest with closed client', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.DeleteTestRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.DeleteTestRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteTest(request), expectedError); - }); + it('invokes verifyTest with closed client', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.VerifyTestRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.VerifyTestRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.verifyTest(request), expectedError); + }); + }); + + describe('listSessions', () => { + it('invokes listSessions without error', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListSessionsRequest(), + ); + const expectedResponse = [ + generateSampleMessage(new protos.google.showcase.v1beta1.Session()), + generateSampleMessage(new protos.google.showcase.v1beta1.Session()), + generateSampleMessage(new protos.google.showcase.v1beta1.Session()), + ]; + client.innerApiCalls.listSessions = stubSimpleCall(expectedResponse); + const [response] = await client.listSessions(request); + assert.deepStrictEqual(response, expectedResponse); }); - describe('verifyTest', () => { - it('invokes verifyTest without error', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.VerifyTestRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.VerifyTestRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.VerifyTestResponse() - ); - client.innerApiCalls.verifyTest = stubSimpleCall(expectedResponse); - const [response] = await client.verifyTest(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.verifyTest as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.verifyTest as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listSessions without error using callback', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListSessionsRequest(), + ); + const expectedResponse = [ + generateSampleMessage(new protos.google.showcase.v1beta1.Session()), + generateSampleMessage(new protos.google.showcase.v1beta1.Session()), + generateSampleMessage(new protos.google.showcase.v1beta1.Session()), + ]; + client.innerApiCalls.listSessions = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listSessions( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.ISession[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes verifyTest without error using callback', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.VerifyTestRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.VerifyTestRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.VerifyTestResponse() - ); - client.innerApiCalls.verifyTest = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.verifyTest( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IVerifyTestResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.verifyTest as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.verifyTest as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listSessions with error', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListSessionsRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.listSessions = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listSessions(request), expectedError); + }); - it('invokes verifyTest with error', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.VerifyTestRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.VerifyTestRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.verifyTest = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.verifyTest(request), expectedError); - const actualRequest = (client.innerApiCalls.verifyTest as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.verifyTest as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes listSessionsStream without error', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListSessionsRequest(), + ); + const expectedResponse = [ + generateSampleMessage(new protos.google.showcase.v1beta1.Session()), + generateSampleMessage(new protos.google.showcase.v1beta1.Session()), + generateSampleMessage(new protos.google.showcase.v1beta1.Session()), + ]; + client.descriptors.page.listSessions.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listSessionsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.showcase.v1beta1.Session[] = []; + stream.on( + 'data', + (response: protos.google.showcase.v1beta1.Session) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); }); - - it('invokes verifyTest with closed client', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.VerifyTestRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.VerifyTestRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.verifyTest(request), expectedError); + stream.on('error', (err: Error) => { + reject(err); }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listSessions.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listSessions, request), + ); }); - describe('listSessions', () => { - it('invokes listSessions without error', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListSessionsRequest() - );const expectedResponse = [ - generateSampleMessage(new protos.google.showcase.v1beta1.Session()), - generateSampleMessage(new protos.google.showcase.v1beta1.Session()), - generateSampleMessage(new protos.google.showcase.v1beta1.Session()), - ]; - client.innerApiCalls.listSessions = stubSimpleCall(expectedResponse); - const [response] = await client.listSessions(request); - assert.deepStrictEqual(response, expectedResponse); - }); - - it('invokes listSessions without error using callback', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListSessionsRequest() - );const expectedResponse = [ - generateSampleMessage(new protos.google.showcase.v1beta1.Session()), - generateSampleMessage(new protos.google.showcase.v1beta1.Session()), - generateSampleMessage(new protos.google.showcase.v1beta1.Session()), - ]; - client.innerApiCalls.listSessions = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listSessions( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.ISession[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); + it('invokes listSessionsStream with error', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListSessionsRequest(), + ); + const expectedError = new Error('expected'); + client.descriptors.page.listSessions.createStream = stubPageStreamingCall( + undefined, + expectedError, + ); + const stream = client.listSessionsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.showcase.v1beta1.Session[] = []; + stream.on( + 'data', + (response: protos.google.showcase.v1beta1.Session) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); }); - - it('invokes listSessions with error', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListSessionsRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.listSessions = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listSessions(request), expectedError); + stream.on('error', (err: Error) => { + reject(err); }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listSessions.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listSessions, request), + ); + }); - it('invokes listSessionsStream without error', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListSessionsRequest() - ); - const expectedResponse = [ - generateSampleMessage(new protos.google.showcase.v1beta1.Session()), - generateSampleMessage(new protos.google.showcase.v1beta1.Session()), - generateSampleMessage(new protos.google.showcase.v1beta1.Session()), - ]; - client.descriptors.page.listSessions.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listSessionsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.showcase.v1beta1.Session[] = []; - stream.on('data', (response: protos.google.showcase.v1beta1.Session) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.listSessions.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listSessions, request)); - }); + it('uses async iteration with listSessions without error', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListSessionsRequest(), + ); + const expectedResponse = [ + generateSampleMessage(new protos.google.showcase.v1beta1.Session()), + generateSampleMessage(new protos.google.showcase.v1beta1.Session()), + generateSampleMessage(new protos.google.showcase.v1beta1.Session()), + ]; + client.descriptors.page.listSessions.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.showcase.v1beta1.ISession[] = []; + const iterable = client.listSessionsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listSessions.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + }); - it('invokes listSessionsStream with error', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListSessionsRequest() - ); - const expectedError = new Error('expected'); - client.descriptors.page.listSessions.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listSessionsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.showcase.v1beta1.Session[] = []; - stream.on('data', (response: protos.google.showcase.v1beta1.Session) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listSessions.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listSessions, request)); - }); + it('uses async iteration with listSessions with error', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListSessionsRequest(), + ); + const expectedError = new Error('expected'); + client.descriptors.page.listSessions.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listSessionsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.showcase.v1beta1.ISession[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listSessions.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + }); + }); + + describe('listTests', () => { + it('invokes listTests without error', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListTestsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.ListTestsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.showcase.v1beta1.Test()), + generateSampleMessage(new protos.google.showcase.v1beta1.Test()), + generateSampleMessage(new protos.google.showcase.v1beta1.Test()), + ]; + client.innerApiCalls.listTests = stubSimpleCall(expectedResponse); + const [response] = await client.listTests(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listTests as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listTests as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('uses async iteration with listSessions without error', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListSessionsRequest() - ); - const expectedResponse = [ - generateSampleMessage(new protos.google.showcase.v1beta1.Session()), - generateSampleMessage(new protos.google.showcase.v1beta1.Session()), - generateSampleMessage(new protos.google.showcase.v1beta1.Session()), - ]; - client.descriptors.page.listSessions.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.showcase.v1beta1.ISession[] = []; - const iterable = client.listSessionsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); + it('invokes listTests without error using callback', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListTestsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.ListTestsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.showcase.v1beta1.Test()), + generateSampleMessage(new protos.google.showcase.v1beta1.Test()), + generateSampleMessage(new protos.google.showcase.v1beta1.Test()), + ]; + client.innerApiCalls.listTests = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listTests( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.ITest[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listSessions.asyncIterate as SinonStub) - .getCall(0).args[1], request); - }); + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listTests as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listTests as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('uses async iteration with listSessions with error', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListSessionsRequest() - ); - const expectedError = new Error('expected'); - client.descriptors.page.listSessions.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listSessionsAsync(request); - await assert.rejects(async () => { - const responses: protos.google.showcase.v1beta1.ISession[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listSessions.asyncIterate as SinonStub) - .getCall(0).args[1], request); - }); + it('invokes listTests with error', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListTestsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.ListTestsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listTests = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.listTests(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listTests as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listTests as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('listTests', () => { - it('invokes listTests without error', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListTestsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.ListTestsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.showcase.v1beta1.Test()), - generateSampleMessage(new protos.google.showcase.v1beta1.Test()), - generateSampleMessage(new protos.google.showcase.v1beta1.Test()), - ]; - client.innerApiCalls.listTests = stubSimpleCall(expectedResponse); - const [response] = await client.listTests(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listTests as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listTests as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes listTestsStream without error', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListTestsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.ListTestsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.showcase.v1beta1.Test()), + generateSampleMessage(new protos.google.showcase.v1beta1.Test()), + generateSampleMessage(new protos.google.showcase.v1beta1.Test()), + ]; + client.descriptors.page.listTests.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listTestsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.showcase.v1beta1.Test[] = []; + stream.on('data', (response: protos.google.showcase.v1beta1.Test) => { + responses.push(response); }); - - it('invokes listTests without error using callback', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListTestsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.ListTestsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.showcase.v1beta1.Test()), - generateSampleMessage(new protos.google.showcase.v1beta1.Test()), - generateSampleMessage(new protos.google.showcase.v1beta1.Test()), - ]; - client.innerApiCalls.listTests = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listTests( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.ITest[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listTests as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listTests as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + stream.on('end', () => { + resolve(responses); }); - - it('invokes listTests with error', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListTestsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.ListTestsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listTests = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listTests(request), expectedError); - const actualRequest = (client.innerApiCalls.listTests as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listTests as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + stream.on('error', (err: Error) => { + reject(err); }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listTests.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listTests, request), + ); + assert( + (client.descriptors.page.listTests.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('invokes listTestsStream without error', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListTestsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.ListTestsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.showcase.v1beta1.Test()), - generateSampleMessage(new protos.google.showcase.v1beta1.Test()), - generateSampleMessage(new protos.google.showcase.v1beta1.Test()), - ]; - client.descriptors.page.listTests.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listTestsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.showcase.v1beta1.Test[] = []; - stream.on('data', (response: protos.google.showcase.v1beta1.Test) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.listTests.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listTests, request)); - assert( - (client.descriptors.page.listTests.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); + it('invokes listTestsStream with error', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListTestsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.ListTestsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listTests.createStream = stubPageStreamingCall( + undefined, + expectedError, + ); + const stream = client.listTestsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.showcase.v1beta1.Test[] = []; + stream.on('data', (response: protos.google.showcase.v1beta1.Test) => { + responses.push(response); }); - - it('invokes listTestsStream with error', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListTestsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.ListTestsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listTests.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listTestsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.showcase.v1beta1.Test[] = []; - stream.on('data', (response: protos.google.showcase.v1beta1.Test) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listTests.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listTests, request)); - assert( - (client.descriptors.page.listTests.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); + stream.on('end', () => { + resolve(responses); }); - - it('uses async iteration with listTests without error', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListTestsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.ListTestsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.showcase.v1beta1.Test()), - generateSampleMessage(new protos.google.showcase.v1beta1.Test()), - generateSampleMessage(new protos.google.showcase.v1beta1.Test()), - ]; - client.descriptors.page.listTests.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.showcase.v1beta1.ITest[] = []; - const iterable = client.listTestsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listTests.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listTests.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); + stream.on('error', (err: Error) => { + reject(err); }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listTests.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listTests, request), + ); + assert( + (client.descriptors.page.listTests.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('uses async iteration with listTests with error', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListTestsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.ListTestsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listTests.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listTestsAsync(request); - await assert.rejects(async () => { - const responses: protos.google.showcase.v1beta1.ITest[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listTests.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listTests.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listTests without error', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListTestsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.ListTestsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.showcase.v1beta1.Test()), + generateSampleMessage(new protos.google.showcase.v1beta1.Test()), + generateSampleMessage(new protos.google.showcase.v1beta1.Test()), + ]; + client.descriptors.page.listTests.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.showcase.v1beta1.ITest[] = []; + const iterable = client.listTestsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + (client.descriptors.page.listTests.asyncIterate as SinonStub).getCall(0) + .args[1], + request, + ); + assert( + (client.descriptors.page.listTests.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); }); - describe('Path templates', () => { - - describe('blueprint', () => { - const fakePath = "/rendered/path/blueprint"; - const expectedParameters = { - session: "sessionValue", - test: "testValue", - blueprint: "blueprintValue", - }; - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.blueprintPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.blueprintPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('blueprintPath', () => { - const result = client.blueprintPath("sessionValue", "testValue", "blueprintValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.blueprintPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchSessionFromBlueprintName', () => { - const result = client.matchSessionFromBlueprintName(fakePath); - assert.strictEqual(result, "sessionValue"); - assert((client.pathTemplates.blueprintPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchTestFromBlueprintName', () => { - const result = client.matchTestFromBlueprintName(fakePath); - assert.strictEqual(result, "testValue"); - assert((client.pathTemplates.blueprintPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBlueprintFromBlueprintName', () => { - const result = client.matchBlueprintFromBlueprintName(fakePath); - assert.strictEqual(result, "blueprintValue"); - assert((client.pathTemplates.blueprintPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('uses async iteration with listTests with error', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListTestsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.ListTestsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listTests.asyncIterate = stubAsyncIterationCall( + undefined, + expectedError, + ); + const iterable = client.listTestsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.showcase.v1beta1.ITest[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + (client.descriptors.page.listTests.asyncIterate as SinonStub).getCall(0) + .args[1], + request, + ); + assert( + (client.descriptors.page.listTests.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + }); + + describe('Path templates', () => { + describe('blueprint', () => { + const fakePath = '/rendered/path/blueprint'; + const expectedParameters = { + session: 'sessionValue', + test: 'testValue', + blueprint: 'blueprintValue', + }; + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.blueprintPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.blueprintPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('blueprintPath', () => { + const result = client.blueprintPath( + 'sessionValue', + 'testValue', + 'blueprintValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.blueprintPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchSessionFromBlueprintName', () => { + const result = client.matchSessionFromBlueprintName(fakePath); + assert.strictEqual(result, 'sessionValue'); + assert( + (client.pathTemplates.blueprintPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchTestFromBlueprintName', () => { + const result = client.matchTestFromBlueprintName(fakePath); + assert.strictEqual(result, 'testValue'); + assert( + (client.pathTemplates.blueprintPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBlueprintFromBlueprintName', () => { + const result = client.matchBlueprintFromBlueprintName(fakePath); + assert.strictEqual(result, 'blueprintValue'); + assert( + (client.pathTemplates.blueprintPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('room', () => { - const fakePath = "/rendered/path/room"; - const expectedParameters = { - room: "roomValue", - }; - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.roomPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.roomPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('roomPath', () => { - const result = client.roomPath("roomValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.roomPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchRoomFromRoomName', () => { - const result = client.matchRoomFromRoomName(fakePath); - assert.strictEqual(result, "roomValue"); - assert((client.pathTemplates.roomPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('room', () => { + const fakePath = '/rendered/path/room'; + const expectedParameters = { + room: 'roomValue', + }; + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.roomPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.roomPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('roomPath', () => { + const result = client.roomPath('roomValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.roomPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchRoomFromRoomName', () => { + const result = client.matchRoomFromRoomName(fakePath); + assert.strictEqual(result, 'roomValue'); + assert( + (client.pathTemplates.roomPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('roomBlurb', () => { - const fakePath = "/rendered/path/roomBlurb"; - const expectedParameters = { - room: "roomValue", - blurb: "blurbValue", - }; - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.roomBlurbPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.roomBlurbPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('roomBlurbPath', () => { - const result = client.roomBlurbPath("roomValue", "blurbValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.roomBlurbPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchRoomFromRoomBlurbName', () => { - const result = client.matchRoomFromRoomBlurbName(fakePath); - assert.strictEqual(result, "roomValue"); - assert((client.pathTemplates.roomBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBlurbFromRoomBlurbName', () => { - const result = client.matchBlurbFromRoomBlurbName(fakePath); - assert.strictEqual(result, "blurbValue"); - assert((client.pathTemplates.roomBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('roomBlurb', () => { + const fakePath = '/rendered/path/roomBlurb'; + const expectedParameters = { + room: 'roomValue', + blurb: 'blurbValue', + }; + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.roomBlurbPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.roomBlurbPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('roomBlurbPath', () => { + const result = client.roomBlurbPath('roomValue', 'blurbValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.roomBlurbPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchRoomFromRoomBlurbName', () => { + const result = client.matchRoomFromRoomBlurbName(fakePath); + assert.strictEqual(result, 'roomValue'); + assert( + (client.pathTemplates.roomBlurbPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBlurbFromRoomBlurbName', () => { + const result = client.matchBlurbFromRoomBlurbName(fakePath); + assert.strictEqual(result, 'blurbValue'); + assert( + (client.pathTemplates.roomBlurbPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('roomBlurbsLegacyRoomBlurb', () => { - const fakePath = "/rendered/path/roomBlurbsLegacyRoomBlurb"; - const expectedParameters = { - room: "roomValue", - legacy_room: "legacyRoomValue", - blurb: "blurbValue", - }; - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('roomBlurbsLegacyRoomBlurbPath', () => { - const result = client.roomBlurbsLegacyRoomBlurbPath("roomValue", "legacyRoomValue", "blurbValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchRoomFromRoomBlurbsLegacyRoomBlurbName', () => { - const result = client.matchRoomFromRoomBlurbsLegacyRoomBlurbName(fakePath); - assert.strictEqual(result, "roomValue"); - assert((client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName', () => { - const result = client.matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName(fakePath); - assert.strictEqual(result, "legacyRoomValue"); - assert((client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBlurbFromRoomBlurbsLegacyRoomBlurbName', () => { - const result = client.matchBlurbFromRoomBlurbsLegacyRoomBlurbName(fakePath); - assert.strictEqual(result, "blurbValue"); - assert((client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('roomBlurbsLegacyRoomBlurb', () => { + const fakePath = '/rendered/path/roomBlurbsLegacyRoomBlurb'; + const expectedParameters = { + room: 'roomValue', + legacy_room: 'legacyRoomValue', + blurb: 'blurbValue', + }; + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('roomBlurbsLegacyRoomBlurbPath', () => { + const result = client.roomBlurbsLegacyRoomBlurbPath( + 'roomValue', + 'legacyRoomValue', + 'blurbValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchRoomFromRoomBlurbsLegacyRoomBlurbName', () => { + const result = + client.matchRoomFromRoomBlurbsLegacyRoomBlurbName(fakePath); + assert.strictEqual(result, 'roomValue'); + assert( + ( + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName', () => { + const result = + client.matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName(fakePath); + assert.strictEqual(result, 'legacyRoomValue'); + assert( + ( + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBlurbFromRoomBlurbsLegacyRoomBlurbName', () => { + const result = + client.matchBlurbFromRoomBlurbsLegacyRoomBlurbName(fakePath); + assert.strictEqual(result, 'blurbValue'); + assert( + ( + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('sequence', () => { - const fakePath = "/rendered/path/sequence"; - const expectedParameters = { - sequence: "sequenceValue", - }; - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.sequencePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.sequencePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('sequencePath', () => { - const result = client.sequencePath("sequenceValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.sequencePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchSequenceFromSequenceName', () => { - const result = client.matchSequenceFromSequenceName(fakePath); - assert.strictEqual(result, "sequenceValue"); - assert((client.pathTemplates.sequencePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('sequence', () => { + const fakePath = '/rendered/path/sequence'; + const expectedParameters = { + sequence: 'sequenceValue', + }; + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.sequencePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.sequencePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('sequencePath', () => { + const result = client.sequencePath('sequenceValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.sequencePathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchSequenceFromSequenceName', () => { + const result = client.matchSequenceFromSequenceName(fakePath); + assert.strictEqual(result, 'sequenceValue'); + assert( + (client.pathTemplates.sequencePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('sequenceReport', () => { - const fakePath = "/rendered/path/sequenceReport"; - const expectedParameters = { - sequence: "sequenceValue", - }; - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.sequenceReportPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.sequenceReportPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('sequenceReportPath', () => { - const result = client.sequenceReportPath("sequenceValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.sequenceReportPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchSequenceFromSequenceReportName', () => { - const result = client.matchSequenceFromSequenceReportName(fakePath); - assert.strictEqual(result, "sequenceValue"); - assert((client.pathTemplates.sequenceReportPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('sequenceReport', () => { + const fakePath = '/rendered/path/sequenceReport'; + const expectedParameters = { + sequence: 'sequenceValue', + }; + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.sequenceReportPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.sequenceReportPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('sequenceReportPath', () => { + const result = client.sequenceReportPath('sequenceValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.sequenceReportPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchSequenceFromSequenceReportName', () => { + const result = client.matchSequenceFromSequenceReportName(fakePath); + assert.strictEqual(result, 'sequenceValue'); + assert( + (client.pathTemplates.sequenceReportPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('session', () => { - const fakePath = "/rendered/path/session"; - const expectedParameters = { - session: "sessionValue", - }; - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.sessionPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.sessionPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('sessionPath', () => { - const result = client.sessionPath("sessionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.sessionPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchSessionFromSessionName', () => { - const result = client.matchSessionFromSessionName(fakePath); - assert.strictEqual(result, "sessionValue"); - assert((client.pathTemplates.sessionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('session', () => { + const fakePath = '/rendered/path/session'; + const expectedParameters = { + session: 'sessionValue', + }; + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.sessionPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.sessionPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('sessionPath', () => { + const result = client.sessionPath('sessionValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.sessionPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchSessionFromSessionName', () => { + const result = client.matchSessionFromSessionName(fakePath); + assert.strictEqual(result, 'sessionValue'); + assert( + (client.pathTemplates.sessionPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('test', () => { - const fakePath = "/rendered/path/test"; - const expectedParameters = { - session: "sessionValue", - test: "testValue", - }; - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.testPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.testPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('testPath', () => { - const result = client.testPath("sessionValue", "testValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.testPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchSessionFromTestName', () => { - const result = client.matchSessionFromTestName(fakePath); - assert.strictEqual(result, "sessionValue"); - assert((client.pathTemplates.testPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchTestFromTestName', () => { - const result = client.matchTestFromTestName(fakePath); - assert.strictEqual(result, "testValue"); - assert((client.pathTemplates.testPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('test', () => { + const fakePath = '/rendered/path/test'; + const expectedParameters = { + session: 'sessionValue', + test: 'testValue', + }; + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.testPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.testPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('testPath', () => { + const result = client.testPath('sessionValue', 'testValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.testPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchSessionFromTestName', () => { + const result = client.matchSessionFromTestName(fakePath); + assert.strictEqual(result, 'sessionValue'); + assert( + (client.pathTemplates.testPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchTestFromTestName', () => { + const result = client.matchTestFromTestName(fakePath); + assert.strictEqual(result, 'testValue'); + assert( + (client.pathTemplates.testPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('user', () => { - const fakePath = "/rendered/path/user"; - const expectedParameters = { - user: "userValue", - }; - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.userPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.userPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('userPath', () => { - const result = client.userPath("userValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.userPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchUserFromUserName', () => { - const result = client.matchUserFromUserName(fakePath); - assert.strictEqual(result, "userValue"); - assert((client.pathTemplates.userPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('user', () => { + const fakePath = '/rendered/path/user'; + const expectedParameters = { + user: 'userValue', + }; + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.userPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.userPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('userPath', () => { + const result = client.userPath('userValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.userPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchUserFromUserName', () => { + const result = client.matchUserFromUserName(fakePath); + assert.strictEqual(result, 'userValue'); + assert( + (client.pathTemplates.userPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('userProfileBlurb', () => { - const fakePath = "/rendered/path/userProfileBlurb"; - const expectedParameters = { - user: "userValue", - blurb: "blurbValue", - }; - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.userProfileBlurbPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.userProfileBlurbPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('userProfileBlurbPath', () => { - const result = client.userProfileBlurbPath("userValue", "blurbValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.userProfileBlurbPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchUserFromUserProfileBlurbName', () => { - const result = client.matchUserFromUserProfileBlurbName(fakePath); - assert.strictEqual(result, "userValue"); - assert((client.pathTemplates.userProfileBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBlurbFromUserProfileBlurbName', () => { - const result = client.matchBlurbFromUserProfileBlurbName(fakePath); - assert.strictEqual(result, "blurbValue"); - assert((client.pathTemplates.userProfileBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('userProfileBlurb', () => { + const fakePath = '/rendered/path/userProfileBlurb'; + const expectedParameters = { + user: 'userValue', + blurb: 'blurbValue', + }; + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.userProfileBlurbPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.userProfileBlurbPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('userProfileBlurbPath', () => { + const result = client.userProfileBlurbPath('userValue', 'blurbValue'); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.userProfileBlurbPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchUserFromUserProfileBlurbName', () => { + const result = client.matchUserFromUserProfileBlurbName(fakePath); + assert.strictEqual(result, 'userValue'); + assert( + (client.pathTemplates.userProfileBlurbPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBlurbFromUserProfileBlurbName', () => { + const result = client.matchBlurbFromUserProfileBlurbName(fakePath); + assert.strictEqual(result, 'blurbValue'); + assert( + (client.pathTemplates.userProfileBlurbPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('userProfileBlurbsLegacyUserBlurb', () => { - const fakePath = "/rendered/path/userProfileBlurbsLegacyUserBlurb"; - const expectedParameters = { - user: "userValue", - legacy_user: "legacyUserValue", - blurb: "blurbValue", - }; - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('userProfileBlurbsLegacyUserBlurbPath', () => { - const result = client.userProfileBlurbsLegacyUserBlurbPath("userValue", "legacyUserValue", "blurbValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchUserFromUserProfileBlurbsLegacyUserBlurbName', () => { - const result = client.matchUserFromUserProfileBlurbsLegacyUserBlurbName(fakePath); - assert.strictEqual(result, "userValue"); - assert((client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName', () => { - const result = client.matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName(fakePath); - assert.strictEqual(result, "legacyUserValue"); - assert((client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBlurbFromUserProfileBlurbsLegacyUserBlurbName', () => { - const result = client.matchBlurbFromUserProfileBlurbsLegacyUserBlurbName(fakePath); - assert.strictEqual(result, "blurbValue"); - assert((client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('userProfileBlurbsLegacyUserBlurb', () => { + const fakePath = '/rendered/path/userProfileBlurbsLegacyUserBlurb'; + const expectedParameters = { + user: 'userValue', + legacy_user: 'legacyUserValue', + blurb: 'blurbValue', + }; + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('userProfileBlurbsLegacyUserBlurbPath', () => { + const result = client.userProfileBlurbsLegacyUserBlurbPath( + 'userValue', + 'legacyUserValue', + 'blurbValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchUserFromUserProfileBlurbsLegacyUserBlurbName', () => { + const result = + client.matchUserFromUserProfileBlurbsLegacyUserBlurbName(fakePath); + assert.strictEqual(result, 'userValue'); + assert( + ( + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName', () => { + const result = + client.matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName( + fakePath, + ); + assert.strictEqual(result, 'legacyUserValue'); + assert( + ( + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBlurbFromUserProfileBlurbsLegacyUserBlurbName', () => { + const result = + client.matchBlurbFromUserProfileBlurbsLegacyUserBlurbName(fakePath); + assert.strictEqual(result, 'blurbValue'); + assert( + ( + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/core/generator/gapic-generator-typescript/baselines/disable-packing-test/src/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/disable-packing-test/src/index.ts.baseline index 55fd8ef14d16..9d0e7c754471 100644 --- a/core/generator/gapic-generator-typescript/baselines/disable-packing-test/src/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/disable-packing-test/src/index.ts.baseline @@ -29,7 +29,23 @@ const SequenceServiceClient = v1beta1.SequenceServiceClient; type SequenceServiceClient = v1beta1.SequenceServiceClient; const TestingClient = v1beta1.TestingClient; type TestingClient = v1beta1.TestingClient; -export {v1beta1, ComplianceClient, EchoClient, IdentityClient, MessagingClient, SequenceServiceClient, TestingClient}; -export default {v1beta1, ComplianceClient, EchoClient, IdentityClient, MessagingClient, SequenceServiceClient, TestingClient}; +export { + v1beta1, + ComplianceClient, + EchoClient, + IdentityClient, + MessagingClient, + SequenceServiceClient, + TestingClient, +}; +export default { + v1beta1, + ComplianceClient, + EchoClient, + IdentityClient, + MessagingClient, + SequenceServiceClient, + TestingClient, +}; import * as protos from '../protos/protos'; -export {protos} +export { protos }; diff --git a/core/generator/gapic-generator-typescript/baselines/disable-packing-test/src/v1beta1/compliance_client.ts.baseline b/core/generator/gapic-generator-typescript/baselines/disable-packing-test/src/v1beta1/compliance_client.ts.baseline index 74362bb329a2..b5990a214d58 100644 --- a/core/generator/gapic-generator-typescript/baselines/disable-packing-test/src/v1beta1/compliance_client.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/disable-packing-test/src/v1beta1/compliance_client.ts.baseline @@ -18,11 +18,16 @@ /* global window */ import type * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions} from 'google-gax'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, +} from 'google-gax'; import * as protos from '../../protos/protos'; import jsonProtos = require('../../protos/protos.json'); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; /** * Client JSON configuration object, loaded from @@ -46,7 +51,7 @@ export class ComplianceClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('showcase'); @@ -59,9 +64,9 @@ export class ComplianceClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; - complianceStub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; + complianceStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of ComplianceClient. @@ -102,21 +107,42 @@ export class ComplianceClient { * const client = new ComplianceClient({fallback: true}, gax); * ``` */ - constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { // Ensure that options include all the required fields. const staticMembers = this.constructor as typeof ComplianceClient; - if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { - throw new Error('Please set either universe_domain or universeDomain, but not both.'); + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); } - const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; - this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; this._servicePath = 'localhost'; - const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; - const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. if (servicePath !== this._servicePath && !('scopes' in opts)) { @@ -138,7 +164,7 @@ export class ComplianceClient { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; @@ -152,10 +178,7 @@ export class ComplianceClient { } // Determine the client header string. - const clientHeader = [ - `gax/${this._gaxModule.version}`, - `gapic/${version}`, - ]; + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/${process.versions.node}`); } else { @@ -177,44 +200,44 @@ export class ComplianceClient { // Create useful helper objects for these. this.pathTemplates = { blueprintPathTemplate: new this._gaxModule.PathTemplate( - 'sessions/{session}/tests/{test}/blueprints/{blueprint}' - ), - roomPathTemplate: new this._gaxModule.PathTemplate( - 'rooms/{room}' + 'sessions/{session}/tests/{test}/blueprints/{blueprint}', ), + roomPathTemplate: new this._gaxModule.PathTemplate('rooms/{room}'), roomBlurbPathTemplate: new this._gaxModule.PathTemplate( - 'rooms/{room}/blurbs/{blurb}' + 'rooms/{room}/blurbs/{blurb}', ), roomBlurbsLegacyRoomBlurbPathTemplate: new this._gaxModule.PathTemplate( - 'rooms/{room}/blurbs/legacy/{legacy_room}.{blurb}' + 'rooms/{room}/blurbs/legacy/{legacy_room}.{blurb}', ), sequencePathTemplate: new this._gaxModule.PathTemplate( - 'sequences/{sequence}' + 'sequences/{sequence}', ), sequenceReportPathTemplate: new this._gaxModule.PathTemplate( - 'sequences/{sequence}/sequenceReport' + 'sequences/{sequence}/sequenceReport', ), sessionPathTemplate: new this._gaxModule.PathTemplate( - 'sessions/{session}' + 'sessions/{session}', ), testPathTemplate: new this._gaxModule.PathTemplate( - 'sessions/{session}/tests/{test}' - ), - userPathTemplate: new this._gaxModule.PathTemplate( - 'users/{user}' + 'sessions/{session}/tests/{test}', ), + userPathTemplate: new this._gaxModule.PathTemplate('users/{user}'), userProfileBlurbPathTemplate: new this._gaxModule.PathTemplate( - 'users/{user}/profile/blurbs/{blurb}' - ), - userProfileBlurbsLegacyUserBlurbPathTemplate: new this._gaxModule.PathTemplate( - 'users/{user}/profile/blurbs/legacy/{legacy_user}~{blurb}' + 'users/{user}/profile/blurbs/{blurb}', ), + userProfileBlurbsLegacyUserBlurbPathTemplate: + new this._gaxModule.PathTemplate( + 'users/{user}/profile/blurbs/legacy/{legacy_user}~{blurb}', + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.showcase.v1beta1.Compliance', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.showcase.v1beta1.Compliance', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + { 'x-goog-api-client': clientHeader.join(' ') }, + ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -245,36 +268,51 @@ export class ComplianceClient { // Put together the "service stub" for // google.showcase.v1beta1.Compliance. this.complianceStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.showcase.v1beta1.Compliance') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.showcase.v1beta1.Compliance', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.showcase.v1beta1.Compliance, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts, + this._providedCustomServicePath, + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const complianceStubMethods = - ['repeatDataBody', 'repeatDataBodyInfo', 'repeatDataQuery', 'repeatDataSimplePath', 'repeatDataPathResource', 'repeatDataPathTrailingResource', 'repeatDataBodyPut', 'repeatDataBodyPatch', 'getEnum', 'verifyEnum']; + const complianceStubMethods = [ + 'repeatDataBody', + 'repeatDataBodyInfo', + 'repeatDataQuery', + 'repeatDataSimplePath', + 'repeatDataPathResource', + 'repeatDataPathTrailingResource', + 'repeatDataBodyPut', + 'repeatDataBodyPatch', + 'getEnum', + 'verifyEnum', + ]; for (const methodName of complianceStubMethods) { const callPromise = this.complianceStub.then( - stub => (...args: Array<{}>) => { - if (this._terminated) { - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error|null|undefined) => () => { + (stub) => + (...args: Array<{}>) => { + if (this._terminated) { + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { throw err; - }); + }, + ); - const descriptor = - undefined; + const descriptor = undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -289,8 +327,14 @@ export class ComplianceClient { * @returns {string} The DNS address for this service. */ static get servicePath() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'localhost'; } @@ -301,8 +345,14 @@ export class ComplianceClient { * @returns {string} The DNS address for this service. */ static get apiEndpoint() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'localhost'; } @@ -342,8 +392,9 @@ export class ComplianceClient { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId(callback?: Callback): - Promise|void { + getProjectId( + callback?: Callback, + ): Promise | void { if (callback) { this.auth.getProjectId(callback); return; @@ -354,1036 +405,1349 @@ export class ComplianceClient { // ------------------- // -- Service calls -- // ------------------- -/** - * This method echoes the ComplianceData request. This method exercises - * sending the entire request object in the REST body. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * @param {google.showcase.v1beta1.ComplianceData} request.info - * @param {boolean} request.serverVerify - * If true, the server will verify that the received request matches - * the request with the same name in the compliance test suite. - * @param {string} request.intendedBindingUri - * The URI template this request is expected to be bound to server-side. - * @param {number} request.fInt32 - * Some top level fields, to test that these are encoded correctly - * in query params. - * @param {number} request.fInt64 - * @param {number} request.fDouble - * @param {number} request.pInt32 - * @param {number} request.pInt64 - * @param {number} request.pDouble - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.RepeatResponse|RepeatResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/compliance.repeat_data_body.js - * region_tag:localhost_v1beta1_generated_Compliance_RepeatDataBody_async - */ + /** + * This method echoes the ComplianceData request. This method exercises + * sending the entire request object in the REST body. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * @param {google.showcase.v1beta1.ComplianceData} request.info + * @param {boolean} request.serverVerify + * If true, the server will verify that the received request matches + * the request with the same name in the compliance test suite. + * @param {string} request.intendedBindingUri + * The URI template this request is expected to be bound to server-side. + * @param {number} request.fInt32 + * Some top level fields, to test that these are encoded correctly + * in query params. + * @param {number} request.fInt64 + * @param {number} request.fDouble + * @param {number} request.pInt32 + * @param {number} request.pInt64 + * @param {number} request.pDouble + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.RepeatResponse|RepeatResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/compliance.repeat_data_body.js + * region_tag:localhost_v1beta1_generated_Compliance_RepeatDataBody_async + */ repeatDataBody( - request?: protos.google.showcase.v1beta1.IRepeatRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IRepeatRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | undefined, + {} | undefined, + ] + >; repeatDataBody( - request: protos.google.showcase.v1beta1.IRepeatRequest, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IRepeatRequest, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + ): void; repeatDataBody( - request: protos.google.showcase.v1beta1.IRepeatRequest, - callback: Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IRepeatRequest, + callback: Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + ): void; repeatDataBody( - request?: protos.google.showcase.v1beta1.IRepeatRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.showcase.v1beta1.IRepeatRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|undefined, {}|undefined - ]>|void { + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('repeatDataBody request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('repeatDataBody response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.repeatDataBody(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|undefined, - {}|undefined - ]) => { - this._log.info('repeatDataBody response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .repeatDataBody(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | undefined, + {} | undefined, + ]) => { + this._log.info('repeatDataBody response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * This method echoes the ComplianceData request. This method exercises - * sending the a message-type field in the REST body. Per AIP-127, only - * top-level, non-repeated fields can be sent this way. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * @param {google.showcase.v1beta1.ComplianceData} request.info - * @param {boolean} request.serverVerify - * If true, the server will verify that the received request matches - * the request with the same name in the compliance test suite. - * @param {string} request.intendedBindingUri - * The URI template this request is expected to be bound to server-side. - * @param {number} request.fInt32 - * Some top level fields, to test that these are encoded correctly - * in query params. - * @param {number} request.fInt64 - * @param {number} request.fDouble - * @param {number} request.pInt32 - * @param {number} request.pInt64 - * @param {number} request.pDouble - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.RepeatResponse|RepeatResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/compliance.repeat_data_body_info.js - * region_tag:localhost_v1beta1_generated_Compliance_RepeatDataBodyInfo_async - */ + /** + * This method echoes the ComplianceData request. This method exercises + * sending the a message-type field in the REST body. Per AIP-127, only + * top-level, non-repeated fields can be sent this way. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * @param {google.showcase.v1beta1.ComplianceData} request.info + * @param {boolean} request.serverVerify + * If true, the server will verify that the received request matches + * the request with the same name in the compliance test suite. + * @param {string} request.intendedBindingUri + * The URI template this request is expected to be bound to server-side. + * @param {number} request.fInt32 + * Some top level fields, to test that these are encoded correctly + * in query params. + * @param {number} request.fInt64 + * @param {number} request.fDouble + * @param {number} request.pInt32 + * @param {number} request.pInt64 + * @param {number} request.pDouble + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.RepeatResponse|RepeatResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/compliance.repeat_data_body_info.js + * region_tag:localhost_v1beta1_generated_Compliance_RepeatDataBodyInfo_async + */ repeatDataBodyInfo( - request?: protos.google.showcase.v1beta1.IRepeatRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IRepeatRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | undefined, + {} | undefined, + ] + >; repeatDataBodyInfo( - request: protos.google.showcase.v1beta1.IRepeatRequest, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IRepeatRequest, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + ): void; repeatDataBodyInfo( - request: protos.google.showcase.v1beta1.IRepeatRequest, - callback: Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IRepeatRequest, + callback: Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + ): void; repeatDataBodyInfo( - request?: protos.google.showcase.v1beta1.IRepeatRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.showcase.v1beta1.IRepeatRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|undefined, {}|undefined - ]>|void { + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('repeatDataBodyInfo request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('repeatDataBodyInfo response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.repeatDataBodyInfo(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|undefined, - {}|undefined - ]) => { - this._log.info('repeatDataBodyInfo response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .repeatDataBodyInfo(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | undefined, + {} | undefined, + ]) => { + this._log.info('repeatDataBodyInfo response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * This method echoes the ComplianceData request. This method exercises - * sending all request fields as query parameters. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * @param {google.showcase.v1beta1.ComplianceData} request.info - * @param {boolean} request.serverVerify - * If true, the server will verify that the received request matches - * the request with the same name in the compliance test suite. - * @param {string} request.intendedBindingUri - * The URI template this request is expected to be bound to server-side. - * @param {number} request.fInt32 - * Some top level fields, to test that these are encoded correctly - * in query params. - * @param {number} request.fInt64 - * @param {number} request.fDouble - * @param {number} request.pInt32 - * @param {number} request.pInt64 - * @param {number} request.pDouble - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.RepeatResponse|RepeatResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/compliance.repeat_data_query.js - * region_tag:localhost_v1beta1_generated_Compliance_RepeatDataQuery_async - */ + /** + * This method echoes the ComplianceData request. This method exercises + * sending all request fields as query parameters. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * @param {google.showcase.v1beta1.ComplianceData} request.info + * @param {boolean} request.serverVerify + * If true, the server will verify that the received request matches + * the request with the same name in the compliance test suite. + * @param {string} request.intendedBindingUri + * The URI template this request is expected to be bound to server-side. + * @param {number} request.fInt32 + * Some top level fields, to test that these are encoded correctly + * in query params. + * @param {number} request.fInt64 + * @param {number} request.fDouble + * @param {number} request.pInt32 + * @param {number} request.pInt64 + * @param {number} request.pDouble + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.RepeatResponse|RepeatResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/compliance.repeat_data_query.js + * region_tag:localhost_v1beta1_generated_Compliance_RepeatDataQuery_async + */ repeatDataQuery( - request?: protos.google.showcase.v1beta1.IRepeatRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IRepeatRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | undefined, + {} | undefined, + ] + >; repeatDataQuery( - request: protos.google.showcase.v1beta1.IRepeatRequest, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IRepeatRequest, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + ): void; repeatDataQuery( - request: protos.google.showcase.v1beta1.IRepeatRequest, - callback: Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IRepeatRequest, + callback: Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + ): void; repeatDataQuery( - request?: protos.google.showcase.v1beta1.IRepeatRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.showcase.v1beta1.IRepeatRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|undefined, {}|undefined - ]>|void { + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('repeatDataQuery request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('repeatDataQuery response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.repeatDataQuery(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|undefined, - {}|undefined - ]) => { - this._log.info('repeatDataQuery response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .repeatDataQuery(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | undefined, + {} | undefined, + ]) => { + this._log.info('repeatDataQuery response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * This method echoes the ComplianceData request. This method exercises - * sending some parameters as "simple" path variables (i.e., of the form - * "/bar/{foo}" rather than "/{foo=bar/*}"), and the rest as query parameters. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * @param {google.showcase.v1beta1.ComplianceData} request.info - * @param {boolean} request.serverVerify - * If true, the server will verify that the received request matches - * the request with the same name in the compliance test suite. - * @param {string} request.intendedBindingUri - * The URI template this request is expected to be bound to server-side. - * @param {number} request.fInt32 - * Some top level fields, to test that these are encoded correctly - * in query params. - * @param {number} request.fInt64 - * @param {number} request.fDouble - * @param {number} request.pInt32 - * @param {number} request.pInt64 - * @param {number} request.pDouble - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.RepeatResponse|RepeatResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/compliance.repeat_data_simple_path.js - * region_tag:localhost_v1beta1_generated_Compliance_RepeatDataSimplePath_async - */ + /** + * This method echoes the ComplianceData request. This method exercises + * sending some parameters as "simple" path variables (i.e., of the form + * "/bar/{foo}" rather than "/{foo=bar/*}"), and the rest as query parameters. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * @param {google.showcase.v1beta1.ComplianceData} request.info + * @param {boolean} request.serverVerify + * If true, the server will verify that the received request matches + * the request with the same name in the compliance test suite. + * @param {string} request.intendedBindingUri + * The URI template this request is expected to be bound to server-side. + * @param {number} request.fInt32 + * Some top level fields, to test that these are encoded correctly + * in query params. + * @param {number} request.fInt64 + * @param {number} request.fDouble + * @param {number} request.pInt32 + * @param {number} request.pInt64 + * @param {number} request.pDouble + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.RepeatResponse|RepeatResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/compliance.repeat_data_simple_path.js + * region_tag:localhost_v1beta1_generated_Compliance_RepeatDataSimplePath_async + */ repeatDataSimplePath( - request?: protos.google.showcase.v1beta1.IRepeatRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IRepeatRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | undefined, + {} | undefined, + ] + >; repeatDataSimplePath( - request: protos.google.showcase.v1beta1.IRepeatRequest, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IRepeatRequest, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + ): void; repeatDataSimplePath( - request: protos.google.showcase.v1beta1.IRepeatRequest, - callback: Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IRepeatRequest, + callback: Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + ): void; repeatDataSimplePath( - request?: protos.google.showcase.v1beta1.IRepeatRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.showcase.v1beta1.IRepeatRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|undefined, {}|undefined - ]>|void { + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'info.f_string': request.info!.fString ?? '', - 'info.f_int32': request.info!.fInt32 ?? '', - 'info.f_double': request.info!.fDouble ?? '', - 'info.f_bool': request.info!.fBool ?? '', - 'info.f_kingdom': request.info!.fKingdom ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'info.f_string': request.info!.fString ?? '', + 'info.f_int32': request.info!.fInt32 ?? '', + 'info.f_double': request.info!.fDouble ?? '', + 'info.f_bool': request.info!.fBool ?? '', + 'info.f_kingdom': request.info!.fKingdom ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('repeatDataSimplePath request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('repeatDataSimplePath response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.repeatDataSimplePath(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|undefined, - {}|undefined - ]) => { - this._log.info('repeatDataSimplePath response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .repeatDataSimplePath(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | undefined, + {} | undefined, + ]) => { + this._log.info('repeatDataSimplePath response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Same as RepeatDataSimplePath, but with a path resource. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * @param {google.showcase.v1beta1.ComplianceData} request.info - * @param {boolean} request.serverVerify - * If true, the server will verify that the received request matches - * the request with the same name in the compliance test suite. - * @param {string} request.intendedBindingUri - * The URI template this request is expected to be bound to server-side. - * @param {number} request.fInt32 - * Some top level fields, to test that these are encoded correctly - * in query params. - * @param {number} request.fInt64 - * @param {number} request.fDouble - * @param {number} request.pInt32 - * @param {number} request.pInt64 - * @param {number} request.pDouble - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.RepeatResponse|RepeatResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/compliance.repeat_data_path_resource.js - * region_tag:localhost_v1beta1_generated_Compliance_RepeatDataPathResource_async - */ + /** + * Same as RepeatDataSimplePath, but with a path resource. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * @param {google.showcase.v1beta1.ComplianceData} request.info + * @param {boolean} request.serverVerify + * If true, the server will verify that the received request matches + * the request with the same name in the compliance test suite. + * @param {string} request.intendedBindingUri + * The URI template this request is expected to be bound to server-side. + * @param {number} request.fInt32 + * Some top level fields, to test that these are encoded correctly + * in query params. + * @param {number} request.fInt64 + * @param {number} request.fDouble + * @param {number} request.pInt32 + * @param {number} request.pInt64 + * @param {number} request.pDouble + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.RepeatResponse|RepeatResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/compliance.repeat_data_path_resource.js + * region_tag:localhost_v1beta1_generated_Compliance_RepeatDataPathResource_async + */ repeatDataPathResource( - request?: protos.google.showcase.v1beta1.IRepeatRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IRepeatRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | undefined, + {} | undefined, + ] + >; repeatDataPathResource( - request: protos.google.showcase.v1beta1.IRepeatRequest, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IRepeatRequest, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + ): void; repeatDataPathResource( - request: protos.google.showcase.v1beta1.IRepeatRequest, - callback: Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IRepeatRequest, + callback: Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + ): void; repeatDataPathResource( - request?: protos.google.showcase.v1beta1.IRepeatRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.showcase.v1beta1.IRepeatRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|undefined, {}|undefined - ]>|void { + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'info.f_string': request.info!.fString ?? '', - 'info.f_child.f_string': request.info!.fChild!.fString ?? '', - 'info.f_bool': request.info!.fBool ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'info.f_string': request.info!.fString ?? '', + 'info.f_child.f_string': request.info!.fChild!.fString ?? '', + 'info.f_bool': request.info!.fBool ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('repeatDataPathResource request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('repeatDataPathResource response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.repeatDataPathResource(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|undefined, - {}|undefined - ]) => { - this._log.info('repeatDataPathResource response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .repeatDataPathResource(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | undefined, + {} | undefined, + ]) => { + this._log.info('repeatDataPathResource response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Same as RepeatDataSimplePath, but with a trailing resource. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * @param {google.showcase.v1beta1.ComplianceData} request.info - * @param {boolean} request.serverVerify - * If true, the server will verify that the received request matches - * the request with the same name in the compliance test suite. - * @param {string} request.intendedBindingUri - * The URI template this request is expected to be bound to server-side. - * @param {number} request.fInt32 - * Some top level fields, to test that these are encoded correctly - * in query params. - * @param {number} request.fInt64 - * @param {number} request.fDouble - * @param {number} request.pInt32 - * @param {number} request.pInt64 - * @param {number} request.pDouble - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.RepeatResponse|RepeatResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/compliance.repeat_data_path_trailing_resource.js - * region_tag:localhost_v1beta1_generated_Compliance_RepeatDataPathTrailingResource_async - */ + /** + * Same as RepeatDataSimplePath, but with a trailing resource. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * @param {google.showcase.v1beta1.ComplianceData} request.info + * @param {boolean} request.serverVerify + * If true, the server will verify that the received request matches + * the request with the same name in the compliance test suite. + * @param {string} request.intendedBindingUri + * The URI template this request is expected to be bound to server-side. + * @param {number} request.fInt32 + * Some top level fields, to test that these are encoded correctly + * in query params. + * @param {number} request.fInt64 + * @param {number} request.fDouble + * @param {number} request.pInt32 + * @param {number} request.pInt64 + * @param {number} request.pDouble + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.RepeatResponse|RepeatResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/compliance.repeat_data_path_trailing_resource.js + * region_tag:localhost_v1beta1_generated_Compliance_RepeatDataPathTrailingResource_async + */ repeatDataPathTrailingResource( - request?: protos.google.showcase.v1beta1.IRepeatRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IRepeatRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | undefined, + {} | undefined, + ] + >; repeatDataPathTrailingResource( - request: protos.google.showcase.v1beta1.IRepeatRequest, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IRepeatRequest, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + ): void; repeatDataPathTrailingResource( - request: protos.google.showcase.v1beta1.IRepeatRequest, - callback: Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IRepeatRequest, + callback: Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + ): void; repeatDataPathTrailingResource( - request?: protos.google.showcase.v1beta1.IRepeatRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.showcase.v1beta1.IRepeatRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|undefined, {}|undefined - ]>|void { + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'info.f_string': request.info!.fString ?? '', - 'info.f_child.f_string': request.info!.fChild!.fString ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'info.f_string': request.info!.fString ?? '', + 'info.f_child.f_string': request.info!.fChild!.fString ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('repeatDataPathTrailingResource request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { - this._log.info('repeatDataPathTrailingResource response %j', response); + this._log.info( + 'repeatDataPathTrailingResource response %j', + response, + ); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.repeatDataPathTrailingResource(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|undefined, - {}|undefined - ]) => { - this._log.info('repeatDataPathTrailingResource response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .repeatDataPathTrailingResource(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | undefined, + {} | undefined, + ]) => { + this._log.info( + 'repeatDataPathTrailingResource response %j', + response, + ); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * This method echoes the ComplianceData request, using the HTTP PUT method. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * @param {google.showcase.v1beta1.ComplianceData} request.info - * @param {boolean} request.serverVerify - * If true, the server will verify that the received request matches - * the request with the same name in the compliance test suite. - * @param {string} request.intendedBindingUri - * The URI template this request is expected to be bound to server-side. - * @param {number} request.fInt32 - * Some top level fields, to test that these are encoded correctly - * in query params. - * @param {number} request.fInt64 - * @param {number} request.fDouble - * @param {number} request.pInt32 - * @param {number} request.pInt64 - * @param {number} request.pDouble - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.RepeatResponse|RepeatResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/compliance.repeat_data_body_put.js - * region_tag:localhost_v1beta1_generated_Compliance_RepeatDataBodyPut_async - */ + /** + * This method echoes the ComplianceData request, using the HTTP PUT method. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * @param {google.showcase.v1beta1.ComplianceData} request.info + * @param {boolean} request.serverVerify + * If true, the server will verify that the received request matches + * the request with the same name in the compliance test suite. + * @param {string} request.intendedBindingUri + * The URI template this request is expected to be bound to server-side. + * @param {number} request.fInt32 + * Some top level fields, to test that these are encoded correctly + * in query params. + * @param {number} request.fInt64 + * @param {number} request.fDouble + * @param {number} request.pInt32 + * @param {number} request.pInt64 + * @param {number} request.pDouble + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.RepeatResponse|RepeatResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/compliance.repeat_data_body_put.js + * region_tag:localhost_v1beta1_generated_Compliance_RepeatDataBodyPut_async + */ repeatDataBodyPut( - request?: protos.google.showcase.v1beta1.IRepeatRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IRepeatRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | undefined, + {} | undefined, + ] + >; repeatDataBodyPut( - request: protos.google.showcase.v1beta1.IRepeatRequest, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IRepeatRequest, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + ): void; repeatDataBodyPut( - request: protos.google.showcase.v1beta1.IRepeatRequest, - callback: Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IRepeatRequest, + callback: Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + ): void; repeatDataBodyPut( - request?: protos.google.showcase.v1beta1.IRepeatRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.showcase.v1beta1.IRepeatRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|undefined, {}|undefined - ]>|void { + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('repeatDataBodyPut request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('repeatDataBodyPut response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.repeatDataBodyPut(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|undefined, - {}|undefined - ]) => { - this._log.info('repeatDataBodyPut response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .repeatDataBodyPut(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | undefined, + {} | undefined, + ]) => { + this._log.info('repeatDataBodyPut response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * This method echoes the ComplianceData request, using the HTTP PATCH method. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * @param {google.showcase.v1beta1.ComplianceData} request.info - * @param {boolean} request.serverVerify - * If true, the server will verify that the received request matches - * the request with the same name in the compliance test suite. - * @param {string} request.intendedBindingUri - * The URI template this request is expected to be bound to server-side. - * @param {number} request.fInt32 - * Some top level fields, to test that these are encoded correctly - * in query params. - * @param {number} request.fInt64 - * @param {number} request.fDouble - * @param {number} request.pInt32 - * @param {number} request.pInt64 - * @param {number} request.pDouble - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.RepeatResponse|RepeatResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/compliance.repeat_data_body_patch.js - * region_tag:localhost_v1beta1_generated_Compliance_RepeatDataBodyPatch_async - */ + /** + * This method echoes the ComplianceData request, using the HTTP PATCH method. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * @param {google.showcase.v1beta1.ComplianceData} request.info + * @param {boolean} request.serverVerify + * If true, the server will verify that the received request matches + * the request with the same name in the compliance test suite. + * @param {string} request.intendedBindingUri + * The URI template this request is expected to be bound to server-side. + * @param {number} request.fInt32 + * Some top level fields, to test that these are encoded correctly + * in query params. + * @param {number} request.fInt64 + * @param {number} request.fDouble + * @param {number} request.pInt32 + * @param {number} request.pInt64 + * @param {number} request.pDouble + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.RepeatResponse|RepeatResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/compliance.repeat_data_body_patch.js + * region_tag:localhost_v1beta1_generated_Compliance_RepeatDataBodyPatch_async + */ repeatDataBodyPatch( - request?: protos.google.showcase.v1beta1.IRepeatRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IRepeatRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | undefined, + {} | undefined, + ] + >; repeatDataBodyPatch( - request: protos.google.showcase.v1beta1.IRepeatRequest, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IRepeatRequest, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + ): void; repeatDataBodyPatch( - request: protos.google.showcase.v1beta1.IRepeatRequest, - callback: Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IRepeatRequest, + callback: Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + ): void; repeatDataBodyPatch( - request?: protos.google.showcase.v1beta1.IRepeatRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.showcase.v1beta1.IRepeatRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|undefined, {}|undefined - ]>|void { + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('repeatDataBodyPatch request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('repeatDataBodyPatch response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.repeatDataBodyPatch(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|undefined, - {}|undefined - ]) => { - this._log.info('repeatDataBodyPatch response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .repeatDataBodyPatch(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | undefined, + {} | undefined, + ]) => { + this._log.info('repeatDataBodyPatch response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * This method requests an enum value from the server. Depending on the contents of EnumRequest, the enum value returned will be a known enum declared in the - * .proto file, or a made-up enum value the is unknown to the client. To verify that clients can round-trip unknown enum vaues they receive, use the - * response from this RPC as the request to VerifyEnum() - * - * The values of enums sent by the server when a known or unknown value is requested will be the same within a single Showcase server run (this is needed for - * VerifyEnum() to work) but are not guaranteed to be the same across separate Showcase server runs. - * - * @param {Object} request - * The request object that will be sent. - * @param {boolean} request.unknownEnum - * Whether the client is requesting a new, unknown enum value or a known enum value already declard in this proto file. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.EnumResponse|EnumResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/compliance.get_enum.js - * region_tag:localhost_v1beta1_generated_Compliance_GetEnum_async - */ + /** + * This method requests an enum value from the server. Depending on the contents of EnumRequest, the enum value returned will be a known enum declared in the + * .proto file, or a made-up enum value the is unknown to the client. To verify that clients can round-trip unknown enum vaues they receive, use the + * response from this RPC as the request to VerifyEnum() + * + * The values of enums sent by the server when a known or unknown value is requested will be the same within a single Showcase server run (this is needed for + * VerifyEnum() to work) but are not guaranteed to be the same across separate Showcase server runs. + * + * @param {Object} request + * The request object that will be sent. + * @param {boolean} request.unknownEnum + * Whether the client is requesting a new, unknown enum value or a known enum value already declard in this proto file. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.EnumResponse|EnumResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/compliance.get_enum.js + * region_tag:localhost_v1beta1_generated_Compliance_GetEnum_async + */ getEnum( - request?: protos.google.showcase.v1beta1.IEnumRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IEnumResponse, - protos.google.showcase.v1beta1.IEnumRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IEnumRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IEnumResponse, + protos.google.showcase.v1beta1.IEnumRequest | undefined, + {} | undefined, + ] + >; getEnum( - request: protos.google.showcase.v1beta1.IEnumRequest, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.IEnumResponse, - protos.google.showcase.v1beta1.IEnumRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IEnumRequest, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.IEnumResponse, + protos.google.showcase.v1beta1.IEnumRequest | null | undefined, + {} | null | undefined + >, + ): void; getEnum( - request: protos.google.showcase.v1beta1.IEnumRequest, - callback: Callback< - protos.google.showcase.v1beta1.IEnumResponse, - protos.google.showcase.v1beta1.IEnumRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IEnumRequest, + callback: Callback< + protos.google.showcase.v1beta1.IEnumResponse, + protos.google.showcase.v1beta1.IEnumRequest | null | undefined, + {} | null | undefined + >, + ): void; getEnum( - request?: protos.google.showcase.v1beta1.IEnumRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.showcase.v1beta1.IEnumRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.IEnumResponse, - protos.google.showcase.v1beta1.IEnumRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.showcase.v1beta1.IEnumResponse, - protos.google.showcase.v1beta1.IEnumRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.IEnumResponse, - protos.google.showcase.v1beta1.IEnumRequest|undefined, {}|undefined - ]>|void { + protos.google.showcase.v1beta1.IEnumRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.IEnumResponse, + protos.google.showcase.v1beta1.IEnumRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IEnumResponse, + protos.google.showcase.v1beta1.IEnumRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('getEnum request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.IEnumResponse, - protos.google.showcase.v1beta1.IEnumRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.IEnumResponse, + protos.google.showcase.v1beta1.IEnumRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getEnum response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getEnum(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.IEnumResponse, - protos.google.showcase.v1beta1.IEnumRequest|undefined, - {}|undefined - ]) => { - this._log.info('getEnum response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getEnum(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.IEnumResponse, + protos.google.showcase.v1beta1.IEnumRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getEnum response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * This method is used to verify that clients can round-trip enum values, which is particularly important for unknown enum values over REST. VerifyEnum() - * verifies that its request, which is presumably the response that the client previously got to a GetEnum(), contains the correct data. If so, it responds - * with the same EnumResponse; otherwise, the RPC errors. - * - * This works because the values of enums sent by the server when a known or unknown value is requested will be the same within a single Showcase server run, - * although they are not guaranteed to be the same across separate Showcase server runs. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.showcase.v1beta1.EnumRequest} request.request - * The original request for a known or unknown enum from the server. - * @param {google.showcase.v1beta1.Continent} request.continent - * The actual enum the server provided. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.EnumResponse|EnumResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/compliance.verify_enum.js - * region_tag:localhost_v1beta1_generated_Compliance_VerifyEnum_async - */ + /** + * This method is used to verify that clients can round-trip enum values, which is particularly important for unknown enum values over REST. VerifyEnum() + * verifies that its request, which is presumably the response that the client previously got to a GetEnum(), contains the correct data. If so, it responds + * with the same EnumResponse; otherwise, the RPC errors. + * + * This works because the values of enums sent by the server when a known or unknown value is requested will be the same within a single Showcase server run, + * although they are not guaranteed to be the same across separate Showcase server runs. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.showcase.v1beta1.EnumRequest} request.request + * The original request for a known or unknown enum from the server. + * @param {google.showcase.v1beta1.Continent} request.continent + * The actual enum the server provided. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.EnumResponse|EnumResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/compliance.verify_enum.js + * region_tag:localhost_v1beta1_generated_Compliance_VerifyEnum_async + */ verifyEnum( - request?: protos.google.showcase.v1beta1.IEnumResponse, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IEnumResponse, - protos.google.showcase.v1beta1.IEnumResponse|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IEnumResponse, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IEnumResponse, + protos.google.showcase.v1beta1.IEnumResponse | undefined, + {} | undefined, + ] + >; verifyEnum( - request: protos.google.showcase.v1beta1.IEnumResponse, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.IEnumResponse, - protos.google.showcase.v1beta1.IEnumResponse|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IEnumResponse, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.IEnumResponse, + protos.google.showcase.v1beta1.IEnumResponse | null | undefined, + {} | null | undefined + >, + ): void; verifyEnum( - request: protos.google.showcase.v1beta1.IEnumResponse, - callback: Callback< - protos.google.showcase.v1beta1.IEnumResponse, - protos.google.showcase.v1beta1.IEnumResponse|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IEnumResponse, + callback: Callback< + protos.google.showcase.v1beta1.IEnumResponse, + protos.google.showcase.v1beta1.IEnumResponse | null | undefined, + {} | null | undefined + >, + ): void; verifyEnum( - request?: protos.google.showcase.v1beta1.IEnumResponse, - optionsOrCallback?: CallOptions|Callback< - protos.google.showcase.v1beta1.IEnumResponse, - protos.google.showcase.v1beta1.IEnumResponse|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.showcase.v1beta1.IEnumResponse, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.IEnumResponse, - protos.google.showcase.v1beta1.IEnumResponse|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.IEnumResponse, - protos.google.showcase.v1beta1.IEnumResponse|undefined, {}|undefined - ]>|void { + protos.google.showcase.v1beta1.IEnumResponse | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.IEnumResponse, + protos.google.showcase.v1beta1.IEnumResponse | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IEnumResponse, + protos.google.showcase.v1beta1.IEnumResponse | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('verifyEnum request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.IEnumResponse, - protos.google.showcase.v1beta1.IEnumResponse|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.IEnumResponse, + protos.google.showcase.v1beta1.IEnumResponse | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('verifyEnum response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.verifyEnum(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.IEnumResponse, - protos.google.showcase.v1beta1.IEnumResponse|undefined, - {}|undefined - ]) => { - this._log.info('verifyEnum response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .verifyEnum(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.IEnumResponse, + protos.google.showcase.v1beta1.IEnumResponse | undefined, + {} | undefined, + ]) => { + this._log.info('verifyEnum response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); @@ -1401,7 +1765,7 @@ export class ComplianceClient { * @param {string} blueprint * @returns {string} Resource name string. */ - blueprintPath(session:string,test:string,blueprint:string) { + blueprintPath(session: string, test: string, blueprint: string) { return this.pathTemplates.blueprintPathTemplate.render({ session: session, test: test, @@ -1417,7 +1781,8 @@ export class ComplianceClient { * @returns {string} A string representing the session. */ matchSessionFromBlueprintName(blueprintName: string) { - return this.pathTemplates.blueprintPathTemplate.match(blueprintName).session; + return this.pathTemplates.blueprintPathTemplate.match(blueprintName) + .session; } /** @@ -1439,7 +1804,8 @@ export class ComplianceClient { * @returns {string} A string representing the blueprint. */ matchBlueprintFromBlueprintName(blueprintName: string) { - return this.pathTemplates.blueprintPathTemplate.match(blueprintName).blueprint; + return this.pathTemplates.blueprintPathTemplate.match(blueprintName) + .blueprint; } /** @@ -1448,7 +1814,7 @@ export class ComplianceClient { * @param {string} room * @returns {string} Resource name string. */ - roomPath(room:string) { + roomPath(room: string) { return this.pathTemplates.roomPathTemplate.render({ room: room, }); @@ -1472,7 +1838,7 @@ export class ComplianceClient { * @param {string} blurb * @returns {string} Resource name string. */ - roomBlurbPath(room:string,blurb:string) { + roomBlurbPath(room: string, blurb: string) { return this.pathTemplates.roomBlurbPathTemplate.render({ room: room, blurb: blurb, @@ -1509,7 +1875,11 @@ export class ComplianceClient { * @param {string} blurb * @returns {string} Resource name string. */ - roomBlurbsLegacyRoomBlurbPath(room:string,legacyRoom:string,blurb:string) { + roomBlurbsLegacyRoomBlurbPath( + room: string, + legacyRoom: string, + blurb: string, + ) { return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.render({ room: room, legacy_room: legacyRoom, @@ -1524,8 +1894,12 @@ export class ComplianceClient { * A fully-qualified path representing room_blurbs_legacy_room_blurb resource. * @returns {string} A string representing the room. */ - matchRoomFromRoomBlurbsLegacyRoomBlurbName(roomBlurbsLegacyRoomBlurbName: string) { - return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match(roomBlurbsLegacyRoomBlurbName).room; + matchRoomFromRoomBlurbsLegacyRoomBlurbName( + roomBlurbsLegacyRoomBlurbName: string, + ) { + return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match( + roomBlurbsLegacyRoomBlurbName, + ).room; } /** @@ -1535,8 +1909,12 @@ export class ComplianceClient { * A fully-qualified path representing room_blurbs_legacy_room_blurb resource. * @returns {string} A string representing the legacy_room. */ - matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName(roomBlurbsLegacyRoomBlurbName: string) { - return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match(roomBlurbsLegacyRoomBlurbName).legacy_room; + matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName( + roomBlurbsLegacyRoomBlurbName: string, + ) { + return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match( + roomBlurbsLegacyRoomBlurbName, + ).legacy_room; } /** @@ -1546,8 +1924,12 @@ export class ComplianceClient { * A fully-qualified path representing room_blurbs_legacy_room_blurb resource. * @returns {string} A string representing the blurb. */ - matchBlurbFromRoomBlurbsLegacyRoomBlurbName(roomBlurbsLegacyRoomBlurbName: string) { - return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match(roomBlurbsLegacyRoomBlurbName).blurb; + matchBlurbFromRoomBlurbsLegacyRoomBlurbName( + roomBlurbsLegacyRoomBlurbName: string, + ) { + return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match( + roomBlurbsLegacyRoomBlurbName, + ).blurb; } /** @@ -1556,7 +1938,7 @@ export class ComplianceClient { * @param {string} sequence * @returns {string} Resource name string. */ - sequencePath(sequence:string) { + sequencePath(sequence: string) { return this.pathTemplates.sequencePathTemplate.render({ sequence: sequence, }); @@ -1579,7 +1961,7 @@ export class ComplianceClient { * @param {string} sequence * @returns {string} Resource name string. */ - sequenceReportPath(sequence:string) { + sequenceReportPath(sequence: string) { return this.pathTemplates.sequenceReportPathTemplate.render({ sequence: sequence, }); @@ -1593,7 +1975,9 @@ export class ComplianceClient { * @returns {string} A string representing the sequence. */ matchSequenceFromSequenceReportName(sequenceReportName: string) { - return this.pathTemplates.sequenceReportPathTemplate.match(sequenceReportName).sequence; + return this.pathTemplates.sequenceReportPathTemplate.match( + sequenceReportName, + ).sequence; } /** @@ -1602,7 +1986,7 @@ export class ComplianceClient { * @param {string} session * @returns {string} Resource name string. */ - sessionPath(session:string) { + sessionPath(session: string) { return this.pathTemplates.sessionPathTemplate.render({ session: session, }); @@ -1626,7 +2010,7 @@ export class ComplianceClient { * @param {string} test * @returns {string} Resource name string. */ - testPath(session:string,test:string) { + testPath(session: string, test: string) { return this.pathTemplates.testPathTemplate.render({ session: session, test: test, @@ -1661,7 +2045,7 @@ export class ComplianceClient { * @param {string} user * @returns {string} Resource name string. */ - userPath(user:string) { + userPath(user: string) { return this.pathTemplates.userPathTemplate.render({ user: user, }); @@ -1685,7 +2069,7 @@ export class ComplianceClient { * @param {string} blurb * @returns {string} Resource name string. */ - userProfileBlurbPath(user:string,blurb:string) { + userProfileBlurbPath(user: string, blurb: string) { return this.pathTemplates.userProfileBlurbPathTemplate.render({ user: user, blurb: blurb, @@ -1700,7 +2084,9 @@ export class ComplianceClient { * @returns {string} A string representing the user. */ matchUserFromUserProfileBlurbName(userProfileBlurbName: string) { - return this.pathTemplates.userProfileBlurbPathTemplate.match(userProfileBlurbName).user; + return this.pathTemplates.userProfileBlurbPathTemplate.match( + userProfileBlurbName, + ).user; } /** @@ -1711,7 +2097,9 @@ export class ComplianceClient { * @returns {string} A string representing the blurb. */ matchBlurbFromUserProfileBlurbName(userProfileBlurbName: string) { - return this.pathTemplates.userProfileBlurbPathTemplate.match(userProfileBlurbName).blurb; + return this.pathTemplates.userProfileBlurbPathTemplate.match( + userProfileBlurbName, + ).blurb; } /** @@ -1722,12 +2110,18 @@ export class ComplianceClient { * @param {string} blurb * @returns {string} Resource name string. */ - userProfileBlurbsLegacyUserBlurbPath(user:string,legacyUser:string,blurb:string) { - return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.render({ - user: user, - legacy_user: legacyUser, - blurb: blurb, - }); + userProfileBlurbsLegacyUserBlurbPath( + user: string, + legacyUser: string, + blurb: string, + ) { + return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.render( + { + user: user, + legacy_user: legacyUser, + blurb: blurb, + }, + ); } /** @@ -1737,8 +2131,12 @@ export class ComplianceClient { * A fully-qualified path representing user_profile_blurbs_legacy_user_blurb resource. * @returns {string} A string representing the user. */ - matchUserFromUserProfileBlurbsLegacyUserBlurbName(userProfileBlurbsLegacyUserBlurbName: string) { - return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match(userProfileBlurbsLegacyUserBlurbName).user; + matchUserFromUserProfileBlurbsLegacyUserBlurbName( + userProfileBlurbsLegacyUserBlurbName: string, + ) { + return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match( + userProfileBlurbsLegacyUserBlurbName, + ).user; } /** @@ -1748,8 +2146,12 @@ export class ComplianceClient { * A fully-qualified path representing user_profile_blurbs_legacy_user_blurb resource. * @returns {string} A string representing the legacy_user. */ - matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName(userProfileBlurbsLegacyUserBlurbName: string) { - return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match(userProfileBlurbsLegacyUserBlurbName).legacy_user; + matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName( + userProfileBlurbsLegacyUserBlurbName: string, + ) { + return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match( + userProfileBlurbsLegacyUserBlurbName, + ).legacy_user; } /** @@ -1759,8 +2161,12 @@ export class ComplianceClient { * A fully-qualified path representing user_profile_blurbs_legacy_user_blurb resource. * @returns {string} A string representing the blurb. */ - matchBlurbFromUserProfileBlurbsLegacyUserBlurbName(userProfileBlurbsLegacyUserBlurbName: string) { - return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match(userProfileBlurbsLegacyUserBlurbName).blurb; + matchBlurbFromUserProfileBlurbsLegacyUserBlurbName( + userProfileBlurbsLegacyUserBlurbName: string, + ) { + return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match( + userProfileBlurbsLegacyUserBlurbName, + ).blurb; } /** @@ -1771,7 +2177,7 @@ export class ComplianceClient { */ close(): Promise { if (this.complianceStub && !this._terminated) { - return this.complianceStub.then(stub => { + return this.complianceStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -1779,4 +2185,4 @@ export class ComplianceClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/core/generator/gapic-generator-typescript/baselines/disable-packing-test/src/v1beta1/echo_client.ts.baseline b/core/generator/gapic-generator-typescript/baselines/disable-packing-test/src/v1beta1/echo_client.ts.baseline index 2b0064ef4bab..8bfe18c60cb5 100644 --- a/core/generator/gapic-generator-typescript/baselines/disable-packing-test/src/v1beta1/echo_client.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/disable-packing-test/src/v1beta1/echo_client.ts.baseline @@ -18,11 +18,20 @@ /* global window */ import type * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions, GrpcClientOptions, LROperation, PaginationCallback, GaxCall} from 'google-gax'; -import {Transform, PassThrough} from 'stream'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + GrpcClientOptions, + LROperation, + PaginationCallback, + GaxCall, +} from 'google-gax'; +import { Transform, PassThrough } from 'stream'; import * as protos from '../../protos/protos'; import jsonProtos = require('../../protos/protos.json'); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; /** * Client JSON configuration object, loaded from @@ -52,7 +61,7 @@ export class EchoClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('showcase'); @@ -65,10 +74,10 @@ export class EchoClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; operationsClient: gax.OperationsClient; - echoStub?: Promise<{[name: string]: Function}>; + echoStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of EchoClient. @@ -109,21 +118,42 @@ export class EchoClient { * const client = new EchoClient({fallback: true}, gax); * ``` */ - constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { // Ensure that options include all the required fields. const staticMembers = this.constructor as typeof EchoClient; - if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { - throw new Error('Please set either universe_domain or universeDomain, but not both.'); + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); } - const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; - this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; this._servicePath = 'localhost'; - const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; - const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. if (servicePath !== this._servicePath && !('scopes' in opts)) { @@ -145,7 +175,7 @@ export class EchoClient { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; @@ -159,10 +189,7 @@ export class EchoClient { } // Determine the client header string. - const clientHeader = [ - `gax/${this._gaxModule.version}`, - `gapic/${version}`, - ]; + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/${process.versions.node}`); } else { @@ -184,54 +211,65 @@ export class EchoClient { // Create useful helper objects for these. this.pathTemplates = { blueprintPathTemplate: new this._gaxModule.PathTemplate( - 'sessions/{session}/tests/{test}/blueprints/{blueprint}' - ), - roomPathTemplate: new this._gaxModule.PathTemplate( - 'rooms/{room}' + 'sessions/{session}/tests/{test}/blueprints/{blueprint}', ), + roomPathTemplate: new this._gaxModule.PathTemplate('rooms/{room}'), roomBlurbPathTemplate: new this._gaxModule.PathTemplate( - 'rooms/{room}/blurbs/{blurb}' + 'rooms/{room}/blurbs/{blurb}', ), roomBlurbsLegacyRoomBlurbPathTemplate: new this._gaxModule.PathTemplate( - 'rooms/{room}/blurbs/legacy/{legacy_room}.{blurb}' + 'rooms/{room}/blurbs/legacy/{legacy_room}.{blurb}', ), sequencePathTemplate: new this._gaxModule.PathTemplate( - 'sequences/{sequence}' + 'sequences/{sequence}', ), sequenceReportPathTemplate: new this._gaxModule.PathTemplate( - 'sequences/{sequence}/sequenceReport' + 'sequences/{sequence}/sequenceReport', ), sessionPathTemplate: new this._gaxModule.PathTemplate( - 'sessions/{session}' + 'sessions/{session}', ), testPathTemplate: new this._gaxModule.PathTemplate( - 'sessions/{session}/tests/{test}' - ), - userPathTemplate: new this._gaxModule.PathTemplate( - 'users/{user}' + 'sessions/{session}/tests/{test}', ), + userPathTemplate: new this._gaxModule.PathTemplate('users/{user}'), userProfileBlurbPathTemplate: new this._gaxModule.PathTemplate( - 'users/{user}/profile/blurbs/{blurb}' - ), - userProfileBlurbsLegacyUserBlurbPathTemplate: new this._gaxModule.PathTemplate( - 'users/{user}/profile/blurbs/legacy/{legacy_user}~{blurb}' + 'users/{user}/profile/blurbs/{blurb}', ), + userProfileBlurbsLegacyUserBlurbPathTemplate: + new this._gaxModule.PathTemplate( + 'users/{user}/profile/blurbs/legacy/{legacy_user}~{blurb}', + ), }; // Some of the methods on this service return "paged" results, // (e.g. 50 results at a time, with tokens to get subsequent // pages). Denote the keys used for pagination and results. this.descriptors.page = { - pagedExpand: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'responses') + pagedExpand: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'responses', + ), }; // Some of the methods on this service provide streaming responses. // Provide descriptors for these. this.descriptors.stream = { - expand: new this._gaxModule.StreamDescriptor(this._gaxModule.StreamType.SERVER_STREAMING, !!opts.fallback, !!opts.gaxServerStreamingRetries), - collect: new this._gaxModule.StreamDescriptor(this._gaxModule.StreamType.CLIENT_STREAMING, !!opts.fallback), - chat: new this._gaxModule.StreamDescriptor(this._gaxModule.StreamType.BIDI_STREAMING, !!opts.fallback, !!opts.gaxServerStreamingRetries) + expand: new this._gaxModule.StreamDescriptor( + this._gaxModule.StreamType.SERVER_STREAMING, + !!opts.fallback, + !!opts.gaxServerStreamingRetries, + ), + collect: new this._gaxModule.StreamDescriptor( + this._gaxModule.StreamType.CLIENT_STREAMING, + !!opts.fallback, + ), + chat: new this._gaxModule.StreamDescriptor( + this._gaxModule.StreamType.BIDI_STREAMING, + !!opts.fallback, + !!opts.gaxServerStreamingRetries, + ), }; const protoFilesRoot = this._gaxModule.protobufFromJSON(jsonProtos); @@ -240,29 +278,40 @@ export class EchoClient { // rather than holding a request open. const lroOptions: GrpcClientOptions = { auth: this.auth, - grpc: 'grpc' in this._gaxGrpc ? this._gaxGrpc.grpc : undefined + grpc: 'grpc' in this._gaxGrpc ? this._gaxGrpc.grpc : undefined, }; if (opts.fallback) { lroOptions.protoJson = protoFilesRoot; lroOptions.httpRules = []; } - this.operationsClient = this._gaxModule.lro(lroOptions).operationsClient(opts); + this.operationsClient = this._gaxModule + .lro(lroOptions) + .operationsClient(opts); const waitResponse = protoFilesRoot.lookup( - '.google.showcase.v1beta1.WaitResponse') as gax.protobuf.Type; + '.google.showcase.v1beta1.WaitResponse', + ) as gax.protobuf.Type; const waitMetadata = protoFilesRoot.lookup( - '.google.showcase.v1beta1.WaitMetadata') as gax.protobuf.Type; + '.google.showcase.v1beta1.WaitMetadata', + ) as gax.protobuf.Type; this.descriptors.longrunning = { wait: new this._gaxModule.LongrunningDescriptor( this.operationsClient, waitResponse.decode.bind(waitResponse), - waitMetadata.decode.bind(waitMetadata)) + waitMetadata.decode.bind(waitMetadata), + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.showcase.v1beta1.Echo', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' '), 'x-goog-api-version': 'v1_20240408'}); + 'google.showcase.v1beta1.Echo', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + { + 'x-goog-api-client': clientHeader.join(' '), + 'x-goog-api-version': 'v1_20240408', + }, + ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -293,35 +342,55 @@ export class EchoClient { // Put together the "service stub" for // google.showcase.v1beta1.Echo. this.echoStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.showcase.v1beta1.Echo') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.showcase.v1beta1.Echo', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.showcase.v1beta1.Echo, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts, + this._providedCustomServicePath, + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const echoStubMethods = - ['echo', 'echoErrorDetails', 'expand', 'collect', 'chat', 'pagedExpand', 'pagedExpandLegacy', 'wait', 'block']; + const echoStubMethods = [ + 'echo', + 'echoErrorDetails', + 'expand', + 'collect', + 'chat', + 'pagedExpand', + 'pagedExpandLegacy', + 'wait', + 'block', + ]; for (const methodName of echoStubMethods) { const callPromise = this.echoStub.then( - stub => (...args: Array<{}>) => { - if (this._terminated) { - if (methodName in this.descriptors.stream) { - const stream = new PassThrough({objectMode: true}); - setImmediate(() => { - stream.emit('error', new this._gaxModule.GoogleError('The client has already been closed.')); - }); - return stream; + (stub) => + (...args: Array<{}>) => { + if (this._terminated) { + if (methodName in this.descriptors.stream) { + const stream = new PassThrough({ objectMode: true }); + setImmediate(() => { + stream.emit( + 'error', + new this._gaxModule.GoogleError( + 'The client has already been closed.', + ), + ); + }); + return stream; + } + return Promise.reject('The client has already been closed.'); } - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error|null|undefined) => () => { + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { throw err; - }); + }, + ); const descriptor = this.descriptors.page[methodName] || @@ -332,7 +401,7 @@ export class EchoClient { callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -347,8 +416,14 @@ export class EchoClient { * @returns {string} The DNS address for this service. */ static get servicePath() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'localhost'; } @@ -359,8 +434,14 @@ export class EchoClient { * @returns {string} The DNS address for this service. */ static get apiEndpoint() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'localhost'; } @@ -400,8 +481,9 @@ export class EchoClient { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId(callback?: Callback): - Promise|void { + getProjectId( + callback?: Callback, + ): Promise | void { if (callback) { this.auth.getProjectId(callback); return; @@ -412,73 +494,86 @@ export class EchoClient { // ------------------- // -- Service calls -- // ------------------- -/** - * @param {Object} request - * The request object that will be sent. - * @param {string} request.content - * The content to be echoed by the server. - * @param {google.rpc.Status} request.error - * The error to be thrown by the server. - * @param {google.showcase.v1beta1.Severity} request.severity - * The severity to be echoed by the server. - * @param {string} request.header - * Optional. This field can be set to test the routing annotation on the Echo method. - * @param {string} request.otherHeader - * Optional. This field can be set to test the routing annotation on the Echo method. - * @param {string} request.requestId - * To facilitate testing of https://google.aip.dev/client-libraries/4235 - * @param {string} request.otherRequestId - * To facilitate testing of https://google.aip.dev/client-libraries/4235 - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.EchoResponse|EchoResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/echo.echo.js - * region_tag:localhost_v1beta1_generated_Echo_Echo_async - */ + /** + * @param {Object} request + * The request object that will be sent. + * @param {string} request.content + * The content to be echoed by the server. + * @param {google.rpc.Status} request.error + * The error to be thrown by the server. + * @param {google.showcase.v1beta1.Severity} request.severity + * The severity to be echoed by the server. + * @param {string} request.header + * Optional. This field can be set to test the routing annotation on the Echo method. + * @param {string} request.otherHeader + * Optional. This field can be set to test the routing annotation on the Echo method. + * @param {string} request.requestId + * To facilitate testing of https://google.aip.dev/client-libraries/4235 + * @param {string} request.otherRequestId + * To facilitate testing of https://google.aip.dev/client-libraries/4235 + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.EchoResponse|EchoResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/echo.echo.js + * region_tag:localhost_v1beta1_generated_Echo_Echo_async + */ echo( - request?: protos.google.showcase.v1beta1.IEchoRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IEchoResponse, - protos.google.showcase.v1beta1.IEchoRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IEchoRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IEchoResponse, + protos.google.showcase.v1beta1.IEchoRequest | undefined, + {} | undefined, + ] + >; echo( - request: protos.google.showcase.v1beta1.IEchoRequest, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.IEchoResponse, - protos.google.showcase.v1beta1.IEchoRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IEchoRequest, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.IEchoResponse, + protos.google.showcase.v1beta1.IEchoRequest | null | undefined, + {} | null | undefined + >, + ): void; echo( - request: protos.google.showcase.v1beta1.IEchoRequest, - callback: Callback< - protos.google.showcase.v1beta1.IEchoResponse, - protos.google.showcase.v1beta1.IEchoRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IEchoRequest, + callback: Callback< + protos.google.showcase.v1beta1.IEchoResponse, + protos.google.showcase.v1beta1.IEchoRequest | null | undefined, + {} | null | undefined + >, + ): void; echo( - request?: protos.google.showcase.v1beta1.IEchoRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.showcase.v1beta1.IEchoRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.IEchoResponse, - protos.google.showcase.v1beta1.IEchoRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.showcase.v1beta1.IEchoResponse, - protos.google.showcase.v1beta1.IEchoRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.IEchoResponse, - protos.google.showcase.v1beta1.IEchoRequest|undefined, {}|undefined - ]>|void { + protos.google.showcase.v1beta1.IEchoRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.IEchoResponse, + protos.google.showcase.v1beta1.IEchoRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IEchoResponse, + protos.google.showcase.v1beta1.IEchoRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; @@ -498,7 +593,9 @@ export class EchoClient { { const fieldValue = request.header; if (fieldValue !== undefined && fieldValue !== null) { - const match = fieldValue.toString().match(RegExp('(?(?:.*)?)')); + const match = fieldValue + .toString() + .match(RegExp('(?(?:.*)?)')); if (match) { const parameterValue = match.groups?.['routing_id'] ?? fieldValue; Object.assign(routingParameter, { routing_id: parameterValue }); @@ -508,7 +605,9 @@ export class EchoClient { { const fieldValue = request.header; if (fieldValue !== undefined && fieldValue !== null) { - const match = fieldValue.toString().match(RegExp('(?regions/[^/]+/zones/[^/]+(?:/.*)?)')); + const match = fieldValue + .toString() + .match(RegExp('(?regions/[^/]+/zones/[^/]+(?:/.*)?)')); if (match) { const parameterValue = match.groups?.['table_name'] ?? fieldValue; Object.assign(routingParameter, { table_name: parameterValue }); @@ -518,7 +617,9 @@ export class EchoClient { { const fieldValue = request.header; if (fieldValue !== undefined && fieldValue !== null) { - const match = fieldValue.toString().match(RegExp('(?projects/[^/]+)(?:/.*)?')); + const match = fieldValue + .toString() + .match(RegExp('(?projects/[^/]+)(?:/.*)?')); if (match) { const parameterValue = match.groups?.['super_id'] ?? fieldValue; Object.assign(routingParameter, { super_id: parameterValue }); @@ -528,7 +629,11 @@ export class EchoClient { { const fieldValue = request.header; if (fieldValue !== undefined && fieldValue !== null) { - const match = fieldValue.toString().match(RegExp('(?projects/[^/]+/instances/[^/]+(?:/.*)?)')); + const match = fieldValue + .toString() + .match( + RegExp('(?projects/[^/]+/instances/[^/]+(?:/.*)?)'), + ); if (match) { const parameterValue = match.groups?.['table_name'] ?? fieldValue; Object.assign(routingParameter, { table_name: parameterValue }); @@ -538,7 +643,11 @@ export class EchoClient { { const fieldValue = request.header; if (fieldValue !== undefined && fieldValue !== null) { - const match = fieldValue.toString().match(RegExp('projects/[^/]+/(?instances/[^/]+)(?:/.*)?')); + const match = fieldValue + .toString() + .match( + RegExp('projects/[^/]+/(?instances/[^/]+)(?:/.*)?'), + ); if (match) { const parameterValue = match.groups?.['instance_id'] ?? fieldValue; Object.assign(routingParameter, { instance_id: parameterValue }); @@ -558,629 +667,852 @@ export class EchoClient { { const fieldValue = request.otherHeader; if (fieldValue !== undefined && fieldValue !== null) { - const match = fieldValue.toString().match(RegExp('(?projects/[^/]+)(?:/.*)?')); + const match = fieldValue + .toString() + .match(RegExp('(?projects/[^/]+)(?:/.*)?')); if (match) { const parameterValue = match.groups?.['qux'] ?? fieldValue; Object.assign(routingParameter, { qux: parameterValue }); } } } - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams( - routingParameter - ); - this.initialize().catch(err => {throw err}); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams(routingParameter); + this.initialize().catch((err) => { + throw err; + }); this._log.info('echo request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.IEchoResponse, - protos.google.showcase.v1beta1.IEchoRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.IEchoResponse, + protos.google.showcase.v1beta1.IEchoRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('echo response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.echo(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.IEchoResponse, - protos.google.showcase.v1beta1.IEchoRequest|undefined, - {}|undefined - ]) => { - this._log.info('echo response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .echo(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.IEchoResponse, + protos.google.showcase.v1beta1.IEchoRequest | undefined, + {} | undefined, + ]) => { + this._log.info('echo response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * This method returns error details in a repeated "google.protobuf.Any" - * field. This method showcases handling errors thus encoded, particularly - * over REST transport. Note that GAPICs only allow the type - * "google.protobuf.Any" for field paths ending in "error.details", and, at - * run-time, the actual types for these fields must be one of the types in - * google/rpc/error_details.proto. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.singleDetailText - * Content to return in a singular `*.error.details` field of type - * `google.protobuf.Any` - * @param {string[]} request.multiDetailText - * Content to return in a repeated `*.error.details` field of type - * `google.protobuf.Any` - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.EchoErrorDetailsResponse|EchoErrorDetailsResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/echo.echo_error_details.js - * region_tag:localhost_v1beta1_generated_Echo_EchoErrorDetails_async - */ + /** + * This method returns error details in a repeated "google.protobuf.Any" + * field. This method showcases handling errors thus encoded, particularly + * over REST transport. Note that GAPICs only allow the type + * "google.protobuf.Any" for field paths ending in "error.details", and, at + * run-time, the actual types for these fields must be one of the types in + * google/rpc/error_details.proto. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.singleDetailText + * Content to return in a singular `*.error.details` field of type + * `google.protobuf.Any` + * @param {string[]} request.multiDetailText + * Content to return in a repeated `*.error.details` field of type + * `google.protobuf.Any` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.EchoErrorDetailsResponse|EchoErrorDetailsResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/echo.echo_error_details.js + * region_tag:localhost_v1beta1_generated_Echo_EchoErrorDetails_async + */ echoErrorDetails( - request?: protos.google.showcase.v1beta1.IEchoErrorDetailsRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IEchoErrorDetailsResponse, - protos.google.showcase.v1beta1.IEchoErrorDetailsRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IEchoErrorDetailsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IEchoErrorDetailsResponse, + protos.google.showcase.v1beta1.IEchoErrorDetailsRequest | undefined, + {} | undefined, + ] + >; echoErrorDetails( - request: protos.google.showcase.v1beta1.IEchoErrorDetailsRequest, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.IEchoErrorDetailsResponse, - protos.google.showcase.v1beta1.IEchoErrorDetailsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IEchoErrorDetailsRequest, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.IEchoErrorDetailsResponse, + | protos.google.showcase.v1beta1.IEchoErrorDetailsRequest + | null + | undefined, + {} | null | undefined + >, + ): void; echoErrorDetails( - request: protos.google.showcase.v1beta1.IEchoErrorDetailsRequest, - callback: Callback< - protos.google.showcase.v1beta1.IEchoErrorDetailsResponse, - protos.google.showcase.v1beta1.IEchoErrorDetailsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IEchoErrorDetailsRequest, + callback: Callback< + protos.google.showcase.v1beta1.IEchoErrorDetailsResponse, + | protos.google.showcase.v1beta1.IEchoErrorDetailsRequest + | null + | undefined, + {} | null | undefined + >, + ): void; echoErrorDetails( - request?: protos.google.showcase.v1beta1.IEchoErrorDetailsRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.showcase.v1beta1.IEchoErrorDetailsResponse, - protos.google.showcase.v1beta1.IEchoErrorDetailsRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.showcase.v1beta1.IEchoErrorDetailsRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.IEchoErrorDetailsResponse, - protos.google.showcase.v1beta1.IEchoErrorDetailsRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.IEchoErrorDetailsResponse, - protos.google.showcase.v1beta1.IEchoErrorDetailsRequest|undefined, {}|undefined - ]>|void { + | protos.google.showcase.v1beta1.IEchoErrorDetailsRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.IEchoErrorDetailsResponse, + | protos.google.showcase.v1beta1.IEchoErrorDetailsRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IEchoErrorDetailsResponse, + protos.google.showcase.v1beta1.IEchoErrorDetailsRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('echoErrorDetails request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.IEchoErrorDetailsResponse, - protos.google.showcase.v1beta1.IEchoErrorDetailsRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.IEchoErrorDetailsResponse, + | protos.google.showcase.v1beta1.IEchoErrorDetailsRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('echoErrorDetails response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.echoErrorDetails(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.IEchoErrorDetailsResponse, - protos.google.showcase.v1beta1.IEchoErrorDetailsRequest|undefined, - {}|undefined - ]) => { - this._log.info('echoErrorDetails response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .echoErrorDetails(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.IEchoErrorDetailsResponse, + protos.google.showcase.v1beta1.IEchoErrorDetailsRequest | undefined, + {} | undefined, + ]) => { + this._log.info('echoErrorDetails response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * This is similar to the PagedExpand except that it uses - * max_results instead of page_size, as some legacy APIs still - * do. New APIs should NOT use this pattern. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.content - * The string to expand. - * @param {number} request.maxResults - * The number of words to returned in each page. - * (-- aip.dev/not-precedent: This is a legacy, non-standard pattern that - * violates aip.dev/158. Ordinarily, this should be page_size. --) - * @param {string} request.pageToken - * The position of the page to be returned. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.PagedExpandResponse|PagedExpandResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/echo.paged_expand_legacy.js - * region_tag:localhost_v1beta1_generated_Echo_PagedExpandLegacy_async - */ + /** + * This is similar to the PagedExpand except that it uses + * max_results instead of page_size, as some legacy APIs still + * do. New APIs should NOT use this pattern. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.content + * The string to expand. + * @param {number} request.maxResults + * The number of words to returned in each page. + * (-- aip.dev/not-precedent: This is a legacy, non-standard pattern that + * violates aip.dev/158. Ordinarily, this should be page_size. --) + * @param {string} request.pageToken + * The position of the page to be returned. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.PagedExpandResponse|PagedExpandResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/echo.paged_expand_legacy.js + * region_tag:localhost_v1beta1_generated_Echo_PagedExpandLegacy_async + */ pagedExpandLegacy( - request?: protos.google.showcase.v1beta1.IPagedExpandLegacyRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IPagedExpandResponse, - protos.google.showcase.v1beta1.IPagedExpandLegacyRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IPagedExpandLegacyRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IPagedExpandResponse, + protos.google.showcase.v1beta1.IPagedExpandLegacyRequest | undefined, + {} | undefined, + ] + >; pagedExpandLegacy( - request: protos.google.showcase.v1beta1.IPagedExpandLegacyRequest, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.IPagedExpandResponse, - protos.google.showcase.v1beta1.IPagedExpandLegacyRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IPagedExpandLegacyRequest, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.IPagedExpandResponse, + | protos.google.showcase.v1beta1.IPagedExpandLegacyRequest + | null + | undefined, + {} | null | undefined + >, + ): void; pagedExpandLegacy( - request: protos.google.showcase.v1beta1.IPagedExpandLegacyRequest, - callback: Callback< - protos.google.showcase.v1beta1.IPagedExpandResponse, - protos.google.showcase.v1beta1.IPagedExpandLegacyRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IPagedExpandLegacyRequest, + callback: Callback< + protos.google.showcase.v1beta1.IPagedExpandResponse, + | protos.google.showcase.v1beta1.IPagedExpandLegacyRequest + | null + | undefined, + {} | null | undefined + >, + ): void; pagedExpandLegacy( - request?: protos.google.showcase.v1beta1.IPagedExpandLegacyRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.showcase.v1beta1.IPagedExpandResponse, - protos.google.showcase.v1beta1.IPagedExpandLegacyRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.showcase.v1beta1.IPagedExpandLegacyRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.IPagedExpandResponse, - protos.google.showcase.v1beta1.IPagedExpandLegacyRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.IPagedExpandResponse, - protos.google.showcase.v1beta1.IPagedExpandLegacyRequest|undefined, {}|undefined - ]>|void { + | protos.google.showcase.v1beta1.IPagedExpandLegacyRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.IPagedExpandResponse, + | protos.google.showcase.v1beta1.IPagedExpandLegacyRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IPagedExpandResponse, + protos.google.showcase.v1beta1.IPagedExpandLegacyRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('pagedExpandLegacy request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.IPagedExpandResponse, - protos.google.showcase.v1beta1.IPagedExpandLegacyRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.IPagedExpandResponse, + | protos.google.showcase.v1beta1.IPagedExpandLegacyRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('pagedExpandLegacy response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.pagedExpandLegacy(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.IPagedExpandResponse, - protos.google.showcase.v1beta1.IPagedExpandLegacyRequest|undefined, - {}|undefined - ]) => { - this._log.info('pagedExpandLegacy response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .pagedExpandLegacy(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.IPagedExpandResponse, + protos.google.showcase.v1beta1.IPagedExpandLegacyRequest | undefined, + {} | undefined, + ]) => { + this._log.info('pagedExpandLegacy response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * This method will block (wait) for the requested amount of time - * and then return the response or error. - * This method showcases how a client handles delays or retries. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.protobuf.Duration} request.responseDelay - * The amount of time to block before returning a response. - * @param {google.rpc.Status} request.error - * The error that will be returned by the server. If this code is specified - * to be the OK rpc code, an empty response will be returned. - * @param {google.showcase.v1beta1.BlockResponse} request.success - * The response to be returned that will signify successful method call. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.BlockResponse|BlockResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/echo.block.js - * region_tag:localhost_v1beta1_generated_Echo_Block_async - */ + /** + * This method will block (wait) for the requested amount of time + * and then return the response or error. + * This method showcases how a client handles delays or retries. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.protobuf.Duration} request.responseDelay + * The amount of time to block before returning a response. + * @param {google.rpc.Status} request.error + * The error that will be returned by the server. If this code is specified + * to be the OK rpc code, an empty response will be returned. + * @param {google.showcase.v1beta1.BlockResponse} request.success + * The response to be returned that will signify successful method call. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.BlockResponse|BlockResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/echo.block.js + * region_tag:localhost_v1beta1_generated_Echo_Block_async + */ block( - request?: protos.google.showcase.v1beta1.IBlockRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IBlockResponse, - protos.google.showcase.v1beta1.IBlockRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IBlockRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IBlockResponse, + protos.google.showcase.v1beta1.IBlockRequest | undefined, + {} | undefined, + ] + >; block( - request: protos.google.showcase.v1beta1.IBlockRequest, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.IBlockResponse, - protos.google.showcase.v1beta1.IBlockRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IBlockRequest, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.IBlockResponse, + protos.google.showcase.v1beta1.IBlockRequest | null | undefined, + {} | null | undefined + >, + ): void; block( - request: protos.google.showcase.v1beta1.IBlockRequest, - callback: Callback< - protos.google.showcase.v1beta1.IBlockResponse, - protos.google.showcase.v1beta1.IBlockRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IBlockRequest, + callback: Callback< + protos.google.showcase.v1beta1.IBlockResponse, + protos.google.showcase.v1beta1.IBlockRequest | null | undefined, + {} | null | undefined + >, + ): void; block( - request?: protos.google.showcase.v1beta1.IBlockRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.showcase.v1beta1.IBlockResponse, - protos.google.showcase.v1beta1.IBlockRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.showcase.v1beta1.IBlockRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.IBlockResponse, - protos.google.showcase.v1beta1.IBlockRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.IBlockResponse, - protos.google.showcase.v1beta1.IBlockRequest|undefined, {}|undefined - ]>|void { + protos.google.showcase.v1beta1.IBlockRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.IBlockResponse, + protos.google.showcase.v1beta1.IBlockRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IBlockResponse, + protos.google.showcase.v1beta1.IBlockRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('block request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.IBlockResponse, - protos.google.showcase.v1beta1.IBlockRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.IBlockResponse, + protos.google.showcase.v1beta1.IBlockRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('block response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.block(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.IBlockResponse, - protos.google.showcase.v1beta1.IBlockRequest|undefined, - {}|undefined - ]) => { - this._log.info('block response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .block(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.IBlockResponse, + protos.google.showcase.v1beta1.IBlockRequest | undefined, + {} | undefined, + ]) => { + this._log.info('block response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * This method splits the given content into words and will pass each word back - * through the stream. This method showcases server-side streaming RPCs. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.content - * The content that will be split into words and returned on the stream. - * @param {google.rpc.Status} request.error - * The error that is thrown after all words are sent on the stream. - * @param {google.protobuf.Duration} request.streamWaitTime - * The wait time between each server streaming messages - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits {@link protos.google.showcase.v1beta1.EchoResponse|EchoResponse} on 'data' event. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#server-streaming | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/echo.expand.js - * region_tag:localhost_v1beta1_generated_Echo_Expand_async - */ + /** + * This method splits the given content into words and will pass each word back + * through the stream. This method showcases server-side streaming RPCs. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.content + * The content that will be split into words and returned on the stream. + * @param {google.rpc.Status} request.error + * The error that is thrown after all words are sent on the stream. + * @param {google.protobuf.Duration} request.streamWaitTime + * The wait time between each server streaming messages + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits {@link protos.google.showcase.v1beta1.EchoResponse|EchoResponse} on 'data' event. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#server-streaming | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/echo.expand.js + * region_tag:localhost_v1beta1_generated_Echo_Expand_async + */ expand( - request?: protos.google.showcase.v1beta1.IExpandRequest, - options?: CallOptions): - gax.CancellableStream{ + request?: protos.google.showcase.v1beta1.IExpandRequest, + options?: CallOptions, + ): gax.CancellableStream { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('expand stream %j', options); return this.innerApiCalls.expand(request, options); } -/** - * This method will collect the words given to it. When the stream is closed - * by the client, this method will return the a concatenation of the strings - * passed to it. This method showcases client-side streaming RPCs. - * - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - A writable stream which accepts objects representing - * {@link protos.google.showcase.v1beta1.EchoRequest|EchoRequest}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#client-streaming | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/echo.collect.js - * region_tag:localhost_v1beta1_generated_Echo_Collect_async - */ + /** + * This method will collect the words given to it. When the stream is closed + * by the client, this method will return the a concatenation of the strings + * passed to it. This method showcases client-side streaming RPCs. + * + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} - A writable stream which accepts objects representing + * {@link protos.google.showcase.v1beta1.EchoRequest|EchoRequest}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#client-streaming | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/echo.collect.js + * region_tag:localhost_v1beta1_generated_Echo_Collect_async + */ collect( - options?: CallOptions, - callback?: Callback< - protos.google.showcase.v1beta1.IEchoResponse, - protos.google.showcase.v1beta1.IEchoRequest|null|undefined, - {}|null|undefined>): - gax.CancellableStream; + options?: CallOptions, + callback?: Callback< + protos.google.showcase.v1beta1.IEchoResponse, + protos.google.showcase.v1beta1.IEchoRequest | null | undefined, + {} | null | undefined + >, + ): gax.CancellableStream; collect( - callback?: Callback< - protos.google.showcase.v1beta1.IEchoResponse, - protos.google.showcase.v1beta1.IEchoRequest|null|undefined, - {}|null|undefined>): - gax.CancellableStream; + callback?: Callback< + protos.google.showcase.v1beta1.IEchoResponse, + protos.google.showcase.v1beta1.IEchoRequest | null | undefined, + {} | null | undefined + >, + ): gax.CancellableStream; collect( - optionsOrCallback?: CallOptions|Callback< - protos.google.showcase.v1beta1.IEchoResponse, - protos.google.showcase.v1beta1.IEchoRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.showcase.v1beta1.IEchoResponse, - protos.google.showcase.v1beta1.IEchoRequest|null|undefined, - {}|null|undefined>): - gax.CancellableStream { + optionsOrCallback?: + | CallOptions + | Callback< + protos.google.showcase.v1beta1.IEchoResponse, + protos.google.showcase.v1beta1.IEchoRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.IEchoResponse, + protos.google.showcase.v1beta1.IEchoRequest | null | undefined, + {} | null | undefined + >, + ): gax.CancellableStream { if (optionsOrCallback instanceof Function && callback === undefined) { - callback = optionsOrCallback; - optionsOrCallback = {}; + callback = optionsOrCallback; + optionsOrCallback = {}; } const options = optionsOrCallback as CallOptions; - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('collect stream %j', options); return this.innerApiCalls.collect(null, options, callback); } -/** - * This method, upon receiving a request on the stream, will pass the same - * content back on the stream. This method showcases bidirectional - * streaming RPCs. - * - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which is both readable and writable. It accepts objects - * representing {@link protos.google.showcase.v1beta1.EchoRequest|EchoRequest} for write() method, and - * will emit objects representing {@link protos.google.showcase.v1beta1.EchoResponse|EchoResponse} on 'data' event asynchronously. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#bi-directional-streaming | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/echo.chat.js - * region_tag:localhost_v1beta1_generated_Echo_Chat_async - */ - chat( - options?: CallOptions): - gax.CancellableStream { - this.initialize().catch(err => {throw err}); + /** + * This method, upon receiving a request on the stream, will pass the same + * content back on the stream. This method showcases bidirectional + * streaming RPCs. + * + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which is both readable and writable. It accepts objects + * representing {@link protos.google.showcase.v1beta1.EchoRequest|EchoRequest} for write() method, and + * will emit objects representing {@link protos.google.showcase.v1beta1.EchoResponse|EchoResponse} on 'data' event asynchronously. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#bi-directional-streaming | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/echo.chat.js + * region_tag:localhost_v1beta1_generated_Echo_Chat_async + */ + chat(options?: CallOptions): gax.CancellableStream { + this.initialize().catch((err) => { + throw err; + }); this._log.info('chat stream %j', options); return this.innerApiCalls.chat(null, options); } -/** - * This method will wait for the requested amount of time and then return. - * This method showcases how a client handles a request timeout. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.protobuf.Timestamp} request.endTime - * The time that this operation will complete. - * @param {google.protobuf.Duration} request.ttl - * The duration of this operation. - * @param {google.rpc.Status} request.error - * The error that will be returned by the server. If this code is specified - * to be the OK rpc code, an empty response will be returned. - * @param {google.showcase.v1beta1.WaitResponse} request.success - * The response to be returned on operation completion. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing - * a long running operation. Its `promise()` method returns a promise - * you can `await` for. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/echo.wait.js - * region_tag:localhost_v1beta1_generated_Echo_Wait_async - */ + /** + * This method will wait for the requested amount of time and then return. + * This method showcases how a client handles a request timeout. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.protobuf.Timestamp} request.endTime + * The time that this operation will complete. + * @param {google.protobuf.Duration} request.ttl + * The duration of this operation. + * @param {google.rpc.Status} request.error + * The error that will be returned by the server. If this code is specified + * to be the OK rpc code, an empty response will be returned. + * @param {google.showcase.v1beta1.WaitResponse} request.success + * The response to be returned on operation completion. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/echo.wait.js + * region_tag:localhost_v1beta1_generated_Echo_Wait_async + */ wait( - request?: protos.google.showcase.v1beta1.IWaitRequest, - options?: CallOptions): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IWaitRequest, + options?: CallOptions, + ): Promise< + [ + LROperation< + protos.google.showcase.v1beta1.IWaitResponse, + protos.google.showcase.v1beta1.IWaitMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; wait( - request: protos.google.showcase.v1beta1.IWaitRequest, - options: CallOptions, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IWaitRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.showcase.v1beta1.IWaitResponse, + protos.google.showcase.v1beta1.IWaitMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; wait( - request: protos.google.showcase.v1beta1.IWaitRequest, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IWaitRequest, + callback: Callback< + LROperation< + protos.google.showcase.v1beta1.IWaitResponse, + protos.google.showcase.v1beta1.IWaitMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; wait( - request?: protos.google.showcase.v1beta1.IWaitRequest, - optionsOrCallback?: CallOptions|Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>, - callback?: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>|void { + request?: protos.google.showcase.v1beta1.IWaitRequest, + optionsOrCallback?: + | CallOptions + | Callback< + LROperation< + protos.google.showcase.v1beta1.IWaitResponse, + protos.google.showcase.v1beta1.IWaitMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + callback?: Callback< + LROperation< + protos.google.showcase.v1beta1.IWaitResponse, + protos.google.showcase.v1beta1.IWaitMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + LROperation< + protos.google.showcase.v1beta1.IWaitResponse, + protos.google.showcase.v1beta1.IWaitMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize().catch(err => {throw err}); - const wrappedCallback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>|undefined = callback + this.initialize().catch((err) => { + throw err; + }); + const wrappedCallback: + | Callback< + LROperation< + protos.google.showcase.v1beta1.IWaitResponse, + protos.google.showcase.v1beta1.IWaitMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, rawResponse, _) => { this._log.info('wait response %j', rawResponse); callback!(error, response, rawResponse, _); // We verified callback above. } : undefined; this._log.info('wait request %j', request); - return this.innerApiCalls.wait(request, options, wrappedCallback) - ?.then(([response, rawResponse, _]: [ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]) => { - this._log.info('wait response %j', rawResponse); - return [response, rawResponse, _]; - }); + return this.innerApiCalls + .wait(request, options, wrappedCallback) + ?.then( + ([response, rawResponse, _]: [ + LROperation< + protos.google.showcase.v1beta1.IWaitResponse, + protos.google.showcase.v1beta1.IWaitMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ]) => { + this._log.info('wait response %j', rawResponse); + return [response, rawResponse, _]; + }, + ); } -/** - * Check the status of the long running operation returned by `wait()`. - * @param {String} name - * The operation name that will be passed. - * @returns {Promise} - The promise which resolves to an object. - * The decoded operation object has result and metadata field to get information from. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/echo.wait.js - * region_tag:localhost_v1beta1_generated_Echo_Wait_async - */ - async checkWaitProgress(name: string): Promise>{ + /** + * Check the status of the long running operation returned by `wait()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/echo.wait.js + * region_tag:localhost_v1beta1_generated_Echo_Wait_async + */ + async checkWaitProgress( + name: string, + ): Promise< + LROperation< + protos.google.showcase.v1beta1.WaitResponse, + protos.google.showcase.v1beta1.WaitMetadata + > + > { this._log.info('wait long-running'); - const request = new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest({name}); + const request = + new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( + { name }, + ); const [operation] = await this.operationsClient.getOperation(request); - const decodeOperation = new this._gaxModule.Operation(operation, this.descriptors.longrunning.wait, this._gaxModule.createDefaultBackoffSettings()); - return decodeOperation as LROperation; + const decodeOperation = new this._gaxModule.Operation( + operation, + this.descriptors.longrunning.wait, + this._gaxModule.createDefaultBackoffSettings(), + ); + return decodeOperation as LROperation< + protos.google.showcase.v1beta1.WaitResponse, + protos.google.showcase.v1beta1.WaitMetadata + >; } - /** - * This is similar to the Expand method but instead of returning a stream of - * expanded words, this method returns a paged list of expanded words. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.content - * The string to expand. - * @param {number} request.pageSize - * The number of words to returned in each page. - * @param {string} request.pageToken - * The position of the page to be returned. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.showcase.v1beta1.EchoResponse|EchoResponse}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `pagedExpandAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * This is similar to the Expand method but instead of returning a stream of + * expanded words, this method returns a paged list of expanded words. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.content + * The string to expand. + * @param {number} request.pageSize + * The number of words to returned in each page. + * @param {string} request.pageToken + * The position of the page to be returned. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.showcase.v1beta1.EchoResponse|EchoResponse}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `pagedExpandAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ pagedExpand( - request?: protos.google.showcase.v1beta1.IPagedExpandRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IEchoResponse[], - protos.google.showcase.v1beta1.IPagedExpandRequest|null, - protos.google.showcase.v1beta1.IPagedExpandResponse - ]>; + request?: protos.google.showcase.v1beta1.IPagedExpandRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IEchoResponse[], + protos.google.showcase.v1beta1.IPagedExpandRequest | null, + protos.google.showcase.v1beta1.IPagedExpandResponse, + ] + >; pagedExpand( - request: protos.google.showcase.v1beta1.IPagedExpandRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.showcase.v1beta1.IPagedExpandRequest, - protos.google.showcase.v1beta1.IPagedExpandResponse|null|undefined, - protos.google.showcase.v1beta1.IEchoResponse>): void; + request: protos.google.showcase.v1beta1.IPagedExpandRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.showcase.v1beta1.IPagedExpandRequest, + protos.google.showcase.v1beta1.IPagedExpandResponse | null | undefined, + protos.google.showcase.v1beta1.IEchoResponse + >, + ): void; pagedExpand( - request: protos.google.showcase.v1beta1.IPagedExpandRequest, - callback: PaginationCallback< - protos.google.showcase.v1beta1.IPagedExpandRequest, - protos.google.showcase.v1beta1.IPagedExpandResponse|null|undefined, - protos.google.showcase.v1beta1.IEchoResponse>): void; + request: protos.google.showcase.v1beta1.IPagedExpandRequest, + callback: PaginationCallback< + protos.google.showcase.v1beta1.IPagedExpandRequest, + protos.google.showcase.v1beta1.IPagedExpandResponse | null | undefined, + protos.google.showcase.v1beta1.IEchoResponse + >, + ): void; pagedExpand( - request?: protos.google.showcase.v1beta1.IPagedExpandRequest, - optionsOrCallback?: CallOptions|PaginationCallback< + request?: protos.google.showcase.v1beta1.IPagedExpandRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.showcase.v1beta1.IPagedExpandRequest, - protos.google.showcase.v1beta1.IPagedExpandResponse|null|undefined, - protos.google.showcase.v1beta1.IEchoResponse>, - callback?: PaginationCallback< - protos.google.showcase.v1beta1.IPagedExpandRequest, - protos.google.showcase.v1beta1.IPagedExpandResponse|null|undefined, - protos.google.showcase.v1beta1.IEchoResponse>): - Promise<[ - protos.google.showcase.v1beta1.IEchoResponse[], - protos.google.showcase.v1beta1.IPagedExpandRequest|null, - protos.google.showcase.v1beta1.IPagedExpandResponse - ]>|void { + | protos.google.showcase.v1beta1.IPagedExpandResponse + | null + | undefined, + protos.google.showcase.v1beta1.IEchoResponse + >, + callback?: PaginationCallback< + protos.google.showcase.v1beta1.IPagedExpandRequest, + protos.google.showcase.v1beta1.IPagedExpandResponse | null | undefined, + protos.google.showcase.v1beta1.IEchoResponse + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IEchoResponse[], + protos.google.showcase.v1beta1.IPagedExpandRequest | null, + protos.google.showcase.v1beta1.IPagedExpandResponse, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.showcase.v1beta1.IPagedExpandRequest, - protos.google.showcase.v1beta1.IPagedExpandResponse|null|undefined, - protos.google.showcase.v1beta1.IEchoResponse>|undefined = callback + this.initialize().catch((err) => { + throw err; + }); + const wrappedCallback: + | PaginationCallback< + protos.google.showcase.v1beta1.IPagedExpandRequest, + | protos.google.showcase.v1beta1.IPagedExpandResponse + | null + | undefined, + protos.google.showcase.v1beta1.IEchoResponse + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('pagedExpand values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -1189,96 +1521,102 @@ export class EchoClient { this._log.info('pagedExpand request %j', request); return this.innerApiCalls .pagedExpand(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.showcase.v1beta1.IEchoResponse[], - protos.google.showcase.v1beta1.IPagedExpandRequest|null, - protos.google.showcase.v1beta1.IPagedExpandResponse - ]) => { - this._log.info('pagedExpand values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.showcase.v1beta1.IEchoResponse[], + protos.google.showcase.v1beta1.IPagedExpandRequest | null, + protos.google.showcase.v1beta1.IPagedExpandResponse, + ]) => { + this._log.info('pagedExpand values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `pagedExpand`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.content - * The string to expand. - * @param {number} request.pageSize - * The number of words to returned in each page. - * @param {string} request.pageToken - * The position of the page to be returned. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.showcase.v1beta1.EchoResponse|EchoResponse} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `pagedExpandAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `pagedExpand`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.content + * The string to expand. + * @param {number} request.pageSize + * The number of words to returned in each page. + * @param {string} request.pageToken + * The position of the page to be returned. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.showcase.v1beta1.EchoResponse|EchoResponse} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `pagedExpandAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ pagedExpandStream( - request?: protos.google.showcase.v1beta1.IPagedExpandRequest, - options?: CallOptions): - Transform{ + request?: protos.google.showcase.v1beta1.IPagedExpandRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; const defaultCallSettings = this._defaults['pagedExpand']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('pagedExpand stream %j', request); return this.descriptors.page.pagedExpand.createStream( this.innerApiCalls.pagedExpand as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `pagedExpand`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.content - * The string to expand. - * @param {number} request.pageSize - * The number of words to returned in each page. - * @param {string} request.pageToken - * The position of the page to be returned. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.showcase.v1beta1.EchoResponse|EchoResponse}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/echo.paged_expand.js - * region_tag:localhost_v1beta1_generated_Echo_PagedExpand_async - */ + /** + * Equivalent to `pagedExpand`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.content + * The string to expand. + * @param {number} request.pageSize + * The number of words to returned in each page. + * @param {string} request.pageToken + * The position of the page to be returned. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.showcase.v1beta1.EchoResponse|EchoResponse}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/echo.paged_expand.js + * region_tag:localhost_v1beta1_generated_Echo_PagedExpand_async + */ pagedExpandAsync( - request?: protos.google.showcase.v1beta1.IPagedExpandRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.showcase.v1beta1.IPagedExpandRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; const defaultCallSettings = this._defaults['pagedExpand']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('pagedExpand iterate %j', request); return this.descriptors.page.pagedExpand.asyncIterate( this.innerApiCalls['pagedExpand'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } // -------------------- @@ -1293,7 +1631,7 @@ export class EchoClient { * @param {string} blueprint * @returns {string} Resource name string. */ - blueprintPath(session:string,test:string,blueprint:string) { + blueprintPath(session: string, test: string, blueprint: string) { return this.pathTemplates.blueprintPathTemplate.render({ session: session, test: test, @@ -1309,7 +1647,8 @@ export class EchoClient { * @returns {string} A string representing the session. */ matchSessionFromBlueprintName(blueprintName: string) { - return this.pathTemplates.blueprintPathTemplate.match(blueprintName).session; + return this.pathTemplates.blueprintPathTemplate.match(blueprintName) + .session; } /** @@ -1331,7 +1670,8 @@ export class EchoClient { * @returns {string} A string representing the blueprint. */ matchBlueprintFromBlueprintName(blueprintName: string) { - return this.pathTemplates.blueprintPathTemplate.match(blueprintName).blueprint; + return this.pathTemplates.blueprintPathTemplate.match(blueprintName) + .blueprint; } /** @@ -1340,7 +1680,7 @@ export class EchoClient { * @param {string} room * @returns {string} Resource name string. */ - roomPath(room:string) { + roomPath(room: string) { return this.pathTemplates.roomPathTemplate.render({ room: room, }); @@ -1364,7 +1704,7 @@ export class EchoClient { * @param {string} blurb * @returns {string} Resource name string. */ - roomBlurbPath(room:string,blurb:string) { + roomBlurbPath(room: string, blurb: string) { return this.pathTemplates.roomBlurbPathTemplate.render({ room: room, blurb: blurb, @@ -1401,7 +1741,11 @@ export class EchoClient { * @param {string} blurb * @returns {string} Resource name string. */ - roomBlurbsLegacyRoomBlurbPath(room:string,legacyRoom:string,blurb:string) { + roomBlurbsLegacyRoomBlurbPath( + room: string, + legacyRoom: string, + blurb: string, + ) { return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.render({ room: room, legacy_room: legacyRoom, @@ -1416,8 +1760,12 @@ export class EchoClient { * A fully-qualified path representing room_blurbs_legacy_room_blurb resource. * @returns {string} A string representing the room. */ - matchRoomFromRoomBlurbsLegacyRoomBlurbName(roomBlurbsLegacyRoomBlurbName: string) { - return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match(roomBlurbsLegacyRoomBlurbName).room; + matchRoomFromRoomBlurbsLegacyRoomBlurbName( + roomBlurbsLegacyRoomBlurbName: string, + ) { + return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match( + roomBlurbsLegacyRoomBlurbName, + ).room; } /** @@ -1427,8 +1775,12 @@ export class EchoClient { * A fully-qualified path representing room_blurbs_legacy_room_blurb resource. * @returns {string} A string representing the legacy_room. */ - matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName(roomBlurbsLegacyRoomBlurbName: string) { - return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match(roomBlurbsLegacyRoomBlurbName).legacy_room; + matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName( + roomBlurbsLegacyRoomBlurbName: string, + ) { + return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match( + roomBlurbsLegacyRoomBlurbName, + ).legacy_room; } /** @@ -1438,8 +1790,12 @@ export class EchoClient { * A fully-qualified path representing room_blurbs_legacy_room_blurb resource. * @returns {string} A string representing the blurb. */ - matchBlurbFromRoomBlurbsLegacyRoomBlurbName(roomBlurbsLegacyRoomBlurbName: string) { - return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match(roomBlurbsLegacyRoomBlurbName).blurb; + matchBlurbFromRoomBlurbsLegacyRoomBlurbName( + roomBlurbsLegacyRoomBlurbName: string, + ) { + return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match( + roomBlurbsLegacyRoomBlurbName, + ).blurb; } /** @@ -1448,7 +1804,7 @@ export class EchoClient { * @param {string} sequence * @returns {string} Resource name string. */ - sequencePath(sequence:string) { + sequencePath(sequence: string) { return this.pathTemplates.sequencePathTemplate.render({ sequence: sequence, }); @@ -1471,7 +1827,7 @@ export class EchoClient { * @param {string} sequence * @returns {string} Resource name string. */ - sequenceReportPath(sequence:string) { + sequenceReportPath(sequence: string) { return this.pathTemplates.sequenceReportPathTemplate.render({ sequence: sequence, }); @@ -1485,7 +1841,9 @@ export class EchoClient { * @returns {string} A string representing the sequence. */ matchSequenceFromSequenceReportName(sequenceReportName: string) { - return this.pathTemplates.sequenceReportPathTemplate.match(sequenceReportName).sequence; + return this.pathTemplates.sequenceReportPathTemplate.match( + sequenceReportName, + ).sequence; } /** @@ -1494,7 +1852,7 @@ export class EchoClient { * @param {string} session * @returns {string} Resource name string. */ - sessionPath(session:string) { + sessionPath(session: string) { return this.pathTemplates.sessionPathTemplate.render({ session: session, }); @@ -1518,7 +1876,7 @@ export class EchoClient { * @param {string} test * @returns {string} Resource name string. */ - testPath(session:string,test:string) { + testPath(session: string, test: string) { return this.pathTemplates.testPathTemplate.render({ session: session, test: test, @@ -1553,7 +1911,7 @@ export class EchoClient { * @param {string} user * @returns {string} Resource name string. */ - userPath(user:string) { + userPath(user: string) { return this.pathTemplates.userPathTemplate.render({ user: user, }); @@ -1577,7 +1935,7 @@ export class EchoClient { * @param {string} blurb * @returns {string} Resource name string. */ - userProfileBlurbPath(user:string,blurb:string) { + userProfileBlurbPath(user: string, blurb: string) { return this.pathTemplates.userProfileBlurbPathTemplate.render({ user: user, blurb: blurb, @@ -1592,7 +1950,9 @@ export class EchoClient { * @returns {string} A string representing the user. */ matchUserFromUserProfileBlurbName(userProfileBlurbName: string) { - return this.pathTemplates.userProfileBlurbPathTemplate.match(userProfileBlurbName).user; + return this.pathTemplates.userProfileBlurbPathTemplate.match( + userProfileBlurbName, + ).user; } /** @@ -1603,7 +1963,9 @@ export class EchoClient { * @returns {string} A string representing the blurb. */ matchBlurbFromUserProfileBlurbName(userProfileBlurbName: string) { - return this.pathTemplates.userProfileBlurbPathTemplate.match(userProfileBlurbName).blurb; + return this.pathTemplates.userProfileBlurbPathTemplate.match( + userProfileBlurbName, + ).blurb; } /** @@ -1614,12 +1976,18 @@ export class EchoClient { * @param {string} blurb * @returns {string} Resource name string. */ - userProfileBlurbsLegacyUserBlurbPath(user:string,legacyUser:string,blurb:string) { - return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.render({ - user: user, - legacy_user: legacyUser, - blurb: blurb, - }); + userProfileBlurbsLegacyUserBlurbPath( + user: string, + legacyUser: string, + blurb: string, + ) { + return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.render( + { + user: user, + legacy_user: legacyUser, + blurb: blurb, + }, + ); } /** @@ -1629,8 +1997,12 @@ export class EchoClient { * A fully-qualified path representing user_profile_blurbs_legacy_user_blurb resource. * @returns {string} A string representing the user. */ - matchUserFromUserProfileBlurbsLegacyUserBlurbName(userProfileBlurbsLegacyUserBlurbName: string) { - return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match(userProfileBlurbsLegacyUserBlurbName).user; + matchUserFromUserProfileBlurbsLegacyUserBlurbName( + userProfileBlurbsLegacyUserBlurbName: string, + ) { + return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match( + userProfileBlurbsLegacyUserBlurbName, + ).user; } /** @@ -1640,8 +2012,12 @@ export class EchoClient { * A fully-qualified path representing user_profile_blurbs_legacy_user_blurb resource. * @returns {string} A string representing the legacy_user. */ - matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName(userProfileBlurbsLegacyUserBlurbName: string) { - return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match(userProfileBlurbsLegacyUserBlurbName).legacy_user; + matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName( + userProfileBlurbsLegacyUserBlurbName: string, + ) { + return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match( + userProfileBlurbsLegacyUserBlurbName, + ).legacy_user; } /** @@ -1651,8 +2027,12 @@ export class EchoClient { * A fully-qualified path representing user_profile_blurbs_legacy_user_blurb resource. * @returns {string} A string representing the blurb. */ - matchBlurbFromUserProfileBlurbsLegacyUserBlurbName(userProfileBlurbsLegacyUserBlurbName: string) { - return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match(userProfileBlurbsLegacyUserBlurbName).blurb; + matchBlurbFromUserProfileBlurbsLegacyUserBlurbName( + userProfileBlurbsLegacyUserBlurbName: string, + ) { + return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match( + userProfileBlurbsLegacyUserBlurbName, + ).blurb; } /** @@ -1663,7 +2043,7 @@ export class EchoClient { */ close(): Promise { if (this.echoStub && !this._terminated) { - return this.echoStub.then(stub => { + return this.echoStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -1672,4 +2052,4 @@ export class EchoClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/core/generator/gapic-generator-typescript/baselines/disable-packing-test/src/v1beta1/identity_client.ts.baseline b/core/generator/gapic-generator-typescript/baselines/disable-packing-test/src/v1beta1/identity_client.ts.baseline index 8eeb4b4bce52..d1e73b2eb6dc 100644 --- a/core/generator/gapic-generator-typescript/baselines/disable-packing-test/src/v1beta1/identity_client.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/disable-packing-test/src/v1beta1/identity_client.ts.baseline @@ -18,11 +18,18 @@ /* global window */ import type * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions, PaginationCallback, GaxCall} from 'google-gax'; -import {Transform} from 'stream'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + PaginationCallback, + GaxCall, +} from 'google-gax'; +import { Transform } from 'stream'; import * as protos from '../../protos/protos'; import jsonProtos = require('../../protos/protos.json'); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; /** * Client JSON configuration object, loaded from @@ -44,7 +51,7 @@ export class IdentityClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('showcase'); @@ -57,9 +64,9 @@ export class IdentityClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; - identityStub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; + identityStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of IdentityClient. @@ -100,21 +107,42 @@ export class IdentityClient { * const client = new IdentityClient({fallback: true}, gax); * ``` */ - constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { // Ensure that options include all the required fields. const staticMembers = this.constructor as typeof IdentityClient; - if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { - throw new Error('Please set either universe_domain or universeDomain, but not both.'); + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); } - const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; - this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; this._servicePath = 'localhost'; - const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; - const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. if (servicePath !== this._servicePath && !('scopes' in opts)) { @@ -136,7 +164,7 @@ export class IdentityClient { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; @@ -150,10 +178,7 @@ export class IdentityClient { } // Determine the client header string. - const clientHeader = [ - `gax/${this._gaxModule.version}`, - `gapic/${version}`, - ]; + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/${process.versions.node}`); } else { @@ -175,52 +200,55 @@ export class IdentityClient { // Create useful helper objects for these. this.pathTemplates = { blueprintPathTemplate: new this._gaxModule.PathTemplate( - 'sessions/{session}/tests/{test}/blueprints/{blueprint}' - ), - roomPathTemplate: new this._gaxModule.PathTemplate( - 'rooms/{room}' + 'sessions/{session}/tests/{test}/blueprints/{blueprint}', ), + roomPathTemplate: new this._gaxModule.PathTemplate('rooms/{room}'), roomBlurbPathTemplate: new this._gaxModule.PathTemplate( - 'rooms/{room}/blurbs/{blurb}' + 'rooms/{room}/blurbs/{blurb}', ), roomBlurbsLegacyRoomBlurbPathTemplate: new this._gaxModule.PathTemplate( - 'rooms/{room}/blurbs/legacy/{legacy_room}.{blurb}' + 'rooms/{room}/blurbs/legacy/{legacy_room}.{blurb}', ), sequencePathTemplate: new this._gaxModule.PathTemplate( - 'sequences/{sequence}' + 'sequences/{sequence}', ), sequenceReportPathTemplate: new this._gaxModule.PathTemplate( - 'sequences/{sequence}/sequenceReport' + 'sequences/{sequence}/sequenceReport', ), sessionPathTemplate: new this._gaxModule.PathTemplate( - 'sessions/{session}' + 'sessions/{session}', ), testPathTemplate: new this._gaxModule.PathTemplate( - 'sessions/{session}/tests/{test}' - ), - userPathTemplate: new this._gaxModule.PathTemplate( - 'users/{user}' + 'sessions/{session}/tests/{test}', ), + userPathTemplate: new this._gaxModule.PathTemplate('users/{user}'), userProfileBlurbPathTemplate: new this._gaxModule.PathTemplate( - 'users/{user}/profile/blurbs/{blurb}' - ), - userProfileBlurbsLegacyUserBlurbPathTemplate: new this._gaxModule.PathTemplate( - 'users/{user}/profile/blurbs/legacy/{legacy_user}~{blurb}' + 'users/{user}/profile/blurbs/{blurb}', ), + userProfileBlurbsLegacyUserBlurbPathTemplate: + new this._gaxModule.PathTemplate( + 'users/{user}/profile/blurbs/legacy/{legacy_user}~{blurb}', + ), }; // Some of the methods on this service return "paged" results, // (e.g. 50 results at a time, with tokens to get subsequent // pages). Denote the keys used for pagination and results. this.descriptors.page = { - listUsers: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'users') + listUsers: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'users', + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.showcase.v1beta1.Identity', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.showcase.v1beta1.Identity', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + { 'x-goog-api-client': clientHeader.join(' ') }, + ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -251,37 +279,46 @@ export class IdentityClient { // Put together the "service stub" for // google.showcase.v1beta1.Identity. this.identityStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.showcase.v1beta1.Identity') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.showcase.v1beta1.Identity', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.showcase.v1beta1.Identity, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts, + this._providedCustomServicePath, + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const identityStubMethods = - ['createUser', 'getUser', 'updateUser', 'deleteUser', 'listUsers']; + const identityStubMethods = [ + 'createUser', + 'getUser', + 'updateUser', + 'deleteUser', + 'listUsers', + ]; for (const methodName of identityStubMethods) { const callPromise = this.identityStub.then( - stub => (...args: Array<{}>) => { - if (this._terminated) { - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error|null|undefined) => () => { + (stub) => + (...args: Array<{}>) => { + if (this._terminated) { + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { throw err; - }); + }, + ); - const descriptor = - this.descriptors.page[methodName] || - undefined; + const descriptor = this.descriptors.page[methodName] || undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -296,8 +333,14 @@ export class IdentityClient { * @returns {string} The DNS address for this service. */ static get servicePath() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'localhost'; } @@ -308,8 +351,14 @@ export class IdentityClient { * @returns {string} The DNS address for this service. */ static get apiEndpoint() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'localhost'; } @@ -349,8 +398,9 @@ export class IdentityClient { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId(callback?: Callback): - Promise|void { + getProjectId( + callback?: Callback, + ): Promise | void { if (callback) { this.auth.getProjectId(callback); return; @@ -361,458 +411,595 @@ export class IdentityClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Creates a user. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.showcase.v1beta1.User} request.user - * The user to create. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.User|User}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/identity.create_user.js - * region_tag:localhost_v1beta1_generated_Identity_CreateUser_async - */ + /** + * Creates a user. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.showcase.v1beta1.User} request.user + * The user to create. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.User|User}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/identity.create_user.js + * region_tag:localhost_v1beta1_generated_Identity_CreateUser_async + */ createUser( - request?: protos.google.showcase.v1beta1.ICreateUserRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IUser, - protos.google.showcase.v1beta1.ICreateUserRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.ICreateUserRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IUser, + protos.google.showcase.v1beta1.ICreateUserRequest | undefined, + {} | undefined, + ] + >; createUser( - request: protos.google.showcase.v1beta1.ICreateUserRequest, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.IUser, - protos.google.showcase.v1beta1.ICreateUserRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.ICreateUserRequest, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.IUser, + protos.google.showcase.v1beta1.ICreateUserRequest | null | undefined, + {} | null | undefined + >, + ): void; createUser( - request: protos.google.showcase.v1beta1.ICreateUserRequest, - callback: Callback< - protos.google.showcase.v1beta1.IUser, - protos.google.showcase.v1beta1.ICreateUserRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.ICreateUserRequest, + callback: Callback< + protos.google.showcase.v1beta1.IUser, + protos.google.showcase.v1beta1.ICreateUserRequest | null | undefined, + {} | null | undefined + >, + ): void; createUser( - request?: protos.google.showcase.v1beta1.ICreateUserRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.showcase.v1beta1.ICreateUserRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.IUser, - protos.google.showcase.v1beta1.ICreateUserRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.showcase.v1beta1.IUser, - protos.google.showcase.v1beta1.ICreateUserRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.IUser, - protos.google.showcase.v1beta1.ICreateUserRequest|undefined, {}|undefined - ]>|void { + protos.google.showcase.v1beta1.ICreateUserRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.IUser, + protos.google.showcase.v1beta1.ICreateUserRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IUser, + protos.google.showcase.v1beta1.ICreateUserRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('createUser request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.IUser, - protos.google.showcase.v1beta1.ICreateUserRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.IUser, + protos.google.showcase.v1beta1.ICreateUserRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createUser response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.createUser(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.IUser, - protos.google.showcase.v1beta1.ICreateUserRequest|undefined, - {}|undefined - ]) => { - this._log.info('createUser response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createUser(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.IUser, + protos.google.showcase.v1beta1.ICreateUserRequest | undefined, + {} | undefined, + ]) => { + this._log.info('createUser response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Retrieves the User with the given uri. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * The resource name of the requested user. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.User|User}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/identity.get_user.js - * region_tag:localhost_v1beta1_generated_Identity_GetUser_async - */ + /** + * Retrieves the User with the given uri. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * The resource name of the requested user. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.User|User}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/identity.get_user.js + * region_tag:localhost_v1beta1_generated_Identity_GetUser_async + */ getUser( - request?: protos.google.showcase.v1beta1.IGetUserRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IUser, - protos.google.showcase.v1beta1.IGetUserRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IGetUserRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IUser, + protos.google.showcase.v1beta1.IGetUserRequest | undefined, + {} | undefined, + ] + >; getUser( - request: protos.google.showcase.v1beta1.IGetUserRequest, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.IUser, - protos.google.showcase.v1beta1.IGetUserRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IGetUserRequest, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.IUser, + protos.google.showcase.v1beta1.IGetUserRequest | null | undefined, + {} | null | undefined + >, + ): void; getUser( - request: protos.google.showcase.v1beta1.IGetUserRequest, - callback: Callback< - protos.google.showcase.v1beta1.IUser, - protos.google.showcase.v1beta1.IGetUserRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IGetUserRequest, + callback: Callback< + protos.google.showcase.v1beta1.IUser, + protos.google.showcase.v1beta1.IGetUserRequest | null | undefined, + {} | null | undefined + >, + ): void; getUser( - request?: protos.google.showcase.v1beta1.IGetUserRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.showcase.v1beta1.IGetUserRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.IUser, - protos.google.showcase.v1beta1.IGetUserRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.showcase.v1beta1.IUser, - protos.google.showcase.v1beta1.IGetUserRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.IUser, - protos.google.showcase.v1beta1.IGetUserRequest|undefined, {}|undefined - ]>|void { + protos.google.showcase.v1beta1.IGetUserRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.IUser, + protos.google.showcase.v1beta1.IGetUserRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IUser, + protos.google.showcase.v1beta1.IGetUserRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getUser request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.IUser, - protos.google.showcase.v1beta1.IGetUserRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.IUser, + protos.google.showcase.v1beta1.IGetUserRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getUser response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getUser(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.IUser, - protos.google.showcase.v1beta1.IGetUserRequest|undefined, - {}|undefined - ]) => { - this._log.info('getUser response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getUser(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.IUser, + protos.google.showcase.v1beta1.IGetUserRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getUser response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Updates a user. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.showcase.v1beta1.User} request.user - * The user to update. - * @param {google.protobuf.FieldMask} request.updateMask - * The field mask to determine which fields are to be updated. If empty, the - * server will assume all fields are to be updated. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.User|User}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/identity.update_user.js - * region_tag:localhost_v1beta1_generated_Identity_UpdateUser_async - */ + /** + * Updates a user. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.showcase.v1beta1.User} request.user + * The user to update. + * @param {google.protobuf.FieldMask} request.updateMask + * The field mask to determine which fields are to be updated. If empty, the + * server will assume all fields are to be updated. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.User|User}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/identity.update_user.js + * region_tag:localhost_v1beta1_generated_Identity_UpdateUser_async + */ updateUser( - request?: protos.google.showcase.v1beta1.IUpdateUserRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IUser, - protos.google.showcase.v1beta1.IUpdateUserRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IUpdateUserRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IUser, + protos.google.showcase.v1beta1.IUpdateUserRequest | undefined, + {} | undefined, + ] + >; updateUser( - request: protos.google.showcase.v1beta1.IUpdateUserRequest, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.IUser, - protos.google.showcase.v1beta1.IUpdateUserRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IUpdateUserRequest, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.IUser, + protos.google.showcase.v1beta1.IUpdateUserRequest | null | undefined, + {} | null | undefined + >, + ): void; updateUser( - request: protos.google.showcase.v1beta1.IUpdateUserRequest, - callback: Callback< - protos.google.showcase.v1beta1.IUser, - protos.google.showcase.v1beta1.IUpdateUserRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IUpdateUserRequest, + callback: Callback< + protos.google.showcase.v1beta1.IUser, + protos.google.showcase.v1beta1.IUpdateUserRequest | null | undefined, + {} | null | undefined + >, + ): void; updateUser( - request?: protos.google.showcase.v1beta1.IUpdateUserRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.showcase.v1beta1.IUpdateUserRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.IUser, - protos.google.showcase.v1beta1.IUpdateUserRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.showcase.v1beta1.IUser, - protos.google.showcase.v1beta1.IUpdateUserRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.IUser, - protos.google.showcase.v1beta1.IUpdateUserRequest|undefined, {}|undefined - ]>|void { + protos.google.showcase.v1beta1.IUpdateUserRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.IUser, + protos.google.showcase.v1beta1.IUpdateUserRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IUser, + protos.google.showcase.v1beta1.IUpdateUserRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'user.name': request.user!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'user.name': request.user!.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateUser request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.IUser, - protos.google.showcase.v1beta1.IUpdateUserRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.IUser, + protos.google.showcase.v1beta1.IUpdateUserRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateUser response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.updateUser(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.IUser, - protos.google.showcase.v1beta1.IUpdateUserRequest|undefined, - {}|undefined - ]) => { - this._log.info('updateUser response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateUser(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.IUser, + protos.google.showcase.v1beta1.IUpdateUserRequest | undefined, + {} | undefined, + ]) => { + this._log.info('updateUser response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Deletes a user, their profile, and all of their authored messages. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * The resource name of the user to delete. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/identity.delete_user.js - * region_tag:localhost_v1beta1_generated_Identity_DeleteUser_async - */ + /** + * Deletes a user, their profile, and all of their authored messages. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * The resource name of the user to delete. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/identity.delete_user.js + * region_tag:localhost_v1beta1_generated_Identity_DeleteUser_async + */ deleteUser( - request?: protos.google.showcase.v1beta1.IDeleteUserRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteUserRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IDeleteUserRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteUserRequest | undefined, + {} | undefined, + ] + >; deleteUser( - request: protos.google.showcase.v1beta1.IDeleteUserRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteUserRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IDeleteUserRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteUserRequest | null | undefined, + {} | null | undefined + >, + ): void; deleteUser( - request: protos.google.showcase.v1beta1.IDeleteUserRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteUserRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IDeleteUserRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteUserRequest | null | undefined, + {} | null | undefined + >, + ): void; deleteUser( - request?: protos.google.showcase.v1beta1.IDeleteUserRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteUserRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.showcase.v1beta1.IDeleteUserRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteUserRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteUserRequest|undefined, {}|undefined - ]>|void { + protos.google.showcase.v1beta1.IDeleteUserRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteUserRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteUserRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('deleteUser request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteUserRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteUserRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteUser response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.deleteUser(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteUserRequest|undefined, - {}|undefined - ]) => { - this._log.info('deleteUser response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteUser(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteUserRequest | undefined, + {} | undefined, + ]) => { + this._log.info('deleteUser response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } - /** - * Lists all users. - * - * @param {Object} request - * The request object that will be sent. - * @param {number} request.pageSize - * The maximum number of users to return. Server may return fewer users - * than requested. If unspecified, server will pick an appropriate default. - * @param {string} request.pageToken - * The value of google.showcase.v1beta1.ListUsersResponse.next_page_token - * returned from the previous call to - * `google.showcase.v1beta1.Identity\ListUsers` method. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.showcase.v1beta1.User|User}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `listUsersAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Lists all users. + * + * @param {Object} request + * The request object that will be sent. + * @param {number} request.pageSize + * The maximum number of users to return. Server may return fewer users + * than requested. If unspecified, server will pick an appropriate default. + * @param {string} request.pageToken + * The value of google.showcase.v1beta1.ListUsersResponse.next_page_token + * returned from the previous call to + * `google.showcase.v1beta1.Identity\ListUsers` method. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.showcase.v1beta1.User|User}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listUsersAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listUsers( - request?: protos.google.showcase.v1beta1.IListUsersRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IUser[], - protos.google.showcase.v1beta1.IListUsersRequest|null, - protos.google.showcase.v1beta1.IListUsersResponse - ]>; + request?: protos.google.showcase.v1beta1.IListUsersRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IUser[], + protos.google.showcase.v1beta1.IListUsersRequest | null, + protos.google.showcase.v1beta1.IListUsersResponse, + ] + >; listUsers( - request: protos.google.showcase.v1beta1.IListUsersRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.showcase.v1beta1.IListUsersRequest, - protos.google.showcase.v1beta1.IListUsersResponse|null|undefined, - protos.google.showcase.v1beta1.IUser>): void; + request: protos.google.showcase.v1beta1.IListUsersRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.showcase.v1beta1.IListUsersRequest, + protos.google.showcase.v1beta1.IListUsersResponse | null | undefined, + protos.google.showcase.v1beta1.IUser + >, + ): void; listUsers( - request: protos.google.showcase.v1beta1.IListUsersRequest, - callback: PaginationCallback< - protos.google.showcase.v1beta1.IListUsersRequest, - protos.google.showcase.v1beta1.IListUsersResponse|null|undefined, - protos.google.showcase.v1beta1.IUser>): void; + request: protos.google.showcase.v1beta1.IListUsersRequest, + callback: PaginationCallback< + protos.google.showcase.v1beta1.IListUsersRequest, + protos.google.showcase.v1beta1.IListUsersResponse | null | undefined, + protos.google.showcase.v1beta1.IUser + >, + ): void; listUsers( - request?: protos.google.showcase.v1beta1.IListUsersRequest, - optionsOrCallback?: CallOptions|PaginationCallback< + request?: protos.google.showcase.v1beta1.IListUsersRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.showcase.v1beta1.IListUsersRequest, - protos.google.showcase.v1beta1.IListUsersResponse|null|undefined, - protos.google.showcase.v1beta1.IUser>, - callback?: PaginationCallback< - protos.google.showcase.v1beta1.IListUsersRequest, - protos.google.showcase.v1beta1.IListUsersResponse|null|undefined, - protos.google.showcase.v1beta1.IUser>): - Promise<[ - protos.google.showcase.v1beta1.IUser[], - protos.google.showcase.v1beta1.IListUsersRequest|null, - protos.google.showcase.v1beta1.IListUsersResponse - ]>|void { + protos.google.showcase.v1beta1.IListUsersResponse | null | undefined, + protos.google.showcase.v1beta1.IUser + >, + callback?: PaginationCallback< + protos.google.showcase.v1beta1.IListUsersRequest, + protos.google.showcase.v1beta1.IListUsersResponse | null | undefined, + protos.google.showcase.v1beta1.IUser + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IUser[], + protos.google.showcase.v1beta1.IListUsersRequest | null, + protos.google.showcase.v1beta1.IListUsersResponse, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.showcase.v1beta1.IListUsersRequest, - protos.google.showcase.v1beta1.IListUsersResponse|null|undefined, - protos.google.showcase.v1beta1.IUser>|undefined = callback + this.initialize().catch((err) => { + throw err; + }); + const wrappedCallback: + | PaginationCallback< + protos.google.showcase.v1beta1.IListUsersRequest, + protos.google.showcase.v1beta1.IListUsersResponse | null | undefined, + protos.google.showcase.v1beta1.IUser + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listUsers values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -821,98 +1008,104 @@ export class IdentityClient { this._log.info('listUsers request %j', request); return this.innerApiCalls .listUsers(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.showcase.v1beta1.IUser[], - protos.google.showcase.v1beta1.IListUsersRequest|null, - protos.google.showcase.v1beta1.IListUsersResponse - ]) => { - this._log.info('listUsers values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.showcase.v1beta1.IUser[], + protos.google.showcase.v1beta1.IListUsersRequest | null, + protos.google.showcase.v1beta1.IListUsersResponse, + ]) => { + this._log.info('listUsers values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listUsers`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {number} request.pageSize - * The maximum number of users to return. Server may return fewer users - * than requested. If unspecified, server will pick an appropriate default. - * @param {string} request.pageToken - * The value of google.showcase.v1beta1.ListUsersResponse.next_page_token - * returned from the previous call to - * `google.showcase.v1beta1.Identity\ListUsers` method. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.showcase.v1beta1.User|User} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `listUsersAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `listUsers`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {number} request.pageSize + * The maximum number of users to return. Server may return fewer users + * than requested. If unspecified, server will pick an appropriate default. + * @param {string} request.pageToken + * The value of google.showcase.v1beta1.ListUsersResponse.next_page_token + * returned from the previous call to + * `google.showcase.v1beta1.Identity\ListUsers` method. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.showcase.v1beta1.User|User} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listUsersAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listUsersStream( - request?: protos.google.showcase.v1beta1.IListUsersRequest, - options?: CallOptions): - Transform{ + request?: protos.google.showcase.v1beta1.IListUsersRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; const defaultCallSettings = this._defaults['listUsers']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listUsers stream %j', request); return this.descriptors.page.listUsers.createStream( this.innerApiCalls.listUsers as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listUsers`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {number} request.pageSize - * The maximum number of users to return. Server may return fewer users - * than requested. If unspecified, server will pick an appropriate default. - * @param {string} request.pageToken - * The value of google.showcase.v1beta1.ListUsersResponse.next_page_token - * returned from the previous call to - * `google.showcase.v1beta1.Identity\ListUsers` method. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.showcase.v1beta1.User|User}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/identity.list_users.js - * region_tag:localhost_v1beta1_generated_Identity_ListUsers_async - */ + /** + * Equivalent to `listUsers`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {number} request.pageSize + * The maximum number of users to return. Server may return fewer users + * than requested. If unspecified, server will pick an appropriate default. + * @param {string} request.pageToken + * The value of google.showcase.v1beta1.ListUsersResponse.next_page_token + * returned from the previous call to + * `google.showcase.v1beta1.Identity\ListUsers` method. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.showcase.v1beta1.User|User}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/identity.list_users.js + * region_tag:localhost_v1beta1_generated_Identity_ListUsers_async + */ listUsersAsync( - request?: protos.google.showcase.v1beta1.IListUsersRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.showcase.v1beta1.IListUsersRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; const defaultCallSettings = this._defaults['listUsers']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listUsers iterate %j', request); return this.descriptors.page.listUsers.asyncIterate( this.innerApiCalls['listUsers'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } // -------------------- @@ -927,7 +1120,7 @@ export class IdentityClient { * @param {string} blueprint * @returns {string} Resource name string. */ - blueprintPath(session:string,test:string,blueprint:string) { + blueprintPath(session: string, test: string, blueprint: string) { return this.pathTemplates.blueprintPathTemplate.render({ session: session, test: test, @@ -943,7 +1136,8 @@ export class IdentityClient { * @returns {string} A string representing the session. */ matchSessionFromBlueprintName(blueprintName: string) { - return this.pathTemplates.blueprintPathTemplate.match(blueprintName).session; + return this.pathTemplates.blueprintPathTemplate.match(blueprintName) + .session; } /** @@ -965,7 +1159,8 @@ export class IdentityClient { * @returns {string} A string representing the blueprint. */ matchBlueprintFromBlueprintName(blueprintName: string) { - return this.pathTemplates.blueprintPathTemplate.match(blueprintName).blueprint; + return this.pathTemplates.blueprintPathTemplate.match(blueprintName) + .blueprint; } /** @@ -974,7 +1169,7 @@ export class IdentityClient { * @param {string} room * @returns {string} Resource name string. */ - roomPath(room:string) { + roomPath(room: string) { return this.pathTemplates.roomPathTemplate.render({ room: room, }); @@ -998,7 +1193,7 @@ export class IdentityClient { * @param {string} blurb * @returns {string} Resource name string. */ - roomBlurbPath(room:string,blurb:string) { + roomBlurbPath(room: string, blurb: string) { return this.pathTemplates.roomBlurbPathTemplate.render({ room: room, blurb: blurb, @@ -1035,7 +1230,11 @@ export class IdentityClient { * @param {string} blurb * @returns {string} Resource name string. */ - roomBlurbsLegacyRoomBlurbPath(room:string,legacyRoom:string,blurb:string) { + roomBlurbsLegacyRoomBlurbPath( + room: string, + legacyRoom: string, + blurb: string, + ) { return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.render({ room: room, legacy_room: legacyRoom, @@ -1050,8 +1249,12 @@ export class IdentityClient { * A fully-qualified path representing room_blurbs_legacy_room_blurb resource. * @returns {string} A string representing the room. */ - matchRoomFromRoomBlurbsLegacyRoomBlurbName(roomBlurbsLegacyRoomBlurbName: string) { - return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match(roomBlurbsLegacyRoomBlurbName).room; + matchRoomFromRoomBlurbsLegacyRoomBlurbName( + roomBlurbsLegacyRoomBlurbName: string, + ) { + return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match( + roomBlurbsLegacyRoomBlurbName, + ).room; } /** @@ -1061,8 +1264,12 @@ export class IdentityClient { * A fully-qualified path representing room_blurbs_legacy_room_blurb resource. * @returns {string} A string representing the legacy_room. */ - matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName(roomBlurbsLegacyRoomBlurbName: string) { - return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match(roomBlurbsLegacyRoomBlurbName).legacy_room; + matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName( + roomBlurbsLegacyRoomBlurbName: string, + ) { + return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match( + roomBlurbsLegacyRoomBlurbName, + ).legacy_room; } /** @@ -1072,8 +1279,12 @@ export class IdentityClient { * A fully-qualified path representing room_blurbs_legacy_room_blurb resource. * @returns {string} A string representing the blurb. */ - matchBlurbFromRoomBlurbsLegacyRoomBlurbName(roomBlurbsLegacyRoomBlurbName: string) { - return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match(roomBlurbsLegacyRoomBlurbName).blurb; + matchBlurbFromRoomBlurbsLegacyRoomBlurbName( + roomBlurbsLegacyRoomBlurbName: string, + ) { + return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match( + roomBlurbsLegacyRoomBlurbName, + ).blurb; } /** @@ -1082,7 +1293,7 @@ export class IdentityClient { * @param {string} sequence * @returns {string} Resource name string. */ - sequencePath(sequence:string) { + sequencePath(sequence: string) { return this.pathTemplates.sequencePathTemplate.render({ sequence: sequence, }); @@ -1105,7 +1316,7 @@ export class IdentityClient { * @param {string} sequence * @returns {string} Resource name string. */ - sequenceReportPath(sequence:string) { + sequenceReportPath(sequence: string) { return this.pathTemplates.sequenceReportPathTemplate.render({ sequence: sequence, }); @@ -1119,7 +1330,9 @@ export class IdentityClient { * @returns {string} A string representing the sequence. */ matchSequenceFromSequenceReportName(sequenceReportName: string) { - return this.pathTemplates.sequenceReportPathTemplate.match(sequenceReportName).sequence; + return this.pathTemplates.sequenceReportPathTemplate.match( + sequenceReportName, + ).sequence; } /** @@ -1128,7 +1341,7 @@ export class IdentityClient { * @param {string} session * @returns {string} Resource name string. */ - sessionPath(session:string) { + sessionPath(session: string) { return this.pathTemplates.sessionPathTemplate.render({ session: session, }); @@ -1152,7 +1365,7 @@ export class IdentityClient { * @param {string} test * @returns {string} Resource name string. */ - testPath(session:string,test:string) { + testPath(session: string, test: string) { return this.pathTemplates.testPathTemplate.render({ session: session, test: test, @@ -1187,7 +1400,7 @@ export class IdentityClient { * @param {string} user * @returns {string} Resource name string. */ - userPath(user:string) { + userPath(user: string) { return this.pathTemplates.userPathTemplate.render({ user: user, }); @@ -1211,7 +1424,7 @@ export class IdentityClient { * @param {string} blurb * @returns {string} Resource name string. */ - userProfileBlurbPath(user:string,blurb:string) { + userProfileBlurbPath(user: string, blurb: string) { return this.pathTemplates.userProfileBlurbPathTemplate.render({ user: user, blurb: blurb, @@ -1226,7 +1439,9 @@ export class IdentityClient { * @returns {string} A string representing the user. */ matchUserFromUserProfileBlurbName(userProfileBlurbName: string) { - return this.pathTemplates.userProfileBlurbPathTemplate.match(userProfileBlurbName).user; + return this.pathTemplates.userProfileBlurbPathTemplate.match( + userProfileBlurbName, + ).user; } /** @@ -1237,7 +1452,9 @@ export class IdentityClient { * @returns {string} A string representing the blurb. */ matchBlurbFromUserProfileBlurbName(userProfileBlurbName: string) { - return this.pathTemplates.userProfileBlurbPathTemplate.match(userProfileBlurbName).blurb; + return this.pathTemplates.userProfileBlurbPathTemplate.match( + userProfileBlurbName, + ).blurb; } /** @@ -1248,12 +1465,18 @@ export class IdentityClient { * @param {string} blurb * @returns {string} Resource name string. */ - userProfileBlurbsLegacyUserBlurbPath(user:string,legacyUser:string,blurb:string) { - return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.render({ - user: user, - legacy_user: legacyUser, - blurb: blurb, - }); + userProfileBlurbsLegacyUserBlurbPath( + user: string, + legacyUser: string, + blurb: string, + ) { + return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.render( + { + user: user, + legacy_user: legacyUser, + blurb: blurb, + }, + ); } /** @@ -1263,8 +1486,12 @@ export class IdentityClient { * A fully-qualified path representing user_profile_blurbs_legacy_user_blurb resource. * @returns {string} A string representing the user. */ - matchUserFromUserProfileBlurbsLegacyUserBlurbName(userProfileBlurbsLegacyUserBlurbName: string) { - return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match(userProfileBlurbsLegacyUserBlurbName).user; + matchUserFromUserProfileBlurbsLegacyUserBlurbName( + userProfileBlurbsLegacyUserBlurbName: string, + ) { + return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match( + userProfileBlurbsLegacyUserBlurbName, + ).user; } /** @@ -1274,8 +1501,12 @@ export class IdentityClient { * A fully-qualified path representing user_profile_blurbs_legacy_user_blurb resource. * @returns {string} A string representing the legacy_user. */ - matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName(userProfileBlurbsLegacyUserBlurbName: string) { - return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match(userProfileBlurbsLegacyUserBlurbName).legacy_user; + matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName( + userProfileBlurbsLegacyUserBlurbName: string, + ) { + return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match( + userProfileBlurbsLegacyUserBlurbName, + ).legacy_user; } /** @@ -1285,8 +1516,12 @@ export class IdentityClient { * A fully-qualified path representing user_profile_blurbs_legacy_user_blurb resource. * @returns {string} A string representing the blurb. */ - matchBlurbFromUserProfileBlurbsLegacyUserBlurbName(userProfileBlurbsLegacyUserBlurbName: string) { - return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match(userProfileBlurbsLegacyUserBlurbName).blurb; + matchBlurbFromUserProfileBlurbsLegacyUserBlurbName( + userProfileBlurbsLegacyUserBlurbName: string, + ) { + return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match( + userProfileBlurbsLegacyUserBlurbName, + ).blurb; } /** @@ -1297,7 +1532,7 @@ export class IdentityClient { */ close(): Promise { if (this.identityStub && !this._terminated) { - return this.identityStub.then(stub => { + return this.identityStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -1305,4 +1540,4 @@ export class IdentityClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/core/generator/gapic-generator-typescript/baselines/disable-packing-test/src/v1beta1/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/disable-packing-test/src/v1beta1/index.ts.baseline index f3bb4c129cce..297c19fa8f9d 100644 --- a/core/generator/gapic-generator-typescript/baselines/disable-packing-test/src/v1beta1/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/disable-packing-test/src/v1beta1/index.ts.baseline @@ -16,9 +16,9 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -export {ComplianceClient} from './compliance_client'; -export {EchoClient} from './echo_client'; -export {IdentityClient} from './identity_client'; -export {MessagingClient} from './messaging_client'; -export {SequenceServiceClient} from './sequence_service_client'; -export {TestingClient} from './testing_client'; +export { ComplianceClient } from './compliance_client'; +export { EchoClient } from './echo_client'; +export { IdentityClient } from './identity_client'; +export { MessagingClient } from './messaging_client'; +export { SequenceServiceClient } from './sequence_service_client'; +export { TestingClient } from './testing_client'; diff --git a/core/generator/gapic-generator-typescript/baselines/disable-packing-test/src/v1beta1/messaging_client.ts.baseline b/core/generator/gapic-generator-typescript/baselines/disable-packing-test/src/v1beta1/messaging_client.ts.baseline index 319223c209b4..8db1a3abf3b0 100644 --- a/core/generator/gapic-generator-typescript/baselines/disable-packing-test/src/v1beta1/messaging_client.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/disable-packing-test/src/v1beta1/messaging_client.ts.baseline @@ -18,11 +18,20 @@ /* global window */ import type * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions, GrpcClientOptions, LROperation, PaginationCallback, GaxCall} from 'google-gax'; -import {Transform, PassThrough} from 'stream'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + GrpcClientOptions, + LROperation, + PaginationCallback, + GaxCall, +} from 'google-gax'; +import { Transform, PassThrough } from 'stream'; import * as protos from '../../protos/protos'; import jsonProtos = require('../../protos/protos.json'); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; /** * Client JSON configuration object, loaded from @@ -47,7 +56,7 @@ export class MessagingClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('showcase'); @@ -60,10 +69,10 @@ export class MessagingClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; operationsClient: gax.OperationsClient; - messagingStub?: Promise<{[name: string]: Function}>; + messagingStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of MessagingClient. @@ -104,21 +113,42 @@ export class MessagingClient { * const client = new MessagingClient({fallback: true}, gax); * ``` */ - constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { // Ensure that options include all the required fields. const staticMembers = this.constructor as typeof MessagingClient; - if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { - throw new Error('Please set either universe_domain or universeDomain, but not both.'); + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); } - const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; - this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; this._servicePath = 'localhost'; - const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; - const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. if (servicePath !== this._servicePath && !('scopes' in opts)) { @@ -140,7 +170,7 @@ export class MessagingClient { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; @@ -154,10 +184,7 @@ export class MessagingClient { } // Determine the client header string. - const clientHeader = [ - `gax/${this._gaxModule.version}`, - `gapic/${version}`, - ]; + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/${process.versions.node}`); } else { @@ -179,56 +206,70 @@ export class MessagingClient { // Create useful helper objects for these. this.pathTemplates = { blueprintPathTemplate: new this._gaxModule.PathTemplate( - 'sessions/{session}/tests/{test}/blueprints/{blueprint}' - ), - roomPathTemplate: new this._gaxModule.PathTemplate( - 'rooms/{room}' + 'sessions/{session}/tests/{test}/blueprints/{blueprint}', ), + roomPathTemplate: new this._gaxModule.PathTemplate('rooms/{room}'), roomBlurbPathTemplate: new this._gaxModule.PathTemplate( - 'rooms/{room}/blurbs/{blurb}' + 'rooms/{room}/blurbs/{blurb}', ), roomBlurbsLegacyRoomBlurbPathTemplate: new this._gaxModule.PathTemplate( - 'rooms/{room}/blurbs/legacy/{legacy_room}.{blurb}' + 'rooms/{room}/blurbs/legacy/{legacy_room}.{blurb}', ), sequencePathTemplate: new this._gaxModule.PathTemplate( - 'sequences/{sequence}' + 'sequences/{sequence}', ), sequenceReportPathTemplate: new this._gaxModule.PathTemplate( - 'sequences/{sequence}/sequenceReport' + 'sequences/{sequence}/sequenceReport', ), sessionPathTemplate: new this._gaxModule.PathTemplate( - 'sessions/{session}' + 'sessions/{session}', ), testPathTemplate: new this._gaxModule.PathTemplate( - 'sessions/{session}/tests/{test}' - ), - userPathTemplate: new this._gaxModule.PathTemplate( - 'users/{user}' + 'sessions/{session}/tests/{test}', ), + userPathTemplate: new this._gaxModule.PathTemplate('users/{user}'), userProfileBlurbPathTemplate: new this._gaxModule.PathTemplate( - 'users/{user}/profile/blurbs/{blurb}' - ), - userProfileBlurbsLegacyUserBlurbPathTemplate: new this._gaxModule.PathTemplate( - 'users/{user}/profile/blurbs/legacy/{legacy_user}~{blurb}' + 'users/{user}/profile/blurbs/{blurb}', ), + userProfileBlurbsLegacyUserBlurbPathTemplate: + new this._gaxModule.PathTemplate( + 'users/{user}/profile/blurbs/legacy/{legacy_user}~{blurb}', + ), }; // Some of the methods on this service return "paged" results, // (e.g. 50 results at a time, with tokens to get subsequent // pages). Denote the keys used for pagination and results. this.descriptors.page = { - listRooms: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'rooms'), - listBlurbs: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'blurbs') + listRooms: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'rooms', + ), + listBlurbs: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'blurbs', + ), }; // Some of the methods on this service provide streaming responses. // Provide descriptors for these. this.descriptors.stream = { - streamBlurbs: new this._gaxModule.StreamDescriptor(this._gaxModule.StreamType.SERVER_STREAMING, !!opts.fallback, !!opts.gaxServerStreamingRetries), - sendBlurbs: new this._gaxModule.StreamDescriptor(this._gaxModule.StreamType.CLIENT_STREAMING, !!opts.fallback), - connect: new this._gaxModule.StreamDescriptor(this._gaxModule.StreamType.BIDI_STREAMING, !!opts.fallback, !!opts.gaxServerStreamingRetries) + streamBlurbs: new this._gaxModule.StreamDescriptor( + this._gaxModule.StreamType.SERVER_STREAMING, + !!opts.fallback, + !!opts.gaxServerStreamingRetries, + ), + sendBlurbs: new this._gaxModule.StreamDescriptor( + this._gaxModule.StreamType.CLIENT_STREAMING, + !!opts.fallback, + ), + connect: new this._gaxModule.StreamDescriptor( + this._gaxModule.StreamType.BIDI_STREAMING, + !!opts.fallback, + !!opts.gaxServerStreamingRetries, + ), }; const protoFilesRoot = this._gaxModule.protobufFromJSON(jsonProtos); @@ -237,29 +278,37 @@ export class MessagingClient { // rather than holding a request open. const lroOptions: GrpcClientOptions = { auth: this.auth, - grpc: 'grpc' in this._gaxGrpc ? this._gaxGrpc.grpc : undefined + grpc: 'grpc' in this._gaxGrpc ? this._gaxGrpc.grpc : undefined, }; if (opts.fallback) { lroOptions.protoJson = protoFilesRoot; lroOptions.httpRules = []; } - this.operationsClient = this._gaxModule.lro(lroOptions).operationsClient(opts); + this.operationsClient = this._gaxModule + .lro(lroOptions) + .operationsClient(opts); const searchBlurbsResponse = protoFilesRoot.lookup( - '.google.showcase.v1beta1.SearchBlurbsResponse') as gax.protobuf.Type; + '.google.showcase.v1beta1.SearchBlurbsResponse', + ) as gax.protobuf.Type; const searchBlurbsMetadata = protoFilesRoot.lookup( - '.google.showcase.v1beta1.SearchBlurbsMetadata') as gax.protobuf.Type; + '.google.showcase.v1beta1.SearchBlurbsMetadata', + ) as gax.protobuf.Type; this.descriptors.longrunning = { searchBlurbs: new this._gaxModule.LongrunningDescriptor( this.operationsClient, searchBlurbsResponse.decode.bind(searchBlurbsResponse), - searchBlurbsMetadata.decode.bind(searchBlurbsMetadata)) + searchBlurbsMetadata.decode.bind(searchBlurbsMetadata), + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.showcase.v1beta1.Messaging', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.showcase.v1beta1.Messaging', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + { 'x-goog-api-client': clientHeader.join(' ') }, + ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -290,35 +339,60 @@ export class MessagingClient { // Put together the "service stub" for // google.showcase.v1beta1.Messaging. this.messagingStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.showcase.v1beta1.Messaging') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.showcase.v1beta1.Messaging', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.showcase.v1beta1.Messaging, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts, + this._providedCustomServicePath, + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const messagingStubMethods = - ['createRoom', 'getRoom', 'updateRoom', 'deleteRoom', 'listRooms', 'createBlurb', 'getBlurb', 'updateBlurb', 'deleteBlurb', 'listBlurbs', 'searchBlurbs', 'streamBlurbs', 'sendBlurbs', 'connect']; + const messagingStubMethods = [ + 'createRoom', + 'getRoom', + 'updateRoom', + 'deleteRoom', + 'listRooms', + 'createBlurb', + 'getBlurb', + 'updateBlurb', + 'deleteBlurb', + 'listBlurbs', + 'searchBlurbs', + 'streamBlurbs', + 'sendBlurbs', + 'connect', + ]; for (const methodName of messagingStubMethods) { const callPromise = this.messagingStub.then( - stub => (...args: Array<{}>) => { - if (this._terminated) { - if (methodName in this.descriptors.stream) { - const stream = new PassThrough({objectMode: true}); - setImmediate(() => { - stream.emit('error', new this._gaxModule.GoogleError('The client has already been closed.')); - }); - return stream; + (stub) => + (...args: Array<{}>) => { + if (this._terminated) { + if (methodName in this.descriptors.stream) { + const stream = new PassThrough({ objectMode: true }); + setImmediate(() => { + stream.emit( + 'error', + new this._gaxModule.GoogleError( + 'The client has already been closed.', + ), + ); + }); + return stream; + } + return Promise.reject('The client has already been closed.'); } - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error|null|undefined) => () => { + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { throw err; - }); + }, + ); const descriptor = this.descriptors.page[methodName] || @@ -329,7 +403,7 @@ export class MessagingClient { callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -344,8 +418,14 @@ export class MessagingClient { * @returns {string} The DNS address for this service. */ static get servicePath() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'localhost'; } @@ -356,8 +436,14 @@ export class MessagingClient { * @returns {string} The DNS address for this service. */ static get apiEndpoint() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'localhost'; } @@ -397,8 +483,9 @@ export class MessagingClient { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId(callback?: Callback): - Promise|void { + getProjectId( + callback?: Callback, + ): Promise | void { if (callback) { this.auth.getProjectId(callback); return; @@ -409,1072 +496,1400 @@ export class MessagingClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Creates a room. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.showcase.v1beta1.Room} request.room - * The room to create. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.Room|Room}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/messaging.create_room.js - * region_tag:localhost_v1beta1_generated_Messaging_CreateRoom_async - */ + /** + * Creates a room. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.showcase.v1beta1.Room} request.room + * The room to create. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.Room|Room}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/messaging.create_room.js + * region_tag:localhost_v1beta1_generated_Messaging_CreateRoom_async + */ createRoom( - request?: protos.google.showcase.v1beta1.ICreateRoomRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IRoom, - protos.google.showcase.v1beta1.ICreateRoomRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.ICreateRoomRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IRoom, + protos.google.showcase.v1beta1.ICreateRoomRequest | undefined, + {} | undefined, + ] + >; createRoom( - request: protos.google.showcase.v1beta1.ICreateRoomRequest, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.IRoom, - protos.google.showcase.v1beta1.ICreateRoomRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.ICreateRoomRequest, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.IRoom, + protos.google.showcase.v1beta1.ICreateRoomRequest | null | undefined, + {} | null | undefined + >, + ): void; createRoom( - request: protos.google.showcase.v1beta1.ICreateRoomRequest, - callback: Callback< - protos.google.showcase.v1beta1.IRoom, - protos.google.showcase.v1beta1.ICreateRoomRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.ICreateRoomRequest, + callback: Callback< + protos.google.showcase.v1beta1.IRoom, + protos.google.showcase.v1beta1.ICreateRoomRequest | null | undefined, + {} | null | undefined + >, + ): void; createRoom( - request?: protos.google.showcase.v1beta1.ICreateRoomRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.showcase.v1beta1.IRoom, - protos.google.showcase.v1beta1.ICreateRoomRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.showcase.v1beta1.ICreateRoomRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.IRoom, - protos.google.showcase.v1beta1.ICreateRoomRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.IRoom, - protos.google.showcase.v1beta1.ICreateRoomRequest|undefined, {}|undefined - ]>|void { + protos.google.showcase.v1beta1.ICreateRoomRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.IRoom, + protos.google.showcase.v1beta1.ICreateRoomRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IRoom, + protos.google.showcase.v1beta1.ICreateRoomRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('createRoom request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.IRoom, - protos.google.showcase.v1beta1.ICreateRoomRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.IRoom, + protos.google.showcase.v1beta1.ICreateRoomRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createRoom response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.createRoom(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.IRoom, - protos.google.showcase.v1beta1.ICreateRoomRequest|undefined, - {}|undefined - ]) => { - this._log.info('createRoom response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createRoom(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.IRoom, + protos.google.showcase.v1beta1.ICreateRoomRequest | undefined, + {} | undefined, + ]) => { + this._log.info('createRoom response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Retrieves the Room with the given resource name. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * The resource name of the requested room. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.Room|Room}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/messaging.get_room.js - * region_tag:localhost_v1beta1_generated_Messaging_GetRoom_async - */ + /** + * Retrieves the Room with the given resource name. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * The resource name of the requested room. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.Room|Room}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/messaging.get_room.js + * region_tag:localhost_v1beta1_generated_Messaging_GetRoom_async + */ getRoom( - request?: protos.google.showcase.v1beta1.IGetRoomRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IRoom, - protos.google.showcase.v1beta1.IGetRoomRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IGetRoomRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IRoom, + protos.google.showcase.v1beta1.IGetRoomRequest | undefined, + {} | undefined, + ] + >; getRoom( - request: protos.google.showcase.v1beta1.IGetRoomRequest, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.IRoom, - protos.google.showcase.v1beta1.IGetRoomRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IGetRoomRequest, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.IRoom, + protos.google.showcase.v1beta1.IGetRoomRequest | null | undefined, + {} | null | undefined + >, + ): void; getRoom( - request: protos.google.showcase.v1beta1.IGetRoomRequest, - callback: Callback< - protos.google.showcase.v1beta1.IRoom, - protos.google.showcase.v1beta1.IGetRoomRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IGetRoomRequest, + callback: Callback< + protos.google.showcase.v1beta1.IRoom, + protos.google.showcase.v1beta1.IGetRoomRequest | null | undefined, + {} | null | undefined + >, + ): void; getRoom( - request?: protos.google.showcase.v1beta1.IGetRoomRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.showcase.v1beta1.IRoom, - protos.google.showcase.v1beta1.IGetRoomRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.showcase.v1beta1.IGetRoomRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.IRoom, - protos.google.showcase.v1beta1.IGetRoomRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.IRoom, - protos.google.showcase.v1beta1.IGetRoomRequest|undefined, {}|undefined - ]>|void { + protos.google.showcase.v1beta1.IGetRoomRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.IRoom, + protos.google.showcase.v1beta1.IGetRoomRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IRoom, + protos.google.showcase.v1beta1.IGetRoomRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getRoom request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.IRoom, - protos.google.showcase.v1beta1.IGetRoomRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.IRoom, + protos.google.showcase.v1beta1.IGetRoomRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getRoom response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getRoom(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.IRoom, - protos.google.showcase.v1beta1.IGetRoomRequest|undefined, - {}|undefined - ]) => { - this._log.info('getRoom response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getRoom(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.IRoom, + protos.google.showcase.v1beta1.IGetRoomRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getRoom response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Updates a room. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.showcase.v1beta1.Room} request.room - * The room to update. - * @param {google.protobuf.FieldMask} request.updateMask - * The field mask to determine which fields are to be updated. If empty, the - * server will assume all fields are to be updated. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.Room|Room}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/messaging.update_room.js - * region_tag:localhost_v1beta1_generated_Messaging_UpdateRoom_async - */ + /** + * Updates a room. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.showcase.v1beta1.Room} request.room + * The room to update. + * @param {google.protobuf.FieldMask} request.updateMask + * The field mask to determine which fields are to be updated. If empty, the + * server will assume all fields are to be updated. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.Room|Room}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/messaging.update_room.js + * region_tag:localhost_v1beta1_generated_Messaging_UpdateRoom_async + */ updateRoom( - request?: protos.google.showcase.v1beta1.IUpdateRoomRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IRoom, - protos.google.showcase.v1beta1.IUpdateRoomRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IUpdateRoomRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IRoom, + protos.google.showcase.v1beta1.IUpdateRoomRequest | undefined, + {} | undefined, + ] + >; updateRoom( - request: protos.google.showcase.v1beta1.IUpdateRoomRequest, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.IRoom, - protos.google.showcase.v1beta1.IUpdateRoomRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IUpdateRoomRequest, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.IRoom, + protos.google.showcase.v1beta1.IUpdateRoomRequest | null | undefined, + {} | null | undefined + >, + ): void; updateRoom( - request: protos.google.showcase.v1beta1.IUpdateRoomRequest, - callback: Callback< - protos.google.showcase.v1beta1.IRoom, - protos.google.showcase.v1beta1.IUpdateRoomRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IUpdateRoomRequest, + callback: Callback< + protos.google.showcase.v1beta1.IRoom, + protos.google.showcase.v1beta1.IUpdateRoomRequest | null | undefined, + {} | null | undefined + >, + ): void; updateRoom( - request?: protos.google.showcase.v1beta1.IUpdateRoomRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.showcase.v1beta1.IUpdateRoomRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.IRoom, - protos.google.showcase.v1beta1.IUpdateRoomRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.showcase.v1beta1.IRoom, - protos.google.showcase.v1beta1.IUpdateRoomRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.IRoom, - protos.google.showcase.v1beta1.IUpdateRoomRequest|undefined, {}|undefined - ]>|void { + protos.google.showcase.v1beta1.IUpdateRoomRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.IRoom, + protos.google.showcase.v1beta1.IUpdateRoomRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IRoom, + protos.google.showcase.v1beta1.IUpdateRoomRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'room.name': request.room!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'room.name': request.room!.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateRoom request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.IRoom, - protos.google.showcase.v1beta1.IUpdateRoomRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.IRoom, + protos.google.showcase.v1beta1.IUpdateRoomRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateRoom response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.updateRoom(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.IRoom, - protos.google.showcase.v1beta1.IUpdateRoomRequest|undefined, - {}|undefined - ]) => { - this._log.info('updateRoom response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateRoom(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.IRoom, + protos.google.showcase.v1beta1.IUpdateRoomRequest | undefined, + {} | undefined, + ]) => { + this._log.info('updateRoom response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Deletes a room and all of its blurbs. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * The resource name of the requested room. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/messaging.delete_room.js - * region_tag:localhost_v1beta1_generated_Messaging_DeleteRoom_async - */ + /** + * Deletes a room and all of its blurbs. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * The resource name of the requested room. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/messaging.delete_room.js + * region_tag:localhost_v1beta1_generated_Messaging_DeleteRoom_async + */ deleteRoom( - request?: protos.google.showcase.v1beta1.IDeleteRoomRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteRoomRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IDeleteRoomRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteRoomRequest | undefined, + {} | undefined, + ] + >; deleteRoom( - request: protos.google.showcase.v1beta1.IDeleteRoomRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteRoomRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IDeleteRoomRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteRoomRequest | null | undefined, + {} | null | undefined + >, + ): void; deleteRoom( - request: protos.google.showcase.v1beta1.IDeleteRoomRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteRoomRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IDeleteRoomRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteRoomRequest | null | undefined, + {} | null | undefined + >, + ): void; deleteRoom( - request?: protos.google.showcase.v1beta1.IDeleteRoomRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.showcase.v1beta1.IDeleteRoomRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteRoomRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteRoomRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteRoomRequest|undefined, {}|undefined - ]>|void { + protos.google.showcase.v1beta1.IDeleteRoomRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteRoomRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteRoomRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('deleteRoom request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteRoomRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteRoomRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteRoom response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.deleteRoom(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteRoomRequest|undefined, - {}|undefined - ]) => { - this._log.info('deleteRoom response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteRoom(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteRoomRequest | undefined, + {} | undefined, + ]) => { + this._log.info('deleteRoom response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Creates a blurb. If the parent is a room, the blurb is understood to be a - * message in that room. If the parent is a profile, the blurb is understood - * to be a post on the profile. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * The resource name of the chat room or user profile that this blurb will - * be tied to. - * @param {google.showcase.v1beta1.Blurb} request.blurb - * The blurb to create. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.Blurb|Blurb}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/messaging.create_blurb.js - * region_tag:localhost_v1beta1_generated_Messaging_CreateBlurb_async - */ + /** + * Creates a blurb. If the parent is a room, the blurb is understood to be a + * message in that room. If the parent is a profile, the blurb is understood + * to be a post on the profile. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * The resource name of the chat room or user profile that this blurb will + * be tied to. + * @param {google.showcase.v1beta1.Blurb} request.blurb + * The blurb to create. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.Blurb|Blurb}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/messaging.create_blurb.js + * region_tag:localhost_v1beta1_generated_Messaging_CreateBlurb_async + */ createBlurb( - request?: protos.google.showcase.v1beta1.ICreateBlurbRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IBlurb, - protos.google.showcase.v1beta1.ICreateBlurbRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.ICreateBlurbRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IBlurb, + protos.google.showcase.v1beta1.ICreateBlurbRequest | undefined, + {} | undefined, + ] + >; createBlurb( - request: protos.google.showcase.v1beta1.ICreateBlurbRequest, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.IBlurb, - protos.google.showcase.v1beta1.ICreateBlurbRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.ICreateBlurbRequest, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.IBlurb, + protos.google.showcase.v1beta1.ICreateBlurbRequest | null | undefined, + {} | null | undefined + >, + ): void; createBlurb( - request: protos.google.showcase.v1beta1.ICreateBlurbRequest, - callback: Callback< - protos.google.showcase.v1beta1.IBlurb, - protos.google.showcase.v1beta1.ICreateBlurbRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.ICreateBlurbRequest, + callback: Callback< + protos.google.showcase.v1beta1.IBlurb, + protos.google.showcase.v1beta1.ICreateBlurbRequest | null | undefined, + {} | null | undefined + >, + ): void; createBlurb( - request?: protos.google.showcase.v1beta1.ICreateBlurbRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.showcase.v1beta1.ICreateBlurbRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.IBlurb, - protos.google.showcase.v1beta1.ICreateBlurbRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.showcase.v1beta1.IBlurb, - protos.google.showcase.v1beta1.ICreateBlurbRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.IBlurb, - protos.google.showcase.v1beta1.ICreateBlurbRequest|undefined, {}|undefined - ]>|void { + protos.google.showcase.v1beta1.ICreateBlurbRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.IBlurb, + protos.google.showcase.v1beta1.ICreateBlurbRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IBlurb, + protos.google.showcase.v1beta1.ICreateBlurbRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('createBlurb request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.IBlurb, - protos.google.showcase.v1beta1.ICreateBlurbRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.IBlurb, + protos.google.showcase.v1beta1.ICreateBlurbRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createBlurb response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.createBlurb(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.IBlurb, - protos.google.showcase.v1beta1.ICreateBlurbRequest|undefined, - {}|undefined - ]) => { - this._log.info('createBlurb response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createBlurb(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.IBlurb, + protos.google.showcase.v1beta1.ICreateBlurbRequest | undefined, + {} | undefined, + ]) => { + this._log.info('createBlurb response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Retrieves the Blurb with the given resource name. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * The resource name of the requested blurb. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.Blurb|Blurb}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/messaging.get_blurb.js - * region_tag:localhost_v1beta1_generated_Messaging_GetBlurb_async - */ + /** + * Retrieves the Blurb with the given resource name. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * The resource name of the requested blurb. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.Blurb|Blurb}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/messaging.get_blurb.js + * region_tag:localhost_v1beta1_generated_Messaging_GetBlurb_async + */ getBlurb( - request?: protos.google.showcase.v1beta1.IGetBlurbRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IBlurb, - protos.google.showcase.v1beta1.IGetBlurbRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IGetBlurbRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IBlurb, + protos.google.showcase.v1beta1.IGetBlurbRequest | undefined, + {} | undefined, + ] + >; getBlurb( - request: protos.google.showcase.v1beta1.IGetBlurbRequest, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.IBlurb, - protos.google.showcase.v1beta1.IGetBlurbRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IGetBlurbRequest, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.IBlurb, + protos.google.showcase.v1beta1.IGetBlurbRequest | null | undefined, + {} | null | undefined + >, + ): void; getBlurb( - request: protos.google.showcase.v1beta1.IGetBlurbRequest, - callback: Callback< - protos.google.showcase.v1beta1.IBlurb, - protos.google.showcase.v1beta1.IGetBlurbRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IGetBlurbRequest, + callback: Callback< + protos.google.showcase.v1beta1.IBlurb, + protos.google.showcase.v1beta1.IGetBlurbRequest | null | undefined, + {} | null | undefined + >, + ): void; getBlurb( - request?: protos.google.showcase.v1beta1.IGetBlurbRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.showcase.v1beta1.IGetBlurbRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.IBlurb, - protos.google.showcase.v1beta1.IGetBlurbRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.showcase.v1beta1.IBlurb, - protos.google.showcase.v1beta1.IGetBlurbRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.IBlurb, - protos.google.showcase.v1beta1.IGetBlurbRequest|undefined, {}|undefined - ]>|void { + protos.google.showcase.v1beta1.IGetBlurbRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.IBlurb, + protos.google.showcase.v1beta1.IGetBlurbRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IBlurb, + protos.google.showcase.v1beta1.IGetBlurbRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getBlurb request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.IBlurb, - protos.google.showcase.v1beta1.IGetBlurbRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.IBlurb, + protos.google.showcase.v1beta1.IGetBlurbRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getBlurb response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getBlurb(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.IBlurb, - protos.google.showcase.v1beta1.IGetBlurbRequest|undefined, - {}|undefined - ]) => { - this._log.info('getBlurb response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getBlurb(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.IBlurb, + protos.google.showcase.v1beta1.IGetBlurbRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getBlurb response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Updates a blurb. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.showcase.v1beta1.Blurb} request.blurb - * The blurb to update. - * @param {google.protobuf.FieldMask} request.updateMask - * The field mask to determine wich fields are to be updated. If empty, the - * server will assume all fields are to be updated. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.Blurb|Blurb}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/messaging.update_blurb.js - * region_tag:localhost_v1beta1_generated_Messaging_UpdateBlurb_async - */ + /** + * Updates a blurb. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.showcase.v1beta1.Blurb} request.blurb + * The blurb to update. + * @param {google.protobuf.FieldMask} request.updateMask + * The field mask to determine wich fields are to be updated. If empty, the + * server will assume all fields are to be updated. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.Blurb|Blurb}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/messaging.update_blurb.js + * region_tag:localhost_v1beta1_generated_Messaging_UpdateBlurb_async + */ updateBlurb( - request?: protos.google.showcase.v1beta1.IUpdateBlurbRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IBlurb, - protos.google.showcase.v1beta1.IUpdateBlurbRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IUpdateBlurbRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IBlurb, + protos.google.showcase.v1beta1.IUpdateBlurbRequest | undefined, + {} | undefined, + ] + >; updateBlurb( - request: protos.google.showcase.v1beta1.IUpdateBlurbRequest, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.IBlurb, - protos.google.showcase.v1beta1.IUpdateBlurbRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IUpdateBlurbRequest, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.IBlurb, + protos.google.showcase.v1beta1.IUpdateBlurbRequest | null | undefined, + {} | null | undefined + >, + ): void; updateBlurb( - request: protos.google.showcase.v1beta1.IUpdateBlurbRequest, - callback: Callback< - protos.google.showcase.v1beta1.IBlurb, - protos.google.showcase.v1beta1.IUpdateBlurbRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IUpdateBlurbRequest, + callback: Callback< + protos.google.showcase.v1beta1.IBlurb, + protos.google.showcase.v1beta1.IUpdateBlurbRequest | null | undefined, + {} | null | undefined + >, + ): void; updateBlurb( - request?: protos.google.showcase.v1beta1.IUpdateBlurbRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.showcase.v1beta1.IBlurb, - protos.google.showcase.v1beta1.IUpdateBlurbRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.showcase.v1beta1.IUpdateBlurbRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.IBlurb, - protos.google.showcase.v1beta1.IUpdateBlurbRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.IBlurb, - protos.google.showcase.v1beta1.IUpdateBlurbRequest|undefined, {}|undefined - ]>|void { + protos.google.showcase.v1beta1.IUpdateBlurbRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.IBlurb, + protos.google.showcase.v1beta1.IUpdateBlurbRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IBlurb, + protos.google.showcase.v1beta1.IUpdateBlurbRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'blurb.name': request.blurb!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'blurb.name': request.blurb!.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateBlurb request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.IBlurb, - protos.google.showcase.v1beta1.IUpdateBlurbRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.IBlurb, + protos.google.showcase.v1beta1.IUpdateBlurbRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateBlurb response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.updateBlurb(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.IBlurb, - protos.google.showcase.v1beta1.IUpdateBlurbRequest|undefined, - {}|undefined - ]) => { - this._log.info('updateBlurb response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateBlurb(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.IBlurb, + protos.google.showcase.v1beta1.IUpdateBlurbRequest | undefined, + {} | undefined, + ]) => { + this._log.info('updateBlurb response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Deletes a blurb. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * The resource name of the requested blurb. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/messaging.delete_blurb.js - * region_tag:localhost_v1beta1_generated_Messaging_DeleteBlurb_async - */ + /** + * Deletes a blurb. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * The resource name of the requested blurb. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/messaging.delete_blurb.js + * region_tag:localhost_v1beta1_generated_Messaging_DeleteBlurb_async + */ deleteBlurb( - request?: protos.google.showcase.v1beta1.IDeleteBlurbRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteBlurbRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IDeleteBlurbRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteBlurbRequest | undefined, + {} | undefined, + ] + >; deleteBlurb( - request: protos.google.showcase.v1beta1.IDeleteBlurbRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteBlurbRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IDeleteBlurbRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteBlurbRequest | null | undefined, + {} | null | undefined + >, + ): void; deleteBlurb( - request: protos.google.showcase.v1beta1.IDeleteBlurbRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteBlurbRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IDeleteBlurbRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteBlurbRequest | null | undefined, + {} | null | undefined + >, + ): void; deleteBlurb( - request?: protos.google.showcase.v1beta1.IDeleteBlurbRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteBlurbRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.showcase.v1beta1.IDeleteBlurbRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteBlurbRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteBlurbRequest|undefined, {}|undefined - ]>|void { + protos.google.showcase.v1beta1.IDeleteBlurbRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteBlurbRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteBlurbRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('deleteBlurb request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteBlurbRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteBlurbRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteBlurb response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.deleteBlurb(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteBlurbRequest|undefined, - {}|undefined - ]) => { - this._log.info('deleteBlurb response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteBlurb(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteBlurbRequest | undefined, + {} | undefined, + ]) => { + this._log.info('deleteBlurb response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * This returns a stream that emits the blurbs that are created for a - * particular chat room or user profile. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * The resource name of a chat room or user profile whose blurbs to stream. - * @param {google.protobuf.Timestamp} request.expireTime - * The time at which this stream will close. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits {@link protos.google.showcase.v1beta1.StreamBlurbsResponse|StreamBlurbsResponse} on 'data' event. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#server-streaming | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/messaging.stream_blurbs.js - * region_tag:localhost_v1beta1_generated_Messaging_StreamBlurbs_async - */ + /** + * This returns a stream that emits the blurbs that are created for a + * particular chat room or user profile. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * The resource name of a chat room or user profile whose blurbs to stream. + * @param {google.protobuf.Timestamp} request.expireTime + * The time at which this stream will close. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits {@link protos.google.showcase.v1beta1.StreamBlurbsResponse|StreamBlurbsResponse} on 'data' event. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#server-streaming | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/messaging.stream_blurbs.js + * region_tag:localhost_v1beta1_generated_Messaging_StreamBlurbs_async + */ streamBlurbs( - request?: protos.google.showcase.v1beta1.IStreamBlurbsRequest, - options?: CallOptions): - gax.CancellableStream{ + request?: protos.google.showcase.v1beta1.IStreamBlurbsRequest, + options?: CallOptions, + ): gax.CancellableStream { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('streamBlurbs stream %j', options); return this.innerApiCalls.streamBlurbs(request, options); } -/** - * This is a stream to create multiple blurbs. If an invalid blurb is - * requested to be created, the stream will close with an error. - * - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - A writable stream which accepts objects representing - * {@link protos.google.showcase.v1beta1.CreateBlurbRequest|CreateBlurbRequest}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#client-streaming | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/messaging.send_blurbs.js - * region_tag:localhost_v1beta1_generated_Messaging_SendBlurbs_async - */ + /** + * This is a stream to create multiple blurbs. If an invalid blurb is + * requested to be created, the stream will close with an error. + * + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} - A writable stream which accepts objects representing + * {@link protos.google.showcase.v1beta1.CreateBlurbRequest|CreateBlurbRequest}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#client-streaming | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/messaging.send_blurbs.js + * region_tag:localhost_v1beta1_generated_Messaging_SendBlurbs_async + */ sendBlurbs( - options?: CallOptions, - callback?: Callback< - protos.google.showcase.v1beta1.ISendBlurbsResponse, - protos.google.showcase.v1beta1.ICreateBlurbRequest|null|undefined, - {}|null|undefined>): - gax.CancellableStream; + options?: CallOptions, + callback?: Callback< + protos.google.showcase.v1beta1.ISendBlurbsResponse, + protos.google.showcase.v1beta1.ICreateBlurbRequest | null | undefined, + {} | null | undefined + >, + ): gax.CancellableStream; sendBlurbs( - callback?: Callback< - protos.google.showcase.v1beta1.ISendBlurbsResponse, - protos.google.showcase.v1beta1.ICreateBlurbRequest|null|undefined, - {}|null|undefined>): - gax.CancellableStream; + callback?: Callback< + protos.google.showcase.v1beta1.ISendBlurbsResponse, + protos.google.showcase.v1beta1.ICreateBlurbRequest | null | undefined, + {} | null | undefined + >, + ): gax.CancellableStream; sendBlurbs( - optionsOrCallback?: CallOptions|Callback< - protos.google.showcase.v1beta1.ISendBlurbsResponse, - protos.google.showcase.v1beta1.ICreateBlurbRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.showcase.v1beta1.ISendBlurbsResponse, - protos.google.showcase.v1beta1.ICreateBlurbRequest|null|undefined, - {}|null|undefined>): - gax.CancellableStream { + optionsOrCallback?: + | CallOptions + | Callback< + protos.google.showcase.v1beta1.ISendBlurbsResponse, + protos.google.showcase.v1beta1.ICreateBlurbRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.ISendBlurbsResponse, + protos.google.showcase.v1beta1.ICreateBlurbRequest | null | undefined, + {} | null | undefined + >, + ): gax.CancellableStream { if (optionsOrCallback instanceof Function && callback === undefined) { - callback = optionsOrCallback; - optionsOrCallback = {}; + callback = optionsOrCallback; + optionsOrCallback = {}; } const options = optionsOrCallback as CallOptions; - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('sendBlurbs stream %j', options); return this.innerApiCalls.sendBlurbs(null, options, callback); } -/** - * This method starts a bidirectional stream that receives all blurbs that - * are being created after the stream has started and sends requests to create - * blurbs. If an invalid blurb is requested to be created, the stream will - * close with an error. - * - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which is both readable and writable. It accepts objects - * representing {@link protos.google.showcase.v1beta1.ConnectRequest|ConnectRequest} for write() method, and - * will emit objects representing {@link protos.google.showcase.v1beta1.StreamBlurbsResponse|StreamBlurbsResponse} on 'data' event asynchronously. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#bi-directional-streaming | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/messaging.connect.js - * region_tag:localhost_v1beta1_generated_Messaging_Connect_async - */ - connect( - options?: CallOptions): - gax.CancellableStream { - this.initialize().catch(err => {throw err}); + /** + * This method starts a bidirectional stream that receives all blurbs that + * are being created after the stream has started and sends requests to create + * blurbs. If an invalid blurb is requested to be created, the stream will + * close with an error. + * + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which is both readable and writable. It accepts objects + * representing {@link protos.google.showcase.v1beta1.ConnectRequest|ConnectRequest} for write() method, and + * will emit objects representing {@link protos.google.showcase.v1beta1.StreamBlurbsResponse|StreamBlurbsResponse} on 'data' event asynchronously. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#bi-directional-streaming | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/messaging.connect.js + * region_tag:localhost_v1beta1_generated_Messaging_Connect_async + */ + connect(options?: CallOptions): gax.CancellableStream { + this.initialize().catch((err) => { + throw err; + }); this._log.info('connect stream %j', options); return this.innerApiCalls.connect(null, options); } -/** - * This method searches through all blurbs across all rooms and profiles - * for blurbs containing to words found in the query. Only posts that - * contain an exact match of a queried word will be returned. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.query - * The query used to search for blurbs containing to words of this string. - * Only posts that contain an exact match of a queried word will be returned. - * @param {string} request.parent - * The rooms or profiles to search. If unset, `SearchBlurbs` will search all - * rooms and all profiles. - * @param {number} request.pageSize - * The maximum number of blurbs return. Server may return fewer - * blurbs than requested. If unspecified, server will pick an appropriate - * default. - * @param {string} request.pageToken - * The value of - * google.showcase.v1beta1.SearchBlurbsResponse.next_page_token - * returned from the previous call to - * `google.showcase.v1beta1.Messaging\SearchBlurbs` method. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing - * a long running operation. Its `promise()` method returns a promise - * you can `await` for. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/messaging.search_blurbs.js - * region_tag:localhost_v1beta1_generated_Messaging_SearchBlurbs_async - */ + /** + * This method searches through all blurbs across all rooms and profiles + * for blurbs containing to words found in the query. Only posts that + * contain an exact match of a queried word will be returned. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.query + * The query used to search for blurbs containing to words of this string. + * Only posts that contain an exact match of a queried word will be returned. + * @param {string} request.parent + * The rooms or profiles to search. If unset, `SearchBlurbs` will search all + * rooms and all profiles. + * @param {number} request.pageSize + * The maximum number of blurbs return. Server may return fewer + * blurbs than requested. If unspecified, server will pick an appropriate + * default. + * @param {string} request.pageToken + * The value of + * google.showcase.v1beta1.SearchBlurbsResponse.next_page_token + * returned from the previous call to + * `google.showcase.v1beta1.Messaging\SearchBlurbs` method. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/messaging.search_blurbs.js + * region_tag:localhost_v1beta1_generated_Messaging_SearchBlurbs_async + */ searchBlurbs( - request?: protos.google.showcase.v1beta1.ISearchBlurbsRequest, - options?: CallOptions): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.ISearchBlurbsRequest, + options?: CallOptions, + ): Promise< + [ + LROperation< + protos.google.showcase.v1beta1.ISearchBlurbsResponse, + protos.google.showcase.v1beta1.ISearchBlurbsMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; searchBlurbs( - request: protos.google.showcase.v1beta1.ISearchBlurbsRequest, - options: CallOptions, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.ISearchBlurbsRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.showcase.v1beta1.ISearchBlurbsResponse, + protos.google.showcase.v1beta1.ISearchBlurbsMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; searchBlurbs( - request: protos.google.showcase.v1beta1.ISearchBlurbsRequest, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.ISearchBlurbsRequest, + callback: Callback< + LROperation< + protos.google.showcase.v1beta1.ISearchBlurbsResponse, + protos.google.showcase.v1beta1.ISearchBlurbsMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; searchBlurbs( - request?: protos.google.showcase.v1beta1.ISearchBlurbsRequest, - optionsOrCallback?: CallOptions|Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>, - callback?: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>|void { + request?: protos.google.showcase.v1beta1.ISearchBlurbsRequest, + optionsOrCallback?: + | CallOptions + | Callback< + LROperation< + protos.google.showcase.v1beta1.ISearchBlurbsResponse, + protos.google.showcase.v1beta1.ISearchBlurbsMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + callback?: Callback< + LROperation< + protos.google.showcase.v1beta1.ISearchBlurbsResponse, + protos.google.showcase.v1beta1.ISearchBlurbsMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + LROperation< + protos.google.showcase.v1beta1.ISearchBlurbsResponse, + protos.google.showcase.v1beta1.ISearchBlurbsMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + LROperation< + protos.google.showcase.v1beta1.ISearchBlurbsResponse, + protos.google.showcase.v1beta1.ISearchBlurbsMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, rawResponse, _) => { this._log.info('searchBlurbs response %j', rawResponse); callback!(error, response, rawResponse, _); // We verified callback above. } : undefined; this._log.info('searchBlurbs request %j', request); - return this.innerApiCalls.searchBlurbs(request, options, wrappedCallback) - ?.then(([response, rawResponse, _]: [ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]) => { - this._log.info('searchBlurbs response %j', rawResponse); - return [response, rawResponse, _]; - }); + return this.innerApiCalls + .searchBlurbs(request, options, wrappedCallback) + ?.then( + ([response, rawResponse, _]: [ + LROperation< + protos.google.showcase.v1beta1.ISearchBlurbsResponse, + protos.google.showcase.v1beta1.ISearchBlurbsMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ]) => { + this._log.info('searchBlurbs response %j', rawResponse); + return [response, rawResponse, _]; + }, + ); } -/** - * Check the status of the long running operation returned by `searchBlurbs()`. - * @param {String} name - * The operation name that will be passed. - * @returns {Promise} - The promise which resolves to an object. - * The decoded operation object has result and metadata field to get information from. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/messaging.search_blurbs.js - * region_tag:localhost_v1beta1_generated_Messaging_SearchBlurbs_async - */ - async checkSearchBlurbsProgress(name: string): Promise>{ + /** + * Check the status of the long running operation returned by `searchBlurbs()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/messaging.search_blurbs.js + * region_tag:localhost_v1beta1_generated_Messaging_SearchBlurbs_async + */ + async checkSearchBlurbsProgress( + name: string, + ): Promise< + LROperation< + protos.google.showcase.v1beta1.SearchBlurbsResponse, + protos.google.showcase.v1beta1.SearchBlurbsMetadata + > + > { this._log.info('searchBlurbs long-running'); - const request = new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest({name}); + const request = + new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( + { name }, + ); const [operation] = await this.operationsClient.getOperation(request); - const decodeOperation = new this._gaxModule.Operation(operation, this.descriptors.longrunning.searchBlurbs, this._gaxModule.createDefaultBackoffSettings()); - return decodeOperation as LROperation; + const decodeOperation = new this._gaxModule.Operation( + operation, + this.descriptors.longrunning.searchBlurbs, + this._gaxModule.createDefaultBackoffSettings(), + ); + return decodeOperation as LROperation< + protos.google.showcase.v1beta1.SearchBlurbsResponse, + protos.google.showcase.v1beta1.SearchBlurbsMetadata + >; } - /** - * Lists all chat rooms. - * - * @param {Object} request - * The request object that will be sent. - * @param {number} request.pageSize - * The maximum number of rooms return. Server may return fewer rooms - * than requested. If unspecified, server will pick an appropriate default. - * @param {string} request.pageToken - * The value of google.showcase.v1beta1.ListRoomsResponse.next_page_token - * returned from the previous call to - * `google.showcase.v1beta1.Messaging\ListRooms` method. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.showcase.v1beta1.Room|Room}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `listRoomsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Lists all chat rooms. + * + * @param {Object} request + * The request object that will be sent. + * @param {number} request.pageSize + * The maximum number of rooms return. Server may return fewer rooms + * than requested. If unspecified, server will pick an appropriate default. + * @param {string} request.pageToken + * The value of google.showcase.v1beta1.ListRoomsResponse.next_page_token + * returned from the previous call to + * `google.showcase.v1beta1.Messaging\ListRooms` method. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.showcase.v1beta1.Room|Room}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listRoomsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listRooms( - request?: protos.google.showcase.v1beta1.IListRoomsRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IRoom[], - protos.google.showcase.v1beta1.IListRoomsRequest|null, - protos.google.showcase.v1beta1.IListRoomsResponse - ]>; + request?: protos.google.showcase.v1beta1.IListRoomsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IRoom[], + protos.google.showcase.v1beta1.IListRoomsRequest | null, + protos.google.showcase.v1beta1.IListRoomsResponse, + ] + >; listRooms( - request: protos.google.showcase.v1beta1.IListRoomsRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.showcase.v1beta1.IListRoomsRequest, - protos.google.showcase.v1beta1.IListRoomsResponse|null|undefined, - protos.google.showcase.v1beta1.IRoom>): void; + request: protos.google.showcase.v1beta1.IListRoomsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.showcase.v1beta1.IListRoomsRequest, + protos.google.showcase.v1beta1.IListRoomsResponse | null | undefined, + protos.google.showcase.v1beta1.IRoom + >, + ): void; listRooms( - request: protos.google.showcase.v1beta1.IListRoomsRequest, - callback: PaginationCallback< - protos.google.showcase.v1beta1.IListRoomsRequest, - protos.google.showcase.v1beta1.IListRoomsResponse|null|undefined, - protos.google.showcase.v1beta1.IRoom>): void; + request: protos.google.showcase.v1beta1.IListRoomsRequest, + callback: PaginationCallback< + protos.google.showcase.v1beta1.IListRoomsRequest, + protos.google.showcase.v1beta1.IListRoomsResponse | null | undefined, + protos.google.showcase.v1beta1.IRoom + >, + ): void; listRooms( - request?: protos.google.showcase.v1beta1.IListRoomsRequest, - optionsOrCallback?: CallOptions|PaginationCallback< + request?: protos.google.showcase.v1beta1.IListRoomsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.showcase.v1beta1.IListRoomsRequest, - protos.google.showcase.v1beta1.IListRoomsResponse|null|undefined, - protos.google.showcase.v1beta1.IRoom>, - callback?: PaginationCallback< - protos.google.showcase.v1beta1.IListRoomsRequest, - protos.google.showcase.v1beta1.IListRoomsResponse|null|undefined, - protos.google.showcase.v1beta1.IRoom>): - Promise<[ - protos.google.showcase.v1beta1.IRoom[], - protos.google.showcase.v1beta1.IListRoomsRequest|null, - protos.google.showcase.v1beta1.IListRoomsResponse - ]>|void { + protos.google.showcase.v1beta1.IListRoomsResponse | null | undefined, + protos.google.showcase.v1beta1.IRoom + >, + callback?: PaginationCallback< + protos.google.showcase.v1beta1.IListRoomsRequest, + protos.google.showcase.v1beta1.IListRoomsResponse | null | undefined, + protos.google.showcase.v1beta1.IRoom + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IRoom[], + protos.google.showcase.v1beta1.IListRoomsRequest | null, + protos.google.showcase.v1beta1.IListRoomsResponse, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.showcase.v1beta1.IListRoomsRequest, - protos.google.showcase.v1beta1.IListRoomsResponse|null|undefined, - protos.google.showcase.v1beta1.IRoom>|undefined = callback + this.initialize().catch((err) => { + throw err; + }); + const wrappedCallback: + | PaginationCallback< + protos.google.showcase.v1beta1.IListRoomsRequest, + protos.google.showcase.v1beta1.IListRoomsResponse | null | undefined, + protos.google.showcase.v1beta1.IRoom + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listRooms values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -1483,186 +1898,207 @@ export class MessagingClient { this._log.info('listRooms request %j', request); return this.innerApiCalls .listRooms(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.showcase.v1beta1.IRoom[], - protos.google.showcase.v1beta1.IListRoomsRequest|null, - protos.google.showcase.v1beta1.IListRoomsResponse - ]) => { - this._log.info('listRooms values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.showcase.v1beta1.IRoom[], + protos.google.showcase.v1beta1.IListRoomsRequest | null, + protos.google.showcase.v1beta1.IListRoomsResponse, + ]) => { + this._log.info('listRooms values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listRooms`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {number} request.pageSize - * The maximum number of rooms return. Server may return fewer rooms - * than requested. If unspecified, server will pick an appropriate default. - * @param {string} request.pageToken - * The value of google.showcase.v1beta1.ListRoomsResponse.next_page_token - * returned from the previous call to - * `google.showcase.v1beta1.Messaging\ListRooms` method. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.showcase.v1beta1.Room|Room} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `listRoomsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `listRooms`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {number} request.pageSize + * The maximum number of rooms return. Server may return fewer rooms + * than requested. If unspecified, server will pick an appropriate default. + * @param {string} request.pageToken + * The value of google.showcase.v1beta1.ListRoomsResponse.next_page_token + * returned from the previous call to + * `google.showcase.v1beta1.Messaging\ListRooms` method. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.showcase.v1beta1.Room|Room} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listRoomsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listRoomsStream( - request?: protos.google.showcase.v1beta1.IListRoomsRequest, - options?: CallOptions): - Transform{ + request?: protos.google.showcase.v1beta1.IListRoomsRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; const defaultCallSettings = this._defaults['listRooms']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listRooms stream %j', request); return this.descriptors.page.listRooms.createStream( this.innerApiCalls.listRooms as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listRooms`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {number} request.pageSize - * The maximum number of rooms return. Server may return fewer rooms - * than requested. If unspecified, server will pick an appropriate default. - * @param {string} request.pageToken - * The value of google.showcase.v1beta1.ListRoomsResponse.next_page_token - * returned from the previous call to - * `google.showcase.v1beta1.Messaging\ListRooms` method. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.showcase.v1beta1.Room|Room}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/messaging.list_rooms.js - * region_tag:localhost_v1beta1_generated_Messaging_ListRooms_async - */ + /** + * Equivalent to `listRooms`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {number} request.pageSize + * The maximum number of rooms return. Server may return fewer rooms + * than requested. If unspecified, server will pick an appropriate default. + * @param {string} request.pageToken + * The value of google.showcase.v1beta1.ListRoomsResponse.next_page_token + * returned from the previous call to + * `google.showcase.v1beta1.Messaging\ListRooms` method. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.showcase.v1beta1.Room|Room}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/messaging.list_rooms.js + * region_tag:localhost_v1beta1_generated_Messaging_ListRooms_async + */ listRoomsAsync( - request?: protos.google.showcase.v1beta1.IListRoomsRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.showcase.v1beta1.IListRoomsRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; const defaultCallSettings = this._defaults['listRooms']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listRooms iterate %j', request); return this.descriptors.page.listRooms.asyncIterate( this.innerApiCalls['listRooms'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } - /** - * Lists blurbs for a specific chat room or user profile depending on the - * parent resource name. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * The resource name of the requested room or profile whos blurbs to list. - * @param {number} request.pageSize - * The maximum number of blurbs to return. Server may return fewer - * blurbs than requested. If unspecified, server will pick an appropriate - * default. - * @param {string} request.pageToken - * The value of google.showcase.v1beta1.ListBlurbsResponse.next_page_token - * returned from the previous call to - * `google.showcase.v1beta1.Messaging\ListBlurbs` method. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.showcase.v1beta1.Blurb|Blurb}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `listBlurbsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Lists blurbs for a specific chat room or user profile depending on the + * parent resource name. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * The resource name of the requested room or profile whos blurbs to list. + * @param {number} request.pageSize + * The maximum number of blurbs to return. Server may return fewer + * blurbs than requested. If unspecified, server will pick an appropriate + * default. + * @param {string} request.pageToken + * The value of google.showcase.v1beta1.ListBlurbsResponse.next_page_token + * returned from the previous call to + * `google.showcase.v1beta1.Messaging\ListBlurbs` method. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.showcase.v1beta1.Blurb|Blurb}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listBlurbsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listBlurbs( - request?: protos.google.showcase.v1beta1.IListBlurbsRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IBlurb[], - protos.google.showcase.v1beta1.IListBlurbsRequest|null, - protos.google.showcase.v1beta1.IListBlurbsResponse - ]>; + request?: protos.google.showcase.v1beta1.IListBlurbsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IBlurb[], + protos.google.showcase.v1beta1.IListBlurbsRequest | null, + protos.google.showcase.v1beta1.IListBlurbsResponse, + ] + >; listBlurbs( - request: protos.google.showcase.v1beta1.IListBlurbsRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.showcase.v1beta1.IListBlurbsRequest, - protos.google.showcase.v1beta1.IListBlurbsResponse|null|undefined, - protos.google.showcase.v1beta1.IBlurb>): void; + request: protos.google.showcase.v1beta1.IListBlurbsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.showcase.v1beta1.IListBlurbsRequest, + protos.google.showcase.v1beta1.IListBlurbsResponse | null | undefined, + protos.google.showcase.v1beta1.IBlurb + >, + ): void; listBlurbs( - request: protos.google.showcase.v1beta1.IListBlurbsRequest, - callback: PaginationCallback< - protos.google.showcase.v1beta1.IListBlurbsRequest, - protos.google.showcase.v1beta1.IListBlurbsResponse|null|undefined, - protos.google.showcase.v1beta1.IBlurb>): void; + request: protos.google.showcase.v1beta1.IListBlurbsRequest, + callback: PaginationCallback< + protos.google.showcase.v1beta1.IListBlurbsRequest, + protos.google.showcase.v1beta1.IListBlurbsResponse | null | undefined, + protos.google.showcase.v1beta1.IBlurb + >, + ): void; listBlurbs( - request?: protos.google.showcase.v1beta1.IListBlurbsRequest, - optionsOrCallback?: CallOptions|PaginationCallback< + request?: protos.google.showcase.v1beta1.IListBlurbsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.showcase.v1beta1.IListBlurbsRequest, - protos.google.showcase.v1beta1.IListBlurbsResponse|null|undefined, - protos.google.showcase.v1beta1.IBlurb>, - callback?: PaginationCallback< - protos.google.showcase.v1beta1.IListBlurbsRequest, - protos.google.showcase.v1beta1.IListBlurbsResponse|null|undefined, - protos.google.showcase.v1beta1.IBlurb>): - Promise<[ - protos.google.showcase.v1beta1.IBlurb[], - protos.google.showcase.v1beta1.IListBlurbsRequest|null, - protos.google.showcase.v1beta1.IListBlurbsResponse - ]>|void { + protos.google.showcase.v1beta1.IListBlurbsResponse | null | undefined, + protos.google.showcase.v1beta1.IBlurb + >, + callback?: PaginationCallback< + protos.google.showcase.v1beta1.IListBlurbsRequest, + protos.google.showcase.v1beta1.IListBlurbsResponse | null | undefined, + protos.google.showcase.v1beta1.IBlurb + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IBlurb[], + protos.google.showcase.v1beta1.IListBlurbsRequest | null, + protos.google.showcase.v1beta1.IListBlurbsResponse, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.showcase.v1beta1.IListBlurbsRequest, - protos.google.showcase.v1beta1.IListBlurbsResponse|null|undefined, - protos.google.showcase.v1beta1.IBlurb>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.showcase.v1beta1.IListBlurbsRequest, + protos.google.showcase.v1beta1.IListBlurbsResponse | null | undefined, + protos.google.showcase.v1beta1.IBlurb + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listBlurbs values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -1671,114 +2107,118 @@ export class MessagingClient { this._log.info('listBlurbs request %j', request); return this.innerApiCalls .listBlurbs(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.showcase.v1beta1.IBlurb[], - protos.google.showcase.v1beta1.IListBlurbsRequest|null, - protos.google.showcase.v1beta1.IListBlurbsResponse - ]) => { - this._log.info('listBlurbs values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.showcase.v1beta1.IBlurb[], + protos.google.showcase.v1beta1.IListBlurbsRequest | null, + protos.google.showcase.v1beta1.IListBlurbsResponse, + ]) => { + this._log.info('listBlurbs values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listBlurbs`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * The resource name of the requested room or profile whos blurbs to list. - * @param {number} request.pageSize - * The maximum number of blurbs to return. Server may return fewer - * blurbs than requested. If unspecified, server will pick an appropriate - * default. - * @param {string} request.pageToken - * The value of google.showcase.v1beta1.ListBlurbsResponse.next_page_token - * returned from the previous call to - * `google.showcase.v1beta1.Messaging\ListBlurbs` method. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.showcase.v1beta1.Blurb|Blurb} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `listBlurbsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `listBlurbs`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * The resource name of the requested room or profile whos blurbs to list. + * @param {number} request.pageSize + * The maximum number of blurbs to return. Server may return fewer + * blurbs than requested. If unspecified, server will pick an appropriate + * default. + * @param {string} request.pageToken + * The value of google.showcase.v1beta1.ListBlurbsResponse.next_page_token + * returned from the previous call to + * `google.showcase.v1beta1.Messaging\ListBlurbs` method. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.showcase.v1beta1.Blurb|Blurb} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listBlurbsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listBlurbsStream( - request?: protos.google.showcase.v1beta1.IListBlurbsRequest, - options?: CallOptions): - Transform{ + request?: protos.google.showcase.v1beta1.IListBlurbsRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); const defaultCallSettings = this._defaults['listBlurbs']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listBlurbs stream %j', request); return this.descriptors.page.listBlurbs.createStream( this.innerApiCalls.listBlurbs as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listBlurbs`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * The resource name of the requested room or profile whos blurbs to list. - * @param {number} request.pageSize - * The maximum number of blurbs to return. Server may return fewer - * blurbs than requested. If unspecified, server will pick an appropriate - * default. - * @param {string} request.pageToken - * The value of google.showcase.v1beta1.ListBlurbsResponse.next_page_token - * returned from the previous call to - * `google.showcase.v1beta1.Messaging\ListBlurbs` method. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.showcase.v1beta1.Blurb|Blurb}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/messaging.list_blurbs.js - * region_tag:localhost_v1beta1_generated_Messaging_ListBlurbs_async - */ + /** + * Equivalent to `listBlurbs`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * The resource name of the requested room or profile whos blurbs to list. + * @param {number} request.pageSize + * The maximum number of blurbs to return. Server may return fewer + * blurbs than requested. If unspecified, server will pick an appropriate + * default. + * @param {string} request.pageToken + * The value of google.showcase.v1beta1.ListBlurbsResponse.next_page_token + * returned from the previous call to + * `google.showcase.v1beta1.Messaging\ListBlurbs` method. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.showcase.v1beta1.Blurb|Blurb}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/messaging.list_blurbs.js + * region_tag:localhost_v1beta1_generated_Messaging_ListBlurbs_async + */ listBlurbsAsync( - request?: protos.google.showcase.v1beta1.IListBlurbsRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.showcase.v1beta1.IListBlurbsRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); const defaultCallSettings = this._defaults['listBlurbs']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listBlurbs iterate %j', request); return this.descriptors.page.listBlurbs.asyncIterate( this.innerApiCalls['listBlurbs'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } // -------------------- @@ -1793,7 +2233,7 @@ export class MessagingClient { * @param {string} blueprint * @returns {string} Resource name string. */ - blueprintPath(session:string,test:string,blueprint:string) { + blueprintPath(session: string, test: string, blueprint: string) { return this.pathTemplates.blueprintPathTemplate.render({ session: session, test: test, @@ -1809,7 +2249,8 @@ export class MessagingClient { * @returns {string} A string representing the session. */ matchSessionFromBlueprintName(blueprintName: string) { - return this.pathTemplates.blueprintPathTemplate.match(blueprintName).session; + return this.pathTemplates.blueprintPathTemplate.match(blueprintName) + .session; } /** @@ -1831,7 +2272,8 @@ export class MessagingClient { * @returns {string} A string representing the blueprint. */ matchBlueprintFromBlueprintName(blueprintName: string) { - return this.pathTemplates.blueprintPathTemplate.match(blueprintName).blueprint; + return this.pathTemplates.blueprintPathTemplate.match(blueprintName) + .blueprint; } /** @@ -1840,7 +2282,7 @@ export class MessagingClient { * @param {string} room * @returns {string} Resource name string. */ - roomPath(room:string) { + roomPath(room: string) { return this.pathTemplates.roomPathTemplate.render({ room: room, }); @@ -1864,7 +2306,7 @@ export class MessagingClient { * @param {string} blurb * @returns {string} Resource name string. */ - roomBlurbPath(room:string,blurb:string) { + roomBlurbPath(room: string, blurb: string) { return this.pathTemplates.roomBlurbPathTemplate.render({ room: room, blurb: blurb, @@ -1901,7 +2343,11 @@ export class MessagingClient { * @param {string} blurb * @returns {string} Resource name string. */ - roomBlurbsLegacyRoomBlurbPath(room:string,legacyRoom:string,blurb:string) { + roomBlurbsLegacyRoomBlurbPath( + room: string, + legacyRoom: string, + blurb: string, + ) { return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.render({ room: room, legacy_room: legacyRoom, @@ -1916,8 +2362,12 @@ export class MessagingClient { * A fully-qualified path representing room_blurbs_legacy_room_blurb resource. * @returns {string} A string representing the room. */ - matchRoomFromRoomBlurbsLegacyRoomBlurbName(roomBlurbsLegacyRoomBlurbName: string) { - return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match(roomBlurbsLegacyRoomBlurbName).room; + matchRoomFromRoomBlurbsLegacyRoomBlurbName( + roomBlurbsLegacyRoomBlurbName: string, + ) { + return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match( + roomBlurbsLegacyRoomBlurbName, + ).room; } /** @@ -1927,8 +2377,12 @@ export class MessagingClient { * A fully-qualified path representing room_blurbs_legacy_room_blurb resource. * @returns {string} A string representing the legacy_room. */ - matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName(roomBlurbsLegacyRoomBlurbName: string) { - return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match(roomBlurbsLegacyRoomBlurbName).legacy_room; + matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName( + roomBlurbsLegacyRoomBlurbName: string, + ) { + return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match( + roomBlurbsLegacyRoomBlurbName, + ).legacy_room; } /** @@ -1938,8 +2392,12 @@ export class MessagingClient { * A fully-qualified path representing room_blurbs_legacy_room_blurb resource. * @returns {string} A string representing the blurb. */ - matchBlurbFromRoomBlurbsLegacyRoomBlurbName(roomBlurbsLegacyRoomBlurbName: string) { - return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match(roomBlurbsLegacyRoomBlurbName).blurb; + matchBlurbFromRoomBlurbsLegacyRoomBlurbName( + roomBlurbsLegacyRoomBlurbName: string, + ) { + return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match( + roomBlurbsLegacyRoomBlurbName, + ).blurb; } /** @@ -1948,7 +2406,7 @@ export class MessagingClient { * @param {string} sequence * @returns {string} Resource name string. */ - sequencePath(sequence:string) { + sequencePath(sequence: string) { return this.pathTemplates.sequencePathTemplate.render({ sequence: sequence, }); @@ -1971,7 +2429,7 @@ export class MessagingClient { * @param {string} sequence * @returns {string} Resource name string. */ - sequenceReportPath(sequence:string) { + sequenceReportPath(sequence: string) { return this.pathTemplates.sequenceReportPathTemplate.render({ sequence: sequence, }); @@ -1985,7 +2443,9 @@ export class MessagingClient { * @returns {string} A string representing the sequence. */ matchSequenceFromSequenceReportName(sequenceReportName: string) { - return this.pathTemplates.sequenceReportPathTemplate.match(sequenceReportName).sequence; + return this.pathTemplates.sequenceReportPathTemplate.match( + sequenceReportName, + ).sequence; } /** @@ -1994,7 +2454,7 @@ export class MessagingClient { * @param {string} session * @returns {string} Resource name string. */ - sessionPath(session:string) { + sessionPath(session: string) { return this.pathTemplates.sessionPathTemplate.render({ session: session, }); @@ -2018,7 +2478,7 @@ export class MessagingClient { * @param {string} test * @returns {string} Resource name string. */ - testPath(session:string,test:string) { + testPath(session: string, test: string) { return this.pathTemplates.testPathTemplate.render({ session: session, test: test, @@ -2053,7 +2513,7 @@ export class MessagingClient { * @param {string} user * @returns {string} Resource name string. */ - userPath(user:string) { + userPath(user: string) { return this.pathTemplates.userPathTemplate.render({ user: user, }); @@ -2077,7 +2537,7 @@ export class MessagingClient { * @param {string} blurb * @returns {string} Resource name string. */ - userProfileBlurbPath(user:string,blurb:string) { + userProfileBlurbPath(user: string, blurb: string) { return this.pathTemplates.userProfileBlurbPathTemplate.render({ user: user, blurb: blurb, @@ -2092,7 +2552,9 @@ export class MessagingClient { * @returns {string} A string representing the user. */ matchUserFromUserProfileBlurbName(userProfileBlurbName: string) { - return this.pathTemplates.userProfileBlurbPathTemplate.match(userProfileBlurbName).user; + return this.pathTemplates.userProfileBlurbPathTemplate.match( + userProfileBlurbName, + ).user; } /** @@ -2103,7 +2565,9 @@ export class MessagingClient { * @returns {string} A string representing the blurb. */ matchBlurbFromUserProfileBlurbName(userProfileBlurbName: string) { - return this.pathTemplates.userProfileBlurbPathTemplate.match(userProfileBlurbName).blurb; + return this.pathTemplates.userProfileBlurbPathTemplate.match( + userProfileBlurbName, + ).blurb; } /** @@ -2114,12 +2578,18 @@ export class MessagingClient { * @param {string} blurb * @returns {string} Resource name string. */ - userProfileBlurbsLegacyUserBlurbPath(user:string,legacyUser:string,blurb:string) { - return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.render({ - user: user, - legacy_user: legacyUser, - blurb: blurb, - }); + userProfileBlurbsLegacyUserBlurbPath( + user: string, + legacyUser: string, + blurb: string, + ) { + return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.render( + { + user: user, + legacy_user: legacyUser, + blurb: blurb, + }, + ); } /** @@ -2129,8 +2599,12 @@ export class MessagingClient { * A fully-qualified path representing user_profile_blurbs_legacy_user_blurb resource. * @returns {string} A string representing the user. */ - matchUserFromUserProfileBlurbsLegacyUserBlurbName(userProfileBlurbsLegacyUserBlurbName: string) { - return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match(userProfileBlurbsLegacyUserBlurbName).user; + matchUserFromUserProfileBlurbsLegacyUserBlurbName( + userProfileBlurbsLegacyUserBlurbName: string, + ) { + return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match( + userProfileBlurbsLegacyUserBlurbName, + ).user; } /** @@ -2140,8 +2614,12 @@ export class MessagingClient { * A fully-qualified path representing user_profile_blurbs_legacy_user_blurb resource. * @returns {string} A string representing the legacy_user. */ - matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName(userProfileBlurbsLegacyUserBlurbName: string) { - return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match(userProfileBlurbsLegacyUserBlurbName).legacy_user; + matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName( + userProfileBlurbsLegacyUserBlurbName: string, + ) { + return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match( + userProfileBlurbsLegacyUserBlurbName, + ).legacy_user; } /** @@ -2151,8 +2629,12 @@ export class MessagingClient { * A fully-qualified path representing user_profile_blurbs_legacy_user_blurb resource. * @returns {string} A string representing the blurb. */ - matchBlurbFromUserProfileBlurbsLegacyUserBlurbName(userProfileBlurbsLegacyUserBlurbName: string) { - return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match(userProfileBlurbsLegacyUserBlurbName).blurb; + matchBlurbFromUserProfileBlurbsLegacyUserBlurbName( + userProfileBlurbsLegacyUserBlurbName: string, + ) { + return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match( + userProfileBlurbsLegacyUserBlurbName, + ).blurb; } /** @@ -2163,7 +2645,7 @@ export class MessagingClient { */ close(): Promise { if (this.messagingStub && !this._terminated) { - return this.messagingStub.then(stub => { + return this.messagingStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -2172,4 +2654,4 @@ export class MessagingClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/core/generator/gapic-generator-typescript/baselines/disable-packing-test/src/v1beta1/sequence_service_client.ts.baseline b/core/generator/gapic-generator-typescript/baselines/disable-packing-test/src/v1beta1/sequence_service_client.ts.baseline index 81d1cf10364c..a852db0e1a71 100644 --- a/core/generator/gapic-generator-typescript/baselines/disable-packing-test/src/v1beta1/sequence_service_client.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/disable-packing-test/src/v1beta1/sequence_service_client.ts.baseline @@ -18,11 +18,16 @@ /* global window */ import type * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions} from 'google-gax'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, +} from 'google-gax'; import * as protos from '../../protos/protos'; import jsonProtos = require('../../protos/protos.json'); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; /** * Client JSON configuration object, loaded from @@ -43,7 +48,7 @@ export class SequenceServiceClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('showcase'); @@ -56,9 +61,9 @@ export class SequenceServiceClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; - sequenceServiceStub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; + sequenceServiceStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of SequenceServiceClient. @@ -99,21 +104,42 @@ export class SequenceServiceClient { * const client = new SequenceServiceClient({fallback: true}, gax); * ``` */ - constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { // Ensure that options include all the required fields. const staticMembers = this.constructor as typeof SequenceServiceClient; - if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { - throw new Error('Please set either universe_domain or universeDomain, but not both.'); + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); } - const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; - this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; this._servicePath = 'localhost'; - const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; - const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. if (servicePath !== this._servicePath && !('scopes' in opts)) { @@ -135,7 +161,7 @@ export class SequenceServiceClient { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; @@ -149,10 +175,7 @@ export class SequenceServiceClient { } // Determine the client header string. - const clientHeader = [ - `gax/${this._gaxModule.version}`, - `gapic/${version}`, - ]; + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/${process.versions.node}`); } else { @@ -174,44 +197,44 @@ export class SequenceServiceClient { // Create useful helper objects for these. this.pathTemplates = { blueprintPathTemplate: new this._gaxModule.PathTemplate( - 'sessions/{session}/tests/{test}/blueprints/{blueprint}' - ), - roomPathTemplate: new this._gaxModule.PathTemplate( - 'rooms/{room}' + 'sessions/{session}/tests/{test}/blueprints/{blueprint}', ), + roomPathTemplate: new this._gaxModule.PathTemplate('rooms/{room}'), roomBlurbPathTemplate: new this._gaxModule.PathTemplate( - 'rooms/{room}/blurbs/{blurb}' + 'rooms/{room}/blurbs/{blurb}', ), roomBlurbsLegacyRoomBlurbPathTemplate: new this._gaxModule.PathTemplate( - 'rooms/{room}/blurbs/legacy/{legacy_room}.{blurb}' + 'rooms/{room}/blurbs/legacy/{legacy_room}.{blurb}', ), sequencePathTemplate: new this._gaxModule.PathTemplate( - 'sequences/{sequence}' + 'sequences/{sequence}', ), sequenceReportPathTemplate: new this._gaxModule.PathTemplate( - 'sequences/{sequence}/sequenceReport' + 'sequences/{sequence}/sequenceReport', ), sessionPathTemplate: new this._gaxModule.PathTemplate( - 'sessions/{session}' + 'sessions/{session}', ), testPathTemplate: new this._gaxModule.PathTemplate( - 'sessions/{session}/tests/{test}' - ), - userPathTemplate: new this._gaxModule.PathTemplate( - 'users/{user}' + 'sessions/{session}/tests/{test}', ), + userPathTemplate: new this._gaxModule.PathTemplate('users/{user}'), userProfileBlurbPathTemplate: new this._gaxModule.PathTemplate( - 'users/{user}/profile/blurbs/{blurb}' - ), - userProfileBlurbsLegacyUserBlurbPathTemplate: new this._gaxModule.PathTemplate( - 'users/{user}/profile/blurbs/legacy/{legacy_user}~{blurb}' + 'users/{user}/profile/blurbs/{blurb}', ), + userProfileBlurbsLegacyUserBlurbPathTemplate: + new this._gaxModule.PathTemplate( + 'users/{user}/profile/blurbs/legacy/{legacy_user}~{blurb}', + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.showcase.v1beta1.SequenceService', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.showcase.v1beta1.SequenceService', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + { 'x-goog-api-client': clientHeader.join(' ') }, + ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -242,36 +265,44 @@ export class SequenceServiceClient { // Put together the "service stub" for // google.showcase.v1beta1.SequenceService. this.sequenceServiceStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.showcase.v1beta1.SequenceService') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.showcase.v1beta1.SequenceService', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.showcase.v1beta1.SequenceService, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts, + this._providedCustomServicePath, + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const sequenceServiceStubMethods = - ['createSequence', 'getSequenceReport', 'attemptSequence']; + const sequenceServiceStubMethods = [ + 'createSequence', + 'getSequenceReport', + 'attemptSequence', + ]; for (const methodName of sequenceServiceStubMethods) { const callPromise = this.sequenceServiceStub.then( - stub => (...args: Array<{}>) => { - if (this._terminated) { - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error|null|undefined) => () => { + (stub) => + (...args: Array<{}>) => { + if (this._terminated) { + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { throw err; - }); + }, + ); - const descriptor = - undefined; + const descriptor = undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -286,8 +317,14 @@ export class SequenceServiceClient { * @returns {string} The DNS address for this service. */ static get servicePath() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'localhost'; } @@ -298,8 +335,14 @@ export class SequenceServiceClient { * @returns {string} The DNS address for this service. */ static get apiEndpoint() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'localhost'; } @@ -339,8 +382,9 @@ export class SequenceServiceClient { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId(callback?: Callback): - Promise|void { + getProjectId( + callback?: Callback, + ): Promise | void { if (callback) { this.auth.getProjectId(callback); return; @@ -351,276 +395,385 @@ export class SequenceServiceClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Creates a sequence. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.showcase.v1beta1.Sequence} request.sequence - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.Sequence|Sequence}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/sequence_service.create_sequence.js - * region_tag:localhost_v1beta1_generated_SequenceService_CreateSequence_async - */ + /** + * Creates a sequence. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.showcase.v1beta1.Sequence} request.sequence + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.Sequence|Sequence}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/sequence_service.create_sequence.js + * region_tag:localhost_v1beta1_generated_SequenceService_CreateSequence_async + */ createSequence( - request?: protos.google.showcase.v1beta1.ICreateSequenceRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.ISequence, - protos.google.showcase.v1beta1.ICreateSequenceRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.ICreateSequenceRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.ISequence, + protos.google.showcase.v1beta1.ICreateSequenceRequest | undefined, + {} | undefined, + ] + >; createSequence( - request: protos.google.showcase.v1beta1.ICreateSequenceRequest, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.ISequence, - protos.google.showcase.v1beta1.ICreateSequenceRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.ICreateSequenceRequest, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.ISequence, + protos.google.showcase.v1beta1.ICreateSequenceRequest | null | undefined, + {} | null | undefined + >, + ): void; createSequence( - request: protos.google.showcase.v1beta1.ICreateSequenceRequest, - callback: Callback< - protos.google.showcase.v1beta1.ISequence, - protos.google.showcase.v1beta1.ICreateSequenceRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.ICreateSequenceRequest, + callback: Callback< + protos.google.showcase.v1beta1.ISequence, + protos.google.showcase.v1beta1.ICreateSequenceRequest | null | undefined, + {} | null | undefined + >, + ): void; createSequence( - request?: protos.google.showcase.v1beta1.ICreateSequenceRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.showcase.v1beta1.ISequence, - protos.google.showcase.v1beta1.ICreateSequenceRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.showcase.v1beta1.ICreateSequenceRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.ISequence, - protos.google.showcase.v1beta1.ICreateSequenceRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.ISequence, - protos.google.showcase.v1beta1.ICreateSequenceRequest|undefined, {}|undefined - ]>|void { + | protos.google.showcase.v1beta1.ICreateSequenceRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.ISequence, + protos.google.showcase.v1beta1.ICreateSequenceRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.ISequence, + protos.google.showcase.v1beta1.ICreateSequenceRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('createSequence request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.ISequence, - protos.google.showcase.v1beta1.ICreateSequenceRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.ISequence, + | protos.google.showcase.v1beta1.ICreateSequenceRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createSequence response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.createSequence(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.ISequence, - protos.google.showcase.v1beta1.ICreateSequenceRequest|undefined, - {}|undefined - ]) => { - this._log.info('createSequence response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createSequence(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.ISequence, + protos.google.showcase.v1beta1.ICreateSequenceRequest | undefined, + {} | undefined, + ]) => { + this._log.info('createSequence response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Retrieves a sequence. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.SequenceReport|SequenceReport}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/sequence_service.get_sequence_report.js - * region_tag:localhost_v1beta1_generated_SequenceService_GetSequenceReport_async - */ + /** + * Retrieves a sequence. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.SequenceReport|SequenceReport}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/sequence_service.get_sequence_report.js + * region_tag:localhost_v1beta1_generated_SequenceService_GetSequenceReport_async + */ getSequenceReport( - request?: protos.google.showcase.v1beta1.IGetSequenceReportRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.ISequenceReport, - protos.google.showcase.v1beta1.IGetSequenceReportRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IGetSequenceReportRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.ISequenceReport, + protos.google.showcase.v1beta1.IGetSequenceReportRequest | undefined, + {} | undefined, + ] + >; getSequenceReport( - request: protos.google.showcase.v1beta1.IGetSequenceReportRequest, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.ISequenceReport, - protos.google.showcase.v1beta1.IGetSequenceReportRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IGetSequenceReportRequest, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.ISequenceReport, + | protos.google.showcase.v1beta1.IGetSequenceReportRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getSequenceReport( - request: protos.google.showcase.v1beta1.IGetSequenceReportRequest, - callback: Callback< - protos.google.showcase.v1beta1.ISequenceReport, - protos.google.showcase.v1beta1.IGetSequenceReportRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IGetSequenceReportRequest, + callback: Callback< + protos.google.showcase.v1beta1.ISequenceReport, + | protos.google.showcase.v1beta1.IGetSequenceReportRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getSequenceReport( - request?: protos.google.showcase.v1beta1.IGetSequenceReportRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.showcase.v1beta1.ISequenceReport, - protos.google.showcase.v1beta1.IGetSequenceReportRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.showcase.v1beta1.IGetSequenceReportRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.ISequenceReport, - protos.google.showcase.v1beta1.IGetSequenceReportRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.ISequenceReport, - protos.google.showcase.v1beta1.IGetSequenceReportRequest|undefined, {}|undefined - ]>|void { + | protos.google.showcase.v1beta1.IGetSequenceReportRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.ISequenceReport, + | protos.google.showcase.v1beta1.IGetSequenceReportRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.ISequenceReport, + protos.google.showcase.v1beta1.IGetSequenceReportRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getSequenceReport request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.ISequenceReport, - protos.google.showcase.v1beta1.IGetSequenceReportRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.ISequenceReport, + | protos.google.showcase.v1beta1.IGetSequenceReportRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getSequenceReport response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getSequenceReport(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.ISequenceReport, - protos.google.showcase.v1beta1.IGetSequenceReportRequest|undefined, - {}|undefined - ]) => { - this._log.info('getSequenceReport response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getSequenceReport(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.ISequenceReport, + protos.google.showcase.v1beta1.IGetSequenceReportRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getSequenceReport response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Attempts a sequence. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/sequence_service.attempt_sequence.js - * region_tag:localhost_v1beta1_generated_SequenceService_AttemptSequence_async - */ + /** + * Attempts a sequence. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/sequence_service.attempt_sequence.js + * region_tag:localhost_v1beta1_generated_SequenceService_AttemptSequence_async + */ attemptSequence( - request?: protos.google.showcase.v1beta1.IAttemptSequenceRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IAttemptSequenceRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IAttemptSequenceRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IAttemptSequenceRequest | undefined, + {} | undefined, + ] + >; attemptSequence( - request: protos.google.showcase.v1beta1.IAttemptSequenceRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IAttemptSequenceRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IAttemptSequenceRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IAttemptSequenceRequest | null | undefined, + {} | null | undefined + >, + ): void; attemptSequence( - request: protos.google.showcase.v1beta1.IAttemptSequenceRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IAttemptSequenceRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IAttemptSequenceRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IAttemptSequenceRequest | null | undefined, + {} | null | undefined + >, + ): void; attemptSequence( - request?: protos.google.showcase.v1beta1.IAttemptSequenceRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IAttemptSequenceRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.showcase.v1beta1.IAttemptSequenceRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IAttemptSequenceRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IAttemptSequenceRequest|undefined, {}|undefined - ]>|void { + | protos.google.showcase.v1beta1.IAttemptSequenceRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IAttemptSequenceRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IAttemptSequenceRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('attemptSequence request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IAttemptSequenceRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.showcase.v1beta1.IAttemptSequenceRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('attemptSequence response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.attemptSequence(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IAttemptSequenceRequest|undefined, - {}|undefined - ]) => { - this._log.info('attemptSequence response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .attemptSequence(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IAttemptSequenceRequest | undefined, + {} | undefined, + ]) => { + this._log.info('attemptSequence response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); @@ -638,7 +791,7 @@ export class SequenceServiceClient { * @param {string} blueprint * @returns {string} Resource name string. */ - blueprintPath(session:string,test:string,blueprint:string) { + blueprintPath(session: string, test: string, blueprint: string) { return this.pathTemplates.blueprintPathTemplate.render({ session: session, test: test, @@ -654,7 +807,8 @@ export class SequenceServiceClient { * @returns {string} A string representing the session. */ matchSessionFromBlueprintName(blueprintName: string) { - return this.pathTemplates.blueprintPathTemplate.match(blueprintName).session; + return this.pathTemplates.blueprintPathTemplate.match(blueprintName) + .session; } /** @@ -676,7 +830,8 @@ export class SequenceServiceClient { * @returns {string} A string representing the blueprint. */ matchBlueprintFromBlueprintName(blueprintName: string) { - return this.pathTemplates.blueprintPathTemplate.match(blueprintName).blueprint; + return this.pathTemplates.blueprintPathTemplate.match(blueprintName) + .blueprint; } /** @@ -685,7 +840,7 @@ export class SequenceServiceClient { * @param {string} room * @returns {string} Resource name string. */ - roomPath(room:string) { + roomPath(room: string) { return this.pathTemplates.roomPathTemplate.render({ room: room, }); @@ -709,7 +864,7 @@ export class SequenceServiceClient { * @param {string} blurb * @returns {string} Resource name string. */ - roomBlurbPath(room:string,blurb:string) { + roomBlurbPath(room: string, blurb: string) { return this.pathTemplates.roomBlurbPathTemplate.render({ room: room, blurb: blurb, @@ -746,7 +901,11 @@ export class SequenceServiceClient { * @param {string} blurb * @returns {string} Resource name string. */ - roomBlurbsLegacyRoomBlurbPath(room:string,legacyRoom:string,blurb:string) { + roomBlurbsLegacyRoomBlurbPath( + room: string, + legacyRoom: string, + blurb: string, + ) { return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.render({ room: room, legacy_room: legacyRoom, @@ -761,8 +920,12 @@ export class SequenceServiceClient { * A fully-qualified path representing room_blurbs_legacy_room_blurb resource. * @returns {string} A string representing the room. */ - matchRoomFromRoomBlurbsLegacyRoomBlurbName(roomBlurbsLegacyRoomBlurbName: string) { - return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match(roomBlurbsLegacyRoomBlurbName).room; + matchRoomFromRoomBlurbsLegacyRoomBlurbName( + roomBlurbsLegacyRoomBlurbName: string, + ) { + return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match( + roomBlurbsLegacyRoomBlurbName, + ).room; } /** @@ -772,8 +935,12 @@ export class SequenceServiceClient { * A fully-qualified path representing room_blurbs_legacy_room_blurb resource. * @returns {string} A string representing the legacy_room. */ - matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName(roomBlurbsLegacyRoomBlurbName: string) { - return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match(roomBlurbsLegacyRoomBlurbName).legacy_room; + matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName( + roomBlurbsLegacyRoomBlurbName: string, + ) { + return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match( + roomBlurbsLegacyRoomBlurbName, + ).legacy_room; } /** @@ -783,8 +950,12 @@ export class SequenceServiceClient { * A fully-qualified path representing room_blurbs_legacy_room_blurb resource. * @returns {string} A string representing the blurb. */ - matchBlurbFromRoomBlurbsLegacyRoomBlurbName(roomBlurbsLegacyRoomBlurbName: string) { - return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match(roomBlurbsLegacyRoomBlurbName).blurb; + matchBlurbFromRoomBlurbsLegacyRoomBlurbName( + roomBlurbsLegacyRoomBlurbName: string, + ) { + return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match( + roomBlurbsLegacyRoomBlurbName, + ).blurb; } /** @@ -793,7 +964,7 @@ export class SequenceServiceClient { * @param {string} sequence * @returns {string} Resource name string. */ - sequencePath(sequence:string) { + sequencePath(sequence: string) { return this.pathTemplates.sequencePathTemplate.render({ sequence: sequence, }); @@ -816,7 +987,7 @@ export class SequenceServiceClient { * @param {string} sequence * @returns {string} Resource name string. */ - sequenceReportPath(sequence:string) { + sequenceReportPath(sequence: string) { return this.pathTemplates.sequenceReportPathTemplate.render({ sequence: sequence, }); @@ -830,7 +1001,9 @@ export class SequenceServiceClient { * @returns {string} A string representing the sequence. */ matchSequenceFromSequenceReportName(sequenceReportName: string) { - return this.pathTemplates.sequenceReportPathTemplate.match(sequenceReportName).sequence; + return this.pathTemplates.sequenceReportPathTemplate.match( + sequenceReportName, + ).sequence; } /** @@ -839,7 +1012,7 @@ export class SequenceServiceClient { * @param {string} session * @returns {string} Resource name string. */ - sessionPath(session:string) { + sessionPath(session: string) { return this.pathTemplates.sessionPathTemplate.render({ session: session, }); @@ -863,7 +1036,7 @@ export class SequenceServiceClient { * @param {string} test * @returns {string} Resource name string. */ - testPath(session:string,test:string) { + testPath(session: string, test: string) { return this.pathTemplates.testPathTemplate.render({ session: session, test: test, @@ -898,7 +1071,7 @@ export class SequenceServiceClient { * @param {string} user * @returns {string} Resource name string. */ - userPath(user:string) { + userPath(user: string) { return this.pathTemplates.userPathTemplate.render({ user: user, }); @@ -922,7 +1095,7 @@ export class SequenceServiceClient { * @param {string} blurb * @returns {string} Resource name string. */ - userProfileBlurbPath(user:string,blurb:string) { + userProfileBlurbPath(user: string, blurb: string) { return this.pathTemplates.userProfileBlurbPathTemplate.render({ user: user, blurb: blurb, @@ -937,7 +1110,9 @@ export class SequenceServiceClient { * @returns {string} A string representing the user. */ matchUserFromUserProfileBlurbName(userProfileBlurbName: string) { - return this.pathTemplates.userProfileBlurbPathTemplate.match(userProfileBlurbName).user; + return this.pathTemplates.userProfileBlurbPathTemplate.match( + userProfileBlurbName, + ).user; } /** @@ -948,7 +1123,9 @@ export class SequenceServiceClient { * @returns {string} A string representing the blurb. */ matchBlurbFromUserProfileBlurbName(userProfileBlurbName: string) { - return this.pathTemplates.userProfileBlurbPathTemplate.match(userProfileBlurbName).blurb; + return this.pathTemplates.userProfileBlurbPathTemplate.match( + userProfileBlurbName, + ).blurb; } /** @@ -959,12 +1136,18 @@ export class SequenceServiceClient { * @param {string} blurb * @returns {string} Resource name string. */ - userProfileBlurbsLegacyUserBlurbPath(user:string,legacyUser:string,blurb:string) { - return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.render({ - user: user, - legacy_user: legacyUser, - blurb: blurb, - }); + userProfileBlurbsLegacyUserBlurbPath( + user: string, + legacyUser: string, + blurb: string, + ) { + return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.render( + { + user: user, + legacy_user: legacyUser, + blurb: blurb, + }, + ); } /** @@ -974,8 +1157,12 @@ export class SequenceServiceClient { * A fully-qualified path representing user_profile_blurbs_legacy_user_blurb resource. * @returns {string} A string representing the user. */ - matchUserFromUserProfileBlurbsLegacyUserBlurbName(userProfileBlurbsLegacyUserBlurbName: string) { - return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match(userProfileBlurbsLegacyUserBlurbName).user; + matchUserFromUserProfileBlurbsLegacyUserBlurbName( + userProfileBlurbsLegacyUserBlurbName: string, + ) { + return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match( + userProfileBlurbsLegacyUserBlurbName, + ).user; } /** @@ -985,8 +1172,12 @@ export class SequenceServiceClient { * A fully-qualified path representing user_profile_blurbs_legacy_user_blurb resource. * @returns {string} A string representing the legacy_user. */ - matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName(userProfileBlurbsLegacyUserBlurbName: string) { - return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match(userProfileBlurbsLegacyUserBlurbName).legacy_user; + matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName( + userProfileBlurbsLegacyUserBlurbName: string, + ) { + return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match( + userProfileBlurbsLegacyUserBlurbName, + ).legacy_user; } /** @@ -996,8 +1187,12 @@ export class SequenceServiceClient { * A fully-qualified path representing user_profile_blurbs_legacy_user_blurb resource. * @returns {string} A string representing the blurb. */ - matchBlurbFromUserProfileBlurbsLegacyUserBlurbName(userProfileBlurbsLegacyUserBlurbName: string) { - return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match(userProfileBlurbsLegacyUserBlurbName).blurb; + matchBlurbFromUserProfileBlurbsLegacyUserBlurbName( + userProfileBlurbsLegacyUserBlurbName: string, + ) { + return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match( + userProfileBlurbsLegacyUserBlurbName, + ).blurb; } /** @@ -1008,7 +1203,7 @@ export class SequenceServiceClient { */ close(): Promise { if (this.sequenceServiceStub && !this._terminated) { - return this.sequenceServiceStub.then(stub => { + return this.sequenceServiceStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -1016,4 +1211,4 @@ export class SequenceServiceClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/core/generator/gapic-generator-typescript/baselines/disable-packing-test/src/v1beta1/testing_client.ts.baseline b/core/generator/gapic-generator-typescript/baselines/disable-packing-test/src/v1beta1/testing_client.ts.baseline index fdb68229da8a..d657fb401c29 100644 --- a/core/generator/gapic-generator-typescript/baselines/disable-packing-test/src/v1beta1/testing_client.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/disable-packing-test/src/v1beta1/testing_client.ts.baseline @@ -18,11 +18,18 @@ /* global window */ import type * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions, PaginationCallback, GaxCall} from 'google-gax'; -import {Transform} from 'stream'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + PaginationCallback, + GaxCall, +} from 'google-gax'; +import { Transform } from 'stream'; import * as protos from '../../protos/protos'; import jsonProtos = require('../../protos/protos.json'); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; /** * Client JSON configuration object, loaded from @@ -45,7 +52,7 @@ export class TestingClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('showcase'); @@ -58,9 +65,9 @@ export class TestingClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; - testingStub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; + testingStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of TestingClient. @@ -101,21 +108,42 @@ export class TestingClient { * const client = new TestingClient({fallback: true}, gax); * ``` */ - constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { // Ensure that options include all the required fields. const staticMembers = this.constructor as typeof TestingClient; - if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { - throw new Error('Please set either universe_domain or universeDomain, but not both.'); + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); } - const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; - this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; this._servicePath = 'localhost'; - const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; - const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. if (servicePath !== this._servicePath && !('scopes' in opts)) { @@ -137,7 +165,7 @@ export class TestingClient { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; @@ -151,10 +179,7 @@ export class TestingClient { } // Determine the client header string. - const clientHeader = [ - `gax/${this._gaxModule.version}`, - `gapic/${version}`, - ]; + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/${process.versions.node}`); } else { @@ -176,54 +201,60 @@ export class TestingClient { // Create useful helper objects for these. this.pathTemplates = { blueprintPathTemplate: new this._gaxModule.PathTemplate( - 'sessions/{session}/tests/{test}/blueprints/{blueprint}' - ), - roomPathTemplate: new this._gaxModule.PathTemplate( - 'rooms/{room}' + 'sessions/{session}/tests/{test}/blueprints/{blueprint}', ), + roomPathTemplate: new this._gaxModule.PathTemplate('rooms/{room}'), roomBlurbPathTemplate: new this._gaxModule.PathTemplate( - 'rooms/{room}/blurbs/{blurb}' + 'rooms/{room}/blurbs/{blurb}', ), roomBlurbsLegacyRoomBlurbPathTemplate: new this._gaxModule.PathTemplate( - 'rooms/{room}/blurbs/legacy/{legacy_room}.{blurb}' + 'rooms/{room}/blurbs/legacy/{legacy_room}.{blurb}', ), sequencePathTemplate: new this._gaxModule.PathTemplate( - 'sequences/{sequence}' + 'sequences/{sequence}', ), sequenceReportPathTemplate: new this._gaxModule.PathTemplate( - 'sequences/{sequence}/sequenceReport' + 'sequences/{sequence}/sequenceReport', ), sessionPathTemplate: new this._gaxModule.PathTemplate( - 'sessions/{session}' + 'sessions/{session}', ), testPathTemplate: new this._gaxModule.PathTemplate( - 'sessions/{session}/tests/{test}' - ), - userPathTemplate: new this._gaxModule.PathTemplate( - 'users/{user}' + 'sessions/{session}/tests/{test}', ), + userPathTemplate: new this._gaxModule.PathTemplate('users/{user}'), userProfileBlurbPathTemplate: new this._gaxModule.PathTemplate( - 'users/{user}/profile/blurbs/{blurb}' - ), - userProfileBlurbsLegacyUserBlurbPathTemplate: new this._gaxModule.PathTemplate( - 'users/{user}/profile/blurbs/legacy/{legacy_user}~{blurb}' + 'users/{user}/profile/blurbs/{blurb}', ), + userProfileBlurbsLegacyUserBlurbPathTemplate: + new this._gaxModule.PathTemplate( + 'users/{user}/profile/blurbs/legacy/{legacy_user}~{blurb}', + ), }; // Some of the methods on this service return "paged" results, // (e.g. 50 results at a time, with tokens to get subsequent // pages). Denote the keys used for pagination and results. this.descriptors.page = { - listSessions: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'sessions'), - listTests: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'tests') + listSessions: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'sessions', + ), + listTests: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'tests', + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.showcase.v1beta1.Testing', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.showcase.v1beta1.Testing', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + { 'x-goog-api-client': clientHeader.join(' ') }, + ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -254,37 +285,49 @@ export class TestingClient { // Put together the "service stub" for // google.showcase.v1beta1.Testing. this.testingStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.showcase.v1beta1.Testing') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.showcase.v1beta1.Testing', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.showcase.v1beta1.Testing, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts, + this._providedCustomServicePath, + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const testingStubMethods = - ['createSession', 'getSession', 'listSessions', 'deleteSession', 'reportSession', 'listTests', 'deleteTest', 'verifyTest']; + const testingStubMethods = [ + 'createSession', + 'getSession', + 'listSessions', + 'deleteSession', + 'reportSession', + 'listTests', + 'deleteTest', + 'verifyTest', + ]; for (const methodName of testingStubMethods) { const callPromise = this.testingStub.then( - stub => (...args: Array<{}>) => { - if (this._terminated) { - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error|null|undefined) => () => { + (stub) => + (...args: Array<{}>) => { + if (this._terminated) { + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { throw err; - }); + }, + ); - const descriptor = - this.descriptors.page[methodName] || - undefined; + const descriptor = this.descriptors.page[methodName] || undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -299,8 +342,14 @@ export class TestingClient { * @returns {string} The DNS address for this service. */ static get servicePath() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'localhost'; } @@ -311,8 +360,14 @@ export class TestingClient { * @returns {string} The DNS address for this service. */ static get apiEndpoint() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'localhost'; } @@ -352,8 +407,9 @@ export class TestingClient { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId(callback?: Callback): - Promise|void { + getProjectId( + callback?: Callback, + ): Promise | void { if (callback) { this.auth.getProjectId(callback); return; @@ -364,656 +420,869 @@ export class TestingClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Creates a new testing session. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.showcase.v1beta1.Session} request.session - * The session to be created. - * Sessions are immutable once they are created (although they can - * be deleted). - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.Session|Session}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/testing.create_session.js - * region_tag:localhost_v1beta1_generated_Testing_CreateSession_async - */ + /** + * Creates a new testing session. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.showcase.v1beta1.Session} request.session + * The session to be created. + * Sessions are immutable once they are created (although they can + * be deleted). + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.Session|Session}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/testing.create_session.js + * region_tag:localhost_v1beta1_generated_Testing_CreateSession_async + */ createSession( - request?: protos.google.showcase.v1beta1.ICreateSessionRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.ISession, - protos.google.showcase.v1beta1.ICreateSessionRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.ICreateSessionRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.ISession, + protos.google.showcase.v1beta1.ICreateSessionRequest | undefined, + {} | undefined, + ] + >; createSession( - request: protos.google.showcase.v1beta1.ICreateSessionRequest, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.ISession, - protos.google.showcase.v1beta1.ICreateSessionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.ICreateSessionRequest, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.ISession, + protos.google.showcase.v1beta1.ICreateSessionRequest | null | undefined, + {} | null | undefined + >, + ): void; createSession( - request: protos.google.showcase.v1beta1.ICreateSessionRequest, - callback: Callback< - protos.google.showcase.v1beta1.ISession, - protos.google.showcase.v1beta1.ICreateSessionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.ICreateSessionRequest, + callback: Callback< + protos.google.showcase.v1beta1.ISession, + protos.google.showcase.v1beta1.ICreateSessionRequest | null | undefined, + {} | null | undefined + >, + ): void; createSession( - request?: protos.google.showcase.v1beta1.ICreateSessionRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.showcase.v1beta1.ISession, - protos.google.showcase.v1beta1.ICreateSessionRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.showcase.v1beta1.ICreateSessionRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.ISession, - protos.google.showcase.v1beta1.ICreateSessionRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.ISession, - protos.google.showcase.v1beta1.ICreateSessionRequest|undefined, {}|undefined - ]>|void { + | protos.google.showcase.v1beta1.ICreateSessionRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.ISession, + protos.google.showcase.v1beta1.ICreateSessionRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.ISession, + protos.google.showcase.v1beta1.ICreateSessionRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('createSession request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.ISession, - protos.google.showcase.v1beta1.ICreateSessionRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.ISession, + | protos.google.showcase.v1beta1.ICreateSessionRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createSession response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.createSession(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.ISession, - protos.google.showcase.v1beta1.ICreateSessionRequest|undefined, - {}|undefined - ]) => { - this._log.info('createSession response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createSession(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.ISession, + protos.google.showcase.v1beta1.ICreateSessionRequest | undefined, + {} | undefined, + ]) => { + this._log.info('createSession response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Gets a testing session. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * The session to be retrieved. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.Session|Session}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/testing.get_session.js - * region_tag:localhost_v1beta1_generated_Testing_GetSession_async - */ + /** + * Gets a testing session. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * The session to be retrieved. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.Session|Session}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/testing.get_session.js + * region_tag:localhost_v1beta1_generated_Testing_GetSession_async + */ getSession( - request?: protos.google.showcase.v1beta1.IGetSessionRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.ISession, - protos.google.showcase.v1beta1.IGetSessionRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IGetSessionRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.ISession, + protos.google.showcase.v1beta1.IGetSessionRequest | undefined, + {} | undefined, + ] + >; getSession( - request: protos.google.showcase.v1beta1.IGetSessionRequest, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.ISession, - protos.google.showcase.v1beta1.IGetSessionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IGetSessionRequest, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.ISession, + protos.google.showcase.v1beta1.IGetSessionRequest | null | undefined, + {} | null | undefined + >, + ): void; getSession( - request: protos.google.showcase.v1beta1.IGetSessionRequest, - callback: Callback< - protos.google.showcase.v1beta1.ISession, - protos.google.showcase.v1beta1.IGetSessionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IGetSessionRequest, + callback: Callback< + protos.google.showcase.v1beta1.ISession, + protos.google.showcase.v1beta1.IGetSessionRequest | null | undefined, + {} | null | undefined + >, + ): void; getSession( - request?: protos.google.showcase.v1beta1.IGetSessionRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.showcase.v1beta1.ISession, - protos.google.showcase.v1beta1.IGetSessionRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.showcase.v1beta1.IGetSessionRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.ISession, - protos.google.showcase.v1beta1.IGetSessionRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.ISession, - protos.google.showcase.v1beta1.IGetSessionRequest|undefined, {}|undefined - ]>|void { + protos.google.showcase.v1beta1.IGetSessionRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.ISession, + protos.google.showcase.v1beta1.IGetSessionRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.ISession, + protos.google.showcase.v1beta1.IGetSessionRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getSession request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.ISession, - protos.google.showcase.v1beta1.IGetSessionRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.ISession, + protos.google.showcase.v1beta1.IGetSessionRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getSession response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getSession(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.ISession, - protos.google.showcase.v1beta1.IGetSessionRequest|undefined, - {}|undefined - ]) => { - this._log.info('getSession response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getSession(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.ISession, + protos.google.showcase.v1beta1.IGetSessionRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getSession response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Delete a test session. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * The session to be deleted. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/testing.delete_session.js - * region_tag:localhost_v1beta1_generated_Testing_DeleteSession_async - */ + /** + * Delete a test session. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * The session to be deleted. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/testing.delete_session.js + * region_tag:localhost_v1beta1_generated_Testing_DeleteSession_async + */ deleteSession( - request?: protos.google.showcase.v1beta1.IDeleteSessionRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteSessionRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IDeleteSessionRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteSessionRequest | undefined, + {} | undefined, + ] + >; deleteSession( - request: protos.google.showcase.v1beta1.IDeleteSessionRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteSessionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IDeleteSessionRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteSessionRequest | null | undefined, + {} | null | undefined + >, + ): void; deleteSession( - request: protos.google.showcase.v1beta1.IDeleteSessionRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteSessionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IDeleteSessionRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteSessionRequest | null | undefined, + {} | null | undefined + >, + ): void; deleteSession( - request?: protos.google.showcase.v1beta1.IDeleteSessionRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.showcase.v1beta1.IDeleteSessionRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteSessionRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteSessionRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteSessionRequest|undefined, {}|undefined - ]>|void { + | protos.google.showcase.v1beta1.IDeleteSessionRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteSessionRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteSessionRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('deleteSession request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteSessionRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.showcase.v1beta1.IDeleteSessionRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteSession response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.deleteSession(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteSessionRequest|undefined, - {}|undefined - ]) => { - this._log.info('deleteSession response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteSession(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteSessionRequest | undefined, + {} | undefined, + ]) => { + this._log.info('deleteSession response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Report on the status of a session. - * This generates a report detailing which tests have been completed, - * and an overall rollup. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * The session to be reported on. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.ReportSessionResponse|ReportSessionResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/testing.report_session.js - * region_tag:localhost_v1beta1_generated_Testing_ReportSession_async - */ + /** + * Report on the status of a session. + * This generates a report detailing which tests have been completed, + * and an overall rollup. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * The session to be reported on. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.ReportSessionResponse|ReportSessionResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/testing.report_session.js + * region_tag:localhost_v1beta1_generated_Testing_ReportSession_async + */ reportSession( - request?: protos.google.showcase.v1beta1.IReportSessionRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IReportSessionResponse, - protos.google.showcase.v1beta1.IReportSessionRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IReportSessionRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IReportSessionResponse, + protos.google.showcase.v1beta1.IReportSessionRequest | undefined, + {} | undefined, + ] + >; reportSession( - request: protos.google.showcase.v1beta1.IReportSessionRequest, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.IReportSessionResponse, - protos.google.showcase.v1beta1.IReportSessionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IReportSessionRequest, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.IReportSessionResponse, + protos.google.showcase.v1beta1.IReportSessionRequest | null | undefined, + {} | null | undefined + >, + ): void; reportSession( - request: protos.google.showcase.v1beta1.IReportSessionRequest, - callback: Callback< - protos.google.showcase.v1beta1.IReportSessionResponse, - protos.google.showcase.v1beta1.IReportSessionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IReportSessionRequest, + callback: Callback< + protos.google.showcase.v1beta1.IReportSessionResponse, + protos.google.showcase.v1beta1.IReportSessionRequest | null | undefined, + {} | null | undefined + >, + ): void; reportSession( - request?: protos.google.showcase.v1beta1.IReportSessionRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.showcase.v1beta1.IReportSessionResponse, - protos.google.showcase.v1beta1.IReportSessionRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.showcase.v1beta1.IReportSessionRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.IReportSessionResponse, - protos.google.showcase.v1beta1.IReportSessionRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.IReportSessionResponse, - protos.google.showcase.v1beta1.IReportSessionRequest|undefined, {}|undefined - ]>|void { + | protos.google.showcase.v1beta1.IReportSessionRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.IReportSessionResponse, + protos.google.showcase.v1beta1.IReportSessionRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IReportSessionResponse, + protos.google.showcase.v1beta1.IReportSessionRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('reportSession request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.IReportSessionResponse, - protos.google.showcase.v1beta1.IReportSessionRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.IReportSessionResponse, + | protos.google.showcase.v1beta1.IReportSessionRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('reportSession response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.reportSession(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.IReportSessionResponse, - protos.google.showcase.v1beta1.IReportSessionRequest|undefined, - {}|undefined - ]) => { - this._log.info('reportSession response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .reportSession(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.IReportSessionResponse, + protos.google.showcase.v1beta1.IReportSessionRequest | undefined, + {} | undefined, + ]) => { + this._log.info('reportSession response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Explicitly decline to implement a test. - * - * This removes the test from subsequent `ListTests` calls, and - * attempting to do the test will error. - * - * This method will error if attempting to delete a required test. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * The test to be deleted. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/testing.delete_test.js - * region_tag:localhost_v1beta1_generated_Testing_DeleteTest_async - */ + /** + * Explicitly decline to implement a test. + * + * This removes the test from subsequent `ListTests` calls, and + * attempting to do the test will error. + * + * This method will error if attempting to delete a required test. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * The test to be deleted. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/testing.delete_test.js + * region_tag:localhost_v1beta1_generated_Testing_DeleteTest_async + */ deleteTest( - request?: protos.google.showcase.v1beta1.IDeleteTestRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteTestRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IDeleteTestRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteTestRequest | undefined, + {} | undefined, + ] + >; deleteTest( - request: protos.google.showcase.v1beta1.IDeleteTestRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteTestRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IDeleteTestRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteTestRequest | null | undefined, + {} | null | undefined + >, + ): void; deleteTest( - request: protos.google.showcase.v1beta1.IDeleteTestRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteTestRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IDeleteTestRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteTestRequest | null | undefined, + {} | null | undefined + >, + ): void; deleteTest( - request?: protos.google.showcase.v1beta1.IDeleteTestRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.showcase.v1beta1.IDeleteTestRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteTestRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteTestRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteTestRequest|undefined, {}|undefined - ]>|void { + protos.google.showcase.v1beta1.IDeleteTestRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteTestRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteTestRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('deleteTest request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteTestRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteTestRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteTest response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.deleteTest(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteTestRequest|undefined, - {}|undefined - ]) => { - this._log.info('deleteTest response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteTest(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteTestRequest | undefined, + {} | undefined, + ]) => { + this._log.info('deleteTest response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Register a response to a test. - * - * In cases where a test involves registering a final answer at the - * end of the test, this method provides the means to do so. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * The test to have an answer registered to it. - * @param {Buffer} request.answer - * The answer from the test. - * @param {Buffer[]} request.answers - * The answers from the test if multiple are to be checked - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.VerifyTestResponse|VerifyTestResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/testing.verify_test.js - * region_tag:localhost_v1beta1_generated_Testing_VerifyTest_async - */ + /** + * Register a response to a test. + * + * In cases where a test involves registering a final answer at the + * end of the test, this method provides the means to do so. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * The test to have an answer registered to it. + * @param {Buffer} request.answer + * The answer from the test. + * @param {Buffer[]} request.answers + * The answers from the test if multiple are to be checked + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.VerifyTestResponse|VerifyTestResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/testing.verify_test.js + * region_tag:localhost_v1beta1_generated_Testing_VerifyTest_async + */ verifyTest( - request?: protos.google.showcase.v1beta1.IVerifyTestRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IVerifyTestResponse, - protos.google.showcase.v1beta1.IVerifyTestRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IVerifyTestRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IVerifyTestResponse, + protos.google.showcase.v1beta1.IVerifyTestRequest | undefined, + {} | undefined, + ] + >; verifyTest( - request: protos.google.showcase.v1beta1.IVerifyTestRequest, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.IVerifyTestResponse, - protos.google.showcase.v1beta1.IVerifyTestRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IVerifyTestRequest, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.IVerifyTestResponse, + protos.google.showcase.v1beta1.IVerifyTestRequest | null | undefined, + {} | null | undefined + >, + ): void; verifyTest( - request: protos.google.showcase.v1beta1.IVerifyTestRequest, - callback: Callback< - protos.google.showcase.v1beta1.IVerifyTestResponse, - protos.google.showcase.v1beta1.IVerifyTestRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IVerifyTestRequest, + callback: Callback< + protos.google.showcase.v1beta1.IVerifyTestResponse, + protos.google.showcase.v1beta1.IVerifyTestRequest | null | undefined, + {} | null | undefined + >, + ): void; verifyTest( - request?: protos.google.showcase.v1beta1.IVerifyTestRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.showcase.v1beta1.IVerifyTestRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.IVerifyTestResponse, - protos.google.showcase.v1beta1.IVerifyTestRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.showcase.v1beta1.IVerifyTestResponse, - protos.google.showcase.v1beta1.IVerifyTestRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.IVerifyTestResponse, - protos.google.showcase.v1beta1.IVerifyTestRequest|undefined, {}|undefined - ]>|void { + protos.google.showcase.v1beta1.IVerifyTestRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.IVerifyTestResponse, + protos.google.showcase.v1beta1.IVerifyTestRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IVerifyTestResponse, + protos.google.showcase.v1beta1.IVerifyTestRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('verifyTest request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.IVerifyTestResponse, - protos.google.showcase.v1beta1.IVerifyTestRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.IVerifyTestResponse, + protos.google.showcase.v1beta1.IVerifyTestRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('verifyTest response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.verifyTest(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.IVerifyTestResponse, - protos.google.showcase.v1beta1.IVerifyTestRequest|undefined, - {}|undefined - ]) => { - this._log.info('verifyTest response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .verifyTest(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.IVerifyTestResponse, + protos.google.showcase.v1beta1.IVerifyTestRequest | undefined, + {} | undefined, + ]) => { + this._log.info('verifyTest response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } - /** - * Lists the current test sessions. - * - * @param {Object} request - * The request object that will be sent. - * @param {number} request.pageSize - * The maximum number of sessions to return per page. - * @param {string} request.pageToken - * The page token, for retrieving subsequent pages. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.showcase.v1beta1.Session|Session}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `listSessionsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Lists the current test sessions. + * + * @param {Object} request + * The request object that will be sent. + * @param {number} request.pageSize + * The maximum number of sessions to return per page. + * @param {string} request.pageToken + * The page token, for retrieving subsequent pages. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.showcase.v1beta1.Session|Session}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listSessionsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listSessions( - request?: protos.google.showcase.v1beta1.IListSessionsRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.ISession[], - protos.google.showcase.v1beta1.IListSessionsRequest|null, - protos.google.showcase.v1beta1.IListSessionsResponse - ]>; + request?: protos.google.showcase.v1beta1.IListSessionsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.ISession[], + protos.google.showcase.v1beta1.IListSessionsRequest | null, + protos.google.showcase.v1beta1.IListSessionsResponse, + ] + >; listSessions( - request: protos.google.showcase.v1beta1.IListSessionsRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.showcase.v1beta1.IListSessionsRequest, - protos.google.showcase.v1beta1.IListSessionsResponse|null|undefined, - protos.google.showcase.v1beta1.ISession>): void; + request: protos.google.showcase.v1beta1.IListSessionsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.showcase.v1beta1.IListSessionsRequest, + protos.google.showcase.v1beta1.IListSessionsResponse | null | undefined, + protos.google.showcase.v1beta1.ISession + >, + ): void; listSessions( - request: protos.google.showcase.v1beta1.IListSessionsRequest, - callback: PaginationCallback< - protos.google.showcase.v1beta1.IListSessionsRequest, - protos.google.showcase.v1beta1.IListSessionsResponse|null|undefined, - protos.google.showcase.v1beta1.ISession>): void; + request: protos.google.showcase.v1beta1.IListSessionsRequest, + callback: PaginationCallback< + protos.google.showcase.v1beta1.IListSessionsRequest, + protos.google.showcase.v1beta1.IListSessionsResponse | null | undefined, + protos.google.showcase.v1beta1.ISession + >, + ): void; listSessions( - request?: protos.google.showcase.v1beta1.IListSessionsRequest, - optionsOrCallback?: CallOptions|PaginationCallback< + request?: protos.google.showcase.v1beta1.IListSessionsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.showcase.v1beta1.IListSessionsRequest, - protos.google.showcase.v1beta1.IListSessionsResponse|null|undefined, - protos.google.showcase.v1beta1.ISession>, - callback?: PaginationCallback< - protos.google.showcase.v1beta1.IListSessionsRequest, - protos.google.showcase.v1beta1.IListSessionsResponse|null|undefined, - protos.google.showcase.v1beta1.ISession>): - Promise<[ - protos.google.showcase.v1beta1.ISession[], - protos.google.showcase.v1beta1.IListSessionsRequest|null, - protos.google.showcase.v1beta1.IListSessionsResponse - ]>|void { + | protos.google.showcase.v1beta1.IListSessionsResponse + | null + | undefined, + protos.google.showcase.v1beta1.ISession + >, + callback?: PaginationCallback< + protos.google.showcase.v1beta1.IListSessionsRequest, + protos.google.showcase.v1beta1.IListSessionsResponse | null | undefined, + protos.google.showcase.v1beta1.ISession + >, + ): Promise< + [ + protos.google.showcase.v1beta1.ISession[], + protos.google.showcase.v1beta1.IListSessionsRequest | null, + protos.google.showcase.v1beta1.IListSessionsResponse, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.showcase.v1beta1.IListSessionsRequest, - protos.google.showcase.v1beta1.IListSessionsResponse|null|undefined, - protos.google.showcase.v1beta1.ISession>|undefined = callback + this.initialize().catch((err) => { + throw err; + }); + const wrappedCallback: + | PaginationCallback< + protos.google.showcase.v1beta1.IListSessionsRequest, + | protos.google.showcase.v1beta1.IListSessionsResponse + | null + | undefined, + protos.google.showcase.v1beta1.ISession + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listSessions values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -1022,175 +1291,196 @@ export class TestingClient { this._log.info('listSessions request %j', request); return this.innerApiCalls .listSessions(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.showcase.v1beta1.ISession[], - protos.google.showcase.v1beta1.IListSessionsRequest|null, - protos.google.showcase.v1beta1.IListSessionsResponse - ]) => { - this._log.info('listSessions values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.showcase.v1beta1.ISession[], + protos.google.showcase.v1beta1.IListSessionsRequest | null, + protos.google.showcase.v1beta1.IListSessionsResponse, + ]) => { + this._log.info('listSessions values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listSessions`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {number} request.pageSize - * The maximum number of sessions to return per page. - * @param {string} request.pageToken - * The page token, for retrieving subsequent pages. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.showcase.v1beta1.Session|Session} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `listSessionsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `listSessions`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {number} request.pageSize + * The maximum number of sessions to return per page. + * @param {string} request.pageToken + * The page token, for retrieving subsequent pages. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.showcase.v1beta1.Session|Session} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listSessionsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listSessionsStream( - request?: protos.google.showcase.v1beta1.IListSessionsRequest, - options?: CallOptions): - Transform{ + request?: protos.google.showcase.v1beta1.IListSessionsRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; const defaultCallSettings = this._defaults['listSessions']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listSessions stream %j', request); return this.descriptors.page.listSessions.createStream( this.innerApiCalls.listSessions as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listSessions`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {number} request.pageSize - * The maximum number of sessions to return per page. - * @param {string} request.pageToken - * The page token, for retrieving subsequent pages. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.showcase.v1beta1.Session|Session}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/testing.list_sessions.js - * region_tag:localhost_v1beta1_generated_Testing_ListSessions_async - */ + /** + * Equivalent to `listSessions`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {number} request.pageSize + * The maximum number of sessions to return per page. + * @param {string} request.pageToken + * The page token, for retrieving subsequent pages. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.showcase.v1beta1.Session|Session}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/testing.list_sessions.js + * region_tag:localhost_v1beta1_generated_Testing_ListSessions_async + */ listSessionsAsync( - request?: protos.google.showcase.v1beta1.IListSessionsRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.showcase.v1beta1.IListSessionsRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; const defaultCallSettings = this._defaults['listSessions']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listSessions iterate %j', request); return this.descriptors.page.listSessions.asyncIterate( this.innerApiCalls['listSessions'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } - /** - * List the tests of a sessesion. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * The session. - * @param {number} request.pageSize - * The maximum number of tests to return per page. - * @param {string} request.pageToken - * The page token, for retrieving subsequent pages. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.showcase.v1beta1.Test|Test}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `listTestsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * List the tests of a sessesion. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * The session. + * @param {number} request.pageSize + * The maximum number of tests to return per page. + * @param {string} request.pageToken + * The page token, for retrieving subsequent pages. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.showcase.v1beta1.Test|Test}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listTestsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listTests( - request?: protos.google.showcase.v1beta1.IListTestsRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.ITest[], - protos.google.showcase.v1beta1.IListTestsRequest|null, - protos.google.showcase.v1beta1.IListTestsResponse - ]>; + request?: protos.google.showcase.v1beta1.IListTestsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.ITest[], + protos.google.showcase.v1beta1.IListTestsRequest | null, + protos.google.showcase.v1beta1.IListTestsResponse, + ] + >; listTests( - request: protos.google.showcase.v1beta1.IListTestsRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.showcase.v1beta1.IListTestsRequest, - protos.google.showcase.v1beta1.IListTestsResponse|null|undefined, - protos.google.showcase.v1beta1.ITest>): void; + request: protos.google.showcase.v1beta1.IListTestsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.showcase.v1beta1.IListTestsRequest, + protos.google.showcase.v1beta1.IListTestsResponse | null | undefined, + protos.google.showcase.v1beta1.ITest + >, + ): void; listTests( - request: protos.google.showcase.v1beta1.IListTestsRequest, - callback: PaginationCallback< - protos.google.showcase.v1beta1.IListTestsRequest, - protos.google.showcase.v1beta1.IListTestsResponse|null|undefined, - protos.google.showcase.v1beta1.ITest>): void; + request: protos.google.showcase.v1beta1.IListTestsRequest, + callback: PaginationCallback< + protos.google.showcase.v1beta1.IListTestsRequest, + protos.google.showcase.v1beta1.IListTestsResponse | null | undefined, + protos.google.showcase.v1beta1.ITest + >, + ): void; listTests( - request?: protos.google.showcase.v1beta1.IListTestsRequest, - optionsOrCallback?: CallOptions|PaginationCallback< - protos.google.showcase.v1beta1.IListTestsRequest, - protos.google.showcase.v1beta1.IListTestsResponse|null|undefined, - protos.google.showcase.v1beta1.ITest>, - callback?: PaginationCallback< + request?: protos.google.showcase.v1beta1.IListTestsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.showcase.v1beta1.IListTestsRequest, - protos.google.showcase.v1beta1.IListTestsResponse|null|undefined, - protos.google.showcase.v1beta1.ITest>): - Promise<[ - protos.google.showcase.v1beta1.ITest[], - protos.google.showcase.v1beta1.IListTestsRequest|null, - protos.google.showcase.v1beta1.IListTestsResponse - ]>|void { + protos.google.showcase.v1beta1.IListTestsResponse | null | undefined, + protos.google.showcase.v1beta1.ITest + >, + callback?: PaginationCallback< + protos.google.showcase.v1beta1.IListTestsRequest, + protos.google.showcase.v1beta1.IListTestsResponse | null | undefined, + protos.google.showcase.v1beta1.ITest + >, + ): Promise< + [ + protos.google.showcase.v1beta1.ITest[], + protos.google.showcase.v1beta1.IListTestsRequest | null, + protos.google.showcase.v1beta1.IListTestsResponse, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.showcase.v1beta1.IListTestsRequest, - protos.google.showcase.v1beta1.IListTestsResponse|null|undefined, - protos.google.showcase.v1beta1.ITest>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.showcase.v1beta1.IListTestsRequest, + protos.google.showcase.v1beta1.IListTestsResponse | null | undefined, + protos.google.showcase.v1beta1.ITest + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listTests values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -1199,106 +1489,110 @@ export class TestingClient { this._log.info('listTests request %j', request); return this.innerApiCalls .listTests(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.showcase.v1beta1.ITest[], - protos.google.showcase.v1beta1.IListTestsRequest|null, - protos.google.showcase.v1beta1.IListTestsResponse - ]) => { - this._log.info('listTests values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.showcase.v1beta1.ITest[], + protos.google.showcase.v1beta1.IListTestsRequest | null, + protos.google.showcase.v1beta1.IListTestsResponse, + ]) => { + this._log.info('listTests values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listTests`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * The session. - * @param {number} request.pageSize - * The maximum number of tests to return per page. - * @param {string} request.pageToken - * The page token, for retrieving subsequent pages. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.showcase.v1beta1.Test|Test} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `listTestsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `listTests`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * The session. + * @param {number} request.pageSize + * The maximum number of tests to return per page. + * @param {string} request.pageToken + * The page token, for retrieving subsequent pages. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.showcase.v1beta1.Test|Test} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listTestsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listTestsStream( - request?: protos.google.showcase.v1beta1.IListTestsRequest, - options?: CallOptions): - Transform{ + request?: protos.google.showcase.v1beta1.IListTestsRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); const defaultCallSettings = this._defaults['listTests']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listTests stream %j', request); return this.descriptors.page.listTests.createStream( this.innerApiCalls.listTests as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listTests`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * The session. - * @param {number} request.pageSize - * The maximum number of tests to return per page. - * @param {string} request.pageToken - * The page token, for retrieving subsequent pages. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.showcase.v1beta1.Test|Test}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/testing.list_tests.js - * region_tag:localhost_v1beta1_generated_Testing_ListTests_async - */ + /** + * Equivalent to `listTests`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * The session. + * @param {number} request.pageSize + * The maximum number of tests to return per page. + * @param {string} request.pageToken + * The page token, for retrieving subsequent pages. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.showcase.v1beta1.Test|Test}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/testing.list_tests.js + * region_tag:localhost_v1beta1_generated_Testing_ListTests_async + */ listTestsAsync( - request?: protos.google.showcase.v1beta1.IListTestsRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.showcase.v1beta1.IListTestsRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); const defaultCallSettings = this._defaults['listTests']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listTests iterate %j', request); return this.descriptors.page.listTests.asyncIterate( this.innerApiCalls['listTests'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } // -------------------- @@ -1313,7 +1607,7 @@ export class TestingClient { * @param {string} blueprint * @returns {string} Resource name string. */ - blueprintPath(session:string,test:string,blueprint:string) { + blueprintPath(session: string, test: string, blueprint: string) { return this.pathTemplates.blueprintPathTemplate.render({ session: session, test: test, @@ -1329,7 +1623,8 @@ export class TestingClient { * @returns {string} A string representing the session. */ matchSessionFromBlueprintName(blueprintName: string) { - return this.pathTemplates.blueprintPathTemplate.match(blueprintName).session; + return this.pathTemplates.blueprintPathTemplate.match(blueprintName) + .session; } /** @@ -1351,7 +1646,8 @@ export class TestingClient { * @returns {string} A string representing the blueprint. */ matchBlueprintFromBlueprintName(blueprintName: string) { - return this.pathTemplates.blueprintPathTemplate.match(blueprintName).blueprint; + return this.pathTemplates.blueprintPathTemplate.match(blueprintName) + .blueprint; } /** @@ -1360,7 +1656,7 @@ export class TestingClient { * @param {string} room * @returns {string} Resource name string. */ - roomPath(room:string) { + roomPath(room: string) { return this.pathTemplates.roomPathTemplate.render({ room: room, }); @@ -1384,7 +1680,7 @@ export class TestingClient { * @param {string} blurb * @returns {string} Resource name string. */ - roomBlurbPath(room:string,blurb:string) { + roomBlurbPath(room: string, blurb: string) { return this.pathTemplates.roomBlurbPathTemplate.render({ room: room, blurb: blurb, @@ -1421,7 +1717,11 @@ export class TestingClient { * @param {string} blurb * @returns {string} Resource name string. */ - roomBlurbsLegacyRoomBlurbPath(room:string,legacyRoom:string,blurb:string) { + roomBlurbsLegacyRoomBlurbPath( + room: string, + legacyRoom: string, + blurb: string, + ) { return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.render({ room: room, legacy_room: legacyRoom, @@ -1436,8 +1736,12 @@ export class TestingClient { * A fully-qualified path representing room_blurbs_legacy_room_blurb resource. * @returns {string} A string representing the room. */ - matchRoomFromRoomBlurbsLegacyRoomBlurbName(roomBlurbsLegacyRoomBlurbName: string) { - return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match(roomBlurbsLegacyRoomBlurbName).room; + matchRoomFromRoomBlurbsLegacyRoomBlurbName( + roomBlurbsLegacyRoomBlurbName: string, + ) { + return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match( + roomBlurbsLegacyRoomBlurbName, + ).room; } /** @@ -1447,8 +1751,12 @@ export class TestingClient { * A fully-qualified path representing room_blurbs_legacy_room_blurb resource. * @returns {string} A string representing the legacy_room. */ - matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName(roomBlurbsLegacyRoomBlurbName: string) { - return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match(roomBlurbsLegacyRoomBlurbName).legacy_room; + matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName( + roomBlurbsLegacyRoomBlurbName: string, + ) { + return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match( + roomBlurbsLegacyRoomBlurbName, + ).legacy_room; } /** @@ -1458,8 +1766,12 @@ export class TestingClient { * A fully-qualified path representing room_blurbs_legacy_room_blurb resource. * @returns {string} A string representing the blurb. */ - matchBlurbFromRoomBlurbsLegacyRoomBlurbName(roomBlurbsLegacyRoomBlurbName: string) { - return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match(roomBlurbsLegacyRoomBlurbName).blurb; + matchBlurbFromRoomBlurbsLegacyRoomBlurbName( + roomBlurbsLegacyRoomBlurbName: string, + ) { + return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match( + roomBlurbsLegacyRoomBlurbName, + ).blurb; } /** @@ -1468,7 +1780,7 @@ export class TestingClient { * @param {string} sequence * @returns {string} Resource name string. */ - sequencePath(sequence:string) { + sequencePath(sequence: string) { return this.pathTemplates.sequencePathTemplate.render({ sequence: sequence, }); @@ -1491,7 +1803,7 @@ export class TestingClient { * @param {string} sequence * @returns {string} Resource name string. */ - sequenceReportPath(sequence:string) { + sequenceReportPath(sequence: string) { return this.pathTemplates.sequenceReportPathTemplate.render({ sequence: sequence, }); @@ -1505,7 +1817,9 @@ export class TestingClient { * @returns {string} A string representing the sequence. */ matchSequenceFromSequenceReportName(sequenceReportName: string) { - return this.pathTemplates.sequenceReportPathTemplate.match(sequenceReportName).sequence; + return this.pathTemplates.sequenceReportPathTemplate.match( + sequenceReportName, + ).sequence; } /** @@ -1514,7 +1828,7 @@ export class TestingClient { * @param {string} session * @returns {string} Resource name string. */ - sessionPath(session:string) { + sessionPath(session: string) { return this.pathTemplates.sessionPathTemplate.render({ session: session, }); @@ -1538,7 +1852,7 @@ export class TestingClient { * @param {string} test * @returns {string} Resource name string. */ - testPath(session:string,test:string) { + testPath(session: string, test: string) { return this.pathTemplates.testPathTemplate.render({ session: session, test: test, @@ -1573,7 +1887,7 @@ export class TestingClient { * @param {string} user * @returns {string} Resource name string. */ - userPath(user:string) { + userPath(user: string) { return this.pathTemplates.userPathTemplate.render({ user: user, }); @@ -1597,7 +1911,7 @@ export class TestingClient { * @param {string} blurb * @returns {string} Resource name string. */ - userProfileBlurbPath(user:string,blurb:string) { + userProfileBlurbPath(user: string, blurb: string) { return this.pathTemplates.userProfileBlurbPathTemplate.render({ user: user, blurb: blurb, @@ -1612,7 +1926,9 @@ export class TestingClient { * @returns {string} A string representing the user. */ matchUserFromUserProfileBlurbName(userProfileBlurbName: string) { - return this.pathTemplates.userProfileBlurbPathTemplate.match(userProfileBlurbName).user; + return this.pathTemplates.userProfileBlurbPathTemplate.match( + userProfileBlurbName, + ).user; } /** @@ -1623,7 +1939,9 @@ export class TestingClient { * @returns {string} A string representing the blurb. */ matchBlurbFromUserProfileBlurbName(userProfileBlurbName: string) { - return this.pathTemplates.userProfileBlurbPathTemplate.match(userProfileBlurbName).blurb; + return this.pathTemplates.userProfileBlurbPathTemplate.match( + userProfileBlurbName, + ).blurb; } /** @@ -1634,12 +1952,18 @@ export class TestingClient { * @param {string} blurb * @returns {string} Resource name string. */ - userProfileBlurbsLegacyUserBlurbPath(user:string,legacyUser:string,blurb:string) { - return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.render({ - user: user, - legacy_user: legacyUser, - blurb: blurb, - }); + userProfileBlurbsLegacyUserBlurbPath( + user: string, + legacyUser: string, + blurb: string, + ) { + return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.render( + { + user: user, + legacy_user: legacyUser, + blurb: blurb, + }, + ); } /** @@ -1649,8 +1973,12 @@ export class TestingClient { * A fully-qualified path representing user_profile_blurbs_legacy_user_blurb resource. * @returns {string} A string representing the user. */ - matchUserFromUserProfileBlurbsLegacyUserBlurbName(userProfileBlurbsLegacyUserBlurbName: string) { - return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match(userProfileBlurbsLegacyUserBlurbName).user; + matchUserFromUserProfileBlurbsLegacyUserBlurbName( + userProfileBlurbsLegacyUserBlurbName: string, + ) { + return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match( + userProfileBlurbsLegacyUserBlurbName, + ).user; } /** @@ -1660,8 +1988,12 @@ export class TestingClient { * A fully-qualified path representing user_profile_blurbs_legacy_user_blurb resource. * @returns {string} A string representing the legacy_user. */ - matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName(userProfileBlurbsLegacyUserBlurbName: string) { - return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match(userProfileBlurbsLegacyUserBlurbName).legacy_user; + matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName( + userProfileBlurbsLegacyUserBlurbName: string, + ) { + return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match( + userProfileBlurbsLegacyUserBlurbName, + ).legacy_user; } /** @@ -1671,8 +2003,12 @@ export class TestingClient { * A fully-qualified path representing user_profile_blurbs_legacy_user_blurb resource. * @returns {string} A string representing the blurb. */ - matchBlurbFromUserProfileBlurbsLegacyUserBlurbName(userProfileBlurbsLegacyUserBlurbName: string) { - return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match(userProfileBlurbsLegacyUserBlurbName).blurb; + matchBlurbFromUserProfileBlurbsLegacyUserBlurbName( + userProfileBlurbsLegacyUserBlurbName: string, + ) { + return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match( + userProfileBlurbsLegacyUserBlurbName, + ).blurb; } /** @@ -1683,7 +2019,7 @@ export class TestingClient { */ close(): Promise { if (this.testingStub && !this._terminated) { - return this.testingStub.then(stub => { + return this.testingStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -1691,4 +2027,4 @@ export class TestingClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/core/generator/gapic-generator-typescript/baselines/disable-packing-test/test/gapic_compliance_v1beta1.ts.baseline b/core/generator/gapic-generator-typescript/baselines/disable-packing-test/test/gapic_compliance_v1beta1.ts.baseline index 33c4db06519a..e70a93a0bc75 100644 --- a/core/generator/gapic-generator-typescript/baselines/disable-packing-test/test/gapic_compliance_v1beta1.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/disable-packing-test/test/gapic_compliance_v1beta1.ts.baseline @@ -19,1541 +19,1948 @@ import * as protos from '../protos/protos'; import * as assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as complianceModule from '../src'; -import {protobuf} from 'google-gax'; +import { protobuf } from 'google-gax'; // Dynamically loaded proto JSON is needed to get the type information // to fill in default values for request objects -const root = protobuf.Root.fromJSON(require('../protos/protos.json')).resolveAll(); +const root = protobuf.Root.fromJSON( + require('../protos/protos.json'), +).resolveAll(); // eslint-disable-next-line @typescript-eslint/no-unused-vars function getTypeDefaultValue(typeName: string, fields: string[]) { - let type = root.lookupType(typeName) as protobuf.Type; - for (const field of fields.slice(0, -1)) { - type = type.fields[field]?.resolvedType as protobuf.Type; - } - return type.fields[fields[fields.length - 1]]?.defaultValue; + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type.fields[field]?.resolvedType as protobuf.Type; + } + return type.fields[fields[fields.length - 1]]?.defaultValue; } function generateSampleMessage(instance: T) { - const filledObject = (instance.constructor as typeof protobuf.Message) - .toObject(instance as protobuf.Message, {defaults: true}); - return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, { defaults: true }); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; } function stubSimpleCall(response?: ResponseType, error?: Error) { - return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); } -function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { - return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +function stubSimpleCallWithCallback( + response?: ResponseType, + error?: Error, +) { + return error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); } describe('v1beta1.ComplianceClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new complianceModule.v1beta1.ComplianceClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'localhost'); - }); - - it('has universeDomain', () => { - const client = new complianceModule.v1beta1.ComplianceClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); - - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - it('throws DeprecationWarning if static servicePath is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const servicePath = complianceModule.v1beta1.ComplianceClient.servicePath; - assert.strictEqual(servicePath, 'localhost'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = complianceModule.v1beta1.ComplianceClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'localhost'); - assert(stub.called); - stub.restore(); - }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { new complianceModule.v1beta1.ComplianceClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); - - it('has port', () => { - const port = complianceModule.v1beta1.ComplianceClient.port; - assert(port); - assert(typeof port === 'number'); - }); - - it('should create a client with no option', () => { - const client = new complianceModule.v1beta1.ComplianceClient(); - assert(client); - }); - - it('should create a client with gRPC fallback', () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - fallback: true, - }); - assert(client); - }); - - it('has initialize method and supports deferred initialization', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.complianceStub, undefined); - await client.initialize(); - assert(client.complianceStub); - }); - - it('has close method for the initialized client', done => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.complianceStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); - - it('has close method for the non-initialized client', done => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.complianceStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); - - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); - }); - - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId((err?: Error|null, projectId?: string|null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } - }); - }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new complianceModule.v1beta1.ComplianceClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'localhost'); }); - describe('repeatDataBody', () => { - it('invokes repeatDataBody without error', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatResponse() - ); - client.innerApiCalls.repeatDataBody = stubSimpleCall(expectedResponse); - const [response] = await client.repeatDataBody(request); - assert.deepStrictEqual(response, expectedResponse); - }); - - it('invokes repeatDataBody without error using callback', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatResponse() - ); - client.innerApiCalls.repeatDataBody = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.repeatDataBody( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IRepeatResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); + it('has universeDomain', () => { + const client = new complianceModule.v1beta1.ComplianceClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - it('invokes repeatDataBody with error', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.repeatDataBody = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.repeatDataBody(request), expectedError); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = + complianceModule.v1beta1.ComplianceClient.servicePath; + assert.strictEqual(servicePath, 'localhost'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + complianceModule.v1beta1.ComplianceClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'localhost'); + assert(stub.called); + stub.restore(); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new complianceModule.v1beta1.ComplianceClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); + }); - it('invokes repeatDataBody with closed client', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.repeatDataBody(request), expectedError); - }); + it('has port', () => { + const port = complianceModule.v1beta1.ComplianceClient.port; + assert(port); + assert(typeof port === 'number'); }); - describe('repeatDataBodyInfo', () => { - it('invokes repeatDataBodyInfo without error', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatResponse() - ); - client.innerApiCalls.repeatDataBodyInfo = stubSimpleCall(expectedResponse); - const [response] = await client.repeatDataBodyInfo(request); - assert.deepStrictEqual(response, expectedResponse); - }); + it('should create a client with no option', () => { + const client = new complianceModule.v1beta1.ComplianceClient(); + assert(client); + }); - it('invokes repeatDataBodyInfo without error using callback', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatResponse() - ); - client.innerApiCalls.repeatDataBodyInfo = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.repeatDataBodyInfo( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IRepeatResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); + it('should create a client with gRPC fallback', () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + fallback: true, + }); + assert(client); + }); - it('invokes repeatDataBodyInfo with error', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.repeatDataBodyInfo = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.repeatDataBodyInfo(request), expectedError); - }); + it('has initialize method and supports deferred initialization', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.complianceStub, undefined); + await client.initialize(); + assert(client.complianceStub); + }); - it('invokes repeatDataBodyInfo with closed client', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.repeatDataBodyInfo(request), expectedError); + it('has close method for the initialized client', (done) => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.complianceStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); }); - describe('repeatDataQuery', () => { - it('invokes repeatDataQuery without error', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatResponse() - ); - client.innerApiCalls.repeatDataQuery = stubSimpleCall(expectedResponse); - const [response] = await client.repeatDataQuery(request); - assert.deepStrictEqual(response, expectedResponse); + it('has close method for the non-initialized client', (done) => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.complianceStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes repeatDataQuery without error using callback', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatResponse() - ); - client.innerApiCalls.repeatDataQuery = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.repeatDataQuery( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IRepeatResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + }); - it('invokes repeatDataQuery with error', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.repeatDataQuery = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.repeatDataQuery(request), expectedError); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + }); + + describe('repeatDataBody', () => { + it('invokes repeatDataBody without error', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatResponse(), + ); + client.innerApiCalls.repeatDataBody = stubSimpleCall(expectedResponse); + const [response] = await client.repeatDataBody(request); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes repeatDataQuery with closed client', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.repeatDataQuery(request), expectedError); - }); + it('invokes repeatDataBody without error using callback', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatResponse(), + ); + client.innerApiCalls.repeatDataBody = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.repeatDataBody( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IRepeatResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); }); - describe('repeatDataSimplePath', () => { - it('invokes repeatDataSimplePath without error', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - request.info ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fString']); - request.info.fString = defaultValue1; - request.info ??= {}; - const defaultValue2 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fInt32']); - request.info.fInt32 = defaultValue2; - request.info ??= {}; - const defaultValue3 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fDouble']); - request.info.fDouble = defaultValue3; - request.info ??= {}; - const defaultValue4 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fBool']); - request.info.fBool = defaultValue4; - request.info ??= {}; - const defaultValue5 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fKingdom']); - request.info.fKingdom = defaultValue5; - const expectedHeaderRequestParams = `info.f_string=${defaultValue1 ?? '' }&info.f_int32=${defaultValue2 ?? '' }&info.f_double=${defaultValue3 ?? '' }&info.f_bool=${defaultValue4 ?? '' }&info.f_kingdom=${defaultValue5 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatResponse() - ); - client.innerApiCalls.repeatDataSimplePath = stubSimpleCall(expectedResponse); - const [response] = await client.repeatDataSimplePath(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.repeatDataSimplePath as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.repeatDataSimplePath as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes repeatDataBody with error', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.repeatDataBody = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.repeatDataBody(request), expectedError); + }); - it('invokes repeatDataSimplePath without error using callback', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - request.info ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fString']); - request.info.fString = defaultValue1; - request.info ??= {}; - const defaultValue2 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fInt32']); - request.info.fInt32 = defaultValue2; - request.info ??= {}; - const defaultValue3 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fDouble']); - request.info.fDouble = defaultValue3; - request.info ??= {}; - const defaultValue4 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fBool']); - request.info.fBool = defaultValue4; - request.info ??= {}; - const defaultValue5 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fKingdom']); - request.info.fKingdom = defaultValue5; - const expectedHeaderRequestParams = `info.f_string=${defaultValue1 ?? '' }&info.f_int32=${defaultValue2 ?? '' }&info.f_double=${defaultValue3 ?? '' }&info.f_bool=${defaultValue4 ?? '' }&info.f_kingdom=${defaultValue5 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatResponse() - ); - client.innerApiCalls.repeatDataSimplePath = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.repeatDataSimplePath( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IRepeatResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.repeatDataSimplePath as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.repeatDataSimplePath as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes repeatDataBody with closed client', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.repeatDataBody(request), expectedError); + }); + }); + + describe('repeatDataBodyInfo', () => { + it('invokes repeatDataBodyInfo without error', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatResponse(), + ); + client.innerApiCalls.repeatDataBodyInfo = + stubSimpleCall(expectedResponse); + const [response] = await client.repeatDataBodyInfo(request); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes repeatDataSimplePath with error', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - request.info ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fString']); - request.info.fString = defaultValue1; - request.info ??= {}; - const defaultValue2 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fInt32']); - request.info.fInt32 = defaultValue2; - request.info ??= {}; - const defaultValue3 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fDouble']); - request.info.fDouble = defaultValue3; - request.info ??= {}; - const defaultValue4 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fBool']); - request.info.fBool = defaultValue4; - request.info ??= {}; - const defaultValue5 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fKingdom']); - request.info.fKingdom = defaultValue5; - const expectedHeaderRequestParams = `info.f_string=${defaultValue1 ?? '' }&info.f_int32=${defaultValue2 ?? '' }&info.f_double=${defaultValue3 ?? '' }&info.f_bool=${defaultValue4 ?? '' }&info.f_kingdom=${defaultValue5 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.repeatDataSimplePath = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.repeatDataSimplePath(request), expectedError); - const actualRequest = (client.innerApiCalls.repeatDataSimplePath as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.repeatDataSimplePath as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes repeatDataBodyInfo without error using callback', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatResponse(), + ); + client.innerApiCalls.repeatDataBodyInfo = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.repeatDataBodyInfo( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IRepeatResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes repeatDataSimplePath with closed client', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - request.info ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fString']); - request.info.fString = defaultValue1; - request.info ??= {}; - const defaultValue2 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fInt32']); - request.info.fInt32 = defaultValue2; - request.info ??= {}; - const defaultValue3 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fDouble']); - request.info.fDouble = defaultValue3; - request.info ??= {}; - const defaultValue4 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fBool']); - request.info.fBool = defaultValue4; - request.info ??= {}; - const defaultValue5 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fKingdom']); - request.info.fKingdom = defaultValue5; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.repeatDataSimplePath(request), expectedError); - }); + it('invokes repeatDataBodyInfo with error', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.repeatDataBodyInfo = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.repeatDataBodyInfo(request), expectedError); }); - describe('repeatDataPathResource', () => { - it('invokes repeatDataPathResource without error', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - request.info ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fString']); - request.info.fString = defaultValue1; - request.info ??= {}; - request.info.fChild ??= {}; - const defaultValue2 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fChild', 'fString']); - request.info.fChild.fString = defaultValue2; - request.info ??= {}; - const defaultValue3 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fBool']); - request.info.fBool = defaultValue3; - const expectedHeaderRequestParams = `info.f_string=${defaultValue1 ?? '' }&info.f_child.f_string=${defaultValue2 ?? '' }&info.f_bool=${defaultValue3 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatResponse() - ); - client.innerApiCalls.repeatDataPathResource = stubSimpleCall(expectedResponse); - const [response] = await client.repeatDataPathResource(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.repeatDataPathResource as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.repeatDataPathResource as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes repeatDataBodyInfo with closed client', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.repeatDataBodyInfo(request), expectedError); + }); + }); + + describe('repeatDataQuery', () => { + it('invokes repeatDataQuery without error', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatResponse(), + ); + client.innerApiCalls.repeatDataQuery = stubSimpleCall(expectedResponse); + const [response] = await client.repeatDataQuery(request); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes repeatDataPathResource without error using callback', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - request.info ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fString']); - request.info.fString = defaultValue1; - request.info ??= {}; - request.info.fChild ??= {}; - const defaultValue2 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fChild', 'fString']); - request.info.fChild.fString = defaultValue2; - request.info ??= {}; - const defaultValue3 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fBool']); - request.info.fBool = defaultValue3; - const expectedHeaderRequestParams = `info.f_string=${defaultValue1 ?? '' }&info.f_child.f_string=${defaultValue2 ?? '' }&info.f_bool=${defaultValue3 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatResponse() - ); - client.innerApiCalls.repeatDataPathResource = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.repeatDataPathResource( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IRepeatResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.repeatDataPathResource as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.repeatDataPathResource as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes repeatDataQuery without error using callback', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatResponse(), + ); + client.innerApiCalls.repeatDataQuery = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.repeatDataQuery( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IRepeatResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes repeatDataPathResource with error', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - request.info ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fString']); - request.info.fString = defaultValue1; - request.info ??= {}; - request.info.fChild ??= {}; - const defaultValue2 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fChild', 'fString']); - request.info.fChild.fString = defaultValue2; - request.info ??= {}; - const defaultValue3 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fBool']); - request.info.fBool = defaultValue3; - const expectedHeaderRequestParams = `info.f_string=${defaultValue1 ?? '' }&info.f_child.f_string=${defaultValue2 ?? '' }&info.f_bool=${defaultValue3 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.repeatDataPathResource = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.repeatDataPathResource(request), expectedError); - const actualRequest = (client.innerApiCalls.repeatDataPathResource as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.repeatDataPathResource as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes repeatDataQuery with error', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.repeatDataQuery = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.repeatDataQuery(request), expectedError); + }); - it('invokes repeatDataPathResource with closed client', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - request.info ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fString']); - request.info.fString = defaultValue1; - request.info ??= {}; - request.info.fChild ??= {}; - const defaultValue2 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fChild', 'fString']); - request.info.fChild.fString = defaultValue2; - request.info ??= {}; - const defaultValue3 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fBool']); - request.info.fBool = defaultValue3; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.repeatDataPathResource(request), expectedError); - }); + it('invokes repeatDataQuery with closed client', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.repeatDataQuery(request), expectedError); + }); + }); + + describe('repeatDataSimplePath', () => { + it('invokes repeatDataSimplePath without error', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + request.info ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fString'], + ); + request.info.fString = defaultValue1; + request.info ??= {}; + const defaultValue2 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fInt32'], + ); + request.info.fInt32 = defaultValue2; + request.info ??= {}; + const defaultValue3 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fDouble'], + ); + request.info.fDouble = defaultValue3; + request.info ??= {}; + const defaultValue4 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fBool'], + ); + request.info.fBool = defaultValue4; + request.info ??= {}; + const defaultValue5 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fKingdom'], + ); + request.info.fKingdom = defaultValue5; + const expectedHeaderRequestParams = `info.f_string=${defaultValue1 ?? ''}&info.f_int32=${defaultValue2 ?? ''}&info.f_double=${defaultValue3 ?? ''}&info.f_bool=${defaultValue4 ?? ''}&info.f_kingdom=${defaultValue5 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatResponse(), + ); + client.innerApiCalls.repeatDataSimplePath = + stubSimpleCall(expectedResponse); + const [response] = await client.repeatDataSimplePath(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.repeatDataSimplePath as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.repeatDataSimplePath as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('repeatDataPathTrailingResource', () => { - it('invokes repeatDataPathTrailingResource without error', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - request.info ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fString']); - request.info.fString = defaultValue1; - request.info ??= {}; - request.info.fChild ??= {}; - const defaultValue2 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fChild', 'fString']); - request.info.fChild.fString = defaultValue2; - const expectedHeaderRequestParams = `info.f_string=${defaultValue1 ?? '' }&info.f_child.f_string=${defaultValue2 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatResponse() - ); - client.innerApiCalls.repeatDataPathTrailingResource = stubSimpleCall(expectedResponse); - const [response] = await client.repeatDataPathTrailingResource(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.repeatDataPathTrailingResource as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.repeatDataPathTrailingResource as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes repeatDataSimplePath without error using callback', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + request.info ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fString'], + ); + request.info.fString = defaultValue1; + request.info ??= {}; + const defaultValue2 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fInt32'], + ); + request.info.fInt32 = defaultValue2; + request.info ??= {}; + const defaultValue3 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fDouble'], + ); + request.info.fDouble = defaultValue3; + request.info ??= {}; + const defaultValue4 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fBool'], + ); + request.info.fBool = defaultValue4; + request.info ??= {}; + const defaultValue5 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fKingdom'], + ); + request.info.fKingdom = defaultValue5; + const expectedHeaderRequestParams = `info.f_string=${defaultValue1 ?? ''}&info.f_int32=${defaultValue2 ?? ''}&info.f_double=${defaultValue3 ?? ''}&info.f_bool=${defaultValue4 ?? ''}&info.f_kingdom=${defaultValue5 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatResponse(), + ); + client.innerApiCalls.repeatDataSimplePath = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.repeatDataSimplePath( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IRepeatResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.repeatDataSimplePath as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.repeatDataSimplePath as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes repeatDataPathTrailingResource without error using callback', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - request.info ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fString']); - request.info.fString = defaultValue1; - request.info ??= {}; - request.info.fChild ??= {}; - const defaultValue2 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fChild', 'fString']); - request.info.fChild.fString = defaultValue2; - const expectedHeaderRequestParams = `info.f_string=${defaultValue1 ?? '' }&info.f_child.f_string=${defaultValue2 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatResponse() - ); - client.innerApiCalls.repeatDataPathTrailingResource = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.repeatDataPathTrailingResource( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IRepeatResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.repeatDataPathTrailingResource as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.repeatDataPathTrailingResource as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes repeatDataSimplePath with error', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + request.info ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fString'], + ); + request.info.fString = defaultValue1; + request.info ??= {}; + const defaultValue2 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fInt32'], + ); + request.info.fInt32 = defaultValue2; + request.info ??= {}; + const defaultValue3 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fDouble'], + ); + request.info.fDouble = defaultValue3; + request.info ??= {}; + const defaultValue4 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fBool'], + ); + request.info.fBool = defaultValue4; + request.info ??= {}; + const defaultValue5 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fKingdom'], + ); + request.info.fKingdom = defaultValue5; + const expectedHeaderRequestParams = `info.f_string=${defaultValue1 ?? ''}&info.f_int32=${defaultValue2 ?? ''}&info.f_double=${defaultValue3 ?? ''}&info.f_bool=${defaultValue4 ?? ''}&info.f_kingdom=${defaultValue5 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.repeatDataSimplePath = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.repeatDataSimplePath(request), expectedError); + const actualRequest = ( + client.innerApiCalls.repeatDataSimplePath as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.repeatDataSimplePath as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes repeatDataPathTrailingResource with error', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - request.info ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fString']); - request.info.fString = defaultValue1; - request.info ??= {}; - request.info.fChild ??= {}; - const defaultValue2 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fChild', 'fString']); - request.info.fChild.fString = defaultValue2; - const expectedHeaderRequestParams = `info.f_string=${defaultValue1 ?? '' }&info.f_child.f_string=${defaultValue2 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.repeatDataPathTrailingResource = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.repeatDataPathTrailingResource(request), expectedError); - const actualRequest = (client.innerApiCalls.repeatDataPathTrailingResource as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.repeatDataPathTrailingResource as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes repeatDataSimplePath with closed client', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + request.info ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fString'], + ); + request.info.fString = defaultValue1; + request.info ??= {}; + const defaultValue2 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fInt32'], + ); + request.info.fInt32 = defaultValue2; + request.info ??= {}; + const defaultValue3 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fDouble'], + ); + request.info.fDouble = defaultValue3; + request.info ??= {}; + const defaultValue4 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fBool'], + ); + request.info.fBool = defaultValue4; + request.info ??= {}; + const defaultValue5 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fKingdom'], + ); + request.info.fKingdom = defaultValue5; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.repeatDataSimplePath(request), expectedError); + }); + }); + + describe('repeatDataPathResource', () => { + it('invokes repeatDataPathResource without error', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + request.info ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fString'], + ); + request.info.fString = defaultValue1; + request.info ??= {}; + request.info.fChild ??= {}; + const defaultValue2 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fChild', 'fString'], + ); + request.info.fChild.fString = defaultValue2; + request.info ??= {}; + const defaultValue3 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fBool'], + ); + request.info.fBool = defaultValue3; + const expectedHeaderRequestParams = `info.f_string=${defaultValue1 ?? ''}&info.f_child.f_string=${defaultValue2 ?? ''}&info.f_bool=${defaultValue3 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatResponse(), + ); + client.innerApiCalls.repeatDataPathResource = + stubSimpleCall(expectedResponse); + const [response] = await client.repeatDataPathResource(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.repeatDataPathResource as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.repeatDataPathResource as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes repeatDataPathTrailingResource with closed client', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - request.info ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fString']); - request.info.fString = defaultValue1; - request.info ??= {}; - request.info.fChild ??= {}; - const defaultValue2 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fChild', 'fString']); - request.info.fChild.fString = defaultValue2; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.repeatDataPathTrailingResource(request), expectedError); - }); + it('invokes repeatDataPathResource without error using callback', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + request.info ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fString'], + ); + request.info.fString = defaultValue1; + request.info ??= {}; + request.info.fChild ??= {}; + const defaultValue2 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fChild', 'fString'], + ); + request.info.fChild.fString = defaultValue2; + request.info ??= {}; + const defaultValue3 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fBool'], + ); + request.info.fBool = defaultValue3; + const expectedHeaderRequestParams = `info.f_string=${defaultValue1 ?? ''}&info.f_child.f_string=${defaultValue2 ?? ''}&info.f_bool=${defaultValue3 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatResponse(), + ); + client.innerApiCalls.repeatDataPathResource = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.repeatDataPathResource( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IRepeatResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.repeatDataPathResource as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.repeatDataPathResource as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('repeatDataBodyPut', () => { - it('invokes repeatDataBodyPut without error', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatResponse() - ); - client.innerApiCalls.repeatDataBodyPut = stubSimpleCall(expectedResponse); - const [response] = await client.repeatDataBodyPut(request); - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes repeatDataPathResource with error', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + request.info ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fString'], + ); + request.info.fString = defaultValue1; + request.info ??= {}; + request.info.fChild ??= {}; + const defaultValue2 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fChild', 'fString'], + ); + request.info.fChild.fString = defaultValue2; + request.info ??= {}; + const defaultValue3 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fBool'], + ); + request.info.fBool = defaultValue3; + const expectedHeaderRequestParams = `info.f_string=${defaultValue1 ?? ''}&info.f_child.f_string=${defaultValue2 ?? ''}&info.f_bool=${defaultValue3 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.repeatDataPathResource = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.repeatDataPathResource(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.repeatDataPathResource as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.repeatDataPathResource as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes repeatDataBodyPut without error using callback', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatResponse() - ); - client.innerApiCalls.repeatDataBodyPut = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.repeatDataBodyPut( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IRepeatResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes repeatDataPathResource with closed client', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + request.info ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fString'], + ); + request.info.fString = defaultValue1; + request.info ??= {}; + request.info.fChild ??= {}; + const defaultValue2 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fChild', 'fString'], + ); + request.info.fChild.fString = defaultValue2; + request.info ??= {}; + const defaultValue3 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fBool'], + ); + request.info.fBool = defaultValue3; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.repeatDataPathResource(request), + expectedError, + ); + }); + }); + + describe('repeatDataPathTrailingResource', () => { + it('invokes repeatDataPathTrailingResource without error', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + request.info ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fString'], + ); + request.info.fString = defaultValue1; + request.info ??= {}; + request.info.fChild ??= {}; + const defaultValue2 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fChild', 'fString'], + ); + request.info.fChild.fString = defaultValue2; + const expectedHeaderRequestParams = `info.f_string=${defaultValue1 ?? ''}&info.f_child.f_string=${defaultValue2 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatResponse(), + ); + client.innerApiCalls.repeatDataPathTrailingResource = + stubSimpleCall(expectedResponse); + const [response] = await client.repeatDataPathTrailingResource(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.repeatDataPathTrailingResource as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.repeatDataPathTrailingResource as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes repeatDataBodyPut with error', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.repeatDataBodyPut = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.repeatDataBodyPut(request), expectedError); - }); + it('invokes repeatDataPathTrailingResource without error using callback', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + request.info ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fString'], + ); + request.info.fString = defaultValue1; + request.info ??= {}; + request.info.fChild ??= {}; + const defaultValue2 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fChild', 'fString'], + ); + request.info.fChild.fString = defaultValue2; + const expectedHeaderRequestParams = `info.f_string=${defaultValue1 ?? ''}&info.f_child.f_string=${defaultValue2 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatResponse(), + ); + client.innerApiCalls.repeatDataPathTrailingResource = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.repeatDataPathTrailingResource( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IRepeatResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.repeatDataPathTrailingResource as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.repeatDataPathTrailingResource as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes repeatDataBodyPut with closed client', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.repeatDataBodyPut(request), expectedError); - }); + it('invokes repeatDataPathTrailingResource with error', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + request.info ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fString'], + ); + request.info.fString = defaultValue1; + request.info ??= {}; + request.info.fChild ??= {}; + const defaultValue2 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fChild', 'fString'], + ); + request.info.fChild.fString = defaultValue2; + const expectedHeaderRequestParams = `info.f_string=${defaultValue1 ?? ''}&info.f_child.f_string=${defaultValue2 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.repeatDataPathTrailingResource = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.repeatDataPathTrailingResource(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.repeatDataPathTrailingResource as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.repeatDataPathTrailingResource as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('repeatDataBodyPatch', () => { - it('invokes repeatDataBodyPatch without error', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatResponse() - ); - client.innerApiCalls.repeatDataBodyPatch = stubSimpleCall(expectedResponse); - const [response] = await client.repeatDataBodyPatch(request); - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes repeatDataPathTrailingResource with closed client', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + request.info ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fString'], + ); + request.info.fString = defaultValue1; + request.info ??= {}; + request.info.fChild ??= {}; + const defaultValue2 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fChild', 'fString'], + ); + request.info.fChild.fString = defaultValue2; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.repeatDataPathTrailingResource(request), + expectedError, + ); + }); + }); + + describe('repeatDataBodyPut', () => { + it('invokes repeatDataBodyPut without error', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatResponse(), + ); + client.innerApiCalls.repeatDataBodyPut = stubSimpleCall(expectedResponse); + const [response] = await client.repeatDataBodyPut(request); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes repeatDataBodyPatch without error using callback', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatResponse() - ); - client.innerApiCalls.repeatDataBodyPatch = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.repeatDataBodyPatch( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IRepeatResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes repeatDataBodyPut without error using callback', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatResponse(), + ); + client.innerApiCalls.repeatDataBodyPut = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.repeatDataBodyPut( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IRepeatResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes repeatDataBodyPatch with error', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.repeatDataBodyPatch = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.repeatDataBodyPatch(request), expectedError); - }); + it('invokes repeatDataBodyPut with error', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.repeatDataBodyPut = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.repeatDataBodyPut(request), expectedError); + }); - it('invokes repeatDataBodyPatch with closed client', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.repeatDataBodyPatch(request), expectedError); - }); + it('invokes repeatDataBodyPut with closed client', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.repeatDataBodyPut(request), expectedError); + }); + }); + + describe('repeatDataBodyPatch', () => { + it('invokes repeatDataBodyPatch without error', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatResponse(), + ); + client.innerApiCalls.repeatDataBodyPatch = + stubSimpleCall(expectedResponse); + const [response] = await client.repeatDataBodyPatch(request); + assert.deepStrictEqual(response, expectedResponse); }); - describe('getEnum', () => { - it('invokes getEnum without error', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.EnumRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.EnumResponse() - ); - client.innerApiCalls.getEnum = stubSimpleCall(expectedResponse); - const [response] = await client.getEnum(request); - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes repeatDataBodyPatch without error using callback', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatResponse(), + ); + client.innerApiCalls.repeatDataBodyPatch = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.repeatDataBodyPatch( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IRepeatResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes getEnum without error using callback', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.EnumRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.EnumResponse() - ); - client.innerApiCalls.getEnum = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getEnum( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IEnumResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes repeatDataBodyPatch with error', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.repeatDataBodyPatch = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.repeatDataBodyPatch(request), expectedError); + }); - it('invokes getEnum with error', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.EnumRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.getEnum = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getEnum(request), expectedError); - }); + it('invokes repeatDataBodyPatch with closed client', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.repeatDataBodyPatch(request), expectedError); + }); + }); + + describe('getEnum', () => { + it('invokes getEnum without error', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.EnumRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.EnumResponse(), + ); + client.innerApiCalls.getEnum = stubSimpleCall(expectedResponse); + const [response] = await client.getEnum(request); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes getEnum with closed client', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.EnumRequest() - ); - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getEnum(request), expectedError); - }); + it('invokes getEnum without error using callback', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.EnumRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.EnumResponse(), + ); + client.innerApiCalls.getEnum = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getEnum( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IEnumResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); }); - describe('verifyEnum', () => { - it('invokes verifyEnum without error', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.EnumResponse() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.EnumResponse() - ); - client.innerApiCalls.verifyEnum = stubSimpleCall(expectedResponse); - const [response] = await client.verifyEnum(request); - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes getEnum with error', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.EnumRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.getEnum = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.getEnum(request), expectedError); + }); - it('invokes verifyEnum without error using callback', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.EnumResponse() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.EnumResponse() - ); - client.innerApiCalls.verifyEnum = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.verifyEnum( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IEnumResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes getEnum with closed client', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.EnumRequest(), + ); + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getEnum(request), expectedError); + }); + }); + + describe('verifyEnum', () => { + it('invokes verifyEnum without error', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.EnumResponse(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.EnumResponse(), + ); + client.innerApiCalls.verifyEnum = stubSimpleCall(expectedResponse); + const [response] = await client.verifyEnum(request); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes verifyEnum with error', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.EnumResponse() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.verifyEnum = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.verifyEnum(request), expectedError); - }); + it('invokes verifyEnum without error using callback', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.EnumResponse(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.EnumResponse(), + ); + client.innerApiCalls.verifyEnum = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.verifyEnum( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IEnumResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes verifyEnum with closed client', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.EnumResponse() - ); - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.verifyEnum(request), expectedError); - }); + it('invokes verifyEnum with error', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.EnumResponse(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.verifyEnum = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.verifyEnum(request), expectedError); }); - describe('Path templates', () => { - - describe('blueprint', async () => { - const fakePath = "/rendered/path/blueprint"; - const expectedParameters = { - session: "sessionValue", - test: "testValue", - blueprint: "blueprintValue", - }; - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.blueprintPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.blueprintPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('blueprintPath', () => { - const result = client.blueprintPath("sessionValue", "testValue", "blueprintValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.blueprintPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchSessionFromBlueprintName', () => { - const result = client.matchSessionFromBlueprintName(fakePath); - assert.strictEqual(result, "sessionValue"); - assert((client.pathTemplates.blueprintPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchTestFromBlueprintName', () => { - const result = client.matchTestFromBlueprintName(fakePath); - assert.strictEqual(result, "testValue"); - assert((client.pathTemplates.blueprintPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBlueprintFromBlueprintName', () => { - const result = client.matchBlueprintFromBlueprintName(fakePath); - assert.strictEqual(result, "blueprintValue"); - assert((client.pathTemplates.blueprintPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('invokes verifyEnum with closed client', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.EnumResponse(), + ); + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.verifyEnum(request), expectedError); + }); + }); + + describe('Path templates', () => { + describe('blueprint', async () => { + const fakePath = '/rendered/path/blueprint'; + const expectedParameters = { + session: 'sessionValue', + test: 'testValue', + blueprint: 'blueprintValue', + }; + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.blueprintPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.blueprintPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('blueprintPath', () => { + const result = client.blueprintPath( + 'sessionValue', + 'testValue', + 'blueprintValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.blueprintPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchSessionFromBlueprintName', () => { + const result = client.matchSessionFromBlueprintName(fakePath); + assert.strictEqual(result, 'sessionValue'); + assert( + (client.pathTemplates.blueprintPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchTestFromBlueprintName', () => { + const result = client.matchTestFromBlueprintName(fakePath); + assert.strictEqual(result, 'testValue'); + assert( + (client.pathTemplates.blueprintPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBlueprintFromBlueprintName', () => { + const result = client.matchBlueprintFromBlueprintName(fakePath); + assert.strictEqual(result, 'blueprintValue'); + assert( + (client.pathTemplates.blueprintPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('room', async () => { - const fakePath = "/rendered/path/room"; - const expectedParameters = { - room: "roomValue", - }; - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.roomPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.roomPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('roomPath', () => { - const result = client.roomPath("roomValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.roomPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchRoomFromRoomName', () => { - const result = client.matchRoomFromRoomName(fakePath); - assert.strictEqual(result, "roomValue"); - assert((client.pathTemplates.roomPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('room', async () => { + const fakePath = '/rendered/path/room'; + const expectedParameters = { + room: 'roomValue', + }; + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.roomPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.roomPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('roomPath', () => { + const result = client.roomPath('roomValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.roomPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchRoomFromRoomName', () => { + const result = client.matchRoomFromRoomName(fakePath); + assert.strictEqual(result, 'roomValue'); + assert( + (client.pathTemplates.roomPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('roomBlurb', async () => { - const fakePath = "/rendered/path/roomBlurb"; - const expectedParameters = { - room: "roomValue", - blurb: "blurbValue", - }; - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.roomBlurbPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.roomBlurbPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('roomBlurbPath', () => { - const result = client.roomBlurbPath("roomValue", "blurbValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.roomBlurbPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchRoomFromRoomBlurbName', () => { - const result = client.matchRoomFromRoomBlurbName(fakePath); - assert.strictEqual(result, "roomValue"); - assert((client.pathTemplates.roomBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBlurbFromRoomBlurbName', () => { - const result = client.matchBlurbFromRoomBlurbName(fakePath); - assert.strictEqual(result, "blurbValue"); - assert((client.pathTemplates.roomBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('roomBlurb', async () => { + const fakePath = '/rendered/path/roomBlurb'; + const expectedParameters = { + room: 'roomValue', + blurb: 'blurbValue', + }; + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.roomBlurbPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.roomBlurbPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('roomBlurbPath', () => { + const result = client.roomBlurbPath('roomValue', 'blurbValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.roomBlurbPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchRoomFromRoomBlurbName', () => { + const result = client.matchRoomFromRoomBlurbName(fakePath); + assert.strictEqual(result, 'roomValue'); + assert( + (client.pathTemplates.roomBlurbPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBlurbFromRoomBlurbName', () => { + const result = client.matchBlurbFromRoomBlurbName(fakePath); + assert.strictEqual(result, 'blurbValue'); + assert( + (client.pathTemplates.roomBlurbPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('roomBlurbsLegacyRoomBlurb', async () => { - const fakePath = "/rendered/path/roomBlurbsLegacyRoomBlurb"; - const expectedParameters = { - room: "roomValue", - legacy_room: "legacyRoomValue", - blurb: "blurbValue", - }; - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('roomBlurbsLegacyRoomBlurbPath', () => { - const result = client.roomBlurbsLegacyRoomBlurbPath("roomValue", "legacyRoomValue", "blurbValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchRoomFromRoomBlurbsLegacyRoomBlurbName', () => { - const result = client.matchRoomFromRoomBlurbsLegacyRoomBlurbName(fakePath); - assert.strictEqual(result, "roomValue"); - assert((client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName', () => { - const result = client.matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName(fakePath); - assert.strictEqual(result, "legacyRoomValue"); - assert((client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBlurbFromRoomBlurbsLegacyRoomBlurbName', () => { - const result = client.matchBlurbFromRoomBlurbsLegacyRoomBlurbName(fakePath); - assert.strictEqual(result, "blurbValue"); - assert((client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('roomBlurbsLegacyRoomBlurb', async () => { + const fakePath = '/rendered/path/roomBlurbsLegacyRoomBlurb'; + const expectedParameters = { + room: 'roomValue', + legacy_room: 'legacyRoomValue', + blurb: 'blurbValue', + }; + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('roomBlurbsLegacyRoomBlurbPath', () => { + const result = client.roomBlurbsLegacyRoomBlurbPath( + 'roomValue', + 'legacyRoomValue', + 'blurbValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchRoomFromRoomBlurbsLegacyRoomBlurbName', () => { + const result = + client.matchRoomFromRoomBlurbsLegacyRoomBlurbName(fakePath); + assert.strictEqual(result, 'roomValue'); + assert( + ( + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName', () => { + const result = + client.matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName(fakePath); + assert.strictEqual(result, 'legacyRoomValue'); + assert( + ( + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBlurbFromRoomBlurbsLegacyRoomBlurbName', () => { + const result = + client.matchBlurbFromRoomBlurbsLegacyRoomBlurbName(fakePath); + assert.strictEqual(result, 'blurbValue'); + assert( + ( + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('sequence', async () => { - const fakePath = "/rendered/path/sequence"; - const expectedParameters = { - sequence: "sequenceValue", - }; - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.sequencePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.sequencePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('sequencePath', () => { - const result = client.sequencePath("sequenceValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.sequencePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchSequenceFromSequenceName', () => { - const result = client.matchSequenceFromSequenceName(fakePath); - assert.strictEqual(result, "sequenceValue"); - assert((client.pathTemplates.sequencePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('sequence', async () => { + const fakePath = '/rendered/path/sequence'; + const expectedParameters = { + sequence: 'sequenceValue', + }; + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.sequencePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.sequencePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('sequencePath', () => { + const result = client.sequencePath('sequenceValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.sequencePathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchSequenceFromSequenceName', () => { + const result = client.matchSequenceFromSequenceName(fakePath); + assert.strictEqual(result, 'sequenceValue'); + assert( + (client.pathTemplates.sequencePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('sequenceReport', async () => { - const fakePath = "/rendered/path/sequenceReport"; - const expectedParameters = { - sequence: "sequenceValue", - }; - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.sequenceReportPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.sequenceReportPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('sequenceReportPath', () => { - const result = client.sequenceReportPath("sequenceValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.sequenceReportPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchSequenceFromSequenceReportName', () => { - const result = client.matchSequenceFromSequenceReportName(fakePath); - assert.strictEqual(result, "sequenceValue"); - assert((client.pathTemplates.sequenceReportPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('sequenceReport', async () => { + const fakePath = '/rendered/path/sequenceReport'; + const expectedParameters = { + sequence: 'sequenceValue', + }; + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.sequenceReportPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.sequenceReportPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('sequenceReportPath', () => { + const result = client.sequenceReportPath('sequenceValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.sequenceReportPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchSequenceFromSequenceReportName', () => { + const result = client.matchSequenceFromSequenceReportName(fakePath); + assert.strictEqual(result, 'sequenceValue'); + assert( + (client.pathTemplates.sequenceReportPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('session', async () => { - const fakePath = "/rendered/path/session"; - const expectedParameters = { - session: "sessionValue", - }; - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.sessionPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.sessionPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('sessionPath', () => { - const result = client.sessionPath("sessionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.sessionPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchSessionFromSessionName', () => { - const result = client.matchSessionFromSessionName(fakePath); - assert.strictEqual(result, "sessionValue"); - assert((client.pathTemplates.sessionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('session', async () => { + const fakePath = '/rendered/path/session'; + const expectedParameters = { + session: 'sessionValue', + }; + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.sessionPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.sessionPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('sessionPath', () => { + const result = client.sessionPath('sessionValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.sessionPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchSessionFromSessionName', () => { + const result = client.matchSessionFromSessionName(fakePath); + assert.strictEqual(result, 'sessionValue'); + assert( + (client.pathTemplates.sessionPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('test', async () => { - const fakePath = "/rendered/path/test"; - const expectedParameters = { - session: "sessionValue", - test: "testValue", - }; - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.testPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.testPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('testPath', () => { - const result = client.testPath("sessionValue", "testValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.testPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchSessionFromTestName', () => { - const result = client.matchSessionFromTestName(fakePath); - assert.strictEqual(result, "sessionValue"); - assert((client.pathTemplates.testPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchTestFromTestName', () => { - const result = client.matchTestFromTestName(fakePath); - assert.strictEqual(result, "testValue"); - assert((client.pathTemplates.testPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('test', async () => { + const fakePath = '/rendered/path/test'; + const expectedParameters = { + session: 'sessionValue', + test: 'testValue', + }; + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.testPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.testPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('testPath', () => { + const result = client.testPath('sessionValue', 'testValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.testPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchSessionFromTestName', () => { + const result = client.matchSessionFromTestName(fakePath); + assert.strictEqual(result, 'sessionValue'); + assert( + (client.pathTemplates.testPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchTestFromTestName', () => { + const result = client.matchTestFromTestName(fakePath); + assert.strictEqual(result, 'testValue'); + assert( + (client.pathTemplates.testPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('user', async () => { - const fakePath = "/rendered/path/user"; - const expectedParameters = { - user: "userValue", - }; - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.userPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.userPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('userPath', () => { - const result = client.userPath("userValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.userPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchUserFromUserName', () => { - const result = client.matchUserFromUserName(fakePath); - assert.strictEqual(result, "userValue"); - assert((client.pathTemplates.userPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('user', async () => { + const fakePath = '/rendered/path/user'; + const expectedParameters = { + user: 'userValue', + }; + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.userPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.userPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('userPath', () => { + const result = client.userPath('userValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.userPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchUserFromUserName', () => { + const result = client.matchUserFromUserName(fakePath); + assert.strictEqual(result, 'userValue'); + assert( + (client.pathTemplates.userPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('userProfileBlurb', async () => { - const fakePath = "/rendered/path/userProfileBlurb"; - const expectedParameters = { - user: "userValue", - blurb: "blurbValue", - }; - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.userProfileBlurbPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.userProfileBlurbPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('userProfileBlurbPath', () => { - const result = client.userProfileBlurbPath("userValue", "blurbValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.userProfileBlurbPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchUserFromUserProfileBlurbName', () => { - const result = client.matchUserFromUserProfileBlurbName(fakePath); - assert.strictEqual(result, "userValue"); - assert((client.pathTemplates.userProfileBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBlurbFromUserProfileBlurbName', () => { - const result = client.matchBlurbFromUserProfileBlurbName(fakePath); - assert.strictEqual(result, "blurbValue"); - assert((client.pathTemplates.userProfileBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('userProfileBlurb', async () => { + const fakePath = '/rendered/path/userProfileBlurb'; + const expectedParameters = { + user: 'userValue', + blurb: 'blurbValue', + }; + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.userProfileBlurbPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.userProfileBlurbPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('userProfileBlurbPath', () => { + const result = client.userProfileBlurbPath('userValue', 'blurbValue'); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.userProfileBlurbPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchUserFromUserProfileBlurbName', () => { + const result = client.matchUserFromUserProfileBlurbName(fakePath); + assert.strictEqual(result, 'userValue'); + assert( + (client.pathTemplates.userProfileBlurbPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBlurbFromUserProfileBlurbName', () => { + const result = client.matchBlurbFromUserProfileBlurbName(fakePath); + assert.strictEqual(result, 'blurbValue'); + assert( + (client.pathTemplates.userProfileBlurbPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('userProfileBlurbsLegacyUserBlurb', async () => { - const fakePath = "/rendered/path/userProfileBlurbsLegacyUserBlurb"; - const expectedParameters = { - user: "userValue", - legacy_user: "legacyUserValue", - blurb: "blurbValue", - }; - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('userProfileBlurbsLegacyUserBlurbPath', () => { - const result = client.userProfileBlurbsLegacyUserBlurbPath("userValue", "legacyUserValue", "blurbValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchUserFromUserProfileBlurbsLegacyUserBlurbName', () => { - const result = client.matchUserFromUserProfileBlurbsLegacyUserBlurbName(fakePath); - assert.strictEqual(result, "userValue"); - assert((client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName', () => { - const result = client.matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName(fakePath); - assert.strictEqual(result, "legacyUserValue"); - assert((client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBlurbFromUserProfileBlurbsLegacyUserBlurbName', () => { - const result = client.matchBlurbFromUserProfileBlurbsLegacyUserBlurbName(fakePath); - assert.strictEqual(result, "blurbValue"); - assert((client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('userProfileBlurbsLegacyUserBlurb', async () => { + const fakePath = '/rendered/path/userProfileBlurbsLegacyUserBlurb'; + const expectedParameters = { + user: 'userValue', + legacy_user: 'legacyUserValue', + blurb: 'blurbValue', + }; + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('userProfileBlurbsLegacyUserBlurbPath', () => { + const result = client.userProfileBlurbsLegacyUserBlurbPath( + 'userValue', + 'legacyUserValue', + 'blurbValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchUserFromUserProfileBlurbsLegacyUserBlurbName', () => { + const result = + client.matchUserFromUserProfileBlurbsLegacyUserBlurbName(fakePath); + assert.strictEqual(result, 'userValue'); + assert( + ( + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName', () => { + const result = + client.matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName( + fakePath, + ); + assert.strictEqual(result, 'legacyUserValue'); + assert( + ( + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBlurbFromUserProfileBlurbsLegacyUserBlurbName', () => { + const result = + client.matchBlurbFromUserProfileBlurbsLegacyUserBlurbName(fakePath); + assert.strictEqual(result, 'blurbValue'); + assert( + ( + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/core/generator/gapic-generator-typescript/baselines/disable-packing-test/test/gapic_echo_v1beta1.ts.baseline b/core/generator/gapic-generator-typescript/baselines/disable-packing-test/test/gapic_echo_v1beta1.ts.baseline index 1f5a591bdcd3..b34e52c37fd2 100644 --- a/core/generator/gapic-generator-typescript/baselines/disable-packing-test/test/gapic_echo_v1beta1.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/disable-packing-test/test/gapic_echo_v1beta1.ts.baseline @@ -19,1511 +19,1920 @@ import * as protos from '../protos/protos'; import * as assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as echoModule from '../src'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; -import {protobuf, LROperation, operationsProtos} from 'google-gax'; +import { protobuf, LROperation, operationsProtos } from 'google-gax'; // Dynamically loaded proto JSON is needed to get the type information // to fill in default values for request objects -const root = protobuf.Root.fromJSON(require('../protos/protos.json')).resolveAll(); +const root = protobuf.Root.fromJSON( + require('../protos/protos.json'), +).resolveAll(); // eslint-disable-next-line @typescript-eslint/no-unused-vars function getTypeDefaultValue(typeName: string, fields: string[]) { - let type = root.lookupType(typeName) as protobuf.Type; - for (const field of fields.slice(0, -1)) { - type = type.fields[field]?.resolvedType as protobuf.Type; - } - return type.fields[fields[fields.length - 1]]?.defaultValue; + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type.fields[field]?.resolvedType as protobuf.Type; + } + return type.fields[fields[fields.length - 1]]?.defaultValue; } function generateSampleMessage(instance: T) { - const filledObject = (instance.constructor as typeof protobuf.Message) - .toObject(instance as protobuf.Message, {defaults: true}); - return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, { defaults: true }); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; } function stubSimpleCall(response?: ResponseType, error?: Error) { - return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); } -function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { - return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +function stubSimpleCallWithCallback( + response?: ResponseType, + error?: Error, +) { + return error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); } -function stubServerStreamingCall(response?: ResponseType, error?: Error) { - const transformStub = error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); - const mockStream = new PassThrough({ - objectMode: true, - transform: transformStub, - }); - // write something to the stream to trigger transformStub and send the response back to the client - setImmediate(() => { mockStream.write({}); }); - setImmediate(() => { mockStream.end(); }); - return sinon.stub().returns(mockStream); +function stubServerStreamingCall( + response?: ResponseType, + error?: Error, +) { + const transformStub = error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + // write something to the stream to trigger transformStub and send the response back to the client + setImmediate(() => { + mockStream.write({}); + }); + setImmediate(() => { + mockStream.end(); + }); + return sinon.stub().returns(mockStream); } -function stubBidiStreamingCall(response?: ResponseType, error?: Error) { - const transformStub = error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); - const mockStream = new PassThrough({ - objectMode: true, - transform: transformStub, - }); - return sinon.stub().returns(mockStream); +function stubBidiStreamingCall( + response?: ResponseType, + error?: Error, +) { + const transformStub = error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + return sinon.stub().returns(mockStream); } -function stubClientStreamingCall(response?: ResponseType, error?: Error) { - if (error) { - return sinon.stub().callsArgWith(2, error); - } - const transformStub = sinon.stub(); - const mockStream = new PassThrough({ - objectMode: true, - transform: transformStub, - }); - return sinon.stub().returns(mockStream).callsArgWith(2, null, response); +function stubClientStreamingCall( + response?: ResponseType, + error?: Error, +) { + if (error) { + return sinon.stub().callsArgWith(2, error); + } + const transformStub = sinon.stub(); + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + return sinon.stub().returns(mockStream).callsArgWith(2, null, response); } -function stubLongRunningCall(response?: ResponseType, callError?: Error, lroError?: Error) { - const innerStub = lroError ? sinon.stub().rejects(lroError) : sinon.stub().resolves([response]); - const mockOperation = { - promise: innerStub, - }; - return callError ? sinon.stub().rejects(callError) : sinon.stub().resolves([mockOperation]); +function stubLongRunningCall( + response?: ResponseType, + callError?: Error, + lroError?: Error, +) { + const innerStub = lroError + ? sinon.stub().rejects(lroError) + : sinon.stub().resolves([response]); + const mockOperation = { + promise: innerStub, + }; + return callError + ? sinon.stub().rejects(callError) + : sinon.stub().resolves([mockOperation]); } -function stubLongRunningCallWithCallback(response?: ResponseType, callError?: Error, lroError?: Error) { - const innerStub = lroError ? sinon.stub().rejects(lroError) : sinon.stub().resolves([response]); - const mockOperation = { - promise: innerStub, - }; - return callError ? sinon.stub().callsArgWith(2, callError) : sinon.stub().callsArgWith(2, null, mockOperation); +function stubLongRunningCallWithCallback( + response?: ResponseType, + callError?: Error, + lroError?: Error, +) { + const innerStub = lroError + ? sinon.stub().rejects(lroError) + : sinon.stub().resolves([response]); + const mockOperation = { + promise: innerStub, + }; + return callError + ? sinon.stub().callsArgWith(2, callError) + : sinon.stub().callsArgWith(2, null, mockOperation); } -function stubPageStreamingCall(responses?: ResponseType[], error?: Error) { - const pagingStub = sinon.stub(); - if (responses) { - for (let i = 0; i < responses.length; ++i) { - pagingStub.onCall(i).callsArgWith(2, null, responses[i]); - } +function stubPageStreamingCall( + responses?: ResponseType[], + error?: Error, +) { + const pagingStub = sinon.stub(); + if (responses) { + for (let i = 0; i < responses.length; ++i) { + pagingStub.onCall(i).callsArgWith(2, null, responses[i]); } - const transformStub = error ? sinon.stub().callsArgWith(2, error) : pagingStub; - const mockStream = new PassThrough({ - objectMode: true, - transform: transformStub, - }); - // trigger as many responses as needed - if (responses) { - for (let i = 0; i < responses.length; ++i) { - setImmediate(() => { mockStream.write({}); }); - } - setImmediate(() => { mockStream.end(); }); - } else { - setImmediate(() => { mockStream.write({}); }); - setImmediate(() => { mockStream.end(); }); + } + const transformStub = error + ? sinon.stub().callsArgWith(2, error) + : pagingStub; + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + // trigger as many responses as needed + if (responses) { + for (let i = 0; i < responses.length; ++i) { + setImmediate(() => { + mockStream.write({}); + }); } - return sinon.stub().returns(mockStream); + setImmediate(() => { + mockStream.end(); + }); + } else { + setImmediate(() => { + mockStream.write({}); + }); + setImmediate(() => { + mockStream.end(); + }); + } + return sinon.stub().returns(mockStream); } -function stubAsyncIterationCall(responses?: ResponseType[], error?: Error) { - let counter = 0; - const asyncIterable = { - [Symbol.asyncIterator]() { - return { - async next() { - if (error) { - return Promise.reject(error); - } - if (counter >= responses!.length) { - return Promise.resolve({done: true, value: undefined}); - } - return Promise.resolve({done: false, value: responses![counter++]}); - } - }; - } - }; - return sinon.stub().returns(asyncIterable); +function stubAsyncIterationCall( + responses?: ResponseType[], + error?: Error, +) { + let counter = 0; + const asyncIterable = { + [Symbol.asyncIterator]() { + return { + async next() { + if (error) { + return Promise.reject(error); + } + if (counter >= responses!.length) { + return Promise.resolve({ done: true, value: undefined }); + } + return Promise.resolve({ done: false, value: responses![counter++] }); + }, + }; + }, + }; + return sinon.stub().returns(asyncIterable); } describe('v1beta1.EchoClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new echoModule.v1beta1.EchoClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'localhost'); - }); - - it('has universeDomain', () => { - const client = new echoModule.v1beta1.EchoClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); - - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - it('throws DeprecationWarning if static servicePath is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const servicePath = echoModule.v1beta1.EchoClient.servicePath; - assert.strictEqual(servicePath, 'localhost'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = echoModule.v1beta1.EchoClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'localhost'); - assert(stub.called); - stub.restore(); - }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { new echoModule.v1beta1.EchoClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); - - it('has port', () => { - const port = echoModule.v1beta1.EchoClient.port; - assert(port); - assert(typeof port === 'number'); - }); - - it('should create a client with no option', () => { - const client = new echoModule.v1beta1.EchoClient(); - assert(client); - }); - - it('should create a client with gRPC fallback', () => { - const client = new echoModule.v1beta1.EchoClient({ - fallback: true, - }); - assert(client); - }); - - it('has initialize method and supports deferred initialization', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.echoStub, undefined); - await client.initialize(); - assert(client.echoStub); - }); - - it('has close method for the initialized client', done => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.echoStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); - - it('has close method for the non-initialized client', done => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.echoStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new echoModule.v1beta1.EchoClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'localhost'); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); - }); + it('has universeDomain', () => { + const client = new echoModule.v1beta1.EchoClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId((err?: Error|null, projectId?: string|null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } - }); - }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = echoModule.v1beta1.EchoClient.servicePath; + assert.strictEqual(servicePath, 'localhost'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = echoModule.v1beta1.EchoClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'localhost'); + assert(stub.called); + stub.restore(); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new echoModule.v1beta1.EchoClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); }); - describe('echo', () => { - it('invokes echo without error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.EchoRequest() - ); - // path template: {qux=projects/*}/** - request.otherHeader = 'projects/value/value'; - const expectedHeaderRequestParams = 'qux=projects%2Fvalue'; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.EchoResponse() - ); - client.innerApiCalls.echo = stubSimpleCall(expectedResponse); - const [response] = await client.echo(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.echo as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.echo as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has port', () => { + const port = echoModule.v1beta1.EchoClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('invokes echo without error using callback', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.EchoRequest() - ); - // path template: {qux=projects/*}/** - request.otherHeader = 'projects/value/value'; - const expectedHeaderRequestParams = 'qux=projects%2Fvalue'; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.EchoResponse() - ); - client.innerApiCalls.echo = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.echo( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IEchoResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.echo as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.echo as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('should create a client with no option', () => { + const client = new echoModule.v1beta1.EchoClient(); + assert(client); + }); - it('invokes echo with error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.EchoRequest() - ); - // path template: {qux=projects/*}/** - request.otherHeader = 'projects/value/value'; - const expectedHeaderRequestParams = 'qux=projects%2Fvalue'; - const expectedError = new Error('expected'); - client.innerApiCalls.echo = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.echo(request), expectedError); - const actualRequest = (client.innerApiCalls.echo as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.echo as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('should create a client with gRPC fallback', () => { + const client = new echoModule.v1beta1.EchoClient({ + fallback: true, + }); + assert(client); + }); - it('invokes echo with closed client', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.EchoRequest() - ); - // path template: {qux=projects/*}/** - request.otherHeader = 'projects/value/value'; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.echo(request), expectedError); - }); + it('has initialize method and supports deferred initialization', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.echoStub, undefined); + await client.initialize(); + assert(client.echoStub); }); - describe('echoErrorDetails', () => { - it('invokes echoErrorDetails without error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.EchoErrorDetailsRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.EchoErrorDetailsResponse() - ); - client.innerApiCalls.echoErrorDetails = stubSimpleCall(expectedResponse); - const [response] = await client.echoErrorDetails(request); - assert.deepStrictEqual(response, expectedResponse); + it('has close method for the initialized client', (done) => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.echoStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes echoErrorDetails without error using callback', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.EchoErrorDetailsRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.EchoErrorDetailsResponse() - ); - client.innerApiCalls.echoErrorDetails = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.echoErrorDetails( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IEchoErrorDetailsResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); + it('has close method for the non-initialized client', (done) => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.echoStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes echoErrorDetails with error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.EchoErrorDetailsRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.echoErrorDetails = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.echoErrorDetails(request), expectedError); - }); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + }); - it('invokes echoErrorDetails with closed client', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.EchoErrorDetailsRequest() - ); - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.echoErrorDetails(request), expectedError); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + }); + + describe('echo', () => { + it('invokes echo without error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.EchoRequest(), + ); + // path template: {qux=projects/*}/** + request.otherHeader = 'projects/value/value'; + const expectedHeaderRequestParams = 'qux=projects%2Fvalue'; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.EchoResponse(), + ); + client.innerApiCalls.echo = stubSimpleCall(expectedResponse); + const [response] = await client.echo(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.echo as SinonStub).getCall(0) + .args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.echo as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('pagedExpandLegacy', () => { - it('invokes pagedExpandLegacy without error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.PagedExpandLegacyRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.PagedExpandResponse() - ); - client.innerApiCalls.pagedExpandLegacy = stubSimpleCall(expectedResponse); - const [response] = await client.pagedExpandLegacy(request); - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes echo without error using callback', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.EchoRequest(), + ); + // path template: {qux=projects/*}/** + request.otherHeader = 'projects/value/value'; + const expectedHeaderRequestParams = 'qux=projects%2Fvalue'; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.EchoResponse(), + ); + client.innerApiCalls.echo = stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.echo( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IEchoResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.echo as SinonStub).getCall(0) + .args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.echo as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes pagedExpandLegacy without error using callback', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.PagedExpandLegacyRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.PagedExpandResponse() - ); - client.innerApiCalls.pagedExpandLegacy = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.pagedExpandLegacy( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IPagedExpandResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes echo with error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.EchoRequest(), + ); + // path template: {qux=projects/*}/** + request.otherHeader = 'projects/value/value'; + const expectedHeaderRequestParams = 'qux=projects%2Fvalue'; + const expectedError = new Error('expected'); + client.innerApiCalls.echo = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.echo(request), expectedError); + const actualRequest = (client.innerApiCalls.echo as SinonStub).getCall(0) + .args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.echo as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes pagedExpandLegacy with error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.PagedExpandLegacyRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.pagedExpandLegacy = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.pagedExpandLegacy(request), expectedError); - }); + it('invokes echo with closed client', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.EchoRequest(), + ); + // path template: {qux=projects/*}/** + request.otherHeader = 'projects/value/value'; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.echo(request), expectedError); + }); + }); + + describe('echoErrorDetails', () => { + it('invokes echoErrorDetails without error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.EchoErrorDetailsRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.EchoErrorDetailsResponse(), + ); + client.innerApiCalls.echoErrorDetails = stubSimpleCall(expectedResponse); + const [response] = await client.echoErrorDetails(request); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes pagedExpandLegacy with closed client', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.PagedExpandLegacyRequest() - ); - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.pagedExpandLegacy(request), expectedError); - }); + it('invokes echoErrorDetails without error using callback', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.EchoErrorDetailsRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.EchoErrorDetailsResponse(), + ); + client.innerApiCalls.echoErrorDetails = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.echoErrorDetails( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IEchoErrorDetailsResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); }); - describe('block', () => { - it('invokes block without error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.BlockRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.BlockResponse() - ); - client.innerApiCalls.block = stubSimpleCall(expectedResponse); - const [response] = await client.block(request); - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes echoErrorDetails with error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.EchoErrorDetailsRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.echoErrorDetails = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.echoErrorDetails(request), expectedError); + }); - it('invokes block without error using callback', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.BlockRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.BlockResponse() - ); - client.innerApiCalls.block = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.block( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IBlockResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes echoErrorDetails with closed client', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.EchoErrorDetailsRequest(), + ); + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.echoErrorDetails(request), expectedError); + }); + }); + + describe('pagedExpandLegacy', () => { + it('invokes pagedExpandLegacy without error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.PagedExpandLegacyRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.PagedExpandResponse(), + ); + client.innerApiCalls.pagedExpandLegacy = stubSimpleCall(expectedResponse); + const [response] = await client.pagedExpandLegacy(request); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes block with error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.BlockRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.block = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.block(request), expectedError); - }); + it('invokes pagedExpandLegacy without error using callback', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.PagedExpandLegacyRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.PagedExpandResponse(), + ); + client.innerApiCalls.pagedExpandLegacy = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.pagedExpandLegacy( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IPagedExpandResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes block with closed client', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.BlockRequest() - ); - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.block(request), expectedError); - }); + it('invokes pagedExpandLegacy with error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.PagedExpandLegacyRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.pagedExpandLegacy = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.pagedExpandLegacy(request), expectedError); }); - describe('wait', () => { - it('invokes wait without error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.WaitRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.wait = stubLongRunningCall(expectedResponse); - const [operation] = await client.wait(request); - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes pagedExpandLegacy with closed client', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.PagedExpandLegacyRequest(), + ); + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.pagedExpandLegacy(request), expectedError); + }); + }); + + describe('block', () => { + it('invokes block without error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.BlockRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.BlockResponse(), + ); + client.innerApiCalls.block = stubSimpleCall(expectedResponse); + const [response] = await client.block(request); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes wait without error using callback', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.WaitRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.wait = stubLongRunningCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.wait( - request, - (err?: Error|null, - result?: LROperation|null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const operation = await promise as LROperation; - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes block without error using callback', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.BlockRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.BlockResponse(), + ); + client.innerApiCalls.block = stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.block( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IBlockResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes wait with call error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.WaitRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.wait = stubLongRunningCall(undefined, expectedError); - await assert.rejects(client.wait(request), expectedError); - }); + it('invokes block with error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.BlockRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.block = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.block(request), expectedError); + }); - it('invokes wait with LRO error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.WaitRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.wait = stubLongRunningCall(undefined, undefined, expectedError); - const [operation] = await client.wait(request); - await assert.rejects(operation.promise(), expectedError); - }); + it('invokes block with closed client', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.BlockRequest(), + ); + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.block(request), expectedError); + }); + }); + + describe('wait', () => { + it('invokes wait without error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.WaitRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.wait = stubLongRunningCall(expectedResponse); + const [operation] = await client.wait(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes checkWaitProgress without error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedResponse = generateSampleMessage( - new operationsProtos.google.longrunning.Operation() - ); - expectedResponse.name = 'test'; - expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; - expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')} - - client.operationsClient.getOperation = stubSimpleCall(expectedResponse); - const decodedOperation = await client.checkWaitProgress(expectedResponse.name); - assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); - assert(decodedOperation.metadata); - assert((client.operationsClient.getOperation as SinonStub).getCall(0)); - }); + it('invokes wait without error using callback', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.WaitRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.wait = + stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.wait( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.showcase.v1beta1.IWaitResponse, + protos.google.showcase.v1beta1.IWaitMetadata + > | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const operation = (await promise) as LROperation< + protos.google.showcase.v1beta1.IWaitResponse, + protos.google.showcase.v1beta1.IWaitMetadata + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes checkWaitProgress with error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedError = new Error('expected'); - - client.operationsClient.getOperation = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.checkWaitProgress(''), expectedError); - assert((client.operationsClient.getOperation as SinonStub) - .getCall(0)); - }); + it('invokes wait with call error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.WaitRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.wait = stubLongRunningCall(undefined, expectedError); + await assert.rejects(client.wait(request), expectedError); }); - describe('expand', () => { - it('invokes expand without error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ExpandRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.EchoResponse() - ); - client.innerApiCalls.expand = stubServerStreamingCall(expectedResponse); - const stream = client.expand(request); - const promise = new Promise((resolve, reject) => { - stream.on('data', (response: protos.google.showcase.v1beta1.EchoResponse) => { - resolve(response); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes wait with LRO error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.WaitRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.wait = stubLongRunningCall( + undefined, + undefined, + expectedError, + ); + const [operation] = await client.wait(request); + await assert.rejects(operation.promise(), expectedError); + }); - it('invokes expand without error and gaxServerStreamingRetries enabled', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - gaxServerStreamingRetries: true - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ExpandRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.EchoResponse() - ); - client.innerApiCalls.expand = stubServerStreamingCall(expectedResponse); - const stream = client.expand(request); - const promise = new Promise((resolve, reject) => { - stream.on('data', (response: protos.google.showcase.v1beta1.EchoResponse) => { - resolve(response); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes checkWaitProgress without error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation(), + ); + expectedResponse.name = 'test'; + expectedResponse.response = { type_url: 'url', value: Buffer.from('') }; + expectedResponse.metadata = { type_url: 'url', value: Buffer.from('') }; + + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const decodedOperation = await client.checkWaitProgress( + expectedResponse.name, + ); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); - it('invokes expand with error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ExpandRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.expand = stubServerStreamingCall(undefined, expectedError); - const stream = client.expand(request); - const promise = new Promise((resolve, reject) => { - stream.on('data', (response: protos.google.showcase.v1beta1.EchoResponse) => { - resolve(response); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); + it('invokes checkWaitProgress with error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const expectedError = new Error('expected'); + + client.operationsClient.getOperation = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.checkWaitProgress(''), expectedError); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + }); + + describe('expand', () => { + it('invokes expand without error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ExpandRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.EchoResponse(), + ); + client.innerApiCalls.expand = stubServerStreamingCall(expectedResponse); + const stream = client.expand(request); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + (response: protos.google.showcase.v1beta1.EchoResponse) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes expand with closed client', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ExpandRequest() - ); - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - const stream = client.expand(request, {retryRequestOptions: {noResponseRetries: 0}}); - const promise = new Promise((resolve, reject) => { - stream.on('data', (response: protos.google.showcase.v1beta1.EchoResponse) => { - resolve(response); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - }); - it('should create a client with gaxServerStreamingRetries enabled', () => { - const client = new echoModule.v1beta1.EchoClient({ - gaxServerStreamingRetries: true, - }); - assert(client); + it('invokes expand without error and gaxServerStreamingRetries enabled', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + gaxServerStreamingRetries: true, + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ExpandRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.EchoResponse(), + ); + client.innerApiCalls.expand = stubServerStreamingCall(expectedResponse); + const stream = client.expand(request); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + (response: protos.google.showcase.v1beta1.EchoResponse) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); }); - describe('chat', () => { - it('invokes chat without error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.EchoRequest() - ); - - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.EchoResponse() - ); - client.innerApiCalls.chat = stubBidiStreamingCall(expectedResponse); - const stream = client.chat(); - const promise = new Promise((resolve, reject) => { - stream.on('data', (response: protos.google.showcase.v1beta1.EchoResponse) => { - resolve(response); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - stream.write(request); - stream.end(); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - assert((client.innerApiCalls.chat as SinonStub) - .getCall(0).calledWith(null)); - assert.deepStrictEqual(((stream as unknown as PassThrough) - ._transform as SinonStub).getCall(0).args[0], request); + it('invokes expand with error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ExpandRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.expand = stubServerStreamingCall( + undefined, + expectedError, + ); + const stream = client.expand(request); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + (response: protos.google.showcase.v1beta1.EchoResponse) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); }); + }); + await assert.rejects(promise, expectedError); + }); - it('invokes chat with error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.EchoRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.chat = stubBidiStreamingCall(undefined, expectedError); - const stream = client.chat(); - const promise = new Promise((resolve, reject) => { - stream.on('data', (response: protos.google.showcase.v1beta1.EchoResponse) => { - resolve(response); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - stream.write(request); - stream.end(); - }); - await assert.rejects(promise, expectedError); - assert((client.innerApiCalls.chat as SinonStub) - .getCall(0).calledWith(null)); - assert.deepStrictEqual(((stream as unknown as PassThrough) - ._transform as SinonStub).getCall(0).args[0], request); + it('invokes expand with closed client', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ExpandRequest(), + ); + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + const stream = client.expand(request, { + retryRequestOptions: { noResponseRetries: 0 }, + }); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + (response: protos.google.showcase.v1beta1.EchoResponse) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); }); + }); + await assert.rejects(promise, expectedError); }); - - describe('collect', () => { - it('invokes collect without error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.EchoRequest() - ); - - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.EchoResponse() - ); - client.innerApiCalls.collect = stubClientStreamingCall(expectedResponse); - let stream: PassThrough; - const promise = new Promise((resolve, reject) => { - stream = client.collect( - (err?: Error|null, result?: protos.google.showcase.v1beta1.IEchoResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }) as unknown as PassThrough; - stream.write(request); - stream.end(); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - assert((client.innerApiCalls.collect as SinonStub) - .getCall(0).calledWith(null, {} /*, callback defined above */)); - assert.deepStrictEqual((stream!._transform as SinonStub).getCall(0).args[0], request); + it('should create a client with gaxServerStreamingRetries enabled', () => { + const client = new echoModule.v1beta1.EchoClient({ + gaxServerStreamingRetries: true, + }); + assert(client); + }); + }); + + describe('chat', () => { + it('invokes chat without error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.EchoRequest(), + ); + + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.EchoResponse(), + ); + client.innerApiCalls.chat = stubBidiStreamingCall(expectedResponse); + const stream = client.chat(); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + (response: protos.google.showcase.v1beta1.EchoResponse) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); }); + stream.write(request); + stream.end(); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + assert( + (client.innerApiCalls.chat as SinonStub).getCall(0).calledWith(null), + ); + assert.deepStrictEqual( + ((stream as unknown as PassThrough)._transform as SinonStub).getCall(0) + .args[0], + request, + ); + }); - it('invokes collect with error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.EchoRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.collect = stubClientStreamingCall(undefined, expectedError); - let stream: PassThrough; - const promise = new Promise((resolve, reject) => { - stream = client.collect( - (err?: Error|null, result?: protos.google.showcase.v1beta1.IEchoResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }) as unknown as PassThrough; - stream.write(request); - stream.end(); - }); - await assert.rejects(promise, expectedError); - assert((client.innerApiCalls.collect as SinonStub) - .getCall(0).calledWith(null, {} /*, callback defined above */)); + it('invokes chat with error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.EchoRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.chat = stubBidiStreamingCall( + undefined, + expectedError, + ); + const stream = client.chat(); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + (response: protos.google.showcase.v1beta1.EchoResponse) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); }); + stream.write(request); + stream.end(); + }); + await assert.rejects(promise, expectedError); + assert( + (client.innerApiCalls.chat as SinonStub).getCall(0).calledWith(null), + ); + assert.deepStrictEqual( + ((stream as unknown as PassThrough)._transform as SinonStub).getCall(0) + .args[0], + request, + ); + }); + }); + + describe('collect', () => { + it('invokes collect without error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.EchoRequest(), + ); + + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.EchoResponse(), + ); + client.innerApiCalls.collect = stubClientStreamingCall(expectedResponse); + let stream: PassThrough; + const promise = new Promise((resolve, reject) => { + stream = client.collect( + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IEchoResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ) as unknown as PassThrough; + stream.write(request); + stream.end(); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + assert( + (client.innerApiCalls.collect as SinonStub) + .getCall(0) + .calledWith(null, {} /*, callback defined above */), + ); + assert.deepStrictEqual( + (stream!._transform as SinonStub).getCall(0).args[0], + request, + ); }); - describe('pagedExpand', () => { - it('invokes pagedExpand without error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.PagedExpandRequest() - );const expectedResponse = [ - generateSampleMessage(new protos.google.showcase.v1beta1.EchoResponse()), - generateSampleMessage(new protos.google.showcase.v1beta1.EchoResponse()), - generateSampleMessage(new protos.google.showcase.v1beta1.EchoResponse()), - ]; - client.innerApiCalls.pagedExpand = stubSimpleCall(expectedResponse); - const [response] = await client.pagedExpand(request); - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes collect with error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.EchoRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.collect = stubClientStreamingCall( + undefined, + expectedError, + ); + let stream: PassThrough; + const promise = new Promise((resolve, reject) => { + stream = client.collect( + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IEchoResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ) as unknown as PassThrough; + stream.write(request); + stream.end(); + }); + await assert.rejects(promise, expectedError); + assert( + (client.innerApiCalls.collect as SinonStub) + .getCall(0) + .calledWith(null, {} /*, callback defined above */), + ); + }); + }); + + describe('pagedExpand', () => { + it('invokes pagedExpand without error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.PagedExpandRequest(), + ); + const expectedResponse = [ + generateSampleMessage( + new protos.google.showcase.v1beta1.EchoResponse(), + ), + generateSampleMessage( + new protos.google.showcase.v1beta1.EchoResponse(), + ), + generateSampleMessage( + new protos.google.showcase.v1beta1.EchoResponse(), + ), + ]; + client.innerApiCalls.pagedExpand = stubSimpleCall(expectedResponse); + const [response] = await client.pagedExpand(request); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes pagedExpand without error using callback', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.PagedExpandRequest() - );const expectedResponse = [ - generateSampleMessage(new protos.google.showcase.v1beta1.EchoResponse()), - generateSampleMessage(new protos.google.showcase.v1beta1.EchoResponse()), - generateSampleMessage(new protos.google.showcase.v1beta1.EchoResponse()), - ]; - client.innerApiCalls.pagedExpand = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.pagedExpand( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IEchoResponse[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes pagedExpand without error using callback', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.PagedExpandRequest(), + ); + const expectedResponse = [ + generateSampleMessage( + new protos.google.showcase.v1beta1.EchoResponse(), + ), + generateSampleMessage( + new protos.google.showcase.v1beta1.EchoResponse(), + ), + generateSampleMessage( + new protos.google.showcase.v1beta1.EchoResponse(), + ), + ]; + client.innerApiCalls.pagedExpand = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.pagedExpand( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IEchoResponse[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes pagedExpand with error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.PagedExpandRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.pagedExpand = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.pagedExpand(request), expectedError); - }); + it('invokes pagedExpand with error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.PagedExpandRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.pagedExpand = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.pagedExpand(request), expectedError); + }); - it('invokes pagedExpandStream without error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.PagedExpandRequest() - ); - const expectedResponse = [ - generateSampleMessage(new protos.google.showcase.v1beta1.EchoResponse()), - generateSampleMessage(new protos.google.showcase.v1beta1.EchoResponse()), - generateSampleMessage(new protos.google.showcase.v1beta1.EchoResponse()), - ]; - client.descriptors.page.pagedExpand.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.pagedExpandStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.showcase.v1beta1.EchoResponse[] = []; - stream.on('data', (response: protos.google.showcase.v1beta1.EchoResponse) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.pagedExpand.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.pagedExpand, request)); + it('invokes pagedExpandStream without error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.PagedExpandRequest(), + ); + const expectedResponse = [ + generateSampleMessage( + new protos.google.showcase.v1beta1.EchoResponse(), + ), + generateSampleMessage( + new protos.google.showcase.v1beta1.EchoResponse(), + ), + generateSampleMessage( + new protos.google.showcase.v1beta1.EchoResponse(), + ), + ]; + client.descriptors.page.pagedExpand.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.pagedExpandStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.showcase.v1beta1.EchoResponse[] = []; + stream.on( + 'data', + (response: protos.google.showcase.v1beta1.EchoResponse) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); }); - - it('invokes pagedExpandStream with error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.PagedExpandRequest() - ); - const expectedError = new Error('expected'); - client.descriptors.page.pagedExpand.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.pagedExpandStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.showcase.v1beta1.EchoResponse[] = []; - stream.on('data', (response: protos.google.showcase.v1beta1.EchoResponse) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.pagedExpand.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.pagedExpand, request)); + stream.on('error', (err: Error) => { + reject(err); }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.pagedExpand.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.pagedExpand, request), + ); + }); - it('uses async iteration with pagedExpand without error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.PagedExpandRequest() - ); - const expectedResponse = [ - generateSampleMessage(new protos.google.showcase.v1beta1.EchoResponse()), - generateSampleMessage(new protos.google.showcase.v1beta1.EchoResponse()), - generateSampleMessage(new protos.google.showcase.v1beta1.EchoResponse()), - ]; - client.descriptors.page.pagedExpand.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.showcase.v1beta1.IEchoResponse[] = []; - const iterable = client.pagedExpandAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.pagedExpand.asyncIterate as SinonStub) - .getCall(0).args[1], request); + it('invokes pagedExpandStream with error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.PagedExpandRequest(), + ); + const expectedError = new Error('expected'); + client.descriptors.page.pagedExpand.createStream = stubPageStreamingCall( + undefined, + expectedError, + ); + const stream = client.pagedExpandStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.showcase.v1beta1.EchoResponse[] = []; + stream.on( + 'data', + (response: protos.google.showcase.v1beta1.EchoResponse) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); }); - - it('uses async iteration with pagedExpand with error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.PagedExpandRequest() - ); - const expectedError = new Error('expected'); - client.descriptors.page.pagedExpand.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.pagedExpandAsync(request); - await assert.rejects(async () => { - const responses: protos.google.showcase.v1beta1.IEchoResponse[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.pagedExpand.asyncIterate as SinonStub) - .getCall(0).args[1], request); + stream.on('error', (err: Error) => { + reject(err); }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.pagedExpand.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.pagedExpand, request), + ); }); + it('uses async iteration with pagedExpand without error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.PagedExpandRequest(), + ); + const expectedResponse = [ + generateSampleMessage( + new protos.google.showcase.v1beta1.EchoResponse(), + ), + generateSampleMessage( + new protos.google.showcase.v1beta1.EchoResponse(), + ), + generateSampleMessage( + new protos.google.showcase.v1beta1.EchoResponse(), + ), + ]; + client.descriptors.page.pagedExpand.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.showcase.v1beta1.IEchoResponse[] = []; + const iterable = client.pagedExpandAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + (client.descriptors.page.pagedExpand.asyncIterate as SinonStub).getCall( + 0, + ).args[1], + request, + ); + }); - describe('Path templates', () => { - - describe('blueprint', async () => { - const fakePath = "/rendered/path/blueprint"; - const expectedParameters = { - session: "sessionValue", - test: "testValue", - blueprint: "blueprintValue", - }; - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.blueprintPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.blueprintPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('blueprintPath', () => { - const result = client.blueprintPath("sessionValue", "testValue", "blueprintValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.blueprintPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchSessionFromBlueprintName', () => { - const result = client.matchSessionFromBlueprintName(fakePath); - assert.strictEqual(result, "sessionValue"); - assert((client.pathTemplates.blueprintPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchTestFromBlueprintName', () => { - const result = client.matchTestFromBlueprintName(fakePath); - assert.strictEqual(result, "testValue"); - assert((client.pathTemplates.blueprintPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBlueprintFromBlueprintName', () => { - const result = client.matchBlueprintFromBlueprintName(fakePath); - assert.strictEqual(result, "blueprintValue"); - assert((client.pathTemplates.blueprintPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('uses async iteration with pagedExpand with error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.PagedExpandRequest(), + ); + const expectedError = new Error('expected'); + client.descriptors.page.pagedExpand.asyncIterate = stubAsyncIterationCall( + undefined, + expectedError, + ); + const iterable = client.pagedExpandAsync(request); + await assert.rejects(async () => { + const responses: protos.google.showcase.v1beta1.IEchoResponse[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + (client.descriptors.page.pagedExpand.asyncIterate as SinonStub).getCall( + 0, + ).args[1], + request, + ); + }); + }); + + describe('Path templates', () => { + describe('blueprint', async () => { + const fakePath = '/rendered/path/blueprint'; + const expectedParameters = { + session: 'sessionValue', + test: 'testValue', + blueprint: 'blueprintValue', + }; + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.blueprintPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.blueprintPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('blueprintPath', () => { + const result = client.blueprintPath( + 'sessionValue', + 'testValue', + 'blueprintValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.blueprintPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchSessionFromBlueprintName', () => { + const result = client.matchSessionFromBlueprintName(fakePath); + assert.strictEqual(result, 'sessionValue'); + assert( + (client.pathTemplates.blueprintPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchTestFromBlueprintName', () => { + const result = client.matchTestFromBlueprintName(fakePath); + assert.strictEqual(result, 'testValue'); + assert( + (client.pathTemplates.blueprintPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBlueprintFromBlueprintName', () => { + const result = client.matchBlueprintFromBlueprintName(fakePath); + assert.strictEqual(result, 'blueprintValue'); + assert( + (client.pathTemplates.blueprintPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('room', async () => { - const fakePath = "/rendered/path/room"; - const expectedParameters = { - room: "roomValue", - }; - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.roomPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.roomPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('roomPath', () => { - const result = client.roomPath("roomValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.roomPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchRoomFromRoomName', () => { - const result = client.matchRoomFromRoomName(fakePath); - assert.strictEqual(result, "roomValue"); - assert((client.pathTemplates.roomPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('room', async () => { + const fakePath = '/rendered/path/room'; + const expectedParameters = { + room: 'roomValue', + }; + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.roomPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.roomPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('roomPath', () => { + const result = client.roomPath('roomValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.roomPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchRoomFromRoomName', () => { + const result = client.matchRoomFromRoomName(fakePath); + assert.strictEqual(result, 'roomValue'); + assert( + (client.pathTemplates.roomPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('roomBlurb', async () => { - const fakePath = "/rendered/path/roomBlurb"; - const expectedParameters = { - room: "roomValue", - blurb: "blurbValue", - }; - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.roomBlurbPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.roomBlurbPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('roomBlurbPath', () => { - const result = client.roomBlurbPath("roomValue", "blurbValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.roomBlurbPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchRoomFromRoomBlurbName', () => { - const result = client.matchRoomFromRoomBlurbName(fakePath); - assert.strictEqual(result, "roomValue"); - assert((client.pathTemplates.roomBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBlurbFromRoomBlurbName', () => { - const result = client.matchBlurbFromRoomBlurbName(fakePath); - assert.strictEqual(result, "blurbValue"); - assert((client.pathTemplates.roomBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('roomBlurb', async () => { + const fakePath = '/rendered/path/roomBlurb'; + const expectedParameters = { + room: 'roomValue', + blurb: 'blurbValue', + }; + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.roomBlurbPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.roomBlurbPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('roomBlurbPath', () => { + const result = client.roomBlurbPath('roomValue', 'blurbValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.roomBlurbPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchRoomFromRoomBlurbName', () => { + const result = client.matchRoomFromRoomBlurbName(fakePath); + assert.strictEqual(result, 'roomValue'); + assert( + (client.pathTemplates.roomBlurbPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBlurbFromRoomBlurbName', () => { + const result = client.matchBlurbFromRoomBlurbName(fakePath); + assert.strictEqual(result, 'blurbValue'); + assert( + (client.pathTemplates.roomBlurbPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('roomBlurbsLegacyRoomBlurb', async () => { - const fakePath = "/rendered/path/roomBlurbsLegacyRoomBlurb"; - const expectedParameters = { - room: "roomValue", - legacy_room: "legacyRoomValue", - blurb: "blurbValue", - }; - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('roomBlurbsLegacyRoomBlurbPath', () => { - const result = client.roomBlurbsLegacyRoomBlurbPath("roomValue", "legacyRoomValue", "blurbValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchRoomFromRoomBlurbsLegacyRoomBlurbName', () => { - const result = client.matchRoomFromRoomBlurbsLegacyRoomBlurbName(fakePath); - assert.strictEqual(result, "roomValue"); - assert((client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName', () => { - const result = client.matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName(fakePath); - assert.strictEqual(result, "legacyRoomValue"); - assert((client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBlurbFromRoomBlurbsLegacyRoomBlurbName', () => { - const result = client.matchBlurbFromRoomBlurbsLegacyRoomBlurbName(fakePath); - assert.strictEqual(result, "blurbValue"); - assert((client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('roomBlurbsLegacyRoomBlurb', async () => { + const fakePath = '/rendered/path/roomBlurbsLegacyRoomBlurb'; + const expectedParameters = { + room: 'roomValue', + legacy_room: 'legacyRoomValue', + blurb: 'blurbValue', + }; + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('roomBlurbsLegacyRoomBlurbPath', () => { + const result = client.roomBlurbsLegacyRoomBlurbPath( + 'roomValue', + 'legacyRoomValue', + 'blurbValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchRoomFromRoomBlurbsLegacyRoomBlurbName', () => { + const result = + client.matchRoomFromRoomBlurbsLegacyRoomBlurbName(fakePath); + assert.strictEqual(result, 'roomValue'); + assert( + ( + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName', () => { + const result = + client.matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName(fakePath); + assert.strictEqual(result, 'legacyRoomValue'); + assert( + ( + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBlurbFromRoomBlurbsLegacyRoomBlurbName', () => { + const result = + client.matchBlurbFromRoomBlurbsLegacyRoomBlurbName(fakePath); + assert.strictEqual(result, 'blurbValue'); + assert( + ( + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('sequence', async () => { - const fakePath = "/rendered/path/sequence"; - const expectedParameters = { - sequence: "sequenceValue", - }; - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.sequencePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.sequencePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('sequencePath', () => { - const result = client.sequencePath("sequenceValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.sequencePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchSequenceFromSequenceName', () => { - const result = client.matchSequenceFromSequenceName(fakePath); - assert.strictEqual(result, "sequenceValue"); - assert((client.pathTemplates.sequencePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('sequence', async () => { + const fakePath = '/rendered/path/sequence'; + const expectedParameters = { + sequence: 'sequenceValue', + }; + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.sequencePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.sequencePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('sequencePath', () => { + const result = client.sequencePath('sequenceValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.sequencePathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchSequenceFromSequenceName', () => { + const result = client.matchSequenceFromSequenceName(fakePath); + assert.strictEqual(result, 'sequenceValue'); + assert( + (client.pathTemplates.sequencePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('sequenceReport', async () => { - const fakePath = "/rendered/path/sequenceReport"; - const expectedParameters = { - sequence: "sequenceValue", - }; - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.sequenceReportPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.sequenceReportPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('sequenceReportPath', () => { - const result = client.sequenceReportPath("sequenceValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.sequenceReportPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchSequenceFromSequenceReportName', () => { - const result = client.matchSequenceFromSequenceReportName(fakePath); - assert.strictEqual(result, "sequenceValue"); - assert((client.pathTemplates.sequenceReportPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('sequenceReport', async () => { + const fakePath = '/rendered/path/sequenceReport'; + const expectedParameters = { + sequence: 'sequenceValue', + }; + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.sequenceReportPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.sequenceReportPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('sequenceReportPath', () => { + const result = client.sequenceReportPath('sequenceValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.sequenceReportPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchSequenceFromSequenceReportName', () => { + const result = client.matchSequenceFromSequenceReportName(fakePath); + assert.strictEqual(result, 'sequenceValue'); + assert( + (client.pathTemplates.sequenceReportPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('session', async () => { - const fakePath = "/rendered/path/session"; - const expectedParameters = { - session: "sessionValue", - }; - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.sessionPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.sessionPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('sessionPath', () => { - const result = client.sessionPath("sessionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.sessionPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchSessionFromSessionName', () => { - const result = client.matchSessionFromSessionName(fakePath); - assert.strictEqual(result, "sessionValue"); - assert((client.pathTemplates.sessionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('session', async () => { + const fakePath = '/rendered/path/session'; + const expectedParameters = { + session: 'sessionValue', + }; + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.sessionPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.sessionPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('sessionPath', () => { + const result = client.sessionPath('sessionValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.sessionPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchSessionFromSessionName', () => { + const result = client.matchSessionFromSessionName(fakePath); + assert.strictEqual(result, 'sessionValue'); + assert( + (client.pathTemplates.sessionPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('test', async () => { - const fakePath = "/rendered/path/test"; - const expectedParameters = { - session: "sessionValue", - test: "testValue", - }; - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.testPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.testPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('testPath', () => { - const result = client.testPath("sessionValue", "testValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.testPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchSessionFromTestName', () => { - const result = client.matchSessionFromTestName(fakePath); - assert.strictEqual(result, "sessionValue"); - assert((client.pathTemplates.testPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchTestFromTestName', () => { - const result = client.matchTestFromTestName(fakePath); - assert.strictEqual(result, "testValue"); - assert((client.pathTemplates.testPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('test', async () => { + const fakePath = '/rendered/path/test'; + const expectedParameters = { + session: 'sessionValue', + test: 'testValue', + }; + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.testPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.testPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('testPath', () => { + const result = client.testPath('sessionValue', 'testValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.testPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchSessionFromTestName', () => { + const result = client.matchSessionFromTestName(fakePath); + assert.strictEqual(result, 'sessionValue'); + assert( + (client.pathTemplates.testPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchTestFromTestName', () => { + const result = client.matchTestFromTestName(fakePath); + assert.strictEqual(result, 'testValue'); + assert( + (client.pathTemplates.testPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('user', async () => { - const fakePath = "/rendered/path/user"; - const expectedParameters = { - user: "userValue", - }; - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.userPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.userPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('userPath', () => { - const result = client.userPath("userValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.userPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchUserFromUserName', () => { - const result = client.matchUserFromUserName(fakePath); - assert.strictEqual(result, "userValue"); - assert((client.pathTemplates.userPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('user', async () => { + const fakePath = '/rendered/path/user'; + const expectedParameters = { + user: 'userValue', + }; + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.userPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.userPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('userPath', () => { + const result = client.userPath('userValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.userPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchUserFromUserName', () => { + const result = client.matchUserFromUserName(fakePath); + assert.strictEqual(result, 'userValue'); + assert( + (client.pathTemplates.userPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('userProfileBlurb', async () => { - const fakePath = "/rendered/path/userProfileBlurb"; - const expectedParameters = { - user: "userValue", - blurb: "blurbValue", - }; - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.userProfileBlurbPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.userProfileBlurbPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('userProfileBlurbPath', () => { - const result = client.userProfileBlurbPath("userValue", "blurbValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.userProfileBlurbPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchUserFromUserProfileBlurbName', () => { - const result = client.matchUserFromUserProfileBlurbName(fakePath); - assert.strictEqual(result, "userValue"); - assert((client.pathTemplates.userProfileBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBlurbFromUserProfileBlurbName', () => { - const result = client.matchBlurbFromUserProfileBlurbName(fakePath); - assert.strictEqual(result, "blurbValue"); - assert((client.pathTemplates.userProfileBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('userProfileBlurb', async () => { + const fakePath = '/rendered/path/userProfileBlurb'; + const expectedParameters = { + user: 'userValue', + blurb: 'blurbValue', + }; + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.userProfileBlurbPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.userProfileBlurbPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('userProfileBlurbPath', () => { + const result = client.userProfileBlurbPath('userValue', 'blurbValue'); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.userProfileBlurbPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchUserFromUserProfileBlurbName', () => { + const result = client.matchUserFromUserProfileBlurbName(fakePath); + assert.strictEqual(result, 'userValue'); + assert( + (client.pathTemplates.userProfileBlurbPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBlurbFromUserProfileBlurbName', () => { + const result = client.matchBlurbFromUserProfileBlurbName(fakePath); + assert.strictEqual(result, 'blurbValue'); + assert( + (client.pathTemplates.userProfileBlurbPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('userProfileBlurbsLegacyUserBlurb', async () => { - const fakePath = "/rendered/path/userProfileBlurbsLegacyUserBlurb"; - const expectedParameters = { - user: "userValue", - legacy_user: "legacyUserValue", - blurb: "blurbValue", - }; - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('userProfileBlurbsLegacyUserBlurbPath', () => { - const result = client.userProfileBlurbsLegacyUserBlurbPath("userValue", "legacyUserValue", "blurbValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchUserFromUserProfileBlurbsLegacyUserBlurbName', () => { - const result = client.matchUserFromUserProfileBlurbsLegacyUserBlurbName(fakePath); - assert.strictEqual(result, "userValue"); - assert((client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName', () => { - const result = client.matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName(fakePath); - assert.strictEqual(result, "legacyUserValue"); - assert((client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBlurbFromUserProfileBlurbsLegacyUserBlurbName', () => { - const result = client.matchBlurbFromUserProfileBlurbsLegacyUserBlurbName(fakePath); - assert.strictEqual(result, "blurbValue"); - assert((client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('userProfileBlurbsLegacyUserBlurb', async () => { + const fakePath = '/rendered/path/userProfileBlurbsLegacyUserBlurb'; + const expectedParameters = { + user: 'userValue', + legacy_user: 'legacyUserValue', + blurb: 'blurbValue', + }; + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('userProfileBlurbsLegacyUserBlurbPath', () => { + const result = client.userProfileBlurbsLegacyUserBlurbPath( + 'userValue', + 'legacyUserValue', + 'blurbValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchUserFromUserProfileBlurbsLegacyUserBlurbName', () => { + const result = + client.matchUserFromUserProfileBlurbsLegacyUserBlurbName(fakePath); + assert.strictEqual(result, 'userValue'); + assert( + ( + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName', () => { + const result = + client.matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName( + fakePath, + ); + assert.strictEqual(result, 'legacyUserValue'); + assert( + ( + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBlurbFromUserProfileBlurbsLegacyUserBlurbName', () => { + const result = + client.matchBlurbFromUserProfileBlurbsLegacyUserBlurbName(fakePath); + assert.strictEqual(result, 'blurbValue'); + assert( + ( + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/core/generator/gapic-generator-typescript/baselines/disable-packing-test/test/gapic_identity_v1beta1.ts.baseline b/core/generator/gapic-generator-typescript/baselines/disable-packing-test/test/gapic_identity_v1beta1.ts.baseline index b938f6196ed4..ca7f5f649db0 100644 --- a/core/generator/gapic-generator-typescript/baselines/disable-packing-test/test/gapic_identity_v1beta1.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/disable-packing-test/test/gapic_identity_v1beta1.ts.baseline @@ -19,1185 +19,1498 @@ import * as protos from '../protos/protos'; import * as assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as identityModule from '../src'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; -import {protobuf} from 'google-gax'; +import { protobuf } from 'google-gax'; // Dynamically loaded proto JSON is needed to get the type information // to fill in default values for request objects -const root = protobuf.Root.fromJSON(require('../protos/protos.json')).resolveAll(); +const root = protobuf.Root.fromJSON( + require('../protos/protos.json'), +).resolveAll(); // eslint-disable-next-line @typescript-eslint/no-unused-vars function getTypeDefaultValue(typeName: string, fields: string[]) { - let type = root.lookupType(typeName) as protobuf.Type; - for (const field of fields.slice(0, -1)) { - type = type.fields[field]?.resolvedType as protobuf.Type; - } - return type.fields[fields[fields.length - 1]]?.defaultValue; + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type.fields[field]?.resolvedType as protobuf.Type; + } + return type.fields[fields[fields.length - 1]]?.defaultValue; } function generateSampleMessage(instance: T) { - const filledObject = (instance.constructor as typeof protobuf.Message) - .toObject(instance as protobuf.Message, {defaults: true}); - return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, { defaults: true }); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; } function stubSimpleCall(response?: ResponseType, error?: Error) { - return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); } -function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { - return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +function stubSimpleCallWithCallback( + response?: ResponseType, + error?: Error, +) { + return error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); } -function stubPageStreamingCall(responses?: ResponseType[], error?: Error) { - const pagingStub = sinon.stub(); - if (responses) { - for (let i = 0; i < responses.length; ++i) { - pagingStub.onCall(i).callsArgWith(2, null, responses[i]); - } +function stubPageStreamingCall( + responses?: ResponseType[], + error?: Error, +) { + const pagingStub = sinon.stub(); + if (responses) { + for (let i = 0; i < responses.length; ++i) { + pagingStub.onCall(i).callsArgWith(2, null, responses[i]); } - const transformStub = error ? sinon.stub().callsArgWith(2, error) : pagingStub; - const mockStream = new PassThrough({ - objectMode: true, - transform: transformStub, - }); - // trigger as many responses as needed - if (responses) { - for (let i = 0; i < responses.length; ++i) { - setImmediate(() => { mockStream.write({}); }); - } - setImmediate(() => { mockStream.end(); }); - } else { - setImmediate(() => { mockStream.write({}); }); - setImmediate(() => { mockStream.end(); }); + } + const transformStub = error + ? sinon.stub().callsArgWith(2, error) + : pagingStub; + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + // trigger as many responses as needed + if (responses) { + for (let i = 0; i < responses.length; ++i) { + setImmediate(() => { + mockStream.write({}); + }); } - return sinon.stub().returns(mockStream); + setImmediate(() => { + mockStream.end(); + }); + } else { + setImmediate(() => { + mockStream.write({}); + }); + setImmediate(() => { + mockStream.end(); + }); + } + return sinon.stub().returns(mockStream); } -function stubAsyncIterationCall(responses?: ResponseType[], error?: Error) { - let counter = 0; - const asyncIterable = { - [Symbol.asyncIterator]() { - return { - async next() { - if (error) { - return Promise.reject(error); - } - if (counter >= responses!.length) { - return Promise.resolve({done: true, value: undefined}); - } - return Promise.resolve({done: false, value: responses![counter++]}); - } - }; - } - }; - return sinon.stub().returns(asyncIterable); +function stubAsyncIterationCall( + responses?: ResponseType[], + error?: Error, +) { + let counter = 0; + const asyncIterable = { + [Symbol.asyncIterator]() { + return { + async next() { + if (error) { + return Promise.reject(error); + } + if (counter >= responses!.length) { + return Promise.resolve({ done: true, value: undefined }); + } + return Promise.resolve({ done: false, value: responses![counter++] }); + }, + }; + }, + }; + return sinon.stub().returns(asyncIterable); } describe('v1beta1.IdentityClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new identityModule.v1beta1.IdentityClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'localhost'); - }); - - it('has universeDomain', () => { - const client = new identityModule.v1beta1.IdentityClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); - - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - it('throws DeprecationWarning if static servicePath is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const servicePath = identityModule.v1beta1.IdentityClient.servicePath; - assert.strictEqual(servicePath, 'localhost'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = identityModule.v1beta1.IdentityClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'localhost'); - assert(stub.called); - stub.restore(); - }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { new identityModule.v1beta1.IdentityClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new identityModule.v1beta1.IdentityClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'localhost'); + }); - it('has port', () => { - const port = identityModule.v1beta1.IdentityClient.port; - assert(port); - assert(typeof port === 'number'); - }); + it('has universeDomain', () => { + const client = new identityModule.v1beta1.IdentityClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - it('should create a client with no option', () => { - const client = new identityModule.v1beta1.IdentityClient(); - assert(client); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = identityModule.v1beta1.IdentityClient.servicePath; + assert.strictEqual(servicePath, 'localhost'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = identityModule.v1beta1.IdentityClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'localhost'); + assert(stub.called); + stub.restore(); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new identityModule.v1beta1.IdentityClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); + }); - it('should create a client with gRPC fallback', () => { - const client = new identityModule.v1beta1.IdentityClient({ - fallback: true, - }); - assert(client); - }); + it('has port', () => { + const port = identityModule.v1beta1.IdentityClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('has initialize method and supports deferred initialization', async () => { - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.identityStub, undefined); - await client.initialize(); - assert(client.identityStub); - }); + it('should create a client with no option', () => { + const client = new identityModule.v1beta1.IdentityClient(); + assert(client); + }); - it('has close method for the initialized client', done => { - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.identityStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('should create a client with gRPC fallback', () => { + const client = new identityModule.v1beta1.IdentityClient({ + fallback: true, + }); + assert(client); + }); - it('has close method for the non-initialized client', done => { - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.identityStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('has initialize method and supports deferred initialization', async () => { + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.identityStub, undefined); + await client.initialize(); + assert(client.identityStub); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + it('has close method for the initialized client', (done) => { + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.identityStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId((err?: Error|null, projectId?: string|null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } - }); - }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); + it('has close method for the non-initialized client', (done) => { + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.identityStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); }); - describe('createUser', () => { - it('invokes createUser without error', async () => { - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.CreateUserRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.User() - ); - client.innerApiCalls.createUser = stubSimpleCall(expectedResponse); - const [response] = await client.createUser(request); - assert.deepStrictEqual(response, expectedResponse); - }); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + }); - it('invokes createUser without error using callback', async () => { - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.CreateUserRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.User() - ); - client.innerApiCalls.createUser = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createUser( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IUser|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + }); + + describe('createUser', () => { + it('invokes createUser without error', async () => { + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.CreateUserRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.User(), + ); + client.innerApiCalls.createUser = stubSimpleCall(expectedResponse); + const [response] = await client.createUser(request); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes createUser with error', async () => { - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.CreateUserRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.createUser = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createUser(request), expectedError); - }); + it('invokes createUser without error using callback', async () => { + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.CreateUserRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.User(), + ); + client.innerApiCalls.createUser = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createUser( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IUser | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes createUser with closed client', async () => { - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.CreateUserRequest() - ); - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createUser(request), expectedError); - }); + it('invokes createUser with error', async () => { + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.CreateUserRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.createUser = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.createUser(request), expectedError); }); - describe('getUser', () => { - it('invokes getUser without error', async () => { - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.GetUserRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.GetUserRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.User() - ); - client.innerApiCalls.getUser = stubSimpleCall(expectedResponse); - const [response] = await client.getUser(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getUser as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getUser as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createUser with closed client', async () => { + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.CreateUserRequest(), + ); + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.createUser(request), expectedError); + }); + }); + + describe('getUser', () => { + it('invokes getUser without error', async () => { + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.GetUserRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.GetUserRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.User(), + ); + client.innerApiCalls.getUser = stubSimpleCall(expectedResponse); + const [response] = await client.getUser(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.getUser as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getUser as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getUser without error using callback', async () => { - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.GetUserRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.GetUserRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.User() - ); - client.innerApiCalls.getUser = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getUser( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IUser|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getUser as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getUser as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getUser without error using callback', async () => { + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.GetUserRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.GetUserRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.User(), + ); + client.innerApiCalls.getUser = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getUser( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IUser | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.getUser as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getUser as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getUser with error', async () => { - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.GetUserRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.GetUserRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getUser = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getUser(request), expectedError); - const actualRequest = (client.innerApiCalls.getUser as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getUser as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getUser with error', async () => { + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.GetUserRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.GetUserRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getUser = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.getUser(request), expectedError); + const actualRequest = (client.innerApiCalls.getUser as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getUser as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getUser with closed client', async () => { - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.GetUserRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.GetUserRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getUser(request), expectedError); - }); + it('invokes getUser with closed client', async () => { + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.GetUserRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.GetUserRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getUser(request), expectedError); + }); + }); + + describe('updateUser', () => { + it('invokes updateUser without error', async () => { + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.UpdateUserRequest(), + ); + request.user ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.UpdateUserRequest', + ['user', 'name'], + ); + request.user.name = defaultValue1; + const expectedHeaderRequestParams = `user.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.User(), + ); + client.innerApiCalls.updateUser = stubSimpleCall(expectedResponse); + const [response] = await client.updateUser(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateUser as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateUser as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('updateUser', () => { - it('invokes updateUser without error', async () => { - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.UpdateUserRequest() - ); - request.user ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.UpdateUserRequest', ['user', 'name']); - request.user.name = defaultValue1; - const expectedHeaderRequestParams = `user.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.User() - ); - client.innerApiCalls.updateUser = stubSimpleCall(expectedResponse); - const [response] = await client.updateUser(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateUser as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateUser as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateUser without error using callback', async () => { + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.UpdateUserRequest(), + ); + request.user ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.UpdateUserRequest', + ['user', 'name'], + ); + request.user.name = defaultValue1; + const expectedHeaderRequestParams = `user.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.User(), + ); + client.innerApiCalls.updateUser = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateUser( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IUser | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateUser as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateUser as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateUser without error using callback', async () => { - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.UpdateUserRequest() - ); - request.user ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.UpdateUserRequest', ['user', 'name']); - request.user.name = defaultValue1; - const expectedHeaderRequestParams = `user.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.User() - ); - client.innerApiCalls.updateUser = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateUser( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IUser|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateUser as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateUser as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateUser with error', async () => { + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.UpdateUserRequest(), + ); + request.user ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.UpdateUserRequest', + ['user', 'name'], + ); + request.user.name = defaultValue1; + const expectedHeaderRequestParams = `user.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateUser = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.updateUser(request), expectedError); + const actualRequest = ( + client.innerApiCalls.updateUser as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateUser as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateUser with error', async () => { - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.UpdateUserRequest() - ); - request.user ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.UpdateUserRequest', ['user', 'name']); - request.user.name = defaultValue1; - const expectedHeaderRequestParams = `user.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateUser = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateUser(request), expectedError); - const actualRequest = (client.innerApiCalls.updateUser as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateUser as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateUser with closed client', async () => { + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.UpdateUserRequest(), + ); + request.user ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.UpdateUserRequest', + ['user', 'name'], + ); + request.user.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.updateUser(request), expectedError); + }); + }); + + describe('deleteUser', () => { + it('invokes deleteUser without error', async () => { + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.DeleteUserRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.DeleteUserRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteUser = stubSimpleCall(expectedResponse); + const [response] = await client.deleteUser(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteUser as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteUser as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateUser with closed client', async () => { - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.UpdateUserRequest() - ); - request.user ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.UpdateUserRequest', ['user', 'name']); - request.user.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateUser(request), expectedError); - }); + it('invokes deleteUser without error using callback', async () => { + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.DeleteUserRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.DeleteUserRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteUser = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteUser( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteUser as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteUser as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('deleteUser', () => { - it('invokes deleteUser without error', async () => { - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.DeleteUserRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.DeleteUserRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteUser = stubSimpleCall(expectedResponse); - const [response] = await client.deleteUser(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteUser as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteUser as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteUser with error', async () => { + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.DeleteUserRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.DeleteUserRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteUser = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.deleteUser(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteUser as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteUser as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteUser without error using callback', async () => { - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.DeleteUserRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.DeleteUserRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteUser = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteUser( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteUser as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteUser as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteUser with closed client', async () => { + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.DeleteUserRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.DeleteUserRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.deleteUser(request), expectedError); + }); + }); + + describe('listUsers', () => { + it('invokes listUsers without error', async () => { + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListUsersRequest(), + ); + const expectedResponse = [ + generateSampleMessage(new protos.google.showcase.v1beta1.User()), + generateSampleMessage(new protos.google.showcase.v1beta1.User()), + generateSampleMessage(new protos.google.showcase.v1beta1.User()), + ]; + client.innerApiCalls.listUsers = stubSimpleCall(expectedResponse); + const [response] = await client.listUsers(request); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes deleteUser with error', async () => { - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.DeleteUserRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.DeleteUserRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteUser = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteUser(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteUser as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteUser as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listUsers without error using callback', async () => { + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListUsersRequest(), + ); + const expectedResponse = [ + generateSampleMessage(new protos.google.showcase.v1beta1.User()), + generateSampleMessage(new protos.google.showcase.v1beta1.User()), + generateSampleMessage(new protos.google.showcase.v1beta1.User()), + ]; + client.innerApiCalls.listUsers = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listUsers( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IUser[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes deleteUser with closed client', async () => { - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.DeleteUserRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.DeleteUserRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteUser(request), expectedError); - }); + it('invokes listUsers with error', async () => { + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListUsersRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.listUsers = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.listUsers(request), expectedError); }); - describe('listUsers', () => { - it('invokes listUsers without error', async () => { - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListUsersRequest() - );const expectedResponse = [ - generateSampleMessage(new protos.google.showcase.v1beta1.User()), - generateSampleMessage(new protos.google.showcase.v1beta1.User()), - generateSampleMessage(new protos.google.showcase.v1beta1.User()), - ]; - client.innerApiCalls.listUsers = stubSimpleCall(expectedResponse); - const [response] = await client.listUsers(request); - assert.deepStrictEqual(response, expectedResponse); + it('invokes listUsersStream without error', async () => { + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListUsersRequest(), + ); + const expectedResponse = [ + generateSampleMessage(new protos.google.showcase.v1beta1.User()), + generateSampleMessage(new protos.google.showcase.v1beta1.User()), + generateSampleMessage(new protos.google.showcase.v1beta1.User()), + ]; + client.descriptors.page.listUsers.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listUsersStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.showcase.v1beta1.User[] = []; + stream.on('data', (response: protos.google.showcase.v1beta1.User) => { + responses.push(response); }); - - it('invokes listUsers without error using callback', async () => { - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListUsersRequest() - );const expectedResponse = [ - generateSampleMessage(new protos.google.showcase.v1beta1.User()), - generateSampleMessage(new protos.google.showcase.v1beta1.User()), - generateSampleMessage(new protos.google.showcase.v1beta1.User()), - ]; - client.innerApiCalls.listUsers = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listUsers( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IUser[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); + stream.on('end', () => { + resolve(responses); }); - - it('invokes listUsers with error', async () => { - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListUsersRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.listUsers = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listUsers(request), expectedError); + stream.on('error', (err: Error) => { + reject(err); }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listUsers.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listUsers, request), + ); + }); - it('invokes listUsersStream without error', async () => { - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListUsersRequest() - ); - const expectedResponse = [ - generateSampleMessage(new protos.google.showcase.v1beta1.User()), - generateSampleMessage(new protos.google.showcase.v1beta1.User()), - generateSampleMessage(new protos.google.showcase.v1beta1.User()), - ]; - client.descriptors.page.listUsers.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listUsersStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.showcase.v1beta1.User[] = []; - stream.on('data', (response: protos.google.showcase.v1beta1.User) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.listUsers.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listUsers, request)); + it('invokes listUsersStream with error', async () => { + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListUsersRequest(), + ); + const expectedError = new Error('expected'); + client.descriptors.page.listUsers.createStream = stubPageStreamingCall( + undefined, + expectedError, + ); + const stream = client.listUsersStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.showcase.v1beta1.User[] = []; + stream.on('data', (response: protos.google.showcase.v1beta1.User) => { + responses.push(response); }); - - it('invokes listUsersStream with error', async () => { - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListUsersRequest() - ); - const expectedError = new Error('expected'); - client.descriptors.page.listUsers.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listUsersStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.showcase.v1beta1.User[] = []; - stream.on('data', (response: protos.google.showcase.v1beta1.User) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listUsers.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listUsers, request)); + stream.on('end', () => { + resolve(responses); }); - - it('uses async iteration with listUsers without error', async () => { - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListUsersRequest() - ); - const expectedResponse = [ - generateSampleMessage(new protos.google.showcase.v1beta1.User()), - generateSampleMessage(new protos.google.showcase.v1beta1.User()), - generateSampleMessage(new protos.google.showcase.v1beta1.User()), - ]; - client.descriptors.page.listUsers.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.showcase.v1beta1.IUser[] = []; - const iterable = client.listUsersAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listUsers.asyncIterate as SinonStub) - .getCall(0).args[1], request); + stream.on('error', (err: Error) => { + reject(err); }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listUsers.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listUsers, request), + ); + }); - it('uses async iteration with listUsers with error', async () => { - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListUsersRequest() - ); - const expectedError = new Error('expected'); - client.descriptors.page.listUsers.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listUsersAsync(request); - await assert.rejects(async () => { - const responses: protos.google.showcase.v1beta1.IUser[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listUsers.asyncIterate as SinonStub) - .getCall(0).args[1], request); - }); + it('uses async iteration with listUsers without error', async () => { + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListUsersRequest(), + ); + const expectedResponse = [ + generateSampleMessage(new protos.google.showcase.v1beta1.User()), + generateSampleMessage(new protos.google.showcase.v1beta1.User()), + generateSampleMessage(new protos.google.showcase.v1beta1.User()), + ]; + client.descriptors.page.listUsers.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.showcase.v1beta1.IUser[] = []; + const iterable = client.listUsersAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + (client.descriptors.page.listUsers.asyncIterate as SinonStub).getCall(0) + .args[1], + request, + ); }); - describe('Path templates', () => { - - describe('blueprint', async () => { - const fakePath = "/rendered/path/blueprint"; - const expectedParameters = { - session: "sessionValue", - test: "testValue", - blueprint: "blueprintValue", - }; - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.blueprintPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.blueprintPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('blueprintPath', () => { - const result = client.blueprintPath("sessionValue", "testValue", "blueprintValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.blueprintPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchSessionFromBlueprintName', () => { - const result = client.matchSessionFromBlueprintName(fakePath); - assert.strictEqual(result, "sessionValue"); - assert((client.pathTemplates.blueprintPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchTestFromBlueprintName', () => { - const result = client.matchTestFromBlueprintName(fakePath); - assert.strictEqual(result, "testValue"); - assert((client.pathTemplates.blueprintPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBlueprintFromBlueprintName', () => { - const result = client.matchBlueprintFromBlueprintName(fakePath); - assert.strictEqual(result, "blueprintValue"); - assert((client.pathTemplates.blueprintPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('uses async iteration with listUsers with error', async () => { + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListUsersRequest(), + ); + const expectedError = new Error('expected'); + client.descriptors.page.listUsers.asyncIterate = stubAsyncIterationCall( + undefined, + expectedError, + ); + const iterable = client.listUsersAsync(request); + await assert.rejects(async () => { + const responses: protos.google.showcase.v1beta1.IUser[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + (client.descriptors.page.listUsers.asyncIterate as SinonStub).getCall(0) + .args[1], + request, + ); + }); + }); + + describe('Path templates', () => { + describe('blueprint', async () => { + const fakePath = '/rendered/path/blueprint'; + const expectedParameters = { + session: 'sessionValue', + test: 'testValue', + blueprint: 'blueprintValue', + }; + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.blueprintPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.blueprintPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('blueprintPath', () => { + const result = client.blueprintPath( + 'sessionValue', + 'testValue', + 'blueprintValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.blueprintPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchSessionFromBlueprintName', () => { + const result = client.matchSessionFromBlueprintName(fakePath); + assert.strictEqual(result, 'sessionValue'); + assert( + (client.pathTemplates.blueprintPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchTestFromBlueprintName', () => { + const result = client.matchTestFromBlueprintName(fakePath); + assert.strictEqual(result, 'testValue'); + assert( + (client.pathTemplates.blueprintPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBlueprintFromBlueprintName', () => { + const result = client.matchBlueprintFromBlueprintName(fakePath); + assert.strictEqual(result, 'blueprintValue'); + assert( + (client.pathTemplates.blueprintPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('room', async () => { - const fakePath = "/rendered/path/room"; - const expectedParameters = { - room: "roomValue", - }; - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.roomPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.roomPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('roomPath', () => { - const result = client.roomPath("roomValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.roomPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchRoomFromRoomName', () => { - const result = client.matchRoomFromRoomName(fakePath); - assert.strictEqual(result, "roomValue"); - assert((client.pathTemplates.roomPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('room', async () => { + const fakePath = '/rendered/path/room'; + const expectedParameters = { + room: 'roomValue', + }; + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.roomPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.roomPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('roomPath', () => { + const result = client.roomPath('roomValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.roomPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchRoomFromRoomName', () => { + const result = client.matchRoomFromRoomName(fakePath); + assert.strictEqual(result, 'roomValue'); + assert( + (client.pathTemplates.roomPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('roomBlurb', async () => { - const fakePath = "/rendered/path/roomBlurb"; - const expectedParameters = { - room: "roomValue", - blurb: "blurbValue", - }; - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.roomBlurbPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.roomBlurbPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('roomBlurbPath', () => { - const result = client.roomBlurbPath("roomValue", "blurbValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.roomBlurbPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchRoomFromRoomBlurbName', () => { - const result = client.matchRoomFromRoomBlurbName(fakePath); - assert.strictEqual(result, "roomValue"); - assert((client.pathTemplates.roomBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBlurbFromRoomBlurbName', () => { - const result = client.matchBlurbFromRoomBlurbName(fakePath); - assert.strictEqual(result, "blurbValue"); - assert((client.pathTemplates.roomBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('roomBlurb', async () => { + const fakePath = '/rendered/path/roomBlurb'; + const expectedParameters = { + room: 'roomValue', + blurb: 'blurbValue', + }; + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.roomBlurbPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.roomBlurbPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('roomBlurbPath', () => { + const result = client.roomBlurbPath('roomValue', 'blurbValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.roomBlurbPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchRoomFromRoomBlurbName', () => { + const result = client.matchRoomFromRoomBlurbName(fakePath); + assert.strictEqual(result, 'roomValue'); + assert( + (client.pathTemplates.roomBlurbPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBlurbFromRoomBlurbName', () => { + const result = client.matchBlurbFromRoomBlurbName(fakePath); + assert.strictEqual(result, 'blurbValue'); + assert( + (client.pathTemplates.roomBlurbPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('roomBlurbsLegacyRoomBlurb', async () => { - const fakePath = "/rendered/path/roomBlurbsLegacyRoomBlurb"; - const expectedParameters = { - room: "roomValue", - legacy_room: "legacyRoomValue", - blurb: "blurbValue", - }; - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('roomBlurbsLegacyRoomBlurbPath', () => { - const result = client.roomBlurbsLegacyRoomBlurbPath("roomValue", "legacyRoomValue", "blurbValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchRoomFromRoomBlurbsLegacyRoomBlurbName', () => { - const result = client.matchRoomFromRoomBlurbsLegacyRoomBlurbName(fakePath); - assert.strictEqual(result, "roomValue"); - assert((client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName', () => { - const result = client.matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName(fakePath); - assert.strictEqual(result, "legacyRoomValue"); - assert((client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBlurbFromRoomBlurbsLegacyRoomBlurbName', () => { - const result = client.matchBlurbFromRoomBlurbsLegacyRoomBlurbName(fakePath); - assert.strictEqual(result, "blurbValue"); - assert((client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('roomBlurbsLegacyRoomBlurb', async () => { + const fakePath = '/rendered/path/roomBlurbsLegacyRoomBlurb'; + const expectedParameters = { + room: 'roomValue', + legacy_room: 'legacyRoomValue', + blurb: 'blurbValue', + }; + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('roomBlurbsLegacyRoomBlurbPath', () => { + const result = client.roomBlurbsLegacyRoomBlurbPath( + 'roomValue', + 'legacyRoomValue', + 'blurbValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchRoomFromRoomBlurbsLegacyRoomBlurbName', () => { + const result = + client.matchRoomFromRoomBlurbsLegacyRoomBlurbName(fakePath); + assert.strictEqual(result, 'roomValue'); + assert( + ( + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName', () => { + const result = + client.matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName(fakePath); + assert.strictEqual(result, 'legacyRoomValue'); + assert( + ( + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBlurbFromRoomBlurbsLegacyRoomBlurbName', () => { + const result = + client.matchBlurbFromRoomBlurbsLegacyRoomBlurbName(fakePath); + assert.strictEqual(result, 'blurbValue'); + assert( + ( + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('sequence', async () => { - const fakePath = "/rendered/path/sequence"; - const expectedParameters = { - sequence: "sequenceValue", - }; - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.sequencePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.sequencePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('sequencePath', () => { - const result = client.sequencePath("sequenceValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.sequencePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchSequenceFromSequenceName', () => { - const result = client.matchSequenceFromSequenceName(fakePath); - assert.strictEqual(result, "sequenceValue"); - assert((client.pathTemplates.sequencePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('sequence', async () => { + const fakePath = '/rendered/path/sequence'; + const expectedParameters = { + sequence: 'sequenceValue', + }; + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.sequencePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.sequencePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('sequencePath', () => { + const result = client.sequencePath('sequenceValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.sequencePathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchSequenceFromSequenceName', () => { + const result = client.matchSequenceFromSequenceName(fakePath); + assert.strictEqual(result, 'sequenceValue'); + assert( + (client.pathTemplates.sequencePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('sequenceReport', async () => { - const fakePath = "/rendered/path/sequenceReport"; - const expectedParameters = { - sequence: "sequenceValue", - }; - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.sequenceReportPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.sequenceReportPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('sequenceReportPath', () => { - const result = client.sequenceReportPath("sequenceValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.sequenceReportPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchSequenceFromSequenceReportName', () => { - const result = client.matchSequenceFromSequenceReportName(fakePath); - assert.strictEqual(result, "sequenceValue"); - assert((client.pathTemplates.sequenceReportPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('sequenceReport', async () => { + const fakePath = '/rendered/path/sequenceReport'; + const expectedParameters = { + sequence: 'sequenceValue', + }; + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.sequenceReportPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.sequenceReportPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('sequenceReportPath', () => { + const result = client.sequenceReportPath('sequenceValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.sequenceReportPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchSequenceFromSequenceReportName', () => { + const result = client.matchSequenceFromSequenceReportName(fakePath); + assert.strictEqual(result, 'sequenceValue'); + assert( + (client.pathTemplates.sequenceReportPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('session', async () => { - const fakePath = "/rendered/path/session"; - const expectedParameters = { - session: "sessionValue", - }; - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.sessionPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.sessionPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('sessionPath', () => { - const result = client.sessionPath("sessionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.sessionPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchSessionFromSessionName', () => { - const result = client.matchSessionFromSessionName(fakePath); - assert.strictEqual(result, "sessionValue"); - assert((client.pathTemplates.sessionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('session', async () => { + const fakePath = '/rendered/path/session'; + const expectedParameters = { + session: 'sessionValue', + }; + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.sessionPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.sessionPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('sessionPath', () => { + const result = client.sessionPath('sessionValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.sessionPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchSessionFromSessionName', () => { + const result = client.matchSessionFromSessionName(fakePath); + assert.strictEqual(result, 'sessionValue'); + assert( + (client.pathTemplates.sessionPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('test', async () => { - const fakePath = "/rendered/path/test"; - const expectedParameters = { - session: "sessionValue", - test: "testValue", - }; - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.testPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.testPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('testPath', () => { - const result = client.testPath("sessionValue", "testValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.testPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchSessionFromTestName', () => { - const result = client.matchSessionFromTestName(fakePath); - assert.strictEqual(result, "sessionValue"); - assert((client.pathTemplates.testPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchTestFromTestName', () => { - const result = client.matchTestFromTestName(fakePath); - assert.strictEqual(result, "testValue"); - assert((client.pathTemplates.testPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('test', async () => { + const fakePath = '/rendered/path/test'; + const expectedParameters = { + session: 'sessionValue', + test: 'testValue', + }; + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.testPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.testPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('testPath', () => { + const result = client.testPath('sessionValue', 'testValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.testPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchSessionFromTestName', () => { + const result = client.matchSessionFromTestName(fakePath); + assert.strictEqual(result, 'sessionValue'); + assert( + (client.pathTemplates.testPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchTestFromTestName', () => { + const result = client.matchTestFromTestName(fakePath); + assert.strictEqual(result, 'testValue'); + assert( + (client.pathTemplates.testPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('user', async () => { - const fakePath = "/rendered/path/user"; - const expectedParameters = { - user: "userValue", - }; - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.userPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.userPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('userPath', () => { - const result = client.userPath("userValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.userPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchUserFromUserName', () => { - const result = client.matchUserFromUserName(fakePath); - assert.strictEqual(result, "userValue"); - assert((client.pathTemplates.userPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('user', async () => { + const fakePath = '/rendered/path/user'; + const expectedParameters = { + user: 'userValue', + }; + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.userPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.userPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('userPath', () => { + const result = client.userPath('userValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.userPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchUserFromUserName', () => { + const result = client.matchUserFromUserName(fakePath); + assert.strictEqual(result, 'userValue'); + assert( + (client.pathTemplates.userPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('userProfileBlurb', async () => { - const fakePath = "/rendered/path/userProfileBlurb"; - const expectedParameters = { - user: "userValue", - blurb: "blurbValue", - }; - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.userProfileBlurbPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.userProfileBlurbPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('userProfileBlurbPath', () => { - const result = client.userProfileBlurbPath("userValue", "blurbValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.userProfileBlurbPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchUserFromUserProfileBlurbName', () => { - const result = client.matchUserFromUserProfileBlurbName(fakePath); - assert.strictEqual(result, "userValue"); - assert((client.pathTemplates.userProfileBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBlurbFromUserProfileBlurbName', () => { - const result = client.matchBlurbFromUserProfileBlurbName(fakePath); - assert.strictEqual(result, "blurbValue"); - assert((client.pathTemplates.userProfileBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('userProfileBlurb', async () => { + const fakePath = '/rendered/path/userProfileBlurb'; + const expectedParameters = { + user: 'userValue', + blurb: 'blurbValue', + }; + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.userProfileBlurbPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.userProfileBlurbPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('userProfileBlurbPath', () => { + const result = client.userProfileBlurbPath('userValue', 'blurbValue'); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.userProfileBlurbPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchUserFromUserProfileBlurbName', () => { + const result = client.matchUserFromUserProfileBlurbName(fakePath); + assert.strictEqual(result, 'userValue'); + assert( + (client.pathTemplates.userProfileBlurbPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBlurbFromUserProfileBlurbName', () => { + const result = client.matchBlurbFromUserProfileBlurbName(fakePath); + assert.strictEqual(result, 'blurbValue'); + assert( + (client.pathTemplates.userProfileBlurbPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('userProfileBlurbsLegacyUserBlurb', async () => { - const fakePath = "/rendered/path/userProfileBlurbsLegacyUserBlurb"; - const expectedParameters = { - user: "userValue", - legacy_user: "legacyUserValue", - blurb: "blurbValue", - }; - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('userProfileBlurbsLegacyUserBlurbPath', () => { - const result = client.userProfileBlurbsLegacyUserBlurbPath("userValue", "legacyUserValue", "blurbValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchUserFromUserProfileBlurbsLegacyUserBlurbName', () => { - const result = client.matchUserFromUserProfileBlurbsLegacyUserBlurbName(fakePath); - assert.strictEqual(result, "userValue"); - assert((client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName', () => { - const result = client.matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName(fakePath); - assert.strictEqual(result, "legacyUserValue"); - assert((client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBlurbFromUserProfileBlurbsLegacyUserBlurbName', () => { - const result = client.matchBlurbFromUserProfileBlurbsLegacyUserBlurbName(fakePath); - assert.strictEqual(result, "blurbValue"); - assert((client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('userProfileBlurbsLegacyUserBlurb', async () => { + const fakePath = '/rendered/path/userProfileBlurbsLegacyUserBlurb'; + const expectedParameters = { + user: 'userValue', + legacy_user: 'legacyUserValue', + blurb: 'blurbValue', + }; + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('userProfileBlurbsLegacyUserBlurbPath', () => { + const result = client.userProfileBlurbsLegacyUserBlurbPath( + 'userValue', + 'legacyUserValue', + 'blurbValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchUserFromUserProfileBlurbsLegacyUserBlurbName', () => { + const result = + client.matchUserFromUserProfileBlurbsLegacyUserBlurbName(fakePath); + assert.strictEqual(result, 'userValue'); + assert( + ( + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName', () => { + const result = + client.matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName( + fakePath, + ); + assert.strictEqual(result, 'legacyUserValue'); + assert( + ( + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBlurbFromUserProfileBlurbsLegacyUserBlurbName', () => { + const result = + client.matchBlurbFromUserProfileBlurbsLegacyUserBlurbName(fakePath); + assert.strictEqual(result, 'blurbValue'); + assert( + ( + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/core/generator/gapic-generator-typescript/baselines/disable-packing-test/test/gapic_messaging_v1beta1.ts.baseline b/core/generator/gapic-generator-typescript/baselines/disable-packing-test/test/gapic_messaging_v1beta1.ts.baseline index d7b2ff9708e6..450a955a3ddd 100644 --- a/core/generator/gapic-generator-typescript/baselines/disable-packing-test/test/gapic_messaging_v1beta1.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/disable-packing-test/test/gapic_messaging_v1beta1.ts.baseline @@ -19,2338 +19,2940 @@ import * as protos from '../protos/protos'; import * as assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as messagingModule from '../src'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; -import {protobuf, LROperation, operationsProtos} from 'google-gax'; +import { protobuf, LROperation, operationsProtos } from 'google-gax'; // Dynamically loaded proto JSON is needed to get the type information // to fill in default values for request objects -const root = protobuf.Root.fromJSON(require('../protos/protos.json')).resolveAll(); +const root = protobuf.Root.fromJSON( + require('../protos/protos.json'), +).resolveAll(); // eslint-disable-next-line @typescript-eslint/no-unused-vars function getTypeDefaultValue(typeName: string, fields: string[]) { - let type = root.lookupType(typeName) as protobuf.Type; - for (const field of fields.slice(0, -1)) { - type = type.fields[field]?.resolvedType as protobuf.Type; - } - return type.fields[fields[fields.length - 1]]?.defaultValue; + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type.fields[field]?.resolvedType as protobuf.Type; + } + return type.fields[fields[fields.length - 1]]?.defaultValue; } function generateSampleMessage(instance: T) { - const filledObject = (instance.constructor as typeof protobuf.Message) - .toObject(instance as protobuf.Message, {defaults: true}); - return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, { defaults: true }); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; } function stubSimpleCall(response?: ResponseType, error?: Error) { - return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); } -function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { - return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +function stubSimpleCallWithCallback( + response?: ResponseType, + error?: Error, +) { + return error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); } -function stubServerStreamingCall(response?: ResponseType, error?: Error) { - const transformStub = error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); - const mockStream = new PassThrough({ - objectMode: true, - transform: transformStub, - }); - // write something to the stream to trigger transformStub and send the response back to the client - setImmediate(() => { mockStream.write({}); }); - setImmediate(() => { mockStream.end(); }); - return sinon.stub().returns(mockStream); +function stubServerStreamingCall( + response?: ResponseType, + error?: Error, +) { + const transformStub = error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + // write something to the stream to trigger transformStub and send the response back to the client + setImmediate(() => { + mockStream.write({}); + }); + setImmediate(() => { + mockStream.end(); + }); + return sinon.stub().returns(mockStream); } -function stubBidiStreamingCall(response?: ResponseType, error?: Error) { - const transformStub = error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); - const mockStream = new PassThrough({ - objectMode: true, - transform: transformStub, - }); - return sinon.stub().returns(mockStream); +function stubBidiStreamingCall( + response?: ResponseType, + error?: Error, +) { + const transformStub = error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + return sinon.stub().returns(mockStream); } -function stubClientStreamingCall(response?: ResponseType, error?: Error) { - if (error) { - return sinon.stub().callsArgWith(2, error); - } - const transformStub = sinon.stub(); - const mockStream = new PassThrough({ - objectMode: true, - transform: transformStub, - }); - return sinon.stub().returns(mockStream).callsArgWith(2, null, response); +function stubClientStreamingCall( + response?: ResponseType, + error?: Error, +) { + if (error) { + return sinon.stub().callsArgWith(2, error); + } + const transformStub = sinon.stub(); + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + return sinon.stub().returns(mockStream).callsArgWith(2, null, response); } -function stubLongRunningCall(response?: ResponseType, callError?: Error, lroError?: Error) { - const innerStub = lroError ? sinon.stub().rejects(lroError) : sinon.stub().resolves([response]); - const mockOperation = { - promise: innerStub, - }; - return callError ? sinon.stub().rejects(callError) : sinon.stub().resolves([mockOperation]); +function stubLongRunningCall( + response?: ResponseType, + callError?: Error, + lroError?: Error, +) { + const innerStub = lroError + ? sinon.stub().rejects(lroError) + : sinon.stub().resolves([response]); + const mockOperation = { + promise: innerStub, + }; + return callError + ? sinon.stub().rejects(callError) + : sinon.stub().resolves([mockOperation]); } -function stubLongRunningCallWithCallback(response?: ResponseType, callError?: Error, lroError?: Error) { - const innerStub = lroError ? sinon.stub().rejects(lroError) : sinon.stub().resolves([response]); - const mockOperation = { - promise: innerStub, - }; - return callError ? sinon.stub().callsArgWith(2, callError) : sinon.stub().callsArgWith(2, null, mockOperation); +function stubLongRunningCallWithCallback( + response?: ResponseType, + callError?: Error, + lroError?: Error, +) { + const innerStub = lroError + ? sinon.stub().rejects(lroError) + : sinon.stub().resolves([response]); + const mockOperation = { + promise: innerStub, + }; + return callError + ? sinon.stub().callsArgWith(2, callError) + : sinon.stub().callsArgWith(2, null, mockOperation); } -function stubPageStreamingCall(responses?: ResponseType[], error?: Error) { - const pagingStub = sinon.stub(); - if (responses) { - for (let i = 0; i < responses.length; ++i) { - pagingStub.onCall(i).callsArgWith(2, null, responses[i]); - } +function stubPageStreamingCall( + responses?: ResponseType[], + error?: Error, +) { + const pagingStub = sinon.stub(); + if (responses) { + for (let i = 0; i < responses.length; ++i) { + pagingStub.onCall(i).callsArgWith(2, null, responses[i]); } - const transformStub = error ? sinon.stub().callsArgWith(2, error) : pagingStub; - const mockStream = new PassThrough({ - objectMode: true, - transform: transformStub, - }); - // trigger as many responses as needed - if (responses) { - for (let i = 0; i < responses.length; ++i) { - setImmediate(() => { mockStream.write({}); }); - } - setImmediate(() => { mockStream.end(); }); - } else { - setImmediate(() => { mockStream.write({}); }); - setImmediate(() => { mockStream.end(); }); + } + const transformStub = error + ? sinon.stub().callsArgWith(2, error) + : pagingStub; + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + // trigger as many responses as needed + if (responses) { + for (let i = 0; i < responses.length; ++i) { + setImmediate(() => { + mockStream.write({}); + }); } - return sinon.stub().returns(mockStream); + setImmediate(() => { + mockStream.end(); + }); + } else { + setImmediate(() => { + mockStream.write({}); + }); + setImmediate(() => { + mockStream.end(); + }); + } + return sinon.stub().returns(mockStream); } -function stubAsyncIterationCall(responses?: ResponseType[], error?: Error) { - let counter = 0; - const asyncIterable = { - [Symbol.asyncIterator]() { - return { - async next() { - if (error) { - return Promise.reject(error); - } - if (counter >= responses!.length) { - return Promise.resolve({done: true, value: undefined}); - } - return Promise.resolve({done: false, value: responses![counter++]}); - } - }; - } - }; - return sinon.stub().returns(asyncIterable); +function stubAsyncIterationCall( + responses?: ResponseType[], + error?: Error, +) { + let counter = 0; + const asyncIterable = { + [Symbol.asyncIterator]() { + return { + async next() { + if (error) { + return Promise.reject(error); + } + if (counter >= responses!.length) { + return Promise.resolve({ done: true, value: undefined }); + } + return Promise.resolve({ done: false, value: responses![counter++] }); + }, + }; + }, + }; + return sinon.stub().returns(asyncIterable); } describe('v1beta1.MessagingClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new messagingModule.v1beta1.MessagingClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'localhost'); - }); - - it('has universeDomain', () => { - const client = new messagingModule.v1beta1.MessagingClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); - - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - it('throws DeprecationWarning if static servicePath is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const servicePath = messagingModule.v1beta1.MessagingClient.servicePath; - assert.strictEqual(servicePath, 'localhost'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = messagingModule.v1beta1.MessagingClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'localhost'); - assert(stub.called); - stub.restore(); - }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { new messagingModule.v1beta1.MessagingClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); - - it('has port', () => { - const port = messagingModule.v1beta1.MessagingClient.port; - assert(port); - assert(typeof port === 'number'); - }); - - it('should create a client with no option', () => { - const client = new messagingModule.v1beta1.MessagingClient(); - assert(client); - }); - - it('should create a client with gRPC fallback', () => { - const client = new messagingModule.v1beta1.MessagingClient({ - fallback: true, - }); - assert(client); - }); - - it('has initialize method and supports deferred initialization', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.messagingStub, undefined); - await client.initialize(); - assert(client.messagingStub); - }); - - it('has close method for the initialized client', done => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.messagingStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); - - it('has close method for the non-initialized client', done => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.messagingStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); - - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); - }); - - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId((err?: Error|null, projectId?: string|null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } - }); - }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new messagingModule.v1beta1.MessagingClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'localhost'); }); - describe('createRoom', () => { - it('invokes createRoom without error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.CreateRoomRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.Room() - ); - client.innerApiCalls.createRoom = stubSimpleCall(expectedResponse); - const [response] = await client.createRoom(request); - assert.deepStrictEqual(response, expectedResponse); - }); - - it('invokes createRoom without error using callback', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.CreateRoomRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.Room() - ); - client.innerApiCalls.createRoom = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createRoom( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IRoom|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); + it('has universeDomain', () => { + const client = new messagingModule.v1beta1.MessagingClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - it('invokes createRoom with error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.CreateRoomRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.createRoom = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createRoom(request), expectedError); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = messagingModule.v1beta1.MessagingClient.servicePath; + assert.strictEqual(servicePath, 'localhost'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = messagingModule.v1beta1.MessagingClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'localhost'); + assert(stub.called); + stub.restore(); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new messagingModule.v1beta1.MessagingClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); + }); - it('invokes createRoom with closed client', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.CreateRoomRequest() - ); - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createRoom(request), expectedError); - }); + it('has port', () => { + const port = messagingModule.v1beta1.MessagingClient.port; + assert(port); + assert(typeof port === 'number'); }); - describe('getRoom', () => { - it('invokes getRoom without error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.GetRoomRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.GetRoomRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.Room() - ); - client.innerApiCalls.getRoom = stubSimpleCall(expectedResponse); - const [response] = await client.getRoom(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getRoom as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getRoom as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('should create a client with no option', () => { + const client = new messagingModule.v1beta1.MessagingClient(); + assert(client); + }); - it('invokes getRoom without error using callback', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.GetRoomRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.GetRoomRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.Room() - ); - client.innerApiCalls.getRoom = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getRoom( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IRoom|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getRoom as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getRoom as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('should create a client with gRPC fallback', () => { + const client = new messagingModule.v1beta1.MessagingClient({ + fallback: true, + }); + assert(client); + }); - it('invokes getRoom with error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.GetRoomRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.GetRoomRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getRoom = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getRoom(request), expectedError); - const actualRequest = (client.innerApiCalls.getRoom as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getRoom as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has initialize method and supports deferred initialization', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.messagingStub, undefined); + await client.initialize(); + assert(client.messagingStub); + }); - it('invokes getRoom with closed client', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.GetRoomRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.GetRoomRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getRoom(request), expectedError); + it('has close method for the initialized client', (done) => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.messagingStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); }); - describe('updateRoom', () => { - it('invokes updateRoom without error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.UpdateRoomRequest() - ); - request.room ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.UpdateRoomRequest', ['room', 'name']); - request.room.name = defaultValue1; - const expectedHeaderRequestParams = `room.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.Room() - ); - client.innerApiCalls.updateRoom = stubSimpleCall(expectedResponse); - const [response] = await client.updateRoom(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateRoom as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateRoom as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('has close method for the non-initialized client', (done) => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.messagingStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes updateRoom without error using callback', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.UpdateRoomRequest() - ); - request.room ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.UpdateRoomRequest', ['room', 'name']); - request.room.name = defaultValue1; - const expectedHeaderRequestParams = `room.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.Room() - ); - client.innerApiCalls.updateRoom = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateRoom( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IRoom|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateRoom as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateRoom as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + }); - it('invokes updateRoom with error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.UpdateRoomRequest() - ); - request.room ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.UpdateRoomRequest', ['room', 'name']); - request.room.name = defaultValue1; - const expectedHeaderRequestParams = `room.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateRoom = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateRoom(request), expectedError); - const actualRequest = (client.innerApiCalls.updateRoom as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateRoom as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } + }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + }); + + describe('createRoom', () => { + it('invokes createRoom without error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.CreateRoomRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.Room(), + ); + client.innerApiCalls.createRoom = stubSimpleCall(expectedResponse); + const [response] = await client.createRoom(request); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes updateRoom with closed client', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.UpdateRoomRequest() - ); - request.room ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.UpdateRoomRequest', ['room', 'name']); - request.room.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateRoom(request), expectedError); - }); + it('invokes createRoom without error using callback', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.CreateRoomRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.Room(), + ); + client.innerApiCalls.createRoom = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createRoom( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IRoom | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); }); - describe('deleteRoom', () => { - it('invokes deleteRoom without error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.DeleteRoomRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.DeleteRoomRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteRoom = stubSimpleCall(expectedResponse); - const [response] = await client.deleteRoom(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteRoom as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteRoom as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createRoom with error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.CreateRoomRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.createRoom = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.createRoom(request), expectedError); + }); - it('invokes deleteRoom without error using callback', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.DeleteRoomRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.DeleteRoomRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteRoom = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteRoom( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteRoom as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteRoom as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createRoom with closed client', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.CreateRoomRequest(), + ); + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.createRoom(request), expectedError); + }); + }); + + describe('getRoom', () => { + it('invokes getRoom without error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.GetRoomRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.GetRoomRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.Room(), + ); + client.innerApiCalls.getRoom = stubSimpleCall(expectedResponse); + const [response] = await client.getRoom(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.getRoom as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getRoom as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteRoom with error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.DeleteRoomRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.DeleteRoomRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteRoom = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteRoom(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteRoom as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteRoom as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getRoom without error using callback', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.GetRoomRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.GetRoomRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.Room(), + ); + client.innerApiCalls.getRoom = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getRoom( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IRoom | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.getRoom as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getRoom as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteRoom with closed client', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.DeleteRoomRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.DeleteRoomRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteRoom(request), expectedError); - }); + it('invokes getRoom with error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.GetRoomRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.GetRoomRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getRoom = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.getRoom(request), expectedError); + const actualRequest = (client.innerApiCalls.getRoom as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getRoom as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('createBlurb', () => { - it('invokes createBlurb without error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.CreateBlurbRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.CreateBlurbRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.Blurb() - ); - client.innerApiCalls.createBlurb = stubSimpleCall(expectedResponse); - const [response] = await client.createBlurb(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createBlurb as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createBlurb as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getRoom with closed client', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.GetRoomRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.GetRoomRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getRoom(request), expectedError); + }); + }); + + describe('updateRoom', () => { + it('invokes updateRoom without error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.UpdateRoomRequest(), + ); + request.room ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.UpdateRoomRequest', + ['room', 'name'], + ); + request.room.name = defaultValue1; + const expectedHeaderRequestParams = `room.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.Room(), + ); + client.innerApiCalls.updateRoom = stubSimpleCall(expectedResponse); + const [response] = await client.updateRoom(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateRoom as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateRoom as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createBlurb without error using callback', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.CreateBlurbRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.CreateBlurbRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.Blurb() - ); - client.innerApiCalls.createBlurb = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createBlurb( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IBlurb|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createBlurb as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createBlurb as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateRoom without error using callback', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.UpdateRoomRequest(), + ); + request.room ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.UpdateRoomRequest', + ['room', 'name'], + ); + request.room.name = defaultValue1; + const expectedHeaderRequestParams = `room.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.Room(), + ); + client.innerApiCalls.updateRoom = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateRoom( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IRoom | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateRoom as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateRoom as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createBlurb with error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.CreateBlurbRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.CreateBlurbRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createBlurb = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createBlurb(request), expectedError); - const actualRequest = (client.innerApiCalls.createBlurb as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createBlurb as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateRoom with error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.UpdateRoomRequest(), + ); + request.room ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.UpdateRoomRequest', + ['room', 'name'], + ); + request.room.name = defaultValue1; + const expectedHeaderRequestParams = `room.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateRoom = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.updateRoom(request), expectedError); + const actualRequest = ( + client.innerApiCalls.updateRoom as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateRoom as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createBlurb with closed client', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.CreateBlurbRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.CreateBlurbRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createBlurb(request), expectedError); - }); + it('invokes updateRoom with closed client', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.UpdateRoomRequest(), + ); + request.room ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.UpdateRoomRequest', + ['room', 'name'], + ); + request.room.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.updateRoom(request), expectedError); + }); + }); + + describe('deleteRoom', () => { + it('invokes deleteRoom without error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.DeleteRoomRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.DeleteRoomRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteRoom = stubSimpleCall(expectedResponse); + const [response] = await client.deleteRoom(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteRoom as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteRoom as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('getBlurb', () => { - it('invokes getBlurb without error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.GetBlurbRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.GetBlurbRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.Blurb() - ); - client.innerApiCalls.getBlurb = stubSimpleCall(expectedResponse); - const [response] = await client.getBlurb(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getBlurb as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getBlurb as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteRoom without error using callback', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.DeleteRoomRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.DeleteRoomRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteRoom = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteRoom( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteRoom as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteRoom as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getBlurb without error using callback', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.GetBlurbRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.GetBlurbRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.Blurb() - ); - client.innerApiCalls.getBlurb = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getBlurb( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IBlurb|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getBlurb as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getBlurb as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteRoom with error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.DeleteRoomRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.DeleteRoomRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteRoom = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.deleteRoom(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteRoom as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteRoom as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getBlurb with error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.GetBlurbRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.GetBlurbRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getBlurb = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getBlurb(request), expectedError); - const actualRequest = (client.innerApiCalls.getBlurb as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getBlurb as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteRoom with closed client', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.DeleteRoomRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.DeleteRoomRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.deleteRoom(request), expectedError); + }); + }); + + describe('createBlurb', () => { + it('invokes createBlurb without error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.CreateBlurbRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.CreateBlurbRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.Blurb(), + ); + client.innerApiCalls.createBlurb = stubSimpleCall(expectedResponse); + const [response] = await client.createBlurb(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createBlurb as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createBlurb as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getBlurb with closed client', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.GetBlurbRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.GetBlurbRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getBlurb(request), expectedError); - }); + it('invokes createBlurb without error using callback', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.CreateBlurbRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.CreateBlurbRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.Blurb(), + ); + client.innerApiCalls.createBlurb = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createBlurb( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IBlurb | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createBlurb as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createBlurb as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('updateBlurb', () => { - it('invokes updateBlurb without error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.UpdateBlurbRequest() - ); - request.blurb ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.UpdateBlurbRequest', ['blurb', 'name']); - request.blurb.name = defaultValue1; - const expectedHeaderRequestParams = `blurb.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.Blurb() - ); - client.innerApiCalls.updateBlurb = stubSimpleCall(expectedResponse); - const [response] = await client.updateBlurb(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateBlurb as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateBlurb as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createBlurb with error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.CreateBlurbRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.CreateBlurbRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createBlurb = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.createBlurb(request), expectedError); + const actualRequest = ( + client.innerApiCalls.createBlurb as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createBlurb as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateBlurb without error using callback', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.UpdateBlurbRequest() - ); - request.blurb ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.UpdateBlurbRequest', ['blurb', 'name']); - request.blurb.name = defaultValue1; - const expectedHeaderRequestParams = `blurb.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.Blurb() - ); - client.innerApiCalls.updateBlurb = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateBlurb( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IBlurb|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateBlurb as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateBlurb as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createBlurb with closed client', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.CreateBlurbRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.CreateBlurbRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.createBlurb(request), expectedError); + }); + }); + + describe('getBlurb', () => { + it('invokes getBlurb without error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.GetBlurbRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.GetBlurbRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.Blurb(), + ); + client.innerApiCalls.getBlurb = stubSimpleCall(expectedResponse); + const [response] = await client.getBlurb(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getBlurb as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getBlurb as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateBlurb with error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.UpdateBlurbRequest() - ); - request.blurb ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.UpdateBlurbRequest', ['blurb', 'name']); - request.blurb.name = defaultValue1; - const expectedHeaderRequestParams = `blurb.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateBlurb = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateBlurb(request), expectedError); - const actualRequest = (client.innerApiCalls.updateBlurb as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateBlurb as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getBlurb without error using callback', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.GetBlurbRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.GetBlurbRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.Blurb(), + ); + client.innerApiCalls.getBlurb = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getBlurb( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IBlurb | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getBlurb as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getBlurb as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateBlurb with closed client', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.UpdateBlurbRequest() - ); - request.blurb ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.UpdateBlurbRequest', ['blurb', 'name']); - request.blurb.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateBlurb(request), expectedError); - }); + it('invokes getBlurb with error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.GetBlurbRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.GetBlurbRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getBlurb = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.getBlurb(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getBlurb as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getBlurb as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('deleteBlurb', () => { - it('invokes deleteBlurb without error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.DeleteBlurbRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.DeleteBlurbRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteBlurb = stubSimpleCall(expectedResponse); - const [response] = await client.deleteBlurb(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteBlurb as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteBlurb as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getBlurb with closed client', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.GetBlurbRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.GetBlurbRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getBlurb(request), expectedError); + }); + }); + + describe('updateBlurb', () => { + it('invokes updateBlurb without error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.UpdateBlurbRequest(), + ); + request.blurb ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.UpdateBlurbRequest', + ['blurb', 'name'], + ); + request.blurb.name = defaultValue1; + const expectedHeaderRequestParams = `blurb.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.Blurb(), + ); + client.innerApiCalls.updateBlurb = stubSimpleCall(expectedResponse); + const [response] = await client.updateBlurb(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateBlurb as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateBlurb as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteBlurb without error using callback', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.DeleteBlurbRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.DeleteBlurbRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteBlurb = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteBlurb( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteBlurb as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteBlurb as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateBlurb without error using callback', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.UpdateBlurbRequest(), + ); + request.blurb ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.UpdateBlurbRequest', + ['blurb', 'name'], + ); + request.blurb.name = defaultValue1; + const expectedHeaderRequestParams = `blurb.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.Blurb(), + ); + client.innerApiCalls.updateBlurb = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateBlurb( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IBlurb | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateBlurb as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateBlurb as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteBlurb with error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.DeleteBlurbRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.DeleteBlurbRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteBlurb = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteBlurb(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteBlurb as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteBlurb as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateBlurb with error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.UpdateBlurbRequest(), + ); + request.blurb ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.UpdateBlurbRequest', + ['blurb', 'name'], + ); + request.blurb.name = defaultValue1; + const expectedHeaderRequestParams = `blurb.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateBlurb = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.updateBlurb(request), expectedError); + const actualRequest = ( + client.innerApiCalls.updateBlurb as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateBlurb as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteBlurb with closed client', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.DeleteBlurbRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.DeleteBlurbRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteBlurb(request), expectedError); - }); + it('invokes updateBlurb with closed client', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.UpdateBlurbRequest(), + ); + request.blurb ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.UpdateBlurbRequest', + ['blurb', 'name'], + ); + request.blurb.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.updateBlurb(request), expectedError); + }); + }); + + describe('deleteBlurb', () => { + it('invokes deleteBlurb without error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.DeleteBlurbRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.DeleteBlurbRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteBlurb = stubSimpleCall(expectedResponse); + const [response] = await client.deleteBlurb(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteBlurb as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteBlurb as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('searchBlurbs', () => { - it('invokes searchBlurbs without error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.SearchBlurbsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.SearchBlurbsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.searchBlurbs = stubLongRunningCall(expectedResponse); - const [operation] = await client.searchBlurbs(request); - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.searchBlurbs as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.searchBlurbs as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteBlurb without error using callback', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.DeleteBlurbRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.DeleteBlurbRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteBlurb = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteBlurb( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteBlurb as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteBlurb as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes searchBlurbs without error using callback', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.SearchBlurbsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.SearchBlurbsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.searchBlurbs = stubLongRunningCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.searchBlurbs( - request, - (err?: Error|null, - result?: LROperation|null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const operation = await promise as LROperation; - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.searchBlurbs as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.searchBlurbs as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteBlurb with error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.DeleteBlurbRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.DeleteBlurbRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteBlurb = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.deleteBlurb(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteBlurb as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteBlurb as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes searchBlurbs with call error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.SearchBlurbsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.SearchBlurbsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.searchBlurbs = stubLongRunningCall(undefined, expectedError); - await assert.rejects(client.searchBlurbs(request), expectedError); - const actualRequest = (client.innerApiCalls.searchBlurbs as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.searchBlurbs as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteBlurb with closed client', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.DeleteBlurbRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.DeleteBlurbRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.deleteBlurb(request), expectedError); + }); + }); + + describe('searchBlurbs', () => { + it('invokes searchBlurbs without error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.SearchBlurbsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.SearchBlurbsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.searchBlurbs = stubLongRunningCall(expectedResponse); + const [operation] = await client.searchBlurbs(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.searchBlurbs as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.searchBlurbs as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes searchBlurbs with LRO error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.SearchBlurbsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.SearchBlurbsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.searchBlurbs = stubLongRunningCall(undefined, undefined, expectedError); - const [operation] = await client.searchBlurbs(request); - await assert.rejects(operation.promise(), expectedError); - const actualRequest = (client.innerApiCalls.searchBlurbs as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.searchBlurbs as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes searchBlurbs without error using callback', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.SearchBlurbsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.SearchBlurbsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.searchBlurbs = + stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.searchBlurbs( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.showcase.v1beta1.ISearchBlurbsResponse, + protos.google.showcase.v1beta1.ISearchBlurbsMetadata + > | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const operation = (await promise) as LROperation< + protos.google.showcase.v1beta1.ISearchBlurbsResponse, + protos.google.showcase.v1beta1.ISearchBlurbsMetadata + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.searchBlurbs as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.searchBlurbs as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkSearchBlurbsProgress without error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedResponse = generateSampleMessage( - new operationsProtos.google.longrunning.Operation() - ); - expectedResponse.name = 'test'; - expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; - expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')} - - client.operationsClient.getOperation = stubSimpleCall(expectedResponse); - const decodedOperation = await client.checkSearchBlurbsProgress(expectedResponse.name); - assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); - assert(decodedOperation.metadata); - assert((client.operationsClient.getOperation as SinonStub).getCall(0)); - }); + it('invokes searchBlurbs with call error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.SearchBlurbsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.SearchBlurbsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.searchBlurbs = stubLongRunningCall( + undefined, + expectedError, + ); + await assert.rejects(client.searchBlurbs(request), expectedError); + const actualRequest = ( + client.innerApiCalls.searchBlurbs as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.searchBlurbs as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkSearchBlurbsProgress with error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedError = new Error('expected'); - - client.operationsClient.getOperation = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.checkSearchBlurbsProgress(''), expectedError); - assert((client.operationsClient.getOperation as SinonStub) - .getCall(0)); - }); + it('invokes searchBlurbs with LRO error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.SearchBlurbsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.SearchBlurbsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.searchBlurbs = stubLongRunningCall( + undefined, + undefined, + expectedError, + ); + const [operation] = await client.searchBlurbs(request); + await assert.rejects(operation.promise(), expectedError); + const actualRequest = ( + client.innerApiCalls.searchBlurbs as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.searchBlurbs as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('streamBlurbs', () => { - it('invokes streamBlurbs without error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.StreamBlurbsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.StreamBlurbsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.StreamBlurbsResponse() - ); - client.innerApiCalls.streamBlurbs = stubServerStreamingCall(expectedResponse); - const stream = client.streamBlurbs(request); - const promise = new Promise((resolve, reject) => { - stream.on('data', (response: protos.google.showcase.v1beta1.StreamBlurbsResponse) => { - resolve(response); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.streamBlurbs as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.streamBlurbs as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes checkSearchBlurbsProgress without error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation(), + ); + expectedResponse.name = 'test'; + expectedResponse.response = { type_url: 'url', value: Buffer.from('') }; + expectedResponse.metadata = { type_url: 'url', value: Buffer.from('') }; + + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const decodedOperation = await client.checkSearchBlurbsProgress( + expectedResponse.name, + ); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); - it('invokes streamBlurbs without error and gaxServerStreamingRetries enabled', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - gaxServerStreamingRetries: true - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.StreamBlurbsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.StreamBlurbsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.StreamBlurbsResponse() - ); - client.innerApiCalls.streamBlurbs = stubServerStreamingCall(expectedResponse); - const stream = client.streamBlurbs(request); - const promise = new Promise((resolve, reject) => { - stream.on('data', (response: protos.google.showcase.v1beta1.StreamBlurbsResponse) => { - resolve(response); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.streamBlurbs as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.streamBlurbs as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes checkSearchBlurbsProgress with error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const expectedError = new Error('expected'); + + client.operationsClient.getOperation = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.checkSearchBlurbsProgress(''), expectedError); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + }); + + describe('streamBlurbs', () => { + it('invokes streamBlurbs without error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.StreamBlurbsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.StreamBlurbsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.StreamBlurbsResponse(), + ); + client.innerApiCalls.streamBlurbs = + stubServerStreamingCall(expectedResponse); + const stream = client.streamBlurbs(request); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + (response: protos.google.showcase.v1beta1.StreamBlurbsResponse) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.streamBlurbs as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.streamBlurbs as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes streamBlurbs with error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.StreamBlurbsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.StreamBlurbsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.streamBlurbs = stubServerStreamingCall(undefined, expectedError); - const stream = client.streamBlurbs(request); - const promise = new Promise((resolve, reject) => { - stream.on('data', (response: protos.google.showcase.v1beta1.StreamBlurbsResponse) => { - resolve(response); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - const actualRequest = (client.innerApiCalls.streamBlurbs as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.streamBlurbs as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes streamBlurbs without error and gaxServerStreamingRetries enabled', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + gaxServerStreamingRetries: true, + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.StreamBlurbsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.StreamBlurbsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.StreamBlurbsResponse(), + ); + client.innerApiCalls.streamBlurbs = + stubServerStreamingCall(expectedResponse); + const stream = client.streamBlurbs(request); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + (response: protos.google.showcase.v1beta1.StreamBlurbsResponse) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.streamBlurbs as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.streamBlurbs as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes streamBlurbs with closed client', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.StreamBlurbsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.StreamBlurbsRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - const stream = client.streamBlurbs(request, {retryRequestOptions: {noResponseRetries: 0}}); - const promise = new Promise((resolve, reject) => { - stream.on('data', (response: protos.google.showcase.v1beta1.StreamBlurbsResponse) => { - resolve(response); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - }); - it('should create a client with gaxServerStreamingRetries enabled', () => { - const client = new messagingModule.v1beta1.MessagingClient({ - gaxServerStreamingRetries: true, - }); - assert(client); - }); + it('invokes streamBlurbs with error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.StreamBlurbsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.StreamBlurbsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.streamBlurbs = stubServerStreamingCall( + undefined, + expectedError, + ); + const stream = client.streamBlurbs(request); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + (response: protos.google.showcase.v1beta1.StreamBlurbsResponse) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + const actualRequest = ( + client.innerApiCalls.streamBlurbs as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.streamBlurbs as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('connect', () => { - it('invokes connect without error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ConnectRequest() - ); - - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.StreamBlurbsResponse() - ); - client.innerApiCalls.connect = stubBidiStreamingCall(expectedResponse); - const stream = client.connect(); - const promise = new Promise((resolve, reject) => { - stream.on('data', (response: protos.google.showcase.v1beta1.StreamBlurbsResponse) => { - resolve(response); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - stream.write(request); - stream.end(); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - assert((client.innerApiCalls.connect as SinonStub) - .getCall(0).calledWith(null)); - assert.deepStrictEqual(((stream as unknown as PassThrough) - ._transform as SinonStub).getCall(0).args[0], request); - }); + it('invokes streamBlurbs with closed client', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.StreamBlurbsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.StreamBlurbsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + const stream = client.streamBlurbs(request, { + retryRequestOptions: { noResponseRetries: 0 }, + }); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + (response: protos.google.showcase.v1beta1.StreamBlurbsResponse) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + }); + it('should create a client with gaxServerStreamingRetries enabled', () => { + const client = new messagingModule.v1beta1.MessagingClient({ + gaxServerStreamingRetries: true, + }); + assert(client); + }); + }); + + describe('connect', () => { + it('invokes connect without error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ConnectRequest(), + ); + + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.StreamBlurbsResponse(), + ); + client.innerApiCalls.connect = stubBidiStreamingCall(expectedResponse); + const stream = client.connect(); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + (response: protos.google.showcase.v1beta1.StreamBlurbsResponse) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); + }); + stream.write(request); + stream.end(); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + assert( + (client.innerApiCalls.connect as SinonStub).getCall(0).calledWith(null), + ); + assert.deepStrictEqual( + ((stream as unknown as PassThrough)._transform as SinonStub).getCall(0) + .args[0], + request, + ); + }); - it('invokes connect with error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ConnectRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.connect = stubBidiStreamingCall(undefined, expectedError); - const stream = client.connect(); - const promise = new Promise((resolve, reject) => { - stream.on('data', (response: protos.google.showcase.v1beta1.StreamBlurbsResponse) => { - resolve(response); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - stream.write(request); - stream.end(); - }); - await assert.rejects(promise, expectedError); - assert((client.innerApiCalls.connect as SinonStub) - .getCall(0).calledWith(null)); - assert.deepStrictEqual(((stream as unknown as PassThrough) - ._transform as SinonStub).getCall(0).args[0], request); - }); + it('invokes connect with error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ConnectRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.connect = stubBidiStreamingCall( + undefined, + expectedError, + ); + const stream = client.connect(); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + (response: protos.google.showcase.v1beta1.StreamBlurbsResponse) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); + }); + stream.write(request); + stream.end(); + }); + await assert.rejects(promise, expectedError); + assert( + (client.innerApiCalls.connect as SinonStub).getCall(0).calledWith(null), + ); + assert.deepStrictEqual( + ((stream as unknown as PassThrough)._transform as SinonStub).getCall(0) + .args[0], + request, + ); + }); + }); + + describe('sendBlurbs', () => { + it('invokes sendBlurbs without error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.CreateBlurbRequest(), + ); + + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.SendBlurbsResponse(), + ); + client.innerApiCalls.sendBlurbs = + stubClientStreamingCall(expectedResponse); + let stream: PassThrough; + const promise = new Promise((resolve, reject) => { + stream = client.sendBlurbs( + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.ISendBlurbsResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ) as unknown as PassThrough; + stream.write(request); + stream.end(); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + assert( + (client.innerApiCalls.sendBlurbs as SinonStub) + .getCall(0) + .calledWith(null, {} /*, callback defined above */), + ); + assert.deepStrictEqual( + (stream!._transform as SinonStub).getCall(0).args[0], + request, + ); }); - describe('sendBlurbs', () => { - it('invokes sendBlurbs without error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.CreateBlurbRequest() - ); - - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.SendBlurbsResponse() - ); - client.innerApiCalls.sendBlurbs = stubClientStreamingCall(expectedResponse); - let stream: PassThrough; - const promise = new Promise((resolve, reject) => { - stream = client.sendBlurbs( - (err?: Error|null, result?: protos.google.showcase.v1beta1.ISendBlurbsResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }) as unknown as PassThrough; - stream.write(request); - stream.end(); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - assert((client.innerApiCalls.sendBlurbs as SinonStub) - .getCall(0).calledWith(null, {} /*, callback defined above */)); - assert.deepStrictEqual((stream!._transform as SinonStub).getCall(0).args[0], request); - }); + it('invokes sendBlurbs with error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.CreateBlurbRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.sendBlurbs = stubClientStreamingCall( + undefined, + expectedError, + ); + let stream: PassThrough; + const promise = new Promise((resolve, reject) => { + stream = client.sendBlurbs( + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.ISendBlurbsResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ) as unknown as PassThrough; + stream.write(request); + stream.end(); + }); + await assert.rejects(promise, expectedError); + assert( + (client.innerApiCalls.sendBlurbs as SinonStub) + .getCall(0) + .calledWith(null, {} /*, callback defined above */), + ); + }); + }); + + describe('listRooms', () => { + it('invokes listRooms without error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListRoomsRequest(), + ); + const expectedResponse = [ + generateSampleMessage(new protos.google.showcase.v1beta1.Room()), + generateSampleMessage(new protos.google.showcase.v1beta1.Room()), + generateSampleMessage(new protos.google.showcase.v1beta1.Room()), + ]; + client.innerApiCalls.listRooms = stubSimpleCall(expectedResponse); + const [response] = await client.listRooms(request); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes sendBlurbs with error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.CreateBlurbRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.sendBlurbs = stubClientStreamingCall(undefined, expectedError); - let stream: PassThrough; - const promise = new Promise((resolve, reject) => { - stream = client.sendBlurbs( - (err?: Error|null, result?: protos.google.showcase.v1beta1.ISendBlurbsResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }) as unknown as PassThrough; - stream.write(request); - stream.end(); - }); - await assert.rejects(promise, expectedError); - assert((client.innerApiCalls.sendBlurbs as SinonStub) - .getCall(0).calledWith(null, {} /*, callback defined above */)); - }); + it('invokes listRooms without error using callback', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListRoomsRequest(), + ); + const expectedResponse = [ + generateSampleMessage(new protos.google.showcase.v1beta1.Room()), + generateSampleMessage(new protos.google.showcase.v1beta1.Room()), + generateSampleMessage(new protos.google.showcase.v1beta1.Room()), + ]; + client.innerApiCalls.listRooms = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listRooms( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IRoom[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); }); - describe('listRooms', () => { - it('invokes listRooms without error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListRoomsRequest() - );const expectedResponse = [ - generateSampleMessage(new protos.google.showcase.v1beta1.Room()), - generateSampleMessage(new protos.google.showcase.v1beta1.Room()), - generateSampleMessage(new protos.google.showcase.v1beta1.Room()), - ]; - client.innerApiCalls.listRooms = stubSimpleCall(expectedResponse); - const [response] = await client.listRooms(request); - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes listRooms with error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListRoomsRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.listRooms = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.listRooms(request), expectedError); + }); - it('invokes listRooms without error using callback', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListRoomsRequest() - );const expectedResponse = [ - generateSampleMessage(new protos.google.showcase.v1beta1.Room()), - generateSampleMessage(new protos.google.showcase.v1beta1.Room()), - generateSampleMessage(new protos.google.showcase.v1beta1.Room()), - ]; - client.innerApiCalls.listRooms = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listRooms( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IRoom[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes listRoomsStream without error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListRoomsRequest(), + ); + const expectedResponse = [ + generateSampleMessage(new protos.google.showcase.v1beta1.Room()), + generateSampleMessage(new protos.google.showcase.v1beta1.Room()), + generateSampleMessage(new protos.google.showcase.v1beta1.Room()), + ]; + client.descriptors.page.listRooms.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listRoomsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.showcase.v1beta1.Room[] = []; + stream.on('data', (response: protos.google.showcase.v1beta1.Room) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listRooms.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listRooms, request), + ); + }); - it('invokes listRooms with error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListRoomsRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.listRooms = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listRooms(request), expectedError); - }); + it('invokes listRoomsStream with error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListRoomsRequest(), + ); + const expectedError = new Error('expected'); + client.descriptors.page.listRooms.createStream = stubPageStreamingCall( + undefined, + expectedError, + ); + const stream = client.listRoomsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.showcase.v1beta1.Room[] = []; + stream.on('data', (response: protos.google.showcase.v1beta1.Room) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listRooms.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listRooms, request), + ); + }); - it('invokes listRoomsStream without error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListRoomsRequest() - ); - const expectedResponse = [ - generateSampleMessage(new protos.google.showcase.v1beta1.Room()), - generateSampleMessage(new protos.google.showcase.v1beta1.Room()), - generateSampleMessage(new protos.google.showcase.v1beta1.Room()), - ]; - client.descriptors.page.listRooms.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listRoomsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.showcase.v1beta1.Room[] = []; - stream.on('data', (response: protos.google.showcase.v1beta1.Room) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.listRooms.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listRooms, request)); - }); + it('uses async iteration with listRooms without error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListRoomsRequest(), + ); + const expectedResponse = [ + generateSampleMessage(new protos.google.showcase.v1beta1.Room()), + generateSampleMessage(new protos.google.showcase.v1beta1.Room()), + generateSampleMessage(new protos.google.showcase.v1beta1.Room()), + ]; + client.descriptors.page.listRooms.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.showcase.v1beta1.IRoom[] = []; + const iterable = client.listRoomsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + (client.descriptors.page.listRooms.asyncIterate as SinonStub).getCall(0) + .args[1], + request, + ); + }); - it('invokes listRoomsStream with error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListRoomsRequest() - ); - const expectedError = new Error('expected'); - client.descriptors.page.listRooms.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listRoomsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.showcase.v1beta1.Room[] = []; - stream.on('data', (response: protos.google.showcase.v1beta1.Room) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listRooms.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listRooms, request)); - }); + it('uses async iteration with listRooms with error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListRoomsRequest(), + ); + const expectedError = new Error('expected'); + client.descriptors.page.listRooms.asyncIterate = stubAsyncIterationCall( + undefined, + expectedError, + ); + const iterable = client.listRoomsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.showcase.v1beta1.IRoom[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + (client.descriptors.page.listRooms.asyncIterate as SinonStub).getCall(0) + .args[1], + request, + ); + }); + }); + + describe('listBlurbs', () => { + it('invokes listBlurbs without error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListBlurbsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.ListBlurbsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.showcase.v1beta1.Blurb()), + generateSampleMessage(new protos.google.showcase.v1beta1.Blurb()), + generateSampleMessage(new protos.google.showcase.v1beta1.Blurb()), + ]; + client.innerApiCalls.listBlurbs = stubSimpleCall(expectedResponse); + const [response] = await client.listBlurbs(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listBlurbs as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listBlurbs as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('uses async iteration with listRooms without error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListRoomsRequest() - ); - const expectedResponse = [ - generateSampleMessage(new protos.google.showcase.v1beta1.Room()), - generateSampleMessage(new protos.google.showcase.v1beta1.Room()), - generateSampleMessage(new protos.google.showcase.v1beta1.Room()), - ]; - client.descriptors.page.listRooms.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.showcase.v1beta1.IRoom[] = []; - const iterable = client.listRoomsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); + it('invokes listBlurbs without error using callback', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListBlurbsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.ListBlurbsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.showcase.v1beta1.Blurb()), + generateSampleMessage(new protos.google.showcase.v1beta1.Blurb()), + generateSampleMessage(new protos.google.showcase.v1beta1.Blurb()), + ]; + client.innerApiCalls.listBlurbs = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listBlurbs( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IBlurb[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listRooms.asyncIterate as SinonStub) - .getCall(0).args[1], request); - }); - - it('uses async iteration with listRooms with error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListRoomsRequest() - ); - const expectedError = new Error('expected'); - client.descriptors.page.listRooms.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listRoomsAsync(request); - await assert.rejects(async () => { - const responses: protos.google.showcase.v1beta1.IRoom[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listRooms.asyncIterate as SinonStub) - .getCall(0).args[1], request); - }); + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listBlurbs as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listBlurbs as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('listBlurbs', () => { - it('invokes listBlurbs without error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListBlurbsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.ListBlurbsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.showcase.v1beta1.Blurb()), - generateSampleMessage(new protos.google.showcase.v1beta1.Blurb()), - generateSampleMessage(new protos.google.showcase.v1beta1.Blurb()), - ]; - client.innerApiCalls.listBlurbs = stubSimpleCall(expectedResponse); - const [response] = await client.listBlurbs(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listBlurbs as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listBlurbs as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listBlurbs without error using callback', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListBlurbsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.ListBlurbsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.showcase.v1beta1.Blurb()), - generateSampleMessage(new protos.google.showcase.v1beta1.Blurb()), - generateSampleMessage(new protos.google.showcase.v1beta1.Blurb()), - ]; - client.innerApiCalls.listBlurbs = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listBlurbs( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IBlurb[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listBlurbs as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listBlurbs as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listBlurbs with error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListBlurbsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.ListBlurbsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listBlurbs = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listBlurbs(request), expectedError); - const actualRequest = (client.innerApiCalls.listBlurbs as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listBlurbs as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listBlurbsStream without error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListBlurbsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.ListBlurbsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.showcase.v1beta1.Blurb()), - generateSampleMessage(new protos.google.showcase.v1beta1.Blurb()), - generateSampleMessage(new protos.google.showcase.v1beta1.Blurb()), - ]; - client.descriptors.page.listBlurbs.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listBlurbsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.showcase.v1beta1.Blurb[] = []; - stream.on('data', (response: protos.google.showcase.v1beta1.Blurb) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.listBlurbs.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listBlurbs, request)); - assert( - (client.descriptors.page.listBlurbs.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listBlurbs with error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListBlurbsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.ListBlurbsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listBlurbs = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listBlurbs(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listBlurbs as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listBlurbs as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listBlurbsStream with error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListBlurbsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.ListBlurbsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listBlurbs.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listBlurbsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.showcase.v1beta1.Blurb[] = []; - stream.on('data', (response: protos.google.showcase.v1beta1.Blurb) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listBlurbs.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listBlurbs, request)); - assert( - (client.descriptors.page.listBlurbs.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listBlurbsStream without error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListBlurbsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.ListBlurbsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.showcase.v1beta1.Blurb()), + generateSampleMessage(new protos.google.showcase.v1beta1.Blurb()), + generateSampleMessage(new protos.google.showcase.v1beta1.Blurb()), + ]; + client.descriptors.page.listBlurbs.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listBlurbsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.showcase.v1beta1.Blurb[] = []; + stream.on('data', (response: protos.google.showcase.v1beta1.Blurb) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listBlurbs.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listBlurbs, request), + ); + assert( + (client.descriptors.page.listBlurbs.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('uses async iteration with listBlurbs without error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListBlurbsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.ListBlurbsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.showcase.v1beta1.Blurb()), - generateSampleMessage(new protos.google.showcase.v1beta1.Blurb()), - generateSampleMessage(new protos.google.showcase.v1beta1.Blurb()), - ]; - client.descriptors.page.listBlurbs.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.showcase.v1beta1.IBlurb[] = []; - const iterable = client.listBlurbsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listBlurbs.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listBlurbs.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listBlurbsStream with error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListBlurbsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.ListBlurbsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listBlurbs.createStream = stubPageStreamingCall( + undefined, + expectedError, + ); + const stream = client.listBlurbsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.showcase.v1beta1.Blurb[] = []; + stream.on('data', (response: protos.google.showcase.v1beta1.Blurb) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listBlurbs.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listBlurbs, request), + ); + assert( + (client.descriptors.page.listBlurbs.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('uses async iteration with listBlurbs with error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListBlurbsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.ListBlurbsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listBlurbs.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listBlurbsAsync(request); - await assert.rejects(async () => { - const responses: protos.google.showcase.v1beta1.IBlurb[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listBlurbs.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listBlurbs.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listBlurbs without error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListBlurbsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.ListBlurbsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.showcase.v1beta1.Blurb()), + generateSampleMessage(new protos.google.showcase.v1beta1.Blurb()), + generateSampleMessage(new protos.google.showcase.v1beta1.Blurb()), + ]; + client.descriptors.page.listBlurbs.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.showcase.v1beta1.IBlurb[] = []; + const iterable = client.listBlurbsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + (client.descriptors.page.listBlurbs.asyncIterate as SinonStub).getCall( + 0, + ).args[1], + request, + ); + assert( + (client.descriptors.page.listBlurbs.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); }); - describe('Path templates', () => { - - describe('blueprint', async () => { - const fakePath = "/rendered/path/blueprint"; - const expectedParameters = { - session: "sessionValue", - test: "testValue", - blueprint: "blueprintValue", - }; - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.blueprintPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.blueprintPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('blueprintPath', () => { - const result = client.blueprintPath("sessionValue", "testValue", "blueprintValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.blueprintPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchSessionFromBlueprintName', () => { - const result = client.matchSessionFromBlueprintName(fakePath); - assert.strictEqual(result, "sessionValue"); - assert((client.pathTemplates.blueprintPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchTestFromBlueprintName', () => { - const result = client.matchTestFromBlueprintName(fakePath); - assert.strictEqual(result, "testValue"); - assert((client.pathTemplates.blueprintPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBlueprintFromBlueprintName', () => { - const result = client.matchBlueprintFromBlueprintName(fakePath); - assert.strictEqual(result, "blueprintValue"); - assert((client.pathTemplates.blueprintPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('uses async iteration with listBlurbs with error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListBlurbsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.ListBlurbsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listBlurbs.asyncIterate = stubAsyncIterationCall( + undefined, + expectedError, + ); + const iterable = client.listBlurbsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.showcase.v1beta1.IBlurb[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + (client.descriptors.page.listBlurbs.asyncIterate as SinonStub).getCall( + 0, + ).args[1], + request, + ); + assert( + (client.descriptors.page.listBlurbs.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + }); + + describe('Path templates', () => { + describe('blueprint', async () => { + const fakePath = '/rendered/path/blueprint'; + const expectedParameters = { + session: 'sessionValue', + test: 'testValue', + blueprint: 'blueprintValue', + }; + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.blueprintPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.blueprintPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('blueprintPath', () => { + const result = client.blueprintPath( + 'sessionValue', + 'testValue', + 'blueprintValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.blueprintPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchSessionFromBlueprintName', () => { + const result = client.matchSessionFromBlueprintName(fakePath); + assert.strictEqual(result, 'sessionValue'); + assert( + (client.pathTemplates.blueprintPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchTestFromBlueprintName', () => { + const result = client.matchTestFromBlueprintName(fakePath); + assert.strictEqual(result, 'testValue'); + assert( + (client.pathTemplates.blueprintPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBlueprintFromBlueprintName', () => { + const result = client.matchBlueprintFromBlueprintName(fakePath); + assert.strictEqual(result, 'blueprintValue'); + assert( + (client.pathTemplates.blueprintPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('room', async () => { - const fakePath = "/rendered/path/room"; - const expectedParameters = { - room: "roomValue", - }; - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.roomPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.roomPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('roomPath', () => { - const result = client.roomPath("roomValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.roomPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchRoomFromRoomName', () => { - const result = client.matchRoomFromRoomName(fakePath); - assert.strictEqual(result, "roomValue"); - assert((client.pathTemplates.roomPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('room', async () => { + const fakePath = '/rendered/path/room'; + const expectedParameters = { + room: 'roomValue', + }; + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.roomPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.roomPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('roomPath', () => { + const result = client.roomPath('roomValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.roomPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchRoomFromRoomName', () => { + const result = client.matchRoomFromRoomName(fakePath); + assert.strictEqual(result, 'roomValue'); + assert( + (client.pathTemplates.roomPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('roomBlurb', async () => { - const fakePath = "/rendered/path/roomBlurb"; - const expectedParameters = { - room: "roomValue", - blurb: "blurbValue", - }; - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.roomBlurbPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.roomBlurbPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('roomBlurbPath', () => { - const result = client.roomBlurbPath("roomValue", "blurbValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.roomBlurbPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchRoomFromRoomBlurbName', () => { - const result = client.matchRoomFromRoomBlurbName(fakePath); - assert.strictEqual(result, "roomValue"); - assert((client.pathTemplates.roomBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBlurbFromRoomBlurbName', () => { - const result = client.matchBlurbFromRoomBlurbName(fakePath); - assert.strictEqual(result, "blurbValue"); - assert((client.pathTemplates.roomBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('roomBlurb', async () => { + const fakePath = '/rendered/path/roomBlurb'; + const expectedParameters = { + room: 'roomValue', + blurb: 'blurbValue', + }; + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.roomBlurbPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.roomBlurbPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('roomBlurbPath', () => { + const result = client.roomBlurbPath('roomValue', 'blurbValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.roomBlurbPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchRoomFromRoomBlurbName', () => { + const result = client.matchRoomFromRoomBlurbName(fakePath); + assert.strictEqual(result, 'roomValue'); + assert( + (client.pathTemplates.roomBlurbPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBlurbFromRoomBlurbName', () => { + const result = client.matchBlurbFromRoomBlurbName(fakePath); + assert.strictEqual(result, 'blurbValue'); + assert( + (client.pathTemplates.roomBlurbPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('roomBlurbsLegacyRoomBlurb', async () => { - const fakePath = "/rendered/path/roomBlurbsLegacyRoomBlurb"; - const expectedParameters = { - room: "roomValue", - legacy_room: "legacyRoomValue", - blurb: "blurbValue", - }; - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('roomBlurbsLegacyRoomBlurbPath', () => { - const result = client.roomBlurbsLegacyRoomBlurbPath("roomValue", "legacyRoomValue", "blurbValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchRoomFromRoomBlurbsLegacyRoomBlurbName', () => { - const result = client.matchRoomFromRoomBlurbsLegacyRoomBlurbName(fakePath); - assert.strictEqual(result, "roomValue"); - assert((client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName', () => { - const result = client.matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName(fakePath); - assert.strictEqual(result, "legacyRoomValue"); - assert((client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBlurbFromRoomBlurbsLegacyRoomBlurbName', () => { - const result = client.matchBlurbFromRoomBlurbsLegacyRoomBlurbName(fakePath); - assert.strictEqual(result, "blurbValue"); - assert((client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('roomBlurbsLegacyRoomBlurb', async () => { + const fakePath = '/rendered/path/roomBlurbsLegacyRoomBlurb'; + const expectedParameters = { + room: 'roomValue', + legacy_room: 'legacyRoomValue', + blurb: 'blurbValue', + }; + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('roomBlurbsLegacyRoomBlurbPath', () => { + const result = client.roomBlurbsLegacyRoomBlurbPath( + 'roomValue', + 'legacyRoomValue', + 'blurbValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchRoomFromRoomBlurbsLegacyRoomBlurbName', () => { + const result = + client.matchRoomFromRoomBlurbsLegacyRoomBlurbName(fakePath); + assert.strictEqual(result, 'roomValue'); + assert( + ( + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName', () => { + const result = + client.matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName(fakePath); + assert.strictEqual(result, 'legacyRoomValue'); + assert( + ( + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBlurbFromRoomBlurbsLegacyRoomBlurbName', () => { + const result = + client.matchBlurbFromRoomBlurbsLegacyRoomBlurbName(fakePath); + assert.strictEqual(result, 'blurbValue'); + assert( + ( + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('sequence', async () => { - const fakePath = "/rendered/path/sequence"; - const expectedParameters = { - sequence: "sequenceValue", - }; - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.sequencePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.sequencePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('sequencePath', () => { - const result = client.sequencePath("sequenceValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.sequencePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchSequenceFromSequenceName', () => { - const result = client.matchSequenceFromSequenceName(fakePath); - assert.strictEqual(result, "sequenceValue"); - assert((client.pathTemplates.sequencePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('sequence', async () => { + const fakePath = '/rendered/path/sequence'; + const expectedParameters = { + sequence: 'sequenceValue', + }; + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.sequencePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.sequencePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('sequencePath', () => { + const result = client.sequencePath('sequenceValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.sequencePathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchSequenceFromSequenceName', () => { + const result = client.matchSequenceFromSequenceName(fakePath); + assert.strictEqual(result, 'sequenceValue'); + assert( + (client.pathTemplates.sequencePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('sequenceReport', async () => { - const fakePath = "/rendered/path/sequenceReport"; - const expectedParameters = { - sequence: "sequenceValue", - }; - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.sequenceReportPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.sequenceReportPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('sequenceReportPath', () => { - const result = client.sequenceReportPath("sequenceValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.sequenceReportPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchSequenceFromSequenceReportName', () => { - const result = client.matchSequenceFromSequenceReportName(fakePath); - assert.strictEqual(result, "sequenceValue"); - assert((client.pathTemplates.sequenceReportPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('sequenceReport', async () => { + const fakePath = '/rendered/path/sequenceReport'; + const expectedParameters = { + sequence: 'sequenceValue', + }; + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.sequenceReportPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.sequenceReportPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('sequenceReportPath', () => { + const result = client.sequenceReportPath('sequenceValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.sequenceReportPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchSequenceFromSequenceReportName', () => { + const result = client.matchSequenceFromSequenceReportName(fakePath); + assert.strictEqual(result, 'sequenceValue'); + assert( + (client.pathTemplates.sequenceReportPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('session', async () => { - const fakePath = "/rendered/path/session"; - const expectedParameters = { - session: "sessionValue", - }; - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.sessionPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.sessionPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('sessionPath', () => { - const result = client.sessionPath("sessionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.sessionPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchSessionFromSessionName', () => { - const result = client.matchSessionFromSessionName(fakePath); - assert.strictEqual(result, "sessionValue"); - assert((client.pathTemplates.sessionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('session', async () => { + const fakePath = '/rendered/path/session'; + const expectedParameters = { + session: 'sessionValue', + }; + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.sessionPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.sessionPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('sessionPath', () => { + const result = client.sessionPath('sessionValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.sessionPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchSessionFromSessionName', () => { + const result = client.matchSessionFromSessionName(fakePath); + assert.strictEqual(result, 'sessionValue'); + assert( + (client.pathTemplates.sessionPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('test', async () => { - const fakePath = "/rendered/path/test"; - const expectedParameters = { - session: "sessionValue", - test: "testValue", - }; - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.testPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.testPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('testPath', () => { - const result = client.testPath("sessionValue", "testValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.testPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchSessionFromTestName', () => { - const result = client.matchSessionFromTestName(fakePath); - assert.strictEqual(result, "sessionValue"); - assert((client.pathTemplates.testPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchTestFromTestName', () => { - const result = client.matchTestFromTestName(fakePath); - assert.strictEqual(result, "testValue"); - assert((client.pathTemplates.testPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('test', async () => { + const fakePath = '/rendered/path/test'; + const expectedParameters = { + session: 'sessionValue', + test: 'testValue', + }; + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.testPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.testPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('testPath', () => { + const result = client.testPath('sessionValue', 'testValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.testPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchSessionFromTestName', () => { + const result = client.matchSessionFromTestName(fakePath); + assert.strictEqual(result, 'sessionValue'); + assert( + (client.pathTemplates.testPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchTestFromTestName', () => { + const result = client.matchTestFromTestName(fakePath); + assert.strictEqual(result, 'testValue'); + assert( + (client.pathTemplates.testPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('user', async () => { - const fakePath = "/rendered/path/user"; - const expectedParameters = { - user: "userValue", - }; - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.userPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.userPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('userPath', () => { - const result = client.userPath("userValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.userPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchUserFromUserName', () => { - const result = client.matchUserFromUserName(fakePath); - assert.strictEqual(result, "userValue"); - assert((client.pathTemplates.userPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('user', async () => { + const fakePath = '/rendered/path/user'; + const expectedParameters = { + user: 'userValue', + }; + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.userPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.userPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('userPath', () => { + const result = client.userPath('userValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.userPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchUserFromUserName', () => { + const result = client.matchUserFromUserName(fakePath); + assert.strictEqual(result, 'userValue'); + assert( + (client.pathTemplates.userPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('userProfileBlurb', async () => { - const fakePath = "/rendered/path/userProfileBlurb"; - const expectedParameters = { - user: "userValue", - blurb: "blurbValue", - }; - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.userProfileBlurbPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.userProfileBlurbPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('userProfileBlurbPath', () => { - const result = client.userProfileBlurbPath("userValue", "blurbValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.userProfileBlurbPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchUserFromUserProfileBlurbName', () => { - const result = client.matchUserFromUserProfileBlurbName(fakePath); - assert.strictEqual(result, "userValue"); - assert((client.pathTemplates.userProfileBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBlurbFromUserProfileBlurbName', () => { - const result = client.matchBlurbFromUserProfileBlurbName(fakePath); - assert.strictEqual(result, "blurbValue"); - assert((client.pathTemplates.userProfileBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('userProfileBlurb', async () => { + const fakePath = '/rendered/path/userProfileBlurb'; + const expectedParameters = { + user: 'userValue', + blurb: 'blurbValue', + }; + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.userProfileBlurbPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.userProfileBlurbPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('userProfileBlurbPath', () => { + const result = client.userProfileBlurbPath('userValue', 'blurbValue'); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.userProfileBlurbPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchUserFromUserProfileBlurbName', () => { + const result = client.matchUserFromUserProfileBlurbName(fakePath); + assert.strictEqual(result, 'userValue'); + assert( + (client.pathTemplates.userProfileBlurbPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBlurbFromUserProfileBlurbName', () => { + const result = client.matchBlurbFromUserProfileBlurbName(fakePath); + assert.strictEqual(result, 'blurbValue'); + assert( + (client.pathTemplates.userProfileBlurbPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('userProfileBlurbsLegacyUserBlurb', async () => { - const fakePath = "/rendered/path/userProfileBlurbsLegacyUserBlurb"; - const expectedParameters = { - user: "userValue", - legacy_user: "legacyUserValue", - blurb: "blurbValue", - }; - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('userProfileBlurbsLegacyUserBlurbPath', () => { - const result = client.userProfileBlurbsLegacyUserBlurbPath("userValue", "legacyUserValue", "blurbValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchUserFromUserProfileBlurbsLegacyUserBlurbName', () => { - const result = client.matchUserFromUserProfileBlurbsLegacyUserBlurbName(fakePath); - assert.strictEqual(result, "userValue"); - assert((client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName', () => { - const result = client.matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName(fakePath); - assert.strictEqual(result, "legacyUserValue"); - assert((client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBlurbFromUserProfileBlurbsLegacyUserBlurbName', () => { - const result = client.matchBlurbFromUserProfileBlurbsLegacyUserBlurbName(fakePath); - assert.strictEqual(result, "blurbValue"); - assert((client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('userProfileBlurbsLegacyUserBlurb', async () => { + const fakePath = '/rendered/path/userProfileBlurbsLegacyUserBlurb'; + const expectedParameters = { + user: 'userValue', + legacy_user: 'legacyUserValue', + blurb: 'blurbValue', + }; + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('userProfileBlurbsLegacyUserBlurbPath', () => { + const result = client.userProfileBlurbsLegacyUserBlurbPath( + 'userValue', + 'legacyUserValue', + 'blurbValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchUserFromUserProfileBlurbsLegacyUserBlurbName', () => { + const result = + client.matchUserFromUserProfileBlurbsLegacyUserBlurbName(fakePath); + assert.strictEqual(result, 'userValue'); + assert( + ( + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName', () => { + const result = + client.matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName( + fakePath, + ); + assert.strictEqual(result, 'legacyUserValue'); + assert( + ( + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBlurbFromUserProfileBlurbsLegacyUserBlurbName', () => { + const result = + client.matchBlurbFromUserProfileBlurbsLegacyUserBlurbName(fakePath); + assert.strictEqual(result, 'blurbValue'); + assert( + ( + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/core/generator/gapic-generator-typescript/baselines/disable-packing-test/test/gapic_sequence_service_v1beta1.ts.baseline b/core/generator/gapic-generator-typescript/baselines/disable-packing-test/test/gapic_sequence_service_v1beta1.ts.baseline index e772cf81a761..a38f5ecf3aa4 100644 --- a/core/generator/gapic-generator-typescript/baselines/disable-packing-test/test/gapic_sequence_service_v1beta1.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/disable-packing-test/test/gapic_sequence_service_v1beta1.ts.baseline @@ -19,851 +19,1104 @@ import * as protos from '../protos/protos'; import * as assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as sequenceserviceModule from '../src'; -import {protobuf} from 'google-gax'; +import { protobuf } from 'google-gax'; // Dynamically loaded proto JSON is needed to get the type information // to fill in default values for request objects -const root = protobuf.Root.fromJSON(require('../protos/protos.json')).resolveAll(); +const root = protobuf.Root.fromJSON( + require('../protos/protos.json'), +).resolveAll(); // eslint-disable-next-line @typescript-eslint/no-unused-vars function getTypeDefaultValue(typeName: string, fields: string[]) { - let type = root.lookupType(typeName) as protobuf.Type; - for (const field of fields.slice(0, -1)) { - type = type.fields[field]?.resolvedType as protobuf.Type; - } - return type.fields[fields[fields.length - 1]]?.defaultValue; + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type.fields[field]?.resolvedType as protobuf.Type; + } + return type.fields[fields[fields.length - 1]]?.defaultValue; } function generateSampleMessage(instance: T) { - const filledObject = (instance.constructor as typeof protobuf.Message) - .toObject(instance as protobuf.Message, {defaults: true}); - return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, { defaults: true }); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; } function stubSimpleCall(response?: ResponseType, error?: Error) { - return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); } -function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { - return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +function stubSimpleCallWithCallback( + response?: ResponseType, + error?: Error, +) { + return error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); } describe('v1beta1.SequenceServiceClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'localhost'); - }); - - it('has universeDomain', () => { - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); - - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - it('throws DeprecationWarning if static servicePath is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const servicePath = sequenceserviceModule.v1beta1.SequenceServiceClient.servicePath; - assert.strictEqual(servicePath, 'localhost'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = sequenceserviceModule.v1beta1.SequenceServiceClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'localhost'); - assert(stub.called); - stub.restore(); - }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { new sequenceserviceModule.v1beta1.SequenceServiceClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); - - it('has port', () => { - const port = sequenceserviceModule.v1beta1.SequenceServiceClient.port; - assert(port); - assert(typeof port === 'number'); - }); - - it('should create a client with no option', () => { - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient(); - assert(client); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'localhost'); + }); - it('should create a client with gRPC fallback', () => { - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ - fallback: true, - }); - assert(client); - }); + it('has universeDomain', () => { + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - it('has initialize method and supports deferred initialization', async () => { - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.sequenceServiceStub, undefined); - await client.initialize(); - assert(client.sequenceServiceStub); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = + sequenceserviceModule.v1beta1.SequenceServiceClient.servicePath; + assert.strictEqual(servicePath, 'localhost'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + sequenceserviceModule.v1beta1.SequenceServiceClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'localhost'); + assert(stub.called); + stub.restore(); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new sequenceserviceModule.v1beta1.SequenceServiceClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); + }); - it('has close method for the initialized client', done => { - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.sequenceServiceStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('has port', () => { + const port = sequenceserviceModule.v1beta1.SequenceServiceClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('has close method for the non-initialized client', done => { - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.sequenceServiceStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('should create a client with no option', () => { + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient(); + assert(client); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); - }); + it('should create a client with gRPC fallback', () => { + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ + fallback: true, + }); + assert(client); + }); - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId((err?: Error|null, projectId?: string|null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } - }); - }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); - }); + it('has initialize method and supports deferred initialization', async () => { + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.sequenceServiceStub, undefined); + await client.initialize(); + assert(client.sequenceServiceStub); }); - describe('createSequence', () => { - it('invokes createSequence without error', async () => { - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.CreateSequenceRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.Sequence() - ); - client.innerApiCalls.createSequence = stubSimpleCall(expectedResponse); - const [response] = await client.createSequence(request); - assert.deepStrictEqual(response, expectedResponse); + it('has close method for the initialized client', (done) => { + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.sequenceServiceStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes createSequence without error using callback', async () => { - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.CreateSequenceRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.Sequence() - ); - client.innerApiCalls.createSequence = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createSequence( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.ISequence|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); + it('has close method for the non-initialized client', (done) => { + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.sequenceServiceStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes createSequence with error', async () => { - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.CreateSequenceRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.createSequence = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createSequence(request), expectedError); - }); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + }); - it('invokes createSequence with closed client', async () => { - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.CreateSequenceRequest() - ); - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createSequence(request), expectedError); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + }); + + describe('createSequence', () => { + it('invokes createSequence without error', async () => { + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.CreateSequenceRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.Sequence(), + ); + client.innerApiCalls.createSequence = stubSimpleCall(expectedResponse); + const [response] = await client.createSequence(request); + assert.deepStrictEqual(response, expectedResponse); }); - describe('getSequenceReport', () => { - it('invokes getSequenceReport without error', async () => { - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.GetSequenceReportRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.GetSequenceReportRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.SequenceReport() - ); - client.innerApiCalls.getSequenceReport = stubSimpleCall(expectedResponse); - const [response] = await client.getSequenceReport(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getSequenceReport as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getSequenceReport as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createSequence without error using callback', async () => { + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.CreateSequenceRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.Sequence(), + ); + client.innerApiCalls.createSequence = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createSequence( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.ISequence | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes getSequenceReport without error using callback', async () => { - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.GetSequenceReportRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.GetSequenceReportRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.SequenceReport() - ); - client.innerApiCalls.getSequenceReport = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getSequenceReport( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.ISequenceReport|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getSequenceReport as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getSequenceReport as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createSequence with error', async () => { + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.CreateSequenceRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.createSequence = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.createSequence(request), expectedError); + }); - it('invokes getSequenceReport with error', async () => { - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.GetSequenceReportRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.GetSequenceReportRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getSequenceReport = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getSequenceReport(request), expectedError); - const actualRequest = (client.innerApiCalls.getSequenceReport as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getSequenceReport as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createSequence with closed client', async () => { + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.CreateSequenceRequest(), + ); + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.createSequence(request), expectedError); + }); + }); + + describe('getSequenceReport', () => { + it('invokes getSequenceReport without error', async () => { + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.GetSequenceReportRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.GetSequenceReportRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.SequenceReport(), + ); + client.innerApiCalls.getSequenceReport = stubSimpleCall(expectedResponse); + const [response] = await client.getSequenceReport(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getSequenceReport as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getSequenceReport as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getSequenceReport with closed client', async () => { - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.GetSequenceReportRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.GetSequenceReportRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getSequenceReport(request), expectedError); - }); + it('invokes getSequenceReport without error using callback', async () => { + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.GetSequenceReportRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.GetSequenceReportRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.SequenceReport(), + ); + client.innerApiCalls.getSequenceReport = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getSequenceReport( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.ISequenceReport | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getSequenceReport as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getSequenceReport as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('attemptSequence', () => { - it('invokes attemptSequence without error', async () => { - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.AttemptSequenceRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.AttemptSequenceRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.attemptSequence = stubSimpleCall(expectedResponse); - const [response] = await client.attemptSequence(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.attemptSequence as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.attemptSequence as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getSequenceReport with error', async () => { + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.GetSequenceReportRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.GetSequenceReportRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getSequenceReport = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getSequenceReport(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getSequenceReport as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getSequenceReport as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes attemptSequence without error using callback', async () => { - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.AttemptSequenceRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.AttemptSequenceRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.attemptSequence = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.attemptSequence( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.attemptSequence as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.attemptSequence as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getSequenceReport with closed client', async () => { + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.GetSequenceReportRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.GetSequenceReportRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getSequenceReport(request), expectedError); + }); + }); + + describe('attemptSequence', () => { + it('invokes attemptSequence without error', async () => { + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.AttemptSequenceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.AttemptSequenceRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.attemptSequence = stubSimpleCall(expectedResponse); + const [response] = await client.attemptSequence(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.attemptSequence as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.attemptSequence as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes attemptSequence with error', async () => { - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.AttemptSequenceRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.AttemptSequenceRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.attemptSequence = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.attemptSequence(request), expectedError); - const actualRequest = (client.innerApiCalls.attemptSequence as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.attemptSequence as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes attemptSequence without error using callback', async () => { + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.AttemptSequenceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.AttemptSequenceRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.attemptSequence = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.attemptSequence( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.attemptSequence as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.attemptSequence as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes attemptSequence with closed client', async () => { - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.AttemptSequenceRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.AttemptSequenceRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.attemptSequence(request), expectedError); - }); + it('invokes attemptSequence with error', async () => { + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.AttemptSequenceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.AttemptSequenceRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.attemptSequence = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.attemptSequence(request), expectedError); + const actualRequest = ( + client.innerApiCalls.attemptSequence as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.attemptSequence as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('Path templates', () => { - - describe('blueprint', async () => { - const fakePath = "/rendered/path/blueprint"; - const expectedParameters = { - session: "sessionValue", - test: "testValue", - blueprint: "blueprintValue", - }; - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.blueprintPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.blueprintPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('blueprintPath', () => { - const result = client.blueprintPath("sessionValue", "testValue", "blueprintValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.blueprintPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchSessionFromBlueprintName', () => { - const result = client.matchSessionFromBlueprintName(fakePath); - assert.strictEqual(result, "sessionValue"); - assert((client.pathTemplates.blueprintPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchTestFromBlueprintName', () => { - const result = client.matchTestFromBlueprintName(fakePath); - assert.strictEqual(result, "testValue"); - assert((client.pathTemplates.blueprintPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBlueprintFromBlueprintName', () => { - const result = client.matchBlueprintFromBlueprintName(fakePath); - assert.strictEqual(result, "blueprintValue"); - assert((client.pathTemplates.blueprintPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('invokes attemptSequence with closed client', async () => { + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.AttemptSequenceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.AttemptSequenceRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.attemptSequence(request), expectedError); + }); + }); + + describe('Path templates', () => { + describe('blueprint', async () => { + const fakePath = '/rendered/path/blueprint'; + const expectedParameters = { + session: 'sessionValue', + test: 'testValue', + blueprint: 'blueprintValue', + }; + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.blueprintPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.blueprintPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('blueprintPath', () => { + const result = client.blueprintPath( + 'sessionValue', + 'testValue', + 'blueprintValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.blueprintPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchSessionFromBlueprintName', () => { + const result = client.matchSessionFromBlueprintName(fakePath); + assert.strictEqual(result, 'sessionValue'); + assert( + (client.pathTemplates.blueprintPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchTestFromBlueprintName', () => { + const result = client.matchTestFromBlueprintName(fakePath); + assert.strictEqual(result, 'testValue'); + assert( + (client.pathTemplates.blueprintPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBlueprintFromBlueprintName', () => { + const result = client.matchBlueprintFromBlueprintName(fakePath); + assert.strictEqual(result, 'blueprintValue'); + assert( + (client.pathTemplates.blueprintPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('room', async () => { - const fakePath = "/rendered/path/room"; - const expectedParameters = { - room: "roomValue", - }; - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.roomPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.roomPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('roomPath', () => { - const result = client.roomPath("roomValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.roomPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchRoomFromRoomName', () => { - const result = client.matchRoomFromRoomName(fakePath); - assert.strictEqual(result, "roomValue"); - assert((client.pathTemplates.roomPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('room', async () => { + const fakePath = '/rendered/path/room'; + const expectedParameters = { + room: 'roomValue', + }; + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.roomPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.roomPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('roomPath', () => { + const result = client.roomPath('roomValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.roomPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchRoomFromRoomName', () => { + const result = client.matchRoomFromRoomName(fakePath); + assert.strictEqual(result, 'roomValue'); + assert( + (client.pathTemplates.roomPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('roomBlurb', async () => { - const fakePath = "/rendered/path/roomBlurb"; - const expectedParameters = { - room: "roomValue", - blurb: "blurbValue", - }; - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.roomBlurbPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.roomBlurbPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('roomBlurbPath', () => { - const result = client.roomBlurbPath("roomValue", "blurbValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.roomBlurbPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchRoomFromRoomBlurbName', () => { - const result = client.matchRoomFromRoomBlurbName(fakePath); - assert.strictEqual(result, "roomValue"); - assert((client.pathTemplates.roomBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBlurbFromRoomBlurbName', () => { - const result = client.matchBlurbFromRoomBlurbName(fakePath); - assert.strictEqual(result, "blurbValue"); - assert((client.pathTemplates.roomBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('roomBlurb', async () => { + const fakePath = '/rendered/path/roomBlurb'; + const expectedParameters = { + room: 'roomValue', + blurb: 'blurbValue', + }; + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.roomBlurbPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.roomBlurbPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('roomBlurbPath', () => { + const result = client.roomBlurbPath('roomValue', 'blurbValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.roomBlurbPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchRoomFromRoomBlurbName', () => { + const result = client.matchRoomFromRoomBlurbName(fakePath); + assert.strictEqual(result, 'roomValue'); + assert( + (client.pathTemplates.roomBlurbPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBlurbFromRoomBlurbName', () => { + const result = client.matchBlurbFromRoomBlurbName(fakePath); + assert.strictEqual(result, 'blurbValue'); + assert( + (client.pathTemplates.roomBlurbPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('roomBlurbsLegacyRoomBlurb', async () => { - const fakePath = "/rendered/path/roomBlurbsLegacyRoomBlurb"; - const expectedParameters = { - room: "roomValue", - legacy_room: "legacyRoomValue", - blurb: "blurbValue", - }; - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('roomBlurbsLegacyRoomBlurbPath', () => { - const result = client.roomBlurbsLegacyRoomBlurbPath("roomValue", "legacyRoomValue", "blurbValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchRoomFromRoomBlurbsLegacyRoomBlurbName', () => { - const result = client.matchRoomFromRoomBlurbsLegacyRoomBlurbName(fakePath); - assert.strictEqual(result, "roomValue"); - assert((client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName', () => { - const result = client.matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName(fakePath); - assert.strictEqual(result, "legacyRoomValue"); - assert((client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBlurbFromRoomBlurbsLegacyRoomBlurbName', () => { - const result = client.matchBlurbFromRoomBlurbsLegacyRoomBlurbName(fakePath); - assert.strictEqual(result, "blurbValue"); - assert((client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('roomBlurbsLegacyRoomBlurb', async () => { + const fakePath = '/rendered/path/roomBlurbsLegacyRoomBlurb'; + const expectedParameters = { + room: 'roomValue', + legacy_room: 'legacyRoomValue', + blurb: 'blurbValue', + }; + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('roomBlurbsLegacyRoomBlurbPath', () => { + const result = client.roomBlurbsLegacyRoomBlurbPath( + 'roomValue', + 'legacyRoomValue', + 'blurbValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchRoomFromRoomBlurbsLegacyRoomBlurbName', () => { + const result = + client.matchRoomFromRoomBlurbsLegacyRoomBlurbName(fakePath); + assert.strictEqual(result, 'roomValue'); + assert( + ( + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName', () => { + const result = + client.matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName(fakePath); + assert.strictEqual(result, 'legacyRoomValue'); + assert( + ( + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBlurbFromRoomBlurbsLegacyRoomBlurbName', () => { + const result = + client.matchBlurbFromRoomBlurbsLegacyRoomBlurbName(fakePath); + assert.strictEqual(result, 'blurbValue'); + assert( + ( + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('sequence', async () => { - const fakePath = "/rendered/path/sequence"; - const expectedParameters = { - sequence: "sequenceValue", - }; - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.sequencePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.sequencePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('sequencePath', () => { - const result = client.sequencePath("sequenceValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.sequencePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchSequenceFromSequenceName', () => { - const result = client.matchSequenceFromSequenceName(fakePath); - assert.strictEqual(result, "sequenceValue"); - assert((client.pathTemplates.sequencePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('sequence', async () => { + const fakePath = '/rendered/path/sequence'; + const expectedParameters = { + sequence: 'sequenceValue', + }; + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.sequencePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.sequencePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('sequencePath', () => { + const result = client.sequencePath('sequenceValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.sequencePathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchSequenceFromSequenceName', () => { + const result = client.matchSequenceFromSequenceName(fakePath); + assert.strictEqual(result, 'sequenceValue'); + assert( + (client.pathTemplates.sequencePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('sequenceReport', async () => { - const fakePath = "/rendered/path/sequenceReport"; - const expectedParameters = { - sequence: "sequenceValue", - }; - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.sequenceReportPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.sequenceReportPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('sequenceReportPath', () => { - const result = client.sequenceReportPath("sequenceValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.sequenceReportPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchSequenceFromSequenceReportName', () => { - const result = client.matchSequenceFromSequenceReportName(fakePath); - assert.strictEqual(result, "sequenceValue"); - assert((client.pathTemplates.sequenceReportPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('sequenceReport', async () => { + const fakePath = '/rendered/path/sequenceReport'; + const expectedParameters = { + sequence: 'sequenceValue', + }; + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.sequenceReportPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.sequenceReportPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('sequenceReportPath', () => { + const result = client.sequenceReportPath('sequenceValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.sequenceReportPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchSequenceFromSequenceReportName', () => { + const result = client.matchSequenceFromSequenceReportName(fakePath); + assert.strictEqual(result, 'sequenceValue'); + assert( + (client.pathTemplates.sequenceReportPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('session', async () => { - const fakePath = "/rendered/path/session"; - const expectedParameters = { - session: "sessionValue", - }; - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.sessionPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.sessionPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('sessionPath', () => { - const result = client.sessionPath("sessionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.sessionPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchSessionFromSessionName', () => { - const result = client.matchSessionFromSessionName(fakePath); - assert.strictEqual(result, "sessionValue"); - assert((client.pathTemplates.sessionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('session', async () => { + const fakePath = '/rendered/path/session'; + const expectedParameters = { + session: 'sessionValue', + }; + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.sessionPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.sessionPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('sessionPath', () => { + const result = client.sessionPath('sessionValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.sessionPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchSessionFromSessionName', () => { + const result = client.matchSessionFromSessionName(fakePath); + assert.strictEqual(result, 'sessionValue'); + assert( + (client.pathTemplates.sessionPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('test', async () => { - const fakePath = "/rendered/path/test"; - const expectedParameters = { - session: "sessionValue", - test: "testValue", - }; - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.testPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.testPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('testPath', () => { - const result = client.testPath("sessionValue", "testValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.testPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchSessionFromTestName', () => { - const result = client.matchSessionFromTestName(fakePath); - assert.strictEqual(result, "sessionValue"); - assert((client.pathTemplates.testPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchTestFromTestName', () => { - const result = client.matchTestFromTestName(fakePath); - assert.strictEqual(result, "testValue"); - assert((client.pathTemplates.testPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('test', async () => { + const fakePath = '/rendered/path/test'; + const expectedParameters = { + session: 'sessionValue', + test: 'testValue', + }; + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.testPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.testPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('testPath', () => { + const result = client.testPath('sessionValue', 'testValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.testPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchSessionFromTestName', () => { + const result = client.matchSessionFromTestName(fakePath); + assert.strictEqual(result, 'sessionValue'); + assert( + (client.pathTemplates.testPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchTestFromTestName', () => { + const result = client.matchTestFromTestName(fakePath); + assert.strictEqual(result, 'testValue'); + assert( + (client.pathTemplates.testPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('user', async () => { - const fakePath = "/rendered/path/user"; - const expectedParameters = { - user: "userValue", - }; - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.userPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.userPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('userPath', () => { - const result = client.userPath("userValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.userPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchUserFromUserName', () => { - const result = client.matchUserFromUserName(fakePath); - assert.strictEqual(result, "userValue"); - assert((client.pathTemplates.userPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('user', async () => { + const fakePath = '/rendered/path/user'; + const expectedParameters = { + user: 'userValue', + }; + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.userPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.userPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('userPath', () => { + const result = client.userPath('userValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.userPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchUserFromUserName', () => { + const result = client.matchUserFromUserName(fakePath); + assert.strictEqual(result, 'userValue'); + assert( + (client.pathTemplates.userPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('userProfileBlurb', async () => { - const fakePath = "/rendered/path/userProfileBlurb"; - const expectedParameters = { - user: "userValue", - blurb: "blurbValue", - }; - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.userProfileBlurbPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.userProfileBlurbPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('userProfileBlurbPath', () => { - const result = client.userProfileBlurbPath("userValue", "blurbValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.userProfileBlurbPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchUserFromUserProfileBlurbName', () => { - const result = client.matchUserFromUserProfileBlurbName(fakePath); - assert.strictEqual(result, "userValue"); - assert((client.pathTemplates.userProfileBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBlurbFromUserProfileBlurbName', () => { - const result = client.matchBlurbFromUserProfileBlurbName(fakePath); - assert.strictEqual(result, "blurbValue"); - assert((client.pathTemplates.userProfileBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('userProfileBlurb', async () => { + const fakePath = '/rendered/path/userProfileBlurb'; + const expectedParameters = { + user: 'userValue', + blurb: 'blurbValue', + }; + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.userProfileBlurbPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.userProfileBlurbPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('userProfileBlurbPath', () => { + const result = client.userProfileBlurbPath('userValue', 'blurbValue'); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.userProfileBlurbPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchUserFromUserProfileBlurbName', () => { + const result = client.matchUserFromUserProfileBlurbName(fakePath); + assert.strictEqual(result, 'userValue'); + assert( + (client.pathTemplates.userProfileBlurbPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBlurbFromUserProfileBlurbName', () => { + const result = client.matchBlurbFromUserProfileBlurbName(fakePath); + assert.strictEqual(result, 'blurbValue'); + assert( + (client.pathTemplates.userProfileBlurbPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('userProfileBlurbsLegacyUserBlurb', async () => { - const fakePath = "/rendered/path/userProfileBlurbsLegacyUserBlurb"; - const expectedParameters = { - user: "userValue", - legacy_user: "legacyUserValue", - blurb: "blurbValue", - }; - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('userProfileBlurbsLegacyUserBlurbPath', () => { - const result = client.userProfileBlurbsLegacyUserBlurbPath("userValue", "legacyUserValue", "blurbValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchUserFromUserProfileBlurbsLegacyUserBlurbName', () => { - const result = client.matchUserFromUserProfileBlurbsLegacyUserBlurbName(fakePath); - assert.strictEqual(result, "userValue"); - assert((client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName', () => { - const result = client.matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName(fakePath); - assert.strictEqual(result, "legacyUserValue"); - assert((client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBlurbFromUserProfileBlurbsLegacyUserBlurbName', () => { - const result = client.matchBlurbFromUserProfileBlurbsLegacyUserBlurbName(fakePath); - assert.strictEqual(result, "blurbValue"); - assert((client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('userProfileBlurbsLegacyUserBlurb', async () => { + const fakePath = '/rendered/path/userProfileBlurbsLegacyUserBlurb'; + const expectedParameters = { + user: 'userValue', + legacy_user: 'legacyUserValue', + blurb: 'blurbValue', + }; + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('userProfileBlurbsLegacyUserBlurbPath', () => { + const result = client.userProfileBlurbsLegacyUserBlurbPath( + 'userValue', + 'legacyUserValue', + 'blurbValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchUserFromUserProfileBlurbsLegacyUserBlurbName', () => { + const result = + client.matchUserFromUserProfileBlurbsLegacyUserBlurbName(fakePath); + assert.strictEqual(result, 'userValue'); + assert( + ( + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName', () => { + const result = + client.matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName( + fakePath, + ); + assert.strictEqual(result, 'legacyUserValue'); + assert( + ( + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBlurbFromUserProfileBlurbsLegacyUserBlurbName', () => { + const result = + client.matchBlurbFromUserProfileBlurbsLegacyUserBlurbName(fakePath); + assert.strictEqual(result, 'blurbValue'); + assert( + ( + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/core/generator/gapic-generator-typescript/baselines/disable-packing-test/test/gapic_testing_v1beta1.ts.baseline b/core/generator/gapic-generator-typescript/baselines/disable-packing-test/test/gapic_testing_v1beta1.ts.baseline index 55e55cff9e27..2a880c521c73 100644 --- a/core/generator/gapic-generator-typescript/baselines/disable-packing-test/test/gapic_testing_v1beta1.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/disable-packing-test/test/gapic_testing_v1beta1.ts.baseline @@ -19,1642 +19,2064 @@ import * as protos from '../protos/protos'; import * as assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as testingModule from '../src'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; -import {protobuf} from 'google-gax'; +import { protobuf } from 'google-gax'; // Dynamically loaded proto JSON is needed to get the type information // to fill in default values for request objects -const root = protobuf.Root.fromJSON(require('../protos/protos.json')).resolveAll(); +const root = protobuf.Root.fromJSON( + require('../protos/protos.json'), +).resolveAll(); // eslint-disable-next-line @typescript-eslint/no-unused-vars function getTypeDefaultValue(typeName: string, fields: string[]) { - let type = root.lookupType(typeName) as protobuf.Type; - for (const field of fields.slice(0, -1)) { - type = type.fields[field]?.resolvedType as protobuf.Type; - } - return type.fields[fields[fields.length - 1]]?.defaultValue; + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type.fields[field]?.resolvedType as protobuf.Type; + } + return type.fields[fields[fields.length - 1]]?.defaultValue; } function generateSampleMessage(instance: T) { - const filledObject = (instance.constructor as typeof protobuf.Message) - .toObject(instance as protobuf.Message, {defaults: true}); - return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, { defaults: true }); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; } function stubSimpleCall(response?: ResponseType, error?: Error) { - return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); } -function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { - return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +function stubSimpleCallWithCallback( + response?: ResponseType, + error?: Error, +) { + return error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); } -function stubPageStreamingCall(responses?: ResponseType[], error?: Error) { - const pagingStub = sinon.stub(); - if (responses) { - for (let i = 0; i < responses.length; ++i) { - pagingStub.onCall(i).callsArgWith(2, null, responses[i]); - } +function stubPageStreamingCall( + responses?: ResponseType[], + error?: Error, +) { + const pagingStub = sinon.stub(); + if (responses) { + for (let i = 0; i < responses.length; ++i) { + pagingStub.onCall(i).callsArgWith(2, null, responses[i]); } - const transformStub = error ? sinon.stub().callsArgWith(2, error) : pagingStub; - const mockStream = new PassThrough({ - objectMode: true, - transform: transformStub, - }); - // trigger as many responses as needed - if (responses) { - for (let i = 0; i < responses.length; ++i) { - setImmediate(() => { mockStream.write({}); }); - } - setImmediate(() => { mockStream.end(); }); - } else { - setImmediate(() => { mockStream.write({}); }); - setImmediate(() => { mockStream.end(); }); + } + const transformStub = error + ? sinon.stub().callsArgWith(2, error) + : pagingStub; + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + // trigger as many responses as needed + if (responses) { + for (let i = 0; i < responses.length; ++i) { + setImmediate(() => { + mockStream.write({}); + }); } - return sinon.stub().returns(mockStream); + setImmediate(() => { + mockStream.end(); + }); + } else { + setImmediate(() => { + mockStream.write({}); + }); + setImmediate(() => { + mockStream.end(); + }); + } + return sinon.stub().returns(mockStream); } -function stubAsyncIterationCall(responses?: ResponseType[], error?: Error) { - let counter = 0; - const asyncIterable = { - [Symbol.asyncIterator]() { - return { - async next() { - if (error) { - return Promise.reject(error); - } - if (counter >= responses!.length) { - return Promise.resolve({done: true, value: undefined}); - } - return Promise.resolve({done: false, value: responses![counter++]}); - } - }; - } - }; - return sinon.stub().returns(asyncIterable); +function stubAsyncIterationCall( + responses?: ResponseType[], + error?: Error, +) { + let counter = 0; + const asyncIterable = { + [Symbol.asyncIterator]() { + return { + async next() { + if (error) { + return Promise.reject(error); + } + if (counter >= responses!.length) { + return Promise.resolve({ done: true, value: undefined }); + } + return Promise.resolve({ done: false, value: responses![counter++] }); + }, + }; + }, + }; + return sinon.stub().returns(asyncIterable); } describe('v1beta1.TestingClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new testingModule.v1beta1.TestingClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'localhost'); - }); - - it('has universeDomain', () => { - const client = new testingModule.v1beta1.TestingClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); - - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - it('throws DeprecationWarning if static servicePath is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const servicePath = testingModule.v1beta1.TestingClient.servicePath; - assert.strictEqual(servicePath, 'localhost'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = testingModule.v1beta1.TestingClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'localhost'); - assert(stub.called); - stub.restore(); - }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { new testingModule.v1beta1.TestingClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new testingModule.v1beta1.TestingClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'localhost'); + }); - it('has port', () => { - const port = testingModule.v1beta1.TestingClient.port; - assert(port); - assert(typeof port === 'number'); - }); + it('has universeDomain', () => { + const client = new testingModule.v1beta1.TestingClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - it('should create a client with no option', () => { - const client = new testingModule.v1beta1.TestingClient(); - assert(client); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = testingModule.v1beta1.TestingClient.servicePath; + assert.strictEqual(servicePath, 'localhost'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = testingModule.v1beta1.TestingClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'localhost'); + assert(stub.called); + stub.restore(); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new testingModule.v1beta1.TestingClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); + }); - it('should create a client with gRPC fallback', () => { - const client = new testingModule.v1beta1.TestingClient({ - fallback: true, - }); - assert(client); - }); + it('has port', () => { + const port = testingModule.v1beta1.TestingClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('has initialize method and supports deferred initialization', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.testingStub, undefined); - await client.initialize(); - assert(client.testingStub); - }); + it('should create a client with no option', () => { + const client = new testingModule.v1beta1.TestingClient(); + assert(client); + }); - it('has close method for the initialized client', done => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.testingStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('should create a client with gRPC fallback', () => { + const client = new testingModule.v1beta1.TestingClient({ + fallback: true, + }); + assert(client); + }); - it('has close method for the non-initialized client', done => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.testingStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('has initialize method and supports deferred initialization', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.testingStub, undefined); + await client.initialize(); + assert(client.testingStub); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + it('has close method for the initialized client', (done) => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.testingStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId((err?: Error|null, projectId?: string|null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } - }); - }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); + it('has close method for the non-initialized client', (done) => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.testingStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); }); - describe('createSession', () => { - it('invokes createSession without error', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.CreateSessionRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.Session() - ); - client.innerApiCalls.createSession = stubSimpleCall(expectedResponse); - const [response] = await client.createSession(request); - assert.deepStrictEqual(response, expectedResponse); - }); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + }); - it('invokes createSession without error using callback', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.CreateSessionRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.Session() - ); - client.innerApiCalls.createSession = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createSession( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.ISession|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + }); + + describe('createSession', () => { + it('invokes createSession without error', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.CreateSessionRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.Session(), + ); + client.innerApiCalls.createSession = stubSimpleCall(expectedResponse); + const [response] = await client.createSession(request); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes createSession with error', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.CreateSessionRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.createSession = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createSession(request), expectedError); - }); + it('invokes createSession without error using callback', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.CreateSessionRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.Session(), + ); + client.innerApiCalls.createSession = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createSession( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.ISession | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes createSession with closed client', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.CreateSessionRequest() - ); - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createSession(request), expectedError); - }); + it('invokes createSession with error', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.CreateSessionRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.createSession = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.createSession(request), expectedError); }); - describe('getSession', () => { - it('invokes getSession without error', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.GetSessionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.GetSessionRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.Session() - ); - client.innerApiCalls.getSession = stubSimpleCall(expectedResponse); - const [response] = await client.getSession(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getSession as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getSession as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createSession with closed client', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.CreateSessionRequest(), + ); + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.createSession(request), expectedError); + }); + }); + + describe('getSession', () => { + it('invokes getSession without error', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.GetSessionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.GetSessionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.Session(), + ); + client.innerApiCalls.getSession = stubSimpleCall(expectedResponse); + const [response] = await client.getSession(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getSession as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getSession as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getSession without error using callback', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.GetSessionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.GetSessionRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.Session() - ); - client.innerApiCalls.getSession = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getSession( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.ISession|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getSession as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getSession as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getSession without error using callback', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.GetSessionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.GetSessionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.Session(), + ); + client.innerApiCalls.getSession = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getSession( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.ISession | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getSession as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getSession as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getSession with error', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.GetSessionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.GetSessionRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getSession = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getSession(request), expectedError); - const actualRequest = (client.innerApiCalls.getSession as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getSession as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getSession with error', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.GetSessionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.GetSessionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getSession = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getSession(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getSession as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getSession as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getSession with closed client', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.GetSessionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.GetSessionRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getSession(request), expectedError); - }); + it('invokes getSession with closed client', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.GetSessionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.GetSessionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getSession(request), expectedError); + }); + }); + + describe('deleteSession', () => { + it('invokes deleteSession without error', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.DeleteSessionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.DeleteSessionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteSession = stubSimpleCall(expectedResponse); + const [response] = await client.deleteSession(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteSession as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteSession as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('deleteSession', () => { - it('invokes deleteSession without error', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.DeleteSessionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.DeleteSessionRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteSession = stubSimpleCall(expectedResponse); - const [response] = await client.deleteSession(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteSession as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteSession as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteSession without error using callback', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.DeleteSessionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.DeleteSessionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteSession = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteSession( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteSession as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteSession as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteSession without error using callback', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.DeleteSessionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.DeleteSessionRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteSession = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteSession( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteSession as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteSession as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteSession with error', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.DeleteSessionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.DeleteSessionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteSession = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.deleteSession(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteSession as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteSession as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteSession with error', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.DeleteSessionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.DeleteSessionRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteSession = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteSession(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteSession as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteSession as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteSession with closed client', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.DeleteSessionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.DeleteSessionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.deleteSession(request), expectedError); + }); + }); + + describe('reportSession', () => { + it('invokes reportSession without error', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ReportSessionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.ReportSessionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.ReportSessionResponse(), + ); + client.innerApiCalls.reportSession = stubSimpleCall(expectedResponse); + const [response] = await client.reportSession(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.reportSession as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.reportSession as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteSession with closed client', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.DeleteSessionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.DeleteSessionRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteSession(request), expectedError); - }); + it('invokes reportSession without error using callback', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ReportSessionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.ReportSessionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.ReportSessionResponse(), + ); + client.innerApiCalls.reportSession = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.reportSession( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IReportSessionResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.reportSession as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.reportSession as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('reportSession', () => { - it('invokes reportSession without error', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ReportSessionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.ReportSessionRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.ReportSessionResponse() - ); - client.innerApiCalls.reportSession = stubSimpleCall(expectedResponse); - const [response] = await client.reportSession(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.reportSession as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.reportSession as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes reportSession with error', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ReportSessionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.ReportSessionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.reportSession = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.reportSession(request), expectedError); + const actualRequest = ( + client.innerApiCalls.reportSession as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.reportSession as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes reportSession without error using callback', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ReportSessionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.ReportSessionRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.ReportSessionResponse() - ); - client.innerApiCalls.reportSession = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.reportSession( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IReportSessionResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.reportSession as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.reportSession as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes reportSession with closed client', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ReportSessionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.ReportSessionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.reportSession(request), expectedError); + }); + }); + + describe('deleteTest', () => { + it('invokes deleteTest without error', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.DeleteTestRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.DeleteTestRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteTest = stubSimpleCall(expectedResponse); + const [response] = await client.deleteTest(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteTest as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteTest as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes reportSession with error', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ReportSessionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.ReportSessionRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.reportSession = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.reportSession(request), expectedError); - const actualRequest = (client.innerApiCalls.reportSession as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.reportSession as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteTest without error using callback', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.DeleteTestRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.DeleteTestRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteTest = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteTest( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteTest as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteTest as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes reportSession with closed client', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ReportSessionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.ReportSessionRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.reportSession(request), expectedError); - }); + it('invokes deleteTest with error', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.DeleteTestRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.DeleteTestRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteTest = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.deleteTest(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteTest as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteTest as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('deleteTest', () => { - it('invokes deleteTest without error', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.DeleteTestRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.DeleteTestRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteTest = stubSimpleCall(expectedResponse); - const [response] = await client.deleteTest(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteTest as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteTest as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteTest with closed client', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.DeleteTestRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.DeleteTestRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.deleteTest(request), expectedError); + }); + }); + + describe('verifyTest', () => { + it('invokes verifyTest without error', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.VerifyTestRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.VerifyTestRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.VerifyTestResponse(), + ); + client.innerApiCalls.verifyTest = stubSimpleCall(expectedResponse); + const [response] = await client.verifyTest(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.verifyTest as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.verifyTest as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteTest without error using callback', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.DeleteTestRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.DeleteTestRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteTest = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteTest( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteTest as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteTest as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes verifyTest without error using callback', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.VerifyTestRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.VerifyTestRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.VerifyTestResponse(), + ); + client.innerApiCalls.verifyTest = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.verifyTest( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IVerifyTestResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.verifyTest as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.verifyTest as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteTest with error', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.DeleteTestRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.DeleteTestRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteTest = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteTest(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteTest as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteTest as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes verifyTest with error', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.VerifyTestRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.VerifyTestRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.verifyTest = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.verifyTest(request), expectedError); + const actualRequest = ( + client.innerApiCalls.verifyTest as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.verifyTest as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteTest with closed client', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.DeleteTestRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.DeleteTestRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteTest(request), expectedError); - }); + it('invokes verifyTest with closed client', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.VerifyTestRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.VerifyTestRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.verifyTest(request), expectedError); + }); + }); + + describe('listSessions', () => { + it('invokes listSessions without error', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListSessionsRequest(), + ); + const expectedResponse = [ + generateSampleMessage(new protos.google.showcase.v1beta1.Session()), + generateSampleMessage(new protos.google.showcase.v1beta1.Session()), + generateSampleMessage(new protos.google.showcase.v1beta1.Session()), + ]; + client.innerApiCalls.listSessions = stubSimpleCall(expectedResponse); + const [response] = await client.listSessions(request); + assert.deepStrictEqual(response, expectedResponse); }); - describe('verifyTest', () => { - it('invokes verifyTest without error', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.VerifyTestRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.VerifyTestRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.VerifyTestResponse() - ); - client.innerApiCalls.verifyTest = stubSimpleCall(expectedResponse); - const [response] = await client.verifyTest(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.verifyTest as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.verifyTest as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listSessions without error using callback', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListSessionsRequest(), + ); + const expectedResponse = [ + generateSampleMessage(new protos.google.showcase.v1beta1.Session()), + generateSampleMessage(new protos.google.showcase.v1beta1.Session()), + generateSampleMessage(new protos.google.showcase.v1beta1.Session()), + ]; + client.innerApiCalls.listSessions = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listSessions( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.ISession[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes verifyTest without error using callback', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.VerifyTestRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.VerifyTestRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.VerifyTestResponse() - ); - client.innerApiCalls.verifyTest = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.verifyTest( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IVerifyTestResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.verifyTest as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.verifyTest as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listSessions with error', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListSessionsRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.listSessions = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listSessions(request), expectedError); + }); - it('invokes verifyTest with error', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.VerifyTestRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.VerifyTestRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.verifyTest = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.verifyTest(request), expectedError); - const actualRequest = (client.innerApiCalls.verifyTest as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.verifyTest as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes listSessionsStream without error', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListSessionsRequest(), + ); + const expectedResponse = [ + generateSampleMessage(new protos.google.showcase.v1beta1.Session()), + generateSampleMessage(new protos.google.showcase.v1beta1.Session()), + generateSampleMessage(new protos.google.showcase.v1beta1.Session()), + ]; + client.descriptors.page.listSessions.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listSessionsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.showcase.v1beta1.Session[] = []; + stream.on( + 'data', + (response: protos.google.showcase.v1beta1.Session) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); }); - - it('invokes verifyTest with closed client', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.VerifyTestRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.VerifyTestRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.verifyTest(request), expectedError); + stream.on('error', (err: Error) => { + reject(err); }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listSessions.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listSessions, request), + ); }); - describe('listSessions', () => { - it('invokes listSessions without error', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListSessionsRequest() - );const expectedResponse = [ - generateSampleMessage(new protos.google.showcase.v1beta1.Session()), - generateSampleMessage(new protos.google.showcase.v1beta1.Session()), - generateSampleMessage(new protos.google.showcase.v1beta1.Session()), - ]; - client.innerApiCalls.listSessions = stubSimpleCall(expectedResponse); - const [response] = await client.listSessions(request); - assert.deepStrictEqual(response, expectedResponse); - }); - - it('invokes listSessions without error using callback', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListSessionsRequest() - );const expectedResponse = [ - generateSampleMessage(new protos.google.showcase.v1beta1.Session()), - generateSampleMessage(new protos.google.showcase.v1beta1.Session()), - generateSampleMessage(new protos.google.showcase.v1beta1.Session()), - ]; - client.innerApiCalls.listSessions = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listSessions( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.ISession[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); + it('invokes listSessionsStream with error', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListSessionsRequest(), + ); + const expectedError = new Error('expected'); + client.descriptors.page.listSessions.createStream = stubPageStreamingCall( + undefined, + expectedError, + ); + const stream = client.listSessionsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.showcase.v1beta1.Session[] = []; + stream.on( + 'data', + (response: protos.google.showcase.v1beta1.Session) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); }); - - it('invokes listSessions with error', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListSessionsRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.listSessions = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listSessions(request), expectedError); + stream.on('error', (err: Error) => { + reject(err); }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listSessions.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listSessions, request), + ); + }); - it('invokes listSessionsStream without error', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListSessionsRequest() - ); - const expectedResponse = [ - generateSampleMessage(new protos.google.showcase.v1beta1.Session()), - generateSampleMessage(new protos.google.showcase.v1beta1.Session()), - generateSampleMessage(new protos.google.showcase.v1beta1.Session()), - ]; - client.descriptors.page.listSessions.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listSessionsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.showcase.v1beta1.Session[] = []; - stream.on('data', (response: protos.google.showcase.v1beta1.Session) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.listSessions.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listSessions, request)); - }); + it('uses async iteration with listSessions without error', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListSessionsRequest(), + ); + const expectedResponse = [ + generateSampleMessage(new protos.google.showcase.v1beta1.Session()), + generateSampleMessage(new protos.google.showcase.v1beta1.Session()), + generateSampleMessage(new protos.google.showcase.v1beta1.Session()), + ]; + client.descriptors.page.listSessions.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.showcase.v1beta1.ISession[] = []; + const iterable = client.listSessionsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listSessions.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + }); - it('invokes listSessionsStream with error', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListSessionsRequest() - ); - const expectedError = new Error('expected'); - client.descriptors.page.listSessions.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listSessionsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.showcase.v1beta1.Session[] = []; - stream.on('data', (response: protos.google.showcase.v1beta1.Session) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listSessions.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listSessions, request)); - }); + it('uses async iteration with listSessions with error', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListSessionsRequest(), + ); + const expectedError = new Error('expected'); + client.descriptors.page.listSessions.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listSessionsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.showcase.v1beta1.ISession[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listSessions.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + }); + }); + + describe('listTests', () => { + it('invokes listTests without error', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListTestsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.ListTestsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.showcase.v1beta1.Test()), + generateSampleMessage(new protos.google.showcase.v1beta1.Test()), + generateSampleMessage(new protos.google.showcase.v1beta1.Test()), + ]; + client.innerApiCalls.listTests = stubSimpleCall(expectedResponse); + const [response] = await client.listTests(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listTests as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listTests as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('uses async iteration with listSessions without error', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListSessionsRequest() - ); - const expectedResponse = [ - generateSampleMessage(new protos.google.showcase.v1beta1.Session()), - generateSampleMessage(new protos.google.showcase.v1beta1.Session()), - generateSampleMessage(new protos.google.showcase.v1beta1.Session()), - ]; - client.descriptors.page.listSessions.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.showcase.v1beta1.ISession[] = []; - const iterable = client.listSessionsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); + it('invokes listTests without error using callback', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListTestsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.ListTestsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.showcase.v1beta1.Test()), + generateSampleMessage(new protos.google.showcase.v1beta1.Test()), + generateSampleMessage(new protos.google.showcase.v1beta1.Test()), + ]; + client.innerApiCalls.listTests = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listTests( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.ITest[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listSessions.asyncIterate as SinonStub) - .getCall(0).args[1], request); - }); + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listTests as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listTests as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('uses async iteration with listSessions with error', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListSessionsRequest() - ); - const expectedError = new Error('expected'); - client.descriptors.page.listSessions.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listSessionsAsync(request); - await assert.rejects(async () => { - const responses: protos.google.showcase.v1beta1.ISession[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listSessions.asyncIterate as SinonStub) - .getCall(0).args[1], request); - }); + it('invokes listTests with error', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListTestsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.ListTestsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listTests = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.listTests(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listTests as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listTests as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('listTests', () => { - it('invokes listTests without error', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListTestsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.ListTestsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.showcase.v1beta1.Test()), - generateSampleMessage(new protos.google.showcase.v1beta1.Test()), - generateSampleMessage(new protos.google.showcase.v1beta1.Test()), - ]; - client.innerApiCalls.listTests = stubSimpleCall(expectedResponse); - const [response] = await client.listTests(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listTests as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listTests as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes listTestsStream without error', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListTestsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.ListTestsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.showcase.v1beta1.Test()), + generateSampleMessage(new protos.google.showcase.v1beta1.Test()), + generateSampleMessage(new protos.google.showcase.v1beta1.Test()), + ]; + client.descriptors.page.listTests.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listTestsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.showcase.v1beta1.Test[] = []; + stream.on('data', (response: protos.google.showcase.v1beta1.Test) => { + responses.push(response); }); - - it('invokes listTests without error using callback', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListTestsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.ListTestsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.showcase.v1beta1.Test()), - generateSampleMessage(new protos.google.showcase.v1beta1.Test()), - generateSampleMessage(new protos.google.showcase.v1beta1.Test()), - ]; - client.innerApiCalls.listTests = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listTests( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.ITest[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listTests as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listTests as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + stream.on('end', () => { + resolve(responses); }); - - it('invokes listTests with error', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListTestsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.ListTestsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listTests = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listTests(request), expectedError); - const actualRequest = (client.innerApiCalls.listTests as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listTests as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + stream.on('error', (err: Error) => { + reject(err); }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listTests.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listTests, request), + ); + assert( + (client.descriptors.page.listTests.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('invokes listTestsStream without error', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListTestsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.ListTestsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.showcase.v1beta1.Test()), - generateSampleMessage(new protos.google.showcase.v1beta1.Test()), - generateSampleMessage(new protos.google.showcase.v1beta1.Test()), - ]; - client.descriptors.page.listTests.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listTestsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.showcase.v1beta1.Test[] = []; - stream.on('data', (response: protos.google.showcase.v1beta1.Test) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.listTests.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listTests, request)); - assert( - (client.descriptors.page.listTests.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); + it('invokes listTestsStream with error', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListTestsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.ListTestsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listTests.createStream = stubPageStreamingCall( + undefined, + expectedError, + ); + const stream = client.listTestsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.showcase.v1beta1.Test[] = []; + stream.on('data', (response: protos.google.showcase.v1beta1.Test) => { + responses.push(response); }); - - it('invokes listTestsStream with error', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListTestsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.ListTestsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listTests.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listTestsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.showcase.v1beta1.Test[] = []; - stream.on('data', (response: protos.google.showcase.v1beta1.Test) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listTests.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listTests, request)); - assert( - (client.descriptors.page.listTests.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); + stream.on('end', () => { + resolve(responses); }); - - it('uses async iteration with listTests without error', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListTestsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.ListTestsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.showcase.v1beta1.Test()), - generateSampleMessage(new protos.google.showcase.v1beta1.Test()), - generateSampleMessage(new protos.google.showcase.v1beta1.Test()), - ]; - client.descriptors.page.listTests.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.showcase.v1beta1.ITest[] = []; - const iterable = client.listTestsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listTests.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listTests.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); + stream.on('error', (err: Error) => { + reject(err); }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listTests.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listTests, request), + ); + assert( + (client.descriptors.page.listTests.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('uses async iteration with listTests with error', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListTestsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.ListTestsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listTests.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listTestsAsync(request); - await assert.rejects(async () => { - const responses: protos.google.showcase.v1beta1.ITest[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listTests.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listTests.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listTests without error', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListTestsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.ListTestsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.showcase.v1beta1.Test()), + generateSampleMessage(new protos.google.showcase.v1beta1.Test()), + generateSampleMessage(new protos.google.showcase.v1beta1.Test()), + ]; + client.descriptors.page.listTests.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.showcase.v1beta1.ITest[] = []; + const iterable = client.listTestsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + (client.descriptors.page.listTests.asyncIterate as SinonStub).getCall(0) + .args[1], + request, + ); + assert( + (client.descriptors.page.listTests.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); }); - describe('Path templates', () => { - - describe('blueprint', async () => { - const fakePath = "/rendered/path/blueprint"; - const expectedParameters = { - session: "sessionValue", - test: "testValue", - blueprint: "blueprintValue", - }; - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.blueprintPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.blueprintPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('blueprintPath', () => { - const result = client.blueprintPath("sessionValue", "testValue", "blueprintValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.blueprintPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchSessionFromBlueprintName', () => { - const result = client.matchSessionFromBlueprintName(fakePath); - assert.strictEqual(result, "sessionValue"); - assert((client.pathTemplates.blueprintPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchTestFromBlueprintName', () => { - const result = client.matchTestFromBlueprintName(fakePath); - assert.strictEqual(result, "testValue"); - assert((client.pathTemplates.blueprintPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBlueprintFromBlueprintName', () => { - const result = client.matchBlueprintFromBlueprintName(fakePath); - assert.strictEqual(result, "blueprintValue"); - assert((client.pathTemplates.blueprintPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('uses async iteration with listTests with error', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListTestsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.ListTestsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listTests.asyncIterate = stubAsyncIterationCall( + undefined, + expectedError, + ); + const iterable = client.listTestsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.showcase.v1beta1.ITest[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + (client.descriptors.page.listTests.asyncIterate as SinonStub).getCall(0) + .args[1], + request, + ); + assert( + (client.descriptors.page.listTests.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + }); + + describe('Path templates', () => { + describe('blueprint', async () => { + const fakePath = '/rendered/path/blueprint'; + const expectedParameters = { + session: 'sessionValue', + test: 'testValue', + blueprint: 'blueprintValue', + }; + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.blueprintPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.blueprintPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('blueprintPath', () => { + const result = client.blueprintPath( + 'sessionValue', + 'testValue', + 'blueprintValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.blueprintPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchSessionFromBlueprintName', () => { + const result = client.matchSessionFromBlueprintName(fakePath); + assert.strictEqual(result, 'sessionValue'); + assert( + (client.pathTemplates.blueprintPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchTestFromBlueprintName', () => { + const result = client.matchTestFromBlueprintName(fakePath); + assert.strictEqual(result, 'testValue'); + assert( + (client.pathTemplates.blueprintPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBlueprintFromBlueprintName', () => { + const result = client.matchBlueprintFromBlueprintName(fakePath); + assert.strictEqual(result, 'blueprintValue'); + assert( + (client.pathTemplates.blueprintPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('room', async () => { - const fakePath = "/rendered/path/room"; - const expectedParameters = { - room: "roomValue", - }; - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.roomPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.roomPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('roomPath', () => { - const result = client.roomPath("roomValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.roomPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchRoomFromRoomName', () => { - const result = client.matchRoomFromRoomName(fakePath); - assert.strictEqual(result, "roomValue"); - assert((client.pathTemplates.roomPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('room', async () => { + const fakePath = '/rendered/path/room'; + const expectedParameters = { + room: 'roomValue', + }; + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.roomPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.roomPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('roomPath', () => { + const result = client.roomPath('roomValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.roomPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchRoomFromRoomName', () => { + const result = client.matchRoomFromRoomName(fakePath); + assert.strictEqual(result, 'roomValue'); + assert( + (client.pathTemplates.roomPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('roomBlurb', async () => { - const fakePath = "/rendered/path/roomBlurb"; - const expectedParameters = { - room: "roomValue", - blurb: "blurbValue", - }; - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.roomBlurbPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.roomBlurbPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('roomBlurbPath', () => { - const result = client.roomBlurbPath("roomValue", "blurbValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.roomBlurbPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchRoomFromRoomBlurbName', () => { - const result = client.matchRoomFromRoomBlurbName(fakePath); - assert.strictEqual(result, "roomValue"); - assert((client.pathTemplates.roomBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBlurbFromRoomBlurbName', () => { - const result = client.matchBlurbFromRoomBlurbName(fakePath); - assert.strictEqual(result, "blurbValue"); - assert((client.pathTemplates.roomBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('roomBlurb', async () => { + const fakePath = '/rendered/path/roomBlurb'; + const expectedParameters = { + room: 'roomValue', + blurb: 'blurbValue', + }; + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.roomBlurbPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.roomBlurbPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('roomBlurbPath', () => { + const result = client.roomBlurbPath('roomValue', 'blurbValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.roomBlurbPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchRoomFromRoomBlurbName', () => { + const result = client.matchRoomFromRoomBlurbName(fakePath); + assert.strictEqual(result, 'roomValue'); + assert( + (client.pathTemplates.roomBlurbPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBlurbFromRoomBlurbName', () => { + const result = client.matchBlurbFromRoomBlurbName(fakePath); + assert.strictEqual(result, 'blurbValue'); + assert( + (client.pathTemplates.roomBlurbPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('roomBlurbsLegacyRoomBlurb', async () => { - const fakePath = "/rendered/path/roomBlurbsLegacyRoomBlurb"; - const expectedParameters = { - room: "roomValue", - legacy_room: "legacyRoomValue", - blurb: "blurbValue", - }; - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('roomBlurbsLegacyRoomBlurbPath', () => { - const result = client.roomBlurbsLegacyRoomBlurbPath("roomValue", "legacyRoomValue", "blurbValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchRoomFromRoomBlurbsLegacyRoomBlurbName', () => { - const result = client.matchRoomFromRoomBlurbsLegacyRoomBlurbName(fakePath); - assert.strictEqual(result, "roomValue"); - assert((client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName', () => { - const result = client.matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName(fakePath); - assert.strictEqual(result, "legacyRoomValue"); - assert((client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBlurbFromRoomBlurbsLegacyRoomBlurbName', () => { - const result = client.matchBlurbFromRoomBlurbsLegacyRoomBlurbName(fakePath); - assert.strictEqual(result, "blurbValue"); - assert((client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('roomBlurbsLegacyRoomBlurb', async () => { + const fakePath = '/rendered/path/roomBlurbsLegacyRoomBlurb'; + const expectedParameters = { + room: 'roomValue', + legacy_room: 'legacyRoomValue', + blurb: 'blurbValue', + }; + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('roomBlurbsLegacyRoomBlurbPath', () => { + const result = client.roomBlurbsLegacyRoomBlurbPath( + 'roomValue', + 'legacyRoomValue', + 'blurbValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchRoomFromRoomBlurbsLegacyRoomBlurbName', () => { + const result = + client.matchRoomFromRoomBlurbsLegacyRoomBlurbName(fakePath); + assert.strictEqual(result, 'roomValue'); + assert( + ( + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName', () => { + const result = + client.matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName(fakePath); + assert.strictEqual(result, 'legacyRoomValue'); + assert( + ( + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBlurbFromRoomBlurbsLegacyRoomBlurbName', () => { + const result = + client.matchBlurbFromRoomBlurbsLegacyRoomBlurbName(fakePath); + assert.strictEqual(result, 'blurbValue'); + assert( + ( + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('sequence', async () => { - const fakePath = "/rendered/path/sequence"; - const expectedParameters = { - sequence: "sequenceValue", - }; - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.sequencePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.sequencePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('sequencePath', () => { - const result = client.sequencePath("sequenceValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.sequencePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchSequenceFromSequenceName', () => { - const result = client.matchSequenceFromSequenceName(fakePath); - assert.strictEqual(result, "sequenceValue"); - assert((client.pathTemplates.sequencePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('sequence', async () => { + const fakePath = '/rendered/path/sequence'; + const expectedParameters = { + sequence: 'sequenceValue', + }; + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.sequencePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.sequencePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('sequencePath', () => { + const result = client.sequencePath('sequenceValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.sequencePathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchSequenceFromSequenceName', () => { + const result = client.matchSequenceFromSequenceName(fakePath); + assert.strictEqual(result, 'sequenceValue'); + assert( + (client.pathTemplates.sequencePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('sequenceReport', async () => { - const fakePath = "/rendered/path/sequenceReport"; - const expectedParameters = { - sequence: "sequenceValue", - }; - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.sequenceReportPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.sequenceReportPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('sequenceReportPath', () => { - const result = client.sequenceReportPath("sequenceValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.sequenceReportPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchSequenceFromSequenceReportName', () => { - const result = client.matchSequenceFromSequenceReportName(fakePath); - assert.strictEqual(result, "sequenceValue"); - assert((client.pathTemplates.sequenceReportPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('sequenceReport', async () => { + const fakePath = '/rendered/path/sequenceReport'; + const expectedParameters = { + sequence: 'sequenceValue', + }; + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.sequenceReportPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.sequenceReportPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('sequenceReportPath', () => { + const result = client.sequenceReportPath('sequenceValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.sequenceReportPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchSequenceFromSequenceReportName', () => { + const result = client.matchSequenceFromSequenceReportName(fakePath); + assert.strictEqual(result, 'sequenceValue'); + assert( + (client.pathTemplates.sequenceReportPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('session', async () => { - const fakePath = "/rendered/path/session"; - const expectedParameters = { - session: "sessionValue", - }; - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.sessionPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.sessionPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('sessionPath', () => { - const result = client.sessionPath("sessionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.sessionPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchSessionFromSessionName', () => { - const result = client.matchSessionFromSessionName(fakePath); - assert.strictEqual(result, "sessionValue"); - assert((client.pathTemplates.sessionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('session', async () => { + const fakePath = '/rendered/path/session'; + const expectedParameters = { + session: 'sessionValue', + }; + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.sessionPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.sessionPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('sessionPath', () => { + const result = client.sessionPath('sessionValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.sessionPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchSessionFromSessionName', () => { + const result = client.matchSessionFromSessionName(fakePath); + assert.strictEqual(result, 'sessionValue'); + assert( + (client.pathTemplates.sessionPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('test', async () => { - const fakePath = "/rendered/path/test"; - const expectedParameters = { - session: "sessionValue", - test: "testValue", - }; - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.testPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.testPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('testPath', () => { - const result = client.testPath("sessionValue", "testValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.testPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchSessionFromTestName', () => { - const result = client.matchSessionFromTestName(fakePath); - assert.strictEqual(result, "sessionValue"); - assert((client.pathTemplates.testPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchTestFromTestName', () => { - const result = client.matchTestFromTestName(fakePath); - assert.strictEqual(result, "testValue"); - assert((client.pathTemplates.testPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('test', async () => { + const fakePath = '/rendered/path/test'; + const expectedParameters = { + session: 'sessionValue', + test: 'testValue', + }; + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.testPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.testPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('testPath', () => { + const result = client.testPath('sessionValue', 'testValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.testPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchSessionFromTestName', () => { + const result = client.matchSessionFromTestName(fakePath); + assert.strictEqual(result, 'sessionValue'); + assert( + (client.pathTemplates.testPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchTestFromTestName', () => { + const result = client.matchTestFromTestName(fakePath); + assert.strictEqual(result, 'testValue'); + assert( + (client.pathTemplates.testPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('user', async () => { - const fakePath = "/rendered/path/user"; - const expectedParameters = { - user: "userValue", - }; - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.userPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.userPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('userPath', () => { - const result = client.userPath("userValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.userPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchUserFromUserName', () => { - const result = client.matchUserFromUserName(fakePath); - assert.strictEqual(result, "userValue"); - assert((client.pathTemplates.userPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('user', async () => { + const fakePath = '/rendered/path/user'; + const expectedParameters = { + user: 'userValue', + }; + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.userPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.userPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('userPath', () => { + const result = client.userPath('userValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.userPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchUserFromUserName', () => { + const result = client.matchUserFromUserName(fakePath); + assert.strictEqual(result, 'userValue'); + assert( + (client.pathTemplates.userPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('userProfileBlurb', async () => { - const fakePath = "/rendered/path/userProfileBlurb"; - const expectedParameters = { - user: "userValue", - blurb: "blurbValue", - }; - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.userProfileBlurbPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.userProfileBlurbPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('userProfileBlurbPath', () => { - const result = client.userProfileBlurbPath("userValue", "blurbValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.userProfileBlurbPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchUserFromUserProfileBlurbName', () => { - const result = client.matchUserFromUserProfileBlurbName(fakePath); - assert.strictEqual(result, "userValue"); - assert((client.pathTemplates.userProfileBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBlurbFromUserProfileBlurbName', () => { - const result = client.matchBlurbFromUserProfileBlurbName(fakePath); - assert.strictEqual(result, "blurbValue"); - assert((client.pathTemplates.userProfileBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('userProfileBlurb', async () => { + const fakePath = '/rendered/path/userProfileBlurb'; + const expectedParameters = { + user: 'userValue', + blurb: 'blurbValue', + }; + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.userProfileBlurbPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.userProfileBlurbPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('userProfileBlurbPath', () => { + const result = client.userProfileBlurbPath('userValue', 'blurbValue'); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.userProfileBlurbPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchUserFromUserProfileBlurbName', () => { + const result = client.matchUserFromUserProfileBlurbName(fakePath); + assert.strictEqual(result, 'userValue'); + assert( + (client.pathTemplates.userProfileBlurbPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBlurbFromUserProfileBlurbName', () => { + const result = client.matchBlurbFromUserProfileBlurbName(fakePath); + assert.strictEqual(result, 'blurbValue'); + assert( + (client.pathTemplates.userProfileBlurbPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('userProfileBlurbsLegacyUserBlurb', async () => { - const fakePath = "/rendered/path/userProfileBlurbsLegacyUserBlurb"; - const expectedParameters = { - user: "userValue", - legacy_user: "legacyUserValue", - blurb: "blurbValue", - }; - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('userProfileBlurbsLegacyUserBlurbPath', () => { - const result = client.userProfileBlurbsLegacyUserBlurbPath("userValue", "legacyUserValue", "blurbValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchUserFromUserProfileBlurbsLegacyUserBlurbName', () => { - const result = client.matchUserFromUserProfileBlurbsLegacyUserBlurbName(fakePath); - assert.strictEqual(result, "userValue"); - assert((client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName', () => { - const result = client.matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName(fakePath); - assert.strictEqual(result, "legacyUserValue"); - assert((client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBlurbFromUserProfileBlurbsLegacyUserBlurbName', () => { - const result = client.matchBlurbFromUserProfileBlurbsLegacyUserBlurbName(fakePath); - assert.strictEqual(result, "blurbValue"); - assert((client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('userProfileBlurbsLegacyUserBlurb', async () => { + const fakePath = '/rendered/path/userProfileBlurbsLegacyUserBlurb'; + const expectedParameters = { + user: 'userValue', + legacy_user: 'legacyUserValue', + blurb: 'blurbValue', + }; + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('userProfileBlurbsLegacyUserBlurbPath', () => { + const result = client.userProfileBlurbsLegacyUserBlurbPath( + 'userValue', + 'legacyUserValue', + 'blurbValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchUserFromUserProfileBlurbsLegacyUserBlurbName', () => { + const result = + client.matchUserFromUserProfileBlurbsLegacyUserBlurbName(fakePath); + assert.strictEqual(result, 'userValue'); + assert( + ( + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName', () => { + const result = + client.matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName( + fakePath, + ); + assert.strictEqual(result, 'legacyUserValue'); + assert( + ( + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBlurbFromUserProfileBlurbsLegacyUserBlurbName', () => { + const result = + client.matchBlurbFromUserProfileBlurbsLegacyUserBlurbName(fakePath); + assert.strictEqual(result, 'blurbValue'); + assert( + ( + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/core/generator/gapic-generator-typescript/baselines/dlp-esm/esm/src/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/dlp-esm/esm/src/index.ts.baseline index 409e88a67690..b6396af6d0ce 100644 --- a/core/generator/gapic-generator-typescript/baselines/dlp-esm/esm/src/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/dlp-esm/esm/src/index.ts.baseline @@ -19,8 +19,8 @@ import * as v2 from './v2/index.js'; const DlpServiceClient = v2.DlpServiceClient; type DlpServiceClient = v2.DlpServiceClient; -export {v2, DlpServiceClient}; -export default {v2, DlpServiceClient}; +export { v2, DlpServiceClient }; +export default { v2, DlpServiceClient }; // @ts-ignore import * as protos from '../../protos/protos.js'; -export {protos} +export { protos }; diff --git a/core/generator/gapic-generator-typescript/baselines/dlp-esm/esm/src/v2/dlp_service_client.ts.baseline b/core/generator/gapic-generator-typescript/baselines/dlp-esm/esm/src/v2/dlp_service_client.ts.baseline index 34c8964ef0a2..7ad51227eba1 100644 --- a/core/generator/gapic-generator-typescript/baselines/dlp-esm/esm/src/v2/dlp_service_client.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/dlp-esm/esm/src/v2/dlp_service_client.ts.baseline @@ -18,15 +18,22 @@ /* global window */ import * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions, PaginationCallback, GaxCall} from 'google-gax'; -import {Transform} from 'stream'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + PaginationCallback, + GaxCall, +} from 'google-gax'; +import { Transform } from 'stream'; // @ts-ignore import type * as protos from '../../../protos/protos.js'; import * as dlp_service_client_config from './dlp_service_client_config.json'; import fs from 'fs'; import path from 'path'; -import {fileURLToPath} from 'url'; -import {getJSON} from '../json-helper.cjs'; +import { fileURLToPath } from 'url'; +import { getJSON } from '../json-helper.cjs'; // @ts-ignore const dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -36,15 +43,15 @@ const dirname = path.dirname(fileURLToPath(import.meta.url)); * This file defines retry strategy and timeouts for all API methods in this library. */ const gapicConfig = getJSON( - path.join(dirname, 'dlp_service_client_config.json') + path.join(dirname, 'dlp_service_client_config.json'), ); const jsonProtos = getJSON( - path.join(dirname, '..', '..', '..', 'protos/protos.json') + path.join(dirname, '..', '..', '..', 'protos/protos.json'), ); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; const version = getJSON( - path.join(dirname, '..', '..', '..', '..', 'package.json') + path.join(dirname, '..', '..', '..', '..', 'package.json'), ).version; /** @@ -67,7 +74,7 @@ export class DlpServiceClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('dlp'); @@ -79,9 +86,9 @@ export class DlpServiceClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; - dlpServiceStub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; + dlpServiceStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of DlpServiceClient. @@ -123,21 +130,42 @@ export class DlpServiceClient { * const client = new DlpServiceClient({fallback: 'rest'}, gax); * ``` */ - constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { // Ensure that options include all the required fields. const staticMembers = this.constructor as typeof DlpServiceClient; - if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { - throw new Error('Please set either universe_domain or universeDomain, but not both.'); + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); } - const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; - this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; this._servicePath = 'dlp.' + this._universeDomain; - const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; - const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. if (servicePath !== this._servicePath && !('scopes' in opts)) { @@ -159,7 +187,7 @@ export class DlpServiceClient { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; @@ -176,10 +204,7 @@ export class DlpServiceClient { const isEsm = true; const isEsmString = isEsm ? '-esm' : '-cjs'; // Determine the client header string. - const clientHeader = [ - `gax/${this._gaxModule.version}`, - `gapic/${version}`, - ]; + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/{process.versions.node}${isEsmString}`); } else { @@ -187,7 +212,7 @@ export class DlpServiceClient { } if (!opts.fallback) { clientHeader.push(`grpc/${this._gaxGrpc.grpcVersion}`); - } else if (opts.fallback === 'rest' ) { + } else if (opts.fallback === 'rest') { clientHeader.push(`rest/${this._gaxGrpc.grpcVersion}`); } if (opts.libName && opts.libVersion) { @@ -195,41 +220,44 @@ export class DlpServiceClient { } // Load the applicable protos. - this._protos = this._gaxGrpc.loadProtoJSON(jsonProtos as gax.protobuf.INamespace); + this._protos = this._gaxGrpc.loadProtoJSON( + jsonProtos as gax.protobuf.INamespace, + ); // This API contains "path templates"; forward-slash-separated // identifiers to uniquely identify resources within the API. // Create useful helper objects for these. this.pathTemplates = { dlpJobPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/dlpJobs/{dlp_job}' + 'projects/{project}/dlpJobs/{dlp_job}', ), jobTriggerPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/jobTriggers/{job_trigger}' + 'projects/{project}/jobTriggers/{job_trigger}', ), organizationPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}' - ), - organizationDeidentifyTemplatePathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/deidentifyTemplates/{deidentify_template}' + 'organizations/{organization}', ), + organizationDeidentifyTemplatePathTemplate: + new this._gaxModule.PathTemplate( + 'organizations/{organization}/deidentifyTemplates/{deidentify_template}', + ), organizationInspectTemplatePathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/inspectTemplates/{inspect_template}' + 'organizations/{organization}/inspectTemplates/{inspect_template}', ), organizationStoredInfoTypePathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/storedInfoTypes/{stored_info_type}' + 'organizations/{organization}/storedInfoTypes/{stored_info_type}', ), projectPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}' + 'projects/{project}', ), projectDeidentifyTemplatePathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/deidentifyTemplates/{deidentify_template}' + 'projects/{project}/deidentifyTemplates/{deidentify_template}', ), projectInspectTemplatePathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/inspectTemplates/{inspect_template}' + 'projects/{project}/inspectTemplates/{inspect_template}', ), projectStoredInfoTypePathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/storedInfoTypes/{stored_info_type}' + 'projects/{project}/storedInfoTypes/{stored_info_type}', ), }; @@ -237,22 +265,40 @@ export class DlpServiceClient { // (e.g. 50 results at a time, with tokens to get subsequent // pages). Denote the keys used for pagination and results. this.descriptors.page = { - listInspectTemplates: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'inspectTemplates'), - listDeidentifyTemplates: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'deidentifyTemplates'), - listJobTriggers: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'jobTriggers'), - listDlpJobs: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'jobs'), - listStoredInfoTypes: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'storedInfoTypes') + listInspectTemplates: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'inspectTemplates', + ), + listDeidentifyTemplates: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'deidentifyTemplates', + ), + listJobTriggers: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'jobTriggers', + ), + listDlpJobs: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'jobs', + ), + listStoredInfoTypes: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'storedInfoTypes', + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.privacy.dlp.v2.DlpService', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.privacy.dlp.v2.DlpService', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + { 'x-goog-api-client': clientHeader.join(' ') }, + ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -283,37 +329,72 @@ export class DlpServiceClient { // Put together the "service stub" for // google.privacy.dlp.v2.DlpService. this.dlpServiceStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.privacy.dlp.v2.DlpService') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.privacy.dlp.v2.DlpService', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.privacy.dlp.v2.DlpService, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts, + this._providedCustomServicePath, + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const dlpServiceStubMethods = - ['inspectContent', 'redactImage', 'deidentifyContent', 'reidentifyContent', 'listInfoTypes', 'createInspectTemplate', 'updateInspectTemplate', 'getInspectTemplate', 'listInspectTemplates', 'deleteInspectTemplate', 'createDeidentifyTemplate', 'updateDeidentifyTemplate', 'getDeidentifyTemplate', 'listDeidentifyTemplates', 'deleteDeidentifyTemplate', 'createJobTrigger', 'updateJobTrigger', 'getJobTrigger', 'listJobTriggers', 'deleteJobTrigger', 'activateJobTrigger', 'createDlpJob', 'listDlpJobs', 'getDlpJob', 'deleteDlpJob', 'cancelDlpJob', 'createStoredInfoType', 'updateStoredInfoType', 'getStoredInfoType', 'listStoredInfoTypes', 'deleteStoredInfoType']; + const dlpServiceStubMethods = [ + 'inspectContent', + 'redactImage', + 'deidentifyContent', + 'reidentifyContent', + 'listInfoTypes', + 'createInspectTemplate', + 'updateInspectTemplate', + 'getInspectTemplate', + 'listInspectTemplates', + 'deleteInspectTemplate', + 'createDeidentifyTemplate', + 'updateDeidentifyTemplate', + 'getDeidentifyTemplate', + 'listDeidentifyTemplates', + 'deleteDeidentifyTemplate', + 'createJobTrigger', + 'updateJobTrigger', + 'getJobTrigger', + 'listJobTriggers', + 'deleteJobTrigger', + 'activateJobTrigger', + 'createDlpJob', + 'listDlpJobs', + 'getDlpJob', + 'deleteDlpJob', + 'cancelDlpJob', + 'createStoredInfoType', + 'updateStoredInfoType', + 'getStoredInfoType', + 'listStoredInfoTypes', + 'deleteStoredInfoType', + ]; for (const methodName of dlpServiceStubMethods) { const callPromise = this.dlpServiceStub.then( - stub => (...args: Array<{}>) => { - if (this._terminated) { - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error|null|undefined) => () => { + (stub) => + (...args: Array<{}>) => { + if (this._terminated) { + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { throw err; - }); + }, + ); - const descriptor = - this.descriptors.page[methodName] || - undefined; + const descriptor = this.descriptors.page[methodName] || undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -328,8 +409,14 @@ export class DlpServiceClient { * @returns {string} The DNS address for this service. */ static get servicePath() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'dlp.googleapis.com'; } @@ -341,8 +428,14 @@ export class DlpServiceClient { * @returns {string} The DNS address for this service. */ static get apiEndpoint() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'dlp.googleapis.com'; } @@ -373,9 +466,7 @@ export class DlpServiceClient { * @returns {string[]} List of default scopes. */ static get scopes() { - return [ - 'https://www.googleapis.com/auth/cloud-platform' - ]; + return ['https://www.googleapis.com/auth/cloud-platform']; } getProjectId(): Promise; @@ -384,8 +475,9 @@ export class DlpServiceClient { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId(callback?: Callback): - Promise|void { + getProjectId( + callback?: Callback, + ): Promise | void { if (callback) { this.auth.getProjectId(callback); return; @@ -396,2794 +488,3794 @@ export class DlpServiceClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Finds potentially sensitive info in content. - * This method has limits on input size, processing time, and output size. - * - * When no InfoTypes or CustomInfoTypes are specified in this request, the - * system will automatically choose what detectors to run. By default this may - * be all types, but may change over time as detectors are updated. - * - * For how to guides, see https://cloud.google.com/dlp/docs/inspecting-images - * and https://cloud.google.com/dlp/docs/inspecting-text, - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * The parent resource name, for example projects/my-project-id. - * @param {google.privacy.dlp.v2.InspectConfig} request.inspectConfig - * Configuration for the inspector. What specified here will override - * the template referenced by the inspect_template_name argument. - * @param {google.privacy.dlp.v2.ContentItem} request.item - * The item to inspect. - * @param {string} request.inspectTemplateName - * Template to use. Any configuration directly specified in - * inspect_config will override those set in the template. Singular fields - * that are set in this request will replace their corresponding fields in the - * template. Repeated fields are appended. Singular sub-messages and groups - * are recursively merged. - * @param {string} request.locationId - * The geographic location to process content inspection. Reserved for future - * extensions. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.privacy.dlp.v2.InspectContentResponse|InspectContentResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/dlp_service.inspect_content.js - * region_tag:dlp_v2_generated_DlpService_InspectContent_async - */ + /** + * Finds potentially sensitive info in content. + * This method has limits on input size, processing time, and output size. + * + * When no InfoTypes or CustomInfoTypes are specified in this request, the + * system will automatically choose what detectors to run. By default this may + * be all types, but may change over time as detectors are updated. + * + * For how to guides, see https://cloud.google.com/dlp/docs/inspecting-images + * and https://cloud.google.com/dlp/docs/inspecting-text, + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * The parent resource name, for example projects/my-project-id. + * @param {google.privacy.dlp.v2.InspectConfig} request.inspectConfig + * Configuration for the inspector. What specified here will override + * the template referenced by the inspect_template_name argument. + * @param {google.privacy.dlp.v2.ContentItem} request.item + * The item to inspect. + * @param {string} request.inspectTemplateName + * Template to use. Any configuration directly specified in + * inspect_config will override those set in the template. Singular fields + * that are set in this request will replace their corresponding fields in the + * template. Repeated fields are appended. Singular sub-messages and groups + * are recursively merged. + * @param {string} request.locationId + * The geographic location to process content inspection. Reserved for future + * extensions. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.privacy.dlp.v2.InspectContentResponse|InspectContentResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/dlp_service.inspect_content.js + * region_tag:dlp_v2_generated_DlpService_InspectContent_async + */ inspectContent( - request?: protos.google.privacy.dlp.v2.IInspectContentRequest, - options?: CallOptions): - Promise<[ - protos.google.privacy.dlp.v2.IInspectContentResponse, - protos.google.privacy.dlp.v2.IInspectContentRequest|undefined, {}|undefined - ]>; + request?: protos.google.privacy.dlp.v2.IInspectContentRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.privacy.dlp.v2.IInspectContentResponse, + protos.google.privacy.dlp.v2.IInspectContentRequest | undefined, + {} | undefined, + ] + >; inspectContent( - request: protos.google.privacy.dlp.v2.IInspectContentRequest, - options: CallOptions, - callback: Callback< - protos.google.privacy.dlp.v2.IInspectContentResponse, - protos.google.privacy.dlp.v2.IInspectContentRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.privacy.dlp.v2.IInspectContentRequest, + options: CallOptions, + callback: Callback< + protos.google.privacy.dlp.v2.IInspectContentResponse, + protos.google.privacy.dlp.v2.IInspectContentRequest | null | undefined, + {} | null | undefined + >, + ): void; inspectContent( - request: protos.google.privacy.dlp.v2.IInspectContentRequest, - callback: Callback< - protos.google.privacy.dlp.v2.IInspectContentResponse, - protos.google.privacy.dlp.v2.IInspectContentRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.privacy.dlp.v2.IInspectContentRequest, + callback: Callback< + protos.google.privacy.dlp.v2.IInspectContentResponse, + protos.google.privacy.dlp.v2.IInspectContentRequest | null | undefined, + {} | null | undefined + >, + ): void; inspectContent( - request?: protos.google.privacy.dlp.v2.IInspectContentRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.privacy.dlp.v2.IInspectContentRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.privacy.dlp.v2.IInspectContentResponse, - protos.google.privacy.dlp.v2.IInspectContentRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.privacy.dlp.v2.IInspectContentResponse, - protos.google.privacy.dlp.v2.IInspectContentRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.privacy.dlp.v2.IInspectContentResponse, - protos.google.privacy.dlp.v2.IInspectContentRequest|undefined, {}|undefined - ]>|void { + | protos.google.privacy.dlp.v2.IInspectContentRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.privacy.dlp.v2.IInspectContentResponse, + protos.google.privacy.dlp.v2.IInspectContentRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.privacy.dlp.v2.IInspectContentResponse, + protos.google.privacy.dlp.v2.IInspectContentRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - 'location_id': request.locationId?.toString() ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + location_id: request.locationId?.toString() ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('inspectContent request %j', request); - const wrappedCallback: Callback< - protos.google.privacy.dlp.v2.IInspectContentResponse, - protos.google.privacy.dlp.v2.IInspectContentRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.privacy.dlp.v2.IInspectContentResponse, + | protos.google.privacy.dlp.v2.IInspectContentRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('inspectContent response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.inspectContent(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.privacy.dlp.v2.IInspectContentResponse, - protos.google.privacy.dlp.v2.IInspectContentRequest|undefined, {}|undefined - ]) => { - this._log.info('inspectContent response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .inspectContent(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.privacy.dlp.v2.IInspectContentResponse, + protos.google.privacy.dlp.v2.IInspectContentRequest | undefined, + {} | undefined, + ]) => { + this._log.info('inspectContent response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Redacts potentially sensitive info from an image. - * This method has limits on input size, processing time, and output size. - * See https://cloud.google.com/dlp/docs/redacting-sensitive-data-images to - * learn more. - * - * When no InfoTypes or CustomInfoTypes are specified in this request, the - * system will automatically choose what detectors to run. By default this may - * be all types, but may change over time as detectors are updated. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * The parent resource name, for example projects/my-project-id. - * @param {string} request.locationId - * The geographic location to process the request. Reserved for future - * extensions. - * @param {google.privacy.dlp.v2.InspectConfig} request.inspectConfig - * Configuration for the inspector. - * @param {number[]} request.imageRedactionConfigs - * The configuration for specifying what content to redact from images. - * @param {boolean} request.includeFindings - * Whether the response should include findings along with the redacted - * image. - * @param {google.privacy.dlp.v2.ByteContentItem} request.byteItem - * The content must be PNG, JPEG, SVG or BMP. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.privacy.dlp.v2.RedactImageResponse|RedactImageResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/dlp_service.redact_image.js - * region_tag:dlp_v2_generated_DlpService_RedactImage_async - */ + /** + * Redacts potentially sensitive info from an image. + * This method has limits on input size, processing time, and output size. + * See https://cloud.google.com/dlp/docs/redacting-sensitive-data-images to + * learn more. + * + * When no InfoTypes or CustomInfoTypes are specified in this request, the + * system will automatically choose what detectors to run. By default this may + * be all types, but may change over time as detectors are updated. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * The parent resource name, for example projects/my-project-id. + * @param {string} request.locationId + * The geographic location to process the request. Reserved for future + * extensions. + * @param {google.privacy.dlp.v2.InspectConfig} request.inspectConfig + * Configuration for the inspector. + * @param {number[]} request.imageRedactionConfigs + * The configuration for specifying what content to redact from images. + * @param {boolean} request.includeFindings + * Whether the response should include findings along with the redacted + * image. + * @param {google.privacy.dlp.v2.ByteContentItem} request.byteItem + * The content must be PNG, JPEG, SVG or BMP. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.privacy.dlp.v2.RedactImageResponse|RedactImageResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/dlp_service.redact_image.js + * region_tag:dlp_v2_generated_DlpService_RedactImage_async + */ redactImage( - request?: protos.google.privacy.dlp.v2.IRedactImageRequest, - options?: CallOptions): - Promise<[ - protos.google.privacy.dlp.v2.IRedactImageResponse, - protos.google.privacy.dlp.v2.IRedactImageRequest|undefined, {}|undefined - ]>; + request?: protos.google.privacy.dlp.v2.IRedactImageRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.privacy.dlp.v2.IRedactImageResponse, + protos.google.privacy.dlp.v2.IRedactImageRequest | undefined, + {} | undefined, + ] + >; redactImage( - request: protos.google.privacy.dlp.v2.IRedactImageRequest, - options: CallOptions, - callback: Callback< - protos.google.privacy.dlp.v2.IRedactImageResponse, - protos.google.privacy.dlp.v2.IRedactImageRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.privacy.dlp.v2.IRedactImageRequest, + options: CallOptions, + callback: Callback< + protos.google.privacy.dlp.v2.IRedactImageResponse, + protos.google.privacy.dlp.v2.IRedactImageRequest | null | undefined, + {} | null | undefined + >, + ): void; redactImage( - request: protos.google.privacy.dlp.v2.IRedactImageRequest, - callback: Callback< - protos.google.privacy.dlp.v2.IRedactImageResponse, - protos.google.privacy.dlp.v2.IRedactImageRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.privacy.dlp.v2.IRedactImageRequest, + callback: Callback< + protos.google.privacy.dlp.v2.IRedactImageResponse, + protos.google.privacy.dlp.v2.IRedactImageRequest | null | undefined, + {} | null | undefined + >, + ): void; redactImage( - request?: protos.google.privacy.dlp.v2.IRedactImageRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.privacy.dlp.v2.IRedactImageResponse, - protos.google.privacy.dlp.v2.IRedactImageRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.privacy.dlp.v2.IRedactImageRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.privacy.dlp.v2.IRedactImageResponse, - protos.google.privacy.dlp.v2.IRedactImageRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.privacy.dlp.v2.IRedactImageResponse, - protos.google.privacy.dlp.v2.IRedactImageRequest|undefined, {}|undefined - ]>|void { + protos.google.privacy.dlp.v2.IRedactImageRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.privacy.dlp.v2.IRedactImageResponse, + protos.google.privacy.dlp.v2.IRedactImageRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.privacy.dlp.v2.IRedactImageResponse, + protos.google.privacy.dlp.v2.IRedactImageRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - 'location_id': request.locationId?.toString() ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + location_id: request.locationId?.toString() ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('redactImage request %j', request); - const wrappedCallback: Callback< - protos.google.privacy.dlp.v2.IRedactImageResponse, - protos.google.privacy.dlp.v2.IRedactImageRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.privacy.dlp.v2.IRedactImageResponse, + protos.google.privacy.dlp.v2.IRedactImageRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('redactImage response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.redactImage(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.privacy.dlp.v2.IRedactImageResponse, - protos.google.privacy.dlp.v2.IRedactImageRequest|undefined, {}|undefined - ]) => { - this._log.info('redactImage response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .redactImage(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.privacy.dlp.v2.IRedactImageResponse, + protos.google.privacy.dlp.v2.IRedactImageRequest | undefined, + {} | undefined, + ]) => { + this._log.info('redactImage response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * De-identifies potentially sensitive info from a ContentItem. - * This method has limits on input size and output size. - * See https://cloud.google.com/dlp/docs/deidentify-sensitive-data to - * learn more. - * - * When no InfoTypes or CustomInfoTypes are specified in this request, the - * system will automatically choose what detectors to run. By default this may - * be all types, but may change over time as detectors are updated. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * The parent resource name, for example projects/my-project-id. - * @param {google.privacy.dlp.v2.DeidentifyConfig} request.deidentifyConfig - * Configuration for the de-identification of the content item. - * Items specified here will override the template referenced by the - * deidentify_template_name argument. - * @param {google.privacy.dlp.v2.InspectConfig} request.inspectConfig - * Configuration for the inspector. - * Items specified here will override the template referenced by the - * inspect_template_name argument. - * @param {google.privacy.dlp.v2.ContentItem} request.item - * The item to de-identify. Will be treated as text. - * @param {string} request.inspectTemplateName - * Template to use. Any configuration directly specified in - * inspect_config will override those set in the template. Singular fields - * that are set in this request will replace their corresponding fields in the - * template. Repeated fields are appended. Singular sub-messages and groups - * are recursively merged. - * @param {string} request.deidentifyTemplateName - * Template to use. Any configuration directly specified in - * deidentify_config will override those set in the template. Singular fields - * that are set in this request will replace their corresponding fields in the - * template. Repeated fields are appended. Singular sub-messages and groups - * are recursively merged. - * @param {string} request.locationId - * The geographic location to process de-identification. Reserved for future - * extensions. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.privacy.dlp.v2.DeidentifyContentResponse|DeidentifyContentResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/dlp_service.deidentify_content.js - * region_tag:dlp_v2_generated_DlpService_DeidentifyContent_async - */ + /** + * De-identifies potentially sensitive info from a ContentItem. + * This method has limits on input size and output size. + * See https://cloud.google.com/dlp/docs/deidentify-sensitive-data to + * learn more. + * + * When no InfoTypes or CustomInfoTypes are specified in this request, the + * system will automatically choose what detectors to run. By default this may + * be all types, but may change over time as detectors are updated. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * The parent resource name, for example projects/my-project-id. + * @param {google.privacy.dlp.v2.DeidentifyConfig} request.deidentifyConfig + * Configuration for the de-identification of the content item. + * Items specified here will override the template referenced by the + * deidentify_template_name argument. + * @param {google.privacy.dlp.v2.InspectConfig} request.inspectConfig + * Configuration for the inspector. + * Items specified here will override the template referenced by the + * inspect_template_name argument. + * @param {google.privacy.dlp.v2.ContentItem} request.item + * The item to de-identify. Will be treated as text. + * @param {string} request.inspectTemplateName + * Template to use. Any configuration directly specified in + * inspect_config will override those set in the template. Singular fields + * that are set in this request will replace their corresponding fields in the + * template. Repeated fields are appended. Singular sub-messages and groups + * are recursively merged. + * @param {string} request.deidentifyTemplateName + * Template to use. Any configuration directly specified in + * deidentify_config will override those set in the template. Singular fields + * that are set in this request will replace their corresponding fields in the + * template. Repeated fields are appended. Singular sub-messages and groups + * are recursively merged. + * @param {string} request.locationId + * The geographic location to process de-identification. Reserved for future + * extensions. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.privacy.dlp.v2.DeidentifyContentResponse|DeidentifyContentResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/dlp_service.deidentify_content.js + * region_tag:dlp_v2_generated_DlpService_DeidentifyContent_async + */ deidentifyContent( - request?: protos.google.privacy.dlp.v2.IDeidentifyContentRequest, - options?: CallOptions): - Promise<[ - protos.google.privacy.dlp.v2.IDeidentifyContentResponse, - protos.google.privacy.dlp.v2.IDeidentifyContentRequest|undefined, {}|undefined - ]>; + request?: protos.google.privacy.dlp.v2.IDeidentifyContentRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.privacy.dlp.v2.IDeidentifyContentResponse, + protos.google.privacy.dlp.v2.IDeidentifyContentRequest | undefined, + {} | undefined, + ] + >; deidentifyContent( - request: protos.google.privacy.dlp.v2.IDeidentifyContentRequest, - options: CallOptions, - callback: Callback< - protos.google.privacy.dlp.v2.IDeidentifyContentResponse, - protos.google.privacy.dlp.v2.IDeidentifyContentRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.privacy.dlp.v2.IDeidentifyContentRequest, + options: CallOptions, + callback: Callback< + protos.google.privacy.dlp.v2.IDeidentifyContentResponse, + protos.google.privacy.dlp.v2.IDeidentifyContentRequest | null | undefined, + {} | null | undefined + >, + ): void; deidentifyContent( - request: protos.google.privacy.dlp.v2.IDeidentifyContentRequest, - callback: Callback< - protos.google.privacy.dlp.v2.IDeidentifyContentResponse, - protos.google.privacy.dlp.v2.IDeidentifyContentRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.privacy.dlp.v2.IDeidentifyContentRequest, + callback: Callback< + protos.google.privacy.dlp.v2.IDeidentifyContentResponse, + protos.google.privacy.dlp.v2.IDeidentifyContentRequest | null | undefined, + {} | null | undefined + >, + ): void; deidentifyContent( - request?: protos.google.privacy.dlp.v2.IDeidentifyContentRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.privacy.dlp.v2.IDeidentifyContentRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.privacy.dlp.v2.IDeidentifyContentResponse, - protos.google.privacy.dlp.v2.IDeidentifyContentRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.privacy.dlp.v2.IDeidentifyContentResponse, - protos.google.privacy.dlp.v2.IDeidentifyContentRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.privacy.dlp.v2.IDeidentifyContentResponse, - protos.google.privacy.dlp.v2.IDeidentifyContentRequest|undefined, {}|undefined - ]>|void { + | protos.google.privacy.dlp.v2.IDeidentifyContentRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.privacy.dlp.v2.IDeidentifyContentResponse, + protos.google.privacy.dlp.v2.IDeidentifyContentRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.privacy.dlp.v2.IDeidentifyContentResponse, + protos.google.privacy.dlp.v2.IDeidentifyContentRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - 'location_id': request.locationId?.toString() ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + location_id: request.locationId?.toString() ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('deidentifyContent request %j', request); - const wrappedCallback: Callback< - protos.google.privacy.dlp.v2.IDeidentifyContentResponse, - protos.google.privacy.dlp.v2.IDeidentifyContentRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.privacy.dlp.v2.IDeidentifyContentResponse, + | protos.google.privacy.dlp.v2.IDeidentifyContentRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deidentifyContent response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.deidentifyContent(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.privacy.dlp.v2.IDeidentifyContentResponse, - protos.google.privacy.dlp.v2.IDeidentifyContentRequest|undefined, {}|undefined - ]) => { - this._log.info('deidentifyContent response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deidentifyContent(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.privacy.dlp.v2.IDeidentifyContentResponse, + protos.google.privacy.dlp.v2.IDeidentifyContentRequest | undefined, + {} | undefined, + ]) => { + this._log.info('deidentifyContent response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Re-identifies content that has been de-identified. - * See - * https://cloud.google.com/dlp/docs/pseudonymization#re-identification_in_free_text_code_example - * to learn more. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent resource name. - * @param {google.privacy.dlp.v2.DeidentifyConfig} request.reidentifyConfig - * Configuration for the re-identification of the content item. - * This field shares the same proto message type that is used for - * de-identification, however its usage here is for the reversal of the - * previous de-identification. Re-identification is performed by examining - * the transformations used to de-identify the items and executing the - * reverse. This requires that only reversible transformations - * be provided here. The reversible transformations are: - * - * - `CryptoDeterministicConfig` - * - `CryptoReplaceFfxFpeConfig` - * @param {google.privacy.dlp.v2.InspectConfig} request.inspectConfig - * Configuration for the inspector. - * @param {google.privacy.dlp.v2.ContentItem} request.item - * The item to re-identify. Will be treated as text. - * @param {string} request.inspectTemplateName - * Template to use. Any configuration directly specified in - * `inspect_config` will override those set in the template. Singular fields - * that are set in this request will replace their corresponding fields in the - * template. Repeated fields are appended. Singular sub-messages and groups - * are recursively merged. - * @param {string} request.reidentifyTemplateName - * Template to use. References an instance of `DeidentifyTemplate`. - * Any configuration directly specified in `reidentify_config` or - * `inspect_config` will override those set in the template. Singular fields - * that are set in this request will replace their corresponding fields in the - * template. Repeated fields are appended. Singular sub-messages and groups - * are recursively merged. - * @param {string} request.locationId - * The geographic location to process content reidentification. Reserved for - * future extensions. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.privacy.dlp.v2.ReidentifyContentResponse|ReidentifyContentResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/dlp_service.reidentify_content.js - * region_tag:dlp_v2_generated_DlpService_ReidentifyContent_async - */ + /** + * Re-identifies content that has been de-identified. + * See + * https://cloud.google.com/dlp/docs/pseudonymization#re-identification_in_free_text_code_example + * to learn more. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource name. + * @param {google.privacy.dlp.v2.DeidentifyConfig} request.reidentifyConfig + * Configuration for the re-identification of the content item. + * This field shares the same proto message type that is used for + * de-identification, however its usage here is for the reversal of the + * previous de-identification. Re-identification is performed by examining + * the transformations used to de-identify the items and executing the + * reverse. This requires that only reversible transformations + * be provided here. The reversible transformations are: + * + * - `CryptoDeterministicConfig` + * - `CryptoReplaceFfxFpeConfig` + * @param {google.privacy.dlp.v2.InspectConfig} request.inspectConfig + * Configuration for the inspector. + * @param {google.privacy.dlp.v2.ContentItem} request.item + * The item to re-identify. Will be treated as text. + * @param {string} request.inspectTemplateName + * Template to use. Any configuration directly specified in + * `inspect_config` will override those set in the template. Singular fields + * that are set in this request will replace their corresponding fields in the + * template. Repeated fields are appended. Singular sub-messages and groups + * are recursively merged. + * @param {string} request.reidentifyTemplateName + * Template to use. References an instance of `DeidentifyTemplate`. + * Any configuration directly specified in `reidentify_config` or + * `inspect_config` will override those set in the template. Singular fields + * that are set in this request will replace their corresponding fields in the + * template. Repeated fields are appended. Singular sub-messages and groups + * are recursively merged. + * @param {string} request.locationId + * The geographic location to process content reidentification. Reserved for + * future extensions. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.privacy.dlp.v2.ReidentifyContentResponse|ReidentifyContentResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/dlp_service.reidentify_content.js + * region_tag:dlp_v2_generated_DlpService_ReidentifyContent_async + */ reidentifyContent( - request?: protos.google.privacy.dlp.v2.IReidentifyContentRequest, - options?: CallOptions): - Promise<[ - protos.google.privacy.dlp.v2.IReidentifyContentResponse, - protos.google.privacy.dlp.v2.IReidentifyContentRequest|undefined, {}|undefined - ]>; + request?: protos.google.privacy.dlp.v2.IReidentifyContentRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.privacy.dlp.v2.IReidentifyContentResponse, + protos.google.privacy.dlp.v2.IReidentifyContentRequest | undefined, + {} | undefined, + ] + >; reidentifyContent( - request: protos.google.privacy.dlp.v2.IReidentifyContentRequest, - options: CallOptions, - callback: Callback< - protos.google.privacy.dlp.v2.IReidentifyContentResponse, - protos.google.privacy.dlp.v2.IReidentifyContentRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.privacy.dlp.v2.IReidentifyContentRequest, + options: CallOptions, + callback: Callback< + protos.google.privacy.dlp.v2.IReidentifyContentResponse, + protos.google.privacy.dlp.v2.IReidentifyContentRequest | null | undefined, + {} | null | undefined + >, + ): void; reidentifyContent( - request: protos.google.privacy.dlp.v2.IReidentifyContentRequest, - callback: Callback< - protos.google.privacy.dlp.v2.IReidentifyContentResponse, - protos.google.privacy.dlp.v2.IReidentifyContentRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.privacy.dlp.v2.IReidentifyContentRequest, + callback: Callback< + protos.google.privacy.dlp.v2.IReidentifyContentResponse, + protos.google.privacy.dlp.v2.IReidentifyContentRequest | null | undefined, + {} | null | undefined + >, + ): void; reidentifyContent( - request?: protos.google.privacy.dlp.v2.IReidentifyContentRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.privacy.dlp.v2.IReidentifyContentResponse, - protos.google.privacy.dlp.v2.IReidentifyContentRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.privacy.dlp.v2.IReidentifyContentRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.privacy.dlp.v2.IReidentifyContentResponse, - protos.google.privacy.dlp.v2.IReidentifyContentRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.privacy.dlp.v2.IReidentifyContentResponse, - protos.google.privacy.dlp.v2.IReidentifyContentRequest|undefined, {}|undefined - ]>|void { + | protos.google.privacy.dlp.v2.IReidentifyContentRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.privacy.dlp.v2.IReidentifyContentResponse, + protos.google.privacy.dlp.v2.IReidentifyContentRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.privacy.dlp.v2.IReidentifyContentResponse, + protos.google.privacy.dlp.v2.IReidentifyContentRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - 'location_id': request.locationId?.toString() ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + location_id: request.locationId?.toString() ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('reidentifyContent request %j', request); - const wrappedCallback: Callback< - protos.google.privacy.dlp.v2.IReidentifyContentResponse, - protos.google.privacy.dlp.v2.IReidentifyContentRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.privacy.dlp.v2.IReidentifyContentResponse, + | protos.google.privacy.dlp.v2.IReidentifyContentRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('reidentifyContent response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.reidentifyContent(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.privacy.dlp.v2.IReidentifyContentResponse, - protos.google.privacy.dlp.v2.IReidentifyContentRequest|undefined, {}|undefined - ]) => { - this._log.info('reidentifyContent response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .reidentifyContent(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.privacy.dlp.v2.IReidentifyContentResponse, + protos.google.privacy.dlp.v2.IReidentifyContentRequest | undefined, + {} | undefined, + ]) => { + this._log.info('reidentifyContent response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Returns a list of the sensitive information types that the DLP API - * supports. See https://cloud.google.com/dlp/docs/infotypes-reference to - * learn more. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.languageCode - * BCP-47 language code for localized infoType friendly - * names. If omitted, or if localized strings are not available, - * en-US strings will be returned. - * @param {string} request.filter - * filter to only return infoTypes supported by certain parts of the - * API. Defaults to supported_by=INSPECT. - * @param {string} request.locationId - * The geographic location to list info types. Reserved for future - * extensions. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.privacy.dlp.v2.ListInfoTypesResponse|ListInfoTypesResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/dlp_service.list_info_types.js - * region_tag:dlp_v2_generated_DlpService_ListInfoTypes_async - */ + /** + * Returns a list of the sensitive information types that the DLP API + * supports. See https://cloud.google.com/dlp/docs/infotypes-reference to + * learn more. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.languageCode + * BCP-47 language code for localized infoType friendly + * names. If omitted, or if localized strings are not available, + * en-US strings will be returned. + * @param {string} request.filter + * filter to only return infoTypes supported by certain parts of the + * API. Defaults to supported_by=INSPECT. + * @param {string} request.locationId + * The geographic location to list info types. Reserved for future + * extensions. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.privacy.dlp.v2.ListInfoTypesResponse|ListInfoTypesResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/dlp_service.list_info_types.js + * region_tag:dlp_v2_generated_DlpService_ListInfoTypes_async + */ listInfoTypes( - request?: protos.google.privacy.dlp.v2.IListInfoTypesRequest, - options?: CallOptions): - Promise<[ - protos.google.privacy.dlp.v2.IListInfoTypesResponse, - protos.google.privacy.dlp.v2.IListInfoTypesRequest|undefined, {}|undefined - ]>; + request?: protos.google.privacy.dlp.v2.IListInfoTypesRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.privacy.dlp.v2.IListInfoTypesResponse, + protos.google.privacy.dlp.v2.IListInfoTypesRequest | undefined, + {} | undefined, + ] + >; listInfoTypes( - request: protos.google.privacy.dlp.v2.IListInfoTypesRequest, - options: CallOptions, - callback: Callback< - protos.google.privacy.dlp.v2.IListInfoTypesResponse, - protos.google.privacy.dlp.v2.IListInfoTypesRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.privacy.dlp.v2.IListInfoTypesRequest, + options: CallOptions, + callback: Callback< + protos.google.privacy.dlp.v2.IListInfoTypesResponse, + protos.google.privacy.dlp.v2.IListInfoTypesRequest | null | undefined, + {} | null | undefined + >, + ): void; listInfoTypes( - request: protos.google.privacy.dlp.v2.IListInfoTypesRequest, - callback: Callback< - protos.google.privacy.dlp.v2.IListInfoTypesResponse, - protos.google.privacy.dlp.v2.IListInfoTypesRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.privacy.dlp.v2.IListInfoTypesRequest, + callback: Callback< + protos.google.privacy.dlp.v2.IListInfoTypesResponse, + protos.google.privacy.dlp.v2.IListInfoTypesRequest | null | undefined, + {} | null | undefined + >, + ): void; listInfoTypes( - request?: protos.google.privacy.dlp.v2.IListInfoTypesRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.privacy.dlp.v2.IListInfoTypesRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.privacy.dlp.v2.IListInfoTypesResponse, - protos.google.privacy.dlp.v2.IListInfoTypesRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.privacy.dlp.v2.IListInfoTypesResponse, - protos.google.privacy.dlp.v2.IListInfoTypesRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.privacy.dlp.v2.IListInfoTypesResponse, - protos.google.privacy.dlp.v2.IListInfoTypesRequest|undefined, {}|undefined - ]>|void { + protos.google.privacy.dlp.v2.IListInfoTypesRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.privacy.dlp.v2.IListInfoTypesResponse, + protos.google.privacy.dlp.v2.IListInfoTypesRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.privacy.dlp.v2.IListInfoTypesResponse, + protos.google.privacy.dlp.v2.IListInfoTypesRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'location_id': request.locationId?.toString() ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + location_id: request.locationId?.toString() ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('listInfoTypes request %j', request); - const wrappedCallback: Callback< - protos.google.privacy.dlp.v2.IListInfoTypesResponse, - protos.google.privacy.dlp.v2.IListInfoTypesRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.privacy.dlp.v2.IListInfoTypesResponse, + protos.google.privacy.dlp.v2.IListInfoTypesRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('listInfoTypes response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.listInfoTypes(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.privacy.dlp.v2.IListInfoTypesResponse, - protos.google.privacy.dlp.v2.IListInfoTypesRequest|undefined, {}|undefined - ]) => { - this._log.info('listInfoTypes response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .listInfoTypes(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.privacy.dlp.v2.IListInfoTypesResponse, + protos.google.privacy.dlp.v2.IListInfoTypesRequest | undefined, + {} | undefined, + ]) => { + this._log.info('listInfoTypes response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Creates an InspectTemplate for re-using frequently used configuration - * for inspecting content, images, and storage. - * See https://cloud.google.com/dlp/docs/creating-templates to learn more. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent resource name, for example projects/my-project-id or - * organizations/my-org-id. - * @param {google.privacy.dlp.v2.InspectTemplate} request.inspectTemplate - * Required. The InspectTemplate to create. - * @param {string} request.templateId - * The template id can contain uppercase and lowercase letters, - * numbers, and hyphens; that is, it must match the regular - * expression: `[a-zA-Z\\d-_]+`. The maximum length is 100 - * characters. Can be empty to allow the system to generate one. - * @param {string} request.locationId - * The geographic location to store the inspection template. Reserved for - * future extensions. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.privacy.dlp.v2.InspectTemplate|InspectTemplate}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/dlp_service.create_inspect_template.js - * region_tag:dlp_v2_generated_DlpService_CreateInspectTemplate_async - */ + /** + * Creates an InspectTemplate for re-using frequently used configuration + * for inspecting content, images, and storage. + * See https://cloud.google.com/dlp/docs/creating-templates to learn more. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource name, for example projects/my-project-id or + * organizations/my-org-id. + * @param {google.privacy.dlp.v2.InspectTemplate} request.inspectTemplate + * Required. The InspectTemplate to create. + * @param {string} request.templateId + * The template id can contain uppercase and lowercase letters, + * numbers, and hyphens; that is, it must match the regular + * expression: `[a-zA-Z\\d-_]+`. The maximum length is 100 + * characters. Can be empty to allow the system to generate one. + * @param {string} request.locationId + * The geographic location to store the inspection template. Reserved for + * future extensions. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.privacy.dlp.v2.InspectTemplate|InspectTemplate}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/dlp_service.create_inspect_template.js + * region_tag:dlp_v2_generated_DlpService_CreateInspectTemplate_async + */ createInspectTemplate( - request?: protos.google.privacy.dlp.v2.ICreateInspectTemplateRequest, - options?: CallOptions): - Promise<[ - protos.google.privacy.dlp.v2.IInspectTemplate, - protos.google.privacy.dlp.v2.ICreateInspectTemplateRequest|undefined, {}|undefined - ]>; + request?: protos.google.privacy.dlp.v2.ICreateInspectTemplateRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.privacy.dlp.v2.IInspectTemplate, + protos.google.privacy.dlp.v2.ICreateInspectTemplateRequest | undefined, + {} | undefined, + ] + >; createInspectTemplate( - request: protos.google.privacy.dlp.v2.ICreateInspectTemplateRequest, - options: CallOptions, - callback: Callback< - protos.google.privacy.dlp.v2.IInspectTemplate, - protos.google.privacy.dlp.v2.ICreateInspectTemplateRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.privacy.dlp.v2.ICreateInspectTemplateRequest, + options: CallOptions, + callback: Callback< + protos.google.privacy.dlp.v2.IInspectTemplate, + | protos.google.privacy.dlp.v2.ICreateInspectTemplateRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createInspectTemplate( - request: protos.google.privacy.dlp.v2.ICreateInspectTemplateRequest, - callback: Callback< - protos.google.privacy.dlp.v2.IInspectTemplate, - protos.google.privacy.dlp.v2.ICreateInspectTemplateRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.privacy.dlp.v2.ICreateInspectTemplateRequest, + callback: Callback< + protos.google.privacy.dlp.v2.IInspectTemplate, + | protos.google.privacy.dlp.v2.ICreateInspectTemplateRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createInspectTemplate( - request?: protos.google.privacy.dlp.v2.ICreateInspectTemplateRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.privacy.dlp.v2.IInspectTemplate, - protos.google.privacy.dlp.v2.ICreateInspectTemplateRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.privacy.dlp.v2.ICreateInspectTemplateRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.privacy.dlp.v2.IInspectTemplate, - protos.google.privacy.dlp.v2.ICreateInspectTemplateRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.privacy.dlp.v2.IInspectTemplate, - protos.google.privacy.dlp.v2.ICreateInspectTemplateRequest|undefined, {}|undefined - ]>|void { + | protos.google.privacy.dlp.v2.ICreateInspectTemplateRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.privacy.dlp.v2.IInspectTemplate, + | protos.google.privacy.dlp.v2.ICreateInspectTemplateRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.privacy.dlp.v2.IInspectTemplate, + protos.google.privacy.dlp.v2.ICreateInspectTemplateRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - 'location_id': request.locationId?.toString() ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + location_id: request.locationId?.toString() ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('createInspectTemplate request %j', request); - const wrappedCallback: Callback< - protos.google.privacy.dlp.v2.IInspectTemplate, - protos.google.privacy.dlp.v2.ICreateInspectTemplateRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.privacy.dlp.v2.IInspectTemplate, + | protos.google.privacy.dlp.v2.ICreateInspectTemplateRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createInspectTemplate response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.createInspectTemplate(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.privacy.dlp.v2.IInspectTemplate, - protos.google.privacy.dlp.v2.ICreateInspectTemplateRequest|undefined, {}|undefined - ]) => { - this._log.info('createInspectTemplate response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createInspectTemplate(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.privacy.dlp.v2.IInspectTemplate, + ( + | protos.google.privacy.dlp.v2.ICreateInspectTemplateRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('createInspectTemplate response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Updates the InspectTemplate. - * See https://cloud.google.com/dlp/docs/creating-templates to learn more. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. Resource name of organization and inspectTemplate to be updated, for - * example `organizations/433245324/inspectTemplates/432452342` or - * projects/project-id/inspectTemplates/432452342. - * @param {google.privacy.dlp.v2.InspectTemplate} request.inspectTemplate - * New InspectTemplate value. - * @param {google.protobuf.FieldMask} request.updateMask - * Mask to control which fields get updated. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.privacy.dlp.v2.InspectTemplate|InspectTemplate}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/dlp_service.update_inspect_template.js - * region_tag:dlp_v2_generated_DlpService_UpdateInspectTemplate_async - */ + /** + * Updates the InspectTemplate. + * See https://cloud.google.com/dlp/docs/creating-templates to learn more. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Resource name of organization and inspectTemplate to be updated, for + * example `organizations/433245324/inspectTemplates/432452342` or + * projects/project-id/inspectTemplates/432452342. + * @param {google.privacy.dlp.v2.InspectTemplate} request.inspectTemplate + * New InspectTemplate value. + * @param {google.protobuf.FieldMask} request.updateMask + * Mask to control which fields get updated. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.privacy.dlp.v2.InspectTemplate|InspectTemplate}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/dlp_service.update_inspect_template.js + * region_tag:dlp_v2_generated_DlpService_UpdateInspectTemplate_async + */ updateInspectTemplate( - request?: protos.google.privacy.dlp.v2.IUpdateInspectTemplateRequest, - options?: CallOptions): - Promise<[ - protos.google.privacy.dlp.v2.IInspectTemplate, - protos.google.privacy.dlp.v2.IUpdateInspectTemplateRequest|undefined, {}|undefined - ]>; + request?: protos.google.privacy.dlp.v2.IUpdateInspectTemplateRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.privacy.dlp.v2.IInspectTemplate, + protos.google.privacy.dlp.v2.IUpdateInspectTemplateRequest | undefined, + {} | undefined, + ] + >; updateInspectTemplate( - request: protos.google.privacy.dlp.v2.IUpdateInspectTemplateRequest, - options: CallOptions, - callback: Callback< - protos.google.privacy.dlp.v2.IInspectTemplate, - protos.google.privacy.dlp.v2.IUpdateInspectTemplateRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.privacy.dlp.v2.IUpdateInspectTemplateRequest, + options: CallOptions, + callback: Callback< + protos.google.privacy.dlp.v2.IInspectTemplate, + | protos.google.privacy.dlp.v2.IUpdateInspectTemplateRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateInspectTemplate( - request: protos.google.privacy.dlp.v2.IUpdateInspectTemplateRequest, - callback: Callback< - protos.google.privacy.dlp.v2.IInspectTemplate, - protos.google.privacy.dlp.v2.IUpdateInspectTemplateRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.privacy.dlp.v2.IUpdateInspectTemplateRequest, + callback: Callback< + protos.google.privacy.dlp.v2.IInspectTemplate, + | protos.google.privacy.dlp.v2.IUpdateInspectTemplateRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateInspectTemplate( - request?: protos.google.privacy.dlp.v2.IUpdateInspectTemplateRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.privacy.dlp.v2.IUpdateInspectTemplateRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.privacy.dlp.v2.IInspectTemplate, - protos.google.privacy.dlp.v2.IUpdateInspectTemplateRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.privacy.dlp.v2.IInspectTemplate, - protos.google.privacy.dlp.v2.IUpdateInspectTemplateRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.privacy.dlp.v2.IInspectTemplate, - protos.google.privacy.dlp.v2.IUpdateInspectTemplateRequest|undefined, {}|undefined - ]>|void { + | protos.google.privacy.dlp.v2.IUpdateInspectTemplateRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.privacy.dlp.v2.IInspectTemplate, + | protos.google.privacy.dlp.v2.IUpdateInspectTemplateRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.privacy.dlp.v2.IInspectTemplate, + protos.google.privacy.dlp.v2.IUpdateInspectTemplateRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateInspectTemplate request %j', request); - const wrappedCallback: Callback< - protos.google.privacy.dlp.v2.IInspectTemplate, - protos.google.privacy.dlp.v2.IUpdateInspectTemplateRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.privacy.dlp.v2.IInspectTemplate, + | protos.google.privacy.dlp.v2.IUpdateInspectTemplateRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateInspectTemplate response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.updateInspectTemplate(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.privacy.dlp.v2.IInspectTemplate, - protos.google.privacy.dlp.v2.IUpdateInspectTemplateRequest|undefined, {}|undefined - ]) => { - this._log.info('updateInspectTemplate response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateInspectTemplate(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.privacy.dlp.v2.IInspectTemplate, + ( + | protos.google.privacy.dlp.v2.IUpdateInspectTemplateRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('updateInspectTemplate response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Gets an InspectTemplate. - * See https://cloud.google.com/dlp/docs/creating-templates to learn more. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. Resource name of the organization and inspectTemplate to be read, for - * example `organizations/433245324/inspectTemplates/432452342` or - * projects/project-id/inspectTemplates/432452342. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.privacy.dlp.v2.InspectTemplate|InspectTemplate}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/dlp_service.get_inspect_template.js - * region_tag:dlp_v2_generated_DlpService_GetInspectTemplate_async - */ + /** + * Gets an InspectTemplate. + * See https://cloud.google.com/dlp/docs/creating-templates to learn more. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Resource name of the organization and inspectTemplate to be read, for + * example `organizations/433245324/inspectTemplates/432452342` or + * projects/project-id/inspectTemplates/432452342. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.privacy.dlp.v2.InspectTemplate|InspectTemplate}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/dlp_service.get_inspect_template.js + * region_tag:dlp_v2_generated_DlpService_GetInspectTemplate_async + */ getInspectTemplate( - request?: protos.google.privacy.dlp.v2.IGetInspectTemplateRequest, - options?: CallOptions): - Promise<[ - protos.google.privacy.dlp.v2.IInspectTemplate, - protos.google.privacy.dlp.v2.IGetInspectTemplateRequest|undefined, {}|undefined - ]>; + request?: protos.google.privacy.dlp.v2.IGetInspectTemplateRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.privacy.dlp.v2.IInspectTemplate, + protos.google.privacy.dlp.v2.IGetInspectTemplateRequest | undefined, + {} | undefined, + ] + >; getInspectTemplate( - request: protos.google.privacy.dlp.v2.IGetInspectTemplateRequest, - options: CallOptions, - callback: Callback< - protos.google.privacy.dlp.v2.IInspectTemplate, - protos.google.privacy.dlp.v2.IGetInspectTemplateRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.privacy.dlp.v2.IGetInspectTemplateRequest, + options: CallOptions, + callback: Callback< + protos.google.privacy.dlp.v2.IInspectTemplate, + | protos.google.privacy.dlp.v2.IGetInspectTemplateRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getInspectTemplate( - request: protos.google.privacy.dlp.v2.IGetInspectTemplateRequest, - callback: Callback< - protos.google.privacy.dlp.v2.IInspectTemplate, - protos.google.privacy.dlp.v2.IGetInspectTemplateRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.privacy.dlp.v2.IGetInspectTemplateRequest, + callback: Callback< + protos.google.privacy.dlp.v2.IInspectTemplate, + | protos.google.privacy.dlp.v2.IGetInspectTemplateRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getInspectTemplate( - request?: protos.google.privacy.dlp.v2.IGetInspectTemplateRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.privacy.dlp.v2.IInspectTemplate, - protos.google.privacy.dlp.v2.IGetInspectTemplateRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.privacy.dlp.v2.IGetInspectTemplateRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.privacy.dlp.v2.IInspectTemplate, - protos.google.privacy.dlp.v2.IGetInspectTemplateRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.privacy.dlp.v2.IInspectTemplate, - protos.google.privacy.dlp.v2.IGetInspectTemplateRequest|undefined, {}|undefined - ]>|void { + | protos.google.privacy.dlp.v2.IGetInspectTemplateRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.privacy.dlp.v2.IInspectTemplate, + | protos.google.privacy.dlp.v2.IGetInspectTemplateRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.privacy.dlp.v2.IInspectTemplate, + protos.google.privacy.dlp.v2.IGetInspectTemplateRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getInspectTemplate request %j', request); - const wrappedCallback: Callback< - protos.google.privacy.dlp.v2.IInspectTemplate, - protos.google.privacy.dlp.v2.IGetInspectTemplateRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.privacy.dlp.v2.IInspectTemplate, + | protos.google.privacy.dlp.v2.IGetInspectTemplateRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getInspectTemplate response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.getInspectTemplate(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.privacy.dlp.v2.IInspectTemplate, - protos.google.privacy.dlp.v2.IGetInspectTemplateRequest|undefined, {}|undefined - ]) => { - this._log.info('getInspectTemplate response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getInspectTemplate(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.privacy.dlp.v2.IInspectTemplate, + protos.google.privacy.dlp.v2.IGetInspectTemplateRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getInspectTemplate response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Deletes an InspectTemplate. - * See https://cloud.google.com/dlp/docs/creating-templates to learn more. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. Resource name of the organization and inspectTemplate to be deleted, for - * example `organizations/433245324/inspectTemplates/432452342` or - * projects/project-id/inspectTemplates/432452342. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/dlp_service.delete_inspect_template.js - * region_tag:dlp_v2_generated_DlpService_DeleteInspectTemplate_async - */ + /** + * Deletes an InspectTemplate. + * See https://cloud.google.com/dlp/docs/creating-templates to learn more. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Resource name of the organization and inspectTemplate to be deleted, for + * example `organizations/433245324/inspectTemplates/432452342` or + * projects/project-id/inspectTemplates/432452342. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/dlp_service.delete_inspect_template.js + * region_tag:dlp_v2_generated_DlpService_DeleteInspectTemplate_async + */ deleteInspectTemplate( - request?: protos.google.privacy.dlp.v2.IDeleteInspectTemplateRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.privacy.dlp.v2.IDeleteInspectTemplateRequest|undefined, {}|undefined - ]>; + request?: protos.google.privacy.dlp.v2.IDeleteInspectTemplateRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.privacy.dlp.v2.IDeleteInspectTemplateRequest | undefined, + {} | undefined, + ] + >; deleteInspectTemplate( - request: protos.google.privacy.dlp.v2.IDeleteInspectTemplateRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.privacy.dlp.v2.IDeleteInspectTemplateRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.privacy.dlp.v2.IDeleteInspectTemplateRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.privacy.dlp.v2.IDeleteInspectTemplateRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteInspectTemplate( - request: protos.google.privacy.dlp.v2.IDeleteInspectTemplateRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.privacy.dlp.v2.IDeleteInspectTemplateRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.privacy.dlp.v2.IDeleteInspectTemplateRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.privacy.dlp.v2.IDeleteInspectTemplateRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteInspectTemplate( - request?: protos.google.privacy.dlp.v2.IDeleteInspectTemplateRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.privacy.dlp.v2.IDeleteInspectTemplateRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.privacy.dlp.v2.IDeleteInspectTemplateRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.protobuf.IEmpty, - protos.google.privacy.dlp.v2.IDeleteInspectTemplateRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.privacy.dlp.v2.IDeleteInspectTemplateRequest|undefined, {}|undefined - ]>|void { + | protos.google.privacy.dlp.v2.IDeleteInspectTemplateRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + | protos.google.privacy.dlp.v2.IDeleteInspectTemplateRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.privacy.dlp.v2.IDeleteInspectTemplateRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('deleteInspectTemplate request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.privacy.dlp.v2.IDeleteInspectTemplateRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.privacy.dlp.v2.IDeleteInspectTemplateRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteInspectTemplate response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.deleteInspectTemplate(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.privacy.dlp.v2.IDeleteInspectTemplateRequest|undefined, {}|undefined - ]) => { - this._log.info('deleteInspectTemplate response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteInspectTemplate(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + ( + | protos.google.privacy.dlp.v2.IDeleteInspectTemplateRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('deleteInspectTemplate response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Creates a DeidentifyTemplate for re-using frequently used configuration - * for de-identifying content, images, and storage. - * See https://cloud.google.com/dlp/docs/creating-templates-deid to learn - * more. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent resource name, for example projects/my-project-id or - * organizations/my-org-id. - * @param {google.privacy.dlp.v2.DeidentifyTemplate} request.deidentifyTemplate - * Required. The DeidentifyTemplate to create. - * @param {string} request.templateId - * The template id can contain uppercase and lowercase letters, - * numbers, and hyphens; that is, it must match the regular - * expression: `[a-zA-Z\\d-_]+`. The maximum length is 100 - * characters. Can be empty to allow the system to generate one. - * @param {string} request.locationId - * The geographic location to store the deidentification template. Reserved - * for future extensions. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.privacy.dlp.v2.DeidentifyTemplate|DeidentifyTemplate}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/dlp_service.create_deidentify_template.js - * region_tag:dlp_v2_generated_DlpService_CreateDeidentifyTemplate_async - */ + /** + * Creates a DeidentifyTemplate for re-using frequently used configuration + * for de-identifying content, images, and storage. + * See https://cloud.google.com/dlp/docs/creating-templates-deid to learn + * more. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource name, for example projects/my-project-id or + * organizations/my-org-id. + * @param {google.privacy.dlp.v2.DeidentifyTemplate} request.deidentifyTemplate + * Required. The DeidentifyTemplate to create. + * @param {string} request.templateId + * The template id can contain uppercase and lowercase letters, + * numbers, and hyphens; that is, it must match the regular + * expression: `[a-zA-Z\\d-_]+`. The maximum length is 100 + * characters. Can be empty to allow the system to generate one. + * @param {string} request.locationId + * The geographic location to store the deidentification template. Reserved + * for future extensions. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.privacy.dlp.v2.DeidentifyTemplate|DeidentifyTemplate}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/dlp_service.create_deidentify_template.js + * region_tag:dlp_v2_generated_DlpService_CreateDeidentifyTemplate_async + */ createDeidentifyTemplate( - request?: protos.google.privacy.dlp.v2.ICreateDeidentifyTemplateRequest, - options?: CallOptions): - Promise<[ - protos.google.privacy.dlp.v2.IDeidentifyTemplate, - protos.google.privacy.dlp.v2.ICreateDeidentifyTemplateRequest|undefined, {}|undefined - ]>; + request?: protos.google.privacy.dlp.v2.ICreateDeidentifyTemplateRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.privacy.dlp.v2.IDeidentifyTemplate, + protos.google.privacy.dlp.v2.ICreateDeidentifyTemplateRequest | undefined, + {} | undefined, + ] + >; createDeidentifyTemplate( - request: protos.google.privacy.dlp.v2.ICreateDeidentifyTemplateRequest, - options: CallOptions, - callback: Callback< - protos.google.privacy.dlp.v2.IDeidentifyTemplate, - protos.google.privacy.dlp.v2.ICreateDeidentifyTemplateRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.privacy.dlp.v2.ICreateDeidentifyTemplateRequest, + options: CallOptions, + callback: Callback< + protos.google.privacy.dlp.v2.IDeidentifyTemplate, + | protos.google.privacy.dlp.v2.ICreateDeidentifyTemplateRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createDeidentifyTemplate( - request: protos.google.privacy.dlp.v2.ICreateDeidentifyTemplateRequest, - callback: Callback< - protos.google.privacy.dlp.v2.IDeidentifyTemplate, - protos.google.privacy.dlp.v2.ICreateDeidentifyTemplateRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.privacy.dlp.v2.ICreateDeidentifyTemplateRequest, + callback: Callback< + protos.google.privacy.dlp.v2.IDeidentifyTemplate, + | protos.google.privacy.dlp.v2.ICreateDeidentifyTemplateRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createDeidentifyTemplate( - request?: protos.google.privacy.dlp.v2.ICreateDeidentifyTemplateRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.privacy.dlp.v2.IDeidentifyTemplate, - protos.google.privacy.dlp.v2.ICreateDeidentifyTemplateRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.privacy.dlp.v2.ICreateDeidentifyTemplateRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.privacy.dlp.v2.IDeidentifyTemplate, - protos.google.privacy.dlp.v2.ICreateDeidentifyTemplateRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.privacy.dlp.v2.IDeidentifyTemplate, - protos.google.privacy.dlp.v2.ICreateDeidentifyTemplateRequest|undefined, {}|undefined - ]>|void { + | protos.google.privacy.dlp.v2.ICreateDeidentifyTemplateRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.privacy.dlp.v2.IDeidentifyTemplate, + | protos.google.privacy.dlp.v2.ICreateDeidentifyTemplateRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.privacy.dlp.v2.IDeidentifyTemplate, + protos.google.privacy.dlp.v2.ICreateDeidentifyTemplateRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - 'location_id': request.locationId?.toString() ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + location_id: request.locationId?.toString() ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('createDeidentifyTemplate request %j', request); - const wrappedCallback: Callback< - protos.google.privacy.dlp.v2.IDeidentifyTemplate, - protos.google.privacy.dlp.v2.ICreateDeidentifyTemplateRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.privacy.dlp.v2.IDeidentifyTemplate, + | protos.google.privacy.dlp.v2.ICreateDeidentifyTemplateRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createDeidentifyTemplate response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.createDeidentifyTemplate(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.privacy.dlp.v2.IDeidentifyTemplate, - protos.google.privacy.dlp.v2.ICreateDeidentifyTemplateRequest|undefined, {}|undefined - ]) => { - this._log.info('createDeidentifyTemplate response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createDeidentifyTemplate(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.privacy.dlp.v2.IDeidentifyTemplate, + ( + | protos.google.privacy.dlp.v2.ICreateDeidentifyTemplateRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('createDeidentifyTemplate response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Updates the DeidentifyTemplate. - * See https://cloud.google.com/dlp/docs/creating-templates-deid to learn - * more. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. Resource name of organization and deidentify template to be updated, for - * example `organizations/433245324/deidentifyTemplates/432452342` or - * projects/project-id/deidentifyTemplates/432452342. - * @param {google.privacy.dlp.v2.DeidentifyTemplate} request.deidentifyTemplate - * New DeidentifyTemplate value. - * @param {google.protobuf.FieldMask} request.updateMask - * Mask to control which fields get updated. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.privacy.dlp.v2.DeidentifyTemplate|DeidentifyTemplate}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/dlp_service.update_deidentify_template.js - * region_tag:dlp_v2_generated_DlpService_UpdateDeidentifyTemplate_async - */ + /** + * Updates the DeidentifyTemplate. + * See https://cloud.google.com/dlp/docs/creating-templates-deid to learn + * more. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Resource name of organization and deidentify template to be updated, for + * example `organizations/433245324/deidentifyTemplates/432452342` or + * projects/project-id/deidentifyTemplates/432452342. + * @param {google.privacy.dlp.v2.DeidentifyTemplate} request.deidentifyTemplate + * New DeidentifyTemplate value. + * @param {google.protobuf.FieldMask} request.updateMask + * Mask to control which fields get updated. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.privacy.dlp.v2.DeidentifyTemplate|DeidentifyTemplate}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/dlp_service.update_deidentify_template.js + * region_tag:dlp_v2_generated_DlpService_UpdateDeidentifyTemplate_async + */ updateDeidentifyTemplate( - request?: protos.google.privacy.dlp.v2.IUpdateDeidentifyTemplateRequest, - options?: CallOptions): - Promise<[ - protos.google.privacy.dlp.v2.IDeidentifyTemplate, - protos.google.privacy.dlp.v2.IUpdateDeidentifyTemplateRequest|undefined, {}|undefined - ]>; + request?: protos.google.privacy.dlp.v2.IUpdateDeidentifyTemplateRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.privacy.dlp.v2.IDeidentifyTemplate, + protos.google.privacy.dlp.v2.IUpdateDeidentifyTemplateRequest | undefined, + {} | undefined, + ] + >; updateDeidentifyTemplate( - request: protos.google.privacy.dlp.v2.IUpdateDeidentifyTemplateRequest, - options: CallOptions, - callback: Callback< - protos.google.privacy.dlp.v2.IDeidentifyTemplate, - protos.google.privacy.dlp.v2.IUpdateDeidentifyTemplateRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.privacy.dlp.v2.IUpdateDeidentifyTemplateRequest, + options: CallOptions, + callback: Callback< + protos.google.privacy.dlp.v2.IDeidentifyTemplate, + | protos.google.privacy.dlp.v2.IUpdateDeidentifyTemplateRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateDeidentifyTemplate( - request: protos.google.privacy.dlp.v2.IUpdateDeidentifyTemplateRequest, - callback: Callback< - protos.google.privacy.dlp.v2.IDeidentifyTemplate, - protos.google.privacy.dlp.v2.IUpdateDeidentifyTemplateRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.privacy.dlp.v2.IUpdateDeidentifyTemplateRequest, + callback: Callback< + protos.google.privacy.dlp.v2.IDeidentifyTemplate, + | protos.google.privacy.dlp.v2.IUpdateDeidentifyTemplateRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateDeidentifyTemplate( - request?: protos.google.privacy.dlp.v2.IUpdateDeidentifyTemplateRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.privacy.dlp.v2.IUpdateDeidentifyTemplateRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.privacy.dlp.v2.IDeidentifyTemplate, - protos.google.privacy.dlp.v2.IUpdateDeidentifyTemplateRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.privacy.dlp.v2.IDeidentifyTemplate, - protos.google.privacy.dlp.v2.IUpdateDeidentifyTemplateRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.privacy.dlp.v2.IDeidentifyTemplate, - protos.google.privacy.dlp.v2.IUpdateDeidentifyTemplateRequest|undefined, {}|undefined - ]>|void { + | protos.google.privacy.dlp.v2.IUpdateDeidentifyTemplateRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.privacy.dlp.v2.IDeidentifyTemplate, + | protos.google.privacy.dlp.v2.IUpdateDeidentifyTemplateRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.privacy.dlp.v2.IDeidentifyTemplate, + protos.google.privacy.dlp.v2.IUpdateDeidentifyTemplateRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateDeidentifyTemplate request %j', request); - const wrappedCallback: Callback< - protos.google.privacy.dlp.v2.IDeidentifyTemplate, - protos.google.privacy.dlp.v2.IUpdateDeidentifyTemplateRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.privacy.dlp.v2.IDeidentifyTemplate, + | protos.google.privacy.dlp.v2.IUpdateDeidentifyTemplateRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateDeidentifyTemplate response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.updateDeidentifyTemplate(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.privacy.dlp.v2.IDeidentifyTemplate, - protos.google.privacy.dlp.v2.IUpdateDeidentifyTemplateRequest|undefined, {}|undefined - ]) => { - this._log.info('updateDeidentifyTemplate response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateDeidentifyTemplate(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.privacy.dlp.v2.IDeidentifyTemplate, + ( + | protos.google.privacy.dlp.v2.IUpdateDeidentifyTemplateRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('updateDeidentifyTemplate response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Gets a DeidentifyTemplate. - * See https://cloud.google.com/dlp/docs/creating-templates-deid to learn - * more. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. Resource name of the organization and deidentify template to be read, for - * example `organizations/433245324/deidentifyTemplates/432452342` or - * projects/project-id/deidentifyTemplates/432452342. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.privacy.dlp.v2.DeidentifyTemplate|DeidentifyTemplate}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/dlp_service.get_deidentify_template.js - * region_tag:dlp_v2_generated_DlpService_GetDeidentifyTemplate_async - */ + /** + * Gets a DeidentifyTemplate. + * See https://cloud.google.com/dlp/docs/creating-templates-deid to learn + * more. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Resource name of the organization and deidentify template to be read, for + * example `organizations/433245324/deidentifyTemplates/432452342` or + * projects/project-id/deidentifyTemplates/432452342. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.privacy.dlp.v2.DeidentifyTemplate|DeidentifyTemplate}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/dlp_service.get_deidentify_template.js + * region_tag:dlp_v2_generated_DlpService_GetDeidentifyTemplate_async + */ getDeidentifyTemplate( - request?: protos.google.privacy.dlp.v2.IGetDeidentifyTemplateRequest, - options?: CallOptions): - Promise<[ - protos.google.privacy.dlp.v2.IDeidentifyTemplate, - protos.google.privacy.dlp.v2.IGetDeidentifyTemplateRequest|undefined, {}|undefined - ]>; + request?: protos.google.privacy.dlp.v2.IGetDeidentifyTemplateRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.privacy.dlp.v2.IDeidentifyTemplate, + protos.google.privacy.dlp.v2.IGetDeidentifyTemplateRequest | undefined, + {} | undefined, + ] + >; getDeidentifyTemplate( - request: protos.google.privacy.dlp.v2.IGetDeidentifyTemplateRequest, - options: CallOptions, - callback: Callback< - protos.google.privacy.dlp.v2.IDeidentifyTemplate, - protos.google.privacy.dlp.v2.IGetDeidentifyTemplateRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.privacy.dlp.v2.IGetDeidentifyTemplateRequest, + options: CallOptions, + callback: Callback< + protos.google.privacy.dlp.v2.IDeidentifyTemplate, + | protos.google.privacy.dlp.v2.IGetDeidentifyTemplateRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getDeidentifyTemplate( - request: protos.google.privacy.dlp.v2.IGetDeidentifyTemplateRequest, - callback: Callback< - protos.google.privacy.dlp.v2.IDeidentifyTemplate, - protos.google.privacy.dlp.v2.IGetDeidentifyTemplateRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.privacy.dlp.v2.IGetDeidentifyTemplateRequest, + callback: Callback< + protos.google.privacy.dlp.v2.IDeidentifyTemplate, + | protos.google.privacy.dlp.v2.IGetDeidentifyTemplateRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getDeidentifyTemplate( - request?: protos.google.privacy.dlp.v2.IGetDeidentifyTemplateRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.privacy.dlp.v2.IDeidentifyTemplate, - protos.google.privacy.dlp.v2.IGetDeidentifyTemplateRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.privacy.dlp.v2.IGetDeidentifyTemplateRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.privacy.dlp.v2.IDeidentifyTemplate, - protos.google.privacy.dlp.v2.IGetDeidentifyTemplateRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.privacy.dlp.v2.IDeidentifyTemplate, - protos.google.privacy.dlp.v2.IGetDeidentifyTemplateRequest|undefined, {}|undefined - ]>|void { + | protos.google.privacy.dlp.v2.IGetDeidentifyTemplateRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.privacy.dlp.v2.IDeidentifyTemplate, + | protos.google.privacy.dlp.v2.IGetDeidentifyTemplateRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.privacy.dlp.v2.IDeidentifyTemplate, + protos.google.privacy.dlp.v2.IGetDeidentifyTemplateRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getDeidentifyTemplate request %j', request); - const wrappedCallback: Callback< - protos.google.privacy.dlp.v2.IDeidentifyTemplate, - protos.google.privacy.dlp.v2.IGetDeidentifyTemplateRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.privacy.dlp.v2.IDeidentifyTemplate, + | protos.google.privacy.dlp.v2.IGetDeidentifyTemplateRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getDeidentifyTemplate response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.getDeidentifyTemplate(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.privacy.dlp.v2.IDeidentifyTemplate, - protos.google.privacy.dlp.v2.IGetDeidentifyTemplateRequest|undefined, {}|undefined - ]) => { - this._log.info('getDeidentifyTemplate response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getDeidentifyTemplate(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.privacy.dlp.v2.IDeidentifyTemplate, + ( + | protos.google.privacy.dlp.v2.IGetDeidentifyTemplateRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('getDeidentifyTemplate response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Deletes a DeidentifyTemplate. - * See https://cloud.google.com/dlp/docs/creating-templates-deid to learn - * more. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. Resource name of the organization and deidentify template to be deleted, - * for example `organizations/433245324/deidentifyTemplates/432452342` or - * projects/project-id/deidentifyTemplates/432452342. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/dlp_service.delete_deidentify_template.js - * region_tag:dlp_v2_generated_DlpService_DeleteDeidentifyTemplate_async - */ + /** + * Deletes a DeidentifyTemplate. + * See https://cloud.google.com/dlp/docs/creating-templates-deid to learn + * more. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Resource name of the organization and deidentify template to be deleted, + * for example `organizations/433245324/deidentifyTemplates/432452342` or + * projects/project-id/deidentifyTemplates/432452342. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/dlp_service.delete_deidentify_template.js + * region_tag:dlp_v2_generated_DlpService_DeleteDeidentifyTemplate_async + */ deleteDeidentifyTemplate( - request?: protos.google.privacy.dlp.v2.IDeleteDeidentifyTemplateRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.privacy.dlp.v2.IDeleteDeidentifyTemplateRequest|undefined, {}|undefined - ]>; + request?: protos.google.privacy.dlp.v2.IDeleteDeidentifyTemplateRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.privacy.dlp.v2.IDeleteDeidentifyTemplateRequest | undefined, + {} | undefined, + ] + >; deleteDeidentifyTemplate( - request: protos.google.privacy.dlp.v2.IDeleteDeidentifyTemplateRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.privacy.dlp.v2.IDeleteDeidentifyTemplateRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.privacy.dlp.v2.IDeleteDeidentifyTemplateRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.privacy.dlp.v2.IDeleteDeidentifyTemplateRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteDeidentifyTemplate( - request: protos.google.privacy.dlp.v2.IDeleteDeidentifyTemplateRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.privacy.dlp.v2.IDeleteDeidentifyTemplateRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.privacy.dlp.v2.IDeleteDeidentifyTemplateRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.privacy.dlp.v2.IDeleteDeidentifyTemplateRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteDeidentifyTemplate( - request?: protos.google.privacy.dlp.v2.IDeleteDeidentifyTemplateRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.privacy.dlp.v2.IDeleteDeidentifyTemplateRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.privacy.dlp.v2.IDeleteDeidentifyTemplateRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.protobuf.IEmpty, - protos.google.privacy.dlp.v2.IDeleteDeidentifyTemplateRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.privacy.dlp.v2.IDeleteDeidentifyTemplateRequest|undefined, {}|undefined - ]>|void { + | protos.google.privacy.dlp.v2.IDeleteDeidentifyTemplateRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + | protos.google.privacy.dlp.v2.IDeleteDeidentifyTemplateRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.privacy.dlp.v2.IDeleteDeidentifyTemplateRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('deleteDeidentifyTemplate request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.privacy.dlp.v2.IDeleteDeidentifyTemplateRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.privacy.dlp.v2.IDeleteDeidentifyTemplateRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteDeidentifyTemplate response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.deleteDeidentifyTemplate(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.privacy.dlp.v2.IDeleteDeidentifyTemplateRequest|undefined, {}|undefined - ]) => { - this._log.info('deleteDeidentifyTemplate response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteDeidentifyTemplate(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + ( + | protos.google.privacy.dlp.v2.IDeleteDeidentifyTemplateRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('deleteDeidentifyTemplate response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Creates a job trigger to run DLP actions such as scanning storage for - * sensitive information on a set schedule. - * See https://cloud.google.com/dlp/docs/creating-job-triggers to learn more. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent resource name, for example projects/my-project-id. - * @param {google.privacy.dlp.v2.JobTrigger} request.jobTrigger - * Required. The JobTrigger to create. - * @param {string} request.triggerId - * The trigger id can contain uppercase and lowercase letters, - * numbers, and hyphens; that is, it must match the regular - * expression: `[a-zA-Z\\d-_]+`. The maximum length is 100 - * characters. Can be empty to allow the system to generate one. - * @param {string} request.locationId - * The geographic location to store the job trigger. Reserved for - * future extensions. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.privacy.dlp.v2.JobTrigger|JobTrigger}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/dlp_service.create_job_trigger.js - * region_tag:dlp_v2_generated_DlpService_CreateJobTrigger_async - */ + /** + * Creates a job trigger to run DLP actions such as scanning storage for + * sensitive information on a set schedule. + * See https://cloud.google.com/dlp/docs/creating-job-triggers to learn more. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource name, for example projects/my-project-id. + * @param {google.privacy.dlp.v2.JobTrigger} request.jobTrigger + * Required. The JobTrigger to create. + * @param {string} request.triggerId + * The trigger id can contain uppercase and lowercase letters, + * numbers, and hyphens; that is, it must match the regular + * expression: `[a-zA-Z\\d-_]+`. The maximum length is 100 + * characters. Can be empty to allow the system to generate one. + * @param {string} request.locationId + * The geographic location to store the job trigger. Reserved for + * future extensions. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.privacy.dlp.v2.JobTrigger|JobTrigger}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/dlp_service.create_job_trigger.js + * region_tag:dlp_v2_generated_DlpService_CreateJobTrigger_async + */ createJobTrigger( - request?: protos.google.privacy.dlp.v2.ICreateJobTriggerRequest, - options?: CallOptions): - Promise<[ - protos.google.privacy.dlp.v2.IJobTrigger, - protos.google.privacy.dlp.v2.ICreateJobTriggerRequest|undefined, {}|undefined - ]>; + request?: protos.google.privacy.dlp.v2.ICreateJobTriggerRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.privacy.dlp.v2.IJobTrigger, + protos.google.privacy.dlp.v2.ICreateJobTriggerRequest | undefined, + {} | undefined, + ] + >; createJobTrigger( - request: protos.google.privacy.dlp.v2.ICreateJobTriggerRequest, - options: CallOptions, - callback: Callback< - protos.google.privacy.dlp.v2.IJobTrigger, - protos.google.privacy.dlp.v2.ICreateJobTriggerRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.privacy.dlp.v2.ICreateJobTriggerRequest, + options: CallOptions, + callback: Callback< + protos.google.privacy.dlp.v2.IJobTrigger, + protos.google.privacy.dlp.v2.ICreateJobTriggerRequest | null | undefined, + {} | null | undefined + >, + ): void; createJobTrigger( - request: protos.google.privacy.dlp.v2.ICreateJobTriggerRequest, - callback: Callback< - protos.google.privacy.dlp.v2.IJobTrigger, - protos.google.privacy.dlp.v2.ICreateJobTriggerRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.privacy.dlp.v2.ICreateJobTriggerRequest, + callback: Callback< + protos.google.privacy.dlp.v2.IJobTrigger, + protos.google.privacy.dlp.v2.ICreateJobTriggerRequest | null | undefined, + {} | null | undefined + >, + ): void; createJobTrigger( - request?: protos.google.privacy.dlp.v2.ICreateJobTriggerRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.privacy.dlp.v2.IJobTrigger, - protos.google.privacy.dlp.v2.ICreateJobTriggerRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.privacy.dlp.v2.ICreateJobTriggerRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.privacy.dlp.v2.IJobTrigger, - protos.google.privacy.dlp.v2.ICreateJobTriggerRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.privacy.dlp.v2.IJobTrigger, - protos.google.privacy.dlp.v2.ICreateJobTriggerRequest|undefined, {}|undefined - ]>|void { + | protos.google.privacy.dlp.v2.ICreateJobTriggerRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.privacy.dlp.v2.IJobTrigger, + protos.google.privacy.dlp.v2.ICreateJobTriggerRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.privacy.dlp.v2.IJobTrigger, + protos.google.privacy.dlp.v2.ICreateJobTriggerRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - 'location_id': request.locationId?.toString() ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + location_id: request.locationId?.toString() ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('createJobTrigger request %j', request); - const wrappedCallback: Callback< - protos.google.privacy.dlp.v2.IJobTrigger, - protos.google.privacy.dlp.v2.ICreateJobTriggerRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.privacy.dlp.v2.IJobTrigger, + | protos.google.privacy.dlp.v2.ICreateJobTriggerRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createJobTrigger response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.createJobTrigger(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.privacy.dlp.v2.IJobTrigger, - protos.google.privacy.dlp.v2.ICreateJobTriggerRequest|undefined, {}|undefined - ]) => { - this._log.info('createJobTrigger response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createJobTrigger(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.privacy.dlp.v2.IJobTrigger, + protos.google.privacy.dlp.v2.ICreateJobTriggerRequest | undefined, + {} | undefined, + ]) => { + this._log.info('createJobTrigger response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Updates a job trigger. - * See https://cloud.google.com/dlp/docs/creating-job-triggers to learn more. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. Resource name of the project and the triggeredJob, for example - * `projects/dlp-test-project/jobTriggers/53234423`. - * @param {google.privacy.dlp.v2.JobTrigger} request.jobTrigger - * New JobTrigger value. - * @param {google.protobuf.FieldMask} request.updateMask - * Mask to control which fields get updated. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.privacy.dlp.v2.JobTrigger|JobTrigger}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/dlp_service.update_job_trigger.js - * region_tag:dlp_v2_generated_DlpService_UpdateJobTrigger_async - */ + /** + * Updates a job trigger. + * See https://cloud.google.com/dlp/docs/creating-job-triggers to learn more. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Resource name of the project and the triggeredJob, for example + * `projects/dlp-test-project/jobTriggers/53234423`. + * @param {google.privacy.dlp.v2.JobTrigger} request.jobTrigger + * New JobTrigger value. + * @param {google.protobuf.FieldMask} request.updateMask + * Mask to control which fields get updated. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.privacy.dlp.v2.JobTrigger|JobTrigger}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/dlp_service.update_job_trigger.js + * region_tag:dlp_v2_generated_DlpService_UpdateJobTrigger_async + */ updateJobTrigger( - request?: protos.google.privacy.dlp.v2.IUpdateJobTriggerRequest, - options?: CallOptions): - Promise<[ - protos.google.privacy.dlp.v2.IJobTrigger, - protos.google.privacy.dlp.v2.IUpdateJobTriggerRequest|undefined, {}|undefined - ]>; + request?: protos.google.privacy.dlp.v2.IUpdateJobTriggerRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.privacy.dlp.v2.IJobTrigger, + protos.google.privacy.dlp.v2.IUpdateJobTriggerRequest | undefined, + {} | undefined, + ] + >; updateJobTrigger( - request: protos.google.privacy.dlp.v2.IUpdateJobTriggerRequest, - options: CallOptions, - callback: Callback< - protos.google.privacy.dlp.v2.IJobTrigger, - protos.google.privacy.dlp.v2.IUpdateJobTriggerRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.privacy.dlp.v2.IUpdateJobTriggerRequest, + options: CallOptions, + callback: Callback< + protos.google.privacy.dlp.v2.IJobTrigger, + protos.google.privacy.dlp.v2.IUpdateJobTriggerRequest | null | undefined, + {} | null | undefined + >, + ): void; updateJobTrigger( - request: protos.google.privacy.dlp.v2.IUpdateJobTriggerRequest, - callback: Callback< - protos.google.privacy.dlp.v2.IJobTrigger, - protos.google.privacy.dlp.v2.IUpdateJobTriggerRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.privacy.dlp.v2.IUpdateJobTriggerRequest, + callback: Callback< + protos.google.privacy.dlp.v2.IJobTrigger, + protos.google.privacy.dlp.v2.IUpdateJobTriggerRequest | null | undefined, + {} | null | undefined + >, + ): void; updateJobTrigger( - request?: protos.google.privacy.dlp.v2.IUpdateJobTriggerRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.privacy.dlp.v2.IUpdateJobTriggerRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.privacy.dlp.v2.IJobTrigger, - protos.google.privacy.dlp.v2.IUpdateJobTriggerRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.privacy.dlp.v2.IJobTrigger, - protos.google.privacy.dlp.v2.IUpdateJobTriggerRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.privacy.dlp.v2.IJobTrigger, - protos.google.privacy.dlp.v2.IUpdateJobTriggerRequest|undefined, {}|undefined - ]>|void { + | protos.google.privacy.dlp.v2.IUpdateJobTriggerRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.privacy.dlp.v2.IJobTrigger, + protos.google.privacy.dlp.v2.IUpdateJobTriggerRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.privacy.dlp.v2.IJobTrigger, + protos.google.privacy.dlp.v2.IUpdateJobTriggerRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateJobTrigger request %j', request); - const wrappedCallback: Callback< - protos.google.privacy.dlp.v2.IJobTrigger, - protos.google.privacy.dlp.v2.IUpdateJobTriggerRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.privacy.dlp.v2.IJobTrigger, + | protos.google.privacy.dlp.v2.IUpdateJobTriggerRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateJobTrigger response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.updateJobTrigger(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.privacy.dlp.v2.IJobTrigger, - protos.google.privacy.dlp.v2.IUpdateJobTriggerRequest|undefined, {}|undefined - ]) => { - this._log.info('updateJobTrigger response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateJobTrigger(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.privacy.dlp.v2.IJobTrigger, + protos.google.privacy.dlp.v2.IUpdateJobTriggerRequest | undefined, + {} | undefined, + ]) => { + this._log.info('updateJobTrigger response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Gets a job trigger. - * See https://cloud.google.com/dlp/docs/creating-job-triggers to learn more. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. Resource name of the project and the triggeredJob, for example - * `projects/dlp-test-project/jobTriggers/53234423`. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.privacy.dlp.v2.JobTrigger|JobTrigger}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/dlp_service.get_job_trigger.js - * region_tag:dlp_v2_generated_DlpService_GetJobTrigger_async - */ + /** + * Gets a job trigger. + * See https://cloud.google.com/dlp/docs/creating-job-triggers to learn more. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Resource name of the project and the triggeredJob, for example + * `projects/dlp-test-project/jobTriggers/53234423`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.privacy.dlp.v2.JobTrigger|JobTrigger}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/dlp_service.get_job_trigger.js + * region_tag:dlp_v2_generated_DlpService_GetJobTrigger_async + */ getJobTrigger( - request?: protos.google.privacy.dlp.v2.IGetJobTriggerRequest, - options?: CallOptions): - Promise<[ - protos.google.privacy.dlp.v2.IJobTrigger, - protos.google.privacy.dlp.v2.IGetJobTriggerRequest|undefined, {}|undefined - ]>; + request?: protos.google.privacy.dlp.v2.IGetJobTriggerRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.privacy.dlp.v2.IJobTrigger, + protos.google.privacy.dlp.v2.IGetJobTriggerRequest | undefined, + {} | undefined, + ] + >; getJobTrigger( - request: protos.google.privacy.dlp.v2.IGetJobTriggerRequest, - options: CallOptions, - callback: Callback< - protos.google.privacy.dlp.v2.IJobTrigger, - protos.google.privacy.dlp.v2.IGetJobTriggerRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.privacy.dlp.v2.IGetJobTriggerRequest, + options: CallOptions, + callback: Callback< + protos.google.privacy.dlp.v2.IJobTrigger, + protos.google.privacy.dlp.v2.IGetJobTriggerRequest | null | undefined, + {} | null | undefined + >, + ): void; getJobTrigger( - request: protos.google.privacy.dlp.v2.IGetJobTriggerRequest, - callback: Callback< - protos.google.privacy.dlp.v2.IJobTrigger, - protos.google.privacy.dlp.v2.IGetJobTriggerRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.privacy.dlp.v2.IGetJobTriggerRequest, + callback: Callback< + protos.google.privacy.dlp.v2.IJobTrigger, + protos.google.privacy.dlp.v2.IGetJobTriggerRequest | null | undefined, + {} | null | undefined + >, + ): void; getJobTrigger( - request?: protos.google.privacy.dlp.v2.IGetJobTriggerRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.privacy.dlp.v2.IJobTrigger, - protos.google.privacy.dlp.v2.IGetJobTriggerRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.privacy.dlp.v2.IGetJobTriggerRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.privacy.dlp.v2.IJobTrigger, - protos.google.privacy.dlp.v2.IGetJobTriggerRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.privacy.dlp.v2.IJobTrigger, - protos.google.privacy.dlp.v2.IGetJobTriggerRequest|undefined, {}|undefined - ]>|void { + protos.google.privacy.dlp.v2.IGetJobTriggerRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.privacy.dlp.v2.IJobTrigger, + protos.google.privacy.dlp.v2.IGetJobTriggerRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.privacy.dlp.v2.IJobTrigger, + protos.google.privacy.dlp.v2.IGetJobTriggerRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getJobTrigger request %j', request); - const wrappedCallback: Callback< - protos.google.privacy.dlp.v2.IJobTrigger, - protos.google.privacy.dlp.v2.IGetJobTriggerRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.privacy.dlp.v2.IJobTrigger, + protos.google.privacy.dlp.v2.IGetJobTriggerRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getJobTrigger response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.getJobTrigger(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.privacy.dlp.v2.IJobTrigger, - protos.google.privacy.dlp.v2.IGetJobTriggerRequest|undefined, {}|undefined - ]) => { - this._log.info('getJobTrigger response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getJobTrigger(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.privacy.dlp.v2.IJobTrigger, + protos.google.privacy.dlp.v2.IGetJobTriggerRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getJobTrigger response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Deletes a job trigger. - * See https://cloud.google.com/dlp/docs/creating-job-triggers to learn more. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. Resource name of the project and the triggeredJob, for example - * `projects/dlp-test-project/jobTriggers/53234423`. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/dlp_service.delete_job_trigger.js - * region_tag:dlp_v2_generated_DlpService_DeleteJobTrigger_async - */ + /** + * Deletes a job trigger. + * See https://cloud.google.com/dlp/docs/creating-job-triggers to learn more. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Resource name of the project and the triggeredJob, for example + * `projects/dlp-test-project/jobTriggers/53234423`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/dlp_service.delete_job_trigger.js + * region_tag:dlp_v2_generated_DlpService_DeleteJobTrigger_async + */ deleteJobTrigger( - request?: protos.google.privacy.dlp.v2.IDeleteJobTriggerRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.privacy.dlp.v2.IDeleteJobTriggerRequest|undefined, {}|undefined - ]>; + request?: protos.google.privacy.dlp.v2.IDeleteJobTriggerRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.privacy.dlp.v2.IDeleteJobTriggerRequest | undefined, + {} | undefined, + ] + >; deleteJobTrigger( - request: protos.google.privacy.dlp.v2.IDeleteJobTriggerRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.privacy.dlp.v2.IDeleteJobTriggerRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.privacy.dlp.v2.IDeleteJobTriggerRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.privacy.dlp.v2.IDeleteJobTriggerRequest | null | undefined, + {} | null | undefined + >, + ): void; deleteJobTrigger( - request: protos.google.privacy.dlp.v2.IDeleteJobTriggerRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.privacy.dlp.v2.IDeleteJobTriggerRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.privacy.dlp.v2.IDeleteJobTriggerRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.privacy.dlp.v2.IDeleteJobTriggerRequest | null | undefined, + {} | null | undefined + >, + ): void; deleteJobTrigger( - request?: protos.google.privacy.dlp.v2.IDeleteJobTriggerRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.privacy.dlp.v2.IDeleteJobTriggerRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.privacy.dlp.v2.IDeleteJobTriggerRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.protobuf.IEmpty, - protos.google.privacy.dlp.v2.IDeleteJobTriggerRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.privacy.dlp.v2.IDeleteJobTriggerRequest|undefined, {}|undefined - ]>|void { + | protos.google.privacy.dlp.v2.IDeleteJobTriggerRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + protos.google.privacy.dlp.v2.IDeleteJobTriggerRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.privacy.dlp.v2.IDeleteJobTriggerRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('deleteJobTrigger request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.privacy.dlp.v2.IDeleteJobTriggerRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.privacy.dlp.v2.IDeleteJobTriggerRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteJobTrigger response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.deleteJobTrigger(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.privacy.dlp.v2.IDeleteJobTriggerRequest|undefined, {}|undefined - ]) => { - this._log.info('deleteJobTrigger response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteJobTrigger(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.privacy.dlp.v2.IDeleteJobTriggerRequest | undefined, + {} | undefined, + ]) => { + this._log.info('deleteJobTrigger response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Activate a job trigger. Causes the immediate execute of a trigger - * instead of waiting on the trigger event to occur. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. Resource name of the trigger to activate, for example - * `projects/dlp-test-project/jobTriggers/53234423`. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.privacy.dlp.v2.DlpJob|DlpJob}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/dlp_service.activate_job_trigger.js - * region_tag:dlp_v2_generated_DlpService_ActivateJobTrigger_async - */ + /** + * Activate a job trigger. Causes the immediate execute of a trigger + * instead of waiting on the trigger event to occur. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Resource name of the trigger to activate, for example + * `projects/dlp-test-project/jobTriggers/53234423`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.privacy.dlp.v2.DlpJob|DlpJob}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/dlp_service.activate_job_trigger.js + * region_tag:dlp_v2_generated_DlpService_ActivateJobTrigger_async + */ activateJobTrigger( - request?: protos.google.privacy.dlp.v2.IActivateJobTriggerRequest, - options?: CallOptions): - Promise<[ - protos.google.privacy.dlp.v2.IDlpJob, - protos.google.privacy.dlp.v2.IActivateJobTriggerRequest|undefined, {}|undefined - ]>; + request?: protos.google.privacy.dlp.v2.IActivateJobTriggerRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.privacy.dlp.v2.IDlpJob, + protos.google.privacy.dlp.v2.IActivateJobTriggerRequest | undefined, + {} | undefined, + ] + >; activateJobTrigger( - request: protos.google.privacy.dlp.v2.IActivateJobTriggerRequest, - options: CallOptions, - callback: Callback< - protos.google.privacy.dlp.v2.IDlpJob, - protos.google.privacy.dlp.v2.IActivateJobTriggerRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.privacy.dlp.v2.IActivateJobTriggerRequest, + options: CallOptions, + callback: Callback< + protos.google.privacy.dlp.v2.IDlpJob, + | protos.google.privacy.dlp.v2.IActivateJobTriggerRequest + | null + | undefined, + {} | null | undefined + >, + ): void; activateJobTrigger( - request: protos.google.privacy.dlp.v2.IActivateJobTriggerRequest, - callback: Callback< - protos.google.privacy.dlp.v2.IDlpJob, - protos.google.privacy.dlp.v2.IActivateJobTriggerRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.privacy.dlp.v2.IActivateJobTriggerRequest, + callback: Callback< + protos.google.privacy.dlp.v2.IDlpJob, + | protos.google.privacy.dlp.v2.IActivateJobTriggerRequest + | null + | undefined, + {} | null | undefined + >, + ): void; activateJobTrigger( - request?: protos.google.privacy.dlp.v2.IActivateJobTriggerRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.privacy.dlp.v2.IDlpJob, - protos.google.privacy.dlp.v2.IActivateJobTriggerRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.privacy.dlp.v2.IActivateJobTriggerRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.privacy.dlp.v2.IDlpJob, - protos.google.privacy.dlp.v2.IActivateJobTriggerRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.privacy.dlp.v2.IDlpJob, - protos.google.privacy.dlp.v2.IActivateJobTriggerRequest|undefined, {}|undefined - ]>|void { + | protos.google.privacy.dlp.v2.IActivateJobTriggerRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.privacy.dlp.v2.IDlpJob, + | protos.google.privacy.dlp.v2.IActivateJobTriggerRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.privacy.dlp.v2.IDlpJob, + protos.google.privacy.dlp.v2.IActivateJobTriggerRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('activateJobTrigger request %j', request); - const wrappedCallback: Callback< - protos.google.privacy.dlp.v2.IDlpJob, - protos.google.privacy.dlp.v2.IActivateJobTriggerRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.privacy.dlp.v2.IDlpJob, + | protos.google.privacy.dlp.v2.IActivateJobTriggerRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('activateJobTrigger response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.activateJobTrigger(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.privacy.dlp.v2.IDlpJob, - protos.google.privacy.dlp.v2.IActivateJobTriggerRequest|undefined, {}|undefined - ]) => { - this._log.info('activateJobTrigger response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .activateJobTrigger(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.privacy.dlp.v2.IDlpJob, + protos.google.privacy.dlp.v2.IActivateJobTriggerRequest | undefined, + {} | undefined, + ]) => { + this._log.info('activateJobTrigger response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Creates a new job to inspect storage or calculate risk metrics. - * See https://cloud.google.com/dlp/docs/inspecting-storage and - * https://cloud.google.com/dlp/docs/compute-risk-analysis to learn more. - * - * When no InfoTypes or CustomInfoTypes are specified in inspect jobs, the - * system will automatically choose what detectors to run. By default this may - * be all types, but may change over time as detectors are updated. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent resource name, for example projects/my-project-id. - * @param {google.privacy.dlp.v2.InspectJobConfig} request.inspectJob - * Set to control what and how to inspect. - * @param {google.privacy.dlp.v2.RiskAnalysisJobConfig} request.riskJob - * Set to choose what metric to calculate. - * @param {string} request.jobId - * The job id can contain uppercase and lowercase letters, - * numbers, and hyphens; that is, it must match the regular - * expression: `[a-zA-Z\\d-_]+`. The maximum length is 100 - * characters. Can be empty to allow the system to generate one. - * @param {string} request.locationId - * The geographic location to store and process the job. Reserved for - * future extensions. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.privacy.dlp.v2.DlpJob|DlpJob}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/dlp_service.create_dlp_job.js - * region_tag:dlp_v2_generated_DlpService_CreateDlpJob_async - */ + /** + * Creates a new job to inspect storage or calculate risk metrics. + * See https://cloud.google.com/dlp/docs/inspecting-storage and + * https://cloud.google.com/dlp/docs/compute-risk-analysis to learn more. + * + * When no InfoTypes or CustomInfoTypes are specified in inspect jobs, the + * system will automatically choose what detectors to run. By default this may + * be all types, but may change over time as detectors are updated. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource name, for example projects/my-project-id. + * @param {google.privacy.dlp.v2.InspectJobConfig} request.inspectJob + * Set to control what and how to inspect. + * @param {google.privacy.dlp.v2.RiskAnalysisJobConfig} request.riskJob + * Set to choose what metric to calculate. + * @param {string} request.jobId + * The job id can contain uppercase and lowercase letters, + * numbers, and hyphens; that is, it must match the regular + * expression: `[a-zA-Z\\d-_]+`. The maximum length is 100 + * characters. Can be empty to allow the system to generate one. + * @param {string} request.locationId + * The geographic location to store and process the job. Reserved for + * future extensions. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.privacy.dlp.v2.DlpJob|DlpJob}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/dlp_service.create_dlp_job.js + * region_tag:dlp_v2_generated_DlpService_CreateDlpJob_async + */ createDlpJob( - request?: protos.google.privacy.dlp.v2.ICreateDlpJobRequest, - options?: CallOptions): - Promise<[ - protos.google.privacy.dlp.v2.IDlpJob, - protos.google.privacy.dlp.v2.ICreateDlpJobRequest|undefined, {}|undefined - ]>; + request?: protos.google.privacy.dlp.v2.ICreateDlpJobRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.privacy.dlp.v2.IDlpJob, + protos.google.privacy.dlp.v2.ICreateDlpJobRequest | undefined, + {} | undefined, + ] + >; createDlpJob( - request: protos.google.privacy.dlp.v2.ICreateDlpJobRequest, - options: CallOptions, - callback: Callback< - protos.google.privacy.dlp.v2.IDlpJob, - protos.google.privacy.dlp.v2.ICreateDlpJobRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.privacy.dlp.v2.ICreateDlpJobRequest, + options: CallOptions, + callback: Callback< + protos.google.privacy.dlp.v2.IDlpJob, + protos.google.privacy.dlp.v2.ICreateDlpJobRequest | null | undefined, + {} | null | undefined + >, + ): void; createDlpJob( - request: protos.google.privacy.dlp.v2.ICreateDlpJobRequest, - callback: Callback< - protos.google.privacy.dlp.v2.IDlpJob, - protos.google.privacy.dlp.v2.ICreateDlpJobRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.privacy.dlp.v2.ICreateDlpJobRequest, + callback: Callback< + protos.google.privacy.dlp.v2.IDlpJob, + protos.google.privacy.dlp.v2.ICreateDlpJobRequest | null | undefined, + {} | null | undefined + >, + ): void; createDlpJob( - request?: protos.google.privacy.dlp.v2.ICreateDlpJobRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.privacy.dlp.v2.ICreateDlpJobRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.privacy.dlp.v2.IDlpJob, - protos.google.privacy.dlp.v2.ICreateDlpJobRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.privacy.dlp.v2.IDlpJob, - protos.google.privacy.dlp.v2.ICreateDlpJobRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.privacy.dlp.v2.IDlpJob, - protos.google.privacy.dlp.v2.ICreateDlpJobRequest|undefined, {}|undefined - ]>|void { + protos.google.privacy.dlp.v2.ICreateDlpJobRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.privacy.dlp.v2.IDlpJob, + protos.google.privacy.dlp.v2.ICreateDlpJobRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.privacy.dlp.v2.IDlpJob, + protos.google.privacy.dlp.v2.ICreateDlpJobRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - 'location_id': request.locationId?.toString() ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + location_id: request.locationId?.toString() ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('createDlpJob request %j', request); - const wrappedCallback: Callback< - protos.google.privacy.dlp.v2.IDlpJob, - protos.google.privacy.dlp.v2.ICreateDlpJobRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.privacy.dlp.v2.IDlpJob, + protos.google.privacy.dlp.v2.ICreateDlpJobRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createDlpJob response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.createDlpJob(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.privacy.dlp.v2.IDlpJob, - protos.google.privacy.dlp.v2.ICreateDlpJobRequest|undefined, {}|undefined - ]) => { - this._log.info('createDlpJob response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createDlpJob(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.privacy.dlp.v2.IDlpJob, + protos.google.privacy.dlp.v2.ICreateDlpJobRequest | undefined, + {} | undefined, + ]) => { + this._log.info('createDlpJob response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Gets the latest state of a long-running DlpJob. - * See https://cloud.google.com/dlp/docs/inspecting-storage and - * https://cloud.google.com/dlp/docs/compute-risk-analysis to learn more. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The name of the DlpJob resource. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.privacy.dlp.v2.DlpJob|DlpJob}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/dlp_service.get_dlp_job.js - * region_tag:dlp_v2_generated_DlpService_GetDlpJob_async - */ + /** + * Gets the latest state of a long-running DlpJob. + * See https://cloud.google.com/dlp/docs/inspecting-storage and + * https://cloud.google.com/dlp/docs/compute-risk-analysis to learn more. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The name of the DlpJob resource. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.privacy.dlp.v2.DlpJob|DlpJob}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/dlp_service.get_dlp_job.js + * region_tag:dlp_v2_generated_DlpService_GetDlpJob_async + */ getDlpJob( - request?: protos.google.privacy.dlp.v2.IGetDlpJobRequest, - options?: CallOptions): - Promise<[ - protos.google.privacy.dlp.v2.IDlpJob, - protos.google.privacy.dlp.v2.IGetDlpJobRequest|undefined, {}|undefined - ]>; + request?: protos.google.privacy.dlp.v2.IGetDlpJobRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.privacy.dlp.v2.IDlpJob, + protos.google.privacy.dlp.v2.IGetDlpJobRequest | undefined, + {} | undefined, + ] + >; getDlpJob( - request: protos.google.privacy.dlp.v2.IGetDlpJobRequest, - options: CallOptions, - callback: Callback< - protos.google.privacy.dlp.v2.IDlpJob, - protos.google.privacy.dlp.v2.IGetDlpJobRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.privacy.dlp.v2.IGetDlpJobRequest, + options: CallOptions, + callback: Callback< + protos.google.privacy.dlp.v2.IDlpJob, + protos.google.privacy.dlp.v2.IGetDlpJobRequest | null | undefined, + {} | null | undefined + >, + ): void; getDlpJob( - request: protos.google.privacy.dlp.v2.IGetDlpJobRequest, - callback: Callback< - protos.google.privacy.dlp.v2.IDlpJob, - protos.google.privacy.dlp.v2.IGetDlpJobRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.privacy.dlp.v2.IGetDlpJobRequest, + callback: Callback< + protos.google.privacy.dlp.v2.IDlpJob, + protos.google.privacy.dlp.v2.IGetDlpJobRequest | null | undefined, + {} | null | undefined + >, + ): void; getDlpJob( - request?: protos.google.privacy.dlp.v2.IGetDlpJobRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.privacy.dlp.v2.IDlpJob, - protos.google.privacy.dlp.v2.IGetDlpJobRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.privacy.dlp.v2.IGetDlpJobRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.privacy.dlp.v2.IDlpJob, - protos.google.privacy.dlp.v2.IGetDlpJobRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.privacy.dlp.v2.IDlpJob, - protos.google.privacy.dlp.v2.IGetDlpJobRequest|undefined, {}|undefined - ]>|void { + protos.google.privacy.dlp.v2.IGetDlpJobRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.privacy.dlp.v2.IDlpJob, + protos.google.privacy.dlp.v2.IGetDlpJobRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.privacy.dlp.v2.IDlpJob, + protos.google.privacy.dlp.v2.IGetDlpJobRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getDlpJob request %j', request); - const wrappedCallback: Callback< - protos.google.privacy.dlp.v2.IDlpJob, - protos.google.privacy.dlp.v2.IGetDlpJobRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.privacy.dlp.v2.IDlpJob, + protos.google.privacy.dlp.v2.IGetDlpJobRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getDlpJob response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.getDlpJob(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.privacy.dlp.v2.IDlpJob, - protos.google.privacy.dlp.v2.IGetDlpJobRequest|undefined, {}|undefined - ]) => { - this._log.info('getDlpJob response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getDlpJob(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.privacy.dlp.v2.IDlpJob, + protos.google.privacy.dlp.v2.IGetDlpJobRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getDlpJob response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Deletes a long-running DlpJob. This method indicates that the client is - * no longer interested in the DlpJob result. The job will be cancelled if - * possible. - * See https://cloud.google.com/dlp/docs/inspecting-storage and - * https://cloud.google.com/dlp/docs/compute-risk-analysis to learn more. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The name of the DlpJob resource to be deleted. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/dlp_service.delete_dlp_job.js - * region_tag:dlp_v2_generated_DlpService_DeleteDlpJob_async - */ + /** + * Deletes a long-running DlpJob. This method indicates that the client is + * no longer interested in the DlpJob result. The job will be cancelled if + * possible. + * See https://cloud.google.com/dlp/docs/inspecting-storage and + * https://cloud.google.com/dlp/docs/compute-risk-analysis to learn more. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The name of the DlpJob resource to be deleted. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/dlp_service.delete_dlp_job.js + * region_tag:dlp_v2_generated_DlpService_DeleteDlpJob_async + */ deleteDlpJob( - request?: protos.google.privacy.dlp.v2.IDeleteDlpJobRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.privacy.dlp.v2.IDeleteDlpJobRequest|undefined, {}|undefined - ]>; + request?: protos.google.privacy.dlp.v2.IDeleteDlpJobRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.privacy.dlp.v2.IDeleteDlpJobRequest | undefined, + {} | undefined, + ] + >; deleteDlpJob( - request: protos.google.privacy.dlp.v2.IDeleteDlpJobRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.privacy.dlp.v2.IDeleteDlpJobRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.privacy.dlp.v2.IDeleteDlpJobRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.privacy.dlp.v2.IDeleteDlpJobRequest | null | undefined, + {} | null | undefined + >, + ): void; deleteDlpJob( - request: protos.google.privacy.dlp.v2.IDeleteDlpJobRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.privacy.dlp.v2.IDeleteDlpJobRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.privacy.dlp.v2.IDeleteDlpJobRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.privacy.dlp.v2.IDeleteDlpJobRequest | null | undefined, + {} | null | undefined + >, + ): void; deleteDlpJob( - request?: protos.google.privacy.dlp.v2.IDeleteDlpJobRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.privacy.dlp.v2.IDeleteDlpJobRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.privacy.dlp.v2.IDeleteDlpJobRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.protobuf.IEmpty, - protos.google.privacy.dlp.v2.IDeleteDlpJobRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.privacy.dlp.v2.IDeleteDlpJobRequest|undefined, {}|undefined - ]>|void { + protos.google.privacy.dlp.v2.IDeleteDlpJobRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + protos.google.privacy.dlp.v2.IDeleteDlpJobRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.privacy.dlp.v2.IDeleteDlpJobRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('deleteDlpJob request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.privacy.dlp.v2.IDeleteDlpJobRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + protos.google.privacy.dlp.v2.IDeleteDlpJobRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteDlpJob response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.deleteDlpJob(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.privacy.dlp.v2.IDeleteDlpJobRequest|undefined, {}|undefined - ]) => { - this._log.info('deleteDlpJob response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteDlpJob(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.privacy.dlp.v2.IDeleteDlpJobRequest | undefined, + {} | undefined, + ]) => { + this._log.info('deleteDlpJob response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Starts asynchronous cancellation on a long-running DlpJob. The server - * makes a best effort to cancel the DlpJob, but success is not - * guaranteed. - * See https://cloud.google.com/dlp/docs/inspecting-storage and - * https://cloud.google.com/dlp/docs/compute-risk-analysis to learn more. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The name of the DlpJob resource to be cancelled. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/dlp_service.cancel_dlp_job.js - * region_tag:dlp_v2_generated_DlpService_CancelDlpJob_async - */ + /** + * Starts asynchronous cancellation on a long-running DlpJob. The server + * makes a best effort to cancel the DlpJob, but success is not + * guaranteed. + * See https://cloud.google.com/dlp/docs/inspecting-storage and + * https://cloud.google.com/dlp/docs/compute-risk-analysis to learn more. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The name of the DlpJob resource to be cancelled. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/dlp_service.cancel_dlp_job.js + * region_tag:dlp_v2_generated_DlpService_CancelDlpJob_async + */ cancelDlpJob( - request?: protos.google.privacy.dlp.v2.ICancelDlpJobRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.privacy.dlp.v2.ICancelDlpJobRequest|undefined, {}|undefined - ]>; + request?: protos.google.privacy.dlp.v2.ICancelDlpJobRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.privacy.dlp.v2.ICancelDlpJobRequest | undefined, + {} | undefined, + ] + >; cancelDlpJob( - request: protos.google.privacy.dlp.v2.ICancelDlpJobRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.privacy.dlp.v2.ICancelDlpJobRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.privacy.dlp.v2.ICancelDlpJobRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.privacy.dlp.v2.ICancelDlpJobRequest | null | undefined, + {} | null | undefined + >, + ): void; cancelDlpJob( - request: protos.google.privacy.dlp.v2.ICancelDlpJobRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.privacy.dlp.v2.ICancelDlpJobRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.privacy.dlp.v2.ICancelDlpJobRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.privacy.dlp.v2.ICancelDlpJobRequest | null | undefined, + {} | null | undefined + >, + ): void; cancelDlpJob( - request?: protos.google.privacy.dlp.v2.ICancelDlpJobRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.protobuf.IEmpty, - protos.google.privacy.dlp.v2.ICancelDlpJobRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.privacy.dlp.v2.ICancelDlpJobRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.privacy.dlp.v2.ICancelDlpJobRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.privacy.dlp.v2.ICancelDlpJobRequest|undefined, {}|undefined - ]>|void { + protos.google.privacy.dlp.v2.ICancelDlpJobRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + protos.google.privacy.dlp.v2.ICancelDlpJobRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.privacy.dlp.v2.ICancelDlpJobRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('cancelDlpJob request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.privacy.dlp.v2.ICancelDlpJobRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + protos.google.privacy.dlp.v2.ICancelDlpJobRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('cancelDlpJob response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.cancelDlpJob(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.privacy.dlp.v2.ICancelDlpJobRequest|undefined, {}|undefined - ]) => { - this._log.info('cancelDlpJob response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .cancelDlpJob(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.privacy.dlp.v2.ICancelDlpJobRequest | undefined, + {} | undefined, + ]) => { + this._log.info('cancelDlpJob response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Creates a pre-built stored infoType to be used for inspection. - * See https://cloud.google.com/dlp/docs/creating-stored-infotypes to - * learn more. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent resource name, for example projects/my-project-id or - * organizations/my-org-id. - * @param {google.privacy.dlp.v2.StoredInfoTypeConfig} request.config - * Required. Configuration of the storedInfoType to create. - * @param {string} request.storedInfoTypeId - * The storedInfoType ID can contain uppercase and lowercase letters, - * numbers, and hyphens; that is, it must match the regular - * expression: `[a-zA-Z\\d-_]+`. The maximum length is 100 - * characters. Can be empty to allow the system to generate one. - * @param {string} request.locationId - * The geographic location to store the stored infoType. Reserved for - * future extensions. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.privacy.dlp.v2.StoredInfoType|StoredInfoType}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/dlp_service.create_stored_info_type.js - * region_tag:dlp_v2_generated_DlpService_CreateStoredInfoType_async - */ + /** + * Creates a pre-built stored infoType to be used for inspection. + * See https://cloud.google.com/dlp/docs/creating-stored-infotypes to + * learn more. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource name, for example projects/my-project-id or + * organizations/my-org-id. + * @param {google.privacy.dlp.v2.StoredInfoTypeConfig} request.config + * Required. Configuration of the storedInfoType to create. + * @param {string} request.storedInfoTypeId + * The storedInfoType ID can contain uppercase and lowercase letters, + * numbers, and hyphens; that is, it must match the regular + * expression: `[a-zA-Z\\d-_]+`. The maximum length is 100 + * characters. Can be empty to allow the system to generate one. + * @param {string} request.locationId + * The geographic location to store the stored infoType. Reserved for + * future extensions. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.privacy.dlp.v2.StoredInfoType|StoredInfoType}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/dlp_service.create_stored_info_type.js + * region_tag:dlp_v2_generated_DlpService_CreateStoredInfoType_async + */ createStoredInfoType( - request?: protos.google.privacy.dlp.v2.ICreateStoredInfoTypeRequest, - options?: CallOptions): - Promise<[ - protos.google.privacy.dlp.v2.IStoredInfoType, - protos.google.privacy.dlp.v2.ICreateStoredInfoTypeRequest|undefined, {}|undefined - ]>; + request?: protos.google.privacy.dlp.v2.ICreateStoredInfoTypeRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.privacy.dlp.v2.IStoredInfoType, + protos.google.privacy.dlp.v2.ICreateStoredInfoTypeRequest | undefined, + {} | undefined, + ] + >; createStoredInfoType( - request: protos.google.privacy.dlp.v2.ICreateStoredInfoTypeRequest, - options: CallOptions, - callback: Callback< - protos.google.privacy.dlp.v2.IStoredInfoType, - protos.google.privacy.dlp.v2.ICreateStoredInfoTypeRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.privacy.dlp.v2.ICreateStoredInfoTypeRequest, + options: CallOptions, + callback: Callback< + protos.google.privacy.dlp.v2.IStoredInfoType, + | protos.google.privacy.dlp.v2.ICreateStoredInfoTypeRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createStoredInfoType( - request: protos.google.privacy.dlp.v2.ICreateStoredInfoTypeRequest, - callback: Callback< - protos.google.privacy.dlp.v2.IStoredInfoType, - protos.google.privacy.dlp.v2.ICreateStoredInfoTypeRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.privacy.dlp.v2.ICreateStoredInfoTypeRequest, + callback: Callback< + protos.google.privacy.dlp.v2.IStoredInfoType, + | protos.google.privacy.dlp.v2.ICreateStoredInfoTypeRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createStoredInfoType( - request?: protos.google.privacy.dlp.v2.ICreateStoredInfoTypeRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.privacy.dlp.v2.ICreateStoredInfoTypeRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.privacy.dlp.v2.IStoredInfoType, - protos.google.privacy.dlp.v2.ICreateStoredInfoTypeRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.privacy.dlp.v2.IStoredInfoType, - protos.google.privacy.dlp.v2.ICreateStoredInfoTypeRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.privacy.dlp.v2.IStoredInfoType, - protos.google.privacy.dlp.v2.ICreateStoredInfoTypeRequest|undefined, {}|undefined - ]>|void { + | protos.google.privacy.dlp.v2.ICreateStoredInfoTypeRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.privacy.dlp.v2.IStoredInfoType, + | protos.google.privacy.dlp.v2.ICreateStoredInfoTypeRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.privacy.dlp.v2.IStoredInfoType, + protos.google.privacy.dlp.v2.ICreateStoredInfoTypeRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - 'location_id': request.locationId?.toString() ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + location_id: request.locationId?.toString() ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('createStoredInfoType request %j', request); - const wrappedCallback: Callback< - protos.google.privacy.dlp.v2.IStoredInfoType, - protos.google.privacy.dlp.v2.ICreateStoredInfoTypeRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.privacy.dlp.v2.IStoredInfoType, + | protos.google.privacy.dlp.v2.ICreateStoredInfoTypeRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createStoredInfoType response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.createStoredInfoType(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.privacy.dlp.v2.IStoredInfoType, - protos.google.privacy.dlp.v2.ICreateStoredInfoTypeRequest|undefined, {}|undefined - ]) => { - this._log.info('createStoredInfoType response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createStoredInfoType(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.privacy.dlp.v2.IStoredInfoType, + protos.google.privacy.dlp.v2.ICreateStoredInfoTypeRequest | undefined, + {} | undefined, + ]) => { + this._log.info('createStoredInfoType response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Updates the stored infoType by creating a new version. The existing version - * will continue to be used until the new version is ready. - * See https://cloud.google.com/dlp/docs/creating-stored-infotypes to - * learn more. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. Resource name of organization and storedInfoType to be updated, for - * example `organizations/433245324/storedInfoTypes/432452342` or - * projects/project-id/storedInfoTypes/432452342. - * @param {google.privacy.dlp.v2.StoredInfoTypeConfig} request.config - * Updated configuration for the storedInfoType. If not provided, a new - * version of the storedInfoType will be created with the existing - * configuration. - * @param {google.protobuf.FieldMask} request.updateMask - * Mask to control which fields get updated. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.privacy.dlp.v2.StoredInfoType|StoredInfoType}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/dlp_service.update_stored_info_type.js - * region_tag:dlp_v2_generated_DlpService_UpdateStoredInfoType_async - */ + /** + * Updates the stored infoType by creating a new version. The existing version + * will continue to be used until the new version is ready. + * See https://cloud.google.com/dlp/docs/creating-stored-infotypes to + * learn more. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Resource name of organization and storedInfoType to be updated, for + * example `organizations/433245324/storedInfoTypes/432452342` or + * projects/project-id/storedInfoTypes/432452342. + * @param {google.privacy.dlp.v2.StoredInfoTypeConfig} request.config + * Updated configuration for the storedInfoType. If not provided, a new + * version of the storedInfoType will be created with the existing + * configuration. + * @param {google.protobuf.FieldMask} request.updateMask + * Mask to control which fields get updated. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.privacy.dlp.v2.StoredInfoType|StoredInfoType}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/dlp_service.update_stored_info_type.js + * region_tag:dlp_v2_generated_DlpService_UpdateStoredInfoType_async + */ updateStoredInfoType( - request?: protos.google.privacy.dlp.v2.IUpdateStoredInfoTypeRequest, - options?: CallOptions): - Promise<[ - protos.google.privacy.dlp.v2.IStoredInfoType, - protos.google.privacy.dlp.v2.IUpdateStoredInfoTypeRequest|undefined, {}|undefined - ]>; + request?: protos.google.privacy.dlp.v2.IUpdateStoredInfoTypeRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.privacy.dlp.v2.IStoredInfoType, + protos.google.privacy.dlp.v2.IUpdateStoredInfoTypeRequest | undefined, + {} | undefined, + ] + >; updateStoredInfoType( - request: protos.google.privacy.dlp.v2.IUpdateStoredInfoTypeRequest, - options: CallOptions, - callback: Callback< - protos.google.privacy.dlp.v2.IStoredInfoType, - protos.google.privacy.dlp.v2.IUpdateStoredInfoTypeRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.privacy.dlp.v2.IUpdateStoredInfoTypeRequest, + options: CallOptions, + callback: Callback< + protos.google.privacy.dlp.v2.IStoredInfoType, + | protos.google.privacy.dlp.v2.IUpdateStoredInfoTypeRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateStoredInfoType( - request: protos.google.privacy.dlp.v2.IUpdateStoredInfoTypeRequest, - callback: Callback< - protos.google.privacy.dlp.v2.IStoredInfoType, - protos.google.privacy.dlp.v2.IUpdateStoredInfoTypeRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.privacy.dlp.v2.IUpdateStoredInfoTypeRequest, + callback: Callback< + protos.google.privacy.dlp.v2.IStoredInfoType, + | protos.google.privacy.dlp.v2.IUpdateStoredInfoTypeRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateStoredInfoType( - request?: protos.google.privacy.dlp.v2.IUpdateStoredInfoTypeRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.privacy.dlp.v2.IStoredInfoType, - protos.google.privacy.dlp.v2.IUpdateStoredInfoTypeRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.privacy.dlp.v2.IUpdateStoredInfoTypeRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.privacy.dlp.v2.IStoredInfoType, - protos.google.privacy.dlp.v2.IUpdateStoredInfoTypeRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.privacy.dlp.v2.IStoredInfoType, - protos.google.privacy.dlp.v2.IUpdateStoredInfoTypeRequest|undefined, {}|undefined - ]>|void { + | protos.google.privacy.dlp.v2.IUpdateStoredInfoTypeRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.privacy.dlp.v2.IStoredInfoType, + | protos.google.privacy.dlp.v2.IUpdateStoredInfoTypeRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.privacy.dlp.v2.IStoredInfoType, + protos.google.privacy.dlp.v2.IUpdateStoredInfoTypeRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateStoredInfoType request %j', request); - const wrappedCallback: Callback< - protos.google.privacy.dlp.v2.IStoredInfoType, - protos.google.privacy.dlp.v2.IUpdateStoredInfoTypeRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.privacy.dlp.v2.IStoredInfoType, + | protos.google.privacy.dlp.v2.IUpdateStoredInfoTypeRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateStoredInfoType response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.updateStoredInfoType(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.privacy.dlp.v2.IStoredInfoType, - protos.google.privacy.dlp.v2.IUpdateStoredInfoTypeRequest|undefined, {}|undefined - ]) => { - this._log.info('updateStoredInfoType response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateStoredInfoType(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.privacy.dlp.v2.IStoredInfoType, + protos.google.privacy.dlp.v2.IUpdateStoredInfoTypeRequest | undefined, + {} | undefined, + ]) => { + this._log.info('updateStoredInfoType response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Gets a stored infoType. - * See https://cloud.google.com/dlp/docs/creating-stored-infotypes to - * learn more. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. Resource name of the organization and storedInfoType to be read, for - * example `organizations/433245324/storedInfoTypes/432452342` or - * projects/project-id/storedInfoTypes/432452342. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.privacy.dlp.v2.StoredInfoType|StoredInfoType}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/dlp_service.get_stored_info_type.js - * region_tag:dlp_v2_generated_DlpService_GetStoredInfoType_async - */ + /** + * Gets a stored infoType. + * See https://cloud.google.com/dlp/docs/creating-stored-infotypes to + * learn more. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Resource name of the organization and storedInfoType to be read, for + * example `organizations/433245324/storedInfoTypes/432452342` or + * projects/project-id/storedInfoTypes/432452342. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.privacy.dlp.v2.StoredInfoType|StoredInfoType}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/dlp_service.get_stored_info_type.js + * region_tag:dlp_v2_generated_DlpService_GetStoredInfoType_async + */ getStoredInfoType( - request?: protos.google.privacy.dlp.v2.IGetStoredInfoTypeRequest, - options?: CallOptions): - Promise<[ - protos.google.privacy.dlp.v2.IStoredInfoType, - protos.google.privacy.dlp.v2.IGetStoredInfoTypeRequest|undefined, {}|undefined - ]>; + request?: protos.google.privacy.dlp.v2.IGetStoredInfoTypeRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.privacy.dlp.v2.IStoredInfoType, + protos.google.privacy.dlp.v2.IGetStoredInfoTypeRequest | undefined, + {} | undefined, + ] + >; getStoredInfoType( - request: protos.google.privacy.dlp.v2.IGetStoredInfoTypeRequest, - options: CallOptions, - callback: Callback< - protos.google.privacy.dlp.v2.IStoredInfoType, - protos.google.privacy.dlp.v2.IGetStoredInfoTypeRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.privacy.dlp.v2.IGetStoredInfoTypeRequest, + options: CallOptions, + callback: Callback< + protos.google.privacy.dlp.v2.IStoredInfoType, + protos.google.privacy.dlp.v2.IGetStoredInfoTypeRequest | null | undefined, + {} | null | undefined + >, + ): void; getStoredInfoType( - request: protos.google.privacy.dlp.v2.IGetStoredInfoTypeRequest, - callback: Callback< - protos.google.privacy.dlp.v2.IStoredInfoType, - protos.google.privacy.dlp.v2.IGetStoredInfoTypeRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.privacy.dlp.v2.IGetStoredInfoTypeRequest, + callback: Callback< + protos.google.privacy.dlp.v2.IStoredInfoType, + protos.google.privacy.dlp.v2.IGetStoredInfoTypeRequest | null | undefined, + {} | null | undefined + >, + ): void; getStoredInfoType( - request?: protos.google.privacy.dlp.v2.IGetStoredInfoTypeRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.privacy.dlp.v2.IGetStoredInfoTypeRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.privacy.dlp.v2.IStoredInfoType, - protos.google.privacy.dlp.v2.IGetStoredInfoTypeRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.privacy.dlp.v2.IStoredInfoType, - protos.google.privacy.dlp.v2.IGetStoredInfoTypeRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.privacy.dlp.v2.IStoredInfoType, - protos.google.privacy.dlp.v2.IGetStoredInfoTypeRequest|undefined, {}|undefined - ]>|void { + | protos.google.privacy.dlp.v2.IGetStoredInfoTypeRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.privacy.dlp.v2.IStoredInfoType, + protos.google.privacy.dlp.v2.IGetStoredInfoTypeRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.privacy.dlp.v2.IStoredInfoType, + protos.google.privacy.dlp.v2.IGetStoredInfoTypeRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getStoredInfoType request %j', request); - const wrappedCallback: Callback< - protos.google.privacy.dlp.v2.IStoredInfoType, - protos.google.privacy.dlp.v2.IGetStoredInfoTypeRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.privacy.dlp.v2.IStoredInfoType, + | protos.google.privacy.dlp.v2.IGetStoredInfoTypeRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getStoredInfoType response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.getStoredInfoType(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.privacy.dlp.v2.IStoredInfoType, - protos.google.privacy.dlp.v2.IGetStoredInfoTypeRequest|undefined, {}|undefined - ]) => { - this._log.info('getStoredInfoType response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getStoredInfoType(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.privacy.dlp.v2.IStoredInfoType, + protos.google.privacy.dlp.v2.IGetStoredInfoTypeRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getStoredInfoType response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Deletes a stored infoType. - * See https://cloud.google.com/dlp/docs/creating-stored-infotypes to - * learn more. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. Resource name of the organization and storedInfoType to be deleted, for - * example `organizations/433245324/storedInfoTypes/432452342` or - * projects/project-id/storedInfoTypes/432452342. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/dlp_service.delete_stored_info_type.js - * region_tag:dlp_v2_generated_DlpService_DeleteStoredInfoType_async - */ + /** + * Deletes a stored infoType. + * See https://cloud.google.com/dlp/docs/creating-stored-infotypes to + * learn more. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Resource name of the organization and storedInfoType to be deleted, for + * example `organizations/433245324/storedInfoTypes/432452342` or + * projects/project-id/storedInfoTypes/432452342. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/dlp_service.delete_stored_info_type.js + * region_tag:dlp_v2_generated_DlpService_DeleteStoredInfoType_async + */ deleteStoredInfoType( - request?: protos.google.privacy.dlp.v2.IDeleteStoredInfoTypeRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.privacy.dlp.v2.IDeleteStoredInfoTypeRequest|undefined, {}|undefined - ]>; + request?: protos.google.privacy.dlp.v2.IDeleteStoredInfoTypeRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.privacy.dlp.v2.IDeleteStoredInfoTypeRequest | undefined, + {} | undefined, + ] + >; deleteStoredInfoType( - request: protos.google.privacy.dlp.v2.IDeleteStoredInfoTypeRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.privacy.dlp.v2.IDeleteStoredInfoTypeRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.privacy.dlp.v2.IDeleteStoredInfoTypeRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.privacy.dlp.v2.IDeleteStoredInfoTypeRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteStoredInfoType( - request: protos.google.privacy.dlp.v2.IDeleteStoredInfoTypeRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.privacy.dlp.v2.IDeleteStoredInfoTypeRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.privacy.dlp.v2.IDeleteStoredInfoTypeRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.privacy.dlp.v2.IDeleteStoredInfoTypeRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteStoredInfoType( - request?: protos.google.privacy.dlp.v2.IDeleteStoredInfoTypeRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.protobuf.IEmpty, - protos.google.privacy.dlp.v2.IDeleteStoredInfoTypeRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.privacy.dlp.v2.IDeleteStoredInfoTypeRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.privacy.dlp.v2.IDeleteStoredInfoTypeRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.privacy.dlp.v2.IDeleteStoredInfoTypeRequest|undefined, {}|undefined - ]>|void { + | protos.google.privacy.dlp.v2.IDeleteStoredInfoTypeRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + | protos.google.privacy.dlp.v2.IDeleteStoredInfoTypeRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.privacy.dlp.v2.IDeleteStoredInfoTypeRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('deleteStoredInfoType request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.privacy.dlp.v2.IDeleteStoredInfoTypeRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.privacy.dlp.v2.IDeleteStoredInfoTypeRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteStoredInfoType response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.deleteStoredInfoType(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.privacy.dlp.v2.IDeleteStoredInfoTypeRequest|undefined, {}|undefined - ]) => { - this._log.info('deleteStoredInfoType response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteStoredInfoType(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.privacy.dlp.v2.IDeleteStoredInfoTypeRequest | undefined, + {} | undefined, + ]) => { + this._log.info('deleteStoredInfoType response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } - /** - * Lists InspectTemplates. - * See https://cloud.google.com/dlp/docs/creating-templates to learn more. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent resource name, for example projects/my-project-id or - * organizations/my-org-id. - * @param {string} request.pageToken - * Page token to continue retrieval. Comes from previous call - * to `ListInspectTemplates`. - * @param {number} request.pageSize - * Size of the page, can be limited by server. If zero server returns - * a page of max size 100. - * @param {string} request.orderBy - * Comma separated list of fields to order by, - * followed by `asc` or `desc` postfix. This list is case-insensitive, - * default sorting order is ascending, redundant space characters are - * insignificant. - * - * Example: `name asc,update_time, create_time desc` - * - * Supported fields are: - * - * - `create_time`: corresponds to time the template was created. - * - `update_time`: corresponds to time the template was last updated. - * - `name`: corresponds to template's name. - * - `display_name`: corresponds to template's display name. - * @param {string} request.locationId - * The geographic location where inspection templates will be retrieved from. - * Use `-` for all locations. Reserved for future extensions. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.privacy.dlp.v2.InspectTemplate|InspectTemplate}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `listInspectTemplatesAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Lists InspectTemplates. + * See https://cloud.google.com/dlp/docs/creating-templates to learn more. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource name, for example projects/my-project-id or + * organizations/my-org-id. + * @param {string} request.pageToken + * Page token to continue retrieval. Comes from previous call + * to `ListInspectTemplates`. + * @param {number} request.pageSize + * Size of the page, can be limited by server. If zero server returns + * a page of max size 100. + * @param {string} request.orderBy + * Comma separated list of fields to order by, + * followed by `asc` or `desc` postfix. This list is case-insensitive, + * default sorting order is ascending, redundant space characters are + * insignificant. + * + * Example: `name asc,update_time, create_time desc` + * + * Supported fields are: + * + * - `create_time`: corresponds to time the template was created. + * - `update_time`: corresponds to time the template was last updated. + * - `name`: corresponds to template's name. + * - `display_name`: corresponds to template's display name. + * @param {string} request.locationId + * The geographic location where inspection templates will be retrieved from. + * Use `-` for all locations. Reserved for future extensions. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.privacy.dlp.v2.InspectTemplate|InspectTemplate}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listInspectTemplatesAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listInspectTemplates( - request?: protos.google.privacy.dlp.v2.IListInspectTemplatesRequest, - options?: CallOptions): - Promise<[ - protos.google.privacy.dlp.v2.IInspectTemplate[], - protos.google.privacy.dlp.v2.IListInspectTemplatesRequest|null, - protos.google.privacy.dlp.v2.IListInspectTemplatesResponse - ]>; + request?: protos.google.privacy.dlp.v2.IListInspectTemplatesRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.privacy.dlp.v2.IInspectTemplate[], + protos.google.privacy.dlp.v2.IListInspectTemplatesRequest | null, + protos.google.privacy.dlp.v2.IListInspectTemplatesResponse, + ] + >; listInspectTemplates( - request: protos.google.privacy.dlp.v2.IListInspectTemplatesRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.privacy.dlp.v2.IListInspectTemplatesRequest, - protos.google.privacy.dlp.v2.IListInspectTemplatesResponse|null|undefined, - protos.google.privacy.dlp.v2.IInspectTemplate>): void; + request: protos.google.privacy.dlp.v2.IListInspectTemplatesRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.privacy.dlp.v2.IListInspectTemplatesRequest, + | protos.google.privacy.dlp.v2.IListInspectTemplatesResponse + | null + | undefined, + protos.google.privacy.dlp.v2.IInspectTemplate + >, + ): void; listInspectTemplates( - request: protos.google.privacy.dlp.v2.IListInspectTemplatesRequest, - callback: PaginationCallback< - protos.google.privacy.dlp.v2.IListInspectTemplatesRequest, - protos.google.privacy.dlp.v2.IListInspectTemplatesResponse|null|undefined, - protos.google.privacy.dlp.v2.IInspectTemplate>): void; + request: protos.google.privacy.dlp.v2.IListInspectTemplatesRequest, + callback: PaginationCallback< + protos.google.privacy.dlp.v2.IListInspectTemplatesRequest, + | protos.google.privacy.dlp.v2.IListInspectTemplatesResponse + | null + | undefined, + protos.google.privacy.dlp.v2.IInspectTemplate + >, + ): void; listInspectTemplates( - request?: protos.google.privacy.dlp.v2.IListInspectTemplatesRequest, - optionsOrCallback?: CallOptions|PaginationCallback< - protos.google.privacy.dlp.v2.IListInspectTemplatesRequest, - protos.google.privacy.dlp.v2.IListInspectTemplatesResponse|null|undefined, - protos.google.privacy.dlp.v2.IInspectTemplate>, - callback?: PaginationCallback< + request?: protos.google.privacy.dlp.v2.IListInspectTemplatesRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.privacy.dlp.v2.IListInspectTemplatesRequest, - protos.google.privacy.dlp.v2.IListInspectTemplatesResponse|null|undefined, - protos.google.privacy.dlp.v2.IInspectTemplate>): - Promise<[ - protos.google.privacy.dlp.v2.IInspectTemplate[], - protos.google.privacy.dlp.v2.IListInspectTemplatesRequest|null, - protos.google.privacy.dlp.v2.IListInspectTemplatesResponse - ]>|void { + | protos.google.privacy.dlp.v2.IListInspectTemplatesResponse + | null + | undefined, + protos.google.privacy.dlp.v2.IInspectTemplate + >, + callback?: PaginationCallback< + protos.google.privacy.dlp.v2.IListInspectTemplatesRequest, + | protos.google.privacy.dlp.v2.IListInspectTemplatesResponse + | null + | undefined, + protos.google.privacy.dlp.v2.IInspectTemplate + >, + ): Promise< + [ + protos.google.privacy.dlp.v2.IInspectTemplate[], + protos.google.privacy.dlp.v2.IListInspectTemplatesRequest | null, + protos.google.privacy.dlp.v2.IListInspectTemplatesResponse, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - 'location_id': request.locationId?.toString() ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + location_id: request.locationId?.toString() ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.privacy.dlp.v2.IListInspectTemplatesRequest, - protos.google.privacy.dlp.v2.IListInspectTemplatesResponse|null|undefined, - protos.google.privacy.dlp.v2.IInspectTemplate>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.privacy.dlp.v2.IListInspectTemplatesRequest, + | protos.google.privacy.dlp.v2.IListInspectTemplatesResponse + | null + | undefined, + protos.google.privacy.dlp.v2.IInspectTemplate + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listInspectTemplates values %j', values); callback!(error, values, nextPageRequest, rawResponse); @@ -3192,254 +4284,283 @@ export class DlpServiceClient { this._log.info('listInspectTemplates request %j', request); return this.innerApiCalls .listInspectTemplates(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.privacy.dlp.v2.IInspectTemplate[], - protos.google.privacy.dlp.v2.IListInspectTemplatesRequest|null, - protos.google.privacy.dlp.v2.IListInspectTemplatesResponse - ]) => { - this._log.info('listInspectTemplates values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.privacy.dlp.v2.IInspectTemplate[], + protos.google.privacy.dlp.v2.IListInspectTemplatesRequest | null, + protos.google.privacy.dlp.v2.IListInspectTemplatesResponse, + ]) => { + this._log.info('listInspectTemplates values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listInspectTemplates`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent resource name, for example projects/my-project-id or - * organizations/my-org-id. - * @param {string} request.pageToken - * Page token to continue retrieval. Comes from previous call - * to `ListInspectTemplates`. - * @param {number} request.pageSize - * Size of the page, can be limited by server. If zero server returns - * a page of max size 100. - * @param {string} request.orderBy - * Comma separated list of fields to order by, - * followed by `asc` or `desc` postfix. This list is case-insensitive, - * default sorting order is ascending, redundant space characters are - * insignificant. - * - * Example: `name asc,update_time, create_time desc` - * - * Supported fields are: - * - * - `create_time`: corresponds to time the template was created. - * - `update_time`: corresponds to time the template was last updated. - * - `name`: corresponds to template's name. - * - `display_name`: corresponds to template's display name. - * @param {string} request.locationId - * The geographic location where inspection templates will be retrieved from. - * Use `-` for all locations. Reserved for future extensions. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.privacy.dlp.v2.InspectTemplate|InspectTemplate} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `listInspectTemplatesAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `listInspectTemplates`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource name, for example projects/my-project-id or + * organizations/my-org-id. + * @param {string} request.pageToken + * Page token to continue retrieval. Comes from previous call + * to `ListInspectTemplates`. + * @param {number} request.pageSize + * Size of the page, can be limited by server. If zero server returns + * a page of max size 100. + * @param {string} request.orderBy + * Comma separated list of fields to order by, + * followed by `asc` or `desc` postfix. This list is case-insensitive, + * default sorting order is ascending, redundant space characters are + * insignificant. + * + * Example: `name asc,update_time, create_time desc` + * + * Supported fields are: + * + * - `create_time`: corresponds to time the template was created. + * - `update_time`: corresponds to time the template was last updated. + * - `name`: corresponds to template's name. + * - `display_name`: corresponds to template's display name. + * @param {string} request.locationId + * The geographic location where inspection templates will be retrieved from. + * Use `-` for all locations. Reserved for future extensions. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.privacy.dlp.v2.InspectTemplate|InspectTemplate} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listInspectTemplatesAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listInspectTemplatesStream( - request?: protos.google.privacy.dlp.v2.IListInspectTemplatesRequest, - options?: CallOptions): - Transform{ + request?: protos.google.privacy.dlp.v2.IListInspectTemplatesRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - 'location_id': request.locationId?.toString() ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + location_id: request.locationId?.toString() ?? '', + }); const defaultCallSettings = this._defaults['listInspectTemplates']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listInspectTemplates stream %j', request); return this.descriptors.page.listInspectTemplates.createStream( this.innerApiCalls.listInspectTemplates as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listInspectTemplates`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent resource name, for example projects/my-project-id or - * organizations/my-org-id. - * @param {string} request.pageToken - * Page token to continue retrieval. Comes from previous call - * to `ListInspectTemplates`. - * @param {number} request.pageSize - * Size of the page, can be limited by server. If zero server returns - * a page of max size 100. - * @param {string} request.orderBy - * Comma separated list of fields to order by, - * followed by `asc` or `desc` postfix. This list is case-insensitive, - * default sorting order is ascending, redundant space characters are - * insignificant. - * - * Example: `name asc,update_time, create_time desc` - * - * Supported fields are: - * - * - `create_time`: corresponds to time the template was created. - * - `update_time`: corresponds to time the template was last updated. - * - `name`: corresponds to template's name. - * - `display_name`: corresponds to template's display name. - * @param {string} request.locationId - * The geographic location where inspection templates will be retrieved from. - * Use `-` for all locations. Reserved for future extensions. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.privacy.dlp.v2.InspectTemplate|InspectTemplate}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v2/dlp_service.list_inspect_templates.js - * region_tag:dlp_v2_generated_DlpService_ListInspectTemplates_async - */ + /** + * Equivalent to `listInspectTemplates`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource name, for example projects/my-project-id or + * organizations/my-org-id. + * @param {string} request.pageToken + * Page token to continue retrieval. Comes from previous call + * to `ListInspectTemplates`. + * @param {number} request.pageSize + * Size of the page, can be limited by server. If zero server returns + * a page of max size 100. + * @param {string} request.orderBy + * Comma separated list of fields to order by, + * followed by `asc` or `desc` postfix. This list is case-insensitive, + * default sorting order is ascending, redundant space characters are + * insignificant. + * + * Example: `name asc,update_time, create_time desc` + * + * Supported fields are: + * + * - `create_time`: corresponds to time the template was created. + * - `update_time`: corresponds to time the template was last updated. + * - `name`: corresponds to template's name. + * - `display_name`: corresponds to template's display name. + * @param {string} request.locationId + * The geographic location where inspection templates will be retrieved from. + * Use `-` for all locations. Reserved for future extensions. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.privacy.dlp.v2.InspectTemplate|InspectTemplate}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v2/dlp_service.list_inspect_templates.js + * region_tag:dlp_v2_generated_DlpService_ListInspectTemplates_async + */ listInspectTemplatesAsync( - request?: protos.google.privacy.dlp.v2.IListInspectTemplatesRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.privacy.dlp.v2.IListInspectTemplatesRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - 'location_id': request.locationId?.toString() ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + location_id: request.locationId?.toString() ?? '', + }); const defaultCallSettings = this._defaults['listInspectTemplates']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listInspectTemplates iterate %j', request); return this.descriptors.page.listInspectTemplates.asyncIterate( this.innerApiCalls['listInspectTemplates'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } - /** - * Lists DeidentifyTemplates. - * See https://cloud.google.com/dlp/docs/creating-templates-deid to learn - * more. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent resource name, for example projects/my-project-id or - * organizations/my-org-id. - * @param {string} request.pageToken - * Page token to continue retrieval. Comes from previous call - * to `ListDeidentifyTemplates`. - * @param {number} request.pageSize - * Size of the page, can be limited by server. If zero server returns - * a page of max size 100. - * @param {string} request.orderBy - * Comma separated list of fields to order by, - * followed by `asc` or `desc` postfix. This list is case-insensitive, - * default sorting order is ascending, redundant space characters are - * insignificant. - * - * Example: `name asc,update_time, create_time desc` - * - * Supported fields are: - * - * - `create_time`: corresponds to time the template was created. - * - `update_time`: corresponds to time the template was last updated. - * - `name`: corresponds to template's name. - * - `display_name`: corresponds to template's display name. - * @param {string} request.locationId - * The geographic location where deidentifications templates will be retrieved - * from. Use `-` for all locations. Reserved for future extensions. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.privacy.dlp.v2.DeidentifyTemplate|DeidentifyTemplate}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `listDeidentifyTemplatesAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Lists DeidentifyTemplates. + * See https://cloud.google.com/dlp/docs/creating-templates-deid to learn + * more. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource name, for example projects/my-project-id or + * organizations/my-org-id. + * @param {string} request.pageToken + * Page token to continue retrieval. Comes from previous call + * to `ListDeidentifyTemplates`. + * @param {number} request.pageSize + * Size of the page, can be limited by server. If zero server returns + * a page of max size 100. + * @param {string} request.orderBy + * Comma separated list of fields to order by, + * followed by `asc` or `desc` postfix. This list is case-insensitive, + * default sorting order is ascending, redundant space characters are + * insignificant. + * + * Example: `name asc,update_time, create_time desc` + * + * Supported fields are: + * + * - `create_time`: corresponds to time the template was created. + * - `update_time`: corresponds to time the template was last updated. + * - `name`: corresponds to template's name. + * - `display_name`: corresponds to template's display name. + * @param {string} request.locationId + * The geographic location where deidentifications templates will be retrieved + * from. Use `-` for all locations. Reserved for future extensions. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.privacy.dlp.v2.DeidentifyTemplate|DeidentifyTemplate}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listDeidentifyTemplatesAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listDeidentifyTemplates( - request?: protos.google.privacy.dlp.v2.IListDeidentifyTemplatesRequest, - options?: CallOptions): - Promise<[ - protos.google.privacy.dlp.v2.IDeidentifyTemplate[], - protos.google.privacy.dlp.v2.IListDeidentifyTemplatesRequest|null, - protos.google.privacy.dlp.v2.IListDeidentifyTemplatesResponse - ]>; + request?: protos.google.privacy.dlp.v2.IListDeidentifyTemplatesRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.privacy.dlp.v2.IDeidentifyTemplate[], + protos.google.privacy.dlp.v2.IListDeidentifyTemplatesRequest | null, + protos.google.privacy.dlp.v2.IListDeidentifyTemplatesResponse, + ] + >; listDeidentifyTemplates( - request: protos.google.privacy.dlp.v2.IListDeidentifyTemplatesRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.privacy.dlp.v2.IListDeidentifyTemplatesRequest, - protos.google.privacy.dlp.v2.IListDeidentifyTemplatesResponse|null|undefined, - protos.google.privacy.dlp.v2.IDeidentifyTemplate>): void; + request: protos.google.privacy.dlp.v2.IListDeidentifyTemplatesRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.privacy.dlp.v2.IListDeidentifyTemplatesRequest, + | protos.google.privacy.dlp.v2.IListDeidentifyTemplatesResponse + | null + | undefined, + protos.google.privacy.dlp.v2.IDeidentifyTemplate + >, + ): void; listDeidentifyTemplates( - request: protos.google.privacy.dlp.v2.IListDeidentifyTemplatesRequest, - callback: PaginationCallback< - protos.google.privacy.dlp.v2.IListDeidentifyTemplatesRequest, - protos.google.privacy.dlp.v2.IListDeidentifyTemplatesResponse|null|undefined, - protos.google.privacy.dlp.v2.IDeidentifyTemplate>): void; + request: protos.google.privacy.dlp.v2.IListDeidentifyTemplatesRequest, + callback: PaginationCallback< + protos.google.privacy.dlp.v2.IListDeidentifyTemplatesRequest, + | protos.google.privacy.dlp.v2.IListDeidentifyTemplatesResponse + | null + | undefined, + protos.google.privacy.dlp.v2.IDeidentifyTemplate + >, + ): void; listDeidentifyTemplates( - request?: protos.google.privacy.dlp.v2.IListDeidentifyTemplatesRequest, - optionsOrCallback?: CallOptions|PaginationCallback< + request?: protos.google.privacy.dlp.v2.IListDeidentifyTemplatesRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.privacy.dlp.v2.IListDeidentifyTemplatesRequest, - protos.google.privacy.dlp.v2.IListDeidentifyTemplatesResponse|null|undefined, - protos.google.privacy.dlp.v2.IDeidentifyTemplate>, - callback?: PaginationCallback< - protos.google.privacy.dlp.v2.IListDeidentifyTemplatesRequest, - protos.google.privacy.dlp.v2.IListDeidentifyTemplatesResponse|null|undefined, - protos.google.privacy.dlp.v2.IDeidentifyTemplate>): - Promise<[ - protos.google.privacy.dlp.v2.IDeidentifyTemplate[], - protos.google.privacy.dlp.v2.IListDeidentifyTemplatesRequest|null, - protos.google.privacy.dlp.v2.IListDeidentifyTemplatesResponse - ]>|void { + | protos.google.privacy.dlp.v2.IListDeidentifyTemplatesResponse + | null + | undefined, + protos.google.privacy.dlp.v2.IDeidentifyTemplate + >, + callback?: PaginationCallback< + protos.google.privacy.dlp.v2.IListDeidentifyTemplatesRequest, + | protos.google.privacy.dlp.v2.IListDeidentifyTemplatesResponse + | null + | undefined, + protos.google.privacy.dlp.v2.IDeidentifyTemplate + >, + ): Promise< + [ + protos.google.privacy.dlp.v2.IDeidentifyTemplate[], + protos.google.privacy.dlp.v2.IListDeidentifyTemplatesRequest | null, + protos.google.privacy.dlp.v2.IListDeidentifyTemplatesResponse, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - 'location_id': request.locationId?.toString() ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + location_id: request.locationId?.toString() ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.privacy.dlp.v2.IListDeidentifyTemplatesRequest, - protos.google.privacy.dlp.v2.IListDeidentifyTemplatesResponse|null|undefined, - protos.google.privacy.dlp.v2.IDeidentifyTemplate>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.privacy.dlp.v2.IListDeidentifyTemplatesRequest, + | protos.google.privacy.dlp.v2.IListDeidentifyTemplatesResponse + | null + | undefined, + protos.google.privacy.dlp.v2.IDeidentifyTemplate + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listDeidentifyTemplates values %j', values); callback!(error, values, nextPageRequest, rawResponse); @@ -3448,279 +4569,302 @@ export class DlpServiceClient { this._log.info('listDeidentifyTemplates request %j', request); return this.innerApiCalls .listDeidentifyTemplates(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.privacy.dlp.v2.IDeidentifyTemplate[], - protos.google.privacy.dlp.v2.IListDeidentifyTemplatesRequest|null, - protos.google.privacy.dlp.v2.IListDeidentifyTemplatesResponse - ]) => { - this._log.info('listDeidentifyTemplates values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.privacy.dlp.v2.IDeidentifyTemplate[], + protos.google.privacy.dlp.v2.IListDeidentifyTemplatesRequest | null, + protos.google.privacy.dlp.v2.IListDeidentifyTemplatesResponse, + ]) => { + this._log.info('listDeidentifyTemplates values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listDeidentifyTemplates`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent resource name, for example projects/my-project-id or - * organizations/my-org-id. - * @param {string} request.pageToken - * Page token to continue retrieval. Comes from previous call - * to `ListDeidentifyTemplates`. - * @param {number} request.pageSize - * Size of the page, can be limited by server. If zero server returns - * a page of max size 100. - * @param {string} request.orderBy - * Comma separated list of fields to order by, - * followed by `asc` or `desc` postfix. This list is case-insensitive, - * default sorting order is ascending, redundant space characters are - * insignificant. - * - * Example: `name asc,update_time, create_time desc` - * - * Supported fields are: - * - * - `create_time`: corresponds to time the template was created. - * - `update_time`: corresponds to time the template was last updated. - * - `name`: corresponds to template's name. - * - `display_name`: corresponds to template's display name. - * @param {string} request.locationId - * The geographic location where deidentifications templates will be retrieved - * from. Use `-` for all locations. Reserved for future extensions. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.privacy.dlp.v2.DeidentifyTemplate|DeidentifyTemplate} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `listDeidentifyTemplatesAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `listDeidentifyTemplates`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource name, for example projects/my-project-id or + * organizations/my-org-id. + * @param {string} request.pageToken + * Page token to continue retrieval. Comes from previous call + * to `ListDeidentifyTemplates`. + * @param {number} request.pageSize + * Size of the page, can be limited by server. If zero server returns + * a page of max size 100. + * @param {string} request.orderBy + * Comma separated list of fields to order by, + * followed by `asc` or `desc` postfix. This list is case-insensitive, + * default sorting order is ascending, redundant space characters are + * insignificant. + * + * Example: `name asc,update_time, create_time desc` + * + * Supported fields are: + * + * - `create_time`: corresponds to time the template was created. + * - `update_time`: corresponds to time the template was last updated. + * - `name`: corresponds to template's name. + * - `display_name`: corresponds to template's display name. + * @param {string} request.locationId + * The geographic location where deidentifications templates will be retrieved + * from. Use `-` for all locations. Reserved for future extensions. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.privacy.dlp.v2.DeidentifyTemplate|DeidentifyTemplate} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listDeidentifyTemplatesAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listDeidentifyTemplatesStream( - request?: protos.google.privacy.dlp.v2.IListDeidentifyTemplatesRequest, - options?: CallOptions): - Transform{ + request?: protos.google.privacy.dlp.v2.IListDeidentifyTemplatesRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - 'location_id': request.locationId?.toString() ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + location_id: request.locationId?.toString() ?? '', + }); const defaultCallSettings = this._defaults['listDeidentifyTemplates']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listDeidentifyTemplates stream %j', request); return this.descriptors.page.listDeidentifyTemplates.createStream( this.innerApiCalls.listDeidentifyTemplates as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listDeidentifyTemplates`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent resource name, for example projects/my-project-id or - * organizations/my-org-id. - * @param {string} request.pageToken - * Page token to continue retrieval. Comes from previous call - * to `ListDeidentifyTemplates`. - * @param {number} request.pageSize - * Size of the page, can be limited by server. If zero server returns - * a page of max size 100. - * @param {string} request.orderBy - * Comma separated list of fields to order by, - * followed by `asc` or `desc` postfix. This list is case-insensitive, - * default sorting order is ascending, redundant space characters are - * insignificant. - * - * Example: `name asc,update_time, create_time desc` - * - * Supported fields are: - * - * - `create_time`: corresponds to time the template was created. - * - `update_time`: corresponds to time the template was last updated. - * - `name`: corresponds to template's name. - * - `display_name`: corresponds to template's display name. - * @param {string} request.locationId - * The geographic location where deidentifications templates will be retrieved - * from. Use `-` for all locations. Reserved for future extensions. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.privacy.dlp.v2.DeidentifyTemplate|DeidentifyTemplate}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v2/dlp_service.list_deidentify_templates.js - * region_tag:dlp_v2_generated_DlpService_ListDeidentifyTemplates_async - */ + /** + * Equivalent to `listDeidentifyTemplates`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource name, for example projects/my-project-id or + * organizations/my-org-id. + * @param {string} request.pageToken + * Page token to continue retrieval. Comes from previous call + * to `ListDeidentifyTemplates`. + * @param {number} request.pageSize + * Size of the page, can be limited by server. If zero server returns + * a page of max size 100. + * @param {string} request.orderBy + * Comma separated list of fields to order by, + * followed by `asc` or `desc` postfix. This list is case-insensitive, + * default sorting order is ascending, redundant space characters are + * insignificant. + * + * Example: `name asc,update_time, create_time desc` + * + * Supported fields are: + * + * - `create_time`: corresponds to time the template was created. + * - `update_time`: corresponds to time the template was last updated. + * - `name`: corresponds to template's name. + * - `display_name`: corresponds to template's display name. + * @param {string} request.locationId + * The geographic location where deidentifications templates will be retrieved + * from. Use `-` for all locations. Reserved for future extensions. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.privacy.dlp.v2.DeidentifyTemplate|DeidentifyTemplate}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v2/dlp_service.list_deidentify_templates.js + * region_tag:dlp_v2_generated_DlpService_ListDeidentifyTemplates_async + */ listDeidentifyTemplatesAsync( - request?: protos.google.privacy.dlp.v2.IListDeidentifyTemplatesRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.privacy.dlp.v2.IListDeidentifyTemplatesRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - 'location_id': request.locationId?.toString() ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + location_id: request.locationId?.toString() ?? '', + }); const defaultCallSettings = this._defaults['listDeidentifyTemplates']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listDeidentifyTemplates iterate %j', request); return this.descriptors.page.listDeidentifyTemplates.asyncIterate( this.innerApiCalls['listDeidentifyTemplates'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } - /** - * Lists job triggers. - * See https://cloud.google.com/dlp/docs/creating-job-triggers to learn more. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent resource name, for example `projects/my-project-id`. - * @param {string} request.pageToken - * Page token to continue retrieval. Comes from previous call - * to ListJobTriggers. `order_by` field must not - * change for subsequent calls. - * @param {number} request.pageSize - * Size of the page, can be limited by a server. - * @param {string} request.orderBy - * Comma separated list of triggeredJob fields to order by, - * followed by `asc` or `desc` postfix. This list is case-insensitive, - * default sorting order is ascending, redundant space characters are - * insignificant. - * - * Example: `name asc,update_time, create_time desc` - * - * Supported fields are: - * - * - `create_time`: corresponds to time the JobTrigger was created. - * - `update_time`: corresponds to time the JobTrigger was last updated. - * - `last_run_time`: corresponds to the last time the JobTrigger ran. - * - `name`: corresponds to JobTrigger's name. - * - `display_name`: corresponds to JobTrigger's display name. - * - `status`: corresponds to JobTrigger's status. - * @param {string} request.filter - * Allows filtering. - * - * Supported syntax: - * - * * Filter expressions are made up of one or more restrictions. - * * Restrictions can be combined by `AND` or `OR` logical operators. A - * sequence of restrictions implicitly uses `AND`. - * * A restriction has the form of `{field} {operator} {value}`. - * * Supported fields/values for inspect jobs: - * - `status` - HEALTHY|PAUSED|CANCELLED - * - `inspected_storage` - DATASTORE|CLOUD_STORAGE|BIGQUERY - * - 'last_run_time` - RFC 3339 formatted timestamp, surrounded by - * quotation marks. Nanoseconds are ignored. - * - 'error_count' - Number of errors that have occurred while running. - * * The operator must be `=` or `!=` for status and inspected_storage. - * - * Examples: - * - * * inspected_storage = cloud_storage AND status = HEALTHY - * * inspected_storage = cloud_storage OR inspected_storage = bigquery - * * inspected_storage = cloud_storage AND (state = PAUSED OR state = HEALTHY) - * * last_run_time > \"2017-12-12T00:00:00+00:00\" - * - * The length of this field should be no more than 500 characters. - * @param {string} request.locationId - * The geographic location where job triggers will be retrieved from. - * Use `-` for all locations. Reserved for future extensions. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.privacy.dlp.v2.JobTrigger|JobTrigger}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `listJobTriggersAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Lists job triggers. + * See https://cloud.google.com/dlp/docs/creating-job-triggers to learn more. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource name, for example `projects/my-project-id`. + * @param {string} request.pageToken + * Page token to continue retrieval. Comes from previous call + * to ListJobTriggers. `order_by` field must not + * change for subsequent calls. + * @param {number} request.pageSize + * Size of the page, can be limited by a server. + * @param {string} request.orderBy + * Comma separated list of triggeredJob fields to order by, + * followed by `asc` or `desc` postfix. This list is case-insensitive, + * default sorting order is ascending, redundant space characters are + * insignificant. + * + * Example: `name asc,update_time, create_time desc` + * + * Supported fields are: + * + * - `create_time`: corresponds to time the JobTrigger was created. + * - `update_time`: corresponds to time the JobTrigger was last updated. + * - `last_run_time`: corresponds to the last time the JobTrigger ran. + * - `name`: corresponds to JobTrigger's name. + * - `display_name`: corresponds to JobTrigger's display name. + * - `status`: corresponds to JobTrigger's status. + * @param {string} request.filter + * Allows filtering. + * + * Supported syntax: + * + * * Filter expressions are made up of one or more restrictions. + * * Restrictions can be combined by `AND` or `OR` logical operators. A + * sequence of restrictions implicitly uses `AND`. + * * A restriction has the form of `{field} {operator} {value}`. + * * Supported fields/values for inspect jobs: + * - `status` - HEALTHY|PAUSED|CANCELLED + * - `inspected_storage` - DATASTORE|CLOUD_STORAGE|BIGQUERY + * - 'last_run_time` - RFC 3339 formatted timestamp, surrounded by + * quotation marks. Nanoseconds are ignored. + * - 'error_count' - Number of errors that have occurred while running. + * * The operator must be `=` or `!=` for status and inspected_storage. + * + * Examples: + * + * * inspected_storage = cloud_storage AND status = HEALTHY + * * inspected_storage = cloud_storage OR inspected_storage = bigquery + * * inspected_storage = cloud_storage AND (state = PAUSED OR state = HEALTHY) + * * last_run_time > \"2017-12-12T00:00:00+00:00\" + * + * The length of this field should be no more than 500 characters. + * @param {string} request.locationId + * The geographic location where job triggers will be retrieved from. + * Use `-` for all locations. Reserved for future extensions. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.privacy.dlp.v2.JobTrigger|JobTrigger}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listJobTriggersAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listJobTriggers( - request?: protos.google.privacy.dlp.v2.IListJobTriggersRequest, - options?: CallOptions): - Promise<[ - protos.google.privacy.dlp.v2.IJobTrigger[], - protos.google.privacy.dlp.v2.IListJobTriggersRequest|null, - protos.google.privacy.dlp.v2.IListJobTriggersResponse - ]>; + request?: protos.google.privacy.dlp.v2.IListJobTriggersRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.privacy.dlp.v2.IJobTrigger[], + protos.google.privacy.dlp.v2.IListJobTriggersRequest | null, + protos.google.privacy.dlp.v2.IListJobTriggersResponse, + ] + >; listJobTriggers( - request: protos.google.privacy.dlp.v2.IListJobTriggersRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.privacy.dlp.v2.IListJobTriggersRequest, - protos.google.privacy.dlp.v2.IListJobTriggersResponse|null|undefined, - protos.google.privacy.dlp.v2.IJobTrigger>): void; + request: protos.google.privacy.dlp.v2.IListJobTriggersRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.privacy.dlp.v2.IListJobTriggersRequest, + protos.google.privacy.dlp.v2.IListJobTriggersResponse | null | undefined, + protos.google.privacy.dlp.v2.IJobTrigger + >, + ): void; listJobTriggers( - request: protos.google.privacy.dlp.v2.IListJobTriggersRequest, - callback: PaginationCallback< - protos.google.privacy.dlp.v2.IListJobTriggersRequest, - protos.google.privacy.dlp.v2.IListJobTriggersResponse|null|undefined, - protos.google.privacy.dlp.v2.IJobTrigger>): void; + request: protos.google.privacy.dlp.v2.IListJobTriggersRequest, + callback: PaginationCallback< + protos.google.privacy.dlp.v2.IListJobTriggersRequest, + protos.google.privacy.dlp.v2.IListJobTriggersResponse | null | undefined, + protos.google.privacy.dlp.v2.IJobTrigger + >, + ): void; listJobTriggers( - request?: protos.google.privacy.dlp.v2.IListJobTriggersRequest, - optionsOrCallback?: CallOptions|PaginationCallback< + request?: protos.google.privacy.dlp.v2.IListJobTriggersRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.privacy.dlp.v2.IListJobTriggersRequest, - protos.google.privacy.dlp.v2.IListJobTriggersResponse|null|undefined, - protos.google.privacy.dlp.v2.IJobTrigger>, - callback?: PaginationCallback< - protos.google.privacy.dlp.v2.IListJobTriggersRequest, - protos.google.privacy.dlp.v2.IListJobTriggersResponse|null|undefined, - protos.google.privacy.dlp.v2.IJobTrigger>): - Promise<[ - protos.google.privacy.dlp.v2.IJobTrigger[], - protos.google.privacy.dlp.v2.IListJobTriggersRequest|null, - protos.google.privacy.dlp.v2.IListJobTriggersResponse - ]>|void { + | protos.google.privacy.dlp.v2.IListJobTriggersResponse + | null + | undefined, + protos.google.privacy.dlp.v2.IJobTrigger + >, + callback?: PaginationCallback< + protos.google.privacy.dlp.v2.IListJobTriggersRequest, + protos.google.privacy.dlp.v2.IListJobTriggersResponse | null | undefined, + protos.google.privacy.dlp.v2.IJobTrigger + >, + ): Promise< + [ + protos.google.privacy.dlp.v2.IJobTrigger[], + protos.google.privacy.dlp.v2.IListJobTriggersRequest | null, + protos.google.privacy.dlp.v2.IListJobTriggersResponse, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - 'location_id': request.locationId?.toString() ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + location_id: request.locationId?.toString() ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.privacy.dlp.v2.IListJobTriggersRequest, - protos.google.privacy.dlp.v2.IListJobTriggersResponse|null|undefined, - protos.google.privacy.dlp.v2.IJobTrigger>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.privacy.dlp.v2.IListJobTriggersRequest, + | protos.google.privacy.dlp.v2.IListJobTriggersResponse + | null + | undefined, + protos.google.privacy.dlp.v2.IJobTrigger + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listJobTriggers values %j', values); callback!(error, values, nextPageRequest, rawResponse); @@ -3729,334 +4873,353 @@ export class DlpServiceClient { this._log.info('listJobTriggers request %j', request); return this.innerApiCalls .listJobTriggers(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.privacy.dlp.v2.IJobTrigger[], - protos.google.privacy.dlp.v2.IListJobTriggersRequest|null, - protos.google.privacy.dlp.v2.IListJobTriggersResponse - ]) => { - this._log.info('listJobTriggers values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.privacy.dlp.v2.IJobTrigger[], + protos.google.privacy.dlp.v2.IListJobTriggersRequest | null, + protos.google.privacy.dlp.v2.IListJobTriggersResponse, + ]) => { + this._log.info('listJobTriggers values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listJobTriggers`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent resource name, for example `projects/my-project-id`. - * @param {string} request.pageToken - * Page token to continue retrieval. Comes from previous call - * to ListJobTriggers. `order_by` field must not - * change for subsequent calls. - * @param {number} request.pageSize - * Size of the page, can be limited by a server. - * @param {string} request.orderBy - * Comma separated list of triggeredJob fields to order by, - * followed by `asc` or `desc` postfix. This list is case-insensitive, - * default sorting order is ascending, redundant space characters are - * insignificant. - * - * Example: `name asc,update_time, create_time desc` - * - * Supported fields are: - * - * - `create_time`: corresponds to time the JobTrigger was created. - * - `update_time`: corresponds to time the JobTrigger was last updated. - * - `last_run_time`: corresponds to the last time the JobTrigger ran. - * - `name`: corresponds to JobTrigger's name. - * - `display_name`: corresponds to JobTrigger's display name. - * - `status`: corresponds to JobTrigger's status. - * @param {string} request.filter - * Allows filtering. - * - * Supported syntax: - * - * * Filter expressions are made up of one or more restrictions. - * * Restrictions can be combined by `AND` or `OR` logical operators. A - * sequence of restrictions implicitly uses `AND`. - * * A restriction has the form of `{field} {operator} {value}`. - * * Supported fields/values for inspect jobs: - * - `status` - HEALTHY|PAUSED|CANCELLED - * - `inspected_storage` - DATASTORE|CLOUD_STORAGE|BIGQUERY - * - 'last_run_time` - RFC 3339 formatted timestamp, surrounded by - * quotation marks. Nanoseconds are ignored. - * - 'error_count' - Number of errors that have occurred while running. - * * The operator must be `=` or `!=` for status and inspected_storage. - * - * Examples: - * - * * inspected_storage = cloud_storage AND status = HEALTHY - * * inspected_storage = cloud_storage OR inspected_storage = bigquery - * * inspected_storage = cloud_storage AND (state = PAUSED OR state = HEALTHY) - * * last_run_time > \"2017-12-12T00:00:00+00:00\" - * - * The length of this field should be no more than 500 characters. - * @param {string} request.locationId - * The geographic location where job triggers will be retrieved from. - * Use `-` for all locations. Reserved for future extensions. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.privacy.dlp.v2.JobTrigger|JobTrigger} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `listJobTriggersAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `listJobTriggers`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource name, for example `projects/my-project-id`. + * @param {string} request.pageToken + * Page token to continue retrieval. Comes from previous call + * to ListJobTriggers. `order_by` field must not + * change for subsequent calls. + * @param {number} request.pageSize + * Size of the page, can be limited by a server. + * @param {string} request.orderBy + * Comma separated list of triggeredJob fields to order by, + * followed by `asc` or `desc` postfix. This list is case-insensitive, + * default sorting order is ascending, redundant space characters are + * insignificant. + * + * Example: `name asc,update_time, create_time desc` + * + * Supported fields are: + * + * - `create_time`: corresponds to time the JobTrigger was created. + * - `update_time`: corresponds to time the JobTrigger was last updated. + * - `last_run_time`: corresponds to the last time the JobTrigger ran. + * - `name`: corresponds to JobTrigger's name. + * - `display_name`: corresponds to JobTrigger's display name. + * - `status`: corresponds to JobTrigger's status. + * @param {string} request.filter + * Allows filtering. + * + * Supported syntax: + * + * * Filter expressions are made up of one or more restrictions. + * * Restrictions can be combined by `AND` or `OR` logical operators. A + * sequence of restrictions implicitly uses `AND`. + * * A restriction has the form of `{field} {operator} {value}`. + * * Supported fields/values for inspect jobs: + * - `status` - HEALTHY|PAUSED|CANCELLED + * - `inspected_storage` - DATASTORE|CLOUD_STORAGE|BIGQUERY + * - 'last_run_time` - RFC 3339 formatted timestamp, surrounded by + * quotation marks. Nanoseconds are ignored. + * - 'error_count' - Number of errors that have occurred while running. + * * The operator must be `=` or `!=` for status and inspected_storage. + * + * Examples: + * + * * inspected_storage = cloud_storage AND status = HEALTHY + * * inspected_storage = cloud_storage OR inspected_storage = bigquery + * * inspected_storage = cloud_storage AND (state = PAUSED OR state = HEALTHY) + * * last_run_time > \"2017-12-12T00:00:00+00:00\" + * + * The length of this field should be no more than 500 characters. + * @param {string} request.locationId + * The geographic location where job triggers will be retrieved from. + * Use `-` for all locations. Reserved for future extensions. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.privacy.dlp.v2.JobTrigger|JobTrigger} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listJobTriggersAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listJobTriggersStream( - request?: protos.google.privacy.dlp.v2.IListJobTriggersRequest, - options?: CallOptions): - Transform{ + request?: protos.google.privacy.dlp.v2.IListJobTriggersRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - 'location_id': request.locationId?.toString() ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + location_id: request.locationId?.toString() ?? '', + }); const defaultCallSettings = this._defaults['listJobTriggers']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listJobTriggers stream %j', request); return this.descriptors.page.listJobTriggers.createStream( this.innerApiCalls.listJobTriggers as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listJobTriggers`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent resource name, for example `projects/my-project-id`. - * @param {string} request.pageToken - * Page token to continue retrieval. Comes from previous call - * to ListJobTriggers. `order_by` field must not - * change for subsequent calls. - * @param {number} request.pageSize - * Size of the page, can be limited by a server. - * @param {string} request.orderBy - * Comma separated list of triggeredJob fields to order by, - * followed by `asc` or `desc` postfix. This list is case-insensitive, - * default sorting order is ascending, redundant space characters are - * insignificant. - * - * Example: `name asc,update_time, create_time desc` - * - * Supported fields are: - * - * - `create_time`: corresponds to time the JobTrigger was created. - * - `update_time`: corresponds to time the JobTrigger was last updated. - * - `last_run_time`: corresponds to the last time the JobTrigger ran. - * - `name`: corresponds to JobTrigger's name. - * - `display_name`: corresponds to JobTrigger's display name. - * - `status`: corresponds to JobTrigger's status. - * @param {string} request.filter - * Allows filtering. - * - * Supported syntax: - * - * * Filter expressions are made up of one or more restrictions. - * * Restrictions can be combined by `AND` or `OR` logical operators. A - * sequence of restrictions implicitly uses `AND`. - * * A restriction has the form of `{field} {operator} {value}`. - * * Supported fields/values for inspect jobs: - * - `status` - HEALTHY|PAUSED|CANCELLED - * - `inspected_storage` - DATASTORE|CLOUD_STORAGE|BIGQUERY - * - 'last_run_time` - RFC 3339 formatted timestamp, surrounded by - * quotation marks. Nanoseconds are ignored. - * - 'error_count' - Number of errors that have occurred while running. - * * The operator must be `=` or `!=` for status and inspected_storage. - * - * Examples: - * - * * inspected_storage = cloud_storage AND status = HEALTHY - * * inspected_storage = cloud_storage OR inspected_storage = bigquery - * * inspected_storage = cloud_storage AND (state = PAUSED OR state = HEALTHY) - * * last_run_time > \"2017-12-12T00:00:00+00:00\" - * - * The length of this field should be no more than 500 characters. - * @param {string} request.locationId - * The geographic location where job triggers will be retrieved from. - * Use `-` for all locations. Reserved for future extensions. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.privacy.dlp.v2.JobTrigger|JobTrigger}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v2/dlp_service.list_job_triggers.js - * region_tag:dlp_v2_generated_DlpService_ListJobTriggers_async - */ + /** + * Equivalent to `listJobTriggers`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource name, for example `projects/my-project-id`. + * @param {string} request.pageToken + * Page token to continue retrieval. Comes from previous call + * to ListJobTriggers. `order_by` field must not + * change for subsequent calls. + * @param {number} request.pageSize + * Size of the page, can be limited by a server. + * @param {string} request.orderBy + * Comma separated list of triggeredJob fields to order by, + * followed by `asc` or `desc` postfix. This list is case-insensitive, + * default sorting order is ascending, redundant space characters are + * insignificant. + * + * Example: `name asc,update_time, create_time desc` + * + * Supported fields are: + * + * - `create_time`: corresponds to time the JobTrigger was created. + * - `update_time`: corresponds to time the JobTrigger was last updated. + * - `last_run_time`: corresponds to the last time the JobTrigger ran. + * - `name`: corresponds to JobTrigger's name. + * - `display_name`: corresponds to JobTrigger's display name. + * - `status`: corresponds to JobTrigger's status. + * @param {string} request.filter + * Allows filtering. + * + * Supported syntax: + * + * * Filter expressions are made up of one or more restrictions. + * * Restrictions can be combined by `AND` or `OR` logical operators. A + * sequence of restrictions implicitly uses `AND`. + * * A restriction has the form of `{field} {operator} {value}`. + * * Supported fields/values for inspect jobs: + * - `status` - HEALTHY|PAUSED|CANCELLED + * - `inspected_storage` - DATASTORE|CLOUD_STORAGE|BIGQUERY + * - 'last_run_time` - RFC 3339 formatted timestamp, surrounded by + * quotation marks. Nanoseconds are ignored. + * - 'error_count' - Number of errors that have occurred while running. + * * The operator must be `=` or `!=` for status and inspected_storage. + * + * Examples: + * + * * inspected_storage = cloud_storage AND status = HEALTHY + * * inspected_storage = cloud_storage OR inspected_storage = bigquery + * * inspected_storage = cloud_storage AND (state = PAUSED OR state = HEALTHY) + * * last_run_time > \"2017-12-12T00:00:00+00:00\" + * + * The length of this field should be no more than 500 characters. + * @param {string} request.locationId + * The geographic location where job triggers will be retrieved from. + * Use `-` for all locations. Reserved for future extensions. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.privacy.dlp.v2.JobTrigger|JobTrigger}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v2/dlp_service.list_job_triggers.js + * region_tag:dlp_v2_generated_DlpService_ListJobTriggers_async + */ listJobTriggersAsync( - request?: protos.google.privacy.dlp.v2.IListJobTriggersRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.privacy.dlp.v2.IListJobTriggersRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - 'location_id': request.locationId?.toString() ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + location_id: request.locationId?.toString() ?? '', + }); const defaultCallSettings = this._defaults['listJobTriggers']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listJobTriggers iterate %j', request); return this.descriptors.page.listJobTriggers.asyncIterate( this.innerApiCalls['listJobTriggers'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } - /** - * Lists DlpJobs that match the specified filter in the request. - * See https://cloud.google.com/dlp/docs/inspecting-storage and - * https://cloud.google.com/dlp/docs/compute-risk-analysis to learn more. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent resource name, for example projects/my-project-id. - * @param {string} request.filter - * Allows filtering. - * - * Supported syntax: - * - * * Filter expressions are made up of one or more restrictions. - * * Restrictions can be combined by `AND` or `OR` logical operators. A - * sequence of restrictions implicitly uses `AND`. - * * A restriction has the form of `{field} {operator} {value}`. - * * Supported fields/values for inspect jobs: - * - `state` - PENDING|RUNNING|CANCELED|FINISHED|FAILED - * - `inspected_storage` - DATASTORE|CLOUD_STORAGE|BIGQUERY - * - `trigger_name` - The resource name of the trigger that created job. - * - 'end_time` - Corresponds to time the job finished. - * - 'start_time` - Corresponds to time the job finished. - * * Supported fields for risk analysis jobs: - * - `state` - RUNNING|CANCELED|FINISHED|FAILED - * - 'end_time` - Corresponds to time the job finished. - * - 'start_time` - Corresponds to time the job finished. - * * The operator must be `=` or `!=`. - * - * Examples: - * - * * inspected_storage = cloud_storage AND state = done - * * inspected_storage = cloud_storage OR inspected_storage = bigquery - * * inspected_storage = cloud_storage AND (state = done OR state = canceled) - * * end_time > \"2017-12-12T00:00:00+00:00\" - * - * The length of this field should be no more than 500 characters. - * @param {number} request.pageSize - * The standard list page size. - * @param {string} request.pageToken - * The standard list page token. - * @param {google.privacy.dlp.v2.DlpJobType} request.type - * The type of job. Defaults to `DlpJobType.INSPECT` - * @param {string} request.orderBy - * Comma separated list of fields to order by, - * followed by `asc` or `desc` postfix. This list is case-insensitive, - * default sorting order is ascending, redundant space characters are - * insignificant. - * - * Example: `name asc, end_time asc, create_time desc` - * - * Supported fields are: - * - * - `create_time`: corresponds to time the job was created. - * - `end_time`: corresponds to time the job ended. - * - `name`: corresponds to job's name. - * - `state`: corresponds to `state` - * @param {string} request.locationId - * The geographic location where jobs will be retrieved from. - * Use `-` for all locations. Reserved for future extensions. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.privacy.dlp.v2.DlpJob|DlpJob}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `listDlpJobsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Lists DlpJobs that match the specified filter in the request. + * See https://cloud.google.com/dlp/docs/inspecting-storage and + * https://cloud.google.com/dlp/docs/compute-risk-analysis to learn more. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource name, for example projects/my-project-id. + * @param {string} request.filter + * Allows filtering. + * + * Supported syntax: + * + * * Filter expressions are made up of one or more restrictions. + * * Restrictions can be combined by `AND` or `OR` logical operators. A + * sequence of restrictions implicitly uses `AND`. + * * A restriction has the form of `{field} {operator} {value}`. + * * Supported fields/values for inspect jobs: + * - `state` - PENDING|RUNNING|CANCELED|FINISHED|FAILED + * - `inspected_storage` - DATASTORE|CLOUD_STORAGE|BIGQUERY + * - `trigger_name` - The resource name of the trigger that created job. + * - 'end_time` - Corresponds to time the job finished. + * - 'start_time` - Corresponds to time the job finished. + * * Supported fields for risk analysis jobs: + * - `state` - RUNNING|CANCELED|FINISHED|FAILED + * - 'end_time` - Corresponds to time the job finished. + * - 'start_time` - Corresponds to time the job finished. + * * The operator must be `=` or `!=`. + * + * Examples: + * + * * inspected_storage = cloud_storage AND state = done + * * inspected_storage = cloud_storage OR inspected_storage = bigquery + * * inspected_storage = cloud_storage AND (state = done OR state = canceled) + * * end_time > \"2017-12-12T00:00:00+00:00\" + * + * The length of this field should be no more than 500 characters. + * @param {number} request.pageSize + * The standard list page size. + * @param {string} request.pageToken + * The standard list page token. + * @param {google.privacy.dlp.v2.DlpJobType} request.type + * The type of job. Defaults to `DlpJobType.INSPECT` + * @param {string} request.orderBy + * Comma separated list of fields to order by, + * followed by `asc` or `desc` postfix. This list is case-insensitive, + * default sorting order is ascending, redundant space characters are + * insignificant. + * + * Example: `name asc, end_time asc, create_time desc` + * + * Supported fields are: + * + * - `create_time`: corresponds to time the job was created. + * - `end_time`: corresponds to time the job ended. + * - `name`: corresponds to job's name. + * - `state`: corresponds to `state` + * @param {string} request.locationId + * The geographic location where jobs will be retrieved from. + * Use `-` for all locations. Reserved for future extensions. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.privacy.dlp.v2.DlpJob|DlpJob}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listDlpJobsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listDlpJobs( - request?: protos.google.privacy.dlp.v2.IListDlpJobsRequest, - options?: CallOptions): - Promise<[ - protos.google.privacy.dlp.v2.IDlpJob[], - protos.google.privacy.dlp.v2.IListDlpJobsRequest|null, - protos.google.privacy.dlp.v2.IListDlpJobsResponse - ]>; + request?: protos.google.privacy.dlp.v2.IListDlpJobsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.privacy.dlp.v2.IDlpJob[], + protos.google.privacy.dlp.v2.IListDlpJobsRequest | null, + protos.google.privacy.dlp.v2.IListDlpJobsResponse, + ] + >; listDlpJobs( - request: protos.google.privacy.dlp.v2.IListDlpJobsRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.privacy.dlp.v2.IListDlpJobsRequest, - protos.google.privacy.dlp.v2.IListDlpJobsResponse|null|undefined, - protos.google.privacy.dlp.v2.IDlpJob>): void; + request: protos.google.privacy.dlp.v2.IListDlpJobsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.privacy.dlp.v2.IListDlpJobsRequest, + protos.google.privacy.dlp.v2.IListDlpJobsResponse | null | undefined, + protos.google.privacy.dlp.v2.IDlpJob + >, + ): void; listDlpJobs( - request: protos.google.privacy.dlp.v2.IListDlpJobsRequest, - callback: PaginationCallback< - protos.google.privacy.dlp.v2.IListDlpJobsRequest, - protos.google.privacy.dlp.v2.IListDlpJobsResponse|null|undefined, - protos.google.privacy.dlp.v2.IDlpJob>): void; + request: protos.google.privacy.dlp.v2.IListDlpJobsRequest, + callback: PaginationCallback< + protos.google.privacy.dlp.v2.IListDlpJobsRequest, + protos.google.privacy.dlp.v2.IListDlpJobsResponse | null | undefined, + protos.google.privacy.dlp.v2.IDlpJob + >, + ): void; listDlpJobs( - request?: protos.google.privacy.dlp.v2.IListDlpJobsRequest, - optionsOrCallback?: CallOptions|PaginationCallback< - protos.google.privacy.dlp.v2.IListDlpJobsRequest, - protos.google.privacy.dlp.v2.IListDlpJobsResponse|null|undefined, - protos.google.privacy.dlp.v2.IDlpJob>, - callback?: PaginationCallback< + request?: protos.google.privacy.dlp.v2.IListDlpJobsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.privacy.dlp.v2.IListDlpJobsRequest, - protos.google.privacy.dlp.v2.IListDlpJobsResponse|null|undefined, - protos.google.privacy.dlp.v2.IDlpJob>): - Promise<[ - protos.google.privacy.dlp.v2.IDlpJob[], - protos.google.privacy.dlp.v2.IListDlpJobsRequest|null, - protos.google.privacy.dlp.v2.IListDlpJobsResponse - ]>|void { + protos.google.privacy.dlp.v2.IListDlpJobsResponse | null | undefined, + protos.google.privacy.dlp.v2.IDlpJob + >, + callback?: PaginationCallback< + protos.google.privacy.dlp.v2.IListDlpJobsRequest, + protos.google.privacy.dlp.v2.IListDlpJobsResponse | null | undefined, + protos.google.privacy.dlp.v2.IDlpJob + >, + ): Promise< + [ + protos.google.privacy.dlp.v2.IDlpJob[], + protos.google.privacy.dlp.v2.IListDlpJobsRequest | null, + protos.google.privacy.dlp.v2.IListDlpJobsResponse, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - 'location_id': request.locationId?.toString() ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + location_id: request.locationId?.toString() ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.privacy.dlp.v2.IListDlpJobsRequest, - protos.google.privacy.dlp.v2.IListDlpJobsResponse|null|undefined, - protos.google.privacy.dlp.v2.IDlpJob>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.privacy.dlp.v2.IListDlpJobsRequest, + protos.google.privacy.dlp.v2.IListDlpJobsResponse | null | undefined, + protos.google.privacy.dlp.v2.IDlpJob + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listDlpJobs values %j', values); callback!(error, values, nextPageRequest, rawResponse); @@ -4065,311 +5228,340 @@ export class DlpServiceClient { this._log.info('listDlpJobs request %j', request); return this.innerApiCalls .listDlpJobs(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.privacy.dlp.v2.IDlpJob[], - protos.google.privacy.dlp.v2.IListDlpJobsRequest|null, - protos.google.privacy.dlp.v2.IListDlpJobsResponse - ]) => { - this._log.info('listDlpJobs values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.privacy.dlp.v2.IDlpJob[], + protos.google.privacy.dlp.v2.IListDlpJobsRequest | null, + protos.google.privacy.dlp.v2.IListDlpJobsResponse, + ]) => { + this._log.info('listDlpJobs values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listDlpJobs`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent resource name, for example projects/my-project-id. - * @param {string} request.filter - * Allows filtering. - * - * Supported syntax: - * - * * Filter expressions are made up of one or more restrictions. - * * Restrictions can be combined by `AND` or `OR` logical operators. A - * sequence of restrictions implicitly uses `AND`. - * * A restriction has the form of `{field} {operator} {value}`. - * * Supported fields/values for inspect jobs: - * - `state` - PENDING|RUNNING|CANCELED|FINISHED|FAILED - * - `inspected_storage` - DATASTORE|CLOUD_STORAGE|BIGQUERY - * - `trigger_name` - The resource name of the trigger that created job. - * - 'end_time` - Corresponds to time the job finished. - * - 'start_time` - Corresponds to time the job finished. - * * Supported fields for risk analysis jobs: - * - `state` - RUNNING|CANCELED|FINISHED|FAILED - * - 'end_time` - Corresponds to time the job finished. - * - 'start_time` - Corresponds to time the job finished. - * * The operator must be `=` or `!=`. - * - * Examples: - * - * * inspected_storage = cloud_storage AND state = done - * * inspected_storage = cloud_storage OR inspected_storage = bigquery - * * inspected_storage = cloud_storage AND (state = done OR state = canceled) - * * end_time > \"2017-12-12T00:00:00+00:00\" - * - * The length of this field should be no more than 500 characters. - * @param {number} request.pageSize - * The standard list page size. - * @param {string} request.pageToken - * The standard list page token. - * @param {google.privacy.dlp.v2.DlpJobType} request.type - * The type of job. Defaults to `DlpJobType.INSPECT` - * @param {string} request.orderBy - * Comma separated list of fields to order by, - * followed by `asc` or `desc` postfix. This list is case-insensitive, - * default sorting order is ascending, redundant space characters are - * insignificant. - * - * Example: `name asc, end_time asc, create_time desc` - * - * Supported fields are: - * - * - `create_time`: corresponds to time the job was created. - * - `end_time`: corresponds to time the job ended. - * - `name`: corresponds to job's name. - * - `state`: corresponds to `state` - * @param {string} request.locationId - * The geographic location where jobs will be retrieved from. - * Use `-` for all locations. Reserved for future extensions. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.privacy.dlp.v2.DlpJob|DlpJob} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `listDlpJobsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `listDlpJobs`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource name, for example projects/my-project-id. + * @param {string} request.filter + * Allows filtering. + * + * Supported syntax: + * + * * Filter expressions are made up of one or more restrictions. + * * Restrictions can be combined by `AND` or `OR` logical operators. A + * sequence of restrictions implicitly uses `AND`. + * * A restriction has the form of `{field} {operator} {value}`. + * * Supported fields/values for inspect jobs: + * - `state` - PENDING|RUNNING|CANCELED|FINISHED|FAILED + * - `inspected_storage` - DATASTORE|CLOUD_STORAGE|BIGQUERY + * - `trigger_name` - The resource name of the trigger that created job. + * - 'end_time` - Corresponds to time the job finished. + * - 'start_time` - Corresponds to time the job finished. + * * Supported fields for risk analysis jobs: + * - `state` - RUNNING|CANCELED|FINISHED|FAILED + * - 'end_time` - Corresponds to time the job finished. + * - 'start_time` - Corresponds to time the job finished. + * * The operator must be `=` or `!=`. + * + * Examples: + * + * * inspected_storage = cloud_storage AND state = done + * * inspected_storage = cloud_storage OR inspected_storage = bigquery + * * inspected_storage = cloud_storage AND (state = done OR state = canceled) + * * end_time > \"2017-12-12T00:00:00+00:00\" + * + * The length of this field should be no more than 500 characters. + * @param {number} request.pageSize + * The standard list page size. + * @param {string} request.pageToken + * The standard list page token. + * @param {google.privacy.dlp.v2.DlpJobType} request.type + * The type of job. Defaults to `DlpJobType.INSPECT` + * @param {string} request.orderBy + * Comma separated list of fields to order by, + * followed by `asc` or `desc` postfix. This list is case-insensitive, + * default sorting order is ascending, redundant space characters are + * insignificant. + * + * Example: `name asc, end_time asc, create_time desc` + * + * Supported fields are: + * + * - `create_time`: corresponds to time the job was created. + * - `end_time`: corresponds to time the job ended. + * - `name`: corresponds to job's name. + * - `state`: corresponds to `state` + * @param {string} request.locationId + * The geographic location where jobs will be retrieved from. + * Use `-` for all locations. Reserved for future extensions. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.privacy.dlp.v2.DlpJob|DlpJob} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listDlpJobsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listDlpJobsStream( - request?: protos.google.privacy.dlp.v2.IListDlpJobsRequest, - options?: CallOptions): - Transform{ + request?: protos.google.privacy.dlp.v2.IListDlpJobsRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - 'location_id': request.locationId?.toString() ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + location_id: request.locationId?.toString() ?? '', + }); const defaultCallSettings = this._defaults['listDlpJobs']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listDlpJobs stream %j', request); return this.descriptors.page.listDlpJobs.createStream( this.innerApiCalls.listDlpJobs as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listDlpJobs`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent resource name, for example projects/my-project-id. - * @param {string} request.filter - * Allows filtering. - * - * Supported syntax: - * - * * Filter expressions are made up of one or more restrictions. - * * Restrictions can be combined by `AND` or `OR` logical operators. A - * sequence of restrictions implicitly uses `AND`. - * * A restriction has the form of `{field} {operator} {value}`. - * * Supported fields/values for inspect jobs: - * - `state` - PENDING|RUNNING|CANCELED|FINISHED|FAILED - * - `inspected_storage` - DATASTORE|CLOUD_STORAGE|BIGQUERY - * - `trigger_name` - The resource name of the trigger that created job. - * - 'end_time` - Corresponds to time the job finished. - * - 'start_time` - Corresponds to time the job finished. - * * Supported fields for risk analysis jobs: - * - `state` - RUNNING|CANCELED|FINISHED|FAILED - * - 'end_time` - Corresponds to time the job finished. - * - 'start_time` - Corresponds to time the job finished. - * * The operator must be `=` or `!=`. - * - * Examples: - * - * * inspected_storage = cloud_storage AND state = done - * * inspected_storage = cloud_storage OR inspected_storage = bigquery - * * inspected_storage = cloud_storage AND (state = done OR state = canceled) - * * end_time > \"2017-12-12T00:00:00+00:00\" - * - * The length of this field should be no more than 500 characters. - * @param {number} request.pageSize - * The standard list page size. - * @param {string} request.pageToken - * The standard list page token. - * @param {google.privacy.dlp.v2.DlpJobType} request.type - * The type of job. Defaults to `DlpJobType.INSPECT` - * @param {string} request.orderBy - * Comma separated list of fields to order by, - * followed by `asc` or `desc` postfix. This list is case-insensitive, - * default sorting order is ascending, redundant space characters are - * insignificant. - * - * Example: `name asc, end_time asc, create_time desc` - * - * Supported fields are: - * - * - `create_time`: corresponds to time the job was created. - * - `end_time`: corresponds to time the job ended. - * - `name`: corresponds to job's name. - * - `state`: corresponds to `state` - * @param {string} request.locationId - * The geographic location where jobs will be retrieved from. - * Use `-` for all locations. Reserved for future extensions. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.privacy.dlp.v2.DlpJob|DlpJob}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v2/dlp_service.list_dlp_jobs.js - * region_tag:dlp_v2_generated_DlpService_ListDlpJobs_async - */ + /** + * Equivalent to `listDlpJobs`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource name, for example projects/my-project-id. + * @param {string} request.filter + * Allows filtering. + * + * Supported syntax: + * + * * Filter expressions are made up of one or more restrictions. + * * Restrictions can be combined by `AND` or `OR` logical operators. A + * sequence of restrictions implicitly uses `AND`. + * * A restriction has the form of `{field} {operator} {value}`. + * * Supported fields/values for inspect jobs: + * - `state` - PENDING|RUNNING|CANCELED|FINISHED|FAILED + * - `inspected_storage` - DATASTORE|CLOUD_STORAGE|BIGQUERY + * - `trigger_name` - The resource name of the trigger that created job. + * - 'end_time` - Corresponds to time the job finished. + * - 'start_time` - Corresponds to time the job finished. + * * Supported fields for risk analysis jobs: + * - `state` - RUNNING|CANCELED|FINISHED|FAILED + * - 'end_time` - Corresponds to time the job finished. + * - 'start_time` - Corresponds to time the job finished. + * * The operator must be `=` or `!=`. + * + * Examples: + * + * * inspected_storage = cloud_storage AND state = done + * * inspected_storage = cloud_storage OR inspected_storage = bigquery + * * inspected_storage = cloud_storage AND (state = done OR state = canceled) + * * end_time > \"2017-12-12T00:00:00+00:00\" + * + * The length of this field should be no more than 500 characters. + * @param {number} request.pageSize + * The standard list page size. + * @param {string} request.pageToken + * The standard list page token. + * @param {google.privacy.dlp.v2.DlpJobType} request.type + * The type of job. Defaults to `DlpJobType.INSPECT` + * @param {string} request.orderBy + * Comma separated list of fields to order by, + * followed by `asc` or `desc` postfix. This list is case-insensitive, + * default sorting order is ascending, redundant space characters are + * insignificant. + * + * Example: `name asc, end_time asc, create_time desc` + * + * Supported fields are: + * + * - `create_time`: corresponds to time the job was created. + * - `end_time`: corresponds to time the job ended. + * - `name`: corresponds to job's name. + * - `state`: corresponds to `state` + * @param {string} request.locationId + * The geographic location where jobs will be retrieved from. + * Use `-` for all locations. Reserved for future extensions. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.privacy.dlp.v2.DlpJob|DlpJob}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v2/dlp_service.list_dlp_jobs.js + * region_tag:dlp_v2_generated_DlpService_ListDlpJobs_async + */ listDlpJobsAsync( - request?: protos.google.privacy.dlp.v2.IListDlpJobsRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.privacy.dlp.v2.IListDlpJobsRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - 'location_id': request.locationId?.toString() ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + location_id: request.locationId?.toString() ?? '', + }); const defaultCallSettings = this._defaults['listDlpJobs']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listDlpJobs iterate %j', request); return this.descriptors.page.listDlpJobs.asyncIterate( this.innerApiCalls['listDlpJobs'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } - /** - * Lists stored infoTypes. - * See https://cloud.google.com/dlp/docs/creating-stored-infotypes to - * learn more. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent resource name, for example projects/my-project-id or - * organizations/my-org-id. - * @param {string} request.pageToken - * Page token to continue retrieval. Comes from previous call - * to `ListStoredInfoTypes`. - * @param {number} request.pageSize - * Size of the page, can be limited by server. If zero server returns - * a page of max size 100. - * @param {string} request.orderBy - * Comma separated list of fields to order by, - * followed by `asc` or `desc` postfix. This list is case-insensitive, - * default sorting order is ascending, redundant space characters are - * insignificant. - * - * Example: `name asc, display_name, create_time desc` - * - * Supported fields are: - * - * - `create_time`: corresponds to time the most recent version of the - * resource was created. - * - `state`: corresponds to the state of the resource. - * - `name`: corresponds to resource name. - * - `display_name`: corresponds to info type's display name. - * @param {string} request.locationId - * The geographic location where stored infoTypes will be retrieved from. - * Use `-` for all locations. Reserved for future extensions. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.privacy.dlp.v2.StoredInfoType|StoredInfoType}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `listStoredInfoTypesAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Lists stored infoTypes. + * See https://cloud.google.com/dlp/docs/creating-stored-infotypes to + * learn more. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource name, for example projects/my-project-id or + * organizations/my-org-id. + * @param {string} request.pageToken + * Page token to continue retrieval. Comes from previous call + * to `ListStoredInfoTypes`. + * @param {number} request.pageSize + * Size of the page, can be limited by server. If zero server returns + * a page of max size 100. + * @param {string} request.orderBy + * Comma separated list of fields to order by, + * followed by `asc` or `desc` postfix. This list is case-insensitive, + * default sorting order is ascending, redundant space characters are + * insignificant. + * + * Example: `name asc, display_name, create_time desc` + * + * Supported fields are: + * + * - `create_time`: corresponds to time the most recent version of the + * resource was created. + * - `state`: corresponds to the state of the resource. + * - `name`: corresponds to resource name. + * - `display_name`: corresponds to info type's display name. + * @param {string} request.locationId + * The geographic location where stored infoTypes will be retrieved from. + * Use `-` for all locations. Reserved for future extensions. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.privacy.dlp.v2.StoredInfoType|StoredInfoType}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listStoredInfoTypesAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listStoredInfoTypes( - request?: protos.google.privacy.dlp.v2.IListStoredInfoTypesRequest, - options?: CallOptions): - Promise<[ - protos.google.privacy.dlp.v2.IStoredInfoType[], - protos.google.privacy.dlp.v2.IListStoredInfoTypesRequest|null, - protos.google.privacy.dlp.v2.IListStoredInfoTypesResponse - ]>; + request?: protos.google.privacy.dlp.v2.IListStoredInfoTypesRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.privacy.dlp.v2.IStoredInfoType[], + protos.google.privacy.dlp.v2.IListStoredInfoTypesRequest | null, + protos.google.privacy.dlp.v2.IListStoredInfoTypesResponse, + ] + >; listStoredInfoTypes( - request: protos.google.privacy.dlp.v2.IListStoredInfoTypesRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.privacy.dlp.v2.IListStoredInfoTypesRequest, - protos.google.privacy.dlp.v2.IListStoredInfoTypesResponse|null|undefined, - protos.google.privacy.dlp.v2.IStoredInfoType>): void; + request: protos.google.privacy.dlp.v2.IListStoredInfoTypesRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.privacy.dlp.v2.IListStoredInfoTypesRequest, + | protos.google.privacy.dlp.v2.IListStoredInfoTypesResponse + | null + | undefined, + protos.google.privacy.dlp.v2.IStoredInfoType + >, + ): void; listStoredInfoTypes( - request: protos.google.privacy.dlp.v2.IListStoredInfoTypesRequest, - callback: PaginationCallback< - protos.google.privacy.dlp.v2.IListStoredInfoTypesRequest, - protos.google.privacy.dlp.v2.IListStoredInfoTypesResponse|null|undefined, - protos.google.privacy.dlp.v2.IStoredInfoType>): void; + request: protos.google.privacy.dlp.v2.IListStoredInfoTypesRequest, + callback: PaginationCallback< + protos.google.privacy.dlp.v2.IListStoredInfoTypesRequest, + | protos.google.privacy.dlp.v2.IListStoredInfoTypesResponse + | null + | undefined, + protos.google.privacy.dlp.v2.IStoredInfoType + >, + ): void; listStoredInfoTypes( - request?: protos.google.privacy.dlp.v2.IListStoredInfoTypesRequest, - optionsOrCallback?: CallOptions|PaginationCallback< + request?: protos.google.privacy.dlp.v2.IListStoredInfoTypesRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.privacy.dlp.v2.IListStoredInfoTypesRequest, - protos.google.privacy.dlp.v2.IListStoredInfoTypesResponse|null|undefined, - protos.google.privacy.dlp.v2.IStoredInfoType>, - callback?: PaginationCallback< - protos.google.privacy.dlp.v2.IListStoredInfoTypesRequest, - protos.google.privacy.dlp.v2.IListStoredInfoTypesResponse|null|undefined, - protos.google.privacy.dlp.v2.IStoredInfoType>): - Promise<[ - protos.google.privacy.dlp.v2.IStoredInfoType[], - protos.google.privacy.dlp.v2.IListStoredInfoTypesRequest|null, - protos.google.privacy.dlp.v2.IListStoredInfoTypesResponse - ]>|void { + | protos.google.privacy.dlp.v2.IListStoredInfoTypesResponse + | null + | undefined, + protos.google.privacy.dlp.v2.IStoredInfoType + >, + callback?: PaginationCallback< + protos.google.privacy.dlp.v2.IListStoredInfoTypesRequest, + | protos.google.privacy.dlp.v2.IListStoredInfoTypesResponse + | null + | undefined, + protos.google.privacy.dlp.v2.IStoredInfoType + >, + ): Promise< + [ + protos.google.privacy.dlp.v2.IStoredInfoType[], + protos.google.privacy.dlp.v2.IListStoredInfoTypesRequest | null, + protos.google.privacy.dlp.v2.IListStoredInfoTypesResponse, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - 'location_id': request.locationId?.toString() ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + location_id: request.locationId?.toString() ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.privacy.dlp.v2.IListStoredInfoTypesRequest, - protos.google.privacy.dlp.v2.IListStoredInfoTypesResponse|null|undefined, - protos.google.privacy.dlp.v2.IStoredInfoType>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.privacy.dlp.v2.IListStoredInfoTypesRequest, + | protos.google.privacy.dlp.v2.IListStoredInfoTypesResponse + | null + | undefined, + protos.google.privacy.dlp.v2.IStoredInfoType + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listStoredInfoTypes values %j', values); callback!(error, values, nextPageRequest, rawResponse); @@ -4378,150 +5570,154 @@ export class DlpServiceClient { this._log.info('listStoredInfoTypes request %j', request); return this.innerApiCalls .listStoredInfoTypes(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.privacy.dlp.v2.IStoredInfoType[], - protos.google.privacy.dlp.v2.IListStoredInfoTypesRequest|null, - protos.google.privacy.dlp.v2.IListStoredInfoTypesResponse - ]) => { - this._log.info('listStoredInfoTypes values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.privacy.dlp.v2.IStoredInfoType[], + protos.google.privacy.dlp.v2.IListStoredInfoTypesRequest | null, + protos.google.privacy.dlp.v2.IListStoredInfoTypesResponse, + ]) => { + this._log.info('listStoredInfoTypes values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listStoredInfoTypes`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent resource name, for example projects/my-project-id or - * organizations/my-org-id. - * @param {string} request.pageToken - * Page token to continue retrieval. Comes from previous call - * to `ListStoredInfoTypes`. - * @param {number} request.pageSize - * Size of the page, can be limited by server. If zero server returns - * a page of max size 100. - * @param {string} request.orderBy - * Comma separated list of fields to order by, - * followed by `asc` or `desc` postfix. This list is case-insensitive, - * default sorting order is ascending, redundant space characters are - * insignificant. - * - * Example: `name asc, display_name, create_time desc` - * - * Supported fields are: - * - * - `create_time`: corresponds to time the most recent version of the - * resource was created. - * - `state`: corresponds to the state of the resource. - * - `name`: corresponds to resource name. - * - `display_name`: corresponds to info type's display name. - * @param {string} request.locationId - * The geographic location where stored infoTypes will be retrieved from. - * Use `-` for all locations. Reserved for future extensions. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.privacy.dlp.v2.StoredInfoType|StoredInfoType} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `listStoredInfoTypesAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `listStoredInfoTypes`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource name, for example projects/my-project-id or + * organizations/my-org-id. + * @param {string} request.pageToken + * Page token to continue retrieval. Comes from previous call + * to `ListStoredInfoTypes`. + * @param {number} request.pageSize + * Size of the page, can be limited by server. If zero server returns + * a page of max size 100. + * @param {string} request.orderBy + * Comma separated list of fields to order by, + * followed by `asc` or `desc` postfix. This list is case-insensitive, + * default sorting order is ascending, redundant space characters are + * insignificant. + * + * Example: `name asc, display_name, create_time desc` + * + * Supported fields are: + * + * - `create_time`: corresponds to time the most recent version of the + * resource was created. + * - `state`: corresponds to the state of the resource. + * - `name`: corresponds to resource name. + * - `display_name`: corresponds to info type's display name. + * @param {string} request.locationId + * The geographic location where stored infoTypes will be retrieved from. + * Use `-` for all locations. Reserved for future extensions. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.privacy.dlp.v2.StoredInfoType|StoredInfoType} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listStoredInfoTypesAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listStoredInfoTypesStream( - request?: protos.google.privacy.dlp.v2.IListStoredInfoTypesRequest, - options?: CallOptions): - Transform{ + request?: protos.google.privacy.dlp.v2.IListStoredInfoTypesRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - 'location_id': request.locationId?.toString() ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + location_id: request.locationId?.toString() ?? '', + }); const defaultCallSettings = this._defaults['listStoredInfoTypes']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listStoredInfoTypes stream %j', request); return this.descriptors.page.listStoredInfoTypes.createStream( this.innerApiCalls.listStoredInfoTypes as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listStoredInfoTypes`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent resource name, for example projects/my-project-id or - * organizations/my-org-id. - * @param {string} request.pageToken - * Page token to continue retrieval. Comes from previous call - * to `ListStoredInfoTypes`. - * @param {number} request.pageSize - * Size of the page, can be limited by server. If zero server returns - * a page of max size 100. - * @param {string} request.orderBy - * Comma separated list of fields to order by, - * followed by `asc` or `desc` postfix. This list is case-insensitive, - * default sorting order is ascending, redundant space characters are - * insignificant. - * - * Example: `name asc, display_name, create_time desc` - * - * Supported fields are: - * - * - `create_time`: corresponds to time the most recent version of the - * resource was created. - * - `state`: corresponds to the state of the resource. - * - `name`: corresponds to resource name. - * - `display_name`: corresponds to info type's display name. - * @param {string} request.locationId - * The geographic location where stored infoTypes will be retrieved from. - * Use `-` for all locations. Reserved for future extensions. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.privacy.dlp.v2.StoredInfoType|StoredInfoType}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v2/dlp_service.list_stored_info_types.js - * region_tag:dlp_v2_generated_DlpService_ListStoredInfoTypes_async - */ + /** + * Equivalent to `listStoredInfoTypes`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource name, for example projects/my-project-id or + * organizations/my-org-id. + * @param {string} request.pageToken + * Page token to continue retrieval. Comes from previous call + * to `ListStoredInfoTypes`. + * @param {number} request.pageSize + * Size of the page, can be limited by server. If zero server returns + * a page of max size 100. + * @param {string} request.orderBy + * Comma separated list of fields to order by, + * followed by `asc` or `desc` postfix. This list is case-insensitive, + * default sorting order is ascending, redundant space characters are + * insignificant. + * + * Example: `name asc, display_name, create_time desc` + * + * Supported fields are: + * + * - `create_time`: corresponds to time the most recent version of the + * resource was created. + * - `state`: corresponds to the state of the resource. + * - `name`: corresponds to resource name. + * - `display_name`: corresponds to info type's display name. + * @param {string} request.locationId + * The geographic location where stored infoTypes will be retrieved from. + * Use `-` for all locations. Reserved for future extensions. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.privacy.dlp.v2.StoredInfoType|StoredInfoType}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v2/dlp_service.list_stored_info_types.js + * region_tag:dlp_v2_generated_DlpService_ListStoredInfoTypes_async + */ listStoredInfoTypesAsync( - request?: protos.google.privacy.dlp.v2.IListStoredInfoTypesRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.privacy.dlp.v2.IListStoredInfoTypesRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - 'location_id': request.locationId?.toString() ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + location_id: request.locationId?.toString() ?? '', + }); const defaultCallSettings = this._defaults['listStoredInfoTypes']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listStoredInfoTypes iterate %j', request); return this.descriptors.page.listStoredInfoTypes.asyncIterate( this.innerApiCalls['listStoredInfoTypes'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } // -------------------- @@ -4535,7 +5731,7 @@ export class DlpServiceClient { * @param {string} dlp_job * @returns {string} Resource name string. */ - dlpJobPath(project:string,dlpJob:string) { + dlpJobPath(project: string, dlpJob: string) { return this.pathTemplates.dlpJobPathTemplate.render({ project: project, dlp_job: dlpJob, @@ -4571,7 +5767,7 @@ export class DlpServiceClient { * @param {string} job_trigger * @returns {string} Resource name string. */ - jobTriggerPath(project:string,jobTrigger:string) { + jobTriggerPath(project: string, jobTrigger: string) { return this.pathTemplates.jobTriggerPathTemplate.render({ project: project, job_trigger: jobTrigger, @@ -4586,7 +5782,8 @@ export class DlpServiceClient { * @returns {string} A string representing the project. */ matchProjectFromJobTriggerName(jobTriggerName: string) { - return this.pathTemplates.jobTriggerPathTemplate.match(jobTriggerName).project; + return this.pathTemplates.jobTriggerPathTemplate.match(jobTriggerName) + .project; } /** @@ -4597,7 +5794,8 @@ export class DlpServiceClient { * @returns {string} A string representing the job_trigger. */ matchJobTriggerFromJobTriggerName(jobTriggerName: string) { - return this.pathTemplates.jobTriggerPathTemplate.match(jobTriggerName).job_trigger; + return this.pathTemplates.jobTriggerPathTemplate.match(jobTriggerName) + .job_trigger; } /** @@ -4606,7 +5804,7 @@ export class DlpServiceClient { * @param {string} organization * @returns {string} Resource name string. */ - organizationPath(organization:string) { + organizationPath(organization: string) { return this.pathTemplates.organizationPathTemplate.render({ organization: organization, }); @@ -4620,7 +5818,8 @@ export class DlpServiceClient { * @returns {string} A string representing the organization. */ matchOrganizationFromOrganizationName(organizationName: string) { - return this.pathTemplates.organizationPathTemplate.match(organizationName).organization; + return this.pathTemplates.organizationPathTemplate.match(organizationName) + .organization; } /** @@ -4630,11 +5829,16 @@ export class DlpServiceClient { * @param {string} deidentify_template * @returns {string} Resource name string. */ - organizationDeidentifyTemplatePath(organization:string,deidentifyTemplate:string) { - return this.pathTemplates.organizationDeidentifyTemplatePathTemplate.render({ - organization: organization, - deidentify_template: deidentifyTemplate, - }); + organizationDeidentifyTemplatePath( + organization: string, + deidentifyTemplate: string, + ) { + return this.pathTemplates.organizationDeidentifyTemplatePathTemplate.render( + { + organization: organization, + deidentify_template: deidentifyTemplate, + }, + ); } /** @@ -4644,8 +5848,12 @@ export class DlpServiceClient { * A fully-qualified path representing organization_deidentify_template resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationDeidentifyTemplateName(organizationDeidentifyTemplateName: string) { - return this.pathTemplates.organizationDeidentifyTemplatePathTemplate.match(organizationDeidentifyTemplateName).organization; + matchOrganizationFromOrganizationDeidentifyTemplateName( + organizationDeidentifyTemplateName: string, + ) { + return this.pathTemplates.organizationDeidentifyTemplatePathTemplate.match( + organizationDeidentifyTemplateName, + ).organization; } /** @@ -4655,8 +5863,12 @@ export class DlpServiceClient { * A fully-qualified path representing organization_deidentify_template resource. * @returns {string} A string representing the deidentify_template. */ - matchDeidentifyTemplateFromOrganizationDeidentifyTemplateName(organizationDeidentifyTemplateName: string) { - return this.pathTemplates.organizationDeidentifyTemplatePathTemplate.match(organizationDeidentifyTemplateName).deidentify_template; + matchDeidentifyTemplateFromOrganizationDeidentifyTemplateName( + organizationDeidentifyTemplateName: string, + ) { + return this.pathTemplates.organizationDeidentifyTemplatePathTemplate.match( + organizationDeidentifyTemplateName, + ).deidentify_template; } /** @@ -4666,7 +5878,10 @@ export class DlpServiceClient { * @param {string} inspect_template * @returns {string} Resource name string. */ - organizationInspectTemplatePath(organization:string,inspectTemplate:string) { + organizationInspectTemplatePath( + organization: string, + inspectTemplate: string, + ) { return this.pathTemplates.organizationInspectTemplatePathTemplate.render({ organization: organization, inspect_template: inspectTemplate, @@ -4680,8 +5895,12 @@ export class DlpServiceClient { * A fully-qualified path representing organization_inspect_template resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationInspectTemplateName(organizationInspectTemplateName: string) { - return this.pathTemplates.organizationInspectTemplatePathTemplate.match(organizationInspectTemplateName).organization; + matchOrganizationFromOrganizationInspectTemplateName( + organizationInspectTemplateName: string, + ) { + return this.pathTemplates.organizationInspectTemplatePathTemplate.match( + organizationInspectTemplateName, + ).organization; } /** @@ -4691,8 +5910,12 @@ export class DlpServiceClient { * A fully-qualified path representing organization_inspect_template resource. * @returns {string} A string representing the inspect_template. */ - matchInspectTemplateFromOrganizationInspectTemplateName(organizationInspectTemplateName: string) { - return this.pathTemplates.organizationInspectTemplatePathTemplate.match(organizationInspectTemplateName).inspect_template; + matchInspectTemplateFromOrganizationInspectTemplateName( + organizationInspectTemplateName: string, + ) { + return this.pathTemplates.organizationInspectTemplatePathTemplate.match( + organizationInspectTemplateName, + ).inspect_template; } /** @@ -4702,7 +5925,7 @@ export class DlpServiceClient { * @param {string} stored_info_type * @returns {string} Resource name string. */ - organizationStoredInfoTypePath(organization:string,storedInfoType:string) { + organizationStoredInfoTypePath(organization: string, storedInfoType: string) { return this.pathTemplates.organizationStoredInfoTypePathTemplate.render({ organization: organization, stored_info_type: storedInfoType, @@ -4716,8 +5939,12 @@ export class DlpServiceClient { * A fully-qualified path representing organization_stored_info_type resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationStoredInfoTypeName(organizationStoredInfoTypeName: string) { - return this.pathTemplates.organizationStoredInfoTypePathTemplate.match(organizationStoredInfoTypeName).organization; + matchOrganizationFromOrganizationStoredInfoTypeName( + organizationStoredInfoTypeName: string, + ) { + return this.pathTemplates.organizationStoredInfoTypePathTemplate.match( + organizationStoredInfoTypeName, + ).organization; } /** @@ -4727,8 +5954,12 @@ export class DlpServiceClient { * A fully-qualified path representing organization_stored_info_type resource. * @returns {string} A string representing the stored_info_type. */ - matchStoredInfoTypeFromOrganizationStoredInfoTypeName(organizationStoredInfoTypeName: string) { - return this.pathTemplates.organizationStoredInfoTypePathTemplate.match(organizationStoredInfoTypeName).stored_info_type; + matchStoredInfoTypeFromOrganizationStoredInfoTypeName( + organizationStoredInfoTypeName: string, + ) { + return this.pathTemplates.organizationStoredInfoTypePathTemplate.match( + organizationStoredInfoTypeName, + ).stored_info_type; } /** @@ -4737,7 +5968,7 @@ export class DlpServiceClient { * @param {string} project * @returns {string} Resource name string. */ - projectPath(project:string) { + projectPath(project: string) { return this.pathTemplates.projectPathTemplate.render({ project: project, }); @@ -4761,7 +5992,7 @@ export class DlpServiceClient { * @param {string} deidentify_template * @returns {string} Resource name string. */ - projectDeidentifyTemplatePath(project:string,deidentifyTemplate:string) { + projectDeidentifyTemplatePath(project: string, deidentifyTemplate: string) { return this.pathTemplates.projectDeidentifyTemplatePathTemplate.render({ project: project, deidentify_template: deidentifyTemplate, @@ -4775,8 +6006,12 @@ export class DlpServiceClient { * A fully-qualified path representing project_deidentify_template resource. * @returns {string} A string representing the project. */ - matchProjectFromProjectDeidentifyTemplateName(projectDeidentifyTemplateName: string) { - return this.pathTemplates.projectDeidentifyTemplatePathTemplate.match(projectDeidentifyTemplateName).project; + matchProjectFromProjectDeidentifyTemplateName( + projectDeidentifyTemplateName: string, + ) { + return this.pathTemplates.projectDeidentifyTemplatePathTemplate.match( + projectDeidentifyTemplateName, + ).project; } /** @@ -4786,8 +6021,12 @@ export class DlpServiceClient { * A fully-qualified path representing project_deidentify_template resource. * @returns {string} A string representing the deidentify_template. */ - matchDeidentifyTemplateFromProjectDeidentifyTemplateName(projectDeidentifyTemplateName: string) { - return this.pathTemplates.projectDeidentifyTemplatePathTemplate.match(projectDeidentifyTemplateName).deidentify_template; + matchDeidentifyTemplateFromProjectDeidentifyTemplateName( + projectDeidentifyTemplateName: string, + ) { + return this.pathTemplates.projectDeidentifyTemplatePathTemplate.match( + projectDeidentifyTemplateName, + ).deidentify_template; } /** @@ -4797,7 +6036,7 @@ export class DlpServiceClient { * @param {string} inspect_template * @returns {string} Resource name string. */ - projectInspectTemplatePath(project:string,inspectTemplate:string) { + projectInspectTemplatePath(project: string, inspectTemplate: string) { return this.pathTemplates.projectInspectTemplatePathTemplate.render({ project: project, inspect_template: inspectTemplate, @@ -4811,8 +6050,12 @@ export class DlpServiceClient { * A fully-qualified path representing project_inspect_template resource. * @returns {string} A string representing the project. */ - matchProjectFromProjectInspectTemplateName(projectInspectTemplateName: string) { - return this.pathTemplates.projectInspectTemplatePathTemplate.match(projectInspectTemplateName).project; + matchProjectFromProjectInspectTemplateName( + projectInspectTemplateName: string, + ) { + return this.pathTemplates.projectInspectTemplatePathTemplate.match( + projectInspectTemplateName, + ).project; } /** @@ -4822,8 +6065,12 @@ export class DlpServiceClient { * A fully-qualified path representing project_inspect_template resource. * @returns {string} A string representing the inspect_template. */ - matchInspectTemplateFromProjectInspectTemplateName(projectInspectTemplateName: string) { - return this.pathTemplates.projectInspectTemplatePathTemplate.match(projectInspectTemplateName).inspect_template; + matchInspectTemplateFromProjectInspectTemplateName( + projectInspectTemplateName: string, + ) { + return this.pathTemplates.projectInspectTemplatePathTemplate.match( + projectInspectTemplateName, + ).inspect_template; } /** @@ -4833,7 +6080,7 @@ export class DlpServiceClient { * @param {string} stored_info_type * @returns {string} Resource name string. */ - projectStoredInfoTypePath(project:string,storedInfoType:string) { + projectStoredInfoTypePath(project: string, storedInfoType: string) { return this.pathTemplates.projectStoredInfoTypePathTemplate.render({ project: project, stored_info_type: storedInfoType, @@ -4848,7 +6095,9 @@ export class DlpServiceClient { * @returns {string} A string representing the project. */ matchProjectFromProjectStoredInfoTypeName(projectStoredInfoTypeName: string) { - return this.pathTemplates.projectStoredInfoTypePathTemplate.match(projectStoredInfoTypeName).project; + return this.pathTemplates.projectStoredInfoTypePathTemplate.match( + projectStoredInfoTypeName, + ).project; } /** @@ -4858,8 +6107,12 @@ export class DlpServiceClient { * A fully-qualified path representing project_stored_info_type resource. * @returns {string} A string representing the stored_info_type. */ - matchStoredInfoTypeFromProjectStoredInfoTypeName(projectStoredInfoTypeName: string) { - return this.pathTemplates.projectStoredInfoTypePathTemplate.match(projectStoredInfoTypeName).stored_info_type; + matchStoredInfoTypeFromProjectStoredInfoTypeName( + projectStoredInfoTypeName: string, + ) { + return this.pathTemplates.projectStoredInfoTypePathTemplate.match( + projectStoredInfoTypeName, + ).stored_info_type; } /** @@ -4870,7 +6123,7 @@ export class DlpServiceClient { */ close(): Promise { if (this.dlpServiceStub && !this._terminated) { - return this.dlpServiceStub.then(stub => { + return this.dlpServiceStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -4878,4 +6131,4 @@ export class DlpServiceClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/core/generator/gapic-generator-typescript/baselines/dlp-esm/esm/src/v2/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/dlp-esm/esm/src/v2/index.ts.baseline index 6dbc1b1c2fad..6cea83737a65 100644 --- a/core/generator/gapic-generator-typescript/baselines/dlp-esm/esm/src/v2/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/dlp-esm/esm/src/v2/index.ts.baseline @@ -16,4 +16,4 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -export {DlpServiceClient} from './dlp_service_client.js'; +export { DlpServiceClient } from './dlp_service_client.js'; diff --git a/core/generator/gapic-generator-typescript/baselines/dlp-esm/esm/system-test/fixtures/sample/src/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/dlp-esm/esm/system-test/fixtures/sample/src/index.ts.baseline index d83930c09280..38a7a13d9b94 100644 --- a/core/generator/gapic-generator-typescript/baselines/dlp-esm/esm/system-test/fixtures/sample/src/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/dlp-esm/esm/system-test/fixtures/sample/src/index.ts.baseline @@ -17,7 +17,7 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -import {DlpServiceClient} from 'dlp'; +import { DlpServiceClient } from 'dlp'; // check that the client class type name can be used function doStuffWithDlpServiceClient(client: DlpServiceClient) { diff --git a/core/generator/gapic-generator-typescript/baselines/dlp-esm/esm/system-test/install.ts.baseline b/core/generator/gapic-generator-typescript/baselines/dlp-esm/esm/system-test/install.ts.baseline index e079c4fa1101..d109fdd8c97f 100644 --- a/core/generator/gapic-generator-typescript/baselines/dlp-esm/esm/system-test/install.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/dlp-esm/esm/system-test/install.ts.baseline @@ -16,40 +16,45 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -import {packNTest} from 'pack-n-play'; -import {readFileSync} from 'fs'; -import {describe, it} from 'mocha'; +import { packNTest } from 'pack-n-play'; +import { readFileSync } from 'fs'; +import { describe, it } from 'mocha'; describe('📦 pack-n-play test', () => { - it('TypeScript', async function() { + it('TypeScript', async function () { this.timeout(300000); await packNTest({ packageDir: process.cwd(), sample: { description: 'TypeScript user can use the type definitions', - ts: readFileSync('./esm/system-test/fixtures/sample/src/index.ts').toString() - } + ts: readFileSync( + './esm/system-test/fixtures/sample/src/index.ts', + ).toString(), + }, }); }); - it('ESM module', async function() { + it('ESM module', async function () { this.timeout(300000); await packNTest({ sample: { description: 'Should be able to import using ESM', - esm: readFileSync('./esm/system-test/fixtures/sample/src/index.js').toString(), + esm: readFileSync( + './esm/system-test/fixtures/sample/src/index.js', + ).toString(), }, }); }); - it('CJS module', async function() { + it('CJS module', async function () { this.timeout(300000); await packNTest({ sample: { description: 'Should be able to import using CJS', - cjs: readFileSync('./esm/system-test/fixtures/sample/src/index.cjs').toString(), + cjs: readFileSync( + './esm/system-test/fixtures/sample/src/index.cjs', + ).toString(), }, }); }); - }); diff --git a/core/generator/gapic-generator-typescript/baselines/dlp-esm/esm/test/gapic_dlp_service_v2.ts.baseline b/core/generator/gapic-generator-typescript/baselines/dlp-esm/esm/test/gapic_dlp_service_v2.ts.baseline index 3da7e9dfb6f2..88b93b3f1bd9 100644 --- a/core/generator/gapic-generator-typescript/baselines/dlp-esm/esm/test/gapic_dlp_service_v2.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/dlp-esm/esm/test/gapic_dlp_service_v2.ts.baseline @@ -20,16 +20,16 @@ import * as protos from '../../protos/protos.js'; import assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as dlpserviceModule from '../src/index.js'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; -import {protobuf} from 'google-gax'; +import { protobuf } from 'google-gax'; import fs from 'fs'; import path from 'path'; -import {fileURLToPath} from 'url'; +import { fileURLToPath } from 'url'; // @ts-ignore const dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -37,4847 +37,6313 @@ const dirname = path.dirname(fileURLToPath(import.meta.url)); // to fill in default values for request objects const root = protobuf.Root.fromJSON( JSON.parse( - fs.readFileSync(path.join(dirname, '..', '..', 'protos/protos.json'), 'utf8') - )) + fs.readFileSync( + path.join(dirname, '..', '..', 'protos/protos.json'), + 'utf8', + ), + ), +); // eslint-disable-next-line @typescript-eslint/no-unused-vars function getTypeDefaultValue(typeName: string, fields: string[]) { - let type = root.lookupType(typeName) as protobuf.Type; - for (const field of fields.slice(0, -1)) { - type = type?.fields[field]?.resolvedType as protobuf.Type; - } - return type?.fields[fields[fields.length - 1]]?.defaultValue ?? null; + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type?.fields[field]?.resolvedType as protobuf.Type; + } + return type?.fields[fields[fields.length - 1]]?.defaultValue ?? null; } function generateSampleMessage(instance: T) { - const filledObject = (instance.constructor as typeof protobuf.Message) - .toObject(instance as protobuf.Message, {defaults: true}); - return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, { defaults: true }); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; } function stubSimpleCall(response?: ResponseType, error?: Error) { - return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); } -function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { - return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +function stubSimpleCallWithCallback( + response?: ResponseType, + error?: Error, +) { + return error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); } -function stubPageStreamingCall(responses?: ResponseType[], error?: Error) { - const pagingStub = sinon.stub(); - if (responses) { - for (let i = 0; i < responses.length; ++i) { - pagingStub.onCall(i).callsArgWith(2, null, responses[i]); - } +function stubPageStreamingCall( + responses?: ResponseType[], + error?: Error, +) { + const pagingStub = sinon.stub(); + if (responses) { + for (let i = 0; i < responses.length; ++i) { + pagingStub.onCall(i).callsArgWith(2, null, responses[i]); } - const transformStub = error ? sinon.stub().callsArgWith(2, error) : pagingStub; - const mockStream = new PassThrough({ - objectMode: true, - transform: transformStub, - }); - // trigger as many responses as needed - if (responses) { - for (let i = 0; i < responses.length; ++i) { - setImmediate(() => { mockStream.write({}); }); - } - setImmediate(() => { mockStream.end(); }); - } else { - setImmediate(() => { mockStream.write({}); }); - setImmediate(() => { mockStream.end(); }); + } + const transformStub = error + ? sinon.stub().callsArgWith(2, error) + : pagingStub; + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + // trigger as many responses as needed + if (responses) { + for (let i = 0; i < responses.length; ++i) { + setImmediate(() => { + mockStream.write({}); + }); } - return sinon.stub().returns(mockStream); + setImmediate(() => { + mockStream.end(); + }); + } else { + setImmediate(() => { + mockStream.write({}); + }); + setImmediate(() => { + mockStream.end(); + }); + } + return sinon.stub().returns(mockStream); } -function stubAsyncIterationCall(responses?: ResponseType[], error?: Error) { - let counter = 0; - const asyncIterable = { - [Symbol.asyncIterator]() { - return { - async next() { - if (error) { - return Promise.reject(error); - } - if (counter >= responses!.length) { - return Promise.resolve({done: true, value: undefined}); - } - return Promise.resolve({done: false, value: responses![counter++]}); - } - }; - } - }; - return sinon.stub().returns(asyncIterable); +function stubAsyncIterationCall( + responses?: ResponseType[], + error?: Error, +) { + let counter = 0; + const asyncIterable = { + [Symbol.asyncIterator]() { + return { + async next() { + if (error) { + return Promise.reject(error); + } + if (counter >= responses!.length) { + return Promise.resolve({ done: true, value: undefined }); + } + return Promise.resolve({ done: false, value: responses![counter++] }); + }, + }; + }, + }; + return sinon.stub().returns(asyncIterable); } describe('v2.DlpServiceClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new dlpserviceModule.v2.DlpServiceClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'dlp.googleapis.com'); - }); - - it('has universeDomain', () => { - const client = new dlpserviceModule.v2.DlpServiceClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); - - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - it('throws DeprecationWarning if static servicePath is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const servicePath = dlpserviceModule.v2.DlpServiceClient.servicePath; - assert.strictEqual(servicePath, 'dlp.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = dlpserviceModule.v2.DlpServiceClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'dlp.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new dlpserviceModule.v2.DlpServiceClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'dlp.example.com'); - }); - - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new dlpserviceModule.v2.DlpServiceClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'dlp.example.com'); - }); - - if (typeof process === 'object' && 'env' in process) { - describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { - it('sets apiEndpoint from environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new dlpserviceModule.v2.DlpServiceClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'dlp.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - - it('value configured in code has priority over environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new dlpserviceModule.v2.DlpServiceClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'dlp.configured.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { new dlpserviceModule.v2.DlpServiceClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); - - it('has port', () => { - const port = dlpserviceModule.v2.DlpServiceClient.port; - assert(port); - assert(typeof port === 'number'); - }); - - it('should create a client with no option', () => { - const client = new dlpserviceModule.v2.DlpServiceClient(); - assert(client); - }); - - it('should create a client with gRPC fallback', () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - fallback: true, - }); - assert(client); - }); - - it('has initialize method and supports deferred initialization', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.dlpServiceStub, undefined); - await client.initialize(); - assert(client.dlpServiceStub); - }); - - it('has close method for the initialized client', done => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.dlpServiceStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); - - it('has close method for the non-initialized client', done => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.dlpServiceStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); - - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); - }); - - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId((err?: Error|null, projectId?: string|null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } - }); - }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new dlpserviceModule.v2.DlpServiceClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'dlp.googleapis.com'); }); - describe('inspectContent', () => { - it('invokes inspectContent without error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.InspectContentRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.InspectContentRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.InspectContentRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.privacy.dlp.v2.InspectContentResponse() - ); - client.innerApiCalls.inspectContent = stubSimpleCall(expectedResponse); - const [response] = await client.inspectContent(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.inspectContent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.inspectContent as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes inspectContent without error using callback', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.InspectContentRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.InspectContentRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.InspectContentRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.privacy.dlp.v2.InspectContentResponse() - ); - client.innerApiCalls.inspectContent = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.inspectContent( - request, - (err?: Error|null, result?: protos.google.privacy.dlp.v2.IInspectContentResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.inspectContent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.inspectContent as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes inspectContent with error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.InspectContentRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.InspectContentRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.InspectContentRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.inspectContent = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.inspectContent(request), expectedError); - const actualRequest = (client.innerApiCalls.inspectContent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.inspectContent as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes inspectContent with closed client', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.InspectContentRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.InspectContentRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.InspectContentRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.inspectContent(request), expectedError); - }); + it('has universeDomain', () => { + const client = new dlpserviceModule.v2.DlpServiceClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); }); - describe('redactImage', () => { - it('invokes redactImage without error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.RedactImageRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.RedactImageRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.RedactImageRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.privacy.dlp.v2.RedactImageResponse() - ); - client.innerApiCalls.redactImage = stubSimpleCall(expectedResponse); - const [response] = await client.redactImage(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.redactImage as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.redactImage as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes redactImage without error using callback', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.RedactImageRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.RedactImageRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.RedactImageRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.privacy.dlp.v2.RedactImageResponse() - ); - client.innerApiCalls.redactImage = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.redactImage( - request, - (err?: Error|null, result?: protos.google.privacy.dlp.v2.IRedactImageResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.redactImage as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.redactImage as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes redactImage with error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.RedactImageRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.RedactImageRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.RedactImageRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.redactImage = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.redactImage(request), expectedError); - const actualRequest = (client.innerApiCalls.redactImage as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.redactImage as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes redactImage with closed client', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.RedactImageRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.RedactImageRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.RedactImageRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.redactImage(request), expectedError); - }); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = dlpserviceModule.v2.DlpServiceClient.servicePath; + assert.strictEqual(servicePath, 'dlp.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = dlpserviceModule.v2.DlpServiceClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'dlp.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + universeDomain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'dlp.example.com'); }); - describe('deidentifyContent', () => { - it('invokes deidentifyContent without error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.DeidentifyContentRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.DeidentifyContentRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.DeidentifyContentRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.privacy.dlp.v2.DeidentifyContentResponse() - ); - client.innerApiCalls.deidentifyContent = stubSimpleCall(expectedResponse); - const [response] = await client.deidentifyContent(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deidentifyContent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deidentifyContent as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes deidentifyContent without error using callback', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.DeidentifyContentRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.DeidentifyContentRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.DeidentifyContentRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.privacy.dlp.v2.DeidentifyContentResponse() - ); - client.innerApiCalls.deidentifyContent = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deidentifyContent( - request, - (err?: Error|null, result?: protos.google.privacy.dlp.v2.IDeidentifyContentResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deidentifyContent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deidentifyContent as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes deidentifyContent with error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.DeidentifyContentRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.DeidentifyContentRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.DeidentifyContentRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deidentifyContent = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deidentifyContent(request), expectedError); - const actualRequest = (client.innerApiCalls.deidentifyContent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deidentifyContent as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes deidentifyContent with closed client', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.DeidentifyContentRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.DeidentifyContentRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.DeidentifyContentRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deidentifyContent(request), expectedError); - }); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + universe_domain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'dlp.example.com'); }); - describe('reidentifyContent', () => { - it('invokes reidentifyContent without error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.ReidentifyContentRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.ReidentifyContentRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.ReidentifyContentRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.privacy.dlp.v2.ReidentifyContentResponse() - ); - client.innerApiCalls.reidentifyContent = stubSimpleCall(expectedResponse); - const [response] = await client.reidentifyContent(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.reidentifyContent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.reidentifyContent as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes reidentifyContent without error using callback', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.ReidentifyContentRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.ReidentifyContentRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.ReidentifyContentRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.privacy.dlp.v2.ReidentifyContentResponse() - ); - client.innerApiCalls.reidentifyContent = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.reidentifyContent( - request, - (err?: Error|null, result?: protos.google.privacy.dlp.v2.IReidentifyContentResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.reidentifyContent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.reidentifyContent as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes reidentifyContent with error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.ReidentifyContentRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.ReidentifyContentRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.ReidentifyContentRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.reidentifyContent = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.reidentifyContent(request), expectedError); - const actualRequest = (client.innerApiCalls.reidentifyContent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.reidentifyContent as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes reidentifyContent with closed client', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.ReidentifyContentRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.ReidentifyContentRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.ReidentifyContentRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.reidentifyContent(request), expectedError); + if (typeof process === 'object' && 'env' in process) { + describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { + it('sets apiEndpoint from environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new dlpserviceModule.v2.DlpServiceClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'dlp.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } + }); + + it('value configured in code has priority over environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new dlpserviceModule.v2.DlpServiceClient({ + universeDomain: 'configured.example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'dlp.configured.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } + }); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new dlpserviceModule.v2.DlpServiceClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); }); - describe('listInfoTypes', () => { - it('invokes listInfoTypes without error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.ListInfoTypesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListInfoTypesRequest', ['locationId']); - request.locationId = defaultValue1; - const expectedHeaderRequestParams = `location_id=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.privacy.dlp.v2.ListInfoTypesResponse() - ); - client.innerApiCalls.listInfoTypes = stubSimpleCall(expectedResponse); - const [response] = await client.listInfoTypes(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listInfoTypes as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listInfoTypes as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listInfoTypes without error using callback', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.ListInfoTypesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListInfoTypesRequest', ['locationId']); - request.locationId = defaultValue1; - const expectedHeaderRequestParams = `location_id=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.privacy.dlp.v2.ListInfoTypesResponse() - ); - client.innerApiCalls.listInfoTypes = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listInfoTypes( - request, - (err?: Error|null, result?: protos.google.privacy.dlp.v2.IListInfoTypesResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listInfoTypes as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listInfoTypes as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has port', () => { + const port = dlpserviceModule.v2.DlpServiceClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('invokes listInfoTypes with error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.ListInfoTypesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListInfoTypesRequest', ['locationId']); - request.locationId = defaultValue1; - const expectedHeaderRequestParams = `location_id=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listInfoTypes = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listInfoTypes(request), expectedError); - const actualRequest = (client.innerApiCalls.listInfoTypes as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listInfoTypes as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('should create a client with no option', () => { + const client = new dlpserviceModule.v2.DlpServiceClient(); + assert(client); + }); - it('invokes listInfoTypes with closed client', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.ListInfoTypesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListInfoTypesRequest', ['locationId']); - request.locationId = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.listInfoTypes(request), expectedError); - }); + it('should create a client with gRPC fallback', () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + fallback: true, + }); + assert(client); }); - describe('createInspectTemplate', () => { - it('invokes createInspectTemplate without error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.CreateInspectTemplateRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.CreateInspectTemplateRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.CreateInspectTemplateRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.privacy.dlp.v2.InspectTemplate() - ); - client.innerApiCalls.createInspectTemplate = stubSimpleCall(expectedResponse); - const [response] = await client.createInspectTemplate(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createInspectTemplate as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createInspectTemplate as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has initialize method and supports deferred initialization', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.dlpServiceStub, undefined); + await client.initialize(); + assert(client.dlpServiceStub); + }); - it('invokes createInspectTemplate without error using callback', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.CreateInspectTemplateRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.CreateInspectTemplateRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.CreateInspectTemplateRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.privacy.dlp.v2.InspectTemplate() - ); - client.innerApiCalls.createInspectTemplate = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createInspectTemplate( - request, - (err?: Error|null, result?: protos.google.privacy.dlp.v2.IInspectTemplate|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createInspectTemplate as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createInspectTemplate as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('has close method for the initialized client', (done) => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.dlpServiceStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes createInspectTemplate with error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.CreateInspectTemplateRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.CreateInspectTemplateRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.CreateInspectTemplateRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createInspectTemplate = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createInspectTemplate(request), expectedError); - const actualRequest = (client.innerApiCalls.createInspectTemplate as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createInspectTemplate as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('has close method for the non-initialized client', (done) => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.dlpServiceStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes createInspectTemplate with closed client', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.CreateInspectTemplateRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.CreateInspectTemplateRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.CreateInspectTemplateRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createInspectTemplate(request), expectedError); - }); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); }); - describe('updateInspectTemplate', () => { - it('invokes updateInspectTemplate without error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.UpdateInspectTemplateRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.UpdateInspectTemplateRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.privacy.dlp.v2.InspectTemplate() - ); - client.innerApiCalls.updateInspectTemplate = stubSimpleCall(expectedResponse); - const [response] = await client.updateInspectTemplate(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateInspectTemplate as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateInspectTemplate as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } + }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + }); + + describe('inspectContent', () => { + it('invokes inspectContent without error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.InspectContentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.InspectContentRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.InspectContentRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.privacy.dlp.v2.InspectContentResponse(), + ); + client.innerApiCalls.inspectContent = stubSimpleCall(expectedResponse); + const [response] = await client.inspectContent(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.inspectContent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.inspectContent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateInspectTemplate without error using callback', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.UpdateInspectTemplateRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.UpdateInspectTemplateRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.privacy.dlp.v2.InspectTemplate() - ); - client.innerApiCalls.updateInspectTemplate = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateInspectTemplate( - request, - (err?: Error|null, result?: protos.google.privacy.dlp.v2.IInspectTemplate|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateInspectTemplate as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateInspectTemplate as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes inspectContent without error using callback', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.InspectContentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.InspectContentRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.InspectContentRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.privacy.dlp.v2.InspectContentResponse(), + ); + client.innerApiCalls.inspectContent = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.inspectContent( + request, + ( + err?: Error | null, + result?: protos.google.privacy.dlp.v2.IInspectContentResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.inspectContent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.inspectContent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateInspectTemplate with error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.UpdateInspectTemplateRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.UpdateInspectTemplateRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateInspectTemplate = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateInspectTemplate(request), expectedError); - const actualRequest = (client.innerApiCalls.updateInspectTemplate as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateInspectTemplate as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes inspectContent with error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.InspectContentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.InspectContentRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.InspectContentRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.inspectContent = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.inspectContent(request), expectedError); + const actualRequest = ( + client.innerApiCalls.inspectContent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.inspectContent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateInspectTemplate with closed client', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.UpdateInspectTemplateRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.UpdateInspectTemplateRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateInspectTemplate(request), expectedError); - }); + it('invokes inspectContent with closed client', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.InspectContentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.InspectContentRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.InspectContentRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.inspectContent(request), expectedError); + }); + }); + + describe('redactImage', () => { + it('invokes redactImage without error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.RedactImageRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.RedactImageRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.RedactImageRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.privacy.dlp.v2.RedactImageResponse(), + ); + client.innerApiCalls.redactImage = stubSimpleCall(expectedResponse); + const [response] = await client.redactImage(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.redactImage as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.redactImage as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('getInspectTemplate', () => { - it('invokes getInspectTemplate without error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.GetInspectTemplateRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.GetInspectTemplateRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.privacy.dlp.v2.InspectTemplate() - ); - client.innerApiCalls.getInspectTemplate = stubSimpleCall(expectedResponse); - const [response] = await client.getInspectTemplate(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getInspectTemplate as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getInspectTemplate as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes redactImage without error using callback', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.RedactImageRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.RedactImageRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.RedactImageRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.privacy.dlp.v2.RedactImageResponse(), + ); + client.innerApiCalls.redactImage = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.redactImage( + request, + ( + err?: Error | null, + result?: protos.google.privacy.dlp.v2.IRedactImageResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.redactImage as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.redactImage as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getInspectTemplate without error using callback', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.GetInspectTemplateRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.GetInspectTemplateRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.privacy.dlp.v2.InspectTemplate() - ); - client.innerApiCalls.getInspectTemplate = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getInspectTemplate( - request, - (err?: Error|null, result?: protos.google.privacy.dlp.v2.IInspectTemplate|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getInspectTemplate as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getInspectTemplate as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes redactImage with error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.RedactImageRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.RedactImageRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.RedactImageRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.redactImage = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.redactImage(request), expectedError); + const actualRequest = ( + client.innerApiCalls.redactImage as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.redactImage as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getInspectTemplate with error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.GetInspectTemplateRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.GetInspectTemplateRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getInspectTemplate = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getInspectTemplate(request), expectedError); - const actualRequest = (client.innerApiCalls.getInspectTemplate as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getInspectTemplate as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes redactImage with closed client', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.RedactImageRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.RedactImageRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.RedactImageRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.redactImage(request), expectedError); + }); + }); + + describe('deidentifyContent', () => { + it('invokes deidentifyContent without error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.DeidentifyContentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.DeidentifyContentRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.DeidentifyContentRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.privacy.dlp.v2.DeidentifyContentResponse(), + ); + client.innerApiCalls.deidentifyContent = stubSimpleCall(expectedResponse); + const [response] = await client.deidentifyContent(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deidentifyContent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deidentifyContent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getInspectTemplate with closed client', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.GetInspectTemplateRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.GetInspectTemplateRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getInspectTemplate(request), expectedError); - }); + it('invokes deidentifyContent without error using callback', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.DeidentifyContentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.DeidentifyContentRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.DeidentifyContentRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.privacy.dlp.v2.DeidentifyContentResponse(), + ); + client.innerApiCalls.deidentifyContent = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deidentifyContent( + request, + ( + err?: Error | null, + result?: protos.google.privacy.dlp.v2.IDeidentifyContentResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deidentifyContent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deidentifyContent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('deleteInspectTemplate', () => { - it('invokes deleteInspectTemplate without error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.DeleteInspectTemplateRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.DeleteInspectTemplateRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteInspectTemplate = stubSimpleCall(expectedResponse); - const [response] = await client.deleteInspectTemplate(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteInspectTemplate as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteInspectTemplate as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deidentifyContent with error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.DeidentifyContentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.DeidentifyContentRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.DeidentifyContentRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deidentifyContent = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.deidentifyContent(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deidentifyContent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deidentifyContent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteInspectTemplate without error using callback', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.DeleteInspectTemplateRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.DeleteInspectTemplateRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteInspectTemplate = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteInspectTemplate( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteInspectTemplate as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteInspectTemplate as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deidentifyContent with closed client', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.DeidentifyContentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.DeidentifyContentRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.DeidentifyContentRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.deidentifyContent(request), expectedError); + }); + }); + + describe('reidentifyContent', () => { + it('invokes reidentifyContent without error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.ReidentifyContentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ReidentifyContentRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ReidentifyContentRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.privacy.dlp.v2.ReidentifyContentResponse(), + ); + client.innerApiCalls.reidentifyContent = stubSimpleCall(expectedResponse); + const [response] = await client.reidentifyContent(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.reidentifyContent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.reidentifyContent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteInspectTemplate with error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.DeleteInspectTemplateRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.DeleteInspectTemplateRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteInspectTemplate = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteInspectTemplate(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteInspectTemplate as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteInspectTemplate as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes reidentifyContent without error using callback', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.ReidentifyContentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ReidentifyContentRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ReidentifyContentRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.privacy.dlp.v2.ReidentifyContentResponse(), + ); + client.innerApiCalls.reidentifyContent = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.reidentifyContent( + request, + ( + err?: Error | null, + result?: protos.google.privacy.dlp.v2.IReidentifyContentResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.reidentifyContent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.reidentifyContent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteInspectTemplate with closed client', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.DeleteInspectTemplateRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.DeleteInspectTemplateRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteInspectTemplate(request), expectedError); - }); + it('invokes reidentifyContent with error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.ReidentifyContentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ReidentifyContentRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ReidentifyContentRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.reidentifyContent = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.reidentifyContent(request), expectedError); + const actualRequest = ( + client.innerApiCalls.reidentifyContent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.reidentifyContent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('createDeidentifyTemplate', () => { - it('invokes createDeidentifyTemplate without error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.CreateDeidentifyTemplateRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.CreateDeidentifyTemplateRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.CreateDeidentifyTemplateRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.privacy.dlp.v2.DeidentifyTemplate() - ); - client.innerApiCalls.createDeidentifyTemplate = stubSimpleCall(expectedResponse); - const [response] = await client.createDeidentifyTemplate(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createDeidentifyTemplate as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createDeidentifyTemplate as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes reidentifyContent with closed client', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.ReidentifyContentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ReidentifyContentRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ReidentifyContentRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.reidentifyContent(request), expectedError); + }); + }); + + describe('listInfoTypes', () => { + it('invokes listInfoTypes without error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.ListInfoTypesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListInfoTypesRequest', + ['locationId'], + ); + request.locationId = defaultValue1; + const expectedHeaderRequestParams = `location_id=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.privacy.dlp.v2.ListInfoTypesResponse(), + ); + client.innerApiCalls.listInfoTypes = stubSimpleCall(expectedResponse); + const [response] = await client.listInfoTypes(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listInfoTypes as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listInfoTypes as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createDeidentifyTemplate without error using callback', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.CreateDeidentifyTemplateRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.CreateDeidentifyTemplateRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.CreateDeidentifyTemplateRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.privacy.dlp.v2.DeidentifyTemplate() - ); - client.innerApiCalls.createDeidentifyTemplate = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createDeidentifyTemplate( - request, - (err?: Error|null, result?: protos.google.privacy.dlp.v2.IDeidentifyTemplate|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createDeidentifyTemplate as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createDeidentifyTemplate as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listInfoTypes without error using callback', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.ListInfoTypesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListInfoTypesRequest', + ['locationId'], + ); + request.locationId = defaultValue1; + const expectedHeaderRequestParams = `location_id=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.privacy.dlp.v2.ListInfoTypesResponse(), + ); + client.innerApiCalls.listInfoTypes = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listInfoTypes( + request, + ( + err?: Error | null, + result?: protos.google.privacy.dlp.v2.IListInfoTypesResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listInfoTypes as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listInfoTypes as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createDeidentifyTemplate with error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.CreateDeidentifyTemplateRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.CreateDeidentifyTemplateRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.CreateDeidentifyTemplateRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createDeidentifyTemplate = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createDeidentifyTemplate(request), expectedError); - const actualRequest = (client.innerApiCalls.createDeidentifyTemplate as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createDeidentifyTemplate as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listInfoTypes with error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.ListInfoTypesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListInfoTypesRequest', + ['locationId'], + ); + request.locationId = defaultValue1; + const expectedHeaderRequestParams = `location_id=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listInfoTypes = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listInfoTypes(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listInfoTypes as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listInfoTypes as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createDeidentifyTemplate with closed client', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.CreateDeidentifyTemplateRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.CreateDeidentifyTemplateRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.CreateDeidentifyTemplateRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createDeidentifyTemplate(request), expectedError); - }); + it('invokes listInfoTypes with closed client', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.ListInfoTypesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListInfoTypesRequest', + ['locationId'], + ); + request.locationId = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.listInfoTypes(request), expectedError); + }); + }); + + describe('createInspectTemplate', () => { + it('invokes createInspectTemplate without error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.CreateInspectTemplateRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.CreateInspectTemplateRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.CreateInspectTemplateRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.privacy.dlp.v2.InspectTemplate(), + ); + client.innerApiCalls.createInspectTemplate = + stubSimpleCall(expectedResponse); + const [response] = await client.createInspectTemplate(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createInspectTemplate as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createInspectTemplate as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('updateDeidentifyTemplate', () => { - it('invokes updateDeidentifyTemplate without error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.UpdateDeidentifyTemplateRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.UpdateDeidentifyTemplateRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.privacy.dlp.v2.DeidentifyTemplate() - ); - client.innerApiCalls.updateDeidentifyTemplate = stubSimpleCall(expectedResponse); - const [response] = await client.updateDeidentifyTemplate(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateDeidentifyTemplate as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateDeidentifyTemplate as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createInspectTemplate without error using callback', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.CreateInspectTemplateRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.CreateInspectTemplateRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.CreateInspectTemplateRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.privacy.dlp.v2.InspectTemplate(), + ); + client.innerApiCalls.createInspectTemplate = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createInspectTemplate( + request, + ( + err?: Error | null, + result?: protos.google.privacy.dlp.v2.IInspectTemplate | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createInspectTemplate as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createInspectTemplate as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateDeidentifyTemplate without error using callback', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.UpdateDeidentifyTemplateRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.UpdateDeidentifyTemplateRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.privacy.dlp.v2.DeidentifyTemplate() - ); - client.innerApiCalls.updateDeidentifyTemplate = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateDeidentifyTemplate( - request, - (err?: Error|null, result?: protos.google.privacy.dlp.v2.IDeidentifyTemplate|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateDeidentifyTemplate as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateDeidentifyTemplate as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createInspectTemplate with error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.CreateInspectTemplateRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.CreateInspectTemplateRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.CreateInspectTemplateRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createInspectTemplate = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.createInspectTemplate(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.createInspectTemplate as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createInspectTemplate as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateDeidentifyTemplate with error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.UpdateDeidentifyTemplateRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.UpdateDeidentifyTemplateRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateDeidentifyTemplate = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateDeidentifyTemplate(request), expectedError); - const actualRequest = (client.innerApiCalls.updateDeidentifyTemplate as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateDeidentifyTemplate as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createInspectTemplate with closed client', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.CreateInspectTemplateRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.CreateInspectTemplateRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.CreateInspectTemplateRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.createInspectTemplate(request), + expectedError, + ); + }); + }); + + describe('updateInspectTemplate', () => { + it('invokes updateInspectTemplate without error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.UpdateInspectTemplateRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.UpdateInspectTemplateRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.privacy.dlp.v2.InspectTemplate(), + ); + client.innerApiCalls.updateInspectTemplate = + stubSimpleCall(expectedResponse); + const [response] = await client.updateInspectTemplate(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateInspectTemplate as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateInspectTemplate as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateDeidentifyTemplate with closed client', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.UpdateDeidentifyTemplateRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.UpdateDeidentifyTemplateRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateDeidentifyTemplate(request), expectedError); - }); + it('invokes updateInspectTemplate without error using callback', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.UpdateInspectTemplateRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.UpdateInspectTemplateRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.privacy.dlp.v2.InspectTemplate(), + ); + client.innerApiCalls.updateInspectTemplate = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateInspectTemplate( + request, + ( + err?: Error | null, + result?: protos.google.privacy.dlp.v2.IInspectTemplate | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateInspectTemplate as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateInspectTemplate as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('getDeidentifyTemplate', () => { - it('invokes getDeidentifyTemplate without error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.GetDeidentifyTemplateRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.GetDeidentifyTemplateRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.privacy.dlp.v2.DeidentifyTemplate() - ); - client.innerApiCalls.getDeidentifyTemplate = stubSimpleCall(expectedResponse); - const [response] = await client.getDeidentifyTemplate(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getDeidentifyTemplate as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getDeidentifyTemplate as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateInspectTemplate with error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.UpdateInspectTemplateRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.UpdateInspectTemplateRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateInspectTemplate = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.updateInspectTemplate(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.updateInspectTemplate as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateInspectTemplate as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getDeidentifyTemplate without error using callback', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.GetDeidentifyTemplateRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.GetDeidentifyTemplateRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.privacy.dlp.v2.DeidentifyTemplate() - ); - client.innerApiCalls.getDeidentifyTemplate = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getDeidentifyTemplate( - request, - (err?: Error|null, result?: protos.google.privacy.dlp.v2.IDeidentifyTemplate|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getDeidentifyTemplate as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getDeidentifyTemplate as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateInspectTemplate with closed client', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.UpdateInspectTemplateRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.UpdateInspectTemplateRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.updateInspectTemplate(request), + expectedError, + ); + }); + }); + + describe('getInspectTemplate', () => { + it('invokes getInspectTemplate without error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.GetInspectTemplateRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.GetInspectTemplateRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.privacy.dlp.v2.InspectTemplate(), + ); + client.innerApiCalls.getInspectTemplate = + stubSimpleCall(expectedResponse); + const [response] = await client.getInspectTemplate(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getInspectTemplate as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getInspectTemplate as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getDeidentifyTemplate with error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.GetDeidentifyTemplateRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.GetDeidentifyTemplateRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getDeidentifyTemplate = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getDeidentifyTemplate(request), expectedError); - const actualRequest = (client.innerApiCalls.getDeidentifyTemplate as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getDeidentifyTemplate as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getInspectTemplate without error using callback', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.GetInspectTemplateRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.GetInspectTemplateRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.privacy.dlp.v2.InspectTemplate(), + ); + client.innerApiCalls.getInspectTemplate = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getInspectTemplate( + request, + ( + err?: Error | null, + result?: protos.google.privacy.dlp.v2.IInspectTemplate | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getInspectTemplate as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getInspectTemplate as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getDeidentifyTemplate with closed client', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.GetDeidentifyTemplateRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.GetDeidentifyTemplateRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getDeidentifyTemplate(request), expectedError); - }); + it('invokes getInspectTemplate with error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.GetInspectTemplateRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.GetInspectTemplateRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getInspectTemplate = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getInspectTemplate(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getInspectTemplate as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getInspectTemplate as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('deleteDeidentifyTemplate', () => { - it('invokes deleteDeidentifyTemplate without error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.DeleteDeidentifyTemplateRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.DeleteDeidentifyTemplateRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteDeidentifyTemplate = stubSimpleCall(expectedResponse); - const [response] = await client.deleteDeidentifyTemplate(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteDeidentifyTemplate as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteDeidentifyTemplate as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getInspectTemplate with closed client', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.GetInspectTemplateRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.GetInspectTemplateRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getInspectTemplate(request), expectedError); + }); + }); + + describe('deleteInspectTemplate', () => { + it('invokes deleteInspectTemplate without error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.DeleteInspectTemplateRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.DeleteInspectTemplateRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteInspectTemplate = + stubSimpleCall(expectedResponse); + const [response] = await client.deleteInspectTemplate(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteInspectTemplate as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteInspectTemplate as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteDeidentifyTemplate without error using callback', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.DeleteDeidentifyTemplateRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.DeleteDeidentifyTemplateRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteDeidentifyTemplate = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteDeidentifyTemplate( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteDeidentifyTemplate as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteDeidentifyTemplate as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteInspectTemplate without error using callback', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.DeleteInspectTemplateRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.DeleteInspectTemplateRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteInspectTemplate = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteInspectTemplate( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteInspectTemplate as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteInspectTemplate as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteDeidentifyTemplate with error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.DeleteDeidentifyTemplateRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.DeleteDeidentifyTemplateRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteDeidentifyTemplate = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteDeidentifyTemplate(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteDeidentifyTemplate as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteDeidentifyTemplate as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteInspectTemplate with error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.DeleteInspectTemplateRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.DeleteInspectTemplateRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteInspectTemplate = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.deleteInspectTemplate(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.deleteInspectTemplate as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteInspectTemplate as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteDeidentifyTemplate with closed client', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.DeleteDeidentifyTemplateRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.DeleteDeidentifyTemplateRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteDeidentifyTemplate(request), expectedError); - }); + it('invokes deleteInspectTemplate with closed client', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.DeleteInspectTemplateRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.DeleteInspectTemplateRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.deleteInspectTemplate(request), + expectedError, + ); + }); + }); + + describe('createDeidentifyTemplate', () => { + it('invokes createDeidentifyTemplate without error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.CreateDeidentifyTemplateRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.CreateDeidentifyTemplateRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.CreateDeidentifyTemplateRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.privacy.dlp.v2.DeidentifyTemplate(), + ); + client.innerApiCalls.createDeidentifyTemplate = + stubSimpleCall(expectedResponse); + const [response] = await client.createDeidentifyTemplate(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createDeidentifyTemplate as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createDeidentifyTemplate as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('createJobTrigger', () => { - it('invokes createJobTrigger without error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.CreateJobTriggerRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.CreateJobTriggerRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.CreateJobTriggerRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.privacy.dlp.v2.JobTrigger() - ); - client.innerApiCalls.createJobTrigger = stubSimpleCall(expectedResponse); - const [response] = await client.createJobTrigger(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createJobTrigger as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createJobTrigger as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createDeidentifyTemplate without error using callback', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.CreateDeidentifyTemplateRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.CreateDeidentifyTemplateRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.CreateDeidentifyTemplateRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.privacy.dlp.v2.DeidentifyTemplate(), + ); + client.innerApiCalls.createDeidentifyTemplate = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createDeidentifyTemplate( + request, + ( + err?: Error | null, + result?: protos.google.privacy.dlp.v2.IDeidentifyTemplate | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createDeidentifyTemplate as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createDeidentifyTemplate as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createJobTrigger without error using callback', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.CreateJobTriggerRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.CreateJobTriggerRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.CreateJobTriggerRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.privacy.dlp.v2.JobTrigger() - ); - client.innerApiCalls.createJobTrigger = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createJobTrigger( - request, - (err?: Error|null, result?: protos.google.privacy.dlp.v2.IJobTrigger|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createJobTrigger as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createJobTrigger as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createDeidentifyTemplate with error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.CreateDeidentifyTemplateRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.CreateDeidentifyTemplateRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.CreateDeidentifyTemplateRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createDeidentifyTemplate = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.createDeidentifyTemplate(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.createDeidentifyTemplate as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createDeidentifyTemplate as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createJobTrigger with error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.CreateJobTriggerRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.CreateJobTriggerRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.CreateJobTriggerRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createJobTrigger = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createJobTrigger(request), expectedError); - const actualRequest = (client.innerApiCalls.createJobTrigger as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createJobTrigger as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createDeidentifyTemplate with closed client', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.CreateDeidentifyTemplateRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.CreateDeidentifyTemplateRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.CreateDeidentifyTemplateRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.createDeidentifyTemplate(request), + expectedError, + ); + }); + }); + + describe('updateDeidentifyTemplate', () => { + it('invokes updateDeidentifyTemplate without error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.UpdateDeidentifyTemplateRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.UpdateDeidentifyTemplateRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.privacy.dlp.v2.DeidentifyTemplate(), + ); + client.innerApiCalls.updateDeidentifyTemplate = + stubSimpleCall(expectedResponse); + const [response] = await client.updateDeidentifyTemplate(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateDeidentifyTemplate as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateDeidentifyTemplate as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createJobTrigger with closed client', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.CreateJobTriggerRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.CreateJobTriggerRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.CreateJobTriggerRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createJobTrigger(request), expectedError); - }); + it('invokes updateDeidentifyTemplate without error using callback', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.UpdateDeidentifyTemplateRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.UpdateDeidentifyTemplateRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.privacy.dlp.v2.DeidentifyTemplate(), + ); + client.innerApiCalls.updateDeidentifyTemplate = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateDeidentifyTemplate( + request, + ( + err?: Error | null, + result?: protos.google.privacy.dlp.v2.IDeidentifyTemplate | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateDeidentifyTemplate as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateDeidentifyTemplate as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('updateJobTrigger', () => { - it('invokes updateJobTrigger without error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.UpdateJobTriggerRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.UpdateJobTriggerRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.privacy.dlp.v2.JobTrigger() - ); - client.innerApiCalls.updateJobTrigger = stubSimpleCall(expectedResponse); - const [response] = await client.updateJobTrigger(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateJobTrigger as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateJobTrigger as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateDeidentifyTemplate with error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.UpdateDeidentifyTemplateRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.UpdateDeidentifyTemplateRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateDeidentifyTemplate = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.updateDeidentifyTemplate(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.updateDeidentifyTemplate as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateDeidentifyTemplate as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateJobTrigger without error using callback', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.UpdateJobTriggerRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.UpdateJobTriggerRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.privacy.dlp.v2.JobTrigger() - ); - client.innerApiCalls.updateJobTrigger = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateJobTrigger( - request, - (err?: Error|null, result?: protos.google.privacy.dlp.v2.IJobTrigger|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateJobTrigger as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateJobTrigger as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateDeidentifyTemplate with closed client', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.UpdateDeidentifyTemplateRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.UpdateDeidentifyTemplateRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.updateDeidentifyTemplate(request), + expectedError, + ); + }); + }); + + describe('getDeidentifyTemplate', () => { + it('invokes getDeidentifyTemplate without error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.GetDeidentifyTemplateRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.GetDeidentifyTemplateRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.privacy.dlp.v2.DeidentifyTemplate(), + ); + client.innerApiCalls.getDeidentifyTemplate = + stubSimpleCall(expectedResponse); + const [response] = await client.getDeidentifyTemplate(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getDeidentifyTemplate as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getDeidentifyTemplate as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateJobTrigger with error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.UpdateJobTriggerRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.UpdateJobTriggerRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateJobTrigger = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateJobTrigger(request), expectedError); - const actualRequest = (client.innerApiCalls.updateJobTrigger as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateJobTrigger as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getDeidentifyTemplate without error using callback', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.GetDeidentifyTemplateRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.GetDeidentifyTemplateRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.privacy.dlp.v2.DeidentifyTemplate(), + ); + client.innerApiCalls.getDeidentifyTemplate = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getDeidentifyTemplate( + request, + ( + err?: Error | null, + result?: protos.google.privacy.dlp.v2.IDeidentifyTemplate | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getDeidentifyTemplate as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getDeidentifyTemplate as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateJobTrigger with closed client', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.UpdateJobTriggerRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.UpdateJobTriggerRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateJobTrigger(request), expectedError); - }); + it('invokes getDeidentifyTemplate with error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.GetDeidentifyTemplateRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.GetDeidentifyTemplateRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getDeidentifyTemplate = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.getDeidentifyTemplate(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.getDeidentifyTemplate as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getDeidentifyTemplate as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('getJobTrigger', () => { - it('invokes getJobTrigger without error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.GetJobTriggerRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.GetJobTriggerRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.privacy.dlp.v2.JobTrigger() - ); - client.innerApiCalls.getJobTrigger = stubSimpleCall(expectedResponse); - const [response] = await client.getJobTrigger(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getJobTrigger as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getJobTrigger as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getDeidentifyTemplate with closed client', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.GetDeidentifyTemplateRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.GetDeidentifyTemplateRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.getDeidentifyTemplate(request), + expectedError, + ); + }); + }); + + describe('deleteDeidentifyTemplate', () => { + it('invokes deleteDeidentifyTemplate without error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.DeleteDeidentifyTemplateRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.DeleteDeidentifyTemplateRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteDeidentifyTemplate = + stubSimpleCall(expectedResponse); + const [response] = await client.deleteDeidentifyTemplate(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteDeidentifyTemplate as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteDeidentifyTemplate as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getJobTrigger without error using callback', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.GetJobTriggerRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.GetJobTriggerRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.privacy.dlp.v2.JobTrigger() - ); - client.innerApiCalls.getJobTrigger = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getJobTrigger( - request, - (err?: Error|null, result?: protos.google.privacy.dlp.v2.IJobTrigger|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getJobTrigger as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getJobTrigger as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteDeidentifyTemplate without error using callback', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.DeleteDeidentifyTemplateRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.DeleteDeidentifyTemplateRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteDeidentifyTemplate = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteDeidentifyTemplate( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteDeidentifyTemplate as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteDeidentifyTemplate as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getJobTrigger with error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.GetJobTriggerRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.GetJobTriggerRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getJobTrigger = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getJobTrigger(request), expectedError); - const actualRequest = (client.innerApiCalls.getJobTrigger as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getJobTrigger as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteDeidentifyTemplate with error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.DeleteDeidentifyTemplateRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.DeleteDeidentifyTemplateRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteDeidentifyTemplate = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.deleteDeidentifyTemplate(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.deleteDeidentifyTemplate as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteDeidentifyTemplate as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getJobTrigger with closed client', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.GetJobTriggerRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.GetJobTriggerRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getJobTrigger(request), expectedError); - }); + it('invokes deleteDeidentifyTemplate with closed client', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.DeleteDeidentifyTemplateRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.DeleteDeidentifyTemplateRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.deleteDeidentifyTemplate(request), + expectedError, + ); + }); + }); + + describe('createJobTrigger', () => { + it('invokes createJobTrigger without error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.CreateJobTriggerRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.CreateJobTriggerRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.CreateJobTriggerRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.privacy.dlp.v2.JobTrigger(), + ); + client.innerApiCalls.createJobTrigger = stubSimpleCall(expectedResponse); + const [response] = await client.createJobTrigger(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createJobTrigger as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createJobTrigger as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('deleteJobTrigger', () => { - it('invokes deleteJobTrigger without error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.DeleteJobTriggerRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.DeleteJobTriggerRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteJobTrigger = stubSimpleCall(expectedResponse); - const [response] = await client.deleteJobTrigger(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteJobTrigger as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteJobTrigger as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createJobTrigger without error using callback', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.CreateJobTriggerRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.CreateJobTriggerRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.CreateJobTriggerRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.privacy.dlp.v2.JobTrigger(), + ); + client.innerApiCalls.createJobTrigger = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createJobTrigger( + request, + ( + err?: Error | null, + result?: protos.google.privacy.dlp.v2.IJobTrigger | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createJobTrigger as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createJobTrigger as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteJobTrigger without error using callback', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.DeleteJobTriggerRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.DeleteJobTriggerRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteJobTrigger = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteJobTrigger( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteJobTrigger as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteJobTrigger as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createJobTrigger with error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.CreateJobTriggerRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.CreateJobTriggerRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.CreateJobTriggerRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createJobTrigger = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.createJobTrigger(request), expectedError); + const actualRequest = ( + client.innerApiCalls.createJobTrigger as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createJobTrigger as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteJobTrigger with error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.DeleteJobTriggerRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.DeleteJobTriggerRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteJobTrigger = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteJobTrigger(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteJobTrigger as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteJobTrigger as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createJobTrigger with closed client', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.CreateJobTriggerRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.CreateJobTriggerRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.CreateJobTriggerRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.createJobTrigger(request), expectedError); + }); + }); + + describe('updateJobTrigger', () => { + it('invokes updateJobTrigger without error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.UpdateJobTriggerRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.UpdateJobTriggerRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.privacy.dlp.v2.JobTrigger(), + ); + client.innerApiCalls.updateJobTrigger = stubSimpleCall(expectedResponse); + const [response] = await client.updateJobTrigger(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateJobTrigger as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateJobTrigger as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteJobTrigger with closed client', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.DeleteJobTriggerRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.DeleteJobTriggerRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteJobTrigger(request), expectedError); - }); + it('invokes updateJobTrigger without error using callback', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.UpdateJobTriggerRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.UpdateJobTriggerRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.privacy.dlp.v2.JobTrigger(), + ); + client.innerApiCalls.updateJobTrigger = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateJobTrigger( + request, + ( + err?: Error | null, + result?: protos.google.privacy.dlp.v2.IJobTrigger | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateJobTrigger as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateJobTrigger as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('activateJobTrigger', () => { - it('invokes activateJobTrigger without error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.ActivateJobTriggerRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.ActivateJobTriggerRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.privacy.dlp.v2.DlpJob() - ); - client.innerApiCalls.activateJobTrigger = stubSimpleCall(expectedResponse); - const [response] = await client.activateJobTrigger(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.activateJobTrigger as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.activateJobTrigger as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateJobTrigger with error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.UpdateJobTriggerRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.UpdateJobTriggerRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateJobTrigger = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.updateJobTrigger(request), expectedError); + const actualRequest = ( + client.innerApiCalls.updateJobTrigger as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateJobTrigger as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes activateJobTrigger without error using callback', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.ActivateJobTriggerRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.ActivateJobTriggerRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.privacy.dlp.v2.DlpJob() - ); - client.innerApiCalls.activateJobTrigger = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.activateJobTrigger( - request, - (err?: Error|null, result?: protos.google.privacy.dlp.v2.IDlpJob|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.activateJobTrigger as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.activateJobTrigger as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateJobTrigger with closed client', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.UpdateJobTriggerRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.UpdateJobTriggerRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.updateJobTrigger(request), expectedError); + }); + }); + + describe('getJobTrigger', () => { + it('invokes getJobTrigger without error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.GetJobTriggerRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.GetJobTriggerRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.privacy.dlp.v2.JobTrigger(), + ); + client.innerApiCalls.getJobTrigger = stubSimpleCall(expectedResponse); + const [response] = await client.getJobTrigger(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getJobTrigger as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getJobTrigger as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes activateJobTrigger with error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.ActivateJobTriggerRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.ActivateJobTriggerRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.activateJobTrigger = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.activateJobTrigger(request), expectedError); - const actualRequest = (client.innerApiCalls.activateJobTrigger as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.activateJobTrigger as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getJobTrigger without error using callback', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.GetJobTriggerRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.GetJobTriggerRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.privacy.dlp.v2.JobTrigger(), + ); + client.innerApiCalls.getJobTrigger = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getJobTrigger( + request, + ( + err?: Error | null, + result?: protos.google.privacy.dlp.v2.IJobTrigger | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getJobTrigger as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getJobTrigger as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes activateJobTrigger with closed client', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.ActivateJobTriggerRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.ActivateJobTriggerRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.activateJobTrigger(request), expectedError); - }); + it('invokes getJobTrigger with error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.GetJobTriggerRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.GetJobTriggerRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getJobTrigger = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getJobTrigger(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getJobTrigger as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getJobTrigger as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('createDlpJob', () => { - it('invokes createDlpJob without error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.CreateDlpJobRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.CreateDlpJobRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.CreateDlpJobRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.privacy.dlp.v2.DlpJob() - ); - client.innerApiCalls.createDlpJob = stubSimpleCall(expectedResponse); - const [response] = await client.createDlpJob(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createDlpJob as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createDlpJob as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getJobTrigger with closed client', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.GetJobTriggerRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.GetJobTriggerRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getJobTrigger(request), expectedError); + }); + }); + + describe('deleteJobTrigger', () => { + it('invokes deleteJobTrigger without error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.DeleteJobTriggerRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.DeleteJobTriggerRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteJobTrigger = stubSimpleCall(expectedResponse); + const [response] = await client.deleteJobTrigger(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteJobTrigger as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteJobTrigger as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createDlpJob without error using callback', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.CreateDlpJobRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.CreateDlpJobRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.CreateDlpJobRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.privacy.dlp.v2.DlpJob() - ); - client.innerApiCalls.createDlpJob = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createDlpJob( - request, - (err?: Error|null, result?: protos.google.privacy.dlp.v2.IDlpJob|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createDlpJob as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createDlpJob as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteJobTrigger without error using callback', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.DeleteJobTriggerRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.DeleteJobTriggerRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteJobTrigger = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteJobTrigger( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteJobTrigger as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteJobTrigger as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createDlpJob with error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.CreateDlpJobRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.CreateDlpJobRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.CreateDlpJobRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createDlpJob = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createDlpJob(request), expectedError); - const actualRequest = (client.innerApiCalls.createDlpJob as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createDlpJob as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteJobTrigger with error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.DeleteJobTriggerRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.DeleteJobTriggerRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteJobTrigger = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.deleteJobTrigger(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteJobTrigger as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteJobTrigger as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createDlpJob with closed client', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.CreateDlpJobRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.CreateDlpJobRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.CreateDlpJobRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createDlpJob(request), expectedError); - }); + it('invokes deleteJobTrigger with closed client', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.DeleteJobTriggerRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.DeleteJobTriggerRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.deleteJobTrigger(request), expectedError); + }); + }); + + describe('activateJobTrigger', () => { + it('invokes activateJobTrigger without error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.ActivateJobTriggerRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ActivateJobTriggerRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.privacy.dlp.v2.DlpJob(), + ); + client.innerApiCalls.activateJobTrigger = + stubSimpleCall(expectedResponse); + const [response] = await client.activateJobTrigger(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.activateJobTrigger as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.activateJobTrigger as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('getDlpJob', () => { - it('invokes getDlpJob without error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.GetDlpJobRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.GetDlpJobRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.privacy.dlp.v2.DlpJob() - ); - client.innerApiCalls.getDlpJob = stubSimpleCall(expectedResponse); - const [response] = await client.getDlpJob(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getDlpJob as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getDlpJob as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes activateJobTrigger without error using callback', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.ActivateJobTriggerRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ActivateJobTriggerRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.privacy.dlp.v2.DlpJob(), + ); + client.innerApiCalls.activateJobTrigger = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.activateJobTrigger( + request, + ( + err?: Error | null, + result?: protos.google.privacy.dlp.v2.IDlpJob | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.activateJobTrigger as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.activateJobTrigger as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getDlpJob without error using callback', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.GetDlpJobRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.GetDlpJobRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.privacy.dlp.v2.DlpJob() - ); - client.innerApiCalls.getDlpJob = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getDlpJob( - request, - (err?: Error|null, result?: protos.google.privacy.dlp.v2.IDlpJob|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getDlpJob as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getDlpJob as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes activateJobTrigger with error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.ActivateJobTriggerRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ActivateJobTriggerRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.activateJobTrigger = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.activateJobTrigger(request), expectedError); + const actualRequest = ( + client.innerApiCalls.activateJobTrigger as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.activateJobTrigger as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getDlpJob with error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.GetDlpJobRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.GetDlpJobRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getDlpJob = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getDlpJob(request), expectedError); - const actualRequest = (client.innerApiCalls.getDlpJob as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getDlpJob as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes activateJobTrigger with closed client', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.ActivateJobTriggerRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ActivateJobTriggerRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.activateJobTrigger(request), expectedError); + }); + }); + + describe('createDlpJob', () => { + it('invokes createDlpJob without error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.CreateDlpJobRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.CreateDlpJobRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.CreateDlpJobRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.privacy.dlp.v2.DlpJob(), + ); + client.innerApiCalls.createDlpJob = stubSimpleCall(expectedResponse); + const [response] = await client.createDlpJob(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createDlpJob as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createDlpJob as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getDlpJob with closed client', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.GetDlpJobRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.GetDlpJobRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getDlpJob(request), expectedError); - }); + it('invokes createDlpJob without error using callback', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.CreateDlpJobRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.CreateDlpJobRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.CreateDlpJobRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.privacy.dlp.v2.DlpJob(), + ); + client.innerApiCalls.createDlpJob = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createDlpJob( + request, + ( + err?: Error | null, + result?: protos.google.privacy.dlp.v2.IDlpJob | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createDlpJob as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createDlpJob as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('deleteDlpJob', () => { - it('invokes deleteDlpJob without error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.DeleteDlpJobRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.DeleteDlpJobRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteDlpJob = stubSimpleCall(expectedResponse); - const [response] = await client.deleteDlpJob(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteDlpJob as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteDlpJob as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createDlpJob with error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.CreateDlpJobRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.CreateDlpJobRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.CreateDlpJobRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createDlpJob = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.createDlpJob(request), expectedError); + const actualRequest = ( + client.innerApiCalls.createDlpJob as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createDlpJob as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteDlpJob without error using callback', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.DeleteDlpJobRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.DeleteDlpJobRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteDlpJob = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteDlpJob( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteDlpJob as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteDlpJob as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createDlpJob with closed client', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.CreateDlpJobRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.CreateDlpJobRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.CreateDlpJobRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.createDlpJob(request), expectedError); + }); + }); + + describe('getDlpJob', () => { + it('invokes getDlpJob without error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.GetDlpJobRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.GetDlpJobRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.privacy.dlp.v2.DlpJob(), + ); + client.innerApiCalls.getDlpJob = stubSimpleCall(expectedResponse); + const [response] = await client.getDlpJob(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getDlpJob as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getDlpJob as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteDlpJob with error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.DeleteDlpJobRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.DeleteDlpJobRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteDlpJob = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteDlpJob(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteDlpJob as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteDlpJob as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getDlpJob without error using callback', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.GetDlpJobRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.GetDlpJobRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.privacy.dlp.v2.DlpJob(), + ); + client.innerApiCalls.getDlpJob = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getDlpJob( + request, + ( + err?: Error | null, + result?: protos.google.privacy.dlp.v2.IDlpJob | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getDlpJob as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getDlpJob as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteDlpJob with closed client', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.DeleteDlpJobRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.DeleteDlpJobRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteDlpJob(request), expectedError); - }); + it('invokes getDlpJob with error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.GetDlpJobRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.GetDlpJobRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getDlpJob = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.getDlpJob(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getDlpJob as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getDlpJob as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('cancelDlpJob', () => { - it('invokes cancelDlpJob without error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.CancelDlpJobRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.CancelDlpJobRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.cancelDlpJob = stubSimpleCall(expectedResponse); - const [response] = await client.cancelDlpJob(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.cancelDlpJob as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.cancelDlpJob as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getDlpJob with closed client', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.GetDlpJobRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.GetDlpJobRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getDlpJob(request), expectedError); + }); + }); + + describe('deleteDlpJob', () => { + it('invokes deleteDlpJob without error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.DeleteDlpJobRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.DeleteDlpJobRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteDlpJob = stubSimpleCall(expectedResponse); + const [response] = await client.deleteDlpJob(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteDlpJob as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteDlpJob as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes cancelDlpJob without error using callback', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.CancelDlpJobRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.CancelDlpJobRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.cancelDlpJob = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.cancelDlpJob( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.cancelDlpJob as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.cancelDlpJob as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteDlpJob without error using callback', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.DeleteDlpJobRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.DeleteDlpJobRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteDlpJob = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteDlpJob( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteDlpJob as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteDlpJob as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes cancelDlpJob with error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.CancelDlpJobRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.CancelDlpJobRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.cancelDlpJob = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.cancelDlpJob(request), expectedError); - const actualRequest = (client.innerApiCalls.cancelDlpJob as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.cancelDlpJob as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteDlpJob with error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.DeleteDlpJobRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.DeleteDlpJobRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteDlpJob = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.deleteDlpJob(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteDlpJob as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteDlpJob as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes cancelDlpJob with closed client', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.CancelDlpJobRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.CancelDlpJobRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.cancelDlpJob(request), expectedError); - }); + it('invokes deleteDlpJob with closed client', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.DeleteDlpJobRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.DeleteDlpJobRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.deleteDlpJob(request), expectedError); + }); + }); + + describe('cancelDlpJob', () => { + it('invokes cancelDlpJob without error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.CancelDlpJobRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.CancelDlpJobRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.cancelDlpJob = stubSimpleCall(expectedResponse); + const [response] = await client.cancelDlpJob(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.cancelDlpJob as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.cancelDlpJob as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('createStoredInfoType', () => { - it('invokes createStoredInfoType without error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.CreateStoredInfoTypeRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.CreateStoredInfoTypeRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.CreateStoredInfoTypeRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.privacy.dlp.v2.StoredInfoType() - ); - client.innerApiCalls.createStoredInfoType = stubSimpleCall(expectedResponse); - const [response] = await client.createStoredInfoType(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createStoredInfoType as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createStoredInfoType as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes cancelDlpJob without error using callback', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.CancelDlpJobRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.CancelDlpJobRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.cancelDlpJob = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.cancelDlpJob( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.cancelDlpJob as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.cancelDlpJob as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createStoredInfoType without error using callback', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.CreateStoredInfoTypeRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.CreateStoredInfoTypeRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.CreateStoredInfoTypeRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.privacy.dlp.v2.StoredInfoType() - ); - client.innerApiCalls.createStoredInfoType = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createStoredInfoType( - request, - (err?: Error|null, result?: protos.google.privacy.dlp.v2.IStoredInfoType|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createStoredInfoType as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createStoredInfoType as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes cancelDlpJob with error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.CancelDlpJobRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.CancelDlpJobRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.cancelDlpJob = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.cancelDlpJob(request), expectedError); + const actualRequest = ( + client.innerApiCalls.cancelDlpJob as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.cancelDlpJob as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createStoredInfoType with error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.CreateStoredInfoTypeRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.CreateStoredInfoTypeRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.CreateStoredInfoTypeRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createStoredInfoType = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createStoredInfoType(request), expectedError); - const actualRequest = (client.innerApiCalls.createStoredInfoType as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createStoredInfoType as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes cancelDlpJob with closed client', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.CancelDlpJobRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.CancelDlpJobRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.cancelDlpJob(request), expectedError); + }); + }); + + describe('createStoredInfoType', () => { + it('invokes createStoredInfoType without error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.CreateStoredInfoTypeRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.CreateStoredInfoTypeRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.CreateStoredInfoTypeRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.privacy.dlp.v2.StoredInfoType(), + ); + client.innerApiCalls.createStoredInfoType = + stubSimpleCall(expectedResponse); + const [response] = await client.createStoredInfoType(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createStoredInfoType as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createStoredInfoType as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createStoredInfoType with closed client', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.CreateStoredInfoTypeRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.CreateStoredInfoTypeRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.CreateStoredInfoTypeRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createStoredInfoType(request), expectedError); - }); + it('invokes createStoredInfoType without error using callback', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.CreateStoredInfoTypeRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.CreateStoredInfoTypeRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.CreateStoredInfoTypeRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.privacy.dlp.v2.StoredInfoType(), + ); + client.innerApiCalls.createStoredInfoType = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createStoredInfoType( + request, + ( + err?: Error | null, + result?: protos.google.privacy.dlp.v2.IStoredInfoType | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createStoredInfoType as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createStoredInfoType as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('updateStoredInfoType', () => { - it('invokes updateStoredInfoType without error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.UpdateStoredInfoTypeRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.UpdateStoredInfoTypeRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.privacy.dlp.v2.StoredInfoType() - ); - client.innerApiCalls.updateStoredInfoType = stubSimpleCall(expectedResponse); - const [response] = await client.updateStoredInfoType(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateStoredInfoType as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateStoredInfoType as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createStoredInfoType with error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.CreateStoredInfoTypeRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.CreateStoredInfoTypeRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.CreateStoredInfoTypeRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createStoredInfoType = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.createStoredInfoType(request), expectedError); + const actualRequest = ( + client.innerApiCalls.createStoredInfoType as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createStoredInfoType as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateStoredInfoType without error using callback', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.UpdateStoredInfoTypeRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.UpdateStoredInfoTypeRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.privacy.dlp.v2.StoredInfoType() - ); - client.innerApiCalls.updateStoredInfoType = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateStoredInfoType( - request, - (err?: Error|null, result?: protos.google.privacy.dlp.v2.IStoredInfoType|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateStoredInfoType as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateStoredInfoType as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createStoredInfoType with closed client', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.CreateStoredInfoTypeRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.CreateStoredInfoTypeRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.CreateStoredInfoTypeRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.createStoredInfoType(request), expectedError); + }); + }); + + describe('updateStoredInfoType', () => { + it('invokes updateStoredInfoType without error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.UpdateStoredInfoTypeRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.UpdateStoredInfoTypeRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.privacy.dlp.v2.StoredInfoType(), + ); + client.innerApiCalls.updateStoredInfoType = + stubSimpleCall(expectedResponse); + const [response] = await client.updateStoredInfoType(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateStoredInfoType as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateStoredInfoType as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateStoredInfoType with error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.UpdateStoredInfoTypeRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.UpdateStoredInfoTypeRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateStoredInfoType = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateStoredInfoType(request), expectedError); - const actualRequest = (client.innerApiCalls.updateStoredInfoType as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateStoredInfoType as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateStoredInfoType without error using callback', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.UpdateStoredInfoTypeRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.UpdateStoredInfoTypeRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.privacy.dlp.v2.StoredInfoType(), + ); + client.innerApiCalls.updateStoredInfoType = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateStoredInfoType( + request, + ( + err?: Error | null, + result?: protos.google.privacy.dlp.v2.IStoredInfoType | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateStoredInfoType as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateStoredInfoType as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateStoredInfoType with closed client', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.UpdateStoredInfoTypeRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.UpdateStoredInfoTypeRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateStoredInfoType(request), expectedError); - }); + it('invokes updateStoredInfoType with error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.UpdateStoredInfoTypeRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.UpdateStoredInfoTypeRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateStoredInfoType = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.updateStoredInfoType(request), expectedError); + const actualRequest = ( + client.innerApiCalls.updateStoredInfoType as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateStoredInfoType as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('getStoredInfoType', () => { - it('invokes getStoredInfoType without error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.GetStoredInfoTypeRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.GetStoredInfoTypeRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.privacy.dlp.v2.StoredInfoType() - ); - client.innerApiCalls.getStoredInfoType = stubSimpleCall(expectedResponse); - const [response] = await client.getStoredInfoType(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getStoredInfoType as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getStoredInfoType as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateStoredInfoType with closed client', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.UpdateStoredInfoTypeRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.UpdateStoredInfoTypeRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.updateStoredInfoType(request), expectedError); + }); + }); + + describe('getStoredInfoType', () => { + it('invokes getStoredInfoType without error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.GetStoredInfoTypeRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.GetStoredInfoTypeRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.privacy.dlp.v2.StoredInfoType(), + ); + client.innerApiCalls.getStoredInfoType = stubSimpleCall(expectedResponse); + const [response] = await client.getStoredInfoType(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getStoredInfoType as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getStoredInfoType as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getStoredInfoType without error using callback', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.GetStoredInfoTypeRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.GetStoredInfoTypeRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.privacy.dlp.v2.StoredInfoType() - ); - client.innerApiCalls.getStoredInfoType = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getStoredInfoType( - request, - (err?: Error|null, result?: protos.google.privacy.dlp.v2.IStoredInfoType|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getStoredInfoType as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getStoredInfoType as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getStoredInfoType without error using callback', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.GetStoredInfoTypeRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.GetStoredInfoTypeRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.privacy.dlp.v2.StoredInfoType(), + ); + client.innerApiCalls.getStoredInfoType = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getStoredInfoType( + request, + ( + err?: Error | null, + result?: protos.google.privacy.dlp.v2.IStoredInfoType | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getStoredInfoType as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getStoredInfoType as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getStoredInfoType with error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.GetStoredInfoTypeRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.GetStoredInfoTypeRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getStoredInfoType = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getStoredInfoType(request), expectedError); - const actualRequest = (client.innerApiCalls.getStoredInfoType as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getStoredInfoType as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getStoredInfoType with error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.GetStoredInfoTypeRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.GetStoredInfoTypeRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getStoredInfoType = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getStoredInfoType(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getStoredInfoType as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getStoredInfoType as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getStoredInfoType with closed client', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.GetStoredInfoTypeRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.GetStoredInfoTypeRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getStoredInfoType(request), expectedError); - }); + it('invokes getStoredInfoType with closed client', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.GetStoredInfoTypeRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.GetStoredInfoTypeRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getStoredInfoType(request), expectedError); + }); + }); + + describe('deleteStoredInfoType', () => { + it('invokes deleteStoredInfoType without error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.DeleteStoredInfoTypeRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.DeleteStoredInfoTypeRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteStoredInfoType = + stubSimpleCall(expectedResponse); + const [response] = await client.deleteStoredInfoType(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteStoredInfoType as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteStoredInfoType as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('deleteStoredInfoType', () => { - it('invokes deleteStoredInfoType without error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.DeleteStoredInfoTypeRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.DeleteStoredInfoTypeRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteStoredInfoType = stubSimpleCall(expectedResponse); - const [response] = await client.deleteStoredInfoType(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteStoredInfoType as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteStoredInfoType as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteStoredInfoType without error using callback', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.DeleteStoredInfoTypeRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.DeleteStoredInfoTypeRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteStoredInfoType = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteStoredInfoType( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteStoredInfoType as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteStoredInfoType as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteStoredInfoType without error using callback', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.DeleteStoredInfoTypeRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.DeleteStoredInfoTypeRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteStoredInfoType = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteStoredInfoType( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteStoredInfoType as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteStoredInfoType as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteStoredInfoType with error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.DeleteStoredInfoTypeRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.DeleteStoredInfoTypeRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteStoredInfoType = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.deleteStoredInfoType(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteStoredInfoType as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteStoredInfoType as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteStoredInfoType with error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.DeleteStoredInfoTypeRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.DeleteStoredInfoTypeRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteStoredInfoType = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteStoredInfoType(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteStoredInfoType as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteStoredInfoType as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteStoredInfoType with closed client', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.DeleteStoredInfoTypeRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.DeleteStoredInfoTypeRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.deleteStoredInfoType(request), expectedError); + }); + }); + + describe('listInspectTemplates', () => { + it('invokes listInspectTemplates without error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.ListInspectTemplatesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListInspectTemplatesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListInspectTemplatesRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.privacy.dlp.v2.InspectTemplate(), + ), + generateSampleMessage( + new protos.google.privacy.dlp.v2.InspectTemplate(), + ), + generateSampleMessage( + new protos.google.privacy.dlp.v2.InspectTemplate(), + ), + ]; + client.innerApiCalls.listInspectTemplates = + stubSimpleCall(expectedResponse); + const [response] = await client.listInspectTemplates(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listInspectTemplates as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listInspectTemplates as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteStoredInfoType with closed client', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.DeleteStoredInfoTypeRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.DeleteStoredInfoTypeRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteStoredInfoType(request), expectedError); - }); + it('invokes listInspectTemplates without error using callback', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.ListInspectTemplatesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListInspectTemplatesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListInspectTemplatesRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.privacy.dlp.v2.InspectTemplate(), + ), + generateSampleMessage( + new protos.google.privacy.dlp.v2.InspectTemplate(), + ), + generateSampleMessage( + new protos.google.privacy.dlp.v2.InspectTemplate(), + ), + ]; + client.innerApiCalls.listInspectTemplates = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listInspectTemplates( + request, + ( + err?: Error | null, + result?: protos.google.privacy.dlp.v2.IInspectTemplate[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listInspectTemplates as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listInspectTemplates as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('listInspectTemplates', () => { - it('invokes listInspectTemplates without error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.ListInspectTemplatesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListInspectTemplatesRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListInspectTemplatesRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.privacy.dlp.v2.InspectTemplate()), - generateSampleMessage(new protos.google.privacy.dlp.v2.InspectTemplate()), - generateSampleMessage(new protos.google.privacy.dlp.v2.InspectTemplate()), - ]; - client.innerApiCalls.listInspectTemplates = stubSimpleCall(expectedResponse); - const [response] = await client.listInspectTemplates(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listInspectTemplates as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listInspectTemplates as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listInspectTemplates with error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.ListInspectTemplatesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListInspectTemplatesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListInspectTemplatesRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listInspectTemplates = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listInspectTemplates(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listInspectTemplates as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listInspectTemplates as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listInspectTemplates without error using callback', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.ListInspectTemplatesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListInspectTemplatesRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListInspectTemplatesRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.privacy.dlp.v2.InspectTemplate()), - generateSampleMessage(new protos.google.privacy.dlp.v2.InspectTemplate()), - generateSampleMessage(new protos.google.privacy.dlp.v2.InspectTemplate()), - ]; - client.innerApiCalls.listInspectTemplates = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listInspectTemplates( - request, - (err?: Error|null, result?: protos.google.privacy.dlp.v2.IInspectTemplate[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listInspectTemplates as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listInspectTemplates as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listInspectTemplatesStream without error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.ListInspectTemplatesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListInspectTemplatesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListInspectTemplatesRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.privacy.dlp.v2.InspectTemplate(), + ), + generateSampleMessage( + new protos.google.privacy.dlp.v2.InspectTemplate(), + ), + generateSampleMessage( + new protos.google.privacy.dlp.v2.InspectTemplate(), + ), + ]; + client.descriptors.page.listInspectTemplates.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listInspectTemplatesStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.privacy.dlp.v2.InspectTemplate[] = []; + stream.on( + 'data', + (response: protos.google.privacy.dlp.v2.InspectTemplate) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listInspectTemplates.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listInspectTemplates, request), + ); + assert( + (client.descriptors.page.listInspectTemplates.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('invokes listInspectTemplates with error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.ListInspectTemplatesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListInspectTemplatesRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListInspectTemplatesRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listInspectTemplates = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listInspectTemplates(request), expectedError); - const actualRequest = (client.innerApiCalls.listInspectTemplates as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listInspectTemplates as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listInspectTemplatesStream with error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.ListInspectTemplatesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListInspectTemplatesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListInspectTemplatesRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listInspectTemplates.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listInspectTemplatesStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.privacy.dlp.v2.InspectTemplate[] = []; + stream.on( + 'data', + (response: protos.google.privacy.dlp.v2.InspectTemplate) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listInspectTemplates.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listInspectTemplates, request), + ); + assert( + (client.descriptors.page.listInspectTemplates.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('invokes listInspectTemplatesStream without error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.ListInspectTemplatesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListInspectTemplatesRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListInspectTemplatesRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.privacy.dlp.v2.InspectTemplate()), - generateSampleMessage(new protos.google.privacy.dlp.v2.InspectTemplate()), - generateSampleMessage(new protos.google.privacy.dlp.v2.InspectTemplate()), - ]; - client.descriptors.page.listInspectTemplates.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listInspectTemplatesStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.privacy.dlp.v2.InspectTemplate[] = []; - stream.on('data', (response: protos.google.privacy.dlp.v2.InspectTemplate) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.listInspectTemplates.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listInspectTemplates, request)); - assert( - (client.descriptors.page.listInspectTemplates.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listInspectTemplates without error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.ListInspectTemplatesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListInspectTemplatesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListInspectTemplatesRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.privacy.dlp.v2.InspectTemplate(), + ), + generateSampleMessage( + new protos.google.privacy.dlp.v2.InspectTemplate(), + ), + generateSampleMessage( + new protos.google.privacy.dlp.v2.InspectTemplate(), + ), + ]; + client.descriptors.page.listInspectTemplates.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.privacy.dlp.v2.IInspectTemplate[] = []; + const iterable = client.listInspectTemplatesAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listInspectTemplates.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listInspectTemplates.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('invokes listInspectTemplatesStream with error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.ListInspectTemplatesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListInspectTemplatesRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListInspectTemplatesRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listInspectTemplates.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listInspectTemplatesStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.privacy.dlp.v2.InspectTemplate[] = []; - stream.on('data', (response: protos.google.privacy.dlp.v2.InspectTemplate) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listInspectTemplates.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listInspectTemplates, request)); - assert( - (client.descriptors.page.listInspectTemplates.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listInspectTemplates with error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.ListInspectTemplatesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListInspectTemplatesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListInspectTemplatesRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listInspectTemplates.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listInspectTemplatesAsync(request); + await assert.rejects(async () => { + const responses: protos.google.privacy.dlp.v2.IInspectTemplate[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listInspectTemplates.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listInspectTemplates.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + }); + + describe('listDeidentifyTemplates', () => { + it('invokes listDeidentifyTemplates without error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.ListDeidentifyTemplatesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListDeidentifyTemplatesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListDeidentifyTemplatesRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.privacy.dlp.v2.DeidentifyTemplate(), + ), + generateSampleMessage( + new protos.google.privacy.dlp.v2.DeidentifyTemplate(), + ), + generateSampleMessage( + new protos.google.privacy.dlp.v2.DeidentifyTemplate(), + ), + ]; + client.innerApiCalls.listDeidentifyTemplates = + stubSimpleCall(expectedResponse); + const [response] = await client.listDeidentifyTemplates(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listDeidentifyTemplates as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listDeidentifyTemplates as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('uses async iteration with listInspectTemplates without error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.ListInspectTemplatesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListInspectTemplatesRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListInspectTemplatesRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.privacy.dlp.v2.InspectTemplate()), - generateSampleMessage(new protos.google.privacy.dlp.v2.InspectTemplate()), - generateSampleMessage(new protos.google.privacy.dlp.v2.InspectTemplate()), - ]; - client.descriptors.page.listInspectTemplates.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.privacy.dlp.v2.IInspectTemplate[] = []; - const iterable = client.listInspectTemplatesAsync(request); - for await (const resource of iterable) { - responses.push(resource!); + it('invokes listDeidentifyTemplates without error using callback', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.ListDeidentifyTemplatesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListDeidentifyTemplatesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListDeidentifyTemplatesRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.privacy.dlp.v2.DeidentifyTemplate(), + ), + generateSampleMessage( + new protos.google.privacy.dlp.v2.DeidentifyTemplate(), + ), + generateSampleMessage( + new protos.google.privacy.dlp.v2.DeidentifyTemplate(), + ), + ]; + client.innerApiCalls.listDeidentifyTemplates = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listDeidentifyTemplates( + request, + ( + err?: Error | null, + result?: protos.google.privacy.dlp.v2.IDeidentifyTemplate[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listInspectTemplates.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listInspectTemplates.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); - - it('uses async iteration with listInspectTemplates with error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.ListInspectTemplatesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListInspectTemplatesRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListInspectTemplatesRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listInspectTemplates.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listInspectTemplatesAsync(request); - await assert.rejects(async () => { - const responses: protos.google.privacy.dlp.v2.IInspectTemplate[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listInspectTemplates.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listInspectTemplates.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listDeidentifyTemplates as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listDeidentifyTemplates as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('listDeidentifyTemplates', () => { - it('invokes listDeidentifyTemplates without error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.ListDeidentifyTemplatesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListDeidentifyTemplatesRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListDeidentifyTemplatesRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.privacy.dlp.v2.DeidentifyTemplate()), - generateSampleMessage(new protos.google.privacy.dlp.v2.DeidentifyTemplate()), - generateSampleMessage(new protos.google.privacy.dlp.v2.DeidentifyTemplate()), - ]; - client.innerApiCalls.listDeidentifyTemplates = stubSimpleCall(expectedResponse); - const [response] = await client.listDeidentifyTemplates(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listDeidentifyTemplates as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listDeidentifyTemplates as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listDeidentifyTemplates with error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.ListDeidentifyTemplatesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListDeidentifyTemplatesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListDeidentifyTemplatesRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listDeidentifyTemplates = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.listDeidentifyTemplates(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.listDeidentifyTemplates as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listDeidentifyTemplates as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listDeidentifyTemplates without error using callback', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.ListDeidentifyTemplatesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListDeidentifyTemplatesRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListDeidentifyTemplatesRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.privacy.dlp.v2.DeidentifyTemplate()), - generateSampleMessage(new protos.google.privacy.dlp.v2.DeidentifyTemplate()), - generateSampleMessage(new protos.google.privacy.dlp.v2.DeidentifyTemplate()), - ]; - client.innerApiCalls.listDeidentifyTemplates = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listDeidentifyTemplates( - request, - (err?: Error|null, result?: protos.google.privacy.dlp.v2.IDeidentifyTemplate[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listDeidentifyTemplates as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listDeidentifyTemplates as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listDeidentifyTemplatesStream without error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.ListDeidentifyTemplatesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListDeidentifyTemplatesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListDeidentifyTemplatesRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.privacy.dlp.v2.DeidentifyTemplate(), + ), + generateSampleMessage( + new protos.google.privacy.dlp.v2.DeidentifyTemplate(), + ), + generateSampleMessage( + new protos.google.privacy.dlp.v2.DeidentifyTemplate(), + ), + ]; + client.descriptors.page.listDeidentifyTemplates.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listDeidentifyTemplatesStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.privacy.dlp.v2.DeidentifyTemplate[] = []; + stream.on( + 'data', + (response: protos.google.privacy.dlp.v2.DeidentifyTemplate) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + ( + client.descriptors.page.listDeidentifyTemplates + .createStream as SinonStub + ) + .getCall(0) + .calledWith(client.innerApiCalls.listDeidentifyTemplates, request), + ); + assert( + ( + client.descriptors.page.listDeidentifyTemplates + .createStream as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); - it('invokes listDeidentifyTemplates with error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.ListDeidentifyTemplatesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListDeidentifyTemplatesRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListDeidentifyTemplatesRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listDeidentifyTemplates = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listDeidentifyTemplates(request), expectedError); - const actualRequest = (client.innerApiCalls.listDeidentifyTemplates as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listDeidentifyTemplates as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listDeidentifyTemplatesStream with error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.ListDeidentifyTemplatesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListDeidentifyTemplatesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListDeidentifyTemplatesRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listDeidentifyTemplates.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listDeidentifyTemplatesStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.privacy.dlp.v2.DeidentifyTemplate[] = []; + stream.on( + 'data', + (response: protos.google.privacy.dlp.v2.DeidentifyTemplate) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + ( + client.descriptors.page.listDeidentifyTemplates + .createStream as SinonStub + ) + .getCall(0) + .calledWith(client.innerApiCalls.listDeidentifyTemplates, request), + ); + assert( + ( + client.descriptors.page.listDeidentifyTemplates + .createStream as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); - it('invokes listDeidentifyTemplatesStream without error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.ListDeidentifyTemplatesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListDeidentifyTemplatesRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListDeidentifyTemplatesRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.privacy.dlp.v2.DeidentifyTemplate()), - generateSampleMessage(new protos.google.privacy.dlp.v2.DeidentifyTemplate()), - generateSampleMessage(new protos.google.privacy.dlp.v2.DeidentifyTemplate()), - ]; - client.descriptors.page.listDeidentifyTemplates.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listDeidentifyTemplatesStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.privacy.dlp.v2.DeidentifyTemplate[] = []; - stream.on('data', (response: protos.google.privacy.dlp.v2.DeidentifyTemplate) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.listDeidentifyTemplates.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listDeidentifyTemplates, request)); - assert( - (client.descriptors.page.listDeidentifyTemplates.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listDeidentifyTemplates without error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.ListDeidentifyTemplatesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListDeidentifyTemplatesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListDeidentifyTemplatesRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.privacy.dlp.v2.DeidentifyTemplate(), + ), + generateSampleMessage( + new protos.google.privacy.dlp.v2.DeidentifyTemplate(), + ), + generateSampleMessage( + new protos.google.privacy.dlp.v2.DeidentifyTemplate(), + ), + ]; + client.descriptors.page.listDeidentifyTemplates.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.privacy.dlp.v2.IDeidentifyTemplate[] = []; + const iterable = client.listDeidentifyTemplatesAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listDeidentifyTemplates + .asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + ( + client.descriptors.page.listDeidentifyTemplates + .asyncIterate as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); - it('invokes listDeidentifyTemplatesStream with error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.ListDeidentifyTemplatesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListDeidentifyTemplatesRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListDeidentifyTemplatesRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listDeidentifyTemplates.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listDeidentifyTemplatesStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.privacy.dlp.v2.DeidentifyTemplate[] = []; - stream.on('data', (response: protos.google.privacy.dlp.v2.DeidentifyTemplate) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listDeidentifyTemplates.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listDeidentifyTemplates, request)); - assert( - (client.descriptors.page.listDeidentifyTemplates.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listDeidentifyTemplates with error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.ListDeidentifyTemplatesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListDeidentifyTemplatesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListDeidentifyTemplatesRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listDeidentifyTemplates.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listDeidentifyTemplatesAsync(request); + await assert.rejects(async () => { + const responses: protos.google.privacy.dlp.v2.IDeidentifyTemplate[] = + []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listDeidentifyTemplates + .asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + ( + client.descriptors.page.listDeidentifyTemplates + .asyncIterate as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); + }); + + describe('listJobTriggers', () => { + it('invokes listJobTriggers without error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.ListJobTriggersRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListJobTriggersRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListJobTriggersRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.privacy.dlp.v2.JobTrigger()), + generateSampleMessage(new protos.google.privacy.dlp.v2.JobTrigger()), + generateSampleMessage(new protos.google.privacy.dlp.v2.JobTrigger()), + ]; + client.innerApiCalls.listJobTriggers = stubSimpleCall(expectedResponse); + const [response] = await client.listJobTriggers(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listJobTriggers as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listJobTriggers as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('uses async iteration with listDeidentifyTemplates without error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.ListDeidentifyTemplatesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListDeidentifyTemplatesRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListDeidentifyTemplatesRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.privacy.dlp.v2.DeidentifyTemplate()), - generateSampleMessage(new protos.google.privacy.dlp.v2.DeidentifyTemplate()), - generateSampleMessage(new protos.google.privacy.dlp.v2.DeidentifyTemplate()), - ]; - client.descriptors.page.listDeidentifyTemplates.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.privacy.dlp.v2.IDeidentifyTemplate[] = []; - const iterable = client.listDeidentifyTemplatesAsync(request); - for await (const resource of iterable) { - responses.push(resource!); + it('invokes listJobTriggers without error using callback', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.ListJobTriggersRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListJobTriggersRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListJobTriggersRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.privacy.dlp.v2.JobTrigger()), + generateSampleMessage(new protos.google.privacy.dlp.v2.JobTrigger()), + generateSampleMessage(new protos.google.privacy.dlp.v2.JobTrigger()), + ]; + client.innerApiCalls.listJobTriggers = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listJobTriggers( + request, + ( + err?: Error | null, + result?: protos.google.privacy.dlp.v2.IJobTrigger[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listDeidentifyTemplates.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listDeidentifyTemplates.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); - - it('uses async iteration with listDeidentifyTemplates with error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.ListDeidentifyTemplatesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListDeidentifyTemplatesRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListDeidentifyTemplatesRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listDeidentifyTemplates.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listDeidentifyTemplatesAsync(request); - await assert.rejects(async () => { - const responses: protos.google.privacy.dlp.v2.IDeidentifyTemplate[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listDeidentifyTemplates.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listDeidentifyTemplates.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listJobTriggers as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listJobTriggers as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('listJobTriggers', () => { - it('invokes listJobTriggers without error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.ListJobTriggersRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListJobTriggersRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListJobTriggersRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.privacy.dlp.v2.JobTrigger()), - generateSampleMessage(new protos.google.privacy.dlp.v2.JobTrigger()), - generateSampleMessage(new protos.google.privacy.dlp.v2.JobTrigger()), - ]; - client.innerApiCalls.listJobTriggers = stubSimpleCall(expectedResponse); - const [response] = await client.listJobTriggers(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listJobTriggers as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listJobTriggers as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listJobTriggers with error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.ListJobTriggersRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListJobTriggersRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListJobTriggersRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listJobTriggers = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listJobTriggers(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listJobTriggers as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listJobTriggers as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listJobTriggers without error using callback', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.ListJobTriggersRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListJobTriggersRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListJobTriggersRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.privacy.dlp.v2.JobTrigger()), - generateSampleMessage(new protos.google.privacy.dlp.v2.JobTrigger()), - generateSampleMessage(new protos.google.privacy.dlp.v2.JobTrigger()), - ]; - client.innerApiCalls.listJobTriggers = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listJobTriggers( - request, - (err?: Error|null, result?: protos.google.privacy.dlp.v2.IJobTrigger[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listJobTriggers as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listJobTriggers as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listJobTriggersStream without error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.ListJobTriggersRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListJobTriggersRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListJobTriggersRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.privacy.dlp.v2.JobTrigger()), + generateSampleMessage(new protos.google.privacy.dlp.v2.JobTrigger()), + generateSampleMessage(new protos.google.privacy.dlp.v2.JobTrigger()), + ]; + client.descriptors.page.listJobTriggers.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listJobTriggersStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.privacy.dlp.v2.JobTrigger[] = []; + stream.on( + 'data', + (response: protos.google.privacy.dlp.v2.JobTrigger) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listJobTriggers.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listJobTriggers, request), + ); + assert( + (client.descriptors.page.listJobTriggers.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('invokes listJobTriggers with error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.ListJobTriggersRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListJobTriggersRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListJobTriggersRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listJobTriggers = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listJobTriggers(request), expectedError); - const actualRequest = (client.innerApiCalls.listJobTriggers as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listJobTriggers as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listJobTriggersStream with error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.ListJobTriggersRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListJobTriggersRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListJobTriggersRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listJobTriggers.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listJobTriggersStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.privacy.dlp.v2.JobTrigger[] = []; + stream.on( + 'data', + (response: protos.google.privacy.dlp.v2.JobTrigger) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listJobTriggers.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listJobTriggers, request), + ); + assert( + (client.descriptors.page.listJobTriggers.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('invokes listJobTriggersStream without error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.ListJobTriggersRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListJobTriggersRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListJobTriggersRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.privacy.dlp.v2.JobTrigger()), - generateSampleMessage(new protos.google.privacy.dlp.v2.JobTrigger()), - generateSampleMessage(new protos.google.privacy.dlp.v2.JobTrigger()), - ]; - client.descriptors.page.listJobTriggers.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listJobTriggersStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.privacy.dlp.v2.JobTrigger[] = []; - stream.on('data', (response: protos.google.privacy.dlp.v2.JobTrigger) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.listJobTriggers.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listJobTriggers, request)); - assert( - (client.descriptors.page.listJobTriggers.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listJobTriggers without error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.ListJobTriggersRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListJobTriggersRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListJobTriggersRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.privacy.dlp.v2.JobTrigger()), + generateSampleMessage(new protos.google.privacy.dlp.v2.JobTrigger()), + generateSampleMessage(new protos.google.privacy.dlp.v2.JobTrigger()), + ]; + client.descriptors.page.listJobTriggers.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.privacy.dlp.v2.IJobTrigger[] = []; + const iterable = client.listJobTriggersAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listJobTriggers.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listJobTriggers.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('invokes listJobTriggersStream with error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.ListJobTriggersRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListJobTriggersRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListJobTriggersRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listJobTriggers.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listJobTriggersStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.privacy.dlp.v2.JobTrigger[] = []; - stream.on('data', (response: protos.google.privacy.dlp.v2.JobTrigger) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listJobTriggers.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listJobTriggers, request)); - assert( - (client.descriptors.page.listJobTriggers.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listJobTriggers with error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.ListJobTriggersRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListJobTriggersRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListJobTriggersRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listJobTriggers.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listJobTriggersAsync(request); + await assert.rejects(async () => { + const responses: protos.google.privacy.dlp.v2.IJobTrigger[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listJobTriggers.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listJobTriggers.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + }); + + describe('listDlpJobs', () => { + it('invokes listDlpJobs without error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.ListDlpJobsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListDlpJobsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListDlpJobsRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.privacy.dlp.v2.DlpJob()), + generateSampleMessage(new protos.google.privacy.dlp.v2.DlpJob()), + generateSampleMessage(new protos.google.privacy.dlp.v2.DlpJob()), + ]; + client.innerApiCalls.listDlpJobs = stubSimpleCall(expectedResponse); + const [response] = await client.listDlpJobs(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listDlpJobs as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listDlpJobs as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('uses async iteration with listJobTriggers without error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.ListJobTriggersRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListJobTriggersRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListJobTriggersRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.privacy.dlp.v2.JobTrigger()), - generateSampleMessage(new protos.google.privacy.dlp.v2.JobTrigger()), - generateSampleMessage(new protos.google.privacy.dlp.v2.JobTrigger()), - ]; - client.descriptors.page.listJobTriggers.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.privacy.dlp.v2.IJobTrigger[] = []; - const iterable = client.listJobTriggersAsync(request); - for await (const resource of iterable) { - responses.push(resource!); + it('invokes listDlpJobs without error using callback', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.ListDlpJobsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListDlpJobsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListDlpJobsRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.privacy.dlp.v2.DlpJob()), + generateSampleMessage(new protos.google.privacy.dlp.v2.DlpJob()), + generateSampleMessage(new protos.google.privacy.dlp.v2.DlpJob()), + ]; + client.innerApiCalls.listDlpJobs = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listDlpJobs( + request, + ( + err?: Error | null, + result?: protos.google.privacy.dlp.v2.IDlpJob[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listJobTriggers.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listJobTriggers.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); - - it('uses async iteration with listJobTriggers with error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.ListJobTriggersRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListJobTriggersRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListJobTriggersRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listJobTriggers.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listJobTriggersAsync(request); - await assert.rejects(async () => { - const responses: protos.google.privacy.dlp.v2.IJobTrigger[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listJobTriggers.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listJobTriggers.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listDlpJobs as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listDlpJobs as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('listDlpJobs', () => { - it('invokes listDlpJobs without error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.ListDlpJobsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListDlpJobsRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListDlpJobsRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.privacy.dlp.v2.DlpJob()), - generateSampleMessage(new protos.google.privacy.dlp.v2.DlpJob()), - generateSampleMessage(new protos.google.privacy.dlp.v2.DlpJob()), - ]; - client.innerApiCalls.listDlpJobs = stubSimpleCall(expectedResponse); - const [response] = await client.listDlpJobs(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listDlpJobs as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listDlpJobs as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listDlpJobs with error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.ListDlpJobsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListDlpJobsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListDlpJobsRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listDlpJobs = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listDlpJobs(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listDlpJobs as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listDlpJobs as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listDlpJobs without error using callback', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.ListDlpJobsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListDlpJobsRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListDlpJobsRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.privacy.dlp.v2.DlpJob()), - generateSampleMessage(new protos.google.privacy.dlp.v2.DlpJob()), - generateSampleMessage(new protos.google.privacy.dlp.v2.DlpJob()), - ]; - client.innerApiCalls.listDlpJobs = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listDlpJobs( - request, - (err?: Error|null, result?: protos.google.privacy.dlp.v2.IDlpJob[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listDlpJobs as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listDlpJobs as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listDlpJobsStream without error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.ListDlpJobsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListDlpJobsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListDlpJobsRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.privacy.dlp.v2.DlpJob()), + generateSampleMessage(new protos.google.privacy.dlp.v2.DlpJob()), + generateSampleMessage(new protos.google.privacy.dlp.v2.DlpJob()), + ]; + client.descriptors.page.listDlpJobs.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listDlpJobsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.privacy.dlp.v2.DlpJob[] = []; + stream.on('data', (response: protos.google.privacy.dlp.v2.DlpJob) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listDlpJobs.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listDlpJobs, request), + ); + assert( + (client.descriptors.page.listDlpJobs.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('invokes listDlpJobs with error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.ListDlpJobsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListDlpJobsRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListDlpJobsRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listDlpJobs = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listDlpJobs(request), expectedError); - const actualRequest = (client.innerApiCalls.listDlpJobs as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listDlpJobs as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listDlpJobsStream with error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.ListDlpJobsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListDlpJobsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListDlpJobsRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listDlpJobs.createStream = stubPageStreamingCall( + undefined, + expectedError, + ); + const stream = client.listDlpJobsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.privacy.dlp.v2.DlpJob[] = []; + stream.on('data', (response: protos.google.privacy.dlp.v2.DlpJob) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listDlpJobs.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listDlpJobs, request), + ); + assert( + (client.descriptors.page.listDlpJobs.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('invokes listDlpJobsStream without error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.ListDlpJobsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListDlpJobsRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListDlpJobsRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.privacy.dlp.v2.DlpJob()), - generateSampleMessage(new protos.google.privacy.dlp.v2.DlpJob()), - generateSampleMessage(new protos.google.privacy.dlp.v2.DlpJob()), - ]; - client.descriptors.page.listDlpJobs.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listDlpJobsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.privacy.dlp.v2.DlpJob[] = []; - stream.on('data', (response: protos.google.privacy.dlp.v2.DlpJob) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.listDlpJobs.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listDlpJobs, request)); - assert( - (client.descriptors.page.listDlpJobs.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listDlpJobs without error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.ListDlpJobsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListDlpJobsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListDlpJobsRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.privacy.dlp.v2.DlpJob()), + generateSampleMessage(new protos.google.privacy.dlp.v2.DlpJob()), + generateSampleMessage(new protos.google.privacy.dlp.v2.DlpJob()), + ]; + client.descriptors.page.listDlpJobs.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.privacy.dlp.v2.IDlpJob[] = []; + const iterable = client.listDlpJobsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + (client.descriptors.page.listDlpJobs.asyncIterate as SinonStub).getCall( + 0, + ).args[1], + request, + ); + assert( + (client.descriptors.page.listDlpJobs.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('invokes listDlpJobsStream with error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.ListDlpJobsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListDlpJobsRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListDlpJobsRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listDlpJobs.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listDlpJobsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.privacy.dlp.v2.DlpJob[] = []; - stream.on('data', (response: protos.google.privacy.dlp.v2.DlpJob) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listDlpJobs.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listDlpJobs, request)); - assert( - (client.descriptors.page.listDlpJobs.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listDlpJobs with error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.ListDlpJobsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListDlpJobsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListDlpJobsRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listDlpJobs.asyncIterate = stubAsyncIterationCall( + undefined, + expectedError, + ); + const iterable = client.listDlpJobsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.privacy.dlp.v2.IDlpJob[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + (client.descriptors.page.listDlpJobs.asyncIterate as SinonStub).getCall( + 0, + ).args[1], + request, + ); + assert( + (client.descriptors.page.listDlpJobs.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + }); + + describe('listStoredInfoTypes', () => { + it('invokes listStoredInfoTypes without error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.ListStoredInfoTypesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListStoredInfoTypesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListStoredInfoTypesRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.privacy.dlp.v2.StoredInfoType(), + ), + generateSampleMessage( + new protos.google.privacy.dlp.v2.StoredInfoType(), + ), + generateSampleMessage( + new protos.google.privacy.dlp.v2.StoredInfoType(), + ), + ]; + client.innerApiCalls.listStoredInfoTypes = + stubSimpleCall(expectedResponse); + const [response] = await client.listStoredInfoTypes(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listStoredInfoTypes as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listStoredInfoTypes as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('uses async iteration with listDlpJobs without error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.ListDlpJobsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListDlpJobsRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListDlpJobsRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.privacy.dlp.v2.DlpJob()), - generateSampleMessage(new protos.google.privacy.dlp.v2.DlpJob()), - generateSampleMessage(new protos.google.privacy.dlp.v2.DlpJob()), - ]; - client.descriptors.page.listDlpJobs.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.privacy.dlp.v2.IDlpJob[] = []; - const iterable = client.listDlpJobsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); + it('invokes listStoredInfoTypes without error using callback', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.ListStoredInfoTypesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListStoredInfoTypesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListStoredInfoTypesRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.privacy.dlp.v2.StoredInfoType(), + ), + generateSampleMessage( + new protos.google.privacy.dlp.v2.StoredInfoType(), + ), + generateSampleMessage( + new protos.google.privacy.dlp.v2.StoredInfoType(), + ), + ]; + client.innerApiCalls.listStoredInfoTypes = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listStoredInfoTypes( + request, + ( + err?: Error | null, + result?: protos.google.privacy.dlp.v2.IStoredInfoType[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listDlpJobs.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listDlpJobs.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); - - it('uses async iteration with listDlpJobs with error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.ListDlpJobsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListDlpJobsRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListDlpJobsRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listDlpJobs.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listDlpJobsAsync(request); - await assert.rejects(async () => { - const responses: protos.google.privacy.dlp.v2.IDlpJob[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listDlpJobs.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listDlpJobs.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listStoredInfoTypes as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listStoredInfoTypes as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('listStoredInfoTypes', () => { - it('invokes listStoredInfoTypes without error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.ListStoredInfoTypesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListStoredInfoTypesRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListStoredInfoTypesRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.privacy.dlp.v2.StoredInfoType()), - generateSampleMessage(new protos.google.privacy.dlp.v2.StoredInfoType()), - generateSampleMessage(new protos.google.privacy.dlp.v2.StoredInfoType()), - ]; - client.innerApiCalls.listStoredInfoTypes = stubSimpleCall(expectedResponse); - const [response] = await client.listStoredInfoTypes(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listStoredInfoTypes as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listStoredInfoTypes as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listStoredInfoTypes without error using callback', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.ListStoredInfoTypesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListStoredInfoTypesRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListStoredInfoTypesRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.privacy.dlp.v2.StoredInfoType()), - generateSampleMessage(new protos.google.privacy.dlp.v2.StoredInfoType()), - generateSampleMessage(new protos.google.privacy.dlp.v2.StoredInfoType()), - ]; - client.innerApiCalls.listStoredInfoTypes = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listStoredInfoTypes( - request, - (err?: Error|null, result?: protos.google.privacy.dlp.v2.IStoredInfoType[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listStoredInfoTypes as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listStoredInfoTypes as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listStoredInfoTypes with error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.ListStoredInfoTypesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListStoredInfoTypesRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListStoredInfoTypesRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listStoredInfoTypes = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listStoredInfoTypes(request), expectedError); - const actualRequest = (client.innerApiCalls.listStoredInfoTypes as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listStoredInfoTypes as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listStoredInfoTypesStream without error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.ListStoredInfoTypesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListStoredInfoTypesRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListStoredInfoTypesRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.privacy.dlp.v2.StoredInfoType()), - generateSampleMessage(new protos.google.privacy.dlp.v2.StoredInfoType()), - generateSampleMessage(new protos.google.privacy.dlp.v2.StoredInfoType()), - ]; - client.descriptors.page.listStoredInfoTypes.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listStoredInfoTypesStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.privacy.dlp.v2.StoredInfoType[] = []; - stream.on('data', (response: protos.google.privacy.dlp.v2.StoredInfoType) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.listStoredInfoTypes.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listStoredInfoTypes, request)); - assert( - (client.descriptors.page.listStoredInfoTypes.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listStoredInfoTypes with error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.ListStoredInfoTypesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListStoredInfoTypesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListStoredInfoTypesRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listStoredInfoTypes = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listStoredInfoTypes(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listStoredInfoTypes as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listStoredInfoTypes as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listStoredInfoTypesStream with error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.ListStoredInfoTypesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListStoredInfoTypesRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListStoredInfoTypesRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listStoredInfoTypes.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listStoredInfoTypesStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.privacy.dlp.v2.StoredInfoType[] = []; - stream.on('data', (response: protos.google.privacy.dlp.v2.StoredInfoType) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listStoredInfoTypes.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listStoredInfoTypes, request)); - assert( - (client.descriptors.page.listStoredInfoTypes.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listStoredInfoTypesStream without error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.ListStoredInfoTypesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListStoredInfoTypesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListStoredInfoTypesRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.privacy.dlp.v2.StoredInfoType(), + ), + generateSampleMessage( + new protos.google.privacy.dlp.v2.StoredInfoType(), + ), + generateSampleMessage( + new protos.google.privacy.dlp.v2.StoredInfoType(), + ), + ]; + client.descriptors.page.listStoredInfoTypes.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listStoredInfoTypesStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.privacy.dlp.v2.StoredInfoType[] = []; + stream.on( + 'data', + (response: protos.google.privacy.dlp.v2.StoredInfoType) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listStoredInfoTypes.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listStoredInfoTypes, request), + ); + assert( + (client.descriptors.page.listStoredInfoTypes.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('uses async iteration with listStoredInfoTypes without error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.ListStoredInfoTypesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListStoredInfoTypesRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListStoredInfoTypesRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.privacy.dlp.v2.StoredInfoType()), - generateSampleMessage(new protos.google.privacy.dlp.v2.StoredInfoType()), - generateSampleMessage(new protos.google.privacy.dlp.v2.StoredInfoType()), - ]; - client.descriptors.page.listStoredInfoTypes.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.privacy.dlp.v2.IStoredInfoType[] = []; - const iterable = client.listStoredInfoTypesAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listStoredInfoTypes.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listStoredInfoTypes.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listStoredInfoTypesStream with error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.ListStoredInfoTypesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListStoredInfoTypesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListStoredInfoTypesRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listStoredInfoTypes.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listStoredInfoTypesStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.privacy.dlp.v2.StoredInfoType[] = []; + stream.on( + 'data', + (response: protos.google.privacy.dlp.v2.StoredInfoType) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listStoredInfoTypes.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listStoredInfoTypes, request), + ); + assert( + (client.descriptors.page.listStoredInfoTypes.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('uses async iteration with listStoredInfoTypes with error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.ListStoredInfoTypesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListStoredInfoTypesRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListStoredInfoTypesRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listStoredInfoTypes.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listStoredInfoTypesAsync(request); - await assert.rejects(async () => { - const responses: protos.google.privacy.dlp.v2.IStoredInfoType[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listStoredInfoTypes.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listStoredInfoTypes.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listStoredInfoTypes without error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.ListStoredInfoTypesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListStoredInfoTypesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListStoredInfoTypesRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.privacy.dlp.v2.StoredInfoType(), + ), + generateSampleMessage( + new protos.google.privacy.dlp.v2.StoredInfoType(), + ), + generateSampleMessage( + new protos.google.privacy.dlp.v2.StoredInfoType(), + ), + ]; + client.descriptors.page.listStoredInfoTypes.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.privacy.dlp.v2.IStoredInfoType[] = []; + const iterable = client.listStoredInfoTypesAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listStoredInfoTypes.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listStoredInfoTypes.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); }); - describe('Path templates', () => { - - describe('dlpJob', () => { - const fakePath = "/rendered/path/dlpJob"; - const expectedParameters = { - project: "projectValue", - dlp_job: "dlpJobValue", - }; - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.dlpJobPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.dlpJobPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('dlpJobPath', () => { - const result = client.dlpJobPath("projectValue", "dlpJobValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.dlpJobPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromDlpJobName', () => { - const result = client.matchProjectFromDlpJobName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.dlpJobPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchDlpJobFromDlpJobName', () => { - const result = client.matchDlpJobFromDlpJobName(fakePath); - assert.strictEqual(result, "dlpJobValue"); - assert((client.pathTemplates.dlpJobPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('uses async iteration with listStoredInfoTypes with error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.ListStoredInfoTypesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListStoredInfoTypesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListStoredInfoTypesRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listStoredInfoTypes.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listStoredInfoTypesAsync(request); + await assert.rejects(async () => { + const responses: protos.google.privacy.dlp.v2.IStoredInfoType[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listStoredInfoTypes.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listStoredInfoTypes.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + }); + + describe('Path templates', () => { + describe('dlpJob', () => { + const fakePath = '/rendered/path/dlpJob'; + const expectedParameters = { + project: 'projectValue', + dlp_job: 'dlpJobValue', + }; + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.dlpJobPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.dlpJobPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('dlpJobPath', () => { + const result = client.dlpJobPath('projectValue', 'dlpJobValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.dlpJobPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromDlpJobName', () => { + const result = client.matchProjectFromDlpJobName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.dlpJobPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchDlpJobFromDlpJobName', () => { + const result = client.matchDlpJobFromDlpJobName(fakePath); + assert.strictEqual(result, 'dlpJobValue'); + assert( + (client.pathTemplates.dlpJobPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('jobTrigger', () => { - const fakePath = "/rendered/path/jobTrigger"; - const expectedParameters = { - project: "projectValue", - job_trigger: "jobTriggerValue", - }; - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.jobTriggerPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.jobTriggerPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('jobTriggerPath', () => { - const result = client.jobTriggerPath("projectValue", "jobTriggerValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.jobTriggerPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromJobTriggerName', () => { - const result = client.matchProjectFromJobTriggerName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.jobTriggerPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchJobTriggerFromJobTriggerName', () => { - const result = client.matchJobTriggerFromJobTriggerName(fakePath); - assert.strictEqual(result, "jobTriggerValue"); - assert((client.pathTemplates.jobTriggerPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('jobTrigger', () => { + const fakePath = '/rendered/path/jobTrigger'; + const expectedParameters = { + project: 'projectValue', + job_trigger: 'jobTriggerValue', + }; + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.jobTriggerPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.jobTriggerPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('jobTriggerPath', () => { + const result = client.jobTriggerPath('projectValue', 'jobTriggerValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.jobTriggerPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromJobTriggerName', () => { + const result = client.matchProjectFromJobTriggerName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.jobTriggerPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchJobTriggerFromJobTriggerName', () => { + const result = client.matchJobTriggerFromJobTriggerName(fakePath); + assert.strictEqual(result, 'jobTriggerValue'); + assert( + (client.pathTemplates.jobTriggerPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('organization', () => { - const fakePath = "/rendered/path/organization"; - const expectedParameters = { - organization: "organizationValue", - }; - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.organizationPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationPath', () => { - const result = client.organizationPath("organizationValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationName', () => { - const result = client.matchOrganizationFromOrganizationName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('organization', () => { + const fakePath = '/rendered/path/organization'; + const expectedParameters = { + organization: 'organizationValue', + }; + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.organizationPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.organizationPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('organizationPath', () => { + const result = client.organizationPath('organizationValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.organizationPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationName', () => { + const result = client.matchOrganizationFromOrganizationName(fakePath); + assert.strictEqual(result, 'organizationValue'); + assert( + (client.pathTemplates.organizationPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('organizationDeidentifyTemplate', () => { - const fakePath = "/rendered/path/organizationDeidentifyTemplate"; - const expectedParameters = { - organization: "organizationValue", - deidentify_template: "deidentifyTemplateValue", - }; - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.organizationDeidentifyTemplatePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationDeidentifyTemplatePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationDeidentifyTemplatePath', () => { - const result = client.organizationDeidentifyTemplatePath("organizationValue", "deidentifyTemplateValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationDeidentifyTemplatePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationDeidentifyTemplateName', () => { - const result = client.matchOrganizationFromOrganizationDeidentifyTemplateName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationDeidentifyTemplatePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchDeidentifyTemplateFromOrganizationDeidentifyTemplateName', () => { - const result = client.matchDeidentifyTemplateFromOrganizationDeidentifyTemplateName(fakePath); - assert.strictEqual(result, "deidentifyTemplateValue"); - assert((client.pathTemplates.organizationDeidentifyTemplatePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('organizationDeidentifyTemplate', () => { + const fakePath = '/rendered/path/organizationDeidentifyTemplate'; + const expectedParameters = { + organization: 'organizationValue', + deidentify_template: 'deidentifyTemplateValue', + }; + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.organizationDeidentifyTemplatePathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.organizationDeidentifyTemplatePathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('organizationDeidentifyTemplatePath', () => { + const result = client.organizationDeidentifyTemplatePath( + 'organizationValue', + 'deidentifyTemplateValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationDeidentifyTemplatePathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationDeidentifyTemplateName', () => { + const result = + client.matchOrganizationFromOrganizationDeidentifyTemplateName( + fakePath, + ); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationDeidentifyTemplatePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchDeidentifyTemplateFromOrganizationDeidentifyTemplateName', () => { + const result = + client.matchDeidentifyTemplateFromOrganizationDeidentifyTemplateName( + fakePath, + ); + assert.strictEqual(result, 'deidentifyTemplateValue'); + assert( + ( + client.pathTemplates.organizationDeidentifyTemplatePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('organizationInspectTemplate', () => { - const fakePath = "/rendered/path/organizationInspectTemplate"; - const expectedParameters = { - organization: "organizationValue", - inspect_template: "inspectTemplateValue", - }; - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.organizationInspectTemplatePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationInspectTemplatePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationInspectTemplatePath', () => { - const result = client.organizationInspectTemplatePath("organizationValue", "inspectTemplateValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationInspectTemplatePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationInspectTemplateName', () => { - const result = client.matchOrganizationFromOrganizationInspectTemplateName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationInspectTemplatePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchInspectTemplateFromOrganizationInspectTemplateName', () => { - const result = client.matchInspectTemplateFromOrganizationInspectTemplateName(fakePath); - assert.strictEqual(result, "inspectTemplateValue"); - assert((client.pathTemplates.organizationInspectTemplatePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('organizationInspectTemplate', () => { + const fakePath = '/rendered/path/organizationInspectTemplate'; + const expectedParameters = { + organization: 'organizationValue', + inspect_template: 'inspectTemplateValue', + }; + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.organizationInspectTemplatePathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.organizationInspectTemplatePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('organizationInspectTemplatePath', () => { + const result = client.organizationInspectTemplatePath( + 'organizationValue', + 'inspectTemplateValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationInspectTemplatePathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationInspectTemplateName', () => { + const result = + client.matchOrganizationFromOrganizationInspectTemplateName(fakePath); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationInspectTemplatePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchInspectTemplateFromOrganizationInspectTemplateName', () => { + const result = + client.matchInspectTemplateFromOrganizationInspectTemplateName( + fakePath, + ); + assert.strictEqual(result, 'inspectTemplateValue'); + assert( + ( + client.pathTemplates.organizationInspectTemplatePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('organizationStoredInfoType', () => { - const fakePath = "/rendered/path/organizationStoredInfoType"; - const expectedParameters = { - organization: "organizationValue", - stored_info_type: "storedInfoTypeValue", - }; - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.organizationStoredInfoTypePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationStoredInfoTypePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationStoredInfoTypePath', () => { - const result = client.organizationStoredInfoTypePath("organizationValue", "storedInfoTypeValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationStoredInfoTypePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationStoredInfoTypeName', () => { - const result = client.matchOrganizationFromOrganizationStoredInfoTypeName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationStoredInfoTypePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchStoredInfoTypeFromOrganizationStoredInfoTypeName', () => { - const result = client.matchStoredInfoTypeFromOrganizationStoredInfoTypeName(fakePath); - assert.strictEqual(result, "storedInfoTypeValue"); - assert((client.pathTemplates.organizationStoredInfoTypePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('organizationStoredInfoType', () => { + const fakePath = '/rendered/path/organizationStoredInfoType'; + const expectedParameters = { + organization: 'organizationValue', + stored_info_type: 'storedInfoTypeValue', + }; + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.organizationStoredInfoTypePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.organizationStoredInfoTypePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('organizationStoredInfoTypePath', () => { + const result = client.organizationStoredInfoTypePath( + 'organizationValue', + 'storedInfoTypeValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationStoredInfoTypePathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationStoredInfoTypeName', () => { + const result = + client.matchOrganizationFromOrganizationStoredInfoTypeName(fakePath); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationStoredInfoTypePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchStoredInfoTypeFromOrganizationStoredInfoTypeName', () => { + const result = + client.matchStoredInfoTypeFromOrganizationStoredInfoTypeName( + fakePath, + ); + assert.strictEqual(result, 'storedInfoTypeValue'); + assert( + ( + client.pathTemplates.organizationStoredInfoTypePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('project', () => { - const fakePath = "/rendered/path/project"; - const expectedParameters = { - project: "projectValue", - }; - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.projectPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectPath', () => { - const result = client.projectPath("projectValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectName', () => { - const result = client.matchProjectFromProjectName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('project', () => { + const fakePath = '/rendered/path/project'; + const expectedParameters = { + project: 'projectValue', + }; + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.projectPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectPath', () => { + const result = client.projectPath('projectValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.projectPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectName', () => { + const result = client.matchProjectFromProjectName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.projectPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectDeidentifyTemplate', () => { - const fakePath = "/rendered/path/projectDeidentifyTemplate"; - const expectedParameters = { - project: "projectValue", - deidentify_template: "deidentifyTemplateValue", - }; - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.projectDeidentifyTemplatePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectDeidentifyTemplatePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectDeidentifyTemplatePath', () => { - const result = client.projectDeidentifyTemplatePath("projectValue", "deidentifyTemplateValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectDeidentifyTemplatePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectDeidentifyTemplateName', () => { - const result = client.matchProjectFromProjectDeidentifyTemplateName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectDeidentifyTemplatePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchDeidentifyTemplateFromProjectDeidentifyTemplateName', () => { - const result = client.matchDeidentifyTemplateFromProjectDeidentifyTemplateName(fakePath); - assert.strictEqual(result, "deidentifyTemplateValue"); - assert((client.pathTemplates.projectDeidentifyTemplatePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectDeidentifyTemplate', () => { + const fakePath = '/rendered/path/projectDeidentifyTemplate'; + const expectedParameters = { + project: 'projectValue', + deidentify_template: 'deidentifyTemplateValue', + }; + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.projectDeidentifyTemplatePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectDeidentifyTemplatePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectDeidentifyTemplatePath', () => { + const result = client.projectDeidentifyTemplatePath( + 'projectValue', + 'deidentifyTemplateValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.projectDeidentifyTemplatePathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectDeidentifyTemplateName', () => { + const result = + client.matchProjectFromProjectDeidentifyTemplateName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.projectDeidentifyTemplatePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchDeidentifyTemplateFromProjectDeidentifyTemplateName', () => { + const result = + client.matchDeidentifyTemplateFromProjectDeidentifyTemplateName( + fakePath, + ); + assert.strictEqual(result, 'deidentifyTemplateValue'); + assert( + ( + client.pathTemplates.projectDeidentifyTemplatePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectInspectTemplate', () => { - const fakePath = "/rendered/path/projectInspectTemplate"; - const expectedParameters = { - project: "projectValue", - inspect_template: "inspectTemplateValue", - }; - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.projectInspectTemplatePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectInspectTemplatePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectInspectTemplatePath', () => { - const result = client.projectInspectTemplatePath("projectValue", "inspectTemplateValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectInspectTemplatePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectInspectTemplateName', () => { - const result = client.matchProjectFromProjectInspectTemplateName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectInspectTemplatePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchInspectTemplateFromProjectInspectTemplateName', () => { - const result = client.matchInspectTemplateFromProjectInspectTemplateName(fakePath); - assert.strictEqual(result, "inspectTemplateValue"); - assert((client.pathTemplates.projectInspectTemplatePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectInspectTemplate', () => { + const fakePath = '/rendered/path/projectInspectTemplate'; + const expectedParameters = { + project: 'projectValue', + inspect_template: 'inspectTemplateValue', + }; + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.projectInspectTemplatePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectInspectTemplatePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectInspectTemplatePath', () => { + const result = client.projectInspectTemplatePath( + 'projectValue', + 'inspectTemplateValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.projectInspectTemplatePathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectInspectTemplateName', () => { + const result = + client.matchProjectFromProjectInspectTemplateName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.projectInspectTemplatePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchInspectTemplateFromProjectInspectTemplateName', () => { + const result = + client.matchInspectTemplateFromProjectInspectTemplateName(fakePath); + assert.strictEqual(result, 'inspectTemplateValue'); + assert( + ( + client.pathTemplates.projectInspectTemplatePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectStoredInfoType', () => { - const fakePath = "/rendered/path/projectStoredInfoType"; - const expectedParameters = { - project: "projectValue", - stored_info_type: "storedInfoTypeValue", - }; - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.projectStoredInfoTypePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectStoredInfoTypePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectStoredInfoTypePath', () => { - const result = client.projectStoredInfoTypePath("projectValue", "storedInfoTypeValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectStoredInfoTypePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectStoredInfoTypeName', () => { - const result = client.matchProjectFromProjectStoredInfoTypeName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectStoredInfoTypePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchStoredInfoTypeFromProjectStoredInfoTypeName', () => { - const result = client.matchStoredInfoTypeFromProjectStoredInfoTypeName(fakePath); - assert.strictEqual(result, "storedInfoTypeValue"); - assert((client.pathTemplates.projectStoredInfoTypePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectStoredInfoType', () => { + const fakePath = '/rendered/path/projectStoredInfoType'; + const expectedParameters = { + project: 'projectValue', + stored_info_type: 'storedInfoTypeValue', + }; + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.projectStoredInfoTypePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectStoredInfoTypePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectStoredInfoTypePath', () => { + const result = client.projectStoredInfoTypePath( + 'projectValue', + 'storedInfoTypeValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.projectStoredInfoTypePathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectStoredInfoTypeName', () => { + const result = + client.matchProjectFromProjectStoredInfoTypeName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.projectStoredInfoTypePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchStoredInfoTypeFromProjectStoredInfoTypeName', () => { + const result = + client.matchStoredInfoTypeFromProjectStoredInfoTypeName(fakePath); + assert.strictEqual(result, 'storedInfoTypeValue'); + assert( + ( + client.pathTemplates.projectStoredInfoTypePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/core/generator/gapic-generator-typescript/baselines/dlp/src/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/dlp/src/index.ts.baseline index 71974c943a92..0972497533a8 100644 --- a/core/generator/gapic-generator-typescript/baselines/dlp/src/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/dlp/src/index.ts.baseline @@ -19,7 +19,7 @@ import * as v2 from './v2'; const DlpServiceClient = v2.DlpServiceClient; type DlpServiceClient = v2.DlpServiceClient; -export {v2, DlpServiceClient}; -export default {v2, DlpServiceClient}; +export { v2, DlpServiceClient }; +export default { v2, DlpServiceClient }; import * as protos from '../protos/protos'; -export {protos} +export { protos }; diff --git a/core/generator/gapic-generator-typescript/baselines/dlp/src/v2/dlp_service_client.ts.baseline b/core/generator/gapic-generator-typescript/baselines/dlp/src/v2/dlp_service_client.ts.baseline index 073ba1d4679f..ff12c7bb0e26 100644 --- a/core/generator/gapic-generator-typescript/baselines/dlp/src/v2/dlp_service_client.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/dlp/src/v2/dlp_service_client.ts.baseline @@ -18,11 +18,18 @@ /* global window */ import type * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions, PaginationCallback, GaxCall} from 'google-gax'; -import {Transform} from 'stream'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + PaginationCallback, + GaxCall, +} from 'google-gax'; +import { Transform } from 'stream'; import * as protos from '../../protos/protos'; import jsonProtos = require('../../protos/protos.json'); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; /** * Client JSON configuration object, loaded from @@ -52,7 +59,7 @@ export class DlpServiceClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('dlp'); @@ -65,9 +72,9 @@ export class DlpServiceClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; - dlpServiceStub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; + dlpServiceStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of DlpServiceClient. @@ -108,21 +115,42 @@ export class DlpServiceClient { * const client = new DlpServiceClient({fallback: true}, gax); * ``` */ - constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { // Ensure that options include all the required fields. const staticMembers = this.constructor as typeof DlpServiceClient; - if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { - throw new Error('Please set either universe_domain or universeDomain, but not both.'); + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); } - const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; - this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; this._servicePath = 'dlp.' + this._universeDomain; - const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; - const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. if (servicePath !== this._servicePath && !('scopes' in opts)) { @@ -144,7 +172,7 @@ export class DlpServiceClient { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; @@ -158,10 +186,7 @@ export class DlpServiceClient { } // Determine the client header string. - const clientHeader = [ - `gax/${this._gaxModule.version}`, - `gapic/${version}`, - ]; + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/${process.versions.node}`); } else { @@ -183,34 +208,35 @@ export class DlpServiceClient { // Create useful helper objects for these. this.pathTemplates = { dlpJobPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/dlpJobs/{dlp_job}' + 'projects/{project}/dlpJobs/{dlp_job}', ), jobTriggerPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/jobTriggers/{job_trigger}' + 'projects/{project}/jobTriggers/{job_trigger}', ), organizationPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}' - ), - organizationDeidentifyTemplatePathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/deidentifyTemplates/{deidentify_template}' + 'organizations/{organization}', ), + organizationDeidentifyTemplatePathTemplate: + new this._gaxModule.PathTemplate( + 'organizations/{organization}/deidentifyTemplates/{deidentify_template}', + ), organizationInspectTemplatePathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/inspectTemplates/{inspect_template}' + 'organizations/{organization}/inspectTemplates/{inspect_template}', ), organizationStoredInfoTypePathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/storedInfoTypes/{stored_info_type}' + 'organizations/{organization}/storedInfoTypes/{stored_info_type}', ), projectPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}' + 'projects/{project}', ), projectDeidentifyTemplatePathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/deidentifyTemplates/{deidentify_template}' + 'projects/{project}/deidentifyTemplates/{deidentify_template}', ), projectInspectTemplatePathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/inspectTemplates/{inspect_template}' + 'projects/{project}/inspectTemplates/{inspect_template}', ), projectStoredInfoTypePathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/storedInfoTypes/{stored_info_type}' + 'projects/{project}/storedInfoTypes/{stored_info_type}', ), }; @@ -218,22 +244,40 @@ export class DlpServiceClient { // (e.g. 50 results at a time, with tokens to get subsequent // pages). Denote the keys used for pagination and results. this.descriptors.page = { - listInspectTemplates: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'inspectTemplates'), - listDeidentifyTemplates: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'deidentifyTemplates'), - listJobTriggers: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'jobTriggers'), - listDlpJobs: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'jobs'), - listStoredInfoTypes: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'storedInfoTypes') + listInspectTemplates: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'inspectTemplates', + ), + listDeidentifyTemplates: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'deidentifyTemplates', + ), + listJobTriggers: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'jobTriggers', + ), + listDlpJobs: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'jobs', + ), + listStoredInfoTypes: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'storedInfoTypes', + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.privacy.dlp.v2.DlpService', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.privacy.dlp.v2.DlpService', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + { 'x-goog-api-client': clientHeader.join(' ') }, + ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -264,37 +308,72 @@ export class DlpServiceClient { // Put together the "service stub" for // google.privacy.dlp.v2.DlpService. this.dlpServiceStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.privacy.dlp.v2.DlpService') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.privacy.dlp.v2.DlpService', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.privacy.dlp.v2.DlpService, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts, + this._providedCustomServicePath, + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const dlpServiceStubMethods = - ['inspectContent', 'redactImage', 'deidentifyContent', 'reidentifyContent', 'listInfoTypes', 'createInspectTemplate', 'updateInspectTemplate', 'getInspectTemplate', 'listInspectTemplates', 'deleteInspectTemplate', 'createDeidentifyTemplate', 'updateDeidentifyTemplate', 'getDeidentifyTemplate', 'listDeidentifyTemplates', 'deleteDeidentifyTemplate', 'createJobTrigger', 'updateJobTrigger', 'getJobTrigger', 'listJobTriggers', 'deleteJobTrigger', 'activateJobTrigger', 'createDlpJob', 'listDlpJobs', 'getDlpJob', 'deleteDlpJob', 'cancelDlpJob', 'createStoredInfoType', 'updateStoredInfoType', 'getStoredInfoType', 'listStoredInfoTypes', 'deleteStoredInfoType']; + const dlpServiceStubMethods = [ + 'inspectContent', + 'redactImage', + 'deidentifyContent', + 'reidentifyContent', + 'listInfoTypes', + 'createInspectTemplate', + 'updateInspectTemplate', + 'getInspectTemplate', + 'listInspectTemplates', + 'deleteInspectTemplate', + 'createDeidentifyTemplate', + 'updateDeidentifyTemplate', + 'getDeidentifyTemplate', + 'listDeidentifyTemplates', + 'deleteDeidentifyTemplate', + 'createJobTrigger', + 'updateJobTrigger', + 'getJobTrigger', + 'listJobTriggers', + 'deleteJobTrigger', + 'activateJobTrigger', + 'createDlpJob', + 'listDlpJobs', + 'getDlpJob', + 'deleteDlpJob', + 'cancelDlpJob', + 'createStoredInfoType', + 'updateStoredInfoType', + 'getStoredInfoType', + 'listStoredInfoTypes', + 'deleteStoredInfoType', + ]; for (const methodName of dlpServiceStubMethods) { const callPromise = this.dlpServiceStub.then( - stub => (...args: Array<{}>) => { - if (this._terminated) { - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error|null|undefined) => () => { + (stub) => + (...args: Array<{}>) => { + if (this._terminated) { + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { throw err; - }); + }, + ); - const descriptor = - this.descriptors.page[methodName] || - undefined; + const descriptor = this.descriptors.page[methodName] || undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -309,8 +388,14 @@ export class DlpServiceClient { * @returns {string} The DNS address for this service. */ static get servicePath() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'dlp.googleapis.com'; } @@ -321,8 +406,14 @@ export class DlpServiceClient { * @returns {string} The DNS address for this service. */ static get apiEndpoint() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'dlp.googleapis.com'; } @@ -353,9 +444,7 @@ export class DlpServiceClient { * @returns {string[]} List of default scopes. */ static get scopes() { - return [ - 'https://www.googleapis.com/auth/cloud-platform' - ]; + return ['https://www.googleapis.com/auth/cloud-platform']; } getProjectId(): Promise; @@ -364,8 +453,9 @@ export class DlpServiceClient { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId(callback?: Callback): - Promise|void { + getProjectId( + callback?: Callback, + ): Promise | void { if (callback) { this.auth.getProjectId(callback); return; @@ -376,2820 +466,3794 @@ export class DlpServiceClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Finds potentially sensitive info in content. - * This method has limits on input size, processing time, and output size. - * - * When no InfoTypes or CustomInfoTypes are specified in this request, the - * system will automatically choose what detectors to run. By default this may - * be all types, but may change over time as detectors are updated. - * - * For how to guides, see https://cloud.google.com/dlp/docs/inspecting-images - * and https://cloud.google.com/dlp/docs/inspecting-text, - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * The parent resource name, for example projects/my-project-id. - * @param {google.privacy.dlp.v2.InspectConfig} request.inspectConfig - * Configuration for the inspector. What specified here will override - * the template referenced by the inspect_template_name argument. - * @param {google.privacy.dlp.v2.ContentItem} request.item - * The item to inspect. - * @param {string} request.inspectTemplateName - * Template to use. Any configuration directly specified in - * inspect_config will override those set in the template. Singular fields - * that are set in this request will replace their corresponding fields in the - * template. Repeated fields are appended. Singular sub-messages and groups - * are recursively merged. - * @param {string} request.locationId - * The geographic location to process content inspection. Reserved for future - * extensions. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.privacy.dlp.v2.InspectContentResponse|InspectContentResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/dlp_service.inspect_content.js - * region_tag:dlp_v2_generated_DlpService_InspectContent_async - */ + /** + * Finds potentially sensitive info in content. + * This method has limits on input size, processing time, and output size. + * + * When no InfoTypes or CustomInfoTypes are specified in this request, the + * system will automatically choose what detectors to run. By default this may + * be all types, but may change over time as detectors are updated. + * + * For how to guides, see https://cloud.google.com/dlp/docs/inspecting-images + * and https://cloud.google.com/dlp/docs/inspecting-text, + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * The parent resource name, for example projects/my-project-id. + * @param {google.privacy.dlp.v2.InspectConfig} request.inspectConfig + * Configuration for the inspector. What specified here will override + * the template referenced by the inspect_template_name argument. + * @param {google.privacy.dlp.v2.ContentItem} request.item + * The item to inspect. + * @param {string} request.inspectTemplateName + * Template to use. Any configuration directly specified in + * inspect_config will override those set in the template. Singular fields + * that are set in this request will replace their corresponding fields in the + * template. Repeated fields are appended. Singular sub-messages and groups + * are recursively merged. + * @param {string} request.locationId + * The geographic location to process content inspection. Reserved for future + * extensions. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.privacy.dlp.v2.InspectContentResponse|InspectContentResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/dlp_service.inspect_content.js + * region_tag:dlp_v2_generated_DlpService_InspectContent_async + */ inspectContent( - request?: protos.google.privacy.dlp.v2.IInspectContentRequest, - options?: CallOptions): - Promise<[ - protos.google.privacy.dlp.v2.IInspectContentResponse, - protos.google.privacy.dlp.v2.IInspectContentRequest|undefined, {}|undefined - ]>; + request?: protos.google.privacy.dlp.v2.IInspectContentRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.privacy.dlp.v2.IInspectContentResponse, + protos.google.privacy.dlp.v2.IInspectContentRequest | undefined, + {} | undefined, + ] + >; inspectContent( - request: protos.google.privacy.dlp.v2.IInspectContentRequest, - options: CallOptions, - callback: Callback< - protos.google.privacy.dlp.v2.IInspectContentResponse, - protos.google.privacy.dlp.v2.IInspectContentRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.privacy.dlp.v2.IInspectContentRequest, + options: CallOptions, + callback: Callback< + protos.google.privacy.dlp.v2.IInspectContentResponse, + protos.google.privacy.dlp.v2.IInspectContentRequest | null | undefined, + {} | null | undefined + >, + ): void; inspectContent( - request: protos.google.privacy.dlp.v2.IInspectContentRequest, - callback: Callback< - protos.google.privacy.dlp.v2.IInspectContentResponse, - protos.google.privacy.dlp.v2.IInspectContentRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.privacy.dlp.v2.IInspectContentRequest, + callback: Callback< + protos.google.privacy.dlp.v2.IInspectContentResponse, + protos.google.privacy.dlp.v2.IInspectContentRequest | null | undefined, + {} | null | undefined + >, + ): void; inspectContent( - request?: protos.google.privacy.dlp.v2.IInspectContentRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.privacy.dlp.v2.IInspectContentResponse, - protos.google.privacy.dlp.v2.IInspectContentRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.privacy.dlp.v2.IInspectContentRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.privacy.dlp.v2.IInspectContentResponse, - protos.google.privacy.dlp.v2.IInspectContentRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.privacy.dlp.v2.IInspectContentResponse, - protos.google.privacy.dlp.v2.IInspectContentRequest|undefined, {}|undefined - ]>|void { + | protos.google.privacy.dlp.v2.IInspectContentRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.privacy.dlp.v2.IInspectContentResponse, + protos.google.privacy.dlp.v2.IInspectContentRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.privacy.dlp.v2.IInspectContentResponse, + protos.google.privacy.dlp.v2.IInspectContentRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - 'location_id': request.locationId?.toString() ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + location_id: request.locationId?.toString() ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('inspectContent request %j', request); - const wrappedCallback: Callback< - protos.google.privacy.dlp.v2.IInspectContentResponse, - protos.google.privacy.dlp.v2.IInspectContentRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.privacy.dlp.v2.IInspectContentResponse, + | protos.google.privacy.dlp.v2.IInspectContentRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('inspectContent response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.inspectContent(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.privacy.dlp.v2.IInspectContentResponse, - protos.google.privacy.dlp.v2.IInspectContentRequest|undefined, - {}|undefined - ]) => { - this._log.info('inspectContent response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .inspectContent(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.privacy.dlp.v2.IInspectContentResponse, + protos.google.privacy.dlp.v2.IInspectContentRequest | undefined, + {} | undefined, + ]) => { + this._log.info('inspectContent response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Redacts potentially sensitive info from an image. - * This method has limits on input size, processing time, and output size. - * See https://cloud.google.com/dlp/docs/redacting-sensitive-data-images to - * learn more. - * - * When no InfoTypes or CustomInfoTypes are specified in this request, the - * system will automatically choose what detectors to run. By default this may - * be all types, but may change over time as detectors are updated. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * The parent resource name, for example projects/my-project-id. - * @param {string} request.locationId - * The geographic location to process the request. Reserved for future - * extensions. - * @param {google.privacy.dlp.v2.InspectConfig} request.inspectConfig - * Configuration for the inspector. - * @param {number[]} request.imageRedactionConfigs - * The configuration for specifying what content to redact from images. - * @param {boolean} request.includeFindings - * Whether the response should include findings along with the redacted - * image. - * @param {google.privacy.dlp.v2.ByteContentItem} request.byteItem - * The content must be PNG, JPEG, SVG or BMP. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.privacy.dlp.v2.RedactImageResponse|RedactImageResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/dlp_service.redact_image.js - * region_tag:dlp_v2_generated_DlpService_RedactImage_async - */ + /** + * Redacts potentially sensitive info from an image. + * This method has limits on input size, processing time, and output size. + * See https://cloud.google.com/dlp/docs/redacting-sensitive-data-images to + * learn more. + * + * When no InfoTypes or CustomInfoTypes are specified in this request, the + * system will automatically choose what detectors to run. By default this may + * be all types, but may change over time as detectors are updated. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * The parent resource name, for example projects/my-project-id. + * @param {string} request.locationId + * The geographic location to process the request. Reserved for future + * extensions. + * @param {google.privacy.dlp.v2.InspectConfig} request.inspectConfig + * Configuration for the inspector. + * @param {number[]} request.imageRedactionConfigs + * The configuration for specifying what content to redact from images. + * @param {boolean} request.includeFindings + * Whether the response should include findings along with the redacted + * image. + * @param {google.privacy.dlp.v2.ByteContentItem} request.byteItem + * The content must be PNG, JPEG, SVG or BMP. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.privacy.dlp.v2.RedactImageResponse|RedactImageResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/dlp_service.redact_image.js + * region_tag:dlp_v2_generated_DlpService_RedactImage_async + */ redactImage( - request?: protos.google.privacy.dlp.v2.IRedactImageRequest, - options?: CallOptions): - Promise<[ - protos.google.privacy.dlp.v2.IRedactImageResponse, - protos.google.privacy.dlp.v2.IRedactImageRequest|undefined, {}|undefined - ]>; + request?: protos.google.privacy.dlp.v2.IRedactImageRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.privacy.dlp.v2.IRedactImageResponse, + protos.google.privacy.dlp.v2.IRedactImageRequest | undefined, + {} | undefined, + ] + >; redactImage( - request: protos.google.privacy.dlp.v2.IRedactImageRequest, - options: CallOptions, - callback: Callback< - protos.google.privacy.dlp.v2.IRedactImageResponse, - protos.google.privacy.dlp.v2.IRedactImageRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.privacy.dlp.v2.IRedactImageRequest, + options: CallOptions, + callback: Callback< + protos.google.privacy.dlp.v2.IRedactImageResponse, + protos.google.privacy.dlp.v2.IRedactImageRequest | null | undefined, + {} | null | undefined + >, + ): void; redactImage( - request: protos.google.privacy.dlp.v2.IRedactImageRequest, - callback: Callback< - protos.google.privacy.dlp.v2.IRedactImageResponse, - protos.google.privacy.dlp.v2.IRedactImageRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.privacy.dlp.v2.IRedactImageRequest, + callback: Callback< + protos.google.privacy.dlp.v2.IRedactImageResponse, + protos.google.privacy.dlp.v2.IRedactImageRequest | null | undefined, + {} | null | undefined + >, + ): void; redactImage( - request?: protos.google.privacy.dlp.v2.IRedactImageRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.privacy.dlp.v2.IRedactImageRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.privacy.dlp.v2.IRedactImageResponse, - protos.google.privacy.dlp.v2.IRedactImageRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.privacy.dlp.v2.IRedactImageResponse, - protos.google.privacy.dlp.v2.IRedactImageRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.privacy.dlp.v2.IRedactImageResponse, - protos.google.privacy.dlp.v2.IRedactImageRequest|undefined, {}|undefined - ]>|void { + protos.google.privacy.dlp.v2.IRedactImageRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.privacy.dlp.v2.IRedactImageResponse, + protos.google.privacy.dlp.v2.IRedactImageRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.privacy.dlp.v2.IRedactImageResponse, + protos.google.privacy.dlp.v2.IRedactImageRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - 'location_id': request.locationId?.toString() ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + location_id: request.locationId?.toString() ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('redactImage request %j', request); - const wrappedCallback: Callback< - protos.google.privacy.dlp.v2.IRedactImageResponse, - protos.google.privacy.dlp.v2.IRedactImageRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.privacy.dlp.v2.IRedactImageResponse, + protos.google.privacy.dlp.v2.IRedactImageRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('redactImage response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.redactImage(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.privacy.dlp.v2.IRedactImageResponse, - protos.google.privacy.dlp.v2.IRedactImageRequest|undefined, - {}|undefined - ]) => { - this._log.info('redactImage response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .redactImage(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.privacy.dlp.v2.IRedactImageResponse, + protos.google.privacy.dlp.v2.IRedactImageRequest | undefined, + {} | undefined, + ]) => { + this._log.info('redactImage response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * De-identifies potentially sensitive info from a ContentItem. - * This method has limits on input size and output size. - * See https://cloud.google.com/dlp/docs/deidentify-sensitive-data to - * learn more. - * - * When no InfoTypes or CustomInfoTypes are specified in this request, the - * system will automatically choose what detectors to run. By default this may - * be all types, but may change over time as detectors are updated. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * The parent resource name, for example projects/my-project-id. - * @param {google.privacy.dlp.v2.DeidentifyConfig} request.deidentifyConfig - * Configuration for the de-identification of the content item. - * Items specified here will override the template referenced by the - * deidentify_template_name argument. - * @param {google.privacy.dlp.v2.InspectConfig} request.inspectConfig - * Configuration for the inspector. - * Items specified here will override the template referenced by the - * inspect_template_name argument. - * @param {google.privacy.dlp.v2.ContentItem} request.item - * The item to de-identify. Will be treated as text. - * @param {string} request.inspectTemplateName - * Template to use. Any configuration directly specified in - * inspect_config will override those set in the template. Singular fields - * that are set in this request will replace their corresponding fields in the - * template. Repeated fields are appended. Singular sub-messages and groups - * are recursively merged. - * @param {string} request.deidentifyTemplateName - * Template to use. Any configuration directly specified in - * deidentify_config will override those set in the template. Singular fields - * that are set in this request will replace their corresponding fields in the - * template. Repeated fields are appended. Singular sub-messages and groups - * are recursively merged. - * @param {string} request.locationId - * The geographic location to process de-identification. Reserved for future - * extensions. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.privacy.dlp.v2.DeidentifyContentResponse|DeidentifyContentResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/dlp_service.deidentify_content.js - * region_tag:dlp_v2_generated_DlpService_DeidentifyContent_async - */ + /** + * De-identifies potentially sensitive info from a ContentItem. + * This method has limits on input size and output size. + * See https://cloud.google.com/dlp/docs/deidentify-sensitive-data to + * learn more. + * + * When no InfoTypes or CustomInfoTypes are specified in this request, the + * system will automatically choose what detectors to run. By default this may + * be all types, but may change over time as detectors are updated. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * The parent resource name, for example projects/my-project-id. + * @param {google.privacy.dlp.v2.DeidentifyConfig} request.deidentifyConfig + * Configuration for the de-identification of the content item. + * Items specified here will override the template referenced by the + * deidentify_template_name argument. + * @param {google.privacy.dlp.v2.InspectConfig} request.inspectConfig + * Configuration for the inspector. + * Items specified here will override the template referenced by the + * inspect_template_name argument. + * @param {google.privacy.dlp.v2.ContentItem} request.item + * The item to de-identify. Will be treated as text. + * @param {string} request.inspectTemplateName + * Template to use. Any configuration directly specified in + * inspect_config will override those set in the template. Singular fields + * that are set in this request will replace their corresponding fields in the + * template. Repeated fields are appended. Singular sub-messages and groups + * are recursively merged. + * @param {string} request.deidentifyTemplateName + * Template to use. Any configuration directly specified in + * deidentify_config will override those set in the template. Singular fields + * that are set in this request will replace their corresponding fields in the + * template. Repeated fields are appended. Singular sub-messages and groups + * are recursively merged. + * @param {string} request.locationId + * The geographic location to process de-identification. Reserved for future + * extensions. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.privacy.dlp.v2.DeidentifyContentResponse|DeidentifyContentResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/dlp_service.deidentify_content.js + * region_tag:dlp_v2_generated_DlpService_DeidentifyContent_async + */ deidentifyContent( - request?: protos.google.privacy.dlp.v2.IDeidentifyContentRequest, - options?: CallOptions): - Promise<[ - protos.google.privacy.dlp.v2.IDeidentifyContentResponse, - protos.google.privacy.dlp.v2.IDeidentifyContentRequest|undefined, {}|undefined - ]>; + request?: protos.google.privacy.dlp.v2.IDeidentifyContentRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.privacy.dlp.v2.IDeidentifyContentResponse, + protos.google.privacy.dlp.v2.IDeidentifyContentRequest | undefined, + {} | undefined, + ] + >; deidentifyContent( - request: protos.google.privacy.dlp.v2.IDeidentifyContentRequest, - options: CallOptions, - callback: Callback< - protos.google.privacy.dlp.v2.IDeidentifyContentResponse, - protos.google.privacy.dlp.v2.IDeidentifyContentRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.privacy.dlp.v2.IDeidentifyContentRequest, + options: CallOptions, + callback: Callback< + protos.google.privacy.dlp.v2.IDeidentifyContentResponse, + protos.google.privacy.dlp.v2.IDeidentifyContentRequest | null | undefined, + {} | null | undefined + >, + ): void; deidentifyContent( - request: protos.google.privacy.dlp.v2.IDeidentifyContentRequest, - callback: Callback< - protos.google.privacy.dlp.v2.IDeidentifyContentResponse, - protos.google.privacy.dlp.v2.IDeidentifyContentRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.privacy.dlp.v2.IDeidentifyContentRequest, + callback: Callback< + protos.google.privacy.dlp.v2.IDeidentifyContentResponse, + protos.google.privacy.dlp.v2.IDeidentifyContentRequest | null | undefined, + {} | null | undefined + >, + ): void; deidentifyContent( - request?: protos.google.privacy.dlp.v2.IDeidentifyContentRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.privacy.dlp.v2.IDeidentifyContentResponse, - protos.google.privacy.dlp.v2.IDeidentifyContentRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.privacy.dlp.v2.IDeidentifyContentRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.privacy.dlp.v2.IDeidentifyContentResponse, - protos.google.privacy.dlp.v2.IDeidentifyContentRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.privacy.dlp.v2.IDeidentifyContentResponse, - protos.google.privacy.dlp.v2.IDeidentifyContentRequest|undefined, {}|undefined - ]>|void { + | protos.google.privacy.dlp.v2.IDeidentifyContentRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.privacy.dlp.v2.IDeidentifyContentResponse, + protos.google.privacy.dlp.v2.IDeidentifyContentRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.privacy.dlp.v2.IDeidentifyContentResponse, + protos.google.privacy.dlp.v2.IDeidentifyContentRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - 'location_id': request.locationId?.toString() ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + location_id: request.locationId?.toString() ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('deidentifyContent request %j', request); - const wrappedCallback: Callback< - protos.google.privacy.dlp.v2.IDeidentifyContentResponse, - protos.google.privacy.dlp.v2.IDeidentifyContentRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.privacy.dlp.v2.IDeidentifyContentResponse, + | protos.google.privacy.dlp.v2.IDeidentifyContentRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deidentifyContent response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.deidentifyContent(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.privacy.dlp.v2.IDeidentifyContentResponse, - protos.google.privacy.dlp.v2.IDeidentifyContentRequest|undefined, - {}|undefined - ]) => { - this._log.info('deidentifyContent response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deidentifyContent(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.privacy.dlp.v2.IDeidentifyContentResponse, + protos.google.privacy.dlp.v2.IDeidentifyContentRequest | undefined, + {} | undefined, + ]) => { + this._log.info('deidentifyContent response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Re-identifies content that has been de-identified. - * See - * https://cloud.google.com/dlp/docs/pseudonymization#re-identification_in_free_text_code_example - * to learn more. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent resource name. - * @param {google.privacy.dlp.v2.DeidentifyConfig} request.reidentifyConfig - * Configuration for the re-identification of the content item. - * This field shares the same proto message type that is used for - * de-identification, however its usage here is for the reversal of the - * previous de-identification. Re-identification is performed by examining - * the transformations used to de-identify the items and executing the - * reverse. This requires that only reversible transformations - * be provided here. The reversible transformations are: - * - * - `CryptoDeterministicConfig` - * - `CryptoReplaceFfxFpeConfig` - * @param {google.privacy.dlp.v2.InspectConfig} request.inspectConfig - * Configuration for the inspector. - * @param {google.privacy.dlp.v2.ContentItem} request.item - * The item to re-identify. Will be treated as text. - * @param {string} request.inspectTemplateName - * Template to use. Any configuration directly specified in - * `inspect_config` will override those set in the template. Singular fields - * that are set in this request will replace their corresponding fields in the - * template. Repeated fields are appended. Singular sub-messages and groups - * are recursively merged. - * @param {string} request.reidentifyTemplateName - * Template to use. References an instance of `DeidentifyTemplate`. - * Any configuration directly specified in `reidentify_config` or - * `inspect_config` will override those set in the template. Singular fields - * that are set in this request will replace their corresponding fields in the - * template. Repeated fields are appended. Singular sub-messages and groups - * are recursively merged. - * @param {string} request.locationId - * The geographic location to process content reidentification. Reserved for - * future extensions. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.privacy.dlp.v2.ReidentifyContentResponse|ReidentifyContentResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/dlp_service.reidentify_content.js - * region_tag:dlp_v2_generated_DlpService_ReidentifyContent_async - */ + /** + * Re-identifies content that has been de-identified. + * See + * https://cloud.google.com/dlp/docs/pseudonymization#re-identification_in_free_text_code_example + * to learn more. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource name. + * @param {google.privacy.dlp.v2.DeidentifyConfig} request.reidentifyConfig + * Configuration for the re-identification of the content item. + * This field shares the same proto message type that is used for + * de-identification, however its usage here is for the reversal of the + * previous de-identification. Re-identification is performed by examining + * the transformations used to de-identify the items and executing the + * reverse. This requires that only reversible transformations + * be provided here. The reversible transformations are: + * + * - `CryptoDeterministicConfig` + * - `CryptoReplaceFfxFpeConfig` + * @param {google.privacy.dlp.v2.InspectConfig} request.inspectConfig + * Configuration for the inspector. + * @param {google.privacy.dlp.v2.ContentItem} request.item + * The item to re-identify. Will be treated as text. + * @param {string} request.inspectTemplateName + * Template to use. Any configuration directly specified in + * `inspect_config` will override those set in the template. Singular fields + * that are set in this request will replace their corresponding fields in the + * template. Repeated fields are appended. Singular sub-messages and groups + * are recursively merged. + * @param {string} request.reidentifyTemplateName + * Template to use. References an instance of `DeidentifyTemplate`. + * Any configuration directly specified in `reidentify_config` or + * `inspect_config` will override those set in the template. Singular fields + * that are set in this request will replace their corresponding fields in the + * template. Repeated fields are appended. Singular sub-messages and groups + * are recursively merged. + * @param {string} request.locationId + * The geographic location to process content reidentification. Reserved for + * future extensions. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.privacy.dlp.v2.ReidentifyContentResponse|ReidentifyContentResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/dlp_service.reidentify_content.js + * region_tag:dlp_v2_generated_DlpService_ReidentifyContent_async + */ reidentifyContent( - request?: protos.google.privacy.dlp.v2.IReidentifyContentRequest, - options?: CallOptions): - Promise<[ - protos.google.privacy.dlp.v2.IReidentifyContentResponse, - protos.google.privacy.dlp.v2.IReidentifyContentRequest|undefined, {}|undefined - ]>; + request?: protos.google.privacy.dlp.v2.IReidentifyContentRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.privacy.dlp.v2.IReidentifyContentResponse, + protos.google.privacy.dlp.v2.IReidentifyContentRequest | undefined, + {} | undefined, + ] + >; reidentifyContent( - request: protos.google.privacy.dlp.v2.IReidentifyContentRequest, - options: CallOptions, - callback: Callback< - protos.google.privacy.dlp.v2.IReidentifyContentResponse, - protos.google.privacy.dlp.v2.IReidentifyContentRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.privacy.dlp.v2.IReidentifyContentRequest, + options: CallOptions, + callback: Callback< + protos.google.privacy.dlp.v2.IReidentifyContentResponse, + protos.google.privacy.dlp.v2.IReidentifyContentRequest | null | undefined, + {} | null | undefined + >, + ): void; reidentifyContent( - request: protos.google.privacy.dlp.v2.IReidentifyContentRequest, - callback: Callback< - protos.google.privacy.dlp.v2.IReidentifyContentResponse, - protos.google.privacy.dlp.v2.IReidentifyContentRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.privacy.dlp.v2.IReidentifyContentRequest, + callback: Callback< + protos.google.privacy.dlp.v2.IReidentifyContentResponse, + protos.google.privacy.dlp.v2.IReidentifyContentRequest | null | undefined, + {} | null | undefined + >, + ): void; reidentifyContent( - request?: protos.google.privacy.dlp.v2.IReidentifyContentRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.privacy.dlp.v2.IReidentifyContentRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.privacy.dlp.v2.IReidentifyContentResponse, - protos.google.privacy.dlp.v2.IReidentifyContentRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.privacy.dlp.v2.IReidentifyContentResponse, - protos.google.privacy.dlp.v2.IReidentifyContentRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.privacy.dlp.v2.IReidentifyContentResponse, - protos.google.privacy.dlp.v2.IReidentifyContentRequest|undefined, {}|undefined - ]>|void { + | protos.google.privacy.dlp.v2.IReidentifyContentRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.privacy.dlp.v2.IReidentifyContentResponse, + protos.google.privacy.dlp.v2.IReidentifyContentRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.privacy.dlp.v2.IReidentifyContentResponse, + protos.google.privacy.dlp.v2.IReidentifyContentRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - 'location_id': request.locationId?.toString() ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + location_id: request.locationId?.toString() ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('reidentifyContent request %j', request); - const wrappedCallback: Callback< - protos.google.privacy.dlp.v2.IReidentifyContentResponse, - protos.google.privacy.dlp.v2.IReidentifyContentRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.privacy.dlp.v2.IReidentifyContentResponse, + | protos.google.privacy.dlp.v2.IReidentifyContentRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('reidentifyContent response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.reidentifyContent(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.privacy.dlp.v2.IReidentifyContentResponse, - protos.google.privacy.dlp.v2.IReidentifyContentRequest|undefined, - {}|undefined - ]) => { - this._log.info('reidentifyContent response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .reidentifyContent(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.privacy.dlp.v2.IReidentifyContentResponse, + protos.google.privacy.dlp.v2.IReidentifyContentRequest | undefined, + {} | undefined, + ]) => { + this._log.info('reidentifyContent response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Returns a list of the sensitive information types that the DLP API - * supports. See https://cloud.google.com/dlp/docs/infotypes-reference to - * learn more. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.languageCode - * BCP-47 language code for localized infoType friendly - * names. If omitted, or if localized strings are not available, - * en-US strings will be returned. - * @param {string} request.filter - * filter to only return infoTypes supported by certain parts of the - * API. Defaults to supported_by=INSPECT. - * @param {string} request.locationId - * The geographic location to list info types. Reserved for future - * extensions. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.privacy.dlp.v2.ListInfoTypesResponse|ListInfoTypesResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/dlp_service.list_info_types.js - * region_tag:dlp_v2_generated_DlpService_ListInfoTypes_async - */ + /** + * Returns a list of the sensitive information types that the DLP API + * supports. See https://cloud.google.com/dlp/docs/infotypes-reference to + * learn more. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.languageCode + * BCP-47 language code for localized infoType friendly + * names. If omitted, or if localized strings are not available, + * en-US strings will be returned. + * @param {string} request.filter + * filter to only return infoTypes supported by certain parts of the + * API. Defaults to supported_by=INSPECT. + * @param {string} request.locationId + * The geographic location to list info types. Reserved for future + * extensions. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.privacy.dlp.v2.ListInfoTypesResponse|ListInfoTypesResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/dlp_service.list_info_types.js + * region_tag:dlp_v2_generated_DlpService_ListInfoTypes_async + */ listInfoTypes( - request?: protos.google.privacy.dlp.v2.IListInfoTypesRequest, - options?: CallOptions): - Promise<[ - protos.google.privacy.dlp.v2.IListInfoTypesResponse, - protos.google.privacy.dlp.v2.IListInfoTypesRequest|undefined, {}|undefined - ]>; + request?: protos.google.privacy.dlp.v2.IListInfoTypesRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.privacy.dlp.v2.IListInfoTypesResponse, + protos.google.privacy.dlp.v2.IListInfoTypesRequest | undefined, + {} | undefined, + ] + >; listInfoTypes( - request: protos.google.privacy.dlp.v2.IListInfoTypesRequest, - options: CallOptions, - callback: Callback< - protos.google.privacy.dlp.v2.IListInfoTypesResponse, - protos.google.privacy.dlp.v2.IListInfoTypesRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.privacy.dlp.v2.IListInfoTypesRequest, + options: CallOptions, + callback: Callback< + protos.google.privacy.dlp.v2.IListInfoTypesResponse, + protos.google.privacy.dlp.v2.IListInfoTypesRequest | null | undefined, + {} | null | undefined + >, + ): void; listInfoTypes( - request: protos.google.privacy.dlp.v2.IListInfoTypesRequest, - callback: Callback< - protos.google.privacy.dlp.v2.IListInfoTypesResponse, - protos.google.privacy.dlp.v2.IListInfoTypesRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.privacy.dlp.v2.IListInfoTypesRequest, + callback: Callback< + protos.google.privacy.dlp.v2.IListInfoTypesResponse, + protos.google.privacy.dlp.v2.IListInfoTypesRequest | null | undefined, + {} | null | undefined + >, + ): void; listInfoTypes( - request?: protos.google.privacy.dlp.v2.IListInfoTypesRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.privacy.dlp.v2.IListInfoTypesResponse, - protos.google.privacy.dlp.v2.IListInfoTypesRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.privacy.dlp.v2.IListInfoTypesRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.privacy.dlp.v2.IListInfoTypesResponse, - protos.google.privacy.dlp.v2.IListInfoTypesRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.privacy.dlp.v2.IListInfoTypesResponse, - protos.google.privacy.dlp.v2.IListInfoTypesRequest|undefined, {}|undefined - ]>|void { + protos.google.privacy.dlp.v2.IListInfoTypesRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.privacy.dlp.v2.IListInfoTypesResponse, + protos.google.privacy.dlp.v2.IListInfoTypesRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.privacy.dlp.v2.IListInfoTypesResponse, + protos.google.privacy.dlp.v2.IListInfoTypesRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'location_id': request.locationId?.toString() ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + location_id: request.locationId?.toString() ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('listInfoTypes request %j', request); - const wrappedCallback: Callback< - protos.google.privacy.dlp.v2.IListInfoTypesResponse, - protos.google.privacy.dlp.v2.IListInfoTypesRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.privacy.dlp.v2.IListInfoTypesResponse, + protos.google.privacy.dlp.v2.IListInfoTypesRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('listInfoTypes response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.listInfoTypes(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.privacy.dlp.v2.IListInfoTypesResponse, - protos.google.privacy.dlp.v2.IListInfoTypesRequest|undefined, - {}|undefined - ]) => { - this._log.info('listInfoTypes response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .listInfoTypes(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.privacy.dlp.v2.IListInfoTypesResponse, + protos.google.privacy.dlp.v2.IListInfoTypesRequest | undefined, + {} | undefined, + ]) => { + this._log.info('listInfoTypes response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Creates an InspectTemplate for re-using frequently used configuration - * for inspecting content, images, and storage. - * See https://cloud.google.com/dlp/docs/creating-templates to learn more. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent resource name, for example projects/my-project-id or - * organizations/my-org-id. - * @param {google.privacy.dlp.v2.InspectTemplate} request.inspectTemplate - * Required. The InspectTemplate to create. - * @param {string} request.templateId - * The template id can contain uppercase and lowercase letters, - * numbers, and hyphens; that is, it must match the regular - * expression: `[a-zA-Z\\d-_]+`. The maximum length is 100 - * characters. Can be empty to allow the system to generate one. - * @param {string} request.locationId - * The geographic location to store the inspection template. Reserved for - * future extensions. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.privacy.dlp.v2.InspectTemplate|InspectTemplate}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/dlp_service.create_inspect_template.js - * region_tag:dlp_v2_generated_DlpService_CreateInspectTemplate_async - */ + /** + * Creates an InspectTemplate for re-using frequently used configuration + * for inspecting content, images, and storage. + * See https://cloud.google.com/dlp/docs/creating-templates to learn more. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource name, for example projects/my-project-id or + * organizations/my-org-id. + * @param {google.privacy.dlp.v2.InspectTemplate} request.inspectTemplate + * Required. The InspectTemplate to create. + * @param {string} request.templateId + * The template id can contain uppercase and lowercase letters, + * numbers, and hyphens; that is, it must match the regular + * expression: `[a-zA-Z\\d-_]+`. The maximum length is 100 + * characters. Can be empty to allow the system to generate one. + * @param {string} request.locationId + * The geographic location to store the inspection template. Reserved for + * future extensions. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.privacy.dlp.v2.InspectTemplate|InspectTemplate}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/dlp_service.create_inspect_template.js + * region_tag:dlp_v2_generated_DlpService_CreateInspectTemplate_async + */ createInspectTemplate( - request?: protos.google.privacy.dlp.v2.ICreateInspectTemplateRequest, - options?: CallOptions): - Promise<[ - protos.google.privacy.dlp.v2.IInspectTemplate, - protos.google.privacy.dlp.v2.ICreateInspectTemplateRequest|undefined, {}|undefined - ]>; + request?: protos.google.privacy.dlp.v2.ICreateInspectTemplateRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.privacy.dlp.v2.IInspectTemplate, + protos.google.privacy.dlp.v2.ICreateInspectTemplateRequest | undefined, + {} | undefined, + ] + >; createInspectTemplate( - request: protos.google.privacy.dlp.v2.ICreateInspectTemplateRequest, - options: CallOptions, - callback: Callback< - protos.google.privacy.dlp.v2.IInspectTemplate, - protos.google.privacy.dlp.v2.ICreateInspectTemplateRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.privacy.dlp.v2.ICreateInspectTemplateRequest, + options: CallOptions, + callback: Callback< + protos.google.privacy.dlp.v2.IInspectTemplate, + | protos.google.privacy.dlp.v2.ICreateInspectTemplateRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createInspectTemplate( - request: protos.google.privacy.dlp.v2.ICreateInspectTemplateRequest, - callback: Callback< - protos.google.privacy.dlp.v2.IInspectTemplate, - protos.google.privacy.dlp.v2.ICreateInspectTemplateRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.privacy.dlp.v2.ICreateInspectTemplateRequest, + callback: Callback< + protos.google.privacy.dlp.v2.IInspectTemplate, + | protos.google.privacy.dlp.v2.ICreateInspectTemplateRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createInspectTemplate( - request?: protos.google.privacy.dlp.v2.ICreateInspectTemplateRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.privacy.dlp.v2.ICreateInspectTemplateRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.privacy.dlp.v2.IInspectTemplate, - protos.google.privacy.dlp.v2.ICreateInspectTemplateRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.privacy.dlp.v2.IInspectTemplate, - protos.google.privacy.dlp.v2.ICreateInspectTemplateRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.privacy.dlp.v2.IInspectTemplate, - protos.google.privacy.dlp.v2.ICreateInspectTemplateRequest|undefined, {}|undefined - ]>|void { + | protos.google.privacy.dlp.v2.ICreateInspectTemplateRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.privacy.dlp.v2.IInspectTemplate, + | protos.google.privacy.dlp.v2.ICreateInspectTemplateRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.privacy.dlp.v2.IInspectTemplate, + protos.google.privacy.dlp.v2.ICreateInspectTemplateRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - 'location_id': request.locationId?.toString() ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + location_id: request.locationId?.toString() ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('createInspectTemplate request %j', request); - const wrappedCallback: Callback< - protos.google.privacy.dlp.v2.IInspectTemplate, - protos.google.privacy.dlp.v2.ICreateInspectTemplateRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.privacy.dlp.v2.IInspectTemplate, + | protos.google.privacy.dlp.v2.ICreateInspectTemplateRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createInspectTemplate response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.createInspectTemplate(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.privacy.dlp.v2.IInspectTemplate, - protos.google.privacy.dlp.v2.ICreateInspectTemplateRequest|undefined, - {}|undefined - ]) => { - this._log.info('createInspectTemplate response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createInspectTemplate(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.privacy.dlp.v2.IInspectTemplate, + ( + | protos.google.privacy.dlp.v2.ICreateInspectTemplateRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('createInspectTemplate response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Updates the InspectTemplate. - * See https://cloud.google.com/dlp/docs/creating-templates to learn more. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. Resource name of organization and inspectTemplate to be updated, for - * example `organizations/433245324/inspectTemplates/432452342` or - * projects/project-id/inspectTemplates/432452342. - * @param {google.privacy.dlp.v2.InspectTemplate} request.inspectTemplate - * New InspectTemplate value. - * @param {google.protobuf.FieldMask} request.updateMask - * Mask to control which fields get updated. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.privacy.dlp.v2.InspectTemplate|InspectTemplate}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/dlp_service.update_inspect_template.js - * region_tag:dlp_v2_generated_DlpService_UpdateInspectTemplate_async - */ + /** + * Updates the InspectTemplate. + * See https://cloud.google.com/dlp/docs/creating-templates to learn more. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Resource name of organization and inspectTemplate to be updated, for + * example `organizations/433245324/inspectTemplates/432452342` or + * projects/project-id/inspectTemplates/432452342. + * @param {google.privacy.dlp.v2.InspectTemplate} request.inspectTemplate + * New InspectTemplate value. + * @param {google.protobuf.FieldMask} request.updateMask + * Mask to control which fields get updated. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.privacy.dlp.v2.InspectTemplate|InspectTemplate}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/dlp_service.update_inspect_template.js + * region_tag:dlp_v2_generated_DlpService_UpdateInspectTemplate_async + */ updateInspectTemplate( - request?: protos.google.privacy.dlp.v2.IUpdateInspectTemplateRequest, - options?: CallOptions): - Promise<[ - protos.google.privacy.dlp.v2.IInspectTemplate, - protos.google.privacy.dlp.v2.IUpdateInspectTemplateRequest|undefined, {}|undefined - ]>; + request?: protos.google.privacy.dlp.v2.IUpdateInspectTemplateRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.privacy.dlp.v2.IInspectTemplate, + protos.google.privacy.dlp.v2.IUpdateInspectTemplateRequest | undefined, + {} | undefined, + ] + >; updateInspectTemplate( - request: protos.google.privacy.dlp.v2.IUpdateInspectTemplateRequest, - options: CallOptions, - callback: Callback< - protos.google.privacy.dlp.v2.IInspectTemplate, - protos.google.privacy.dlp.v2.IUpdateInspectTemplateRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.privacy.dlp.v2.IUpdateInspectTemplateRequest, + options: CallOptions, + callback: Callback< + protos.google.privacy.dlp.v2.IInspectTemplate, + | protos.google.privacy.dlp.v2.IUpdateInspectTemplateRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateInspectTemplate( - request: protos.google.privacy.dlp.v2.IUpdateInspectTemplateRequest, - callback: Callback< - protos.google.privacy.dlp.v2.IInspectTemplate, - protos.google.privacy.dlp.v2.IUpdateInspectTemplateRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.privacy.dlp.v2.IUpdateInspectTemplateRequest, + callback: Callback< + protos.google.privacy.dlp.v2.IInspectTemplate, + | protos.google.privacy.dlp.v2.IUpdateInspectTemplateRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateInspectTemplate( - request?: protos.google.privacy.dlp.v2.IUpdateInspectTemplateRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.privacy.dlp.v2.IInspectTemplate, - protos.google.privacy.dlp.v2.IUpdateInspectTemplateRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.privacy.dlp.v2.IUpdateInspectTemplateRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.privacy.dlp.v2.IInspectTemplate, - protos.google.privacy.dlp.v2.IUpdateInspectTemplateRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.privacy.dlp.v2.IInspectTemplate, - protos.google.privacy.dlp.v2.IUpdateInspectTemplateRequest|undefined, {}|undefined - ]>|void { + | protos.google.privacy.dlp.v2.IUpdateInspectTemplateRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.privacy.dlp.v2.IInspectTemplate, + | protos.google.privacy.dlp.v2.IUpdateInspectTemplateRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.privacy.dlp.v2.IInspectTemplate, + protos.google.privacy.dlp.v2.IUpdateInspectTemplateRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateInspectTemplate request %j', request); - const wrappedCallback: Callback< - protos.google.privacy.dlp.v2.IInspectTemplate, - protos.google.privacy.dlp.v2.IUpdateInspectTemplateRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.privacy.dlp.v2.IInspectTemplate, + | protos.google.privacy.dlp.v2.IUpdateInspectTemplateRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateInspectTemplate response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.updateInspectTemplate(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.privacy.dlp.v2.IInspectTemplate, - protos.google.privacy.dlp.v2.IUpdateInspectTemplateRequest|undefined, - {}|undefined - ]) => { - this._log.info('updateInspectTemplate response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateInspectTemplate(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.privacy.dlp.v2.IInspectTemplate, + ( + | protos.google.privacy.dlp.v2.IUpdateInspectTemplateRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('updateInspectTemplate response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Gets an InspectTemplate. - * See https://cloud.google.com/dlp/docs/creating-templates to learn more. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. Resource name of the organization and inspectTemplate to be read, for - * example `organizations/433245324/inspectTemplates/432452342` or - * projects/project-id/inspectTemplates/432452342. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.privacy.dlp.v2.InspectTemplate|InspectTemplate}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/dlp_service.get_inspect_template.js - * region_tag:dlp_v2_generated_DlpService_GetInspectTemplate_async - */ + /** + * Gets an InspectTemplate. + * See https://cloud.google.com/dlp/docs/creating-templates to learn more. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Resource name of the organization and inspectTemplate to be read, for + * example `organizations/433245324/inspectTemplates/432452342` or + * projects/project-id/inspectTemplates/432452342. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.privacy.dlp.v2.InspectTemplate|InspectTemplate}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/dlp_service.get_inspect_template.js + * region_tag:dlp_v2_generated_DlpService_GetInspectTemplate_async + */ getInspectTemplate( - request?: protos.google.privacy.dlp.v2.IGetInspectTemplateRequest, - options?: CallOptions): - Promise<[ - protos.google.privacy.dlp.v2.IInspectTemplate, - protos.google.privacy.dlp.v2.IGetInspectTemplateRequest|undefined, {}|undefined - ]>; + request?: protos.google.privacy.dlp.v2.IGetInspectTemplateRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.privacy.dlp.v2.IInspectTemplate, + protos.google.privacy.dlp.v2.IGetInspectTemplateRequest | undefined, + {} | undefined, + ] + >; getInspectTemplate( - request: protos.google.privacy.dlp.v2.IGetInspectTemplateRequest, - options: CallOptions, - callback: Callback< - protos.google.privacy.dlp.v2.IInspectTemplate, - protos.google.privacy.dlp.v2.IGetInspectTemplateRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.privacy.dlp.v2.IGetInspectTemplateRequest, + options: CallOptions, + callback: Callback< + protos.google.privacy.dlp.v2.IInspectTemplate, + | protos.google.privacy.dlp.v2.IGetInspectTemplateRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getInspectTemplate( - request: protos.google.privacy.dlp.v2.IGetInspectTemplateRequest, - callback: Callback< - protos.google.privacy.dlp.v2.IInspectTemplate, - protos.google.privacy.dlp.v2.IGetInspectTemplateRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.privacy.dlp.v2.IGetInspectTemplateRequest, + callback: Callback< + protos.google.privacy.dlp.v2.IInspectTemplate, + | protos.google.privacy.dlp.v2.IGetInspectTemplateRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getInspectTemplate( - request?: protos.google.privacy.dlp.v2.IGetInspectTemplateRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.privacy.dlp.v2.IGetInspectTemplateRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.privacy.dlp.v2.IInspectTemplate, - protos.google.privacy.dlp.v2.IGetInspectTemplateRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.privacy.dlp.v2.IInspectTemplate, - protos.google.privacy.dlp.v2.IGetInspectTemplateRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.privacy.dlp.v2.IInspectTemplate, - protos.google.privacy.dlp.v2.IGetInspectTemplateRequest|undefined, {}|undefined - ]>|void { + | protos.google.privacy.dlp.v2.IGetInspectTemplateRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.privacy.dlp.v2.IInspectTemplate, + | protos.google.privacy.dlp.v2.IGetInspectTemplateRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.privacy.dlp.v2.IInspectTemplate, + protos.google.privacy.dlp.v2.IGetInspectTemplateRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getInspectTemplate request %j', request); - const wrappedCallback: Callback< - protos.google.privacy.dlp.v2.IInspectTemplate, - protos.google.privacy.dlp.v2.IGetInspectTemplateRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.privacy.dlp.v2.IInspectTemplate, + | protos.google.privacy.dlp.v2.IGetInspectTemplateRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getInspectTemplate response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getInspectTemplate(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.privacy.dlp.v2.IInspectTemplate, - protos.google.privacy.dlp.v2.IGetInspectTemplateRequest|undefined, - {}|undefined - ]) => { - this._log.info('getInspectTemplate response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getInspectTemplate(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.privacy.dlp.v2.IInspectTemplate, + protos.google.privacy.dlp.v2.IGetInspectTemplateRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getInspectTemplate response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Deletes an InspectTemplate. - * See https://cloud.google.com/dlp/docs/creating-templates to learn more. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. Resource name of the organization and inspectTemplate to be deleted, for - * example `organizations/433245324/inspectTemplates/432452342` or - * projects/project-id/inspectTemplates/432452342. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/dlp_service.delete_inspect_template.js - * region_tag:dlp_v2_generated_DlpService_DeleteInspectTemplate_async - */ + /** + * Deletes an InspectTemplate. + * See https://cloud.google.com/dlp/docs/creating-templates to learn more. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Resource name of the organization and inspectTemplate to be deleted, for + * example `organizations/433245324/inspectTemplates/432452342` or + * projects/project-id/inspectTemplates/432452342. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/dlp_service.delete_inspect_template.js + * region_tag:dlp_v2_generated_DlpService_DeleteInspectTemplate_async + */ deleteInspectTemplate( - request?: protos.google.privacy.dlp.v2.IDeleteInspectTemplateRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.privacy.dlp.v2.IDeleteInspectTemplateRequest|undefined, {}|undefined - ]>; + request?: protos.google.privacy.dlp.v2.IDeleteInspectTemplateRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.privacy.dlp.v2.IDeleteInspectTemplateRequest | undefined, + {} | undefined, + ] + >; deleteInspectTemplate( - request: protos.google.privacy.dlp.v2.IDeleteInspectTemplateRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.privacy.dlp.v2.IDeleteInspectTemplateRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.privacy.dlp.v2.IDeleteInspectTemplateRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.privacy.dlp.v2.IDeleteInspectTemplateRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteInspectTemplate( - request: protos.google.privacy.dlp.v2.IDeleteInspectTemplateRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.privacy.dlp.v2.IDeleteInspectTemplateRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.privacy.dlp.v2.IDeleteInspectTemplateRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.privacy.dlp.v2.IDeleteInspectTemplateRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteInspectTemplate( - request?: protos.google.privacy.dlp.v2.IDeleteInspectTemplateRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.protobuf.IEmpty, - protos.google.privacy.dlp.v2.IDeleteInspectTemplateRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.privacy.dlp.v2.IDeleteInspectTemplateRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.privacy.dlp.v2.IDeleteInspectTemplateRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.privacy.dlp.v2.IDeleteInspectTemplateRequest|undefined, {}|undefined - ]>|void { + | protos.google.privacy.dlp.v2.IDeleteInspectTemplateRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + | protos.google.privacy.dlp.v2.IDeleteInspectTemplateRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.privacy.dlp.v2.IDeleteInspectTemplateRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('deleteInspectTemplate request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.privacy.dlp.v2.IDeleteInspectTemplateRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.privacy.dlp.v2.IDeleteInspectTemplateRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteInspectTemplate response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.deleteInspectTemplate(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.privacy.dlp.v2.IDeleteInspectTemplateRequest|undefined, - {}|undefined - ]) => { - this._log.info('deleteInspectTemplate response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteInspectTemplate(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + ( + | protos.google.privacy.dlp.v2.IDeleteInspectTemplateRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('deleteInspectTemplate response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Creates a DeidentifyTemplate for re-using frequently used configuration - * for de-identifying content, images, and storage. - * See https://cloud.google.com/dlp/docs/creating-templates-deid to learn - * more. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent resource name, for example projects/my-project-id or - * organizations/my-org-id. - * @param {google.privacy.dlp.v2.DeidentifyTemplate} request.deidentifyTemplate - * Required. The DeidentifyTemplate to create. - * @param {string} request.templateId - * The template id can contain uppercase and lowercase letters, - * numbers, and hyphens; that is, it must match the regular - * expression: `[a-zA-Z\\d-_]+`. The maximum length is 100 - * characters. Can be empty to allow the system to generate one. - * @param {string} request.locationId - * The geographic location to store the deidentification template. Reserved - * for future extensions. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.privacy.dlp.v2.DeidentifyTemplate|DeidentifyTemplate}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/dlp_service.create_deidentify_template.js - * region_tag:dlp_v2_generated_DlpService_CreateDeidentifyTemplate_async - */ + /** + * Creates a DeidentifyTemplate for re-using frequently used configuration + * for de-identifying content, images, and storage. + * See https://cloud.google.com/dlp/docs/creating-templates-deid to learn + * more. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource name, for example projects/my-project-id or + * organizations/my-org-id. + * @param {google.privacy.dlp.v2.DeidentifyTemplate} request.deidentifyTemplate + * Required. The DeidentifyTemplate to create. + * @param {string} request.templateId + * The template id can contain uppercase and lowercase letters, + * numbers, and hyphens; that is, it must match the regular + * expression: `[a-zA-Z\\d-_]+`. The maximum length is 100 + * characters. Can be empty to allow the system to generate one. + * @param {string} request.locationId + * The geographic location to store the deidentification template. Reserved + * for future extensions. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.privacy.dlp.v2.DeidentifyTemplate|DeidentifyTemplate}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/dlp_service.create_deidentify_template.js + * region_tag:dlp_v2_generated_DlpService_CreateDeidentifyTemplate_async + */ createDeidentifyTemplate( - request?: protos.google.privacy.dlp.v2.ICreateDeidentifyTemplateRequest, - options?: CallOptions): - Promise<[ - protos.google.privacy.dlp.v2.IDeidentifyTemplate, - protos.google.privacy.dlp.v2.ICreateDeidentifyTemplateRequest|undefined, {}|undefined - ]>; + request?: protos.google.privacy.dlp.v2.ICreateDeidentifyTemplateRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.privacy.dlp.v2.IDeidentifyTemplate, + protos.google.privacy.dlp.v2.ICreateDeidentifyTemplateRequest | undefined, + {} | undefined, + ] + >; createDeidentifyTemplate( - request: protos.google.privacy.dlp.v2.ICreateDeidentifyTemplateRequest, - options: CallOptions, - callback: Callback< - protos.google.privacy.dlp.v2.IDeidentifyTemplate, - protos.google.privacy.dlp.v2.ICreateDeidentifyTemplateRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.privacy.dlp.v2.ICreateDeidentifyTemplateRequest, + options: CallOptions, + callback: Callback< + protos.google.privacy.dlp.v2.IDeidentifyTemplate, + | protos.google.privacy.dlp.v2.ICreateDeidentifyTemplateRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createDeidentifyTemplate( - request: protos.google.privacy.dlp.v2.ICreateDeidentifyTemplateRequest, - callback: Callback< - protos.google.privacy.dlp.v2.IDeidentifyTemplate, - protos.google.privacy.dlp.v2.ICreateDeidentifyTemplateRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.privacy.dlp.v2.ICreateDeidentifyTemplateRequest, + callback: Callback< + protos.google.privacy.dlp.v2.IDeidentifyTemplate, + | protos.google.privacy.dlp.v2.ICreateDeidentifyTemplateRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createDeidentifyTemplate( - request?: protos.google.privacy.dlp.v2.ICreateDeidentifyTemplateRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.privacy.dlp.v2.ICreateDeidentifyTemplateRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.privacy.dlp.v2.IDeidentifyTemplate, - protos.google.privacy.dlp.v2.ICreateDeidentifyTemplateRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.privacy.dlp.v2.IDeidentifyTemplate, - protos.google.privacy.dlp.v2.ICreateDeidentifyTemplateRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.privacy.dlp.v2.IDeidentifyTemplate, - protos.google.privacy.dlp.v2.ICreateDeidentifyTemplateRequest|undefined, {}|undefined - ]>|void { + | protos.google.privacy.dlp.v2.ICreateDeidentifyTemplateRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.privacy.dlp.v2.IDeidentifyTemplate, + | protos.google.privacy.dlp.v2.ICreateDeidentifyTemplateRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.privacy.dlp.v2.IDeidentifyTemplate, + protos.google.privacy.dlp.v2.ICreateDeidentifyTemplateRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - 'location_id': request.locationId?.toString() ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + location_id: request.locationId?.toString() ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('createDeidentifyTemplate request %j', request); - const wrappedCallback: Callback< - protos.google.privacy.dlp.v2.IDeidentifyTemplate, - protos.google.privacy.dlp.v2.ICreateDeidentifyTemplateRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.privacy.dlp.v2.IDeidentifyTemplate, + | protos.google.privacy.dlp.v2.ICreateDeidentifyTemplateRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createDeidentifyTemplate response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.createDeidentifyTemplate(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.privacy.dlp.v2.IDeidentifyTemplate, - protos.google.privacy.dlp.v2.ICreateDeidentifyTemplateRequest|undefined, - {}|undefined - ]) => { - this._log.info('createDeidentifyTemplate response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createDeidentifyTemplate(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.privacy.dlp.v2.IDeidentifyTemplate, + ( + | protos.google.privacy.dlp.v2.ICreateDeidentifyTemplateRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('createDeidentifyTemplate response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Updates the DeidentifyTemplate. - * See https://cloud.google.com/dlp/docs/creating-templates-deid to learn - * more. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. Resource name of organization and deidentify template to be updated, for - * example `organizations/433245324/deidentifyTemplates/432452342` or - * projects/project-id/deidentifyTemplates/432452342. - * @param {google.privacy.dlp.v2.DeidentifyTemplate} request.deidentifyTemplate - * New DeidentifyTemplate value. - * @param {google.protobuf.FieldMask} request.updateMask - * Mask to control which fields get updated. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.privacy.dlp.v2.DeidentifyTemplate|DeidentifyTemplate}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/dlp_service.update_deidentify_template.js - * region_tag:dlp_v2_generated_DlpService_UpdateDeidentifyTemplate_async - */ + /** + * Updates the DeidentifyTemplate. + * See https://cloud.google.com/dlp/docs/creating-templates-deid to learn + * more. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Resource name of organization and deidentify template to be updated, for + * example `organizations/433245324/deidentifyTemplates/432452342` or + * projects/project-id/deidentifyTemplates/432452342. + * @param {google.privacy.dlp.v2.DeidentifyTemplate} request.deidentifyTemplate + * New DeidentifyTemplate value. + * @param {google.protobuf.FieldMask} request.updateMask + * Mask to control which fields get updated. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.privacy.dlp.v2.DeidentifyTemplate|DeidentifyTemplate}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/dlp_service.update_deidentify_template.js + * region_tag:dlp_v2_generated_DlpService_UpdateDeidentifyTemplate_async + */ updateDeidentifyTemplate( - request?: protos.google.privacy.dlp.v2.IUpdateDeidentifyTemplateRequest, - options?: CallOptions): - Promise<[ - protos.google.privacy.dlp.v2.IDeidentifyTemplate, - protos.google.privacy.dlp.v2.IUpdateDeidentifyTemplateRequest|undefined, {}|undefined - ]>; + request?: protos.google.privacy.dlp.v2.IUpdateDeidentifyTemplateRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.privacy.dlp.v2.IDeidentifyTemplate, + protos.google.privacy.dlp.v2.IUpdateDeidentifyTemplateRequest | undefined, + {} | undefined, + ] + >; updateDeidentifyTemplate( - request: protos.google.privacy.dlp.v2.IUpdateDeidentifyTemplateRequest, - options: CallOptions, - callback: Callback< - protos.google.privacy.dlp.v2.IDeidentifyTemplate, - protos.google.privacy.dlp.v2.IUpdateDeidentifyTemplateRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.privacy.dlp.v2.IUpdateDeidentifyTemplateRequest, + options: CallOptions, + callback: Callback< + protos.google.privacy.dlp.v2.IDeidentifyTemplate, + | protos.google.privacy.dlp.v2.IUpdateDeidentifyTemplateRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateDeidentifyTemplate( - request: protos.google.privacy.dlp.v2.IUpdateDeidentifyTemplateRequest, - callback: Callback< - protos.google.privacy.dlp.v2.IDeidentifyTemplate, - protos.google.privacy.dlp.v2.IUpdateDeidentifyTemplateRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.privacy.dlp.v2.IUpdateDeidentifyTemplateRequest, + callback: Callback< + protos.google.privacy.dlp.v2.IDeidentifyTemplate, + | protos.google.privacy.dlp.v2.IUpdateDeidentifyTemplateRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateDeidentifyTemplate( - request?: protos.google.privacy.dlp.v2.IUpdateDeidentifyTemplateRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.privacy.dlp.v2.IDeidentifyTemplate, - protos.google.privacy.dlp.v2.IUpdateDeidentifyTemplateRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.privacy.dlp.v2.IUpdateDeidentifyTemplateRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.privacy.dlp.v2.IDeidentifyTemplate, - protos.google.privacy.dlp.v2.IUpdateDeidentifyTemplateRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.privacy.dlp.v2.IDeidentifyTemplate, - protos.google.privacy.dlp.v2.IUpdateDeidentifyTemplateRequest|undefined, {}|undefined - ]>|void { + | protos.google.privacy.dlp.v2.IUpdateDeidentifyTemplateRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.privacy.dlp.v2.IDeidentifyTemplate, + | protos.google.privacy.dlp.v2.IUpdateDeidentifyTemplateRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.privacy.dlp.v2.IDeidentifyTemplate, + protos.google.privacy.dlp.v2.IUpdateDeidentifyTemplateRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateDeidentifyTemplate request %j', request); - const wrappedCallback: Callback< - protos.google.privacy.dlp.v2.IDeidentifyTemplate, - protos.google.privacy.dlp.v2.IUpdateDeidentifyTemplateRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.privacy.dlp.v2.IDeidentifyTemplate, + | protos.google.privacy.dlp.v2.IUpdateDeidentifyTemplateRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateDeidentifyTemplate response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.updateDeidentifyTemplate(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.privacy.dlp.v2.IDeidentifyTemplate, - protos.google.privacy.dlp.v2.IUpdateDeidentifyTemplateRequest|undefined, - {}|undefined - ]) => { - this._log.info('updateDeidentifyTemplate response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateDeidentifyTemplate(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.privacy.dlp.v2.IDeidentifyTemplate, + ( + | protos.google.privacy.dlp.v2.IUpdateDeidentifyTemplateRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('updateDeidentifyTemplate response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Gets a DeidentifyTemplate. - * See https://cloud.google.com/dlp/docs/creating-templates-deid to learn - * more. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. Resource name of the organization and deidentify template to be read, for - * example `organizations/433245324/deidentifyTemplates/432452342` or - * projects/project-id/deidentifyTemplates/432452342. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.privacy.dlp.v2.DeidentifyTemplate|DeidentifyTemplate}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/dlp_service.get_deidentify_template.js - * region_tag:dlp_v2_generated_DlpService_GetDeidentifyTemplate_async - */ + /** + * Gets a DeidentifyTemplate. + * See https://cloud.google.com/dlp/docs/creating-templates-deid to learn + * more. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Resource name of the organization and deidentify template to be read, for + * example `organizations/433245324/deidentifyTemplates/432452342` or + * projects/project-id/deidentifyTemplates/432452342. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.privacy.dlp.v2.DeidentifyTemplate|DeidentifyTemplate}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/dlp_service.get_deidentify_template.js + * region_tag:dlp_v2_generated_DlpService_GetDeidentifyTemplate_async + */ getDeidentifyTemplate( - request?: protos.google.privacy.dlp.v2.IGetDeidentifyTemplateRequest, - options?: CallOptions): - Promise<[ - protos.google.privacy.dlp.v2.IDeidentifyTemplate, - protos.google.privacy.dlp.v2.IGetDeidentifyTemplateRequest|undefined, {}|undefined - ]>; + request?: protos.google.privacy.dlp.v2.IGetDeidentifyTemplateRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.privacy.dlp.v2.IDeidentifyTemplate, + protos.google.privacy.dlp.v2.IGetDeidentifyTemplateRequest | undefined, + {} | undefined, + ] + >; getDeidentifyTemplate( - request: protos.google.privacy.dlp.v2.IGetDeidentifyTemplateRequest, - options: CallOptions, - callback: Callback< - protos.google.privacy.dlp.v2.IDeidentifyTemplate, - protos.google.privacy.dlp.v2.IGetDeidentifyTemplateRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.privacy.dlp.v2.IGetDeidentifyTemplateRequest, + options: CallOptions, + callback: Callback< + protos.google.privacy.dlp.v2.IDeidentifyTemplate, + | protos.google.privacy.dlp.v2.IGetDeidentifyTemplateRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getDeidentifyTemplate( - request: protos.google.privacy.dlp.v2.IGetDeidentifyTemplateRequest, - callback: Callback< - protos.google.privacy.dlp.v2.IDeidentifyTemplate, - protos.google.privacy.dlp.v2.IGetDeidentifyTemplateRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.privacy.dlp.v2.IGetDeidentifyTemplateRequest, + callback: Callback< + protos.google.privacy.dlp.v2.IDeidentifyTemplate, + | protos.google.privacy.dlp.v2.IGetDeidentifyTemplateRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getDeidentifyTemplate( - request?: protos.google.privacy.dlp.v2.IGetDeidentifyTemplateRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.privacy.dlp.v2.IGetDeidentifyTemplateRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.privacy.dlp.v2.IDeidentifyTemplate, - protos.google.privacy.dlp.v2.IGetDeidentifyTemplateRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.privacy.dlp.v2.IDeidentifyTemplate, - protos.google.privacy.dlp.v2.IGetDeidentifyTemplateRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.privacy.dlp.v2.IDeidentifyTemplate, - protos.google.privacy.dlp.v2.IGetDeidentifyTemplateRequest|undefined, {}|undefined - ]>|void { + | protos.google.privacy.dlp.v2.IGetDeidentifyTemplateRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.privacy.dlp.v2.IDeidentifyTemplate, + | protos.google.privacy.dlp.v2.IGetDeidentifyTemplateRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.privacy.dlp.v2.IDeidentifyTemplate, + protos.google.privacy.dlp.v2.IGetDeidentifyTemplateRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getDeidentifyTemplate request %j', request); - const wrappedCallback: Callback< - protos.google.privacy.dlp.v2.IDeidentifyTemplate, - protos.google.privacy.dlp.v2.IGetDeidentifyTemplateRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.privacy.dlp.v2.IDeidentifyTemplate, + | protos.google.privacy.dlp.v2.IGetDeidentifyTemplateRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getDeidentifyTemplate response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getDeidentifyTemplate(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.privacy.dlp.v2.IDeidentifyTemplate, - protos.google.privacy.dlp.v2.IGetDeidentifyTemplateRequest|undefined, - {}|undefined - ]) => { - this._log.info('getDeidentifyTemplate response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getDeidentifyTemplate(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.privacy.dlp.v2.IDeidentifyTemplate, + ( + | protos.google.privacy.dlp.v2.IGetDeidentifyTemplateRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('getDeidentifyTemplate response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Deletes a DeidentifyTemplate. - * See https://cloud.google.com/dlp/docs/creating-templates-deid to learn - * more. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. Resource name of the organization and deidentify template to be deleted, - * for example `organizations/433245324/deidentifyTemplates/432452342` or - * projects/project-id/deidentifyTemplates/432452342. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/dlp_service.delete_deidentify_template.js - * region_tag:dlp_v2_generated_DlpService_DeleteDeidentifyTemplate_async - */ + /** + * Deletes a DeidentifyTemplate. + * See https://cloud.google.com/dlp/docs/creating-templates-deid to learn + * more. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Resource name of the organization and deidentify template to be deleted, + * for example `organizations/433245324/deidentifyTemplates/432452342` or + * projects/project-id/deidentifyTemplates/432452342. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/dlp_service.delete_deidentify_template.js + * region_tag:dlp_v2_generated_DlpService_DeleteDeidentifyTemplate_async + */ deleteDeidentifyTemplate( - request?: protos.google.privacy.dlp.v2.IDeleteDeidentifyTemplateRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.privacy.dlp.v2.IDeleteDeidentifyTemplateRequest|undefined, {}|undefined - ]>; + request?: protos.google.privacy.dlp.v2.IDeleteDeidentifyTemplateRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.privacy.dlp.v2.IDeleteDeidentifyTemplateRequest | undefined, + {} | undefined, + ] + >; deleteDeidentifyTemplate( - request: protos.google.privacy.dlp.v2.IDeleteDeidentifyTemplateRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.privacy.dlp.v2.IDeleteDeidentifyTemplateRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.privacy.dlp.v2.IDeleteDeidentifyTemplateRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.privacy.dlp.v2.IDeleteDeidentifyTemplateRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteDeidentifyTemplate( - request: protos.google.privacy.dlp.v2.IDeleteDeidentifyTemplateRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.privacy.dlp.v2.IDeleteDeidentifyTemplateRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.privacy.dlp.v2.IDeleteDeidentifyTemplateRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.privacy.dlp.v2.IDeleteDeidentifyTemplateRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteDeidentifyTemplate( - request?: protos.google.privacy.dlp.v2.IDeleteDeidentifyTemplateRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.protobuf.IEmpty, - protos.google.privacy.dlp.v2.IDeleteDeidentifyTemplateRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.privacy.dlp.v2.IDeleteDeidentifyTemplateRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.privacy.dlp.v2.IDeleteDeidentifyTemplateRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.privacy.dlp.v2.IDeleteDeidentifyTemplateRequest|undefined, {}|undefined - ]>|void { + | protos.google.privacy.dlp.v2.IDeleteDeidentifyTemplateRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + | protos.google.privacy.dlp.v2.IDeleteDeidentifyTemplateRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.privacy.dlp.v2.IDeleteDeidentifyTemplateRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('deleteDeidentifyTemplate request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.privacy.dlp.v2.IDeleteDeidentifyTemplateRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.privacy.dlp.v2.IDeleteDeidentifyTemplateRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteDeidentifyTemplate response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.deleteDeidentifyTemplate(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.privacy.dlp.v2.IDeleteDeidentifyTemplateRequest|undefined, - {}|undefined - ]) => { - this._log.info('deleteDeidentifyTemplate response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteDeidentifyTemplate(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + ( + | protos.google.privacy.dlp.v2.IDeleteDeidentifyTemplateRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('deleteDeidentifyTemplate response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Creates a job trigger to run DLP actions such as scanning storage for - * sensitive information on a set schedule. - * See https://cloud.google.com/dlp/docs/creating-job-triggers to learn more. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent resource name, for example projects/my-project-id. - * @param {google.privacy.dlp.v2.JobTrigger} request.jobTrigger - * Required. The JobTrigger to create. - * @param {string} request.triggerId - * The trigger id can contain uppercase and lowercase letters, - * numbers, and hyphens; that is, it must match the regular - * expression: `[a-zA-Z\\d-_]+`. The maximum length is 100 - * characters. Can be empty to allow the system to generate one. - * @param {string} request.locationId - * The geographic location to store the job trigger. Reserved for - * future extensions. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.privacy.dlp.v2.JobTrigger|JobTrigger}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/dlp_service.create_job_trigger.js - * region_tag:dlp_v2_generated_DlpService_CreateJobTrigger_async - */ + /** + * Creates a job trigger to run DLP actions such as scanning storage for + * sensitive information on a set schedule. + * See https://cloud.google.com/dlp/docs/creating-job-triggers to learn more. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource name, for example projects/my-project-id. + * @param {google.privacy.dlp.v2.JobTrigger} request.jobTrigger + * Required. The JobTrigger to create. + * @param {string} request.triggerId + * The trigger id can contain uppercase and lowercase letters, + * numbers, and hyphens; that is, it must match the regular + * expression: `[a-zA-Z\\d-_]+`. The maximum length is 100 + * characters. Can be empty to allow the system to generate one. + * @param {string} request.locationId + * The geographic location to store the job trigger. Reserved for + * future extensions. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.privacy.dlp.v2.JobTrigger|JobTrigger}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/dlp_service.create_job_trigger.js + * region_tag:dlp_v2_generated_DlpService_CreateJobTrigger_async + */ createJobTrigger( - request?: protos.google.privacy.dlp.v2.ICreateJobTriggerRequest, - options?: CallOptions): - Promise<[ - protos.google.privacy.dlp.v2.IJobTrigger, - protos.google.privacy.dlp.v2.ICreateJobTriggerRequest|undefined, {}|undefined - ]>; + request?: protos.google.privacy.dlp.v2.ICreateJobTriggerRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.privacy.dlp.v2.IJobTrigger, + protos.google.privacy.dlp.v2.ICreateJobTriggerRequest | undefined, + {} | undefined, + ] + >; createJobTrigger( - request: protos.google.privacy.dlp.v2.ICreateJobTriggerRequest, - options: CallOptions, - callback: Callback< - protos.google.privacy.dlp.v2.IJobTrigger, - protos.google.privacy.dlp.v2.ICreateJobTriggerRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.privacy.dlp.v2.ICreateJobTriggerRequest, + options: CallOptions, + callback: Callback< + protos.google.privacy.dlp.v2.IJobTrigger, + protos.google.privacy.dlp.v2.ICreateJobTriggerRequest | null | undefined, + {} | null | undefined + >, + ): void; createJobTrigger( - request: protos.google.privacy.dlp.v2.ICreateJobTriggerRequest, - callback: Callback< - protos.google.privacy.dlp.v2.IJobTrigger, - protos.google.privacy.dlp.v2.ICreateJobTriggerRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.privacy.dlp.v2.ICreateJobTriggerRequest, + callback: Callback< + protos.google.privacy.dlp.v2.IJobTrigger, + protos.google.privacy.dlp.v2.ICreateJobTriggerRequest | null | undefined, + {} | null | undefined + >, + ): void; createJobTrigger( - request?: protos.google.privacy.dlp.v2.ICreateJobTriggerRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.privacy.dlp.v2.ICreateJobTriggerRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.privacy.dlp.v2.IJobTrigger, - protos.google.privacy.dlp.v2.ICreateJobTriggerRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.privacy.dlp.v2.IJobTrigger, - protos.google.privacy.dlp.v2.ICreateJobTriggerRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.privacy.dlp.v2.IJobTrigger, - protos.google.privacy.dlp.v2.ICreateJobTriggerRequest|undefined, {}|undefined - ]>|void { + | protos.google.privacy.dlp.v2.ICreateJobTriggerRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.privacy.dlp.v2.IJobTrigger, + protos.google.privacy.dlp.v2.ICreateJobTriggerRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.privacy.dlp.v2.IJobTrigger, + protos.google.privacy.dlp.v2.ICreateJobTriggerRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - 'location_id': request.locationId?.toString() ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + location_id: request.locationId?.toString() ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('createJobTrigger request %j', request); - const wrappedCallback: Callback< - protos.google.privacy.dlp.v2.IJobTrigger, - protos.google.privacy.dlp.v2.ICreateJobTriggerRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.privacy.dlp.v2.IJobTrigger, + | protos.google.privacy.dlp.v2.ICreateJobTriggerRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createJobTrigger response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.createJobTrigger(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.privacy.dlp.v2.IJobTrigger, - protos.google.privacy.dlp.v2.ICreateJobTriggerRequest|undefined, - {}|undefined - ]) => { - this._log.info('createJobTrigger response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createJobTrigger(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.privacy.dlp.v2.IJobTrigger, + protos.google.privacy.dlp.v2.ICreateJobTriggerRequest | undefined, + {} | undefined, + ]) => { + this._log.info('createJobTrigger response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Updates a job trigger. - * See https://cloud.google.com/dlp/docs/creating-job-triggers to learn more. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. Resource name of the project and the triggeredJob, for example - * `projects/dlp-test-project/jobTriggers/53234423`. - * @param {google.privacy.dlp.v2.JobTrigger} request.jobTrigger - * New JobTrigger value. - * @param {google.protobuf.FieldMask} request.updateMask - * Mask to control which fields get updated. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.privacy.dlp.v2.JobTrigger|JobTrigger}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/dlp_service.update_job_trigger.js - * region_tag:dlp_v2_generated_DlpService_UpdateJobTrigger_async - */ + /** + * Updates a job trigger. + * See https://cloud.google.com/dlp/docs/creating-job-triggers to learn more. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Resource name of the project and the triggeredJob, for example + * `projects/dlp-test-project/jobTriggers/53234423`. + * @param {google.privacy.dlp.v2.JobTrigger} request.jobTrigger + * New JobTrigger value. + * @param {google.protobuf.FieldMask} request.updateMask + * Mask to control which fields get updated. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.privacy.dlp.v2.JobTrigger|JobTrigger}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/dlp_service.update_job_trigger.js + * region_tag:dlp_v2_generated_DlpService_UpdateJobTrigger_async + */ updateJobTrigger( - request?: protos.google.privacy.dlp.v2.IUpdateJobTriggerRequest, - options?: CallOptions): - Promise<[ - protos.google.privacy.dlp.v2.IJobTrigger, - protos.google.privacy.dlp.v2.IUpdateJobTriggerRequest|undefined, {}|undefined - ]>; + request?: protos.google.privacy.dlp.v2.IUpdateJobTriggerRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.privacy.dlp.v2.IJobTrigger, + protos.google.privacy.dlp.v2.IUpdateJobTriggerRequest | undefined, + {} | undefined, + ] + >; updateJobTrigger( - request: protos.google.privacy.dlp.v2.IUpdateJobTriggerRequest, - options: CallOptions, - callback: Callback< - protos.google.privacy.dlp.v2.IJobTrigger, - protos.google.privacy.dlp.v2.IUpdateJobTriggerRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.privacy.dlp.v2.IUpdateJobTriggerRequest, + options: CallOptions, + callback: Callback< + protos.google.privacy.dlp.v2.IJobTrigger, + protos.google.privacy.dlp.v2.IUpdateJobTriggerRequest | null | undefined, + {} | null | undefined + >, + ): void; updateJobTrigger( - request: protos.google.privacy.dlp.v2.IUpdateJobTriggerRequest, - callback: Callback< - protos.google.privacy.dlp.v2.IJobTrigger, - protos.google.privacy.dlp.v2.IUpdateJobTriggerRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.privacy.dlp.v2.IUpdateJobTriggerRequest, + callback: Callback< + protos.google.privacy.dlp.v2.IJobTrigger, + protos.google.privacy.dlp.v2.IUpdateJobTriggerRequest | null | undefined, + {} | null | undefined + >, + ): void; updateJobTrigger( - request?: protos.google.privacy.dlp.v2.IUpdateJobTriggerRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.privacy.dlp.v2.IJobTrigger, - protos.google.privacy.dlp.v2.IUpdateJobTriggerRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.privacy.dlp.v2.IUpdateJobTriggerRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.privacy.dlp.v2.IJobTrigger, - protos.google.privacy.dlp.v2.IUpdateJobTriggerRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.privacy.dlp.v2.IJobTrigger, - protos.google.privacy.dlp.v2.IUpdateJobTriggerRequest|undefined, {}|undefined - ]>|void { + | protos.google.privacy.dlp.v2.IUpdateJobTriggerRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.privacy.dlp.v2.IJobTrigger, + protos.google.privacy.dlp.v2.IUpdateJobTriggerRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.privacy.dlp.v2.IJobTrigger, + protos.google.privacy.dlp.v2.IUpdateJobTriggerRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateJobTrigger request %j', request); - const wrappedCallback: Callback< - protos.google.privacy.dlp.v2.IJobTrigger, - protos.google.privacy.dlp.v2.IUpdateJobTriggerRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.privacy.dlp.v2.IJobTrigger, + | protos.google.privacy.dlp.v2.IUpdateJobTriggerRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateJobTrigger response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.updateJobTrigger(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.privacy.dlp.v2.IJobTrigger, - protos.google.privacy.dlp.v2.IUpdateJobTriggerRequest|undefined, - {}|undefined - ]) => { - this._log.info('updateJobTrigger response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateJobTrigger(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.privacy.dlp.v2.IJobTrigger, + protos.google.privacy.dlp.v2.IUpdateJobTriggerRequest | undefined, + {} | undefined, + ]) => { + this._log.info('updateJobTrigger response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Gets a job trigger. - * See https://cloud.google.com/dlp/docs/creating-job-triggers to learn more. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. Resource name of the project and the triggeredJob, for example - * `projects/dlp-test-project/jobTriggers/53234423`. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.privacy.dlp.v2.JobTrigger|JobTrigger}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/dlp_service.get_job_trigger.js - * region_tag:dlp_v2_generated_DlpService_GetJobTrigger_async - */ + /** + * Gets a job trigger. + * See https://cloud.google.com/dlp/docs/creating-job-triggers to learn more. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Resource name of the project and the triggeredJob, for example + * `projects/dlp-test-project/jobTriggers/53234423`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.privacy.dlp.v2.JobTrigger|JobTrigger}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/dlp_service.get_job_trigger.js + * region_tag:dlp_v2_generated_DlpService_GetJobTrigger_async + */ getJobTrigger( - request?: protos.google.privacy.dlp.v2.IGetJobTriggerRequest, - options?: CallOptions): - Promise<[ - protos.google.privacy.dlp.v2.IJobTrigger, - protos.google.privacy.dlp.v2.IGetJobTriggerRequest|undefined, {}|undefined - ]>; + request?: protos.google.privacy.dlp.v2.IGetJobTriggerRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.privacy.dlp.v2.IJobTrigger, + protos.google.privacy.dlp.v2.IGetJobTriggerRequest | undefined, + {} | undefined, + ] + >; getJobTrigger( - request: protos.google.privacy.dlp.v2.IGetJobTriggerRequest, - options: CallOptions, - callback: Callback< - protos.google.privacy.dlp.v2.IJobTrigger, - protos.google.privacy.dlp.v2.IGetJobTriggerRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.privacy.dlp.v2.IGetJobTriggerRequest, + options: CallOptions, + callback: Callback< + protos.google.privacy.dlp.v2.IJobTrigger, + protos.google.privacy.dlp.v2.IGetJobTriggerRequest | null | undefined, + {} | null | undefined + >, + ): void; getJobTrigger( - request: protos.google.privacy.dlp.v2.IGetJobTriggerRequest, - callback: Callback< - protos.google.privacy.dlp.v2.IJobTrigger, - protos.google.privacy.dlp.v2.IGetJobTriggerRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.privacy.dlp.v2.IGetJobTriggerRequest, + callback: Callback< + protos.google.privacy.dlp.v2.IJobTrigger, + protos.google.privacy.dlp.v2.IGetJobTriggerRequest | null | undefined, + {} | null | undefined + >, + ): void; getJobTrigger( - request?: protos.google.privacy.dlp.v2.IGetJobTriggerRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.privacy.dlp.v2.IGetJobTriggerRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.privacy.dlp.v2.IJobTrigger, - protos.google.privacy.dlp.v2.IGetJobTriggerRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.privacy.dlp.v2.IJobTrigger, - protos.google.privacy.dlp.v2.IGetJobTriggerRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.privacy.dlp.v2.IJobTrigger, - protos.google.privacy.dlp.v2.IGetJobTriggerRequest|undefined, {}|undefined - ]>|void { + protos.google.privacy.dlp.v2.IGetJobTriggerRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.privacy.dlp.v2.IJobTrigger, + protos.google.privacy.dlp.v2.IGetJobTriggerRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.privacy.dlp.v2.IJobTrigger, + protos.google.privacy.dlp.v2.IGetJobTriggerRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getJobTrigger request %j', request); - const wrappedCallback: Callback< - protos.google.privacy.dlp.v2.IJobTrigger, - protos.google.privacy.dlp.v2.IGetJobTriggerRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.privacy.dlp.v2.IJobTrigger, + protos.google.privacy.dlp.v2.IGetJobTriggerRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getJobTrigger response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getJobTrigger(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.privacy.dlp.v2.IJobTrigger, - protos.google.privacy.dlp.v2.IGetJobTriggerRequest|undefined, - {}|undefined - ]) => { - this._log.info('getJobTrigger response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getJobTrigger(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.privacy.dlp.v2.IJobTrigger, + protos.google.privacy.dlp.v2.IGetJobTriggerRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getJobTrigger response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Deletes a job trigger. - * See https://cloud.google.com/dlp/docs/creating-job-triggers to learn more. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. Resource name of the project and the triggeredJob, for example - * `projects/dlp-test-project/jobTriggers/53234423`. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/dlp_service.delete_job_trigger.js - * region_tag:dlp_v2_generated_DlpService_DeleteJobTrigger_async - */ + /** + * Deletes a job trigger. + * See https://cloud.google.com/dlp/docs/creating-job-triggers to learn more. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Resource name of the project and the triggeredJob, for example + * `projects/dlp-test-project/jobTriggers/53234423`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/dlp_service.delete_job_trigger.js + * region_tag:dlp_v2_generated_DlpService_DeleteJobTrigger_async + */ deleteJobTrigger( - request?: protos.google.privacy.dlp.v2.IDeleteJobTriggerRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.privacy.dlp.v2.IDeleteJobTriggerRequest|undefined, {}|undefined - ]>; + request?: protos.google.privacy.dlp.v2.IDeleteJobTriggerRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.privacy.dlp.v2.IDeleteJobTriggerRequest | undefined, + {} | undefined, + ] + >; deleteJobTrigger( - request: protos.google.privacy.dlp.v2.IDeleteJobTriggerRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.privacy.dlp.v2.IDeleteJobTriggerRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.privacy.dlp.v2.IDeleteJobTriggerRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.privacy.dlp.v2.IDeleteJobTriggerRequest | null | undefined, + {} | null | undefined + >, + ): void; deleteJobTrigger( - request: protos.google.privacy.dlp.v2.IDeleteJobTriggerRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.privacy.dlp.v2.IDeleteJobTriggerRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.privacy.dlp.v2.IDeleteJobTriggerRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.privacy.dlp.v2.IDeleteJobTriggerRequest | null | undefined, + {} | null | undefined + >, + ): void; deleteJobTrigger( - request?: protos.google.privacy.dlp.v2.IDeleteJobTriggerRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.protobuf.IEmpty, - protos.google.privacy.dlp.v2.IDeleteJobTriggerRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.privacy.dlp.v2.IDeleteJobTriggerRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.privacy.dlp.v2.IDeleteJobTriggerRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.privacy.dlp.v2.IDeleteJobTriggerRequest|undefined, {}|undefined - ]>|void { + | protos.google.privacy.dlp.v2.IDeleteJobTriggerRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + protos.google.privacy.dlp.v2.IDeleteJobTriggerRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.privacy.dlp.v2.IDeleteJobTriggerRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('deleteJobTrigger request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.privacy.dlp.v2.IDeleteJobTriggerRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.privacy.dlp.v2.IDeleteJobTriggerRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteJobTrigger response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.deleteJobTrigger(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.privacy.dlp.v2.IDeleteJobTriggerRequest|undefined, - {}|undefined - ]) => { - this._log.info('deleteJobTrigger response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteJobTrigger(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.privacy.dlp.v2.IDeleteJobTriggerRequest | undefined, + {} | undefined, + ]) => { + this._log.info('deleteJobTrigger response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Activate a job trigger. Causes the immediate execute of a trigger - * instead of waiting on the trigger event to occur. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. Resource name of the trigger to activate, for example - * `projects/dlp-test-project/jobTriggers/53234423`. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.privacy.dlp.v2.DlpJob|DlpJob}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/dlp_service.activate_job_trigger.js - * region_tag:dlp_v2_generated_DlpService_ActivateJobTrigger_async - */ + /** + * Activate a job trigger. Causes the immediate execute of a trigger + * instead of waiting on the trigger event to occur. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Resource name of the trigger to activate, for example + * `projects/dlp-test-project/jobTriggers/53234423`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.privacy.dlp.v2.DlpJob|DlpJob}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/dlp_service.activate_job_trigger.js + * region_tag:dlp_v2_generated_DlpService_ActivateJobTrigger_async + */ activateJobTrigger( - request?: protos.google.privacy.dlp.v2.IActivateJobTriggerRequest, - options?: CallOptions): - Promise<[ - protos.google.privacy.dlp.v2.IDlpJob, - protos.google.privacy.dlp.v2.IActivateJobTriggerRequest|undefined, {}|undefined - ]>; + request?: protos.google.privacy.dlp.v2.IActivateJobTriggerRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.privacy.dlp.v2.IDlpJob, + protos.google.privacy.dlp.v2.IActivateJobTriggerRequest | undefined, + {} | undefined, + ] + >; activateJobTrigger( - request: protos.google.privacy.dlp.v2.IActivateJobTriggerRequest, - options: CallOptions, - callback: Callback< - protos.google.privacy.dlp.v2.IDlpJob, - protos.google.privacy.dlp.v2.IActivateJobTriggerRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.privacy.dlp.v2.IActivateJobTriggerRequest, + options: CallOptions, + callback: Callback< + protos.google.privacy.dlp.v2.IDlpJob, + | protos.google.privacy.dlp.v2.IActivateJobTriggerRequest + | null + | undefined, + {} | null | undefined + >, + ): void; activateJobTrigger( - request: protos.google.privacy.dlp.v2.IActivateJobTriggerRequest, - callback: Callback< - protos.google.privacy.dlp.v2.IDlpJob, - protos.google.privacy.dlp.v2.IActivateJobTriggerRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.privacy.dlp.v2.IActivateJobTriggerRequest, + callback: Callback< + protos.google.privacy.dlp.v2.IDlpJob, + | protos.google.privacy.dlp.v2.IActivateJobTriggerRequest + | null + | undefined, + {} | null | undefined + >, + ): void; activateJobTrigger( - request?: protos.google.privacy.dlp.v2.IActivateJobTriggerRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.privacy.dlp.v2.IActivateJobTriggerRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.privacy.dlp.v2.IDlpJob, - protos.google.privacy.dlp.v2.IActivateJobTriggerRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.privacy.dlp.v2.IDlpJob, - protos.google.privacy.dlp.v2.IActivateJobTriggerRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.privacy.dlp.v2.IDlpJob, - protos.google.privacy.dlp.v2.IActivateJobTriggerRequest|undefined, {}|undefined - ]>|void { + | protos.google.privacy.dlp.v2.IActivateJobTriggerRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.privacy.dlp.v2.IDlpJob, + | protos.google.privacy.dlp.v2.IActivateJobTriggerRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.privacy.dlp.v2.IDlpJob, + protos.google.privacy.dlp.v2.IActivateJobTriggerRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('activateJobTrigger request %j', request); - const wrappedCallback: Callback< - protos.google.privacy.dlp.v2.IDlpJob, - protos.google.privacy.dlp.v2.IActivateJobTriggerRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.privacy.dlp.v2.IDlpJob, + | protos.google.privacy.dlp.v2.IActivateJobTriggerRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('activateJobTrigger response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.activateJobTrigger(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.privacy.dlp.v2.IDlpJob, - protos.google.privacy.dlp.v2.IActivateJobTriggerRequest|undefined, - {}|undefined - ]) => { - this._log.info('activateJobTrigger response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .activateJobTrigger(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.privacy.dlp.v2.IDlpJob, + protos.google.privacy.dlp.v2.IActivateJobTriggerRequest | undefined, + {} | undefined, + ]) => { + this._log.info('activateJobTrigger response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Creates a new job to inspect storage or calculate risk metrics. - * See https://cloud.google.com/dlp/docs/inspecting-storage and - * https://cloud.google.com/dlp/docs/compute-risk-analysis to learn more. - * - * When no InfoTypes or CustomInfoTypes are specified in inspect jobs, the - * system will automatically choose what detectors to run. By default this may - * be all types, but may change over time as detectors are updated. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent resource name, for example projects/my-project-id. - * @param {google.privacy.dlp.v2.InspectJobConfig} request.inspectJob - * Set to control what and how to inspect. - * @param {google.privacy.dlp.v2.RiskAnalysisJobConfig} request.riskJob - * Set to choose what metric to calculate. - * @param {string} request.jobId - * The job id can contain uppercase and lowercase letters, - * numbers, and hyphens; that is, it must match the regular - * expression: `[a-zA-Z\\d-_]+`. The maximum length is 100 - * characters. Can be empty to allow the system to generate one. - * @param {string} request.locationId - * The geographic location to store and process the job. Reserved for - * future extensions. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.privacy.dlp.v2.DlpJob|DlpJob}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/dlp_service.create_dlp_job.js - * region_tag:dlp_v2_generated_DlpService_CreateDlpJob_async - */ + /** + * Creates a new job to inspect storage or calculate risk metrics. + * See https://cloud.google.com/dlp/docs/inspecting-storage and + * https://cloud.google.com/dlp/docs/compute-risk-analysis to learn more. + * + * When no InfoTypes or CustomInfoTypes are specified in inspect jobs, the + * system will automatically choose what detectors to run. By default this may + * be all types, but may change over time as detectors are updated. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource name, for example projects/my-project-id. + * @param {google.privacy.dlp.v2.InspectJobConfig} request.inspectJob + * Set to control what and how to inspect. + * @param {google.privacy.dlp.v2.RiskAnalysisJobConfig} request.riskJob + * Set to choose what metric to calculate. + * @param {string} request.jobId + * The job id can contain uppercase and lowercase letters, + * numbers, and hyphens; that is, it must match the regular + * expression: `[a-zA-Z\\d-_]+`. The maximum length is 100 + * characters. Can be empty to allow the system to generate one. + * @param {string} request.locationId + * The geographic location to store and process the job. Reserved for + * future extensions. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.privacy.dlp.v2.DlpJob|DlpJob}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/dlp_service.create_dlp_job.js + * region_tag:dlp_v2_generated_DlpService_CreateDlpJob_async + */ createDlpJob( - request?: protos.google.privacy.dlp.v2.ICreateDlpJobRequest, - options?: CallOptions): - Promise<[ - protos.google.privacy.dlp.v2.IDlpJob, - protos.google.privacy.dlp.v2.ICreateDlpJobRequest|undefined, {}|undefined - ]>; + request?: protos.google.privacy.dlp.v2.ICreateDlpJobRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.privacy.dlp.v2.IDlpJob, + protos.google.privacy.dlp.v2.ICreateDlpJobRequest | undefined, + {} | undefined, + ] + >; createDlpJob( - request: protos.google.privacy.dlp.v2.ICreateDlpJobRequest, - options: CallOptions, - callback: Callback< - protos.google.privacy.dlp.v2.IDlpJob, - protos.google.privacy.dlp.v2.ICreateDlpJobRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.privacy.dlp.v2.ICreateDlpJobRequest, + options: CallOptions, + callback: Callback< + protos.google.privacy.dlp.v2.IDlpJob, + protos.google.privacy.dlp.v2.ICreateDlpJobRequest | null | undefined, + {} | null | undefined + >, + ): void; createDlpJob( - request: protos.google.privacy.dlp.v2.ICreateDlpJobRequest, - callback: Callback< - protos.google.privacy.dlp.v2.IDlpJob, - protos.google.privacy.dlp.v2.ICreateDlpJobRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.privacy.dlp.v2.ICreateDlpJobRequest, + callback: Callback< + protos.google.privacy.dlp.v2.IDlpJob, + protos.google.privacy.dlp.v2.ICreateDlpJobRequest | null | undefined, + {} | null | undefined + >, + ): void; createDlpJob( - request?: protos.google.privacy.dlp.v2.ICreateDlpJobRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.privacy.dlp.v2.IDlpJob, - protos.google.privacy.dlp.v2.ICreateDlpJobRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.privacy.dlp.v2.ICreateDlpJobRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.privacy.dlp.v2.IDlpJob, - protos.google.privacy.dlp.v2.ICreateDlpJobRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.privacy.dlp.v2.IDlpJob, - protos.google.privacy.dlp.v2.ICreateDlpJobRequest|undefined, {}|undefined - ]>|void { + protos.google.privacy.dlp.v2.ICreateDlpJobRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.privacy.dlp.v2.IDlpJob, + protos.google.privacy.dlp.v2.ICreateDlpJobRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.privacy.dlp.v2.IDlpJob, + protos.google.privacy.dlp.v2.ICreateDlpJobRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - 'location_id': request.locationId?.toString() ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + location_id: request.locationId?.toString() ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('createDlpJob request %j', request); - const wrappedCallback: Callback< - protos.google.privacy.dlp.v2.IDlpJob, - protos.google.privacy.dlp.v2.ICreateDlpJobRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.privacy.dlp.v2.IDlpJob, + protos.google.privacy.dlp.v2.ICreateDlpJobRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createDlpJob response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.createDlpJob(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.privacy.dlp.v2.IDlpJob, - protos.google.privacy.dlp.v2.ICreateDlpJobRequest|undefined, - {}|undefined - ]) => { - this._log.info('createDlpJob response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createDlpJob(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.privacy.dlp.v2.IDlpJob, + protos.google.privacy.dlp.v2.ICreateDlpJobRequest | undefined, + {} | undefined, + ]) => { + this._log.info('createDlpJob response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Gets the latest state of a long-running DlpJob. - * See https://cloud.google.com/dlp/docs/inspecting-storage and - * https://cloud.google.com/dlp/docs/compute-risk-analysis to learn more. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The name of the DlpJob resource. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.privacy.dlp.v2.DlpJob|DlpJob}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/dlp_service.get_dlp_job.js - * region_tag:dlp_v2_generated_DlpService_GetDlpJob_async - */ + /** + * Gets the latest state of a long-running DlpJob. + * See https://cloud.google.com/dlp/docs/inspecting-storage and + * https://cloud.google.com/dlp/docs/compute-risk-analysis to learn more. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The name of the DlpJob resource. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.privacy.dlp.v2.DlpJob|DlpJob}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/dlp_service.get_dlp_job.js + * region_tag:dlp_v2_generated_DlpService_GetDlpJob_async + */ getDlpJob( - request?: protos.google.privacy.dlp.v2.IGetDlpJobRequest, - options?: CallOptions): - Promise<[ - protos.google.privacy.dlp.v2.IDlpJob, - protos.google.privacy.dlp.v2.IGetDlpJobRequest|undefined, {}|undefined - ]>; + request?: protos.google.privacy.dlp.v2.IGetDlpJobRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.privacy.dlp.v2.IDlpJob, + protos.google.privacy.dlp.v2.IGetDlpJobRequest | undefined, + {} | undefined, + ] + >; getDlpJob( - request: protos.google.privacy.dlp.v2.IGetDlpJobRequest, - options: CallOptions, - callback: Callback< - protos.google.privacy.dlp.v2.IDlpJob, - protos.google.privacy.dlp.v2.IGetDlpJobRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.privacy.dlp.v2.IGetDlpJobRequest, + options: CallOptions, + callback: Callback< + protos.google.privacy.dlp.v2.IDlpJob, + protos.google.privacy.dlp.v2.IGetDlpJobRequest | null | undefined, + {} | null | undefined + >, + ): void; getDlpJob( - request: protos.google.privacy.dlp.v2.IGetDlpJobRequest, - callback: Callback< - protos.google.privacy.dlp.v2.IDlpJob, - protos.google.privacy.dlp.v2.IGetDlpJobRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.privacy.dlp.v2.IGetDlpJobRequest, + callback: Callback< + protos.google.privacy.dlp.v2.IDlpJob, + protos.google.privacy.dlp.v2.IGetDlpJobRequest | null | undefined, + {} | null | undefined + >, + ): void; getDlpJob( - request?: protos.google.privacy.dlp.v2.IGetDlpJobRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.privacy.dlp.v2.IGetDlpJobRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.privacy.dlp.v2.IDlpJob, - protos.google.privacy.dlp.v2.IGetDlpJobRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.privacy.dlp.v2.IDlpJob, - protos.google.privacy.dlp.v2.IGetDlpJobRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.privacy.dlp.v2.IDlpJob, - protos.google.privacy.dlp.v2.IGetDlpJobRequest|undefined, {}|undefined - ]>|void { + protos.google.privacy.dlp.v2.IGetDlpJobRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.privacy.dlp.v2.IDlpJob, + protos.google.privacy.dlp.v2.IGetDlpJobRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.privacy.dlp.v2.IDlpJob, + protos.google.privacy.dlp.v2.IGetDlpJobRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getDlpJob request %j', request); - const wrappedCallback: Callback< - protos.google.privacy.dlp.v2.IDlpJob, - protos.google.privacy.dlp.v2.IGetDlpJobRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.privacy.dlp.v2.IDlpJob, + protos.google.privacy.dlp.v2.IGetDlpJobRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getDlpJob response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getDlpJob(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.privacy.dlp.v2.IDlpJob, - protos.google.privacy.dlp.v2.IGetDlpJobRequest|undefined, - {}|undefined - ]) => { - this._log.info('getDlpJob response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getDlpJob(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.privacy.dlp.v2.IDlpJob, + protos.google.privacy.dlp.v2.IGetDlpJobRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getDlpJob response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Deletes a long-running DlpJob. This method indicates that the client is - * no longer interested in the DlpJob result. The job will be cancelled if - * possible. - * See https://cloud.google.com/dlp/docs/inspecting-storage and - * https://cloud.google.com/dlp/docs/compute-risk-analysis to learn more. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The name of the DlpJob resource to be deleted. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/dlp_service.delete_dlp_job.js - * region_tag:dlp_v2_generated_DlpService_DeleteDlpJob_async - */ + /** + * Deletes a long-running DlpJob. This method indicates that the client is + * no longer interested in the DlpJob result. The job will be cancelled if + * possible. + * See https://cloud.google.com/dlp/docs/inspecting-storage and + * https://cloud.google.com/dlp/docs/compute-risk-analysis to learn more. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The name of the DlpJob resource to be deleted. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/dlp_service.delete_dlp_job.js + * region_tag:dlp_v2_generated_DlpService_DeleteDlpJob_async + */ deleteDlpJob( - request?: protos.google.privacy.dlp.v2.IDeleteDlpJobRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.privacy.dlp.v2.IDeleteDlpJobRequest|undefined, {}|undefined - ]>; + request?: protos.google.privacy.dlp.v2.IDeleteDlpJobRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.privacy.dlp.v2.IDeleteDlpJobRequest | undefined, + {} | undefined, + ] + >; deleteDlpJob( - request: protos.google.privacy.dlp.v2.IDeleteDlpJobRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.privacy.dlp.v2.IDeleteDlpJobRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.privacy.dlp.v2.IDeleteDlpJobRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.privacy.dlp.v2.IDeleteDlpJobRequest | null | undefined, + {} | null | undefined + >, + ): void; deleteDlpJob( - request: protos.google.privacy.dlp.v2.IDeleteDlpJobRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.privacy.dlp.v2.IDeleteDlpJobRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.privacy.dlp.v2.IDeleteDlpJobRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.privacy.dlp.v2.IDeleteDlpJobRequest | null | undefined, + {} | null | undefined + >, + ): void; deleteDlpJob( - request?: protos.google.privacy.dlp.v2.IDeleteDlpJobRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.protobuf.IEmpty, - protos.google.privacy.dlp.v2.IDeleteDlpJobRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.privacy.dlp.v2.IDeleteDlpJobRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.privacy.dlp.v2.IDeleteDlpJobRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.privacy.dlp.v2.IDeleteDlpJobRequest|undefined, {}|undefined - ]>|void { + protos.google.privacy.dlp.v2.IDeleteDlpJobRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + protos.google.privacy.dlp.v2.IDeleteDlpJobRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.privacy.dlp.v2.IDeleteDlpJobRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('deleteDlpJob request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.privacy.dlp.v2.IDeleteDlpJobRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + protos.google.privacy.dlp.v2.IDeleteDlpJobRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteDlpJob response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.deleteDlpJob(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.privacy.dlp.v2.IDeleteDlpJobRequest|undefined, - {}|undefined - ]) => { - this._log.info('deleteDlpJob response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteDlpJob(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.privacy.dlp.v2.IDeleteDlpJobRequest | undefined, + {} | undefined, + ]) => { + this._log.info('deleteDlpJob response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Starts asynchronous cancellation on a long-running DlpJob. The server - * makes a best effort to cancel the DlpJob, but success is not - * guaranteed. - * See https://cloud.google.com/dlp/docs/inspecting-storage and - * https://cloud.google.com/dlp/docs/compute-risk-analysis to learn more. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The name of the DlpJob resource to be cancelled. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/dlp_service.cancel_dlp_job.js - * region_tag:dlp_v2_generated_DlpService_CancelDlpJob_async - */ + /** + * Starts asynchronous cancellation on a long-running DlpJob. The server + * makes a best effort to cancel the DlpJob, but success is not + * guaranteed. + * See https://cloud.google.com/dlp/docs/inspecting-storage and + * https://cloud.google.com/dlp/docs/compute-risk-analysis to learn more. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The name of the DlpJob resource to be cancelled. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/dlp_service.cancel_dlp_job.js + * region_tag:dlp_v2_generated_DlpService_CancelDlpJob_async + */ cancelDlpJob( - request?: protos.google.privacy.dlp.v2.ICancelDlpJobRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.privacy.dlp.v2.ICancelDlpJobRequest|undefined, {}|undefined - ]>; + request?: protos.google.privacy.dlp.v2.ICancelDlpJobRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.privacy.dlp.v2.ICancelDlpJobRequest | undefined, + {} | undefined, + ] + >; cancelDlpJob( - request: protos.google.privacy.dlp.v2.ICancelDlpJobRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.privacy.dlp.v2.ICancelDlpJobRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.privacy.dlp.v2.ICancelDlpJobRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.privacy.dlp.v2.ICancelDlpJobRequest | null | undefined, + {} | null | undefined + >, + ): void; cancelDlpJob( - request: protos.google.privacy.dlp.v2.ICancelDlpJobRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.privacy.dlp.v2.ICancelDlpJobRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.privacy.dlp.v2.ICancelDlpJobRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.privacy.dlp.v2.ICancelDlpJobRequest | null | undefined, + {} | null | undefined + >, + ): void; cancelDlpJob( - request?: protos.google.privacy.dlp.v2.ICancelDlpJobRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.privacy.dlp.v2.ICancelDlpJobRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.privacy.dlp.v2.ICancelDlpJobRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.protobuf.IEmpty, - protos.google.privacy.dlp.v2.ICancelDlpJobRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.privacy.dlp.v2.ICancelDlpJobRequest|undefined, {}|undefined - ]>|void { + protos.google.privacy.dlp.v2.ICancelDlpJobRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + protos.google.privacy.dlp.v2.ICancelDlpJobRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.privacy.dlp.v2.ICancelDlpJobRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('cancelDlpJob request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.privacy.dlp.v2.ICancelDlpJobRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + protos.google.privacy.dlp.v2.ICancelDlpJobRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('cancelDlpJob response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.cancelDlpJob(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.privacy.dlp.v2.ICancelDlpJobRequest|undefined, - {}|undefined - ]) => { - this._log.info('cancelDlpJob response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .cancelDlpJob(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.privacy.dlp.v2.ICancelDlpJobRequest | undefined, + {} | undefined, + ]) => { + this._log.info('cancelDlpJob response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Creates a pre-built stored infoType to be used for inspection. - * See https://cloud.google.com/dlp/docs/creating-stored-infotypes to - * learn more. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent resource name, for example projects/my-project-id or - * organizations/my-org-id. - * @param {google.privacy.dlp.v2.StoredInfoTypeConfig} request.config - * Required. Configuration of the storedInfoType to create. - * @param {string} request.storedInfoTypeId - * The storedInfoType ID can contain uppercase and lowercase letters, - * numbers, and hyphens; that is, it must match the regular - * expression: `[a-zA-Z\\d-_]+`. The maximum length is 100 - * characters. Can be empty to allow the system to generate one. - * @param {string} request.locationId - * The geographic location to store the stored infoType. Reserved for - * future extensions. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.privacy.dlp.v2.StoredInfoType|StoredInfoType}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/dlp_service.create_stored_info_type.js - * region_tag:dlp_v2_generated_DlpService_CreateStoredInfoType_async - */ + /** + * Creates a pre-built stored infoType to be used for inspection. + * See https://cloud.google.com/dlp/docs/creating-stored-infotypes to + * learn more. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource name, for example projects/my-project-id or + * organizations/my-org-id. + * @param {google.privacy.dlp.v2.StoredInfoTypeConfig} request.config + * Required. Configuration of the storedInfoType to create. + * @param {string} request.storedInfoTypeId + * The storedInfoType ID can contain uppercase and lowercase letters, + * numbers, and hyphens; that is, it must match the regular + * expression: `[a-zA-Z\\d-_]+`. The maximum length is 100 + * characters. Can be empty to allow the system to generate one. + * @param {string} request.locationId + * The geographic location to store the stored infoType. Reserved for + * future extensions. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.privacy.dlp.v2.StoredInfoType|StoredInfoType}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/dlp_service.create_stored_info_type.js + * region_tag:dlp_v2_generated_DlpService_CreateStoredInfoType_async + */ createStoredInfoType( - request?: protos.google.privacy.dlp.v2.ICreateStoredInfoTypeRequest, - options?: CallOptions): - Promise<[ - protos.google.privacy.dlp.v2.IStoredInfoType, - protos.google.privacy.dlp.v2.ICreateStoredInfoTypeRequest|undefined, {}|undefined - ]>; + request?: protos.google.privacy.dlp.v2.ICreateStoredInfoTypeRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.privacy.dlp.v2.IStoredInfoType, + protos.google.privacy.dlp.v2.ICreateStoredInfoTypeRequest | undefined, + {} | undefined, + ] + >; createStoredInfoType( - request: protos.google.privacy.dlp.v2.ICreateStoredInfoTypeRequest, - options: CallOptions, - callback: Callback< - protos.google.privacy.dlp.v2.IStoredInfoType, - protos.google.privacy.dlp.v2.ICreateStoredInfoTypeRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.privacy.dlp.v2.ICreateStoredInfoTypeRequest, + options: CallOptions, + callback: Callback< + protos.google.privacy.dlp.v2.IStoredInfoType, + | protos.google.privacy.dlp.v2.ICreateStoredInfoTypeRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createStoredInfoType( - request: protos.google.privacy.dlp.v2.ICreateStoredInfoTypeRequest, - callback: Callback< - protos.google.privacy.dlp.v2.IStoredInfoType, - protos.google.privacy.dlp.v2.ICreateStoredInfoTypeRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.privacy.dlp.v2.ICreateStoredInfoTypeRequest, + callback: Callback< + protos.google.privacy.dlp.v2.IStoredInfoType, + | protos.google.privacy.dlp.v2.ICreateStoredInfoTypeRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createStoredInfoType( - request?: protos.google.privacy.dlp.v2.ICreateStoredInfoTypeRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.privacy.dlp.v2.IStoredInfoType, - protos.google.privacy.dlp.v2.ICreateStoredInfoTypeRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.privacy.dlp.v2.ICreateStoredInfoTypeRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.privacy.dlp.v2.IStoredInfoType, - protos.google.privacy.dlp.v2.ICreateStoredInfoTypeRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.privacy.dlp.v2.IStoredInfoType, - protos.google.privacy.dlp.v2.ICreateStoredInfoTypeRequest|undefined, {}|undefined - ]>|void { + | protos.google.privacy.dlp.v2.ICreateStoredInfoTypeRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.privacy.dlp.v2.IStoredInfoType, + | protos.google.privacy.dlp.v2.ICreateStoredInfoTypeRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.privacy.dlp.v2.IStoredInfoType, + protos.google.privacy.dlp.v2.ICreateStoredInfoTypeRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - 'location_id': request.locationId?.toString() ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + location_id: request.locationId?.toString() ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('createStoredInfoType request %j', request); - const wrappedCallback: Callback< - protos.google.privacy.dlp.v2.IStoredInfoType, - protos.google.privacy.dlp.v2.ICreateStoredInfoTypeRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.privacy.dlp.v2.IStoredInfoType, + | protos.google.privacy.dlp.v2.ICreateStoredInfoTypeRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createStoredInfoType response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.createStoredInfoType(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.privacy.dlp.v2.IStoredInfoType, - protos.google.privacy.dlp.v2.ICreateStoredInfoTypeRequest|undefined, - {}|undefined - ]) => { - this._log.info('createStoredInfoType response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createStoredInfoType(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.privacy.dlp.v2.IStoredInfoType, + protos.google.privacy.dlp.v2.ICreateStoredInfoTypeRequest | undefined, + {} | undefined, + ]) => { + this._log.info('createStoredInfoType response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Updates the stored infoType by creating a new version. The existing version - * will continue to be used until the new version is ready. - * See https://cloud.google.com/dlp/docs/creating-stored-infotypes to - * learn more. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. Resource name of organization and storedInfoType to be updated, for - * example `organizations/433245324/storedInfoTypes/432452342` or - * projects/project-id/storedInfoTypes/432452342. - * @param {google.privacy.dlp.v2.StoredInfoTypeConfig} request.config - * Updated configuration for the storedInfoType. If not provided, a new - * version of the storedInfoType will be created with the existing - * configuration. - * @param {google.protobuf.FieldMask} request.updateMask - * Mask to control which fields get updated. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.privacy.dlp.v2.StoredInfoType|StoredInfoType}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/dlp_service.update_stored_info_type.js - * region_tag:dlp_v2_generated_DlpService_UpdateStoredInfoType_async - */ + /** + * Updates the stored infoType by creating a new version. The existing version + * will continue to be used until the new version is ready. + * See https://cloud.google.com/dlp/docs/creating-stored-infotypes to + * learn more. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Resource name of organization and storedInfoType to be updated, for + * example `organizations/433245324/storedInfoTypes/432452342` or + * projects/project-id/storedInfoTypes/432452342. + * @param {google.privacy.dlp.v2.StoredInfoTypeConfig} request.config + * Updated configuration for the storedInfoType. If not provided, a new + * version of the storedInfoType will be created with the existing + * configuration. + * @param {google.protobuf.FieldMask} request.updateMask + * Mask to control which fields get updated. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.privacy.dlp.v2.StoredInfoType|StoredInfoType}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/dlp_service.update_stored_info_type.js + * region_tag:dlp_v2_generated_DlpService_UpdateStoredInfoType_async + */ updateStoredInfoType( - request?: protos.google.privacy.dlp.v2.IUpdateStoredInfoTypeRequest, - options?: CallOptions): - Promise<[ - protos.google.privacy.dlp.v2.IStoredInfoType, - protos.google.privacy.dlp.v2.IUpdateStoredInfoTypeRequest|undefined, {}|undefined - ]>; + request?: protos.google.privacy.dlp.v2.IUpdateStoredInfoTypeRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.privacy.dlp.v2.IStoredInfoType, + protos.google.privacy.dlp.v2.IUpdateStoredInfoTypeRequest | undefined, + {} | undefined, + ] + >; updateStoredInfoType( - request: protos.google.privacy.dlp.v2.IUpdateStoredInfoTypeRequest, - options: CallOptions, - callback: Callback< - protos.google.privacy.dlp.v2.IStoredInfoType, - protos.google.privacy.dlp.v2.IUpdateStoredInfoTypeRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.privacy.dlp.v2.IUpdateStoredInfoTypeRequest, + options: CallOptions, + callback: Callback< + protos.google.privacy.dlp.v2.IStoredInfoType, + | protos.google.privacy.dlp.v2.IUpdateStoredInfoTypeRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateStoredInfoType( - request: protos.google.privacy.dlp.v2.IUpdateStoredInfoTypeRequest, - callback: Callback< - protos.google.privacy.dlp.v2.IStoredInfoType, - protos.google.privacy.dlp.v2.IUpdateStoredInfoTypeRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.privacy.dlp.v2.IUpdateStoredInfoTypeRequest, + callback: Callback< + protos.google.privacy.dlp.v2.IStoredInfoType, + | protos.google.privacy.dlp.v2.IUpdateStoredInfoTypeRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateStoredInfoType( - request?: protos.google.privacy.dlp.v2.IUpdateStoredInfoTypeRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.privacy.dlp.v2.IUpdateStoredInfoTypeRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.privacy.dlp.v2.IStoredInfoType, - protos.google.privacy.dlp.v2.IUpdateStoredInfoTypeRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.privacy.dlp.v2.IStoredInfoType, - protos.google.privacy.dlp.v2.IUpdateStoredInfoTypeRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.privacy.dlp.v2.IStoredInfoType, - protos.google.privacy.dlp.v2.IUpdateStoredInfoTypeRequest|undefined, {}|undefined - ]>|void { + | protos.google.privacy.dlp.v2.IUpdateStoredInfoTypeRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.privacy.dlp.v2.IStoredInfoType, + | protos.google.privacy.dlp.v2.IUpdateStoredInfoTypeRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.privacy.dlp.v2.IStoredInfoType, + protos.google.privacy.dlp.v2.IUpdateStoredInfoTypeRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateStoredInfoType request %j', request); - const wrappedCallback: Callback< - protos.google.privacy.dlp.v2.IStoredInfoType, - protos.google.privacy.dlp.v2.IUpdateStoredInfoTypeRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.privacy.dlp.v2.IStoredInfoType, + | protos.google.privacy.dlp.v2.IUpdateStoredInfoTypeRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateStoredInfoType response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.updateStoredInfoType(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.privacy.dlp.v2.IStoredInfoType, - protos.google.privacy.dlp.v2.IUpdateStoredInfoTypeRequest|undefined, - {}|undefined - ]) => { - this._log.info('updateStoredInfoType response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateStoredInfoType(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.privacy.dlp.v2.IStoredInfoType, + protos.google.privacy.dlp.v2.IUpdateStoredInfoTypeRequest | undefined, + {} | undefined, + ]) => { + this._log.info('updateStoredInfoType response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Gets a stored infoType. - * See https://cloud.google.com/dlp/docs/creating-stored-infotypes to - * learn more. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. Resource name of the organization and storedInfoType to be read, for - * example `organizations/433245324/storedInfoTypes/432452342` or - * projects/project-id/storedInfoTypes/432452342. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.privacy.dlp.v2.StoredInfoType|StoredInfoType}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/dlp_service.get_stored_info_type.js - * region_tag:dlp_v2_generated_DlpService_GetStoredInfoType_async - */ + /** + * Gets a stored infoType. + * See https://cloud.google.com/dlp/docs/creating-stored-infotypes to + * learn more. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Resource name of the organization and storedInfoType to be read, for + * example `organizations/433245324/storedInfoTypes/432452342` or + * projects/project-id/storedInfoTypes/432452342. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.privacy.dlp.v2.StoredInfoType|StoredInfoType}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/dlp_service.get_stored_info_type.js + * region_tag:dlp_v2_generated_DlpService_GetStoredInfoType_async + */ getStoredInfoType( - request?: protos.google.privacy.dlp.v2.IGetStoredInfoTypeRequest, - options?: CallOptions): - Promise<[ - protos.google.privacy.dlp.v2.IStoredInfoType, - protos.google.privacy.dlp.v2.IGetStoredInfoTypeRequest|undefined, {}|undefined - ]>; + request?: protos.google.privacy.dlp.v2.IGetStoredInfoTypeRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.privacy.dlp.v2.IStoredInfoType, + protos.google.privacy.dlp.v2.IGetStoredInfoTypeRequest | undefined, + {} | undefined, + ] + >; getStoredInfoType( - request: protos.google.privacy.dlp.v2.IGetStoredInfoTypeRequest, - options: CallOptions, - callback: Callback< - protos.google.privacy.dlp.v2.IStoredInfoType, - protos.google.privacy.dlp.v2.IGetStoredInfoTypeRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.privacy.dlp.v2.IGetStoredInfoTypeRequest, + options: CallOptions, + callback: Callback< + protos.google.privacy.dlp.v2.IStoredInfoType, + protos.google.privacy.dlp.v2.IGetStoredInfoTypeRequest | null | undefined, + {} | null | undefined + >, + ): void; getStoredInfoType( - request: protos.google.privacy.dlp.v2.IGetStoredInfoTypeRequest, - callback: Callback< - protos.google.privacy.dlp.v2.IStoredInfoType, - protos.google.privacy.dlp.v2.IGetStoredInfoTypeRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.privacy.dlp.v2.IGetStoredInfoTypeRequest, + callback: Callback< + protos.google.privacy.dlp.v2.IStoredInfoType, + protos.google.privacy.dlp.v2.IGetStoredInfoTypeRequest | null | undefined, + {} | null | undefined + >, + ): void; getStoredInfoType( - request?: protos.google.privacy.dlp.v2.IGetStoredInfoTypeRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.privacy.dlp.v2.IStoredInfoType, - protos.google.privacy.dlp.v2.IGetStoredInfoTypeRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.privacy.dlp.v2.IGetStoredInfoTypeRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.privacy.dlp.v2.IStoredInfoType, - protos.google.privacy.dlp.v2.IGetStoredInfoTypeRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.privacy.dlp.v2.IStoredInfoType, - protos.google.privacy.dlp.v2.IGetStoredInfoTypeRequest|undefined, {}|undefined - ]>|void { + | protos.google.privacy.dlp.v2.IGetStoredInfoTypeRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.privacy.dlp.v2.IStoredInfoType, + protos.google.privacy.dlp.v2.IGetStoredInfoTypeRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.privacy.dlp.v2.IStoredInfoType, + protos.google.privacy.dlp.v2.IGetStoredInfoTypeRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getStoredInfoType request %j', request); - const wrappedCallback: Callback< - protos.google.privacy.dlp.v2.IStoredInfoType, - protos.google.privacy.dlp.v2.IGetStoredInfoTypeRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.privacy.dlp.v2.IStoredInfoType, + | protos.google.privacy.dlp.v2.IGetStoredInfoTypeRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getStoredInfoType response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getStoredInfoType(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.privacy.dlp.v2.IStoredInfoType, - protos.google.privacy.dlp.v2.IGetStoredInfoTypeRequest|undefined, - {}|undefined - ]) => { - this._log.info('getStoredInfoType response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getStoredInfoType(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.privacy.dlp.v2.IStoredInfoType, + protos.google.privacy.dlp.v2.IGetStoredInfoTypeRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getStoredInfoType response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Deletes a stored infoType. - * See https://cloud.google.com/dlp/docs/creating-stored-infotypes to - * learn more. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. Resource name of the organization and storedInfoType to be deleted, for - * example `organizations/433245324/storedInfoTypes/432452342` or - * projects/project-id/storedInfoTypes/432452342. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/dlp_service.delete_stored_info_type.js - * region_tag:dlp_v2_generated_DlpService_DeleteStoredInfoType_async - */ + /** + * Deletes a stored infoType. + * See https://cloud.google.com/dlp/docs/creating-stored-infotypes to + * learn more. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Resource name of the organization and storedInfoType to be deleted, for + * example `organizations/433245324/storedInfoTypes/432452342` or + * projects/project-id/storedInfoTypes/432452342. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/dlp_service.delete_stored_info_type.js + * region_tag:dlp_v2_generated_DlpService_DeleteStoredInfoType_async + */ deleteStoredInfoType( - request?: protos.google.privacy.dlp.v2.IDeleteStoredInfoTypeRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.privacy.dlp.v2.IDeleteStoredInfoTypeRequest|undefined, {}|undefined - ]>; + request?: protos.google.privacy.dlp.v2.IDeleteStoredInfoTypeRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.privacy.dlp.v2.IDeleteStoredInfoTypeRequest | undefined, + {} | undefined, + ] + >; deleteStoredInfoType( - request: protos.google.privacy.dlp.v2.IDeleteStoredInfoTypeRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.privacy.dlp.v2.IDeleteStoredInfoTypeRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.privacy.dlp.v2.IDeleteStoredInfoTypeRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.privacy.dlp.v2.IDeleteStoredInfoTypeRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteStoredInfoType( - request: protos.google.privacy.dlp.v2.IDeleteStoredInfoTypeRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.privacy.dlp.v2.IDeleteStoredInfoTypeRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.privacy.dlp.v2.IDeleteStoredInfoTypeRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.privacy.dlp.v2.IDeleteStoredInfoTypeRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteStoredInfoType( - request?: protos.google.privacy.dlp.v2.IDeleteStoredInfoTypeRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.privacy.dlp.v2.IDeleteStoredInfoTypeRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.privacy.dlp.v2.IDeleteStoredInfoTypeRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.protobuf.IEmpty, - protos.google.privacy.dlp.v2.IDeleteStoredInfoTypeRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.privacy.dlp.v2.IDeleteStoredInfoTypeRequest|undefined, {}|undefined - ]>|void { + | protos.google.privacy.dlp.v2.IDeleteStoredInfoTypeRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + | protos.google.privacy.dlp.v2.IDeleteStoredInfoTypeRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.privacy.dlp.v2.IDeleteStoredInfoTypeRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('deleteStoredInfoType request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.privacy.dlp.v2.IDeleteStoredInfoTypeRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.privacy.dlp.v2.IDeleteStoredInfoTypeRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteStoredInfoType response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.deleteStoredInfoType(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.privacy.dlp.v2.IDeleteStoredInfoTypeRequest|undefined, - {}|undefined - ]) => { - this._log.info('deleteStoredInfoType response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteStoredInfoType(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.privacy.dlp.v2.IDeleteStoredInfoTypeRequest | undefined, + {} | undefined, + ]) => { + this._log.info('deleteStoredInfoType response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } - /** - * Lists InspectTemplates. - * See https://cloud.google.com/dlp/docs/creating-templates to learn more. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent resource name, for example projects/my-project-id or - * organizations/my-org-id. - * @param {string} request.pageToken - * Page token to continue retrieval. Comes from previous call - * to `ListInspectTemplates`. - * @param {number} request.pageSize - * Size of the page, can be limited by server. If zero server returns - * a page of max size 100. - * @param {string} request.orderBy - * Comma separated list of fields to order by, - * followed by `asc` or `desc` postfix. This list is case-insensitive, - * default sorting order is ascending, redundant space characters are - * insignificant. - * - * Example: `name asc,update_time, create_time desc` - * - * Supported fields are: - * - * - `create_time`: corresponds to time the template was created. - * - `update_time`: corresponds to time the template was last updated. - * - `name`: corresponds to template's name. - * - `display_name`: corresponds to template's display name. - * @param {string} request.locationId - * The geographic location where inspection templates will be retrieved from. - * Use `-` for all locations. Reserved for future extensions. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.privacy.dlp.v2.InspectTemplate|InspectTemplate}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `listInspectTemplatesAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Lists InspectTemplates. + * See https://cloud.google.com/dlp/docs/creating-templates to learn more. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource name, for example projects/my-project-id or + * organizations/my-org-id. + * @param {string} request.pageToken + * Page token to continue retrieval. Comes from previous call + * to `ListInspectTemplates`. + * @param {number} request.pageSize + * Size of the page, can be limited by server. If zero server returns + * a page of max size 100. + * @param {string} request.orderBy + * Comma separated list of fields to order by, + * followed by `asc` or `desc` postfix. This list is case-insensitive, + * default sorting order is ascending, redundant space characters are + * insignificant. + * + * Example: `name asc,update_time, create_time desc` + * + * Supported fields are: + * + * - `create_time`: corresponds to time the template was created. + * - `update_time`: corresponds to time the template was last updated. + * - `name`: corresponds to template's name. + * - `display_name`: corresponds to template's display name. + * @param {string} request.locationId + * The geographic location where inspection templates will be retrieved from. + * Use `-` for all locations. Reserved for future extensions. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.privacy.dlp.v2.InspectTemplate|InspectTemplate}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listInspectTemplatesAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listInspectTemplates( - request?: protos.google.privacy.dlp.v2.IListInspectTemplatesRequest, - options?: CallOptions): - Promise<[ - protos.google.privacy.dlp.v2.IInspectTemplate[], - protos.google.privacy.dlp.v2.IListInspectTemplatesRequest|null, - protos.google.privacy.dlp.v2.IListInspectTemplatesResponse - ]>; + request?: protos.google.privacy.dlp.v2.IListInspectTemplatesRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.privacy.dlp.v2.IInspectTemplate[], + protos.google.privacy.dlp.v2.IListInspectTemplatesRequest | null, + protos.google.privacy.dlp.v2.IListInspectTemplatesResponse, + ] + >; listInspectTemplates( - request: protos.google.privacy.dlp.v2.IListInspectTemplatesRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.privacy.dlp.v2.IListInspectTemplatesRequest, - protos.google.privacy.dlp.v2.IListInspectTemplatesResponse|null|undefined, - protos.google.privacy.dlp.v2.IInspectTemplate>): void; + request: protos.google.privacy.dlp.v2.IListInspectTemplatesRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.privacy.dlp.v2.IListInspectTemplatesRequest, + | protos.google.privacy.dlp.v2.IListInspectTemplatesResponse + | null + | undefined, + protos.google.privacy.dlp.v2.IInspectTemplate + >, + ): void; listInspectTemplates( - request: protos.google.privacy.dlp.v2.IListInspectTemplatesRequest, - callback: PaginationCallback< - protos.google.privacy.dlp.v2.IListInspectTemplatesRequest, - protos.google.privacy.dlp.v2.IListInspectTemplatesResponse|null|undefined, - protos.google.privacy.dlp.v2.IInspectTemplate>): void; + request: protos.google.privacy.dlp.v2.IListInspectTemplatesRequest, + callback: PaginationCallback< + protos.google.privacy.dlp.v2.IListInspectTemplatesRequest, + | protos.google.privacy.dlp.v2.IListInspectTemplatesResponse + | null + | undefined, + protos.google.privacy.dlp.v2.IInspectTemplate + >, + ): void; listInspectTemplates( - request?: protos.google.privacy.dlp.v2.IListInspectTemplatesRequest, - optionsOrCallback?: CallOptions|PaginationCallback< + request?: protos.google.privacy.dlp.v2.IListInspectTemplatesRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.privacy.dlp.v2.IListInspectTemplatesRequest, - protos.google.privacy.dlp.v2.IListInspectTemplatesResponse|null|undefined, - protos.google.privacy.dlp.v2.IInspectTemplate>, - callback?: PaginationCallback< - protos.google.privacy.dlp.v2.IListInspectTemplatesRequest, - protos.google.privacy.dlp.v2.IListInspectTemplatesResponse|null|undefined, - protos.google.privacy.dlp.v2.IInspectTemplate>): - Promise<[ - protos.google.privacy.dlp.v2.IInspectTemplate[], - protos.google.privacy.dlp.v2.IListInspectTemplatesRequest|null, - protos.google.privacy.dlp.v2.IListInspectTemplatesResponse - ]>|void { + | protos.google.privacy.dlp.v2.IListInspectTemplatesResponse + | null + | undefined, + protos.google.privacy.dlp.v2.IInspectTemplate + >, + callback?: PaginationCallback< + protos.google.privacy.dlp.v2.IListInspectTemplatesRequest, + | protos.google.privacy.dlp.v2.IListInspectTemplatesResponse + | null + | undefined, + protos.google.privacy.dlp.v2.IInspectTemplate + >, + ): Promise< + [ + protos.google.privacy.dlp.v2.IInspectTemplate[], + protos.google.privacy.dlp.v2.IListInspectTemplatesRequest | null, + protos.google.privacy.dlp.v2.IListInspectTemplatesResponse, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - 'location_id': request.locationId?.toString() ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + location_id: request.locationId?.toString() ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.privacy.dlp.v2.IListInspectTemplatesRequest, - protos.google.privacy.dlp.v2.IListInspectTemplatesResponse|null|undefined, - protos.google.privacy.dlp.v2.IInspectTemplate>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.privacy.dlp.v2.IListInspectTemplatesRequest, + | protos.google.privacy.dlp.v2.IListInspectTemplatesResponse + | null + | undefined, + protos.google.privacy.dlp.v2.IInspectTemplate + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listInspectTemplates values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -3198,254 +4262,283 @@ export class DlpServiceClient { this._log.info('listInspectTemplates request %j', request); return this.innerApiCalls .listInspectTemplates(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.privacy.dlp.v2.IInspectTemplate[], - protos.google.privacy.dlp.v2.IListInspectTemplatesRequest|null, - protos.google.privacy.dlp.v2.IListInspectTemplatesResponse - ]) => { - this._log.info('listInspectTemplates values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.privacy.dlp.v2.IInspectTemplate[], + protos.google.privacy.dlp.v2.IListInspectTemplatesRequest | null, + protos.google.privacy.dlp.v2.IListInspectTemplatesResponse, + ]) => { + this._log.info('listInspectTemplates values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listInspectTemplates`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent resource name, for example projects/my-project-id or - * organizations/my-org-id. - * @param {string} request.pageToken - * Page token to continue retrieval. Comes from previous call - * to `ListInspectTemplates`. - * @param {number} request.pageSize - * Size of the page, can be limited by server. If zero server returns - * a page of max size 100. - * @param {string} request.orderBy - * Comma separated list of fields to order by, - * followed by `asc` or `desc` postfix. This list is case-insensitive, - * default sorting order is ascending, redundant space characters are - * insignificant. - * - * Example: `name asc,update_time, create_time desc` - * - * Supported fields are: - * - * - `create_time`: corresponds to time the template was created. - * - `update_time`: corresponds to time the template was last updated. - * - `name`: corresponds to template's name. - * - `display_name`: corresponds to template's display name. - * @param {string} request.locationId - * The geographic location where inspection templates will be retrieved from. - * Use `-` for all locations. Reserved for future extensions. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.privacy.dlp.v2.InspectTemplate|InspectTemplate} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `listInspectTemplatesAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `listInspectTemplates`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource name, for example projects/my-project-id or + * organizations/my-org-id. + * @param {string} request.pageToken + * Page token to continue retrieval. Comes from previous call + * to `ListInspectTemplates`. + * @param {number} request.pageSize + * Size of the page, can be limited by server. If zero server returns + * a page of max size 100. + * @param {string} request.orderBy + * Comma separated list of fields to order by, + * followed by `asc` or `desc` postfix. This list is case-insensitive, + * default sorting order is ascending, redundant space characters are + * insignificant. + * + * Example: `name asc,update_time, create_time desc` + * + * Supported fields are: + * + * - `create_time`: corresponds to time the template was created. + * - `update_time`: corresponds to time the template was last updated. + * - `name`: corresponds to template's name. + * - `display_name`: corresponds to template's display name. + * @param {string} request.locationId + * The geographic location where inspection templates will be retrieved from. + * Use `-` for all locations. Reserved for future extensions. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.privacy.dlp.v2.InspectTemplate|InspectTemplate} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listInspectTemplatesAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listInspectTemplatesStream( - request?: protos.google.privacy.dlp.v2.IListInspectTemplatesRequest, - options?: CallOptions): - Transform{ + request?: protos.google.privacy.dlp.v2.IListInspectTemplatesRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - 'location_id': request.locationId?.toString() ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + location_id: request.locationId?.toString() ?? '', + }); const defaultCallSettings = this._defaults['listInspectTemplates']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listInspectTemplates stream %j', request); return this.descriptors.page.listInspectTemplates.createStream( this.innerApiCalls.listInspectTemplates as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listInspectTemplates`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent resource name, for example projects/my-project-id or - * organizations/my-org-id. - * @param {string} request.pageToken - * Page token to continue retrieval. Comes from previous call - * to `ListInspectTemplates`. - * @param {number} request.pageSize - * Size of the page, can be limited by server. If zero server returns - * a page of max size 100. - * @param {string} request.orderBy - * Comma separated list of fields to order by, - * followed by `asc` or `desc` postfix. This list is case-insensitive, - * default sorting order is ascending, redundant space characters are - * insignificant. - * - * Example: `name asc,update_time, create_time desc` - * - * Supported fields are: - * - * - `create_time`: corresponds to time the template was created. - * - `update_time`: corresponds to time the template was last updated. - * - `name`: corresponds to template's name. - * - `display_name`: corresponds to template's display name. - * @param {string} request.locationId - * The geographic location where inspection templates will be retrieved from. - * Use `-` for all locations. Reserved for future extensions. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.privacy.dlp.v2.InspectTemplate|InspectTemplate}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v2/dlp_service.list_inspect_templates.js - * region_tag:dlp_v2_generated_DlpService_ListInspectTemplates_async - */ + /** + * Equivalent to `listInspectTemplates`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource name, for example projects/my-project-id or + * organizations/my-org-id. + * @param {string} request.pageToken + * Page token to continue retrieval. Comes from previous call + * to `ListInspectTemplates`. + * @param {number} request.pageSize + * Size of the page, can be limited by server. If zero server returns + * a page of max size 100. + * @param {string} request.orderBy + * Comma separated list of fields to order by, + * followed by `asc` or `desc` postfix. This list is case-insensitive, + * default sorting order is ascending, redundant space characters are + * insignificant. + * + * Example: `name asc,update_time, create_time desc` + * + * Supported fields are: + * + * - `create_time`: corresponds to time the template was created. + * - `update_time`: corresponds to time the template was last updated. + * - `name`: corresponds to template's name. + * - `display_name`: corresponds to template's display name. + * @param {string} request.locationId + * The geographic location where inspection templates will be retrieved from. + * Use `-` for all locations. Reserved for future extensions. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.privacy.dlp.v2.InspectTemplate|InspectTemplate}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v2/dlp_service.list_inspect_templates.js + * region_tag:dlp_v2_generated_DlpService_ListInspectTemplates_async + */ listInspectTemplatesAsync( - request?: protos.google.privacy.dlp.v2.IListInspectTemplatesRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.privacy.dlp.v2.IListInspectTemplatesRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - 'location_id': request.locationId?.toString() ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + location_id: request.locationId?.toString() ?? '', + }); const defaultCallSettings = this._defaults['listInspectTemplates']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listInspectTemplates iterate %j', request); return this.descriptors.page.listInspectTemplates.asyncIterate( this.innerApiCalls['listInspectTemplates'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } - /** - * Lists DeidentifyTemplates. - * See https://cloud.google.com/dlp/docs/creating-templates-deid to learn - * more. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent resource name, for example projects/my-project-id or - * organizations/my-org-id. - * @param {string} request.pageToken - * Page token to continue retrieval. Comes from previous call - * to `ListDeidentifyTemplates`. - * @param {number} request.pageSize - * Size of the page, can be limited by server. If zero server returns - * a page of max size 100. - * @param {string} request.orderBy - * Comma separated list of fields to order by, - * followed by `asc` or `desc` postfix. This list is case-insensitive, - * default sorting order is ascending, redundant space characters are - * insignificant. - * - * Example: `name asc,update_time, create_time desc` - * - * Supported fields are: - * - * - `create_time`: corresponds to time the template was created. - * - `update_time`: corresponds to time the template was last updated. - * - `name`: corresponds to template's name. - * - `display_name`: corresponds to template's display name. - * @param {string} request.locationId - * The geographic location where deidentifications templates will be retrieved - * from. Use `-` for all locations. Reserved for future extensions. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.privacy.dlp.v2.DeidentifyTemplate|DeidentifyTemplate}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `listDeidentifyTemplatesAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Lists DeidentifyTemplates. + * See https://cloud.google.com/dlp/docs/creating-templates-deid to learn + * more. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource name, for example projects/my-project-id or + * organizations/my-org-id. + * @param {string} request.pageToken + * Page token to continue retrieval. Comes from previous call + * to `ListDeidentifyTemplates`. + * @param {number} request.pageSize + * Size of the page, can be limited by server. If zero server returns + * a page of max size 100. + * @param {string} request.orderBy + * Comma separated list of fields to order by, + * followed by `asc` or `desc` postfix. This list is case-insensitive, + * default sorting order is ascending, redundant space characters are + * insignificant. + * + * Example: `name asc,update_time, create_time desc` + * + * Supported fields are: + * + * - `create_time`: corresponds to time the template was created. + * - `update_time`: corresponds to time the template was last updated. + * - `name`: corresponds to template's name. + * - `display_name`: corresponds to template's display name. + * @param {string} request.locationId + * The geographic location where deidentifications templates will be retrieved + * from. Use `-` for all locations. Reserved for future extensions. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.privacy.dlp.v2.DeidentifyTemplate|DeidentifyTemplate}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listDeidentifyTemplatesAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listDeidentifyTemplates( - request?: protos.google.privacy.dlp.v2.IListDeidentifyTemplatesRequest, - options?: CallOptions): - Promise<[ - protos.google.privacy.dlp.v2.IDeidentifyTemplate[], - protos.google.privacy.dlp.v2.IListDeidentifyTemplatesRequest|null, - protos.google.privacy.dlp.v2.IListDeidentifyTemplatesResponse - ]>; + request?: protos.google.privacy.dlp.v2.IListDeidentifyTemplatesRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.privacy.dlp.v2.IDeidentifyTemplate[], + protos.google.privacy.dlp.v2.IListDeidentifyTemplatesRequest | null, + protos.google.privacy.dlp.v2.IListDeidentifyTemplatesResponse, + ] + >; listDeidentifyTemplates( - request: protos.google.privacy.dlp.v2.IListDeidentifyTemplatesRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.privacy.dlp.v2.IListDeidentifyTemplatesRequest, - protos.google.privacy.dlp.v2.IListDeidentifyTemplatesResponse|null|undefined, - protos.google.privacy.dlp.v2.IDeidentifyTemplate>): void; + request: protos.google.privacy.dlp.v2.IListDeidentifyTemplatesRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.privacy.dlp.v2.IListDeidentifyTemplatesRequest, + | protos.google.privacy.dlp.v2.IListDeidentifyTemplatesResponse + | null + | undefined, + protos.google.privacy.dlp.v2.IDeidentifyTemplate + >, + ): void; listDeidentifyTemplates( - request: protos.google.privacy.dlp.v2.IListDeidentifyTemplatesRequest, - callback: PaginationCallback< - protos.google.privacy.dlp.v2.IListDeidentifyTemplatesRequest, - protos.google.privacy.dlp.v2.IListDeidentifyTemplatesResponse|null|undefined, - protos.google.privacy.dlp.v2.IDeidentifyTemplate>): void; + request: protos.google.privacy.dlp.v2.IListDeidentifyTemplatesRequest, + callback: PaginationCallback< + protos.google.privacy.dlp.v2.IListDeidentifyTemplatesRequest, + | protos.google.privacy.dlp.v2.IListDeidentifyTemplatesResponse + | null + | undefined, + protos.google.privacy.dlp.v2.IDeidentifyTemplate + >, + ): void; listDeidentifyTemplates( - request?: protos.google.privacy.dlp.v2.IListDeidentifyTemplatesRequest, - optionsOrCallback?: CallOptions|PaginationCallback< + request?: protos.google.privacy.dlp.v2.IListDeidentifyTemplatesRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.privacy.dlp.v2.IListDeidentifyTemplatesRequest, - protos.google.privacy.dlp.v2.IListDeidentifyTemplatesResponse|null|undefined, - protos.google.privacy.dlp.v2.IDeidentifyTemplate>, - callback?: PaginationCallback< - protos.google.privacy.dlp.v2.IListDeidentifyTemplatesRequest, - protos.google.privacy.dlp.v2.IListDeidentifyTemplatesResponse|null|undefined, - protos.google.privacy.dlp.v2.IDeidentifyTemplate>): - Promise<[ - protos.google.privacy.dlp.v2.IDeidentifyTemplate[], - protos.google.privacy.dlp.v2.IListDeidentifyTemplatesRequest|null, - protos.google.privacy.dlp.v2.IListDeidentifyTemplatesResponse - ]>|void { + | protos.google.privacy.dlp.v2.IListDeidentifyTemplatesResponse + | null + | undefined, + protos.google.privacy.dlp.v2.IDeidentifyTemplate + >, + callback?: PaginationCallback< + protos.google.privacy.dlp.v2.IListDeidentifyTemplatesRequest, + | protos.google.privacy.dlp.v2.IListDeidentifyTemplatesResponse + | null + | undefined, + protos.google.privacy.dlp.v2.IDeidentifyTemplate + >, + ): Promise< + [ + protos.google.privacy.dlp.v2.IDeidentifyTemplate[], + protos.google.privacy.dlp.v2.IListDeidentifyTemplatesRequest | null, + protos.google.privacy.dlp.v2.IListDeidentifyTemplatesResponse, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - 'location_id': request.locationId?.toString() ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + location_id: request.locationId?.toString() ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.privacy.dlp.v2.IListDeidentifyTemplatesRequest, - protos.google.privacy.dlp.v2.IListDeidentifyTemplatesResponse|null|undefined, - protos.google.privacy.dlp.v2.IDeidentifyTemplate>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.privacy.dlp.v2.IListDeidentifyTemplatesRequest, + | protos.google.privacy.dlp.v2.IListDeidentifyTemplatesResponse + | null + | undefined, + protos.google.privacy.dlp.v2.IDeidentifyTemplate + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listDeidentifyTemplates values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -3454,279 +4547,302 @@ export class DlpServiceClient { this._log.info('listDeidentifyTemplates request %j', request); return this.innerApiCalls .listDeidentifyTemplates(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.privacy.dlp.v2.IDeidentifyTemplate[], - protos.google.privacy.dlp.v2.IListDeidentifyTemplatesRequest|null, - protos.google.privacy.dlp.v2.IListDeidentifyTemplatesResponse - ]) => { - this._log.info('listDeidentifyTemplates values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.privacy.dlp.v2.IDeidentifyTemplate[], + protos.google.privacy.dlp.v2.IListDeidentifyTemplatesRequest | null, + protos.google.privacy.dlp.v2.IListDeidentifyTemplatesResponse, + ]) => { + this._log.info('listDeidentifyTemplates values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listDeidentifyTemplates`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent resource name, for example projects/my-project-id or - * organizations/my-org-id. - * @param {string} request.pageToken - * Page token to continue retrieval. Comes from previous call - * to `ListDeidentifyTemplates`. - * @param {number} request.pageSize - * Size of the page, can be limited by server. If zero server returns - * a page of max size 100. - * @param {string} request.orderBy - * Comma separated list of fields to order by, - * followed by `asc` or `desc` postfix. This list is case-insensitive, - * default sorting order is ascending, redundant space characters are - * insignificant. - * - * Example: `name asc,update_time, create_time desc` - * - * Supported fields are: - * - * - `create_time`: corresponds to time the template was created. - * - `update_time`: corresponds to time the template was last updated. - * - `name`: corresponds to template's name. - * - `display_name`: corresponds to template's display name. - * @param {string} request.locationId - * The geographic location where deidentifications templates will be retrieved - * from. Use `-` for all locations. Reserved for future extensions. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.privacy.dlp.v2.DeidentifyTemplate|DeidentifyTemplate} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `listDeidentifyTemplatesAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `listDeidentifyTemplates`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource name, for example projects/my-project-id or + * organizations/my-org-id. + * @param {string} request.pageToken + * Page token to continue retrieval. Comes from previous call + * to `ListDeidentifyTemplates`. + * @param {number} request.pageSize + * Size of the page, can be limited by server. If zero server returns + * a page of max size 100. + * @param {string} request.orderBy + * Comma separated list of fields to order by, + * followed by `asc` or `desc` postfix. This list is case-insensitive, + * default sorting order is ascending, redundant space characters are + * insignificant. + * + * Example: `name asc,update_time, create_time desc` + * + * Supported fields are: + * + * - `create_time`: corresponds to time the template was created. + * - `update_time`: corresponds to time the template was last updated. + * - `name`: corresponds to template's name. + * - `display_name`: corresponds to template's display name. + * @param {string} request.locationId + * The geographic location where deidentifications templates will be retrieved + * from. Use `-` for all locations. Reserved for future extensions. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.privacy.dlp.v2.DeidentifyTemplate|DeidentifyTemplate} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listDeidentifyTemplatesAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listDeidentifyTemplatesStream( - request?: protos.google.privacy.dlp.v2.IListDeidentifyTemplatesRequest, - options?: CallOptions): - Transform{ + request?: protos.google.privacy.dlp.v2.IListDeidentifyTemplatesRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - 'location_id': request.locationId?.toString() ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + location_id: request.locationId?.toString() ?? '', + }); const defaultCallSettings = this._defaults['listDeidentifyTemplates']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listDeidentifyTemplates stream %j', request); return this.descriptors.page.listDeidentifyTemplates.createStream( this.innerApiCalls.listDeidentifyTemplates as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listDeidentifyTemplates`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent resource name, for example projects/my-project-id or - * organizations/my-org-id. - * @param {string} request.pageToken - * Page token to continue retrieval. Comes from previous call - * to `ListDeidentifyTemplates`. - * @param {number} request.pageSize - * Size of the page, can be limited by server. If zero server returns - * a page of max size 100. - * @param {string} request.orderBy - * Comma separated list of fields to order by, - * followed by `asc` or `desc` postfix. This list is case-insensitive, - * default sorting order is ascending, redundant space characters are - * insignificant. - * - * Example: `name asc,update_time, create_time desc` - * - * Supported fields are: - * - * - `create_time`: corresponds to time the template was created. - * - `update_time`: corresponds to time the template was last updated. - * - `name`: corresponds to template's name. - * - `display_name`: corresponds to template's display name. - * @param {string} request.locationId - * The geographic location where deidentifications templates will be retrieved - * from. Use `-` for all locations. Reserved for future extensions. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.privacy.dlp.v2.DeidentifyTemplate|DeidentifyTemplate}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v2/dlp_service.list_deidentify_templates.js - * region_tag:dlp_v2_generated_DlpService_ListDeidentifyTemplates_async - */ + /** + * Equivalent to `listDeidentifyTemplates`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource name, for example projects/my-project-id or + * organizations/my-org-id. + * @param {string} request.pageToken + * Page token to continue retrieval. Comes from previous call + * to `ListDeidentifyTemplates`. + * @param {number} request.pageSize + * Size of the page, can be limited by server. If zero server returns + * a page of max size 100. + * @param {string} request.orderBy + * Comma separated list of fields to order by, + * followed by `asc` or `desc` postfix. This list is case-insensitive, + * default sorting order is ascending, redundant space characters are + * insignificant. + * + * Example: `name asc,update_time, create_time desc` + * + * Supported fields are: + * + * - `create_time`: corresponds to time the template was created. + * - `update_time`: corresponds to time the template was last updated. + * - `name`: corresponds to template's name. + * - `display_name`: corresponds to template's display name. + * @param {string} request.locationId + * The geographic location where deidentifications templates will be retrieved + * from. Use `-` for all locations. Reserved for future extensions. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.privacy.dlp.v2.DeidentifyTemplate|DeidentifyTemplate}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v2/dlp_service.list_deidentify_templates.js + * region_tag:dlp_v2_generated_DlpService_ListDeidentifyTemplates_async + */ listDeidentifyTemplatesAsync( - request?: protos.google.privacy.dlp.v2.IListDeidentifyTemplatesRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.privacy.dlp.v2.IListDeidentifyTemplatesRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - 'location_id': request.locationId?.toString() ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + location_id: request.locationId?.toString() ?? '', + }); const defaultCallSettings = this._defaults['listDeidentifyTemplates']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listDeidentifyTemplates iterate %j', request); return this.descriptors.page.listDeidentifyTemplates.asyncIterate( this.innerApiCalls['listDeidentifyTemplates'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } - /** - * Lists job triggers. - * See https://cloud.google.com/dlp/docs/creating-job-triggers to learn more. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent resource name, for example `projects/my-project-id`. - * @param {string} request.pageToken - * Page token to continue retrieval. Comes from previous call - * to ListJobTriggers. `order_by` field must not - * change for subsequent calls. - * @param {number} request.pageSize - * Size of the page, can be limited by a server. - * @param {string} request.orderBy - * Comma separated list of triggeredJob fields to order by, - * followed by `asc` or `desc` postfix. This list is case-insensitive, - * default sorting order is ascending, redundant space characters are - * insignificant. - * - * Example: `name asc,update_time, create_time desc` - * - * Supported fields are: - * - * - `create_time`: corresponds to time the JobTrigger was created. - * - `update_time`: corresponds to time the JobTrigger was last updated. - * - `last_run_time`: corresponds to the last time the JobTrigger ran. - * - `name`: corresponds to JobTrigger's name. - * - `display_name`: corresponds to JobTrigger's display name. - * - `status`: corresponds to JobTrigger's status. - * @param {string} request.filter - * Allows filtering. - * - * Supported syntax: - * - * * Filter expressions are made up of one or more restrictions. - * * Restrictions can be combined by `AND` or `OR` logical operators. A - * sequence of restrictions implicitly uses `AND`. - * * A restriction has the form of `{field} {operator} {value}`. - * * Supported fields/values for inspect jobs: - * - `status` - HEALTHY|PAUSED|CANCELLED - * - `inspected_storage` - DATASTORE|CLOUD_STORAGE|BIGQUERY - * - 'last_run_time` - RFC 3339 formatted timestamp, surrounded by - * quotation marks. Nanoseconds are ignored. - * - 'error_count' - Number of errors that have occurred while running. - * * The operator must be `=` or `!=` for status and inspected_storage. - * - * Examples: - * - * * inspected_storage = cloud_storage AND status = HEALTHY - * * inspected_storage = cloud_storage OR inspected_storage = bigquery - * * inspected_storage = cloud_storage AND (state = PAUSED OR state = HEALTHY) - * * last_run_time > \"2017-12-12T00:00:00+00:00\" - * - * The length of this field should be no more than 500 characters. - * @param {string} request.locationId - * The geographic location where job triggers will be retrieved from. - * Use `-` for all locations. Reserved for future extensions. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.privacy.dlp.v2.JobTrigger|JobTrigger}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `listJobTriggersAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Lists job triggers. + * See https://cloud.google.com/dlp/docs/creating-job-triggers to learn more. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource name, for example `projects/my-project-id`. + * @param {string} request.pageToken + * Page token to continue retrieval. Comes from previous call + * to ListJobTriggers. `order_by` field must not + * change for subsequent calls. + * @param {number} request.pageSize + * Size of the page, can be limited by a server. + * @param {string} request.orderBy + * Comma separated list of triggeredJob fields to order by, + * followed by `asc` or `desc` postfix. This list is case-insensitive, + * default sorting order is ascending, redundant space characters are + * insignificant. + * + * Example: `name asc,update_time, create_time desc` + * + * Supported fields are: + * + * - `create_time`: corresponds to time the JobTrigger was created. + * - `update_time`: corresponds to time the JobTrigger was last updated. + * - `last_run_time`: corresponds to the last time the JobTrigger ran. + * - `name`: corresponds to JobTrigger's name. + * - `display_name`: corresponds to JobTrigger's display name. + * - `status`: corresponds to JobTrigger's status. + * @param {string} request.filter + * Allows filtering. + * + * Supported syntax: + * + * * Filter expressions are made up of one or more restrictions. + * * Restrictions can be combined by `AND` or `OR` logical operators. A + * sequence of restrictions implicitly uses `AND`. + * * A restriction has the form of `{field} {operator} {value}`. + * * Supported fields/values for inspect jobs: + * - `status` - HEALTHY|PAUSED|CANCELLED + * - `inspected_storage` - DATASTORE|CLOUD_STORAGE|BIGQUERY + * - 'last_run_time` - RFC 3339 formatted timestamp, surrounded by + * quotation marks. Nanoseconds are ignored. + * - 'error_count' - Number of errors that have occurred while running. + * * The operator must be `=` or `!=` for status and inspected_storage. + * + * Examples: + * + * * inspected_storage = cloud_storage AND status = HEALTHY + * * inspected_storage = cloud_storage OR inspected_storage = bigquery + * * inspected_storage = cloud_storage AND (state = PAUSED OR state = HEALTHY) + * * last_run_time > \"2017-12-12T00:00:00+00:00\" + * + * The length of this field should be no more than 500 characters. + * @param {string} request.locationId + * The geographic location where job triggers will be retrieved from. + * Use `-` for all locations. Reserved for future extensions. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.privacy.dlp.v2.JobTrigger|JobTrigger}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listJobTriggersAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listJobTriggers( - request?: protos.google.privacy.dlp.v2.IListJobTriggersRequest, - options?: CallOptions): - Promise<[ - protos.google.privacy.dlp.v2.IJobTrigger[], - protos.google.privacy.dlp.v2.IListJobTriggersRequest|null, - protos.google.privacy.dlp.v2.IListJobTriggersResponse - ]>; + request?: protos.google.privacy.dlp.v2.IListJobTriggersRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.privacy.dlp.v2.IJobTrigger[], + protos.google.privacy.dlp.v2.IListJobTriggersRequest | null, + protos.google.privacy.dlp.v2.IListJobTriggersResponse, + ] + >; listJobTriggers( - request: protos.google.privacy.dlp.v2.IListJobTriggersRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.privacy.dlp.v2.IListJobTriggersRequest, - protos.google.privacy.dlp.v2.IListJobTriggersResponse|null|undefined, - protos.google.privacy.dlp.v2.IJobTrigger>): void; + request: protos.google.privacy.dlp.v2.IListJobTriggersRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.privacy.dlp.v2.IListJobTriggersRequest, + protos.google.privacy.dlp.v2.IListJobTriggersResponse | null | undefined, + protos.google.privacy.dlp.v2.IJobTrigger + >, + ): void; listJobTriggers( - request: protos.google.privacy.dlp.v2.IListJobTriggersRequest, - callback: PaginationCallback< - protos.google.privacy.dlp.v2.IListJobTriggersRequest, - protos.google.privacy.dlp.v2.IListJobTriggersResponse|null|undefined, - protos.google.privacy.dlp.v2.IJobTrigger>): void; + request: protos.google.privacy.dlp.v2.IListJobTriggersRequest, + callback: PaginationCallback< + protos.google.privacy.dlp.v2.IListJobTriggersRequest, + protos.google.privacy.dlp.v2.IListJobTriggersResponse | null | undefined, + protos.google.privacy.dlp.v2.IJobTrigger + >, + ): void; listJobTriggers( - request?: protos.google.privacy.dlp.v2.IListJobTriggersRequest, - optionsOrCallback?: CallOptions|PaginationCallback< + request?: protos.google.privacy.dlp.v2.IListJobTriggersRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.privacy.dlp.v2.IListJobTriggersRequest, - protos.google.privacy.dlp.v2.IListJobTriggersResponse|null|undefined, - protos.google.privacy.dlp.v2.IJobTrigger>, - callback?: PaginationCallback< - protos.google.privacy.dlp.v2.IListJobTriggersRequest, - protos.google.privacy.dlp.v2.IListJobTriggersResponse|null|undefined, - protos.google.privacy.dlp.v2.IJobTrigger>): - Promise<[ - protos.google.privacy.dlp.v2.IJobTrigger[], - protos.google.privacy.dlp.v2.IListJobTriggersRequest|null, - protos.google.privacy.dlp.v2.IListJobTriggersResponse - ]>|void { + | protos.google.privacy.dlp.v2.IListJobTriggersResponse + | null + | undefined, + protos.google.privacy.dlp.v2.IJobTrigger + >, + callback?: PaginationCallback< + protos.google.privacy.dlp.v2.IListJobTriggersRequest, + protos.google.privacy.dlp.v2.IListJobTriggersResponse | null | undefined, + protos.google.privacy.dlp.v2.IJobTrigger + >, + ): Promise< + [ + protos.google.privacy.dlp.v2.IJobTrigger[], + protos.google.privacy.dlp.v2.IListJobTriggersRequest | null, + protos.google.privacy.dlp.v2.IListJobTriggersResponse, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - 'location_id': request.locationId?.toString() ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + location_id: request.locationId?.toString() ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.privacy.dlp.v2.IListJobTriggersRequest, - protos.google.privacy.dlp.v2.IListJobTriggersResponse|null|undefined, - protos.google.privacy.dlp.v2.IJobTrigger>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.privacy.dlp.v2.IListJobTriggersRequest, + | protos.google.privacy.dlp.v2.IListJobTriggersResponse + | null + | undefined, + protos.google.privacy.dlp.v2.IJobTrigger + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listJobTriggers values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -3735,334 +4851,353 @@ export class DlpServiceClient { this._log.info('listJobTriggers request %j', request); return this.innerApiCalls .listJobTriggers(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.privacy.dlp.v2.IJobTrigger[], - protos.google.privacy.dlp.v2.IListJobTriggersRequest|null, - protos.google.privacy.dlp.v2.IListJobTriggersResponse - ]) => { - this._log.info('listJobTriggers values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.privacy.dlp.v2.IJobTrigger[], + protos.google.privacy.dlp.v2.IListJobTriggersRequest | null, + protos.google.privacy.dlp.v2.IListJobTriggersResponse, + ]) => { + this._log.info('listJobTriggers values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listJobTriggers`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent resource name, for example `projects/my-project-id`. - * @param {string} request.pageToken - * Page token to continue retrieval. Comes from previous call - * to ListJobTriggers. `order_by` field must not - * change for subsequent calls. - * @param {number} request.pageSize - * Size of the page, can be limited by a server. - * @param {string} request.orderBy - * Comma separated list of triggeredJob fields to order by, - * followed by `asc` or `desc` postfix. This list is case-insensitive, - * default sorting order is ascending, redundant space characters are - * insignificant. - * - * Example: `name asc,update_time, create_time desc` - * - * Supported fields are: - * - * - `create_time`: corresponds to time the JobTrigger was created. - * - `update_time`: corresponds to time the JobTrigger was last updated. - * - `last_run_time`: corresponds to the last time the JobTrigger ran. - * - `name`: corresponds to JobTrigger's name. - * - `display_name`: corresponds to JobTrigger's display name. - * - `status`: corresponds to JobTrigger's status. - * @param {string} request.filter - * Allows filtering. - * - * Supported syntax: - * - * * Filter expressions are made up of one or more restrictions. - * * Restrictions can be combined by `AND` or `OR` logical operators. A - * sequence of restrictions implicitly uses `AND`. - * * A restriction has the form of `{field} {operator} {value}`. - * * Supported fields/values for inspect jobs: - * - `status` - HEALTHY|PAUSED|CANCELLED - * - `inspected_storage` - DATASTORE|CLOUD_STORAGE|BIGQUERY - * - 'last_run_time` - RFC 3339 formatted timestamp, surrounded by - * quotation marks. Nanoseconds are ignored. - * - 'error_count' - Number of errors that have occurred while running. - * * The operator must be `=` or `!=` for status and inspected_storage. - * - * Examples: - * - * * inspected_storage = cloud_storage AND status = HEALTHY - * * inspected_storage = cloud_storage OR inspected_storage = bigquery - * * inspected_storage = cloud_storage AND (state = PAUSED OR state = HEALTHY) - * * last_run_time > \"2017-12-12T00:00:00+00:00\" - * - * The length of this field should be no more than 500 characters. - * @param {string} request.locationId - * The geographic location where job triggers will be retrieved from. - * Use `-` for all locations. Reserved for future extensions. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.privacy.dlp.v2.JobTrigger|JobTrigger} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `listJobTriggersAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `listJobTriggers`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource name, for example `projects/my-project-id`. + * @param {string} request.pageToken + * Page token to continue retrieval. Comes from previous call + * to ListJobTriggers. `order_by` field must not + * change for subsequent calls. + * @param {number} request.pageSize + * Size of the page, can be limited by a server. + * @param {string} request.orderBy + * Comma separated list of triggeredJob fields to order by, + * followed by `asc` or `desc` postfix. This list is case-insensitive, + * default sorting order is ascending, redundant space characters are + * insignificant. + * + * Example: `name asc,update_time, create_time desc` + * + * Supported fields are: + * + * - `create_time`: corresponds to time the JobTrigger was created. + * - `update_time`: corresponds to time the JobTrigger was last updated. + * - `last_run_time`: corresponds to the last time the JobTrigger ran. + * - `name`: corresponds to JobTrigger's name. + * - `display_name`: corresponds to JobTrigger's display name. + * - `status`: corresponds to JobTrigger's status. + * @param {string} request.filter + * Allows filtering. + * + * Supported syntax: + * + * * Filter expressions are made up of one or more restrictions. + * * Restrictions can be combined by `AND` or `OR` logical operators. A + * sequence of restrictions implicitly uses `AND`. + * * A restriction has the form of `{field} {operator} {value}`. + * * Supported fields/values for inspect jobs: + * - `status` - HEALTHY|PAUSED|CANCELLED + * - `inspected_storage` - DATASTORE|CLOUD_STORAGE|BIGQUERY + * - 'last_run_time` - RFC 3339 formatted timestamp, surrounded by + * quotation marks. Nanoseconds are ignored. + * - 'error_count' - Number of errors that have occurred while running. + * * The operator must be `=` or `!=` for status and inspected_storage. + * + * Examples: + * + * * inspected_storage = cloud_storage AND status = HEALTHY + * * inspected_storage = cloud_storage OR inspected_storage = bigquery + * * inspected_storage = cloud_storage AND (state = PAUSED OR state = HEALTHY) + * * last_run_time > \"2017-12-12T00:00:00+00:00\" + * + * The length of this field should be no more than 500 characters. + * @param {string} request.locationId + * The geographic location where job triggers will be retrieved from. + * Use `-` for all locations. Reserved for future extensions. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.privacy.dlp.v2.JobTrigger|JobTrigger} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listJobTriggersAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listJobTriggersStream( - request?: protos.google.privacy.dlp.v2.IListJobTriggersRequest, - options?: CallOptions): - Transform{ + request?: protos.google.privacy.dlp.v2.IListJobTriggersRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - 'location_id': request.locationId?.toString() ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + location_id: request.locationId?.toString() ?? '', + }); const defaultCallSettings = this._defaults['listJobTriggers']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listJobTriggers stream %j', request); return this.descriptors.page.listJobTriggers.createStream( this.innerApiCalls.listJobTriggers as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listJobTriggers`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent resource name, for example `projects/my-project-id`. - * @param {string} request.pageToken - * Page token to continue retrieval. Comes from previous call - * to ListJobTriggers. `order_by` field must not - * change for subsequent calls. - * @param {number} request.pageSize - * Size of the page, can be limited by a server. - * @param {string} request.orderBy - * Comma separated list of triggeredJob fields to order by, - * followed by `asc` or `desc` postfix. This list is case-insensitive, - * default sorting order is ascending, redundant space characters are - * insignificant. - * - * Example: `name asc,update_time, create_time desc` - * - * Supported fields are: - * - * - `create_time`: corresponds to time the JobTrigger was created. - * - `update_time`: corresponds to time the JobTrigger was last updated. - * - `last_run_time`: corresponds to the last time the JobTrigger ran. - * - `name`: corresponds to JobTrigger's name. - * - `display_name`: corresponds to JobTrigger's display name. - * - `status`: corresponds to JobTrigger's status. - * @param {string} request.filter - * Allows filtering. - * - * Supported syntax: - * - * * Filter expressions are made up of one or more restrictions. - * * Restrictions can be combined by `AND` or `OR` logical operators. A - * sequence of restrictions implicitly uses `AND`. - * * A restriction has the form of `{field} {operator} {value}`. - * * Supported fields/values for inspect jobs: - * - `status` - HEALTHY|PAUSED|CANCELLED - * - `inspected_storage` - DATASTORE|CLOUD_STORAGE|BIGQUERY - * - 'last_run_time` - RFC 3339 formatted timestamp, surrounded by - * quotation marks. Nanoseconds are ignored. - * - 'error_count' - Number of errors that have occurred while running. - * * The operator must be `=` or `!=` for status and inspected_storage. - * - * Examples: - * - * * inspected_storage = cloud_storage AND status = HEALTHY - * * inspected_storage = cloud_storage OR inspected_storage = bigquery - * * inspected_storage = cloud_storage AND (state = PAUSED OR state = HEALTHY) - * * last_run_time > \"2017-12-12T00:00:00+00:00\" - * - * The length of this field should be no more than 500 characters. - * @param {string} request.locationId - * The geographic location where job triggers will be retrieved from. - * Use `-` for all locations. Reserved for future extensions. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.privacy.dlp.v2.JobTrigger|JobTrigger}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v2/dlp_service.list_job_triggers.js - * region_tag:dlp_v2_generated_DlpService_ListJobTriggers_async - */ + /** + * Equivalent to `listJobTriggers`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource name, for example `projects/my-project-id`. + * @param {string} request.pageToken + * Page token to continue retrieval. Comes from previous call + * to ListJobTriggers. `order_by` field must not + * change for subsequent calls. + * @param {number} request.pageSize + * Size of the page, can be limited by a server. + * @param {string} request.orderBy + * Comma separated list of triggeredJob fields to order by, + * followed by `asc` or `desc` postfix. This list is case-insensitive, + * default sorting order is ascending, redundant space characters are + * insignificant. + * + * Example: `name asc,update_time, create_time desc` + * + * Supported fields are: + * + * - `create_time`: corresponds to time the JobTrigger was created. + * - `update_time`: corresponds to time the JobTrigger was last updated. + * - `last_run_time`: corresponds to the last time the JobTrigger ran. + * - `name`: corresponds to JobTrigger's name. + * - `display_name`: corresponds to JobTrigger's display name. + * - `status`: corresponds to JobTrigger's status. + * @param {string} request.filter + * Allows filtering. + * + * Supported syntax: + * + * * Filter expressions are made up of one or more restrictions. + * * Restrictions can be combined by `AND` or `OR` logical operators. A + * sequence of restrictions implicitly uses `AND`. + * * A restriction has the form of `{field} {operator} {value}`. + * * Supported fields/values for inspect jobs: + * - `status` - HEALTHY|PAUSED|CANCELLED + * - `inspected_storage` - DATASTORE|CLOUD_STORAGE|BIGQUERY + * - 'last_run_time` - RFC 3339 formatted timestamp, surrounded by + * quotation marks. Nanoseconds are ignored. + * - 'error_count' - Number of errors that have occurred while running. + * * The operator must be `=` or `!=` for status and inspected_storage. + * + * Examples: + * + * * inspected_storage = cloud_storage AND status = HEALTHY + * * inspected_storage = cloud_storage OR inspected_storage = bigquery + * * inspected_storage = cloud_storage AND (state = PAUSED OR state = HEALTHY) + * * last_run_time > \"2017-12-12T00:00:00+00:00\" + * + * The length of this field should be no more than 500 characters. + * @param {string} request.locationId + * The geographic location where job triggers will be retrieved from. + * Use `-` for all locations. Reserved for future extensions. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.privacy.dlp.v2.JobTrigger|JobTrigger}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v2/dlp_service.list_job_triggers.js + * region_tag:dlp_v2_generated_DlpService_ListJobTriggers_async + */ listJobTriggersAsync( - request?: protos.google.privacy.dlp.v2.IListJobTriggersRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.privacy.dlp.v2.IListJobTriggersRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - 'location_id': request.locationId?.toString() ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + location_id: request.locationId?.toString() ?? '', + }); const defaultCallSettings = this._defaults['listJobTriggers']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listJobTriggers iterate %j', request); return this.descriptors.page.listJobTriggers.asyncIterate( this.innerApiCalls['listJobTriggers'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } - /** - * Lists DlpJobs that match the specified filter in the request. - * See https://cloud.google.com/dlp/docs/inspecting-storage and - * https://cloud.google.com/dlp/docs/compute-risk-analysis to learn more. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent resource name, for example projects/my-project-id. - * @param {string} request.filter - * Allows filtering. - * - * Supported syntax: - * - * * Filter expressions are made up of one or more restrictions. - * * Restrictions can be combined by `AND` or `OR` logical operators. A - * sequence of restrictions implicitly uses `AND`. - * * A restriction has the form of `{field} {operator} {value}`. - * * Supported fields/values for inspect jobs: - * - `state` - PENDING|RUNNING|CANCELED|FINISHED|FAILED - * - `inspected_storage` - DATASTORE|CLOUD_STORAGE|BIGQUERY - * - `trigger_name` - The resource name of the trigger that created job. - * - 'end_time` - Corresponds to time the job finished. - * - 'start_time` - Corresponds to time the job finished. - * * Supported fields for risk analysis jobs: - * - `state` - RUNNING|CANCELED|FINISHED|FAILED - * - 'end_time` - Corresponds to time the job finished. - * - 'start_time` - Corresponds to time the job finished. - * * The operator must be `=` or `!=`. - * - * Examples: - * - * * inspected_storage = cloud_storage AND state = done - * * inspected_storage = cloud_storage OR inspected_storage = bigquery - * * inspected_storage = cloud_storage AND (state = done OR state = canceled) - * * end_time > \"2017-12-12T00:00:00+00:00\" - * - * The length of this field should be no more than 500 characters. - * @param {number} request.pageSize - * The standard list page size. - * @param {string} request.pageToken - * The standard list page token. - * @param {google.privacy.dlp.v2.DlpJobType} request.type - * The type of job. Defaults to `DlpJobType.INSPECT` - * @param {string} request.orderBy - * Comma separated list of fields to order by, - * followed by `asc` or `desc` postfix. This list is case-insensitive, - * default sorting order is ascending, redundant space characters are - * insignificant. - * - * Example: `name asc, end_time asc, create_time desc` - * - * Supported fields are: - * - * - `create_time`: corresponds to time the job was created. - * - `end_time`: corresponds to time the job ended. - * - `name`: corresponds to job's name. - * - `state`: corresponds to `state` - * @param {string} request.locationId - * The geographic location where jobs will be retrieved from. - * Use `-` for all locations. Reserved for future extensions. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.privacy.dlp.v2.DlpJob|DlpJob}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `listDlpJobsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Lists DlpJobs that match the specified filter in the request. + * See https://cloud.google.com/dlp/docs/inspecting-storage and + * https://cloud.google.com/dlp/docs/compute-risk-analysis to learn more. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource name, for example projects/my-project-id. + * @param {string} request.filter + * Allows filtering. + * + * Supported syntax: + * + * * Filter expressions are made up of one or more restrictions. + * * Restrictions can be combined by `AND` or `OR` logical operators. A + * sequence of restrictions implicitly uses `AND`. + * * A restriction has the form of `{field} {operator} {value}`. + * * Supported fields/values for inspect jobs: + * - `state` - PENDING|RUNNING|CANCELED|FINISHED|FAILED + * - `inspected_storage` - DATASTORE|CLOUD_STORAGE|BIGQUERY + * - `trigger_name` - The resource name of the trigger that created job. + * - 'end_time` - Corresponds to time the job finished. + * - 'start_time` - Corresponds to time the job finished. + * * Supported fields for risk analysis jobs: + * - `state` - RUNNING|CANCELED|FINISHED|FAILED + * - 'end_time` - Corresponds to time the job finished. + * - 'start_time` - Corresponds to time the job finished. + * * The operator must be `=` or `!=`. + * + * Examples: + * + * * inspected_storage = cloud_storage AND state = done + * * inspected_storage = cloud_storage OR inspected_storage = bigquery + * * inspected_storage = cloud_storage AND (state = done OR state = canceled) + * * end_time > \"2017-12-12T00:00:00+00:00\" + * + * The length of this field should be no more than 500 characters. + * @param {number} request.pageSize + * The standard list page size. + * @param {string} request.pageToken + * The standard list page token. + * @param {google.privacy.dlp.v2.DlpJobType} request.type + * The type of job. Defaults to `DlpJobType.INSPECT` + * @param {string} request.orderBy + * Comma separated list of fields to order by, + * followed by `asc` or `desc` postfix. This list is case-insensitive, + * default sorting order is ascending, redundant space characters are + * insignificant. + * + * Example: `name asc, end_time asc, create_time desc` + * + * Supported fields are: + * + * - `create_time`: corresponds to time the job was created. + * - `end_time`: corresponds to time the job ended. + * - `name`: corresponds to job's name. + * - `state`: corresponds to `state` + * @param {string} request.locationId + * The geographic location where jobs will be retrieved from. + * Use `-` for all locations. Reserved for future extensions. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.privacy.dlp.v2.DlpJob|DlpJob}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listDlpJobsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listDlpJobs( - request?: protos.google.privacy.dlp.v2.IListDlpJobsRequest, - options?: CallOptions): - Promise<[ - protos.google.privacy.dlp.v2.IDlpJob[], - protos.google.privacy.dlp.v2.IListDlpJobsRequest|null, - protos.google.privacy.dlp.v2.IListDlpJobsResponse - ]>; + request?: protos.google.privacy.dlp.v2.IListDlpJobsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.privacy.dlp.v2.IDlpJob[], + protos.google.privacy.dlp.v2.IListDlpJobsRequest | null, + protos.google.privacy.dlp.v2.IListDlpJobsResponse, + ] + >; listDlpJobs( - request: protos.google.privacy.dlp.v2.IListDlpJobsRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.privacy.dlp.v2.IListDlpJobsRequest, - protos.google.privacy.dlp.v2.IListDlpJobsResponse|null|undefined, - protos.google.privacy.dlp.v2.IDlpJob>): void; + request: protos.google.privacy.dlp.v2.IListDlpJobsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.privacy.dlp.v2.IListDlpJobsRequest, + protos.google.privacy.dlp.v2.IListDlpJobsResponse | null | undefined, + protos.google.privacy.dlp.v2.IDlpJob + >, + ): void; listDlpJobs( - request: protos.google.privacy.dlp.v2.IListDlpJobsRequest, - callback: PaginationCallback< - protos.google.privacy.dlp.v2.IListDlpJobsRequest, - protos.google.privacy.dlp.v2.IListDlpJobsResponse|null|undefined, - protos.google.privacy.dlp.v2.IDlpJob>): void; + request: protos.google.privacy.dlp.v2.IListDlpJobsRequest, + callback: PaginationCallback< + protos.google.privacy.dlp.v2.IListDlpJobsRequest, + protos.google.privacy.dlp.v2.IListDlpJobsResponse | null | undefined, + protos.google.privacy.dlp.v2.IDlpJob + >, + ): void; listDlpJobs( - request?: protos.google.privacy.dlp.v2.IListDlpJobsRequest, - optionsOrCallback?: CallOptions|PaginationCallback< - protos.google.privacy.dlp.v2.IListDlpJobsRequest, - protos.google.privacy.dlp.v2.IListDlpJobsResponse|null|undefined, - protos.google.privacy.dlp.v2.IDlpJob>, - callback?: PaginationCallback< + request?: protos.google.privacy.dlp.v2.IListDlpJobsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.privacy.dlp.v2.IListDlpJobsRequest, - protos.google.privacy.dlp.v2.IListDlpJobsResponse|null|undefined, - protos.google.privacy.dlp.v2.IDlpJob>): - Promise<[ - protos.google.privacy.dlp.v2.IDlpJob[], - protos.google.privacy.dlp.v2.IListDlpJobsRequest|null, - protos.google.privacy.dlp.v2.IListDlpJobsResponse - ]>|void { + protos.google.privacy.dlp.v2.IListDlpJobsResponse | null | undefined, + protos.google.privacy.dlp.v2.IDlpJob + >, + callback?: PaginationCallback< + protos.google.privacy.dlp.v2.IListDlpJobsRequest, + protos.google.privacy.dlp.v2.IListDlpJobsResponse | null | undefined, + protos.google.privacy.dlp.v2.IDlpJob + >, + ): Promise< + [ + protos.google.privacy.dlp.v2.IDlpJob[], + protos.google.privacy.dlp.v2.IListDlpJobsRequest | null, + protos.google.privacy.dlp.v2.IListDlpJobsResponse, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - 'location_id': request.locationId?.toString() ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + location_id: request.locationId?.toString() ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.privacy.dlp.v2.IListDlpJobsRequest, - protos.google.privacy.dlp.v2.IListDlpJobsResponse|null|undefined, - protos.google.privacy.dlp.v2.IDlpJob>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.privacy.dlp.v2.IListDlpJobsRequest, + protos.google.privacy.dlp.v2.IListDlpJobsResponse | null | undefined, + protos.google.privacy.dlp.v2.IDlpJob + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listDlpJobs values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -4071,311 +5206,340 @@ export class DlpServiceClient { this._log.info('listDlpJobs request %j', request); return this.innerApiCalls .listDlpJobs(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.privacy.dlp.v2.IDlpJob[], - protos.google.privacy.dlp.v2.IListDlpJobsRequest|null, - protos.google.privacy.dlp.v2.IListDlpJobsResponse - ]) => { - this._log.info('listDlpJobs values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.privacy.dlp.v2.IDlpJob[], + protos.google.privacy.dlp.v2.IListDlpJobsRequest | null, + protos.google.privacy.dlp.v2.IListDlpJobsResponse, + ]) => { + this._log.info('listDlpJobs values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listDlpJobs`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent resource name, for example projects/my-project-id. - * @param {string} request.filter - * Allows filtering. - * - * Supported syntax: - * - * * Filter expressions are made up of one or more restrictions. - * * Restrictions can be combined by `AND` or `OR` logical operators. A - * sequence of restrictions implicitly uses `AND`. - * * A restriction has the form of `{field} {operator} {value}`. - * * Supported fields/values for inspect jobs: - * - `state` - PENDING|RUNNING|CANCELED|FINISHED|FAILED - * - `inspected_storage` - DATASTORE|CLOUD_STORAGE|BIGQUERY - * - `trigger_name` - The resource name of the trigger that created job. - * - 'end_time` - Corresponds to time the job finished. - * - 'start_time` - Corresponds to time the job finished. - * * Supported fields for risk analysis jobs: - * - `state` - RUNNING|CANCELED|FINISHED|FAILED - * - 'end_time` - Corresponds to time the job finished. - * - 'start_time` - Corresponds to time the job finished. - * * The operator must be `=` or `!=`. - * - * Examples: - * - * * inspected_storage = cloud_storage AND state = done - * * inspected_storage = cloud_storage OR inspected_storage = bigquery - * * inspected_storage = cloud_storage AND (state = done OR state = canceled) - * * end_time > \"2017-12-12T00:00:00+00:00\" - * - * The length of this field should be no more than 500 characters. - * @param {number} request.pageSize - * The standard list page size. - * @param {string} request.pageToken - * The standard list page token. - * @param {google.privacy.dlp.v2.DlpJobType} request.type - * The type of job. Defaults to `DlpJobType.INSPECT` - * @param {string} request.orderBy - * Comma separated list of fields to order by, - * followed by `asc` or `desc` postfix. This list is case-insensitive, - * default sorting order is ascending, redundant space characters are - * insignificant. - * - * Example: `name asc, end_time asc, create_time desc` - * - * Supported fields are: - * - * - `create_time`: corresponds to time the job was created. - * - `end_time`: corresponds to time the job ended. - * - `name`: corresponds to job's name. - * - `state`: corresponds to `state` - * @param {string} request.locationId - * The geographic location where jobs will be retrieved from. - * Use `-` for all locations. Reserved for future extensions. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.privacy.dlp.v2.DlpJob|DlpJob} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `listDlpJobsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `listDlpJobs`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource name, for example projects/my-project-id. + * @param {string} request.filter + * Allows filtering. + * + * Supported syntax: + * + * * Filter expressions are made up of one or more restrictions. + * * Restrictions can be combined by `AND` or `OR` logical operators. A + * sequence of restrictions implicitly uses `AND`. + * * A restriction has the form of `{field} {operator} {value}`. + * * Supported fields/values for inspect jobs: + * - `state` - PENDING|RUNNING|CANCELED|FINISHED|FAILED + * - `inspected_storage` - DATASTORE|CLOUD_STORAGE|BIGQUERY + * - `trigger_name` - The resource name of the trigger that created job. + * - 'end_time` - Corresponds to time the job finished. + * - 'start_time` - Corresponds to time the job finished. + * * Supported fields for risk analysis jobs: + * - `state` - RUNNING|CANCELED|FINISHED|FAILED + * - 'end_time` - Corresponds to time the job finished. + * - 'start_time` - Corresponds to time the job finished. + * * The operator must be `=` or `!=`. + * + * Examples: + * + * * inspected_storage = cloud_storage AND state = done + * * inspected_storage = cloud_storage OR inspected_storage = bigquery + * * inspected_storage = cloud_storage AND (state = done OR state = canceled) + * * end_time > \"2017-12-12T00:00:00+00:00\" + * + * The length of this field should be no more than 500 characters. + * @param {number} request.pageSize + * The standard list page size. + * @param {string} request.pageToken + * The standard list page token. + * @param {google.privacy.dlp.v2.DlpJobType} request.type + * The type of job. Defaults to `DlpJobType.INSPECT` + * @param {string} request.orderBy + * Comma separated list of fields to order by, + * followed by `asc` or `desc` postfix. This list is case-insensitive, + * default sorting order is ascending, redundant space characters are + * insignificant. + * + * Example: `name asc, end_time asc, create_time desc` + * + * Supported fields are: + * + * - `create_time`: corresponds to time the job was created. + * - `end_time`: corresponds to time the job ended. + * - `name`: corresponds to job's name. + * - `state`: corresponds to `state` + * @param {string} request.locationId + * The geographic location where jobs will be retrieved from. + * Use `-` for all locations. Reserved for future extensions. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.privacy.dlp.v2.DlpJob|DlpJob} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listDlpJobsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listDlpJobsStream( - request?: protos.google.privacy.dlp.v2.IListDlpJobsRequest, - options?: CallOptions): - Transform{ + request?: protos.google.privacy.dlp.v2.IListDlpJobsRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - 'location_id': request.locationId?.toString() ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + location_id: request.locationId?.toString() ?? '', + }); const defaultCallSettings = this._defaults['listDlpJobs']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listDlpJobs stream %j', request); return this.descriptors.page.listDlpJobs.createStream( this.innerApiCalls.listDlpJobs as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listDlpJobs`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent resource name, for example projects/my-project-id. - * @param {string} request.filter - * Allows filtering. - * - * Supported syntax: - * - * * Filter expressions are made up of one or more restrictions. - * * Restrictions can be combined by `AND` or `OR` logical operators. A - * sequence of restrictions implicitly uses `AND`. - * * A restriction has the form of `{field} {operator} {value}`. - * * Supported fields/values for inspect jobs: - * - `state` - PENDING|RUNNING|CANCELED|FINISHED|FAILED - * - `inspected_storage` - DATASTORE|CLOUD_STORAGE|BIGQUERY - * - `trigger_name` - The resource name of the trigger that created job. - * - 'end_time` - Corresponds to time the job finished. - * - 'start_time` - Corresponds to time the job finished. - * * Supported fields for risk analysis jobs: - * - `state` - RUNNING|CANCELED|FINISHED|FAILED - * - 'end_time` - Corresponds to time the job finished. - * - 'start_time` - Corresponds to time the job finished. - * * The operator must be `=` or `!=`. - * - * Examples: - * - * * inspected_storage = cloud_storage AND state = done - * * inspected_storage = cloud_storage OR inspected_storage = bigquery - * * inspected_storage = cloud_storage AND (state = done OR state = canceled) - * * end_time > \"2017-12-12T00:00:00+00:00\" - * - * The length of this field should be no more than 500 characters. - * @param {number} request.pageSize - * The standard list page size. - * @param {string} request.pageToken - * The standard list page token. - * @param {google.privacy.dlp.v2.DlpJobType} request.type - * The type of job. Defaults to `DlpJobType.INSPECT` - * @param {string} request.orderBy - * Comma separated list of fields to order by, - * followed by `asc` or `desc` postfix. This list is case-insensitive, - * default sorting order is ascending, redundant space characters are - * insignificant. - * - * Example: `name asc, end_time asc, create_time desc` - * - * Supported fields are: - * - * - `create_time`: corresponds to time the job was created. - * - `end_time`: corresponds to time the job ended. - * - `name`: corresponds to job's name. - * - `state`: corresponds to `state` - * @param {string} request.locationId - * The geographic location where jobs will be retrieved from. - * Use `-` for all locations. Reserved for future extensions. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.privacy.dlp.v2.DlpJob|DlpJob}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v2/dlp_service.list_dlp_jobs.js - * region_tag:dlp_v2_generated_DlpService_ListDlpJobs_async - */ + /** + * Equivalent to `listDlpJobs`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource name, for example projects/my-project-id. + * @param {string} request.filter + * Allows filtering. + * + * Supported syntax: + * + * * Filter expressions are made up of one or more restrictions. + * * Restrictions can be combined by `AND` or `OR` logical operators. A + * sequence of restrictions implicitly uses `AND`. + * * A restriction has the form of `{field} {operator} {value}`. + * * Supported fields/values for inspect jobs: + * - `state` - PENDING|RUNNING|CANCELED|FINISHED|FAILED + * - `inspected_storage` - DATASTORE|CLOUD_STORAGE|BIGQUERY + * - `trigger_name` - The resource name of the trigger that created job. + * - 'end_time` - Corresponds to time the job finished. + * - 'start_time` - Corresponds to time the job finished. + * * Supported fields for risk analysis jobs: + * - `state` - RUNNING|CANCELED|FINISHED|FAILED + * - 'end_time` - Corresponds to time the job finished. + * - 'start_time` - Corresponds to time the job finished. + * * The operator must be `=` or `!=`. + * + * Examples: + * + * * inspected_storage = cloud_storage AND state = done + * * inspected_storage = cloud_storage OR inspected_storage = bigquery + * * inspected_storage = cloud_storage AND (state = done OR state = canceled) + * * end_time > \"2017-12-12T00:00:00+00:00\" + * + * The length of this field should be no more than 500 characters. + * @param {number} request.pageSize + * The standard list page size. + * @param {string} request.pageToken + * The standard list page token. + * @param {google.privacy.dlp.v2.DlpJobType} request.type + * The type of job. Defaults to `DlpJobType.INSPECT` + * @param {string} request.orderBy + * Comma separated list of fields to order by, + * followed by `asc` or `desc` postfix. This list is case-insensitive, + * default sorting order is ascending, redundant space characters are + * insignificant. + * + * Example: `name asc, end_time asc, create_time desc` + * + * Supported fields are: + * + * - `create_time`: corresponds to time the job was created. + * - `end_time`: corresponds to time the job ended. + * - `name`: corresponds to job's name. + * - `state`: corresponds to `state` + * @param {string} request.locationId + * The geographic location where jobs will be retrieved from. + * Use `-` for all locations. Reserved for future extensions. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.privacy.dlp.v2.DlpJob|DlpJob}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v2/dlp_service.list_dlp_jobs.js + * region_tag:dlp_v2_generated_DlpService_ListDlpJobs_async + */ listDlpJobsAsync( - request?: protos.google.privacy.dlp.v2.IListDlpJobsRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.privacy.dlp.v2.IListDlpJobsRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - 'location_id': request.locationId?.toString() ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + location_id: request.locationId?.toString() ?? '', + }); const defaultCallSettings = this._defaults['listDlpJobs']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listDlpJobs iterate %j', request); return this.descriptors.page.listDlpJobs.asyncIterate( this.innerApiCalls['listDlpJobs'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } - /** - * Lists stored infoTypes. - * See https://cloud.google.com/dlp/docs/creating-stored-infotypes to - * learn more. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent resource name, for example projects/my-project-id or - * organizations/my-org-id. - * @param {string} request.pageToken - * Page token to continue retrieval. Comes from previous call - * to `ListStoredInfoTypes`. - * @param {number} request.pageSize - * Size of the page, can be limited by server. If zero server returns - * a page of max size 100. - * @param {string} request.orderBy - * Comma separated list of fields to order by, - * followed by `asc` or `desc` postfix. This list is case-insensitive, - * default sorting order is ascending, redundant space characters are - * insignificant. - * - * Example: `name asc, display_name, create_time desc` - * - * Supported fields are: - * - * - `create_time`: corresponds to time the most recent version of the - * resource was created. - * - `state`: corresponds to the state of the resource. - * - `name`: corresponds to resource name. - * - `display_name`: corresponds to info type's display name. - * @param {string} request.locationId - * The geographic location where stored infoTypes will be retrieved from. - * Use `-` for all locations. Reserved for future extensions. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.privacy.dlp.v2.StoredInfoType|StoredInfoType}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `listStoredInfoTypesAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Lists stored infoTypes. + * See https://cloud.google.com/dlp/docs/creating-stored-infotypes to + * learn more. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource name, for example projects/my-project-id or + * organizations/my-org-id. + * @param {string} request.pageToken + * Page token to continue retrieval. Comes from previous call + * to `ListStoredInfoTypes`. + * @param {number} request.pageSize + * Size of the page, can be limited by server. If zero server returns + * a page of max size 100. + * @param {string} request.orderBy + * Comma separated list of fields to order by, + * followed by `asc` or `desc` postfix. This list is case-insensitive, + * default sorting order is ascending, redundant space characters are + * insignificant. + * + * Example: `name asc, display_name, create_time desc` + * + * Supported fields are: + * + * - `create_time`: corresponds to time the most recent version of the + * resource was created. + * - `state`: corresponds to the state of the resource. + * - `name`: corresponds to resource name. + * - `display_name`: corresponds to info type's display name. + * @param {string} request.locationId + * The geographic location where stored infoTypes will be retrieved from. + * Use `-` for all locations. Reserved for future extensions. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.privacy.dlp.v2.StoredInfoType|StoredInfoType}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listStoredInfoTypesAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listStoredInfoTypes( - request?: protos.google.privacy.dlp.v2.IListStoredInfoTypesRequest, - options?: CallOptions): - Promise<[ - protos.google.privacy.dlp.v2.IStoredInfoType[], - protos.google.privacy.dlp.v2.IListStoredInfoTypesRequest|null, - protos.google.privacy.dlp.v2.IListStoredInfoTypesResponse - ]>; + request?: protos.google.privacy.dlp.v2.IListStoredInfoTypesRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.privacy.dlp.v2.IStoredInfoType[], + protos.google.privacy.dlp.v2.IListStoredInfoTypesRequest | null, + protos.google.privacy.dlp.v2.IListStoredInfoTypesResponse, + ] + >; listStoredInfoTypes( - request: protos.google.privacy.dlp.v2.IListStoredInfoTypesRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.privacy.dlp.v2.IListStoredInfoTypesRequest, - protos.google.privacy.dlp.v2.IListStoredInfoTypesResponse|null|undefined, - protos.google.privacy.dlp.v2.IStoredInfoType>): void; + request: protos.google.privacy.dlp.v2.IListStoredInfoTypesRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.privacy.dlp.v2.IListStoredInfoTypesRequest, + | protos.google.privacy.dlp.v2.IListStoredInfoTypesResponse + | null + | undefined, + protos.google.privacy.dlp.v2.IStoredInfoType + >, + ): void; listStoredInfoTypes( - request: protos.google.privacy.dlp.v2.IListStoredInfoTypesRequest, - callback: PaginationCallback< - protos.google.privacy.dlp.v2.IListStoredInfoTypesRequest, - protos.google.privacy.dlp.v2.IListStoredInfoTypesResponse|null|undefined, - protos.google.privacy.dlp.v2.IStoredInfoType>): void; + request: protos.google.privacy.dlp.v2.IListStoredInfoTypesRequest, + callback: PaginationCallback< + protos.google.privacy.dlp.v2.IListStoredInfoTypesRequest, + | protos.google.privacy.dlp.v2.IListStoredInfoTypesResponse + | null + | undefined, + protos.google.privacy.dlp.v2.IStoredInfoType + >, + ): void; listStoredInfoTypes( - request?: protos.google.privacy.dlp.v2.IListStoredInfoTypesRequest, - optionsOrCallback?: CallOptions|PaginationCallback< + request?: protos.google.privacy.dlp.v2.IListStoredInfoTypesRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.privacy.dlp.v2.IListStoredInfoTypesRequest, - protos.google.privacy.dlp.v2.IListStoredInfoTypesResponse|null|undefined, - protos.google.privacy.dlp.v2.IStoredInfoType>, - callback?: PaginationCallback< - protos.google.privacy.dlp.v2.IListStoredInfoTypesRequest, - protos.google.privacy.dlp.v2.IListStoredInfoTypesResponse|null|undefined, - protos.google.privacy.dlp.v2.IStoredInfoType>): - Promise<[ - protos.google.privacy.dlp.v2.IStoredInfoType[], - protos.google.privacy.dlp.v2.IListStoredInfoTypesRequest|null, - protos.google.privacy.dlp.v2.IListStoredInfoTypesResponse - ]>|void { + | protos.google.privacy.dlp.v2.IListStoredInfoTypesResponse + | null + | undefined, + protos.google.privacy.dlp.v2.IStoredInfoType + >, + callback?: PaginationCallback< + protos.google.privacy.dlp.v2.IListStoredInfoTypesRequest, + | protos.google.privacy.dlp.v2.IListStoredInfoTypesResponse + | null + | undefined, + protos.google.privacy.dlp.v2.IStoredInfoType + >, + ): Promise< + [ + protos.google.privacy.dlp.v2.IStoredInfoType[], + protos.google.privacy.dlp.v2.IListStoredInfoTypesRequest | null, + protos.google.privacy.dlp.v2.IListStoredInfoTypesResponse, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - 'location_id': request.locationId?.toString() ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + location_id: request.locationId?.toString() ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.privacy.dlp.v2.IListStoredInfoTypesRequest, - protos.google.privacy.dlp.v2.IListStoredInfoTypesResponse|null|undefined, - protos.google.privacy.dlp.v2.IStoredInfoType>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.privacy.dlp.v2.IListStoredInfoTypesRequest, + | protos.google.privacy.dlp.v2.IListStoredInfoTypesResponse + | null + | undefined, + protos.google.privacy.dlp.v2.IStoredInfoType + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listStoredInfoTypes values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -4384,150 +5548,154 @@ export class DlpServiceClient { this._log.info('listStoredInfoTypes request %j', request); return this.innerApiCalls .listStoredInfoTypes(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.privacy.dlp.v2.IStoredInfoType[], - protos.google.privacy.dlp.v2.IListStoredInfoTypesRequest|null, - protos.google.privacy.dlp.v2.IListStoredInfoTypesResponse - ]) => { - this._log.info('listStoredInfoTypes values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.privacy.dlp.v2.IStoredInfoType[], + protos.google.privacy.dlp.v2.IListStoredInfoTypesRequest | null, + protos.google.privacy.dlp.v2.IListStoredInfoTypesResponse, + ]) => { + this._log.info('listStoredInfoTypes values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listStoredInfoTypes`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent resource name, for example projects/my-project-id or - * organizations/my-org-id. - * @param {string} request.pageToken - * Page token to continue retrieval. Comes from previous call - * to `ListStoredInfoTypes`. - * @param {number} request.pageSize - * Size of the page, can be limited by server. If zero server returns - * a page of max size 100. - * @param {string} request.orderBy - * Comma separated list of fields to order by, - * followed by `asc` or `desc` postfix. This list is case-insensitive, - * default sorting order is ascending, redundant space characters are - * insignificant. - * - * Example: `name asc, display_name, create_time desc` - * - * Supported fields are: - * - * - `create_time`: corresponds to time the most recent version of the - * resource was created. - * - `state`: corresponds to the state of the resource. - * - `name`: corresponds to resource name. - * - `display_name`: corresponds to info type's display name. - * @param {string} request.locationId - * The geographic location where stored infoTypes will be retrieved from. - * Use `-` for all locations. Reserved for future extensions. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.privacy.dlp.v2.StoredInfoType|StoredInfoType} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `listStoredInfoTypesAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `listStoredInfoTypes`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource name, for example projects/my-project-id or + * organizations/my-org-id. + * @param {string} request.pageToken + * Page token to continue retrieval. Comes from previous call + * to `ListStoredInfoTypes`. + * @param {number} request.pageSize + * Size of the page, can be limited by server. If zero server returns + * a page of max size 100. + * @param {string} request.orderBy + * Comma separated list of fields to order by, + * followed by `asc` or `desc` postfix. This list is case-insensitive, + * default sorting order is ascending, redundant space characters are + * insignificant. + * + * Example: `name asc, display_name, create_time desc` + * + * Supported fields are: + * + * - `create_time`: corresponds to time the most recent version of the + * resource was created. + * - `state`: corresponds to the state of the resource. + * - `name`: corresponds to resource name. + * - `display_name`: corresponds to info type's display name. + * @param {string} request.locationId + * The geographic location where stored infoTypes will be retrieved from. + * Use `-` for all locations. Reserved for future extensions. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.privacy.dlp.v2.StoredInfoType|StoredInfoType} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listStoredInfoTypesAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listStoredInfoTypesStream( - request?: protos.google.privacy.dlp.v2.IListStoredInfoTypesRequest, - options?: CallOptions): - Transform{ + request?: protos.google.privacy.dlp.v2.IListStoredInfoTypesRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - 'location_id': request.locationId?.toString() ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + location_id: request.locationId?.toString() ?? '', + }); const defaultCallSettings = this._defaults['listStoredInfoTypes']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listStoredInfoTypes stream %j', request); return this.descriptors.page.listStoredInfoTypes.createStream( this.innerApiCalls.listStoredInfoTypes as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listStoredInfoTypes`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent resource name, for example projects/my-project-id or - * organizations/my-org-id. - * @param {string} request.pageToken - * Page token to continue retrieval. Comes from previous call - * to `ListStoredInfoTypes`. - * @param {number} request.pageSize - * Size of the page, can be limited by server. If zero server returns - * a page of max size 100. - * @param {string} request.orderBy - * Comma separated list of fields to order by, - * followed by `asc` or `desc` postfix. This list is case-insensitive, - * default sorting order is ascending, redundant space characters are - * insignificant. - * - * Example: `name asc, display_name, create_time desc` - * - * Supported fields are: - * - * - `create_time`: corresponds to time the most recent version of the - * resource was created. - * - `state`: corresponds to the state of the resource. - * - `name`: corresponds to resource name. - * - `display_name`: corresponds to info type's display name. - * @param {string} request.locationId - * The geographic location where stored infoTypes will be retrieved from. - * Use `-` for all locations. Reserved for future extensions. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.privacy.dlp.v2.StoredInfoType|StoredInfoType}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v2/dlp_service.list_stored_info_types.js - * region_tag:dlp_v2_generated_DlpService_ListStoredInfoTypes_async - */ + /** + * Equivalent to `listStoredInfoTypes`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource name, for example projects/my-project-id or + * organizations/my-org-id. + * @param {string} request.pageToken + * Page token to continue retrieval. Comes from previous call + * to `ListStoredInfoTypes`. + * @param {number} request.pageSize + * Size of the page, can be limited by server. If zero server returns + * a page of max size 100. + * @param {string} request.orderBy + * Comma separated list of fields to order by, + * followed by `asc` or `desc` postfix. This list is case-insensitive, + * default sorting order is ascending, redundant space characters are + * insignificant. + * + * Example: `name asc, display_name, create_time desc` + * + * Supported fields are: + * + * - `create_time`: corresponds to time the most recent version of the + * resource was created. + * - `state`: corresponds to the state of the resource. + * - `name`: corresponds to resource name. + * - `display_name`: corresponds to info type's display name. + * @param {string} request.locationId + * The geographic location where stored infoTypes will be retrieved from. + * Use `-` for all locations. Reserved for future extensions. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.privacy.dlp.v2.StoredInfoType|StoredInfoType}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v2/dlp_service.list_stored_info_types.js + * region_tag:dlp_v2_generated_DlpService_ListStoredInfoTypes_async + */ listStoredInfoTypesAsync( - request?: protos.google.privacy.dlp.v2.IListStoredInfoTypesRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.privacy.dlp.v2.IListStoredInfoTypesRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - 'location_id': request.locationId?.toString() ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + location_id: request.locationId?.toString() ?? '', + }); const defaultCallSettings = this._defaults['listStoredInfoTypes']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listStoredInfoTypes iterate %j', request); return this.descriptors.page.listStoredInfoTypes.asyncIterate( this.innerApiCalls['listStoredInfoTypes'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } // -------------------- @@ -4541,7 +5709,7 @@ export class DlpServiceClient { * @param {string} dlp_job * @returns {string} Resource name string. */ - dlpJobPath(project:string,dlpJob:string) { + dlpJobPath(project: string, dlpJob: string) { return this.pathTemplates.dlpJobPathTemplate.render({ project: project, dlp_job: dlpJob, @@ -4577,7 +5745,7 @@ export class DlpServiceClient { * @param {string} job_trigger * @returns {string} Resource name string. */ - jobTriggerPath(project:string,jobTrigger:string) { + jobTriggerPath(project: string, jobTrigger: string) { return this.pathTemplates.jobTriggerPathTemplate.render({ project: project, job_trigger: jobTrigger, @@ -4592,7 +5760,8 @@ export class DlpServiceClient { * @returns {string} A string representing the project. */ matchProjectFromJobTriggerName(jobTriggerName: string) { - return this.pathTemplates.jobTriggerPathTemplate.match(jobTriggerName).project; + return this.pathTemplates.jobTriggerPathTemplate.match(jobTriggerName) + .project; } /** @@ -4603,7 +5772,8 @@ export class DlpServiceClient { * @returns {string} A string representing the job_trigger. */ matchJobTriggerFromJobTriggerName(jobTriggerName: string) { - return this.pathTemplates.jobTriggerPathTemplate.match(jobTriggerName).job_trigger; + return this.pathTemplates.jobTriggerPathTemplate.match(jobTriggerName) + .job_trigger; } /** @@ -4612,7 +5782,7 @@ export class DlpServiceClient { * @param {string} organization * @returns {string} Resource name string. */ - organizationPath(organization:string) { + organizationPath(organization: string) { return this.pathTemplates.organizationPathTemplate.render({ organization: organization, }); @@ -4626,7 +5796,8 @@ export class DlpServiceClient { * @returns {string} A string representing the organization. */ matchOrganizationFromOrganizationName(organizationName: string) { - return this.pathTemplates.organizationPathTemplate.match(organizationName).organization; + return this.pathTemplates.organizationPathTemplate.match(organizationName) + .organization; } /** @@ -4636,11 +5807,16 @@ export class DlpServiceClient { * @param {string} deidentify_template * @returns {string} Resource name string. */ - organizationDeidentifyTemplatePath(organization:string,deidentifyTemplate:string) { - return this.pathTemplates.organizationDeidentifyTemplatePathTemplate.render({ - organization: organization, - deidentify_template: deidentifyTemplate, - }); + organizationDeidentifyTemplatePath( + organization: string, + deidentifyTemplate: string, + ) { + return this.pathTemplates.organizationDeidentifyTemplatePathTemplate.render( + { + organization: organization, + deidentify_template: deidentifyTemplate, + }, + ); } /** @@ -4650,8 +5826,12 @@ export class DlpServiceClient { * A fully-qualified path representing organization_deidentify_template resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationDeidentifyTemplateName(organizationDeidentifyTemplateName: string) { - return this.pathTemplates.organizationDeidentifyTemplatePathTemplate.match(organizationDeidentifyTemplateName).organization; + matchOrganizationFromOrganizationDeidentifyTemplateName( + organizationDeidentifyTemplateName: string, + ) { + return this.pathTemplates.organizationDeidentifyTemplatePathTemplate.match( + organizationDeidentifyTemplateName, + ).organization; } /** @@ -4661,8 +5841,12 @@ export class DlpServiceClient { * A fully-qualified path representing organization_deidentify_template resource. * @returns {string} A string representing the deidentify_template. */ - matchDeidentifyTemplateFromOrganizationDeidentifyTemplateName(organizationDeidentifyTemplateName: string) { - return this.pathTemplates.organizationDeidentifyTemplatePathTemplate.match(organizationDeidentifyTemplateName).deidentify_template; + matchDeidentifyTemplateFromOrganizationDeidentifyTemplateName( + organizationDeidentifyTemplateName: string, + ) { + return this.pathTemplates.organizationDeidentifyTemplatePathTemplate.match( + organizationDeidentifyTemplateName, + ).deidentify_template; } /** @@ -4672,7 +5856,10 @@ export class DlpServiceClient { * @param {string} inspect_template * @returns {string} Resource name string. */ - organizationInspectTemplatePath(organization:string,inspectTemplate:string) { + organizationInspectTemplatePath( + organization: string, + inspectTemplate: string, + ) { return this.pathTemplates.organizationInspectTemplatePathTemplate.render({ organization: organization, inspect_template: inspectTemplate, @@ -4686,8 +5873,12 @@ export class DlpServiceClient { * A fully-qualified path representing organization_inspect_template resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationInspectTemplateName(organizationInspectTemplateName: string) { - return this.pathTemplates.organizationInspectTemplatePathTemplate.match(organizationInspectTemplateName).organization; + matchOrganizationFromOrganizationInspectTemplateName( + organizationInspectTemplateName: string, + ) { + return this.pathTemplates.organizationInspectTemplatePathTemplate.match( + organizationInspectTemplateName, + ).organization; } /** @@ -4697,8 +5888,12 @@ export class DlpServiceClient { * A fully-qualified path representing organization_inspect_template resource. * @returns {string} A string representing the inspect_template. */ - matchInspectTemplateFromOrganizationInspectTemplateName(organizationInspectTemplateName: string) { - return this.pathTemplates.organizationInspectTemplatePathTemplate.match(organizationInspectTemplateName).inspect_template; + matchInspectTemplateFromOrganizationInspectTemplateName( + organizationInspectTemplateName: string, + ) { + return this.pathTemplates.organizationInspectTemplatePathTemplate.match( + organizationInspectTemplateName, + ).inspect_template; } /** @@ -4708,7 +5903,7 @@ export class DlpServiceClient { * @param {string} stored_info_type * @returns {string} Resource name string. */ - organizationStoredInfoTypePath(organization:string,storedInfoType:string) { + organizationStoredInfoTypePath(organization: string, storedInfoType: string) { return this.pathTemplates.organizationStoredInfoTypePathTemplate.render({ organization: organization, stored_info_type: storedInfoType, @@ -4722,8 +5917,12 @@ export class DlpServiceClient { * A fully-qualified path representing organization_stored_info_type resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationStoredInfoTypeName(organizationStoredInfoTypeName: string) { - return this.pathTemplates.organizationStoredInfoTypePathTemplate.match(organizationStoredInfoTypeName).organization; + matchOrganizationFromOrganizationStoredInfoTypeName( + organizationStoredInfoTypeName: string, + ) { + return this.pathTemplates.organizationStoredInfoTypePathTemplate.match( + organizationStoredInfoTypeName, + ).organization; } /** @@ -4733,8 +5932,12 @@ export class DlpServiceClient { * A fully-qualified path representing organization_stored_info_type resource. * @returns {string} A string representing the stored_info_type. */ - matchStoredInfoTypeFromOrganizationStoredInfoTypeName(organizationStoredInfoTypeName: string) { - return this.pathTemplates.organizationStoredInfoTypePathTemplate.match(organizationStoredInfoTypeName).stored_info_type; + matchStoredInfoTypeFromOrganizationStoredInfoTypeName( + organizationStoredInfoTypeName: string, + ) { + return this.pathTemplates.organizationStoredInfoTypePathTemplate.match( + organizationStoredInfoTypeName, + ).stored_info_type; } /** @@ -4743,7 +5946,7 @@ export class DlpServiceClient { * @param {string} project * @returns {string} Resource name string. */ - projectPath(project:string) { + projectPath(project: string) { return this.pathTemplates.projectPathTemplate.render({ project: project, }); @@ -4767,7 +5970,7 @@ export class DlpServiceClient { * @param {string} deidentify_template * @returns {string} Resource name string. */ - projectDeidentifyTemplatePath(project:string,deidentifyTemplate:string) { + projectDeidentifyTemplatePath(project: string, deidentifyTemplate: string) { return this.pathTemplates.projectDeidentifyTemplatePathTemplate.render({ project: project, deidentify_template: deidentifyTemplate, @@ -4781,8 +5984,12 @@ export class DlpServiceClient { * A fully-qualified path representing project_deidentify_template resource. * @returns {string} A string representing the project. */ - matchProjectFromProjectDeidentifyTemplateName(projectDeidentifyTemplateName: string) { - return this.pathTemplates.projectDeidentifyTemplatePathTemplate.match(projectDeidentifyTemplateName).project; + matchProjectFromProjectDeidentifyTemplateName( + projectDeidentifyTemplateName: string, + ) { + return this.pathTemplates.projectDeidentifyTemplatePathTemplate.match( + projectDeidentifyTemplateName, + ).project; } /** @@ -4792,8 +5999,12 @@ export class DlpServiceClient { * A fully-qualified path representing project_deidentify_template resource. * @returns {string} A string representing the deidentify_template. */ - matchDeidentifyTemplateFromProjectDeidentifyTemplateName(projectDeidentifyTemplateName: string) { - return this.pathTemplates.projectDeidentifyTemplatePathTemplate.match(projectDeidentifyTemplateName).deidentify_template; + matchDeidentifyTemplateFromProjectDeidentifyTemplateName( + projectDeidentifyTemplateName: string, + ) { + return this.pathTemplates.projectDeidentifyTemplatePathTemplate.match( + projectDeidentifyTemplateName, + ).deidentify_template; } /** @@ -4803,7 +6014,7 @@ export class DlpServiceClient { * @param {string} inspect_template * @returns {string} Resource name string. */ - projectInspectTemplatePath(project:string,inspectTemplate:string) { + projectInspectTemplatePath(project: string, inspectTemplate: string) { return this.pathTemplates.projectInspectTemplatePathTemplate.render({ project: project, inspect_template: inspectTemplate, @@ -4817,8 +6028,12 @@ export class DlpServiceClient { * A fully-qualified path representing project_inspect_template resource. * @returns {string} A string representing the project. */ - matchProjectFromProjectInspectTemplateName(projectInspectTemplateName: string) { - return this.pathTemplates.projectInspectTemplatePathTemplate.match(projectInspectTemplateName).project; + matchProjectFromProjectInspectTemplateName( + projectInspectTemplateName: string, + ) { + return this.pathTemplates.projectInspectTemplatePathTemplate.match( + projectInspectTemplateName, + ).project; } /** @@ -4828,8 +6043,12 @@ export class DlpServiceClient { * A fully-qualified path representing project_inspect_template resource. * @returns {string} A string representing the inspect_template. */ - matchInspectTemplateFromProjectInspectTemplateName(projectInspectTemplateName: string) { - return this.pathTemplates.projectInspectTemplatePathTemplate.match(projectInspectTemplateName).inspect_template; + matchInspectTemplateFromProjectInspectTemplateName( + projectInspectTemplateName: string, + ) { + return this.pathTemplates.projectInspectTemplatePathTemplate.match( + projectInspectTemplateName, + ).inspect_template; } /** @@ -4839,7 +6058,7 @@ export class DlpServiceClient { * @param {string} stored_info_type * @returns {string} Resource name string. */ - projectStoredInfoTypePath(project:string,storedInfoType:string) { + projectStoredInfoTypePath(project: string, storedInfoType: string) { return this.pathTemplates.projectStoredInfoTypePathTemplate.render({ project: project, stored_info_type: storedInfoType, @@ -4854,7 +6073,9 @@ export class DlpServiceClient { * @returns {string} A string representing the project. */ matchProjectFromProjectStoredInfoTypeName(projectStoredInfoTypeName: string) { - return this.pathTemplates.projectStoredInfoTypePathTemplate.match(projectStoredInfoTypeName).project; + return this.pathTemplates.projectStoredInfoTypePathTemplate.match( + projectStoredInfoTypeName, + ).project; } /** @@ -4864,8 +6085,12 @@ export class DlpServiceClient { * A fully-qualified path representing project_stored_info_type resource. * @returns {string} A string representing the stored_info_type. */ - matchStoredInfoTypeFromProjectStoredInfoTypeName(projectStoredInfoTypeName: string) { - return this.pathTemplates.projectStoredInfoTypePathTemplate.match(projectStoredInfoTypeName).stored_info_type; + matchStoredInfoTypeFromProjectStoredInfoTypeName( + projectStoredInfoTypeName: string, + ) { + return this.pathTemplates.projectStoredInfoTypePathTemplate.match( + projectStoredInfoTypeName, + ).stored_info_type; } /** @@ -4876,7 +6101,7 @@ export class DlpServiceClient { */ close(): Promise { if (this.dlpServiceStub && !this._terminated) { - return this.dlpServiceStub.then(stub => { + return this.dlpServiceStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -4884,4 +6109,4 @@ export class DlpServiceClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/core/generator/gapic-generator-typescript/baselines/dlp/src/v2/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/dlp/src/v2/index.ts.baseline index 676584dc4e43..824f284af950 100644 --- a/core/generator/gapic-generator-typescript/baselines/dlp/src/v2/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/dlp/src/v2/index.ts.baseline @@ -16,4 +16,4 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -export {DlpServiceClient} from './dlp_service_client'; +export { DlpServiceClient } from './dlp_service_client'; diff --git a/core/generator/gapic-generator-typescript/baselines/dlp/system-test/fixtures/sample/src/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/dlp/system-test/fixtures/sample/src/index.ts.baseline index 9a3099a6afc2..4297e22ab0c2 100644 --- a/core/generator/gapic-generator-typescript/baselines/dlp/system-test/fixtures/sample/src/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/dlp/system-test/fixtures/sample/src/index.ts.baseline @@ -16,7 +16,7 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -import {DlpServiceClient} from 'dlp'; +import { DlpServiceClient } from 'dlp'; // check that the client class type name can be used function doStuffWithDlpServiceClient(client: DlpServiceClient) { diff --git a/core/generator/gapic-generator-typescript/baselines/dlp/system-test/install.ts.baseline b/core/generator/gapic-generator-typescript/baselines/dlp/system-test/install.ts.baseline index f66069aa3940..ccf167042d2e 100644 --- a/core/generator/gapic-generator-typescript/baselines/dlp/system-test/install.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/dlp/system-test/install.ts.baseline @@ -16,34 +16,36 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -import {packNTest} from 'pack-n-play'; -import {readFileSync} from 'fs'; -import {describe, it} from 'mocha'; +import { packNTest } from 'pack-n-play'; +import { readFileSync } from 'fs'; +import { describe, it } from 'mocha'; describe('📦 pack-n-play test', () => { - - it('TypeScript code', async function() { + it('TypeScript code', async function () { this.timeout(300000); const options = { packageDir: process.cwd(), sample: { description: 'TypeScript user can use the type definitions', - ts: readFileSync('./system-test/fixtures/sample/src/index.ts').toString() - } + ts: readFileSync( + './system-test/fixtures/sample/src/index.ts', + ).toString(), + }, }; await packNTest(options); }); - it('JavaScript code', async function() { + it('JavaScript code', async function () { this.timeout(300000); const options = { packageDir: process.cwd(), sample: { description: 'JavaScript user can use the library', - cjs: readFileSync('./system-test/fixtures/sample/src/index.js').toString() - } + cjs: readFileSync( + './system-test/fixtures/sample/src/index.js', + ).toString(), + }, }; await packNTest(options); }); - }); diff --git a/core/generator/gapic-generator-typescript/baselines/dlp/test/gapic_dlp_service_v2.ts.baseline b/core/generator/gapic-generator-typescript/baselines/dlp/test/gapic_dlp_service_v2.ts.baseline index 0952f9f499eb..6e735d3c95c9 100644 --- a/core/generator/gapic-generator-typescript/baselines/dlp/test/gapic_dlp_service_v2.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/dlp/test/gapic_dlp_service_v2.ts.baseline @@ -19,4856 +19,6300 @@ import * as protos from '../protos/protos'; import * as assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as dlpserviceModule from '../src'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; -import {protobuf} from 'google-gax'; +import { protobuf } from 'google-gax'; // Dynamically loaded proto JSON is needed to get the type information // to fill in default values for request objects -const root = protobuf.Root.fromJSON(require('../protos/protos.json')).resolveAll(); +const root = protobuf.Root.fromJSON( + require('../protos/protos.json'), +).resolveAll(); // eslint-disable-next-line @typescript-eslint/no-unused-vars function getTypeDefaultValue(typeName: string, fields: string[]) { - let type = root.lookupType(typeName) as protobuf.Type; - for (const field of fields.slice(0, -1)) { - type = type.fields[field]?.resolvedType as protobuf.Type; - } - return type.fields[fields[fields.length - 1]]?.defaultValue; + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type.fields[field]?.resolvedType as protobuf.Type; + } + return type.fields[fields[fields.length - 1]]?.defaultValue; } function generateSampleMessage(instance: T) { - const filledObject = (instance.constructor as typeof protobuf.Message) - .toObject(instance as protobuf.Message, {defaults: true}); - return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, { defaults: true }); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; } function stubSimpleCall(response?: ResponseType, error?: Error) { - return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); } -function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { - return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +function stubSimpleCallWithCallback( + response?: ResponseType, + error?: Error, +) { + return error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); } -function stubPageStreamingCall(responses?: ResponseType[], error?: Error) { - const pagingStub = sinon.stub(); - if (responses) { - for (let i = 0; i < responses.length; ++i) { - pagingStub.onCall(i).callsArgWith(2, null, responses[i]); - } +function stubPageStreamingCall( + responses?: ResponseType[], + error?: Error, +) { + const pagingStub = sinon.stub(); + if (responses) { + for (let i = 0; i < responses.length; ++i) { + pagingStub.onCall(i).callsArgWith(2, null, responses[i]); } - const transformStub = error ? sinon.stub().callsArgWith(2, error) : pagingStub; - const mockStream = new PassThrough({ - objectMode: true, - transform: transformStub, - }); - // trigger as many responses as needed - if (responses) { - for (let i = 0; i < responses.length; ++i) { - setImmediate(() => { mockStream.write({}); }); - } - setImmediate(() => { mockStream.end(); }); - } else { - setImmediate(() => { mockStream.write({}); }); - setImmediate(() => { mockStream.end(); }); + } + const transformStub = error + ? sinon.stub().callsArgWith(2, error) + : pagingStub; + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + // trigger as many responses as needed + if (responses) { + for (let i = 0; i < responses.length; ++i) { + setImmediate(() => { + mockStream.write({}); + }); } - return sinon.stub().returns(mockStream); + setImmediate(() => { + mockStream.end(); + }); + } else { + setImmediate(() => { + mockStream.write({}); + }); + setImmediate(() => { + mockStream.end(); + }); + } + return sinon.stub().returns(mockStream); } -function stubAsyncIterationCall(responses?: ResponseType[], error?: Error) { - let counter = 0; - const asyncIterable = { - [Symbol.asyncIterator]() { - return { - async next() { - if (error) { - return Promise.reject(error); - } - if (counter >= responses!.length) { - return Promise.resolve({done: true, value: undefined}); - } - return Promise.resolve({done: false, value: responses![counter++]}); - } - }; - } - }; - return sinon.stub().returns(asyncIterable); +function stubAsyncIterationCall( + responses?: ResponseType[], + error?: Error, +) { + let counter = 0; + const asyncIterable = { + [Symbol.asyncIterator]() { + return { + async next() { + if (error) { + return Promise.reject(error); + } + if (counter >= responses!.length) { + return Promise.resolve({ done: true, value: undefined }); + } + return Promise.resolve({ done: false, value: responses![counter++] }); + }, + }; + }, + }; + return sinon.stub().returns(asyncIterable); } describe('v2.DlpServiceClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new dlpserviceModule.v2.DlpServiceClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'dlp.googleapis.com'); - }); - - it('has universeDomain', () => { - const client = new dlpserviceModule.v2.DlpServiceClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); - - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - it('throws DeprecationWarning if static servicePath is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const servicePath = dlpserviceModule.v2.DlpServiceClient.servicePath; - assert.strictEqual(servicePath, 'dlp.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = dlpserviceModule.v2.DlpServiceClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'dlp.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new dlpserviceModule.v2.DlpServiceClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'dlp.example.com'); - }); - - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new dlpserviceModule.v2.DlpServiceClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'dlp.example.com'); - }); - - if (typeof process === 'object' && 'env' in process) { - describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { - it('sets apiEndpoint from environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new dlpserviceModule.v2.DlpServiceClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'dlp.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - - it('value configured in code has priority over environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new dlpserviceModule.v2.DlpServiceClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'dlp.configured.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { new dlpserviceModule.v2.DlpServiceClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); - - it('has port', () => { - const port = dlpserviceModule.v2.DlpServiceClient.port; - assert(port); - assert(typeof port === 'number'); - }); - - it('should create a client with no option', () => { - const client = new dlpserviceModule.v2.DlpServiceClient(); - assert(client); - }); - - it('should create a client with gRPC fallback', () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - fallback: true, - }); - assert(client); - }); - - it('has initialize method and supports deferred initialization', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.dlpServiceStub, undefined); - await client.initialize(); - assert(client.dlpServiceStub); - }); - - it('has close method for the initialized client', done => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.dlpServiceStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); - - it('has close method for the non-initialized client', done => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.dlpServiceStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); - - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); - }); - - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId((err?: Error|null, projectId?: string|null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } - }); - }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new dlpserviceModule.v2.DlpServiceClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'dlp.googleapis.com'); }); - describe('inspectContent', () => { - it('invokes inspectContent without error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.InspectContentRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.InspectContentRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.InspectContentRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.privacy.dlp.v2.InspectContentResponse() - ); - client.innerApiCalls.inspectContent = stubSimpleCall(expectedResponse); - const [response] = await client.inspectContent(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.inspectContent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.inspectContent as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes inspectContent without error using callback', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.InspectContentRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.InspectContentRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.InspectContentRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.privacy.dlp.v2.InspectContentResponse() - ); - client.innerApiCalls.inspectContent = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.inspectContent( - request, - (err?: Error|null, result?: protos.google.privacy.dlp.v2.IInspectContentResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.inspectContent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.inspectContent as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes inspectContent with error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.InspectContentRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.InspectContentRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.InspectContentRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.inspectContent = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.inspectContent(request), expectedError); - const actualRequest = (client.innerApiCalls.inspectContent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.inspectContent as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes inspectContent with closed client', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.InspectContentRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.InspectContentRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.InspectContentRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.inspectContent(request), expectedError); - }); + it('has universeDomain', () => { + const client = new dlpserviceModule.v2.DlpServiceClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); }); - describe('redactImage', () => { - it('invokes redactImage without error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.RedactImageRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.RedactImageRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.RedactImageRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.privacy.dlp.v2.RedactImageResponse() - ); - client.innerApiCalls.redactImage = stubSimpleCall(expectedResponse); - const [response] = await client.redactImage(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.redactImage as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.redactImage as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes redactImage without error using callback', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.RedactImageRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.RedactImageRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.RedactImageRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.privacy.dlp.v2.RedactImageResponse() - ); - client.innerApiCalls.redactImage = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.redactImage( - request, - (err?: Error|null, result?: protos.google.privacy.dlp.v2.IRedactImageResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.redactImage as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.redactImage as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes redactImage with error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.RedactImageRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.RedactImageRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.RedactImageRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.redactImage = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.redactImage(request), expectedError); - const actualRequest = (client.innerApiCalls.redactImage as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.redactImage as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes redactImage with closed client', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.RedactImageRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.RedactImageRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.RedactImageRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.redactImage(request), expectedError); - }); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = dlpserviceModule.v2.DlpServiceClient.servicePath; + assert.strictEqual(servicePath, 'dlp.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = dlpserviceModule.v2.DlpServiceClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'dlp.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + universeDomain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'dlp.example.com'); }); - describe('deidentifyContent', () => { - it('invokes deidentifyContent without error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.DeidentifyContentRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.DeidentifyContentRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.DeidentifyContentRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.privacy.dlp.v2.DeidentifyContentResponse() - ); - client.innerApiCalls.deidentifyContent = stubSimpleCall(expectedResponse); - const [response] = await client.deidentifyContent(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deidentifyContent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deidentifyContent as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes deidentifyContent without error using callback', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.DeidentifyContentRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.DeidentifyContentRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.DeidentifyContentRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.privacy.dlp.v2.DeidentifyContentResponse() - ); - client.innerApiCalls.deidentifyContent = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deidentifyContent( - request, - (err?: Error|null, result?: protos.google.privacy.dlp.v2.IDeidentifyContentResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deidentifyContent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deidentifyContent as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes deidentifyContent with error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.DeidentifyContentRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.DeidentifyContentRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.DeidentifyContentRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deidentifyContent = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deidentifyContent(request), expectedError); - const actualRequest = (client.innerApiCalls.deidentifyContent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deidentifyContent as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes deidentifyContent with closed client', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.DeidentifyContentRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.DeidentifyContentRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.DeidentifyContentRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deidentifyContent(request), expectedError); - }); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + universe_domain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'dlp.example.com'); }); - describe('reidentifyContent', () => { - it('invokes reidentifyContent without error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.ReidentifyContentRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.ReidentifyContentRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.ReidentifyContentRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.privacy.dlp.v2.ReidentifyContentResponse() - ); - client.innerApiCalls.reidentifyContent = stubSimpleCall(expectedResponse); - const [response] = await client.reidentifyContent(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.reidentifyContent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.reidentifyContent as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes reidentifyContent without error using callback', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.ReidentifyContentRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.ReidentifyContentRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.ReidentifyContentRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.privacy.dlp.v2.ReidentifyContentResponse() - ); - client.innerApiCalls.reidentifyContent = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.reidentifyContent( - request, - (err?: Error|null, result?: protos.google.privacy.dlp.v2.IReidentifyContentResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.reidentifyContent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.reidentifyContent as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes reidentifyContent with error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.ReidentifyContentRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.ReidentifyContentRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.ReidentifyContentRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.reidentifyContent = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.reidentifyContent(request), expectedError); - const actualRequest = (client.innerApiCalls.reidentifyContent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.reidentifyContent as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes reidentifyContent with closed client', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.ReidentifyContentRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.ReidentifyContentRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.ReidentifyContentRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.reidentifyContent(request), expectedError); + if (typeof process === 'object' && 'env' in process) { + describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { + it('sets apiEndpoint from environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new dlpserviceModule.v2.DlpServiceClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'dlp.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } + }); + + it('value configured in code has priority over environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new dlpserviceModule.v2.DlpServiceClient({ + universeDomain: 'configured.example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'dlp.configured.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } + }); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new dlpserviceModule.v2.DlpServiceClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); }); - describe('listInfoTypes', () => { - it('invokes listInfoTypes without error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.ListInfoTypesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListInfoTypesRequest', ['locationId']); - request.locationId = defaultValue1; - const expectedHeaderRequestParams = `location_id=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.privacy.dlp.v2.ListInfoTypesResponse() - ); - client.innerApiCalls.listInfoTypes = stubSimpleCall(expectedResponse); - const [response] = await client.listInfoTypes(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listInfoTypes as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listInfoTypes as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listInfoTypes without error using callback', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.ListInfoTypesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListInfoTypesRequest', ['locationId']); - request.locationId = defaultValue1; - const expectedHeaderRequestParams = `location_id=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.privacy.dlp.v2.ListInfoTypesResponse() - ); - client.innerApiCalls.listInfoTypes = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listInfoTypes( - request, - (err?: Error|null, result?: protos.google.privacy.dlp.v2.IListInfoTypesResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listInfoTypes as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listInfoTypes as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has port', () => { + const port = dlpserviceModule.v2.DlpServiceClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('invokes listInfoTypes with error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.ListInfoTypesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListInfoTypesRequest', ['locationId']); - request.locationId = defaultValue1; - const expectedHeaderRequestParams = `location_id=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listInfoTypes = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listInfoTypes(request), expectedError); - const actualRequest = (client.innerApiCalls.listInfoTypes as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listInfoTypes as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('should create a client with no option', () => { + const client = new dlpserviceModule.v2.DlpServiceClient(); + assert(client); + }); - it('invokes listInfoTypes with closed client', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.ListInfoTypesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListInfoTypesRequest', ['locationId']); - request.locationId = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.listInfoTypes(request), expectedError); - }); + it('should create a client with gRPC fallback', () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + fallback: true, + }); + assert(client); }); - describe('createInspectTemplate', () => { - it('invokes createInspectTemplate without error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.CreateInspectTemplateRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.CreateInspectTemplateRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.CreateInspectTemplateRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.privacy.dlp.v2.InspectTemplate() - ); - client.innerApiCalls.createInspectTemplate = stubSimpleCall(expectedResponse); - const [response] = await client.createInspectTemplate(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createInspectTemplate as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createInspectTemplate as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has initialize method and supports deferred initialization', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.dlpServiceStub, undefined); + await client.initialize(); + assert(client.dlpServiceStub); + }); - it('invokes createInspectTemplate without error using callback', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.CreateInspectTemplateRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.CreateInspectTemplateRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.CreateInspectTemplateRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.privacy.dlp.v2.InspectTemplate() - ); - client.innerApiCalls.createInspectTemplate = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createInspectTemplate( - request, - (err?: Error|null, result?: protos.google.privacy.dlp.v2.IInspectTemplate|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createInspectTemplate as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createInspectTemplate as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('has close method for the initialized client', (done) => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.dlpServiceStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes createInspectTemplate with error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.CreateInspectTemplateRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.CreateInspectTemplateRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.CreateInspectTemplateRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createInspectTemplate = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createInspectTemplate(request), expectedError); - const actualRequest = (client.innerApiCalls.createInspectTemplate as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createInspectTemplate as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('has close method for the non-initialized client', (done) => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.dlpServiceStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes createInspectTemplate with closed client', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.CreateInspectTemplateRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.CreateInspectTemplateRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.CreateInspectTemplateRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createInspectTemplate(request), expectedError); - }); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); }); - describe('updateInspectTemplate', () => { - it('invokes updateInspectTemplate without error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.UpdateInspectTemplateRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.UpdateInspectTemplateRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.privacy.dlp.v2.InspectTemplate() - ); - client.innerApiCalls.updateInspectTemplate = stubSimpleCall(expectedResponse); - const [response] = await client.updateInspectTemplate(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateInspectTemplate as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateInspectTemplate as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } + }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + }); + + describe('inspectContent', () => { + it('invokes inspectContent without error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.InspectContentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.InspectContentRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.InspectContentRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.privacy.dlp.v2.InspectContentResponse(), + ); + client.innerApiCalls.inspectContent = stubSimpleCall(expectedResponse); + const [response] = await client.inspectContent(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.inspectContent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.inspectContent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateInspectTemplate without error using callback', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.UpdateInspectTemplateRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.UpdateInspectTemplateRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.privacy.dlp.v2.InspectTemplate() - ); - client.innerApiCalls.updateInspectTemplate = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateInspectTemplate( - request, - (err?: Error|null, result?: protos.google.privacy.dlp.v2.IInspectTemplate|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateInspectTemplate as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateInspectTemplate as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes inspectContent without error using callback', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.InspectContentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.InspectContentRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.InspectContentRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.privacy.dlp.v2.InspectContentResponse(), + ); + client.innerApiCalls.inspectContent = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.inspectContent( + request, + ( + err?: Error | null, + result?: protos.google.privacy.dlp.v2.IInspectContentResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.inspectContent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.inspectContent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateInspectTemplate with error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.UpdateInspectTemplateRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.UpdateInspectTemplateRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateInspectTemplate = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateInspectTemplate(request), expectedError); - const actualRequest = (client.innerApiCalls.updateInspectTemplate as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateInspectTemplate as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes inspectContent with error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.InspectContentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.InspectContentRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.InspectContentRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.inspectContent = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.inspectContent(request), expectedError); + const actualRequest = ( + client.innerApiCalls.inspectContent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.inspectContent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateInspectTemplate with closed client', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.UpdateInspectTemplateRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.UpdateInspectTemplateRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateInspectTemplate(request), expectedError); - }); + it('invokes inspectContent with closed client', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.InspectContentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.InspectContentRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.InspectContentRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.inspectContent(request), expectedError); + }); + }); + + describe('redactImage', () => { + it('invokes redactImage without error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.RedactImageRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.RedactImageRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.RedactImageRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.privacy.dlp.v2.RedactImageResponse(), + ); + client.innerApiCalls.redactImage = stubSimpleCall(expectedResponse); + const [response] = await client.redactImage(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.redactImage as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.redactImage as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('getInspectTemplate', () => { - it('invokes getInspectTemplate without error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.GetInspectTemplateRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.GetInspectTemplateRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.privacy.dlp.v2.InspectTemplate() - ); - client.innerApiCalls.getInspectTemplate = stubSimpleCall(expectedResponse); - const [response] = await client.getInspectTemplate(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getInspectTemplate as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getInspectTemplate as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes redactImage without error using callback', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.RedactImageRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.RedactImageRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.RedactImageRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.privacy.dlp.v2.RedactImageResponse(), + ); + client.innerApiCalls.redactImage = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.redactImage( + request, + ( + err?: Error | null, + result?: protos.google.privacy.dlp.v2.IRedactImageResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.redactImage as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.redactImage as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getInspectTemplate without error using callback', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.GetInspectTemplateRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.GetInspectTemplateRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.privacy.dlp.v2.InspectTemplate() - ); - client.innerApiCalls.getInspectTemplate = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getInspectTemplate( - request, - (err?: Error|null, result?: protos.google.privacy.dlp.v2.IInspectTemplate|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getInspectTemplate as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getInspectTemplate as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes redactImage with error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.RedactImageRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.RedactImageRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.RedactImageRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.redactImage = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.redactImage(request), expectedError); + const actualRequest = ( + client.innerApiCalls.redactImage as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.redactImage as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getInspectTemplate with error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.GetInspectTemplateRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.GetInspectTemplateRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getInspectTemplate = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getInspectTemplate(request), expectedError); - const actualRequest = (client.innerApiCalls.getInspectTemplate as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getInspectTemplate as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes redactImage with closed client', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.RedactImageRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.RedactImageRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.RedactImageRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.redactImage(request), expectedError); + }); + }); + + describe('deidentifyContent', () => { + it('invokes deidentifyContent without error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.DeidentifyContentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.DeidentifyContentRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.DeidentifyContentRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.privacy.dlp.v2.DeidentifyContentResponse(), + ); + client.innerApiCalls.deidentifyContent = stubSimpleCall(expectedResponse); + const [response] = await client.deidentifyContent(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deidentifyContent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deidentifyContent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getInspectTemplate with closed client', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.GetInspectTemplateRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.GetInspectTemplateRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getInspectTemplate(request), expectedError); - }); + it('invokes deidentifyContent without error using callback', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.DeidentifyContentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.DeidentifyContentRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.DeidentifyContentRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.privacy.dlp.v2.DeidentifyContentResponse(), + ); + client.innerApiCalls.deidentifyContent = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deidentifyContent( + request, + ( + err?: Error | null, + result?: protos.google.privacy.dlp.v2.IDeidentifyContentResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deidentifyContent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deidentifyContent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('deleteInspectTemplate', () => { - it('invokes deleteInspectTemplate without error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.DeleteInspectTemplateRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.DeleteInspectTemplateRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteInspectTemplate = stubSimpleCall(expectedResponse); - const [response] = await client.deleteInspectTemplate(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteInspectTemplate as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteInspectTemplate as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deidentifyContent with error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.DeidentifyContentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.DeidentifyContentRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.DeidentifyContentRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deidentifyContent = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.deidentifyContent(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deidentifyContent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deidentifyContent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteInspectTemplate without error using callback', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.DeleteInspectTemplateRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.DeleteInspectTemplateRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteInspectTemplate = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteInspectTemplate( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteInspectTemplate as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteInspectTemplate as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deidentifyContent with closed client', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.DeidentifyContentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.DeidentifyContentRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.DeidentifyContentRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.deidentifyContent(request), expectedError); + }); + }); + + describe('reidentifyContent', () => { + it('invokes reidentifyContent without error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.ReidentifyContentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ReidentifyContentRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ReidentifyContentRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.privacy.dlp.v2.ReidentifyContentResponse(), + ); + client.innerApiCalls.reidentifyContent = stubSimpleCall(expectedResponse); + const [response] = await client.reidentifyContent(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.reidentifyContent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.reidentifyContent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteInspectTemplate with error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.DeleteInspectTemplateRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.DeleteInspectTemplateRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteInspectTemplate = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteInspectTemplate(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteInspectTemplate as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteInspectTemplate as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes reidentifyContent without error using callback', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.ReidentifyContentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ReidentifyContentRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ReidentifyContentRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.privacy.dlp.v2.ReidentifyContentResponse(), + ); + client.innerApiCalls.reidentifyContent = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.reidentifyContent( + request, + ( + err?: Error | null, + result?: protos.google.privacy.dlp.v2.IReidentifyContentResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.reidentifyContent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.reidentifyContent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteInspectTemplate with closed client', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.DeleteInspectTemplateRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.DeleteInspectTemplateRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteInspectTemplate(request), expectedError); - }); + it('invokes reidentifyContent with error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.ReidentifyContentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ReidentifyContentRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ReidentifyContentRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.reidentifyContent = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.reidentifyContent(request), expectedError); + const actualRequest = ( + client.innerApiCalls.reidentifyContent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.reidentifyContent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('createDeidentifyTemplate', () => { - it('invokes createDeidentifyTemplate without error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.CreateDeidentifyTemplateRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.CreateDeidentifyTemplateRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.CreateDeidentifyTemplateRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.privacy.dlp.v2.DeidentifyTemplate() - ); - client.innerApiCalls.createDeidentifyTemplate = stubSimpleCall(expectedResponse); - const [response] = await client.createDeidentifyTemplate(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createDeidentifyTemplate as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createDeidentifyTemplate as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes reidentifyContent with closed client', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.ReidentifyContentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ReidentifyContentRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ReidentifyContentRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.reidentifyContent(request), expectedError); + }); + }); + + describe('listInfoTypes', () => { + it('invokes listInfoTypes without error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.ListInfoTypesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListInfoTypesRequest', + ['locationId'], + ); + request.locationId = defaultValue1; + const expectedHeaderRequestParams = `location_id=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.privacy.dlp.v2.ListInfoTypesResponse(), + ); + client.innerApiCalls.listInfoTypes = stubSimpleCall(expectedResponse); + const [response] = await client.listInfoTypes(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listInfoTypes as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listInfoTypes as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createDeidentifyTemplate without error using callback', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.CreateDeidentifyTemplateRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.CreateDeidentifyTemplateRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.CreateDeidentifyTemplateRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.privacy.dlp.v2.DeidentifyTemplate() - ); - client.innerApiCalls.createDeidentifyTemplate = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createDeidentifyTemplate( - request, - (err?: Error|null, result?: protos.google.privacy.dlp.v2.IDeidentifyTemplate|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createDeidentifyTemplate as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createDeidentifyTemplate as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listInfoTypes without error using callback', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.ListInfoTypesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListInfoTypesRequest', + ['locationId'], + ); + request.locationId = defaultValue1; + const expectedHeaderRequestParams = `location_id=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.privacy.dlp.v2.ListInfoTypesResponse(), + ); + client.innerApiCalls.listInfoTypes = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listInfoTypes( + request, + ( + err?: Error | null, + result?: protos.google.privacy.dlp.v2.IListInfoTypesResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listInfoTypes as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listInfoTypes as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createDeidentifyTemplate with error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.CreateDeidentifyTemplateRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.CreateDeidentifyTemplateRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.CreateDeidentifyTemplateRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createDeidentifyTemplate = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createDeidentifyTemplate(request), expectedError); - const actualRequest = (client.innerApiCalls.createDeidentifyTemplate as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createDeidentifyTemplate as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listInfoTypes with error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.ListInfoTypesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListInfoTypesRequest', + ['locationId'], + ); + request.locationId = defaultValue1; + const expectedHeaderRequestParams = `location_id=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listInfoTypes = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listInfoTypes(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listInfoTypes as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listInfoTypes as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createDeidentifyTemplate with closed client', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.CreateDeidentifyTemplateRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.CreateDeidentifyTemplateRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.CreateDeidentifyTemplateRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createDeidentifyTemplate(request), expectedError); - }); + it('invokes listInfoTypes with closed client', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.ListInfoTypesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListInfoTypesRequest', + ['locationId'], + ); + request.locationId = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.listInfoTypes(request), expectedError); + }); + }); + + describe('createInspectTemplate', () => { + it('invokes createInspectTemplate without error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.CreateInspectTemplateRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.CreateInspectTemplateRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.CreateInspectTemplateRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.privacy.dlp.v2.InspectTemplate(), + ); + client.innerApiCalls.createInspectTemplate = + stubSimpleCall(expectedResponse); + const [response] = await client.createInspectTemplate(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createInspectTemplate as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createInspectTemplate as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('updateDeidentifyTemplate', () => { - it('invokes updateDeidentifyTemplate without error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.UpdateDeidentifyTemplateRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.UpdateDeidentifyTemplateRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.privacy.dlp.v2.DeidentifyTemplate() - ); - client.innerApiCalls.updateDeidentifyTemplate = stubSimpleCall(expectedResponse); - const [response] = await client.updateDeidentifyTemplate(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateDeidentifyTemplate as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateDeidentifyTemplate as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createInspectTemplate without error using callback', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.CreateInspectTemplateRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.CreateInspectTemplateRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.CreateInspectTemplateRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.privacy.dlp.v2.InspectTemplate(), + ); + client.innerApiCalls.createInspectTemplate = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createInspectTemplate( + request, + ( + err?: Error | null, + result?: protos.google.privacy.dlp.v2.IInspectTemplate | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createInspectTemplate as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createInspectTemplate as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateDeidentifyTemplate without error using callback', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.UpdateDeidentifyTemplateRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.UpdateDeidentifyTemplateRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.privacy.dlp.v2.DeidentifyTemplate() - ); - client.innerApiCalls.updateDeidentifyTemplate = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateDeidentifyTemplate( - request, - (err?: Error|null, result?: protos.google.privacy.dlp.v2.IDeidentifyTemplate|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateDeidentifyTemplate as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateDeidentifyTemplate as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createInspectTemplate with error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.CreateInspectTemplateRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.CreateInspectTemplateRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.CreateInspectTemplateRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createInspectTemplate = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.createInspectTemplate(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.createInspectTemplate as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createInspectTemplate as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateDeidentifyTemplate with error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.UpdateDeidentifyTemplateRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.UpdateDeidentifyTemplateRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateDeidentifyTemplate = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateDeidentifyTemplate(request), expectedError); - const actualRequest = (client.innerApiCalls.updateDeidentifyTemplate as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateDeidentifyTemplate as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createInspectTemplate with closed client', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.CreateInspectTemplateRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.CreateInspectTemplateRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.CreateInspectTemplateRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.createInspectTemplate(request), + expectedError, + ); + }); + }); + + describe('updateInspectTemplate', () => { + it('invokes updateInspectTemplate without error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.UpdateInspectTemplateRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.UpdateInspectTemplateRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.privacy.dlp.v2.InspectTemplate(), + ); + client.innerApiCalls.updateInspectTemplate = + stubSimpleCall(expectedResponse); + const [response] = await client.updateInspectTemplate(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateInspectTemplate as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateInspectTemplate as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateDeidentifyTemplate with closed client', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.UpdateDeidentifyTemplateRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.UpdateDeidentifyTemplateRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateDeidentifyTemplate(request), expectedError); - }); + it('invokes updateInspectTemplate without error using callback', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.UpdateInspectTemplateRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.UpdateInspectTemplateRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.privacy.dlp.v2.InspectTemplate(), + ); + client.innerApiCalls.updateInspectTemplate = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateInspectTemplate( + request, + ( + err?: Error | null, + result?: protos.google.privacy.dlp.v2.IInspectTemplate | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateInspectTemplate as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateInspectTemplate as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('getDeidentifyTemplate', () => { - it('invokes getDeidentifyTemplate without error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.GetDeidentifyTemplateRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.GetDeidentifyTemplateRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.privacy.dlp.v2.DeidentifyTemplate() - ); - client.innerApiCalls.getDeidentifyTemplate = stubSimpleCall(expectedResponse); - const [response] = await client.getDeidentifyTemplate(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getDeidentifyTemplate as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getDeidentifyTemplate as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateInspectTemplate with error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.UpdateInspectTemplateRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.UpdateInspectTemplateRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateInspectTemplate = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.updateInspectTemplate(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.updateInspectTemplate as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateInspectTemplate as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getDeidentifyTemplate without error using callback', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.GetDeidentifyTemplateRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.GetDeidentifyTemplateRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.privacy.dlp.v2.DeidentifyTemplate() - ); - client.innerApiCalls.getDeidentifyTemplate = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getDeidentifyTemplate( - request, - (err?: Error|null, result?: protos.google.privacy.dlp.v2.IDeidentifyTemplate|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getDeidentifyTemplate as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getDeidentifyTemplate as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateInspectTemplate with closed client', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.UpdateInspectTemplateRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.UpdateInspectTemplateRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.updateInspectTemplate(request), + expectedError, + ); + }); + }); + + describe('getInspectTemplate', () => { + it('invokes getInspectTemplate without error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.GetInspectTemplateRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.GetInspectTemplateRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.privacy.dlp.v2.InspectTemplate(), + ); + client.innerApiCalls.getInspectTemplate = + stubSimpleCall(expectedResponse); + const [response] = await client.getInspectTemplate(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getInspectTemplate as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getInspectTemplate as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getDeidentifyTemplate with error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.GetDeidentifyTemplateRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.GetDeidentifyTemplateRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getDeidentifyTemplate = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getDeidentifyTemplate(request), expectedError); - const actualRequest = (client.innerApiCalls.getDeidentifyTemplate as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getDeidentifyTemplate as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getInspectTemplate without error using callback', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.GetInspectTemplateRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.GetInspectTemplateRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.privacy.dlp.v2.InspectTemplate(), + ); + client.innerApiCalls.getInspectTemplate = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getInspectTemplate( + request, + ( + err?: Error | null, + result?: protos.google.privacy.dlp.v2.IInspectTemplate | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getInspectTemplate as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getInspectTemplate as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getDeidentifyTemplate with closed client', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.GetDeidentifyTemplateRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.GetDeidentifyTemplateRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getDeidentifyTemplate(request), expectedError); - }); + it('invokes getInspectTemplate with error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.GetInspectTemplateRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.GetInspectTemplateRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getInspectTemplate = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getInspectTemplate(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getInspectTemplate as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getInspectTemplate as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('deleteDeidentifyTemplate', () => { - it('invokes deleteDeidentifyTemplate without error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.DeleteDeidentifyTemplateRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.DeleteDeidentifyTemplateRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteDeidentifyTemplate = stubSimpleCall(expectedResponse); - const [response] = await client.deleteDeidentifyTemplate(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteDeidentifyTemplate as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteDeidentifyTemplate as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getInspectTemplate with closed client', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.GetInspectTemplateRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.GetInspectTemplateRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getInspectTemplate(request), expectedError); + }); + }); + + describe('deleteInspectTemplate', () => { + it('invokes deleteInspectTemplate without error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.DeleteInspectTemplateRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.DeleteInspectTemplateRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteInspectTemplate = + stubSimpleCall(expectedResponse); + const [response] = await client.deleteInspectTemplate(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteInspectTemplate as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteInspectTemplate as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteDeidentifyTemplate without error using callback', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.DeleteDeidentifyTemplateRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.DeleteDeidentifyTemplateRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteDeidentifyTemplate = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteDeidentifyTemplate( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteDeidentifyTemplate as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteDeidentifyTemplate as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteInspectTemplate without error using callback', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.DeleteInspectTemplateRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.DeleteInspectTemplateRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteInspectTemplate = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteInspectTemplate( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteInspectTemplate as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteInspectTemplate as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteDeidentifyTemplate with error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.DeleteDeidentifyTemplateRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.DeleteDeidentifyTemplateRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteDeidentifyTemplate = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteDeidentifyTemplate(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteDeidentifyTemplate as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteDeidentifyTemplate as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteInspectTemplate with error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.DeleteInspectTemplateRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.DeleteInspectTemplateRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteInspectTemplate = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.deleteInspectTemplate(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.deleteInspectTemplate as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteInspectTemplate as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteDeidentifyTemplate with closed client', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.DeleteDeidentifyTemplateRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.DeleteDeidentifyTemplateRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteDeidentifyTemplate(request), expectedError); - }); + it('invokes deleteInspectTemplate with closed client', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.DeleteInspectTemplateRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.DeleteInspectTemplateRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.deleteInspectTemplate(request), + expectedError, + ); + }); + }); + + describe('createDeidentifyTemplate', () => { + it('invokes createDeidentifyTemplate without error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.CreateDeidentifyTemplateRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.CreateDeidentifyTemplateRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.CreateDeidentifyTemplateRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.privacy.dlp.v2.DeidentifyTemplate(), + ); + client.innerApiCalls.createDeidentifyTemplate = + stubSimpleCall(expectedResponse); + const [response] = await client.createDeidentifyTemplate(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createDeidentifyTemplate as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createDeidentifyTemplate as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('createJobTrigger', () => { - it('invokes createJobTrigger without error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.CreateJobTriggerRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.CreateJobTriggerRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.CreateJobTriggerRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.privacy.dlp.v2.JobTrigger() - ); - client.innerApiCalls.createJobTrigger = stubSimpleCall(expectedResponse); - const [response] = await client.createJobTrigger(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createJobTrigger as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createJobTrigger as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createDeidentifyTemplate without error using callback', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.CreateDeidentifyTemplateRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.CreateDeidentifyTemplateRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.CreateDeidentifyTemplateRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.privacy.dlp.v2.DeidentifyTemplate(), + ); + client.innerApiCalls.createDeidentifyTemplate = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createDeidentifyTemplate( + request, + ( + err?: Error | null, + result?: protos.google.privacy.dlp.v2.IDeidentifyTemplate | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createDeidentifyTemplate as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createDeidentifyTemplate as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createJobTrigger without error using callback', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.CreateJobTriggerRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.CreateJobTriggerRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.CreateJobTriggerRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.privacy.dlp.v2.JobTrigger() - ); - client.innerApiCalls.createJobTrigger = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createJobTrigger( - request, - (err?: Error|null, result?: protos.google.privacy.dlp.v2.IJobTrigger|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createJobTrigger as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createJobTrigger as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createDeidentifyTemplate with error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.CreateDeidentifyTemplateRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.CreateDeidentifyTemplateRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.CreateDeidentifyTemplateRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createDeidentifyTemplate = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.createDeidentifyTemplate(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.createDeidentifyTemplate as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createDeidentifyTemplate as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createJobTrigger with error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.CreateJobTriggerRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.CreateJobTriggerRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.CreateJobTriggerRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createJobTrigger = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createJobTrigger(request), expectedError); - const actualRequest = (client.innerApiCalls.createJobTrigger as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createJobTrigger as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createDeidentifyTemplate with closed client', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.CreateDeidentifyTemplateRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.CreateDeidentifyTemplateRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.CreateDeidentifyTemplateRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.createDeidentifyTemplate(request), + expectedError, + ); + }); + }); + + describe('updateDeidentifyTemplate', () => { + it('invokes updateDeidentifyTemplate without error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.UpdateDeidentifyTemplateRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.UpdateDeidentifyTemplateRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.privacy.dlp.v2.DeidentifyTemplate(), + ); + client.innerApiCalls.updateDeidentifyTemplate = + stubSimpleCall(expectedResponse); + const [response] = await client.updateDeidentifyTemplate(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateDeidentifyTemplate as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateDeidentifyTemplate as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createJobTrigger with closed client', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.CreateJobTriggerRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.CreateJobTriggerRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.CreateJobTriggerRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createJobTrigger(request), expectedError); - }); + it('invokes updateDeidentifyTemplate without error using callback', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.UpdateDeidentifyTemplateRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.UpdateDeidentifyTemplateRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.privacy.dlp.v2.DeidentifyTemplate(), + ); + client.innerApiCalls.updateDeidentifyTemplate = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateDeidentifyTemplate( + request, + ( + err?: Error | null, + result?: protos.google.privacy.dlp.v2.IDeidentifyTemplate | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateDeidentifyTemplate as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateDeidentifyTemplate as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('updateJobTrigger', () => { - it('invokes updateJobTrigger without error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.UpdateJobTriggerRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.UpdateJobTriggerRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.privacy.dlp.v2.JobTrigger() - ); - client.innerApiCalls.updateJobTrigger = stubSimpleCall(expectedResponse); - const [response] = await client.updateJobTrigger(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateJobTrigger as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateJobTrigger as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateDeidentifyTemplate with error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.UpdateDeidentifyTemplateRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.UpdateDeidentifyTemplateRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateDeidentifyTemplate = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.updateDeidentifyTemplate(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.updateDeidentifyTemplate as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateDeidentifyTemplate as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateJobTrigger without error using callback', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.UpdateJobTriggerRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.UpdateJobTriggerRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.privacy.dlp.v2.JobTrigger() - ); - client.innerApiCalls.updateJobTrigger = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateJobTrigger( - request, - (err?: Error|null, result?: protos.google.privacy.dlp.v2.IJobTrigger|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateJobTrigger as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateJobTrigger as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateDeidentifyTemplate with closed client', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.UpdateDeidentifyTemplateRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.UpdateDeidentifyTemplateRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.updateDeidentifyTemplate(request), + expectedError, + ); + }); + }); + + describe('getDeidentifyTemplate', () => { + it('invokes getDeidentifyTemplate without error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.GetDeidentifyTemplateRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.GetDeidentifyTemplateRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.privacy.dlp.v2.DeidentifyTemplate(), + ); + client.innerApiCalls.getDeidentifyTemplate = + stubSimpleCall(expectedResponse); + const [response] = await client.getDeidentifyTemplate(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getDeidentifyTemplate as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getDeidentifyTemplate as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateJobTrigger with error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.UpdateJobTriggerRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.UpdateJobTriggerRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateJobTrigger = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateJobTrigger(request), expectedError); - const actualRequest = (client.innerApiCalls.updateJobTrigger as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateJobTrigger as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getDeidentifyTemplate without error using callback', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.GetDeidentifyTemplateRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.GetDeidentifyTemplateRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.privacy.dlp.v2.DeidentifyTemplate(), + ); + client.innerApiCalls.getDeidentifyTemplate = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getDeidentifyTemplate( + request, + ( + err?: Error | null, + result?: protos.google.privacy.dlp.v2.IDeidentifyTemplate | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getDeidentifyTemplate as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getDeidentifyTemplate as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateJobTrigger with closed client', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.UpdateJobTriggerRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.UpdateJobTriggerRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateJobTrigger(request), expectedError); - }); + it('invokes getDeidentifyTemplate with error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.GetDeidentifyTemplateRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.GetDeidentifyTemplateRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getDeidentifyTemplate = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.getDeidentifyTemplate(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.getDeidentifyTemplate as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getDeidentifyTemplate as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('getJobTrigger', () => { - it('invokes getJobTrigger without error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.GetJobTriggerRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.GetJobTriggerRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.privacy.dlp.v2.JobTrigger() - ); - client.innerApiCalls.getJobTrigger = stubSimpleCall(expectedResponse); - const [response] = await client.getJobTrigger(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getJobTrigger as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getJobTrigger as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getDeidentifyTemplate with closed client', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.GetDeidentifyTemplateRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.GetDeidentifyTemplateRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.getDeidentifyTemplate(request), + expectedError, + ); + }); + }); + + describe('deleteDeidentifyTemplate', () => { + it('invokes deleteDeidentifyTemplate without error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.DeleteDeidentifyTemplateRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.DeleteDeidentifyTemplateRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteDeidentifyTemplate = + stubSimpleCall(expectedResponse); + const [response] = await client.deleteDeidentifyTemplate(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteDeidentifyTemplate as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteDeidentifyTemplate as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getJobTrigger without error using callback', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.GetJobTriggerRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.GetJobTriggerRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.privacy.dlp.v2.JobTrigger() - ); - client.innerApiCalls.getJobTrigger = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getJobTrigger( - request, - (err?: Error|null, result?: protos.google.privacy.dlp.v2.IJobTrigger|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getJobTrigger as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getJobTrigger as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteDeidentifyTemplate without error using callback', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.DeleteDeidentifyTemplateRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.DeleteDeidentifyTemplateRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteDeidentifyTemplate = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteDeidentifyTemplate( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteDeidentifyTemplate as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteDeidentifyTemplate as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getJobTrigger with error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.GetJobTriggerRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.GetJobTriggerRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getJobTrigger = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getJobTrigger(request), expectedError); - const actualRequest = (client.innerApiCalls.getJobTrigger as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getJobTrigger as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteDeidentifyTemplate with error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.DeleteDeidentifyTemplateRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.DeleteDeidentifyTemplateRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteDeidentifyTemplate = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.deleteDeidentifyTemplate(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.deleteDeidentifyTemplate as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteDeidentifyTemplate as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getJobTrigger with closed client', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.GetJobTriggerRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.GetJobTriggerRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getJobTrigger(request), expectedError); - }); + it('invokes deleteDeidentifyTemplate with closed client', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.DeleteDeidentifyTemplateRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.DeleteDeidentifyTemplateRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.deleteDeidentifyTemplate(request), + expectedError, + ); + }); + }); + + describe('createJobTrigger', () => { + it('invokes createJobTrigger without error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.CreateJobTriggerRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.CreateJobTriggerRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.CreateJobTriggerRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.privacy.dlp.v2.JobTrigger(), + ); + client.innerApiCalls.createJobTrigger = stubSimpleCall(expectedResponse); + const [response] = await client.createJobTrigger(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createJobTrigger as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createJobTrigger as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('deleteJobTrigger', () => { - it('invokes deleteJobTrigger without error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.DeleteJobTriggerRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.DeleteJobTriggerRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteJobTrigger = stubSimpleCall(expectedResponse); - const [response] = await client.deleteJobTrigger(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteJobTrigger as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteJobTrigger as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createJobTrigger without error using callback', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.CreateJobTriggerRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.CreateJobTriggerRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.CreateJobTriggerRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.privacy.dlp.v2.JobTrigger(), + ); + client.innerApiCalls.createJobTrigger = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createJobTrigger( + request, + ( + err?: Error | null, + result?: protos.google.privacy.dlp.v2.IJobTrigger | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createJobTrigger as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createJobTrigger as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteJobTrigger without error using callback', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.DeleteJobTriggerRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.DeleteJobTriggerRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteJobTrigger = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteJobTrigger( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteJobTrigger as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteJobTrigger as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createJobTrigger with error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.CreateJobTriggerRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.CreateJobTriggerRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.CreateJobTriggerRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createJobTrigger = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.createJobTrigger(request), expectedError); + const actualRequest = ( + client.innerApiCalls.createJobTrigger as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createJobTrigger as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteJobTrigger with error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.DeleteJobTriggerRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.DeleteJobTriggerRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteJobTrigger = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteJobTrigger(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteJobTrigger as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteJobTrigger as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createJobTrigger with closed client', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.CreateJobTriggerRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.CreateJobTriggerRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.CreateJobTriggerRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.createJobTrigger(request), expectedError); + }); + }); + + describe('updateJobTrigger', () => { + it('invokes updateJobTrigger without error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.UpdateJobTriggerRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.UpdateJobTriggerRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.privacy.dlp.v2.JobTrigger(), + ); + client.innerApiCalls.updateJobTrigger = stubSimpleCall(expectedResponse); + const [response] = await client.updateJobTrigger(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateJobTrigger as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateJobTrigger as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteJobTrigger with closed client', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.DeleteJobTriggerRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.DeleteJobTriggerRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteJobTrigger(request), expectedError); - }); + it('invokes updateJobTrigger without error using callback', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.UpdateJobTriggerRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.UpdateJobTriggerRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.privacy.dlp.v2.JobTrigger(), + ); + client.innerApiCalls.updateJobTrigger = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateJobTrigger( + request, + ( + err?: Error | null, + result?: protos.google.privacy.dlp.v2.IJobTrigger | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateJobTrigger as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateJobTrigger as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('activateJobTrigger', () => { - it('invokes activateJobTrigger without error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.ActivateJobTriggerRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.ActivateJobTriggerRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.privacy.dlp.v2.DlpJob() - ); - client.innerApiCalls.activateJobTrigger = stubSimpleCall(expectedResponse); - const [response] = await client.activateJobTrigger(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.activateJobTrigger as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.activateJobTrigger as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateJobTrigger with error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.UpdateJobTriggerRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.UpdateJobTriggerRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateJobTrigger = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.updateJobTrigger(request), expectedError); + const actualRequest = ( + client.innerApiCalls.updateJobTrigger as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateJobTrigger as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes activateJobTrigger without error using callback', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.ActivateJobTriggerRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.ActivateJobTriggerRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.privacy.dlp.v2.DlpJob() - ); - client.innerApiCalls.activateJobTrigger = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.activateJobTrigger( - request, - (err?: Error|null, result?: protos.google.privacy.dlp.v2.IDlpJob|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.activateJobTrigger as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.activateJobTrigger as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateJobTrigger with closed client', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.UpdateJobTriggerRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.UpdateJobTriggerRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.updateJobTrigger(request), expectedError); + }); + }); + + describe('getJobTrigger', () => { + it('invokes getJobTrigger without error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.GetJobTriggerRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.GetJobTriggerRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.privacy.dlp.v2.JobTrigger(), + ); + client.innerApiCalls.getJobTrigger = stubSimpleCall(expectedResponse); + const [response] = await client.getJobTrigger(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getJobTrigger as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getJobTrigger as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes activateJobTrigger with error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.ActivateJobTriggerRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.ActivateJobTriggerRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.activateJobTrigger = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.activateJobTrigger(request), expectedError); - const actualRequest = (client.innerApiCalls.activateJobTrigger as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.activateJobTrigger as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getJobTrigger without error using callback', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.GetJobTriggerRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.GetJobTriggerRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.privacy.dlp.v2.JobTrigger(), + ); + client.innerApiCalls.getJobTrigger = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getJobTrigger( + request, + ( + err?: Error | null, + result?: protos.google.privacy.dlp.v2.IJobTrigger | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getJobTrigger as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getJobTrigger as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes activateJobTrigger with closed client', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.ActivateJobTriggerRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.ActivateJobTriggerRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.activateJobTrigger(request), expectedError); - }); + it('invokes getJobTrigger with error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.GetJobTriggerRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.GetJobTriggerRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getJobTrigger = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getJobTrigger(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getJobTrigger as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getJobTrigger as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('createDlpJob', () => { - it('invokes createDlpJob without error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.CreateDlpJobRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.CreateDlpJobRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.CreateDlpJobRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.privacy.dlp.v2.DlpJob() - ); - client.innerApiCalls.createDlpJob = stubSimpleCall(expectedResponse); - const [response] = await client.createDlpJob(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createDlpJob as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createDlpJob as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getJobTrigger with closed client', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.GetJobTriggerRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.GetJobTriggerRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getJobTrigger(request), expectedError); + }); + }); + + describe('deleteJobTrigger', () => { + it('invokes deleteJobTrigger without error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.DeleteJobTriggerRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.DeleteJobTriggerRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteJobTrigger = stubSimpleCall(expectedResponse); + const [response] = await client.deleteJobTrigger(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteJobTrigger as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteJobTrigger as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createDlpJob without error using callback', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.CreateDlpJobRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.CreateDlpJobRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.CreateDlpJobRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.privacy.dlp.v2.DlpJob() - ); - client.innerApiCalls.createDlpJob = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createDlpJob( - request, - (err?: Error|null, result?: protos.google.privacy.dlp.v2.IDlpJob|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createDlpJob as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createDlpJob as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteJobTrigger without error using callback', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.DeleteJobTriggerRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.DeleteJobTriggerRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteJobTrigger = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteJobTrigger( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteJobTrigger as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteJobTrigger as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createDlpJob with error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.CreateDlpJobRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.CreateDlpJobRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.CreateDlpJobRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createDlpJob = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createDlpJob(request), expectedError); - const actualRequest = (client.innerApiCalls.createDlpJob as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createDlpJob as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteJobTrigger with error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.DeleteJobTriggerRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.DeleteJobTriggerRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteJobTrigger = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.deleteJobTrigger(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteJobTrigger as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteJobTrigger as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createDlpJob with closed client', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.CreateDlpJobRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.CreateDlpJobRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.CreateDlpJobRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createDlpJob(request), expectedError); - }); + it('invokes deleteJobTrigger with closed client', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.DeleteJobTriggerRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.DeleteJobTriggerRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.deleteJobTrigger(request), expectedError); + }); + }); + + describe('activateJobTrigger', () => { + it('invokes activateJobTrigger without error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.ActivateJobTriggerRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ActivateJobTriggerRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.privacy.dlp.v2.DlpJob(), + ); + client.innerApiCalls.activateJobTrigger = + stubSimpleCall(expectedResponse); + const [response] = await client.activateJobTrigger(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.activateJobTrigger as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.activateJobTrigger as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('getDlpJob', () => { - it('invokes getDlpJob without error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.GetDlpJobRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.GetDlpJobRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.privacy.dlp.v2.DlpJob() - ); - client.innerApiCalls.getDlpJob = stubSimpleCall(expectedResponse); - const [response] = await client.getDlpJob(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getDlpJob as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getDlpJob as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes activateJobTrigger without error using callback', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.ActivateJobTriggerRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ActivateJobTriggerRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.privacy.dlp.v2.DlpJob(), + ); + client.innerApiCalls.activateJobTrigger = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.activateJobTrigger( + request, + ( + err?: Error | null, + result?: protos.google.privacy.dlp.v2.IDlpJob | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.activateJobTrigger as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.activateJobTrigger as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getDlpJob without error using callback', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.GetDlpJobRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.GetDlpJobRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.privacy.dlp.v2.DlpJob() - ); - client.innerApiCalls.getDlpJob = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getDlpJob( - request, - (err?: Error|null, result?: protos.google.privacy.dlp.v2.IDlpJob|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getDlpJob as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getDlpJob as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes activateJobTrigger with error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.ActivateJobTriggerRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ActivateJobTriggerRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.activateJobTrigger = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.activateJobTrigger(request), expectedError); + const actualRequest = ( + client.innerApiCalls.activateJobTrigger as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.activateJobTrigger as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getDlpJob with error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.GetDlpJobRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.GetDlpJobRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getDlpJob = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getDlpJob(request), expectedError); - const actualRequest = (client.innerApiCalls.getDlpJob as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getDlpJob as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes activateJobTrigger with closed client', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.ActivateJobTriggerRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ActivateJobTriggerRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.activateJobTrigger(request), expectedError); + }); + }); + + describe('createDlpJob', () => { + it('invokes createDlpJob without error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.CreateDlpJobRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.CreateDlpJobRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.CreateDlpJobRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.privacy.dlp.v2.DlpJob(), + ); + client.innerApiCalls.createDlpJob = stubSimpleCall(expectedResponse); + const [response] = await client.createDlpJob(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createDlpJob as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createDlpJob as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getDlpJob with closed client', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.GetDlpJobRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.GetDlpJobRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getDlpJob(request), expectedError); - }); + it('invokes createDlpJob without error using callback', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.CreateDlpJobRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.CreateDlpJobRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.CreateDlpJobRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.privacy.dlp.v2.DlpJob(), + ); + client.innerApiCalls.createDlpJob = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createDlpJob( + request, + ( + err?: Error | null, + result?: protos.google.privacy.dlp.v2.IDlpJob | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createDlpJob as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createDlpJob as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('deleteDlpJob', () => { - it('invokes deleteDlpJob without error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.DeleteDlpJobRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.DeleteDlpJobRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteDlpJob = stubSimpleCall(expectedResponse); - const [response] = await client.deleteDlpJob(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteDlpJob as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteDlpJob as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createDlpJob with error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.CreateDlpJobRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.CreateDlpJobRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.CreateDlpJobRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createDlpJob = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.createDlpJob(request), expectedError); + const actualRequest = ( + client.innerApiCalls.createDlpJob as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createDlpJob as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteDlpJob without error using callback', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.DeleteDlpJobRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.DeleteDlpJobRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteDlpJob = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteDlpJob( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteDlpJob as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteDlpJob as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createDlpJob with closed client', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.CreateDlpJobRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.CreateDlpJobRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.CreateDlpJobRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.createDlpJob(request), expectedError); + }); + }); + + describe('getDlpJob', () => { + it('invokes getDlpJob without error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.GetDlpJobRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.GetDlpJobRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.privacy.dlp.v2.DlpJob(), + ); + client.innerApiCalls.getDlpJob = stubSimpleCall(expectedResponse); + const [response] = await client.getDlpJob(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getDlpJob as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getDlpJob as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteDlpJob with error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.DeleteDlpJobRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.DeleteDlpJobRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteDlpJob = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteDlpJob(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteDlpJob as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteDlpJob as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getDlpJob without error using callback', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.GetDlpJobRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.GetDlpJobRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.privacy.dlp.v2.DlpJob(), + ); + client.innerApiCalls.getDlpJob = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getDlpJob( + request, + ( + err?: Error | null, + result?: protos.google.privacy.dlp.v2.IDlpJob | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getDlpJob as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getDlpJob as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteDlpJob with closed client', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.DeleteDlpJobRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.DeleteDlpJobRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteDlpJob(request), expectedError); - }); + it('invokes getDlpJob with error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.GetDlpJobRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.GetDlpJobRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getDlpJob = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.getDlpJob(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getDlpJob as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getDlpJob as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('cancelDlpJob', () => { - it('invokes cancelDlpJob without error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.CancelDlpJobRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.CancelDlpJobRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.cancelDlpJob = stubSimpleCall(expectedResponse); - const [response] = await client.cancelDlpJob(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.cancelDlpJob as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.cancelDlpJob as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getDlpJob with closed client', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.GetDlpJobRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.GetDlpJobRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getDlpJob(request), expectedError); + }); + }); + + describe('deleteDlpJob', () => { + it('invokes deleteDlpJob without error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.DeleteDlpJobRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.DeleteDlpJobRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteDlpJob = stubSimpleCall(expectedResponse); + const [response] = await client.deleteDlpJob(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteDlpJob as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteDlpJob as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes cancelDlpJob without error using callback', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.CancelDlpJobRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.CancelDlpJobRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.cancelDlpJob = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.cancelDlpJob( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.cancelDlpJob as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.cancelDlpJob as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteDlpJob without error using callback', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.DeleteDlpJobRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.DeleteDlpJobRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteDlpJob = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteDlpJob( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteDlpJob as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteDlpJob as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes cancelDlpJob with error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.CancelDlpJobRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.CancelDlpJobRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.cancelDlpJob = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.cancelDlpJob(request), expectedError); - const actualRequest = (client.innerApiCalls.cancelDlpJob as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.cancelDlpJob as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteDlpJob with error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.DeleteDlpJobRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.DeleteDlpJobRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteDlpJob = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.deleteDlpJob(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteDlpJob as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteDlpJob as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes cancelDlpJob with closed client', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.CancelDlpJobRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.CancelDlpJobRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.cancelDlpJob(request), expectedError); - }); + it('invokes deleteDlpJob with closed client', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.DeleteDlpJobRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.DeleteDlpJobRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.deleteDlpJob(request), expectedError); + }); + }); + + describe('cancelDlpJob', () => { + it('invokes cancelDlpJob without error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.CancelDlpJobRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.CancelDlpJobRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.cancelDlpJob = stubSimpleCall(expectedResponse); + const [response] = await client.cancelDlpJob(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.cancelDlpJob as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.cancelDlpJob as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('createStoredInfoType', () => { - it('invokes createStoredInfoType without error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.CreateStoredInfoTypeRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.CreateStoredInfoTypeRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.CreateStoredInfoTypeRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.privacy.dlp.v2.StoredInfoType() - ); - client.innerApiCalls.createStoredInfoType = stubSimpleCall(expectedResponse); - const [response] = await client.createStoredInfoType(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createStoredInfoType as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createStoredInfoType as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes cancelDlpJob without error using callback', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.CancelDlpJobRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.CancelDlpJobRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.cancelDlpJob = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.cancelDlpJob( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.cancelDlpJob as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.cancelDlpJob as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createStoredInfoType without error using callback', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.CreateStoredInfoTypeRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.CreateStoredInfoTypeRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.CreateStoredInfoTypeRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.privacy.dlp.v2.StoredInfoType() - ); - client.innerApiCalls.createStoredInfoType = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createStoredInfoType( - request, - (err?: Error|null, result?: protos.google.privacy.dlp.v2.IStoredInfoType|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createStoredInfoType as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createStoredInfoType as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes cancelDlpJob with error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.CancelDlpJobRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.CancelDlpJobRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.cancelDlpJob = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.cancelDlpJob(request), expectedError); + const actualRequest = ( + client.innerApiCalls.cancelDlpJob as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.cancelDlpJob as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createStoredInfoType with error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.CreateStoredInfoTypeRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.CreateStoredInfoTypeRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.CreateStoredInfoTypeRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createStoredInfoType = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createStoredInfoType(request), expectedError); - const actualRequest = (client.innerApiCalls.createStoredInfoType as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createStoredInfoType as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes cancelDlpJob with closed client', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.CancelDlpJobRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.CancelDlpJobRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.cancelDlpJob(request), expectedError); + }); + }); + + describe('createStoredInfoType', () => { + it('invokes createStoredInfoType without error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.CreateStoredInfoTypeRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.CreateStoredInfoTypeRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.CreateStoredInfoTypeRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.privacy.dlp.v2.StoredInfoType(), + ); + client.innerApiCalls.createStoredInfoType = + stubSimpleCall(expectedResponse); + const [response] = await client.createStoredInfoType(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createStoredInfoType as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createStoredInfoType as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createStoredInfoType with closed client', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.CreateStoredInfoTypeRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.CreateStoredInfoTypeRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.CreateStoredInfoTypeRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createStoredInfoType(request), expectedError); - }); + it('invokes createStoredInfoType without error using callback', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.CreateStoredInfoTypeRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.CreateStoredInfoTypeRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.CreateStoredInfoTypeRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.privacy.dlp.v2.StoredInfoType(), + ); + client.innerApiCalls.createStoredInfoType = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createStoredInfoType( + request, + ( + err?: Error | null, + result?: protos.google.privacy.dlp.v2.IStoredInfoType | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createStoredInfoType as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createStoredInfoType as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('updateStoredInfoType', () => { - it('invokes updateStoredInfoType without error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.UpdateStoredInfoTypeRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.UpdateStoredInfoTypeRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.privacy.dlp.v2.StoredInfoType() - ); - client.innerApiCalls.updateStoredInfoType = stubSimpleCall(expectedResponse); - const [response] = await client.updateStoredInfoType(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateStoredInfoType as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateStoredInfoType as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createStoredInfoType with error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.CreateStoredInfoTypeRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.CreateStoredInfoTypeRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.CreateStoredInfoTypeRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createStoredInfoType = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.createStoredInfoType(request), expectedError); + const actualRequest = ( + client.innerApiCalls.createStoredInfoType as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createStoredInfoType as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateStoredInfoType without error using callback', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.UpdateStoredInfoTypeRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.UpdateStoredInfoTypeRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.privacy.dlp.v2.StoredInfoType() - ); - client.innerApiCalls.updateStoredInfoType = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateStoredInfoType( - request, - (err?: Error|null, result?: protos.google.privacy.dlp.v2.IStoredInfoType|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateStoredInfoType as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateStoredInfoType as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createStoredInfoType with closed client', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.CreateStoredInfoTypeRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.CreateStoredInfoTypeRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.CreateStoredInfoTypeRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.createStoredInfoType(request), expectedError); + }); + }); + + describe('updateStoredInfoType', () => { + it('invokes updateStoredInfoType without error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.UpdateStoredInfoTypeRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.UpdateStoredInfoTypeRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.privacy.dlp.v2.StoredInfoType(), + ); + client.innerApiCalls.updateStoredInfoType = + stubSimpleCall(expectedResponse); + const [response] = await client.updateStoredInfoType(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateStoredInfoType as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateStoredInfoType as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateStoredInfoType with error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.UpdateStoredInfoTypeRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.UpdateStoredInfoTypeRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateStoredInfoType = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateStoredInfoType(request), expectedError); - const actualRequest = (client.innerApiCalls.updateStoredInfoType as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateStoredInfoType as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateStoredInfoType without error using callback', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.UpdateStoredInfoTypeRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.UpdateStoredInfoTypeRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.privacy.dlp.v2.StoredInfoType(), + ); + client.innerApiCalls.updateStoredInfoType = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateStoredInfoType( + request, + ( + err?: Error | null, + result?: protos.google.privacy.dlp.v2.IStoredInfoType | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateStoredInfoType as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateStoredInfoType as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateStoredInfoType with closed client', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.UpdateStoredInfoTypeRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.UpdateStoredInfoTypeRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateStoredInfoType(request), expectedError); - }); + it('invokes updateStoredInfoType with error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.UpdateStoredInfoTypeRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.UpdateStoredInfoTypeRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateStoredInfoType = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.updateStoredInfoType(request), expectedError); + const actualRequest = ( + client.innerApiCalls.updateStoredInfoType as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateStoredInfoType as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('getStoredInfoType', () => { - it('invokes getStoredInfoType without error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.GetStoredInfoTypeRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.GetStoredInfoTypeRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.privacy.dlp.v2.StoredInfoType() - ); - client.innerApiCalls.getStoredInfoType = stubSimpleCall(expectedResponse); - const [response] = await client.getStoredInfoType(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getStoredInfoType as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getStoredInfoType as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateStoredInfoType with closed client', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.UpdateStoredInfoTypeRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.UpdateStoredInfoTypeRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.updateStoredInfoType(request), expectedError); + }); + }); + + describe('getStoredInfoType', () => { + it('invokes getStoredInfoType without error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.GetStoredInfoTypeRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.GetStoredInfoTypeRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.privacy.dlp.v2.StoredInfoType(), + ); + client.innerApiCalls.getStoredInfoType = stubSimpleCall(expectedResponse); + const [response] = await client.getStoredInfoType(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getStoredInfoType as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getStoredInfoType as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getStoredInfoType without error using callback', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.GetStoredInfoTypeRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.GetStoredInfoTypeRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.privacy.dlp.v2.StoredInfoType() - ); - client.innerApiCalls.getStoredInfoType = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getStoredInfoType( - request, - (err?: Error|null, result?: protos.google.privacy.dlp.v2.IStoredInfoType|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getStoredInfoType as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getStoredInfoType as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getStoredInfoType without error using callback', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.GetStoredInfoTypeRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.GetStoredInfoTypeRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.privacy.dlp.v2.StoredInfoType(), + ); + client.innerApiCalls.getStoredInfoType = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getStoredInfoType( + request, + ( + err?: Error | null, + result?: protos.google.privacy.dlp.v2.IStoredInfoType | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getStoredInfoType as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getStoredInfoType as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getStoredInfoType with error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.GetStoredInfoTypeRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.GetStoredInfoTypeRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getStoredInfoType = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getStoredInfoType(request), expectedError); - const actualRequest = (client.innerApiCalls.getStoredInfoType as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getStoredInfoType as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getStoredInfoType with error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.GetStoredInfoTypeRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.GetStoredInfoTypeRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getStoredInfoType = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getStoredInfoType(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getStoredInfoType as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getStoredInfoType as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getStoredInfoType with closed client', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.GetStoredInfoTypeRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.GetStoredInfoTypeRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getStoredInfoType(request), expectedError); - }); + it('invokes getStoredInfoType with closed client', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.GetStoredInfoTypeRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.GetStoredInfoTypeRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getStoredInfoType(request), expectedError); + }); + }); + + describe('deleteStoredInfoType', () => { + it('invokes deleteStoredInfoType without error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.DeleteStoredInfoTypeRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.DeleteStoredInfoTypeRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteStoredInfoType = + stubSimpleCall(expectedResponse); + const [response] = await client.deleteStoredInfoType(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteStoredInfoType as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteStoredInfoType as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('deleteStoredInfoType', () => { - it('invokes deleteStoredInfoType without error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.DeleteStoredInfoTypeRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.DeleteStoredInfoTypeRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteStoredInfoType = stubSimpleCall(expectedResponse); - const [response] = await client.deleteStoredInfoType(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteStoredInfoType as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteStoredInfoType as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteStoredInfoType without error using callback', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.DeleteStoredInfoTypeRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.DeleteStoredInfoTypeRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteStoredInfoType = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteStoredInfoType( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteStoredInfoType as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteStoredInfoType as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteStoredInfoType without error using callback', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.DeleteStoredInfoTypeRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.DeleteStoredInfoTypeRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteStoredInfoType = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteStoredInfoType( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteStoredInfoType as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteStoredInfoType as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteStoredInfoType with error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.DeleteStoredInfoTypeRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.DeleteStoredInfoTypeRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteStoredInfoType = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.deleteStoredInfoType(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteStoredInfoType as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteStoredInfoType as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteStoredInfoType with error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.DeleteStoredInfoTypeRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.DeleteStoredInfoTypeRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteStoredInfoType = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteStoredInfoType(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteStoredInfoType as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteStoredInfoType as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteStoredInfoType with closed client', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.DeleteStoredInfoTypeRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.DeleteStoredInfoTypeRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.deleteStoredInfoType(request), expectedError); + }); + }); + + describe('listInspectTemplates', () => { + it('invokes listInspectTemplates without error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.ListInspectTemplatesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListInspectTemplatesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListInspectTemplatesRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.privacy.dlp.v2.InspectTemplate(), + ), + generateSampleMessage( + new protos.google.privacy.dlp.v2.InspectTemplate(), + ), + generateSampleMessage( + new protos.google.privacy.dlp.v2.InspectTemplate(), + ), + ]; + client.innerApiCalls.listInspectTemplates = + stubSimpleCall(expectedResponse); + const [response] = await client.listInspectTemplates(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listInspectTemplates as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listInspectTemplates as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteStoredInfoType with closed client', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.DeleteStoredInfoTypeRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.DeleteStoredInfoTypeRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteStoredInfoType(request), expectedError); - }); + it('invokes listInspectTemplates without error using callback', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.ListInspectTemplatesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListInspectTemplatesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListInspectTemplatesRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.privacy.dlp.v2.InspectTemplate(), + ), + generateSampleMessage( + new protos.google.privacy.dlp.v2.InspectTemplate(), + ), + generateSampleMessage( + new protos.google.privacy.dlp.v2.InspectTemplate(), + ), + ]; + client.innerApiCalls.listInspectTemplates = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listInspectTemplates( + request, + ( + err?: Error | null, + result?: protos.google.privacy.dlp.v2.IInspectTemplate[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listInspectTemplates as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listInspectTemplates as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('listInspectTemplates', () => { - it('invokes listInspectTemplates without error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.ListInspectTemplatesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListInspectTemplatesRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListInspectTemplatesRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.privacy.dlp.v2.InspectTemplate()), - generateSampleMessage(new protos.google.privacy.dlp.v2.InspectTemplate()), - generateSampleMessage(new protos.google.privacy.dlp.v2.InspectTemplate()), - ]; - client.innerApiCalls.listInspectTemplates = stubSimpleCall(expectedResponse); - const [response] = await client.listInspectTemplates(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listInspectTemplates as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listInspectTemplates as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listInspectTemplates with error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.ListInspectTemplatesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListInspectTemplatesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListInspectTemplatesRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listInspectTemplates = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listInspectTemplates(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listInspectTemplates as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listInspectTemplates as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listInspectTemplates without error using callback', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.ListInspectTemplatesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListInspectTemplatesRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListInspectTemplatesRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.privacy.dlp.v2.InspectTemplate()), - generateSampleMessage(new protos.google.privacy.dlp.v2.InspectTemplate()), - generateSampleMessage(new protos.google.privacy.dlp.v2.InspectTemplate()), - ]; - client.innerApiCalls.listInspectTemplates = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listInspectTemplates( - request, - (err?: Error|null, result?: protos.google.privacy.dlp.v2.IInspectTemplate[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listInspectTemplates as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listInspectTemplates as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listInspectTemplatesStream without error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.ListInspectTemplatesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListInspectTemplatesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListInspectTemplatesRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.privacy.dlp.v2.InspectTemplate(), + ), + generateSampleMessage( + new protos.google.privacy.dlp.v2.InspectTemplate(), + ), + generateSampleMessage( + new protos.google.privacy.dlp.v2.InspectTemplate(), + ), + ]; + client.descriptors.page.listInspectTemplates.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listInspectTemplatesStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.privacy.dlp.v2.InspectTemplate[] = []; + stream.on( + 'data', + (response: protos.google.privacy.dlp.v2.InspectTemplate) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listInspectTemplates.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listInspectTemplates, request), + ); + assert( + (client.descriptors.page.listInspectTemplates.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('invokes listInspectTemplates with error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.ListInspectTemplatesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListInspectTemplatesRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListInspectTemplatesRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listInspectTemplates = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listInspectTemplates(request), expectedError); - const actualRequest = (client.innerApiCalls.listInspectTemplates as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listInspectTemplates as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listInspectTemplatesStream with error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.ListInspectTemplatesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListInspectTemplatesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListInspectTemplatesRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listInspectTemplates.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listInspectTemplatesStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.privacy.dlp.v2.InspectTemplate[] = []; + stream.on( + 'data', + (response: protos.google.privacy.dlp.v2.InspectTemplate) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listInspectTemplates.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listInspectTemplates, request), + ); + assert( + (client.descriptors.page.listInspectTemplates.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('invokes listInspectTemplatesStream without error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.ListInspectTemplatesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListInspectTemplatesRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListInspectTemplatesRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.privacy.dlp.v2.InspectTemplate()), - generateSampleMessage(new protos.google.privacy.dlp.v2.InspectTemplate()), - generateSampleMessage(new protos.google.privacy.dlp.v2.InspectTemplate()), - ]; - client.descriptors.page.listInspectTemplates.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listInspectTemplatesStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.privacy.dlp.v2.InspectTemplate[] = []; - stream.on('data', (response: protos.google.privacy.dlp.v2.InspectTemplate) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.listInspectTemplates.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listInspectTemplates, request)); - assert( - (client.descriptors.page.listInspectTemplates.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listInspectTemplates without error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.ListInspectTemplatesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListInspectTemplatesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListInspectTemplatesRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.privacy.dlp.v2.InspectTemplate(), + ), + generateSampleMessage( + new protos.google.privacy.dlp.v2.InspectTemplate(), + ), + generateSampleMessage( + new protos.google.privacy.dlp.v2.InspectTemplate(), + ), + ]; + client.descriptors.page.listInspectTemplates.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.privacy.dlp.v2.IInspectTemplate[] = []; + const iterable = client.listInspectTemplatesAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listInspectTemplates.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listInspectTemplates.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('invokes listInspectTemplatesStream with error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.ListInspectTemplatesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListInspectTemplatesRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListInspectTemplatesRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listInspectTemplates.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listInspectTemplatesStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.privacy.dlp.v2.InspectTemplate[] = []; - stream.on('data', (response: protos.google.privacy.dlp.v2.InspectTemplate) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listInspectTemplates.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listInspectTemplates, request)); - assert( - (client.descriptors.page.listInspectTemplates.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listInspectTemplates with error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.ListInspectTemplatesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListInspectTemplatesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListInspectTemplatesRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listInspectTemplates.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listInspectTemplatesAsync(request); + await assert.rejects(async () => { + const responses: protos.google.privacy.dlp.v2.IInspectTemplate[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listInspectTemplates.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listInspectTemplates.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + }); + + describe('listDeidentifyTemplates', () => { + it('invokes listDeidentifyTemplates without error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.ListDeidentifyTemplatesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListDeidentifyTemplatesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListDeidentifyTemplatesRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.privacy.dlp.v2.DeidentifyTemplate(), + ), + generateSampleMessage( + new protos.google.privacy.dlp.v2.DeidentifyTemplate(), + ), + generateSampleMessage( + new protos.google.privacy.dlp.v2.DeidentifyTemplate(), + ), + ]; + client.innerApiCalls.listDeidentifyTemplates = + stubSimpleCall(expectedResponse); + const [response] = await client.listDeidentifyTemplates(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listDeidentifyTemplates as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listDeidentifyTemplates as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('uses async iteration with listInspectTemplates without error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.ListInspectTemplatesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListInspectTemplatesRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListInspectTemplatesRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.privacy.dlp.v2.InspectTemplate()), - generateSampleMessage(new protos.google.privacy.dlp.v2.InspectTemplate()), - generateSampleMessage(new protos.google.privacy.dlp.v2.InspectTemplate()), - ]; - client.descriptors.page.listInspectTemplates.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.privacy.dlp.v2.IInspectTemplate[] = []; - const iterable = client.listInspectTemplatesAsync(request); - for await (const resource of iterable) { - responses.push(resource!); + it('invokes listDeidentifyTemplates without error using callback', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.ListDeidentifyTemplatesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListDeidentifyTemplatesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListDeidentifyTemplatesRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.privacy.dlp.v2.DeidentifyTemplate(), + ), + generateSampleMessage( + new protos.google.privacy.dlp.v2.DeidentifyTemplate(), + ), + generateSampleMessage( + new protos.google.privacy.dlp.v2.DeidentifyTemplate(), + ), + ]; + client.innerApiCalls.listDeidentifyTemplates = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listDeidentifyTemplates( + request, + ( + err?: Error | null, + result?: protos.google.privacy.dlp.v2.IDeidentifyTemplate[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listInspectTemplates.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listInspectTemplates.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); - - it('uses async iteration with listInspectTemplates with error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.ListInspectTemplatesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListInspectTemplatesRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListInspectTemplatesRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listInspectTemplates.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listInspectTemplatesAsync(request); - await assert.rejects(async () => { - const responses: protos.google.privacy.dlp.v2.IInspectTemplate[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listInspectTemplates.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listInspectTemplates.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listDeidentifyTemplates as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listDeidentifyTemplates as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('listDeidentifyTemplates', () => { - it('invokes listDeidentifyTemplates without error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.ListDeidentifyTemplatesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListDeidentifyTemplatesRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListDeidentifyTemplatesRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.privacy.dlp.v2.DeidentifyTemplate()), - generateSampleMessage(new protos.google.privacy.dlp.v2.DeidentifyTemplate()), - generateSampleMessage(new protos.google.privacy.dlp.v2.DeidentifyTemplate()), - ]; - client.innerApiCalls.listDeidentifyTemplates = stubSimpleCall(expectedResponse); - const [response] = await client.listDeidentifyTemplates(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listDeidentifyTemplates as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listDeidentifyTemplates as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listDeidentifyTemplates with error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.ListDeidentifyTemplatesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListDeidentifyTemplatesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListDeidentifyTemplatesRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listDeidentifyTemplates = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.listDeidentifyTemplates(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.listDeidentifyTemplates as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listDeidentifyTemplates as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listDeidentifyTemplates without error using callback', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.ListDeidentifyTemplatesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListDeidentifyTemplatesRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListDeidentifyTemplatesRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.privacy.dlp.v2.DeidentifyTemplate()), - generateSampleMessage(new protos.google.privacy.dlp.v2.DeidentifyTemplate()), - generateSampleMessage(new protos.google.privacy.dlp.v2.DeidentifyTemplate()), - ]; - client.innerApiCalls.listDeidentifyTemplates = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listDeidentifyTemplates( - request, - (err?: Error|null, result?: protos.google.privacy.dlp.v2.IDeidentifyTemplate[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listDeidentifyTemplates as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listDeidentifyTemplates as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listDeidentifyTemplatesStream without error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.ListDeidentifyTemplatesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListDeidentifyTemplatesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListDeidentifyTemplatesRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.privacy.dlp.v2.DeidentifyTemplate(), + ), + generateSampleMessage( + new protos.google.privacy.dlp.v2.DeidentifyTemplate(), + ), + generateSampleMessage( + new protos.google.privacy.dlp.v2.DeidentifyTemplate(), + ), + ]; + client.descriptors.page.listDeidentifyTemplates.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listDeidentifyTemplatesStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.privacy.dlp.v2.DeidentifyTemplate[] = []; + stream.on( + 'data', + (response: protos.google.privacy.dlp.v2.DeidentifyTemplate) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + ( + client.descriptors.page.listDeidentifyTemplates + .createStream as SinonStub + ) + .getCall(0) + .calledWith(client.innerApiCalls.listDeidentifyTemplates, request), + ); + assert( + ( + client.descriptors.page.listDeidentifyTemplates + .createStream as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); - it('invokes listDeidentifyTemplates with error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.ListDeidentifyTemplatesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListDeidentifyTemplatesRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListDeidentifyTemplatesRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listDeidentifyTemplates = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listDeidentifyTemplates(request), expectedError); - const actualRequest = (client.innerApiCalls.listDeidentifyTemplates as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listDeidentifyTemplates as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listDeidentifyTemplatesStream with error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.ListDeidentifyTemplatesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListDeidentifyTemplatesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListDeidentifyTemplatesRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listDeidentifyTemplates.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listDeidentifyTemplatesStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.privacy.dlp.v2.DeidentifyTemplate[] = []; + stream.on( + 'data', + (response: protos.google.privacy.dlp.v2.DeidentifyTemplate) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + ( + client.descriptors.page.listDeidentifyTemplates + .createStream as SinonStub + ) + .getCall(0) + .calledWith(client.innerApiCalls.listDeidentifyTemplates, request), + ); + assert( + ( + client.descriptors.page.listDeidentifyTemplates + .createStream as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); - it('invokes listDeidentifyTemplatesStream without error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.ListDeidentifyTemplatesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListDeidentifyTemplatesRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListDeidentifyTemplatesRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.privacy.dlp.v2.DeidentifyTemplate()), - generateSampleMessage(new protos.google.privacy.dlp.v2.DeidentifyTemplate()), - generateSampleMessage(new protos.google.privacy.dlp.v2.DeidentifyTemplate()), - ]; - client.descriptors.page.listDeidentifyTemplates.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listDeidentifyTemplatesStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.privacy.dlp.v2.DeidentifyTemplate[] = []; - stream.on('data', (response: protos.google.privacy.dlp.v2.DeidentifyTemplate) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.listDeidentifyTemplates.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listDeidentifyTemplates, request)); - assert( - (client.descriptors.page.listDeidentifyTemplates.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listDeidentifyTemplates without error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.ListDeidentifyTemplatesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListDeidentifyTemplatesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListDeidentifyTemplatesRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.privacy.dlp.v2.DeidentifyTemplate(), + ), + generateSampleMessage( + new protos.google.privacy.dlp.v2.DeidentifyTemplate(), + ), + generateSampleMessage( + new protos.google.privacy.dlp.v2.DeidentifyTemplate(), + ), + ]; + client.descriptors.page.listDeidentifyTemplates.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.privacy.dlp.v2.IDeidentifyTemplate[] = []; + const iterable = client.listDeidentifyTemplatesAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listDeidentifyTemplates + .asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + ( + client.descriptors.page.listDeidentifyTemplates + .asyncIterate as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); - it('invokes listDeidentifyTemplatesStream with error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.ListDeidentifyTemplatesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListDeidentifyTemplatesRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListDeidentifyTemplatesRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listDeidentifyTemplates.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listDeidentifyTemplatesStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.privacy.dlp.v2.DeidentifyTemplate[] = []; - stream.on('data', (response: protos.google.privacy.dlp.v2.DeidentifyTemplate) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listDeidentifyTemplates.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listDeidentifyTemplates, request)); - assert( - (client.descriptors.page.listDeidentifyTemplates.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listDeidentifyTemplates with error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.ListDeidentifyTemplatesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListDeidentifyTemplatesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListDeidentifyTemplatesRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listDeidentifyTemplates.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listDeidentifyTemplatesAsync(request); + await assert.rejects(async () => { + const responses: protos.google.privacy.dlp.v2.IDeidentifyTemplate[] = + []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listDeidentifyTemplates + .asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + ( + client.descriptors.page.listDeidentifyTemplates + .asyncIterate as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); + }); + + describe('listJobTriggers', () => { + it('invokes listJobTriggers without error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.ListJobTriggersRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListJobTriggersRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListJobTriggersRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.privacy.dlp.v2.JobTrigger()), + generateSampleMessage(new protos.google.privacy.dlp.v2.JobTrigger()), + generateSampleMessage(new protos.google.privacy.dlp.v2.JobTrigger()), + ]; + client.innerApiCalls.listJobTriggers = stubSimpleCall(expectedResponse); + const [response] = await client.listJobTriggers(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listJobTriggers as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listJobTriggers as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('uses async iteration with listDeidentifyTemplates without error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.ListDeidentifyTemplatesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListDeidentifyTemplatesRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListDeidentifyTemplatesRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.privacy.dlp.v2.DeidentifyTemplate()), - generateSampleMessage(new protos.google.privacy.dlp.v2.DeidentifyTemplate()), - generateSampleMessage(new protos.google.privacy.dlp.v2.DeidentifyTemplate()), - ]; - client.descriptors.page.listDeidentifyTemplates.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.privacy.dlp.v2.IDeidentifyTemplate[] = []; - const iterable = client.listDeidentifyTemplatesAsync(request); - for await (const resource of iterable) { - responses.push(resource!); + it('invokes listJobTriggers without error using callback', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.ListJobTriggersRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListJobTriggersRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListJobTriggersRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.privacy.dlp.v2.JobTrigger()), + generateSampleMessage(new protos.google.privacy.dlp.v2.JobTrigger()), + generateSampleMessage(new protos.google.privacy.dlp.v2.JobTrigger()), + ]; + client.innerApiCalls.listJobTriggers = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listJobTriggers( + request, + ( + err?: Error | null, + result?: protos.google.privacy.dlp.v2.IJobTrigger[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listDeidentifyTemplates.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listDeidentifyTemplates.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); - - it('uses async iteration with listDeidentifyTemplates with error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.ListDeidentifyTemplatesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListDeidentifyTemplatesRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListDeidentifyTemplatesRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listDeidentifyTemplates.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listDeidentifyTemplatesAsync(request); - await assert.rejects(async () => { - const responses: protos.google.privacy.dlp.v2.IDeidentifyTemplate[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listDeidentifyTemplates.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listDeidentifyTemplates.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listJobTriggers as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listJobTriggers as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('listJobTriggers', () => { - it('invokes listJobTriggers without error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.ListJobTriggersRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListJobTriggersRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListJobTriggersRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.privacy.dlp.v2.JobTrigger()), - generateSampleMessage(new protos.google.privacy.dlp.v2.JobTrigger()), - generateSampleMessage(new protos.google.privacy.dlp.v2.JobTrigger()), - ]; - client.innerApiCalls.listJobTriggers = stubSimpleCall(expectedResponse); - const [response] = await client.listJobTriggers(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listJobTriggers as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listJobTriggers as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listJobTriggers with error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.ListJobTriggersRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListJobTriggersRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListJobTriggersRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listJobTriggers = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listJobTriggers(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listJobTriggers as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listJobTriggers as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listJobTriggers without error using callback', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.ListJobTriggersRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListJobTriggersRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListJobTriggersRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.privacy.dlp.v2.JobTrigger()), - generateSampleMessage(new protos.google.privacy.dlp.v2.JobTrigger()), - generateSampleMessage(new protos.google.privacy.dlp.v2.JobTrigger()), - ]; - client.innerApiCalls.listJobTriggers = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listJobTriggers( - request, - (err?: Error|null, result?: protos.google.privacy.dlp.v2.IJobTrigger[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listJobTriggers as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listJobTriggers as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listJobTriggersStream without error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.ListJobTriggersRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListJobTriggersRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListJobTriggersRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.privacy.dlp.v2.JobTrigger()), + generateSampleMessage(new protos.google.privacy.dlp.v2.JobTrigger()), + generateSampleMessage(new protos.google.privacy.dlp.v2.JobTrigger()), + ]; + client.descriptors.page.listJobTriggers.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listJobTriggersStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.privacy.dlp.v2.JobTrigger[] = []; + stream.on( + 'data', + (response: protos.google.privacy.dlp.v2.JobTrigger) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listJobTriggers.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listJobTriggers, request), + ); + assert( + (client.descriptors.page.listJobTriggers.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('invokes listJobTriggers with error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.ListJobTriggersRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListJobTriggersRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListJobTriggersRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listJobTriggers = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listJobTriggers(request), expectedError); - const actualRequest = (client.innerApiCalls.listJobTriggers as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listJobTriggers as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listJobTriggersStream with error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.ListJobTriggersRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListJobTriggersRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListJobTriggersRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listJobTriggers.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listJobTriggersStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.privacy.dlp.v2.JobTrigger[] = []; + stream.on( + 'data', + (response: protos.google.privacy.dlp.v2.JobTrigger) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listJobTriggers.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listJobTriggers, request), + ); + assert( + (client.descriptors.page.listJobTriggers.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('invokes listJobTriggersStream without error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.ListJobTriggersRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListJobTriggersRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListJobTriggersRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.privacy.dlp.v2.JobTrigger()), - generateSampleMessage(new protos.google.privacy.dlp.v2.JobTrigger()), - generateSampleMessage(new protos.google.privacy.dlp.v2.JobTrigger()), - ]; - client.descriptors.page.listJobTriggers.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listJobTriggersStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.privacy.dlp.v2.JobTrigger[] = []; - stream.on('data', (response: protos.google.privacy.dlp.v2.JobTrigger) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.listJobTriggers.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listJobTriggers, request)); - assert( - (client.descriptors.page.listJobTriggers.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listJobTriggers without error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.ListJobTriggersRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListJobTriggersRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListJobTriggersRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.privacy.dlp.v2.JobTrigger()), + generateSampleMessage(new protos.google.privacy.dlp.v2.JobTrigger()), + generateSampleMessage(new protos.google.privacy.dlp.v2.JobTrigger()), + ]; + client.descriptors.page.listJobTriggers.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.privacy.dlp.v2.IJobTrigger[] = []; + const iterable = client.listJobTriggersAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listJobTriggers.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listJobTriggers.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('invokes listJobTriggersStream with error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.ListJobTriggersRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListJobTriggersRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListJobTriggersRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listJobTriggers.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listJobTriggersStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.privacy.dlp.v2.JobTrigger[] = []; - stream.on('data', (response: protos.google.privacy.dlp.v2.JobTrigger) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listJobTriggers.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listJobTriggers, request)); - assert( - (client.descriptors.page.listJobTriggers.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listJobTriggers with error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.ListJobTriggersRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListJobTriggersRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListJobTriggersRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listJobTriggers.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listJobTriggersAsync(request); + await assert.rejects(async () => { + const responses: protos.google.privacy.dlp.v2.IJobTrigger[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listJobTriggers.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listJobTriggers.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + }); + + describe('listDlpJobs', () => { + it('invokes listDlpJobs without error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.ListDlpJobsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListDlpJobsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListDlpJobsRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.privacy.dlp.v2.DlpJob()), + generateSampleMessage(new protos.google.privacy.dlp.v2.DlpJob()), + generateSampleMessage(new protos.google.privacy.dlp.v2.DlpJob()), + ]; + client.innerApiCalls.listDlpJobs = stubSimpleCall(expectedResponse); + const [response] = await client.listDlpJobs(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listDlpJobs as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listDlpJobs as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('uses async iteration with listJobTriggers without error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.ListJobTriggersRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListJobTriggersRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListJobTriggersRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.privacy.dlp.v2.JobTrigger()), - generateSampleMessage(new protos.google.privacy.dlp.v2.JobTrigger()), - generateSampleMessage(new protos.google.privacy.dlp.v2.JobTrigger()), - ]; - client.descriptors.page.listJobTriggers.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.privacy.dlp.v2.IJobTrigger[] = []; - const iterable = client.listJobTriggersAsync(request); - for await (const resource of iterable) { - responses.push(resource!); + it('invokes listDlpJobs without error using callback', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.ListDlpJobsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListDlpJobsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListDlpJobsRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.privacy.dlp.v2.DlpJob()), + generateSampleMessage(new protos.google.privacy.dlp.v2.DlpJob()), + generateSampleMessage(new protos.google.privacy.dlp.v2.DlpJob()), + ]; + client.innerApiCalls.listDlpJobs = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listDlpJobs( + request, + ( + err?: Error | null, + result?: protos.google.privacy.dlp.v2.IDlpJob[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listJobTriggers.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listJobTriggers.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); - - it('uses async iteration with listJobTriggers with error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.ListJobTriggersRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListJobTriggersRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListJobTriggersRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listJobTriggers.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listJobTriggersAsync(request); - await assert.rejects(async () => { - const responses: protos.google.privacy.dlp.v2.IJobTrigger[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listJobTriggers.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listJobTriggers.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listDlpJobs as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listDlpJobs as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('listDlpJobs', () => { - it('invokes listDlpJobs without error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.ListDlpJobsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListDlpJobsRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListDlpJobsRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.privacy.dlp.v2.DlpJob()), - generateSampleMessage(new protos.google.privacy.dlp.v2.DlpJob()), - generateSampleMessage(new protos.google.privacy.dlp.v2.DlpJob()), - ]; - client.innerApiCalls.listDlpJobs = stubSimpleCall(expectedResponse); - const [response] = await client.listDlpJobs(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listDlpJobs as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listDlpJobs as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listDlpJobs with error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.ListDlpJobsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListDlpJobsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListDlpJobsRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listDlpJobs = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listDlpJobs(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listDlpJobs as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listDlpJobs as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listDlpJobs without error using callback', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.ListDlpJobsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListDlpJobsRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListDlpJobsRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.privacy.dlp.v2.DlpJob()), - generateSampleMessage(new protos.google.privacy.dlp.v2.DlpJob()), - generateSampleMessage(new protos.google.privacy.dlp.v2.DlpJob()), - ]; - client.innerApiCalls.listDlpJobs = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listDlpJobs( - request, - (err?: Error|null, result?: protos.google.privacy.dlp.v2.IDlpJob[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listDlpJobs as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listDlpJobs as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listDlpJobsStream without error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.ListDlpJobsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListDlpJobsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListDlpJobsRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.privacy.dlp.v2.DlpJob()), + generateSampleMessage(new protos.google.privacy.dlp.v2.DlpJob()), + generateSampleMessage(new protos.google.privacy.dlp.v2.DlpJob()), + ]; + client.descriptors.page.listDlpJobs.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listDlpJobsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.privacy.dlp.v2.DlpJob[] = []; + stream.on('data', (response: protos.google.privacy.dlp.v2.DlpJob) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listDlpJobs.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listDlpJobs, request), + ); + assert( + (client.descriptors.page.listDlpJobs.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('invokes listDlpJobs with error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.ListDlpJobsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListDlpJobsRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListDlpJobsRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listDlpJobs = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listDlpJobs(request), expectedError); - const actualRequest = (client.innerApiCalls.listDlpJobs as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listDlpJobs as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listDlpJobsStream with error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.ListDlpJobsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListDlpJobsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListDlpJobsRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listDlpJobs.createStream = stubPageStreamingCall( + undefined, + expectedError, + ); + const stream = client.listDlpJobsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.privacy.dlp.v2.DlpJob[] = []; + stream.on('data', (response: protos.google.privacy.dlp.v2.DlpJob) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listDlpJobs.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listDlpJobs, request), + ); + assert( + (client.descriptors.page.listDlpJobs.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('invokes listDlpJobsStream without error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.ListDlpJobsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListDlpJobsRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListDlpJobsRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.privacy.dlp.v2.DlpJob()), - generateSampleMessage(new protos.google.privacy.dlp.v2.DlpJob()), - generateSampleMessage(new protos.google.privacy.dlp.v2.DlpJob()), - ]; - client.descriptors.page.listDlpJobs.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listDlpJobsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.privacy.dlp.v2.DlpJob[] = []; - stream.on('data', (response: protos.google.privacy.dlp.v2.DlpJob) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.listDlpJobs.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listDlpJobs, request)); - assert( - (client.descriptors.page.listDlpJobs.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listDlpJobs without error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.ListDlpJobsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListDlpJobsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListDlpJobsRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.privacy.dlp.v2.DlpJob()), + generateSampleMessage(new protos.google.privacy.dlp.v2.DlpJob()), + generateSampleMessage(new protos.google.privacy.dlp.v2.DlpJob()), + ]; + client.descriptors.page.listDlpJobs.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.privacy.dlp.v2.IDlpJob[] = []; + const iterable = client.listDlpJobsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + (client.descriptors.page.listDlpJobs.asyncIterate as SinonStub).getCall( + 0, + ).args[1], + request, + ); + assert( + (client.descriptors.page.listDlpJobs.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('invokes listDlpJobsStream with error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.ListDlpJobsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListDlpJobsRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListDlpJobsRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listDlpJobs.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listDlpJobsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.privacy.dlp.v2.DlpJob[] = []; - stream.on('data', (response: protos.google.privacy.dlp.v2.DlpJob) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listDlpJobs.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listDlpJobs, request)); - assert( - (client.descriptors.page.listDlpJobs.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listDlpJobs with error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.ListDlpJobsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListDlpJobsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListDlpJobsRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listDlpJobs.asyncIterate = stubAsyncIterationCall( + undefined, + expectedError, + ); + const iterable = client.listDlpJobsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.privacy.dlp.v2.IDlpJob[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + (client.descriptors.page.listDlpJobs.asyncIterate as SinonStub).getCall( + 0, + ).args[1], + request, + ); + assert( + (client.descriptors.page.listDlpJobs.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + }); + + describe('listStoredInfoTypes', () => { + it('invokes listStoredInfoTypes without error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.ListStoredInfoTypesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListStoredInfoTypesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListStoredInfoTypesRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.privacy.dlp.v2.StoredInfoType(), + ), + generateSampleMessage( + new protos.google.privacy.dlp.v2.StoredInfoType(), + ), + generateSampleMessage( + new protos.google.privacy.dlp.v2.StoredInfoType(), + ), + ]; + client.innerApiCalls.listStoredInfoTypes = + stubSimpleCall(expectedResponse); + const [response] = await client.listStoredInfoTypes(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listStoredInfoTypes as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listStoredInfoTypes as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('uses async iteration with listDlpJobs without error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.ListDlpJobsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListDlpJobsRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListDlpJobsRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.privacy.dlp.v2.DlpJob()), - generateSampleMessage(new protos.google.privacy.dlp.v2.DlpJob()), - generateSampleMessage(new protos.google.privacy.dlp.v2.DlpJob()), - ]; - client.descriptors.page.listDlpJobs.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.privacy.dlp.v2.IDlpJob[] = []; - const iterable = client.listDlpJobsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); + it('invokes listStoredInfoTypes without error using callback', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.ListStoredInfoTypesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListStoredInfoTypesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListStoredInfoTypesRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.privacy.dlp.v2.StoredInfoType(), + ), + generateSampleMessage( + new protos.google.privacy.dlp.v2.StoredInfoType(), + ), + generateSampleMessage( + new protos.google.privacy.dlp.v2.StoredInfoType(), + ), + ]; + client.innerApiCalls.listStoredInfoTypes = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listStoredInfoTypes( + request, + ( + err?: Error | null, + result?: protos.google.privacy.dlp.v2.IStoredInfoType[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listDlpJobs.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listDlpJobs.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); - - it('uses async iteration with listDlpJobs with error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.ListDlpJobsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListDlpJobsRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListDlpJobsRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listDlpJobs.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listDlpJobsAsync(request); - await assert.rejects(async () => { - const responses: protos.google.privacy.dlp.v2.IDlpJob[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listDlpJobs.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listDlpJobs.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listStoredInfoTypes as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listStoredInfoTypes as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('listStoredInfoTypes', () => { - it('invokes listStoredInfoTypes without error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.ListStoredInfoTypesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListStoredInfoTypesRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListStoredInfoTypesRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.privacy.dlp.v2.StoredInfoType()), - generateSampleMessage(new protos.google.privacy.dlp.v2.StoredInfoType()), - generateSampleMessage(new protos.google.privacy.dlp.v2.StoredInfoType()), - ]; - client.innerApiCalls.listStoredInfoTypes = stubSimpleCall(expectedResponse); - const [response] = await client.listStoredInfoTypes(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listStoredInfoTypes as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listStoredInfoTypes as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listStoredInfoTypes without error using callback', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.ListStoredInfoTypesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListStoredInfoTypesRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListStoredInfoTypesRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.privacy.dlp.v2.StoredInfoType()), - generateSampleMessage(new protos.google.privacy.dlp.v2.StoredInfoType()), - generateSampleMessage(new protos.google.privacy.dlp.v2.StoredInfoType()), - ]; - client.innerApiCalls.listStoredInfoTypes = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listStoredInfoTypes( - request, - (err?: Error|null, result?: protos.google.privacy.dlp.v2.IStoredInfoType[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listStoredInfoTypes as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listStoredInfoTypes as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listStoredInfoTypes with error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.ListStoredInfoTypesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListStoredInfoTypesRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListStoredInfoTypesRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listStoredInfoTypes = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listStoredInfoTypes(request), expectedError); - const actualRequest = (client.innerApiCalls.listStoredInfoTypes as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listStoredInfoTypes as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listStoredInfoTypesStream without error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.ListStoredInfoTypesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListStoredInfoTypesRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListStoredInfoTypesRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.privacy.dlp.v2.StoredInfoType()), - generateSampleMessage(new protos.google.privacy.dlp.v2.StoredInfoType()), - generateSampleMessage(new protos.google.privacy.dlp.v2.StoredInfoType()), - ]; - client.descriptors.page.listStoredInfoTypes.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listStoredInfoTypesStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.privacy.dlp.v2.StoredInfoType[] = []; - stream.on('data', (response: protos.google.privacy.dlp.v2.StoredInfoType) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.listStoredInfoTypes.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listStoredInfoTypes, request)); - assert( - (client.descriptors.page.listStoredInfoTypes.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listStoredInfoTypes with error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.ListStoredInfoTypesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListStoredInfoTypesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListStoredInfoTypesRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listStoredInfoTypes = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listStoredInfoTypes(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listStoredInfoTypes as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listStoredInfoTypes as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listStoredInfoTypesStream with error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.ListStoredInfoTypesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListStoredInfoTypesRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListStoredInfoTypesRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listStoredInfoTypes.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listStoredInfoTypesStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.privacy.dlp.v2.StoredInfoType[] = []; - stream.on('data', (response: protos.google.privacy.dlp.v2.StoredInfoType) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listStoredInfoTypes.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listStoredInfoTypes, request)); - assert( - (client.descriptors.page.listStoredInfoTypes.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listStoredInfoTypesStream without error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.ListStoredInfoTypesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListStoredInfoTypesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListStoredInfoTypesRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.privacy.dlp.v2.StoredInfoType(), + ), + generateSampleMessage( + new protos.google.privacy.dlp.v2.StoredInfoType(), + ), + generateSampleMessage( + new protos.google.privacy.dlp.v2.StoredInfoType(), + ), + ]; + client.descriptors.page.listStoredInfoTypes.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listStoredInfoTypesStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.privacy.dlp.v2.StoredInfoType[] = []; + stream.on( + 'data', + (response: protos.google.privacy.dlp.v2.StoredInfoType) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listStoredInfoTypes.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listStoredInfoTypes, request), + ); + assert( + (client.descriptors.page.listStoredInfoTypes.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('uses async iteration with listStoredInfoTypes without error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.ListStoredInfoTypesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListStoredInfoTypesRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListStoredInfoTypesRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.privacy.dlp.v2.StoredInfoType()), - generateSampleMessage(new protos.google.privacy.dlp.v2.StoredInfoType()), - generateSampleMessage(new protos.google.privacy.dlp.v2.StoredInfoType()), - ]; - client.descriptors.page.listStoredInfoTypes.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.privacy.dlp.v2.IStoredInfoType[] = []; - const iterable = client.listStoredInfoTypesAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listStoredInfoTypes.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listStoredInfoTypes.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listStoredInfoTypesStream with error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.ListStoredInfoTypesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListStoredInfoTypesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListStoredInfoTypesRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listStoredInfoTypes.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listStoredInfoTypesStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.privacy.dlp.v2.StoredInfoType[] = []; + stream.on( + 'data', + (response: protos.google.privacy.dlp.v2.StoredInfoType) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listStoredInfoTypes.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listStoredInfoTypes, request), + ); + assert( + (client.descriptors.page.listStoredInfoTypes.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('uses async iteration with listStoredInfoTypes with error', async () => { - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.privacy.dlp.v2.ListStoredInfoTypesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListStoredInfoTypesRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.privacy.dlp.v2.ListStoredInfoTypesRequest', ['locationId']); - request.locationId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&location_id=${defaultValue2 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listStoredInfoTypes.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listStoredInfoTypesAsync(request); - await assert.rejects(async () => { - const responses: protos.google.privacy.dlp.v2.IStoredInfoType[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listStoredInfoTypes.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listStoredInfoTypes.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listStoredInfoTypes without error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.ListStoredInfoTypesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListStoredInfoTypesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListStoredInfoTypesRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.privacy.dlp.v2.StoredInfoType(), + ), + generateSampleMessage( + new protos.google.privacy.dlp.v2.StoredInfoType(), + ), + generateSampleMessage( + new protos.google.privacy.dlp.v2.StoredInfoType(), + ), + ]; + client.descriptors.page.listStoredInfoTypes.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.privacy.dlp.v2.IStoredInfoType[] = []; + const iterable = client.listStoredInfoTypesAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listStoredInfoTypes.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listStoredInfoTypes.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); }); - describe('Path templates', () => { - - describe('dlpJob', async () => { - const fakePath = "/rendered/path/dlpJob"; - const expectedParameters = { - project: "projectValue", - dlp_job: "dlpJobValue", - }; - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.dlpJobPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.dlpJobPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('dlpJobPath', () => { - const result = client.dlpJobPath("projectValue", "dlpJobValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.dlpJobPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromDlpJobName', () => { - const result = client.matchProjectFromDlpJobName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.dlpJobPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchDlpJobFromDlpJobName', () => { - const result = client.matchDlpJobFromDlpJobName(fakePath); - assert.strictEqual(result, "dlpJobValue"); - assert((client.pathTemplates.dlpJobPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('uses async iteration with listStoredInfoTypes with error', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.privacy.dlp.v2.ListStoredInfoTypesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListStoredInfoTypesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.privacy.dlp.v2.ListStoredInfoTypesRequest', + ['locationId'], + ); + request.locationId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&location_id=${defaultValue2 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listStoredInfoTypes.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listStoredInfoTypesAsync(request); + await assert.rejects(async () => { + const responses: protos.google.privacy.dlp.v2.IStoredInfoType[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listStoredInfoTypes.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listStoredInfoTypes.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + }); + + describe('Path templates', () => { + describe('dlpJob', async () => { + const fakePath = '/rendered/path/dlpJob'; + const expectedParameters = { + project: 'projectValue', + dlp_job: 'dlpJobValue', + }; + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.dlpJobPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.dlpJobPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('dlpJobPath', () => { + const result = client.dlpJobPath('projectValue', 'dlpJobValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.dlpJobPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromDlpJobName', () => { + const result = client.matchProjectFromDlpJobName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.dlpJobPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchDlpJobFromDlpJobName', () => { + const result = client.matchDlpJobFromDlpJobName(fakePath); + assert.strictEqual(result, 'dlpJobValue'); + assert( + (client.pathTemplates.dlpJobPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('jobTrigger', async () => { - const fakePath = "/rendered/path/jobTrigger"; - const expectedParameters = { - project: "projectValue", - job_trigger: "jobTriggerValue", - }; - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.jobTriggerPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.jobTriggerPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('jobTriggerPath', () => { - const result = client.jobTriggerPath("projectValue", "jobTriggerValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.jobTriggerPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromJobTriggerName', () => { - const result = client.matchProjectFromJobTriggerName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.jobTriggerPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchJobTriggerFromJobTriggerName', () => { - const result = client.matchJobTriggerFromJobTriggerName(fakePath); - assert.strictEqual(result, "jobTriggerValue"); - assert((client.pathTemplates.jobTriggerPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('jobTrigger', async () => { + const fakePath = '/rendered/path/jobTrigger'; + const expectedParameters = { + project: 'projectValue', + job_trigger: 'jobTriggerValue', + }; + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.jobTriggerPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.jobTriggerPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('jobTriggerPath', () => { + const result = client.jobTriggerPath('projectValue', 'jobTriggerValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.jobTriggerPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromJobTriggerName', () => { + const result = client.matchProjectFromJobTriggerName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.jobTriggerPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchJobTriggerFromJobTriggerName', () => { + const result = client.matchJobTriggerFromJobTriggerName(fakePath); + assert.strictEqual(result, 'jobTriggerValue'); + assert( + (client.pathTemplates.jobTriggerPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('organization', async () => { - const fakePath = "/rendered/path/organization"; - const expectedParameters = { - organization: "organizationValue", - }; - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.organizationPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationPath', () => { - const result = client.organizationPath("organizationValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationName', () => { - const result = client.matchOrganizationFromOrganizationName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('organization', async () => { + const fakePath = '/rendered/path/organization'; + const expectedParameters = { + organization: 'organizationValue', + }; + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.organizationPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.organizationPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('organizationPath', () => { + const result = client.organizationPath('organizationValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.organizationPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationName', () => { + const result = client.matchOrganizationFromOrganizationName(fakePath); + assert.strictEqual(result, 'organizationValue'); + assert( + (client.pathTemplates.organizationPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('organizationDeidentifyTemplate', async () => { - const fakePath = "/rendered/path/organizationDeidentifyTemplate"; - const expectedParameters = { - organization: "organizationValue", - deidentify_template: "deidentifyTemplateValue", - }; - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.organizationDeidentifyTemplatePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationDeidentifyTemplatePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationDeidentifyTemplatePath', () => { - const result = client.organizationDeidentifyTemplatePath("organizationValue", "deidentifyTemplateValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationDeidentifyTemplatePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationDeidentifyTemplateName', () => { - const result = client.matchOrganizationFromOrganizationDeidentifyTemplateName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationDeidentifyTemplatePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchDeidentifyTemplateFromOrganizationDeidentifyTemplateName', () => { - const result = client.matchDeidentifyTemplateFromOrganizationDeidentifyTemplateName(fakePath); - assert.strictEqual(result, "deidentifyTemplateValue"); - assert((client.pathTemplates.organizationDeidentifyTemplatePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('organizationDeidentifyTemplate', async () => { + const fakePath = '/rendered/path/organizationDeidentifyTemplate'; + const expectedParameters = { + organization: 'organizationValue', + deidentify_template: 'deidentifyTemplateValue', + }; + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.organizationDeidentifyTemplatePathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.organizationDeidentifyTemplatePathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('organizationDeidentifyTemplatePath', () => { + const result = client.organizationDeidentifyTemplatePath( + 'organizationValue', + 'deidentifyTemplateValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationDeidentifyTemplatePathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationDeidentifyTemplateName', () => { + const result = + client.matchOrganizationFromOrganizationDeidentifyTemplateName( + fakePath, + ); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationDeidentifyTemplatePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchDeidentifyTemplateFromOrganizationDeidentifyTemplateName', () => { + const result = + client.matchDeidentifyTemplateFromOrganizationDeidentifyTemplateName( + fakePath, + ); + assert.strictEqual(result, 'deidentifyTemplateValue'); + assert( + ( + client.pathTemplates.organizationDeidentifyTemplatePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('organizationInspectTemplate', async () => { - const fakePath = "/rendered/path/organizationInspectTemplate"; - const expectedParameters = { - organization: "organizationValue", - inspect_template: "inspectTemplateValue", - }; - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.organizationInspectTemplatePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationInspectTemplatePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationInspectTemplatePath', () => { - const result = client.organizationInspectTemplatePath("organizationValue", "inspectTemplateValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationInspectTemplatePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationInspectTemplateName', () => { - const result = client.matchOrganizationFromOrganizationInspectTemplateName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationInspectTemplatePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchInspectTemplateFromOrganizationInspectTemplateName', () => { - const result = client.matchInspectTemplateFromOrganizationInspectTemplateName(fakePath); - assert.strictEqual(result, "inspectTemplateValue"); - assert((client.pathTemplates.organizationInspectTemplatePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('organizationInspectTemplate', async () => { + const fakePath = '/rendered/path/organizationInspectTemplate'; + const expectedParameters = { + organization: 'organizationValue', + inspect_template: 'inspectTemplateValue', + }; + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.organizationInspectTemplatePathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.organizationInspectTemplatePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('organizationInspectTemplatePath', () => { + const result = client.organizationInspectTemplatePath( + 'organizationValue', + 'inspectTemplateValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationInspectTemplatePathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationInspectTemplateName', () => { + const result = + client.matchOrganizationFromOrganizationInspectTemplateName(fakePath); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationInspectTemplatePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchInspectTemplateFromOrganizationInspectTemplateName', () => { + const result = + client.matchInspectTemplateFromOrganizationInspectTemplateName( + fakePath, + ); + assert.strictEqual(result, 'inspectTemplateValue'); + assert( + ( + client.pathTemplates.organizationInspectTemplatePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('organizationStoredInfoType', async () => { - const fakePath = "/rendered/path/organizationStoredInfoType"; - const expectedParameters = { - organization: "organizationValue", - stored_info_type: "storedInfoTypeValue", - }; - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.organizationStoredInfoTypePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationStoredInfoTypePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationStoredInfoTypePath', () => { - const result = client.organizationStoredInfoTypePath("organizationValue", "storedInfoTypeValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationStoredInfoTypePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationStoredInfoTypeName', () => { - const result = client.matchOrganizationFromOrganizationStoredInfoTypeName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationStoredInfoTypePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchStoredInfoTypeFromOrganizationStoredInfoTypeName', () => { - const result = client.matchStoredInfoTypeFromOrganizationStoredInfoTypeName(fakePath); - assert.strictEqual(result, "storedInfoTypeValue"); - assert((client.pathTemplates.organizationStoredInfoTypePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('organizationStoredInfoType', async () => { + const fakePath = '/rendered/path/organizationStoredInfoType'; + const expectedParameters = { + organization: 'organizationValue', + stored_info_type: 'storedInfoTypeValue', + }; + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.organizationStoredInfoTypePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.organizationStoredInfoTypePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('organizationStoredInfoTypePath', () => { + const result = client.organizationStoredInfoTypePath( + 'organizationValue', + 'storedInfoTypeValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationStoredInfoTypePathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationStoredInfoTypeName', () => { + const result = + client.matchOrganizationFromOrganizationStoredInfoTypeName(fakePath); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationStoredInfoTypePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchStoredInfoTypeFromOrganizationStoredInfoTypeName', () => { + const result = + client.matchStoredInfoTypeFromOrganizationStoredInfoTypeName( + fakePath, + ); + assert.strictEqual(result, 'storedInfoTypeValue'); + assert( + ( + client.pathTemplates.organizationStoredInfoTypePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('project', async () => { - const fakePath = "/rendered/path/project"; - const expectedParameters = { - project: "projectValue", - }; - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.projectPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectPath', () => { - const result = client.projectPath("projectValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectName', () => { - const result = client.matchProjectFromProjectName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('project', async () => { + const fakePath = '/rendered/path/project'; + const expectedParameters = { + project: 'projectValue', + }; + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.projectPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectPath', () => { + const result = client.projectPath('projectValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.projectPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectName', () => { + const result = client.matchProjectFromProjectName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.projectPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectDeidentifyTemplate', async () => { - const fakePath = "/rendered/path/projectDeidentifyTemplate"; - const expectedParameters = { - project: "projectValue", - deidentify_template: "deidentifyTemplateValue", - }; - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.projectDeidentifyTemplatePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectDeidentifyTemplatePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectDeidentifyTemplatePath', () => { - const result = client.projectDeidentifyTemplatePath("projectValue", "deidentifyTemplateValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectDeidentifyTemplatePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectDeidentifyTemplateName', () => { - const result = client.matchProjectFromProjectDeidentifyTemplateName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectDeidentifyTemplatePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchDeidentifyTemplateFromProjectDeidentifyTemplateName', () => { - const result = client.matchDeidentifyTemplateFromProjectDeidentifyTemplateName(fakePath); - assert.strictEqual(result, "deidentifyTemplateValue"); - assert((client.pathTemplates.projectDeidentifyTemplatePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectDeidentifyTemplate', async () => { + const fakePath = '/rendered/path/projectDeidentifyTemplate'; + const expectedParameters = { + project: 'projectValue', + deidentify_template: 'deidentifyTemplateValue', + }; + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.projectDeidentifyTemplatePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectDeidentifyTemplatePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectDeidentifyTemplatePath', () => { + const result = client.projectDeidentifyTemplatePath( + 'projectValue', + 'deidentifyTemplateValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.projectDeidentifyTemplatePathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectDeidentifyTemplateName', () => { + const result = + client.matchProjectFromProjectDeidentifyTemplateName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.projectDeidentifyTemplatePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchDeidentifyTemplateFromProjectDeidentifyTemplateName', () => { + const result = + client.matchDeidentifyTemplateFromProjectDeidentifyTemplateName( + fakePath, + ); + assert.strictEqual(result, 'deidentifyTemplateValue'); + assert( + ( + client.pathTemplates.projectDeidentifyTemplatePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectInspectTemplate', async () => { - const fakePath = "/rendered/path/projectInspectTemplate"; - const expectedParameters = { - project: "projectValue", - inspect_template: "inspectTemplateValue", - }; - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.projectInspectTemplatePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectInspectTemplatePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectInspectTemplatePath', () => { - const result = client.projectInspectTemplatePath("projectValue", "inspectTemplateValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectInspectTemplatePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectInspectTemplateName', () => { - const result = client.matchProjectFromProjectInspectTemplateName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectInspectTemplatePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchInspectTemplateFromProjectInspectTemplateName', () => { - const result = client.matchInspectTemplateFromProjectInspectTemplateName(fakePath); - assert.strictEqual(result, "inspectTemplateValue"); - assert((client.pathTemplates.projectInspectTemplatePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectInspectTemplate', async () => { + const fakePath = '/rendered/path/projectInspectTemplate'; + const expectedParameters = { + project: 'projectValue', + inspect_template: 'inspectTemplateValue', + }; + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.projectInspectTemplatePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectInspectTemplatePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectInspectTemplatePath', () => { + const result = client.projectInspectTemplatePath( + 'projectValue', + 'inspectTemplateValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.projectInspectTemplatePathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectInspectTemplateName', () => { + const result = + client.matchProjectFromProjectInspectTemplateName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.projectInspectTemplatePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchInspectTemplateFromProjectInspectTemplateName', () => { + const result = + client.matchInspectTemplateFromProjectInspectTemplateName(fakePath); + assert.strictEqual(result, 'inspectTemplateValue'); + assert( + ( + client.pathTemplates.projectInspectTemplatePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectStoredInfoType', async () => { - const fakePath = "/rendered/path/projectStoredInfoType"; - const expectedParameters = { - project: "projectValue", - stored_info_type: "storedInfoTypeValue", - }; - const client = new dlpserviceModule.v2.DlpServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.projectStoredInfoTypePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectStoredInfoTypePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectStoredInfoTypePath', () => { - const result = client.projectStoredInfoTypePath("projectValue", "storedInfoTypeValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectStoredInfoTypePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectStoredInfoTypeName', () => { - const result = client.matchProjectFromProjectStoredInfoTypeName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectStoredInfoTypePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchStoredInfoTypeFromProjectStoredInfoTypeName', () => { - const result = client.matchStoredInfoTypeFromProjectStoredInfoTypeName(fakePath); - assert.strictEqual(result, "storedInfoTypeValue"); - assert((client.pathTemplates.projectStoredInfoTypePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectStoredInfoType', async () => { + const fakePath = '/rendered/path/projectStoredInfoType'; + const expectedParameters = { + project: 'projectValue', + stored_info_type: 'storedInfoTypeValue', + }; + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.projectStoredInfoTypePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectStoredInfoTypePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectStoredInfoTypePath', () => { + const result = client.projectStoredInfoTypePath( + 'projectValue', + 'storedInfoTypeValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.projectStoredInfoTypePathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectStoredInfoTypeName', () => { + const result = + client.matchProjectFromProjectStoredInfoTypeName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.projectStoredInfoTypePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchStoredInfoTypeFromProjectStoredInfoTypeName', () => { + const result = + client.matchStoredInfoTypeFromProjectStoredInfoTypeName(fakePath); + assert.strictEqual(result, 'storedInfoTypeValue'); + assert( + ( + client.pathTemplates.projectStoredInfoTypePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/core/generator/gapic-generator-typescript/baselines/duplicate_methods_test-esm/esm/src/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/duplicate_methods_test-esm/esm/src/index.ts.baseline index 2f77a6060187..617f07bc8b4e 100644 --- a/core/generator/gapic-generator-typescript/baselines/duplicate_methods_test-esm/esm/src/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/duplicate_methods_test-esm/esm/src/index.ts.baseline @@ -19,8 +19,8 @@ import * as v1 from './v1/index.js'; const DuplicateMethodsTestServiceClient = v1.DuplicateMethodsTestServiceClient; type DuplicateMethodsTestServiceClient = v1.DuplicateMethodsTestServiceClient; -export {v1, DuplicateMethodsTestServiceClient}; -export default {v1, DuplicateMethodsTestServiceClient}; +export { v1, DuplicateMethodsTestServiceClient }; +export default { v1, DuplicateMethodsTestServiceClient }; // @ts-ignore import * as protos from '../../protos/protos.js'; -export {protos} +export { protos }; diff --git a/core/generator/gapic-generator-typescript/baselines/duplicate_methods_test-esm/esm/src/v1/duplicate_methods_test_service_client.ts.baseline b/core/generator/gapic-generator-typescript/baselines/duplicate_methods_test-esm/esm/src/v1/duplicate_methods_test_service_client.ts.baseline index e2576720d4e4..30f8481d0ea9 100644 --- a/core/generator/gapic-generator-typescript/baselines/duplicate_methods_test-esm/esm/src/v1/duplicate_methods_test_service_client.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/duplicate_methods_test-esm/esm/src/v1/duplicate_methods_test_service_client.ts.baseline @@ -18,15 +18,26 @@ /* global window */ import * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions, PaginationCallback, GaxCall, IamClient, IamProtos, LocationsClient, LocationProtos} from 'google-gax'; -import {Transform} from 'stream'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + PaginationCallback, + GaxCall, + IamClient, + IamProtos, + LocationsClient, + LocationProtos, +} from 'google-gax'; +import { Transform } from 'stream'; // @ts-ignore import type * as protos from '../../../protos/protos.js'; import * as duplicate_methods_test_service_client_config from './duplicate_methods_test_service_client_config.json'; import fs from 'fs'; import path from 'path'; -import {fileURLToPath} from 'url'; -import {getJSON} from '../json-helper.cjs'; +import { fileURLToPath } from 'url'; +import { getJSON } from '../json-helper.cjs'; // @ts-ignore const dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -36,15 +47,15 @@ const dirname = path.dirname(fileURLToPath(import.meta.url)); * This file defines retry strategy and timeouts for all API methods in this library. */ const gapicConfig = getJSON( - path.join(dirname, 'duplicate_methods_test_service_client_config.json') + path.join(dirname, 'duplicate_methods_test_service_client_config.json'), ); const jsonProtos = getJSON( - path.join(dirname, '..', '..', '..', 'protos/protos.json') + path.join(dirname, '..', '..', '..', 'protos/protos.json'), ); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; const version = getJSON( - path.join(dirname, '..', '..', '..', '..', 'package.json') + path.join(dirname, '..', '..', '..', '..', 'package.json'), ).version; /** @@ -58,7 +69,7 @@ export class DuplicateMethodsTestServiceClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('duplicate-methods-test'); @@ -70,10 +81,10 @@ export class DuplicateMethodsTestServiceClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; + innerApiCalls: { [name: string]: Function }; iamClient: IamClient; locationsClient: LocationsClient; - duplicateMethodsTestServiceStub?: Promise<{[name: string]: Function}>; + duplicateMethodsTestServiceStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of DuplicateMethodsTestServiceClient. @@ -115,21 +126,43 @@ export class DuplicateMethodsTestServiceClient { * const client = new DuplicateMethodsTestServiceClient({fallback: 'rest'}, gax); * ``` */ - constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { // Ensure that options include all the required fields. - const staticMembers = this.constructor as typeof DuplicateMethodsTestServiceClient; - if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { - throw new Error('Please set either universe_domain or universeDomain, but not both.'); + const staticMembers = this + .constructor as typeof DuplicateMethodsTestServiceClient; + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); } - const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; - this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; this._servicePath = 'duplicatemethodstest.' + this._universeDomain; - const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; - const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. if (servicePath !== this._servicePath && !('scopes' in opts)) { @@ -151,7 +184,7 @@ export class DuplicateMethodsTestServiceClient { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; @@ -164,21 +197,17 @@ export class DuplicateMethodsTestServiceClient { this.auth.defaultScopes = staticMembers.scopes; } this.iamClient = new this._gaxModule.IamClient(this._gaxGrpc, opts); - + this.locationsClient = new this._gaxModule.LocationsClient( this._gaxGrpc, - opts + opts, ); - // Add ESM headers const isEsm = true; const isEsmString = isEsm ? '-esm' : '-cjs'; // Determine the client header string. - const clientHeader = [ - `gax/${this._gaxModule.version}`, - `gapic/${version}`, - ]; + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/{process.versions.node}${isEsmString}`); } else { @@ -186,7 +215,7 @@ export class DuplicateMethodsTestServiceClient { } if (!opts.fallback) { clientHeader.push(`grpc/${this._gaxGrpc.grpcVersion}`); - } else if (opts.fallback === 'rest' ) { + } else if (opts.fallback === 'rest') { clientHeader.push(`rest/${this._gaxGrpc.grpcVersion}`); } if (opts.libName && opts.libVersion) { @@ -194,20 +223,28 @@ export class DuplicateMethodsTestServiceClient { } // Load the applicable protos. - this._protos = this._gaxGrpc.loadProtoJSON(jsonProtos as gax.protobuf.INamespace); + this._protos = this._gaxGrpc.loadProtoJSON( + jsonProtos as gax.protobuf.INamespace, + ); // Some of the methods on this service return "paged" results, // (e.g. 50 results at a time, with tokens to get subsequent // pages). Denote the keys used for pagination and results. this.descriptors.page = { - listLocations: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'locations') + listLocations: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'locations', + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.duplicate_methods_test.v1.DuplicateMethodsTestService', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.duplicate_methods_test.v1.DuplicateMethodsTestService', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + { 'x-goog-api-client': clientHeader.join(' ') }, + ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -238,37 +275,45 @@ export class DuplicateMethodsTestServiceClient { // Put together the "service stub" for // google.duplicate_methods_test.v1.DuplicateMethodsTestService. this.duplicateMethodsTestServiceStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.duplicate_methods_test.v1.DuplicateMethodsTestService') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any - (this._protos as any).google.duplicate_methods_test.v1.DuplicateMethodsTestService, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.duplicate_methods_test.v1.DuplicateMethodsTestService', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any + (this._protos as any).google.duplicate_methods_test.v1 + .DuplicateMethodsTestService, + this._opts, + this._providedCustomServicePath, + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const duplicateMethodsTestServiceStubMethods = - ['getIamPolicy', 'listLocations', 'echo']; + const duplicateMethodsTestServiceStubMethods = [ + 'getIamPolicy', + 'listLocations', + 'echo', + ]; for (const methodName of duplicateMethodsTestServiceStubMethods) { const callPromise = this.duplicateMethodsTestServiceStub.then( - stub => (...args: Array<{}>) => { - if (this._terminated) { - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error|null|undefined) => () => { + (stub) => + (...args: Array<{}>) => { + if (this._terminated) { + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { throw err; - }); + }, + ); - const descriptor = - this.descriptors.page[methodName] || - undefined; + const descriptor = this.descriptors.page[methodName] || undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -283,8 +328,14 @@ export class DuplicateMethodsTestServiceClient { * @returns {string} The DNS address for this service. */ static get servicePath() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'duplicatemethodstest.googleapis.com'; } @@ -296,8 +347,14 @@ export class DuplicateMethodsTestServiceClient { * @returns {string} The DNS address for this service. */ static get apiEndpoint() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'duplicatemethodstest.googleapis.com'; } @@ -328,9 +385,7 @@ export class DuplicateMethodsTestServiceClient { * @returns {string[]} List of default scopes. */ static get scopes() { - return [ - 'https://www.googleapis.com/auth/cloud-platform' - ]; + return ['https://www.googleapis.com/auth/cloud-platform']; } getProjectId(): Promise; @@ -339,8 +394,9 @@ export class DuplicateMethodsTestServiceClient { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId(callback?: Callback): - Promise|void { + getProjectId( + callback?: Callback, + ): Promise | void { if (callback) { this.auth.getProjectId(callback); return; @@ -351,274 +407,360 @@ export class DuplicateMethodsTestServiceClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Native GetIamPolicy method that conflicts with the IAMPolicy mixin. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.resource - * REQUIRED: The resource for which the policy is being requested. - * See the operation documentation for the appropriate value for this field. - * @param {google.iam.v1.GetPolicyOptions} request.options - * OPTIONAL: A `GetPolicyOptions` object for specifying options to - * `GetIamPolicy`. This field is only used by Cloud IAM. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.iam.v1.Policy|Policy}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1/duplicate_methods_test_service.get_iam_policy.js - * region_tag:duplicatemethodstest_v1_generated_DuplicateMethodsTestService_GetIamPolicy_async - */ + /** + * Native GetIamPolicy method that conflicts with the IAMPolicy mixin. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.resource + * REQUIRED: The resource for which the policy is being requested. + * See the operation documentation for the appropriate value for this field. + * @param {google.iam.v1.GetPolicyOptions} request.options + * OPTIONAL: A `GetPolicyOptions` object for specifying options to + * `GetIamPolicy`. This field is only used by Cloud IAM. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.iam.v1.Policy|Policy}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/duplicate_methods_test_service.get_iam_policy.js + * region_tag:duplicatemethodstest_v1_generated_DuplicateMethodsTestService_GetIamPolicy_async + */ getIamPolicy( - request?: protos.google.iam.v1.IGetIamPolicyRequest, - options?: CallOptions): - Promise<[ - protos.google.iam.v1.IPolicy, - protos.google.iam.v1.IGetIamPolicyRequest|undefined, {}|undefined - ]>; + request?: protos.google.iam.v1.IGetIamPolicyRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.iam.v1.IPolicy, + protos.google.iam.v1.IGetIamPolicyRequest | undefined, + {} | undefined, + ] + >; getIamPolicy( - request: protos.google.iam.v1.IGetIamPolicyRequest, - options: CallOptions, - callback: Callback< - protos.google.iam.v1.IPolicy, - protos.google.iam.v1.IGetIamPolicyRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.iam.v1.IGetIamPolicyRequest, + options: CallOptions, + callback: Callback< + protos.google.iam.v1.IPolicy, + protos.google.iam.v1.IGetIamPolicyRequest | null | undefined, + {} | null | undefined + >, + ): void; getIamPolicy( - request: protos.google.iam.v1.IGetIamPolicyRequest, - callback: Callback< - protos.google.iam.v1.IPolicy, - protos.google.iam.v1.IGetIamPolicyRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.iam.v1.IGetIamPolicyRequest, + callback: Callback< + protos.google.iam.v1.IPolicy, + protos.google.iam.v1.IGetIamPolicyRequest | null | undefined, + {} | null | undefined + >, + ): void; getIamPolicy( - request?: protos.google.iam.v1.IGetIamPolicyRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.iam.v1.IPolicy, - protos.google.iam.v1.IGetIamPolicyRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.iam.v1.IGetIamPolicyRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.iam.v1.IPolicy, - protos.google.iam.v1.IGetIamPolicyRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.iam.v1.IPolicy, - protos.google.iam.v1.IGetIamPolicyRequest|undefined, {}|undefined - ]>|void { + protos.google.iam.v1.IGetIamPolicyRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.iam.v1.IPolicy, + protos.google.iam.v1.IGetIamPolicyRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.iam.v1.IPolicy, + protos.google.iam.v1.IGetIamPolicyRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'resource': request.resource ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + resource: request.resource ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getIamPolicy request %j', request); - const wrappedCallback: Callback< - protos.google.iam.v1.IPolicy, - protos.google.iam.v1.IGetIamPolicyRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.iam.v1.IPolicy, + protos.google.iam.v1.IGetIamPolicyRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getIamPolicy response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.getIamPolicy(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.iam.v1.IPolicy, - protos.google.iam.v1.IGetIamPolicyRequest|undefined, {}|undefined - ]) => { - this._log.info('getIamPolicy response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getIamPolicy(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.iam.v1.IPolicy, + protos.google.iam.v1.IGetIamPolicyRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getIamPolicy response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Another native method to ensure the service is valid and has other methods. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.content - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.duplicate_methods_test.v1.EchoResponse|EchoResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1/duplicate_methods_test_service.echo.js - * region_tag:duplicatemethodstest_v1_generated_DuplicateMethodsTestService_Echo_async - */ + /** + * Another native method to ensure the service is valid and has other methods. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.content + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.duplicate_methods_test.v1.EchoResponse|EchoResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/duplicate_methods_test_service.echo.js + * region_tag:duplicatemethodstest_v1_generated_DuplicateMethodsTestService_Echo_async + */ echo( - request?: protos.google.duplicate_methods_test.v1.IEchoRequest, - options?: CallOptions): - Promise<[ - protos.google.duplicate_methods_test.v1.IEchoResponse, - protos.google.duplicate_methods_test.v1.IEchoRequest|undefined, {}|undefined - ]>; + request?: protos.google.duplicate_methods_test.v1.IEchoRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.duplicate_methods_test.v1.IEchoResponse, + protos.google.duplicate_methods_test.v1.IEchoRequest | undefined, + {} | undefined, + ] + >; echo( - request: protos.google.duplicate_methods_test.v1.IEchoRequest, - options: CallOptions, - callback: Callback< - protos.google.duplicate_methods_test.v1.IEchoResponse, - protos.google.duplicate_methods_test.v1.IEchoRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.duplicate_methods_test.v1.IEchoRequest, + options: CallOptions, + callback: Callback< + protos.google.duplicate_methods_test.v1.IEchoResponse, + protos.google.duplicate_methods_test.v1.IEchoRequest | null | undefined, + {} | null | undefined + >, + ): void; echo( - request: protos.google.duplicate_methods_test.v1.IEchoRequest, - callback: Callback< - protos.google.duplicate_methods_test.v1.IEchoResponse, - protos.google.duplicate_methods_test.v1.IEchoRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.duplicate_methods_test.v1.IEchoRequest, + callback: Callback< + protos.google.duplicate_methods_test.v1.IEchoResponse, + protos.google.duplicate_methods_test.v1.IEchoRequest | null | undefined, + {} | null | undefined + >, + ): void; echo( - request?: protos.google.duplicate_methods_test.v1.IEchoRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.duplicate_methods_test.v1.IEchoResponse, - protos.google.duplicate_methods_test.v1.IEchoRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.duplicate_methods_test.v1.IEchoRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.duplicate_methods_test.v1.IEchoResponse, - protos.google.duplicate_methods_test.v1.IEchoRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.duplicate_methods_test.v1.IEchoResponse, - protos.google.duplicate_methods_test.v1.IEchoRequest|undefined, {}|undefined - ]>|void { + | protos.google.duplicate_methods_test.v1.IEchoRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.duplicate_methods_test.v1.IEchoResponse, + protos.google.duplicate_methods_test.v1.IEchoRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.duplicate_methods_test.v1.IEchoResponse, + protos.google.duplicate_methods_test.v1.IEchoRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('echo request %j', request); - const wrappedCallback: Callback< - protos.google.duplicate_methods_test.v1.IEchoResponse, - protos.google.duplicate_methods_test.v1.IEchoRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.duplicate_methods_test.v1.IEchoResponse, + | protos.google.duplicate_methods_test.v1.IEchoRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('echo response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.echo(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.duplicate_methods_test.v1.IEchoResponse, - protos.google.duplicate_methods_test.v1.IEchoRequest|undefined, {}|undefined - ]) => { - this._log.info('echo response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .echo(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.duplicate_methods_test.v1.IEchoResponse, + protos.google.duplicate_methods_test.v1.IEchoRequest | undefined, + {} | undefined, + ]) => { + this._log.info('echo response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } - /** - * Native ListLocations method that conflicts with the Locations mixin. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * The resource that owns the locations collection, if applicable. - * @param {string} request.filter - * The standard list filter. - * @param {number} request.pageSize - * The standard list page size. - * @param {string} request.pageToken - * The standard list page token. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.cloud.location.Location|Location}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `listLocationsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Native ListLocations method that conflicts with the Locations mixin. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * The resource that owns the locations collection, if applicable. + * @param {string} request.filter + * The standard list filter. + * @param {number} request.pageSize + * The standard list page size. + * @param {string} request.pageToken + * The standard list page token. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.cloud.location.Location|Location}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listLocationsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listLocations( - request?: protos.google.cloud.location.IListLocationsRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.location.ILocation[], - protos.google.cloud.location.IListLocationsRequest|null, - protos.google.cloud.location.IListLocationsResponse - ]>; + request?: protos.google.cloud.location.IListLocationsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.location.ILocation[], + protos.google.cloud.location.IListLocationsRequest | null, + protos.google.cloud.location.IListLocationsResponse, + ] + >; listLocations( - request: protos.google.cloud.location.IListLocationsRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.cloud.location.IListLocationsRequest, - protos.google.cloud.location.IListLocationsResponse|null|undefined, - protos.google.cloud.location.ILocation>): void; + request: protos.google.cloud.location.IListLocationsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.cloud.location.IListLocationsRequest, + protos.google.cloud.location.IListLocationsResponse | null | undefined, + protos.google.cloud.location.ILocation + >, + ): void; listLocations( - request: protos.google.cloud.location.IListLocationsRequest, - callback: PaginationCallback< - protos.google.cloud.location.IListLocationsRequest, - protos.google.cloud.location.IListLocationsResponse|null|undefined, - protos.google.cloud.location.ILocation>): void; + request: protos.google.cloud.location.IListLocationsRequest, + callback: PaginationCallback< + protos.google.cloud.location.IListLocationsRequest, + protos.google.cloud.location.IListLocationsResponse | null | undefined, + protos.google.cloud.location.ILocation + >, + ): void; listLocations( - request?: protos.google.cloud.location.IListLocationsRequest, - optionsOrCallback?: CallOptions|PaginationCallback< - protos.google.cloud.location.IListLocationsRequest, - protos.google.cloud.location.IListLocationsResponse|null|undefined, - protos.google.cloud.location.ILocation>, - callback?: PaginationCallback< + request?: protos.google.cloud.location.IListLocationsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.cloud.location.IListLocationsRequest, - protos.google.cloud.location.IListLocationsResponse|null|undefined, - protos.google.cloud.location.ILocation>): - Promise<[ - protos.google.cloud.location.ILocation[], - protos.google.cloud.location.IListLocationsRequest|null, - protos.google.cloud.location.IListLocationsResponse - ]>|void { + | protos.google.cloud.location.IListLocationsResponse + | null + | undefined, + protos.google.cloud.location.ILocation + >, + callback?: PaginationCallback< + protos.google.cloud.location.IListLocationsRequest, + protos.google.cloud.location.IListLocationsResponse | null | undefined, + protos.google.cloud.location.ILocation + >, + ): Promise< + [ + protos.google.cloud.location.ILocation[], + protos.google.cloud.location.IListLocationsRequest | null, + protos.google.cloud.location.IListLocationsResponse, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.cloud.location.IListLocationsRequest, - protos.google.cloud.location.IListLocationsResponse|null|undefined, - protos.google.cloud.location.ILocation>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.cloud.location.IListLocationsRequest, + | protos.google.cloud.location.IListLocationsResponse + | null + | undefined, + protos.google.cloud.location.ILocation + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listLocations values %j', values); callback!(error, values, nextPageRequest, rawResponse); @@ -627,167 +769,171 @@ export class DuplicateMethodsTestServiceClient { this._log.info('listLocations request %j', request); return this.innerApiCalls .listLocations(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.cloud.location.ILocation[], - protos.google.cloud.location.IListLocationsRequest|null, - protos.google.cloud.location.IListLocationsResponse - ]) => { - this._log.info('listLocations values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.cloud.location.ILocation[], + protos.google.cloud.location.IListLocationsRequest | null, + protos.google.cloud.location.IListLocationsResponse, + ]) => { + this._log.info('listLocations values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listLocations`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * The resource that owns the locations collection, if applicable. - * @param {string} request.filter - * The standard list filter. - * @param {number} request.pageSize - * The standard list page size. - * @param {string} request.pageToken - * The standard list page token. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.cloud.location.Location|Location} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `listLocationsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `listLocations`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * The resource that owns the locations collection, if applicable. + * @param {string} request.filter + * The standard list filter. + * @param {number} request.pageSize + * The standard list page size. + * @param {string} request.pageToken + * The standard list page token. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.cloud.location.Location|Location} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listLocationsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listLocationsStream( - request?: protos.google.cloud.location.IListLocationsRequest, - options?: CallOptions): - Transform{ + request?: protos.google.cloud.location.IListLocationsRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); const defaultCallSettings = this._defaults['listLocations']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listLocations stream %j', request); return this.descriptors.page.listLocations.createStream( this.innerApiCalls.listLocations as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listLocations`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * The resource that owns the locations collection, if applicable. - * @param {string} request.filter - * The standard list filter. - * @param {number} request.pageSize - * The standard list page size. - * @param {string} request.pageToken - * The standard list page token. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.cloud.location.Location|Location}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v1/duplicate_methods_test_service.list_locations.js - * region_tag:duplicatemethodstest_v1_generated_DuplicateMethodsTestService_ListLocations_async - */ + /** + * Equivalent to `listLocations`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * The resource that owns the locations collection, if applicable. + * @param {string} request.filter + * The standard list filter. + * @param {number} request.pageSize + * The standard list page size. + * @param {string} request.pageToken + * The standard list page token. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.cloud.location.Location|Location}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v1/duplicate_methods_test_service.list_locations.js + * region_tag:duplicatemethodstest_v1_generated_DuplicateMethodsTestService_ListLocations_async + */ listLocationsAsync( - request?: protos.google.cloud.location.IListLocationsRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.cloud.location.IListLocationsRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); const defaultCallSettings = this._defaults['listLocations']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listLocations iterate %j', request); return this.descriptors.page.listLocations.asyncIterate( this.innerApiCalls['listLocations'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } -/** - * Gets the access control policy for a resource. Returns an empty policy - * if the resource exists and does not have a policy set. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.resource - * REQUIRED: The resource for which the policy is being requested. - * See the operation documentation for the appropriate value for this field. - * @param {Object} [request.options] - * OPTIONAL: A `GetPolicyOptions` object for specifying options to - * `GetIamPolicy`. This field is only used by Cloud IAM. - * - * This object should have the same structure as {@link google.iam.v1.GetPolicyOptions | GetPolicyOptions}. - * @param {Object} [options] - * Optional parameters. You can override the default settings for this call, e.g, timeout, - * retries, paginations, etc. See {@link https://googleapis.github.io/gax-nodejs/interfaces/CallOptions.html | gax.CallOptions} for the details. - * @param {function(?Error, ?Object)} [callback] - * The function which will be called with the result of the API call. - * - * The second parameter to the callback is an object representing {@link google.iam.v1.Policy | Policy}. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link google.iam.v1.Policy | Policy}. - * The promise has a method named "cancel" which cancels the ongoing API call. - */ + /** + * Gets the access control policy for a resource. Returns an empty policy + * if the resource exists and does not have a policy set. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.resource + * REQUIRED: The resource for which the policy is being requested. + * See the operation documentation for the appropriate value for this field. + * @param {Object} [request.options] + * OPTIONAL: A `GetPolicyOptions` object for specifying options to + * `GetIamPolicy`. This field is only used by Cloud IAM. + * + * This object should have the same structure as {@link google.iam.v1.GetPolicyOptions | GetPolicyOptions}. + * @param {Object} [options] + * Optional parameters. You can override the default settings for this call, e.g, timeout, + * retries, paginations, etc. See {@link https://googleapis.github.io/gax-nodejs/interfaces/CallOptions.html | gax.CallOptions} for the details. + * @param {function(?Error, ?Object)} [callback] + * The function which will be called with the result of the API call. + * + * The second parameter to the callback is an object representing {@link google.iam.v1.Policy | Policy}. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link google.iam.v1.Policy | Policy}. + * The promise has a method named "cancel" which cancels the ongoing API call. + */ -/** - * Returns permissions that a caller has on the specified resource. If the - * resource does not exist, this will return an empty set of - * permissions, not a NOT_FOUND error. - * - * Note: This operation is designed to be used for building - * permission-aware UIs and command-line tools, not for authorization - * checking. This operation may "fail open" without warning. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.resource - * REQUIRED: The resource for which the policy detail is being requested. - * See the operation documentation for the appropriate value for this field. - * @param {string[]} request.permissions - * The set of permissions to check for the `resource`. Permissions with - * wildcards (such as '*' or 'storage.*') are not allowed. For more - * information see {@link https://cloud.google.com/iam/docs/overview#permissions | IAM Overview }. - * @param {Object} [options] - * Optional parameters. You can override the default settings for this call, e.g, timeout, - * retries, paginations, etc. See {@link https://googleapis.github.io/gax-nodejs/interfaces/CallOptions.html | gax.CallOptions} for the details. - * @param {function(?Error, ?Object)} [callback] - * The function which will be called with the result of the API call. - * - * The second parameter to the callback is an object representing {@link google.iam.v1.TestIamPermissionsResponse | TestIamPermissionsResponse}. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link google.iam.v1.TestIamPermissionsResponse | TestIamPermissionsResponse}. - * The promise has a method named "cancel" which cancels the ongoing API call. - */ + /** + * Returns permissions that a caller has on the specified resource. If the + * resource does not exist, this will return an empty set of + * permissions, not a NOT_FOUND error. + * + * Note: This operation is designed to be used for building + * permission-aware UIs and command-line tools, not for authorization + * checking. This operation may "fail open" without warning. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.resource + * REQUIRED: The resource for which the policy detail is being requested. + * See the operation documentation for the appropriate value for this field. + * @param {string[]} request.permissions + * The set of permissions to check for the `resource`. Permissions with + * wildcards (such as '*' or 'storage.*') are not allowed. For more + * information see {@link https://cloud.google.com/iam/docs/overview#permissions | IAM Overview }. + * @param {Object} [options] + * Optional parameters. You can override the default settings for this call, e.g, timeout, + * retries, paginations, etc. See {@link https://googleapis.github.io/gax-nodejs/interfaces/CallOptions.html | gax.CallOptions} for the details. + * @param {function(?Error, ?Object)} [callback] + * The function which will be called with the result of the API call. + * + * The second parameter to the callback is an object representing {@link google.iam.v1.TestIamPermissionsResponse | TestIamPermissionsResponse}. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link google.iam.v1.TestIamPermissionsResponse | TestIamPermissionsResponse}. + * The promise has a method named "cancel" which cancels the ongoing API call. + */ setIamPolicy( request: IamProtos.google.iam.v1.SetIamPolicyRequest, options?: @@ -801,41 +947,41 @@ export class DuplicateMethodsTestServiceClient { IamProtos.google.iam.v1.Policy, IamProtos.google.iam.v1.SetIamPolicyRequest | null | undefined, {} | null | undefined - > - ):Promise<[IamProtos.google.iam.v1.Policy]> { + >, + ): Promise<[IamProtos.google.iam.v1.Policy]> { return this.iamClient.setIamPolicy(request, options, callback); } -/** - * Returns permissions that a caller has on the specified resource. If the - * resource does not exist, this will return an empty set of - * permissions, not a NOT_FOUND error. - * - * Note: This operation is designed to be used for building - * permission-aware UIs and command-line tools, not for authorization - * checking. This operation may "fail open" without warning. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.resource - * REQUIRED: The resource for which the policy detail is being requested. - * See the operation documentation for the appropriate value for this field. - * @param {string[]} request.permissions - * The set of permissions to check for the `resource`. Permissions with - * wildcards (such as '*' or 'storage.*') are not allowed. For more - * information see {@link https://cloud.google.com/iam/docs/overview#permissions | IAM Overview }. - * @param {Object} [options] - * Optional parameters. You can override the default settings for this call, e.g, timeout, - * retries, paginations, etc. See {@link https://googleapis.github.io/gax-nodejs/interfaces/CallOptions.html | gax.CallOptions} for the details. - * @param {function(?Error, ?Object)} [callback] - * The function which will be called with the result of the API call. - * - * The second parameter to the callback is an object representing {@link google.iam.v1.TestIamPermissionsResponse | TestIamPermissionsResponse}. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link google.iam.v1.TestIamPermissionsResponse | TestIamPermissionsResponse}. - * The promise has a method named "cancel" which cancels the ongoing API call. - * - */ + /** + * Returns permissions that a caller has on the specified resource. If the + * resource does not exist, this will return an empty set of + * permissions, not a NOT_FOUND error. + * + * Note: This operation is designed to be used for building + * permission-aware UIs and command-line tools, not for authorization + * checking. This operation may "fail open" without warning. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.resource + * REQUIRED: The resource for which the policy detail is being requested. + * See the operation documentation for the appropriate value for this field. + * @param {string[]} request.permissions + * The set of permissions to check for the `resource`. Permissions with + * wildcards (such as '*' or 'storage.*') are not allowed. For more + * information see {@link https://cloud.google.com/iam/docs/overview#permissions | IAM Overview }. + * @param {Object} [options] + * Optional parameters. You can override the default settings for this call, e.g, timeout, + * retries, paginations, etc. See {@link https://googleapis.github.io/gax-nodejs/interfaces/CallOptions.html | gax.CallOptions} for the details. + * @param {function(?Error, ?Object)} [callback] + * The function which will be called with the result of the API call. + * + * The second parameter to the callback is an object representing {@link google.iam.v1.TestIamPermissionsResponse | TestIamPermissionsResponse}. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link google.iam.v1.TestIamPermissionsResponse | TestIamPermissionsResponse}. + * The promise has a method named "cancel" which cancels the ongoing API call. + * + */ testIamPermissions( request: IamProtos.google.iam.v1.TestIamPermissionsRequest, options?: @@ -849,13 +995,12 @@ export class DuplicateMethodsTestServiceClient { IamProtos.google.iam.v1.TestIamPermissionsResponse, IamProtos.google.iam.v1.TestIamPermissionsRequest | null | undefined, {} | null | undefined - > - ):Promise<[IamProtos.google.iam.v1.TestIamPermissionsResponse]> { + >, + ): Promise<[IamProtos.google.iam.v1.TestIamPermissionsResponse]> { return this.iamClient.testIamPermissions(request, options, callback); } - - /** + /** * Gets information about a location. * * @param {Object} request @@ -890,12 +1035,11 @@ export class DuplicateMethodsTestServiceClient { | null | undefined, {} | null | undefined - > + >, ): Promise { return this.locationsClient.getLocation(request, options, callback); } - /** * Terminate the gRPC channel and close the client. * @@ -904,14 +1048,18 @@ export class DuplicateMethodsTestServiceClient { */ close(): Promise { if (this.duplicateMethodsTestServiceStub && !this._terminated) { - return this.duplicateMethodsTestServiceStub.then(stub => { + return this.duplicateMethodsTestServiceStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); - this.iamClient.close().catch(err => {throw err}); - this.locationsClient.close().catch(err => {throw err}); + this.iamClient.close().catch((err) => { + throw err; + }); + this.locationsClient.close().catch((err) => { + throw err; + }); }); } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/core/generator/gapic-generator-typescript/baselines/duplicate_methods_test-esm/esm/src/v1/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/duplicate_methods_test-esm/esm/src/v1/index.ts.baseline index 0104bde3222f..702c1380581d 100644 --- a/core/generator/gapic-generator-typescript/baselines/duplicate_methods_test-esm/esm/src/v1/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/duplicate_methods_test-esm/esm/src/v1/index.ts.baseline @@ -16,4 +16,4 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -export {DuplicateMethodsTestServiceClient} from './duplicate_methods_test_service_client.js'; +export { DuplicateMethodsTestServiceClient } from './duplicate_methods_test_service_client.js'; diff --git a/core/generator/gapic-generator-typescript/baselines/duplicate_methods_test-esm/esm/system-test/fixtures/sample/src/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/duplicate_methods_test-esm/esm/system-test/fixtures/sample/src/index.ts.baseline index b5b59ab82822..2aab4c8464eb 100644 --- a/core/generator/gapic-generator-typescript/baselines/duplicate_methods_test-esm/esm/system-test/fixtures/sample/src/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/duplicate_methods_test-esm/esm/system-test/fixtures/sample/src/index.ts.baseline @@ -17,17 +17,22 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -import {DuplicateMethodsTestServiceClient} from 'duplicate-methods-test'; +import { DuplicateMethodsTestServiceClient } from 'duplicate-methods-test'; // check that the client class type name can be used -function doStuffWithDuplicateMethodsTestServiceClient(client: DuplicateMethodsTestServiceClient) { +function doStuffWithDuplicateMethodsTestServiceClient( + client: DuplicateMethodsTestServiceClient, +) { client.close(); } function main() { // check that the client instance can be created - const duplicateMethodsTestServiceClient = new DuplicateMethodsTestServiceClient(); - doStuffWithDuplicateMethodsTestServiceClient(duplicateMethodsTestServiceClient); + const duplicateMethodsTestServiceClient = + new DuplicateMethodsTestServiceClient(); + doStuffWithDuplicateMethodsTestServiceClient( + duplicateMethodsTestServiceClient, + ); } main(); diff --git a/core/generator/gapic-generator-typescript/baselines/duplicate_methods_test-esm/esm/system-test/install.ts.baseline b/core/generator/gapic-generator-typescript/baselines/duplicate_methods_test-esm/esm/system-test/install.ts.baseline index e079c4fa1101..d109fdd8c97f 100644 --- a/core/generator/gapic-generator-typescript/baselines/duplicate_methods_test-esm/esm/system-test/install.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/duplicate_methods_test-esm/esm/system-test/install.ts.baseline @@ -16,40 +16,45 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -import {packNTest} from 'pack-n-play'; -import {readFileSync} from 'fs'; -import {describe, it} from 'mocha'; +import { packNTest } from 'pack-n-play'; +import { readFileSync } from 'fs'; +import { describe, it } from 'mocha'; describe('📦 pack-n-play test', () => { - it('TypeScript', async function() { + it('TypeScript', async function () { this.timeout(300000); await packNTest({ packageDir: process.cwd(), sample: { description: 'TypeScript user can use the type definitions', - ts: readFileSync('./esm/system-test/fixtures/sample/src/index.ts').toString() - } + ts: readFileSync( + './esm/system-test/fixtures/sample/src/index.ts', + ).toString(), + }, }); }); - it('ESM module', async function() { + it('ESM module', async function () { this.timeout(300000); await packNTest({ sample: { description: 'Should be able to import using ESM', - esm: readFileSync('./esm/system-test/fixtures/sample/src/index.js').toString(), + esm: readFileSync( + './esm/system-test/fixtures/sample/src/index.js', + ).toString(), }, }); }); - it('CJS module', async function() { + it('CJS module', async function () { this.timeout(300000); await packNTest({ sample: { description: 'Should be able to import using CJS', - cjs: readFileSync('./esm/system-test/fixtures/sample/src/index.cjs').toString(), + cjs: readFileSync( + './esm/system-test/fixtures/sample/src/index.cjs', + ).toString(), }, }); }); - }); diff --git a/core/generator/gapic-generator-typescript/baselines/duplicate_methods_test-esm/esm/test/gapic_duplicate_methods_test_service_v1.ts.baseline b/core/generator/gapic-generator-typescript/baselines/duplicate_methods_test-esm/esm/test/gapic_duplicate_methods_test_service_v1.ts.baseline index ad48c9cffc7b..9fdfb3fa7ccf 100644 --- a/core/generator/gapic-generator-typescript/baselines/duplicate_methods_test-esm/esm/test/gapic_duplicate_methods_test_service_v1.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/duplicate_methods_test-esm/esm/test/gapic_duplicate_methods_test_service_v1.ts.baseline @@ -20,16 +20,16 @@ import * as protos from '../../protos/protos.js'; import assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as duplicatemethodstestserviceModule from '../src/index.js'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; -import {protobuf, IamProtos, LocationProtos} from 'google-gax'; +import { protobuf, IamProtos, LocationProtos } from 'google-gax'; import fs from 'fs'; import path from 'path'; -import {fileURLToPath} from 'url'; +import { fileURLToPath } from 'url'; // @ts-ignore const dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -37,941 +37,1240 @@ const dirname = path.dirname(fileURLToPath(import.meta.url)); // to fill in default values for request objects const root = protobuf.Root.fromJSON( JSON.parse( - fs.readFileSync(path.join(dirname, '..', '..', 'protos/protos.json'), 'utf8') - )) + fs.readFileSync( + path.join(dirname, '..', '..', 'protos/protos.json'), + 'utf8', + ), + ), +); // eslint-disable-next-line @typescript-eslint/no-unused-vars function getTypeDefaultValue(typeName: string, fields: string[]) { - let type = root.lookupType(typeName) as protobuf.Type; - for (const field of fields.slice(0, -1)) { - type = type?.fields[field]?.resolvedType as protobuf.Type; - } - return type?.fields[fields[fields.length - 1]]?.defaultValue ?? null; + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type?.fields[field]?.resolvedType as protobuf.Type; + } + return type?.fields[fields[fields.length - 1]]?.defaultValue ?? null; } function generateSampleMessage(instance: T) { - const filledObject = (instance.constructor as typeof protobuf.Message) - .toObject(instance as protobuf.Message, {defaults: true}); - return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, { defaults: true }); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; } function stubSimpleCall(response?: ResponseType, error?: Error) { - return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); } -function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { - return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +function stubSimpleCallWithCallback( + response?: ResponseType, + error?: Error, +) { + return error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); } -function stubPageStreamingCall(responses?: ResponseType[], error?: Error) { - const pagingStub = sinon.stub(); - if (responses) { - for (let i = 0; i < responses.length; ++i) { - pagingStub.onCall(i).callsArgWith(2, null, responses[i]); - } +function stubPageStreamingCall( + responses?: ResponseType[], + error?: Error, +) { + const pagingStub = sinon.stub(); + if (responses) { + for (let i = 0; i < responses.length; ++i) { + pagingStub.onCall(i).callsArgWith(2, null, responses[i]); } - const transformStub = error ? sinon.stub().callsArgWith(2, error) : pagingStub; - const mockStream = new PassThrough({ - objectMode: true, - transform: transformStub, - }); - // trigger as many responses as needed - if (responses) { - for (let i = 0; i < responses.length; ++i) { - setImmediate(() => { mockStream.write({}); }); - } - setImmediate(() => { mockStream.end(); }); - } else { - setImmediate(() => { mockStream.write({}); }); - setImmediate(() => { mockStream.end(); }); + } + const transformStub = error + ? sinon.stub().callsArgWith(2, error) + : pagingStub; + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + // trigger as many responses as needed + if (responses) { + for (let i = 0; i < responses.length; ++i) { + setImmediate(() => { + mockStream.write({}); + }); } - return sinon.stub().returns(mockStream); + setImmediate(() => { + mockStream.end(); + }); + } else { + setImmediate(() => { + mockStream.write({}); + }); + setImmediate(() => { + mockStream.end(); + }); + } + return sinon.stub().returns(mockStream); } -function stubAsyncIterationCall(responses?: ResponseType[], error?: Error) { - let counter = 0; - const asyncIterable = { - [Symbol.asyncIterator]() { - return { - async next() { - if (error) { - return Promise.reject(error); - } - if (counter >= responses!.length) { - return Promise.resolve({done: true, value: undefined}); - } - return Promise.resolve({done: false, value: responses![counter++]}); - } - }; - } - }; - return sinon.stub().returns(asyncIterable); +function stubAsyncIterationCall( + responses?: ResponseType[], + error?: Error, +) { + let counter = 0; + const asyncIterable = { + [Symbol.asyncIterator]() { + return { + async next() { + if (error) { + return Promise.reject(error); + } + if (counter >= responses!.length) { + return Promise.resolve({ done: true, value: undefined }); + } + return Promise.resolve({ done: false, value: responses![counter++] }); + }, + }; + }, + }; + return sinon.stub().returns(asyncIterable); } describe('v1.DuplicateMethodsTestServiceClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'duplicatemethodstest.googleapis.com'); - }); - - it('has universeDomain', () => { - const client = new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); - - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - it('throws DeprecationWarning if static servicePath is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const servicePath = duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient.servicePath; - assert.strictEqual(servicePath, 'duplicatemethodstest.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'duplicatemethodstest.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'duplicatemethodstest.example.com'); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = + new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'duplicatemethodstest.googleapis.com'); + }); - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'duplicatemethodstest.example.com'); - }); + it('has universeDomain', () => { + const client = + new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - if (typeof process === 'object' && 'env' in process) { - describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { - it('sets apiEndpoint from environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'duplicatemethodstest.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - - it('value configured in code has priority over environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'duplicatemethodstest.configured.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = + duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient + .servicePath; + assert.strictEqual(servicePath, 'duplicatemethodstest.googleapis.com'); + assert(stub.called); + stub.restore(); + }); - it('has port', () => { - const port = duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient.port; - assert(port); - assert(typeof port === 'number'); - }); + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient + .apiEndpoint; + assert.strictEqual(apiEndpoint, 'duplicatemethodstest.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = + new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient( + { universeDomain: 'example.com' }, + ); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'duplicatemethodstest.example.com'); + }); - it('should create a client with no option', () => { - const client = new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient(); - assert(client); - }); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = + new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient( + { universe_domain: 'example.com' }, + ); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'duplicatemethodstest.example.com'); + }); - it('should create a client with gRPC fallback', () => { - const client = new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient({ - fallback: true, - }); - assert(client); + if (typeof process === 'object' && 'env' in process) { + describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { + it('sets apiEndpoint from environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = + new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'duplicatemethodstest.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - it('has initialize method and supports deferred initialization', async () => { - const client = new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.duplicateMethodsTestServiceStub, undefined); - await client.initialize(); - assert(client.duplicateMethodsTestServiceStub); + it('value configured in code has priority over environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = + new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient( + { universeDomain: 'configured.example.com' }, + ); + const servicePath = client.apiEndpoint; + assert.strictEqual( + servicePath, + 'duplicatemethodstest.configured.example.com', + ); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient( + { universe_domain: 'example.com', universeDomain: 'example.net' }, + ); + }); + }); - it('has close method for the initialized client', done => { - const client = new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.duplicateMethodsTestServiceStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('has port', () => { + const port = + duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient + .port; + assert(port); + assert(typeof port === 'number'); + }); - it('has close method for the non-initialized client', done => { - const client = new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.duplicateMethodsTestServiceStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('should create a client with no option', () => { + const client = + new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient(); + assert(client); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); - }); + it('should create a client with gRPC fallback', () => { + const client = + new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient( + { + fallback: true, + }, + ); + assert(client); + }); - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId((err?: Error|null, projectId?: string|null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } - }); - }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); - }); + it('has initialize method and supports deferred initialization', async () => { + const client = + new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + assert.strictEqual(client.duplicateMethodsTestServiceStub, undefined); + await client.initialize(); + assert(client.duplicateMethodsTestServiceStub); }); - describe('getIamPolicy', () => { - it('invokes getIamPolicy without error', async () => { - const client = new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.iam.v1.GetIamPolicyRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.iam.v1.GetIamPolicyRequest', ['resource']); - request.resource = defaultValue1; - const expectedHeaderRequestParams = `resource=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.iam.v1.Policy() - ); - client.innerApiCalls.getIamPolicy = stubSimpleCall(expectedResponse); - const [response] = await client.getIamPolicy(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getIamPolicy as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getIamPolicy as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('has close method for the initialized client', (done) => { + const client = + new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + client.initialize().catch((err) => { + throw err; + }); + assert(client.duplicateMethodsTestServiceStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes getIamPolicy without error using callback', async () => { - const client = new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.iam.v1.GetIamPolicyRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.iam.v1.GetIamPolicyRequest', ['resource']); - request.resource = defaultValue1; - const expectedHeaderRequestParams = `resource=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.iam.v1.Policy() - ); - client.innerApiCalls.getIamPolicy = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getIamPolicy( - request, - (err?: Error|null, result?: protos.google.iam.v1.IPolicy|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getIamPolicy as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getIamPolicy as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('has close method for the non-initialized client', (done) => { + const client = + new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + assert.strictEqual(client.duplicateMethodsTestServiceStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes getIamPolicy with error', async () => { - const client = new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.iam.v1.GetIamPolicyRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.iam.v1.GetIamPolicyRequest', ['resource']); - request.resource = defaultValue1; - const expectedHeaderRequestParams = `resource=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getIamPolicy = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getIamPolicy(request), expectedError); - const actualRequest = (client.innerApiCalls.getIamPolicy as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getIamPolicy as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = + new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + }); - it('invokes getIamPolicy with closed client', async () => { - const client = new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.iam.v1.GetIamPolicyRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.iam.v1.GetIamPolicyRequest', ['resource']); - request.resource = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getIamPolicy(request), expectedError); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = + new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); }); + }); - describe('echo', () => { - it('invokes echo without error', async () => { - const client = new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.duplicate_methods_test.v1.EchoRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.duplicate_methods_test.v1.EchoResponse() - ); - client.innerApiCalls.echo = stubSimpleCall(expectedResponse); - const [response] = await client.echo(request); - assert.deepStrictEqual(response, expectedResponse); - }); + describe('getIamPolicy', () => { + it('invokes getIamPolicy without error', async () => { + const client = + new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.iam.v1.GetIamPolicyRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.iam.v1.GetIamPolicyRequest', + ['resource'], + ); + request.resource = defaultValue1; + const expectedHeaderRequestParams = `resource=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.iam.v1.Policy(), + ); + client.innerApiCalls.getIamPolicy = stubSimpleCall(expectedResponse); + const [response] = await client.getIamPolicy(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getIamPolicy as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getIamPolicy as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes echo without error using callback', async () => { - const client = new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.duplicate_methods_test.v1.EchoRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.duplicate_methods_test.v1.EchoResponse() - ); - client.innerApiCalls.echo = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.echo( - request, - (err?: Error|null, result?: protos.google.duplicate_methods_test.v1.IEchoResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes getIamPolicy without error using callback', async () => { + const client = + new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.iam.v1.GetIamPolicyRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.iam.v1.GetIamPolicyRequest', + ['resource'], + ); + request.resource = defaultValue1; + const expectedHeaderRequestParams = `resource=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.iam.v1.Policy(), + ); + client.innerApiCalls.getIamPolicy = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getIamPolicy( + request, + ( + err?: Error | null, + result?: protos.google.iam.v1.IPolicy | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getIamPolicy as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getIamPolicy as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes echo with error', async () => { - const client = new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.duplicate_methods_test.v1.EchoRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.echo = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.echo(request), expectedError); - }); + it('invokes getIamPolicy with error', async () => { + const client = + new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.iam.v1.GetIamPolicyRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.iam.v1.GetIamPolicyRequest', + ['resource'], + ); + request.resource = defaultValue1; + const expectedHeaderRequestParams = `resource=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getIamPolicy = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getIamPolicy(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getIamPolicy as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getIamPolicy as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes echo with closed client', async () => { - const client = new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.duplicate_methods_test.v1.EchoRequest() - ); - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.echo(request), expectedError); - }); + it('invokes getIamPolicy with closed client', async () => { + const client = + new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.iam.v1.GetIamPolicyRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.iam.v1.GetIamPolicyRequest', + ['resource'], + ); + request.resource = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getIamPolicy(request), expectedError); }); + }); - describe('listLocations', () => { - it('invokes listLocations without error', async () => { - const client = new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.location.ListLocationsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.location.ListLocationsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.location.Location()), - generateSampleMessage(new protos.google.cloud.location.Location()), - generateSampleMessage(new protos.google.cloud.location.Location()), - ]; - client.innerApiCalls.listLocations = stubSimpleCall(expectedResponse); - const [response] = await client.listLocations(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listLocations as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listLocations as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + describe('echo', () => { + it('invokes echo without error', async () => { + const client = + new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.duplicate_methods_test.v1.EchoRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.duplicate_methods_test.v1.EchoResponse(), + ); + client.innerApiCalls.echo = stubSimpleCall(expectedResponse); + const [response] = await client.echo(request); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes listLocations without error using callback', async () => { - const client = new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.location.ListLocationsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.location.ListLocationsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.location.Location()), - generateSampleMessage(new protos.google.cloud.location.Location()), - generateSampleMessage(new protos.google.cloud.location.Location()), - ]; - client.innerApiCalls.listLocations = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listLocations( - request, - (err?: Error|null, result?: protos.google.cloud.location.ILocation[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listLocations as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listLocations as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes echo without error using callback', async () => { + const client = + new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.duplicate_methods_test.v1.EchoRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.duplicate_methods_test.v1.EchoResponse(), + ); + client.innerApiCalls.echo = stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.echo( + request, + ( + err?: Error | null, + result?: protos.google.duplicate_methods_test.v1.IEchoResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes listLocations with error', async () => { - const client = new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.location.ListLocationsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.location.ListLocationsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listLocations = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listLocations(request), expectedError); - const actualRequest = (client.innerApiCalls.listLocations as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listLocations as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes echo with error', async () => { + const client = + new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.duplicate_methods_test.v1.EchoRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.echo = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.echo(request), expectedError); + }); - it('invokes listLocationsStream without error', async () => { - const client = new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.location.ListLocationsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.location.ListLocationsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.location.Location()), - generateSampleMessage(new protos.google.cloud.location.Location()), - generateSampleMessage(new protos.google.cloud.location.Location()), - ]; - client.descriptors.page.listLocations.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listLocationsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.cloud.location.Location[] = []; - stream.on('data', (response: protos.google.cloud.location.Location) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.listLocations.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listLocations, request)); - assert( - (client.descriptors.page.listLocations.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes echo with closed client', async () => { + const client = + new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.duplicate_methods_test.v1.EchoRequest(), + ); + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.echo(request), expectedError); + }); + }); - it('invokes listLocationsStream with error', async () => { - const client = new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.location.ListLocationsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.location.ListLocationsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listLocations.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listLocationsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.cloud.location.Location[] = []; - stream.on('data', (response: protos.google.cloud.location.Location) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listLocations.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listLocations, request)); - assert( - (client.descriptors.page.listLocations.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + describe('listLocations', () => { + it('invokes listLocations without error', async () => { + const client = + new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.location.ListLocationsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.location.ListLocationsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.location.Location()), + generateSampleMessage(new protos.google.cloud.location.Location()), + generateSampleMessage(new protos.google.cloud.location.Location()), + ]; + client.innerApiCalls.listLocations = stubSimpleCall(expectedResponse); + const [response] = await client.listLocations(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listLocations as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listLocations as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('uses async iteration with listLocations without error', async () => { - const client = new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.location.ListLocationsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.location.ListLocationsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.location.Location()), - generateSampleMessage(new protos.google.cloud.location.Location()), - generateSampleMessage(new protos.google.cloud.location.Location()), - ]; - client.descriptors.page.listLocations.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.cloud.location.ILocation[] = []; - const iterable = client.listLocationsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); + it('invokes listLocations without error using callback', async () => { + const client = + new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.location.ListLocationsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.location.ListLocationsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.location.Location()), + generateSampleMessage(new protos.google.cloud.location.Location()), + generateSampleMessage(new protos.google.cloud.location.Location()), + ]; + client.innerApiCalls.listLocations = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listLocations( + request, + ( + err?: Error | null, + result?: protos.google.cloud.location.ILocation[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listLocations.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listLocations.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listLocations as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listLocations as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('uses async iteration with listLocations with error', async () => { - const client = new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.location.ListLocationsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.location.ListLocationsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listLocations.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listLocationsAsync(request); - await assert.rejects(async () => { - const responses: protos.google.cloud.location.ILocation[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listLocations.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listLocations.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listLocations with error', async () => { + const client = + new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.location.ListLocationsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.location.ListLocationsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listLocations = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listLocations(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listLocations as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listLocations as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('setIamPolicy', () => { - it('invokes setIamPolicy without error', async () => { - const client = new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new IamProtos.google.iam.v1.SetIamPolicyRequest() - ); - request.resource = ''; - const expectedHeaderRequestParams = 'resource='; - const expectedOptions = { - otherArgs: { - headers: { - 'x-goog-request-params': expectedHeaderRequestParams, - }, - }, - }; - const expectedResponse = generateSampleMessage( - new IamProtos.google.iam.v1.Policy() - ); - client.iamClient.setIamPolicy = stubSimpleCall(expectedResponse); - const response = await client.setIamPolicy(request, expectedOptions); - assert.deepStrictEqual(response, [expectedResponse]); - assert((client.iamClient.setIamPolicy as SinonStub) - .getCall(0).calledWith(request, expectedOptions, undefined)); + + it('invokes listLocationsStream without error', async () => { + const client = + new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.location.ListLocationsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.location.ListLocationsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.location.Location()), + generateSampleMessage(new protos.google.cloud.location.Location()), + generateSampleMessage(new protos.google.cloud.location.Location()), + ]; + client.descriptors.page.listLocations.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listLocationsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.cloud.location.Location[] = []; + stream.on('data', (response: protos.google.cloud.location.Location) => { + responses.push(response); }); - it('invokes setIamPolicy without error using callback', async () => { - const client = new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new IamProtos.google.iam.v1.SetIamPolicyRequest() - ); - request.resource = ''; - const expectedHeaderRequestParams = 'resource='; - const expectedOptions = { - otherArgs: { - headers: { - 'x-goog-request-params': expectedHeaderRequestParams, - }, - }, - }; - const expectedResponse = generateSampleMessage( - new IamProtos.google.iam.v1.Policy() - ); - client.iamClient.setIamPolicy = sinon.stub().callsArgWith(2, null, expectedResponse); - const promise = new Promise((resolve, reject) => { - client.setIamPolicy( - request, - expectedOptions, - (err?: Error|null, result?: IamProtos.google.iam.v1.Policy|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }).catch(err => {throw err}); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - assert((client.iamClient.setIamPolicy as SinonStub) - .getCall(0)); + stream.on('end', () => { + resolve(responses); }); - it('invokes setIamPolicy with error', async () => { - const client = new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new IamProtos.google.iam.v1.SetIamPolicyRequest() - ); - request.resource = ''; - const expectedHeaderRequestParams = 'resource='; - const expectedOptions = { - otherArgs: { - headers: { - 'x-goog-request-params': expectedHeaderRequestParams, - }, - }, - }; - const expectedError = new Error('expected'); - client.iamClient.setIamPolicy = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.setIamPolicy(request, expectedOptions), expectedError); - assert((client.iamClient.setIamPolicy as SinonStub) - .getCall(0).calledWith(request, expectedOptions, undefined)); + stream.on('error', (err: Error) => { + reject(err); }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listLocations.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listLocations, request), + ); + assert( + (client.descriptors.page.listLocations.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); }); - describe('testIamPermissions', () => { - it('invokes testIamPermissions without error', async () => { - const client = new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new IamProtos.google.iam.v1.TestIamPermissionsRequest() - ); - request.resource = ''; - const expectedHeaderRequestParams = 'resource='; - const expectedOptions = { - otherArgs: { - headers: { - 'x-goog-request-params': expectedHeaderRequestParams, - }, - }, - }; - const expectedResponse = generateSampleMessage( - new IamProtos.google.iam.v1.TestIamPermissionsResponse() - ); - client.iamClient.testIamPermissions = stubSimpleCall(expectedResponse); - const response = await client.testIamPermissions(request, expectedOptions); - assert.deepStrictEqual(response, [expectedResponse]); - assert((client.iamClient.testIamPermissions as SinonStub) - .getCall(0).calledWith(request, expectedOptions, undefined)); + + it('invokes listLocationsStream with error', async () => { + const client = + new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.location.ListLocationsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.location.ListLocationsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listLocations.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listLocationsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.cloud.location.Location[] = []; + stream.on('data', (response: protos.google.cloud.location.Location) => { + responses.push(response); }); - it('invokes testIamPermissions without error using callback', async () => { - const client = new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new IamProtos.google.iam.v1.TestIamPermissionsRequest() - ); - request.resource = ''; - const expectedHeaderRequestParams = 'resource='; - const expectedOptions = { - otherArgs: { - headers: { - 'x-goog-request-params': expectedHeaderRequestParams, - }, - }, - }; - const expectedResponse = generateSampleMessage( - new IamProtos.google.iam.v1.TestIamPermissionsResponse() - ); - client.iamClient.testIamPermissions = sinon.stub().callsArgWith(2, null, expectedResponse); - const promise = new Promise((resolve, reject) => { - client.testIamPermissions( - request, - expectedOptions, - (err?: Error|null, result?: IamProtos.google.iam.v1.TestIamPermissionsResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }).catch(err => {throw err}); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - assert((client.iamClient.testIamPermissions as SinonStub) - .getCall(0)); + stream.on('end', () => { + resolve(responses); }); - it('invokes testIamPermissions with error', async () => { - const client = new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new IamProtos.google.iam.v1.TestIamPermissionsRequest() - ); - request.resource = ''; - const expectedHeaderRequestParams = 'resource='; - const expectedOptions = { - otherArgs: { - headers: { - 'x-goog-request-params': expectedHeaderRequestParams, - }, - }, - }; - const expectedError = new Error('expected'); - client.iamClient.testIamPermissions = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.testIamPermissions(request, expectedOptions), expectedError); - assert((client.iamClient.testIamPermissions as SinonStub) - .getCall(0).calledWith(request, expectedOptions, undefined)); + stream.on('error', (err: Error) => { + reject(err); }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listLocations.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listLocations, request), + ); + assert( + (client.descriptors.page.listLocations.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); }); - describe('getLocation', () => { - it('invokes getLocation without error', async () => { - const client = new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new LocationProtos.google.cloud.location.GetLocationRequest() - ); - request.name = ''; - const expectedHeaderRequestParams = 'name='; - const expectedOptions = { - otherArgs: { - headers: { - 'x-goog-request-params': expectedHeaderRequestParams, - }, - }, - }; - const expectedResponse = generateSampleMessage( - new LocationProtos.google.cloud.location.Location() - ); - client.locationsClient.getLocation = stubSimpleCall(expectedResponse); - const response = await client.getLocation(request, expectedOptions); - assert.deepStrictEqual(response, [expectedResponse]); - assert((client.locationsClient.getLocation as SinonStub) - .getCall(0).calledWith(request, expectedOptions, undefined)); - }); - it('invokes getLocation without error using callback', async () => { - const client = new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new LocationProtos.google.cloud.location.GetLocationRequest() - ); - request.name = ''; - const expectedHeaderRequestParams = 'name='; - const expectedOptions = { - otherArgs: { - headers: { - 'x-goog-request-params': expectedHeaderRequestParams, - }, - }, - }; - const expectedResponse = generateSampleMessage( - new LocationProtos.google.cloud.location.Location() - ); - client.locationsClient.getLocation = sinon.stub().callsArgWith(2, null, expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getLocation( - request, - expectedOptions, - ( - err?: Error | null, - result?: LocationProtos.google.cloud.location.ILocation | null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - assert((client.locationsClient.getLocation as SinonStub) - .getCall(0)); - }); - it('invokes getLocation with error', async () => { - const client = new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new LocationProtos.google.cloud.location.GetLocationRequest() - ); - request.name = ''; - const expectedHeaderRequestParams = 'name='; - const expectedOptions = { - otherArgs: { - headers: { - 'x-goog-request-params': expectedHeaderRequestParams, - }, - }, - }; - const expectedError = new Error('expected'); - client.locationsClient.getLocation = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getLocation(request, expectedOptions), expectedError); - assert((client.locationsClient.getLocation as SinonStub) - .getCall(0).calledWith(request, expectedOptions, undefined)); - }); + + it('uses async iteration with listLocations without error', async () => { + const client = + new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.location.ListLocationsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.location.ListLocationsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.location.Location()), + generateSampleMessage(new protos.google.cloud.location.Location()), + generateSampleMessage(new protos.google.cloud.location.Location()), + ]; + client.descriptors.page.listLocations.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.cloud.location.ILocation[] = []; + const iterable = client.listLocationsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listLocations.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listLocations.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + + it('uses async iteration with listLocations with error', async () => { + const client = + new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.location.ListLocationsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.location.ListLocationsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listLocations.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listLocationsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.cloud.location.ILocation[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listLocations.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listLocations.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + }); + describe('setIamPolicy', () => { + it('invokes setIamPolicy without error', async () => { + const client = + new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new IamProtos.google.iam.v1.SetIamPolicyRequest(), + ); + request.resource = ''; + const expectedHeaderRequestParams = 'resource='; + const expectedOptions = { + otherArgs: { + headers: { + 'x-goog-request-params': expectedHeaderRequestParams, + }, + }, + }; + const expectedResponse = generateSampleMessage( + new IamProtos.google.iam.v1.Policy(), + ); + client.iamClient.setIamPolicy = stubSimpleCall(expectedResponse); + const response = await client.setIamPolicy(request, expectedOptions); + assert.deepStrictEqual(response, [expectedResponse]); + assert( + (client.iamClient.setIamPolicy as SinonStub) + .getCall(0) + .calledWith(request, expectedOptions, undefined), + ); + }); + it('invokes setIamPolicy without error using callback', async () => { + const client = + new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new IamProtos.google.iam.v1.SetIamPolicyRequest(), + ); + request.resource = ''; + const expectedHeaderRequestParams = 'resource='; + const expectedOptions = { + otherArgs: { + headers: { + 'x-goog-request-params': expectedHeaderRequestParams, + }, + }, + }; + const expectedResponse = generateSampleMessage( + new IamProtos.google.iam.v1.Policy(), + ); + client.iamClient.setIamPolicy = sinon + .stub() + .callsArgWith(2, null, expectedResponse); + const promise = new Promise((resolve, reject) => { + client + .setIamPolicy( + request, + expectedOptions, + ( + err?: Error | null, + result?: IamProtos.google.iam.v1.Policy | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ) + .catch((err) => { + throw err; + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + assert((client.iamClient.setIamPolicy as SinonStub).getCall(0)); + }); + it('invokes setIamPolicy with error', async () => { + const client = + new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new IamProtos.google.iam.v1.SetIamPolicyRequest(), + ); + request.resource = ''; + const expectedHeaderRequestParams = 'resource='; + const expectedOptions = { + otherArgs: { + headers: { + 'x-goog-request-params': expectedHeaderRequestParams, + }, + }, + }; + const expectedError = new Error('expected'); + client.iamClient.setIamPolicy = stubSimpleCall(undefined, expectedError); + await assert.rejects( + client.setIamPolicy(request, expectedOptions), + expectedError, + ); + assert( + (client.iamClient.setIamPolicy as SinonStub) + .getCall(0) + .calledWith(request, expectedOptions, undefined), + ); + }); + }); + describe('testIamPermissions', () => { + it('invokes testIamPermissions without error', async () => { + const client = + new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new IamProtos.google.iam.v1.TestIamPermissionsRequest(), + ); + request.resource = ''; + const expectedHeaderRequestParams = 'resource='; + const expectedOptions = { + otherArgs: { + headers: { + 'x-goog-request-params': expectedHeaderRequestParams, + }, + }, + }; + const expectedResponse = generateSampleMessage( + new IamProtos.google.iam.v1.TestIamPermissionsResponse(), + ); + client.iamClient.testIamPermissions = stubSimpleCall(expectedResponse); + const response = await client.testIamPermissions( + request, + expectedOptions, + ); + assert.deepStrictEqual(response, [expectedResponse]); + assert( + (client.iamClient.testIamPermissions as SinonStub) + .getCall(0) + .calledWith(request, expectedOptions, undefined), + ); + }); + it('invokes testIamPermissions without error using callback', async () => { + const client = + new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new IamProtos.google.iam.v1.TestIamPermissionsRequest(), + ); + request.resource = ''; + const expectedHeaderRequestParams = 'resource='; + const expectedOptions = { + otherArgs: { + headers: { + 'x-goog-request-params': expectedHeaderRequestParams, + }, + }, + }; + const expectedResponse = generateSampleMessage( + new IamProtos.google.iam.v1.TestIamPermissionsResponse(), + ); + client.iamClient.testIamPermissions = sinon + .stub() + .callsArgWith(2, null, expectedResponse); + const promise = new Promise((resolve, reject) => { + client + .testIamPermissions( + request, + expectedOptions, + ( + err?: Error | null, + result?: IamProtos.google.iam.v1.TestIamPermissionsResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ) + .catch((err) => { + throw err; + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + assert((client.iamClient.testIamPermissions as SinonStub).getCall(0)); + }); + it('invokes testIamPermissions with error', async () => { + const client = + new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new IamProtos.google.iam.v1.TestIamPermissionsRequest(), + ); + request.resource = ''; + const expectedHeaderRequestParams = 'resource='; + const expectedOptions = { + otherArgs: { + headers: { + 'x-goog-request-params': expectedHeaderRequestParams, + }, + }, + }; + const expectedError = new Error('expected'); + client.iamClient.testIamPermissions = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.testIamPermissions(request, expectedOptions), + expectedError, + ); + assert( + (client.iamClient.testIamPermissions as SinonStub) + .getCall(0) + .calledWith(request, expectedOptions, undefined), + ); + }); + }); + describe('getLocation', () => { + it('invokes getLocation without error', async () => { + const client = + new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new LocationProtos.google.cloud.location.GetLocationRequest(), + ); + request.name = ''; + const expectedHeaderRequestParams = 'name='; + const expectedOptions = { + otherArgs: { + headers: { + 'x-goog-request-params': expectedHeaderRequestParams, + }, + }, + }; + const expectedResponse = generateSampleMessage( + new LocationProtos.google.cloud.location.Location(), + ); + client.locationsClient.getLocation = stubSimpleCall(expectedResponse); + const response = await client.getLocation(request, expectedOptions); + assert.deepStrictEqual(response, [expectedResponse]); + assert( + (client.locationsClient.getLocation as SinonStub) + .getCall(0) + .calledWith(request, expectedOptions, undefined), + ); + }); + it('invokes getLocation without error using callback', async () => { + const client = + new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new LocationProtos.google.cloud.location.GetLocationRequest(), + ); + request.name = ''; + const expectedHeaderRequestParams = 'name='; + const expectedOptions = { + otherArgs: { + headers: { + 'x-goog-request-params': expectedHeaderRequestParams, + }, + }, + }; + const expectedResponse = generateSampleMessage( + new LocationProtos.google.cloud.location.Location(), + ); + client.locationsClient.getLocation = sinon + .stub() + .callsArgWith(2, null, expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getLocation( + request, + expectedOptions, + ( + err?: Error | null, + result?: LocationProtos.google.cloud.location.ILocation | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + assert((client.locationsClient.getLocation as SinonStub).getCall(0)); + }); + it('invokes getLocation with error', async () => { + const client = + new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new LocationProtos.google.cloud.location.GetLocationRequest(), + ); + request.name = ''; + const expectedHeaderRequestParams = 'name='; + const expectedOptions = { + otherArgs: { + headers: { + 'x-goog-request-params': expectedHeaderRequestParams, + }, + }, + }; + const expectedError = new Error('expected'); + client.locationsClient.getLocation = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.getLocation(request, expectedOptions), + expectedError, + ); + assert( + (client.locationsClient.getLocation as SinonStub) + .getCall(0) + .calledWith(request, expectedOptions, undefined), + ); }); + }); }); diff --git a/core/generator/gapic-generator-typescript/baselines/duplicate_methods_test/src/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/duplicate_methods_test/src/index.ts.baseline index f49a9ce39e40..7cec916e506b 100644 --- a/core/generator/gapic-generator-typescript/baselines/duplicate_methods_test/src/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/duplicate_methods_test/src/index.ts.baseline @@ -19,7 +19,7 @@ import * as v1 from './v1'; const DuplicateMethodsTestServiceClient = v1.DuplicateMethodsTestServiceClient; type DuplicateMethodsTestServiceClient = v1.DuplicateMethodsTestServiceClient; -export {v1, DuplicateMethodsTestServiceClient}; -export default {v1, DuplicateMethodsTestServiceClient}; +export { v1, DuplicateMethodsTestServiceClient }; +export default { v1, DuplicateMethodsTestServiceClient }; import * as protos from '../protos/protos'; -export {protos} +export { protos }; diff --git a/core/generator/gapic-generator-typescript/baselines/duplicate_methods_test/src/v1/duplicate_methods_test_service_client.ts.baseline b/core/generator/gapic-generator-typescript/baselines/duplicate_methods_test/src/v1/duplicate_methods_test_service_client.ts.baseline index d50cf3be6a49..7d18045658f1 100644 --- a/core/generator/gapic-generator-typescript/baselines/duplicate_methods_test/src/v1/duplicate_methods_test_service_client.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/duplicate_methods_test/src/v1/duplicate_methods_test_service_client.ts.baseline @@ -18,11 +18,22 @@ /* global window */ import type * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions, PaginationCallback, GaxCall, IamClient, IamProtos, LocationsClient, LocationProtos} from 'google-gax'; -import {Transform} from 'stream'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + PaginationCallback, + GaxCall, + IamClient, + IamProtos, + LocationsClient, + LocationProtos, +} from 'google-gax'; +import { Transform } from 'stream'; import * as protos from '../../protos/protos'; import jsonProtos = require('../../protos/protos.json'); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; /** * Client JSON configuration object, loaded from @@ -43,7 +54,7 @@ export class DuplicateMethodsTestServiceClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('duplicate-methods-test'); @@ -56,10 +67,10 @@ export class DuplicateMethodsTestServiceClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; + innerApiCalls: { [name: string]: Function }; iamClient: IamClient; locationsClient: LocationsClient; - duplicateMethodsTestServiceStub?: Promise<{[name: string]: Function}>; + duplicateMethodsTestServiceStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of DuplicateMethodsTestServiceClient. @@ -100,21 +111,43 @@ export class DuplicateMethodsTestServiceClient { * const client = new DuplicateMethodsTestServiceClient({fallback: true}, gax); * ``` */ - constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { // Ensure that options include all the required fields. - const staticMembers = this.constructor as typeof DuplicateMethodsTestServiceClient; - if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { - throw new Error('Please set either universe_domain or universeDomain, but not both.'); + const staticMembers = this + .constructor as typeof DuplicateMethodsTestServiceClient; + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); } - const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; - this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; this._servicePath = 'duplicatemethodstest.' + this._universeDomain; - const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; - const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. if (servicePath !== this._servicePath && !('scopes' in opts)) { @@ -136,7 +169,7 @@ export class DuplicateMethodsTestServiceClient { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; @@ -149,18 +182,14 @@ export class DuplicateMethodsTestServiceClient { this.auth.defaultScopes = staticMembers.scopes; } this.iamClient = new this._gaxModule.IamClient(this._gaxGrpc, opts); - + this.locationsClient = new this._gaxModule.LocationsClient( this._gaxGrpc, - opts + opts, ); - // Determine the client header string. - const clientHeader = [ - `gax/${this._gaxModule.version}`, - `gapic/${version}`, - ]; + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/${process.versions.node}`); } else { @@ -181,14 +210,20 @@ export class DuplicateMethodsTestServiceClient { // (e.g. 50 results at a time, with tokens to get subsequent // pages). Denote the keys used for pagination and results. this.descriptors.page = { - listLocations: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'locations') + listLocations: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'locations', + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.duplicate_methods_test.v1.DuplicateMethodsTestService', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.duplicate_methods_test.v1.DuplicateMethodsTestService', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + { 'x-goog-api-client': clientHeader.join(' ') }, + ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -219,37 +254,45 @@ export class DuplicateMethodsTestServiceClient { // Put together the "service stub" for // google.duplicate_methods_test.v1.DuplicateMethodsTestService. this.duplicateMethodsTestServiceStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.duplicate_methods_test.v1.DuplicateMethodsTestService') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any - (this._protos as any).google.duplicate_methods_test.v1.DuplicateMethodsTestService, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.duplicate_methods_test.v1.DuplicateMethodsTestService', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any + (this._protos as any).google.duplicate_methods_test.v1 + .DuplicateMethodsTestService, + this._opts, + this._providedCustomServicePath, + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const duplicateMethodsTestServiceStubMethods = - ['getIamPolicy', 'listLocations', 'echo']; + const duplicateMethodsTestServiceStubMethods = [ + 'getIamPolicy', + 'listLocations', + 'echo', + ]; for (const methodName of duplicateMethodsTestServiceStubMethods) { const callPromise = this.duplicateMethodsTestServiceStub.then( - stub => (...args: Array<{}>) => { - if (this._terminated) { - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error|null|undefined) => () => { + (stub) => + (...args: Array<{}>) => { + if (this._terminated) { + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { throw err; - }); + }, + ); - const descriptor = - this.descriptors.page[methodName] || - undefined; + const descriptor = this.descriptors.page[methodName] || undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -264,8 +307,14 @@ export class DuplicateMethodsTestServiceClient { * @returns {string} The DNS address for this service. */ static get servicePath() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'duplicatemethodstest.googleapis.com'; } @@ -276,8 +325,14 @@ export class DuplicateMethodsTestServiceClient { * @returns {string} The DNS address for this service. */ static get apiEndpoint() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'duplicatemethodstest.googleapis.com'; } @@ -308,9 +363,7 @@ export class DuplicateMethodsTestServiceClient { * @returns {string[]} List of default scopes. */ static get scopes() { - return [ - 'https://www.googleapis.com/auth/cloud-platform' - ]; + return ['https://www.googleapis.com/auth/cloud-platform']; } getProjectId(): Promise; @@ -319,8 +372,9 @@ export class DuplicateMethodsTestServiceClient { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId(callback?: Callback): - Promise|void { + getProjectId( + callback?: Callback, + ): Promise | void { if (callback) { this.auth.getProjectId(callback); return; @@ -331,276 +385,360 @@ export class DuplicateMethodsTestServiceClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Native GetIamPolicy method that conflicts with the IAMPolicy mixin. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.resource - * REQUIRED: The resource for which the policy is being requested. - * See the operation documentation for the appropriate value for this field. - * @param {google.iam.v1.GetPolicyOptions} request.options - * OPTIONAL: A `GetPolicyOptions` object for specifying options to - * `GetIamPolicy`. This field is only used by Cloud IAM. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.iam.v1.Policy|Policy}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1/duplicate_methods_test_service.get_iam_policy.js - * region_tag:duplicatemethodstest_v1_generated_DuplicateMethodsTestService_GetIamPolicy_async - */ + /** + * Native GetIamPolicy method that conflicts with the IAMPolicy mixin. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.resource + * REQUIRED: The resource for which the policy is being requested. + * See the operation documentation for the appropriate value for this field. + * @param {google.iam.v1.GetPolicyOptions} request.options + * OPTIONAL: A `GetPolicyOptions` object for specifying options to + * `GetIamPolicy`. This field is only used by Cloud IAM. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.iam.v1.Policy|Policy}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/duplicate_methods_test_service.get_iam_policy.js + * region_tag:duplicatemethodstest_v1_generated_DuplicateMethodsTestService_GetIamPolicy_async + */ getIamPolicy( - request?: protos.google.iam.v1.IGetIamPolicyRequest, - options?: CallOptions): - Promise<[ - protos.google.iam.v1.IPolicy, - protos.google.iam.v1.IGetIamPolicyRequest|undefined, {}|undefined - ]>; + request?: protos.google.iam.v1.IGetIamPolicyRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.iam.v1.IPolicy, + protos.google.iam.v1.IGetIamPolicyRequest | undefined, + {} | undefined, + ] + >; getIamPolicy( - request: protos.google.iam.v1.IGetIamPolicyRequest, - options: CallOptions, - callback: Callback< - protos.google.iam.v1.IPolicy, - protos.google.iam.v1.IGetIamPolicyRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.iam.v1.IGetIamPolicyRequest, + options: CallOptions, + callback: Callback< + protos.google.iam.v1.IPolicy, + protos.google.iam.v1.IGetIamPolicyRequest | null | undefined, + {} | null | undefined + >, + ): void; getIamPolicy( - request: protos.google.iam.v1.IGetIamPolicyRequest, - callback: Callback< - protos.google.iam.v1.IPolicy, - protos.google.iam.v1.IGetIamPolicyRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.iam.v1.IGetIamPolicyRequest, + callback: Callback< + protos.google.iam.v1.IPolicy, + protos.google.iam.v1.IGetIamPolicyRequest | null | undefined, + {} | null | undefined + >, + ): void; getIamPolicy( - request?: protos.google.iam.v1.IGetIamPolicyRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.iam.v1.IPolicy, - protos.google.iam.v1.IGetIamPolicyRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.iam.v1.IGetIamPolicyRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.iam.v1.IPolicy, - protos.google.iam.v1.IGetIamPolicyRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.iam.v1.IPolicy, - protos.google.iam.v1.IGetIamPolicyRequest|undefined, {}|undefined - ]>|void { + protos.google.iam.v1.IGetIamPolicyRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.iam.v1.IPolicy, + protos.google.iam.v1.IGetIamPolicyRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.iam.v1.IPolicy, + protos.google.iam.v1.IGetIamPolicyRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'resource': request.resource ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + resource: request.resource ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getIamPolicy request %j', request); - const wrappedCallback: Callback< - protos.google.iam.v1.IPolicy, - protos.google.iam.v1.IGetIamPolicyRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.iam.v1.IPolicy, + protos.google.iam.v1.IGetIamPolicyRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getIamPolicy response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getIamPolicy(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.iam.v1.IPolicy, - protos.google.iam.v1.IGetIamPolicyRequest|undefined, - {}|undefined - ]) => { - this._log.info('getIamPolicy response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getIamPolicy(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.iam.v1.IPolicy, + protos.google.iam.v1.IGetIamPolicyRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getIamPolicy response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Another native method to ensure the service is valid and has other methods. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.content - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.duplicate_methods_test.v1.EchoResponse|EchoResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1/duplicate_methods_test_service.echo.js - * region_tag:duplicatemethodstest_v1_generated_DuplicateMethodsTestService_Echo_async - */ + /** + * Another native method to ensure the service is valid and has other methods. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.content + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.duplicate_methods_test.v1.EchoResponse|EchoResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/duplicate_methods_test_service.echo.js + * region_tag:duplicatemethodstest_v1_generated_DuplicateMethodsTestService_Echo_async + */ echo( - request?: protos.google.duplicate_methods_test.v1.IEchoRequest, - options?: CallOptions): - Promise<[ - protos.google.duplicate_methods_test.v1.IEchoResponse, - protos.google.duplicate_methods_test.v1.IEchoRequest|undefined, {}|undefined - ]>; + request?: protos.google.duplicate_methods_test.v1.IEchoRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.duplicate_methods_test.v1.IEchoResponse, + protos.google.duplicate_methods_test.v1.IEchoRequest | undefined, + {} | undefined, + ] + >; echo( - request: protos.google.duplicate_methods_test.v1.IEchoRequest, - options: CallOptions, - callback: Callback< - protos.google.duplicate_methods_test.v1.IEchoResponse, - protos.google.duplicate_methods_test.v1.IEchoRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.duplicate_methods_test.v1.IEchoRequest, + options: CallOptions, + callback: Callback< + protos.google.duplicate_methods_test.v1.IEchoResponse, + protos.google.duplicate_methods_test.v1.IEchoRequest | null | undefined, + {} | null | undefined + >, + ): void; echo( - request: protos.google.duplicate_methods_test.v1.IEchoRequest, - callback: Callback< - protos.google.duplicate_methods_test.v1.IEchoResponse, - protos.google.duplicate_methods_test.v1.IEchoRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.duplicate_methods_test.v1.IEchoRequest, + callback: Callback< + protos.google.duplicate_methods_test.v1.IEchoResponse, + protos.google.duplicate_methods_test.v1.IEchoRequest | null | undefined, + {} | null | undefined + >, + ): void; echo( - request?: protos.google.duplicate_methods_test.v1.IEchoRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.duplicate_methods_test.v1.IEchoResponse, - protos.google.duplicate_methods_test.v1.IEchoRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.duplicate_methods_test.v1.IEchoRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.duplicate_methods_test.v1.IEchoResponse, - protos.google.duplicate_methods_test.v1.IEchoRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.duplicate_methods_test.v1.IEchoResponse, - protos.google.duplicate_methods_test.v1.IEchoRequest|undefined, {}|undefined - ]>|void { + | protos.google.duplicate_methods_test.v1.IEchoRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.duplicate_methods_test.v1.IEchoResponse, + protos.google.duplicate_methods_test.v1.IEchoRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.duplicate_methods_test.v1.IEchoResponse, + protos.google.duplicate_methods_test.v1.IEchoRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('echo request %j', request); - const wrappedCallback: Callback< - protos.google.duplicate_methods_test.v1.IEchoResponse, - protos.google.duplicate_methods_test.v1.IEchoRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.duplicate_methods_test.v1.IEchoResponse, + | protos.google.duplicate_methods_test.v1.IEchoRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('echo response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.echo(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.duplicate_methods_test.v1.IEchoResponse, - protos.google.duplicate_methods_test.v1.IEchoRequest|undefined, - {}|undefined - ]) => { - this._log.info('echo response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .echo(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.duplicate_methods_test.v1.IEchoResponse, + protos.google.duplicate_methods_test.v1.IEchoRequest | undefined, + {} | undefined, + ]) => { + this._log.info('echo response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } - /** - * Native ListLocations method that conflicts with the Locations mixin. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * The resource that owns the locations collection, if applicable. - * @param {string} request.filter - * The standard list filter. - * @param {number} request.pageSize - * The standard list page size. - * @param {string} request.pageToken - * The standard list page token. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.cloud.location.Location|Location}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `listLocationsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Native ListLocations method that conflicts with the Locations mixin. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * The resource that owns the locations collection, if applicable. + * @param {string} request.filter + * The standard list filter. + * @param {number} request.pageSize + * The standard list page size. + * @param {string} request.pageToken + * The standard list page token. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.cloud.location.Location|Location}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listLocationsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listLocations( - request?: protos.google.cloud.location.IListLocationsRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.location.ILocation[], - protos.google.cloud.location.IListLocationsRequest|null, - protos.google.cloud.location.IListLocationsResponse - ]>; + request?: protos.google.cloud.location.IListLocationsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.location.ILocation[], + protos.google.cloud.location.IListLocationsRequest | null, + protos.google.cloud.location.IListLocationsResponse, + ] + >; listLocations( - request: protos.google.cloud.location.IListLocationsRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.cloud.location.IListLocationsRequest, - protos.google.cloud.location.IListLocationsResponse|null|undefined, - protos.google.cloud.location.ILocation>): void; + request: protos.google.cloud.location.IListLocationsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.cloud.location.IListLocationsRequest, + protos.google.cloud.location.IListLocationsResponse | null | undefined, + protos.google.cloud.location.ILocation + >, + ): void; listLocations( - request: protos.google.cloud.location.IListLocationsRequest, - callback: PaginationCallback< - protos.google.cloud.location.IListLocationsRequest, - protos.google.cloud.location.IListLocationsResponse|null|undefined, - protos.google.cloud.location.ILocation>): void; + request: protos.google.cloud.location.IListLocationsRequest, + callback: PaginationCallback< + protos.google.cloud.location.IListLocationsRequest, + protos.google.cloud.location.IListLocationsResponse | null | undefined, + protos.google.cloud.location.ILocation + >, + ): void; listLocations( - request?: protos.google.cloud.location.IListLocationsRequest, - optionsOrCallback?: CallOptions|PaginationCallback< - protos.google.cloud.location.IListLocationsRequest, - protos.google.cloud.location.IListLocationsResponse|null|undefined, - protos.google.cloud.location.ILocation>, - callback?: PaginationCallback< + request?: protos.google.cloud.location.IListLocationsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.cloud.location.IListLocationsRequest, - protos.google.cloud.location.IListLocationsResponse|null|undefined, - protos.google.cloud.location.ILocation>): - Promise<[ - protos.google.cloud.location.ILocation[], - protos.google.cloud.location.IListLocationsRequest|null, - protos.google.cloud.location.IListLocationsResponse - ]>|void { + | protos.google.cloud.location.IListLocationsResponse + | null + | undefined, + protos.google.cloud.location.ILocation + >, + callback?: PaginationCallback< + protos.google.cloud.location.IListLocationsRequest, + protos.google.cloud.location.IListLocationsResponse | null | undefined, + protos.google.cloud.location.ILocation + >, + ): Promise< + [ + protos.google.cloud.location.ILocation[], + protos.google.cloud.location.IListLocationsRequest | null, + protos.google.cloud.location.IListLocationsResponse, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.cloud.location.IListLocationsRequest, - protos.google.cloud.location.IListLocationsResponse|null|undefined, - protos.google.cloud.location.ILocation>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.cloud.location.IListLocationsRequest, + | protos.google.cloud.location.IListLocationsResponse + | null + | undefined, + protos.google.cloud.location.ILocation + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listLocations values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -609,167 +747,171 @@ export class DuplicateMethodsTestServiceClient { this._log.info('listLocations request %j', request); return this.innerApiCalls .listLocations(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.cloud.location.ILocation[], - protos.google.cloud.location.IListLocationsRequest|null, - protos.google.cloud.location.IListLocationsResponse - ]) => { - this._log.info('listLocations values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.cloud.location.ILocation[], + protos.google.cloud.location.IListLocationsRequest | null, + protos.google.cloud.location.IListLocationsResponse, + ]) => { + this._log.info('listLocations values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listLocations`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * The resource that owns the locations collection, if applicable. - * @param {string} request.filter - * The standard list filter. - * @param {number} request.pageSize - * The standard list page size. - * @param {string} request.pageToken - * The standard list page token. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.cloud.location.Location|Location} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `listLocationsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `listLocations`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * The resource that owns the locations collection, if applicable. + * @param {string} request.filter + * The standard list filter. + * @param {number} request.pageSize + * The standard list page size. + * @param {string} request.pageToken + * The standard list page token. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.cloud.location.Location|Location} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listLocationsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listLocationsStream( - request?: protos.google.cloud.location.IListLocationsRequest, - options?: CallOptions): - Transform{ + request?: protos.google.cloud.location.IListLocationsRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); const defaultCallSettings = this._defaults['listLocations']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listLocations stream %j', request); return this.descriptors.page.listLocations.createStream( this.innerApiCalls.listLocations as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listLocations`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * The resource that owns the locations collection, if applicable. - * @param {string} request.filter - * The standard list filter. - * @param {number} request.pageSize - * The standard list page size. - * @param {string} request.pageToken - * The standard list page token. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.cloud.location.Location|Location}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v1/duplicate_methods_test_service.list_locations.js - * region_tag:duplicatemethodstest_v1_generated_DuplicateMethodsTestService_ListLocations_async - */ + /** + * Equivalent to `listLocations`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * The resource that owns the locations collection, if applicable. + * @param {string} request.filter + * The standard list filter. + * @param {number} request.pageSize + * The standard list page size. + * @param {string} request.pageToken + * The standard list page token. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.cloud.location.Location|Location}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v1/duplicate_methods_test_service.list_locations.js + * region_tag:duplicatemethodstest_v1_generated_DuplicateMethodsTestService_ListLocations_async + */ listLocationsAsync( - request?: protos.google.cloud.location.IListLocationsRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.cloud.location.IListLocationsRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); const defaultCallSettings = this._defaults['listLocations']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listLocations iterate %j', request); return this.descriptors.page.listLocations.asyncIterate( this.innerApiCalls['listLocations'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } -/** - * Gets the access control policy for a resource. Returns an empty policy - * if the resource exists and does not have a policy set. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.resource - * REQUIRED: The resource for which the policy is being requested. - * See the operation documentation for the appropriate value for this field. - * @param {Object} [request.options] - * OPTIONAL: A `GetPolicyOptions` object for specifying options to - * `GetIamPolicy`. This field is only used by Cloud IAM. - * - * This object should have the same structure as {@link google.iam.v1.GetPolicyOptions | GetPolicyOptions}. - * @param {Object} [options] - * Optional parameters. You can override the default settings for this call, e.g, timeout, - * retries, paginations, etc. See {@link https://googleapis.github.io/gax-nodejs/interfaces/CallOptions.html | gax.CallOptions} for the details. - * @param {function(?Error, ?Object)} [callback] - * The function which will be called with the result of the API call. - * - * The second parameter to the callback is an object representing {@link google.iam.v1.Policy | Policy}. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link google.iam.v1.Policy | Policy}. - * The promise has a method named "cancel" which cancels the ongoing API call. - */ + /** + * Gets the access control policy for a resource. Returns an empty policy + * if the resource exists and does not have a policy set. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.resource + * REQUIRED: The resource for which the policy is being requested. + * See the operation documentation for the appropriate value for this field. + * @param {Object} [request.options] + * OPTIONAL: A `GetPolicyOptions` object for specifying options to + * `GetIamPolicy`. This field is only used by Cloud IAM. + * + * This object should have the same structure as {@link google.iam.v1.GetPolicyOptions | GetPolicyOptions}. + * @param {Object} [options] + * Optional parameters. You can override the default settings for this call, e.g, timeout, + * retries, paginations, etc. See {@link https://googleapis.github.io/gax-nodejs/interfaces/CallOptions.html | gax.CallOptions} for the details. + * @param {function(?Error, ?Object)} [callback] + * The function which will be called with the result of the API call. + * + * The second parameter to the callback is an object representing {@link google.iam.v1.Policy | Policy}. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link google.iam.v1.Policy | Policy}. + * The promise has a method named "cancel" which cancels the ongoing API call. + */ -/** - * Returns permissions that a caller has on the specified resource. If the - * resource does not exist, this will return an empty set of - * permissions, not a NOT_FOUND error. - * - * Note: This operation is designed to be used for building - * permission-aware UIs and command-line tools, not for authorization - * checking. This operation may "fail open" without warning. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.resource - * REQUIRED: The resource for which the policy detail is being requested. - * See the operation documentation for the appropriate value for this field. - * @param {string[]} request.permissions - * The set of permissions to check for the `resource`. Permissions with - * wildcards (such as '*' or 'storage.*') are not allowed. For more - * information see {@link https://cloud.google.com/iam/docs/overview#permissions | IAM Overview }. - * @param {Object} [options] - * Optional parameters. You can override the default settings for this call, e.g, timeout, - * retries, paginations, etc. See {@link https://googleapis.github.io/gax-nodejs/interfaces/CallOptions.html | gax.CallOptions} for the details. - * @param {function(?Error, ?Object)} [callback] - * The function which will be called with the result of the API call. - * - * The second parameter to the callback is an object representing {@link google.iam.v1.TestIamPermissionsResponse | TestIamPermissionsResponse}. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link google.iam.v1.TestIamPermissionsResponse | TestIamPermissionsResponse}. - * The promise has a method named "cancel" which cancels the ongoing API call. - */ + /** + * Returns permissions that a caller has on the specified resource. If the + * resource does not exist, this will return an empty set of + * permissions, not a NOT_FOUND error. + * + * Note: This operation is designed to be used for building + * permission-aware UIs and command-line tools, not for authorization + * checking. This operation may "fail open" without warning. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.resource + * REQUIRED: The resource for which the policy detail is being requested. + * See the operation documentation for the appropriate value for this field. + * @param {string[]} request.permissions + * The set of permissions to check for the `resource`. Permissions with + * wildcards (such as '*' or 'storage.*') are not allowed. For more + * information see {@link https://cloud.google.com/iam/docs/overview#permissions | IAM Overview }. + * @param {Object} [options] + * Optional parameters. You can override the default settings for this call, e.g, timeout, + * retries, paginations, etc. See {@link https://googleapis.github.io/gax-nodejs/interfaces/CallOptions.html | gax.CallOptions} for the details. + * @param {function(?Error, ?Object)} [callback] + * The function which will be called with the result of the API call. + * + * The second parameter to the callback is an object representing {@link google.iam.v1.TestIamPermissionsResponse | TestIamPermissionsResponse}. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link google.iam.v1.TestIamPermissionsResponse | TestIamPermissionsResponse}. + * The promise has a method named "cancel" which cancels the ongoing API call. + */ setIamPolicy( request: IamProtos.google.iam.v1.SetIamPolicyRequest, options?: @@ -783,41 +925,41 @@ export class DuplicateMethodsTestServiceClient { IamProtos.google.iam.v1.Policy, IamProtos.google.iam.v1.SetIamPolicyRequest | null | undefined, {} | null | undefined - > - ):Promise<[IamProtos.google.iam.v1.Policy]> { + >, + ): Promise<[IamProtos.google.iam.v1.Policy]> { return this.iamClient.setIamPolicy(request, options, callback); } -/** - * Returns permissions that a caller has on the specified resource. If the - * resource does not exist, this will return an empty set of - * permissions, not a NOT_FOUND error. - * - * Note: This operation is designed to be used for building - * permission-aware UIs and command-line tools, not for authorization - * checking. This operation may "fail open" without warning. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.resource - * REQUIRED: The resource for which the policy detail is being requested. - * See the operation documentation for the appropriate value for this field. - * @param {string[]} request.permissions - * The set of permissions to check for the `resource`. Permissions with - * wildcards (such as '*' or 'storage.*') are not allowed. For more - * information see {@link https://cloud.google.com/iam/docs/overview#permissions | IAM Overview }. - * @param {Object} [options] - * Optional parameters. You can override the default settings for this call, e.g, timeout, - * retries, paginations, etc. See {@link https://googleapis.github.io/gax-nodejs/interfaces/CallOptions.html | gax.CallOptions} for the details. - * @param {function(?Error, ?Object)} [callback] - * The function which will be called with the result of the API call. - * - * The second parameter to the callback is an object representing {@link google.iam.v1.TestIamPermissionsResponse | TestIamPermissionsResponse}. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link google.iam.v1.TestIamPermissionsResponse | TestIamPermissionsResponse}. - * The promise has a method named "cancel" which cancels the ongoing API call. - * - */ + /** + * Returns permissions that a caller has on the specified resource. If the + * resource does not exist, this will return an empty set of + * permissions, not a NOT_FOUND error. + * + * Note: This operation is designed to be used for building + * permission-aware UIs and command-line tools, not for authorization + * checking. This operation may "fail open" without warning. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.resource + * REQUIRED: The resource for which the policy detail is being requested. + * See the operation documentation for the appropriate value for this field. + * @param {string[]} request.permissions + * The set of permissions to check for the `resource`. Permissions with + * wildcards (such as '*' or 'storage.*') are not allowed. For more + * information see {@link https://cloud.google.com/iam/docs/overview#permissions | IAM Overview }. + * @param {Object} [options] + * Optional parameters. You can override the default settings for this call, e.g, timeout, + * retries, paginations, etc. See {@link https://googleapis.github.io/gax-nodejs/interfaces/CallOptions.html | gax.CallOptions} for the details. + * @param {function(?Error, ?Object)} [callback] + * The function which will be called with the result of the API call. + * + * The second parameter to the callback is an object representing {@link google.iam.v1.TestIamPermissionsResponse | TestIamPermissionsResponse}. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link google.iam.v1.TestIamPermissionsResponse | TestIamPermissionsResponse}. + * The promise has a method named "cancel" which cancels the ongoing API call. + * + */ testIamPermissions( request: IamProtos.google.iam.v1.TestIamPermissionsRequest, options?: @@ -831,13 +973,12 @@ export class DuplicateMethodsTestServiceClient { IamProtos.google.iam.v1.TestIamPermissionsResponse, IamProtos.google.iam.v1.TestIamPermissionsRequest | null | undefined, {} | null | undefined - > - ):Promise<[IamProtos.google.iam.v1.TestIamPermissionsResponse]> { + >, + ): Promise<[IamProtos.google.iam.v1.TestIamPermissionsResponse]> { return this.iamClient.testIamPermissions(request, options, callback); } - - /** + /** * Gets information about a location. * * @param {Object} request @@ -872,12 +1013,11 @@ export class DuplicateMethodsTestServiceClient { | null | undefined, {} | null | undefined - > + >, ): Promise { return this.locationsClient.getLocation(request, options, callback); } - /** * Terminate the gRPC channel and close the client. * @@ -886,14 +1026,18 @@ export class DuplicateMethodsTestServiceClient { */ close(): Promise { if (this.duplicateMethodsTestServiceStub && !this._terminated) { - return this.duplicateMethodsTestServiceStub.then(stub => { + return this.duplicateMethodsTestServiceStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); - this.iamClient.close().catch(err => {throw err}); - this.locationsClient.close().catch(err => {throw err}); + this.iamClient.close().catch((err) => { + throw err; + }); + this.locationsClient.close().catch((err) => { + throw err; + }); }); } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/core/generator/gapic-generator-typescript/baselines/duplicate_methods_test/src/v1/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/duplicate_methods_test/src/v1/index.ts.baseline index 37e108cedea7..7e37332dc4e4 100644 --- a/core/generator/gapic-generator-typescript/baselines/duplicate_methods_test/src/v1/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/duplicate_methods_test/src/v1/index.ts.baseline @@ -16,4 +16,4 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -export {DuplicateMethodsTestServiceClient} from './duplicate_methods_test_service_client'; +export { DuplicateMethodsTestServiceClient } from './duplicate_methods_test_service_client'; diff --git a/core/generator/gapic-generator-typescript/baselines/duplicate_methods_test/system-test/fixtures/sample/src/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/duplicate_methods_test/system-test/fixtures/sample/src/index.ts.baseline index b837e1bcff4f..f47ee90661e3 100644 --- a/core/generator/gapic-generator-typescript/baselines/duplicate_methods_test/system-test/fixtures/sample/src/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/duplicate_methods_test/system-test/fixtures/sample/src/index.ts.baseline @@ -16,17 +16,22 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -import {DuplicateMethodsTestServiceClient} from 'duplicate-methods-test'; +import { DuplicateMethodsTestServiceClient } from 'duplicate-methods-test'; // check that the client class type name can be used -function doStuffWithDuplicateMethodsTestServiceClient(client: DuplicateMethodsTestServiceClient) { +function doStuffWithDuplicateMethodsTestServiceClient( + client: DuplicateMethodsTestServiceClient, +) { client.close(); } function main() { // check that the client instance can be created - const duplicateMethodsTestServiceClient = new DuplicateMethodsTestServiceClient(); - doStuffWithDuplicateMethodsTestServiceClient(duplicateMethodsTestServiceClient); + const duplicateMethodsTestServiceClient = + new DuplicateMethodsTestServiceClient(); + doStuffWithDuplicateMethodsTestServiceClient( + duplicateMethodsTestServiceClient, + ); } main(); diff --git a/core/generator/gapic-generator-typescript/baselines/duplicate_methods_test/system-test/install.ts.baseline b/core/generator/gapic-generator-typescript/baselines/duplicate_methods_test/system-test/install.ts.baseline index f66069aa3940..ccf167042d2e 100644 --- a/core/generator/gapic-generator-typescript/baselines/duplicate_methods_test/system-test/install.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/duplicate_methods_test/system-test/install.ts.baseline @@ -16,34 +16,36 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -import {packNTest} from 'pack-n-play'; -import {readFileSync} from 'fs'; -import {describe, it} from 'mocha'; +import { packNTest } from 'pack-n-play'; +import { readFileSync } from 'fs'; +import { describe, it } from 'mocha'; describe('📦 pack-n-play test', () => { - - it('TypeScript code', async function() { + it('TypeScript code', async function () { this.timeout(300000); const options = { packageDir: process.cwd(), sample: { description: 'TypeScript user can use the type definitions', - ts: readFileSync('./system-test/fixtures/sample/src/index.ts').toString() - } + ts: readFileSync( + './system-test/fixtures/sample/src/index.ts', + ).toString(), + }, }; await packNTest(options); }); - it('JavaScript code', async function() { + it('JavaScript code', async function () { this.timeout(300000); const options = { packageDir: process.cwd(), sample: { description: 'JavaScript user can use the library', - cjs: readFileSync('./system-test/fixtures/sample/src/index.js').toString() - } + cjs: readFileSync( + './system-test/fixtures/sample/src/index.js', + ).toString(), + }, }; await packNTest(options); }); - }); diff --git a/core/generator/gapic-generator-typescript/baselines/duplicate_methods_test/test/gapic_duplicate_methods_test_service_v1.ts.baseline b/core/generator/gapic-generator-typescript/baselines/duplicate_methods_test/test/gapic_duplicate_methods_test_service_v1.ts.baseline index e9f1676ac7cf..e379077f4c6a 100644 --- a/core/generator/gapic-generator-typescript/baselines/duplicate_methods_test/test/gapic_duplicate_methods_test_service_v1.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/duplicate_methods_test/test/gapic_duplicate_methods_test_service_v1.ts.baseline @@ -19,950 +19,1247 @@ import * as protos from '../protos/protos'; import * as assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as duplicatemethodstestserviceModule from '../src'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; -import {protobuf, IamProtos, LocationProtos} from 'google-gax'; +import { protobuf, IamProtos, LocationProtos } from 'google-gax'; // Dynamically loaded proto JSON is needed to get the type information // to fill in default values for request objects -const root = protobuf.Root.fromJSON(require('../protos/protos.json')).resolveAll(); +const root = protobuf.Root.fromJSON( + require('../protos/protos.json'), +).resolveAll(); // eslint-disable-next-line @typescript-eslint/no-unused-vars function getTypeDefaultValue(typeName: string, fields: string[]) { - let type = root.lookupType(typeName) as protobuf.Type; - for (const field of fields.slice(0, -1)) { - type = type.fields[field]?.resolvedType as protobuf.Type; - } - return type.fields[fields[fields.length - 1]]?.defaultValue; + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type.fields[field]?.resolvedType as protobuf.Type; + } + return type.fields[fields[fields.length - 1]]?.defaultValue; } function generateSampleMessage(instance: T) { - const filledObject = (instance.constructor as typeof protobuf.Message) - .toObject(instance as protobuf.Message, {defaults: true}); - return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, { defaults: true }); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; } function stubSimpleCall(response?: ResponseType, error?: Error) { - return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); } -function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { - return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +function stubSimpleCallWithCallback( + response?: ResponseType, + error?: Error, +) { + return error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); } -function stubPageStreamingCall(responses?: ResponseType[], error?: Error) { - const pagingStub = sinon.stub(); - if (responses) { - for (let i = 0; i < responses.length; ++i) { - pagingStub.onCall(i).callsArgWith(2, null, responses[i]); - } +function stubPageStreamingCall( + responses?: ResponseType[], + error?: Error, +) { + const pagingStub = sinon.stub(); + if (responses) { + for (let i = 0; i < responses.length; ++i) { + pagingStub.onCall(i).callsArgWith(2, null, responses[i]); } - const transformStub = error ? sinon.stub().callsArgWith(2, error) : pagingStub; - const mockStream = new PassThrough({ - objectMode: true, - transform: transformStub, - }); - // trigger as many responses as needed - if (responses) { - for (let i = 0; i < responses.length; ++i) { - setImmediate(() => { mockStream.write({}); }); - } - setImmediate(() => { mockStream.end(); }); - } else { - setImmediate(() => { mockStream.write({}); }); - setImmediate(() => { mockStream.end(); }); + } + const transformStub = error + ? sinon.stub().callsArgWith(2, error) + : pagingStub; + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + // trigger as many responses as needed + if (responses) { + for (let i = 0; i < responses.length; ++i) { + setImmediate(() => { + mockStream.write({}); + }); } - return sinon.stub().returns(mockStream); + setImmediate(() => { + mockStream.end(); + }); + } else { + setImmediate(() => { + mockStream.write({}); + }); + setImmediate(() => { + mockStream.end(); + }); + } + return sinon.stub().returns(mockStream); } -function stubAsyncIterationCall(responses?: ResponseType[], error?: Error) { - let counter = 0; - const asyncIterable = { - [Symbol.asyncIterator]() { - return { - async next() { - if (error) { - return Promise.reject(error); - } - if (counter >= responses!.length) { - return Promise.resolve({done: true, value: undefined}); - } - return Promise.resolve({done: false, value: responses![counter++]}); - } - }; - } - }; - return sinon.stub().returns(asyncIterable); +function stubAsyncIterationCall( + responses?: ResponseType[], + error?: Error, +) { + let counter = 0; + const asyncIterable = { + [Symbol.asyncIterator]() { + return { + async next() { + if (error) { + return Promise.reject(error); + } + if (counter >= responses!.length) { + return Promise.resolve({ done: true, value: undefined }); + } + return Promise.resolve({ done: false, value: responses![counter++] }); + }, + }; + }, + }; + return sinon.stub().returns(asyncIterable); } describe('v1.DuplicateMethodsTestServiceClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'duplicatemethodstest.googleapis.com'); - }); - - it('has universeDomain', () => { - const client = new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); - - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - it('throws DeprecationWarning if static servicePath is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const servicePath = duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient.servicePath; - assert.strictEqual(servicePath, 'duplicatemethodstest.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'duplicatemethodstest.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'duplicatemethodstest.example.com'); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = + new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'duplicatemethodstest.googleapis.com'); + }); - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'duplicatemethodstest.example.com'); - }); + it('has universeDomain', () => { + const client = + new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - if (typeof process === 'object' && 'env' in process) { - describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { - it('sets apiEndpoint from environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'duplicatemethodstest.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - - it('value configured in code has priority over environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'duplicatemethodstest.configured.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = + duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient + .servicePath; + assert.strictEqual(servicePath, 'duplicatemethodstest.googleapis.com'); + assert(stub.called); + stub.restore(); + }); - it('has port', () => { - const port = duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient.port; - assert(port); - assert(typeof port === 'number'); - }); + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient + .apiEndpoint; + assert.strictEqual(apiEndpoint, 'duplicatemethodstest.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = + new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient( + { universeDomain: 'example.com' }, + ); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'duplicatemethodstest.example.com'); + }); - it('should create a client with no option', () => { - const client = new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient(); - assert(client); - }); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = + new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient( + { universe_domain: 'example.com' }, + ); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'duplicatemethodstest.example.com'); + }); - it('should create a client with gRPC fallback', () => { - const client = new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient({ - fallback: true, - }); - assert(client); + if (typeof process === 'object' && 'env' in process) { + describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { + it('sets apiEndpoint from environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = + new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'duplicatemethodstest.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - it('has initialize method and supports deferred initialization', async () => { - const client = new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.duplicateMethodsTestServiceStub, undefined); - await client.initialize(); - assert(client.duplicateMethodsTestServiceStub); + it('value configured in code has priority over environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = + new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient( + { universeDomain: 'configured.example.com' }, + ); + const servicePath = client.apiEndpoint; + assert.strictEqual( + servicePath, + 'duplicatemethodstest.configured.example.com', + ); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient( + { universe_domain: 'example.com', universeDomain: 'example.net' }, + ); + }); + }); - it('has close method for the initialized client', done => { - const client = new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.duplicateMethodsTestServiceStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('has port', () => { + const port = + duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient + .port; + assert(port); + assert(typeof port === 'number'); + }); - it('has close method for the non-initialized client', done => { - const client = new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.duplicateMethodsTestServiceStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('should create a client with no option', () => { + const client = + new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient(); + assert(client); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); - }); + it('should create a client with gRPC fallback', () => { + const client = + new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient( + { + fallback: true, + }, + ); + assert(client); + }); - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId((err?: Error|null, projectId?: string|null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } - }); - }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); - }); + it('has initialize method and supports deferred initialization', async () => { + const client = + new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + assert.strictEqual(client.duplicateMethodsTestServiceStub, undefined); + await client.initialize(); + assert(client.duplicateMethodsTestServiceStub); }); - describe('getIamPolicy', () => { - it('invokes getIamPolicy without error', async () => { - const client = new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.iam.v1.GetIamPolicyRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.iam.v1.GetIamPolicyRequest', ['resource']); - request.resource = defaultValue1; - const expectedHeaderRequestParams = `resource=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.iam.v1.Policy() - ); - client.innerApiCalls.getIamPolicy = stubSimpleCall(expectedResponse); - const [response] = await client.getIamPolicy(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getIamPolicy as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getIamPolicy as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('has close method for the initialized client', (done) => { + const client = + new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + client.initialize().catch((err) => { + throw err; + }); + assert(client.duplicateMethodsTestServiceStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes getIamPolicy without error using callback', async () => { - const client = new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.iam.v1.GetIamPolicyRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.iam.v1.GetIamPolicyRequest', ['resource']); - request.resource = defaultValue1; - const expectedHeaderRequestParams = `resource=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.iam.v1.Policy() - ); - client.innerApiCalls.getIamPolicy = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getIamPolicy( - request, - (err?: Error|null, result?: protos.google.iam.v1.IPolicy|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getIamPolicy as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getIamPolicy as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('has close method for the non-initialized client', (done) => { + const client = + new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + assert.strictEqual(client.duplicateMethodsTestServiceStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes getIamPolicy with error', async () => { - const client = new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.iam.v1.GetIamPolicyRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.iam.v1.GetIamPolicyRequest', ['resource']); - request.resource = defaultValue1; - const expectedHeaderRequestParams = `resource=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getIamPolicy = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getIamPolicy(request), expectedError); - const actualRequest = (client.innerApiCalls.getIamPolicy as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getIamPolicy as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = + new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + }); - it('invokes getIamPolicy with closed client', async () => { - const client = new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.iam.v1.GetIamPolicyRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.iam.v1.GetIamPolicyRequest', ['resource']); - request.resource = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getIamPolicy(request), expectedError); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = + new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); }); + }); - describe('echo', () => { - it('invokes echo without error', async () => { - const client = new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.duplicate_methods_test.v1.EchoRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.duplicate_methods_test.v1.EchoResponse() - ); - client.innerApiCalls.echo = stubSimpleCall(expectedResponse); - const [response] = await client.echo(request); - assert.deepStrictEqual(response, expectedResponse); - }); + describe('getIamPolicy', () => { + it('invokes getIamPolicy without error', async () => { + const client = + new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.iam.v1.GetIamPolicyRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.iam.v1.GetIamPolicyRequest', + ['resource'], + ); + request.resource = defaultValue1; + const expectedHeaderRequestParams = `resource=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.iam.v1.Policy(), + ); + client.innerApiCalls.getIamPolicy = stubSimpleCall(expectedResponse); + const [response] = await client.getIamPolicy(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getIamPolicy as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getIamPolicy as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes echo without error using callback', async () => { - const client = new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.duplicate_methods_test.v1.EchoRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.duplicate_methods_test.v1.EchoResponse() - ); - client.innerApiCalls.echo = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.echo( - request, - (err?: Error|null, result?: protos.google.duplicate_methods_test.v1.IEchoResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes getIamPolicy without error using callback', async () => { + const client = + new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.iam.v1.GetIamPolicyRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.iam.v1.GetIamPolicyRequest', + ['resource'], + ); + request.resource = defaultValue1; + const expectedHeaderRequestParams = `resource=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.iam.v1.Policy(), + ); + client.innerApiCalls.getIamPolicy = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getIamPolicy( + request, + ( + err?: Error | null, + result?: protos.google.iam.v1.IPolicy | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getIamPolicy as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getIamPolicy as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes echo with error', async () => { - const client = new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.duplicate_methods_test.v1.EchoRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.echo = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.echo(request), expectedError); - }); + it('invokes getIamPolicy with error', async () => { + const client = + new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.iam.v1.GetIamPolicyRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.iam.v1.GetIamPolicyRequest', + ['resource'], + ); + request.resource = defaultValue1; + const expectedHeaderRequestParams = `resource=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getIamPolicy = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getIamPolicy(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getIamPolicy as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getIamPolicy as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes echo with closed client', async () => { - const client = new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.duplicate_methods_test.v1.EchoRequest() - ); - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.echo(request), expectedError); - }); + it('invokes getIamPolicy with closed client', async () => { + const client = + new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.iam.v1.GetIamPolicyRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.iam.v1.GetIamPolicyRequest', + ['resource'], + ); + request.resource = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getIamPolicy(request), expectedError); }); + }); - describe('listLocations', () => { - it('invokes listLocations without error', async () => { - const client = new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.location.ListLocationsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.location.ListLocationsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.location.Location()), - generateSampleMessage(new protos.google.cloud.location.Location()), - generateSampleMessage(new protos.google.cloud.location.Location()), - ]; - client.innerApiCalls.listLocations = stubSimpleCall(expectedResponse); - const [response] = await client.listLocations(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listLocations as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listLocations as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + describe('echo', () => { + it('invokes echo without error', async () => { + const client = + new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.duplicate_methods_test.v1.EchoRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.duplicate_methods_test.v1.EchoResponse(), + ); + client.innerApiCalls.echo = stubSimpleCall(expectedResponse); + const [response] = await client.echo(request); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes listLocations without error using callback', async () => { - const client = new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.location.ListLocationsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.location.ListLocationsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.location.Location()), - generateSampleMessage(new protos.google.cloud.location.Location()), - generateSampleMessage(new protos.google.cloud.location.Location()), - ]; - client.innerApiCalls.listLocations = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listLocations( - request, - (err?: Error|null, result?: protos.google.cloud.location.ILocation[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listLocations as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listLocations as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes echo without error using callback', async () => { + const client = + new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.duplicate_methods_test.v1.EchoRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.duplicate_methods_test.v1.EchoResponse(), + ); + client.innerApiCalls.echo = stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.echo( + request, + ( + err?: Error | null, + result?: protos.google.duplicate_methods_test.v1.IEchoResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes listLocations with error', async () => { - const client = new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.location.ListLocationsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.location.ListLocationsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listLocations = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listLocations(request), expectedError); - const actualRequest = (client.innerApiCalls.listLocations as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listLocations as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes echo with error', async () => { + const client = + new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.duplicate_methods_test.v1.EchoRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.echo = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.echo(request), expectedError); + }); - it('invokes listLocationsStream without error', async () => { - const client = new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.location.ListLocationsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.location.ListLocationsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.location.Location()), - generateSampleMessage(new protos.google.cloud.location.Location()), - generateSampleMessage(new protos.google.cloud.location.Location()), - ]; - client.descriptors.page.listLocations.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listLocationsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.cloud.location.Location[] = []; - stream.on('data', (response: protos.google.cloud.location.Location) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.listLocations.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listLocations, request)); - assert( - (client.descriptors.page.listLocations.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes echo with closed client', async () => { + const client = + new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.duplicate_methods_test.v1.EchoRequest(), + ); + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.echo(request), expectedError); + }); + }); - it('invokes listLocationsStream with error', async () => { - const client = new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.location.ListLocationsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.location.ListLocationsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listLocations.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listLocationsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.cloud.location.Location[] = []; - stream.on('data', (response: protos.google.cloud.location.Location) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listLocations.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listLocations, request)); - assert( - (client.descriptors.page.listLocations.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + describe('listLocations', () => { + it('invokes listLocations without error', async () => { + const client = + new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.location.ListLocationsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.location.ListLocationsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.location.Location()), + generateSampleMessage(new protos.google.cloud.location.Location()), + generateSampleMessage(new protos.google.cloud.location.Location()), + ]; + client.innerApiCalls.listLocations = stubSimpleCall(expectedResponse); + const [response] = await client.listLocations(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listLocations as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listLocations as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('uses async iteration with listLocations without error', async () => { - const client = new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.location.ListLocationsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.location.ListLocationsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.location.Location()), - generateSampleMessage(new protos.google.cloud.location.Location()), - generateSampleMessage(new protos.google.cloud.location.Location()), - ]; - client.descriptors.page.listLocations.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.cloud.location.ILocation[] = []; - const iterable = client.listLocationsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); + it('invokes listLocations without error using callback', async () => { + const client = + new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.location.ListLocationsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.location.ListLocationsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.location.Location()), + generateSampleMessage(new protos.google.cloud.location.Location()), + generateSampleMessage(new protos.google.cloud.location.Location()), + ]; + client.innerApiCalls.listLocations = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listLocations( + request, + ( + err?: Error | null, + result?: protos.google.cloud.location.ILocation[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listLocations.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listLocations.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listLocations as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listLocations as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('uses async iteration with listLocations with error', async () => { - const client = new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.location.ListLocationsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.location.ListLocationsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listLocations.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listLocationsAsync(request); - await assert.rejects(async () => { - const responses: protos.google.cloud.location.ILocation[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listLocations.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listLocations.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listLocations with error', async () => { + const client = + new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.location.ListLocationsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.location.ListLocationsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listLocations = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listLocations(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listLocations as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listLocations as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('setIamPolicy', () => { - it('invokes setIamPolicy without error', async () => { - const client = new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new IamProtos.google.iam.v1.SetIamPolicyRequest() - ); - request.resource = ''; - const expectedHeaderRequestParams = 'resource='; - const expectedOptions = { - otherArgs: { - headers: { - 'x-goog-request-params': expectedHeaderRequestParams, - }, - }, - }; - const expectedResponse = generateSampleMessage( - new IamProtos.google.iam.v1.Policy() - ); - client.iamClient.setIamPolicy = stubSimpleCall(expectedResponse); - const response = await client.setIamPolicy(request, expectedOptions); - assert.deepStrictEqual(response, [expectedResponse]); - assert((client.iamClient.setIamPolicy as SinonStub) - .getCall(0).calledWith(request, expectedOptions, undefined)); + + it('invokes listLocationsStream without error', async () => { + const client = + new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.location.ListLocationsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.location.ListLocationsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.location.Location()), + generateSampleMessage(new protos.google.cloud.location.Location()), + generateSampleMessage(new protos.google.cloud.location.Location()), + ]; + client.descriptors.page.listLocations.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listLocationsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.cloud.location.Location[] = []; + stream.on('data', (response: protos.google.cloud.location.Location) => { + responses.push(response); }); - it('invokes setIamPolicy without error using callback', async () => { - const client = new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new IamProtos.google.iam.v1.SetIamPolicyRequest() - ); - request.resource = ''; - const expectedHeaderRequestParams = 'resource='; - const expectedOptions = { - otherArgs: { - headers: { - 'x-goog-request-params': expectedHeaderRequestParams, - }, - }, - }; - const expectedResponse = generateSampleMessage( - new IamProtos.google.iam.v1.Policy() - ); - client.iamClient.setIamPolicy = sinon.stub().callsArgWith(2, null, expectedResponse); - const promise = new Promise((resolve, reject) => { - client.setIamPolicy( - request, - expectedOptions, - (err?: Error|null, result?: IamProtos.google.iam.v1.Policy|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }).catch(err => {throw err}); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - assert((client.iamClient.setIamPolicy as SinonStub) - .getCall(0)); + stream.on('end', () => { + resolve(responses); }); - it('invokes setIamPolicy with error', async () => { - const client = new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new IamProtos.google.iam.v1.SetIamPolicyRequest() - ); - request.resource = ''; - const expectedHeaderRequestParams = 'resource='; - const expectedOptions = { - otherArgs: { - headers: { - 'x-goog-request-params': expectedHeaderRequestParams, - }, - }, - }; - const expectedError = new Error('expected'); - client.iamClient.setIamPolicy = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.setIamPolicy(request, expectedOptions), expectedError); - assert((client.iamClient.setIamPolicy as SinonStub) - .getCall(0).calledWith(request, expectedOptions, undefined)); + stream.on('error', (err: Error) => { + reject(err); }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listLocations.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listLocations, request), + ); + assert( + (client.descriptors.page.listLocations.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); }); - describe('testIamPermissions', () => { - it('invokes testIamPermissions without error', async () => { - const client = new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new IamProtos.google.iam.v1.TestIamPermissionsRequest() - ); - request.resource = ''; - const expectedHeaderRequestParams = 'resource='; - const expectedOptions = { - otherArgs: { - headers: { - 'x-goog-request-params': expectedHeaderRequestParams, - }, - }, - }; - const expectedResponse = generateSampleMessage( - new IamProtos.google.iam.v1.TestIamPermissionsResponse() - ); - client.iamClient.testIamPermissions = stubSimpleCall(expectedResponse); - const response = await client.testIamPermissions(request, expectedOptions); - assert.deepStrictEqual(response, [expectedResponse]); - assert((client.iamClient.testIamPermissions as SinonStub) - .getCall(0).calledWith(request, expectedOptions, undefined)); + + it('invokes listLocationsStream with error', async () => { + const client = + new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.location.ListLocationsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.location.ListLocationsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listLocations.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listLocationsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.cloud.location.Location[] = []; + stream.on('data', (response: protos.google.cloud.location.Location) => { + responses.push(response); }); - it('invokes testIamPermissions without error using callback', async () => { - const client = new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new IamProtos.google.iam.v1.TestIamPermissionsRequest() - ); - request.resource = ''; - const expectedHeaderRequestParams = 'resource='; - const expectedOptions = { - otherArgs: { - headers: { - 'x-goog-request-params': expectedHeaderRequestParams, - }, - }, - }; - const expectedResponse = generateSampleMessage( - new IamProtos.google.iam.v1.TestIamPermissionsResponse() - ); - client.iamClient.testIamPermissions = sinon.stub().callsArgWith(2, null, expectedResponse); - const promise = new Promise((resolve, reject) => { - client.testIamPermissions( - request, - expectedOptions, - (err?: Error|null, result?: IamProtos.google.iam.v1.TestIamPermissionsResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }).catch(err => {throw err}); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - assert((client.iamClient.testIamPermissions as SinonStub) - .getCall(0)); + stream.on('end', () => { + resolve(responses); }); - it('invokes testIamPermissions with error', async () => { - const client = new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new IamProtos.google.iam.v1.TestIamPermissionsRequest() - ); - request.resource = ''; - const expectedHeaderRequestParams = 'resource='; - const expectedOptions = { - otherArgs: { - headers: { - 'x-goog-request-params': expectedHeaderRequestParams, - }, - }, - }; - const expectedError = new Error('expected'); - client.iamClient.testIamPermissions = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.testIamPermissions(request, expectedOptions), expectedError); - assert((client.iamClient.testIamPermissions as SinonStub) - .getCall(0).calledWith(request, expectedOptions, undefined)); + stream.on('error', (err: Error) => { + reject(err); }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listLocations.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listLocations, request), + ); + assert( + (client.descriptors.page.listLocations.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); }); - describe('getLocation', () => { - it('invokes getLocation without error', async () => { - const client = new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new LocationProtos.google.cloud.location.GetLocationRequest() - ); - request.name = ''; - const expectedHeaderRequestParams = 'name='; - const expectedOptions = { - otherArgs: { - headers: { - 'x-goog-request-params': expectedHeaderRequestParams, - }, - }, - }; - const expectedResponse = generateSampleMessage( - new LocationProtos.google.cloud.location.Location() - ); - client.locationsClient.getLocation = stubSimpleCall(expectedResponse); - const response = await client.getLocation(request, expectedOptions); - assert.deepStrictEqual(response, [expectedResponse]); - assert((client.locationsClient.getLocation as SinonStub) - .getCall(0).calledWith(request, expectedOptions, undefined)); - }); - it('invokes getLocation without error using callback', async () => { - const client = new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new LocationProtos.google.cloud.location.GetLocationRequest() - ); - request.name = ''; - const expectedHeaderRequestParams = 'name='; - const expectedOptions = { - otherArgs: { - headers: { - 'x-goog-request-params': expectedHeaderRequestParams, - }, - }, - }; - const expectedResponse = generateSampleMessage( - new LocationProtos.google.cloud.location.Location() - ); - client.locationsClient.getLocation = sinon.stub().callsArgWith(2, null, expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getLocation( - request, - expectedOptions, - ( - err?: Error | null, - result?: LocationProtos.google.cloud.location.ILocation | null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - assert((client.locationsClient.getLocation as SinonStub) - .getCall(0)); - }); - it('invokes getLocation with error', async () => { - const client = new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new LocationProtos.google.cloud.location.GetLocationRequest() - ); - request.name = ''; - const expectedHeaderRequestParams = 'name='; - const expectedOptions = { - otherArgs: { - headers: { - 'x-goog-request-params': expectedHeaderRequestParams, - }, - }, - }; - const expectedError = new Error('expected'); - client.locationsClient.getLocation = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getLocation(request, expectedOptions), expectedError); - assert((client.locationsClient.getLocation as SinonStub) - .getCall(0).calledWith(request, expectedOptions, undefined)); - }); + + it('uses async iteration with listLocations without error', async () => { + const client = + new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.location.ListLocationsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.location.ListLocationsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.location.Location()), + generateSampleMessage(new protos.google.cloud.location.Location()), + generateSampleMessage(new protos.google.cloud.location.Location()), + ]; + client.descriptors.page.listLocations.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.cloud.location.ILocation[] = []; + const iterable = client.listLocationsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listLocations.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listLocations.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + + it('uses async iteration with listLocations with error', async () => { + const client = + new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.location.ListLocationsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.location.ListLocationsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listLocations.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listLocationsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.cloud.location.ILocation[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listLocations.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listLocations.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + }); + describe('setIamPolicy', () => { + it('invokes setIamPolicy without error', async () => { + const client = + new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new IamProtos.google.iam.v1.SetIamPolicyRequest(), + ); + request.resource = ''; + const expectedHeaderRequestParams = 'resource='; + const expectedOptions = { + otherArgs: { + headers: { + 'x-goog-request-params': expectedHeaderRequestParams, + }, + }, + }; + const expectedResponse = generateSampleMessage( + new IamProtos.google.iam.v1.Policy(), + ); + client.iamClient.setIamPolicy = stubSimpleCall(expectedResponse); + const response = await client.setIamPolicy(request, expectedOptions); + assert.deepStrictEqual(response, [expectedResponse]); + assert( + (client.iamClient.setIamPolicy as SinonStub) + .getCall(0) + .calledWith(request, expectedOptions, undefined), + ); + }); + it('invokes setIamPolicy without error using callback', async () => { + const client = + new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new IamProtos.google.iam.v1.SetIamPolicyRequest(), + ); + request.resource = ''; + const expectedHeaderRequestParams = 'resource='; + const expectedOptions = { + otherArgs: { + headers: { + 'x-goog-request-params': expectedHeaderRequestParams, + }, + }, + }; + const expectedResponse = generateSampleMessage( + new IamProtos.google.iam.v1.Policy(), + ); + client.iamClient.setIamPolicy = sinon + .stub() + .callsArgWith(2, null, expectedResponse); + const promise = new Promise((resolve, reject) => { + client + .setIamPolicy( + request, + expectedOptions, + ( + err?: Error | null, + result?: IamProtos.google.iam.v1.Policy | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ) + .catch((err) => { + throw err; + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + assert((client.iamClient.setIamPolicy as SinonStub).getCall(0)); + }); + it('invokes setIamPolicy with error', async () => { + const client = + new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new IamProtos.google.iam.v1.SetIamPolicyRequest(), + ); + request.resource = ''; + const expectedHeaderRequestParams = 'resource='; + const expectedOptions = { + otherArgs: { + headers: { + 'x-goog-request-params': expectedHeaderRequestParams, + }, + }, + }; + const expectedError = new Error('expected'); + client.iamClient.setIamPolicy = stubSimpleCall(undefined, expectedError); + await assert.rejects( + client.setIamPolicy(request, expectedOptions), + expectedError, + ); + assert( + (client.iamClient.setIamPolicy as SinonStub) + .getCall(0) + .calledWith(request, expectedOptions, undefined), + ); + }); + }); + describe('testIamPermissions', () => { + it('invokes testIamPermissions without error', async () => { + const client = + new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new IamProtos.google.iam.v1.TestIamPermissionsRequest(), + ); + request.resource = ''; + const expectedHeaderRequestParams = 'resource='; + const expectedOptions = { + otherArgs: { + headers: { + 'x-goog-request-params': expectedHeaderRequestParams, + }, + }, + }; + const expectedResponse = generateSampleMessage( + new IamProtos.google.iam.v1.TestIamPermissionsResponse(), + ); + client.iamClient.testIamPermissions = stubSimpleCall(expectedResponse); + const response = await client.testIamPermissions( + request, + expectedOptions, + ); + assert.deepStrictEqual(response, [expectedResponse]); + assert( + (client.iamClient.testIamPermissions as SinonStub) + .getCall(0) + .calledWith(request, expectedOptions, undefined), + ); + }); + it('invokes testIamPermissions without error using callback', async () => { + const client = + new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new IamProtos.google.iam.v1.TestIamPermissionsRequest(), + ); + request.resource = ''; + const expectedHeaderRequestParams = 'resource='; + const expectedOptions = { + otherArgs: { + headers: { + 'x-goog-request-params': expectedHeaderRequestParams, + }, + }, + }; + const expectedResponse = generateSampleMessage( + new IamProtos.google.iam.v1.TestIamPermissionsResponse(), + ); + client.iamClient.testIamPermissions = sinon + .stub() + .callsArgWith(2, null, expectedResponse); + const promise = new Promise((resolve, reject) => { + client + .testIamPermissions( + request, + expectedOptions, + ( + err?: Error | null, + result?: IamProtos.google.iam.v1.TestIamPermissionsResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ) + .catch((err) => { + throw err; + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + assert((client.iamClient.testIamPermissions as SinonStub).getCall(0)); + }); + it('invokes testIamPermissions with error', async () => { + const client = + new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new IamProtos.google.iam.v1.TestIamPermissionsRequest(), + ); + request.resource = ''; + const expectedHeaderRequestParams = 'resource='; + const expectedOptions = { + otherArgs: { + headers: { + 'x-goog-request-params': expectedHeaderRequestParams, + }, + }, + }; + const expectedError = new Error('expected'); + client.iamClient.testIamPermissions = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.testIamPermissions(request, expectedOptions), + expectedError, + ); + assert( + (client.iamClient.testIamPermissions as SinonStub) + .getCall(0) + .calledWith(request, expectedOptions, undefined), + ); + }); + }); + describe('getLocation', () => { + it('invokes getLocation without error', async () => { + const client = + new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new LocationProtos.google.cloud.location.GetLocationRequest(), + ); + request.name = ''; + const expectedHeaderRequestParams = 'name='; + const expectedOptions = { + otherArgs: { + headers: { + 'x-goog-request-params': expectedHeaderRequestParams, + }, + }, + }; + const expectedResponse = generateSampleMessage( + new LocationProtos.google.cloud.location.Location(), + ); + client.locationsClient.getLocation = stubSimpleCall(expectedResponse); + const response = await client.getLocation(request, expectedOptions); + assert.deepStrictEqual(response, [expectedResponse]); + assert( + (client.locationsClient.getLocation as SinonStub) + .getCall(0) + .calledWith(request, expectedOptions, undefined), + ); + }); + it('invokes getLocation without error using callback', async () => { + const client = + new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new LocationProtos.google.cloud.location.GetLocationRequest(), + ); + request.name = ''; + const expectedHeaderRequestParams = 'name='; + const expectedOptions = { + otherArgs: { + headers: { + 'x-goog-request-params': expectedHeaderRequestParams, + }, + }, + }; + const expectedResponse = generateSampleMessage( + new LocationProtos.google.cloud.location.Location(), + ); + client.locationsClient.getLocation = sinon + .stub() + .callsArgWith(2, null, expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getLocation( + request, + expectedOptions, + ( + err?: Error | null, + result?: LocationProtos.google.cloud.location.ILocation | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + assert((client.locationsClient.getLocation as SinonStub).getCall(0)); + }); + it('invokes getLocation with error', async () => { + const client = + new duplicatemethodstestserviceModule.v1.DuplicateMethodsTestServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new LocationProtos.google.cloud.location.GetLocationRequest(), + ); + request.name = ''; + const expectedHeaderRequestParams = 'name='; + const expectedOptions = { + otherArgs: { + headers: { + 'x-goog-request-params': expectedHeaderRequestParams, + }, + }, + }; + const expectedError = new Error('expected'); + client.locationsClient.getLocation = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.getLocation(request, expectedOptions), + expectedError, + ); + assert( + (client.locationsClient.getLocation as SinonStub) + .getCall(0) + .calledWith(request, expectedOptions, undefined), + ); }); + }); }); diff --git a/core/generator/gapic-generator-typescript/baselines/kms-esm/esm/src/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/kms-esm/esm/src/index.ts.baseline index 8d2cd5910206..f85c77550337 100644 --- a/core/generator/gapic-generator-typescript/baselines/kms-esm/esm/src/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/kms-esm/esm/src/index.ts.baseline @@ -19,8 +19,8 @@ import * as v1 from './v1/index.js'; const KeyManagementServiceClient = v1.KeyManagementServiceClient; type KeyManagementServiceClient = v1.KeyManagementServiceClient; -export {v1, KeyManagementServiceClient}; -export default {v1, KeyManagementServiceClient}; +export { v1, KeyManagementServiceClient }; +export default { v1, KeyManagementServiceClient }; // @ts-ignore import * as protos from '../../protos/protos.js'; -export {protos} +export { protos }; diff --git a/core/generator/gapic-generator-typescript/baselines/kms-esm/esm/src/v1/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/kms-esm/esm/src/v1/index.ts.baseline index 9e6bc3bc748c..4873ef49f746 100644 --- a/core/generator/gapic-generator-typescript/baselines/kms-esm/esm/src/v1/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/kms-esm/esm/src/v1/index.ts.baseline @@ -16,4 +16,4 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -export {KeyManagementServiceClient} from './key_management_service_client.js'; +export { KeyManagementServiceClient } from './key_management_service_client.js'; diff --git a/core/generator/gapic-generator-typescript/baselines/kms-esm/esm/src/v1/key_management_service_client.ts.baseline b/core/generator/gapic-generator-typescript/baselines/kms-esm/esm/src/v1/key_management_service_client.ts.baseline index 205e430c9fc7..c0ec9c2cb7f8 100644 --- a/core/generator/gapic-generator-typescript/baselines/kms-esm/esm/src/v1/key_management_service_client.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/kms-esm/esm/src/v1/key_management_service_client.ts.baseline @@ -18,15 +18,24 @@ /* global window */ import * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions, PaginationCallback, GaxCall, IamClient, IamProtos} from 'google-gax'; -import {Transform} from 'stream'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + PaginationCallback, + GaxCall, + IamClient, + IamProtos, +} from 'google-gax'; +import { Transform } from 'stream'; // @ts-ignore import type * as protos from '../../../protos/protos.js'; import * as key_management_service_client_config from './key_management_service_client_config.json'; import fs from 'fs'; import path from 'path'; -import {fileURLToPath} from 'url'; -import {getJSON} from '../json-helper.cjs'; +import { fileURLToPath } from 'url'; +import { getJSON } from '../json-helper.cjs'; // @ts-ignore const dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -36,15 +45,15 @@ const dirname = path.dirname(fileURLToPath(import.meta.url)); * This file defines retry strategy and timeouts for all API methods in this library. */ const gapicConfig = getJSON( - path.join(dirname, 'key_management_service_client_config.json') + path.join(dirname, 'key_management_service_client_config.json'), ); const jsonProtos = getJSON( - path.join(dirname, '..', '..', '..', 'protos/protos.json') + path.join(dirname, '..', '..', '..', 'protos/protos.json'), ); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; const version = getJSON( - path.join(dirname, '..', '..', '..', '..', 'package.json') + path.join(dirname, '..', '..', '..', '..', 'package.json'), ).version; /** @@ -69,7 +78,7 @@ export class KeyManagementServiceClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('kms'); @@ -81,9 +90,9 @@ export class KeyManagementServiceClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; + innerApiCalls: { [name: string]: Function }; iamClient: IamClient; - keyManagementServiceStub?: Promise<{[name: string]: Function}>; + keyManagementServiceStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of KeyManagementServiceClient. @@ -125,21 +134,42 @@ export class KeyManagementServiceClient { * const client = new KeyManagementServiceClient({fallback: 'rest'}, gax); * ``` */ - constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { // Ensure that options include all the required fields. const staticMembers = this.constructor as typeof KeyManagementServiceClient; - if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { - throw new Error('Please set either universe_domain or universeDomain, but not both.'); + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); } - const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; - this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; this._servicePath = 'cloudkms.' + this._universeDomain; - const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; - const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. if (servicePath !== this._servicePath && !('scopes' in opts)) { @@ -161,7 +191,7 @@ export class KeyManagementServiceClient { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; @@ -174,16 +204,12 @@ export class KeyManagementServiceClient { this.auth.defaultScopes = staticMembers.scopes; } this.iamClient = new this._gaxModule.IamClient(this._gaxGrpc, opts); - // Add ESM headers const isEsm = true; const isEsmString = isEsm ? '-esm' : '-cjs'; // Determine the client header string. - const clientHeader = [ - `gax/${this._gaxModule.version}`, - `gapic/${version}`, - ]; + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/{process.versions.node}${isEsmString}`); } else { @@ -191,7 +217,7 @@ export class KeyManagementServiceClient { } if (!opts.fallback) { clientHeader.push(`grpc/${this._gaxGrpc.grpcVersion}`); - } else if (opts.fallback === 'rest' ) { + } else if (opts.fallback === 'rest') { clientHeader.push(`rest/${this._gaxGrpc.grpcVersion}`); } if (opts.libName && opts.libVersion) { @@ -199,26 +225,43 @@ export class KeyManagementServiceClient { } // Load the applicable protos. - this._protos = this._gaxGrpc.loadProtoJSON(jsonProtos as gax.protobuf.INamespace); + this._protos = this._gaxGrpc.loadProtoJSON( + jsonProtos as gax.protobuf.INamespace, + ); // Some of the methods on this service return "paged" results, // (e.g. 50 results at a time, with tokens to get subsequent // pages). Denote the keys used for pagination and results. this.descriptors.page = { - listKeyRings: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'keyRings'), - listCryptoKeys: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'cryptoKeys'), - listCryptoKeyVersions: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'cryptoKeyVersions'), - listImportJobs: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'importJobs') + listKeyRings: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'keyRings', + ), + listCryptoKeys: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'cryptoKeys', + ), + listCryptoKeyVersions: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'cryptoKeyVersions', + ), + listImportJobs: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'importJobs', + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.cloud.kms.v1.KeyManagementService', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.cloud.kms.v1.KeyManagementService', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + { 'x-goog-api-client': clientHeader.join(' ') }, + ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -249,37 +292,64 @@ export class KeyManagementServiceClient { // Put together the "service stub" for // google.cloud.kms.v1.KeyManagementService. this.keyManagementServiceStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.cloud.kms.v1.KeyManagementService') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.cloud.kms.v1.KeyManagementService', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.cloud.kms.v1.KeyManagementService, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts, + this._providedCustomServicePath, + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const keyManagementServiceStubMethods = - ['listKeyRings', 'listCryptoKeys', 'listCryptoKeyVersions', 'listImportJobs', 'getKeyRing', 'getCryptoKey', 'getCryptoKeyVersion', 'getPublicKey', 'getImportJob', 'createKeyRing', 'createCryptoKey', 'createCryptoKeyVersion', 'importCryptoKeyVersion', 'createImportJob', 'updateCryptoKey', 'updateCryptoKeyVersion', 'encrypt', 'decrypt', 'asymmetricSign', 'asymmetricDecrypt', 'updateCryptoKeyPrimaryVersion', 'destroyCryptoKeyVersion', 'restoreCryptoKeyVersion']; + const keyManagementServiceStubMethods = [ + 'listKeyRings', + 'listCryptoKeys', + 'listCryptoKeyVersions', + 'listImportJobs', + 'getKeyRing', + 'getCryptoKey', + 'getCryptoKeyVersion', + 'getPublicKey', + 'getImportJob', + 'createKeyRing', + 'createCryptoKey', + 'createCryptoKeyVersion', + 'importCryptoKeyVersion', + 'createImportJob', + 'updateCryptoKey', + 'updateCryptoKeyVersion', + 'encrypt', + 'decrypt', + 'asymmetricSign', + 'asymmetricDecrypt', + 'updateCryptoKeyPrimaryVersion', + 'destroyCryptoKeyVersion', + 'restoreCryptoKeyVersion', + ]; for (const methodName of keyManagementServiceStubMethods) { const callPromise = this.keyManagementServiceStub.then( - stub => (...args: Array<{}>) => { - if (this._terminated) { - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error|null|undefined) => () => { + (stub) => + (...args: Array<{}>) => { + if (this._terminated) { + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { throw err; - }); + }, + ); - const descriptor = - this.descriptors.page[methodName] || - undefined; + const descriptor = this.descriptors.page[methodName] || undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -294,8 +364,14 @@ export class KeyManagementServiceClient { * @returns {string} The DNS address for this service. */ static get servicePath() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'cloudkms.googleapis.com'; } @@ -307,8 +383,14 @@ export class KeyManagementServiceClient { * @returns {string} The DNS address for this service. */ static get apiEndpoint() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'cloudkms.googleapis.com'; } @@ -341,7 +423,7 @@ export class KeyManagementServiceClient { static get scopes() { return [ 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloudkms' + 'https://www.googleapis.com/auth/cloudkms', ]; } @@ -351,8 +433,9 @@ export class KeyManagementServiceClient { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId(callback?: Callback): - Promise|void { + getProjectId( + callback?: Callback, + ): Promise | void { if (callback) { this.auth.getProjectId(callback); return; @@ -363,2015 +446,2702 @@ export class KeyManagementServiceClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Returns metadata for a given {@link protos.google.cloud.kms.v1.KeyRing|KeyRing}. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * The {@link protos.google.cloud.kms.v1.KeyRing.name|name} of the {@link protos.google.cloud.kms.v1.KeyRing|KeyRing} to get. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.kms.v1.KeyRing|KeyRing}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1/key_management_service.get_key_ring.js - * region_tag:cloudkms_v1_generated_KeyManagementService_GetKeyRing_async - */ + /** + * Returns metadata for a given {@link protos.google.cloud.kms.v1.KeyRing|KeyRing}. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * The {@link protos.google.cloud.kms.v1.KeyRing.name|name} of the {@link protos.google.cloud.kms.v1.KeyRing|KeyRing} to get. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.kms.v1.KeyRing|KeyRing}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/key_management_service.get_key_ring.js + * region_tag:cloudkms_v1_generated_KeyManagementService_GetKeyRing_async + */ getKeyRing( - request?: protos.google.cloud.kms.v1.IGetKeyRingRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.kms.v1.IKeyRing, - protos.google.cloud.kms.v1.IGetKeyRingRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.kms.v1.IGetKeyRingRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.kms.v1.IKeyRing, + protos.google.cloud.kms.v1.IGetKeyRingRequest | undefined, + {} | undefined, + ] + >; getKeyRing( - request: protos.google.cloud.kms.v1.IGetKeyRingRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.kms.v1.IKeyRing, - protos.google.cloud.kms.v1.IGetKeyRingRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.kms.v1.IGetKeyRingRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.kms.v1.IKeyRing, + protos.google.cloud.kms.v1.IGetKeyRingRequest | null | undefined, + {} | null | undefined + >, + ): void; getKeyRing( - request: protos.google.cloud.kms.v1.IGetKeyRingRequest, - callback: Callback< - protos.google.cloud.kms.v1.IKeyRing, - protos.google.cloud.kms.v1.IGetKeyRingRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.kms.v1.IGetKeyRingRequest, + callback: Callback< + protos.google.cloud.kms.v1.IKeyRing, + protos.google.cloud.kms.v1.IGetKeyRingRequest | null | undefined, + {} | null | undefined + >, + ): void; getKeyRing( - request?: protos.google.cloud.kms.v1.IGetKeyRingRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.kms.v1.IKeyRing, - protos.google.cloud.kms.v1.IGetKeyRingRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.kms.v1.IGetKeyRingRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.kms.v1.IKeyRing, - protos.google.cloud.kms.v1.IGetKeyRingRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.kms.v1.IKeyRing, - protos.google.cloud.kms.v1.IGetKeyRingRequest|undefined, {}|undefined - ]>|void { + protos.google.cloud.kms.v1.IGetKeyRingRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.kms.v1.IKeyRing, + protos.google.cloud.kms.v1.IGetKeyRingRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.kms.v1.IKeyRing, + protos.google.cloud.kms.v1.IGetKeyRingRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getKeyRing request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.kms.v1.IKeyRing, - protos.google.cloud.kms.v1.IGetKeyRingRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.kms.v1.IKeyRing, + protos.google.cloud.kms.v1.IGetKeyRingRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getKeyRing response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.getKeyRing(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.kms.v1.IKeyRing, - protos.google.cloud.kms.v1.IGetKeyRingRequest|undefined, {}|undefined - ]) => { - this._log.info('getKeyRing response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getKeyRing(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.kms.v1.IKeyRing, + protos.google.cloud.kms.v1.IGetKeyRingRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getKeyRing response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Returns metadata for a given {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKey}, as well as its - * {@link protos.google.cloud.kms.v1.CryptoKey.primary|primary} {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersion}. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * The {@link protos.google.cloud.kms.v1.CryptoKey.name|name} of the {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKey} to get. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKey}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1/key_management_service.get_crypto_key.js - * region_tag:cloudkms_v1_generated_KeyManagementService_GetCryptoKey_async - */ + /** + * Returns metadata for a given {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKey}, as well as its + * {@link protos.google.cloud.kms.v1.CryptoKey.primary|primary} {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersion}. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * The {@link protos.google.cloud.kms.v1.CryptoKey.name|name} of the {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKey} to get. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKey}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/key_management_service.get_crypto_key.js + * region_tag:cloudkms_v1_generated_KeyManagementService_GetCryptoKey_async + */ getCryptoKey( - request?: protos.google.cloud.kms.v1.IGetCryptoKeyRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.kms.v1.ICryptoKey, - protos.google.cloud.kms.v1.IGetCryptoKeyRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.kms.v1.IGetCryptoKeyRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.kms.v1.ICryptoKey, + protos.google.cloud.kms.v1.IGetCryptoKeyRequest | undefined, + {} | undefined, + ] + >; getCryptoKey( - request: protos.google.cloud.kms.v1.IGetCryptoKeyRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.kms.v1.ICryptoKey, - protos.google.cloud.kms.v1.IGetCryptoKeyRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.kms.v1.IGetCryptoKeyRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.kms.v1.ICryptoKey, + protos.google.cloud.kms.v1.IGetCryptoKeyRequest | null | undefined, + {} | null | undefined + >, + ): void; getCryptoKey( - request: protos.google.cloud.kms.v1.IGetCryptoKeyRequest, - callback: Callback< - protos.google.cloud.kms.v1.ICryptoKey, - protos.google.cloud.kms.v1.IGetCryptoKeyRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.kms.v1.IGetCryptoKeyRequest, + callback: Callback< + protos.google.cloud.kms.v1.ICryptoKey, + protos.google.cloud.kms.v1.IGetCryptoKeyRequest | null | undefined, + {} | null | undefined + >, + ): void; getCryptoKey( - request?: protos.google.cloud.kms.v1.IGetCryptoKeyRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.kms.v1.ICryptoKey, - protos.google.cloud.kms.v1.IGetCryptoKeyRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.kms.v1.IGetCryptoKeyRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.kms.v1.ICryptoKey, - protos.google.cloud.kms.v1.IGetCryptoKeyRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.kms.v1.ICryptoKey, - protos.google.cloud.kms.v1.IGetCryptoKeyRequest|undefined, {}|undefined - ]>|void { + protos.google.cloud.kms.v1.IGetCryptoKeyRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.kms.v1.ICryptoKey, + protos.google.cloud.kms.v1.IGetCryptoKeyRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.kms.v1.ICryptoKey, + protos.google.cloud.kms.v1.IGetCryptoKeyRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getCryptoKey request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.kms.v1.ICryptoKey, - protos.google.cloud.kms.v1.IGetCryptoKeyRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.kms.v1.ICryptoKey, + protos.google.cloud.kms.v1.IGetCryptoKeyRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getCryptoKey response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.getCryptoKey(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.kms.v1.ICryptoKey, - protos.google.cloud.kms.v1.IGetCryptoKeyRequest|undefined, {}|undefined - ]) => { - this._log.info('getCryptoKey response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getCryptoKey(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.kms.v1.ICryptoKey, + protos.google.cloud.kms.v1.IGetCryptoKeyRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getCryptoKey response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Returns metadata for a given {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersion}. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * The {@link protos.google.cloud.kms.v1.CryptoKeyVersion.name|name} of the {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersion} to get. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersion}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1/key_management_service.get_crypto_key_version.js - * region_tag:cloudkms_v1_generated_KeyManagementService_GetCryptoKeyVersion_async - */ + /** + * Returns metadata for a given {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersion}. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * The {@link protos.google.cloud.kms.v1.CryptoKeyVersion.name|name} of the {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersion} to get. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersion}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/key_management_service.get_crypto_key_version.js + * region_tag:cloudkms_v1_generated_KeyManagementService_GetCryptoKeyVersion_async + */ getCryptoKeyVersion( - request?: protos.google.cloud.kms.v1.IGetCryptoKeyVersionRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.kms.v1.ICryptoKeyVersion, - protos.google.cloud.kms.v1.IGetCryptoKeyVersionRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.kms.v1.IGetCryptoKeyVersionRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.kms.v1.ICryptoKeyVersion, + protos.google.cloud.kms.v1.IGetCryptoKeyVersionRequest | undefined, + {} | undefined, + ] + >; getCryptoKeyVersion( - request: protos.google.cloud.kms.v1.IGetCryptoKeyVersionRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.kms.v1.ICryptoKeyVersion, - protos.google.cloud.kms.v1.IGetCryptoKeyVersionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.kms.v1.IGetCryptoKeyVersionRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.kms.v1.ICryptoKeyVersion, + protos.google.cloud.kms.v1.IGetCryptoKeyVersionRequest | null | undefined, + {} | null | undefined + >, + ): void; getCryptoKeyVersion( - request: protos.google.cloud.kms.v1.IGetCryptoKeyVersionRequest, - callback: Callback< - protos.google.cloud.kms.v1.ICryptoKeyVersion, - protos.google.cloud.kms.v1.IGetCryptoKeyVersionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.kms.v1.IGetCryptoKeyVersionRequest, + callback: Callback< + protos.google.cloud.kms.v1.ICryptoKeyVersion, + protos.google.cloud.kms.v1.IGetCryptoKeyVersionRequest | null | undefined, + {} | null | undefined + >, + ): void; getCryptoKeyVersion( - request?: protos.google.cloud.kms.v1.IGetCryptoKeyVersionRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.kms.v1.ICryptoKeyVersion, - protos.google.cloud.kms.v1.IGetCryptoKeyVersionRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.kms.v1.IGetCryptoKeyVersionRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.kms.v1.ICryptoKeyVersion, - protos.google.cloud.kms.v1.IGetCryptoKeyVersionRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.kms.v1.ICryptoKeyVersion, - protos.google.cloud.kms.v1.IGetCryptoKeyVersionRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.kms.v1.IGetCryptoKeyVersionRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.kms.v1.ICryptoKeyVersion, + protos.google.cloud.kms.v1.IGetCryptoKeyVersionRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.kms.v1.ICryptoKeyVersion, + protos.google.cloud.kms.v1.IGetCryptoKeyVersionRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getCryptoKeyVersion request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.kms.v1.ICryptoKeyVersion, - protos.google.cloud.kms.v1.IGetCryptoKeyVersionRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.kms.v1.ICryptoKeyVersion, + | protos.google.cloud.kms.v1.IGetCryptoKeyVersionRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getCryptoKeyVersion response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.getCryptoKeyVersion(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.kms.v1.ICryptoKeyVersion, - protos.google.cloud.kms.v1.IGetCryptoKeyVersionRequest|undefined, {}|undefined - ]) => { - this._log.info('getCryptoKeyVersion response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getCryptoKeyVersion(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.kms.v1.ICryptoKeyVersion, + protos.google.cloud.kms.v1.IGetCryptoKeyVersionRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getCryptoKeyVersion response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Returns the public key for the given {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersion}. The - * {@link protos.google.cloud.kms.v1.CryptoKey.purpose|CryptoKey.purpose} must be - * {@link protos.google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ASYMMETRIC_SIGN|ASYMMETRIC_SIGN} or - * {@link protos.google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ASYMMETRIC_DECRYPT|ASYMMETRIC_DECRYPT}. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * The {@link protos.google.cloud.kms.v1.CryptoKeyVersion.name|name} of the {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersion} public key to - * get. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.kms.v1.PublicKey|PublicKey}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1/key_management_service.get_public_key.js - * region_tag:cloudkms_v1_generated_KeyManagementService_GetPublicKey_async - */ + /** + * Returns the public key for the given {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersion}. The + * {@link protos.google.cloud.kms.v1.CryptoKey.purpose|CryptoKey.purpose} must be + * {@link protos.google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ASYMMETRIC_SIGN|ASYMMETRIC_SIGN} or + * {@link protos.google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ASYMMETRIC_DECRYPT|ASYMMETRIC_DECRYPT}. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * The {@link protos.google.cloud.kms.v1.CryptoKeyVersion.name|name} of the {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersion} public key to + * get. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.kms.v1.PublicKey|PublicKey}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/key_management_service.get_public_key.js + * region_tag:cloudkms_v1_generated_KeyManagementService_GetPublicKey_async + */ getPublicKey( - request?: protos.google.cloud.kms.v1.IGetPublicKeyRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.kms.v1.IPublicKey, - protos.google.cloud.kms.v1.IGetPublicKeyRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.kms.v1.IGetPublicKeyRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.kms.v1.IPublicKey, + protos.google.cloud.kms.v1.IGetPublicKeyRequest | undefined, + {} | undefined, + ] + >; getPublicKey( - request: protos.google.cloud.kms.v1.IGetPublicKeyRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.kms.v1.IPublicKey, - protos.google.cloud.kms.v1.IGetPublicKeyRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.kms.v1.IGetPublicKeyRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.kms.v1.IPublicKey, + protos.google.cloud.kms.v1.IGetPublicKeyRequest | null | undefined, + {} | null | undefined + >, + ): void; getPublicKey( - request: protos.google.cloud.kms.v1.IGetPublicKeyRequest, - callback: Callback< - protos.google.cloud.kms.v1.IPublicKey, - protos.google.cloud.kms.v1.IGetPublicKeyRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.kms.v1.IGetPublicKeyRequest, + callback: Callback< + protos.google.cloud.kms.v1.IPublicKey, + protos.google.cloud.kms.v1.IGetPublicKeyRequest | null | undefined, + {} | null | undefined + >, + ): void; getPublicKey( - request?: protos.google.cloud.kms.v1.IGetPublicKeyRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.kms.v1.IPublicKey, - protos.google.cloud.kms.v1.IGetPublicKeyRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.kms.v1.IGetPublicKeyRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.kms.v1.IPublicKey, - protos.google.cloud.kms.v1.IGetPublicKeyRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.kms.v1.IPublicKey, - protos.google.cloud.kms.v1.IGetPublicKeyRequest|undefined, {}|undefined - ]>|void { + protos.google.cloud.kms.v1.IGetPublicKeyRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.kms.v1.IPublicKey, + protos.google.cloud.kms.v1.IGetPublicKeyRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.kms.v1.IPublicKey, + protos.google.cloud.kms.v1.IGetPublicKeyRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getPublicKey request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.kms.v1.IPublicKey, - protos.google.cloud.kms.v1.IGetPublicKeyRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.kms.v1.IPublicKey, + protos.google.cloud.kms.v1.IGetPublicKeyRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getPublicKey response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.getPublicKey(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.kms.v1.IPublicKey, - protos.google.cloud.kms.v1.IGetPublicKeyRequest|undefined, {}|undefined - ]) => { - this._log.info('getPublicKey response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getPublicKey(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.kms.v1.IPublicKey, + protos.google.cloud.kms.v1.IGetPublicKeyRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getPublicKey response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Returns metadata for a given {@link protos.google.cloud.kms.v1.ImportJob|ImportJob}. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * The {@link protos.google.cloud.kms.v1.ImportJob.name|name} of the {@link protos.google.cloud.kms.v1.ImportJob|ImportJob} to get. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.kms.v1.ImportJob|ImportJob}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1/key_management_service.get_import_job.js - * region_tag:cloudkms_v1_generated_KeyManagementService_GetImportJob_async - */ + /** + * Returns metadata for a given {@link protos.google.cloud.kms.v1.ImportJob|ImportJob}. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * The {@link protos.google.cloud.kms.v1.ImportJob.name|name} of the {@link protos.google.cloud.kms.v1.ImportJob|ImportJob} to get. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.kms.v1.ImportJob|ImportJob}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/key_management_service.get_import_job.js + * region_tag:cloudkms_v1_generated_KeyManagementService_GetImportJob_async + */ getImportJob( - request?: protos.google.cloud.kms.v1.IGetImportJobRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.kms.v1.IImportJob, - protos.google.cloud.kms.v1.IGetImportJobRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.kms.v1.IGetImportJobRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.kms.v1.IImportJob, + protos.google.cloud.kms.v1.IGetImportJobRequest | undefined, + {} | undefined, + ] + >; getImportJob( - request: protos.google.cloud.kms.v1.IGetImportJobRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.kms.v1.IImportJob, - protos.google.cloud.kms.v1.IGetImportJobRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.kms.v1.IGetImportJobRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.kms.v1.IImportJob, + protos.google.cloud.kms.v1.IGetImportJobRequest | null | undefined, + {} | null | undefined + >, + ): void; getImportJob( - request: protos.google.cloud.kms.v1.IGetImportJobRequest, - callback: Callback< - protos.google.cloud.kms.v1.IImportJob, - protos.google.cloud.kms.v1.IGetImportJobRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.kms.v1.IGetImportJobRequest, + callback: Callback< + protos.google.cloud.kms.v1.IImportJob, + protos.google.cloud.kms.v1.IGetImportJobRequest | null | undefined, + {} | null | undefined + >, + ): void; getImportJob( - request?: protos.google.cloud.kms.v1.IGetImportJobRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.kms.v1.IImportJob, - protos.google.cloud.kms.v1.IGetImportJobRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.kms.v1.IGetImportJobRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.kms.v1.IImportJob, - protos.google.cloud.kms.v1.IGetImportJobRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.kms.v1.IImportJob, - protos.google.cloud.kms.v1.IGetImportJobRequest|undefined, {}|undefined - ]>|void { + protos.google.cloud.kms.v1.IGetImportJobRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.kms.v1.IImportJob, + protos.google.cloud.kms.v1.IGetImportJobRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.kms.v1.IImportJob, + protos.google.cloud.kms.v1.IGetImportJobRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getImportJob request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.kms.v1.IImportJob, - protos.google.cloud.kms.v1.IGetImportJobRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.kms.v1.IImportJob, + protos.google.cloud.kms.v1.IGetImportJobRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getImportJob response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.getImportJob(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.kms.v1.IImportJob, - protos.google.cloud.kms.v1.IGetImportJobRequest|undefined, {}|undefined - ]) => { - this._log.info('getImportJob response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getImportJob(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.kms.v1.IImportJob, + protos.google.cloud.kms.v1.IGetImportJobRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getImportJob response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Create a new {@link protos.google.cloud.kms.v1.KeyRing|KeyRing} in a given Project and Location. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The resource name of the location associated with the - * {@link protos.google.cloud.kms.v1.KeyRing|KeyRings}, in the format `projects/* /locations/*`. - * @param {string} request.keyRingId - * Required. It must be unique within a location and match the regular - * expression `[a-zA-Z0-9_-]{1,63}` - * @param {google.cloud.kms.v1.KeyRing} request.keyRing - * A {@link protos.google.cloud.kms.v1.KeyRing|KeyRing} with initial field values. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.kms.v1.KeyRing|KeyRing}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1/key_management_service.create_key_ring.js - * region_tag:cloudkms_v1_generated_KeyManagementService_CreateKeyRing_async - */ + /** + * Create a new {@link protos.google.cloud.kms.v1.KeyRing|KeyRing} in a given Project and Location. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The resource name of the location associated with the + * {@link protos.google.cloud.kms.v1.KeyRing|KeyRings}, in the format `projects/* /locations/*`. + * @param {string} request.keyRingId + * Required. It must be unique within a location and match the regular + * expression `[a-zA-Z0-9_-]{1,63}` + * @param {google.cloud.kms.v1.KeyRing} request.keyRing + * A {@link protos.google.cloud.kms.v1.KeyRing|KeyRing} with initial field values. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.kms.v1.KeyRing|KeyRing}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/key_management_service.create_key_ring.js + * region_tag:cloudkms_v1_generated_KeyManagementService_CreateKeyRing_async + */ createKeyRing( - request?: protos.google.cloud.kms.v1.ICreateKeyRingRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.kms.v1.IKeyRing, - protos.google.cloud.kms.v1.ICreateKeyRingRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.kms.v1.ICreateKeyRingRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.kms.v1.IKeyRing, + protos.google.cloud.kms.v1.ICreateKeyRingRequest | undefined, + {} | undefined, + ] + >; createKeyRing( - request: protos.google.cloud.kms.v1.ICreateKeyRingRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.kms.v1.IKeyRing, - protos.google.cloud.kms.v1.ICreateKeyRingRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.kms.v1.ICreateKeyRingRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.kms.v1.IKeyRing, + protos.google.cloud.kms.v1.ICreateKeyRingRequest | null | undefined, + {} | null | undefined + >, + ): void; createKeyRing( - request: protos.google.cloud.kms.v1.ICreateKeyRingRequest, - callback: Callback< - protos.google.cloud.kms.v1.IKeyRing, - protos.google.cloud.kms.v1.ICreateKeyRingRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.kms.v1.ICreateKeyRingRequest, + callback: Callback< + protos.google.cloud.kms.v1.IKeyRing, + protos.google.cloud.kms.v1.ICreateKeyRingRequest | null | undefined, + {} | null | undefined + >, + ): void; createKeyRing( - request?: protos.google.cloud.kms.v1.ICreateKeyRingRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.kms.v1.IKeyRing, - protos.google.cloud.kms.v1.ICreateKeyRingRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.kms.v1.ICreateKeyRingRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.kms.v1.IKeyRing, - protos.google.cloud.kms.v1.ICreateKeyRingRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.kms.v1.IKeyRing, - protos.google.cloud.kms.v1.ICreateKeyRingRequest|undefined, {}|undefined - ]>|void { + protos.google.cloud.kms.v1.ICreateKeyRingRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.kms.v1.IKeyRing, + protos.google.cloud.kms.v1.ICreateKeyRingRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.kms.v1.IKeyRing, + protos.google.cloud.kms.v1.ICreateKeyRingRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('createKeyRing request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.kms.v1.IKeyRing, - protos.google.cloud.kms.v1.ICreateKeyRingRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.kms.v1.IKeyRing, + protos.google.cloud.kms.v1.ICreateKeyRingRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createKeyRing response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.createKeyRing(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.kms.v1.IKeyRing, - protos.google.cloud.kms.v1.ICreateKeyRingRequest|undefined, {}|undefined - ]) => { - this._log.info('createKeyRing response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createKeyRing(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.kms.v1.IKeyRing, + protos.google.cloud.kms.v1.ICreateKeyRingRequest | undefined, + {} | undefined, + ]) => { + this._log.info('createKeyRing response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Create a new {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKey} within a {@link protos.google.cloud.kms.v1.KeyRing|KeyRing}. - * - * {@link protos.google.cloud.kms.v1.CryptoKey.purpose|CryptoKey.purpose} and - * {@link protos.google.cloud.kms.v1.CryptoKeyVersionTemplate.algorithm|CryptoKey.version_template.algorithm} - * are required. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The {@link protos.google.cloud.kms.v1.KeyRing.name|name} of the KeyRing associated with the - * {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKeys}. - * @param {string} request.cryptoKeyId - * Required. It must be unique within a KeyRing and match the regular - * expression `[a-zA-Z0-9_-]{1,63}` - * @param {google.cloud.kms.v1.CryptoKey} request.cryptoKey - * A {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKey} with initial field values. - * @param {boolean} request.skipInitialVersionCreation - * If set to true, the request will create a {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKey} without any - * {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersions}. You must manually call - * {@link protos.google.cloud.kms.v1.KeyManagementService.CreateCryptoKeyVersion|CreateCryptoKeyVersion} or - * {@link protos.google.cloud.kms.v1.KeyManagementService.ImportCryptoKeyVersion|ImportCryptoKeyVersion} - * before you can use this {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKey}. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKey}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1/key_management_service.create_crypto_key.js - * region_tag:cloudkms_v1_generated_KeyManagementService_CreateCryptoKey_async - */ + /** + * Create a new {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKey} within a {@link protos.google.cloud.kms.v1.KeyRing|KeyRing}. + * + * {@link protos.google.cloud.kms.v1.CryptoKey.purpose|CryptoKey.purpose} and + * {@link protos.google.cloud.kms.v1.CryptoKeyVersionTemplate.algorithm|CryptoKey.version_template.algorithm} + * are required. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The {@link protos.google.cloud.kms.v1.KeyRing.name|name} of the KeyRing associated with the + * {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKeys}. + * @param {string} request.cryptoKeyId + * Required. It must be unique within a KeyRing and match the regular + * expression `[a-zA-Z0-9_-]{1,63}` + * @param {google.cloud.kms.v1.CryptoKey} request.cryptoKey + * A {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKey} with initial field values. + * @param {boolean} request.skipInitialVersionCreation + * If set to true, the request will create a {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKey} without any + * {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersions}. You must manually call + * {@link protos.google.cloud.kms.v1.KeyManagementService.CreateCryptoKeyVersion|CreateCryptoKeyVersion} or + * {@link protos.google.cloud.kms.v1.KeyManagementService.ImportCryptoKeyVersion|ImportCryptoKeyVersion} + * before you can use this {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKey}. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKey}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/key_management_service.create_crypto_key.js + * region_tag:cloudkms_v1_generated_KeyManagementService_CreateCryptoKey_async + */ createCryptoKey( - request?: protos.google.cloud.kms.v1.ICreateCryptoKeyRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.kms.v1.ICryptoKey, - protos.google.cloud.kms.v1.ICreateCryptoKeyRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.kms.v1.ICreateCryptoKeyRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.kms.v1.ICryptoKey, + protos.google.cloud.kms.v1.ICreateCryptoKeyRequest | undefined, + {} | undefined, + ] + >; createCryptoKey( - request: protos.google.cloud.kms.v1.ICreateCryptoKeyRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.kms.v1.ICryptoKey, - protos.google.cloud.kms.v1.ICreateCryptoKeyRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.kms.v1.ICreateCryptoKeyRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.kms.v1.ICryptoKey, + protos.google.cloud.kms.v1.ICreateCryptoKeyRequest | null | undefined, + {} | null | undefined + >, + ): void; createCryptoKey( - request: protos.google.cloud.kms.v1.ICreateCryptoKeyRequest, - callback: Callback< - protos.google.cloud.kms.v1.ICryptoKey, - protos.google.cloud.kms.v1.ICreateCryptoKeyRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.kms.v1.ICreateCryptoKeyRequest, + callback: Callback< + protos.google.cloud.kms.v1.ICryptoKey, + protos.google.cloud.kms.v1.ICreateCryptoKeyRequest | null | undefined, + {} | null | undefined + >, + ): void; createCryptoKey( - request?: protos.google.cloud.kms.v1.ICreateCryptoKeyRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.kms.v1.ICryptoKey, - protos.google.cloud.kms.v1.ICreateCryptoKeyRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.kms.v1.ICreateCryptoKeyRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.kms.v1.ICryptoKey, - protos.google.cloud.kms.v1.ICreateCryptoKeyRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.kms.v1.ICryptoKey, - protos.google.cloud.kms.v1.ICreateCryptoKeyRequest|undefined, {}|undefined - ]>|void { + protos.google.cloud.kms.v1.ICreateCryptoKeyRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.kms.v1.ICryptoKey, + protos.google.cloud.kms.v1.ICreateCryptoKeyRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.kms.v1.ICryptoKey, + protos.google.cloud.kms.v1.ICreateCryptoKeyRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('createCryptoKey request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.kms.v1.ICryptoKey, - protos.google.cloud.kms.v1.ICreateCryptoKeyRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.kms.v1.ICryptoKey, + protos.google.cloud.kms.v1.ICreateCryptoKeyRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createCryptoKey response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.createCryptoKey(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.kms.v1.ICryptoKey, - protos.google.cloud.kms.v1.ICreateCryptoKeyRequest|undefined, {}|undefined - ]) => { - this._log.info('createCryptoKey response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createCryptoKey(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.kms.v1.ICryptoKey, + protos.google.cloud.kms.v1.ICreateCryptoKeyRequest | undefined, + {} | undefined, + ]) => { + this._log.info('createCryptoKey response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Create a new {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersion} in a {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKey}. - * - * The server will assign the next sequential id. If unset, - * {@link protos.google.cloud.kms.v1.CryptoKeyVersion.state|state} will be set to - * {@link protos.google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED|ENABLED}. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The {@link protos.google.cloud.kms.v1.CryptoKey.name|name} of the {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKey} associated with - * the {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersions}. - * @param {google.cloud.kms.v1.CryptoKeyVersion} request.cryptoKeyVersion - * A {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersion} with initial field values. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersion}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1/key_management_service.create_crypto_key_version.js - * region_tag:cloudkms_v1_generated_KeyManagementService_CreateCryptoKeyVersion_async - */ + /** + * Create a new {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersion} in a {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKey}. + * + * The server will assign the next sequential id. If unset, + * {@link protos.google.cloud.kms.v1.CryptoKeyVersion.state|state} will be set to + * {@link protos.google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED|ENABLED}. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The {@link protos.google.cloud.kms.v1.CryptoKey.name|name} of the {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKey} associated with + * the {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersions}. + * @param {google.cloud.kms.v1.CryptoKeyVersion} request.cryptoKeyVersion + * A {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersion} with initial field values. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersion}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/key_management_service.create_crypto_key_version.js + * region_tag:cloudkms_v1_generated_KeyManagementService_CreateCryptoKeyVersion_async + */ createCryptoKeyVersion( - request?: protos.google.cloud.kms.v1.ICreateCryptoKeyVersionRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.kms.v1.ICryptoKeyVersion, - protos.google.cloud.kms.v1.ICreateCryptoKeyVersionRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.kms.v1.ICreateCryptoKeyVersionRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.kms.v1.ICryptoKeyVersion, + protos.google.cloud.kms.v1.ICreateCryptoKeyVersionRequest | undefined, + {} | undefined, + ] + >; createCryptoKeyVersion( - request: protos.google.cloud.kms.v1.ICreateCryptoKeyVersionRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.kms.v1.ICryptoKeyVersion, - protos.google.cloud.kms.v1.ICreateCryptoKeyVersionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.kms.v1.ICreateCryptoKeyVersionRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.kms.v1.ICryptoKeyVersion, + | protos.google.cloud.kms.v1.ICreateCryptoKeyVersionRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createCryptoKeyVersion( - request: protos.google.cloud.kms.v1.ICreateCryptoKeyVersionRequest, - callback: Callback< - protos.google.cloud.kms.v1.ICryptoKeyVersion, - protos.google.cloud.kms.v1.ICreateCryptoKeyVersionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.kms.v1.ICreateCryptoKeyVersionRequest, + callback: Callback< + protos.google.cloud.kms.v1.ICryptoKeyVersion, + | protos.google.cloud.kms.v1.ICreateCryptoKeyVersionRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createCryptoKeyVersion( - request?: protos.google.cloud.kms.v1.ICreateCryptoKeyVersionRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.kms.v1.ICryptoKeyVersion, - protos.google.cloud.kms.v1.ICreateCryptoKeyVersionRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.kms.v1.ICreateCryptoKeyVersionRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.kms.v1.ICryptoKeyVersion, - protos.google.cloud.kms.v1.ICreateCryptoKeyVersionRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.kms.v1.ICryptoKeyVersion, - protos.google.cloud.kms.v1.ICreateCryptoKeyVersionRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.kms.v1.ICreateCryptoKeyVersionRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.kms.v1.ICryptoKeyVersion, + | protos.google.cloud.kms.v1.ICreateCryptoKeyVersionRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.kms.v1.ICryptoKeyVersion, + protos.google.cloud.kms.v1.ICreateCryptoKeyVersionRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('createCryptoKeyVersion request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.kms.v1.ICryptoKeyVersion, - protos.google.cloud.kms.v1.ICreateCryptoKeyVersionRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.kms.v1.ICryptoKeyVersion, + | protos.google.cloud.kms.v1.ICreateCryptoKeyVersionRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createCryptoKeyVersion response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.createCryptoKeyVersion(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.kms.v1.ICryptoKeyVersion, - protos.google.cloud.kms.v1.ICreateCryptoKeyVersionRequest|undefined, {}|undefined - ]) => { - this._log.info('createCryptoKeyVersion response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createCryptoKeyVersion(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.kms.v1.ICryptoKeyVersion, + protos.google.cloud.kms.v1.ICreateCryptoKeyVersionRequest | undefined, + {} | undefined, + ]) => { + this._log.info('createCryptoKeyVersion response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Imports a new {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersion} into an existing {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKey} using the - * wrapped key material provided in the request. - * - * The version ID will be assigned the next sequential id within the - * {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKey}. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The {@link protos.google.cloud.kms.v1.CryptoKey.name|name} of the {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKey} to - * be imported into. - * @param {google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionAlgorithm} request.algorithm - * Required. The {@link protos.google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionAlgorithm|algorithm} of - * the key being imported. This does not need to match the - * {@link protos.google.cloud.kms.v1.CryptoKey.version_template|version_template} of the {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKey} this - * version imports into. - * @param {string} request.importJob - * Required. The {@link protos.google.cloud.kms.v1.ImportJob.name|name} of the {@link protos.google.cloud.kms.v1.ImportJob|ImportJob} that was used to - * wrap this key material. - * @param {Buffer} request.rsaAesWrappedKey - * Wrapped key material produced with - * {@link protos.google.cloud.kms.v1.ImportJob.ImportMethod.RSA_OAEP_3072_SHA1_AES_256|RSA_OAEP_3072_SHA1_AES_256} - * or - * {@link protos.google.cloud.kms.v1.ImportJob.ImportMethod.RSA_OAEP_4096_SHA1_AES_256|RSA_OAEP_4096_SHA1_AES_256}. - * - * This field contains the concatenation of two wrapped keys: - *
    - *
  1. An ephemeral AES-256 wrapping key wrapped with the - * {@link protos.google.cloud.kms.v1.ImportJob.public_key|public_key} using RSAES-OAEP with SHA-1, - * MGF1 with SHA-1, and an empty label. - *
  2. - *
  3. The key to be imported, wrapped with the ephemeral AES-256 key - * using AES-KWP (RFC 5649). - *
  4. - *
- * - * This format is the same as the format produced by PKCS#11 mechanism - * CKM_RSA_AES_KEY_WRAP. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersion}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1/key_management_service.import_crypto_key_version.js - * region_tag:cloudkms_v1_generated_KeyManagementService_ImportCryptoKeyVersion_async - */ + /** + * Imports a new {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersion} into an existing {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKey} using the + * wrapped key material provided in the request. + * + * The version ID will be assigned the next sequential id within the + * {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKey}. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The {@link protos.google.cloud.kms.v1.CryptoKey.name|name} of the {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKey} to + * be imported into. + * @param {google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionAlgorithm} request.algorithm + * Required. The {@link protos.google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionAlgorithm|algorithm} of + * the key being imported. This does not need to match the + * {@link protos.google.cloud.kms.v1.CryptoKey.version_template|version_template} of the {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKey} this + * version imports into. + * @param {string} request.importJob + * Required. The {@link protos.google.cloud.kms.v1.ImportJob.name|name} of the {@link protos.google.cloud.kms.v1.ImportJob|ImportJob} that was used to + * wrap this key material. + * @param {Buffer} request.rsaAesWrappedKey + * Wrapped key material produced with + * {@link protos.google.cloud.kms.v1.ImportJob.ImportMethod.RSA_OAEP_3072_SHA1_AES_256|RSA_OAEP_3072_SHA1_AES_256} + * or + * {@link protos.google.cloud.kms.v1.ImportJob.ImportMethod.RSA_OAEP_4096_SHA1_AES_256|RSA_OAEP_4096_SHA1_AES_256}. + * + * This field contains the concatenation of two wrapped keys: + *
    + *
  1. An ephemeral AES-256 wrapping key wrapped with the + * {@link protos.google.cloud.kms.v1.ImportJob.public_key|public_key} using RSAES-OAEP with SHA-1, + * MGF1 with SHA-1, and an empty label. + *
  2. + *
  3. The key to be imported, wrapped with the ephemeral AES-256 key + * using AES-KWP (RFC 5649). + *
  4. + *
+ * + * This format is the same as the format produced by PKCS#11 mechanism + * CKM_RSA_AES_KEY_WRAP. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersion}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/key_management_service.import_crypto_key_version.js + * region_tag:cloudkms_v1_generated_KeyManagementService_ImportCryptoKeyVersion_async + */ importCryptoKeyVersion( - request?: protos.google.cloud.kms.v1.IImportCryptoKeyVersionRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.kms.v1.ICryptoKeyVersion, - protos.google.cloud.kms.v1.IImportCryptoKeyVersionRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.kms.v1.IImportCryptoKeyVersionRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.kms.v1.ICryptoKeyVersion, + protos.google.cloud.kms.v1.IImportCryptoKeyVersionRequest | undefined, + {} | undefined, + ] + >; importCryptoKeyVersion( - request: protos.google.cloud.kms.v1.IImportCryptoKeyVersionRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.kms.v1.ICryptoKeyVersion, - protos.google.cloud.kms.v1.IImportCryptoKeyVersionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.kms.v1.IImportCryptoKeyVersionRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.kms.v1.ICryptoKeyVersion, + | protos.google.cloud.kms.v1.IImportCryptoKeyVersionRequest + | null + | undefined, + {} | null | undefined + >, + ): void; importCryptoKeyVersion( - request: protos.google.cloud.kms.v1.IImportCryptoKeyVersionRequest, - callback: Callback< - protos.google.cloud.kms.v1.ICryptoKeyVersion, - protos.google.cloud.kms.v1.IImportCryptoKeyVersionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.kms.v1.IImportCryptoKeyVersionRequest, + callback: Callback< + protos.google.cloud.kms.v1.ICryptoKeyVersion, + | protos.google.cloud.kms.v1.IImportCryptoKeyVersionRequest + | null + | undefined, + {} | null | undefined + >, + ): void; importCryptoKeyVersion( - request?: protos.google.cloud.kms.v1.IImportCryptoKeyVersionRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.kms.v1.ICryptoKeyVersion, - protos.google.cloud.kms.v1.IImportCryptoKeyVersionRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.kms.v1.IImportCryptoKeyVersionRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.kms.v1.ICryptoKeyVersion, - protos.google.cloud.kms.v1.IImportCryptoKeyVersionRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.kms.v1.ICryptoKeyVersion, - protos.google.cloud.kms.v1.IImportCryptoKeyVersionRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.kms.v1.IImportCryptoKeyVersionRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.kms.v1.ICryptoKeyVersion, + | protos.google.cloud.kms.v1.IImportCryptoKeyVersionRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.kms.v1.ICryptoKeyVersion, + protos.google.cloud.kms.v1.IImportCryptoKeyVersionRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('importCryptoKeyVersion request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.kms.v1.ICryptoKeyVersion, - protos.google.cloud.kms.v1.IImportCryptoKeyVersionRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.kms.v1.ICryptoKeyVersion, + | protos.google.cloud.kms.v1.IImportCryptoKeyVersionRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('importCryptoKeyVersion response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.importCryptoKeyVersion(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.kms.v1.ICryptoKeyVersion, - protos.google.cloud.kms.v1.IImportCryptoKeyVersionRequest|undefined, {}|undefined - ]) => { - this._log.info('importCryptoKeyVersion response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .importCryptoKeyVersion(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.kms.v1.ICryptoKeyVersion, + protos.google.cloud.kms.v1.IImportCryptoKeyVersionRequest | undefined, + {} | undefined, + ]) => { + this._log.info('importCryptoKeyVersion response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Create a new {@link protos.google.cloud.kms.v1.ImportJob|ImportJob} within a {@link protos.google.cloud.kms.v1.KeyRing|KeyRing}. - * - * {@link protos.google.cloud.kms.v1.ImportJob.import_method|ImportJob.import_method} is required. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The {@link protos.google.cloud.kms.v1.KeyRing.name|name} of the {@link protos.google.cloud.kms.v1.KeyRing|KeyRing} associated with the - * {@link protos.google.cloud.kms.v1.ImportJob|ImportJobs}. - * @param {string} request.importJobId - * Required. It must be unique within a KeyRing and match the regular - * expression `[a-zA-Z0-9_-]{1,63}` - * @param {google.cloud.kms.v1.ImportJob} request.importJob - * Required. An {@link protos.google.cloud.kms.v1.ImportJob|ImportJob} with initial field values. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.kms.v1.ImportJob|ImportJob}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1/key_management_service.create_import_job.js - * region_tag:cloudkms_v1_generated_KeyManagementService_CreateImportJob_async - */ + /** + * Create a new {@link protos.google.cloud.kms.v1.ImportJob|ImportJob} within a {@link protos.google.cloud.kms.v1.KeyRing|KeyRing}. + * + * {@link protos.google.cloud.kms.v1.ImportJob.import_method|ImportJob.import_method} is required. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The {@link protos.google.cloud.kms.v1.KeyRing.name|name} of the {@link protos.google.cloud.kms.v1.KeyRing|KeyRing} associated with the + * {@link protos.google.cloud.kms.v1.ImportJob|ImportJobs}. + * @param {string} request.importJobId + * Required. It must be unique within a KeyRing and match the regular + * expression `[a-zA-Z0-9_-]{1,63}` + * @param {google.cloud.kms.v1.ImportJob} request.importJob + * Required. An {@link protos.google.cloud.kms.v1.ImportJob|ImportJob} with initial field values. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.kms.v1.ImportJob|ImportJob}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/key_management_service.create_import_job.js + * region_tag:cloudkms_v1_generated_KeyManagementService_CreateImportJob_async + */ createImportJob( - request?: protos.google.cloud.kms.v1.ICreateImportJobRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.kms.v1.IImportJob, - protos.google.cloud.kms.v1.ICreateImportJobRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.kms.v1.ICreateImportJobRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.kms.v1.IImportJob, + protos.google.cloud.kms.v1.ICreateImportJobRequest | undefined, + {} | undefined, + ] + >; createImportJob( - request: protos.google.cloud.kms.v1.ICreateImportJobRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.kms.v1.IImportJob, - protos.google.cloud.kms.v1.ICreateImportJobRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.kms.v1.ICreateImportJobRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.kms.v1.IImportJob, + protos.google.cloud.kms.v1.ICreateImportJobRequest | null | undefined, + {} | null | undefined + >, + ): void; createImportJob( - request: protos.google.cloud.kms.v1.ICreateImportJobRequest, - callback: Callback< - protos.google.cloud.kms.v1.IImportJob, - protos.google.cloud.kms.v1.ICreateImportJobRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.kms.v1.ICreateImportJobRequest, + callback: Callback< + protos.google.cloud.kms.v1.IImportJob, + protos.google.cloud.kms.v1.ICreateImportJobRequest | null | undefined, + {} | null | undefined + >, + ): void; createImportJob( - request?: protos.google.cloud.kms.v1.ICreateImportJobRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.kms.v1.IImportJob, - protos.google.cloud.kms.v1.ICreateImportJobRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.kms.v1.ICreateImportJobRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.kms.v1.IImportJob, - protos.google.cloud.kms.v1.ICreateImportJobRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.kms.v1.IImportJob, - protos.google.cloud.kms.v1.ICreateImportJobRequest|undefined, {}|undefined - ]>|void { + protos.google.cloud.kms.v1.ICreateImportJobRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.kms.v1.IImportJob, + protos.google.cloud.kms.v1.ICreateImportJobRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.kms.v1.IImportJob, + protos.google.cloud.kms.v1.ICreateImportJobRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('createImportJob request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.kms.v1.IImportJob, - protos.google.cloud.kms.v1.ICreateImportJobRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.kms.v1.IImportJob, + protos.google.cloud.kms.v1.ICreateImportJobRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createImportJob response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.createImportJob(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.kms.v1.IImportJob, - protos.google.cloud.kms.v1.ICreateImportJobRequest|undefined, {}|undefined - ]) => { - this._log.info('createImportJob response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createImportJob(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.kms.v1.IImportJob, + protos.google.cloud.kms.v1.ICreateImportJobRequest | undefined, + {} | undefined, + ]) => { + this._log.info('createImportJob response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Update a {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKey}. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.cloud.kms.v1.CryptoKey} request.cryptoKey - * {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKey} with updated values. - * @param {google.protobuf.FieldMask} request.updateMask - * Required list of fields to be updated in this request. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKey}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1/key_management_service.update_crypto_key.js - * region_tag:cloudkms_v1_generated_KeyManagementService_UpdateCryptoKey_async - */ + /** + * Update a {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKey}. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.cloud.kms.v1.CryptoKey} request.cryptoKey + * {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKey} with updated values. + * @param {google.protobuf.FieldMask} request.updateMask + * Required list of fields to be updated in this request. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKey}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/key_management_service.update_crypto_key.js + * region_tag:cloudkms_v1_generated_KeyManagementService_UpdateCryptoKey_async + */ updateCryptoKey( - request?: protos.google.cloud.kms.v1.IUpdateCryptoKeyRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.kms.v1.ICryptoKey, - protos.google.cloud.kms.v1.IUpdateCryptoKeyRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.kms.v1.IUpdateCryptoKeyRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.kms.v1.ICryptoKey, + protos.google.cloud.kms.v1.IUpdateCryptoKeyRequest | undefined, + {} | undefined, + ] + >; updateCryptoKey( - request: protos.google.cloud.kms.v1.IUpdateCryptoKeyRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.kms.v1.ICryptoKey, - protos.google.cloud.kms.v1.IUpdateCryptoKeyRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.kms.v1.IUpdateCryptoKeyRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.kms.v1.ICryptoKey, + protos.google.cloud.kms.v1.IUpdateCryptoKeyRequest | null | undefined, + {} | null | undefined + >, + ): void; updateCryptoKey( - request: protos.google.cloud.kms.v1.IUpdateCryptoKeyRequest, - callback: Callback< - protos.google.cloud.kms.v1.ICryptoKey, - protos.google.cloud.kms.v1.IUpdateCryptoKeyRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.kms.v1.IUpdateCryptoKeyRequest, + callback: Callback< + protos.google.cloud.kms.v1.ICryptoKey, + protos.google.cloud.kms.v1.IUpdateCryptoKeyRequest | null | undefined, + {} | null | undefined + >, + ): void; updateCryptoKey( - request?: protos.google.cloud.kms.v1.IUpdateCryptoKeyRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.kms.v1.ICryptoKey, - protos.google.cloud.kms.v1.IUpdateCryptoKeyRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.kms.v1.IUpdateCryptoKeyRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.kms.v1.ICryptoKey, - protos.google.cloud.kms.v1.IUpdateCryptoKeyRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.kms.v1.ICryptoKey, - protos.google.cloud.kms.v1.IUpdateCryptoKeyRequest|undefined, {}|undefined - ]>|void { + protos.google.cloud.kms.v1.IUpdateCryptoKeyRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.kms.v1.ICryptoKey, + protos.google.cloud.kms.v1.IUpdateCryptoKeyRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.kms.v1.ICryptoKey, + protos.google.cloud.kms.v1.IUpdateCryptoKeyRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'crypto_key.name': request.cryptoKey!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'crypto_key.name': request.cryptoKey!.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateCryptoKey request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.kms.v1.ICryptoKey, - protos.google.cloud.kms.v1.IUpdateCryptoKeyRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.kms.v1.ICryptoKey, + protos.google.cloud.kms.v1.IUpdateCryptoKeyRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateCryptoKey response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.updateCryptoKey(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.kms.v1.ICryptoKey, - protos.google.cloud.kms.v1.IUpdateCryptoKeyRequest|undefined, {}|undefined - ]) => { - this._log.info('updateCryptoKey response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateCryptoKey(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.kms.v1.ICryptoKey, + protos.google.cloud.kms.v1.IUpdateCryptoKeyRequest | undefined, + {} | undefined, + ]) => { + this._log.info('updateCryptoKey response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Update a {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersion}'s metadata. - * - * {@link protos.google.cloud.kms.v1.CryptoKeyVersion.state|state} may be changed between - * {@link protos.google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED|ENABLED} and - * {@link protos.google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DISABLED|DISABLED} using this - * method. See {@link protos.google.cloud.kms.v1.KeyManagementService.DestroyCryptoKeyVersion|DestroyCryptoKeyVersion} and {@link protos.google.cloud.kms.v1.KeyManagementService.RestoreCryptoKeyVersion|RestoreCryptoKeyVersion} to - * move between other states. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.cloud.kms.v1.CryptoKeyVersion} request.cryptoKeyVersion - * {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersion} with updated values. - * @param {google.protobuf.FieldMask} request.updateMask - * Required list of fields to be updated in this request. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersion}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1/key_management_service.update_crypto_key_version.js - * region_tag:cloudkms_v1_generated_KeyManagementService_UpdateCryptoKeyVersion_async - */ + /** + * Update a {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersion}'s metadata. + * + * {@link protos.google.cloud.kms.v1.CryptoKeyVersion.state|state} may be changed between + * {@link protos.google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED|ENABLED} and + * {@link protos.google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DISABLED|DISABLED} using this + * method. See {@link protos.google.cloud.kms.v1.KeyManagementService.DestroyCryptoKeyVersion|DestroyCryptoKeyVersion} and {@link protos.google.cloud.kms.v1.KeyManagementService.RestoreCryptoKeyVersion|RestoreCryptoKeyVersion} to + * move between other states. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.cloud.kms.v1.CryptoKeyVersion} request.cryptoKeyVersion + * {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersion} with updated values. + * @param {google.protobuf.FieldMask} request.updateMask + * Required list of fields to be updated in this request. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersion}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/key_management_service.update_crypto_key_version.js + * region_tag:cloudkms_v1_generated_KeyManagementService_UpdateCryptoKeyVersion_async + */ updateCryptoKeyVersion( - request?: protos.google.cloud.kms.v1.IUpdateCryptoKeyVersionRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.kms.v1.ICryptoKeyVersion, - protos.google.cloud.kms.v1.IUpdateCryptoKeyVersionRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.kms.v1.IUpdateCryptoKeyVersionRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.kms.v1.ICryptoKeyVersion, + protos.google.cloud.kms.v1.IUpdateCryptoKeyVersionRequest | undefined, + {} | undefined, + ] + >; updateCryptoKeyVersion( - request: protos.google.cloud.kms.v1.IUpdateCryptoKeyVersionRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.kms.v1.ICryptoKeyVersion, - protos.google.cloud.kms.v1.IUpdateCryptoKeyVersionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.kms.v1.IUpdateCryptoKeyVersionRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.kms.v1.ICryptoKeyVersion, + | protos.google.cloud.kms.v1.IUpdateCryptoKeyVersionRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateCryptoKeyVersion( - request: protos.google.cloud.kms.v1.IUpdateCryptoKeyVersionRequest, - callback: Callback< - protos.google.cloud.kms.v1.ICryptoKeyVersion, - protos.google.cloud.kms.v1.IUpdateCryptoKeyVersionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.kms.v1.IUpdateCryptoKeyVersionRequest, + callback: Callback< + protos.google.cloud.kms.v1.ICryptoKeyVersion, + | protos.google.cloud.kms.v1.IUpdateCryptoKeyVersionRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateCryptoKeyVersion( - request?: protos.google.cloud.kms.v1.IUpdateCryptoKeyVersionRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.kms.v1.ICryptoKeyVersion, - protos.google.cloud.kms.v1.IUpdateCryptoKeyVersionRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.kms.v1.IUpdateCryptoKeyVersionRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.kms.v1.ICryptoKeyVersion, - protos.google.cloud.kms.v1.IUpdateCryptoKeyVersionRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.kms.v1.ICryptoKeyVersion, - protos.google.cloud.kms.v1.IUpdateCryptoKeyVersionRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.kms.v1.IUpdateCryptoKeyVersionRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.kms.v1.ICryptoKeyVersion, + | protos.google.cloud.kms.v1.IUpdateCryptoKeyVersionRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.kms.v1.ICryptoKeyVersion, + protos.google.cloud.kms.v1.IUpdateCryptoKeyVersionRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'crypto_key_version.name': request.cryptoKeyVersion!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'crypto_key_version.name': request.cryptoKeyVersion!.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateCryptoKeyVersion request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.kms.v1.ICryptoKeyVersion, - protos.google.cloud.kms.v1.IUpdateCryptoKeyVersionRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.kms.v1.ICryptoKeyVersion, + | protos.google.cloud.kms.v1.IUpdateCryptoKeyVersionRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateCryptoKeyVersion response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.updateCryptoKeyVersion(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.kms.v1.ICryptoKeyVersion, - protos.google.cloud.kms.v1.IUpdateCryptoKeyVersionRequest|undefined, {}|undefined - ]) => { - this._log.info('updateCryptoKeyVersion response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateCryptoKeyVersion(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.kms.v1.ICryptoKeyVersion, + protos.google.cloud.kms.v1.IUpdateCryptoKeyVersionRequest | undefined, + {} | undefined, + ]) => { + this._log.info('updateCryptoKeyVersion response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Encrypts data, so that it can only be recovered by a call to {@link protos.google.cloud.kms.v1.KeyManagementService.Decrypt|Decrypt}. - * The {@link protos.google.cloud.kms.v1.CryptoKey.purpose|CryptoKey.purpose} must be - * {@link protos.google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT|ENCRYPT_DECRYPT}. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The resource name of the {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKey} or {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersion} - * to use for encryption. - * - * If a {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKey} is specified, the server will use its - * {@link protos.google.cloud.kms.v1.CryptoKey.primary|primary version}. - * @param {Buffer} request.plaintext - * Required. The data to encrypt. Must be no larger than 64KiB. - * - * The maximum size depends on the key version's - * {@link protos.google.cloud.kms.v1.CryptoKeyVersionTemplate.protection_level|protection_level}. For - * {@link protos.google.cloud.kms.v1.ProtectionLevel.SOFTWARE|SOFTWARE} keys, the plaintext must be no larger - * than 64KiB. For {@link protos.google.cloud.kms.v1.ProtectionLevel.HSM|HSM} keys, the combined length of the - * plaintext and additional_authenticated_data fields must be no larger than - * 8KiB. - * @param {Buffer} request.additionalAuthenticatedData - * Optional data that, if specified, must also be provided during decryption - * through {@link protos.google.cloud.kms.v1.DecryptRequest.additional_authenticated_data|DecryptRequest.additional_authenticated_data}. - * - * The maximum size depends on the key version's - * {@link protos.google.cloud.kms.v1.CryptoKeyVersionTemplate.protection_level|protection_level}. For - * {@link protos.google.cloud.kms.v1.ProtectionLevel.SOFTWARE|SOFTWARE} keys, the AAD must be no larger than - * 64KiB. For {@link protos.google.cloud.kms.v1.ProtectionLevel.HSM|HSM} keys, the combined length of the - * plaintext and additional_authenticated_data fields must be no larger than - * 8KiB. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.kms.v1.EncryptResponse|EncryptResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1/key_management_service.encrypt.js - * region_tag:cloudkms_v1_generated_KeyManagementService_Encrypt_async - */ + /** + * Encrypts data, so that it can only be recovered by a call to {@link protos.google.cloud.kms.v1.KeyManagementService.Decrypt|Decrypt}. + * The {@link protos.google.cloud.kms.v1.CryptoKey.purpose|CryptoKey.purpose} must be + * {@link protos.google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT|ENCRYPT_DECRYPT}. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The resource name of the {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKey} or {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersion} + * to use for encryption. + * + * If a {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKey} is specified, the server will use its + * {@link protos.google.cloud.kms.v1.CryptoKey.primary|primary version}. + * @param {Buffer} request.plaintext + * Required. The data to encrypt. Must be no larger than 64KiB. + * + * The maximum size depends on the key version's + * {@link protos.google.cloud.kms.v1.CryptoKeyVersionTemplate.protection_level|protection_level}. For + * {@link protos.google.cloud.kms.v1.ProtectionLevel.SOFTWARE|SOFTWARE} keys, the plaintext must be no larger + * than 64KiB. For {@link protos.google.cloud.kms.v1.ProtectionLevel.HSM|HSM} keys, the combined length of the + * plaintext and additional_authenticated_data fields must be no larger than + * 8KiB. + * @param {Buffer} request.additionalAuthenticatedData + * Optional data that, if specified, must also be provided during decryption + * through {@link protos.google.cloud.kms.v1.DecryptRequest.additional_authenticated_data|DecryptRequest.additional_authenticated_data}. + * + * The maximum size depends on the key version's + * {@link protos.google.cloud.kms.v1.CryptoKeyVersionTemplate.protection_level|protection_level}. For + * {@link protos.google.cloud.kms.v1.ProtectionLevel.SOFTWARE|SOFTWARE} keys, the AAD must be no larger than + * 64KiB. For {@link protos.google.cloud.kms.v1.ProtectionLevel.HSM|HSM} keys, the combined length of the + * plaintext and additional_authenticated_data fields must be no larger than + * 8KiB. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.kms.v1.EncryptResponse|EncryptResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/key_management_service.encrypt.js + * region_tag:cloudkms_v1_generated_KeyManagementService_Encrypt_async + */ encrypt( - request?: protos.google.cloud.kms.v1.IEncryptRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.kms.v1.IEncryptResponse, - protos.google.cloud.kms.v1.IEncryptRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.kms.v1.IEncryptRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.kms.v1.IEncryptResponse, + protos.google.cloud.kms.v1.IEncryptRequest | undefined, + {} | undefined, + ] + >; encrypt( - request: protos.google.cloud.kms.v1.IEncryptRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.kms.v1.IEncryptResponse, - protos.google.cloud.kms.v1.IEncryptRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.kms.v1.IEncryptRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.kms.v1.IEncryptResponse, + protos.google.cloud.kms.v1.IEncryptRequest | null | undefined, + {} | null | undefined + >, + ): void; encrypt( - request: protos.google.cloud.kms.v1.IEncryptRequest, - callback: Callback< - protos.google.cloud.kms.v1.IEncryptResponse, - protos.google.cloud.kms.v1.IEncryptRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.kms.v1.IEncryptRequest, + callback: Callback< + protos.google.cloud.kms.v1.IEncryptResponse, + protos.google.cloud.kms.v1.IEncryptRequest | null | undefined, + {} | null | undefined + >, + ): void; encrypt( - request?: protos.google.cloud.kms.v1.IEncryptRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.kms.v1.IEncryptResponse, - protos.google.cloud.kms.v1.IEncryptRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.kms.v1.IEncryptRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.kms.v1.IEncryptResponse, - protos.google.cloud.kms.v1.IEncryptRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.kms.v1.IEncryptResponse, - protos.google.cloud.kms.v1.IEncryptRequest|undefined, {}|undefined - ]>|void { + protos.google.cloud.kms.v1.IEncryptRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.kms.v1.IEncryptResponse, + protos.google.cloud.kms.v1.IEncryptRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.kms.v1.IEncryptResponse, + protos.google.cloud.kms.v1.IEncryptRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('encrypt request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.kms.v1.IEncryptResponse, - protos.google.cloud.kms.v1.IEncryptRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.kms.v1.IEncryptResponse, + protos.google.cloud.kms.v1.IEncryptRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('encrypt response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.encrypt(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.kms.v1.IEncryptResponse, - protos.google.cloud.kms.v1.IEncryptRequest|undefined, {}|undefined - ]) => { - this._log.info('encrypt response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .encrypt(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.kms.v1.IEncryptResponse, + protos.google.cloud.kms.v1.IEncryptRequest | undefined, + {} | undefined, + ]) => { + this._log.info('encrypt response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Decrypts data that was protected by {@link protos.google.cloud.kms.v1.KeyManagementService.Encrypt|Encrypt}. The {@link protos.google.cloud.kms.v1.CryptoKey.purpose|CryptoKey.purpose} - * must be {@link protos.google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT|ENCRYPT_DECRYPT}. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The resource name of the {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKey} to use for decryption. - * The server will choose the appropriate version. - * @param {Buffer} request.ciphertext - * Required. The encrypted data originally returned in - * {@link protos.google.cloud.kms.v1.EncryptResponse.ciphertext|EncryptResponse.ciphertext}. - * @param {Buffer} request.additionalAuthenticatedData - * Optional data that must match the data originally supplied in - * {@link protos.google.cloud.kms.v1.EncryptRequest.additional_authenticated_data|EncryptRequest.additional_authenticated_data}. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.kms.v1.DecryptResponse|DecryptResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1/key_management_service.decrypt.js - * region_tag:cloudkms_v1_generated_KeyManagementService_Decrypt_async - */ + /** + * Decrypts data that was protected by {@link protos.google.cloud.kms.v1.KeyManagementService.Encrypt|Encrypt}. The {@link protos.google.cloud.kms.v1.CryptoKey.purpose|CryptoKey.purpose} + * must be {@link protos.google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT|ENCRYPT_DECRYPT}. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The resource name of the {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKey} to use for decryption. + * The server will choose the appropriate version. + * @param {Buffer} request.ciphertext + * Required. The encrypted data originally returned in + * {@link protos.google.cloud.kms.v1.EncryptResponse.ciphertext|EncryptResponse.ciphertext}. + * @param {Buffer} request.additionalAuthenticatedData + * Optional data that must match the data originally supplied in + * {@link protos.google.cloud.kms.v1.EncryptRequest.additional_authenticated_data|EncryptRequest.additional_authenticated_data}. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.kms.v1.DecryptResponse|DecryptResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/key_management_service.decrypt.js + * region_tag:cloudkms_v1_generated_KeyManagementService_Decrypt_async + */ decrypt( - request?: protos.google.cloud.kms.v1.IDecryptRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.kms.v1.IDecryptResponse, - protos.google.cloud.kms.v1.IDecryptRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.kms.v1.IDecryptRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.kms.v1.IDecryptResponse, + protos.google.cloud.kms.v1.IDecryptRequest | undefined, + {} | undefined, + ] + >; decrypt( - request: protos.google.cloud.kms.v1.IDecryptRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.kms.v1.IDecryptResponse, - protos.google.cloud.kms.v1.IDecryptRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.kms.v1.IDecryptRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.kms.v1.IDecryptResponse, + protos.google.cloud.kms.v1.IDecryptRequest | null | undefined, + {} | null | undefined + >, + ): void; decrypt( - request: protos.google.cloud.kms.v1.IDecryptRequest, - callback: Callback< - protos.google.cloud.kms.v1.IDecryptResponse, - protos.google.cloud.kms.v1.IDecryptRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.kms.v1.IDecryptRequest, + callback: Callback< + protos.google.cloud.kms.v1.IDecryptResponse, + protos.google.cloud.kms.v1.IDecryptRequest | null | undefined, + {} | null | undefined + >, + ): void; decrypt( - request?: protos.google.cloud.kms.v1.IDecryptRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.kms.v1.IDecryptResponse, - protos.google.cloud.kms.v1.IDecryptRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.kms.v1.IDecryptRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.kms.v1.IDecryptResponse, - protos.google.cloud.kms.v1.IDecryptRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.kms.v1.IDecryptResponse, - protos.google.cloud.kms.v1.IDecryptRequest|undefined, {}|undefined - ]>|void { + protos.google.cloud.kms.v1.IDecryptRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.kms.v1.IDecryptResponse, + protos.google.cloud.kms.v1.IDecryptRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.kms.v1.IDecryptResponse, + protos.google.cloud.kms.v1.IDecryptRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('decrypt request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.kms.v1.IDecryptResponse, - protos.google.cloud.kms.v1.IDecryptRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.kms.v1.IDecryptResponse, + protos.google.cloud.kms.v1.IDecryptRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('decrypt response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.decrypt(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.kms.v1.IDecryptResponse, - protos.google.cloud.kms.v1.IDecryptRequest|undefined, {}|undefined - ]) => { - this._log.info('decrypt response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .decrypt(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.kms.v1.IDecryptResponse, + protos.google.cloud.kms.v1.IDecryptRequest | undefined, + {} | undefined, + ]) => { + this._log.info('decrypt response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Signs data using a {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersion} with {@link protos.google.cloud.kms.v1.CryptoKey.purpose|CryptoKey.purpose} - * ASYMMETRIC_SIGN, producing a signature that can be verified with the public - * key retrieved from {@link protos.google.cloud.kms.v1.KeyManagementService.GetPublicKey|GetPublicKey}. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The resource name of the {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersion} to use for signing. - * @param {google.cloud.kms.v1.Digest} request.digest - * Required. The digest of the data to sign. The digest must be produced with - * the same digest algorithm as specified by the key version's - * {@link protos.google.cloud.kms.v1.CryptoKeyVersion.algorithm|algorithm}. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.kms.v1.AsymmetricSignResponse|AsymmetricSignResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1/key_management_service.asymmetric_sign.js - * region_tag:cloudkms_v1_generated_KeyManagementService_AsymmetricSign_async - */ + /** + * Signs data using a {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersion} with {@link protos.google.cloud.kms.v1.CryptoKey.purpose|CryptoKey.purpose} + * ASYMMETRIC_SIGN, producing a signature that can be verified with the public + * key retrieved from {@link protos.google.cloud.kms.v1.KeyManagementService.GetPublicKey|GetPublicKey}. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The resource name of the {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersion} to use for signing. + * @param {google.cloud.kms.v1.Digest} request.digest + * Required. The digest of the data to sign. The digest must be produced with + * the same digest algorithm as specified by the key version's + * {@link protos.google.cloud.kms.v1.CryptoKeyVersion.algorithm|algorithm}. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.kms.v1.AsymmetricSignResponse|AsymmetricSignResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/key_management_service.asymmetric_sign.js + * region_tag:cloudkms_v1_generated_KeyManagementService_AsymmetricSign_async + */ asymmetricSign( - request?: protos.google.cloud.kms.v1.IAsymmetricSignRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.kms.v1.IAsymmetricSignResponse, - protos.google.cloud.kms.v1.IAsymmetricSignRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.kms.v1.IAsymmetricSignRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.kms.v1.IAsymmetricSignResponse, + protos.google.cloud.kms.v1.IAsymmetricSignRequest | undefined, + {} | undefined, + ] + >; asymmetricSign( - request: protos.google.cloud.kms.v1.IAsymmetricSignRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.kms.v1.IAsymmetricSignResponse, - protos.google.cloud.kms.v1.IAsymmetricSignRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.kms.v1.IAsymmetricSignRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.kms.v1.IAsymmetricSignResponse, + protos.google.cloud.kms.v1.IAsymmetricSignRequest | null | undefined, + {} | null | undefined + >, + ): void; asymmetricSign( - request: protos.google.cloud.kms.v1.IAsymmetricSignRequest, - callback: Callback< - protos.google.cloud.kms.v1.IAsymmetricSignResponse, - protos.google.cloud.kms.v1.IAsymmetricSignRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.kms.v1.IAsymmetricSignRequest, + callback: Callback< + protos.google.cloud.kms.v1.IAsymmetricSignResponse, + protos.google.cloud.kms.v1.IAsymmetricSignRequest | null | undefined, + {} | null | undefined + >, + ): void; asymmetricSign( - request?: protos.google.cloud.kms.v1.IAsymmetricSignRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.kms.v1.IAsymmetricSignResponse, - protos.google.cloud.kms.v1.IAsymmetricSignRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.kms.v1.IAsymmetricSignRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.kms.v1.IAsymmetricSignResponse, - protos.google.cloud.kms.v1.IAsymmetricSignRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.kms.v1.IAsymmetricSignResponse, - protos.google.cloud.kms.v1.IAsymmetricSignRequest|undefined, {}|undefined - ]>|void { + protos.google.cloud.kms.v1.IAsymmetricSignRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.kms.v1.IAsymmetricSignResponse, + protos.google.cloud.kms.v1.IAsymmetricSignRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.kms.v1.IAsymmetricSignResponse, + protos.google.cloud.kms.v1.IAsymmetricSignRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('asymmetricSign request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.kms.v1.IAsymmetricSignResponse, - protos.google.cloud.kms.v1.IAsymmetricSignRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.kms.v1.IAsymmetricSignResponse, + protos.google.cloud.kms.v1.IAsymmetricSignRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('asymmetricSign response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.asymmetricSign(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.kms.v1.IAsymmetricSignResponse, - protos.google.cloud.kms.v1.IAsymmetricSignRequest|undefined, {}|undefined - ]) => { - this._log.info('asymmetricSign response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .asymmetricSign(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.kms.v1.IAsymmetricSignResponse, + protos.google.cloud.kms.v1.IAsymmetricSignRequest | undefined, + {} | undefined, + ]) => { + this._log.info('asymmetricSign response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Decrypts data that was encrypted with a public key retrieved from - * {@link protos.google.cloud.kms.v1.KeyManagementService.GetPublicKey|GetPublicKey} corresponding to a {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersion} with - * {@link protos.google.cloud.kms.v1.CryptoKey.purpose|CryptoKey.purpose} ASYMMETRIC_DECRYPT. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The resource name of the {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersion} to use for - * decryption. - * @param {Buffer} request.ciphertext - * Required. The data encrypted with the named {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersion}'s public - * key using OAEP. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.kms.v1.AsymmetricDecryptResponse|AsymmetricDecryptResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1/key_management_service.asymmetric_decrypt.js - * region_tag:cloudkms_v1_generated_KeyManagementService_AsymmetricDecrypt_async - */ + /** + * Decrypts data that was encrypted with a public key retrieved from + * {@link protos.google.cloud.kms.v1.KeyManagementService.GetPublicKey|GetPublicKey} corresponding to a {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersion} with + * {@link protos.google.cloud.kms.v1.CryptoKey.purpose|CryptoKey.purpose} ASYMMETRIC_DECRYPT. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The resource name of the {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersion} to use for + * decryption. + * @param {Buffer} request.ciphertext + * Required. The data encrypted with the named {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersion}'s public + * key using OAEP. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.kms.v1.AsymmetricDecryptResponse|AsymmetricDecryptResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/key_management_service.asymmetric_decrypt.js + * region_tag:cloudkms_v1_generated_KeyManagementService_AsymmetricDecrypt_async + */ asymmetricDecrypt( - request?: protos.google.cloud.kms.v1.IAsymmetricDecryptRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.kms.v1.IAsymmetricDecryptResponse, - protos.google.cloud.kms.v1.IAsymmetricDecryptRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.kms.v1.IAsymmetricDecryptRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.kms.v1.IAsymmetricDecryptResponse, + protos.google.cloud.kms.v1.IAsymmetricDecryptRequest | undefined, + {} | undefined, + ] + >; asymmetricDecrypt( - request: protos.google.cloud.kms.v1.IAsymmetricDecryptRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.kms.v1.IAsymmetricDecryptResponse, - protos.google.cloud.kms.v1.IAsymmetricDecryptRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.kms.v1.IAsymmetricDecryptRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.kms.v1.IAsymmetricDecryptResponse, + protos.google.cloud.kms.v1.IAsymmetricDecryptRequest | null | undefined, + {} | null | undefined + >, + ): void; asymmetricDecrypt( - request: protos.google.cloud.kms.v1.IAsymmetricDecryptRequest, - callback: Callback< - protos.google.cloud.kms.v1.IAsymmetricDecryptResponse, - protos.google.cloud.kms.v1.IAsymmetricDecryptRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.kms.v1.IAsymmetricDecryptRequest, + callback: Callback< + protos.google.cloud.kms.v1.IAsymmetricDecryptResponse, + protos.google.cloud.kms.v1.IAsymmetricDecryptRequest | null | undefined, + {} | null | undefined + >, + ): void; asymmetricDecrypt( - request?: protos.google.cloud.kms.v1.IAsymmetricDecryptRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.kms.v1.IAsymmetricDecryptResponse, - protos.google.cloud.kms.v1.IAsymmetricDecryptRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.kms.v1.IAsymmetricDecryptRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.kms.v1.IAsymmetricDecryptResponse, - protos.google.cloud.kms.v1.IAsymmetricDecryptRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.kms.v1.IAsymmetricDecryptResponse, - protos.google.cloud.kms.v1.IAsymmetricDecryptRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.kms.v1.IAsymmetricDecryptRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.kms.v1.IAsymmetricDecryptResponse, + protos.google.cloud.kms.v1.IAsymmetricDecryptRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.kms.v1.IAsymmetricDecryptResponse, + protos.google.cloud.kms.v1.IAsymmetricDecryptRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('asymmetricDecrypt request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.kms.v1.IAsymmetricDecryptResponse, - protos.google.cloud.kms.v1.IAsymmetricDecryptRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.kms.v1.IAsymmetricDecryptResponse, + | protos.google.cloud.kms.v1.IAsymmetricDecryptRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('asymmetricDecrypt response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.asymmetricDecrypt(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.kms.v1.IAsymmetricDecryptResponse, - protos.google.cloud.kms.v1.IAsymmetricDecryptRequest|undefined, {}|undefined - ]) => { - this._log.info('asymmetricDecrypt response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .asymmetricDecrypt(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.kms.v1.IAsymmetricDecryptResponse, + protos.google.cloud.kms.v1.IAsymmetricDecryptRequest | undefined, + {} | undefined, + ]) => { + this._log.info('asymmetricDecrypt response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Update the version of a {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKey} that will be used in {@link protos.google.cloud.kms.v1.KeyManagementService.Encrypt|Encrypt}. - * - * Returns an error if called on an asymmetric key. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * The resource name of the {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKey} to update. - * @param {string} request.cryptoKeyVersionId - * The id of the child {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersion} to use as primary. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKey}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1/key_management_service.update_crypto_key_primary_version.js - * region_tag:cloudkms_v1_generated_KeyManagementService_UpdateCryptoKeyPrimaryVersion_async - */ + /** + * Update the version of a {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKey} that will be used in {@link protos.google.cloud.kms.v1.KeyManagementService.Encrypt|Encrypt}. + * + * Returns an error if called on an asymmetric key. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * The resource name of the {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKey} to update. + * @param {string} request.cryptoKeyVersionId + * The id of the child {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersion} to use as primary. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKey}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/key_management_service.update_crypto_key_primary_version.js + * region_tag:cloudkms_v1_generated_KeyManagementService_UpdateCryptoKeyPrimaryVersion_async + */ updateCryptoKeyPrimaryVersion( - request?: protos.google.cloud.kms.v1.IUpdateCryptoKeyPrimaryVersionRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.kms.v1.ICryptoKey, - protos.google.cloud.kms.v1.IUpdateCryptoKeyPrimaryVersionRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.kms.v1.IUpdateCryptoKeyPrimaryVersionRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.kms.v1.ICryptoKey, + ( + | protos.google.cloud.kms.v1.IUpdateCryptoKeyPrimaryVersionRequest + | undefined + ), + {} | undefined, + ] + >; updateCryptoKeyPrimaryVersion( - request: protos.google.cloud.kms.v1.IUpdateCryptoKeyPrimaryVersionRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.kms.v1.ICryptoKey, - protos.google.cloud.kms.v1.IUpdateCryptoKeyPrimaryVersionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.kms.v1.IUpdateCryptoKeyPrimaryVersionRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.kms.v1.ICryptoKey, + | protos.google.cloud.kms.v1.IUpdateCryptoKeyPrimaryVersionRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateCryptoKeyPrimaryVersion( - request: protos.google.cloud.kms.v1.IUpdateCryptoKeyPrimaryVersionRequest, - callback: Callback< - protos.google.cloud.kms.v1.ICryptoKey, - protos.google.cloud.kms.v1.IUpdateCryptoKeyPrimaryVersionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.kms.v1.IUpdateCryptoKeyPrimaryVersionRequest, + callback: Callback< + protos.google.cloud.kms.v1.ICryptoKey, + | protos.google.cloud.kms.v1.IUpdateCryptoKeyPrimaryVersionRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateCryptoKeyPrimaryVersion( - request?: protos.google.cloud.kms.v1.IUpdateCryptoKeyPrimaryVersionRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.kms.v1.ICryptoKey, - protos.google.cloud.kms.v1.IUpdateCryptoKeyPrimaryVersionRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.kms.v1.IUpdateCryptoKeyPrimaryVersionRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.kms.v1.ICryptoKey, - protos.google.cloud.kms.v1.IUpdateCryptoKeyPrimaryVersionRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.kms.v1.ICryptoKey, - protos.google.cloud.kms.v1.IUpdateCryptoKeyPrimaryVersionRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.kms.v1.IUpdateCryptoKeyPrimaryVersionRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.kms.v1.ICryptoKey, + | protos.google.cloud.kms.v1.IUpdateCryptoKeyPrimaryVersionRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.kms.v1.ICryptoKey, + ( + | protos.google.cloud.kms.v1.IUpdateCryptoKeyPrimaryVersionRequest + | undefined + ), + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateCryptoKeyPrimaryVersion request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.kms.v1.ICryptoKey, - protos.google.cloud.kms.v1.IUpdateCryptoKeyPrimaryVersionRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.kms.v1.ICryptoKey, + | protos.google.cloud.kms.v1.IUpdateCryptoKeyPrimaryVersionRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateCryptoKeyPrimaryVersion response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.updateCryptoKeyPrimaryVersion(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.kms.v1.ICryptoKey, - protos.google.cloud.kms.v1.IUpdateCryptoKeyPrimaryVersionRequest|undefined, {}|undefined - ]) => { - this._log.info('updateCryptoKeyPrimaryVersion response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateCryptoKeyPrimaryVersion(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.kms.v1.ICryptoKey, + ( + | protos.google.cloud.kms.v1.IUpdateCryptoKeyPrimaryVersionRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('updateCryptoKeyPrimaryVersion response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Schedule a {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersion} for destruction. - * - * Upon calling this method, {@link protos.google.cloud.kms.v1.CryptoKeyVersion.state|CryptoKeyVersion.state} will be set to - * {@link protos.google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DESTROY_SCHEDULED|DESTROY_SCHEDULED} - * and {@link protos.google.cloud.kms.v1.CryptoKeyVersion.destroy_time|destroy_time} will be set to a time 24 - * hours in the future, at which point the {@link protos.google.cloud.kms.v1.CryptoKeyVersion.state|state} - * will be changed to - * {@link protos.google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DESTROYED|DESTROYED}, and the key - * material will be irrevocably destroyed. - * - * Before the {@link protos.google.cloud.kms.v1.CryptoKeyVersion.destroy_time|destroy_time} is reached, - * {@link protos.google.cloud.kms.v1.KeyManagementService.RestoreCryptoKeyVersion|RestoreCryptoKeyVersion} may be called to reverse the process. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * The resource name of the {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersion} to destroy. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersion}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1/key_management_service.destroy_crypto_key_version.js - * region_tag:cloudkms_v1_generated_KeyManagementService_DestroyCryptoKeyVersion_async - */ + /** + * Schedule a {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersion} for destruction. + * + * Upon calling this method, {@link protos.google.cloud.kms.v1.CryptoKeyVersion.state|CryptoKeyVersion.state} will be set to + * {@link protos.google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DESTROY_SCHEDULED|DESTROY_SCHEDULED} + * and {@link protos.google.cloud.kms.v1.CryptoKeyVersion.destroy_time|destroy_time} will be set to a time 24 + * hours in the future, at which point the {@link protos.google.cloud.kms.v1.CryptoKeyVersion.state|state} + * will be changed to + * {@link protos.google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DESTROYED|DESTROYED}, and the key + * material will be irrevocably destroyed. + * + * Before the {@link protos.google.cloud.kms.v1.CryptoKeyVersion.destroy_time|destroy_time} is reached, + * {@link protos.google.cloud.kms.v1.KeyManagementService.RestoreCryptoKeyVersion|RestoreCryptoKeyVersion} may be called to reverse the process. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * The resource name of the {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersion} to destroy. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersion}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/key_management_service.destroy_crypto_key_version.js + * region_tag:cloudkms_v1_generated_KeyManagementService_DestroyCryptoKeyVersion_async + */ destroyCryptoKeyVersion( - request?: protos.google.cloud.kms.v1.IDestroyCryptoKeyVersionRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.kms.v1.ICryptoKeyVersion, - protos.google.cloud.kms.v1.IDestroyCryptoKeyVersionRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.kms.v1.IDestroyCryptoKeyVersionRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.kms.v1.ICryptoKeyVersion, + protos.google.cloud.kms.v1.IDestroyCryptoKeyVersionRequest | undefined, + {} | undefined, + ] + >; destroyCryptoKeyVersion( - request: protos.google.cloud.kms.v1.IDestroyCryptoKeyVersionRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.kms.v1.ICryptoKeyVersion, - protos.google.cloud.kms.v1.IDestroyCryptoKeyVersionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.kms.v1.IDestroyCryptoKeyVersionRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.kms.v1.ICryptoKeyVersion, + | protos.google.cloud.kms.v1.IDestroyCryptoKeyVersionRequest + | null + | undefined, + {} | null | undefined + >, + ): void; destroyCryptoKeyVersion( - request: protos.google.cloud.kms.v1.IDestroyCryptoKeyVersionRequest, - callback: Callback< - protos.google.cloud.kms.v1.ICryptoKeyVersion, - protos.google.cloud.kms.v1.IDestroyCryptoKeyVersionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.kms.v1.IDestroyCryptoKeyVersionRequest, + callback: Callback< + protos.google.cloud.kms.v1.ICryptoKeyVersion, + | protos.google.cloud.kms.v1.IDestroyCryptoKeyVersionRequest + | null + | undefined, + {} | null | undefined + >, + ): void; destroyCryptoKeyVersion( - request?: protos.google.cloud.kms.v1.IDestroyCryptoKeyVersionRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.kms.v1.ICryptoKeyVersion, - protos.google.cloud.kms.v1.IDestroyCryptoKeyVersionRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.kms.v1.IDestroyCryptoKeyVersionRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.kms.v1.ICryptoKeyVersion, - protos.google.cloud.kms.v1.IDestroyCryptoKeyVersionRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.kms.v1.ICryptoKeyVersion, - protos.google.cloud.kms.v1.IDestroyCryptoKeyVersionRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.kms.v1.IDestroyCryptoKeyVersionRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.kms.v1.ICryptoKeyVersion, + | protos.google.cloud.kms.v1.IDestroyCryptoKeyVersionRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.kms.v1.ICryptoKeyVersion, + protos.google.cloud.kms.v1.IDestroyCryptoKeyVersionRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('destroyCryptoKeyVersion request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.kms.v1.ICryptoKeyVersion, - protos.google.cloud.kms.v1.IDestroyCryptoKeyVersionRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.kms.v1.ICryptoKeyVersion, + | protos.google.cloud.kms.v1.IDestroyCryptoKeyVersionRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('destroyCryptoKeyVersion response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.destroyCryptoKeyVersion(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.kms.v1.ICryptoKeyVersion, - protos.google.cloud.kms.v1.IDestroyCryptoKeyVersionRequest|undefined, {}|undefined - ]) => { - this._log.info('destroyCryptoKeyVersion response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .destroyCryptoKeyVersion(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.kms.v1.ICryptoKeyVersion, + ( + | protos.google.cloud.kms.v1.IDestroyCryptoKeyVersionRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('destroyCryptoKeyVersion response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Restore a {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersion} in the - * {@link protos.google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DESTROY_SCHEDULED|DESTROY_SCHEDULED} - * state. - * - * Upon restoration of the CryptoKeyVersion, {@link protos.google.cloud.kms.v1.CryptoKeyVersion.state|state} - * will be set to {@link protos.google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DISABLED|DISABLED}, - * and {@link protos.google.cloud.kms.v1.CryptoKeyVersion.destroy_time|destroy_time} will be cleared. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * The resource name of the {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersion} to restore. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersion}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1/key_management_service.restore_crypto_key_version.js - * region_tag:cloudkms_v1_generated_KeyManagementService_RestoreCryptoKeyVersion_async - */ + /** + * Restore a {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersion} in the + * {@link protos.google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DESTROY_SCHEDULED|DESTROY_SCHEDULED} + * state. + * + * Upon restoration of the CryptoKeyVersion, {@link protos.google.cloud.kms.v1.CryptoKeyVersion.state|state} + * will be set to {@link protos.google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DISABLED|DISABLED}, + * and {@link protos.google.cloud.kms.v1.CryptoKeyVersion.destroy_time|destroy_time} will be cleared. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * The resource name of the {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersion} to restore. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersion}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/key_management_service.restore_crypto_key_version.js + * region_tag:cloudkms_v1_generated_KeyManagementService_RestoreCryptoKeyVersion_async + */ restoreCryptoKeyVersion( - request?: protos.google.cloud.kms.v1.IRestoreCryptoKeyVersionRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.kms.v1.ICryptoKeyVersion, - protos.google.cloud.kms.v1.IRestoreCryptoKeyVersionRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.kms.v1.IRestoreCryptoKeyVersionRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.kms.v1.ICryptoKeyVersion, + protos.google.cloud.kms.v1.IRestoreCryptoKeyVersionRequest | undefined, + {} | undefined, + ] + >; restoreCryptoKeyVersion( - request: protos.google.cloud.kms.v1.IRestoreCryptoKeyVersionRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.kms.v1.ICryptoKeyVersion, - protos.google.cloud.kms.v1.IRestoreCryptoKeyVersionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.kms.v1.IRestoreCryptoKeyVersionRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.kms.v1.ICryptoKeyVersion, + | protos.google.cloud.kms.v1.IRestoreCryptoKeyVersionRequest + | null + | undefined, + {} | null | undefined + >, + ): void; restoreCryptoKeyVersion( - request: protos.google.cloud.kms.v1.IRestoreCryptoKeyVersionRequest, - callback: Callback< - protos.google.cloud.kms.v1.ICryptoKeyVersion, - protos.google.cloud.kms.v1.IRestoreCryptoKeyVersionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.kms.v1.IRestoreCryptoKeyVersionRequest, + callback: Callback< + protos.google.cloud.kms.v1.ICryptoKeyVersion, + | protos.google.cloud.kms.v1.IRestoreCryptoKeyVersionRequest + | null + | undefined, + {} | null | undefined + >, + ): void; restoreCryptoKeyVersion( - request?: protos.google.cloud.kms.v1.IRestoreCryptoKeyVersionRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.kms.v1.ICryptoKeyVersion, - protos.google.cloud.kms.v1.IRestoreCryptoKeyVersionRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.kms.v1.IRestoreCryptoKeyVersionRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.kms.v1.ICryptoKeyVersion, - protos.google.cloud.kms.v1.IRestoreCryptoKeyVersionRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.kms.v1.ICryptoKeyVersion, - protos.google.cloud.kms.v1.IRestoreCryptoKeyVersionRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.kms.v1.IRestoreCryptoKeyVersionRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.kms.v1.ICryptoKeyVersion, + | protos.google.cloud.kms.v1.IRestoreCryptoKeyVersionRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.kms.v1.ICryptoKeyVersion, + protos.google.cloud.kms.v1.IRestoreCryptoKeyVersionRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('restoreCryptoKeyVersion request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.kms.v1.ICryptoKeyVersion, - protos.google.cloud.kms.v1.IRestoreCryptoKeyVersionRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.kms.v1.ICryptoKeyVersion, + | protos.google.cloud.kms.v1.IRestoreCryptoKeyVersionRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('restoreCryptoKeyVersion response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.restoreCryptoKeyVersion(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.kms.v1.ICryptoKeyVersion, - protos.google.cloud.kms.v1.IRestoreCryptoKeyVersionRequest|undefined, {}|undefined - ]) => { - this._log.info('restoreCryptoKeyVersion response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .restoreCryptoKeyVersion(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.kms.v1.ICryptoKeyVersion, + ( + | protos.google.cloud.kms.v1.IRestoreCryptoKeyVersionRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('restoreCryptoKeyVersion response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } - /** - * Lists {@link protos.google.cloud.kms.v1.KeyRing|KeyRings}. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The resource name of the location associated with the - * {@link protos.google.cloud.kms.v1.KeyRing|KeyRings}, in the format `projects/* /locations/*`. - * @param {number} request.pageSize - * Optional limit on the number of {@link protos.google.cloud.kms.v1.KeyRing|KeyRings} to include in the - * response. Further {@link protos.google.cloud.kms.v1.KeyRing|KeyRings} can subsequently be obtained by - * including the {@link protos.google.cloud.kms.v1.ListKeyRingsResponse.next_page_token|ListKeyRingsResponse.next_page_token} in a subsequent - * request. If unspecified, the server will pick an appropriate default. - * @param {string} request.pageToken - * Optional pagination token, returned earlier via - * {@link protos.google.cloud.kms.v1.ListKeyRingsResponse.next_page_token|ListKeyRingsResponse.next_page_token}. - * @param {string} request.filter - * Optional. Only include resources that match the filter in the response. - * @param {string} request.orderBy - * Optional. Specify how the results should be sorted. If not specified, the - * results will be sorted in the default order. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.cloud.kms.v1.KeyRing|KeyRing}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `listKeyRingsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Lists {@link protos.google.cloud.kms.v1.KeyRing|KeyRings}. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The resource name of the location associated with the + * {@link protos.google.cloud.kms.v1.KeyRing|KeyRings}, in the format `projects/* /locations/*`. + * @param {number} request.pageSize + * Optional limit on the number of {@link protos.google.cloud.kms.v1.KeyRing|KeyRings} to include in the + * response. Further {@link protos.google.cloud.kms.v1.KeyRing|KeyRings} can subsequently be obtained by + * including the {@link protos.google.cloud.kms.v1.ListKeyRingsResponse.next_page_token|ListKeyRingsResponse.next_page_token} in a subsequent + * request. If unspecified, the server will pick an appropriate default. + * @param {string} request.pageToken + * Optional pagination token, returned earlier via + * {@link protos.google.cloud.kms.v1.ListKeyRingsResponse.next_page_token|ListKeyRingsResponse.next_page_token}. + * @param {string} request.filter + * Optional. Only include resources that match the filter in the response. + * @param {string} request.orderBy + * Optional. Specify how the results should be sorted. If not specified, the + * results will be sorted in the default order. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.cloud.kms.v1.KeyRing|KeyRing}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listKeyRingsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listKeyRings( - request?: protos.google.cloud.kms.v1.IListKeyRingsRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.kms.v1.IKeyRing[], - protos.google.cloud.kms.v1.IListKeyRingsRequest|null, - protos.google.cloud.kms.v1.IListKeyRingsResponse - ]>; + request?: protos.google.cloud.kms.v1.IListKeyRingsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.kms.v1.IKeyRing[], + protos.google.cloud.kms.v1.IListKeyRingsRequest | null, + protos.google.cloud.kms.v1.IListKeyRingsResponse, + ] + >; listKeyRings( - request: protos.google.cloud.kms.v1.IListKeyRingsRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.cloud.kms.v1.IListKeyRingsRequest, - protos.google.cloud.kms.v1.IListKeyRingsResponse|null|undefined, - protos.google.cloud.kms.v1.IKeyRing>): void; + request: protos.google.cloud.kms.v1.IListKeyRingsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.cloud.kms.v1.IListKeyRingsRequest, + protos.google.cloud.kms.v1.IListKeyRingsResponse | null | undefined, + protos.google.cloud.kms.v1.IKeyRing + >, + ): void; listKeyRings( - request: protos.google.cloud.kms.v1.IListKeyRingsRequest, - callback: PaginationCallback< - protos.google.cloud.kms.v1.IListKeyRingsRequest, - protos.google.cloud.kms.v1.IListKeyRingsResponse|null|undefined, - protos.google.cloud.kms.v1.IKeyRing>): void; + request: protos.google.cloud.kms.v1.IListKeyRingsRequest, + callback: PaginationCallback< + protos.google.cloud.kms.v1.IListKeyRingsRequest, + protos.google.cloud.kms.v1.IListKeyRingsResponse | null | undefined, + protos.google.cloud.kms.v1.IKeyRing + >, + ): void; listKeyRings( - request?: protos.google.cloud.kms.v1.IListKeyRingsRequest, - optionsOrCallback?: CallOptions|PaginationCallback< - protos.google.cloud.kms.v1.IListKeyRingsRequest, - protos.google.cloud.kms.v1.IListKeyRingsResponse|null|undefined, - protos.google.cloud.kms.v1.IKeyRing>, - callback?: PaginationCallback< + request?: protos.google.cloud.kms.v1.IListKeyRingsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.cloud.kms.v1.IListKeyRingsRequest, - protos.google.cloud.kms.v1.IListKeyRingsResponse|null|undefined, - protos.google.cloud.kms.v1.IKeyRing>): - Promise<[ - protos.google.cloud.kms.v1.IKeyRing[], - protos.google.cloud.kms.v1.IListKeyRingsRequest|null, - protos.google.cloud.kms.v1.IListKeyRingsResponse - ]>|void { + protos.google.cloud.kms.v1.IListKeyRingsResponse | null | undefined, + protos.google.cloud.kms.v1.IKeyRing + >, + callback?: PaginationCallback< + protos.google.cloud.kms.v1.IListKeyRingsRequest, + protos.google.cloud.kms.v1.IListKeyRingsResponse | null | undefined, + protos.google.cloud.kms.v1.IKeyRing + >, + ): Promise< + [ + protos.google.cloud.kms.v1.IKeyRing[], + protos.google.cloud.kms.v1.IListKeyRingsRequest | null, + protos.google.cloud.kms.v1.IListKeyRingsResponse, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.cloud.kms.v1.IListKeyRingsRequest, - protos.google.cloud.kms.v1.IListKeyRingsResponse|null|undefined, - protos.google.cloud.kms.v1.IKeyRing>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.cloud.kms.v1.IListKeyRingsRequest, + protos.google.cloud.kms.v1.IListKeyRingsResponse | null | undefined, + protos.google.cloud.kms.v1.IKeyRing + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listKeyRings values %j', values); callback!(error, values, nextPageRequest, rawResponse); @@ -2380,221 +3150,240 @@ export class KeyManagementServiceClient { this._log.info('listKeyRings request %j', request); return this.innerApiCalls .listKeyRings(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.cloud.kms.v1.IKeyRing[], - protos.google.cloud.kms.v1.IListKeyRingsRequest|null, - protos.google.cloud.kms.v1.IListKeyRingsResponse - ]) => { - this._log.info('listKeyRings values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.cloud.kms.v1.IKeyRing[], + protos.google.cloud.kms.v1.IListKeyRingsRequest | null, + protos.google.cloud.kms.v1.IListKeyRingsResponse, + ]) => { + this._log.info('listKeyRings values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listKeyRings`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The resource name of the location associated with the - * {@link protos.google.cloud.kms.v1.KeyRing|KeyRings}, in the format `projects/* /locations/*`. - * @param {number} request.pageSize - * Optional limit on the number of {@link protos.google.cloud.kms.v1.KeyRing|KeyRings} to include in the - * response. Further {@link protos.google.cloud.kms.v1.KeyRing|KeyRings} can subsequently be obtained by - * including the {@link protos.google.cloud.kms.v1.ListKeyRingsResponse.next_page_token|ListKeyRingsResponse.next_page_token} in a subsequent - * request. If unspecified, the server will pick an appropriate default. - * @param {string} request.pageToken - * Optional pagination token, returned earlier via - * {@link protos.google.cloud.kms.v1.ListKeyRingsResponse.next_page_token|ListKeyRingsResponse.next_page_token}. - * @param {string} request.filter - * Optional. Only include resources that match the filter in the response. - * @param {string} request.orderBy - * Optional. Specify how the results should be sorted. If not specified, the - * results will be sorted in the default order. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.cloud.kms.v1.KeyRing|KeyRing} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `listKeyRingsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `listKeyRings`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The resource name of the location associated with the + * {@link protos.google.cloud.kms.v1.KeyRing|KeyRings}, in the format `projects/* /locations/*`. + * @param {number} request.pageSize + * Optional limit on the number of {@link protos.google.cloud.kms.v1.KeyRing|KeyRings} to include in the + * response. Further {@link protos.google.cloud.kms.v1.KeyRing|KeyRings} can subsequently be obtained by + * including the {@link protos.google.cloud.kms.v1.ListKeyRingsResponse.next_page_token|ListKeyRingsResponse.next_page_token} in a subsequent + * request. If unspecified, the server will pick an appropriate default. + * @param {string} request.pageToken + * Optional pagination token, returned earlier via + * {@link protos.google.cloud.kms.v1.ListKeyRingsResponse.next_page_token|ListKeyRingsResponse.next_page_token}. + * @param {string} request.filter + * Optional. Only include resources that match the filter in the response. + * @param {string} request.orderBy + * Optional. Specify how the results should be sorted. If not specified, the + * results will be sorted in the default order. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.cloud.kms.v1.KeyRing|KeyRing} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listKeyRingsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listKeyRingsStream( - request?: protos.google.cloud.kms.v1.IListKeyRingsRequest, - options?: CallOptions): - Transform{ + request?: protos.google.cloud.kms.v1.IListKeyRingsRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); const defaultCallSettings = this._defaults['listKeyRings']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listKeyRings stream %j', request); return this.descriptors.page.listKeyRings.createStream( this.innerApiCalls.listKeyRings as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listKeyRings`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The resource name of the location associated with the - * {@link protos.google.cloud.kms.v1.KeyRing|KeyRings}, in the format `projects/* /locations/*`. - * @param {number} request.pageSize - * Optional limit on the number of {@link protos.google.cloud.kms.v1.KeyRing|KeyRings} to include in the - * response. Further {@link protos.google.cloud.kms.v1.KeyRing|KeyRings} can subsequently be obtained by - * including the {@link protos.google.cloud.kms.v1.ListKeyRingsResponse.next_page_token|ListKeyRingsResponse.next_page_token} in a subsequent - * request. If unspecified, the server will pick an appropriate default. - * @param {string} request.pageToken - * Optional pagination token, returned earlier via - * {@link protos.google.cloud.kms.v1.ListKeyRingsResponse.next_page_token|ListKeyRingsResponse.next_page_token}. - * @param {string} request.filter - * Optional. Only include resources that match the filter in the response. - * @param {string} request.orderBy - * Optional. Specify how the results should be sorted. If not specified, the - * results will be sorted in the default order. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.cloud.kms.v1.KeyRing|KeyRing}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v1/key_management_service.list_key_rings.js - * region_tag:cloudkms_v1_generated_KeyManagementService_ListKeyRings_async - */ + /** + * Equivalent to `listKeyRings`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The resource name of the location associated with the + * {@link protos.google.cloud.kms.v1.KeyRing|KeyRings}, in the format `projects/* /locations/*`. + * @param {number} request.pageSize + * Optional limit on the number of {@link protos.google.cloud.kms.v1.KeyRing|KeyRings} to include in the + * response. Further {@link protos.google.cloud.kms.v1.KeyRing|KeyRings} can subsequently be obtained by + * including the {@link protos.google.cloud.kms.v1.ListKeyRingsResponse.next_page_token|ListKeyRingsResponse.next_page_token} in a subsequent + * request. If unspecified, the server will pick an appropriate default. + * @param {string} request.pageToken + * Optional pagination token, returned earlier via + * {@link protos.google.cloud.kms.v1.ListKeyRingsResponse.next_page_token|ListKeyRingsResponse.next_page_token}. + * @param {string} request.filter + * Optional. Only include resources that match the filter in the response. + * @param {string} request.orderBy + * Optional. Specify how the results should be sorted. If not specified, the + * results will be sorted in the default order. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.cloud.kms.v1.KeyRing|KeyRing}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v1/key_management_service.list_key_rings.js + * region_tag:cloudkms_v1_generated_KeyManagementService_ListKeyRings_async + */ listKeyRingsAsync( - request?: protos.google.cloud.kms.v1.IListKeyRingsRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.cloud.kms.v1.IListKeyRingsRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); const defaultCallSettings = this._defaults['listKeyRings']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listKeyRings iterate %j', request); return this.descriptors.page.listKeyRings.asyncIterate( this.innerApiCalls['listKeyRings'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } - /** - * Lists {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKeys}. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The resource name of the {@link protos.google.cloud.kms.v1.KeyRing|KeyRing} to list, in the format - * `projects/* /locations/* /keyRings/*`. - * @param {number} request.pageSize - * Optional limit on the number of {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKeys} to include in the - * response. Further {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKeys} can subsequently be obtained by - * including the {@link protos.google.cloud.kms.v1.ListCryptoKeysResponse.next_page_token|ListCryptoKeysResponse.next_page_token} in a subsequent - * request. If unspecified, the server will pick an appropriate default. - * @param {string} request.pageToken - * Optional pagination token, returned earlier via - * {@link protos.google.cloud.kms.v1.ListCryptoKeysResponse.next_page_token|ListCryptoKeysResponse.next_page_token}. - * @param {google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionView} request.versionView - * The fields of the primary version to include in the response. - * @param {string} request.filter - * Optional. Only include resources that match the filter in the response. - * @param {string} request.orderBy - * Optional. Specify how the results should be sorted. If not specified, the - * results will be sorted in the default order. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKey}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `listCryptoKeysAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Lists {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKeys}. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The resource name of the {@link protos.google.cloud.kms.v1.KeyRing|KeyRing} to list, in the format + * `projects/* /locations/* /keyRings/*`. + * @param {number} request.pageSize + * Optional limit on the number of {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKeys} to include in the + * response. Further {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKeys} can subsequently be obtained by + * including the {@link protos.google.cloud.kms.v1.ListCryptoKeysResponse.next_page_token|ListCryptoKeysResponse.next_page_token} in a subsequent + * request. If unspecified, the server will pick an appropriate default. + * @param {string} request.pageToken + * Optional pagination token, returned earlier via + * {@link protos.google.cloud.kms.v1.ListCryptoKeysResponse.next_page_token|ListCryptoKeysResponse.next_page_token}. + * @param {google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionView} request.versionView + * The fields of the primary version to include in the response. + * @param {string} request.filter + * Optional. Only include resources that match the filter in the response. + * @param {string} request.orderBy + * Optional. Specify how the results should be sorted. If not specified, the + * results will be sorted in the default order. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKey}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listCryptoKeysAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listCryptoKeys( - request?: protos.google.cloud.kms.v1.IListCryptoKeysRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.kms.v1.ICryptoKey[], - protos.google.cloud.kms.v1.IListCryptoKeysRequest|null, - protos.google.cloud.kms.v1.IListCryptoKeysResponse - ]>; + request?: protos.google.cloud.kms.v1.IListCryptoKeysRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.kms.v1.ICryptoKey[], + protos.google.cloud.kms.v1.IListCryptoKeysRequest | null, + protos.google.cloud.kms.v1.IListCryptoKeysResponse, + ] + >; listCryptoKeys( - request: protos.google.cloud.kms.v1.IListCryptoKeysRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.cloud.kms.v1.IListCryptoKeysRequest, - protos.google.cloud.kms.v1.IListCryptoKeysResponse|null|undefined, - protos.google.cloud.kms.v1.ICryptoKey>): void; + request: protos.google.cloud.kms.v1.IListCryptoKeysRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.cloud.kms.v1.IListCryptoKeysRequest, + protos.google.cloud.kms.v1.IListCryptoKeysResponse | null | undefined, + protos.google.cloud.kms.v1.ICryptoKey + >, + ): void; listCryptoKeys( - request: protos.google.cloud.kms.v1.IListCryptoKeysRequest, - callback: PaginationCallback< - protos.google.cloud.kms.v1.IListCryptoKeysRequest, - protos.google.cloud.kms.v1.IListCryptoKeysResponse|null|undefined, - protos.google.cloud.kms.v1.ICryptoKey>): void; + request: protos.google.cloud.kms.v1.IListCryptoKeysRequest, + callback: PaginationCallback< + protos.google.cloud.kms.v1.IListCryptoKeysRequest, + protos.google.cloud.kms.v1.IListCryptoKeysResponse | null | undefined, + protos.google.cloud.kms.v1.ICryptoKey + >, + ): void; listCryptoKeys( - request?: protos.google.cloud.kms.v1.IListCryptoKeysRequest, - optionsOrCallback?: CallOptions|PaginationCallback< - protos.google.cloud.kms.v1.IListCryptoKeysRequest, - protos.google.cloud.kms.v1.IListCryptoKeysResponse|null|undefined, - protos.google.cloud.kms.v1.ICryptoKey>, - callback?: PaginationCallback< + request?: protos.google.cloud.kms.v1.IListCryptoKeysRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.cloud.kms.v1.IListCryptoKeysRequest, - protos.google.cloud.kms.v1.IListCryptoKeysResponse|null|undefined, - protos.google.cloud.kms.v1.ICryptoKey>): - Promise<[ - protos.google.cloud.kms.v1.ICryptoKey[], - protos.google.cloud.kms.v1.IListCryptoKeysRequest|null, - protos.google.cloud.kms.v1.IListCryptoKeysResponse - ]>|void { + protos.google.cloud.kms.v1.IListCryptoKeysResponse | null | undefined, + protos.google.cloud.kms.v1.ICryptoKey + >, + callback?: PaginationCallback< + protos.google.cloud.kms.v1.IListCryptoKeysRequest, + protos.google.cloud.kms.v1.IListCryptoKeysResponse | null | undefined, + protos.google.cloud.kms.v1.ICryptoKey + >, + ): Promise< + [ + protos.google.cloud.kms.v1.ICryptoKey[], + protos.google.cloud.kms.v1.IListCryptoKeysRequest | null, + protos.google.cloud.kms.v1.IListCryptoKeysResponse, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.cloud.kms.v1.IListCryptoKeysRequest, - protos.google.cloud.kms.v1.IListCryptoKeysResponse|null|undefined, - protos.google.cloud.kms.v1.ICryptoKey>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.cloud.kms.v1.IListCryptoKeysRequest, + protos.google.cloud.kms.v1.IListCryptoKeysResponse | null | undefined, + protos.google.cloud.kms.v1.ICryptoKey + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listCryptoKeys values %j', values); callback!(error, values, nextPageRequest, rawResponse); @@ -2603,226 +3392,255 @@ export class KeyManagementServiceClient { this._log.info('listCryptoKeys request %j', request); return this.innerApiCalls .listCryptoKeys(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.cloud.kms.v1.ICryptoKey[], - protos.google.cloud.kms.v1.IListCryptoKeysRequest|null, - protos.google.cloud.kms.v1.IListCryptoKeysResponse - ]) => { - this._log.info('listCryptoKeys values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.cloud.kms.v1.ICryptoKey[], + protos.google.cloud.kms.v1.IListCryptoKeysRequest | null, + protos.google.cloud.kms.v1.IListCryptoKeysResponse, + ]) => { + this._log.info('listCryptoKeys values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listCryptoKeys`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The resource name of the {@link protos.google.cloud.kms.v1.KeyRing|KeyRing} to list, in the format - * `projects/* /locations/* /keyRings/*`. - * @param {number} request.pageSize - * Optional limit on the number of {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKeys} to include in the - * response. Further {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKeys} can subsequently be obtained by - * including the {@link protos.google.cloud.kms.v1.ListCryptoKeysResponse.next_page_token|ListCryptoKeysResponse.next_page_token} in a subsequent - * request. If unspecified, the server will pick an appropriate default. - * @param {string} request.pageToken - * Optional pagination token, returned earlier via - * {@link protos.google.cloud.kms.v1.ListCryptoKeysResponse.next_page_token|ListCryptoKeysResponse.next_page_token}. - * @param {google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionView} request.versionView - * The fields of the primary version to include in the response. - * @param {string} request.filter - * Optional. Only include resources that match the filter in the response. - * @param {string} request.orderBy - * Optional. Specify how the results should be sorted. If not specified, the - * results will be sorted in the default order. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKey} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `listCryptoKeysAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `listCryptoKeys`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The resource name of the {@link protos.google.cloud.kms.v1.KeyRing|KeyRing} to list, in the format + * `projects/* /locations/* /keyRings/*`. + * @param {number} request.pageSize + * Optional limit on the number of {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKeys} to include in the + * response. Further {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKeys} can subsequently be obtained by + * including the {@link protos.google.cloud.kms.v1.ListCryptoKeysResponse.next_page_token|ListCryptoKeysResponse.next_page_token} in a subsequent + * request. If unspecified, the server will pick an appropriate default. + * @param {string} request.pageToken + * Optional pagination token, returned earlier via + * {@link protos.google.cloud.kms.v1.ListCryptoKeysResponse.next_page_token|ListCryptoKeysResponse.next_page_token}. + * @param {google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionView} request.versionView + * The fields of the primary version to include in the response. + * @param {string} request.filter + * Optional. Only include resources that match the filter in the response. + * @param {string} request.orderBy + * Optional. Specify how the results should be sorted. If not specified, the + * results will be sorted in the default order. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKey} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listCryptoKeysAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listCryptoKeysStream( - request?: protos.google.cloud.kms.v1.IListCryptoKeysRequest, - options?: CallOptions): - Transform{ + request?: protos.google.cloud.kms.v1.IListCryptoKeysRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); const defaultCallSettings = this._defaults['listCryptoKeys']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listCryptoKeys stream %j', request); return this.descriptors.page.listCryptoKeys.createStream( this.innerApiCalls.listCryptoKeys as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listCryptoKeys`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The resource name of the {@link protos.google.cloud.kms.v1.KeyRing|KeyRing} to list, in the format - * `projects/* /locations/* /keyRings/*`. - * @param {number} request.pageSize - * Optional limit on the number of {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKeys} to include in the - * response. Further {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKeys} can subsequently be obtained by - * including the {@link protos.google.cloud.kms.v1.ListCryptoKeysResponse.next_page_token|ListCryptoKeysResponse.next_page_token} in a subsequent - * request. If unspecified, the server will pick an appropriate default. - * @param {string} request.pageToken - * Optional pagination token, returned earlier via - * {@link protos.google.cloud.kms.v1.ListCryptoKeysResponse.next_page_token|ListCryptoKeysResponse.next_page_token}. - * @param {google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionView} request.versionView - * The fields of the primary version to include in the response. - * @param {string} request.filter - * Optional. Only include resources that match the filter in the response. - * @param {string} request.orderBy - * Optional. Specify how the results should be sorted. If not specified, the - * results will be sorted in the default order. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKey}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v1/key_management_service.list_crypto_keys.js - * region_tag:cloudkms_v1_generated_KeyManagementService_ListCryptoKeys_async - */ + /** + * Equivalent to `listCryptoKeys`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The resource name of the {@link protos.google.cloud.kms.v1.KeyRing|KeyRing} to list, in the format + * `projects/* /locations/* /keyRings/*`. + * @param {number} request.pageSize + * Optional limit on the number of {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKeys} to include in the + * response. Further {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKeys} can subsequently be obtained by + * including the {@link protos.google.cloud.kms.v1.ListCryptoKeysResponse.next_page_token|ListCryptoKeysResponse.next_page_token} in a subsequent + * request. If unspecified, the server will pick an appropriate default. + * @param {string} request.pageToken + * Optional pagination token, returned earlier via + * {@link protos.google.cloud.kms.v1.ListCryptoKeysResponse.next_page_token|ListCryptoKeysResponse.next_page_token}. + * @param {google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionView} request.versionView + * The fields of the primary version to include in the response. + * @param {string} request.filter + * Optional. Only include resources that match the filter in the response. + * @param {string} request.orderBy + * Optional. Specify how the results should be sorted. If not specified, the + * results will be sorted in the default order. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKey}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v1/key_management_service.list_crypto_keys.js + * region_tag:cloudkms_v1_generated_KeyManagementService_ListCryptoKeys_async + */ listCryptoKeysAsync( - request?: protos.google.cloud.kms.v1.IListCryptoKeysRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.cloud.kms.v1.IListCryptoKeysRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); const defaultCallSettings = this._defaults['listCryptoKeys']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listCryptoKeys iterate %j', request); return this.descriptors.page.listCryptoKeys.asyncIterate( this.innerApiCalls['listCryptoKeys'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } - /** - * Lists {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersions}. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The resource name of the {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKey} to list, in the format - * `projects/* /locations/* /keyRings/* /cryptoKeys/*`. - * @param {number} request.pageSize - * Optional limit on the number of {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersions} to - * include in the response. Further {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersions} can - * subsequently be obtained by including the - * {@link protos.google.cloud.kms.v1.ListCryptoKeyVersionsResponse.next_page_token|ListCryptoKeyVersionsResponse.next_page_token} in a subsequent request. - * If unspecified, the server will pick an appropriate default. - * @param {string} request.pageToken - * Optional pagination token, returned earlier via - * {@link protos.google.cloud.kms.v1.ListCryptoKeyVersionsResponse.next_page_token|ListCryptoKeyVersionsResponse.next_page_token}. - * @param {google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionView} request.view - * The fields to include in the response. - * @param {string} request.filter - * Optional. Only include resources that match the filter in the response. - * @param {string} request.orderBy - * Optional. Specify how the results should be sorted. If not specified, the - * results will be sorted in the default order. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersion}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `listCryptoKeyVersionsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Lists {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersions}. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The resource name of the {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKey} to list, in the format + * `projects/* /locations/* /keyRings/* /cryptoKeys/*`. + * @param {number} request.pageSize + * Optional limit on the number of {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersions} to + * include in the response. Further {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersions} can + * subsequently be obtained by including the + * {@link protos.google.cloud.kms.v1.ListCryptoKeyVersionsResponse.next_page_token|ListCryptoKeyVersionsResponse.next_page_token} in a subsequent request. + * If unspecified, the server will pick an appropriate default. + * @param {string} request.pageToken + * Optional pagination token, returned earlier via + * {@link protos.google.cloud.kms.v1.ListCryptoKeyVersionsResponse.next_page_token|ListCryptoKeyVersionsResponse.next_page_token}. + * @param {google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionView} request.view + * The fields to include in the response. + * @param {string} request.filter + * Optional. Only include resources that match the filter in the response. + * @param {string} request.orderBy + * Optional. Specify how the results should be sorted. If not specified, the + * results will be sorted in the default order. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersion}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listCryptoKeyVersionsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listCryptoKeyVersions( - request?: protos.google.cloud.kms.v1.IListCryptoKeyVersionsRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.kms.v1.ICryptoKeyVersion[], - protos.google.cloud.kms.v1.IListCryptoKeyVersionsRequest|null, - protos.google.cloud.kms.v1.IListCryptoKeyVersionsResponse - ]>; + request?: protos.google.cloud.kms.v1.IListCryptoKeyVersionsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.kms.v1.ICryptoKeyVersion[], + protos.google.cloud.kms.v1.IListCryptoKeyVersionsRequest | null, + protos.google.cloud.kms.v1.IListCryptoKeyVersionsResponse, + ] + >; listCryptoKeyVersions( - request: protos.google.cloud.kms.v1.IListCryptoKeyVersionsRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.cloud.kms.v1.IListCryptoKeyVersionsRequest, - protos.google.cloud.kms.v1.IListCryptoKeyVersionsResponse|null|undefined, - protos.google.cloud.kms.v1.ICryptoKeyVersion>): void; + request: protos.google.cloud.kms.v1.IListCryptoKeyVersionsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.cloud.kms.v1.IListCryptoKeyVersionsRequest, + | protos.google.cloud.kms.v1.IListCryptoKeyVersionsResponse + | null + | undefined, + protos.google.cloud.kms.v1.ICryptoKeyVersion + >, + ): void; listCryptoKeyVersions( - request: protos.google.cloud.kms.v1.IListCryptoKeyVersionsRequest, - callback: PaginationCallback< - protos.google.cloud.kms.v1.IListCryptoKeyVersionsRequest, - protos.google.cloud.kms.v1.IListCryptoKeyVersionsResponse|null|undefined, - protos.google.cloud.kms.v1.ICryptoKeyVersion>): void; + request: protos.google.cloud.kms.v1.IListCryptoKeyVersionsRequest, + callback: PaginationCallback< + protos.google.cloud.kms.v1.IListCryptoKeyVersionsRequest, + | protos.google.cloud.kms.v1.IListCryptoKeyVersionsResponse + | null + | undefined, + protos.google.cloud.kms.v1.ICryptoKeyVersion + >, + ): void; listCryptoKeyVersions( - request?: protos.google.cloud.kms.v1.IListCryptoKeyVersionsRequest, - optionsOrCallback?: CallOptions|PaginationCallback< - protos.google.cloud.kms.v1.IListCryptoKeyVersionsRequest, - protos.google.cloud.kms.v1.IListCryptoKeyVersionsResponse|null|undefined, - protos.google.cloud.kms.v1.ICryptoKeyVersion>, - callback?: PaginationCallback< + request?: protos.google.cloud.kms.v1.IListCryptoKeyVersionsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.cloud.kms.v1.IListCryptoKeyVersionsRequest, - protos.google.cloud.kms.v1.IListCryptoKeyVersionsResponse|null|undefined, - protos.google.cloud.kms.v1.ICryptoKeyVersion>): - Promise<[ - protos.google.cloud.kms.v1.ICryptoKeyVersion[], - protos.google.cloud.kms.v1.IListCryptoKeyVersionsRequest|null, - protos.google.cloud.kms.v1.IListCryptoKeyVersionsResponse - ]>|void { + | protos.google.cloud.kms.v1.IListCryptoKeyVersionsResponse + | null + | undefined, + protos.google.cloud.kms.v1.ICryptoKeyVersion + >, + callback?: PaginationCallback< + protos.google.cloud.kms.v1.IListCryptoKeyVersionsRequest, + | protos.google.cloud.kms.v1.IListCryptoKeyVersionsResponse + | null + | undefined, + protos.google.cloud.kms.v1.ICryptoKeyVersion + >, + ): Promise< + [ + protos.google.cloud.kms.v1.ICryptoKeyVersion[], + protos.google.cloud.kms.v1.IListCryptoKeyVersionsRequest | null, + protos.google.cloud.kms.v1.IListCryptoKeyVersionsResponse, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.cloud.kms.v1.IListCryptoKeyVersionsRequest, - protos.google.cloud.kms.v1.IListCryptoKeyVersionsResponse|null|undefined, - protos.google.cloud.kms.v1.ICryptoKeyVersion>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.cloud.kms.v1.IListCryptoKeyVersionsRequest, + | protos.google.cloud.kms.v1.IListCryptoKeyVersionsResponse + | null + | undefined, + protos.google.cloud.kms.v1.ICryptoKeyVersion + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listCryptoKeyVersions values %j', values); callback!(error, values, nextPageRequest, rawResponse); @@ -2831,225 +3649,244 @@ export class KeyManagementServiceClient { this._log.info('listCryptoKeyVersions request %j', request); return this.innerApiCalls .listCryptoKeyVersions(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.cloud.kms.v1.ICryptoKeyVersion[], - protos.google.cloud.kms.v1.IListCryptoKeyVersionsRequest|null, - protos.google.cloud.kms.v1.IListCryptoKeyVersionsResponse - ]) => { - this._log.info('listCryptoKeyVersions values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.cloud.kms.v1.ICryptoKeyVersion[], + protos.google.cloud.kms.v1.IListCryptoKeyVersionsRequest | null, + protos.google.cloud.kms.v1.IListCryptoKeyVersionsResponse, + ]) => { + this._log.info('listCryptoKeyVersions values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listCryptoKeyVersions`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The resource name of the {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKey} to list, in the format - * `projects/* /locations/* /keyRings/* /cryptoKeys/*`. - * @param {number} request.pageSize - * Optional limit on the number of {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersions} to - * include in the response. Further {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersions} can - * subsequently be obtained by including the - * {@link protos.google.cloud.kms.v1.ListCryptoKeyVersionsResponse.next_page_token|ListCryptoKeyVersionsResponse.next_page_token} in a subsequent request. - * If unspecified, the server will pick an appropriate default. - * @param {string} request.pageToken - * Optional pagination token, returned earlier via - * {@link protos.google.cloud.kms.v1.ListCryptoKeyVersionsResponse.next_page_token|ListCryptoKeyVersionsResponse.next_page_token}. - * @param {google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionView} request.view - * The fields to include in the response. - * @param {string} request.filter - * Optional. Only include resources that match the filter in the response. - * @param {string} request.orderBy - * Optional. Specify how the results should be sorted. If not specified, the - * results will be sorted in the default order. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersion} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `listCryptoKeyVersionsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `listCryptoKeyVersions`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The resource name of the {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKey} to list, in the format + * `projects/* /locations/* /keyRings/* /cryptoKeys/*`. + * @param {number} request.pageSize + * Optional limit on the number of {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersions} to + * include in the response. Further {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersions} can + * subsequently be obtained by including the + * {@link protos.google.cloud.kms.v1.ListCryptoKeyVersionsResponse.next_page_token|ListCryptoKeyVersionsResponse.next_page_token} in a subsequent request. + * If unspecified, the server will pick an appropriate default. + * @param {string} request.pageToken + * Optional pagination token, returned earlier via + * {@link protos.google.cloud.kms.v1.ListCryptoKeyVersionsResponse.next_page_token|ListCryptoKeyVersionsResponse.next_page_token}. + * @param {google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionView} request.view + * The fields to include in the response. + * @param {string} request.filter + * Optional. Only include resources that match the filter in the response. + * @param {string} request.orderBy + * Optional. Specify how the results should be sorted. If not specified, the + * results will be sorted in the default order. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersion} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listCryptoKeyVersionsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listCryptoKeyVersionsStream( - request?: protos.google.cloud.kms.v1.IListCryptoKeyVersionsRequest, - options?: CallOptions): - Transform{ + request?: protos.google.cloud.kms.v1.IListCryptoKeyVersionsRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); const defaultCallSettings = this._defaults['listCryptoKeyVersions']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listCryptoKeyVersions stream %j', request); return this.descriptors.page.listCryptoKeyVersions.createStream( this.innerApiCalls.listCryptoKeyVersions as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listCryptoKeyVersions`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The resource name of the {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKey} to list, in the format - * `projects/* /locations/* /keyRings/* /cryptoKeys/*`. - * @param {number} request.pageSize - * Optional limit on the number of {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersions} to - * include in the response. Further {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersions} can - * subsequently be obtained by including the - * {@link protos.google.cloud.kms.v1.ListCryptoKeyVersionsResponse.next_page_token|ListCryptoKeyVersionsResponse.next_page_token} in a subsequent request. - * If unspecified, the server will pick an appropriate default. - * @param {string} request.pageToken - * Optional pagination token, returned earlier via - * {@link protos.google.cloud.kms.v1.ListCryptoKeyVersionsResponse.next_page_token|ListCryptoKeyVersionsResponse.next_page_token}. - * @param {google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionView} request.view - * The fields to include in the response. - * @param {string} request.filter - * Optional. Only include resources that match the filter in the response. - * @param {string} request.orderBy - * Optional. Specify how the results should be sorted. If not specified, the - * results will be sorted in the default order. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersion}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v1/key_management_service.list_crypto_key_versions.js - * region_tag:cloudkms_v1_generated_KeyManagementService_ListCryptoKeyVersions_async - */ + /** + * Equivalent to `listCryptoKeyVersions`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The resource name of the {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKey} to list, in the format + * `projects/* /locations/* /keyRings/* /cryptoKeys/*`. + * @param {number} request.pageSize + * Optional limit on the number of {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersions} to + * include in the response. Further {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersions} can + * subsequently be obtained by including the + * {@link protos.google.cloud.kms.v1.ListCryptoKeyVersionsResponse.next_page_token|ListCryptoKeyVersionsResponse.next_page_token} in a subsequent request. + * If unspecified, the server will pick an appropriate default. + * @param {string} request.pageToken + * Optional pagination token, returned earlier via + * {@link protos.google.cloud.kms.v1.ListCryptoKeyVersionsResponse.next_page_token|ListCryptoKeyVersionsResponse.next_page_token}. + * @param {google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionView} request.view + * The fields to include in the response. + * @param {string} request.filter + * Optional. Only include resources that match the filter in the response. + * @param {string} request.orderBy + * Optional. Specify how the results should be sorted. If not specified, the + * results will be sorted in the default order. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersion}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v1/key_management_service.list_crypto_key_versions.js + * region_tag:cloudkms_v1_generated_KeyManagementService_ListCryptoKeyVersions_async + */ listCryptoKeyVersionsAsync( - request?: protos.google.cloud.kms.v1.IListCryptoKeyVersionsRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.cloud.kms.v1.IListCryptoKeyVersionsRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); const defaultCallSettings = this._defaults['listCryptoKeyVersions']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listCryptoKeyVersions iterate %j', request); return this.descriptors.page.listCryptoKeyVersions.asyncIterate( this.innerApiCalls['listCryptoKeyVersions'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } - /** - * Lists {@link protos.google.cloud.kms.v1.ImportJob|ImportJobs}. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The resource name of the {@link protos.google.cloud.kms.v1.KeyRing|KeyRing} to list, in the format - * `projects/* /locations/* /keyRings/*`. - * @param {number} request.pageSize - * Optional limit on the number of {@link protos.google.cloud.kms.v1.ImportJob|ImportJobs} to include in the - * response. Further {@link protos.google.cloud.kms.v1.ImportJob|ImportJobs} can subsequently be obtained by - * including the {@link protos.google.cloud.kms.v1.ListImportJobsResponse.next_page_token|ListImportJobsResponse.next_page_token} in a subsequent - * request. If unspecified, the server will pick an appropriate default. - * @param {string} request.pageToken - * Optional pagination token, returned earlier via - * {@link protos.google.cloud.kms.v1.ListImportJobsResponse.next_page_token|ListImportJobsResponse.next_page_token}. - * @param {string} request.filter - * Optional. Only include resources that match the filter in the response. - * @param {string} request.orderBy - * Optional. Specify how the results should be sorted. If not specified, the - * results will be sorted in the default order. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.cloud.kms.v1.ImportJob|ImportJob}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `listImportJobsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Lists {@link protos.google.cloud.kms.v1.ImportJob|ImportJobs}. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The resource name of the {@link protos.google.cloud.kms.v1.KeyRing|KeyRing} to list, in the format + * `projects/* /locations/* /keyRings/*`. + * @param {number} request.pageSize + * Optional limit on the number of {@link protos.google.cloud.kms.v1.ImportJob|ImportJobs} to include in the + * response. Further {@link protos.google.cloud.kms.v1.ImportJob|ImportJobs} can subsequently be obtained by + * including the {@link protos.google.cloud.kms.v1.ListImportJobsResponse.next_page_token|ListImportJobsResponse.next_page_token} in a subsequent + * request. If unspecified, the server will pick an appropriate default. + * @param {string} request.pageToken + * Optional pagination token, returned earlier via + * {@link protos.google.cloud.kms.v1.ListImportJobsResponse.next_page_token|ListImportJobsResponse.next_page_token}. + * @param {string} request.filter + * Optional. Only include resources that match the filter in the response. + * @param {string} request.orderBy + * Optional. Specify how the results should be sorted. If not specified, the + * results will be sorted in the default order. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.cloud.kms.v1.ImportJob|ImportJob}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listImportJobsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listImportJobs( - request?: protos.google.cloud.kms.v1.IListImportJobsRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.kms.v1.IImportJob[], - protos.google.cloud.kms.v1.IListImportJobsRequest|null, - protos.google.cloud.kms.v1.IListImportJobsResponse - ]>; + request?: protos.google.cloud.kms.v1.IListImportJobsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.kms.v1.IImportJob[], + protos.google.cloud.kms.v1.IListImportJobsRequest | null, + protos.google.cloud.kms.v1.IListImportJobsResponse, + ] + >; listImportJobs( - request: protos.google.cloud.kms.v1.IListImportJobsRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.cloud.kms.v1.IListImportJobsRequest, - protos.google.cloud.kms.v1.IListImportJobsResponse|null|undefined, - protos.google.cloud.kms.v1.IImportJob>): void; + request: protos.google.cloud.kms.v1.IListImportJobsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.cloud.kms.v1.IListImportJobsRequest, + protos.google.cloud.kms.v1.IListImportJobsResponse | null | undefined, + protos.google.cloud.kms.v1.IImportJob + >, + ): void; listImportJobs( - request: protos.google.cloud.kms.v1.IListImportJobsRequest, - callback: PaginationCallback< - protos.google.cloud.kms.v1.IListImportJobsRequest, - protos.google.cloud.kms.v1.IListImportJobsResponse|null|undefined, - protos.google.cloud.kms.v1.IImportJob>): void; + request: protos.google.cloud.kms.v1.IListImportJobsRequest, + callback: PaginationCallback< + protos.google.cloud.kms.v1.IListImportJobsRequest, + protos.google.cloud.kms.v1.IListImportJobsResponse | null | undefined, + protos.google.cloud.kms.v1.IImportJob + >, + ): void; listImportJobs( - request?: protos.google.cloud.kms.v1.IListImportJobsRequest, - optionsOrCallback?: CallOptions|PaginationCallback< + request?: protos.google.cloud.kms.v1.IListImportJobsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.cloud.kms.v1.IListImportJobsRequest, - protos.google.cloud.kms.v1.IListImportJobsResponse|null|undefined, - protos.google.cloud.kms.v1.IImportJob>, - callback?: PaginationCallback< - protos.google.cloud.kms.v1.IListImportJobsRequest, - protos.google.cloud.kms.v1.IListImportJobsResponse|null|undefined, - protos.google.cloud.kms.v1.IImportJob>): - Promise<[ - protos.google.cloud.kms.v1.IImportJob[], - protos.google.cloud.kms.v1.IListImportJobsRequest|null, - protos.google.cloud.kms.v1.IListImportJobsResponse - ]>|void { + protos.google.cloud.kms.v1.IListImportJobsResponse | null | undefined, + protos.google.cloud.kms.v1.IImportJob + >, + callback?: PaginationCallback< + protos.google.cloud.kms.v1.IListImportJobsRequest, + protos.google.cloud.kms.v1.IListImportJobsResponse | null | undefined, + protos.google.cloud.kms.v1.IImportJob + >, + ): Promise< + [ + protos.google.cloud.kms.v1.IImportJob[], + protos.google.cloud.kms.v1.IListImportJobsRequest | null, + protos.google.cloud.kms.v1.IListImportJobsResponse, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.cloud.kms.v1.IListImportJobsRequest, - protos.google.cloud.kms.v1.IListImportJobsResponse|null|undefined, - protos.google.cloud.kms.v1.IImportJob>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.cloud.kms.v1.IListImportJobsRequest, + protos.google.cloud.kms.v1.IListImportJobsResponse | null | undefined, + protos.google.cloud.kms.v1.IImportJob + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listImportJobs values %j', values); callback!(error, values, nextPageRequest, rawResponse); @@ -3058,153 +3895,157 @@ export class KeyManagementServiceClient { this._log.info('listImportJobs request %j', request); return this.innerApiCalls .listImportJobs(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.cloud.kms.v1.IImportJob[], - protos.google.cloud.kms.v1.IListImportJobsRequest|null, - protos.google.cloud.kms.v1.IListImportJobsResponse - ]) => { - this._log.info('listImportJobs values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.cloud.kms.v1.IImportJob[], + protos.google.cloud.kms.v1.IListImportJobsRequest | null, + protos.google.cloud.kms.v1.IListImportJobsResponse, + ]) => { + this._log.info('listImportJobs values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listImportJobs`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The resource name of the {@link protos.google.cloud.kms.v1.KeyRing|KeyRing} to list, in the format - * `projects/* /locations/* /keyRings/*`. - * @param {number} request.pageSize - * Optional limit on the number of {@link protos.google.cloud.kms.v1.ImportJob|ImportJobs} to include in the - * response. Further {@link protos.google.cloud.kms.v1.ImportJob|ImportJobs} can subsequently be obtained by - * including the {@link protos.google.cloud.kms.v1.ListImportJobsResponse.next_page_token|ListImportJobsResponse.next_page_token} in a subsequent - * request. If unspecified, the server will pick an appropriate default. - * @param {string} request.pageToken - * Optional pagination token, returned earlier via - * {@link protos.google.cloud.kms.v1.ListImportJobsResponse.next_page_token|ListImportJobsResponse.next_page_token}. - * @param {string} request.filter - * Optional. Only include resources that match the filter in the response. - * @param {string} request.orderBy - * Optional. Specify how the results should be sorted. If not specified, the - * results will be sorted in the default order. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.cloud.kms.v1.ImportJob|ImportJob} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `listImportJobsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `listImportJobs`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The resource name of the {@link protos.google.cloud.kms.v1.KeyRing|KeyRing} to list, in the format + * `projects/* /locations/* /keyRings/*`. + * @param {number} request.pageSize + * Optional limit on the number of {@link protos.google.cloud.kms.v1.ImportJob|ImportJobs} to include in the + * response. Further {@link protos.google.cloud.kms.v1.ImportJob|ImportJobs} can subsequently be obtained by + * including the {@link protos.google.cloud.kms.v1.ListImportJobsResponse.next_page_token|ListImportJobsResponse.next_page_token} in a subsequent + * request. If unspecified, the server will pick an appropriate default. + * @param {string} request.pageToken + * Optional pagination token, returned earlier via + * {@link protos.google.cloud.kms.v1.ListImportJobsResponse.next_page_token|ListImportJobsResponse.next_page_token}. + * @param {string} request.filter + * Optional. Only include resources that match the filter in the response. + * @param {string} request.orderBy + * Optional. Specify how the results should be sorted. If not specified, the + * results will be sorted in the default order. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.cloud.kms.v1.ImportJob|ImportJob} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listImportJobsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listImportJobsStream( - request?: protos.google.cloud.kms.v1.IListImportJobsRequest, - options?: CallOptions): - Transform{ + request?: protos.google.cloud.kms.v1.IListImportJobsRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); const defaultCallSettings = this._defaults['listImportJobs']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listImportJobs stream %j', request); return this.descriptors.page.listImportJobs.createStream( this.innerApiCalls.listImportJobs as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listImportJobs`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The resource name of the {@link protos.google.cloud.kms.v1.KeyRing|KeyRing} to list, in the format - * `projects/* /locations/* /keyRings/*`. - * @param {number} request.pageSize - * Optional limit on the number of {@link protos.google.cloud.kms.v1.ImportJob|ImportJobs} to include in the - * response. Further {@link protos.google.cloud.kms.v1.ImportJob|ImportJobs} can subsequently be obtained by - * including the {@link protos.google.cloud.kms.v1.ListImportJobsResponse.next_page_token|ListImportJobsResponse.next_page_token} in a subsequent - * request. If unspecified, the server will pick an appropriate default. - * @param {string} request.pageToken - * Optional pagination token, returned earlier via - * {@link protos.google.cloud.kms.v1.ListImportJobsResponse.next_page_token|ListImportJobsResponse.next_page_token}. - * @param {string} request.filter - * Optional. Only include resources that match the filter in the response. - * @param {string} request.orderBy - * Optional. Specify how the results should be sorted. If not specified, the - * results will be sorted in the default order. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.cloud.kms.v1.ImportJob|ImportJob}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v1/key_management_service.list_import_jobs.js - * region_tag:cloudkms_v1_generated_KeyManagementService_ListImportJobs_async - */ + /** + * Equivalent to `listImportJobs`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The resource name of the {@link protos.google.cloud.kms.v1.KeyRing|KeyRing} to list, in the format + * `projects/* /locations/* /keyRings/*`. + * @param {number} request.pageSize + * Optional limit on the number of {@link protos.google.cloud.kms.v1.ImportJob|ImportJobs} to include in the + * response. Further {@link protos.google.cloud.kms.v1.ImportJob|ImportJobs} can subsequently be obtained by + * including the {@link protos.google.cloud.kms.v1.ListImportJobsResponse.next_page_token|ListImportJobsResponse.next_page_token} in a subsequent + * request. If unspecified, the server will pick an appropriate default. + * @param {string} request.pageToken + * Optional pagination token, returned earlier via + * {@link protos.google.cloud.kms.v1.ListImportJobsResponse.next_page_token|ListImportJobsResponse.next_page_token}. + * @param {string} request.filter + * Optional. Only include resources that match the filter in the response. + * @param {string} request.orderBy + * Optional. Specify how the results should be sorted. If not specified, the + * results will be sorted in the default order. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.cloud.kms.v1.ImportJob|ImportJob}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v1/key_management_service.list_import_jobs.js + * region_tag:cloudkms_v1_generated_KeyManagementService_ListImportJobs_async + */ listImportJobsAsync( - request?: protos.google.cloud.kms.v1.IListImportJobsRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.cloud.kms.v1.IListImportJobsRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); const defaultCallSettings = this._defaults['listImportJobs']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listImportJobs iterate %j', request); return this.descriptors.page.listImportJobs.asyncIterate( this.innerApiCalls['listImportJobs'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } -/** - * Gets the access control policy for a resource. Returns an empty policy - * if the resource exists and does not have a policy set. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.resource - * REQUIRED: The resource for which the policy is being requested. - * See the operation documentation for the appropriate value for this field. - * @param {Object} [request.options] - * OPTIONAL: A `GetPolicyOptions` object for specifying options to - * `GetIamPolicy`. This field is only used by Cloud IAM. - * - * This object should have the same structure as {@link google.iam.v1.GetPolicyOptions | GetPolicyOptions}. - * @param {Object} [options] - * Optional parameters. You can override the default settings for this call, e.g, timeout, - * retries, paginations, etc. See {@link https://googleapis.github.io/gax-nodejs/interfaces/CallOptions.html | gax.CallOptions} for the details. - * @param {function(?Error, ?Object)} [callback] - * The function which will be called with the result of the API call. - * - * The second parameter to the callback is an object representing {@link google.iam.v1.Policy | Policy}. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link google.iam.v1.Policy | Policy}. - * The promise has a method named "cancel" which cancels the ongoing API call. - */ + /** + * Gets the access control policy for a resource. Returns an empty policy + * if the resource exists and does not have a policy set. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.resource + * REQUIRED: The resource for which the policy is being requested. + * See the operation documentation for the appropriate value for this field. + * @param {Object} [request.options] + * OPTIONAL: A `GetPolicyOptions` object for specifying options to + * `GetIamPolicy`. This field is only used by Cloud IAM. + * + * This object should have the same structure as {@link google.iam.v1.GetPolicyOptions | GetPolicyOptions}. + * @param {Object} [options] + * Optional parameters. You can override the default settings for this call, e.g, timeout, + * retries, paginations, etc. See {@link https://googleapis.github.io/gax-nodejs/interfaces/CallOptions.html | gax.CallOptions} for the details. + * @param {function(?Error, ?Object)} [callback] + * The function which will be called with the result of the API call. + * + * The second parameter to the callback is an object representing {@link google.iam.v1.Policy | Policy}. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link google.iam.v1.Policy | Policy}. + * The promise has a method named "cancel" which cancels the ongoing API call. + */ getIamPolicy( request: IamProtos.google.iam.v1.GetIamPolicyRequest, options?: @@ -3218,40 +4059,40 @@ export class KeyManagementServiceClient { IamProtos.google.iam.v1.Policy, IamProtos.google.iam.v1.GetIamPolicyRequest | null | undefined, {} | null | undefined - > - ):Promise<[IamProtos.google.iam.v1.Policy]> { + >, + ): Promise<[IamProtos.google.iam.v1.Policy]> { return this.iamClient.getIamPolicy(request, options, callback); } -/** - * Returns permissions that a caller has on the specified resource. If the - * resource does not exist, this will return an empty set of - * permissions, not a NOT_FOUND error. - * - * Note: This operation is designed to be used for building - * permission-aware UIs and command-line tools, not for authorization - * checking. This operation may "fail open" without warning. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.resource - * REQUIRED: The resource for which the policy detail is being requested. - * See the operation documentation for the appropriate value for this field. - * @param {string[]} request.permissions - * The set of permissions to check for the `resource`. Permissions with - * wildcards (such as '*' or 'storage.*') are not allowed. For more - * information see {@link https://cloud.google.com/iam/docs/overview#permissions | IAM Overview }. - * @param {Object} [options] - * Optional parameters. You can override the default settings for this call, e.g, timeout, - * retries, paginations, etc. See {@link https://googleapis.github.io/gax-nodejs/interfaces/CallOptions.html | gax.CallOptions} for the details. - * @param {function(?Error, ?Object)} [callback] - * The function which will be called with the result of the API call. - * - * The second parameter to the callback is an object representing {@link google.iam.v1.TestIamPermissionsResponse | TestIamPermissionsResponse}. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link google.iam.v1.TestIamPermissionsResponse | TestIamPermissionsResponse}. - * The promise has a method named "cancel" which cancels the ongoing API call. - */ + /** + * Returns permissions that a caller has on the specified resource. If the + * resource does not exist, this will return an empty set of + * permissions, not a NOT_FOUND error. + * + * Note: This operation is designed to be used for building + * permission-aware UIs and command-line tools, not for authorization + * checking. This operation may "fail open" without warning. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.resource + * REQUIRED: The resource for which the policy detail is being requested. + * See the operation documentation for the appropriate value for this field. + * @param {string[]} request.permissions + * The set of permissions to check for the `resource`. Permissions with + * wildcards (such as '*' or 'storage.*') are not allowed. For more + * information see {@link https://cloud.google.com/iam/docs/overview#permissions | IAM Overview }. + * @param {Object} [options] + * Optional parameters. You can override the default settings for this call, e.g, timeout, + * retries, paginations, etc. See {@link https://googleapis.github.io/gax-nodejs/interfaces/CallOptions.html | gax.CallOptions} for the details. + * @param {function(?Error, ?Object)} [callback] + * The function which will be called with the result of the API call. + * + * The second parameter to the callback is an object representing {@link google.iam.v1.TestIamPermissionsResponse | TestIamPermissionsResponse}. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link google.iam.v1.TestIamPermissionsResponse | TestIamPermissionsResponse}. + * The promise has a method named "cancel" which cancels the ongoing API call. + */ setIamPolicy( request: IamProtos.google.iam.v1.SetIamPolicyRequest, options?: @@ -3265,41 +4106,41 @@ export class KeyManagementServiceClient { IamProtos.google.iam.v1.Policy, IamProtos.google.iam.v1.SetIamPolicyRequest | null | undefined, {} | null | undefined - > - ):Promise<[IamProtos.google.iam.v1.Policy]> { + >, + ): Promise<[IamProtos.google.iam.v1.Policy]> { return this.iamClient.setIamPolicy(request, options, callback); } -/** - * Returns permissions that a caller has on the specified resource. If the - * resource does not exist, this will return an empty set of - * permissions, not a NOT_FOUND error. - * - * Note: This operation is designed to be used for building - * permission-aware UIs and command-line tools, not for authorization - * checking. This operation may "fail open" without warning. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.resource - * REQUIRED: The resource for which the policy detail is being requested. - * See the operation documentation for the appropriate value for this field. - * @param {string[]} request.permissions - * The set of permissions to check for the `resource`. Permissions with - * wildcards (such as '*' or 'storage.*') are not allowed. For more - * information see {@link https://cloud.google.com/iam/docs/overview#permissions | IAM Overview }. - * @param {Object} [options] - * Optional parameters. You can override the default settings for this call, e.g, timeout, - * retries, paginations, etc. See {@link https://googleapis.github.io/gax-nodejs/interfaces/CallOptions.html | gax.CallOptions} for the details. - * @param {function(?Error, ?Object)} [callback] - * The function which will be called with the result of the API call. - * - * The second parameter to the callback is an object representing {@link google.iam.v1.TestIamPermissionsResponse | TestIamPermissionsResponse}. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link google.iam.v1.TestIamPermissionsResponse | TestIamPermissionsResponse}. - * The promise has a method named "cancel" which cancels the ongoing API call. - * - */ + /** + * Returns permissions that a caller has on the specified resource. If the + * resource does not exist, this will return an empty set of + * permissions, not a NOT_FOUND error. + * + * Note: This operation is designed to be used for building + * permission-aware UIs and command-line tools, not for authorization + * checking. This operation may "fail open" without warning. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.resource + * REQUIRED: The resource for which the policy detail is being requested. + * See the operation documentation for the appropriate value for this field. + * @param {string[]} request.permissions + * The set of permissions to check for the `resource`. Permissions with + * wildcards (such as '*' or 'storage.*') are not allowed. For more + * information see {@link https://cloud.google.com/iam/docs/overview#permissions | IAM Overview }. + * @param {Object} [options] + * Optional parameters. You can override the default settings for this call, e.g, timeout, + * retries, paginations, etc. See {@link https://googleapis.github.io/gax-nodejs/interfaces/CallOptions.html | gax.CallOptions} for the details. + * @param {function(?Error, ?Object)} [callback] + * The function which will be called with the result of the API call. + * + * The second parameter to the callback is an object representing {@link google.iam.v1.TestIamPermissionsResponse | TestIamPermissionsResponse}. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link google.iam.v1.TestIamPermissionsResponse | TestIamPermissionsResponse}. + * The promise has a method named "cancel" which cancels the ongoing API call. + * + */ testIamPermissions( request: IamProtos.google.iam.v1.TestIamPermissionsRequest, options?: @@ -3313,12 +4154,11 @@ export class KeyManagementServiceClient { IamProtos.google.iam.v1.TestIamPermissionsResponse, IamProtos.google.iam.v1.TestIamPermissionsRequest | null | undefined, {} | null | undefined - > - ):Promise<[IamProtos.google.iam.v1.TestIamPermissionsResponse]> { + >, + ): Promise<[IamProtos.google.iam.v1.TestIamPermissionsResponse]> { return this.iamClient.testIamPermissions(request, options, callback); } - /** * Terminate the gRPC channel and close the client. * @@ -3327,13 +4167,15 @@ export class KeyManagementServiceClient { */ close(): Promise { if (this.keyManagementServiceStub && !this._terminated) { - return this.keyManagementServiceStub.then(stub => { + return this.keyManagementServiceStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); - this.iamClient.close().catch(err => {throw err}); + this.iamClient.close().catch((err) => { + throw err; + }); }); } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/core/generator/gapic-generator-typescript/baselines/kms-esm/esm/system-test/fixtures/sample/src/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/kms-esm/esm/system-test/fixtures/sample/src/index.ts.baseline index 8c695e4b03b2..a327ebc55d56 100644 --- a/core/generator/gapic-generator-typescript/baselines/kms-esm/esm/system-test/fixtures/sample/src/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/kms-esm/esm/system-test/fixtures/sample/src/index.ts.baseline @@ -17,10 +17,12 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -import {KeyManagementServiceClient} from 'kms'; +import { KeyManagementServiceClient } from 'kms'; // check that the client class type name can be used -function doStuffWithKeyManagementServiceClient(client: KeyManagementServiceClient) { +function doStuffWithKeyManagementServiceClient( + client: KeyManagementServiceClient, +) { client.close(); } diff --git a/core/generator/gapic-generator-typescript/baselines/kms-esm/esm/system-test/install.ts.baseline b/core/generator/gapic-generator-typescript/baselines/kms-esm/esm/system-test/install.ts.baseline index e079c4fa1101..d109fdd8c97f 100644 --- a/core/generator/gapic-generator-typescript/baselines/kms-esm/esm/system-test/install.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/kms-esm/esm/system-test/install.ts.baseline @@ -16,40 +16,45 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -import {packNTest} from 'pack-n-play'; -import {readFileSync} from 'fs'; -import {describe, it} from 'mocha'; +import { packNTest } from 'pack-n-play'; +import { readFileSync } from 'fs'; +import { describe, it } from 'mocha'; describe('📦 pack-n-play test', () => { - it('TypeScript', async function() { + it('TypeScript', async function () { this.timeout(300000); await packNTest({ packageDir: process.cwd(), sample: { description: 'TypeScript user can use the type definitions', - ts: readFileSync('./esm/system-test/fixtures/sample/src/index.ts').toString() - } + ts: readFileSync( + './esm/system-test/fixtures/sample/src/index.ts', + ).toString(), + }, }); }); - it('ESM module', async function() { + it('ESM module', async function () { this.timeout(300000); await packNTest({ sample: { description: 'Should be able to import using ESM', - esm: readFileSync('./esm/system-test/fixtures/sample/src/index.js').toString(), + esm: readFileSync( + './esm/system-test/fixtures/sample/src/index.js', + ).toString(), }, }); }); - it('CJS module', async function() { + it('CJS module', async function () { this.timeout(300000); await packNTest({ sample: { description: 'Should be able to import using CJS', - cjs: readFileSync('./esm/system-test/fixtures/sample/src/index.cjs').toString(), + cjs: readFileSync( + './esm/system-test/fixtures/sample/src/index.cjs', + ).toString(), }, }); }); - }); diff --git a/core/generator/gapic-generator-typescript/baselines/kms-esm/esm/test/gapic_key_management_service_v1.ts.baseline b/core/generator/gapic-generator-typescript/baselines/kms-esm/esm/test/gapic_key_management_service_v1.ts.baseline index a70096f09c23..b7ee642a4f5c 100644 --- a/core/generator/gapic-generator-typescript/baselines/kms-esm/esm/test/gapic_key_management_service_v1.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/kms-esm/esm/test/gapic_key_management_service_v1.ts.baseline @@ -20,16 +20,16 @@ import * as protos from '../../protos/protos.js'; import assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as keymanagementserviceModule from '../src/index.js'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; -import {protobuf, IamProtos} from 'google-gax'; +import { protobuf, IamProtos } from 'google-gax'; import fs from 'fs'; import path from 'path'; -import {fileURLToPath} from 'url'; +import { fileURLToPath } from 'url'; // @ts-ignore const dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -37,3550 +37,4546 @@ const dirname = path.dirname(fileURLToPath(import.meta.url)); // to fill in default values for request objects const root = protobuf.Root.fromJSON( JSON.parse( - fs.readFileSync(path.join(dirname, '..', '..', 'protos/protos.json'), 'utf8') - )) + fs.readFileSync( + path.join(dirname, '..', '..', 'protos/protos.json'), + 'utf8', + ), + ), +); // eslint-disable-next-line @typescript-eslint/no-unused-vars function getTypeDefaultValue(typeName: string, fields: string[]) { - let type = root.lookupType(typeName) as protobuf.Type; - for (const field of fields.slice(0, -1)) { - type = type?.fields[field]?.resolvedType as protobuf.Type; - } - return type?.fields[fields[fields.length - 1]]?.defaultValue ?? null; + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type?.fields[field]?.resolvedType as protobuf.Type; + } + return type?.fields[fields[fields.length - 1]]?.defaultValue ?? null; } function generateSampleMessage(instance: T) { - const filledObject = (instance.constructor as typeof protobuf.Message) - .toObject(instance as protobuf.Message, {defaults: true}); - return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, { defaults: true }); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; } function stubSimpleCall(response?: ResponseType, error?: Error) { - return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); } -function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { - return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +function stubSimpleCallWithCallback( + response?: ResponseType, + error?: Error, +) { + return error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); } -function stubPageStreamingCall(responses?: ResponseType[], error?: Error) { - const pagingStub = sinon.stub(); - if (responses) { - for (let i = 0; i < responses.length; ++i) { - pagingStub.onCall(i).callsArgWith(2, null, responses[i]); - } +function stubPageStreamingCall( + responses?: ResponseType[], + error?: Error, +) { + const pagingStub = sinon.stub(); + if (responses) { + for (let i = 0; i < responses.length; ++i) { + pagingStub.onCall(i).callsArgWith(2, null, responses[i]); } - const transformStub = error ? sinon.stub().callsArgWith(2, error) : pagingStub; - const mockStream = new PassThrough({ - objectMode: true, - transform: transformStub, - }); - // trigger as many responses as needed - if (responses) { - for (let i = 0; i < responses.length; ++i) { - setImmediate(() => { mockStream.write({}); }); - } - setImmediate(() => { mockStream.end(); }); - } else { - setImmediate(() => { mockStream.write({}); }); - setImmediate(() => { mockStream.end(); }); + } + const transformStub = error + ? sinon.stub().callsArgWith(2, error) + : pagingStub; + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + // trigger as many responses as needed + if (responses) { + for (let i = 0; i < responses.length; ++i) { + setImmediate(() => { + mockStream.write({}); + }); } - return sinon.stub().returns(mockStream); + setImmediate(() => { + mockStream.end(); + }); + } else { + setImmediate(() => { + mockStream.write({}); + }); + setImmediate(() => { + mockStream.end(); + }); + } + return sinon.stub().returns(mockStream); } -function stubAsyncIterationCall(responses?: ResponseType[], error?: Error) { - let counter = 0; - const asyncIterable = { - [Symbol.asyncIterator]() { - return { - async next() { - if (error) { - return Promise.reject(error); - } - if (counter >= responses!.length) { - return Promise.resolve({done: true, value: undefined}); - } - return Promise.resolve({done: false, value: responses![counter++]}); - } - }; - } - }; - return sinon.stub().returns(asyncIterable); +function stubAsyncIterationCall( + responses?: ResponseType[], + error?: Error, +) { + let counter = 0; + const asyncIterable = { + [Symbol.asyncIterator]() { + return { + async next() { + if (error) { + return Promise.reject(error); + } + if (counter >= responses!.length) { + return Promise.resolve({ done: true, value: undefined }); + } + return Promise.resolve({ done: false, value: responses![counter++] }); + }, + }; + }, + }; + return sinon.stub().returns(asyncIterable); } describe('v1.KeyManagementServiceClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'cloudkms.googleapis.com'); - }); - - it('has universeDomain', () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); - - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - it('throws DeprecationWarning if static servicePath is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const servicePath = keymanagementserviceModule.v1.KeyManagementServiceClient.servicePath; - assert.strictEqual(servicePath, 'cloudkms.googleapis.com'); - assert(stub.called); - stub.restore(); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'cloudkms.googleapis.com'); + }); - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = keymanagementserviceModule.v1.KeyManagementServiceClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'cloudkms.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'cloudkms.example.com'); - }); - - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'cloudkms.example.com'); - }); - - if (typeof process === 'object' && 'env' in process) { - describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { - it('sets apiEndpoint from environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'cloudkms.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - - it('value configured in code has priority over environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'cloudkms.configured.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { new keymanagementserviceModule.v1.KeyManagementServiceClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); + it('has universeDomain', () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); + + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = + keymanagementserviceModule.v1.KeyManagementServiceClient.servicePath; + assert.strictEqual(servicePath, 'cloudkms.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + keymanagementserviceModule.v1.KeyManagementServiceClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'cloudkms.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + universeDomain: 'example.com', }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'cloudkms.example.com'); + }); - it('has port', () => { - const port = keymanagementserviceModule.v1.KeyManagementServiceClient.port; - assert(port); - assert(typeof port === 'number'); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + universe_domain: 'example.com', }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'cloudkms.example.com'); + }); - it('should create a client with no option', () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient(); - assert(client); + if (typeof process === 'object' && 'env' in process) { + describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { + it('sets apiEndpoint from environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'cloudkms.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - it('should create a client with gRPC fallback', () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - fallback: true, - }); - assert(client); + it('value configured in code has priority over environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + universeDomain: 'configured.example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'cloudkms.configured.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } + }); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); + }); - it('has initialize method and supports deferred initialization', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.keyManagementServiceStub, undefined); - await client.initialize(); - assert(client.keyManagementServiceStub); + it('has port', () => { + const port = + keymanagementserviceModule.v1.KeyManagementServiceClient.port; + assert(port); + assert(typeof port === 'number'); + }); + + it('should create a client with no option', () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient(); + assert(client); + }); + + it('should create a client with gRPC fallback', () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + fallback: true, }); + assert(client); + }); - it('has close method for the initialized client', done => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.keyManagementServiceStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); + it('has initialize method and supports deferred initialization', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + assert.strictEqual(client.keyManagementServiceStub, undefined); + await client.initialize(); + assert(client.keyManagementServiceStub); + }); - it('has close method for the non-initialized client', done => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.keyManagementServiceStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); + it('has close method for the initialized client', (done) => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.keyManagementServiceStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + it('has close method for the non-initialized client', (done) => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + assert.strictEqual(client.keyManagementServiceStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; + }); + }); - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId((err?: Error|null, projectId?: string|null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } - }); - }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); }); - describe('getKeyRing', () => { - it('invokes getKeyRing without error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.GetKeyRingRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.GetKeyRingRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.kms.v1.KeyRing() - ); - client.innerApiCalls.getKeyRing = stubSimpleCall(expectedResponse); - const [response] = await client.getKeyRing(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getKeyRing as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getKeyRing as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getKeyRing without error using callback', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.GetKeyRingRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.GetKeyRingRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.kms.v1.KeyRing() - ); - client.innerApiCalls.getKeyRing = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getKeyRing( - request, - (err?: Error|null, result?: protos.google.cloud.kms.v1.IKeyRing|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getKeyRing as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getKeyRing as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getKeyRing with error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.GetKeyRingRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.GetKeyRingRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getKeyRing = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getKeyRing(request), expectedError); - const actualRequest = (client.innerApiCalls.getKeyRing as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getKeyRing as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getKeyRing with closed client', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.GetKeyRingRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.GetKeyRingRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getKeyRing(request), expectedError); - }); - }); - - describe('getCryptoKey', () => { - it('invokes getCryptoKey without error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.GetCryptoKeyRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.GetCryptoKeyRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.kms.v1.CryptoKey() - ); - client.innerApiCalls.getCryptoKey = stubSimpleCall(expectedResponse); - const [response] = await client.getCryptoKey(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getCryptoKey as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getCryptoKey as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getCryptoKey without error using callback', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.GetCryptoKeyRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.GetCryptoKeyRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.kms.v1.CryptoKey() - ); - client.innerApiCalls.getCryptoKey = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getCryptoKey( - request, - (err?: Error|null, result?: protos.google.cloud.kms.v1.ICryptoKey|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getCryptoKey as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getCryptoKey as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getCryptoKey with error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.GetCryptoKeyRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.GetCryptoKeyRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getCryptoKey = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getCryptoKey(request), expectedError); - const actualRequest = (client.innerApiCalls.getCryptoKey as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getCryptoKey as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getCryptoKey with closed client', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.GetCryptoKeyRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.GetCryptoKeyRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getCryptoKey(request), expectedError); - }); - }); - - describe('getCryptoKeyVersion', () => { - it('invokes getCryptoKeyVersion without error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.GetCryptoKeyVersionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.GetCryptoKeyVersionRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.kms.v1.CryptoKeyVersion() - ); - client.innerApiCalls.getCryptoKeyVersion = stubSimpleCall(expectedResponse); - const [response] = await client.getCryptoKeyVersion(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getCryptoKeyVersion as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getCryptoKeyVersion as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getCryptoKeyVersion without error using callback', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.GetCryptoKeyVersionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.GetCryptoKeyVersionRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.kms.v1.CryptoKeyVersion() - ); - client.innerApiCalls.getCryptoKeyVersion = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getCryptoKeyVersion( - request, - (err?: Error|null, result?: protos.google.cloud.kms.v1.ICryptoKeyVersion|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getCryptoKeyVersion as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getCryptoKeyVersion as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getCryptoKeyVersion with error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.GetCryptoKeyVersionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.GetCryptoKeyVersionRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getCryptoKeyVersion = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getCryptoKeyVersion(request), expectedError); - const actualRequest = (client.innerApiCalls.getCryptoKeyVersion as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getCryptoKeyVersion as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getCryptoKeyVersion with closed client', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.GetCryptoKeyVersionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.GetCryptoKeyVersionRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getCryptoKeyVersion(request), expectedError); - }); - }); - - describe('getPublicKey', () => { - it('invokes getPublicKey without error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.GetPublicKeyRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.GetPublicKeyRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.kms.v1.PublicKey() - ); - client.innerApiCalls.getPublicKey = stubSimpleCall(expectedResponse); - const [response] = await client.getPublicKey(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getPublicKey as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getPublicKey as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getPublicKey without error using callback', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.GetPublicKeyRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.GetPublicKeyRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.kms.v1.PublicKey() - ); - client.innerApiCalls.getPublicKey = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getPublicKey( - request, - (err?: Error|null, result?: protos.google.cloud.kms.v1.IPublicKey|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getPublicKey as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getPublicKey as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getPublicKey with error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.GetPublicKeyRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.GetPublicKeyRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getPublicKey = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getPublicKey(request), expectedError); - const actualRequest = (client.innerApiCalls.getPublicKey as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getPublicKey as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getPublicKey with closed client', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.GetPublicKeyRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.GetPublicKeyRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getPublicKey(request), expectedError); - }); - }); - - describe('getImportJob', () => { - it('invokes getImportJob without error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.GetImportJobRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.GetImportJobRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.kms.v1.ImportJob() - ); - client.innerApiCalls.getImportJob = stubSimpleCall(expectedResponse); - const [response] = await client.getImportJob(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getImportJob as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getImportJob as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getImportJob without error using callback', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.GetImportJobRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.GetImportJobRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.kms.v1.ImportJob() - ); - client.innerApiCalls.getImportJob = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getImportJob( - request, - (err?: Error|null, result?: protos.google.cloud.kms.v1.IImportJob|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getImportJob as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getImportJob as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getImportJob with error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.GetImportJobRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.GetImportJobRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getImportJob = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getImportJob(request), expectedError); - const actualRequest = (client.innerApiCalls.getImportJob as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getImportJob as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getImportJob with closed client', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.GetImportJobRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.GetImportJobRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getImportJob(request), expectedError); - }); - }); - - describe('createKeyRing', () => { - it('invokes createKeyRing without error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.CreateKeyRingRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.CreateKeyRingRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.kms.v1.KeyRing() - ); - client.innerApiCalls.createKeyRing = stubSimpleCall(expectedResponse); - const [response] = await client.createKeyRing(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createKeyRing as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createKeyRing as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createKeyRing without error using callback', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.CreateKeyRingRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.CreateKeyRingRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.kms.v1.KeyRing() - ); - client.innerApiCalls.createKeyRing = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createKeyRing( - request, - (err?: Error|null, result?: protos.google.cloud.kms.v1.IKeyRing|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createKeyRing as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createKeyRing as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createKeyRing with error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.CreateKeyRingRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.CreateKeyRingRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createKeyRing = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createKeyRing(request), expectedError); - const actualRequest = (client.innerApiCalls.createKeyRing as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createKeyRing as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createKeyRing with closed client', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.CreateKeyRingRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.CreateKeyRingRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createKeyRing(request), expectedError); - }); - }); - - describe('createCryptoKey', () => { - it('invokes createCryptoKey without error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.CreateCryptoKeyRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.CreateCryptoKeyRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.kms.v1.CryptoKey() - ); - client.innerApiCalls.createCryptoKey = stubSimpleCall(expectedResponse); - const [response] = await client.createCryptoKey(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createCryptoKey as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createCryptoKey as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createCryptoKey without error using callback', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.CreateCryptoKeyRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.CreateCryptoKeyRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.kms.v1.CryptoKey() - ); - client.innerApiCalls.createCryptoKey = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createCryptoKey( - request, - (err?: Error|null, result?: protos.google.cloud.kms.v1.ICryptoKey|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createCryptoKey as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createCryptoKey as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createCryptoKey with error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.CreateCryptoKeyRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.CreateCryptoKeyRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createCryptoKey = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createCryptoKey(request), expectedError); - const actualRequest = (client.innerApiCalls.createCryptoKey as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createCryptoKey as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createCryptoKey with closed client', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.CreateCryptoKeyRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.CreateCryptoKeyRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createCryptoKey(request), expectedError); - }); - }); - - describe('createCryptoKeyVersion', () => { - it('invokes createCryptoKeyVersion without error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.CreateCryptoKeyVersionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.CreateCryptoKeyVersionRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.kms.v1.CryptoKeyVersion() - ); - client.innerApiCalls.createCryptoKeyVersion = stubSimpleCall(expectedResponse); - const [response] = await client.createCryptoKeyVersion(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createCryptoKeyVersion as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createCryptoKeyVersion as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createCryptoKeyVersion without error using callback', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.CreateCryptoKeyVersionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.CreateCryptoKeyVersionRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.kms.v1.CryptoKeyVersion() - ); - client.innerApiCalls.createCryptoKeyVersion = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createCryptoKeyVersion( - request, - (err?: Error|null, result?: protos.google.cloud.kms.v1.ICryptoKeyVersion|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createCryptoKeyVersion as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createCryptoKeyVersion as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createCryptoKeyVersion with error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.CreateCryptoKeyVersionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.CreateCryptoKeyVersionRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createCryptoKeyVersion = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createCryptoKeyVersion(request), expectedError); - const actualRequest = (client.innerApiCalls.createCryptoKeyVersion as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createCryptoKeyVersion as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createCryptoKeyVersion with closed client', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.CreateCryptoKeyVersionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.CreateCryptoKeyVersionRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createCryptoKeyVersion(request), expectedError); - }); - }); - - describe('importCryptoKeyVersion', () => { - it('invokes importCryptoKeyVersion without error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.ImportCryptoKeyVersionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.ImportCryptoKeyVersionRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.kms.v1.CryptoKeyVersion() - ); - client.innerApiCalls.importCryptoKeyVersion = stubSimpleCall(expectedResponse); - const [response] = await client.importCryptoKeyVersion(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.importCryptoKeyVersion as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.importCryptoKeyVersion as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes importCryptoKeyVersion without error using callback', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.ImportCryptoKeyVersionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.ImportCryptoKeyVersionRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.kms.v1.CryptoKeyVersion() - ); - client.innerApiCalls.importCryptoKeyVersion = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.importCryptoKeyVersion( - request, - (err?: Error|null, result?: protos.google.cloud.kms.v1.ICryptoKeyVersion|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.importCryptoKeyVersion as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.importCryptoKeyVersion as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes importCryptoKeyVersion with error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.ImportCryptoKeyVersionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.ImportCryptoKeyVersionRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.importCryptoKeyVersion = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.importCryptoKeyVersion(request), expectedError); - const actualRequest = (client.innerApiCalls.importCryptoKeyVersion as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.importCryptoKeyVersion as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes importCryptoKeyVersion with closed client', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.ImportCryptoKeyVersionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.ImportCryptoKeyVersionRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.importCryptoKeyVersion(request), expectedError); - }); - }); - - describe('createImportJob', () => { - it('invokes createImportJob without error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.CreateImportJobRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.CreateImportJobRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.kms.v1.ImportJob() - ); - client.innerApiCalls.createImportJob = stubSimpleCall(expectedResponse); - const [response] = await client.createImportJob(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createImportJob as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createImportJob as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createImportJob without error using callback', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.CreateImportJobRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.CreateImportJobRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.kms.v1.ImportJob() - ); - client.innerApiCalls.createImportJob = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createImportJob( - request, - (err?: Error|null, result?: protos.google.cloud.kms.v1.IImportJob|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createImportJob as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createImportJob as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createImportJob with error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.CreateImportJobRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.CreateImportJobRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createImportJob = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createImportJob(request), expectedError); - const actualRequest = (client.innerApiCalls.createImportJob as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createImportJob as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createImportJob with closed client', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.CreateImportJobRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.CreateImportJobRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createImportJob(request), expectedError); - }); - }); - - describe('updateCryptoKey', () => { - it('invokes updateCryptoKey without error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.UpdateCryptoKeyRequest() - ); - request.cryptoKey ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.UpdateCryptoKeyRequest', ['cryptoKey', 'name']); - request.cryptoKey.name = defaultValue1; - const expectedHeaderRequestParams = `crypto_key.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.kms.v1.CryptoKey() - ); - client.innerApiCalls.updateCryptoKey = stubSimpleCall(expectedResponse); - const [response] = await client.updateCryptoKey(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateCryptoKey as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateCryptoKey as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateCryptoKey without error using callback', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.UpdateCryptoKeyRequest() - ); - request.cryptoKey ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.UpdateCryptoKeyRequest', ['cryptoKey', 'name']); - request.cryptoKey.name = defaultValue1; - const expectedHeaderRequestParams = `crypto_key.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.kms.v1.CryptoKey() - ); - client.innerApiCalls.updateCryptoKey = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateCryptoKey( - request, - (err?: Error|null, result?: protos.google.cloud.kms.v1.ICryptoKey|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateCryptoKey as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateCryptoKey as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateCryptoKey with error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.UpdateCryptoKeyRequest() - ); - request.cryptoKey ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.UpdateCryptoKeyRequest', ['cryptoKey', 'name']); - request.cryptoKey.name = defaultValue1; - const expectedHeaderRequestParams = `crypto_key.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateCryptoKey = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateCryptoKey(request), expectedError); - const actualRequest = (client.innerApiCalls.updateCryptoKey as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateCryptoKey as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateCryptoKey with closed client', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.UpdateCryptoKeyRequest() - ); - request.cryptoKey ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.UpdateCryptoKeyRequest', ['cryptoKey', 'name']); - request.cryptoKey.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateCryptoKey(request), expectedError); - }); - }); - - describe('updateCryptoKeyVersion', () => { - it('invokes updateCryptoKeyVersion without error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.UpdateCryptoKeyVersionRequest() - ); - request.cryptoKeyVersion ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.UpdateCryptoKeyVersionRequest', ['cryptoKeyVersion', 'name']); - request.cryptoKeyVersion.name = defaultValue1; - const expectedHeaderRequestParams = `crypto_key_version.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.kms.v1.CryptoKeyVersion() - ); - client.innerApiCalls.updateCryptoKeyVersion = stubSimpleCall(expectedResponse); - const [response] = await client.updateCryptoKeyVersion(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateCryptoKeyVersion as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateCryptoKeyVersion as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateCryptoKeyVersion without error using callback', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.UpdateCryptoKeyVersionRequest() - ); - request.cryptoKeyVersion ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.UpdateCryptoKeyVersionRequest', ['cryptoKeyVersion', 'name']); - request.cryptoKeyVersion.name = defaultValue1; - const expectedHeaderRequestParams = `crypto_key_version.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.kms.v1.CryptoKeyVersion() - ); - client.innerApiCalls.updateCryptoKeyVersion = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateCryptoKeyVersion( - request, - (err?: Error|null, result?: protos.google.cloud.kms.v1.ICryptoKeyVersion|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateCryptoKeyVersion as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateCryptoKeyVersion as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateCryptoKeyVersion with error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.UpdateCryptoKeyVersionRequest() - ); - request.cryptoKeyVersion ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.UpdateCryptoKeyVersionRequest', ['cryptoKeyVersion', 'name']); - request.cryptoKeyVersion.name = defaultValue1; - const expectedHeaderRequestParams = `crypto_key_version.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateCryptoKeyVersion = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateCryptoKeyVersion(request), expectedError); - const actualRequest = (client.innerApiCalls.updateCryptoKeyVersion as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateCryptoKeyVersion as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateCryptoKeyVersion with closed client', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.UpdateCryptoKeyVersionRequest() - ); - request.cryptoKeyVersion ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.UpdateCryptoKeyVersionRequest', ['cryptoKeyVersion', 'name']); - request.cryptoKeyVersion.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateCryptoKeyVersion(request), expectedError); - }); - }); - - describe('encrypt', () => { - it('invokes encrypt without error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.EncryptRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.EncryptRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.kms.v1.EncryptResponse() - ); - client.innerApiCalls.encrypt = stubSimpleCall(expectedResponse); - const [response] = await client.encrypt(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.encrypt as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.encrypt as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes encrypt without error using callback', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.EncryptRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.EncryptRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.kms.v1.EncryptResponse() - ); - client.innerApiCalls.encrypt = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.encrypt( - request, - (err?: Error|null, result?: protos.google.cloud.kms.v1.IEncryptResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.encrypt as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.encrypt as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes encrypt with error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.EncryptRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.EncryptRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.encrypt = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.encrypt(request), expectedError); - const actualRequest = (client.innerApiCalls.encrypt as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.encrypt as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes encrypt with closed client', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.EncryptRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.EncryptRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.encrypt(request), expectedError); - }); - }); - - describe('decrypt', () => { - it('invokes decrypt without error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.DecryptRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.DecryptRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.kms.v1.DecryptResponse() - ); - client.innerApiCalls.decrypt = stubSimpleCall(expectedResponse); - const [response] = await client.decrypt(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.decrypt as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.decrypt as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes decrypt without error using callback', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.DecryptRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.DecryptRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.kms.v1.DecryptResponse() - ); - client.innerApiCalls.decrypt = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.decrypt( - request, - (err?: Error|null, result?: protos.google.cloud.kms.v1.IDecryptResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.decrypt as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.decrypt as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes decrypt with error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.DecryptRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.DecryptRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.decrypt = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.decrypt(request), expectedError); - const actualRequest = (client.innerApiCalls.decrypt as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.decrypt as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes decrypt with closed client', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.DecryptRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.DecryptRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.decrypt(request), expectedError); - }); - }); - - describe('asymmetricSign', () => { - it('invokes asymmetricSign without error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.AsymmetricSignRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.AsymmetricSignRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.kms.v1.AsymmetricSignResponse() - ); - client.innerApiCalls.asymmetricSign = stubSimpleCall(expectedResponse); - const [response] = await client.asymmetricSign(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.asymmetricSign as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.asymmetricSign as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes asymmetricSign without error using callback', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.AsymmetricSignRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.AsymmetricSignRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.kms.v1.AsymmetricSignResponse() - ); - client.innerApiCalls.asymmetricSign = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.asymmetricSign( - request, - (err?: Error|null, result?: protos.google.cloud.kms.v1.IAsymmetricSignResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.asymmetricSign as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.asymmetricSign as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes asymmetricSign with error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.AsymmetricSignRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.AsymmetricSignRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.asymmetricSign = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.asymmetricSign(request), expectedError); - const actualRequest = (client.innerApiCalls.asymmetricSign as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.asymmetricSign as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes asymmetricSign with closed client', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.AsymmetricSignRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.AsymmetricSignRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.asymmetricSign(request), expectedError); - }); - }); - - describe('asymmetricDecrypt', () => { - it('invokes asymmetricDecrypt without error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.AsymmetricDecryptRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.AsymmetricDecryptRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.kms.v1.AsymmetricDecryptResponse() - ); - client.innerApiCalls.asymmetricDecrypt = stubSimpleCall(expectedResponse); - const [response] = await client.asymmetricDecrypt(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.asymmetricDecrypt as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.asymmetricDecrypt as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes asymmetricDecrypt without error using callback', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.AsymmetricDecryptRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.AsymmetricDecryptRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.kms.v1.AsymmetricDecryptResponse() - ); - client.innerApiCalls.asymmetricDecrypt = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.asymmetricDecrypt( - request, - (err?: Error|null, result?: protos.google.cloud.kms.v1.IAsymmetricDecryptResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.asymmetricDecrypt as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.asymmetricDecrypt as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes asymmetricDecrypt with error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.AsymmetricDecryptRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.AsymmetricDecryptRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.asymmetricDecrypt = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.asymmetricDecrypt(request), expectedError); - const actualRequest = (client.innerApiCalls.asymmetricDecrypt as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.asymmetricDecrypt as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes asymmetricDecrypt with closed client', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.AsymmetricDecryptRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.AsymmetricDecryptRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.asymmetricDecrypt(request), expectedError); - }); - }); - - describe('updateCryptoKeyPrimaryVersion', () => { - it('invokes updateCryptoKeyPrimaryVersion without error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.UpdateCryptoKeyPrimaryVersionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.UpdateCryptoKeyPrimaryVersionRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.kms.v1.CryptoKey() - ); - client.innerApiCalls.updateCryptoKeyPrimaryVersion = stubSimpleCall(expectedResponse); - const [response] = await client.updateCryptoKeyPrimaryVersion(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateCryptoKeyPrimaryVersion as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateCryptoKeyPrimaryVersion as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateCryptoKeyPrimaryVersion without error using callback', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.UpdateCryptoKeyPrimaryVersionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.UpdateCryptoKeyPrimaryVersionRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.kms.v1.CryptoKey() - ); - client.innerApiCalls.updateCryptoKeyPrimaryVersion = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateCryptoKeyPrimaryVersion( - request, - (err?: Error|null, result?: protos.google.cloud.kms.v1.ICryptoKey|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateCryptoKeyPrimaryVersion as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateCryptoKeyPrimaryVersion as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateCryptoKeyPrimaryVersion with error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.UpdateCryptoKeyPrimaryVersionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.UpdateCryptoKeyPrimaryVersionRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateCryptoKeyPrimaryVersion = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateCryptoKeyPrimaryVersion(request), expectedError); - const actualRequest = (client.innerApiCalls.updateCryptoKeyPrimaryVersion as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateCryptoKeyPrimaryVersion as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateCryptoKeyPrimaryVersion with closed client', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.UpdateCryptoKeyPrimaryVersionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.UpdateCryptoKeyPrimaryVersionRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateCryptoKeyPrimaryVersion(request), expectedError); - }); - }); - - describe('destroyCryptoKeyVersion', () => { - it('invokes destroyCryptoKeyVersion without error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.DestroyCryptoKeyVersionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.DestroyCryptoKeyVersionRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.kms.v1.CryptoKeyVersion() - ); - client.innerApiCalls.destroyCryptoKeyVersion = stubSimpleCall(expectedResponse); - const [response] = await client.destroyCryptoKeyVersion(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.destroyCryptoKeyVersion as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.destroyCryptoKeyVersion as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes destroyCryptoKeyVersion without error using callback', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.DestroyCryptoKeyVersionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.DestroyCryptoKeyVersionRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.kms.v1.CryptoKeyVersion() - ); - client.innerApiCalls.destroyCryptoKeyVersion = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.destroyCryptoKeyVersion( - request, - (err?: Error|null, result?: protos.google.cloud.kms.v1.ICryptoKeyVersion|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.destroyCryptoKeyVersion as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.destroyCryptoKeyVersion as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes destroyCryptoKeyVersion with error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.DestroyCryptoKeyVersionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.DestroyCryptoKeyVersionRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.destroyCryptoKeyVersion = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.destroyCryptoKeyVersion(request), expectedError); - const actualRequest = (client.innerApiCalls.destroyCryptoKeyVersion as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.destroyCryptoKeyVersion as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes destroyCryptoKeyVersion with closed client', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.DestroyCryptoKeyVersionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.DestroyCryptoKeyVersionRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.destroyCryptoKeyVersion(request), expectedError); - }); - }); - - describe('restoreCryptoKeyVersion', () => { - it('invokes restoreCryptoKeyVersion without error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.RestoreCryptoKeyVersionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.RestoreCryptoKeyVersionRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.kms.v1.CryptoKeyVersion() - ); - client.innerApiCalls.restoreCryptoKeyVersion = stubSimpleCall(expectedResponse); - const [response] = await client.restoreCryptoKeyVersion(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.restoreCryptoKeyVersion as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.restoreCryptoKeyVersion as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes restoreCryptoKeyVersion without error using callback', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.RestoreCryptoKeyVersionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.RestoreCryptoKeyVersionRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.kms.v1.CryptoKeyVersion() - ); - client.innerApiCalls.restoreCryptoKeyVersion = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.restoreCryptoKeyVersion( - request, - (err?: Error|null, result?: protos.google.cloud.kms.v1.ICryptoKeyVersion|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.restoreCryptoKeyVersion as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.restoreCryptoKeyVersion as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes restoreCryptoKeyVersion with error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.RestoreCryptoKeyVersionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.RestoreCryptoKeyVersionRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.restoreCryptoKeyVersion = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.restoreCryptoKeyVersion(request), expectedError); - const actualRequest = (client.innerApiCalls.restoreCryptoKeyVersion as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.restoreCryptoKeyVersion as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes restoreCryptoKeyVersion with closed client', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.RestoreCryptoKeyVersionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.RestoreCryptoKeyVersionRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.restoreCryptoKeyVersion(request), expectedError); - }); - }); - - describe('listKeyRings', () => { - it('invokes listKeyRings without error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.ListKeyRingsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.ListKeyRingsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.kms.v1.KeyRing()), - generateSampleMessage(new protos.google.cloud.kms.v1.KeyRing()), - generateSampleMessage(new protos.google.cloud.kms.v1.KeyRing()), - ]; - client.innerApiCalls.listKeyRings = stubSimpleCall(expectedResponse); - const [response] = await client.listKeyRings(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listKeyRings as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listKeyRings as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listKeyRings without error using callback', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.ListKeyRingsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.ListKeyRingsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.kms.v1.KeyRing()), - generateSampleMessage(new protos.google.cloud.kms.v1.KeyRing()), - generateSampleMessage(new protos.google.cloud.kms.v1.KeyRing()), - ]; - client.innerApiCalls.listKeyRings = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listKeyRings( - request, - (err?: Error|null, result?: protos.google.cloud.kms.v1.IKeyRing[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listKeyRings as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listKeyRings as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listKeyRings with error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.ListKeyRingsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.ListKeyRingsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listKeyRings = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listKeyRings(request), expectedError); - const actualRequest = (client.innerApiCalls.listKeyRings as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listKeyRings as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listKeyRingsStream without error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.ListKeyRingsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.ListKeyRingsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.kms.v1.KeyRing()), - generateSampleMessage(new protos.google.cloud.kms.v1.KeyRing()), - generateSampleMessage(new protos.google.cloud.kms.v1.KeyRing()), - ]; - client.descriptors.page.listKeyRings.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listKeyRingsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.cloud.kms.v1.KeyRing[] = []; - stream.on('data', (response: protos.google.cloud.kms.v1.KeyRing) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.listKeyRings.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listKeyRings, request)); - assert( - (client.descriptors.page.listKeyRings.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); - - it('invokes listKeyRingsStream with error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.ListKeyRingsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.ListKeyRingsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listKeyRings.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listKeyRingsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.cloud.kms.v1.KeyRing[] = []; - stream.on('data', (response: protos.google.cloud.kms.v1.KeyRing) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listKeyRings.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listKeyRings, request)); - assert( - (client.descriptors.page.listKeyRings.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); - - it('uses async iteration with listKeyRings without error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.ListKeyRingsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.ListKeyRingsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.kms.v1.KeyRing()), - generateSampleMessage(new protos.google.cloud.kms.v1.KeyRing()), - generateSampleMessage(new protos.google.cloud.kms.v1.KeyRing()), - ]; - client.descriptors.page.listKeyRings.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.cloud.kms.v1.IKeyRing[] = []; - const iterable = client.listKeyRingsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } + }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + }); + + describe('getKeyRing', () => { + it('invokes getKeyRing without error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.GetKeyRingRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.GetKeyRingRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.kms.v1.KeyRing(), + ); + client.innerApiCalls.getKeyRing = stubSimpleCall(expectedResponse); + const [response] = await client.getKeyRing(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getKeyRing as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getKeyRing as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getKeyRing without error using callback', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.GetKeyRingRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.GetKeyRingRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.kms.v1.KeyRing(), + ); + client.innerApiCalls.getKeyRing = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getKeyRing( + request, + ( + err?: Error | null, + result?: protos.google.cloud.kms.v1.IKeyRing | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listKeyRings.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listKeyRings.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); - - it('uses async iteration with listKeyRings with error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.ListKeyRingsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.ListKeyRingsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listKeyRings.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listKeyRingsAsync(request); - await assert.rejects(async () => { - const responses: protos.google.cloud.kms.v1.IKeyRing[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listKeyRings.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listKeyRings.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); - }); - - describe('listCryptoKeys', () => { - it('invokes listCryptoKeys without error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.ListCryptoKeysRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.ListCryptoKeysRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.kms.v1.CryptoKey()), - generateSampleMessage(new protos.google.cloud.kms.v1.CryptoKey()), - generateSampleMessage(new protos.google.cloud.kms.v1.CryptoKey()), - ]; - client.innerApiCalls.listCryptoKeys = stubSimpleCall(expectedResponse); - const [response] = await client.listCryptoKeys(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listCryptoKeys as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listCryptoKeys as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listCryptoKeys without error using callback', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.ListCryptoKeysRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.ListCryptoKeysRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.kms.v1.CryptoKey()), - generateSampleMessage(new protos.google.cloud.kms.v1.CryptoKey()), - generateSampleMessage(new protos.google.cloud.kms.v1.CryptoKey()), - ]; - client.innerApiCalls.listCryptoKeys = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listCryptoKeys( - request, - (err?: Error|null, result?: protos.google.cloud.kms.v1.ICryptoKey[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listCryptoKeys as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listCryptoKeys as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listCryptoKeys with error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.ListCryptoKeysRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.ListCryptoKeysRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listCryptoKeys = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listCryptoKeys(request), expectedError); - const actualRequest = (client.innerApiCalls.listCryptoKeys as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listCryptoKeys as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listCryptoKeysStream without error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.ListCryptoKeysRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.ListCryptoKeysRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.kms.v1.CryptoKey()), - generateSampleMessage(new protos.google.cloud.kms.v1.CryptoKey()), - generateSampleMessage(new protos.google.cloud.kms.v1.CryptoKey()), - ]; - client.descriptors.page.listCryptoKeys.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listCryptoKeysStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.cloud.kms.v1.CryptoKey[] = []; - stream.on('data', (response: protos.google.cloud.kms.v1.CryptoKey) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.listCryptoKeys.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listCryptoKeys, request)); - assert( - (client.descriptors.page.listCryptoKeys.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); - - it('invokes listCryptoKeysStream with error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.ListCryptoKeysRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.ListCryptoKeysRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listCryptoKeys.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listCryptoKeysStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.cloud.kms.v1.CryptoKey[] = []; - stream.on('data', (response: protos.google.cloud.kms.v1.CryptoKey) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listCryptoKeys.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listCryptoKeys, request)); - assert( - (client.descriptors.page.listCryptoKeys.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); - - it('uses async iteration with listCryptoKeys without error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.ListCryptoKeysRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.ListCryptoKeysRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.kms.v1.CryptoKey()), - generateSampleMessage(new protos.google.cloud.kms.v1.CryptoKey()), - generateSampleMessage(new protos.google.cloud.kms.v1.CryptoKey()), - ]; - client.descriptors.page.listCryptoKeys.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.cloud.kms.v1.ICryptoKey[] = []; - const iterable = client.listCryptoKeysAsync(request); - for await (const resource of iterable) { - responses.push(resource!); + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getKeyRing as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getKeyRing as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getKeyRing with error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.GetKeyRingRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.GetKeyRingRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getKeyRing = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getKeyRing(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getKeyRing as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getKeyRing as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getKeyRing with closed client', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.GetKeyRingRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.GetKeyRingRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getKeyRing(request), expectedError); + }); + }); + + describe('getCryptoKey', () => { + it('invokes getCryptoKey without error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.GetCryptoKeyRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.GetCryptoKeyRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.kms.v1.CryptoKey(), + ); + client.innerApiCalls.getCryptoKey = stubSimpleCall(expectedResponse); + const [response] = await client.getCryptoKey(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getCryptoKey as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getCryptoKey as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getCryptoKey without error using callback', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.GetCryptoKeyRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.GetCryptoKeyRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.kms.v1.CryptoKey(), + ); + client.innerApiCalls.getCryptoKey = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getCryptoKey( + request, + ( + err?: Error | null, + result?: protos.google.cloud.kms.v1.ICryptoKey | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listCryptoKeys.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listCryptoKeys.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); - - it('uses async iteration with listCryptoKeys with error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.ListCryptoKeysRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.ListCryptoKeysRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listCryptoKeys.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listCryptoKeysAsync(request); - await assert.rejects(async () => { - const responses: protos.google.cloud.kms.v1.ICryptoKey[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listCryptoKeys.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listCryptoKeys.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); - }); - - describe('listCryptoKeyVersions', () => { - it('invokes listCryptoKeyVersions without error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.ListCryptoKeyVersionsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.ListCryptoKeyVersionsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.kms.v1.CryptoKeyVersion()), - generateSampleMessage(new protos.google.cloud.kms.v1.CryptoKeyVersion()), - generateSampleMessage(new protos.google.cloud.kms.v1.CryptoKeyVersion()), - ]; - client.innerApiCalls.listCryptoKeyVersions = stubSimpleCall(expectedResponse); - const [response] = await client.listCryptoKeyVersions(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listCryptoKeyVersions as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listCryptoKeyVersions as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listCryptoKeyVersions without error using callback', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.ListCryptoKeyVersionsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.ListCryptoKeyVersionsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.kms.v1.CryptoKeyVersion()), - generateSampleMessage(new protos.google.cloud.kms.v1.CryptoKeyVersion()), - generateSampleMessage(new protos.google.cloud.kms.v1.CryptoKeyVersion()), - ]; - client.innerApiCalls.listCryptoKeyVersions = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listCryptoKeyVersions( - request, - (err?: Error|null, result?: protos.google.cloud.kms.v1.ICryptoKeyVersion[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listCryptoKeyVersions as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listCryptoKeyVersions as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listCryptoKeyVersions with error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.ListCryptoKeyVersionsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.ListCryptoKeyVersionsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listCryptoKeyVersions = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listCryptoKeyVersions(request), expectedError); - const actualRequest = (client.innerApiCalls.listCryptoKeyVersions as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listCryptoKeyVersions as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listCryptoKeyVersionsStream without error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.ListCryptoKeyVersionsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.ListCryptoKeyVersionsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.kms.v1.CryptoKeyVersion()), - generateSampleMessage(new protos.google.cloud.kms.v1.CryptoKeyVersion()), - generateSampleMessage(new protos.google.cloud.kms.v1.CryptoKeyVersion()), - ]; - client.descriptors.page.listCryptoKeyVersions.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listCryptoKeyVersionsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.cloud.kms.v1.CryptoKeyVersion[] = []; - stream.on('data', (response: protos.google.cloud.kms.v1.CryptoKeyVersion) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.listCryptoKeyVersions.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listCryptoKeyVersions, request)); - assert( - (client.descriptors.page.listCryptoKeyVersions.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); - - it('invokes listCryptoKeyVersionsStream with error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.ListCryptoKeyVersionsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.ListCryptoKeyVersionsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listCryptoKeyVersions.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listCryptoKeyVersionsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.cloud.kms.v1.CryptoKeyVersion[] = []; - stream.on('data', (response: protos.google.cloud.kms.v1.CryptoKeyVersion) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listCryptoKeyVersions.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listCryptoKeyVersions, request)); - assert( - (client.descriptors.page.listCryptoKeyVersions.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); - - it('uses async iteration with listCryptoKeyVersions without error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.ListCryptoKeyVersionsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.ListCryptoKeyVersionsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.kms.v1.CryptoKeyVersion()), - generateSampleMessage(new protos.google.cloud.kms.v1.CryptoKeyVersion()), - generateSampleMessage(new protos.google.cloud.kms.v1.CryptoKeyVersion()), - ]; - client.descriptors.page.listCryptoKeyVersions.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.cloud.kms.v1.ICryptoKeyVersion[] = []; - const iterable = client.listCryptoKeyVersionsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getCryptoKey as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getCryptoKey as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getCryptoKey with error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.GetCryptoKeyRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.GetCryptoKeyRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getCryptoKey = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getCryptoKey(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getCryptoKey as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getCryptoKey as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getCryptoKey with closed client', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.GetCryptoKeyRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.GetCryptoKeyRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getCryptoKey(request), expectedError); + }); + }); + + describe('getCryptoKeyVersion', () => { + it('invokes getCryptoKeyVersion without error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.GetCryptoKeyVersionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.GetCryptoKeyVersionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.kms.v1.CryptoKeyVersion(), + ); + client.innerApiCalls.getCryptoKeyVersion = + stubSimpleCall(expectedResponse); + const [response] = await client.getCryptoKeyVersion(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getCryptoKeyVersion as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getCryptoKeyVersion as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getCryptoKeyVersion without error using callback', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.GetCryptoKeyVersionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.GetCryptoKeyVersionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.kms.v1.CryptoKeyVersion(), + ); + client.innerApiCalls.getCryptoKeyVersion = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getCryptoKeyVersion( + request, + ( + err?: Error | null, + result?: protos.google.cloud.kms.v1.ICryptoKeyVersion | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listCryptoKeyVersions.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listCryptoKeyVersions.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); - - it('uses async iteration with listCryptoKeyVersions with error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.ListCryptoKeyVersionsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.ListCryptoKeyVersionsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listCryptoKeyVersions.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listCryptoKeyVersionsAsync(request); - await assert.rejects(async () => { - const responses: protos.google.cloud.kms.v1.ICryptoKeyVersion[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listCryptoKeyVersions.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listCryptoKeyVersions.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); - }); - - describe('listImportJobs', () => { - it('invokes listImportJobs without error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.ListImportJobsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.ListImportJobsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.kms.v1.ImportJob()), - generateSampleMessage(new protos.google.cloud.kms.v1.ImportJob()), - generateSampleMessage(new protos.google.cloud.kms.v1.ImportJob()), - ]; - client.innerApiCalls.listImportJobs = stubSimpleCall(expectedResponse); - const [response] = await client.listImportJobs(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listImportJobs as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listImportJobs as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listImportJobs without error using callback', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.ListImportJobsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.ListImportJobsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.kms.v1.ImportJob()), - generateSampleMessage(new protos.google.cloud.kms.v1.ImportJob()), - generateSampleMessage(new protos.google.cloud.kms.v1.ImportJob()), - ]; - client.innerApiCalls.listImportJobs = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listImportJobs( - request, - (err?: Error|null, result?: protos.google.cloud.kms.v1.IImportJob[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listImportJobs as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listImportJobs as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listImportJobs with error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.ListImportJobsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.ListImportJobsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listImportJobs = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listImportJobs(request), expectedError); - const actualRequest = (client.innerApiCalls.listImportJobs as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listImportJobs as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listImportJobsStream without error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.ListImportJobsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.ListImportJobsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.kms.v1.ImportJob()), - generateSampleMessage(new protos.google.cloud.kms.v1.ImportJob()), - generateSampleMessage(new protos.google.cloud.kms.v1.ImportJob()), - ]; - client.descriptors.page.listImportJobs.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listImportJobsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.cloud.kms.v1.ImportJob[] = []; - stream.on('data', (response: protos.google.cloud.kms.v1.ImportJob) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.listImportJobs.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listImportJobs, request)); - assert( - (client.descriptors.page.listImportJobs.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); - - it('invokes listImportJobsStream with error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.ListImportJobsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.ListImportJobsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listImportJobs.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listImportJobsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.cloud.kms.v1.ImportJob[] = []; - stream.on('data', (response: protos.google.cloud.kms.v1.ImportJob) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listImportJobs.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listImportJobs, request)); - assert( - (client.descriptors.page.listImportJobs.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); - - it('uses async iteration with listImportJobs without error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.ListImportJobsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.ListImportJobsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.kms.v1.ImportJob()), - generateSampleMessage(new protos.google.cloud.kms.v1.ImportJob()), - generateSampleMessage(new protos.google.cloud.kms.v1.ImportJob()), - ]; - client.descriptors.page.listImportJobs.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.cloud.kms.v1.IImportJob[] = []; - const iterable = client.listImportJobsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getCryptoKeyVersion as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getCryptoKeyVersion as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getCryptoKeyVersion with error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.GetCryptoKeyVersionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.GetCryptoKeyVersionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getCryptoKeyVersion = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getCryptoKeyVersion(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getCryptoKeyVersion as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getCryptoKeyVersion as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getCryptoKeyVersion with closed client', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.GetCryptoKeyVersionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.GetCryptoKeyVersionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getCryptoKeyVersion(request), expectedError); + }); + }); + + describe('getPublicKey', () => { + it('invokes getPublicKey without error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.GetPublicKeyRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.GetPublicKeyRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.kms.v1.PublicKey(), + ); + client.innerApiCalls.getPublicKey = stubSimpleCall(expectedResponse); + const [response] = await client.getPublicKey(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getPublicKey as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getPublicKey as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getPublicKey without error using callback', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.GetPublicKeyRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.GetPublicKeyRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.kms.v1.PublicKey(), + ); + client.innerApiCalls.getPublicKey = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getPublicKey( + request, + ( + err?: Error | null, + result?: protos.google.cloud.kms.v1.IPublicKey | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listImportJobs.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listImportJobs.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); - - it('uses async iteration with listImportJobs with error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.ListImportJobsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.ListImportJobsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listImportJobs.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listImportJobsAsync(request); - await assert.rejects(async () => { - const responses: protos.google.cloud.kms.v1.IImportJob[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listImportJobs.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listImportJobs.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); - }); - describe('getIamPolicy', () => { - it('invokes getIamPolicy without error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new IamProtos.google.iam.v1.GetIamPolicyRequest() - ); - request.resource = ''; - const expectedHeaderRequestParams = 'resource='; - const expectedOptions = { - otherArgs: { - headers: { - 'x-goog-request-params': expectedHeaderRequestParams, - }, - }, - }; - const expectedResponse = generateSampleMessage( - new IamProtos.google.iam.v1.Policy() - ); - client.iamClient.getIamPolicy = stubSimpleCall(expectedResponse); - const response = await client.getIamPolicy(request, expectedOptions); - assert.deepStrictEqual(response, [expectedResponse]); - assert((client.iamClient.getIamPolicy as SinonStub) - .getCall(0).calledWith(request, expectedOptions, undefined)); - }); - it('invokes getIamPolicy without error using callback', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new IamProtos.google.iam.v1.GetIamPolicyRequest() - ); - request.resource = ''; - const expectedHeaderRequestParams = 'resource='; - const expectedOptions = { - otherArgs: { - headers: { - 'x-goog-request-params': expectedHeaderRequestParams, - }, - }, - }; - const expectedResponse = generateSampleMessage( - new IamProtos.google.iam.v1.Policy() - ); - client.iamClient.getIamPolicy = sinon.stub().callsArgWith(2, null, expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getIamPolicy( - request, - expectedOptions, - (err?: Error|null, result?: IamProtos.google.iam.v1.Policy|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }).catch(err => {throw err}); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - assert((client.iamClient.getIamPolicy as SinonStub) - .getCall(0)); - }); - it('invokes getIamPolicy with error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new IamProtos.google.iam.v1.GetIamPolicyRequest() - ); - request.resource = ''; - const expectedHeaderRequestParams = 'resource='; - const expectedOptions = { - otherArgs: { - headers: { - 'x-goog-request-params': expectedHeaderRequestParams, - }, - }, - }; - const expectedError = new Error('expected'); - client.iamClient.getIamPolicy = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getIamPolicy(request, expectedOptions), expectedError); - assert((client.iamClient.getIamPolicy as SinonStub) - .getCall(0).calledWith(request, expectedOptions, undefined)); - }); - }); - describe('setIamPolicy', () => { - it('invokes setIamPolicy without error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new IamProtos.google.iam.v1.SetIamPolicyRequest() - ); - request.resource = ''; - const expectedHeaderRequestParams = 'resource='; - const expectedOptions = { - otherArgs: { - headers: { - 'x-goog-request-params': expectedHeaderRequestParams, - }, - }, - }; - const expectedResponse = generateSampleMessage( - new IamProtos.google.iam.v1.Policy() - ); - client.iamClient.setIamPolicy = stubSimpleCall(expectedResponse); - const response = await client.setIamPolicy(request, expectedOptions); - assert.deepStrictEqual(response, [expectedResponse]); - assert((client.iamClient.setIamPolicy as SinonStub) - .getCall(0).calledWith(request, expectedOptions, undefined)); - }); - it('invokes setIamPolicy without error using callback', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new IamProtos.google.iam.v1.SetIamPolicyRequest() - ); - request.resource = ''; - const expectedHeaderRequestParams = 'resource='; - const expectedOptions = { - otherArgs: { - headers: { - 'x-goog-request-params': expectedHeaderRequestParams, - }, - }, - }; - const expectedResponse = generateSampleMessage( - new IamProtos.google.iam.v1.Policy() - ); - client.iamClient.setIamPolicy = sinon.stub().callsArgWith(2, null, expectedResponse); - const promise = new Promise((resolve, reject) => { - client.setIamPolicy( - request, - expectedOptions, - (err?: Error|null, result?: IamProtos.google.iam.v1.Policy|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }).catch(err => {throw err}); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - assert((client.iamClient.setIamPolicy as SinonStub) - .getCall(0)); - }); - it('invokes setIamPolicy with error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new IamProtos.google.iam.v1.SetIamPolicyRequest() - ); - request.resource = ''; - const expectedHeaderRequestParams = 'resource='; - const expectedOptions = { - otherArgs: { - headers: { - 'x-goog-request-params': expectedHeaderRequestParams, - }, - }, - }; - const expectedError = new Error('expected'); - client.iamClient.setIamPolicy = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.setIamPolicy(request, expectedOptions), expectedError); - assert((client.iamClient.setIamPolicy as SinonStub) - .getCall(0).calledWith(request, expectedOptions, undefined)); - }); - }); - describe('testIamPermissions', () => { - it('invokes testIamPermissions without error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new IamProtos.google.iam.v1.TestIamPermissionsRequest() - ); - request.resource = ''; - const expectedHeaderRequestParams = 'resource='; - const expectedOptions = { - otherArgs: { - headers: { - 'x-goog-request-params': expectedHeaderRequestParams, - }, - }, - }; - const expectedResponse = generateSampleMessage( - new IamProtos.google.iam.v1.TestIamPermissionsResponse() - ); - client.iamClient.testIamPermissions = stubSimpleCall(expectedResponse); - const response = await client.testIamPermissions(request, expectedOptions); - assert.deepStrictEqual(response, [expectedResponse]); - assert((client.iamClient.testIamPermissions as SinonStub) - .getCall(0).calledWith(request, expectedOptions, undefined)); - }); - it('invokes testIamPermissions without error using callback', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new IamProtos.google.iam.v1.TestIamPermissionsRequest() - ); - request.resource = ''; - const expectedHeaderRequestParams = 'resource='; - const expectedOptions = { - otherArgs: { - headers: { - 'x-goog-request-params': expectedHeaderRequestParams, - }, - }, - }; - const expectedResponse = generateSampleMessage( - new IamProtos.google.iam.v1.TestIamPermissionsResponse() - ); - client.iamClient.testIamPermissions = sinon.stub().callsArgWith(2, null, expectedResponse); - const promise = new Promise((resolve, reject) => { - client.testIamPermissions( - request, - expectedOptions, - (err?: Error|null, result?: IamProtos.google.iam.v1.TestIamPermissionsResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }).catch(err => {throw err}); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - assert((client.iamClient.testIamPermissions as SinonStub) - .getCall(0)); - }); - it('invokes testIamPermissions with error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new IamProtos.google.iam.v1.TestIamPermissionsRequest() - ); - request.resource = ''; - const expectedHeaderRequestParams = 'resource='; - const expectedOptions = { - otherArgs: { - headers: { - 'x-goog-request-params': expectedHeaderRequestParams, - }, - }, - }; - const expectedError = new Error('expected'); - client.iamClient.testIamPermissions = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.testIamPermissions(request, expectedOptions), expectedError); - assert((client.iamClient.testIamPermissions as SinonStub) - .getCall(0).calledWith(request, expectedOptions, undefined)); + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getPublicKey as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getPublicKey as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getPublicKey with error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.GetPublicKeyRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.GetPublicKeyRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getPublicKey = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getPublicKey(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getPublicKey as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getPublicKey as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getPublicKey with closed client', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.GetPublicKeyRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.GetPublicKeyRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getPublicKey(request), expectedError); + }); + }); + + describe('getImportJob', () => { + it('invokes getImportJob without error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.GetImportJobRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.GetImportJobRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.kms.v1.ImportJob(), + ); + client.innerApiCalls.getImportJob = stubSimpleCall(expectedResponse); + const [response] = await client.getImportJob(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getImportJob as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getImportJob as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getImportJob without error using callback', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.GetImportJobRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.GetImportJobRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.kms.v1.ImportJob(), + ); + client.innerApiCalls.getImportJob = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getImportJob( + request, + ( + err?: Error | null, + result?: protos.google.cloud.kms.v1.IImportJob | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getImportJob as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getImportJob as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getImportJob with error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.GetImportJobRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.GetImportJobRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getImportJob = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getImportJob(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getImportJob as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getImportJob as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getImportJob with closed client', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.GetImportJobRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.GetImportJobRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getImportJob(request), expectedError); + }); + }); + + describe('createKeyRing', () => { + it('invokes createKeyRing without error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.CreateKeyRingRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.CreateKeyRingRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.kms.v1.KeyRing(), + ); + client.innerApiCalls.createKeyRing = stubSimpleCall(expectedResponse); + const [response] = await client.createKeyRing(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createKeyRing as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createKeyRing as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createKeyRing without error using callback', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.CreateKeyRingRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.CreateKeyRingRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.kms.v1.KeyRing(), + ); + client.innerApiCalls.createKeyRing = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createKeyRing( + request, + ( + err?: Error | null, + result?: protos.google.cloud.kms.v1.IKeyRing | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createKeyRing as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createKeyRing as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createKeyRing with error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.CreateKeyRingRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.CreateKeyRingRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createKeyRing = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.createKeyRing(request), expectedError); + const actualRequest = ( + client.innerApiCalls.createKeyRing as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createKeyRing as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createKeyRing with closed client', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.CreateKeyRingRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.CreateKeyRingRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.createKeyRing(request), expectedError); + }); + }); + + describe('createCryptoKey', () => { + it('invokes createCryptoKey without error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.CreateCryptoKeyRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.CreateCryptoKeyRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.kms.v1.CryptoKey(), + ); + client.innerApiCalls.createCryptoKey = stubSimpleCall(expectedResponse); + const [response] = await client.createCryptoKey(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createCryptoKey as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createCryptoKey as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createCryptoKey without error using callback', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.CreateCryptoKeyRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.CreateCryptoKeyRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.kms.v1.CryptoKey(), + ); + client.innerApiCalls.createCryptoKey = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createCryptoKey( + request, + ( + err?: Error | null, + result?: protos.google.cloud.kms.v1.ICryptoKey | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createCryptoKey as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createCryptoKey as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createCryptoKey with error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.CreateCryptoKeyRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.CreateCryptoKeyRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createCryptoKey = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.createCryptoKey(request), expectedError); + const actualRequest = ( + client.innerApiCalls.createCryptoKey as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createCryptoKey as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createCryptoKey with closed client', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.CreateCryptoKeyRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.CreateCryptoKeyRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.createCryptoKey(request), expectedError); + }); + }); + + describe('createCryptoKeyVersion', () => { + it('invokes createCryptoKeyVersion without error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.CreateCryptoKeyVersionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.CreateCryptoKeyVersionRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.kms.v1.CryptoKeyVersion(), + ); + client.innerApiCalls.createCryptoKeyVersion = + stubSimpleCall(expectedResponse); + const [response] = await client.createCryptoKeyVersion(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createCryptoKeyVersion as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createCryptoKeyVersion as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createCryptoKeyVersion without error using callback', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.CreateCryptoKeyVersionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.CreateCryptoKeyVersionRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.kms.v1.CryptoKeyVersion(), + ); + client.innerApiCalls.createCryptoKeyVersion = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createCryptoKeyVersion( + request, + ( + err?: Error | null, + result?: protos.google.cloud.kms.v1.ICryptoKeyVersion | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createCryptoKeyVersion as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createCryptoKeyVersion as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createCryptoKeyVersion with error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.CreateCryptoKeyVersionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.CreateCryptoKeyVersionRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createCryptoKeyVersion = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.createCryptoKeyVersion(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.createCryptoKeyVersion as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createCryptoKeyVersion as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createCryptoKeyVersion with closed client', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.CreateCryptoKeyVersionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.CreateCryptoKeyVersionRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.createCryptoKeyVersion(request), + expectedError, + ); + }); + }); + + describe('importCryptoKeyVersion', () => { + it('invokes importCryptoKeyVersion without error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.ImportCryptoKeyVersionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.ImportCryptoKeyVersionRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.kms.v1.CryptoKeyVersion(), + ); + client.innerApiCalls.importCryptoKeyVersion = + stubSimpleCall(expectedResponse); + const [response] = await client.importCryptoKeyVersion(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.importCryptoKeyVersion as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.importCryptoKeyVersion as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes importCryptoKeyVersion without error using callback', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.ImportCryptoKeyVersionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.ImportCryptoKeyVersionRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.kms.v1.CryptoKeyVersion(), + ); + client.innerApiCalls.importCryptoKeyVersion = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.importCryptoKeyVersion( + request, + ( + err?: Error | null, + result?: protos.google.cloud.kms.v1.ICryptoKeyVersion | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.importCryptoKeyVersion as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.importCryptoKeyVersion as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes importCryptoKeyVersion with error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.ImportCryptoKeyVersionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.ImportCryptoKeyVersionRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.importCryptoKeyVersion = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.importCryptoKeyVersion(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.importCryptoKeyVersion as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.importCryptoKeyVersion as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes importCryptoKeyVersion with closed client', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.ImportCryptoKeyVersionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.ImportCryptoKeyVersionRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.importCryptoKeyVersion(request), + expectedError, + ); + }); + }); + + describe('createImportJob', () => { + it('invokes createImportJob without error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.CreateImportJobRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.CreateImportJobRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.kms.v1.ImportJob(), + ); + client.innerApiCalls.createImportJob = stubSimpleCall(expectedResponse); + const [response] = await client.createImportJob(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createImportJob as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createImportJob as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createImportJob without error using callback', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.CreateImportJobRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.CreateImportJobRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.kms.v1.ImportJob(), + ); + client.innerApiCalls.createImportJob = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createImportJob( + request, + ( + err?: Error | null, + result?: protos.google.cloud.kms.v1.IImportJob | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createImportJob as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createImportJob as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createImportJob with error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.CreateImportJobRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.CreateImportJobRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createImportJob = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.createImportJob(request), expectedError); + const actualRequest = ( + client.innerApiCalls.createImportJob as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createImportJob as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createImportJob with closed client', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.CreateImportJobRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.CreateImportJobRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.createImportJob(request), expectedError); + }); + }); + + describe('updateCryptoKey', () => { + it('invokes updateCryptoKey without error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.UpdateCryptoKeyRequest(), + ); + request.cryptoKey ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.UpdateCryptoKeyRequest', + ['cryptoKey', 'name'], + ); + request.cryptoKey.name = defaultValue1; + const expectedHeaderRequestParams = `crypto_key.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.kms.v1.CryptoKey(), + ); + client.innerApiCalls.updateCryptoKey = stubSimpleCall(expectedResponse); + const [response] = await client.updateCryptoKey(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateCryptoKey as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateCryptoKey as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateCryptoKey without error using callback', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.UpdateCryptoKeyRequest(), + ); + request.cryptoKey ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.UpdateCryptoKeyRequest', + ['cryptoKey', 'name'], + ); + request.cryptoKey.name = defaultValue1; + const expectedHeaderRequestParams = `crypto_key.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.kms.v1.CryptoKey(), + ); + client.innerApiCalls.updateCryptoKey = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateCryptoKey( + request, + ( + err?: Error | null, + result?: protos.google.cloud.kms.v1.ICryptoKey | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateCryptoKey as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateCryptoKey as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateCryptoKey with error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.UpdateCryptoKeyRequest(), + ); + request.cryptoKey ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.UpdateCryptoKeyRequest', + ['cryptoKey', 'name'], + ); + request.cryptoKey.name = defaultValue1; + const expectedHeaderRequestParams = `crypto_key.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateCryptoKey = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.updateCryptoKey(request), expectedError); + const actualRequest = ( + client.innerApiCalls.updateCryptoKey as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateCryptoKey as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateCryptoKey with closed client', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.UpdateCryptoKeyRequest(), + ); + request.cryptoKey ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.UpdateCryptoKeyRequest', + ['cryptoKey', 'name'], + ); + request.cryptoKey.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.updateCryptoKey(request), expectedError); + }); + }); + + describe('updateCryptoKeyVersion', () => { + it('invokes updateCryptoKeyVersion without error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.UpdateCryptoKeyVersionRequest(), + ); + request.cryptoKeyVersion ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.UpdateCryptoKeyVersionRequest', + ['cryptoKeyVersion', 'name'], + ); + request.cryptoKeyVersion.name = defaultValue1; + const expectedHeaderRequestParams = `crypto_key_version.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.kms.v1.CryptoKeyVersion(), + ); + client.innerApiCalls.updateCryptoKeyVersion = + stubSimpleCall(expectedResponse); + const [response] = await client.updateCryptoKeyVersion(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateCryptoKeyVersion as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateCryptoKeyVersion as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateCryptoKeyVersion without error using callback', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.UpdateCryptoKeyVersionRequest(), + ); + request.cryptoKeyVersion ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.UpdateCryptoKeyVersionRequest', + ['cryptoKeyVersion', 'name'], + ); + request.cryptoKeyVersion.name = defaultValue1; + const expectedHeaderRequestParams = `crypto_key_version.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.kms.v1.CryptoKeyVersion(), + ); + client.innerApiCalls.updateCryptoKeyVersion = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateCryptoKeyVersion( + request, + ( + err?: Error | null, + result?: protos.google.cloud.kms.v1.ICryptoKeyVersion | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateCryptoKeyVersion as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateCryptoKeyVersion as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateCryptoKeyVersion with error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.UpdateCryptoKeyVersionRequest(), + ); + request.cryptoKeyVersion ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.UpdateCryptoKeyVersionRequest', + ['cryptoKeyVersion', 'name'], + ); + request.cryptoKeyVersion.name = defaultValue1; + const expectedHeaderRequestParams = `crypto_key_version.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateCryptoKeyVersion = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.updateCryptoKeyVersion(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.updateCryptoKeyVersion as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateCryptoKeyVersion as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateCryptoKeyVersion with closed client', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.UpdateCryptoKeyVersionRequest(), + ); + request.cryptoKeyVersion ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.UpdateCryptoKeyVersionRequest', + ['cryptoKeyVersion', 'name'], + ); + request.cryptoKeyVersion.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.updateCryptoKeyVersion(request), + expectedError, + ); + }); + }); + + describe('encrypt', () => { + it('invokes encrypt without error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.EncryptRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.EncryptRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.kms.v1.EncryptResponse(), + ); + client.innerApiCalls.encrypt = stubSimpleCall(expectedResponse); + const [response] = await client.encrypt(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.encrypt as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.encrypt as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes encrypt without error using callback', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.EncryptRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.EncryptRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.kms.v1.EncryptResponse(), + ); + client.innerApiCalls.encrypt = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.encrypt( + request, + ( + err?: Error | null, + result?: protos.google.cloud.kms.v1.IEncryptResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.encrypt as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.encrypt as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes encrypt with error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.EncryptRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.EncryptRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.encrypt = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.encrypt(request), expectedError); + const actualRequest = (client.innerApiCalls.encrypt as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.encrypt as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes encrypt with closed client', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.EncryptRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.EncryptRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.encrypt(request), expectedError); + }); + }); + + describe('decrypt', () => { + it('invokes decrypt without error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.DecryptRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.DecryptRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.kms.v1.DecryptResponse(), + ); + client.innerApiCalls.decrypt = stubSimpleCall(expectedResponse); + const [response] = await client.decrypt(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.decrypt as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.decrypt as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes decrypt without error using callback', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.DecryptRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.DecryptRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.kms.v1.DecryptResponse(), + ); + client.innerApiCalls.decrypt = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.decrypt( + request, + ( + err?: Error | null, + result?: protos.google.cloud.kms.v1.IDecryptResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.decrypt as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.decrypt as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes decrypt with error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.DecryptRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.DecryptRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.decrypt = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.decrypt(request), expectedError); + const actualRequest = (client.innerApiCalls.decrypt as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.decrypt as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes decrypt with closed client', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.DecryptRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.DecryptRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.decrypt(request), expectedError); + }); + }); + + describe('asymmetricSign', () => { + it('invokes asymmetricSign without error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.AsymmetricSignRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.AsymmetricSignRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.kms.v1.AsymmetricSignResponse(), + ); + client.innerApiCalls.asymmetricSign = stubSimpleCall(expectedResponse); + const [response] = await client.asymmetricSign(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.asymmetricSign as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.asymmetricSign as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes asymmetricSign without error using callback', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.AsymmetricSignRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.AsymmetricSignRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.kms.v1.AsymmetricSignResponse(), + ); + client.innerApiCalls.asymmetricSign = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.asymmetricSign( + request, + ( + err?: Error | null, + result?: protos.google.cloud.kms.v1.IAsymmetricSignResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.asymmetricSign as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.asymmetricSign as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes asymmetricSign with error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.AsymmetricSignRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.AsymmetricSignRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.asymmetricSign = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.asymmetricSign(request), expectedError); + const actualRequest = ( + client.innerApiCalls.asymmetricSign as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.asymmetricSign as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes asymmetricSign with closed client', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.AsymmetricSignRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.AsymmetricSignRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.asymmetricSign(request), expectedError); + }); + }); + + describe('asymmetricDecrypt', () => { + it('invokes asymmetricDecrypt without error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.AsymmetricDecryptRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.AsymmetricDecryptRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.kms.v1.AsymmetricDecryptResponse(), + ); + client.innerApiCalls.asymmetricDecrypt = stubSimpleCall(expectedResponse); + const [response] = await client.asymmetricDecrypt(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.asymmetricDecrypt as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.asymmetricDecrypt as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes asymmetricDecrypt without error using callback', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.AsymmetricDecryptRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.AsymmetricDecryptRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.kms.v1.AsymmetricDecryptResponse(), + ); + client.innerApiCalls.asymmetricDecrypt = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.asymmetricDecrypt( + request, + ( + err?: Error | null, + result?: protos.google.cloud.kms.v1.IAsymmetricDecryptResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.asymmetricDecrypt as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.asymmetricDecrypt as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes asymmetricDecrypt with error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.AsymmetricDecryptRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.AsymmetricDecryptRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.asymmetricDecrypt = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.asymmetricDecrypt(request), expectedError); + const actualRequest = ( + client.innerApiCalls.asymmetricDecrypt as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.asymmetricDecrypt as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes asymmetricDecrypt with closed client', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.AsymmetricDecryptRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.AsymmetricDecryptRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.asymmetricDecrypt(request), expectedError); + }); + }); + + describe('updateCryptoKeyPrimaryVersion', () => { + it('invokes updateCryptoKeyPrimaryVersion without error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.UpdateCryptoKeyPrimaryVersionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.UpdateCryptoKeyPrimaryVersionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.kms.v1.CryptoKey(), + ); + client.innerApiCalls.updateCryptoKeyPrimaryVersion = + stubSimpleCall(expectedResponse); + const [response] = await client.updateCryptoKeyPrimaryVersion(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateCryptoKeyPrimaryVersion as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateCryptoKeyPrimaryVersion as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateCryptoKeyPrimaryVersion without error using callback', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.UpdateCryptoKeyPrimaryVersionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.UpdateCryptoKeyPrimaryVersionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.kms.v1.CryptoKey(), + ); + client.innerApiCalls.updateCryptoKeyPrimaryVersion = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateCryptoKeyPrimaryVersion( + request, + ( + err?: Error | null, + result?: protos.google.cloud.kms.v1.ICryptoKey | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateCryptoKeyPrimaryVersion as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateCryptoKeyPrimaryVersion as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateCryptoKeyPrimaryVersion with error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.UpdateCryptoKeyPrimaryVersionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.UpdateCryptoKeyPrimaryVersionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateCryptoKeyPrimaryVersion = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.updateCryptoKeyPrimaryVersion(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.updateCryptoKeyPrimaryVersion as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateCryptoKeyPrimaryVersion as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateCryptoKeyPrimaryVersion with closed client', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.UpdateCryptoKeyPrimaryVersionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.UpdateCryptoKeyPrimaryVersionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.updateCryptoKeyPrimaryVersion(request), + expectedError, + ); + }); + }); + + describe('destroyCryptoKeyVersion', () => { + it('invokes destroyCryptoKeyVersion without error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.DestroyCryptoKeyVersionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.DestroyCryptoKeyVersionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.kms.v1.CryptoKeyVersion(), + ); + client.innerApiCalls.destroyCryptoKeyVersion = + stubSimpleCall(expectedResponse); + const [response] = await client.destroyCryptoKeyVersion(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.destroyCryptoKeyVersion as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.destroyCryptoKeyVersion as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes destroyCryptoKeyVersion without error using callback', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.DestroyCryptoKeyVersionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.DestroyCryptoKeyVersionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.kms.v1.CryptoKeyVersion(), + ); + client.innerApiCalls.destroyCryptoKeyVersion = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.destroyCryptoKeyVersion( + request, + ( + err?: Error | null, + result?: protos.google.cloud.kms.v1.ICryptoKeyVersion | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.destroyCryptoKeyVersion as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.destroyCryptoKeyVersion as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes destroyCryptoKeyVersion with error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.DestroyCryptoKeyVersionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.DestroyCryptoKeyVersionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.destroyCryptoKeyVersion = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.destroyCryptoKeyVersion(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.destroyCryptoKeyVersion as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.destroyCryptoKeyVersion as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes destroyCryptoKeyVersion with closed client', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.DestroyCryptoKeyVersionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.DestroyCryptoKeyVersionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.destroyCryptoKeyVersion(request), + expectedError, + ); + }); + }); + + describe('restoreCryptoKeyVersion', () => { + it('invokes restoreCryptoKeyVersion without error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.RestoreCryptoKeyVersionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.RestoreCryptoKeyVersionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.kms.v1.CryptoKeyVersion(), + ); + client.innerApiCalls.restoreCryptoKeyVersion = + stubSimpleCall(expectedResponse); + const [response] = await client.restoreCryptoKeyVersion(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.restoreCryptoKeyVersion as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.restoreCryptoKeyVersion as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes restoreCryptoKeyVersion without error using callback', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.RestoreCryptoKeyVersionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.RestoreCryptoKeyVersionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.kms.v1.CryptoKeyVersion(), + ); + client.innerApiCalls.restoreCryptoKeyVersion = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.restoreCryptoKeyVersion( + request, + ( + err?: Error | null, + result?: protos.google.cloud.kms.v1.ICryptoKeyVersion | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.restoreCryptoKeyVersion as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.restoreCryptoKeyVersion as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes restoreCryptoKeyVersion with error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.RestoreCryptoKeyVersionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.RestoreCryptoKeyVersionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.restoreCryptoKeyVersion = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.restoreCryptoKeyVersion(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.restoreCryptoKeyVersion as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.restoreCryptoKeyVersion as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes restoreCryptoKeyVersion with closed client', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.RestoreCryptoKeyVersionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.RestoreCryptoKeyVersionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.restoreCryptoKeyVersion(request), + expectedError, + ); + }); + }); + + describe('listKeyRings', () => { + it('invokes listKeyRings without error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.ListKeyRingsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.ListKeyRingsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.kms.v1.KeyRing()), + generateSampleMessage(new protos.google.cloud.kms.v1.KeyRing()), + generateSampleMessage(new protos.google.cloud.kms.v1.KeyRing()), + ]; + client.innerApiCalls.listKeyRings = stubSimpleCall(expectedResponse); + const [response] = await client.listKeyRings(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listKeyRings as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listKeyRings as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listKeyRings without error using callback', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.ListKeyRingsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.ListKeyRingsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.kms.v1.KeyRing()), + generateSampleMessage(new protos.google.cloud.kms.v1.KeyRing()), + generateSampleMessage(new protos.google.cloud.kms.v1.KeyRing()), + ]; + client.innerApiCalls.listKeyRings = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listKeyRings( + request, + ( + err?: Error | null, + result?: protos.google.cloud.kms.v1.IKeyRing[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listKeyRings as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listKeyRings as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listKeyRings with error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.ListKeyRingsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.ListKeyRingsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listKeyRings = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listKeyRings(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listKeyRings as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listKeyRings as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listKeyRingsStream without error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.ListKeyRingsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.ListKeyRingsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.kms.v1.KeyRing()), + generateSampleMessage(new protos.google.cloud.kms.v1.KeyRing()), + generateSampleMessage(new protos.google.cloud.kms.v1.KeyRing()), + ]; + client.descriptors.page.listKeyRings.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listKeyRingsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.cloud.kms.v1.KeyRing[] = []; + stream.on('data', (response: protos.google.cloud.kms.v1.KeyRing) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listKeyRings.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listKeyRings, request), + ); + assert( + (client.descriptors.page.listKeyRings.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + + it('invokes listKeyRingsStream with error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.ListKeyRingsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.ListKeyRingsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listKeyRings.createStream = stubPageStreamingCall( + undefined, + expectedError, + ); + const stream = client.listKeyRingsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.cloud.kms.v1.KeyRing[] = []; + stream.on('data', (response: protos.google.cloud.kms.v1.KeyRing) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listKeyRings.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listKeyRings, request), + ); + assert( + (client.descriptors.page.listKeyRings.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + + it('uses async iteration with listKeyRings without error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.ListKeyRingsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.ListKeyRingsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.kms.v1.KeyRing()), + generateSampleMessage(new protos.google.cloud.kms.v1.KeyRing()), + generateSampleMessage(new protos.google.cloud.kms.v1.KeyRing()), + ]; + client.descriptors.page.listKeyRings.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.cloud.kms.v1.IKeyRing[] = []; + const iterable = client.listKeyRingsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listKeyRings.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listKeyRings.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + + it('uses async iteration with listKeyRings with error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.ListKeyRingsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.ListKeyRingsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listKeyRings.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listKeyRingsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.cloud.kms.v1.IKeyRing[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listKeyRings.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listKeyRings.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + }); + + describe('listCryptoKeys', () => { + it('invokes listCryptoKeys without error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.ListCryptoKeysRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.ListCryptoKeysRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.kms.v1.CryptoKey()), + generateSampleMessage(new protos.google.cloud.kms.v1.CryptoKey()), + generateSampleMessage(new protos.google.cloud.kms.v1.CryptoKey()), + ]; + client.innerApiCalls.listCryptoKeys = stubSimpleCall(expectedResponse); + const [response] = await client.listCryptoKeys(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listCryptoKeys as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listCryptoKeys as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listCryptoKeys without error using callback', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.ListCryptoKeysRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.ListCryptoKeysRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.kms.v1.CryptoKey()), + generateSampleMessage(new protos.google.cloud.kms.v1.CryptoKey()), + generateSampleMessage(new protos.google.cloud.kms.v1.CryptoKey()), + ]; + client.innerApiCalls.listCryptoKeys = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listCryptoKeys( + request, + ( + err?: Error | null, + result?: protos.google.cloud.kms.v1.ICryptoKey[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listCryptoKeys as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listCryptoKeys as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listCryptoKeys with error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.ListCryptoKeysRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.ListCryptoKeysRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listCryptoKeys = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listCryptoKeys(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listCryptoKeys as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listCryptoKeys as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listCryptoKeysStream without error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.ListCryptoKeysRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.ListCryptoKeysRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.kms.v1.CryptoKey()), + generateSampleMessage(new protos.google.cloud.kms.v1.CryptoKey()), + generateSampleMessage(new protos.google.cloud.kms.v1.CryptoKey()), + ]; + client.descriptors.page.listCryptoKeys.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listCryptoKeysStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.cloud.kms.v1.CryptoKey[] = []; + stream.on('data', (response: protos.google.cloud.kms.v1.CryptoKey) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listCryptoKeys.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listCryptoKeys, request), + ); + assert( + (client.descriptors.page.listCryptoKeys.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + + it('invokes listCryptoKeysStream with error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.ListCryptoKeysRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.ListCryptoKeysRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listCryptoKeys.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listCryptoKeysStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.cloud.kms.v1.CryptoKey[] = []; + stream.on('data', (response: protos.google.cloud.kms.v1.CryptoKey) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listCryptoKeys.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listCryptoKeys, request), + ); + assert( + (client.descriptors.page.listCryptoKeys.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + + it('uses async iteration with listCryptoKeys without error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.ListCryptoKeysRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.ListCryptoKeysRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.kms.v1.CryptoKey()), + generateSampleMessage(new protos.google.cloud.kms.v1.CryptoKey()), + generateSampleMessage(new protos.google.cloud.kms.v1.CryptoKey()), + ]; + client.descriptors.page.listCryptoKeys.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.cloud.kms.v1.ICryptoKey[] = []; + const iterable = client.listCryptoKeysAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listCryptoKeys.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listCryptoKeys.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + + it('uses async iteration with listCryptoKeys with error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.ListCryptoKeysRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.ListCryptoKeysRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listCryptoKeys.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listCryptoKeysAsync(request); + await assert.rejects(async () => { + const responses: protos.google.cloud.kms.v1.ICryptoKey[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listCryptoKeys.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listCryptoKeys.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + }); + + describe('listCryptoKeyVersions', () => { + it('invokes listCryptoKeyVersions without error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.ListCryptoKeyVersionsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.ListCryptoKeyVersionsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.cloud.kms.v1.CryptoKeyVersion(), + ), + generateSampleMessage( + new protos.google.cloud.kms.v1.CryptoKeyVersion(), + ), + generateSampleMessage( + new protos.google.cloud.kms.v1.CryptoKeyVersion(), + ), + ]; + client.innerApiCalls.listCryptoKeyVersions = + stubSimpleCall(expectedResponse); + const [response] = await client.listCryptoKeyVersions(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listCryptoKeyVersions as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listCryptoKeyVersions as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listCryptoKeyVersions without error using callback', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.ListCryptoKeyVersionsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.ListCryptoKeyVersionsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.cloud.kms.v1.CryptoKeyVersion(), + ), + generateSampleMessage( + new protos.google.cloud.kms.v1.CryptoKeyVersion(), + ), + generateSampleMessage( + new protos.google.cloud.kms.v1.CryptoKeyVersion(), + ), + ]; + client.innerApiCalls.listCryptoKeyVersions = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listCryptoKeyVersions( + request, + ( + err?: Error | null, + result?: protos.google.cloud.kms.v1.ICryptoKeyVersion[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listCryptoKeyVersions as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listCryptoKeyVersions as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listCryptoKeyVersions with error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.ListCryptoKeyVersionsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.ListCryptoKeyVersionsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listCryptoKeyVersions = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.listCryptoKeyVersions(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.listCryptoKeyVersions as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listCryptoKeyVersions as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listCryptoKeyVersionsStream without error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.ListCryptoKeyVersionsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.ListCryptoKeyVersionsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.cloud.kms.v1.CryptoKeyVersion(), + ), + generateSampleMessage( + new protos.google.cloud.kms.v1.CryptoKeyVersion(), + ), + generateSampleMessage( + new protos.google.cloud.kms.v1.CryptoKeyVersion(), + ), + ]; + client.descriptors.page.listCryptoKeyVersions.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listCryptoKeyVersionsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.cloud.kms.v1.CryptoKeyVersion[] = []; + stream.on( + 'data', + (response: protos.google.cloud.kms.v1.CryptoKeyVersion) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + ( + client.descriptors.page.listCryptoKeyVersions + .createStream as SinonStub + ) + .getCall(0) + .calledWith(client.innerApiCalls.listCryptoKeyVersions, request), + ); + assert( + ( + client.descriptors.page.listCryptoKeyVersions + .createStream as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); + + it('invokes listCryptoKeyVersionsStream with error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.ListCryptoKeyVersionsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.ListCryptoKeyVersionsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listCryptoKeyVersions.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listCryptoKeyVersionsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.cloud.kms.v1.CryptoKeyVersion[] = []; + stream.on( + 'data', + (response: protos.google.cloud.kms.v1.CryptoKeyVersion) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + ( + client.descriptors.page.listCryptoKeyVersions + .createStream as SinonStub + ) + .getCall(0) + .calledWith(client.innerApiCalls.listCryptoKeyVersions, request), + ); + assert( + ( + client.descriptors.page.listCryptoKeyVersions + .createStream as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); + + it('uses async iteration with listCryptoKeyVersions without error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.ListCryptoKeyVersionsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.ListCryptoKeyVersionsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.cloud.kms.v1.CryptoKeyVersion(), + ), + generateSampleMessage( + new protos.google.cloud.kms.v1.CryptoKeyVersion(), + ), + generateSampleMessage( + new protos.google.cloud.kms.v1.CryptoKeyVersion(), + ), + ]; + client.descriptors.page.listCryptoKeyVersions.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.cloud.kms.v1.ICryptoKeyVersion[] = []; + const iterable = client.listCryptoKeyVersionsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listCryptoKeyVersions + .asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + ( + client.descriptors.page.listCryptoKeyVersions + .asyncIterate as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); + + it('uses async iteration with listCryptoKeyVersions with error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.ListCryptoKeyVersionsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.ListCryptoKeyVersionsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listCryptoKeyVersions.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listCryptoKeyVersionsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.cloud.kms.v1.ICryptoKeyVersion[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listCryptoKeyVersions + .asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + ( + client.descriptors.page.listCryptoKeyVersions + .asyncIterate as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); + }); + + describe('listImportJobs', () => { + it('invokes listImportJobs without error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.ListImportJobsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.ListImportJobsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.kms.v1.ImportJob()), + generateSampleMessage(new protos.google.cloud.kms.v1.ImportJob()), + generateSampleMessage(new protos.google.cloud.kms.v1.ImportJob()), + ]; + client.innerApiCalls.listImportJobs = stubSimpleCall(expectedResponse); + const [response] = await client.listImportJobs(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listImportJobs as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listImportJobs as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listImportJobs without error using callback', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.ListImportJobsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.ListImportJobsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.kms.v1.ImportJob()), + generateSampleMessage(new protos.google.cloud.kms.v1.ImportJob()), + generateSampleMessage(new protos.google.cloud.kms.v1.ImportJob()), + ]; + client.innerApiCalls.listImportJobs = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listImportJobs( + request, + ( + err?: Error | null, + result?: protos.google.cloud.kms.v1.IImportJob[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listImportJobs as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listImportJobs as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listImportJobs with error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.ListImportJobsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.ListImportJobsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listImportJobs = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listImportJobs(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listImportJobs as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listImportJobs as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listImportJobsStream without error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.ListImportJobsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.ListImportJobsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.kms.v1.ImportJob()), + generateSampleMessage(new protos.google.cloud.kms.v1.ImportJob()), + generateSampleMessage(new protos.google.cloud.kms.v1.ImportJob()), + ]; + client.descriptors.page.listImportJobs.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listImportJobsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.cloud.kms.v1.ImportJob[] = []; + stream.on('data', (response: protos.google.cloud.kms.v1.ImportJob) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listImportJobs.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listImportJobs, request), + ); + assert( + (client.descriptors.page.listImportJobs.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + + it('invokes listImportJobsStream with error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.ListImportJobsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.ListImportJobsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listImportJobs.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listImportJobsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.cloud.kms.v1.ImportJob[] = []; + stream.on('data', (response: protos.google.cloud.kms.v1.ImportJob) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listImportJobs.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listImportJobs, request), + ); + assert( + (client.descriptors.page.listImportJobs.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + + it('uses async iteration with listImportJobs without error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.ListImportJobsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.ListImportJobsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.kms.v1.ImportJob()), + generateSampleMessage(new protos.google.cloud.kms.v1.ImportJob()), + generateSampleMessage(new protos.google.cloud.kms.v1.ImportJob()), + ]; + client.descriptors.page.listImportJobs.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.cloud.kms.v1.IImportJob[] = []; + const iterable = client.listImportJobsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listImportJobs.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listImportJobs.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + + it('uses async iteration with listImportJobs with error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.ListImportJobsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.ListImportJobsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listImportJobs.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listImportJobsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.cloud.kms.v1.IImportJob[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listImportJobs.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listImportJobs.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + }); + describe('getIamPolicy', () => { + it('invokes getIamPolicy without error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new IamProtos.google.iam.v1.GetIamPolicyRequest(), + ); + request.resource = ''; + const expectedHeaderRequestParams = 'resource='; + const expectedOptions = { + otherArgs: { + headers: { + 'x-goog-request-params': expectedHeaderRequestParams, + }, + }, + }; + const expectedResponse = generateSampleMessage( + new IamProtos.google.iam.v1.Policy(), + ); + client.iamClient.getIamPolicy = stubSimpleCall(expectedResponse); + const response = await client.getIamPolicy(request, expectedOptions); + assert.deepStrictEqual(response, [expectedResponse]); + assert( + (client.iamClient.getIamPolicy as SinonStub) + .getCall(0) + .calledWith(request, expectedOptions, undefined), + ); + }); + it('invokes getIamPolicy without error using callback', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new IamProtos.google.iam.v1.GetIamPolicyRequest(), + ); + request.resource = ''; + const expectedHeaderRequestParams = 'resource='; + const expectedOptions = { + otherArgs: { + headers: { + 'x-goog-request-params': expectedHeaderRequestParams, + }, + }, + }; + const expectedResponse = generateSampleMessage( + new IamProtos.google.iam.v1.Policy(), + ); + client.iamClient.getIamPolicy = sinon + .stub() + .callsArgWith(2, null, expectedResponse); + const promise = new Promise((resolve, reject) => { + client + .getIamPolicy( + request, + expectedOptions, + ( + err?: Error | null, + result?: IamProtos.google.iam.v1.Policy | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ) + .catch((err) => { + throw err; + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + assert((client.iamClient.getIamPolicy as SinonStub).getCall(0)); + }); + it('invokes getIamPolicy with error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new IamProtos.google.iam.v1.GetIamPolicyRequest(), + ); + request.resource = ''; + const expectedHeaderRequestParams = 'resource='; + const expectedOptions = { + otherArgs: { + headers: { + 'x-goog-request-params': expectedHeaderRequestParams, + }, + }, + }; + const expectedError = new Error('expected'); + client.iamClient.getIamPolicy = stubSimpleCall(undefined, expectedError); + await assert.rejects( + client.getIamPolicy(request, expectedOptions), + expectedError, + ); + assert( + (client.iamClient.getIamPolicy as SinonStub) + .getCall(0) + .calledWith(request, expectedOptions, undefined), + ); + }); + }); + describe('setIamPolicy', () => { + it('invokes setIamPolicy without error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new IamProtos.google.iam.v1.SetIamPolicyRequest(), + ); + request.resource = ''; + const expectedHeaderRequestParams = 'resource='; + const expectedOptions = { + otherArgs: { + headers: { + 'x-goog-request-params': expectedHeaderRequestParams, + }, + }, + }; + const expectedResponse = generateSampleMessage( + new IamProtos.google.iam.v1.Policy(), + ); + client.iamClient.setIamPolicy = stubSimpleCall(expectedResponse); + const response = await client.setIamPolicy(request, expectedOptions); + assert.deepStrictEqual(response, [expectedResponse]); + assert( + (client.iamClient.setIamPolicy as SinonStub) + .getCall(0) + .calledWith(request, expectedOptions, undefined), + ); + }); + it('invokes setIamPolicy without error using callback', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new IamProtos.google.iam.v1.SetIamPolicyRequest(), + ); + request.resource = ''; + const expectedHeaderRequestParams = 'resource='; + const expectedOptions = { + otherArgs: { + headers: { + 'x-goog-request-params': expectedHeaderRequestParams, + }, + }, + }; + const expectedResponse = generateSampleMessage( + new IamProtos.google.iam.v1.Policy(), + ); + client.iamClient.setIamPolicy = sinon + .stub() + .callsArgWith(2, null, expectedResponse); + const promise = new Promise((resolve, reject) => { + client + .setIamPolicy( + request, + expectedOptions, + ( + err?: Error | null, + result?: IamProtos.google.iam.v1.Policy | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ) + .catch((err) => { + throw err; + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + assert((client.iamClient.setIamPolicy as SinonStub).getCall(0)); + }); + it('invokes setIamPolicy with error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new IamProtos.google.iam.v1.SetIamPolicyRequest(), + ); + request.resource = ''; + const expectedHeaderRequestParams = 'resource='; + const expectedOptions = { + otherArgs: { + headers: { + 'x-goog-request-params': expectedHeaderRequestParams, + }, + }, + }; + const expectedError = new Error('expected'); + client.iamClient.setIamPolicy = stubSimpleCall(undefined, expectedError); + await assert.rejects( + client.setIamPolicy(request, expectedOptions), + expectedError, + ); + assert( + (client.iamClient.setIamPolicy as SinonStub) + .getCall(0) + .calledWith(request, expectedOptions, undefined), + ); + }); + }); + describe('testIamPermissions', () => { + it('invokes testIamPermissions without error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new IamProtos.google.iam.v1.TestIamPermissionsRequest(), + ); + request.resource = ''; + const expectedHeaderRequestParams = 'resource='; + const expectedOptions = { + otherArgs: { + headers: { + 'x-goog-request-params': expectedHeaderRequestParams, + }, + }, + }; + const expectedResponse = generateSampleMessage( + new IamProtos.google.iam.v1.TestIamPermissionsResponse(), + ); + client.iamClient.testIamPermissions = stubSimpleCall(expectedResponse); + const response = await client.testIamPermissions( + request, + expectedOptions, + ); + assert.deepStrictEqual(response, [expectedResponse]); + assert( + (client.iamClient.testIamPermissions as SinonStub) + .getCall(0) + .calledWith(request, expectedOptions, undefined), + ); + }); + it('invokes testIamPermissions without error using callback', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new IamProtos.google.iam.v1.TestIamPermissionsRequest(), + ); + request.resource = ''; + const expectedHeaderRequestParams = 'resource='; + const expectedOptions = { + otherArgs: { + headers: { + 'x-goog-request-params': expectedHeaderRequestParams, + }, + }, + }; + const expectedResponse = generateSampleMessage( + new IamProtos.google.iam.v1.TestIamPermissionsResponse(), + ); + client.iamClient.testIamPermissions = sinon + .stub() + .callsArgWith(2, null, expectedResponse); + const promise = new Promise((resolve, reject) => { + client + .testIamPermissions( + request, + expectedOptions, + ( + err?: Error | null, + result?: IamProtos.google.iam.v1.TestIamPermissionsResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ) + .catch((err) => { + throw err; + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + assert((client.iamClient.testIamPermissions as SinonStub).getCall(0)); + }); + it('invokes testIamPermissions with error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new IamProtos.google.iam.v1.TestIamPermissionsRequest(), + ); + request.resource = ''; + const expectedHeaderRequestParams = 'resource='; + const expectedOptions = { + otherArgs: { + headers: { + 'x-goog-request-params': expectedHeaderRequestParams, + }, + }, + }; + const expectedError = new Error('expected'); + client.iamClient.testIamPermissions = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.testIamPermissions(request, expectedOptions), + expectedError, + ); + assert( + (client.iamClient.testIamPermissions as SinonStub) + .getCall(0) + .calledWith(request, expectedOptions, undefined), + ); }); + }); }); diff --git a/core/generator/gapic-generator-typescript/baselines/kms/src/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/kms/src/index.ts.baseline index 8b85dab08172..a3663835d202 100644 --- a/core/generator/gapic-generator-typescript/baselines/kms/src/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/kms/src/index.ts.baseline @@ -19,7 +19,7 @@ import * as v1 from './v1'; const KeyManagementServiceClient = v1.KeyManagementServiceClient; type KeyManagementServiceClient = v1.KeyManagementServiceClient; -export {v1, KeyManagementServiceClient}; -export default {v1, KeyManagementServiceClient}; +export { v1, KeyManagementServiceClient }; +export default { v1, KeyManagementServiceClient }; import * as protos from '../protos/protos'; -export {protos} +export { protos }; diff --git a/core/generator/gapic-generator-typescript/baselines/kms/src/v1/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/kms/src/v1/index.ts.baseline index 5238b41c0fc5..f5e55d595763 100644 --- a/core/generator/gapic-generator-typescript/baselines/kms/src/v1/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/kms/src/v1/index.ts.baseline @@ -16,4 +16,4 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -export {KeyManagementServiceClient} from './key_management_service_client'; +export { KeyManagementServiceClient } from './key_management_service_client'; diff --git a/core/generator/gapic-generator-typescript/baselines/kms/src/v1/key_management_service_client.ts.baseline b/core/generator/gapic-generator-typescript/baselines/kms/src/v1/key_management_service_client.ts.baseline index 5ab7909bf3b5..09a02f6b5c12 100644 --- a/core/generator/gapic-generator-typescript/baselines/kms/src/v1/key_management_service_client.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/kms/src/v1/key_management_service_client.ts.baseline @@ -18,11 +18,20 @@ /* global window */ import type * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions, PaginationCallback, GaxCall, IamClient, IamProtos} from 'google-gax'; -import {Transform} from 'stream'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + PaginationCallback, + GaxCall, + IamClient, + IamProtos, +} from 'google-gax'; +import { Transform } from 'stream'; import * as protos from '../../protos/protos'; import jsonProtos = require('../../protos/protos.json'); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; /** * Client JSON configuration object, loaded from @@ -54,7 +63,7 @@ export class KeyManagementServiceClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('kms'); @@ -67,9 +76,9 @@ export class KeyManagementServiceClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; + innerApiCalls: { [name: string]: Function }; iamClient: IamClient; - keyManagementServiceStub?: Promise<{[name: string]: Function}>; + keyManagementServiceStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of KeyManagementServiceClient. @@ -110,21 +119,42 @@ export class KeyManagementServiceClient { * const client = new KeyManagementServiceClient({fallback: true}, gax); * ``` */ - constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { // Ensure that options include all the required fields. const staticMembers = this.constructor as typeof KeyManagementServiceClient; - if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { - throw new Error('Please set either universe_domain or universeDomain, but not both.'); + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); } - const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; - this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; this._servicePath = 'cloudkms.' + this._universeDomain; - const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; - const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. if (servicePath !== this._servicePath && !('scopes' in opts)) { @@ -146,7 +176,7 @@ export class KeyManagementServiceClient { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; @@ -159,13 +189,9 @@ export class KeyManagementServiceClient { this.auth.defaultScopes = staticMembers.scopes; } this.iamClient = new this._gaxModule.IamClient(this._gaxGrpc, opts); - // Determine the client header string. - const clientHeader = [ - `gax/${this._gaxModule.version}`, - `gapic/${version}`, - ]; + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/${process.versions.node}`); } else { @@ -186,20 +212,35 @@ export class KeyManagementServiceClient { // (e.g. 50 results at a time, with tokens to get subsequent // pages). Denote the keys used for pagination and results. this.descriptors.page = { - listKeyRings: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'keyRings'), - listCryptoKeys: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'cryptoKeys'), - listCryptoKeyVersions: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'cryptoKeyVersions'), - listImportJobs: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'importJobs') + listKeyRings: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'keyRings', + ), + listCryptoKeys: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'cryptoKeys', + ), + listCryptoKeyVersions: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'cryptoKeyVersions', + ), + listImportJobs: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'importJobs', + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.cloud.kms.v1.KeyManagementService', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.cloud.kms.v1.KeyManagementService', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + { 'x-goog-api-client': clientHeader.join(' ') }, + ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -230,37 +271,64 @@ export class KeyManagementServiceClient { // Put together the "service stub" for // google.cloud.kms.v1.KeyManagementService. this.keyManagementServiceStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.cloud.kms.v1.KeyManagementService') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.cloud.kms.v1.KeyManagementService', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.cloud.kms.v1.KeyManagementService, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts, + this._providedCustomServicePath, + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const keyManagementServiceStubMethods = - ['listKeyRings', 'listCryptoKeys', 'listCryptoKeyVersions', 'listImportJobs', 'getKeyRing', 'getCryptoKey', 'getCryptoKeyVersion', 'getPublicKey', 'getImportJob', 'createKeyRing', 'createCryptoKey', 'createCryptoKeyVersion', 'importCryptoKeyVersion', 'createImportJob', 'updateCryptoKey', 'updateCryptoKeyVersion', 'encrypt', 'decrypt', 'asymmetricSign', 'asymmetricDecrypt', 'updateCryptoKeyPrimaryVersion', 'destroyCryptoKeyVersion', 'restoreCryptoKeyVersion']; + const keyManagementServiceStubMethods = [ + 'listKeyRings', + 'listCryptoKeys', + 'listCryptoKeyVersions', + 'listImportJobs', + 'getKeyRing', + 'getCryptoKey', + 'getCryptoKeyVersion', + 'getPublicKey', + 'getImportJob', + 'createKeyRing', + 'createCryptoKey', + 'createCryptoKeyVersion', + 'importCryptoKeyVersion', + 'createImportJob', + 'updateCryptoKey', + 'updateCryptoKeyVersion', + 'encrypt', + 'decrypt', + 'asymmetricSign', + 'asymmetricDecrypt', + 'updateCryptoKeyPrimaryVersion', + 'destroyCryptoKeyVersion', + 'restoreCryptoKeyVersion', + ]; for (const methodName of keyManagementServiceStubMethods) { const callPromise = this.keyManagementServiceStub.then( - stub => (...args: Array<{}>) => { - if (this._terminated) { - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error|null|undefined) => () => { + (stub) => + (...args: Array<{}>) => { + if (this._terminated) { + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { throw err; - }); + }, + ); - const descriptor = - this.descriptors.page[methodName] || - undefined; + const descriptor = this.descriptors.page[methodName] || undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -275,8 +343,14 @@ export class KeyManagementServiceClient { * @returns {string} The DNS address for this service. */ static get servicePath() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'cloudkms.googleapis.com'; } @@ -287,8 +361,14 @@ export class KeyManagementServiceClient { * @returns {string} The DNS address for this service. */ static get apiEndpoint() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'cloudkms.googleapis.com'; } @@ -321,7 +401,7 @@ export class KeyManagementServiceClient { static get scopes() { return [ 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloudkms' + 'https://www.googleapis.com/auth/cloudkms', ]; } @@ -331,8 +411,9 @@ export class KeyManagementServiceClient { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId(callback?: Callback): - Promise|void { + getProjectId( + callback?: Callback, + ): Promise | void { if (callback) { this.auth.getProjectId(callback); return; @@ -343,2034 +424,2702 @@ export class KeyManagementServiceClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Returns metadata for a given {@link protos.google.cloud.kms.v1.KeyRing|KeyRing}. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * The {@link protos.google.cloud.kms.v1.KeyRing.name|name} of the {@link protos.google.cloud.kms.v1.KeyRing|KeyRing} to get. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.kms.v1.KeyRing|KeyRing}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1/key_management_service.get_key_ring.js - * region_tag:cloudkms_v1_generated_KeyManagementService_GetKeyRing_async - */ + /** + * Returns metadata for a given {@link protos.google.cloud.kms.v1.KeyRing|KeyRing}. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * The {@link protos.google.cloud.kms.v1.KeyRing.name|name} of the {@link protos.google.cloud.kms.v1.KeyRing|KeyRing} to get. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.kms.v1.KeyRing|KeyRing}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/key_management_service.get_key_ring.js + * region_tag:cloudkms_v1_generated_KeyManagementService_GetKeyRing_async + */ getKeyRing( - request?: protos.google.cloud.kms.v1.IGetKeyRingRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.kms.v1.IKeyRing, - protos.google.cloud.kms.v1.IGetKeyRingRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.kms.v1.IGetKeyRingRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.kms.v1.IKeyRing, + protos.google.cloud.kms.v1.IGetKeyRingRequest | undefined, + {} | undefined, + ] + >; getKeyRing( - request: protos.google.cloud.kms.v1.IGetKeyRingRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.kms.v1.IKeyRing, - protos.google.cloud.kms.v1.IGetKeyRingRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.kms.v1.IGetKeyRingRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.kms.v1.IKeyRing, + protos.google.cloud.kms.v1.IGetKeyRingRequest | null | undefined, + {} | null | undefined + >, + ): void; getKeyRing( - request: protos.google.cloud.kms.v1.IGetKeyRingRequest, - callback: Callback< - protos.google.cloud.kms.v1.IKeyRing, - protos.google.cloud.kms.v1.IGetKeyRingRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.kms.v1.IGetKeyRingRequest, + callback: Callback< + protos.google.cloud.kms.v1.IKeyRing, + protos.google.cloud.kms.v1.IGetKeyRingRequest | null | undefined, + {} | null | undefined + >, + ): void; getKeyRing( - request?: protos.google.cloud.kms.v1.IGetKeyRingRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.kms.v1.IKeyRing, - protos.google.cloud.kms.v1.IGetKeyRingRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.kms.v1.IGetKeyRingRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.kms.v1.IKeyRing, - protos.google.cloud.kms.v1.IGetKeyRingRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.kms.v1.IKeyRing, - protos.google.cloud.kms.v1.IGetKeyRingRequest|undefined, {}|undefined - ]>|void { + protos.google.cloud.kms.v1.IGetKeyRingRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.kms.v1.IKeyRing, + protos.google.cloud.kms.v1.IGetKeyRingRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.kms.v1.IKeyRing, + protos.google.cloud.kms.v1.IGetKeyRingRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getKeyRing request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.kms.v1.IKeyRing, - protos.google.cloud.kms.v1.IGetKeyRingRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.kms.v1.IKeyRing, + protos.google.cloud.kms.v1.IGetKeyRingRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getKeyRing response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getKeyRing(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.kms.v1.IKeyRing, - protos.google.cloud.kms.v1.IGetKeyRingRequest|undefined, - {}|undefined - ]) => { - this._log.info('getKeyRing response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getKeyRing(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.kms.v1.IKeyRing, + protos.google.cloud.kms.v1.IGetKeyRingRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getKeyRing response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Returns metadata for a given {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKey}, as well as its - * {@link protos.google.cloud.kms.v1.CryptoKey.primary|primary} {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersion}. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * The {@link protos.google.cloud.kms.v1.CryptoKey.name|name} of the {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKey} to get. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKey}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1/key_management_service.get_crypto_key.js - * region_tag:cloudkms_v1_generated_KeyManagementService_GetCryptoKey_async - */ + /** + * Returns metadata for a given {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKey}, as well as its + * {@link protos.google.cloud.kms.v1.CryptoKey.primary|primary} {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersion}. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * The {@link protos.google.cloud.kms.v1.CryptoKey.name|name} of the {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKey} to get. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKey}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/key_management_service.get_crypto_key.js + * region_tag:cloudkms_v1_generated_KeyManagementService_GetCryptoKey_async + */ getCryptoKey( - request?: protos.google.cloud.kms.v1.IGetCryptoKeyRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.kms.v1.ICryptoKey, - protos.google.cloud.kms.v1.IGetCryptoKeyRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.kms.v1.IGetCryptoKeyRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.kms.v1.ICryptoKey, + protos.google.cloud.kms.v1.IGetCryptoKeyRequest | undefined, + {} | undefined, + ] + >; getCryptoKey( - request: protos.google.cloud.kms.v1.IGetCryptoKeyRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.kms.v1.ICryptoKey, - protos.google.cloud.kms.v1.IGetCryptoKeyRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.kms.v1.IGetCryptoKeyRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.kms.v1.ICryptoKey, + protos.google.cloud.kms.v1.IGetCryptoKeyRequest | null | undefined, + {} | null | undefined + >, + ): void; getCryptoKey( - request: protos.google.cloud.kms.v1.IGetCryptoKeyRequest, - callback: Callback< - protos.google.cloud.kms.v1.ICryptoKey, - protos.google.cloud.kms.v1.IGetCryptoKeyRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.kms.v1.IGetCryptoKeyRequest, + callback: Callback< + protos.google.cloud.kms.v1.ICryptoKey, + protos.google.cloud.kms.v1.IGetCryptoKeyRequest | null | undefined, + {} | null | undefined + >, + ): void; getCryptoKey( - request?: protos.google.cloud.kms.v1.IGetCryptoKeyRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.kms.v1.ICryptoKey, - protos.google.cloud.kms.v1.IGetCryptoKeyRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.kms.v1.IGetCryptoKeyRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.kms.v1.ICryptoKey, - protos.google.cloud.kms.v1.IGetCryptoKeyRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.kms.v1.ICryptoKey, - protos.google.cloud.kms.v1.IGetCryptoKeyRequest|undefined, {}|undefined - ]>|void { + protos.google.cloud.kms.v1.IGetCryptoKeyRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.kms.v1.ICryptoKey, + protos.google.cloud.kms.v1.IGetCryptoKeyRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.kms.v1.ICryptoKey, + protos.google.cloud.kms.v1.IGetCryptoKeyRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getCryptoKey request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.kms.v1.ICryptoKey, - protos.google.cloud.kms.v1.IGetCryptoKeyRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.kms.v1.ICryptoKey, + protos.google.cloud.kms.v1.IGetCryptoKeyRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getCryptoKey response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getCryptoKey(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.kms.v1.ICryptoKey, - protos.google.cloud.kms.v1.IGetCryptoKeyRequest|undefined, - {}|undefined - ]) => { - this._log.info('getCryptoKey response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getCryptoKey(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.kms.v1.ICryptoKey, + protos.google.cloud.kms.v1.IGetCryptoKeyRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getCryptoKey response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Returns metadata for a given {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersion}. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * The {@link protos.google.cloud.kms.v1.CryptoKeyVersion.name|name} of the {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersion} to get. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersion}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1/key_management_service.get_crypto_key_version.js - * region_tag:cloudkms_v1_generated_KeyManagementService_GetCryptoKeyVersion_async - */ + /** + * Returns metadata for a given {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersion}. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * The {@link protos.google.cloud.kms.v1.CryptoKeyVersion.name|name} of the {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersion} to get. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersion}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/key_management_service.get_crypto_key_version.js + * region_tag:cloudkms_v1_generated_KeyManagementService_GetCryptoKeyVersion_async + */ getCryptoKeyVersion( - request?: protos.google.cloud.kms.v1.IGetCryptoKeyVersionRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.kms.v1.ICryptoKeyVersion, - protos.google.cloud.kms.v1.IGetCryptoKeyVersionRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.kms.v1.IGetCryptoKeyVersionRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.kms.v1.ICryptoKeyVersion, + protos.google.cloud.kms.v1.IGetCryptoKeyVersionRequest | undefined, + {} | undefined, + ] + >; getCryptoKeyVersion( - request: protos.google.cloud.kms.v1.IGetCryptoKeyVersionRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.kms.v1.ICryptoKeyVersion, - protos.google.cloud.kms.v1.IGetCryptoKeyVersionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.kms.v1.IGetCryptoKeyVersionRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.kms.v1.ICryptoKeyVersion, + protos.google.cloud.kms.v1.IGetCryptoKeyVersionRequest | null | undefined, + {} | null | undefined + >, + ): void; getCryptoKeyVersion( - request: protos.google.cloud.kms.v1.IGetCryptoKeyVersionRequest, - callback: Callback< - protos.google.cloud.kms.v1.ICryptoKeyVersion, - protos.google.cloud.kms.v1.IGetCryptoKeyVersionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.kms.v1.IGetCryptoKeyVersionRequest, + callback: Callback< + protos.google.cloud.kms.v1.ICryptoKeyVersion, + protos.google.cloud.kms.v1.IGetCryptoKeyVersionRequest | null | undefined, + {} | null | undefined + >, + ): void; getCryptoKeyVersion( - request?: protos.google.cloud.kms.v1.IGetCryptoKeyVersionRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.kms.v1.ICryptoKeyVersion, - protos.google.cloud.kms.v1.IGetCryptoKeyVersionRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.kms.v1.IGetCryptoKeyVersionRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.kms.v1.ICryptoKeyVersion, - protos.google.cloud.kms.v1.IGetCryptoKeyVersionRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.kms.v1.ICryptoKeyVersion, - protos.google.cloud.kms.v1.IGetCryptoKeyVersionRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.kms.v1.IGetCryptoKeyVersionRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.kms.v1.ICryptoKeyVersion, + protos.google.cloud.kms.v1.IGetCryptoKeyVersionRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.kms.v1.ICryptoKeyVersion, + protos.google.cloud.kms.v1.IGetCryptoKeyVersionRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getCryptoKeyVersion request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.kms.v1.ICryptoKeyVersion, - protos.google.cloud.kms.v1.IGetCryptoKeyVersionRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.kms.v1.ICryptoKeyVersion, + | protos.google.cloud.kms.v1.IGetCryptoKeyVersionRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getCryptoKeyVersion response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getCryptoKeyVersion(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.kms.v1.ICryptoKeyVersion, - protos.google.cloud.kms.v1.IGetCryptoKeyVersionRequest|undefined, - {}|undefined - ]) => { - this._log.info('getCryptoKeyVersion response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getCryptoKeyVersion(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.kms.v1.ICryptoKeyVersion, + protos.google.cloud.kms.v1.IGetCryptoKeyVersionRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getCryptoKeyVersion response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Returns the public key for the given {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersion}. The - * {@link protos.google.cloud.kms.v1.CryptoKey.purpose|CryptoKey.purpose} must be - * {@link protos.google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ASYMMETRIC_SIGN|ASYMMETRIC_SIGN} or - * {@link protos.google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ASYMMETRIC_DECRYPT|ASYMMETRIC_DECRYPT}. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * The {@link protos.google.cloud.kms.v1.CryptoKeyVersion.name|name} of the {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersion} public key to - * get. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.kms.v1.PublicKey|PublicKey}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1/key_management_service.get_public_key.js - * region_tag:cloudkms_v1_generated_KeyManagementService_GetPublicKey_async - */ + /** + * Returns the public key for the given {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersion}. The + * {@link protos.google.cloud.kms.v1.CryptoKey.purpose|CryptoKey.purpose} must be + * {@link protos.google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ASYMMETRIC_SIGN|ASYMMETRIC_SIGN} or + * {@link protos.google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ASYMMETRIC_DECRYPT|ASYMMETRIC_DECRYPT}. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * The {@link protos.google.cloud.kms.v1.CryptoKeyVersion.name|name} of the {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersion} public key to + * get. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.kms.v1.PublicKey|PublicKey}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/key_management_service.get_public_key.js + * region_tag:cloudkms_v1_generated_KeyManagementService_GetPublicKey_async + */ getPublicKey( - request?: protos.google.cloud.kms.v1.IGetPublicKeyRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.kms.v1.IPublicKey, - protos.google.cloud.kms.v1.IGetPublicKeyRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.kms.v1.IGetPublicKeyRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.kms.v1.IPublicKey, + protos.google.cloud.kms.v1.IGetPublicKeyRequest | undefined, + {} | undefined, + ] + >; getPublicKey( - request: protos.google.cloud.kms.v1.IGetPublicKeyRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.kms.v1.IPublicKey, - protos.google.cloud.kms.v1.IGetPublicKeyRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.kms.v1.IGetPublicKeyRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.kms.v1.IPublicKey, + protos.google.cloud.kms.v1.IGetPublicKeyRequest | null | undefined, + {} | null | undefined + >, + ): void; getPublicKey( - request: protos.google.cloud.kms.v1.IGetPublicKeyRequest, - callback: Callback< - protos.google.cloud.kms.v1.IPublicKey, - protos.google.cloud.kms.v1.IGetPublicKeyRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.kms.v1.IGetPublicKeyRequest, + callback: Callback< + protos.google.cloud.kms.v1.IPublicKey, + protos.google.cloud.kms.v1.IGetPublicKeyRequest | null | undefined, + {} | null | undefined + >, + ): void; getPublicKey( - request?: protos.google.cloud.kms.v1.IGetPublicKeyRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.kms.v1.IPublicKey, - protos.google.cloud.kms.v1.IGetPublicKeyRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.kms.v1.IGetPublicKeyRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.kms.v1.IPublicKey, - protos.google.cloud.kms.v1.IGetPublicKeyRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.kms.v1.IPublicKey, - protos.google.cloud.kms.v1.IGetPublicKeyRequest|undefined, {}|undefined - ]>|void { + protos.google.cloud.kms.v1.IGetPublicKeyRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.kms.v1.IPublicKey, + protos.google.cloud.kms.v1.IGetPublicKeyRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.kms.v1.IPublicKey, + protos.google.cloud.kms.v1.IGetPublicKeyRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getPublicKey request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.kms.v1.IPublicKey, - protos.google.cloud.kms.v1.IGetPublicKeyRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.kms.v1.IPublicKey, + protos.google.cloud.kms.v1.IGetPublicKeyRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getPublicKey response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getPublicKey(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.kms.v1.IPublicKey, - protos.google.cloud.kms.v1.IGetPublicKeyRequest|undefined, - {}|undefined - ]) => { - this._log.info('getPublicKey response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getPublicKey(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.kms.v1.IPublicKey, + protos.google.cloud.kms.v1.IGetPublicKeyRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getPublicKey response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Returns metadata for a given {@link protos.google.cloud.kms.v1.ImportJob|ImportJob}. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * The {@link protos.google.cloud.kms.v1.ImportJob.name|name} of the {@link protos.google.cloud.kms.v1.ImportJob|ImportJob} to get. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.kms.v1.ImportJob|ImportJob}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1/key_management_service.get_import_job.js - * region_tag:cloudkms_v1_generated_KeyManagementService_GetImportJob_async - */ + /** + * Returns metadata for a given {@link protos.google.cloud.kms.v1.ImportJob|ImportJob}. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * The {@link protos.google.cloud.kms.v1.ImportJob.name|name} of the {@link protos.google.cloud.kms.v1.ImportJob|ImportJob} to get. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.kms.v1.ImportJob|ImportJob}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/key_management_service.get_import_job.js + * region_tag:cloudkms_v1_generated_KeyManagementService_GetImportJob_async + */ getImportJob( - request?: protos.google.cloud.kms.v1.IGetImportJobRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.kms.v1.IImportJob, - protos.google.cloud.kms.v1.IGetImportJobRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.kms.v1.IGetImportJobRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.kms.v1.IImportJob, + protos.google.cloud.kms.v1.IGetImportJobRequest | undefined, + {} | undefined, + ] + >; getImportJob( - request: protos.google.cloud.kms.v1.IGetImportJobRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.kms.v1.IImportJob, - protos.google.cloud.kms.v1.IGetImportJobRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.kms.v1.IGetImportJobRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.kms.v1.IImportJob, + protos.google.cloud.kms.v1.IGetImportJobRequest | null | undefined, + {} | null | undefined + >, + ): void; getImportJob( - request: protos.google.cloud.kms.v1.IGetImportJobRequest, - callback: Callback< - protos.google.cloud.kms.v1.IImportJob, - protos.google.cloud.kms.v1.IGetImportJobRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.kms.v1.IGetImportJobRequest, + callback: Callback< + protos.google.cloud.kms.v1.IImportJob, + protos.google.cloud.kms.v1.IGetImportJobRequest | null | undefined, + {} | null | undefined + >, + ): void; getImportJob( - request?: protos.google.cloud.kms.v1.IGetImportJobRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.kms.v1.IImportJob, - protos.google.cloud.kms.v1.IGetImportJobRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.kms.v1.IGetImportJobRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.kms.v1.IImportJob, - protos.google.cloud.kms.v1.IGetImportJobRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.kms.v1.IImportJob, - protos.google.cloud.kms.v1.IGetImportJobRequest|undefined, {}|undefined - ]>|void { + protos.google.cloud.kms.v1.IGetImportJobRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.kms.v1.IImportJob, + protos.google.cloud.kms.v1.IGetImportJobRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.kms.v1.IImportJob, + protos.google.cloud.kms.v1.IGetImportJobRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getImportJob request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.kms.v1.IImportJob, - protos.google.cloud.kms.v1.IGetImportJobRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.kms.v1.IImportJob, + protos.google.cloud.kms.v1.IGetImportJobRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getImportJob response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getImportJob(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.kms.v1.IImportJob, - protos.google.cloud.kms.v1.IGetImportJobRequest|undefined, - {}|undefined - ]) => { - this._log.info('getImportJob response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getImportJob(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.kms.v1.IImportJob, + protos.google.cloud.kms.v1.IGetImportJobRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getImportJob response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Create a new {@link protos.google.cloud.kms.v1.KeyRing|KeyRing} in a given Project and Location. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The resource name of the location associated with the - * {@link protos.google.cloud.kms.v1.KeyRing|KeyRings}, in the format `projects/* /locations/*`. - * @param {string} request.keyRingId - * Required. It must be unique within a location and match the regular - * expression `[a-zA-Z0-9_-]{1,63}` - * @param {google.cloud.kms.v1.KeyRing} request.keyRing - * A {@link protos.google.cloud.kms.v1.KeyRing|KeyRing} with initial field values. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.kms.v1.KeyRing|KeyRing}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1/key_management_service.create_key_ring.js - * region_tag:cloudkms_v1_generated_KeyManagementService_CreateKeyRing_async - */ + /** + * Create a new {@link protos.google.cloud.kms.v1.KeyRing|KeyRing} in a given Project and Location. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The resource name of the location associated with the + * {@link protos.google.cloud.kms.v1.KeyRing|KeyRings}, in the format `projects/* /locations/*`. + * @param {string} request.keyRingId + * Required. It must be unique within a location and match the regular + * expression `[a-zA-Z0-9_-]{1,63}` + * @param {google.cloud.kms.v1.KeyRing} request.keyRing + * A {@link protos.google.cloud.kms.v1.KeyRing|KeyRing} with initial field values. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.kms.v1.KeyRing|KeyRing}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/key_management_service.create_key_ring.js + * region_tag:cloudkms_v1_generated_KeyManagementService_CreateKeyRing_async + */ createKeyRing( - request?: protos.google.cloud.kms.v1.ICreateKeyRingRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.kms.v1.IKeyRing, - protos.google.cloud.kms.v1.ICreateKeyRingRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.kms.v1.ICreateKeyRingRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.kms.v1.IKeyRing, + protos.google.cloud.kms.v1.ICreateKeyRingRequest | undefined, + {} | undefined, + ] + >; createKeyRing( - request: protos.google.cloud.kms.v1.ICreateKeyRingRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.kms.v1.IKeyRing, - protos.google.cloud.kms.v1.ICreateKeyRingRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.kms.v1.ICreateKeyRingRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.kms.v1.IKeyRing, + protos.google.cloud.kms.v1.ICreateKeyRingRequest | null | undefined, + {} | null | undefined + >, + ): void; createKeyRing( - request: protos.google.cloud.kms.v1.ICreateKeyRingRequest, - callback: Callback< - protos.google.cloud.kms.v1.IKeyRing, - protos.google.cloud.kms.v1.ICreateKeyRingRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.kms.v1.ICreateKeyRingRequest, + callback: Callback< + protos.google.cloud.kms.v1.IKeyRing, + protos.google.cloud.kms.v1.ICreateKeyRingRequest | null | undefined, + {} | null | undefined + >, + ): void; createKeyRing( - request?: protos.google.cloud.kms.v1.ICreateKeyRingRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.kms.v1.IKeyRing, - protos.google.cloud.kms.v1.ICreateKeyRingRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.kms.v1.ICreateKeyRingRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.kms.v1.IKeyRing, - protos.google.cloud.kms.v1.ICreateKeyRingRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.kms.v1.IKeyRing, - protos.google.cloud.kms.v1.ICreateKeyRingRequest|undefined, {}|undefined - ]>|void { + protos.google.cloud.kms.v1.ICreateKeyRingRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.kms.v1.IKeyRing, + protos.google.cloud.kms.v1.ICreateKeyRingRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.kms.v1.IKeyRing, + protos.google.cloud.kms.v1.ICreateKeyRingRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('createKeyRing request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.kms.v1.IKeyRing, - protos.google.cloud.kms.v1.ICreateKeyRingRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.kms.v1.IKeyRing, + protos.google.cloud.kms.v1.ICreateKeyRingRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createKeyRing response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.createKeyRing(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.kms.v1.IKeyRing, - protos.google.cloud.kms.v1.ICreateKeyRingRequest|undefined, - {}|undefined - ]) => { - this._log.info('createKeyRing response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createKeyRing(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.kms.v1.IKeyRing, + protos.google.cloud.kms.v1.ICreateKeyRingRequest | undefined, + {} | undefined, + ]) => { + this._log.info('createKeyRing response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Create a new {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKey} within a {@link protos.google.cloud.kms.v1.KeyRing|KeyRing}. - * - * {@link protos.google.cloud.kms.v1.CryptoKey.purpose|CryptoKey.purpose} and - * {@link protos.google.cloud.kms.v1.CryptoKeyVersionTemplate.algorithm|CryptoKey.version_template.algorithm} - * are required. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The {@link protos.google.cloud.kms.v1.KeyRing.name|name} of the KeyRing associated with the - * {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKeys}. - * @param {string} request.cryptoKeyId - * Required. It must be unique within a KeyRing and match the regular - * expression `[a-zA-Z0-9_-]{1,63}` - * @param {google.cloud.kms.v1.CryptoKey} request.cryptoKey - * A {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKey} with initial field values. - * @param {boolean} request.skipInitialVersionCreation - * If set to true, the request will create a {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKey} without any - * {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersions}. You must manually call - * {@link protos.google.cloud.kms.v1.KeyManagementService.CreateCryptoKeyVersion|CreateCryptoKeyVersion} or - * {@link protos.google.cloud.kms.v1.KeyManagementService.ImportCryptoKeyVersion|ImportCryptoKeyVersion} - * before you can use this {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKey}. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKey}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1/key_management_service.create_crypto_key.js - * region_tag:cloudkms_v1_generated_KeyManagementService_CreateCryptoKey_async - */ + /** + * Create a new {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKey} within a {@link protos.google.cloud.kms.v1.KeyRing|KeyRing}. + * + * {@link protos.google.cloud.kms.v1.CryptoKey.purpose|CryptoKey.purpose} and + * {@link protos.google.cloud.kms.v1.CryptoKeyVersionTemplate.algorithm|CryptoKey.version_template.algorithm} + * are required. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The {@link protos.google.cloud.kms.v1.KeyRing.name|name} of the KeyRing associated with the + * {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKeys}. + * @param {string} request.cryptoKeyId + * Required. It must be unique within a KeyRing and match the regular + * expression `[a-zA-Z0-9_-]{1,63}` + * @param {google.cloud.kms.v1.CryptoKey} request.cryptoKey + * A {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKey} with initial field values. + * @param {boolean} request.skipInitialVersionCreation + * If set to true, the request will create a {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKey} without any + * {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersions}. You must manually call + * {@link protos.google.cloud.kms.v1.KeyManagementService.CreateCryptoKeyVersion|CreateCryptoKeyVersion} or + * {@link protos.google.cloud.kms.v1.KeyManagementService.ImportCryptoKeyVersion|ImportCryptoKeyVersion} + * before you can use this {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKey}. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKey}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/key_management_service.create_crypto_key.js + * region_tag:cloudkms_v1_generated_KeyManagementService_CreateCryptoKey_async + */ createCryptoKey( - request?: protos.google.cloud.kms.v1.ICreateCryptoKeyRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.kms.v1.ICryptoKey, - protos.google.cloud.kms.v1.ICreateCryptoKeyRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.kms.v1.ICreateCryptoKeyRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.kms.v1.ICryptoKey, + protos.google.cloud.kms.v1.ICreateCryptoKeyRequest | undefined, + {} | undefined, + ] + >; createCryptoKey( - request: protos.google.cloud.kms.v1.ICreateCryptoKeyRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.kms.v1.ICryptoKey, - protos.google.cloud.kms.v1.ICreateCryptoKeyRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.kms.v1.ICreateCryptoKeyRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.kms.v1.ICryptoKey, + protos.google.cloud.kms.v1.ICreateCryptoKeyRequest | null | undefined, + {} | null | undefined + >, + ): void; createCryptoKey( - request: protos.google.cloud.kms.v1.ICreateCryptoKeyRequest, - callback: Callback< - protos.google.cloud.kms.v1.ICryptoKey, - protos.google.cloud.kms.v1.ICreateCryptoKeyRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.kms.v1.ICreateCryptoKeyRequest, + callback: Callback< + protos.google.cloud.kms.v1.ICryptoKey, + protos.google.cloud.kms.v1.ICreateCryptoKeyRequest | null | undefined, + {} | null | undefined + >, + ): void; createCryptoKey( - request?: protos.google.cloud.kms.v1.ICreateCryptoKeyRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.kms.v1.ICryptoKey, - protos.google.cloud.kms.v1.ICreateCryptoKeyRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.kms.v1.ICreateCryptoKeyRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.kms.v1.ICryptoKey, - protos.google.cloud.kms.v1.ICreateCryptoKeyRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.kms.v1.ICryptoKey, - protos.google.cloud.kms.v1.ICreateCryptoKeyRequest|undefined, {}|undefined - ]>|void { + protos.google.cloud.kms.v1.ICreateCryptoKeyRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.kms.v1.ICryptoKey, + protos.google.cloud.kms.v1.ICreateCryptoKeyRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.kms.v1.ICryptoKey, + protos.google.cloud.kms.v1.ICreateCryptoKeyRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('createCryptoKey request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.kms.v1.ICryptoKey, - protos.google.cloud.kms.v1.ICreateCryptoKeyRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.kms.v1.ICryptoKey, + protos.google.cloud.kms.v1.ICreateCryptoKeyRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createCryptoKey response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.createCryptoKey(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.kms.v1.ICryptoKey, - protos.google.cloud.kms.v1.ICreateCryptoKeyRequest|undefined, - {}|undefined - ]) => { - this._log.info('createCryptoKey response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createCryptoKey(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.kms.v1.ICryptoKey, + protos.google.cloud.kms.v1.ICreateCryptoKeyRequest | undefined, + {} | undefined, + ]) => { + this._log.info('createCryptoKey response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Create a new {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersion} in a {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKey}. - * - * The server will assign the next sequential id. If unset, - * {@link protos.google.cloud.kms.v1.CryptoKeyVersion.state|state} will be set to - * {@link protos.google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED|ENABLED}. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The {@link protos.google.cloud.kms.v1.CryptoKey.name|name} of the {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKey} associated with - * the {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersions}. - * @param {google.cloud.kms.v1.CryptoKeyVersion} request.cryptoKeyVersion - * A {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersion} with initial field values. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersion}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1/key_management_service.create_crypto_key_version.js - * region_tag:cloudkms_v1_generated_KeyManagementService_CreateCryptoKeyVersion_async - */ + /** + * Create a new {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersion} in a {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKey}. + * + * The server will assign the next sequential id. If unset, + * {@link protos.google.cloud.kms.v1.CryptoKeyVersion.state|state} will be set to + * {@link protos.google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED|ENABLED}. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The {@link protos.google.cloud.kms.v1.CryptoKey.name|name} of the {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKey} associated with + * the {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersions}. + * @param {google.cloud.kms.v1.CryptoKeyVersion} request.cryptoKeyVersion + * A {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersion} with initial field values. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersion}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/key_management_service.create_crypto_key_version.js + * region_tag:cloudkms_v1_generated_KeyManagementService_CreateCryptoKeyVersion_async + */ createCryptoKeyVersion( - request?: protos.google.cloud.kms.v1.ICreateCryptoKeyVersionRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.kms.v1.ICryptoKeyVersion, - protos.google.cloud.kms.v1.ICreateCryptoKeyVersionRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.kms.v1.ICreateCryptoKeyVersionRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.kms.v1.ICryptoKeyVersion, + protos.google.cloud.kms.v1.ICreateCryptoKeyVersionRequest | undefined, + {} | undefined, + ] + >; createCryptoKeyVersion( - request: protos.google.cloud.kms.v1.ICreateCryptoKeyVersionRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.kms.v1.ICryptoKeyVersion, - protos.google.cloud.kms.v1.ICreateCryptoKeyVersionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.kms.v1.ICreateCryptoKeyVersionRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.kms.v1.ICryptoKeyVersion, + | protos.google.cloud.kms.v1.ICreateCryptoKeyVersionRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createCryptoKeyVersion( - request: protos.google.cloud.kms.v1.ICreateCryptoKeyVersionRequest, - callback: Callback< - protos.google.cloud.kms.v1.ICryptoKeyVersion, - protos.google.cloud.kms.v1.ICreateCryptoKeyVersionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.kms.v1.ICreateCryptoKeyVersionRequest, + callback: Callback< + protos.google.cloud.kms.v1.ICryptoKeyVersion, + | protos.google.cloud.kms.v1.ICreateCryptoKeyVersionRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createCryptoKeyVersion( - request?: protos.google.cloud.kms.v1.ICreateCryptoKeyVersionRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.kms.v1.ICryptoKeyVersion, - protos.google.cloud.kms.v1.ICreateCryptoKeyVersionRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.kms.v1.ICreateCryptoKeyVersionRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.kms.v1.ICryptoKeyVersion, - protos.google.cloud.kms.v1.ICreateCryptoKeyVersionRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.kms.v1.ICryptoKeyVersion, - protos.google.cloud.kms.v1.ICreateCryptoKeyVersionRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.kms.v1.ICreateCryptoKeyVersionRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.kms.v1.ICryptoKeyVersion, + | protos.google.cloud.kms.v1.ICreateCryptoKeyVersionRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.kms.v1.ICryptoKeyVersion, + protos.google.cloud.kms.v1.ICreateCryptoKeyVersionRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('createCryptoKeyVersion request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.kms.v1.ICryptoKeyVersion, - protos.google.cloud.kms.v1.ICreateCryptoKeyVersionRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.kms.v1.ICryptoKeyVersion, + | protos.google.cloud.kms.v1.ICreateCryptoKeyVersionRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createCryptoKeyVersion response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.createCryptoKeyVersion(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.kms.v1.ICryptoKeyVersion, - protos.google.cloud.kms.v1.ICreateCryptoKeyVersionRequest|undefined, - {}|undefined - ]) => { - this._log.info('createCryptoKeyVersion response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createCryptoKeyVersion(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.kms.v1.ICryptoKeyVersion, + protos.google.cloud.kms.v1.ICreateCryptoKeyVersionRequest | undefined, + {} | undefined, + ]) => { + this._log.info('createCryptoKeyVersion response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Imports a new {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersion} into an existing {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKey} using the - * wrapped key material provided in the request. - * - * The version ID will be assigned the next sequential id within the - * {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKey}. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The {@link protos.google.cloud.kms.v1.CryptoKey.name|name} of the {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKey} to - * be imported into. - * @param {google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionAlgorithm} request.algorithm - * Required. The {@link protos.google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionAlgorithm|algorithm} of - * the key being imported. This does not need to match the - * {@link protos.google.cloud.kms.v1.CryptoKey.version_template|version_template} of the {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKey} this - * version imports into. - * @param {string} request.importJob - * Required. The {@link protos.google.cloud.kms.v1.ImportJob.name|name} of the {@link protos.google.cloud.kms.v1.ImportJob|ImportJob} that was used to - * wrap this key material. - * @param {Buffer} request.rsaAesWrappedKey - * Wrapped key material produced with - * {@link protos.google.cloud.kms.v1.ImportJob.ImportMethod.RSA_OAEP_3072_SHA1_AES_256|RSA_OAEP_3072_SHA1_AES_256} - * or - * {@link protos.google.cloud.kms.v1.ImportJob.ImportMethod.RSA_OAEP_4096_SHA1_AES_256|RSA_OAEP_4096_SHA1_AES_256}. - * - * This field contains the concatenation of two wrapped keys: - *
    - *
  1. An ephemeral AES-256 wrapping key wrapped with the - * {@link protos.google.cloud.kms.v1.ImportJob.public_key|public_key} using RSAES-OAEP with SHA-1, - * MGF1 with SHA-1, and an empty label. - *
  2. - *
  3. The key to be imported, wrapped with the ephemeral AES-256 key - * using AES-KWP (RFC 5649). - *
  4. - *
- * - * This format is the same as the format produced by PKCS#11 mechanism - * CKM_RSA_AES_KEY_WRAP. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersion}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1/key_management_service.import_crypto_key_version.js - * region_tag:cloudkms_v1_generated_KeyManagementService_ImportCryptoKeyVersion_async - */ + /** + * Imports a new {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersion} into an existing {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKey} using the + * wrapped key material provided in the request. + * + * The version ID will be assigned the next sequential id within the + * {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKey}. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The {@link protos.google.cloud.kms.v1.CryptoKey.name|name} of the {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKey} to + * be imported into. + * @param {google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionAlgorithm} request.algorithm + * Required. The {@link protos.google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionAlgorithm|algorithm} of + * the key being imported. This does not need to match the + * {@link protos.google.cloud.kms.v1.CryptoKey.version_template|version_template} of the {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKey} this + * version imports into. + * @param {string} request.importJob + * Required. The {@link protos.google.cloud.kms.v1.ImportJob.name|name} of the {@link protos.google.cloud.kms.v1.ImportJob|ImportJob} that was used to + * wrap this key material. + * @param {Buffer} request.rsaAesWrappedKey + * Wrapped key material produced with + * {@link protos.google.cloud.kms.v1.ImportJob.ImportMethod.RSA_OAEP_3072_SHA1_AES_256|RSA_OAEP_3072_SHA1_AES_256} + * or + * {@link protos.google.cloud.kms.v1.ImportJob.ImportMethod.RSA_OAEP_4096_SHA1_AES_256|RSA_OAEP_4096_SHA1_AES_256}. + * + * This field contains the concatenation of two wrapped keys: + *
    + *
  1. An ephemeral AES-256 wrapping key wrapped with the + * {@link protos.google.cloud.kms.v1.ImportJob.public_key|public_key} using RSAES-OAEP with SHA-1, + * MGF1 with SHA-1, and an empty label. + *
  2. + *
  3. The key to be imported, wrapped with the ephemeral AES-256 key + * using AES-KWP (RFC 5649). + *
  4. + *
+ * + * This format is the same as the format produced by PKCS#11 mechanism + * CKM_RSA_AES_KEY_WRAP. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersion}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/key_management_service.import_crypto_key_version.js + * region_tag:cloudkms_v1_generated_KeyManagementService_ImportCryptoKeyVersion_async + */ importCryptoKeyVersion( - request?: protos.google.cloud.kms.v1.IImportCryptoKeyVersionRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.kms.v1.ICryptoKeyVersion, - protos.google.cloud.kms.v1.IImportCryptoKeyVersionRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.kms.v1.IImportCryptoKeyVersionRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.kms.v1.ICryptoKeyVersion, + protos.google.cloud.kms.v1.IImportCryptoKeyVersionRequest | undefined, + {} | undefined, + ] + >; importCryptoKeyVersion( - request: protos.google.cloud.kms.v1.IImportCryptoKeyVersionRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.kms.v1.ICryptoKeyVersion, - protos.google.cloud.kms.v1.IImportCryptoKeyVersionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.kms.v1.IImportCryptoKeyVersionRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.kms.v1.ICryptoKeyVersion, + | protos.google.cloud.kms.v1.IImportCryptoKeyVersionRequest + | null + | undefined, + {} | null | undefined + >, + ): void; importCryptoKeyVersion( - request: protos.google.cloud.kms.v1.IImportCryptoKeyVersionRequest, - callback: Callback< - protos.google.cloud.kms.v1.ICryptoKeyVersion, - protos.google.cloud.kms.v1.IImportCryptoKeyVersionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.kms.v1.IImportCryptoKeyVersionRequest, + callback: Callback< + protos.google.cloud.kms.v1.ICryptoKeyVersion, + | protos.google.cloud.kms.v1.IImportCryptoKeyVersionRequest + | null + | undefined, + {} | null | undefined + >, + ): void; importCryptoKeyVersion( - request?: protos.google.cloud.kms.v1.IImportCryptoKeyVersionRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.kms.v1.ICryptoKeyVersion, - protos.google.cloud.kms.v1.IImportCryptoKeyVersionRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.kms.v1.IImportCryptoKeyVersionRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.kms.v1.ICryptoKeyVersion, - protos.google.cloud.kms.v1.IImportCryptoKeyVersionRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.kms.v1.ICryptoKeyVersion, - protos.google.cloud.kms.v1.IImportCryptoKeyVersionRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.kms.v1.IImportCryptoKeyVersionRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.kms.v1.ICryptoKeyVersion, + | protos.google.cloud.kms.v1.IImportCryptoKeyVersionRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.kms.v1.ICryptoKeyVersion, + protos.google.cloud.kms.v1.IImportCryptoKeyVersionRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('importCryptoKeyVersion request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.kms.v1.ICryptoKeyVersion, - protos.google.cloud.kms.v1.IImportCryptoKeyVersionRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.kms.v1.ICryptoKeyVersion, + | protos.google.cloud.kms.v1.IImportCryptoKeyVersionRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('importCryptoKeyVersion response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.importCryptoKeyVersion(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.kms.v1.ICryptoKeyVersion, - protos.google.cloud.kms.v1.IImportCryptoKeyVersionRequest|undefined, - {}|undefined - ]) => { - this._log.info('importCryptoKeyVersion response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .importCryptoKeyVersion(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.kms.v1.ICryptoKeyVersion, + protos.google.cloud.kms.v1.IImportCryptoKeyVersionRequest | undefined, + {} | undefined, + ]) => { + this._log.info('importCryptoKeyVersion response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Create a new {@link protos.google.cloud.kms.v1.ImportJob|ImportJob} within a {@link protos.google.cloud.kms.v1.KeyRing|KeyRing}. - * - * {@link protos.google.cloud.kms.v1.ImportJob.import_method|ImportJob.import_method} is required. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The {@link protos.google.cloud.kms.v1.KeyRing.name|name} of the {@link protos.google.cloud.kms.v1.KeyRing|KeyRing} associated with the - * {@link protos.google.cloud.kms.v1.ImportJob|ImportJobs}. - * @param {string} request.importJobId - * Required. It must be unique within a KeyRing and match the regular - * expression `[a-zA-Z0-9_-]{1,63}` - * @param {google.cloud.kms.v1.ImportJob} request.importJob - * Required. An {@link protos.google.cloud.kms.v1.ImportJob|ImportJob} with initial field values. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.kms.v1.ImportJob|ImportJob}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1/key_management_service.create_import_job.js - * region_tag:cloudkms_v1_generated_KeyManagementService_CreateImportJob_async - */ + /** + * Create a new {@link protos.google.cloud.kms.v1.ImportJob|ImportJob} within a {@link protos.google.cloud.kms.v1.KeyRing|KeyRing}. + * + * {@link protos.google.cloud.kms.v1.ImportJob.import_method|ImportJob.import_method} is required. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The {@link protos.google.cloud.kms.v1.KeyRing.name|name} of the {@link protos.google.cloud.kms.v1.KeyRing|KeyRing} associated with the + * {@link protos.google.cloud.kms.v1.ImportJob|ImportJobs}. + * @param {string} request.importJobId + * Required. It must be unique within a KeyRing and match the regular + * expression `[a-zA-Z0-9_-]{1,63}` + * @param {google.cloud.kms.v1.ImportJob} request.importJob + * Required. An {@link protos.google.cloud.kms.v1.ImportJob|ImportJob} with initial field values. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.kms.v1.ImportJob|ImportJob}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/key_management_service.create_import_job.js + * region_tag:cloudkms_v1_generated_KeyManagementService_CreateImportJob_async + */ createImportJob( - request?: protos.google.cloud.kms.v1.ICreateImportJobRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.kms.v1.IImportJob, - protos.google.cloud.kms.v1.ICreateImportJobRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.kms.v1.ICreateImportJobRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.kms.v1.IImportJob, + protos.google.cloud.kms.v1.ICreateImportJobRequest | undefined, + {} | undefined, + ] + >; createImportJob( - request: protos.google.cloud.kms.v1.ICreateImportJobRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.kms.v1.IImportJob, - protos.google.cloud.kms.v1.ICreateImportJobRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.kms.v1.ICreateImportJobRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.kms.v1.IImportJob, + protos.google.cloud.kms.v1.ICreateImportJobRequest | null | undefined, + {} | null | undefined + >, + ): void; createImportJob( - request: protos.google.cloud.kms.v1.ICreateImportJobRequest, - callback: Callback< - protos.google.cloud.kms.v1.IImportJob, - protos.google.cloud.kms.v1.ICreateImportJobRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.kms.v1.ICreateImportJobRequest, + callback: Callback< + protos.google.cloud.kms.v1.IImportJob, + protos.google.cloud.kms.v1.ICreateImportJobRequest | null | undefined, + {} | null | undefined + >, + ): void; createImportJob( - request?: protos.google.cloud.kms.v1.ICreateImportJobRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.kms.v1.IImportJob, - protos.google.cloud.kms.v1.ICreateImportJobRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.kms.v1.ICreateImportJobRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.kms.v1.IImportJob, - protos.google.cloud.kms.v1.ICreateImportJobRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.kms.v1.IImportJob, - protos.google.cloud.kms.v1.ICreateImportJobRequest|undefined, {}|undefined - ]>|void { + protos.google.cloud.kms.v1.ICreateImportJobRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.kms.v1.IImportJob, + protos.google.cloud.kms.v1.ICreateImportJobRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.kms.v1.IImportJob, + protos.google.cloud.kms.v1.ICreateImportJobRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('createImportJob request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.kms.v1.IImportJob, - protos.google.cloud.kms.v1.ICreateImportJobRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.kms.v1.IImportJob, + protos.google.cloud.kms.v1.ICreateImportJobRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createImportJob response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.createImportJob(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.kms.v1.IImportJob, - protos.google.cloud.kms.v1.ICreateImportJobRequest|undefined, - {}|undefined - ]) => { - this._log.info('createImportJob response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createImportJob(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.kms.v1.IImportJob, + protos.google.cloud.kms.v1.ICreateImportJobRequest | undefined, + {} | undefined, + ]) => { + this._log.info('createImportJob response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Update a {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKey}. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.cloud.kms.v1.CryptoKey} request.cryptoKey - * {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKey} with updated values. - * @param {google.protobuf.FieldMask} request.updateMask - * Required list of fields to be updated in this request. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKey}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1/key_management_service.update_crypto_key.js - * region_tag:cloudkms_v1_generated_KeyManagementService_UpdateCryptoKey_async - */ + /** + * Update a {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKey}. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.cloud.kms.v1.CryptoKey} request.cryptoKey + * {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKey} with updated values. + * @param {google.protobuf.FieldMask} request.updateMask + * Required list of fields to be updated in this request. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKey}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/key_management_service.update_crypto_key.js + * region_tag:cloudkms_v1_generated_KeyManagementService_UpdateCryptoKey_async + */ updateCryptoKey( - request?: protos.google.cloud.kms.v1.IUpdateCryptoKeyRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.kms.v1.ICryptoKey, - protos.google.cloud.kms.v1.IUpdateCryptoKeyRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.kms.v1.IUpdateCryptoKeyRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.kms.v1.ICryptoKey, + protos.google.cloud.kms.v1.IUpdateCryptoKeyRequest | undefined, + {} | undefined, + ] + >; updateCryptoKey( - request: protos.google.cloud.kms.v1.IUpdateCryptoKeyRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.kms.v1.ICryptoKey, - protos.google.cloud.kms.v1.IUpdateCryptoKeyRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.kms.v1.IUpdateCryptoKeyRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.kms.v1.ICryptoKey, + protos.google.cloud.kms.v1.IUpdateCryptoKeyRequest | null | undefined, + {} | null | undefined + >, + ): void; updateCryptoKey( - request: protos.google.cloud.kms.v1.IUpdateCryptoKeyRequest, - callback: Callback< - protos.google.cloud.kms.v1.ICryptoKey, - protos.google.cloud.kms.v1.IUpdateCryptoKeyRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.kms.v1.IUpdateCryptoKeyRequest, + callback: Callback< + protos.google.cloud.kms.v1.ICryptoKey, + protos.google.cloud.kms.v1.IUpdateCryptoKeyRequest | null | undefined, + {} | null | undefined + >, + ): void; updateCryptoKey( - request?: protos.google.cloud.kms.v1.IUpdateCryptoKeyRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.kms.v1.ICryptoKey, - protos.google.cloud.kms.v1.IUpdateCryptoKeyRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.kms.v1.IUpdateCryptoKeyRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.kms.v1.ICryptoKey, - protos.google.cloud.kms.v1.IUpdateCryptoKeyRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.kms.v1.ICryptoKey, - protos.google.cloud.kms.v1.IUpdateCryptoKeyRequest|undefined, {}|undefined - ]>|void { + protos.google.cloud.kms.v1.IUpdateCryptoKeyRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.kms.v1.ICryptoKey, + protos.google.cloud.kms.v1.IUpdateCryptoKeyRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.kms.v1.ICryptoKey, + protos.google.cloud.kms.v1.IUpdateCryptoKeyRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'crypto_key.name': request.cryptoKey!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'crypto_key.name': request.cryptoKey!.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateCryptoKey request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.kms.v1.ICryptoKey, - protos.google.cloud.kms.v1.IUpdateCryptoKeyRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.kms.v1.ICryptoKey, + protos.google.cloud.kms.v1.IUpdateCryptoKeyRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateCryptoKey response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.updateCryptoKey(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.kms.v1.ICryptoKey, - protos.google.cloud.kms.v1.IUpdateCryptoKeyRequest|undefined, - {}|undefined - ]) => { - this._log.info('updateCryptoKey response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateCryptoKey(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.kms.v1.ICryptoKey, + protos.google.cloud.kms.v1.IUpdateCryptoKeyRequest | undefined, + {} | undefined, + ]) => { + this._log.info('updateCryptoKey response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Update a {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersion}'s metadata. - * - * {@link protos.google.cloud.kms.v1.CryptoKeyVersion.state|state} may be changed between - * {@link protos.google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED|ENABLED} and - * {@link protos.google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DISABLED|DISABLED} using this - * method. See {@link protos.google.cloud.kms.v1.KeyManagementService.DestroyCryptoKeyVersion|DestroyCryptoKeyVersion} and {@link protos.google.cloud.kms.v1.KeyManagementService.RestoreCryptoKeyVersion|RestoreCryptoKeyVersion} to - * move between other states. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.cloud.kms.v1.CryptoKeyVersion} request.cryptoKeyVersion - * {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersion} with updated values. - * @param {google.protobuf.FieldMask} request.updateMask - * Required list of fields to be updated in this request. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersion}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1/key_management_service.update_crypto_key_version.js - * region_tag:cloudkms_v1_generated_KeyManagementService_UpdateCryptoKeyVersion_async - */ + /** + * Update a {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersion}'s metadata. + * + * {@link protos.google.cloud.kms.v1.CryptoKeyVersion.state|state} may be changed between + * {@link protos.google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED|ENABLED} and + * {@link protos.google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DISABLED|DISABLED} using this + * method. See {@link protos.google.cloud.kms.v1.KeyManagementService.DestroyCryptoKeyVersion|DestroyCryptoKeyVersion} and {@link protos.google.cloud.kms.v1.KeyManagementService.RestoreCryptoKeyVersion|RestoreCryptoKeyVersion} to + * move between other states. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.cloud.kms.v1.CryptoKeyVersion} request.cryptoKeyVersion + * {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersion} with updated values. + * @param {google.protobuf.FieldMask} request.updateMask + * Required list of fields to be updated in this request. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersion}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/key_management_service.update_crypto_key_version.js + * region_tag:cloudkms_v1_generated_KeyManagementService_UpdateCryptoKeyVersion_async + */ updateCryptoKeyVersion( - request?: protos.google.cloud.kms.v1.IUpdateCryptoKeyVersionRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.kms.v1.ICryptoKeyVersion, - protos.google.cloud.kms.v1.IUpdateCryptoKeyVersionRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.kms.v1.IUpdateCryptoKeyVersionRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.kms.v1.ICryptoKeyVersion, + protos.google.cloud.kms.v1.IUpdateCryptoKeyVersionRequest | undefined, + {} | undefined, + ] + >; updateCryptoKeyVersion( - request: protos.google.cloud.kms.v1.IUpdateCryptoKeyVersionRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.kms.v1.ICryptoKeyVersion, - protos.google.cloud.kms.v1.IUpdateCryptoKeyVersionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.kms.v1.IUpdateCryptoKeyVersionRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.kms.v1.ICryptoKeyVersion, + | protos.google.cloud.kms.v1.IUpdateCryptoKeyVersionRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateCryptoKeyVersion( - request: protos.google.cloud.kms.v1.IUpdateCryptoKeyVersionRequest, - callback: Callback< - protos.google.cloud.kms.v1.ICryptoKeyVersion, - protos.google.cloud.kms.v1.IUpdateCryptoKeyVersionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.kms.v1.IUpdateCryptoKeyVersionRequest, + callback: Callback< + protos.google.cloud.kms.v1.ICryptoKeyVersion, + | protos.google.cloud.kms.v1.IUpdateCryptoKeyVersionRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateCryptoKeyVersion( - request?: protos.google.cloud.kms.v1.IUpdateCryptoKeyVersionRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.kms.v1.ICryptoKeyVersion, - protos.google.cloud.kms.v1.IUpdateCryptoKeyVersionRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.kms.v1.IUpdateCryptoKeyVersionRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.kms.v1.ICryptoKeyVersion, - protos.google.cloud.kms.v1.IUpdateCryptoKeyVersionRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.kms.v1.ICryptoKeyVersion, - protos.google.cloud.kms.v1.IUpdateCryptoKeyVersionRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.kms.v1.IUpdateCryptoKeyVersionRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.kms.v1.ICryptoKeyVersion, + | protos.google.cloud.kms.v1.IUpdateCryptoKeyVersionRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.kms.v1.ICryptoKeyVersion, + protos.google.cloud.kms.v1.IUpdateCryptoKeyVersionRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'crypto_key_version.name': request.cryptoKeyVersion!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'crypto_key_version.name': request.cryptoKeyVersion!.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateCryptoKeyVersion request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.kms.v1.ICryptoKeyVersion, - protos.google.cloud.kms.v1.IUpdateCryptoKeyVersionRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.kms.v1.ICryptoKeyVersion, + | protos.google.cloud.kms.v1.IUpdateCryptoKeyVersionRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateCryptoKeyVersion response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.updateCryptoKeyVersion(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.kms.v1.ICryptoKeyVersion, - protos.google.cloud.kms.v1.IUpdateCryptoKeyVersionRequest|undefined, - {}|undefined - ]) => { - this._log.info('updateCryptoKeyVersion response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateCryptoKeyVersion(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.kms.v1.ICryptoKeyVersion, + protos.google.cloud.kms.v1.IUpdateCryptoKeyVersionRequest | undefined, + {} | undefined, + ]) => { + this._log.info('updateCryptoKeyVersion response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Encrypts data, so that it can only be recovered by a call to {@link protos.google.cloud.kms.v1.KeyManagementService.Decrypt|Decrypt}. - * The {@link protos.google.cloud.kms.v1.CryptoKey.purpose|CryptoKey.purpose} must be - * {@link protos.google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT|ENCRYPT_DECRYPT}. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The resource name of the {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKey} or {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersion} - * to use for encryption. - * - * If a {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKey} is specified, the server will use its - * {@link protos.google.cloud.kms.v1.CryptoKey.primary|primary version}. - * @param {Buffer} request.plaintext - * Required. The data to encrypt. Must be no larger than 64KiB. - * - * The maximum size depends on the key version's - * {@link protos.google.cloud.kms.v1.CryptoKeyVersionTemplate.protection_level|protection_level}. For - * {@link protos.google.cloud.kms.v1.ProtectionLevel.SOFTWARE|SOFTWARE} keys, the plaintext must be no larger - * than 64KiB. For {@link protos.google.cloud.kms.v1.ProtectionLevel.HSM|HSM} keys, the combined length of the - * plaintext and additional_authenticated_data fields must be no larger than - * 8KiB. - * @param {Buffer} request.additionalAuthenticatedData - * Optional data that, if specified, must also be provided during decryption - * through {@link protos.google.cloud.kms.v1.DecryptRequest.additional_authenticated_data|DecryptRequest.additional_authenticated_data}. - * - * The maximum size depends on the key version's - * {@link protos.google.cloud.kms.v1.CryptoKeyVersionTemplate.protection_level|protection_level}. For - * {@link protos.google.cloud.kms.v1.ProtectionLevel.SOFTWARE|SOFTWARE} keys, the AAD must be no larger than - * 64KiB. For {@link protos.google.cloud.kms.v1.ProtectionLevel.HSM|HSM} keys, the combined length of the - * plaintext and additional_authenticated_data fields must be no larger than - * 8KiB. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.kms.v1.EncryptResponse|EncryptResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1/key_management_service.encrypt.js - * region_tag:cloudkms_v1_generated_KeyManagementService_Encrypt_async - */ + /** + * Encrypts data, so that it can only be recovered by a call to {@link protos.google.cloud.kms.v1.KeyManagementService.Decrypt|Decrypt}. + * The {@link protos.google.cloud.kms.v1.CryptoKey.purpose|CryptoKey.purpose} must be + * {@link protos.google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT|ENCRYPT_DECRYPT}. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The resource name of the {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKey} or {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersion} + * to use for encryption. + * + * If a {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKey} is specified, the server will use its + * {@link protos.google.cloud.kms.v1.CryptoKey.primary|primary version}. + * @param {Buffer} request.plaintext + * Required. The data to encrypt. Must be no larger than 64KiB. + * + * The maximum size depends on the key version's + * {@link protos.google.cloud.kms.v1.CryptoKeyVersionTemplate.protection_level|protection_level}. For + * {@link protos.google.cloud.kms.v1.ProtectionLevel.SOFTWARE|SOFTWARE} keys, the plaintext must be no larger + * than 64KiB. For {@link protos.google.cloud.kms.v1.ProtectionLevel.HSM|HSM} keys, the combined length of the + * plaintext and additional_authenticated_data fields must be no larger than + * 8KiB. + * @param {Buffer} request.additionalAuthenticatedData + * Optional data that, if specified, must also be provided during decryption + * through {@link protos.google.cloud.kms.v1.DecryptRequest.additional_authenticated_data|DecryptRequest.additional_authenticated_data}. + * + * The maximum size depends on the key version's + * {@link protos.google.cloud.kms.v1.CryptoKeyVersionTemplate.protection_level|protection_level}. For + * {@link protos.google.cloud.kms.v1.ProtectionLevel.SOFTWARE|SOFTWARE} keys, the AAD must be no larger than + * 64KiB. For {@link protos.google.cloud.kms.v1.ProtectionLevel.HSM|HSM} keys, the combined length of the + * plaintext and additional_authenticated_data fields must be no larger than + * 8KiB. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.kms.v1.EncryptResponse|EncryptResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/key_management_service.encrypt.js + * region_tag:cloudkms_v1_generated_KeyManagementService_Encrypt_async + */ encrypt( - request?: protos.google.cloud.kms.v1.IEncryptRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.kms.v1.IEncryptResponse, - protos.google.cloud.kms.v1.IEncryptRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.kms.v1.IEncryptRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.kms.v1.IEncryptResponse, + protos.google.cloud.kms.v1.IEncryptRequest | undefined, + {} | undefined, + ] + >; encrypt( - request: protos.google.cloud.kms.v1.IEncryptRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.kms.v1.IEncryptResponse, - protos.google.cloud.kms.v1.IEncryptRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.kms.v1.IEncryptRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.kms.v1.IEncryptResponse, + protos.google.cloud.kms.v1.IEncryptRequest | null | undefined, + {} | null | undefined + >, + ): void; encrypt( - request: protos.google.cloud.kms.v1.IEncryptRequest, - callback: Callback< - protos.google.cloud.kms.v1.IEncryptResponse, - protos.google.cloud.kms.v1.IEncryptRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.kms.v1.IEncryptRequest, + callback: Callback< + protos.google.cloud.kms.v1.IEncryptResponse, + protos.google.cloud.kms.v1.IEncryptRequest | null | undefined, + {} | null | undefined + >, + ): void; encrypt( - request?: protos.google.cloud.kms.v1.IEncryptRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.kms.v1.IEncryptResponse, - protos.google.cloud.kms.v1.IEncryptRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.kms.v1.IEncryptRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.kms.v1.IEncryptResponse, - protos.google.cloud.kms.v1.IEncryptRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.kms.v1.IEncryptResponse, - protos.google.cloud.kms.v1.IEncryptRequest|undefined, {}|undefined - ]>|void { + protos.google.cloud.kms.v1.IEncryptRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.kms.v1.IEncryptResponse, + protos.google.cloud.kms.v1.IEncryptRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.kms.v1.IEncryptResponse, + protos.google.cloud.kms.v1.IEncryptRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('encrypt request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.kms.v1.IEncryptResponse, - protos.google.cloud.kms.v1.IEncryptRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.kms.v1.IEncryptResponse, + protos.google.cloud.kms.v1.IEncryptRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('encrypt response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.encrypt(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.kms.v1.IEncryptResponse, - protos.google.cloud.kms.v1.IEncryptRequest|undefined, - {}|undefined - ]) => { - this._log.info('encrypt response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .encrypt(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.kms.v1.IEncryptResponse, + protos.google.cloud.kms.v1.IEncryptRequest | undefined, + {} | undefined, + ]) => { + this._log.info('encrypt response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Decrypts data that was protected by {@link protos.google.cloud.kms.v1.KeyManagementService.Encrypt|Encrypt}. The {@link protos.google.cloud.kms.v1.CryptoKey.purpose|CryptoKey.purpose} - * must be {@link protos.google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT|ENCRYPT_DECRYPT}. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The resource name of the {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKey} to use for decryption. - * The server will choose the appropriate version. - * @param {Buffer} request.ciphertext - * Required. The encrypted data originally returned in - * {@link protos.google.cloud.kms.v1.EncryptResponse.ciphertext|EncryptResponse.ciphertext}. - * @param {Buffer} request.additionalAuthenticatedData - * Optional data that must match the data originally supplied in - * {@link protos.google.cloud.kms.v1.EncryptRequest.additional_authenticated_data|EncryptRequest.additional_authenticated_data}. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.kms.v1.DecryptResponse|DecryptResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1/key_management_service.decrypt.js - * region_tag:cloudkms_v1_generated_KeyManagementService_Decrypt_async - */ + /** + * Decrypts data that was protected by {@link protos.google.cloud.kms.v1.KeyManagementService.Encrypt|Encrypt}. The {@link protos.google.cloud.kms.v1.CryptoKey.purpose|CryptoKey.purpose} + * must be {@link protos.google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT|ENCRYPT_DECRYPT}. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The resource name of the {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKey} to use for decryption. + * The server will choose the appropriate version. + * @param {Buffer} request.ciphertext + * Required. The encrypted data originally returned in + * {@link protos.google.cloud.kms.v1.EncryptResponse.ciphertext|EncryptResponse.ciphertext}. + * @param {Buffer} request.additionalAuthenticatedData + * Optional data that must match the data originally supplied in + * {@link protos.google.cloud.kms.v1.EncryptRequest.additional_authenticated_data|EncryptRequest.additional_authenticated_data}. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.kms.v1.DecryptResponse|DecryptResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/key_management_service.decrypt.js + * region_tag:cloudkms_v1_generated_KeyManagementService_Decrypt_async + */ decrypt( - request?: protos.google.cloud.kms.v1.IDecryptRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.kms.v1.IDecryptResponse, - protos.google.cloud.kms.v1.IDecryptRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.kms.v1.IDecryptRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.kms.v1.IDecryptResponse, + protos.google.cloud.kms.v1.IDecryptRequest | undefined, + {} | undefined, + ] + >; decrypt( - request: protos.google.cloud.kms.v1.IDecryptRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.kms.v1.IDecryptResponse, - protos.google.cloud.kms.v1.IDecryptRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.kms.v1.IDecryptRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.kms.v1.IDecryptResponse, + protos.google.cloud.kms.v1.IDecryptRequest | null | undefined, + {} | null | undefined + >, + ): void; decrypt( - request: protos.google.cloud.kms.v1.IDecryptRequest, - callback: Callback< - protos.google.cloud.kms.v1.IDecryptResponse, - protos.google.cloud.kms.v1.IDecryptRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.kms.v1.IDecryptRequest, + callback: Callback< + protos.google.cloud.kms.v1.IDecryptResponse, + protos.google.cloud.kms.v1.IDecryptRequest | null | undefined, + {} | null | undefined + >, + ): void; decrypt( - request?: protos.google.cloud.kms.v1.IDecryptRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.kms.v1.IDecryptResponse, - protos.google.cloud.kms.v1.IDecryptRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.kms.v1.IDecryptRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.kms.v1.IDecryptResponse, - protos.google.cloud.kms.v1.IDecryptRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.kms.v1.IDecryptResponse, - protos.google.cloud.kms.v1.IDecryptRequest|undefined, {}|undefined - ]>|void { + protos.google.cloud.kms.v1.IDecryptRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.kms.v1.IDecryptResponse, + protos.google.cloud.kms.v1.IDecryptRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.kms.v1.IDecryptResponse, + protos.google.cloud.kms.v1.IDecryptRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('decrypt request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.kms.v1.IDecryptResponse, - protos.google.cloud.kms.v1.IDecryptRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.kms.v1.IDecryptResponse, + protos.google.cloud.kms.v1.IDecryptRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('decrypt response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.decrypt(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.kms.v1.IDecryptResponse, - protos.google.cloud.kms.v1.IDecryptRequest|undefined, - {}|undefined - ]) => { - this._log.info('decrypt response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .decrypt(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.kms.v1.IDecryptResponse, + protos.google.cloud.kms.v1.IDecryptRequest | undefined, + {} | undefined, + ]) => { + this._log.info('decrypt response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Signs data using a {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersion} with {@link protos.google.cloud.kms.v1.CryptoKey.purpose|CryptoKey.purpose} - * ASYMMETRIC_SIGN, producing a signature that can be verified with the public - * key retrieved from {@link protos.google.cloud.kms.v1.KeyManagementService.GetPublicKey|GetPublicKey}. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The resource name of the {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersion} to use for signing. - * @param {google.cloud.kms.v1.Digest} request.digest - * Required. The digest of the data to sign. The digest must be produced with - * the same digest algorithm as specified by the key version's - * {@link protos.google.cloud.kms.v1.CryptoKeyVersion.algorithm|algorithm}. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.kms.v1.AsymmetricSignResponse|AsymmetricSignResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1/key_management_service.asymmetric_sign.js - * region_tag:cloudkms_v1_generated_KeyManagementService_AsymmetricSign_async - */ + /** + * Signs data using a {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersion} with {@link protos.google.cloud.kms.v1.CryptoKey.purpose|CryptoKey.purpose} + * ASYMMETRIC_SIGN, producing a signature that can be verified with the public + * key retrieved from {@link protos.google.cloud.kms.v1.KeyManagementService.GetPublicKey|GetPublicKey}. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The resource name of the {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersion} to use for signing. + * @param {google.cloud.kms.v1.Digest} request.digest + * Required. The digest of the data to sign. The digest must be produced with + * the same digest algorithm as specified by the key version's + * {@link protos.google.cloud.kms.v1.CryptoKeyVersion.algorithm|algorithm}. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.kms.v1.AsymmetricSignResponse|AsymmetricSignResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/key_management_service.asymmetric_sign.js + * region_tag:cloudkms_v1_generated_KeyManagementService_AsymmetricSign_async + */ asymmetricSign( - request?: protos.google.cloud.kms.v1.IAsymmetricSignRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.kms.v1.IAsymmetricSignResponse, - protos.google.cloud.kms.v1.IAsymmetricSignRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.kms.v1.IAsymmetricSignRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.kms.v1.IAsymmetricSignResponse, + protos.google.cloud.kms.v1.IAsymmetricSignRequest | undefined, + {} | undefined, + ] + >; asymmetricSign( - request: protos.google.cloud.kms.v1.IAsymmetricSignRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.kms.v1.IAsymmetricSignResponse, - protos.google.cloud.kms.v1.IAsymmetricSignRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.kms.v1.IAsymmetricSignRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.kms.v1.IAsymmetricSignResponse, + protos.google.cloud.kms.v1.IAsymmetricSignRequest | null | undefined, + {} | null | undefined + >, + ): void; asymmetricSign( - request: protos.google.cloud.kms.v1.IAsymmetricSignRequest, - callback: Callback< - protos.google.cloud.kms.v1.IAsymmetricSignResponse, - protos.google.cloud.kms.v1.IAsymmetricSignRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.kms.v1.IAsymmetricSignRequest, + callback: Callback< + protos.google.cloud.kms.v1.IAsymmetricSignResponse, + protos.google.cloud.kms.v1.IAsymmetricSignRequest | null | undefined, + {} | null | undefined + >, + ): void; asymmetricSign( - request?: protos.google.cloud.kms.v1.IAsymmetricSignRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.kms.v1.IAsymmetricSignResponse, - protos.google.cloud.kms.v1.IAsymmetricSignRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.kms.v1.IAsymmetricSignRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.kms.v1.IAsymmetricSignResponse, - protos.google.cloud.kms.v1.IAsymmetricSignRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.kms.v1.IAsymmetricSignResponse, - protos.google.cloud.kms.v1.IAsymmetricSignRequest|undefined, {}|undefined - ]>|void { + protos.google.cloud.kms.v1.IAsymmetricSignRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.kms.v1.IAsymmetricSignResponse, + protos.google.cloud.kms.v1.IAsymmetricSignRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.kms.v1.IAsymmetricSignResponse, + protos.google.cloud.kms.v1.IAsymmetricSignRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('asymmetricSign request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.kms.v1.IAsymmetricSignResponse, - protos.google.cloud.kms.v1.IAsymmetricSignRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.kms.v1.IAsymmetricSignResponse, + protos.google.cloud.kms.v1.IAsymmetricSignRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('asymmetricSign response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.asymmetricSign(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.kms.v1.IAsymmetricSignResponse, - protos.google.cloud.kms.v1.IAsymmetricSignRequest|undefined, - {}|undefined - ]) => { - this._log.info('asymmetricSign response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .asymmetricSign(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.kms.v1.IAsymmetricSignResponse, + protos.google.cloud.kms.v1.IAsymmetricSignRequest | undefined, + {} | undefined, + ]) => { + this._log.info('asymmetricSign response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Decrypts data that was encrypted with a public key retrieved from - * {@link protos.google.cloud.kms.v1.KeyManagementService.GetPublicKey|GetPublicKey} corresponding to a {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersion} with - * {@link protos.google.cloud.kms.v1.CryptoKey.purpose|CryptoKey.purpose} ASYMMETRIC_DECRYPT. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The resource name of the {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersion} to use for - * decryption. - * @param {Buffer} request.ciphertext - * Required. The data encrypted with the named {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersion}'s public - * key using OAEP. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.kms.v1.AsymmetricDecryptResponse|AsymmetricDecryptResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1/key_management_service.asymmetric_decrypt.js - * region_tag:cloudkms_v1_generated_KeyManagementService_AsymmetricDecrypt_async - */ + /** + * Decrypts data that was encrypted with a public key retrieved from + * {@link protos.google.cloud.kms.v1.KeyManagementService.GetPublicKey|GetPublicKey} corresponding to a {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersion} with + * {@link protos.google.cloud.kms.v1.CryptoKey.purpose|CryptoKey.purpose} ASYMMETRIC_DECRYPT. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The resource name of the {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersion} to use for + * decryption. + * @param {Buffer} request.ciphertext + * Required. The data encrypted with the named {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersion}'s public + * key using OAEP. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.kms.v1.AsymmetricDecryptResponse|AsymmetricDecryptResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/key_management_service.asymmetric_decrypt.js + * region_tag:cloudkms_v1_generated_KeyManagementService_AsymmetricDecrypt_async + */ asymmetricDecrypt( - request?: protos.google.cloud.kms.v1.IAsymmetricDecryptRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.kms.v1.IAsymmetricDecryptResponse, - protos.google.cloud.kms.v1.IAsymmetricDecryptRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.kms.v1.IAsymmetricDecryptRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.kms.v1.IAsymmetricDecryptResponse, + protos.google.cloud.kms.v1.IAsymmetricDecryptRequest | undefined, + {} | undefined, + ] + >; asymmetricDecrypt( - request: protos.google.cloud.kms.v1.IAsymmetricDecryptRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.kms.v1.IAsymmetricDecryptResponse, - protos.google.cloud.kms.v1.IAsymmetricDecryptRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.kms.v1.IAsymmetricDecryptRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.kms.v1.IAsymmetricDecryptResponse, + protos.google.cloud.kms.v1.IAsymmetricDecryptRequest | null | undefined, + {} | null | undefined + >, + ): void; asymmetricDecrypt( - request: protos.google.cloud.kms.v1.IAsymmetricDecryptRequest, - callback: Callback< - protos.google.cloud.kms.v1.IAsymmetricDecryptResponse, - protos.google.cloud.kms.v1.IAsymmetricDecryptRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.kms.v1.IAsymmetricDecryptRequest, + callback: Callback< + protos.google.cloud.kms.v1.IAsymmetricDecryptResponse, + protos.google.cloud.kms.v1.IAsymmetricDecryptRequest | null | undefined, + {} | null | undefined + >, + ): void; asymmetricDecrypt( - request?: protos.google.cloud.kms.v1.IAsymmetricDecryptRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.kms.v1.IAsymmetricDecryptResponse, - protos.google.cloud.kms.v1.IAsymmetricDecryptRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.kms.v1.IAsymmetricDecryptRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.kms.v1.IAsymmetricDecryptResponse, - protos.google.cloud.kms.v1.IAsymmetricDecryptRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.kms.v1.IAsymmetricDecryptResponse, - protos.google.cloud.kms.v1.IAsymmetricDecryptRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.kms.v1.IAsymmetricDecryptRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.kms.v1.IAsymmetricDecryptResponse, + protos.google.cloud.kms.v1.IAsymmetricDecryptRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.kms.v1.IAsymmetricDecryptResponse, + protos.google.cloud.kms.v1.IAsymmetricDecryptRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('asymmetricDecrypt request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.kms.v1.IAsymmetricDecryptResponse, - protos.google.cloud.kms.v1.IAsymmetricDecryptRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.kms.v1.IAsymmetricDecryptResponse, + | protos.google.cloud.kms.v1.IAsymmetricDecryptRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('asymmetricDecrypt response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.asymmetricDecrypt(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.kms.v1.IAsymmetricDecryptResponse, - protos.google.cloud.kms.v1.IAsymmetricDecryptRequest|undefined, - {}|undefined - ]) => { - this._log.info('asymmetricDecrypt response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .asymmetricDecrypt(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.kms.v1.IAsymmetricDecryptResponse, + protos.google.cloud.kms.v1.IAsymmetricDecryptRequest | undefined, + {} | undefined, + ]) => { + this._log.info('asymmetricDecrypt response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Update the version of a {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKey} that will be used in {@link protos.google.cloud.kms.v1.KeyManagementService.Encrypt|Encrypt}. - * - * Returns an error if called on an asymmetric key. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * The resource name of the {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKey} to update. - * @param {string} request.cryptoKeyVersionId - * The id of the child {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersion} to use as primary. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKey}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1/key_management_service.update_crypto_key_primary_version.js - * region_tag:cloudkms_v1_generated_KeyManagementService_UpdateCryptoKeyPrimaryVersion_async - */ + /** + * Update the version of a {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKey} that will be used in {@link protos.google.cloud.kms.v1.KeyManagementService.Encrypt|Encrypt}. + * + * Returns an error if called on an asymmetric key. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * The resource name of the {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKey} to update. + * @param {string} request.cryptoKeyVersionId + * The id of the child {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersion} to use as primary. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKey}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/key_management_service.update_crypto_key_primary_version.js + * region_tag:cloudkms_v1_generated_KeyManagementService_UpdateCryptoKeyPrimaryVersion_async + */ updateCryptoKeyPrimaryVersion( - request?: protos.google.cloud.kms.v1.IUpdateCryptoKeyPrimaryVersionRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.kms.v1.ICryptoKey, - protos.google.cloud.kms.v1.IUpdateCryptoKeyPrimaryVersionRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.kms.v1.IUpdateCryptoKeyPrimaryVersionRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.kms.v1.ICryptoKey, + ( + | protos.google.cloud.kms.v1.IUpdateCryptoKeyPrimaryVersionRequest + | undefined + ), + {} | undefined, + ] + >; updateCryptoKeyPrimaryVersion( - request: protos.google.cloud.kms.v1.IUpdateCryptoKeyPrimaryVersionRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.kms.v1.ICryptoKey, - protos.google.cloud.kms.v1.IUpdateCryptoKeyPrimaryVersionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.kms.v1.IUpdateCryptoKeyPrimaryVersionRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.kms.v1.ICryptoKey, + | protos.google.cloud.kms.v1.IUpdateCryptoKeyPrimaryVersionRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateCryptoKeyPrimaryVersion( - request: protos.google.cloud.kms.v1.IUpdateCryptoKeyPrimaryVersionRequest, - callback: Callback< - protos.google.cloud.kms.v1.ICryptoKey, - protos.google.cloud.kms.v1.IUpdateCryptoKeyPrimaryVersionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.kms.v1.IUpdateCryptoKeyPrimaryVersionRequest, + callback: Callback< + protos.google.cloud.kms.v1.ICryptoKey, + | protos.google.cloud.kms.v1.IUpdateCryptoKeyPrimaryVersionRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateCryptoKeyPrimaryVersion( - request?: protos.google.cloud.kms.v1.IUpdateCryptoKeyPrimaryVersionRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.kms.v1.ICryptoKey, - protos.google.cloud.kms.v1.IUpdateCryptoKeyPrimaryVersionRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.kms.v1.IUpdateCryptoKeyPrimaryVersionRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.kms.v1.ICryptoKey, - protos.google.cloud.kms.v1.IUpdateCryptoKeyPrimaryVersionRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.kms.v1.ICryptoKey, - protos.google.cloud.kms.v1.IUpdateCryptoKeyPrimaryVersionRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.kms.v1.IUpdateCryptoKeyPrimaryVersionRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.kms.v1.ICryptoKey, + | protos.google.cloud.kms.v1.IUpdateCryptoKeyPrimaryVersionRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.kms.v1.ICryptoKey, + ( + | protos.google.cloud.kms.v1.IUpdateCryptoKeyPrimaryVersionRequest + | undefined + ), + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateCryptoKeyPrimaryVersion request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.kms.v1.ICryptoKey, - protos.google.cloud.kms.v1.IUpdateCryptoKeyPrimaryVersionRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.kms.v1.ICryptoKey, + | protos.google.cloud.kms.v1.IUpdateCryptoKeyPrimaryVersionRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateCryptoKeyPrimaryVersion response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.updateCryptoKeyPrimaryVersion(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.kms.v1.ICryptoKey, - protos.google.cloud.kms.v1.IUpdateCryptoKeyPrimaryVersionRequest|undefined, - {}|undefined - ]) => { - this._log.info('updateCryptoKeyPrimaryVersion response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateCryptoKeyPrimaryVersion(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.kms.v1.ICryptoKey, + ( + | protos.google.cloud.kms.v1.IUpdateCryptoKeyPrimaryVersionRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('updateCryptoKeyPrimaryVersion response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Schedule a {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersion} for destruction. - * - * Upon calling this method, {@link protos.google.cloud.kms.v1.CryptoKeyVersion.state|CryptoKeyVersion.state} will be set to - * {@link protos.google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DESTROY_SCHEDULED|DESTROY_SCHEDULED} - * and {@link protos.google.cloud.kms.v1.CryptoKeyVersion.destroy_time|destroy_time} will be set to a time 24 - * hours in the future, at which point the {@link protos.google.cloud.kms.v1.CryptoKeyVersion.state|state} - * will be changed to - * {@link protos.google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DESTROYED|DESTROYED}, and the key - * material will be irrevocably destroyed. - * - * Before the {@link protos.google.cloud.kms.v1.CryptoKeyVersion.destroy_time|destroy_time} is reached, - * {@link protos.google.cloud.kms.v1.KeyManagementService.RestoreCryptoKeyVersion|RestoreCryptoKeyVersion} may be called to reverse the process. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * The resource name of the {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersion} to destroy. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersion}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1/key_management_service.destroy_crypto_key_version.js - * region_tag:cloudkms_v1_generated_KeyManagementService_DestroyCryptoKeyVersion_async - */ + /** + * Schedule a {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersion} for destruction. + * + * Upon calling this method, {@link protos.google.cloud.kms.v1.CryptoKeyVersion.state|CryptoKeyVersion.state} will be set to + * {@link protos.google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DESTROY_SCHEDULED|DESTROY_SCHEDULED} + * and {@link protos.google.cloud.kms.v1.CryptoKeyVersion.destroy_time|destroy_time} will be set to a time 24 + * hours in the future, at which point the {@link protos.google.cloud.kms.v1.CryptoKeyVersion.state|state} + * will be changed to + * {@link protos.google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DESTROYED|DESTROYED}, and the key + * material will be irrevocably destroyed. + * + * Before the {@link protos.google.cloud.kms.v1.CryptoKeyVersion.destroy_time|destroy_time} is reached, + * {@link protos.google.cloud.kms.v1.KeyManagementService.RestoreCryptoKeyVersion|RestoreCryptoKeyVersion} may be called to reverse the process. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * The resource name of the {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersion} to destroy. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersion}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/key_management_service.destroy_crypto_key_version.js + * region_tag:cloudkms_v1_generated_KeyManagementService_DestroyCryptoKeyVersion_async + */ destroyCryptoKeyVersion( - request?: protos.google.cloud.kms.v1.IDestroyCryptoKeyVersionRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.kms.v1.ICryptoKeyVersion, - protos.google.cloud.kms.v1.IDestroyCryptoKeyVersionRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.kms.v1.IDestroyCryptoKeyVersionRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.kms.v1.ICryptoKeyVersion, + protos.google.cloud.kms.v1.IDestroyCryptoKeyVersionRequest | undefined, + {} | undefined, + ] + >; destroyCryptoKeyVersion( - request: protos.google.cloud.kms.v1.IDestroyCryptoKeyVersionRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.kms.v1.ICryptoKeyVersion, - protos.google.cloud.kms.v1.IDestroyCryptoKeyVersionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.kms.v1.IDestroyCryptoKeyVersionRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.kms.v1.ICryptoKeyVersion, + | protos.google.cloud.kms.v1.IDestroyCryptoKeyVersionRequest + | null + | undefined, + {} | null | undefined + >, + ): void; destroyCryptoKeyVersion( - request: protos.google.cloud.kms.v1.IDestroyCryptoKeyVersionRequest, - callback: Callback< - protos.google.cloud.kms.v1.ICryptoKeyVersion, - protos.google.cloud.kms.v1.IDestroyCryptoKeyVersionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.kms.v1.IDestroyCryptoKeyVersionRequest, + callback: Callback< + protos.google.cloud.kms.v1.ICryptoKeyVersion, + | protos.google.cloud.kms.v1.IDestroyCryptoKeyVersionRequest + | null + | undefined, + {} | null | undefined + >, + ): void; destroyCryptoKeyVersion( - request?: protos.google.cloud.kms.v1.IDestroyCryptoKeyVersionRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.kms.v1.ICryptoKeyVersion, - protos.google.cloud.kms.v1.IDestroyCryptoKeyVersionRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.kms.v1.IDestroyCryptoKeyVersionRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.kms.v1.ICryptoKeyVersion, - protos.google.cloud.kms.v1.IDestroyCryptoKeyVersionRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.kms.v1.ICryptoKeyVersion, - protos.google.cloud.kms.v1.IDestroyCryptoKeyVersionRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.kms.v1.IDestroyCryptoKeyVersionRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.kms.v1.ICryptoKeyVersion, + | protos.google.cloud.kms.v1.IDestroyCryptoKeyVersionRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.kms.v1.ICryptoKeyVersion, + protos.google.cloud.kms.v1.IDestroyCryptoKeyVersionRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('destroyCryptoKeyVersion request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.kms.v1.ICryptoKeyVersion, - protos.google.cloud.kms.v1.IDestroyCryptoKeyVersionRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.kms.v1.ICryptoKeyVersion, + | protos.google.cloud.kms.v1.IDestroyCryptoKeyVersionRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('destroyCryptoKeyVersion response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.destroyCryptoKeyVersion(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.kms.v1.ICryptoKeyVersion, - protos.google.cloud.kms.v1.IDestroyCryptoKeyVersionRequest|undefined, - {}|undefined - ]) => { - this._log.info('destroyCryptoKeyVersion response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .destroyCryptoKeyVersion(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.kms.v1.ICryptoKeyVersion, + ( + | protos.google.cloud.kms.v1.IDestroyCryptoKeyVersionRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('destroyCryptoKeyVersion response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Restore a {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersion} in the - * {@link protos.google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DESTROY_SCHEDULED|DESTROY_SCHEDULED} - * state. - * - * Upon restoration of the CryptoKeyVersion, {@link protos.google.cloud.kms.v1.CryptoKeyVersion.state|state} - * will be set to {@link protos.google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DISABLED|DISABLED}, - * and {@link protos.google.cloud.kms.v1.CryptoKeyVersion.destroy_time|destroy_time} will be cleared. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * The resource name of the {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersion} to restore. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersion}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1/key_management_service.restore_crypto_key_version.js - * region_tag:cloudkms_v1_generated_KeyManagementService_RestoreCryptoKeyVersion_async - */ + /** + * Restore a {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersion} in the + * {@link protos.google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DESTROY_SCHEDULED|DESTROY_SCHEDULED} + * state. + * + * Upon restoration of the CryptoKeyVersion, {@link protos.google.cloud.kms.v1.CryptoKeyVersion.state|state} + * will be set to {@link protos.google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DISABLED|DISABLED}, + * and {@link protos.google.cloud.kms.v1.CryptoKeyVersion.destroy_time|destroy_time} will be cleared. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * The resource name of the {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersion} to restore. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersion}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/key_management_service.restore_crypto_key_version.js + * region_tag:cloudkms_v1_generated_KeyManagementService_RestoreCryptoKeyVersion_async + */ restoreCryptoKeyVersion( - request?: protos.google.cloud.kms.v1.IRestoreCryptoKeyVersionRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.kms.v1.ICryptoKeyVersion, - protos.google.cloud.kms.v1.IRestoreCryptoKeyVersionRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.kms.v1.IRestoreCryptoKeyVersionRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.kms.v1.ICryptoKeyVersion, + protos.google.cloud.kms.v1.IRestoreCryptoKeyVersionRequest | undefined, + {} | undefined, + ] + >; restoreCryptoKeyVersion( - request: protos.google.cloud.kms.v1.IRestoreCryptoKeyVersionRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.kms.v1.ICryptoKeyVersion, - protos.google.cloud.kms.v1.IRestoreCryptoKeyVersionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.kms.v1.IRestoreCryptoKeyVersionRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.kms.v1.ICryptoKeyVersion, + | protos.google.cloud.kms.v1.IRestoreCryptoKeyVersionRequest + | null + | undefined, + {} | null | undefined + >, + ): void; restoreCryptoKeyVersion( - request: protos.google.cloud.kms.v1.IRestoreCryptoKeyVersionRequest, - callback: Callback< - protos.google.cloud.kms.v1.ICryptoKeyVersion, - protos.google.cloud.kms.v1.IRestoreCryptoKeyVersionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.kms.v1.IRestoreCryptoKeyVersionRequest, + callback: Callback< + protos.google.cloud.kms.v1.ICryptoKeyVersion, + | protos.google.cloud.kms.v1.IRestoreCryptoKeyVersionRequest + | null + | undefined, + {} | null | undefined + >, + ): void; restoreCryptoKeyVersion( - request?: protos.google.cloud.kms.v1.IRestoreCryptoKeyVersionRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.kms.v1.ICryptoKeyVersion, - protos.google.cloud.kms.v1.IRestoreCryptoKeyVersionRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.kms.v1.IRestoreCryptoKeyVersionRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.kms.v1.ICryptoKeyVersion, - protos.google.cloud.kms.v1.IRestoreCryptoKeyVersionRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.kms.v1.ICryptoKeyVersion, - protos.google.cloud.kms.v1.IRestoreCryptoKeyVersionRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.kms.v1.IRestoreCryptoKeyVersionRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.kms.v1.ICryptoKeyVersion, + | protos.google.cloud.kms.v1.IRestoreCryptoKeyVersionRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.kms.v1.ICryptoKeyVersion, + protos.google.cloud.kms.v1.IRestoreCryptoKeyVersionRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('restoreCryptoKeyVersion request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.kms.v1.ICryptoKeyVersion, - protos.google.cloud.kms.v1.IRestoreCryptoKeyVersionRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.kms.v1.ICryptoKeyVersion, + | protos.google.cloud.kms.v1.IRestoreCryptoKeyVersionRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('restoreCryptoKeyVersion response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.restoreCryptoKeyVersion(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.kms.v1.ICryptoKeyVersion, - protos.google.cloud.kms.v1.IRestoreCryptoKeyVersionRequest|undefined, - {}|undefined - ]) => { - this._log.info('restoreCryptoKeyVersion response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .restoreCryptoKeyVersion(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.kms.v1.ICryptoKeyVersion, + ( + | protos.google.cloud.kms.v1.IRestoreCryptoKeyVersionRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('restoreCryptoKeyVersion response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } - /** - * Lists {@link protos.google.cloud.kms.v1.KeyRing|KeyRings}. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The resource name of the location associated with the - * {@link protos.google.cloud.kms.v1.KeyRing|KeyRings}, in the format `projects/* /locations/*`. - * @param {number} request.pageSize - * Optional limit on the number of {@link protos.google.cloud.kms.v1.KeyRing|KeyRings} to include in the - * response. Further {@link protos.google.cloud.kms.v1.KeyRing|KeyRings} can subsequently be obtained by - * including the {@link protos.google.cloud.kms.v1.ListKeyRingsResponse.next_page_token|ListKeyRingsResponse.next_page_token} in a subsequent - * request. If unspecified, the server will pick an appropriate default. - * @param {string} request.pageToken - * Optional pagination token, returned earlier via - * {@link protos.google.cloud.kms.v1.ListKeyRingsResponse.next_page_token|ListKeyRingsResponse.next_page_token}. - * @param {string} request.filter - * Optional. Only include resources that match the filter in the response. - * @param {string} request.orderBy - * Optional. Specify how the results should be sorted. If not specified, the - * results will be sorted in the default order. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.cloud.kms.v1.KeyRing|KeyRing}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `listKeyRingsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Lists {@link protos.google.cloud.kms.v1.KeyRing|KeyRings}. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The resource name of the location associated with the + * {@link protos.google.cloud.kms.v1.KeyRing|KeyRings}, in the format `projects/* /locations/*`. + * @param {number} request.pageSize + * Optional limit on the number of {@link protos.google.cloud.kms.v1.KeyRing|KeyRings} to include in the + * response. Further {@link protos.google.cloud.kms.v1.KeyRing|KeyRings} can subsequently be obtained by + * including the {@link protos.google.cloud.kms.v1.ListKeyRingsResponse.next_page_token|ListKeyRingsResponse.next_page_token} in a subsequent + * request. If unspecified, the server will pick an appropriate default. + * @param {string} request.pageToken + * Optional pagination token, returned earlier via + * {@link protos.google.cloud.kms.v1.ListKeyRingsResponse.next_page_token|ListKeyRingsResponse.next_page_token}. + * @param {string} request.filter + * Optional. Only include resources that match the filter in the response. + * @param {string} request.orderBy + * Optional. Specify how the results should be sorted. If not specified, the + * results will be sorted in the default order. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.cloud.kms.v1.KeyRing|KeyRing}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listKeyRingsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listKeyRings( - request?: protos.google.cloud.kms.v1.IListKeyRingsRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.kms.v1.IKeyRing[], - protos.google.cloud.kms.v1.IListKeyRingsRequest|null, - protos.google.cloud.kms.v1.IListKeyRingsResponse - ]>; + request?: protos.google.cloud.kms.v1.IListKeyRingsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.kms.v1.IKeyRing[], + protos.google.cloud.kms.v1.IListKeyRingsRequest | null, + protos.google.cloud.kms.v1.IListKeyRingsResponse, + ] + >; listKeyRings( - request: protos.google.cloud.kms.v1.IListKeyRingsRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.cloud.kms.v1.IListKeyRingsRequest, - protos.google.cloud.kms.v1.IListKeyRingsResponse|null|undefined, - protos.google.cloud.kms.v1.IKeyRing>): void; + request: protos.google.cloud.kms.v1.IListKeyRingsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.cloud.kms.v1.IListKeyRingsRequest, + protos.google.cloud.kms.v1.IListKeyRingsResponse | null | undefined, + protos.google.cloud.kms.v1.IKeyRing + >, + ): void; listKeyRings( - request: protos.google.cloud.kms.v1.IListKeyRingsRequest, - callback: PaginationCallback< - protos.google.cloud.kms.v1.IListKeyRingsRequest, - protos.google.cloud.kms.v1.IListKeyRingsResponse|null|undefined, - protos.google.cloud.kms.v1.IKeyRing>): void; + request: protos.google.cloud.kms.v1.IListKeyRingsRequest, + callback: PaginationCallback< + protos.google.cloud.kms.v1.IListKeyRingsRequest, + protos.google.cloud.kms.v1.IListKeyRingsResponse | null | undefined, + protos.google.cloud.kms.v1.IKeyRing + >, + ): void; listKeyRings( - request?: protos.google.cloud.kms.v1.IListKeyRingsRequest, - optionsOrCallback?: CallOptions|PaginationCallback< - protos.google.cloud.kms.v1.IListKeyRingsRequest, - protos.google.cloud.kms.v1.IListKeyRingsResponse|null|undefined, - protos.google.cloud.kms.v1.IKeyRing>, - callback?: PaginationCallback< + request?: protos.google.cloud.kms.v1.IListKeyRingsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.cloud.kms.v1.IListKeyRingsRequest, - protos.google.cloud.kms.v1.IListKeyRingsResponse|null|undefined, - protos.google.cloud.kms.v1.IKeyRing>): - Promise<[ - protos.google.cloud.kms.v1.IKeyRing[], - protos.google.cloud.kms.v1.IListKeyRingsRequest|null, - protos.google.cloud.kms.v1.IListKeyRingsResponse - ]>|void { + protos.google.cloud.kms.v1.IListKeyRingsResponse | null | undefined, + protos.google.cloud.kms.v1.IKeyRing + >, + callback?: PaginationCallback< + protos.google.cloud.kms.v1.IListKeyRingsRequest, + protos.google.cloud.kms.v1.IListKeyRingsResponse | null | undefined, + protos.google.cloud.kms.v1.IKeyRing + >, + ): Promise< + [ + protos.google.cloud.kms.v1.IKeyRing[], + protos.google.cloud.kms.v1.IListKeyRingsRequest | null, + protos.google.cloud.kms.v1.IListKeyRingsResponse, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.cloud.kms.v1.IListKeyRingsRequest, - protos.google.cloud.kms.v1.IListKeyRingsResponse|null|undefined, - protos.google.cloud.kms.v1.IKeyRing>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.cloud.kms.v1.IListKeyRingsRequest, + protos.google.cloud.kms.v1.IListKeyRingsResponse | null | undefined, + protos.google.cloud.kms.v1.IKeyRing + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listKeyRings values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -2379,221 +3128,240 @@ export class KeyManagementServiceClient { this._log.info('listKeyRings request %j', request); return this.innerApiCalls .listKeyRings(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.cloud.kms.v1.IKeyRing[], - protos.google.cloud.kms.v1.IListKeyRingsRequest|null, - protos.google.cloud.kms.v1.IListKeyRingsResponse - ]) => { - this._log.info('listKeyRings values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.cloud.kms.v1.IKeyRing[], + protos.google.cloud.kms.v1.IListKeyRingsRequest | null, + protos.google.cloud.kms.v1.IListKeyRingsResponse, + ]) => { + this._log.info('listKeyRings values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listKeyRings`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The resource name of the location associated with the - * {@link protos.google.cloud.kms.v1.KeyRing|KeyRings}, in the format `projects/* /locations/*`. - * @param {number} request.pageSize - * Optional limit on the number of {@link protos.google.cloud.kms.v1.KeyRing|KeyRings} to include in the - * response. Further {@link protos.google.cloud.kms.v1.KeyRing|KeyRings} can subsequently be obtained by - * including the {@link protos.google.cloud.kms.v1.ListKeyRingsResponse.next_page_token|ListKeyRingsResponse.next_page_token} in a subsequent - * request. If unspecified, the server will pick an appropriate default. - * @param {string} request.pageToken - * Optional pagination token, returned earlier via - * {@link protos.google.cloud.kms.v1.ListKeyRingsResponse.next_page_token|ListKeyRingsResponse.next_page_token}. - * @param {string} request.filter - * Optional. Only include resources that match the filter in the response. - * @param {string} request.orderBy - * Optional. Specify how the results should be sorted. If not specified, the - * results will be sorted in the default order. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.cloud.kms.v1.KeyRing|KeyRing} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `listKeyRingsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `listKeyRings`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The resource name of the location associated with the + * {@link protos.google.cloud.kms.v1.KeyRing|KeyRings}, in the format `projects/* /locations/*`. + * @param {number} request.pageSize + * Optional limit on the number of {@link protos.google.cloud.kms.v1.KeyRing|KeyRings} to include in the + * response. Further {@link protos.google.cloud.kms.v1.KeyRing|KeyRings} can subsequently be obtained by + * including the {@link protos.google.cloud.kms.v1.ListKeyRingsResponse.next_page_token|ListKeyRingsResponse.next_page_token} in a subsequent + * request. If unspecified, the server will pick an appropriate default. + * @param {string} request.pageToken + * Optional pagination token, returned earlier via + * {@link protos.google.cloud.kms.v1.ListKeyRingsResponse.next_page_token|ListKeyRingsResponse.next_page_token}. + * @param {string} request.filter + * Optional. Only include resources that match the filter in the response. + * @param {string} request.orderBy + * Optional. Specify how the results should be sorted. If not specified, the + * results will be sorted in the default order. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.cloud.kms.v1.KeyRing|KeyRing} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listKeyRingsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listKeyRingsStream( - request?: protos.google.cloud.kms.v1.IListKeyRingsRequest, - options?: CallOptions): - Transform{ + request?: protos.google.cloud.kms.v1.IListKeyRingsRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); const defaultCallSettings = this._defaults['listKeyRings']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listKeyRings stream %j', request); return this.descriptors.page.listKeyRings.createStream( this.innerApiCalls.listKeyRings as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listKeyRings`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The resource name of the location associated with the - * {@link protos.google.cloud.kms.v1.KeyRing|KeyRings}, in the format `projects/* /locations/*`. - * @param {number} request.pageSize - * Optional limit on the number of {@link protos.google.cloud.kms.v1.KeyRing|KeyRings} to include in the - * response. Further {@link protos.google.cloud.kms.v1.KeyRing|KeyRings} can subsequently be obtained by - * including the {@link protos.google.cloud.kms.v1.ListKeyRingsResponse.next_page_token|ListKeyRingsResponse.next_page_token} in a subsequent - * request. If unspecified, the server will pick an appropriate default. - * @param {string} request.pageToken - * Optional pagination token, returned earlier via - * {@link protos.google.cloud.kms.v1.ListKeyRingsResponse.next_page_token|ListKeyRingsResponse.next_page_token}. - * @param {string} request.filter - * Optional. Only include resources that match the filter in the response. - * @param {string} request.orderBy - * Optional. Specify how the results should be sorted. If not specified, the - * results will be sorted in the default order. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.cloud.kms.v1.KeyRing|KeyRing}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v1/key_management_service.list_key_rings.js - * region_tag:cloudkms_v1_generated_KeyManagementService_ListKeyRings_async - */ + /** + * Equivalent to `listKeyRings`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The resource name of the location associated with the + * {@link protos.google.cloud.kms.v1.KeyRing|KeyRings}, in the format `projects/* /locations/*`. + * @param {number} request.pageSize + * Optional limit on the number of {@link protos.google.cloud.kms.v1.KeyRing|KeyRings} to include in the + * response. Further {@link protos.google.cloud.kms.v1.KeyRing|KeyRings} can subsequently be obtained by + * including the {@link protos.google.cloud.kms.v1.ListKeyRingsResponse.next_page_token|ListKeyRingsResponse.next_page_token} in a subsequent + * request. If unspecified, the server will pick an appropriate default. + * @param {string} request.pageToken + * Optional pagination token, returned earlier via + * {@link protos.google.cloud.kms.v1.ListKeyRingsResponse.next_page_token|ListKeyRingsResponse.next_page_token}. + * @param {string} request.filter + * Optional. Only include resources that match the filter in the response. + * @param {string} request.orderBy + * Optional. Specify how the results should be sorted. If not specified, the + * results will be sorted in the default order. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.cloud.kms.v1.KeyRing|KeyRing}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v1/key_management_service.list_key_rings.js + * region_tag:cloudkms_v1_generated_KeyManagementService_ListKeyRings_async + */ listKeyRingsAsync( - request?: protos.google.cloud.kms.v1.IListKeyRingsRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.cloud.kms.v1.IListKeyRingsRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); const defaultCallSettings = this._defaults['listKeyRings']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listKeyRings iterate %j', request); return this.descriptors.page.listKeyRings.asyncIterate( this.innerApiCalls['listKeyRings'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } - /** - * Lists {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKeys}. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The resource name of the {@link protos.google.cloud.kms.v1.KeyRing|KeyRing} to list, in the format - * `projects/* /locations/* /keyRings/*`. - * @param {number} request.pageSize - * Optional limit on the number of {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKeys} to include in the - * response. Further {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKeys} can subsequently be obtained by - * including the {@link protos.google.cloud.kms.v1.ListCryptoKeysResponse.next_page_token|ListCryptoKeysResponse.next_page_token} in a subsequent - * request. If unspecified, the server will pick an appropriate default. - * @param {string} request.pageToken - * Optional pagination token, returned earlier via - * {@link protos.google.cloud.kms.v1.ListCryptoKeysResponse.next_page_token|ListCryptoKeysResponse.next_page_token}. - * @param {google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionView} request.versionView - * The fields of the primary version to include in the response. - * @param {string} request.filter - * Optional. Only include resources that match the filter in the response. - * @param {string} request.orderBy - * Optional. Specify how the results should be sorted. If not specified, the - * results will be sorted in the default order. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKey}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `listCryptoKeysAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Lists {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKeys}. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The resource name of the {@link protos.google.cloud.kms.v1.KeyRing|KeyRing} to list, in the format + * `projects/* /locations/* /keyRings/*`. + * @param {number} request.pageSize + * Optional limit on the number of {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKeys} to include in the + * response. Further {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKeys} can subsequently be obtained by + * including the {@link protos.google.cloud.kms.v1.ListCryptoKeysResponse.next_page_token|ListCryptoKeysResponse.next_page_token} in a subsequent + * request. If unspecified, the server will pick an appropriate default. + * @param {string} request.pageToken + * Optional pagination token, returned earlier via + * {@link protos.google.cloud.kms.v1.ListCryptoKeysResponse.next_page_token|ListCryptoKeysResponse.next_page_token}. + * @param {google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionView} request.versionView + * The fields of the primary version to include in the response. + * @param {string} request.filter + * Optional. Only include resources that match the filter in the response. + * @param {string} request.orderBy + * Optional. Specify how the results should be sorted. If not specified, the + * results will be sorted in the default order. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKey}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listCryptoKeysAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listCryptoKeys( - request?: protos.google.cloud.kms.v1.IListCryptoKeysRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.kms.v1.ICryptoKey[], - protos.google.cloud.kms.v1.IListCryptoKeysRequest|null, - protos.google.cloud.kms.v1.IListCryptoKeysResponse - ]>; + request?: protos.google.cloud.kms.v1.IListCryptoKeysRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.kms.v1.ICryptoKey[], + protos.google.cloud.kms.v1.IListCryptoKeysRequest | null, + protos.google.cloud.kms.v1.IListCryptoKeysResponse, + ] + >; listCryptoKeys( - request: protos.google.cloud.kms.v1.IListCryptoKeysRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.cloud.kms.v1.IListCryptoKeysRequest, - protos.google.cloud.kms.v1.IListCryptoKeysResponse|null|undefined, - protos.google.cloud.kms.v1.ICryptoKey>): void; + request: protos.google.cloud.kms.v1.IListCryptoKeysRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.cloud.kms.v1.IListCryptoKeysRequest, + protos.google.cloud.kms.v1.IListCryptoKeysResponse | null | undefined, + protos.google.cloud.kms.v1.ICryptoKey + >, + ): void; listCryptoKeys( - request: protos.google.cloud.kms.v1.IListCryptoKeysRequest, - callback: PaginationCallback< - protos.google.cloud.kms.v1.IListCryptoKeysRequest, - protos.google.cloud.kms.v1.IListCryptoKeysResponse|null|undefined, - protos.google.cloud.kms.v1.ICryptoKey>): void; + request: protos.google.cloud.kms.v1.IListCryptoKeysRequest, + callback: PaginationCallback< + protos.google.cloud.kms.v1.IListCryptoKeysRequest, + protos.google.cloud.kms.v1.IListCryptoKeysResponse | null | undefined, + protos.google.cloud.kms.v1.ICryptoKey + >, + ): void; listCryptoKeys( - request?: protos.google.cloud.kms.v1.IListCryptoKeysRequest, - optionsOrCallback?: CallOptions|PaginationCallback< - protos.google.cloud.kms.v1.IListCryptoKeysRequest, - protos.google.cloud.kms.v1.IListCryptoKeysResponse|null|undefined, - protos.google.cloud.kms.v1.ICryptoKey>, - callback?: PaginationCallback< + request?: protos.google.cloud.kms.v1.IListCryptoKeysRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.cloud.kms.v1.IListCryptoKeysRequest, - protos.google.cloud.kms.v1.IListCryptoKeysResponse|null|undefined, - protos.google.cloud.kms.v1.ICryptoKey>): - Promise<[ - protos.google.cloud.kms.v1.ICryptoKey[], - protos.google.cloud.kms.v1.IListCryptoKeysRequest|null, - protos.google.cloud.kms.v1.IListCryptoKeysResponse - ]>|void { + protos.google.cloud.kms.v1.IListCryptoKeysResponse | null | undefined, + protos.google.cloud.kms.v1.ICryptoKey + >, + callback?: PaginationCallback< + protos.google.cloud.kms.v1.IListCryptoKeysRequest, + protos.google.cloud.kms.v1.IListCryptoKeysResponse | null | undefined, + protos.google.cloud.kms.v1.ICryptoKey + >, + ): Promise< + [ + protos.google.cloud.kms.v1.ICryptoKey[], + protos.google.cloud.kms.v1.IListCryptoKeysRequest | null, + protos.google.cloud.kms.v1.IListCryptoKeysResponse, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.cloud.kms.v1.IListCryptoKeysRequest, - protos.google.cloud.kms.v1.IListCryptoKeysResponse|null|undefined, - protos.google.cloud.kms.v1.ICryptoKey>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.cloud.kms.v1.IListCryptoKeysRequest, + protos.google.cloud.kms.v1.IListCryptoKeysResponse | null | undefined, + protos.google.cloud.kms.v1.ICryptoKey + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listCryptoKeys values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -2602,226 +3370,255 @@ export class KeyManagementServiceClient { this._log.info('listCryptoKeys request %j', request); return this.innerApiCalls .listCryptoKeys(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.cloud.kms.v1.ICryptoKey[], - protos.google.cloud.kms.v1.IListCryptoKeysRequest|null, - protos.google.cloud.kms.v1.IListCryptoKeysResponse - ]) => { - this._log.info('listCryptoKeys values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.cloud.kms.v1.ICryptoKey[], + protos.google.cloud.kms.v1.IListCryptoKeysRequest | null, + protos.google.cloud.kms.v1.IListCryptoKeysResponse, + ]) => { + this._log.info('listCryptoKeys values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listCryptoKeys`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The resource name of the {@link protos.google.cloud.kms.v1.KeyRing|KeyRing} to list, in the format - * `projects/* /locations/* /keyRings/*`. - * @param {number} request.pageSize - * Optional limit on the number of {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKeys} to include in the - * response. Further {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKeys} can subsequently be obtained by - * including the {@link protos.google.cloud.kms.v1.ListCryptoKeysResponse.next_page_token|ListCryptoKeysResponse.next_page_token} in a subsequent - * request. If unspecified, the server will pick an appropriate default. - * @param {string} request.pageToken - * Optional pagination token, returned earlier via - * {@link protos.google.cloud.kms.v1.ListCryptoKeysResponse.next_page_token|ListCryptoKeysResponse.next_page_token}. - * @param {google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionView} request.versionView - * The fields of the primary version to include in the response. - * @param {string} request.filter - * Optional. Only include resources that match the filter in the response. - * @param {string} request.orderBy - * Optional. Specify how the results should be sorted. If not specified, the - * results will be sorted in the default order. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKey} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `listCryptoKeysAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `listCryptoKeys`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The resource name of the {@link protos.google.cloud.kms.v1.KeyRing|KeyRing} to list, in the format + * `projects/* /locations/* /keyRings/*`. + * @param {number} request.pageSize + * Optional limit on the number of {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKeys} to include in the + * response. Further {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKeys} can subsequently be obtained by + * including the {@link protos.google.cloud.kms.v1.ListCryptoKeysResponse.next_page_token|ListCryptoKeysResponse.next_page_token} in a subsequent + * request. If unspecified, the server will pick an appropriate default. + * @param {string} request.pageToken + * Optional pagination token, returned earlier via + * {@link protos.google.cloud.kms.v1.ListCryptoKeysResponse.next_page_token|ListCryptoKeysResponse.next_page_token}. + * @param {google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionView} request.versionView + * The fields of the primary version to include in the response. + * @param {string} request.filter + * Optional. Only include resources that match the filter in the response. + * @param {string} request.orderBy + * Optional. Specify how the results should be sorted. If not specified, the + * results will be sorted in the default order. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKey} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listCryptoKeysAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listCryptoKeysStream( - request?: protos.google.cloud.kms.v1.IListCryptoKeysRequest, - options?: CallOptions): - Transform{ + request?: protos.google.cloud.kms.v1.IListCryptoKeysRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); const defaultCallSettings = this._defaults['listCryptoKeys']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listCryptoKeys stream %j', request); return this.descriptors.page.listCryptoKeys.createStream( this.innerApiCalls.listCryptoKeys as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listCryptoKeys`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The resource name of the {@link protos.google.cloud.kms.v1.KeyRing|KeyRing} to list, in the format - * `projects/* /locations/* /keyRings/*`. - * @param {number} request.pageSize - * Optional limit on the number of {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKeys} to include in the - * response. Further {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKeys} can subsequently be obtained by - * including the {@link protos.google.cloud.kms.v1.ListCryptoKeysResponse.next_page_token|ListCryptoKeysResponse.next_page_token} in a subsequent - * request. If unspecified, the server will pick an appropriate default. - * @param {string} request.pageToken - * Optional pagination token, returned earlier via - * {@link protos.google.cloud.kms.v1.ListCryptoKeysResponse.next_page_token|ListCryptoKeysResponse.next_page_token}. - * @param {google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionView} request.versionView - * The fields of the primary version to include in the response. - * @param {string} request.filter - * Optional. Only include resources that match the filter in the response. - * @param {string} request.orderBy - * Optional. Specify how the results should be sorted. If not specified, the - * results will be sorted in the default order. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKey}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v1/key_management_service.list_crypto_keys.js - * region_tag:cloudkms_v1_generated_KeyManagementService_ListCryptoKeys_async - */ + /** + * Equivalent to `listCryptoKeys`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The resource name of the {@link protos.google.cloud.kms.v1.KeyRing|KeyRing} to list, in the format + * `projects/* /locations/* /keyRings/*`. + * @param {number} request.pageSize + * Optional limit on the number of {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKeys} to include in the + * response. Further {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKeys} can subsequently be obtained by + * including the {@link protos.google.cloud.kms.v1.ListCryptoKeysResponse.next_page_token|ListCryptoKeysResponse.next_page_token} in a subsequent + * request. If unspecified, the server will pick an appropriate default. + * @param {string} request.pageToken + * Optional pagination token, returned earlier via + * {@link protos.google.cloud.kms.v1.ListCryptoKeysResponse.next_page_token|ListCryptoKeysResponse.next_page_token}. + * @param {google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionView} request.versionView + * The fields of the primary version to include in the response. + * @param {string} request.filter + * Optional. Only include resources that match the filter in the response. + * @param {string} request.orderBy + * Optional. Specify how the results should be sorted. If not specified, the + * results will be sorted in the default order. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKey}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v1/key_management_service.list_crypto_keys.js + * region_tag:cloudkms_v1_generated_KeyManagementService_ListCryptoKeys_async + */ listCryptoKeysAsync( - request?: protos.google.cloud.kms.v1.IListCryptoKeysRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.cloud.kms.v1.IListCryptoKeysRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); const defaultCallSettings = this._defaults['listCryptoKeys']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listCryptoKeys iterate %j', request); return this.descriptors.page.listCryptoKeys.asyncIterate( this.innerApiCalls['listCryptoKeys'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } - /** - * Lists {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersions}. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The resource name of the {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKey} to list, in the format - * `projects/* /locations/* /keyRings/* /cryptoKeys/*`. - * @param {number} request.pageSize - * Optional limit on the number of {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersions} to - * include in the response. Further {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersions} can - * subsequently be obtained by including the - * {@link protos.google.cloud.kms.v1.ListCryptoKeyVersionsResponse.next_page_token|ListCryptoKeyVersionsResponse.next_page_token} in a subsequent request. - * If unspecified, the server will pick an appropriate default. - * @param {string} request.pageToken - * Optional pagination token, returned earlier via - * {@link protos.google.cloud.kms.v1.ListCryptoKeyVersionsResponse.next_page_token|ListCryptoKeyVersionsResponse.next_page_token}. - * @param {google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionView} request.view - * The fields to include in the response. - * @param {string} request.filter - * Optional. Only include resources that match the filter in the response. - * @param {string} request.orderBy - * Optional. Specify how the results should be sorted. If not specified, the - * results will be sorted in the default order. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersion}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `listCryptoKeyVersionsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Lists {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersions}. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The resource name of the {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKey} to list, in the format + * `projects/* /locations/* /keyRings/* /cryptoKeys/*`. + * @param {number} request.pageSize + * Optional limit on the number of {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersions} to + * include in the response. Further {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersions} can + * subsequently be obtained by including the + * {@link protos.google.cloud.kms.v1.ListCryptoKeyVersionsResponse.next_page_token|ListCryptoKeyVersionsResponse.next_page_token} in a subsequent request. + * If unspecified, the server will pick an appropriate default. + * @param {string} request.pageToken + * Optional pagination token, returned earlier via + * {@link protos.google.cloud.kms.v1.ListCryptoKeyVersionsResponse.next_page_token|ListCryptoKeyVersionsResponse.next_page_token}. + * @param {google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionView} request.view + * The fields to include in the response. + * @param {string} request.filter + * Optional. Only include resources that match the filter in the response. + * @param {string} request.orderBy + * Optional. Specify how the results should be sorted. If not specified, the + * results will be sorted in the default order. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersion}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listCryptoKeyVersionsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listCryptoKeyVersions( - request?: protos.google.cloud.kms.v1.IListCryptoKeyVersionsRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.kms.v1.ICryptoKeyVersion[], - protos.google.cloud.kms.v1.IListCryptoKeyVersionsRequest|null, - protos.google.cloud.kms.v1.IListCryptoKeyVersionsResponse - ]>; + request?: protos.google.cloud.kms.v1.IListCryptoKeyVersionsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.kms.v1.ICryptoKeyVersion[], + protos.google.cloud.kms.v1.IListCryptoKeyVersionsRequest | null, + protos.google.cloud.kms.v1.IListCryptoKeyVersionsResponse, + ] + >; listCryptoKeyVersions( - request: protos.google.cloud.kms.v1.IListCryptoKeyVersionsRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.cloud.kms.v1.IListCryptoKeyVersionsRequest, - protos.google.cloud.kms.v1.IListCryptoKeyVersionsResponse|null|undefined, - protos.google.cloud.kms.v1.ICryptoKeyVersion>): void; + request: protos.google.cloud.kms.v1.IListCryptoKeyVersionsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.cloud.kms.v1.IListCryptoKeyVersionsRequest, + | protos.google.cloud.kms.v1.IListCryptoKeyVersionsResponse + | null + | undefined, + protos.google.cloud.kms.v1.ICryptoKeyVersion + >, + ): void; listCryptoKeyVersions( - request: protos.google.cloud.kms.v1.IListCryptoKeyVersionsRequest, - callback: PaginationCallback< - protos.google.cloud.kms.v1.IListCryptoKeyVersionsRequest, - protos.google.cloud.kms.v1.IListCryptoKeyVersionsResponse|null|undefined, - protos.google.cloud.kms.v1.ICryptoKeyVersion>): void; + request: protos.google.cloud.kms.v1.IListCryptoKeyVersionsRequest, + callback: PaginationCallback< + protos.google.cloud.kms.v1.IListCryptoKeyVersionsRequest, + | protos.google.cloud.kms.v1.IListCryptoKeyVersionsResponse + | null + | undefined, + protos.google.cloud.kms.v1.ICryptoKeyVersion + >, + ): void; listCryptoKeyVersions( - request?: protos.google.cloud.kms.v1.IListCryptoKeyVersionsRequest, - optionsOrCallback?: CallOptions|PaginationCallback< - protos.google.cloud.kms.v1.IListCryptoKeyVersionsRequest, - protos.google.cloud.kms.v1.IListCryptoKeyVersionsResponse|null|undefined, - protos.google.cloud.kms.v1.ICryptoKeyVersion>, - callback?: PaginationCallback< + request?: protos.google.cloud.kms.v1.IListCryptoKeyVersionsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.cloud.kms.v1.IListCryptoKeyVersionsRequest, - protos.google.cloud.kms.v1.IListCryptoKeyVersionsResponse|null|undefined, - protos.google.cloud.kms.v1.ICryptoKeyVersion>): - Promise<[ - protos.google.cloud.kms.v1.ICryptoKeyVersion[], - protos.google.cloud.kms.v1.IListCryptoKeyVersionsRequest|null, - protos.google.cloud.kms.v1.IListCryptoKeyVersionsResponse - ]>|void { + | protos.google.cloud.kms.v1.IListCryptoKeyVersionsResponse + | null + | undefined, + protos.google.cloud.kms.v1.ICryptoKeyVersion + >, + callback?: PaginationCallback< + protos.google.cloud.kms.v1.IListCryptoKeyVersionsRequest, + | protos.google.cloud.kms.v1.IListCryptoKeyVersionsResponse + | null + | undefined, + protos.google.cloud.kms.v1.ICryptoKeyVersion + >, + ): Promise< + [ + protos.google.cloud.kms.v1.ICryptoKeyVersion[], + protos.google.cloud.kms.v1.IListCryptoKeyVersionsRequest | null, + protos.google.cloud.kms.v1.IListCryptoKeyVersionsResponse, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.cloud.kms.v1.IListCryptoKeyVersionsRequest, - protos.google.cloud.kms.v1.IListCryptoKeyVersionsResponse|null|undefined, - protos.google.cloud.kms.v1.ICryptoKeyVersion>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.cloud.kms.v1.IListCryptoKeyVersionsRequest, + | protos.google.cloud.kms.v1.IListCryptoKeyVersionsResponse + | null + | undefined, + protos.google.cloud.kms.v1.ICryptoKeyVersion + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listCryptoKeyVersions values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -2830,225 +3627,244 @@ export class KeyManagementServiceClient { this._log.info('listCryptoKeyVersions request %j', request); return this.innerApiCalls .listCryptoKeyVersions(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.cloud.kms.v1.ICryptoKeyVersion[], - protos.google.cloud.kms.v1.IListCryptoKeyVersionsRequest|null, - protos.google.cloud.kms.v1.IListCryptoKeyVersionsResponse - ]) => { - this._log.info('listCryptoKeyVersions values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.cloud.kms.v1.ICryptoKeyVersion[], + protos.google.cloud.kms.v1.IListCryptoKeyVersionsRequest | null, + protos.google.cloud.kms.v1.IListCryptoKeyVersionsResponse, + ]) => { + this._log.info('listCryptoKeyVersions values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listCryptoKeyVersions`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The resource name of the {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKey} to list, in the format - * `projects/* /locations/* /keyRings/* /cryptoKeys/*`. - * @param {number} request.pageSize - * Optional limit on the number of {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersions} to - * include in the response. Further {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersions} can - * subsequently be obtained by including the - * {@link protos.google.cloud.kms.v1.ListCryptoKeyVersionsResponse.next_page_token|ListCryptoKeyVersionsResponse.next_page_token} in a subsequent request. - * If unspecified, the server will pick an appropriate default. - * @param {string} request.pageToken - * Optional pagination token, returned earlier via - * {@link protos.google.cloud.kms.v1.ListCryptoKeyVersionsResponse.next_page_token|ListCryptoKeyVersionsResponse.next_page_token}. - * @param {google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionView} request.view - * The fields to include in the response. - * @param {string} request.filter - * Optional. Only include resources that match the filter in the response. - * @param {string} request.orderBy - * Optional. Specify how the results should be sorted. If not specified, the - * results will be sorted in the default order. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersion} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `listCryptoKeyVersionsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `listCryptoKeyVersions`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The resource name of the {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKey} to list, in the format + * `projects/* /locations/* /keyRings/* /cryptoKeys/*`. + * @param {number} request.pageSize + * Optional limit on the number of {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersions} to + * include in the response. Further {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersions} can + * subsequently be obtained by including the + * {@link protos.google.cloud.kms.v1.ListCryptoKeyVersionsResponse.next_page_token|ListCryptoKeyVersionsResponse.next_page_token} in a subsequent request. + * If unspecified, the server will pick an appropriate default. + * @param {string} request.pageToken + * Optional pagination token, returned earlier via + * {@link protos.google.cloud.kms.v1.ListCryptoKeyVersionsResponse.next_page_token|ListCryptoKeyVersionsResponse.next_page_token}. + * @param {google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionView} request.view + * The fields to include in the response. + * @param {string} request.filter + * Optional. Only include resources that match the filter in the response. + * @param {string} request.orderBy + * Optional. Specify how the results should be sorted. If not specified, the + * results will be sorted in the default order. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersion} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listCryptoKeyVersionsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listCryptoKeyVersionsStream( - request?: protos.google.cloud.kms.v1.IListCryptoKeyVersionsRequest, - options?: CallOptions): - Transform{ + request?: protos.google.cloud.kms.v1.IListCryptoKeyVersionsRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); const defaultCallSettings = this._defaults['listCryptoKeyVersions']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listCryptoKeyVersions stream %j', request); return this.descriptors.page.listCryptoKeyVersions.createStream( this.innerApiCalls.listCryptoKeyVersions as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listCryptoKeyVersions`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The resource name of the {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKey} to list, in the format - * `projects/* /locations/* /keyRings/* /cryptoKeys/*`. - * @param {number} request.pageSize - * Optional limit on the number of {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersions} to - * include in the response. Further {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersions} can - * subsequently be obtained by including the - * {@link protos.google.cloud.kms.v1.ListCryptoKeyVersionsResponse.next_page_token|ListCryptoKeyVersionsResponse.next_page_token} in a subsequent request. - * If unspecified, the server will pick an appropriate default. - * @param {string} request.pageToken - * Optional pagination token, returned earlier via - * {@link protos.google.cloud.kms.v1.ListCryptoKeyVersionsResponse.next_page_token|ListCryptoKeyVersionsResponse.next_page_token}. - * @param {google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionView} request.view - * The fields to include in the response. - * @param {string} request.filter - * Optional. Only include resources that match the filter in the response. - * @param {string} request.orderBy - * Optional. Specify how the results should be sorted. If not specified, the - * results will be sorted in the default order. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersion}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v1/key_management_service.list_crypto_key_versions.js - * region_tag:cloudkms_v1_generated_KeyManagementService_ListCryptoKeyVersions_async - */ + /** + * Equivalent to `listCryptoKeyVersions`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The resource name of the {@link protos.google.cloud.kms.v1.CryptoKey|CryptoKey} to list, in the format + * `projects/* /locations/* /keyRings/* /cryptoKeys/*`. + * @param {number} request.pageSize + * Optional limit on the number of {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersions} to + * include in the response. Further {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersions} can + * subsequently be obtained by including the + * {@link protos.google.cloud.kms.v1.ListCryptoKeyVersionsResponse.next_page_token|ListCryptoKeyVersionsResponse.next_page_token} in a subsequent request. + * If unspecified, the server will pick an appropriate default. + * @param {string} request.pageToken + * Optional pagination token, returned earlier via + * {@link protos.google.cloud.kms.v1.ListCryptoKeyVersionsResponse.next_page_token|ListCryptoKeyVersionsResponse.next_page_token}. + * @param {google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionView} request.view + * The fields to include in the response. + * @param {string} request.filter + * Optional. Only include resources that match the filter in the response. + * @param {string} request.orderBy + * Optional. Specify how the results should be sorted. If not specified, the + * results will be sorted in the default order. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.cloud.kms.v1.CryptoKeyVersion|CryptoKeyVersion}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v1/key_management_service.list_crypto_key_versions.js + * region_tag:cloudkms_v1_generated_KeyManagementService_ListCryptoKeyVersions_async + */ listCryptoKeyVersionsAsync( - request?: protos.google.cloud.kms.v1.IListCryptoKeyVersionsRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.cloud.kms.v1.IListCryptoKeyVersionsRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); const defaultCallSettings = this._defaults['listCryptoKeyVersions']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listCryptoKeyVersions iterate %j', request); return this.descriptors.page.listCryptoKeyVersions.asyncIterate( this.innerApiCalls['listCryptoKeyVersions'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } - /** - * Lists {@link protos.google.cloud.kms.v1.ImportJob|ImportJobs}. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The resource name of the {@link protos.google.cloud.kms.v1.KeyRing|KeyRing} to list, in the format - * `projects/* /locations/* /keyRings/*`. - * @param {number} request.pageSize - * Optional limit on the number of {@link protos.google.cloud.kms.v1.ImportJob|ImportJobs} to include in the - * response. Further {@link protos.google.cloud.kms.v1.ImportJob|ImportJobs} can subsequently be obtained by - * including the {@link protos.google.cloud.kms.v1.ListImportJobsResponse.next_page_token|ListImportJobsResponse.next_page_token} in a subsequent - * request. If unspecified, the server will pick an appropriate default. - * @param {string} request.pageToken - * Optional pagination token, returned earlier via - * {@link protos.google.cloud.kms.v1.ListImportJobsResponse.next_page_token|ListImportJobsResponse.next_page_token}. - * @param {string} request.filter - * Optional. Only include resources that match the filter in the response. - * @param {string} request.orderBy - * Optional. Specify how the results should be sorted. If not specified, the - * results will be sorted in the default order. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.cloud.kms.v1.ImportJob|ImportJob}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `listImportJobsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Lists {@link protos.google.cloud.kms.v1.ImportJob|ImportJobs}. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The resource name of the {@link protos.google.cloud.kms.v1.KeyRing|KeyRing} to list, in the format + * `projects/* /locations/* /keyRings/*`. + * @param {number} request.pageSize + * Optional limit on the number of {@link protos.google.cloud.kms.v1.ImportJob|ImportJobs} to include in the + * response. Further {@link protos.google.cloud.kms.v1.ImportJob|ImportJobs} can subsequently be obtained by + * including the {@link protos.google.cloud.kms.v1.ListImportJobsResponse.next_page_token|ListImportJobsResponse.next_page_token} in a subsequent + * request. If unspecified, the server will pick an appropriate default. + * @param {string} request.pageToken + * Optional pagination token, returned earlier via + * {@link protos.google.cloud.kms.v1.ListImportJobsResponse.next_page_token|ListImportJobsResponse.next_page_token}. + * @param {string} request.filter + * Optional. Only include resources that match the filter in the response. + * @param {string} request.orderBy + * Optional. Specify how the results should be sorted. If not specified, the + * results will be sorted in the default order. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.cloud.kms.v1.ImportJob|ImportJob}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listImportJobsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listImportJobs( - request?: protos.google.cloud.kms.v1.IListImportJobsRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.kms.v1.IImportJob[], - protos.google.cloud.kms.v1.IListImportJobsRequest|null, - protos.google.cloud.kms.v1.IListImportJobsResponse - ]>; + request?: protos.google.cloud.kms.v1.IListImportJobsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.kms.v1.IImportJob[], + protos.google.cloud.kms.v1.IListImportJobsRequest | null, + protos.google.cloud.kms.v1.IListImportJobsResponse, + ] + >; listImportJobs( - request: protos.google.cloud.kms.v1.IListImportJobsRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.cloud.kms.v1.IListImportJobsRequest, - protos.google.cloud.kms.v1.IListImportJobsResponse|null|undefined, - protos.google.cloud.kms.v1.IImportJob>): void; + request: protos.google.cloud.kms.v1.IListImportJobsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.cloud.kms.v1.IListImportJobsRequest, + protos.google.cloud.kms.v1.IListImportJobsResponse | null | undefined, + protos.google.cloud.kms.v1.IImportJob + >, + ): void; listImportJobs( - request: protos.google.cloud.kms.v1.IListImportJobsRequest, - callback: PaginationCallback< - protos.google.cloud.kms.v1.IListImportJobsRequest, - protos.google.cloud.kms.v1.IListImportJobsResponse|null|undefined, - protos.google.cloud.kms.v1.IImportJob>): void; + request: protos.google.cloud.kms.v1.IListImportJobsRequest, + callback: PaginationCallback< + protos.google.cloud.kms.v1.IListImportJobsRequest, + protos.google.cloud.kms.v1.IListImportJobsResponse | null | undefined, + protos.google.cloud.kms.v1.IImportJob + >, + ): void; listImportJobs( - request?: protos.google.cloud.kms.v1.IListImportJobsRequest, - optionsOrCallback?: CallOptions|PaginationCallback< + request?: protos.google.cloud.kms.v1.IListImportJobsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.cloud.kms.v1.IListImportJobsRequest, - protos.google.cloud.kms.v1.IListImportJobsResponse|null|undefined, - protos.google.cloud.kms.v1.IImportJob>, - callback?: PaginationCallback< - protos.google.cloud.kms.v1.IListImportJobsRequest, - protos.google.cloud.kms.v1.IListImportJobsResponse|null|undefined, - protos.google.cloud.kms.v1.IImportJob>): - Promise<[ - protos.google.cloud.kms.v1.IImportJob[], - protos.google.cloud.kms.v1.IListImportJobsRequest|null, - protos.google.cloud.kms.v1.IListImportJobsResponse - ]>|void { + protos.google.cloud.kms.v1.IListImportJobsResponse | null | undefined, + protos.google.cloud.kms.v1.IImportJob + >, + callback?: PaginationCallback< + protos.google.cloud.kms.v1.IListImportJobsRequest, + protos.google.cloud.kms.v1.IListImportJobsResponse | null | undefined, + protos.google.cloud.kms.v1.IImportJob + >, + ): Promise< + [ + protos.google.cloud.kms.v1.IImportJob[], + protos.google.cloud.kms.v1.IListImportJobsRequest | null, + protos.google.cloud.kms.v1.IListImportJobsResponse, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.cloud.kms.v1.IListImportJobsRequest, - protos.google.cloud.kms.v1.IListImportJobsResponse|null|undefined, - protos.google.cloud.kms.v1.IImportJob>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.cloud.kms.v1.IListImportJobsRequest, + protos.google.cloud.kms.v1.IListImportJobsResponse | null | undefined, + protos.google.cloud.kms.v1.IImportJob + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listImportJobs values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -3057,153 +3873,157 @@ export class KeyManagementServiceClient { this._log.info('listImportJobs request %j', request); return this.innerApiCalls .listImportJobs(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.cloud.kms.v1.IImportJob[], - protos.google.cloud.kms.v1.IListImportJobsRequest|null, - protos.google.cloud.kms.v1.IListImportJobsResponse - ]) => { - this._log.info('listImportJobs values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.cloud.kms.v1.IImportJob[], + protos.google.cloud.kms.v1.IListImportJobsRequest | null, + protos.google.cloud.kms.v1.IListImportJobsResponse, + ]) => { + this._log.info('listImportJobs values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listImportJobs`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The resource name of the {@link protos.google.cloud.kms.v1.KeyRing|KeyRing} to list, in the format - * `projects/* /locations/* /keyRings/*`. - * @param {number} request.pageSize - * Optional limit on the number of {@link protos.google.cloud.kms.v1.ImportJob|ImportJobs} to include in the - * response. Further {@link protos.google.cloud.kms.v1.ImportJob|ImportJobs} can subsequently be obtained by - * including the {@link protos.google.cloud.kms.v1.ListImportJobsResponse.next_page_token|ListImportJobsResponse.next_page_token} in a subsequent - * request. If unspecified, the server will pick an appropriate default. - * @param {string} request.pageToken - * Optional pagination token, returned earlier via - * {@link protos.google.cloud.kms.v1.ListImportJobsResponse.next_page_token|ListImportJobsResponse.next_page_token}. - * @param {string} request.filter - * Optional. Only include resources that match the filter in the response. - * @param {string} request.orderBy - * Optional. Specify how the results should be sorted. If not specified, the - * results will be sorted in the default order. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.cloud.kms.v1.ImportJob|ImportJob} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `listImportJobsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `listImportJobs`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The resource name of the {@link protos.google.cloud.kms.v1.KeyRing|KeyRing} to list, in the format + * `projects/* /locations/* /keyRings/*`. + * @param {number} request.pageSize + * Optional limit on the number of {@link protos.google.cloud.kms.v1.ImportJob|ImportJobs} to include in the + * response. Further {@link protos.google.cloud.kms.v1.ImportJob|ImportJobs} can subsequently be obtained by + * including the {@link protos.google.cloud.kms.v1.ListImportJobsResponse.next_page_token|ListImportJobsResponse.next_page_token} in a subsequent + * request. If unspecified, the server will pick an appropriate default. + * @param {string} request.pageToken + * Optional pagination token, returned earlier via + * {@link protos.google.cloud.kms.v1.ListImportJobsResponse.next_page_token|ListImportJobsResponse.next_page_token}. + * @param {string} request.filter + * Optional. Only include resources that match the filter in the response. + * @param {string} request.orderBy + * Optional. Specify how the results should be sorted. If not specified, the + * results will be sorted in the default order. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.cloud.kms.v1.ImportJob|ImportJob} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listImportJobsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listImportJobsStream( - request?: protos.google.cloud.kms.v1.IListImportJobsRequest, - options?: CallOptions): - Transform{ + request?: protos.google.cloud.kms.v1.IListImportJobsRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); const defaultCallSettings = this._defaults['listImportJobs']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listImportJobs stream %j', request); return this.descriptors.page.listImportJobs.createStream( this.innerApiCalls.listImportJobs as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listImportJobs`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The resource name of the {@link protos.google.cloud.kms.v1.KeyRing|KeyRing} to list, in the format - * `projects/* /locations/* /keyRings/*`. - * @param {number} request.pageSize - * Optional limit on the number of {@link protos.google.cloud.kms.v1.ImportJob|ImportJobs} to include in the - * response. Further {@link protos.google.cloud.kms.v1.ImportJob|ImportJobs} can subsequently be obtained by - * including the {@link protos.google.cloud.kms.v1.ListImportJobsResponse.next_page_token|ListImportJobsResponse.next_page_token} in a subsequent - * request. If unspecified, the server will pick an appropriate default. - * @param {string} request.pageToken - * Optional pagination token, returned earlier via - * {@link protos.google.cloud.kms.v1.ListImportJobsResponse.next_page_token|ListImportJobsResponse.next_page_token}. - * @param {string} request.filter - * Optional. Only include resources that match the filter in the response. - * @param {string} request.orderBy - * Optional. Specify how the results should be sorted. If not specified, the - * results will be sorted in the default order. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.cloud.kms.v1.ImportJob|ImportJob}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v1/key_management_service.list_import_jobs.js - * region_tag:cloudkms_v1_generated_KeyManagementService_ListImportJobs_async - */ + /** + * Equivalent to `listImportJobs`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The resource name of the {@link protos.google.cloud.kms.v1.KeyRing|KeyRing} to list, in the format + * `projects/* /locations/* /keyRings/*`. + * @param {number} request.pageSize + * Optional limit on the number of {@link protos.google.cloud.kms.v1.ImportJob|ImportJobs} to include in the + * response. Further {@link protos.google.cloud.kms.v1.ImportJob|ImportJobs} can subsequently be obtained by + * including the {@link protos.google.cloud.kms.v1.ListImportJobsResponse.next_page_token|ListImportJobsResponse.next_page_token} in a subsequent + * request. If unspecified, the server will pick an appropriate default. + * @param {string} request.pageToken + * Optional pagination token, returned earlier via + * {@link protos.google.cloud.kms.v1.ListImportJobsResponse.next_page_token|ListImportJobsResponse.next_page_token}. + * @param {string} request.filter + * Optional. Only include resources that match the filter in the response. + * @param {string} request.orderBy + * Optional. Specify how the results should be sorted. If not specified, the + * results will be sorted in the default order. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.cloud.kms.v1.ImportJob|ImportJob}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v1/key_management_service.list_import_jobs.js + * region_tag:cloudkms_v1_generated_KeyManagementService_ListImportJobs_async + */ listImportJobsAsync( - request?: protos.google.cloud.kms.v1.IListImportJobsRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.cloud.kms.v1.IListImportJobsRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); const defaultCallSettings = this._defaults['listImportJobs']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listImportJobs iterate %j', request); return this.descriptors.page.listImportJobs.asyncIterate( this.innerApiCalls['listImportJobs'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } -/** - * Gets the access control policy for a resource. Returns an empty policy - * if the resource exists and does not have a policy set. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.resource - * REQUIRED: The resource for which the policy is being requested. - * See the operation documentation for the appropriate value for this field. - * @param {Object} [request.options] - * OPTIONAL: A `GetPolicyOptions` object for specifying options to - * `GetIamPolicy`. This field is only used by Cloud IAM. - * - * This object should have the same structure as {@link google.iam.v1.GetPolicyOptions | GetPolicyOptions}. - * @param {Object} [options] - * Optional parameters. You can override the default settings for this call, e.g, timeout, - * retries, paginations, etc. See {@link https://googleapis.github.io/gax-nodejs/interfaces/CallOptions.html | gax.CallOptions} for the details. - * @param {function(?Error, ?Object)} [callback] - * The function which will be called with the result of the API call. - * - * The second parameter to the callback is an object representing {@link google.iam.v1.Policy | Policy}. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link google.iam.v1.Policy | Policy}. - * The promise has a method named "cancel" which cancels the ongoing API call. - */ + /** + * Gets the access control policy for a resource. Returns an empty policy + * if the resource exists and does not have a policy set. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.resource + * REQUIRED: The resource for which the policy is being requested. + * See the operation documentation for the appropriate value for this field. + * @param {Object} [request.options] + * OPTIONAL: A `GetPolicyOptions` object for specifying options to + * `GetIamPolicy`. This field is only used by Cloud IAM. + * + * This object should have the same structure as {@link google.iam.v1.GetPolicyOptions | GetPolicyOptions}. + * @param {Object} [options] + * Optional parameters. You can override the default settings for this call, e.g, timeout, + * retries, paginations, etc. See {@link https://googleapis.github.io/gax-nodejs/interfaces/CallOptions.html | gax.CallOptions} for the details. + * @param {function(?Error, ?Object)} [callback] + * The function which will be called with the result of the API call. + * + * The second parameter to the callback is an object representing {@link google.iam.v1.Policy | Policy}. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link google.iam.v1.Policy | Policy}. + * The promise has a method named "cancel" which cancels the ongoing API call. + */ getIamPolicy( request: IamProtos.google.iam.v1.GetIamPolicyRequest, options?: @@ -3217,40 +4037,40 @@ export class KeyManagementServiceClient { IamProtos.google.iam.v1.Policy, IamProtos.google.iam.v1.GetIamPolicyRequest | null | undefined, {} | null | undefined - > - ):Promise<[IamProtos.google.iam.v1.Policy]> { + >, + ): Promise<[IamProtos.google.iam.v1.Policy]> { return this.iamClient.getIamPolicy(request, options, callback); } -/** - * Returns permissions that a caller has on the specified resource. If the - * resource does not exist, this will return an empty set of - * permissions, not a NOT_FOUND error. - * - * Note: This operation is designed to be used for building - * permission-aware UIs and command-line tools, not for authorization - * checking. This operation may "fail open" without warning. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.resource - * REQUIRED: The resource for which the policy detail is being requested. - * See the operation documentation for the appropriate value for this field. - * @param {string[]} request.permissions - * The set of permissions to check for the `resource`. Permissions with - * wildcards (such as '*' or 'storage.*') are not allowed. For more - * information see {@link https://cloud.google.com/iam/docs/overview#permissions | IAM Overview }. - * @param {Object} [options] - * Optional parameters. You can override the default settings for this call, e.g, timeout, - * retries, paginations, etc. See {@link https://googleapis.github.io/gax-nodejs/interfaces/CallOptions.html | gax.CallOptions} for the details. - * @param {function(?Error, ?Object)} [callback] - * The function which will be called with the result of the API call. - * - * The second parameter to the callback is an object representing {@link google.iam.v1.TestIamPermissionsResponse | TestIamPermissionsResponse}. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link google.iam.v1.TestIamPermissionsResponse | TestIamPermissionsResponse}. - * The promise has a method named "cancel" which cancels the ongoing API call. - */ + /** + * Returns permissions that a caller has on the specified resource. If the + * resource does not exist, this will return an empty set of + * permissions, not a NOT_FOUND error. + * + * Note: This operation is designed to be used for building + * permission-aware UIs and command-line tools, not for authorization + * checking. This operation may "fail open" without warning. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.resource + * REQUIRED: The resource for which the policy detail is being requested. + * See the operation documentation for the appropriate value for this field. + * @param {string[]} request.permissions + * The set of permissions to check for the `resource`. Permissions with + * wildcards (such as '*' or 'storage.*') are not allowed. For more + * information see {@link https://cloud.google.com/iam/docs/overview#permissions | IAM Overview }. + * @param {Object} [options] + * Optional parameters. You can override the default settings for this call, e.g, timeout, + * retries, paginations, etc. See {@link https://googleapis.github.io/gax-nodejs/interfaces/CallOptions.html | gax.CallOptions} for the details. + * @param {function(?Error, ?Object)} [callback] + * The function which will be called with the result of the API call. + * + * The second parameter to the callback is an object representing {@link google.iam.v1.TestIamPermissionsResponse | TestIamPermissionsResponse}. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link google.iam.v1.TestIamPermissionsResponse | TestIamPermissionsResponse}. + * The promise has a method named "cancel" which cancels the ongoing API call. + */ setIamPolicy( request: IamProtos.google.iam.v1.SetIamPolicyRequest, options?: @@ -3264,41 +4084,41 @@ export class KeyManagementServiceClient { IamProtos.google.iam.v1.Policy, IamProtos.google.iam.v1.SetIamPolicyRequest | null | undefined, {} | null | undefined - > - ):Promise<[IamProtos.google.iam.v1.Policy]> { + >, + ): Promise<[IamProtos.google.iam.v1.Policy]> { return this.iamClient.setIamPolicy(request, options, callback); } -/** - * Returns permissions that a caller has on the specified resource. If the - * resource does not exist, this will return an empty set of - * permissions, not a NOT_FOUND error. - * - * Note: This operation is designed to be used for building - * permission-aware UIs and command-line tools, not for authorization - * checking. This operation may "fail open" without warning. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.resource - * REQUIRED: The resource for which the policy detail is being requested. - * See the operation documentation for the appropriate value for this field. - * @param {string[]} request.permissions - * The set of permissions to check for the `resource`. Permissions with - * wildcards (such as '*' or 'storage.*') are not allowed. For more - * information see {@link https://cloud.google.com/iam/docs/overview#permissions | IAM Overview }. - * @param {Object} [options] - * Optional parameters. You can override the default settings for this call, e.g, timeout, - * retries, paginations, etc. See {@link https://googleapis.github.io/gax-nodejs/interfaces/CallOptions.html | gax.CallOptions} for the details. - * @param {function(?Error, ?Object)} [callback] - * The function which will be called with the result of the API call. - * - * The second parameter to the callback is an object representing {@link google.iam.v1.TestIamPermissionsResponse | TestIamPermissionsResponse}. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link google.iam.v1.TestIamPermissionsResponse | TestIamPermissionsResponse}. - * The promise has a method named "cancel" which cancels the ongoing API call. - * - */ + /** + * Returns permissions that a caller has on the specified resource. If the + * resource does not exist, this will return an empty set of + * permissions, not a NOT_FOUND error. + * + * Note: This operation is designed to be used for building + * permission-aware UIs and command-line tools, not for authorization + * checking. This operation may "fail open" without warning. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.resource + * REQUIRED: The resource for which the policy detail is being requested. + * See the operation documentation for the appropriate value for this field. + * @param {string[]} request.permissions + * The set of permissions to check for the `resource`. Permissions with + * wildcards (such as '*' or 'storage.*') are not allowed. For more + * information see {@link https://cloud.google.com/iam/docs/overview#permissions | IAM Overview }. + * @param {Object} [options] + * Optional parameters. You can override the default settings for this call, e.g, timeout, + * retries, paginations, etc. See {@link https://googleapis.github.io/gax-nodejs/interfaces/CallOptions.html | gax.CallOptions} for the details. + * @param {function(?Error, ?Object)} [callback] + * The function which will be called with the result of the API call. + * + * The second parameter to the callback is an object representing {@link google.iam.v1.TestIamPermissionsResponse | TestIamPermissionsResponse}. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link google.iam.v1.TestIamPermissionsResponse | TestIamPermissionsResponse}. + * The promise has a method named "cancel" which cancels the ongoing API call. + * + */ testIamPermissions( request: IamProtos.google.iam.v1.TestIamPermissionsRequest, options?: @@ -3312,12 +4132,11 @@ export class KeyManagementServiceClient { IamProtos.google.iam.v1.TestIamPermissionsResponse, IamProtos.google.iam.v1.TestIamPermissionsRequest | null | undefined, {} | null | undefined - > - ):Promise<[IamProtos.google.iam.v1.TestIamPermissionsResponse]> { + >, + ): Promise<[IamProtos.google.iam.v1.TestIamPermissionsResponse]> { return this.iamClient.testIamPermissions(request, options, callback); } - /** * Terminate the gRPC channel and close the client. * @@ -3326,13 +4145,15 @@ export class KeyManagementServiceClient { */ close(): Promise { if (this.keyManagementServiceStub && !this._terminated) { - return this.keyManagementServiceStub.then(stub => { + return this.keyManagementServiceStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); - this.iamClient.close().catch(err => {throw err}); + this.iamClient.close().catch((err) => { + throw err; + }); }); } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/core/generator/gapic-generator-typescript/baselines/kms/system-test/fixtures/sample/src/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/kms/system-test/fixtures/sample/src/index.ts.baseline index b3732005b505..5fe0fd560143 100644 --- a/core/generator/gapic-generator-typescript/baselines/kms/system-test/fixtures/sample/src/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/kms/system-test/fixtures/sample/src/index.ts.baseline @@ -16,10 +16,12 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -import {KeyManagementServiceClient} from 'kms'; +import { KeyManagementServiceClient } from 'kms'; // check that the client class type name can be used -function doStuffWithKeyManagementServiceClient(client: KeyManagementServiceClient) { +function doStuffWithKeyManagementServiceClient( + client: KeyManagementServiceClient, +) { client.close(); } diff --git a/core/generator/gapic-generator-typescript/baselines/kms/system-test/install.ts.baseline b/core/generator/gapic-generator-typescript/baselines/kms/system-test/install.ts.baseline index f66069aa3940..ccf167042d2e 100644 --- a/core/generator/gapic-generator-typescript/baselines/kms/system-test/install.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/kms/system-test/install.ts.baseline @@ -16,34 +16,36 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -import {packNTest} from 'pack-n-play'; -import {readFileSync} from 'fs'; -import {describe, it} from 'mocha'; +import { packNTest } from 'pack-n-play'; +import { readFileSync } from 'fs'; +import { describe, it } from 'mocha'; describe('📦 pack-n-play test', () => { - - it('TypeScript code', async function() { + it('TypeScript code', async function () { this.timeout(300000); const options = { packageDir: process.cwd(), sample: { description: 'TypeScript user can use the type definitions', - ts: readFileSync('./system-test/fixtures/sample/src/index.ts').toString() - } + ts: readFileSync( + './system-test/fixtures/sample/src/index.ts', + ).toString(), + }, }; await packNTest(options); }); - it('JavaScript code', async function() { + it('JavaScript code', async function () { this.timeout(300000); const options = { packageDir: process.cwd(), sample: { description: 'JavaScript user can use the library', - cjs: readFileSync('./system-test/fixtures/sample/src/index.js').toString() - } + cjs: readFileSync( + './system-test/fixtures/sample/src/index.js', + ).toString(), + }, }; await packNTest(options); }); - }); diff --git a/core/generator/gapic-generator-typescript/baselines/kms/test/gapic_key_management_service_v1.ts.baseline b/core/generator/gapic-generator-typescript/baselines/kms/test/gapic_key_management_service_v1.ts.baseline index b0382f4b2d22..3944168f76c3 100644 --- a/core/generator/gapic-generator-typescript/baselines/kms/test/gapic_key_management_service_v1.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/kms/test/gapic_key_management_service_v1.ts.baseline @@ -19,3559 +19,4553 @@ import * as protos from '../protos/protos'; import * as assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as keymanagementserviceModule from '../src'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; -import {protobuf, IamProtos} from 'google-gax'; +import { protobuf, IamProtos } from 'google-gax'; // Dynamically loaded proto JSON is needed to get the type information // to fill in default values for request objects -const root = protobuf.Root.fromJSON(require('../protos/protos.json')).resolveAll(); +const root = protobuf.Root.fromJSON( + require('../protos/protos.json'), +).resolveAll(); // eslint-disable-next-line @typescript-eslint/no-unused-vars function getTypeDefaultValue(typeName: string, fields: string[]) { - let type = root.lookupType(typeName) as protobuf.Type; - for (const field of fields.slice(0, -1)) { - type = type.fields[field]?.resolvedType as protobuf.Type; - } - return type.fields[fields[fields.length - 1]]?.defaultValue; + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type.fields[field]?.resolvedType as protobuf.Type; + } + return type.fields[fields[fields.length - 1]]?.defaultValue; } function generateSampleMessage(instance: T) { - const filledObject = (instance.constructor as typeof protobuf.Message) - .toObject(instance as protobuf.Message, {defaults: true}); - return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, { defaults: true }); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; } function stubSimpleCall(response?: ResponseType, error?: Error) { - return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); } -function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { - return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +function stubSimpleCallWithCallback( + response?: ResponseType, + error?: Error, +) { + return error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); } -function stubPageStreamingCall(responses?: ResponseType[], error?: Error) { - const pagingStub = sinon.stub(); - if (responses) { - for (let i = 0; i < responses.length; ++i) { - pagingStub.onCall(i).callsArgWith(2, null, responses[i]); - } +function stubPageStreamingCall( + responses?: ResponseType[], + error?: Error, +) { + const pagingStub = sinon.stub(); + if (responses) { + for (let i = 0; i < responses.length; ++i) { + pagingStub.onCall(i).callsArgWith(2, null, responses[i]); } - const transformStub = error ? sinon.stub().callsArgWith(2, error) : pagingStub; - const mockStream = new PassThrough({ - objectMode: true, - transform: transformStub, - }); - // trigger as many responses as needed - if (responses) { - for (let i = 0; i < responses.length; ++i) { - setImmediate(() => { mockStream.write({}); }); - } - setImmediate(() => { mockStream.end(); }); - } else { - setImmediate(() => { mockStream.write({}); }); - setImmediate(() => { mockStream.end(); }); + } + const transformStub = error + ? sinon.stub().callsArgWith(2, error) + : pagingStub; + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + // trigger as many responses as needed + if (responses) { + for (let i = 0; i < responses.length; ++i) { + setImmediate(() => { + mockStream.write({}); + }); } - return sinon.stub().returns(mockStream); + setImmediate(() => { + mockStream.end(); + }); + } else { + setImmediate(() => { + mockStream.write({}); + }); + setImmediate(() => { + mockStream.end(); + }); + } + return sinon.stub().returns(mockStream); } -function stubAsyncIterationCall(responses?: ResponseType[], error?: Error) { - let counter = 0; - const asyncIterable = { - [Symbol.asyncIterator]() { - return { - async next() { - if (error) { - return Promise.reject(error); - } - if (counter >= responses!.length) { - return Promise.resolve({done: true, value: undefined}); - } - return Promise.resolve({done: false, value: responses![counter++]}); - } - }; - } - }; - return sinon.stub().returns(asyncIterable); +function stubAsyncIterationCall( + responses?: ResponseType[], + error?: Error, +) { + let counter = 0; + const asyncIterable = { + [Symbol.asyncIterator]() { + return { + async next() { + if (error) { + return Promise.reject(error); + } + if (counter >= responses!.length) { + return Promise.resolve({ done: true, value: undefined }); + } + return Promise.resolve({ done: false, value: responses![counter++] }); + }, + }; + }, + }; + return sinon.stub().returns(asyncIterable); } describe('v1.KeyManagementServiceClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'cloudkms.googleapis.com'); - }); - - it('has universeDomain', () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); - - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - it('throws DeprecationWarning if static servicePath is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const servicePath = keymanagementserviceModule.v1.KeyManagementServiceClient.servicePath; - assert.strictEqual(servicePath, 'cloudkms.googleapis.com'); - assert(stub.called); - stub.restore(); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'cloudkms.googleapis.com'); + }); - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = keymanagementserviceModule.v1.KeyManagementServiceClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'cloudkms.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'cloudkms.example.com'); - }); - - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'cloudkms.example.com'); - }); - - if (typeof process === 'object' && 'env' in process) { - describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { - it('sets apiEndpoint from environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'cloudkms.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - - it('value configured in code has priority over environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'cloudkms.configured.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { new keymanagementserviceModule.v1.KeyManagementServiceClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); + it('has universeDomain', () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); + + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = + keymanagementserviceModule.v1.KeyManagementServiceClient.servicePath; + assert.strictEqual(servicePath, 'cloudkms.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + keymanagementserviceModule.v1.KeyManagementServiceClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'cloudkms.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + universeDomain: 'example.com', }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'cloudkms.example.com'); + }); - it('has port', () => { - const port = keymanagementserviceModule.v1.KeyManagementServiceClient.port; - assert(port); - assert(typeof port === 'number'); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + universe_domain: 'example.com', }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'cloudkms.example.com'); + }); - it('should create a client with no option', () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient(); - assert(client); + if (typeof process === 'object' && 'env' in process) { + describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { + it('sets apiEndpoint from environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'cloudkms.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - it('should create a client with gRPC fallback', () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - fallback: true, - }); - assert(client); + it('value configured in code has priority over environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + universeDomain: 'configured.example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'cloudkms.configured.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } + }); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); + }); - it('has initialize method and supports deferred initialization', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.keyManagementServiceStub, undefined); - await client.initialize(); - assert(client.keyManagementServiceStub); + it('has port', () => { + const port = + keymanagementserviceModule.v1.KeyManagementServiceClient.port; + assert(port); + assert(typeof port === 'number'); + }); + + it('should create a client with no option', () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient(); + assert(client); + }); + + it('should create a client with gRPC fallback', () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + fallback: true, }); + assert(client); + }); - it('has close method for the initialized client', done => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.keyManagementServiceStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); + it('has initialize method and supports deferred initialization', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + assert.strictEqual(client.keyManagementServiceStub, undefined); + await client.initialize(); + assert(client.keyManagementServiceStub); + }); - it('has close method for the non-initialized client', done => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.keyManagementServiceStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); + it('has close method for the initialized client', (done) => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.keyManagementServiceStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + it('has close method for the non-initialized client', (done) => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + assert.strictEqual(client.keyManagementServiceStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; + }); + }); - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId((err?: Error|null, projectId?: string|null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } - }); - }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); }); - describe('getKeyRing', () => { - it('invokes getKeyRing without error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.GetKeyRingRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.GetKeyRingRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.kms.v1.KeyRing() - ); - client.innerApiCalls.getKeyRing = stubSimpleCall(expectedResponse); - const [response] = await client.getKeyRing(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getKeyRing as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getKeyRing as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getKeyRing without error using callback', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.GetKeyRingRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.GetKeyRingRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.kms.v1.KeyRing() - ); - client.innerApiCalls.getKeyRing = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getKeyRing( - request, - (err?: Error|null, result?: protos.google.cloud.kms.v1.IKeyRing|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getKeyRing as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getKeyRing as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getKeyRing with error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.GetKeyRingRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.GetKeyRingRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getKeyRing = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getKeyRing(request), expectedError); - const actualRequest = (client.innerApiCalls.getKeyRing as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getKeyRing as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getKeyRing with closed client', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.GetKeyRingRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.GetKeyRingRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getKeyRing(request), expectedError); - }); - }); - - describe('getCryptoKey', () => { - it('invokes getCryptoKey without error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.GetCryptoKeyRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.GetCryptoKeyRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.kms.v1.CryptoKey() - ); - client.innerApiCalls.getCryptoKey = stubSimpleCall(expectedResponse); - const [response] = await client.getCryptoKey(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getCryptoKey as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getCryptoKey as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getCryptoKey without error using callback', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.GetCryptoKeyRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.GetCryptoKeyRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.kms.v1.CryptoKey() - ); - client.innerApiCalls.getCryptoKey = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getCryptoKey( - request, - (err?: Error|null, result?: protos.google.cloud.kms.v1.ICryptoKey|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getCryptoKey as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getCryptoKey as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getCryptoKey with error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.GetCryptoKeyRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.GetCryptoKeyRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getCryptoKey = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getCryptoKey(request), expectedError); - const actualRequest = (client.innerApiCalls.getCryptoKey as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getCryptoKey as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getCryptoKey with closed client', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.GetCryptoKeyRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.GetCryptoKeyRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getCryptoKey(request), expectedError); - }); - }); - - describe('getCryptoKeyVersion', () => { - it('invokes getCryptoKeyVersion without error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.GetCryptoKeyVersionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.GetCryptoKeyVersionRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.kms.v1.CryptoKeyVersion() - ); - client.innerApiCalls.getCryptoKeyVersion = stubSimpleCall(expectedResponse); - const [response] = await client.getCryptoKeyVersion(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getCryptoKeyVersion as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getCryptoKeyVersion as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getCryptoKeyVersion without error using callback', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.GetCryptoKeyVersionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.GetCryptoKeyVersionRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.kms.v1.CryptoKeyVersion() - ); - client.innerApiCalls.getCryptoKeyVersion = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getCryptoKeyVersion( - request, - (err?: Error|null, result?: protos.google.cloud.kms.v1.ICryptoKeyVersion|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getCryptoKeyVersion as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getCryptoKeyVersion as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getCryptoKeyVersion with error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.GetCryptoKeyVersionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.GetCryptoKeyVersionRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getCryptoKeyVersion = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getCryptoKeyVersion(request), expectedError); - const actualRequest = (client.innerApiCalls.getCryptoKeyVersion as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getCryptoKeyVersion as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getCryptoKeyVersion with closed client', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.GetCryptoKeyVersionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.GetCryptoKeyVersionRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getCryptoKeyVersion(request), expectedError); - }); - }); - - describe('getPublicKey', () => { - it('invokes getPublicKey without error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.GetPublicKeyRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.GetPublicKeyRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.kms.v1.PublicKey() - ); - client.innerApiCalls.getPublicKey = stubSimpleCall(expectedResponse); - const [response] = await client.getPublicKey(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getPublicKey as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getPublicKey as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getPublicKey without error using callback', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.GetPublicKeyRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.GetPublicKeyRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.kms.v1.PublicKey() - ); - client.innerApiCalls.getPublicKey = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getPublicKey( - request, - (err?: Error|null, result?: protos.google.cloud.kms.v1.IPublicKey|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getPublicKey as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getPublicKey as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getPublicKey with error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.GetPublicKeyRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.GetPublicKeyRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getPublicKey = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getPublicKey(request), expectedError); - const actualRequest = (client.innerApiCalls.getPublicKey as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getPublicKey as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getPublicKey with closed client', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.GetPublicKeyRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.GetPublicKeyRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getPublicKey(request), expectedError); - }); - }); - - describe('getImportJob', () => { - it('invokes getImportJob without error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.GetImportJobRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.GetImportJobRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.kms.v1.ImportJob() - ); - client.innerApiCalls.getImportJob = stubSimpleCall(expectedResponse); - const [response] = await client.getImportJob(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getImportJob as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getImportJob as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getImportJob without error using callback', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.GetImportJobRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.GetImportJobRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.kms.v1.ImportJob() - ); - client.innerApiCalls.getImportJob = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getImportJob( - request, - (err?: Error|null, result?: protos.google.cloud.kms.v1.IImportJob|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getImportJob as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getImportJob as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getImportJob with error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.GetImportJobRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.GetImportJobRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getImportJob = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getImportJob(request), expectedError); - const actualRequest = (client.innerApiCalls.getImportJob as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getImportJob as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getImportJob with closed client', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.GetImportJobRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.GetImportJobRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getImportJob(request), expectedError); - }); - }); - - describe('createKeyRing', () => { - it('invokes createKeyRing without error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.CreateKeyRingRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.CreateKeyRingRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.kms.v1.KeyRing() - ); - client.innerApiCalls.createKeyRing = stubSimpleCall(expectedResponse); - const [response] = await client.createKeyRing(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createKeyRing as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createKeyRing as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createKeyRing without error using callback', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.CreateKeyRingRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.CreateKeyRingRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.kms.v1.KeyRing() - ); - client.innerApiCalls.createKeyRing = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createKeyRing( - request, - (err?: Error|null, result?: protos.google.cloud.kms.v1.IKeyRing|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createKeyRing as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createKeyRing as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createKeyRing with error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.CreateKeyRingRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.CreateKeyRingRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createKeyRing = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createKeyRing(request), expectedError); - const actualRequest = (client.innerApiCalls.createKeyRing as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createKeyRing as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createKeyRing with closed client', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.CreateKeyRingRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.CreateKeyRingRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createKeyRing(request), expectedError); - }); - }); - - describe('createCryptoKey', () => { - it('invokes createCryptoKey without error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.CreateCryptoKeyRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.CreateCryptoKeyRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.kms.v1.CryptoKey() - ); - client.innerApiCalls.createCryptoKey = stubSimpleCall(expectedResponse); - const [response] = await client.createCryptoKey(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createCryptoKey as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createCryptoKey as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createCryptoKey without error using callback', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.CreateCryptoKeyRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.CreateCryptoKeyRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.kms.v1.CryptoKey() - ); - client.innerApiCalls.createCryptoKey = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createCryptoKey( - request, - (err?: Error|null, result?: protos.google.cloud.kms.v1.ICryptoKey|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createCryptoKey as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createCryptoKey as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createCryptoKey with error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.CreateCryptoKeyRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.CreateCryptoKeyRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createCryptoKey = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createCryptoKey(request), expectedError); - const actualRequest = (client.innerApiCalls.createCryptoKey as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createCryptoKey as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createCryptoKey with closed client', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.CreateCryptoKeyRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.CreateCryptoKeyRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createCryptoKey(request), expectedError); - }); - }); - - describe('createCryptoKeyVersion', () => { - it('invokes createCryptoKeyVersion without error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.CreateCryptoKeyVersionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.CreateCryptoKeyVersionRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.kms.v1.CryptoKeyVersion() - ); - client.innerApiCalls.createCryptoKeyVersion = stubSimpleCall(expectedResponse); - const [response] = await client.createCryptoKeyVersion(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createCryptoKeyVersion as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createCryptoKeyVersion as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createCryptoKeyVersion without error using callback', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.CreateCryptoKeyVersionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.CreateCryptoKeyVersionRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.kms.v1.CryptoKeyVersion() - ); - client.innerApiCalls.createCryptoKeyVersion = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createCryptoKeyVersion( - request, - (err?: Error|null, result?: protos.google.cloud.kms.v1.ICryptoKeyVersion|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createCryptoKeyVersion as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createCryptoKeyVersion as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createCryptoKeyVersion with error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.CreateCryptoKeyVersionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.CreateCryptoKeyVersionRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createCryptoKeyVersion = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createCryptoKeyVersion(request), expectedError); - const actualRequest = (client.innerApiCalls.createCryptoKeyVersion as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createCryptoKeyVersion as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createCryptoKeyVersion with closed client', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.CreateCryptoKeyVersionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.CreateCryptoKeyVersionRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createCryptoKeyVersion(request), expectedError); - }); - }); - - describe('importCryptoKeyVersion', () => { - it('invokes importCryptoKeyVersion without error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.ImportCryptoKeyVersionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.ImportCryptoKeyVersionRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.kms.v1.CryptoKeyVersion() - ); - client.innerApiCalls.importCryptoKeyVersion = stubSimpleCall(expectedResponse); - const [response] = await client.importCryptoKeyVersion(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.importCryptoKeyVersion as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.importCryptoKeyVersion as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes importCryptoKeyVersion without error using callback', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.ImportCryptoKeyVersionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.ImportCryptoKeyVersionRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.kms.v1.CryptoKeyVersion() - ); - client.innerApiCalls.importCryptoKeyVersion = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.importCryptoKeyVersion( - request, - (err?: Error|null, result?: protos.google.cloud.kms.v1.ICryptoKeyVersion|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.importCryptoKeyVersion as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.importCryptoKeyVersion as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes importCryptoKeyVersion with error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.ImportCryptoKeyVersionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.ImportCryptoKeyVersionRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.importCryptoKeyVersion = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.importCryptoKeyVersion(request), expectedError); - const actualRequest = (client.innerApiCalls.importCryptoKeyVersion as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.importCryptoKeyVersion as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes importCryptoKeyVersion with closed client', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.ImportCryptoKeyVersionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.ImportCryptoKeyVersionRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.importCryptoKeyVersion(request), expectedError); - }); - }); - - describe('createImportJob', () => { - it('invokes createImportJob without error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.CreateImportJobRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.CreateImportJobRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.kms.v1.ImportJob() - ); - client.innerApiCalls.createImportJob = stubSimpleCall(expectedResponse); - const [response] = await client.createImportJob(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createImportJob as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createImportJob as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createImportJob without error using callback', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.CreateImportJobRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.CreateImportJobRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.kms.v1.ImportJob() - ); - client.innerApiCalls.createImportJob = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createImportJob( - request, - (err?: Error|null, result?: protos.google.cloud.kms.v1.IImportJob|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createImportJob as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createImportJob as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createImportJob with error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.CreateImportJobRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.CreateImportJobRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createImportJob = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createImportJob(request), expectedError); - const actualRequest = (client.innerApiCalls.createImportJob as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createImportJob as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createImportJob with closed client', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.CreateImportJobRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.CreateImportJobRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createImportJob(request), expectedError); - }); - }); - - describe('updateCryptoKey', () => { - it('invokes updateCryptoKey without error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.UpdateCryptoKeyRequest() - ); - request.cryptoKey ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.UpdateCryptoKeyRequest', ['cryptoKey', 'name']); - request.cryptoKey.name = defaultValue1; - const expectedHeaderRequestParams = `crypto_key.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.kms.v1.CryptoKey() - ); - client.innerApiCalls.updateCryptoKey = stubSimpleCall(expectedResponse); - const [response] = await client.updateCryptoKey(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateCryptoKey as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateCryptoKey as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateCryptoKey without error using callback', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.UpdateCryptoKeyRequest() - ); - request.cryptoKey ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.UpdateCryptoKeyRequest', ['cryptoKey', 'name']); - request.cryptoKey.name = defaultValue1; - const expectedHeaderRequestParams = `crypto_key.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.kms.v1.CryptoKey() - ); - client.innerApiCalls.updateCryptoKey = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateCryptoKey( - request, - (err?: Error|null, result?: protos.google.cloud.kms.v1.ICryptoKey|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateCryptoKey as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateCryptoKey as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateCryptoKey with error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.UpdateCryptoKeyRequest() - ); - request.cryptoKey ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.UpdateCryptoKeyRequest', ['cryptoKey', 'name']); - request.cryptoKey.name = defaultValue1; - const expectedHeaderRequestParams = `crypto_key.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateCryptoKey = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateCryptoKey(request), expectedError); - const actualRequest = (client.innerApiCalls.updateCryptoKey as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateCryptoKey as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateCryptoKey with closed client', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.UpdateCryptoKeyRequest() - ); - request.cryptoKey ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.UpdateCryptoKeyRequest', ['cryptoKey', 'name']); - request.cryptoKey.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateCryptoKey(request), expectedError); - }); - }); - - describe('updateCryptoKeyVersion', () => { - it('invokes updateCryptoKeyVersion without error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.UpdateCryptoKeyVersionRequest() - ); - request.cryptoKeyVersion ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.UpdateCryptoKeyVersionRequest', ['cryptoKeyVersion', 'name']); - request.cryptoKeyVersion.name = defaultValue1; - const expectedHeaderRequestParams = `crypto_key_version.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.kms.v1.CryptoKeyVersion() - ); - client.innerApiCalls.updateCryptoKeyVersion = stubSimpleCall(expectedResponse); - const [response] = await client.updateCryptoKeyVersion(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateCryptoKeyVersion as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateCryptoKeyVersion as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateCryptoKeyVersion without error using callback', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.UpdateCryptoKeyVersionRequest() - ); - request.cryptoKeyVersion ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.UpdateCryptoKeyVersionRequest', ['cryptoKeyVersion', 'name']); - request.cryptoKeyVersion.name = defaultValue1; - const expectedHeaderRequestParams = `crypto_key_version.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.kms.v1.CryptoKeyVersion() - ); - client.innerApiCalls.updateCryptoKeyVersion = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateCryptoKeyVersion( - request, - (err?: Error|null, result?: protos.google.cloud.kms.v1.ICryptoKeyVersion|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateCryptoKeyVersion as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateCryptoKeyVersion as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateCryptoKeyVersion with error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.UpdateCryptoKeyVersionRequest() - ); - request.cryptoKeyVersion ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.UpdateCryptoKeyVersionRequest', ['cryptoKeyVersion', 'name']); - request.cryptoKeyVersion.name = defaultValue1; - const expectedHeaderRequestParams = `crypto_key_version.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateCryptoKeyVersion = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateCryptoKeyVersion(request), expectedError); - const actualRequest = (client.innerApiCalls.updateCryptoKeyVersion as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateCryptoKeyVersion as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateCryptoKeyVersion with closed client', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.UpdateCryptoKeyVersionRequest() - ); - request.cryptoKeyVersion ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.UpdateCryptoKeyVersionRequest', ['cryptoKeyVersion', 'name']); - request.cryptoKeyVersion.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateCryptoKeyVersion(request), expectedError); - }); - }); - - describe('encrypt', () => { - it('invokes encrypt without error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.EncryptRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.EncryptRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.kms.v1.EncryptResponse() - ); - client.innerApiCalls.encrypt = stubSimpleCall(expectedResponse); - const [response] = await client.encrypt(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.encrypt as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.encrypt as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes encrypt without error using callback', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.EncryptRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.EncryptRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.kms.v1.EncryptResponse() - ); - client.innerApiCalls.encrypt = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.encrypt( - request, - (err?: Error|null, result?: protos.google.cloud.kms.v1.IEncryptResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.encrypt as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.encrypt as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes encrypt with error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.EncryptRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.EncryptRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.encrypt = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.encrypt(request), expectedError); - const actualRequest = (client.innerApiCalls.encrypt as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.encrypt as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes encrypt with closed client', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.EncryptRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.EncryptRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.encrypt(request), expectedError); - }); - }); - - describe('decrypt', () => { - it('invokes decrypt without error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.DecryptRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.DecryptRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.kms.v1.DecryptResponse() - ); - client.innerApiCalls.decrypt = stubSimpleCall(expectedResponse); - const [response] = await client.decrypt(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.decrypt as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.decrypt as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes decrypt without error using callback', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.DecryptRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.DecryptRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.kms.v1.DecryptResponse() - ); - client.innerApiCalls.decrypt = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.decrypt( - request, - (err?: Error|null, result?: protos.google.cloud.kms.v1.IDecryptResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.decrypt as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.decrypt as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes decrypt with error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.DecryptRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.DecryptRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.decrypt = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.decrypt(request), expectedError); - const actualRequest = (client.innerApiCalls.decrypt as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.decrypt as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes decrypt with closed client', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.DecryptRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.DecryptRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.decrypt(request), expectedError); - }); - }); - - describe('asymmetricSign', () => { - it('invokes asymmetricSign without error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.AsymmetricSignRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.AsymmetricSignRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.kms.v1.AsymmetricSignResponse() - ); - client.innerApiCalls.asymmetricSign = stubSimpleCall(expectedResponse); - const [response] = await client.asymmetricSign(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.asymmetricSign as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.asymmetricSign as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes asymmetricSign without error using callback', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.AsymmetricSignRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.AsymmetricSignRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.kms.v1.AsymmetricSignResponse() - ); - client.innerApiCalls.asymmetricSign = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.asymmetricSign( - request, - (err?: Error|null, result?: protos.google.cloud.kms.v1.IAsymmetricSignResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.asymmetricSign as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.asymmetricSign as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes asymmetricSign with error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.AsymmetricSignRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.AsymmetricSignRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.asymmetricSign = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.asymmetricSign(request), expectedError); - const actualRequest = (client.innerApiCalls.asymmetricSign as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.asymmetricSign as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes asymmetricSign with closed client', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.AsymmetricSignRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.AsymmetricSignRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.asymmetricSign(request), expectedError); - }); - }); - - describe('asymmetricDecrypt', () => { - it('invokes asymmetricDecrypt without error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.AsymmetricDecryptRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.AsymmetricDecryptRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.kms.v1.AsymmetricDecryptResponse() - ); - client.innerApiCalls.asymmetricDecrypt = stubSimpleCall(expectedResponse); - const [response] = await client.asymmetricDecrypt(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.asymmetricDecrypt as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.asymmetricDecrypt as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes asymmetricDecrypt without error using callback', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.AsymmetricDecryptRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.AsymmetricDecryptRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.kms.v1.AsymmetricDecryptResponse() - ); - client.innerApiCalls.asymmetricDecrypt = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.asymmetricDecrypt( - request, - (err?: Error|null, result?: protos.google.cloud.kms.v1.IAsymmetricDecryptResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.asymmetricDecrypt as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.asymmetricDecrypt as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes asymmetricDecrypt with error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.AsymmetricDecryptRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.AsymmetricDecryptRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.asymmetricDecrypt = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.asymmetricDecrypt(request), expectedError); - const actualRequest = (client.innerApiCalls.asymmetricDecrypt as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.asymmetricDecrypt as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes asymmetricDecrypt with closed client', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.AsymmetricDecryptRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.AsymmetricDecryptRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.asymmetricDecrypt(request), expectedError); - }); - }); - - describe('updateCryptoKeyPrimaryVersion', () => { - it('invokes updateCryptoKeyPrimaryVersion without error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.UpdateCryptoKeyPrimaryVersionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.UpdateCryptoKeyPrimaryVersionRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.kms.v1.CryptoKey() - ); - client.innerApiCalls.updateCryptoKeyPrimaryVersion = stubSimpleCall(expectedResponse); - const [response] = await client.updateCryptoKeyPrimaryVersion(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateCryptoKeyPrimaryVersion as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateCryptoKeyPrimaryVersion as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateCryptoKeyPrimaryVersion without error using callback', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.UpdateCryptoKeyPrimaryVersionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.UpdateCryptoKeyPrimaryVersionRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.kms.v1.CryptoKey() - ); - client.innerApiCalls.updateCryptoKeyPrimaryVersion = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateCryptoKeyPrimaryVersion( - request, - (err?: Error|null, result?: protos.google.cloud.kms.v1.ICryptoKey|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateCryptoKeyPrimaryVersion as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateCryptoKeyPrimaryVersion as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateCryptoKeyPrimaryVersion with error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.UpdateCryptoKeyPrimaryVersionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.UpdateCryptoKeyPrimaryVersionRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateCryptoKeyPrimaryVersion = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateCryptoKeyPrimaryVersion(request), expectedError); - const actualRequest = (client.innerApiCalls.updateCryptoKeyPrimaryVersion as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateCryptoKeyPrimaryVersion as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateCryptoKeyPrimaryVersion with closed client', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.UpdateCryptoKeyPrimaryVersionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.UpdateCryptoKeyPrimaryVersionRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateCryptoKeyPrimaryVersion(request), expectedError); - }); - }); - - describe('destroyCryptoKeyVersion', () => { - it('invokes destroyCryptoKeyVersion without error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.DestroyCryptoKeyVersionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.DestroyCryptoKeyVersionRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.kms.v1.CryptoKeyVersion() - ); - client.innerApiCalls.destroyCryptoKeyVersion = stubSimpleCall(expectedResponse); - const [response] = await client.destroyCryptoKeyVersion(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.destroyCryptoKeyVersion as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.destroyCryptoKeyVersion as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes destroyCryptoKeyVersion without error using callback', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.DestroyCryptoKeyVersionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.DestroyCryptoKeyVersionRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.kms.v1.CryptoKeyVersion() - ); - client.innerApiCalls.destroyCryptoKeyVersion = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.destroyCryptoKeyVersion( - request, - (err?: Error|null, result?: protos.google.cloud.kms.v1.ICryptoKeyVersion|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.destroyCryptoKeyVersion as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.destroyCryptoKeyVersion as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes destroyCryptoKeyVersion with error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.DestroyCryptoKeyVersionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.DestroyCryptoKeyVersionRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.destroyCryptoKeyVersion = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.destroyCryptoKeyVersion(request), expectedError); - const actualRequest = (client.innerApiCalls.destroyCryptoKeyVersion as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.destroyCryptoKeyVersion as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes destroyCryptoKeyVersion with closed client', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.DestroyCryptoKeyVersionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.DestroyCryptoKeyVersionRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.destroyCryptoKeyVersion(request), expectedError); - }); - }); - - describe('restoreCryptoKeyVersion', () => { - it('invokes restoreCryptoKeyVersion without error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.RestoreCryptoKeyVersionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.RestoreCryptoKeyVersionRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.kms.v1.CryptoKeyVersion() - ); - client.innerApiCalls.restoreCryptoKeyVersion = stubSimpleCall(expectedResponse); - const [response] = await client.restoreCryptoKeyVersion(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.restoreCryptoKeyVersion as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.restoreCryptoKeyVersion as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes restoreCryptoKeyVersion without error using callback', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.RestoreCryptoKeyVersionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.RestoreCryptoKeyVersionRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.kms.v1.CryptoKeyVersion() - ); - client.innerApiCalls.restoreCryptoKeyVersion = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.restoreCryptoKeyVersion( - request, - (err?: Error|null, result?: protos.google.cloud.kms.v1.ICryptoKeyVersion|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.restoreCryptoKeyVersion as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.restoreCryptoKeyVersion as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes restoreCryptoKeyVersion with error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.RestoreCryptoKeyVersionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.RestoreCryptoKeyVersionRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.restoreCryptoKeyVersion = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.restoreCryptoKeyVersion(request), expectedError); - const actualRequest = (client.innerApiCalls.restoreCryptoKeyVersion as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.restoreCryptoKeyVersion as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes restoreCryptoKeyVersion with closed client', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.RestoreCryptoKeyVersionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.RestoreCryptoKeyVersionRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.restoreCryptoKeyVersion(request), expectedError); - }); - }); - - describe('listKeyRings', () => { - it('invokes listKeyRings without error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.ListKeyRingsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.ListKeyRingsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.kms.v1.KeyRing()), - generateSampleMessage(new protos.google.cloud.kms.v1.KeyRing()), - generateSampleMessage(new protos.google.cloud.kms.v1.KeyRing()), - ]; - client.innerApiCalls.listKeyRings = stubSimpleCall(expectedResponse); - const [response] = await client.listKeyRings(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listKeyRings as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listKeyRings as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listKeyRings without error using callback', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.ListKeyRingsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.ListKeyRingsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.kms.v1.KeyRing()), - generateSampleMessage(new protos.google.cloud.kms.v1.KeyRing()), - generateSampleMessage(new protos.google.cloud.kms.v1.KeyRing()), - ]; - client.innerApiCalls.listKeyRings = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listKeyRings( - request, - (err?: Error|null, result?: protos.google.cloud.kms.v1.IKeyRing[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listKeyRings as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listKeyRings as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listKeyRings with error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.ListKeyRingsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.ListKeyRingsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listKeyRings = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listKeyRings(request), expectedError); - const actualRequest = (client.innerApiCalls.listKeyRings as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listKeyRings as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listKeyRingsStream without error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.ListKeyRingsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.ListKeyRingsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.kms.v1.KeyRing()), - generateSampleMessage(new protos.google.cloud.kms.v1.KeyRing()), - generateSampleMessage(new protos.google.cloud.kms.v1.KeyRing()), - ]; - client.descriptors.page.listKeyRings.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listKeyRingsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.cloud.kms.v1.KeyRing[] = []; - stream.on('data', (response: protos.google.cloud.kms.v1.KeyRing) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.listKeyRings.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listKeyRings, request)); - assert( - (client.descriptors.page.listKeyRings.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); - - it('invokes listKeyRingsStream with error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.ListKeyRingsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.ListKeyRingsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listKeyRings.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listKeyRingsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.cloud.kms.v1.KeyRing[] = []; - stream.on('data', (response: protos.google.cloud.kms.v1.KeyRing) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listKeyRings.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listKeyRings, request)); - assert( - (client.descriptors.page.listKeyRings.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); - - it('uses async iteration with listKeyRings without error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.ListKeyRingsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.ListKeyRingsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.kms.v1.KeyRing()), - generateSampleMessage(new protos.google.cloud.kms.v1.KeyRing()), - generateSampleMessage(new protos.google.cloud.kms.v1.KeyRing()), - ]; - client.descriptors.page.listKeyRings.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.cloud.kms.v1.IKeyRing[] = []; - const iterable = client.listKeyRingsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } + }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + }); + + describe('getKeyRing', () => { + it('invokes getKeyRing without error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.GetKeyRingRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.GetKeyRingRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.kms.v1.KeyRing(), + ); + client.innerApiCalls.getKeyRing = stubSimpleCall(expectedResponse); + const [response] = await client.getKeyRing(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getKeyRing as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getKeyRing as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getKeyRing without error using callback', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.GetKeyRingRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.GetKeyRingRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.kms.v1.KeyRing(), + ); + client.innerApiCalls.getKeyRing = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getKeyRing( + request, + ( + err?: Error | null, + result?: protos.google.cloud.kms.v1.IKeyRing | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listKeyRings.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listKeyRings.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); - - it('uses async iteration with listKeyRings with error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.ListKeyRingsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.ListKeyRingsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listKeyRings.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listKeyRingsAsync(request); - await assert.rejects(async () => { - const responses: protos.google.cloud.kms.v1.IKeyRing[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listKeyRings.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listKeyRings.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); - }); - - describe('listCryptoKeys', () => { - it('invokes listCryptoKeys without error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.ListCryptoKeysRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.ListCryptoKeysRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.kms.v1.CryptoKey()), - generateSampleMessage(new protos.google.cloud.kms.v1.CryptoKey()), - generateSampleMessage(new protos.google.cloud.kms.v1.CryptoKey()), - ]; - client.innerApiCalls.listCryptoKeys = stubSimpleCall(expectedResponse); - const [response] = await client.listCryptoKeys(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listCryptoKeys as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listCryptoKeys as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listCryptoKeys without error using callback', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.ListCryptoKeysRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.ListCryptoKeysRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.kms.v1.CryptoKey()), - generateSampleMessage(new protos.google.cloud.kms.v1.CryptoKey()), - generateSampleMessage(new protos.google.cloud.kms.v1.CryptoKey()), - ]; - client.innerApiCalls.listCryptoKeys = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listCryptoKeys( - request, - (err?: Error|null, result?: protos.google.cloud.kms.v1.ICryptoKey[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listCryptoKeys as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listCryptoKeys as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listCryptoKeys with error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.ListCryptoKeysRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.ListCryptoKeysRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listCryptoKeys = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listCryptoKeys(request), expectedError); - const actualRequest = (client.innerApiCalls.listCryptoKeys as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listCryptoKeys as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listCryptoKeysStream without error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.ListCryptoKeysRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.ListCryptoKeysRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.kms.v1.CryptoKey()), - generateSampleMessage(new protos.google.cloud.kms.v1.CryptoKey()), - generateSampleMessage(new protos.google.cloud.kms.v1.CryptoKey()), - ]; - client.descriptors.page.listCryptoKeys.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listCryptoKeysStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.cloud.kms.v1.CryptoKey[] = []; - stream.on('data', (response: protos.google.cloud.kms.v1.CryptoKey) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.listCryptoKeys.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listCryptoKeys, request)); - assert( - (client.descriptors.page.listCryptoKeys.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); - - it('invokes listCryptoKeysStream with error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.ListCryptoKeysRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.ListCryptoKeysRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listCryptoKeys.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listCryptoKeysStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.cloud.kms.v1.CryptoKey[] = []; - stream.on('data', (response: protos.google.cloud.kms.v1.CryptoKey) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listCryptoKeys.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listCryptoKeys, request)); - assert( - (client.descriptors.page.listCryptoKeys.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); - - it('uses async iteration with listCryptoKeys without error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.ListCryptoKeysRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.ListCryptoKeysRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.kms.v1.CryptoKey()), - generateSampleMessage(new protos.google.cloud.kms.v1.CryptoKey()), - generateSampleMessage(new protos.google.cloud.kms.v1.CryptoKey()), - ]; - client.descriptors.page.listCryptoKeys.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.cloud.kms.v1.ICryptoKey[] = []; - const iterable = client.listCryptoKeysAsync(request); - for await (const resource of iterable) { - responses.push(resource!); + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getKeyRing as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getKeyRing as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getKeyRing with error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.GetKeyRingRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.GetKeyRingRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getKeyRing = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getKeyRing(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getKeyRing as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getKeyRing as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getKeyRing with closed client', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.GetKeyRingRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.GetKeyRingRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getKeyRing(request), expectedError); + }); + }); + + describe('getCryptoKey', () => { + it('invokes getCryptoKey without error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.GetCryptoKeyRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.GetCryptoKeyRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.kms.v1.CryptoKey(), + ); + client.innerApiCalls.getCryptoKey = stubSimpleCall(expectedResponse); + const [response] = await client.getCryptoKey(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getCryptoKey as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getCryptoKey as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getCryptoKey without error using callback', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.GetCryptoKeyRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.GetCryptoKeyRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.kms.v1.CryptoKey(), + ); + client.innerApiCalls.getCryptoKey = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getCryptoKey( + request, + ( + err?: Error | null, + result?: protos.google.cloud.kms.v1.ICryptoKey | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listCryptoKeys.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listCryptoKeys.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); - - it('uses async iteration with listCryptoKeys with error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.ListCryptoKeysRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.ListCryptoKeysRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listCryptoKeys.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listCryptoKeysAsync(request); - await assert.rejects(async () => { - const responses: protos.google.cloud.kms.v1.ICryptoKey[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listCryptoKeys.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listCryptoKeys.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); - }); - - describe('listCryptoKeyVersions', () => { - it('invokes listCryptoKeyVersions without error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.ListCryptoKeyVersionsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.ListCryptoKeyVersionsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.kms.v1.CryptoKeyVersion()), - generateSampleMessage(new protos.google.cloud.kms.v1.CryptoKeyVersion()), - generateSampleMessage(new protos.google.cloud.kms.v1.CryptoKeyVersion()), - ]; - client.innerApiCalls.listCryptoKeyVersions = stubSimpleCall(expectedResponse); - const [response] = await client.listCryptoKeyVersions(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listCryptoKeyVersions as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listCryptoKeyVersions as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listCryptoKeyVersions without error using callback', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.ListCryptoKeyVersionsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.ListCryptoKeyVersionsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.kms.v1.CryptoKeyVersion()), - generateSampleMessage(new protos.google.cloud.kms.v1.CryptoKeyVersion()), - generateSampleMessage(new protos.google.cloud.kms.v1.CryptoKeyVersion()), - ]; - client.innerApiCalls.listCryptoKeyVersions = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listCryptoKeyVersions( - request, - (err?: Error|null, result?: protos.google.cloud.kms.v1.ICryptoKeyVersion[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listCryptoKeyVersions as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listCryptoKeyVersions as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listCryptoKeyVersions with error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.ListCryptoKeyVersionsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.ListCryptoKeyVersionsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listCryptoKeyVersions = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listCryptoKeyVersions(request), expectedError); - const actualRequest = (client.innerApiCalls.listCryptoKeyVersions as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listCryptoKeyVersions as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listCryptoKeyVersionsStream without error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.ListCryptoKeyVersionsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.ListCryptoKeyVersionsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.kms.v1.CryptoKeyVersion()), - generateSampleMessage(new protos.google.cloud.kms.v1.CryptoKeyVersion()), - generateSampleMessage(new protos.google.cloud.kms.v1.CryptoKeyVersion()), - ]; - client.descriptors.page.listCryptoKeyVersions.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listCryptoKeyVersionsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.cloud.kms.v1.CryptoKeyVersion[] = []; - stream.on('data', (response: protos.google.cloud.kms.v1.CryptoKeyVersion) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.listCryptoKeyVersions.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listCryptoKeyVersions, request)); - assert( - (client.descriptors.page.listCryptoKeyVersions.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); - - it('invokes listCryptoKeyVersionsStream with error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.ListCryptoKeyVersionsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.ListCryptoKeyVersionsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listCryptoKeyVersions.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listCryptoKeyVersionsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.cloud.kms.v1.CryptoKeyVersion[] = []; - stream.on('data', (response: protos.google.cloud.kms.v1.CryptoKeyVersion) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listCryptoKeyVersions.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listCryptoKeyVersions, request)); - assert( - (client.descriptors.page.listCryptoKeyVersions.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); - - it('uses async iteration with listCryptoKeyVersions without error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.ListCryptoKeyVersionsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.ListCryptoKeyVersionsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.kms.v1.CryptoKeyVersion()), - generateSampleMessage(new protos.google.cloud.kms.v1.CryptoKeyVersion()), - generateSampleMessage(new protos.google.cloud.kms.v1.CryptoKeyVersion()), - ]; - client.descriptors.page.listCryptoKeyVersions.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.cloud.kms.v1.ICryptoKeyVersion[] = []; - const iterable = client.listCryptoKeyVersionsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getCryptoKey as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getCryptoKey as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getCryptoKey with error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.GetCryptoKeyRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.GetCryptoKeyRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getCryptoKey = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getCryptoKey(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getCryptoKey as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getCryptoKey as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getCryptoKey with closed client', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.GetCryptoKeyRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.GetCryptoKeyRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getCryptoKey(request), expectedError); + }); + }); + + describe('getCryptoKeyVersion', () => { + it('invokes getCryptoKeyVersion without error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.GetCryptoKeyVersionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.GetCryptoKeyVersionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.kms.v1.CryptoKeyVersion(), + ); + client.innerApiCalls.getCryptoKeyVersion = + stubSimpleCall(expectedResponse); + const [response] = await client.getCryptoKeyVersion(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getCryptoKeyVersion as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getCryptoKeyVersion as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getCryptoKeyVersion without error using callback', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.GetCryptoKeyVersionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.GetCryptoKeyVersionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.kms.v1.CryptoKeyVersion(), + ); + client.innerApiCalls.getCryptoKeyVersion = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getCryptoKeyVersion( + request, + ( + err?: Error | null, + result?: protos.google.cloud.kms.v1.ICryptoKeyVersion | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listCryptoKeyVersions.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listCryptoKeyVersions.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); - - it('uses async iteration with listCryptoKeyVersions with error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.ListCryptoKeyVersionsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.ListCryptoKeyVersionsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listCryptoKeyVersions.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listCryptoKeyVersionsAsync(request); - await assert.rejects(async () => { - const responses: protos.google.cloud.kms.v1.ICryptoKeyVersion[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listCryptoKeyVersions.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listCryptoKeyVersions.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); - }); - - describe('listImportJobs', () => { - it('invokes listImportJobs without error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.ListImportJobsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.ListImportJobsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.kms.v1.ImportJob()), - generateSampleMessage(new protos.google.cloud.kms.v1.ImportJob()), - generateSampleMessage(new protos.google.cloud.kms.v1.ImportJob()), - ]; - client.innerApiCalls.listImportJobs = stubSimpleCall(expectedResponse); - const [response] = await client.listImportJobs(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listImportJobs as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listImportJobs as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listImportJobs without error using callback', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.ListImportJobsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.ListImportJobsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.kms.v1.ImportJob()), - generateSampleMessage(new protos.google.cloud.kms.v1.ImportJob()), - generateSampleMessage(new protos.google.cloud.kms.v1.ImportJob()), - ]; - client.innerApiCalls.listImportJobs = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listImportJobs( - request, - (err?: Error|null, result?: protos.google.cloud.kms.v1.IImportJob[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listImportJobs as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listImportJobs as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listImportJobs with error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.ListImportJobsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.ListImportJobsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listImportJobs = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listImportJobs(request), expectedError); - const actualRequest = (client.innerApiCalls.listImportJobs as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listImportJobs as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listImportJobsStream without error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.ListImportJobsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.ListImportJobsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.kms.v1.ImportJob()), - generateSampleMessage(new protos.google.cloud.kms.v1.ImportJob()), - generateSampleMessage(new protos.google.cloud.kms.v1.ImportJob()), - ]; - client.descriptors.page.listImportJobs.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listImportJobsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.cloud.kms.v1.ImportJob[] = []; - stream.on('data', (response: protos.google.cloud.kms.v1.ImportJob) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.listImportJobs.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listImportJobs, request)); - assert( - (client.descriptors.page.listImportJobs.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); - - it('invokes listImportJobsStream with error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.ListImportJobsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.ListImportJobsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listImportJobs.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listImportJobsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.cloud.kms.v1.ImportJob[] = []; - stream.on('data', (response: protos.google.cloud.kms.v1.ImportJob) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listImportJobs.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listImportJobs, request)); - assert( - (client.descriptors.page.listImportJobs.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); - - it('uses async iteration with listImportJobs without error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.ListImportJobsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.ListImportJobsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.kms.v1.ImportJob()), - generateSampleMessage(new protos.google.cloud.kms.v1.ImportJob()), - generateSampleMessage(new protos.google.cloud.kms.v1.ImportJob()), - ]; - client.descriptors.page.listImportJobs.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.cloud.kms.v1.IImportJob[] = []; - const iterable = client.listImportJobsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getCryptoKeyVersion as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getCryptoKeyVersion as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getCryptoKeyVersion with error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.GetCryptoKeyVersionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.GetCryptoKeyVersionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getCryptoKeyVersion = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getCryptoKeyVersion(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getCryptoKeyVersion as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getCryptoKeyVersion as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getCryptoKeyVersion with closed client', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.GetCryptoKeyVersionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.GetCryptoKeyVersionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getCryptoKeyVersion(request), expectedError); + }); + }); + + describe('getPublicKey', () => { + it('invokes getPublicKey without error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.GetPublicKeyRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.GetPublicKeyRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.kms.v1.PublicKey(), + ); + client.innerApiCalls.getPublicKey = stubSimpleCall(expectedResponse); + const [response] = await client.getPublicKey(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getPublicKey as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getPublicKey as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getPublicKey without error using callback', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.GetPublicKeyRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.GetPublicKeyRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.kms.v1.PublicKey(), + ); + client.innerApiCalls.getPublicKey = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getPublicKey( + request, + ( + err?: Error | null, + result?: protos.google.cloud.kms.v1.IPublicKey | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listImportJobs.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listImportJobs.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); - - it('uses async iteration with listImportJobs with error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.kms.v1.ListImportJobsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.kms.v1.ListImportJobsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listImportJobs.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listImportJobsAsync(request); - await assert.rejects(async () => { - const responses: protos.google.cloud.kms.v1.IImportJob[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listImportJobs.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listImportJobs.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); - }); - describe('getIamPolicy', () => { - it('invokes getIamPolicy without error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new IamProtos.google.iam.v1.GetIamPolicyRequest() - ); - request.resource = ''; - const expectedHeaderRequestParams = 'resource='; - const expectedOptions = { - otherArgs: { - headers: { - 'x-goog-request-params': expectedHeaderRequestParams, - }, - }, - }; - const expectedResponse = generateSampleMessage( - new IamProtos.google.iam.v1.Policy() - ); - client.iamClient.getIamPolicy = stubSimpleCall(expectedResponse); - const response = await client.getIamPolicy(request, expectedOptions); - assert.deepStrictEqual(response, [expectedResponse]); - assert((client.iamClient.getIamPolicy as SinonStub) - .getCall(0).calledWith(request, expectedOptions, undefined)); - }); - it('invokes getIamPolicy without error using callback', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new IamProtos.google.iam.v1.GetIamPolicyRequest() - ); - request.resource = ''; - const expectedHeaderRequestParams = 'resource='; - const expectedOptions = { - otherArgs: { - headers: { - 'x-goog-request-params': expectedHeaderRequestParams, - }, - }, - }; - const expectedResponse = generateSampleMessage( - new IamProtos.google.iam.v1.Policy() - ); - client.iamClient.getIamPolicy = sinon.stub().callsArgWith(2, null, expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getIamPolicy( - request, - expectedOptions, - (err?: Error|null, result?: IamProtos.google.iam.v1.Policy|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }).catch(err => {throw err}); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - assert((client.iamClient.getIamPolicy as SinonStub) - .getCall(0)); - }); - it('invokes getIamPolicy with error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new IamProtos.google.iam.v1.GetIamPolicyRequest() - ); - request.resource = ''; - const expectedHeaderRequestParams = 'resource='; - const expectedOptions = { - otherArgs: { - headers: { - 'x-goog-request-params': expectedHeaderRequestParams, - }, - }, - }; - const expectedError = new Error('expected'); - client.iamClient.getIamPolicy = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getIamPolicy(request, expectedOptions), expectedError); - assert((client.iamClient.getIamPolicy as SinonStub) - .getCall(0).calledWith(request, expectedOptions, undefined)); - }); - }); - describe('setIamPolicy', () => { - it('invokes setIamPolicy without error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new IamProtos.google.iam.v1.SetIamPolicyRequest() - ); - request.resource = ''; - const expectedHeaderRequestParams = 'resource='; - const expectedOptions = { - otherArgs: { - headers: { - 'x-goog-request-params': expectedHeaderRequestParams, - }, - }, - }; - const expectedResponse = generateSampleMessage( - new IamProtos.google.iam.v1.Policy() - ); - client.iamClient.setIamPolicy = stubSimpleCall(expectedResponse); - const response = await client.setIamPolicy(request, expectedOptions); - assert.deepStrictEqual(response, [expectedResponse]); - assert((client.iamClient.setIamPolicy as SinonStub) - .getCall(0).calledWith(request, expectedOptions, undefined)); - }); - it('invokes setIamPolicy without error using callback', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new IamProtos.google.iam.v1.SetIamPolicyRequest() - ); - request.resource = ''; - const expectedHeaderRequestParams = 'resource='; - const expectedOptions = { - otherArgs: { - headers: { - 'x-goog-request-params': expectedHeaderRequestParams, - }, - }, - }; - const expectedResponse = generateSampleMessage( - new IamProtos.google.iam.v1.Policy() - ); - client.iamClient.setIamPolicy = sinon.stub().callsArgWith(2, null, expectedResponse); - const promise = new Promise((resolve, reject) => { - client.setIamPolicy( - request, - expectedOptions, - (err?: Error|null, result?: IamProtos.google.iam.v1.Policy|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }).catch(err => {throw err}); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - assert((client.iamClient.setIamPolicy as SinonStub) - .getCall(0)); - }); - it('invokes setIamPolicy with error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new IamProtos.google.iam.v1.SetIamPolicyRequest() - ); - request.resource = ''; - const expectedHeaderRequestParams = 'resource='; - const expectedOptions = { - otherArgs: { - headers: { - 'x-goog-request-params': expectedHeaderRequestParams, - }, - }, - }; - const expectedError = new Error('expected'); - client.iamClient.setIamPolicy = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.setIamPolicy(request, expectedOptions), expectedError); - assert((client.iamClient.setIamPolicy as SinonStub) - .getCall(0).calledWith(request, expectedOptions, undefined)); - }); - }); - describe('testIamPermissions', () => { - it('invokes testIamPermissions without error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new IamProtos.google.iam.v1.TestIamPermissionsRequest() - ); - request.resource = ''; - const expectedHeaderRequestParams = 'resource='; - const expectedOptions = { - otherArgs: { - headers: { - 'x-goog-request-params': expectedHeaderRequestParams, - }, - }, - }; - const expectedResponse = generateSampleMessage( - new IamProtos.google.iam.v1.TestIamPermissionsResponse() - ); - client.iamClient.testIamPermissions = stubSimpleCall(expectedResponse); - const response = await client.testIamPermissions(request, expectedOptions); - assert.deepStrictEqual(response, [expectedResponse]); - assert((client.iamClient.testIamPermissions as SinonStub) - .getCall(0).calledWith(request, expectedOptions, undefined)); - }); - it('invokes testIamPermissions without error using callback', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new IamProtos.google.iam.v1.TestIamPermissionsRequest() - ); - request.resource = ''; - const expectedHeaderRequestParams = 'resource='; - const expectedOptions = { - otherArgs: { - headers: { - 'x-goog-request-params': expectedHeaderRequestParams, - }, - }, - }; - const expectedResponse = generateSampleMessage( - new IamProtos.google.iam.v1.TestIamPermissionsResponse() - ); - client.iamClient.testIamPermissions = sinon.stub().callsArgWith(2, null, expectedResponse); - const promise = new Promise((resolve, reject) => { - client.testIamPermissions( - request, - expectedOptions, - (err?: Error|null, result?: IamProtos.google.iam.v1.TestIamPermissionsResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }).catch(err => {throw err}); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - assert((client.iamClient.testIamPermissions as SinonStub) - .getCall(0)); - }); - it('invokes testIamPermissions with error', async () => { - const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new IamProtos.google.iam.v1.TestIamPermissionsRequest() - ); - request.resource = ''; - const expectedHeaderRequestParams = 'resource='; - const expectedOptions = { - otherArgs: { - headers: { - 'x-goog-request-params': expectedHeaderRequestParams, - }, - }, - }; - const expectedError = new Error('expected'); - client.iamClient.testIamPermissions = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.testIamPermissions(request, expectedOptions), expectedError); - assert((client.iamClient.testIamPermissions as SinonStub) - .getCall(0).calledWith(request, expectedOptions, undefined)); + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getPublicKey as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getPublicKey as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getPublicKey with error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.GetPublicKeyRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.GetPublicKeyRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getPublicKey = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getPublicKey(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getPublicKey as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getPublicKey as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getPublicKey with closed client', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.GetPublicKeyRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.GetPublicKeyRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getPublicKey(request), expectedError); + }); + }); + + describe('getImportJob', () => { + it('invokes getImportJob without error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.GetImportJobRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.GetImportJobRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.kms.v1.ImportJob(), + ); + client.innerApiCalls.getImportJob = stubSimpleCall(expectedResponse); + const [response] = await client.getImportJob(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getImportJob as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getImportJob as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getImportJob without error using callback', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.GetImportJobRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.GetImportJobRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.kms.v1.ImportJob(), + ); + client.innerApiCalls.getImportJob = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getImportJob( + request, + ( + err?: Error | null, + result?: protos.google.cloud.kms.v1.IImportJob | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getImportJob as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getImportJob as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getImportJob with error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.GetImportJobRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.GetImportJobRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getImportJob = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getImportJob(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getImportJob as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getImportJob as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getImportJob with closed client', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.GetImportJobRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.GetImportJobRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getImportJob(request), expectedError); + }); + }); + + describe('createKeyRing', () => { + it('invokes createKeyRing without error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.CreateKeyRingRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.CreateKeyRingRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.kms.v1.KeyRing(), + ); + client.innerApiCalls.createKeyRing = stubSimpleCall(expectedResponse); + const [response] = await client.createKeyRing(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createKeyRing as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createKeyRing as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createKeyRing without error using callback', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.CreateKeyRingRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.CreateKeyRingRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.kms.v1.KeyRing(), + ); + client.innerApiCalls.createKeyRing = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createKeyRing( + request, + ( + err?: Error | null, + result?: protos.google.cloud.kms.v1.IKeyRing | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createKeyRing as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createKeyRing as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createKeyRing with error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.CreateKeyRingRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.CreateKeyRingRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createKeyRing = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.createKeyRing(request), expectedError); + const actualRequest = ( + client.innerApiCalls.createKeyRing as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createKeyRing as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createKeyRing with closed client', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.CreateKeyRingRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.CreateKeyRingRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.createKeyRing(request), expectedError); + }); + }); + + describe('createCryptoKey', () => { + it('invokes createCryptoKey without error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.CreateCryptoKeyRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.CreateCryptoKeyRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.kms.v1.CryptoKey(), + ); + client.innerApiCalls.createCryptoKey = stubSimpleCall(expectedResponse); + const [response] = await client.createCryptoKey(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createCryptoKey as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createCryptoKey as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createCryptoKey without error using callback', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.CreateCryptoKeyRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.CreateCryptoKeyRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.kms.v1.CryptoKey(), + ); + client.innerApiCalls.createCryptoKey = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createCryptoKey( + request, + ( + err?: Error | null, + result?: protos.google.cloud.kms.v1.ICryptoKey | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createCryptoKey as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createCryptoKey as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createCryptoKey with error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.CreateCryptoKeyRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.CreateCryptoKeyRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createCryptoKey = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.createCryptoKey(request), expectedError); + const actualRequest = ( + client.innerApiCalls.createCryptoKey as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createCryptoKey as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createCryptoKey with closed client', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.CreateCryptoKeyRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.CreateCryptoKeyRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.createCryptoKey(request), expectedError); + }); + }); + + describe('createCryptoKeyVersion', () => { + it('invokes createCryptoKeyVersion without error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.CreateCryptoKeyVersionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.CreateCryptoKeyVersionRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.kms.v1.CryptoKeyVersion(), + ); + client.innerApiCalls.createCryptoKeyVersion = + stubSimpleCall(expectedResponse); + const [response] = await client.createCryptoKeyVersion(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createCryptoKeyVersion as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createCryptoKeyVersion as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createCryptoKeyVersion without error using callback', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.CreateCryptoKeyVersionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.CreateCryptoKeyVersionRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.kms.v1.CryptoKeyVersion(), + ); + client.innerApiCalls.createCryptoKeyVersion = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createCryptoKeyVersion( + request, + ( + err?: Error | null, + result?: protos.google.cloud.kms.v1.ICryptoKeyVersion | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createCryptoKeyVersion as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createCryptoKeyVersion as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createCryptoKeyVersion with error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.CreateCryptoKeyVersionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.CreateCryptoKeyVersionRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createCryptoKeyVersion = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.createCryptoKeyVersion(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.createCryptoKeyVersion as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createCryptoKeyVersion as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createCryptoKeyVersion with closed client', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.CreateCryptoKeyVersionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.CreateCryptoKeyVersionRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.createCryptoKeyVersion(request), + expectedError, + ); + }); + }); + + describe('importCryptoKeyVersion', () => { + it('invokes importCryptoKeyVersion without error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.ImportCryptoKeyVersionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.ImportCryptoKeyVersionRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.kms.v1.CryptoKeyVersion(), + ); + client.innerApiCalls.importCryptoKeyVersion = + stubSimpleCall(expectedResponse); + const [response] = await client.importCryptoKeyVersion(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.importCryptoKeyVersion as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.importCryptoKeyVersion as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes importCryptoKeyVersion without error using callback', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.ImportCryptoKeyVersionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.ImportCryptoKeyVersionRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.kms.v1.CryptoKeyVersion(), + ); + client.innerApiCalls.importCryptoKeyVersion = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.importCryptoKeyVersion( + request, + ( + err?: Error | null, + result?: protos.google.cloud.kms.v1.ICryptoKeyVersion | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.importCryptoKeyVersion as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.importCryptoKeyVersion as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes importCryptoKeyVersion with error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.ImportCryptoKeyVersionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.ImportCryptoKeyVersionRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.importCryptoKeyVersion = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.importCryptoKeyVersion(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.importCryptoKeyVersion as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.importCryptoKeyVersion as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes importCryptoKeyVersion with closed client', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.ImportCryptoKeyVersionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.ImportCryptoKeyVersionRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.importCryptoKeyVersion(request), + expectedError, + ); + }); + }); + + describe('createImportJob', () => { + it('invokes createImportJob without error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.CreateImportJobRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.CreateImportJobRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.kms.v1.ImportJob(), + ); + client.innerApiCalls.createImportJob = stubSimpleCall(expectedResponse); + const [response] = await client.createImportJob(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createImportJob as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createImportJob as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createImportJob without error using callback', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.CreateImportJobRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.CreateImportJobRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.kms.v1.ImportJob(), + ); + client.innerApiCalls.createImportJob = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createImportJob( + request, + ( + err?: Error | null, + result?: protos.google.cloud.kms.v1.IImportJob | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createImportJob as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createImportJob as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createImportJob with error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.CreateImportJobRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.CreateImportJobRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createImportJob = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.createImportJob(request), expectedError); + const actualRequest = ( + client.innerApiCalls.createImportJob as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createImportJob as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createImportJob with closed client', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.CreateImportJobRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.CreateImportJobRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.createImportJob(request), expectedError); + }); + }); + + describe('updateCryptoKey', () => { + it('invokes updateCryptoKey without error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.UpdateCryptoKeyRequest(), + ); + request.cryptoKey ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.UpdateCryptoKeyRequest', + ['cryptoKey', 'name'], + ); + request.cryptoKey.name = defaultValue1; + const expectedHeaderRequestParams = `crypto_key.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.kms.v1.CryptoKey(), + ); + client.innerApiCalls.updateCryptoKey = stubSimpleCall(expectedResponse); + const [response] = await client.updateCryptoKey(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateCryptoKey as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateCryptoKey as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateCryptoKey without error using callback', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.UpdateCryptoKeyRequest(), + ); + request.cryptoKey ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.UpdateCryptoKeyRequest', + ['cryptoKey', 'name'], + ); + request.cryptoKey.name = defaultValue1; + const expectedHeaderRequestParams = `crypto_key.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.kms.v1.CryptoKey(), + ); + client.innerApiCalls.updateCryptoKey = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateCryptoKey( + request, + ( + err?: Error | null, + result?: protos.google.cloud.kms.v1.ICryptoKey | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateCryptoKey as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateCryptoKey as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateCryptoKey with error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.UpdateCryptoKeyRequest(), + ); + request.cryptoKey ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.UpdateCryptoKeyRequest', + ['cryptoKey', 'name'], + ); + request.cryptoKey.name = defaultValue1; + const expectedHeaderRequestParams = `crypto_key.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateCryptoKey = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.updateCryptoKey(request), expectedError); + const actualRequest = ( + client.innerApiCalls.updateCryptoKey as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateCryptoKey as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateCryptoKey with closed client', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.UpdateCryptoKeyRequest(), + ); + request.cryptoKey ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.UpdateCryptoKeyRequest', + ['cryptoKey', 'name'], + ); + request.cryptoKey.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.updateCryptoKey(request), expectedError); + }); + }); + + describe('updateCryptoKeyVersion', () => { + it('invokes updateCryptoKeyVersion without error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.UpdateCryptoKeyVersionRequest(), + ); + request.cryptoKeyVersion ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.UpdateCryptoKeyVersionRequest', + ['cryptoKeyVersion', 'name'], + ); + request.cryptoKeyVersion.name = defaultValue1; + const expectedHeaderRequestParams = `crypto_key_version.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.kms.v1.CryptoKeyVersion(), + ); + client.innerApiCalls.updateCryptoKeyVersion = + stubSimpleCall(expectedResponse); + const [response] = await client.updateCryptoKeyVersion(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateCryptoKeyVersion as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateCryptoKeyVersion as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateCryptoKeyVersion without error using callback', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.UpdateCryptoKeyVersionRequest(), + ); + request.cryptoKeyVersion ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.UpdateCryptoKeyVersionRequest', + ['cryptoKeyVersion', 'name'], + ); + request.cryptoKeyVersion.name = defaultValue1; + const expectedHeaderRequestParams = `crypto_key_version.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.kms.v1.CryptoKeyVersion(), + ); + client.innerApiCalls.updateCryptoKeyVersion = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateCryptoKeyVersion( + request, + ( + err?: Error | null, + result?: protos.google.cloud.kms.v1.ICryptoKeyVersion | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateCryptoKeyVersion as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateCryptoKeyVersion as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateCryptoKeyVersion with error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.UpdateCryptoKeyVersionRequest(), + ); + request.cryptoKeyVersion ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.UpdateCryptoKeyVersionRequest', + ['cryptoKeyVersion', 'name'], + ); + request.cryptoKeyVersion.name = defaultValue1; + const expectedHeaderRequestParams = `crypto_key_version.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateCryptoKeyVersion = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.updateCryptoKeyVersion(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.updateCryptoKeyVersion as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateCryptoKeyVersion as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateCryptoKeyVersion with closed client', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.UpdateCryptoKeyVersionRequest(), + ); + request.cryptoKeyVersion ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.UpdateCryptoKeyVersionRequest', + ['cryptoKeyVersion', 'name'], + ); + request.cryptoKeyVersion.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.updateCryptoKeyVersion(request), + expectedError, + ); + }); + }); + + describe('encrypt', () => { + it('invokes encrypt without error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.EncryptRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.EncryptRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.kms.v1.EncryptResponse(), + ); + client.innerApiCalls.encrypt = stubSimpleCall(expectedResponse); + const [response] = await client.encrypt(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.encrypt as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.encrypt as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes encrypt without error using callback', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.EncryptRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.EncryptRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.kms.v1.EncryptResponse(), + ); + client.innerApiCalls.encrypt = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.encrypt( + request, + ( + err?: Error | null, + result?: protos.google.cloud.kms.v1.IEncryptResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.encrypt as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.encrypt as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes encrypt with error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.EncryptRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.EncryptRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.encrypt = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.encrypt(request), expectedError); + const actualRequest = (client.innerApiCalls.encrypt as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.encrypt as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes encrypt with closed client', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.EncryptRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.EncryptRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.encrypt(request), expectedError); + }); + }); + + describe('decrypt', () => { + it('invokes decrypt without error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.DecryptRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.DecryptRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.kms.v1.DecryptResponse(), + ); + client.innerApiCalls.decrypt = stubSimpleCall(expectedResponse); + const [response] = await client.decrypt(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.decrypt as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.decrypt as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes decrypt without error using callback', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.DecryptRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.DecryptRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.kms.v1.DecryptResponse(), + ); + client.innerApiCalls.decrypt = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.decrypt( + request, + ( + err?: Error | null, + result?: protos.google.cloud.kms.v1.IDecryptResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.decrypt as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.decrypt as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes decrypt with error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.DecryptRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.DecryptRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.decrypt = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.decrypt(request), expectedError); + const actualRequest = (client.innerApiCalls.decrypt as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.decrypt as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes decrypt with closed client', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.DecryptRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.DecryptRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.decrypt(request), expectedError); + }); + }); + + describe('asymmetricSign', () => { + it('invokes asymmetricSign without error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.AsymmetricSignRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.AsymmetricSignRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.kms.v1.AsymmetricSignResponse(), + ); + client.innerApiCalls.asymmetricSign = stubSimpleCall(expectedResponse); + const [response] = await client.asymmetricSign(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.asymmetricSign as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.asymmetricSign as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes asymmetricSign without error using callback', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.AsymmetricSignRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.AsymmetricSignRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.kms.v1.AsymmetricSignResponse(), + ); + client.innerApiCalls.asymmetricSign = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.asymmetricSign( + request, + ( + err?: Error | null, + result?: protos.google.cloud.kms.v1.IAsymmetricSignResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.asymmetricSign as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.asymmetricSign as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes asymmetricSign with error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.AsymmetricSignRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.AsymmetricSignRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.asymmetricSign = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.asymmetricSign(request), expectedError); + const actualRequest = ( + client.innerApiCalls.asymmetricSign as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.asymmetricSign as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes asymmetricSign with closed client', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.AsymmetricSignRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.AsymmetricSignRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.asymmetricSign(request), expectedError); + }); + }); + + describe('asymmetricDecrypt', () => { + it('invokes asymmetricDecrypt without error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.AsymmetricDecryptRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.AsymmetricDecryptRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.kms.v1.AsymmetricDecryptResponse(), + ); + client.innerApiCalls.asymmetricDecrypt = stubSimpleCall(expectedResponse); + const [response] = await client.asymmetricDecrypt(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.asymmetricDecrypt as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.asymmetricDecrypt as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes asymmetricDecrypt without error using callback', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.AsymmetricDecryptRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.AsymmetricDecryptRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.kms.v1.AsymmetricDecryptResponse(), + ); + client.innerApiCalls.asymmetricDecrypt = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.asymmetricDecrypt( + request, + ( + err?: Error | null, + result?: protos.google.cloud.kms.v1.IAsymmetricDecryptResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.asymmetricDecrypt as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.asymmetricDecrypt as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes asymmetricDecrypt with error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.AsymmetricDecryptRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.AsymmetricDecryptRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.asymmetricDecrypt = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.asymmetricDecrypt(request), expectedError); + const actualRequest = ( + client.innerApiCalls.asymmetricDecrypt as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.asymmetricDecrypt as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes asymmetricDecrypt with closed client', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.AsymmetricDecryptRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.AsymmetricDecryptRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.asymmetricDecrypt(request), expectedError); + }); + }); + + describe('updateCryptoKeyPrimaryVersion', () => { + it('invokes updateCryptoKeyPrimaryVersion without error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.UpdateCryptoKeyPrimaryVersionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.UpdateCryptoKeyPrimaryVersionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.kms.v1.CryptoKey(), + ); + client.innerApiCalls.updateCryptoKeyPrimaryVersion = + stubSimpleCall(expectedResponse); + const [response] = await client.updateCryptoKeyPrimaryVersion(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateCryptoKeyPrimaryVersion as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateCryptoKeyPrimaryVersion as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateCryptoKeyPrimaryVersion without error using callback', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.UpdateCryptoKeyPrimaryVersionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.UpdateCryptoKeyPrimaryVersionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.kms.v1.CryptoKey(), + ); + client.innerApiCalls.updateCryptoKeyPrimaryVersion = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateCryptoKeyPrimaryVersion( + request, + ( + err?: Error | null, + result?: protos.google.cloud.kms.v1.ICryptoKey | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateCryptoKeyPrimaryVersion as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateCryptoKeyPrimaryVersion as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateCryptoKeyPrimaryVersion with error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.UpdateCryptoKeyPrimaryVersionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.UpdateCryptoKeyPrimaryVersionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateCryptoKeyPrimaryVersion = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.updateCryptoKeyPrimaryVersion(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.updateCryptoKeyPrimaryVersion as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateCryptoKeyPrimaryVersion as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateCryptoKeyPrimaryVersion with closed client', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.UpdateCryptoKeyPrimaryVersionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.UpdateCryptoKeyPrimaryVersionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.updateCryptoKeyPrimaryVersion(request), + expectedError, + ); + }); + }); + + describe('destroyCryptoKeyVersion', () => { + it('invokes destroyCryptoKeyVersion without error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.DestroyCryptoKeyVersionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.DestroyCryptoKeyVersionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.kms.v1.CryptoKeyVersion(), + ); + client.innerApiCalls.destroyCryptoKeyVersion = + stubSimpleCall(expectedResponse); + const [response] = await client.destroyCryptoKeyVersion(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.destroyCryptoKeyVersion as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.destroyCryptoKeyVersion as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes destroyCryptoKeyVersion without error using callback', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.DestroyCryptoKeyVersionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.DestroyCryptoKeyVersionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.kms.v1.CryptoKeyVersion(), + ); + client.innerApiCalls.destroyCryptoKeyVersion = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.destroyCryptoKeyVersion( + request, + ( + err?: Error | null, + result?: protos.google.cloud.kms.v1.ICryptoKeyVersion | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.destroyCryptoKeyVersion as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.destroyCryptoKeyVersion as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes destroyCryptoKeyVersion with error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.DestroyCryptoKeyVersionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.DestroyCryptoKeyVersionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.destroyCryptoKeyVersion = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.destroyCryptoKeyVersion(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.destroyCryptoKeyVersion as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.destroyCryptoKeyVersion as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes destroyCryptoKeyVersion with closed client', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.DestroyCryptoKeyVersionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.DestroyCryptoKeyVersionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.destroyCryptoKeyVersion(request), + expectedError, + ); + }); + }); + + describe('restoreCryptoKeyVersion', () => { + it('invokes restoreCryptoKeyVersion without error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.RestoreCryptoKeyVersionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.RestoreCryptoKeyVersionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.kms.v1.CryptoKeyVersion(), + ); + client.innerApiCalls.restoreCryptoKeyVersion = + stubSimpleCall(expectedResponse); + const [response] = await client.restoreCryptoKeyVersion(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.restoreCryptoKeyVersion as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.restoreCryptoKeyVersion as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes restoreCryptoKeyVersion without error using callback', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.RestoreCryptoKeyVersionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.RestoreCryptoKeyVersionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.kms.v1.CryptoKeyVersion(), + ); + client.innerApiCalls.restoreCryptoKeyVersion = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.restoreCryptoKeyVersion( + request, + ( + err?: Error | null, + result?: protos.google.cloud.kms.v1.ICryptoKeyVersion | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.restoreCryptoKeyVersion as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.restoreCryptoKeyVersion as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes restoreCryptoKeyVersion with error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.RestoreCryptoKeyVersionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.RestoreCryptoKeyVersionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.restoreCryptoKeyVersion = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.restoreCryptoKeyVersion(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.restoreCryptoKeyVersion as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.restoreCryptoKeyVersion as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes restoreCryptoKeyVersion with closed client', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.RestoreCryptoKeyVersionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.RestoreCryptoKeyVersionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.restoreCryptoKeyVersion(request), + expectedError, + ); + }); + }); + + describe('listKeyRings', () => { + it('invokes listKeyRings without error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.ListKeyRingsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.ListKeyRingsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.kms.v1.KeyRing()), + generateSampleMessage(new protos.google.cloud.kms.v1.KeyRing()), + generateSampleMessage(new protos.google.cloud.kms.v1.KeyRing()), + ]; + client.innerApiCalls.listKeyRings = stubSimpleCall(expectedResponse); + const [response] = await client.listKeyRings(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listKeyRings as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listKeyRings as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listKeyRings without error using callback', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.ListKeyRingsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.ListKeyRingsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.kms.v1.KeyRing()), + generateSampleMessage(new protos.google.cloud.kms.v1.KeyRing()), + generateSampleMessage(new protos.google.cloud.kms.v1.KeyRing()), + ]; + client.innerApiCalls.listKeyRings = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listKeyRings( + request, + ( + err?: Error | null, + result?: protos.google.cloud.kms.v1.IKeyRing[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listKeyRings as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listKeyRings as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listKeyRings with error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.ListKeyRingsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.ListKeyRingsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listKeyRings = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listKeyRings(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listKeyRings as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listKeyRings as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listKeyRingsStream without error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.ListKeyRingsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.ListKeyRingsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.kms.v1.KeyRing()), + generateSampleMessage(new protos.google.cloud.kms.v1.KeyRing()), + generateSampleMessage(new protos.google.cloud.kms.v1.KeyRing()), + ]; + client.descriptors.page.listKeyRings.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listKeyRingsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.cloud.kms.v1.KeyRing[] = []; + stream.on('data', (response: protos.google.cloud.kms.v1.KeyRing) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listKeyRings.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listKeyRings, request), + ); + assert( + (client.descriptors.page.listKeyRings.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + + it('invokes listKeyRingsStream with error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.ListKeyRingsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.ListKeyRingsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listKeyRings.createStream = stubPageStreamingCall( + undefined, + expectedError, + ); + const stream = client.listKeyRingsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.cloud.kms.v1.KeyRing[] = []; + stream.on('data', (response: protos.google.cloud.kms.v1.KeyRing) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listKeyRings.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listKeyRings, request), + ); + assert( + (client.descriptors.page.listKeyRings.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + + it('uses async iteration with listKeyRings without error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.ListKeyRingsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.ListKeyRingsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.kms.v1.KeyRing()), + generateSampleMessage(new protos.google.cloud.kms.v1.KeyRing()), + generateSampleMessage(new protos.google.cloud.kms.v1.KeyRing()), + ]; + client.descriptors.page.listKeyRings.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.cloud.kms.v1.IKeyRing[] = []; + const iterable = client.listKeyRingsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listKeyRings.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listKeyRings.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + + it('uses async iteration with listKeyRings with error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.ListKeyRingsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.ListKeyRingsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listKeyRings.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listKeyRingsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.cloud.kms.v1.IKeyRing[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listKeyRings.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listKeyRings.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + }); + + describe('listCryptoKeys', () => { + it('invokes listCryptoKeys without error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.ListCryptoKeysRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.ListCryptoKeysRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.kms.v1.CryptoKey()), + generateSampleMessage(new protos.google.cloud.kms.v1.CryptoKey()), + generateSampleMessage(new protos.google.cloud.kms.v1.CryptoKey()), + ]; + client.innerApiCalls.listCryptoKeys = stubSimpleCall(expectedResponse); + const [response] = await client.listCryptoKeys(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listCryptoKeys as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listCryptoKeys as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listCryptoKeys without error using callback', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.ListCryptoKeysRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.ListCryptoKeysRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.kms.v1.CryptoKey()), + generateSampleMessage(new protos.google.cloud.kms.v1.CryptoKey()), + generateSampleMessage(new protos.google.cloud.kms.v1.CryptoKey()), + ]; + client.innerApiCalls.listCryptoKeys = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listCryptoKeys( + request, + ( + err?: Error | null, + result?: protos.google.cloud.kms.v1.ICryptoKey[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listCryptoKeys as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listCryptoKeys as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listCryptoKeys with error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.ListCryptoKeysRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.ListCryptoKeysRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listCryptoKeys = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listCryptoKeys(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listCryptoKeys as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listCryptoKeys as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listCryptoKeysStream without error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.ListCryptoKeysRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.ListCryptoKeysRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.kms.v1.CryptoKey()), + generateSampleMessage(new protos.google.cloud.kms.v1.CryptoKey()), + generateSampleMessage(new protos.google.cloud.kms.v1.CryptoKey()), + ]; + client.descriptors.page.listCryptoKeys.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listCryptoKeysStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.cloud.kms.v1.CryptoKey[] = []; + stream.on('data', (response: protos.google.cloud.kms.v1.CryptoKey) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listCryptoKeys.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listCryptoKeys, request), + ); + assert( + (client.descriptors.page.listCryptoKeys.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + + it('invokes listCryptoKeysStream with error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.ListCryptoKeysRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.ListCryptoKeysRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listCryptoKeys.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listCryptoKeysStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.cloud.kms.v1.CryptoKey[] = []; + stream.on('data', (response: protos.google.cloud.kms.v1.CryptoKey) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listCryptoKeys.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listCryptoKeys, request), + ); + assert( + (client.descriptors.page.listCryptoKeys.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + + it('uses async iteration with listCryptoKeys without error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.ListCryptoKeysRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.ListCryptoKeysRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.kms.v1.CryptoKey()), + generateSampleMessage(new protos.google.cloud.kms.v1.CryptoKey()), + generateSampleMessage(new protos.google.cloud.kms.v1.CryptoKey()), + ]; + client.descriptors.page.listCryptoKeys.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.cloud.kms.v1.ICryptoKey[] = []; + const iterable = client.listCryptoKeysAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listCryptoKeys.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listCryptoKeys.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + + it('uses async iteration with listCryptoKeys with error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.ListCryptoKeysRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.ListCryptoKeysRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listCryptoKeys.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listCryptoKeysAsync(request); + await assert.rejects(async () => { + const responses: protos.google.cloud.kms.v1.ICryptoKey[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listCryptoKeys.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listCryptoKeys.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + }); + + describe('listCryptoKeyVersions', () => { + it('invokes listCryptoKeyVersions without error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.ListCryptoKeyVersionsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.ListCryptoKeyVersionsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.cloud.kms.v1.CryptoKeyVersion(), + ), + generateSampleMessage( + new protos.google.cloud.kms.v1.CryptoKeyVersion(), + ), + generateSampleMessage( + new protos.google.cloud.kms.v1.CryptoKeyVersion(), + ), + ]; + client.innerApiCalls.listCryptoKeyVersions = + stubSimpleCall(expectedResponse); + const [response] = await client.listCryptoKeyVersions(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listCryptoKeyVersions as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listCryptoKeyVersions as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listCryptoKeyVersions without error using callback', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.ListCryptoKeyVersionsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.ListCryptoKeyVersionsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.cloud.kms.v1.CryptoKeyVersion(), + ), + generateSampleMessage( + new protos.google.cloud.kms.v1.CryptoKeyVersion(), + ), + generateSampleMessage( + new protos.google.cloud.kms.v1.CryptoKeyVersion(), + ), + ]; + client.innerApiCalls.listCryptoKeyVersions = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listCryptoKeyVersions( + request, + ( + err?: Error | null, + result?: protos.google.cloud.kms.v1.ICryptoKeyVersion[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listCryptoKeyVersions as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listCryptoKeyVersions as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listCryptoKeyVersions with error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.ListCryptoKeyVersionsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.ListCryptoKeyVersionsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listCryptoKeyVersions = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.listCryptoKeyVersions(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.listCryptoKeyVersions as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listCryptoKeyVersions as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listCryptoKeyVersionsStream without error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.ListCryptoKeyVersionsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.ListCryptoKeyVersionsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.cloud.kms.v1.CryptoKeyVersion(), + ), + generateSampleMessage( + new protos.google.cloud.kms.v1.CryptoKeyVersion(), + ), + generateSampleMessage( + new protos.google.cloud.kms.v1.CryptoKeyVersion(), + ), + ]; + client.descriptors.page.listCryptoKeyVersions.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listCryptoKeyVersionsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.cloud.kms.v1.CryptoKeyVersion[] = []; + stream.on( + 'data', + (response: protos.google.cloud.kms.v1.CryptoKeyVersion) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + ( + client.descriptors.page.listCryptoKeyVersions + .createStream as SinonStub + ) + .getCall(0) + .calledWith(client.innerApiCalls.listCryptoKeyVersions, request), + ); + assert( + ( + client.descriptors.page.listCryptoKeyVersions + .createStream as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); + + it('invokes listCryptoKeyVersionsStream with error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.ListCryptoKeyVersionsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.ListCryptoKeyVersionsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listCryptoKeyVersions.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listCryptoKeyVersionsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.cloud.kms.v1.CryptoKeyVersion[] = []; + stream.on( + 'data', + (response: protos.google.cloud.kms.v1.CryptoKeyVersion) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + ( + client.descriptors.page.listCryptoKeyVersions + .createStream as SinonStub + ) + .getCall(0) + .calledWith(client.innerApiCalls.listCryptoKeyVersions, request), + ); + assert( + ( + client.descriptors.page.listCryptoKeyVersions + .createStream as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); + + it('uses async iteration with listCryptoKeyVersions without error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.ListCryptoKeyVersionsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.ListCryptoKeyVersionsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.cloud.kms.v1.CryptoKeyVersion(), + ), + generateSampleMessage( + new protos.google.cloud.kms.v1.CryptoKeyVersion(), + ), + generateSampleMessage( + new protos.google.cloud.kms.v1.CryptoKeyVersion(), + ), + ]; + client.descriptors.page.listCryptoKeyVersions.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.cloud.kms.v1.ICryptoKeyVersion[] = []; + const iterable = client.listCryptoKeyVersionsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listCryptoKeyVersions + .asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + ( + client.descriptors.page.listCryptoKeyVersions + .asyncIterate as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); + + it('uses async iteration with listCryptoKeyVersions with error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.ListCryptoKeyVersionsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.ListCryptoKeyVersionsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listCryptoKeyVersions.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listCryptoKeyVersionsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.cloud.kms.v1.ICryptoKeyVersion[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listCryptoKeyVersions + .asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + ( + client.descriptors.page.listCryptoKeyVersions + .asyncIterate as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); + }); + + describe('listImportJobs', () => { + it('invokes listImportJobs without error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.ListImportJobsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.ListImportJobsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.kms.v1.ImportJob()), + generateSampleMessage(new protos.google.cloud.kms.v1.ImportJob()), + generateSampleMessage(new protos.google.cloud.kms.v1.ImportJob()), + ]; + client.innerApiCalls.listImportJobs = stubSimpleCall(expectedResponse); + const [response] = await client.listImportJobs(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listImportJobs as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listImportJobs as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listImportJobs without error using callback', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.ListImportJobsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.ListImportJobsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.kms.v1.ImportJob()), + generateSampleMessage(new protos.google.cloud.kms.v1.ImportJob()), + generateSampleMessage(new protos.google.cloud.kms.v1.ImportJob()), + ]; + client.innerApiCalls.listImportJobs = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listImportJobs( + request, + ( + err?: Error | null, + result?: protos.google.cloud.kms.v1.IImportJob[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listImportJobs as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listImportJobs as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listImportJobs with error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.ListImportJobsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.ListImportJobsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listImportJobs = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listImportJobs(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listImportJobs as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listImportJobs as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listImportJobsStream without error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.ListImportJobsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.ListImportJobsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.kms.v1.ImportJob()), + generateSampleMessage(new protos.google.cloud.kms.v1.ImportJob()), + generateSampleMessage(new protos.google.cloud.kms.v1.ImportJob()), + ]; + client.descriptors.page.listImportJobs.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listImportJobsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.cloud.kms.v1.ImportJob[] = []; + stream.on('data', (response: protos.google.cloud.kms.v1.ImportJob) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listImportJobs.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listImportJobs, request), + ); + assert( + (client.descriptors.page.listImportJobs.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + + it('invokes listImportJobsStream with error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.ListImportJobsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.ListImportJobsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listImportJobs.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listImportJobsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.cloud.kms.v1.ImportJob[] = []; + stream.on('data', (response: protos.google.cloud.kms.v1.ImportJob) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listImportJobs.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listImportJobs, request), + ); + assert( + (client.descriptors.page.listImportJobs.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + + it('uses async iteration with listImportJobs without error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.ListImportJobsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.ListImportJobsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.kms.v1.ImportJob()), + generateSampleMessage(new protos.google.cloud.kms.v1.ImportJob()), + generateSampleMessage(new protos.google.cloud.kms.v1.ImportJob()), + ]; + client.descriptors.page.listImportJobs.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.cloud.kms.v1.IImportJob[] = []; + const iterable = client.listImportJobsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listImportJobs.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listImportJobs.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + + it('uses async iteration with listImportJobs with error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.kms.v1.ListImportJobsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.kms.v1.ListImportJobsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listImportJobs.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listImportJobsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.cloud.kms.v1.IImportJob[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listImportJobs.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listImportJobs.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + }); + describe('getIamPolicy', () => { + it('invokes getIamPolicy without error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new IamProtos.google.iam.v1.GetIamPolicyRequest(), + ); + request.resource = ''; + const expectedHeaderRequestParams = 'resource='; + const expectedOptions = { + otherArgs: { + headers: { + 'x-goog-request-params': expectedHeaderRequestParams, + }, + }, + }; + const expectedResponse = generateSampleMessage( + new IamProtos.google.iam.v1.Policy(), + ); + client.iamClient.getIamPolicy = stubSimpleCall(expectedResponse); + const response = await client.getIamPolicy(request, expectedOptions); + assert.deepStrictEqual(response, [expectedResponse]); + assert( + (client.iamClient.getIamPolicy as SinonStub) + .getCall(0) + .calledWith(request, expectedOptions, undefined), + ); + }); + it('invokes getIamPolicy without error using callback', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new IamProtos.google.iam.v1.GetIamPolicyRequest(), + ); + request.resource = ''; + const expectedHeaderRequestParams = 'resource='; + const expectedOptions = { + otherArgs: { + headers: { + 'x-goog-request-params': expectedHeaderRequestParams, + }, + }, + }; + const expectedResponse = generateSampleMessage( + new IamProtos.google.iam.v1.Policy(), + ); + client.iamClient.getIamPolicy = sinon + .stub() + .callsArgWith(2, null, expectedResponse); + const promise = new Promise((resolve, reject) => { + client + .getIamPolicy( + request, + expectedOptions, + ( + err?: Error | null, + result?: IamProtos.google.iam.v1.Policy | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ) + .catch((err) => { + throw err; + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + assert((client.iamClient.getIamPolicy as SinonStub).getCall(0)); + }); + it('invokes getIamPolicy with error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new IamProtos.google.iam.v1.GetIamPolicyRequest(), + ); + request.resource = ''; + const expectedHeaderRequestParams = 'resource='; + const expectedOptions = { + otherArgs: { + headers: { + 'x-goog-request-params': expectedHeaderRequestParams, + }, + }, + }; + const expectedError = new Error('expected'); + client.iamClient.getIamPolicy = stubSimpleCall(undefined, expectedError); + await assert.rejects( + client.getIamPolicy(request, expectedOptions), + expectedError, + ); + assert( + (client.iamClient.getIamPolicy as SinonStub) + .getCall(0) + .calledWith(request, expectedOptions, undefined), + ); + }); + }); + describe('setIamPolicy', () => { + it('invokes setIamPolicy without error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new IamProtos.google.iam.v1.SetIamPolicyRequest(), + ); + request.resource = ''; + const expectedHeaderRequestParams = 'resource='; + const expectedOptions = { + otherArgs: { + headers: { + 'x-goog-request-params': expectedHeaderRequestParams, + }, + }, + }; + const expectedResponse = generateSampleMessage( + new IamProtos.google.iam.v1.Policy(), + ); + client.iamClient.setIamPolicy = stubSimpleCall(expectedResponse); + const response = await client.setIamPolicy(request, expectedOptions); + assert.deepStrictEqual(response, [expectedResponse]); + assert( + (client.iamClient.setIamPolicy as SinonStub) + .getCall(0) + .calledWith(request, expectedOptions, undefined), + ); + }); + it('invokes setIamPolicy without error using callback', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new IamProtos.google.iam.v1.SetIamPolicyRequest(), + ); + request.resource = ''; + const expectedHeaderRequestParams = 'resource='; + const expectedOptions = { + otherArgs: { + headers: { + 'x-goog-request-params': expectedHeaderRequestParams, + }, + }, + }; + const expectedResponse = generateSampleMessage( + new IamProtos.google.iam.v1.Policy(), + ); + client.iamClient.setIamPolicy = sinon + .stub() + .callsArgWith(2, null, expectedResponse); + const promise = new Promise((resolve, reject) => { + client + .setIamPolicy( + request, + expectedOptions, + ( + err?: Error | null, + result?: IamProtos.google.iam.v1.Policy | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ) + .catch((err) => { + throw err; + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + assert((client.iamClient.setIamPolicy as SinonStub).getCall(0)); + }); + it('invokes setIamPolicy with error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new IamProtos.google.iam.v1.SetIamPolicyRequest(), + ); + request.resource = ''; + const expectedHeaderRequestParams = 'resource='; + const expectedOptions = { + otherArgs: { + headers: { + 'x-goog-request-params': expectedHeaderRequestParams, + }, + }, + }; + const expectedError = new Error('expected'); + client.iamClient.setIamPolicy = stubSimpleCall(undefined, expectedError); + await assert.rejects( + client.setIamPolicy(request, expectedOptions), + expectedError, + ); + assert( + (client.iamClient.setIamPolicy as SinonStub) + .getCall(0) + .calledWith(request, expectedOptions, undefined), + ); + }); + }); + describe('testIamPermissions', () => { + it('invokes testIamPermissions without error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new IamProtos.google.iam.v1.TestIamPermissionsRequest(), + ); + request.resource = ''; + const expectedHeaderRequestParams = 'resource='; + const expectedOptions = { + otherArgs: { + headers: { + 'x-goog-request-params': expectedHeaderRequestParams, + }, + }, + }; + const expectedResponse = generateSampleMessage( + new IamProtos.google.iam.v1.TestIamPermissionsResponse(), + ); + client.iamClient.testIamPermissions = stubSimpleCall(expectedResponse); + const response = await client.testIamPermissions( + request, + expectedOptions, + ); + assert.deepStrictEqual(response, [expectedResponse]); + assert( + (client.iamClient.testIamPermissions as SinonStub) + .getCall(0) + .calledWith(request, expectedOptions, undefined), + ); + }); + it('invokes testIamPermissions without error using callback', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new IamProtos.google.iam.v1.TestIamPermissionsRequest(), + ); + request.resource = ''; + const expectedHeaderRequestParams = 'resource='; + const expectedOptions = { + otherArgs: { + headers: { + 'x-goog-request-params': expectedHeaderRequestParams, + }, + }, + }; + const expectedResponse = generateSampleMessage( + new IamProtos.google.iam.v1.TestIamPermissionsResponse(), + ); + client.iamClient.testIamPermissions = sinon + .stub() + .callsArgWith(2, null, expectedResponse); + const promise = new Promise((resolve, reject) => { + client + .testIamPermissions( + request, + expectedOptions, + ( + err?: Error | null, + result?: IamProtos.google.iam.v1.TestIamPermissionsResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ) + .catch((err) => { + throw err; + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + assert((client.iamClient.testIamPermissions as SinonStub).getCall(0)); + }); + it('invokes testIamPermissions with error', async () => { + const client = + new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new IamProtos.google.iam.v1.TestIamPermissionsRequest(), + ); + request.resource = ''; + const expectedHeaderRequestParams = 'resource='; + const expectedOptions = { + otherArgs: { + headers: { + 'x-goog-request-params': expectedHeaderRequestParams, + }, + }, + }; + const expectedError = new Error('expected'); + client.iamClient.testIamPermissions = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.testIamPermissions(request, expectedOptions), + expectedError, + ); + assert( + (client.iamClient.testIamPermissions as SinonStub) + .getCall(0) + .calledWith(request, expectedOptions, undefined), + ); }); + }); }); diff --git a/core/generator/gapic-generator-typescript/baselines/logging-esm/esm/src/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/logging-esm/esm/src/index.ts.baseline index 5d29d89a98e4..0e4a8635120c 100644 --- a/core/generator/gapic-generator-typescript/baselines/logging-esm/esm/src/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/logging-esm/esm/src/index.ts.baseline @@ -23,8 +23,18 @@ const LoggingServiceV2Client = v2.LoggingServiceV2Client; type LoggingServiceV2Client = v2.LoggingServiceV2Client; const MetricsServiceV2Client = v2.MetricsServiceV2Client; type MetricsServiceV2Client = v2.MetricsServiceV2Client; -export {v2, ConfigServiceV2Client, LoggingServiceV2Client, MetricsServiceV2Client}; -export default {v2, ConfigServiceV2Client, LoggingServiceV2Client, MetricsServiceV2Client}; +export { + v2, + ConfigServiceV2Client, + LoggingServiceV2Client, + MetricsServiceV2Client, +}; +export default { + v2, + ConfigServiceV2Client, + LoggingServiceV2Client, + MetricsServiceV2Client, +}; // @ts-ignore import * as protos from '../../protos/protos.js'; -export {protos} +export { protos }; diff --git a/core/generator/gapic-generator-typescript/baselines/logging-esm/esm/src/v2/config_service_v2_client.ts.baseline b/core/generator/gapic-generator-typescript/baselines/logging-esm/esm/src/v2/config_service_v2_client.ts.baseline index b93456194098..21727f6414dc 100644 --- a/core/generator/gapic-generator-typescript/baselines/logging-esm/esm/src/v2/config_service_v2_client.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/logging-esm/esm/src/v2/config_service_v2_client.ts.baseline @@ -18,15 +18,24 @@ /* global window */ import * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions, GrpcClientOptions, LROperation, PaginationCallback, GaxCall} from 'google-gax'; -import {Transform} from 'stream'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + GrpcClientOptions, + LROperation, + PaginationCallback, + GaxCall, +} from 'google-gax'; +import { Transform } from 'stream'; // @ts-ignore import type * as protos from '../../../protos/protos.js'; import * as config_service_v2_client_config from './config_service_v2_client_config.json'; import fs from 'fs'; import path from 'path'; -import {fileURLToPath} from 'url'; -import {getJSON} from '../json-helper.cjs'; +import { fileURLToPath } from 'url'; +import { getJSON } from '../json-helper.cjs'; // @ts-ignore const dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -36,15 +45,15 @@ const dirname = path.dirname(fileURLToPath(import.meta.url)); * This file defines retry strategy and timeouts for all API methods in this library. */ const gapicConfig = getJSON( - path.join(dirname, 'config_service_v2_client_config.json') + path.join(dirname, 'config_service_v2_client_config.json'), ); const jsonProtos = getJSON( - path.join(dirname, '..', '..', '..', 'protos/protos.json') + path.join(dirname, '..', '..', '..', 'protos/protos.json'), ); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; const version = getJSON( - path.join(dirname, '..', '..', '..', '..', 'package.json') + path.join(dirname, '..', '..', '..', '..', 'package.json'), ).version; /** @@ -59,7 +68,7 @@ export class ConfigServiceV2Client { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('logging'); @@ -71,10 +80,10 @@ export class ConfigServiceV2Client { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; operationsClient: gax.OperationsClient; - configServiceV2Stub?: Promise<{[name: string]: Function}>; + configServiceV2Stub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of ConfigServiceV2Client. @@ -116,21 +125,42 @@ export class ConfigServiceV2Client { * const client = new ConfigServiceV2Client({fallback: 'rest'}, gax); * ``` */ - constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { // Ensure that options include all the required fields. const staticMembers = this.constructor as typeof ConfigServiceV2Client; - if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { - throw new Error('Please set either universe_domain or universeDomain, but not both.'); + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); } - const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; - this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; this._servicePath = 'logging.' + this._universeDomain; - const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; - const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. if (servicePath !== this._servicePath && !('scopes' in opts)) { @@ -152,7 +182,7 @@ export class ConfigServiceV2Client { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; @@ -169,10 +199,7 @@ export class ConfigServiceV2Client { const isEsm = true; const isEsmString = isEsm ? '-esm' : '-cjs'; // Determine the client header string. - const clientHeader = [ - `gax/${this._gaxModule.version}`, - `gapic/${version}`, - ]; + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/{process.versions.node}${isEsmString}`); } else { @@ -180,7 +207,7 @@ export class ConfigServiceV2Client { } if (!opts.fallback) { clientHeader.push(`grpc/${this._gaxGrpc.grpcVersion}`); - } else if (opts.fallback === 'rest' ) { + } else if (opts.fallback === 'rest') { clientHeader.push(`rest/${this._gaxGrpc.grpcVersion}`); } if (opts.libName && opts.libVersion) { @@ -188,104 +215,109 @@ export class ConfigServiceV2Client { } // Load the applicable protos. - this._protos = this._gaxGrpc.loadProtoJSON(jsonProtos as gax.protobuf.INamespace); + this._protos = this._gaxGrpc.loadProtoJSON( + jsonProtos as gax.protobuf.INamespace, + ); // This API contains "path templates"; forward-slash-separated // identifiers to uniquely identify resources within the API. // Create useful helper objects for these. this.pathTemplates = { billingAccountCmekSettingsPathTemplate: new this._gaxModule.PathTemplate( - 'billingAccounts/{billing_account}/cmekSettings' + 'billingAccounts/{billing_account}/cmekSettings', ), billingAccountExclusionPathTemplate: new this._gaxModule.PathTemplate( - 'billingAccounts/{billing_account}/exclusions/{exclusion}' - ), - billingAccountLocationBucketPathTemplate: new this._gaxModule.PathTemplate( - 'billingAccounts/{billing_account}/locations/{location}/buckets/{bucket}' - ), - billingAccountLocationBucketViewPathTemplate: new this._gaxModule.PathTemplate( - 'billingAccounts/{billing_account}/locations/{location}/buckets/{bucket}/views/{view}' + 'billingAccounts/{billing_account}/exclusions/{exclusion}', ), + billingAccountLocationBucketPathTemplate: + new this._gaxModule.PathTemplate( + 'billingAccounts/{billing_account}/locations/{location}/buckets/{bucket}', + ), + billingAccountLocationBucketViewPathTemplate: + new this._gaxModule.PathTemplate( + 'billingAccounts/{billing_account}/locations/{location}/buckets/{bucket}/views/{view}', + ), billingAccountLogPathTemplate: new this._gaxModule.PathTemplate( - 'billingAccounts/{billing_account}/logs/{log}' + 'billingAccounts/{billing_account}/logs/{log}', ), billingAccountSettingsPathTemplate: new this._gaxModule.PathTemplate( - 'billingAccounts/{billing_account}/settings' + 'billingAccounts/{billing_account}/settings', ), billingAccountSinkPathTemplate: new this._gaxModule.PathTemplate( - 'billingAccounts/{billing_account}/sinks/{sink}' + 'billingAccounts/{billing_account}/sinks/{sink}', ), folderCmekSettingsPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/cmekSettings' + 'folders/{folder}/cmekSettings', ), folderExclusionPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/exclusions/{exclusion}' + 'folders/{folder}/exclusions/{exclusion}', ), folderLocationBucketPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/locations/{location}/buckets/{bucket}' + 'folders/{folder}/locations/{location}/buckets/{bucket}', ), folderLocationBucketViewPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/locations/{location}/buckets/{bucket}/views/{view}' + 'folders/{folder}/locations/{location}/buckets/{bucket}/views/{view}', ), folderLogPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/logs/{log}' + 'folders/{folder}/logs/{log}', ), folderSettingsPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/settings' + 'folders/{folder}/settings', ), folderSinkPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/sinks/{sink}' + 'folders/{folder}/sinks/{sink}', ), locationPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}' + 'projects/{project}/locations/{location}', ), logMetricPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/metrics/{metric}' + 'projects/{project}/metrics/{metric}', ), organizationCmekSettingsPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/cmekSettings' + 'organizations/{organization}/cmekSettings', ), organizationExclusionPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/exclusions/{exclusion}' + 'organizations/{organization}/exclusions/{exclusion}', ), organizationLocationBucketPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/locations/{location}/buckets/{bucket}' - ), - organizationLocationBucketViewPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/locations/{location}/buckets/{bucket}/views/{view}' + 'organizations/{organization}/locations/{location}/buckets/{bucket}', ), + organizationLocationBucketViewPathTemplate: + new this._gaxModule.PathTemplate( + 'organizations/{organization}/locations/{location}/buckets/{bucket}/views/{view}', + ), organizationLogPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/logs/{log}' + 'organizations/{organization}/logs/{log}', ), organizationSettingsPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/settings' + 'organizations/{organization}/settings', ), organizationSinkPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/sinks/{sink}' + 'organizations/{organization}/sinks/{sink}', ), projectPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}' + 'projects/{project}', ), projectCmekSettingsPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/cmekSettings' + 'projects/{project}/cmekSettings', ), projectExclusionPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/exclusions/{exclusion}' + 'projects/{project}/exclusions/{exclusion}', ), projectLocationBucketPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/buckets/{bucket}' + 'projects/{project}/locations/{location}/buckets/{bucket}', ), projectLocationBucketViewPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/buckets/{bucket}/views/{view}' + 'projects/{project}/locations/{location}/buckets/{bucket}/views/{view}', ), projectLogPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/logs/{log}' + 'projects/{project}/logs/{log}', ), projectSettingsPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/settings' + 'projects/{project}/settings', ), projectSinkPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/sinks/{sink}' + 'projects/{project}/sinks/{sink}', ), }; @@ -293,14 +325,26 @@ export class ConfigServiceV2Client { // (e.g. 50 results at a time, with tokens to get subsequent // pages). Denote the keys used for pagination and results. this.descriptors.page = { - listBuckets: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'buckets'), - listViews: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'views'), - listSinks: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'sinks'), - listExclusions: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'exclusions') + listBuckets: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'buckets', + ), + listViews: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'views', + ), + listSinks: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'sinks', + ), + listExclusions: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'exclusions', + ), }; const protoFilesRoot = this._gaxModule.protobufFromJSON(jsonProtos); @@ -309,29 +353,37 @@ export class ConfigServiceV2Client { // rather than holding a request open. const lroOptions: GrpcClientOptions = { auth: this.auth, - grpc: 'grpc' in this._gaxGrpc ? this._gaxGrpc.grpc : undefined + grpc: 'grpc' in this._gaxGrpc ? this._gaxGrpc.grpc : undefined, }; if (opts.fallback === 'rest') { lroOptions.protoJson = protoFilesRoot; lroOptions.httpRules = []; } - this.operationsClient = this._gaxModule.lro(lroOptions).operationsClient(opts); + this.operationsClient = this._gaxModule + .lro(lroOptions) + .operationsClient(opts); const copyLogEntriesResponse = protoFilesRoot.lookup( - '.google.logging.v2.CopyLogEntriesResponse') as gax.protobuf.Type; + '.google.logging.v2.CopyLogEntriesResponse', + ) as gax.protobuf.Type; const copyLogEntriesMetadata = protoFilesRoot.lookup( - '.google.logging.v2.CopyLogEntriesMetadata') as gax.protobuf.Type; + '.google.logging.v2.CopyLogEntriesMetadata', + ) as gax.protobuf.Type; this.descriptors.longrunning = { copyLogEntries: new this._gaxModule.LongrunningDescriptor( this.operationsClient, copyLogEntriesResponse.decode.bind(copyLogEntriesResponse), - copyLogEntriesMetadata.decode.bind(copyLogEntriesMetadata)) + copyLogEntriesMetadata.decode.bind(copyLogEntriesMetadata), + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.logging.v2.ConfigServiceV2', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.logging.v2.ConfigServiceV2', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + { 'x-goog-api-client': clientHeader.join(' ') }, + ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -362,28 +414,60 @@ export class ConfigServiceV2Client { // Put together the "service stub" for // google.logging.v2.ConfigServiceV2. this.configServiceV2Stub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.logging.v2.ConfigServiceV2') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.logging.v2.ConfigServiceV2', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.logging.v2.ConfigServiceV2, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts, + this._providedCustomServicePath, + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const configServiceV2StubMethods = - ['listBuckets', 'getBucket', 'createBucket', 'updateBucket', 'deleteBucket', 'undeleteBucket', 'listViews', 'getView', 'createView', 'updateView', 'deleteView', 'listSinks', 'getSink', 'createSink', 'updateSink', 'deleteSink', 'listExclusions', 'getExclusion', 'createExclusion', 'updateExclusion', 'deleteExclusion', 'getCmekSettings', 'updateCmekSettings', 'getSettings', 'updateSettings', 'copyLogEntries']; + const configServiceV2StubMethods = [ + 'listBuckets', + 'getBucket', + 'createBucket', + 'updateBucket', + 'deleteBucket', + 'undeleteBucket', + 'listViews', + 'getView', + 'createView', + 'updateView', + 'deleteView', + 'listSinks', + 'getSink', + 'createSink', + 'updateSink', + 'deleteSink', + 'listExclusions', + 'getExclusion', + 'createExclusion', + 'updateExclusion', + 'deleteExclusion', + 'getCmekSettings', + 'updateCmekSettings', + 'getSettings', + 'updateSettings', + 'copyLogEntries', + ]; for (const methodName of configServiceV2StubMethods) { const callPromise = this.configServiceV2Stub.then( - stub => (...args: Array<{}>) => { - if (this._terminated) { - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error|null|undefined) => () => { + (stub) => + (...args: Array<{}>) => { + if (this._terminated) { + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { throw err; - }); + }, + ); const descriptor = this.descriptors.page[methodName] || @@ -393,7 +477,7 @@ export class ConfigServiceV2Client { callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -408,8 +492,14 @@ export class ConfigServiceV2Client { * @returns {string} The DNS address for this service. */ static get servicePath() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'logging.googleapis.com'; } @@ -421,8 +511,14 @@ export class ConfigServiceV2Client { * @returns {string} The DNS address for this service. */ static get apiEndpoint() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'logging.googleapis.com'; } @@ -457,7 +553,7 @@ export class ConfigServiceV2Client { 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/cloud-platform.read-only', 'https://www.googleapis.com/auth/logging.admin', - 'https://www.googleapis.com/auth/logging.read' + 'https://www.googleapis.com/auth/logging.read', ]; } @@ -467,8 +563,9 @@ export class ConfigServiceV2Client { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId(callback?: Callback): - Promise|void { + getProjectId( + callback?: Callback, + ): Promise | void { if (callback) { this.auth.getProjectId(callback); return; @@ -479,2563 +576,3296 @@ export class ConfigServiceV2Client { // ------------------- // -- Service calls -- // ------------------- -/** - * Gets a log bucket. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The resource name of the bucket: - * - * "projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" - * "organizations/[ORGANIZATION_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" - * "billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" - * "folders/[FOLDER_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" - * - * For example: - * - * `"projects/my-project/locations/global/buckets/my-bucket"` - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.logging.v2.LogBucket|LogBucket}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/config_service_v2.get_bucket.js - * region_tag:logging_v2_generated_ConfigServiceV2_GetBucket_async - */ + /** + * Gets a log bucket. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The resource name of the bucket: + * + * "projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" + * "organizations/[ORGANIZATION_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" + * "billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" + * "folders/[FOLDER_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" + * + * For example: + * + * `"projects/my-project/locations/global/buckets/my-bucket"` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.logging.v2.LogBucket|LogBucket}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/config_service_v2.get_bucket.js + * region_tag:logging_v2_generated_ConfigServiceV2_GetBucket_async + */ getBucket( - request?: protos.google.logging.v2.IGetBucketRequest, - options?: CallOptions): - Promise<[ - protos.google.logging.v2.ILogBucket, - protos.google.logging.v2.IGetBucketRequest|undefined, {}|undefined - ]>; + request?: protos.google.logging.v2.IGetBucketRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.logging.v2.ILogBucket, + protos.google.logging.v2.IGetBucketRequest | undefined, + {} | undefined, + ] + >; getBucket( - request: protos.google.logging.v2.IGetBucketRequest, - options: CallOptions, - callback: Callback< - protos.google.logging.v2.ILogBucket, - protos.google.logging.v2.IGetBucketRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.logging.v2.IGetBucketRequest, + options: CallOptions, + callback: Callback< + protos.google.logging.v2.ILogBucket, + protos.google.logging.v2.IGetBucketRequest | null | undefined, + {} | null | undefined + >, + ): void; getBucket( - request: protos.google.logging.v2.IGetBucketRequest, - callback: Callback< - protos.google.logging.v2.ILogBucket, - protos.google.logging.v2.IGetBucketRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.logging.v2.IGetBucketRequest, + callback: Callback< + protos.google.logging.v2.ILogBucket, + protos.google.logging.v2.IGetBucketRequest | null | undefined, + {} | null | undefined + >, + ): void; getBucket( - request?: protos.google.logging.v2.IGetBucketRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.logging.v2.ILogBucket, - protos.google.logging.v2.IGetBucketRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.logging.v2.IGetBucketRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.logging.v2.ILogBucket, - protos.google.logging.v2.IGetBucketRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.logging.v2.ILogBucket, - protos.google.logging.v2.IGetBucketRequest|undefined, {}|undefined - ]>|void { + protos.google.logging.v2.IGetBucketRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.logging.v2.ILogBucket, + protos.google.logging.v2.IGetBucketRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.logging.v2.ILogBucket, + protos.google.logging.v2.IGetBucketRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getBucket request %j', request); - const wrappedCallback: Callback< - protos.google.logging.v2.ILogBucket, - protos.google.logging.v2.IGetBucketRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.logging.v2.ILogBucket, + protos.google.logging.v2.IGetBucketRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getBucket response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.getBucket(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.logging.v2.ILogBucket, - protos.google.logging.v2.IGetBucketRequest|undefined, {}|undefined - ]) => { - this._log.info('getBucket response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getBucket(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.logging.v2.ILogBucket, + protos.google.logging.v2.IGetBucketRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getBucket response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Creates a log bucket that can be used to store log entries. After a bucket - * has been created, the bucket's location cannot be changed. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The resource in which to create the log bucket: - * - * "projects/[PROJECT_ID]/locations/[LOCATION_ID]" - * - * For example: - * - * `"projects/my-project/locations/global"` - * @param {string} request.bucketId - * Required. A client-assigned identifier such as `"my-bucket"`. Identifiers are limited - * to 100 characters and can include only letters, digits, underscores, - * hyphens, and periods. - * @param {google.logging.v2.LogBucket} request.bucket - * Required. The new bucket. The region specified in the new bucket must be compliant - * with any Location Restriction Org Policy. The name field in the bucket is - * ignored. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.logging.v2.LogBucket|LogBucket}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/config_service_v2.create_bucket.js - * region_tag:logging_v2_generated_ConfigServiceV2_CreateBucket_async - */ + /** + * Creates a log bucket that can be used to store log entries. After a bucket + * has been created, the bucket's location cannot be changed. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The resource in which to create the log bucket: + * + * "projects/[PROJECT_ID]/locations/[LOCATION_ID]" + * + * For example: + * + * `"projects/my-project/locations/global"` + * @param {string} request.bucketId + * Required. A client-assigned identifier such as `"my-bucket"`. Identifiers are limited + * to 100 characters and can include only letters, digits, underscores, + * hyphens, and periods. + * @param {google.logging.v2.LogBucket} request.bucket + * Required. The new bucket. The region specified in the new bucket must be compliant + * with any Location Restriction Org Policy. The name field in the bucket is + * ignored. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.logging.v2.LogBucket|LogBucket}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/config_service_v2.create_bucket.js + * region_tag:logging_v2_generated_ConfigServiceV2_CreateBucket_async + */ createBucket( - request?: protos.google.logging.v2.ICreateBucketRequest, - options?: CallOptions): - Promise<[ - protos.google.logging.v2.ILogBucket, - protos.google.logging.v2.ICreateBucketRequest|undefined, {}|undefined - ]>; + request?: protos.google.logging.v2.ICreateBucketRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.logging.v2.ILogBucket, + protos.google.logging.v2.ICreateBucketRequest | undefined, + {} | undefined, + ] + >; createBucket( - request: protos.google.logging.v2.ICreateBucketRequest, - options: CallOptions, - callback: Callback< - protos.google.logging.v2.ILogBucket, - protos.google.logging.v2.ICreateBucketRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.logging.v2.ICreateBucketRequest, + options: CallOptions, + callback: Callback< + protos.google.logging.v2.ILogBucket, + protos.google.logging.v2.ICreateBucketRequest | null | undefined, + {} | null | undefined + >, + ): void; createBucket( - request: protos.google.logging.v2.ICreateBucketRequest, - callback: Callback< - protos.google.logging.v2.ILogBucket, - protos.google.logging.v2.ICreateBucketRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.logging.v2.ICreateBucketRequest, + callback: Callback< + protos.google.logging.v2.ILogBucket, + protos.google.logging.v2.ICreateBucketRequest | null | undefined, + {} | null | undefined + >, + ): void; createBucket( - request?: protos.google.logging.v2.ICreateBucketRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.logging.v2.ICreateBucketRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.logging.v2.ILogBucket, - protos.google.logging.v2.ICreateBucketRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.logging.v2.ILogBucket, - protos.google.logging.v2.ICreateBucketRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.logging.v2.ILogBucket, - protos.google.logging.v2.ICreateBucketRequest|undefined, {}|undefined - ]>|void { + protos.google.logging.v2.ICreateBucketRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.logging.v2.ILogBucket, + protos.google.logging.v2.ICreateBucketRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.logging.v2.ILogBucket, + protos.google.logging.v2.ICreateBucketRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('createBucket request %j', request); - const wrappedCallback: Callback< - protos.google.logging.v2.ILogBucket, - protos.google.logging.v2.ICreateBucketRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.logging.v2.ILogBucket, + protos.google.logging.v2.ICreateBucketRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createBucket response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.createBucket(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.logging.v2.ILogBucket, - protos.google.logging.v2.ICreateBucketRequest|undefined, {}|undefined - ]) => { - this._log.info('createBucket response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createBucket(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.logging.v2.ILogBucket, + protos.google.logging.v2.ICreateBucketRequest | undefined, + {} | undefined, + ]) => { + this._log.info('createBucket response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Updates a log bucket. This method replaces the following fields in the - * existing bucket with values from the new bucket: `retention_period` - * - * If the retention period is decreased and the bucket is locked, - * `FAILED_PRECONDITION` will be returned. - * - * If the bucket has a `lifecycle_state` of `DELETE_REQUESTED`, then - * `FAILED_PRECONDITION` will be returned. - * - * After a bucket has been created, the bucket's location cannot be changed. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The full resource name of the bucket to update. - * - * "projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" - * "organizations/[ORGANIZATION_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" - * "billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" - * "folders/[FOLDER_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" - * - * For example: - * - * `"projects/my-project/locations/global/buckets/my-bucket"` - * @param {google.logging.v2.LogBucket} request.bucket - * Required. The updated bucket. - * @param {google.protobuf.FieldMask} request.updateMask - * Required. Field mask that specifies the fields in `bucket` that need an update. A - * bucket field will be overwritten if, and only if, it is in the update mask. - * `name` and output only fields cannot be updated. - * - * For a detailed `FieldMask` definition, see: - * https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#google.protobuf.FieldMask - * - * For example: `updateMask=retention_days` - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.logging.v2.LogBucket|LogBucket}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/config_service_v2.update_bucket.js - * region_tag:logging_v2_generated_ConfigServiceV2_UpdateBucket_async - */ + /** + * Updates a log bucket. This method replaces the following fields in the + * existing bucket with values from the new bucket: `retention_period` + * + * If the retention period is decreased and the bucket is locked, + * `FAILED_PRECONDITION` will be returned. + * + * If the bucket has a `lifecycle_state` of `DELETE_REQUESTED`, then + * `FAILED_PRECONDITION` will be returned. + * + * After a bucket has been created, the bucket's location cannot be changed. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The full resource name of the bucket to update. + * + * "projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" + * "organizations/[ORGANIZATION_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" + * "billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" + * "folders/[FOLDER_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" + * + * For example: + * + * `"projects/my-project/locations/global/buckets/my-bucket"` + * @param {google.logging.v2.LogBucket} request.bucket + * Required. The updated bucket. + * @param {google.protobuf.FieldMask} request.updateMask + * Required. Field mask that specifies the fields in `bucket` that need an update. A + * bucket field will be overwritten if, and only if, it is in the update mask. + * `name` and output only fields cannot be updated. + * + * For a detailed `FieldMask` definition, see: + * https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#google.protobuf.FieldMask + * + * For example: `updateMask=retention_days` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.logging.v2.LogBucket|LogBucket}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/config_service_v2.update_bucket.js + * region_tag:logging_v2_generated_ConfigServiceV2_UpdateBucket_async + */ updateBucket( - request?: protos.google.logging.v2.IUpdateBucketRequest, - options?: CallOptions): - Promise<[ - protos.google.logging.v2.ILogBucket, - protos.google.logging.v2.IUpdateBucketRequest|undefined, {}|undefined - ]>; + request?: protos.google.logging.v2.IUpdateBucketRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.logging.v2.ILogBucket, + protos.google.logging.v2.IUpdateBucketRequest | undefined, + {} | undefined, + ] + >; updateBucket( - request: protos.google.logging.v2.IUpdateBucketRequest, - options: CallOptions, - callback: Callback< - protos.google.logging.v2.ILogBucket, - protos.google.logging.v2.IUpdateBucketRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.logging.v2.IUpdateBucketRequest, + options: CallOptions, + callback: Callback< + protos.google.logging.v2.ILogBucket, + protos.google.logging.v2.IUpdateBucketRequest | null | undefined, + {} | null | undefined + >, + ): void; updateBucket( - request: protos.google.logging.v2.IUpdateBucketRequest, - callback: Callback< - protos.google.logging.v2.ILogBucket, - protos.google.logging.v2.IUpdateBucketRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.logging.v2.IUpdateBucketRequest, + callback: Callback< + protos.google.logging.v2.ILogBucket, + protos.google.logging.v2.IUpdateBucketRequest | null | undefined, + {} | null | undefined + >, + ): void; updateBucket( - request?: protos.google.logging.v2.IUpdateBucketRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.logging.v2.IUpdateBucketRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.logging.v2.ILogBucket, - protos.google.logging.v2.IUpdateBucketRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.logging.v2.ILogBucket, - protos.google.logging.v2.IUpdateBucketRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.logging.v2.ILogBucket, - protos.google.logging.v2.IUpdateBucketRequest|undefined, {}|undefined - ]>|void { + protos.google.logging.v2.IUpdateBucketRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.logging.v2.ILogBucket, + protos.google.logging.v2.IUpdateBucketRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.logging.v2.ILogBucket, + protos.google.logging.v2.IUpdateBucketRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateBucket request %j', request); - const wrappedCallback: Callback< - protos.google.logging.v2.ILogBucket, - protos.google.logging.v2.IUpdateBucketRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.logging.v2.ILogBucket, + protos.google.logging.v2.IUpdateBucketRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateBucket response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.updateBucket(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.logging.v2.ILogBucket, - protos.google.logging.v2.IUpdateBucketRequest|undefined, {}|undefined - ]) => { - this._log.info('updateBucket response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateBucket(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.logging.v2.ILogBucket, + protos.google.logging.v2.IUpdateBucketRequest | undefined, + {} | undefined, + ]) => { + this._log.info('updateBucket response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Deletes a log bucket. - * - * Changes the bucket's `lifecycle_state` to the `DELETE_REQUESTED` state. - * After 7 days, the bucket will be purged and all log entries in the bucket - * will be permanently deleted. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The full resource name of the bucket to delete. - * - * "projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" - * "organizations/[ORGANIZATION_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" - * "billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" - * "folders/[FOLDER_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" - * - * For example: - * - * `"projects/my-project/locations/global/buckets/my-bucket"` - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/config_service_v2.delete_bucket.js - * region_tag:logging_v2_generated_ConfigServiceV2_DeleteBucket_async - */ + /** + * Deletes a log bucket. + * + * Changes the bucket's `lifecycle_state` to the `DELETE_REQUESTED` state. + * After 7 days, the bucket will be purged and all log entries in the bucket + * will be permanently deleted. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The full resource name of the bucket to delete. + * + * "projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" + * "organizations/[ORGANIZATION_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" + * "billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" + * "folders/[FOLDER_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" + * + * For example: + * + * `"projects/my-project/locations/global/buckets/my-bucket"` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/config_service_v2.delete_bucket.js + * region_tag:logging_v2_generated_ConfigServiceV2_DeleteBucket_async + */ deleteBucket( - request?: protos.google.logging.v2.IDeleteBucketRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.logging.v2.IDeleteBucketRequest|undefined, {}|undefined - ]>; + request?: protos.google.logging.v2.IDeleteBucketRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.logging.v2.IDeleteBucketRequest | undefined, + {} | undefined, + ] + >; deleteBucket( - request: protos.google.logging.v2.IDeleteBucketRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.logging.v2.IDeleteBucketRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.logging.v2.IDeleteBucketRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.logging.v2.IDeleteBucketRequest | null | undefined, + {} | null | undefined + >, + ): void; deleteBucket( - request: protos.google.logging.v2.IDeleteBucketRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.logging.v2.IDeleteBucketRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.logging.v2.IDeleteBucketRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.logging.v2.IDeleteBucketRequest | null | undefined, + {} | null | undefined + >, + ): void; deleteBucket( - request?: protos.google.logging.v2.IDeleteBucketRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.protobuf.IEmpty, - protos.google.logging.v2.IDeleteBucketRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.logging.v2.IDeleteBucketRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.logging.v2.IDeleteBucketRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.logging.v2.IDeleteBucketRequest|undefined, {}|undefined - ]>|void { + protos.google.logging.v2.IDeleteBucketRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + protos.google.logging.v2.IDeleteBucketRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.logging.v2.IDeleteBucketRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('deleteBucket request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.logging.v2.IDeleteBucketRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + protos.google.logging.v2.IDeleteBucketRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteBucket response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.deleteBucket(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.logging.v2.IDeleteBucketRequest|undefined, {}|undefined - ]) => { - this._log.info('deleteBucket response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteBucket(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.logging.v2.IDeleteBucketRequest | undefined, + {} | undefined, + ]) => { + this._log.info('deleteBucket response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Undeletes a log bucket. A bucket that has been deleted can be undeleted - * within the grace period of 7 days. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The full resource name of the bucket to undelete. - * - * "projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" - * "organizations/[ORGANIZATION_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" - * "billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" - * "folders/[FOLDER_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" - * - * For example: - * - * `"projects/my-project/locations/global/buckets/my-bucket"` - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/config_service_v2.undelete_bucket.js - * region_tag:logging_v2_generated_ConfigServiceV2_UndeleteBucket_async - */ + /** + * Undeletes a log bucket. A bucket that has been deleted can be undeleted + * within the grace period of 7 days. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The full resource name of the bucket to undelete. + * + * "projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" + * "organizations/[ORGANIZATION_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" + * "billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" + * "folders/[FOLDER_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" + * + * For example: + * + * `"projects/my-project/locations/global/buckets/my-bucket"` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/config_service_v2.undelete_bucket.js + * region_tag:logging_v2_generated_ConfigServiceV2_UndeleteBucket_async + */ undeleteBucket( - request?: protos.google.logging.v2.IUndeleteBucketRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.logging.v2.IUndeleteBucketRequest|undefined, {}|undefined - ]>; + request?: protos.google.logging.v2.IUndeleteBucketRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.logging.v2.IUndeleteBucketRequest | undefined, + {} | undefined, + ] + >; undeleteBucket( - request: protos.google.logging.v2.IUndeleteBucketRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.logging.v2.IUndeleteBucketRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.logging.v2.IUndeleteBucketRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.logging.v2.IUndeleteBucketRequest | null | undefined, + {} | null | undefined + >, + ): void; undeleteBucket( - request: protos.google.logging.v2.IUndeleteBucketRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.logging.v2.IUndeleteBucketRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.logging.v2.IUndeleteBucketRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.logging.v2.IUndeleteBucketRequest | null | undefined, + {} | null | undefined + >, + ): void; undeleteBucket( - request?: protos.google.logging.v2.IUndeleteBucketRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.logging.v2.IUndeleteBucketRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.logging.v2.IUndeleteBucketRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.protobuf.IEmpty, - protos.google.logging.v2.IUndeleteBucketRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.logging.v2.IUndeleteBucketRequest|undefined, {}|undefined - ]>|void { + protos.google.logging.v2.IUndeleteBucketRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + protos.google.logging.v2.IUndeleteBucketRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.logging.v2.IUndeleteBucketRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('undeleteBucket request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.logging.v2.IUndeleteBucketRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + protos.google.logging.v2.IUndeleteBucketRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('undeleteBucket response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.undeleteBucket(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.logging.v2.IUndeleteBucketRequest|undefined, {}|undefined - ]) => { - this._log.info('undeleteBucket response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .undeleteBucket(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.logging.v2.IUndeleteBucketRequest | undefined, + {} | undefined, + ]) => { + this._log.info('undeleteBucket response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Gets a view on a log bucket.. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The resource name of the policy: - * - * "projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]" - * - * For example: - * - * `"projects/my-project/locations/global/buckets/my-bucket/views/my-view"` - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.logging.v2.LogView|LogView}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/config_service_v2.get_view.js - * region_tag:logging_v2_generated_ConfigServiceV2_GetView_async - */ + /** + * Gets a view on a log bucket.. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The resource name of the policy: + * + * "projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]" + * + * For example: + * + * `"projects/my-project/locations/global/buckets/my-bucket/views/my-view"` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.logging.v2.LogView|LogView}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/config_service_v2.get_view.js + * region_tag:logging_v2_generated_ConfigServiceV2_GetView_async + */ getView( - request?: protos.google.logging.v2.IGetViewRequest, - options?: CallOptions): - Promise<[ - protos.google.logging.v2.ILogView, - protos.google.logging.v2.IGetViewRequest|undefined, {}|undefined - ]>; + request?: protos.google.logging.v2.IGetViewRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.logging.v2.ILogView, + protos.google.logging.v2.IGetViewRequest | undefined, + {} | undefined, + ] + >; getView( - request: protos.google.logging.v2.IGetViewRequest, - options: CallOptions, - callback: Callback< - protos.google.logging.v2.ILogView, - protos.google.logging.v2.IGetViewRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.logging.v2.IGetViewRequest, + options: CallOptions, + callback: Callback< + protos.google.logging.v2.ILogView, + protos.google.logging.v2.IGetViewRequest | null | undefined, + {} | null | undefined + >, + ): void; getView( - request: protos.google.logging.v2.IGetViewRequest, - callback: Callback< - protos.google.logging.v2.ILogView, - protos.google.logging.v2.IGetViewRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.logging.v2.IGetViewRequest, + callback: Callback< + protos.google.logging.v2.ILogView, + protos.google.logging.v2.IGetViewRequest | null | undefined, + {} | null | undefined + >, + ): void; getView( - request?: protos.google.logging.v2.IGetViewRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.logging.v2.ILogView, - protos.google.logging.v2.IGetViewRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.logging.v2.IGetViewRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.logging.v2.ILogView, - protos.google.logging.v2.IGetViewRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.logging.v2.ILogView, - protos.google.logging.v2.IGetViewRequest|undefined, {}|undefined - ]>|void { + protos.google.logging.v2.IGetViewRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.logging.v2.ILogView, + protos.google.logging.v2.IGetViewRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.logging.v2.ILogView, + protos.google.logging.v2.IGetViewRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getView request %j', request); - const wrappedCallback: Callback< - protos.google.logging.v2.ILogView, - protos.google.logging.v2.IGetViewRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.logging.v2.ILogView, + protos.google.logging.v2.IGetViewRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getView response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.getView(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.logging.v2.ILogView, - protos.google.logging.v2.IGetViewRequest|undefined, {}|undefined - ]) => { - this._log.info('getView response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getView(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.logging.v2.ILogView, + protos.google.logging.v2.IGetViewRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getView response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Creates a view over log entries in a log bucket. A bucket may contain a - * maximum of 30 views. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The bucket in which to create the view - * - * `"projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]"` - * - * For example: - * - * `"projects/my-project/locations/global/buckets/my-bucket"` - * @param {string} request.viewId - * Required. The id to use for this view. - * @param {google.logging.v2.LogView} request.view - * Required. The new view. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.logging.v2.LogView|LogView}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/config_service_v2.create_view.js - * region_tag:logging_v2_generated_ConfigServiceV2_CreateView_async - */ + /** + * Creates a view over log entries in a log bucket. A bucket may contain a + * maximum of 30 views. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The bucket in which to create the view + * + * `"projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]"` + * + * For example: + * + * `"projects/my-project/locations/global/buckets/my-bucket"` + * @param {string} request.viewId + * Required. The id to use for this view. + * @param {google.logging.v2.LogView} request.view + * Required. The new view. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.logging.v2.LogView|LogView}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/config_service_v2.create_view.js + * region_tag:logging_v2_generated_ConfigServiceV2_CreateView_async + */ createView( - request?: protos.google.logging.v2.ICreateViewRequest, - options?: CallOptions): - Promise<[ - protos.google.logging.v2.ILogView, - protos.google.logging.v2.ICreateViewRequest|undefined, {}|undefined - ]>; + request?: protos.google.logging.v2.ICreateViewRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.logging.v2.ILogView, + protos.google.logging.v2.ICreateViewRequest | undefined, + {} | undefined, + ] + >; createView( - request: protos.google.logging.v2.ICreateViewRequest, - options: CallOptions, - callback: Callback< - protos.google.logging.v2.ILogView, - protos.google.logging.v2.ICreateViewRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.logging.v2.ICreateViewRequest, + options: CallOptions, + callback: Callback< + protos.google.logging.v2.ILogView, + protos.google.logging.v2.ICreateViewRequest | null | undefined, + {} | null | undefined + >, + ): void; createView( - request: protos.google.logging.v2.ICreateViewRequest, - callback: Callback< - protos.google.logging.v2.ILogView, - protos.google.logging.v2.ICreateViewRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.logging.v2.ICreateViewRequest, + callback: Callback< + protos.google.logging.v2.ILogView, + protos.google.logging.v2.ICreateViewRequest | null | undefined, + {} | null | undefined + >, + ): void; createView( - request?: protos.google.logging.v2.ICreateViewRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.logging.v2.ILogView, - protos.google.logging.v2.ICreateViewRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.logging.v2.ICreateViewRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.logging.v2.ILogView, - protos.google.logging.v2.ICreateViewRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.logging.v2.ILogView, - protos.google.logging.v2.ICreateViewRequest|undefined, {}|undefined - ]>|void { + protos.google.logging.v2.ICreateViewRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.logging.v2.ILogView, + protos.google.logging.v2.ICreateViewRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.logging.v2.ILogView, + protos.google.logging.v2.ICreateViewRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('createView request %j', request); - const wrappedCallback: Callback< - protos.google.logging.v2.ILogView, - protos.google.logging.v2.ICreateViewRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.logging.v2.ILogView, + protos.google.logging.v2.ICreateViewRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createView response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.createView(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.logging.v2.ILogView, - protos.google.logging.v2.ICreateViewRequest|undefined, {}|undefined - ]) => { - this._log.info('createView response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createView(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.logging.v2.ILogView, + protos.google.logging.v2.ICreateViewRequest | undefined, + {} | undefined, + ]) => { + this._log.info('createView response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Updates a view on a log bucket. This method replaces the following fields - * in the existing view with values from the new view: `filter`. - * If an `UNAVAILABLE` error is returned, this indicates that system is not in - * a state where it can update the view. If this occurs, please try again in a - * few minutes. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The full resource name of the view to update - * - * "projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]" - * - * For example: - * - * `"projects/my-project/locations/global/buckets/my-bucket/views/my-view"` - * @param {google.logging.v2.LogView} request.view - * Required. The updated view. - * @param {google.protobuf.FieldMask} [request.updateMask] - * Optional. Field mask that specifies the fields in `view` that need - * an update. A field will be overwritten if, and only if, it is - * in the update mask. `name` and output only fields cannot be updated. - * - * For a detailed `FieldMask` definition, see - * https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#google.protobuf.FieldMask - * - * For example: `updateMask=filter` - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.logging.v2.LogView|LogView}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/config_service_v2.update_view.js - * region_tag:logging_v2_generated_ConfigServiceV2_UpdateView_async - */ + /** + * Updates a view on a log bucket. This method replaces the following fields + * in the existing view with values from the new view: `filter`. + * If an `UNAVAILABLE` error is returned, this indicates that system is not in + * a state where it can update the view. If this occurs, please try again in a + * few minutes. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The full resource name of the view to update + * + * "projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]" + * + * For example: + * + * `"projects/my-project/locations/global/buckets/my-bucket/views/my-view"` + * @param {google.logging.v2.LogView} request.view + * Required. The updated view. + * @param {google.protobuf.FieldMask} [request.updateMask] + * Optional. Field mask that specifies the fields in `view` that need + * an update. A field will be overwritten if, and only if, it is + * in the update mask. `name` and output only fields cannot be updated. + * + * For a detailed `FieldMask` definition, see + * https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#google.protobuf.FieldMask + * + * For example: `updateMask=filter` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.logging.v2.LogView|LogView}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/config_service_v2.update_view.js + * region_tag:logging_v2_generated_ConfigServiceV2_UpdateView_async + */ updateView( - request?: protos.google.logging.v2.IUpdateViewRequest, - options?: CallOptions): - Promise<[ - protos.google.logging.v2.ILogView, - protos.google.logging.v2.IUpdateViewRequest|undefined, {}|undefined - ]>; + request?: protos.google.logging.v2.IUpdateViewRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.logging.v2.ILogView, + protos.google.logging.v2.IUpdateViewRequest | undefined, + {} | undefined, + ] + >; updateView( - request: protos.google.logging.v2.IUpdateViewRequest, - options: CallOptions, - callback: Callback< - protos.google.logging.v2.ILogView, - protos.google.logging.v2.IUpdateViewRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.logging.v2.IUpdateViewRequest, + options: CallOptions, + callback: Callback< + protos.google.logging.v2.ILogView, + protos.google.logging.v2.IUpdateViewRequest | null | undefined, + {} | null | undefined + >, + ): void; updateView( - request: protos.google.logging.v2.IUpdateViewRequest, - callback: Callback< - protos.google.logging.v2.ILogView, - protos.google.logging.v2.IUpdateViewRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.logging.v2.IUpdateViewRequest, + callback: Callback< + protos.google.logging.v2.ILogView, + protos.google.logging.v2.IUpdateViewRequest | null | undefined, + {} | null | undefined + >, + ): void; updateView( - request?: protos.google.logging.v2.IUpdateViewRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.logging.v2.ILogView, - protos.google.logging.v2.IUpdateViewRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.logging.v2.IUpdateViewRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.logging.v2.ILogView, - protos.google.logging.v2.IUpdateViewRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.logging.v2.ILogView, - protos.google.logging.v2.IUpdateViewRequest|undefined, {}|undefined - ]>|void { + protos.google.logging.v2.IUpdateViewRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.logging.v2.ILogView, + protos.google.logging.v2.IUpdateViewRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.logging.v2.ILogView, + protos.google.logging.v2.IUpdateViewRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateView request %j', request); - const wrappedCallback: Callback< - protos.google.logging.v2.ILogView, - protos.google.logging.v2.IUpdateViewRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.logging.v2.ILogView, + protos.google.logging.v2.IUpdateViewRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateView response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.updateView(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.logging.v2.ILogView, - protos.google.logging.v2.IUpdateViewRequest|undefined, {}|undefined - ]) => { - this._log.info('updateView response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateView(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.logging.v2.ILogView, + protos.google.logging.v2.IUpdateViewRequest | undefined, + {} | undefined, + ]) => { + this._log.info('updateView response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Deletes a view on a log bucket. - * If an `UNAVAILABLE` error is returned, this indicates that system is not in - * a state where it can delete the view. If this occurs, please try again in a - * few minutes. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The full resource name of the view to delete: - * - * "projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]" - * - * For example: - * - * `"projects/my-project/locations/global/buckets/my-bucket/views/my-view"` - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/config_service_v2.delete_view.js - * region_tag:logging_v2_generated_ConfigServiceV2_DeleteView_async - */ + /** + * Deletes a view on a log bucket. + * If an `UNAVAILABLE` error is returned, this indicates that system is not in + * a state where it can delete the view. If this occurs, please try again in a + * few minutes. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The full resource name of the view to delete: + * + * "projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]" + * + * For example: + * + * `"projects/my-project/locations/global/buckets/my-bucket/views/my-view"` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/config_service_v2.delete_view.js + * region_tag:logging_v2_generated_ConfigServiceV2_DeleteView_async + */ deleteView( - request?: protos.google.logging.v2.IDeleteViewRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.logging.v2.IDeleteViewRequest|undefined, {}|undefined - ]>; + request?: protos.google.logging.v2.IDeleteViewRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.logging.v2.IDeleteViewRequest | undefined, + {} | undefined, + ] + >; deleteView( - request: protos.google.logging.v2.IDeleteViewRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.logging.v2.IDeleteViewRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.logging.v2.IDeleteViewRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.logging.v2.IDeleteViewRequest | null | undefined, + {} | null | undefined + >, + ): void; deleteView( - request: protos.google.logging.v2.IDeleteViewRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.logging.v2.IDeleteViewRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.logging.v2.IDeleteViewRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.logging.v2.IDeleteViewRequest | null | undefined, + {} | null | undefined + >, + ): void; deleteView( - request?: protos.google.logging.v2.IDeleteViewRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.logging.v2.IDeleteViewRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.logging.v2.IDeleteViewRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.protobuf.IEmpty, - protos.google.logging.v2.IDeleteViewRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.logging.v2.IDeleteViewRequest|undefined, {}|undefined - ]>|void { + protos.google.logging.v2.IDeleteViewRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + protos.google.logging.v2.IDeleteViewRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.logging.v2.IDeleteViewRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('deleteView request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.logging.v2.IDeleteViewRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + protos.google.logging.v2.IDeleteViewRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteView response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.deleteView(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.logging.v2.IDeleteViewRequest|undefined, {}|undefined - ]) => { - this._log.info('deleteView response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteView(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.logging.v2.IDeleteViewRequest | undefined, + {} | undefined, + ]) => { + this._log.info('deleteView response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Gets a sink. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.sinkName - * Required. The resource name of the sink: - * - * "projects/[PROJECT_ID]/sinks/[SINK_ID]" - * "organizations/[ORGANIZATION_ID]/sinks/[SINK_ID]" - * "billingAccounts/[BILLING_ACCOUNT_ID]/sinks/[SINK_ID]" - * "folders/[FOLDER_ID]/sinks/[SINK_ID]" - * - * For example: - * - * `"projects/my-project/sinks/my-sink"` - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.logging.v2.LogSink|LogSink}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/config_service_v2.get_sink.js - * region_tag:logging_v2_generated_ConfigServiceV2_GetSink_async - */ + /** + * Gets a sink. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.sinkName + * Required. The resource name of the sink: + * + * "projects/[PROJECT_ID]/sinks/[SINK_ID]" + * "organizations/[ORGANIZATION_ID]/sinks/[SINK_ID]" + * "billingAccounts/[BILLING_ACCOUNT_ID]/sinks/[SINK_ID]" + * "folders/[FOLDER_ID]/sinks/[SINK_ID]" + * + * For example: + * + * `"projects/my-project/sinks/my-sink"` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.logging.v2.LogSink|LogSink}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/config_service_v2.get_sink.js + * region_tag:logging_v2_generated_ConfigServiceV2_GetSink_async + */ getSink( - request?: protos.google.logging.v2.IGetSinkRequest, - options?: CallOptions): - Promise<[ - protos.google.logging.v2.ILogSink, - protos.google.logging.v2.IGetSinkRequest|undefined, {}|undefined - ]>; + request?: protos.google.logging.v2.IGetSinkRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.logging.v2.ILogSink, + protos.google.logging.v2.IGetSinkRequest | undefined, + {} | undefined, + ] + >; getSink( - request: protos.google.logging.v2.IGetSinkRequest, - options: CallOptions, - callback: Callback< - protos.google.logging.v2.ILogSink, - protos.google.logging.v2.IGetSinkRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.logging.v2.IGetSinkRequest, + options: CallOptions, + callback: Callback< + protos.google.logging.v2.ILogSink, + protos.google.logging.v2.IGetSinkRequest | null | undefined, + {} | null | undefined + >, + ): void; getSink( - request: protos.google.logging.v2.IGetSinkRequest, - callback: Callback< - protos.google.logging.v2.ILogSink, - protos.google.logging.v2.IGetSinkRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.logging.v2.IGetSinkRequest, + callback: Callback< + protos.google.logging.v2.ILogSink, + protos.google.logging.v2.IGetSinkRequest | null | undefined, + {} | null | undefined + >, + ): void; getSink( - request?: protos.google.logging.v2.IGetSinkRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.logging.v2.ILogSink, - protos.google.logging.v2.IGetSinkRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.logging.v2.IGetSinkRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.logging.v2.ILogSink, - protos.google.logging.v2.IGetSinkRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.logging.v2.ILogSink, - protos.google.logging.v2.IGetSinkRequest|undefined, {}|undefined - ]>|void { + protos.google.logging.v2.IGetSinkRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.logging.v2.ILogSink, + protos.google.logging.v2.IGetSinkRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.logging.v2.ILogSink, + protos.google.logging.v2.IGetSinkRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'sink_name': request.sinkName ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + sink_name: request.sinkName ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getSink request %j', request); - const wrappedCallback: Callback< - protos.google.logging.v2.ILogSink, - protos.google.logging.v2.IGetSinkRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.logging.v2.ILogSink, + protos.google.logging.v2.IGetSinkRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getSink response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.getSink(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.logging.v2.ILogSink, - protos.google.logging.v2.IGetSinkRequest|undefined, {}|undefined - ]) => { - this._log.info('getSink response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getSink(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.logging.v2.ILogSink, + protos.google.logging.v2.IGetSinkRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getSink response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Creates a sink that exports specified log entries to a destination. The - * export of newly-ingested log entries begins immediately, unless the sink's - * `writer_identity` is not permitted to write to the destination. A sink can - * export log entries only from the resource owning the sink. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The resource in which to create the sink: - * - * "projects/[PROJECT_ID]" - * "organizations/[ORGANIZATION_ID]" - * "billingAccounts/[BILLING_ACCOUNT_ID]" - * "folders/[FOLDER_ID]" - * - * For examples: - * - * `"projects/my-project"` - * `"organizations/123456789"` - * @param {google.logging.v2.LogSink} request.sink - * Required. The new sink, whose `name` parameter is a sink identifier that - * is not already in use. - * @param {boolean} [request.uniqueWriterIdentity] - * Optional. Determines the kind of IAM identity returned as `writer_identity` - * in the new sink. If this value is omitted or set to false, and if the - * sink's parent is a project, then the value returned as `writer_identity` is - * the same group or service account used by Cloud Logging before the addition - * of writer identities to this API. The sink's destination must be in the - * same project as the sink itself. - * - * If this field is set to true, or if the sink is owned by a non-project - * resource such as an organization, then the value of `writer_identity` will - * be a unique service account used only for exports from the new sink. For - * more information, see `writer_identity` in {@link protos.google.logging.v2.LogSink|LogSink}. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.logging.v2.LogSink|LogSink}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/config_service_v2.create_sink.js - * region_tag:logging_v2_generated_ConfigServiceV2_CreateSink_async - */ + /** + * Creates a sink that exports specified log entries to a destination. The + * export of newly-ingested log entries begins immediately, unless the sink's + * `writer_identity` is not permitted to write to the destination. A sink can + * export log entries only from the resource owning the sink. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The resource in which to create the sink: + * + * "projects/[PROJECT_ID]" + * "organizations/[ORGANIZATION_ID]" + * "billingAccounts/[BILLING_ACCOUNT_ID]" + * "folders/[FOLDER_ID]" + * + * For examples: + * + * `"projects/my-project"` + * `"organizations/123456789"` + * @param {google.logging.v2.LogSink} request.sink + * Required. The new sink, whose `name` parameter is a sink identifier that + * is not already in use. + * @param {boolean} [request.uniqueWriterIdentity] + * Optional. Determines the kind of IAM identity returned as `writer_identity` + * in the new sink. If this value is omitted or set to false, and if the + * sink's parent is a project, then the value returned as `writer_identity` is + * the same group or service account used by Cloud Logging before the addition + * of writer identities to this API. The sink's destination must be in the + * same project as the sink itself. + * + * If this field is set to true, or if the sink is owned by a non-project + * resource such as an organization, then the value of `writer_identity` will + * be a unique service account used only for exports from the new sink. For + * more information, see `writer_identity` in {@link protos.google.logging.v2.LogSink|LogSink}. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.logging.v2.LogSink|LogSink}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/config_service_v2.create_sink.js + * region_tag:logging_v2_generated_ConfigServiceV2_CreateSink_async + */ createSink( - request?: protos.google.logging.v2.ICreateSinkRequest, - options?: CallOptions): - Promise<[ - protos.google.logging.v2.ILogSink, - protos.google.logging.v2.ICreateSinkRequest|undefined, {}|undefined - ]>; + request?: protos.google.logging.v2.ICreateSinkRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.logging.v2.ILogSink, + protos.google.logging.v2.ICreateSinkRequest | undefined, + {} | undefined, + ] + >; createSink( - request: protos.google.logging.v2.ICreateSinkRequest, - options: CallOptions, - callback: Callback< - protos.google.logging.v2.ILogSink, - protos.google.logging.v2.ICreateSinkRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.logging.v2.ICreateSinkRequest, + options: CallOptions, + callback: Callback< + protos.google.logging.v2.ILogSink, + protos.google.logging.v2.ICreateSinkRequest | null | undefined, + {} | null | undefined + >, + ): void; createSink( - request: protos.google.logging.v2.ICreateSinkRequest, - callback: Callback< - protos.google.logging.v2.ILogSink, - protos.google.logging.v2.ICreateSinkRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.logging.v2.ICreateSinkRequest, + callback: Callback< + protos.google.logging.v2.ILogSink, + protos.google.logging.v2.ICreateSinkRequest | null | undefined, + {} | null | undefined + >, + ): void; createSink( - request?: protos.google.logging.v2.ICreateSinkRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.logging.v2.ICreateSinkRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.logging.v2.ILogSink, - protos.google.logging.v2.ICreateSinkRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.logging.v2.ILogSink, - protos.google.logging.v2.ICreateSinkRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.logging.v2.ILogSink, - protos.google.logging.v2.ICreateSinkRequest|undefined, {}|undefined - ]>|void { + protos.google.logging.v2.ICreateSinkRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.logging.v2.ILogSink, + protos.google.logging.v2.ICreateSinkRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.logging.v2.ILogSink, + protos.google.logging.v2.ICreateSinkRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('createSink request %j', request); - const wrappedCallback: Callback< - protos.google.logging.v2.ILogSink, - protos.google.logging.v2.ICreateSinkRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.logging.v2.ILogSink, + protos.google.logging.v2.ICreateSinkRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createSink response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.createSink(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.logging.v2.ILogSink, - protos.google.logging.v2.ICreateSinkRequest|undefined, {}|undefined - ]) => { - this._log.info('createSink response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createSink(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.logging.v2.ILogSink, + protos.google.logging.v2.ICreateSinkRequest | undefined, + {} | undefined, + ]) => { + this._log.info('createSink response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Updates a sink. This method replaces the following fields in the existing - * sink with values from the new sink: `destination`, and `filter`. - * - * The updated sink might also have a new `writer_identity`; see the - * `unique_writer_identity` field. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.sinkName - * Required. The full resource name of the sink to update, including the parent - * resource and the sink identifier: - * - * "projects/[PROJECT_ID]/sinks/[SINK_ID]" - * "organizations/[ORGANIZATION_ID]/sinks/[SINK_ID]" - * "billingAccounts/[BILLING_ACCOUNT_ID]/sinks/[SINK_ID]" - * "folders/[FOLDER_ID]/sinks/[SINK_ID]" - * - * For example: - * - * `"projects/my-project/sinks/my-sink"` - * @param {google.logging.v2.LogSink} request.sink - * Required. The updated sink, whose name is the same identifier that appears as part - * of `sink_name`. - * @param {boolean} [request.uniqueWriterIdentity] - * Optional. See {@link protos.google.logging.v2.ConfigServiceV2.CreateSink|sinks.create} - * for a description of this field. When updating a sink, the effect of this - * field on the value of `writer_identity` in the updated sink depends on both - * the old and new values of this field: - * - * + If the old and new values of this field are both false or both true, - * then there is no change to the sink's `writer_identity`. - * + If the old value is false and the new value is true, then - * `writer_identity` is changed to a unique service account. - * + It is an error if the old value is true and the new value is - * set to false or defaulted to false. - * @param {google.protobuf.FieldMask} [request.updateMask] - * Optional. Field mask that specifies the fields in `sink` that need - * an update. A sink field will be overwritten if, and only if, it is - * in the update mask. `name` and output only fields cannot be updated. - * - * An empty `updateMask` is temporarily treated as using the following mask - * for backwards compatibility purposes: - * - * `destination,filter,includeChildren` - * - * At some point in the future, behavior will be removed and specifying an - * empty `updateMask` will be an error. - * - * For a detailed `FieldMask` definition, see - * https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#google.protobuf.FieldMask - * - * For example: `updateMask=filter` - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.logging.v2.LogSink|LogSink}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/config_service_v2.update_sink.js - * region_tag:logging_v2_generated_ConfigServiceV2_UpdateSink_async - */ + /** + * Updates a sink. This method replaces the following fields in the existing + * sink with values from the new sink: `destination`, and `filter`. + * + * The updated sink might also have a new `writer_identity`; see the + * `unique_writer_identity` field. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.sinkName + * Required. The full resource name of the sink to update, including the parent + * resource and the sink identifier: + * + * "projects/[PROJECT_ID]/sinks/[SINK_ID]" + * "organizations/[ORGANIZATION_ID]/sinks/[SINK_ID]" + * "billingAccounts/[BILLING_ACCOUNT_ID]/sinks/[SINK_ID]" + * "folders/[FOLDER_ID]/sinks/[SINK_ID]" + * + * For example: + * + * `"projects/my-project/sinks/my-sink"` + * @param {google.logging.v2.LogSink} request.sink + * Required. The updated sink, whose name is the same identifier that appears as part + * of `sink_name`. + * @param {boolean} [request.uniqueWriterIdentity] + * Optional. See {@link protos.google.logging.v2.ConfigServiceV2.CreateSink|sinks.create} + * for a description of this field. When updating a sink, the effect of this + * field on the value of `writer_identity` in the updated sink depends on both + * the old and new values of this field: + * + * + If the old and new values of this field are both false or both true, + * then there is no change to the sink's `writer_identity`. + * + If the old value is false and the new value is true, then + * `writer_identity` is changed to a unique service account. + * + It is an error if the old value is true and the new value is + * set to false or defaulted to false. + * @param {google.protobuf.FieldMask} [request.updateMask] + * Optional. Field mask that specifies the fields in `sink` that need + * an update. A sink field will be overwritten if, and only if, it is + * in the update mask. `name` and output only fields cannot be updated. + * + * An empty `updateMask` is temporarily treated as using the following mask + * for backwards compatibility purposes: + * + * `destination,filter,includeChildren` + * + * At some point in the future, behavior will be removed and specifying an + * empty `updateMask` will be an error. + * + * For a detailed `FieldMask` definition, see + * https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#google.protobuf.FieldMask + * + * For example: `updateMask=filter` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.logging.v2.LogSink|LogSink}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/config_service_v2.update_sink.js + * region_tag:logging_v2_generated_ConfigServiceV2_UpdateSink_async + */ updateSink( - request?: protos.google.logging.v2.IUpdateSinkRequest, - options?: CallOptions): - Promise<[ - protos.google.logging.v2.ILogSink, - protos.google.logging.v2.IUpdateSinkRequest|undefined, {}|undefined - ]>; + request?: protos.google.logging.v2.IUpdateSinkRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.logging.v2.ILogSink, + protos.google.logging.v2.IUpdateSinkRequest | undefined, + {} | undefined, + ] + >; updateSink( - request: protos.google.logging.v2.IUpdateSinkRequest, - options: CallOptions, - callback: Callback< - protos.google.logging.v2.ILogSink, - protos.google.logging.v2.IUpdateSinkRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.logging.v2.IUpdateSinkRequest, + options: CallOptions, + callback: Callback< + protos.google.logging.v2.ILogSink, + protos.google.logging.v2.IUpdateSinkRequest | null | undefined, + {} | null | undefined + >, + ): void; updateSink( - request: protos.google.logging.v2.IUpdateSinkRequest, - callback: Callback< - protos.google.logging.v2.ILogSink, - protos.google.logging.v2.IUpdateSinkRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.logging.v2.IUpdateSinkRequest, + callback: Callback< + protos.google.logging.v2.ILogSink, + protos.google.logging.v2.IUpdateSinkRequest | null | undefined, + {} | null | undefined + >, + ): void; updateSink( - request?: protos.google.logging.v2.IUpdateSinkRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.logging.v2.ILogSink, - protos.google.logging.v2.IUpdateSinkRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.logging.v2.IUpdateSinkRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.logging.v2.ILogSink, - protos.google.logging.v2.IUpdateSinkRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.logging.v2.ILogSink, - protos.google.logging.v2.IUpdateSinkRequest|undefined, {}|undefined - ]>|void { + protos.google.logging.v2.IUpdateSinkRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.logging.v2.ILogSink, + protos.google.logging.v2.IUpdateSinkRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.logging.v2.ILogSink, + protos.google.logging.v2.IUpdateSinkRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'sink_name': request.sinkName ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + sink_name: request.sinkName ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateSink request %j', request); - const wrappedCallback: Callback< - protos.google.logging.v2.ILogSink, - protos.google.logging.v2.IUpdateSinkRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.logging.v2.ILogSink, + protos.google.logging.v2.IUpdateSinkRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateSink response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.updateSink(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.logging.v2.ILogSink, - protos.google.logging.v2.IUpdateSinkRequest|undefined, {}|undefined - ]) => { - this._log.info('updateSink response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateSink(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.logging.v2.ILogSink, + protos.google.logging.v2.IUpdateSinkRequest | undefined, + {} | undefined, + ]) => { + this._log.info('updateSink response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Deletes a sink. If the sink has a unique `writer_identity`, then that - * service account is also deleted. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.sinkName - * Required. The full resource name of the sink to delete, including the parent - * resource and the sink identifier: - * - * "projects/[PROJECT_ID]/sinks/[SINK_ID]" - * "organizations/[ORGANIZATION_ID]/sinks/[SINK_ID]" - * "billingAccounts/[BILLING_ACCOUNT_ID]/sinks/[SINK_ID]" - * "folders/[FOLDER_ID]/sinks/[SINK_ID]" - * - * For example: - * - * `"projects/my-project/sinks/my-sink"` - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/config_service_v2.delete_sink.js - * region_tag:logging_v2_generated_ConfigServiceV2_DeleteSink_async - */ + /** + * Deletes a sink. If the sink has a unique `writer_identity`, then that + * service account is also deleted. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.sinkName + * Required. The full resource name of the sink to delete, including the parent + * resource and the sink identifier: + * + * "projects/[PROJECT_ID]/sinks/[SINK_ID]" + * "organizations/[ORGANIZATION_ID]/sinks/[SINK_ID]" + * "billingAccounts/[BILLING_ACCOUNT_ID]/sinks/[SINK_ID]" + * "folders/[FOLDER_ID]/sinks/[SINK_ID]" + * + * For example: + * + * `"projects/my-project/sinks/my-sink"` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/config_service_v2.delete_sink.js + * region_tag:logging_v2_generated_ConfigServiceV2_DeleteSink_async + */ deleteSink( - request?: protos.google.logging.v2.IDeleteSinkRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.logging.v2.IDeleteSinkRequest|undefined, {}|undefined - ]>; + request?: protos.google.logging.v2.IDeleteSinkRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.logging.v2.IDeleteSinkRequest | undefined, + {} | undefined, + ] + >; deleteSink( - request: protos.google.logging.v2.IDeleteSinkRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.logging.v2.IDeleteSinkRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.logging.v2.IDeleteSinkRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.logging.v2.IDeleteSinkRequest | null | undefined, + {} | null | undefined + >, + ): void; deleteSink( - request: protos.google.logging.v2.IDeleteSinkRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.logging.v2.IDeleteSinkRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.logging.v2.IDeleteSinkRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.logging.v2.IDeleteSinkRequest | null | undefined, + {} | null | undefined + >, + ): void; deleteSink( - request?: protos.google.logging.v2.IDeleteSinkRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.logging.v2.IDeleteSinkRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.logging.v2.IDeleteSinkRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.protobuf.IEmpty, - protos.google.logging.v2.IDeleteSinkRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.logging.v2.IDeleteSinkRequest|undefined, {}|undefined - ]>|void { + protos.google.logging.v2.IDeleteSinkRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + protos.google.logging.v2.IDeleteSinkRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.logging.v2.IDeleteSinkRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'sink_name': request.sinkName ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + sink_name: request.sinkName ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('deleteSink request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.logging.v2.IDeleteSinkRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + protos.google.logging.v2.IDeleteSinkRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteSink response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.deleteSink(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.logging.v2.IDeleteSinkRequest|undefined, {}|undefined - ]) => { - this._log.info('deleteSink response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteSink(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.logging.v2.IDeleteSinkRequest | undefined, + {} | undefined, + ]) => { + this._log.info('deleteSink response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Gets the description of an exclusion in the _Default sink. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The resource name of an existing exclusion: - * - * "projects/[PROJECT_ID]/exclusions/[EXCLUSION_ID]" - * "organizations/[ORGANIZATION_ID]/exclusions/[EXCLUSION_ID]" - * "billingAccounts/[BILLING_ACCOUNT_ID]/exclusions/[EXCLUSION_ID]" - * "folders/[FOLDER_ID]/exclusions/[EXCLUSION_ID]" - * - * For example: - * - * `"projects/my-project/exclusions/my-exclusion"` - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.logging.v2.LogExclusion|LogExclusion}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/config_service_v2.get_exclusion.js - * region_tag:logging_v2_generated_ConfigServiceV2_GetExclusion_async - */ + /** + * Gets the description of an exclusion in the _Default sink. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The resource name of an existing exclusion: + * + * "projects/[PROJECT_ID]/exclusions/[EXCLUSION_ID]" + * "organizations/[ORGANIZATION_ID]/exclusions/[EXCLUSION_ID]" + * "billingAccounts/[BILLING_ACCOUNT_ID]/exclusions/[EXCLUSION_ID]" + * "folders/[FOLDER_ID]/exclusions/[EXCLUSION_ID]" + * + * For example: + * + * `"projects/my-project/exclusions/my-exclusion"` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.logging.v2.LogExclusion|LogExclusion}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/config_service_v2.get_exclusion.js + * region_tag:logging_v2_generated_ConfigServiceV2_GetExclusion_async + */ getExclusion( - request?: protos.google.logging.v2.IGetExclusionRequest, - options?: CallOptions): - Promise<[ - protos.google.logging.v2.ILogExclusion, - protos.google.logging.v2.IGetExclusionRequest|undefined, {}|undefined - ]>; + request?: protos.google.logging.v2.IGetExclusionRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.logging.v2.ILogExclusion, + protos.google.logging.v2.IGetExclusionRequest | undefined, + {} | undefined, + ] + >; getExclusion( - request: protos.google.logging.v2.IGetExclusionRequest, - options: CallOptions, - callback: Callback< - protos.google.logging.v2.ILogExclusion, - protos.google.logging.v2.IGetExclusionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.logging.v2.IGetExclusionRequest, + options: CallOptions, + callback: Callback< + protos.google.logging.v2.ILogExclusion, + protos.google.logging.v2.IGetExclusionRequest | null | undefined, + {} | null | undefined + >, + ): void; getExclusion( - request: protos.google.logging.v2.IGetExclusionRequest, - callback: Callback< - protos.google.logging.v2.ILogExclusion, - protos.google.logging.v2.IGetExclusionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.logging.v2.IGetExclusionRequest, + callback: Callback< + protos.google.logging.v2.ILogExclusion, + protos.google.logging.v2.IGetExclusionRequest | null | undefined, + {} | null | undefined + >, + ): void; getExclusion( - request?: protos.google.logging.v2.IGetExclusionRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.logging.v2.ILogExclusion, - protos.google.logging.v2.IGetExclusionRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.logging.v2.IGetExclusionRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.logging.v2.ILogExclusion, - protos.google.logging.v2.IGetExclusionRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.logging.v2.ILogExclusion, - protos.google.logging.v2.IGetExclusionRequest|undefined, {}|undefined - ]>|void { + protos.google.logging.v2.IGetExclusionRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.logging.v2.ILogExclusion, + protos.google.logging.v2.IGetExclusionRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.logging.v2.ILogExclusion, + protos.google.logging.v2.IGetExclusionRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getExclusion request %j', request); - const wrappedCallback: Callback< - protos.google.logging.v2.ILogExclusion, - protos.google.logging.v2.IGetExclusionRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.logging.v2.ILogExclusion, + protos.google.logging.v2.IGetExclusionRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getExclusion response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.getExclusion(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.logging.v2.ILogExclusion, - protos.google.logging.v2.IGetExclusionRequest|undefined, {}|undefined - ]) => { - this._log.info('getExclusion response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getExclusion(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.logging.v2.ILogExclusion, + protos.google.logging.v2.IGetExclusionRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getExclusion response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Creates a new exclusion in the _Default sink in a specified parent - * resource. Only log entries belonging to that resource can be excluded. You - * can have up to 10 exclusions in a resource. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent resource in which to create the exclusion: - * - * "projects/[PROJECT_ID]" - * "organizations/[ORGANIZATION_ID]" - * "billingAccounts/[BILLING_ACCOUNT_ID]" - * "folders/[FOLDER_ID]" - * - * For examples: - * - * `"projects/my-logging-project"` - * `"organizations/123456789"` - * @param {google.logging.v2.LogExclusion} request.exclusion - * Required. The new exclusion, whose `name` parameter is an exclusion name - * that is not already used in the parent resource. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.logging.v2.LogExclusion|LogExclusion}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/config_service_v2.create_exclusion.js - * region_tag:logging_v2_generated_ConfigServiceV2_CreateExclusion_async - */ + /** + * Creates a new exclusion in the _Default sink in a specified parent + * resource. Only log entries belonging to that resource can be excluded. You + * can have up to 10 exclusions in a resource. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource in which to create the exclusion: + * + * "projects/[PROJECT_ID]" + * "organizations/[ORGANIZATION_ID]" + * "billingAccounts/[BILLING_ACCOUNT_ID]" + * "folders/[FOLDER_ID]" + * + * For examples: + * + * `"projects/my-logging-project"` + * `"organizations/123456789"` + * @param {google.logging.v2.LogExclusion} request.exclusion + * Required. The new exclusion, whose `name` parameter is an exclusion name + * that is not already used in the parent resource. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.logging.v2.LogExclusion|LogExclusion}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/config_service_v2.create_exclusion.js + * region_tag:logging_v2_generated_ConfigServiceV2_CreateExclusion_async + */ createExclusion( - request?: protos.google.logging.v2.ICreateExclusionRequest, - options?: CallOptions): - Promise<[ - protos.google.logging.v2.ILogExclusion, - protos.google.logging.v2.ICreateExclusionRequest|undefined, {}|undefined - ]>; + request?: protos.google.logging.v2.ICreateExclusionRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.logging.v2.ILogExclusion, + protos.google.logging.v2.ICreateExclusionRequest | undefined, + {} | undefined, + ] + >; createExclusion( - request: protos.google.logging.v2.ICreateExclusionRequest, - options: CallOptions, - callback: Callback< - protos.google.logging.v2.ILogExclusion, - protos.google.logging.v2.ICreateExclusionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.logging.v2.ICreateExclusionRequest, + options: CallOptions, + callback: Callback< + protos.google.logging.v2.ILogExclusion, + protos.google.logging.v2.ICreateExclusionRequest | null | undefined, + {} | null | undefined + >, + ): void; createExclusion( - request: protos.google.logging.v2.ICreateExclusionRequest, - callback: Callback< - protos.google.logging.v2.ILogExclusion, - protos.google.logging.v2.ICreateExclusionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.logging.v2.ICreateExclusionRequest, + callback: Callback< + protos.google.logging.v2.ILogExclusion, + protos.google.logging.v2.ICreateExclusionRequest | null | undefined, + {} | null | undefined + >, + ): void; createExclusion( - request?: protos.google.logging.v2.ICreateExclusionRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.logging.v2.ILogExclusion, - protos.google.logging.v2.ICreateExclusionRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.logging.v2.ICreateExclusionRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.logging.v2.ILogExclusion, - protos.google.logging.v2.ICreateExclusionRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.logging.v2.ILogExclusion, - protos.google.logging.v2.ICreateExclusionRequest|undefined, {}|undefined - ]>|void { + protos.google.logging.v2.ICreateExclusionRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.logging.v2.ILogExclusion, + protos.google.logging.v2.ICreateExclusionRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.logging.v2.ILogExclusion, + protos.google.logging.v2.ICreateExclusionRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('createExclusion request %j', request); - const wrappedCallback: Callback< - protos.google.logging.v2.ILogExclusion, - protos.google.logging.v2.ICreateExclusionRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.logging.v2.ILogExclusion, + protos.google.logging.v2.ICreateExclusionRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createExclusion response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.createExclusion(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.logging.v2.ILogExclusion, - protos.google.logging.v2.ICreateExclusionRequest|undefined, {}|undefined - ]) => { - this._log.info('createExclusion response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createExclusion(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.logging.v2.ILogExclusion, + protos.google.logging.v2.ICreateExclusionRequest | undefined, + {} | undefined, + ]) => { + this._log.info('createExclusion response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Changes one or more properties of an existing exclusion in the _Default - * sink. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The resource name of the exclusion to update: - * - * "projects/[PROJECT_ID]/exclusions/[EXCLUSION_ID]" - * "organizations/[ORGANIZATION_ID]/exclusions/[EXCLUSION_ID]" - * "billingAccounts/[BILLING_ACCOUNT_ID]/exclusions/[EXCLUSION_ID]" - * "folders/[FOLDER_ID]/exclusions/[EXCLUSION_ID]" - * - * For example: - * - * `"projects/my-project/exclusions/my-exclusion"` - * @param {google.logging.v2.LogExclusion} request.exclusion - * Required. New values for the existing exclusion. Only the fields specified in - * `update_mask` are relevant. - * @param {google.protobuf.FieldMask} request.updateMask - * Required. A non-empty list of fields to change in the existing exclusion. New values - * for the fields are taken from the corresponding fields in the - * {@link protos.google.logging.v2.LogExclusion|LogExclusion} included in this request. Fields not mentioned in - * `update_mask` are not changed and are ignored in the request. - * - * For example, to change the filter and description of an exclusion, - * specify an `update_mask` of `"filter,description"`. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.logging.v2.LogExclusion|LogExclusion}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/config_service_v2.update_exclusion.js - * region_tag:logging_v2_generated_ConfigServiceV2_UpdateExclusion_async - */ + /** + * Changes one or more properties of an existing exclusion in the _Default + * sink. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The resource name of the exclusion to update: + * + * "projects/[PROJECT_ID]/exclusions/[EXCLUSION_ID]" + * "organizations/[ORGANIZATION_ID]/exclusions/[EXCLUSION_ID]" + * "billingAccounts/[BILLING_ACCOUNT_ID]/exclusions/[EXCLUSION_ID]" + * "folders/[FOLDER_ID]/exclusions/[EXCLUSION_ID]" + * + * For example: + * + * `"projects/my-project/exclusions/my-exclusion"` + * @param {google.logging.v2.LogExclusion} request.exclusion + * Required. New values for the existing exclusion. Only the fields specified in + * `update_mask` are relevant. + * @param {google.protobuf.FieldMask} request.updateMask + * Required. A non-empty list of fields to change in the existing exclusion. New values + * for the fields are taken from the corresponding fields in the + * {@link protos.google.logging.v2.LogExclusion|LogExclusion} included in this request. Fields not mentioned in + * `update_mask` are not changed and are ignored in the request. + * + * For example, to change the filter and description of an exclusion, + * specify an `update_mask` of `"filter,description"`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.logging.v2.LogExclusion|LogExclusion}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/config_service_v2.update_exclusion.js + * region_tag:logging_v2_generated_ConfigServiceV2_UpdateExclusion_async + */ updateExclusion( - request?: protos.google.logging.v2.IUpdateExclusionRequest, - options?: CallOptions): - Promise<[ - protos.google.logging.v2.ILogExclusion, - protos.google.logging.v2.IUpdateExclusionRequest|undefined, {}|undefined - ]>; + request?: protos.google.logging.v2.IUpdateExclusionRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.logging.v2.ILogExclusion, + protos.google.logging.v2.IUpdateExclusionRequest | undefined, + {} | undefined, + ] + >; updateExclusion( - request: protos.google.logging.v2.IUpdateExclusionRequest, - options: CallOptions, - callback: Callback< - protos.google.logging.v2.ILogExclusion, - protos.google.logging.v2.IUpdateExclusionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.logging.v2.IUpdateExclusionRequest, + options: CallOptions, + callback: Callback< + protos.google.logging.v2.ILogExclusion, + protos.google.logging.v2.IUpdateExclusionRequest | null | undefined, + {} | null | undefined + >, + ): void; updateExclusion( - request: protos.google.logging.v2.IUpdateExclusionRequest, - callback: Callback< - protos.google.logging.v2.ILogExclusion, - protos.google.logging.v2.IUpdateExclusionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.logging.v2.IUpdateExclusionRequest, + callback: Callback< + protos.google.logging.v2.ILogExclusion, + protos.google.logging.v2.IUpdateExclusionRequest | null | undefined, + {} | null | undefined + >, + ): void; updateExclusion( - request?: protos.google.logging.v2.IUpdateExclusionRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.logging.v2.ILogExclusion, - protos.google.logging.v2.IUpdateExclusionRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.logging.v2.IUpdateExclusionRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.logging.v2.ILogExclusion, - protos.google.logging.v2.IUpdateExclusionRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.logging.v2.ILogExclusion, - protos.google.logging.v2.IUpdateExclusionRequest|undefined, {}|undefined - ]>|void { + protos.google.logging.v2.IUpdateExclusionRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.logging.v2.ILogExclusion, + protos.google.logging.v2.IUpdateExclusionRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.logging.v2.ILogExclusion, + protos.google.logging.v2.IUpdateExclusionRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateExclusion request %j', request); - const wrappedCallback: Callback< - protos.google.logging.v2.ILogExclusion, - protos.google.logging.v2.IUpdateExclusionRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.logging.v2.ILogExclusion, + protos.google.logging.v2.IUpdateExclusionRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateExclusion response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.updateExclusion(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.logging.v2.ILogExclusion, - protos.google.logging.v2.IUpdateExclusionRequest|undefined, {}|undefined - ]) => { - this._log.info('updateExclusion response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateExclusion(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.logging.v2.ILogExclusion, + protos.google.logging.v2.IUpdateExclusionRequest | undefined, + {} | undefined, + ]) => { + this._log.info('updateExclusion response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Deletes an exclusion in the _Default sink. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The resource name of an existing exclusion to delete: - * - * "projects/[PROJECT_ID]/exclusions/[EXCLUSION_ID]" - * "organizations/[ORGANIZATION_ID]/exclusions/[EXCLUSION_ID]" - * "billingAccounts/[BILLING_ACCOUNT_ID]/exclusions/[EXCLUSION_ID]" - * "folders/[FOLDER_ID]/exclusions/[EXCLUSION_ID]" - * - * For example: - * - * `"projects/my-project/exclusions/my-exclusion"` - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/config_service_v2.delete_exclusion.js - * region_tag:logging_v2_generated_ConfigServiceV2_DeleteExclusion_async - */ + /** + * Deletes an exclusion in the _Default sink. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The resource name of an existing exclusion to delete: + * + * "projects/[PROJECT_ID]/exclusions/[EXCLUSION_ID]" + * "organizations/[ORGANIZATION_ID]/exclusions/[EXCLUSION_ID]" + * "billingAccounts/[BILLING_ACCOUNT_ID]/exclusions/[EXCLUSION_ID]" + * "folders/[FOLDER_ID]/exclusions/[EXCLUSION_ID]" + * + * For example: + * + * `"projects/my-project/exclusions/my-exclusion"` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/config_service_v2.delete_exclusion.js + * region_tag:logging_v2_generated_ConfigServiceV2_DeleteExclusion_async + */ deleteExclusion( - request?: protos.google.logging.v2.IDeleteExclusionRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.logging.v2.IDeleteExclusionRequest|undefined, {}|undefined - ]>; + request?: protos.google.logging.v2.IDeleteExclusionRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.logging.v2.IDeleteExclusionRequest | undefined, + {} | undefined, + ] + >; deleteExclusion( - request: protos.google.logging.v2.IDeleteExclusionRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.logging.v2.IDeleteExclusionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.logging.v2.IDeleteExclusionRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.logging.v2.IDeleteExclusionRequest | null | undefined, + {} | null | undefined + >, + ): void; deleteExclusion( - request: protos.google.logging.v2.IDeleteExclusionRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.logging.v2.IDeleteExclusionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.logging.v2.IDeleteExclusionRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.logging.v2.IDeleteExclusionRequest | null | undefined, + {} | null | undefined + >, + ): void; deleteExclusion( - request?: protos.google.logging.v2.IDeleteExclusionRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.protobuf.IEmpty, - protos.google.logging.v2.IDeleteExclusionRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.logging.v2.IDeleteExclusionRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.logging.v2.IDeleteExclusionRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.logging.v2.IDeleteExclusionRequest|undefined, {}|undefined - ]>|void { + protos.google.logging.v2.IDeleteExclusionRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + protos.google.logging.v2.IDeleteExclusionRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.logging.v2.IDeleteExclusionRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('deleteExclusion request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.logging.v2.IDeleteExclusionRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + protos.google.logging.v2.IDeleteExclusionRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteExclusion response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.deleteExclusion(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.logging.v2.IDeleteExclusionRequest|undefined, {}|undefined - ]) => { - this._log.info('deleteExclusion response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteExclusion(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.logging.v2.IDeleteExclusionRequest | undefined, + {} | undefined, + ]) => { + this._log.info('deleteExclusion response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Gets the Logging CMEK settings for the given resource. - * - * Note: CMEK for the Log Router can be configured for Google Cloud projects, - * folders, organizations and billing accounts. Once configured for an - * organization, it applies to all projects and folders in the Google Cloud - * organization. - * - * See [Enabling CMEK for Log - * Router](https://cloud.google.com/logging/docs/routing/managed-encryption) - * for more information. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The resource for which to retrieve CMEK settings. - * - * "projects/[PROJECT_ID]/cmekSettings" - * "organizations/[ORGANIZATION_ID]/cmekSettings" - * "billingAccounts/[BILLING_ACCOUNT_ID]/cmekSettings" - * "folders/[FOLDER_ID]/cmekSettings" - * - * For example: - * - * `"organizations/12345/cmekSettings"` - * - * Note: CMEK for the Log Router can be configured for Google Cloud projects, - * folders, organizations and billing accounts. Once configured for an - * organization, it applies to all projects and folders in the Google Cloud - * organization. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.logging.v2.CmekSettings|CmekSettings}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/config_service_v2.get_cmek_settings.js - * region_tag:logging_v2_generated_ConfigServiceV2_GetCmekSettings_async - */ + /** + * Gets the Logging CMEK settings for the given resource. + * + * Note: CMEK for the Log Router can be configured for Google Cloud projects, + * folders, organizations and billing accounts. Once configured for an + * organization, it applies to all projects and folders in the Google Cloud + * organization. + * + * See [Enabling CMEK for Log + * Router](https://cloud.google.com/logging/docs/routing/managed-encryption) + * for more information. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The resource for which to retrieve CMEK settings. + * + * "projects/[PROJECT_ID]/cmekSettings" + * "organizations/[ORGANIZATION_ID]/cmekSettings" + * "billingAccounts/[BILLING_ACCOUNT_ID]/cmekSettings" + * "folders/[FOLDER_ID]/cmekSettings" + * + * For example: + * + * `"organizations/12345/cmekSettings"` + * + * Note: CMEK for the Log Router can be configured for Google Cloud projects, + * folders, organizations and billing accounts. Once configured for an + * organization, it applies to all projects and folders in the Google Cloud + * organization. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.logging.v2.CmekSettings|CmekSettings}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/config_service_v2.get_cmek_settings.js + * region_tag:logging_v2_generated_ConfigServiceV2_GetCmekSettings_async + */ getCmekSettings( - request?: protos.google.logging.v2.IGetCmekSettingsRequest, - options?: CallOptions): - Promise<[ - protos.google.logging.v2.ICmekSettings, - protos.google.logging.v2.IGetCmekSettingsRequest|undefined, {}|undefined - ]>; + request?: protos.google.logging.v2.IGetCmekSettingsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.logging.v2.ICmekSettings, + protos.google.logging.v2.IGetCmekSettingsRequest | undefined, + {} | undefined, + ] + >; getCmekSettings( - request: protos.google.logging.v2.IGetCmekSettingsRequest, - options: CallOptions, - callback: Callback< - protos.google.logging.v2.ICmekSettings, - protos.google.logging.v2.IGetCmekSettingsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.logging.v2.IGetCmekSettingsRequest, + options: CallOptions, + callback: Callback< + protos.google.logging.v2.ICmekSettings, + protos.google.logging.v2.IGetCmekSettingsRequest | null | undefined, + {} | null | undefined + >, + ): void; getCmekSettings( - request: protos.google.logging.v2.IGetCmekSettingsRequest, - callback: Callback< - protos.google.logging.v2.ICmekSettings, - protos.google.logging.v2.IGetCmekSettingsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.logging.v2.IGetCmekSettingsRequest, + callback: Callback< + protos.google.logging.v2.ICmekSettings, + protos.google.logging.v2.IGetCmekSettingsRequest | null | undefined, + {} | null | undefined + >, + ): void; getCmekSettings( - request?: protos.google.logging.v2.IGetCmekSettingsRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.logging.v2.IGetCmekSettingsRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.logging.v2.ICmekSettings, - protos.google.logging.v2.IGetCmekSettingsRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.logging.v2.ICmekSettings, - protos.google.logging.v2.IGetCmekSettingsRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.logging.v2.ICmekSettings, - protos.google.logging.v2.IGetCmekSettingsRequest|undefined, {}|undefined - ]>|void { + protos.google.logging.v2.IGetCmekSettingsRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.logging.v2.ICmekSettings, + protos.google.logging.v2.IGetCmekSettingsRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.logging.v2.ICmekSettings, + protos.google.logging.v2.IGetCmekSettingsRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getCmekSettings request %j', request); - const wrappedCallback: Callback< - protos.google.logging.v2.ICmekSettings, - protos.google.logging.v2.IGetCmekSettingsRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.logging.v2.ICmekSettings, + protos.google.logging.v2.IGetCmekSettingsRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getCmekSettings response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.getCmekSettings(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.logging.v2.ICmekSettings, - protos.google.logging.v2.IGetCmekSettingsRequest|undefined, {}|undefined - ]) => { - this._log.info('getCmekSettings response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getCmekSettings(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.logging.v2.ICmekSettings, + protos.google.logging.v2.IGetCmekSettingsRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getCmekSettings response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Updates the Log Router CMEK settings for the given resource. - * - * Note: CMEK for the Log Router can currently only be configured for Google - * Cloud organizations. Once configured, it applies to all projects and - * folders in the Google Cloud organization. - * - * {@link protos.google.logging.v2.ConfigServiceV2.UpdateCmekSettings|UpdateCmekSettings} - * will fail if 1) `kms_key_name` is invalid, or 2) the associated service - * account does not have the required - * `roles/cloudkms.cryptoKeyEncrypterDecrypter` role assigned for the key, or - * 3) access to the key is disabled. - * - * See [Enabling CMEK for Log - * Router](https://cloud.google.com/logging/docs/routing/managed-encryption) - * for more information. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The resource name for the CMEK settings to update. - * - * "projects/[PROJECT_ID]/cmekSettings" - * "organizations/[ORGANIZATION_ID]/cmekSettings" - * "billingAccounts/[BILLING_ACCOUNT_ID]/cmekSettings" - * "folders/[FOLDER_ID]/cmekSettings" - * - * For example: - * - * `"organizations/12345/cmekSettings"` - * - * Note: CMEK for the Log Router can currently only be configured for Google - * Cloud organizations. Once configured, it applies to all projects and - * folders in the Google Cloud organization. - * @param {google.logging.v2.CmekSettings} request.cmekSettings - * Required. The CMEK settings to update. - * - * See [Enabling CMEK for Log - * Router](https://cloud.google.com/logging/docs/routing/managed-encryption) - * for more information. - * @param {google.protobuf.FieldMask} [request.updateMask] - * Optional. Field mask identifying which fields from `cmek_settings` should - * be updated. A field will be overwritten if and only if it is in the update - * mask. Output only fields cannot be updated. - * - * See {@link protos.google.protobuf.FieldMask|FieldMask} for more information. - * - * For example: `"updateMask=kmsKeyName"` - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.logging.v2.CmekSettings|CmekSettings}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/config_service_v2.update_cmek_settings.js - * region_tag:logging_v2_generated_ConfigServiceV2_UpdateCmekSettings_async - */ + /** + * Updates the Log Router CMEK settings for the given resource. + * + * Note: CMEK for the Log Router can currently only be configured for Google + * Cloud organizations. Once configured, it applies to all projects and + * folders in the Google Cloud organization. + * + * {@link protos.google.logging.v2.ConfigServiceV2.UpdateCmekSettings|UpdateCmekSettings} + * will fail if 1) `kms_key_name` is invalid, or 2) the associated service + * account does not have the required + * `roles/cloudkms.cryptoKeyEncrypterDecrypter` role assigned for the key, or + * 3) access to the key is disabled. + * + * See [Enabling CMEK for Log + * Router](https://cloud.google.com/logging/docs/routing/managed-encryption) + * for more information. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The resource name for the CMEK settings to update. + * + * "projects/[PROJECT_ID]/cmekSettings" + * "organizations/[ORGANIZATION_ID]/cmekSettings" + * "billingAccounts/[BILLING_ACCOUNT_ID]/cmekSettings" + * "folders/[FOLDER_ID]/cmekSettings" + * + * For example: + * + * `"organizations/12345/cmekSettings"` + * + * Note: CMEK for the Log Router can currently only be configured for Google + * Cloud organizations. Once configured, it applies to all projects and + * folders in the Google Cloud organization. + * @param {google.logging.v2.CmekSettings} request.cmekSettings + * Required. The CMEK settings to update. + * + * See [Enabling CMEK for Log + * Router](https://cloud.google.com/logging/docs/routing/managed-encryption) + * for more information. + * @param {google.protobuf.FieldMask} [request.updateMask] + * Optional. Field mask identifying which fields from `cmek_settings` should + * be updated. A field will be overwritten if and only if it is in the update + * mask. Output only fields cannot be updated. + * + * See {@link protos.google.protobuf.FieldMask|FieldMask} for more information. + * + * For example: `"updateMask=kmsKeyName"` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.logging.v2.CmekSettings|CmekSettings}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/config_service_v2.update_cmek_settings.js + * region_tag:logging_v2_generated_ConfigServiceV2_UpdateCmekSettings_async + */ updateCmekSettings( - request?: protos.google.logging.v2.IUpdateCmekSettingsRequest, - options?: CallOptions): - Promise<[ - protos.google.logging.v2.ICmekSettings, - protos.google.logging.v2.IUpdateCmekSettingsRequest|undefined, {}|undefined - ]>; + request?: protos.google.logging.v2.IUpdateCmekSettingsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.logging.v2.ICmekSettings, + protos.google.logging.v2.IUpdateCmekSettingsRequest | undefined, + {} | undefined, + ] + >; updateCmekSettings( - request: protos.google.logging.v2.IUpdateCmekSettingsRequest, - options: CallOptions, - callback: Callback< - protos.google.logging.v2.ICmekSettings, - protos.google.logging.v2.IUpdateCmekSettingsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.logging.v2.IUpdateCmekSettingsRequest, + options: CallOptions, + callback: Callback< + protos.google.logging.v2.ICmekSettings, + protos.google.logging.v2.IUpdateCmekSettingsRequest | null | undefined, + {} | null | undefined + >, + ): void; updateCmekSettings( - request: protos.google.logging.v2.IUpdateCmekSettingsRequest, - callback: Callback< - protos.google.logging.v2.ICmekSettings, - protos.google.logging.v2.IUpdateCmekSettingsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.logging.v2.IUpdateCmekSettingsRequest, + callback: Callback< + protos.google.logging.v2.ICmekSettings, + protos.google.logging.v2.IUpdateCmekSettingsRequest | null | undefined, + {} | null | undefined + >, + ): void; updateCmekSettings( - request?: protos.google.logging.v2.IUpdateCmekSettingsRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.logging.v2.ICmekSettings, - protos.google.logging.v2.IUpdateCmekSettingsRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.logging.v2.IUpdateCmekSettingsRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.logging.v2.ICmekSettings, - protos.google.logging.v2.IUpdateCmekSettingsRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.logging.v2.ICmekSettings, - protos.google.logging.v2.IUpdateCmekSettingsRequest|undefined, {}|undefined - ]>|void { + | protos.google.logging.v2.IUpdateCmekSettingsRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.logging.v2.ICmekSettings, + protos.google.logging.v2.IUpdateCmekSettingsRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.logging.v2.ICmekSettings, + protos.google.logging.v2.IUpdateCmekSettingsRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateCmekSettings request %j', request); - const wrappedCallback: Callback< - protos.google.logging.v2.ICmekSettings, - protos.google.logging.v2.IUpdateCmekSettingsRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.logging.v2.ICmekSettings, + | protos.google.logging.v2.IUpdateCmekSettingsRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateCmekSettings response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.updateCmekSettings(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.logging.v2.ICmekSettings, - protos.google.logging.v2.IUpdateCmekSettingsRequest|undefined, {}|undefined - ]) => { - this._log.info('updateCmekSettings response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateCmekSettings(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.logging.v2.ICmekSettings, + protos.google.logging.v2.IUpdateCmekSettingsRequest | undefined, + {} | undefined, + ]) => { + this._log.info('updateCmekSettings response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Gets the Log Router settings for the given resource. - * - * Note: Settings for the Log Router can be get for Google Cloud projects, - * folders, organizations and billing accounts. Currently it can only be - * configured for organizations. Once configured for an organization, it - * applies to all projects and folders in the Google Cloud organization. - * - * See [Enabling CMEK for Log - * Router](https://cloud.google.com/logging/docs/routing/managed-encryption) - * for more information. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The resource for which to retrieve settings. - * - * "projects/[PROJECT_ID]/settings" - * "organizations/[ORGANIZATION_ID]/settings" - * "billingAccounts/[BILLING_ACCOUNT_ID]/settings" - * "folders/[FOLDER_ID]/settings" - * - * For example: - * - * `"organizations/12345/settings"` - * - * Note: Settings for the Log Router can be get for Google Cloud projects, - * folders, organizations and billing accounts. Currently it can only be - * configured for organizations. Once configured for an organization, it - * applies to all projects and folders in the Google Cloud organization. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.logging.v2.Settings|Settings}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/config_service_v2.get_settings.js - * region_tag:logging_v2_generated_ConfigServiceV2_GetSettings_async - */ + /** + * Gets the Log Router settings for the given resource. + * + * Note: Settings for the Log Router can be get for Google Cloud projects, + * folders, organizations and billing accounts. Currently it can only be + * configured for organizations. Once configured for an organization, it + * applies to all projects and folders in the Google Cloud organization. + * + * See [Enabling CMEK for Log + * Router](https://cloud.google.com/logging/docs/routing/managed-encryption) + * for more information. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The resource for which to retrieve settings. + * + * "projects/[PROJECT_ID]/settings" + * "organizations/[ORGANIZATION_ID]/settings" + * "billingAccounts/[BILLING_ACCOUNT_ID]/settings" + * "folders/[FOLDER_ID]/settings" + * + * For example: + * + * `"organizations/12345/settings"` + * + * Note: Settings for the Log Router can be get for Google Cloud projects, + * folders, organizations and billing accounts. Currently it can only be + * configured for organizations. Once configured for an organization, it + * applies to all projects and folders in the Google Cloud organization. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.logging.v2.Settings|Settings}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/config_service_v2.get_settings.js + * region_tag:logging_v2_generated_ConfigServiceV2_GetSettings_async + */ getSettings( - request?: protos.google.logging.v2.IGetSettingsRequest, - options?: CallOptions): - Promise<[ - protos.google.logging.v2.ISettings, - protos.google.logging.v2.IGetSettingsRequest|undefined, {}|undefined - ]>; + request?: protos.google.logging.v2.IGetSettingsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.logging.v2.ISettings, + protos.google.logging.v2.IGetSettingsRequest | undefined, + {} | undefined, + ] + >; getSettings( - request: protos.google.logging.v2.IGetSettingsRequest, - options: CallOptions, - callback: Callback< - protos.google.logging.v2.ISettings, - protos.google.logging.v2.IGetSettingsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.logging.v2.IGetSettingsRequest, + options: CallOptions, + callback: Callback< + protos.google.logging.v2.ISettings, + protos.google.logging.v2.IGetSettingsRequest | null | undefined, + {} | null | undefined + >, + ): void; getSettings( - request: protos.google.logging.v2.IGetSettingsRequest, - callback: Callback< - protos.google.logging.v2.ISettings, - protos.google.logging.v2.IGetSettingsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.logging.v2.IGetSettingsRequest, + callback: Callback< + protos.google.logging.v2.ISettings, + protos.google.logging.v2.IGetSettingsRequest | null | undefined, + {} | null | undefined + >, + ): void; getSettings( - request?: protos.google.logging.v2.IGetSettingsRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.logging.v2.ISettings, - protos.google.logging.v2.IGetSettingsRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.logging.v2.IGetSettingsRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.logging.v2.ISettings, - protos.google.logging.v2.IGetSettingsRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.logging.v2.ISettings, - protos.google.logging.v2.IGetSettingsRequest|undefined, {}|undefined - ]>|void { + protos.google.logging.v2.IGetSettingsRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.logging.v2.ISettings, + protos.google.logging.v2.IGetSettingsRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.logging.v2.ISettings, + protos.google.logging.v2.IGetSettingsRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getSettings request %j', request); - const wrappedCallback: Callback< - protos.google.logging.v2.ISettings, - protos.google.logging.v2.IGetSettingsRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.logging.v2.ISettings, + protos.google.logging.v2.IGetSettingsRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getSettings response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.getSettings(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.logging.v2.ISettings, - protos.google.logging.v2.IGetSettingsRequest|undefined, {}|undefined - ]) => { - this._log.info('getSettings response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getSettings(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.logging.v2.ISettings, + protos.google.logging.v2.IGetSettingsRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getSettings response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Updates the Log Router settings for the given resource. - * - * Note: Settings for the Log Router can currently only be configured for - * Google Cloud organizations. Once configured, it applies to all projects and - * folders in the Google Cloud organization. - * - * {@link protos.google.logging.v2.ConfigServiceV2.UpdateSettings|UpdateSettings} - * will fail if 1) `kms_key_name` is invalid, or 2) the associated service - * account does not have the required - * `roles/cloudkms.cryptoKeyEncrypterDecrypter` role assigned for the key, or - * 3) access to the key is disabled. 4) `location_id` is not supported by - * Logging. 5) `location_id` violate OrgPolicy. - * - * See [Enabling CMEK for Log - * Router](https://cloud.google.com/logging/docs/routing/managed-encryption) - * for more information. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The resource name for the settings to update. - * - * "organizations/[ORGANIZATION_ID]/settings" - * - * For example: - * - * `"organizations/12345/settings"` - * - * Note: Settings for the Log Router can currently only be configured for - * Google Cloud organizations. Once configured, it applies to all projects and - * folders in the Google Cloud organization. - * @param {google.logging.v2.Settings} request.settings - * Required. The settings to update. - * - * See [Enabling CMEK for Log - * Router](https://cloud.google.com/logging/docs/routing/managed-encryption) - * for more information. - * @param {google.protobuf.FieldMask} [request.updateMask] - * Optional. Field mask identifying which fields from `settings` should - * be updated. A field will be overwritten if and only if it is in the update - * mask. Output only fields cannot be updated. - * - * See {@link protos.google.protobuf.FieldMask|FieldMask} for more information. - * - * For example: `"updateMask=kmsKeyName"` - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.logging.v2.Settings|Settings}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/config_service_v2.update_settings.js - * region_tag:logging_v2_generated_ConfigServiceV2_UpdateSettings_async - */ + /** + * Updates the Log Router settings for the given resource. + * + * Note: Settings for the Log Router can currently only be configured for + * Google Cloud organizations. Once configured, it applies to all projects and + * folders in the Google Cloud organization. + * + * {@link protos.google.logging.v2.ConfigServiceV2.UpdateSettings|UpdateSettings} + * will fail if 1) `kms_key_name` is invalid, or 2) the associated service + * account does not have the required + * `roles/cloudkms.cryptoKeyEncrypterDecrypter` role assigned for the key, or + * 3) access to the key is disabled. 4) `location_id` is not supported by + * Logging. 5) `location_id` violate OrgPolicy. + * + * See [Enabling CMEK for Log + * Router](https://cloud.google.com/logging/docs/routing/managed-encryption) + * for more information. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The resource name for the settings to update. + * + * "organizations/[ORGANIZATION_ID]/settings" + * + * For example: + * + * `"organizations/12345/settings"` + * + * Note: Settings for the Log Router can currently only be configured for + * Google Cloud organizations. Once configured, it applies to all projects and + * folders in the Google Cloud organization. + * @param {google.logging.v2.Settings} request.settings + * Required. The settings to update. + * + * See [Enabling CMEK for Log + * Router](https://cloud.google.com/logging/docs/routing/managed-encryption) + * for more information. + * @param {google.protobuf.FieldMask} [request.updateMask] + * Optional. Field mask identifying which fields from `settings` should + * be updated. A field will be overwritten if and only if it is in the update + * mask. Output only fields cannot be updated. + * + * See {@link protos.google.protobuf.FieldMask|FieldMask} for more information. + * + * For example: `"updateMask=kmsKeyName"` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.logging.v2.Settings|Settings}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/config_service_v2.update_settings.js + * region_tag:logging_v2_generated_ConfigServiceV2_UpdateSettings_async + */ updateSettings( - request?: protos.google.logging.v2.IUpdateSettingsRequest, - options?: CallOptions): - Promise<[ - protos.google.logging.v2.ISettings, - protos.google.logging.v2.IUpdateSettingsRequest|undefined, {}|undefined - ]>; + request?: protos.google.logging.v2.IUpdateSettingsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.logging.v2.ISettings, + protos.google.logging.v2.IUpdateSettingsRequest | undefined, + {} | undefined, + ] + >; updateSettings( - request: protos.google.logging.v2.IUpdateSettingsRequest, - options: CallOptions, - callback: Callback< - protos.google.logging.v2.ISettings, - protos.google.logging.v2.IUpdateSettingsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.logging.v2.IUpdateSettingsRequest, + options: CallOptions, + callback: Callback< + protos.google.logging.v2.ISettings, + protos.google.logging.v2.IUpdateSettingsRequest | null | undefined, + {} | null | undefined + >, + ): void; updateSettings( - request: protos.google.logging.v2.IUpdateSettingsRequest, - callback: Callback< - protos.google.logging.v2.ISettings, - protos.google.logging.v2.IUpdateSettingsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.logging.v2.IUpdateSettingsRequest, + callback: Callback< + protos.google.logging.v2.ISettings, + protos.google.logging.v2.IUpdateSettingsRequest | null | undefined, + {} | null | undefined + >, + ): void; updateSettings( - request?: protos.google.logging.v2.IUpdateSettingsRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.logging.v2.ISettings, - protos.google.logging.v2.IUpdateSettingsRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.logging.v2.IUpdateSettingsRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.logging.v2.ISettings, - protos.google.logging.v2.IUpdateSettingsRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.logging.v2.ISettings, - protos.google.logging.v2.IUpdateSettingsRequest|undefined, {}|undefined - ]>|void { + protos.google.logging.v2.IUpdateSettingsRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.logging.v2.ISettings, + protos.google.logging.v2.IUpdateSettingsRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.logging.v2.ISettings, + protos.google.logging.v2.IUpdateSettingsRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateSettings request %j', request); - const wrappedCallback: Callback< - protos.google.logging.v2.ISettings, - protos.google.logging.v2.IUpdateSettingsRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.logging.v2.ISettings, + protos.google.logging.v2.IUpdateSettingsRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateSettings response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.updateSettings(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.logging.v2.ISettings, - protos.google.logging.v2.IUpdateSettingsRequest|undefined, {}|undefined - ]) => { - this._log.info('updateSettings response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateSettings(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.logging.v2.ISettings, + protos.google.logging.v2.IUpdateSettingsRequest | undefined, + {} | undefined, + ]) => { + this._log.info('updateSettings response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Copies a set of log entries from a log bucket to a Cloud Storage bucket. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. Log bucket from which to copy log entries. - * - * For example: - * - * `"projects/my-project/locations/global/buckets/my-source-bucket"` - * @param {string} [request.filter] - * Optional. A filter specifying which log entries to copy. The filter must be no more - * than 20k characters. An empty filter matches all log entries. - * @param {string} request.destination - * Required. Destination to which to copy log entries. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing - * a long running operation. Its `promise()` method returns a promise - * you can `await` for. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v2/config_service_v2.copy_log_entries.js - * region_tag:logging_v2_generated_ConfigServiceV2_CopyLogEntries_async - */ + /** + * Copies a set of log entries from a log bucket to a Cloud Storage bucket. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Log bucket from which to copy log entries. + * + * For example: + * + * `"projects/my-project/locations/global/buckets/my-source-bucket"` + * @param {string} [request.filter] + * Optional. A filter specifying which log entries to copy. The filter must be no more + * than 20k characters. An empty filter matches all log entries. + * @param {string} request.destination + * Required. Destination to which to copy log entries. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v2/config_service_v2.copy_log_entries.js + * region_tag:logging_v2_generated_ConfigServiceV2_CopyLogEntries_async + */ copyLogEntries( - request?: protos.google.logging.v2.ICopyLogEntriesRequest, - options?: CallOptions): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>; + request?: protos.google.logging.v2.ICopyLogEntriesRequest, + options?: CallOptions, + ): Promise< + [ + LROperation< + protos.google.logging.v2.ICopyLogEntriesResponse, + protos.google.logging.v2.ICopyLogEntriesMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; copyLogEntries( - request: protos.google.logging.v2.ICopyLogEntriesRequest, - options: CallOptions, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.logging.v2.ICopyLogEntriesRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.logging.v2.ICopyLogEntriesResponse, + protos.google.logging.v2.ICopyLogEntriesMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; copyLogEntries( - request: protos.google.logging.v2.ICopyLogEntriesRequest, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.logging.v2.ICopyLogEntriesRequest, + callback: Callback< + LROperation< + protos.google.logging.v2.ICopyLogEntriesResponse, + protos.google.logging.v2.ICopyLogEntriesMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; copyLogEntries( - request?: protos.google.logging.v2.ICopyLogEntriesRequest, - optionsOrCallback?: CallOptions|Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>, - callback?: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>|void { + request?: protos.google.logging.v2.ICopyLogEntriesRequest, + optionsOrCallback?: + | CallOptions + | Callback< + LROperation< + protos.google.logging.v2.ICopyLogEntriesResponse, + protos.google.logging.v2.ICopyLogEntriesMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + callback?: Callback< + LROperation< + protos.google.logging.v2.ICopyLogEntriesResponse, + protos.google.logging.v2.ICopyLogEntriesMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + LROperation< + protos.google.logging.v2.ICopyLogEntriesResponse, + protos.google.logging.v2.ICopyLogEntriesMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize().catch(err => {throw err}); - const wrappedCallback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>|undefined = callback + this.initialize().catch((err) => { + throw err; + }); + const wrappedCallback: + | Callback< + LROperation< + protos.google.logging.v2.ICopyLogEntriesResponse, + protos.google.logging.v2.ICopyLogEntriesMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, rawResponse, _) => { this._log.info('copyLogEntries response %j', rawResponse); callback!(error, response, rawResponse, _); // We verified `callback` above. } : undefined; this._log.info('copyLogEntries request %j', request); - return this.innerApiCalls.copyLogEntries(request, options, wrappedCallback) - ?.then(([response, rawResponse, _]: [ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]) => { - this._log.info('copyLogEntries response %j', rawResponse); - return [response, rawResponse, _]; - }); + return this.innerApiCalls + .copyLogEntries(request, options, wrappedCallback) + ?.then( + ([response, rawResponse, _]: [ + LROperation< + protos.google.logging.v2.ICopyLogEntriesResponse, + protos.google.logging.v2.ICopyLogEntriesMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ]) => { + this._log.info('copyLogEntries response %j', rawResponse); + return [response, rawResponse, _]; + }, + ); } -/** - * Check the status of the long running operation returned by `copyLogEntries()`. - * @param {String} name - * The operation name that will be passed. - * @returns {Promise} - The promise which resolves to an object. - * The decoded operation object has result and metadata field to get information from. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v2/config_service_v2.copy_log_entries.js - * region_tag:logging_v2_generated_ConfigServiceV2_CopyLogEntries_async - */ - async checkCopyLogEntriesProgress(name: string): Promise>{ + /** + * Check the status of the long running operation returned by `copyLogEntries()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v2/config_service_v2.copy_log_entries.js + * region_tag:logging_v2_generated_ConfigServiceV2_CopyLogEntries_async + */ + async checkCopyLogEntriesProgress( + name: string, + ): Promise< + LROperation< + protos.google.logging.v2.CopyLogEntriesResponse, + protos.google.logging.v2.CopyLogEntriesMetadata + > + > { this._log.info('copyLogEntries long-running'); - const request = new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest({name}); + const request = + new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( + { name }, + ); const [operation] = await this.operationsClient.getOperation(request); - const decodeOperation = new this._gaxModule.Operation(operation, this.descriptors.longrunning.copyLogEntries, this._gaxModule.createDefaultBackoffSettings()); - return decodeOperation as LROperation; - } - /** - * Lists log buckets. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent resource whose buckets are to be listed: - * - * "projects/[PROJECT_ID]/locations/[LOCATION_ID]" - * "organizations/[ORGANIZATION_ID]/locations/[LOCATION_ID]" - * "billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]" - * "folders/[FOLDER_ID]/locations/[LOCATION_ID]" - * - * Note: The locations portion of the resource must be specified, but - * supplying the character `-` in place of [LOCATION_ID] will return all - * buckets. - * @param {string} [request.pageToken] - * Optional. If present, then retrieve the next batch of results from the preceding call - * to this method. `pageToken` must be the value of `nextPageToken` from the - * previous response. The values of other method parameters should be - * identical to those in the previous call. - * @param {number} [request.pageSize] - * Optional. The maximum number of results to return from this request. Non-positive - * values are ignored. The presence of `nextPageToken` in the response - * indicates that more results might be available. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.logging.v2.LogBucket|LogBucket}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `listBucketsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + const decodeOperation = new this._gaxModule.Operation( + operation, + this.descriptors.longrunning.copyLogEntries, + this._gaxModule.createDefaultBackoffSettings(), + ); + return decodeOperation as LROperation< + protos.google.logging.v2.CopyLogEntriesResponse, + protos.google.logging.v2.CopyLogEntriesMetadata + >; + } + /** + * Lists log buckets. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource whose buckets are to be listed: + * + * "projects/[PROJECT_ID]/locations/[LOCATION_ID]" + * "organizations/[ORGANIZATION_ID]/locations/[LOCATION_ID]" + * "billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]" + * "folders/[FOLDER_ID]/locations/[LOCATION_ID]" + * + * Note: The locations portion of the resource must be specified, but + * supplying the character `-` in place of [LOCATION_ID] will return all + * buckets. + * @param {string} [request.pageToken] + * Optional. If present, then retrieve the next batch of results from the preceding call + * to this method. `pageToken` must be the value of `nextPageToken` from the + * previous response. The values of other method parameters should be + * identical to those in the previous call. + * @param {number} [request.pageSize] + * Optional. The maximum number of results to return from this request. Non-positive + * values are ignored. The presence of `nextPageToken` in the response + * indicates that more results might be available. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.logging.v2.LogBucket|LogBucket}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listBucketsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listBuckets( - request?: protos.google.logging.v2.IListBucketsRequest, - options?: CallOptions): - Promise<[ - protos.google.logging.v2.ILogBucket[], - protos.google.logging.v2.IListBucketsRequest|null, - protos.google.logging.v2.IListBucketsResponse - ]>; + request?: protos.google.logging.v2.IListBucketsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.logging.v2.ILogBucket[], + protos.google.logging.v2.IListBucketsRequest | null, + protos.google.logging.v2.IListBucketsResponse, + ] + >; listBuckets( - request: protos.google.logging.v2.IListBucketsRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.logging.v2.IListBucketsRequest, - protos.google.logging.v2.IListBucketsResponse|null|undefined, - protos.google.logging.v2.ILogBucket>): void; + request: protos.google.logging.v2.IListBucketsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.logging.v2.IListBucketsRequest, + protos.google.logging.v2.IListBucketsResponse | null | undefined, + protos.google.logging.v2.ILogBucket + >, + ): void; listBuckets( - request: protos.google.logging.v2.IListBucketsRequest, - callback: PaginationCallback< - protos.google.logging.v2.IListBucketsRequest, - protos.google.logging.v2.IListBucketsResponse|null|undefined, - protos.google.logging.v2.ILogBucket>): void; + request: protos.google.logging.v2.IListBucketsRequest, + callback: PaginationCallback< + protos.google.logging.v2.IListBucketsRequest, + protos.google.logging.v2.IListBucketsResponse | null | undefined, + protos.google.logging.v2.ILogBucket + >, + ): void; listBuckets( - request?: protos.google.logging.v2.IListBucketsRequest, - optionsOrCallback?: CallOptions|PaginationCallback< + request?: protos.google.logging.v2.IListBucketsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.logging.v2.IListBucketsRequest, - protos.google.logging.v2.IListBucketsResponse|null|undefined, - protos.google.logging.v2.ILogBucket>, - callback?: PaginationCallback< - protos.google.logging.v2.IListBucketsRequest, - protos.google.logging.v2.IListBucketsResponse|null|undefined, - protos.google.logging.v2.ILogBucket>): - Promise<[ - protos.google.logging.v2.ILogBucket[], - protos.google.logging.v2.IListBucketsRequest|null, - protos.google.logging.v2.IListBucketsResponse - ]>|void { + protos.google.logging.v2.IListBucketsResponse | null | undefined, + protos.google.logging.v2.ILogBucket + >, + callback?: PaginationCallback< + protos.google.logging.v2.IListBucketsRequest, + protos.google.logging.v2.IListBucketsResponse | null | undefined, + protos.google.logging.v2.ILogBucket + >, + ): Promise< + [ + protos.google.logging.v2.ILogBucket[], + protos.google.logging.v2.IListBucketsRequest | null, + protos.google.logging.v2.IListBucketsResponse, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.logging.v2.IListBucketsRequest, - protos.google.logging.v2.IListBucketsResponse|null|undefined, - protos.google.logging.v2.ILogBucket>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.logging.v2.IListBucketsRequest, + protos.google.logging.v2.IListBucketsResponse | null | undefined, + protos.google.logging.v2.ILogBucket + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listBuckets values %j', values); callback!(error, values, nextPageRequest, rawResponse); @@ -3044,225 +3874,244 @@ export class ConfigServiceV2Client { this._log.info('listBuckets request %j', request); return this.innerApiCalls .listBuckets(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.logging.v2.ILogBucket[], - protos.google.logging.v2.IListBucketsRequest|null, - protos.google.logging.v2.IListBucketsResponse - ]) => { - this._log.info('listBuckets values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.logging.v2.ILogBucket[], + protos.google.logging.v2.IListBucketsRequest | null, + protos.google.logging.v2.IListBucketsResponse, + ]) => { + this._log.info('listBuckets values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listBuckets`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent resource whose buckets are to be listed: - * - * "projects/[PROJECT_ID]/locations/[LOCATION_ID]" - * "organizations/[ORGANIZATION_ID]/locations/[LOCATION_ID]" - * "billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]" - * "folders/[FOLDER_ID]/locations/[LOCATION_ID]" - * - * Note: The locations portion of the resource must be specified, but - * supplying the character `-` in place of [LOCATION_ID] will return all - * buckets. - * @param {string} [request.pageToken] - * Optional. If present, then retrieve the next batch of results from the preceding call - * to this method. `pageToken` must be the value of `nextPageToken` from the - * previous response. The values of other method parameters should be - * identical to those in the previous call. - * @param {number} [request.pageSize] - * Optional. The maximum number of results to return from this request. Non-positive - * values are ignored. The presence of `nextPageToken` in the response - * indicates that more results might be available. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.logging.v2.LogBucket|LogBucket} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `listBucketsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `listBuckets`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource whose buckets are to be listed: + * + * "projects/[PROJECT_ID]/locations/[LOCATION_ID]" + * "organizations/[ORGANIZATION_ID]/locations/[LOCATION_ID]" + * "billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]" + * "folders/[FOLDER_ID]/locations/[LOCATION_ID]" + * + * Note: The locations portion of the resource must be specified, but + * supplying the character `-` in place of [LOCATION_ID] will return all + * buckets. + * @param {string} [request.pageToken] + * Optional. If present, then retrieve the next batch of results from the preceding call + * to this method. `pageToken` must be the value of `nextPageToken` from the + * previous response. The values of other method parameters should be + * identical to those in the previous call. + * @param {number} [request.pageSize] + * Optional. The maximum number of results to return from this request. Non-positive + * values are ignored. The presence of `nextPageToken` in the response + * indicates that more results might be available. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.logging.v2.LogBucket|LogBucket} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listBucketsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listBucketsStream( - request?: protos.google.logging.v2.IListBucketsRequest, - options?: CallOptions): - Transform{ + request?: protos.google.logging.v2.IListBucketsRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); const defaultCallSettings = this._defaults['listBuckets']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listBuckets stream %j', request); return this.descriptors.page.listBuckets.createStream( this.innerApiCalls.listBuckets as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listBuckets`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent resource whose buckets are to be listed: - * - * "projects/[PROJECT_ID]/locations/[LOCATION_ID]" - * "organizations/[ORGANIZATION_ID]/locations/[LOCATION_ID]" - * "billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]" - * "folders/[FOLDER_ID]/locations/[LOCATION_ID]" - * - * Note: The locations portion of the resource must be specified, but - * supplying the character `-` in place of [LOCATION_ID] will return all - * buckets. - * @param {string} [request.pageToken] - * Optional. If present, then retrieve the next batch of results from the preceding call - * to this method. `pageToken` must be the value of `nextPageToken` from the - * previous response. The values of other method parameters should be - * identical to those in the previous call. - * @param {number} [request.pageSize] - * Optional. The maximum number of results to return from this request. Non-positive - * values are ignored. The presence of `nextPageToken` in the response - * indicates that more results might be available. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.logging.v2.LogBucket|LogBucket}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v2/config_service_v2.list_buckets.js - * region_tag:logging_v2_generated_ConfigServiceV2_ListBuckets_async - */ + /** + * Equivalent to `listBuckets`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource whose buckets are to be listed: + * + * "projects/[PROJECT_ID]/locations/[LOCATION_ID]" + * "organizations/[ORGANIZATION_ID]/locations/[LOCATION_ID]" + * "billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]" + * "folders/[FOLDER_ID]/locations/[LOCATION_ID]" + * + * Note: The locations portion of the resource must be specified, but + * supplying the character `-` in place of [LOCATION_ID] will return all + * buckets. + * @param {string} [request.pageToken] + * Optional. If present, then retrieve the next batch of results from the preceding call + * to this method. `pageToken` must be the value of `nextPageToken` from the + * previous response. The values of other method parameters should be + * identical to those in the previous call. + * @param {number} [request.pageSize] + * Optional. The maximum number of results to return from this request. Non-positive + * values are ignored. The presence of `nextPageToken` in the response + * indicates that more results might be available. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.logging.v2.LogBucket|LogBucket}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v2/config_service_v2.list_buckets.js + * region_tag:logging_v2_generated_ConfigServiceV2_ListBuckets_async + */ listBucketsAsync( - request?: protos.google.logging.v2.IListBucketsRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.logging.v2.IListBucketsRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); const defaultCallSettings = this._defaults['listBuckets']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listBuckets iterate %j', request); return this.descriptors.page.listBuckets.asyncIterate( this.innerApiCalls['listBuckets'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } - /** - * Lists views on a log bucket. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The bucket whose views are to be listed: - * - * "projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" - * @param {string} [request.pageToken] - * Optional. If present, then retrieve the next batch of results from the preceding call - * to this method. `pageToken` must be the value of `nextPageToken` from the - * previous response. The values of other method parameters should be - * identical to those in the previous call. - * @param {number} [request.pageSize] - * Optional. The maximum number of results to return from this request. - * - * Non-positive values are ignored. The presence of `nextPageToken` in the - * response indicates that more results might be available. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.logging.v2.LogView|LogView}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `listViewsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Lists views on a log bucket. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The bucket whose views are to be listed: + * + * "projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" + * @param {string} [request.pageToken] + * Optional. If present, then retrieve the next batch of results from the preceding call + * to this method. `pageToken` must be the value of `nextPageToken` from the + * previous response. The values of other method parameters should be + * identical to those in the previous call. + * @param {number} [request.pageSize] + * Optional. The maximum number of results to return from this request. + * + * Non-positive values are ignored. The presence of `nextPageToken` in the + * response indicates that more results might be available. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.logging.v2.LogView|LogView}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listViewsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listViews( - request?: protos.google.logging.v2.IListViewsRequest, - options?: CallOptions): - Promise<[ - protos.google.logging.v2.ILogView[], - protos.google.logging.v2.IListViewsRequest|null, - protos.google.logging.v2.IListViewsResponse - ]>; + request?: protos.google.logging.v2.IListViewsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.logging.v2.ILogView[], + protos.google.logging.v2.IListViewsRequest | null, + protos.google.logging.v2.IListViewsResponse, + ] + >; listViews( - request: protos.google.logging.v2.IListViewsRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.logging.v2.IListViewsRequest, - protos.google.logging.v2.IListViewsResponse|null|undefined, - protos.google.logging.v2.ILogView>): void; + request: protos.google.logging.v2.IListViewsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.logging.v2.IListViewsRequest, + protos.google.logging.v2.IListViewsResponse | null | undefined, + protos.google.logging.v2.ILogView + >, + ): void; listViews( - request: protos.google.logging.v2.IListViewsRequest, - callback: PaginationCallback< - protos.google.logging.v2.IListViewsRequest, - protos.google.logging.v2.IListViewsResponse|null|undefined, - protos.google.logging.v2.ILogView>): void; + request: protos.google.logging.v2.IListViewsRequest, + callback: PaginationCallback< + protos.google.logging.v2.IListViewsRequest, + protos.google.logging.v2.IListViewsResponse | null | undefined, + protos.google.logging.v2.ILogView + >, + ): void; listViews( - request?: protos.google.logging.v2.IListViewsRequest, - optionsOrCallback?: CallOptions|PaginationCallback< - protos.google.logging.v2.IListViewsRequest, - protos.google.logging.v2.IListViewsResponse|null|undefined, - protos.google.logging.v2.ILogView>, - callback?: PaginationCallback< + request?: protos.google.logging.v2.IListViewsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.logging.v2.IListViewsRequest, - protos.google.logging.v2.IListViewsResponse|null|undefined, - protos.google.logging.v2.ILogView>): - Promise<[ - protos.google.logging.v2.ILogView[], - protos.google.logging.v2.IListViewsRequest|null, - protos.google.logging.v2.IListViewsResponse - ]>|void { + protos.google.logging.v2.IListViewsResponse | null | undefined, + protos.google.logging.v2.ILogView + >, + callback?: PaginationCallback< + protos.google.logging.v2.IListViewsRequest, + protos.google.logging.v2.IListViewsResponse | null | undefined, + protos.google.logging.v2.ILogView + >, + ): Promise< + [ + protos.google.logging.v2.ILogView[], + protos.google.logging.v2.IListViewsRequest | null, + protos.google.logging.v2.IListViewsResponse, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.logging.v2.IListViewsRequest, - protos.google.logging.v2.IListViewsResponse|null|undefined, - protos.google.logging.v2.ILogView>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.logging.v2.IListViewsRequest, + protos.google.logging.v2.IListViewsResponse | null | undefined, + protos.google.logging.v2.ILogView + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listViews values %j', values); callback!(error, values, nextPageRequest, rawResponse); @@ -3271,215 +4120,234 @@ export class ConfigServiceV2Client { this._log.info('listViews request %j', request); return this.innerApiCalls .listViews(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.logging.v2.ILogView[], - protos.google.logging.v2.IListViewsRequest|null, - protos.google.logging.v2.IListViewsResponse - ]) => { - this._log.info('listViews values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.logging.v2.ILogView[], + protos.google.logging.v2.IListViewsRequest | null, + protos.google.logging.v2.IListViewsResponse, + ]) => { + this._log.info('listViews values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listViews`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The bucket whose views are to be listed: - * - * "projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" - * @param {string} [request.pageToken] - * Optional. If present, then retrieve the next batch of results from the preceding call - * to this method. `pageToken` must be the value of `nextPageToken` from the - * previous response. The values of other method parameters should be - * identical to those in the previous call. - * @param {number} [request.pageSize] - * Optional. The maximum number of results to return from this request. - * - * Non-positive values are ignored. The presence of `nextPageToken` in the - * response indicates that more results might be available. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.logging.v2.LogView|LogView} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `listViewsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `listViews`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The bucket whose views are to be listed: + * + * "projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" + * @param {string} [request.pageToken] + * Optional. If present, then retrieve the next batch of results from the preceding call + * to this method. `pageToken` must be the value of `nextPageToken` from the + * previous response. The values of other method parameters should be + * identical to those in the previous call. + * @param {number} [request.pageSize] + * Optional. The maximum number of results to return from this request. + * + * Non-positive values are ignored. The presence of `nextPageToken` in the + * response indicates that more results might be available. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.logging.v2.LogView|LogView} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listViewsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listViewsStream( - request?: protos.google.logging.v2.IListViewsRequest, - options?: CallOptions): - Transform{ + request?: protos.google.logging.v2.IListViewsRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); const defaultCallSettings = this._defaults['listViews']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listViews stream %j', request); return this.descriptors.page.listViews.createStream( this.innerApiCalls.listViews as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listViews`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The bucket whose views are to be listed: - * - * "projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" - * @param {string} [request.pageToken] - * Optional. If present, then retrieve the next batch of results from the preceding call - * to this method. `pageToken` must be the value of `nextPageToken` from the - * previous response. The values of other method parameters should be - * identical to those in the previous call. - * @param {number} [request.pageSize] - * Optional. The maximum number of results to return from this request. - * - * Non-positive values are ignored. The presence of `nextPageToken` in the - * response indicates that more results might be available. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.logging.v2.LogView|LogView}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v2/config_service_v2.list_views.js - * region_tag:logging_v2_generated_ConfigServiceV2_ListViews_async - */ + /** + * Equivalent to `listViews`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The bucket whose views are to be listed: + * + * "projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" + * @param {string} [request.pageToken] + * Optional. If present, then retrieve the next batch of results from the preceding call + * to this method. `pageToken` must be the value of `nextPageToken` from the + * previous response. The values of other method parameters should be + * identical to those in the previous call. + * @param {number} [request.pageSize] + * Optional. The maximum number of results to return from this request. + * + * Non-positive values are ignored. The presence of `nextPageToken` in the + * response indicates that more results might be available. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.logging.v2.LogView|LogView}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v2/config_service_v2.list_views.js + * region_tag:logging_v2_generated_ConfigServiceV2_ListViews_async + */ listViewsAsync( - request?: protos.google.logging.v2.IListViewsRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.logging.v2.IListViewsRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); const defaultCallSettings = this._defaults['listViews']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listViews iterate %j', request); return this.descriptors.page.listViews.asyncIterate( this.innerApiCalls['listViews'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } - /** - * Lists sinks. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent resource whose sinks are to be listed: - * - * "projects/[PROJECT_ID]" - * "organizations/[ORGANIZATION_ID]" - * "billingAccounts/[BILLING_ACCOUNT_ID]" - * "folders/[FOLDER_ID]" - * @param {string} [request.pageToken] - * Optional. If present, then retrieve the next batch of results from the - * preceding call to this method. `pageToken` must be the value of - * `nextPageToken` from the previous response. The values of other method - * parameters should be identical to those in the previous call. - * @param {number} [request.pageSize] - * Optional. The maximum number of results to return from this request. - * Non-positive values are ignored. The presence of `nextPageToken` in the - * response indicates that more results might be available. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.logging.v2.LogSink|LogSink}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `listSinksAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Lists sinks. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource whose sinks are to be listed: + * + * "projects/[PROJECT_ID]" + * "organizations/[ORGANIZATION_ID]" + * "billingAccounts/[BILLING_ACCOUNT_ID]" + * "folders/[FOLDER_ID]" + * @param {string} [request.pageToken] + * Optional. If present, then retrieve the next batch of results from the + * preceding call to this method. `pageToken` must be the value of + * `nextPageToken` from the previous response. The values of other method + * parameters should be identical to those in the previous call. + * @param {number} [request.pageSize] + * Optional. The maximum number of results to return from this request. + * Non-positive values are ignored. The presence of `nextPageToken` in the + * response indicates that more results might be available. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.logging.v2.LogSink|LogSink}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listSinksAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listSinks( - request?: protos.google.logging.v2.IListSinksRequest, - options?: CallOptions): - Promise<[ - protos.google.logging.v2.ILogSink[], - protos.google.logging.v2.IListSinksRequest|null, - protos.google.logging.v2.IListSinksResponse - ]>; + request?: protos.google.logging.v2.IListSinksRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.logging.v2.ILogSink[], + protos.google.logging.v2.IListSinksRequest | null, + protos.google.logging.v2.IListSinksResponse, + ] + >; listSinks( - request: protos.google.logging.v2.IListSinksRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.logging.v2.IListSinksRequest, - protos.google.logging.v2.IListSinksResponse|null|undefined, - protos.google.logging.v2.ILogSink>): void; + request: protos.google.logging.v2.IListSinksRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.logging.v2.IListSinksRequest, + protos.google.logging.v2.IListSinksResponse | null | undefined, + protos.google.logging.v2.ILogSink + >, + ): void; listSinks( - request: protos.google.logging.v2.IListSinksRequest, - callback: PaginationCallback< - protos.google.logging.v2.IListSinksRequest, - protos.google.logging.v2.IListSinksResponse|null|undefined, - protos.google.logging.v2.ILogSink>): void; + request: protos.google.logging.v2.IListSinksRequest, + callback: PaginationCallback< + protos.google.logging.v2.IListSinksRequest, + protos.google.logging.v2.IListSinksResponse | null | undefined, + protos.google.logging.v2.ILogSink + >, + ): void; listSinks( - request?: protos.google.logging.v2.IListSinksRequest, - optionsOrCallback?: CallOptions|PaginationCallback< - protos.google.logging.v2.IListSinksRequest, - protos.google.logging.v2.IListSinksResponse|null|undefined, - protos.google.logging.v2.ILogSink>, - callback?: PaginationCallback< + request?: protos.google.logging.v2.IListSinksRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.logging.v2.IListSinksRequest, - protos.google.logging.v2.IListSinksResponse|null|undefined, - protos.google.logging.v2.ILogSink>): - Promise<[ - protos.google.logging.v2.ILogSink[], - protos.google.logging.v2.IListSinksRequest|null, - protos.google.logging.v2.IListSinksResponse - ]>|void { + protos.google.logging.v2.IListSinksResponse | null | undefined, + protos.google.logging.v2.ILogSink + >, + callback?: PaginationCallback< + protos.google.logging.v2.IListSinksRequest, + protos.google.logging.v2.IListSinksResponse | null | undefined, + protos.google.logging.v2.ILogSink + >, + ): Promise< + [ + protos.google.logging.v2.ILogSink[], + protos.google.logging.v2.IListSinksRequest | null, + protos.google.logging.v2.IListSinksResponse, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.logging.v2.IListSinksRequest, - protos.google.logging.v2.IListSinksResponse|null|undefined, - protos.google.logging.v2.ILogSink>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.logging.v2.IListSinksRequest, + protos.google.logging.v2.IListSinksResponse | null | undefined, + protos.google.logging.v2.ILogSink + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listSinks values %j', values); callback!(error, values, nextPageRequest, rawResponse); @@ -3488,219 +4356,238 @@ export class ConfigServiceV2Client { this._log.info('listSinks request %j', request); return this.innerApiCalls .listSinks(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.logging.v2.ILogSink[], - protos.google.logging.v2.IListSinksRequest|null, - protos.google.logging.v2.IListSinksResponse - ]) => { - this._log.info('listSinks values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.logging.v2.ILogSink[], + protos.google.logging.v2.IListSinksRequest | null, + protos.google.logging.v2.IListSinksResponse, + ]) => { + this._log.info('listSinks values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listSinks`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent resource whose sinks are to be listed: - * - * "projects/[PROJECT_ID]" - * "organizations/[ORGANIZATION_ID]" - * "billingAccounts/[BILLING_ACCOUNT_ID]" - * "folders/[FOLDER_ID]" - * @param {string} [request.pageToken] - * Optional. If present, then retrieve the next batch of results from the - * preceding call to this method. `pageToken` must be the value of - * `nextPageToken` from the previous response. The values of other method - * parameters should be identical to those in the previous call. - * @param {number} [request.pageSize] - * Optional. The maximum number of results to return from this request. - * Non-positive values are ignored. The presence of `nextPageToken` in the - * response indicates that more results might be available. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.logging.v2.LogSink|LogSink} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `listSinksAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `listSinks`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource whose sinks are to be listed: + * + * "projects/[PROJECT_ID]" + * "organizations/[ORGANIZATION_ID]" + * "billingAccounts/[BILLING_ACCOUNT_ID]" + * "folders/[FOLDER_ID]" + * @param {string} [request.pageToken] + * Optional. If present, then retrieve the next batch of results from the + * preceding call to this method. `pageToken` must be the value of + * `nextPageToken` from the previous response. The values of other method + * parameters should be identical to those in the previous call. + * @param {number} [request.pageSize] + * Optional. The maximum number of results to return from this request. + * Non-positive values are ignored. The presence of `nextPageToken` in the + * response indicates that more results might be available. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.logging.v2.LogSink|LogSink} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listSinksAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listSinksStream( - request?: protos.google.logging.v2.IListSinksRequest, - options?: CallOptions): - Transform{ + request?: protos.google.logging.v2.IListSinksRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); const defaultCallSettings = this._defaults['listSinks']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listSinks stream %j', request); return this.descriptors.page.listSinks.createStream( this.innerApiCalls.listSinks as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listSinks`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent resource whose sinks are to be listed: - * - * "projects/[PROJECT_ID]" - * "organizations/[ORGANIZATION_ID]" - * "billingAccounts/[BILLING_ACCOUNT_ID]" - * "folders/[FOLDER_ID]" - * @param {string} [request.pageToken] - * Optional. If present, then retrieve the next batch of results from the - * preceding call to this method. `pageToken` must be the value of - * `nextPageToken` from the previous response. The values of other method - * parameters should be identical to those in the previous call. - * @param {number} [request.pageSize] - * Optional. The maximum number of results to return from this request. - * Non-positive values are ignored. The presence of `nextPageToken` in the - * response indicates that more results might be available. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.logging.v2.LogSink|LogSink}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v2/config_service_v2.list_sinks.js - * region_tag:logging_v2_generated_ConfigServiceV2_ListSinks_async - */ + /** + * Equivalent to `listSinks`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource whose sinks are to be listed: + * + * "projects/[PROJECT_ID]" + * "organizations/[ORGANIZATION_ID]" + * "billingAccounts/[BILLING_ACCOUNT_ID]" + * "folders/[FOLDER_ID]" + * @param {string} [request.pageToken] + * Optional. If present, then retrieve the next batch of results from the + * preceding call to this method. `pageToken` must be the value of + * `nextPageToken` from the previous response. The values of other method + * parameters should be identical to those in the previous call. + * @param {number} [request.pageSize] + * Optional. The maximum number of results to return from this request. + * Non-positive values are ignored. The presence of `nextPageToken` in the + * response indicates that more results might be available. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.logging.v2.LogSink|LogSink}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v2/config_service_v2.list_sinks.js + * region_tag:logging_v2_generated_ConfigServiceV2_ListSinks_async + */ listSinksAsync( - request?: protos.google.logging.v2.IListSinksRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.logging.v2.IListSinksRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); const defaultCallSettings = this._defaults['listSinks']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listSinks iterate %j', request); return this.descriptors.page.listSinks.asyncIterate( this.innerApiCalls['listSinks'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } - /** - * Lists all the exclusions on the _Default sink in a parent resource. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent resource whose exclusions are to be listed. - * - * "projects/[PROJECT_ID]" - * "organizations/[ORGANIZATION_ID]" - * "billingAccounts/[BILLING_ACCOUNT_ID]" - * "folders/[FOLDER_ID]" - * @param {string} [request.pageToken] - * Optional. If present, then retrieve the next batch of results from the - * preceding call to this method. `pageToken` must be the value of - * `nextPageToken` from the previous response. The values of other method - * parameters should be identical to those in the previous call. - * @param {number} [request.pageSize] - * Optional. The maximum number of results to return from this request. - * Non-positive values are ignored. The presence of `nextPageToken` in the - * response indicates that more results might be available. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.logging.v2.LogExclusion|LogExclusion}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `listExclusionsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Lists all the exclusions on the _Default sink in a parent resource. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource whose exclusions are to be listed. + * + * "projects/[PROJECT_ID]" + * "organizations/[ORGANIZATION_ID]" + * "billingAccounts/[BILLING_ACCOUNT_ID]" + * "folders/[FOLDER_ID]" + * @param {string} [request.pageToken] + * Optional. If present, then retrieve the next batch of results from the + * preceding call to this method. `pageToken` must be the value of + * `nextPageToken` from the previous response. The values of other method + * parameters should be identical to those in the previous call. + * @param {number} [request.pageSize] + * Optional. The maximum number of results to return from this request. + * Non-positive values are ignored. The presence of `nextPageToken` in the + * response indicates that more results might be available. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.logging.v2.LogExclusion|LogExclusion}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listExclusionsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listExclusions( - request?: protos.google.logging.v2.IListExclusionsRequest, - options?: CallOptions): - Promise<[ - protos.google.logging.v2.ILogExclusion[], - protos.google.logging.v2.IListExclusionsRequest|null, - protos.google.logging.v2.IListExclusionsResponse - ]>; + request?: protos.google.logging.v2.IListExclusionsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.logging.v2.ILogExclusion[], + protos.google.logging.v2.IListExclusionsRequest | null, + protos.google.logging.v2.IListExclusionsResponse, + ] + >; listExclusions( - request: protos.google.logging.v2.IListExclusionsRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.logging.v2.IListExclusionsRequest, - protos.google.logging.v2.IListExclusionsResponse|null|undefined, - protos.google.logging.v2.ILogExclusion>): void; + request: protos.google.logging.v2.IListExclusionsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.logging.v2.IListExclusionsRequest, + protos.google.logging.v2.IListExclusionsResponse | null | undefined, + protos.google.logging.v2.ILogExclusion + >, + ): void; listExclusions( - request: protos.google.logging.v2.IListExclusionsRequest, - callback: PaginationCallback< - protos.google.logging.v2.IListExclusionsRequest, - protos.google.logging.v2.IListExclusionsResponse|null|undefined, - protos.google.logging.v2.ILogExclusion>): void; + request: protos.google.logging.v2.IListExclusionsRequest, + callback: PaginationCallback< + protos.google.logging.v2.IListExclusionsRequest, + protos.google.logging.v2.IListExclusionsResponse | null | undefined, + protos.google.logging.v2.ILogExclusion + >, + ): void; listExclusions( - request?: protos.google.logging.v2.IListExclusionsRequest, - optionsOrCallback?: CallOptions|PaginationCallback< - protos.google.logging.v2.IListExclusionsRequest, - protos.google.logging.v2.IListExclusionsResponse|null|undefined, - protos.google.logging.v2.ILogExclusion>, - callback?: PaginationCallback< + request?: protos.google.logging.v2.IListExclusionsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.logging.v2.IListExclusionsRequest, - protos.google.logging.v2.IListExclusionsResponse|null|undefined, - protos.google.logging.v2.ILogExclusion>): - Promise<[ - protos.google.logging.v2.ILogExclusion[], - protos.google.logging.v2.IListExclusionsRequest|null, - protos.google.logging.v2.IListExclusionsResponse - ]>|void { + protos.google.logging.v2.IListExclusionsResponse | null | undefined, + protos.google.logging.v2.ILogExclusion + >, + callback?: PaginationCallback< + protos.google.logging.v2.IListExclusionsRequest, + protos.google.logging.v2.IListExclusionsResponse | null | undefined, + protos.google.logging.v2.ILogExclusion + >, + ): Promise< + [ + protos.google.logging.v2.ILogExclusion[], + protos.google.logging.v2.IListExclusionsRequest | null, + protos.google.logging.v2.IListExclusionsResponse, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.logging.v2.IListExclusionsRequest, - protos.google.logging.v2.IListExclusionsResponse|null|undefined, - protos.google.logging.v2.ILogExclusion>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.logging.v2.IListExclusionsRequest, + protos.google.logging.v2.IListExclusionsResponse | null | undefined, + protos.google.logging.v2.ILogExclusion + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listExclusions values %j', values); callback!(error, values, nextPageRequest, rawResponse); @@ -3709,126 +4596,130 @@ export class ConfigServiceV2Client { this._log.info('listExclusions request %j', request); return this.innerApiCalls .listExclusions(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.logging.v2.ILogExclusion[], - protos.google.logging.v2.IListExclusionsRequest|null, - protos.google.logging.v2.IListExclusionsResponse - ]) => { - this._log.info('listExclusions values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.logging.v2.ILogExclusion[], + protos.google.logging.v2.IListExclusionsRequest | null, + protos.google.logging.v2.IListExclusionsResponse, + ]) => { + this._log.info('listExclusions values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listExclusions`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent resource whose exclusions are to be listed. - * - * "projects/[PROJECT_ID]" - * "organizations/[ORGANIZATION_ID]" - * "billingAccounts/[BILLING_ACCOUNT_ID]" - * "folders/[FOLDER_ID]" - * @param {string} [request.pageToken] - * Optional. If present, then retrieve the next batch of results from the - * preceding call to this method. `pageToken` must be the value of - * `nextPageToken` from the previous response. The values of other method - * parameters should be identical to those in the previous call. - * @param {number} [request.pageSize] - * Optional. The maximum number of results to return from this request. - * Non-positive values are ignored. The presence of `nextPageToken` in the - * response indicates that more results might be available. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.logging.v2.LogExclusion|LogExclusion} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `listExclusionsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `listExclusions`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource whose exclusions are to be listed. + * + * "projects/[PROJECT_ID]" + * "organizations/[ORGANIZATION_ID]" + * "billingAccounts/[BILLING_ACCOUNT_ID]" + * "folders/[FOLDER_ID]" + * @param {string} [request.pageToken] + * Optional. If present, then retrieve the next batch of results from the + * preceding call to this method. `pageToken` must be the value of + * `nextPageToken` from the previous response. The values of other method + * parameters should be identical to those in the previous call. + * @param {number} [request.pageSize] + * Optional. The maximum number of results to return from this request. + * Non-positive values are ignored. The presence of `nextPageToken` in the + * response indicates that more results might be available. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.logging.v2.LogExclusion|LogExclusion} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listExclusionsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listExclusionsStream( - request?: protos.google.logging.v2.IListExclusionsRequest, - options?: CallOptions): - Transform{ + request?: protos.google.logging.v2.IListExclusionsRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); const defaultCallSettings = this._defaults['listExclusions']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listExclusions stream %j', request); return this.descriptors.page.listExclusions.createStream( this.innerApiCalls.listExclusions as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listExclusions`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent resource whose exclusions are to be listed. - * - * "projects/[PROJECT_ID]" - * "organizations/[ORGANIZATION_ID]" - * "billingAccounts/[BILLING_ACCOUNT_ID]" - * "folders/[FOLDER_ID]" - * @param {string} [request.pageToken] - * Optional. If present, then retrieve the next batch of results from the - * preceding call to this method. `pageToken` must be the value of - * `nextPageToken` from the previous response. The values of other method - * parameters should be identical to those in the previous call. - * @param {number} [request.pageSize] - * Optional. The maximum number of results to return from this request. - * Non-positive values are ignored. The presence of `nextPageToken` in the - * response indicates that more results might be available. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.logging.v2.LogExclusion|LogExclusion}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v2/config_service_v2.list_exclusions.js - * region_tag:logging_v2_generated_ConfigServiceV2_ListExclusions_async - */ + /** + * Equivalent to `listExclusions`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource whose exclusions are to be listed. + * + * "projects/[PROJECT_ID]" + * "organizations/[ORGANIZATION_ID]" + * "billingAccounts/[BILLING_ACCOUNT_ID]" + * "folders/[FOLDER_ID]" + * @param {string} [request.pageToken] + * Optional. If present, then retrieve the next batch of results from the + * preceding call to this method. `pageToken` must be the value of + * `nextPageToken` from the previous response. The values of other method + * parameters should be identical to those in the previous call. + * @param {number} [request.pageSize] + * Optional. The maximum number of results to return from this request. + * Non-positive values are ignored. The presence of `nextPageToken` in the + * response indicates that more results might be available. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.logging.v2.LogExclusion|LogExclusion}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v2/config_service_v2.list_exclusions.js + * region_tag:logging_v2_generated_ConfigServiceV2_ListExclusions_async + */ listExclusionsAsync( - request?: protos.google.logging.v2.IListExclusionsRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.logging.v2.IListExclusionsRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); const defaultCallSettings = this._defaults['listExclusions']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listExclusions iterate %j', request); return this.descriptors.page.listExclusions.asyncIterate( this.innerApiCalls['listExclusions'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } // -------------------- @@ -3841,7 +4732,7 @@ export class ConfigServiceV2Client { * @param {string} billing_account * @returns {string} Resource name string. */ - billingAccountCmekSettingsPath(billingAccount:string) { + billingAccountCmekSettingsPath(billingAccount: string) { return this.pathTemplates.billingAccountCmekSettingsPathTemplate.render({ billing_account: billingAccount, }); @@ -3854,8 +4745,12 @@ export class ConfigServiceV2Client { * A fully-qualified path representing billing_account_cmekSettings resource. * @returns {string} A string representing the billing_account. */ - matchBillingAccountFromBillingAccountCmekSettingsName(billingAccountCmekSettingsName: string) { - return this.pathTemplates.billingAccountCmekSettingsPathTemplate.match(billingAccountCmekSettingsName).billing_account; + matchBillingAccountFromBillingAccountCmekSettingsName( + billingAccountCmekSettingsName: string, + ) { + return this.pathTemplates.billingAccountCmekSettingsPathTemplate.match( + billingAccountCmekSettingsName, + ).billing_account; } /** @@ -3865,7 +4760,7 @@ export class ConfigServiceV2Client { * @param {string} exclusion * @returns {string} Resource name string. */ - billingAccountExclusionPath(billingAccount:string,exclusion:string) { + billingAccountExclusionPath(billingAccount: string, exclusion: string) { return this.pathTemplates.billingAccountExclusionPathTemplate.render({ billing_account: billingAccount, exclusion: exclusion, @@ -3879,8 +4774,12 @@ export class ConfigServiceV2Client { * A fully-qualified path representing billing_account_exclusion resource. * @returns {string} A string representing the billing_account. */ - matchBillingAccountFromBillingAccountExclusionName(billingAccountExclusionName: string) { - return this.pathTemplates.billingAccountExclusionPathTemplate.match(billingAccountExclusionName).billing_account; + matchBillingAccountFromBillingAccountExclusionName( + billingAccountExclusionName: string, + ) { + return this.pathTemplates.billingAccountExclusionPathTemplate.match( + billingAccountExclusionName, + ).billing_account; } /** @@ -3890,8 +4789,12 @@ export class ConfigServiceV2Client { * A fully-qualified path representing billing_account_exclusion resource. * @returns {string} A string representing the exclusion. */ - matchExclusionFromBillingAccountExclusionName(billingAccountExclusionName: string) { - return this.pathTemplates.billingAccountExclusionPathTemplate.match(billingAccountExclusionName).exclusion; + matchExclusionFromBillingAccountExclusionName( + billingAccountExclusionName: string, + ) { + return this.pathTemplates.billingAccountExclusionPathTemplate.match( + billingAccountExclusionName, + ).exclusion; } /** @@ -3902,7 +4805,11 @@ export class ConfigServiceV2Client { * @param {string} bucket * @returns {string} Resource name string. */ - billingAccountLocationBucketPath(billingAccount:string,location:string,bucket:string) { + billingAccountLocationBucketPath( + billingAccount: string, + location: string, + bucket: string, + ) { return this.pathTemplates.billingAccountLocationBucketPathTemplate.render({ billing_account: billingAccount, location: location, @@ -3917,8 +4824,12 @@ export class ConfigServiceV2Client { * A fully-qualified path representing billing_account_location_bucket resource. * @returns {string} A string representing the billing_account. */ - matchBillingAccountFromBillingAccountLocationBucketName(billingAccountLocationBucketName: string) { - return this.pathTemplates.billingAccountLocationBucketPathTemplate.match(billingAccountLocationBucketName).billing_account; + matchBillingAccountFromBillingAccountLocationBucketName( + billingAccountLocationBucketName: string, + ) { + return this.pathTemplates.billingAccountLocationBucketPathTemplate.match( + billingAccountLocationBucketName, + ).billing_account; } /** @@ -3928,8 +4839,12 @@ export class ConfigServiceV2Client { * A fully-qualified path representing billing_account_location_bucket resource. * @returns {string} A string representing the location. */ - matchLocationFromBillingAccountLocationBucketName(billingAccountLocationBucketName: string) { - return this.pathTemplates.billingAccountLocationBucketPathTemplate.match(billingAccountLocationBucketName).location; + matchLocationFromBillingAccountLocationBucketName( + billingAccountLocationBucketName: string, + ) { + return this.pathTemplates.billingAccountLocationBucketPathTemplate.match( + billingAccountLocationBucketName, + ).location; } /** @@ -3939,8 +4854,12 @@ export class ConfigServiceV2Client { * A fully-qualified path representing billing_account_location_bucket resource. * @returns {string} A string representing the bucket. */ - matchBucketFromBillingAccountLocationBucketName(billingAccountLocationBucketName: string) { - return this.pathTemplates.billingAccountLocationBucketPathTemplate.match(billingAccountLocationBucketName).bucket; + matchBucketFromBillingAccountLocationBucketName( + billingAccountLocationBucketName: string, + ) { + return this.pathTemplates.billingAccountLocationBucketPathTemplate.match( + billingAccountLocationBucketName, + ).bucket; } /** @@ -3952,13 +4871,20 @@ export class ConfigServiceV2Client { * @param {string} view * @returns {string} Resource name string. */ - billingAccountLocationBucketViewPath(billingAccount:string,location:string,bucket:string,view:string) { - return this.pathTemplates.billingAccountLocationBucketViewPathTemplate.render({ - billing_account: billingAccount, - location: location, - bucket: bucket, - view: view, - }); + billingAccountLocationBucketViewPath( + billingAccount: string, + location: string, + bucket: string, + view: string, + ) { + return this.pathTemplates.billingAccountLocationBucketViewPathTemplate.render( + { + billing_account: billingAccount, + location: location, + bucket: bucket, + view: view, + }, + ); } /** @@ -3968,8 +4894,12 @@ export class ConfigServiceV2Client { * A fully-qualified path representing billing_account_location_bucket_view resource. * @returns {string} A string representing the billing_account. */ - matchBillingAccountFromBillingAccountLocationBucketViewName(billingAccountLocationBucketViewName: string) { - return this.pathTemplates.billingAccountLocationBucketViewPathTemplate.match(billingAccountLocationBucketViewName).billing_account; + matchBillingAccountFromBillingAccountLocationBucketViewName( + billingAccountLocationBucketViewName: string, + ) { + return this.pathTemplates.billingAccountLocationBucketViewPathTemplate.match( + billingAccountLocationBucketViewName, + ).billing_account; } /** @@ -3979,8 +4909,12 @@ export class ConfigServiceV2Client { * A fully-qualified path representing billing_account_location_bucket_view resource. * @returns {string} A string representing the location. */ - matchLocationFromBillingAccountLocationBucketViewName(billingAccountLocationBucketViewName: string) { - return this.pathTemplates.billingAccountLocationBucketViewPathTemplate.match(billingAccountLocationBucketViewName).location; + matchLocationFromBillingAccountLocationBucketViewName( + billingAccountLocationBucketViewName: string, + ) { + return this.pathTemplates.billingAccountLocationBucketViewPathTemplate.match( + billingAccountLocationBucketViewName, + ).location; } /** @@ -3990,8 +4924,12 @@ export class ConfigServiceV2Client { * A fully-qualified path representing billing_account_location_bucket_view resource. * @returns {string} A string representing the bucket. */ - matchBucketFromBillingAccountLocationBucketViewName(billingAccountLocationBucketViewName: string) { - return this.pathTemplates.billingAccountLocationBucketViewPathTemplate.match(billingAccountLocationBucketViewName).bucket; + matchBucketFromBillingAccountLocationBucketViewName( + billingAccountLocationBucketViewName: string, + ) { + return this.pathTemplates.billingAccountLocationBucketViewPathTemplate.match( + billingAccountLocationBucketViewName, + ).bucket; } /** @@ -4001,8 +4939,12 @@ export class ConfigServiceV2Client { * A fully-qualified path representing billing_account_location_bucket_view resource. * @returns {string} A string representing the view. */ - matchViewFromBillingAccountLocationBucketViewName(billingAccountLocationBucketViewName: string) { - return this.pathTemplates.billingAccountLocationBucketViewPathTemplate.match(billingAccountLocationBucketViewName).view; + matchViewFromBillingAccountLocationBucketViewName( + billingAccountLocationBucketViewName: string, + ) { + return this.pathTemplates.billingAccountLocationBucketViewPathTemplate.match( + billingAccountLocationBucketViewName, + ).view; } /** @@ -4012,7 +4954,7 @@ export class ConfigServiceV2Client { * @param {string} log * @returns {string} Resource name string. */ - billingAccountLogPath(billingAccount:string,log:string) { + billingAccountLogPath(billingAccount: string, log: string) { return this.pathTemplates.billingAccountLogPathTemplate.render({ billing_account: billingAccount, log: log, @@ -4027,7 +4969,9 @@ export class ConfigServiceV2Client { * @returns {string} A string representing the billing_account. */ matchBillingAccountFromBillingAccountLogName(billingAccountLogName: string) { - return this.pathTemplates.billingAccountLogPathTemplate.match(billingAccountLogName).billing_account; + return this.pathTemplates.billingAccountLogPathTemplate.match( + billingAccountLogName, + ).billing_account; } /** @@ -4038,7 +4982,9 @@ export class ConfigServiceV2Client { * @returns {string} A string representing the log. */ matchLogFromBillingAccountLogName(billingAccountLogName: string) { - return this.pathTemplates.billingAccountLogPathTemplate.match(billingAccountLogName).log; + return this.pathTemplates.billingAccountLogPathTemplate.match( + billingAccountLogName, + ).log; } /** @@ -4047,7 +4993,7 @@ export class ConfigServiceV2Client { * @param {string} billing_account * @returns {string} Resource name string. */ - billingAccountSettingsPath(billingAccount:string) { + billingAccountSettingsPath(billingAccount: string) { return this.pathTemplates.billingAccountSettingsPathTemplate.render({ billing_account: billingAccount, }); @@ -4060,8 +5006,12 @@ export class ConfigServiceV2Client { * A fully-qualified path representing billing_account_settings resource. * @returns {string} A string representing the billing_account. */ - matchBillingAccountFromBillingAccountSettingsName(billingAccountSettingsName: string) { - return this.pathTemplates.billingAccountSettingsPathTemplate.match(billingAccountSettingsName).billing_account; + matchBillingAccountFromBillingAccountSettingsName( + billingAccountSettingsName: string, + ) { + return this.pathTemplates.billingAccountSettingsPathTemplate.match( + billingAccountSettingsName, + ).billing_account; } /** @@ -4071,7 +5021,7 @@ export class ConfigServiceV2Client { * @param {string} sink * @returns {string} Resource name string. */ - billingAccountSinkPath(billingAccount:string,sink:string) { + billingAccountSinkPath(billingAccount: string, sink: string) { return this.pathTemplates.billingAccountSinkPathTemplate.render({ billing_account: billingAccount, sink: sink, @@ -4085,8 +5035,12 @@ export class ConfigServiceV2Client { * A fully-qualified path representing billing_account_sink resource. * @returns {string} A string representing the billing_account. */ - matchBillingAccountFromBillingAccountSinkName(billingAccountSinkName: string) { - return this.pathTemplates.billingAccountSinkPathTemplate.match(billingAccountSinkName).billing_account; + matchBillingAccountFromBillingAccountSinkName( + billingAccountSinkName: string, + ) { + return this.pathTemplates.billingAccountSinkPathTemplate.match( + billingAccountSinkName, + ).billing_account; } /** @@ -4097,7 +5051,9 @@ export class ConfigServiceV2Client { * @returns {string} A string representing the sink. */ matchSinkFromBillingAccountSinkName(billingAccountSinkName: string) { - return this.pathTemplates.billingAccountSinkPathTemplate.match(billingAccountSinkName).sink; + return this.pathTemplates.billingAccountSinkPathTemplate.match( + billingAccountSinkName, + ).sink; } /** @@ -4106,7 +5062,7 @@ export class ConfigServiceV2Client { * @param {string} folder * @returns {string} Resource name string. */ - folderCmekSettingsPath(folder:string) { + folderCmekSettingsPath(folder: string) { return this.pathTemplates.folderCmekSettingsPathTemplate.render({ folder: folder, }); @@ -4120,7 +5076,9 @@ export class ConfigServiceV2Client { * @returns {string} A string representing the folder. */ matchFolderFromFolderCmekSettingsName(folderCmekSettingsName: string) { - return this.pathTemplates.folderCmekSettingsPathTemplate.match(folderCmekSettingsName).folder; + return this.pathTemplates.folderCmekSettingsPathTemplate.match( + folderCmekSettingsName, + ).folder; } /** @@ -4130,7 +5088,7 @@ export class ConfigServiceV2Client { * @param {string} exclusion * @returns {string} Resource name string. */ - folderExclusionPath(folder:string,exclusion:string) { + folderExclusionPath(folder: string, exclusion: string) { return this.pathTemplates.folderExclusionPathTemplate.render({ folder: folder, exclusion: exclusion, @@ -4145,7 +5103,9 @@ export class ConfigServiceV2Client { * @returns {string} A string representing the folder. */ matchFolderFromFolderExclusionName(folderExclusionName: string) { - return this.pathTemplates.folderExclusionPathTemplate.match(folderExclusionName).folder; + return this.pathTemplates.folderExclusionPathTemplate.match( + folderExclusionName, + ).folder; } /** @@ -4156,7 +5116,9 @@ export class ConfigServiceV2Client { * @returns {string} A string representing the exclusion. */ matchExclusionFromFolderExclusionName(folderExclusionName: string) { - return this.pathTemplates.folderExclusionPathTemplate.match(folderExclusionName).exclusion; + return this.pathTemplates.folderExclusionPathTemplate.match( + folderExclusionName, + ).exclusion; } /** @@ -4167,7 +5129,7 @@ export class ConfigServiceV2Client { * @param {string} bucket * @returns {string} Resource name string. */ - folderLocationBucketPath(folder:string,location:string,bucket:string) { + folderLocationBucketPath(folder: string, location: string, bucket: string) { return this.pathTemplates.folderLocationBucketPathTemplate.render({ folder: folder, location: location, @@ -4183,7 +5145,9 @@ export class ConfigServiceV2Client { * @returns {string} A string representing the folder. */ matchFolderFromFolderLocationBucketName(folderLocationBucketName: string) { - return this.pathTemplates.folderLocationBucketPathTemplate.match(folderLocationBucketName).folder; + return this.pathTemplates.folderLocationBucketPathTemplate.match( + folderLocationBucketName, + ).folder; } /** @@ -4194,7 +5158,9 @@ export class ConfigServiceV2Client { * @returns {string} A string representing the location. */ matchLocationFromFolderLocationBucketName(folderLocationBucketName: string) { - return this.pathTemplates.folderLocationBucketPathTemplate.match(folderLocationBucketName).location; + return this.pathTemplates.folderLocationBucketPathTemplate.match( + folderLocationBucketName, + ).location; } /** @@ -4205,7 +5171,9 @@ export class ConfigServiceV2Client { * @returns {string} A string representing the bucket. */ matchBucketFromFolderLocationBucketName(folderLocationBucketName: string) { - return this.pathTemplates.folderLocationBucketPathTemplate.match(folderLocationBucketName).bucket; + return this.pathTemplates.folderLocationBucketPathTemplate.match( + folderLocationBucketName, + ).bucket; } /** @@ -4217,7 +5185,12 @@ export class ConfigServiceV2Client { * @param {string} view * @returns {string} Resource name string. */ - folderLocationBucketViewPath(folder:string,location:string,bucket:string,view:string) { + folderLocationBucketViewPath( + folder: string, + location: string, + bucket: string, + view: string, + ) { return this.pathTemplates.folderLocationBucketViewPathTemplate.render({ folder: folder, location: location, @@ -4233,8 +5206,12 @@ export class ConfigServiceV2Client { * A fully-qualified path representing folder_location_bucket_view resource. * @returns {string} A string representing the folder. */ - matchFolderFromFolderLocationBucketViewName(folderLocationBucketViewName: string) { - return this.pathTemplates.folderLocationBucketViewPathTemplate.match(folderLocationBucketViewName).folder; + matchFolderFromFolderLocationBucketViewName( + folderLocationBucketViewName: string, + ) { + return this.pathTemplates.folderLocationBucketViewPathTemplate.match( + folderLocationBucketViewName, + ).folder; } /** @@ -4244,8 +5221,12 @@ export class ConfigServiceV2Client { * A fully-qualified path representing folder_location_bucket_view resource. * @returns {string} A string representing the location. */ - matchLocationFromFolderLocationBucketViewName(folderLocationBucketViewName: string) { - return this.pathTemplates.folderLocationBucketViewPathTemplate.match(folderLocationBucketViewName).location; + matchLocationFromFolderLocationBucketViewName( + folderLocationBucketViewName: string, + ) { + return this.pathTemplates.folderLocationBucketViewPathTemplate.match( + folderLocationBucketViewName, + ).location; } /** @@ -4255,8 +5236,12 @@ export class ConfigServiceV2Client { * A fully-qualified path representing folder_location_bucket_view resource. * @returns {string} A string representing the bucket. */ - matchBucketFromFolderLocationBucketViewName(folderLocationBucketViewName: string) { - return this.pathTemplates.folderLocationBucketViewPathTemplate.match(folderLocationBucketViewName).bucket; + matchBucketFromFolderLocationBucketViewName( + folderLocationBucketViewName: string, + ) { + return this.pathTemplates.folderLocationBucketViewPathTemplate.match( + folderLocationBucketViewName, + ).bucket; } /** @@ -4266,8 +5251,12 @@ export class ConfigServiceV2Client { * A fully-qualified path representing folder_location_bucket_view resource. * @returns {string} A string representing the view. */ - matchViewFromFolderLocationBucketViewName(folderLocationBucketViewName: string) { - return this.pathTemplates.folderLocationBucketViewPathTemplate.match(folderLocationBucketViewName).view; + matchViewFromFolderLocationBucketViewName( + folderLocationBucketViewName: string, + ) { + return this.pathTemplates.folderLocationBucketViewPathTemplate.match( + folderLocationBucketViewName, + ).view; } /** @@ -4277,7 +5266,7 @@ export class ConfigServiceV2Client { * @param {string} log * @returns {string} Resource name string. */ - folderLogPath(folder:string,log:string) { + folderLogPath(folder: string, log: string) { return this.pathTemplates.folderLogPathTemplate.render({ folder: folder, log: log, @@ -4312,7 +5301,7 @@ export class ConfigServiceV2Client { * @param {string} folder * @returns {string} Resource name string. */ - folderSettingsPath(folder:string) { + folderSettingsPath(folder: string) { return this.pathTemplates.folderSettingsPathTemplate.render({ folder: folder, }); @@ -4326,7 +5315,9 @@ export class ConfigServiceV2Client { * @returns {string} A string representing the folder. */ matchFolderFromFolderSettingsName(folderSettingsName: string) { - return this.pathTemplates.folderSettingsPathTemplate.match(folderSettingsName).folder; + return this.pathTemplates.folderSettingsPathTemplate.match( + folderSettingsName, + ).folder; } /** @@ -4336,7 +5327,7 @@ export class ConfigServiceV2Client { * @param {string} sink * @returns {string} Resource name string. */ - folderSinkPath(folder:string,sink:string) { + folderSinkPath(folder: string, sink: string) { return this.pathTemplates.folderSinkPathTemplate.render({ folder: folder, sink: sink, @@ -4351,7 +5342,8 @@ export class ConfigServiceV2Client { * @returns {string} A string representing the folder. */ matchFolderFromFolderSinkName(folderSinkName: string) { - return this.pathTemplates.folderSinkPathTemplate.match(folderSinkName).folder; + return this.pathTemplates.folderSinkPathTemplate.match(folderSinkName) + .folder; } /** @@ -4372,7 +5364,7 @@ export class ConfigServiceV2Client { * @param {string} location * @returns {string} Resource name string. */ - locationPath(project:string,location:string) { + locationPath(project: string, location: string) { return this.pathTemplates.locationPathTemplate.render({ project: project, location: location, @@ -4408,7 +5400,7 @@ export class ConfigServiceV2Client { * @param {string} metric * @returns {string} Resource name string. */ - logMetricPath(project:string,metric:string) { + logMetricPath(project: string, metric: string) { return this.pathTemplates.logMetricPathTemplate.render({ project: project, metric: metric, @@ -4423,7 +5415,8 @@ export class ConfigServiceV2Client { * @returns {string} A string representing the project. */ matchProjectFromLogMetricName(logMetricName: string) { - return this.pathTemplates.logMetricPathTemplate.match(logMetricName).project; + return this.pathTemplates.logMetricPathTemplate.match(logMetricName) + .project; } /** @@ -4443,7 +5436,7 @@ export class ConfigServiceV2Client { * @param {string} organization * @returns {string} Resource name string. */ - organizationCmekSettingsPath(organization:string) { + organizationCmekSettingsPath(organization: string) { return this.pathTemplates.organizationCmekSettingsPathTemplate.render({ organization: organization, }); @@ -4456,8 +5449,12 @@ export class ConfigServiceV2Client { * A fully-qualified path representing organization_cmekSettings resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationCmekSettingsName(organizationCmekSettingsName: string) { - return this.pathTemplates.organizationCmekSettingsPathTemplate.match(organizationCmekSettingsName).organization; + matchOrganizationFromOrganizationCmekSettingsName( + organizationCmekSettingsName: string, + ) { + return this.pathTemplates.organizationCmekSettingsPathTemplate.match( + organizationCmekSettingsName, + ).organization; } /** @@ -4467,7 +5464,7 @@ export class ConfigServiceV2Client { * @param {string} exclusion * @returns {string} Resource name string. */ - organizationExclusionPath(organization:string,exclusion:string) { + organizationExclusionPath(organization: string, exclusion: string) { return this.pathTemplates.organizationExclusionPathTemplate.render({ organization: organization, exclusion: exclusion, @@ -4481,8 +5478,12 @@ export class ConfigServiceV2Client { * A fully-qualified path representing organization_exclusion resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationExclusionName(organizationExclusionName: string) { - return this.pathTemplates.organizationExclusionPathTemplate.match(organizationExclusionName).organization; + matchOrganizationFromOrganizationExclusionName( + organizationExclusionName: string, + ) { + return this.pathTemplates.organizationExclusionPathTemplate.match( + organizationExclusionName, + ).organization; } /** @@ -4492,8 +5493,12 @@ export class ConfigServiceV2Client { * A fully-qualified path representing organization_exclusion resource. * @returns {string} A string representing the exclusion. */ - matchExclusionFromOrganizationExclusionName(organizationExclusionName: string) { - return this.pathTemplates.organizationExclusionPathTemplate.match(organizationExclusionName).exclusion; + matchExclusionFromOrganizationExclusionName( + organizationExclusionName: string, + ) { + return this.pathTemplates.organizationExclusionPathTemplate.match( + organizationExclusionName, + ).exclusion; } /** @@ -4504,7 +5509,11 @@ export class ConfigServiceV2Client { * @param {string} bucket * @returns {string} Resource name string. */ - organizationLocationBucketPath(organization:string,location:string,bucket:string) { + organizationLocationBucketPath( + organization: string, + location: string, + bucket: string, + ) { return this.pathTemplates.organizationLocationBucketPathTemplate.render({ organization: organization, location: location, @@ -4519,8 +5528,12 @@ export class ConfigServiceV2Client { * A fully-qualified path representing organization_location_bucket resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationLocationBucketName(organizationLocationBucketName: string) { - return this.pathTemplates.organizationLocationBucketPathTemplate.match(organizationLocationBucketName).organization; + matchOrganizationFromOrganizationLocationBucketName( + organizationLocationBucketName: string, + ) { + return this.pathTemplates.organizationLocationBucketPathTemplate.match( + organizationLocationBucketName, + ).organization; } /** @@ -4530,8 +5543,12 @@ export class ConfigServiceV2Client { * A fully-qualified path representing organization_location_bucket resource. * @returns {string} A string representing the location. */ - matchLocationFromOrganizationLocationBucketName(organizationLocationBucketName: string) { - return this.pathTemplates.organizationLocationBucketPathTemplate.match(organizationLocationBucketName).location; + matchLocationFromOrganizationLocationBucketName( + organizationLocationBucketName: string, + ) { + return this.pathTemplates.organizationLocationBucketPathTemplate.match( + organizationLocationBucketName, + ).location; } /** @@ -4541,8 +5558,12 @@ export class ConfigServiceV2Client { * A fully-qualified path representing organization_location_bucket resource. * @returns {string} A string representing the bucket. */ - matchBucketFromOrganizationLocationBucketName(organizationLocationBucketName: string) { - return this.pathTemplates.organizationLocationBucketPathTemplate.match(organizationLocationBucketName).bucket; + matchBucketFromOrganizationLocationBucketName( + organizationLocationBucketName: string, + ) { + return this.pathTemplates.organizationLocationBucketPathTemplate.match( + organizationLocationBucketName, + ).bucket; } /** @@ -4554,13 +5575,20 @@ export class ConfigServiceV2Client { * @param {string} view * @returns {string} Resource name string. */ - organizationLocationBucketViewPath(organization:string,location:string,bucket:string,view:string) { - return this.pathTemplates.organizationLocationBucketViewPathTemplate.render({ - organization: organization, - location: location, - bucket: bucket, - view: view, - }); + organizationLocationBucketViewPath( + organization: string, + location: string, + bucket: string, + view: string, + ) { + return this.pathTemplates.organizationLocationBucketViewPathTemplate.render( + { + organization: organization, + location: location, + bucket: bucket, + view: view, + }, + ); } /** @@ -4570,8 +5598,12 @@ export class ConfigServiceV2Client { * A fully-qualified path representing organization_location_bucket_view resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationLocationBucketViewName(organizationLocationBucketViewName: string) { - return this.pathTemplates.organizationLocationBucketViewPathTemplate.match(organizationLocationBucketViewName).organization; + matchOrganizationFromOrganizationLocationBucketViewName( + organizationLocationBucketViewName: string, + ) { + return this.pathTemplates.organizationLocationBucketViewPathTemplate.match( + organizationLocationBucketViewName, + ).organization; } /** @@ -4581,8 +5613,12 @@ export class ConfigServiceV2Client { * A fully-qualified path representing organization_location_bucket_view resource. * @returns {string} A string representing the location. */ - matchLocationFromOrganizationLocationBucketViewName(organizationLocationBucketViewName: string) { - return this.pathTemplates.organizationLocationBucketViewPathTemplate.match(organizationLocationBucketViewName).location; + matchLocationFromOrganizationLocationBucketViewName( + organizationLocationBucketViewName: string, + ) { + return this.pathTemplates.organizationLocationBucketViewPathTemplate.match( + organizationLocationBucketViewName, + ).location; } /** @@ -4592,8 +5628,12 @@ export class ConfigServiceV2Client { * A fully-qualified path representing organization_location_bucket_view resource. * @returns {string} A string representing the bucket. */ - matchBucketFromOrganizationLocationBucketViewName(organizationLocationBucketViewName: string) { - return this.pathTemplates.organizationLocationBucketViewPathTemplate.match(organizationLocationBucketViewName).bucket; + matchBucketFromOrganizationLocationBucketViewName( + organizationLocationBucketViewName: string, + ) { + return this.pathTemplates.organizationLocationBucketViewPathTemplate.match( + organizationLocationBucketViewName, + ).bucket; } /** @@ -4603,8 +5643,12 @@ export class ConfigServiceV2Client { * A fully-qualified path representing organization_location_bucket_view resource. * @returns {string} A string representing the view. */ - matchViewFromOrganizationLocationBucketViewName(organizationLocationBucketViewName: string) { - return this.pathTemplates.organizationLocationBucketViewPathTemplate.match(organizationLocationBucketViewName).view; + matchViewFromOrganizationLocationBucketViewName( + organizationLocationBucketViewName: string, + ) { + return this.pathTemplates.organizationLocationBucketViewPathTemplate.match( + organizationLocationBucketViewName, + ).view; } /** @@ -4614,7 +5658,7 @@ export class ConfigServiceV2Client { * @param {string} log * @returns {string} Resource name string. */ - organizationLogPath(organization:string,log:string) { + organizationLogPath(organization: string, log: string) { return this.pathTemplates.organizationLogPathTemplate.render({ organization: organization, log: log, @@ -4629,7 +5673,9 @@ export class ConfigServiceV2Client { * @returns {string} A string representing the organization. */ matchOrganizationFromOrganizationLogName(organizationLogName: string) { - return this.pathTemplates.organizationLogPathTemplate.match(organizationLogName).organization; + return this.pathTemplates.organizationLogPathTemplate.match( + organizationLogName, + ).organization; } /** @@ -4640,7 +5686,9 @@ export class ConfigServiceV2Client { * @returns {string} A string representing the log. */ matchLogFromOrganizationLogName(organizationLogName: string) { - return this.pathTemplates.organizationLogPathTemplate.match(organizationLogName).log; + return this.pathTemplates.organizationLogPathTemplate.match( + organizationLogName, + ).log; } /** @@ -4649,7 +5697,7 @@ export class ConfigServiceV2Client { * @param {string} organization * @returns {string} Resource name string. */ - organizationSettingsPath(organization:string) { + organizationSettingsPath(organization: string) { return this.pathTemplates.organizationSettingsPathTemplate.render({ organization: organization, }); @@ -4662,8 +5710,12 @@ export class ConfigServiceV2Client { * A fully-qualified path representing organization_settings resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationSettingsName(organizationSettingsName: string) { - return this.pathTemplates.organizationSettingsPathTemplate.match(organizationSettingsName).organization; + matchOrganizationFromOrganizationSettingsName( + organizationSettingsName: string, + ) { + return this.pathTemplates.organizationSettingsPathTemplate.match( + organizationSettingsName, + ).organization; } /** @@ -4673,7 +5725,7 @@ export class ConfigServiceV2Client { * @param {string} sink * @returns {string} Resource name string. */ - organizationSinkPath(organization:string,sink:string) { + organizationSinkPath(organization: string, sink: string) { return this.pathTemplates.organizationSinkPathTemplate.render({ organization: organization, sink: sink, @@ -4688,7 +5740,9 @@ export class ConfigServiceV2Client { * @returns {string} A string representing the organization. */ matchOrganizationFromOrganizationSinkName(organizationSinkName: string) { - return this.pathTemplates.organizationSinkPathTemplate.match(organizationSinkName).organization; + return this.pathTemplates.organizationSinkPathTemplate.match( + organizationSinkName, + ).organization; } /** @@ -4699,7 +5753,9 @@ export class ConfigServiceV2Client { * @returns {string} A string representing the sink. */ matchSinkFromOrganizationSinkName(organizationSinkName: string) { - return this.pathTemplates.organizationSinkPathTemplate.match(organizationSinkName).sink; + return this.pathTemplates.organizationSinkPathTemplate.match( + organizationSinkName, + ).sink; } /** @@ -4708,7 +5764,7 @@ export class ConfigServiceV2Client { * @param {string} project * @returns {string} Resource name string. */ - projectPath(project:string) { + projectPath(project: string) { return this.pathTemplates.projectPathTemplate.render({ project: project, }); @@ -4731,7 +5787,7 @@ export class ConfigServiceV2Client { * @param {string} project * @returns {string} Resource name string. */ - projectCmekSettingsPath(project:string) { + projectCmekSettingsPath(project: string) { return this.pathTemplates.projectCmekSettingsPathTemplate.render({ project: project, }); @@ -4745,7 +5801,9 @@ export class ConfigServiceV2Client { * @returns {string} A string representing the project. */ matchProjectFromProjectCmekSettingsName(projectCmekSettingsName: string) { - return this.pathTemplates.projectCmekSettingsPathTemplate.match(projectCmekSettingsName).project; + return this.pathTemplates.projectCmekSettingsPathTemplate.match( + projectCmekSettingsName, + ).project; } /** @@ -4755,7 +5813,7 @@ export class ConfigServiceV2Client { * @param {string} exclusion * @returns {string} Resource name string. */ - projectExclusionPath(project:string,exclusion:string) { + projectExclusionPath(project: string, exclusion: string) { return this.pathTemplates.projectExclusionPathTemplate.render({ project: project, exclusion: exclusion, @@ -4770,7 +5828,9 @@ export class ConfigServiceV2Client { * @returns {string} A string representing the project. */ matchProjectFromProjectExclusionName(projectExclusionName: string) { - return this.pathTemplates.projectExclusionPathTemplate.match(projectExclusionName).project; + return this.pathTemplates.projectExclusionPathTemplate.match( + projectExclusionName, + ).project; } /** @@ -4781,7 +5841,9 @@ export class ConfigServiceV2Client { * @returns {string} A string representing the exclusion. */ matchExclusionFromProjectExclusionName(projectExclusionName: string) { - return this.pathTemplates.projectExclusionPathTemplate.match(projectExclusionName).exclusion; + return this.pathTemplates.projectExclusionPathTemplate.match( + projectExclusionName, + ).exclusion; } /** @@ -4792,7 +5854,7 @@ export class ConfigServiceV2Client { * @param {string} bucket * @returns {string} Resource name string. */ - projectLocationBucketPath(project:string,location:string,bucket:string) { + projectLocationBucketPath(project: string, location: string, bucket: string) { return this.pathTemplates.projectLocationBucketPathTemplate.render({ project: project, location: location, @@ -4808,7 +5870,9 @@ export class ConfigServiceV2Client { * @returns {string} A string representing the project. */ matchProjectFromProjectLocationBucketName(projectLocationBucketName: string) { - return this.pathTemplates.projectLocationBucketPathTemplate.match(projectLocationBucketName).project; + return this.pathTemplates.projectLocationBucketPathTemplate.match( + projectLocationBucketName, + ).project; } /** @@ -4818,8 +5882,12 @@ export class ConfigServiceV2Client { * A fully-qualified path representing project_location_bucket resource. * @returns {string} A string representing the location. */ - matchLocationFromProjectLocationBucketName(projectLocationBucketName: string) { - return this.pathTemplates.projectLocationBucketPathTemplate.match(projectLocationBucketName).location; + matchLocationFromProjectLocationBucketName( + projectLocationBucketName: string, + ) { + return this.pathTemplates.projectLocationBucketPathTemplate.match( + projectLocationBucketName, + ).location; } /** @@ -4830,7 +5898,9 @@ export class ConfigServiceV2Client { * @returns {string} A string representing the bucket. */ matchBucketFromProjectLocationBucketName(projectLocationBucketName: string) { - return this.pathTemplates.projectLocationBucketPathTemplate.match(projectLocationBucketName).bucket; + return this.pathTemplates.projectLocationBucketPathTemplate.match( + projectLocationBucketName, + ).bucket; } /** @@ -4842,7 +5912,12 @@ export class ConfigServiceV2Client { * @param {string} view * @returns {string} Resource name string. */ - projectLocationBucketViewPath(project:string,location:string,bucket:string,view:string) { + projectLocationBucketViewPath( + project: string, + location: string, + bucket: string, + view: string, + ) { return this.pathTemplates.projectLocationBucketViewPathTemplate.render({ project: project, location: location, @@ -4858,8 +5933,12 @@ export class ConfigServiceV2Client { * A fully-qualified path representing project_location_bucket_view resource. * @returns {string} A string representing the project. */ - matchProjectFromProjectLocationBucketViewName(projectLocationBucketViewName: string) { - return this.pathTemplates.projectLocationBucketViewPathTemplate.match(projectLocationBucketViewName).project; + matchProjectFromProjectLocationBucketViewName( + projectLocationBucketViewName: string, + ) { + return this.pathTemplates.projectLocationBucketViewPathTemplate.match( + projectLocationBucketViewName, + ).project; } /** @@ -4869,8 +5948,12 @@ export class ConfigServiceV2Client { * A fully-qualified path representing project_location_bucket_view resource. * @returns {string} A string representing the location. */ - matchLocationFromProjectLocationBucketViewName(projectLocationBucketViewName: string) { - return this.pathTemplates.projectLocationBucketViewPathTemplate.match(projectLocationBucketViewName).location; + matchLocationFromProjectLocationBucketViewName( + projectLocationBucketViewName: string, + ) { + return this.pathTemplates.projectLocationBucketViewPathTemplate.match( + projectLocationBucketViewName, + ).location; } /** @@ -4880,8 +5963,12 @@ export class ConfigServiceV2Client { * A fully-qualified path representing project_location_bucket_view resource. * @returns {string} A string representing the bucket. */ - matchBucketFromProjectLocationBucketViewName(projectLocationBucketViewName: string) { - return this.pathTemplates.projectLocationBucketViewPathTemplate.match(projectLocationBucketViewName).bucket; + matchBucketFromProjectLocationBucketViewName( + projectLocationBucketViewName: string, + ) { + return this.pathTemplates.projectLocationBucketViewPathTemplate.match( + projectLocationBucketViewName, + ).bucket; } /** @@ -4891,8 +5978,12 @@ export class ConfigServiceV2Client { * A fully-qualified path representing project_location_bucket_view resource. * @returns {string} A string representing the view. */ - matchViewFromProjectLocationBucketViewName(projectLocationBucketViewName: string) { - return this.pathTemplates.projectLocationBucketViewPathTemplate.match(projectLocationBucketViewName).view; + matchViewFromProjectLocationBucketViewName( + projectLocationBucketViewName: string, + ) { + return this.pathTemplates.projectLocationBucketViewPathTemplate.match( + projectLocationBucketViewName, + ).view; } /** @@ -4902,7 +5993,7 @@ export class ConfigServiceV2Client { * @param {string} log * @returns {string} Resource name string. */ - projectLogPath(project:string,log:string) { + projectLogPath(project: string, log: string) { return this.pathTemplates.projectLogPathTemplate.render({ project: project, log: log, @@ -4917,7 +6008,8 @@ export class ConfigServiceV2Client { * @returns {string} A string representing the project. */ matchProjectFromProjectLogName(projectLogName: string) { - return this.pathTemplates.projectLogPathTemplate.match(projectLogName).project; + return this.pathTemplates.projectLogPathTemplate.match(projectLogName) + .project; } /** @@ -4937,7 +6029,7 @@ export class ConfigServiceV2Client { * @param {string} project * @returns {string} Resource name string. */ - projectSettingsPath(project:string) { + projectSettingsPath(project: string) { return this.pathTemplates.projectSettingsPathTemplate.render({ project: project, }); @@ -4951,7 +6043,9 @@ export class ConfigServiceV2Client { * @returns {string} A string representing the project. */ matchProjectFromProjectSettingsName(projectSettingsName: string) { - return this.pathTemplates.projectSettingsPathTemplate.match(projectSettingsName).project; + return this.pathTemplates.projectSettingsPathTemplate.match( + projectSettingsName, + ).project; } /** @@ -4961,7 +6055,7 @@ export class ConfigServiceV2Client { * @param {string} sink * @returns {string} Resource name string. */ - projectSinkPath(project:string,sink:string) { + projectSinkPath(project: string, sink: string) { return this.pathTemplates.projectSinkPathTemplate.render({ project: project, sink: sink, @@ -4976,7 +6070,8 @@ export class ConfigServiceV2Client { * @returns {string} A string representing the project. */ matchProjectFromProjectSinkName(projectSinkName: string) { - return this.pathTemplates.projectSinkPathTemplate.match(projectSinkName).project; + return this.pathTemplates.projectSinkPathTemplate.match(projectSinkName) + .project; } /** @@ -4987,7 +6082,8 @@ export class ConfigServiceV2Client { * @returns {string} A string representing the sink. */ matchSinkFromProjectSinkName(projectSinkName: string) { - return this.pathTemplates.projectSinkPathTemplate.match(projectSinkName).sink; + return this.pathTemplates.projectSinkPathTemplate.match(projectSinkName) + .sink; } /** @@ -4998,7 +6094,7 @@ export class ConfigServiceV2Client { */ close(): Promise { if (this.configServiceV2Stub && !this._terminated) { - return this.configServiceV2Stub.then(stub => { + return this.configServiceV2Stub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -5007,4 +6103,4 @@ export class ConfigServiceV2Client { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/core/generator/gapic-generator-typescript/baselines/logging-esm/esm/src/v2/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/logging-esm/esm/src/v2/index.ts.baseline index 4dd29130988d..d3c68de72129 100644 --- a/core/generator/gapic-generator-typescript/baselines/logging-esm/esm/src/v2/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/logging-esm/esm/src/v2/index.ts.baseline @@ -16,6 +16,6 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -export {ConfigServiceV2Client} from './config_service_v2_client.js'; -export {LoggingServiceV2Client} from './logging_service_v2_client.js'; -export {MetricsServiceV2Client} from './metrics_service_v2_client.js'; +export { ConfigServiceV2Client } from './config_service_v2_client.js'; +export { LoggingServiceV2Client } from './logging_service_v2_client.js'; +export { MetricsServiceV2Client } from './metrics_service_v2_client.js'; diff --git a/core/generator/gapic-generator-typescript/baselines/logging-esm/esm/src/v2/logging_service_v2_client.ts.baseline b/core/generator/gapic-generator-typescript/baselines/logging-esm/esm/src/v2/logging_service_v2_client.ts.baseline index 5da76945a799..67c1c6a3e0c5 100644 --- a/core/generator/gapic-generator-typescript/baselines/logging-esm/esm/src/v2/logging_service_v2_client.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/logging-esm/esm/src/v2/logging_service_v2_client.ts.baseline @@ -18,15 +18,22 @@ /* global window */ import * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions, PaginationCallback, GaxCall} from 'google-gax'; -import {Transform, PassThrough} from 'stream'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + PaginationCallback, + GaxCall, +} from 'google-gax'; +import { Transform, PassThrough } from 'stream'; // @ts-ignore import type * as protos from '../../../protos/protos.js'; import * as logging_service_v2_client_config from './logging_service_v2_client_config.json'; import fs from 'fs'; import path from 'path'; -import {fileURLToPath} from 'url'; -import {getJSON} from '../json-helper.cjs'; +import { fileURLToPath } from 'url'; +import { getJSON } from '../json-helper.cjs'; // @ts-ignore const dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -36,15 +43,15 @@ const dirname = path.dirname(fileURLToPath(import.meta.url)); * This file defines retry strategy and timeouts for all API methods in this library. */ const gapicConfig = getJSON( - path.join(dirname, 'logging_service_v2_client_config.json') + path.join(dirname, 'logging_service_v2_client_config.json'), ); const jsonProtos = getJSON( - path.join(dirname, '..', '..', '..', 'protos/protos.json') + path.join(dirname, '..', '..', '..', 'protos/protos.json'), ); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; const version = getJSON( - path.join(dirname, '..', '..', '..', '..', 'package.json') + path.join(dirname, '..', '..', '..', '..', 'package.json'), ).version; /** @@ -59,7 +66,7 @@ export class LoggingServiceV2Client { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('logging'); @@ -71,9 +78,9 @@ export class LoggingServiceV2Client { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; - loggingServiceV2Stub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; + loggingServiceV2Stub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of LoggingServiceV2Client. @@ -115,21 +122,42 @@ export class LoggingServiceV2Client { * const client = new LoggingServiceV2Client({fallback: 'rest'}, gax); * ``` */ - constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { // Ensure that options include all the required fields. const staticMembers = this.constructor as typeof LoggingServiceV2Client; - if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { - throw new Error('Please set either universe_domain or universeDomain, but not both.'); + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); } - const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; - this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; this._servicePath = 'logging.' + this._universeDomain; - const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; - const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. if (servicePath !== this._servicePath && !('scopes' in opts)) { @@ -151,7 +179,7 @@ export class LoggingServiceV2Client { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; @@ -168,10 +196,7 @@ export class LoggingServiceV2Client { const isEsm = true; const isEsmString = isEsm ? '-esm' : '-cjs'; // Determine the client header string. - const clientHeader = [ - `gax/${this._gaxModule.version}`, - `gapic/${version}`, - ]; + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/{process.versions.node}${isEsmString}`); } else { @@ -179,7 +204,7 @@ export class LoggingServiceV2Client { } if (!opts.fallback) { clientHeader.push(`grpc/${this._gaxGrpc.grpcVersion}`); - } else if (opts.fallback === 'rest' ) { + } else if (opts.fallback === 'rest') { clientHeader.push(`rest/${this._gaxGrpc.grpcVersion}`); } if (opts.libName && opts.libVersion) { @@ -187,101 +212,106 @@ export class LoggingServiceV2Client { } // Load the applicable protos. - this._protos = this._gaxGrpc.loadProtoJSON(jsonProtos as gax.protobuf.INamespace); + this._protos = this._gaxGrpc.loadProtoJSON( + jsonProtos as gax.protobuf.INamespace, + ); // This API contains "path templates"; forward-slash-separated // identifiers to uniquely identify resources within the API. // Create useful helper objects for these. this.pathTemplates = { billingAccountCmekSettingsPathTemplate: new this._gaxModule.PathTemplate( - 'billingAccounts/{billing_account}/cmekSettings' + 'billingAccounts/{billing_account}/cmekSettings', ), billingAccountExclusionPathTemplate: new this._gaxModule.PathTemplate( - 'billingAccounts/{billing_account}/exclusions/{exclusion}' - ), - billingAccountLocationBucketPathTemplate: new this._gaxModule.PathTemplate( - 'billingAccounts/{billing_account}/locations/{location}/buckets/{bucket}' - ), - billingAccountLocationBucketViewPathTemplate: new this._gaxModule.PathTemplate( - 'billingAccounts/{billing_account}/locations/{location}/buckets/{bucket}/views/{view}' + 'billingAccounts/{billing_account}/exclusions/{exclusion}', ), + billingAccountLocationBucketPathTemplate: + new this._gaxModule.PathTemplate( + 'billingAccounts/{billing_account}/locations/{location}/buckets/{bucket}', + ), + billingAccountLocationBucketViewPathTemplate: + new this._gaxModule.PathTemplate( + 'billingAccounts/{billing_account}/locations/{location}/buckets/{bucket}/views/{view}', + ), billingAccountLogPathTemplate: new this._gaxModule.PathTemplate( - 'billingAccounts/{billing_account}/logs/{log}' + 'billingAccounts/{billing_account}/logs/{log}', ), billingAccountSettingsPathTemplate: new this._gaxModule.PathTemplate( - 'billingAccounts/{billing_account}/settings' + 'billingAccounts/{billing_account}/settings', ), billingAccountSinkPathTemplate: new this._gaxModule.PathTemplate( - 'billingAccounts/{billing_account}/sinks/{sink}' + 'billingAccounts/{billing_account}/sinks/{sink}', ), folderCmekSettingsPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/cmekSettings' + 'folders/{folder}/cmekSettings', ), folderExclusionPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/exclusions/{exclusion}' + 'folders/{folder}/exclusions/{exclusion}', ), folderLocationBucketPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/locations/{location}/buckets/{bucket}' + 'folders/{folder}/locations/{location}/buckets/{bucket}', ), folderLocationBucketViewPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/locations/{location}/buckets/{bucket}/views/{view}' + 'folders/{folder}/locations/{location}/buckets/{bucket}/views/{view}', ), folderLogPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/logs/{log}' + 'folders/{folder}/logs/{log}', ), folderSettingsPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/settings' + 'folders/{folder}/settings', ), folderSinkPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/sinks/{sink}' + 'folders/{folder}/sinks/{sink}', ), logMetricPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/metrics/{metric}' + 'projects/{project}/metrics/{metric}', ), organizationCmekSettingsPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/cmekSettings' + 'organizations/{organization}/cmekSettings', ), organizationExclusionPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/exclusions/{exclusion}' + 'organizations/{organization}/exclusions/{exclusion}', ), organizationLocationBucketPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/locations/{location}/buckets/{bucket}' - ), - organizationLocationBucketViewPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/locations/{location}/buckets/{bucket}/views/{view}' + 'organizations/{organization}/locations/{location}/buckets/{bucket}', ), + organizationLocationBucketViewPathTemplate: + new this._gaxModule.PathTemplate( + 'organizations/{organization}/locations/{location}/buckets/{bucket}/views/{view}', + ), organizationLogPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/logs/{log}' + 'organizations/{organization}/logs/{log}', ), organizationSettingsPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/settings' + 'organizations/{organization}/settings', ), organizationSinkPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/sinks/{sink}' + 'organizations/{organization}/sinks/{sink}', ), projectPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}' + 'projects/{project}', ), projectCmekSettingsPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/cmekSettings' + 'projects/{project}/cmekSettings', ), projectExclusionPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/exclusions/{exclusion}' + 'projects/{project}/exclusions/{exclusion}', ), projectLocationBucketPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/buckets/{bucket}' + 'projects/{project}/locations/{location}/buckets/{bucket}', ), projectLocationBucketViewPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/buckets/{bucket}/views/{view}' + 'projects/{project}/locations/{location}/buckets/{bucket}/views/{view}', ), projectLogPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/logs/{log}' + 'projects/{project}/logs/{log}', ), projectSettingsPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/settings' + 'projects/{project}/settings', ), projectSinkPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/sinks/{sink}' + 'projects/{project}/sinks/{sink}', ), }; @@ -289,18 +319,31 @@ export class LoggingServiceV2Client { // (e.g. 50 results at a time, with tokens to get subsequent // pages). Denote the keys used for pagination and results. this.descriptors.page = { - listLogEntries: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'entries'), - listMonitoredResourceDescriptors: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'resourceDescriptors'), - listLogs: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'logNames') + listLogEntries: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'entries', + ), + listMonitoredResourceDescriptors: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'resourceDescriptors', + ), + listLogs: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'logNames', + ), }; // Some of the methods on this service provide streaming responses. // Provide descriptors for these. this.descriptors.stream = { - tailLogEntries: new this._gaxModule.StreamDescriptor(this._gaxModule.StreamType.BIDI_STREAMING, !!opts.fallback, !!opts.gaxServerStreamingRetries) + tailLogEntries: new this._gaxModule.StreamDescriptor( + this._gaxModule.StreamType.BIDI_STREAMING, + !!opts.fallback, + !!opts.gaxServerStreamingRetries, + ), }; const protoFilesRoot = this._gaxModule.protobufFromJSON(jsonProtos); @@ -310,19 +353,22 @@ export class LoggingServiceV2Client { this.descriptors.batching = { writeLogEntries: new this._gaxModule.BundleDescriptor( 'entries', - ['log_name','resource','labels'], + ['log_name', 'resource', 'labels'], null, this._gaxModule.GrpcClient.createByteLengthFunction( // eslint-disable-next-line @typescript-eslint/no-explicit-any - protoFilesRoot.lookupType('google.logging.v2.LogEntry') as any - ) + protoFilesRoot.lookupType('google.logging.v2.LogEntry') as any, + ), ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.logging.v2.LoggingServiceV2', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.logging.v2.LoggingServiceV2', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + { 'x-goog-api-client': clientHeader.join(' ') }, + ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -353,35 +399,52 @@ export class LoggingServiceV2Client { // Put together the "service stub" for // google.logging.v2.LoggingServiceV2. this.loggingServiceV2Stub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.logging.v2.LoggingServiceV2') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.logging.v2.LoggingServiceV2', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.logging.v2.LoggingServiceV2, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts, + this._providedCustomServicePath, + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const loggingServiceV2StubMethods = - ['deleteLog', 'writeLogEntries', 'listLogEntries', 'listMonitoredResourceDescriptors', 'listLogs', 'tailLogEntries']; + const loggingServiceV2StubMethods = [ + 'deleteLog', + 'writeLogEntries', + 'listLogEntries', + 'listMonitoredResourceDescriptors', + 'listLogs', + 'tailLogEntries', + ]; for (const methodName of loggingServiceV2StubMethods) { const callPromise = this.loggingServiceV2Stub.then( - stub => (...args: Array<{}>) => { - if (this._terminated) { - if (methodName in this.descriptors.stream) { - const stream = new PassThrough({objectMode: true}); - setImmediate(() => { - stream.emit('error', new this._gaxModule.GoogleError('The client has already been closed.')); - }); - return stream; + (stub) => + (...args: Array<{}>) => { + if (this._terminated) { + if (methodName in this.descriptors.stream) { + const stream = new PassThrough({ objectMode: true }); + setImmediate(() => { + stream.emit( + 'error', + new this._gaxModule.GoogleError( + 'The client has already been closed.', + ), + ); + }); + return stream; + } + return Promise.reject('The client has already been closed.'); } - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error|null|undefined) => () => { + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { throw err; - }); + }, + ); const descriptor = this.descriptors.page[methodName] || @@ -392,7 +455,7 @@ export class LoggingServiceV2Client { callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -407,8 +470,14 @@ export class LoggingServiceV2Client { * @returns {string} The DNS address for this service. */ static get servicePath() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'logging.googleapis.com'; } @@ -420,8 +489,14 @@ export class LoggingServiceV2Client { * @returns {string} The DNS address for this service. */ static get apiEndpoint() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'logging.googleapis.com'; } @@ -457,7 +532,7 @@ export class LoggingServiceV2Client { 'https://www.googleapis.com/auth/cloud-platform.read-only', 'https://www.googleapis.com/auth/logging.admin', 'https://www.googleapis.com/auth/logging.read', - 'https://www.googleapis.com/auth/logging.write' + 'https://www.googleapis.com/auth/logging.write', ]; } @@ -467,8 +542,9 @@ export class LoggingServiceV2Client { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId(callback?: Callback): - Promise|void { + getProjectId( + callback?: Callback, + ): Promise | void { if (callback) { this.auth.getProjectId(callback); return; @@ -479,412 +555,491 @@ export class LoggingServiceV2Client { // ------------------- // -- Service calls -- // ------------------- -/** - * Deletes all the log entries in a log for the _Default Log Bucket. The log - * reappears if it receives new entries. Log entries written shortly before - * the delete operation might not be deleted. Entries received after the - * delete operation with a timestamp before the operation will be deleted. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.logName - * Required. The resource name of the log to delete: - * - * * `projects/[PROJECT_ID]/logs/[LOG_ID]` - * * `organizations/[ORGANIZATION_ID]/logs/[LOG_ID]` - * * `billingAccounts/[BILLING_ACCOUNT_ID]/logs/[LOG_ID]` - * * `folders/[FOLDER_ID]/logs/[LOG_ID]` - * - * `[LOG_ID]` must be URL-encoded. For example, - * `"projects/my-project-id/logs/syslog"`, - * `"organizations/123/logs/cloudaudit.googleapis.com%2Factivity"`. - * - * For more information about log names, see - * {@link protos.google.logging.v2.LogEntry|LogEntry}. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/logging_service_v2.delete_log.js - * region_tag:logging_v2_generated_LoggingServiceV2_DeleteLog_async - */ + /** + * Deletes all the log entries in a log for the _Default Log Bucket. The log + * reappears if it receives new entries. Log entries written shortly before + * the delete operation might not be deleted. Entries received after the + * delete operation with a timestamp before the operation will be deleted. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.logName + * Required. The resource name of the log to delete: + * + * * `projects/[PROJECT_ID]/logs/[LOG_ID]` + * * `organizations/[ORGANIZATION_ID]/logs/[LOG_ID]` + * * `billingAccounts/[BILLING_ACCOUNT_ID]/logs/[LOG_ID]` + * * `folders/[FOLDER_ID]/logs/[LOG_ID]` + * + * `[LOG_ID]` must be URL-encoded. For example, + * `"projects/my-project-id/logs/syslog"`, + * `"organizations/123/logs/cloudaudit.googleapis.com%2Factivity"`. + * + * For more information about log names, see + * {@link protos.google.logging.v2.LogEntry|LogEntry}. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/logging_service_v2.delete_log.js + * region_tag:logging_v2_generated_LoggingServiceV2_DeleteLog_async + */ deleteLog( - request?: protos.google.logging.v2.IDeleteLogRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.logging.v2.IDeleteLogRequest|undefined, {}|undefined - ]>; + request?: protos.google.logging.v2.IDeleteLogRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.logging.v2.IDeleteLogRequest | undefined, + {} | undefined, + ] + >; deleteLog( - request: protos.google.logging.v2.IDeleteLogRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.logging.v2.IDeleteLogRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.logging.v2.IDeleteLogRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.logging.v2.IDeleteLogRequest | null | undefined, + {} | null | undefined + >, + ): void; deleteLog( - request: protos.google.logging.v2.IDeleteLogRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.logging.v2.IDeleteLogRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.logging.v2.IDeleteLogRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.logging.v2.IDeleteLogRequest | null | undefined, + {} | null | undefined + >, + ): void; deleteLog( - request?: protos.google.logging.v2.IDeleteLogRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.protobuf.IEmpty, - protos.google.logging.v2.IDeleteLogRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.logging.v2.IDeleteLogRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.logging.v2.IDeleteLogRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.logging.v2.IDeleteLogRequest|undefined, {}|undefined - ]>|void { + protos.google.logging.v2.IDeleteLogRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + protos.google.logging.v2.IDeleteLogRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.logging.v2.IDeleteLogRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'log_name': request.logName ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + log_name: request.logName ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('deleteLog request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.logging.v2.IDeleteLogRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + protos.google.logging.v2.IDeleteLogRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteLog response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.deleteLog(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.logging.v2.IDeleteLogRequest|undefined, {}|undefined - ]) => { - this._log.info('deleteLog response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteLog(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.logging.v2.IDeleteLogRequest | undefined, + {} | undefined, + ]) => { + this._log.info('deleteLog response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Writes log entries to Logging. This API method is the - * only way to send log entries to Logging. This method - * is used, directly or indirectly, by the Logging agent - * (fluentd) and all logging libraries configured to use Logging. - * A single request may contain log entries for a maximum of 1000 - * different resources (projects, organizations, billing accounts or - * folders) - * - * @param {Object} request - * The request object that will be sent. - * @param {string} [request.logName] - * Optional. A default log resource name that is assigned to all log entries - * in `entries` that do not specify a value for `log_name`: - * - * * `projects/[PROJECT_ID]/logs/[LOG_ID]` - * * `organizations/[ORGANIZATION_ID]/logs/[LOG_ID]` - * * `billingAccounts/[BILLING_ACCOUNT_ID]/logs/[LOG_ID]` - * * `folders/[FOLDER_ID]/logs/[LOG_ID]` - * - * `[LOG_ID]` must be URL-encoded. For example: - * - * "projects/my-project-id/logs/syslog" - * "organizations/123/logs/cloudaudit.googleapis.com%2Factivity" - * - * The permission `logging.logEntries.create` is needed on each project, - * organization, billing account, or folder that is receiving new log - * entries, whether the resource is specified in `logName` or in an - * individual log entry. - * @param {google.api.MonitoredResource} [request.resource] - * Optional. A default monitored resource object that is assigned to all log - * entries in `entries` that do not specify a value for `resource`. Example: - * - * { "type": "gce_instance", - * "labels": { - * "zone": "us-central1-a", "instance_id": "00000000000000000000" }} - * - * See {@link protos.google.logging.v2.LogEntry|LogEntry}. - * @param {number[]} [request.labels] - * Optional. Default labels that are added to the `labels` field of all log - * entries in `entries`. If a log entry already has a label with the same key - * as a label in this parameter, then the log entry's label is not changed. - * See {@link protos.google.logging.v2.LogEntry|LogEntry}. - * @param {number[]} request.entries - * Required. The log entries to send to Logging. The order of log - * entries in this list does not matter. Values supplied in this method's - * `log_name`, `resource`, and `labels` fields are copied into those log - * entries in this list that do not include values for their corresponding - * fields. For more information, see the - * {@link protos.google.logging.v2.LogEntry|LogEntry} type. - * - * If the `timestamp` or `insert_id` fields are missing in log entries, then - * this method supplies the current time or a unique identifier, respectively. - * The supplied values are chosen so that, among the log entries that did not - * supply their own values, the entries earlier in the list will sort before - * the entries later in the list. See the `entries.list` method. - * - * Log entries with timestamps that are more than the - * [logs retention period](https://cloud.google.com/logging/quotas) in - * the past or more than 24 hours in the future will not be available when - * calling `entries.list`. However, those log entries can still be [exported - * with - * LogSinks](https://cloud.google.com/logging/docs/api/tasks/exporting-logs). - * - * To improve throughput and to avoid exceeding the - * [quota limit](https://cloud.google.com/logging/quotas) for calls to - * `entries.write`, you should try to include several log entries in this - * list, rather than calling this method for each individual log entry. - * @param {boolean} [request.partialSuccess] - * Optional. Whether valid entries should be written even if some other - * entries fail due to INVALID_ARGUMENT or PERMISSION_DENIED errors. If any - * entry is not written, then the response status is the error associated - * with one of the failed entries and the response includes error details - * keyed by the entries' zero-based index in the `entries.write` method. - * @param {boolean} [request.dryRun] - * Optional. If true, the request should expect normal response, but the - * entries won't be persisted nor exported. Useful for checking whether the - * logging API endpoints are working properly before sending valuable data. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.logging.v2.WriteLogEntriesResponse|WriteLogEntriesResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/logging_service_v2.write_log_entries.js - * region_tag:logging_v2_generated_LoggingServiceV2_WriteLogEntries_async - */ + /** + * Writes log entries to Logging. This API method is the + * only way to send log entries to Logging. This method + * is used, directly or indirectly, by the Logging agent + * (fluentd) and all logging libraries configured to use Logging. + * A single request may contain log entries for a maximum of 1000 + * different resources (projects, organizations, billing accounts or + * folders) + * + * @param {Object} request + * The request object that will be sent. + * @param {string} [request.logName] + * Optional. A default log resource name that is assigned to all log entries + * in `entries` that do not specify a value for `log_name`: + * + * * `projects/[PROJECT_ID]/logs/[LOG_ID]` + * * `organizations/[ORGANIZATION_ID]/logs/[LOG_ID]` + * * `billingAccounts/[BILLING_ACCOUNT_ID]/logs/[LOG_ID]` + * * `folders/[FOLDER_ID]/logs/[LOG_ID]` + * + * `[LOG_ID]` must be URL-encoded. For example: + * + * "projects/my-project-id/logs/syslog" + * "organizations/123/logs/cloudaudit.googleapis.com%2Factivity" + * + * The permission `logging.logEntries.create` is needed on each project, + * organization, billing account, or folder that is receiving new log + * entries, whether the resource is specified in `logName` or in an + * individual log entry. + * @param {google.api.MonitoredResource} [request.resource] + * Optional. A default monitored resource object that is assigned to all log + * entries in `entries` that do not specify a value for `resource`. Example: + * + * { "type": "gce_instance", + * "labels": { + * "zone": "us-central1-a", "instance_id": "00000000000000000000" }} + * + * See {@link protos.google.logging.v2.LogEntry|LogEntry}. + * @param {number[]} [request.labels] + * Optional. Default labels that are added to the `labels` field of all log + * entries in `entries`. If a log entry already has a label with the same key + * as a label in this parameter, then the log entry's label is not changed. + * See {@link protos.google.logging.v2.LogEntry|LogEntry}. + * @param {number[]} request.entries + * Required. The log entries to send to Logging. The order of log + * entries in this list does not matter. Values supplied in this method's + * `log_name`, `resource`, and `labels` fields are copied into those log + * entries in this list that do not include values for their corresponding + * fields. For more information, see the + * {@link protos.google.logging.v2.LogEntry|LogEntry} type. + * + * If the `timestamp` or `insert_id` fields are missing in log entries, then + * this method supplies the current time or a unique identifier, respectively. + * The supplied values are chosen so that, among the log entries that did not + * supply their own values, the entries earlier in the list will sort before + * the entries later in the list. See the `entries.list` method. + * + * Log entries with timestamps that are more than the + * [logs retention period](https://cloud.google.com/logging/quotas) in + * the past or more than 24 hours in the future will not be available when + * calling `entries.list`. However, those log entries can still be [exported + * with + * LogSinks](https://cloud.google.com/logging/docs/api/tasks/exporting-logs). + * + * To improve throughput and to avoid exceeding the + * [quota limit](https://cloud.google.com/logging/quotas) for calls to + * `entries.write`, you should try to include several log entries in this + * list, rather than calling this method for each individual log entry. + * @param {boolean} [request.partialSuccess] + * Optional. Whether valid entries should be written even if some other + * entries fail due to INVALID_ARGUMENT or PERMISSION_DENIED errors. If any + * entry is not written, then the response status is the error associated + * with one of the failed entries and the response includes error details + * keyed by the entries' zero-based index in the `entries.write` method. + * @param {boolean} [request.dryRun] + * Optional. If true, the request should expect normal response, but the + * entries won't be persisted nor exported. Useful for checking whether the + * logging API endpoints are working properly before sending valuable data. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.logging.v2.WriteLogEntriesResponse|WriteLogEntriesResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/logging_service_v2.write_log_entries.js + * region_tag:logging_v2_generated_LoggingServiceV2_WriteLogEntries_async + */ writeLogEntries( - request?: protos.google.logging.v2.IWriteLogEntriesRequest, - options?: CallOptions): - Promise<[ - protos.google.logging.v2.IWriteLogEntriesResponse, - protos.google.logging.v2.IWriteLogEntriesRequest|undefined, {}|undefined - ]>; + request?: protos.google.logging.v2.IWriteLogEntriesRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.logging.v2.IWriteLogEntriesResponse, + protos.google.logging.v2.IWriteLogEntriesRequest | undefined, + {} | undefined, + ] + >; writeLogEntries( - request: protos.google.logging.v2.IWriteLogEntriesRequest, - options: CallOptions, - callback: Callback< - protos.google.logging.v2.IWriteLogEntriesResponse, - protos.google.logging.v2.IWriteLogEntriesRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.logging.v2.IWriteLogEntriesRequest, + options: CallOptions, + callback: Callback< + protos.google.logging.v2.IWriteLogEntriesResponse, + protos.google.logging.v2.IWriteLogEntriesRequest | null | undefined, + {} | null | undefined + >, + ): void; writeLogEntries( - request: protos.google.logging.v2.IWriteLogEntriesRequest, - callback: Callback< - protos.google.logging.v2.IWriteLogEntriesResponse, - protos.google.logging.v2.IWriteLogEntriesRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.logging.v2.IWriteLogEntriesRequest, + callback: Callback< + protos.google.logging.v2.IWriteLogEntriesResponse, + protos.google.logging.v2.IWriteLogEntriesRequest | null | undefined, + {} | null | undefined + >, + ): void; writeLogEntries( - request?: protos.google.logging.v2.IWriteLogEntriesRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.logging.v2.IWriteLogEntriesResponse, - protos.google.logging.v2.IWriteLogEntriesRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.logging.v2.IWriteLogEntriesRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.logging.v2.IWriteLogEntriesResponse, - protos.google.logging.v2.IWriteLogEntriesRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.logging.v2.IWriteLogEntriesResponse, - protos.google.logging.v2.IWriteLogEntriesRequest|undefined, {}|undefined - ]>|void { + protos.google.logging.v2.IWriteLogEntriesRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.logging.v2.IWriteLogEntriesResponse, + protos.google.logging.v2.IWriteLogEntriesRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.logging.v2.IWriteLogEntriesResponse, + protos.google.logging.v2.IWriteLogEntriesRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('writeLogEntries request %j', request); - const wrappedCallback: Callback< - protos.google.logging.v2.IWriteLogEntriesResponse, - protos.google.logging.v2.IWriteLogEntriesRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.logging.v2.IWriteLogEntriesResponse, + protos.google.logging.v2.IWriteLogEntriesRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('writeLogEntries response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.writeLogEntries(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.logging.v2.IWriteLogEntriesResponse, - protos.google.logging.v2.IWriteLogEntriesRequest|undefined, {}|undefined - ]) => { - this._log.info('writeLogEntries response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .writeLogEntries(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.logging.v2.IWriteLogEntriesResponse, + protos.google.logging.v2.IWriteLogEntriesRequest | undefined, + {} | undefined, + ]) => { + this._log.info('writeLogEntries response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Streaming read of log entries as they are ingested. Until the stream is - * terminated, it will continue reading logs. - * - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which is both readable and writable. It accepts objects - * representing {@link protos.google.logging.v2.TailLogEntriesRequest|TailLogEntriesRequest} for write() method, and - * will emit objects representing {@link protos.google.logging.v2.TailLogEntriesResponse|TailLogEntriesResponse} on 'data' event asynchronously. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#bi-directional-streaming | documentation } - * for more details and examples. - * @example include:samples/generated/v2/logging_service_v2.tail_log_entries.js - * region_tag:logging_v2_generated_LoggingServiceV2_TailLogEntries_async - */ - tailLogEntries( - options?: CallOptions): - gax.CancellableStream { - this.initialize().catch(err => {throw err}); + /** + * Streaming read of log entries as they are ingested. Until the stream is + * terminated, it will continue reading logs. + * + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which is both readable and writable. It accepts objects + * representing {@link protos.google.logging.v2.TailLogEntriesRequest|TailLogEntriesRequest} for write() method, and + * will emit objects representing {@link protos.google.logging.v2.TailLogEntriesResponse|TailLogEntriesResponse} on 'data' event asynchronously. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#bi-directional-streaming | documentation } + * for more details and examples. + * @example include:samples/generated/v2/logging_service_v2.tail_log_entries.js + * region_tag:logging_v2_generated_LoggingServiceV2_TailLogEntries_async + */ + tailLogEntries(options?: CallOptions): gax.CancellableStream { + this.initialize().catch((err) => { + throw err; + }); this._log.info('tailLogEntries stream %j', options); return this.innerApiCalls.tailLogEntries(null, options); } - /** - * Lists log entries. Use this method to retrieve log entries that originated - * from a project/folder/organization/billing account. For ways to export log - * entries, see [Exporting - * Logs](https://cloud.google.com/logging/docs/export). - * - * @param {Object} request - * The request object that will be sent. - * @param {string[]} request.resourceNames - * Required. Names of one or more parent resources from which to - * retrieve log entries: - * - * * `projects/[PROJECT_ID]` - * * `organizations/[ORGANIZATION_ID]` - * * `billingAccounts/[BILLING_ACCOUNT_ID]` - * * `folders/[FOLDER_ID]` - * - * May alternatively be one or more views: - * - * * `projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]` - * * `organizations/[ORGANIZATION_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]` - * * `billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]` - * * `folders/[FOLDER_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]` - * - * Projects listed in the `project_ids` field are added to this list. - * @param {string} [request.filter] - * Optional. A filter that chooses which log entries to return. See [Advanced - * Logs Queries](https://cloud.google.com/logging/docs/view/advanced-queries). - * Only log entries that match the filter are returned. An empty filter - * matches all log entries in the resources listed in `resource_names`. - * Referencing a parent resource that is not listed in `resource_names` will - * cause the filter to return no results. The maximum length of the filter is - * 20000 characters. - * @param {string} [request.orderBy] - * Optional. How the results should be sorted. Presently, the only permitted - * values are `"timestamp asc"` (default) and `"timestamp desc"`. The first - * option returns entries in order of increasing values of - * `LogEntry.timestamp` (oldest first), and the second option returns entries - * in order of decreasing timestamps (newest first). Entries with equal - * timestamps are returned in order of their `insert_id` values. - * @param {number} [request.pageSize] - * Optional. The maximum number of results to return from this request. Default is 50. - * If the value is negative or exceeds 1000, the request is rejected. The - * presence of `next_page_token` in the response indicates that more results - * might be available. - * @param {string} [request.pageToken] - * Optional. If present, then retrieve the next batch of results from the - * preceding call to this method. `page_token` must be the value of - * `next_page_token` from the previous response. The values of other method - * parameters should be identical to those in the previous call. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.logging.v2.LogEntry|LogEntry}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `listLogEntriesAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Lists log entries. Use this method to retrieve log entries that originated + * from a project/folder/organization/billing account. For ways to export log + * entries, see [Exporting + * Logs](https://cloud.google.com/logging/docs/export). + * + * @param {Object} request + * The request object that will be sent. + * @param {string[]} request.resourceNames + * Required. Names of one or more parent resources from which to + * retrieve log entries: + * + * * `projects/[PROJECT_ID]` + * * `organizations/[ORGANIZATION_ID]` + * * `billingAccounts/[BILLING_ACCOUNT_ID]` + * * `folders/[FOLDER_ID]` + * + * May alternatively be one or more views: + * + * * `projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]` + * * `organizations/[ORGANIZATION_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]` + * * `billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]` + * * `folders/[FOLDER_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]` + * + * Projects listed in the `project_ids` field are added to this list. + * @param {string} [request.filter] + * Optional. A filter that chooses which log entries to return. See [Advanced + * Logs Queries](https://cloud.google.com/logging/docs/view/advanced-queries). + * Only log entries that match the filter are returned. An empty filter + * matches all log entries in the resources listed in `resource_names`. + * Referencing a parent resource that is not listed in `resource_names` will + * cause the filter to return no results. The maximum length of the filter is + * 20000 characters. + * @param {string} [request.orderBy] + * Optional. How the results should be sorted. Presently, the only permitted + * values are `"timestamp asc"` (default) and `"timestamp desc"`. The first + * option returns entries in order of increasing values of + * `LogEntry.timestamp` (oldest first), and the second option returns entries + * in order of decreasing timestamps (newest first). Entries with equal + * timestamps are returned in order of their `insert_id` values. + * @param {number} [request.pageSize] + * Optional. The maximum number of results to return from this request. Default is 50. + * If the value is negative or exceeds 1000, the request is rejected. The + * presence of `next_page_token` in the response indicates that more results + * might be available. + * @param {string} [request.pageToken] + * Optional. If present, then retrieve the next batch of results from the + * preceding call to this method. `page_token` must be the value of + * `next_page_token` from the previous response. The values of other method + * parameters should be identical to those in the previous call. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.logging.v2.LogEntry|LogEntry}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listLogEntriesAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listLogEntries( - request?: protos.google.logging.v2.IListLogEntriesRequest, - options?: CallOptions): - Promise<[ - protos.google.logging.v2.ILogEntry[], - protos.google.logging.v2.IListLogEntriesRequest|null, - protos.google.logging.v2.IListLogEntriesResponse - ]>; + request?: protos.google.logging.v2.IListLogEntriesRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.logging.v2.ILogEntry[], + protos.google.logging.v2.IListLogEntriesRequest | null, + protos.google.logging.v2.IListLogEntriesResponse, + ] + >; listLogEntries( - request: protos.google.logging.v2.IListLogEntriesRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.logging.v2.IListLogEntriesRequest, - protos.google.logging.v2.IListLogEntriesResponse|null|undefined, - protos.google.logging.v2.ILogEntry>): void; + request: protos.google.logging.v2.IListLogEntriesRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.logging.v2.IListLogEntriesRequest, + protos.google.logging.v2.IListLogEntriesResponse | null | undefined, + protos.google.logging.v2.ILogEntry + >, + ): void; listLogEntries( - request: protos.google.logging.v2.IListLogEntriesRequest, - callback: PaginationCallback< - protos.google.logging.v2.IListLogEntriesRequest, - protos.google.logging.v2.IListLogEntriesResponse|null|undefined, - protos.google.logging.v2.ILogEntry>): void; + request: protos.google.logging.v2.IListLogEntriesRequest, + callback: PaginationCallback< + protos.google.logging.v2.IListLogEntriesRequest, + protos.google.logging.v2.IListLogEntriesResponse | null | undefined, + protos.google.logging.v2.ILogEntry + >, + ): void; listLogEntries( - request?: protos.google.logging.v2.IListLogEntriesRequest, - optionsOrCallback?: CallOptions|PaginationCallback< + request?: protos.google.logging.v2.IListLogEntriesRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.logging.v2.IListLogEntriesRequest, - protos.google.logging.v2.IListLogEntriesResponse|null|undefined, - protos.google.logging.v2.ILogEntry>, - callback?: PaginationCallback< - protos.google.logging.v2.IListLogEntriesRequest, - protos.google.logging.v2.IListLogEntriesResponse|null|undefined, - protos.google.logging.v2.ILogEntry>): - Promise<[ - protos.google.logging.v2.ILogEntry[], - protos.google.logging.v2.IListLogEntriesRequest|null, - protos.google.logging.v2.IListLogEntriesResponse - ]>|void { + protos.google.logging.v2.IListLogEntriesResponse | null | undefined, + protos.google.logging.v2.ILogEntry + >, + callback?: PaginationCallback< + protos.google.logging.v2.IListLogEntriesRequest, + protos.google.logging.v2.IListLogEntriesResponse | null | undefined, + protos.google.logging.v2.ILogEntry + >, + ): Promise< + [ + protos.google.logging.v2.ILogEntry[], + protos.google.logging.v2.IListLogEntriesRequest | null, + protos.google.logging.v2.IListLogEntriesResponse, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.logging.v2.IListLogEntriesRequest, - protos.google.logging.v2.IListLogEntriesResponse|null|undefined, - protos.google.logging.v2.ILogEntry>|undefined = callback + this.initialize().catch((err) => { + throw err; + }); + const wrappedCallback: + | PaginationCallback< + protos.google.logging.v2.IListLogEntriesRequest, + protos.google.logging.v2.IListLogEntriesResponse | null | undefined, + protos.google.logging.v2.ILogEntry + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listLogEntries values %j', values); callback!(error, values, nextPageRequest, rawResponse); @@ -893,249 +1048,281 @@ export class LoggingServiceV2Client { this._log.info('listLogEntries request %j', request); return this.innerApiCalls .listLogEntries(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.logging.v2.ILogEntry[], - protos.google.logging.v2.IListLogEntriesRequest|null, - protos.google.logging.v2.IListLogEntriesResponse - ]) => { - this._log.info('listLogEntries values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.logging.v2.ILogEntry[], + protos.google.logging.v2.IListLogEntriesRequest | null, + protos.google.logging.v2.IListLogEntriesResponse, + ]) => { + this._log.info('listLogEntries values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listLogEntries`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string[]} request.resourceNames - * Required. Names of one or more parent resources from which to - * retrieve log entries: - * - * * `projects/[PROJECT_ID]` - * * `organizations/[ORGANIZATION_ID]` - * * `billingAccounts/[BILLING_ACCOUNT_ID]` - * * `folders/[FOLDER_ID]` - * - * May alternatively be one or more views: - * - * * `projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]` - * * `organizations/[ORGANIZATION_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]` - * * `billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]` - * * `folders/[FOLDER_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]` - * - * Projects listed in the `project_ids` field are added to this list. - * @param {string} [request.filter] - * Optional. A filter that chooses which log entries to return. See [Advanced - * Logs Queries](https://cloud.google.com/logging/docs/view/advanced-queries). - * Only log entries that match the filter are returned. An empty filter - * matches all log entries in the resources listed in `resource_names`. - * Referencing a parent resource that is not listed in `resource_names` will - * cause the filter to return no results. The maximum length of the filter is - * 20000 characters. - * @param {string} [request.orderBy] - * Optional. How the results should be sorted. Presently, the only permitted - * values are `"timestamp asc"` (default) and `"timestamp desc"`. The first - * option returns entries in order of increasing values of - * `LogEntry.timestamp` (oldest first), and the second option returns entries - * in order of decreasing timestamps (newest first). Entries with equal - * timestamps are returned in order of their `insert_id` values. - * @param {number} [request.pageSize] - * Optional. The maximum number of results to return from this request. Default is 50. - * If the value is negative or exceeds 1000, the request is rejected. The - * presence of `next_page_token` in the response indicates that more results - * might be available. - * @param {string} [request.pageToken] - * Optional. If present, then retrieve the next batch of results from the - * preceding call to this method. `page_token` must be the value of - * `next_page_token` from the previous response. The values of other method - * parameters should be identical to those in the previous call. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.logging.v2.LogEntry|LogEntry} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `listLogEntriesAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `listLogEntries`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string[]} request.resourceNames + * Required. Names of one or more parent resources from which to + * retrieve log entries: + * + * * `projects/[PROJECT_ID]` + * * `organizations/[ORGANIZATION_ID]` + * * `billingAccounts/[BILLING_ACCOUNT_ID]` + * * `folders/[FOLDER_ID]` + * + * May alternatively be one or more views: + * + * * `projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]` + * * `organizations/[ORGANIZATION_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]` + * * `billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]` + * * `folders/[FOLDER_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]` + * + * Projects listed in the `project_ids` field are added to this list. + * @param {string} [request.filter] + * Optional. A filter that chooses which log entries to return. See [Advanced + * Logs Queries](https://cloud.google.com/logging/docs/view/advanced-queries). + * Only log entries that match the filter are returned. An empty filter + * matches all log entries in the resources listed in `resource_names`. + * Referencing a parent resource that is not listed in `resource_names` will + * cause the filter to return no results. The maximum length of the filter is + * 20000 characters. + * @param {string} [request.orderBy] + * Optional. How the results should be sorted. Presently, the only permitted + * values are `"timestamp asc"` (default) and `"timestamp desc"`. The first + * option returns entries in order of increasing values of + * `LogEntry.timestamp` (oldest first), and the second option returns entries + * in order of decreasing timestamps (newest first). Entries with equal + * timestamps are returned in order of their `insert_id` values. + * @param {number} [request.pageSize] + * Optional. The maximum number of results to return from this request. Default is 50. + * If the value is negative or exceeds 1000, the request is rejected. The + * presence of `next_page_token` in the response indicates that more results + * might be available. + * @param {string} [request.pageToken] + * Optional. If present, then retrieve the next batch of results from the + * preceding call to this method. `page_token` must be the value of + * `next_page_token` from the previous response. The values of other method + * parameters should be identical to those in the previous call. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.logging.v2.LogEntry|LogEntry} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listLogEntriesAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listLogEntriesStream( - request?: protos.google.logging.v2.IListLogEntriesRequest, - options?: CallOptions): - Transform{ + request?: protos.google.logging.v2.IListLogEntriesRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; const defaultCallSettings = this._defaults['listLogEntries']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listLogEntries stream %j', request); return this.descriptors.page.listLogEntries.createStream( this.innerApiCalls.listLogEntries as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listLogEntries`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {string[]} request.resourceNames - * Required. Names of one or more parent resources from which to - * retrieve log entries: - * - * * `projects/[PROJECT_ID]` - * * `organizations/[ORGANIZATION_ID]` - * * `billingAccounts/[BILLING_ACCOUNT_ID]` - * * `folders/[FOLDER_ID]` - * - * May alternatively be one or more views: - * - * * `projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]` - * * `organizations/[ORGANIZATION_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]` - * * `billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]` - * * `folders/[FOLDER_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]` - * - * Projects listed in the `project_ids` field are added to this list. - * @param {string} [request.filter] - * Optional. A filter that chooses which log entries to return. See [Advanced - * Logs Queries](https://cloud.google.com/logging/docs/view/advanced-queries). - * Only log entries that match the filter are returned. An empty filter - * matches all log entries in the resources listed in `resource_names`. - * Referencing a parent resource that is not listed in `resource_names` will - * cause the filter to return no results. The maximum length of the filter is - * 20000 characters. - * @param {string} [request.orderBy] - * Optional. How the results should be sorted. Presently, the only permitted - * values are `"timestamp asc"` (default) and `"timestamp desc"`. The first - * option returns entries in order of increasing values of - * `LogEntry.timestamp` (oldest first), and the second option returns entries - * in order of decreasing timestamps (newest first). Entries with equal - * timestamps are returned in order of their `insert_id` values. - * @param {number} [request.pageSize] - * Optional. The maximum number of results to return from this request. Default is 50. - * If the value is negative or exceeds 1000, the request is rejected. The - * presence of `next_page_token` in the response indicates that more results - * might be available. - * @param {string} [request.pageToken] - * Optional. If present, then retrieve the next batch of results from the - * preceding call to this method. `page_token` must be the value of - * `next_page_token` from the previous response. The values of other method - * parameters should be identical to those in the previous call. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.logging.v2.LogEntry|LogEntry}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v2/logging_service_v2.list_log_entries.js - * region_tag:logging_v2_generated_LoggingServiceV2_ListLogEntries_async - */ + /** + * Equivalent to `listLogEntries`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string[]} request.resourceNames + * Required. Names of one or more parent resources from which to + * retrieve log entries: + * + * * `projects/[PROJECT_ID]` + * * `organizations/[ORGANIZATION_ID]` + * * `billingAccounts/[BILLING_ACCOUNT_ID]` + * * `folders/[FOLDER_ID]` + * + * May alternatively be one or more views: + * + * * `projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]` + * * `organizations/[ORGANIZATION_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]` + * * `billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]` + * * `folders/[FOLDER_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]` + * + * Projects listed in the `project_ids` field are added to this list. + * @param {string} [request.filter] + * Optional. A filter that chooses which log entries to return. See [Advanced + * Logs Queries](https://cloud.google.com/logging/docs/view/advanced-queries). + * Only log entries that match the filter are returned. An empty filter + * matches all log entries in the resources listed in `resource_names`. + * Referencing a parent resource that is not listed in `resource_names` will + * cause the filter to return no results. The maximum length of the filter is + * 20000 characters. + * @param {string} [request.orderBy] + * Optional. How the results should be sorted. Presently, the only permitted + * values are `"timestamp asc"` (default) and `"timestamp desc"`. The first + * option returns entries in order of increasing values of + * `LogEntry.timestamp` (oldest first), and the second option returns entries + * in order of decreasing timestamps (newest first). Entries with equal + * timestamps are returned in order of their `insert_id` values. + * @param {number} [request.pageSize] + * Optional. The maximum number of results to return from this request. Default is 50. + * If the value is negative or exceeds 1000, the request is rejected. The + * presence of `next_page_token` in the response indicates that more results + * might be available. + * @param {string} [request.pageToken] + * Optional. If present, then retrieve the next batch of results from the + * preceding call to this method. `page_token` must be the value of + * `next_page_token` from the previous response. The values of other method + * parameters should be identical to those in the previous call. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.logging.v2.LogEntry|LogEntry}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v2/logging_service_v2.list_log_entries.js + * region_tag:logging_v2_generated_LoggingServiceV2_ListLogEntries_async + */ listLogEntriesAsync( - request?: protos.google.logging.v2.IListLogEntriesRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.logging.v2.IListLogEntriesRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; const defaultCallSettings = this._defaults['listLogEntries']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listLogEntries iterate %j', request); return this.descriptors.page.listLogEntries.asyncIterate( this.innerApiCalls['listLogEntries'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } - /** - * Lists the descriptors for monitored resource types used by Logging. - * - * @param {Object} request - * The request object that will be sent. - * @param {number} [request.pageSize] - * Optional. The maximum number of results to return from this request. - * Non-positive values are ignored. The presence of `nextPageToken` in the - * response indicates that more results might be available. - * @param {string} [request.pageToken] - * Optional. If present, then retrieve the next batch of results from the - * preceding call to this method. `pageToken` must be the value of - * `nextPageToken` from the previous response. The values of other method - * parameters should be identical to those in the previous call. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.api.MonitoredResourceDescriptor|MonitoredResourceDescriptor}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `listMonitoredResourceDescriptorsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Lists the descriptors for monitored resource types used by Logging. + * + * @param {Object} request + * The request object that will be sent. + * @param {number} [request.pageSize] + * Optional. The maximum number of results to return from this request. + * Non-positive values are ignored. The presence of `nextPageToken` in the + * response indicates that more results might be available. + * @param {string} [request.pageToken] + * Optional. If present, then retrieve the next batch of results from the + * preceding call to this method. `pageToken` must be the value of + * `nextPageToken` from the previous response. The values of other method + * parameters should be identical to those in the previous call. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.api.MonitoredResourceDescriptor|MonitoredResourceDescriptor}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listMonitoredResourceDescriptorsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listMonitoredResourceDescriptors( - request?: protos.google.logging.v2.IListMonitoredResourceDescriptorsRequest, - options?: CallOptions): - Promise<[ - protos.google.api.IMonitoredResourceDescriptor[], - protos.google.logging.v2.IListMonitoredResourceDescriptorsRequest|null, - protos.google.logging.v2.IListMonitoredResourceDescriptorsResponse - ]>; + request?: protos.google.logging.v2.IListMonitoredResourceDescriptorsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.api.IMonitoredResourceDescriptor[], + protos.google.logging.v2.IListMonitoredResourceDescriptorsRequest | null, + protos.google.logging.v2.IListMonitoredResourceDescriptorsResponse, + ] + >; listMonitoredResourceDescriptors( - request: protos.google.logging.v2.IListMonitoredResourceDescriptorsRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.logging.v2.IListMonitoredResourceDescriptorsRequest, - protos.google.logging.v2.IListMonitoredResourceDescriptorsResponse|null|undefined, - protos.google.api.IMonitoredResourceDescriptor>): void; + request: protos.google.logging.v2.IListMonitoredResourceDescriptorsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.logging.v2.IListMonitoredResourceDescriptorsRequest, + | protos.google.logging.v2.IListMonitoredResourceDescriptorsResponse + | null + | undefined, + protos.google.api.IMonitoredResourceDescriptor + >, + ): void; listMonitoredResourceDescriptors( - request: protos.google.logging.v2.IListMonitoredResourceDescriptorsRequest, - callback: PaginationCallback< - protos.google.logging.v2.IListMonitoredResourceDescriptorsRequest, - protos.google.logging.v2.IListMonitoredResourceDescriptorsResponse|null|undefined, - protos.google.api.IMonitoredResourceDescriptor>): void; + request: protos.google.logging.v2.IListMonitoredResourceDescriptorsRequest, + callback: PaginationCallback< + protos.google.logging.v2.IListMonitoredResourceDescriptorsRequest, + | protos.google.logging.v2.IListMonitoredResourceDescriptorsResponse + | null + | undefined, + protos.google.api.IMonitoredResourceDescriptor + >, + ): void; listMonitoredResourceDescriptors( - request?: protos.google.logging.v2.IListMonitoredResourceDescriptorsRequest, - optionsOrCallback?: CallOptions|PaginationCallback< + request?: protos.google.logging.v2.IListMonitoredResourceDescriptorsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.logging.v2.IListMonitoredResourceDescriptorsRequest, - protos.google.logging.v2.IListMonitoredResourceDescriptorsResponse|null|undefined, - protos.google.api.IMonitoredResourceDescriptor>, - callback?: PaginationCallback< - protos.google.logging.v2.IListMonitoredResourceDescriptorsRequest, - protos.google.logging.v2.IListMonitoredResourceDescriptorsResponse|null|undefined, - protos.google.api.IMonitoredResourceDescriptor>): - Promise<[ - protos.google.api.IMonitoredResourceDescriptor[], - protos.google.logging.v2.IListMonitoredResourceDescriptorsRequest|null, - protos.google.logging.v2.IListMonitoredResourceDescriptorsResponse - ]>|void { + | protos.google.logging.v2.IListMonitoredResourceDescriptorsResponse + | null + | undefined, + protos.google.api.IMonitoredResourceDescriptor + >, + callback?: PaginationCallback< + protos.google.logging.v2.IListMonitoredResourceDescriptorsRequest, + | protos.google.logging.v2.IListMonitoredResourceDescriptorsResponse + | null + | undefined, + protos.google.api.IMonitoredResourceDescriptor + >, + ): Promise< + [ + protos.google.api.IMonitoredResourceDescriptor[], + protos.google.logging.v2.IListMonitoredResourceDescriptorsRequest | null, + protos.google.logging.v2.IListMonitoredResourceDescriptorsResponse, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.logging.v2.IListMonitoredResourceDescriptorsRequest, - protos.google.logging.v2.IListMonitoredResourceDescriptorsResponse|null|undefined, - protos.google.api.IMonitoredResourceDescriptor>|undefined = callback + this.initialize().catch((err) => { + throw err; + }); + const wrappedCallback: + | PaginationCallback< + protos.google.logging.v2.IListMonitoredResourceDescriptorsRequest, + | protos.google.logging.v2.IListMonitoredResourceDescriptorsResponse + | null + | undefined, + protos.google.api.IMonitoredResourceDescriptor + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listMonitoredResourceDescriptors values %j', values); callback!(error, values, nextPageRequest, rawResponse); @@ -1144,210 +1331,236 @@ export class LoggingServiceV2Client { this._log.info('listMonitoredResourceDescriptors request %j', request); return this.innerApiCalls .listMonitoredResourceDescriptors(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.api.IMonitoredResourceDescriptor[], - protos.google.logging.v2.IListMonitoredResourceDescriptorsRequest|null, - protos.google.logging.v2.IListMonitoredResourceDescriptorsResponse - ]) => { - this._log.info('listMonitoredResourceDescriptors values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.api.IMonitoredResourceDescriptor[], + protos.google.logging.v2.IListMonitoredResourceDescriptorsRequest | null, + protos.google.logging.v2.IListMonitoredResourceDescriptorsResponse, + ]) => { + this._log.info( + 'listMonitoredResourceDescriptors values %j', + response, + ); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listMonitoredResourceDescriptors`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {number} [request.pageSize] - * Optional. The maximum number of results to return from this request. - * Non-positive values are ignored. The presence of `nextPageToken` in the - * response indicates that more results might be available. - * @param {string} [request.pageToken] - * Optional. If present, then retrieve the next batch of results from the - * preceding call to this method. `pageToken` must be the value of - * `nextPageToken` from the previous response. The values of other method - * parameters should be identical to those in the previous call. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.api.MonitoredResourceDescriptor|MonitoredResourceDescriptor} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `listMonitoredResourceDescriptorsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `listMonitoredResourceDescriptors`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {number} [request.pageSize] + * Optional. The maximum number of results to return from this request. + * Non-positive values are ignored. The presence of `nextPageToken` in the + * response indicates that more results might be available. + * @param {string} [request.pageToken] + * Optional. If present, then retrieve the next batch of results from the + * preceding call to this method. `pageToken` must be the value of + * `nextPageToken` from the previous response. The values of other method + * parameters should be identical to those in the previous call. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.api.MonitoredResourceDescriptor|MonitoredResourceDescriptor} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listMonitoredResourceDescriptorsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listMonitoredResourceDescriptorsStream( - request?: protos.google.logging.v2.IListMonitoredResourceDescriptorsRequest, - options?: CallOptions): - Transform{ + request?: protos.google.logging.v2.IListMonitoredResourceDescriptorsRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - const defaultCallSettings = this._defaults['listMonitoredResourceDescriptors']; + const defaultCallSettings = + this._defaults['listMonitoredResourceDescriptors']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listMonitoredResourceDescriptors stream %j', request); return this.descriptors.page.listMonitoredResourceDescriptors.createStream( this.innerApiCalls.listMonitoredResourceDescriptors as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listMonitoredResourceDescriptors`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {number} [request.pageSize] - * Optional. The maximum number of results to return from this request. - * Non-positive values are ignored. The presence of `nextPageToken` in the - * response indicates that more results might be available. - * @param {string} [request.pageToken] - * Optional. If present, then retrieve the next batch of results from the - * preceding call to this method. `pageToken` must be the value of - * `nextPageToken` from the previous response. The values of other method - * parameters should be identical to those in the previous call. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.api.MonitoredResourceDescriptor|MonitoredResourceDescriptor}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v2/logging_service_v2.list_monitored_resource_descriptors.js - * region_tag:logging_v2_generated_LoggingServiceV2_ListMonitoredResourceDescriptors_async - */ + /** + * Equivalent to `listMonitoredResourceDescriptors`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {number} [request.pageSize] + * Optional. The maximum number of results to return from this request. + * Non-positive values are ignored. The presence of `nextPageToken` in the + * response indicates that more results might be available. + * @param {string} [request.pageToken] + * Optional. If present, then retrieve the next batch of results from the + * preceding call to this method. `pageToken` must be the value of + * `nextPageToken` from the previous response. The values of other method + * parameters should be identical to those in the previous call. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.api.MonitoredResourceDescriptor|MonitoredResourceDescriptor}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v2/logging_service_v2.list_monitored_resource_descriptors.js + * region_tag:logging_v2_generated_LoggingServiceV2_ListMonitoredResourceDescriptors_async + */ listMonitoredResourceDescriptorsAsync( - request?: protos.google.logging.v2.IListMonitoredResourceDescriptorsRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.logging.v2.IListMonitoredResourceDescriptorsRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - const defaultCallSettings = this._defaults['listMonitoredResourceDescriptors']; + const defaultCallSettings = + this._defaults['listMonitoredResourceDescriptors']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listMonitoredResourceDescriptors iterate %j', request); return this.descriptors.page.listMonitoredResourceDescriptors.asyncIterate( this.innerApiCalls['listMonitoredResourceDescriptors'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } - /** - * Lists the logs in projects, organizations, folders, or billing accounts. - * Only logs that have entries are listed. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The resource name that owns the logs: - * - * * `projects/[PROJECT_ID]` - * * `organizations/[ORGANIZATION_ID]` - * * `billingAccounts/[BILLING_ACCOUNT_ID]` - * * `folders/[FOLDER_ID]` - * @param {number} [request.pageSize] - * Optional. The maximum number of results to return from this request. - * Non-positive values are ignored. The presence of `nextPageToken` in the - * response indicates that more results might be available. - * @param {string} [request.pageToken] - * Optional. If present, then retrieve the next batch of results from the - * preceding call to this method. `pageToken` must be the value of - * `nextPageToken` from the previous response. The values of other method - * parameters should be identical to those in the previous call. - * @param {string[]} [request.resourceNames] - * Optional. The resource name that owns the logs: - * - * * `projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]` - * * `organizations/[ORGANIZATION_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]` - * * `billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]` - * * `folders/[FOLDER_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]` - * - * To support legacy queries, it could also be: - * - * * `projects/[PROJECT_ID]` - * * `organizations/[ORGANIZATION_ID]` - * * `billingAccounts/[BILLING_ACCOUNT_ID]` - * * `folders/[FOLDER_ID]` - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of string. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `listLogsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Lists the logs in projects, organizations, folders, or billing accounts. + * Only logs that have entries are listed. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The resource name that owns the logs: + * + * * `projects/[PROJECT_ID]` + * * `organizations/[ORGANIZATION_ID]` + * * `billingAccounts/[BILLING_ACCOUNT_ID]` + * * `folders/[FOLDER_ID]` + * @param {number} [request.pageSize] + * Optional. The maximum number of results to return from this request. + * Non-positive values are ignored. The presence of `nextPageToken` in the + * response indicates that more results might be available. + * @param {string} [request.pageToken] + * Optional. If present, then retrieve the next batch of results from the + * preceding call to this method. `pageToken` must be the value of + * `nextPageToken` from the previous response. The values of other method + * parameters should be identical to those in the previous call. + * @param {string[]} [request.resourceNames] + * Optional. The resource name that owns the logs: + * + * * `projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]` + * * `organizations/[ORGANIZATION_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]` + * * `billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]` + * * `folders/[FOLDER_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]` + * + * To support legacy queries, it could also be: + * + * * `projects/[PROJECT_ID]` + * * `organizations/[ORGANIZATION_ID]` + * * `billingAccounts/[BILLING_ACCOUNT_ID]` + * * `folders/[FOLDER_ID]` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of string. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listLogsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listLogs( - request?: protos.google.logging.v2.IListLogsRequest, - options?: CallOptions): - Promise<[ - string[], - protos.google.logging.v2.IListLogsRequest|null, - protos.google.logging.v2.IListLogsResponse - ]>; + request?: protos.google.logging.v2.IListLogsRequest, + options?: CallOptions, + ): Promise< + [ + string[], + protos.google.logging.v2.IListLogsRequest | null, + protos.google.logging.v2.IListLogsResponse, + ] + >; listLogs( - request: protos.google.logging.v2.IListLogsRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.logging.v2.IListLogsRequest, - protos.google.logging.v2.IListLogsResponse|null|undefined, - string>): void; + request: protos.google.logging.v2.IListLogsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.logging.v2.IListLogsRequest, + protos.google.logging.v2.IListLogsResponse | null | undefined, + string + >, + ): void; listLogs( - request: protos.google.logging.v2.IListLogsRequest, - callback: PaginationCallback< - protos.google.logging.v2.IListLogsRequest, - protos.google.logging.v2.IListLogsResponse|null|undefined, - string>): void; + request: protos.google.logging.v2.IListLogsRequest, + callback: PaginationCallback< + protos.google.logging.v2.IListLogsRequest, + protos.google.logging.v2.IListLogsResponse | null | undefined, + string + >, + ): void; listLogs( - request?: protos.google.logging.v2.IListLogsRequest, - optionsOrCallback?: CallOptions|PaginationCallback< - protos.google.logging.v2.IListLogsRequest, - protos.google.logging.v2.IListLogsResponse|null|undefined, - string>, - callback?: PaginationCallback< + request?: protos.google.logging.v2.IListLogsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.logging.v2.IListLogsRequest, - protos.google.logging.v2.IListLogsResponse|null|undefined, - string>): - Promise<[ - string[], - protos.google.logging.v2.IListLogsRequest|null, - protos.google.logging.v2.IListLogsResponse - ]>|void { + protos.google.logging.v2.IListLogsResponse | null | undefined, + string + >, + callback?: PaginationCallback< + protos.google.logging.v2.IListLogsRequest, + protos.google.logging.v2.IListLogsResponse | null | undefined, + string + >, + ): Promise< + [ + string[], + protos.google.logging.v2.IListLogsRequest | null, + protos.google.logging.v2.IListLogsResponse, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.logging.v2.IListLogsRequest, - protos.google.logging.v2.IListLogsResponse|null|undefined, - string>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.logging.v2.IListLogsRequest, + protos.google.logging.v2.IListLogsResponse | null | undefined, + string + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listLogs values %j', values); callback!(error, values, nextPageRequest, rawResponse); @@ -1356,154 +1569,158 @@ export class LoggingServiceV2Client { this._log.info('listLogs request %j', request); return this.innerApiCalls .listLogs(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - string[], - protos.google.logging.v2.IListLogsRequest|null, - protos.google.logging.v2.IListLogsResponse - ]) => { - this._log.info('listLogs values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + string[], + protos.google.logging.v2.IListLogsRequest | null, + protos.google.logging.v2.IListLogsResponse, + ]) => { + this._log.info('listLogs values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listLogs`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The resource name that owns the logs: - * - * * `projects/[PROJECT_ID]` - * * `organizations/[ORGANIZATION_ID]` - * * `billingAccounts/[BILLING_ACCOUNT_ID]` - * * `folders/[FOLDER_ID]` - * @param {number} [request.pageSize] - * Optional. The maximum number of results to return from this request. - * Non-positive values are ignored. The presence of `nextPageToken` in the - * response indicates that more results might be available. - * @param {string} [request.pageToken] - * Optional. If present, then retrieve the next batch of results from the - * preceding call to this method. `pageToken` must be the value of - * `nextPageToken` from the previous response. The values of other method - * parameters should be identical to those in the previous call. - * @param {string[]} [request.resourceNames] - * Optional. The resource name that owns the logs: - * - * * `projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]` - * * `organizations/[ORGANIZATION_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]` - * * `billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]` - * * `folders/[FOLDER_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]` - * - * To support legacy queries, it could also be: - * - * * `projects/[PROJECT_ID]` - * * `organizations/[ORGANIZATION_ID]` - * * `billingAccounts/[BILLING_ACCOUNT_ID]` - * * `folders/[FOLDER_ID]` - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing string on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `listLogsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `listLogs`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The resource name that owns the logs: + * + * * `projects/[PROJECT_ID]` + * * `organizations/[ORGANIZATION_ID]` + * * `billingAccounts/[BILLING_ACCOUNT_ID]` + * * `folders/[FOLDER_ID]` + * @param {number} [request.pageSize] + * Optional. The maximum number of results to return from this request. + * Non-positive values are ignored. The presence of `nextPageToken` in the + * response indicates that more results might be available. + * @param {string} [request.pageToken] + * Optional. If present, then retrieve the next batch of results from the + * preceding call to this method. `pageToken` must be the value of + * `nextPageToken` from the previous response. The values of other method + * parameters should be identical to those in the previous call. + * @param {string[]} [request.resourceNames] + * Optional. The resource name that owns the logs: + * + * * `projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]` + * * `organizations/[ORGANIZATION_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]` + * * `billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]` + * * `folders/[FOLDER_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]` + * + * To support legacy queries, it could also be: + * + * * `projects/[PROJECT_ID]` + * * `organizations/[ORGANIZATION_ID]` + * * `billingAccounts/[BILLING_ACCOUNT_ID]` + * * `folders/[FOLDER_ID]` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing string on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listLogsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listLogsStream( - request?: protos.google.logging.v2.IListLogsRequest, - options?: CallOptions): - Transform{ + request?: protos.google.logging.v2.IListLogsRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); const defaultCallSettings = this._defaults['listLogs']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listLogs stream %j', request); return this.descriptors.page.listLogs.createStream( this.innerApiCalls.listLogs as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listLogs`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The resource name that owns the logs: - * - * * `projects/[PROJECT_ID]` - * * `organizations/[ORGANIZATION_ID]` - * * `billingAccounts/[BILLING_ACCOUNT_ID]` - * * `folders/[FOLDER_ID]` - * @param {number} [request.pageSize] - * Optional. The maximum number of results to return from this request. - * Non-positive values are ignored. The presence of `nextPageToken` in the - * response indicates that more results might be available. - * @param {string} [request.pageToken] - * Optional. If present, then retrieve the next batch of results from the - * preceding call to this method. `pageToken` must be the value of - * `nextPageToken` from the previous response. The values of other method - * parameters should be identical to those in the previous call. - * @param {string[]} [request.resourceNames] - * Optional. The resource name that owns the logs: - * - * * `projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]` - * * `organizations/[ORGANIZATION_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]` - * * `billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]` - * * `folders/[FOLDER_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]` - * - * To support legacy queries, it could also be: - * - * * `projects/[PROJECT_ID]` - * * `organizations/[ORGANIZATION_ID]` - * * `billingAccounts/[BILLING_ACCOUNT_ID]` - * * `folders/[FOLDER_ID]` - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * string. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v2/logging_service_v2.list_logs.js - * region_tag:logging_v2_generated_LoggingServiceV2_ListLogs_async - */ + /** + * Equivalent to `listLogs`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The resource name that owns the logs: + * + * * `projects/[PROJECT_ID]` + * * `organizations/[ORGANIZATION_ID]` + * * `billingAccounts/[BILLING_ACCOUNT_ID]` + * * `folders/[FOLDER_ID]` + * @param {number} [request.pageSize] + * Optional. The maximum number of results to return from this request. + * Non-positive values are ignored. The presence of `nextPageToken` in the + * response indicates that more results might be available. + * @param {string} [request.pageToken] + * Optional. If present, then retrieve the next batch of results from the + * preceding call to this method. `pageToken` must be the value of + * `nextPageToken` from the previous response. The values of other method + * parameters should be identical to those in the previous call. + * @param {string[]} [request.resourceNames] + * Optional. The resource name that owns the logs: + * + * * `projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]` + * * `organizations/[ORGANIZATION_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]` + * * `billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]` + * * `folders/[FOLDER_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]` + * + * To support legacy queries, it could also be: + * + * * `projects/[PROJECT_ID]` + * * `organizations/[ORGANIZATION_ID]` + * * `billingAccounts/[BILLING_ACCOUNT_ID]` + * * `folders/[FOLDER_ID]` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * string. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v2/logging_service_v2.list_logs.js + * region_tag:logging_v2_generated_LoggingServiceV2_ListLogs_async + */ listLogsAsync( - request?: protos.google.logging.v2.IListLogsRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.logging.v2.IListLogsRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); const defaultCallSettings = this._defaults['listLogs']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listLogs iterate %j', request); return this.descriptors.page.listLogs.asyncIterate( this.innerApiCalls['listLogs'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } // -------------------- @@ -1516,7 +1733,7 @@ export class LoggingServiceV2Client { * @param {string} billing_account * @returns {string} Resource name string. */ - billingAccountCmekSettingsPath(billingAccount:string) { + billingAccountCmekSettingsPath(billingAccount: string) { return this.pathTemplates.billingAccountCmekSettingsPathTemplate.render({ billing_account: billingAccount, }); @@ -1529,8 +1746,12 @@ export class LoggingServiceV2Client { * A fully-qualified path representing billing_account_cmekSettings resource. * @returns {string} A string representing the billing_account. */ - matchBillingAccountFromBillingAccountCmekSettingsName(billingAccountCmekSettingsName: string) { - return this.pathTemplates.billingAccountCmekSettingsPathTemplate.match(billingAccountCmekSettingsName).billing_account; + matchBillingAccountFromBillingAccountCmekSettingsName( + billingAccountCmekSettingsName: string, + ) { + return this.pathTemplates.billingAccountCmekSettingsPathTemplate.match( + billingAccountCmekSettingsName, + ).billing_account; } /** @@ -1540,7 +1761,7 @@ export class LoggingServiceV2Client { * @param {string} exclusion * @returns {string} Resource name string. */ - billingAccountExclusionPath(billingAccount:string,exclusion:string) { + billingAccountExclusionPath(billingAccount: string, exclusion: string) { return this.pathTemplates.billingAccountExclusionPathTemplate.render({ billing_account: billingAccount, exclusion: exclusion, @@ -1554,8 +1775,12 @@ export class LoggingServiceV2Client { * A fully-qualified path representing billing_account_exclusion resource. * @returns {string} A string representing the billing_account. */ - matchBillingAccountFromBillingAccountExclusionName(billingAccountExclusionName: string) { - return this.pathTemplates.billingAccountExclusionPathTemplate.match(billingAccountExclusionName).billing_account; + matchBillingAccountFromBillingAccountExclusionName( + billingAccountExclusionName: string, + ) { + return this.pathTemplates.billingAccountExclusionPathTemplate.match( + billingAccountExclusionName, + ).billing_account; } /** @@ -1565,8 +1790,12 @@ export class LoggingServiceV2Client { * A fully-qualified path representing billing_account_exclusion resource. * @returns {string} A string representing the exclusion. */ - matchExclusionFromBillingAccountExclusionName(billingAccountExclusionName: string) { - return this.pathTemplates.billingAccountExclusionPathTemplate.match(billingAccountExclusionName).exclusion; + matchExclusionFromBillingAccountExclusionName( + billingAccountExclusionName: string, + ) { + return this.pathTemplates.billingAccountExclusionPathTemplate.match( + billingAccountExclusionName, + ).exclusion; } /** @@ -1577,7 +1806,11 @@ export class LoggingServiceV2Client { * @param {string} bucket * @returns {string} Resource name string. */ - billingAccountLocationBucketPath(billingAccount:string,location:string,bucket:string) { + billingAccountLocationBucketPath( + billingAccount: string, + location: string, + bucket: string, + ) { return this.pathTemplates.billingAccountLocationBucketPathTemplate.render({ billing_account: billingAccount, location: location, @@ -1592,8 +1825,12 @@ export class LoggingServiceV2Client { * A fully-qualified path representing billing_account_location_bucket resource. * @returns {string} A string representing the billing_account. */ - matchBillingAccountFromBillingAccountLocationBucketName(billingAccountLocationBucketName: string) { - return this.pathTemplates.billingAccountLocationBucketPathTemplate.match(billingAccountLocationBucketName).billing_account; + matchBillingAccountFromBillingAccountLocationBucketName( + billingAccountLocationBucketName: string, + ) { + return this.pathTemplates.billingAccountLocationBucketPathTemplate.match( + billingAccountLocationBucketName, + ).billing_account; } /** @@ -1603,8 +1840,12 @@ export class LoggingServiceV2Client { * A fully-qualified path representing billing_account_location_bucket resource. * @returns {string} A string representing the location. */ - matchLocationFromBillingAccountLocationBucketName(billingAccountLocationBucketName: string) { - return this.pathTemplates.billingAccountLocationBucketPathTemplate.match(billingAccountLocationBucketName).location; + matchLocationFromBillingAccountLocationBucketName( + billingAccountLocationBucketName: string, + ) { + return this.pathTemplates.billingAccountLocationBucketPathTemplate.match( + billingAccountLocationBucketName, + ).location; } /** @@ -1614,8 +1855,12 @@ export class LoggingServiceV2Client { * A fully-qualified path representing billing_account_location_bucket resource. * @returns {string} A string representing the bucket. */ - matchBucketFromBillingAccountLocationBucketName(billingAccountLocationBucketName: string) { - return this.pathTemplates.billingAccountLocationBucketPathTemplate.match(billingAccountLocationBucketName).bucket; + matchBucketFromBillingAccountLocationBucketName( + billingAccountLocationBucketName: string, + ) { + return this.pathTemplates.billingAccountLocationBucketPathTemplate.match( + billingAccountLocationBucketName, + ).bucket; } /** @@ -1627,13 +1872,20 @@ export class LoggingServiceV2Client { * @param {string} view * @returns {string} Resource name string. */ - billingAccountLocationBucketViewPath(billingAccount:string,location:string,bucket:string,view:string) { - return this.pathTemplates.billingAccountLocationBucketViewPathTemplate.render({ - billing_account: billingAccount, - location: location, - bucket: bucket, - view: view, - }); + billingAccountLocationBucketViewPath( + billingAccount: string, + location: string, + bucket: string, + view: string, + ) { + return this.pathTemplates.billingAccountLocationBucketViewPathTemplate.render( + { + billing_account: billingAccount, + location: location, + bucket: bucket, + view: view, + }, + ); } /** @@ -1643,8 +1895,12 @@ export class LoggingServiceV2Client { * A fully-qualified path representing billing_account_location_bucket_view resource. * @returns {string} A string representing the billing_account. */ - matchBillingAccountFromBillingAccountLocationBucketViewName(billingAccountLocationBucketViewName: string) { - return this.pathTemplates.billingAccountLocationBucketViewPathTemplate.match(billingAccountLocationBucketViewName).billing_account; + matchBillingAccountFromBillingAccountLocationBucketViewName( + billingAccountLocationBucketViewName: string, + ) { + return this.pathTemplates.billingAccountLocationBucketViewPathTemplate.match( + billingAccountLocationBucketViewName, + ).billing_account; } /** @@ -1654,8 +1910,12 @@ export class LoggingServiceV2Client { * A fully-qualified path representing billing_account_location_bucket_view resource. * @returns {string} A string representing the location. */ - matchLocationFromBillingAccountLocationBucketViewName(billingAccountLocationBucketViewName: string) { - return this.pathTemplates.billingAccountLocationBucketViewPathTemplate.match(billingAccountLocationBucketViewName).location; + matchLocationFromBillingAccountLocationBucketViewName( + billingAccountLocationBucketViewName: string, + ) { + return this.pathTemplates.billingAccountLocationBucketViewPathTemplate.match( + billingAccountLocationBucketViewName, + ).location; } /** @@ -1665,8 +1925,12 @@ export class LoggingServiceV2Client { * A fully-qualified path representing billing_account_location_bucket_view resource. * @returns {string} A string representing the bucket. */ - matchBucketFromBillingAccountLocationBucketViewName(billingAccountLocationBucketViewName: string) { - return this.pathTemplates.billingAccountLocationBucketViewPathTemplate.match(billingAccountLocationBucketViewName).bucket; + matchBucketFromBillingAccountLocationBucketViewName( + billingAccountLocationBucketViewName: string, + ) { + return this.pathTemplates.billingAccountLocationBucketViewPathTemplate.match( + billingAccountLocationBucketViewName, + ).bucket; } /** @@ -1676,8 +1940,12 @@ export class LoggingServiceV2Client { * A fully-qualified path representing billing_account_location_bucket_view resource. * @returns {string} A string representing the view. */ - matchViewFromBillingAccountLocationBucketViewName(billingAccountLocationBucketViewName: string) { - return this.pathTemplates.billingAccountLocationBucketViewPathTemplate.match(billingAccountLocationBucketViewName).view; + matchViewFromBillingAccountLocationBucketViewName( + billingAccountLocationBucketViewName: string, + ) { + return this.pathTemplates.billingAccountLocationBucketViewPathTemplate.match( + billingAccountLocationBucketViewName, + ).view; } /** @@ -1687,7 +1955,7 @@ export class LoggingServiceV2Client { * @param {string} log * @returns {string} Resource name string. */ - billingAccountLogPath(billingAccount:string,log:string) { + billingAccountLogPath(billingAccount: string, log: string) { return this.pathTemplates.billingAccountLogPathTemplate.render({ billing_account: billingAccount, log: log, @@ -1702,7 +1970,9 @@ export class LoggingServiceV2Client { * @returns {string} A string representing the billing_account. */ matchBillingAccountFromBillingAccountLogName(billingAccountLogName: string) { - return this.pathTemplates.billingAccountLogPathTemplate.match(billingAccountLogName).billing_account; + return this.pathTemplates.billingAccountLogPathTemplate.match( + billingAccountLogName, + ).billing_account; } /** @@ -1713,7 +1983,9 @@ export class LoggingServiceV2Client { * @returns {string} A string representing the log. */ matchLogFromBillingAccountLogName(billingAccountLogName: string) { - return this.pathTemplates.billingAccountLogPathTemplate.match(billingAccountLogName).log; + return this.pathTemplates.billingAccountLogPathTemplate.match( + billingAccountLogName, + ).log; } /** @@ -1722,7 +1994,7 @@ export class LoggingServiceV2Client { * @param {string} billing_account * @returns {string} Resource name string. */ - billingAccountSettingsPath(billingAccount:string) { + billingAccountSettingsPath(billingAccount: string) { return this.pathTemplates.billingAccountSettingsPathTemplate.render({ billing_account: billingAccount, }); @@ -1735,8 +2007,12 @@ export class LoggingServiceV2Client { * A fully-qualified path representing billing_account_settings resource. * @returns {string} A string representing the billing_account. */ - matchBillingAccountFromBillingAccountSettingsName(billingAccountSettingsName: string) { - return this.pathTemplates.billingAccountSettingsPathTemplate.match(billingAccountSettingsName).billing_account; + matchBillingAccountFromBillingAccountSettingsName( + billingAccountSettingsName: string, + ) { + return this.pathTemplates.billingAccountSettingsPathTemplate.match( + billingAccountSettingsName, + ).billing_account; } /** @@ -1746,7 +2022,7 @@ export class LoggingServiceV2Client { * @param {string} sink * @returns {string} Resource name string. */ - billingAccountSinkPath(billingAccount:string,sink:string) { + billingAccountSinkPath(billingAccount: string, sink: string) { return this.pathTemplates.billingAccountSinkPathTemplate.render({ billing_account: billingAccount, sink: sink, @@ -1760,8 +2036,12 @@ export class LoggingServiceV2Client { * A fully-qualified path representing billing_account_sink resource. * @returns {string} A string representing the billing_account. */ - matchBillingAccountFromBillingAccountSinkName(billingAccountSinkName: string) { - return this.pathTemplates.billingAccountSinkPathTemplate.match(billingAccountSinkName).billing_account; + matchBillingAccountFromBillingAccountSinkName( + billingAccountSinkName: string, + ) { + return this.pathTemplates.billingAccountSinkPathTemplate.match( + billingAccountSinkName, + ).billing_account; } /** @@ -1772,7 +2052,9 @@ export class LoggingServiceV2Client { * @returns {string} A string representing the sink. */ matchSinkFromBillingAccountSinkName(billingAccountSinkName: string) { - return this.pathTemplates.billingAccountSinkPathTemplate.match(billingAccountSinkName).sink; + return this.pathTemplates.billingAccountSinkPathTemplate.match( + billingAccountSinkName, + ).sink; } /** @@ -1781,7 +2063,7 @@ export class LoggingServiceV2Client { * @param {string} folder * @returns {string} Resource name string. */ - folderCmekSettingsPath(folder:string) { + folderCmekSettingsPath(folder: string) { return this.pathTemplates.folderCmekSettingsPathTemplate.render({ folder: folder, }); @@ -1795,7 +2077,9 @@ export class LoggingServiceV2Client { * @returns {string} A string representing the folder. */ matchFolderFromFolderCmekSettingsName(folderCmekSettingsName: string) { - return this.pathTemplates.folderCmekSettingsPathTemplate.match(folderCmekSettingsName).folder; + return this.pathTemplates.folderCmekSettingsPathTemplate.match( + folderCmekSettingsName, + ).folder; } /** @@ -1805,7 +2089,7 @@ export class LoggingServiceV2Client { * @param {string} exclusion * @returns {string} Resource name string. */ - folderExclusionPath(folder:string,exclusion:string) { + folderExclusionPath(folder: string, exclusion: string) { return this.pathTemplates.folderExclusionPathTemplate.render({ folder: folder, exclusion: exclusion, @@ -1820,7 +2104,9 @@ export class LoggingServiceV2Client { * @returns {string} A string representing the folder. */ matchFolderFromFolderExclusionName(folderExclusionName: string) { - return this.pathTemplates.folderExclusionPathTemplate.match(folderExclusionName).folder; + return this.pathTemplates.folderExclusionPathTemplate.match( + folderExclusionName, + ).folder; } /** @@ -1831,7 +2117,9 @@ export class LoggingServiceV2Client { * @returns {string} A string representing the exclusion. */ matchExclusionFromFolderExclusionName(folderExclusionName: string) { - return this.pathTemplates.folderExclusionPathTemplate.match(folderExclusionName).exclusion; + return this.pathTemplates.folderExclusionPathTemplate.match( + folderExclusionName, + ).exclusion; } /** @@ -1842,7 +2130,7 @@ export class LoggingServiceV2Client { * @param {string} bucket * @returns {string} Resource name string. */ - folderLocationBucketPath(folder:string,location:string,bucket:string) { + folderLocationBucketPath(folder: string, location: string, bucket: string) { return this.pathTemplates.folderLocationBucketPathTemplate.render({ folder: folder, location: location, @@ -1858,7 +2146,9 @@ export class LoggingServiceV2Client { * @returns {string} A string representing the folder. */ matchFolderFromFolderLocationBucketName(folderLocationBucketName: string) { - return this.pathTemplates.folderLocationBucketPathTemplate.match(folderLocationBucketName).folder; + return this.pathTemplates.folderLocationBucketPathTemplate.match( + folderLocationBucketName, + ).folder; } /** @@ -1869,7 +2159,9 @@ export class LoggingServiceV2Client { * @returns {string} A string representing the location. */ matchLocationFromFolderLocationBucketName(folderLocationBucketName: string) { - return this.pathTemplates.folderLocationBucketPathTemplate.match(folderLocationBucketName).location; + return this.pathTemplates.folderLocationBucketPathTemplate.match( + folderLocationBucketName, + ).location; } /** @@ -1880,7 +2172,9 @@ export class LoggingServiceV2Client { * @returns {string} A string representing the bucket. */ matchBucketFromFolderLocationBucketName(folderLocationBucketName: string) { - return this.pathTemplates.folderLocationBucketPathTemplate.match(folderLocationBucketName).bucket; + return this.pathTemplates.folderLocationBucketPathTemplate.match( + folderLocationBucketName, + ).bucket; } /** @@ -1892,7 +2186,12 @@ export class LoggingServiceV2Client { * @param {string} view * @returns {string} Resource name string. */ - folderLocationBucketViewPath(folder:string,location:string,bucket:string,view:string) { + folderLocationBucketViewPath( + folder: string, + location: string, + bucket: string, + view: string, + ) { return this.pathTemplates.folderLocationBucketViewPathTemplate.render({ folder: folder, location: location, @@ -1908,8 +2207,12 @@ export class LoggingServiceV2Client { * A fully-qualified path representing folder_location_bucket_view resource. * @returns {string} A string representing the folder. */ - matchFolderFromFolderLocationBucketViewName(folderLocationBucketViewName: string) { - return this.pathTemplates.folderLocationBucketViewPathTemplate.match(folderLocationBucketViewName).folder; + matchFolderFromFolderLocationBucketViewName( + folderLocationBucketViewName: string, + ) { + return this.pathTemplates.folderLocationBucketViewPathTemplate.match( + folderLocationBucketViewName, + ).folder; } /** @@ -1919,8 +2222,12 @@ export class LoggingServiceV2Client { * A fully-qualified path representing folder_location_bucket_view resource. * @returns {string} A string representing the location. */ - matchLocationFromFolderLocationBucketViewName(folderLocationBucketViewName: string) { - return this.pathTemplates.folderLocationBucketViewPathTemplate.match(folderLocationBucketViewName).location; + matchLocationFromFolderLocationBucketViewName( + folderLocationBucketViewName: string, + ) { + return this.pathTemplates.folderLocationBucketViewPathTemplate.match( + folderLocationBucketViewName, + ).location; } /** @@ -1930,8 +2237,12 @@ export class LoggingServiceV2Client { * A fully-qualified path representing folder_location_bucket_view resource. * @returns {string} A string representing the bucket. */ - matchBucketFromFolderLocationBucketViewName(folderLocationBucketViewName: string) { - return this.pathTemplates.folderLocationBucketViewPathTemplate.match(folderLocationBucketViewName).bucket; + matchBucketFromFolderLocationBucketViewName( + folderLocationBucketViewName: string, + ) { + return this.pathTemplates.folderLocationBucketViewPathTemplate.match( + folderLocationBucketViewName, + ).bucket; } /** @@ -1941,8 +2252,12 @@ export class LoggingServiceV2Client { * A fully-qualified path representing folder_location_bucket_view resource. * @returns {string} A string representing the view. */ - matchViewFromFolderLocationBucketViewName(folderLocationBucketViewName: string) { - return this.pathTemplates.folderLocationBucketViewPathTemplate.match(folderLocationBucketViewName).view; + matchViewFromFolderLocationBucketViewName( + folderLocationBucketViewName: string, + ) { + return this.pathTemplates.folderLocationBucketViewPathTemplate.match( + folderLocationBucketViewName, + ).view; } /** @@ -1952,7 +2267,7 @@ export class LoggingServiceV2Client { * @param {string} log * @returns {string} Resource name string. */ - folderLogPath(folder:string,log:string) { + folderLogPath(folder: string, log: string) { return this.pathTemplates.folderLogPathTemplate.render({ folder: folder, log: log, @@ -1987,7 +2302,7 @@ export class LoggingServiceV2Client { * @param {string} folder * @returns {string} Resource name string. */ - folderSettingsPath(folder:string) { + folderSettingsPath(folder: string) { return this.pathTemplates.folderSettingsPathTemplate.render({ folder: folder, }); @@ -2001,7 +2316,9 @@ export class LoggingServiceV2Client { * @returns {string} A string representing the folder. */ matchFolderFromFolderSettingsName(folderSettingsName: string) { - return this.pathTemplates.folderSettingsPathTemplate.match(folderSettingsName).folder; + return this.pathTemplates.folderSettingsPathTemplate.match( + folderSettingsName, + ).folder; } /** @@ -2011,7 +2328,7 @@ export class LoggingServiceV2Client { * @param {string} sink * @returns {string} Resource name string. */ - folderSinkPath(folder:string,sink:string) { + folderSinkPath(folder: string, sink: string) { return this.pathTemplates.folderSinkPathTemplate.render({ folder: folder, sink: sink, @@ -2026,7 +2343,8 @@ export class LoggingServiceV2Client { * @returns {string} A string representing the folder. */ matchFolderFromFolderSinkName(folderSinkName: string) { - return this.pathTemplates.folderSinkPathTemplate.match(folderSinkName).folder; + return this.pathTemplates.folderSinkPathTemplate.match(folderSinkName) + .folder; } /** @@ -2047,7 +2365,7 @@ export class LoggingServiceV2Client { * @param {string} metric * @returns {string} Resource name string. */ - logMetricPath(project:string,metric:string) { + logMetricPath(project: string, metric: string) { return this.pathTemplates.logMetricPathTemplate.render({ project: project, metric: metric, @@ -2062,7 +2380,8 @@ export class LoggingServiceV2Client { * @returns {string} A string representing the project. */ matchProjectFromLogMetricName(logMetricName: string) { - return this.pathTemplates.logMetricPathTemplate.match(logMetricName).project; + return this.pathTemplates.logMetricPathTemplate.match(logMetricName) + .project; } /** @@ -2082,7 +2401,7 @@ export class LoggingServiceV2Client { * @param {string} organization * @returns {string} Resource name string. */ - organizationCmekSettingsPath(organization:string) { + organizationCmekSettingsPath(organization: string) { return this.pathTemplates.organizationCmekSettingsPathTemplate.render({ organization: organization, }); @@ -2095,8 +2414,12 @@ export class LoggingServiceV2Client { * A fully-qualified path representing organization_cmekSettings resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationCmekSettingsName(organizationCmekSettingsName: string) { - return this.pathTemplates.organizationCmekSettingsPathTemplate.match(organizationCmekSettingsName).organization; + matchOrganizationFromOrganizationCmekSettingsName( + organizationCmekSettingsName: string, + ) { + return this.pathTemplates.organizationCmekSettingsPathTemplate.match( + organizationCmekSettingsName, + ).organization; } /** @@ -2106,7 +2429,7 @@ export class LoggingServiceV2Client { * @param {string} exclusion * @returns {string} Resource name string. */ - organizationExclusionPath(organization:string,exclusion:string) { + organizationExclusionPath(organization: string, exclusion: string) { return this.pathTemplates.organizationExclusionPathTemplate.render({ organization: organization, exclusion: exclusion, @@ -2120,8 +2443,12 @@ export class LoggingServiceV2Client { * A fully-qualified path representing organization_exclusion resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationExclusionName(organizationExclusionName: string) { - return this.pathTemplates.organizationExclusionPathTemplate.match(organizationExclusionName).organization; + matchOrganizationFromOrganizationExclusionName( + organizationExclusionName: string, + ) { + return this.pathTemplates.organizationExclusionPathTemplate.match( + organizationExclusionName, + ).organization; } /** @@ -2131,8 +2458,12 @@ export class LoggingServiceV2Client { * A fully-qualified path representing organization_exclusion resource. * @returns {string} A string representing the exclusion. */ - matchExclusionFromOrganizationExclusionName(organizationExclusionName: string) { - return this.pathTemplates.organizationExclusionPathTemplate.match(organizationExclusionName).exclusion; + matchExclusionFromOrganizationExclusionName( + organizationExclusionName: string, + ) { + return this.pathTemplates.organizationExclusionPathTemplate.match( + organizationExclusionName, + ).exclusion; } /** @@ -2143,7 +2474,11 @@ export class LoggingServiceV2Client { * @param {string} bucket * @returns {string} Resource name string. */ - organizationLocationBucketPath(organization:string,location:string,bucket:string) { + organizationLocationBucketPath( + organization: string, + location: string, + bucket: string, + ) { return this.pathTemplates.organizationLocationBucketPathTemplate.render({ organization: organization, location: location, @@ -2158,8 +2493,12 @@ export class LoggingServiceV2Client { * A fully-qualified path representing organization_location_bucket resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationLocationBucketName(organizationLocationBucketName: string) { - return this.pathTemplates.organizationLocationBucketPathTemplate.match(organizationLocationBucketName).organization; + matchOrganizationFromOrganizationLocationBucketName( + organizationLocationBucketName: string, + ) { + return this.pathTemplates.organizationLocationBucketPathTemplate.match( + organizationLocationBucketName, + ).organization; } /** @@ -2169,8 +2508,12 @@ export class LoggingServiceV2Client { * A fully-qualified path representing organization_location_bucket resource. * @returns {string} A string representing the location. */ - matchLocationFromOrganizationLocationBucketName(organizationLocationBucketName: string) { - return this.pathTemplates.organizationLocationBucketPathTemplate.match(organizationLocationBucketName).location; + matchLocationFromOrganizationLocationBucketName( + organizationLocationBucketName: string, + ) { + return this.pathTemplates.organizationLocationBucketPathTemplate.match( + organizationLocationBucketName, + ).location; } /** @@ -2180,8 +2523,12 @@ export class LoggingServiceV2Client { * A fully-qualified path representing organization_location_bucket resource. * @returns {string} A string representing the bucket. */ - matchBucketFromOrganizationLocationBucketName(organizationLocationBucketName: string) { - return this.pathTemplates.organizationLocationBucketPathTemplate.match(organizationLocationBucketName).bucket; + matchBucketFromOrganizationLocationBucketName( + organizationLocationBucketName: string, + ) { + return this.pathTemplates.organizationLocationBucketPathTemplate.match( + organizationLocationBucketName, + ).bucket; } /** @@ -2193,13 +2540,20 @@ export class LoggingServiceV2Client { * @param {string} view * @returns {string} Resource name string. */ - organizationLocationBucketViewPath(organization:string,location:string,bucket:string,view:string) { - return this.pathTemplates.organizationLocationBucketViewPathTemplate.render({ - organization: organization, - location: location, - bucket: bucket, - view: view, - }); + organizationLocationBucketViewPath( + organization: string, + location: string, + bucket: string, + view: string, + ) { + return this.pathTemplates.organizationLocationBucketViewPathTemplate.render( + { + organization: organization, + location: location, + bucket: bucket, + view: view, + }, + ); } /** @@ -2209,8 +2563,12 @@ export class LoggingServiceV2Client { * A fully-qualified path representing organization_location_bucket_view resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationLocationBucketViewName(organizationLocationBucketViewName: string) { - return this.pathTemplates.organizationLocationBucketViewPathTemplate.match(organizationLocationBucketViewName).organization; + matchOrganizationFromOrganizationLocationBucketViewName( + organizationLocationBucketViewName: string, + ) { + return this.pathTemplates.organizationLocationBucketViewPathTemplate.match( + organizationLocationBucketViewName, + ).organization; } /** @@ -2220,8 +2578,12 @@ export class LoggingServiceV2Client { * A fully-qualified path representing organization_location_bucket_view resource. * @returns {string} A string representing the location. */ - matchLocationFromOrganizationLocationBucketViewName(organizationLocationBucketViewName: string) { - return this.pathTemplates.organizationLocationBucketViewPathTemplate.match(organizationLocationBucketViewName).location; + matchLocationFromOrganizationLocationBucketViewName( + organizationLocationBucketViewName: string, + ) { + return this.pathTemplates.organizationLocationBucketViewPathTemplate.match( + organizationLocationBucketViewName, + ).location; } /** @@ -2231,8 +2593,12 @@ export class LoggingServiceV2Client { * A fully-qualified path representing organization_location_bucket_view resource. * @returns {string} A string representing the bucket. */ - matchBucketFromOrganizationLocationBucketViewName(organizationLocationBucketViewName: string) { - return this.pathTemplates.organizationLocationBucketViewPathTemplate.match(organizationLocationBucketViewName).bucket; + matchBucketFromOrganizationLocationBucketViewName( + organizationLocationBucketViewName: string, + ) { + return this.pathTemplates.organizationLocationBucketViewPathTemplate.match( + organizationLocationBucketViewName, + ).bucket; } /** @@ -2242,8 +2608,12 @@ export class LoggingServiceV2Client { * A fully-qualified path representing organization_location_bucket_view resource. * @returns {string} A string representing the view. */ - matchViewFromOrganizationLocationBucketViewName(organizationLocationBucketViewName: string) { - return this.pathTemplates.organizationLocationBucketViewPathTemplate.match(organizationLocationBucketViewName).view; + matchViewFromOrganizationLocationBucketViewName( + organizationLocationBucketViewName: string, + ) { + return this.pathTemplates.organizationLocationBucketViewPathTemplate.match( + organizationLocationBucketViewName, + ).view; } /** @@ -2253,7 +2623,7 @@ export class LoggingServiceV2Client { * @param {string} log * @returns {string} Resource name string. */ - organizationLogPath(organization:string,log:string) { + organizationLogPath(organization: string, log: string) { return this.pathTemplates.organizationLogPathTemplate.render({ organization: organization, log: log, @@ -2268,7 +2638,9 @@ export class LoggingServiceV2Client { * @returns {string} A string representing the organization. */ matchOrganizationFromOrganizationLogName(organizationLogName: string) { - return this.pathTemplates.organizationLogPathTemplate.match(organizationLogName).organization; + return this.pathTemplates.organizationLogPathTemplate.match( + organizationLogName, + ).organization; } /** @@ -2279,7 +2651,9 @@ export class LoggingServiceV2Client { * @returns {string} A string representing the log. */ matchLogFromOrganizationLogName(organizationLogName: string) { - return this.pathTemplates.organizationLogPathTemplate.match(organizationLogName).log; + return this.pathTemplates.organizationLogPathTemplate.match( + organizationLogName, + ).log; } /** @@ -2288,7 +2662,7 @@ export class LoggingServiceV2Client { * @param {string} organization * @returns {string} Resource name string. */ - organizationSettingsPath(organization:string) { + organizationSettingsPath(organization: string) { return this.pathTemplates.organizationSettingsPathTemplate.render({ organization: organization, }); @@ -2301,8 +2675,12 @@ export class LoggingServiceV2Client { * A fully-qualified path representing organization_settings resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationSettingsName(organizationSettingsName: string) { - return this.pathTemplates.organizationSettingsPathTemplate.match(organizationSettingsName).organization; + matchOrganizationFromOrganizationSettingsName( + organizationSettingsName: string, + ) { + return this.pathTemplates.organizationSettingsPathTemplate.match( + organizationSettingsName, + ).organization; } /** @@ -2312,7 +2690,7 @@ export class LoggingServiceV2Client { * @param {string} sink * @returns {string} Resource name string. */ - organizationSinkPath(organization:string,sink:string) { + organizationSinkPath(organization: string, sink: string) { return this.pathTemplates.organizationSinkPathTemplate.render({ organization: organization, sink: sink, @@ -2327,7 +2705,9 @@ export class LoggingServiceV2Client { * @returns {string} A string representing the organization. */ matchOrganizationFromOrganizationSinkName(organizationSinkName: string) { - return this.pathTemplates.organizationSinkPathTemplate.match(organizationSinkName).organization; + return this.pathTemplates.organizationSinkPathTemplate.match( + organizationSinkName, + ).organization; } /** @@ -2338,7 +2718,9 @@ export class LoggingServiceV2Client { * @returns {string} A string representing the sink. */ matchSinkFromOrganizationSinkName(organizationSinkName: string) { - return this.pathTemplates.organizationSinkPathTemplate.match(organizationSinkName).sink; + return this.pathTemplates.organizationSinkPathTemplate.match( + organizationSinkName, + ).sink; } /** @@ -2347,7 +2729,7 @@ export class LoggingServiceV2Client { * @param {string} project * @returns {string} Resource name string. */ - projectPath(project:string) { + projectPath(project: string) { return this.pathTemplates.projectPathTemplate.render({ project: project, }); @@ -2370,7 +2752,7 @@ export class LoggingServiceV2Client { * @param {string} project * @returns {string} Resource name string. */ - projectCmekSettingsPath(project:string) { + projectCmekSettingsPath(project: string) { return this.pathTemplates.projectCmekSettingsPathTemplate.render({ project: project, }); @@ -2384,7 +2766,9 @@ export class LoggingServiceV2Client { * @returns {string} A string representing the project. */ matchProjectFromProjectCmekSettingsName(projectCmekSettingsName: string) { - return this.pathTemplates.projectCmekSettingsPathTemplate.match(projectCmekSettingsName).project; + return this.pathTemplates.projectCmekSettingsPathTemplate.match( + projectCmekSettingsName, + ).project; } /** @@ -2394,7 +2778,7 @@ export class LoggingServiceV2Client { * @param {string} exclusion * @returns {string} Resource name string. */ - projectExclusionPath(project:string,exclusion:string) { + projectExclusionPath(project: string, exclusion: string) { return this.pathTemplates.projectExclusionPathTemplate.render({ project: project, exclusion: exclusion, @@ -2409,7 +2793,9 @@ export class LoggingServiceV2Client { * @returns {string} A string representing the project. */ matchProjectFromProjectExclusionName(projectExclusionName: string) { - return this.pathTemplates.projectExclusionPathTemplate.match(projectExclusionName).project; + return this.pathTemplates.projectExclusionPathTemplate.match( + projectExclusionName, + ).project; } /** @@ -2420,7 +2806,9 @@ export class LoggingServiceV2Client { * @returns {string} A string representing the exclusion. */ matchExclusionFromProjectExclusionName(projectExclusionName: string) { - return this.pathTemplates.projectExclusionPathTemplate.match(projectExclusionName).exclusion; + return this.pathTemplates.projectExclusionPathTemplate.match( + projectExclusionName, + ).exclusion; } /** @@ -2431,7 +2819,7 @@ export class LoggingServiceV2Client { * @param {string} bucket * @returns {string} Resource name string. */ - projectLocationBucketPath(project:string,location:string,bucket:string) { + projectLocationBucketPath(project: string, location: string, bucket: string) { return this.pathTemplates.projectLocationBucketPathTemplate.render({ project: project, location: location, @@ -2447,7 +2835,9 @@ export class LoggingServiceV2Client { * @returns {string} A string representing the project. */ matchProjectFromProjectLocationBucketName(projectLocationBucketName: string) { - return this.pathTemplates.projectLocationBucketPathTemplate.match(projectLocationBucketName).project; + return this.pathTemplates.projectLocationBucketPathTemplate.match( + projectLocationBucketName, + ).project; } /** @@ -2457,8 +2847,12 @@ export class LoggingServiceV2Client { * A fully-qualified path representing project_location_bucket resource. * @returns {string} A string representing the location. */ - matchLocationFromProjectLocationBucketName(projectLocationBucketName: string) { - return this.pathTemplates.projectLocationBucketPathTemplate.match(projectLocationBucketName).location; + matchLocationFromProjectLocationBucketName( + projectLocationBucketName: string, + ) { + return this.pathTemplates.projectLocationBucketPathTemplate.match( + projectLocationBucketName, + ).location; } /** @@ -2469,7 +2863,9 @@ export class LoggingServiceV2Client { * @returns {string} A string representing the bucket. */ matchBucketFromProjectLocationBucketName(projectLocationBucketName: string) { - return this.pathTemplates.projectLocationBucketPathTemplate.match(projectLocationBucketName).bucket; + return this.pathTemplates.projectLocationBucketPathTemplate.match( + projectLocationBucketName, + ).bucket; } /** @@ -2481,7 +2877,12 @@ export class LoggingServiceV2Client { * @param {string} view * @returns {string} Resource name string. */ - projectLocationBucketViewPath(project:string,location:string,bucket:string,view:string) { + projectLocationBucketViewPath( + project: string, + location: string, + bucket: string, + view: string, + ) { return this.pathTemplates.projectLocationBucketViewPathTemplate.render({ project: project, location: location, @@ -2497,8 +2898,12 @@ export class LoggingServiceV2Client { * A fully-qualified path representing project_location_bucket_view resource. * @returns {string} A string representing the project. */ - matchProjectFromProjectLocationBucketViewName(projectLocationBucketViewName: string) { - return this.pathTemplates.projectLocationBucketViewPathTemplate.match(projectLocationBucketViewName).project; + matchProjectFromProjectLocationBucketViewName( + projectLocationBucketViewName: string, + ) { + return this.pathTemplates.projectLocationBucketViewPathTemplate.match( + projectLocationBucketViewName, + ).project; } /** @@ -2508,8 +2913,12 @@ export class LoggingServiceV2Client { * A fully-qualified path representing project_location_bucket_view resource. * @returns {string} A string representing the location. */ - matchLocationFromProjectLocationBucketViewName(projectLocationBucketViewName: string) { - return this.pathTemplates.projectLocationBucketViewPathTemplate.match(projectLocationBucketViewName).location; + matchLocationFromProjectLocationBucketViewName( + projectLocationBucketViewName: string, + ) { + return this.pathTemplates.projectLocationBucketViewPathTemplate.match( + projectLocationBucketViewName, + ).location; } /** @@ -2519,8 +2928,12 @@ export class LoggingServiceV2Client { * A fully-qualified path representing project_location_bucket_view resource. * @returns {string} A string representing the bucket. */ - matchBucketFromProjectLocationBucketViewName(projectLocationBucketViewName: string) { - return this.pathTemplates.projectLocationBucketViewPathTemplate.match(projectLocationBucketViewName).bucket; + matchBucketFromProjectLocationBucketViewName( + projectLocationBucketViewName: string, + ) { + return this.pathTemplates.projectLocationBucketViewPathTemplate.match( + projectLocationBucketViewName, + ).bucket; } /** @@ -2530,8 +2943,12 @@ export class LoggingServiceV2Client { * A fully-qualified path representing project_location_bucket_view resource. * @returns {string} A string representing the view. */ - matchViewFromProjectLocationBucketViewName(projectLocationBucketViewName: string) { - return this.pathTemplates.projectLocationBucketViewPathTemplate.match(projectLocationBucketViewName).view; + matchViewFromProjectLocationBucketViewName( + projectLocationBucketViewName: string, + ) { + return this.pathTemplates.projectLocationBucketViewPathTemplate.match( + projectLocationBucketViewName, + ).view; } /** @@ -2541,7 +2958,7 @@ export class LoggingServiceV2Client { * @param {string} log * @returns {string} Resource name string. */ - projectLogPath(project:string,log:string) { + projectLogPath(project: string, log: string) { return this.pathTemplates.projectLogPathTemplate.render({ project: project, log: log, @@ -2556,7 +2973,8 @@ export class LoggingServiceV2Client { * @returns {string} A string representing the project. */ matchProjectFromProjectLogName(projectLogName: string) { - return this.pathTemplates.projectLogPathTemplate.match(projectLogName).project; + return this.pathTemplates.projectLogPathTemplate.match(projectLogName) + .project; } /** @@ -2576,7 +2994,7 @@ export class LoggingServiceV2Client { * @param {string} project * @returns {string} Resource name string. */ - projectSettingsPath(project:string) { + projectSettingsPath(project: string) { return this.pathTemplates.projectSettingsPathTemplate.render({ project: project, }); @@ -2590,7 +3008,9 @@ export class LoggingServiceV2Client { * @returns {string} A string representing the project. */ matchProjectFromProjectSettingsName(projectSettingsName: string) { - return this.pathTemplates.projectSettingsPathTemplate.match(projectSettingsName).project; + return this.pathTemplates.projectSettingsPathTemplate.match( + projectSettingsName, + ).project; } /** @@ -2600,7 +3020,7 @@ export class LoggingServiceV2Client { * @param {string} sink * @returns {string} Resource name string. */ - projectSinkPath(project:string,sink:string) { + projectSinkPath(project: string, sink: string) { return this.pathTemplates.projectSinkPathTemplate.render({ project: project, sink: sink, @@ -2615,7 +3035,8 @@ export class LoggingServiceV2Client { * @returns {string} A string representing the project. */ matchProjectFromProjectSinkName(projectSinkName: string) { - return this.pathTemplates.projectSinkPathTemplate.match(projectSinkName).project; + return this.pathTemplates.projectSinkPathTemplate.match(projectSinkName) + .project; } /** @@ -2626,7 +3047,8 @@ export class LoggingServiceV2Client { * @returns {string} A string representing the sink. */ matchSinkFromProjectSinkName(projectSinkName: string) { - return this.pathTemplates.projectSinkPathTemplate.match(projectSinkName).sink; + return this.pathTemplates.projectSinkPathTemplate.match(projectSinkName) + .sink; } /** @@ -2637,7 +3059,7 @@ export class LoggingServiceV2Client { */ close(): Promise { if (this.loggingServiceV2Stub && !this._terminated) { - return this.loggingServiceV2Stub.then(stub => { + return this.loggingServiceV2Stub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -2645,4 +3067,4 @@ export class LoggingServiceV2Client { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/core/generator/gapic-generator-typescript/baselines/logging-esm/esm/src/v2/metrics_service_v2_client.ts.baseline b/core/generator/gapic-generator-typescript/baselines/logging-esm/esm/src/v2/metrics_service_v2_client.ts.baseline index b0fe3de47730..e8b830c8a2d8 100644 --- a/core/generator/gapic-generator-typescript/baselines/logging-esm/esm/src/v2/metrics_service_v2_client.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/logging-esm/esm/src/v2/metrics_service_v2_client.ts.baseline @@ -18,15 +18,22 @@ /* global window */ import * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions, PaginationCallback, GaxCall} from 'google-gax'; -import {Transform} from 'stream'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + PaginationCallback, + GaxCall, +} from 'google-gax'; +import { Transform } from 'stream'; // @ts-ignore import type * as protos from '../../../protos/protos.js'; import * as metrics_service_v2_client_config from './metrics_service_v2_client_config.json'; import fs from 'fs'; import path from 'path'; -import {fileURLToPath} from 'url'; -import {getJSON} from '../json-helper.cjs'; +import { fileURLToPath } from 'url'; +import { getJSON } from '../json-helper.cjs'; // @ts-ignore const dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -36,15 +43,15 @@ const dirname = path.dirname(fileURLToPath(import.meta.url)); * This file defines retry strategy and timeouts for all API methods in this library. */ const gapicConfig = getJSON( - path.join(dirname, 'metrics_service_v2_client_config.json') + path.join(dirname, 'metrics_service_v2_client_config.json'), ); const jsonProtos = getJSON( - path.join(dirname, '..', '..', '..', 'protos/protos.json') + path.join(dirname, '..', '..', '..', 'protos/protos.json'), ); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; const version = getJSON( - path.join(dirname, '..', '..', '..', '..', 'package.json') + path.join(dirname, '..', '..', '..', '..', 'package.json'), ).version; /** @@ -59,7 +66,7 @@ export class MetricsServiceV2Client { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('logging'); @@ -71,9 +78,9 @@ export class MetricsServiceV2Client { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; - metricsServiceV2Stub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; + metricsServiceV2Stub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of MetricsServiceV2Client. @@ -115,21 +122,42 @@ export class MetricsServiceV2Client { * const client = new MetricsServiceV2Client({fallback: 'rest'}, gax); * ``` */ - constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { // Ensure that options include all the required fields. const staticMembers = this.constructor as typeof MetricsServiceV2Client; - if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { - throw new Error('Please set either universe_domain or universeDomain, but not both.'); + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); } - const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; - this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; this._servicePath = 'logging.' + this._universeDomain; - const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; - const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. if (servicePath !== this._servicePath && !('scopes' in opts)) { @@ -151,7 +179,7 @@ export class MetricsServiceV2Client { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; @@ -168,10 +196,7 @@ export class MetricsServiceV2Client { const isEsm = true; const isEsmString = isEsm ? '-esm' : '-cjs'; // Determine the client header string. - const clientHeader = [ - `gax/${this._gaxModule.version}`, - `gapic/${version}`, - ]; + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/{process.versions.node}${isEsmString}`); } else { @@ -179,7 +204,7 @@ export class MetricsServiceV2Client { } if (!opts.fallback) { clientHeader.push(`grpc/${this._gaxGrpc.grpcVersion}`); - } else if (opts.fallback === 'rest' ) { + } else if (opts.fallback === 'rest') { clientHeader.push(`rest/${this._gaxGrpc.grpcVersion}`); } if (opts.libName && opts.libVersion) { @@ -187,101 +212,106 @@ export class MetricsServiceV2Client { } // Load the applicable protos. - this._protos = this._gaxGrpc.loadProtoJSON(jsonProtos as gax.protobuf.INamespace); + this._protos = this._gaxGrpc.loadProtoJSON( + jsonProtos as gax.protobuf.INamespace, + ); // This API contains "path templates"; forward-slash-separated // identifiers to uniquely identify resources within the API. // Create useful helper objects for these. this.pathTemplates = { billingAccountCmekSettingsPathTemplate: new this._gaxModule.PathTemplate( - 'billingAccounts/{billing_account}/cmekSettings' + 'billingAccounts/{billing_account}/cmekSettings', ), billingAccountExclusionPathTemplate: new this._gaxModule.PathTemplate( - 'billingAccounts/{billing_account}/exclusions/{exclusion}' - ), - billingAccountLocationBucketPathTemplate: new this._gaxModule.PathTemplate( - 'billingAccounts/{billing_account}/locations/{location}/buckets/{bucket}' - ), - billingAccountLocationBucketViewPathTemplate: new this._gaxModule.PathTemplate( - 'billingAccounts/{billing_account}/locations/{location}/buckets/{bucket}/views/{view}' + 'billingAccounts/{billing_account}/exclusions/{exclusion}', ), + billingAccountLocationBucketPathTemplate: + new this._gaxModule.PathTemplate( + 'billingAccounts/{billing_account}/locations/{location}/buckets/{bucket}', + ), + billingAccountLocationBucketViewPathTemplate: + new this._gaxModule.PathTemplate( + 'billingAccounts/{billing_account}/locations/{location}/buckets/{bucket}/views/{view}', + ), billingAccountLogPathTemplate: new this._gaxModule.PathTemplate( - 'billingAccounts/{billing_account}/logs/{log}' + 'billingAccounts/{billing_account}/logs/{log}', ), billingAccountSettingsPathTemplate: new this._gaxModule.PathTemplate( - 'billingAccounts/{billing_account}/settings' + 'billingAccounts/{billing_account}/settings', ), billingAccountSinkPathTemplate: new this._gaxModule.PathTemplate( - 'billingAccounts/{billing_account}/sinks/{sink}' + 'billingAccounts/{billing_account}/sinks/{sink}', ), folderCmekSettingsPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/cmekSettings' + 'folders/{folder}/cmekSettings', ), folderExclusionPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/exclusions/{exclusion}' + 'folders/{folder}/exclusions/{exclusion}', ), folderLocationBucketPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/locations/{location}/buckets/{bucket}' + 'folders/{folder}/locations/{location}/buckets/{bucket}', ), folderLocationBucketViewPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/locations/{location}/buckets/{bucket}/views/{view}' + 'folders/{folder}/locations/{location}/buckets/{bucket}/views/{view}', ), folderLogPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/logs/{log}' + 'folders/{folder}/logs/{log}', ), folderSettingsPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/settings' + 'folders/{folder}/settings', ), folderSinkPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/sinks/{sink}' + 'folders/{folder}/sinks/{sink}', ), logMetricPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/metrics/{metric}' + 'projects/{project}/metrics/{metric}', ), organizationCmekSettingsPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/cmekSettings' + 'organizations/{organization}/cmekSettings', ), organizationExclusionPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/exclusions/{exclusion}' + 'organizations/{organization}/exclusions/{exclusion}', ), organizationLocationBucketPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/locations/{location}/buckets/{bucket}' - ), - organizationLocationBucketViewPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/locations/{location}/buckets/{bucket}/views/{view}' + 'organizations/{organization}/locations/{location}/buckets/{bucket}', ), + organizationLocationBucketViewPathTemplate: + new this._gaxModule.PathTemplate( + 'organizations/{organization}/locations/{location}/buckets/{bucket}/views/{view}', + ), organizationLogPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/logs/{log}' + 'organizations/{organization}/logs/{log}', ), organizationSettingsPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/settings' + 'organizations/{organization}/settings', ), organizationSinkPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/sinks/{sink}' + 'organizations/{organization}/sinks/{sink}', ), projectPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}' + 'projects/{project}', ), projectCmekSettingsPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/cmekSettings' + 'projects/{project}/cmekSettings', ), projectExclusionPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/exclusions/{exclusion}' + 'projects/{project}/exclusions/{exclusion}', ), projectLocationBucketPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/buckets/{bucket}' + 'projects/{project}/locations/{location}/buckets/{bucket}', ), projectLocationBucketViewPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/buckets/{bucket}/views/{view}' + 'projects/{project}/locations/{location}/buckets/{bucket}/views/{view}', ), projectLogPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/logs/{log}' + 'projects/{project}/logs/{log}', ), projectSettingsPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/settings' + 'projects/{project}/settings', ), projectSinkPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/sinks/{sink}' + 'projects/{project}/sinks/{sink}', ), }; @@ -289,14 +319,20 @@ export class MetricsServiceV2Client { // (e.g. 50 results at a time, with tokens to get subsequent // pages). Denote the keys used for pagination and results. this.descriptors.page = { - listLogMetrics: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'metrics') + listLogMetrics: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'metrics', + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.logging.v2.MetricsServiceV2', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.logging.v2.MetricsServiceV2', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + { 'x-goog-api-client': clientHeader.join(' ') }, + ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -327,37 +363,46 @@ export class MetricsServiceV2Client { // Put together the "service stub" for // google.logging.v2.MetricsServiceV2. this.metricsServiceV2Stub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.logging.v2.MetricsServiceV2') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.logging.v2.MetricsServiceV2', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.logging.v2.MetricsServiceV2, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts, + this._providedCustomServicePath, + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const metricsServiceV2StubMethods = - ['listLogMetrics', 'getLogMetric', 'createLogMetric', 'updateLogMetric', 'deleteLogMetric']; + const metricsServiceV2StubMethods = [ + 'listLogMetrics', + 'getLogMetric', + 'createLogMetric', + 'updateLogMetric', + 'deleteLogMetric', + ]; for (const methodName of metricsServiceV2StubMethods) { const callPromise = this.metricsServiceV2Stub.then( - stub => (...args: Array<{}>) => { - if (this._terminated) { - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error|null|undefined) => () => { + (stub) => + (...args: Array<{}>) => { + if (this._terminated) { + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { throw err; - }); + }, + ); - const descriptor = - this.descriptors.page[methodName] || - undefined; + const descriptor = this.descriptors.page[methodName] || undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -372,8 +417,14 @@ export class MetricsServiceV2Client { * @returns {string} The DNS address for this service. */ static get servicePath() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'logging.googleapis.com'; } @@ -385,8 +436,14 @@ export class MetricsServiceV2Client { * @returns {string} The DNS address for this service. */ static get apiEndpoint() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'logging.googleapis.com'; } @@ -422,7 +479,7 @@ export class MetricsServiceV2Client { 'https://www.googleapis.com/auth/cloud-platform.read-only', 'https://www.googleapis.com/auth/logging.admin', 'https://www.googleapis.com/auth/logging.read', - 'https://www.googleapis.com/auth/logging.write' + 'https://www.googleapis.com/auth/logging.write', ]; } @@ -432,8 +489,9 @@ export class MetricsServiceV2Client { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId(callback?: Callback): - Promise|void { + getProjectId( + callback?: Callback, + ): Promise | void { if (callback) { this.auth.getProjectId(callback); return; @@ -444,486 +502,625 @@ export class MetricsServiceV2Client { // ------------------- // -- Service calls -- // ------------------- -/** - * Gets a logs-based metric. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.metricName - * Required. The resource name of the desired metric: - * - * "projects/[PROJECT_ID]/metrics/[METRIC_ID]" - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.logging.v2.LogMetric|LogMetric}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/metrics_service_v2.get_log_metric.js - * region_tag:logging_v2_generated_MetricsServiceV2_GetLogMetric_async - */ + /** + * Gets a logs-based metric. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.metricName + * Required. The resource name of the desired metric: + * + * "projects/[PROJECT_ID]/metrics/[METRIC_ID]" + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.logging.v2.LogMetric|LogMetric}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/metrics_service_v2.get_log_metric.js + * region_tag:logging_v2_generated_MetricsServiceV2_GetLogMetric_async + */ getLogMetric( - request?: protos.google.logging.v2.IGetLogMetricRequest, - options?: CallOptions): - Promise<[ - protos.google.logging.v2.ILogMetric, - protos.google.logging.v2.IGetLogMetricRequest|undefined, {}|undefined - ]>; + request?: protos.google.logging.v2.IGetLogMetricRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.logging.v2.ILogMetric, + protos.google.logging.v2.IGetLogMetricRequest | undefined, + {} | undefined, + ] + >; getLogMetric( - request: protos.google.logging.v2.IGetLogMetricRequest, - options: CallOptions, - callback: Callback< - protos.google.logging.v2.ILogMetric, - protos.google.logging.v2.IGetLogMetricRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.logging.v2.IGetLogMetricRequest, + options: CallOptions, + callback: Callback< + protos.google.logging.v2.ILogMetric, + protos.google.logging.v2.IGetLogMetricRequest | null | undefined, + {} | null | undefined + >, + ): void; getLogMetric( - request: protos.google.logging.v2.IGetLogMetricRequest, - callback: Callback< - protos.google.logging.v2.ILogMetric, - protos.google.logging.v2.IGetLogMetricRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.logging.v2.IGetLogMetricRequest, + callback: Callback< + protos.google.logging.v2.ILogMetric, + protos.google.logging.v2.IGetLogMetricRequest | null | undefined, + {} | null | undefined + >, + ): void; getLogMetric( - request?: protos.google.logging.v2.IGetLogMetricRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.logging.v2.ILogMetric, - protos.google.logging.v2.IGetLogMetricRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.logging.v2.IGetLogMetricRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.logging.v2.ILogMetric, - protos.google.logging.v2.IGetLogMetricRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.logging.v2.ILogMetric, - protos.google.logging.v2.IGetLogMetricRequest|undefined, {}|undefined - ]>|void { + protos.google.logging.v2.IGetLogMetricRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.logging.v2.ILogMetric, + protos.google.logging.v2.IGetLogMetricRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.logging.v2.ILogMetric, + protos.google.logging.v2.IGetLogMetricRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'metric_name': request.metricName ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + metric_name: request.metricName ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getLogMetric request %j', request); - const wrappedCallback: Callback< - protos.google.logging.v2.ILogMetric, - protos.google.logging.v2.IGetLogMetricRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.logging.v2.ILogMetric, + protos.google.logging.v2.IGetLogMetricRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getLogMetric response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.getLogMetric(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.logging.v2.ILogMetric, - protos.google.logging.v2.IGetLogMetricRequest|undefined, {}|undefined - ]) => { - this._log.info('getLogMetric response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getLogMetric(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.logging.v2.ILogMetric, + protos.google.logging.v2.IGetLogMetricRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getLogMetric response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Creates a logs-based metric. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The resource name of the project in which to create the metric: - * - * "projects/[PROJECT_ID]" - * - * The new metric must be provided in the request. - * @param {google.logging.v2.LogMetric} request.metric - * Required. The new logs-based metric, which must not have an identifier that - * already exists. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.logging.v2.LogMetric|LogMetric}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/metrics_service_v2.create_log_metric.js - * region_tag:logging_v2_generated_MetricsServiceV2_CreateLogMetric_async - */ + /** + * Creates a logs-based metric. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The resource name of the project in which to create the metric: + * + * "projects/[PROJECT_ID]" + * + * The new metric must be provided in the request. + * @param {google.logging.v2.LogMetric} request.metric + * Required. The new logs-based metric, which must not have an identifier that + * already exists. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.logging.v2.LogMetric|LogMetric}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/metrics_service_v2.create_log_metric.js + * region_tag:logging_v2_generated_MetricsServiceV2_CreateLogMetric_async + */ createLogMetric( - request?: protos.google.logging.v2.ICreateLogMetricRequest, - options?: CallOptions): - Promise<[ - protos.google.logging.v2.ILogMetric, - protos.google.logging.v2.ICreateLogMetricRequest|undefined, {}|undefined - ]>; + request?: protos.google.logging.v2.ICreateLogMetricRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.logging.v2.ILogMetric, + protos.google.logging.v2.ICreateLogMetricRequest | undefined, + {} | undefined, + ] + >; createLogMetric( - request: protos.google.logging.v2.ICreateLogMetricRequest, - options: CallOptions, - callback: Callback< - protos.google.logging.v2.ILogMetric, - protos.google.logging.v2.ICreateLogMetricRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.logging.v2.ICreateLogMetricRequest, + options: CallOptions, + callback: Callback< + protos.google.logging.v2.ILogMetric, + protos.google.logging.v2.ICreateLogMetricRequest | null | undefined, + {} | null | undefined + >, + ): void; createLogMetric( - request: protos.google.logging.v2.ICreateLogMetricRequest, - callback: Callback< - protos.google.logging.v2.ILogMetric, - protos.google.logging.v2.ICreateLogMetricRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.logging.v2.ICreateLogMetricRequest, + callback: Callback< + protos.google.logging.v2.ILogMetric, + protos.google.logging.v2.ICreateLogMetricRequest | null | undefined, + {} | null | undefined + >, + ): void; createLogMetric( - request?: protos.google.logging.v2.ICreateLogMetricRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.logging.v2.ILogMetric, - protos.google.logging.v2.ICreateLogMetricRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.logging.v2.ICreateLogMetricRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.logging.v2.ILogMetric, - protos.google.logging.v2.ICreateLogMetricRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.logging.v2.ILogMetric, - protos.google.logging.v2.ICreateLogMetricRequest|undefined, {}|undefined - ]>|void { + protos.google.logging.v2.ICreateLogMetricRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.logging.v2.ILogMetric, + protos.google.logging.v2.ICreateLogMetricRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.logging.v2.ILogMetric, + protos.google.logging.v2.ICreateLogMetricRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('createLogMetric request %j', request); - const wrappedCallback: Callback< - protos.google.logging.v2.ILogMetric, - protos.google.logging.v2.ICreateLogMetricRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.logging.v2.ILogMetric, + protos.google.logging.v2.ICreateLogMetricRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createLogMetric response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.createLogMetric(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.logging.v2.ILogMetric, - protos.google.logging.v2.ICreateLogMetricRequest|undefined, {}|undefined - ]) => { - this._log.info('createLogMetric response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createLogMetric(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.logging.v2.ILogMetric, + protos.google.logging.v2.ICreateLogMetricRequest | undefined, + {} | undefined, + ]) => { + this._log.info('createLogMetric response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Creates or updates a logs-based metric. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.metricName - * Required. The resource name of the metric to update: - * - * "projects/[PROJECT_ID]/metrics/[METRIC_ID]" - * - * The updated metric must be provided in the request and it's - * `name` field must be the same as `[METRIC_ID]` If the metric - * does not exist in `[PROJECT_ID]`, then a new metric is created. - * @param {google.logging.v2.LogMetric} request.metric - * Required. The updated metric. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.logging.v2.LogMetric|LogMetric}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/metrics_service_v2.update_log_metric.js - * region_tag:logging_v2_generated_MetricsServiceV2_UpdateLogMetric_async - */ + /** + * Creates or updates a logs-based metric. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.metricName + * Required. The resource name of the metric to update: + * + * "projects/[PROJECT_ID]/metrics/[METRIC_ID]" + * + * The updated metric must be provided in the request and it's + * `name` field must be the same as `[METRIC_ID]` If the metric + * does not exist in `[PROJECT_ID]`, then a new metric is created. + * @param {google.logging.v2.LogMetric} request.metric + * Required. The updated metric. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.logging.v2.LogMetric|LogMetric}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/metrics_service_v2.update_log_metric.js + * region_tag:logging_v2_generated_MetricsServiceV2_UpdateLogMetric_async + */ updateLogMetric( - request?: protos.google.logging.v2.IUpdateLogMetricRequest, - options?: CallOptions): - Promise<[ - protos.google.logging.v2.ILogMetric, - protos.google.logging.v2.IUpdateLogMetricRequest|undefined, {}|undefined - ]>; + request?: protos.google.logging.v2.IUpdateLogMetricRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.logging.v2.ILogMetric, + protos.google.logging.v2.IUpdateLogMetricRequest | undefined, + {} | undefined, + ] + >; updateLogMetric( - request: protos.google.logging.v2.IUpdateLogMetricRequest, - options: CallOptions, - callback: Callback< - protos.google.logging.v2.ILogMetric, - protos.google.logging.v2.IUpdateLogMetricRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.logging.v2.IUpdateLogMetricRequest, + options: CallOptions, + callback: Callback< + protos.google.logging.v2.ILogMetric, + protos.google.logging.v2.IUpdateLogMetricRequest | null | undefined, + {} | null | undefined + >, + ): void; updateLogMetric( - request: protos.google.logging.v2.IUpdateLogMetricRequest, - callback: Callback< - protos.google.logging.v2.ILogMetric, - protos.google.logging.v2.IUpdateLogMetricRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.logging.v2.IUpdateLogMetricRequest, + callback: Callback< + protos.google.logging.v2.ILogMetric, + protos.google.logging.v2.IUpdateLogMetricRequest | null | undefined, + {} | null | undefined + >, + ): void; updateLogMetric( - request?: protos.google.logging.v2.IUpdateLogMetricRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.logging.v2.ILogMetric, - protos.google.logging.v2.IUpdateLogMetricRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.logging.v2.IUpdateLogMetricRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.logging.v2.ILogMetric, - protos.google.logging.v2.IUpdateLogMetricRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.logging.v2.ILogMetric, - protos.google.logging.v2.IUpdateLogMetricRequest|undefined, {}|undefined - ]>|void { + protos.google.logging.v2.IUpdateLogMetricRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.logging.v2.ILogMetric, + protos.google.logging.v2.IUpdateLogMetricRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.logging.v2.ILogMetric, + protos.google.logging.v2.IUpdateLogMetricRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'metric_name': request.metricName ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + metric_name: request.metricName ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateLogMetric request %j', request); - const wrappedCallback: Callback< - protos.google.logging.v2.ILogMetric, - protos.google.logging.v2.IUpdateLogMetricRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.logging.v2.ILogMetric, + protos.google.logging.v2.IUpdateLogMetricRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateLogMetric response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.updateLogMetric(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.logging.v2.ILogMetric, - protos.google.logging.v2.IUpdateLogMetricRequest|undefined, {}|undefined - ]) => { - this._log.info('updateLogMetric response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateLogMetric(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.logging.v2.ILogMetric, + protos.google.logging.v2.IUpdateLogMetricRequest | undefined, + {} | undefined, + ]) => { + this._log.info('updateLogMetric response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Deletes a logs-based metric. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.metricName - * Required. The resource name of the metric to delete: - * - * "projects/[PROJECT_ID]/metrics/[METRIC_ID]" - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/metrics_service_v2.delete_log_metric.js - * region_tag:logging_v2_generated_MetricsServiceV2_DeleteLogMetric_async - */ + /** + * Deletes a logs-based metric. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.metricName + * Required. The resource name of the metric to delete: + * + * "projects/[PROJECT_ID]/metrics/[METRIC_ID]" + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/metrics_service_v2.delete_log_metric.js + * region_tag:logging_v2_generated_MetricsServiceV2_DeleteLogMetric_async + */ deleteLogMetric( - request?: protos.google.logging.v2.IDeleteLogMetricRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.logging.v2.IDeleteLogMetricRequest|undefined, {}|undefined - ]>; + request?: protos.google.logging.v2.IDeleteLogMetricRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.logging.v2.IDeleteLogMetricRequest | undefined, + {} | undefined, + ] + >; deleteLogMetric( - request: protos.google.logging.v2.IDeleteLogMetricRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.logging.v2.IDeleteLogMetricRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.logging.v2.IDeleteLogMetricRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.logging.v2.IDeleteLogMetricRequest | null | undefined, + {} | null | undefined + >, + ): void; deleteLogMetric( - request: protos.google.logging.v2.IDeleteLogMetricRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.logging.v2.IDeleteLogMetricRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.logging.v2.IDeleteLogMetricRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.logging.v2.IDeleteLogMetricRequest | null | undefined, + {} | null | undefined + >, + ): void; deleteLogMetric( - request?: protos.google.logging.v2.IDeleteLogMetricRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.logging.v2.IDeleteLogMetricRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.logging.v2.IDeleteLogMetricRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.protobuf.IEmpty, - protos.google.logging.v2.IDeleteLogMetricRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.logging.v2.IDeleteLogMetricRequest|undefined, {}|undefined - ]>|void { + protos.google.logging.v2.IDeleteLogMetricRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + protos.google.logging.v2.IDeleteLogMetricRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.logging.v2.IDeleteLogMetricRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'metric_name': request.metricName ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + metric_name: request.metricName ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('deleteLogMetric request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.logging.v2.IDeleteLogMetricRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + protos.google.logging.v2.IDeleteLogMetricRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteLogMetric response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.deleteLogMetric(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.logging.v2.IDeleteLogMetricRequest|undefined, {}|undefined - ]) => { - this._log.info('deleteLogMetric response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteLogMetric(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.logging.v2.IDeleteLogMetricRequest | undefined, + {} | undefined, + ]) => { + this._log.info('deleteLogMetric response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } - /** - * Lists logs-based metrics. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The name of the project containing the metrics: - * - * "projects/[PROJECT_ID]" - * @param {string} [request.pageToken] - * Optional. If present, then retrieve the next batch of results from the - * preceding call to this method. `pageToken` must be the value of - * `nextPageToken` from the previous response. The values of other method - * parameters should be identical to those in the previous call. - * @param {number} [request.pageSize] - * Optional. The maximum number of results to return from this request. - * Non-positive values are ignored. The presence of `nextPageToken` in the - * response indicates that more results might be available. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.logging.v2.LogMetric|LogMetric}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `listLogMetricsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Lists logs-based metrics. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The name of the project containing the metrics: + * + * "projects/[PROJECT_ID]" + * @param {string} [request.pageToken] + * Optional. If present, then retrieve the next batch of results from the + * preceding call to this method. `pageToken` must be the value of + * `nextPageToken` from the previous response. The values of other method + * parameters should be identical to those in the previous call. + * @param {number} [request.pageSize] + * Optional. The maximum number of results to return from this request. + * Non-positive values are ignored. The presence of `nextPageToken` in the + * response indicates that more results might be available. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.logging.v2.LogMetric|LogMetric}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listLogMetricsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listLogMetrics( - request?: protos.google.logging.v2.IListLogMetricsRequest, - options?: CallOptions): - Promise<[ - protos.google.logging.v2.ILogMetric[], - protos.google.logging.v2.IListLogMetricsRequest|null, - protos.google.logging.v2.IListLogMetricsResponse - ]>; + request?: protos.google.logging.v2.IListLogMetricsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.logging.v2.ILogMetric[], + protos.google.logging.v2.IListLogMetricsRequest | null, + protos.google.logging.v2.IListLogMetricsResponse, + ] + >; listLogMetrics( - request: protos.google.logging.v2.IListLogMetricsRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.logging.v2.IListLogMetricsRequest, - protos.google.logging.v2.IListLogMetricsResponse|null|undefined, - protos.google.logging.v2.ILogMetric>): void; + request: protos.google.logging.v2.IListLogMetricsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.logging.v2.IListLogMetricsRequest, + protos.google.logging.v2.IListLogMetricsResponse | null | undefined, + protos.google.logging.v2.ILogMetric + >, + ): void; listLogMetrics( - request: protos.google.logging.v2.IListLogMetricsRequest, - callback: PaginationCallback< - protos.google.logging.v2.IListLogMetricsRequest, - protos.google.logging.v2.IListLogMetricsResponse|null|undefined, - protos.google.logging.v2.ILogMetric>): void; + request: protos.google.logging.v2.IListLogMetricsRequest, + callback: PaginationCallback< + protos.google.logging.v2.IListLogMetricsRequest, + protos.google.logging.v2.IListLogMetricsResponse | null | undefined, + protos.google.logging.v2.ILogMetric + >, + ): void; listLogMetrics( - request?: protos.google.logging.v2.IListLogMetricsRequest, - optionsOrCallback?: CallOptions|PaginationCallback< + request?: protos.google.logging.v2.IListLogMetricsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.logging.v2.IListLogMetricsRequest, - protos.google.logging.v2.IListLogMetricsResponse|null|undefined, - protos.google.logging.v2.ILogMetric>, - callback?: PaginationCallback< - protos.google.logging.v2.IListLogMetricsRequest, - protos.google.logging.v2.IListLogMetricsResponse|null|undefined, - protos.google.logging.v2.ILogMetric>): - Promise<[ - protos.google.logging.v2.ILogMetric[], - protos.google.logging.v2.IListLogMetricsRequest|null, - protos.google.logging.v2.IListLogMetricsResponse - ]>|void { + protos.google.logging.v2.IListLogMetricsResponse | null | undefined, + protos.google.logging.v2.ILogMetric + >, + callback?: PaginationCallback< + protos.google.logging.v2.IListLogMetricsRequest, + protos.google.logging.v2.IListLogMetricsResponse | null | undefined, + protos.google.logging.v2.ILogMetric + >, + ): Promise< + [ + protos.google.logging.v2.ILogMetric[], + protos.google.logging.v2.IListLogMetricsRequest | null, + protos.google.logging.v2.IListLogMetricsResponse, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.logging.v2.IListLogMetricsRequest, - protos.google.logging.v2.IListLogMetricsResponse|null|undefined, - protos.google.logging.v2.ILogMetric>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.logging.v2.IListLogMetricsRequest, + protos.google.logging.v2.IListLogMetricsResponse | null | undefined, + protos.google.logging.v2.ILogMetric + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listLogMetrics values %j', values); callback!(error, values, nextPageRequest, rawResponse); @@ -932,120 +1129,124 @@ export class MetricsServiceV2Client { this._log.info('listLogMetrics request %j', request); return this.innerApiCalls .listLogMetrics(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.logging.v2.ILogMetric[], - protos.google.logging.v2.IListLogMetricsRequest|null, - protos.google.logging.v2.IListLogMetricsResponse - ]) => { - this._log.info('listLogMetrics values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.logging.v2.ILogMetric[], + protos.google.logging.v2.IListLogMetricsRequest | null, + protos.google.logging.v2.IListLogMetricsResponse, + ]) => { + this._log.info('listLogMetrics values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listLogMetrics`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The name of the project containing the metrics: - * - * "projects/[PROJECT_ID]" - * @param {string} [request.pageToken] - * Optional. If present, then retrieve the next batch of results from the - * preceding call to this method. `pageToken` must be the value of - * `nextPageToken` from the previous response. The values of other method - * parameters should be identical to those in the previous call. - * @param {number} [request.pageSize] - * Optional. The maximum number of results to return from this request. - * Non-positive values are ignored. The presence of `nextPageToken` in the - * response indicates that more results might be available. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.logging.v2.LogMetric|LogMetric} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `listLogMetricsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `listLogMetrics`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The name of the project containing the metrics: + * + * "projects/[PROJECT_ID]" + * @param {string} [request.pageToken] + * Optional. If present, then retrieve the next batch of results from the + * preceding call to this method. `pageToken` must be the value of + * `nextPageToken` from the previous response. The values of other method + * parameters should be identical to those in the previous call. + * @param {number} [request.pageSize] + * Optional. The maximum number of results to return from this request. + * Non-positive values are ignored. The presence of `nextPageToken` in the + * response indicates that more results might be available. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.logging.v2.LogMetric|LogMetric} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listLogMetricsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listLogMetricsStream( - request?: protos.google.logging.v2.IListLogMetricsRequest, - options?: CallOptions): - Transform{ + request?: protos.google.logging.v2.IListLogMetricsRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); const defaultCallSettings = this._defaults['listLogMetrics']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listLogMetrics stream %j', request); return this.descriptors.page.listLogMetrics.createStream( this.innerApiCalls.listLogMetrics as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listLogMetrics`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The name of the project containing the metrics: - * - * "projects/[PROJECT_ID]" - * @param {string} [request.pageToken] - * Optional. If present, then retrieve the next batch of results from the - * preceding call to this method. `pageToken` must be the value of - * `nextPageToken` from the previous response. The values of other method - * parameters should be identical to those in the previous call. - * @param {number} [request.pageSize] - * Optional. The maximum number of results to return from this request. - * Non-positive values are ignored. The presence of `nextPageToken` in the - * response indicates that more results might be available. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.logging.v2.LogMetric|LogMetric}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v2/metrics_service_v2.list_log_metrics.js - * region_tag:logging_v2_generated_MetricsServiceV2_ListLogMetrics_async - */ + /** + * Equivalent to `listLogMetrics`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The name of the project containing the metrics: + * + * "projects/[PROJECT_ID]" + * @param {string} [request.pageToken] + * Optional. If present, then retrieve the next batch of results from the + * preceding call to this method. `pageToken` must be the value of + * `nextPageToken` from the previous response. The values of other method + * parameters should be identical to those in the previous call. + * @param {number} [request.pageSize] + * Optional. The maximum number of results to return from this request. + * Non-positive values are ignored. The presence of `nextPageToken` in the + * response indicates that more results might be available. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.logging.v2.LogMetric|LogMetric}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v2/metrics_service_v2.list_log_metrics.js + * region_tag:logging_v2_generated_MetricsServiceV2_ListLogMetrics_async + */ listLogMetricsAsync( - request?: protos.google.logging.v2.IListLogMetricsRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.logging.v2.IListLogMetricsRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); const defaultCallSettings = this._defaults['listLogMetrics']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listLogMetrics iterate %j', request); return this.descriptors.page.listLogMetrics.asyncIterate( this.innerApiCalls['listLogMetrics'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } // -------------------- @@ -1058,7 +1259,7 @@ export class MetricsServiceV2Client { * @param {string} billing_account * @returns {string} Resource name string. */ - billingAccountCmekSettingsPath(billingAccount:string) { + billingAccountCmekSettingsPath(billingAccount: string) { return this.pathTemplates.billingAccountCmekSettingsPathTemplate.render({ billing_account: billingAccount, }); @@ -1071,8 +1272,12 @@ export class MetricsServiceV2Client { * A fully-qualified path representing billing_account_cmekSettings resource. * @returns {string} A string representing the billing_account. */ - matchBillingAccountFromBillingAccountCmekSettingsName(billingAccountCmekSettingsName: string) { - return this.pathTemplates.billingAccountCmekSettingsPathTemplate.match(billingAccountCmekSettingsName).billing_account; + matchBillingAccountFromBillingAccountCmekSettingsName( + billingAccountCmekSettingsName: string, + ) { + return this.pathTemplates.billingAccountCmekSettingsPathTemplate.match( + billingAccountCmekSettingsName, + ).billing_account; } /** @@ -1082,7 +1287,7 @@ export class MetricsServiceV2Client { * @param {string} exclusion * @returns {string} Resource name string. */ - billingAccountExclusionPath(billingAccount:string,exclusion:string) { + billingAccountExclusionPath(billingAccount: string, exclusion: string) { return this.pathTemplates.billingAccountExclusionPathTemplate.render({ billing_account: billingAccount, exclusion: exclusion, @@ -1096,8 +1301,12 @@ export class MetricsServiceV2Client { * A fully-qualified path representing billing_account_exclusion resource. * @returns {string} A string representing the billing_account. */ - matchBillingAccountFromBillingAccountExclusionName(billingAccountExclusionName: string) { - return this.pathTemplates.billingAccountExclusionPathTemplate.match(billingAccountExclusionName).billing_account; + matchBillingAccountFromBillingAccountExclusionName( + billingAccountExclusionName: string, + ) { + return this.pathTemplates.billingAccountExclusionPathTemplate.match( + billingAccountExclusionName, + ).billing_account; } /** @@ -1107,8 +1316,12 @@ export class MetricsServiceV2Client { * A fully-qualified path representing billing_account_exclusion resource. * @returns {string} A string representing the exclusion. */ - matchExclusionFromBillingAccountExclusionName(billingAccountExclusionName: string) { - return this.pathTemplates.billingAccountExclusionPathTemplate.match(billingAccountExclusionName).exclusion; + matchExclusionFromBillingAccountExclusionName( + billingAccountExclusionName: string, + ) { + return this.pathTemplates.billingAccountExclusionPathTemplate.match( + billingAccountExclusionName, + ).exclusion; } /** @@ -1119,7 +1332,11 @@ export class MetricsServiceV2Client { * @param {string} bucket * @returns {string} Resource name string. */ - billingAccountLocationBucketPath(billingAccount:string,location:string,bucket:string) { + billingAccountLocationBucketPath( + billingAccount: string, + location: string, + bucket: string, + ) { return this.pathTemplates.billingAccountLocationBucketPathTemplate.render({ billing_account: billingAccount, location: location, @@ -1134,8 +1351,12 @@ export class MetricsServiceV2Client { * A fully-qualified path representing billing_account_location_bucket resource. * @returns {string} A string representing the billing_account. */ - matchBillingAccountFromBillingAccountLocationBucketName(billingAccountLocationBucketName: string) { - return this.pathTemplates.billingAccountLocationBucketPathTemplate.match(billingAccountLocationBucketName).billing_account; + matchBillingAccountFromBillingAccountLocationBucketName( + billingAccountLocationBucketName: string, + ) { + return this.pathTemplates.billingAccountLocationBucketPathTemplate.match( + billingAccountLocationBucketName, + ).billing_account; } /** @@ -1145,8 +1366,12 @@ export class MetricsServiceV2Client { * A fully-qualified path representing billing_account_location_bucket resource. * @returns {string} A string representing the location. */ - matchLocationFromBillingAccountLocationBucketName(billingAccountLocationBucketName: string) { - return this.pathTemplates.billingAccountLocationBucketPathTemplate.match(billingAccountLocationBucketName).location; + matchLocationFromBillingAccountLocationBucketName( + billingAccountLocationBucketName: string, + ) { + return this.pathTemplates.billingAccountLocationBucketPathTemplate.match( + billingAccountLocationBucketName, + ).location; } /** @@ -1156,8 +1381,12 @@ export class MetricsServiceV2Client { * A fully-qualified path representing billing_account_location_bucket resource. * @returns {string} A string representing the bucket. */ - matchBucketFromBillingAccountLocationBucketName(billingAccountLocationBucketName: string) { - return this.pathTemplates.billingAccountLocationBucketPathTemplate.match(billingAccountLocationBucketName).bucket; + matchBucketFromBillingAccountLocationBucketName( + billingAccountLocationBucketName: string, + ) { + return this.pathTemplates.billingAccountLocationBucketPathTemplate.match( + billingAccountLocationBucketName, + ).bucket; } /** @@ -1169,13 +1398,20 @@ export class MetricsServiceV2Client { * @param {string} view * @returns {string} Resource name string. */ - billingAccountLocationBucketViewPath(billingAccount:string,location:string,bucket:string,view:string) { - return this.pathTemplates.billingAccountLocationBucketViewPathTemplate.render({ - billing_account: billingAccount, - location: location, - bucket: bucket, - view: view, - }); + billingAccountLocationBucketViewPath( + billingAccount: string, + location: string, + bucket: string, + view: string, + ) { + return this.pathTemplates.billingAccountLocationBucketViewPathTemplate.render( + { + billing_account: billingAccount, + location: location, + bucket: bucket, + view: view, + }, + ); } /** @@ -1185,8 +1421,12 @@ export class MetricsServiceV2Client { * A fully-qualified path representing billing_account_location_bucket_view resource. * @returns {string} A string representing the billing_account. */ - matchBillingAccountFromBillingAccountLocationBucketViewName(billingAccountLocationBucketViewName: string) { - return this.pathTemplates.billingAccountLocationBucketViewPathTemplate.match(billingAccountLocationBucketViewName).billing_account; + matchBillingAccountFromBillingAccountLocationBucketViewName( + billingAccountLocationBucketViewName: string, + ) { + return this.pathTemplates.billingAccountLocationBucketViewPathTemplate.match( + billingAccountLocationBucketViewName, + ).billing_account; } /** @@ -1196,8 +1436,12 @@ export class MetricsServiceV2Client { * A fully-qualified path representing billing_account_location_bucket_view resource. * @returns {string} A string representing the location. */ - matchLocationFromBillingAccountLocationBucketViewName(billingAccountLocationBucketViewName: string) { - return this.pathTemplates.billingAccountLocationBucketViewPathTemplate.match(billingAccountLocationBucketViewName).location; + matchLocationFromBillingAccountLocationBucketViewName( + billingAccountLocationBucketViewName: string, + ) { + return this.pathTemplates.billingAccountLocationBucketViewPathTemplate.match( + billingAccountLocationBucketViewName, + ).location; } /** @@ -1207,8 +1451,12 @@ export class MetricsServiceV2Client { * A fully-qualified path representing billing_account_location_bucket_view resource. * @returns {string} A string representing the bucket. */ - matchBucketFromBillingAccountLocationBucketViewName(billingAccountLocationBucketViewName: string) { - return this.pathTemplates.billingAccountLocationBucketViewPathTemplate.match(billingAccountLocationBucketViewName).bucket; + matchBucketFromBillingAccountLocationBucketViewName( + billingAccountLocationBucketViewName: string, + ) { + return this.pathTemplates.billingAccountLocationBucketViewPathTemplate.match( + billingAccountLocationBucketViewName, + ).bucket; } /** @@ -1218,8 +1466,12 @@ export class MetricsServiceV2Client { * A fully-qualified path representing billing_account_location_bucket_view resource. * @returns {string} A string representing the view. */ - matchViewFromBillingAccountLocationBucketViewName(billingAccountLocationBucketViewName: string) { - return this.pathTemplates.billingAccountLocationBucketViewPathTemplate.match(billingAccountLocationBucketViewName).view; + matchViewFromBillingAccountLocationBucketViewName( + billingAccountLocationBucketViewName: string, + ) { + return this.pathTemplates.billingAccountLocationBucketViewPathTemplate.match( + billingAccountLocationBucketViewName, + ).view; } /** @@ -1229,7 +1481,7 @@ export class MetricsServiceV2Client { * @param {string} log * @returns {string} Resource name string. */ - billingAccountLogPath(billingAccount:string,log:string) { + billingAccountLogPath(billingAccount: string, log: string) { return this.pathTemplates.billingAccountLogPathTemplate.render({ billing_account: billingAccount, log: log, @@ -1244,7 +1496,9 @@ export class MetricsServiceV2Client { * @returns {string} A string representing the billing_account. */ matchBillingAccountFromBillingAccountLogName(billingAccountLogName: string) { - return this.pathTemplates.billingAccountLogPathTemplate.match(billingAccountLogName).billing_account; + return this.pathTemplates.billingAccountLogPathTemplate.match( + billingAccountLogName, + ).billing_account; } /** @@ -1255,7 +1509,9 @@ export class MetricsServiceV2Client { * @returns {string} A string representing the log. */ matchLogFromBillingAccountLogName(billingAccountLogName: string) { - return this.pathTemplates.billingAccountLogPathTemplate.match(billingAccountLogName).log; + return this.pathTemplates.billingAccountLogPathTemplate.match( + billingAccountLogName, + ).log; } /** @@ -1264,7 +1520,7 @@ export class MetricsServiceV2Client { * @param {string} billing_account * @returns {string} Resource name string. */ - billingAccountSettingsPath(billingAccount:string) { + billingAccountSettingsPath(billingAccount: string) { return this.pathTemplates.billingAccountSettingsPathTemplate.render({ billing_account: billingAccount, }); @@ -1277,8 +1533,12 @@ export class MetricsServiceV2Client { * A fully-qualified path representing billing_account_settings resource. * @returns {string} A string representing the billing_account. */ - matchBillingAccountFromBillingAccountSettingsName(billingAccountSettingsName: string) { - return this.pathTemplates.billingAccountSettingsPathTemplate.match(billingAccountSettingsName).billing_account; + matchBillingAccountFromBillingAccountSettingsName( + billingAccountSettingsName: string, + ) { + return this.pathTemplates.billingAccountSettingsPathTemplate.match( + billingAccountSettingsName, + ).billing_account; } /** @@ -1288,7 +1548,7 @@ export class MetricsServiceV2Client { * @param {string} sink * @returns {string} Resource name string. */ - billingAccountSinkPath(billingAccount:string,sink:string) { + billingAccountSinkPath(billingAccount: string, sink: string) { return this.pathTemplates.billingAccountSinkPathTemplate.render({ billing_account: billingAccount, sink: sink, @@ -1302,8 +1562,12 @@ export class MetricsServiceV2Client { * A fully-qualified path representing billing_account_sink resource. * @returns {string} A string representing the billing_account. */ - matchBillingAccountFromBillingAccountSinkName(billingAccountSinkName: string) { - return this.pathTemplates.billingAccountSinkPathTemplate.match(billingAccountSinkName).billing_account; + matchBillingAccountFromBillingAccountSinkName( + billingAccountSinkName: string, + ) { + return this.pathTemplates.billingAccountSinkPathTemplate.match( + billingAccountSinkName, + ).billing_account; } /** @@ -1314,7 +1578,9 @@ export class MetricsServiceV2Client { * @returns {string} A string representing the sink. */ matchSinkFromBillingAccountSinkName(billingAccountSinkName: string) { - return this.pathTemplates.billingAccountSinkPathTemplate.match(billingAccountSinkName).sink; + return this.pathTemplates.billingAccountSinkPathTemplate.match( + billingAccountSinkName, + ).sink; } /** @@ -1323,7 +1589,7 @@ export class MetricsServiceV2Client { * @param {string} folder * @returns {string} Resource name string. */ - folderCmekSettingsPath(folder:string) { + folderCmekSettingsPath(folder: string) { return this.pathTemplates.folderCmekSettingsPathTemplate.render({ folder: folder, }); @@ -1337,7 +1603,9 @@ export class MetricsServiceV2Client { * @returns {string} A string representing the folder. */ matchFolderFromFolderCmekSettingsName(folderCmekSettingsName: string) { - return this.pathTemplates.folderCmekSettingsPathTemplate.match(folderCmekSettingsName).folder; + return this.pathTemplates.folderCmekSettingsPathTemplate.match( + folderCmekSettingsName, + ).folder; } /** @@ -1347,7 +1615,7 @@ export class MetricsServiceV2Client { * @param {string} exclusion * @returns {string} Resource name string. */ - folderExclusionPath(folder:string,exclusion:string) { + folderExclusionPath(folder: string, exclusion: string) { return this.pathTemplates.folderExclusionPathTemplate.render({ folder: folder, exclusion: exclusion, @@ -1362,7 +1630,9 @@ export class MetricsServiceV2Client { * @returns {string} A string representing the folder. */ matchFolderFromFolderExclusionName(folderExclusionName: string) { - return this.pathTemplates.folderExclusionPathTemplate.match(folderExclusionName).folder; + return this.pathTemplates.folderExclusionPathTemplate.match( + folderExclusionName, + ).folder; } /** @@ -1373,7 +1643,9 @@ export class MetricsServiceV2Client { * @returns {string} A string representing the exclusion. */ matchExclusionFromFolderExclusionName(folderExclusionName: string) { - return this.pathTemplates.folderExclusionPathTemplate.match(folderExclusionName).exclusion; + return this.pathTemplates.folderExclusionPathTemplate.match( + folderExclusionName, + ).exclusion; } /** @@ -1384,7 +1656,7 @@ export class MetricsServiceV2Client { * @param {string} bucket * @returns {string} Resource name string. */ - folderLocationBucketPath(folder:string,location:string,bucket:string) { + folderLocationBucketPath(folder: string, location: string, bucket: string) { return this.pathTemplates.folderLocationBucketPathTemplate.render({ folder: folder, location: location, @@ -1400,7 +1672,9 @@ export class MetricsServiceV2Client { * @returns {string} A string representing the folder. */ matchFolderFromFolderLocationBucketName(folderLocationBucketName: string) { - return this.pathTemplates.folderLocationBucketPathTemplate.match(folderLocationBucketName).folder; + return this.pathTemplates.folderLocationBucketPathTemplate.match( + folderLocationBucketName, + ).folder; } /** @@ -1411,7 +1685,9 @@ export class MetricsServiceV2Client { * @returns {string} A string representing the location. */ matchLocationFromFolderLocationBucketName(folderLocationBucketName: string) { - return this.pathTemplates.folderLocationBucketPathTemplate.match(folderLocationBucketName).location; + return this.pathTemplates.folderLocationBucketPathTemplate.match( + folderLocationBucketName, + ).location; } /** @@ -1422,7 +1698,9 @@ export class MetricsServiceV2Client { * @returns {string} A string representing the bucket. */ matchBucketFromFolderLocationBucketName(folderLocationBucketName: string) { - return this.pathTemplates.folderLocationBucketPathTemplate.match(folderLocationBucketName).bucket; + return this.pathTemplates.folderLocationBucketPathTemplate.match( + folderLocationBucketName, + ).bucket; } /** @@ -1434,7 +1712,12 @@ export class MetricsServiceV2Client { * @param {string} view * @returns {string} Resource name string. */ - folderLocationBucketViewPath(folder:string,location:string,bucket:string,view:string) { + folderLocationBucketViewPath( + folder: string, + location: string, + bucket: string, + view: string, + ) { return this.pathTemplates.folderLocationBucketViewPathTemplate.render({ folder: folder, location: location, @@ -1450,8 +1733,12 @@ export class MetricsServiceV2Client { * A fully-qualified path representing folder_location_bucket_view resource. * @returns {string} A string representing the folder. */ - matchFolderFromFolderLocationBucketViewName(folderLocationBucketViewName: string) { - return this.pathTemplates.folderLocationBucketViewPathTemplate.match(folderLocationBucketViewName).folder; + matchFolderFromFolderLocationBucketViewName( + folderLocationBucketViewName: string, + ) { + return this.pathTemplates.folderLocationBucketViewPathTemplate.match( + folderLocationBucketViewName, + ).folder; } /** @@ -1461,8 +1748,12 @@ export class MetricsServiceV2Client { * A fully-qualified path representing folder_location_bucket_view resource. * @returns {string} A string representing the location. */ - matchLocationFromFolderLocationBucketViewName(folderLocationBucketViewName: string) { - return this.pathTemplates.folderLocationBucketViewPathTemplate.match(folderLocationBucketViewName).location; + matchLocationFromFolderLocationBucketViewName( + folderLocationBucketViewName: string, + ) { + return this.pathTemplates.folderLocationBucketViewPathTemplate.match( + folderLocationBucketViewName, + ).location; } /** @@ -1472,8 +1763,12 @@ export class MetricsServiceV2Client { * A fully-qualified path representing folder_location_bucket_view resource. * @returns {string} A string representing the bucket. */ - matchBucketFromFolderLocationBucketViewName(folderLocationBucketViewName: string) { - return this.pathTemplates.folderLocationBucketViewPathTemplate.match(folderLocationBucketViewName).bucket; + matchBucketFromFolderLocationBucketViewName( + folderLocationBucketViewName: string, + ) { + return this.pathTemplates.folderLocationBucketViewPathTemplate.match( + folderLocationBucketViewName, + ).bucket; } /** @@ -1483,8 +1778,12 @@ export class MetricsServiceV2Client { * A fully-qualified path representing folder_location_bucket_view resource. * @returns {string} A string representing the view. */ - matchViewFromFolderLocationBucketViewName(folderLocationBucketViewName: string) { - return this.pathTemplates.folderLocationBucketViewPathTemplate.match(folderLocationBucketViewName).view; + matchViewFromFolderLocationBucketViewName( + folderLocationBucketViewName: string, + ) { + return this.pathTemplates.folderLocationBucketViewPathTemplate.match( + folderLocationBucketViewName, + ).view; } /** @@ -1494,7 +1793,7 @@ export class MetricsServiceV2Client { * @param {string} log * @returns {string} Resource name string. */ - folderLogPath(folder:string,log:string) { + folderLogPath(folder: string, log: string) { return this.pathTemplates.folderLogPathTemplate.render({ folder: folder, log: log, @@ -1529,7 +1828,7 @@ export class MetricsServiceV2Client { * @param {string} folder * @returns {string} Resource name string. */ - folderSettingsPath(folder:string) { + folderSettingsPath(folder: string) { return this.pathTemplates.folderSettingsPathTemplate.render({ folder: folder, }); @@ -1543,7 +1842,9 @@ export class MetricsServiceV2Client { * @returns {string} A string representing the folder. */ matchFolderFromFolderSettingsName(folderSettingsName: string) { - return this.pathTemplates.folderSettingsPathTemplate.match(folderSettingsName).folder; + return this.pathTemplates.folderSettingsPathTemplate.match( + folderSettingsName, + ).folder; } /** @@ -1553,7 +1854,7 @@ export class MetricsServiceV2Client { * @param {string} sink * @returns {string} Resource name string. */ - folderSinkPath(folder:string,sink:string) { + folderSinkPath(folder: string, sink: string) { return this.pathTemplates.folderSinkPathTemplate.render({ folder: folder, sink: sink, @@ -1568,7 +1869,8 @@ export class MetricsServiceV2Client { * @returns {string} A string representing the folder. */ matchFolderFromFolderSinkName(folderSinkName: string) { - return this.pathTemplates.folderSinkPathTemplate.match(folderSinkName).folder; + return this.pathTemplates.folderSinkPathTemplate.match(folderSinkName) + .folder; } /** @@ -1589,7 +1891,7 @@ export class MetricsServiceV2Client { * @param {string} metric * @returns {string} Resource name string. */ - logMetricPath(project:string,metric:string) { + logMetricPath(project: string, metric: string) { return this.pathTemplates.logMetricPathTemplate.render({ project: project, metric: metric, @@ -1604,7 +1906,8 @@ export class MetricsServiceV2Client { * @returns {string} A string representing the project. */ matchProjectFromLogMetricName(logMetricName: string) { - return this.pathTemplates.logMetricPathTemplate.match(logMetricName).project; + return this.pathTemplates.logMetricPathTemplate.match(logMetricName) + .project; } /** @@ -1624,7 +1927,7 @@ export class MetricsServiceV2Client { * @param {string} organization * @returns {string} Resource name string. */ - organizationCmekSettingsPath(organization:string) { + organizationCmekSettingsPath(organization: string) { return this.pathTemplates.organizationCmekSettingsPathTemplate.render({ organization: organization, }); @@ -1637,8 +1940,12 @@ export class MetricsServiceV2Client { * A fully-qualified path representing organization_cmekSettings resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationCmekSettingsName(organizationCmekSettingsName: string) { - return this.pathTemplates.organizationCmekSettingsPathTemplate.match(organizationCmekSettingsName).organization; + matchOrganizationFromOrganizationCmekSettingsName( + organizationCmekSettingsName: string, + ) { + return this.pathTemplates.organizationCmekSettingsPathTemplate.match( + organizationCmekSettingsName, + ).organization; } /** @@ -1648,7 +1955,7 @@ export class MetricsServiceV2Client { * @param {string} exclusion * @returns {string} Resource name string. */ - organizationExclusionPath(organization:string,exclusion:string) { + organizationExclusionPath(organization: string, exclusion: string) { return this.pathTemplates.organizationExclusionPathTemplate.render({ organization: organization, exclusion: exclusion, @@ -1662,8 +1969,12 @@ export class MetricsServiceV2Client { * A fully-qualified path representing organization_exclusion resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationExclusionName(organizationExclusionName: string) { - return this.pathTemplates.organizationExclusionPathTemplate.match(organizationExclusionName).organization; + matchOrganizationFromOrganizationExclusionName( + organizationExclusionName: string, + ) { + return this.pathTemplates.organizationExclusionPathTemplate.match( + organizationExclusionName, + ).organization; } /** @@ -1673,8 +1984,12 @@ export class MetricsServiceV2Client { * A fully-qualified path representing organization_exclusion resource. * @returns {string} A string representing the exclusion. */ - matchExclusionFromOrganizationExclusionName(organizationExclusionName: string) { - return this.pathTemplates.organizationExclusionPathTemplate.match(organizationExclusionName).exclusion; + matchExclusionFromOrganizationExclusionName( + organizationExclusionName: string, + ) { + return this.pathTemplates.organizationExclusionPathTemplate.match( + organizationExclusionName, + ).exclusion; } /** @@ -1685,7 +2000,11 @@ export class MetricsServiceV2Client { * @param {string} bucket * @returns {string} Resource name string. */ - organizationLocationBucketPath(organization:string,location:string,bucket:string) { + organizationLocationBucketPath( + organization: string, + location: string, + bucket: string, + ) { return this.pathTemplates.organizationLocationBucketPathTemplate.render({ organization: organization, location: location, @@ -1700,8 +2019,12 @@ export class MetricsServiceV2Client { * A fully-qualified path representing organization_location_bucket resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationLocationBucketName(organizationLocationBucketName: string) { - return this.pathTemplates.organizationLocationBucketPathTemplate.match(organizationLocationBucketName).organization; + matchOrganizationFromOrganizationLocationBucketName( + organizationLocationBucketName: string, + ) { + return this.pathTemplates.organizationLocationBucketPathTemplate.match( + organizationLocationBucketName, + ).organization; } /** @@ -1711,8 +2034,12 @@ export class MetricsServiceV2Client { * A fully-qualified path representing organization_location_bucket resource. * @returns {string} A string representing the location. */ - matchLocationFromOrganizationLocationBucketName(organizationLocationBucketName: string) { - return this.pathTemplates.organizationLocationBucketPathTemplate.match(organizationLocationBucketName).location; + matchLocationFromOrganizationLocationBucketName( + organizationLocationBucketName: string, + ) { + return this.pathTemplates.organizationLocationBucketPathTemplate.match( + organizationLocationBucketName, + ).location; } /** @@ -1722,8 +2049,12 @@ export class MetricsServiceV2Client { * A fully-qualified path representing organization_location_bucket resource. * @returns {string} A string representing the bucket. */ - matchBucketFromOrganizationLocationBucketName(organizationLocationBucketName: string) { - return this.pathTemplates.organizationLocationBucketPathTemplate.match(organizationLocationBucketName).bucket; + matchBucketFromOrganizationLocationBucketName( + organizationLocationBucketName: string, + ) { + return this.pathTemplates.organizationLocationBucketPathTemplate.match( + organizationLocationBucketName, + ).bucket; } /** @@ -1735,13 +2066,20 @@ export class MetricsServiceV2Client { * @param {string} view * @returns {string} Resource name string. */ - organizationLocationBucketViewPath(organization:string,location:string,bucket:string,view:string) { - return this.pathTemplates.organizationLocationBucketViewPathTemplate.render({ - organization: organization, - location: location, - bucket: bucket, - view: view, - }); + organizationLocationBucketViewPath( + organization: string, + location: string, + bucket: string, + view: string, + ) { + return this.pathTemplates.organizationLocationBucketViewPathTemplate.render( + { + organization: organization, + location: location, + bucket: bucket, + view: view, + }, + ); } /** @@ -1751,8 +2089,12 @@ export class MetricsServiceV2Client { * A fully-qualified path representing organization_location_bucket_view resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationLocationBucketViewName(organizationLocationBucketViewName: string) { - return this.pathTemplates.organizationLocationBucketViewPathTemplate.match(organizationLocationBucketViewName).organization; + matchOrganizationFromOrganizationLocationBucketViewName( + organizationLocationBucketViewName: string, + ) { + return this.pathTemplates.organizationLocationBucketViewPathTemplate.match( + organizationLocationBucketViewName, + ).organization; } /** @@ -1762,8 +2104,12 @@ export class MetricsServiceV2Client { * A fully-qualified path representing organization_location_bucket_view resource. * @returns {string} A string representing the location. */ - matchLocationFromOrganizationLocationBucketViewName(organizationLocationBucketViewName: string) { - return this.pathTemplates.organizationLocationBucketViewPathTemplate.match(organizationLocationBucketViewName).location; + matchLocationFromOrganizationLocationBucketViewName( + organizationLocationBucketViewName: string, + ) { + return this.pathTemplates.organizationLocationBucketViewPathTemplate.match( + organizationLocationBucketViewName, + ).location; } /** @@ -1773,8 +2119,12 @@ export class MetricsServiceV2Client { * A fully-qualified path representing organization_location_bucket_view resource. * @returns {string} A string representing the bucket. */ - matchBucketFromOrganizationLocationBucketViewName(organizationLocationBucketViewName: string) { - return this.pathTemplates.organizationLocationBucketViewPathTemplate.match(organizationLocationBucketViewName).bucket; + matchBucketFromOrganizationLocationBucketViewName( + organizationLocationBucketViewName: string, + ) { + return this.pathTemplates.organizationLocationBucketViewPathTemplate.match( + organizationLocationBucketViewName, + ).bucket; } /** @@ -1784,8 +2134,12 @@ export class MetricsServiceV2Client { * A fully-qualified path representing organization_location_bucket_view resource. * @returns {string} A string representing the view. */ - matchViewFromOrganizationLocationBucketViewName(organizationLocationBucketViewName: string) { - return this.pathTemplates.organizationLocationBucketViewPathTemplate.match(organizationLocationBucketViewName).view; + matchViewFromOrganizationLocationBucketViewName( + organizationLocationBucketViewName: string, + ) { + return this.pathTemplates.organizationLocationBucketViewPathTemplate.match( + organizationLocationBucketViewName, + ).view; } /** @@ -1795,7 +2149,7 @@ export class MetricsServiceV2Client { * @param {string} log * @returns {string} Resource name string. */ - organizationLogPath(organization:string,log:string) { + organizationLogPath(organization: string, log: string) { return this.pathTemplates.organizationLogPathTemplate.render({ organization: organization, log: log, @@ -1810,7 +2164,9 @@ export class MetricsServiceV2Client { * @returns {string} A string representing the organization. */ matchOrganizationFromOrganizationLogName(organizationLogName: string) { - return this.pathTemplates.organizationLogPathTemplate.match(organizationLogName).organization; + return this.pathTemplates.organizationLogPathTemplate.match( + organizationLogName, + ).organization; } /** @@ -1821,7 +2177,9 @@ export class MetricsServiceV2Client { * @returns {string} A string representing the log. */ matchLogFromOrganizationLogName(organizationLogName: string) { - return this.pathTemplates.organizationLogPathTemplate.match(organizationLogName).log; + return this.pathTemplates.organizationLogPathTemplate.match( + organizationLogName, + ).log; } /** @@ -1830,7 +2188,7 @@ export class MetricsServiceV2Client { * @param {string} organization * @returns {string} Resource name string. */ - organizationSettingsPath(organization:string) { + organizationSettingsPath(organization: string) { return this.pathTemplates.organizationSettingsPathTemplate.render({ organization: organization, }); @@ -1843,8 +2201,12 @@ export class MetricsServiceV2Client { * A fully-qualified path representing organization_settings resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationSettingsName(organizationSettingsName: string) { - return this.pathTemplates.organizationSettingsPathTemplate.match(organizationSettingsName).organization; + matchOrganizationFromOrganizationSettingsName( + organizationSettingsName: string, + ) { + return this.pathTemplates.organizationSettingsPathTemplate.match( + organizationSettingsName, + ).organization; } /** @@ -1854,7 +2216,7 @@ export class MetricsServiceV2Client { * @param {string} sink * @returns {string} Resource name string. */ - organizationSinkPath(organization:string,sink:string) { + organizationSinkPath(organization: string, sink: string) { return this.pathTemplates.organizationSinkPathTemplate.render({ organization: organization, sink: sink, @@ -1869,7 +2231,9 @@ export class MetricsServiceV2Client { * @returns {string} A string representing the organization. */ matchOrganizationFromOrganizationSinkName(organizationSinkName: string) { - return this.pathTemplates.organizationSinkPathTemplate.match(organizationSinkName).organization; + return this.pathTemplates.organizationSinkPathTemplate.match( + organizationSinkName, + ).organization; } /** @@ -1880,7 +2244,9 @@ export class MetricsServiceV2Client { * @returns {string} A string representing the sink. */ matchSinkFromOrganizationSinkName(organizationSinkName: string) { - return this.pathTemplates.organizationSinkPathTemplate.match(organizationSinkName).sink; + return this.pathTemplates.organizationSinkPathTemplate.match( + organizationSinkName, + ).sink; } /** @@ -1889,7 +2255,7 @@ export class MetricsServiceV2Client { * @param {string} project * @returns {string} Resource name string. */ - projectPath(project:string) { + projectPath(project: string) { return this.pathTemplates.projectPathTemplate.render({ project: project, }); @@ -1912,7 +2278,7 @@ export class MetricsServiceV2Client { * @param {string} project * @returns {string} Resource name string. */ - projectCmekSettingsPath(project:string) { + projectCmekSettingsPath(project: string) { return this.pathTemplates.projectCmekSettingsPathTemplate.render({ project: project, }); @@ -1926,7 +2292,9 @@ export class MetricsServiceV2Client { * @returns {string} A string representing the project. */ matchProjectFromProjectCmekSettingsName(projectCmekSettingsName: string) { - return this.pathTemplates.projectCmekSettingsPathTemplate.match(projectCmekSettingsName).project; + return this.pathTemplates.projectCmekSettingsPathTemplate.match( + projectCmekSettingsName, + ).project; } /** @@ -1936,7 +2304,7 @@ export class MetricsServiceV2Client { * @param {string} exclusion * @returns {string} Resource name string. */ - projectExclusionPath(project:string,exclusion:string) { + projectExclusionPath(project: string, exclusion: string) { return this.pathTemplates.projectExclusionPathTemplate.render({ project: project, exclusion: exclusion, @@ -1951,7 +2319,9 @@ export class MetricsServiceV2Client { * @returns {string} A string representing the project. */ matchProjectFromProjectExclusionName(projectExclusionName: string) { - return this.pathTemplates.projectExclusionPathTemplate.match(projectExclusionName).project; + return this.pathTemplates.projectExclusionPathTemplate.match( + projectExclusionName, + ).project; } /** @@ -1962,7 +2332,9 @@ export class MetricsServiceV2Client { * @returns {string} A string representing the exclusion. */ matchExclusionFromProjectExclusionName(projectExclusionName: string) { - return this.pathTemplates.projectExclusionPathTemplate.match(projectExclusionName).exclusion; + return this.pathTemplates.projectExclusionPathTemplate.match( + projectExclusionName, + ).exclusion; } /** @@ -1973,7 +2345,7 @@ export class MetricsServiceV2Client { * @param {string} bucket * @returns {string} Resource name string. */ - projectLocationBucketPath(project:string,location:string,bucket:string) { + projectLocationBucketPath(project: string, location: string, bucket: string) { return this.pathTemplates.projectLocationBucketPathTemplate.render({ project: project, location: location, @@ -1989,7 +2361,9 @@ export class MetricsServiceV2Client { * @returns {string} A string representing the project. */ matchProjectFromProjectLocationBucketName(projectLocationBucketName: string) { - return this.pathTemplates.projectLocationBucketPathTemplate.match(projectLocationBucketName).project; + return this.pathTemplates.projectLocationBucketPathTemplate.match( + projectLocationBucketName, + ).project; } /** @@ -1999,8 +2373,12 @@ export class MetricsServiceV2Client { * A fully-qualified path representing project_location_bucket resource. * @returns {string} A string representing the location. */ - matchLocationFromProjectLocationBucketName(projectLocationBucketName: string) { - return this.pathTemplates.projectLocationBucketPathTemplate.match(projectLocationBucketName).location; + matchLocationFromProjectLocationBucketName( + projectLocationBucketName: string, + ) { + return this.pathTemplates.projectLocationBucketPathTemplate.match( + projectLocationBucketName, + ).location; } /** @@ -2011,7 +2389,9 @@ export class MetricsServiceV2Client { * @returns {string} A string representing the bucket. */ matchBucketFromProjectLocationBucketName(projectLocationBucketName: string) { - return this.pathTemplates.projectLocationBucketPathTemplate.match(projectLocationBucketName).bucket; + return this.pathTemplates.projectLocationBucketPathTemplate.match( + projectLocationBucketName, + ).bucket; } /** @@ -2023,7 +2403,12 @@ export class MetricsServiceV2Client { * @param {string} view * @returns {string} Resource name string. */ - projectLocationBucketViewPath(project:string,location:string,bucket:string,view:string) { + projectLocationBucketViewPath( + project: string, + location: string, + bucket: string, + view: string, + ) { return this.pathTemplates.projectLocationBucketViewPathTemplate.render({ project: project, location: location, @@ -2039,8 +2424,12 @@ export class MetricsServiceV2Client { * A fully-qualified path representing project_location_bucket_view resource. * @returns {string} A string representing the project. */ - matchProjectFromProjectLocationBucketViewName(projectLocationBucketViewName: string) { - return this.pathTemplates.projectLocationBucketViewPathTemplate.match(projectLocationBucketViewName).project; + matchProjectFromProjectLocationBucketViewName( + projectLocationBucketViewName: string, + ) { + return this.pathTemplates.projectLocationBucketViewPathTemplate.match( + projectLocationBucketViewName, + ).project; } /** @@ -2050,8 +2439,12 @@ export class MetricsServiceV2Client { * A fully-qualified path representing project_location_bucket_view resource. * @returns {string} A string representing the location. */ - matchLocationFromProjectLocationBucketViewName(projectLocationBucketViewName: string) { - return this.pathTemplates.projectLocationBucketViewPathTemplate.match(projectLocationBucketViewName).location; + matchLocationFromProjectLocationBucketViewName( + projectLocationBucketViewName: string, + ) { + return this.pathTemplates.projectLocationBucketViewPathTemplate.match( + projectLocationBucketViewName, + ).location; } /** @@ -2061,8 +2454,12 @@ export class MetricsServiceV2Client { * A fully-qualified path representing project_location_bucket_view resource. * @returns {string} A string representing the bucket. */ - matchBucketFromProjectLocationBucketViewName(projectLocationBucketViewName: string) { - return this.pathTemplates.projectLocationBucketViewPathTemplate.match(projectLocationBucketViewName).bucket; + matchBucketFromProjectLocationBucketViewName( + projectLocationBucketViewName: string, + ) { + return this.pathTemplates.projectLocationBucketViewPathTemplate.match( + projectLocationBucketViewName, + ).bucket; } /** @@ -2072,8 +2469,12 @@ export class MetricsServiceV2Client { * A fully-qualified path representing project_location_bucket_view resource. * @returns {string} A string representing the view. */ - matchViewFromProjectLocationBucketViewName(projectLocationBucketViewName: string) { - return this.pathTemplates.projectLocationBucketViewPathTemplate.match(projectLocationBucketViewName).view; + matchViewFromProjectLocationBucketViewName( + projectLocationBucketViewName: string, + ) { + return this.pathTemplates.projectLocationBucketViewPathTemplate.match( + projectLocationBucketViewName, + ).view; } /** @@ -2083,7 +2484,7 @@ export class MetricsServiceV2Client { * @param {string} log * @returns {string} Resource name string. */ - projectLogPath(project:string,log:string) { + projectLogPath(project: string, log: string) { return this.pathTemplates.projectLogPathTemplate.render({ project: project, log: log, @@ -2098,7 +2499,8 @@ export class MetricsServiceV2Client { * @returns {string} A string representing the project. */ matchProjectFromProjectLogName(projectLogName: string) { - return this.pathTemplates.projectLogPathTemplate.match(projectLogName).project; + return this.pathTemplates.projectLogPathTemplate.match(projectLogName) + .project; } /** @@ -2118,7 +2520,7 @@ export class MetricsServiceV2Client { * @param {string} project * @returns {string} Resource name string. */ - projectSettingsPath(project:string) { + projectSettingsPath(project: string) { return this.pathTemplates.projectSettingsPathTemplate.render({ project: project, }); @@ -2132,7 +2534,9 @@ export class MetricsServiceV2Client { * @returns {string} A string representing the project. */ matchProjectFromProjectSettingsName(projectSettingsName: string) { - return this.pathTemplates.projectSettingsPathTemplate.match(projectSettingsName).project; + return this.pathTemplates.projectSettingsPathTemplate.match( + projectSettingsName, + ).project; } /** @@ -2142,7 +2546,7 @@ export class MetricsServiceV2Client { * @param {string} sink * @returns {string} Resource name string. */ - projectSinkPath(project:string,sink:string) { + projectSinkPath(project: string, sink: string) { return this.pathTemplates.projectSinkPathTemplate.render({ project: project, sink: sink, @@ -2157,7 +2561,8 @@ export class MetricsServiceV2Client { * @returns {string} A string representing the project. */ matchProjectFromProjectSinkName(projectSinkName: string) { - return this.pathTemplates.projectSinkPathTemplate.match(projectSinkName).project; + return this.pathTemplates.projectSinkPathTemplate.match(projectSinkName) + .project; } /** @@ -2168,7 +2573,8 @@ export class MetricsServiceV2Client { * @returns {string} A string representing the sink. */ matchSinkFromProjectSinkName(projectSinkName: string) { - return this.pathTemplates.projectSinkPathTemplate.match(projectSinkName).sink; + return this.pathTemplates.projectSinkPathTemplate.match(projectSinkName) + .sink; } /** @@ -2179,7 +2585,7 @@ export class MetricsServiceV2Client { */ close(): Promise { if (this.metricsServiceV2Stub && !this._terminated) { - return this.metricsServiceV2Stub.then(stub => { + return this.metricsServiceV2Stub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -2187,4 +2593,4 @@ export class MetricsServiceV2Client { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/core/generator/gapic-generator-typescript/baselines/logging-esm/esm/system-test/fixtures/sample/src/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/logging-esm/esm/system-test/fixtures/sample/src/index.ts.baseline index 51f52bae60f7..b75198b72d14 100644 --- a/core/generator/gapic-generator-typescript/baselines/logging-esm/esm/system-test/fixtures/sample/src/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/logging-esm/esm/system-test/fixtures/sample/src/index.ts.baseline @@ -17,7 +17,11 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -import {ConfigServiceV2Client, LoggingServiceV2Client, MetricsServiceV2Client} from 'logging'; +import { + ConfigServiceV2Client, + LoggingServiceV2Client, + MetricsServiceV2Client, +} from 'logging'; // check that the client class type name can be used function doStuffWithConfigServiceV2Client(client: ConfigServiceV2Client) { diff --git a/core/generator/gapic-generator-typescript/baselines/logging-esm/esm/system-test/install.ts.baseline b/core/generator/gapic-generator-typescript/baselines/logging-esm/esm/system-test/install.ts.baseline index e079c4fa1101..d109fdd8c97f 100644 --- a/core/generator/gapic-generator-typescript/baselines/logging-esm/esm/system-test/install.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/logging-esm/esm/system-test/install.ts.baseline @@ -16,40 +16,45 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -import {packNTest} from 'pack-n-play'; -import {readFileSync} from 'fs'; -import {describe, it} from 'mocha'; +import { packNTest } from 'pack-n-play'; +import { readFileSync } from 'fs'; +import { describe, it } from 'mocha'; describe('📦 pack-n-play test', () => { - it('TypeScript', async function() { + it('TypeScript', async function () { this.timeout(300000); await packNTest({ packageDir: process.cwd(), sample: { description: 'TypeScript user can use the type definitions', - ts: readFileSync('./esm/system-test/fixtures/sample/src/index.ts').toString() - } + ts: readFileSync( + './esm/system-test/fixtures/sample/src/index.ts', + ).toString(), + }, }); }); - it('ESM module', async function() { + it('ESM module', async function () { this.timeout(300000); await packNTest({ sample: { description: 'Should be able to import using ESM', - esm: readFileSync('./esm/system-test/fixtures/sample/src/index.js').toString(), + esm: readFileSync( + './esm/system-test/fixtures/sample/src/index.js', + ).toString(), }, }); }); - it('CJS module', async function() { + it('CJS module', async function () { this.timeout(300000); await packNTest({ sample: { description: 'Should be able to import using CJS', - cjs: readFileSync('./esm/system-test/fixtures/sample/src/index.cjs').toString(), + cjs: readFileSync( + './esm/system-test/fixtures/sample/src/index.cjs', + ).toString(), }, }); }); - }); diff --git a/core/generator/gapic-generator-typescript/baselines/logging-esm/esm/test/gapic_config_service_v2_v2.ts.baseline b/core/generator/gapic-generator-typescript/baselines/logging-esm/esm/test/gapic_config_service_v2_v2.ts.baseline index b8ce1e24b5ea..a454c48f6b46 100644 --- a/core/generator/gapic-generator-typescript/baselines/logging-esm/esm/test/gapic_config_service_v2_v2.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/logging-esm/esm/test/gapic_config_service_v2_v2.ts.baseline @@ -20,16 +20,16 @@ import * as protos from '../../protos/protos.js'; import assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as configservicev2Module from '../src/index.js'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; -import {protobuf, LROperation, operationsProtos} from 'google-gax'; +import { protobuf, LROperation, operationsProtos } from 'google-gax'; import fs from 'fs'; import path from 'path'; -import {fileURLToPath} from 'url'; +import { fileURLToPath } from 'url'; // @ts-ignore const dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -37,4817 +37,6316 @@ const dirname = path.dirname(fileURLToPath(import.meta.url)); // to fill in default values for request objects const root = protobuf.Root.fromJSON( JSON.parse( - fs.readFileSync(path.join(dirname, '..', '..', 'protos/protos.json'), 'utf8') - )) + fs.readFileSync( + path.join(dirname, '..', '..', 'protos/protos.json'), + 'utf8', + ), + ), +); // eslint-disable-next-line @typescript-eslint/no-unused-vars function getTypeDefaultValue(typeName: string, fields: string[]) { - let type = root.lookupType(typeName) as protobuf.Type; - for (const field of fields.slice(0, -1)) { - type = type?.fields[field]?.resolvedType as protobuf.Type; - } - return type?.fields[fields[fields.length - 1]]?.defaultValue ?? null; + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type?.fields[field]?.resolvedType as protobuf.Type; + } + return type?.fields[fields[fields.length - 1]]?.defaultValue ?? null; } function generateSampleMessage(instance: T) { - const filledObject = (instance.constructor as typeof protobuf.Message) - .toObject(instance as protobuf.Message, {defaults: true}); - return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, { defaults: true }); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; } function stubSimpleCall(response?: ResponseType, error?: Error) { - return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); } -function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { - return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +function stubSimpleCallWithCallback( + response?: ResponseType, + error?: Error, +) { + return error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); } -function stubLongRunningCall(response?: ResponseType, callError?: Error, lroError?: Error) { - const innerStub = lroError ? sinon.stub().rejects(lroError) : sinon.stub().resolves([response]); - const mockOperation = { - promise: innerStub, - }; - return callError ? sinon.stub().rejects(callError) : sinon.stub().resolves([mockOperation]); +function stubLongRunningCall( + response?: ResponseType, + callError?: Error, + lroError?: Error, +) { + const innerStub = lroError + ? sinon.stub().rejects(lroError) + : sinon.stub().resolves([response]); + const mockOperation = { + promise: innerStub, + }; + return callError + ? sinon.stub().rejects(callError) + : sinon.stub().resolves([mockOperation]); } -function stubLongRunningCallWithCallback(response?: ResponseType, callError?: Error, lroError?: Error) { - const innerStub = lroError ? sinon.stub().rejects(lroError) : sinon.stub().resolves([response]); - const mockOperation = { - promise: innerStub, - }; - return callError ? sinon.stub().callsArgWith(2, callError) : sinon.stub().callsArgWith(2, null, mockOperation); +function stubLongRunningCallWithCallback( + response?: ResponseType, + callError?: Error, + lroError?: Error, +) { + const innerStub = lroError + ? sinon.stub().rejects(lroError) + : sinon.stub().resolves([response]); + const mockOperation = { + promise: innerStub, + }; + return callError + ? sinon.stub().callsArgWith(2, callError) + : sinon.stub().callsArgWith(2, null, mockOperation); } -function stubPageStreamingCall(responses?: ResponseType[], error?: Error) { - const pagingStub = sinon.stub(); - if (responses) { - for (let i = 0; i < responses.length; ++i) { - pagingStub.onCall(i).callsArgWith(2, null, responses[i]); - } +function stubPageStreamingCall( + responses?: ResponseType[], + error?: Error, +) { + const pagingStub = sinon.stub(); + if (responses) { + for (let i = 0; i < responses.length; ++i) { + pagingStub.onCall(i).callsArgWith(2, null, responses[i]); } - const transformStub = error ? sinon.stub().callsArgWith(2, error) : pagingStub; - const mockStream = new PassThrough({ - objectMode: true, - transform: transformStub, - }); - // trigger as many responses as needed - if (responses) { - for (let i = 0; i < responses.length; ++i) { - setImmediate(() => { mockStream.write({}); }); - } - setImmediate(() => { mockStream.end(); }); - } else { - setImmediate(() => { mockStream.write({}); }); - setImmediate(() => { mockStream.end(); }); + } + const transformStub = error + ? sinon.stub().callsArgWith(2, error) + : pagingStub; + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + // trigger as many responses as needed + if (responses) { + for (let i = 0; i < responses.length; ++i) { + setImmediate(() => { + mockStream.write({}); + }); } - return sinon.stub().returns(mockStream); + setImmediate(() => { + mockStream.end(); + }); + } else { + setImmediate(() => { + mockStream.write({}); + }); + setImmediate(() => { + mockStream.end(); + }); + } + return sinon.stub().returns(mockStream); } -function stubAsyncIterationCall(responses?: ResponseType[], error?: Error) { - let counter = 0; - const asyncIterable = { - [Symbol.asyncIterator]() { - return { - async next() { - if (error) { - return Promise.reject(error); - } - if (counter >= responses!.length) { - return Promise.resolve({done: true, value: undefined}); - } - return Promise.resolve({done: false, value: responses![counter++]}); - } - }; - } - }; - return sinon.stub().returns(asyncIterable); +function stubAsyncIterationCall( + responses?: ResponseType[], + error?: Error, +) { + let counter = 0; + const asyncIterable = { + [Symbol.asyncIterator]() { + return { + async next() { + if (error) { + return Promise.reject(error); + } + if (counter >= responses!.length) { + return Promise.resolve({ done: true, value: undefined }); + } + return Promise.resolve({ done: false, value: responses![counter++] }); + }, + }; + }, + }; + return sinon.stub().returns(asyncIterable); } describe('v2.ConfigServiceV2Client', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'logging.googleapis.com'); - }); - - it('has universeDomain', () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); - - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - it('throws DeprecationWarning if static servicePath is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const servicePath = configservicev2Module.v2.ConfigServiceV2Client.servicePath; - assert.strictEqual(servicePath, 'logging.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = configservicev2Module.v2.ConfigServiceV2Client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'logging.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'logging.example.com'); - }); - - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'logging.example.com'); - }); - - if (typeof process === 'object' && 'env' in process) { - describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { - it('sets apiEndpoint from environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new configservicev2Module.v2.ConfigServiceV2Client(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'logging.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - - it('value configured in code has priority over environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new configservicev2Module.v2.ConfigServiceV2Client({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'logging.configured.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { new configservicev2Module.v2.ConfigServiceV2Client({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); - - it('has port', () => { - const port = configservicev2Module.v2.ConfigServiceV2Client.port; - assert(port); - assert(typeof port === 'number'); - }); - - it('should create a client with no option', () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client(); - assert(client); - }); - - it('should create a client with gRPC fallback', () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - fallback: true, - }); - assert(client); - }); - - it('has initialize method and supports deferred initialization', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.configServiceV2Stub, undefined); - await client.initialize(); - assert(client.configServiceV2Stub); - }); - - it('has close method for the initialized client', done => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.configServiceV2Stub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); - - it('has close method for the non-initialized client', done => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.configServiceV2Stub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); - - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); - }); - - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId((err?: Error|null, projectId?: string|null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } - }); - }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'logging.googleapis.com'); }); - describe('getBucket', () => { - it('invokes getBucket without error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.GetBucketRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.GetBucketRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.logging.v2.LogBucket() - ); - client.innerApiCalls.getBucket = stubSimpleCall(expectedResponse); - const [response] = await client.getBucket(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getBucket as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getBucket as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getBucket without error using callback', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.GetBucketRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.GetBucketRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.logging.v2.LogBucket() - ); - client.innerApiCalls.getBucket = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getBucket( - request, - (err?: Error|null, result?: protos.google.logging.v2.ILogBucket|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getBucket as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getBucket as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getBucket with error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.GetBucketRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.GetBucketRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getBucket = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getBucket(request), expectedError); - const actualRequest = (client.innerApiCalls.getBucket as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getBucket as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getBucket with closed client', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.GetBucketRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.GetBucketRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getBucket(request), expectedError); - }); + it('has universeDomain', () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); }); - describe('createBucket', () => { - it('invokes createBucket without error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.CreateBucketRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.CreateBucketRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.logging.v2.LogBucket() - ); - client.innerApiCalls.createBucket = stubSimpleCall(expectedResponse); - const [response] = await client.createBucket(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createBucket as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createBucket as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createBucket without error using callback', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.CreateBucketRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.CreateBucketRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.logging.v2.LogBucket() - ); - client.innerApiCalls.createBucket = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createBucket( - request, - (err?: Error|null, result?: protos.google.logging.v2.ILogBucket|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createBucket as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createBucket as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createBucket with error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.CreateBucketRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.CreateBucketRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createBucket = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createBucket(request), expectedError); - const actualRequest = (client.innerApiCalls.createBucket as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createBucket as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createBucket with closed client', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.CreateBucketRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.CreateBucketRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createBucket(request), expectedError); - }); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = + configservicev2Module.v2.ConfigServiceV2Client.servicePath; + assert.strictEqual(servicePath, 'logging.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + configservicev2Module.v2.ConfigServiceV2Client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'logging.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + universeDomain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'logging.example.com'); }); - describe('updateBucket', () => { - it('invokes updateBucket without error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.UpdateBucketRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.UpdateBucketRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.logging.v2.LogBucket() - ); - client.innerApiCalls.updateBucket = stubSimpleCall(expectedResponse); - const [response] = await client.updateBucket(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateBucket as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateBucket as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateBucket without error using callback', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.UpdateBucketRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.UpdateBucketRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.logging.v2.LogBucket() - ); - client.innerApiCalls.updateBucket = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateBucket( - request, - (err?: Error|null, result?: protos.google.logging.v2.ILogBucket|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateBucket as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateBucket as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateBucket with error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.UpdateBucketRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.UpdateBucketRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateBucket = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateBucket(request), expectedError); - const actualRequest = (client.innerApiCalls.updateBucket as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateBucket as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateBucket with closed client', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.UpdateBucketRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.UpdateBucketRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateBucket(request), expectedError); - }); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + universe_domain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'logging.example.com'); }); - describe('deleteBucket', () => { - it('invokes deleteBucket without error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.DeleteBucketRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.DeleteBucketRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteBucket = stubSimpleCall(expectedResponse); - const [response] = await client.deleteBucket(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteBucket as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteBucket as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + if (typeof process === 'object' && 'env' in process) { + describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { + it('sets apiEndpoint from environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new configservicev2Module.v2.ConfigServiceV2Client(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'logging.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } + }); + + it('value configured in code has priority over environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + universeDomain: 'configured.example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'logging.configured.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } + }); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new configservicev2Module.v2.ConfigServiceV2Client({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); + }); - it('invokes deleteBucket without error using callback', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.DeleteBucketRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.DeleteBucketRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteBucket = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteBucket( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteBucket as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteBucket as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has port', () => { + const port = configservicev2Module.v2.ConfigServiceV2Client.port; + assert(port); + assert(typeof port === 'number'); + }); - it('invokes deleteBucket with error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.DeleteBucketRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.DeleteBucketRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteBucket = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteBucket(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteBucket as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteBucket as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('should create a client with no option', () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client(); + assert(client); + }); - it('invokes deleteBucket with closed client', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.DeleteBucketRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.DeleteBucketRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteBucket(request), expectedError); - }); + it('should create a client with gRPC fallback', () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + fallback: true, + }); + assert(client); }); - describe('undeleteBucket', () => { - it('invokes undeleteBucket without error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.UndeleteBucketRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.UndeleteBucketRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.undeleteBucket = stubSimpleCall(expectedResponse); - const [response] = await client.undeleteBucket(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.undeleteBucket as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.undeleteBucket as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has initialize method and supports deferred initialization', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.configServiceV2Stub, undefined); + await client.initialize(); + assert(client.configServiceV2Stub); + }); - it('invokes undeleteBucket without error using callback', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.UndeleteBucketRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.UndeleteBucketRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.undeleteBucket = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.undeleteBucket( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.undeleteBucket as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.undeleteBucket as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('has close method for the initialized client', (done) => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.configServiceV2Stub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes undeleteBucket with error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.UndeleteBucketRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.UndeleteBucketRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.undeleteBucket = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.undeleteBucket(request), expectedError); - const actualRequest = (client.innerApiCalls.undeleteBucket as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.undeleteBucket as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('has close method for the non-initialized client', (done) => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.configServiceV2Stub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes undeleteBucket with closed client', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.UndeleteBucketRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.UndeleteBucketRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.undeleteBucket(request), expectedError); - }); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); }); - describe('getView', () => { - it('invokes getView without error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.GetViewRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.GetViewRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.logging.v2.LogView() - ); - client.innerApiCalls.getView = stubSimpleCall(expectedResponse); - const [response] = await client.getView(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getView as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getView as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } + }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + }); + + describe('getBucket', () => { + it('invokes getBucket without error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.GetBucketRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.GetBucketRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.logging.v2.LogBucket(), + ); + client.innerApiCalls.getBucket = stubSimpleCall(expectedResponse); + const [response] = await client.getBucket(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getBucket as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getBucket as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getView without error using callback', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.GetViewRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.GetViewRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.logging.v2.LogView() - ); - client.innerApiCalls.getView = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getView( - request, - (err?: Error|null, result?: protos.google.logging.v2.ILogView|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getView as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getView as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getBucket without error using callback', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.GetBucketRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.GetBucketRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.logging.v2.LogBucket(), + ); + client.innerApiCalls.getBucket = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getBucket( + request, + ( + err?: Error | null, + result?: protos.google.logging.v2.ILogBucket | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getBucket as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getBucket as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getView with error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.GetViewRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.GetViewRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getView = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getView(request), expectedError); - const actualRequest = (client.innerApiCalls.getView as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getView as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getBucket with error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.GetBucketRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.GetBucketRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getBucket = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.getBucket(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getBucket as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getBucket as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getView with closed client', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.GetViewRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.GetViewRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getView(request), expectedError); - }); + it('invokes getBucket with closed client', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.GetBucketRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.GetBucketRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getBucket(request), expectedError); + }); + }); + + describe('createBucket', () => { + it('invokes createBucket without error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.CreateBucketRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.CreateBucketRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.logging.v2.LogBucket(), + ); + client.innerApiCalls.createBucket = stubSimpleCall(expectedResponse); + const [response] = await client.createBucket(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createBucket as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createBucket as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('createView', () => { - it('invokes createView without error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.CreateViewRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.CreateViewRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.logging.v2.LogView() - ); - client.innerApiCalls.createView = stubSimpleCall(expectedResponse); - const [response] = await client.createView(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createView as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createView as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createBucket without error using callback', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.CreateBucketRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.CreateBucketRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.logging.v2.LogBucket(), + ); + client.innerApiCalls.createBucket = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createBucket( + request, + ( + err?: Error | null, + result?: protos.google.logging.v2.ILogBucket | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createBucket as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createBucket as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createView without error using callback', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.CreateViewRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.CreateViewRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.logging.v2.LogView() - ); - client.innerApiCalls.createView = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createView( - request, - (err?: Error|null, result?: protos.google.logging.v2.ILogView|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createView as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createView as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createBucket with error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.CreateBucketRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.CreateBucketRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createBucket = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.createBucket(request), expectedError); + const actualRequest = ( + client.innerApiCalls.createBucket as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createBucket as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createView with error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.CreateViewRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.CreateViewRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createView = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createView(request), expectedError); - const actualRequest = (client.innerApiCalls.createView as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createView as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createBucket with closed client', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.CreateBucketRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.CreateBucketRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.createBucket(request), expectedError); + }); + }); + + describe('updateBucket', () => { + it('invokes updateBucket without error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.UpdateBucketRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.UpdateBucketRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.logging.v2.LogBucket(), + ); + client.innerApiCalls.updateBucket = stubSimpleCall(expectedResponse); + const [response] = await client.updateBucket(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateBucket as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateBucket as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createView with closed client', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.CreateViewRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.CreateViewRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createView(request), expectedError); - }); + it('invokes updateBucket without error using callback', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.UpdateBucketRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.UpdateBucketRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.logging.v2.LogBucket(), + ); + client.innerApiCalls.updateBucket = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateBucket( + request, + ( + err?: Error | null, + result?: protos.google.logging.v2.ILogBucket | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateBucket as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateBucket as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('updateView', () => { - it('invokes updateView without error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.UpdateViewRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.UpdateViewRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.logging.v2.LogView() - ); - client.innerApiCalls.updateView = stubSimpleCall(expectedResponse); - const [response] = await client.updateView(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateView as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateView as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateBucket with error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.UpdateBucketRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.UpdateBucketRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateBucket = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.updateBucket(request), expectedError); + const actualRequest = ( + client.innerApiCalls.updateBucket as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateBucket as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateView without error using callback', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.UpdateViewRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.UpdateViewRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.logging.v2.LogView() - ); - client.innerApiCalls.updateView = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateView( - request, - (err?: Error|null, result?: protos.google.logging.v2.ILogView|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateView as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateView as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateBucket with closed client', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.UpdateBucketRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.UpdateBucketRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.updateBucket(request), expectedError); + }); + }); + + describe('deleteBucket', () => { + it('invokes deleteBucket without error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.DeleteBucketRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.DeleteBucketRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteBucket = stubSimpleCall(expectedResponse); + const [response] = await client.deleteBucket(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteBucket as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteBucket as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateView with error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.UpdateViewRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.UpdateViewRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateView = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateView(request), expectedError); - const actualRequest = (client.innerApiCalls.updateView as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateView as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteBucket without error using callback', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.DeleteBucketRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.DeleteBucketRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteBucket = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteBucket( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteBucket as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteBucket as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateView with closed client', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.UpdateViewRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.UpdateViewRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateView(request), expectedError); - }); + it('invokes deleteBucket with error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.DeleteBucketRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.DeleteBucketRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteBucket = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.deleteBucket(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteBucket as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteBucket as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('deleteView', () => { - it('invokes deleteView without error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.DeleteViewRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.DeleteViewRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteView = stubSimpleCall(expectedResponse); - const [response] = await client.deleteView(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteView as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteView as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteBucket with closed client', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.DeleteBucketRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.DeleteBucketRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.deleteBucket(request), expectedError); + }); + }); + + describe('undeleteBucket', () => { + it('invokes undeleteBucket without error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.UndeleteBucketRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.UndeleteBucketRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.undeleteBucket = stubSimpleCall(expectedResponse); + const [response] = await client.undeleteBucket(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.undeleteBucket as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.undeleteBucket as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteView without error using callback', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.DeleteViewRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.DeleteViewRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteView = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteView( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteView as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteView as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes undeleteBucket without error using callback', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.UndeleteBucketRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.UndeleteBucketRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.undeleteBucket = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.undeleteBucket( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.undeleteBucket as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.undeleteBucket as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteView with error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.DeleteViewRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.DeleteViewRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteView = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteView(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteView as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteView as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes undeleteBucket with error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.UndeleteBucketRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.UndeleteBucketRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.undeleteBucket = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.undeleteBucket(request), expectedError); + const actualRequest = ( + client.innerApiCalls.undeleteBucket as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.undeleteBucket as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteView with closed client', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.DeleteViewRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.DeleteViewRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteView(request), expectedError); - }); + it('invokes undeleteBucket with closed client', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.UndeleteBucketRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.UndeleteBucketRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.undeleteBucket(request), expectedError); + }); + }); + + describe('getView', () => { + it('invokes getView without error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.GetViewRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.GetViewRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.logging.v2.LogView(), + ); + client.innerApiCalls.getView = stubSimpleCall(expectedResponse); + const [response] = await client.getView(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.getView as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getView as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('getSink', () => { - it('invokes getSink without error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.GetSinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.GetSinkRequest', ['sinkName']); - request.sinkName = defaultValue1; - const expectedHeaderRequestParams = `sink_name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.logging.v2.LogSink() - ); - client.innerApiCalls.getSink = stubSimpleCall(expectedResponse); - const [response] = await client.getSink(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getSink as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getSink as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getView without error using callback', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.GetViewRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.GetViewRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.logging.v2.LogView(), + ); + client.innerApiCalls.getView = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getView( + request, + ( + err?: Error | null, + result?: protos.google.logging.v2.ILogView | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.getView as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getView as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getSink without error using callback', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.GetSinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.GetSinkRequest', ['sinkName']); - request.sinkName = defaultValue1; - const expectedHeaderRequestParams = `sink_name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.logging.v2.LogSink() - ); - client.innerApiCalls.getSink = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getSink( - request, - (err?: Error|null, result?: protos.google.logging.v2.ILogSink|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getSink as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getSink as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getView with error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.GetViewRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.GetViewRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getView = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.getView(request), expectedError); + const actualRequest = (client.innerApiCalls.getView as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getView as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getSink with error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.GetSinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.GetSinkRequest', ['sinkName']); - request.sinkName = defaultValue1; - const expectedHeaderRequestParams = `sink_name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getSink = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getSink(request), expectedError); - const actualRequest = (client.innerApiCalls.getSink as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getSink as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getView with closed client', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.GetViewRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.GetViewRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getView(request), expectedError); + }); + }); + + describe('createView', () => { + it('invokes createView without error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.CreateViewRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.CreateViewRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.logging.v2.LogView(), + ); + client.innerApiCalls.createView = stubSimpleCall(expectedResponse); + const [response] = await client.createView(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createView as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createView as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getSink with closed client', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.GetSinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.GetSinkRequest', ['sinkName']); - request.sinkName = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getSink(request), expectedError); - }); + it('invokes createView without error using callback', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.CreateViewRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.CreateViewRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.logging.v2.LogView(), + ); + client.innerApiCalls.createView = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createView( + request, + ( + err?: Error | null, + result?: protos.google.logging.v2.ILogView | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createView as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createView as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('createSink', () => { - it('invokes createSink without error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.CreateSinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.CreateSinkRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.logging.v2.LogSink() - ); - client.innerApiCalls.createSink = stubSimpleCall(expectedResponse); - const [response] = await client.createSink(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createSink as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createSink as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createView with error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.CreateViewRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.CreateViewRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createView = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.createView(request), expectedError); + const actualRequest = ( + client.innerApiCalls.createView as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createView as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createSink without error using callback', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.CreateSinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.CreateSinkRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.logging.v2.LogSink() - ); - client.innerApiCalls.createSink = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createSink( - request, - (err?: Error|null, result?: protos.google.logging.v2.ILogSink|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createSink as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createSink as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createView with closed client', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.CreateViewRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.CreateViewRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.createView(request), expectedError); + }); + }); + + describe('updateView', () => { + it('invokes updateView without error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.UpdateViewRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.UpdateViewRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.logging.v2.LogView(), + ); + client.innerApiCalls.updateView = stubSimpleCall(expectedResponse); + const [response] = await client.updateView(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateView as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateView as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createSink with error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.CreateSinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.CreateSinkRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createSink = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createSink(request), expectedError); - const actualRequest = (client.innerApiCalls.createSink as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createSink as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateView without error using callback', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.UpdateViewRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.UpdateViewRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.logging.v2.LogView(), + ); + client.innerApiCalls.updateView = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateView( + request, + ( + err?: Error | null, + result?: protos.google.logging.v2.ILogView | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateView as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateView as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createSink with closed client', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.CreateSinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.CreateSinkRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createSink(request), expectedError); - }); + it('invokes updateView with error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.UpdateViewRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.UpdateViewRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateView = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.updateView(request), expectedError); + const actualRequest = ( + client.innerApiCalls.updateView as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateView as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('updateSink', () => { - it('invokes updateSink without error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.UpdateSinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.UpdateSinkRequest', ['sinkName']); - request.sinkName = defaultValue1; - const expectedHeaderRequestParams = `sink_name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.logging.v2.LogSink() - ); - client.innerApiCalls.updateSink = stubSimpleCall(expectedResponse); - const [response] = await client.updateSink(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateSink as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateSink as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateView with closed client', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.UpdateViewRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.UpdateViewRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.updateView(request), expectedError); + }); + }); + + describe('deleteView', () => { + it('invokes deleteView without error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.DeleteViewRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.DeleteViewRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteView = stubSimpleCall(expectedResponse); + const [response] = await client.deleteView(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteView as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteView as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateSink without error using callback', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.UpdateSinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.UpdateSinkRequest', ['sinkName']); - request.sinkName = defaultValue1; - const expectedHeaderRequestParams = `sink_name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.logging.v2.LogSink() - ); - client.innerApiCalls.updateSink = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateSink( - request, - (err?: Error|null, result?: protos.google.logging.v2.ILogSink|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateSink as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateSink as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteView without error using callback', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.DeleteViewRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.DeleteViewRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteView = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteView( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteView as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteView as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateSink with error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.UpdateSinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.UpdateSinkRequest', ['sinkName']); - request.sinkName = defaultValue1; - const expectedHeaderRequestParams = `sink_name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateSink = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateSink(request), expectedError); - const actualRequest = (client.innerApiCalls.updateSink as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateSink as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteView with error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.DeleteViewRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.DeleteViewRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteView = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.deleteView(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteView as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteView as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateSink with closed client', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.UpdateSinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.UpdateSinkRequest', ['sinkName']); - request.sinkName = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateSink(request), expectedError); - }); + it('invokes deleteView with closed client', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.DeleteViewRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.DeleteViewRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.deleteView(request), expectedError); + }); + }); + + describe('getSink', () => { + it('invokes getSink without error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.GetSinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.GetSinkRequest', + ['sinkName'], + ); + request.sinkName = defaultValue1; + const expectedHeaderRequestParams = `sink_name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.logging.v2.LogSink(), + ); + client.innerApiCalls.getSink = stubSimpleCall(expectedResponse); + const [response] = await client.getSink(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.getSink as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getSink as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('deleteSink', () => { - it('invokes deleteSink without error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.DeleteSinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.DeleteSinkRequest', ['sinkName']); - request.sinkName = defaultValue1; - const expectedHeaderRequestParams = `sink_name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteSink = stubSimpleCall(expectedResponse); - const [response] = await client.deleteSink(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteSink as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteSink as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getSink without error using callback', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.GetSinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.GetSinkRequest', + ['sinkName'], + ); + request.sinkName = defaultValue1; + const expectedHeaderRequestParams = `sink_name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.logging.v2.LogSink(), + ); + client.innerApiCalls.getSink = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getSink( + request, + ( + err?: Error | null, + result?: protos.google.logging.v2.ILogSink | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.getSink as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getSink as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteSink without error using callback', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.DeleteSinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.DeleteSinkRequest', ['sinkName']); - request.sinkName = defaultValue1; - const expectedHeaderRequestParams = `sink_name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteSink = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteSink( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteSink as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteSink as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getSink with error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.GetSinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.GetSinkRequest', + ['sinkName'], + ); + request.sinkName = defaultValue1; + const expectedHeaderRequestParams = `sink_name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getSink = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.getSink(request), expectedError); + const actualRequest = (client.innerApiCalls.getSink as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getSink as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteSink with error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.DeleteSinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.DeleteSinkRequest', ['sinkName']); - request.sinkName = defaultValue1; - const expectedHeaderRequestParams = `sink_name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteSink = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteSink(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteSink as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteSink as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getSink with closed client', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.GetSinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.GetSinkRequest', + ['sinkName'], + ); + request.sinkName = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getSink(request), expectedError); + }); + }); + + describe('createSink', () => { + it('invokes createSink without error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.CreateSinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.CreateSinkRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.logging.v2.LogSink(), + ); + client.innerApiCalls.createSink = stubSimpleCall(expectedResponse); + const [response] = await client.createSink(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createSink as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createSink as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteSink with closed client', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.DeleteSinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.DeleteSinkRequest', ['sinkName']); - request.sinkName = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteSink(request), expectedError); - }); + it('invokes createSink without error using callback', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.CreateSinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.CreateSinkRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.logging.v2.LogSink(), + ); + client.innerApiCalls.createSink = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createSink( + request, + ( + err?: Error | null, + result?: protos.google.logging.v2.ILogSink | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createSink as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createSink as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('getExclusion', () => { - it('invokes getExclusion without error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.GetExclusionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.GetExclusionRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.logging.v2.LogExclusion() - ); - client.innerApiCalls.getExclusion = stubSimpleCall(expectedResponse); - const [response] = await client.getExclusion(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getExclusion as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getExclusion as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createSink with error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.CreateSinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.CreateSinkRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createSink = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.createSink(request), expectedError); + const actualRequest = ( + client.innerApiCalls.createSink as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createSink as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getExclusion without error using callback', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.GetExclusionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.GetExclusionRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.logging.v2.LogExclusion() - ); - client.innerApiCalls.getExclusion = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getExclusion( - request, - (err?: Error|null, result?: protos.google.logging.v2.ILogExclusion|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getExclusion as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getExclusion as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createSink with closed client', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.CreateSinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.CreateSinkRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.createSink(request), expectedError); + }); + }); + + describe('updateSink', () => { + it('invokes updateSink without error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.UpdateSinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.UpdateSinkRequest', + ['sinkName'], + ); + request.sinkName = defaultValue1; + const expectedHeaderRequestParams = `sink_name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.logging.v2.LogSink(), + ); + client.innerApiCalls.updateSink = stubSimpleCall(expectedResponse); + const [response] = await client.updateSink(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateSink as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateSink as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getExclusion with error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.GetExclusionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.GetExclusionRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getExclusion = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getExclusion(request), expectedError); - const actualRequest = (client.innerApiCalls.getExclusion as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getExclusion as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateSink without error using callback', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.UpdateSinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.UpdateSinkRequest', + ['sinkName'], + ); + request.sinkName = defaultValue1; + const expectedHeaderRequestParams = `sink_name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.logging.v2.LogSink(), + ); + client.innerApiCalls.updateSink = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateSink( + request, + ( + err?: Error | null, + result?: protos.google.logging.v2.ILogSink | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateSink as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateSink as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getExclusion with closed client', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.GetExclusionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.GetExclusionRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getExclusion(request), expectedError); - }); + it('invokes updateSink with error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.UpdateSinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.UpdateSinkRequest', + ['sinkName'], + ); + request.sinkName = defaultValue1; + const expectedHeaderRequestParams = `sink_name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateSink = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.updateSink(request), expectedError); + const actualRequest = ( + client.innerApiCalls.updateSink as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateSink as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('createExclusion', () => { - it('invokes createExclusion without error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.CreateExclusionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.CreateExclusionRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.logging.v2.LogExclusion() - ); - client.innerApiCalls.createExclusion = stubSimpleCall(expectedResponse); - const [response] = await client.createExclusion(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createExclusion as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createExclusion as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateSink with closed client', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.UpdateSinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.UpdateSinkRequest', + ['sinkName'], + ); + request.sinkName = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.updateSink(request), expectedError); + }); + }); + + describe('deleteSink', () => { + it('invokes deleteSink without error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.DeleteSinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.DeleteSinkRequest', + ['sinkName'], + ); + request.sinkName = defaultValue1; + const expectedHeaderRequestParams = `sink_name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteSink = stubSimpleCall(expectedResponse); + const [response] = await client.deleteSink(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteSink as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteSink as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createExclusion without error using callback', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.CreateExclusionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.CreateExclusionRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.logging.v2.LogExclusion() - ); - client.innerApiCalls.createExclusion = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createExclusion( - request, - (err?: Error|null, result?: protos.google.logging.v2.ILogExclusion|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createExclusion as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createExclusion as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteSink without error using callback', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.DeleteSinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.DeleteSinkRequest', + ['sinkName'], + ); + request.sinkName = defaultValue1; + const expectedHeaderRequestParams = `sink_name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteSink = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteSink( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteSink as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteSink as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createExclusion with error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.CreateExclusionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.CreateExclusionRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createExclusion = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createExclusion(request), expectedError); - const actualRequest = (client.innerApiCalls.createExclusion as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createExclusion as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteSink with error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.DeleteSinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.DeleteSinkRequest', + ['sinkName'], + ); + request.sinkName = defaultValue1; + const expectedHeaderRequestParams = `sink_name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteSink = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.deleteSink(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteSink as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteSink as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createExclusion with closed client', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.CreateExclusionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.CreateExclusionRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createExclusion(request), expectedError); - }); + it('invokes deleteSink with closed client', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.DeleteSinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.DeleteSinkRequest', + ['sinkName'], + ); + request.sinkName = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.deleteSink(request), expectedError); + }); + }); + + describe('getExclusion', () => { + it('invokes getExclusion without error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.GetExclusionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.GetExclusionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.logging.v2.LogExclusion(), + ); + client.innerApiCalls.getExclusion = stubSimpleCall(expectedResponse); + const [response] = await client.getExclusion(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getExclusion as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getExclusion as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('updateExclusion', () => { - it('invokes updateExclusion without error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.UpdateExclusionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.UpdateExclusionRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.logging.v2.LogExclusion() - ); - client.innerApiCalls.updateExclusion = stubSimpleCall(expectedResponse); - const [response] = await client.updateExclusion(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateExclusion as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateExclusion as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getExclusion without error using callback', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.GetExclusionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.GetExclusionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.logging.v2.LogExclusion(), + ); + client.innerApiCalls.getExclusion = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getExclusion( + request, + ( + err?: Error | null, + result?: protos.google.logging.v2.ILogExclusion | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getExclusion as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getExclusion as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateExclusion without error using callback', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.UpdateExclusionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.UpdateExclusionRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.logging.v2.LogExclusion() - ); - client.innerApiCalls.updateExclusion = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateExclusion( - request, - (err?: Error|null, result?: protos.google.logging.v2.ILogExclusion|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateExclusion as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateExclusion as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getExclusion with error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.GetExclusionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.GetExclusionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getExclusion = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getExclusion(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getExclusion as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getExclusion as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateExclusion with error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.UpdateExclusionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.UpdateExclusionRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateExclusion = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateExclusion(request), expectedError); - const actualRequest = (client.innerApiCalls.updateExclusion as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateExclusion as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getExclusion with closed client', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.GetExclusionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.GetExclusionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getExclusion(request), expectedError); + }); + }); + + describe('createExclusion', () => { + it('invokes createExclusion without error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.CreateExclusionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.CreateExclusionRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.logging.v2.LogExclusion(), + ); + client.innerApiCalls.createExclusion = stubSimpleCall(expectedResponse); + const [response] = await client.createExclusion(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createExclusion as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createExclusion as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateExclusion with closed client', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.UpdateExclusionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.UpdateExclusionRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateExclusion(request), expectedError); - }); + it('invokes createExclusion without error using callback', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.CreateExclusionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.CreateExclusionRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.logging.v2.LogExclusion(), + ); + client.innerApiCalls.createExclusion = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createExclusion( + request, + ( + err?: Error | null, + result?: protos.google.logging.v2.ILogExclusion | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createExclusion as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createExclusion as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('deleteExclusion', () => { - it('invokes deleteExclusion without error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.DeleteExclusionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.DeleteExclusionRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteExclusion = stubSimpleCall(expectedResponse); - const [response] = await client.deleteExclusion(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteExclusion as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteExclusion as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createExclusion with error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.CreateExclusionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.CreateExclusionRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createExclusion = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.createExclusion(request), expectedError); + const actualRequest = ( + client.innerApiCalls.createExclusion as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createExclusion as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteExclusion without error using callback', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.DeleteExclusionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.DeleteExclusionRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteExclusion = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteExclusion( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteExclusion as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteExclusion as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createExclusion with closed client', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.CreateExclusionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.CreateExclusionRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.createExclusion(request), expectedError); + }); + }); + + describe('updateExclusion', () => { + it('invokes updateExclusion without error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.UpdateExclusionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.UpdateExclusionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.logging.v2.LogExclusion(), + ); + client.innerApiCalls.updateExclusion = stubSimpleCall(expectedResponse); + const [response] = await client.updateExclusion(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateExclusion as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateExclusion as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteExclusion with error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.DeleteExclusionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.DeleteExclusionRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteExclusion = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteExclusion(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteExclusion as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteExclusion as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateExclusion without error using callback', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.UpdateExclusionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.UpdateExclusionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.logging.v2.LogExclusion(), + ); + client.innerApiCalls.updateExclusion = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateExclusion( + request, + ( + err?: Error | null, + result?: protos.google.logging.v2.ILogExclusion | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateExclusion as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateExclusion as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteExclusion with closed client', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.DeleteExclusionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.DeleteExclusionRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteExclusion(request), expectedError); - }); + it('invokes updateExclusion with error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.UpdateExclusionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.UpdateExclusionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateExclusion = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.updateExclusion(request), expectedError); + const actualRequest = ( + client.innerApiCalls.updateExclusion as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateExclusion as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('getCmekSettings', () => { - it('invokes getCmekSettings without error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.GetCmekSettingsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.GetCmekSettingsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.logging.v2.CmekSettings() - ); - client.innerApiCalls.getCmekSettings = stubSimpleCall(expectedResponse); - const [response] = await client.getCmekSettings(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getCmekSettings as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getCmekSettings as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateExclusion with closed client', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.UpdateExclusionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.UpdateExclusionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.updateExclusion(request), expectedError); + }); + }); + + describe('deleteExclusion', () => { + it('invokes deleteExclusion without error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.DeleteExclusionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.DeleteExclusionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteExclusion = stubSimpleCall(expectedResponse); + const [response] = await client.deleteExclusion(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteExclusion as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteExclusion as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getCmekSettings without error using callback', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.GetCmekSettingsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.GetCmekSettingsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.logging.v2.CmekSettings() - ); - client.innerApiCalls.getCmekSettings = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getCmekSettings( - request, - (err?: Error|null, result?: protos.google.logging.v2.ICmekSettings|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getCmekSettings as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getCmekSettings as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteExclusion without error using callback', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.DeleteExclusionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.DeleteExclusionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteExclusion = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteExclusion( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteExclusion as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteExclusion as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getCmekSettings with error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.GetCmekSettingsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.GetCmekSettingsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getCmekSettings = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getCmekSettings(request), expectedError); - const actualRequest = (client.innerApiCalls.getCmekSettings as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getCmekSettings as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteExclusion with error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.DeleteExclusionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.DeleteExclusionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteExclusion = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.deleteExclusion(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteExclusion as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteExclusion as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getCmekSettings with closed client', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.GetCmekSettingsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.GetCmekSettingsRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getCmekSettings(request), expectedError); - }); + it('invokes deleteExclusion with closed client', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.DeleteExclusionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.DeleteExclusionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.deleteExclusion(request), expectedError); + }); + }); + + describe('getCmekSettings', () => { + it('invokes getCmekSettings without error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.GetCmekSettingsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.GetCmekSettingsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.logging.v2.CmekSettings(), + ); + client.innerApiCalls.getCmekSettings = stubSimpleCall(expectedResponse); + const [response] = await client.getCmekSettings(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getCmekSettings as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getCmekSettings as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('updateCmekSettings', () => { - it('invokes updateCmekSettings without error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.UpdateCmekSettingsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.UpdateCmekSettingsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.logging.v2.CmekSettings() - ); - client.innerApiCalls.updateCmekSettings = stubSimpleCall(expectedResponse); - const [response] = await client.updateCmekSettings(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateCmekSettings as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateCmekSettings as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getCmekSettings without error using callback', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.GetCmekSettingsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.GetCmekSettingsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.logging.v2.CmekSettings(), + ); + client.innerApiCalls.getCmekSettings = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getCmekSettings( + request, + ( + err?: Error | null, + result?: protos.google.logging.v2.ICmekSettings | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getCmekSettings as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getCmekSettings as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateCmekSettings without error using callback', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.UpdateCmekSettingsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.UpdateCmekSettingsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.logging.v2.CmekSettings() - ); - client.innerApiCalls.updateCmekSettings = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateCmekSettings( - request, - (err?: Error|null, result?: protos.google.logging.v2.ICmekSettings|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateCmekSettings as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateCmekSettings as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getCmekSettings with error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.GetCmekSettingsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.GetCmekSettingsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getCmekSettings = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getCmekSettings(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getCmekSettings as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getCmekSettings as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateCmekSettings with error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.UpdateCmekSettingsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.UpdateCmekSettingsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateCmekSettings = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateCmekSettings(request), expectedError); - const actualRequest = (client.innerApiCalls.updateCmekSettings as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateCmekSettings as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getCmekSettings with closed client', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.GetCmekSettingsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.GetCmekSettingsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getCmekSettings(request), expectedError); + }); + }); + + describe('updateCmekSettings', () => { + it('invokes updateCmekSettings without error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.UpdateCmekSettingsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.UpdateCmekSettingsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.logging.v2.CmekSettings(), + ); + client.innerApiCalls.updateCmekSettings = + stubSimpleCall(expectedResponse); + const [response] = await client.updateCmekSettings(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateCmekSettings as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateCmekSettings as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateCmekSettings with closed client', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.UpdateCmekSettingsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.UpdateCmekSettingsRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateCmekSettings(request), expectedError); - }); + it('invokes updateCmekSettings without error using callback', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.UpdateCmekSettingsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.UpdateCmekSettingsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.logging.v2.CmekSettings(), + ); + client.innerApiCalls.updateCmekSettings = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateCmekSettings( + request, + ( + err?: Error | null, + result?: protos.google.logging.v2.ICmekSettings | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateCmekSettings as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateCmekSettings as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('getSettings', () => { - it('invokes getSettings without error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.GetSettingsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.GetSettingsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.logging.v2.Settings() - ); - client.innerApiCalls.getSettings = stubSimpleCall(expectedResponse); - const [response] = await client.getSettings(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getSettings as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getSettings as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateCmekSettings with error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.UpdateCmekSettingsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.UpdateCmekSettingsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateCmekSettings = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.updateCmekSettings(request), expectedError); + const actualRequest = ( + client.innerApiCalls.updateCmekSettings as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateCmekSettings as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getSettings without error using callback', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.GetSettingsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.GetSettingsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.logging.v2.Settings() - ); - client.innerApiCalls.getSettings = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getSettings( - request, - (err?: Error|null, result?: protos.google.logging.v2.ISettings|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getSettings as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getSettings as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateCmekSettings with closed client', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.UpdateCmekSettingsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.UpdateCmekSettingsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.updateCmekSettings(request), expectedError); + }); + }); + + describe('getSettings', () => { + it('invokes getSettings without error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.GetSettingsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.GetSettingsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.logging.v2.Settings(), + ); + client.innerApiCalls.getSettings = stubSimpleCall(expectedResponse); + const [response] = await client.getSettings(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getSettings as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getSettings as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getSettings with error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.GetSettingsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.GetSettingsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getSettings = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getSettings(request), expectedError); - const actualRequest = (client.innerApiCalls.getSettings as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getSettings as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getSettings without error using callback', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.GetSettingsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.GetSettingsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.logging.v2.Settings(), + ); + client.innerApiCalls.getSettings = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getSettings( + request, + ( + err?: Error | null, + result?: protos.google.logging.v2.ISettings | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getSettings as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getSettings as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getSettings with closed client', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.GetSettingsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.GetSettingsRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getSettings(request), expectedError); - }); + it('invokes getSettings with error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.GetSettingsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.GetSettingsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getSettings = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getSettings(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getSettings as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getSettings as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('updateSettings', () => { - it('invokes updateSettings without error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.UpdateSettingsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.UpdateSettingsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.logging.v2.Settings() - ); - client.innerApiCalls.updateSettings = stubSimpleCall(expectedResponse); - const [response] = await client.updateSettings(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateSettings as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateSettings as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getSettings with closed client', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.GetSettingsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.GetSettingsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getSettings(request), expectedError); + }); + }); + + describe('updateSettings', () => { + it('invokes updateSettings without error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.UpdateSettingsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.UpdateSettingsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.logging.v2.Settings(), + ); + client.innerApiCalls.updateSettings = stubSimpleCall(expectedResponse); + const [response] = await client.updateSettings(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateSettings as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateSettings as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateSettings without error using callback', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.UpdateSettingsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.UpdateSettingsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.logging.v2.Settings() - ); - client.innerApiCalls.updateSettings = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateSettings( - request, - (err?: Error|null, result?: protos.google.logging.v2.ISettings|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateSettings as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateSettings as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateSettings without error using callback', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.UpdateSettingsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.UpdateSettingsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.logging.v2.Settings(), + ); + client.innerApiCalls.updateSettings = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateSettings( + request, + ( + err?: Error | null, + result?: protos.google.logging.v2.ISettings | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateSettings as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateSettings as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateSettings with error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.UpdateSettingsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.UpdateSettingsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateSettings = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateSettings(request), expectedError); - const actualRequest = (client.innerApiCalls.updateSettings as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateSettings as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateSettings with error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.UpdateSettingsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.UpdateSettingsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateSettings = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.updateSettings(request), expectedError); + const actualRequest = ( + client.innerApiCalls.updateSettings as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateSettings as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateSettings with closed client', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.UpdateSettingsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.UpdateSettingsRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateSettings(request), expectedError); - }); + it('invokes updateSettings with closed client', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.UpdateSettingsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.UpdateSettingsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.updateSettings(request), expectedError); + }); + }); + + describe('copyLogEntries', () => { + it('invokes copyLogEntries without error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.CopyLogEntriesRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.copyLogEntries = + stubLongRunningCall(expectedResponse); + const [operation] = await client.copyLogEntries(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); }); - describe('copyLogEntries', () => { - it('invokes copyLogEntries without error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.CopyLogEntriesRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.copyLogEntries = stubLongRunningCall(expectedResponse); - const [operation] = await client.copyLogEntries(request); - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes copyLogEntries without error using callback', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.CopyLogEntriesRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.copyLogEntries = + stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.copyLogEntries( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.logging.v2.ICopyLogEntriesResponse, + protos.google.logging.v2.ICopyLogEntriesMetadata + > | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const operation = (await promise) as LROperation< + protos.google.logging.v2.ICopyLogEntriesResponse, + protos.google.logging.v2.ICopyLogEntriesMetadata + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes copyLogEntries without error using callback', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.CopyLogEntriesRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.copyLogEntries = stubLongRunningCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.copyLogEntries( - request, - (err?: Error|null, - result?: LROperation|null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const operation = await promise as LROperation; - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes copyLogEntries with call error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.CopyLogEntriesRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.copyLogEntries = stubLongRunningCall( + undefined, + expectedError, + ); + await assert.rejects(client.copyLogEntries(request), expectedError); + }); - it('invokes copyLogEntries with call error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.CopyLogEntriesRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.copyLogEntries = stubLongRunningCall(undefined, expectedError); - await assert.rejects(client.copyLogEntries(request), expectedError); - }); + it('invokes copyLogEntries with LRO error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.CopyLogEntriesRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.copyLogEntries = stubLongRunningCall( + undefined, + undefined, + expectedError, + ); + const [operation] = await client.copyLogEntries(request); + await assert.rejects(operation.promise(), expectedError); + }); - it('invokes copyLogEntries with LRO error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.CopyLogEntriesRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.copyLogEntries = stubLongRunningCall(undefined, undefined, expectedError); - const [operation] = await client.copyLogEntries(request); - await assert.rejects(operation.promise(), expectedError); - }); + it('invokes checkCopyLogEntriesProgress without error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation(), + ); + expectedResponse.name = 'test'; + expectedResponse.response = { type_url: 'url', value: Buffer.from('') }; + expectedResponse.metadata = { type_url: 'url', value: Buffer.from('') }; + + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const decodedOperation = await client.checkCopyLogEntriesProgress( + expectedResponse.name, + ); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); - it('invokes checkCopyLogEntriesProgress without error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedResponse = generateSampleMessage( - new operationsProtos.google.longrunning.Operation() - ); - expectedResponse.name = 'test'; - expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; - expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')} - - client.operationsClient.getOperation = stubSimpleCall(expectedResponse); - const decodedOperation = await client.checkCopyLogEntriesProgress(expectedResponse.name); - assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); - assert(decodedOperation.metadata); - assert((client.operationsClient.getOperation as SinonStub).getCall(0)); - }); + it('invokes checkCopyLogEntriesProgress with error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const expectedError = new Error('expected'); + + client.operationsClient.getOperation = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.checkCopyLogEntriesProgress(''), + expectedError, + ); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + }); + + describe('listBuckets', () => { + it('invokes listBuckets without error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.ListBucketsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.ListBucketsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.logging.v2.LogBucket()), + generateSampleMessage(new protos.google.logging.v2.LogBucket()), + generateSampleMessage(new protos.google.logging.v2.LogBucket()), + ]; + client.innerApiCalls.listBuckets = stubSimpleCall(expectedResponse); + const [response] = await client.listBuckets(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listBuckets as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listBuckets as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkCopyLogEntriesProgress with error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedError = new Error('expected'); - - client.operationsClient.getOperation = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.checkCopyLogEntriesProgress(''), expectedError); - assert((client.operationsClient.getOperation as SinonStub) - .getCall(0)); - }); + it('invokes listBuckets without error using callback', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.ListBucketsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.ListBucketsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.logging.v2.LogBucket()), + generateSampleMessage(new protos.google.logging.v2.LogBucket()), + generateSampleMessage(new protos.google.logging.v2.LogBucket()), + ]; + client.innerApiCalls.listBuckets = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listBuckets( + request, + ( + err?: Error | null, + result?: protos.google.logging.v2.ILogBucket[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listBuckets as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listBuckets as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('listBuckets', () => { - it('invokes listBuckets without error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.ListBucketsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.ListBucketsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.logging.v2.LogBucket()), - generateSampleMessage(new protos.google.logging.v2.LogBucket()), - generateSampleMessage(new protos.google.logging.v2.LogBucket()), - ]; - client.innerApiCalls.listBuckets = stubSimpleCall(expectedResponse); - const [response] = await client.listBuckets(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listBuckets as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listBuckets as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listBuckets with error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.ListBucketsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.ListBucketsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listBuckets = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listBuckets(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listBuckets as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listBuckets as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listBuckets without error using callback', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.ListBucketsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.ListBucketsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.logging.v2.LogBucket()), - generateSampleMessage(new protos.google.logging.v2.LogBucket()), - generateSampleMessage(new protos.google.logging.v2.LogBucket()), - ]; - client.innerApiCalls.listBuckets = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listBuckets( - request, - (err?: Error|null, result?: protos.google.logging.v2.ILogBucket[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listBuckets as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listBuckets as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listBucketsStream without error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.ListBucketsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.ListBucketsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.logging.v2.LogBucket()), + generateSampleMessage(new protos.google.logging.v2.LogBucket()), + generateSampleMessage(new protos.google.logging.v2.LogBucket()), + ]; + client.descriptors.page.listBuckets.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listBucketsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.logging.v2.LogBucket[] = []; + stream.on('data', (response: protos.google.logging.v2.LogBucket) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listBuckets.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listBuckets, request), + ); + assert( + (client.descriptors.page.listBuckets.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('invokes listBuckets with error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.ListBucketsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.ListBucketsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listBuckets = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listBuckets(request), expectedError); - const actualRequest = (client.innerApiCalls.listBuckets as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listBuckets as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listBucketsStream with error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.ListBucketsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.ListBucketsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listBuckets.createStream = stubPageStreamingCall( + undefined, + expectedError, + ); + const stream = client.listBucketsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.logging.v2.LogBucket[] = []; + stream.on('data', (response: protos.google.logging.v2.LogBucket) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listBuckets.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listBuckets, request), + ); + assert( + (client.descriptors.page.listBuckets.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('invokes listBucketsStream without error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.ListBucketsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.ListBucketsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.logging.v2.LogBucket()), - generateSampleMessage(new protos.google.logging.v2.LogBucket()), - generateSampleMessage(new protos.google.logging.v2.LogBucket()), - ]; - client.descriptors.page.listBuckets.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listBucketsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.logging.v2.LogBucket[] = []; - stream.on('data', (response: protos.google.logging.v2.LogBucket) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.listBuckets.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listBuckets, request)); - assert( - (client.descriptors.page.listBuckets.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listBuckets without error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.ListBucketsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.ListBucketsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.logging.v2.LogBucket()), + generateSampleMessage(new protos.google.logging.v2.LogBucket()), + generateSampleMessage(new protos.google.logging.v2.LogBucket()), + ]; + client.descriptors.page.listBuckets.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.logging.v2.ILogBucket[] = []; + const iterable = client.listBucketsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + (client.descriptors.page.listBuckets.asyncIterate as SinonStub).getCall( + 0, + ).args[1], + request, + ); + assert( + (client.descriptors.page.listBuckets.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('invokes listBucketsStream with error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.ListBucketsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.ListBucketsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listBuckets.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listBucketsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.logging.v2.LogBucket[] = []; - stream.on('data', (response: protos.google.logging.v2.LogBucket) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listBuckets.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listBuckets, request)); - assert( - (client.descriptors.page.listBuckets.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listBuckets with error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.ListBucketsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.ListBucketsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listBuckets.asyncIterate = stubAsyncIterationCall( + undefined, + expectedError, + ); + const iterable = client.listBucketsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.logging.v2.ILogBucket[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + (client.descriptors.page.listBuckets.asyncIterate as SinonStub).getCall( + 0, + ).args[1], + request, + ); + assert( + (client.descriptors.page.listBuckets.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + }); + + describe('listViews', () => { + it('invokes listViews without error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.ListViewsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.ListViewsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.logging.v2.LogView()), + generateSampleMessage(new protos.google.logging.v2.LogView()), + generateSampleMessage(new protos.google.logging.v2.LogView()), + ]; + client.innerApiCalls.listViews = stubSimpleCall(expectedResponse); + const [response] = await client.listViews(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listViews as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listViews as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('uses async iteration with listBuckets without error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.ListBucketsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.ListBucketsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.logging.v2.LogBucket()), - generateSampleMessage(new protos.google.logging.v2.LogBucket()), - generateSampleMessage(new protos.google.logging.v2.LogBucket()), - ]; - client.descriptors.page.listBuckets.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.logging.v2.ILogBucket[] = []; - const iterable = client.listBucketsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); + it('invokes listViews without error using callback', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.ListViewsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.ListViewsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.logging.v2.LogView()), + generateSampleMessage(new protos.google.logging.v2.LogView()), + generateSampleMessage(new protos.google.logging.v2.LogView()), + ]; + client.innerApiCalls.listViews = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listViews( + request, + ( + err?: Error | null, + result?: protos.google.logging.v2.ILogView[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listBuckets.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listBuckets.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); - - it('uses async iteration with listBuckets with error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.ListBucketsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.ListBucketsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listBuckets.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listBucketsAsync(request); - await assert.rejects(async () => { - const responses: protos.google.logging.v2.ILogBucket[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listBuckets.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listBuckets.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listViews as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listViews as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('listViews', () => { - it('invokes listViews without error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.ListViewsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.ListViewsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.logging.v2.LogView()), - generateSampleMessage(new protos.google.logging.v2.LogView()), - generateSampleMessage(new protos.google.logging.v2.LogView()), - ]; - client.innerApiCalls.listViews = stubSimpleCall(expectedResponse); - const [response] = await client.listViews(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listViews as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listViews as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listViews with error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.ListViewsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.ListViewsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listViews = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.listViews(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listViews as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listViews as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listViews without error using callback', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.ListViewsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.ListViewsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.logging.v2.LogView()), - generateSampleMessage(new protos.google.logging.v2.LogView()), - generateSampleMessage(new protos.google.logging.v2.LogView()), - ]; - client.innerApiCalls.listViews = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listViews( - request, - (err?: Error|null, result?: protos.google.logging.v2.ILogView[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listViews as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listViews as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listViewsStream without error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.ListViewsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.ListViewsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.logging.v2.LogView()), + generateSampleMessage(new protos.google.logging.v2.LogView()), + generateSampleMessage(new protos.google.logging.v2.LogView()), + ]; + client.descriptors.page.listViews.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listViewsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.logging.v2.LogView[] = []; + stream.on('data', (response: protos.google.logging.v2.LogView) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listViews.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listViews, request), + ); + assert( + (client.descriptors.page.listViews.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('invokes listViews with error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.ListViewsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.ListViewsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listViews = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listViews(request), expectedError); - const actualRequest = (client.innerApiCalls.listViews as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listViews as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listViewsStream with error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.ListViewsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.ListViewsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listViews.createStream = stubPageStreamingCall( + undefined, + expectedError, + ); + const stream = client.listViewsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.logging.v2.LogView[] = []; + stream.on('data', (response: protos.google.logging.v2.LogView) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listViews.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listViews, request), + ); + assert( + (client.descriptors.page.listViews.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('invokes listViewsStream without error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.ListViewsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.ListViewsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.logging.v2.LogView()), - generateSampleMessage(new protos.google.logging.v2.LogView()), - generateSampleMessage(new protos.google.logging.v2.LogView()), - ]; - client.descriptors.page.listViews.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listViewsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.logging.v2.LogView[] = []; - stream.on('data', (response: protos.google.logging.v2.LogView) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.listViews.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listViews, request)); - assert( - (client.descriptors.page.listViews.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listViews without error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.ListViewsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.ListViewsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.logging.v2.LogView()), + generateSampleMessage(new protos.google.logging.v2.LogView()), + generateSampleMessage(new protos.google.logging.v2.LogView()), + ]; + client.descriptors.page.listViews.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.logging.v2.ILogView[] = []; + const iterable = client.listViewsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + (client.descriptors.page.listViews.asyncIterate as SinonStub).getCall(0) + .args[1], + request, + ); + assert( + (client.descriptors.page.listViews.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('invokes listViewsStream with error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.ListViewsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.ListViewsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listViews.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listViewsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.logging.v2.LogView[] = []; - stream.on('data', (response: protos.google.logging.v2.LogView) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listViews.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listViews, request)); - assert( - (client.descriptors.page.listViews.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listViews with error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.ListViewsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.ListViewsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listViews.asyncIterate = stubAsyncIterationCall( + undefined, + expectedError, + ); + const iterable = client.listViewsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.logging.v2.ILogView[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + (client.descriptors.page.listViews.asyncIterate as SinonStub).getCall(0) + .args[1], + request, + ); + assert( + (client.descriptors.page.listViews.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + }); + + describe('listSinks', () => { + it('invokes listSinks without error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.ListSinksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.ListSinksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.logging.v2.LogSink()), + generateSampleMessage(new protos.google.logging.v2.LogSink()), + generateSampleMessage(new protos.google.logging.v2.LogSink()), + ]; + client.innerApiCalls.listSinks = stubSimpleCall(expectedResponse); + const [response] = await client.listSinks(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listSinks as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listSinks as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('uses async iteration with listViews without error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.ListViewsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.ListViewsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.logging.v2.LogView()), - generateSampleMessage(new protos.google.logging.v2.LogView()), - generateSampleMessage(new protos.google.logging.v2.LogView()), - ]; - client.descriptors.page.listViews.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.logging.v2.ILogView[] = []; - const iterable = client.listViewsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); + it('invokes listSinks without error using callback', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.ListSinksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.ListSinksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.logging.v2.LogSink()), + generateSampleMessage(new protos.google.logging.v2.LogSink()), + generateSampleMessage(new protos.google.logging.v2.LogSink()), + ]; + client.innerApiCalls.listSinks = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listSinks( + request, + ( + err?: Error | null, + result?: protos.google.logging.v2.ILogSink[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listViews.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listViews.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); - - it('uses async iteration with listViews with error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.ListViewsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.ListViewsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listViews.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listViewsAsync(request); - await assert.rejects(async () => { - const responses: protos.google.logging.v2.ILogView[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listViews.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listViews.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listSinks as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listSinks as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('listSinks', () => { - it('invokes listSinks without error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.ListSinksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.ListSinksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.logging.v2.LogSink()), - generateSampleMessage(new protos.google.logging.v2.LogSink()), - generateSampleMessage(new protos.google.logging.v2.LogSink()), - ]; - client.innerApiCalls.listSinks = stubSimpleCall(expectedResponse); - const [response] = await client.listSinks(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listSinks as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listSinks as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listSinks with error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.ListSinksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.ListSinksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listSinks = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.listSinks(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listSinks as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listSinks as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listSinks without error using callback', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.ListSinksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.ListSinksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.logging.v2.LogSink()), - generateSampleMessage(new protos.google.logging.v2.LogSink()), - generateSampleMessage(new protos.google.logging.v2.LogSink()), - ]; - client.innerApiCalls.listSinks = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listSinks( - request, - (err?: Error|null, result?: protos.google.logging.v2.ILogSink[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listSinks as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listSinks as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listSinksStream without error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.ListSinksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.ListSinksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.logging.v2.LogSink()), + generateSampleMessage(new protos.google.logging.v2.LogSink()), + generateSampleMessage(new protos.google.logging.v2.LogSink()), + ]; + client.descriptors.page.listSinks.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listSinksStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.logging.v2.LogSink[] = []; + stream.on('data', (response: protos.google.logging.v2.LogSink) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listSinks.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listSinks, request), + ); + assert( + (client.descriptors.page.listSinks.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('invokes listSinks with error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.ListSinksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.ListSinksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listSinks = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listSinks(request), expectedError); - const actualRequest = (client.innerApiCalls.listSinks as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listSinks as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listSinksStream with error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.ListSinksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.ListSinksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listSinks.createStream = stubPageStreamingCall( + undefined, + expectedError, + ); + const stream = client.listSinksStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.logging.v2.LogSink[] = []; + stream.on('data', (response: protos.google.logging.v2.LogSink) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listSinks.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listSinks, request), + ); + assert( + (client.descriptors.page.listSinks.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('invokes listSinksStream without error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.ListSinksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.ListSinksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.logging.v2.LogSink()), - generateSampleMessage(new protos.google.logging.v2.LogSink()), - generateSampleMessage(new protos.google.logging.v2.LogSink()), - ]; - client.descriptors.page.listSinks.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listSinksStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.logging.v2.LogSink[] = []; - stream.on('data', (response: protos.google.logging.v2.LogSink) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.listSinks.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listSinks, request)); - assert( - (client.descriptors.page.listSinks.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listSinks without error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.ListSinksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.ListSinksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.logging.v2.LogSink()), + generateSampleMessage(new protos.google.logging.v2.LogSink()), + generateSampleMessage(new protos.google.logging.v2.LogSink()), + ]; + client.descriptors.page.listSinks.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.logging.v2.ILogSink[] = []; + const iterable = client.listSinksAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + (client.descriptors.page.listSinks.asyncIterate as SinonStub).getCall(0) + .args[1], + request, + ); + assert( + (client.descriptors.page.listSinks.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('invokes listSinksStream with error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.ListSinksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.ListSinksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listSinks.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listSinksStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.logging.v2.LogSink[] = []; - stream.on('data', (response: protos.google.logging.v2.LogSink) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listSinks.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listSinks, request)); - assert( - (client.descriptors.page.listSinks.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listSinks with error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.ListSinksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.ListSinksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listSinks.asyncIterate = stubAsyncIterationCall( + undefined, + expectedError, + ); + const iterable = client.listSinksAsync(request); + await assert.rejects(async () => { + const responses: protos.google.logging.v2.ILogSink[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + (client.descriptors.page.listSinks.asyncIterate as SinonStub).getCall(0) + .args[1], + request, + ); + assert( + (client.descriptors.page.listSinks.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + }); + + describe('listExclusions', () => { + it('invokes listExclusions without error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.ListExclusionsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.ListExclusionsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.logging.v2.LogExclusion()), + generateSampleMessage(new protos.google.logging.v2.LogExclusion()), + generateSampleMessage(new protos.google.logging.v2.LogExclusion()), + ]; + client.innerApiCalls.listExclusions = stubSimpleCall(expectedResponse); + const [response] = await client.listExclusions(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listExclusions as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listExclusions as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('uses async iteration with listSinks without error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.ListSinksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.ListSinksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.logging.v2.LogSink()), - generateSampleMessage(new protos.google.logging.v2.LogSink()), - generateSampleMessage(new protos.google.logging.v2.LogSink()), - ]; - client.descriptors.page.listSinks.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.logging.v2.ILogSink[] = []; - const iterable = client.listSinksAsync(request); - for await (const resource of iterable) { - responses.push(resource!); + it('invokes listExclusions without error using callback', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.ListExclusionsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.ListExclusionsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.logging.v2.LogExclusion()), + generateSampleMessage(new protos.google.logging.v2.LogExclusion()), + generateSampleMessage(new protos.google.logging.v2.LogExclusion()), + ]; + client.innerApiCalls.listExclusions = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listExclusions( + request, + ( + err?: Error | null, + result?: protos.google.logging.v2.ILogExclusion[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listSinks.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listSinks.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); - - it('uses async iteration with listSinks with error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.ListSinksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.ListSinksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listSinks.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listSinksAsync(request); - await assert.rejects(async () => { - const responses: protos.google.logging.v2.ILogSink[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listSinks.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listSinks.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listExclusions as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listExclusions as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('listExclusions', () => { - it('invokes listExclusions without error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.ListExclusionsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.ListExclusionsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.logging.v2.LogExclusion()), - generateSampleMessage(new protos.google.logging.v2.LogExclusion()), - generateSampleMessage(new protos.google.logging.v2.LogExclusion()), - ]; - client.innerApiCalls.listExclusions = stubSimpleCall(expectedResponse); - const [response] = await client.listExclusions(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listExclusions as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listExclusions as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listExclusions without error using callback', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.ListExclusionsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.ListExclusionsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.logging.v2.LogExclusion()), - generateSampleMessage(new protos.google.logging.v2.LogExclusion()), - generateSampleMessage(new protos.google.logging.v2.LogExclusion()), - ]; - client.innerApiCalls.listExclusions = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listExclusions( - request, - (err?: Error|null, result?: protos.google.logging.v2.ILogExclusion[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listExclusions as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listExclusions as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listExclusions with error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.ListExclusionsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.ListExclusionsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listExclusions = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listExclusions(request), expectedError); - const actualRequest = (client.innerApiCalls.listExclusions as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listExclusions as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listExclusionsStream without error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.ListExclusionsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.ListExclusionsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.logging.v2.LogExclusion()), - generateSampleMessage(new protos.google.logging.v2.LogExclusion()), - generateSampleMessage(new protos.google.logging.v2.LogExclusion()), - ]; - client.descriptors.page.listExclusions.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listExclusionsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.logging.v2.LogExclusion[] = []; - stream.on('data', (response: protos.google.logging.v2.LogExclusion) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.listExclusions.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listExclusions, request)); - assert( - (client.descriptors.page.listExclusions.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listExclusions with error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.ListExclusionsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.ListExclusionsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listExclusions = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listExclusions(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listExclusions as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listExclusions as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listExclusionsStream with error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.ListExclusionsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.ListExclusionsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listExclusions.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listExclusionsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.logging.v2.LogExclusion[] = []; - stream.on('data', (response: protos.google.logging.v2.LogExclusion) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listExclusions.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listExclusions, request)); - assert( - (client.descriptors.page.listExclusions.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listExclusionsStream without error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.ListExclusionsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.ListExclusionsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.logging.v2.LogExclusion()), + generateSampleMessage(new protos.google.logging.v2.LogExclusion()), + generateSampleMessage(new protos.google.logging.v2.LogExclusion()), + ]; + client.descriptors.page.listExclusions.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listExclusionsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.logging.v2.LogExclusion[] = []; + stream.on('data', (response: protos.google.logging.v2.LogExclusion) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listExclusions.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listExclusions, request), + ); + assert( + (client.descriptors.page.listExclusions.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('uses async iteration with listExclusions without error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.ListExclusionsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.ListExclusionsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.logging.v2.LogExclusion()), - generateSampleMessage(new protos.google.logging.v2.LogExclusion()), - generateSampleMessage(new protos.google.logging.v2.LogExclusion()), - ]; - client.descriptors.page.listExclusions.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.logging.v2.ILogExclusion[] = []; - const iterable = client.listExclusionsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listExclusions.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listExclusions.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listExclusionsStream with error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.ListExclusionsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.ListExclusionsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listExclusions.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listExclusionsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.logging.v2.LogExclusion[] = []; + stream.on('data', (response: protos.google.logging.v2.LogExclusion) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listExclusions.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listExclusions, request), + ); + assert( + (client.descriptors.page.listExclusions.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('uses async iteration with listExclusions with error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.ListExclusionsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.ListExclusionsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listExclusions.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listExclusionsAsync(request); - await assert.rejects(async () => { - const responses: protos.google.logging.v2.ILogExclusion[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listExclusions.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listExclusions.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listExclusions without error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.ListExclusionsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.ListExclusionsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.logging.v2.LogExclusion()), + generateSampleMessage(new protos.google.logging.v2.LogExclusion()), + generateSampleMessage(new protos.google.logging.v2.LogExclusion()), + ]; + client.descriptors.page.listExclusions.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.logging.v2.ILogExclusion[] = []; + const iterable = client.listExclusionsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listExclusions.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listExclusions.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); }); - describe('Path templates', () => { - - describe('billingAccountCmekSettings', () => { - const fakePath = "/rendered/path/billingAccountCmekSettings"; - const expectedParameters = { - billing_account: "billingAccountValue", - }; - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.billingAccountCmekSettingsPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.billingAccountCmekSettingsPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('billingAccountCmekSettingsPath', () => { - const result = client.billingAccountCmekSettingsPath("billingAccountValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.billingAccountCmekSettingsPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchBillingAccountFromBillingAccountCmekSettingsName', () => { - const result = client.matchBillingAccountFromBillingAccountCmekSettingsName(fakePath); - assert.strictEqual(result, "billingAccountValue"); - assert((client.pathTemplates.billingAccountCmekSettingsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('uses async iteration with listExclusions with error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.ListExclusionsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.ListExclusionsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listExclusions.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listExclusionsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.logging.v2.ILogExclusion[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listExclusions.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listExclusions.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + }); + + describe('Path templates', () => { + describe('billingAccountCmekSettings', () => { + const fakePath = '/rendered/path/billingAccountCmekSettings'; + const expectedParameters = { + billing_account: 'billingAccountValue', + }; + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.billingAccountCmekSettingsPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.billingAccountCmekSettingsPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('billingAccountCmekSettingsPath', () => { + const result = client.billingAccountCmekSettingsPath( + 'billingAccountValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.billingAccountCmekSettingsPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchBillingAccountFromBillingAccountCmekSettingsName', () => { + const result = + client.matchBillingAccountFromBillingAccountCmekSettingsName( + fakePath, + ); + assert.strictEqual(result, 'billingAccountValue'); + assert( + ( + client.pathTemplates.billingAccountCmekSettingsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('billingAccountExclusion', () => { - const fakePath = "/rendered/path/billingAccountExclusion"; - const expectedParameters = { - billing_account: "billingAccountValue", - exclusion: "exclusionValue", - }; - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.billingAccountExclusionPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.billingAccountExclusionPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('billingAccountExclusionPath', () => { - const result = client.billingAccountExclusionPath("billingAccountValue", "exclusionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.billingAccountExclusionPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchBillingAccountFromBillingAccountExclusionName', () => { - const result = client.matchBillingAccountFromBillingAccountExclusionName(fakePath); - assert.strictEqual(result, "billingAccountValue"); - assert((client.pathTemplates.billingAccountExclusionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchExclusionFromBillingAccountExclusionName', () => { - const result = client.matchExclusionFromBillingAccountExclusionName(fakePath); - assert.strictEqual(result, "exclusionValue"); - assert((client.pathTemplates.billingAccountExclusionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('billingAccountExclusion', () => { + const fakePath = '/rendered/path/billingAccountExclusion'; + const expectedParameters = { + billing_account: 'billingAccountValue', + exclusion: 'exclusionValue', + }; + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.billingAccountExclusionPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.billingAccountExclusionPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('billingAccountExclusionPath', () => { + const result = client.billingAccountExclusionPath( + 'billingAccountValue', + 'exclusionValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.billingAccountExclusionPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchBillingAccountFromBillingAccountExclusionName', () => { + const result = + client.matchBillingAccountFromBillingAccountExclusionName(fakePath); + assert.strictEqual(result, 'billingAccountValue'); + assert( + ( + client.pathTemplates.billingAccountExclusionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchExclusionFromBillingAccountExclusionName', () => { + const result = + client.matchExclusionFromBillingAccountExclusionName(fakePath); + assert.strictEqual(result, 'exclusionValue'); + assert( + ( + client.pathTemplates.billingAccountExclusionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('billingAccountLocationBucket', () => { - const fakePath = "/rendered/path/billingAccountLocationBucket"; - const expectedParameters = { - billing_account: "billingAccountValue", - location: "locationValue", - bucket: "bucketValue", - }; - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.billingAccountLocationBucketPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.billingAccountLocationBucketPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('billingAccountLocationBucketPath', () => { - const result = client.billingAccountLocationBucketPath("billingAccountValue", "locationValue", "bucketValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.billingAccountLocationBucketPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchBillingAccountFromBillingAccountLocationBucketName', () => { - const result = client.matchBillingAccountFromBillingAccountLocationBucketName(fakePath); - assert.strictEqual(result, "billingAccountValue"); - assert((client.pathTemplates.billingAccountLocationBucketPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromBillingAccountLocationBucketName', () => { - const result = client.matchLocationFromBillingAccountLocationBucketName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.billingAccountLocationBucketPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBucketFromBillingAccountLocationBucketName', () => { - const result = client.matchBucketFromBillingAccountLocationBucketName(fakePath); - assert.strictEqual(result, "bucketValue"); - assert((client.pathTemplates.billingAccountLocationBucketPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('billingAccountLocationBucket', () => { + const fakePath = '/rendered/path/billingAccountLocationBucket'; + const expectedParameters = { + billing_account: 'billingAccountValue', + location: 'locationValue', + bucket: 'bucketValue', + }; + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.billingAccountLocationBucketPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.billingAccountLocationBucketPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('billingAccountLocationBucketPath', () => { + const result = client.billingAccountLocationBucketPath( + 'billingAccountValue', + 'locationValue', + 'bucketValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.billingAccountLocationBucketPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchBillingAccountFromBillingAccountLocationBucketName', () => { + const result = + client.matchBillingAccountFromBillingAccountLocationBucketName( + fakePath, + ); + assert.strictEqual(result, 'billingAccountValue'); + assert( + ( + client.pathTemplates.billingAccountLocationBucketPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromBillingAccountLocationBucketName', () => { + const result = + client.matchLocationFromBillingAccountLocationBucketName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + ( + client.pathTemplates.billingAccountLocationBucketPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBucketFromBillingAccountLocationBucketName', () => { + const result = + client.matchBucketFromBillingAccountLocationBucketName(fakePath); + assert.strictEqual(result, 'bucketValue'); + assert( + ( + client.pathTemplates.billingAccountLocationBucketPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('billingAccountLocationBucketView', () => { - const fakePath = "/rendered/path/billingAccountLocationBucketView"; - const expectedParameters = { - billing_account: "billingAccountValue", - location: "locationValue", - bucket: "bucketValue", - view: "viewValue", - }; - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.billingAccountLocationBucketViewPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.billingAccountLocationBucketViewPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('billingAccountLocationBucketViewPath', () => { - const result = client.billingAccountLocationBucketViewPath("billingAccountValue", "locationValue", "bucketValue", "viewValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.billingAccountLocationBucketViewPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchBillingAccountFromBillingAccountLocationBucketViewName', () => { - const result = client.matchBillingAccountFromBillingAccountLocationBucketViewName(fakePath); - assert.strictEqual(result, "billingAccountValue"); - assert((client.pathTemplates.billingAccountLocationBucketViewPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromBillingAccountLocationBucketViewName', () => { - const result = client.matchLocationFromBillingAccountLocationBucketViewName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.billingAccountLocationBucketViewPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBucketFromBillingAccountLocationBucketViewName', () => { - const result = client.matchBucketFromBillingAccountLocationBucketViewName(fakePath); - assert.strictEqual(result, "bucketValue"); - assert((client.pathTemplates.billingAccountLocationBucketViewPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchViewFromBillingAccountLocationBucketViewName', () => { - const result = client.matchViewFromBillingAccountLocationBucketViewName(fakePath); - assert.strictEqual(result, "viewValue"); - assert((client.pathTemplates.billingAccountLocationBucketViewPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('billingAccountLocationBucketView', () => { + const fakePath = '/rendered/path/billingAccountLocationBucketView'; + const expectedParameters = { + billing_account: 'billingAccountValue', + location: 'locationValue', + bucket: 'bucketValue', + view: 'viewValue', + }; + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.billingAccountLocationBucketViewPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.billingAccountLocationBucketViewPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('billingAccountLocationBucketViewPath', () => { + const result = client.billingAccountLocationBucketViewPath( + 'billingAccountValue', + 'locationValue', + 'bucketValue', + 'viewValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.billingAccountLocationBucketViewPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchBillingAccountFromBillingAccountLocationBucketViewName', () => { + const result = + client.matchBillingAccountFromBillingAccountLocationBucketViewName( + fakePath, + ); + assert.strictEqual(result, 'billingAccountValue'); + assert( + ( + client.pathTemplates.billingAccountLocationBucketViewPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromBillingAccountLocationBucketViewName', () => { + const result = + client.matchLocationFromBillingAccountLocationBucketViewName( + fakePath, + ); + assert.strictEqual(result, 'locationValue'); + assert( + ( + client.pathTemplates.billingAccountLocationBucketViewPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBucketFromBillingAccountLocationBucketViewName', () => { + const result = + client.matchBucketFromBillingAccountLocationBucketViewName(fakePath); + assert.strictEqual(result, 'bucketValue'); + assert( + ( + client.pathTemplates.billingAccountLocationBucketViewPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchViewFromBillingAccountLocationBucketViewName', () => { + const result = + client.matchViewFromBillingAccountLocationBucketViewName(fakePath); + assert.strictEqual(result, 'viewValue'); + assert( + ( + client.pathTemplates.billingAccountLocationBucketViewPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('billingAccountLog', () => { - const fakePath = "/rendered/path/billingAccountLog"; - const expectedParameters = { - billing_account: "billingAccountValue", - log: "logValue", - }; - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.billingAccountLogPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.billingAccountLogPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('billingAccountLogPath', () => { - const result = client.billingAccountLogPath("billingAccountValue", "logValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.billingAccountLogPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchBillingAccountFromBillingAccountLogName', () => { - const result = client.matchBillingAccountFromBillingAccountLogName(fakePath); - assert.strictEqual(result, "billingAccountValue"); - assert((client.pathTemplates.billingAccountLogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLogFromBillingAccountLogName', () => { - const result = client.matchLogFromBillingAccountLogName(fakePath); - assert.strictEqual(result, "logValue"); - assert((client.pathTemplates.billingAccountLogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('billingAccountLog', () => { + const fakePath = '/rendered/path/billingAccountLog'; + const expectedParameters = { + billing_account: 'billingAccountValue', + log: 'logValue', + }; + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.billingAccountLogPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.billingAccountLogPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('billingAccountLogPath', () => { + const result = client.billingAccountLogPath( + 'billingAccountValue', + 'logValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.billingAccountLogPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchBillingAccountFromBillingAccountLogName', () => { + const result = + client.matchBillingAccountFromBillingAccountLogName(fakePath); + assert.strictEqual(result, 'billingAccountValue'); + assert( + ( + client.pathTemplates.billingAccountLogPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLogFromBillingAccountLogName', () => { + const result = client.matchLogFromBillingAccountLogName(fakePath); + assert.strictEqual(result, 'logValue'); + assert( + ( + client.pathTemplates.billingAccountLogPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('billingAccountSettings', () => { - const fakePath = "/rendered/path/billingAccountSettings"; - const expectedParameters = { - billing_account: "billingAccountValue", - }; - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.billingAccountSettingsPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.billingAccountSettingsPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('billingAccountSettingsPath', () => { - const result = client.billingAccountSettingsPath("billingAccountValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.billingAccountSettingsPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchBillingAccountFromBillingAccountSettingsName', () => { - const result = client.matchBillingAccountFromBillingAccountSettingsName(fakePath); - assert.strictEqual(result, "billingAccountValue"); - assert((client.pathTemplates.billingAccountSettingsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('billingAccountSettings', () => { + const fakePath = '/rendered/path/billingAccountSettings'; + const expectedParameters = { + billing_account: 'billingAccountValue', + }; + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.billingAccountSettingsPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.billingAccountSettingsPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('billingAccountSettingsPath', () => { + const result = client.billingAccountSettingsPath('billingAccountValue'); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.billingAccountSettingsPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchBillingAccountFromBillingAccountSettingsName', () => { + const result = + client.matchBillingAccountFromBillingAccountSettingsName(fakePath); + assert.strictEqual(result, 'billingAccountValue'); + assert( + ( + client.pathTemplates.billingAccountSettingsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('billingAccountSink', () => { - const fakePath = "/rendered/path/billingAccountSink"; - const expectedParameters = { - billing_account: "billingAccountValue", - sink: "sinkValue", - }; - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.billingAccountSinkPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.billingAccountSinkPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('billingAccountSinkPath', () => { - const result = client.billingAccountSinkPath("billingAccountValue", "sinkValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.billingAccountSinkPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchBillingAccountFromBillingAccountSinkName', () => { - const result = client.matchBillingAccountFromBillingAccountSinkName(fakePath); - assert.strictEqual(result, "billingAccountValue"); - assert((client.pathTemplates.billingAccountSinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchSinkFromBillingAccountSinkName', () => { - const result = client.matchSinkFromBillingAccountSinkName(fakePath); - assert.strictEqual(result, "sinkValue"); - assert((client.pathTemplates.billingAccountSinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('billingAccountSink', () => { + const fakePath = '/rendered/path/billingAccountSink'; + const expectedParameters = { + billing_account: 'billingAccountValue', + sink: 'sinkValue', + }; + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.billingAccountSinkPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.billingAccountSinkPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('billingAccountSinkPath', () => { + const result = client.billingAccountSinkPath( + 'billingAccountValue', + 'sinkValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.billingAccountSinkPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchBillingAccountFromBillingAccountSinkName', () => { + const result = + client.matchBillingAccountFromBillingAccountSinkName(fakePath); + assert.strictEqual(result, 'billingAccountValue'); + assert( + ( + client.pathTemplates.billingAccountSinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchSinkFromBillingAccountSinkName', () => { + const result = client.matchSinkFromBillingAccountSinkName(fakePath); + assert.strictEqual(result, 'sinkValue'); + assert( + ( + client.pathTemplates.billingAccountSinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('folderCmekSettings', () => { - const fakePath = "/rendered/path/folderCmekSettings"; - const expectedParameters = { - folder: "folderValue", - }; - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.folderCmekSettingsPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderCmekSettingsPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderCmekSettingsPath', () => { - const result = client.folderCmekSettingsPath("folderValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderCmekSettingsPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderCmekSettingsName', () => { - const result = client.matchFolderFromFolderCmekSettingsName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderCmekSettingsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('folderCmekSettings', () => { + const fakePath = '/rendered/path/folderCmekSettings'; + const expectedParameters = { + folder: 'folderValue', + }; + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.folderCmekSettingsPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderCmekSettingsPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderCmekSettingsPath', () => { + const result = client.folderCmekSettingsPath('folderValue'); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.folderCmekSettingsPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderCmekSettingsName', () => { + const result = client.matchFolderFromFolderCmekSettingsName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + ( + client.pathTemplates.folderCmekSettingsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('folderExclusion', () => { - const fakePath = "/rendered/path/folderExclusion"; - const expectedParameters = { - folder: "folderValue", - exclusion: "exclusionValue", - }; - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.folderExclusionPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderExclusionPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderExclusionPath', () => { - const result = client.folderExclusionPath("folderValue", "exclusionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderExclusionPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderExclusionName', () => { - const result = client.matchFolderFromFolderExclusionName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderExclusionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchExclusionFromFolderExclusionName', () => { - const result = client.matchExclusionFromFolderExclusionName(fakePath); - assert.strictEqual(result, "exclusionValue"); - assert((client.pathTemplates.folderExclusionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('folderExclusion', () => { + const fakePath = '/rendered/path/folderExclusion'; + const expectedParameters = { + folder: 'folderValue', + exclusion: 'exclusionValue', + }; + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.folderExclusionPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderExclusionPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderExclusionPath', () => { + const result = client.folderExclusionPath( + 'folderValue', + 'exclusionValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.folderExclusionPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderExclusionName', () => { + const result = client.matchFolderFromFolderExclusionName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + (client.pathTemplates.folderExclusionPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchExclusionFromFolderExclusionName', () => { + const result = client.matchExclusionFromFolderExclusionName(fakePath); + assert.strictEqual(result, 'exclusionValue'); + assert( + (client.pathTemplates.folderExclusionPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('folderLocationBucket', () => { - const fakePath = "/rendered/path/folderLocationBucket"; - const expectedParameters = { - folder: "folderValue", - location: "locationValue", - bucket: "bucketValue", - }; - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.folderLocationBucketPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderLocationBucketPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderLocationBucketPath', () => { - const result = client.folderLocationBucketPath("folderValue", "locationValue", "bucketValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderLocationBucketPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderLocationBucketName', () => { - const result = client.matchFolderFromFolderLocationBucketName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderLocationBucketPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromFolderLocationBucketName', () => { - const result = client.matchLocationFromFolderLocationBucketName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.folderLocationBucketPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBucketFromFolderLocationBucketName', () => { - const result = client.matchBucketFromFolderLocationBucketName(fakePath); - assert.strictEqual(result, "bucketValue"); - assert((client.pathTemplates.folderLocationBucketPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('folderLocationBucket', () => { + const fakePath = '/rendered/path/folderLocationBucket'; + const expectedParameters = { + folder: 'folderValue', + location: 'locationValue', + bucket: 'bucketValue', + }; + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.folderLocationBucketPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderLocationBucketPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderLocationBucketPath', () => { + const result = client.folderLocationBucketPath( + 'folderValue', + 'locationValue', + 'bucketValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.folderLocationBucketPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderLocationBucketName', () => { + const result = client.matchFolderFromFolderLocationBucketName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + ( + client.pathTemplates.folderLocationBucketPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromFolderLocationBucketName', () => { + const result = + client.matchLocationFromFolderLocationBucketName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + ( + client.pathTemplates.folderLocationBucketPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBucketFromFolderLocationBucketName', () => { + const result = client.matchBucketFromFolderLocationBucketName(fakePath); + assert.strictEqual(result, 'bucketValue'); + assert( + ( + client.pathTemplates.folderLocationBucketPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('folderLocationBucketView', () => { - const fakePath = "/rendered/path/folderLocationBucketView"; - const expectedParameters = { - folder: "folderValue", - location: "locationValue", - bucket: "bucketValue", - view: "viewValue", - }; - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.folderLocationBucketViewPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderLocationBucketViewPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderLocationBucketViewPath', () => { - const result = client.folderLocationBucketViewPath("folderValue", "locationValue", "bucketValue", "viewValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderLocationBucketViewPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderLocationBucketViewName', () => { - const result = client.matchFolderFromFolderLocationBucketViewName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderLocationBucketViewPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromFolderLocationBucketViewName', () => { - const result = client.matchLocationFromFolderLocationBucketViewName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.folderLocationBucketViewPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBucketFromFolderLocationBucketViewName', () => { - const result = client.matchBucketFromFolderLocationBucketViewName(fakePath); - assert.strictEqual(result, "bucketValue"); - assert((client.pathTemplates.folderLocationBucketViewPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchViewFromFolderLocationBucketViewName', () => { - const result = client.matchViewFromFolderLocationBucketViewName(fakePath); - assert.strictEqual(result, "viewValue"); - assert((client.pathTemplates.folderLocationBucketViewPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('folderLocationBucketView', () => { + const fakePath = '/rendered/path/folderLocationBucketView'; + const expectedParameters = { + folder: 'folderValue', + location: 'locationValue', + bucket: 'bucketValue', + view: 'viewValue', + }; + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.folderLocationBucketViewPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderLocationBucketViewPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderLocationBucketViewPath', () => { + const result = client.folderLocationBucketViewPath( + 'folderValue', + 'locationValue', + 'bucketValue', + 'viewValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.folderLocationBucketViewPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderLocationBucketViewName', () => { + const result = + client.matchFolderFromFolderLocationBucketViewName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + ( + client.pathTemplates.folderLocationBucketViewPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromFolderLocationBucketViewName', () => { + const result = + client.matchLocationFromFolderLocationBucketViewName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + ( + client.pathTemplates.folderLocationBucketViewPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBucketFromFolderLocationBucketViewName', () => { + const result = + client.matchBucketFromFolderLocationBucketViewName(fakePath); + assert.strictEqual(result, 'bucketValue'); + assert( + ( + client.pathTemplates.folderLocationBucketViewPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchViewFromFolderLocationBucketViewName', () => { + const result = + client.matchViewFromFolderLocationBucketViewName(fakePath); + assert.strictEqual(result, 'viewValue'); + assert( + ( + client.pathTemplates.folderLocationBucketViewPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('folderLog', () => { - const fakePath = "/rendered/path/folderLog"; - const expectedParameters = { - folder: "folderValue", - log: "logValue", - }; - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.folderLogPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderLogPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderLogPath', () => { - const result = client.folderLogPath("folderValue", "logValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderLogPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderLogName', () => { - const result = client.matchFolderFromFolderLogName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderLogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLogFromFolderLogName', () => { - const result = client.matchLogFromFolderLogName(fakePath); - assert.strictEqual(result, "logValue"); - assert((client.pathTemplates.folderLogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('folderLog', () => { + const fakePath = '/rendered/path/folderLog'; + const expectedParameters = { + folder: 'folderValue', + log: 'logValue', + }; + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.folderLogPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderLogPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderLogPath', () => { + const result = client.folderLogPath('folderValue', 'logValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.folderLogPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderLogName', () => { + const result = client.matchFolderFromFolderLogName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + (client.pathTemplates.folderLogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLogFromFolderLogName', () => { + const result = client.matchLogFromFolderLogName(fakePath); + assert.strictEqual(result, 'logValue'); + assert( + (client.pathTemplates.folderLogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('folderSettings', () => { - const fakePath = "/rendered/path/folderSettings"; - const expectedParameters = { - folder: "folderValue", - }; - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.folderSettingsPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderSettingsPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderSettingsPath', () => { - const result = client.folderSettingsPath("folderValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderSettingsPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderSettingsName', () => { - const result = client.matchFolderFromFolderSettingsName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderSettingsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('folderSettings', () => { + const fakePath = '/rendered/path/folderSettings'; + const expectedParameters = { + folder: 'folderValue', + }; + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.folderSettingsPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderSettingsPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderSettingsPath', () => { + const result = client.folderSettingsPath('folderValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.folderSettingsPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderSettingsName', () => { + const result = client.matchFolderFromFolderSettingsName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + (client.pathTemplates.folderSettingsPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('folderSink', () => { - const fakePath = "/rendered/path/folderSink"; - const expectedParameters = { - folder: "folderValue", - sink: "sinkValue", - }; - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.folderSinkPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderSinkPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderSinkPath', () => { - const result = client.folderSinkPath("folderValue", "sinkValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderSinkPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderSinkName', () => { - const result = client.matchFolderFromFolderSinkName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderSinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchSinkFromFolderSinkName', () => { - const result = client.matchSinkFromFolderSinkName(fakePath); - assert.strictEqual(result, "sinkValue"); - assert((client.pathTemplates.folderSinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('folderSink', () => { + const fakePath = '/rendered/path/folderSink'; + const expectedParameters = { + folder: 'folderValue', + sink: 'sinkValue', + }; + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.folderSinkPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderSinkPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderSinkPath', () => { + const result = client.folderSinkPath('folderValue', 'sinkValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.folderSinkPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderSinkName', () => { + const result = client.matchFolderFromFolderSinkName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + (client.pathTemplates.folderSinkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchSinkFromFolderSinkName', () => { + const result = client.matchSinkFromFolderSinkName(fakePath); + assert.strictEqual(result, 'sinkValue'); + assert( + (client.pathTemplates.folderSinkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('location', () => { - const fakePath = "/rendered/path/location"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - }; - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.locationPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.locationPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('locationPath', () => { - const result = client.locationPath("projectValue", "locationValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.locationPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromLocationName', () => { - const result = client.matchProjectFromLocationName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.locationPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromLocationName', () => { - const result = client.matchLocationFromLocationName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.locationPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('location', () => { + const fakePath = '/rendered/path/location'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + }; + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.locationPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.locationPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('locationPath', () => { + const result = client.locationPath('projectValue', 'locationValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.locationPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromLocationName', () => { + const result = client.matchProjectFromLocationName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.locationPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromLocationName', () => { + const result = client.matchLocationFromLocationName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.locationPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('logMetric', () => { - const fakePath = "/rendered/path/logMetric"; - const expectedParameters = { - project: "projectValue", - metric: "metricValue", - }; - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.logMetricPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.logMetricPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('logMetricPath', () => { - const result = client.logMetricPath("projectValue", "metricValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.logMetricPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromLogMetricName', () => { - const result = client.matchProjectFromLogMetricName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.logMetricPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchMetricFromLogMetricName', () => { - const result = client.matchMetricFromLogMetricName(fakePath); - assert.strictEqual(result, "metricValue"); - assert((client.pathTemplates.logMetricPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('logMetric', () => { + const fakePath = '/rendered/path/logMetric'; + const expectedParameters = { + project: 'projectValue', + metric: 'metricValue', + }; + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.logMetricPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.logMetricPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('logMetricPath', () => { + const result = client.logMetricPath('projectValue', 'metricValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.logMetricPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromLogMetricName', () => { + const result = client.matchProjectFromLogMetricName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.logMetricPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchMetricFromLogMetricName', () => { + const result = client.matchMetricFromLogMetricName(fakePath); + assert.strictEqual(result, 'metricValue'); + assert( + (client.pathTemplates.logMetricPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('organizationCmekSettings', () => { - const fakePath = "/rendered/path/organizationCmekSettings"; - const expectedParameters = { - organization: "organizationValue", - }; - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.organizationCmekSettingsPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationCmekSettingsPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationCmekSettingsPath', () => { - const result = client.organizationCmekSettingsPath("organizationValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationCmekSettingsPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationCmekSettingsName', () => { - const result = client.matchOrganizationFromOrganizationCmekSettingsName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationCmekSettingsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('organizationCmekSettings', () => { + const fakePath = '/rendered/path/organizationCmekSettings'; + const expectedParameters = { + organization: 'organizationValue', + }; + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.organizationCmekSettingsPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.organizationCmekSettingsPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('organizationCmekSettingsPath', () => { + const result = client.organizationCmekSettingsPath('organizationValue'); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationCmekSettingsPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationCmekSettingsName', () => { + const result = + client.matchOrganizationFromOrganizationCmekSettingsName(fakePath); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationCmekSettingsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('organizationExclusion', () => { - const fakePath = "/rendered/path/organizationExclusion"; - const expectedParameters = { - organization: "organizationValue", - exclusion: "exclusionValue", - }; - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.organizationExclusionPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationExclusionPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationExclusionPath', () => { - const result = client.organizationExclusionPath("organizationValue", "exclusionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationExclusionPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationExclusionName', () => { - const result = client.matchOrganizationFromOrganizationExclusionName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationExclusionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchExclusionFromOrganizationExclusionName', () => { - const result = client.matchExclusionFromOrganizationExclusionName(fakePath); - assert.strictEqual(result, "exclusionValue"); - assert((client.pathTemplates.organizationExclusionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('organizationExclusion', () => { + const fakePath = '/rendered/path/organizationExclusion'; + const expectedParameters = { + organization: 'organizationValue', + exclusion: 'exclusionValue', + }; + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.organizationExclusionPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.organizationExclusionPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('organizationExclusionPath', () => { + const result = client.organizationExclusionPath( + 'organizationValue', + 'exclusionValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationExclusionPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationExclusionName', () => { + const result = + client.matchOrganizationFromOrganizationExclusionName(fakePath); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationExclusionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchExclusionFromOrganizationExclusionName', () => { + const result = + client.matchExclusionFromOrganizationExclusionName(fakePath); + assert.strictEqual(result, 'exclusionValue'); + assert( + ( + client.pathTemplates.organizationExclusionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('organizationLocationBucket', () => { - const fakePath = "/rendered/path/organizationLocationBucket"; - const expectedParameters = { - organization: "organizationValue", - location: "locationValue", - bucket: "bucketValue", - }; - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.organizationLocationBucketPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationLocationBucketPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationLocationBucketPath', () => { - const result = client.organizationLocationBucketPath("organizationValue", "locationValue", "bucketValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationLocationBucketPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationLocationBucketName', () => { - const result = client.matchOrganizationFromOrganizationLocationBucketName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationLocationBucketPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromOrganizationLocationBucketName', () => { - const result = client.matchLocationFromOrganizationLocationBucketName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.organizationLocationBucketPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBucketFromOrganizationLocationBucketName', () => { - const result = client.matchBucketFromOrganizationLocationBucketName(fakePath); - assert.strictEqual(result, "bucketValue"); - assert((client.pathTemplates.organizationLocationBucketPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('organizationLocationBucket', () => { + const fakePath = '/rendered/path/organizationLocationBucket'; + const expectedParameters = { + organization: 'organizationValue', + location: 'locationValue', + bucket: 'bucketValue', + }; + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.organizationLocationBucketPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.organizationLocationBucketPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('organizationLocationBucketPath', () => { + const result = client.organizationLocationBucketPath( + 'organizationValue', + 'locationValue', + 'bucketValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationLocationBucketPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationLocationBucketName', () => { + const result = + client.matchOrganizationFromOrganizationLocationBucketName(fakePath); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationLocationBucketPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromOrganizationLocationBucketName', () => { + const result = + client.matchLocationFromOrganizationLocationBucketName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + ( + client.pathTemplates.organizationLocationBucketPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBucketFromOrganizationLocationBucketName', () => { + const result = + client.matchBucketFromOrganizationLocationBucketName(fakePath); + assert.strictEqual(result, 'bucketValue'); + assert( + ( + client.pathTemplates.organizationLocationBucketPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('organizationLocationBucketView', () => { - const fakePath = "/rendered/path/organizationLocationBucketView"; - const expectedParameters = { - organization: "organizationValue", - location: "locationValue", - bucket: "bucketValue", - view: "viewValue", - }; - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.organizationLocationBucketViewPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationLocationBucketViewPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationLocationBucketViewPath', () => { - const result = client.organizationLocationBucketViewPath("organizationValue", "locationValue", "bucketValue", "viewValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationLocationBucketViewPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationLocationBucketViewName', () => { - const result = client.matchOrganizationFromOrganizationLocationBucketViewName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationLocationBucketViewPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromOrganizationLocationBucketViewName', () => { - const result = client.matchLocationFromOrganizationLocationBucketViewName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.organizationLocationBucketViewPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBucketFromOrganizationLocationBucketViewName', () => { - const result = client.matchBucketFromOrganizationLocationBucketViewName(fakePath); - assert.strictEqual(result, "bucketValue"); - assert((client.pathTemplates.organizationLocationBucketViewPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchViewFromOrganizationLocationBucketViewName', () => { - const result = client.matchViewFromOrganizationLocationBucketViewName(fakePath); - assert.strictEqual(result, "viewValue"); - assert((client.pathTemplates.organizationLocationBucketViewPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('organizationLocationBucketView', () => { + const fakePath = '/rendered/path/organizationLocationBucketView'; + const expectedParameters = { + organization: 'organizationValue', + location: 'locationValue', + bucket: 'bucketValue', + view: 'viewValue', + }; + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.organizationLocationBucketViewPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.organizationLocationBucketViewPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('organizationLocationBucketViewPath', () => { + const result = client.organizationLocationBucketViewPath( + 'organizationValue', + 'locationValue', + 'bucketValue', + 'viewValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationLocationBucketViewPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationLocationBucketViewName', () => { + const result = + client.matchOrganizationFromOrganizationLocationBucketViewName( + fakePath, + ); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationLocationBucketViewPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromOrganizationLocationBucketViewName', () => { + const result = + client.matchLocationFromOrganizationLocationBucketViewName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + ( + client.pathTemplates.organizationLocationBucketViewPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBucketFromOrganizationLocationBucketViewName', () => { + const result = + client.matchBucketFromOrganizationLocationBucketViewName(fakePath); + assert.strictEqual(result, 'bucketValue'); + assert( + ( + client.pathTemplates.organizationLocationBucketViewPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchViewFromOrganizationLocationBucketViewName', () => { + const result = + client.matchViewFromOrganizationLocationBucketViewName(fakePath); + assert.strictEqual(result, 'viewValue'); + assert( + ( + client.pathTemplates.organizationLocationBucketViewPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('organizationLog', () => { - const fakePath = "/rendered/path/organizationLog"; - const expectedParameters = { - organization: "organizationValue", - log: "logValue", - }; - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.organizationLogPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationLogPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationLogPath', () => { - const result = client.organizationLogPath("organizationValue", "logValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationLogPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationLogName', () => { - const result = client.matchOrganizationFromOrganizationLogName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationLogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLogFromOrganizationLogName', () => { - const result = client.matchLogFromOrganizationLogName(fakePath); - assert.strictEqual(result, "logValue"); - assert((client.pathTemplates.organizationLogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('organizationLog', () => { + const fakePath = '/rendered/path/organizationLog'; + const expectedParameters = { + organization: 'organizationValue', + log: 'logValue', + }; + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.organizationLogPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.organizationLogPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('organizationLogPath', () => { + const result = client.organizationLogPath( + 'organizationValue', + 'logValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.organizationLogPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationLogName', () => { + const result = + client.matchOrganizationFromOrganizationLogName(fakePath); + assert.strictEqual(result, 'organizationValue'); + assert( + (client.pathTemplates.organizationLogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLogFromOrganizationLogName', () => { + const result = client.matchLogFromOrganizationLogName(fakePath); + assert.strictEqual(result, 'logValue'); + assert( + (client.pathTemplates.organizationLogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('organizationSettings', () => { - const fakePath = "/rendered/path/organizationSettings"; - const expectedParameters = { - organization: "organizationValue", - }; - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.organizationSettingsPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationSettingsPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationSettingsPath', () => { - const result = client.organizationSettingsPath("organizationValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationSettingsPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationSettingsName', () => { - const result = client.matchOrganizationFromOrganizationSettingsName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationSettingsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('organizationSettings', () => { + const fakePath = '/rendered/path/organizationSettings'; + const expectedParameters = { + organization: 'organizationValue', + }; + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.organizationSettingsPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.organizationSettingsPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('organizationSettingsPath', () => { + const result = client.organizationSettingsPath('organizationValue'); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationSettingsPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationSettingsName', () => { + const result = + client.matchOrganizationFromOrganizationSettingsName(fakePath); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationSettingsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('organizationSink', () => { - const fakePath = "/rendered/path/organizationSink"; - const expectedParameters = { - organization: "organizationValue", - sink: "sinkValue", - }; - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.organizationSinkPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationSinkPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationSinkPath', () => { - const result = client.organizationSinkPath("organizationValue", "sinkValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationSinkPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationSinkName', () => { - const result = client.matchOrganizationFromOrganizationSinkName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationSinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchSinkFromOrganizationSinkName', () => { - const result = client.matchSinkFromOrganizationSinkName(fakePath); - assert.strictEqual(result, "sinkValue"); - assert((client.pathTemplates.organizationSinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('organizationSink', () => { + const fakePath = '/rendered/path/organizationSink'; + const expectedParameters = { + organization: 'organizationValue', + sink: 'sinkValue', + }; + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.organizationSinkPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.organizationSinkPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('organizationSinkPath', () => { + const result = client.organizationSinkPath( + 'organizationValue', + 'sinkValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationSinkPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationSinkName', () => { + const result = + client.matchOrganizationFromOrganizationSinkName(fakePath); + assert.strictEqual(result, 'organizationValue'); + assert( + (client.pathTemplates.organizationSinkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchSinkFromOrganizationSinkName', () => { + const result = client.matchSinkFromOrganizationSinkName(fakePath); + assert.strictEqual(result, 'sinkValue'); + assert( + (client.pathTemplates.organizationSinkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('project', () => { - const fakePath = "/rendered/path/project"; - const expectedParameters = { - project: "projectValue", - }; - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.projectPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectPath', () => { - const result = client.projectPath("projectValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectName', () => { - const result = client.matchProjectFromProjectName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('project', () => { + const fakePath = '/rendered/path/project'; + const expectedParameters = { + project: 'projectValue', + }; + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.projectPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectPath', () => { + const result = client.projectPath('projectValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.projectPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectName', () => { + const result = client.matchProjectFromProjectName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.projectPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectCmekSettings', () => { - const fakePath = "/rendered/path/projectCmekSettings"; - const expectedParameters = { - project: "projectValue", - }; - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.projectCmekSettingsPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectCmekSettingsPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectCmekSettingsPath', () => { - const result = client.projectCmekSettingsPath("projectValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectCmekSettingsPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectCmekSettingsName', () => { - const result = client.matchProjectFromProjectCmekSettingsName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectCmekSettingsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectCmekSettings', () => { + const fakePath = '/rendered/path/projectCmekSettings'; + const expectedParameters = { + project: 'projectValue', + }; + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.projectCmekSettingsPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectCmekSettingsPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectCmekSettingsPath', () => { + const result = client.projectCmekSettingsPath('projectValue'); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.projectCmekSettingsPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectCmekSettingsName', () => { + const result = client.matchProjectFromProjectCmekSettingsName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.projectCmekSettingsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectExclusion', () => { - const fakePath = "/rendered/path/projectExclusion"; - const expectedParameters = { - project: "projectValue", - exclusion: "exclusionValue", - }; - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.projectExclusionPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectExclusionPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectExclusionPath', () => { - const result = client.projectExclusionPath("projectValue", "exclusionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectExclusionPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectExclusionName', () => { - const result = client.matchProjectFromProjectExclusionName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectExclusionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchExclusionFromProjectExclusionName', () => { - const result = client.matchExclusionFromProjectExclusionName(fakePath); - assert.strictEqual(result, "exclusionValue"); - assert((client.pathTemplates.projectExclusionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectExclusion', () => { + const fakePath = '/rendered/path/projectExclusion'; + const expectedParameters = { + project: 'projectValue', + exclusion: 'exclusionValue', + }; + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.projectExclusionPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectExclusionPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectExclusionPath', () => { + const result = client.projectExclusionPath( + 'projectValue', + 'exclusionValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.projectExclusionPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectExclusionName', () => { + const result = client.matchProjectFromProjectExclusionName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.projectExclusionPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchExclusionFromProjectExclusionName', () => { + const result = client.matchExclusionFromProjectExclusionName(fakePath); + assert.strictEqual(result, 'exclusionValue'); + assert( + (client.pathTemplates.projectExclusionPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectLocationBucket', () => { - const fakePath = "/rendered/path/projectLocationBucket"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - bucket: "bucketValue", - }; - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.projectLocationBucketPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectLocationBucketPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectLocationBucketPath', () => { - const result = client.projectLocationBucketPath("projectValue", "locationValue", "bucketValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectLocationBucketPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectLocationBucketName', () => { - const result = client.matchProjectFromProjectLocationBucketName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectLocationBucketPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromProjectLocationBucketName', () => { - const result = client.matchLocationFromProjectLocationBucketName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.projectLocationBucketPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBucketFromProjectLocationBucketName', () => { - const result = client.matchBucketFromProjectLocationBucketName(fakePath); - assert.strictEqual(result, "bucketValue"); - assert((client.pathTemplates.projectLocationBucketPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectLocationBucket', () => { + const fakePath = '/rendered/path/projectLocationBucket'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + bucket: 'bucketValue', + }; + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.projectLocationBucketPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectLocationBucketPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectLocationBucketPath', () => { + const result = client.projectLocationBucketPath( + 'projectValue', + 'locationValue', + 'bucketValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.projectLocationBucketPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectLocationBucketName', () => { + const result = + client.matchProjectFromProjectLocationBucketName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.projectLocationBucketPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromProjectLocationBucketName', () => { + const result = + client.matchLocationFromProjectLocationBucketName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + ( + client.pathTemplates.projectLocationBucketPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBucketFromProjectLocationBucketName', () => { + const result = + client.matchBucketFromProjectLocationBucketName(fakePath); + assert.strictEqual(result, 'bucketValue'); + assert( + ( + client.pathTemplates.projectLocationBucketPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectLocationBucketView', () => { - const fakePath = "/rendered/path/projectLocationBucketView"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - bucket: "bucketValue", - view: "viewValue", - }; - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.projectLocationBucketViewPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectLocationBucketViewPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectLocationBucketViewPath', () => { - const result = client.projectLocationBucketViewPath("projectValue", "locationValue", "bucketValue", "viewValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectLocationBucketViewPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectLocationBucketViewName', () => { - const result = client.matchProjectFromProjectLocationBucketViewName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectLocationBucketViewPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromProjectLocationBucketViewName', () => { - const result = client.matchLocationFromProjectLocationBucketViewName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.projectLocationBucketViewPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBucketFromProjectLocationBucketViewName', () => { - const result = client.matchBucketFromProjectLocationBucketViewName(fakePath); - assert.strictEqual(result, "bucketValue"); - assert((client.pathTemplates.projectLocationBucketViewPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchViewFromProjectLocationBucketViewName', () => { - const result = client.matchViewFromProjectLocationBucketViewName(fakePath); - assert.strictEqual(result, "viewValue"); - assert((client.pathTemplates.projectLocationBucketViewPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectLocationBucketView', () => { + const fakePath = '/rendered/path/projectLocationBucketView'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + bucket: 'bucketValue', + view: 'viewValue', + }; + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.projectLocationBucketViewPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectLocationBucketViewPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectLocationBucketViewPath', () => { + const result = client.projectLocationBucketViewPath( + 'projectValue', + 'locationValue', + 'bucketValue', + 'viewValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.projectLocationBucketViewPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectLocationBucketViewName', () => { + const result = + client.matchProjectFromProjectLocationBucketViewName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.projectLocationBucketViewPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromProjectLocationBucketViewName', () => { + const result = + client.matchLocationFromProjectLocationBucketViewName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + ( + client.pathTemplates.projectLocationBucketViewPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBucketFromProjectLocationBucketViewName', () => { + const result = + client.matchBucketFromProjectLocationBucketViewName(fakePath); + assert.strictEqual(result, 'bucketValue'); + assert( + ( + client.pathTemplates.projectLocationBucketViewPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchViewFromProjectLocationBucketViewName', () => { + const result = + client.matchViewFromProjectLocationBucketViewName(fakePath); + assert.strictEqual(result, 'viewValue'); + assert( + ( + client.pathTemplates.projectLocationBucketViewPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectLog', () => { - const fakePath = "/rendered/path/projectLog"; - const expectedParameters = { - project: "projectValue", - log: "logValue", - }; - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.projectLogPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectLogPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectLogPath', () => { - const result = client.projectLogPath("projectValue", "logValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectLogPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectLogName', () => { - const result = client.matchProjectFromProjectLogName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectLogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLogFromProjectLogName', () => { - const result = client.matchLogFromProjectLogName(fakePath); - assert.strictEqual(result, "logValue"); - assert((client.pathTemplates.projectLogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectLog', () => { + const fakePath = '/rendered/path/projectLog'; + const expectedParameters = { + project: 'projectValue', + log: 'logValue', + }; + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.projectLogPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectLogPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectLogPath', () => { + const result = client.projectLogPath('projectValue', 'logValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.projectLogPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectLogName', () => { + const result = client.matchProjectFromProjectLogName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.projectLogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLogFromProjectLogName', () => { + const result = client.matchLogFromProjectLogName(fakePath); + assert.strictEqual(result, 'logValue'); + assert( + (client.pathTemplates.projectLogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectSettings', () => { - const fakePath = "/rendered/path/projectSettings"; - const expectedParameters = { - project: "projectValue", - }; - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.projectSettingsPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectSettingsPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectSettingsPath', () => { - const result = client.projectSettingsPath("projectValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectSettingsPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectSettingsName', () => { - const result = client.matchProjectFromProjectSettingsName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectSettingsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectSettings', () => { + const fakePath = '/rendered/path/projectSettings'; + const expectedParameters = { + project: 'projectValue', + }; + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.projectSettingsPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectSettingsPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectSettingsPath', () => { + const result = client.projectSettingsPath('projectValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.projectSettingsPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectSettingsName', () => { + const result = client.matchProjectFromProjectSettingsName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.projectSettingsPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectSink', () => { - const fakePath = "/rendered/path/projectSink"; - const expectedParameters = { - project: "projectValue", - sink: "sinkValue", - }; - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.projectSinkPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectSinkPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectSinkPath', () => { - const result = client.projectSinkPath("projectValue", "sinkValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectSinkPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectSinkName', () => { - const result = client.matchProjectFromProjectSinkName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectSinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchSinkFromProjectSinkName', () => { - const result = client.matchSinkFromProjectSinkName(fakePath); - assert.strictEqual(result, "sinkValue"); - assert((client.pathTemplates.projectSinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectSink', () => { + const fakePath = '/rendered/path/projectSink'; + const expectedParameters = { + project: 'projectValue', + sink: 'sinkValue', + }; + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.projectSinkPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectSinkPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectSinkPath', () => { + const result = client.projectSinkPath('projectValue', 'sinkValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.projectSinkPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectSinkName', () => { + const result = client.matchProjectFromProjectSinkName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.projectSinkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchSinkFromProjectSinkName', () => { + const result = client.matchSinkFromProjectSinkName(fakePath); + assert.strictEqual(result, 'sinkValue'); + assert( + (client.pathTemplates.projectSinkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/core/generator/gapic-generator-typescript/baselines/logging-esm/esm/test/gapic_logging_service_v2_v2.ts.baseline b/core/generator/gapic-generator-typescript/baselines/logging-esm/esm/test/gapic_logging_service_v2_v2.ts.baseline index 2efb4ccb6716..9eaf3008a67f 100644 --- a/core/generator/gapic-generator-typescript/baselines/logging-esm/esm/test/gapic_logging_service_v2_v2.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/logging-esm/esm/test/gapic_logging_service_v2_v2.ts.baseline @@ -20,16 +20,16 @@ import * as protos from '../../protos/protos.js'; import assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as loggingservicev2Module from '../src/index.js'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; -import {protobuf} from 'google-gax'; +import { protobuf } from 'google-gax'; import fs from 'fs'; import path from 'path'; -import {fileURLToPath} from 'url'; +import { fileURLToPath } from 'url'; // @ts-ignore const dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -37,2236 +37,3188 @@ const dirname = path.dirname(fileURLToPath(import.meta.url)); // to fill in default values for request objects const root = protobuf.Root.fromJSON( JSON.parse( - fs.readFileSync(path.join(dirname, '..', '..', 'protos/protos.json'), 'utf8') - )) + fs.readFileSync( + path.join(dirname, '..', '..', 'protos/protos.json'), + 'utf8', + ), + ), +); // eslint-disable-next-line @typescript-eslint/no-unused-vars function getTypeDefaultValue(typeName: string, fields: string[]) { - let type = root.lookupType(typeName) as protobuf.Type; - for (const field of fields.slice(0, -1)) { - type = type?.fields[field]?.resolvedType as protobuf.Type; - } - return type?.fields[fields[fields.length - 1]]?.defaultValue ?? null; + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type?.fields[field]?.resolvedType as protobuf.Type; + } + return type?.fields[fields[fields.length - 1]]?.defaultValue ?? null; } function generateSampleMessage(instance: T) { - const filledObject = (instance.constructor as typeof protobuf.Message) - .toObject(instance as protobuf.Message, {defaults: true}); - return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, { defaults: true }); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; } function stubSimpleCall(response?: ResponseType, error?: Error) { - return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); } -function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { - return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +function stubSimpleCallWithCallback( + response?: ResponseType, + error?: Error, +) { + return error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); } -function stubBidiStreamingCall(response?: ResponseType, error?: Error) { - const transformStub = error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); - const mockStream = new PassThrough({ - objectMode: true, - transform: transformStub, - }); - return sinon.stub().returns(mockStream); +function stubBidiStreamingCall( + response?: ResponseType, + error?: Error, +) { + const transformStub = error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + return sinon.stub().returns(mockStream); } -function stubPageStreamingCall(responses?: ResponseType[], error?: Error) { - const pagingStub = sinon.stub(); - if (responses) { - for (let i = 0; i < responses.length; ++i) { - pagingStub.onCall(i).callsArgWith(2, null, responses[i]); - } +function stubPageStreamingCall( + responses?: ResponseType[], + error?: Error, +) { + const pagingStub = sinon.stub(); + if (responses) { + for (let i = 0; i < responses.length; ++i) { + pagingStub.onCall(i).callsArgWith(2, null, responses[i]); } - const transformStub = error ? sinon.stub().callsArgWith(2, error) : pagingStub; - const mockStream = new PassThrough({ - objectMode: true, - transform: transformStub, - }); - // trigger as many responses as needed - if (responses) { - for (let i = 0; i < responses.length; ++i) { - setImmediate(() => { mockStream.write({}); }); - } - setImmediate(() => { mockStream.end(); }); - } else { - setImmediate(() => { mockStream.write({}); }); - setImmediate(() => { mockStream.end(); }); + } + const transformStub = error + ? sinon.stub().callsArgWith(2, error) + : pagingStub; + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + // trigger as many responses as needed + if (responses) { + for (let i = 0; i < responses.length; ++i) { + setImmediate(() => { + mockStream.write({}); + }); } - return sinon.stub().returns(mockStream); + setImmediate(() => { + mockStream.end(); + }); + } else { + setImmediate(() => { + mockStream.write({}); + }); + setImmediate(() => { + mockStream.end(); + }); + } + return sinon.stub().returns(mockStream); } -function stubAsyncIterationCall(responses?: ResponseType[], error?: Error) { - let counter = 0; - const asyncIterable = { - [Symbol.asyncIterator]() { - return { - async next() { - if (error) { - return Promise.reject(error); - } - if (counter >= responses!.length) { - return Promise.resolve({done: true, value: undefined}); - } - return Promise.resolve({done: false, value: responses![counter++]}); - } - }; - } - }; - return sinon.stub().returns(asyncIterable); +function stubAsyncIterationCall( + responses?: ResponseType[], + error?: Error, +) { + let counter = 0; + const asyncIterable = { + [Symbol.asyncIterator]() { + return { + async next() { + if (error) { + return Promise.reject(error); + } + if (counter >= responses!.length) { + return Promise.resolve({ done: true, value: undefined }); + } + return Promise.resolve({ done: false, value: responses![counter++] }); + }, + }; + }, + }; + return sinon.stub().returns(asyncIterable); } describe('v2.LoggingServiceV2Client', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new loggingservicev2Module.v2.LoggingServiceV2Client(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'logging.googleapis.com'); - }); - - it('has universeDomain', () => { - const client = new loggingservicev2Module.v2.LoggingServiceV2Client(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); - - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - it('throws DeprecationWarning if static servicePath is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const servicePath = loggingservicev2Module.v2.LoggingServiceV2Client.servicePath; - assert.strictEqual(servicePath, 'logging.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = loggingservicev2Module.v2.LoggingServiceV2Client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'logging.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'logging.example.com'); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new loggingservicev2Module.v2.LoggingServiceV2Client(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'logging.googleapis.com'); + }); - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'logging.example.com'); - }); + it('has universeDomain', () => { + const client = new loggingservicev2Module.v2.LoggingServiceV2Client(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - if (typeof process === 'object' && 'env' in process) { - describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { - it('sets apiEndpoint from environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new loggingservicev2Module.v2.LoggingServiceV2Client(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'logging.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - - it('value configured in code has priority over environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'logging.configured.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { new loggingservicev2Module.v2.LoggingServiceV2Client({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = + loggingservicev2Module.v2.LoggingServiceV2Client.servicePath; + assert.strictEqual(servicePath, 'logging.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + loggingservicev2Module.v2.LoggingServiceV2Client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'logging.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + universeDomain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'logging.example.com'); + }); - it('has port', () => { - const port = loggingservicev2Module.v2.LoggingServiceV2Client.port; - assert(port); - assert(typeof port === 'number'); - }); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + universe_domain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'logging.example.com'); + }); - it('should create a client with no option', () => { - const client = new loggingservicev2Module.v2.LoggingServiceV2Client(); - assert(client); + if (typeof process === 'object' && 'env' in process) { + describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { + it('sets apiEndpoint from environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new loggingservicev2Module.v2.LoggingServiceV2Client(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'logging.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } + }); + + it('value configured in code has priority over environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + universeDomain: 'configured.example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'logging.configured.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } + }); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new loggingservicev2Module.v2.LoggingServiceV2Client({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); + }); - it('should create a client with gRPC fallback', () => { - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - fallback: true, - }); - assert(client); - }); + it('has port', () => { + const port = loggingservicev2Module.v2.LoggingServiceV2Client.port; + assert(port); + assert(typeof port === 'number'); + }); - it('has initialize method and supports deferred initialization', async () => { - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.loggingServiceV2Stub, undefined); - await client.initialize(); - assert(client.loggingServiceV2Stub); - }); + it('should create a client with no option', () => { + const client = new loggingservicev2Module.v2.LoggingServiceV2Client(); + assert(client); + }); - it('has close method for the initialized client', done => { - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.loggingServiceV2Stub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('should create a client with gRPC fallback', () => { + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + fallback: true, + }); + assert(client); + }); - it('has close method for the non-initialized client', done => { - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.loggingServiceV2Stub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('has initialize method and supports deferred initialization', async () => { + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.loggingServiceV2Stub, undefined); + await client.initialize(); + assert(client.loggingServiceV2Stub); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + it('has close method for the initialized client', (done) => { + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.loggingServiceV2Stub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId((err?: Error|null, projectId?: string|null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } - }); - }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); + it('has close method for the non-initialized client', (done) => { + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.loggingServiceV2Stub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); }); - describe('deleteLog', () => { - it('invokes deleteLog without error', async () => { - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.DeleteLogRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.DeleteLogRequest', ['logName']); - request.logName = defaultValue1; - const expectedHeaderRequestParams = `log_name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteLog = stubSimpleCall(expectedResponse); - const [response] = await client.deleteLog(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteLog as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteLog as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + }); - it('invokes deleteLog without error using callback', async () => { - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.DeleteLogRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.DeleteLogRequest', ['logName']); - request.logName = defaultValue1; - const expectedHeaderRequestParams = `log_name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteLog = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteLog( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteLog as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteLog as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } + }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + }); + + describe('deleteLog', () => { + it('invokes deleteLog without error', async () => { + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.DeleteLogRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.DeleteLogRequest', + ['logName'], + ); + request.logName = defaultValue1; + const expectedHeaderRequestParams = `log_name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteLog = stubSimpleCall(expectedResponse); + const [response] = await client.deleteLog(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteLog as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteLog as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteLog with error', async () => { - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.DeleteLogRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.DeleteLogRequest', ['logName']); - request.logName = defaultValue1; - const expectedHeaderRequestParams = `log_name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteLog = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteLog(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteLog as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteLog as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteLog without error using callback', async () => { + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.DeleteLogRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.DeleteLogRequest', + ['logName'], + ); + request.logName = defaultValue1; + const expectedHeaderRequestParams = `log_name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteLog = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteLog( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteLog as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteLog as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteLog with closed client', async () => { - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.DeleteLogRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.DeleteLogRequest', ['logName']); - request.logName = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteLog(request), expectedError); - }); + it('invokes deleteLog with error', async () => { + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.DeleteLogRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.DeleteLogRequest', + ['logName'], + ); + request.logName = defaultValue1; + const expectedHeaderRequestParams = `log_name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteLog = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.deleteLog(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteLog as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteLog as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('writeLogEntries', () => { - it('invokes writeLogEntries without error', async () => { - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.WriteLogEntriesRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.logging.v2.WriteLogEntriesResponse() - ); - client.innerApiCalls.writeLogEntries = stubSimpleCall(expectedResponse); - const [response] = await client.writeLogEntries(request); - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes deleteLog with closed client', async () => { + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.DeleteLogRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.DeleteLogRequest', + ['logName'], + ); + request.logName = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.deleteLog(request), expectedError); + }); + }); + + describe('writeLogEntries', () => { + it('invokes writeLogEntries without error', async () => { + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.WriteLogEntriesRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.logging.v2.WriteLogEntriesResponse(), + ); + client.innerApiCalls.writeLogEntries = stubSimpleCall(expectedResponse); + const [response] = await client.writeLogEntries(request); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes writeLogEntries without error using callback', async () => { - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.WriteLogEntriesRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.logging.v2.WriteLogEntriesResponse() - ); - client.innerApiCalls.writeLogEntries = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.writeLogEntries( - request, - (err?: Error|null, result?: protos.google.logging.v2.IWriteLogEntriesResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes writeLogEntries without error using callback', async () => { + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.WriteLogEntriesRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.logging.v2.WriteLogEntriesResponse(), + ); + client.innerApiCalls.writeLogEntries = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.writeLogEntries( + request, + ( + err?: Error | null, + result?: protos.google.logging.v2.IWriteLogEntriesResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes writeLogEntries with error', async () => { - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.WriteLogEntriesRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.writeLogEntries = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.writeLogEntries(request), expectedError); - }); + it('invokes writeLogEntries with error', async () => { + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.WriteLogEntriesRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.writeLogEntries = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.writeLogEntries(request), expectedError); + }); - it('invokes writeLogEntries with closed client', async () => { - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.WriteLogEntriesRequest() - ); - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.writeLogEntries(request), expectedError); - }); + it('invokes writeLogEntries with closed client', async () => { + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.WriteLogEntriesRequest(), + ); + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.writeLogEntries(request), expectedError); + }); + }); + + describe('tailLogEntries', () => { + it('invokes tailLogEntries without error', async () => { + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.TailLogEntriesRequest(), + ); + + const expectedResponse = generateSampleMessage( + new protos.google.logging.v2.TailLogEntriesResponse(), + ); + client.innerApiCalls.tailLogEntries = + stubBidiStreamingCall(expectedResponse); + const stream = client.tailLogEntries(); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + (response: protos.google.logging.v2.TailLogEntriesResponse) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); + }); + stream.write(request); + stream.end(); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + assert( + (client.innerApiCalls.tailLogEntries as SinonStub) + .getCall(0) + .calledWith(null), + ); + assert.deepStrictEqual( + ((stream as unknown as PassThrough)._transform as SinonStub).getCall(0) + .args[0], + request, + ); }); - describe('tailLogEntries', () => { - it('invokes tailLogEntries without error', async () => { - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.TailLogEntriesRequest() - ); - - const expectedResponse = generateSampleMessage( - new protos.google.logging.v2.TailLogEntriesResponse() - ); - client.innerApiCalls.tailLogEntries = stubBidiStreamingCall(expectedResponse); - const stream = client.tailLogEntries(); - const promise = new Promise((resolve, reject) => { - stream.on('data', (response: protos.google.logging.v2.TailLogEntriesResponse) => { - resolve(response); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - stream.write(request); - stream.end(); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - assert((client.innerApiCalls.tailLogEntries as SinonStub) - .getCall(0).calledWith(null)); - assert.deepStrictEqual(((stream as unknown as PassThrough) - ._transform as SinonStub).getCall(0).args[0], request); - }); + it('invokes tailLogEntries with error', async () => { + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.TailLogEntriesRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.tailLogEntries = stubBidiStreamingCall( + undefined, + expectedError, + ); + const stream = client.tailLogEntries(); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + (response: protos.google.logging.v2.TailLogEntriesResponse) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); + }); + stream.write(request); + stream.end(); + }); + await assert.rejects(promise, expectedError); + assert( + (client.innerApiCalls.tailLogEntries as SinonStub) + .getCall(0) + .calledWith(null), + ); + assert.deepStrictEqual( + ((stream as unknown as PassThrough)._transform as SinonStub).getCall(0) + .args[0], + request, + ); + }); + }); + + describe('listLogEntries', () => { + it('invokes listLogEntries without error', async () => { + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.ListLogEntriesRequest(), + ); + const expectedResponse = [ + generateSampleMessage(new protos.google.logging.v2.LogEntry()), + generateSampleMessage(new protos.google.logging.v2.LogEntry()), + generateSampleMessage(new protos.google.logging.v2.LogEntry()), + ]; + client.innerApiCalls.listLogEntries = stubSimpleCall(expectedResponse); + const [response] = await client.listLogEntries(request); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes tailLogEntries with error', async () => { - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.TailLogEntriesRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.tailLogEntries = stubBidiStreamingCall(undefined, expectedError); - const stream = client.tailLogEntries(); - const promise = new Promise((resolve, reject) => { - stream.on('data', (response: protos.google.logging.v2.TailLogEntriesResponse) => { - resolve(response); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - stream.write(request); - stream.end(); - }); - await assert.rejects(promise, expectedError); - assert((client.innerApiCalls.tailLogEntries as SinonStub) - .getCall(0).calledWith(null)); - assert.deepStrictEqual(((stream as unknown as PassThrough) - ._transform as SinonStub).getCall(0).args[0], request); - }); + it('invokes listLogEntries without error using callback', async () => { + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.ListLogEntriesRequest(), + ); + const expectedResponse = [ + generateSampleMessage(new protos.google.logging.v2.LogEntry()), + generateSampleMessage(new protos.google.logging.v2.LogEntry()), + generateSampleMessage(new protos.google.logging.v2.LogEntry()), + ]; + client.innerApiCalls.listLogEntries = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listLogEntries( + request, + ( + err?: Error | null, + result?: protos.google.logging.v2.ILogEntry[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); }); - describe('listLogEntries', () => { - it('invokes listLogEntries without error', async () => { - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.ListLogEntriesRequest() - );const expectedResponse = [ - generateSampleMessage(new protos.google.logging.v2.LogEntry()), - generateSampleMessage(new protos.google.logging.v2.LogEntry()), - generateSampleMessage(new protos.google.logging.v2.LogEntry()), - ]; - client.innerApiCalls.listLogEntries = stubSimpleCall(expectedResponse); - const [response] = await client.listLogEntries(request); - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes listLogEntries with error', async () => { + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.ListLogEntriesRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.listLogEntries = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listLogEntries(request), expectedError); + }); - it('invokes listLogEntries without error using callback', async () => { - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.ListLogEntriesRequest() - );const expectedResponse = [ - generateSampleMessage(new protos.google.logging.v2.LogEntry()), - generateSampleMessage(new protos.google.logging.v2.LogEntry()), - generateSampleMessage(new protos.google.logging.v2.LogEntry()), - ]; - client.innerApiCalls.listLogEntries = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listLogEntries( - request, - (err?: Error|null, result?: protos.google.logging.v2.ILogEntry[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes listLogEntriesStream without error', async () => { + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.ListLogEntriesRequest(), + ); + const expectedResponse = [ + generateSampleMessage(new protos.google.logging.v2.LogEntry()), + generateSampleMessage(new protos.google.logging.v2.LogEntry()), + generateSampleMessage(new protos.google.logging.v2.LogEntry()), + ]; + client.descriptors.page.listLogEntries.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listLogEntriesStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.logging.v2.LogEntry[] = []; + stream.on('data', (response: protos.google.logging.v2.LogEntry) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listLogEntries.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listLogEntries, request), + ); + }); - it('invokes listLogEntries with error', async () => { - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.ListLogEntriesRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.listLogEntries = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listLogEntries(request), expectedError); - }); + it('invokes listLogEntriesStream with error', async () => { + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.ListLogEntriesRequest(), + ); + const expectedError = new Error('expected'); + client.descriptors.page.listLogEntries.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listLogEntriesStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.logging.v2.LogEntry[] = []; + stream.on('data', (response: protos.google.logging.v2.LogEntry) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listLogEntries.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listLogEntries, request), + ); + }); - it('invokes listLogEntriesStream without error', async () => { - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.ListLogEntriesRequest() - ); - const expectedResponse = [ - generateSampleMessage(new protos.google.logging.v2.LogEntry()), - generateSampleMessage(new protos.google.logging.v2.LogEntry()), - generateSampleMessage(new protos.google.logging.v2.LogEntry()), - ]; - client.descriptors.page.listLogEntries.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listLogEntriesStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.logging.v2.LogEntry[] = []; - stream.on('data', (response: protos.google.logging.v2.LogEntry) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.listLogEntries.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listLogEntries, request)); - }); + it('uses async iteration with listLogEntries without error', async () => { + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.ListLogEntriesRequest(), + ); + const expectedResponse = [ + generateSampleMessage(new protos.google.logging.v2.LogEntry()), + generateSampleMessage(new protos.google.logging.v2.LogEntry()), + generateSampleMessage(new protos.google.logging.v2.LogEntry()), + ]; + client.descriptors.page.listLogEntries.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.logging.v2.ILogEntry[] = []; + const iterable = client.listLogEntriesAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listLogEntries.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + }); - it('invokes listLogEntriesStream with error', async () => { - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.ListLogEntriesRequest() - ); - const expectedError = new Error('expected'); - client.descriptors.page.listLogEntries.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listLogEntriesStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.logging.v2.LogEntry[] = []; - stream.on('data', (response: protos.google.logging.v2.LogEntry) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listLogEntries.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listLogEntries, request)); - }); + it('uses async iteration with listLogEntries with error', async () => { + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.ListLogEntriesRequest(), + ); + const expectedError = new Error('expected'); + client.descriptors.page.listLogEntries.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listLogEntriesAsync(request); + await assert.rejects(async () => { + const responses: protos.google.logging.v2.ILogEntry[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listLogEntries.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + }); + }); + + describe('listMonitoredResourceDescriptors', () => { + it('invokes listMonitoredResourceDescriptors without error', async () => { + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.ListMonitoredResourceDescriptorsRequest(), + ); + const expectedResponse = [ + generateSampleMessage( + new protos.google.api.MonitoredResourceDescriptor(), + ), + generateSampleMessage( + new protos.google.api.MonitoredResourceDescriptor(), + ), + generateSampleMessage( + new protos.google.api.MonitoredResourceDescriptor(), + ), + ]; + client.innerApiCalls.listMonitoredResourceDescriptors = + stubSimpleCall(expectedResponse); + const [response] = await client.listMonitoredResourceDescriptors(request); + assert.deepStrictEqual(response, expectedResponse); + }); - it('uses async iteration with listLogEntries without error', async () => { - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.ListLogEntriesRequest() - ); - const expectedResponse = [ - generateSampleMessage(new protos.google.logging.v2.LogEntry()), - generateSampleMessage(new protos.google.logging.v2.LogEntry()), - generateSampleMessage(new protos.google.logging.v2.LogEntry()), - ]; - client.descriptors.page.listLogEntries.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.logging.v2.ILogEntry[] = []; - const iterable = client.listLogEntriesAsync(request); - for await (const resource of iterable) { - responses.push(resource!); + it('invokes listMonitoredResourceDescriptors without error using callback', async () => { + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.ListMonitoredResourceDescriptorsRequest(), + ); + const expectedResponse = [ + generateSampleMessage( + new protos.google.api.MonitoredResourceDescriptor(), + ), + generateSampleMessage( + new protos.google.api.MonitoredResourceDescriptor(), + ), + generateSampleMessage( + new protos.google.api.MonitoredResourceDescriptor(), + ), + ]; + client.innerApiCalls.listMonitoredResourceDescriptors = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listMonitoredResourceDescriptors( + request, + ( + err?: Error | null, + result?: protos.google.api.IMonitoredResourceDescriptor[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listLogEntries.asyncIterate as SinonStub) - .getCall(0).args[1], request); - }); - - it('uses async iteration with listLogEntries with error', async () => { - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.ListLogEntriesRequest() - ); - const expectedError = new Error('expected'); - client.descriptors.page.listLogEntries.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listLogEntriesAsync(request); - await assert.rejects(async () => { - const responses: protos.google.logging.v2.ILogEntry[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listLogEntries.asyncIterate as SinonStub) - .getCall(0).args[1], request); - }); + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); }); - describe('listMonitoredResourceDescriptors', () => { - it('invokes listMonitoredResourceDescriptors without error', async () => { - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.ListMonitoredResourceDescriptorsRequest() - );const expectedResponse = [ - generateSampleMessage(new protos.google.api.MonitoredResourceDescriptor()), - generateSampleMessage(new protos.google.api.MonitoredResourceDescriptor()), - generateSampleMessage(new protos.google.api.MonitoredResourceDescriptor()), - ]; - client.innerApiCalls.listMonitoredResourceDescriptors = stubSimpleCall(expectedResponse); - const [response] = await client.listMonitoredResourceDescriptors(request); - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes listMonitoredResourceDescriptors with error', async () => { + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.ListMonitoredResourceDescriptorsRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.listMonitoredResourceDescriptors = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.listMonitoredResourceDescriptors(request), + expectedError, + ); + }); - it('invokes listMonitoredResourceDescriptors without error using callback', async () => { - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.ListMonitoredResourceDescriptorsRequest() - );const expectedResponse = [ - generateSampleMessage(new protos.google.api.MonitoredResourceDescriptor()), - generateSampleMessage(new protos.google.api.MonitoredResourceDescriptor()), - generateSampleMessage(new protos.google.api.MonitoredResourceDescriptor()), - ]; - client.innerApiCalls.listMonitoredResourceDescriptors = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listMonitoredResourceDescriptors( - request, - (err?: Error|null, result?: protos.google.api.IMonitoredResourceDescriptor[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes listMonitoredResourceDescriptorsStream without error', async () => { + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.ListMonitoredResourceDescriptorsRequest(), + ); + const expectedResponse = [ + generateSampleMessage( + new protos.google.api.MonitoredResourceDescriptor(), + ), + generateSampleMessage( + new protos.google.api.MonitoredResourceDescriptor(), + ), + generateSampleMessage( + new protos.google.api.MonitoredResourceDescriptor(), + ), + ]; + client.descriptors.page.listMonitoredResourceDescriptors.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listMonitoredResourceDescriptorsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.api.MonitoredResourceDescriptor[] = []; + stream.on( + 'data', + (response: protos.google.api.MonitoredResourceDescriptor) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + ( + client.descriptors.page.listMonitoredResourceDescriptors + .createStream as SinonStub + ) + .getCall(0) + .calledWith( + client.innerApiCalls.listMonitoredResourceDescriptors, + request, + ), + ); + }); - it('invokes listMonitoredResourceDescriptors with error', async () => { - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.ListMonitoredResourceDescriptorsRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.listMonitoredResourceDescriptors = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listMonitoredResourceDescriptors(request), expectedError); - }); + it('invokes listMonitoredResourceDescriptorsStream with error', async () => { + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.ListMonitoredResourceDescriptorsRequest(), + ); + const expectedError = new Error('expected'); + client.descriptors.page.listMonitoredResourceDescriptors.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listMonitoredResourceDescriptorsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.api.MonitoredResourceDescriptor[] = []; + stream.on( + 'data', + (response: protos.google.api.MonitoredResourceDescriptor) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + ( + client.descriptors.page.listMonitoredResourceDescriptors + .createStream as SinonStub + ) + .getCall(0) + .calledWith( + client.innerApiCalls.listMonitoredResourceDescriptors, + request, + ), + ); + }); - it('invokes listMonitoredResourceDescriptorsStream without error', async () => { - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.ListMonitoredResourceDescriptorsRequest() - ); - const expectedResponse = [ - generateSampleMessage(new protos.google.api.MonitoredResourceDescriptor()), - generateSampleMessage(new protos.google.api.MonitoredResourceDescriptor()), - generateSampleMessage(new protos.google.api.MonitoredResourceDescriptor()), - ]; - client.descriptors.page.listMonitoredResourceDescriptors.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listMonitoredResourceDescriptorsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.api.MonitoredResourceDescriptor[] = []; - stream.on('data', (response: protos.google.api.MonitoredResourceDescriptor) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.listMonitoredResourceDescriptors.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listMonitoredResourceDescriptors, request)); - }); + it('uses async iteration with listMonitoredResourceDescriptors without error', async () => { + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.ListMonitoredResourceDescriptorsRequest(), + ); + const expectedResponse = [ + generateSampleMessage( + new protos.google.api.MonitoredResourceDescriptor(), + ), + generateSampleMessage( + new protos.google.api.MonitoredResourceDescriptor(), + ), + generateSampleMessage( + new protos.google.api.MonitoredResourceDescriptor(), + ), + ]; + client.descriptors.page.listMonitoredResourceDescriptors.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.api.IMonitoredResourceDescriptor[] = []; + const iterable = client.listMonitoredResourceDescriptorsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listMonitoredResourceDescriptors + .asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + }); - it('invokes listMonitoredResourceDescriptorsStream with error', async () => { - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.ListMonitoredResourceDescriptorsRequest() - ); - const expectedError = new Error('expected'); - client.descriptors.page.listMonitoredResourceDescriptors.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listMonitoredResourceDescriptorsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.api.MonitoredResourceDescriptor[] = []; - stream.on('data', (response: protos.google.api.MonitoredResourceDescriptor) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listMonitoredResourceDescriptors.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listMonitoredResourceDescriptors, request)); - }); + it('uses async iteration with listMonitoredResourceDescriptors with error', async () => { + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.ListMonitoredResourceDescriptorsRequest(), + ); + const expectedError = new Error('expected'); + client.descriptors.page.listMonitoredResourceDescriptors.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listMonitoredResourceDescriptorsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.api.IMonitoredResourceDescriptor[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listMonitoredResourceDescriptors + .asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + }); + }); + + describe('listLogs', () => { + it('invokes listLogs without error', async () => { + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.ListLogsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.ListLogsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [new String(), new String(), new String()]; + client.innerApiCalls.listLogs = stubSimpleCall(expectedResponse); + const [response] = await client.listLogs(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listLogs as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listLogs as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('uses async iteration with listMonitoredResourceDescriptors without error', async () => { - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.ListMonitoredResourceDescriptorsRequest() - ); - const expectedResponse = [ - generateSampleMessage(new protos.google.api.MonitoredResourceDescriptor()), - generateSampleMessage(new protos.google.api.MonitoredResourceDescriptor()), - generateSampleMessage(new protos.google.api.MonitoredResourceDescriptor()), - ]; - client.descriptors.page.listMonitoredResourceDescriptors.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.api.IMonitoredResourceDescriptor[] = []; - const iterable = client.listMonitoredResourceDescriptorsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); + it('invokes listLogs without error using callback', async () => { + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.ListLogsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.ListLogsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [new String(), new String(), new String()]; + client.innerApiCalls.listLogs = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listLogs( + request, + (err?: Error | null, result?: string[] | null) => { + if (err) { + reject(err); + } else { + resolve(result); } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listMonitoredResourceDescriptors.asyncIterate as SinonStub) - .getCall(0).args[1], request); - }); - - it('uses async iteration with listMonitoredResourceDescriptors with error', async () => { - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.ListMonitoredResourceDescriptorsRequest() - ); - const expectedError = new Error('expected'); - client.descriptors.page.listMonitoredResourceDescriptors.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listMonitoredResourceDescriptorsAsync(request); - await assert.rejects(async () => { - const responses: protos.google.api.IMonitoredResourceDescriptor[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listMonitoredResourceDescriptors.asyncIterate as SinonStub) - .getCall(0).args[1], request); - }); + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listLogs as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listLogs as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('listLogs', () => { - it('invokes listLogs without error', async () => { - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.ListLogsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.ListLogsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [new String(), new String(), new String()]; - client.innerApiCalls.listLogs = stubSimpleCall(expectedResponse); - const [response] = await client.listLogs(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listLogs as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listLogs as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listLogs without error using callback', async () => { - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.ListLogsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.ListLogsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [new String(), new String(), new String()]; - client.innerApiCalls.listLogs = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listLogs( - request, - (err?: Error|null, result?: string[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listLogs as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listLogs as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listLogs with error', async () => { - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.ListLogsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.ListLogsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listLogs = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listLogs(request), expectedError); - const actualRequest = (client.innerApiCalls.listLogs as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listLogs as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listLogsStream without error', async () => { - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.ListLogsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.ListLogsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [new String(), new String(), new String()]; - client.descriptors.page.listLogs.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listLogsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: string[] = []; - stream.on('data', (response: string) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.listLogs.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listLogs, request)); - assert( - (client.descriptors.page.listLogs.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listLogs with error', async () => { + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.ListLogsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.ListLogsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listLogs = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.listLogs(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listLogs as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listLogs as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listLogsStream with error', async () => { - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.ListLogsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.ListLogsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listLogs.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listLogsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: string[] = []; - stream.on('data', (response: string) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listLogs.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listLogs, request)); - assert( - (client.descriptors.page.listLogs.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listLogsStream without error', async () => { + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.ListLogsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.ListLogsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [new String(), new String(), new String()]; + client.descriptors.page.listLogs.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listLogsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: string[] = []; + stream.on('data', (response: string) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listLogs.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listLogs, request), + ); + assert( + (client.descriptors.page.listLogs.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('uses async iteration with listLogs without error', async () => { - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.ListLogsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.ListLogsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [new String(), new String(), new String()]; - client.descriptors.page.listLogs.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: string[] = []; - const iterable = client.listLogsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listLogs.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listLogs.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listLogsStream with error', async () => { + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.ListLogsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.ListLogsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listLogs.createStream = stubPageStreamingCall( + undefined, + expectedError, + ); + const stream = client.listLogsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: string[] = []; + stream.on('data', (response: string) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listLogs.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listLogs, request), + ); + assert( + (client.descriptors.page.listLogs.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('uses async iteration with listLogs with error', async () => { - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.ListLogsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.ListLogsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listLogs.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listLogsAsync(request); - await assert.rejects(async () => { - const responses: string[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listLogs.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listLogs.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listLogs without error', async () => { + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.ListLogsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.ListLogsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [new String(), new String(), new String()]; + client.descriptors.page.listLogs.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: string[] = []; + const iterable = client.listLogsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + (client.descriptors.page.listLogs.asyncIterate as SinonStub).getCall(0) + .args[1], + request, + ); + assert( + (client.descriptors.page.listLogs.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); }); - describe('Path templates', () => { - - describe('billingAccountCmekSettings', () => { - const fakePath = "/rendered/path/billingAccountCmekSettings"; - const expectedParameters = { - billing_account: "billingAccountValue", - }; - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.billingAccountCmekSettingsPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.billingAccountCmekSettingsPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('billingAccountCmekSettingsPath', () => { - const result = client.billingAccountCmekSettingsPath("billingAccountValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.billingAccountCmekSettingsPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchBillingAccountFromBillingAccountCmekSettingsName', () => { - const result = client.matchBillingAccountFromBillingAccountCmekSettingsName(fakePath); - assert.strictEqual(result, "billingAccountValue"); - assert((client.pathTemplates.billingAccountCmekSettingsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('uses async iteration with listLogs with error', async () => { + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.ListLogsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.ListLogsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listLogs.asyncIterate = stubAsyncIterationCall( + undefined, + expectedError, + ); + const iterable = client.listLogsAsync(request); + await assert.rejects(async () => { + const responses: string[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + (client.descriptors.page.listLogs.asyncIterate as SinonStub).getCall(0) + .args[1], + request, + ); + assert( + (client.descriptors.page.listLogs.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + }); + + describe('Path templates', () => { + describe('billingAccountCmekSettings', () => { + const fakePath = '/rendered/path/billingAccountCmekSettings'; + const expectedParameters = { + billing_account: 'billingAccountValue', + }; + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.billingAccountCmekSettingsPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.billingAccountCmekSettingsPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('billingAccountCmekSettingsPath', () => { + const result = client.billingAccountCmekSettingsPath( + 'billingAccountValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.billingAccountCmekSettingsPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchBillingAccountFromBillingAccountCmekSettingsName', () => { + const result = + client.matchBillingAccountFromBillingAccountCmekSettingsName( + fakePath, + ); + assert.strictEqual(result, 'billingAccountValue'); + assert( + ( + client.pathTemplates.billingAccountCmekSettingsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('billingAccountExclusion', () => { - const fakePath = "/rendered/path/billingAccountExclusion"; - const expectedParameters = { - billing_account: "billingAccountValue", - exclusion: "exclusionValue", - }; - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.billingAccountExclusionPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.billingAccountExclusionPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('billingAccountExclusionPath', () => { - const result = client.billingAccountExclusionPath("billingAccountValue", "exclusionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.billingAccountExclusionPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchBillingAccountFromBillingAccountExclusionName', () => { - const result = client.matchBillingAccountFromBillingAccountExclusionName(fakePath); - assert.strictEqual(result, "billingAccountValue"); - assert((client.pathTemplates.billingAccountExclusionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchExclusionFromBillingAccountExclusionName', () => { - const result = client.matchExclusionFromBillingAccountExclusionName(fakePath); - assert.strictEqual(result, "exclusionValue"); - assert((client.pathTemplates.billingAccountExclusionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('billingAccountExclusion', () => { + const fakePath = '/rendered/path/billingAccountExclusion'; + const expectedParameters = { + billing_account: 'billingAccountValue', + exclusion: 'exclusionValue', + }; + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.billingAccountExclusionPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.billingAccountExclusionPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('billingAccountExclusionPath', () => { + const result = client.billingAccountExclusionPath( + 'billingAccountValue', + 'exclusionValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.billingAccountExclusionPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchBillingAccountFromBillingAccountExclusionName', () => { + const result = + client.matchBillingAccountFromBillingAccountExclusionName(fakePath); + assert.strictEqual(result, 'billingAccountValue'); + assert( + ( + client.pathTemplates.billingAccountExclusionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchExclusionFromBillingAccountExclusionName', () => { + const result = + client.matchExclusionFromBillingAccountExclusionName(fakePath); + assert.strictEqual(result, 'exclusionValue'); + assert( + ( + client.pathTemplates.billingAccountExclusionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('billingAccountLocationBucket', () => { - const fakePath = "/rendered/path/billingAccountLocationBucket"; - const expectedParameters = { - billing_account: "billingAccountValue", - location: "locationValue", - bucket: "bucketValue", - }; - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.billingAccountLocationBucketPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.billingAccountLocationBucketPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('billingAccountLocationBucketPath', () => { - const result = client.billingAccountLocationBucketPath("billingAccountValue", "locationValue", "bucketValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.billingAccountLocationBucketPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchBillingAccountFromBillingAccountLocationBucketName', () => { - const result = client.matchBillingAccountFromBillingAccountLocationBucketName(fakePath); - assert.strictEqual(result, "billingAccountValue"); - assert((client.pathTemplates.billingAccountLocationBucketPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromBillingAccountLocationBucketName', () => { - const result = client.matchLocationFromBillingAccountLocationBucketName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.billingAccountLocationBucketPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBucketFromBillingAccountLocationBucketName', () => { - const result = client.matchBucketFromBillingAccountLocationBucketName(fakePath); - assert.strictEqual(result, "bucketValue"); - assert((client.pathTemplates.billingAccountLocationBucketPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('billingAccountLocationBucket', () => { + const fakePath = '/rendered/path/billingAccountLocationBucket'; + const expectedParameters = { + billing_account: 'billingAccountValue', + location: 'locationValue', + bucket: 'bucketValue', + }; + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.billingAccountLocationBucketPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.billingAccountLocationBucketPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('billingAccountLocationBucketPath', () => { + const result = client.billingAccountLocationBucketPath( + 'billingAccountValue', + 'locationValue', + 'bucketValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.billingAccountLocationBucketPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchBillingAccountFromBillingAccountLocationBucketName', () => { + const result = + client.matchBillingAccountFromBillingAccountLocationBucketName( + fakePath, + ); + assert.strictEqual(result, 'billingAccountValue'); + assert( + ( + client.pathTemplates.billingAccountLocationBucketPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromBillingAccountLocationBucketName', () => { + const result = + client.matchLocationFromBillingAccountLocationBucketName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + ( + client.pathTemplates.billingAccountLocationBucketPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBucketFromBillingAccountLocationBucketName', () => { + const result = + client.matchBucketFromBillingAccountLocationBucketName(fakePath); + assert.strictEqual(result, 'bucketValue'); + assert( + ( + client.pathTemplates.billingAccountLocationBucketPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('billingAccountLocationBucketView', () => { - const fakePath = "/rendered/path/billingAccountLocationBucketView"; - const expectedParameters = { - billing_account: "billingAccountValue", - location: "locationValue", - bucket: "bucketValue", - view: "viewValue", - }; - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.billingAccountLocationBucketViewPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.billingAccountLocationBucketViewPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('billingAccountLocationBucketViewPath', () => { - const result = client.billingAccountLocationBucketViewPath("billingAccountValue", "locationValue", "bucketValue", "viewValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.billingAccountLocationBucketViewPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchBillingAccountFromBillingAccountLocationBucketViewName', () => { - const result = client.matchBillingAccountFromBillingAccountLocationBucketViewName(fakePath); - assert.strictEqual(result, "billingAccountValue"); - assert((client.pathTemplates.billingAccountLocationBucketViewPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromBillingAccountLocationBucketViewName', () => { - const result = client.matchLocationFromBillingAccountLocationBucketViewName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.billingAccountLocationBucketViewPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBucketFromBillingAccountLocationBucketViewName', () => { - const result = client.matchBucketFromBillingAccountLocationBucketViewName(fakePath); - assert.strictEqual(result, "bucketValue"); - assert((client.pathTemplates.billingAccountLocationBucketViewPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchViewFromBillingAccountLocationBucketViewName', () => { - const result = client.matchViewFromBillingAccountLocationBucketViewName(fakePath); - assert.strictEqual(result, "viewValue"); - assert((client.pathTemplates.billingAccountLocationBucketViewPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('billingAccountLocationBucketView', () => { + const fakePath = '/rendered/path/billingAccountLocationBucketView'; + const expectedParameters = { + billing_account: 'billingAccountValue', + location: 'locationValue', + bucket: 'bucketValue', + view: 'viewValue', + }; + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.billingAccountLocationBucketViewPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.billingAccountLocationBucketViewPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('billingAccountLocationBucketViewPath', () => { + const result = client.billingAccountLocationBucketViewPath( + 'billingAccountValue', + 'locationValue', + 'bucketValue', + 'viewValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.billingAccountLocationBucketViewPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchBillingAccountFromBillingAccountLocationBucketViewName', () => { + const result = + client.matchBillingAccountFromBillingAccountLocationBucketViewName( + fakePath, + ); + assert.strictEqual(result, 'billingAccountValue'); + assert( + ( + client.pathTemplates.billingAccountLocationBucketViewPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromBillingAccountLocationBucketViewName', () => { + const result = + client.matchLocationFromBillingAccountLocationBucketViewName( + fakePath, + ); + assert.strictEqual(result, 'locationValue'); + assert( + ( + client.pathTemplates.billingAccountLocationBucketViewPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBucketFromBillingAccountLocationBucketViewName', () => { + const result = + client.matchBucketFromBillingAccountLocationBucketViewName(fakePath); + assert.strictEqual(result, 'bucketValue'); + assert( + ( + client.pathTemplates.billingAccountLocationBucketViewPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchViewFromBillingAccountLocationBucketViewName', () => { + const result = + client.matchViewFromBillingAccountLocationBucketViewName(fakePath); + assert.strictEqual(result, 'viewValue'); + assert( + ( + client.pathTemplates.billingAccountLocationBucketViewPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('billingAccountLog', () => { - const fakePath = "/rendered/path/billingAccountLog"; - const expectedParameters = { - billing_account: "billingAccountValue", - log: "logValue", - }; - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.billingAccountLogPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.billingAccountLogPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('billingAccountLogPath', () => { - const result = client.billingAccountLogPath("billingAccountValue", "logValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.billingAccountLogPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchBillingAccountFromBillingAccountLogName', () => { - const result = client.matchBillingAccountFromBillingAccountLogName(fakePath); - assert.strictEqual(result, "billingAccountValue"); - assert((client.pathTemplates.billingAccountLogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLogFromBillingAccountLogName', () => { - const result = client.matchLogFromBillingAccountLogName(fakePath); - assert.strictEqual(result, "logValue"); - assert((client.pathTemplates.billingAccountLogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('billingAccountLog', () => { + const fakePath = '/rendered/path/billingAccountLog'; + const expectedParameters = { + billing_account: 'billingAccountValue', + log: 'logValue', + }; + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.billingAccountLogPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.billingAccountLogPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('billingAccountLogPath', () => { + const result = client.billingAccountLogPath( + 'billingAccountValue', + 'logValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.billingAccountLogPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchBillingAccountFromBillingAccountLogName', () => { + const result = + client.matchBillingAccountFromBillingAccountLogName(fakePath); + assert.strictEqual(result, 'billingAccountValue'); + assert( + ( + client.pathTemplates.billingAccountLogPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLogFromBillingAccountLogName', () => { + const result = client.matchLogFromBillingAccountLogName(fakePath); + assert.strictEqual(result, 'logValue'); + assert( + ( + client.pathTemplates.billingAccountLogPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('billingAccountSettings', () => { - const fakePath = "/rendered/path/billingAccountSettings"; - const expectedParameters = { - billing_account: "billingAccountValue", - }; - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.billingAccountSettingsPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.billingAccountSettingsPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('billingAccountSettingsPath', () => { - const result = client.billingAccountSettingsPath("billingAccountValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.billingAccountSettingsPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchBillingAccountFromBillingAccountSettingsName', () => { - const result = client.matchBillingAccountFromBillingAccountSettingsName(fakePath); - assert.strictEqual(result, "billingAccountValue"); - assert((client.pathTemplates.billingAccountSettingsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('billingAccountSettings', () => { + const fakePath = '/rendered/path/billingAccountSettings'; + const expectedParameters = { + billing_account: 'billingAccountValue', + }; + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.billingAccountSettingsPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.billingAccountSettingsPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('billingAccountSettingsPath', () => { + const result = client.billingAccountSettingsPath('billingAccountValue'); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.billingAccountSettingsPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchBillingAccountFromBillingAccountSettingsName', () => { + const result = + client.matchBillingAccountFromBillingAccountSettingsName(fakePath); + assert.strictEqual(result, 'billingAccountValue'); + assert( + ( + client.pathTemplates.billingAccountSettingsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('billingAccountSink', () => { - const fakePath = "/rendered/path/billingAccountSink"; - const expectedParameters = { - billing_account: "billingAccountValue", - sink: "sinkValue", - }; - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.billingAccountSinkPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.billingAccountSinkPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('billingAccountSinkPath', () => { - const result = client.billingAccountSinkPath("billingAccountValue", "sinkValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.billingAccountSinkPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchBillingAccountFromBillingAccountSinkName', () => { - const result = client.matchBillingAccountFromBillingAccountSinkName(fakePath); - assert.strictEqual(result, "billingAccountValue"); - assert((client.pathTemplates.billingAccountSinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchSinkFromBillingAccountSinkName', () => { - const result = client.matchSinkFromBillingAccountSinkName(fakePath); - assert.strictEqual(result, "sinkValue"); - assert((client.pathTemplates.billingAccountSinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('billingAccountSink', () => { + const fakePath = '/rendered/path/billingAccountSink'; + const expectedParameters = { + billing_account: 'billingAccountValue', + sink: 'sinkValue', + }; + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.billingAccountSinkPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.billingAccountSinkPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('billingAccountSinkPath', () => { + const result = client.billingAccountSinkPath( + 'billingAccountValue', + 'sinkValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.billingAccountSinkPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchBillingAccountFromBillingAccountSinkName', () => { + const result = + client.matchBillingAccountFromBillingAccountSinkName(fakePath); + assert.strictEqual(result, 'billingAccountValue'); + assert( + ( + client.pathTemplates.billingAccountSinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchSinkFromBillingAccountSinkName', () => { + const result = client.matchSinkFromBillingAccountSinkName(fakePath); + assert.strictEqual(result, 'sinkValue'); + assert( + ( + client.pathTemplates.billingAccountSinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('folderCmekSettings', () => { - const fakePath = "/rendered/path/folderCmekSettings"; - const expectedParameters = { - folder: "folderValue", - }; - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.folderCmekSettingsPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderCmekSettingsPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderCmekSettingsPath', () => { - const result = client.folderCmekSettingsPath("folderValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderCmekSettingsPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderCmekSettingsName', () => { - const result = client.matchFolderFromFolderCmekSettingsName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderCmekSettingsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('folderCmekSettings', () => { + const fakePath = '/rendered/path/folderCmekSettings'; + const expectedParameters = { + folder: 'folderValue', + }; + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.folderCmekSettingsPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderCmekSettingsPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderCmekSettingsPath', () => { + const result = client.folderCmekSettingsPath('folderValue'); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.folderCmekSettingsPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderCmekSettingsName', () => { + const result = client.matchFolderFromFolderCmekSettingsName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + ( + client.pathTemplates.folderCmekSettingsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('folderExclusion', () => { - const fakePath = "/rendered/path/folderExclusion"; - const expectedParameters = { - folder: "folderValue", - exclusion: "exclusionValue", - }; - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.folderExclusionPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderExclusionPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderExclusionPath', () => { - const result = client.folderExclusionPath("folderValue", "exclusionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderExclusionPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderExclusionName', () => { - const result = client.matchFolderFromFolderExclusionName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderExclusionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchExclusionFromFolderExclusionName', () => { - const result = client.matchExclusionFromFolderExclusionName(fakePath); - assert.strictEqual(result, "exclusionValue"); - assert((client.pathTemplates.folderExclusionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('folderExclusion', () => { + const fakePath = '/rendered/path/folderExclusion'; + const expectedParameters = { + folder: 'folderValue', + exclusion: 'exclusionValue', + }; + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.folderExclusionPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderExclusionPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderExclusionPath', () => { + const result = client.folderExclusionPath( + 'folderValue', + 'exclusionValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.folderExclusionPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderExclusionName', () => { + const result = client.matchFolderFromFolderExclusionName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + (client.pathTemplates.folderExclusionPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchExclusionFromFolderExclusionName', () => { + const result = client.matchExclusionFromFolderExclusionName(fakePath); + assert.strictEqual(result, 'exclusionValue'); + assert( + (client.pathTemplates.folderExclusionPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('folderLocationBucket', () => { - const fakePath = "/rendered/path/folderLocationBucket"; - const expectedParameters = { - folder: "folderValue", - location: "locationValue", - bucket: "bucketValue", - }; - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.folderLocationBucketPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderLocationBucketPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderLocationBucketPath', () => { - const result = client.folderLocationBucketPath("folderValue", "locationValue", "bucketValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderLocationBucketPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderLocationBucketName', () => { - const result = client.matchFolderFromFolderLocationBucketName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderLocationBucketPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromFolderLocationBucketName', () => { - const result = client.matchLocationFromFolderLocationBucketName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.folderLocationBucketPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBucketFromFolderLocationBucketName', () => { - const result = client.matchBucketFromFolderLocationBucketName(fakePath); - assert.strictEqual(result, "bucketValue"); - assert((client.pathTemplates.folderLocationBucketPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('folderLocationBucket', () => { + const fakePath = '/rendered/path/folderLocationBucket'; + const expectedParameters = { + folder: 'folderValue', + location: 'locationValue', + bucket: 'bucketValue', + }; + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.folderLocationBucketPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderLocationBucketPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderLocationBucketPath', () => { + const result = client.folderLocationBucketPath( + 'folderValue', + 'locationValue', + 'bucketValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.folderLocationBucketPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderLocationBucketName', () => { + const result = client.matchFolderFromFolderLocationBucketName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + ( + client.pathTemplates.folderLocationBucketPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromFolderLocationBucketName', () => { + const result = + client.matchLocationFromFolderLocationBucketName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + ( + client.pathTemplates.folderLocationBucketPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBucketFromFolderLocationBucketName', () => { + const result = client.matchBucketFromFolderLocationBucketName(fakePath); + assert.strictEqual(result, 'bucketValue'); + assert( + ( + client.pathTemplates.folderLocationBucketPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('folderLocationBucketView', () => { - const fakePath = "/rendered/path/folderLocationBucketView"; - const expectedParameters = { - folder: "folderValue", - location: "locationValue", - bucket: "bucketValue", - view: "viewValue", - }; - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.folderLocationBucketViewPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderLocationBucketViewPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderLocationBucketViewPath', () => { - const result = client.folderLocationBucketViewPath("folderValue", "locationValue", "bucketValue", "viewValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderLocationBucketViewPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderLocationBucketViewName', () => { - const result = client.matchFolderFromFolderLocationBucketViewName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderLocationBucketViewPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromFolderLocationBucketViewName', () => { - const result = client.matchLocationFromFolderLocationBucketViewName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.folderLocationBucketViewPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBucketFromFolderLocationBucketViewName', () => { - const result = client.matchBucketFromFolderLocationBucketViewName(fakePath); - assert.strictEqual(result, "bucketValue"); - assert((client.pathTemplates.folderLocationBucketViewPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchViewFromFolderLocationBucketViewName', () => { - const result = client.matchViewFromFolderLocationBucketViewName(fakePath); - assert.strictEqual(result, "viewValue"); - assert((client.pathTemplates.folderLocationBucketViewPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('folderLocationBucketView', () => { + const fakePath = '/rendered/path/folderLocationBucketView'; + const expectedParameters = { + folder: 'folderValue', + location: 'locationValue', + bucket: 'bucketValue', + view: 'viewValue', + }; + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.folderLocationBucketViewPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderLocationBucketViewPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderLocationBucketViewPath', () => { + const result = client.folderLocationBucketViewPath( + 'folderValue', + 'locationValue', + 'bucketValue', + 'viewValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.folderLocationBucketViewPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderLocationBucketViewName', () => { + const result = + client.matchFolderFromFolderLocationBucketViewName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + ( + client.pathTemplates.folderLocationBucketViewPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromFolderLocationBucketViewName', () => { + const result = + client.matchLocationFromFolderLocationBucketViewName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + ( + client.pathTemplates.folderLocationBucketViewPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBucketFromFolderLocationBucketViewName', () => { + const result = + client.matchBucketFromFolderLocationBucketViewName(fakePath); + assert.strictEqual(result, 'bucketValue'); + assert( + ( + client.pathTemplates.folderLocationBucketViewPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchViewFromFolderLocationBucketViewName', () => { + const result = + client.matchViewFromFolderLocationBucketViewName(fakePath); + assert.strictEqual(result, 'viewValue'); + assert( + ( + client.pathTemplates.folderLocationBucketViewPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('folderLog', () => { - const fakePath = "/rendered/path/folderLog"; - const expectedParameters = { - folder: "folderValue", - log: "logValue", - }; - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.folderLogPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderLogPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderLogPath', () => { - const result = client.folderLogPath("folderValue", "logValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderLogPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderLogName', () => { - const result = client.matchFolderFromFolderLogName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderLogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLogFromFolderLogName', () => { - const result = client.matchLogFromFolderLogName(fakePath); - assert.strictEqual(result, "logValue"); - assert((client.pathTemplates.folderLogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('folderLog', () => { + const fakePath = '/rendered/path/folderLog'; + const expectedParameters = { + folder: 'folderValue', + log: 'logValue', + }; + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.folderLogPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderLogPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderLogPath', () => { + const result = client.folderLogPath('folderValue', 'logValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.folderLogPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderLogName', () => { + const result = client.matchFolderFromFolderLogName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + (client.pathTemplates.folderLogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLogFromFolderLogName', () => { + const result = client.matchLogFromFolderLogName(fakePath); + assert.strictEqual(result, 'logValue'); + assert( + (client.pathTemplates.folderLogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('folderSettings', () => { - const fakePath = "/rendered/path/folderSettings"; - const expectedParameters = { - folder: "folderValue", - }; - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.folderSettingsPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderSettingsPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderSettingsPath', () => { - const result = client.folderSettingsPath("folderValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderSettingsPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderSettingsName', () => { - const result = client.matchFolderFromFolderSettingsName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderSettingsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('folderSettings', () => { + const fakePath = '/rendered/path/folderSettings'; + const expectedParameters = { + folder: 'folderValue', + }; + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.folderSettingsPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderSettingsPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderSettingsPath', () => { + const result = client.folderSettingsPath('folderValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.folderSettingsPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderSettingsName', () => { + const result = client.matchFolderFromFolderSettingsName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + (client.pathTemplates.folderSettingsPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('folderSink', () => { - const fakePath = "/rendered/path/folderSink"; - const expectedParameters = { - folder: "folderValue", - sink: "sinkValue", - }; - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.folderSinkPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderSinkPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderSinkPath', () => { - const result = client.folderSinkPath("folderValue", "sinkValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderSinkPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderSinkName', () => { - const result = client.matchFolderFromFolderSinkName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderSinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchSinkFromFolderSinkName', () => { - const result = client.matchSinkFromFolderSinkName(fakePath); - assert.strictEqual(result, "sinkValue"); - assert((client.pathTemplates.folderSinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('folderSink', () => { + const fakePath = '/rendered/path/folderSink'; + const expectedParameters = { + folder: 'folderValue', + sink: 'sinkValue', + }; + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.folderSinkPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderSinkPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderSinkPath', () => { + const result = client.folderSinkPath('folderValue', 'sinkValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.folderSinkPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderSinkName', () => { + const result = client.matchFolderFromFolderSinkName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + (client.pathTemplates.folderSinkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchSinkFromFolderSinkName', () => { + const result = client.matchSinkFromFolderSinkName(fakePath); + assert.strictEqual(result, 'sinkValue'); + assert( + (client.pathTemplates.folderSinkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('logMetric', () => { - const fakePath = "/rendered/path/logMetric"; - const expectedParameters = { - project: "projectValue", - metric: "metricValue", - }; - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.logMetricPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.logMetricPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('logMetricPath', () => { - const result = client.logMetricPath("projectValue", "metricValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.logMetricPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromLogMetricName', () => { - const result = client.matchProjectFromLogMetricName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.logMetricPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchMetricFromLogMetricName', () => { - const result = client.matchMetricFromLogMetricName(fakePath); - assert.strictEqual(result, "metricValue"); - assert((client.pathTemplates.logMetricPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('logMetric', () => { + const fakePath = '/rendered/path/logMetric'; + const expectedParameters = { + project: 'projectValue', + metric: 'metricValue', + }; + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.logMetricPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.logMetricPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('logMetricPath', () => { + const result = client.logMetricPath('projectValue', 'metricValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.logMetricPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromLogMetricName', () => { + const result = client.matchProjectFromLogMetricName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.logMetricPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchMetricFromLogMetricName', () => { + const result = client.matchMetricFromLogMetricName(fakePath); + assert.strictEqual(result, 'metricValue'); + assert( + (client.pathTemplates.logMetricPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('organizationCmekSettings', () => { - const fakePath = "/rendered/path/organizationCmekSettings"; - const expectedParameters = { - organization: "organizationValue", - }; - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.organizationCmekSettingsPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationCmekSettingsPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationCmekSettingsPath', () => { - const result = client.organizationCmekSettingsPath("organizationValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationCmekSettingsPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationCmekSettingsName', () => { - const result = client.matchOrganizationFromOrganizationCmekSettingsName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationCmekSettingsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('organizationCmekSettings', () => { + const fakePath = '/rendered/path/organizationCmekSettings'; + const expectedParameters = { + organization: 'organizationValue', + }; + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.organizationCmekSettingsPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.organizationCmekSettingsPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('organizationCmekSettingsPath', () => { + const result = client.organizationCmekSettingsPath('organizationValue'); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationCmekSettingsPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationCmekSettingsName', () => { + const result = + client.matchOrganizationFromOrganizationCmekSettingsName(fakePath); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationCmekSettingsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('organizationExclusion', () => { - const fakePath = "/rendered/path/organizationExclusion"; - const expectedParameters = { - organization: "organizationValue", - exclusion: "exclusionValue", - }; - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.organizationExclusionPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationExclusionPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationExclusionPath', () => { - const result = client.organizationExclusionPath("organizationValue", "exclusionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationExclusionPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationExclusionName', () => { - const result = client.matchOrganizationFromOrganizationExclusionName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationExclusionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchExclusionFromOrganizationExclusionName', () => { - const result = client.matchExclusionFromOrganizationExclusionName(fakePath); - assert.strictEqual(result, "exclusionValue"); - assert((client.pathTemplates.organizationExclusionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('organizationExclusion', () => { + const fakePath = '/rendered/path/organizationExclusion'; + const expectedParameters = { + organization: 'organizationValue', + exclusion: 'exclusionValue', + }; + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.organizationExclusionPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.organizationExclusionPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('organizationExclusionPath', () => { + const result = client.organizationExclusionPath( + 'organizationValue', + 'exclusionValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationExclusionPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationExclusionName', () => { + const result = + client.matchOrganizationFromOrganizationExclusionName(fakePath); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationExclusionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchExclusionFromOrganizationExclusionName', () => { + const result = + client.matchExclusionFromOrganizationExclusionName(fakePath); + assert.strictEqual(result, 'exclusionValue'); + assert( + ( + client.pathTemplates.organizationExclusionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('organizationLocationBucket', () => { - const fakePath = "/rendered/path/organizationLocationBucket"; - const expectedParameters = { - organization: "organizationValue", - location: "locationValue", - bucket: "bucketValue", - }; - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.organizationLocationBucketPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationLocationBucketPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationLocationBucketPath', () => { - const result = client.organizationLocationBucketPath("organizationValue", "locationValue", "bucketValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationLocationBucketPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationLocationBucketName', () => { - const result = client.matchOrganizationFromOrganizationLocationBucketName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationLocationBucketPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromOrganizationLocationBucketName', () => { - const result = client.matchLocationFromOrganizationLocationBucketName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.organizationLocationBucketPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBucketFromOrganizationLocationBucketName', () => { - const result = client.matchBucketFromOrganizationLocationBucketName(fakePath); - assert.strictEqual(result, "bucketValue"); - assert((client.pathTemplates.organizationLocationBucketPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('organizationLocationBucket', () => { + const fakePath = '/rendered/path/organizationLocationBucket'; + const expectedParameters = { + organization: 'organizationValue', + location: 'locationValue', + bucket: 'bucketValue', + }; + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.organizationLocationBucketPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.organizationLocationBucketPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('organizationLocationBucketPath', () => { + const result = client.organizationLocationBucketPath( + 'organizationValue', + 'locationValue', + 'bucketValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationLocationBucketPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationLocationBucketName', () => { + const result = + client.matchOrganizationFromOrganizationLocationBucketName(fakePath); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationLocationBucketPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromOrganizationLocationBucketName', () => { + const result = + client.matchLocationFromOrganizationLocationBucketName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + ( + client.pathTemplates.organizationLocationBucketPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBucketFromOrganizationLocationBucketName', () => { + const result = + client.matchBucketFromOrganizationLocationBucketName(fakePath); + assert.strictEqual(result, 'bucketValue'); + assert( + ( + client.pathTemplates.organizationLocationBucketPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('organizationLocationBucketView', () => { - const fakePath = "/rendered/path/organizationLocationBucketView"; - const expectedParameters = { - organization: "organizationValue", - location: "locationValue", - bucket: "bucketValue", - view: "viewValue", - }; - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.organizationLocationBucketViewPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationLocationBucketViewPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationLocationBucketViewPath', () => { - const result = client.organizationLocationBucketViewPath("organizationValue", "locationValue", "bucketValue", "viewValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationLocationBucketViewPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationLocationBucketViewName', () => { - const result = client.matchOrganizationFromOrganizationLocationBucketViewName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationLocationBucketViewPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromOrganizationLocationBucketViewName', () => { - const result = client.matchLocationFromOrganizationLocationBucketViewName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.organizationLocationBucketViewPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBucketFromOrganizationLocationBucketViewName', () => { - const result = client.matchBucketFromOrganizationLocationBucketViewName(fakePath); - assert.strictEqual(result, "bucketValue"); - assert((client.pathTemplates.organizationLocationBucketViewPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchViewFromOrganizationLocationBucketViewName', () => { - const result = client.matchViewFromOrganizationLocationBucketViewName(fakePath); - assert.strictEqual(result, "viewValue"); - assert((client.pathTemplates.organizationLocationBucketViewPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('organizationLocationBucketView', () => { + const fakePath = '/rendered/path/organizationLocationBucketView'; + const expectedParameters = { + organization: 'organizationValue', + location: 'locationValue', + bucket: 'bucketValue', + view: 'viewValue', + }; + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.organizationLocationBucketViewPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.organizationLocationBucketViewPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('organizationLocationBucketViewPath', () => { + const result = client.organizationLocationBucketViewPath( + 'organizationValue', + 'locationValue', + 'bucketValue', + 'viewValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationLocationBucketViewPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationLocationBucketViewName', () => { + const result = + client.matchOrganizationFromOrganizationLocationBucketViewName( + fakePath, + ); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationLocationBucketViewPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromOrganizationLocationBucketViewName', () => { + const result = + client.matchLocationFromOrganizationLocationBucketViewName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + ( + client.pathTemplates.organizationLocationBucketViewPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBucketFromOrganizationLocationBucketViewName', () => { + const result = + client.matchBucketFromOrganizationLocationBucketViewName(fakePath); + assert.strictEqual(result, 'bucketValue'); + assert( + ( + client.pathTemplates.organizationLocationBucketViewPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchViewFromOrganizationLocationBucketViewName', () => { + const result = + client.matchViewFromOrganizationLocationBucketViewName(fakePath); + assert.strictEqual(result, 'viewValue'); + assert( + ( + client.pathTemplates.organizationLocationBucketViewPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('organizationLog', () => { - const fakePath = "/rendered/path/organizationLog"; - const expectedParameters = { - organization: "organizationValue", - log: "logValue", - }; - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.organizationLogPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationLogPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationLogPath', () => { - const result = client.organizationLogPath("organizationValue", "logValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationLogPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationLogName', () => { - const result = client.matchOrganizationFromOrganizationLogName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationLogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLogFromOrganizationLogName', () => { - const result = client.matchLogFromOrganizationLogName(fakePath); - assert.strictEqual(result, "logValue"); - assert((client.pathTemplates.organizationLogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('organizationLog', () => { + const fakePath = '/rendered/path/organizationLog'; + const expectedParameters = { + organization: 'organizationValue', + log: 'logValue', + }; + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.organizationLogPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.organizationLogPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('organizationLogPath', () => { + const result = client.organizationLogPath( + 'organizationValue', + 'logValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.organizationLogPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationLogName', () => { + const result = + client.matchOrganizationFromOrganizationLogName(fakePath); + assert.strictEqual(result, 'organizationValue'); + assert( + (client.pathTemplates.organizationLogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLogFromOrganizationLogName', () => { + const result = client.matchLogFromOrganizationLogName(fakePath); + assert.strictEqual(result, 'logValue'); + assert( + (client.pathTemplates.organizationLogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('organizationSettings', () => { - const fakePath = "/rendered/path/organizationSettings"; - const expectedParameters = { - organization: "organizationValue", - }; - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.organizationSettingsPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationSettingsPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationSettingsPath', () => { - const result = client.organizationSettingsPath("organizationValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationSettingsPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationSettingsName', () => { - const result = client.matchOrganizationFromOrganizationSettingsName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationSettingsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('organizationSettings', () => { + const fakePath = '/rendered/path/organizationSettings'; + const expectedParameters = { + organization: 'organizationValue', + }; + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.organizationSettingsPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.organizationSettingsPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('organizationSettingsPath', () => { + const result = client.organizationSettingsPath('organizationValue'); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationSettingsPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationSettingsName', () => { + const result = + client.matchOrganizationFromOrganizationSettingsName(fakePath); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationSettingsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('organizationSink', () => { - const fakePath = "/rendered/path/organizationSink"; - const expectedParameters = { - organization: "organizationValue", - sink: "sinkValue", - }; - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.organizationSinkPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationSinkPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationSinkPath', () => { - const result = client.organizationSinkPath("organizationValue", "sinkValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationSinkPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationSinkName', () => { - const result = client.matchOrganizationFromOrganizationSinkName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationSinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchSinkFromOrganizationSinkName', () => { - const result = client.matchSinkFromOrganizationSinkName(fakePath); - assert.strictEqual(result, "sinkValue"); - assert((client.pathTemplates.organizationSinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('organizationSink', () => { + const fakePath = '/rendered/path/organizationSink'; + const expectedParameters = { + organization: 'organizationValue', + sink: 'sinkValue', + }; + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.organizationSinkPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.organizationSinkPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('organizationSinkPath', () => { + const result = client.organizationSinkPath( + 'organizationValue', + 'sinkValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationSinkPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationSinkName', () => { + const result = + client.matchOrganizationFromOrganizationSinkName(fakePath); + assert.strictEqual(result, 'organizationValue'); + assert( + (client.pathTemplates.organizationSinkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchSinkFromOrganizationSinkName', () => { + const result = client.matchSinkFromOrganizationSinkName(fakePath); + assert.strictEqual(result, 'sinkValue'); + assert( + (client.pathTemplates.organizationSinkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('project', () => { - const fakePath = "/rendered/path/project"; - const expectedParameters = { - project: "projectValue", - }; - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.projectPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectPath', () => { - const result = client.projectPath("projectValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectName', () => { - const result = client.matchProjectFromProjectName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('project', () => { + const fakePath = '/rendered/path/project'; + const expectedParameters = { + project: 'projectValue', + }; + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.projectPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectPath', () => { + const result = client.projectPath('projectValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.projectPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectName', () => { + const result = client.matchProjectFromProjectName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.projectPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectCmekSettings', () => { - const fakePath = "/rendered/path/projectCmekSettings"; - const expectedParameters = { - project: "projectValue", - }; - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.projectCmekSettingsPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectCmekSettingsPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectCmekSettingsPath', () => { - const result = client.projectCmekSettingsPath("projectValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectCmekSettingsPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectCmekSettingsName', () => { - const result = client.matchProjectFromProjectCmekSettingsName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectCmekSettingsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectCmekSettings', () => { + const fakePath = '/rendered/path/projectCmekSettings'; + const expectedParameters = { + project: 'projectValue', + }; + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.projectCmekSettingsPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectCmekSettingsPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectCmekSettingsPath', () => { + const result = client.projectCmekSettingsPath('projectValue'); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.projectCmekSettingsPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectCmekSettingsName', () => { + const result = client.matchProjectFromProjectCmekSettingsName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.projectCmekSettingsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectExclusion', () => { - const fakePath = "/rendered/path/projectExclusion"; - const expectedParameters = { - project: "projectValue", - exclusion: "exclusionValue", - }; - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.projectExclusionPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectExclusionPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectExclusionPath', () => { - const result = client.projectExclusionPath("projectValue", "exclusionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectExclusionPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectExclusionName', () => { - const result = client.matchProjectFromProjectExclusionName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectExclusionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchExclusionFromProjectExclusionName', () => { - const result = client.matchExclusionFromProjectExclusionName(fakePath); - assert.strictEqual(result, "exclusionValue"); - assert((client.pathTemplates.projectExclusionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectExclusion', () => { + const fakePath = '/rendered/path/projectExclusion'; + const expectedParameters = { + project: 'projectValue', + exclusion: 'exclusionValue', + }; + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.projectExclusionPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectExclusionPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectExclusionPath', () => { + const result = client.projectExclusionPath( + 'projectValue', + 'exclusionValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.projectExclusionPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectExclusionName', () => { + const result = client.matchProjectFromProjectExclusionName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.projectExclusionPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchExclusionFromProjectExclusionName', () => { + const result = client.matchExclusionFromProjectExclusionName(fakePath); + assert.strictEqual(result, 'exclusionValue'); + assert( + (client.pathTemplates.projectExclusionPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectLocationBucket', () => { - const fakePath = "/rendered/path/projectLocationBucket"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - bucket: "bucketValue", - }; - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.projectLocationBucketPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectLocationBucketPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectLocationBucketPath', () => { - const result = client.projectLocationBucketPath("projectValue", "locationValue", "bucketValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectLocationBucketPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectLocationBucketName', () => { - const result = client.matchProjectFromProjectLocationBucketName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectLocationBucketPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromProjectLocationBucketName', () => { - const result = client.matchLocationFromProjectLocationBucketName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.projectLocationBucketPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBucketFromProjectLocationBucketName', () => { - const result = client.matchBucketFromProjectLocationBucketName(fakePath); - assert.strictEqual(result, "bucketValue"); - assert((client.pathTemplates.projectLocationBucketPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectLocationBucket', () => { + const fakePath = '/rendered/path/projectLocationBucket'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + bucket: 'bucketValue', + }; + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.projectLocationBucketPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectLocationBucketPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectLocationBucketPath', () => { + const result = client.projectLocationBucketPath( + 'projectValue', + 'locationValue', + 'bucketValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.projectLocationBucketPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectLocationBucketName', () => { + const result = + client.matchProjectFromProjectLocationBucketName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.projectLocationBucketPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromProjectLocationBucketName', () => { + const result = + client.matchLocationFromProjectLocationBucketName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + ( + client.pathTemplates.projectLocationBucketPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBucketFromProjectLocationBucketName', () => { + const result = + client.matchBucketFromProjectLocationBucketName(fakePath); + assert.strictEqual(result, 'bucketValue'); + assert( + ( + client.pathTemplates.projectLocationBucketPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectLocationBucketView', () => { - const fakePath = "/rendered/path/projectLocationBucketView"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - bucket: "bucketValue", - view: "viewValue", - }; - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.projectLocationBucketViewPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectLocationBucketViewPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectLocationBucketViewPath', () => { - const result = client.projectLocationBucketViewPath("projectValue", "locationValue", "bucketValue", "viewValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectLocationBucketViewPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectLocationBucketViewName', () => { - const result = client.matchProjectFromProjectLocationBucketViewName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectLocationBucketViewPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromProjectLocationBucketViewName', () => { - const result = client.matchLocationFromProjectLocationBucketViewName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.projectLocationBucketViewPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBucketFromProjectLocationBucketViewName', () => { - const result = client.matchBucketFromProjectLocationBucketViewName(fakePath); - assert.strictEqual(result, "bucketValue"); - assert((client.pathTemplates.projectLocationBucketViewPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchViewFromProjectLocationBucketViewName', () => { - const result = client.matchViewFromProjectLocationBucketViewName(fakePath); - assert.strictEqual(result, "viewValue"); - assert((client.pathTemplates.projectLocationBucketViewPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectLocationBucketView', () => { + const fakePath = '/rendered/path/projectLocationBucketView'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + bucket: 'bucketValue', + view: 'viewValue', + }; + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.projectLocationBucketViewPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectLocationBucketViewPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectLocationBucketViewPath', () => { + const result = client.projectLocationBucketViewPath( + 'projectValue', + 'locationValue', + 'bucketValue', + 'viewValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.projectLocationBucketViewPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectLocationBucketViewName', () => { + const result = + client.matchProjectFromProjectLocationBucketViewName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.projectLocationBucketViewPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromProjectLocationBucketViewName', () => { + const result = + client.matchLocationFromProjectLocationBucketViewName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + ( + client.pathTemplates.projectLocationBucketViewPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBucketFromProjectLocationBucketViewName', () => { + const result = + client.matchBucketFromProjectLocationBucketViewName(fakePath); + assert.strictEqual(result, 'bucketValue'); + assert( + ( + client.pathTemplates.projectLocationBucketViewPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchViewFromProjectLocationBucketViewName', () => { + const result = + client.matchViewFromProjectLocationBucketViewName(fakePath); + assert.strictEqual(result, 'viewValue'); + assert( + ( + client.pathTemplates.projectLocationBucketViewPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectLog', () => { - const fakePath = "/rendered/path/projectLog"; - const expectedParameters = { - project: "projectValue", - log: "logValue", - }; - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.projectLogPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectLogPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectLogPath', () => { - const result = client.projectLogPath("projectValue", "logValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectLogPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectLogName', () => { - const result = client.matchProjectFromProjectLogName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectLogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLogFromProjectLogName', () => { - const result = client.matchLogFromProjectLogName(fakePath); - assert.strictEqual(result, "logValue"); - assert((client.pathTemplates.projectLogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectLog', () => { + const fakePath = '/rendered/path/projectLog'; + const expectedParameters = { + project: 'projectValue', + log: 'logValue', + }; + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.projectLogPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectLogPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectLogPath', () => { + const result = client.projectLogPath('projectValue', 'logValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.projectLogPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectLogName', () => { + const result = client.matchProjectFromProjectLogName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.projectLogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLogFromProjectLogName', () => { + const result = client.matchLogFromProjectLogName(fakePath); + assert.strictEqual(result, 'logValue'); + assert( + (client.pathTemplates.projectLogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectSettings', () => { - const fakePath = "/rendered/path/projectSettings"; - const expectedParameters = { - project: "projectValue", - }; - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.projectSettingsPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectSettingsPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectSettingsPath', () => { - const result = client.projectSettingsPath("projectValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectSettingsPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectSettingsName', () => { - const result = client.matchProjectFromProjectSettingsName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectSettingsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectSettings', () => { + const fakePath = '/rendered/path/projectSettings'; + const expectedParameters = { + project: 'projectValue', + }; + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.projectSettingsPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectSettingsPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectSettingsPath', () => { + const result = client.projectSettingsPath('projectValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.projectSettingsPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectSettingsName', () => { + const result = client.matchProjectFromProjectSettingsName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.projectSettingsPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectSink', () => { - const fakePath = "/rendered/path/projectSink"; - const expectedParameters = { - project: "projectValue", - sink: "sinkValue", - }; - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.projectSinkPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectSinkPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectSinkPath', () => { - const result = client.projectSinkPath("projectValue", "sinkValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectSinkPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectSinkName', () => { - const result = client.matchProjectFromProjectSinkName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectSinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchSinkFromProjectSinkName', () => { - const result = client.matchSinkFromProjectSinkName(fakePath); - assert.strictEqual(result, "sinkValue"); - assert((client.pathTemplates.projectSinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectSink', () => { + const fakePath = '/rendered/path/projectSink'; + const expectedParameters = { + project: 'projectValue', + sink: 'sinkValue', + }; + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.projectSinkPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectSinkPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectSinkPath', () => { + const result = client.projectSinkPath('projectValue', 'sinkValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.projectSinkPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectSinkName', () => { + const result = client.matchProjectFromProjectSinkName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.projectSinkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchSinkFromProjectSinkName', () => { + const result = client.matchSinkFromProjectSinkName(fakePath); + assert.strictEqual(result, 'sinkValue'); + assert( + (client.pathTemplates.projectSinkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/core/generator/gapic-generator-typescript/baselines/logging-esm/esm/test/gapic_metrics_service_v2_v2.ts.baseline b/core/generator/gapic-generator-typescript/baselines/logging-esm/esm/test/gapic_metrics_service_v2_v2.ts.baseline index c03485d10852..badd3b3fd54b 100644 --- a/core/generator/gapic-generator-typescript/baselines/logging-esm/esm/test/gapic_metrics_service_v2_v2.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/logging-esm/esm/test/gapic_metrics_service_v2_v2.ts.baseline @@ -20,16 +20,16 @@ import * as protos from '../../protos/protos.js'; import assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as metricsservicev2Module from '../src/index.js'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; -import {protobuf} from 'google-gax'; +import { protobuf } from 'google-gax'; import fs from 'fs'; import path from 'path'; -import {fileURLToPath} from 'url'; +import { fileURLToPath } from 'url'; // @ts-ignore const dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -37,2078 +37,2972 @@ const dirname = path.dirname(fileURLToPath(import.meta.url)); // to fill in default values for request objects const root = protobuf.Root.fromJSON( JSON.parse( - fs.readFileSync(path.join(dirname, '..', '..', 'protos/protos.json'), 'utf8') - )) + fs.readFileSync( + path.join(dirname, '..', '..', 'protos/protos.json'), + 'utf8', + ), + ), +); // eslint-disable-next-line @typescript-eslint/no-unused-vars function getTypeDefaultValue(typeName: string, fields: string[]) { - let type = root.lookupType(typeName) as protobuf.Type; - for (const field of fields.slice(0, -1)) { - type = type?.fields[field]?.resolvedType as protobuf.Type; - } - return type?.fields[fields[fields.length - 1]]?.defaultValue ?? null; + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type?.fields[field]?.resolvedType as protobuf.Type; + } + return type?.fields[fields[fields.length - 1]]?.defaultValue ?? null; } function generateSampleMessage(instance: T) { - const filledObject = (instance.constructor as typeof protobuf.Message) - .toObject(instance as protobuf.Message, {defaults: true}); - return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, { defaults: true }); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; } function stubSimpleCall(response?: ResponseType, error?: Error) { - return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); } -function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { - return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +function stubSimpleCallWithCallback( + response?: ResponseType, + error?: Error, +) { + return error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); } -function stubPageStreamingCall(responses?: ResponseType[], error?: Error) { - const pagingStub = sinon.stub(); - if (responses) { - for (let i = 0; i < responses.length; ++i) { - pagingStub.onCall(i).callsArgWith(2, null, responses[i]); - } +function stubPageStreamingCall( + responses?: ResponseType[], + error?: Error, +) { + const pagingStub = sinon.stub(); + if (responses) { + for (let i = 0; i < responses.length; ++i) { + pagingStub.onCall(i).callsArgWith(2, null, responses[i]); } - const transformStub = error ? sinon.stub().callsArgWith(2, error) : pagingStub; - const mockStream = new PassThrough({ - objectMode: true, - transform: transformStub, - }); - // trigger as many responses as needed - if (responses) { - for (let i = 0; i < responses.length; ++i) { - setImmediate(() => { mockStream.write({}); }); - } - setImmediate(() => { mockStream.end(); }); - } else { - setImmediate(() => { mockStream.write({}); }); - setImmediate(() => { mockStream.end(); }); + } + const transformStub = error + ? sinon.stub().callsArgWith(2, error) + : pagingStub; + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + // trigger as many responses as needed + if (responses) { + for (let i = 0; i < responses.length; ++i) { + setImmediate(() => { + mockStream.write({}); + }); } - return sinon.stub().returns(mockStream); + setImmediate(() => { + mockStream.end(); + }); + } else { + setImmediate(() => { + mockStream.write({}); + }); + setImmediate(() => { + mockStream.end(); + }); + } + return sinon.stub().returns(mockStream); } -function stubAsyncIterationCall(responses?: ResponseType[], error?: Error) { - let counter = 0; - const asyncIterable = { - [Symbol.asyncIterator]() { - return { - async next() { - if (error) { - return Promise.reject(error); - } - if (counter >= responses!.length) { - return Promise.resolve({done: true, value: undefined}); - } - return Promise.resolve({done: false, value: responses![counter++]}); - } - }; - } - }; - return sinon.stub().returns(asyncIterable); +function stubAsyncIterationCall( + responses?: ResponseType[], + error?: Error, +) { + let counter = 0; + const asyncIterable = { + [Symbol.asyncIterator]() { + return { + async next() { + if (error) { + return Promise.reject(error); + } + if (counter >= responses!.length) { + return Promise.resolve({ done: true, value: undefined }); + } + return Promise.resolve({ done: false, value: responses![counter++] }); + }, + }; + }, + }; + return sinon.stub().returns(asyncIterable); } describe('v2.MetricsServiceV2Client', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new metricsservicev2Module.v2.MetricsServiceV2Client(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'logging.googleapis.com'); - }); - - it('has universeDomain', () => { - const client = new metricsservicev2Module.v2.MetricsServiceV2Client(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); - - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - it('throws DeprecationWarning if static servicePath is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const servicePath = metricsservicev2Module.v2.MetricsServiceV2Client.servicePath; - assert.strictEqual(servicePath, 'logging.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = metricsservicev2Module.v2.MetricsServiceV2Client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'logging.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'logging.example.com'); - }); - - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'logging.example.com'); - }); - - if (typeof process === 'object' && 'env' in process) { - describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { - it('sets apiEndpoint from environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new metricsservicev2Module.v2.MetricsServiceV2Client(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'logging.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - - it('value configured in code has priority over environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'logging.configured.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { new metricsservicev2Module.v2.MetricsServiceV2Client({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); - - it('has port', () => { - const port = metricsservicev2Module.v2.MetricsServiceV2Client.port; - assert(port); - assert(typeof port === 'number'); - }); - - it('should create a client with no option', () => { - const client = new metricsservicev2Module.v2.MetricsServiceV2Client(); - assert(client); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new metricsservicev2Module.v2.MetricsServiceV2Client(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'logging.googleapis.com'); + }); - it('should create a client with gRPC fallback', () => { - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - fallback: true, - }); - assert(client); - }); + it('has universeDomain', () => { + const client = new metricsservicev2Module.v2.MetricsServiceV2Client(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - it('has initialize method and supports deferred initialization', async () => { - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.metricsServiceV2Stub, undefined); - await client.initialize(); - assert(client.metricsServiceV2Stub); - }); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = + metricsservicev2Module.v2.MetricsServiceV2Client.servicePath; + assert.strictEqual(servicePath, 'logging.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + metricsservicev2Module.v2.MetricsServiceV2Client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'logging.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + universeDomain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'logging.example.com'); + }); - it('has close method for the initialized client', done => { - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.metricsServiceV2Stub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + universe_domain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'logging.example.com'); + }); - it('has close method for the non-initialized client', done => { - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.metricsServiceV2Stub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); + if (typeof process === 'object' && 'env' in process) { + describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { + it('sets apiEndpoint from environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new metricsservicev2Module.v2.MetricsServiceV2Client(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'logging.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } + }); + + it('value configured in code has priority over environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + universeDomain: 'configured.example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'logging.configured.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } + }); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new metricsservicev2Module.v2.MetricsServiceV2Client({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); - }); + it('has port', () => { + const port = metricsservicev2Module.v2.MetricsServiceV2Client.port; + assert(port); + assert(typeof port === 'number'); + }); - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId((err?: Error|null, projectId?: string|null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } - }); - }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); - }); + it('should create a client with no option', () => { + const client = new metricsservicev2Module.v2.MetricsServiceV2Client(); + assert(client); }); - describe('getLogMetric', () => { - it('invokes getLogMetric without error', async () => { - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.GetLogMetricRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.GetLogMetricRequest', ['metricName']); - request.metricName = defaultValue1; - const expectedHeaderRequestParams = `metric_name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.logging.v2.LogMetric() - ); - client.innerApiCalls.getLogMetric = stubSimpleCall(expectedResponse); - const [response] = await client.getLogMetric(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getLogMetric as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getLogMetric as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('should create a client with gRPC fallback', () => { + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + fallback: true, + }); + assert(client); + }); - it('invokes getLogMetric without error using callback', async () => { - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.GetLogMetricRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.GetLogMetricRequest', ['metricName']); - request.metricName = defaultValue1; - const expectedHeaderRequestParams = `metric_name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.logging.v2.LogMetric() - ); - client.innerApiCalls.getLogMetric = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getLogMetric( - request, - (err?: Error|null, result?: protos.google.logging.v2.ILogMetric|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getLogMetric as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getLogMetric as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has initialize method and supports deferred initialization', async () => { + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.metricsServiceV2Stub, undefined); + await client.initialize(); + assert(client.metricsServiceV2Stub); + }); - it('invokes getLogMetric with error', async () => { - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.GetLogMetricRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.GetLogMetricRequest', ['metricName']); - request.metricName = defaultValue1; - const expectedHeaderRequestParams = `metric_name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getLogMetric = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getLogMetric(request), expectedError); - const actualRequest = (client.innerApiCalls.getLogMetric as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getLogMetric as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('has close method for the initialized client', (done) => { + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.metricsServiceV2Stub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes getLogMetric with closed client', async () => { - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.GetLogMetricRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.GetLogMetricRequest', ['metricName']); - request.metricName = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getLogMetric(request), expectedError); + it('has close method for the non-initialized client', (done) => { + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.metricsServiceV2Stub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); }); - describe('createLogMetric', () => { - it('invokes createLogMetric without error', async () => { - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.CreateLogMetricRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.CreateLogMetricRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.logging.v2.LogMetric() - ); - client.innerApiCalls.createLogMetric = stubSimpleCall(expectedResponse); - const [response] = await client.createLogMetric(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createLogMetric as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createLogMetric as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + }); - it('invokes createLogMetric without error using callback', async () => { - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.CreateLogMetricRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.CreateLogMetricRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.logging.v2.LogMetric() - ); - client.innerApiCalls.createLogMetric = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createLogMetric( - request, - (err?: Error|null, result?: protos.google.logging.v2.ILogMetric|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createLogMetric as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createLogMetric as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } + }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + }); + + describe('getLogMetric', () => { + it('invokes getLogMetric without error', async () => { + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.GetLogMetricRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.GetLogMetricRequest', + ['metricName'], + ); + request.metricName = defaultValue1; + const expectedHeaderRequestParams = `metric_name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.logging.v2.LogMetric(), + ); + client.innerApiCalls.getLogMetric = stubSimpleCall(expectedResponse); + const [response] = await client.getLogMetric(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getLogMetric as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getLogMetric as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createLogMetric with error', async () => { - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.CreateLogMetricRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.CreateLogMetricRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createLogMetric = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createLogMetric(request), expectedError); - const actualRequest = (client.innerApiCalls.createLogMetric as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createLogMetric as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getLogMetric without error using callback', async () => { + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.GetLogMetricRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.GetLogMetricRequest', + ['metricName'], + ); + request.metricName = defaultValue1; + const expectedHeaderRequestParams = `metric_name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.logging.v2.LogMetric(), + ); + client.innerApiCalls.getLogMetric = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getLogMetric( + request, + ( + err?: Error | null, + result?: protos.google.logging.v2.ILogMetric | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getLogMetric as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getLogMetric as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createLogMetric with closed client', async () => { - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.CreateLogMetricRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.CreateLogMetricRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createLogMetric(request), expectedError); - }); + it('invokes getLogMetric with error', async () => { + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.GetLogMetricRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.GetLogMetricRequest', + ['metricName'], + ); + request.metricName = defaultValue1; + const expectedHeaderRequestParams = `metric_name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getLogMetric = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getLogMetric(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getLogMetric as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getLogMetric as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('updateLogMetric', () => { - it('invokes updateLogMetric without error', async () => { - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.UpdateLogMetricRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.UpdateLogMetricRequest', ['metricName']); - request.metricName = defaultValue1; - const expectedHeaderRequestParams = `metric_name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.logging.v2.LogMetric() - ); - client.innerApiCalls.updateLogMetric = stubSimpleCall(expectedResponse); - const [response] = await client.updateLogMetric(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateLogMetric as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateLogMetric as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getLogMetric with closed client', async () => { + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.GetLogMetricRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.GetLogMetricRequest', + ['metricName'], + ); + request.metricName = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getLogMetric(request), expectedError); + }); + }); + + describe('createLogMetric', () => { + it('invokes createLogMetric without error', async () => { + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.CreateLogMetricRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.CreateLogMetricRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.logging.v2.LogMetric(), + ); + client.innerApiCalls.createLogMetric = stubSimpleCall(expectedResponse); + const [response] = await client.createLogMetric(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createLogMetric as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createLogMetric as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateLogMetric without error using callback', async () => { - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.UpdateLogMetricRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.UpdateLogMetricRequest', ['metricName']); - request.metricName = defaultValue1; - const expectedHeaderRequestParams = `metric_name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.logging.v2.LogMetric() - ); - client.innerApiCalls.updateLogMetric = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateLogMetric( - request, - (err?: Error|null, result?: protos.google.logging.v2.ILogMetric|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateLogMetric as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateLogMetric as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createLogMetric without error using callback', async () => { + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.CreateLogMetricRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.CreateLogMetricRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.logging.v2.LogMetric(), + ); + client.innerApiCalls.createLogMetric = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createLogMetric( + request, + ( + err?: Error | null, + result?: protos.google.logging.v2.ILogMetric | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createLogMetric as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createLogMetric as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateLogMetric with error', async () => { - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.UpdateLogMetricRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.UpdateLogMetricRequest', ['metricName']); - request.metricName = defaultValue1; - const expectedHeaderRequestParams = `metric_name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateLogMetric = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateLogMetric(request), expectedError); - const actualRequest = (client.innerApiCalls.updateLogMetric as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateLogMetric as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createLogMetric with error', async () => { + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.CreateLogMetricRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.CreateLogMetricRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createLogMetric = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.createLogMetric(request), expectedError); + const actualRequest = ( + client.innerApiCalls.createLogMetric as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createLogMetric as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateLogMetric with closed client', async () => { - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.UpdateLogMetricRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.UpdateLogMetricRequest', ['metricName']); - request.metricName = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateLogMetric(request), expectedError); - }); + it('invokes createLogMetric with closed client', async () => { + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.CreateLogMetricRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.CreateLogMetricRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.createLogMetric(request), expectedError); + }); + }); + + describe('updateLogMetric', () => { + it('invokes updateLogMetric without error', async () => { + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.UpdateLogMetricRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.UpdateLogMetricRequest', + ['metricName'], + ); + request.metricName = defaultValue1; + const expectedHeaderRequestParams = `metric_name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.logging.v2.LogMetric(), + ); + client.innerApiCalls.updateLogMetric = stubSimpleCall(expectedResponse); + const [response] = await client.updateLogMetric(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateLogMetric as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateLogMetric as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('deleteLogMetric', () => { - it('invokes deleteLogMetric without error', async () => { - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.DeleteLogMetricRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.DeleteLogMetricRequest', ['metricName']); - request.metricName = defaultValue1; - const expectedHeaderRequestParams = `metric_name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteLogMetric = stubSimpleCall(expectedResponse); - const [response] = await client.deleteLogMetric(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteLogMetric as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteLogMetric as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateLogMetric without error using callback', async () => { + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.UpdateLogMetricRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.UpdateLogMetricRequest', + ['metricName'], + ); + request.metricName = defaultValue1; + const expectedHeaderRequestParams = `metric_name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.logging.v2.LogMetric(), + ); + client.innerApiCalls.updateLogMetric = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateLogMetric( + request, + ( + err?: Error | null, + result?: protos.google.logging.v2.ILogMetric | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateLogMetric as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateLogMetric as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteLogMetric without error using callback', async () => { - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.DeleteLogMetricRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.DeleteLogMetricRequest', ['metricName']); - request.metricName = defaultValue1; - const expectedHeaderRequestParams = `metric_name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteLogMetric = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteLogMetric( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteLogMetric as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteLogMetric as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateLogMetric with error', async () => { + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.UpdateLogMetricRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.UpdateLogMetricRequest', + ['metricName'], + ); + request.metricName = defaultValue1; + const expectedHeaderRequestParams = `metric_name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateLogMetric = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.updateLogMetric(request), expectedError); + const actualRequest = ( + client.innerApiCalls.updateLogMetric as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateLogMetric as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteLogMetric with error', async () => { - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.DeleteLogMetricRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.DeleteLogMetricRequest', ['metricName']); - request.metricName = defaultValue1; - const expectedHeaderRequestParams = `metric_name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteLogMetric = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteLogMetric(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteLogMetric as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteLogMetric as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateLogMetric with closed client', async () => { + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.UpdateLogMetricRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.UpdateLogMetricRequest', + ['metricName'], + ); + request.metricName = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.updateLogMetric(request), expectedError); + }); + }); + + describe('deleteLogMetric', () => { + it('invokes deleteLogMetric without error', async () => { + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.DeleteLogMetricRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.DeleteLogMetricRequest', + ['metricName'], + ); + request.metricName = defaultValue1; + const expectedHeaderRequestParams = `metric_name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteLogMetric = stubSimpleCall(expectedResponse); + const [response] = await client.deleteLogMetric(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteLogMetric as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteLogMetric as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteLogMetric with closed client', async () => { - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.DeleteLogMetricRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.DeleteLogMetricRequest', ['metricName']); - request.metricName = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteLogMetric(request), expectedError); - }); + it('invokes deleteLogMetric without error using callback', async () => { + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.DeleteLogMetricRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.DeleteLogMetricRequest', + ['metricName'], + ); + request.metricName = defaultValue1; + const expectedHeaderRequestParams = `metric_name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteLogMetric = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteLogMetric( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteLogMetric as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteLogMetric as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('listLogMetrics', () => { - it('invokes listLogMetrics without error', async () => { - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.ListLogMetricsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.ListLogMetricsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.logging.v2.LogMetric()), - generateSampleMessage(new protos.google.logging.v2.LogMetric()), - generateSampleMessage(new protos.google.logging.v2.LogMetric()), - ]; - client.innerApiCalls.listLogMetrics = stubSimpleCall(expectedResponse); - const [response] = await client.listLogMetrics(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listLogMetrics as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listLogMetrics as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteLogMetric with error', async () => { + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.DeleteLogMetricRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.DeleteLogMetricRequest', + ['metricName'], + ); + request.metricName = defaultValue1; + const expectedHeaderRequestParams = `metric_name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteLogMetric = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.deleteLogMetric(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteLogMetric as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteLogMetric as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listLogMetrics without error using callback', async () => { - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.ListLogMetricsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.ListLogMetricsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.logging.v2.LogMetric()), - generateSampleMessage(new protos.google.logging.v2.LogMetric()), - generateSampleMessage(new protos.google.logging.v2.LogMetric()), - ]; - client.innerApiCalls.listLogMetrics = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listLogMetrics( - request, - (err?: Error|null, result?: protos.google.logging.v2.ILogMetric[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listLogMetrics as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listLogMetrics as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteLogMetric with closed client', async () => { + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.DeleteLogMetricRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.DeleteLogMetricRequest', + ['metricName'], + ); + request.metricName = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.deleteLogMetric(request), expectedError); + }); + }); + + describe('listLogMetrics', () => { + it('invokes listLogMetrics without error', async () => { + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.ListLogMetricsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.ListLogMetricsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.logging.v2.LogMetric()), + generateSampleMessage(new protos.google.logging.v2.LogMetric()), + generateSampleMessage(new protos.google.logging.v2.LogMetric()), + ]; + client.innerApiCalls.listLogMetrics = stubSimpleCall(expectedResponse); + const [response] = await client.listLogMetrics(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listLogMetrics as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listLogMetrics as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listLogMetrics with error', async () => { - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.ListLogMetricsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.ListLogMetricsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listLogMetrics = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listLogMetrics(request), expectedError); - const actualRequest = (client.innerApiCalls.listLogMetrics as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listLogMetrics as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listLogMetrics without error using callback', async () => { + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.ListLogMetricsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.ListLogMetricsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.logging.v2.LogMetric()), + generateSampleMessage(new protos.google.logging.v2.LogMetric()), + generateSampleMessage(new protos.google.logging.v2.LogMetric()), + ]; + client.innerApiCalls.listLogMetrics = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listLogMetrics( + request, + ( + err?: Error | null, + result?: protos.google.logging.v2.ILogMetric[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listLogMetrics as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listLogMetrics as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listLogMetricsStream without error', async () => { - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.ListLogMetricsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.ListLogMetricsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.logging.v2.LogMetric()), - generateSampleMessage(new protos.google.logging.v2.LogMetric()), - generateSampleMessage(new protos.google.logging.v2.LogMetric()), - ]; - client.descriptors.page.listLogMetrics.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listLogMetricsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.logging.v2.LogMetric[] = []; - stream.on('data', (response: protos.google.logging.v2.LogMetric) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.listLogMetrics.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listLogMetrics, request)); - assert( - (client.descriptors.page.listLogMetrics.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listLogMetrics with error', async () => { + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.ListLogMetricsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.ListLogMetricsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listLogMetrics = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listLogMetrics(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listLogMetrics as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listLogMetrics as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listLogMetricsStream with error', async () => { - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.ListLogMetricsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.ListLogMetricsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listLogMetrics.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listLogMetricsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.logging.v2.LogMetric[] = []; - stream.on('data', (response: protos.google.logging.v2.LogMetric) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listLogMetrics.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listLogMetrics, request)); - assert( - (client.descriptors.page.listLogMetrics.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listLogMetricsStream without error', async () => { + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.ListLogMetricsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.ListLogMetricsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.logging.v2.LogMetric()), + generateSampleMessage(new protos.google.logging.v2.LogMetric()), + generateSampleMessage(new protos.google.logging.v2.LogMetric()), + ]; + client.descriptors.page.listLogMetrics.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listLogMetricsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.logging.v2.LogMetric[] = []; + stream.on('data', (response: protos.google.logging.v2.LogMetric) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listLogMetrics.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listLogMetrics, request), + ); + assert( + (client.descriptors.page.listLogMetrics.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('uses async iteration with listLogMetrics without error', async () => { - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.ListLogMetricsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.ListLogMetricsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.logging.v2.LogMetric()), - generateSampleMessage(new protos.google.logging.v2.LogMetric()), - generateSampleMessage(new protos.google.logging.v2.LogMetric()), - ]; - client.descriptors.page.listLogMetrics.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.logging.v2.ILogMetric[] = []; - const iterable = client.listLogMetricsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listLogMetrics.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listLogMetrics.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listLogMetricsStream with error', async () => { + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.ListLogMetricsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.ListLogMetricsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listLogMetrics.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listLogMetricsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.logging.v2.LogMetric[] = []; + stream.on('data', (response: protos.google.logging.v2.LogMetric) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listLogMetrics.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listLogMetrics, request), + ); + assert( + (client.descriptors.page.listLogMetrics.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('uses async iteration with listLogMetrics with error', async () => { - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.ListLogMetricsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.ListLogMetricsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listLogMetrics.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listLogMetricsAsync(request); - await assert.rejects(async () => { - const responses: protos.google.logging.v2.ILogMetric[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listLogMetrics.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listLogMetrics.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listLogMetrics without error', async () => { + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.ListLogMetricsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.ListLogMetricsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.logging.v2.LogMetric()), + generateSampleMessage(new protos.google.logging.v2.LogMetric()), + generateSampleMessage(new protos.google.logging.v2.LogMetric()), + ]; + client.descriptors.page.listLogMetrics.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.logging.v2.ILogMetric[] = []; + const iterable = client.listLogMetricsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listLogMetrics.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listLogMetrics.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); }); - describe('Path templates', () => { - - describe('billingAccountCmekSettings', () => { - const fakePath = "/rendered/path/billingAccountCmekSettings"; - const expectedParameters = { - billing_account: "billingAccountValue", - }; - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.billingAccountCmekSettingsPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.billingAccountCmekSettingsPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('billingAccountCmekSettingsPath', () => { - const result = client.billingAccountCmekSettingsPath("billingAccountValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.billingAccountCmekSettingsPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchBillingAccountFromBillingAccountCmekSettingsName', () => { - const result = client.matchBillingAccountFromBillingAccountCmekSettingsName(fakePath); - assert.strictEqual(result, "billingAccountValue"); - assert((client.pathTemplates.billingAccountCmekSettingsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('uses async iteration with listLogMetrics with error', async () => { + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.ListLogMetricsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.ListLogMetricsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listLogMetrics.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listLogMetricsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.logging.v2.ILogMetric[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listLogMetrics.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listLogMetrics.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + }); + + describe('Path templates', () => { + describe('billingAccountCmekSettings', () => { + const fakePath = '/rendered/path/billingAccountCmekSettings'; + const expectedParameters = { + billing_account: 'billingAccountValue', + }; + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.billingAccountCmekSettingsPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.billingAccountCmekSettingsPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('billingAccountCmekSettingsPath', () => { + const result = client.billingAccountCmekSettingsPath( + 'billingAccountValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.billingAccountCmekSettingsPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchBillingAccountFromBillingAccountCmekSettingsName', () => { + const result = + client.matchBillingAccountFromBillingAccountCmekSettingsName( + fakePath, + ); + assert.strictEqual(result, 'billingAccountValue'); + assert( + ( + client.pathTemplates.billingAccountCmekSettingsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('billingAccountExclusion', () => { - const fakePath = "/rendered/path/billingAccountExclusion"; - const expectedParameters = { - billing_account: "billingAccountValue", - exclusion: "exclusionValue", - }; - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.billingAccountExclusionPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.billingAccountExclusionPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('billingAccountExclusionPath', () => { - const result = client.billingAccountExclusionPath("billingAccountValue", "exclusionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.billingAccountExclusionPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchBillingAccountFromBillingAccountExclusionName', () => { - const result = client.matchBillingAccountFromBillingAccountExclusionName(fakePath); - assert.strictEqual(result, "billingAccountValue"); - assert((client.pathTemplates.billingAccountExclusionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchExclusionFromBillingAccountExclusionName', () => { - const result = client.matchExclusionFromBillingAccountExclusionName(fakePath); - assert.strictEqual(result, "exclusionValue"); - assert((client.pathTemplates.billingAccountExclusionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('billingAccountExclusion', () => { + const fakePath = '/rendered/path/billingAccountExclusion'; + const expectedParameters = { + billing_account: 'billingAccountValue', + exclusion: 'exclusionValue', + }; + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.billingAccountExclusionPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.billingAccountExclusionPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('billingAccountExclusionPath', () => { + const result = client.billingAccountExclusionPath( + 'billingAccountValue', + 'exclusionValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.billingAccountExclusionPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchBillingAccountFromBillingAccountExclusionName', () => { + const result = + client.matchBillingAccountFromBillingAccountExclusionName(fakePath); + assert.strictEqual(result, 'billingAccountValue'); + assert( + ( + client.pathTemplates.billingAccountExclusionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchExclusionFromBillingAccountExclusionName', () => { + const result = + client.matchExclusionFromBillingAccountExclusionName(fakePath); + assert.strictEqual(result, 'exclusionValue'); + assert( + ( + client.pathTemplates.billingAccountExclusionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('billingAccountLocationBucket', () => { - const fakePath = "/rendered/path/billingAccountLocationBucket"; - const expectedParameters = { - billing_account: "billingAccountValue", - location: "locationValue", - bucket: "bucketValue", - }; - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.billingAccountLocationBucketPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.billingAccountLocationBucketPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('billingAccountLocationBucketPath', () => { - const result = client.billingAccountLocationBucketPath("billingAccountValue", "locationValue", "bucketValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.billingAccountLocationBucketPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchBillingAccountFromBillingAccountLocationBucketName', () => { - const result = client.matchBillingAccountFromBillingAccountLocationBucketName(fakePath); - assert.strictEqual(result, "billingAccountValue"); - assert((client.pathTemplates.billingAccountLocationBucketPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromBillingAccountLocationBucketName', () => { - const result = client.matchLocationFromBillingAccountLocationBucketName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.billingAccountLocationBucketPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBucketFromBillingAccountLocationBucketName', () => { - const result = client.matchBucketFromBillingAccountLocationBucketName(fakePath); - assert.strictEqual(result, "bucketValue"); - assert((client.pathTemplates.billingAccountLocationBucketPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('billingAccountLocationBucket', () => { + const fakePath = '/rendered/path/billingAccountLocationBucket'; + const expectedParameters = { + billing_account: 'billingAccountValue', + location: 'locationValue', + bucket: 'bucketValue', + }; + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.billingAccountLocationBucketPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.billingAccountLocationBucketPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('billingAccountLocationBucketPath', () => { + const result = client.billingAccountLocationBucketPath( + 'billingAccountValue', + 'locationValue', + 'bucketValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.billingAccountLocationBucketPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchBillingAccountFromBillingAccountLocationBucketName', () => { + const result = + client.matchBillingAccountFromBillingAccountLocationBucketName( + fakePath, + ); + assert.strictEqual(result, 'billingAccountValue'); + assert( + ( + client.pathTemplates.billingAccountLocationBucketPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromBillingAccountLocationBucketName', () => { + const result = + client.matchLocationFromBillingAccountLocationBucketName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + ( + client.pathTemplates.billingAccountLocationBucketPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBucketFromBillingAccountLocationBucketName', () => { + const result = + client.matchBucketFromBillingAccountLocationBucketName(fakePath); + assert.strictEqual(result, 'bucketValue'); + assert( + ( + client.pathTemplates.billingAccountLocationBucketPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('billingAccountLocationBucketView', () => { - const fakePath = "/rendered/path/billingAccountLocationBucketView"; - const expectedParameters = { - billing_account: "billingAccountValue", - location: "locationValue", - bucket: "bucketValue", - view: "viewValue", - }; - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.billingAccountLocationBucketViewPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.billingAccountLocationBucketViewPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('billingAccountLocationBucketViewPath', () => { - const result = client.billingAccountLocationBucketViewPath("billingAccountValue", "locationValue", "bucketValue", "viewValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.billingAccountLocationBucketViewPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchBillingAccountFromBillingAccountLocationBucketViewName', () => { - const result = client.matchBillingAccountFromBillingAccountLocationBucketViewName(fakePath); - assert.strictEqual(result, "billingAccountValue"); - assert((client.pathTemplates.billingAccountLocationBucketViewPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromBillingAccountLocationBucketViewName', () => { - const result = client.matchLocationFromBillingAccountLocationBucketViewName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.billingAccountLocationBucketViewPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBucketFromBillingAccountLocationBucketViewName', () => { - const result = client.matchBucketFromBillingAccountLocationBucketViewName(fakePath); - assert.strictEqual(result, "bucketValue"); - assert((client.pathTemplates.billingAccountLocationBucketViewPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchViewFromBillingAccountLocationBucketViewName', () => { - const result = client.matchViewFromBillingAccountLocationBucketViewName(fakePath); - assert.strictEqual(result, "viewValue"); - assert((client.pathTemplates.billingAccountLocationBucketViewPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('billingAccountLocationBucketView', () => { + const fakePath = '/rendered/path/billingAccountLocationBucketView'; + const expectedParameters = { + billing_account: 'billingAccountValue', + location: 'locationValue', + bucket: 'bucketValue', + view: 'viewValue', + }; + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.billingAccountLocationBucketViewPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.billingAccountLocationBucketViewPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('billingAccountLocationBucketViewPath', () => { + const result = client.billingAccountLocationBucketViewPath( + 'billingAccountValue', + 'locationValue', + 'bucketValue', + 'viewValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.billingAccountLocationBucketViewPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchBillingAccountFromBillingAccountLocationBucketViewName', () => { + const result = + client.matchBillingAccountFromBillingAccountLocationBucketViewName( + fakePath, + ); + assert.strictEqual(result, 'billingAccountValue'); + assert( + ( + client.pathTemplates.billingAccountLocationBucketViewPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromBillingAccountLocationBucketViewName', () => { + const result = + client.matchLocationFromBillingAccountLocationBucketViewName( + fakePath, + ); + assert.strictEqual(result, 'locationValue'); + assert( + ( + client.pathTemplates.billingAccountLocationBucketViewPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBucketFromBillingAccountLocationBucketViewName', () => { + const result = + client.matchBucketFromBillingAccountLocationBucketViewName(fakePath); + assert.strictEqual(result, 'bucketValue'); + assert( + ( + client.pathTemplates.billingAccountLocationBucketViewPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchViewFromBillingAccountLocationBucketViewName', () => { + const result = + client.matchViewFromBillingAccountLocationBucketViewName(fakePath); + assert.strictEqual(result, 'viewValue'); + assert( + ( + client.pathTemplates.billingAccountLocationBucketViewPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('billingAccountLog', () => { - const fakePath = "/rendered/path/billingAccountLog"; - const expectedParameters = { - billing_account: "billingAccountValue", - log: "logValue", - }; - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.billingAccountLogPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.billingAccountLogPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('billingAccountLogPath', () => { - const result = client.billingAccountLogPath("billingAccountValue", "logValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.billingAccountLogPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchBillingAccountFromBillingAccountLogName', () => { - const result = client.matchBillingAccountFromBillingAccountLogName(fakePath); - assert.strictEqual(result, "billingAccountValue"); - assert((client.pathTemplates.billingAccountLogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLogFromBillingAccountLogName', () => { - const result = client.matchLogFromBillingAccountLogName(fakePath); - assert.strictEqual(result, "logValue"); - assert((client.pathTemplates.billingAccountLogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('billingAccountLog', () => { + const fakePath = '/rendered/path/billingAccountLog'; + const expectedParameters = { + billing_account: 'billingAccountValue', + log: 'logValue', + }; + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.billingAccountLogPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.billingAccountLogPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('billingAccountLogPath', () => { + const result = client.billingAccountLogPath( + 'billingAccountValue', + 'logValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.billingAccountLogPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchBillingAccountFromBillingAccountLogName', () => { + const result = + client.matchBillingAccountFromBillingAccountLogName(fakePath); + assert.strictEqual(result, 'billingAccountValue'); + assert( + ( + client.pathTemplates.billingAccountLogPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLogFromBillingAccountLogName', () => { + const result = client.matchLogFromBillingAccountLogName(fakePath); + assert.strictEqual(result, 'logValue'); + assert( + ( + client.pathTemplates.billingAccountLogPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('billingAccountSettings', () => { - const fakePath = "/rendered/path/billingAccountSettings"; - const expectedParameters = { - billing_account: "billingAccountValue", - }; - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.billingAccountSettingsPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.billingAccountSettingsPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('billingAccountSettingsPath', () => { - const result = client.billingAccountSettingsPath("billingAccountValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.billingAccountSettingsPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchBillingAccountFromBillingAccountSettingsName', () => { - const result = client.matchBillingAccountFromBillingAccountSettingsName(fakePath); - assert.strictEqual(result, "billingAccountValue"); - assert((client.pathTemplates.billingAccountSettingsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('billingAccountSettings', () => { + const fakePath = '/rendered/path/billingAccountSettings'; + const expectedParameters = { + billing_account: 'billingAccountValue', + }; + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.billingAccountSettingsPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.billingAccountSettingsPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('billingAccountSettingsPath', () => { + const result = client.billingAccountSettingsPath('billingAccountValue'); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.billingAccountSettingsPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchBillingAccountFromBillingAccountSettingsName', () => { + const result = + client.matchBillingAccountFromBillingAccountSettingsName(fakePath); + assert.strictEqual(result, 'billingAccountValue'); + assert( + ( + client.pathTemplates.billingAccountSettingsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('billingAccountSink', () => { - const fakePath = "/rendered/path/billingAccountSink"; - const expectedParameters = { - billing_account: "billingAccountValue", - sink: "sinkValue", - }; - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.billingAccountSinkPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.billingAccountSinkPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('billingAccountSinkPath', () => { - const result = client.billingAccountSinkPath("billingAccountValue", "sinkValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.billingAccountSinkPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchBillingAccountFromBillingAccountSinkName', () => { - const result = client.matchBillingAccountFromBillingAccountSinkName(fakePath); - assert.strictEqual(result, "billingAccountValue"); - assert((client.pathTemplates.billingAccountSinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchSinkFromBillingAccountSinkName', () => { - const result = client.matchSinkFromBillingAccountSinkName(fakePath); - assert.strictEqual(result, "sinkValue"); - assert((client.pathTemplates.billingAccountSinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('billingAccountSink', () => { + const fakePath = '/rendered/path/billingAccountSink'; + const expectedParameters = { + billing_account: 'billingAccountValue', + sink: 'sinkValue', + }; + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.billingAccountSinkPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.billingAccountSinkPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('billingAccountSinkPath', () => { + const result = client.billingAccountSinkPath( + 'billingAccountValue', + 'sinkValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.billingAccountSinkPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchBillingAccountFromBillingAccountSinkName', () => { + const result = + client.matchBillingAccountFromBillingAccountSinkName(fakePath); + assert.strictEqual(result, 'billingAccountValue'); + assert( + ( + client.pathTemplates.billingAccountSinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchSinkFromBillingAccountSinkName', () => { + const result = client.matchSinkFromBillingAccountSinkName(fakePath); + assert.strictEqual(result, 'sinkValue'); + assert( + ( + client.pathTemplates.billingAccountSinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('folderCmekSettings', () => { - const fakePath = "/rendered/path/folderCmekSettings"; - const expectedParameters = { - folder: "folderValue", - }; - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.folderCmekSettingsPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderCmekSettingsPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderCmekSettingsPath', () => { - const result = client.folderCmekSettingsPath("folderValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderCmekSettingsPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderCmekSettingsName', () => { - const result = client.matchFolderFromFolderCmekSettingsName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderCmekSettingsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('folderCmekSettings', () => { + const fakePath = '/rendered/path/folderCmekSettings'; + const expectedParameters = { + folder: 'folderValue', + }; + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.folderCmekSettingsPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderCmekSettingsPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderCmekSettingsPath', () => { + const result = client.folderCmekSettingsPath('folderValue'); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.folderCmekSettingsPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderCmekSettingsName', () => { + const result = client.matchFolderFromFolderCmekSettingsName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + ( + client.pathTemplates.folderCmekSettingsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('folderExclusion', () => { - const fakePath = "/rendered/path/folderExclusion"; - const expectedParameters = { - folder: "folderValue", - exclusion: "exclusionValue", - }; - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.folderExclusionPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderExclusionPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderExclusionPath', () => { - const result = client.folderExclusionPath("folderValue", "exclusionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderExclusionPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderExclusionName', () => { - const result = client.matchFolderFromFolderExclusionName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderExclusionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchExclusionFromFolderExclusionName', () => { - const result = client.matchExclusionFromFolderExclusionName(fakePath); - assert.strictEqual(result, "exclusionValue"); - assert((client.pathTemplates.folderExclusionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('folderExclusion', () => { + const fakePath = '/rendered/path/folderExclusion'; + const expectedParameters = { + folder: 'folderValue', + exclusion: 'exclusionValue', + }; + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.folderExclusionPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderExclusionPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderExclusionPath', () => { + const result = client.folderExclusionPath( + 'folderValue', + 'exclusionValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.folderExclusionPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderExclusionName', () => { + const result = client.matchFolderFromFolderExclusionName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + (client.pathTemplates.folderExclusionPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchExclusionFromFolderExclusionName', () => { + const result = client.matchExclusionFromFolderExclusionName(fakePath); + assert.strictEqual(result, 'exclusionValue'); + assert( + (client.pathTemplates.folderExclusionPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('folderLocationBucket', () => { - const fakePath = "/rendered/path/folderLocationBucket"; - const expectedParameters = { - folder: "folderValue", - location: "locationValue", - bucket: "bucketValue", - }; - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.folderLocationBucketPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderLocationBucketPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderLocationBucketPath', () => { - const result = client.folderLocationBucketPath("folderValue", "locationValue", "bucketValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderLocationBucketPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderLocationBucketName', () => { - const result = client.matchFolderFromFolderLocationBucketName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderLocationBucketPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromFolderLocationBucketName', () => { - const result = client.matchLocationFromFolderLocationBucketName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.folderLocationBucketPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBucketFromFolderLocationBucketName', () => { - const result = client.matchBucketFromFolderLocationBucketName(fakePath); - assert.strictEqual(result, "bucketValue"); - assert((client.pathTemplates.folderLocationBucketPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('folderLocationBucket', () => { + const fakePath = '/rendered/path/folderLocationBucket'; + const expectedParameters = { + folder: 'folderValue', + location: 'locationValue', + bucket: 'bucketValue', + }; + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.folderLocationBucketPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderLocationBucketPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderLocationBucketPath', () => { + const result = client.folderLocationBucketPath( + 'folderValue', + 'locationValue', + 'bucketValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.folderLocationBucketPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderLocationBucketName', () => { + const result = client.matchFolderFromFolderLocationBucketName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + ( + client.pathTemplates.folderLocationBucketPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromFolderLocationBucketName', () => { + const result = + client.matchLocationFromFolderLocationBucketName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + ( + client.pathTemplates.folderLocationBucketPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBucketFromFolderLocationBucketName', () => { + const result = client.matchBucketFromFolderLocationBucketName(fakePath); + assert.strictEqual(result, 'bucketValue'); + assert( + ( + client.pathTemplates.folderLocationBucketPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('folderLocationBucketView', () => { - const fakePath = "/rendered/path/folderLocationBucketView"; - const expectedParameters = { - folder: "folderValue", - location: "locationValue", - bucket: "bucketValue", - view: "viewValue", - }; - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.folderLocationBucketViewPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderLocationBucketViewPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderLocationBucketViewPath', () => { - const result = client.folderLocationBucketViewPath("folderValue", "locationValue", "bucketValue", "viewValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderLocationBucketViewPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderLocationBucketViewName', () => { - const result = client.matchFolderFromFolderLocationBucketViewName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderLocationBucketViewPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromFolderLocationBucketViewName', () => { - const result = client.matchLocationFromFolderLocationBucketViewName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.folderLocationBucketViewPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBucketFromFolderLocationBucketViewName', () => { - const result = client.matchBucketFromFolderLocationBucketViewName(fakePath); - assert.strictEqual(result, "bucketValue"); - assert((client.pathTemplates.folderLocationBucketViewPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchViewFromFolderLocationBucketViewName', () => { - const result = client.matchViewFromFolderLocationBucketViewName(fakePath); - assert.strictEqual(result, "viewValue"); - assert((client.pathTemplates.folderLocationBucketViewPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('folderLocationBucketView', () => { + const fakePath = '/rendered/path/folderLocationBucketView'; + const expectedParameters = { + folder: 'folderValue', + location: 'locationValue', + bucket: 'bucketValue', + view: 'viewValue', + }; + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.folderLocationBucketViewPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderLocationBucketViewPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderLocationBucketViewPath', () => { + const result = client.folderLocationBucketViewPath( + 'folderValue', + 'locationValue', + 'bucketValue', + 'viewValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.folderLocationBucketViewPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderLocationBucketViewName', () => { + const result = + client.matchFolderFromFolderLocationBucketViewName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + ( + client.pathTemplates.folderLocationBucketViewPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromFolderLocationBucketViewName', () => { + const result = + client.matchLocationFromFolderLocationBucketViewName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + ( + client.pathTemplates.folderLocationBucketViewPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBucketFromFolderLocationBucketViewName', () => { + const result = + client.matchBucketFromFolderLocationBucketViewName(fakePath); + assert.strictEqual(result, 'bucketValue'); + assert( + ( + client.pathTemplates.folderLocationBucketViewPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchViewFromFolderLocationBucketViewName', () => { + const result = + client.matchViewFromFolderLocationBucketViewName(fakePath); + assert.strictEqual(result, 'viewValue'); + assert( + ( + client.pathTemplates.folderLocationBucketViewPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('folderLog', () => { - const fakePath = "/rendered/path/folderLog"; - const expectedParameters = { - folder: "folderValue", - log: "logValue", - }; - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.folderLogPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderLogPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderLogPath', () => { - const result = client.folderLogPath("folderValue", "logValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderLogPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderLogName', () => { - const result = client.matchFolderFromFolderLogName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderLogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLogFromFolderLogName', () => { - const result = client.matchLogFromFolderLogName(fakePath); - assert.strictEqual(result, "logValue"); - assert((client.pathTemplates.folderLogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('folderLog', () => { + const fakePath = '/rendered/path/folderLog'; + const expectedParameters = { + folder: 'folderValue', + log: 'logValue', + }; + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.folderLogPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderLogPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderLogPath', () => { + const result = client.folderLogPath('folderValue', 'logValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.folderLogPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderLogName', () => { + const result = client.matchFolderFromFolderLogName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + (client.pathTemplates.folderLogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLogFromFolderLogName', () => { + const result = client.matchLogFromFolderLogName(fakePath); + assert.strictEqual(result, 'logValue'); + assert( + (client.pathTemplates.folderLogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('folderSettings', () => { - const fakePath = "/rendered/path/folderSettings"; - const expectedParameters = { - folder: "folderValue", - }; - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.folderSettingsPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderSettingsPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderSettingsPath', () => { - const result = client.folderSettingsPath("folderValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderSettingsPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderSettingsName', () => { - const result = client.matchFolderFromFolderSettingsName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderSettingsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('folderSettings', () => { + const fakePath = '/rendered/path/folderSettings'; + const expectedParameters = { + folder: 'folderValue', + }; + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.folderSettingsPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderSettingsPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderSettingsPath', () => { + const result = client.folderSettingsPath('folderValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.folderSettingsPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderSettingsName', () => { + const result = client.matchFolderFromFolderSettingsName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + (client.pathTemplates.folderSettingsPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('folderSink', () => { - const fakePath = "/rendered/path/folderSink"; - const expectedParameters = { - folder: "folderValue", - sink: "sinkValue", - }; - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.folderSinkPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderSinkPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderSinkPath', () => { - const result = client.folderSinkPath("folderValue", "sinkValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderSinkPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderSinkName', () => { - const result = client.matchFolderFromFolderSinkName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderSinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchSinkFromFolderSinkName', () => { - const result = client.matchSinkFromFolderSinkName(fakePath); - assert.strictEqual(result, "sinkValue"); - assert((client.pathTemplates.folderSinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('folderSink', () => { + const fakePath = '/rendered/path/folderSink'; + const expectedParameters = { + folder: 'folderValue', + sink: 'sinkValue', + }; + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.folderSinkPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderSinkPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderSinkPath', () => { + const result = client.folderSinkPath('folderValue', 'sinkValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.folderSinkPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderSinkName', () => { + const result = client.matchFolderFromFolderSinkName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + (client.pathTemplates.folderSinkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchSinkFromFolderSinkName', () => { + const result = client.matchSinkFromFolderSinkName(fakePath); + assert.strictEqual(result, 'sinkValue'); + assert( + (client.pathTemplates.folderSinkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('logMetric', () => { - const fakePath = "/rendered/path/logMetric"; - const expectedParameters = { - project: "projectValue", - metric: "metricValue", - }; - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.logMetricPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.logMetricPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('logMetricPath', () => { - const result = client.logMetricPath("projectValue", "metricValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.logMetricPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromLogMetricName', () => { - const result = client.matchProjectFromLogMetricName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.logMetricPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchMetricFromLogMetricName', () => { - const result = client.matchMetricFromLogMetricName(fakePath); - assert.strictEqual(result, "metricValue"); - assert((client.pathTemplates.logMetricPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('logMetric', () => { + const fakePath = '/rendered/path/logMetric'; + const expectedParameters = { + project: 'projectValue', + metric: 'metricValue', + }; + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.logMetricPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.logMetricPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('logMetricPath', () => { + const result = client.logMetricPath('projectValue', 'metricValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.logMetricPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromLogMetricName', () => { + const result = client.matchProjectFromLogMetricName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.logMetricPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchMetricFromLogMetricName', () => { + const result = client.matchMetricFromLogMetricName(fakePath); + assert.strictEqual(result, 'metricValue'); + assert( + (client.pathTemplates.logMetricPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('organizationCmekSettings', () => { - const fakePath = "/rendered/path/organizationCmekSettings"; - const expectedParameters = { - organization: "organizationValue", - }; - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.organizationCmekSettingsPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationCmekSettingsPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationCmekSettingsPath', () => { - const result = client.organizationCmekSettingsPath("organizationValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationCmekSettingsPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationCmekSettingsName', () => { - const result = client.matchOrganizationFromOrganizationCmekSettingsName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationCmekSettingsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('organizationCmekSettings', () => { + const fakePath = '/rendered/path/organizationCmekSettings'; + const expectedParameters = { + organization: 'organizationValue', + }; + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.organizationCmekSettingsPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.organizationCmekSettingsPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('organizationCmekSettingsPath', () => { + const result = client.organizationCmekSettingsPath('organizationValue'); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationCmekSettingsPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationCmekSettingsName', () => { + const result = + client.matchOrganizationFromOrganizationCmekSettingsName(fakePath); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationCmekSettingsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('organizationExclusion', () => { - const fakePath = "/rendered/path/organizationExclusion"; - const expectedParameters = { - organization: "organizationValue", - exclusion: "exclusionValue", - }; - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.organizationExclusionPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationExclusionPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationExclusionPath', () => { - const result = client.organizationExclusionPath("organizationValue", "exclusionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationExclusionPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationExclusionName', () => { - const result = client.matchOrganizationFromOrganizationExclusionName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationExclusionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchExclusionFromOrganizationExclusionName', () => { - const result = client.matchExclusionFromOrganizationExclusionName(fakePath); - assert.strictEqual(result, "exclusionValue"); - assert((client.pathTemplates.organizationExclusionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('organizationExclusion', () => { + const fakePath = '/rendered/path/organizationExclusion'; + const expectedParameters = { + organization: 'organizationValue', + exclusion: 'exclusionValue', + }; + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.organizationExclusionPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.organizationExclusionPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('organizationExclusionPath', () => { + const result = client.organizationExclusionPath( + 'organizationValue', + 'exclusionValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationExclusionPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationExclusionName', () => { + const result = + client.matchOrganizationFromOrganizationExclusionName(fakePath); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationExclusionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchExclusionFromOrganizationExclusionName', () => { + const result = + client.matchExclusionFromOrganizationExclusionName(fakePath); + assert.strictEqual(result, 'exclusionValue'); + assert( + ( + client.pathTemplates.organizationExclusionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('organizationLocationBucket', () => { - const fakePath = "/rendered/path/organizationLocationBucket"; - const expectedParameters = { - organization: "organizationValue", - location: "locationValue", - bucket: "bucketValue", - }; - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.organizationLocationBucketPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationLocationBucketPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationLocationBucketPath', () => { - const result = client.organizationLocationBucketPath("organizationValue", "locationValue", "bucketValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationLocationBucketPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationLocationBucketName', () => { - const result = client.matchOrganizationFromOrganizationLocationBucketName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationLocationBucketPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromOrganizationLocationBucketName', () => { - const result = client.matchLocationFromOrganizationLocationBucketName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.organizationLocationBucketPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBucketFromOrganizationLocationBucketName', () => { - const result = client.matchBucketFromOrganizationLocationBucketName(fakePath); - assert.strictEqual(result, "bucketValue"); - assert((client.pathTemplates.organizationLocationBucketPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('organizationLocationBucket', () => { + const fakePath = '/rendered/path/organizationLocationBucket'; + const expectedParameters = { + organization: 'organizationValue', + location: 'locationValue', + bucket: 'bucketValue', + }; + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.organizationLocationBucketPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.organizationLocationBucketPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('organizationLocationBucketPath', () => { + const result = client.organizationLocationBucketPath( + 'organizationValue', + 'locationValue', + 'bucketValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationLocationBucketPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationLocationBucketName', () => { + const result = + client.matchOrganizationFromOrganizationLocationBucketName(fakePath); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationLocationBucketPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromOrganizationLocationBucketName', () => { + const result = + client.matchLocationFromOrganizationLocationBucketName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + ( + client.pathTemplates.organizationLocationBucketPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBucketFromOrganizationLocationBucketName', () => { + const result = + client.matchBucketFromOrganizationLocationBucketName(fakePath); + assert.strictEqual(result, 'bucketValue'); + assert( + ( + client.pathTemplates.organizationLocationBucketPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('organizationLocationBucketView', () => { - const fakePath = "/rendered/path/organizationLocationBucketView"; - const expectedParameters = { - organization: "organizationValue", - location: "locationValue", - bucket: "bucketValue", - view: "viewValue", - }; - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.organizationLocationBucketViewPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationLocationBucketViewPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationLocationBucketViewPath', () => { - const result = client.organizationLocationBucketViewPath("organizationValue", "locationValue", "bucketValue", "viewValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationLocationBucketViewPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationLocationBucketViewName', () => { - const result = client.matchOrganizationFromOrganizationLocationBucketViewName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationLocationBucketViewPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromOrganizationLocationBucketViewName', () => { - const result = client.matchLocationFromOrganizationLocationBucketViewName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.organizationLocationBucketViewPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBucketFromOrganizationLocationBucketViewName', () => { - const result = client.matchBucketFromOrganizationLocationBucketViewName(fakePath); - assert.strictEqual(result, "bucketValue"); - assert((client.pathTemplates.organizationLocationBucketViewPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchViewFromOrganizationLocationBucketViewName', () => { - const result = client.matchViewFromOrganizationLocationBucketViewName(fakePath); - assert.strictEqual(result, "viewValue"); - assert((client.pathTemplates.organizationLocationBucketViewPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('organizationLocationBucketView', () => { + const fakePath = '/rendered/path/organizationLocationBucketView'; + const expectedParameters = { + organization: 'organizationValue', + location: 'locationValue', + bucket: 'bucketValue', + view: 'viewValue', + }; + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.organizationLocationBucketViewPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.organizationLocationBucketViewPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('organizationLocationBucketViewPath', () => { + const result = client.organizationLocationBucketViewPath( + 'organizationValue', + 'locationValue', + 'bucketValue', + 'viewValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationLocationBucketViewPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationLocationBucketViewName', () => { + const result = + client.matchOrganizationFromOrganizationLocationBucketViewName( + fakePath, + ); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationLocationBucketViewPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromOrganizationLocationBucketViewName', () => { + const result = + client.matchLocationFromOrganizationLocationBucketViewName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + ( + client.pathTemplates.organizationLocationBucketViewPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBucketFromOrganizationLocationBucketViewName', () => { + const result = + client.matchBucketFromOrganizationLocationBucketViewName(fakePath); + assert.strictEqual(result, 'bucketValue'); + assert( + ( + client.pathTemplates.organizationLocationBucketViewPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchViewFromOrganizationLocationBucketViewName', () => { + const result = + client.matchViewFromOrganizationLocationBucketViewName(fakePath); + assert.strictEqual(result, 'viewValue'); + assert( + ( + client.pathTemplates.organizationLocationBucketViewPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('organizationLog', () => { - const fakePath = "/rendered/path/organizationLog"; - const expectedParameters = { - organization: "organizationValue", - log: "logValue", - }; - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.organizationLogPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationLogPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationLogPath', () => { - const result = client.organizationLogPath("organizationValue", "logValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationLogPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationLogName', () => { - const result = client.matchOrganizationFromOrganizationLogName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationLogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLogFromOrganizationLogName', () => { - const result = client.matchLogFromOrganizationLogName(fakePath); - assert.strictEqual(result, "logValue"); - assert((client.pathTemplates.organizationLogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('organizationLog', () => { + const fakePath = '/rendered/path/organizationLog'; + const expectedParameters = { + organization: 'organizationValue', + log: 'logValue', + }; + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.organizationLogPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.organizationLogPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('organizationLogPath', () => { + const result = client.organizationLogPath( + 'organizationValue', + 'logValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.organizationLogPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationLogName', () => { + const result = + client.matchOrganizationFromOrganizationLogName(fakePath); + assert.strictEqual(result, 'organizationValue'); + assert( + (client.pathTemplates.organizationLogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLogFromOrganizationLogName', () => { + const result = client.matchLogFromOrganizationLogName(fakePath); + assert.strictEqual(result, 'logValue'); + assert( + (client.pathTemplates.organizationLogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('organizationSettings', () => { - const fakePath = "/rendered/path/organizationSettings"; - const expectedParameters = { - organization: "organizationValue", - }; - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.organizationSettingsPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationSettingsPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationSettingsPath', () => { - const result = client.organizationSettingsPath("organizationValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationSettingsPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationSettingsName', () => { - const result = client.matchOrganizationFromOrganizationSettingsName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationSettingsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('organizationSettings', () => { + const fakePath = '/rendered/path/organizationSettings'; + const expectedParameters = { + organization: 'organizationValue', + }; + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.organizationSettingsPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.organizationSettingsPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('organizationSettingsPath', () => { + const result = client.organizationSettingsPath('organizationValue'); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationSettingsPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationSettingsName', () => { + const result = + client.matchOrganizationFromOrganizationSettingsName(fakePath); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationSettingsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('organizationSink', () => { - const fakePath = "/rendered/path/organizationSink"; - const expectedParameters = { - organization: "organizationValue", - sink: "sinkValue", - }; - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.organizationSinkPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationSinkPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationSinkPath', () => { - const result = client.organizationSinkPath("organizationValue", "sinkValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationSinkPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationSinkName', () => { - const result = client.matchOrganizationFromOrganizationSinkName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationSinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchSinkFromOrganizationSinkName', () => { - const result = client.matchSinkFromOrganizationSinkName(fakePath); - assert.strictEqual(result, "sinkValue"); - assert((client.pathTemplates.organizationSinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('organizationSink', () => { + const fakePath = '/rendered/path/organizationSink'; + const expectedParameters = { + organization: 'organizationValue', + sink: 'sinkValue', + }; + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.organizationSinkPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.organizationSinkPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('organizationSinkPath', () => { + const result = client.organizationSinkPath( + 'organizationValue', + 'sinkValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationSinkPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationSinkName', () => { + const result = + client.matchOrganizationFromOrganizationSinkName(fakePath); + assert.strictEqual(result, 'organizationValue'); + assert( + (client.pathTemplates.organizationSinkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchSinkFromOrganizationSinkName', () => { + const result = client.matchSinkFromOrganizationSinkName(fakePath); + assert.strictEqual(result, 'sinkValue'); + assert( + (client.pathTemplates.organizationSinkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('project', () => { - const fakePath = "/rendered/path/project"; - const expectedParameters = { - project: "projectValue", - }; - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.projectPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectPath', () => { - const result = client.projectPath("projectValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectName', () => { - const result = client.matchProjectFromProjectName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('project', () => { + const fakePath = '/rendered/path/project'; + const expectedParameters = { + project: 'projectValue', + }; + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.projectPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectPath', () => { + const result = client.projectPath('projectValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.projectPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectName', () => { + const result = client.matchProjectFromProjectName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.projectPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectCmekSettings', () => { - const fakePath = "/rendered/path/projectCmekSettings"; - const expectedParameters = { - project: "projectValue", - }; - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.projectCmekSettingsPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectCmekSettingsPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectCmekSettingsPath', () => { - const result = client.projectCmekSettingsPath("projectValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectCmekSettingsPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectCmekSettingsName', () => { - const result = client.matchProjectFromProjectCmekSettingsName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectCmekSettingsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectCmekSettings', () => { + const fakePath = '/rendered/path/projectCmekSettings'; + const expectedParameters = { + project: 'projectValue', + }; + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.projectCmekSettingsPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectCmekSettingsPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectCmekSettingsPath', () => { + const result = client.projectCmekSettingsPath('projectValue'); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.projectCmekSettingsPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectCmekSettingsName', () => { + const result = client.matchProjectFromProjectCmekSettingsName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.projectCmekSettingsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectExclusion', () => { - const fakePath = "/rendered/path/projectExclusion"; - const expectedParameters = { - project: "projectValue", - exclusion: "exclusionValue", - }; - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.projectExclusionPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectExclusionPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectExclusionPath', () => { - const result = client.projectExclusionPath("projectValue", "exclusionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectExclusionPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectExclusionName', () => { - const result = client.matchProjectFromProjectExclusionName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectExclusionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchExclusionFromProjectExclusionName', () => { - const result = client.matchExclusionFromProjectExclusionName(fakePath); - assert.strictEqual(result, "exclusionValue"); - assert((client.pathTemplates.projectExclusionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectExclusion', () => { + const fakePath = '/rendered/path/projectExclusion'; + const expectedParameters = { + project: 'projectValue', + exclusion: 'exclusionValue', + }; + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.projectExclusionPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectExclusionPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectExclusionPath', () => { + const result = client.projectExclusionPath( + 'projectValue', + 'exclusionValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.projectExclusionPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectExclusionName', () => { + const result = client.matchProjectFromProjectExclusionName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.projectExclusionPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchExclusionFromProjectExclusionName', () => { + const result = client.matchExclusionFromProjectExclusionName(fakePath); + assert.strictEqual(result, 'exclusionValue'); + assert( + (client.pathTemplates.projectExclusionPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectLocationBucket', () => { - const fakePath = "/rendered/path/projectLocationBucket"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - bucket: "bucketValue", - }; - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.projectLocationBucketPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectLocationBucketPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectLocationBucketPath', () => { - const result = client.projectLocationBucketPath("projectValue", "locationValue", "bucketValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectLocationBucketPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectLocationBucketName', () => { - const result = client.matchProjectFromProjectLocationBucketName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectLocationBucketPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromProjectLocationBucketName', () => { - const result = client.matchLocationFromProjectLocationBucketName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.projectLocationBucketPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBucketFromProjectLocationBucketName', () => { - const result = client.matchBucketFromProjectLocationBucketName(fakePath); - assert.strictEqual(result, "bucketValue"); - assert((client.pathTemplates.projectLocationBucketPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectLocationBucket', () => { + const fakePath = '/rendered/path/projectLocationBucket'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + bucket: 'bucketValue', + }; + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.projectLocationBucketPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectLocationBucketPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectLocationBucketPath', () => { + const result = client.projectLocationBucketPath( + 'projectValue', + 'locationValue', + 'bucketValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.projectLocationBucketPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectLocationBucketName', () => { + const result = + client.matchProjectFromProjectLocationBucketName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.projectLocationBucketPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromProjectLocationBucketName', () => { + const result = + client.matchLocationFromProjectLocationBucketName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + ( + client.pathTemplates.projectLocationBucketPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBucketFromProjectLocationBucketName', () => { + const result = + client.matchBucketFromProjectLocationBucketName(fakePath); + assert.strictEqual(result, 'bucketValue'); + assert( + ( + client.pathTemplates.projectLocationBucketPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectLocationBucketView', () => { - const fakePath = "/rendered/path/projectLocationBucketView"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - bucket: "bucketValue", - view: "viewValue", - }; - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.projectLocationBucketViewPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectLocationBucketViewPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectLocationBucketViewPath', () => { - const result = client.projectLocationBucketViewPath("projectValue", "locationValue", "bucketValue", "viewValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectLocationBucketViewPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectLocationBucketViewName', () => { - const result = client.matchProjectFromProjectLocationBucketViewName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectLocationBucketViewPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromProjectLocationBucketViewName', () => { - const result = client.matchLocationFromProjectLocationBucketViewName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.projectLocationBucketViewPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBucketFromProjectLocationBucketViewName', () => { - const result = client.matchBucketFromProjectLocationBucketViewName(fakePath); - assert.strictEqual(result, "bucketValue"); - assert((client.pathTemplates.projectLocationBucketViewPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchViewFromProjectLocationBucketViewName', () => { - const result = client.matchViewFromProjectLocationBucketViewName(fakePath); - assert.strictEqual(result, "viewValue"); - assert((client.pathTemplates.projectLocationBucketViewPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectLocationBucketView', () => { + const fakePath = '/rendered/path/projectLocationBucketView'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + bucket: 'bucketValue', + view: 'viewValue', + }; + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.projectLocationBucketViewPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectLocationBucketViewPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectLocationBucketViewPath', () => { + const result = client.projectLocationBucketViewPath( + 'projectValue', + 'locationValue', + 'bucketValue', + 'viewValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.projectLocationBucketViewPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectLocationBucketViewName', () => { + const result = + client.matchProjectFromProjectLocationBucketViewName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.projectLocationBucketViewPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromProjectLocationBucketViewName', () => { + const result = + client.matchLocationFromProjectLocationBucketViewName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + ( + client.pathTemplates.projectLocationBucketViewPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBucketFromProjectLocationBucketViewName', () => { + const result = + client.matchBucketFromProjectLocationBucketViewName(fakePath); + assert.strictEqual(result, 'bucketValue'); + assert( + ( + client.pathTemplates.projectLocationBucketViewPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchViewFromProjectLocationBucketViewName', () => { + const result = + client.matchViewFromProjectLocationBucketViewName(fakePath); + assert.strictEqual(result, 'viewValue'); + assert( + ( + client.pathTemplates.projectLocationBucketViewPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectLog', () => { - const fakePath = "/rendered/path/projectLog"; - const expectedParameters = { - project: "projectValue", - log: "logValue", - }; - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.projectLogPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectLogPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectLogPath', () => { - const result = client.projectLogPath("projectValue", "logValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectLogPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectLogName', () => { - const result = client.matchProjectFromProjectLogName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectLogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLogFromProjectLogName', () => { - const result = client.matchLogFromProjectLogName(fakePath); - assert.strictEqual(result, "logValue"); - assert((client.pathTemplates.projectLogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectLog', () => { + const fakePath = '/rendered/path/projectLog'; + const expectedParameters = { + project: 'projectValue', + log: 'logValue', + }; + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.projectLogPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectLogPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectLogPath', () => { + const result = client.projectLogPath('projectValue', 'logValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.projectLogPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectLogName', () => { + const result = client.matchProjectFromProjectLogName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.projectLogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLogFromProjectLogName', () => { + const result = client.matchLogFromProjectLogName(fakePath); + assert.strictEqual(result, 'logValue'); + assert( + (client.pathTemplates.projectLogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectSettings', () => { - const fakePath = "/rendered/path/projectSettings"; - const expectedParameters = { - project: "projectValue", - }; - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.projectSettingsPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectSettingsPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectSettingsPath', () => { - const result = client.projectSettingsPath("projectValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectSettingsPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectSettingsName', () => { - const result = client.matchProjectFromProjectSettingsName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectSettingsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectSettings', () => { + const fakePath = '/rendered/path/projectSettings'; + const expectedParameters = { + project: 'projectValue', + }; + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.projectSettingsPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectSettingsPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectSettingsPath', () => { + const result = client.projectSettingsPath('projectValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.projectSettingsPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectSettingsName', () => { + const result = client.matchProjectFromProjectSettingsName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.projectSettingsPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectSink', () => { - const fakePath = "/rendered/path/projectSink"; - const expectedParameters = { - project: "projectValue", - sink: "sinkValue", - }; - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.projectSinkPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectSinkPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectSinkPath', () => { - const result = client.projectSinkPath("projectValue", "sinkValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectSinkPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectSinkName', () => { - const result = client.matchProjectFromProjectSinkName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectSinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchSinkFromProjectSinkName', () => { - const result = client.matchSinkFromProjectSinkName(fakePath); - assert.strictEqual(result, "sinkValue"); - assert((client.pathTemplates.projectSinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectSink', () => { + const fakePath = '/rendered/path/projectSink'; + const expectedParameters = { + project: 'projectValue', + sink: 'sinkValue', + }; + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.projectSinkPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectSinkPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectSinkPath', () => { + const result = client.projectSinkPath('projectValue', 'sinkValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.projectSinkPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectSinkName', () => { + const result = client.matchProjectFromProjectSinkName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.projectSinkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchSinkFromProjectSinkName', () => { + const result = client.matchSinkFromProjectSinkName(fakePath); + assert.strictEqual(result, 'sinkValue'); + assert( + (client.pathTemplates.projectSinkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/core/generator/gapic-generator-typescript/baselines/logging/src/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/logging/src/index.ts.baseline index 84e5b85ed9c3..0f1fcaa17eab 100644 --- a/core/generator/gapic-generator-typescript/baselines/logging/src/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/logging/src/index.ts.baseline @@ -23,7 +23,17 @@ const LoggingServiceV2Client = v2.LoggingServiceV2Client; type LoggingServiceV2Client = v2.LoggingServiceV2Client; const MetricsServiceV2Client = v2.MetricsServiceV2Client; type MetricsServiceV2Client = v2.MetricsServiceV2Client; -export {v2, ConfigServiceV2Client, LoggingServiceV2Client, MetricsServiceV2Client}; -export default {v2, ConfigServiceV2Client, LoggingServiceV2Client, MetricsServiceV2Client}; +export { + v2, + ConfigServiceV2Client, + LoggingServiceV2Client, + MetricsServiceV2Client, +}; +export default { + v2, + ConfigServiceV2Client, + LoggingServiceV2Client, + MetricsServiceV2Client, +}; import * as protos from '../protos/protos'; -export {protos} +export { protos }; diff --git a/core/generator/gapic-generator-typescript/baselines/logging/src/v2/config_service_v2_client.ts.baseline b/core/generator/gapic-generator-typescript/baselines/logging/src/v2/config_service_v2_client.ts.baseline index f9876a7c2965..5894273111f5 100644 --- a/core/generator/gapic-generator-typescript/baselines/logging/src/v2/config_service_v2_client.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/logging/src/v2/config_service_v2_client.ts.baseline @@ -18,11 +18,20 @@ /* global window */ import type * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions, GrpcClientOptions, LROperation, PaginationCallback, GaxCall} from 'google-gax'; -import {Transform} from 'stream'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + GrpcClientOptions, + LROperation, + PaginationCallback, + GaxCall, +} from 'google-gax'; +import { Transform } from 'stream'; import * as protos from '../../protos/protos'; import jsonProtos = require('../../protos/protos.json'); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; /** * Client JSON configuration object, loaded from @@ -44,7 +53,7 @@ export class ConfigServiceV2Client { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('logging'); @@ -57,10 +66,10 @@ export class ConfigServiceV2Client { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; operationsClient: gax.OperationsClient; - configServiceV2Stub?: Promise<{[name: string]: Function}>; + configServiceV2Stub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of ConfigServiceV2Client. @@ -101,21 +110,42 @@ export class ConfigServiceV2Client { * const client = new ConfigServiceV2Client({fallback: true}, gax); * ``` */ - constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { // Ensure that options include all the required fields. const staticMembers = this.constructor as typeof ConfigServiceV2Client; - if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { - throw new Error('Please set either universe_domain or universeDomain, but not both.'); + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); } - const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; - this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; this._servicePath = 'logging.' + this._universeDomain; - const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; - const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. if (servicePath !== this._servicePath && !('scopes' in opts)) { @@ -137,7 +167,7 @@ export class ConfigServiceV2Client { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; @@ -151,10 +181,7 @@ export class ConfigServiceV2Client { } // Determine the client header string. - const clientHeader = [ - `gax/${this._gaxModule.version}`, - `gapic/${version}`, - ]; + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/${process.versions.node}`); } else { @@ -176,97 +203,100 @@ export class ConfigServiceV2Client { // Create useful helper objects for these. this.pathTemplates = { billingAccountCmekSettingsPathTemplate: new this._gaxModule.PathTemplate( - 'billingAccounts/{billing_account}/cmekSettings' + 'billingAccounts/{billing_account}/cmekSettings', ), billingAccountExclusionPathTemplate: new this._gaxModule.PathTemplate( - 'billingAccounts/{billing_account}/exclusions/{exclusion}' - ), - billingAccountLocationBucketPathTemplate: new this._gaxModule.PathTemplate( - 'billingAccounts/{billing_account}/locations/{location}/buckets/{bucket}' - ), - billingAccountLocationBucketViewPathTemplate: new this._gaxModule.PathTemplate( - 'billingAccounts/{billing_account}/locations/{location}/buckets/{bucket}/views/{view}' + 'billingAccounts/{billing_account}/exclusions/{exclusion}', ), + billingAccountLocationBucketPathTemplate: + new this._gaxModule.PathTemplate( + 'billingAccounts/{billing_account}/locations/{location}/buckets/{bucket}', + ), + billingAccountLocationBucketViewPathTemplate: + new this._gaxModule.PathTemplate( + 'billingAccounts/{billing_account}/locations/{location}/buckets/{bucket}/views/{view}', + ), billingAccountLogPathTemplate: new this._gaxModule.PathTemplate( - 'billingAccounts/{billing_account}/logs/{log}' + 'billingAccounts/{billing_account}/logs/{log}', ), billingAccountSettingsPathTemplate: new this._gaxModule.PathTemplate( - 'billingAccounts/{billing_account}/settings' + 'billingAccounts/{billing_account}/settings', ), billingAccountSinkPathTemplate: new this._gaxModule.PathTemplate( - 'billingAccounts/{billing_account}/sinks/{sink}' + 'billingAccounts/{billing_account}/sinks/{sink}', ), folderCmekSettingsPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/cmekSettings' + 'folders/{folder}/cmekSettings', ), folderExclusionPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/exclusions/{exclusion}' + 'folders/{folder}/exclusions/{exclusion}', ), folderLocationBucketPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/locations/{location}/buckets/{bucket}' + 'folders/{folder}/locations/{location}/buckets/{bucket}', ), folderLocationBucketViewPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/locations/{location}/buckets/{bucket}/views/{view}' + 'folders/{folder}/locations/{location}/buckets/{bucket}/views/{view}', ), folderLogPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/logs/{log}' + 'folders/{folder}/logs/{log}', ), folderSettingsPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/settings' + 'folders/{folder}/settings', ), folderSinkPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/sinks/{sink}' + 'folders/{folder}/sinks/{sink}', ), locationPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}' + 'projects/{project}/locations/{location}', ), logMetricPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/metrics/{metric}' + 'projects/{project}/metrics/{metric}', ), organizationCmekSettingsPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/cmekSettings' + 'organizations/{organization}/cmekSettings', ), organizationExclusionPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/exclusions/{exclusion}' + 'organizations/{organization}/exclusions/{exclusion}', ), organizationLocationBucketPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/locations/{location}/buckets/{bucket}' - ), - organizationLocationBucketViewPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/locations/{location}/buckets/{bucket}/views/{view}' + 'organizations/{organization}/locations/{location}/buckets/{bucket}', ), + organizationLocationBucketViewPathTemplate: + new this._gaxModule.PathTemplate( + 'organizations/{organization}/locations/{location}/buckets/{bucket}/views/{view}', + ), organizationLogPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/logs/{log}' + 'organizations/{organization}/logs/{log}', ), organizationSettingsPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/settings' + 'organizations/{organization}/settings', ), organizationSinkPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/sinks/{sink}' + 'organizations/{organization}/sinks/{sink}', ), projectPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}' + 'projects/{project}', ), projectCmekSettingsPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/cmekSettings' + 'projects/{project}/cmekSettings', ), projectExclusionPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/exclusions/{exclusion}' + 'projects/{project}/exclusions/{exclusion}', ), projectLocationBucketPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/buckets/{bucket}' + 'projects/{project}/locations/{location}/buckets/{bucket}', ), projectLocationBucketViewPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/buckets/{bucket}/views/{view}' + 'projects/{project}/locations/{location}/buckets/{bucket}/views/{view}', ), projectLogPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/logs/{log}' + 'projects/{project}/logs/{log}', ), projectSettingsPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/settings' + 'projects/{project}/settings', ), projectSinkPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/sinks/{sink}' + 'projects/{project}/sinks/{sink}', ), }; @@ -274,14 +304,26 @@ export class ConfigServiceV2Client { // (e.g. 50 results at a time, with tokens to get subsequent // pages). Denote the keys used for pagination and results. this.descriptors.page = { - listBuckets: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'buckets'), - listViews: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'views'), - listSinks: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'sinks'), - listExclusions: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'exclusions') + listBuckets: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'buckets', + ), + listViews: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'views', + ), + listSinks: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'sinks', + ), + listExclusions: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'exclusions', + ), }; const protoFilesRoot = this._gaxModule.protobufFromJSON(jsonProtos); @@ -290,29 +332,37 @@ export class ConfigServiceV2Client { // rather than holding a request open. const lroOptions: GrpcClientOptions = { auth: this.auth, - grpc: 'grpc' in this._gaxGrpc ? this._gaxGrpc.grpc : undefined + grpc: 'grpc' in this._gaxGrpc ? this._gaxGrpc.grpc : undefined, }; if (opts.fallback) { lroOptions.protoJson = protoFilesRoot; lroOptions.httpRules = []; } - this.operationsClient = this._gaxModule.lro(lroOptions).operationsClient(opts); + this.operationsClient = this._gaxModule + .lro(lroOptions) + .operationsClient(opts); const copyLogEntriesResponse = protoFilesRoot.lookup( - '.google.logging.v2.CopyLogEntriesResponse') as gax.protobuf.Type; + '.google.logging.v2.CopyLogEntriesResponse', + ) as gax.protobuf.Type; const copyLogEntriesMetadata = protoFilesRoot.lookup( - '.google.logging.v2.CopyLogEntriesMetadata') as gax.protobuf.Type; + '.google.logging.v2.CopyLogEntriesMetadata', + ) as gax.protobuf.Type; this.descriptors.longrunning = { copyLogEntries: new this._gaxModule.LongrunningDescriptor( this.operationsClient, copyLogEntriesResponse.decode.bind(copyLogEntriesResponse), - copyLogEntriesMetadata.decode.bind(copyLogEntriesMetadata)) + copyLogEntriesMetadata.decode.bind(copyLogEntriesMetadata), + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.logging.v2.ConfigServiceV2', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.logging.v2.ConfigServiceV2', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + { 'x-goog-api-client': clientHeader.join(' ') }, + ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -343,28 +393,60 @@ export class ConfigServiceV2Client { // Put together the "service stub" for // google.logging.v2.ConfigServiceV2. this.configServiceV2Stub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.logging.v2.ConfigServiceV2') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.logging.v2.ConfigServiceV2', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.logging.v2.ConfigServiceV2, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts, + this._providedCustomServicePath, + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const configServiceV2StubMethods = - ['listBuckets', 'getBucket', 'createBucket', 'updateBucket', 'deleteBucket', 'undeleteBucket', 'listViews', 'getView', 'createView', 'updateView', 'deleteView', 'listSinks', 'getSink', 'createSink', 'updateSink', 'deleteSink', 'listExclusions', 'getExclusion', 'createExclusion', 'updateExclusion', 'deleteExclusion', 'getCmekSettings', 'updateCmekSettings', 'getSettings', 'updateSettings', 'copyLogEntries']; + const configServiceV2StubMethods = [ + 'listBuckets', + 'getBucket', + 'createBucket', + 'updateBucket', + 'deleteBucket', + 'undeleteBucket', + 'listViews', + 'getView', + 'createView', + 'updateView', + 'deleteView', + 'listSinks', + 'getSink', + 'createSink', + 'updateSink', + 'deleteSink', + 'listExclusions', + 'getExclusion', + 'createExclusion', + 'updateExclusion', + 'deleteExclusion', + 'getCmekSettings', + 'updateCmekSettings', + 'getSettings', + 'updateSettings', + 'copyLogEntries', + ]; for (const methodName of configServiceV2StubMethods) { const callPromise = this.configServiceV2Stub.then( - stub => (...args: Array<{}>) => { - if (this._terminated) { - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error|null|undefined) => () => { + (stub) => + (...args: Array<{}>) => { + if (this._terminated) { + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { throw err; - }); + }, + ); const descriptor = this.descriptors.page[methodName] || @@ -374,7 +456,7 @@ export class ConfigServiceV2Client { callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -389,8 +471,14 @@ export class ConfigServiceV2Client { * @returns {string} The DNS address for this service. */ static get servicePath() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'logging.googleapis.com'; } @@ -401,8 +489,14 @@ export class ConfigServiceV2Client { * @returns {string} The DNS address for this service. */ static get apiEndpoint() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'logging.googleapis.com'; } @@ -437,7 +531,7 @@ export class ConfigServiceV2Client { 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/cloud-platform.read-only', 'https://www.googleapis.com/auth/logging.admin', - 'https://www.googleapis.com/auth/logging.read' + 'https://www.googleapis.com/auth/logging.read', ]; } @@ -447,8 +541,9 @@ export class ConfigServiceV2Client { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId(callback?: Callback): - Promise|void { + getProjectId( + callback?: Callback, + ): Promise | void { if (callback) { this.auth.getProjectId(callback); return; @@ -459,2584 +554,3296 @@ export class ConfigServiceV2Client { // ------------------- // -- Service calls -- // ------------------- -/** - * Gets a log bucket. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The resource name of the bucket: - * - * "projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" - * "organizations/[ORGANIZATION_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" - * "billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" - * "folders/[FOLDER_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" - * - * For example: - * - * `"projects/my-project/locations/global/buckets/my-bucket"` - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.logging.v2.LogBucket|LogBucket}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/config_service_v2.get_bucket.js - * region_tag:logging_v2_generated_ConfigServiceV2_GetBucket_async - */ + /** + * Gets a log bucket. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The resource name of the bucket: + * + * "projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" + * "organizations/[ORGANIZATION_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" + * "billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" + * "folders/[FOLDER_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" + * + * For example: + * + * `"projects/my-project/locations/global/buckets/my-bucket"` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.logging.v2.LogBucket|LogBucket}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/config_service_v2.get_bucket.js + * region_tag:logging_v2_generated_ConfigServiceV2_GetBucket_async + */ getBucket( - request?: protos.google.logging.v2.IGetBucketRequest, - options?: CallOptions): - Promise<[ - protos.google.logging.v2.ILogBucket, - protos.google.logging.v2.IGetBucketRequest|undefined, {}|undefined - ]>; + request?: protos.google.logging.v2.IGetBucketRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.logging.v2.ILogBucket, + protos.google.logging.v2.IGetBucketRequest | undefined, + {} | undefined, + ] + >; getBucket( - request: protos.google.logging.v2.IGetBucketRequest, - options: CallOptions, - callback: Callback< - protos.google.logging.v2.ILogBucket, - protos.google.logging.v2.IGetBucketRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.logging.v2.IGetBucketRequest, + options: CallOptions, + callback: Callback< + protos.google.logging.v2.ILogBucket, + protos.google.logging.v2.IGetBucketRequest | null | undefined, + {} | null | undefined + >, + ): void; getBucket( - request: protos.google.logging.v2.IGetBucketRequest, - callback: Callback< - protos.google.logging.v2.ILogBucket, - protos.google.logging.v2.IGetBucketRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.logging.v2.IGetBucketRequest, + callback: Callback< + protos.google.logging.v2.ILogBucket, + protos.google.logging.v2.IGetBucketRequest | null | undefined, + {} | null | undefined + >, + ): void; getBucket( - request?: protos.google.logging.v2.IGetBucketRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.logging.v2.ILogBucket, - protos.google.logging.v2.IGetBucketRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.logging.v2.IGetBucketRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.logging.v2.ILogBucket, - protos.google.logging.v2.IGetBucketRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.logging.v2.ILogBucket, - protos.google.logging.v2.IGetBucketRequest|undefined, {}|undefined - ]>|void { + protos.google.logging.v2.IGetBucketRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.logging.v2.ILogBucket, + protos.google.logging.v2.IGetBucketRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.logging.v2.ILogBucket, + protos.google.logging.v2.IGetBucketRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getBucket request %j', request); - const wrappedCallback: Callback< - protos.google.logging.v2.ILogBucket, - protos.google.logging.v2.IGetBucketRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.logging.v2.ILogBucket, + protos.google.logging.v2.IGetBucketRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getBucket response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getBucket(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.logging.v2.ILogBucket, - protos.google.logging.v2.IGetBucketRequest|undefined, - {}|undefined - ]) => { - this._log.info('getBucket response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getBucket(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.logging.v2.ILogBucket, + protos.google.logging.v2.IGetBucketRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getBucket response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Creates a log bucket that can be used to store log entries. After a bucket - * has been created, the bucket's location cannot be changed. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The resource in which to create the log bucket: - * - * "projects/[PROJECT_ID]/locations/[LOCATION_ID]" - * - * For example: - * - * `"projects/my-project/locations/global"` - * @param {string} request.bucketId - * Required. A client-assigned identifier such as `"my-bucket"`. Identifiers are limited - * to 100 characters and can include only letters, digits, underscores, - * hyphens, and periods. - * @param {google.logging.v2.LogBucket} request.bucket - * Required. The new bucket. The region specified in the new bucket must be compliant - * with any Location Restriction Org Policy. The name field in the bucket is - * ignored. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.logging.v2.LogBucket|LogBucket}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/config_service_v2.create_bucket.js - * region_tag:logging_v2_generated_ConfigServiceV2_CreateBucket_async - */ + /** + * Creates a log bucket that can be used to store log entries. After a bucket + * has been created, the bucket's location cannot be changed. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The resource in which to create the log bucket: + * + * "projects/[PROJECT_ID]/locations/[LOCATION_ID]" + * + * For example: + * + * `"projects/my-project/locations/global"` + * @param {string} request.bucketId + * Required. A client-assigned identifier such as `"my-bucket"`. Identifiers are limited + * to 100 characters and can include only letters, digits, underscores, + * hyphens, and periods. + * @param {google.logging.v2.LogBucket} request.bucket + * Required. The new bucket. The region specified in the new bucket must be compliant + * with any Location Restriction Org Policy. The name field in the bucket is + * ignored. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.logging.v2.LogBucket|LogBucket}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/config_service_v2.create_bucket.js + * region_tag:logging_v2_generated_ConfigServiceV2_CreateBucket_async + */ createBucket( - request?: protos.google.logging.v2.ICreateBucketRequest, - options?: CallOptions): - Promise<[ - protos.google.logging.v2.ILogBucket, - protos.google.logging.v2.ICreateBucketRequest|undefined, {}|undefined - ]>; + request?: protos.google.logging.v2.ICreateBucketRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.logging.v2.ILogBucket, + protos.google.logging.v2.ICreateBucketRequest | undefined, + {} | undefined, + ] + >; createBucket( - request: protos.google.logging.v2.ICreateBucketRequest, - options: CallOptions, - callback: Callback< - protos.google.logging.v2.ILogBucket, - protos.google.logging.v2.ICreateBucketRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.logging.v2.ICreateBucketRequest, + options: CallOptions, + callback: Callback< + protos.google.logging.v2.ILogBucket, + protos.google.logging.v2.ICreateBucketRequest | null | undefined, + {} | null | undefined + >, + ): void; createBucket( - request: protos.google.logging.v2.ICreateBucketRequest, - callback: Callback< - protos.google.logging.v2.ILogBucket, - protos.google.logging.v2.ICreateBucketRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.logging.v2.ICreateBucketRequest, + callback: Callback< + protos.google.logging.v2.ILogBucket, + protos.google.logging.v2.ICreateBucketRequest | null | undefined, + {} | null | undefined + >, + ): void; createBucket( - request?: protos.google.logging.v2.ICreateBucketRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.logging.v2.ILogBucket, - protos.google.logging.v2.ICreateBucketRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.logging.v2.ICreateBucketRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.logging.v2.ILogBucket, - protos.google.logging.v2.ICreateBucketRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.logging.v2.ILogBucket, - protos.google.logging.v2.ICreateBucketRequest|undefined, {}|undefined - ]>|void { + protos.google.logging.v2.ICreateBucketRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.logging.v2.ILogBucket, + protos.google.logging.v2.ICreateBucketRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.logging.v2.ILogBucket, + protos.google.logging.v2.ICreateBucketRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('createBucket request %j', request); - const wrappedCallback: Callback< - protos.google.logging.v2.ILogBucket, - protos.google.logging.v2.ICreateBucketRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.logging.v2.ILogBucket, + protos.google.logging.v2.ICreateBucketRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createBucket response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.createBucket(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.logging.v2.ILogBucket, - protos.google.logging.v2.ICreateBucketRequest|undefined, - {}|undefined - ]) => { - this._log.info('createBucket response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createBucket(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.logging.v2.ILogBucket, + protos.google.logging.v2.ICreateBucketRequest | undefined, + {} | undefined, + ]) => { + this._log.info('createBucket response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Updates a log bucket. This method replaces the following fields in the - * existing bucket with values from the new bucket: `retention_period` - * - * If the retention period is decreased and the bucket is locked, - * `FAILED_PRECONDITION` will be returned. - * - * If the bucket has a `lifecycle_state` of `DELETE_REQUESTED`, then - * `FAILED_PRECONDITION` will be returned. - * - * After a bucket has been created, the bucket's location cannot be changed. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The full resource name of the bucket to update. - * - * "projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" - * "organizations/[ORGANIZATION_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" - * "billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" - * "folders/[FOLDER_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" - * - * For example: - * - * `"projects/my-project/locations/global/buckets/my-bucket"` - * @param {google.logging.v2.LogBucket} request.bucket - * Required. The updated bucket. - * @param {google.protobuf.FieldMask} request.updateMask - * Required. Field mask that specifies the fields in `bucket` that need an update. A - * bucket field will be overwritten if, and only if, it is in the update mask. - * `name` and output only fields cannot be updated. - * - * For a detailed `FieldMask` definition, see: - * https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#google.protobuf.FieldMask - * - * For example: `updateMask=retention_days` - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.logging.v2.LogBucket|LogBucket}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/config_service_v2.update_bucket.js - * region_tag:logging_v2_generated_ConfigServiceV2_UpdateBucket_async - */ + /** + * Updates a log bucket. This method replaces the following fields in the + * existing bucket with values from the new bucket: `retention_period` + * + * If the retention period is decreased and the bucket is locked, + * `FAILED_PRECONDITION` will be returned. + * + * If the bucket has a `lifecycle_state` of `DELETE_REQUESTED`, then + * `FAILED_PRECONDITION` will be returned. + * + * After a bucket has been created, the bucket's location cannot be changed. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The full resource name of the bucket to update. + * + * "projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" + * "organizations/[ORGANIZATION_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" + * "billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" + * "folders/[FOLDER_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" + * + * For example: + * + * `"projects/my-project/locations/global/buckets/my-bucket"` + * @param {google.logging.v2.LogBucket} request.bucket + * Required. The updated bucket. + * @param {google.protobuf.FieldMask} request.updateMask + * Required. Field mask that specifies the fields in `bucket` that need an update. A + * bucket field will be overwritten if, and only if, it is in the update mask. + * `name` and output only fields cannot be updated. + * + * For a detailed `FieldMask` definition, see: + * https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#google.protobuf.FieldMask + * + * For example: `updateMask=retention_days` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.logging.v2.LogBucket|LogBucket}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/config_service_v2.update_bucket.js + * region_tag:logging_v2_generated_ConfigServiceV2_UpdateBucket_async + */ updateBucket( - request?: protos.google.logging.v2.IUpdateBucketRequest, - options?: CallOptions): - Promise<[ - protos.google.logging.v2.ILogBucket, - protos.google.logging.v2.IUpdateBucketRequest|undefined, {}|undefined - ]>; + request?: protos.google.logging.v2.IUpdateBucketRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.logging.v2.ILogBucket, + protos.google.logging.v2.IUpdateBucketRequest | undefined, + {} | undefined, + ] + >; updateBucket( - request: protos.google.logging.v2.IUpdateBucketRequest, - options: CallOptions, - callback: Callback< - protos.google.logging.v2.ILogBucket, - protos.google.logging.v2.IUpdateBucketRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.logging.v2.IUpdateBucketRequest, + options: CallOptions, + callback: Callback< + protos.google.logging.v2.ILogBucket, + protos.google.logging.v2.IUpdateBucketRequest | null | undefined, + {} | null | undefined + >, + ): void; updateBucket( - request: protos.google.logging.v2.IUpdateBucketRequest, - callback: Callback< - protos.google.logging.v2.ILogBucket, - protos.google.logging.v2.IUpdateBucketRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.logging.v2.IUpdateBucketRequest, + callback: Callback< + protos.google.logging.v2.ILogBucket, + protos.google.logging.v2.IUpdateBucketRequest | null | undefined, + {} | null | undefined + >, + ): void; updateBucket( - request?: protos.google.logging.v2.IUpdateBucketRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.logging.v2.ILogBucket, - protos.google.logging.v2.IUpdateBucketRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.logging.v2.IUpdateBucketRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.logging.v2.ILogBucket, - protos.google.logging.v2.IUpdateBucketRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.logging.v2.ILogBucket, - protos.google.logging.v2.IUpdateBucketRequest|undefined, {}|undefined - ]>|void { + protos.google.logging.v2.IUpdateBucketRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.logging.v2.ILogBucket, + protos.google.logging.v2.IUpdateBucketRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.logging.v2.ILogBucket, + protos.google.logging.v2.IUpdateBucketRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateBucket request %j', request); - const wrappedCallback: Callback< - protos.google.logging.v2.ILogBucket, - protos.google.logging.v2.IUpdateBucketRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.logging.v2.ILogBucket, + protos.google.logging.v2.IUpdateBucketRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateBucket response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.updateBucket(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.logging.v2.ILogBucket, - protos.google.logging.v2.IUpdateBucketRequest|undefined, - {}|undefined - ]) => { - this._log.info('updateBucket response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateBucket(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.logging.v2.ILogBucket, + protos.google.logging.v2.IUpdateBucketRequest | undefined, + {} | undefined, + ]) => { + this._log.info('updateBucket response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Deletes a log bucket. - * - * Changes the bucket's `lifecycle_state` to the `DELETE_REQUESTED` state. - * After 7 days, the bucket will be purged and all log entries in the bucket - * will be permanently deleted. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The full resource name of the bucket to delete. - * - * "projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" - * "organizations/[ORGANIZATION_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" - * "billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" - * "folders/[FOLDER_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" - * - * For example: - * - * `"projects/my-project/locations/global/buckets/my-bucket"` - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/config_service_v2.delete_bucket.js - * region_tag:logging_v2_generated_ConfigServiceV2_DeleteBucket_async - */ + /** + * Deletes a log bucket. + * + * Changes the bucket's `lifecycle_state` to the `DELETE_REQUESTED` state. + * After 7 days, the bucket will be purged and all log entries in the bucket + * will be permanently deleted. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The full resource name of the bucket to delete. + * + * "projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" + * "organizations/[ORGANIZATION_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" + * "billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" + * "folders/[FOLDER_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" + * + * For example: + * + * `"projects/my-project/locations/global/buckets/my-bucket"` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/config_service_v2.delete_bucket.js + * region_tag:logging_v2_generated_ConfigServiceV2_DeleteBucket_async + */ deleteBucket( - request?: protos.google.logging.v2.IDeleteBucketRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.logging.v2.IDeleteBucketRequest|undefined, {}|undefined - ]>; + request?: protos.google.logging.v2.IDeleteBucketRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.logging.v2.IDeleteBucketRequest | undefined, + {} | undefined, + ] + >; deleteBucket( - request: protos.google.logging.v2.IDeleteBucketRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.logging.v2.IDeleteBucketRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.logging.v2.IDeleteBucketRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.logging.v2.IDeleteBucketRequest | null | undefined, + {} | null | undefined + >, + ): void; deleteBucket( - request: protos.google.logging.v2.IDeleteBucketRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.logging.v2.IDeleteBucketRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.logging.v2.IDeleteBucketRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.logging.v2.IDeleteBucketRequest | null | undefined, + {} | null | undefined + >, + ): void; deleteBucket( - request?: protos.google.logging.v2.IDeleteBucketRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.protobuf.IEmpty, - protos.google.logging.v2.IDeleteBucketRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.logging.v2.IDeleteBucketRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.logging.v2.IDeleteBucketRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.logging.v2.IDeleteBucketRequest|undefined, {}|undefined - ]>|void { + protos.google.logging.v2.IDeleteBucketRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + protos.google.logging.v2.IDeleteBucketRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.logging.v2.IDeleteBucketRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('deleteBucket request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.logging.v2.IDeleteBucketRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + protos.google.logging.v2.IDeleteBucketRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteBucket response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.deleteBucket(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.logging.v2.IDeleteBucketRequest|undefined, - {}|undefined - ]) => { - this._log.info('deleteBucket response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteBucket(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.logging.v2.IDeleteBucketRequest | undefined, + {} | undefined, + ]) => { + this._log.info('deleteBucket response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Undeletes a log bucket. A bucket that has been deleted can be undeleted - * within the grace period of 7 days. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The full resource name of the bucket to undelete. - * - * "projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" - * "organizations/[ORGANIZATION_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" - * "billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" - * "folders/[FOLDER_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" - * - * For example: - * - * `"projects/my-project/locations/global/buckets/my-bucket"` - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/config_service_v2.undelete_bucket.js - * region_tag:logging_v2_generated_ConfigServiceV2_UndeleteBucket_async - */ + /** + * Undeletes a log bucket. A bucket that has been deleted can be undeleted + * within the grace period of 7 days. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The full resource name of the bucket to undelete. + * + * "projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" + * "organizations/[ORGANIZATION_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" + * "billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" + * "folders/[FOLDER_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" + * + * For example: + * + * `"projects/my-project/locations/global/buckets/my-bucket"` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/config_service_v2.undelete_bucket.js + * region_tag:logging_v2_generated_ConfigServiceV2_UndeleteBucket_async + */ undeleteBucket( - request?: protos.google.logging.v2.IUndeleteBucketRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.logging.v2.IUndeleteBucketRequest|undefined, {}|undefined - ]>; + request?: protos.google.logging.v2.IUndeleteBucketRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.logging.v2.IUndeleteBucketRequest | undefined, + {} | undefined, + ] + >; undeleteBucket( - request: protos.google.logging.v2.IUndeleteBucketRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.logging.v2.IUndeleteBucketRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.logging.v2.IUndeleteBucketRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.logging.v2.IUndeleteBucketRequest | null | undefined, + {} | null | undefined + >, + ): void; undeleteBucket( - request: protos.google.logging.v2.IUndeleteBucketRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.logging.v2.IUndeleteBucketRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.logging.v2.IUndeleteBucketRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.logging.v2.IUndeleteBucketRequest | null | undefined, + {} | null | undefined + >, + ): void; undeleteBucket( - request?: protos.google.logging.v2.IUndeleteBucketRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.protobuf.IEmpty, - protos.google.logging.v2.IUndeleteBucketRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.logging.v2.IUndeleteBucketRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.logging.v2.IUndeleteBucketRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.logging.v2.IUndeleteBucketRequest|undefined, {}|undefined - ]>|void { + protos.google.logging.v2.IUndeleteBucketRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + protos.google.logging.v2.IUndeleteBucketRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.logging.v2.IUndeleteBucketRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('undeleteBucket request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.logging.v2.IUndeleteBucketRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + protos.google.logging.v2.IUndeleteBucketRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('undeleteBucket response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.undeleteBucket(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.logging.v2.IUndeleteBucketRequest|undefined, - {}|undefined - ]) => { - this._log.info('undeleteBucket response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .undeleteBucket(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.logging.v2.IUndeleteBucketRequest | undefined, + {} | undefined, + ]) => { + this._log.info('undeleteBucket response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Gets a view on a log bucket.. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The resource name of the policy: - * - * "projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]" - * - * For example: - * - * `"projects/my-project/locations/global/buckets/my-bucket/views/my-view"` - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.logging.v2.LogView|LogView}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/config_service_v2.get_view.js - * region_tag:logging_v2_generated_ConfigServiceV2_GetView_async - */ + /** + * Gets a view on a log bucket.. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The resource name of the policy: + * + * "projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]" + * + * For example: + * + * `"projects/my-project/locations/global/buckets/my-bucket/views/my-view"` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.logging.v2.LogView|LogView}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/config_service_v2.get_view.js + * region_tag:logging_v2_generated_ConfigServiceV2_GetView_async + */ getView( - request?: protos.google.logging.v2.IGetViewRequest, - options?: CallOptions): - Promise<[ - protos.google.logging.v2.ILogView, - protos.google.logging.v2.IGetViewRequest|undefined, {}|undefined - ]>; + request?: protos.google.logging.v2.IGetViewRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.logging.v2.ILogView, + protos.google.logging.v2.IGetViewRequest | undefined, + {} | undefined, + ] + >; getView( - request: protos.google.logging.v2.IGetViewRequest, - options: CallOptions, - callback: Callback< - protos.google.logging.v2.ILogView, - protos.google.logging.v2.IGetViewRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.logging.v2.IGetViewRequest, + options: CallOptions, + callback: Callback< + protos.google.logging.v2.ILogView, + protos.google.logging.v2.IGetViewRequest | null | undefined, + {} | null | undefined + >, + ): void; getView( - request: protos.google.logging.v2.IGetViewRequest, - callback: Callback< - protos.google.logging.v2.ILogView, - protos.google.logging.v2.IGetViewRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.logging.v2.IGetViewRequest, + callback: Callback< + protos.google.logging.v2.ILogView, + protos.google.logging.v2.IGetViewRequest | null | undefined, + {} | null | undefined + >, + ): void; getView( - request?: protos.google.logging.v2.IGetViewRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.logging.v2.IGetViewRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.logging.v2.ILogView, - protos.google.logging.v2.IGetViewRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.logging.v2.ILogView, - protos.google.logging.v2.IGetViewRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.logging.v2.ILogView, - protos.google.logging.v2.IGetViewRequest|undefined, {}|undefined - ]>|void { + protos.google.logging.v2.IGetViewRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.logging.v2.ILogView, + protos.google.logging.v2.IGetViewRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.logging.v2.ILogView, + protos.google.logging.v2.IGetViewRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getView request %j', request); - const wrappedCallback: Callback< - protos.google.logging.v2.ILogView, - protos.google.logging.v2.IGetViewRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.logging.v2.ILogView, + protos.google.logging.v2.IGetViewRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getView response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getView(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.logging.v2.ILogView, - protos.google.logging.v2.IGetViewRequest|undefined, - {}|undefined - ]) => { - this._log.info('getView response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getView(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.logging.v2.ILogView, + protos.google.logging.v2.IGetViewRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getView response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Creates a view over log entries in a log bucket. A bucket may contain a - * maximum of 30 views. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The bucket in which to create the view - * - * `"projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]"` - * - * For example: - * - * `"projects/my-project/locations/global/buckets/my-bucket"` - * @param {string} request.viewId - * Required. The id to use for this view. - * @param {google.logging.v2.LogView} request.view - * Required. The new view. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.logging.v2.LogView|LogView}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/config_service_v2.create_view.js - * region_tag:logging_v2_generated_ConfigServiceV2_CreateView_async - */ + /** + * Creates a view over log entries in a log bucket. A bucket may contain a + * maximum of 30 views. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The bucket in which to create the view + * + * `"projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]"` + * + * For example: + * + * `"projects/my-project/locations/global/buckets/my-bucket"` + * @param {string} request.viewId + * Required. The id to use for this view. + * @param {google.logging.v2.LogView} request.view + * Required. The new view. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.logging.v2.LogView|LogView}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/config_service_v2.create_view.js + * region_tag:logging_v2_generated_ConfigServiceV2_CreateView_async + */ createView( - request?: protos.google.logging.v2.ICreateViewRequest, - options?: CallOptions): - Promise<[ - protos.google.logging.v2.ILogView, - protos.google.logging.v2.ICreateViewRequest|undefined, {}|undefined - ]>; + request?: protos.google.logging.v2.ICreateViewRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.logging.v2.ILogView, + protos.google.logging.v2.ICreateViewRequest | undefined, + {} | undefined, + ] + >; createView( - request: protos.google.logging.v2.ICreateViewRequest, - options: CallOptions, - callback: Callback< - protos.google.logging.v2.ILogView, - protos.google.logging.v2.ICreateViewRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.logging.v2.ICreateViewRequest, + options: CallOptions, + callback: Callback< + protos.google.logging.v2.ILogView, + protos.google.logging.v2.ICreateViewRequest | null | undefined, + {} | null | undefined + >, + ): void; createView( - request: protos.google.logging.v2.ICreateViewRequest, - callback: Callback< - protos.google.logging.v2.ILogView, - protos.google.logging.v2.ICreateViewRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.logging.v2.ICreateViewRequest, + callback: Callback< + protos.google.logging.v2.ILogView, + protos.google.logging.v2.ICreateViewRequest | null | undefined, + {} | null | undefined + >, + ): void; createView( - request?: protos.google.logging.v2.ICreateViewRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.logging.v2.ILogView, - protos.google.logging.v2.ICreateViewRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.logging.v2.ICreateViewRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.logging.v2.ILogView, - protos.google.logging.v2.ICreateViewRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.logging.v2.ILogView, - protos.google.logging.v2.ICreateViewRequest|undefined, {}|undefined - ]>|void { + protos.google.logging.v2.ICreateViewRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.logging.v2.ILogView, + protos.google.logging.v2.ICreateViewRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.logging.v2.ILogView, + protos.google.logging.v2.ICreateViewRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('createView request %j', request); - const wrappedCallback: Callback< - protos.google.logging.v2.ILogView, - protos.google.logging.v2.ICreateViewRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.logging.v2.ILogView, + protos.google.logging.v2.ICreateViewRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createView response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.createView(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.logging.v2.ILogView, - protos.google.logging.v2.ICreateViewRequest|undefined, - {}|undefined - ]) => { - this._log.info('createView response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createView(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.logging.v2.ILogView, + protos.google.logging.v2.ICreateViewRequest | undefined, + {} | undefined, + ]) => { + this._log.info('createView response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Updates a view on a log bucket. This method replaces the following fields - * in the existing view with values from the new view: `filter`. - * If an `UNAVAILABLE` error is returned, this indicates that system is not in - * a state where it can update the view. If this occurs, please try again in a - * few minutes. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The full resource name of the view to update - * - * "projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]" - * - * For example: - * - * `"projects/my-project/locations/global/buckets/my-bucket/views/my-view"` - * @param {google.logging.v2.LogView} request.view - * Required. The updated view. - * @param {google.protobuf.FieldMask} [request.updateMask] - * Optional. Field mask that specifies the fields in `view` that need - * an update. A field will be overwritten if, and only if, it is - * in the update mask. `name` and output only fields cannot be updated. - * - * For a detailed `FieldMask` definition, see - * https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#google.protobuf.FieldMask - * - * For example: `updateMask=filter` - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.logging.v2.LogView|LogView}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/config_service_v2.update_view.js - * region_tag:logging_v2_generated_ConfigServiceV2_UpdateView_async - */ + /** + * Updates a view on a log bucket. This method replaces the following fields + * in the existing view with values from the new view: `filter`. + * If an `UNAVAILABLE` error is returned, this indicates that system is not in + * a state where it can update the view. If this occurs, please try again in a + * few minutes. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The full resource name of the view to update + * + * "projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]" + * + * For example: + * + * `"projects/my-project/locations/global/buckets/my-bucket/views/my-view"` + * @param {google.logging.v2.LogView} request.view + * Required. The updated view. + * @param {google.protobuf.FieldMask} [request.updateMask] + * Optional. Field mask that specifies the fields in `view` that need + * an update. A field will be overwritten if, and only if, it is + * in the update mask. `name` and output only fields cannot be updated. + * + * For a detailed `FieldMask` definition, see + * https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#google.protobuf.FieldMask + * + * For example: `updateMask=filter` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.logging.v2.LogView|LogView}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/config_service_v2.update_view.js + * region_tag:logging_v2_generated_ConfigServiceV2_UpdateView_async + */ updateView( - request?: protos.google.logging.v2.IUpdateViewRequest, - options?: CallOptions): - Promise<[ - protos.google.logging.v2.ILogView, - protos.google.logging.v2.IUpdateViewRequest|undefined, {}|undefined - ]>; + request?: protos.google.logging.v2.IUpdateViewRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.logging.v2.ILogView, + protos.google.logging.v2.IUpdateViewRequest | undefined, + {} | undefined, + ] + >; updateView( - request: protos.google.logging.v2.IUpdateViewRequest, - options: CallOptions, - callback: Callback< - protos.google.logging.v2.ILogView, - protos.google.logging.v2.IUpdateViewRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.logging.v2.IUpdateViewRequest, + options: CallOptions, + callback: Callback< + protos.google.logging.v2.ILogView, + protos.google.logging.v2.IUpdateViewRequest | null | undefined, + {} | null | undefined + >, + ): void; updateView( - request: protos.google.logging.v2.IUpdateViewRequest, - callback: Callback< - protos.google.logging.v2.ILogView, - protos.google.logging.v2.IUpdateViewRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.logging.v2.IUpdateViewRequest, + callback: Callback< + protos.google.logging.v2.ILogView, + protos.google.logging.v2.IUpdateViewRequest | null | undefined, + {} | null | undefined + >, + ): void; updateView( - request?: protos.google.logging.v2.IUpdateViewRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.logging.v2.ILogView, - protos.google.logging.v2.IUpdateViewRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.logging.v2.IUpdateViewRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.logging.v2.ILogView, - protos.google.logging.v2.IUpdateViewRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.logging.v2.ILogView, - protos.google.logging.v2.IUpdateViewRequest|undefined, {}|undefined - ]>|void { + protos.google.logging.v2.IUpdateViewRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.logging.v2.ILogView, + protos.google.logging.v2.IUpdateViewRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.logging.v2.ILogView, + protos.google.logging.v2.IUpdateViewRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateView request %j', request); - const wrappedCallback: Callback< - protos.google.logging.v2.ILogView, - protos.google.logging.v2.IUpdateViewRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.logging.v2.ILogView, + protos.google.logging.v2.IUpdateViewRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateView response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.updateView(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.logging.v2.ILogView, - protos.google.logging.v2.IUpdateViewRequest|undefined, - {}|undefined - ]) => { - this._log.info('updateView response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateView(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.logging.v2.ILogView, + protos.google.logging.v2.IUpdateViewRequest | undefined, + {} | undefined, + ]) => { + this._log.info('updateView response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Deletes a view on a log bucket. - * If an `UNAVAILABLE` error is returned, this indicates that system is not in - * a state where it can delete the view. If this occurs, please try again in a - * few minutes. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The full resource name of the view to delete: - * - * "projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]" - * - * For example: - * - * `"projects/my-project/locations/global/buckets/my-bucket/views/my-view"` - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/config_service_v2.delete_view.js - * region_tag:logging_v2_generated_ConfigServiceV2_DeleteView_async - */ + /** + * Deletes a view on a log bucket. + * If an `UNAVAILABLE` error is returned, this indicates that system is not in + * a state where it can delete the view. If this occurs, please try again in a + * few minutes. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The full resource name of the view to delete: + * + * "projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]" + * + * For example: + * + * `"projects/my-project/locations/global/buckets/my-bucket/views/my-view"` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/config_service_v2.delete_view.js + * region_tag:logging_v2_generated_ConfigServiceV2_DeleteView_async + */ deleteView( - request?: protos.google.logging.v2.IDeleteViewRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.logging.v2.IDeleteViewRequest|undefined, {}|undefined - ]>; + request?: protos.google.logging.v2.IDeleteViewRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.logging.v2.IDeleteViewRequest | undefined, + {} | undefined, + ] + >; deleteView( - request: protos.google.logging.v2.IDeleteViewRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.logging.v2.IDeleteViewRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.logging.v2.IDeleteViewRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.logging.v2.IDeleteViewRequest | null | undefined, + {} | null | undefined + >, + ): void; deleteView( - request: protos.google.logging.v2.IDeleteViewRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.logging.v2.IDeleteViewRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.logging.v2.IDeleteViewRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.logging.v2.IDeleteViewRequest | null | undefined, + {} | null | undefined + >, + ): void; deleteView( - request?: protos.google.logging.v2.IDeleteViewRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.protobuf.IEmpty, - protos.google.logging.v2.IDeleteViewRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.logging.v2.IDeleteViewRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.logging.v2.IDeleteViewRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.logging.v2.IDeleteViewRequest|undefined, {}|undefined - ]>|void { + protos.google.logging.v2.IDeleteViewRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + protos.google.logging.v2.IDeleteViewRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.logging.v2.IDeleteViewRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('deleteView request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.logging.v2.IDeleteViewRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + protos.google.logging.v2.IDeleteViewRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteView response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.deleteView(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.logging.v2.IDeleteViewRequest|undefined, - {}|undefined - ]) => { - this._log.info('deleteView response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteView(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.logging.v2.IDeleteViewRequest | undefined, + {} | undefined, + ]) => { + this._log.info('deleteView response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Gets a sink. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.sinkName - * Required. The resource name of the sink: - * - * "projects/[PROJECT_ID]/sinks/[SINK_ID]" - * "organizations/[ORGANIZATION_ID]/sinks/[SINK_ID]" - * "billingAccounts/[BILLING_ACCOUNT_ID]/sinks/[SINK_ID]" - * "folders/[FOLDER_ID]/sinks/[SINK_ID]" - * - * For example: - * - * `"projects/my-project/sinks/my-sink"` - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.logging.v2.LogSink|LogSink}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/config_service_v2.get_sink.js - * region_tag:logging_v2_generated_ConfigServiceV2_GetSink_async - */ + /** + * Gets a sink. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.sinkName + * Required. The resource name of the sink: + * + * "projects/[PROJECT_ID]/sinks/[SINK_ID]" + * "organizations/[ORGANIZATION_ID]/sinks/[SINK_ID]" + * "billingAccounts/[BILLING_ACCOUNT_ID]/sinks/[SINK_ID]" + * "folders/[FOLDER_ID]/sinks/[SINK_ID]" + * + * For example: + * + * `"projects/my-project/sinks/my-sink"` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.logging.v2.LogSink|LogSink}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/config_service_v2.get_sink.js + * region_tag:logging_v2_generated_ConfigServiceV2_GetSink_async + */ getSink( - request?: protos.google.logging.v2.IGetSinkRequest, - options?: CallOptions): - Promise<[ - protos.google.logging.v2.ILogSink, - protos.google.logging.v2.IGetSinkRequest|undefined, {}|undefined - ]>; + request?: protos.google.logging.v2.IGetSinkRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.logging.v2.ILogSink, + protos.google.logging.v2.IGetSinkRequest | undefined, + {} | undefined, + ] + >; getSink( - request: protos.google.logging.v2.IGetSinkRequest, - options: CallOptions, - callback: Callback< - protos.google.logging.v2.ILogSink, - protos.google.logging.v2.IGetSinkRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.logging.v2.IGetSinkRequest, + options: CallOptions, + callback: Callback< + protos.google.logging.v2.ILogSink, + protos.google.logging.v2.IGetSinkRequest | null | undefined, + {} | null | undefined + >, + ): void; getSink( - request: protos.google.logging.v2.IGetSinkRequest, - callback: Callback< - protos.google.logging.v2.ILogSink, - protos.google.logging.v2.IGetSinkRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.logging.v2.IGetSinkRequest, + callback: Callback< + protos.google.logging.v2.ILogSink, + protos.google.logging.v2.IGetSinkRequest | null | undefined, + {} | null | undefined + >, + ): void; getSink( - request?: protos.google.logging.v2.IGetSinkRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.logging.v2.ILogSink, - protos.google.logging.v2.IGetSinkRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.logging.v2.IGetSinkRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.logging.v2.ILogSink, - protos.google.logging.v2.IGetSinkRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.logging.v2.ILogSink, - protos.google.logging.v2.IGetSinkRequest|undefined, {}|undefined - ]>|void { + protos.google.logging.v2.IGetSinkRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.logging.v2.ILogSink, + protos.google.logging.v2.IGetSinkRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.logging.v2.ILogSink, + protos.google.logging.v2.IGetSinkRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'sink_name': request.sinkName ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + sink_name: request.sinkName ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getSink request %j', request); - const wrappedCallback: Callback< - protos.google.logging.v2.ILogSink, - protos.google.logging.v2.IGetSinkRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.logging.v2.ILogSink, + protos.google.logging.v2.IGetSinkRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getSink response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getSink(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.logging.v2.ILogSink, - protos.google.logging.v2.IGetSinkRequest|undefined, - {}|undefined - ]) => { - this._log.info('getSink response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getSink(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.logging.v2.ILogSink, + protos.google.logging.v2.IGetSinkRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getSink response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Creates a sink that exports specified log entries to a destination. The - * export of newly-ingested log entries begins immediately, unless the sink's - * `writer_identity` is not permitted to write to the destination. A sink can - * export log entries only from the resource owning the sink. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The resource in which to create the sink: - * - * "projects/[PROJECT_ID]" - * "organizations/[ORGANIZATION_ID]" - * "billingAccounts/[BILLING_ACCOUNT_ID]" - * "folders/[FOLDER_ID]" - * - * For examples: - * - * `"projects/my-project"` - * `"organizations/123456789"` - * @param {google.logging.v2.LogSink} request.sink - * Required. The new sink, whose `name` parameter is a sink identifier that - * is not already in use. - * @param {boolean} [request.uniqueWriterIdentity] - * Optional. Determines the kind of IAM identity returned as `writer_identity` - * in the new sink. If this value is omitted or set to false, and if the - * sink's parent is a project, then the value returned as `writer_identity` is - * the same group or service account used by Cloud Logging before the addition - * of writer identities to this API. The sink's destination must be in the - * same project as the sink itself. - * - * If this field is set to true, or if the sink is owned by a non-project - * resource such as an organization, then the value of `writer_identity` will - * be a unique service account used only for exports from the new sink. For - * more information, see `writer_identity` in {@link protos.google.logging.v2.LogSink|LogSink}. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.logging.v2.LogSink|LogSink}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/config_service_v2.create_sink.js - * region_tag:logging_v2_generated_ConfigServiceV2_CreateSink_async - */ + /** + * Creates a sink that exports specified log entries to a destination. The + * export of newly-ingested log entries begins immediately, unless the sink's + * `writer_identity` is not permitted to write to the destination. A sink can + * export log entries only from the resource owning the sink. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The resource in which to create the sink: + * + * "projects/[PROJECT_ID]" + * "organizations/[ORGANIZATION_ID]" + * "billingAccounts/[BILLING_ACCOUNT_ID]" + * "folders/[FOLDER_ID]" + * + * For examples: + * + * `"projects/my-project"` + * `"organizations/123456789"` + * @param {google.logging.v2.LogSink} request.sink + * Required. The new sink, whose `name` parameter is a sink identifier that + * is not already in use. + * @param {boolean} [request.uniqueWriterIdentity] + * Optional. Determines the kind of IAM identity returned as `writer_identity` + * in the new sink. If this value is omitted or set to false, and if the + * sink's parent is a project, then the value returned as `writer_identity` is + * the same group or service account used by Cloud Logging before the addition + * of writer identities to this API. The sink's destination must be in the + * same project as the sink itself. + * + * If this field is set to true, or if the sink is owned by a non-project + * resource such as an organization, then the value of `writer_identity` will + * be a unique service account used only for exports from the new sink. For + * more information, see `writer_identity` in {@link protos.google.logging.v2.LogSink|LogSink}. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.logging.v2.LogSink|LogSink}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/config_service_v2.create_sink.js + * region_tag:logging_v2_generated_ConfigServiceV2_CreateSink_async + */ createSink( - request?: protos.google.logging.v2.ICreateSinkRequest, - options?: CallOptions): - Promise<[ - protos.google.logging.v2.ILogSink, - protos.google.logging.v2.ICreateSinkRequest|undefined, {}|undefined - ]>; + request?: protos.google.logging.v2.ICreateSinkRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.logging.v2.ILogSink, + protos.google.logging.v2.ICreateSinkRequest | undefined, + {} | undefined, + ] + >; createSink( - request: protos.google.logging.v2.ICreateSinkRequest, - options: CallOptions, - callback: Callback< - protos.google.logging.v2.ILogSink, - protos.google.logging.v2.ICreateSinkRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.logging.v2.ICreateSinkRequest, + options: CallOptions, + callback: Callback< + protos.google.logging.v2.ILogSink, + protos.google.logging.v2.ICreateSinkRequest | null | undefined, + {} | null | undefined + >, + ): void; createSink( - request: protos.google.logging.v2.ICreateSinkRequest, - callback: Callback< - protos.google.logging.v2.ILogSink, - protos.google.logging.v2.ICreateSinkRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.logging.v2.ICreateSinkRequest, + callback: Callback< + protos.google.logging.v2.ILogSink, + protos.google.logging.v2.ICreateSinkRequest | null | undefined, + {} | null | undefined + >, + ): void; createSink( - request?: protos.google.logging.v2.ICreateSinkRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.logging.v2.ICreateSinkRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.logging.v2.ILogSink, - protos.google.logging.v2.ICreateSinkRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.logging.v2.ILogSink, - protos.google.logging.v2.ICreateSinkRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.logging.v2.ILogSink, - protos.google.logging.v2.ICreateSinkRequest|undefined, {}|undefined - ]>|void { + protos.google.logging.v2.ICreateSinkRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.logging.v2.ILogSink, + protos.google.logging.v2.ICreateSinkRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.logging.v2.ILogSink, + protos.google.logging.v2.ICreateSinkRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('createSink request %j', request); - const wrappedCallback: Callback< - protos.google.logging.v2.ILogSink, - protos.google.logging.v2.ICreateSinkRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.logging.v2.ILogSink, + protos.google.logging.v2.ICreateSinkRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createSink response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.createSink(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.logging.v2.ILogSink, - protos.google.logging.v2.ICreateSinkRequest|undefined, - {}|undefined - ]) => { - this._log.info('createSink response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createSink(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.logging.v2.ILogSink, + protos.google.logging.v2.ICreateSinkRequest | undefined, + {} | undefined, + ]) => { + this._log.info('createSink response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Updates a sink. This method replaces the following fields in the existing - * sink with values from the new sink: `destination`, and `filter`. - * - * The updated sink might also have a new `writer_identity`; see the - * `unique_writer_identity` field. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.sinkName - * Required. The full resource name of the sink to update, including the parent - * resource and the sink identifier: - * - * "projects/[PROJECT_ID]/sinks/[SINK_ID]" - * "organizations/[ORGANIZATION_ID]/sinks/[SINK_ID]" - * "billingAccounts/[BILLING_ACCOUNT_ID]/sinks/[SINK_ID]" - * "folders/[FOLDER_ID]/sinks/[SINK_ID]" - * - * For example: - * - * `"projects/my-project/sinks/my-sink"` - * @param {google.logging.v2.LogSink} request.sink - * Required. The updated sink, whose name is the same identifier that appears as part - * of `sink_name`. - * @param {boolean} [request.uniqueWriterIdentity] - * Optional. See {@link protos.google.logging.v2.ConfigServiceV2.CreateSink|sinks.create} - * for a description of this field. When updating a sink, the effect of this - * field on the value of `writer_identity` in the updated sink depends on both - * the old and new values of this field: - * - * + If the old and new values of this field are both false or both true, - * then there is no change to the sink's `writer_identity`. - * + If the old value is false and the new value is true, then - * `writer_identity` is changed to a unique service account. - * + It is an error if the old value is true and the new value is - * set to false or defaulted to false. - * @param {google.protobuf.FieldMask} [request.updateMask] - * Optional. Field mask that specifies the fields in `sink` that need - * an update. A sink field will be overwritten if, and only if, it is - * in the update mask. `name` and output only fields cannot be updated. - * - * An empty `updateMask` is temporarily treated as using the following mask - * for backwards compatibility purposes: - * - * `destination,filter,includeChildren` - * - * At some point in the future, behavior will be removed and specifying an - * empty `updateMask` will be an error. - * - * For a detailed `FieldMask` definition, see - * https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#google.protobuf.FieldMask - * - * For example: `updateMask=filter` - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.logging.v2.LogSink|LogSink}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/config_service_v2.update_sink.js - * region_tag:logging_v2_generated_ConfigServiceV2_UpdateSink_async - */ + /** + * Updates a sink. This method replaces the following fields in the existing + * sink with values from the new sink: `destination`, and `filter`. + * + * The updated sink might also have a new `writer_identity`; see the + * `unique_writer_identity` field. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.sinkName + * Required. The full resource name of the sink to update, including the parent + * resource and the sink identifier: + * + * "projects/[PROJECT_ID]/sinks/[SINK_ID]" + * "organizations/[ORGANIZATION_ID]/sinks/[SINK_ID]" + * "billingAccounts/[BILLING_ACCOUNT_ID]/sinks/[SINK_ID]" + * "folders/[FOLDER_ID]/sinks/[SINK_ID]" + * + * For example: + * + * `"projects/my-project/sinks/my-sink"` + * @param {google.logging.v2.LogSink} request.sink + * Required. The updated sink, whose name is the same identifier that appears as part + * of `sink_name`. + * @param {boolean} [request.uniqueWriterIdentity] + * Optional. See {@link protos.google.logging.v2.ConfigServiceV2.CreateSink|sinks.create} + * for a description of this field. When updating a sink, the effect of this + * field on the value of `writer_identity` in the updated sink depends on both + * the old and new values of this field: + * + * + If the old and new values of this field are both false or both true, + * then there is no change to the sink's `writer_identity`. + * + If the old value is false and the new value is true, then + * `writer_identity` is changed to a unique service account. + * + It is an error if the old value is true and the new value is + * set to false or defaulted to false. + * @param {google.protobuf.FieldMask} [request.updateMask] + * Optional. Field mask that specifies the fields in `sink` that need + * an update. A sink field will be overwritten if, and only if, it is + * in the update mask. `name` and output only fields cannot be updated. + * + * An empty `updateMask` is temporarily treated as using the following mask + * for backwards compatibility purposes: + * + * `destination,filter,includeChildren` + * + * At some point in the future, behavior will be removed and specifying an + * empty `updateMask` will be an error. + * + * For a detailed `FieldMask` definition, see + * https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#google.protobuf.FieldMask + * + * For example: `updateMask=filter` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.logging.v2.LogSink|LogSink}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/config_service_v2.update_sink.js + * region_tag:logging_v2_generated_ConfigServiceV2_UpdateSink_async + */ updateSink( - request?: protos.google.logging.v2.IUpdateSinkRequest, - options?: CallOptions): - Promise<[ - protos.google.logging.v2.ILogSink, - protos.google.logging.v2.IUpdateSinkRequest|undefined, {}|undefined - ]>; + request?: protos.google.logging.v2.IUpdateSinkRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.logging.v2.ILogSink, + protos.google.logging.v2.IUpdateSinkRequest | undefined, + {} | undefined, + ] + >; updateSink( - request: protos.google.logging.v2.IUpdateSinkRequest, - options: CallOptions, - callback: Callback< - protos.google.logging.v2.ILogSink, - protos.google.logging.v2.IUpdateSinkRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.logging.v2.IUpdateSinkRequest, + options: CallOptions, + callback: Callback< + protos.google.logging.v2.ILogSink, + protos.google.logging.v2.IUpdateSinkRequest | null | undefined, + {} | null | undefined + >, + ): void; updateSink( - request: protos.google.logging.v2.IUpdateSinkRequest, - callback: Callback< - protos.google.logging.v2.ILogSink, - protos.google.logging.v2.IUpdateSinkRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.logging.v2.IUpdateSinkRequest, + callback: Callback< + protos.google.logging.v2.ILogSink, + protos.google.logging.v2.IUpdateSinkRequest | null | undefined, + {} | null | undefined + >, + ): void; updateSink( - request?: protos.google.logging.v2.IUpdateSinkRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.logging.v2.ILogSink, - protos.google.logging.v2.IUpdateSinkRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.logging.v2.IUpdateSinkRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.logging.v2.ILogSink, - protos.google.logging.v2.IUpdateSinkRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.logging.v2.ILogSink, - protos.google.logging.v2.IUpdateSinkRequest|undefined, {}|undefined - ]>|void { + protos.google.logging.v2.IUpdateSinkRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.logging.v2.ILogSink, + protos.google.logging.v2.IUpdateSinkRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.logging.v2.ILogSink, + protos.google.logging.v2.IUpdateSinkRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'sink_name': request.sinkName ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + sink_name: request.sinkName ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateSink request %j', request); - const wrappedCallback: Callback< - protos.google.logging.v2.ILogSink, - protos.google.logging.v2.IUpdateSinkRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.logging.v2.ILogSink, + protos.google.logging.v2.IUpdateSinkRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateSink response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.updateSink(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.logging.v2.ILogSink, - protos.google.logging.v2.IUpdateSinkRequest|undefined, - {}|undefined - ]) => { - this._log.info('updateSink response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateSink(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.logging.v2.ILogSink, + protos.google.logging.v2.IUpdateSinkRequest | undefined, + {} | undefined, + ]) => { + this._log.info('updateSink response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Deletes a sink. If the sink has a unique `writer_identity`, then that - * service account is also deleted. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.sinkName - * Required. The full resource name of the sink to delete, including the parent - * resource and the sink identifier: - * - * "projects/[PROJECT_ID]/sinks/[SINK_ID]" - * "organizations/[ORGANIZATION_ID]/sinks/[SINK_ID]" - * "billingAccounts/[BILLING_ACCOUNT_ID]/sinks/[SINK_ID]" - * "folders/[FOLDER_ID]/sinks/[SINK_ID]" - * - * For example: - * - * `"projects/my-project/sinks/my-sink"` - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/config_service_v2.delete_sink.js - * region_tag:logging_v2_generated_ConfigServiceV2_DeleteSink_async - */ + /** + * Deletes a sink. If the sink has a unique `writer_identity`, then that + * service account is also deleted. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.sinkName + * Required. The full resource name of the sink to delete, including the parent + * resource and the sink identifier: + * + * "projects/[PROJECT_ID]/sinks/[SINK_ID]" + * "organizations/[ORGANIZATION_ID]/sinks/[SINK_ID]" + * "billingAccounts/[BILLING_ACCOUNT_ID]/sinks/[SINK_ID]" + * "folders/[FOLDER_ID]/sinks/[SINK_ID]" + * + * For example: + * + * `"projects/my-project/sinks/my-sink"` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/config_service_v2.delete_sink.js + * region_tag:logging_v2_generated_ConfigServiceV2_DeleteSink_async + */ deleteSink( - request?: protos.google.logging.v2.IDeleteSinkRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.logging.v2.IDeleteSinkRequest|undefined, {}|undefined - ]>; + request?: protos.google.logging.v2.IDeleteSinkRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.logging.v2.IDeleteSinkRequest | undefined, + {} | undefined, + ] + >; deleteSink( - request: protos.google.logging.v2.IDeleteSinkRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.logging.v2.IDeleteSinkRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.logging.v2.IDeleteSinkRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.logging.v2.IDeleteSinkRequest | null | undefined, + {} | null | undefined + >, + ): void; deleteSink( - request: protos.google.logging.v2.IDeleteSinkRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.logging.v2.IDeleteSinkRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.logging.v2.IDeleteSinkRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.logging.v2.IDeleteSinkRequest | null | undefined, + {} | null | undefined + >, + ): void; deleteSink( - request?: protos.google.logging.v2.IDeleteSinkRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.logging.v2.IDeleteSinkRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.logging.v2.IDeleteSinkRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.protobuf.IEmpty, - protos.google.logging.v2.IDeleteSinkRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.logging.v2.IDeleteSinkRequest|undefined, {}|undefined - ]>|void { + protos.google.logging.v2.IDeleteSinkRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + protos.google.logging.v2.IDeleteSinkRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.logging.v2.IDeleteSinkRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'sink_name': request.sinkName ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + sink_name: request.sinkName ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('deleteSink request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.logging.v2.IDeleteSinkRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + protos.google.logging.v2.IDeleteSinkRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteSink response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.deleteSink(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.logging.v2.IDeleteSinkRequest|undefined, - {}|undefined - ]) => { - this._log.info('deleteSink response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteSink(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.logging.v2.IDeleteSinkRequest | undefined, + {} | undefined, + ]) => { + this._log.info('deleteSink response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Gets the description of an exclusion in the _Default sink. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The resource name of an existing exclusion: - * - * "projects/[PROJECT_ID]/exclusions/[EXCLUSION_ID]" - * "organizations/[ORGANIZATION_ID]/exclusions/[EXCLUSION_ID]" - * "billingAccounts/[BILLING_ACCOUNT_ID]/exclusions/[EXCLUSION_ID]" - * "folders/[FOLDER_ID]/exclusions/[EXCLUSION_ID]" - * - * For example: - * - * `"projects/my-project/exclusions/my-exclusion"` - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.logging.v2.LogExclusion|LogExclusion}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/config_service_v2.get_exclusion.js - * region_tag:logging_v2_generated_ConfigServiceV2_GetExclusion_async - */ + /** + * Gets the description of an exclusion in the _Default sink. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The resource name of an existing exclusion: + * + * "projects/[PROJECT_ID]/exclusions/[EXCLUSION_ID]" + * "organizations/[ORGANIZATION_ID]/exclusions/[EXCLUSION_ID]" + * "billingAccounts/[BILLING_ACCOUNT_ID]/exclusions/[EXCLUSION_ID]" + * "folders/[FOLDER_ID]/exclusions/[EXCLUSION_ID]" + * + * For example: + * + * `"projects/my-project/exclusions/my-exclusion"` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.logging.v2.LogExclusion|LogExclusion}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/config_service_v2.get_exclusion.js + * region_tag:logging_v2_generated_ConfigServiceV2_GetExclusion_async + */ getExclusion( - request?: protos.google.logging.v2.IGetExclusionRequest, - options?: CallOptions): - Promise<[ - protos.google.logging.v2.ILogExclusion, - protos.google.logging.v2.IGetExclusionRequest|undefined, {}|undefined - ]>; + request?: protos.google.logging.v2.IGetExclusionRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.logging.v2.ILogExclusion, + protos.google.logging.v2.IGetExclusionRequest | undefined, + {} | undefined, + ] + >; getExclusion( - request: protos.google.logging.v2.IGetExclusionRequest, - options: CallOptions, - callback: Callback< - protos.google.logging.v2.ILogExclusion, - protos.google.logging.v2.IGetExclusionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.logging.v2.IGetExclusionRequest, + options: CallOptions, + callback: Callback< + protos.google.logging.v2.ILogExclusion, + protos.google.logging.v2.IGetExclusionRequest | null | undefined, + {} | null | undefined + >, + ): void; getExclusion( - request: protos.google.logging.v2.IGetExclusionRequest, - callback: Callback< - protos.google.logging.v2.ILogExclusion, - protos.google.logging.v2.IGetExclusionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.logging.v2.IGetExclusionRequest, + callback: Callback< + protos.google.logging.v2.ILogExclusion, + protos.google.logging.v2.IGetExclusionRequest | null | undefined, + {} | null | undefined + >, + ): void; getExclusion( - request?: protos.google.logging.v2.IGetExclusionRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.logging.v2.ILogExclusion, - protos.google.logging.v2.IGetExclusionRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.logging.v2.IGetExclusionRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.logging.v2.ILogExclusion, - protos.google.logging.v2.IGetExclusionRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.logging.v2.ILogExclusion, - protos.google.logging.v2.IGetExclusionRequest|undefined, {}|undefined - ]>|void { + protos.google.logging.v2.IGetExclusionRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.logging.v2.ILogExclusion, + protos.google.logging.v2.IGetExclusionRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.logging.v2.ILogExclusion, + protos.google.logging.v2.IGetExclusionRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getExclusion request %j', request); - const wrappedCallback: Callback< - protos.google.logging.v2.ILogExclusion, - protos.google.logging.v2.IGetExclusionRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.logging.v2.ILogExclusion, + protos.google.logging.v2.IGetExclusionRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getExclusion response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getExclusion(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.logging.v2.ILogExclusion, - protos.google.logging.v2.IGetExclusionRequest|undefined, - {}|undefined - ]) => { - this._log.info('getExclusion response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getExclusion(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.logging.v2.ILogExclusion, + protos.google.logging.v2.IGetExclusionRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getExclusion response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Creates a new exclusion in the _Default sink in a specified parent - * resource. Only log entries belonging to that resource can be excluded. You - * can have up to 10 exclusions in a resource. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent resource in which to create the exclusion: - * - * "projects/[PROJECT_ID]" - * "organizations/[ORGANIZATION_ID]" - * "billingAccounts/[BILLING_ACCOUNT_ID]" - * "folders/[FOLDER_ID]" - * - * For examples: - * - * `"projects/my-logging-project"` - * `"organizations/123456789"` - * @param {google.logging.v2.LogExclusion} request.exclusion - * Required. The new exclusion, whose `name` parameter is an exclusion name - * that is not already used in the parent resource. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.logging.v2.LogExclusion|LogExclusion}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/config_service_v2.create_exclusion.js - * region_tag:logging_v2_generated_ConfigServiceV2_CreateExclusion_async - */ + /** + * Creates a new exclusion in the _Default sink in a specified parent + * resource. Only log entries belonging to that resource can be excluded. You + * can have up to 10 exclusions in a resource. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource in which to create the exclusion: + * + * "projects/[PROJECT_ID]" + * "organizations/[ORGANIZATION_ID]" + * "billingAccounts/[BILLING_ACCOUNT_ID]" + * "folders/[FOLDER_ID]" + * + * For examples: + * + * `"projects/my-logging-project"` + * `"organizations/123456789"` + * @param {google.logging.v2.LogExclusion} request.exclusion + * Required. The new exclusion, whose `name` parameter is an exclusion name + * that is not already used in the parent resource. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.logging.v2.LogExclusion|LogExclusion}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/config_service_v2.create_exclusion.js + * region_tag:logging_v2_generated_ConfigServiceV2_CreateExclusion_async + */ createExclusion( - request?: protos.google.logging.v2.ICreateExclusionRequest, - options?: CallOptions): - Promise<[ - protos.google.logging.v2.ILogExclusion, - protos.google.logging.v2.ICreateExclusionRequest|undefined, {}|undefined - ]>; + request?: protos.google.logging.v2.ICreateExclusionRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.logging.v2.ILogExclusion, + protos.google.logging.v2.ICreateExclusionRequest | undefined, + {} | undefined, + ] + >; createExclusion( - request: protos.google.logging.v2.ICreateExclusionRequest, - options: CallOptions, - callback: Callback< - protos.google.logging.v2.ILogExclusion, - protos.google.logging.v2.ICreateExclusionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.logging.v2.ICreateExclusionRequest, + options: CallOptions, + callback: Callback< + protos.google.logging.v2.ILogExclusion, + protos.google.logging.v2.ICreateExclusionRequest | null | undefined, + {} | null | undefined + >, + ): void; createExclusion( - request: protos.google.logging.v2.ICreateExclusionRequest, - callback: Callback< - protos.google.logging.v2.ILogExclusion, - protos.google.logging.v2.ICreateExclusionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.logging.v2.ICreateExclusionRequest, + callback: Callback< + protos.google.logging.v2.ILogExclusion, + protos.google.logging.v2.ICreateExclusionRequest | null | undefined, + {} | null | undefined + >, + ): void; createExclusion( - request?: protos.google.logging.v2.ICreateExclusionRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.logging.v2.ILogExclusion, - protos.google.logging.v2.ICreateExclusionRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.logging.v2.ICreateExclusionRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.logging.v2.ILogExclusion, - protos.google.logging.v2.ICreateExclusionRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.logging.v2.ILogExclusion, - protos.google.logging.v2.ICreateExclusionRequest|undefined, {}|undefined - ]>|void { + protos.google.logging.v2.ICreateExclusionRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.logging.v2.ILogExclusion, + protos.google.logging.v2.ICreateExclusionRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.logging.v2.ILogExclusion, + protos.google.logging.v2.ICreateExclusionRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('createExclusion request %j', request); - const wrappedCallback: Callback< - protos.google.logging.v2.ILogExclusion, - protos.google.logging.v2.ICreateExclusionRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.logging.v2.ILogExclusion, + protos.google.logging.v2.ICreateExclusionRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createExclusion response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.createExclusion(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.logging.v2.ILogExclusion, - protos.google.logging.v2.ICreateExclusionRequest|undefined, - {}|undefined - ]) => { - this._log.info('createExclusion response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createExclusion(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.logging.v2.ILogExclusion, + protos.google.logging.v2.ICreateExclusionRequest | undefined, + {} | undefined, + ]) => { + this._log.info('createExclusion response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Changes one or more properties of an existing exclusion in the _Default - * sink. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The resource name of the exclusion to update: - * - * "projects/[PROJECT_ID]/exclusions/[EXCLUSION_ID]" - * "organizations/[ORGANIZATION_ID]/exclusions/[EXCLUSION_ID]" - * "billingAccounts/[BILLING_ACCOUNT_ID]/exclusions/[EXCLUSION_ID]" - * "folders/[FOLDER_ID]/exclusions/[EXCLUSION_ID]" - * - * For example: - * - * `"projects/my-project/exclusions/my-exclusion"` - * @param {google.logging.v2.LogExclusion} request.exclusion - * Required. New values for the existing exclusion. Only the fields specified in - * `update_mask` are relevant. - * @param {google.protobuf.FieldMask} request.updateMask - * Required. A non-empty list of fields to change in the existing exclusion. New values - * for the fields are taken from the corresponding fields in the - * {@link protos.google.logging.v2.LogExclusion|LogExclusion} included in this request. Fields not mentioned in - * `update_mask` are not changed and are ignored in the request. - * - * For example, to change the filter and description of an exclusion, - * specify an `update_mask` of `"filter,description"`. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.logging.v2.LogExclusion|LogExclusion}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/config_service_v2.update_exclusion.js - * region_tag:logging_v2_generated_ConfigServiceV2_UpdateExclusion_async - */ + /** + * Changes one or more properties of an existing exclusion in the _Default + * sink. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The resource name of the exclusion to update: + * + * "projects/[PROJECT_ID]/exclusions/[EXCLUSION_ID]" + * "organizations/[ORGANIZATION_ID]/exclusions/[EXCLUSION_ID]" + * "billingAccounts/[BILLING_ACCOUNT_ID]/exclusions/[EXCLUSION_ID]" + * "folders/[FOLDER_ID]/exclusions/[EXCLUSION_ID]" + * + * For example: + * + * `"projects/my-project/exclusions/my-exclusion"` + * @param {google.logging.v2.LogExclusion} request.exclusion + * Required. New values for the existing exclusion. Only the fields specified in + * `update_mask` are relevant. + * @param {google.protobuf.FieldMask} request.updateMask + * Required. A non-empty list of fields to change in the existing exclusion. New values + * for the fields are taken from the corresponding fields in the + * {@link protos.google.logging.v2.LogExclusion|LogExclusion} included in this request. Fields not mentioned in + * `update_mask` are not changed and are ignored in the request. + * + * For example, to change the filter and description of an exclusion, + * specify an `update_mask` of `"filter,description"`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.logging.v2.LogExclusion|LogExclusion}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/config_service_v2.update_exclusion.js + * region_tag:logging_v2_generated_ConfigServiceV2_UpdateExclusion_async + */ updateExclusion( - request?: protos.google.logging.v2.IUpdateExclusionRequest, - options?: CallOptions): - Promise<[ - protos.google.logging.v2.ILogExclusion, - protos.google.logging.v2.IUpdateExclusionRequest|undefined, {}|undefined - ]>; + request?: protos.google.logging.v2.IUpdateExclusionRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.logging.v2.ILogExclusion, + protos.google.logging.v2.IUpdateExclusionRequest | undefined, + {} | undefined, + ] + >; updateExclusion( - request: protos.google.logging.v2.IUpdateExclusionRequest, - options: CallOptions, - callback: Callback< - protos.google.logging.v2.ILogExclusion, - protos.google.logging.v2.IUpdateExclusionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.logging.v2.IUpdateExclusionRequest, + options: CallOptions, + callback: Callback< + protos.google.logging.v2.ILogExclusion, + protos.google.logging.v2.IUpdateExclusionRequest | null | undefined, + {} | null | undefined + >, + ): void; updateExclusion( - request: protos.google.logging.v2.IUpdateExclusionRequest, - callback: Callback< - protos.google.logging.v2.ILogExclusion, - protos.google.logging.v2.IUpdateExclusionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.logging.v2.IUpdateExclusionRequest, + callback: Callback< + protos.google.logging.v2.ILogExclusion, + protos.google.logging.v2.IUpdateExclusionRequest | null | undefined, + {} | null | undefined + >, + ): void; updateExclusion( - request?: protos.google.logging.v2.IUpdateExclusionRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.logging.v2.ILogExclusion, - protos.google.logging.v2.IUpdateExclusionRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.logging.v2.IUpdateExclusionRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.logging.v2.ILogExclusion, - protos.google.logging.v2.IUpdateExclusionRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.logging.v2.ILogExclusion, - protos.google.logging.v2.IUpdateExclusionRequest|undefined, {}|undefined - ]>|void { + protos.google.logging.v2.IUpdateExclusionRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.logging.v2.ILogExclusion, + protos.google.logging.v2.IUpdateExclusionRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.logging.v2.ILogExclusion, + protos.google.logging.v2.IUpdateExclusionRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateExclusion request %j', request); - const wrappedCallback: Callback< - protos.google.logging.v2.ILogExclusion, - protos.google.logging.v2.IUpdateExclusionRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.logging.v2.ILogExclusion, + protos.google.logging.v2.IUpdateExclusionRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateExclusion response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.updateExclusion(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.logging.v2.ILogExclusion, - protos.google.logging.v2.IUpdateExclusionRequest|undefined, - {}|undefined - ]) => { - this._log.info('updateExclusion response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateExclusion(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.logging.v2.ILogExclusion, + protos.google.logging.v2.IUpdateExclusionRequest | undefined, + {} | undefined, + ]) => { + this._log.info('updateExclusion response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Deletes an exclusion in the _Default sink. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The resource name of an existing exclusion to delete: - * - * "projects/[PROJECT_ID]/exclusions/[EXCLUSION_ID]" - * "organizations/[ORGANIZATION_ID]/exclusions/[EXCLUSION_ID]" - * "billingAccounts/[BILLING_ACCOUNT_ID]/exclusions/[EXCLUSION_ID]" - * "folders/[FOLDER_ID]/exclusions/[EXCLUSION_ID]" - * - * For example: - * - * `"projects/my-project/exclusions/my-exclusion"` - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/config_service_v2.delete_exclusion.js - * region_tag:logging_v2_generated_ConfigServiceV2_DeleteExclusion_async - */ + /** + * Deletes an exclusion in the _Default sink. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The resource name of an existing exclusion to delete: + * + * "projects/[PROJECT_ID]/exclusions/[EXCLUSION_ID]" + * "organizations/[ORGANIZATION_ID]/exclusions/[EXCLUSION_ID]" + * "billingAccounts/[BILLING_ACCOUNT_ID]/exclusions/[EXCLUSION_ID]" + * "folders/[FOLDER_ID]/exclusions/[EXCLUSION_ID]" + * + * For example: + * + * `"projects/my-project/exclusions/my-exclusion"` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/config_service_v2.delete_exclusion.js + * region_tag:logging_v2_generated_ConfigServiceV2_DeleteExclusion_async + */ deleteExclusion( - request?: protos.google.logging.v2.IDeleteExclusionRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.logging.v2.IDeleteExclusionRequest|undefined, {}|undefined - ]>; + request?: protos.google.logging.v2.IDeleteExclusionRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.logging.v2.IDeleteExclusionRequest | undefined, + {} | undefined, + ] + >; deleteExclusion( - request: protos.google.logging.v2.IDeleteExclusionRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.logging.v2.IDeleteExclusionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.logging.v2.IDeleteExclusionRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.logging.v2.IDeleteExclusionRequest | null | undefined, + {} | null | undefined + >, + ): void; deleteExclusion( - request: protos.google.logging.v2.IDeleteExclusionRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.logging.v2.IDeleteExclusionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.logging.v2.IDeleteExclusionRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.logging.v2.IDeleteExclusionRequest | null | undefined, + {} | null | undefined + >, + ): void; deleteExclusion( - request?: protos.google.logging.v2.IDeleteExclusionRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.protobuf.IEmpty, - protos.google.logging.v2.IDeleteExclusionRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.logging.v2.IDeleteExclusionRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.logging.v2.IDeleteExclusionRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.logging.v2.IDeleteExclusionRequest|undefined, {}|undefined - ]>|void { + protos.google.logging.v2.IDeleteExclusionRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + protos.google.logging.v2.IDeleteExclusionRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.logging.v2.IDeleteExclusionRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('deleteExclusion request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.logging.v2.IDeleteExclusionRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + protos.google.logging.v2.IDeleteExclusionRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteExclusion response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.deleteExclusion(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.logging.v2.IDeleteExclusionRequest|undefined, - {}|undefined - ]) => { - this._log.info('deleteExclusion response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteExclusion(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.logging.v2.IDeleteExclusionRequest | undefined, + {} | undefined, + ]) => { + this._log.info('deleteExclusion response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Gets the Logging CMEK settings for the given resource. - * - * Note: CMEK for the Log Router can be configured for Google Cloud projects, - * folders, organizations and billing accounts. Once configured for an - * organization, it applies to all projects and folders in the Google Cloud - * organization. - * - * See [Enabling CMEK for Log - * Router](https://cloud.google.com/logging/docs/routing/managed-encryption) - * for more information. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The resource for which to retrieve CMEK settings. - * - * "projects/[PROJECT_ID]/cmekSettings" - * "organizations/[ORGANIZATION_ID]/cmekSettings" - * "billingAccounts/[BILLING_ACCOUNT_ID]/cmekSettings" - * "folders/[FOLDER_ID]/cmekSettings" - * - * For example: - * - * `"organizations/12345/cmekSettings"` - * - * Note: CMEK for the Log Router can be configured for Google Cloud projects, - * folders, organizations and billing accounts. Once configured for an - * organization, it applies to all projects and folders in the Google Cloud - * organization. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.logging.v2.CmekSettings|CmekSettings}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/config_service_v2.get_cmek_settings.js - * region_tag:logging_v2_generated_ConfigServiceV2_GetCmekSettings_async - */ + /** + * Gets the Logging CMEK settings for the given resource. + * + * Note: CMEK for the Log Router can be configured for Google Cloud projects, + * folders, organizations and billing accounts. Once configured for an + * organization, it applies to all projects and folders in the Google Cloud + * organization. + * + * See [Enabling CMEK for Log + * Router](https://cloud.google.com/logging/docs/routing/managed-encryption) + * for more information. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The resource for which to retrieve CMEK settings. + * + * "projects/[PROJECT_ID]/cmekSettings" + * "organizations/[ORGANIZATION_ID]/cmekSettings" + * "billingAccounts/[BILLING_ACCOUNT_ID]/cmekSettings" + * "folders/[FOLDER_ID]/cmekSettings" + * + * For example: + * + * `"organizations/12345/cmekSettings"` + * + * Note: CMEK for the Log Router can be configured for Google Cloud projects, + * folders, organizations and billing accounts. Once configured for an + * organization, it applies to all projects and folders in the Google Cloud + * organization. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.logging.v2.CmekSettings|CmekSettings}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/config_service_v2.get_cmek_settings.js + * region_tag:logging_v2_generated_ConfigServiceV2_GetCmekSettings_async + */ getCmekSettings( - request?: protos.google.logging.v2.IGetCmekSettingsRequest, - options?: CallOptions): - Promise<[ - protos.google.logging.v2.ICmekSettings, - protos.google.logging.v2.IGetCmekSettingsRequest|undefined, {}|undefined - ]>; + request?: protos.google.logging.v2.IGetCmekSettingsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.logging.v2.ICmekSettings, + protos.google.logging.v2.IGetCmekSettingsRequest | undefined, + {} | undefined, + ] + >; getCmekSettings( - request: protos.google.logging.v2.IGetCmekSettingsRequest, - options: CallOptions, - callback: Callback< - protos.google.logging.v2.ICmekSettings, - protos.google.logging.v2.IGetCmekSettingsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.logging.v2.IGetCmekSettingsRequest, + options: CallOptions, + callback: Callback< + protos.google.logging.v2.ICmekSettings, + protos.google.logging.v2.IGetCmekSettingsRequest | null | undefined, + {} | null | undefined + >, + ): void; getCmekSettings( - request: protos.google.logging.v2.IGetCmekSettingsRequest, - callback: Callback< - protos.google.logging.v2.ICmekSettings, - protos.google.logging.v2.IGetCmekSettingsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.logging.v2.IGetCmekSettingsRequest, + callback: Callback< + protos.google.logging.v2.ICmekSettings, + protos.google.logging.v2.IGetCmekSettingsRequest | null | undefined, + {} | null | undefined + >, + ): void; getCmekSettings( - request?: protos.google.logging.v2.IGetCmekSettingsRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.logging.v2.IGetCmekSettingsRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.logging.v2.ICmekSettings, - protos.google.logging.v2.IGetCmekSettingsRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.logging.v2.ICmekSettings, - protos.google.logging.v2.IGetCmekSettingsRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.logging.v2.ICmekSettings, - protos.google.logging.v2.IGetCmekSettingsRequest|undefined, {}|undefined - ]>|void { + protos.google.logging.v2.IGetCmekSettingsRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.logging.v2.ICmekSettings, + protos.google.logging.v2.IGetCmekSettingsRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.logging.v2.ICmekSettings, + protos.google.logging.v2.IGetCmekSettingsRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getCmekSettings request %j', request); - const wrappedCallback: Callback< - protos.google.logging.v2.ICmekSettings, - protos.google.logging.v2.IGetCmekSettingsRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.logging.v2.ICmekSettings, + protos.google.logging.v2.IGetCmekSettingsRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getCmekSettings response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getCmekSettings(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.logging.v2.ICmekSettings, - protos.google.logging.v2.IGetCmekSettingsRequest|undefined, - {}|undefined - ]) => { - this._log.info('getCmekSettings response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getCmekSettings(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.logging.v2.ICmekSettings, + protos.google.logging.v2.IGetCmekSettingsRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getCmekSettings response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Updates the Log Router CMEK settings for the given resource. - * - * Note: CMEK for the Log Router can currently only be configured for Google - * Cloud organizations. Once configured, it applies to all projects and - * folders in the Google Cloud organization. - * - * {@link protos.google.logging.v2.ConfigServiceV2.UpdateCmekSettings|UpdateCmekSettings} - * will fail if 1) `kms_key_name` is invalid, or 2) the associated service - * account does not have the required - * `roles/cloudkms.cryptoKeyEncrypterDecrypter` role assigned for the key, or - * 3) access to the key is disabled. - * - * See [Enabling CMEK for Log - * Router](https://cloud.google.com/logging/docs/routing/managed-encryption) - * for more information. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The resource name for the CMEK settings to update. - * - * "projects/[PROJECT_ID]/cmekSettings" - * "organizations/[ORGANIZATION_ID]/cmekSettings" - * "billingAccounts/[BILLING_ACCOUNT_ID]/cmekSettings" - * "folders/[FOLDER_ID]/cmekSettings" - * - * For example: - * - * `"organizations/12345/cmekSettings"` - * - * Note: CMEK for the Log Router can currently only be configured for Google - * Cloud organizations. Once configured, it applies to all projects and - * folders in the Google Cloud organization. - * @param {google.logging.v2.CmekSettings} request.cmekSettings - * Required. The CMEK settings to update. - * - * See [Enabling CMEK for Log - * Router](https://cloud.google.com/logging/docs/routing/managed-encryption) - * for more information. - * @param {google.protobuf.FieldMask} [request.updateMask] - * Optional. Field mask identifying which fields from `cmek_settings` should - * be updated. A field will be overwritten if and only if it is in the update - * mask. Output only fields cannot be updated. - * - * See {@link protos.google.protobuf.FieldMask|FieldMask} for more information. - * - * For example: `"updateMask=kmsKeyName"` - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.logging.v2.CmekSettings|CmekSettings}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/config_service_v2.update_cmek_settings.js - * region_tag:logging_v2_generated_ConfigServiceV2_UpdateCmekSettings_async - */ + /** + * Updates the Log Router CMEK settings for the given resource. + * + * Note: CMEK for the Log Router can currently only be configured for Google + * Cloud organizations. Once configured, it applies to all projects and + * folders in the Google Cloud organization. + * + * {@link protos.google.logging.v2.ConfigServiceV2.UpdateCmekSettings|UpdateCmekSettings} + * will fail if 1) `kms_key_name` is invalid, or 2) the associated service + * account does not have the required + * `roles/cloudkms.cryptoKeyEncrypterDecrypter` role assigned for the key, or + * 3) access to the key is disabled. + * + * See [Enabling CMEK for Log + * Router](https://cloud.google.com/logging/docs/routing/managed-encryption) + * for more information. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The resource name for the CMEK settings to update. + * + * "projects/[PROJECT_ID]/cmekSettings" + * "organizations/[ORGANIZATION_ID]/cmekSettings" + * "billingAccounts/[BILLING_ACCOUNT_ID]/cmekSettings" + * "folders/[FOLDER_ID]/cmekSettings" + * + * For example: + * + * `"organizations/12345/cmekSettings"` + * + * Note: CMEK for the Log Router can currently only be configured for Google + * Cloud organizations. Once configured, it applies to all projects and + * folders in the Google Cloud organization. + * @param {google.logging.v2.CmekSettings} request.cmekSettings + * Required. The CMEK settings to update. + * + * See [Enabling CMEK for Log + * Router](https://cloud.google.com/logging/docs/routing/managed-encryption) + * for more information. + * @param {google.protobuf.FieldMask} [request.updateMask] + * Optional. Field mask identifying which fields from `cmek_settings` should + * be updated. A field will be overwritten if and only if it is in the update + * mask. Output only fields cannot be updated. + * + * See {@link protos.google.protobuf.FieldMask|FieldMask} for more information. + * + * For example: `"updateMask=kmsKeyName"` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.logging.v2.CmekSettings|CmekSettings}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/config_service_v2.update_cmek_settings.js + * region_tag:logging_v2_generated_ConfigServiceV2_UpdateCmekSettings_async + */ updateCmekSettings( - request?: protos.google.logging.v2.IUpdateCmekSettingsRequest, - options?: CallOptions): - Promise<[ - protos.google.logging.v2.ICmekSettings, - protos.google.logging.v2.IUpdateCmekSettingsRequest|undefined, {}|undefined - ]>; + request?: protos.google.logging.v2.IUpdateCmekSettingsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.logging.v2.ICmekSettings, + protos.google.logging.v2.IUpdateCmekSettingsRequest | undefined, + {} | undefined, + ] + >; updateCmekSettings( - request: protos.google.logging.v2.IUpdateCmekSettingsRequest, - options: CallOptions, - callback: Callback< - protos.google.logging.v2.ICmekSettings, - protos.google.logging.v2.IUpdateCmekSettingsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.logging.v2.IUpdateCmekSettingsRequest, + options: CallOptions, + callback: Callback< + protos.google.logging.v2.ICmekSettings, + protos.google.logging.v2.IUpdateCmekSettingsRequest | null | undefined, + {} | null | undefined + >, + ): void; updateCmekSettings( - request: protos.google.logging.v2.IUpdateCmekSettingsRequest, - callback: Callback< - protos.google.logging.v2.ICmekSettings, - protos.google.logging.v2.IUpdateCmekSettingsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.logging.v2.IUpdateCmekSettingsRequest, + callback: Callback< + protos.google.logging.v2.ICmekSettings, + protos.google.logging.v2.IUpdateCmekSettingsRequest | null | undefined, + {} | null | undefined + >, + ): void; updateCmekSettings( - request?: protos.google.logging.v2.IUpdateCmekSettingsRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.logging.v2.ICmekSettings, - protos.google.logging.v2.IUpdateCmekSettingsRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.logging.v2.IUpdateCmekSettingsRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.logging.v2.ICmekSettings, - protos.google.logging.v2.IUpdateCmekSettingsRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.logging.v2.ICmekSettings, - protos.google.logging.v2.IUpdateCmekSettingsRequest|undefined, {}|undefined - ]>|void { + | protos.google.logging.v2.IUpdateCmekSettingsRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.logging.v2.ICmekSettings, + protos.google.logging.v2.IUpdateCmekSettingsRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.logging.v2.ICmekSettings, + protos.google.logging.v2.IUpdateCmekSettingsRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateCmekSettings request %j', request); - const wrappedCallback: Callback< - protos.google.logging.v2.ICmekSettings, - protos.google.logging.v2.IUpdateCmekSettingsRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.logging.v2.ICmekSettings, + | protos.google.logging.v2.IUpdateCmekSettingsRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateCmekSettings response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.updateCmekSettings(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.logging.v2.ICmekSettings, - protos.google.logging.v2.IUpdateCmekSettingsRequest|undefined, - {}|undefined - ]) => { - this._log.info('updateCmekSettings response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateCmekSettings(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.logging.v2.ICmekSettings, + protos.google.logging.v2.IUpdateCmekSettingsRequest | undefined, + {} | undefined, + ]) => { + this._log.info('updateCmekSettings response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Gets the Log Router settings for the given resource. - * - * Note: Settings for the Log Router can be get for Google Cloud projects, - * folders, organizations and billing accounts. Currently it can only be - * configured for organizations. Once configured for an organization, it - * applies to all projects and folders in the Google Cloud organization. - * - * See [Enabling CMEK for Log - * Router](https://cloud.google.com/logging/docs/routing/managed-encryption) - * for more information. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The resource for which to retrieve settings. - * - * "projects/[PROJECT_ID]/settings" - * "organizations/[ORGANIZATION_ID]/settings" - * "billingAccounts/[BILLING_ACCOUNT_ID]/settings" - * "folders/[FOLDER_ID]/settings" - * - * For example: - * - * `"organizations/12345/settings"` - * - * Note: Settings for the Log Router can be get for Google Cloud projects, - * folders, organizations and billing accounts. Currently it can only be - * configured for organizations. Once configured for an organization, it - * applies to all projects and folders in the Google Cloud organization. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.logging.v2.Settings|Settings}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/config_service_v2.get_settings.js - * region_tag:logging_v2_generated_ConfigServiceV2_GetSettings_async - */ + /** + * Gets the Log Router settings for the given resource. + * + * Note: Settings for the Log Router can be get for Google Cloud projects, + * folders, organizations and billing accounts. Currently it can only be + * configured for organizations. Once configured for an organization, it + * applies to all projects and folders in the Google Cloud organization. + * + * See [Enabling CMEK for Log + * Router](https://cloud.google.com/logging/docs/routing/managed-encryption) + * for more information. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The resource for which to retrieve settings. + * + * "projects/[PROJECT_ID]/settings" + * "organizations/[ORGANIZATION_ID]/settings" + * "billingAccounts/[BILLING_ACCOUNT_ID]/settings" + * "folders/[FOLDER_ID]/settings" + * + * For example: + * + * `"organizations/12345/settings"` + * + * Note: Settings for the Log Router can be get for Google Cloud projects, + * folders, organizations and billing accounts. Currently it can only be + * configured for organizations. Once configured for an organization, it + * applies to all projects and folders in the Google Cloud organization. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.logging.v2.Settings|Settings}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/config_service_v2.get_settings.js + * region_tag:logging_v2_generated_ConfigServiceV2_GetSettings_async + */ getSettings( - request?: protos.google.logging.v2.IGetSettingsRequest, - options?: CallOptions): - Promise<[ - protos.google.logging.v2.ISettings, - protos.google.logging.v2.IGetSettingsRequest|undefined, {}|undefined - ]>; + request?: protos.google.logging.v2.IGetSettingsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.logging.v2.ISettings, + protos.google.logging.v2.IGetSettingsRequest | undefined, + {} | undefined, + ] + >; getSettings( - request: protos.google.logging.v2.IGetSettingsRequest, - options: CallOptions, - callback: Callback< - protos.google.logging.v2.ISettings, - protos.google.logging.v2.IGetSettingsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.logging.v2.IGetSettingsRequest, + options: CallOptions, + callback: Callback< + protos.google.logging.v2.ISettings, + protos.google.logging.v2.IGetSettingsRequest | null | undefined, + {} | null | undefined + >, + ): void; getSettings( - request: protos.google.logging.v2.IGetSettingsRequest, - callback: Callback< - protos.google.logging.v2.ISettings, - protos.google.logging.v2.IGetSettingsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.logging.v2.IGetSettingsRequest, + callback: Callback< + protos.google.logging.v2.ISettings, + protos.google.logging.v2.IGetSettingsRequest | null | undefined, + {} | null | undefined + >, + ): void; getSettings( - request?: protos.google.logging.v2.IGetSettingsRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.logging.v2.ISettings, - protos.google.logging.v2.IGetSettingsRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.logging.v2.IGetSettingsRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.logging.v2.ISettings, - protos.google.logging.v2.IGetSettingsRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.logging.v2.ISettings, - protos.google.logging.v2.IGetSettingsRequest|undefined, {}|undefined - ]>|void { + protos.google.logging.v2.IGetSettingsRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.logging.v2.ISettings, + protos.google.logging.v2.IGetSettingsRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.logging.v2.ISettings, + protos.google.logging.v2.IGetSettingsRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getSettings request %j', request); - const wrappedCallback: Callback< - protos.google.logging.v2.ISettings, - protos.google.logging.v2.IGetSettingsRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.logging.v2.ISettings, + protos.google.logging.v2.IGetSettingsRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getSettings response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getSettings(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.logging.v2.ISettings, - protos.google.logging.v2.IGetSettingsRequest|undefined, - {}|undefined - ]) => { - this._log.info('getSettings response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getSettings(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.logging.v2.ISettings, + protos.google.logging.v2.IGetSettingsRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getSettings response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Updates the Log Router settings for the given resource. - * - * Note: Settings for the Log Router can currently only be configured for - * Google Cloud organizations. Once configured, it applies to all projects and - * folders in the Google Cloud organization. - * - * {@link protos.google.logging.v2.ConfigServiceV2.UpdateSettings|UpdateSettings} - * will fail if 1) `kms_key_name` is invalid, or 2) the associated service - * account does not have the required - * `roles/cloudkms.cryptoKeyEncrypterDecrypter` role assigned for the key, or - * 3) access to the key is disabled. 4) `location_id` is not supported by - * Logging. 5) `location_id` violate OrgPolicy. - * - * See [Enabling CMEK for Log - * Router](https://cloud.google.com/logging/docs/routing/managed-encryption) - * for more information. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The resource name for the settings to update. - * - * "organizations/[ORGANIZATION_ID]/settings" - * - * For example: - * - * `"organizations/12345/settings"` - * - * Note: Settings for the Log Router can currently only be configured for - * Google Cloud organizations. Once configured, it applies to all projects and - * folders in the Google Cloud organization. - * @param {google.logging.v2.Settings} request.settings - * Required. The settings to update. - * - * See [Enabling CMEK for Log - * Router](https://cloud.google.com/logging/docs/routing/managed-encryption) - * for more information. - * @param {google.protobuf.FieldMask} [request.updateMask] - * Optional. Field mask identifying which fields from `settings` should - * be updated. A field will be overwritten if and only if it is in the update - * mask. Output only fields cannot be updated. - * - * See {@link protos.google.protobuf.FieldMask|FieldMask} for more information. - * - * For example: `"updateMask=kmsKeyName"` - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.logging.v2.Settings|Settings}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/config_service_v2.update_settings.js - * region_tag:logging_v2_generated_ConfigServiceV2_UpdateSettings_async - */ + /** + * Updates the Log Router settings for the given resource. + * + * Note: Settings for the Log Router can currently only be configured for + * Google Cloud organizations. Once configured, it applies to all projects and + * folders in the Google Cloud organization. + * + * {@link protos.google.logging.v2.ConfigServiceV2.UpdateSettings|UpdateSettings} + * will fail if 1) `kms_key_name` is invalid, or 2) the associated service + * account does not have the required + * `roles/cloudkms.cryptoKeyEncrypterDecrypter` role assigned for the key, or + * 3) access to the key is disabled. 4) `location_id` is not supported by + * Logging. 5) `location_id` violate OrgPolicy. + * + * See [Enabling CMEK for Log + * Router](https://cloud.google.com/logging/docs/routing/managed-encryption) + * for more information. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The resource name for the settings to update. + * + * "organizations/[ORGANIZATION_ID]/settings" + * + * For example: + * + * `"organizations/12345/settings"` + * + * Note: Settings for the Log Router can currently only be configured for + * Google Cloud organizations. Once configured, it applies to all projects and + * folders in the Google Cloud organization. + * @param {google.logging.v2.Settings} request.settings + * Required. The settings to update. + * + * See [Enabling CMEK for Log + * Router](https://cloud.google.com/logging/docs/routing/managed-encryption) + * for more information. + * @param {google.protobuf.FieldMask} [request.updateMask] + * Optional. Field mask identifying which fields from `settings` should + * be updated. A field will be overwritten if and only if it is in the update + * mask. Output only fields cannot be updated. + * + * See {@link protos.google.protobuf.FieldMask|FieldMask} for more information. + * + * For example: `"updateMask=kmsKeyName"` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.logging.v2.Settings|Settings}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/config_service_v2.update_settings.js + * region_tag:logging_v2_generated_ConfigServiceV2_UpdateSettings_async + */ updateSettings( - request?: protos.google.logging.v2.IUpdateSettingsRequest, - options?: CallOptions): - Promise<[ - protos.google.logging.v2.ISettings, - protos.google.logging.v2.IUpdateSettingsRequest|undefined, {}|undefined - ]>; + request?: protos.google.logging.v2.IUpdateSettingsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.logging.v2.ISettings, + protos.google.logging.v2.IUpdateSettingsRequest | undefined, + {} | undefined, + ] + >; updateSettings( - request: protos.google.logging.v2.IUpdateSettingsRequest, - options: CallOptions, - callback: Callback< - protos.google.logging.v2.ISettings, - protos.google.logging.v2.IUpdateSettingsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.logging.v2.IUpdateSettingsRequest, + options: CallOptions, + callback: Callback< + protos.google.logging.v2.ISettings, + protos.google.logging.v2.IUpdateSettingsRequest | null | undefined, + {} | null | undefined + >, + ): void; updateSettings( - request: protos.google.logging.v2.IUpdateSettingsRequest, - callback: Callback< - protos.google.logging.v2.ISettings, - protos.google.logging.v2.IUpdateSettingsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.logging.v2.IUpdateSettingsRequest, + callback: Callback< + protos.google.logging.v2.ISettings, + protos.google.logging.v2.IUpdateSettingsRequest | null | undefined, + {} | null | undefined + >, + ): void; updateSettings( - request?: protos.google.logging.v2.IUpdateSettingsRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.logging.v2.ISettings, - protos.google.logging.v2.IUpdateSettingsRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.logging.v2.IUpdateSettingsRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.logging.v2.ISettings, - protos.google.logging.v2.IUpdateSettingsRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.logging.v2.ISettings, - protos.google.logging.v2.IUpdateSettingsRequest|undefined, {}|undefined - ]>|void { + protos.google.logging.v2.IUpdateSettingsRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.logging.v2.ISettings, + protos.google.logging.v2.IUpdateSettingsRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.logging.v2.ISettings, + protos.google.logging.v2.IUpdateSettingsRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateSettings request %j', request); - const wrappedCallback: Callback< - protos.google.logging.v2.ISettings, - protos.google.logging.v2.IUpdateSettingsRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.logging.v2.ISettings, + protos.google.logging.v2.IUpdateSettingsRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateSettings response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.updateSettings(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.logging.v2.ISettings, - protos.google.logging.v2.IUpdateSettingsRequest|undefined, - {}|undefined - ]) => { - this._log.info('updateSettings response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateSettings(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.logging.v2.ISettings, + protos.google.logging.v2.IUpdateSettingsRequest | undefined, + {} | undefined, + ]) => { + this._log.info('updateSettings response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Copies a set of log entries from a log bucket to a Cloud Storage bucket. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. Log bucket from which to copy log entries. - * - * For example: - * - * `"projects/my-project/locations/global/buckets/my-source-bucket"` - * @param {string} [request.filter] - * Optional. A filter specifying which log entries to copy. The filter must be no more - * than 20k characters. An empty filter matches all log entries. - * @param {string} request.destination - * Required. Destination to which to copy log entries. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing - * a long running operation. Its `promise()` method returns a promise - * you can `await` for. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v2/config_service_v2.copy_log_entries.js - * region_tag:logging_v2_generated_ConfigServiceV2_CopyLogEntries_async - */ + /** + * Copies a set of log entries from a log bucket to a Cloud Storage bucket. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Log bucket from which to copy log entries. + * + * For example: + * + * `"projects/my-project/locations/global/buckets/my-source-bucket"` + * @param {string} [request.filter] + * Optional. A filter specifying which log entries to copy. The filter must be no more + * than 20k characters. An empty filter matches all log entries. + * @param {string} request.destination + * Required. Destination to which to copy log entries. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v2/config_service_v2.copy_log_entries.js + * region_tag:logging_v2_generated_ConfigServiceV2_CopyLogEntries_async + */ copyLogEntries( - request?: protos.google.logging.v2.ICopyLogEntriesRequest, - options?: CallOptions): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>; + request?: protos.google.logging.v2.ICopyLogEntriesRequest, + options?: CallOptions, + ): Promise< + [ + LROperation< + protos.google.logging.v2.ICopyLogEntriesResponse, + protos.google.logging.v2.ICopyLogEntriesMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; copyLogEntries( - request: protos.google.logging.v2.ICopyLogEntriesRequest, - options: CallOptions, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.logging.v2.ICopyLogEntriesRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.logging.v2.ICopyLogEntriesResponse, + protos.google.logging.v2.ICopyLogEntriesMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; copyLogEntries( - request: protos.google.logging.v2.ICopyLogEntriesRequest, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.logging.v2.ICopyLogEntriesRequest, + callback: Callback< + LROperation< + protos.google.logging.v2.ICopyLogEntriesResponse, + protos.google.logging.v2.ICopyLogEntriesMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; copyLogEntries( - request?: protos.google.logging.v2.ICopyLogEntriesRequest, - optionsOrCallback?: CallOptions|Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>, - callback?: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>|void { + request?: protos.google.logging.v2.ICopyLogEntriesRequest, + optionsOrCallback?: + | CallOptions + | Callback< + LROperation< + protos.google.logging.v2.ICopyLogEntriesResponse, + protos.google.logging.v2.ICopyLogEntriesMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + callback?: Callback< + LROperation< + protos.google.logging.v2.ICopyLogEntriesResponse, + protos.google.logging.v2.ICopyLogEntriesMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + LROperation< + protos.google.logging.v2.ICopyLogEntriesResponse, + protos.google.logging.v2.ICopyLogEntriesMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize().catch(err => {throw err}); - const wrappedCallback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>|undefined = callback + this.initialize().catch((err) => { + throw err; + }); + const wrappedCallback: + | Callback< + LROperation< + protos.google.logging.v2.ICopyLogEntriesResponse, + protos.google.logging.v2.ICopyLogEntriesMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, rawResponse, _) => { this._log.info('copyLogEntries response %j', rawResponse); callback!(error, response, rawResponse, _); // We verified callback above. } : undefined; this._log.info('copyLogEntries request %j', request); - return this.innerApiCalls.copyLogEntries(request, options, wrappedCallback) - ?.then(([response, rawResponse, _]: [ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]) => { - this._log.info('copyLogEntries response %j', rawResponse); - return [response, rawResponse, _]; - }); + return this.innerApiCalls + .copyLogEntries(request, options, wrappedCallback) + ?.then( + ([response, rawResponse, _]: [ + LROperation< + protos.google.logging.v2.ICopyLogEntriesResponse, + protos.google.logging.v2.ICopyLogEntriesMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ]) => { + this._log.info('copyLogEntries response %j', rawResponse); + return [response, rawResponse, _]; + }, + ); } -/** - * Check the status of the long running operation returned by `copyLogEntries()`. - * @param {String} name - * The operation name that will be passed. - * @returns {Promise} - The promise which resolves to an object. - * The decoded operation object has result and metadata field to get information from. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v2/config_service_v2.copy_log_entries.js - * region_tag:logging_v2_generated_ConfigServiceV2_CopyLogEntries_async - */ - async checkCopyLogEntriesProgress(name: string): Promise>{ + /** + * Check the status of the long running operation returned by `copyLogEntries()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v2/config_service_v2.copy_log_entries.js + * region_tag:logging_v2_generated_ConfigServiceV2_CopyLogEntries_async + */ + async checkCopyLogEntriesProgress( + name: string, + ): Promise< + LROperation< + protos.google.logging.v2.CopyLogEntriesResponse, + protos.google.logging.v2.CopyLogEntriesMetadata + > + > { this._log.info('copyLogEntries long-running'); - const request = new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest({name}); + const request = + new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( + { name }, + ); const [operation] = await this.operationsClient.getOperation(request); - const decodeOperation = new this._gaxModule.Operation(operation, this.descriptors.longrunning.copyLogEntries, this._gaxModule.createDefaultBackoffSettings()); - return decodeOperation as LROperation; - } - /** - * Lists log buckets. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent resource whose buckets are to be listed: - * - * "projects/[PROJECT_ID]/locations/[LOCATION_ID]" - * "organizations/[ORGANIZATION_ID]/locations/[LOCATION_ID]" - * "billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]" - * "folders/[FOLDER_ID]/locations/[LOCATION_ID]" - * - * Note: The locations portion of the resource must be specified, but - * supplying the character `-` in place of [LOCATION_ID] will return all - * buckets. - * @param {string} [request.pageToken] - * Optional. If present, then retrieve the next batch of results from the preceding call - * to this method. `pageToken` must be the value of `nextPageToken` from the - * previous response. The values of other method parameters should be - * identical to those in the previous call. - * @param {number} [request.pageSize] - * Optional. The maximum number of results to return from this request. Non-positive - * values are ignored. The presence of `nextPageToken` in the response - * indicates that more results might be available. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.logging.v2.LogBucket|LogBucket}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `listBucketsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + const decodeOperation = new this._gaxModule.Operation( + operation, + this.descriptors.longrunning.copyLogEntries, + this._gaxModule.createDefaultBackoffSettings(), + ); + return decodeOperation as LROperation< + protos.google.logging.v2.CopyLogEntriesResponse, + protos.google.logging.v2.CopyLogEntriesMetadata + >; + } + /** + * Lists log buckets. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource whose buckets are to be listed: + * + * "projects/[PROJECT_ID]/locations/[LOCATION_ID]" + * "organizations/[ORGANIZATION_ID]/locations/[LOCATION_ID]" + * "billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]" + * "folders/[FOLDER_ID]/locations/[LOCATION_ID]" + * + * Note: The locations portion of the resource must be specified, but + * supplying the character `-` in place of [LOCATION_ID] will return all + * buckets. + * @param {string} [request.pageToken] + * Optional. If present, then retrieve the next batch of results from the preceding call + * to this method. `pageToken` must be the value of `nextPageToken` from the + * previous response. The values of other method parameters should be + * identical to those in the previous call. + * @param {number} [request.pageSize] + * Optional. The maximum number of results to return from this request. Non-positive + * values are ignored. The presence of `nextPageToken` in the response + * indicates that more results might be available. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.logging.v2.LogBucket|LogBucket}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listBucketsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listBuckets( - request?: protos.google.logging.v2.IListBucketsRequest, - options?: CallOptions): - Promise<[ - protos.google.logging.v2.ILogBucket[], - protos.google.logging.v2.IListBucketsRequest|null, - protos.google.logging.v2.IListBucketsResponse - ]>; + request?: protos.google.logging.v2.IListBucketsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.logging.v2.ILogBucket[], + protos.google.logging.v2.IListBucketsRequest | null, + protos.google.logging.v2.IListBucketsResponse, + ] + >; listBuckets( - request: protos.google.logging.v2.IListBucketsRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.logging.v2.IListBucketsRequest, - protos.google.logging.v2.IListBucketsResponse|null|undefined, - protos.google.logging.v2.ILogBucket>): void; + request: protos.google.logging.v2.IListBucketsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.logging.v2.IListBucketsRequest, + protos.google.logging.v2.IListBucketsResponse | null | undefined, + protos.google.logging.v2.ILogBucket + >, + ): void; listBuckets( - request: protos.google.logging.v2.IListBucketsRequest, - callback: PaginationCallback< - protos.google.logging.v2.IListBucketsRequest, - protos.google.logging.v2.IListBucketsResponse|null|undefined, - protos.google.logging.v2.ILogBucket>): void; + request: protos.google.logging.v2.IListBucketsRequest, + callback: PaginationCallback< + protos.google.logging.v2.IListBucketsRequest, + protos.google.logging.v2.IListBucketsResponse | null | undefined, + protos.google.logging.v2.ILogBucket + >, + ): void; listBuckets( - request?: protos.google.logging.v2.IListBucketsRequest, - optionsOrCallback?: CallOptions|PaginationCallback< + request?: protos.google.logging.v2.IListBucketsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.logging.v2.IListBucketsRequest, - protos.google.logging.v2.IListBucketsResponse|null|undefined, - protos.google.logging.v2.ILogBucket>, - callback?: PaginationCallback< - protos.google.logging.v2.IListBucketsRequest, - protos.google.logging.v2.IListBucketsResponse|null|undefined, - protos.google.logging.v2.ILogBucket>): - Promise<[ - protos.google.logging.v2.ILogBucket[], - protos.google.logging.v2.IListBucketsRequest|null, - protos.google.logging.v2.IListBucketsResponse - ]>|void { + protos.google.logging.v2.IListBucketsResponse | null | undefined, + protos.google.logging.v2.ILogBucket + >, + callback?: PaginationCallback< + protos.google.logging.v2.IListBucketsRequest, + protos.google.logging.v2.IListBucketsResponse | null | undefined, + protos.google.logging.v2.ILogBucket + >, + ): Promise< + [ + protos.google.logging.v2.ILogBucket[], + protos.google.logging.v2.IListBucketsRequest | null, + protos.google.logging.v2.IListBucketsResponse, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.logging.v2.IListBucketsRequest, - protos.google.logging.v2.IListBucketsResponse|null|undefined, - protos.google.logging.v2.ILogBucket>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.logging.v2.IListBucketsRequest, + protos.google.logging.v2.IListBucketsResponse | null | undefined, + protos.google.logging.v2.ILogBucket + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listBuckets values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -3045,225 +3852,244 @@ export class ConfigServiceV2Client { this._log.info('listBuckets request %j', request); return this.innerApiCalls .listBuckets(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.logging.v2.ILogBucket[], - protos.google.logging.v2.IListBucketsRequest|null, - protos.google.logging.v2.IListBucketsResponse - ]) => { - this._log.info('listBuckets values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.logging.v2.ILogBucket[], + protos.google.logging.v2.IListBucketsRequest | null, + protos.google.logging.v2.IListBucketsResponse, + ]) => { + this._log.info('listBuckets values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listBuckets`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent resource whose buckets are to be listed: - * - * "projects/[PROJECT_ID]/locations/[LOCATION_ID]" - * "organizations/[ORGANIZATION_ID]/locations/[LOCATION_ID]" - * "billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]" - * "folders/[FOLDER_ID]/locations/[LOCATION_ID]" - * - * Note: The locations portion of the resource must be specified, but - * supplying the character `-` in place of [LOCATION_ID] will return all - * buckets. - * @param {string} [request.pageToken] - * Optional. If present, then retrieve the next batch of results from the preceding call - * to this method. `pageToken` must be the value of `nextPageToken` from the - * previous response. The values of other method parameters should be - * identical to those in the previous call. - * @param {number} [request.pageSize] - * Optional. The maximum number of results to return from this request. Non-positive - * values are ignored. The presence of `nextPageToken` in the response - * indicates that more results might be available. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.logging.v2.LogBucket|LogBucket} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `listBucketsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `listBuckets`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource whose buckets are to be listed: + * + * "projects/[PROJECT_ID]/locations/[LOCATION_ID]" + * "organizations/[ORGANIZATION_ID]/locations/[LOCATION_ID]" + * "billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]" + * "folders/[FOLDER_ID]/locations/[LOCATION_ID]" + * + * Note: The locations portion of the resource must be specified, but + * supplying the character `-` in place of [LOCATION_ID] will return all + * buckets. + * @param {string} [request.pageToken] + * Optional. If present, then retrieve the next batch of results from the preceding call + * to this method. `pageToken` must be the value of `nextPageToken` from the + * previous response. The values of other method parameters should be + * identical to those in the previous call. + * @param {number} [request.pageSize] + * Optional. The maximum number of results to return from this request. Non-positive + * values are ignored. The presence of `nextPageToken` in the response + * indicates that more results might be available. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.logging.v2.LogBucket|LogBucket} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listBucketsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listBucketsStream( - request?: protos.google.logging.v2.IListBucketsRequest, - options?: CallOptions): - Transform{ + request?: protos.google.logging.v2.IListBucketsRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); const defaultCallSettings = this._defaults['listBuckets']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listBuckets stream %j', request); return this.descriptors.page.listBuckets.createStream( this.innerApiCalls.listBuckets as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listBuckets`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent resource whose buckets are to be listed: - * - * "projects/[PROJECT_ID]/locations/[LOCATION_ID]" - * "organizations/[ORGANIZATION_ID]/locations/[LOCATION_ID]" - * "billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]" - * "folders/[FOLDER_ID]/locations/[LOCATION_ID]" - * - * Note: The locations portion of the resource must be specified, but - * supplying the character `-` in place of [LOCATION_ID] will return all - * buckets. - * @param {string} [request.pageToken] - * Optional. If present, then retrieve the next batch of results from the preceding call - * to this method. `pageToken` must be the value of `nextPageToken` from the - * previous response. The values of other method parameters should be - * identical to those in the previous call. - * @param {number} [request.pageSize] - * Optional. The maximum number of results to return from this request. Non-positive - * values are ignored. The presence of `nextPageToken` in the response - * indicates that more results might be available. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.logging.v2.LogBucket|LogBucket}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v2/config_service_v2.list_buckets.js - * region_tag:logging_v2_generated_ConfigServiceV2_ListBuckets_async - */ + /** + * Equivalent to `listBuckets`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource whose buckets are to be listed: + * + * "projects/[PROJECT_ID]/locations/[LOCATION_ID]" + * "organizations/[ORGANIZATION_ID]/locations/[LOCATION_ID]" + * "billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]" + * "folders/[FOLDER_ID]/locations/[LOCATION_ID]" + * + * Note: The locations portion of the resource must be specified, but + * supplying the character `-` in place of [LOCATION_ID] will return all + * buckets. + * @param {string} [request.pageToken] + * Optional. If present, then retrieve the next batch of results from the preceding call + * to this method. `pageToken` must be the value of `nextPageToken` from the + * previous response. The values of other method parameters should be + * identical to those in the previous call. + * @param {number} [request.pageSize] + * Optional. The maximum number of results to return from this request. Non-positive + * values are ignored. The presence of `nextPageToken` in the response + * indicates that more results might be available. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.logging.v2.LogBucket|LogBucket}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v2/config_service_v2.list_buckets.js + * region_tag:logging_v2_generated_ConfigServiceV2_ListBuckets_async + */ listBucketsAsync( - request?: protos.google.logging.v2.IListBucketsRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.logging.v2.IListBucketsRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); const defaultCallSettings = this._defaults['listBuckets']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listBuckets iterate %j', request); return this.descriptors.page.listBuckets.asyncIterate( this.innerApiCalls['listBuckets'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } - /** - * Lists views on a log bucket. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The bucket whose views are to be listed: - * - * "projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" - * @param {string} [request.pageToken] - * Optional. If present, then retrieve the next batch of results from the preceding call - * to this method. `pageToken` must be the value of `nextPageToken` from the - * previous response. The values of other method parameters should be - * identical to those in the previous call. - * @param {number} [request.pageSize] - * Optional. The maximum number of results to return from this request. - * - * Non-positive values are ignored. The presence of `nextPageToken` in the - * response indicates that more results might be available. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.logging.v2.LogView|LogView}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `listViewsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Lists views on a log bucket. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The bucket whose views are to be listed: + * + * "projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" + * @param {string} [request.pageToken] + * Optional. If present, then retrieve the next batch of results from the preceding call + * to this method. `pageToken` must be the value of `nextPageToken` from the + * previous response. The values of other method parameters should be + * identical to those in the previous call. + * @param {number} [request.pageSize] + * Optional. The maximum number of results to return from this request. + * + * Non-positive values are ignored. The presence of `nextPageToken` in the + * response indicates that more results might be available. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.logging.v2.LogView|LogView}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listViewsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listViews( - request?: protos.google.logging.v2.IListViewsRequest, - options?: CallOptions): - Promise<[ - protos.google.logging.v2.ILogView[], - protos.google.logging.v2.IListViewsRequest|null, - protos.google.logging.v2.IListViewsResponse - ]>; + request?: protos.google.logging.v2.IListViewsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.logging.v2.ILogView[], + protos.google.logging.v2.IListViewsRequest | null, + protos.google.logging.v2.IListViewsResponse, + ] + >; listViews( - request: protos.google.logging.v2.IListViewsRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.logging.v2.IListViewsRequest, - protos.google.logging.v2.IListViewsResponse|null|undefined, - protos.google.logging.v2.ILogView>): void; + request: protos.google.logging.v2.IListViewsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.logging.v2.IListViewsRequest, + protos.google.logging.v2.IListViewsResponse | null | undefined, + protos.google.logging.v2.ILogView + >, + ): void; listViews( - request: protos.google.logging.v2.IListViewsRequest, - callback: PaginationCallback< - protos.google.logging.v2.IListViewsRequest, - protos.google.logging.v2.IListViewsResponse|null|undefined, - protos.google.logging.v2.ILogView>): void; + request: protos.google.logging.v2.IListViewsRequest, + callback: PaginationCallback< + protos.google.logging.v2.IListViewsRequest, + protos.google.logging.v2.IListViewsResponse | null | undefined, + protos.google.logging.v2.ILogView + >, + ): void; listViews( - request?: protos.google.logging.v2.IListViewsRequest, - optionsOrCallback?: CallOptions|PaginationCallback< - protos.google.logging.v2.IListViewsRequest, - protos.google.logging.v2.IListViewsResponse|null|undefined, - protos.google.logging.v2.ILogView>, - callback?: PaginationCallback< + request?: protos.google.logging.v2.IListViewsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.logging.v2.IListViewsRequest, - protos.google.logging.v2.IListViewsResponse|null|undefined, - protos.google.logging.v2.ILogView>): - Promise<[ - protos.google.logging.v2.ILogView[], - protos.google.logging.v2.IListViewsRequest|null, - protos.google.logging.v2.IListViewsResponse - ]>|void { + protos.google.logging.v2.IListViewsResponse | null | undefined, + protos.google.logging.v2.ILogView + >, + callback?: PaginationCallback< + protos.google.logging.v2.IListViewsRequest, + protos.google.logging.v2.IListViewsResponse | null | undefined, + protos.google.logging.v2.ILogView + >, + ): Promise< + [ + protos.google.logging.v2.ILogView[], + protos.google.logging.v2.IListViewsRequest | null, + protos.google.logging.v2.IListViewsResponse, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.logging.v2.IListViewsRequest, - protos.google.logging.v2.IListViewsResponse|null|undefined, - protos.google.logging.v2.ILogView>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.logging.v2.IListViewsRequest, + protos.google.logging.v2.IListViewsResponse | null | undefined, + protos.google.logging.v2.ILogView + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listViews values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -3272,215 +4098,234 @@ export class ConfigServiceV2Client { this._log.info('listViews request %j', request); return this.innerApiCalls .listViews(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.logging.v2.ILogView[], - protos.google.logging.v2.IListViewsRequest|null, - protos.google.logging.v2.IListViewsResponse - ]) => { - this._log.info('listViews values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.logging.v2.ILogView[], + protos.google.logging.v2.IListViewsRequest | null, + protos.google.logging.v2.IListViewsResponse, + ]) => { + this._log.info('listViews values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listViews`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The bucket whose views are to be listed: - * - * "projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" - * @param {string} [request.pageToken] - * Optional. If present, then retrieve the next batch of results from the preceding call - * to this method. `pageToken` must be the value of `nextPageToken` from the - * previous response. The values of other method parameters should be - * identical to those in the previous call. - * @param {number} [request.pageSize] - * Optional. The maximum number of results to return from this request. - * - * Non-positive values are ignored. The presence of `nextPageToken` in the - * response indicates that more results might be available. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.logging.v2.LogView|LogView} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `listViewsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `listViews`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The bucket whose views are to be listed: + * + * "projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" + * @param {string} [request.pageToken] + * Optional. If present, then retrieve the next batch of results from the preceding call + * to this method. `pageToken` must be the value of `nextPageToken` from the + * previous response. The values of other method parameters should be + * identical to those in the previous call. + * @param {number} [request.pageSize] + * Optional. The maximum number of results to return from this request. + * + * Non-positive values are ignored. The presence of `nextPageToken` in the + * response indicates that more results might be available. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.logging.v2.LogView|LogView} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listViewsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listViewsStream( - request?: protos.google.logging.v2.IListViewsRequest, - options?: CallOptions): - Transform{ + request?: protos.google.logging.v2.IListViewsRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); const defaultCallSettings = this._defaults['listViews']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listViews stream %j', request); return this.descriptors.page.listViews.createStream( this.innerApiCalls.listViews as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listViews`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The bucket whose views are to be listed: - * - * "projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" - * @param {string} [request.pageToken] - * Optional. If present, then retrieve the next batch of results from the preceding call - * to this method. `pageToken` must be the value of `nextPageToken` from the - * previous response. The values of other method parameters should be - * identical to those in the previous call. - * @param {number} [request.pageSize] - * Optional. The maximum number of results to return from this request. - * - * Non-positive values are ignored. The presence of `nextPageToken` in the - * response indicates that more results might be available. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.logging.v2.LogView|LogView}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v2/config_service_v2.list_views.js - * region_tag:logging_v2_generated_ConfigServiceV2_ListViews_async - */ + /** + * Equivalent to `listViews`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The bucket whose views are to be listed: + * + * "projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" + * @param {string} [request.pageToken] + * Optional. If present, then retrieve the next batch of results from the preceding call + * to this method. `pageToken` must be the value of `nextPageToken` from the + * previous response. The values of other method parameters should be + * identical to those in the previous call. + * @param {number} [request.pageSize] + * Optional. The maximum number of results to return from this request. + * + * Non-positive values are ignored. The presence of `nextPageToken` in the + * response indicates that more results might be available. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.logging.v2.LogView|LogView}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v2/config_service_v2.list_views.js + * region_tag:logging_v2_generated_ConfigServiceV2_ListViews_async + */ listViewsAsync( - request?: protos.google.logging.v2.IListViewsRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.logging.v2.IListViewsRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); const defaultCallSettings = this._defaults['listViews']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listViews iterate %j', request); return this.descriptors.page.listViews.asyncIterate( this.innerApiCalls['listViews'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } - /** - * Lists sinks. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent resource whose sinks are to be listed: - * - * "projects/[PROJECT_ID]" - * "organizations/[ORGANIZATION_ID]" - * "billingAccounts/[BILLING_ACCOUNT_ID]" - * "folders/[FOLDER_ID]" - * @param {string} [request.pageToken] - * Optional. If present, then retrieve the next batch of results from the - * preceding call to this method. `pageToken` must be the value of - * `nextPageToken` from the previous response. The values of other method - * parameters should be identical to those in the previous call. - * @param {number} [request.pageSize] - * Optional. The maximum number of results to return from this request. - * Non-positive values are ignored. The presence of `nextPageToken` in the - * response indicates that more results might be available. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.logging.v2.LogSink|LogSink}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `listSinksAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Lists sinks. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource whose sinks are to be listed: + * + * "projects/[PROJECT_ID]" + * "organizations/[ORGANIZATION_ID]" + * "billingAccounts/[BILLING_ACCOUNT_ID]" + * "folders/[FOLDER_ID]" + * @param {string} [request.pageToken] + * Optional. If present, then retrieve the next batch of results from the + * preceding call to this method. `pageToken` must be the value of + * `nextPageToken` from the previous response. The values of other method + * parameters should be identical to those in the previous call. + * @param {number} [request.pageSize] + * Optional. The maximum number of results to return from this request. + * Non-positive values are ignored. The presence of `nextPageToken` in the + * response indicates that more results might be available. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.logging.v2.LogSink|LogSink}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listSinksAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listSinks( - request?: protos.google.logging.v2.IListSinksRequest, - options?: CallOptions): - Promise<[ - protos.google.logging.v2.ILogSink[], - protos.google.logging.v2.IListSinksRequest|null, - protos.google.logging.v2.IListSinksResponse - ]>; + request?: protos.google.logging.v2.IListSinksRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.logging.v2.ILogSink[], + protos.google.logging.v2.IListSinksRequest | null, + protos.google.logging.v2.IListSinksResponse, + ] + >; listSinks( - request: protos.google.logging.v2.IListSinksRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.logging.v2.IListSinksRequest, - protos.google.logging.v2.IListSinksResponse|null|undefined, - protos.google.logging.v2.ILogSink>): void; + request: protos.google.logging.v2.IListSinksRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.logging.v2.IListSinksRequest, + protos.google.logging.v2.IListSinksResponse | null | undefined, + protos.google.logging.v2.ILogSink + >, + ): void; listSinks( - request: protos.google.logging.v2.IListSinksRequest, - callback: PaginationCallback< - protos.google.logging.v2.IListSinksRequest, - protos.google.logging.v2.IListSinksResponse|null|undefined, - protos.google.logging.v2.ILogSink>): void; + request: protos.google.logging.v2.IListSinksRequest, + callback: PaginationCallback< + protos.google.logging.v2.IListSinksRequest, + protos.google.logging.v2.IListSinksResponse | null | undefined, + protos.google.logging.v2.ILogSink + >, + ): void; listSinks( - request?: protos.google.logging.v2.IListSinksRequest, - optionsOrCallback?: CallOptions|PaginationCallback< - protos.google.logging.v2.IListSinksRequest, - protos.google.logging.v2.IListSinksResponse|null|undefined, - protos.google.logging.v2.ILogSink>, - callback?: PaginationCallback< + request?: protos.google.logging.v2.IListSinksRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.logging.v2.IListSinksRequest, - protos.google.logging.v2.IListSinksResponse|null|undefined, - protos.google.logging.v2.ILogSink>): - Promise<[ - protos.google.logging.v2.ILogSink[], - protos.google.logging.v2.IListSinksRequest|null, - protos.google.logging.v2.IListSinksResponse - ]>|void { + protos.google.logging.v2.IListSinksResponse | null | undefined, + protos.google.logging.v2.ILogSink + >, + callback?: PaginationCallback< + protos.google.logging.v2.IListSinksRequest, + protos.google.logging.v2.IListSinksResponse | null | undefined, + protos.google.logging.v2.ILogSink + >, + ): Promise< + [ + protos.google.logging.v2.ILogSink[], + protos.google.logging.v2.IListSinksRequest | null, + protos.google.logging.v2.IListSinksResponse, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.logging.v2.IListSinksRequest, - protos.google.logging.v2.IListSinksResponse|null|undefined, - protos.google.logging.v2.ILogSink>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.logging.v2.IListSinksRequest, + protos.google.logging.v2.IListSinksResponse | null | undefined, + protos.google.logging.v2.ILogSink + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listSinks values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -3489,219 +4334,238 @@ export class ConfigServiceV2Client { this._log.info('listSinks request %j', request); return this.innerApiCalls .listSinks(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.logging.v2.ILogSink[], - protos.google.logging.v2.IListSinksRequest|null, - protos.google.logging.v2.IListSinksResponse - ]) => { - this._log.info('listSinks values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.logging.v2.ILogSink[], + protos.google.logging.v2.IListSinksRequest | null, + protos.google.logging.v2.IListSinksResponse, + ]) => { + this._log.info('listSinks values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listSinks`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent resource whose sinks are to be listed: - * - * "projects/[PROJECT_ID]" - * "organizations/[ORGANIZATION_ID]" - * "billingAccounts/[BILLING_ACCOUNT_ID]" - * "folders/[FOLDER_ID]" - * @param {string} [request.pageToken] - * Optional. If present, then retrieve the next batch of results from the - * preceding call to this method. `pageToken` must be the value of - * `nextPageToken` from the previous response. The values of other method - * parameters should be identical to those in the previous call. - * @param {number} [request.pageSize] - * Optional. The maximum number of results to return from this request. - * Non-positive values are ignored. The presence of `nextPageToken` in the - * response indicates that more results might be available. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.logging.v2.LogSink|LogSink} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `listSinksAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `listSinks`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource whose sinks are to be listed: + * + * "projects/[PROJECT_ID]" + * "organizations/[ORGANIZATION_ID]" + * "billingAccounts/[BILLING_ACCOUNT_ID]" + * "folders/[FOLDER_ID]" + * @param {string} [request.pageToken] + * Optional. If present, then retrieve the next batch of results from the + * preceding call to this method. `pageToken` must be the value of + * `nextPageToken` from the previous response. The values of other method + * parameters should be identical to those in the previous call. + * @param {number} [request.pageSize] + * Optional. The maximum number of results to return from this request. + * Non-positive values are ignored. The presence of `nextPageToken` in the + * response indicates that more results might be available. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.logging.v2.LogSink|LogSink} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listSinksAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listSinksStream( - request?: protos.google.logging.v2.IListSinksRequest, - options?: CallOptions): - Transform{ + request?: protos.google.logging.v2.IListSinksRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); const defaultCallSettings = this._defaults['listSinks']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listSinks stream %j', request); return this.descriptors.page.listSinks.createStream( this.innerApiCalls.listSinks as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listSinks`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent resource whose sinks are to be listed: - * - * "projects/[PROJECT_ID]" - * "organizations/[ORGANIZATION_ID]" - * "billingAccounts/[BILLING_ACCOUNT_ID]" - * "folders/[FOLDER_ID]" - * @param {string} [request.pageToken] - * Optional. If present, then retrieve the next batch of results from the - * preceding call to this method. `pageToken` must be the value of - * `nextPageToken` from the previous response. The values of other method - * parameters should be identical to those in the previous call. - * @param {number} [request.pageSize] - * Optional. The maximum number of results to return from this request. - * Non-positive values are ignored. The presence of `nextPageToken` in the - * response indicates that more results might be available. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.logging.v2.LogSink|LogSink}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v2/config_service_v2.list_sinks.js - * region_tag:logging_v2_generated_ConfigServiceV2_ListSinks_async - */ + /** + * Equivalent to `listSinks`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource whose sinks are to be listed: + * + * "projects/[PROJECT_ID]" + * "organizations/[ORGANIZATION_ID]" + * "billingAccounts/[BILLING_ACCOUNT_ID]" + * "folders/[FOLDER_ID]" + * @param {string} [request.pageToken] + * Optional. If present, then retrieve the next batch of results from the + * preceding call to this method. `pageToken` must be the value of + * `nextPageToken` from the previous response. The values of other method + * parameters should be identical to those in the previous call. + * @param {number} [request.pageSize] + * Optional. The maximum number of results to return from this request. + * Non-positive values are ignored. The presence of `nextPageToken` in the + * response indicates that more results might be available. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.logging.v2.LogSink|LogSink}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v2/config_service_v2.list_sinks.js + * region_tag:logging_v2_generated_ConfigServiceV2_ListSinks_async + */ listSinksAsync( - request?: protos.google.logging.v2.IListSinksRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.logging.v2.IListSinksRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); const defaultCallSettings = this._defaults['listSinks']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listSinks iterate %j', request); return this.descriptors.page.listSinks.asyncIterate( this.innerApiCalls['listSinks'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } - /** - * Lists all the exclusions on the _Default sink in a parent resource. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent resource whose exclusions are to be listed. - * - * "projects/[PROJECT_ID]" - * "organizations/[ORGANIZATION_ID]" - * "billingAccounts/[BILLING_ACCOUNT_ID]" - * "folders/[FOLDER_ID]" - * @param {string} [request.pageToken] - * Optional. If present, then retrieve the next batch of results from the - * preceding call to this method. `pageToken` must be the value of - * `nextPageToken` from the previous response. The values of other method - * parameters should be identical to those in the previous call. - * @param {number} [request.pageSize] - * Optional. The maximum number of results to return from this request. - * Non-positive values are ignored. The presence of `nextPageToken` in the - * response indicates that more results might be available. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.logging.v2.LogExclusion|LogExclusion}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `listExclusionsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Lists all the exclusions on the _Default sink in a parent resource. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource whose exclusions are to be listed. + * + * "projects/[PROJECT_ID]" + * "organizations/[ORGANIZATION_ID]" + * "billingAccounts/[BILLING_ACCOUNT_ID]" + * "folders/[FOLDER_ID]" + * @param {string} [request.pageToken] + * Optional. If present, then retrieve the next batch of results from the + * preceding call to this method. `pageToken` must be the value of + * `nextPageToken` from the previous response. The values of other method + * parameters should be identical to those in the previous call. + * @param {number} [request.pageSize] + * Optional. The maximum number of results to return from this request. + * Non-positive values are ignored. The presence of `nextPageToken` in the + * response indicates that more results might be available. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.logging.v2.LogExclusion|LogExclusion}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listExclusionsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listExclusions( - request?: protos.google.logging.v2.IListExclusionsRequest, - options?: CallOptions): - Promise<[ - protos.google.logging.v2.ILogExclusion[], - protos.google.logging.v2.IListExclusionsRequest|null, - protos.google.logging.v2.IListExclusionsResponse - ]>; + request?: protos.google.logging.v2.IListExclusionsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.logging.v2.ILogExclusion[], + protos.google.logging.v2.IListExclusionsRequest | null, + protos.google.logging.v2.IListExclusionsResponse, + ] + >; listExclusions( - request: protos.google.logging.v2.IListExclusionsRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.logging.v2.IListExclusionsRequest, - protos.google.logging.v2.IListExclusionsResponse|null|undefined, - protos.google.logging.v2.ILogExclusion>): void; + request: protos.google.logging.v2.IListExclusionsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.logging.v2.IListExclusionsRequest, + protos.google.logging.v2.IListExclusionsResponse | null | undefined, + protos.google.logging.v2.ILogExclusion + >, + ): void; listExclusions( - request: protos.google.logging.v2.IListExclusionsRequest, - callback: PaginationCallback< - protos.google.logging.v2.IListExclusionsRequest, - protos.google.logging.v2.IListExclusionsResponse|null|undefined, - protos.google.logging.v2.ILogExclusion>): void; + request: protos.google.logging.v2.IListExclusionsRequest, + callback: PaginationCallback< + protos.google.logging.v2.IListExclusionsRequest, + protos.google.logging.v2.IListExclusionsResponse | null | undefined, + protos.google.logging.v2.ILogExclusion + >, + ): void; listExclusions( - request?: protos.google.logging.v2.IListExclusionsRequest, - optionsOrCallback?: CallOptions|PaginationCallback< - protos.google.logging.v2.IListExclusionsRequest, - protos.google.logging.v2.IListExclusionsResponse|null|undefined, - protos.google.logging.v2.ILogExclusion>, - callback?: PaginationCallback< + request?: protos.google.logging.v2.IListExclusionsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.logging.v2.IListExclusionsRequest, - protos.google.logging.v2.IListExclusionsResponse|null|undefined, - protos.google.logging.v2.ILogExclusion>): - Promise<[ - protos.google.logging.v2.ILogExclusion[], - protos.google.logging.v2.IListExclusionsRequest|null, - protos.google.logging.v2.IListExclusionsResponse - ]>|void { + protos.google.logging.v2.IListExclusionsResponse | null | undefined, + protos.google.logging.v2.ILogExclusion + >, + callback?: PaginationCallback< + protos.google.logging.v2.IListExclusionsRequest, + protos.google.logging.v2.IListExclusionsResponse | null | undefined, + protos.google.logging.v2.ILogExclusion + >, + ): Promise< + [ + protos.google.logging.v2.ILogExclusion[], + protos.google.logging.v2.IListExclusionsRequest | null, + protos.google.logging.v2.IListExclusionsResponse, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.logging.v2.IListExclusionsRequest, - protos.google.logging.v2.IListExclusionsResponse|null|undefined, - protos.google.logging.v2.ILogExclusion>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.logging.v2.IListExclusionsRequest, + protos.google.logging.v2.IListExclusionsResponse | null | undefined, + protos.google.logging.v2.ILogExclusion + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listExclusions values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -3710,126 +4574,130 @@ export class ConfigServiceV2Client { this._log.info('listExclusions request %j', request); return this.innerApiCalls .listExclusions(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.logging.v2.ILogExclusion[], - protos.google.logging.v2.IListExclusionsRequest|null, - protos.google.logging.v2.IListExclusionsResponse - ]) => { - this._log.info('listExclusions values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.logging.v2.ILogExclusion[], + protos.google.logging.v2.IListExclusionsRequest | null, + protos.google.logging.v2.IListExclusionsResponse, + ]) => { + this._log.info('listExclusions values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listExclusions`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent resource whose exclusions are to be listed. - * - * "projects/[PROJECT_ID]" - * "organizations/[ORGANIZATION_ID]" - * "billingAccounts/[BILLING_ACCOUNT_ID]" - * "folders/[FOLDER_ID]" - * @param {string} [request.pageToken] - * Optional. If present, then retrieve the next batch of results from the - * preceding call to this method. `pageToken` must be the value of - * `nextPageToken` from the previous response. The values of other method - * parameters should be identical to those in the previous call. - * @param {number} [request.pageSize] - * Optional. The maximum number of results to return from this request. - * Non-positive values are ignored. The presence of `nextPageToken` in the - * response indicates that more results might be available. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.logging.v2.LogExclusion|LogExclusion} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `listExclusionsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `listExclusions`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource whose exclusions are to be listed. + * + * "projects/[PROJECT_ID]" + * "organizations/[ORGANIZATION_ID]" + * "billingAccounts/[BILLING_ACCOUNT_ID]" + * "folders/[FOLDER_ID]" + * @param {string} [request.pageToken] + * Optional. If present, then retrieve the next batch of results from the + * preceding call to this method. `pageToken` must be the value of + * `nextPageToken` from the previous response. The values of other method + * parameters should be identical to those in the previous call. + * @param {number} [request.pageSize] + * Optional. The maximum number of results to return from this request. + * Non-positive values are ignored. The presence of `nextPageToken` in the + * response indicates that more results might be available. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.logging.v2.LogExclusion|LogExclusion} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listExclusionsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listExclusionsStream( - request?: protos.google.logging.v2.IListExclusionsRequest, - options?: CallOptions): - Transform{ + request?: protos.google.logging.v2.IListExclusionsRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); const defaultCallSettings = this._defaults['listExclusions']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listExclusions stream %j', request); return this.descriptors.page.listExclusions.createStream( this.innerApiCalls.listExclusions as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listExclusions`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent resource whose exclusions are to be listed. - * - * "projects/[PROJECT_ID]" - * "organizations/[ORGANIZATION_ID]" - * "billingAccounts/[BILLING_ACCOUNT_ID]" - * "folders/[FOLDER_ID]" - * @param {string} [request.pageToken] - * Optional. If present, then retrieve the next batch of results from the - * preceding call to this method. `pageToken` must be the value of - * `nextPageToken` from the previous response. The values of other method - * parameters should be identical to those in the previous call. - * @param {number} [request.pageSize] - * Optional. The maximum number of results to return from this request. - * Non-positive values are ignored. The presence of `nextPageToken` in the - * response indicates that more results might be available. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.logging.v2.LogExclusion|LogExclusion}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v2/config_service_v2.list_exclusions.js - * region_tag:logging_v2_generated_ConfigServiceV2_ListExclusions_async - */ + /** + * Equivalent to `listExclusions`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource whose exclusions are to be listed. + * + * "projects/[PROJECT_ID]" + * "organizations/[ORGANIZATION_ID]" + * "billingAccounts/[BILLING_ACCOUNT_ID]" + * "folders/[FOLDER_ID]" + * @param {string} [request.pageToken] + * Optional. If present, then retrieve the next batch of results from the + * preceding call to this method. `pageToken` must be the value of + * `nextPageToken` from the previous response. The values of other method + * parameters should be identical to those in the previous call. + * @param {number} [request.pageSize] + * Optional. The maximum number of results to return from this request. + * Non-positive values are ignored. The presence of `nextPageToken` in the + * response indicates that more results might be available. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.logging.v2.LogExclusion|LogExclusion}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v2/config_service_v2.list_exclusions.js + * region_tag:logging_v2_generated_ConfigServiceV2_ListExclusions_async + */ listExclusionsAsync( - request?: protos.google.logging.v2.IListExclusionsRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.logging.v2.IListExclusionsRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); const defaultCallSettings = this._defaults['listExclusions']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listExclusions iterate %j', request); return this.descriptors.page.listExclusions.asyncIterate( this.innerApiCalls['listExclusions'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } // -------------------- @@ -3842,7 +4710,7 @@ export class ConfigServiceV2Client { * @param {string} billing_account * @returns {string} Resource name string. */ - billingAccountCmekSettingsPath(billingAccount:string) { + billingAccountCmekSettingsPath(billingAccount: string) { return this.pathTemplates.billingAccountCmekSettingsPathTemplate.render({ billing_account: billingAccount, }); @@ -3855,8 +4723,12 @@ export class ConfigServiceV2Client { * A fully-qualified path representing billing_account_cmekSettings resource. * @returns {string} A string representing the billing_account. */ - matchBillingAccountFromBillingAccountCmekSettingsName(billingAccountCmekSettingsName: string) { - return this.pathTemplates.billingAccountCmekSettingsPathTemplate.match(billingAccountCmekSettingsName).billing_account; + matchBillingAccountFromBillingAccountCmekSettingsName( + billingAccountCmekSettingsName: string, + ) { + return this.pathTemplates.billingAccountCmekSettingsPathTemplate.match( + billingAccountCmekSettingsName, + ).billing_account; } /** @@ -3866,7 +4738,7 @@ export class ConfigServiceV2Client { * @param {string} exclusion * @returns {string} Resource name string. */ - billingAccountExclusionPath(billingAccount:string,exclusion:string) { + billingAccountExclusionPath(billingAccount: string, exclusion: string) { return this.pathTemplates.billingAccountExclusionPathTemplate.render({ billing_account: billingAccount, exclusion: exclusion, @@ -3880,8 +4752,12 @@ export class ConfigServiceV2Client { * A fully-qualified path representing billing_account_exclusion resource. * @returns {string} A string representing the billing_account. */ - matchBillingAccountFromBillingAccountExclusionName(billingAccountExclusionName: string) { - return this.pathTemplates.billingAccountExclusionPathTemplate.match(billingAccountExclusionName).billing_account; + matchBillingAccountFromBillingAccountExclusionName( + billingAccountExclusionName: string, + ) { + return this.pathTemplates.billingAccountExclusionPathTemplate.match( + billingAccountExclusionName, + ).billing_account; } /** @@ -3891,8 +4767,12 @@ export class ConfigServiceV2Client { * A fully-qualified path representing billing_account_exclusion resource. * @returns {string} A string representing the exclusion. */ - matchExclusionFromBillingAccountExclusionName(billingAccountExclusionName: string) { - return this.pathTemplates.billingAccountExclusionPathTemplate.match(billingAccountExclusionName).exclusion; + matchExclusionFromBillingAccountExclusionName( + billingAccountExclusionName: string, + ) { + return this.pathTemplates.billingAccountExclusionPathTemplate.match( + billingAccountExclusionName, + ).exclusion; } /** @@ -3903,7 +4783,11 @@ export class ConfigServiceV2Client { * @param {string} bucket * @returns {string} Resource name string. */ - billingAccountLocationBucketPath(billingAccount:string,location:string,bucket:string) { + billingAccountLocationBucketPath( + billingAccount: string, + location: string, + bucket: string, + ) { return this.pathTemplates.billingAccountLocationBucketPathTemplate.render({ billing_account: billingAccount, location: location, @@ -3918,8 +4802,12 @@ export class ConfigServiceV2Client { * A fully-qualified path representing billing_account_location_bucket resource. * @returns {string} A string representing the billing_account. */ - matchBillingAccountFromBillingAccountLocationBucketName(billingAccountLocationBucketName: string) { - return this.pathTemplates.billingAccountLocationBucketPathTemplate.match(billingAccountLocationBucketName).billing_account; + matchBillingAccountFromBillingAccountLocationBucketName( + billingAccountLocationBucketName: string, + ) { + return this.pathTemplates.billingAccountLocationBucketPathTemplate.match( + billingAccountLocationBucketName, + ).billing_account; } /** @@ -3929,8 +4817,12 @@ export class ConfigServiceV2Client { * A fully-qualified path representing billing_account_location_bucket resource. * @returns {string} A string representing the location. */ - matchLocationFromBillingAccountLocationBucketName(billingAccountLocationBucketName: string) { - return this.pathTemplates.billingAccountLocationBucketPathTemplate.match(billingAccountLocationBucketName).location; + matchLocationFromBillingAccountLocationBucketName( + billingAccountLocationBucketName: string, + ) { + return this.pathTemplates.billingAccountLocationBucketPathTemplate.match( + billingAccountLocationBucketName, + ).location; } /** @@ -3940,8 +4832,12 @@ export class ConfigServiceV2Client { * A fully-qualified path representing billing_account_location_bucket resource. * @returns {string} A string representing the bucket. */ - matchBucketFromBillingAccountLocationBucketName(billingAccountLocationBucketName: string) { - return this.pathTemplates.billingAccountLocationBucketPathTemplate.match(billingAccountLocationBucketName).bucket; + matchBucketFromBillingAccountLocationBucketName( + billingAccountLocationBucketName: string, + ) { + return this.pathTemplates.billingAccountLocationBucketPathTemplate.match( + billingAccountLocationBucketName, + ).bucket; } /** @@ -3953,13 +4849,20 @@ export class ConfigServiceV2Client { * @param {string} view * @returns {string} Resource name string. */ - billingAccountLocationBucketViewPath(billingAccount:string,location:string,bucket:string,view:string) { - return this.pathTemplates.billingAccountLocationBucketViewPathTemplate.render({ - billing_account: billingAccount, - location: location, - bucket: bucket, - view: view, - }); + billingAccountLocationBucketViewPath( + billingAccount: string, + location: string, + bucket: string, + view: string, + ) { + return this.pathTemplates.billingAccountLocationBucketViewPathTemplate.render( + { + billing_account: billingAccount, + location: location, + bucket: bucket, + view: view, + }, + ); } /** @@ -3969,8 +4872,12 @@ export class ConfigServiceV2Client { * A fully-qualified path representing billing_account_location_bucket_view resource. * @returns {string} A string representing the billing_account. */ - matchBillingAccountFromBillingAccountLocationBucketViewName(billingAccountLocationBucketViewName: string) { - return this.pathTemplates.billingAccountLocationBucketViewPathTemplate.match(billingAccountLocationBucketViewName).billing_account; + matchBillingAccountFromBillingAccountLocationBucketViewName( + billingAccountLocationBucketViewName: string, + ) { + return this.pathTemplates.billingAccountLocationBucketViewPathTemplate.match( + billingAccountLocationBucketViewName, + ).billing_account; } /** @@ -3980,8 +4887,12 @@ export class ConfigServiceV2Client { * A fully-qualified path representing billing_account_location_bucket_view resource. * @returns {string} A string representing the location. */ - matchLocationFromBillingAccountLocationBucketViewName(billingAccountLocationBucketViewName: string) { - return this.pathTemplates.billingAccountLocationBucketViewPathTemplate.match(billingAccountLocationBucketViewName).location; + matchLocationFromBillingAccountLocationBucketViewName( + billingAccountLocationBucketViewName: string, + ) { + return this.pathTemplates.billingAccountLocationBucketViewPathTemplate.match( + billingAccountLocationBucketViewName, + ).location; } /** @@ -3991,8 +4902,12 @@ export class ConfigServiceV2Client { * A fully-qualified path representing billing_account_location_bucket_view resource. * @returns {string} A string representing the bucket. */ - matchBucketFromBillingAccountLocationBucketViewName(billingAccountLocationBucketViewName: string) { - return this.pathTemplates.billingAccountLocationBucketViewPathTemplate.match(billingAccountLocationBucketViewName).bucket; + matchBucketFromBillingAccountLocationBucketViewName( + billingAccountLocationBucketViewName: string, + ) { + return this.pathTemplates.billingAccountLocationBucketViewPathTemplate.match( + billingAccountLocationBucketViewName, + ).bucket; } /** @@ -4002,8 +4917,12 @@ export class ConfigServiceV2Client { * A fully-qualified path representing billing_account_location_bucket_view resource. * @returns {string} A string representing the view. */ - matchViewFromBillingAccountLocationBucketViewName(billingAccountLocationBucketViewName: string) { - return this.pathTemplates.billingAccountLocationBucketViewPathTemplate.match(billingAccountLocationBucketViewName).view; + matchViewFromBillingAccountLocationBucketViewName( + billingAccountLocationBucketViewName: string, + ) { + return this.pathTemplates.billingAccountLocationBucketViewPathTemplate.match( + billingAccountLocationBucketViewName, + ).view; } /** @@ -4013,7 +4932,7 @@ export class ConfigServiceV2Client { * @param {string} log * @returns {string} Resource name string. */ - billingAccountLogPath(billingAccount:string,log:string) { + billingAccountLogPath(billingAccount: string, log: string) { return this.pathTemplates.billingAccountLogPathTemplate.render({ billing_account: billingAccount, log: log, @@ -4028,7 +4947,9 @@ export class ConfigServiceV2Client { * @returns {string} A string representing the billing_account. */ matchBillingAccountFromBillingAccountLogName(billingAccountLogName: string) { - return this.pathTemplates.billingAccountLogPathTemplate.match(billingAccountLogName).billing_account; + return this.pathTemplates.billingAccountLogPathTemplate.match( + billingAccountLogName, + ).billing_account; } /** @@ -4039,7 +4960,9 @@ export class ConfigServiceV2Client { * @returns {string} A string representing the log. */ matchLogFromBillingAccountLogName(billingAccountLogName: string) { - return this.pathTemplates.billingAccountLogPathTemplate.match(billingAccountLogName).log; + return this.pathTemplates.billingAccountLogPathTemplate.match( + billingAccountLogName, + ).log; } /** @@ -4048,7 +4971,7 @@ export class ConfigServiceV2Client { * @param {string} billing_account * @returns {string} Resource name string. */ - billingAccountSettingsPath(billingAccount:string) { + billingAccountSettingsPath(billingAccount: string) { return this.pathTemplates.billingAccountSettingsPathTemplate.render({ billing_account: billingAccount, }); @@ -4061,8 +4984,12 @@ export class ConfigServiceV2Client { * A fully-qualified path representing billing_account_settings resource. * @returns {string} A string representing the billing_account. */ - matchBillingAccountFromBillingAccountSettingsName(billingAccountSettingsName: string) { - return this.pathTemplates.billingAccountSettingsPathTemplate.match(billingAccountSettingsName).billing_account; + matchBillingAccountFromBillingAccountSettingsName( + billingAccountSettingsName: string, + ) { + return this.pathTemplates.billingAccountSettingsPathTemplate.match( + billingAccountSettingsName, + ).billing_account; } /** @@ -4072,7 +4999,7 @@ export class ConfigServiceV2Client { * @param {string} sink * @returns {string} Resource name string. */ - billingAccountSinkPath(billingAccount:string,sink:string) { + billingAccountSinkPath(billingAccount: string, sink: string) { return this.pathTemplates.billingAccountSinkPathTemplate.render({ billing_account: billingAccount, sink: sink, @@ -4086,8 +5013,12 @@ export class ConfigServiceV2Client { * A fully-qualified path representing billing_account_sink resource. * @returns {string} A string representing the billing_account. */ - matchBillingAccountFromBillingAccountSinkName(billingAccountSinkName: string) { - return this.pathTemplates.billingAccountSinkPathTemplate.match(billingAccountSinkName).billing_account; + matchBillingAccountFromBillingAccountSinkName( + billingAccountSinkName: string, + ) { + return this.pathTemplates.billingAccountSinkPathTemplate.match( + billingAccountSinkName, + ).billing_account; } /** @@ -4098,7 +5029,9 @@ export class ConfigServiceV2Client { * @returns {string} A string representing the sink. */ matchSinkFromBillingAccountSinkName(billingAccountSinkName: string) { - return this.pathTemplates.billingAccountSinkPathTemplate.match(billingAccountSinkName).sink; + return this.pathTemplates.billingAccountSinkPathTemplate.match( + billingAccountSinkName, + ).sink; } /** @@ -4107,7 +5040,7 @@ export class ConfigServiceV2Client { * @param {string} folder * @returns {string} Resource name string. */ - folderCmekSettingsPath(folder:string) { + folderCmekSettingsPath(folder: string) { return this.pathTemplates.folderCmekSettingsPathTemplate.render({ folder: folder, }); @@ -4121,7 +5054,9 @@ export class ConfigServiceV2Client { * @returns {string} A string representing the folder. */ matchFolderFromFolderCmekSettingsName(folderCmekSettingsName: string) { - return this.pathTemplates.folderCmekSettingsPathTemplate.match(folderCmekSettingsName).folder; + return this.pathTemplates.folderCmekSettingsPathTemplate.match( + folderCmekSettingsName, + ).folder; } /** @@ -4131,7 +5066,7 @@ export class ConfigServiceV2Client { * @param {string} exclusion * @returns {string} Resource name string. */ - folderExclusionPath(folder:string,exclusion:string) { + folderExclusionPath(folder: string, exclusion: string) { return this.pathTemplates.folderExclusionPathTemplate.render({ folder: folder, exclusion: exclusion, @@ -4146,7 +5081,9 @@ export class ConfigServiceV2Client { * @returns {string} A string representing the folder. */ matchFolderFromFolderExclusionName(folderExclusionName: string) { - return this.pathTemplates.folderExclusionPathTemplate.match(folderExclusionName).folder; + return this.pathTemplates.folderExclusionPathTemplate.match( + folderExclusionName, + ).folder; } /** @@ -4157,7 +5094,9 @@ export class ConfigServiceV2Client { * @returns {string} A string representing the exclusion. */ matchExclusionFromFolderExclusionName(folderExclusionName: string) { - return this.pathTemplates.folderExclusionPathTemplate.match(folderExclusionName).exclusion; + return this.pathTemplates.folderExclusionPathTemplate.match( + folderExclusionName, + ).exclusion; } /** @@ -4168,7 +5107,7 @@ export class ConfigServiceV2Client { * @param {string} bucket * @returns {string} Resource name string. */ - folderLocationBucketPath(folder:string,location:string,bucket:string) { + folderLocationBucketPath(folder: string, location: string, bucket: string) { return this.pathTemplates.folderLocationBucketPathTemplate.render({ folder: folder, location: location, @@ -4184,7 +5123,9 @@ export class ConfigServiceV2Client { * @returns {string} A string representing the folder. */ matchFolderFromFolderLocationBucketName(folderLocationBucketName: string) { - return this.pathTemplates.folderLocationBucketPathTemplate.match(folderLocationBucketName).folder; + return this.pathTemplates.folderLocationBucketPathTemplate.match( + folderLocationBucketName, + ).folder; } /** @@ -4195,7 +5136,9 @@ export class ConfigServiceV2Client { * @returns {string} A string representing the location. */ matchLocationFromFolderLocationBucketName(folderLocationBucketName: string) { - return this.pathTemplates.folderLocationBucketPathTemplate.match(folderLocationBucketName).location; + return this.pathTemplates.folderLocationBucketPathTemplate.match( + folderLocationBucketName, + ).location; } /** @@ -4206,7 +5149,9 @@ export class ConfigServiceV2Client { * @returns {string} A string representing the bucket. */ matchBucketFromFolderLocationBucketName(folderLocationBucketName: string) { - return this.pathTemplates.folderLocationBucketPathTemplate.match(folderLocationBucketName).bucket; + return this.pathTemplates.folderLocationBucketPathTemplate.match( + folderLocationBucketName, + ).bucket; } /** @@ -4218,7 +5163,12 @@ export class ConfigServiceV2Client { * @param {string} view * @returns {string} Resource name string. */ - folderLocationBucketViewPath(folder:string,location:string,bucket:string,view:string) { + folderLocationBucketViewPath( + folder: string, + location: string, + bucket: string, + view: string, + ) { return this.pathTemplates.folderLocationBucketViewPathTemplate.render({ folder: folder, location: location, @@ -4234,8 +5184,12 @@ export class ConfigServiceV2Client { * A fully-qualified path representing folder_location_bucket_view resource. * @returns {string} A string representing the folder. */ - matchFolderFromFolderLocationBucketViewName(folderLocationBucketViewName: string) { - return this.pathTemplates.folderLocationBucketViewPathTemplate.match(folderLocationBucketViewName).folder; + matchFolderFromFolderLocationBucketViewName( + folderLocationBucketViewName: string, + ) { + return this.pathTemplates.folderLocationBucketViewPathTemplate.match( + folderLocationBucketViewName, + ).folder; } /** @@ -4245,8 +5199,12 @@ export class ConfigServiceV2Client { * A fully-qualified path representing folder_location_bucket_view resource. * @returns {string} A string representing the location. */ - matchLocationFromFolderLocationBucketViewName(folderLocationBucketViewName: string) { - return this.pathTemplates.folderLocationBucketViewPathTemplate.match(folderLocationBucketViewName).location; + matchLocationFromFolderLocationBucketViewName( + folderLocationBucketViewName: string, + ) { + return this.pathTemplates.folderLocationBucketViewPathTemplate.match( + folderLocationBucketViewName, + ).location; } /** @@ -4256,8 +5214,12 @@ export class ConfigServiceV2Client { * A fully-qualified path representing folder_location_bucket_view resource. * @returns {string} A string representing the bucket. */ - matchBucketFromFolderLocationBucketViewName(folderLocationBucketViewName: string) { - return this.pathTemplates.folderLocationBucketViewPathTemplate.match(folderLocationBucketViewName).bucket; + matchBucketFromFolderLocationBucketViewName( + folderLocationBucketViewName: string, + ) { + return this.pathTemplates.folderLocationBucketViewPathTemplate.match( + folderLocationBucketViewName, + ).bucket; } /** @@ -4267,8 +5229,12 @@ export class ConfigServiceV2Client { * A fully-qualified path representing folder_location_bucket_view resource. * @returns {string} A string representing the view. */ - matchViewFromFolderLocationBucketViewName(folderLocationBucketViewName: string) { - return this.pathTemplates.folderLocationBucketViewPathTemplate.match(folderLocationBucketViewName).view; + matchViewFromFolderLocationBucketViewName( + folderLocationBucketViewName: string, + ) { + return this.pathTemplates.folderLocationBucketViewPathTemplate.match( + folderLocationBucketViewName, + ).view; } /** @@ -4278,7 +5244,7 @@ export class ConfigServiceV2Client { * @param {string} log * @returns {string} Resource name string. */ - folderLogPath(folder:string,log:string) { + folderLogPath(folder: string, log: string) { return this.pathTemplates.folderLogPathTemplate.render({ folder: folder, log: log, @@ -4313,7 +5279,7 @@ export class ConfigServiceV2Client { * @param {string} folder * @returns {string} Resource name string. */ - folderSettingsPath(folder:string) { + folderSettingsPath(folder: string) { return this.pathTemplates.folderSettingsPathTemplate.render({ folder: folder, }); @@ -4327,7 +5293,9 @@ export class ConfigServiceV2Client { * @returns {string} A string representing the folder. */ matchFolderFromFolderSettingsName(folderSettingsName: string) { - return this.pathTemplates.folderSettingsPathTemplate.match(folderSettingsName).folder; + return this.pathTemplates.folderSettingsPathTemplate.match( + folderSettingsName, + ).folder; } /** @@ -4337,7 +5305,7 @@ export class ConfigServiceV2Client { * @param {string} sink * @returns {string} Resource name string. */ - folderSinkPath(folder:string,sink:string) { + folderSinkPath(folder: string, sink: string) { return this.pathTemplates.folderSinkPathTemplate.render({ folder: folder, sink: sink, @@ -4352,7 +5320,8 @@ export class ConfigServiceV2Client { * @returns {string} A string representing the folder. */ matchFolderFromFolderSinkName(folderSinkName: string) { - return this.pathTemplates.folderSinkPathTemplate.match(folderSinkName).folder; + return this.pathTemplates.folderSinkPathTemplate.match(folderSinkName) + .folder; } /** @@ -4373,7 +5342,7 @@ export class ConfigServiceV2Client { * @param {string} location * @returns {string} Resource name string. */ - locationPath(project:string,location:string) { + locationPath(project: string, location: string) { return this.pathTemplates.locationPathTemplate.render({ project: project, location: location, @@ -4409,7 +5378,7 @@ export class ConfigServiceV2Client { * @param {string} metric * @returns {string} Resource name string. */ - logMetricPath(project:string,metric:string) { + logMetricPath(project: string, metric: string) { return this.pathTemplates.logMetricPathTemplate.render({ project: project, metric: metric, @@ -4424,7 +5393,8 @@ export class ConfigServiceV2Client { * @returns {string} A string representing the project. */ matchProjectFromLogMetricName(logMetricName: string) { - return this.pathTemplates.logMetricPathTemplate.match(logMetricName).project; + return this.pathTemplates.logMetricPathTemplate.match(logMetricName) + .project; } /** @@ -4444,7 +5414,7 @@ export class ConfigServiceV2Client { * @param {string} organization * @returns {string} Resource name string. */ - organizationCmekSettingsPath(organization:string) { + organizationCmekSettingsPath(organization: string) { return this.pathTemplates.organizationCmekSettingsPathTemplate.render({ organization: organization, }); @@ -4457,8 +5427,12 @@ export class ConfigServiceV2Client { * A fully-qualified path representing organization_cmekSettings resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationCmekSettingsName(organizationCmekSettingsName: string) { - return this.pathTemplates.organizationCmekSettingsPathTemplate.match(organizationCmekSettingsName).organization; + matchOrganizationFromOrganizationCmekSettingsName( + organizationCmekSettingsName: string, + ) { + return this.pathTemplates.organizationCmekSettingsPathTemplate.match( + organizationCmekSettingsName, + ).organization; } /** @@ -4468,7 +5442,7 @@ export class ConfigServiceV2Client { * @param {string} exclusion * @returns {string} Resource name string. */ - organizationExclusionPath(organization:string,exclusion:string) { + organizationExclusionPath(organization: string, exclusion: string) { return this.pathTemplates.organizationExclusionPathTemplate.render({ organization: organization, exclusion: exclusion, @@ -4482,8 +5456,12 @@ export class ConfigServiceV2Client { * A fully-qualified path representing organization_exclusion resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationExclusionName(organizationExclusionName: string) { - return this.pathTemplates.organizationExclusionPathTemplate.match(organizationExclusionName).organization; + matchOrganizationFromOrganizationExclusionName( + organizationExclusionName: string, + ) { + return this.pathTemplates.organizationExclusionPathTemplate.match( + organizationExclusionName, + ).organization; } /** @@ -4493,8 +5471,12 @@ export class ConfigServiceV2Client { * A fully-qualified path representing organization_exclusion resource. * @returns {string} A string representing the exclusion. */ - matchExclusionFromOrganizationExclusionName(organizationExclusionName: string) { - return this.pathTemplates.organizationExclusionPathTemplate.match(organizationExclusionName).exclusion; + matchExclusionFromOrganizationExclusionName( + organizationExclusionName: string, + ) { + return this.pathTemplates.organizationExclusionPathTemplate.match( + organizationExclusionName, + ).exclusion; } /** @@ -4505,7 +5487,11 @@ export class ConfigServiceV2Client { * @param {string} bucket * @returns {string} Resource name string. */ - organizationLocationBucketPath(organization:string,location:string,bucket:string) { + organizationLocationBucketPath( + organization: string, + location: string, + bucket: string, + ) { return this.pathTemplates.organizationLocationBucketPathTemplate.render({ organization: organization, location: location, @@ -4520,8 +5506,12 @@ export class ConfigServiceV2Client { * A fully-qualified path representing organization_location_bucket resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationLocationBucketName(organizationLocationBucketName: string) { - return this.pathTemplates.organizationLocationBucketPathTemplate.match(organizationLocationBucketName).organization; + matchOrganizationFromOrganizationLocationBucketName( + organizationLocationBucketName: string, + ) { + return this.pathTemplates.organizationLocationBucketPathTemplate.match( + organizationLocationBucketName, + ).organization; } /** @@ -4531,8 +5521,12 @@ export class ConfigServiceV2Client { * A fully-qualified path representing organization_location_bucket resource. * @returns {string} A string representing the location. */ - matchLocationFromOrganizationLocationBucketName(organizationLocationBucketName: string) { - return this.pathTemplates.organizationLocationBucketPathTemplate.match(organizationLocationBucketName).location; + matchLocationFromOrganizationLocationBucketName( + organizationLocationBucketName: string, + ) { + return this.pathTemplates.organizationLocationBucketPathTemplate.match( + organizationLocationBucketName, + ).location; } /** @@ -4542,8 +5536,12 @@ export class ConfigServiceV2Client { * A fully-qualified path representing organization_location_bucket resource. * @returns {string} A string representing the bucket. */ - matchBucketFromOrganizationLocationBucketName(organizationLocationBucketName: string) { - return this.pathTemplates.organizationLocationBucketPathTemplate.match(organizationLocationBucketName).bucket; + matchBucketFromOrganizationLocationBucketName( + organizationLocationBucketName: string, + ) { + return this.pathTemplates.organizationLocationBucketPathTemplate.match( + organizationLocationBucketName, + ).bucket; } /** @@ -4555,13 +5553,20 @@ export class ConfigServiceV2Client { * @param {string} view * @returns {string} Resource name string. */ - organizationLocationBucketViewPath(organization:string,location:string,bucket:string,view:string) { - return this.pathTemplates.organizationLocationBucketViewPathTemplate.render({ - organization: organization, - location: location, - bucket: bucket, - view: view, - }); + organizationLocationBucketViewPath( + organization: string, + location: string, + bucket: string, + view: string, + ) { + return this.pathTemplates.organizationLocationBucketViewPathTemplate.render( + { + organization: organization, + location: location, + bucket: bucket, + view: view, + }, + ); } /** @@ -4571,8 +5576,12 @@ export class ConfigServiceV2Client { * A fully-qualified path representing organization_location_bucket_view resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationLocationBucketViewName(organizationLocationBucketViewName: string) { - return this.pathTemplates.organizationLocationBucketViewPathTemplate.match(organizationLocationBucketViewName).organization; + matchOrganizationFromOrganizationLocationBucketViewName( + organizationLocationBucketViewName: string, + ) { + return this.pathTemplates.organizationLocationBucketViewPathTemplate.match( + organizationLocationBucketViewName, + ).organization; } /** @@ -4582,8 +5591,12 @@ export class ConfigServiceV2Client { * A fully-qualified path representing organization_location_bucket_view resource. * @returns {string} A string representing the location. */ - matchLocationFromOrganizationLocationBucketViewName(organizationLocationBucketViewName: string) { - return this.pathTemplates.organizationLocationBucketViewPathTemplate.match(organizationLocationBucketViewName).location; + matchLocationFromOrganizationLocationBucketViewName( + organizationLocationBucketViewName: string, + ) { + return this.pathTemplates.organizationLocationBucketViewPathTemplate.match( + organizationLocationBucketViewName, + ).location; } /** @@ -4593,8 +5606,12 @@ export class ConfigServiceV2Client { * A fully-qualified path representing organization_location_bucket_view resource. * @returns {string} A string representing the bucket. */ - matchBucketFromOrganizationLocationBucketViewName(organizationLocationBucketViewName: string) { - return this.pathTemplates.organizationLocationBucketViewPathTemplate.match(organizationLocationBucketViewName).bucket; + matchBucketFromOrganizationLocationBucketViewName( + organizationLocationBucketViewName: string, + ) { + return this.pathTemplates.organizationLocationBucketViewPathTemplate.match( + organizationLocationBucketViewName, + ).bucket; } /** @@ -4604,8 +5621,12 @@ export class ConfigServiceV2Client { * A fully-qualified path representing organization_location_bucket_view resource. * @returns {string} A string representing the view. */ - matchViewFromOrganizationLocationBucketViewName(organizationLocationBucketViewName: string) { - return this.pathTemplates.organizationLocationBucketViewPathTemplate.match(organizationLocationBucketViewName).view; + matchViewFromOrganizationLocationBucketViewName( + organizationLocationBucketViewName: string, + ) { + return this.pathTemplates.organizationLocationBucketViewPathTemplate.match( + organizationLocationBucketViewName, + ).view; } /** @@ -4615,7 +5636,7 @@ export class ConfigServiceV2Client { * @param {string} log * @returns {string} Resource name string. */ - organizationLogPath(organization:string,log:string) { + organizationLogPath(organization: string, log: string) { return this.pathTemplates.organizationLogPathTemplate.render({ organization: organization, log: log, @@ -4630,7 +5651,9 @@ export class ConfigServiceV2Client { * @returns {string} A string representing the organization. */ matchOrganizationFromOrganizationLogName(organizationLogName: string) { - return this.pathTemplates.organizationLogPathTemplate.match(organizationLogName).organization; + return this.pathTemplates.organizationLogPathTemplate.match( + organizationLogName, + ).organization; } /** @@ -4641,7 +5664,9 @@ export class ConfigServiceV2Client { * @returns {string} A string representing the log. */ matchLogFromOrganizationLogName(organizationLogName: string) { - return this.pathTemplates.organizationLogPathTemplate.match(organizationLogName).log; + return this.pathTemplates.organizationLogPathTemplate.match( + organizationLogName, + ).log; } /** @@ -4650,7 +5675,7 @@ export class ConfigServiceV2Client { * @param {string} organization * @returns {string} Resource name string. */ - organizationSettingsPath(organization:string) { + organizationSettingsPath(organization: string) { return this.pathTemplates.organizationSettingsPathTemplate.render({ organization: organization, }); @@ -4663,8 +5688,12 @@ export class ConfigServiceV2Client { * A fully-qualified path representing organization_settings resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationSettingsName(organizationSettingsName: string) { - return this.pathTemplates.organizationSettingsPathTemplate.match(organizationSettingsName).organization; + matchOrganizationFromOrganizationSettingsName( + organizationSettingsName: string, + ) { + return this.pathTemplates.organizationSettingsPathTemplate.match( + organizationSettingsName, + ).organization; } /** @@ -4674,7 +5703,7 @@ export class ConfigServiceV2Client { * @param {string} sink * @returns {string} Resource name string. */ - organizationSinkPath(organization:string,sink:string) { + organizationSinkPath(organization: string, sink: string) { return this.pathTemplates.organizationSinkPathTemplate.render({ organization: organization, sink: sink, @@ -4689,7 +5718,9 @@ export class ConfigServiceV2Client { * @returns {string} A string representing the organization. */ matchOrganizationFromOrganizationSinkName(organizationSinkName: string) { - return this.pathTemplates.organizationSinkPathTemplate.match(organizationSinkName).organization; + return this.pathTemplates.organizationSinkPathTemplate.match( + organizationSinkName, + ).organization; } /** @@ -4700,7 +5731,9 @@ export class ConfigServiceV2Client { * @returns {string} A string representing the sink. */ matchSinkFromOrganizationSinkName(organizationSinkName: string) { - return this.pathTemplates.organizationSinkPathTemplate.match(organizationSinkName).sink; + return this.pathTemplates.organizationSinkPathTemplate.match( + organizationSinkName, + ).sink; } /** @@ -4709,7 +5742,7 @@ export class ConfigServiceV2Client { * @param {string} project * @returns {string} Resource name string. */ - projectPath(project:string) { + projectPath(project: string) { return this.pathTemplates.projectPathTemplate.render({ project: project, }); @@ -4732,7 +5765,7 @@ export class ConfigServiceV2Client { * @param {string} project * @returns {string} Resource name string. */ - projectCmekSettingsPath(project:string) { + projectCmekSettingsPath(project: string) { return this.pathTemplates.projectCmekSettingsPathTemplate.render({ project: project, }); @@ -4746,7 +5779,9 @@ export class ConfigServiceV2Client { * @returns {string} A string representing the project. */ matchProjectFromProjectCmekSettingsName(projectCmekSettingsName: string) { - return this.pathTemplates.projectCmekSettingsPathTemplate.match(projectCmekSettingsName).project; + return this.pathTemplates.projectCmekSettingsPathTemplate.match( + projectCmekSettingsName, + ).project; } /** @@ -4756,7 +5791,7 @@ export class ConfigServiceV2Client { * @param {string} exclusion * @returns {string} Resource name string. */ - projectExclusionPath(project:string,exclusion:string) { + projectExclusionPath(project: string, exclusion: string) { return this.pathTemplates.projectExclusionPathTemplate.render({ project: project, exclusion: exclusion, @@ -4771,7 +5806,9 @@ export class ConfigServiceV2Client { * @returns {string} A string representing the project. */ matchProjectFromProjectExclusionName(projectExclusionName: string) { - return this.pathTemplates.projectExclusionPathTemplate.match(projectExclusionName).project; + return this.pathTemplates.projectExclusionPathTemplate.match( + projectExclusionName, + ).project; } /** @@ -4782,7 +5819,9 @@ export class ConfigServiceV2Client { * @returns {string} A string representing the exclusion. */ matchExclusionFromProjectExclusionName(projectExclusionName: string) { - return this.pathTemplates.projectExclusionPathTemplate.match(projectExclusionName).exclusion; + return this.pathTemplates.projectExclusionPathTemplate.match( + projectExclusionName, + ).exclusion; } /** @@ -4793,7 +5832,7 @@ export class ConfigServiceV2Client { * @param {string} bucket * @returns {string} Resource name string. */ - projectLocationBucketPath(project:string,location:string,bucket:string) { + projectLocationBucketPath(project: string, location: string, bucket: string) { return this.pathTemplates.projectLocationBucketPathTemplate.render({ project: project, location: location, @@ -4809,7 +5848,9 @@ export class ConfigServiceV2Client { * @returns {string} A string representing the project. */ matchProjectFromProjectLocationBucketName(projectLocationBucketName: string) { - return this.pathTemplates.projectLocationBucketPathTemplate.match(projectLocationBucketName).project; + return this.pathTemplates.projectLocationBucketPathTemplate.match( + projectLocationBucketName, + ).project; } /** @@ -4819,8 +5860,12 @@ export class ConfigServiceV2Client { * A fully-qualified path representing project_location_bucket resource. * @returns {string} A string representing the location. */ - matchLocationFromProjectLocationBucketName(projectLocationBucketName: string) { - return this.pathTemplates.projectLocationBucketPathTemplate.match(projectLocationBucketName).location; + matchLocationFromProjectLocationBucketName( + projectLocationBucketName: string, + ) { + return this.pathTemplates.projectLocationBucketPathTemplate.match( + projectLocationBucketName, + ).location; } /** @@ -4831,7 +5876,9 @@ export class ConfigServiceV2Client { * @returns {string} A string representing the bucket. */ matchBucketFromProjectLocationBucketName(projectLocationBucketName: string) { - return this.pathTemplates.projectLocationBucketPathTemplate.match(projectLocationBucketName).bucket; + return this.pathTemplates.projectLocationBucketPathTemplate.match( + projectLocationBucketName, + ).bucket; } /** @@ -4843,7 +5890,12 @@ export class ConfigServiceV2Client { * @param {string} view * @returns {string} Resource name string. */ - projectLocationBucketViewPath(project:string,location:string,bucket:string,view:string) { + projectLocationBucketViewPath( + project: string, + location: string, + bucket: string, + view: string, + ) { return this.pathTemplates.projectLocationBucketViewPathTemplate.render({ project: project, location: location, @@ -4859,8 +5911,12 @@ export class ConfigServiceV2Client { * A fully-qualified path representing project_location_bucket_view resource. * @returns {string} A string representing the project. */ - matchProjectFromProjectLocationBucketViewName(projectLocationBucketViewName: string) { - return this.pathTemplates.projectLocationBucketViewPathTemplate.match(projectLocationBucketViewName).project; + matchProjectFromProjectLocationBucketViewName( + projectLocationBucketViewName: string, + ) { + return this.pathTemplates.projectLocationBucketViewPathTemplate.match( + projectLocationBucketViewName, + ).project; } /** @@ -4870,8 +5926,12 @@ export class ConfigServiceV2Client { * A fully-qualified path representing project_location_bucket_view resource. * @returns {string} A string representing the location. */ - matchLocationFromProjectLocationBucketViewName(projectLocationBucketViewName: string) { - return this.pathTemplates.projectLocationBucketViewPathTemplate.match(projectLocationBucketViewName).location; + matchLocationFromProjectLocationBucketViewName( + projectLocationBucketViewName: string, + ) { + return this.pathTemplates.projectLocationBucketViewPathTemplate.match( + projectLocationBucketViewName, + ).location; } /** @@ -4881,8 +5941,12 @@ export class ConfigServiceV2Client { * A fully-qualified path representing project_location_bucket_view resource. * @returns {string} A string representing the bucket. */ - matchBucketFromProjectLocationBucketViewName(projectLocationBucketViewName: string) { - return this.pathTemplates.projectLocationBucketViewPathTemplate.match(projectLocationBucketViewName).bucket; + matchBucketFromProjectLocationBucketViewName( + projectLocationBucketViewName: string, + ) { + return this.pathTemplates.projectLocationBucketViewPathTemplate.match( + projectLocationBucketViewName, + ).bucket; } /** @@ -4892,8 +5956,12 @@ export class ConfigServiceV2Client { * A fully-qualified path representing project_location_bucket_view resource. * @returns {string} A string representing the view. */ - matchViewFromProjectLocationBucketViewName(projectLocationBucketViewName: string) { - return this.pathTemplates.projectLocationBucketViewPathTemplate.match(projectLocationBucketViewName).view; + matchViewFromProjectLocationBucketViewName( + projectLocationBucketViewName: string, + ) { + return this.pathTemplates.projectLocationBucketViewPathTemplate.match( + projectLocationBucketViewName, + ).view; } /** @@ -4903,7 +5971,7 @@ export class ConfigServiceV2Client { * @param {string} log * @returns {string} Resource name string. */ - projectLogPath(project:string,log:string) { + projectLogPath(project: string, log: string) { return this.pathTemplates.projectLogPathTemplate.render({ project: project, log: log, @@ -4918,7 +5986,8 @@ export class ConfigServiceV2Client { * @returns {string} A string representing the project. */ matchProjectFromProjectLogName(projectLogName: string) { - return this.pathTemplates.projectLogPathTemplate.match(projectLogName).project; + return this.pathTemplates.projectLogPathTemplate.match(projectLogName) + .project; } /** @@ -4938,7 +6007,7 @@ export class ConfigServiceV2Client { * @param {string} project * @returns {string} Resource name string. */ - projectSettingsPath(project:string) { + projectSettingsPath(project: string) { return this.pathTemplates.projectSettingsPathTemplate.render({ project: project, }); @@ -4952,7 +6021,9 @@ export class ConfigServiceV2Client { * @returns {string} A string representing the project. */ matchProjectFromProjectSettingsName(projectSettingsName: string) { - return this.pathTemplates.projectSettingsPathTemplate.match(projectSettingsName).project; + return this.pathTemplates.projectSettingsPathTemplate.match( + projectSettingsName, + ).project; } /** @@ -4962,7 +6033,7 @@ export class ConfigServiceV2Client { * @param {string} sink * @returns {string} Resource name string. */ - projectSinkPath(project:string,sink:string) { + projectSinkPath(project: string, sink: string) { return this.pathTemplates.projectSinkPathTemplate.render({ project: project, sink: sink, @@ -4977,7 +6048,8 @@ export class ConfigServiceV2Client { * @returns {string} A string representing the project. */ matchProjectFromProjectSinkName(projectSinkName: string) { - return this.pathTemplates.projectSinkPathTemplate.match(projectSinkName).project; + return this.pathTemplates.projectSinkPathTemplate.match(projectSinkName) + .project; } /** @@ -4988,7 +6060,8 @@ export class ConfigServiceV2Client { * @returns {string} A string representing the sink. */ matchSinkFromProjectSinkName(projectSinkName: string) { - return this.pathTemplates.projectSinkPathTemplate.match(projectSinkName).sink; + return this.pathTemplates.projectSinkPathTemplate.match(projectSinkName) + .sink; } /** @@ -4999,7 +6072,7 @@ export class ConfigServiceV2Client { */ close(): Promise { if (this.configServiceV2Stub && !this._terminated) { - return this.configServiceV2Stub.then(stub => { + return this.configServiceV2Stub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -5008,4 +6081,4 @@ export class ConfigServiceV2Client { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/core/generator/gapic-generator-typescript/baselines/logging/src/v2/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/logging/src/v2/index.ts.baseline index aa0593f3ee79..2aca5a517ff1 100644 --- a/core/generator/gapic-generator-typescript/baselines/logging/src/v2/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/logging/src/v2/index.ts.baseline @@ -16,6 +16,6 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -export {ConfigServiceV2Client} from './config_service_v2_client'; -export {LoggingServiceV2Client} from './logging_service_v2_client'; -export {MetricsServiceV2Client} from './metrics_service_v2_client'; +export { ConfigServiceV2Client } from './config_service_v2_client'; +export { LoggingServiceV2Client } from './logging_service_v2_client'; +export { MetricsServiceV2Client } from './metrics_service_v2_client'; diff --git a/core/generator/gapic-generator-typescript/baselines/logging/src/v2/logging_service_v2_client.ts.baseline b/core/generator/gapic-generator-typescript/baselines/logging/src/v2/logging_service_v2_client.ts.baseline index 1931a4643857..4702c571be08 100644 --- a/core/generator/gapic-generator-typescript/baselines/logging/src/v2/logging_service_v2_client.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/logging/src/v2/logging_service_v2_client.ts.baseline @@ -18,11 +18,18 @@ /* global window */ import type * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions, PaginationCallback, GaxCall} from 'google-gax'; -import {Transform, PassThrough} from 'stream'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + PaginationCallback, + GaxCall, +} from 'google-gax'; +import { Transform, PassThrough } from 'stream'; import * as protos from '../../protos/protos'; import jsonProtos = require('../../protos/protos.json'); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; /** * Client JSON configuration object, loaded from @@ -44,7 +51,7 @@ export class LoggingServiceV2Client { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('logging'); @@ -57,9 +64,9 @@ export class LoggingServiceV2Client { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; - loggingServiceV2Stub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; + loggingServiceV2Stub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of LoggingServiceV2Client. @@ -100,21 +107,42 @@ export class LoggingServiceV2Client { * const client = new LoggingServiceV2Client({fallback: true}, gax); * ``` */ - constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { // Ensure that options include all the required fields. const staticMembers = this.constructor as typeof LoggingServiceV2Client; - if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { - throw new Error('Please set either universe_domain or universeDomain, but not both.'); + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); } - const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; - this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; this._servicePath = 'logging.' + this._universeDomain; - const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; - const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. if (servicePath !== this._servicePath && !('scopes' in opts)) { @@ -136,7 +164,7 @@ export class LoggingServiceV2Client { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; @@ -150,10 +178,7 @@ export class LoggingServiceV2Client { } // Determine the client header string. - const clientHeader = [ - `gax/${this._gaxModule.version}`, - `gapic/${version}`, - ]; + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/${process.versions.node}`); } else { @@ -175,94 +200,97 @@ export class LoggingServiceV2Client { // Create useful helper objects for these. this.pathTemplates = { billingAccountCmekSettingsPathTemplate: new this._gaxModule.PathTemplate( - 'billingAccounts/{billing_account}/cmekSettings' + 'billingAccounts/{billing_account}/cmekSettings', ), billingAccountExclusionPathTemplate: new this._gaxModule.PathTemplate( - 'billingAccounts/{billing_account}/exclusions/{exclusion}' - ), - billingAccountLocationBucketPathTemplate: new this._gaxModule.PathTemplate( - 'billingAccounts/{billing_account}/locations/{location}/buckets/{bucket}' - ), - billingAccountLocationBucketViewPathTemplate: new this._gaxModule.PathTemplate( - 'billingAccounts/{billing_account}/locations/{location}/buckets/{bucket}/views/{view}' + 'billingAccounts/{billing_account}/exclusions/{exclusion}', ), + billingAccountLocationBucketPathTemplate: + new this._gaxModule.PathTemplate( + 'billingAccounts/{billing_account}/locations/{location}/buckets/{bucket}', + ), + billingAccountLocationBucketViewPathTemplate: + new this._gaxModule.PathTemplate( + 'billingAccounts/{billing_account}/locations/{location}/buckets/{bucket}/views/{view}', + ), billingAccountLogPathTemplate: new this._gaxModule.PathTemplate( - 'billingAccounts/{billing_account}/logs/{log}' + 'billingAccounts/{billing_account}/logs/{log}', ), billingAccountSettingsPathTemplate: new this._gaxModule.PathTemplate( - 'billingAccounts/{billing_account}/settings' + 'billingAccounts/{billing_account}/settings', ), billingAccountSinkPathTemplate: new this._gaxModule.PathTemplate( - 'billingAccounts/{billing_account}/sinks/{sink}' + 'billingAccounts/{billing_account}/sinks/{sink}', ), folderCmekSettingsPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/cmekSettings' + 'folders/{folder}/cmekSettings', ), folderExclusionPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/exclusions/{exclusion}' + 'folders/{folder}/exclusions/{exclusion}', ), folderLocationBucketPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/locations/{location}/buckets/{bucket}' + 'folders/{folder}/locations/{location}/buckets/{bucket}', ), folderLocationBucketViewPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/locations/{location}/buckets/{bucket}/views/{view}' + 'folders/{folder}/locations/{location}/buckets/{bucket}/views/{view}', ), folderLogPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/logs/{log}' + 'folders/{folder}/logs/{log}', ), folderSettingsPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/settings' + 'folders/{folder}/settings', ), folderSinkPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/sinks/{sink}' + 'folders/{folder}/sinks/{sink}', ), logMetricPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/metrics/{metric}' + 'projects/{project}/metrics/{metric}', ), organizationCmekSettingsPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/cmekSettings' + 'organizations/{organization}/cmekSettings', ), organizationExclusionPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/exclusions/{exclusion}' + 'organizations/{organization}/exclusions/{exclusion}', ), organizationLocationBucketPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/locations/{location}/buckets/{bucket}' - ), - organizationLocationBucketViewPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/locations/{location}/buckets/{bucket}/views/{view}' + 'organizations/{organization}/locations/{location}/buckets/{bucket}', ), + organizationLocationBucketViewPathTemplate: + new this._gaxModule.PathTemplate( + 'organizations/{organization}/locations/{location}/buckets/{bucket}/views/{view}', + ), organizationLogPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/logs/{log}' + 'organizations/{organization}/logs/{log}', ), organizationSettingsPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/settings' + 'organizations/{organization}/settings', ), organizationSinkPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/sinks/{sink}' + 'organizations/{organization}/sinks/{sink}', ), projectPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}' + 'projects/{project}', ), projectCmekSettingsPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/cmekSettings' + 'projects/{project}/cmekSettings', ), projectExclusionPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/exclusions/{exclusion}' + 'projects/{project}/exclusions/{exclusion}', ), projectLocationBucketPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/buckets/{bucket}' + 'projects/{project}/locations/{location}/buckets/{bucket}', ), projectLocationBucketViewPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/buckets/{bucket}/views/{view}' + 'projects/{project}/locations/{location}/buckets/{bucket}/views/{view}', ), projectLogPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/logs/{log}' + 'projects/{project}/logs/{log}', ), projectSettingsPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/settings' + 'projects/{project}/settings', ), projectSinkPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/sinks/{sink}' + 'projects/{project}/sinks/{sink}', ), }; @@ -270,18 +298,31 @@ export class LoggingServiceV2Client { // (e.g. 50 results at a time, with tokens to get subsequent // pages). Denote the keys used for pagination and results. this.descriptors.page = { - listLogEntries: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'entries'), - listMonitoredResourceDescriptors: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'resourceDescriptors'), - listLogs: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'logNames') + listLogEntries: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'entries', + ), + listMonitoredResourceDescriptors: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'resourceDescriptors', + ), + listLogs: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'logNames', + ), }; // Some of the methods on this service provide streaming responses. // Provide descriptors for these. this.descriptors.stream = { - tailLogEntries: new this._gaxModule.StreamDescriptor(this._gaxModule.StreamType.BIDI_STREAMING, !!opts.fallback, !!opts.gaxServerStreamingRetries) + tailLogEntries: new this._gaxModule.StreamDescriptor( + this._gaxModule.StreamType.BIDI_STREAMING, + !!opts.fallback, + !!opts.gaxServerStreamingRetries, + ), }; const protoFilesRoot = this._gaxModule.protobufFromJSON(jsonProtos); @@ -291,19 +332,22 @@ export class LoggingServiceV2Client { this.descriptors.batching = { writeLogEntries: new this._gaxModule.BundleDescriptor( 'entries', - ['log_name','resource','labels'], + ['log_name', 'resource', 'labels'], null, this._gaxModule.GrpcClient.createByteLengthFunction( // eslint-disable-next-line @typescript-eslint/no-explicit-any - protoFilesRoot.lookupType('google.logging.v2.LogEntry') as any - ) + protoFilesRoot.lookupType('google.logging.v2.LogEntry') as any, + ), ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.logging.v2.LoggingServiceV2', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.logging.v2.LoggingServiceV2', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + { 'x-goog-api-client': clientHeader.join(' ') }, + ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -334,35 +378,52 @@ export class LoggingServiceV2Client { // Put together the "service stub" for // google.logging.v2.LoggingServiceV2. this.loggingServiceV2Stub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.logging.v2.LoggingServiceV2') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.logging.v2.LoggingServiceV2', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.logging.v2.LoggingServiceV2, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts, + this._providedCustomServicePath, + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const loggingServiceV2StubMethods = - ['deleteLog', 'writeLogEntries', 'listLogEntries', 'listMonitoredResourceDescriptors', 'listLogs', 'tailLogEntries']; + const loggingServiceV2StubMethods = [ + 'deleteLog', + 'writeLogEntries', + 'listLogEntries', + 'listMonitoredResourceDescriptors', + 'listLogs', + 'tailLogEntries', + ]; for (const methodName of loggingServiceV2StubMethods) { const callPromise = this.loggingServiceV2Stub.then( - stub => (...args: Array<{}>) => { - if (this._terminated) { - if (methodName in this.descriptors.stream) { - const stream = new PassThrough({objectMode: true}); - setImmediate(() => { - stream.emit('error', new this._gaxModule.GoogleError('The client has already been closed.')); - }); - return stream; + (stub) => + (...args: Array<{}>) => { + if (this._terminated) { + if (methodName in this.descriptors.stream) { + const stream = new PassThrough({ objectMode: true }); + setImmediate(() => { + stream.emit( + 'error', + new this._gaxModule.GoogleError( + 'The client has already been closed.', + ), + ); + }); + return stream; + } + return Promise.reject('The client has already been closed.'); } - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error|null|undefined) => () => { + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { throw err; - }); + }, + ); const descriptor = this.descriptors.page[methodName] || @@ -373,7 +434,7 @@ export class LoggingServiceV2Client { callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -388,8 +449,14 @@ export class LoggingServiceV2Client { * @returns {string} The DNS address for this service. */ static get servicePath() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'logging.googleapis.com'; } @@ -400,8 +467,14 @@ export class LoggingServiceV2Client { * @returns {string} The DNS address for this service. */ static get apiEndpoint() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'logging.googleapis.com'; } @@ -437,7 +510,7 @@ export class LoggingServiceV2Client { 'https://www.googleapis.com/auth/cloud-platform.read-only', 'https://www.googleapis.com/auth/logging.admin', 'https://www.googleapis.com/auth/logging.read', - 'https://www.googleapis.com/auth/logging.write' + 'https://www.googleapis.com/auth/logging.write', ]; } @@ -447,8 +520,9 @@ export class LoggingServiceV2Client { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId(callback?: Callback): - Promise|void { + getProjectId( + callback?: Callback, + ): Promise | void { if (callback) { this.auth.getProjectId(callback); return; @@ -459,414 +533,491 @@ export class LoggingServiceV2Client { // ------------------- // -- Service calls -- // ------------------- -/** - * Deletes all the log entries in a log for the _Default Log Bucket. The log - * reappears if it receives new entries. Log entries written shortly before - * the delete operation might not be deleted. Entries received after the - * delete operation with a timestamp before the operation will be deleted. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.logName - * Required. The resource name of the log to delete: - * - * * `projects/[PROJECT_ID]/logs/[LOG_ID]` - * * `organizations/[ORGANIZATION_ID]/logs/[LOG_ID]` - * * `billingAccounts/[BILLING_ACCOUNT_ID]/logs/[LOG_ID]` - * * `folders/[FOLDER_ID]/logs/[LOG_ID]` - * - * `[LOG_ID]` must be URL-encoded. For example, - * `"projects/my-project-id/logs/syslog"`, - * `"organizations/123/logs/cloudaudit.googleapis.com%2Factivity"`. - * - * For more information about log names, see - * {@link protos.google.logging.v2.LogEntry|LogEntry}. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/logging_service_v2.delete_log.js - * region_tag:logging_v2_generated_LoggingServiceV2_DeleteLog_async - */ + /** + * Deletes all the log entries in a log for the _Default Log Bucket. The log + * reappears if it receives new entries. Log entries written shortly before + * the delete operation might not be deleted. Entries received after the + * delete operation with a timestamp before the operation will be deleted. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.logName + * Required. The resource name of the log to delete: + * + * * `projects/[PROJECT_ID]/logs/[LOG_ID]` + * * `organizations/[ORGANIZATION_ID]/logs/[LOG_ID]` + * * `billingAccounts/[BILLING_ACCOUNT_ID]/logs/[LOG_ID]` + * * `folders/[FOLDER_ID]/logs/[LOG_ID]` + * + * `[LOG_ID]` must be URL-encoded. For example, + * `"projects/my-project-id/logs/syslog"`, + * `"organizations/123/logs/cloudaudit.googleapis.com%2Factivity"`. + * + * For more information about log names, see + * {@link protos.google.logging.v2.LogEntry|LogEntry}. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/logging_service_v2.delete_log.js + * region_tag:logging_v2_generated_LoggingServiceV2_DeleteLog_async + */ deleteLog( - request?: protos.google.logging.v2.IDeleteLogRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.logging.v2.IDeleteLogRequest|undefined, {}|undefined - ]>; + request?: protos.google.logging.v2.IDeleteLogRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.logging.v2.IDeleteLogRequest | undefined, + {} | undefined, + ] + >; deleteLog( - request: protos.google.logging.v2.IDeleteLogRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.logging.v2.IDeleteLogRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.logging.v2.IDeleteLogRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.logging.v2.IDeleteLogRequest | null | undefined, + {} | null | undefined + >, + ): void; deleteLog( - request: protos.google.logging.v2.IDeleteLogRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.logging.v2.IDeleteLogRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.logging.v2.IDeleteLogRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.logging.v2.IDeleteLogRequest | null | undefined, + {} | null | undefined + >, + ): void; deleteLog( - request?: protos.google.logging.v2.IDeleteLogRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.protobuf.IEmpty, - protos.google.logging.v2.IDeleteLogRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.logging.v2.IDeleteLogRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.logging.v2.IDeleteLogRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.logging.v2.IDeleteLogRequest|undefined, {}|undefined - ]>|void { + protos.google.logging.v2.IDeleteLogRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + protos.google.logging.v2.IDeleteLogRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.logging.v2.IDeleteLogRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'log_name': request.logName ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + log_name: request.logName ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('deleteLog request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.logging.v2.IDeleteLogRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + protos.google.logging.v2.IDeleteLogRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteLog response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.deleteLog(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.logging.v2.IDeleteLogRequest|undefined, - {}|undefined - ]) => { - this._log.info('deleteLog response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteLog(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.logging.v2.IDeleteLogRequest | undefined, + {} | undefined, + ]) => { + this._log.info('deleteLog response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Writes log entries to Logging. This API method is the - * only way to send log entries to Logging. This method - * is used, directly or indirectly, by the Logging agent - * (fluentd) and all logging libraries configured to use Logging. - * A single request may contain log entries for a maximum of 1000 - * different resources (projects, organizations, billing accounts or - * folders) - * - * @param {Object} request - * The request object that will be sent. - * @param {string} [request.logName] - * Optional. A default log resource name that is assigned to all log entries - * in `entries` that do not specify a value for `log_name`: - * - * * `projects/[PROJECT_ID]/logs/[LOG_ID]` - * * `organizations/[ORGANIZATION_ID]/logs/[LOG_ID]` - * * `billingAccounts/[BILLING_ACCOUNT_ID]/logs/[LOG_ID]` - * * `folders/[FOLDER_ID]/logs/[LOG_ID]` - * - * `[LOG_ID]` must be URL-encoded. For example: - * - * "projects/my-project-id/logs/syslog" - * "organizations/123/logs/cloudaudit.googleapis.com%2Factivity" - * - * The permission `logging.logEntries.create` is needed on each project, - * organization, billing account, or folder that is receiving new log - * entries, whether the resource is specified in `logName` or in an - * individual log entry. - * @param {google.api.MonitoredResource} [request.resource] - * Optional. A default monitored resource object that is assigned to all log - * entries in `entries` that do not specify a value for `resource`. Example: - * - * { "type": "gce_instance", - * "labels": { - * "zone": "us-central1-a", "instance_id": "00000000000000000000" }} - * - * See {@link protos.google.logging.v2.LogEntry|LogEntry}. - * @param {number[]} [request.labels] - * Optional. Default labels that are added to the `labels` field of all log - * entries in `entries`. If a log entry already has a label with the same key - * as a label in this parameter, then the log entry's label is not changed. - * See {@link protos.google.logging.v2.LogEntry|LogEntry}. - * @param {number[]} request.entries - * Required. The log entries to send to Logging. The order of log - * entries in this list does not matter. Values supplied in this method's - * `log_name`, `resource`, and `labels` fields are copied into those log - * entries in this list that do not include values for their corresponding - * fields. For more information, see the - * {@link protos.google.logging.v2.LogEntry|LogEntry} type. - * - * If the `timestamp` or `insert_id` fields are missing in log entries, then - * this method supplies the current time or a unique identifier, respectively. - * The supplied values are chosen so that, among the log entries that did not - * supply their own values, the entries earlier in the list will sort before - * the entries later in the list. See the `entries.list` method. - * - * Log entries with timestamps that are more than the - * [logs retention period](https://cloud.google.com/logging/quotas) in - * the past or more than 24 hours in the future will not be available when - * calling `entries.list`. However, those log entries can still be [exported - * with - * LogSinks](https://cloud.google.com/logging/docs/api/tasks/exporting-logs). - * - * To improve throughput and to avoid exceeding the - * [quota limit](https://cloud.google.com/logging/quotas) for calls to - * `entries.write`, you should try to include several log entries in this - * list, rather than calling this method for each individual log entry. - * @param {boolean} [request.partialSuccess] - * Optional. Whether valid entries should be written even if some other - * entries fail due to INVALID_ARGUMENT or PERMISSION_DENIED errors. If any - * entry is not written, then the response status is the error associated - * with one of the failed entries and the response includes error details - * keyed by the entries' zero-based index in the `entries.write` method. - * @param {boolean} [request.dryRun] - * Optional. If true, the request should expect normal response, but the - * entries won't be persisted nor exported. Useful for checking whether the - * logging API endpoints are working properly before sending valuable data. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.logging.v2.WriteLogEntriesResponse|WriteLogEntriesResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/logging_service_v2.write_log_entries.js - * region_tag:logging_v2_generated_LoggingServiceV2_WriteLogEntries_async - */ + /** + * Writes log entries to Logging. This API method is the + * only way to send log entries to Logging. This method + * is used, directly or indirectly, by the Logging agent + * (fluentd) and all logging libraries configured to use Logging. + * A single request may contain log entries for a maximum of 1000 + * different resources (projects, organizations, billing accounts or + * folders) + * + * @param {Object} request + * The request object that will be sent. + * @param {string} [request.logName] + * Optional. A default log resource name that is assigned to all log entries + * in `entries` that do not specify a value for `log_name`: + * + * * `projects/[PROJECT_ID]/logs/[LOG_ID]` + * * `organizations/[ORGANIZATION_ID]/logs/[LOG_ID]` + * * `billingAccounts/[BILLING_ACCOUNT_ID]/logs/[LOG_ID]` + * * `folders/[FOLDER_ID]/logs/[LOG_ID]` + * + * `[LOG_ID]` must be URL-encoded. For example: + * + * "projects/my-project-id/logs/syslog" + * "organizations/123/logs/cloudaudit.googleapis.com%2Factivity" + * + * The permission `logging.logEntries.create` is needed on each project, + * organization, billing account, or folder that is receiving new log + * entries, whether the resource is specified in `logName` or in an + * individual log entry. + * @param {google.api.MonitoredResource} [request.resource] + * Optional. A default monitored resource object that is assigned to all log + * entries in `entries` that do not specify a value for `resource`. Example: + * + * { "type": "gce_instance", + * "labels": { + * "zone": "us-central1-a", "instance_id": "00000000000000000000" }} + * + * See {@link protos.google.logging.v2.LogEntry|LogEntry}. + * @param {number[]} [request.labels] + * Optional. Default labels that are added to the `labels` field of all log + * entries in `entries`. If a log entry already has a label with the same key + * as a label in this parameter, then the log entry's label is not changed. + * See {@link protos.google.logging.v2.LogEntry|LogEntry}. + * @param {number[]} request.entries + * Required. The log entries to send to Logging. The order of log + * entries in this list does not matter. Values supplied in this method's + * `log_name`, `resource`, and `labels` fields are copied into those log + * entries in this list that do not include values for their corresponding + * fields. For more information, see the + * {@link protos.google.logging.v2.LogEntry|LogEntry} type. + * + * If the `timestamp` or `insert_id` fields are missing in log entries, then + * this method supplies the current time or a unique identifier, respectively. + * The supplied values are chosen so that, among the log entries that did not + * supply their own values, the entries earlier in the list will sort before + * the entries later in the list. See the `entries.list` method. + * + * Log entries with timestamps that are more than the + * [logs retention period](https://cloud.google.com/logging/quotas) in + * the past or more than 24 hours in the future will not be available when + * calling `entries.list`. However, those log entries can still be [exported + * with + * LogSinks](https://cloud.google.com/logging/docs/api/tasks/exporting-logs). + * + * To improve throughput and to avoid exceeding the + * [quota limit](https://cloud.google.com/logging/quotas) for calls to + * `entries.write`, you should try to include several log entries in this + * list, rather than calling this method for each individual log entry. + * @param {boolean} [request.partialSuccess] + * Optional. Whether valid entries should be written even if some other + * entries fail due to INVALID_ARGUMENT or PERMISSION_DENIED errors. If any + * entry is not written, then the response status is the error associated + * with one of the failed entries and the response includes error details + * keyed by the entries' zero-based index in the `entries.write` method. + * @param {boolean} [request.dryRun] + * Optional. If true, the request should expect normal response, but the + * entries won't be persisted nor exported. Useful for checking whether the + * logging API endpoints are working properly before sending valuable data. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.logging.v2.WriteLogEntriesResponse|WriteLogEntriesResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/logging_service_v2.write_log_entries.js + * region_tag:logging_v2_generated_LoggingServiceV2_WriteLogEntries_async + */ writeLogEntries( - request?: protos.google.logging.v2.IWriteLogEntriesRequest, - options?: CallOptions): - Promise<[ - protos.google.logging.v2.IWriteLogEntriesResponse, - protos.google.logging.v2.IWriteLogEntriesRequest|undefined, {}|undefined - ]>; + request?: protos.google.logging.v2.IWriteLogEntriesRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.logging.v2.IWriteLogEntriesResponse, + protos.google.logging.v2.IWriteLogEntriesRequest | undefined, + {} | undefined, + ] + >; writeLogEntries( - request: protos.google.logging.v2.IWriteLogEntriesRequest, - options: CallOptions, - callback: Callback< - protos.google.logging.v2.IWriteLogEntriesResponse, - protos.google.logging.v2.IWriteLogEntriesRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.logging.v2.IWriteLogEntriesRequest, + options: CallOptions, + callback: Callback< + protos.google.logging.v2.IWriteLogEntriesResponse, + protos.google.logging.v2.IWriteLogEntriesRequest | null | undefined, + {} | null | undefined + >, + ): void; writeLogEntries( - request: protos.google.logging.v2.IWriteLogEntriesRequest, - callback: Callback< - protos.google.logging.v2.IWriteLogEntriesResponse, - protos.google.logging.v2.IWriteLogEntriesRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.logging.v2.IWriteLogEntriesRequest, + callback: Callback< + protos.google.logging.v2.IWriteLogEntriesResponse, + protos.google.logging.v2.IWriteLogEntriesRequest | null | undefined, + {} | null | undefined + >, + ): void; writeLogEntries( - request?: protos.google.logging.v2.IWriteLogEntriesRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.logging.v2.IWriteLogEntriesResponse, - protos.google.logging.v2.IWriteLogEntriesRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.logging.v2.IWriteLogEntriesRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.logging.v2.IWriteLogEntriesResponse, - protos.google.logging.v2.IWriteLogEntriesRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.logging.v2.IWriteLogEntriesResponse, - protos.google.logging.v2.IWriteLogEntriesRequest|undefined, {}|undefined - ]>|void { + protos.google.logging.v2.IWriteLogEntriesRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.logging.v2.IWriteLogEntriesResponse, + protos.google.logging.v2.IWriteLogEntriesRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.logging.v2.IWriteLogEntriesResponse, + protos.google.logging.v2.IWriteLogEntriesRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('writeLogEntries request %j', request); - const wrappedCallback: Callback< - protos.google.logging.v2.IWriteLogEntriesResponse, - protos.google.logging.v2.IWriteLogEntriesRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.logging.v2.IWriteLogEntriesResponse, + protos.google.logging.v2.IWriteLogEntriesRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('writeLogEntries response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.writeLogEntries(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.logging.v2.IWriteLogEntriesResponse, - protos.google.logging.v2.IWriteLogEntriesRequest|undefined, - {}|undefined - ]) => { - this._log.info('writeLogEntries response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .writeLogEntries(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.logging.v2.IWriteLogEntriesResponse, + protos.google.logging.v2.IWriteLogEntriesRequest | undefined, + {} | undefined, + ]) => { + this._log.info('writeLogEntries response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Streaming read of log entries as they are ingested. Until the stream is - * terminated, it will continue reading logs. - * - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which is both readable and writable. It accepts objects - * representing {@link protos.google.logging.v2.TailLogEntriesRequest|TailLogEntriesRequest} for write() method, and - * will emit objects representing {@link protos.google.logging.v2.TailLogEntriesResponse|TailLogEntriesResponse} on 'data' event asynchronously. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#bi-directional-streaming | documentation } - * for more details and examples. - * @example include:samples/generated/v2/logging_service_v2.tail_log_entries.js - * region_tag:logging_v2_generated_LoggingServiceV2_TailLogEntries_async - */ - tailLogEntries( - options?: CallOptions): - gax.CancellableStream { - this.initialize().catch(err => {throw err}); + /** + * Streaming read of log entries as they are ingested. Until the stream is + * terminated, it will continue reading logs. + * + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which is both readable and writable. It accepts objects + * representing {@link protos.google.logging.v2.TailLogEntriesRequest|TailLogEntriesRequest} for write() method, and + * will emit objects representing {@link protos.google.logging.v2.TailLogEntriesResponse|TailLogEntriesResponse} on 'data' event asynchronously. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#bi-directional-streaming | documentation } + * for more details and examples. + * @example include:samples/generated/v2/logging_service_v2.tail_log_entries.js + * region_tag:logging_v2_generated_LoggingServiceV2_TailLogEntries_async + */ + tailLogEntries(options?: CallOptions): gax.CancellableStream { + this.initialize().catch((err) => { + throw err; + }); this._log.info('tailLogEntries stream %j', options); return this.innerApiCalls.tailLogEntries(null, options); } - /** - * Lists log entries. Use this method to retrieve log entries that originated - * from a project/folder/organization/billing account. For ways to export log - * entries, see [Exporting - * Logs](https://cloud.google.com/logging/docs/export). - * - * @param {Object} request - * The request object that will be sent. - * @param {string[]} request.resourceNames - * Required. Names of one or more parent resources from which to - * retrieve log entries: - * - * * `projects/[PROJECT_ID]` - * * `organizations/[ORGANIZATION_ID]` - * * `billingAccounts/[BILLING_ACCOUNT_ID]` - * * `folders/[FOLDER_ID]` - * - * May alternatively be one or more views: - * - * * `projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]` - * * `organizations/[ORGANIZATION_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]` - * * `billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]` - * * `folders/[FOLDER_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]` - * - * Projects listed in the `project_ids` field are added to this list. - * @param {string} [request.filter] - * Optional. A filter that chooses which log entries to return. See [Advanced - * Logs Queries](https://cloud.google.com/logging/docs/view/advanced-queries). - * Only log entries that match the filter are returned. An empty filter - * matches all log entries in the resources listed in `resource_names`. - * Referencing a parent resource that is not listed in `resource_names` will - * cause the filter to return no results. The maximum length of the filter is - * 20000 characters. - * @param {string} [request.orderBy] - * Optional. How the results should be sorted. Presently, the only permitted - * values are `"timestamp asc"` (default) and `"timestamp desc"`. The first - * option returns entries in order of increasing values of - * `LogEntry.timestamp` (oldest first), and the second option returns entries - * in order of decreasing timestamps (newest first). Entries with equal - * timestamps are returned in order of their `insert_id` values. - * @param {number} [request.pageSize] - * Optional. The maximum number of results to return from this request. Default is 50. - * If the value is negative or exceeds 1000, the request is rejected. The - * presence of `next_page_token` in the response indicates that more results - * might be available. - * @param {string} [request.pageToken] - * Optional. If present, then retrieve the next batch of results from the - * preceding call to this method. `page_token` must be the value of - * `next_page_token` from the previous response. The values of other method - * parameters should be identical to those in the previous call. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.logging.v2.LogEntry|LogEntry}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `listLogEntriesAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Lists log entries. Use this method to retrieve log entries that originated + * from a project/folder/organization/billing account. For ways to export log + * entries, see [Exporting + * Logs](https://cloud.google.com/logging/docs/export). + * + * @param {Object} request + * The request object that will be sent. + * @param {string[]} request.resourceNames + * Required. Names of one or more parent resources from which to + * retrieve log entries: + * + * * `projects/[PROJECT_ID]` + * * `organizations/[ORGANIZATION_ID]` + * * `billingAccounts/[BILLING_ACCOUNT_ID]` + * * `folders/[FOLDER_ID]` + * + * May alternatively be one or more views: + * + * * `projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]` + * * `organizations/[ORGANIZATION_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]` + * * `billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]` + * * `folders/[FOLDER_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]` + * + * Projects listed in the `project_ids` field are added to this list. + * @param {string} [request.filter] + * Optional. A filter that chooses which log entries to return. See [Advanced + * Logs Queries](https://cloud.google.com/logging/docs/view/advanced-queries). + * Only log entries that match the filter are returned. An empty filter + * matches all log entries in the resources listed in `resource_names`. + * Referencing a parent resource that is not listed in `resource_names` will + * cause the filter to return no results. The maximum length of the filter is + * 20000 characters. + * @param {string} [request.orderBy] + * Optional. How the results should be sorted. Presently, the only permitted + * values are `"timestamp asc"` (default) and `"timestamp desc"`. The first + * option returns entries in order of increasing values of + * `LogEntry.timestamp` (oldest first), and the second option returns entries + * in order of decreasing timestamps (newest first). Entries with equal + * timestamps are returned in order of their `insert_id` values. + * @param {number} [request.pageSize] + * Optional. The maximum number of results to return from this request. Default is 50. + * If the value is negative or exceeds 1000, the request is rejected. The + * presence of `next_page_token` in the response indicates that more results + * might be available. + * @param {string} [request.pageToken] + * Optional. If present, then retrieve the next batch of results from the + * preceding call to this method. `page_token` must be the value of + * `next_page_token` from the previous response. The values of other method + * parameters should be identical to those in the previous call. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.logging.v2.LogEntry|LogEntry}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listLogEntriesAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listLogEntries( - request?: protos.google.logging.v2.IListLogEntriesRequest, - options?: CallOptions): - Promise<[ - protos.google.logging.v2.ILogEntry[], - protos.google.logging.v2.IListLogEntriesRequest|null, - protos.google.logging.v2.IListLogEntriesResponse - ]>; + request?: protos.google.logging.v2.IListLogEntriesRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.logging.v2.ILogEntry[], + protos.google.logging.v2.IListLogEntriesRequest | null, + protos.google.logging.v2.IListLogEntriesResponse, + ] + >; listLogEntries( - request: protos.google.logging.v2.IListLogEntriesRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.logging.v2.IListLogEntriesRequest, - protos.google.logging.v2.IListLogEntriesResponse|null|undefined, - protos.google.logging.v2.ILogEntry>): void; + request: protos.google.logging.v2.IListLogEntriesRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.logging.v2.IListLogEntriesRequest, + protos.google.logging.v2.IListLogEntriesResponse | null | undefined, + protos.google.logging.v2.ILogEntry + >, + ): void; listLogEntries( - request: protos.google.logging.v2.IListLogEntriesRequest, - callback: PaginationCallback< - protos.google.logging.v2.IListLogEntriesRequest, - protos.google.logging.v2.IListLogEntriesResponse|null|undefined, - protos.google.logging.v2.ILogEntry>): void; + request: protos.google.logging.v2.IListLogEntriesRequest, + callback: PaginationCallback< + protos.google.logging.v2.IListLogEntriesRequest, + protos.google.logging.v2.IListLogEntriesResponse | null | undefined, + protos.google.logging.v2.ILogEntry + >, + ): void; listLogEntries( - request?: protos.google.logging.v2.IListLogEntriesRequest, - optionsOrCallback?: CallOptions|PaginationCallback< + request?: protos.google.logging.v2.IListLogEntriesRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.logging.v2.IListLogEntriesRequest, - protos.google.logging.v2.IListLogEntriesResponse|null|undefined, - protos.google.logging.v2.ILogEntry>, - callback?: PaginationCallback< - protos.google.logging.v2.IListLogEntriesRequest, - protos.google.logging.v2.IListLogEntriesResponse|null|undefined, - protos.google.logging.v2.ILogEntry>): - Promise<[ - protos.google.logging.v2.ILogEntry[], - protos.google.logging.v2.IListLogEntriesRequest|null, - protos.google.logging.v2.IListLogEntriesResponse - ]>|void { + protos.google.logging.v2.IListLogEntriesResponse | null | undefined, + protos.google.logging.v2.ILogEntry + >, + callback?: PaginationCallback< + protos.google.logging.v2.IListLogEntriesRequest, + protos.google.logging.v2.IListLogEntriesResponse | null | undefined, + protos.google.logging.v2.ILogEntry + >, + ): Promise< + [ + protos.google.logging.v2.ILogEntry[], + protos.google.logging.v2.IListLogEntriesRequest | null, + protos.google.logging.v2.IListLogEntriesResponse, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.logging.v2.IListLogEntriesRequest, - protos.google.logging.v2.IListLogEntriesResponse|null|undefined, - protos.google.logging.v2.ILogEntry>|undefined = callback + this.initialize().catch((err) => { + throw err; + }); + const wrappedCallback: + | PaginationCallback< + protos.google.logging.v2.IListLogEntriesRequest, + protos.google.logging.v2.IListLogEntriesResponse | null | undefined, + protos.google.logging.v2.ILogEntry + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listLogEntries values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -875,249 +1026,281 @@ export class LoggingServiceV2Client { this._log.info('listLogEntries request %j', request); return this.innerApiCalls .listLogEntries(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.logging.v2.ILogEntry[], - protos.google.logging.v2.IListLogEntriesRequest|null, - protos.google.logging.v2.IListLogEntriesResponse - ]) => { - this._log.info('listLogEntries values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.logging.v2.ILogEntry[], + protos.google.logging.v2.IListLogEntriesRequest | null, + protos.google.logging.v2.IListLogEntriesResponse, + ]) => { + this._log.info('listLogEntries values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listLogEntries`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string[]} request.resourceNames - * Required. Names of one or more parent resources from which to - * retrieve log entries: - * - * * `projects/[PROJECT_ID]` - * * `organizations/[ORGANIZATION_ID]` - * * `billingAccounts/[BILLING_ACCOUNT_ID]` - * * `folders/[FOLDER_ID]` - * - * May alternatively be one or more views: - * - * * `projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]` - * * `organizations/[ORGANIZATION_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]` - * * `billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]` - * * `folders/[FOLDER_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]` - * - * Projects listed in the `project_ids` field are added to this list. - * @param {string} [request.filter] - * Optional. A filter that chooses which log entries to return. See [Advanced - * Logs Queries](https://cloud.google.com/logging/docs/view/advanced-queries). - * Only log entries that match the filter are returned. An empty filter - * matches all log entries in the resources listed in `resource_names`. - * Referencing a parent resource that is not listed in `resource_names` will - * cause the filter to return no results. The maximum length of the filter is - * 20000 characters. - * @param {string} [request.orderBy] - * Optional. How the results should be sorted. Presently, the only permitted - * values are `"timestamp asc"` (default) and `"timestamp desc"`. The first - * option returns entries in order of increasing values of - * `LogEntry.timestamp` (oldest first), and the second option returns entries - * in order of decreasing timestamps (newest first). Entries with equal - * timestamps are returned in order of their `insert_id` values. - * @param {number} [request.pageSize] - * Optional. The maximum number of results to return from this request. Default is 50. - * If the value is negative or exceeds 1000, the request is rejected. The - * presence of `next_page_token` in the response indicates that more results - * might be available. - * @param {string} [request.pageToken] - * Optional. If present, then retrieve the next batch of results from the - * preceding call to this method. `page_token` must be the value of - * `next_page_token` from the previous response. The values of other method - * parameters should be identical to those in the previous call. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.logging.v2.LogEntry|LogEntry} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `listLogEntriesAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `listLogEntries`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string[]} request.resourceNames + * Required. Names of one or more parent resources from which to + * retrieve log entries: + * + * * `projects/[PROJECT_ID]` + * * `organizations/[ORGANIZATION_ID]` + * * `billingAccounts/[BILLING_ACCOUNT_ID]` + * * `folders/[FOLDER_ID]` + * + * May alternatively be one or more views: + * + * * `projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]` + * * `organizations/[ORGANIZATION_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]` + * * `billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]` + * * `folders/[FOLDER_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]` + * + * Projects listed in the `project_ids` field are added to this list. + * @param {string} [request.filter] + * Optional. A filter that chooses which log entries to return. See [Advanced + * Logs Queries](https://cloud.google.com/logging/docs/view/advanced-queries). + * Only log entries that match the filter are returned. An empty filter + * matches all log entries in the resources listed in `resource_names`. + * Referencing a parent resource that is not listed in `resource_names` will + * cause the filter to return no results. The maximum length of the filter is + * 20000 characters. + * @param {string} [request.orderBy] + * Optional. How the results should be sorted. Presently, the only permitted + * values are `"timestamp asc"` (default) and `"timestamp desc"`. The first + * option returns entries in order of increasing values of + * `LogEntry.timestamp` (oldest first), and the second option returns entries + * in order of decreasing timestamps (newest first). Entries with equal + * timestamps are returned in order of their `insert_id` values. + * @param {number} [request.pageSize] + * Optional. The maximum number of results to return from this request. Default is 50. + * If the value is negative or exceeds 1000, the request is rejected. The + * presence of `next_page_token` in the response indicates that more results + * might be available. + * @param {string} [request.pageToken] + * Optional. If present, then retrieve the next batch of results from the + * preceding call to this method. `page_token` must be the value of + * `next_page_token` from the previous response. The values of other method + * parameters should be identical to those in the previous call. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.logging.v2.LogEntry|LogEntry} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listLogEntriesAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listLogEntriesStream( - request?: protos.google.logging.v2.IListLogEntriesRequest, - options?: CallOptions): - Transform{ + request?: protos.google.logging.v2.IListLogEntriesRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; const defaultCallSettings = this._defaults['listLogEntries']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listLogEntries stream %j', request); return this.descriptors.page.listLogEntries.createStream( this.innerApiCalls.listLogEntries as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listLogEntries`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {string[]} request.resourceNames - * Required. Names of one or more parent resources from which to - * retrieve log entries: - * - * * `projects/[PROJECT_ID]` - * * `organizations/[ORGANIZATION_ID]` - * * `billingAccounts/[BILLING_ACCOUNT_ID]` - * * `folders/[FOLDER_ID]` - * - * May alternatively be one or more views: - * - * * `projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]` - * * `organizations/[ORGANIZATION_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]` - * * `billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]` - * * `folders/[FOLDER_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]` - * - * Projects listed in the `project_ids` field are added to this list. - * @param {string} [request.filter] - * Optional. A filter that chooses which log entries to return. See [Advanced - * Logs Queries](https://cloud.google.com/logging/docs/view/advanced-queries). - * Only log entries that match the filter are returned. An empty filter - * matches all log entries in the resources listed in `resource_names`. - * Referencing a parent resource that is not listed in `resource_names` will - * cause the filter to return no results. The maximum length of the filter is - * 20000 characters. - * @param {string} [request.orderBy] - * Optional. How the results should be sorted. Presently, the only permitted - * values are `"timestamp asc"` (default) and `"timestamp desc"`. The first - * option returns entries in order of increasing values of - * `LogEntry.timestamp` (oldest first), and the second option returns entries - * in order of decreasing timestamps (newest first). Entries with equal - * timestamps are returned in order of their `insert_id` values. - * @param {number} [request.pageSize] - * Optional. The maximum number of results to return from this request. Default is 50. - * If the value is negative or exceeds 1000, the request is rejected. The - * presence of `next_page_token` in the response indicates that more results - * might be available. - * @param {string} [request.pageToken] - * Optional. If present, then retrieve the next batch of results from the - * preceding call to this method. `page_token` must be the value of - * `next_page_token` from the previous response. The values of other method - * parameters should be identical to those in the previous call. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.logging.v2.LogEntry|LogEntry}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v2/logging_service_v2.list_log_entries.js - * region_tag:logging_v2_generated_LoggingServiceV2_ListLogEntries_async - */ + /** + * Equivalent to `listLogEntries`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string[]} request.resourceNames + * Required. Names of one or more parent resources from which to + * retrieve log entries: + * + * * `projects/[PROJECT_ID]` + * * `organizations/[ORGANIZATION_ID]` + * * `billingAccounts/[BILLING_ACCOUNT_ID]` + * * `folders/[FOLDER_ID]` + * + * May alternatively be one or more views: + * + * * `projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]` + * * `organizations/[ORGANIZATION_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]` + * * `billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]` + * * `folders/[FOLDER_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]` + * + * Projects listed in the `project_ids` field are added to this list. + * @param {string} [request.filter] + * Optional. A filter that chooses which log entries to return. See [Advanced + * Logs Queries](https://cloud.google.com/logging/docs/view/advanced-queries). + * Only log entries that match the filter are returned. An empty filter + * matches all log entries in the resources listed in `resource_names`. + * Referencing a parent resource that is not listed in `resource_names` will + * cause the filter to return no results. The maximum length of the filter is + * 20000 characters. + * @param {string} [request.orderBy] + * Optional. How the results should be sorted. Presently, the only permitted + * values are `"timestamp asc"` (default) and `"timestamp desc"`. The first + * option returns entries in order of increasing values of + * `LogEntry.timestamp` (oldest first), and the second option returns entries + * in order of decreasing timestamps (newest first). Entries with equal + * timestamps are returned in order of their `insert_id` values. + * @param {number} [request.pageSize] + * Optional. The maximum number of results to return from this request. Default is 50. + * If the value is negative or exceeds 1000, the request is rejected. The + * presence of `next_page_token` in the response indicates that more results + * might be available. + * @param {string} [request.pageToken] + * Optional. If present, then retrieve the next batch of results from the + * preceding call to this method. `page_token` must be the value of + * `next_page_token` from the previous response. The values of other method + * parameters should be identical to those in the previous call. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.logging.v2.LogEntry|LogEntry}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v2/logging_service_v2.list_log_entries.js + * region_tag:logging_v2_generated_LoggingServiceV2_ListLogEntries_async + */ listLogEntriesAsync( - request?: protos.google.logging.v2.IListLogEntriesRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.logging.v2.IListLogEntriesRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; const defaultCallSettings = this._defaults['listLogEntries']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listLogEntries iterate %j', request); return this.descriptors.page.listLogEntries.asyncIterate( this.innerApiCalls['listLogEntries'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } - /** - * Lists the descriptors for monitored resource types used by Logging. - * - * @param {Object} request - * The request object that will be sent. - * @param {number} [request.pageSize] - * Optional. The maximum number of results to return from this request. - * Non-positive values are ignored. The presence of `nextPageToken` in the - * response indicates that more results might be available. - * @param {string} [request.pageToken] - * Optional. If present, then retrieve the next batch of results from the - * preceding call to this method. `pageToken` must be the value of - * `nextPageToken` from the previous response. The values of other method - * parameters should be identical to those in the previous call. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.api.MonitoredResourceDescriptor|MonitoredResourceDescriptor}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `listMonitoredResourceDescriptorsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Lists the descriptors for monitored resource types used by Logging. + * + * @param {Object} request + * The request object that will be sent. + * @param {number} [request.pageSize] + * Optional. The maximum number of results to return from this request. + * Non-positive values are ignored. The presence of `nextPageToken` in the + * response indicates that more results might be available. + * @param {string} [request.pageToken] + * Optional. If present, then retrieve the next batch of results from the + * preceding call to this method. `pageToken` must be the value of + * `nextPageToken` from the previous response. The values of other method + * parameters should be identical to those in the previous call. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.api.MonitoredResourceDescriptor|MonitoredResourceDescriptor}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listMonitoredResourceDescriptorsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listMonitoredResourceDescriptors( - request?: protos.google.logging.v2.IListMonitoredResourceDescriptorsRequest, - options?: CallOptions): - Promise<[ - protos.google.api.IMonitoredResourceDescriptor[], - protos.google.logging.v2.IListMonitoredResourceDescriptorsRequest|null, - protos.google.logging.v2.IListMonitoredResourceDescriptorsResponse - ]>; + request?: protos.google.logging.v2.IListMonitoredResourceDescriptorsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.api.IMonitoredResourceDescriptor[], + protos.google.logging.v2.IListMonitoredResourceDescriptorsRequest | null, + protos.google.logging.v2.IListMonitoredResourceDescriptorsResponse, + ] + >; listMonitoredResourceDescriptors( - request: protos.google.logging.v2.IListMonitoredResourceDescriptorsRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.logging.v2.IListMonitoredResourceDescriptorsRequest, - protos.google.logging.v2.IListMonitoredResourceDescriptorsResponse|null|undefined, - protos.google.api.IMonitoredResourceDescriptor>): void; + request: protos.google.logging.v2.IListMonitoredResourceDescriptorsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.logging.v2.IListMonitoredResourceDescriptorsRequest, + | protos.google.logging.v2.IListMonitoredResourceDescriptorsResponse + | null + | undefined, + protos.google.api.IMonitoredResourceDescriptor + >, + ): void; listMonitoredResourceDescriptors( - request: protos.google.logging.v2.IListMonitoredResourceDescriptorsRequest, - callback: PaginationCallback< - protos.google.logging.v2.IListMonitoredResourceDescriptorsRequest, - protos.google.logging.v2.IListMonitoredResourceDescriptorsResponse|null|undefined, - protos.google.api.IMonitoredResourceDescriptor>): void; + request: protos.google.logging.v2.IListMonitoredResourceDescriptorsRequest, + callback: PaginationCallback< + protos.google.logging.v2.IListMonitoredResourceDescriptorsRequest, + | protos.google.logging.v2.IListMonitoredResourceDescriptorsResponse + | null + | undefined, + protos.google.api.IMonitoredResourceDescriptor + >, + ): void; listMonitoredResourceDescriptors( - request?: protos.google.logging.v2.IListMonitoredResourceDescriptorsRequest, - optionsOrCallback?: CallOptions|PaginationCallback< + request?: protos.google.logging.v2.IListMonitoredResourceDescriptorsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.logging.v2.IListMonitoredResourceDescriptorsRequest, - protos.google.logging.v2.IListMonitoredResourceDescriptorsResponse|null|undefined, - protos.google.api.IMonitoredResourceDescriptor>, - callback?: PaginationCallback< - protos.google.logging.v2.IListMonitoredResourceDescriptorsRequest, - protos.google.logging.v2.IListMonitoredResourceDescriptorsResponse|null|undefined, - protos.google.api.IMonitoredResourceDescriptor>): - Promise<[ - protos.google.api.IMonitoredResourceDescriptor[], - protos.google.logging.v2.IListMonitoredResourceDescriptorsRequest|null, - protos.google.logging.v2.IListMonitoredResourceDescriptorsResponse - ]>|void { + | protos.google.logging.v2.IListMonitoredResourceDescriptorsResponse + | null + | undefined, + protos.google.api.IMonitoredResourceDescriptor + >, + callback?: PaginationCallback< + protos.google.logging.v2.IListMonitoredResourceDescriptorsRequest, + | protos.google.logging.v2.IListMonitoredResourceDescriptorsResponse + | null + | undefined, + protos.google.api.IMonitoredResourceDescriptor + >, + ): Promise< + [ + protos.google.api.IMonitoredResourceDescriptor[], + protos.google.logging.v2.IListMonitoredResourceDescriptorsRequest | null, + protos.google.logging.v2.IListMonitoredResourceDescriptorsResponse, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.logging.v2.IListMonitoredResourceDescriptorsRequest, - protos.google.logging.v2.IListMonitoredResourceDescriptorsResponse|null|undefined, - protos.google.api.IMonitoredResourceDescriptor>|undefined = callback + this.initialize().catch((err) => { + throw err; + }); + const wrappedCallback: + | PaginationCallback< + protos.google.logging.v2.IListMonitoredResourceDescriptorsRequest, + | protos.google.logging.v2.IListMonitoredResourceDescriptorsResponse + | null + | undefined, + protos.google.api.IMonitoredResourceDescriptor + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listMonitoredResourceDescriptors values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -1126,210 +1309,236 @@ export class LoggingServiceV2Client { this._log.info('listMonitoredResourceDescriptors request %j', request); return this.innerApiCalls .listMonitoredResourceDescriptors(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.api.IMonitoredResourceDescriptor[], - protos.google.logging.v2.IListMonitoredResourceDescriptorsRequest|null, - protos.google.logging.v2.IListMonitoredResourceDescriptorsResponse - ]) => { - this._log.info('listMonitoredResourceDescriptors values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.api.IMonitoredResourceDescriptor[], + protos.google.logging.v2.IListMonitoredResourceDescriptorsRequest | null, + protos.google.logging.v2.IListMonitoredResourceDescriptorsResponse, + ]) => { + this._log.info( + 'listMonitoredResourceDescriptors values %j', + response, + ); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listMonitoredResourceDescriptors`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {number} [request.pageSize] - * Optional. The maximum number of results to return from this request. - * Non-positive values are ignored. The presence of `nextPageToken` in the - * response indicates that more results might be available. - * @param {string} [request.pageToken] - * Optional. If present, then retrieve the next batch of results from the - * preceding call to this method. `pageToken` must be the value of - * `nextPageToken` from the previous response. The values of other method - * parameters should be identical to those in the previous call. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.api.MonitoredResourceDescriptor|MonitoredResourceDescriptor} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `listMonitoredResourceDescriptorsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `listMonitoredResourceDescriptors`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {number} [request.pageSize] + * Optional. The maximum number of results to return from this request. + * Non-positive values are ignored. The presence of `nextPageToken` in the + * response indicates that more results might be available. + * @param {string} [request.pageToken] + * Optional. If present, then retrieve the next batch of results from the + * preceding call to this method. `pageToken` must be the value of + * `nextPageToken` from the previous response. The values of other method + * parameters should be identical to those in the previous call. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.api.MonitoredResourceDescriptor|MonitoredResourceDescriptor} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listMonitoredResourceDescriptorsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listMonitoredResourceDescriptorsStream( - request?: protos.google.logging.v2.IListMonitoredResourceDescriptorsRequest, - options?: CallOptions): - Transform{ + request?: protos.google.logging.v2.IListMonitoredResourceDescriptorsRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - const defaultCallSettings = this._defaults['listMonitoredResourceDescriptors']; + const defaultCallSettings = + this._defaults['listMonitoredResourceDescriptors']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listMonitoredResourceDescriptors stream %j', request); return this.descriptors.page.listMonitoredResourceDescriptors.createStream( this.innerApiCalls.listMonitoredResourceDescriptors as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listMonitoredResourceDescriptors`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {number} [request.pageSize] - * Optional. The maximum number of results to return from this request. - * Non-positive values are ignored. The presence of `nextPageToken` in the - * response indicates that more results might be available. - * @param {string} [request.pageToken] - * Optional. If present, then retrieve the next batch of results from the - * preceding call to this method. `pageToken` must be the value of - * `nextPageToken` from the previous response. The values of other method - * parameters should be identical to those in the previous call. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.api.MonitoredResourceDescriptor|MonitoredResourceDescriptor}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v2/logging_service_v2.list_monitored_resource_descriptors.js - * region_tag:logging_v2_generated_LoggingServiceV2_ListMonitoredResourceDescriptors_async - */ + /** + * Equivalent to `listMonitoredResourceDescriptors`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {number} [request.pageSize] + * Optional. The maximum number of results to return from this request. + * Non-positive values are ignored. The presence of `nextPageToken` in the + * response indicates that more results might be available. + * @param {string} [request.pageToken] + * Optional. If present, then retrieve the next batch of results from the + * preceding call to this method. `pageToken` must be the value of + * `nextPageToken` from the previous response. The values of other method + * parameters should be identical to those in the previous call. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.api.MonitoredResourceDescriptor|MonitoredResourceDescriptor}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v2/logging_service_v2.list_monitored_resource_descriptors.js + * region_tag:logging_v2_generated_LoggingServiceV2_ListMonitoredResourceDescriptors_async + */ listMonitoredResourceDescriptorsAsync( - request?: protos.google.logging.v2.IListMonitoredResourceDescriptorsRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.logging.v2.IListMonitoredResourceDescriptorsRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - const defaultCallSettings = this._defaults['listMonitoredResourceDescriptors']; + const defaultCallSettings = + this._defaults['listMonitoredResourceDescriptors']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listMonitoredResourceDescriptors iterate %j', request); return this.descriptors.page.listMonitoredResourceDescriptors.asyncIterate( this.innerApiCalls['listMonitoredResourceDescriptors'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } - /** - * Lists the logs in projects, organizations, folders, or billing accounts. - * Only logs that have entries are listed. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The resource name that owns the logs: - * - * * `projects/[PROJECT_ID]` - * * `organizations/[ORGANIZATION_ID]` - * * `billingAccounts/[BILLING_ACCOUNT_ID]` - * * `folders/[FOLDER_ID]` - * @param {number} [request.pageSize] - * Optional. The maximum number of results to return from this request. - * Non-positive values are ignored. The presence of `nextPageToken` in the - * response indicates that more results might be available. - * @param {string} [request.pageToken] - * Optional. If present, then retrieve the next batch of results from the - * preceding call to this method. `pageToken` must be the value of - * `nextPageToken` from the previous response. The values of other method - * parameters should be identical to those in the previous call. - * @param {string[]} [request.resourceNames] - * Optional. The resource name that owns the logs: - * - * * `projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]` - * * `organizations/[ORGANIZATION_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]` - * * `billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]` - * * `folders/[FOLDER_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]` - * - * To support legacy queries, it could also be: - * - * * `projects/[PROJECT_ID]` - * * `organizations/[ORGANIZATION_ID]` - * * `billingAccounts/[BILLING_ACCOUNT_ID]` - * * `folders/[FOLDER_ID]` - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of string. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `listLogsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Lists the logs in projects, organizations, folders, or billing accounts. + * Only logs that have entries are listed. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The resource name that owns the logs: + * + * * `projects/[PROJECT_ID]` + * * `organizations/[ORGANIZATION_ID]` + * * `billingAccounts/[BILLING_ACCOUNT_ID]` + * * `folders/[FOLDER_ID]` + * @param {number} [request.pageSize] + * Optional. The maximum number of results to return from this request. + * Non-positive values are ignored. The presence of `nextPageToken` in the + * response indicates that more results might be available. + * @param {string} [request.pageToken] + * Optional. If present, then retrieve the next batch of results from the + * preceding call to this method. `pageToken` must be the value of + * `nextPageToken` from the previous response. The values of other method + * parameters should be identical to those in the previous call. + * @param {string[]} [request.resourceNames] + * Optional. The resource name that owns the logs: + * + * * `projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]` + * * `organizations/[ORGANIZATION_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]` + * * `billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]` + * * `folders/[FOLDER_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]` + * + * To support legacy queries, it could also be: + * + * * `projects/[PROJECT_ID]` + * * `organizations/[ORGANIZATION_ID]` + * * `billingAccounts/[BILLING_ACCOUNT_ID]` + * * `folders/[FOLDER_ID]` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of string. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listLogsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listLogs( - request?: protos.google.logging.v2.IListLogsRequest, - options?: CallOptions): - Promise<[ - string[], - protos.google.logging.v2.IListLogsRequest|null, - protos.google.logging.v2.IListLogsResponse - ]>; + request?: protos.google.logging.v2.IListLogsRequest, + options?: CallOptions, + ): Promise< + [ + string[], + protos.google.logging.v2.IListLogsRequest | null, + protos.google.logging.v2.IListLogsResponse, + ] + >; listLogs( - request: protos.google.logging.v2.IListLogsRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.logging.v2.IListLogsRequest, - protos.google.logging.v2.IListLogsResponse|null|undefined, - string>): void; + request: protos.google.logging.v2.IListLogsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.logging.v2.IListLogsRequest, + protos.google.logging.v2.IListLogsResponse | null | undefined, + string + >, + ): void; listLogs( - request: protos.google.logging.v2.IListLogsRequest, - callback: PaginationCallback< - protos.google.logging.v2.IListLogsRequest, - protos.google.logging.v2.IListLogsResponse|null|undefined, - string>): void; + request: protos.google.logging.v2.IListLogsRequest, + callback: PaginationCallback< + protos.google.logging.v2.IListLogsRequest, + protos.google.logging.v2.IListLogsResponse | null | undefined, + string + >, + ): void; listLogs( - request?: protos.google.logging.v2.IListLogsRequest, - optionsOrCallback?: CallOptions|PaginationCallback< - protos.google.logging.v2.IListLogsRequest, - protos.google.logging.v2.IListLogsResponse|null|undefined, - string>, - callback?: PaginationCallback< + request?: protos.google.logging.v2.IListLogsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.logging.v2.IListLogsRequest, - protos.google.logging.v2.IListLogsResponse|null|undefined, - string>): - Promise<[ - string[], - protos.google.logging.v2.IListLogsRequest|null, - protos.google.logging.v2.IListLogsResponse - ]>|void { + protos.google.logging.v2.IListLogsResponse | null | undefined, + string + >, + callback?: PaginationCallback< + protos.google.logging.v2.IListLogsRequest, + protos.google.logging.v2.IListLogsResponse | null | undefined, + string + >, + ): Promise< + [ + string[], + protos.google.logging.v2.IListLogsRequest | null, + protos.google.logging.v2.IListLogsResponse, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.logging.v2.IListLogsRequest, - protos.google.logging.v2.IListLogsResponse|null|undefined, - string>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.logging.v2.IListLogsRequest, + protos.google.logging.v2.IListLogsResponse | null | undefined, + string + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listLogs values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -1338,154 +1547,158 @@ export class LoggingServiceV2Client { this._log.info('listLogs request %j', request); return this.innerApiCalls .listLogs(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - string[], - protos.google.logging.v2.IListLogsRequest|null, - protos.google.logging.v2.IListLogsResponse - ]) => { - this._log.info('listLogs values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + string[], + protos.google.logging.v2.IListLogsRequest | null, + protos.google.logging.v2.IListLogsResponse, + ]) => { + this._log.info('listLogs values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listLogs`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The resource name that owns the logs: - * - * * `projects/[PROJECT_ID]` - * * `organizations/[ORGANIZATION_ID]` - * * `billingAccounts/[BILLING_ACCOUNT_ID]` - * * `folders/[FOLDER_ID]` - * @param {number} [request.pageSize] - * Optional. The maximum number of results to return from this request. - * Non-positive values are ignored. The presence of `nextPageToken` in the - * response indicates that more results might be available. - * @param {string} [request.pageToken] - * Optional. If present, then retrieve the next batch of results from the - * preceding call to this method. `pageToken` must be the value of - * `nextPageToken` from the previous response. The values of other method - * parameters should be identical to those in the previous call. - * @param {string[]} [request.resourceNames] - * Optional. The resource name that owns the logs: - * - * * `projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]` - * * `organizations/[ORGANIZATION_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]` - * * `billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]` - * * `folders/[FOLDER_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]` - * - * To support legacy queries, it could also be: - * - * * `projects/[PROJECT_ID]` - * * `organizations/[ORGANIZATION_ID]` - * * `billingAccounts/[BILLING_ACCOUNT_ID]` - * * `folders/[FOLDER_ID]` - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing string on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `listLogsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `listLogs`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The resource name that owns the logs: + * + * * `projects/[PROJECT_ID]` + * * `organizations/[ORGANIZATION_ID]` + * * `billingAccounts/[BILLING_ACCOUNT_ID]` + * * `folders/[FOLDER_ID]` + * @param {number} [request.pageSize] + * Optional. The maximum number of results to return from this request. + * Non-positive values are ignored. The presence of `nextPageToken` in the + * response indicates that more results might be available. + * @param {string} [request.pageToken] + * Optional. If present, then retrieve the next batch of results from the + * preceding call to this method. `pageToken` must be the value of + * `nextPageToken` from the previous response. The values of other method + * parameters should be identical to those in the previous call. + * @param {string[]} [request.resourceNames] + * Optional. The resource name that owns the logs: + * + * * `projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]` + * * `organizations/[ORGANIZATION_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]` + * * `billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]` + * * `folders/[FOLDER_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]` + * + * To support legacy queries, it could also be: + * + * * `projects/[PROJECT_ID]` + * * `organizations/[ORGANIZATION_ID]` + * * `billingAccounts/[BILLING_ACCOUNT_ID]` + * * `folders/[FOLDER_ID]` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing string on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listLogsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listLogsStream( - request?: protos.google.logging.v2.IListLogsRequest, - options?: CallOptions): - Transform{ + request?: protos.google.logging.v2.IListLogsRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); const defaultCallSettings = this._defaults['listLogs']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listLogs stream %j', request); return this.descriptors.page.listLogs.createStream( this.innerApiCalls.listLogs as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listLogs`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The resource name that owns the logs: - * - * * `projects/[PROJECT_ID]` - * * `organizations/[ORGANIZATION_ID]` - * * `billingAccounts/[BILLING_ACCOUNT_ID]` - * * `folders/[FOLDER_ID]` - * @param {number} [request.pageSize] - * Optional. The maximum number of results to return from this request. - * Non-positive values are ignored. The presence of `nextPageToken` in the - * response indicates that more results might be available. - * @param {string} [request.pageToken] - * Optional. If present, then retrieve the next batch of results from the - * preceding call to this method. `pageToken` must be the value of - * `nextPageToken` from the previous response. The values of other method - * parameters should be identical to those in the previous call. - * @param {string[]} [request.resourceNames] - * Optional. The resource name that owns the logs: - * - * * `projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]` - * * `organizations/[ORGANIZATION_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]` - * * `billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]` - * * `folders/[FOLDER_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]` - * - * To support legacy queries, it could also be: - * - * * `projects/[PROJECT_ID]` - * * `organizations/[ORGANIZATION_ID]` - * * `billingAccounts/[BILLING_ACCOUNT_ID]` - * * `folders/[FOLDER_ID]` - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * string. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v2/logging_service_v2.list_logs.js - * region_tag:logging_v2_generated_LoggingServiceV2_ListLogs_async - */ + /** + * Equivalent to `listLogs`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The resource name that owns the logs: + * + * * `projects/[PROJECT_ID]` + * * `organizations/[ORGANIZATION_ID]` + * * `billingAccounts/[BILLING_ACCOUNT_ID]` + * * `folders/[FOLDER_ID]` + * @param {number} [request.pageSize] + * Optional. The maximum number of results to return from this request. + * Non-positive values are ignored. The presence of `nextPageToken` in the + * response indicates that more results might be available. + * @param {string} [request.pageToken] + * Optional. If present, then retrieve the next batch of results from the + * preceding call to this method. `pageToken` must be the value of + * `nextPageToken` from the previous response. The values of other method + * parameters should be identical to those in the previous call. + * @param {string[]} [request.resourceNames] + * Optional. The resource name that owns the logs: + * + * * `projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]` + * * `organizations/[ORGANIZATION_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]` + * * `billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]` + * * `folders/[FOLDER_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]` + * + * To support legacy queries, it could also be: + * + * * `projects/[PROJECT_ID]` + * * `organizations/[ORGANIZATION_ID]` + * * `billingAccounts/[BILLING_ACCOUNT_ID]` + * * `folders/[FOLDER_ID]` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * string. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v2/logging_service_v2.list_logs.js + * region_tag:logging_v2_generated_LoggingServiceV2_ListLogs_async + */ listLogsAsync( - request?: protos.google.logging.v2.IListLogsRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.logging.v2.IListLogsRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); const defaultCallSettings = this._defaults['listLogs']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listLogs iterate %j', request); return this.descriptors.page.listLogs.asyncIterate( this.innerApiCalls['listLogs'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } // -------------------- @@ -1498,7 +1711,7 @@ export class LoggingServiceV2Client { * @param {string} billing_account * @returns {string} Resource name string. */ - billingAccountCmekSettingsPath(billingAccount:string) { + billingAccountCmekSettingsPath(billingAccount: string) { return this.pathTemplates.billingAccountCmekSettingsPathTemplate.render({ billing_account: billingAccount, }); @@ -1511,8 +1724,12 @@ export class LoggingServiceV2Client { * A fully-qualified path representing billing_account_cmekSettings resource. * @returns {string} A string representing the billing_account. */ - matchBillingAccountFromBillingAccountCmekSettingsName(billingAccountCmekSettingsName: string) { - return this.pathTemplates.billingAccountCmekSettingsPathTemplate.match(billingAccountCmekSettingsName).billing_account; + matchBillingAccountFromBillingAccountCmekSettingsName( + billingAccountCmekSettingsName: string, + ) { + return this.pathTemplates.billingAccountCmekSettingsPathTemplate.match( + billingAccountCmekSettingsName, + ).billing_account; } /** @@ -1522,7 +1739,7 @@ export class LoggingServiceV2Client { * @param {string} exclusion * @returns {string} Resource name string. */ - billingAccountExclusionPath(billingAccount:string,exclusion:string) { + billingAccountExclusionPath(billingAccount: string, exclusion: string) { return this.pathTemplates.billingAccountExclusionPathTemplate.render({ billing_account: billingAccount, exclusion: exclusion, @@ -1536,8 +1753,12 @@ export class LoggingServiceV2Client { * A fully-qualified path representing billing_account_exclusion resource. * @returns {string} A string representing the billing_account. */ - matchBillingAccountFromBillingAccountExclusionName(billingAccountExclusionName: string) { - return this.pathTemplates.billingAccountExclusionPathTemplate.match(billingAccountExclusionName).billing_account; + matchBillingAccountFromBillingAccountExclusionName( + billingAccountExclusionName: string, + ) { + return this.pathTemplates.billingAccountExclusionPathTemplate.match( + billingAccountExclusionName, + ).billing_account; } /** @@ -1547,8 +1768,12 @@ export class LoggingServiceV2Client { * A fully-qualified path representing billing_account_exclusion resource. * @returns {string} A string representing the exclusion. */ - matchExclusionFromBillingAccountExclusionName(billingAccountExclusionName: string) { - return this.pathTemplates.billingAccountExclusionPathTemplate.match(billingAccountExclusionName).exclusion; + matchExclusionFromBillingAccountExclusionName( + billingAccountExclusionName: string, + ) { + return this.pathTemplates.billingAccountExclusionPathTemplate.match( + billingAccountExclusionName, + ).exclusion; } /** @@ -1559,7 +1784,11 @@ export class LoggingServiceV2Client { * @param {string} bucket * @returns {string} Resource name string. */ - billingAccountLocationBucketPath(billingAccount:string,location:string,bucket:string) { + billingAccountLocationBucketPath( + billingAccount: string, + location: string, + bucket: string, + ) { return this.pathTemplates.billingAccountLocationBucketPathTemplate.render({ billing_account: billingAccount, location: location, @@ -1574,8 +1803,12 @@ export class LoggingServiceV2Client { * A fully-qualified path representing billing_account_location_bucket resource. * @returns {string} A string representing the billing_account. */ - matchBillingAccountFromBillingAccountLocationBucketName(billingAccountLocationBucketName: string) { - return this.pathTemplates.billingAccountLocationBucketPathTemplate.match(billingAccountLocationBucketName).billing_account; + matchBillingAccountFromBillingAccountLocationBucketName( + billingAccountLocationBucketName: string, + ) { + return this.pathTemplates.billingAccountLocationBucketPathTemplate.match( + billingAccountLocationBucketName, + ).billing_account; } /** @@ -1585,8 +1818,12 @@ export class LoggingServiceV2Client { * A fully-qualified path representing billing_account_location_bucket resource. * @returns {string} A string representing the location. */ - matchLocationFromBillingAccountLocationBucketName(billingAccountLocationBucketName: string) { - return this.pathTemplates.billingAccountLocationBucketPathTemplate.match(billingAccountLocationBucketName).location; + matchLocationFromBillingAccountLocationBucketName( + billingAccountLocationBucketName: string, + ) { + return this.pathTemplates.billingAccountLocationBucketPathTemplate.match( + billingAccountLocationBucketName, + ).location; } /** @@ -1596,8 +1833,12 @@ export class LoggingServiceV2Client { * A fully-qualified path representing billing_account_location_bucket resource. * @returns {string} A string representing the bucket. */ - matchBucketFromBillingAccountLocationBucketName(billingAccountLocationBucketName: string) { - return this.pathTemplates.billingAccountLocationBucketPathTemplate.match(billingAccountLocationBucketName).bucket; + matchBucketFromBillingAccountLocationBucketName( + billingAccountLocationBucketName: string, + ) { + return this.pathTemplates.billingAccountLocationBucketPathTemplate.match( + billingAccountLocationBucketName, + ).bucket; } /** @@ -1609,13 +1850,20 @@ export class LoggingServiceV2Client { * @param {string} view * @returns {string} Resource name string. */ - billingAccountLocationBucketViewPath(billingAccount:string,location:string,bucket:string,view:string) { - return this.pathTemplates.billingAccountLocationBucketViewPathTemplate.render({ - billing_account: billingAccount, - location: location, - bucket: bucket, - view: view, - }); + billingAccountLocationBucketViewPath( + billingAccount: string, + location: string, + bucket: string, + view: string, + ) { + return this.pathTemplates.billingAccountLocationBucketViewPathTemplate.render( + { + billing_account: billingAccount, + location: location, + bucket: bucket, + view: view, + }, + ); } /** @@ -1625,8 +1873,12 @@ export class LoggingServiceV2Client { * A fully-qualified path representing billing_account_location_bucket_view resource. * @returns {string} A string representing the billing_account. */ - matchBillingAccountFromBillingAccountLocationBucketViewName(billingAccountLocationBucketViewName: string) { - return this.pathTemplates.billingAccountLocationBucketViewPathTemplate.match(billingAccountLocationBucketViewName).billing_account; + matchBillingAccountFromBillingAccountLocationBucketViewName( + billingAccountLocationBucketViewName: string, + ) { + return this.pathTemplates.billingAccountLocationBucketViewPathTemplate.match( + billingAccountLocationBucketViewName, + ).billing_account; } /** @@ -1636,8 +1888,12 @@ export class LoggingServiceV2Client { * A fully-qualified path representing billing_account_location_bucket_view resource. * @returns {string} A string representing the location. */ - matchLocationFromBillingAccountLocationBucketViewName(billingAccountLocationBucketViewName: string) { - return this.pathTemplates.billingAccountLocationBucketViewPathTemplate.match(billingAccountLocationBucketViewName).location; + matchLocationFromBillingAccountLocationBucketViewName( + billingAccountLocationBucketViewName: string, + ) { + return this.pathTemplates.billingAccountLocationBucketViewPathTemplate.match( + billingAccountLocationBucketViewName, + ).location; } /** @@ -1647,8 +1903,12 @@ export class LoggingServiceV2Client { * A fully-qualified path representing billing_account_location_bucket_view resource. * @returns {string} A string representing the bucket. */ - matchBucketFromBillingAccountLocationBucketViewName(billingAccountLocationBucketViewName: string) { - return this.pathTemplates.billingAccountLocationBucketViewPathTemplate.match(billingAccountLocationBucketViewName).bucket; + matchBucketFromBillingAccountLocationBucketViewName( + billingAccountLocationBucketViewName: string, + ) { + return this.pathTemplates.billingAccountLocationBucketViewPathTemplate.match( + billingAccountLocationBucketViewName, + ).bucket; } /** @@ -1658,8 +1918,12 @@ export class LoggingServiceV2Client { * A fully-qualified path representing billing_account_location_bucket_view resource. * @returns {string} A string representing the view. */ - matchViewFromBillingAccountLocationBucketViewName(billingAccountLocationBucketViewName: string) { - return this.pathTemplates.billingAccountLocationBucketViewPathTemplate.match(billingAccountLocationBucketViewName).view; + matchViewFromBillingAccountLocationBucketViewName( + billingAccountLocationBucketViewName: string, + ) { + return this.pathTemplates.billingAccountLocationBucketViewPathTemplate.match( + billingAccountLocationBucketViewName, + ).view; } /** @@ -1669,7 +1933,7 @@ export class LoggingServiceV2Client { * @param {string} log * @returns {string} Resource name string. */ - billingAccountLogPath(billingAccount:string,log:string) { + billingAccountLogPath(billingAccount: string, log: string) { return this.pathTemplates.billingAccountLogPathTemplate.render({ billing_account: billingAccount, log: log, @@ -1684,7 +1948,9 @@ export class LoggingServiceV2Client { * @returns {string} A string representing the billing_account. */ matchBillingAccountFromBillingAccountLogName(billingAccountLogName: string) { - return this.pathTemplates.billingAccountLogPathTemplate.match(billingAccountLogName).billing_account; + return this.pathTemplates.billingAccountLogPathTemplate.match( + billingAccountLogName, + ).billing_account; } /** @@ -1695,7 +1961,9 @@ export class LoggingServiceV2Client { * @returns {string} A string representing the log. */ matchLogFromBillingAccountLogName(billingAccountLogName: string) { - return this.pathTemplates.billingAccountLogPathTemplate.match(billingAccountLogName).log; + return this.pathTemplates.billingAccountLogPathTemplate.match( + billingAccountLogName, + ).log; } /** @@ -1704,7 +1972,7 @@ export class LoggingServiceV2Client { * @param {string} billing_account * @returns {string} Resource name string. */ - billingAccountSettingsPath(billingAccount:string) { + billingAccountSettingsPath(billingAccount: string) { return this.pathTemplates.billingAccountSettingsPathTemplate.render({ billing_account: billingAccount, }); @@ -1717,8 +1985,12 @@ export class LoggingServiceV2Client { * A fully-qualified path representing billing_account_settings resource. * @returns {string} A string representing the billing_account. */ - matchBillingAccountFromBillingAccountSettingsName(billingAccountSettingsName: string) { - return this.pathTemplates.billingAccountSettingsPathTemplate.match(billingAccountSettingsName).billing_account; + matchBillingAccountFromBillingAccountSettingsName( + billingAccountSettingsName: string, + ) { + return this.pathTemplates.billingAccountSettingsPathTemplate.match( + billingAccountSettingsName, + ).billing_account; } /** @@ -1728,7 +2000,7 @@ export class LoggingServiceV2Client { * @param {string} sink * @returns {string} Resource name string. */ - billingAccountSinkPath(billingAccount:string,sink:string) { + billingAccountSinkPath(billingAccount: string, sink: string) { return this.pathTemplates.billingAccountSinkPathTemplate.render({ billing_account: billingAccount, sink: sink, @@ -1742,8 +2014,12 @@ export class LoggingServiceV2Client { * A fully-qualified path representing billing_account_sink resource. * @returns {string} A string representing the billing_account. */ - matchBillingAccountFromBillingAccountSinkName(billingAccountSinkName: string) { - return this.pathTemplates.billingAccountSinkPathTemplate.match(billingAccountSinkName).billing_account; + matchBillingAccountFromBillingAccountSinkName( + billingAccountSinkName: string, + ) { + return this.pathTemplates.billingAccountSinkPathTemplate.match( + billingAccountSinkName, + ).billing_account; } /** @@ -1754,7 +2030,9 @@ export class LoggingServiceV2Client { * @returns {string} A string representing the sink. */ matchSinkFromBillingAccountSinkName(billingAccountSinkName: string) { - return this.pathTemplates.billingAccountSinkPathTemplate.match(billingAccountSinkName).sink; + return this.pathTemplates.billingAccountSinkPathTemplate.match( + billingAccountSinkName, + ).sink; } /** @@ -1763,7 +2041,7 @@ export class LoggingServiceV2Client { * @param {string} folder * @returns {string} Resource name string. */ - folderCmekSettingsPath(folder:string) { + folderCmekSettingsPath(folder: string) { return this.pathTemplates.folderCmekSettingsPathTemplate.render({ folder: folder, }); @@ -1777,7 +2055,9 @@ export class LoggingServiceV2Client { * @returns {string} A string representing the folder. */ matchFolderFromFolderCmekSettingsName(folderCmekSettingsName: string) { - return this.pathTemplates.folderCmekSettingsPathTemplate.match(folderCmekSettingsName).folder; + return this.pathTemplates.folderCmekSettingsPathTemplate.match( + folderCmekSettingsName, + ).folder; } /** @@ -1787,7 +2067,7 @@ export class LoggingServiceV2Client { * @param {string} exclusion * @returns {string} Resource name string. */ - folderExclusionPath(folder:string,exclusion:string) { + folderExclusionPath(folder: string, exclusion: string) { return this.pathTemplates.folderExclusionPathTemplate.render({ folder: folder, exclusion: exclusion, @@ -1802,7 +2082,9 @@ export class LoggingServiceV2Client { * @returns {string} A string representing the folder. */ matchFolderFromFolderExclusionName(folderExclusionName: string) { - return this.pathTemplates.folderExclusionPathTemplate.match(folderExclusionName).folder; + return this.pathTemplates.folderExclusionPathTemplate.match( + folderExclusionName, + ).folder; } /** @@ -1813,7 +2095,9 @@ export class LoggingServiceV2Client { * @returns {string} A string representing the exclusion. */ matchExclusionFromFolderExclusionName(folderExclusionName: string) { - return this.pathTemplates.folderExclusionPathTemplate.match(folderExclusionName).exclusion; + return this.pathTemplates.folderExclusionPathTemplate.match( + folderExclusionName, + ).exclusion; } /** @@ -1824,7 +2108,7 @@ export class LoggingServiceV2Client { * @param {string} bucket * @returns {string} Resource name string. */ - folderLocationBucketPath(folder:string,location:string,bucket:string) { + folderLocationBucketPath(folder: string, location: string, bucket: string) { return this.pathTemplates.folderLocationBucketPathTemplate.render({ folder: folder, location: location, @@ -1840,7 +2124,9 @@ export class LoggingServiceV2Client { * @returns {string} A string representing the folder. */ matchFolderFromFolderLocationBucketName(folderLocationBucketName: string) { - return this.pathTemplates.folderLocationBucketPathTemplate.match(folderLocationBucketName).folder; + return this.pathTemplates.folderLocationBucketPathTemplate.match( + folderLocationBucketName, + ).folder; } /** @@ -1851,7 +2137,9 @@ export class LoggingServiceV2Client { * @returns {string} A string representing the location. */ matchLocationFromFolderLocationBucketName(folderLocationBucketName: string) { - return this.pathTemplates.folderLocationBucketPathTemplate.match(folderLocationBucketName).location; + return this.pathTemplates.folderLocationBucketPathTemplate.match( + folderLocationBucketName, + ).location; } /** @@ -1862,7 +2150,9 @@ export class LoggingServiceV2Client { * @returns {string} A string representing the bucket. */ matchBucketFromFolderLocationBucketName(folderLocationBucketName: string) { - return this.pathTemplates.folderLocationBucketPathTemplate.match(folderLocationBucketName).bucket; + return this.pathTemplates.folderLocationBucketPathTemplate.match( + folderLocationBucketName, + ).bucket; } /** @@ -1874,7 +2164,12 @@ export class LoggingServiceV2Client { * @param {string} view * @returns {string} Resource name string. */ - folderLocationBucketViewPath(folder:string,location:string,bucket:string,view:string) { + folderLocationBucketViewPath( + folder: string, + location: string, + bucket: string, + view: string, + ) { return this.pathTemplates.folderLocationBucketViewPathTemplate.render({ folder: folder, location: location, @@ -1890,8 +2185,12 @@ export class LoggingServiceV2Client { * A fully-qualified path representing folder_location_bucket_view resource. * @returns {string} A string representing the folder. */ - matchFolderFromFolderLocationBucketViewName(folderLocationBucketViewName: string) { - return this.pathTemplates.folderLocationBucketViewPathTemplate.match(folderLocationBucketViewName).folder; + matchFolderFromFolderLocationBucketViewName( + folderLocationBucketViewName: string, + ) { + return this.pathTemplates.folderLocationBucketViewPathTemplate.match( + folderLocationBucketViewName, + ).folder; } /** @@ -1901,8 +2200,12 @@ export class LoggingServiceV2Client { * A fully-qualified path representing folder_location_bucket_view resource. * @returns {string} A string representing the location. */ - matchLocationFromFolderLocationBucketViewName(folderLocationBucketViewName: string) { - return this.pathTemplates.folderLocationBucketViewPathTemplate.match(folderLocationBucketViewName).location; + matchLocationFromFolderLocationBucketViewName( + folderLocationBucketViewName: string, + ) { + return this.pathTemplates.folderLocationBucketViewPathTemplate.match( + folderLocationBucketViewName, + ).location; } /** @@ -1912,8 +2215,12 @@ export class LoggingServiceV2Client { * A fully-qualified path representing folder_location_bucket_view resource. * @returns {string} A string representing the bucket. */ - matchBucketFromFolderLocationBucketViewName(folderLocationBucketViewName: string) { - return this.pathTemplates.folderLocationBucketViewPathTemplate.match(folderLocationBucketViewName).bucket; + matchBucketFromFolderLocationBucketViewName( + folderLocationBucketViewName: string, + ) { + return this.pathTemplates.folderLocationBucketViewPathTemplate.match( + folderLocationBucketViewName, + ).bucket; } /** @@ -1923,8 +2230,12 @@ export class LoggingServiceV2Client { * A fully-qualified path representing folder_location_bucket_view resource. * @returns {string} A string representing the view. */ - matchViewFromFolderLocationBucketViewName(folderLocationBucketViewName: string) { - return this.pathTemplates.folderLocationBucketViewPathTemplate.match(folderLocationBucketViewName).view; + matchViewFromFolderLocationBucketViewName( + folderLocationBucketViewName: string, + ) { + return this.pathTemplates.folderLocationBucketViewPathTemplate.match( + folderLocationBucketViewName, + ).view; } /** @@ -1934,7 +2245,7 @@ export class LoggingServiceV2Client { * @param {string} log * @returns {string} Resource name string. */ - folderLogPath(folder:string,log:string) { + folderLogPath(folder: string, log: string) { return this.pathTemplates.folderLogPathTemplate.render({ folder: folder, log: log, @@ -1969,7 +2280,7 @@ export class LoggingServiceV2Client { * @param {string} folder * @returns {string} Resource name string. */ - folderSettingsPath(folder:string) { + folderSettingsPath(folder: string) { return this.pathTemplates.folderSettingsPathTemplate.render({ folder: folder, }); @@ -1983,7 +2294,9 @@ export class LoggingServiceV2Client { * @returns {string} A string representing the folder. */ matchFolderFromFolderSettingsName(folderSettingsName: string) { - return this.pathTemplates.folderSettingsPathTemplate.match(folderSettingsName).folder; + return this.pathTemplates.folderSettingsPathTemplate.match( + folderSettingsName, + ).folder; } /** @@ -1993,7 +2306,7 @@ export class LoggingServiceV2Client { * @param {string} sink * @returns {string} Resource name string. */ - folderSinkPath(folder:string,sink:string) { + folderSinkPath(folder: string, sink: string) { return this.pathTemplates.folderSinkPathTemplate.render({ folder: folder, sink: sink, @@ -2008,7 +2321,8 @@ export class LoggingServiceV2Client { * @returns {string} A string representing the folder. */ matchFolderFromFolderSinkName(folderSinkName: string) { - return this.pathTemplates.folderSinkPathTemplate.match(folderSinkName).folder; + return this.pathTemplates.folderSinkPathTemplate.match(folderSinkName) + .folder; } /** @@ -2029,7 +2343,7 @@ export class LoggingServiceV2Client { * @param {string} metric * @returns {string} Resource name string. */ - logMetricPath(project:string,metric:string) { + logMetricPath(project: string, metric: string) { return this.pathTemplates.logMetricPathTemplate.render({ project: project, metric: metric, @@ -2044,7 +2358,8 @@ export class LoggingServiceV2Client { * @returns {string} A string representing the project. */ matchProjectFromLogMetricName(logMetricName: string) { - return this.pathTemplates.logMetricPathTemplate.match(logMetricName).project; + return this.pathTemplates.logMetricPathTemplate.match(logMetricName) + .project; } /** @@ -2064,7 +2379,7 @@ export class LoggingServiceV2Client { * @param {string} organization * @returns {string} Resource name string. */ - organizationCmekSettingsPath(organization:string) { + organizationCmekSettingsPath(organization: string) { return this.pathTemplates.organizationCmekSettingsPathTemplate.render({ organization: organization, }); @@ -2077,8 +2392,12 @@ export class LoggingServiceV2Client { * A fully-qualified path representing organization_cmekSettings resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationCmekSettingsName(organizationCmekSettingsName: string) { - return this.pathTemplates.organizationCmekSettingsPathTemplate.match(organizationCmekSettingsName).organization; + matchOrganizationFromOrganizationCmekSettingsName( + organizationCmekSettingsName: string, + ) { + return this.pathTemplates.organizationCmekSettingsPathTemplate.match( + organizationCmekSettingsName, + ).organization; } /** @@ -2088,7 +2407,7 @@ export class LoggingServiceV2Client { * @param {string} exclusion * @returns {string} Resource name string. */ - organizationExclusionPath(organization:string,exclusion:string) { + organizationExclusionPath(organization: string, exclusion: string) { return this.pathTemplates.organizationExclusionPathTemplate.render({ organization: organization, exclusion: exclusion, @@ -2102,8 +2421,12 @@ export class LoggingServiceV2Client { * A fully-qualified path representing organization_exclusion resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationExclusionName(organizationExclusionName: string) { - return this.pathTemplates.organizationExclusionPathTemplate.match(organizationExclusionName).organization; + matchOrganizationFromOrganizationExclusionName( + organizationExclusionName: string, + ) { + return this.pathTemplates.organizationExclusionPathTemplate.match( + organizationExclusionName, + ).organization; } /** @@ -2113,8 +2436,12 @@ export class LoggingServiceV2Client { * A fully-qualified path representing organization_exclusion resource. * @returns {string} A string representing the exclusion. */ - matchExclusionFromOrganizationExclusionName(organizationExclusionName: string) { - return this.pathTemplates.organizationExclusionPathTemplate.match(organizationExclusionName).exclusion; + matchExclusionFromOrganizationExclusionName( + organizationExclusionName: string, + ) { + return this.pathTemplates.organizationExclusionPathTemplate.match( + organizationExclusionName, + ).exclusion; } /** @@ -2125,7 +2452,11 @@ export class LoggingServiceV2Client { * @param {string} bucket * @returns {string} Resource name string. */ - organizationLocationBucketPath(organization:string,location:string,bucket:string) { + organizationLocationBucketPath( + organization: string, + location: string, + bucket: string, + ) { return this.pathTemplates.organizationLocationBucketPathTemplate.render({ organization: organization, location: location, @@ -2140,8 +2471,12 @@ export class LoggingServiceV2Client { * A fully-qualified path representing organization_location_bucket resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationLocationBucketName(organizationLocationBucketName: string) { - return this.pathTemplates.organizationLocationBucketPathTemplate.match(organizationLocationBucketName).organization; + matchOrganizationFromOrganizationLocationBucketName( + organizationLocationBucketName: string, + ) { + return this.pathTemplates.organizationLocationBucketPathTemplate.match( + organizationLocationBucketName, + ).organization; } /** @@ -2151,8 +2486,12 @@ export class LoggingServiceV2Client { * A fully-qualified path representing organization_location_bucket resource. * @returns {string} A string representing the location. */ - matchLocationFromOrganizationLocationBucketName(organizationLocationBucketName: string) { - return this.pathTemplates.organizationLocationBucketPathTemplate.match(organizationLocationBucketName).location; + matchLocationFromOrganizationLocationBucketName( + organizationLocationBucketName: string, + ) { + return this.pathTemplates.organizationLocationBucketPathTemplate.match( + organizationLocationBucketName, + ).location; } /** @@ -2162,8 +2501,12 @@ export class LoggingServiceV2Client { * A fully-qualified path representing organization_location_bucket resource. * @returns {string} A string representing the bucket. */ - matchBucketFromOrganizationLocationBucketName(organizationLocationBucketName: string) { - return this.pathTemplates.organizationLocationBucketPathTemplate.match(organizationLocationBucketName).bucket; + matchBucketFromOrganizationLocationBucketName( + organizationLocationBucketName: string, + ) { + return this.pathTemplates.organizationLocationBucketPathTemplate.match( + organizationLocationBucketName, + ).bucket; } /** @@ -2175,13 +2518,20 @@ export class LoggingServiceV2Client { * @param {string} view * @returns {string} Resource name string. */ - organizationLocationBucketViewPath(organization:string,location:string,bucket:string,view:string) { - return this.pathTemplates.organizationLocationBucketViewPathTemplate.render({ - organization: organization, - location: location, - bucket: bucket, - view: view, - }); + organizationLocationBucketViewPath( + organization: string, + location: string, + bucket: string, + view: string, + ) { + return this.pathTemplates.organizationLocationBucketViewPathTemplate.render( + { + organization: organization, + location: location, + bucket: bucket, + view: view, + }, + ); } /** @@ -2191,8 +2541,12 @@ export class LoggingServiceV2Client { * A fully-qualified path representing organization_location_bucket_view resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationLocationBucketViewName(organizationLocationBucketViewName: string) { - return this.pathTemplates.organizationLocationBucketViewPathTemplate.match(organizationLocationBucketViewName).organization; + matchOrganizationFromOrganizationLocationBucketViewName( + organizationLocationBucketViewName: string, + ) { + return this.pathTemplates.organizationLocationBucketViewPathTemplate.match( + organizationLocationBucketViewName, + ).organization; } /** @@ -2202,8 +2556,12 @@ export class LoggingServiceV2Client { * A fully-qualified path representing organization_location_bucket_view resource. * @returns {string} A string representing the location. */ - matchLocationFromOrganizationLocationBucketViewName(organizationLocationBucketViewName: string) { - return this.pathTemplates.organizationLocationBucketViewPathTemplate.match(organizationLocationBucketViewName).location; + matchLocationFromOrganizationLocationBucketViewName( + organizationLocationBucketViewName: string, + ) { + return this.pathTemplates.organizationLocationBucketViewPathTemplate.match( + organizationLocationBucketViewName, + ).location; } /** @@ -2213,8 +2571,12 @@ export class LoggingServiceV2Client { * A fully-qualified path representing organization_location_bucket_view resource. * @returns {string} A string representing the bucket. */ - matchBucketFromOrganizationLocationBucketViewName(organizationLocationBucketViewName: string) { - return this.pathTemplates.organizationLocationBucketViewPathTemplate.match(organizationLocationBucketViewName).bucket; + matchBucketFromOrganizationLocationBucketViewName( + organizationLocationBucketViewName: string, + ) { + return this.pathTemplates.organizationLocationBucketViewPathTemplate.match( + organizationLocationBucketViewName, + ).bucket; } /** @@ -2224,8 +2586,12 @@ export class LoggingServiceV2Client { * A fully-qualified path representing organization_location_bucket_view resource. * @returns {string} A string representing the view. */ - matchViewFromOrganizationLocationBucketViewName(organizationLocationBucketViewName: string) { - return this.pathTemplates.organizationLocationBucketViewPathTemplate.match(organizationLocationBucketViewName).view; + matchViewFromOrganizationLocationBucketViewName( + organizationLocationBucketViewName: string, + ) { + return this.pathTemplates.organizationLocationBucketViewPathTemplate.match( + organizationLocationBucketViewName, + ).view; } /** @@ -2235,7 +2601,7 @@ export class LoggingServiceV2Client { * @param {string} log * @returns {string} Resource name string. */ - organizationLogPath(organization:string,log:string) { + organizationLogPath(organization: string, log: string) { return this.pathTemplates.organizationLogPathTemplate.render({ organization: organization, log: log, @@ -2250,7 +2616,9 @@ export class LoggingServiceV2Client { * @returns {string} A string representing the organization. */ matchOrganizationFromOrganizationLogName(organizationLogName: string) { - return this.pathTemplates.organizationLogPathTemplate.match(organizationLogName).organization; + return this.pathTemplates.organizationLogPathTemplate.match( + organizationLogName, + ).organization; } /** @@ -2261,7 +2629,9 @@ export class LoggingServiceV2Client { * @returns {string} A string representing the log. */ matchLogFromOrganizationLogName(organizationLogName: string) { - return this.pathTemplates.organizationLogPathTemplate.match(organizationLogName).log; + return this.pathTemplates.organizationLogPathTemplate.match( + organizationLogName, + ).log; } /** @@ -2270,7 +2640,7 @@ export class LoggingServiceV2Client { * @param {string} organization * @returns {string} Resource name string. */ - organizationSettingsPath(organization:string) { + organizationSettingsPath(organization: string) { return this.pathTemplates.organizationSettingsPathTemplate.render({ organization: organization, }); @@ -2283,8 +2653,12 @@ export class LoggingServiceV2Client { * A fully-qualified path representing organization_settings resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationSettingsName(organizationSettingsName: string) { - return this.pathTemplates.organizationSettingsPathTemplate.match(organizationSettingsName).organization; + matchOrganizationFromOrganizationSettingsName( + organizationSettingsName: string, + ) { + return this.pathTemplates.organizationSettingsPathTemplate.match( + organizationSettingsName, + ).organization; } /** @@ -2294,7 +2668,7 @@ export class LoggingServiceV2Client { * @param {string} sink * @returns {string} Resource name string. */ - organizationSinkPath(organization:string,sink:string) { + organizationSinkPath(organization: string, sink: string) { return this.pathTemplates.organizationSinkPathTemplate.render({ organization: organization, sink: sink, @@ -2309,7 +2683,9 @@ export class LoggingServiceV2Client { * @returns {string} A string representing the organization. */ matchOrganizationFromOrganizationSinkName(organizationSinkName: string) { - return this.pathTemplates.organizationSinkPathTemplate.match(organizationSinkName).organization; + return this.pathTemplates.organizationSinkPathTemplate.match( + organizationSinkName, + ).organization; } /** @@ -2320,7 +2696,9 @@ export class LoggingServiceV2Client { * @returns {string} A string representing the sink. */ matchSinkFromOrganizationSinkName(organizationSinkName: string) { - return this.pathTemplates.organizationSinkPathTemplate.match(organizationSinkName).sink; + return this.pathTemplates.organizationSinkPathTemplate.match( + organizationSinkName, + ).sink; } /** @@ -2329,7 +2707,7 @@ export class LoggingServiceV2Client { * @param {string} project * @returns {string} Resource name string. */ - projectPath(project:string) { + projectPath(project: string) { return this.pathTemplates.projectPathTemplate.render({ project: project, }); @@ -2352,7 +2730,7 @@ export class LoggingServiceV2Client { * @param {string} project * @returns {string} Resource name string. */ - projectCmekSettingsPath(project:string) { + projectCmekSettingsPath(project: string) { return this.pathTemplates.projectCmekSettingsPathTemplate.render({ project: project, }); @@ -2366,7 +2744,9 @@ export class LoggingServiceV2Client { * @returns {string} A string representing the project. */ matchProjectFromProjectCmekSettingsName(projectCmekSettingsName: string) { - return this.pathTemplates.projectCmekSettingsPathTemplate.match(projectCmekSettingsName).project; + return this.pathTemplates.projectCmekSettingsPathTemplate.match( + projectCmekSettingsName, + ).project; } /** @@ -2376,7 +2756,7 @@ export class LoggingServiceV2Client { * @param {string} exclusion * @returns {string} Resource name string. */ - projectExclusionPath(project:string,exclusion:string) { + projectExclusionPath(project: string, exclusion: string) { return this.pathTemplates.projectExclusionPathTemplate.render({ project: project, exclusion: exclusion, @@ -2391,7 +2771,9 @@ export class LoggingServiceV2Client { * @returns {string} A string representing the project. */ matchProjectFromProjectExclusionName(projectExclusionName: string) { - return this.pathTemplates.projectExclusionPathTemplate.match(projectExclusionName).project; + return this.pathTemplates.projectExclusionPathTemplate.match( + projectExclusionName, + ).project; } /** @@ -2402,7 +2784,9 @@ export class LoggingServiceV2Client { * @returns {string} A string representing the exclusion. */ matchExclusionFromProjectExclusionName(projectExclusionName: string) { - return this.pathTemplates.projectExclusionPathTemplate.match(projectExclusionName).exclusion; + return this.pathTemplates.projectExclusionPathTemplate.match( + projectExclusionName, + ).exclusion; } /** @@ -2413,7 +2797,7 @@ export class LoggingServiceV2Client { * @param {string} bucket * @returns {string} Resource name string. */ - projectLocationBucketPath(project:string,location:string,bucket:string) { + projectLocationBucketPath(project: string, location: string, bucket: string) { return this.pathTemplates.projectLocationBucketPathTemplate.render({ project: project, location: location, @@ -2429,7 +2813,9 @@ export class LoggingServiceV2Client { * @returns {string} A string representing the project. */ matchProjectFromProjectLocationBucketName(projectLocationBucketName: string) { - return this.pathTemplates.projectLocationBucketPathTemplate.match(projectLocationBucketName).project; + return this.pathTemplates.projectLocationBucketPathTemplate.match( + projectLocationBucketName, + ).project; } /** @@ -2439,8 +2825,12 @@ export class LoggingServiceV2Client { * A fully-qualified path representing project_location_bucket resource. * @returns {string} A string representing the location. */ - matchLocationFromProjectLocationBucketName(projectLocationBucketName: string) { - return this.pathTemplates.projectLocationBucketPathTemplate.match(projectLocationBucketName).location; + matchLocationFromProjectLocationBucketName( + projectLocationBucketName: string, + ) { + return this.pathTemplates.projectLocationBucketPathTemplate.match( + projectLocationBucketName, + ).location; } /** @@ -2451,7 +2841,9 @@ export class LoggingServiceV2Client { * @returns {string} A string representing the bucket. */ matchBucketFromProjectLocationBucketName(projectLocationBucketName: string) { - return this.pathTemplates.projectLocationBucketPathTemplate.match(projectLocationBucketName).bucket; + return this.pathTemplates.projectLocationBucketPathTemplate.match( + projectLocationBucketName, + ).bucket; } /** @@ -2463,7 +2855,12 @@ export class LoggingServiceV2Client { * @param {string} view * @returns {string} Resource name string. */ - projectLocationBucketViewPath(project:string,location:string,bucket:string,view:string) { + projectLocationBucketViewPath( + project: string, + location: string, + bucket: string, + view: string, + ) { return this.pathTemplates.projectLocationBucketViewPathTemplate.render({ project: project, location: location, @@ -2479,8 +2876,12 @@ export class LoggingServiceV2Client { * A fully-qualified path representing project_location_bucket_view resource. * @returns {string} A string representing the project. */ - matchProjectFromProjectLocationBucketViewName(projectLocationBucketViewName: string) { - return this.pathTemplates.projectLocationBucketViewPathTemplate.match(projectLocationBucketViewName).project; + matchProjectFromProjectLocationBucketViewName( + projectLocationBucketViewName: string, + ) { + return this.pathTemplates.projectLocationBucketViewPathTemplate.match( + projectLocationBucketViewName, + ).project; } /** @@ -2490,8 +2891,12 @@ export class LoggingServiceV2Client { * A fully-qualified path representing project_location_bucket_view resource. * @returns {string} A string representing the location. */ - matchLocationFromProjectLocationBucketViewName(projectLocationBucketViewName: string) { - return this.pathTemplates.projectLocationBucketViewPathTemplate.match(projectLocationBucketViewName).location; + matchLocationFromProjectLocationBucketViewName( + projectLocationBucketViewName: string, + ) { + return this.pathTemplates.projectLocationBucketViewPathTemplate.match( + projectLocationBucketViewName, + ).location; } /** @@ -2501,8 +2906,12 @@ export class LoggingServiceV2Client { * A fully-qualified path representing project_location_bucket_view resource. * @returns {string} A string representing the bucket. */ - matchBucketFromProjectLocationBucketViewName(projectLocationBucketViewName: string) { - return this.pathTemplates.projectLocationBucketViewPathTemplate.match(projectLocationBucketViewName).bucket; + matchBucketFromProjectLocationBucketViewName( + projectLocationBucketViewName: string, + ) { + return this.pathTemplates.projectLocationBucketViewPathTemplate.match( + projectLocationBucketViewName, + ).bucket; } /** @@ -2512,8 +2921,12 @@ export class LoggingServiceV2Client { * A fully-qualified path representing project_location_bucket_view resource. * @returns {string} A string representing the view. */ - matchViewFromProjectLocationBucketViewName(projectLocationBucketViewName: string) { - return this.pathTemplates.projectLocationBucketViewPathTemplate.match(projectLocationBucketViewName).view; + matchViewFromProjectLocationBucketViewName( + projectLocationBucketViewName: string, + ) { + return this.pathTemplates.projectLocationBucketViewPathTemplate.match( + projectLocationBucketViewName, + ).view; } /** @@ -2523,7 +2936,7 @@ export class LoggingServiceV2Client { * @param {string} log * @returns {string} Resource name string. */ - projectLogPath(project:string,log:string) { + projectLogPath(project: string, log: string) { return this.pathTemplates.projectLogPathTemplate.render({ project: project, log: log, @@ -2538,7 +2951,8 @@ export class LoggingServiceV2Client { * @returns {string} A string representing the project. */ matchProjectFromProjectLogName(projectLogName: string) { - return this.pathTemplates.projectLogPathTemplate.match(projectLogName).project; + return this.pathTemplates.projectLogPathTemplate.match(projectLogName) + .project; } /** @@ -2558,7 +2972,7 @@ export class LoggingServiceV2Client { * @param {string} project * @returns {string} Resource name string. */ - projectSettingsPath(project:string) { + projectSettingsPath(project: string) { return this.pathTemplates.projectSettingsPathTemplate.render({ project: project, }); @@ -2572,7 +2986,9 @@ export class LoggingServiceV2Client { * @returns {string} A string representing the project. */ matchProjectFromProjectSettingsName(projectSettingsName: string) { - return this.pathTemplates.projectSettingsPathTemplate.match(projectSettingsName).project; + return this.pathTemplates.projectSettingsPathTemplate.match( + projectSettingsName, + ).project; } /** @@ -2582,7 +2998,7 @@ export class LoggingServiceV2Client { * @param {string} sink * @returns {string} Resource name string. */ - projectSinkPath(project:string,sink:string) { + projectSinkPath(project: string, sink: string) { return this.pathTemplates.projectSinkPathTemplate.render({ project: project, sink: sink, @@ -2597,7 +3013,8 @@ export class LoggingServiceV2Client { * @returns {string} A string representing the project. */ matchProjectFromProjectSinkName(projectSinkName: string) { - return this.pathTemplates.projectSinkPathTemplate.match(projectSinkName).project; + return this.pathTemplates.projectSinkPathTemplate.match(projectSinkName) + .project; } /** @@ -2608,7 +3025,8 @@ export class LoggingServiceV2Client { * @returns {string} A string representing the sink. */ matchSinkFromProjectSinkName(projectSinkName: string) { - return this.pathTemplates.projectSinkPathTemplate.match(projectSinkName).sink; + return this.pathTemplates.projectSinkPathTemplate.match(projectSinkName) + .sink; } /** @@ -2619,7 +3037,7 @@ export class LoggingServiceV2Client { */ close(): Promise { if (this.loggingServiceV2Stub && !this._terminated) { - return this.loggingServiceV2Stub.then(stub => { + return this.loggingServiceV2Stub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -2627,4 +3045,4 @@ export class LoggingServiceV2Client { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/core/generator/gapic-generator-typescript/baselines/logging/src/v2/metrics_service_v2_client.ts.baseline b/core/generator/gapic-generator-typescript/baselines/logging/src/v2/metrics_service_v2_client.ts.baseline index df1cb1cc8bc2..0c5596dcdfac 100644 --- a/core/generator/gapic-generator-typescript/baselines/logging/src/v2/metrics_service_v2_client.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/logging/src/v2/metrics_service_v2_client.ts.baseline @@ -18,11 +18,18 @@ /* global window */ import type * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions, PaginationCallback, GaxCall} from 'google-gax'; -import {Transform} from 'stream'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + PaginationCallback, + GaxCall, +} from 'google-gax'; +import { Transform } from 'stream'; import * as protos from '../../protos/protos'; import jsonProtos = require('../../protos/protos.json'); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; /** * Client JSON configuration object, loaded from @@ -44,7 +51,7 @@ export class MetricsServiceV2Client { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('logging'); @@ -57,9 +64,9 @@ export class MetricsServiceV2Client { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; - metricsServiceV2Stub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; + metricsServiceV2Stub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of MetricsServiceV2Client. @@ -100,21 +107,42 @@ export class MetricsServiceV2Client { * const client = new MetricsServiceV2Client({fallback: true}, gax); * ``` */ - constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { // Ensure that options include all the required fields. const staticMembers = this.constructor as typeof MetricsServiceV2Client; - if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { - throw new Error('Please set either universe_domain or universeDomain, but not both.'); + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); } - const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; - this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; this._servicePath = 'logging.' + this._universeDomain; - const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; - const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. if (servicePath !== this._servicePath && !('scopes' in opts)) { @@ -136,7 +164,7 @@ export class MetricsServiceV2Client { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; @@ -150,10 +178,7 @@ export class MetricsServiceV2Client { } // Determine the client header string. - const clientHeader = [ - `gax/${this._gaxModule.version}`, - `gapic/${version}`, - ]; + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/${process.versions.node}`); } else { @@ -175,94 +200,97 @@ export class MetricsServiceV2Client { // Create useful helper objects for these. this.pathTemplates = { billingAccountCmekSettingsPathTemplate: new this._gaxModule.PathTemplate( - 'billingAccounts/{billing_account}/cmekSettings' + 'billingAccounts/{billing_account}/cmekSettings', ), billingAccountExclusionPathTemplate: new this._gaxModule.PathTemplate( - 'billingAccounts/{billing_account}/exclusions/{exclusion}' - ), - billingAccountLocationBucketPathTemplate: new this._gaxModule.PathTemplate( - 'billingAccounts/{billing_account}/locations/{location}/buckets/{bucket}' - ), - billingAccountLocationBucketViewPathTemplate: new this._gaxModule.PathTemplate( - 'billingAccounts/{billing_account}/locations/{location}/buckets/{bucket}/views/{view}' + 'billingAccounts/{billing_account}/exclusions/{exclusion}', ), + billingAccountLocationBucketPathTemplate: + new this._gaxModule.PathTemplate( + 'billingAccounts/{billing_account}/locations/{location}/buckets/{bucket}', + ), + billingAccountLocationBucketViewPathTemplate: + new this._gaxModule.PathTemplate( + 'billingAccounts/{billing_account}/locations/{location}/buckets/{bucket}/views/{view}', + ), billingAccountLogPathTemplate: new this._gaxModule.PathTemplate( - 'billingAccounts/{billing_account}/logs/{log}' + 'billingAccounts/{billing_account}/logs/{log}', ), billingAccountSettingsPathTemplate: new this._gaxModule.PathTemplate( - 'billingAccounts/{billing_account}/settings' + 'billingAccounts/{billing_account}/settings', ), billingAccountSinkPathTemplate: new this._gaxModule.PathTemplate( - 'billingAccounts/{billing_account}/sinks/{sink}' + 'billingAccounts/{billing_account}/sinks/{sink}', ), folderCmekSettingsPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/cmekSettings' + 'folders/{folder}/cmekSettings', ), folderExclusionPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/exclusions/{exclusion}' + 'folders/{folder}/exclusions/{exclusion}', ), folderLocationBucketPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/locations/{location}/buckets/{bucket}' + 'folders/{folder}/locations/{location}/buckets/{bucket}', ), folderLocationBucketViewPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/locations/{location}/buckets/{bucket}/views/{view}' + 'folders/{folder}/locations/{location}/buckets/{bucket}/views/{view}', ), folderLogPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/logs/{log}' + 'folders/{folder}/logs/{log}', ), folderSettingsPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/settings' + 'folders/{folder}/settings', ), folderSinkPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/sinks/{sink}' + 'folders/{folder}/sinks/{sink}', ), logMetricPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/metrics/{metric}' + 'projects/{project}/metrics/{metric}', ), organizationCmekSettingsPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/cmekSettings' + 'organizations/{organization}/cmekSettings', ), organizationExclusionPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/exclusions/{exclusion}' + 'organizations/{organization}/exclusions/{exclusion}', ), organizationLocationBucketPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/locations/{location}/buckets/{bucket}' - ), - organizationLocationBucketViewPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/locations/{location}/buckets/{bucket}/views/{view}' + 'organizations/{organization}/locations/{location}/buckets/{bucket}', ), + organizationLocationBucketViewPathTemplate: + new this._gaxModule.PathTemplate( + 'organizations/{organization}/locations/{location}/buckets/{bucket}/views/{view}', + ), organizationLogPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/logs/{log}' + 'organizations/{organization}/logs/{log}', ), organizationSettingsPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/settings' + 'organizations/{organization}/settings', ), organizationSinkPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/sinks/{sink}' + 'organizations/{organization}/sinks/{sink}', ), projectPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}' + 'projects/{project}', ), projectCmekSettingsPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/cmekSettings' + 'projects/{project}/cmekSettings', ), projectExclusionPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/exclusions/{exclusion}' + 'projects/{project}/exclusions/{exclusion}', ), projectLocationBucketPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/buckets/{bucket}' + 'projects/{project}/locations/{location}/buckets/{bucket}', ), projectLocationBucketViewPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/buckets/{bucket}/views/{view}' + 'projects/{project}/locations/{location}/buckets/{bucket}/views/{view}', ), projectLogPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/logs/{log}' + 'projects/{project}/logs/{log}', ), projectSettingsPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/settings' + 'projects/{project}/settings', ), projectSinkPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/sinks/{sink}' + 'projects/{project}/sinks/{sink}', ), }; @@ -270,14 +298,20 @@ export class MetricsServiceV2Client { // (e.g. 50 results at a time, with tokens to get subsequent // pages). Denote the keys used for pagination and results. this.descriptors.page = { - listLogMetrics: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'metrics') + listLogMetrics: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'metrics', + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.logging.v2.MetricsServiceV2', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.logging.v2.MetricsServiceV2', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + { 'x-goog-api-client': clientHeader.join(' ') }, + ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -308,37 +342,46 @@ export class MetricsServiceV2Client { // Put together the "service stub" for // google.logging.v2.MetricsServiceV2. this.metricsServiceV2Stub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.logging.v2.MetricsServiceV2') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.logging.v2.MetricsServiceV2', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.logging.v2.MetricsServiceV2, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts, + this._providedCustomServicePath, + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const metricsServiceV2StubMethods = - ['listLogMetrics', 'getLogMetric', 'createLogMetric', 'updateLogMetric', 'deleteLogMetric']; + const metricsServiceV2StubMethods = [ + 'listLogMetrics', + 'getLogMetric', + 'createLogMetric', + 'updateLogMetric', + 'deleteLogMetric', + ]; for (const methodName of metricsServiceV2StubMethods) { const callPromise = this.metricsServiceV2Stub.then( - stub => (...args: Array<{}>) => { - if (this._terminated) { - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error|null|undefined) => () => { + (stub) => + (...args: Array<{}>) => { + if (this._terminated) { + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { throw err; - }); + }, + ); - const descriptor = - this.descriptors.page[methodName] || - undefined; + const descriptor = this.descriptors.page[methodName] || undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -353,8 +396,14 @@ export class MetricsServiceV2Client { * @returns {string} The DNS address for this service. */ static get servicePath() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'logging.googleapis.com'; } @@ -365,8 +414,14 @@ export class MetricsServiceV2Client { * @returns {string} The DNS address for this service. */ static get apiEndpoint() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'logging.googleapis.com'; } @@ -402,7 +457,7 @@ export class MetricsServiceV2Client { 'https://www.googleapis.com/auth/cloud-platform.read-only', 'https://www.googleapis.com/auth/logging.admin', 'https://www.googleapis.com/auth/logging.read', - 'https://www.googleapis.com/auth/logging.write' + 'https://www.googleapis.com/auth/logging.write', ]; } @@ -412,8 +467,9 @@ export class MetricsServiceV2Client { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId(callback?: Callback): - Promise|void { + getProjectId( + callback?: Callback, + ): Promise | void { if (callback) { this.auth.getProjectId(callback); return; @@ -424,490 +480,625 @@ export class MetricsServiceV2Client { // ------------------- // -- Service calls -- // ------------------- -/** - * Gets a logs-based metric. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.metricName - * Required. The resource name of the desired metric: - * - * "projects/[PROJECT_ID]/metrics/[METRIC_ID]" - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.logging.v2.LogMetric|LogMetric}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/metrics_service_v2.get_log_metric.js - * region_tag:logging_v2_generated_MetricsServiceV2_GetLogMetric_async - */ + /** + * Gets a logs-based metric. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.metricName + * Required. The resource name of the desired metric: + * + * "projects/[PROJECT_ID]/metrics/[METRIC_ID]" + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.logging.v2.LogMetric|LogMetric}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/metrics_service_v2.get_log_metric.js + * region_tag:logging_v2_generated_MetricsServiceV2_GetLogMetric_async + */ getLogMetric( - request?: protos.google.logging.v2.IGetLogMetricRequest, - options?: CallOptions): - Promise<[ - protos.google.logging.v2.ILogMetric, - protos.google.logging.v2.IGetLogMetricRequest|undefined, {}|undefined - ]>; + request?: protos.google.logging.v2.IGetLogMetricRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.logging.v2.ILogMetric, + protos.google.logging.v2.IGetLogMetricRequest | undefined, + {} | undefined, + ] + >; getLogMetric( - request: protos.google.logging.v2.IGetLogMetricRequest, - options: CallOptions, - callback: Callback< - protos.google.logging.v2.ILogMetric, - protos.google.logging.v2.IGetLogMetricRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.logging.v2.IGetLogMetricRequest, + options: CallOptions, + callback: Callback< + protos.google.logging.v2.ILogMetric, + protos.google.logging.v2.IGetLogMetricRequest | null | undefined, + {} | null | undefined + >, + ): void; getLogMetric( - request: protos.google.logging.v2.IGetLogMetricRequest, - callback: Callback< - protos.google.logging.v2.ILogMetric, - protos.google.logging.v2.IGetLogMetricRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.logging.v2.IGetLogMetricRequest, + callback: Callback< + protos.google.logging.v2.ILogMetric, + protos.google.logging.v2.IGetLogMetricRequest | null | undefined, + {} | null | undefined + >, + ): void; getLogMetric( - request?: protos.google.logging.v2.IGetLogMetricRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.logging.v2.IGetLogMetricRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.logging.v2.ILogMetric, - protos.google.logging.v2.IGetLogMetricRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.logging.v2.ILogMetric, - protos.google.logging.v2.IGetLogMetricRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.logging.v2.ILogMetric, - protos.google.logging.v2.IGetLogMetricRequest|undefined, {}|undefined - ]>|void { + protos.google.logging.v2.IGetLogMetricRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.logging.v2.ILogMetric, + protos.google.logging.v2.IGetLogMetricRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.logging.v2.ILogMetric, + protos.google.logging.v2.IGetLogMetricRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'metric_name': request.metricName ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + metric_name: request.metricName ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getLogMetric request %j', request); - const wrappedCallback: Callback< - protos.google.logging.v2.ILogMetric, - protos.google.logging.v2.IGetLogMetricRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.logging.v2.ILogMetric, + protos.google.logging.v2.IGetLogMetricRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getLogMetric response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getLogMetric(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.logging.v2.ILogMetric, - protos.google.logging.v2.IGetLogMetricRequest|undefined, - {}|undefined - ]) => { - this._log.info('getLogMetric response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getLogMetric(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.logging.v2.ILogMetric, + protos.google.logging.v2.IGetLogMetricRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getLogMetric response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Creates a logs-based metric. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The resource name of the project in which to create the metric: - * - * "projects/[PROJECT_ID]" - * - * The new metric must be provided in the request. - * @param {google.logging.v2.LogMetric} request.metric - * Required. The new logs-based metric, which must not have an identifier that - * already exists. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.logging.v2.LogMetric|LogMetric}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/metrics_service_v2.create_log_metric.js - * region_tag:logging_v2_generated_MetricsServiceV2_CreateLogMetric_async - */ + /** + * Creates a logs-based metric. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The resource name of the project in which to create the metric: + * + * "projects/[PROJECT_ID]" + * + * The new metric must be provided in the request. + * @param {google.logging.v2.LogMetric} request.metric + * Required. The new logs-based metric, which must not have an identifier that + * already exists. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.logging.v2.LogMetric|LogMetric}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/metrics_service_v2.create_log_metric.js + * region_tag:logging_v2_generated_MetricsServiceV2_CreateLogMetric_async + */ createLogMetric( - request?: protos.google.logging.v2.ICreateLogMetricRequest, - options?: CallOptions): - Promise<[ - protos.google.logging.v2.ILogMetric, - protos.google.logging.v2.ICreateLogMetricRequest|undefined, {}|undefined - ]>; + request?: protos.google.logging.v2.ICreateLogMetricRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.logging.v2.ILogMetric, + protos.google.logging.v2.ICreateLogMetricRequest | undefined, + {} | undefined, + ] + >; createLogMetric( - request: protos.google.logging.v2.ICreateLogMetricRequest, - options: CallOptions, - callback: Callback< - protos.google.logging.v2.ILogMetric, - protos.google.logging.v2.ICreateLogMetricRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.logging.v2.ICreateLogMetricRequest, + options: CallOptions, + callback: Callback< + protos.google.logging.v2.ILogMetric, + protos.google.logging.v2.ICreateLogMetricRequest | null | undefined, + {} | null | undefined + >, + ): void; createLogMetric( - request: protos.google.logging.v2.ICreateLogMetricRequest, - callback: Callback< - protos.google.logging.v2.ILogMetric, - protos.google.logging.v2.ICreateLogMetricRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.logging.v2.ICreateLogMetricRequest, + callback: Callback< + protos.google.logging.v2.ILogMetric, + protos.google.logging.v2.ICreateLogMetricRequest | null | undefined, + {} | null | undefined + >, + ): void; createLogMetric( - request?: protos.google.logging.v2.ICreateLogMetricRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.logging.v2.ICreateLogMetricRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.logging.v2.ILogMetric, - protos.google.logging.v2.ICreateLogMetricRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.logging.v2.ILogMetric, - protos.google.logging.v2.ICreateLogMetricRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.logging.v2.ILogMetric, - protos.google.logging.v2.ICreateLogMetricRequest|undefined, {}|undefined - ]>|void { + protos.google.logging.v2.ICreateLogMetricRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.logging.v2.ILogMetric, + protos.google.logging.v2.ICreateLogMetricRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.logging.v2.ILogMetric, + protos.google.logging.v2.ICreateLogMetricRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('createLogMetric request %j', request); - const wrappedCallback: Callback< - protos.google.logging.v2.ILogMetric, - protos.google.logging.v2.ICreateLogMetricRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.logging.v2.ILogMetric, + protos.google.logging.v2.ICreateLogMetricRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createLogMetric response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.createLogMetric(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.logging.v2.ILogMetric, - protos.google.logging.v2.ICreateLogMetricRequest|undefined, - {}|undefined - ]) => { - this._log.info('createLogMetric response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createLogMetric(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.logging.v2.ILogMetric, + protos.google.logging.v2.ICreateLogMetricRequest | undefined, + {} | undefined, + ]) => { + this._log.info('createLogMetric response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Creates or updates a logs-based metric. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.metricName - * Required. The resource name of the metric to update: - * - * "projects/[PROJECT_ID]/metrics/[METRIC_ID]" - * - * The updated metric must be provided in the request and it's - * `name` field must be the same as `[METRIC_ID]` If the metric - * does not exist in `[PROJECT_ID]`, then a new metric is created. - * @param {google.logging.v2.LogMetric} request.metric - * Required. The updated metric. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.logging.v2.LogMetric|LogMetric}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/metrics_service_v2.update_log_metric.js - * region_tag:logging_v2_generated_MetricsServiceV2_UpdateLogMetric_async - */ + /** + * Creates or updates a logs-based metric. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.metricName + * Required. The resource name of the metric to update: + * + * "projects/[PROJECT_ID]/metrics/[METRIC_ID]" + * + * The updated metric must be provided in the request and it's + * `name` field must be the same as `[METRIC_ID]` If the metric + * does not exist in `[PROJECT_ID]`, then a new metric is created. + * @param {google.logging.v2.LogMetric} request.metric + * Required. The updated metric. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.logging.v2.LogMetric|LogMetric}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/metrics_service_v2.update_log_metric.js + * region_tag:logging_v2_generated_MetricsServiceV2_UpdateLogMetric_async + */ updateLogMetric( - request?: protos.google.logging.v2.IUpdateLogMetricRequest, - options?: CallOptions): - Promise<[ - protos.google.logging.v2.ILogMetric, - protos.google.logging.v2.IUpdateLogMetricRequest|undefined, {}|undefined - ]>; + request?: protos.google.logging.v2.IUpdateLogMetricRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.logging.v2.ILogMetric, + protos.google.logging.v2.IUpdateLogMetricRequest | undefined, + {} | undefined, + ] + >; updateLogMetric( - request: protos.google.logging.v2.IUpdateLogMetricRequest, - options: CallOptions, - callback: Callback< - protos.google.logging.v2.ILogMetric, - protos.google.logging.v2.IUpdateLogMetricRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.logging.v2.IUpdateLogMetricRequest, + options: CallOptions, + callback: Callback< + protos.google.logging.v2.ILogMetric, + protos.google.logging.v2.IUpdateLogMetricRequest | null | undefined, + {} | null | undefined + >, + ): void; updateLogMetric( - request: protos.google.logging.v2.IUpdateLogMetricRequest, - callback: Callback< - protos.google.logging.v2.ILogMetric, - protos.google.logging.v2.IUpdateLogMetricRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.logging.v2.IUpdateLogMetricRequest, + callback: Callback< + protos.google.logging.v2.ILogMetric, + protos.google.logging.v2.IUpdateLogMetricRequest | null | undefined, + {} | null | undefined + >, + ): void; updateLogMetric( - request?: protos.google.logging.v2.IUpdateLogMetricRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.logging.v2.IUpdateLogMetricRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.logging.v2.ILogMetric, - protos.google.logging.v2.IUpdateLogMetricRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.logging.v2.ILogMetric, - protos.google.logging.v2.IUpdateLogMetricRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.logging.v2.ILogMetric, - protos.google.logging.v2.IUpdateLogMetricRequest|undefined, {}|undefined - ]>|void { + protos.google.logging.v2.IUpdateLogMetricRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.logging.v2.ILogMetric, + protos.google.logging.v2.IUpdateLogMetricRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.logging.v2.ILogMetric, + protos.google.logging.v2.IUpdateLogMetricRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'metric_name': request.metricName ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + metric_name: request.metricName ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateLogMetric request %j', request); - const wrappedCallback: Callback< - protos.google.logging.v2.ILogMetric, - protos.google.logging.v2.IUpdateLogMetricRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.logging.v2.ILogMetric, + protos.google.logging.v2.IUpdateLogMetricRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateLogMetric response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.updateLogMetric(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.logging.v2.ILogMetric, - protos.google.logging.v2.IUpdateLogMetricRequest|undefined, - {}|undefined - ]) => { - this._log.info('updateLogMetric response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateLogMetric(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.logging.v2.ILogMetric, + protos.google.logging.v2.IUpdateLogMetricRequest | undefined, + {} | undefined, + ]) => { + this._log.info('updateLogMetric response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Deletes a logs-based metric. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.metricName - * Required. The resource name of the metric to delete: - * - * "projects/[PROJECT_ID]/metrics/[METRIC_ID]" - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/metrics_service_v2.delete_log_metric.js - * region_tag:logging_v2_generated_MetricsServiceV2_DeleteLogMetric_async - */ + /** + * Deletes a logs-based metric. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.metricName + * Required. The resource name of the metric to delete: + * + * "projects/[PROJECT_ID]/metrics/[METRIC_ID]" + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/metrics_service_v2.delete_log_metric.js + * region_tag:logging_v2_generated_MetricsServiceV2_DeleteLogMetric_async + */ deleteLogMetric( - request?: protos.google.logging.v2.IDeleteLogMetricRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.logging.v2.IDeleteLogMetricRequest|undefined, {}|undefined - ]>; + request?: protos.google.logging.v2.IDeleteLogMetricRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.logging.v2.IDeleteLogMetricRequest | undefined, + {} | undefined, + ] + >; deleteLogMetric( - request: protos.google.logging.v2.IDeleteLogMetricRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.logging.v2.IDeleteLogMetricRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.logging.v2.IDeleteLogMetricRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.logging.v2.IDeleteLogMetricRequest | null | undefined, + {} | null | undefined + >, + ): void; deleteLogMetric( - request: protos.google.logging.v2.IDeleteLogMetricRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.logging.v2.IDeleteLogMetricRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.logging.v2.IDeleteLogMetricRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.logging.v2.IDeleteLogMetricRequest | null | undefined, + {} | null | undefined + >, + ): void; deleteLogMetric( - request?: protos.google.logging.v2.IDeleteLogMetricRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.protobuf.IEmpty, - protos.google.logging.v2.IDeleteLogMetricRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.logging.v2.IDeleteLogMetricRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.logging.v2.IDeleteLogMetricRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.logging.v2.IDeleteLogMetricRequest|undefined, {}|undefined - ]>|void { + protos.google.logging.v2.IDeleteLogMetricRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + protos.google.logging.v2.IDeleteLogMetricRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.logging.v2.IDeleteLogMetricRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'metric_name': request.metricName ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + metric_name: request.metricName ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('deleteLogMetric request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.logging.v2.IDeleteLogMetricRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + protos.google.logging.v2.IDeleteLogMetricRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteLogMetric response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.deleteLogMetric(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.logging.v2.IDeleteLogMetricRequest|undefined, - {}|undefined - ]) => { - this._log.info('deleteLogMetric response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteLogMetric(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.logging.v2.IDeleteLogMetricRequest | undefined, + {} | undefined, + ]) => { + this._log.info('deleteLogMetric response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } - /** - * Lists logs-based metrics. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The name of the project containing the metrics: - * - * "projects/[PROJECT_ID]" - * @param {string} [request.pageToken] - * Optional. If present, then retrieve the next batch of results from the - * preceding call to this method. `pageToken` must be the value of - * `nextPageToken` from the previous response. The values of other method - * parameters should be identical to those in the previous call. - * @param {number} [request.pageSize] - * Optional. The maximum number of results to return from this request. - * Non-positive values are ignored. The presence of `nextPageToken` in the - * response indicates that more results might be available. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.logging.v2.LogMetric|LogMetric}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `listLogMetricsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Lists logs-based metrics. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The name of the project containing the metrics: + * + * "projects/[PROJECT_ID]" + * @param {string} [request.pageToken] + * Optional. If present, then retrieve the next batch of results from the + * preceding call to this method. `pageToken` must be the value of + * `nextPageToken` from the previous response. The values of other method + * parameters should be identical to those in the previous call. + * @param {number} [request.pageSize] + * Optional. The maximum number of results to return from this request. + * Non-positive values are ignored. The presence of `nextPageToken` in the + * response indicates that more results might be available. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.logging.v2.LogMetric|LogMetric}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listLogMetricsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listLogMetrics( - request?: protos.google.logging.v2.IListLogMetricsRequest, - options?: CallOptions): - Promise<[ - protos.google.logging.v2.ILogMetric[], - protos.google.logging.v2.IListLogMetricsRequest|null, - protos.google.logging.v2.IListLogMetricsResponse - ]>; + request?: protos.google.logging.v2.IListLogMetricsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.logging.v2.ILogMetric[], + protos.google.logging.v2.IListLogMetricsRequest | null, + protos.google.logging.v2.IListLogMetricsResponse, + ] + >; listLogMetrics( - request: protos.google.logging.v2.IListLogMetricsRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.logging.v2.IListLogMetricsRequest, - protos.google.logging.v2.IListLogMetricsResponse|null|undefined, - protos.google.logging.v2.ILogMetric>): void; + request: protos.google.logging.v2.IListLogMetricsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.logging.v2.IListLogMetricsRequest, + protos.google.logging.v2.IListLogMetricsResponse | null | undefined, + protos.google.logging.v2.ILogMetric + >, + ): void; listLogMetrics( - request: protos.google.logging.v2.IListLogMetricsRequest, - callback: PaginationCallback< - protos.google.logging.v2.IListLogMetricsRequest, - protos.google.logging.v2.IListLogMetricsResponse|null|undefined, - protos.google.logging.v2.ILogMetric>): void; + request: protos.google.logging.v2.IListLogMetricsRequest, + callback: PaginationCallback< + protos.google.logging.v2.IListLogMetricsRequest, + protos.google.logging.v2.IListLogMetricsResponse | null | undefined, + protos.google.logging.v2.ILogMetric + >, + ): void; listLogMetrics( - request?: protos.google.logging.v2.IListLogMetricsRequest, - optionsOrCallback?: CallOptions|PaginationCallback< - protos.google.logging.v2.IListLogMetricsRequest, - protos.google.logging.v2.IListLogMetricsResponse|null|undefined, - protos.google.logging.v2.ILogMetric>, - callback?: PaginationCallback< + request?: protos.google.logging.v2.IListLogMetricsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.logging.v2.IListLogMetricsRequest, - protos.google.logging.v2.IListLogMetricsResponse|null|undefined, - protos.google.logging.v2.ILogMetric>): - Promise<[ - protos.google.logging.v2.ILogMetric[], - protos.google.logging.v2.IListLogMetricsRequest|null, - protos.google.logging.v2.IListLogMetricsResponse - ]>|void { + protos.google.logging.v2.IListLogMetricsResponse | null | undefined, + protos.google.logging.v2.ILogMetric + >, + callback?: PaginationCallback< + protos.google.logging.v2.IListLogMetricsRequest, + protos.google.logging.v2.IListLogMetricsResponse | null | undefined, + protos.google.logging.v2.ILogMetric + >, + ): Promise< + [ + protos.google.logging.v2.ILogMetric[], + protos.google.logging.v2.IListLogMetricsRequest | null, + protos.google.logging.v2.IListLogMetricsResponse, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.logging.v2.IListLogMetricsRequest, - protos.google.logging.v2.IListLogMetricsResponse|null|undefined, - protos.google.logging.v2.ILogMetric>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.logging.v2.IListLogMetricsRequest, + protos.google.logging.v2.IListLogMetricsResponse | null | undefined, + protos.google.logging.v2.ILogMetric + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listLogMetrics values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -916,120 +1107,124 @@ export class MetricsServiceV2Client { this._log.info('listLogMetrics request %j', request); return this.innerApiCalls .listLogMetrics(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.logging.v2.ILogMetric[], - protos.google.logging.v2.IListLogMetricsRequest|null, - protos.google.logging.v2.IListLogMetricsResponse - ]) => { - this._log.info('listLogMetrics values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.logging.v2.ILogMetric[], + protos.google.logging.v2.IListLogMetricsRequest | null, + protos.google.logging.v2.IListLogMetricsResponse, + ]) => { + this._log.info('listLogMetrics values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listLogMetrics`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The name of the project containing the metrics: - * - * "projects/[PROJECT_ID]" - * @param {string} [request.pageToken] - * Optional. If present, then retrieve the next batch of results from the - * preceding call to this method. `pageToken` must be the value of - * `nextPageToken` from the previous response. The values of other method - * parameters should be identical to those in the previous call. - * @param {number} [request.pageSize] - * Optional. The maximum number of results to return from this request. - * Non-positive values are ignored. The presence of `nextPageToken` in the - * response indicates that more results might be available. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.logging.v2.LogMetric|LogMetric} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `listLogMetricsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `listLogMetrics`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The name of the project containing the metrics: + * + * "projects/[PROJECT_ID]" + * @param {string} [request.pageToken] + * Optional. If present, then retrieve the next batch of results from the + * preceding call to this method. `pageToken` must be the value of + * `nextPageToken` from the previous response. The values of other method + * parameters should be identical to those in the previous call. + * @param {number} [request.pageSize] + * Optional. The maximum number of results to return from this request. + * Non-positive values are ignored. The presence of `nextPageToken` in the + * response indicates that more results might be available. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.logging.v2.LogMetric|LogMetric} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listLogMetricsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listLogMetricsStream( - request?: protos.google.logging.v2.IListLogMetricsRequest, - options?: CallOptions): - Transform{ + request?: protos.google.logging.v2.IListLogMetricsRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); const defaultCallSettings = this._defaults['listLogMetrics']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listLogMetrics stream %j', request); return this.descriptors.page.listLogMetrics.createStream( this.innerApiCalls.listLogMetrics as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listLogMetrics`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The name of the project containing the metrics: - * - * "projects/[PROJECT_ID]" - * @param {string} [request.pageToken] - * Optional. If present, then retrieve the next batch of results from the - * preceding call to this method. `pageToken` must be the value of - * `nextPageToken` from the previous response. The values of other method - * parameters should be identical to those in the previous call. - * @param {number} [request.pageSize] - * Optional. The maximum number of results to return from this request. - * Non-positive values are ignored. The presence of `nextPageToken` in the - * response indicates that more results might be available. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.logging.v2.LogMetric|LogMetric}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v2/metrics_service_v2.list_log_metrics.js - * region_tag:logging_v2_generated_MetricsServiceV2_ListLogMetrics_async - */ + /** + * Equivalent to `listLogMetrics`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The name of the project containing the metrics: + * + * "projects/[PROJECT_ID]" + * @param {string} [request.pageToken] + * Optional. If present, then retrieve the next batch of results from the + * preceding call to this method. `pageToken` must be the value of + * `nextPageToken` from the previous response. The values of other method + * parameters should be identical to those in the previous call. + * @param {number} [request.pageSize] + * Optional. The maximum number of results to return from this request. + * Non-positive values are ignored. The presence of `nextPageToken` in the + * response indicates that more results might be available. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.logging.v2.LogMetric|LogMetric}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v2/metrics_service_v2.list_log_metrics.js + * region_tag:logging_v2_generated_MetricsServiceV2_ListLogMetrics_async + */ listLogMetricsAsync( - request?: protos.google.logging.v2.IListLogMetricsRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.logging.v2.IListLogMetricsRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); const defaultCallSettings = this._defaults['listLogMetrics']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listLogMetrics iterate %j', request); return this.descriptors.page.listLogMetrics.asyncIterate( this.innerApiCalls['listLogMetrics'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } // -------------------- @@ -1042,7 +1237,7 @@ export class MetricsServiceV2Client { * @param {string} billing_account * @returns {string} Resource name string. */ - billingAccountCmekSettingsPath(billingAccount:string) { + billingAccountCmekSettingsPath(billingAccount: string) { return this.pathTemplates.billingAccountCmekSettingsPathTemplate.render({ billing_account: billingAccount, }); @@ -1055,8 +1250,12 @@ export class MetricsServiceV2Client { * A fully-qualified path representing billing_account_cmekSettings resource. * @returns {string} A string representing the billing_account. */ - matchBillingAccountFromBillingAccountCmekSettingsName(billingAccountCmekSettingsName: string) { - return this.pathTemplates.billingAccountCmekSettingsPathTemplate.match(billingAccountCmekSettingsName).billing_account; + matchBillingAccountFromBillingAccountCmekSettingsName( + billingAccountCmekSettingsName: string, + ) { + return this.pathTemplates.billingAccountCmekSettingsPathTemplate.match( + billingAccountCmekSettingsName, + ).billing_account; } /** @@ -1066,7 +1265,7 @@ export class MetricsServiceV2Client { * @param {string} exclusion * @returns {string} Resource name string. */ - billingAccountExclusionPath(billingAccount:string,exclusion:string) { + billingAccountExclusionPath(billingAccount: string, exclusion: string) { return this.pathTemplates.billingAccountExclusionPathTemplate.render({ billing_account: billingAccount, exclusion: exclusion, @@ -1080,8 +1279,12 @@ export class MetricsServiceV2Client { * A fully-qualified path representing billing_account_exclusion resource. * @returns {string} A string representing the billing_account. */ - matchBillingAccountFromBillingAccountExclusionName(billingAccountExclusionName: string) { - return this.pathTemplates.billingAccountExclusionPathTemplate.match(billingAccountExclusionName).billing_account; + matchBillingAccountFromBillingAccountExclusionName( + billingAccountExclusionName: string, + ) { + return this.pathTemplates.billingAccountExclusionPathTemplate.match( + billingAccountExclusionName, + ).billing_account; } /** @@ -1091,8 +1294,12 @@ export class MetricsServiceV2Client { * A fully-qualified path representing billing_account_exclusion resource. * @returns {string} A string representing the exclusion. */ - matchExclusionFromBillingAccountExclusionName(billingAccountExclusionName: string) { - return this.pathTemplates.billingAccountExclusionPathTemplate.match(billingAccountExclusionName).exclusion; + matchExclusionFromBillingAccountExclusionName( + billingAccountExclusionName: string, + ) { + return this.pathTemplates.billingAccountExclusionPathTemplate.match( + billingAccountExclusionName, + ).exclusion; } /** @@ -1103,7 +1310,11 @@ export class MetricsServiceV2Client { * @param {string} bucket * @returns {string} Resource name string. */ - billingAccountLocationBucketPath(billingAccount:string,location:string,bucket:string) { + billingAccountLocationBucketPath( + billingAccount: string, + location: string, + bucket: string, + ) { return this.pathTemplates.billingAccountLocationBucketPathTemplate.render({ billing_account: billingAccount, location: location, @@ -1118,8 +1329,12 @@ export class MetricsServiceV2Client { * A fully-qualified path representing billing_account_location_bucket resource. * @returns {string} A string representing the billing_account. */ - matchBillingAccountFromBillingAccountLocationBucketName(billingAccountLocationBucketName: string) { - return this.pathTemplates.billingAccountLocationBucketPathTemplate.match(billingAccountLocationBucketName).billing_account; + matchBillingAccountFromBillingAccountLocationBucketName( + billingAccountLocationBucketName: string, + ) { + return this.pathTemplates.billingAccountLocationBucketPathTemplate.match( + billingAccountLocationBucketName, + ).billing_account; } /** @@ -1129,8 +1344,12 @@ export class MetricsServiceV2Client { * A fully-qualified path representing billing_account_location_bucket resource. * @returns {string} A string representing the location. */ - matchLocationFromBillingAccountLocationBucketName(billingAccountLocationBucketName: string) { - return this.pathTemplates.billingAccountLocationBucketPathTemplate.match(billingAccountLocationBucketName).location; + matchLocationFromBillingAccountLocationBucketName( + billingAccountLocationBucketName: string, + ) { + return this.pathTemplates.billingAccountLocationBucketPathTemplate.match( + billingAccountLocationBucketName, + ).location; } /** @@ -1140,8 +1359,12 @@ export class MetricsServiceV2Client { * A fully-qualified path representing billing_account_location_bucket resource. * @returns {string} A string representing the bucket. */ - matchBucketFromBillingAccountLocationBucketName(billingAccountLocationBucketName: string) { - return this.pathTemplates.billingAccountLocationBucketPathTemplate.match(billingAccountLocationBucketName).bucket; + matchBucketFromBillingAccountLocationBucketName( + billingAccountLocationBucketName: string, + ) { + return this.pathTemplates.billingAccountLocationBucketPathTemplate.match( + billingAccountLocationBucketName, + ).bucket; } /** @@ -1153,13 +1376,20 @@ export class MetricsServiceV2Client { * @param {string} view * @returns {string} Resource name string. */ - billingAccountLocationBucketViewPath(billingAccount:string,location:string,bucket:string,view:string) { - return this.pathTemplates.billingAccountLocationBucketViewPathTemplate.render({ - billing_account: billingAccount, - location: location, - bucket: bucket, - view: view, - }); + billingAccountLocationBucketViewPath( + billingAccount: string, + location: string, + bucket: string, + view: string, + ) { + return this.pathTemplates.billingAccountLocationBucketViewPathTemplate.render( + { + billing_account: billingAccount, + location: location, + bucket: bucket, + view: view, + }, + ); } /** @@ -1169,8 +1399,12 @@ export class MetricsServiceV2Client { * A fully-qualified path representing billing_account_location_bucket_view resource. * @returns {string} A string representing the billing_account. */ - matchBillingAccountFromBillingAccountLocationBucketViewName(billingAccountLocationBucketViewName: string) { - return this.pathTemplates.billingAccountLocationBucketViewPathTemplate.match(billingAccountLocationBucketViewName).billing_account; + matchBillingAccountFromBillingAccountLocationBucketViewName( + billingAccountLocationBucketViewName: string, + ) { + return this.pathTemplates.billingAccountLocationBucketViewPathTemplate.match( + billingAccountLocationBucketViewName, + ).billing_account; } /** @@ -1180,8 +1414,12 @@ export class MetricsServiceV2Client { * A fully-qualified path representing billing_account_location_bucket_view resource. * @returns {string} A string representing the location. */ - matchLocationFromBillingAccountLocationBucketViewName(billingAccountLocationBucketViewName: string) { - return this.pathTemplates.billingAccountLocationBucketViewPathTemplate.match(billingAccountLocationBucketViewName).location; + matchLocationFromBillingAccountLocationBucketViewName( + billingAccountLocationBucketViewName: string, + ) { + return this.pathTemplates.billingAccountLocationBucketViewPathTemplate.match( + billingAccountLocationBucketViewName, + ).location; } /** @@ -1191,8 +1429,12 @@ export class MetricsServiceV2Client { * A fully-qualified path representing billing_account_location_bucket_view resource. * @returns {string} A string representing the bucket. */ - matchBucketFromBillingAccountLocationBucketViewName(billingAccountLocationBucketViewName: string) { - return this.pathTemplates.billingAccountLocationBucketViewPathTemplate.match(billingAccountLocationBucketViewName).bucket; + matchBucketFromBillingAccountLocationBucketViewName( + billingAccountLocationBucketViewName: string, + ) { + return this.pathTemplates.billingAccountLocationBucketViewPathTemplate.match( + billingAccountLocationBucketViewName, + ).bucket; } /** @@ -1202,8 +1444,12 @@ export class MetricsServiceV2Client { * A fully-qualified path representing billing_account_location_bucket_view resource. * @returns {string} A string representing the view. */ - matchViewFromBillingAccountLocationBucketViewName(billingAccountLocationBucketViewName: string) { - return this.pathTemplates.billingAccountLocationBucketViewPathTemplate.match(billingAccountLocationBucketViewName).view; + matchViewFromBillingAccountLocationBucketViewName( + billingAccountLocationBucketViewName: string, + ) { + return this.pathTemplates.billingAccountLocationBucketViewPathTemplate.match( + billingAccountLocationBucketViewName, + ).view; } /** @@ -1213,7 +1459,7 @@ export class MetricsServiceV2Client { * @param {string} log * @returns {string} Resource name string. */ - billingAccountLogPath(billingAccount:string,log:string) { + billingAccountLogPath(billingAccount: string, log: string) { return this.pathTemplates.billingAccountLogPathTemplate.render({ billing_account: billingAccount, log: log, @@ -1228,7 +1474,9 @@ export class MetricsServiceV2Client { * @returns {string} A string representing the billing_account. */ matchBillingAccountFromBillingAccountLogName(billingAccountLogName: string) { - return this.pathTemplates.billingAccountLogPathTemplate.match(billingAccountLogName).billing_account; + return this.pathTemplates.billingAccountLogPathTemplate.match( + billingAccountLogName, + ).billing_account; } /** @@ -1239,7 +1487,9 @@ export class MetricsServiceV2Client { * @returns {string} A string representing the log. */ matchLogFromBillingAccountLogName(billingAccountLogName: string) { - return this.pathTemplates.billingAccountLogPathTemplate.match(billingAccountLogName).log; + return this.pathTemplates.billingAccountLogPathTemplate.match( + billingAccountLogName, + ).log; } /** @@ -1248,7 +1498,7 @@ export class MetricsServiceV2Client { * @param {string} billing_account * @returns {string} Resource name string. */ - billingAccountSettingsPath(billingAccount:string) { + billingAccountSettingsPath(billingAccount: string) { return this.pathTemplates.billingAccountSettingsPathTemplate.render({ billing_account: billingAccount, }); @@ -1261,8 +1511,12 @@ export class MetricsServiceV2Client { * A fully-qualified path representing billing_account_settings resource. * @returns {string} A string representing the billing_account. */ - matchBillingAccountFromBillingAccountSettingsName(billingAccountSettingsName: string) { - return this.pathTemplates.billingAccountSettingsPathTemplate.match(billingAccountSettingsName).billing_account; + matchBillingAccountFromBillingAccountSettingsName( + billingAccountSettingsName: string, + ) { + return this.pathTemplates.billingAccountSettingsPathTemplate.match( + billingAccountSettingsName, + ).billing_account; } /** @@ -1272,7 +1526,7 @@ export class MetricsServiceV2Client { * @param {string} sink * @returns {string} Resource name string. */ - billingAccountSinkPath(billingAccount:string,sink:string) { + billingAccountSinkPath(billingAccount: string, sink: string) { return this.pathTemplates.billingAccountSinkPathTemplate.render({ billing_account: billingAccount, sink: sink, @@ -1286,8 +1540,12 @@ export class MetricsServiceV2Client { * A fully-qualified path representing billing_account_sink resource. * @returns {string} A string representing the billing_account. */ - matchBillingAccountFromBillingAccountSinkName(billingAccountSinkName: string) { - return this.pathTemplates.billingAccountSinkPathTemplate.match(billingAccountSinkName).billing_account; + matchBillingAccountFromBillingAccountSinkName( + billingAccountSinkName: string, + ) { + return this.pathTemplates.billingAccountSinkPathTemplate.match( + billingAccountSinkName, + ).billing_account; } /** @@ -1298,7 +1556,9 @@ export class MetricsServiceV2Client { * @returns {string} A string representing the sink. */ matchSinkFromBillingAccountSinkName(billingAccountSinkName: string) { - return this.pathTemplates.billingAccountSinkPathTemplate.match(billingAccountSinkName).sink; + return this.pathTemplates.billingAccountSinkPathTemplate.match( + billingAccountSinkName, + ).sink; } /** @@ -1307,7 +1567,7 @@ export class MetricsServiceV2Client { * @param {string} folder * @returns {string} Resource name string. */ - folderCmekSettingsPath(folder:string) { + folderCmekSettingsPath(folder: string) { return this.pathTemplates.folderCmekSettingsPathTemplate.render({ folder: folder, }); @@ -1321,7 +1581,9 @@ export class MetricsServiceV2Client { * @returns {string} A string representing the folder. */ matchFolderFromFolderCmekSettingsName(folderCmekSettingsName: string) { - return this.pathTemplates.folderCmekSettingsPathTemplate.match(folderCmekSettingsName).folder; + return this.pathTemplates.folderCmekSettingsPathTemplate.match( + folderCmekSettingsName, + ).folder; } /** @@ -1331,7 +1593,7 @@ export class MetricsServiceV2Client { * @param {string} exclusion * @returns {string} Resource name string. */ - folderExclusionPath(folder:string,exclusion:string) { + folderExclusionPath(folder: string, exclusion: string) { return this.pathTemplates.folderExclusionPathTemplate.render({ folder: folder, exclusion: exclusion, @@ -1346,7 +1608,9 @@ export class MetricsServiceV2Client { * @returns {string} A string representing the folder. */ matchFolderFromFolderExclusionName(folderExclusionName: string) { - return this.pathTemplates.folderExclusionPathTemplate.match(folderExclusionName).folder; + return this.pathTemplates.folderExclusionPathTemplate.match( + folderExclusionName, + ).folder; } /** @@ -1357,7 +1621,9 @@ export class MetricsServiceV2Client { * @returns {string} A string representing the exclusion. */ matchExclusionFromFolderExclusionName(folderExclusionName: string) { - return this.pathTemplates.folderExclusionPathTemplate.match(folderExclusionName).exclusion; + return this.pathTemplates.folderExclusionPathTemplate.match( + folderExclusionName, + ).exclusion; } /** @@ -1368,7 +1634,7 @@ export class MetricsServiceV2Client { * @param {string} bucket * @returns {string} Resource name string. */ - folderLocationBucketPath(folder:string,location:string,bucket:string) { + folderLocationBucketPath(folder: string, location: string, bucket: string) { return this.pathTemplates.folderLocationBucketPathTemplate.render({ folder: folder, location: location, @@ -1384,7 +1650,9 @@ export class MetricsServiceV2Client { * @returns {string} A string representing the folder. */ matchFolderFromFolderLocationBucketName(folderLocationBucketName: string) { - return this.pathTemplates.folderLocationBucketPathTemplate.match(folderLocationBucketName).folder; + return this.pathTemplates.folderLocationBucketPathTemplate.match( + folderLocationBucketName, + ).folder; } /** @@ -1395,7 +1663,9 @@ export class MetricsServiceV2Client { * @returns {string} A string representing the location. */ matchLocationFromFolderLocationBucketName(folderLocationBucketName: string) { - return this.pathTemplates.folderLocationBucketPathTemplate.match(folderLocationBucketName).location; + return this.pathTemplates.folderLocationBucketPathTemplate.match( + folderLocationBucketName, + ).location; } /** @@ -1406,7 +1676,9 @@ export class MetricsServiceV2Client { * @returns {string} A string representing the bucket. */ matchBucketFromFolderLocationBucketName(folderLocationBucketName: string) { - return this.pathTemplates.folderLocationBucketPathTemplate.match(folderLocationBucketName).bucket; + return this.pathTemplates.folderLocationBucketPathTemplate.match( + folderLocationBucketName, + ).bucket; } /** @@ -1418,7 +1690,12 @@ export class MetricsServiceV2Client { * @param {string} view * @returns {string} Resource name string. */ - folderLocationBucketViewPath(folder:string,location:string,bucket:string,view:string) { + folderLocationBucketViewPath( + folder: string, + location: string, + bucket: string, + view: string, + ) { return this.pathTemplates.folderLocationBucketViewPathTemplate.render({ folder: folder, location: location, @@ -1434,8 +1711,12 @@ export class MetricsServiceV2Client { * A fully-qualified path representing folder_location_bucket_view resource. * @returns {string} A string representing the folder. */ - matchFolderFromFolderLocationBucketViewName(folderLocationBucketViewName: string) { - return this.pathTemplates.folderLocationBucketViewPathTemplate.match(folderLocationBucketViewName).folder; + matchFolderFromFolderLocationBucketViewName( + folderLocationBucketViewName: string, + ) { + return this.pathTemplates.folderLocationBucketViewPathTemplate.match( + folderLocationBucketViewName, + ).folder; } /** @@ -1445,8 +1726,12 @@ export class MetricsServiceV2Client { * A fully-qualified path representing folder_location_bucket_view resource. * @returns {string} A string representing the location. */ - matchLocationFromFolderLocationBucketViewName(folderLocationBucketViewName: string) { - return this.pathTemplates.folderLocationBucketViewPathTemplate.match(folderLocationBucketViewName).location; + matchLocationFromFolderLocationBucketViewName( + folderLocationBucketViewName: string, + ) { + return this.pathTemplates.folderLocationBucketViewPathTemplate.match( + folderLocationBucketViewName, + ).location; } /** @@ -1456,8 +1741,12 @@ export class MetricsServiceV2Client { * A fully-qualified path representing folder_location_bucket_view resource. * @returns {string} A string representing the bucket. */ - matchBucketFromFolderLocationBucketViewName(folderLocationBucketViewName: string) { - return this.pathTemplates.folderLocationBucketViewPathTemplate.match(folderLocationBucketViewName).bucket; + matchBucketFromFolderLocationBucketViewName( + folderLocationBucketViewName: string, + ) { + return this.pathTemplates.folderLocationBucketViewPathTemplate.match( + folderLocationBucketViewName, + ).bucket; } /** @@ -1467,8 +1756,12 @@ export class MetricsServiceV2Client { * A fully-qualified path representing folder_location_bucket_view resource. * @returns {string} A string representing the view. */ - matchViewFromFolderLocationBucketViewName(folderLocationBucketViewName: string) { - return this.pathTemplates.folderLocationBucketViewPathTemplate.match(folderLocationBucketViewName).view; + matchViewFromFolderLocationBucketViewName( + folderLocationBucketViewName: string, + ) { + return this.pathTemplates.folderLocationBucketViewPathTemplate.match( + folderLocationBucketViewName, + ).view; } /** @@ -1478,7 +1771,7 @@ export class MetricsServiceV2Client { * @param {string} log * @returns {string} Resource name string. */ - folderLogPath(folder:string,log:string) { + folderLogPath(folder: string, log: string) { return this.pathTemplates.folderLogPathTemplate.render({ folder: folder, log: log, @@ -1513,7 +1806,7 @@ export class MetricsServiceV2Client { * @param {string} folder * @returns {string} Resource name string. */ - folderSettingsPath(folder:string) { + folderSettingsPath(folder: string) { return this.pathTemplates.folderSettingsPathTemplate.render({ folder: folder, }); @@ -1527,7 +1820,9 @@ export class MetricsServiceV2Client { * @returns {string} A string representing the folder. */ matchFolderFromFolderSettingsName(folderSettingsName: string) { - return this.pathTemplates.folderSettingsPathTemplate.match(folderSettingsName).folder; + return this.pathTemplates.folderSettingsPathTemplate.match( + folderSettingsName, + ).folder; } /** @@ -1537,7 +1832,7 @@ export class MetricsServiceV2Client { * @param {string} sink * @returns {string} Resource name string. */ - folderSinkPath(folder:string,sink:string) { + folderSinkPath(folder: string, sink: string) { return this.pathTemplates.folderSinkPathTemplate.render({ folder: folder, sink: sink, @@ -1552,7 +1847,8 @@ export class MetricsServiceV2Client { * @returns {string} A string representing the folder. */ matchFolderFromFolderSinkName(folderSinkName: string) { - return this.pathTemplates.folderSinkPathTemplate.match(folderSinkName).folder; + return this.pathTemplates.folderSinkPathTemplate.match(folderSinkName) + .folder; } /** @@ -1573,7 +1869,7 @@ export class MetricsServiceV2Client { * @param {string} metric * @returns {string} Resource name string. */ - logMetricPath(project:string,metric:string) { + logMetricPath(project: string, metric: string) { return this.pathTemplates.logMetricPathTemplate.render({ project: project, metric: metric, @@ -1588,7 +1884,8 @@ export class MetricsServiceV2Client { * @returns {string} A string representing the project. */ matchProjectFromLogMetricName(logMetricName: string) { - return this.pathTemplates.logMetricPathTemplate.match(logMetricName).project; + return this.pathTemplates.logMetricPathTemplate.match(logMetricName) + .project; } /** @@ -1608,7 +1905,7 @@ export class MetricsServiceV2Client { * @param {string} organization * @returns {string} Resource name string. */ - organizationCmekSettingsPath(organization:string) { + organizationCmekSettingsPath(organization: string) { return this.pathTemplates.organizationCmekSettingsPathTemplate.render({ organization: organization, }); @@ -1621,8 +1918,12 @@ export class MetricsServiceV2Client { * A fully-qualified path representing organization_cmekSettings resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationCmekSettingsName(organizationCmekSettingsName: string) { - return this.pathTemplates.organizationCmekSettingsPathTemplate.match(organizationCmekSettingsName).organization; + matchOrganizationFromOrganizationCmekSettingsName( + organizationCmekSettingsName: string, + ) { + return this.pathTemplates.organizationCmekSettingsPathTemplate.match( + organizationCmekSettingsName, + ).organization; } /** @@ -1632,7 +1933,7 @@ export class MetricsServiceV2Client { * @param {string} exclusion * @returns {string} Resource name string. */ - organizationExclusionPath(organization:string,exclusion:string) { + organizationExclusionPath(organization: string, exclusion: string) { return this.pathTemplates.organizationExclusionPathTemplate.render({ organization: organization, exclusion: exclusion, @@ -1646,8 +1947,12 @@ export class MetricsServiceV2Client { * A fully-qualified path representing organization_exclusion resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationExclusionName(organizationExclusionName: string) { - return this.pathTemplates.organizationExclusionPathTemplate.match(organizationExclusionName).organization; + matchOrganizationFromOrganizationExclusionName( + organizationExclusionName: string, + ) { + return this.pathTemplates.organizationExclusionPathTemplate.match( + organizationExclusionName, + ).organization; } /** @@ -1657,8 +1962,12 @@ export class MetricsServiceV2Client { * A fully-qualified path representing organization_exclusion resource. * @returns {string} A string representing the exclusion. */ - matchExclusionFromOrganizationExclusionName(organizationExclusionName: string) { - return this.pathTemplates.organizationExclusionPathTemplate.match(organizationExclusionName).exclusion; + matchExclusionFromOrganizationExclusionName( + organizationExclusionName: string, + ) { + return this.pathTemplates.organizationExclusionPathTemplate.match( + organizationExclusionName, + ).exclusion; } /** @@ -1669,7 +1978,11 @@ export class MetricsServiceV2Client { * @param {string} bucket * @returns {string} Resource name string. */ - organizationLocationBucketPath(organization:string,location:string,bucket:string) { + organizationLocationBucketPath( + organization: string, + location: string, + bucket: string, + ) { return this.pathTemplates.organizationLocationBucketPathTemplate.render({ organization: organization, location: location, @@ -1684,8 +1997,12 @@ export class MetricsServiceV2Client { * A fully-qualified path representing organization_location_bucket resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationLocationBucketName(organizationLocationBucketName: string) { - return this.pathTemplates.organizationLocationBucketPathTemplate.match(organizationLocationBucketName).organization; + matchOrganizationFromOrganizationLocationBucketName( + organizationLocationBucketName: string, + ) { + return this.pathTemplates.organizationLocationBucketPathTemplate.match( + organizationLocationBucketName, + ).organization; } /** @@ -1695,8 +2012,12 @@ export class MetricsServiceV2Client { * A fully-qualified path representing organization_location_bucket resource. * @returns {string} A string representing the location. */ - matchLocationFromOrganizationLocationBucketName(organizationLocationBucketName: string) { - return this.pathTemplates.organizationLocationBucketPathTemplate.match(organizationLocationBucketName).location; + matchLocationFromOrganizationLocationBucketName( + organizationLocationBucketName: string, + ) { + return this.pathTemplates.organizationLocationBucketPathTemplate.match( + organizationLocationBucketName, + ).location; } /** @@ -1706,8 +2027,12 @@ export class MetricsServiceV2Client { * A fully-qualified path representing organization_location_bucket resource. * @returns {string} A string representing the bucket. */ - matchBucketFromOrganizationLocationBucketName(organizationLocationBucketName: string) { - return this.pathTemplates.organizationLocationBucketPathTemplate.match(organizationLocationBucketName).bucket; + matchBucketFromOrganizationLocationBucketName( + organizationLocationBucketName: string, + ) { + return this.pathTemplates.organizationLocationBucketPathTemplate.match( + organizationLocationBucketName, + ).bucket; } /** @@ -1719,13 +2044,20 @@ export class MetricsServiceV2Client { * @param {string} view * @returns {string} Resource name string. */ - organizationLocationBucketViewPath(organization:string,location:string,bucket:string,view:string) { - return this.pathTemplates.organizationLocationBucketViewPathTemplate.render({ - organization: organization, - location: location, - bucket: bucket, - view: view, - }); + organizationLocationBucketViewPath( + organization: string, + location: string, + bucket: string, + view: string, + ) { + return this.pathTemplates.organizationLocationBucketViewPathTemplate.render( + { + organization: organization, + location: location, + bucket: bucket, + view: view, + }, + ); } /** @@ -1735,8 +2067,12 @@ export class MetricsServiceV2Client { * A fully-qualified path representing organization_location_bucket_view resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationLocationBucketViewName(organizationLocationBucketViewName: string) { - return this.pathTemplates.organizationLocationBucketViewPathTemplate.match(organizationLocationBucketViewName).organization; + matchOrganizationFromOrganizationLocationBucketViewName( + organizationLocationBucketViewName: string, + ) { + return this.pathTemplates.organizationLocationBucketViewPathTemplate.match( + organizationLocationBucketViewName, + ).organization; } /** @@ -1746,8 +2082,12 @@ export class MetricsServiceV2Client { * A fully-qualified path representing organization_location_bucket_view resource. * @returns {string} A string representing the location. */ - matchLocationFromOrganizationLocationBucketViewName(organizationLocationBucketViewName: string) { - return this.pathTemplates.organizationLocationBucketViewPathTemplate.match(organizationLocationBucketViewName).location; + matchLocationFromOrganizationLocationBucketViewName( + organizationLocationBucketViewName: string, + ) { + return this.pathTemplates.organizationLocationBucketViewPathTemplate.match( + organizationLocationBucketViewName, + ).location; } /** @@ -1757,8 +2097,12 @@ export class MetricsServiceV2Client { * A fully-qualified path representing organization_location_bucket_view resource. * @returns {string} A string representing the bucket. */ - matchBucketFromOrganizationLocationBucketViewName(organizationLocationBucketViewName: string) { - return this.pathTemplates.organizationLocationBucketViewPathTemplate.match(organizationLocationBucketViewName).bucket; + matchBucketFromOrganizationLocationBucketViewName( + organizationLocationBucketViewName: string, + ) { + return this.pathTemplates.organizationLocationBucketViewPathTemplate.match( + organizationLocationBucketViewName, + ).bucket; } /** @@ -1768,8 +2112,12 @@ export class MetricsServiceV2Client { * A fully-qualified path representing organization_location_bucket_view resource. * @returns {string} A string representing the view. */ - matchViewFromOrganizationLocationBucketViewName(organizationLocationBucketViewName: string) { - return this.pathTemplates.organizationLocationBucketViewPathTemplate.match(organizationLocationBucketViewName).view; + matchViewFromOrganizationLocationBucketViewName( + organizationLocationBucketViewName: string, + ) { + return this.pathTemplates.organizationLocationBucketViewPathTemplate.match( + organizationLocationBucketViewName, + ).view; } /** @@ -1779,7 +2127,7 @@ export class MetricsServiceV2Client { * @param {string} log * @returns {string} Resource name string. */ - organizationLogPath(organization:string,log:string) { + organizationLogPath(organization: string, log: string) { return this.pathTemplates.organizationLogPathTemplate.render({ organization: organization, log: log, @@ -1794,7 +2142,9 @@ export class MetricsServiceV2Client { * @returns {string} A string representing the organization. */ matchOrganizationFromOrganizationLogName(organizationLogName: string) { - return this.pathTemplates.organizationLogPathTemplate.match(organizationLogName).organization; + return this.pathTemplates.organizationLogPathTemplate.match( + organizationLogName, + ).organization; } /** @@ -1805,7 +2155,9 @@ export class MetricsServiceV2Client { * @returns {string} A string representing the log. */ matchLogFromOrganizationLogName(organizationLogName: string) { - return this.pathTemplates.organizationLogPathTemplate.match(organizationLogName).log; + return this.pathTemplates.organizationLogPathTemplate.match( + organizationLogName, + ).log; } /** @@ -1814,7 +2166,7 @@ export class MetricsServiceV2Client { * @param {string} organization * @returns {string} Resource name string. */ - organizationSettingsPath(organization:string) { + organizationSettingsPath(organization: string) { return this.pathTemplates.organizationSettingsPathTemplate.render({ organization: organization, }); @@ -1827,8 +2179,12 @@ export class MetricsServiceV2Client { * A fully-qualified path representing organization_settings resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationSettingsName(organizationSettingsName: string) { - return this.pathTemplates.organizationSettingsPathTemplate.match(organizationSettingsName).organization; + matchOrganizationFromOrganizationSettingsName( + organizationSettingsName: string, + ) { + return this.pathTemplates.organizationSettingsPathTemplate.match( + organizationSettingsName, + ).organization; } /** @@ -1838,7 +2194,7 @@ export class MetricsServiceV2Client { * @param {string} sink * @returns {string} Resource name string. */ - organizationSinkPath(organization:string,sink:string) { + organizationSinkPath(organization: string, sink: string) { return this.pathTemplates.organizationSinkPathTemplate.render({ organization: organization, sink: sink, @@ -1853,7 +2209,9 @@ export class MetricsServiceV2Client { * @returns {string} A string representing the organization. */ matchOrganizationFromOrganizationSinkName(organizationSinkName: string) { - return this.pathTemplates.organizationSinkPathTemplate.match(organizationSinkName).organization; + return this.pathTemplates.organizationSinkPathTemplate.match( + organizationSinkName, + ).organization; } /** @@ -1864,7 +2222,9 @@ export class MetricsServiceV2Client { * @returns {string} A string representing the sink. */ matchSinkFromOrganizationSinkName(organizationSinkName: string) { - return this.pathTemplates.organizationSinkPathTemplate.match(organizationSinkName).sink; + return this.pathTemplates.organizationSinkPathTemplate.match( + organizationSinkName, + ).sink; } /** @@ -1873,7 +2233,7 @@ export class MetricsServiceV2Client { * @param {string} project * @returns {string} Resource name string. */ - projectPath(project:string) { + projectPath(project: string) { return this.pathTemplates.projectPathTemplate.render({ project: project, }); @@ -1896,7 +2256,7 @@ export class MetricsServiceV2Client { * @param {string} project * @returns {string} Resource name string. */ - projectCmekSettingsPath(project:string) { + projectCmekSettingsPath(project: string) { return this.pathTemplates.projectCmekSettingsPathTemplate.render({ project: project, }); @@ -1910,7 +2270,9 @@ export class MetricsServiceV2Client { * @returns {string} A string representing the project. */ matchProjectFromProjectCmekSettingsName(projectCmekSettingsName: string) { - return this.pathTemplates.projectCmekSettingsPathTemplate.match(projectCmekSettingsName).project; + return this.pathTemplates.projectCmekSettingsPathTemplate.match( + projectCmekSettingsName, + ).project; } /** @@ -1920,7 +2282,7 @@ export class MetricsServiceV2Client { * @param {string} exclusion * @returns {string} Resource name string. */ - projectExclusionPath(project:string,exclusion:string) { + projectExclusionPath(project: string, exclusion: string) { return this.pathTemplates.projectExclusionPathTemplate.render({ project: project, exclusion: exclusion, @@ -1935,7 +2297,9 @@ export class MetricsServiceV2Client { * @returns {string} A string representing the project. */ matchProjectFromProjectExclusionName(projectExclusionName: string) { - return this.pathTemplates.projectExclusionPathTemplate.match(projectExclusionName).project; + return this.pathTemplates.projectExclusionPathTemplate.match( + projectExclusionName, + ).project; } /** @@ -1946,7 +2310,9 @@ export class MetricsServiceV2Client { * @returns {string} A string representing the exclusion. */ matchExclusionFromProjectExclusionName(projectExclusionName: string) { - return this.pathTemplates.projectExclusionPathTemplate.match(projectExclusionName).exclusion; + return this.pathTemplates.projectExclusionPathTemplate.match( + projectExclusionName, + ).exclusion; } /** @@ -1957,7 +2323,7 @@ export class MetricsServiceV2Client { * @param {string} bucket * @returns {string} Resource name string. */ - projectLocationBucketPath(project:string,location:string,bucket:string) { + projectLocationBucketPath(project: string, location: string, bucket: string) { return this.pathTemplates.projectLocationBucketPathTemplate.render({ project: project, location: location, @@ -1973,7 +2339,9 @@ export class MetricsServiceV2Client { * @returns {string} A string representing the project. */ matchProjectFromProjectLocationBucketName(projectLocationBucketName: string) { - return this.pathTemplates.projectLocationBucketPathTemplate.match(projectLocationBucketName).project; + return this.pathTemplates.projectLocationBucketPathTemplate.match( + projectLocationBucketName, + ).project; } /** @@ -1983,8 +2351,12 @@ export class MetricsServiceV2Client { * A fully-qualified path representing project_location_bucket resource. * @returns {string} A string representing the location. */ - matchLocationFromProjectLocationBucketName(projectLocationBucketName: string) { - return this.pathTemplates.projectLocationBucketPathTemplate.match(projectLocationBucketName).location; + matchLocationFromProjectLocationBucketName( + projectLocationBucketName: string, + ) { + return this.pathTemplates.projectLocationBucketPathTemplate.match( + projectLocationBucketName, + ).location; } /** @@ -1995,7 +2367,9 @@ export class MetricsServiceV2Client { * @returns {string} A string representing the bucket. */ matchBucketFromProjectLocationBucketName(projectLocationBucketName: string) { - return this.pathTemplates.projectLocationBucketPathTemplate.match(projectLocationBucketName).bucket; + return this.pathTemplates.projectLocationBucketPathTemplate.match( + projectLocationBucketName, + ).bucket; } /** @@ -2007,7 +2381,12 @@ export class MetricsServiceV2Client { * @param {string} view * @returns {string} Resource name string. */ - projectLocationBucketViewPath(project:string,location:string,bucket:string,view:string) { + projectLocationBucketViewPath( + project: string, + location: string, + bucket: string, + view: string, + ) { return this.pathTemplates.projectLocationBucketViewPathTemplate.render({ project: project, location: location, @@ -2023,8 +2402,12 @@ export class MetricsServiceV2Client { * A fully-qualified path representing project_location_bucket_view resource. * @returns {string} A string representing the project. */ - matchProjectFromProjectLocationBucketViewName(projectLocationBucketViewName: string) { - return this.pathTemplates.projectLocationBucketViewPathTemplate.match(projectLocationBucketViewName).project; + matchProjectFromProjectLocationBucketViewName( + projectLocationBucketViewName: string, + ) { + return this.pathTemplates.projectLocationBucketViewPathTemplate.match( + projectLocationBucketViewName, + ).project; } /** @@ -2034,8 +2417,12 @@ export class MetricsServiceV2Client { * A fully-qualified path representing project_location_bucket_view resource. * @returns {string} A string representing the location. */ - matchLocationFromProjectLocationBucketViewName(projectLocationBucketViewName: string) { - return this.pathTemplates.projectLocationBucketViewPathTemplate.match(projectLocationBucketViewName).location; + matchLocationFromProjectLocationBucketViewName( + projectLocationBucketViewName: string, + ) { + return this.pathTemplates.projectLocationBucketViewPathTemplate.match( + projectLocationBucketViewName, + ).location; } /** @@ -2045,8 +2432,12 @@ export class MetricsServiceV2Client { * A fully-qualified path representing project_location_bucket_view resource. * @returns {string} A string representing the bucket. */ - matchBucketFromProjectLocationBucketViewName(projectLocationBucketViewName: string) { - return this.pathTemplates.projectLocationBucketViewPathTemplate.match(projectLocationBucketViewName).bucket; + matchBucketFromProjectLocationBucketViewName( + projectLocationBucketViewName: string, + ) { + return this.pathTemplates.projectLocationBucketViewPathTemplate.match( + projectLocationBucketViewName, + ).bucket; } /** @@ -2056,8 +2447,12 @@ export class MetricsServiceV2Client { * A fully-qualified path representing project_location_bucket_view resource. * @returns {string} A string representing the view. */ - matchViewFromProjectLocationBucketViewName(projectLocationBucketViewName: string) { - return this.pathTemplates.projectLocationBucketViewPathTemplate.match(projectLocationBucketViewName).view; + matchViewFromProjectLocationBucketViewName( + projectLocationBucketViewName: string, + ) { + return this.pathTemplates.projectLocationBucketViewPathTemplate.match( + projectLocationBucketViewName, + ).view; } /** @@ -2067,7 +2462,7 @@ export class MetricsServiceV2Client { * @param {string} log * @returns {string} Resource name string. */ - projectLogPath(project:string,log:string) { + projectLogPath(project: string, log: string) { return this.pathTemplates.projectLogPathTemplate.render({ project: project, log: log, @@ -2082,7 +2477,8 @@ export class MetricsServiceV2Client { * @returns {string} A string representing the project. */ matchProjectFromProjectLogName(projectLogName: string) { - return this.pathTemplates.projectLogPathTemplate.match(projectLogName).project; + return this.pathTemplates.projectLogPathTemplate.match(projectLogName) + .project; } /** @@ -2102,7 +2498,7 @@ export class MetricsServiceV2Client { * @param {string} project * @returns {string} Resource name string. */ - projectSettingsPath(project:string) { + projectSettingsPath(project: string) { return this.pathTemplates.projectSettingsPathTemplate.render({ project: project, }); @@ -2116,7 +2512,9 @@ export class MetricsServiceV2Client { * @returns {string} A string representing the project. */ matchProjectFromProjectSettingsName(projectSettingsName: string) { - return this.pathTemplates.projectSettingsPathTemplate.match(projectSettingsName).project; + return this.pathTemplates.projectSettingsPathTemplate.match( + projectSettingsName, + ).project; } /** @@ -2126,7 +2524,7 @@ export class MetricsServiceV2Client { * @param {string} sink * @returns {string} Resource name string. */ - projectSinkPath(project:string,sink:string) { + projectSinkPath(project: string, sink: string) { return this.pathTemplates.projectSinkPathTemplate.render({ project: project, sink: sink, @@ -2141,7 +2539,8 @@ export class MetricsServiceV2Client { * @returns {string} A string representing the project. */ matchProjectFromProjectSinkName(projectSinkName: string) { - return this.pathTemplates.projectSinkPathTemplate.match(projectSinkName).project; + return this.pathTemplates.projectSinkPathTemplate.match(projectSinkName) + .project; } /** @@ -2152,7 +2551,8 @@ export class MetricsServiceV2Client { * @returns {string} A string representing the sink. */ matchSinkFromProjectSinkName(projectSinkName: string) { - return this.pathTemplates.projectSinkPathTemplate.match(projectSinkName).sink; + return this.pathTemplates.projectSinkPathTemplate.match(projectSinkName) + .sink; } /** @@ -2163,7 +2563,7 @@ export class MetricsServiceV2Client { */ close(): Promise { if (this.metricsServiceV2Stub && !this._terminated) { - return this.metricsServiceV2Stub.then(stub => { + return this.metricsServiceV2Stub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -2171,4 +2571,4 @@ export class MetricsServiceV2Client { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/core/generator/gapic-generator-typescript/baselines/logging/system-test/fixtures/sample/src/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/logging/system-test/fixtures/sample/src/index.ts.baseline index 4718840c897b..736a449ee59d 100644 --- a/core/generator/gapic-generator-typescript/baselines/logging/system-test/fixtures/sample/src/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/logging/system-test/fixtures/sample/src/index.ts.baseline @@ -16,7 +16,11 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -import {ConfigServiceV2Client, LoggingServiceV2Client, MetricsServiceV2Client} from 'logging'; +import { + ConfigServiceV2Client, + LoggingServiceV2Client, + MetricsServiceV2Client, +} from 'logging'; // check that the client class type name can be used function doStuffWithConfigServiceV2Client(client: ConfigServiceV2Client) { diff --git a/core/generator/gapic-generator-typescript/baselines/logging/system-test/install.ts.baseline b/core/generator/gapic-generator-typescript/baselines/logging/system-test/install.ts.baseline index f66069aa3940..ccf167042d2e 100644 --- a/core/generator/gapic-generator-typescript/baselines/logging/system-test/install.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/logging/system-test/install.ts.baseline @@ -16,34 +16,36 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -import {packNTest} from 'pack-n-play'; -import {readFileSync} from 'fs'; -import {describe, it} from 'mocha'; +import { packNTest } from 'pack-n-play'; +import { readFileSync } from 'fs'; +import { describe, it } from 'mocha'; describe('📦 pack-n-play test', () => { - - it('TypeScript code', async function() { + it('TypeScript code', async function () { this.timeout(300000); const options = { packageDir: process.cwd(), sample: { description: 'TypeScript user can use the type definitions', - ts: readFileSync('./system-test/fixtures/sample/src/index.ts').toString() - } + ts: readFileSync( + './system-test/fixtures/sample/src/index.ts', + ).toString(), + }, }; await packNTest(options); }); - it('JavaScript code', async function() { + it('JavaScript code', async function () { this.timeout(300000); const options = { packageDir: process.cwd(), sample: { description: 'JavaScript user can use the library', - cjs: readFileSync('./system-test/fixtures/sample/src/index.js').toString() - } + cjs: readFileSync( + './system-test/fixtures/sample/src/index.js', + ).toString(), + }, }; await packNTest(options); }); - }); diff --git a/core/generator/gapic-generator-typescript/baselines/logging/test/gapic_config_service_v2_v2.ts.baseline b/core/generator/gapic-generator-typescript/baselines/logging/test/gapic_config_service_v2_v2.ts.baseline index bde6151a8398..5f9dcf45d788 100644 --- a/core/generator/gapic-generator-typescript/baselines/logging/test/gapic_config_service_v2_v2.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/logging/test/gapic_config_service_v2_v2.ts.baseline @@ -19,4826 +19,6261 @@ import * as protos from '../protos/protos'; import * as assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as configservicev2Module from '../src'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; -import {protobuf, LROperation, operationsProtos} from 'google-gax'; +import { protobuf, LROperation, operationsProtos } from 'google-gax'; // Dynamically loaded proto JSON is needed to get the type information // to fill in default values for request objects -const root = protobuf.Root.fromJSON(require('../protos/protos.json')).resolveAll(); +const root = protobuf.Root.fromJSON( + require('../protos/protos.json'), +).resolveAll(); // eslint-disable-next-line @typescript-eslint/no-unused-vars function getTypeDefaultValue(typeName: string, fields: string[]) { - let type = root.lookupType(typeName) as protobuf.Type; - for (const field of fields.slice(0, -1)) { - type = type.fields[field]?.resolvedType as protobuf.Type; - } - return type.fields[fields[fields.length - 1]]?.defaultValue; + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type.fields[field]?.resolvedType as protobuf.Type; + } + return type.fields[fields[fields.length - 1]]?.defaultValue; } function generateSampleMessage(instance: T) { - const filledObject = (instance.constructor as typeof protobuf.Message) - .toObject(instance as protobuf.Message, {defaults: true}); - return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, { defaults: true }); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; } function stubSimpleCall(response?: ResponseType, error?: Error) { - return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); } -function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { - return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +function stubSimpleCallWithCallback( + response?: ResponseType, + error?: Error, +) { + return error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); } -function stubLongRunningCall(response?: ResponseType, callError?: Error, lroError?: Error) { - const innerStub = lroError ? sinon.stub().rejects(lroError) : sinon.stub().resolves([response]); - const mockOperation = { - promise: innerStub, - }; - return callError ? sinon.stub().rejects(callError) : sinon.stub().resolves([mockOperation]); +function stubLongRunningCall( + response?: ResponseType, + callError?: Error, + lroError?: Error, +) { + const innerStub = lroError + ? sinon.stub().rejects(lroError) + : sinon.stub().resolves([response]); + const mockOperation = { + promise: innerStub, + }; + return callError + ? sinon.stub().rejects(callError) + : sinon.stub().resolves([mockOperation]); } -function stubLongRunningCallWithCallback(response?: ResponseType, callError?: Error, lroError?: Error) { - const innerStub = lroError ? sinon.stub().rejects(lroError) : sinon.stub().resolves([response]); - const mockOperation = { - promise: innerStub, - }; - return callError ? sinon.stub().callsArgWith(2, callError) : sinon.stub().callsArgWith(2, null, mockOperation); +function stubLongRunningCallWithCallback( + response?: ResponseType, + callError?: Error, + lroError?: Error, +) { + const innerStub = lroError + ? sinon.stub().rejects(lroError) + : sinon.stub().resolves([response]); + const mockOperation = { + promise: innerStub, + }; + return callError + ? sinon.stub().callsArgWith(2, callError) + : sinon.stub().callsArgWith(2, null, mockOperation); } -function stubPageStreamingCall(responses?: ResponseType[], error?: Error) { - const pagingStub = sinon.stub(); - if (responses) { - for (let i = 0; i < responses.length; ++i) { - pagingStub.onCall(i).callsArgWith(2, null, responses[i]); - } +function stubPageStreamingCall( + responses?: ResponseType[], + error?: Error, +) { + const pagingStub = sinon.stub(); + if (responses) { + for (let i = 0; i < responses.length; ++i) { + pagingStub.onCall(i).callsArgWith(2, null, responses[i]); } - const transformStub = error ? sinon.stub().callsArgWith(2, error) : pagingStub; - const mockStream = new PassThrough({ - objectMode: true, - transform: transformStub, - }); - // trigger as many responses as needed - if (responses) { - for (let i = 0; i < responses.length; ++i) { - setImmediate(() => { mockStream.write({}); }); - } - setImmediate(() => { mockStream.end(); }); - } else { - setImmediate(() => { mockStream.write({}); }); - setImmediate(() => { mockStream.end(); }); + } + const transformStub = error + ? sinon.stub().callsArgWith(2, error) + : pagingStub; + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + // trigger as many responses as needed + if (responses) { + for (let i = 0; i < responses.length; ++i) { + setImmediate(() => { + mockStream.write({}); + }); } - return sinon.stub().returns(mockStream); + setImmediate(() => { + mockStream.end(); + }); + } else { + setImmediate(() => { + mockStream.write({}); + }); + setImmediate(() => { + mockStream.end(); + }); + } + return sinon.stub().returns(mockStream); } -function stubAsyncIterationCall(responses?: ResponseType[], error?: Error) { - let counter = 0; - const asyncIterable = { - [Symbol.asyncIterator]() { - return { - async next() { - if (error) { - return Promise.reject(error); - } - if (counter >= responses!.length) { - return Promise.resolve({done: true, value: undefined}); - } - return Promise.resolve({done: false, value: responses![counter++]}); - } - }; - } - }; - return sinon.stub().returns(asyncIterable); +function stubAsyncIterationCall( + responses?: ResponseType[], + error?: Error, +) { + let counter = 0; + const asyncIterable = { + [Symbol.asyncIterator]() { + return { + async next() { + if (error) { + return Promise.reject(error); + } + if (counter >= responses!.length) { + return Promise.resolve({ done: true, value: undefined }); + } + return Promise.resolve({ done: false, value: responses![counter++] }); + }, + }; + }, + }; + return sinon.stub().returns(asyncIterable); } describe('v2.ConfigServiceV2Client', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'logging.googleapis.com'); - }); - - it('has universeDomain', () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); - - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - it('throws DeprecationWarning if static servicePath is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const servicePath = configservicev2Module.v2.ConfigServiceV2Client.servicePath; - assert.strictEqual(servicePath, 'logging.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = configservicev2Module.v2.ConfigServiceV2Client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'logging.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'logging.example.com'); - }); - - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'logging.example.com'); - }); - - if (typeof process === 'object' && 'env' in process) { - describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { - it('sets apiEndpoint from environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new configservicev2Module.v2.ConfigServiceV2Client(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'logging.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - - it('value configured in code has priority over environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new configservicev2Module.v2.ConfigServiceV2Client({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'logging.configured.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { new configservicev2Module.v2.ConfigServiceV2Client({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); - - it('has port', () => { - const port = configservicev2Module.v2.ConfigServiceV2Client.port; - assert(port); - assert(typeof port === 'number'); - }); - - it('should create a client with no option', () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client(); - assert(client); - }); - - it('should create a client with gRPC fallback', () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - fallback: true, - }); - assert(client); - }); - - it('has initialize method and supports deferred initialization', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.configServiceV2Stub, undefined); - await client.initialize(); - assert(client.configServiceV2Stub); - }); - - it('has close method for the initialized client', done => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.configServiceV2Stub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); - - it('has close method for the non-initialized client', done => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.configServiceV2Stub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); - - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); - }); - - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId((err?: Error|null, projectId?: string|null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } - }); - }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'logging.googleapis.com'); }); - describe('getBucket', () => { - it('invokes getBucket without error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.GetBucketRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.GetBucketRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.logging.v2.LogBucket() - ); - client.innerApiCalls.getBucket = stubSimpleCall(expectedResponse); - const [response] = await client.getBucket(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getBucket as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getBucket as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getBucket without error using callback', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.GetBucketRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.GetBucketRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.logging.v2.LogBucket() - ); - client.innerApiCalls.getBucket = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getBucket( - request, - (err?: Error|null, result?: protos.google.logging.v2.ILogBucket|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getBucket as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getBucket as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getBucket with error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.GetBucketRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.GetBucketRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getBucket = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getBucket(request), expectedError); - const actualRequest = (client.innerApiCalls.getBucket as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getBucket as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getBucket with closed client', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.GetBucketRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.GetBucketRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getBucket(request), expectedError); - }); + it('has universeDomain', () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); }); - describe('createBucket', () => { - it('invokes createBucket without error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.CreateBucketRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.CreateBucketRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.logging.v2.LogBucket() - ); - client.innerApiCalls.createBucket = stubSimpleCall(expectedResponse); - const [response] = await client.createBucket(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createBucket as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createBucket as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createBucket without error using callback', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.CreateBucketRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.CreateBucketRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.logging.v2.LogBucket() - ); - client.innerApiCalls.createBucket = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createBucket( - request, - (err?: Error|null, result?: protos.google.logging.v2.ILogBucket|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createBucket as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createBucket as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createBucket with error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.CreateBucketRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.CreateBucketRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createBucket = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createBucket(request), expectedError); - const actualRequest = (client.innerApiCalls.createBucket as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createBucket as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createBucket with closed client', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.CreateBucketRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.CreateBucketRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createBucket(request), expectedError); - }); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = + configservicev2Module.v2.ConfigServiceV2Client.servicePath; + assert.strictEqual(servicePath, 'logging.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + configservicev2Module.v2.ConfigServiceV2Client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'logging.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + universeDomain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'logging.example.com'); }); - describe('updateBucket', () => { - it('invokes updateBucket without error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.UpdateBucketRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.UpdateBucketRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.logging.v2.LogBucket() - ); - client.innerApiCalls.updateBucket = stubSimpleCall(expectedResponse); - const [response] = await client.updateBucket(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateBucket as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateBucket as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateBucket without error using callback', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.UpdateBucketRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.UpdateBucketRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.logging.v2.LogBucket() - ); - client.innerApiCalls.updateBucket = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateBucket( - request, - (err?: Error|null, result?: protos.google.logging.v2.ILogBucket|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateBucket as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateBucket as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateBucket with error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.UpdateBucketRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.UpdateBucketRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateBucket = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateBucket(request), expectedError); - const actualRequest = (client.innerApiCalls.updateBucket as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateBucket as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateBucket with closed client', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.UpdateBucketRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.UpdateBucketRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateBucket(request), expectedError); - }); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + universe_domain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'logging.example.com'); }); - describe('deleteBucket', () => { - it('invokes deleteBucket without error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.DeleteBucketRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.DeleteBucketRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteBucket = stubSimpleCall(expectedResponse); - const [response] = await client.deleteBucket(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteBucket as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteBucket as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + if (typeof process === 'object' && 'env' in process) { + describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { + it('sets apiEndpoint from environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new configservicev2Module.v2.ConfigServiceV2Client(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'logging.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } + }); + + it('value configured in code has priority over environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + universeDomain: 'configured.example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'logging.configured.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } + }); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new configservicev2Module.v2.ConfigServiceV2Client({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); + }); - it('invokes deleteBucket without error using callback', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.DeleteBucketRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.DeleteBucketRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteBucket = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteBucket( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteBucket as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteBucket as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has port', () => { + const port = configservicev2Module.v2.ConfigServiceV2Client.port; + assert(port); + assert(typeof port === 'number'); + }); - it('invokes deleteBucket with error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.DeleteBucketRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.DeleteBucketRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteBucket = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteBucket(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteBucket as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteBucket as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('should create a client with no option', () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client(); + assert(client); + }); - it('invokes deleteBucket with closed client', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.DeleteBucketRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.DeleteBucketRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteBucket(request), expectedError); - }); + it('should create a client with gRPC fallback', () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + fallback: true, + }); + assert(client); }); - describe('undeleteBucket', () => { - it('invokes undeleteBucket without error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.UndeleteBucketRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.UndeleteBucketRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.undeleteBucket = stubSimpleCall(expectedResponse); - const [response] = await client.undeleteBucket(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.undeleteBucket as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.undeleteBucket as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has initialize method and supports deferred initialization', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.configServiceV2Stub, undefined); + await client.initialize(); + assert(client.configServiceV2Stub); + }); - it('invokes undeleteBucket without error using callback', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.UndeleteBucketRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.UndeleteBucketRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.undeleteBucket = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.undeleteBucket( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.undeleteBucket as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.undeleteBucket as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('has close method for the initialized client', (done) => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.configServiceV2Stub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes undeleteBucket with error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.UndeleteBucketRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.UndeleteBucketRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.undeleteBucket = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.undeleteBucket(request), expectedError); - const actualRequest = (client.innerApiCalls.undeleteBucket as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.undeleteBucket as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('has close method for the non-initialized client', (done) => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.configServiceV2Stub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes undeleteBucket with closed client', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.UndeleteBucketRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.UndeleteBucketRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.undeleteBucket(request), expectedError); - }); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); }); - describe('getView', () => { - it('invokes getView without error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.GetViewRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.GetViewRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.logging.v2.LogView() - ); - client.innerApiCalls.getView = stubSimpleCall(expectedResponse); - const [response] = await client.getView(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getView as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getView as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } + }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + }); + + describe('getBucket', () => { + it('invokes getBucket without error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.GetBucketRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.GetBucketRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.logging.v2.LogBucket(), + ); + client.innerApiCalls.getBucket = stubSimpleCall(expectedResponse); + const [response] = await client.getBucket(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getBucket as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getBucket as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getView without error using callback', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.GetViewRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.GetViewRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.logging.v2.LogView() - ); - client.innerApiCalls.getView = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getView( - request, - (err?: Error|null, result?: protos.google.logging.v2.ILogView|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getView as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getView as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getBucket without error using callback', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.GetBucketRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.GetBucketRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.logging.v2.LogBucket(), + ); + client.innerApiCalls.getBucket = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getBucket( + request, + ( + err?: Error | null, + result?: protos.google.logging.v2.ILogBucket | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getBucket as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getBucket as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getView with error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.GetViewRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.GetViewRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getView = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getView(request), expectedError); - const actualRequest = (client.innerApiCalls.getView as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getView as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getBucket with error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.GetBucketRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.GetBucketRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getBucket = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.getBucket(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getBucket as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getBucket as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getView with closed client', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.GetViewRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.GetViewRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getView(request), expectedError); - }); + it('invokes getBucket with closed client', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.GetBucketRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.GetBucketRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getBucket(request), expectedError); + }); + }); + + describe('createBucket', () => { + it('invokes createBucket without error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.CreateBucketRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.CreateBucketRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.logging.v2.LogBucket(), + ); + client.innerApiCalls.createBucket = stubSimpleCall(expectedResponse); + const [response] = await client.createBucket(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createBucket as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createBucket as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('createView', () => { - it('invokes createView without error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.CreateViewRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.CreateViewRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.logging.v2.LogView() - ); - client.innerApiCalls.createView = stubSimpleCall(expectedResponse); - const [response] = await client.createView(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createView as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createView as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createBucket without error using callback', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.CreateBucketRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.CreateBucketRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.logging.v2.LogBucket(), + ); + client.innerApiCalls.createBucket = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createBucket( + request, + ( + err?: Error | null, + result?: protos.google.logging.v2.ILogBucket | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createBucket as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createBucket as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createView without error using callback', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.CreateViewRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.CreateViewRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.logging.v2.LogView() - ); - client.innerApiCalls.createView = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createView( - request, - (err?: Error|null, result?: protos.google.logging.v2.ILogView|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createView as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createView as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createBucket with error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.CreateBucketRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.CreateBucketRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createBucket = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.createBucket(request), expectedError); + const actualRequest = ( + client.innerApiCalls.createBucket as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createBucket as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createView with error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.CreateViewRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.CreateViewRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createView = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createView(request), expectedError); - const actualRequest = (client.innerApiCalls.createView as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createView as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createBucket with closed client', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.CreateBucketRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.CreateBucketRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.createBucket(request), expectedError); + }); + }); + + describe('updateBucket', () => { + it('invokes updateBucket without error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.UpdateBucketRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.UpdateBucketRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.logging.v2.LogBucket(), + ); + client.innerApiCalls.updateBucket = stubSimpleCall(expectedResponse); + const [response] = await client.updateBucket(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateBucket as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateBucket as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createView with closed client', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.CreateViewRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.CreateViewRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createView(request), expectedError); - }); + it('invokes updateBucket without error using callback', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.UpdateBucketRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.UpdateBucketRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.logging.v2.LogBucket(), + ); + client.innerApiCalls.updateBucket = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateBucket( + request, + ( + err?: Error | null, + result?: protos.google.logging.v2.ILogBucket | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateBucket as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateBucket as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('updateView', () => { - it('invokes updateView without error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.UpdateViewRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.UpdateViewRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.logging.v2.LogView() - ); - client.innerApiCalls.updateView = stubSimpleCall(expectedResponse); - const [response] = await client.updateView(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateView as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateView as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateBucket with error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.UpdateBucketRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.UpdateBucketRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateBucket = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.updateBucket(request), expectedError); + const actualRequest = ( + client.innerApiCalls.updateBucket as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateBucket as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateView without error using callback', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.UpdateViewRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.UpdateViewRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.logging.v2.LogView() - ); - client.innerApiCalls.updateView = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateView( - request, - (err?: Error|null, result?: protos.google.logging.v2.ILogView|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateView as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateView as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateBucket with closed client', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.UpdateBucketRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.UpdateBucketRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.updateBucket(request), expectedError); + }); + }); + + describe('deleteBucket', () => { + it('invokes deleteBucket without error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.DeleteBucketRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.DeleteBucketRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteBucket = stubSimpleCall(expectedResponse); + const [response] = await client.deleteBucket(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteBucket as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteBucket as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateView with error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.UpdateViewRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.UpdateViewRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateView = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateView(request), expectedError); - const actualRequest = (client.innerApiCalls.updateView as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateView as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteBucket without error using callback', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.DeleteBucketRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.DeleteBucketRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteBucket = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteBucket( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteBucket as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteBucket as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateView with closed client', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.UpdateViewRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.UpdateViewRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateView(request), expectedError); - }); + it('invokes deleteBucket with error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.DeleteBucketRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.DeleteBucketRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteBucket = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.deleteBucket(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteBucket as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteBucket as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('deleteView', () => { - it('invokes deleteView without error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.DeleteViewRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.DeleteViewRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteView = stubSimpleCall(expectedResponse); - const [response] = await client.deleteView(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteView as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteView as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteBucket with closed client', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.DeleteBucketRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.DeleteBucketRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.deleteBucket(request), expectedError); + }); + }); + + describe('undeleteBucket', () => { + it('invokes undeleteBucket without error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.UndeleteBucketRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.UndeleteBucketRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.undeleteBucket = stubSimpleCall(expectedResponse); + const [response] = await client.undeleteBucket(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.undeleteBucket as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.undeleteBucket as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteView without error using callback', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.DeleteViewRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.DeleteViewRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteView = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteView( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteView as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteView as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes undeleteBucket without error using callback', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.UndeleteBucketRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.UndeleteBucketRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.undeleteBucket = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.undeleteBucket( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.undeleteBucket as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.undeleteBucket as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteView with error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.DeleteViewRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.DeleteViewRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteView = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteView(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteView as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteView as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes undeleteBucket with error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.UndeleteBucketRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.UndeleteBucketRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.undeleteBucket = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.undeleteBucket(request), expectedError); + const actualRequest = ( + client.innerApiCalls.undeleteBucket as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.undeleteBucket as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteView with closed client', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.DeleteViewRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.DeleteViewRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteView(request), expectedError); - }); + it('invokes undeleteBucket with closed client', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.UndeleteBucketRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.UndeleteBucketRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.undeleteBucket(request), expectedError); + }); + }); + + describe('getView', () => { + it('invokes getView without error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.GetViewRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.GetViewRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.logging.v2.LogView(), + ); + client.innerApiCalls.getView = stubSimpleCall(expectedResponse); + const [response] = await client.getView(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.getView as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getView as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('getSink', () => { - it('invokes getSink without error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.GetSinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.GetSinkRequest', ['sinkName']); - request.sinkName = defaultValue1; - const expectedHeaderRequestParams = `sink_name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.logging.v2.LogSink() - ); - client.innerApiCalls.getSink = stubSimpleCall(expectedResponse); - const [response] = await client.getSink(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getSink as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getSink as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getView without error using callback', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.GetViewRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.GetViewRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.logging.v2.LogView(), + ); + client.innerApiCalls.getView = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getView( + request, + ( + err?: Error | null, + result?: protos.google.logging.v2.ILogView | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.getView as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getView as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getSink without error using callback', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.GetSinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.GetSinkRequest', ['sinkName']); - request.sinkName = defaultValue1; - const expectedHeaderRequestParams = `sink_name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.logging.v2.LogSink() - ); - client.innerApiCalls.getSink = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getSink( - request, - (err?: Error|null, result?: protos.google.logging.v2.ILogSink|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getSink as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getSink as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getView with error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.GetViewRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.GetViewRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getView = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.getView(request), expectedError); + const actualRequest = (client.innerApiCalls.getView as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getView as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getSink with error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.GetSinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.GetSinkRequest', ['sinkName']); - request.sinkName = defaultValue1; - const expectedHeaderRequestParams = `sink_name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getSink = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getSink(request), expectedError); - const actualRequest = (client.innerApiCalls.getSink as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getSink as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getView with closed client', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.GetViewRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.GetViewRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getView(request), expectedError); + }); + }); + + describe('createView', () => { + it('invokes createView without error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.CreateViewRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.CreateViewRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.logging.v2.LogView(), + ); + client.innerApiCalls.createView = stubSimpleCall(expectedResponse); + const [response] = await client.createView(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createView as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createView as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getSink with closed client', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.GetSinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.GetSinkRequest', ['sinkName']); - request.sinkName = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getSink(request), expectedError); - }); + it('invokes createView without error using callback', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.CreateViewRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.CreateViewRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.logging.v2.LogView(), + ); + client.innerApiCalls.createView = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createView( + request, + ( + err?: Error | null, + result?: protos.google.logging.v2.ILogView | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createView as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createView as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('createSink', () => { - it('invokes createSink without error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.CreateSinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.CreateSinkRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.logging.v2.LogSink() - ); - client.innerApiCalls.createSink = stubSimpleCall(expectedResponse); - const [response] = await client.createSink(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createSink as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createSink as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createView with error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.CreateViewRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.CreateViewRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createView = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.createView(request), expectedError); + const actualRequest = ( + client.innerApiCalls.createView as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createView as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createSink without error using callback', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.CreateSinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.CreateSinkRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.logging.v2.LogSink() - ); - client.innerApiCalls.createSink = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createSink( - request, - (err?: Error|null, result?: protos.google.logging.v2.ILogSink|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createSink as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createSink as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createView with closed client', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.CreateViewRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.CreateViewRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.createView(request), expectedError); + }); + }); + + describe('updateView', () => { + it('invokes updateView without error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.UpdateViewRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.UpdateViewRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.logging.v2.LogView(), + ); + client.innerApiCalls.updateView = stubSimpleCall(expectedResponse); + const [response] = await client.updateView(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateView as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateView as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createSink with error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.CreateSinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.CreateSinkRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createSink = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createSink(request), expectedError); - const actualRequest = (client.innerApiCalls.createSink as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createSink as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateView without error using callback', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.UpdateViewRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.UpdateViewRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.logging.v2.LogView(), + ); + client.innerApiCalls.updateView = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateView( + request, + ( + err?: Error | null, + result?: protos.google.logging.v2.ILogView | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateView as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateView as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createSink with closed client', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.CreateSinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.CreateSinkRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createSink(request), expectedError); - }); + it('invokes updateView with error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.UpdateViewRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.UpdateViewRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateView = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.updateView(request), expectedError); + const actualRequest = ( + client.innerApiCalls.updateView as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateView as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('updateSink', () => { - it('invokes updateSink without error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.UpdateSinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.UpdateSinkRequest', ['sinkName']); - request.sinkName = defaultValue1; - const expectedHeaderRequestParams = `sink_name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.logging.v2.LogSink() - ); - client.innerApiCalls.updateSink = stubSimpleCall(expectedResponse); - const [response] = await client.updateSink(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateSink as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateSink as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateView with closed client', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.UpdateViewRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.UpdateViewRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.updateView(request), expectedError); + }); + }); + + describe('deleteView', () => { + it('invokes deleteView without error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.DeleteViewRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.DeleteViewRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteView = stubSimpleCall(expectedResponse); + const [response] = await client.deleteView(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteView as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteView as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateSink without error using callback', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.UpdateSinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.UpdateSinkRequest', ['sinkName']); - request.sinkName = defaultValue1; - const expectedHeaderRequestParams = `sink_name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.logging.v2.LogSink() - ); - client.innerApiCalls.updateSink = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateSink( - request, - (err?: Error|null, result?: protos.google.logging.v2.ILogSink|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateSink as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateSink as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteView without error using callback', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.DeleteViewRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.DeleteViewRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteView = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteView( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteView as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteView as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateSink with error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.UpdateSinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.UpdateSinkRequest', ['sinkName']); - request.sinkName = defaultValue1; - const expectedHeaderRequestParams = `sink_name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateSink = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateSink(request), expectedError); - const actualRequest = (client.innerApiCalls.updateSink as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateSink as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteView with error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.DeleteViewRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.DeleteViewRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteView = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.deleteView(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteView as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteView as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateSink with closed client', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.UpdateSinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.UpdateSinkRequest', ['sinkName']); - request.sinkName = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateSink(request), expectedError); - }); + it('invokes deleteView with closed client', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.DeleteViewRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.DeleteViewRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.deleteView(request), expectedError); + }); + }); + + describe('getSink', () => { + it('invokes getSink without error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.GetSinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.GetSinkRequest', + ['sinkName'], + ); + request.sinkName = defaultValue1; + const expectedHeaderRequestParams = `sink_name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.logging.v2.LogSink(), + ); + client.innerApiCalls.getSink = stubSimpleCall(expectedResponse); + const [response] = await client.getSink(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.getSink as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getSink as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('deleteSink', () => { - it('invokes deleteSink without error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.DeleteSinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.DeleteSinkRequest', ['sinkName']); - request.sinkName = defaultValue1; - const expectedHeaderRequestParams = `sink_name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteSink = stubSimpleCall(expectedResponse); - const [response] = await client.deleteSink(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteSink as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteSink as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getSink without error using callback', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.GetSinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.GetSinkRequest', + ['sinkName'], + ); + request.sinkName = defaultValue1; + const expectedHeaderRequestParams = `sink_name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.logging.v2.LogSink(), + ); + client.innerApiCalls.getSink = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getSink( + request, + ( + err?: Error | null, + result?: protos.google.logging.v2.ILogSink | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.getSink as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getSink as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteSink without error using callback', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.DeleteSinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.DeleteSinkRequest', ['sinkName']); - request.sinkName = defaultValue1; - const expectedHeaderRequestParams = `sink_name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteSink = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteSink( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteSink as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteSink as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getSink with error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.GetSinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.GetSinkRequest', + ['sinkName'], + ); + request.sinkName = defaultValue1; + const expectedHeaderRequestParams = `sink_name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getSink = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.getSink(request), expectedError); + const actualRequest = (client.innerApiCalls.getSink as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getSink as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteSink with error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.DeleteSinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.DeleteSinkRequest', ['sinkName']); - request.sinkName = defaultValue1; - const expectedHeaderRequestParams = `sink_name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteSink = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteSink(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteSink as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteSink as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getSink with closed client', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.GetSinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.GetSinkRequest', + ['sinkName'], + ); + request.sinkName = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getSink(request), expectedError); + }); + }); + + describe('createSink', () => { + it('invokes createSink without error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.CreateSinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.CreateSinkRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.logging.v2.LogSink(), + ); + client.innerApiCalls.createSink = stubSimpleCall(expectedResponse); + const [response] = await client.createSink(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createSink as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createSink as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteSink with closed client', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.DeleteSinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.DeleteSinkRequest', ['sinkName']); - request.sinkName = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteSink(request), expectedError); - }); + it('invokes createSink without error using callback', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.CreateSinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.CreateSinkRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.logging.v2.LogSink(), + ); + client.innerApiCalls.createSink = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createSink( + request, + ( + err?: Error | null, + result?: protos.google.logging.v2.ILogSink | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createSink as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createSink as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('getExclusion', () => { - it('invokes getExclusion without error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.GetExclusionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.GetExclusionRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.logging.v2.LogExclusion() - ); - client.innerApiCalls.getExclusion = stubSimpleCall(expectedResponse); - const [response] = await client.getExclusion(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getExclusion as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getExclusion as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createSink with error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.CreateSinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.CreateSinkRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createSink = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.createSink(request), expectedError); + const actualRequest = ( + client.innerApiCalls.createSink as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createSink as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getExclusion without error using callback', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.GetExclusionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.GetExclusionRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.logging.v2.LogExclusion() - ); - client.innerApiCalls.getExclusion = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getExclusion( - request, - (err?: Error|null, result?: protos.google.logging.v2.ILogExclusion|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getExclusion as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getExclusion as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createSink with closed client', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.CreateSinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.CreateSinkRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.createSink(request), expectedError); + }); + }); + + describe('updateSink', () => { + it('invokes updateSink without error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.UpdateSinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.UpdateSinkRequest', + ['sinkName'], + ); + request.sinkName = defaultValue1; + const expectedHeaderRequestParams = `sink_name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.logging.v2.LogSink(), + ); + client.innerApiCalls.updateSink = stubSimpleCall(expectedResponse); + const [response] = await client.updateSink(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateSink as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateSink as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getExclusion with error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.GetExclusionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.GetExclusionRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getExclusion = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getExclusion(request), expectedError); - const actualRequest = (client.innerApiCalls.getExclusion as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getExclusion as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateSink without error using callback', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.UpdateSinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.UpdateSinkRequest', + ['sinkName'], + ); + request.sinkName = defaultValue1; + const expectedHeaderRequestParams = `sink_name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.logging.v2.LogSink(), + ); + client.innerApiCalls.updateSink = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateSink( + request, + ( + err?: Error | null, + result?: protos.google.logging.v2.ILogSink | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateSink as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateSink as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getExclusion with closed client', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.GetExclusionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.GetExclusionRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getExclusion(request), expectedError); - }); + it('invokes updateSink with error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.UpdateSinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.UpdateSinkRequest', + ['sinkName'], + ); + request.sinkName = defaultValue1; + const expectedHeaderRequestParams = `sink_name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateSink = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.updateSink(request), expectedError); + const actualRequest = ( + client.innerApiCalls.updateSink as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateSink as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('createExclusion', () => { - it('invokes createExclusion without error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.CreateExclusionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.CreateExclusionRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.logging.v2.LogExclusion() - ); - client.innerApiCalls.createExclusion = stubSimpleCall(expectedResponse); - const [response] = await client.createExclusion(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createExclusion as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createExclusion as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateSink with closed client', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.UpdateSinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.UpdateSinkRequest', + ['sinkName'], + ); + request.sinkName = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.updateSink(request), expectedError); + }); + }); + + describe('deleteSink', () => { + it('invokes deleteSink without error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.DeleteSinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.DeleteSinkRequest', + ['sinkName'], + ); + request.sinkName = defaultValue1; + const expectedHeaderRequestParams = `sink_name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteSink = stubSimpleCall(expectedResponse); + const [response] = await client.deleteSink(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteSink as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteSink as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createExclusion without error using callback', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.CreateExclusionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.CreateExclusionRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.logging.v2.LogExclusion() - ); - client.innerApiCalls.createExclusion = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createExclusion( - request, - (err?: Error|null, result?: protos.google.logging.v2.ILogExclusion|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createExclusion as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createExclusion as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteSink without error using callback', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.DeleteSinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.DeleteSinkRequest', + ['sinkName'], + ); + request.sinkName = defaultValue1; + const expectedHeaderRequestParams = `sink_name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteSink = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteSink( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteSink as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteSink as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createExclusion with error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.CreateExclusionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.CreateExclusionRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createExclusion = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createExclusion(request), expectedError); - const actualRequest = (client.innerApiCalls.createExclusion as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createExclusion as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteSink with error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.DeleteSinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.DeleteSinkRequest', + ['sinkName'], + ); + request.sinkName = defaultValue1; + const expectedHeaderRequestParams = `sink_name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteSink = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.deleteSink(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteSink as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteSink as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createExclusion with closed client', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.CreateExclusionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.CreateExclusionRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createExclusion(request), expectedError); - }); + it('invokes deleteSink with closed client', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.DeleteSinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.DeleteSinkRequest', + ['sinkName'], + ); + request.sinkName = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.deleteSink(request), expectedError); + }); + }); + + describe('getExclusion', () => { + it('invokes getExclusion without error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.GetExclusionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.GetExclusionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.logging.v2.LogExclusion(), + ); + client.innerApiCalls.getExclusion = stubSimpleCall(expectedResponse); + const [response] = await client.getExclusion(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getExclusion as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getExclusion as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('updateExclusion', () => { - it('invokes updateExclusion without error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.UpdateExclusionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.UpdateExclusionRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.logging.v2.LogExclusion() - ); - client.innerApiCalls.updateExclusion = stubSimpleCall(expectedResponse); - const [response] = await client.updateExclusion(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateExclusion as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateExclusion as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getExclusion without error using callback', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.GetExclusionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.GetExclusionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.logging.v2.LogExclusion(), + ); + client.innerApiCalls.getExclusion = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getExclusion( + request, + ( + err?: Error | null, + result?: protos.google.logging.v2.ILogExclusion | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getExclusion as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getExclusion as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateExclusion without error using callback', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.UpdateExclusionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.UpdateExclusionRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.logging.v2.LogExclusion() - ); - client.innerApiCalls.updateExclusion = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateExclusion( - request, - (err?: Error|null, result?: protos.google.logging.v2.ILogExclusion|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateExclusion as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateExclusion as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getExclusion with error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.GetExclusionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.GetExclusionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getExclusion = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getExclusion(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getExclusion as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getExclusion as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateExclusion with error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.UpdateExclusionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.UpdateExclusionRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateExclusion = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateExclusion(request), expectedError); - const actualRequest = (client.innerApiCalls.updateExclusion as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateExclusion as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getExclusion with closed client', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.GetExclusionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.GetExclusionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getExclusion(request), expectedError); + }); + }); + + describe('createExclusion', () => { + it('invokes createExclusion without error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.CreateExclusionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.CreateExclusionRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.logging.v2.LogExclusion(), + ); + client.innerApiCalls.createExclusion = stubSimpleCall(expectedResponse); + const [response] = await client.createExclusion(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createExclusion as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createExclusion as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateExclusion with closed client', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.UpdateExclusionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.UpdateExclusionRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateExclusion(request), expectedError); - }); + it('invokes createExclusion without error using callback', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.CreateExclusionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.CreateExclusionRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.logging.v2.LogExclusion(), + ); + client.innerApiCalls.createExclusion = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createExclusion( + request, + ( + err?: Error | null, + result?: protos.google.logging.v2.ILogExclusion | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createExclusion as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createExclusion as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('deleteExclusion', () => { - it('invokes deleteExclusion without error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.DeleteExclusionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.DeleteExclusionRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteExclusion = stubSimpleCall(expectedResponse); - const [response] = await client.deleteExclusion(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteExclusion as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteExclusion as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createExclusion with error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.CreateExclusionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.CreateExclusionRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createExclusion = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.createExclusion(request), expectedError); + const actualRequest = ( + client.innerApiCalls.createExclusion as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createExclusion as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteExclusion without error using callback', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.DeleteExclusionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.DeleteExclusionRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteExclusion = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteExclusion( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteExclusion as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteExclusion as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createExclusion with closed client', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.CreateExclusionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.CreateExclusionRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.createExclusion(request), expectedError); + }); + }); + + describe('updateExclusion', () => { + it('invokes updateExclusion without error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.UpdateExclusionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.UpdateExclusionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.logging.v2.LogExclusion(), + ); + client.innerApiCalls.updateExclusion = stubSimpleCall(expectedResponse); + const [response] = await client.updateExclusion(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateExclusion as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateExclusion as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteExclusion with error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.DeleteExclusionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.DeleteExclusionRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteExclusion = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteExclusion(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteExclusion as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteExclusion as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateExclusion without error using callback', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.UpdateExclusionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.UpdateExclusionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.logging.v2.LogExclusion(), + ); + client.innerApiCalls.updateExclusion = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateExclusion( + request, + ( + err?: Error | null, + result?: protos.google.logging.v2.ILogExclusion | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateExclusion as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateExclusion as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteExclusion with closed client', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.DeleteExclusionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.DeleteExclusionRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteExclusion(request), expectedError); - }); + it('invokes updateExclusion with error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.UpdateExclusionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.UpdateExclusionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateExclusion = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.updateExclusion(request), expectedError); + const actualRequest = ( + client.innerApiCalls.updateExclusion as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateExclusion as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('getCmekSettings', () => { - it('invokes getCmekSettings without error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.GetCmekSettingsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.GetCmekSettingsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.logging.v2.CmekSettings() - ); - client.innerApiCalls.getCmekSettings = stubSimpleCall(expectedResponse); - const [response] = await client.getCmekSettings(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getCmekSettings as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getCmekSettings as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateExclusion with closed client', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.UpdateExclusionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.UpdateExclusionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.updateExclusion(request), expectedError); + }); + }); + + describe('deleteExclusion', () => { + it('invokes deleteExclusion without error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.DeleteExclusionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.DeleteExclusionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteExclusion = stubSimpleCall(expectedResponse); + const [response] = await client.deleteExclusion(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteExclusion as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteExclusion as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getCmekSettings without error using callback', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.GetCmekSettingsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.GetCmekSettingsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.logging.v2.CmekSettings() - ); - client.innerApiCalls.getCmekSettings = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getCmekSettings( - request, - (err?: Error|null, result?: protos.google.logging.v2.ICmekSettings|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getCmekSettings as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getCmekSettings as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteExclusion without error using callback', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.DeleteExclusionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.DeleteExclusionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteExclusion = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteExclusion( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteExclusion as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteExclusion as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getCmekSettings with error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.GetCmekSettingsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.GetCmekSettingsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getCmekSettings = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getCmekSettings(request), expectedError); - const actualRequest = (client.innerApiCalls.getCmekSettings as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getCmekSettings as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteExclusion with error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.DeleteExclusionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.DeleteExclusionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteExclusion = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.deleteExclusion(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteExclusion as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteExclusion as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getCmekSettings with closed client', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.GetCmekSettingsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.GetCmekSettingsRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getCmekSettings(request), expectedError); - }); + it('invokes deleteExclusion with closed client', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.DeleteExclusionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.DeleteExclusionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.deleteExclusion(request), expectedError); + }); + }); + + describe('getCmekSettings', () => { + it('invokes getCmekSettings without error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.GetCmekSettingsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.GetCmekSettingsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.logging.v2.CmekSettings(), + ); + client.innerApiCalls.getCmekSettings = stubSimpleCall(expectedResponse); + const [response] = await client.getCmekSettings(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getCmekSettings as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getCmekSettings as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('updateCmekSettings', () => { - it('invokes updateCmekSettings without error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.UpdateCmekSettingsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.UpdateCmekSettingsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.logging.v2.CmekSettings() - ); - client.innerApiCalls.updateCmekSettings = stubSimpleCall(expectedResponse); - const [response] = await client.updateCmekSettings(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateCmekSettings as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateCmekSettings as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getCmekSettings without error using callback', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.GetCmekSettingsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.GetCmekSettingsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.logging.v2.CmekSettings(), + ); + client.innerApiCalls.getCmekSettings = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getCmekSettings( + request, + ( + err?: Error | null, + result?: protos.google.logging.v2.ICmekSettings | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getCmekSettings as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getCmekSettings as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateCmekSettings without error using callback', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.UpdateCmekSettingsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.UpdateCmekSettingsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.logging.v2.CmekSettings() - ); - client.innerApiCalls.updateCmekSettings = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateCmekSettings( - request, - (err?: Error|null, result?: protos.google.logging.v2.ICmekSettings|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateCmekSettings as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateCmekSettings as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getCmekSettings with error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.GetCmekSettingsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.GetCmekSettingsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getCmekSettings = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getCmekSettings(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getCmekSettings as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getCmekSettings as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateCmekSettings with error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.UpdateCmekSettingsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.UpdateCmekSettingsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateCmekSettings = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateCmekSettings(request), expectedError); - const actualRequest = (client.innerApiCalls.updateCmekSettings as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateCmekSettings as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getCmekSettings with closed client', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.GetCmekSettingsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.GetCmekSettingsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getCmekSettings(request), expectedError); + }); + }); + + describe('updateCmekSettings', () => { + it('invokes updateCmekSettings without error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.UpdateCmekSettingsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.UpdateCmekSettingsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.logging.v2.CmekSettings(), + ); + client.innerApiCalls.updateCmekSettings = + stubSimpleCall(expectedResponse); + const [response] = await client.updateCmekSettings(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateCmekSettings as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateCmekSettings as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateCmekSettings with closed client', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.UpdateCmekSettingsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.UpdateCmekSettingsRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateCmekSettings(request), expectedError); - }); + it('invokes updateCmekSettings without error using callback', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.UpdateCmekSettingsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.UpdateCmekSettingsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.logging.v2.CmekSettings(), + ); + client.innerApiCalls.updateCmekSettings = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateCmekSettings( + request, + ( + err?: Error | null, + result?: protos.google.logging.v2.ICmekSettings | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateCmekSettings as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateCmekSettings as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('getSettings', () => { - it('invokes getSettings without error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.GetSettingsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.GetSettingsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.logging.v2.Settings() - ); - client.innerApiCalls.getSettings = stubSimpleCall(expectedResponse); - const [response] = await client.getSettings(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getSettings as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getSettings as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateCmekSettings with error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.UpdateCmekSettingsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.UpdateCmekSettingsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateCmekSettings = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.updateCmekSettings(request), expectedError); + const actualRequest = ( + client.innerApiCalls.updateCmekSettings as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateCmekSettings as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getSettings without error using callback', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.GetSettingsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.GetSettingsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.logging.v2.Settings() - ); - client.innerApiCalls.getSettings = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getSettings( - request, - (err?: Error|null, result?: protos.google.logging.v2.ISettings|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getSettings as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getSettings as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateCmekSettings with closed client', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.UpdateCmekSettingsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.UpdateCmekSettingsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.updateCmekSettings(request), expectedError); + }); + }); + + describe('getSettings', () => { + it('invokes getSettings without error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.GetSettingsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.GetSettingsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.logging.v2.Settings(), + ); + client.innerApiCalls.getSettings = stubSimpleCall(expectedResponse); + const [response] = await client.getSettings(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getSettings as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getSettings as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getSettings with error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.GetSettingsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.GetSettingsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getSettings = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getSettings(request), expectedError); - const actualRequest = (client.innerApiCalls.getSettings as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getSettings as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getSettings without error using callback', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.GetSettingsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.GetSettingsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.logging.v2.Settings(), + ); + client.innerApiCalls.getSettings = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getSettings( + request, + ( + err?: Error | null, + result?: protos.google.logging.v2.ISettings | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getSettings as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getSettings as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getSettings with closed client', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.GetSettingsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.GetSettingsRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getSettings(request), expectedError); - }); + it('invokes getSettings with error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.GetSettingsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.GetSettingsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getSettings = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getSettings(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getSettings as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getSettings as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('updateSettings', () => { - it('invokes updateSettings without error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.UpdateSettingsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.UpdateSettingsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.logging.v2.Settings() - ); - client.innerApiCalls.updateSettings = stubSimpleCall(expectedResponse); - const [response] = await client.updateSettings(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateSettings as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateSettings as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getSettings with closed client', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.GetSettingsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.GetSettingsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getSettings(request), expectedError); + }); + }); + + describe('updateSettings', () => { + it('invokes updateSettings without error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.UpdateSettingsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.UpdateSettingsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.logging.v2.Settings(), + ); + client.innerApiCalls.updateSettings = stubSimpleCall(expectedResponse); + const [response] = await client.updateSettings(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateSettings as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateSettings as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateSettings without error using callback', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.UpdateSettingsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.UpdateSettingsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.logging.v2.Settings() - ); - client.innerApiCalls.updateSettings = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateSettings( - request, - (err?: Error|null, result?: protos.google.logging.v2.ISettings|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateSettings as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateSettings as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateSettings without error using callback', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.UpdateSettingsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.UpdateSettingsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.logging.v2.Settings(), + ); + client.innerApiCalls.updateSettings = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateSettings( + request, + ( + err?: Error | null, + result?: protos.google.logging.v2.ISettings | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateSettings as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateSettings as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateSettings with error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.UpdateSettingsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.UpdateSettingsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateSettings = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateSettings(request), expectedError); - const actualRequest = (client.innerApiCalls.updateSettings as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateSettings as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateSettings with error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.UpdateSettingsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.UpdateSettingsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateSettings = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.updateSettings(request), expectedError); + const actualRequest = ( + client.innerApiCalls.updateSettings as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateSettings as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateSettings with closed client', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.UpdateSettingsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.UpdateSettingsRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateSettings(request), expectedError); - }); + it('invokes updateSettings with closed client', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.UpdateSettingsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.UpdateSettingsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.updateSettings(request), expectedError); + }); + }); + + describe('copyLogEntries', () => { + it('invokes copyLogEntries without error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.CopyLogEntriesRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.copyLogEntries = + stubLongRunningCall(expectedResponse); + const [operation] = await client.copyLogEntries(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); }); - describe('copyLogEntries', () => { - it('invokes copyLogEntries without error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.CopyLogEntriesRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.copyLogEntries = stubLongRunningCall(expectedResponse); - const [operation] = await client.copyLogEntries(request); - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes copyLogEntries without error using callback', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.CopyLogEntriesRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.copyLogEntries = + stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.copyLogEntries( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.logging.v2.ICopyLogEntriesResponse, + protos.google.logging.v2.ICopyLogEntriesMetadata + > | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const operation = (await promise) as LROperation< + protos.google.logging.v2.ICopyLogEntriesResponse, + protos.google.logging.v2.ICopyLogEntriesMetadata + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes copyLogEntries without error using callback', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.CopyLogEntriesRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.copyLogEntries = stubLongRunningCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.copyLogEntries( - request, - (err?: Error|null, - result?: LROperation|null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const operation = await promise as LROperation; - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes copyLogEntries with call error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.CopyLogEntriesRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.copyLogEntries = stubLongRunningCall( + undefined, + expectedError, + ); + await assert.rejects(client.copyLogEntries(request), expectedError); + }); - it('invokes copyLogEntries with call error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.CopyLogEntriesRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.copyLogEntries = stubLongRunningCall(undefined, expectedError); - await assert.rejects(client.copyLogEntries(request), expectedError); - }); + it('invokes copyLogEntries with LRO error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.CopyLogEntriesRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.copyLogEntries = stubLongRunningCall( + undefined, + undefined, + expectedError, + ); + const [operation] = await client.copyLogEntries(request); + await assert.rejects(operation.promise(), expectedError); + }); - it('invokes copyLogEntries with LRO error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.CopyLogEntriesRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.copyLogEntries = stubLongRunningCall(undefined, undefined, expectedError); - const [operation] = await client.copyLogEntries(request); - await assert.rejects(operation.promise(), expectedError); - }); + it('invokes checkCopyLogEntriesProgress without error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation(), + ); + expectedResponse.name = 'test'; + expectedResponse.response = { type_url: 'url', value: Buffer.from('') }; + expectedResponse.metadata = { type_url: 'url', value: Buffer.from('') }; + + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const decodedOperation = await client.checkCopyLogEntriesProgress( + expectedResponse.name, + ); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); - it('invokes checkCopyLogEntriesProgress without error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedResponse = generateSampleMessage( - new operationsProtos.google.longrunning.Operation() - ); - expectedResponse.name = 'test'; - expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; - expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')} - - client.operationsClient.getOperation = stubSimpleCall(expectedResponse); - const decodedOperation = await client.checkCopyLogEntriesProgress(expectedResponse.name); - assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); - assert(decodedOperation.metadata); - assert((client.operationsClient.getOperation as SinonStub).getCall(0)); - }); + it('invokes checkCopyLogEntriesProgress with error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const expectedError = new Error('expected'); + + client.operationsClient.getOperation = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.checkCopyLogEntriesProgress(''), + expectedError, + ); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + }); + + describe('listBuckets', () => { + it('invokes listBuckets without error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.ListBucketsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.ListBucketsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.logging.v2.LogBucket()), + generateSampleMessage(new protos.google.logging.v2.LogBucket()), + generateSampleMessage(new protos.google.logging.v2.LogBucket()), + ]; + client.innerApiCalls.listBuckets = stubSimpleCall(expectedResponse); + const [response] = await client.listBuckets(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listBuckets as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listBuckets as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkCopyLogEntriesProgress with error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedError = new Error('expected'); - - client.operationsClient.getOperation = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.checkCopyLogEntriesProgress(''), expectedError); - assert((client.operationsClient.getOperation as SinonStub) - .getCall(0)); - }); + it('invokes listBuckets without error using callback', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.ListBucketsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.ListBucketsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.logging.v2.LogBucket()), + generateSampleMessage(new protos.google.logging.v2.LogBucket()), + generateSampleMessage(new protos.google.logging.v2.LogBucket()), + ]; + client.innerApiCalls.listBuckets = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listBuckets( + request, + ( + err?: Error | null, + result?: protos.google.logging.v2.ILogBucket[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listBuckets as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listBuckets as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('listBuckets', () => { - it('invokes listBuckets without error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.ListBucketsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.ListBucketsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.logging.v2.LogBucket()), - generateSampleMessage(new protos.google.logging.v2.LogBucket()), - generateSampleMessage(new protos.google.logging.v2.LogBucket()), - ]; - client.innerApiCalls.listBuckets = stubSimpleCall(expectedResponse); - const [response] = await client.listBuckets(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listBuckets as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listBuckets as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listBuckets with error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.ListBucketsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.ListBucketsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listBuckets = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listBuckets(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listBuckets as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listBuckets as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listBuckets without error using callback', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.ListBucketsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.ListBucketsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.logging.v2.LogBucket()), - generateSampleMessage(new protos.google.logging.v2.LogBucket()), - generateSampleMessage(new protos.google.logging.v2.LogBucket()), - ]; - client.innerApiCalls.listBuckets = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listBuckets( - request, - (err?: Error|null, result?: protos.google.logging.v2.ILogBucket[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listBuckets as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listBuckets as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listBucketsStream without error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.ListBucketsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.ListBucketsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.logging.v2.LogBucket()), + generateSampleMessage(new protos.google.logging.v2.LogBucket()), + generateSampleMessage(new protos.google.logging.v2.LogBucket()), + ]; + client.descriptors.page.listBuckets.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listBucketsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.logging.v2.LogBucket[] = []; + stream.on('data', (response: protos.google.logging.v2.LogBucket) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listBuckets.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listBuckets, request), + ); + assert( + (client.descriptors.page.listBuckets.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('invokes listBuckets with error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.ListBucketsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.ListBucketsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listBuckets = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listBuckets(request), expectedError); - const actualRequest = (client.innerApiCalls.listBuckets as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listBuckets as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listBucketsStream with error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.ListBucketsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.ListBucketsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listBuckets.createStream = stubPageStreamingCall( + undefined, + expectedError, + ); + const stream = client.listBucketsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.logging.v2.LogBucket[] = []; + stream.on('data', (response: protos.google.logging.v2.LogBucket) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listBuckets.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listBuckets, request), + ); + assert( + (client.descriptors.page.listBuckets.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('invokes listBucketsStream without error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.ListBucketsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.ListBucketsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.logging.v2.LogBucket()), - generateSampleMessage(new protos.google.logging.v2.LogBucket()), - generateSampleMessage(new protos.google.logging.v2.LogBucket()), - ]; - client.descriptors.page.listBuckets.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listBucketsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.logging.v2.LogBucket[] = []; - stream.on('data', (response: protos.google.logging.v2.LogBucket) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.listBuckets.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listBuckets, request)); - assert( - (client.descriptors.page.listBuckets.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listBuckets without error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.ListBucketsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.ListBucketsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.logging.v2.LogBucket()), + generateSampleMessage(new protos.google.logging.v2.LogBucket()), + generateSampleMessage(new protos.google.logging.v2.LogBucket()), + ]; + client.descriptors.page.listBuckets.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.logging.v2.ILogBucket[] = []; + const iterable = client.listBucketsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + (client.descriptors.page.listBuckets.asyncIterate as SinonStub).getCall( + 0, + ).args[1], + request, + ); + assert( + (client.descriptors.page.listBuckets.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('invokes listBucketsStream with error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.ListBucketsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.ListBucketsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listBuckets.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listBucketsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.logging.v2.LogBucket[] = []; - stream.on('data', (response: protos.google.logging.v2.LogBucket) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listBuckets.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listBuckets, request)); - assert( - (client.descriptors.page.listBuckets.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listBuckets with error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.ListBucketsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.ListBucketsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listBuckets.asyncIterate = stubAsyncIterationCall( + undefined, + expectedError, + ); + const iterable = client.listBucketsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.logging.v2.ILogBucket[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + (client.descriptors.page.listBuckets.asyncIterate as SinonStub).getCall( + 0, + ).args[1], + request, + ); + assert( + (client.descriptors.page.listBuckets.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + }); + + describe('listViews', () => { + it('invokes listViews without error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.ListViewsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.ListViewsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.logging.v2.LogView()), + generateSampleMessage(new protos.google.logging.v2.LogView()), + generateSampleMessage(new protos.google.logging.v2.LogView()), + ]; + client.innerApiCalls.listViews = stubSimpleCall(expectedResponse); + const [response] = await client.listViews(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listViews as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listViews as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('uses async iteration with listBuckets without error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.ListBucketsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.ListBucketsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.logging.v2.LogBucket()), - generateSampleMessage(new protos.google.logging.v2.LogBucket()), - generateSampleMessage(new protos.google.logging.v2.LogBucket()), - ]; - client.descriptors.page.listBuckets.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.logging.v2.ILogBucket[] = []; - const iterable = client.listBucketsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); + it('invokes listViews without error using callback', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.ListViewsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.ListViewsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.logging.v2.LogView()), + generateSampleMessage(new protos.google.logging.v2.LogView()), + generateSampleMessage(new protos.google.logging.v2.LogView()), + ]; + client.innerApiCalls.listViews = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listViews( + request, + ( + err?: Error | null, + result?: protos.google.logging.v2.ILogView[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listBuckets.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listBuckets.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); - - it('uses async iteration with listBuckets with error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.ListBucketsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.ListBucketsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listBuckets.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listBucketsAsync(request); - await assert.rejects(async () => { - const responses: protos.google.logging.v2.ILogBucket[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listBuckets.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listBuckets.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listViews as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listViews as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('listViews', () => { - it('invokes listViews without error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.ListViewsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.ListViewsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.logging.v2.LogView()), - generateSampleMessage(new protos.google.logging.v2.LogView()), - generateSampleMessage(new protos.google.logging.v2.LogView()), - ]; - client.innerApiCalls.listViews = stubSimpleCall(expectedResponse); - const [response] = await client.listViews(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listViews as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listViews as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listViews with error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.ListViewsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.ListViewsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listViews = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.listViews(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listViews as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listViews as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listViews without error using callback', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.ListViewsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.ListViewsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.logging.v2.LogView()), - generateSampleMessage(new protos.google.logging.v2.LogView()), - generateSampleMessage(new protos.google.logging.v2.LogView()), - ]; - client.innerApiCalls.listViews = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listViews( - request, - (err?: Error|null, result?: protos.google.logging.v2.ILogView[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listViews as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listViews as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listViewsStream without error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.ListViewsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.ListViewsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.logging.v2.LogView()), + generateSampleMessage(new protos.google.logging.v2.LogView()), + generateSampleMessage(new protos.google.logging.v2.LogView()), + ]; + client.descriptors.page.listViews.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listViewsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.logging.v2.LogView[] = []; + stream.on('data', (response: protos.google.logging.v2.LogView) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listViews.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listViews, request), + ); + assert( + (client.descriptors.page.listViews.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('invokes listViews with error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.ListViewsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.ListViewsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listViews = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listViews(request), expectedError); - const actualRequest = (client.innerApiCalls.listViews as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listViews as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listViewsStream with error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.ListViewsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.ListViewsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listViews.createStream = stubPageStreamingCall( + undefined, + expectedError, + ); + const stream = client.listViewsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.logging.v2.LogView[] = []; + stream.on('data', (response: protos.google.logging.v2.LogView) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listViews.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listViews, request), + ); + assert( + (client.descriptors.page.listViews.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('invokes listViewsStream without error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.ListViewsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.ListViewsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.logging.v2.LogView()), - generateSampleMessage(new protos.google.logging.v2.LogView()), - generateSampleMessage(new protos.google.logging.v2.LogView()), - ]; - client.descriptors.page.listViews.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listViewsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.logging.v2.LogView[] = []; - stream.on('data', (response: protos.google.logging.v2.LogView) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.listViews.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listViews, request)); - assert( - (client.descriptors.page.listViews.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listViews without error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.ListViewsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.ListViewsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.logging.v2.LogView()), + generateSampleMessage(new protos.google.logging.v2.LogView()), + generateSampleMessage(new protos.google.logging.v2.LogView()), + ]; + client.descriptors.page.listViews.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.logging.v2.ILogView[] = []; + const iterable = client.listViewsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + (client.descriptors.page.listViews.asyncIterate as SinonStub).getCall(0) + .args[1], + request, + ); + assert( + (client.descriptors.page.listViews.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('invokes listViewsStream with error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.ListViewsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.ListViewsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listViews.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listViewsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.logging.v2.LogView[] = []; - stream.on('data', (response: protos.google.logging.v2.LogView) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listViews.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listViews, request)); - assert( - (client.descriptors.page.listViews.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listViews with error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.ListViewsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.ListViewsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listViews.asyncIterate = stubAsyncIterationCall( + undefined, + expectedError, + ); + const iterable = client.listViewsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.logging.v2.ILogView[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + (client.descriptors.page.listViews.asyncIterate as SinonStub).getCall(0) + .args[1], + request, + ); + assert( + (client.descriptors.page.listViews.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + }); + + describe('listSinks', () => { + it('invokes listSinks without error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.ListSinksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.ListSinksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.logging.v2.LogSink()), + generateSampleMessage(new protos.google.logging.v2.LogSink()), + generateSampleMessage(new protos.google.logging.v2.LogSink()), + ]; + client.innerApiCalls.listSinks = stubSimpleCall(expectedResponse); + const [response] = await client.listSinks(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listSinks as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listSinks as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('uses async iteration with listViews without error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.ListViewsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.ListViewsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.logging.v2.LogView()), - generateSampleMessage(new protos.google.logging.v2.LogView()), - generateSampleMessage(new protos.google.logging.v2.LogView()), - ]; - client.descriptors.page.listViews.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.logging.v2.ILogView[] = []; - const iterable = client.listViewsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); + it('invokes listSinks without error using callback', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.ListSinksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.ListSinksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.logging.v2.LogSink()), + generateSampleMessage(new protos.google.logging.v2.LogSink()), + generateSampleMessage(new protos.google.logging.v2.LogSink()), + ]; + client.innerApiCalls.listSinks = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listSinks( + request, + ( + err?: Error | null, + result?: protos.google.logging.v2.ILogSink[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listViews.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listViews.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); - - it('uses async iteration with listViews with error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.ListViewsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.ListViewsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listViews.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listViewsAsync(request); - await assert.rejects(async () => { - const responses: protos.google.logging.v2.ILogView[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listViews.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listViews.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listSinks as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listSinks as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('listSinks', () => { - it('invokes listSinks without error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.ListSinksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.ListSinksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.logging.v2.LogSink()), - generateSampleMessage(new protos.google.logging.v2.LogSink()), - generateSampleMessage(new protos.google.logging.v2.LogSink()), - ]; - client.innerApiCalls.listSinks = stubSimpleCall(expectedResponse); - const [response] = await client.listSinks(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listSinks as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listSinks as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listSinks with error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.ListSinksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.ListSinksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listSinks = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.listSinks(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listSinks as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listSinks as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listSinks without error using callback', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.ListSinksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.ListSinksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.logging.v2.LogSink()), - generateSampleMessage(new protos.google.logging.v2.LogSink()), - generateSampleMessage(new protos.google.logging.v2.LogSink()), - ]; - client.innerApiCalls.listSinks = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listSinks( - request, - (err?: Error|null, result?: protos.google.logging.v2.ILogSink[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listSinks as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listSinks as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listSinksStream without error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.ListSinksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.ListSinksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.logging.v2.LogSink()), + generateSampleMessage(new protos.google.logging.v2.LogSink()), + generateSampleMessage(new protos.google.logging.v2.LogSink()), + ]; + client.descriptors.page.listSinks.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listSinksStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.logging.v2.LogSink[] = []; + stream.on('data', (response: protos.google.logging.v2.LogSink) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listSinks.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listSinks, request), + ); + assert( + (client.descriptors.page.listSinks.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('invokes listSinks with error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.ListSinksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.ListSinksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listSinks = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listSinks(request), expectedError); - const actualRequest = (client.innerApiCalls.listSinks as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listSinks as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listSinksStream with error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.ListSinksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.ListSinksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listSinks.createStream = stubPageStreamingCall( + undefined, + expectedError, + ); + const stream = client.listSinksStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.logging.v2.LogSink[] = []; + stream.on('data', (response: protos.google.logging.v2.LogSink) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listSinks.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listSinks, request), + ); + assert( + (client.descriptors.page.listSinks.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('invokes listSinksStream without error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.ListSinksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.ListSinksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.logging.v2.LogSink()), - generateSampleMessage(new protos.google.logging.v2.LogSink()), - generateSampleMessage(new protos.google.logging.v2.LogSink()), - ]; - client.descriptors.page.listSinks.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listSinksStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.logging.v2.LogSink[] = []; - stream.on('data', (response: protos.google.logging.v2.LogSink) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.listSinks.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listSinks, request)); - assert( - (client.descriptors.page.listSinks.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listSinks without error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.ListSinksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.ListSinksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.logging.v2.LogSink()), + generateSampleMessage(new protos.google.logging.v2.LogSink()), + generateSampleMessage(new protos.google.logging.v2.LogSink()), + ]; + client.descriptors.page.listSinks.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.logging.v2.ILogSink[] = []; + const iterable = client.listSinksAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + (client.descriptors.page.listSinks.asyncIterate as SinonStub).getCall(0) + .args[1], + request, + ); + assert( + (client.descriptors.page.listSinks.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('invokes listSinksStream with error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.ListSinksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.ListSinksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listSinks.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listSinksStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.logging.v2.LogSink[] = []; - stream.on('data', (response: protos.google.logging.v2.LogSink) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listSinks.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listSinks, request)); - assert( - (client.descriptors.page.listSinks.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listSinks with error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.ListSinksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.ListSinksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listSinks.asyncIterate = stubAsyncIterationCall( + undefined, + expectedError, + ); + const iterable = client.listSinksAsync(request); + await assert.rejects(async () => { + const responses: protos.google.logging.v2.ILogSink[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + (client.descriptors.page.listSinks.asyncIterate as SinonStub).getCall(0) + .args[1], + request, + ); + assert( + (client.descriptors.page.listSinks.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + }); + + describe('listExclusions', () => { + it('invokes listExclusions without error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.ListExclusionsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.ListExclusionsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.logging.v2.LogExclusion()), + generateSampleMessage(new protos.google.logging.v2.LogExclusion()), + generateSampleMessage(new protos.google.logging.v2.LogExclusion()), + ]; + client.innerApiCalls.listExclusions = stubSimpleCall(expectedResponse); + const [response] = await client.listExclusions(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listExclusions as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listExclusions as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('uses async iteration with listSinks without error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.ListSinksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.ListSinksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.logging.v2.LogSink()), - generateSampleMessage(new protos.google.logging.v2.LogSink()), - generateSampleMessage(new protos.google.logging.v2.LogSink()), - ]; - client.descriptors.page.listSinks.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.logging.v2.ILogSink[] = []; - const iterable = client.listSinksAsync(request); - for await (const resource of iterable) { - responses.push(resource!); + it('invokes listExclusions without error using callback', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.ListExclusionsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.ListExclusionsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.logging.v2.LogExclusion()), + generateSampleMessage(new protos.google.logging.v2.LogExclusion()), + generateSampleMessage(new protos.google.logging.v2.LogExclusion()), + ]; + client.innerApiCalls.listExclusions = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listExclusions( + request, + ( + err?: Error | null, + result?: protos.google.logging.v2.ILogExclusion[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listSinks.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listSinks.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); - - it('uses async iteration with listSinks with error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.ListSinksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.ListSinksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listSinks.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listSinksAsync(request); - await assert.rejects(async () => { - const responses: protos.google.logging.v2.ILogSink[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listSinks.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listSinks.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listExclusions as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listExclusions as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('listExclusions', () => { - it('invokes listExclusions without error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.ListExclusionsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.ListExclusionsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.logging.v2.LogExclusion()), - generateSampleMessage(new protos.google.logging.v2.LogExclusion()), - generateSampleMessage(new protos.google.logging.v2.LogExclusion()), - ]; - client.innerApiCalls.listExclusions = stubSimpleCall(expectedResponse); - const [response] = await client.listExclusions(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listExclusions as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listExclusions as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listExclusions without error using callback', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.ListExclusionsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.ListExclusionsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.logging.v2.LogExclusion()), - generateSampleMessage(new protos.google.logging.v2.LogExclusion()), - generateSampleMessage(new protos.google.logging.v2.LogExclusion()), - ]; - client.innerApiCalls.listExclusions = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listExclusions( - request, - (err?: Error|null, result?: protos.google.logging.v2.ILogExclusion[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listExclusions as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listExclusions as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listExclusions with error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.ListExclusionsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.ListExclusionsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listExclusions = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listExclusions(request), expectedError); - const actualRequest = (client.innerApiCalls.listExclusions as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listExclusions as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listExclusionsStream without error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.ListExclusionsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.ListExclusionsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.logging.v2.LogExclusion()), - generateSampleMessage(new protos.google.logging.v2.LogExclusion()), - generateSampleMessage(new protos.google.logging.v2.LogExclusion()), - ]; - client.descriptors.page.listExclusions.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listExclusionsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.logging.v2.LogExclusion[] = []; - stream.on('data', (response: protos.google.logging.v2.LogExclusion) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.listExclusions.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listExclusions, request)); - assert( - (client.descriptors.page.listExclusions.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listExclusions with error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.ListExclusionsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.ListExclusionsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listExclusions = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listExclusions(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listExclusions as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listExclusions as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listExclusionsStream with error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.ListExclusionsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.ListExclusionsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listExclusions.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listExclusionsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.logging.v2.LogExclusion[] = []; - stream.on('data', (response: protos.google.logging.v2.LogExclusion) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listExclusions.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listExclusions, request)); - assert( - (client.descriptors.page.listExclusions.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listExclusionsStream without error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.ListExclusionsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.ListExclusionsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.logging.v2.LogExclusion()), + generateSampleMessage(new protos.google.logging.v2.LogExclusion()), + generateSampleMessage(new protos.google.logging.v2.LogExclusion()), + ]; + client.descriptors.page.listExclusions.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listExclusionsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.logging.v2.LogExclusion[] = []; + stream.on('data', (response: protos.google.logging.v2.LogExclusion) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listExclusions.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listExclusions, request), + ); + assert( + (client.descriptors.page.listExclusions.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('uses async iteration with listExclusions without error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.ListExclusionsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.ListExclusionsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.logging.v2.LogExclusion()), - generateSampleMessage(new protos.google.logging.v2.LogExclusion()), - generateSampleMessage(new protos.google.logging.v2.LogExclusion()), - ]; - client.descriptors.page.listExclusions.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.logging.v2.ILogExclusion[] = []; - const iterable = client.listExclusionsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listExclusions.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listExclusions.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listExclusionsStream with error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.ListExclusionsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.ListExclusionsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listExclusions.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listExclusionsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.logging.v2.LogExclusion[] = []; + stream.on('data', (response: protos.google.logging.v2.LogExclusion) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listExclusions.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listExclusions, request), + ); + assert( + (client.descriptors.page.listExclusions.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('uses async iteration with listExclusions with error', async () => { - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.ListExclusionsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.ListExclusionsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listExclusions.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listExclusionsAsync(request); - await assert.rejects(async () => { - const responses: protos.google.logging.v2.ILogExclusion[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listExclusions.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listExclusions.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listExclusions without error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.ListExclusionsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.ListExclusionsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.logging.v2.LogExclusion()), + generateSampleMessage(new protos.google.logging.v2.LogExclusion()), + generateSampleMessage(new protos.google.logging.v2.LogExclusion()), + ]; + client.descriptors.page.listExclusions.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.logging.v2.ILogExclusion[] = []; + const iterable = client.listExclusionsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listExclusions.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listExclusions.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); }); - describe('Path templates', () => { - - describe('billingAccountCmekSettings', async () => { - const fakePath = "/rendered/path/billingAccountCmekSettings"; - const expectedParameters = { - billing_account: "billingAccountValue", - }; - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.billingAccountCmekSettingsPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.billingAccountCmekSettingsPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('billingAccountCmekSettingsPath', () => { - const result = client.billingAccountCmekSettingsPath("billingAccountValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.billingAccountCmekSettingsPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchBillingAccountFromBillingAccountCmekSettingsName', () => { - const result = client.matchBillingAccountFromBillingAccountCmekSettingsName(fakePath); - assert.strictEqual(result, "billingAccountValue"); - assert((client.pathTemplates.billingAccountCmekSettingsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('uses async iteration with listExclusions with error', async () => { + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.ListExclusionsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.ListExclusionsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listExclusions.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listExclusionsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.logging.v2.ILogExclusion[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listExclusions.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listExclusions.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + }); + + describe('Path templates', () => { + describe('billingAccountCmekSettings', async () => { + const fakePath = '/rendered/path/billingAccountCmekSettings'; + const expectedParameters = { + billing_account: 'billingAccountValue', + }; + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.billingAccountCmekSettingsPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.billingAccountCmekSettingsPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('billingAccountCmekSettingsPath', () => { + const result = client.billingAccountCmekSettingsPath( + 'billingAccountValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.billingAccountCmekSettingsPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchBillingAccountFromBillingAccountCmekSettingsName', () => { + const result = + client.matchBillingAccountFromBillingAccountCmekSettingsName( + fakePath, + ); + assert.strictEqual(result, 'billingAccountValue'); + assert( + ( + client.pathTemplates.billingAccountCmekSettingsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('billingAccountExclusion', async () => { - const fakePath = "/rendered/path/billingAccountExclusion"; - const expectedParameters = { - billing_account: "billingAccountValue", - exclusion: "exclusionValue", - }; - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.billingAccountExclusionPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.billingAccountExclusionPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('billingAccountExclusionPath', () => { - const result = client.billingAccountExclusionPath("billingAccountValue", "exclusionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.billingAccountExclusionPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchBillingAccountFromBillingAccountExclusionName', () => { - const result = client.matchBillingAccountFromBillingAccountExclusionName(fakePath); - assert.strictEqual(result, "billingAccountValue"); - assert((client.pathTemplates.billingAccountExclusionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchExclusionFromBillingAccountExclusionName', () => { - const result = client.matchExclusionFromBillingAccountExclusionName(fakePath); - assert.strictEqual(result, "exclusionValue"); - assert((client.pathTemplates.billingAccountExclusionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('billingAccountExclusion', async () => { + const fakePath = '/rendered/path/billingAccountExclusion'; + const expectedParameters = { + billing_account: 'billingAccountValue', + exclusion: 'exclusionValue', + }; + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.billingAccountExclusionPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.billingAccountExclusionPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('billingAccountExclusionPath', () => { + const result = client.billingAccountExclusionPath( + 'billingAccountValue', + 'exclusionValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.billingAccountExclusionPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchBillingAccountFromBillingAccountExclusionName', () => { + const result = + client.matchBillingAccountFromBillingAccountExclusionName(fakePath); + assert.strictEqual(result, 'billingAccountValue'); + assert( + ( + client.pathTemplates.billingAccountExclusionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchExclusionFromBillingAccountExclusionName', () => { + const result = + client.matchExclusionFromBillingAccountExclusionName(fakePath); + assert.strictEqual(result, 'exclusionValue'); + assert( + ( + client.pathTemplates.billingAccountExclusionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('billingAccountLocationBucket', async () => { - const fakePath = "/rendered/path/billingAccountLocationBucket"; - const expectedParameters = { - billing_account: "billingAccountValue", - location: "locationValue", - bucket: "bucketValue", - }; - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.billingAccountLocationBucketPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.billingAccountLocationBucketPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('billingAccountLocationBucketPath', () => { - const result = client.billingAccountLocationBucketPath("billingAccountValue", "locationValue", "bucketValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.billingAccountLocationBucketPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchBillingAccountFromBillingAccountLocationBucketName', () => { - const result = client.matchBillingAccountFromBillingAccountLocationBucketName(fakePath); - assert.strictEqual(result, "billingAccountValue"); - assert((client.pathTemplates.billingAccountLocationBucketPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromBillingAccountLocationBucketName', () => { - const result = client.matchLocationFromBillingAccountLocationBucketName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.billingAccountLocationBucketPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBucketFromBillingAccountLocationBucketName', () => { - const result = client.matchBucketFromBillingAccountLocationBucketName(fakePath); - assert.strictEqual(result, "bucketValue"); - assert((client.pathTemplates.billingAccountLocationBucketPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('billingAccountLocationBucket', async () => { + const fakePath = '/rendered/path/billingAccountLocationBucket'; + const expectedParameters = { + billing_account: 'billingAccountValue', + location: 'locationValue', + bucket: 'bucketValue', + }; + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.billingAccountLocationBucketPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.billingAccountLocationBucketPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('billingAccountLocationBucketPath', () => { + const result = client.billingAccountLocationBucketPath( + 'billingAccountValue', + 'locationValue', + 'bucketValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.billingAccountLocationBucketPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchBillingAccountFromBillingAccountLocationBucketName', () => { + const result = + client.matchBillingAccountFromBillingAccountLocationBucketName( + fakePath, + ); + assert.strictEqual(result, 'billingAccountValue'); + assert( + ( + client.pathTemplates.billingAccountLocationBucketPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromBillingAccountLocationBucketName', () => { + const result = + client.matchLocationFromBillingAccountLocationBucketName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + ( + client.pathTemplates.billingAccountLocationBucketPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBucketFromBillingAccountLocationBucketName', () => { + const result = + client.matchBucketFromBillingAccountLocationBucketName(fakePath); + assert.strictEqual(result, 'bucketValue'); + assert( + ( + client.pathTemplates.billingAccountLocationBucketPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('billingAccountLocationBucketView', async () => { - const fakePath = "/rendered/path/billingAccountLocationBucketView"; - const expectedParameters = { - billing_account: "billingAccountValue", - location: "locationValue", - bucket: "bucketValue", - view: "viewValue", - }; - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.billingAccountLocationBucketViewPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.billingAccountLocationBucketViewPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('billingAccountLocationBucketViewPath', () => { - const result = client.billingAccountLocationBucketViewPath("billingAccountValue", "locationValue", "bucketValue", "viewValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.billingAccountLocationBucketViewPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchBillingAccountFromBillingAccountLocationBucketViewName', () => { - const result = client.matchBillingAccountFromBillingAccountLocationBucketViewName(fakePath); - assert.strictEqual(result, "billingAccountValue"); - assert((client.pathTemplates.billingAccountLocationBucketViewPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromBillingAccountLocationBucketViewName', () => { - const result = client.matchLocationFromBillingAccountLocationBucketViewName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.billingAccountLocationBucketViewPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBucketFromBillingAccountLocationBucketViewName', () => { - const result = client.matchBucketFromBillingAccountLocationBucketViewName(fakePath); - assert.strictEqual(result, "bucketValue"); - assert((client.pathTemplates.billingAccountLocationBucketViewPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchViewFromBillingAccountLocationBucketViewName', () => { - const result = client.matchViewFromBillingAccountLocationBucketViewName(fakePath); - assert.strictEqual(result, "viewValue"); - assert((client.pathTemplates.billingAccountLocationBucketViewPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('billingAccountLocationBucketView', async () => { + const fakePath = '/rendered/path/billingAccountLocationBucketView'; + const expectedParameters = { + billing_account: 'billingAccountValue', + location: 'locationValue', + bucket: 'bucketValue', + view: 'viewValue', + }; + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.billingAccountLocationBucketViewPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.billingAccountLocationBucketViewPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('billingAccountLocationBucketViewPath', () => { + const result = client.billingAccountLocationBucketViewPath( + 'billingAccountValue', + 'locationValue', + 'bucketValue', + 'viewValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.billingAccountLocationBucketViewPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchBillingAccountFromBillingAccountLocationBucketViewName', () => { + const result = + client.matchBillingAccountFromBillingAccountLocationBucketViewName( + fakePath, + ); + assert.strictEqual(result, 'billingAccountValue'); + assert( + ( + client.pathTemplates.billingAccountLocationBucketViewPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromBillingAccountLocationBucketViewName', () => { + const result = + client.matchLocationFromBillingAccountLocationBucketViewName( + fakePath, + ); + assert.strictEqual(result, 'locationValue'); + assert( + ( + client.pathTemplates.billingAccountLocationBucketViewPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBucketFromBillingAccountLocationBucketViewName', () => { + const result = + client.matchBucketFromBillingAccountLocationBucketViewName(fakePath); + assert.strictEqual(result, 'bucketValue'); + assert( + ( + client.pathTemplates.billingAccountLocationBucketViewPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchViewFromBillingAccountLocationBucketViewName', () => { + const result = + client.matchViewFromBillingAccountLocationBucketViewName(fakePath); + assert.strictEqual(result, 'viewValue'); + assert( + ( + client.pathTemplates.billingAccountLocationBucketViewPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('billingAccountLog', async () => { - const fakePath = "/rendered/path/billingAccountLog"; - const expectedParameters = { - billing_account: "billingAccountValue", - log: "logValue", - }; - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.billingAccountLogPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.billingAccountLogPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('billingAccountLogPath', () => { - const result = client.billingAccountLogPath("billingAccountValue", "logValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.billingAccountLogPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchBillingAccountFromBillingAccountLogName', () => { - const result = client.matchBillingAccountFromBillingAccountLogName(fakePath); - assert.strictEqual(result, "billingAccountValue"); - assert((client.pathTemplates.billingAccountLogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLogFromBillingAccountLogName', () => { - const result = client.matchLogFromBillingAccountLogName(fakePath); - assert.strictEqual(result, "logValue"); - assert((client.pathTemplates.billingAccountLogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('billingAccountLog', async () => { + const fakePath = '/rendered/path/billingAccountLog'; + const expectedParameters = { + billing_account: 'billingAccountValue', + log: 'logValue', + }; + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.billingAccountLogPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.billingAccountLogPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('billingAccountLogPath', () => { + const result = client.billingAccountLogPath( + 'billingAccountValue', + 'logValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.billingAccountLogPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchBillingAccountFromBillingAccountLogName', () => { + const result = + client.matchBillingAccountFromBillingAccountLogName(fakePath); + assert.strictEqual(result, 'billingAccountValue'); + assert( + ( + client.pathTemplates.billingAccountLogPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLogFromBillingAccountLogName', () => { + const result = client.matchLogFromBillingAccountLogName(fakePath); + assert.strictEqual(result, 'logValue'); + assert( + ( + client.pathTemplates.billingAccountLogPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('billingAccountSettings', async () => { - const fakePath = "/rendered/path/billingAccountSettings"; - const expectedParameters = { - billing_account: "billingAccountValue", - }; - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.billingAccountSettingsPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.billingAccountSettingsPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('billingAccountSettingsPath', () => { - const result = client.billingAccountSettingsPath("billingAccountValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.billingAccountSettingsPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchBillingAccountFromBillingAccountSettingsName', () => { - const result = client.matchBillingAccountFromBillingAccountSettingsName(fakePath); - assert.strictEqual(result, "billingAccountValue"); - assert((client.pathTemplates.billingAccountSettingsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('billingAccountSettings', async () => { + const fakePath = '/rendered/path/billingAccountSettings'; + const expectedParameters = { + billing_account: 'billingAccountValue', + }; + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.billingAccountSettingsPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.billingAccountSettingsPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('billingAccountSettingsPath', () => { + const result = client.billingAccountSettingsPath('billingAccountValue'); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.billingAccountSettingsPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchBillingAccountFromBillingAccountSettingsName', () => { + const result = + client.matchBillingAccountFromBillingAccountSettingsName(fakePath); + assert.strictEqual(result, 'billingAccountValue'); + assert( + ( + client.pathTemplates.billingAccountSettingsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('billingAccountSink', async () => { - const fakePath = "/rendered/path/billingAccountSink"; - const expectedParameters = { - billing_account: "billingAccountValue", - sink: "sinkValue", - }; - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.billingAccountSinkPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.billingAccountSinkPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('billingAccountSinkPath', () => { - const result = client.billingAccountSinkPath("billingAccountValue", "sinkValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.billingAccountSinkPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchBillingAccountFromBillingAccountSinkName', () => { - const result = client.matchBillingAccountFromBillingAccountSinkName(fakePath); - assert.strictEqual(result, "billingAccountValue"); - assert((client.pathTemplates.billingAccountSinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchSinkFromBillingAccountSinkName', () => { - const result = client.matchSinkFromBillingAccountSinkName(fakePath); - assert.strictEqual(result, "sinkValue"); - assert((client.pathTemplates.billingAccountSinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('billingAccountSink', async () => { + const fakePath = '/rendered/path/billingAccountSink'; + const expectedParameters = { + billing_account: 'billingAccountValue', + sink: 'sinkValue', + }; + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.billingAccountSinkPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.billingAccountSinkPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('billingAccountSinkPath', () => { + const result = client.billingAccountSinkPath( + 'billingAccountValue', + 'sinkValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.billingAccountSinkPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchBillingAccountFromBillingAccountSinkName', () => { + const result = + client.matchBillingAccountFromBillingAccountSinkName(fakePath); + assert.strictEqual(result, 'billingAccountValue'); + assert( + ( + client.pathTemplates.billingAccountSinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchSinkFromBillingAccountSinkName', () => { + const result = client.matchSinkFromBillingAccountSinkName(fakePath); + assert.strictEqual(result, 'sinkValue'); + assert( + ( + client.pathTemplates.billingAccountSinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('folderCmekSettings', async () => { - const fakePath = "/rendered/path/folderCmekSettings"; - const expectedParameters = { - folder: "folderValue", - }; - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.folderCmekSettingsPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderCmekSettingsPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderCmekSettingsPath', () => { - const result = client.folderCmekSettingsPath("folderValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderCmekSettingsPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderCmekSettingsName', () => { - const result = client.matchFolderFromFolderCmekSettingsName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderCmekSettingsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('folderCmekSettings', async () => { + const fakePath = '/rendered/path/folderCmekSettings'; + const expectedParameters = { + folder: 'folderValue', + }; + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.folderCmekSettingsPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderCmekSettingsPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderCmekSettingsPath', () => { + const result = client.folderCmekSettingsPath('folderValue'); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.folderCmekSettingsPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderCmekSettingsName', () => { + const result = client.matchFolderFromFolderCmekSettingsName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + ( + client.pathTemplates.folderCmekSettingsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('folderExclusion', async () => { - const fakePath = "/rendered/path/folderExclusion"; - const expectedParameters = { - folder: "folderValue", - exclusion: "exclusionValue", - }; - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.folderExclusionPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderExclusionPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderExclusionPath', () => { - const result = client.folderExclusionPath("folderValue", "exclusionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderExclusionPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderExclusionName', () => { - const result = client.matchFolderFromFolderExclusionName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderExclusionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchExclusionFromFolderExclusionName', () => { - const result = client.matchExclusionFromFolderExclusionName(fakePath); - assert.strictEqual(result, "exclusionValue"); - assert((client.pathTemplates.folderExclusionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('folderExclusion', async () => { + const fakePath = '/rendered/path/folderExclusion'; + const expectedParameters = { + folder: 'folderValue', + exclusion: 'exclusionValue', + }; + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.folderExclusionPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderExclusionPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderExclusionPath', () => { + const result = client.folderExclusionPath( + 'folderValue', + 'exclusionValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.folderExclusionPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderExclusionName', () => { + const result = client.matchFolderFromFolderExclusionName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + (client.pathTemplates.folderExclusionPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchExclusionFromFolderExclusionName', () => { + const result = client.matchExclusionFromFolderExclusionName(fakePath); + assert.strictEqual(result, 'exclusionValue'); + assert( + (client.pathTemplates.folderExclusionPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('folderLocationBucket', async () => { - const fakePath = "/rendered/path/folderLocationBucket"; - const expectedParameters = { - folder: "folderValue", - location: "locationValue", - bucket: "bucketValue", - }; - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.folderLocationBucketPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderLocationBucketPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderLocationBucketPath', () => { - const result = client.folderLocationBucketPath("folderValue", "locationValue", "bucketValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderLocationBucketPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderLocationBucketName', () => { - const result = client.matchFolderFromFolderLocationBucketName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderLocationBucketPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromFolderLocationBucketName', () => { - const result = client.matchLocationFromFolderLocationBucketName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.folderLocationBucketPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBucketFromFolderLocationBucketName', () => { - const result = client.matchBucketFromFolderLocationBucketName(fakePath); - assert.strictEqual(result, "bucketValue"); - assert((client.pathTemplates.folderLocationBucketPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('folderLocationBucket', async () => { + const fakePath = '/rendered/path/folderLocationBucket'; + const expectedParameters = { + folder: 'folderValue', + location: 'locationValue', + bucket: 'bucketValue', + }; + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.folderLocationBucketPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderLocationBucketPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderLocationBucketPath', () => { + const result = client.folderLocationBucketPath( + 'folderValue', + 'locationValue', + 'bucketValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.folderLocationBucketPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderLocationBucketName', () => { + const result = client.matchFolderFromFolderLocationBucketName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + ( + client.pathTemplates.folderLocationBucketPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromFolderLocationBucketName', () => { + const result = + client.matchLocationFromFolderLocationBucketName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + ( + client.pathTemplates.folderLocationBucketPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBucketFromFolderLocationBucketName', () => { + const result = client.matchBucketFromFolderLocationBucketName(fakePath); + assert.strictEqual(result, 'bucketValue'); + assert( + ( + client.pathTemplates.folderLocationBucketPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('folderLocationBucketView', async () => { - const fakePath = "/rendered/path/folderLocationBucketView"; - const expectedParameters = { - folder: "folderValue", - location: "locationValue", - bucket: "bucketValue", - view: "viewValue", - }; - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.folderLocationBucketViewPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderLocationBucketViewPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderLocationBucketViewPath', () => { - const result = client.folderLocationBucketViewPath("folderValue", "locationValue", "bucketValue", "viewValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderLocationBucketViewPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderLocationBucketViewName', () => { - const result = client.matchFolderFromFolderLocationBucketViewName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderLocationBucketViewPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromFolderLocationBucketViewName', () => { - const result = client.matchLocationFromFolderLocationBucketViewName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.folderLocationBucketViewPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBucketFromFolderLocationBucketViewName', () => { - const result = client.matchBucketFromFolderLocationBucketViewName(fakePath); - assert.strictEqual(result, "bucketValue"); - assert((client.pathTemplates.folderLocationBucketViewPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchViewFromFolderLocationBucketViewName', () => { - const result = client.matchViewFromFolderLocationBucketViewName(fakePath); - assert.strictEqual(result, "viewValue"); - assert((client.pathTemplates.folderLocationBucketViewPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('folderLocationBucketView', async () => { + const fakePath = '/rendered/path/folderLocationBucketView'; + const expectedParameters = { + folder: 'folderValue', + location: 'locationValue', + bucket: 'bucketValue', + view: 'viewValue', + }; + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.folderLocationBucketViewPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderLocationBucketViewPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderLocationBucketViewPath', () => { + const result = client.folderLocationBucketViewPath( + 'folderValue', + 'locationValue', + 'bucketValue', + 'viewValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.folderLocationBucketViewPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderLocationBucketViewName', () => { + const result = + client.matchFolderFromFolderLocationBucketViewName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + ( + client.pathTemplates.folderLocationBucketViewPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromFolderLocationBucketViewName', () => { + const result = + client.matchLocationFromFolderLocationBucketViewName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + ( + client.pathTemplates.folderLocationBucketViewPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBucketFromFolderLocationBucketViewName', () => { + const result = + client.matchBucketFromFolderLocationBucketViewName(fakePath); + assert.strictEqual(result, 'bucketValue'); + assert( + ( + client.pathTemplates.folderLocationBucketViewPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchViewFromFolderLocationBucketViewName', () => { + const result = + client.matchViewFromFolderLocationBucketViewName(fakePath); + assert.strictEqual(result, 'viewValue'); + assert( + ( + client.pathTemplates.folderLocationBucketViewPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('folderLog', async () => { - const fakePath = "/rendered/path/folderLog"; - const expectedParameters = { - folder: "folderValue", - log: "logValue", - }; - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.folderLogPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderLogPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderLogPath', () => { - const result = client.folderLogPath("folderValue", "logValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderLogPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderLogName', () => { - const result = client.matchFolderFromFolderLogName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderLogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLogFromFolderLogName', () => { - const result = client.matchLogFromFolderLogName(fakePath); - assert.strictEqual(result, "logValue"); - assert((client.pathTemplates.folderLogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('folderLog', async () => { + const fakePath = '/rendered/path/folderLog'; + const expectedParameters = { + folder: 'folderValue', + log: 'logValue', + }; + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.folderLogPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderLogPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderLogPath', () => { + const result = client.folderLogPath('folderValue', 'logValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.folderLogPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderLogName', () => { + const result = client.matchFolderFromFolderLogName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + (client.pathTemplates.folderLogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLogFromFolderLogName', () => { + const result = client.matchLogFromFolderLogName(fakePath); + assert.strictEqual(result, 'logValue'); + assert( + (client.pathTemplates.folderLogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('folderSettings', async () => { - const fakePath = "/rendered/path/folderSettings"; - const expectedParameters = { - folder: "folderValue", - }; - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.folderSettingsPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderSettingsPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderSettingsPath', () => { - const result = client.folderSettingsPath("folderValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderSettingsPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderSettingsName', () => { - const result = client.matchFolderFromFolderSettingsName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderSettingsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('folderSettings', async () => { + const fakePath = '/rendered/path/folderSettings'; + const expectedParameters = { + folder: 'folderValue', + }; + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.folderSettingsPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderSettingsPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderSettingsPath', () => { + const result = client.folderSettingsPath('folderValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.folderSettingsPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderSettingsName', () => { + const result = client.matchFolderFromFolderSettingsName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + (client.pathTemplates.folderSettingsPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('folderSink', async () => { - const fakePath = "/rendered/path/folderSink"; - const expectedParameters = { - folder: "folderValue", - sink: "sinkValue", - }; - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.folderSinkPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderSinkPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderSinkPath', () => { - const result = client.folderSinkPath("folderValue", "sinkValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderSinkPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderSinkName', () => { - const result = client.matchFolderFromFolderSinkName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderSinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchSinkFromFolderSinkName', () => { - const result = client.matchSinkFromFolderSinkName(fakePath); - assert.strictEqual(result, "sinkValue"); - assert((client.pathTemplates.folderSinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('folderSink', async () => { + const fakePath = '/rendered/path/folderSink'; + const expectedParameters = { + folder: 'folderValue', + sink: 'sinkValue', + }; + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.folderSinkPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderSinkPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderSinkPath', () => { + const result = client.folderSinkPath('folderValue', 'sinkValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.folderSinkPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderSinkName', () => { + const result = client.matchFolderFromFolderSinkName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + (client.pathTemplates.folderSinkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchSinkFromFolderSinkName', () => { + const result = client.matchSinkFromFolderSinkName(fakePath); + assert.strictEqual(result, 'sinkValue'); + assert( + (client.pathTemplates.folderSinkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('location', async () => { - const fakePath = "/rendered/path/location"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - }; - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.locationPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.locationPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('locationPath', () => { - const result = client.locationPath("projectValue", "locationValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.locationPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromLocationName', () => { - const result = client.matchProjectFromLocationName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.locationPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromLocationName', () => { - const result = client.matchLocationFromLocationName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.locationPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('location', async () => { + const fakePath = '/rendered/path/location'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + }; + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.locationPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.locationPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('locationPath', () => { + const result = client.locationPath('projectValue', 'locationValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.locationPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromLocationName', () => { + const result = client.matchProjectFromLocationName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.locationPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromLocationName', () => { + const result = client.matchLocationFromLocationName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.locationPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('logMetric', async () => { - const fakePath = "/rendered/path/logMetric"; - const expectedParameters = { - project: "projectValue", - metric: "metricValue", - }; - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.logMetricPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.logMetricPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('logMetricPath', () => { - const result = client.logMetricPath("projectValue", "metricValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.logMetricPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromLogMetricName', () => { - const result = client.matchProjectFromLogMetricName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.logMetricPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchMetricFromLogMetricName', () => { - const result = client.matchMetricFromLogMetricName(fakePath); - assert.strictEqual(result, "metricValue"); - assert((client.pathTemplates.logMetricPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('logMetric', async () => { + const fakePath = '/rendered/path/logMetric'; + const expectedParameters = { + project: 'projectValue', + metric: 'metricValue', + }; + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.logMetricPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.logMetricPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('logMetricPath', () => { + const result = client.logMetricPath('projectValue', 'metricValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.logMetricPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromLogMetricName', () => { + const result = client.matchProjectFromLogMetricName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.logMetricPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchMetricFromLogMetricName', () => { + const result = client.matchMetricFromLogMetricName(fakePath); + assert.strictEqual(result, 'metricValue'); + assert( + (client.pathTemplates.logMetricPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('organizationCmekSettings', async () => { - const fakePath = "/rendered/path/organizationCmekSettings"; - const expectedParameters = { - organization: "organizationValue", - }; - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.organizationCmekSettingsPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationCmekSettingsPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationCmekSettingsPath', () => { - const result = client.organizationCmekSettingsPath("organizationValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationCmekSettingsPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationCmekSettingsName', () => { - const result = client.matchOrganizationFromOrganizationCmekSettingsName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationCmekSettingsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('organizationCmekSettings', async () => { + const fakePath = '/rendered/path/organizationCmekSettings'; + const expectedParameters = { + organization: 'organizationValue', + }; + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.organizationCmekSettingsPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.organizationCmekSettingsPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('organizationCmekSettingsPath', () => { + const result = client.organizationCmekSettingsPath('organizationValue'); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationCmekSettingsPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationCmekSettingsName', () => { + const result = + client.matchOrganizationFromOrganizationCmekSettingsName(fakePath); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationCmekSettingsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('organizationExclusion', async () => { - const fakePath = "/rendered/path/organizationExclusion"; - const expectedParameters = { - organization: "organizationValue", - exclusion: "exclusionValue", - }; - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.organizationExclusionPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationExclusionPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationExclusionPath', () => { - const result = client.organizationExclusionPath("organizationValue", "exclusionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationExclusionPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationExclusionName', () => { - const result = client.matchOrganizationFromOrganizationExclusionName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationExclusionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchExclusionFromOrganizationExclusionName', () => { - const result = client.matchExclusionFromOrganizationExclusionName(fakePath); - assert.strictEqual(result, "exclusionValue"); - assert((client.pathTemplates.organizationExclusionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('organizationExclusion', async () => { + const fakePath = '/rendered/path/organizationExclusion'; + const expectedParameters = { + organization: 'organizationValue', + exclusion: 'exclusionValue', + }; + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.organizationExclusionPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.organizationExclusionPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('organizationExclusionPath', () => { + const result = client.organizationExclusionPath( + 'organizationValue', + 'exclusionValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationExclusionPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationExclusionName', () => { + const result = + client.matchOrganizationFromOrganizationExclusionName(fakePath); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationExclusionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchExclusionFromOrganizationExclusionName', () => { + const result = + client.matchExclusionFromOrganizationExclusionName(fakePath); + assert.strictEqual(result, 'exclusionValue'); + assert( + ( + client.pathTemplates.organizationExclusionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('organizationLocationBucket', async () => { - const fakePath = "/rendered/path/organizationLocationBucket"; - const expectedParameters = { - organization: "organizationValue", - location: "locationValue", - bucket: "bucketValue", - }; - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.organizationLocationBucketPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationLocationBucketPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationLocationBucketPath', () => { - const result = client.organizationLocationBucketPath("organizationValue", "locationValue", "bucketValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationLocationBucketPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationLocationBucketName', () => { - const result = client.matchOrganizationFromOrganizationLocationBucketName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationLocationBucketPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromOrganizationLocationBucketName', () => { - const result = client.matchLocationFromOrganizationLocationBucketName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.organizationLocationBucketPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBucketFromOrganizationLocationBucketName', () => { - const result = client.matchBucketFromOrganizationLocationBucketName(fakePath); - assert.strictEqual(result, "bucketValue"); - assert((client.pathTemplates.organizationLocationBucketPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('organizationLocationBucket', async () => { + const fakePath = '/rendered/path/organizationLocationBucket'; + const expectedParameters = { + organization: 'organizationValue', + location: 'locationValue', + bucket: 'bucketValue', + }; + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.organizationLocationBucketPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.organizationLocationBucketPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('organizationLocationBucketPath', () => { + const result = client.organizationLocationBucketPath( + 'organizationValue', + 'locationValue', + 'bucketValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationLocationBucketPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationLocationBucketName', () => { + const result = + client.matchOrganizationFromOrganizationLocationBucketName(fakePath); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationLocationBucketPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromOrganizationLocationBucketName', () => { + const result = + client.matchLocationFromOrganizationLocationBucketName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + ( + client.pathTemplates.organizationLocationBucketPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBucketFromOrganizationLocationBucketName', () => { + const result = + client.matchBucketFromOrganizationLocationBucketName(fakePath); + assert.strictEqual(result, 'bucketValue'); + assert( + ( + client.pathTemplates.organizationLocationBucketPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('organizationLocationBucketView', async () => { - const fakePath = "/rendered/path/organizationLocationBucketView"; - const expectedParameters = { - organization: "organizationValue", - location: "locationValue", - bucket: "bucketValue", - view: "viewValue", - }; - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.organizationLocationBucketViewPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationLocationBucketViewPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationLocationBucketViewPath', () => { - const result = client.organizationLocationBucketViewPath("organizationValue", "locationValue", "bucketValue", "viewValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationLocationBucketViewPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationLocationBucketViewName', () => { - const result = client.matchOrganizationFromOrganizationLocationBucketViewName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationLocationBucketViewPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromOrganizationLocationBucketViewName', () => { - const result = client.matchLocationFromOrganizationLocationBucketViewName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.organizationLocationBucketViewPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBucketFromOrganizationLocationBucketViewName', () => { - const result = client.matchBucketFromOrganizationLocationBucketViewName(fakePath); - assert.strictEqual(result, "bucketValue"); - assert((client.pathTemplates.organizationLocationBucketViewPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchViewFromOrganizationLocationBucketViewName', () => { - const result = client.matchViewFromOrganizationLocationBucketViewName(fakePath); - assert.strictEqual(result, "viewValue"); - assert((client.pathTemplates.organizationLocationBucketViewPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('organizationLocationBucketView', async () => { + const fakePath = '/rendered/path/organizationLocationBucketView'; + const expectedParameters = { + organization: 'organizationValue', + location: 'locationValue', + bucket: 'bucketValue', + view: 'viewValue', + }; + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.organizationLocationBucketViewPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.organizationLocationBucketViewPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('organizationLocationBucketViewPath', () => { + const result = client.organizationLocationBucketViewPath( + 'organizationValue', + 'locationValue', + 'bucketValue', + 'viewValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationLocationBucketViewPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationLocationBucketViewName', () => { + const result = + client.matchOrganizationFromOrganizationLocationBucketViewName( + fakePath, + ); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationLocationBucketViewPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromOrganizationLocationBucketViewName', () => { + const result = + client.matchLocationFromOrganizationLocationBucketViewName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + ( + client.pathTemplates.organizationLocationBucketViewPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBucketFromOrganizationLocationBucketViewName', () => { + const result = + client.matchBucketFromOrganizationLocationBucketViewName(fakePath); + assert.strictEqual(result, 'bucketValue'); + assert( + ( + client.pathTemplates.organizationLocationBucketViewPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchViewFromOrganizationLocationBucketViewName', () => { + const result = + client.matchViewFromOrganizationLocationBucketViewName(fakePath); + assert.strictEqual(result, 'viewValue'); + assert( + ( + client.pathTemplates.organizationLocationBucketViewPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('organizationLog', async () => { - const fakePath = "/rendered/path/organizationLog"; - const expectedParameters = { - organization: "organizationValue", - log: "logValue", - }; - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.organizationLogPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationLogPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationLogPath', () => { - const result = client.organizationLogPath("organizationValue", "logValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationLogPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationLogName', () => { - const result = client.matchOrganizationFromOrganizationLogName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationLogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLogFromOrganizationLogName', () => { - const result = client.matchLogFromOrganizationLogName(fakePath); - assert.strictEqual(result, "logValue"); - assert((client.pathTemplates.organizationLogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('organizationLog', async () => { + const fakePath = '/rendered/path/organizationLog'; + const expectedParameters = { + organization: 'organizationValue', + log: 'logValue', + }; + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.organizationLogPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.organizationLogPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('organizationLogPath', () => { + const result = client.organizationLogPath( + 'organizationValue', + 'logValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.organizationLogPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationLogName', () => { + const result = + client.matchOrganizationFromOrganizationLogName(fakePath); + assert.strictEqual(result, 'organizationValue'); + assert( + (client.pathTemplates.organizationLogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLogFromOrganizationLogName', () => { + const result = client.matchLogFromOrganizationLogName(fakePath); + assert.strictEqual(result, 'logValue'); + assert( + (client.pathTemplates.organizationLogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('organizationSettings', async () => { - const fakePath = "/rendered/path/organizationSettings"; - const expectedParameters = { - organization: "organizationValue", - }; - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.organizationSettingsPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationSettingsPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationSettingsPath', () => { - const result = client.organizationSettingsPath("organizationValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationSettingsPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationSettingsName', () => { - const result = client.matchOrganizationFromOrganizationSettingsName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationSettingsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('organizationSettings', async () => { + const fakePath = '/rendered/path/organizationSettings'; + const expectedParameters = { + organization: 'organizationValue', + }; + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.organizationSettingsPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.organizationSettingsPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('organizationSettingsPath', () => { + const result = client.organizationSettingsPath('organizationValue'); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationSettingsPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationSettingsName', () => { + const result = + client.matchOrganizationFromOrganizationSettingsName(fakePath); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationSettingsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('organizationSink', async () => { - const fakePath = "/rendered/path/organizationSink"; - const expectedParameters = { - organization: "organizationValue", - sink: "sinkValue", - }; - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.organizationSinkPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationSinkPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationSinkPath', () => { - const result = client.organizationSinkPath("organizationValue", "sinkValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationSinkPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationSinkName', () => { - const result = client.matchOrganizationFromOrganizationSinkName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationSinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchSinkFromOrganizationSinkName', () => { - const result = client.matchSinkFromOrganizationSinkName(fakePath); - assert.strictEqual(result, "sinkValue"); - assert((client.pathTemplates.organizationSinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('organizationSink', async () => { + const fakePath = '/rendered/path/organizationSink'; + const expectedParameters = { + organization: 'organizationValue', + sink: 'sinkValue', + }; + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.organizationSinkPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.organizationSinkPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('organizationSinkPath', () => { + const result = client.organizationSinkPath( + 'organizationValue', + 'sinkValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationSinkPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationSinkName', () => { + const result = + client.matchOrganizationFromOrganizationSinkName(fakePath); + assert.strictEqual(result, 'organizationValue'); + assert( + (client.pathTemplates.organizationSinkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchSinkFromOrganizationSinkName', () => { + const result = client.matchSinkFromOrganizationSinkName(fakePath); + assert.strictEqual(result, 'sinkValue'); + assert( + (client.pathTemplates.organizationSinkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('project', async () => { - const fakePath = "/rendered/path/project"; - const expectedParameters = { - project: "projectValue", - }; - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.projectPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectPath', () => { - const result = client.projectPath("projectValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectName', () => { - const result = client.matchProjectFromProjectName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('project', async () => { + const fakePath = '/rendered/path/project'; + const expectedParameters = { + project: 'projectValue', + }; + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.projectPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectPath', () => { + const result = client.projectPath('projectValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.projectPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectName', () => { + const result = client.matchProjectFromProjectName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.projectPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectCmekSettings', async () => { - const fakePath = "/rendered/path/projectCmekSettings"; - const expectedParameters = { - project: "projectValue", - }; - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.projectCmekSettingsPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectCmekSettingsPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectCmekSettingsPath', () => { - const result = client.projectCmekSettingsPath("projectValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectCmekSettingsPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectCmekSettingsName', () => { - const result = client.matchProjectFromProjectCmekSettingsName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectCmekSettingsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectCmekSettings', async () => { + const fakePath = '/rendered/path/projectCmekSettings'; + const expectedParameters = { + project: 'projectValue', + }; + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.projectCmekSettingsPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectCmekSettingsPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectCmekSettingsPath', () => { + const result = client.projectCmekSettingsPath('projectValue'); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.projectCmekSettingsPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectCmekSettingsName', () => { + const result = client.matchProjectFromProjectCmekSettingsName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.projectCmekSettingsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectExclusion', async () => { - const fakePath = "/rendered/path/projectExclusion"; - const expectedParameters = { - project: "projectValue", - exclusion: "exclusionValue", - }; - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.projectExclusionPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectExclusionPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectExclusionPath', () => { - const result = client.projectExclusionPath("projectValue", "exclusionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectExclusionPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectExclusionName', () => { - const result = client.matchProjectFromProjectExclusionName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectExclusionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchExclusionFromProjectExclusionName', () => { - const result = client.matchExclusionFromProjectExclusionName(fakePath); - assert.strictEqual(result, "exclusionValue"); - assert((client.pathTemplates.projectExclusionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectExclusion', async () => { + const fakePath = '/rendered/path/projectExclusion'; + const expectedParameters = { + project: 'projectValue', + exclusion: 'exclusionValue', + }; + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.projectExclusionPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectExclusionPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectExclusionPath', () => { + const result = client.projectExclusionPath( + 'projectValue', + 'exclusionValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.projectExclusionPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectExclusionName', () => { + const result = client.matchProjectFromProjectExclusionName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.projectExclusionPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchExclusionFromProjectExclusionName', () => { + const result = client.matchExclusionFromProjectExclusionName(fakePath); + assert.strictEqual(result, 'exclusionValue'); + assert( + (client.pathTemplates.projectExclusionPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectLocationBucket', async () => { - const fakePath = "/rendered/path/projectLocationBucket"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - bucket: "bucketValue", - }; - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.projectLocationBucketPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectLocationBucketPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectLocationBucketPath', () => { - const result = client.projectLocationBucketPath("projectValue", "locationValue", "bucketValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectLocationBucketPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectLocationBucketName', () => { - const result = client.matchProjectFromProjectLocationBucketName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectLocationBucketPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromProjectLocationBucketName', () => { - const result = client.matchLocationFromProjectLocationBucketName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.projectLocationBucketPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBucketFromProjectLocationBucketName', () => { - const result = client.matchBucketFromProjectLocationBucketName(fakePath); - assert.strictEqual(result, "bucketValue"); - assert((client.pathTemplates.projectLocationBucketPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectLocationBucket', async () => { + const fakePath = '/rendered/path/projectLocationBucket'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + bucket: 'bucketValue', + }; + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.projectLocationBucketPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectLocationBucketPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectLocationBucketPath', () => { + const result = client.projectLocationBucketPath( + 'projectValue', + 'locationValue', + 'bucketValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.projectLocationBucketPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectLocationBucketName', () => { + const result = + client.matchProjectFromProjectLocationBucketName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.projectLocationBucketPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromProjectLocationBucketName', () => { + const result = + client.matchLocationFromProjectLocationBucketName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + ( + client.pathTemplates.projectLocationBucketPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBucketFromProjectLocationBucketName', () => { + const result = + client.matchBucketFromProjectLocationBucketName(fakePath); + assert.strictEqual(result, 'bucketValue'); + assert( + ( + client.pathTemplates.projectLocationBucketPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectLocationBucketView', async () => { - const fakePath = "/rendered/path/projectLocationBucketView"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - bucket: "bucketValue", - view: "viewValue", - }; - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.projectLocationBucketViewPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectLocationBucketViewPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectLocationBucketViewPath', () => { - const result = client.projectLocationBucketViewPath("projectValue", "locationValue", "bucketValue", "viewValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectLocationBucketViewPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectLocationBucketViewName', () => { - const result = client.matchProjectFromProjectLocationBucketViewName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectLocationBucketViewPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromProjectLocationBucketViewName', () => { - const result = client.matchLocationFromProjectLocationBucketViewName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.projectLocationBucketViewPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBucketFromProjectLocationBucketViewName', () => { - const result = client.matchBucketFromProjectLocationBucketViewName(fakePath); - assert.strictEqual(result, "bucketValue"); - assert((client.pathTemplates.projectLocationBucketViewPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchViewFromProjectLocationBucketViewName', () => { - const result = client.matchViewFromProjectLocationBucketViewName(fakePath); - assert.strictEqual(result, "viewValue"); - assert((client.pathTemplates.projectLocationBucketViewPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectLocationBucketView', async () => { + const fakePath = '/rendered/path/projectLocationBucketView'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + bucket: 'bucketValue', + view: 'viewValue', + }; + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.projectLocationBucketViewPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectLocationBucketViewPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectLocationBucketViewPath', () => { + const result = client.projectLocationBucketViewPath( + 'projectValue', + 'locationValue', + 'bucketValue', + 'viewValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.projectLocationBucketViewPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectLocationBucketViewName', () => { + const result = + client.matchProjectFromProjectLocationBucketViewName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.projectLocationBucketViewPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromProjectLocationBucketViewName', () => { + const result = + client.matchLocationFromProjectLocationBucketViewName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + ( + client.pathTemplates.projectLocationBucketViewPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBucketFromProjectLocationBucketViewName', () => { + const result = + client.matchBucketFromProjectLocationBucketViewName(fakePath); + assert.strictEqual(result, 'bucketValue'); + assert( + ( + client.pathTemplates.projectLocationBucketViewPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchViewFromProjectLocationBucketViewName', () => { + const result = + client.matchViewFromProjectLocationBucketViewName(fakePath); + assert.strictEqual(result, 'viewValue'); + assert( + ( + client.pathTemplates.projectLocationBucketViewPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectLog', async () => { - const fakePath = "/rendered/path/projectLog"; - const expectedParameters = { - project: "projectValue", - log: "logValue", - }; - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.projectLogPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectLogPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectLogPath', () => { - const result = client.projectLogPath("projectValue", "logValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectLogPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectLogName', () => { - const result = client.matchProjectFromProjectLogName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectLogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLogFromProjectLogName', () => { - const result = client.matchLogFromProjectLogName(fakePath); - assert.strictEqual(result, "logValue"); - assert((client.pathTemplates.projectLogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectLog', async () => { + const fakePath = '/rendered/path/projectLog'; + const expectedParameters = { + project: 'projectValue', + log: 'logValue', + }; + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.projectLogPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectLogPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectLogPath', () => { + const result = client.projectLogPath('projectValue', 'logValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.projectLogPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectLogName', () => { + const result = client.matchProjectFromProjectLogName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.projectLogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLogFromProjectLogName', () => { + const result = client.matchLogFromProjectLogName(fakePath); + assert.strictEqual(result, 'logValue'); + assert( + (client.pathTemplates.projectLogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectSettings', async () => { - const fakePath = "/rendered/path/projectSettings"; - const expectedParameters = { - project: "projectValue", - }; - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.projectSettingsPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectSettingsPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectSettingsPath', () => { - const result = client.projectSettingsPath("projectValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectSettingsPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectSettingsName', () => { - const result = client.matchProjectFromProjectSettingsName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectSettingsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectSettings', async () => { + const fakePath = '/rendered/path/projectSettings'; + const expectedParameters = { + project: 'projectValue', + }; + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.projectSettingsPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectSettingsPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectSettingsPath', () => { + const result = client.projectSettingsPath('projectValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.projectSettingsPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectSettingsName', () => { + const result = client.matchProjectFromProjectSettingsName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.projectSettingsPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectSink', async () => { - const fakePath = "/rendered/path/projectSink"; - const expectedParameters = { - project: "projectValue", - sink: "sinkValue", - }; - const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.projectSinkPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectSinkPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectSinkPath', () => { - const result = client.projectSinkPath("projectValue", "sinkValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectSinkPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectSinkName', () => { - const result = client.matchProjectFromProjectSinkName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectSinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchSinkFromProjectSinkName', () => { - const result = client.matchSinkFromProjectSinkName(fakePath); - assert.strictEqual(result, "sinkValue"); - assert((client.pathTemplates.projectSinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectSink', async () => { + const fakePath = '/rendered/path/projectSink'; + const expectedParameters = { + project: 'projectValue', + sink: 'sinkValue', + }; + const client = new configservicev2Module.v2.ConfigServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.projectSinkPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectSinkPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectSinkPath', () => { + const result = client.projectSinkPath('projectValue', 'sinkValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.projectSinkPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectSinkName', () => { + const result = client.matchProjectFromProjectSinkName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.projectSinkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchSinkFromProjectSinkName', () => { + const result = client.matchSinkFromProjectSinkName(fakePath); + assert.strictEqual(result, 'sinkValue'); + assert( + (client.pathTemplates.projectSinkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/core/generator/gapic-generator-typescript/baselines/logging/test/gapic_logging_service_v2_v2.ts.baseline b/core/generator/gapic-generator-typescript/baselines/logging/test/gapic_logging_service_v2_v2.ts.baseline index 12256c5f1e8b..a80db0a4cb50 100644 --- a/core/generator/gapic-generator-typescript/baselines/logging/test/gapic_logging_service_v2_v2.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/logging/test/gapic_logging_service_v2_v2.ts.baseline @@ -19,2245 +19,3135 @@ import * as protos from '../protos/protos'; import * as assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as loggingservicev2Module from '../src'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; -import {protobuf} from 'google-gax'; +import { protobuf } from 'google-gax'; // Dynamically loaded proto JSON is needed to get the type information // to fill in default values for request objects -const root = protobuf.Root.fromJSON(require('../protos/protos.json')).resolveAll(); +const root = protobuf.Root.fromJSON( + require('../protos/protos.json'), +).resolveAll(); // eslint-disable-next-line @typescript-eslint/no-unused-vars function getTypeDefaultValue(typeName: string, fields: string[]) { - let type = root.lookupType(typeName) as protobuf.Type; - for (const field of fields.slice(0, -1)) { - type = type.fields[field]?.resolvedType as protobuf.Type; - } - return type.fields[fields[fields.length - 1]]?.defaultValue; + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type.fields[field]?.resolvedType as protobuf.Type; + } + return type.fields[fields[fields.length - 1]]?.defaultValue; } function generateSampleMessage(instance: T) { - const filledObject = (instance.constructor as typeof protobuf.Message) - .toObject(instance as protobuf.Message, {defaults: true}); - return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, { defaults: true }); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; } function stubSimpleCall(response?: ResponseType, error?: Error) { - return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); } -function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { - return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +function stubSimpleCallWithCallback( + response?: ResponseType, + error?: Error, +) { + return error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); } -function stubBidiStreamingCall(response?: ResponseType, error?: Error) { - const transformStub = error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); - const mockStream = new PassThrough({ - objectMode: true, - transform: transformStub, - }); - return sinon.stub().returns(mockStream); +function stubBidiStreamingCall( + response?: ResponseType, + error?: Error, +) { + const transformStub = error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + return sinon.stub().returns(mockStream); } -function stubPageStreamingCall(responses?: ResponseType[], error?: Error) { - const pagingStub = sinon.stub(); - if (responses) { - for (let i = 0; i < responses.length; ++i) { - pagingStub.onCall(i).callsArgWith(2, null, responses[i]); - } +function stubPageStreamingCall( + responses?: ResponseType[], + error?: Error, +) { + const pagingStub = sinon.stub(); + if (responses) { + for (let i = 0; i < responses.length; ++i) { + pagingStub.onCall(i).callsArgWith(2, null, responses[i]); } - const transformStub = error ? sinon.stub().callsArgWith(2, error) : pagingStub; - const mockStream = new PassThrough({ - objectMode: true, - transform: transformStub, - }); - // trigger as many responses as needed - if (responses) { - for (let i = 0; i < responses.length; ++i) { - setImmediate(() => { mockStream.write({}); }); - } - setImmediate(() => { mockStream.end(); }); - } else { - setImmediate(() => { mockStream.write({}); }); - setImmediate(() => { mockStream.end(); }); + } + const transformStub = error + ? sinon.stub().callsArgWith(2, error) + : pagingStub; + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + // trigger as many responses as needed + if (responses) { + for (let i = 0; i < responses.length; ++i) { + setImmediate(() => { + mockStream.write({}); + }); } - return sinon.stub().returns(mockStream); + setImmediate(() => { + mockStream.end(); + }); + } else { + setImmediate(() => { + mockStream.write({}); + }); + setImmediate(() => { + mockStream.end(); + }); + } + return sinon.stub().returns(mockStream); } -function stubAsyncIterationCall(responses?: ResponseType[], error?: Error) { - let counter = 0; - const asyncIterable = { - [Symbol.asyncIterator]() { - return { - async next() { - if (error) { - return Promise.reject(error); - } - if (counter >= responses!.length) { - return Promise.resolve({done: true, value: undefined}); - } - return Promise.resolve({done: false, value: responses![counter++]}); - } - }; - } - }; - return sinon.stub().returns(asyncIterable); +function stubAsyncIterationCall( + responses?: ResponseType[], + error?: Error, +) { + let counter = 0; + const asyncIterable = { + [Symbol.asyncIterator]() { + return { + async next() { + if (error) { + return Promise.reject(error); + } + if (counter >= responses!.length) { + return Promise.resolve({ done: true, value: undefined }); + } + return Promise.resolve({ done: false, value: responses![counter++] }); + }, + }; + }, + }; + return sinon.stub().returns(asyncIterable); } describe('v2.LoggingServiceV2Client', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new loggingservicev2Module.v2.LoggingServiceV2Client(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'logging.googleapis.com'); - }); - - it('has universeDomain', () => { - const client = new loggingservicev2Module.v2.LoggingServiceV2Client(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); - - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - it('throws DeprecationWarning if static servicePath is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const servicePath = loggingservicev2Module.v2.LoggingServiceV2Client.servicePath; - assert.strictEqual(servicePath, 'logging.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = loggingservicev2Module.v2.LoggingServiceV2Client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'logging.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'logging.example.com'); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new loggingservicev2Module.v2.LoggingServiceV2Client(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'logging.googleapis.com'); + }); - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'logging.example.com'); - }); + it('has universeDomain', () => { + const client = new loggingservicev2Module.v2.LoggingServiceV2Client(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - if (typeof process === 'object' && 'env' in process) { - describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { - it('sets apiEndpoint from environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new loggingservicev2Module.v2.LoggingServiceV2Client(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'logging.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - - it('value configured in code has priority over environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'logging.configured.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { new loggingservicev2Module.v2.LoggingServiceV2Client({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = + loggingservicev2Module.v2.LoggingServiceV2Client.servicePath; + assert.strictEqual(servicePath, 'logging.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + loggingservicev2Module.v2.LoggingServiceV2Client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'logging.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + universeDomain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'logging.example.com'); + }); - it('has port', () => { - const port = loggingservicev2Module.v2.LoggingServiceV2Client.port; - assert(port); - assert(typeof port === 'number'); - }); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + universe_domain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'logging.example.com'); + }); - it('should create a client with no option', () => { - const client = new loggingservicev2Module.v2.LoggingServiceV2Client(); - assert(client); + if (typeof process === 'object' && 'env' in process) { + describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { + it('sets apiEndpoint from environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new loggingservicev2Module.v2.LoggingServiceV2Client(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'logging.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } + }); + + it('value configured in code has priority over environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + universeDomain: 'configured.example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'logging.configured.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } + }); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new loggingservicev2Module.v2.LoggingServiceV2Client({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); + }); - it('should create a client with gRPC fallback', () => { - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - fallback: true, - }); - assert(client); - }); + it('has port', () => { + const port = loggingservicev2Module.v2.LoggingServiceV2Client.port; + assert(port); + assert(typeof port === 'number'); + }); - it('has initialize method and supports deferred initialization', async () => { - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.loggingServiceV2Stub, undefined); - await client.initialize(); - assert(client.loggingServiceV2Stub); - }); + it('should create a client with no option', () => { + const client = new loggingservicev2Module.v2.LoggingServiceV2Client(); + assert(client); + }); - it('has close method for the initialized client', done => { - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.loggingServiceV2Stub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('should create a client with gRPC fallback', () => { + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + fallback: true, + }); + assert(client); + }); - it('has close method for the non-initialized client', done => { - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.loggingServiceV2Stub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('has initialize method and supports deferred initialization', async () => { + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.loggingServiceV2Stub, undefined); + await client.initialize(); + assert(client.loggingServiceV2Stub); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + it('has close method for the initialized client', (done) => { + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.loggingServiceV2Stub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId((err?: Error|null, projectId?: string|null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } - }); - }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); + it('has close method for the non-initialized client', (done) => { + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.loggingServiceV2Stub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); }); - describe('deleteLog', () => { - it('invokes deleteLog without error', async () => { - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.DeleteLogRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.DeleteLogRequest', ['logName']); - request.logName = defaultValue1; - const expectedHeaderRequestParams = `log_name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteLog = stubSimpleCall(expectedResponse); - const [response] = await client.deleteLog(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteLog as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteLog as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + }); - it('invokes deleteLog without error using callback', async () => { - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.DeleteLogRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.DeleteLogRequest', ['logName']); - request.logName = defaultValue1; - const expectedHeaderRequestParams = `log_name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteLog = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteLog( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteLog as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteLog as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } + }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + }); + + describe('deleteLog', () => { + it('invokes deleteLog without error', async () => { + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.DeleteLogRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.DeleteLogRequest', + ['logName'], + ); + request.logName = defaultValue1; + const expectedHeaderRequestParams = `log_name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteLog = stubSimpleCall(expectedResponse); + const [response] = await client.deleteLog(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteLog as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteLog as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteLog with error', async () => { - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.DeleteLogRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.DeleteLogRequest', ['logName']); - request.logName = defaultValue1; - const expectedHeaderRequestParams = `log_name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteLog = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteLog(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteLog as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteLog as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteLog without error using callback', async () => { + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.DeleteLogRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.DeleteLogRequest', + ['logName'], + ); + request.logName = defaultValue1; + const expectedHeaderRequestParams = `log_name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteLog = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteLog( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteLog as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteLog as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteLog with closed client', async () => { - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.DeleteLogRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.DeleteLogRequest', ['logName']); - request.logName = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteLog(request), expectedError); - }); + it('invokes deleteLog with error', async () => { + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.DeleteLogRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.DeleteLogRequest', + ['logName'], + ); + request.logName = defaultValue1; + const expectedHeaderRequestParams = `log_name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteLog = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.deleteLog(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteLog as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteLog as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('writeLogEntries', () => { - it('invokes writeLogEntries without error', async () => { - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.WriteLogEntriesRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.logging.v2.WriteLogEntriesResponse() - ); - client.innerApiCalls.writeLogEntries = stubSimpleCall(expectedResponse); - const [response] = await client.writeLogEntries(request); - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes deleteLog with closed client', async () => { + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.DeleteLogRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.DeleteLogRequest', + ['logName'], + ); + request.logName = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.deleteLog(request), expectedError); + }); + }); + + describe('writeLogEntries', () => { + it('invokes writeLogEntries without error', async () => { + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.WriteLogEntriesRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.logging.v2.WriteLogEntriesResponse(), + ); + client.innerApiCalls.writeLogEntries = stubSimpleCall(expectedResponse); + const [response] = await client.writeLogEntries(request); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes writeLogEntries without error using callback', async () => { - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.WriteLogEntriesRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.logging.v2.WriteLogEntriesResponse() - ); - client.innerApiCalls.writeLogEntries = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.writeLogEntries( - request, - (err?: Error|null, result?: protos.google.logging.v2.IWriteLogEntriesResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes writeLogEntries without error using callback', async () => { + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.WriteLogEntriesRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.logging.v2.WriteLogEntriesResponse(), + ); + client.innerApiCalls.writeLogEntries = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.writeLogEntries( + request, + ( + err?: Error | null, + result?: protos.google.logging.v2.IWriteLogEntriesResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes writeLogEntries with error', async () => { - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.WriteLogEntriesRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.writeLogEntries = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.writeLogEntries(request), expectedError); - }); + it('invokes writeLogEntries with error', async () => { + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.WriteLogEntriesRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.writeLogEntries = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.writeLogEntries(request), expectedError); + }); - it('invokes writeLogEntries with closed client', async () => { - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.WriteLogEntriesRequest() - ); - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.writeLogEntries(request), expectedError); - }); + it('invokes writeLogEntries with closed client', async () => { + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.WriteLogEntriesRequest(), + ); + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.writeLogEntries(request), expectedError); + }); + }); + + describe('tailLogEntries', () => { + it('invokes tailLogEntries without error', async () => { + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.TailLogEntriesRequest(), + ); + + const expectedResponse = generateSampleMessage( + new protos.google.logging.v2.TailLogEntriesResponse(), + ); + client.innerApiCalls.tailLogEntries = + stubBidiStreamingCall(expectedResponse); + const stream = client.tailLogEntries(); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + (response: protos.google.logging.v2.TailLogEntriesResponse) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); + }); + stream.write(request); + stream.end(); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + assert( + (client.innerApiCalls.tailLogEntries as SinonStub) + .getCall(0) + .calledWith(null), + ); + assert.deepStrictEqual( + ((stream as unknown as PassThrough)._transform as SinonStub).getCall(0) + .args[0], + request, + ); }); - describe('tailLogEntries', () => { - it('invokes tailLogEntries without error', async () => { - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.TailLogEntriesRequest() - ); - - const expectedResponse = generateSampleMessage( - new protos.google.logging.v2.TailLogEntriesResponse() - ); - client.innerApiCalls.tailLogEntries = stubBidiStreamingCall(expectedResponse); - const stream = client.tailLogEntries(); - const promise = new Promise((resolve, reject) => { - stream.on('data', (response: protos.google.logging.v2.TailLogEntriesResponse) => { - resolve(response); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - stream.write(request); - stream.end(); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - assert((client.innerApiCalls.tailLogEntries as SinonStub) - .getCall(0).calledWith(null)); - assert.deepStrictEqual(((stream as unknown as PassThrough) - ._transform as SinonStub).getCall(0).args[0], request); - }); + it('invokes tailLogEntries with error', async () => { + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.TailLogEntriesRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.tailLogEntries = stubBidiStreamingCall( + undefined, + expectedError, + ); + const stream = client.tailLogEntries(); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + (response: protos.google.logging.v2.TailLogEntriesResponse) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); + }); + stream.write(request); + stream.end(); + }); + await assert.rejects(promise, expectedError); + assert( + (client.innerApiCalls.tailLogEntries as SinonStub) + .getCall(0) + .calledWith(null), + ); + assert.deepStrictEqual( + ((stream as unknown as PassThrough)._transform as SinonStub).getCall(0) + .args[0], + request, + ); + }); + }); + + describe('listLogEntries', () => { + it('invokes listLogEntries without error', async () => { + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.ListLogEntriesRequest(), + ); + const expectedResponse = [ + generateSampleMessage(new protos.google.logging.v2.LogEntry()), + generateSampleMessage(new protos.google.logging.v2.LogEntry()), + generateSampleMessage(new protos.google.logging.v2.LogEntry()), + ]; + client.innerApiCalls.listLogEntries = stubSimpleCall(expectedResponse); + const [response] = await client.listLogEntries(request); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes tailLogEntries with error', async () => { - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.TailLogEntriesRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.tailLogEntries = stubBidiStreamingCall(undefined, expectedError); - const stream = client.tailLogEntries(); - const promise = new Promise((resolve, reject) => { - stream.on('data', (response: protos.google.logging.v2.TailLogEntriesResponse) => { - resolve(response); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - stream.write(request); - stream.end(); - }); - await assert.rejects(promise, expectedError); - assert((client.innerApiCalls.tailLogEntries as SinonStub) - .getCall(0).calledWith(null)); - assert.deepStrictEqual(((stream as unknown as PassThrough) - ._transform as SinonStub).getCall(0).args[0], request); - }); + it('invokes listLogEntries without error using callback', async () => { + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.ListLogEntriesRequest(), + ); + const expectedResponse = [ + generateSampleMessage(new protos.google.logging.v2.LogEntry()), + generateSampleMessage(new protos.google.logging.v2.LogEntry()), + generateSampleMessage(new protos.google.logging.v2.LogEntry()), + ]; + client.innerApiCalls.listLogEntries = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listLogEntries( + request, + ( + err?: Error | null, + result?: protos.google.logging.v2.ILogEntry[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); }); - describe('listLogEntries', () => { - it('invokes listLogEntries without error', async () => { - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.ListLogEntriesRequest() - );const expectedResponse = [ - generateSampleMessage(new protos.google.logging.v2.LogEntry()), - generateSampleMessage(new protos.google.logging.v2.LogEntry()), - generateSampleMessage(new protos.google.logging.v2.LogEntry()), - ]; - client.innerApiCalls.listLogEntries = stubSimpleCall(expectedResponse); - const [response] = await client.listLogEntries(request); - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes listLogEntries with error', async () => { + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.ListLogEntriesRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.listLogEntries = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listLogEntries(request), expectedError); + }); - it('invokes listLogEntries without error using callback', async () => { - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.ListLogEntriesRequest() - );const expectedResponse = [ - generateSampleMessage(new protos.google.logging.v2.LogEntry()), - generateSampleMessage(new protos.google.logging.v2.LogEntry()), - generateSampleMessage(new protos.google.logging.v2.LogEntry()), - ]; - client.innerApiCalls.listLogEntries = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listLogEntries( - request, - (err?: Error|null, result?: protos.google.logging.v2.ILogEntry[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes listLogEntriesStream without error', async () => { + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.ListLogEntriesRequest(), + ); + const expectedResponse = [ + generateSampleMessage(new protos.google.logging.v2.LogEntry()), + generateSampleMessage(new protos.google.logging.v2.LogEntry()), + generateSampleMessage(new protos.google.logging.v2.LogEntry()), + ]; + client.descriptors.page.listLogEntries.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listLogEntriesStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.logging.v2.LogEntry[] = []; + stream.on('data', (response: protos.google.logging.v2.LogEntry) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listLogEntries.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listLogEntries, request), + ); + }); - it('invokes listLogEntries with error', async () => { - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.ListLogEntriesRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.listLogEntries = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listLogEntries(request), expectedError); - }); + it('invokes listLogEntriesStream with error', async () => { + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.ListLogEntriesRequest(), + ); + const expectedError = new Error('expected'); + client.descriptors.page.listLogEntries.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listLogEntriesStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.logging.v2.LogEntry[] = []; + stream.on('data', (response: protos.google.logging.v2.LogEntry) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listLogEntries.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listLogEntries, request), + ); + }); - it('invokes listLogEntriesStream without error', async () => { - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.ListLogEntriesRequest() - ); - const expectedResponse = [ - generateSampleMessage(new protos.google.logging.v2.LogEntry()), - generateSampleMessage(new protos.google.logging.v2.LogEntry()), - generateSampleMessage(new protos.google.logging.v2.LogEntry()), - ]; - client.descriptors.page.listLogEntries.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listLogEntriesStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.logging.v2.LogEntry[] = []; - stream.on('data', (response: protos.google.logging.v2.LogEntry) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.listLogEntries.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listLogEntries, request)); - }); + it('uses async iteration with listLogEntries without error', async () => { + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.ListLogEntriesRequest(), + ); + const expectedResponse = [ + generateSampleMessage(new protos.google.logging.v2.LogEntry()), + generateSampleMessage(new protos.google.logging.v2.LogEntry()), + generateSampleMessage(new protos.google.logging.v2.LogEntry()), + ]; + client.descriptors.page.listLogEntries.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.logging.v2.ILogEntry[] = []; + const iterable = client.listLogEntriesAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listLogEntries.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + }); - it('invokes listLogEntriesStream with error', async () => { - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.ListLogEntriesRequest() - ); - const expectedError = new Error('expected'); - client.descriptors.page.listLogEntries.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listLogEntriesStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.logging.v2.LogEntry[] = []; - stream.on('data', (response: protos.google.logging.v2.LogEntry) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listLogEntries.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listLogEntries, request)); - }); + it('uses async iteration with listLogEntries with error', async () => { + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.ListLogEntriesRequest(), + ); + const expectedError = new Error('expected'); + client.descriptors.page.listLogEntries.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listLogEntriesAsync(request); + await assert.rejects(async () => { + const responses: protos.google.logging.v2.ILogEntry[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listLogEntries.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + }); + }); + + describe('listMonitoredResourceDescriptors', () => { + it('invokes listMonitoredResourceDescriptors without error', async () => { + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.ListMonitoredResourceDescriptorsRequest(), + ); + const expectedResponse = [ + generateSampleMessage( + new protos.google.api.MonitoredResourceDescriptor(), + ), + generateSampleMessage( + new protos.google.api.MonitoredResourceDescriptor(), + ), + generateSampleMessage( + new protos.google.api.MonitoredResourceDescriptor(), + ), + ]; + client.innerApiCalls.listMonitoredResourceDescriptors = + stubSimpleCall(expectedResponse); + const [response] = await client.listMonitoredResourceDescriptors(request); + assert.deepStrictEqual(response, expectedResponse); + }); - it('uses async iteration with listLogEntries without error', async () => { - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.ListLogEntriesRequest() - ); - const expectedResponse = [ - generateSampleMessage(new protos.google.logging.v2.LogEntry()), - generateSampleMessage(new protos.google.logging.v2.LogEntry()), - generateSampleMessage(new protos.google.logging.v2.LogEntry()), - ]; - client.descriptors.page.listLogEntries.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.logging.v2.ILogEntry[] = []; - const iterable = client.listLogEntriesAsync(request); - for await (const resource of iterable) { - responses.push(resource!); + it('invokes listMonitoredResourceDescriptors without error using callback', async () => { + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.ListMonitoredResourceDescriptorsRequest(), + ); + const expectedResponse = [ + generateSampleMessage( + new protos.google.api.MonitoredResourceDescriptor(), + ), + generateSampleMessage( + new protos.google.api.MonitoredResourceDescriptor(), + ), + generateSampleMessage( + new protos.google.api.MonitoredResourceDescriptor(), + ), + ]; + client.innerApiCalls.listMonitoredResourceDescriptors = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listMonitoredResourceDescriptors( + request, + ( + err?: Error | null, + result?: protos.google.api.IMonitoredResourceDescriptor[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listLogEntries.asyncIterate as SinonStub) - .getCall(0).args[1], request); - }); - - it('uses async iteration with listLogEntries with error', async () => { - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.ListLogEntriesRequest() - ); - const expectedError = new Error('expected'); - client.descriptors.page.listLogEntries.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listLogEntriesAsync(request); - await assert.rejects(async () => { - const responses: protos.google.logging.v2.ILogEntry[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listLogEntries.asyncIterate as SinonStub) - .getCall(0).args[1], request); - }); + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); }); - describe('listMonitoredResourceDescriptors', () => { - it('invokes listMonitoredResourceDescriptors without error', async () => { - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.ListMonitoredResourceDescriptorsRequest() - );const expectedResponse = [ - generateSampleMessage(new protos.google.api.MonitoredResourceDescriptor()), - generateSampleMessage(new protos.google.api.MonitoredResourceDescriptor()), - generateSampleMessage(new protos.google.api.MonitoredResourceDescriptor()), - ]; - client.innerApiCalls.listMonitoredResourceDescriptors = stubSimpleCall(expectedResponse); - const [response] = await client.listMonitoredResourceDescriptors(request); - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes listMonitoredResourceDescriptors with error', async () => { + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.ListMonitoredResourceDescriptorsRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.listMonitoredResourceDescriptors = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.listMonitoredResourceDescriptors(request), + expectedError, + ); + }); - it('invokes listMonitoredResourceDescriptors without error using callback', async () => { - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.ListMonitoredResourceDescriptorsRequest() - );const expectedResponse = [ - generateSampleMessage(new protos.google.api.MonitoredResourceDescriptor()), - generateSampleMessage(new protos.google.api.MonitoredResourceDescriptor()), - generateSampleMessage(new protos.google.api.MonitoredResourceDescriptor()), - ]; - client.innerApiCalls.listMonitoredResourceDescriptors = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listMonitoredResourceDescriptors( - request, - (err?: Error|null, result?: protos.google.api.IMonitoredResourceDescriptor[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes listMonitoredResourceDescriptorsStream without error', async () => { + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.ListMonitoredResourceDescriptorsRequest(), + ); + const expectedResponse = [ + generateSampleMessage( + new protos.google.api.MonitoredResourceDescriptor(), + ), + generateSampleMessage( + new protos.google.api.MonitoredResourceDescriptor(), + ), + generateSampleMessage( + new protos.google.api.MonitoredResourceDescriptor(), + ), + ]; + client.descriptors.page.listMonitoredResourceDescriptors.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listMonitoredResourceDescriptorsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.api.MonitoredResourceDescriptor[] = []; + stream.on( + 'data', + (response: protos.google.api.MonitoredResourceDescriptor) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + ( + client.descriptors.page.listMonitoredResourceDescriptors + .createStream as SinonStub + ) + .getCall(0) + .calledWith( + client.innerApiCalls.listMonitoredResourceDescriptors, + request, + ), + ); + }); - it('invokes listMonitoredResourceDescriptors with error', async () => { - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.ListMonitoredResourceDescriptorsRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.listMonitoredResourceDescriptors = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listMonitoredResourceDescriptors(request), expectedError); - }); + it('invokes listMonitoredResourceDescriptorsStream with error', async () => { + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.ListMonitoredResourceDescriptorsRequest(), + ); + const expectedError = new Error('expected'); + client.descriptors.page.listMonitoredResourceDescriptors.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listMonitoredResourceDescriptorsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.api.MonitoredResourceDescriptor[] = []; + stream.on( + 'data', + (response: protos.google.api.MonitoredResourceDescriptor) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + ( + client.descriptors.page.listMonitoredResourceDescriptors + .createStream as SinonStub + ) + .getCall(0) + .calledWith( + client.innerApiCalls.listMonitoredResourceDescriptors, + request, + ), + ); + }); - it('invokes listMonitoredResourceDescriptorsStream without error', async () => { - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.ListMonitoredResourceDescriptorsRequest() - ); - const expectedResponse = [ - generateSampleMessage(new protos.google.api.MonitoredResourceDescriptor()), - generateSampleMessage(new protos.google.api.MonitoredResourceDescriptor()), - generateSampleMessage(new protos.google.api.MonitoredResourceDescriptor()), - ]; - client.descriptors.page.listMonitoredResourceDescriptors.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listMonitoredResourceDescriptorsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.api.MonitoredResourceDescriptor[] = []; - stream.on('data', (response: protos.google.api.MonitoredResourceDescriptor) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.listMonitoredResourceDescriptors.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listMonitoredResourceDescriptors, request)); - }); + it('uses async iteration with listMonitoredResourceDescriptors without error', async () => { + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.ListMonitoredResourceDescriptorsRequest(), + ); + const expectedResponse = [ + generateSampleMessage( + new protos.google.api.MonitoredResourceDescriptor(), + ), + generateSampleMessage( + new protos.google.api.MonitoredResourceDescriptor(), + ), + generateSampleMessage( + new protos.google.api.MonitoredResourceDescriptor(), + ), + ]; + client.descriptors.page.listMonitoredResourceDescriptors.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.api.IMonitoredResourceDescriptor[] = []; + const iterable = client.listMonitoredResourceDescriptorsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listMonitoredResourceDescriptors + .asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + }); - it('invokes listMonitoredResourceDescriptorsStream with error', async () => { - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.ListMonitoredResourceDescriptorsRequest() - ); - const expectedError = new Error('expected'); - client.descriptors.page.listMonitoredResourceDescriptors.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listMonitoredResourceDescriptorsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.api.MonitoredResourceDescriptor[] = []; - stream.on('data', (response: protos.google.api.MonitoredResourceDescriptor) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listMonitoredResourceDescriptors.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listMonitoredResourceDescriptors, request)); - }); + it('uses async iteration with listMonitoredResourceDescriptors with error', async () => { + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.ListMonitoredResourceDescriptorsRequest(), + ); + const expectedError = new Error('expected'); + client.descriptors.page.listMonitoredResourceDescriptors.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listMonitoredResourceDescriptorsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.api.IMonitoredResourceDescriptor[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listMonitoredResourceDescriptors + .asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + }); + }); + + describe('listLogs', () => { + it('invokes listLogs without error', async () => { + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.ListLogsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.ListLogsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [new String(), new String(), new String()]; + client.innerApiCalls.listLogs = stubSimpleCall(expectedResponse); + const [response] = await client.listLogs(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listLogs as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listLogs as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('uses async iteration with listMonitoredResourceDescriptors without error', async () => { - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.ListMonitoredResourceDescriptorsRequest() - ); - const expectedResponse = [ - generateSampleMessage(new protos.google.api.MonitoredResourceDescriptor()), - generateSampleMessage(new protos.google.api.MonitoredResourceDescriptor()), - generateSampleMessage(new protos.google.api.MonitoredResourceDescriptor()), - ]; - client.descriptors.page.listMonitoredResourceDescriptors.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.api.IMonitoredResourceDescriptor[] = []; - const iterable = client.listMonitoredResourceDescriptorsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); + it('invokes listLogs without error using callback', async () => { + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.ListLogsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.ListLogsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [new String(), new String(), new String()]; + client.innerApiCalls.listLogs = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listLogs( + request, + (err?: Error | null, result?: string[] | null) => { + if (err) { + reject(err); + } else { + resolve(result); } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listMonitoredResourceDescriptors.asyncIterate as SinonStub) - .getCall(0).args[1], request); - }); - - it('uses async iteration with listMonitoredResourceDescriptors with error', async () => { - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.ListMonitoredResourceDescriptorsRequest() - ); - const expectedError = new Error('expected'); - client.descriptors.page.listMonitoredResourceDescriptors.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listMonitoredResourceDescriptorsAsync(request); - await assert.rejects(async () => { - const responses: protos.google.api.IMonitoredResourceDescriptor[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listMonitoredResourceDescriptors.asyncIterate as SinonStub) - .getCall(0).args[1], request); - }); + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listLogs as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listLogs as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('listLogs', () => { - it('invokes listLogs without error', async () => { - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.ListLogsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.ListLogsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [new String(), new String(), new String()]; - client.innerApiCalls.listLogs = stubSimpleCall(expectedResponse); - const [response] = await client.listLogs(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listLogs as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listLogs as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listLogs without error using callback', async () => { - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.ListLogsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.ListLogsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [new String(), new String(), new String()]; - client.innerApiCalls.listLogs = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listLogs( - request, - (err?: Error|null, result?: string[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listLogs as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listLogs as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listLogs with error', async () => { - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.ListLogsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.ListLogsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listLogs = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listLogs(request), expectedError); - const actualRequest = (client.innerApiCalls.listLogs as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listLogs as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listLogsStream without error', async () => { - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.ListLogsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.ListLogsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [new String(), new String(), new String()]; - client.descriptors.page.listLogs.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listLogsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: string[] = []; - stream.on('data', (response: string) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.listLogs.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listLogs, request)); - assert( - (client.descriptors.page.listLogs.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listLogs with error', async () => { + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.ListLogsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.ListLogsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listLogs = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.listLogs(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listLogs as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listLogs as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listLogsStream with error', async () => { - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.ListLogsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.ListLogsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listLogs.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listLogsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: string[] = []; - stream.on('data', (response: string) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listLogs.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listLogs, request)); - assert( - (client.descriptors.page.listLogs.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listLogsStream without error', async () => { + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.ListLogsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.ListLogsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [new String(), new String(), new String()]; + client.descriptors.page.listLogs.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listLogsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: string[] = []; + stream.on('data', (response: string) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listLogs.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listLogs, request), + ); + assert( + (client.descriptors.page.listLogs.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('uses async iteration with listLogs without error', async () => { - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.ListLogsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.ListLogsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [new String(), new String(), new String()]; - client.descriptors.page.listLogs.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: string[] = []; - const iterable = client.listLogsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listLogs.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listLogs.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listLogsStream with error', async () => { + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.ListLogsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.ListLogsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listLogs.createStream = stubPageStreamingCall( + undefined, + expectedError, + ); + const stream = client.listLogsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: string[] = []; + stream.on('data', (response: string) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listLogs.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listLogs, request), + ); + assert( + (client.descriptors.page.listLogs.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('uses async iteration with listLogs with error', async () => { - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.ListLogsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.ListLogsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listLogs.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listLogsAsync(request); - await assert.rejects(async () => { - const responses: string[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listLogs.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listLogs.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listLogs without error', async () => { + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.ListLogsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.ListLogsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [new String(), new String(), new String()]; + client.descriptors.page.listLogs.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: string[] = []; + const iterable = client.listLogsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + (client.descriptors.page.listLogs.asyncIterate as SinonStub).getCall(0) + .args[1], + request, + ); + assert( + (client.descriptors.page.listLogs.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); }); - describe('Path templates', () => { - - describe('billingAccountCmekSettings', async () => { - const fakePath = "/rendered/path/billingAccountCmekSettings"; - const expectedParameters = { - billing_account: "billingAccountValue", - }; - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.billingAccountCmekSettingsPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.billingAccountCmekSettingsPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('billingAccountCmekSettingsPath', () => { - const result = client.billingAccountCmekSettingsPath("billingAccountValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.billingAccountCmekSettingsPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchBillingAccountFromBillingAccountCmekSettingsName', () => { - const result = client.matchBillingAccountFromBillingAccountCmekSettingsName(fakePath); - assert.strictEqual(result, "billingAccountValue"); - assert((client.pathTemplates.billingAccountCmekSettingsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('uses async iteration with listLogs with error', async () => { + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.ListLogsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.ListLogsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listLogs.asyncIterate = stubAsyncIterationCall( + undefined, + expectedError, + ); + const iterable = client.listLogsAsync(request); + await assert.rejects(async () => { + const responses: string[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + (client.descriptors.page.listLogs.asyncIterate as SinonStub).getCall(0) + .args[1], + request, + ); + assert( + (client.descriptors.page.listLogs.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + }); + + describe('Path templates', () => { + describe('billingAccountCmekSettings', async () => { + const fakePath = '/rendered/path/billingAccountCmekSettings'; + const expectedParameters = { + billing_account: 'billingAccountValue', + }; + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.billingAccountCmekSettingsPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.billingAccountCmekSettingsPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('billingAccountCmekSettingsPath', () => { + const result = client.billingAccountCmekSettingsPath( + 'billingAccountValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.billingAccountCmekSettingsPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchBillingAccountFromBillingAccountCmekSettingsName', () => { + const result = + client.matchBillingAccountFromBillingAccountCmekSettingsName( + fakePath, + ); + assert.strictEqual(result, 'billingAccountValue'); + assert( + ( + client.pathTemplates.billingAccountCmekSettingsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('billingAccountExclusion', async () => { - const fakePath = "/rendered/path/billingAccountExclusion"; - const expectedParameters = { - billing_account: "billingAccountValue", - exclusion: "exclusionValue", - }; - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.billingAccountExclusionPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.billingAccountExclusionPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('billingAccountExclusionPath', () => { - const result = client.billingAccountExclusionPath("billingAccountValue", "exclusionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.billingAccountExclusionPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchBillingAccountFromBillingAccountExclusionName', () => { - const result = client.matchBillingAccountFromBillingAccountExclusionName(fakePath); - assert.strictEqual(result, "billingAccountValue"); - assert((client.pathTemplates.billingAccountExclusionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchExclusionFromBillingAccountExclusionName', () => { - const result = client.matchExclusionFromBillingAccountExclusionName(fakePath); - assert.strictEqual(result, "exclusionValue"); - assert((client.pathTemplates.billingAccountExclusionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('billingAccountExclusion', async () => { + const fakePath = '/rendered/path/billingAccountExclusion'; + const expectedParameters = { + billing_account: 'billingAccountValue', + exclusion: 'exclusionValue', + }; + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.billingAccountExclusionPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.billingAccountExclusionPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('billingAccountExclusionPath', () => { + const result = client.billingAccountExclusionPath( + 'billingAccountValue', + 'exclusionValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.billingAccountExclusionPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchBillingAccountFromBillingAccountExclusionName', () => { + const result = + client.matchBillingAccountFromBillingAccountExclusionName(fakePath); + assert.strictEqual(result, 'billingAccountValue'); + assert( + ( + client.pathTemplates.billingAccountExclusionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchExclusionFromBillingAccountExclusionName', () => { + const result = + client.matchExclusionFromBillingAccountExclusionName(fakePath); + assert.strictEqual(result, 'exclusionValue'); + assert( + ( + client.pathTemplates.billingAccountExclusionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('billingAccountLocationBucket', async () => { - const fakePath = "/rendered/path/billingAccountLocationBucket"; - const expectedParameters = { - billing_account: "billingAccountValue", - location: "locationValue", - bucket: "bucketValue", - }; - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.billingAccountLocationBucketPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.billingAccountLocationBucketPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('billingAccountLocationBucketPath', () => { - const result = client.billingAccountLocationBucketPath("billingAccountValue", "locationValue", "bucketValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.billingAccountLocationBucketPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchBillingAccountFromBillingAccountLocationBucketName', () => { - const result = client.matchBillingAccountFromBillingAccountLocationBucketName(fakePath); - assert.strictEqual(result, "billingAccountValue"); - assert((client.pathTemplates.billingAccountLocationBucketPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromBillingAccountLocationBucketName', () => { - const result = client.matchLocationFromBillingAccountLocationBucketName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.billingAccountLocationBucketPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBucketFromBillingAccountLocationBucketName', () => { - const result = client.matchBucketFromBillingAccountLocationBucketName(fakePath); - assert.strictEqual(result, "bucketValue"); - assert((client.pathTemplates.billingAccountLocationBucketPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('billingAccountLocationBucket', async () => { + const fakePath = '/rendered/path/billingAccountLocationBucket'; + const expectedParameters = { + billing_account: 'billingAccountValue', + location: 'locationValue', + bucket: 'bucketValue', + }; + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.billingAccountLocationBucketPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.billingAccountLocationBucketPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('billingAccountLocationBucketPath', () => { + const result = client.billingAccountLocationBucketPath( + 'billingAccountValue', + 'locationValue', + 'bucketValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.billingAccountLocationBucketPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchBillingAccountFromBillingAccountLocationBucketName', () => { + const result = + client.matchBillingAccountFromBillingAccountLocationBucketName( + fakePath, + ); + assert.strictEqual(result, 'billingAccountValue'); + assert( + ( + client.pathTemplates.billingAccountLocationBucketPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromBillingAccountLocationBucketName', () => { + const result = + client.matchLocationFromBillingAccountLocationBucketName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + ( + client.pathTemplates.billingAccountLocationBucketPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBucketFromBillingAccountLocationBucketName', () => { + const result = + client.matchBucketFromBillingAccountLocationBucketName(fakePath); + assert.strictEqual(result, 'bucketValue'); + assert( + ( + client.pathTemplates.billingAccountLocationBucketPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('billingAccountLocationBucketView', async () => { - const fakePath = "/rendered/path/billingAccountLocationBucketView"; - const expectedParameters = { - billing_account: "billingAccountValue", - location: "locationValue", - bucket: "bucketValue", - view: "viewValue", - }; - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.billingAccountLocationBucketViewPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.billingAccountLocationBucketViewPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('billingAccountLocationBucketViewPath', () => { - const result = client.billingAccountLocationBucketViewPath("billingAccountValue", "locationValue", "bucketValue", "viewValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.billingAccountLocationBucketViewPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchBillingAccountFromBillingAccountLocationBucketViewName', () => { - const result = client.matchBillingAccountFromBillingAccountLocationBucketViewName(fakePath); - assert.strictEqual(result, "billingAccountValue"); - assert((client.pathTemplates.billingAccountLocationBucketViewPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromBillingAccountLocationBucketViewName', () => { - const result = client.matchLocationFromBillingAccountLocationBucketViewName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.billingAccountLocationBucketViewPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBucketFromBillingAccountLocationBucketViewName', () => { - const result = client.matchBucketFromBillingAccountLocationBucketViewName(fakePath); - assert.strictEqual(result, "bucketValue"); - assert((client.pathTemplates.billingAccountLocationBucketViewPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchViewFromBillingAccountLocationBucketViewName', () => { - const result = client.matchViewFromBillingAccountLocationBucketViewName(fakePath); - assert.strictEqual(result, "viewValue"); - assert((client.pathTemplates.billingAccountLocationBucketViewPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('billingAccountLocationBucketView', async () => { + const fakePath = '/rendered/path/billingAccountLocationBucketView'; + const expectedParameters = { + billing_account: 'billingAccountValue', + location: 'locationValue', + bucket: 'bucketValue', + view: 'viewValue', + }; + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.billingAccountLocationBucketViewPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.billingAccountLocationBucketViewPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('billingAccountLocationBucketViewPath', () => { + const result = client.billingAccountLocationBucketViewPath( + 'billingAccountValue', + 'locationValue', + 'bucketValue', + 'viewValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.billingAccountLocationBucketViewPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchBillingAccountFromBillingAccountLocationBucketViewName', () => { + const result = + client.matchBillingAccountFromBillingAccountLocationBucketViewName( + fakePath, + ); + assert.strictEqual(result, 'billingAccountValue'); + assert( + ( + client.pathTemplates.billingAccountLocationBucketViewPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromBillingAccountLocationBucketViewName', () => { + const result = + client.matchLocationFromBillingAccountLocationBucketViewName( + fakePath, + ); + assert.strictEqual(result, 'locationValue'); + assert( + ( + client.pathTemplates.billingAccountLocationBucketViewPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBucketFromBillingAccountLocationBucketViewName', () => { + const result = + client.matchBucketFromBillingAccountLocationBucketViewName(fakePath); + assert.strictEqual(result, 'bucketValue'); + assert( + ( + client.pathTemplates.billingAccountLocationBucketViewPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchViewFromBillingAccountLocationBucketViewName', () => { + const result = + client.matchViewFromBillingAccountLocationBucketViewName(fakePath); + assert.strictEqual(result, 'viewValue'); + assert( + ( + client.pathTemplates.billingAccountLocationBucketViewPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('billingAccountLog', async () => { - const fakePath = "/rendered/path/billingAccountLog"; - const expectedParameters = { - billing_account: "billingAccountValue", - log: "logValue", - }; - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.billingAccountLogPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.billingAccountLogPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('billingAccountLogPath', () => { - const result = client.billingAccountLogPath("billingAccountValue", "logValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.billingAccountLogPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchBillingAccountFromBillingAccountLogName', () => { - const result = client.matchBillingAccountFromBillingAccountLogName(fakePath); - assert.strictEqual(result, "billingAccountValue"); - assert((client.pathTemplates.billingAccountLogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLogFromBillingAccountLogName', () => { - const result = client.matchLogFromBillingAccountLogName(fakePath); - assert.strictEqual(result, "logValue"); - assert((client.pathTemplates.billingAccountLogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('billingAccountLog', async () => { + const fakePath = '/rendered/path/billingAccountLog'; + const expectedParameters = { + billing_account: 'billingAccountValue', + log: 'logValue', + }; + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.billingAccountLogPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.billingAccountLogPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('billingAccountLogPath', () => { + const result = client.billingAccountLogPath( + 'billingAccountValue', + 'logValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.billingAccountLogPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchBillingAccountFromBillingAccountLogName', () => { + const result = + client.matchBillingAccountFromBillingAccountLogName(fakePath); + assert.strictEqual(result, 'billingAccountValue'); + assert( + ( + client.pathTemplates.billingAccountLogPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLogFromBillingAccountLogName', () => { + const result = client.matchLogFromBillingAccountLogName(fakePath); + assert.strictEqual(result, 'logValue'); + assert( + ( + client.pathTemplates.billingAccountLogPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('billingAccountSettings', async () => { - const fakePath = "/rendered/path/billingAccountSettings"; - const expectedParameters = { - billing_account: "billingAccountValue", - }; - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.billingAccountSettingsPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.billingAccountSettingsPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('billingAccountSettingsPath', () => { - const result = client.billingAccountSettingsPath("billingAccountValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.billingAccountSettingsPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchBillingAccountFromBillingAccountSettingsName', () => { - const result = client.matchBillingAccountFromBillingAccountSettingsName(fakePath); - assert.strictEqual(result, "billingAccountValue"); - assert((client.pathTemplates.billingAccountSettingsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('billingAccountSettings', async () => { + const fakePath = '/rendered/path/billingAccountSettings'; + const expectedParameters = { + billing_account: 'billingAccountValue', + }; + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.billingAccountSettingsPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.billingAccountSettingsPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('billingAccountSettingsPath', () => { + const result = client.billingAccountSettingsPath('billingAccountValue'); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.billingAccountSettingsPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchBillingAccountFromBillingAccountSettingsName', () => { + const result = + client.matchBillingAccountFromBillingAccountSettingsName(fakePath); + assert.strictEqual(result, 'billingAccountValue'); + assert( + ( + client.pathTemplates.billingAccountSettingsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('billingAccountSink', async () => { - const fakePath = "/rendered/path/billingAccountSink"; - const expectedParameters = { - billing_account: "billingAccountValue", - sink: "sinkValue", - }; - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.billingAccountSinkPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.billingAccountSinkPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('billingAccountSinkPath', () => { - const result = client.billingAccountSinkPath("billingAccountValue", "sinkValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.billingAccountSinkPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchBillingAccountFromBillingAccountSinkName', () => { - const result = client.matchBillingAccountFromBillingAccountSinkName(fakePath); - assert.strictEqual(result, "billingAccountValue"); - assert((client.pathTemplates.billingAccountSinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchSinkFromBillingAccountSinkName', () => { - const result = client.matchSinkFromBillingAccountSinkName(fakePath); - assert.strictEqual(result, "sinkValue"); - assert((client.pathTemplates.billingAccountSinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('billingAccountSink', async () => { + const fakePath = '/rendered/path/billingAccountSink'; + const expectedParameters = { + billing_account: 'billingAccountValue', + sink: 'sinkValue', + }; + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.billingAccountSinkPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.billingAccountSinkPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('billingAccountSinkPath', () => { + const result = client.billingAccountSinkPath( + 'billingAccountValue', + 'sinkValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.billingAccountSinkPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchBillingAccountFromBillingAccountSinkName', () => { + const result = + client.matchBillingAccountFromBillingAccountSinkName(fakePath); + assert.strictEqual(result, 'billingAccountValue'); + assert( + ( + client.pathTemplates.billingAccountSinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchSinkFromBillingAccountSinkName', () => { + const result = client.matchSinkFromBillingAccountSinkName(fakePath); + assert.strictEqual(result, 'sinkValue'); + assert( + ( + client.pathTemplates.billingAccountSinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('folderCmekSettings', async () => { - const fakePath = "/rendered/path/folderCmekSettings"; - const expectedParameters = { - folder: "folderValue", - }; - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.folderCmekSettingsPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderCmekSettingsPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderCmekSettingsPath', () => { - const result = client.folderCmekSettingsPath("folderValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderCmekSettingsPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderCmekSettingsName', () => { - const result = client.matchFolderFromFolderCmekSettingsName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderCmekSettingsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('folderCmekSettings', async () => { + const fakePath = '/rendered/path/folderCmekSettings'; + const expectedParameters = { + folder: 'folderValue', + }; + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.folderCmekSettingsPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderCmekSettingsPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderCmekSettingsPath', () => { + const result = client.folderCmekSettingsPath('folderValue'); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.folderCmekSettingsPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderCmekSettingsName', () => { + const result = client.matchFolderFromFolderCmekSettingsName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + ( + client.pathTemplates.folderCmekSettingsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('folderExclusion', async () => { - const fakePath = "/rendered/path/folderExclusion"; - const expectedParameters = { - folder: "folderValue", - exclusion: "exclusionValue", - }; - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.folderExclusionPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderExclusionPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderExclusionPath', () => { - const result = client.folderExclusionPath("folderValue", "exclusionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderExclusionPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderExclusionName', () => { - const result = client.matchFolderFromFolderExclusionName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderExclusionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchExclusionFromFolderExclusionName', () => { - const result = client.matchExclusionFromFolderExclusionName(fakePath); - assert.strictEqual(result, "exclusionValue"); - assert((client.pathTemplates.folderExclusionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('folderExclusion', async () => { + const fakePath = '/rendered/path/folderExclusion'; + const expectedParameters = { + folder: 'folderValue', + exclusion: 'exclusionValue', + }; + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.folderExclusionPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderExclusionPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderExclusionPath', () => { + const result = client.folderExclusionPath( + 'folderValue', + 'exclusionValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.folderExclusionPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderExclusionName', () => { + const result = client.matchFolderFromFolderExclusionName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + (client.pathTemplates.folderExclusionPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchExclusionFromFolderExclusionName', () => { + const result = client.matchExclusionFromFolderExclusionName(fakePath); + assert.strictEqual(result, 'exclusionValue'); + assert( + (client.pathTemplates.folderExclusionPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('folderLocationBucket', async () => { - const fakePath = "/rendered/path/folderLocationBucket"; - const expectedParameters = { - folder: "folderValue", - location: "locationValue", - bucket: "bucketValue", - }; - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.folderLocationBucketPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderLocationBucketPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderLocationBucketPath', () => { - const result = client.folderLocationBucketPath("folderValue", "locationValue", "bucketValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderLocationBucketPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderLocationBucketName', () => { - const result = client.matchFolderFromFolderLocationBucketName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderLocationBucketPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromFolderLocationBucketName', () => { - const result = client.matchLocationFromFolderLocationBucketName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.folderLocationBucketPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBucketFromFolderLocationBucketName', () => { - const result = client.matchBucketFromFolderLocationBucketName(fakePath); - assert.strictEqual(result, "bucketValue"); - assert((client.pathTemplates.folderLocationBucketPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('folderLocationBucket', async () => { + const fakePath = '/rendered/path/folderLocationBucket'; + const expectedParameters = { + folder: 'folderValue', + location: 'locationValue', + bucket: 'bucketValue', + }; + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.folderLocationBucketPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderLocationBucketPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderLocationBucketPath', () => { + const result = client.folderLocationBucketPath( + 'folderValue', + 'locationValue', + 'bucketValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.folderLocationBucketPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderLocationBucketName', () => { + const result = client.matchFolderFromFolderLocationBucketName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + ( + client.pathTemplates.folderLocationBucketPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromFolderLocationBucketName', () => { + const result = + client.matchLocationFromFolderLocationBucketName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + ( + client.pathTemplates.folderLocationBucketPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBucketFromFolderLocationBucketName', () => { + const result = client.matchBucketFromFolderLocationBucketName(fakePath); + assert.strictEqual(result, 'bucketValue'); + assert( + ( + client.pathTemplates.folderLocationBucketPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('folderLocationBucketView', async () => { - const fakePath = "/rendered/path/folderLocationBucketView"; - const expectedParameters = { - folder: "folderValue", - location: "locationValue", - bucket: "bucketValue", - view: "viewValue", - }; - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.folderLocationBucketViewPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderLocationBucketViewPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderLocationBucketViewPath', () => { - const result = client.folderLocationBucketViewPath("folderValue", "locationValue", "bucketValue", "viewValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderLocationBucketViewPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderLocationBucketViewName', () => { - const result = client.matchFolderFromFolderLocationBucketViewName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderLocationBucketViewPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromFolderLocationBucketViewName', () => { - const result = client.matchLocationFromFolderLocationBucketViewName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.folderLocationBucketViewPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBucketFromFolderLocationBucketViewName', () => { - const result = client.matchBucketFromFolderLocationBucketViewName(fakePath); - assert.strictEqual(result, "bucketValue"); - assert((client.pathTemplates.folderLocationBucketViewPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchViewFromFolderLocationBucketViewName', () => { - const result = client.matchViewFromFolderLocationBucketViewName(fakePath); - assert.strictEqual(result, "viewValue"); - assert((client.pathTemplates.folderLocationBucketViewPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('folderLocationBucketView', async () => { + const fakePath = '/rendered/path/folderLocationBucketView'; + const expectedParameters = { + folder: 'folderValue', + location: 'locationValue', + bucket: 'bucketValue', + view: 'viewValue', + }; + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.folderLocationBucketViewPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderLocationBucketViewPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderLocationBucketViewPath', () => { + const result = client.folderLocationBucketViewPath( + 'folderValue', + 'locationValue', + 'bucketValue', + 'viewValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.folderLocationBucketViewPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderLocationBucketViewName', () => { + const result = + client.matchFolderFromFolderLocationBucketViewName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + ( + client.pathTemplates.folderLocationBucketViewPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromFolderLocationBucketViewName', () => { + const result = + client.matchLocationFromFolderLocationBucketViewName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + ( + client.pathTemplates.folderLocationBucketViewPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBucketFromFolderLocationBucketViewName', () => { + const result = + client.matchBucketFromFolderLocationBucketViewName(fakePath); + assert.strictEqual(result, 'bucketValue'); + assert( + ( + client.pathTemplates.folderLocationBucketViewPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchViewFromFolderLocationBucketViewName', () => { + const result = + client.matchViewFromFolderLocationBucketViewName(fakePath); + assert.strictEqual(result, 'viewValue'); + assert( + ( + client.pathTemplates.folderLocationBucketViewPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('folderLog', async () => { - const fakePath = "/rendered/path/folderLog"; - const expectedParameters = { - folder: "folderValue", - log: "logValue", - }; - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.folderLogPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderLogPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderLogPath', () => { - const result = client.folderLogPath("folderValue", "logValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderLogPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderLogName', () => { - const result = client.matchFolderFromFolderLogName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderLogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLogFromFolderLogName', () => { - const result = client.matchLogFromFolderLogName(fakePath); - assert.strictEqual(result, "logValue"); - assert((client.pathTemplates.folderLogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('folderLog', async () => { + const fakePath = '/rendered/path/folderLog'; + const expectedParameters = { + folder: 'folderValue', + log: 'logValue', + }; + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.folderLogPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderLogPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderLogPath', () => { + const result = client.folderLogPath('folderValue', 'logValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.folderLogPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderLogName', () => { + const result = client.matchFolderFromFolderLogName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + (client.pathTemplates.folderLogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLogFromFolderLogName', () => { + const result = client.matchLogFromFolderLogName(fakePath); + assert.strictEqual(result, 'logValue'); + assert( + (client.pathTemplates.folderLogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('folderSettings', async () => { - const fakePath = "/rendered/path/folderSettings"; - const expectedParameters = { - folder: "folderValue", - }; - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.folderSettingsPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderSettingsPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderSettingsPath', () => { - const result = client.folderSettingsPath("folderValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderSettingsPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderSettingsName', () => { - const result = client.matchFolderFromFolderSettingsName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderSettingsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('folderSettings', async () => { + const fakePath = '/rendered/path/folderSettings'; + const expectedParameters = { + folder: 'folderValue', + }; + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.folderSettingsPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderSettingsPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderSettingsPath', () => { + const result = client.folderSettingsPath('folderValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.folderSettingsPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderSettingsName', () => { + const result = client.matchFolderFromFolderSettingsName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + (client.pathTemplates.folderSettingsPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('folderSink', async () => { - const fakePath = "/rendered/path/folderSink"; - const expectedParameters = { - folder: "folderValue", - sink: "sinkValue", - }; - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.folderSinkPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderSinkPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderSinkPath', () => { - const result = client.folderSinkPath("folderValue", "sinkValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderSinkPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderSinkName', () => { - const result = client.matchFolderFromFolderSinkName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderSinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchSinkFromFolderSinkName', () => { - const result = client.matchSinkFromFolderSinkName(fakePath); - assert.strictEqual(result, "sinkValue"); - assert((client.pathTemplates.folderSinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('folderSink', async () => { + const fakePath = '/rendered/path/folderSink'; + const expectedParameters = { + folder: 'folderValue', + sink: 'sinkValue', + }; + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.folderSinkPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderSinkPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderSinkPath', () => { + const result = client.folderSinkPath('folderValue', 'sinkValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.folderSinkPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderSinkName', () => { + const result = client.matchFolderFromFolderSinkName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + (client.pathTemplates.folderSinkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchSinkFromFolderSinkName', () => { + const result = client.matchSinkFromFolderSinkName(fakePath); + assert.strictEqual(result, 'sinkValue'); + assert( + (client.pathTemplates.folderSinkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('logMetric', async () => { - const fakePath = "/rendered/path/logMetric"; - const expectedParameters = { - project: "projectValue", - metric: "metricValue", - }; - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.logMetricPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.logMetricPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('logMetricPath', () => { - const result = client.logMetricPath("projectValue", "metricValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.logMetricPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromLogMetricName', () => { - const result = client.matchProjectFromLogMetricName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.logMetricPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchMetricFromLogMetricName', () => { - const result = client.matchMetricFromLogMetricName(fakePath); - assert.strictEqual(result, "metricValue"); - assert((client.pathTemplates.logMetricPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('logMetric', async () => { + const fakePath = '/rendered/path/logMetric'; + const expectedParameters = { + project: 'projectValue', + metric: 'metricValue', + }; + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.logMetricPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.logMetricPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('logMetricPath', () => { + const result = client.logMetricPath('projectValue', 'metricValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.logMetricPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromLogMetricName', () => { + const result = client.matchProjectFromLogMetricName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.logMetricPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchMetricFromLogMetricName', () => { + const result = client.matchMetricFromLogMetricName(fakePath); + assert.strictEqual(result, 'metricValue'); + assert( + (client.pathTemplates.logMetricPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('organizationCmekSettings', async () => { - const fakePath = "/rendered/path/organizationCmekSettings"; - const expectedParameters = { - organization: "organizationValue", - }; - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.organizationCmekSettingsPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationCmekSettingsPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationCmekSettingsPath', () => { - const result = client.organizationCmekSettingsPath("organizationValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationCmekSettingsPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationCmekSettingsName', () => { - const result = client.matchOrganizationFromOrganizationCmekSettingsName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationCmekSettingsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('organizationCmekSettings', async () => { + const fakePath = '/rendered/path/organizationCmekSettings'; + const expectedParameters = { + organization: 'organizationValue', + }; + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.organizationCmekSettingsPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.organizationCmekSettingsPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('organizationCmekSettingsPath', () => { + const result = client.organizationCmekSettingsPath('organizationValue'); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationCmekSettingsPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationCmekSettingsName', () => { + const result = + client.matchOrganizationFromOrganizationCmekSettingsName(fakePath); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationCmekSettingsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('organizationExclusion', async () => { - const fakePath = "/rendered/path/organizationExclusion"; - const expectedParameters = { - organization: "organizationValue", - exclusion: "exclusionValue", - }; - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.organizationExclusionPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationExclusionPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationExclusionPath', () => { - const result = client.organizationExclusionPath("organizationValue", "exclusionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationExclusionPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationExclusionName', () => { - const result = client.matchOrganizationFromOrganizationExclusionName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationExclusionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchExclusionFromOrganizationExclusionName', () => { - const result = client.matchExclusionFromOrganizationExclusionName(fakePath); - assert.strictEqual(result, "exclusionValue"); - assert((client.pathTemplates.organizationExclusionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('organizationExclusion', async () => { + const fakePath = '/rendered/path/organizationExclusion'; + const expectedParameters = { + organization: 'organizationValue', + exclusion: 'exclusionValue', + }; + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.organizationExclusionPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.organizationExclusionPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('organizationExclusionPath', () => { + const result = client.organizationExclusionPath( + 'organizationValue', + 'exclusionValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationExclusionPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationExclusionName', () => { + const result = + client.matchOrganizationFromOrganizationExclusionName(fakePath); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationExclusionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchExclusionFromOrganizationExclusionName', () => { + const result = + client.matchExclusionFromOrganizationExclusionName(fakePath); + assert.strictEqual(result, 'exclusionValue'); + assert( + ( + client.pathTemplates.organizationExclusionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('organizationLocationBucket', async () => { - const fakePath = "/rendered/path/organizationLocationBucket"; - const expectedParameters = { - organization: "organizationValue", - location: "locationValue", - bucket: "bucketValue", - }; - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.organizationLocationBucketPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationLocationBucketPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationLocationBucketPath', () => { - const result = client.organizationLocationBucketPath("organizationValue", "locationValue", "bucketValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationLocationBucketPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationLocationBucketName', () => { - const result = client.matchOrganizationFromOrganizationLocationBucketName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationLocationBucketPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromOrganizationLocationBucketName', () => { - const result = client.matchLocationFromOrganizationLocationBucketName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.organizationLocationBucketPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBucketFromOrganizationLocationBucketName', () => { - const result = client.matchBucketFromOrganizationLocationBucketName(fakePath); - assert.strictEqual(result, "bucketValue"); - assert((client.pathTemplates.organizationLocationBucketPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('organizationLocationBucket', async () => { + const fakePath = '/rendered/path/organizationLocationBucket'; + const expectedParameters = { + organization: 'organizationValue', + location: 'locationValue', + bucket: 'bucketValue', + }; + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.organizationLocationBucketPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.organizationLocationBucketPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('organizationLocationBucketPath', () => { + const result = client.organizationLocationBucketPath( + 'organizationValue', + 'locationValue', + 'bucketValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationLocationBucketPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationLocationBucketName', () => { + const result = + client.matchOrganizationFromOrganizationLocationBucketName(fakePath); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationLocationBucketPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromOrganizationLocationBucketName', () => { + const result = + client.matchLocationFromOrganizationLocationBucketName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + ( + client.pathTemplates.organizationLocationBucketPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBucketFromOrganizationLocationBucketName', () => { + const result = + client.matchBucketFromOrganizationLocationBucketName(fakePath); + assert.strictEqual(result, 'bucketValue'); + assert( + ( + client.pathTemplates.organizationLocationBucketPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('organizationLocationBucketView', async () => { - const fakePath = "/rendered/path/organizationLocationBucketView"; - const expectedParameters = { - organization: "organizationValue", - location: "locationValue", - bucket: "bucketValue", - view: "viewValue", - }; - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.organizationLocationBucketViewPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationLocationBucketViewPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationLocationBucketViewPath', () => { - const result = client.organizationLocationBucketViewPath("organizationValue", "locationValue", "bucketValue", "viewValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationLocationBucketViewPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationLocationBucketViewName', () => { - const result = client.matchOrganizationFromOrganizationLocationBucketViewName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationLocationBucketViewPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromOrganizationLocationBucketViewName', () => { - const result = client.matchLocationFromOrganizationLocationBucketViewName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.organizationLocationBucketViewPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBucketFromOrganizationLocationBucketViewName', () => { - const result = client.matchBucketFromOrganizationLocationBucketViewName(fakePath); - assert.strictEqual(result, "bucketValue"); - assert((client.pathTemplates.organizationLocationBucketViewPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchViewFromOrganizationLocationBucketViewName', () => { - const result = client.matchViewFromOrganizationLocationBucketViewName(fakePath); - assert.strictEqual(result, "viewValue"); - assert((client.pathTemplates.organizationLocationBucketViewPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('organizationLocationBucketView', async () => { + const fakePath = '/rendered/path/organizationLocationBucketView'; + const expectedParameters = { + organization: 'organizationValue', + location: 'locationValue', + bucket: 'bucketValue', + view: 'viewValue', + }; + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.organizationLocationBucketViewPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.organizationLocationBucketViewPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('organizationLocationBucketViewPath', () => { + const result = client.organizationLocationBucketViewPath( + 'organizationValue', + 'locationValue', + 'bucketValue', + 'viewValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationLocationBucketViewPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationLocationBucketViewName', () => { + const result = + client.matchOrganizationFromOrganizationLocationBucketViewName( + fakePath, + ); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationLocationBucketViewPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromOrganizationLocationBucketViewName', () => { + const result = + client.matchLocationFromOrganizationLocationBucketViewName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + ( + client.pathTemplates.organizationLocationBucketViewPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBucketFromOrganizationLocationBucketViewName', () => { + const result = + client.matchBucketFromOrganizationLocationBucketViewName(fakePath); + assert.strictEqual(result, 'bucketValue'); + assert( + ( + client.pathTemplates.organizationLocationBucketViewPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchViewFromOrganizationLocationBucketViewName', () => { + const result = + client.matchViewFromOrganizationLocationBucketViewName(fakePath); + assert.strictEqual(result, 'viewValue'); + assert( + ( + client.pathTemplates.organizationLocationBucketViewPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('organizationLog', async () => { - const fakePath = "/rendered/path/organizationLog"; - const expectedParameters = { - organization: "organizationValue", - log: "logValue", - }; - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.organizationLogPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationLogPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationLogPath', () => { - const result = client.organizationLogPath("organizationValue", "logValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationLogPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationLogName', () => { - const result = client.matchOrganizationFromOrganizationLogName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationLogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLogFromOrganizationLogName', () => { - const result = client.matchLogFromOrganizationLogName(fakePath); - assert.strictEqual(result, "logValue"); - assert((client.pathTemplates.organizationLogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('organizationLog', async () => { + const fakePath = '/rendered/path/organizationLog'; + const expectedParameters = { + organization: 'organizationValue', + log: 'logValue', + }; + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.organizationLogPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.organizationLogPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('organizationLogPath', () => { + const result = client.organizationLogPath( + 'organizationValue', + 'logValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.organizationLogPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationLogName', () => { + const result = + client.matchOrganizationFromOrganizationLogName(fakePath); + assert.strictEqual(result, 'organizationValue'); + assert( + (client.pathTemplates.organizationLogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLogFromOrganizationLogName', () => { + const result = client.matchLogFromOrganizationLogName(fakePath); + assert.strictEqual(result, 'logValue'); + assert( + (client.pathTemplates.organizationLogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('organizationSettings', async () => { - const fakePath = "/rendered/path/organizationSettings"; - const expectedParameters = { - organization: "organizationValue", - }; - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.organizationSettingsPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationSettingsPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationSettingsPath', () => { - const result = client.organizationSettingsPath("organizationValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationSettingsPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationSettingsName', () => { - const result = client.matchOrganizationFromOrganizationSettingsName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationSettingsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('organizationSettings', async () => { + const fakePath = '/rendered/path/organizationSettings'; + const expectedParameters = { + organization: 'organizationValue', + }; + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.organizationSettingsPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.organizationSettingsPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('organizationSettingsPath', () => { + const result = client.organizationSettingsPath('organizationValue'); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationSettingsPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationSettingsName', () => { + const result = + client.matchOrganizationFromOrganizationSettingsName(fakePath); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationSettingsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('organizationSink', async () => { - const fakePath = "/rendered/path/organizationSink"; - const expectedParameters = { - organization: "organizationValue", - sink: "sinkValue", - }; - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.organizationSinkPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationSinkPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationSinkPath', () => { - const result = client.organizationSinkPath("organizationValue", "sinkValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationSinkPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationSinkName', () => { - const result = client.matchOrganizationFromOrganizationSinkName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationSinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchSinkFromOrganizationSinkName', () => { - const result = client.matchSinkFromOrganizationSinkName(fakePath); - assert.strictEqual(result, "sinkValue"); - assert((client.pathTemplates.organizationSinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('organizationSink', async () => { + const fakePath = '/rendered/path/organizationSink'; + const expectedParameters = { + organization: 'organizationValue', + sink: 'sinkValue', + }; + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.organizationSinkPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.organizationSinkPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('organizationSinkPath', () => { + const result = client.organizationSinkPath( + 'organizationValue', + 'sinkValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationSinkPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationSinkName', () => { + const result = + client.matchOrganizationFromOrganizationSinkName(fakePath); + assert.strictEqual(result, 'organizationValue'); + assert( + (client.pathTemplates.organizationSinkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchSinkFromOrganizationSinkName', () => { + const result = client.matchSinkFromOrganizationSinkName(fakePath); + assert.strictEqual(result, 'sinkValue'); + assert( + (client.pathTemplates.organizationSinkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('project', async () => { - const fakePath = "/rendered/path/project"; - const expectedParameters = { - project: "projectValue", - }; - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.projectPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectPath', () => { - const result = client.projectPath("projectValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectName', () => { - const result = client.matchProjectFromProjectName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('project', async () => { + const fakePath = '/rendered/path/project'; + const expectedParameters = { + project: 'projectValue', + }; + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.projectPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectPath', () => { + const result = client.projectPath('projectValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.projectPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectName', () => { + const result = client.matchProjectFromProjectName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.projectPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectCmekSettings', async () => { - const fakePath = "/rendered/path/projectCmekSettings"; - const expectedParameters = { - project: "projectValue", - }; - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.projectCmekSettingsPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectCmekSettingsPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectCmekSettingsPath', () => { - const result = client.projectCmekSettingsPath("projectValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectCmekSettingsPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectCmekSettingsName', () => { - const result = client.matchProjectFromProjectCmekSettingsName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectCmekSettingsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectCmekSettings', async () => { + const fakePath = '/rendered/path/projectCmekSettings'; + const expectedParameters = { + project: 'projectValue', + }; + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.projectCmekSettingsPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectCmekSettingsPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectCmekSettingsPath', () => { + const result = client.projectCmekSettingsPath('projectValue'); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.projectCmekSettingsPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectCmekSettingsName', () => { + const result = client.matchProjectFromProjectCmekSettingsName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.projectCmekSettingsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectExclusion', async () => { - const fakePath = "/rendered/path/projectExclusion"; - const expectedParameters = { - project: "projectValue", - exclusion: "exclusionValue", - }; - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.projectExclusionPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectExclusionPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectExclusionPath', () => { - const result = client.projectExclusionPath("projectValue", "exclusionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectExclusionPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectExclusionName', () => { - const result = client.matchProjectFromProjectExclusionName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectExclusionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchExclusionFromProjectExclusionName', () => { - const result = client.matchExclusionFromProjectExclusionName(fakePath); - assert.strictEqual(result, "exclusionValue"); - assert((client.pathTemplates.projectExclusionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectExclusion', async () => { + const fakePath = '/rendered/path/projectExclusion'; + const expectedParameters = { + project: 'projectValue', + exclusion: 'exclusionValue', + }; + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.projectExclusionPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectExclusionPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectExclusionPath', () => { + const result = client.projectExclusionPath( + 'projectValue', + 'exclusionValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.projectExclusionPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectExclusionName', () => { + const result = client.matchProjectFromProjectExclusionName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.projectExclusionPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchExclusionFromProjectExclusionName', () => { + const result = client.matchExclusionFromProjectExclusionName(fakePath); + assert.strictEqual(result, 'exclusionValue'); + assert( + (client.pathTemplates.projectExclusionPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectLocationBucket', async () => { - const fakePath = "/rendered/path/projectLocationBucket"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - bucket: "bucketValue", - }; - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.projectLocationBucketPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectLocationBucketPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectLocationBucketPath', () => { - const result = client.projectLocationBucketPath("projectValue", "locationValue", "bucketValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectLocationBucketPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectLocationBucketName', () => { - const result = client.matchProjectFromProjectLocationBucketName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectLocationBucketPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromProjectLocationBucketName', () => { - const result = client.matchLocationFromProjectLocationBucketName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.projectLocationBucketPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBucketFromProjectLocationBucketName', () => { - const result = client.matchBucketFromProjectLocationBucketName(fakePath); - assert.strictEqual(result, "bucketValue"); - assert((client.pathTemplates.projectLocationBucketPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectLocationBucket', async () => { + const fakePath = '/rendered/path/projectLocationBucket'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + bucket: 'bucketValue', + }; + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.projectLocationBucketPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectLocationBucketPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectLocationBucketPath', () => { + const result = client.projectLocationBucketPath( + 'projectValue', + 'locationValue', + 'bucketValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.projectLocationBucketPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectLocationBucketName', () => { + const result = + client.matchProjectFromProjectLocationBucketName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.projectLocationBucketPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromProjectLocationBucketName', () => { + const result = + client.matchLocationFromProjectLocationBucketName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + ( + client.pathTemplates.projectLocationBucketPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBucketFromProjectLocationBucketName', () => { + const result = + client.matchBucketFromProjectLocationBucketName(fakePath); + assert.strictEqual(result, 'bucketValue'); + assert( + ( + client.pathTemplates.projectLocationBucketPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectLocationBucketView', async () => { - const fakePath = "/rendered/path/projectLocationBucketView"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - bucket: "bucketValue", - view: "viewValue", - }; - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.projectLocationBucketViewPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectLocationBucketViewPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectLocationBucketViewPath', () => { - const result = client.projectLocationBucketViewPath("projectValue", "locationValue", "bucketValue", "viewValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectLocationBucketViewPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectLocationBucketViewName', () => { - const result = client.matchProjectFromProjectLocationBucketViewName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectLocationBucketViewPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromProjectLocationBucketViewName', () => { - const result = client.matchLocationFromProjectLocationBucketViewName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.projectLocationBucketViewPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBucketFromProjectLocationBucketViewName', () => { - const result = client.matchBucketFromProjectLocationBucketViewName(fakePath); - assert.strictEqual(result, "bucketValue"); - assert((client.pathTemplates.projectLocationBucketViewPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchViewFromProjectLocationBucketViewName', () => { - const result = client.matchViewFromProjectLocationBucketViewName(fakePath); - assert.strictEqual(result, "viewValue"); - assert((client.pathTemplates.projectLocationBucketViewPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectLocationBucketView', async () => { + const fakePath = '/rendered/path/projectLocationBucketView'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + bucket: 'bucketValue', + view: 'viewValue', + }; + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.projectLocationBucketViewPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectLocationBucketViewPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectLocationBucketViewPath', () => { + const result = client.projectLocationBucketViewPath( + 'projectValue', + 'locationValue', + 'bucketValue', + 'viewValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.projectLocationBucketViewPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectLocationBucketViewName', () => { + const result = + client.matchProjectFromProjectLocationBucketViewName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.projectLocationBucketViewPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromProjectLocationBucketViewName', () => { + const result = + client.matchLocationFromProjectLocationBucketViewName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + ( + client.pathTemplates.projectLocationBucketViewPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBucketFromProjectLocationBucketViewName', () => { + const result = + client.matchBucketFromProjectLocationBucketViewName(fakePath); + assert.strictEqual(result, 'bucketValue'); + assert( + ( + client.pathTemplates.projectLocationBucketViewPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchViewFromProjectLocationBucketViewName', () => { + const result = + client.matchViewFromProjectLocationBucketViewName(fakePath); + assert.strictEqual(result, 'viewValue'); + assert( + ( + client.pathTemplates.projectLocationBucketViewPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectLog', async () => { - const fakePath = "/rendered/path/projectLog"; - const expectedParameters = { - project: "projectValue", - log: "logValue", - }; - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.projectLogPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectLogPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectLogPath', () => { - const result = client.projectLogPath("projectValue", "logValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectLogPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectLogName', () => { - const result = client.matchProjectFromProjectLogName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectLogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLogFromProjectLogName', () => { - const result = client.matchLogFromProjectLogName(fakePath); - assert.strictEqual(result, "logValue"); - assert((client.pathTemplates.projectLogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectLog', async () => { + const fakePath = '/rendered/path/projectLog'; + const expectedParameters = { + project: 'projectValue', + log: 'logValue', + }; + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.projectLogPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectLogPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectLogPath', () => { + const result = client.projectLogPath('projectValue', 'logValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.projectLogPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectLogName', () => { + const result = client.matchProjectFromProjectLogName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.projectLogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLogFromProjectLogName', () => { + const result = client.matchLogFromProjectLogName(fakePath); + assert.strictEqual(result, 'logValue'); + assert( + (client.pathTemplates.projectLogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectSettings', async () => { - const fakePath = "/rendered/path/projectSettings"; - const expectedParameters = { - project: "projectValue", - }; - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.projectSettingsPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectSettingsPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectSettingsPath', () => { - const result = client.projectSettingsPath("projectValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectSettingsPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectSettingsName', () => { - const result = client.matchProjectFromProjectSettingsName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectSettingsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectSettings', async () => { + const fakePath = '/rendered/path/projectSettings'; + const expectedParameters = { + project: 'projectValue', + }; + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.projectSettingsPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectSettingsPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectSettingsPath', () => { + const result = client.projectSettingsPath('projectValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.projectSettingsPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectSettingsName', () => { + const result = client.matchProjectFromProjectSettingsName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.projectSettingsPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectSink', async () => { - const fakePath = "/rendered/path/projectSink"; - const expectedParameters = { - project: "projectValue", - sink: "sinkValue", - }; - const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.projectSinkPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectSinkPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectSinkPath', () => { - const result = client.projectSinkPath("projectValue", "sinkValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectSinkPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectSinkName', () => { - const result = client.matchProjectFromProjectSinkName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectSinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchSinkFromProjectSinkName', () => { - const result = client.matchSinkFromProjectSinkName(fakePath); - assert.strictEqual(result, "sinkValue"); - assert((client.pathTemplates.projectSinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectSink', async () => { + const fakePath = '/rendered/path/projectSink'; + const expectedParameters = { + project: 'projectValue', + sink: 'sinkValue', + }; + const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.projectSinkPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectSinkPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectSinkPath', () => { + const result = client.projectSinkPath('projectValue', 'sinkValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.projectSinkPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectSinkName', () => { + const result = client.matchProjectFromProjectSinkName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.projectSinkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchSinkFromProjectSinkName', () => { + const result = client.matchSinkFromProjectSinkName(fakePath); + assert.strictEqual(result, 'sinkValue'); + assert( + (client.pathTemplates.projectSinkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/core/generator/gapic-generator-typescript/baselines/logging/test/gapic_metrics_service_v2_v2.ts.baseline b/core/generator/gapic-generator-typescript/baselines/logging/test/gapic_metrics_service_v2_v2.ts.baseline index 42c74d03e950..9235e5013d1e 100644 --- a/core/generator/gapic-generator-typescript/baselines/logging/test/gapic_metrics_service_v2_v2.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/logging/test/gapic_metrics_service_v2_v2.ts.baseline @@ -19,2087 +19,2919 @@ import * as protos from '../protos/protos'; import * as assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as metricsservicev2Module from '../src'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; -import {protobuf} from 'google-gax'; +import { protobuf } from 'google-gax'; // Dynamically loaded proto JSON is needed to get the type information // to fill in default values for request objects -const root = protobuf.Root.fromJSON(require('../protos/protos.json')).resolveAll(); +const root = protobuf.Root.fromJSON( + require('../protos/protos.json'), +).resolveAll(); // eslint-disable-next-line @typescript-eslint/no-unused-vars function getTypeDefaultValue(typeName: string, fields: string[]) { - let type = root.lookupType(typeName) as protobuf.Type; - for (const field of fields.slice(0, -1)) { - type = type.fields[field]?.resolvedType as protobuf.Type; - } - return type.fields[fields[fields.length - 1]]?.defaultValue; + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type.fields[field]?.resolvedType as protobuf.Type; + } + return type.fields[fields[fields.length - 1]]?.defaultValue; } function generateSampleMessage(instance: T) { - const filledObject = (instance.constructor as typeof protobuf.Message) - .toObject(instance as protobuf.Message, {defaults: true}); - return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, { defaults: true }); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; } function stubSimpleCall(response?: ResponseType, error?: Error) { - return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); } -function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { - return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +function stubSimpleCallWithCallback( + response?: ResponseType, + error?: Error, +) { + return error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); } -function stubPageStreamingCall(responses?: ResponseType[], error?: Error) { - const pagingStub = sinon.stub(); - if (responses) { - for (let i = 0; i < responses.length; ++i) { - pagingStub.onCall(i).callsArgWith(2, null, responses[i]); - } +function stubPageStreamingCall( + responses?: ResponseType[], + error?: Error, +) { + const pagingStub = sinon.stub(); + if (responses) { + for (let i = 0; i < responses.length; ++i) { + pagingStub.onCall(i).callsArgWith(2, null, responses[i]); } - const transformStub = error ? sinon.stub().callsArgWith(2, error) : pagingStub; - const mockStream = new PassThrough({ - objectMode: true, - transform: transformStub, - }); - // trigger as many responses as needed - if (responses) { - for (let i = 0; i < responses.length; ++i) { - setImmediate(() => { mockStream.write({}); }); - } - setImmediate(() => { mockStream.end(); }); - } else { - setImmediate(() => { mockStream.write({}); }); - setImmediate(() => { mockStream.end(); }); + } + const transformStub = error + ? sinon.stub().callsArgWith(2, error) + : pagingStub; + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + // trigger as many responses as needed + if (responses) { + for (let i = 0; i < responses.length; ++i) { + setImmediate(() => { + mockStream.write({}); + }); } - return sinon.stub().returns(mockStream); + setImmediate(() => { + mockStream.end(); + }); + } else { + setImmediate(() => { + mockStream.write({}); + }); + setImmediate(() => { + mockStream.end(); + }); + } + return sinon.stub().returns(mockStream); } -function stubAsyncIterationCall(responses?: ResponseType[], error?: Error) { - let counter = 0; - const asyncIterable = { - [Symbol.asyncIterator]() { - return { - async next() { - if (error) { - return Promise.reject(error); - } - if (counter >= responses!.length) { - return Promise.resolve({done: true, value: undefined}); - } - return Promise.resolve({done: false, value: responses![counter++]}); - } - }; - } - }; - return sinon.stub().returns(asyncIterable); +function stubAsyncIterationCall( + responses?: ResponseType[], + error?: Error, +) { + let counter = 0; + const asyncIterable = { + [Symbol.asyncIterator]() { + return { + async next() { + if (error) { + return Promise.reject(error); + } + if (counter >= responses!.length) { + return Promise.resolve({ done: true, value: undefined }); + } + return Promise.resolve({ done: false, value: responses![counter++] }); + }, + }; + }, + }; + return sinon.stub().returns(asyncIterable); } describe('v2.MetricsServiceV2Client', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new metricsservicev2Module.v2.MetricsServiceV2Client(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'logging.googleapis.com'); - }); - - it('has universeDomain', () => { - const client = new metricsservicev2Module.v2.MetricsServiceV2Client(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); - - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - it('throws DeprecationWarning if static servicePath is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const servicePath = metricsservicev2Module.v2.MetricsServiceV2Client.servicePath; - assert.strictEqual(servicePath, 'logging.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = metricsservicev2Module.v2.MetricsServiceV2Client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'logging.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'logging.example.com'); - }); - - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'logging.example.com'); - }); - - if (typeof process === 'object' && 'env' in process) { - describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { - it('sets apiEndpoint from environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new metricsservicev2Module.v2.MetricsServiceV2Client(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'logging.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - - it('value configured in code has priority over environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'logging.configured.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { new metricsservicev2Module.v2.MetricsServiceV2Client({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); - - it('has port', () => { - const port = metricsservicev2Module.v2.MetricsServiceV2Client.port; - assert(port); - assert(typeof port === 'number'); - }); - - it('should create a client with no option', () => { - const client = new metricsservicev2Module.v2.MetricsServiceV2Client(); - assert(client); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new metricsservicev2Module.v2.MetricsServiceV2Client(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'logging.googleapis.com'); + }); - it('should create a client with gRPC fallback', () => { - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - fallback: true, - }); - assert(client); - }); + it('has universeDomain', () => { + const client = new metricsservicev2Module.v2.MetricsServiceV2Client(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - it('has initialize method and supports deferred initialization', async () => { - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.metricsServiceV2Stub, undefined); - await client.initialize(); - assert(client.metricsServiceV2Stub); - }); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = + metricsservicev2Module.v2.MetricsServiceV2Client.servicePath; + assert.strictEqual(servicePath, 'logging.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + metricsservicev2Module.v2.MetricsServiceV2Client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'logging.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + universeDomain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'logging.example.com'); + }); - it('has close method for the initialized client', done => { - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.metricsServiceV2Stub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + universe_domain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'logging.example.com'); + }); - it('has close method for the non-initialized client', done => { - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.metricsServiceV2Stub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); + if (typeof process === 'object' && 'env' in process) { + describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { + it('sets apiEndpoint from environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new metricsservicev2Module.v2.MetricsServiceV2Client(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'logging.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } + }); + + it('value configured in code has priority over environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + universeDomain: 'configured.example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'logging.configured.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } + }); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new metricsservicev2Module.v2.MetricsServiceV2Client({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); - }); + it('has port', () => { + const port = metricsservicev2Module.v2.MetricsServiceV2Client.port; + assert(port); + assert(typeof port === 'number'); + }); - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId((err?: Error|null, projectId?: string|null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } - }); - }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); - }); + it('should create a client with no option', () => { + const client = new metricsservicev2Module.v2.MetricsServiceV2Client(); + assert(client); }); - describe('getLogMetric', () => { - it('invokes getLogMetric without error', async () => { - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.GetLogMetricRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.GetLogMetricRequest', ['metricName']); - request.metricName = defaultValue1; - const expectedHeaderRequestParams = `metric_name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.logging.v2.LogMetric() - ); - client.innerApiCalls.getLogMetric = stubSimpleCall(expectedResponse); - const [response] = await client.getLogMetric(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getLogMetric as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getLogMetric as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('should create a client with gRPC fallback', () => { + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + fallback: true, + }); + assert(client); + }); - it('invokes getLogMetric without error using callback', async () => { - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.GetLogMetricRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.GetLogMetricRequest', ['metricName']); - request.metricName = defaultValue1; - const expectedHeaderRequestParams = `metric_name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.logging.v2.LogMetric() - ); - client.innerApiCalls.getLogMetric = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getLogMetric( - request, - (err?: Error|null, result?: protos.google.logging.v2.ILogMetric|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getLogMetric as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getLogMetric as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has initialize method and supports deferred initialization', async () => { + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.metricsServiceV2Stub, undefined); + await client.initialize(); + assert(client.metricsServiceV2Stub); + }); - it('invokes getLogMetric with error', async () => { - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.GetLogMetricRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.GetLogMetricRequest', ['metricName']); - request.metricName = defaultValue1; - const expectedHeaderRequestParams = `metric_name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getLogMetric = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getLogMetric(request), expectedError); - const actualRequest = (client.innerApiCalls.getLogMetric as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getLogMetric as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('has close method for the initialized client', (done) => { + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.metricsServiceV2Stub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes getLogMetric with closed client', async () => { - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.GetLogMetricRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.GetLogMetricRequest', ['metricName']); - request.metricName = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getLogMetric(request), expectedError); + it('has close method for the non-initialized client', (done) => { + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.metricsServiceV2Stub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); }); - describe('createLogMetric', () => { - it('invokes createLogMetric without error', async () => { - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.CreateLogMetricRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.CreateLogMetricRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.logging.v2.LogMetric() - ); - client.innerApiCalls.createLogMetric = stubSimpleCall(expectedResponse); - const [response] = await client.createLogMetric(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createLogMetric as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createLogMetric as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + }); - it('invokes createLogMetric without error using callback', async () => { - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.CreateLogMetricRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.CreateLogMetricRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.logging.v2.LogMetric() - ); - client.innerApiCalls.createLogMetric = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createLogMetric( - request, - (err?: Error|null, result?: protos.google.logging.v2.ILogMetric|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createLogMetric as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createLogMetric as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } + }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + }); + + describe('getLogMetric', () => { + it('invokes getLogMetric without error', async () => { + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.GetLogMetricRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.GetLogMetricRequest', + ['metricName'], + ); + request.metricName = defaultValue1; + const expectedHeaderRequestParams = `metric_name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.logging.v2.LogMetric(), + ); + client.innerApiCalls.getLogMetric = stubSimpleCall(expectedResponse); + const [response] = await client.getLogMetric(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getLogMetric as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getLogMetric as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createLogMetric with error', async () => { - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.CreateLogMetricRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.CreateLogMetricRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createLogMetric = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createLogMetric(request), expectedError); - const actualRequest = (client.innerApiCalls.createLogMetric as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createLogMetric as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getLogMetric without error using callback', async () => { + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.GetLogMetricRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.GetLogMetricRequest', + ['metricName'], + ); + request.metricName = defaultValue1; + const expectedHeaderRequestParams = `metric_name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.logging.v2.LogMetric(), + ); + client.innerApiCalls.getLogMetric = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getLogMetric( + request, + ( + err?: Error | null, + result?: protos.google.logging.v2.ILogMetric | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getLogMetric as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getLogMetric as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createLogMetric with closed client', async () => { - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.CreateLogMetricRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.CreateLogMetricRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createLogMetric(request), expectedError); - }); + it('invokes getLogMetric with error', async () => { + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.GetLogMetricRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.GetLogMetricRequest', + ['metricName'], + ); + request.metricName = defaultValue1; + const expectedHeaderRequestParams = `metric_name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getLogMetric = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getLogMetric(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getLogMetric as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getLogMetric as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('updateLogMetric', () => { - it('invokes updateLogMetric without error', async () => { - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.UpdateLogMetricRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.UpdateLogMetricRequest', ['metricName']); - request.metricName = defaultValue1; - const expectedHeaderRequestParams = `metric_name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.logging.v2.LogMetric() - ); - client.innerApiCalls.updateLogMetric = stubSimpleCall(expectedResponse); - const [response] = await client.updateLogMetric(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateLogMetric as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateLogMetric as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getLogMetric with closed client', async () => { + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.GetLogMetricRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.GetLogMetricRequest', + ['metricName'], + ); + request.metricName = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getLogMetric(request), expectedError); + }); + }); + + describe('createLogMetric', () => { + it('invokes createLogMetric without error', async () => { + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.CreateLogMetricRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.CreateLogMetricRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.logging.v2.LogMetric(), + ); + client.innerApiCalls.createLogMetric = stubSimpleCall(expectedResponse); + const [response] = await client.createLogMetric(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createLogMetric as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createLogMetric as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateLogMetric without error using callback', async () => { - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.UpdateLogMetricRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.UpdateLogMetricRequest', ['metricName']); - request.metricName = defaultValue1; - const expectedHeaderRequestParams = `metric_name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.logging.v2.LogMetric() - ); - client.innerApiCalls.updateLogMetric = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateLogMetric( - request, - (err?: Error|null, result?: protos.google.logging.v2.ILogMetric|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateLogMetric as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateLogMetric as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createLogMetric without error using callback', async () => { + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.CreateLogMetricRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.CreateLogMetricRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.logging.v2.LogMetric(), + ); + client.innerApiCalls.createLogMetric = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createLogMetric( + request, + ( + err?: Error | null, + result?: protos.google.logging.v2.ILogMetric | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createLogMetric as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createLogMetric as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateLogMetric with error', async () => { - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.UpdateLogMetricRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.UpdateLogMetricRequest', ['metricName']); - request.metricName = defaultValue1; - const expectedHeaderRequestParams = `metric_name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateLogMetric = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateLogMetric(request), expectedError); - const actualRequest = (client.innerApiCalls.updateLogMetric as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateLogMetric as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createLogMetric with error', async () => { + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.CreateLogMetricRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.CreateLogMetricRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createLogMetric = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.createLogMetric(request), expectedError); + const actualRequest = ( + client.innerApiCalls.createLogMetric as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createLogMetric as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateLogMetric with closed client', async () => { - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.UpdateLogMetricRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.UpdateLogMetricRequest', ['metricName']); - request.metricName = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateLogMetric(request), expectedError); - }); + it('invokes createLogMetric with closed client', async () => { + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.CreateLogMetricRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.CreateLogMetricRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.createLogMetric(request), expectedError); + }); + }); + + describe('updateLogMetric', () => { + it('invokes updateLogMetric without error', async () => { + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.UpdateLogMetricRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.UpdateLogMetricRequest', + ['metricName'], + ); + request.metricName = defaultValue1; + const expectedHeaderRequestParams = `metric_name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.logging.v2.LogMetric(), + ); + client.innerApiCalls.updateLogMetric = stubSimpleCall(expectedResponse); + const [response] = await client.updateLogMetric(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateLogMetric as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateLogMetric as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('deleteLogMetric', () => { - it('invokes deleteLogMetric without error', async () => { - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.DeleteLogMetricRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.DeleteLogMetricRequest', ['metricName']); - request.metricName = defaultValue1; - const expectedHeaderRequestParams = `metric_name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteLogMetric = stubSimpleCall(expectedResponse); - const [response] = await client.deleteLogMetric(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteLogMetric as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteLogMetric as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateLogMetric without error using callback', async () => { + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.UpdateLogMetricRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.UpdateLogMetricRequest', + ['metricName'], + ); + request.metricName = defaultValue1; + const expectedHeaderRequestParams = `metric_name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.logging.v2.LogMetric(), + ); + client.innerApiCalls.updateLogMetric = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateLogMetric( + request, + ( + err?: Error | null, + result?: protos.google.logging.v2.ILogMetric | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateLogMetric as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateLogMetric as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteLogMetric without error using callback', async () => { - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.DeleteLogMetricRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.DeleteLogMetricRequest', ['metricName']); - request.metricName = defaultValue1; - const expectedHeaderRequestParams = `metric_name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteLogMetric = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteLogMetric( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteLogMetric as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteLogMetric as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateLogMetric with error', async () => { + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.UpdateLogMetricRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.UpdateLogMetricRequest', + ['metricName'], + ); + request.metricName = defaultValue1; + const expectedHeaderRequestParams = `metric_name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateLogMetric = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.updateLogMetric(request), expectedError); + const actualRequest = ( + client.innerApiCalls.updateLogMetric as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateLogMetric as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteLogMetric with error', async () => { - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.DeleteLogMetricRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.DeleteLogMetricRequest', ['metricName']); - request.metricName = defaultValue1; - const expectedHeaderRequestParams = `metric_name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteLogMetric = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteLogMetric(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteLogMetric as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteLogMetric as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateLogMetric with closed client', async () => { + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.UpdateLogMetricRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.UpdateLogMetricRequest', + ['metricName'], + ); + request.metricName = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.updateLogMetric(request), expectedError); + }); + }); + + describe('deleteLogMetric', () => { + it('invokes deleteLogMetric without error', async () => { + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.DeleteLogMetricRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.DeleteLogMetricRequest', + ['metricName'], + ); + request.metricName = defaultValue1; + const expectedHeaderRequestParams = `metric_name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteLogMetric = stubSimpleCall(expectedResponse); + const [response] = await client.deleteLogMetric(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteLogMetric as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteLogMetric as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteLogMetric with closed client', async () => { - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.DeleteLogMetricRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.DeleteLogMetricRequest', ['metricName']); - request.metricName = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteLogMetric(request), expectedError); - }); + it('invokes deleteLogMetric without error using callback', async () => { + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.DeleteLogMetricRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.DeleteLogMetricRequest', + ['metricName'], + ); + request.metricName = defaultValue1; + const expectedHeaderRequestParams = `metric_name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteLogMetric = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteLogMetric( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteLogMetric as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteLogMetric as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('listLogMetrics', () => { - it('invokes listLogMetrics without error', async () => { - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.ListLogMetricsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.ListLogMetricsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.logging.v2.LogMetric()), - generateSampleMessage(new protos.google.logging.v2.LogMetric()), - generateSampleMessage(new protos.google.logging.v2.LogMetric()), - ]; - client.innerApiCalls.listLogMetrics = stubSimpleCall(expectedResponse); - const [response] = await client.listLogMetrics(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listLogMetrics as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listLogMetrics as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteLogMetric with error', async () => { + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.DeleteLogMetricRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.DeleteLogMetricRequest', + ['metricName'], + ); + request.metricName = defaultValue1; + const expectedHeaderRequestParams = `metric_name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteLogMetric = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.deleteLogMetric(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteLogMetric as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteLogMetric as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listLogMetrics without error using callback', async () => { - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.ListLogMetricsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.ListLogMetricsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.logging.v2.LogMetric()), - generateSampleMessage(new protos.google.logging.v2.LogMetric()), - generateSampleMessage(new protos.google.logging.v2.LogMetric()), - ]; - client.innerApiCalls.listLogMetrics = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listLogMetrics( - request, - (err?: Error|null, result?: protos.google.logging.v2.ILogMetric[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listLogMetrics as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listLogMetrics as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteLogMetric with closed client', async () => { + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.DeleteLogMetricRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.DeleteLogMetricRequest', + ['metricName'], + ); + request.metricName = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.deleteLogMetric(request), expectedError); + }); + }); + + describe('listLogMetrics', () => { + it('invokes listLogMetrics without error', async () => { + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.ListLogMetricsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.ListLogMetricsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.logging.v2.LogMetric()), + generateSampleMessage(new protos.google.logging.v2.LogMetric()), + generateSampleMessage(new protos.google.logging.v2.LogMetric()), + ]; + client.innerApiCalls.listLogMetrics = stubSimpleCall(expectedResponse); + const [response] = await client.listLogMetrics(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listLogMetrics as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listLogMetrics as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listLogMetrics with error', async () => { - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.ListLogMetricsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.ListLogMetricsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listLogMetrics = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listLogMetrics(request), expectedError); - const actualRequest = (client.innerApiCalls.listLogMetrics as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listLogMetrics as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listLogMetrics without error using callback', async () => { + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.ListLogMetricsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.ListLogMetricsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.logging.v2.LogMetric()), + generateSampleMessage(new protos.google.logging.v2.LogMetric()), + generateSampleMessage(new protos.google.logging.v2.LogMetric()), + ]; + client.innerApiCalls.listLogMetrics = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listLogMetrics( + request, + ( + err?: Error | null, + result?: protos.google.logging.v2.ILogMetric[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listLogMetrics as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listLogMetrics as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listLogMetricsStream without error', async () => { - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.ListLogMetricsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.ListLogMetricsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.logging.v2.LogMetric()), - generateSampleMessage(new protos.google.logging.v2.LogMetric()), - generateSampleMessage(new protos.google.logging.v2.LogMetric()), - ]; - client.descriptors.page.listLogMetrics.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listLogMetricsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.logging.v2.LogMetric[] = []; - stream.on('data', (response: protos.google.logging.v2.LogMetric) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.listLogMetrics.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listLogMetrics, request)); - assert( - (client.descriptors.page.listLogMetrics.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listLogMetrics with error', async () => { + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.ListLogMetricsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.ListLogMetricsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listLogMetrics = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listLogMetrics(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listLogMetrics as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listLogMetrics as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listLogMetricsStream with error', async () => { - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.ListLogMetricsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.ListLogMetricsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listLogMetrics.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listLogMetricsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.logging.v2.LogMetric[] = []; - stream.on('data', (response: protos.google.logging.v2.LogMetric) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listLogMetrics.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listLogMetrics, request)); - assert( - (client.descriptors.page.listLogMetrics.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listLogMetricsStream without error', async () => { + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.ListLogMetricsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.ListLogMetricsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.logging.v2.LogMetric()), + generateSampleMessage(new protos.google.logging.v2.LogMetric()), + generateSampleMessage(new protos.google.logging.v2.LogMetric()), + ]; + client.descriptors.page.listLogMetrics.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listLogMetricsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.logging.v2.LogMetric[] = []; + stream.on('data', (response: protos.google.logging.v2.LogMetric) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listLogMetrics.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listLogMetrics, request), + ); + assert( + (client.descriptors.page.listLogMetrics.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('uses async iteration with listLogMetrics without error', async () => { - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.ListLogMetricsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.ListLogMetricsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.logging.v2.LogMetric()), - generateSampleMessage(new protos.google.logging.v2.LogMetric()), - generateSampleMessage(new protos.google.logging.v2.LogMetric()), - ]; - client.descriptors.page.listLogMetrics.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.logging.v2.ILogMetric[] = []; - const iterable = client.listLogMetricsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listLogMetrics.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listLogMetrics.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listLogMetricsStream with error', async () => { + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.ListLogMetricsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.ListLogMetricsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listLogMetrics.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listLogMetricsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.logging.v2.LogMetric[] = []; + stream.on('data', (response: protos.google.logging.v2.LogMetric) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listLogMetrics.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listLogMetrics, request), + ); + assert( + (client.descriptors.page.listLogMetrics.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('uses async iteration with listLogMetrics with error', async () => { - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.logging.v2.ListLogMetricsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.logging.v2.ListLogMetricsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listLogMetrics.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listLogMetricsAsync(request); - await assert.rejects(async () => { - const responses: protos.google.logging.v2.ILogMetric[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listLogMetrics.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listLogMetrics.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listLogMetrics without error', async () => { + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.ListLogMetricsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.ListLogMetricsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.logging.v2.LogMetric()), + generateSampleMessage(new protos.google.logging.v2.LogMetric()), + generateSampleMessage(new protos.google.logging.v2.LogMetric()), + ]; + client.descriptors.page.listLogMetrics.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.logging.v2.ILogMetric[] = []; + const iterable = client.listLogMetricsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listLogMetrics.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listLogMetrics.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); }); - describe('Path templates', () => { - - describe('billingAccountCmekSettings', async () => { - const fakePath = "/rendered/path/billingAccountCmekSettings"; - const expectedParameters = { - billing_account: "billingAccountValue", - }; - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.billingAccountCmekSettingsPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.billingAccountCmekSettingsPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('billingAccountCmekSettingsPath', () => { - const result = client.billingAccountCmekSettingsPath("billingAccountValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.billingAccountCmekSettingsPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchBillingAccountFromBillingAccountCmekSettingsName', () => { - const result = client.matchBillingAccountFromBillingAccountCmekSettingsName(fakePath); - assert.strictEqual(result, "billingAccountValue"); - assert((client.pathTemplates.billingAccountCmekSettingsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('uses async iteration with listLogMetrics with error', async () => { + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.logging.v2.ListLogMetricsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.logging.v2.ListLogMetricsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listLogMetrics.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listLogMetricsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.logging.v2.ILogMetric[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listLogMetrics.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listLogMetrics.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + }); + + describe('Path templates', () => { + describe('billingAccountCmekSettings', async () => { + const fakePath = '/rendered/path/billingAccountCmekSettings'; + const expectedParameters = { + billing_account: 'billingAccountValue', + }; + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.billingAccountCmekSettingsPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.billingAccountCmekSettingsPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('billingAccountCmekSettingsPath', () => { + const result = client.billingAccountCmekSettingsPath( + 'billingAccountValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.billingAccountCmekSettingsPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchBillingAccountFromBillingAccountCmekSettingsName', () => { + const result = + client.matchBillingAccountFromBillingAccountCmekSettingsName( + fakePath, + ); + assert.strictEqual(result, 'billingAccountValue'); + assert( + ( + client.pathTemplates.billingAccountCmekSettingsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('billingAccountExclusion', async () => { - const fakePath = "/rendered/path/billingAccountExclusion"; - const expectedParameters = { - billing_account: "billingAccountValue", - exclusion: "exclusionValue", - }; - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.billingAccountExclusionPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.billingAccountExclusionPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('billingAccountExclusionPath', () => { - const result = client.billingAccountExclusionPath("billingAccountValue", "exclusionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.billingAccountExclusionPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchBillingAccountFromBillingAccountExclusionName', () => { - const result = client.matchBillingAccountFromBillingAccountExclusionName(fakePath); - assert.strictEqual(result, "billingAccountValue"); - assert((client.pathTemplates.billingAccountExclusionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchExclusionFromBillingAccountExclusionName', () => { - const result = client.matchExclusionFromBillingAccountExclusionName(fakePath); - assert.strictEqual(result, "exclusionValue"); - assert((client.pathTemplates.billingAccountExclusionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('billingAccountExclusion', async () => { + const fakePath = '/rendered/path/billingAccountExclusion'; + const expectedParameters = { + billing_account: 'billingAccountValue', + exclusion: 'exclusionValue', + }; + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.billingAccountExclusionPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.billingAccountExclusionPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('billingAccountExclusionPath', () => { + const result = client.billingAccountExclusionPath( + 'billingAccountValue', + 'exclusionValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.billingAccountExclusionPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchBillingAccountFromBillingAccountExclusionName', () => { + const result = + client.matchBillingAccountFromBillingAccountExclusionName(fakePath); + assert.strictEqual(result, 'billingAccountValue'); + assert( + ( + client.pathTemplates.billingAccountExclusionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchExclusionFromBillingAccountExclusionName', () => { + const result = + client.matchExclusionFromBillingAccountExclusionName(fakePath); + assert.strictEqual(result, 'exclusionValue'); + assert( + ( + client.pathTemplates.billingAccountExclusionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('billingAccountLocationBucket', async () => { - const fakePath = "/rendered/path/billingAccountLocationBucket"; - const expectedParameters = { - billing_account: "billingAccountValue", - location: "locationValue", - bucket: "bucketValue", - }; - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.billingAccountLocationBucketPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.billingAccountLocationBucketPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('billingAccountLocationBucketPath', () => { - const result = client.billingAccountLocationBucketPath("billingAccountValue", "locationValue", "bucketValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.billingAccountLocationBucketPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchBillingAccountFromBillingAccountLocationBucketName', () => { - const result = client.matchBillingAccountFromBillingAccountLocationBucketName(fakePath); - assert.strictEqual(result, "billingAccountValue"); - assert((client.pathTemplates.billingAccountLocationBucketPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromBillingAccountLocationBucketName', () => { - const result = client.matchLocationFromBillingAccountLocationBucketName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.billingAccountLocationBucketPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBucketFromBillingAccountLocationBucketName', () => { - const result = client.matchBucketFromBillingAccountLocationBucketName(fakePath); - assert.strictEqual(result, "bucketValue"); - assert((client.pathTemplates.billingAccountLocationBucketPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('billingAccountLocationBucket', async () => { + const fakePath = '/rendered/path/billingAccountLocationBucket'; + const expectedParameters = { + billing_account: 'billingAccountValue', + location: 'locationValue', + bucket: 'bucketValue', + }; + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.billingAccountLocationBucketPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.billingAccountLocationBucketPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('billingAccountLocationBucketPath', () => { + const result = client.billingAccountLocationBucketPath( + 'billingAccountValue', + 'locationValue', + 'bucketValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.billingAccountLocationBucketPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchBillingAccountFromBillingAccountLocationBucketName', () => { + const result = + client.matchBillingAccountFromBillingAccountLocationBucketName( + fakePath, + ); + assert.strictEqual(result, 'billingAccountValue'); + assert( + ( + client.pathTemplates.billingAccountLocationBucketPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromBillingAccountLocationBucketName', () => { + const result = + client.matchLocationFromBillingAccountLocationBucketName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + ( + client.pathTemplates.billingAccountLocationBucketPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBucketFromBillingAccountLocationBucketName', () => { + const result = + client.matchBucketFromBillingAccountLocationBucketName(fakePath); + assert.strictEqual(result, 'bucketValue'); + assert( + ( + client.pathTemplates.billingAccountLocationBucketPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('billingAccountLocationBucketView', async () => { - const fakePath = "/rendered/path/billingAccountLocationBucketView"; - const expectedParameters = { - billing_account: "billingAccountValue", - location: "locationValue", - bucket: "bucketValue", - view: "viewValue", - }; - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.billingAccountLocationBucketViewPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.billingAccountLocationBucketViewPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('billingAccountLocationBucketViewPath', () => { - const result = client.billingAccountLocationBucketViewPath("billingAccountValue", "locationValue", "bucketValue", "viewValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.billingAccountLocationBucketViewPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchBillingAccountFromBillingAccountLocationBucketViewName', () => { - const result = client.matchBillingAccountFromBillingAccountLocationBucketViewName(fakePath); - assert.strictEqual(result, "billingAccountValue"); - assert((client.pathTemplates.billingAccountLocationBucketViewPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromBillingAccountLocationBucketViewName', () => { - const result = client.matchLocationFromBillingAccountLocationBucketViewName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.billingAccountLocationBucketViewPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBucketFromBillingAccountLocationBucketViewName', () => { - const result = client.matchBucketFromBillingAccountLocationBucketViewName(fakePath); - assert.strictEqual(result, "bucketValue"); - assert((client.pathTemplates.billingAccountLocationBucketViewPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchViewFromBillingAccountLocationBucketViewName', () => { - const result = client.matchViewFromBillingAccountLocationBucketViewName(fakePath); - assert.strictEqual(result, "viewValue"); - assert((client.pathTemplates.billingAccountLocationBucketViewPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('billingAccountLocationBucketView', async () => { + const fakePath = '/rendered/path/billingAccountLocationBucketView'; + const expectedParameters = { + billing_account: 'billingAccountValue', + location: 'locationValue', + bucket: 'bucketValue', + view: 'viewValue', + }; + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.billingAccountLocationBucketViewPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.billingAccountLocationBucketViewPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('billingAccountLocationBucketViewPath', () => { + const result = client.billingAccountLocationBucketViewPath( + 'billingAccountValue', + 'locationValue', + 'bucketValue', + 'viewValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.billingAccountLocationBucketViewPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchBillingAccountFromBillingAccountLocationBucketViewName', () => { + const result = + client.matchBillingAccountFromBillingAccountLocationBucketViewName( + fakePath, + ); + assert.strictEqual(result, 'billingAccountValue'); + assert( + ( + client.pathTemplates.billingAccountLocationBucketViewPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromBillingAccountLocationBucketViewName', () => { + const result = + client.matchLocationFromBillingAccountLocationBucketViewName( + fakePath, + ); + assert.strictEqual(result, 'locationValue'); + assert( + ( + client.pathTemplates.billingAccountLocationBucketViewPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBucketFromBillingAccountLocationBucketViewName', () => { + const result = + client.matchBucketFromBillingAccountLocationBucketViewName(fakePath); + assert.strictEqual(result, 'bucketValue'); + assert( + ( + client.pathTemplates.billingAccountLocationBucketViewPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchViewFromBillingAccountLocationBucketViewName', () => { + const result = + client.matchViewFromBillingAccountLocationBucketViewName(fakePath); + assert.strictEqual(result, 'viewValue'); + assert( + ( + client.pathTemplates.billingAccountLocationBucketViewPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('billingAccountLog', async () => { - const fakePath = "/rendered/path/billingAccountLog"; - const expectedParameters = { - billing_account: "billingAccountValue", - log: "logValue", - }; - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.billingAccountLogPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.billingAccountLogPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('billingAccountLogPath', () => { - const result = client.billingAccountLogPath("billingAccountValue", "logValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.billingAccountLogPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchBillingAccountFromBillingAccountLogName', () => { - const result = client.matchBillingAccountFromBillingAccountLogName(fakePath); - assert.strictEqual(result, "billingAccountValue"); - assert((client.pathTemplates.billingAccountLogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLogFromBillingAccountLogName', () => { - const result = client.matchLogFromBillingAccountLogName(fakePath); - assert.strictEqual(result, "logValue"); - assert((client.pathTemplates.billingAccountLogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('billingAccountLog', async () => { + const fakePath = '/rendered/path/billingAccountLog'; + const expectedParameters = { + billing_account: 'billingAccountValue', + log: 'logValue', + }; + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.billingAccountLogPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.billingAccountLogPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('billingAccountLogPath', () => { + const result = client.billingAccountLogPath( + 'billingAccountValue', + 'logValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.billingAccountLogPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchBillingAccountFromBillingAccountLogName', () => { + const result = + client.matchBillingAccountFromBillingAccountLogName(fakePath); + assert.strictEqual(result, 'billingAccountValue'); + assert( + ( + client.pathTemplates.billingAccountLogPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLogFromBillingAccountLogName', () => { + const result = client.matchLogFromBillingAccountLogName(fakePath); + assert.strictEqual(result, 'logValue'); + assert( + ( + client.pathTemplates.billingAccountLogPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('billingAccountSettings', async () => { - const fakePath = "/rendered/path/billingAccountSettings"; - const expectedParameters = { - billing_account: "billingAccountValue", - }; - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.billingAccountSettingsPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.billingAccountSettingsPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('billingAccountSettingsPath', () => { - const result = client.billingAccountSettingsPath("billingAccountValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.billingAccountSettingsPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchBillingAccountFromBillingAccountSettingsName', () => { - const result = client.matchBillingAccountFromBillingAccountSettingsName(fakePath); - assert.strictEqual(result, "billingAccountValue"); - assert((client.pathTemplates.billingAccountSettingsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('billingAccountSettings', async () => { + const fakePath = '/rendered/path/billingAccountSettings'; + const expectedParameters = { + billing_account: 'billingAccountValue', + }; + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.billingAccountSettingsPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.billingAccountSettingsPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('billingAccountSettingsPath', () => { + const result = client.billingAccountSettingsPath('billingAccountValue'); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.billingAccountSettingsPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchBillingAccountFromBillingAccountSettingsName', () => { + const result = + client.matchBillingAccountFromBillingAccountSettingsName(fakePath); + assert.strictEqual(result, 'billingAccountValue'); + assert( + ( + client.pathTemplates.billingAccountSettingsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('billingAccountSink', async () => { - const fakePath = "/rendered/path/billingAccountSink"; - const expectedParameters = { - billing_account: "billingAccountValue", - sink: "sinkValue", - }; - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.billingAccountSinkPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.billingAccountSinkPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('billingAccountSinkPath', () => { - const result = client.billingAccountSinkPath("billingAccountValue", "sinkValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.billingAccountSinkPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchBillingAccountFromBillingAccountSinkName', () => { - const result = client.matchBillingAccountFromBillingAccountSinkName(fakePath); - assert.strictEqual(result, "billingAccountValue"); - assert((client.pathTemplates.billingAccountSinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchSinkFromBillingAccountSinkName', () => { - const result = client.matchSinkFromBillingAccountSinkName(fakePath); - assert.strictEqual(result, "sinkValue"); - assert((client.pathTemplates.billingAccountSinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('billingAccountSink', async () => { + const fakePath = '/rendered/path/billingAccountSink'; + const expectedParameters = { + billing_account: 'billingAccountValue', + sink: 'sinkValue', + }; + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.billingAccountSinkPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.billingAccountSinkPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('billingAccountSinkPath', () => { + const result = client.billingAccountSinkPath( + 'billingAccountValue', + 'sinkValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.billingAccountSinkPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchBillingAccountFromBillingAccountSinkName', () => { + const result = + client.matchBillingAccountFromBillingAccountSinkName(fakePath); + assert.strictEqual(result, 'billingAccountValue'); + assert( + ( + client.pathTemplates.billingAccountSinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchSinkFromBillingAccountSinkName', () => { + const result = client.matchSinkFromBillingAccountSinkName(fakePath); + assert.strictEqual(result, 'sinkValue'); + assert( + ( + client.pathTemplates.billingAccountSinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('folderCmekSettings', async () => { - const fakePath = "/rendered/path/folderCmekSettings"; - const expectedParameters = { - folder: "folderValue", - }; - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.folderCmekSettingsPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderCmekSettingsPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderCmekSettingsPath', () => { - const result = client.folderCmekSettingsPath("folderValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderCmekSettingsPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderCmekSettingsName', () => { - const result = client.matchFolderFromFolderCmekSettingsName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderCmekSettingsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('folderCmekSettings', async () => { + const fakePath = '/rendered/path/folderCmekSettings'; + const expectedParameters = { + folder: 'folderValue', + }; + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.folderCmekSettingsPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderCmekSettingsPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderCmekSettingsPath', () => { + const result = client.folderCmekSettingsPath('folderValue'); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.folderCmekSettingsPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderCmekSettingsName', () => { + const result = client.matchFolderFromFolderCmekSettingsName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + ( + client.pathTemplates.folderCmekSettingsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('folderExclusion', async () => { - const fakePath = "/rendered/path/folderExclusion"; - const expectedParameters = { - folder: "folderValue", - exclusion: "exclusionValue", - }; - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.folderExclusionPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderExclusionPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderExclusionPath', () => { - const result = client.folderExclusionPath("folderValue", "exclusionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderExclusionPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderExclusionName', () => { - const result = client.matchFolderFromFolderExclusionName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderExclusionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchExclusionFromFolderExclusionName', () => { - const result = client.matchExclusionFromFolderExclusionName(fakePath); - assert.strictEqual(result, "exclusionValue"); - assert((client.pathTemplates.folderExclusionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('folderExclusion', async () => { + const fakePath = '/rendered/path/folderExclusion'; + const expectedParameters = { + folder: 'folderValue', + exclusion: 'exclusionValue', + }; + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.folderExclusionPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderExclusionPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderExclusionPath', () => { + const result = client.folderExclusionPath( + 'folderValue', + 'exclusionValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.folderExclusionPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderExclusionName', () => { + const result = client.matchFolderFromFolderExclusionName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + (client.pathTemplates.folderExclusionPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchExclusionFromFolderExclusionName', () => { + const result = client.matchExclusionFromFolderExclusionName(fakePath); + assert.strictEqual(result, 'exclusionValue'); + assert( + (client.pathTemplates.folderExclusionPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('folderLocationBucket', async () => { - const fakePath = "/rendered/path/folderLocationBucket"; - const expectedParameters = { - folder: "folderValue", - location: "locationValue", - bucket: "bucketValue", - }; - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.folderLocationBucketPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderLocationBucketPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderLocationBucketPath', () => { - const result = client.folderLocationBucketPath("folderValue", "locationValue", "bucketValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderLocationBucketPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderLocationBucketName', () => { - const result = client.matchFolderFromFolderLocationBucketName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderLocationBucketPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromFolderLocationBucketName', () => { - const result = client.matchLocationFromFolderLocationBucketName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.folderLocationBucketPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBucketFromFolderLocationBucketName', () => { - const result = client.matchBucketFromFolderLocationBucketName(fakePath); - assert.strictEqual(result, "bucketValue"); - assert((client.pathTemplates.folderLocationBucketPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('folderLocationBucket', async () => { + const fakePath = '/rendered/path/folderLocationBucket'; + const expectedParameters = { + folder: 'folderValue', + location: 'locationValue', + bucket: 'bucketValue', + }; + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.folderLocationBucketPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderLocationBucketPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderLocationBucketPath', () => { + const result = client.folderLocationBucketPath( + 'folderValue', + 'locationValue', + 'bucketValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.folderLocationBucketPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderLocationBucketName', () => { + const result = client.matchFolderFromFolderLocationBucketName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + ( + client.pathTemplates.folderLocationBucketPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromFolderLocationBucketName', () => { + const result = + client.matchLocationFromFolderLocationBucketName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + ( + client.pathTemplates.folderLocationBucketPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBucketFromFolderLocationBucketName', () => { + const result = client.matchBucketFromFolderLocationBucketName(fakePath); + assert.strictEqual(result, 'bucketValue'); + assert( + ( + client.pathTemplates.folderLocationBucketPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('folderLocationBucketView', async () => { - const fakePath = "/rendered/path/folderLocationBucketView"; - const expectedParameters = { - folder: "folderValue", - location: "locationValue", - bucket: "bucketValue", - view: "viewValue", - }; - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.folderLocationBucketViewPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderLocationBucketViewPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderLocationBucketViewPath', () => { - const result = client.folderLocationBucketViewPath("folderValue", "locationValue", "bucketValue", "viewValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderLocationBucketViewPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderLocationBucketViewName', () => { - const result = client.matchFolderFromFolderLocationBucketViewName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderLocationBucketViewPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromFolderLocationBucketViewName', () => { - const result = client.matchLocationFromFolderLocationBucketViewName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.folderLocationBucketViewPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBucketFromFolderLocationBucketViewName', () => { - const result = client.matchBucketFromFolderLocationBucketViewName(fakePath); - assert.strictEqual(result, "bucketValue"); - assert((client.pathTemplates.folderLocationBucketViewPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchViewFromFolderLocationBucketViewName', () => { - const result = client.matchViewFromFolderLocationBucketViewName(fakePath); - assert.strictEqual(result, "viewValue"); - assert((client.pathTemplates.folderLocationBucketViewPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('folderLocationBucketView', async () => { + const fakePath = '/rendered/path/folderLocationBucketView'; + const expectedParameters = { + folder: 'folderValue', + location: 'locationValue', + bucket: 'bucketValue', + view: 'viewValue', + }; + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.folderLocationBucketViewPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderLocationBucketViewPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderLocationBucketViewPath', () => { + const result = client.folderLocationBucketViewPath( + 'folderValue', + 'locationValue', + 'bucketValue', + 'viewValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.folderLocationBucketViewPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderLocationBucketViewName', () => { + const result = + client.matchFolderFromFolderLocationBucketViewName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + ( + client.pathTemplates.folderLocationBucketViewPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromFolderLocationBucketViewName', () => { + const result = + client.matchLocationFromFolderLocationBucketViewName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + ( + client.pathTemplates.folderLocationBucketViewPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBucketFromFolderLocationBucketViewName', () => { + const result = + client.matchBucketFromFolderLocationBucketViewName(fakePath); + assert.strictEqual(result, 'bucketValue'); + assert( + ( + client.pathTemplates.folderLocationBucketViewPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchViewFromFolderLocationBucketViewName', () => { + const result = + client.matchViewFromFolderLocationBucketViewName(fakePath); + assert.strictEqual(result, 'viewValue'); + assert( + ( + client.pathTemplates.folderLocationBucketViewPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('folderLog', async () => { - const fakePath = "/rendered/path/folderLog"; - const expectedParameters = { - folder: "folderValue", - log: "logValue", - }; - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.folderLogPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderLogPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderLogPath', () => { - const result = client.folderLogPath("folderValue", "logValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderLogPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderLogName', () => { - const result = client.matchFolderFromFolderLogName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderLogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLogFromFolderLogName', () => { - const result = client.matchLogFromFolderLogName(fakePath); - assert.strictEqual(result, "logValue"); - assert((client.pathTemplates.folderLogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('folderLog', async () => { + const fakePath = '/rendered/path/folderLog'; + const expectedParameters = { + folder: 'folderValue', + log: 'logValue', + }; + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.folderLogPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderLogPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderLogPath', () => { + const result = client.folderLogPath('folderValue', 'logValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.folderLogPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderLogName', () => { + const result = client.matchFolderFromFolderLogName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + (client.pathTemplates.folderLogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLogFromFolderLogName', () => { + const result = client.matchLogFromFolderLogName(fakePath); + assert.strictEqual(result, 'logValue'); + assert( + (client.pathTemplates.folderLogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('folderSettings', async () => { - const fakePath = "/rendered/path/folderSettings"; - const expectedParameters = { - folder: "folderValue", - }; - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.folderSettingsPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderSettingsPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderSettingsPath', () => { - const result = client.folderSettingsPath("folderValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderSettingsPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderSettingsName', () => { - const result = client.matchFolderFromFolderSettingsName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderSettingsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('folderSettings', async () => { + const fakePath = '/rendered/path/folderSettings'; + const expectedParameters = { + folder: 'folderValue', + }; + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.folderSettingsPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderSettingsPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderSettingsPath', () => { + const result = client.folderSettingsPath('folderValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.folderSettingsPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderSettingsName', () => { + const result = client.matchFolderFromFolderSettingsName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + (client.pathTemplates.folderSettingsPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('folderSink', async () => { - const fakePath = "/rendered/path/folderSink"; - const expectedParameters = { - folder: "folderValue", - sink: "sinkValue", - }; - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.folderSinkPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderSinkPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderSinkPath', () => { - const result = client.folderSinkPath("folderValue", "sinkValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderSinkPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderSinkName', () => { - const result = client.matchFolderFromFolderSinkName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderSinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchSinkFromFolderSinkName', () => { - const result = client.matchSinkFromFolderSinkName(fakePath); - assert.strictEqual(result, "sinkValue"); - assert((client.pathTemplates.folderSinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('folderSink', async () => { + const fakePath = '/rendered/path/folderSink'; + const expectedParameters = { + folder: 'folderValue', + sink: 'sinkValue', + }; + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.folderSinkPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderSinkPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderSinkPath', () => { + const result = client.folderSinkPath('folderValue', 'sinkValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.folderSinkPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderSinkName', () => { + const result = client.matchFolderFromFolderSinkName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + (client.pathTemplates.folderSinkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchSinkFromFolderSinkName', () => { + const result = client.matchSinkFromFolderSinkName(fakePath); + assert.strictEqual(result, 'sinkValue'); + assert( + (client.pathTemplates.folderSinkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('logMetric', async () => { - const fakePath = "/rendered/path/logMetric"; - const expectedParameters = { - project: "projectValue", - metric: "metricValue", - }; - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.logMetricPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.logMetricPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('logMetricPath', () => { - const result = client.logMetricPath("projectValue", "metricValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.logMetricPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromLogMetricName', () => { - const result = client.matchProjectFromLogMetricName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.logMetricPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchMetricFromLogMetricName', () => { - const result = client.matchMetricFromLogMetricName(fakePath); - assert.strictEqual(result, "metricValue"); - assert((client.pathTemplates.logMetricPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('logMetric', async () => { + const fakePath = '/rendered/path/logMetric'; + const expectedParameters = { + project: 'projectValue', + metric: 'metricValue', + }; + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.logMetricPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.logMetricPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('logMetricPath', () => { + const result = client.logMetricPath('projectValue', 'metricValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.logMetricPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromLogMetricName', () => { + const result = client.matchProjectFromLogMetricName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.logMetricPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchMetricFromLogMetricName', () => { + const result = client.matchMetricFromLogMetricName(fakePath); + assert.strictEqual(result, 'metricValue'); + assert( + (client.pathTemplates.logMetricPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('organizationCmekSettings', async () => { - const fakePath = "/rendered/path/organizationCmekSettings"; - const expectedParameters = { - organization: "organizationValue", - }; - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.organizationCmekSettingsPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationCmekSettingsPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationCmekSettingsPath', () => { - const result = client.organizationCmekSettingsPath("organizationValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationCmekSettingsPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationCmekSettingsName', () => { - const result = client.matchOrganizationFromOrganizationCmekSettingsName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationCmekSettingsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('organizationCmekSettings', async () => { + const fakePath = '/rendered/path/organizationCmekSettings'; + const expectedParameters = { + organization: 'organizationValue', + }; + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.organizationCmekSettingsPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.organizationCmekSettingsPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('organizationCmekSettingsPath', () => { + const result = client.organizationCmekSettingsPath('organizationValue'); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationCmekSettingsPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationCmekSettingsName', () => { + const result = + client.matchOrganizationFromOrganizationCmekSettingsName(fakePath); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationCmekSettingsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('organizationExclusion', async () => { - const fakePath = "/rendered/path/organizationExclusion"; - const expectedParameters = { - organization: "organizationValue", - exclusion: "exclusionValue", - }; - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.organizationExclusionPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationExclusionPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationExclusionPath', () => { - const result = client.organizationExclusionPath("organizationValue", "exclusionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationExclusionPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationExclusionName', () => { - const result = client.matchOrganizationFromOrganizationExclusionName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationExclusionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchExclusionFromOrganizationExclusionName', () => { - const result = client.matchExclusionFromOrganizationExclusionName(fakePath); - assert.strictEqual(result, "exclusionValue"); - assert((client.pathTemplates.organizationExclusionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('organizationExclusion', async () => { + const fakePath = '/rendered/path/organizationExclusion'; + const expectedParameters = { + organization: 'organizationValue', + exclusion: 'exclusionValue', + }; + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.organizationExclusionPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.organizationExclusionPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('organizationExclusionPath', () => { + const result = client.organizationExclusionPath( + 'organizationValue', + 'exclusionValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationExclusionPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationExclusionName', () => { + const result = + client.matchOrganizationFromOrganizationExclusionName(fakePath); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationExclusionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchExclusionFromOrganizationExclusionName', () => { + const result = + client.matchExclusionFromOrganizationExclusionName(fakePath); + assert.strictEqual(result, 'exclusionValue'); + assert( + ( + client.pathTemplates.organizationExclusionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('organizationLocationBucket', async () => { - const fakePath = "/rendered/path/organizationLocationBucket"; - const expectedParameters = { - organization: "organizationValue", - location: "locationValue", - bucket: "bucketValue", - }; - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.organizationLocationBucketPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationLocationBucketPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationLocationBucketPath', () => { - const result = client.organizationLocationBucketPath("organizationValue", "locationValue", "bucketValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationLocationBucketPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationLocationBucketName', () => { - const result = client.matchOrganizationFromOrganizationLocationBucketName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationLocationBucketPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromOrganizationLocationBucketName', () => { - const result = client.matchLocationFromOrganizationLocationBucketName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.organizationLocationBucketPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBucketFromOrganizationLocationBucketName', () => { - const result = client.matchBucketFromOrganizationLocationBucketName(fakePath); - assert.strictEqual(result, "bucketValue"); - assert((client.pathTemplates.organizationLocationBucketPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('organizationLocationBucket', async () => { + const fakePath = '/rendered/path/organizationLocationBucket'; + const expectedParameters = { + organization: 'organizationValue', + location: 'locationValue', + bucket: 'bucketValue', + }; + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.organizationLocationBucketPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.organizationLocationBucketPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('organizationLocationBucketPath', () => { + const result = client.organizationLocationBucketPath( + 'organizationValue', + 'locationValue', + 'bucketValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationLocationBucketPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationLocationBucketName', () => { + const result = + client.matchOrganizationFromOrganizationLocationBucketName(fakePath); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationLocationBucketPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromOrganizationLocationBucketName', () => { + const result = + client.matchLocationFromOrganizationLocationBucketName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + ( + client.pathTemplates.organizationLocationBucketPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBucketFromOrganizationLocationBucketName', () => { + const result = + client.matchBucketFromOrganizationLocationBucketName(fakePath); + assert.strictEqual(result, 'bucketValue'); + assert( + ( + client.pathTemplates.organizationLocationBucketPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('organizationLocationBucketView', async () => { - const fakePath = "/rendered/path/organizationLocationBucketView"; - const expectedParameters = { - organization: "organizationValue", - location: "locationValue", - bucket: "bucketValue", - view: "viewValue", - }; - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.organizationLocationBucketViewPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationLocationBucketViewPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationLocationBucketViewPath', () => { - const result = client.organizationLocationBucketViewPath("organizationValue", "locationValue", "bucketValue", "viewValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationLocationBucketViewPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationLocationBucketViewName', () => { - const result = client.matchOrganizationFromOrganizationLocationBucketViewName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationLocationBucketViewPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromOrganizationLocationBucketViewName', () => { - const result = client.matchLocationFromOrganizationLocationBucketViewName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.organizationLocationBucketViewPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBucketFromOrganizationLocationBucketViewName', () => { - const result = client.matchBucketFromOrganizationLocationBucketViewName(fakePath); - assert.strictEqual(result, "bucketValue"); - assert((client.pathTemplates.organizationLocationBucketViewPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchViewFromOrganizationLocationBucketViewName', () => { - const result = client.matchViewFromOrganizationLocationBucketViewName(fakePath); - assert.strictEqual(result, "viewValue"); - assert((client.pathTemplates.organizationLocationBucketViewPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('organizationLocationBucketView', async () => { + const fakePath = '/rendered/path/organizationLocationBucketView'; + const expectedParameters = { + organization: 'organizationValue', + location: 'locationValue', + bucket: 'bucketValue', + view: 'viewValue', + }; + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.organizationLocationBucketViewPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.organizationLocationBucketViewPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('organizationLocationBucketViewPath', () => { + const result = client.organizationLocationBucketViewPath( + 'organizationValue', + 'locationValue', + 'bucketValue', + 'viewValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationLocationBucketViewPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationLocationBucketViewName', () => { + const result = + client.matchOrganizationFromOrganizationLocationBucketViewName( + fakePath, + ); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationLocationBucketViewPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromOrganizationLocationBucketViewName', () => { + const result = + client.matchLocationFromOrganizationLocationBucketViewName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + ( + client.pathTemplates.organizationLocationBucketViewPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBucketFromOrganizationLocationBucketViewName', () => { + const result = + client.matchBucketFromOrganizationLocationBucketViewName(fakePath); + assert.strictEqual(result, 'bucketValue'); + assert( + ( + client.pathTemplates.organizationLocationBucketViewPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchViewFromOrganizationLocationBucketViewName', () => { + const result = + client.matchViewFromOrganizationLocationBucketViewName(fakePath); + assert.strictEqual(result, 'viewValue'); + assert( + ( + client.pathTemplates.organizationLocationBucketViewPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('organizationLog', async () => { - const fakePath = "/rendered/path/organizationLog"; - const expectedParameters = { - organization: "organizationValue", - log: "logValue", - }; - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.organizationLogPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationLogPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationLogPath', () => { - const result = client.organizationLogPath("organizationValue", "logValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationLogPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationLogName', () => { - const result = client.matchOrganizationFromOrganizationLogName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationLogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLogFromOrganizationLogName', () => { - const result = client.matchLogFromOrganizationLogName(fakePath); - assert.strictEqual(result, "logValue"); - assert((client.pathTemplates.organizationLogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('organizationLog', async () => { + const fakePath = '/rendered/path/organizationLog'; + const expectedParameters = { + organization: 'organizationValue', + log: 'logValue', + }; + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.organizationLogPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.organizationLogPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('organizationLogPath', () => { + const result = client.organizationLogPath( + 'organizationValue', + 'logValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.organizationLogPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationLogName', () => { + const result = + client.matchOrganizationFromOrganizationLogName(fakePath); + assert.strictEqual(result, 'organizationValue'); + assert( + (client.pathTemplates.organizationLogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLogFromOrganizationLogName', () => { + const result = client.matchLogFromOrganizationLogName(fakePath); + assert.strictEqual(result, 'logValue'); + assert( + (client.pathTemplates.organizationLogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('organizationSettings', async () => { - const fakePath = "/rendered/path/organizationSettings"; - const expectedParameters = { - organization: "organizationValue", - }; - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.organizationSettingsPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationSettingsPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationSettingsPath', () => { - const result = client.organizationSettingsPath("organizationValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationSettingsPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationSettingsName', () => { - const result = client.matchOrganizationFromOrganizationSettingsName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationSettingsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('organizationSettings', async () => { + const fakePath = '/rendered/path/organizationSettings'; + const expectedParameters = { + organization: 'organizationValue', + }; + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.organizationSettingsPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.organizationSettingsPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('organizationSettingsPath', () => { + const result = client.organizationSettingsPath('organizationValue'); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationSettingsPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationSettingsName', () => { + const result = + client.matchOrganizationFromOrganizationSettingsName(fakePath); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationSettingsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('organizationSink', async () => { - const fakePath = "/rendered/path/organizationSink"; - const expectedParameters = { - organization: "organizationValue", - sink: "sinkValue", - }; - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.organizationSinkPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationSinkPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationSinkPath', () => { - const result = client.organizationSinkPath("organizationValue", "sinkValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationSinkPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationSinkName', () => { - const result = client.matchOrganizationFromOrganizationSinkName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationSinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchSinkFromOrganizationSinkName', () => { - const result = client.matchSinkFromOrganizationSinkName(fakePath); - assert.strictEqual(result, "sinkValue"); - assert((client.pathTemplates.organizationSinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('organizationSink', async () => { + const fakePath = '/rendered/path/organizationSink'; + const expectedParameters = { + organization: 'organizationValue', + sink: 'sinkValue', + }; + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.organizationSinkPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.organizationSinkPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('organizationSinkPath', () => { + const result = client.organizationSinkPath( + 'organizationValue', + 'sinkValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationSinkPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationSinkName', () => { + const result = + client.matchOrganizationFromOrganizationSinkName(fakePath); + assert.strictEqual(result, 'organizationValue'); + assert( + (client.pathTemplates.organizationSinkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchSinkFromOrganizationSinkName', () => { + const result = client.matchSinkFromOrganizationSinkName(fakePath); + assert.strictEqual(result, 'sinkValue'); + assert( + (client.pathTemplates.organizationSinkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('project', async () => { - const fakePath = "/rendered/path/project"; - const expectedParameters = { - project: "projectValue", - }; - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.projectPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectPath', () => { - const result = client.projectPath("projectValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectName', () => { - const result = client.matchProjectFromProjectName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('project', async () => { + const fakePath = '/rendered/path/project'; + const expectedParameters = { + project: 'projectValue', + }; + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.projectPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectPath', () => { + const result = client.projectPath('projectValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.projectPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectName', () => { + const result = client.matchProjectFromProjectName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.projectPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectCmekSettings', async () => { - const fakePath = "/rendered/path/projectCmekSettings"; - const expectedParameters = { - project: "projectValue", - }; - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.projectCmekSettingsPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectCmekSettingsPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectCmekSettingsPath', () => { - const result = client.projectCmekSettingsPath("projectValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectCmekSettingsPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectCmekSettingsName', () => { - const result = client.matchProjectFromProjectCmekSettingsName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectCmekSettingsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectCmekSettings', async () => { + const fakePath = '/rendered/path/projectCmekSettings'; + const expectedParameters = { + project: 'projectValue', + }; + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.projectCmekSettingsPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectCmekSettingsPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectCmekSettingsPath', () => { + const result = client.projectCmekSettingsPath('projectValue'); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.projectCmekSettingsPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectCmekSettingsName', () => { + const result = client.matchProjectFromProjectCmekSettingsName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.projectCmekSettingsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectExclusion', async () => { - const fakePath = "/rendered/path/projectExclusion"; - const expectedParameters = { - project: "projectValue", - exclusion: "exclusionValue", - }; - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.projectExclusionPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectExclusionPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectExclusionPath', () => { - const result = client.projectExclusionPath("projectValue", "exclusionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectExclusionPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectExclusionName', () => { - const result = client.matchProjectFromProjectExclusionName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectExclusionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchExclusionFromProjectExclusionName', () => { - const result = client.matchExclusionFromProjectExclusionName(fakePath); - assert.strictEqual(result, "exclusionValue"); - assert((client.pathTemplates.projectExclusionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectExclusion', async () => { + const fakePath = '/rendered/path/projectExclusion'; + const expectedParameters = { + project: 'projectValue', + exclusion: 'exclusionValue', + }; + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.projectExclusionPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectExclusionPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectExclusionPath', () => { + const result = client.projectExclusionPath( + 'projectValue', + 'exclusionValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.projectExclusionPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectExclusionName', () => { + const result = client.matchProjectFromProjectExclusionName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.projectExclusionPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchExclusionFromProjectExclusionName', () => { + const result = client.matchExclusionFromProjectExclusionName(fakePath); + assert.strictEqual(result, 'exclusionValue'); + assert( + (client.pathTemplates.projectExclusionPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectLocationBucket', async () => { - const fakePath = "/rendered/path/projectLocationBucket"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - bucket: "bucketValue", - }; - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.projectLocationBucketPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectLocationBucketPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectLocationBucketPath', () => { - const result = client.projectLocationBucketPath("projectValue", "locationValue", "bucketValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectLocationBucketPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectLocationBucketName', () => { - const result = client.matchProjectFromProjectLocationBucketName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectLocationBucketPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromProjectLocationBucketName', () => { - const result = client.matchLocationFromProjectLocationBucketName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.projectLocationBucketPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBucketFromProjectLocationBucketName', () => { - const result = client.matchBucketFromProjectLocationBucketName(fakePath); - assert.strictEqual(result, "bucketValue"); - assert((client.pathTemplates.projectLocationBucketPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectLocationBucket', async () => { + const fakePath = '/rendered/path/projectLocationBucket'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + bucket: 'bucketValue', + }; + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.projectLocationBucketPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectLocationBucketPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectLocationBucketPath', () => { + const result = client.projectLocationBucketPath( + 'projectValue', + 'locationValue', + 'bucketValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.projectLocationBucketPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectLocationBucketName', () => { + const result = + client.matchProjectFromProjectLocationBucketName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.projectLocationBucketPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromProjectLocationBucketName', () => { + const result = + client.matchLocationFromProjectLocationBucketName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + ( + client.pathTemplates.projectLocationBucketPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBucketFromProjectLocationBucketName', () => { + const result = + client.matchBucketFromProjectLocationBucketName(fakePath); + assert.strictEqual(result, 'bucketValue'); + assert( + ( + client.pathTemplates.projectLocationBucketPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectLocationBucketView', async () => { - const fakePath = "/rendered/path/projectLocationBucketView"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - bucket: "bucketValue", - view: "viewValue", - }; - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.projectLocationBucketViewPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectLocationBucketViewPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectLocationBucketViewPath', () => { - const result = client.projectLocationBucketViewPath("projectValue", "locationValue", "bucketValue", "viewValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectLocationBucketViewPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectLocationBucketViewName', () => { - const result = client.matchProjectFromProjectLocationBucketViewName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectLocationBucketViewPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromProjectLocationBucketViewName', () => { - const result = client.matchLocationFromProjectLocationBucketViewName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.projectLocationBucketViewPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBucketFromProjectLocationBucketViewName', () => { - const result = client.matchBucketFromProjectLocationBucketViewName(fakePath); - assert.strictEqual(result, "bucketValue"); - assert((client.pathTemplates.projectLocationBucketViewPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchViewFromProjectLocationBucketViewName', () => { - const result = client.matchViewFromProjectLocationBucketViewName(fakePath); - assert.strictEqual(result, "viewValue"); - assert((client.pathTemplates.projectLocationBucketViewPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectLocationBucketView', async () => { + const fakePath = '/rendered/path/projectLocationBucketView'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + bucket: 'bucketValue', + view: 'viewValue', + }; + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.projectLocationBucketViewPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectLocationBucketViewPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectLocationBucketViewPath', () => { + const result = client.projectLocationBucketViewPath( + 'projectValue', + 'locationValue', + 'bucketValue', + 'viewValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.projectLocationBucketViewPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectLocationBucketViewName', () => { + const result = + client.matchProjectFromProjectLocationBucketViewName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.projectLocationBucketViewPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromProjectLocationBucketViewName', () => { + const result = + client.matchLocationFromProjectLocationBucketViewName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + ( + client.pathTemplates.projectLocationBucketViewPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBucketFromProjectLocationBucketViewName', () => { + const result = + client.matchBucketFromProjectLocationBucketViewName(fakePath); + assert.strictEqual(result, 'bucketValue'); + assert( + ( + client.pathTemplates.projectLocationBucketViewPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchViewFromProjectLocationBucketViewName', () => { + const result = + client.matchViewFromProjectLocationBucketViewName(fakePath); + assert.strictEqual(result, 'viewValue'); + assert( + ( + client.pathTemplates.projectLocationBucketViewPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectLog', async () => { - const fakePath = "/rendered/path/projectLog"; - const expectedParameters = { - project: "projectValue", - log: "logValue", - }; - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.projectLogPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectLogPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectLogPath', () => { - const result = client.projectLogPath("projectValue", "logValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectLogPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectLogName', () => { - const result = client.matchProjectFromProjectLogName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectLogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLogFromProjectLogName', () => { - const result = client.matchLogFromProjectLogName(fakePath); - assert.strictEqual(result, "logValue"); - assert((client.pathTemplates.projectLogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectLog', async () => { + const fakePath = '/rendered/path/projectLog'; + const expectedParameters = { + project: 'projectValue', + log: 'logValue', + }; + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.projectLogPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectLogPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectLogPath', () => { + const result = client.projectLogPath('projectValue', 'logValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.projectLogPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectLogName', () => { + const result = client.matchProjectFromProjectLogName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.projectLogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLogFromProjectLogName', () => { + const result = client.matchLogFromProjectLogName(fakePath); + assert.strictEqual(result, 'logValue'); + assert( + (client.pathTemplates.projectLogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectSettings', async () => { - const fakePath = "/rendered/path/projectSettings"; - const expectedParameters = { - project: "projectValue", - }; - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.projectSettingsPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectSettingsPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectSettingsPath', () => { - const result = client.projectSettingsPath("projectValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectSettingsPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectSettingsName', () => { - const result = client.matchProjectFromProjectSettingsName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectSettingsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectSettings', async () => { + const fakePath = '/rendered/path/projectSettings'; + const expectedParameters = { + project: 'projectValue', + }; + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.projectSettingsPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectSettingsPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectSettingsPath', () => { + const result = client.projectSettingsPath('projectValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.projectSettingsPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectSettingsName', () => { + const result = client.matchProjectFromProjectSettingsName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.projectSettingsPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectSink', async () => { - const fakePath = "/rendered/path/projectSink"; - const expectedParameters = { - project: "projectValue", - sink: "sinkValue", - }; - const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.projectSinkPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectSinkPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectSinkPath', () => { - const result = client.projectSinkPath("projectValue", "sinkValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectSinkPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectSinkName', () => { - const result = client.matchProjectFromProjectSinkName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectSinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchSinkFromProjectSinkName', () => { - const result = client.matchSinkFromProjectSinkName(fakePath); - assert.strictEqual(result, "sinkValue"); - assert((client.pathTemplates.projectSinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectSink', async () => { + const fakePath = '/rendered/path/projectSink'; + const expectedParameters = { + project: 'projectValue', + sink: 'sinkValue', + }; + const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.projectSinkPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectSinkPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectSinkPath', () => { + const result = client.projectSinkPath('projectValue', 'sinkValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.projectSinkPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectSinkName', () => { + const result = client.matchProjectFromProjectSinkName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.projectSinkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchSinkFromProjectSinkName', () => { + const result = client.matchSinkFromProjectSinkName(fakePath); + assert.strictEqual(result, 'sinkValue'); + assert( + (client.pathTemplates.projectSinkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/core/generator/gapic-generator-typescript/baselines/monitoring-esm/esm/src/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/monitoring-esm/esm/src/index.ts.baseline index c72b2783391b..2e008cbf4823 100644 --- a/core/generator/gapic-generator-typescript/baselines/monitoring-esm/esm/src/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/monitoring-esm/esm/src/index.ts.baseline @@ -29,8 +29,24 @@ const ServiceMonitoringServiceClient = v3.ServiceMonitoringServiceClient; type ServiceMonitoringServiceClient = v3.ServiceMonitoringServiceClient; const UptimeCheckServiceClient = v3.UptimeCheckServiceClient; type UptimeCheckServiceClient = v3.UptimeCheckServiceClient; -export {v3, AlertPolicyServiceClient, GroupServiceClient, MetricServiceClient, NotificationChannelServiceClient, ServiceMonitoringServiceClient, UptimeCheckServiceClient}; -export default {v3, AlertPolicyServiceClient, GroupServiceClient, MetricServiceClient, NotificationChannelServiceClient, ServiceMonitoringServiceClient, UptimeCheckServiceClient}; +export { + v3, + AlertPolicyServiceClient, + GroupServiceClient, + MetricServiceClient, + NotificationChannelServiceClient, + ServiceMonitoringServiceClient, + UptimeCheckServiceClient, +}; +export default { + v3, + AlertPolicyServiceClient, + GroupServiceClient, + MetricServiceClient, + NotificationChannelServiceClient, + ServiceMonitoringServiceClient, + UptimeCheckServiceClient, +}; // @ts-ignore import * as protos from '../../protos/protos.js'; -export {protos} +export { protos }; diff --git a/core/generator/gapic-generator-typescript/baselines/monitoring-esm/esm/src/v3/alert_policy_service_client.ts.baseline b/core/generator/gapic-generator-typescript/baselines/monitoring-esm/esm/src/v3/alert_policy_service_client.ts.baseline index ef8c6adb0934..3272ac5cdfe5 100644 --- a/core/generator/gapic-generator-typescript/baselines/monitoring-esm/esm/src/v3/alert_policy_service_client.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/monitoring-esm/esm/src/v3/alert_policy_service_client.ts.baseline @@ -18,15 +18,22 @@ /* global window */ import * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions, PaginationCallback, GaxCall} from 'google-gax'; -import {Transform} from 'stream'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + PaginationCallback, + GaxCall, +} from 'google-gax'; +import { Transform } from 'stream'; // @ts-ignore import type * as protos from '../../../protos/protos.js'; import * as alert_policy_service_client_config from './alert_policy_service_client_config.json'; import fs from 'fs'; import path from 'path'; -import {fileURLToPath} from 'url'; -import {getJSON} from '../json-helper.cjs'; +import { fileURLToPath } from 'url'; +import { getJSON } from '../json-helper.cjs'; // @ts-ignore const dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -36,15 +43,15 @@ const dirname = path.dirname(fileURLToPath(import.meta.url)); * This file defines retry strategy and timeouts for all API methods in this library. */ const gapicConfig = getJSON( - path.join(dirname, 'alert_policy_service_client_config.json') + path.join(dirname, 'alert_policy_service_client_config.json'), ); const jsonProtos = getJSON( - path.join(dirname, '..', '..', '..', 'protos/protos.json') + path.join(dirname, '..', '..', '..', 'protos/protos.json'), ); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; const version = getJSON( - path.join(dirname, '..', '..', '..', '..', 'package.json') + path.join(dirname, '..', '..', '..', '..', 'package.json'), ).version; /** @@ -67,7 +74,7 @@ export class AlertPolicyServiceClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('monitoring'); @@ -79,9 +86,9 @@ export class AlertPolicyServiceClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; - alertPolicyServiceStub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; + alertPolicyServiceStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of AlertPolicyServiceClient. @@ -123,21 +130,42 @@ export class AlertPolicyServiceClient { * const client = new AlertPolicyServiceClient({fallback: 'rest'}, gax); * ``` */ - constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { // Ensure that options include all the required fields. const staticMembers = this.constructor as typeof AlertPolicyServiceClient; - if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { - throw new Error('Please set either universe_domain or universeDomain, but not both.'); + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); } - const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; - this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; this._servicePath = 'monitoring.' + this._universeDomain; - const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; - const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. if (servicePath !== this._servicePath && !('scopes' in opts)) { @@ -159,7 +187,7 @@ export class AlertPolicyServiceClient { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; @@ -176,10 +204,7 @@ export class AlertPolicyServiceClient { const isEsm = true; const isEsmString = isEsm ? '-esm' : '-cjs'; // Determine the client header string. - const clientHeader = [ - `gax/${this._gaxModule.version}`, - `gapic/${version}`, - ]; + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/{process.versions.node}${isEsmString}`); } else { @@ -187,7 +212,7 @@ export class AlertPolicyServiceClient { } if (!opts.fallback) { clientHeader.push(`grpc/${this._gaxGrpc.grpcVersion}`); - } else if (opts.fallback === 'rest' ) { + } else if (opts.fallback === 'rest') { clientHeader.push(`rest/${this._gaxGrpc.grpcVersion}`); } if (opts.libName && opts.libVersion) { @@ -195,83 +220,92 @@ export class AlertPolicyServiceClient { } // Load the applicable protos. - this._protos = this._gaxGrpc.loadProtoJSON(jsonProtos as gax.protobuf.INamespace); + this._protos = this._gaxGrpc.loadProtoJSON( + jsonProtos as gax.protobuf.INamespace, + ); // This API contains "path templates"; forward-slash-separated // identifiers to uniquely identify resources within the API. // Create useful helper objects for these. this.pathTemplates = { folderAlertPolicyPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/alertPolicies/{alert_policy}' + 'folders/{folder}/alertPolicies/{alert_policy}', ), folderAlertPolicyConditionPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/alertPolicies/{alert_policy}/conditions/{condition}' + 'folders/{folder}/alertPolicies/{alert_policy}/conditions/{condition}', ), folderChannelDescriptorPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/notificationChannelDescriptors/{channel_descriptor}' + 'folders/{folder}/notificationChannelDescriptors/{channel_descriptor}', ), folderGroupPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/groups/{group}' + 'folders/{folder}/groups/{group}', ), folderNotificationChannelPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/notificationChannels/{notification_channel}' + 'folders/{folder}/notificationChannels/{notification_channel}', ), folderServicePathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/services/{service}' - ), - folderServiceServiceLevelObjectivePathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/services/{service}/serviceLevelObjectives/{service_level_objective}' + 'folders/{folder}/services/{service}', ), + folderServiceServiceLevelObjectivePathTemplate: + new this._gaxModule.PathTemplate( + 'folders/{folder}/services/{service}/serviceLevelObjectives/{service_level_objective}', + ), folderUptimeCheckConfigPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/uptimeCheckConfigs/{uptime_check_config}' + 'folders/{folder}/uptimeCheckConfigs/{uptime_check_config}', ), organizationAlertPolicyPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/alertPolicies/{alert_policy}' - ), - organizationAlertPolicyConditionPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/alertPolicies/{alert_policy}/conditions/{condition}' - ), - organizationChannelDescriptorPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/notificationChannelDescriptors/{channel_descriptor}' + 'organizations/{organization}/alertPolicies/{alert_policy}', ), + organizationAlertPolicyConditionPathTemplate: + new this._gaxModule.PathTemplate( + 'organizations/{organization}/alertPolicies/{alert_policy}/conditions/{condition}', + ), + organizationChannelDescriptorPathTemplate: + new this._gaxModule.PathTemplate( + 'organizations/{organization}/notificationChannelDescriptors/{channel_descriptor}', + ), organizationGroupPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/groups/{group}' - ), - organizationNotificationChannelPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/notificationChannels/{notification_channel}' + 'organizations/{organization}/groups/{group}', ), + organizationNotificationChannelPathTemplate: + new this._gaxModule.PathTemplate( + 'organizations/{organization}/notificationChannels/{notification_channel}', + ), organizationServicePathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/services/{service}' - ), - organizationServiceServiceLevelObjectivePathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/services/{service}/serviceLevelObjectives/{service_level_objective}' - ), - organizationUptimeCheckConfigPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/uptimeCheckConfigs/{uptime_check_config}' + 'organizations/{organization}/services/{service}', ), + organizationServiceServiceLevelObjectivePathTemplate: + new this._gaxModule.PathTemplate( + 'organizations/{organization}/services/{service}/serviceLevelObjectives/{service_level_objective}', + ), + organizationUptimeCheckConfigPathTemplate: + new this._gaxModule.PathTemplate( + 'organizations/{organization}/uptimeCheckConfigs/{uptime_check_config}', + ), projectAlertPolicyPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/alertPolicies/{alert_policy}' + 'projects/{project}/alertPolicies/{alert_policy}', ), projectAlertPolicyConditionPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/alertPolicies/{alert_policy}/conditions/{condition}' + 'projects/{project}/alertPolicies/{alert_policy}/conditions/{condition}', ), projectChannelDescriptorPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/notificationChannelDescriptors/{channel_descriptor}' + 'projects/{project}/notificationChannelDescriptors/{channel_descriptor}', ), projectGroupPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/groups/{group}' + 'projects/{project}/groups/{group}', ), projectNotificationChannelPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/notificationChannels/{notification_channel}' + 'projects/{project}/notificationChannels/{notification_channel}', ), projectServicePathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/services/{service}' - ), - projectServiceServiceLevelObjectivePathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/services/{service}/serviceLevelObjectives/{service_level_objective}' + 'projects/{project}/services/{service}', ), + projectServiceServiceLevelObjectivePathTemplate: + new this._gaxModule.PathTemplate( + 'projects/{project}/services/{service}/serviceLevelObjectives/{service_level_objective}', + ), projectUptimeCheckConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/uptimeCheckConfigs/{uptime_check_config}' + 'projects/{project}/uptimeCheckConfigs/{uptime_check_config}', ), }; @@ -279,14 +313,20 @@ export class AlertPolicyServiceClient { // (e.g. 50 results at a time, with tokens to get subsequent // pages). Denote the keys used for pagination and results. this.descriptors.page = { - listAlertPolicies: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'alertPolicies') + listAlertPolicies: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'alertPolicies', + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.monitoring.v3.AlertPolicyService', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.monitoring.v3.AlertPolicyService', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + { 'x-goog-api-client': clientHeader.join(' ') }, + ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -317,37 +357,46 @@ export class AlertPolicyServiceClient { // Put together the "service stub" for // google.monitoring.v3.AlertPolicyService. this.alertPolicyServiceStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.monitoring.v3.AlertPolicyService') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.monitoring.v3.AlertPolicyService', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.monitoring.v3.AlertPolicyService, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts, + this._providedCustomServicePath, + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const alertPolicyServiceStubMethods = - ['listAlertPolicies', 'getAlertPolicy', 'createAlertPolicy', 'deleteAlertPolicy', 'updateAlertPolicy']; + const alertPolicyServiceStubMethods = [ + 'listAlertPolicies', + 'getAlertPolicy', + 'createAlertPolicy', + 'deleteAlertPolicy', + 'updateAlertPolicy', + ]; for (const methodName of alertPolicyServiceStubMethods) { const callPromise = this.alertPolicyServiceStub.then( - stub => (...args: Array<{}>) => { - if (this._terminated) { - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error|null|undefined) => () => { + (stub) => + (...args: Array<{}>) => { + if (this._terminated) { + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { throw err; - }); + }, + ); - const descriptor = - this.descriptors.page[methodName] || - undefined; + const descriptor = this.descriptors.page[methodName] || undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -362,8 +411,14 @@ export class AlertPolicyServiceClient { * @returns {string} The DNS address for this service. */ static get servicePath() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'monitoring.googleapis.com'; } @@ -375,8 +430,14 @@ export class AlertPolicyServiceClient { * @returns {string} The DNS address for this service. */ static get apiEndpoint() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'monitoring.googleapis.com'; } @@ -410,7 +471,7 @@ export class AlertPolicyServiceClient { return [ 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/monitoring', - 'https://www.googleapis.com/auth/monitoring.read' + 'https://www.googleapis.com/auth/monitoring.read', ]; } @@ -420,8 +481,9 @@ export class AlertPolicyServiceClient { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId(callback?: Callback): - Promise|void { + getProjectId( + callback?: Callback, + ): Promise | void { if (callback) { this.auth.getProjectId(callback); return; @@ -432,528 +494,683 @@ export class AlertPolicyServiceClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Gets a single alerting policy. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The alerting policy to retrieve. The format is - * - * projects/[PROJECT_ID]/alertPolicies/[ALERT_POLICY_ID] - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.monitoring.v3.AlertPolicy|AlertPolicy}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v3/alert_policy_service.get_alert_policy.js - * region_tag:monitoring_v3_generated_AlertPolicyService_GetAlertPolicy_async - */ + /** + * Gets a single alerting policy. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The alerting policy to retrieve. The format is + * + * projects/[PROJECT_ID]/alertPolicies/[ALERT_POLICY_ID] + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.monitoring.v3.AlertPolicy|AlertPolicy}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v3/alert_policy_service.get_alert_policy.js + * region_tag:monitoring_v3_generated_AlertPolicyService_GetAlertPolicy_async + */ getAlertPolicy( - request?: protos.google.monitoring.v3.IGetAlertPolicyRequest, - options?: CallOptions): - Promise<[ - protos.google.monitoring.v3.IAlertPolicy, - protos.google.monitoring.v3.IGetAlertPolicyRequest|undefined, {}|undefined - ]>; + request?: protos.google.monitoring.v3.IGetAlertPolicyRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.monitoring.v3.IAlertPolicy, + protos.google.monitoring.v3.IGetAlertPolicyRequest | undefined, + {} | undefined, + ] + >; getAlertPolicy( - request: protos.google.monitoring.v3.IGetAlertPolicyRequest, - options: CallOptions, - callback: Callback< - protos.google.monitoring.v3.IAlertPolicy, - protos.google.monitoring.v3.IGetAlertPolicyRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.IGetAlertPolicyRequest, + options: CallOptions, + callback: Callback< + protos.google.monitoring.v3.IAlertPolicy, + protos.google.monitoring.v3.IGetAlertPolicyRequest | null | undefined, + {} | null | undefined + >, + ): void; getAlertPolicy( - request: protos.google.monitoring.v3.IGetAlertPolicyRequest, - callback: Callback< - protos.google.monitoring.v3.IAlertPolicy, - protos.google.monitoring.v3.IGetAlertPolicyRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.IGetAlertPolicyRequest, + callback: Callback< + protos.google.monitoring.v3.IAlertPolicy, + protos.google.monitoring.v3.IGetAlertPolicyRequest | null | undefined, + {} | null | undefined + >, + ): void; getAlertPolicy( - request?: protos.google.monitoring.v3.IGetAlertPolicyRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.monitoring.v3.IAlertPolicy, - protos.google.monitoring.v3.IGetAlertPolicyRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.monitoring.v3.IGetAlertPolicyRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.monitoring.v3.IAlertPolicy, - protos.google.monitoring.v3.IGetAlertPolicyRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.monitoring.v3.IAlertPolicy, - protos.google.monitoring.v3.IGetAlertPolicyRequest|undefined, {}|undefined - ]>|void { + protos.google.monitoring.v3.IGetAlertPolicyRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.monitoring.v3.IAlertPolicy, + protos.google.monitoring.v3.IGetAlertPolicyRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.monitoring.v3.IAlertPolicy, + protos.google.monitoring.v3.IGetAlertPolicyRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getAlertPolicy request %j', request); - const wrappedCallback: Callback< - protos.google.monitoring.v3.IAlertPolicy, - protos.google.monitoring.v3.IGetAlertPolicyRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.monitoring.v3.IAlertPolicy, + protos.google.monitoring.v3.IGetAlertPolicyRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getAlertPolicy response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.getAlertPolicy(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.monitoring.v3.IAlertPolicy, - protos.google.monitoring.v3.IGetAlertPolicyRequest|undefined, {}|undefined - ]) => { - this._log.info('getAlertPolicy response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getAlertPolicy(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.monitoring.v3.IAlertPolicy, + protos.google.monitoring.v3.IGetAlertPolicyRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getAlertPolicy response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Creates a new alerting policy. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The project in which to create the alerting policy. The format is - * `projects/[PROJECT_ID]`. - * - * Note that this field names the parent container in which the alerting - * policy will be written, not the name of the created policy. The alerting - * policy that is returned will have a name that contains a normalized - * representation of this name as a prefix but adds a suffix of the form - * `/alertPolicies/[POLICY_ID]`, identifying the policy in the container. - * @param {google.monitoring.v3.AlertPolicy} request.alertPolicy - * Required. The requested alerting policy. You should omit the `name` field in this - * policy. The name will be returned in the new policy, including - * a new [ALERT_POLICY_ID] value. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.monitoring.v3.AlertPolicy|AlertPolicy}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v3/alert_policy_service.create_alert_policy.js - * region_tag:monitoring_v3_generated_AlertPolicyService_CreateAlertPolicy_async - */ + /** + * Creates a new alerting policy. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The project in which to create the alerting policy. The format is + * `projects/[PROJECT_ID]`. + * + * Note that this field names the parent container in which the alerting + * policy will be written, not the name of the created policy. The alerting + * policy that is returned will have a name that contains a normalized + * representation of this name as a prefix but adds a suffix of the form + * `/alertPolicies/[POLICY_ID]`, identifying the policy in the container. + * @param {google.monitoring.v3.AlertPolicy} request.alertPolicy + * Required. The requested alerting policy. You should omit the `name` field in this + * policy. The name will be returned in the new policy, including + * a new [ALERT_POLICY_ID] value. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.monitoring.v3.AlertPolicy|AlertPolicy}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v3/alert_policy_service.create_alert_policy.js + * region_tag:monitoring_v3_generated_AlertPolicyService_CreateAlertPolicy_async + */ createAlertPolicy( - request?: protos.google.monitoring.v3.ICreateAlertPolicyRequest, - options?: CallOptions): - Promise<[ - protos.google.monitoring.v3.IAlertPolicy, - protos.google.monitoring.v3.ICreateAlertPolicyRequest|undefined, {}|undefined - ]>; + request?: protos.google.monitoring.v3.ICreateAlertPolicyRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.monitoring.v3.IAlertPolicy, + protos.google.monitoring.v3.ICreateAlertPolicyRequest | undefined, + {} | undefined, + ] + >; createAlertPolicy( - request: protos.google.monitoring.v3.ICreateAlertPolicyRequest, - options: CallOptions, - callback: Callback< - protos.google.monitoring.v3.IAlertPolicy, - protos.google.monitoring.v3.ICreateAlertPolicyRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.ICreateAlertPolicyRequest, + options: CallOptions, + callback: Callback< + protos.google.monitoring.v3.IAlertPolicy, + protos.google.monitoring.v3.ICreateAlertPolicyRequest | null | undefined, + {} | null | undefined + >, + ): void; createAlertPolicy( - request: protos.google.monitoring.v3.ICreateAlertPolicyRequest, - callback: Callback< - protos.google.monitoring.v3.IAlertPolicy, - protos.google.monitoring.v3.ICreateAlertPolicyRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.ICreateAlertPolicyRequest, + callback: Callback< + protos.google.monitoring.v3.IAlertPolicy, + protos.google.monitoring.v3.ICreateAlertPolicyRequest | null | undefined, + {} | null | undefined + >, + ): void; createAlertPolicy( - request?: protos.google.monitoring.v3.ICreateAlertPolicyRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.monitoring.v3.IAlertPolicy, - protos.google.monitoring.v3.ICreateAlertPolicyRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.monitoring.v3.ICreateAlertPolicyRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.monitoring.v3.IAlertPolicy, - protos.google.monitoring.v3.ICreateAlertPolicyRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.monitoring.v3.IAlertPolicy, - protos.google.monitoring.v3.ICreateAlertPolicyRequest|undefined, {}|undefined - ]>|void { + | protos.google.monitoring.v3.ICreateAlertPolicyRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.monitoring.v3.IAlertPolicy, + protos.google.monitoring.v3.ICreateAlertPolicyRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.monitoring.v3.IAlertPolicy, + protos.google.monitoring.v3.ICreateAlertPolicyRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('createAlertPolicy request %j', request); - const wrappedCallback: Callback< - protos.google.monitoring.v3.IAlertPolicy, - protos.google.monitoring.v3.ICreateAlertPolicyRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.monitoring.v3.IAlertPolicy, + | protos.google.monitoring.v3.ICreateAlertPolicyRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createAlertPolicy response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.createAlertPolicy(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.monitoring.v3.IAlertPolicy, - protos.google.monitoring.v3.ICreateAlertPolicyRequest|undefined, {}|undefined - ]) => { - this._log.info('createAlertPolicy response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createAlertPolicy(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.monitoring.v3.IAlertPolicy, + protos.google.monitoring.v3.ICreateAlertPolicyRequest | undefined, + {} | undefined, + ]) => { + this._log.info('createAlertPolicy response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Deletes an alerting policy. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The alerting policy to delete. The format is: - * - * projects/[PROJECT_ID]/alertPolicies/[ALERT_POLICY_ID] - * - * For more information, see {@link protos.google.monitoring.v3.AlertPolicy|AlertPolicy}. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v3/alert_policy_service.delete_alert_policy.js - * region_tag:monitoring_v3_generated_AlertPolicyService_DeleteAlertPolicy_async - */ + /** + * Deletes an alerting policy. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The alerting policy to delete. The format is: + * + * projects/[PROJECT_ID]/alertPolicies/[ALERT_POLICY_ID] + * + * For more information, see {@link protos.google.monitoring.v3.AlertPolicy|AlertPolicy}. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v3/alert_policy_service.delete_alert_policy.js + * region_tag:monitoring_v3_generated_AlertPolicyService_DeleteAlertPolicy_async + */ deleteAlertPolicy( - request?: protos.google.monitoring.v3.IDeleteAlertPolicyRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.IDeleteAlertPolicyRequest|undefined, {}|undefined - ]>; + request?: protos.google.monitoring.v3.IDeleteAlertPolicyRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.monitoring.v3.IDeleteAlertPolicyRequest | undefined, + {} | undefined, + ] + >; deleteAlertPolicy( - request: protos.google.monitoring.v3.IDeleteAlertPolicyRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.IDeleteAlertPolicyRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.IDeleteAlertPolicyRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.monitoring.v3.IDeleteAlertPolicyRequest | null | undefined, + {} | null | undefined + >, + ): void; deleteAlertPolicy( - request: protos.google.monitoring.v3.IDeleteAlertPolicyRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.IDeleteAlertPolicyRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.IDeleteAlertPolicyRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.monitoring.v3.IDeleteAlertPolicyRequest | null | undefined, + {} | null | undefined + >, + ): void; deleteAlertPolicy( - request?: protos.google.monitoring.v3.IDeleteAlertPolicyRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.monitoring.v3.IDeleteAlertPolicyRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.IDeleteAlertPolicyRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.IDeleteAlertPolicyRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.IDeleteAlertPolicyRequest|undefined, {}|undefined - ]>|void { + | protos.google.monitoring.v3.IDeleteAlertPolicyRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + protos.google.monitoring.v3.IDeleteAlertPolicyRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.monitoring.v3.IDeleteAlertPolicyRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('deleteAlertPolicy request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.IDeleteAlertPolicyRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.monitoring.v3.IDeleteAlertPolicyRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteAlertPolicy response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.deleteAlertPolicy(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.IDeleteAlertPolicyRequest|undefined, {}|undefined - ]) => { - this._log.info('deleteAlertPolicy response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteAlertPolicy(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.monitoring.v3.IDeleteAlertPolicyRequest | undefined, + {} | undefined, + ]) => { + this._log.info('deleteAlertPolicy response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Updates an alerting policy. You can either replace the entire policy with - * a new one or replace only certain fields in the current alerting policy by - * specifying the fields to be updated via `updateMask`. Returns the - * updated alerting policy. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.protobuf.FieldMask} request.updateMask - * Optional. A list of alerting policy field names. If this field is not - * empty, each listed field in the existing alerting policy is set to the - * value of the corresponding field in the supplied policy (`alert_policy`), - * or to the field's default value if the field is not in the supplied - * alerting policy. Fields not listed retain their previous value. - * - * Examples of valid field masks include `display_name`, `documentation`, - * `documentation.content`, `documentation.mime_type`, `user_labels`, - * `user_label.nameofkey`, `enabled`, `conditions`, `combiner`, etc. - * - * If this field is empty, then the supplied alerting policy replaces the - * existing policy. It is the same as deleting the existing policy and - * adding the supplied policy, except for the following: - * - * + The new policy will have the same `[ALERT_POLICY_ID]` as the former - * policy. This gives you continuity with the former policy in your - * notifications and incidents. - * + Conditions in the new policy will keep their former `[CONDITION_ID]` if - * the supplied condition includes the `name` field with that - * `[CONDITION_ID]`. If the supplied condition omits the `name` field, - * then a new `[CONDITION_ID]` is created. - * @param {google.monitoring.v3.AlertPolicy} request.alertPolicy - * Required. The updated alerting policy or the updated values for the - * fields listed in `update_mask`. - * If `update_mask` is not empty, any fields in this policy that are - * not in `update_mask` are ignored. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.monitoring.v3.AlertPolicy|AlertPolicy}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v3/alert_policy_service.update_alert_policy.js - * region_tag:monitoring_v3_generated_AlertPolicyService_UpdateAlertPolicy_async - */ + /** + * Updates an alerting policy. You can either replace the entire policy with + * a new one or replace only certain fields in the current alerting policy by + * specifying the fields to be updated via `updateMask`. Returns the + * updated alerting policy. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.protobuf.FieldMask} request.updateMask + * Optional. A list of alerting policy field names. If this field is not + * empty, each listed field in the existing alerting policy is set to the + * value of the corresponding field in the supplied policy (`alert_policy`), + * or to the field's default value if the field is not in the supplied + * alerting policy. Fields not listed retain their previous value. + * + * Examples of valid field masks include `display_name`, `documentation`, + * `documentation.content`, `documentation.mime_type`, `user_labels`, + * `user_label.nameofkey`, `enabled`, `conditions`, `combiner`, etc. + * + * If this field is empty, then the supplied alerting policy replaces the + * existing policy. It is the same as deleting the existing policy and + * adding the supplied policy, except for the following: + * + * + The new policy will have the same `[ALERT_POLICY_ID]` as the former + * policy. This gives you continuity with the former policy in your + * notifications and incidents. + * + Conditions in the new policy will keep their former `[CONDITION_ID]` if + * the supplied condition includes the `name` field with that + * `[CONDITION_ID]`. If the supplied condition omits the `name` field, + * then a new `[CONDITION_ID]` is created. + * @param {google.monitoring.v3.AlertPolicy} request.alertPolicy + * Required. The updated alerting policy or the updated values for the + * fields listed in `update_mask`. + * If `update_mask` is not empty, any fields in this policy that are + * not in `update_mask` are ignored. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.monitoring.v3.AlertPolicy|AlertPolicy}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v3/alert_policy_service.update_alert_policy.js + * region_tag:monitoring_v3_generated_AlertPolicyService_UpdateAlertPolicy_async + */ updateAlertPolicy( - request?: protos.google.monitoring.v3.IUpdateAlertPolicyRequest, - options?: CallOptions): - Promise<[ - protos.google.monitoring.v3.IAlertPolicy, - protos.google.monitoring.v3.IUpdateAlertPolicyRequest|undefined, {}|undefined - ]>; + request?: protos.google.monitoring.v3.IUpdateAlertPolicyRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.monitoring.v3.IAlertPolicy, + protos.google.monitoring.v3.IUpdateAlertPolicyRequest | undefined, + {} | undefined, + ] + >; updateAlertPolicy( - request: protos.google.monitoring.v3.IUpdateAlertPolicyRequest, - options: CallOptions, - callback: Callback< - protos.google.monitoring.v3.IAlertPolicy, - protos.google.monitoring.v3.IUpdateAlertPolicyRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.IUpdateAlertPolicyRequest, + options: CallOptions, + callback: Callback< + protos.google.monitoring.v3.IAlertPolicy, + protos.google.monitoring.v3.IUpdateAlertPolicyRequest | null | undefined, + {} | null | undefined + >, + ): void; updateAlertPolicy( - request: protos.google.monitoring.v3.IUpdateAlertPolicyRequest, - callback: Callback< - protos.google.monitoring.v3.IAlertPolicy, - protos.google.monitoring.v3.IUpdateAlertPolicyRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.IUpdateAlertPolicyRequest, + callback: Callback< + protos.google.monitoring.v3.IAlertPolicy, + protos.google.monitoring.v3.IUpdateAlertPolicyRequest | null | undefined, + {} | null | undefined + >, + ): void; updateAlertPolicy( - request?: protos.google.monitoring.v3.IUpdateAlertPolicyRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.monitoring.v3.IUpdateAlertPolicyRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.monitoring.v3.IAlertPolicy, - protos.google.monitoring.v3.IUpdateAlertPolicyRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.monitoring.v3.IAlertPolicy, - protos.google.monitoring.v3.IUpdateAlertPolicyRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.monitoring.v3.IAlertPolicy, - protos.google.monitoring.v3.IUpdateAlertPolicyRequest|undefined, {}|undefined - ]>|void { + | protos.google.monitoring.v3.IUpdateAlertPolicyRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.monitoring.v3.IAlertPolicy, + protos.google.monitoring.v3.IUpdateAlertPolicyRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.monitoring.v3.IAlertPolicy, + protos.google.monitoring.v3.IUpdateAlertPolicyRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'alert_policy.name': request.alertPolicy!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'alert_policy.name': request.alertPolicy!.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateAlertPolicy request %j', request); - const wrappedCallback: Callback< - protos.google.monitoring.v3.IAlertPolicy, - protos.google.monitoring.v3.IUpdateAlertPolicyRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.monitoring.v3.IAlertPolicy, + | protos.google.monitoring.v3.IUpdateAlertPolicyRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateAlertPolicy response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.updateAlertPolicy(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.monitoring.v3.IAlertPolicy, - protos.google.monitoring.v3.IUpdateAlertPolicyRequest|undefined, {}|undefined - ]) => { - this._log.info('updateAlertPolicy response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateAlertPolicy(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.monitoring.v3.IAlertPolicy, + protos.google.monitoring.v3.IUpdateAlertPolicyRequest | undefined, + {} | undefined, + ]) => { + this._log.info('updateAlertPolicy response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } - /** - * Lists the existing alerting policies for the project. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The project whose alert policies are to be listed. The format is - * - * projects/[PROJECT_ID] - * - * Note that this field names the parent container in which the alerting - * policies to be listed are stored. To retrieve a single alerting policy - * by name, use the - * {@link protos.google.monitoring.v3.AlertPolicyService.GetAlertPolicy|GetAlertPolicy} - * operation, instead. - * @param {string} request.filter - * If provided, this field specifies the criteria that must be met by - * alert policies to be included in the response. - * - * For more details, see [sorting and - * filtering](/monitoring/api/v3/sorting-and-filtering). - * @param {string} request.orderBy - * A comma-separated list of fields by which to sort the result. Supports - * the same set of field references as the `filter` field. Entries can be - * prefixed with a minus sign to sort by the field in descending order. - * - * For more details, see [sorting and - * filtering](/monitoring/api/v3/sorting-and-filtering). - * @param {number} request.pageSize - * The maximum number of results to return in a single response. - * @param {string} request.pageToken - * If this field is not empty then it must contain the `nextPageToken` value - * returned by a previous call to this method. Using this field causes the - * method to return more results from the previous method call. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.monitoring.v3.AlertPolicy|AlertPolicy}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `listAlertPoliciesAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Lists the existing alerting policies for the project. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The project whose alert policies are to be listed. The format is + * + * projects/[PROJECT_ID] + * + * Note that this field names the parent container in which the alerting + * policies to be listed are stored. To retrieve a single alerting policy + * by name, use the + * {@link protos.google.monitoring.v3.AlertPolicyService.GetAlertPolicy|GetAlertPolicy} + * operation, instead. + * @param {string} request.filter + * If provided, this field specifies the criteria that must be met by + * alert policies to be included in the response. + * + * For more details, see [sorting and + * filtering](/monitoring/api/v3/sorting-and-filtering). + * @param {string} request.orderBy + * A comma-separated list of fields by which to sort the result. Supports + * the same set of field references as the `filter` field. Entries can be + * prefixed with a minus sign to sort by the field in descending order. + * + * For more details, see [sorting and + * filtering](/monitoring/api/v3/sorting-and-filtering). + * @param {number} request.pageSize + * The maximum number of results to return in a single response. + * @param {string} request.pageToken + * If this field is not empty then it must contain the `nextPageToken` value + * returned by a previous call to this method. Using this field causes the + * method to return more results from the previous method call. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.monitoring.v3.AlertPolicy|AlertPolicy}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listAlertPoliciesAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listAlertPolicies( - request?: protos.google.monitoring.v3.IListAlertPoliciesRequest, - options?: CallOptions): - Promise<[ - protos.google.monitoring.v3.IAlertPolicy[], - protos.google.monitoring.v3.IListAlertPoliciesRequest|null, - protos.google.monitoring.v3.IListAlertPoliciesResponse - ]>; + request?: protos.google.monitoring.v3.IListAlertPoliciesRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.monitoring.v3.IAlertPolicy[], + protos.google.monitoring.v3.IListAlertPoliciesRequest | null, + protos.google.monitoring.v3.IListAlertPoliciesResponse, + ] + >; listAlertPolicies( - request: protos.google.monitoring.v3.IListAlertPoliciesRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.monitoring.v3.IListAlertPoliciesRequest, - protos.google.monitoring.v3.IListAlertPoliciesResponse|null|undefined, - protos.google.monitoring.v3.IAlertPolicy>): void; + request: protos.google.monitoring.v3.IListAlertPoliciesRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.monitoring.v3.IListAlertPoliciesRequest, + protos.google.monitoring.v3.IListAlertPoliciesResponse | null | undefined, + protos.google.monitoring.v3.IAlertPolicy + >, + ): void; listAlertPolicies( - request: protos.google.monitoring.v3.IListAlertPoliciesRequest, - callback: PaginationCallback< - protos.google.monitoring.v3.IListAlertPoliciesRequest, - protos.google.monitoring.v3.IListAlertPoliciesResponse|null|undefined, - protos.google.monitoring.v3.IAlertPolicy>): void; + request: protos.google.monitoring.v3.IListAlertPoliciesRequest, + callback: PaginationCallback< + protos.google.monitoring.v3.IListAlertPoliciesRequest, + protos.google.monitoring.v3.IListAlertPoliciesResponse | null | undefined, + protos.google.monitoring.v3.IAlertPolicy + >, + ): void; listAlertPolicies( - request?: protos.google.monitoring.v3.IListAlertPoliciesRequest, - optionsOrCallback?: CallOptions|PaginationCallback< - protos.google.monitoring.v3.IListAlertPoliciesRequest, - protos.google.monitoring.v3.IListAlertPoliciesResponse|null|undefined, - protos.google.monitoring.v3.IAlertPolicy>, - callback?: PaginationCallback< + request?: protos.google.monitoring.v3.IListAlertPoliciesRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.monitoring.v3.IListAlertPoliciesRequest, - protos.google.monitoring.v3.IListAlertPoliciesResponse|null|undefined, - protos.google.monitoring.v3.IAlertPolicy>): - Promise<[ - protos.google.monitoring.v3.IAlertPolicy[], - protos.google.monitoring.v3.IListAlertPoliciesRequest|null, - protos.google.monitoring.v3.IListAlertPoliciesResponse - ]>|void { + | protos.google.monitoring.v3.IListAlertPoliciesResponse + | null + | undefined, + protos.google.monitoring.v3.IAlertPolicy + >, + callback?: PaginationCallback< + protos.google.monitoring.v3.IListAlertPoliciesRequest, + protos.google.monitoring.v3.IListAlertPoliciesResponse | null | undefined, + protos.google.monitoring.v3.IAlertPolicy + >, + ): Promise< + [ + protos.google.monitoring.v3.IAlertPolicy[], + protos.google.monitoring.v3.IListAlertPoliciesRequest | null, + protos.google.monitoring.v3.IListAlertPoliciesResponse, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.monitoring.v3.IListAlertPoliciesRequest, - protos.google.monitoring.v3.IListAlertPoliciesResponse|null|undefined, - protos.google.monitoring.v3.IAlertPolicy>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.monitoring.v3.IListAlertPoliciesRequest, + | protos.google.monitoring.v3.IListAlertPoliciesResponse + | null + | undefined, + protos.google.monitoring.v3.IAlertPolicy + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listAlertPolicies values %j', values); callback!(error, values, nextPageRequest, rawResponse); @@ -962,152 +1179,156 @@ export class AlertPolicyServiceClient { this._log.info('listAlertPolicies request %j', request); return this.innerApiCalls .listAlertPolicies(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.monitoring.v3.IAlertPolicy[], - protos.google.monitoring.v3.IListAlertPoliciesRequest|null, - protos.google.monitoring.v3.IListAlertPoliciesResponse - ]) => { - this._log.info('listAlertPolicies values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.monitoring.v3.IAlertPolicy[], + protos.google.monitoring.v3.IListAlertPoliciesRequest | null, + protos.google.monitoring.v3.IListAlertPoliciesResponse, + ]) => { + this._log.info('listAlertPolicies values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listAlertPolicies`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The project whose alert policies are to be listed. The format is - * - * projects/[PROJECT_ID] - * - * Note that this field names the parent container in which the alerting - * policies to be listed are stored. To retrieve a single alerting policy - * by name, use the - * {@link protos.google.monitoring.v3.AlertPolicyService.GetAlertPolicy|GetAlertPolicy} - * operation, instead. - * @param {string} request.filter - * If provided, this field specifies the criteria that must be met by - * alert policies to be included in the response. - * - * For more details, see [sorting and - * filtering](/monitoring/api/v3/sorting-and-filtering). - * @param {string} request.orderBy - * A comma-separated list of fields by which to sort the result. Supports - * the same set of field references as the `filter` field. Entries can be - * prefixed with a minus sign to sort by the field in descending order. - * - * For more details, see [sorting and - * filtering](/monitoring/api/v3/sorting-and-filtering). - * @param {number} request.pageSize - * The maximum number of results to return in a single response. - * @param {string} request.pageToken - * If this field is not empty then it must contain the `nextPageToken` value - * returned by a previous call to this method. Using this field causes the - * method to return more results from the previous method call. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.monitoring.v3.AlertPolicy|AlertPolicy} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `listAlertPoliciesAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `listAlertPolicies`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The project whose alert policies are to be listed. The format is + * + * projects/[PROJECT_ID] + * + * Note that this field names the parent container in which the alerting + * policies to be listed are stored. To retrieve a single alerting policy + * by name, use the + * {@link protos.google.monitoring.v3.AlertPolicyService.GetAlertPolicy|GetAlertPolicy} + * operation, instead. + * @param {string} request.filter + * If provided, this field specifies the criteria that must be met by + * alert policies to be included in the response. + * + * For more details, see [sorting and + * filtering](/monitoring/api/v3/sorting-and-filtering). + * @param {string} request.orderBy + * A comma-separated list of fields by which to sort the result. Supports + * the same set of field references as the `filter` field. Entries can be + * prefixed with a minus sign to sort by the field in descending order. + * + * For more details, see [sorting and + * filtering](/monitoring/api/v3/sorting-and-filtering). + * @param {number} request.pageSize + * The maximum number of results to return in a single response. + * @param {string} request.pageToken + * If this field is not empty then it must contain the `nextPageToken` value + * returned by a previous call to this method. Using this field causes the + * method to return more results from the previous method call. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.monitoring.v3.AlertPolicy|AlertPolicy} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listAlertPoliciesAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listAlertPoliciesStream( - request?: protos.google.monitoring.v3.IListAlertPoliciesRequest, - options?: CallOptions): - Transform{ + request?: protos.google.monitoring.v3.IListAlertPoliciesRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); const defaultCallSettings = this._defaults['listAlertPolicies']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listAlertPolicies stream %j', request); return this.descriptors.page.listAlertPolicies.createStream( this.innerApiCalls.listAlertPolicies as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listAlertPolicies`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The project whose alert policies are to be listed. The format is - * - * projects/[PROJECT_ID] - * - * Note that this field names the parent container in which the alerting - * policies to be listed are stored. To retrieve a single alerting policy - * by name, use the - * {@link protos.google.monitoring.v3.AlertPolicyService.GetAlertPolicy|GetAlertPolicy} - * operation, instead. - * @param {string} request.filter - * If provided, this field specifies the criteria that must be met by - * alert policies to be included in the response. - * - * For more details, see [sorting and - * filtering](/monitoring/api/v3/sorting-and-filtering). - * @param {string} request.orderBy - * A comma-separated list of fields by which to sort the result. Supports - * the same set of field references as the `filter` field. Entries can be - * prefixed with a minus sign to sort by the field in descending order. - * - * For more details, see [sorting and - * filtering](/monitoring/api/v3/sorting-and-filtering). - * @param {number} request.pageSize - * The maximum number of results to return in a single response. - * @param {string} request.pageToken - * If this field is not empty then it must contain the `nextPageToken` value - * returned by a previous call to this method. Using this field causes the - * method to return more results from the previous method call. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.monitoring.v3.AlertPolicy|AlertPolicy}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v3/alert_policy_service.list_alert_policies.js - * region_tag:monitoring_v3_generated_AlertPolicyService_ListAlertPolicies_async - */ + /** + * Equivalent to `listAlertPolicies`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The project whose alert policies are to be listed. The format is + * + * projects/[PROJECT_ID] + * + * Note that this field names the parent container in which the alerting + * policies to be listed are stored. To retrieve a single alerting policy + * by name, use the + * {@link protos.google.monitoring.v3.AlertPolicyService.GetAlertPolicy|GetAlertPolicy} + * operation, instead. + * @param {string} request.filter + * If provided, this field specifies the criteria that must be met by + * alert policies to be included in the response. + * + * For more details, see [sorting and + * filtering](/monitoring/api/v3/sorting-and-filtering). + * @param {string} request.orderBy + * A comma-separated list of fields by which to sort the result. Supports + * the same set of field references as the `filter` field. Entries can be + * prefixed with a minus sign to sort by the field in descending order. + * + * For more details, see [sorting and + * filtering](/monitoring/api/v3/sorting-and-filtering). + * @param {number} request.pageSize + * The maximum number of results to return in a single response. + * @param {string} request.pageToken + * If this field is not empty then it must contain the `nextPageToken` value + * returned by a previous call to this method. Using this field causes the + * method to return more results from the previous method call. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.monitoring.v3.AlertPolicy|AlertPolicy}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v3/alert_policy_service.list_alert_policies.js + * region_tag:monitoring_v3_generated_AlertPolicyService_ListAlertPolicies_async + */ listAlertPoliciesAsync( - request?: protos.google.monitoring.v3.IListAlertPoliciesRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.monitoring.v3.IListAlertPoliciesRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); const defaultCallSettings = this._defaults['listAlertPolicies']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listAlertPolicies iterate %j', request); return this.descriptors.page.listAlertPolicies.asyncIterate( this.innerApiCalls['listAlertPolicies'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } // -------------------- @@ -1121,7 +1342,7 @@ export class AlertPolicyServiceClient { * @param {string} alert_policy * @returns {string} Resource name string. */ - folderAlertPolicyPath(folder:string,alertPolicy:string) { + folderAlertPolicyPath(folder: string, alertPolicy: string) { return this.pathTemplates.folderAlertPolicyPathTemplate.render({ folder: folder, alert_policy: alertPolicy, @@ -1136,7 +1357,9 @@ export class AlertPolicyServiceClient { * @returns {string} A string representing the folder. */ matchFolderFromFolderAlertPolicyName(folderAlertPolicyName: string) { - return this.pathTemplates.folderAlertPolicyPathTemplate.match(folderAlertPolicyName).folder; + return this.pathTemplates.folderAlertPolicyPathTemplate.match( + folderAlertPolicyName, + ).folder; } /** @@ -1147,7 +1370,9 @@ export class AlertPolicyServiceClient { * @returns {string} A string representing the alert_policy. */ matchAlertPolicyFromFolderAlertPolicyName(folderAlertPolicyName: string) { - return this.pathTemplates.folderAlertPolicyPathTemplate.match(folderAlertPolicyName).alert_policy; + return this.pathTemplates.folderAlertPolicyPathTemplate.match( + folderAlertPolicyName, + ).alert_policy; } /** @@ -1158,7 +1383,11 @@ export class AlertPolicyServiceClient { * @param {string} condition * @returns {string} Resource name string. */ - folderAlertPolicyConditionPath(folder:string,alertPolicy:string,condition:string) { + folderAlertPolicyConditionPath( + folder: string, + alertPolicy: string, + condition: string, + ) { return this.pathTemplates.folderAlertPolicyConditionPathTemplate.render({ folder: folder, alert_policy: alertPolicy, @@ -1173,8 +1402,12 @@ export class AlertPolicyServiceClient { * A fully-qualified path representing folder_alert_policy_condition resource. * @returns {string} A string representing the folder. */ - matchFolderFromFolderAlertPolicyConditionName(folderAlertPolicyConditionName: string) { - return this.pathTemplates.folderAlertPolicyConditionPathTemplate.match(folderAlertPolicyConditionName).folder; + matchFolderFromFolderAlertPolicyConditionName( + folderAlertPolicyConditionName: string, + ) { + return this.pathTemplates.folderAlertPolicyConditionPathTemplate.match( + folderAlertPolicyConditionName, + ).folder; } /** @@ -1184,8 +1417,12 @@ export class AlertPolicyServiceClient { * A fully-qualified path representing folder_alert_policy_condition resource. * @returns {string} A string representing the alert_policy. */ - matchAlertPolicyFromFolderAlertPolicyConditionName(folderAlertPolicyConditionName: string) { - return this.pathTemplates.folderAlertPolicyConditionPathTemplate.match(folderAlertPolicyConditionName).alert_policy; + matchAlertPolicyFromFolderAlertPolicyConditionName( + folderAlertPolicyConditionName: string, + ) { + return this.pathTemplates.folderAlertPolicyConditionPathTemplate.match( + folderAlertPolicyConditionName, + ).alert_policy; } /** @@ -1195,8 +1432,12 @@ export class AlertPolicyServiceClient { * A fully-qualified path representing folder_alert_policy_condition resource. * @returns {string} A string representing the condition. */ - matchConditionFromFolderAlertPolicyConditionName(folderAlertPolicyConditionName: string) { - return this.pathTemplates.folderAlertPolicyConditionPathTemplate.match(folderAlertPolicyConditionName).condition; + matchConditionFromFolderAlertPolicyConditionName( + folderAlertPolicyConditionName: string, + ) { + return this.pathTemplates.folderAlertPolicyConditionPathTemplate.match( + folderAlertPolicyConditionName, + ).condition; } /** @@ -1206,7 +1447,7 @@ export class AlertPolicyServiceClient { * @param {string} channel_descriptor * @returns {string} Resource name string. */ - folderChannelDescriptorPath(folder:string,channelDescriptor:string) { + folderChannelDescriptorPath(folder: string, channelDescriptor: string) { return this.pathTemplates.folderChannelDescriptorPathTemplate.render({ folder: folder, channel_descriptor: channelDescriptor, @@ -1220,8 +1461,12 @@ export class AlertPolicyServiceClient { * A fully-qualified path representing folder_channel_descriptor resource. * @returns {string} A string representing the folder. */ - matchFolderFromFolderChannelDescriptorName(folderChannelDescriptorName: string) { - return this.pathTemplates.folderChannelDescriptorPathTemplate.match(folderChannelDescriptorName).folder; + matchFolderFromFolderChannelDescriptorName( + folderChannelDescriptorName: string, + ) { + return this.pathTemplates.folderChannelDescriptorPathTemplate.match( + folderChannelDescriptorName, + ).folder; } /** @@ -1231,8 +1476,12 @@ export class AlertPolicyServiceClient { * A fully-qualified path representing folder_channel_descriptor resource. * @returns {string} A string representing the channel_descriptor. */ - matchChannelDescriptorFromFolderChannelDescriptorName(folderChannelDescriptorName: string) { - return this.pathTemplates.folderChannelDescriptorPathTemplate.match(folderChannelDescriptorName).channel_descriptor; + matchChannelDescriptorFromFolderChannelDescriptorName( + folderChannelDescriptorName: string, + ) { + return this.pathTemplates.folderChannelDescriptorPathTemplate.match( + folderChannelDescriptorName, + ).channel_descriptor; } /** @@ -1242,7 +1491,7 @@ export class AlertPolicyServiceClient { * @param {string} group * @returns {string} Resource name string. */ - folderGroupPath(folder:string,group:string) { + folderGroupPath(folder: string, group: string) { return this.pathTemplates.folderGroupPathTemplate.render({ folder: folder, group: group, @@ -1257,7 +1506,8 @@ export class AlertPolicyServiceClient { * @returns {string} A string representing the folder. */ matchFolderFromFolderGroupName(folderGroupName: string) { - return this.pathTemplates.folderGroupPathTemplate.match(folderGroupName).folder; + return this.pathTemplates.folderGroupPathTemplate.match(folderGroupName) + .folder; } /** @@ -1268,7 +1518,8 @@ export class AlertPolicyServiceClient { * @returns {string} A string representing the group. */ matchGroupFromFolderGroupName(folderGroupName: string) { - return this.pathTemplates.folderGroupPathTemplate.match(folderGroupName).group; + return this.pathTemplates.folderGroupPathTemplate.match(folderGroupName) + .group; } /** @@ -1278,7 +1529,7 @@ export class AlertPolicyServiceClient { * @param {string} notification_channel * @returns {string} Resource name string. */ - folderNotificationChannelPath(folder:string,notificationChannel:string) { + folderNotificationChannelPath(folder: string, notificationChannel: string) { return this.pathTemplates.folderNotificationChannelPathTemplate.render({ folder: folder, notification_channel: notificationChannel, @@ -1292,8 +1543,12 @@ export class AlertPolicyServiceClient { * A fully-qualified path representing folder_notification_channel resource. * @returns {string} A string representing the folder. */ - matchFolderFromFolderNotificationChannelName(folderNotificationChannelName: string) { - return this.pathTemplates.folderNotificationChannelPathTemplate.match(folderNotificationChannelName).folder; + matchFolderFromFolderNotificationChannelName( + folderNotificationChannelName: string, + ) { + return this.pathTemplates.folderNotificationChannelPathTemplate.match( + folderNotificationChannelName, + ).folder; } /** @@ -1303,8 +1558,12 @@ export class AlertPolicyServiceClient { * A fully-qualified path representing folder_notification_channel resource. * @returns {string} A string representing the notification_channel. */ - matchNotificationChannelFromFolderNotificationChannelName(folderNotificationChannelName: string) { - return this.pathTemplates.folderNotificationChannelPathTemplate.match(folderNotificationChannelName).notification_channel; + matchNotificationChannelFromFolderNotificationChannelName( + folderNotificationChannelName: string, + ) { + return this.pathTemplates.folderNotificationChannelPathTemplate.match( + folderNotificationChannelName, + ).notification_channel; } /** @@ -1314,7 +1573,7 @@ export class AlertPolicyServiceClient { * @param {string} service * @returns {string} Resource name string. */ - folderServicePath(folder:string,service:string) { + folderServicePath(folder: string, service: string) { return this.pathTemplates.folderServicePathTemplate.render({ folder: folder, service: service, @@ -1329,7 +1588,8 @@ export class AlertPolicyServiceClient { * @returns {string} A string representing the folder. */ matchFolderFromFolderServiceName(folderServiceName: string) { - return this.pathTemplates.folderServicePathTemplate.match(folderServiceName).folder; + return this.pathTemplates.folderServicePathTemplate.match(folderServiceName) + .folder; } /** @@ -1340,7 +1600,8 @@ export class AlertPolicyServiceClient { * @returns {string} A string representing the service. */ matchServiceFromFolderServiceName(folderServiceName: string) { - return this.pathTemplates.folderServicePathTemplate.match(folderServiceName).service; + return this.pathTemplates.folderServicePathTemplate.match(folderServiceName) + .service; } /** @@ -1351,12 +1612,18 @@ export class AlertPolicyServiceClient { * @param {string} service_level_objective * @returns {string} Resource name string. */ - folderServiceServiceLevelObjectivePath(folder:string,service:string,serviceLevelObjective:string) { - return this.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.render({ - folder: folder, - service: service, - service_level_objective: serviceLevelObjective, - }); + folderServiceServiceLevelObjectivePath( + folder: string, + service: string, + serviceLevelObjective: string, + ) { + return this.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.render( + { + folder: folder, + service: service, + service_level_objective: serviceLevelObjective, + }, + ); } /** @@ -1366,8 +1633,12 @@ export class AlertPolicyServiceClient { * A fully-qualified path representing folder_service_service_level_objective resource. * @returns {string} A string representing the folder. */ - matchFolderFromFolderServiceServiceLevelObjectiveName(folderServiceServiceLevelObjectiveName: string) { - return this.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match(folderServiceServiceLevelObjectiveName).folder; + matchFolderFromFolderServiceServiceLevelObjectiveName( + folderServiceServiceLevelObjectiveName: string, + ) { + return this.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match( + folderServiceServiceLevelObjectiveName, + ).folder; } /** @@ -1377,8 +1648,12 @@ export class AlertPolicyServiceClient { * A fully-qualified path representing folder_service_service_level_objective resource. * @returns {string} A string representing the service. */ - matchServiceFromFolderServiceServiceLevelObjectiveName(folderServiceServiceLevelObjectiveName: string) { - return this.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match(folderServiceServiceLevelObjectiveName).service; + matchServiceFromFolderServiceServiceLevelObjectiveName( + folderServiceServiceLevelObjectiveName: string, + ) { + return this.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match( + folderServiceServiceLevelObjectiveName, + ).service; } /** @@ -1388,8 +1663,12 @@ export class AlertPolicyServiceClient { * A fully-qualified path representing folder_service_service_level_objective resource. * @returns {string} A string representing the service_level_objective. */ - matchServiceLevelObjectiveFromFolderServiceServiceLevelObjectiveName(folderServiceServiceLevelObjectiveName: string) { - return this.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match(folderServiceServiceLevelObjectiveName).service_level_objective; + matchServiceLevelObjectiveFromFolderServiceServiceLevelObjectiveName( + folderServiceServiceLevelObjectiveName: string, + ) { + return this.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match( + folderServiceServiceLevelObjectiveName, + ).service_level_objective; } /** @@ -1399,7 +1678,7 @@ export class AlertPolicyServiceClient { * @param {string} uptime_check_config * @returns {string} Resource name string. */ - folderUptimeCheckConfigPath(folder:string,uptimeCheckConfig:string) { + folderUptimeCheckConfigPath(folder: string, uptimeCheckConfig: string) { return this.pathTemplates.folderUptimeCheckConfigPathTemplate.render({ folder: folder, uptime_check_config: uptimeCheckConfig, @@ -1413,8 +1692,12 @@ export class AlertPolicyServiceClient { * A fully-qualified path representing folder_uptime_check_config resource. * @returns {string} A string representing the folder. */ - matchFolderFromFolderUptimeCheckConfigName(folderUptimeCheckConfigName: string) { - return this.pathTemplates.folderUptimeCheckConfigPathTemplate.match(folderUptimeCheckConfigName).folder; + matchFolderFromFolderUptimeCheckConfigName( + folderUptimeCheckConfigName: string, + ) { + return this.pathTemplates.folderUptimeCheckConfigPathTemplate.match( + folderUptimeCheckConfigName, + ).folder; } /** @@ -1424,8 +1707,12 @@ export class AlertPolicyServiceClient { * A fully-qualified path representing folder_uptime_check_config resource. * @returns {string} A string representing the uptime_check_config. */ - matchUptimeCheckConfigFromFolderUptimeCheckConfigName(folderUptimeCheckConfigName: string) { - return this.pathTemplates.folderUptimeCheckConfigPathTemplate.match(folderUptimeCheckConfigName).uptime_check_config; + matchUptimeCheckConfigFromFolderUptimeCheckConfigName( + folderUptimeCheckConfigName: string, + ) { + return this.pathTemplates.folderUptimeCheckConfigPathTemplate.match( + folderUptimeCheckConfigName, + ).uptime_check_config; } /** @@ -1435,7 +1722,7 @@ export class AlertPolicyServiceClient { * @param {string} alert_policy * @returns {string} Resource name string. */ - organizationAlertPolicyPath(organization:string,alertPolicy:string) { + organizationAlertPolicyPath(organization: string, alertPolicy: string) { return this.pathTemplates.organizationAlertPolicyPathTemplate.render({ organization: organization, alert_policy: alertPolicy, @@ -1449,8 +1736,12 @@ export class AlertPolicyServiceClient { * A fully-qualified path representing organization_alert_policy resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationAlertPolicyName(organizationAlertPolicyName: string) { - return this.pathTemplates.organizationAlertPolicyPathTemplate.match(organizationAlertPolicyName).organization; + matchOrganizationFromOrganizationAlertPolicyName( + organizationAlertPolicyName: string, + ) { + return this.pathTemplates.organizationAlertPolicyPathTemplate.match( + organizationAlertPolicyName, + ).organization; } /** @@ -1460,8 +1751,12 @@ export class AlertPolicyServiceClient { * A fully-qualified path representing organization_alert_policy resource. * @returns {string} A string representing the alert_policy. */ - matchAlertPolicyFromOrganizationAlertPolicyName(organizationAlertPolicyName: string) { - return this.pathTemplates.organizationAlertPolicyPathTemplate.match(organizationAlertPolicyName).alert_policy; + matchAlertPolicyFromOrganizationAlertPolicyName( + organizationAlertPolicyName: string, + ) { + return this.pathTemplates.organizationAlertPolicyPathTemplate.match( + organizationAlertPolicyName, + ).alert_policy; } /** @@ -1472,12 +1767,18 @@ export class AlertPolicyServiceClient { * @param {string} condition * @returns {string} Resource name string. */ - organizationAlertPolicyConditionPath(organization:string,alertPolicy:string,condition:string) { - return this.pathTemplates.organizationAlertPolicyConditionPathTemplate.render({ - organization: organization, - alert_policy: alertPolicy, - condition: condition, - }); + organizationAlertPolicyConditionPath( + organization: string, + alertPolicy: string, + condition: string, + ) { + return this.pathTemplates.organizationAlertPolicyConditionPathTemplate.render( + { + organization: organization, + alert_policy: alertPolicy, + condition: condition, + }, + ); } /** @@ -1487,8 +1788,12 @@ export class AlertPolicyServiceClient { * A fully-qualified path representing organization_alert_policy_condition resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationAlertPolicyConditionName(organizationAlertPolicyConditionName: string) { - return this.pathTemplates.organizationAlertPolicyConditionPathTemplate.match(organizationAlertPolicyConditionName).organization; + matchOrganizationFromOrganizationAlertPolicyConditionName( + organizationAlertPolicyConditionName: string, + ) { + return this.pathTemplates.organizationAlertPolicyConditionPathTemplate.match( + organizationAlertPolicyConditionName, + ).organization; } /** @@ -1498,8 +1803,12 @@ export class AlertPolicyServiceClient { * A fully-qualified path representing organization_alert_policy_condition resource. * @returns {string} A string representing the alert_policy. */ - matchAlertPolicyFromOrganizationAlertPolicyConditionName(organizationAlertPolicyConditionName: string) { - return this.pathTemplates.organizationAlertPolicyConditionPathTemplate.match(organizationAlertPolicyConditionName).alert_policy; + matchAlertPolicyFromOrganizationAlertPolicyConditionName( + organizationAlertPolicyConditionName: string, + ) { + return this.pathTemplates.organizationAlertPolicyConditionPathTemplate.match( + organizationAlertPolicyConditionName, + ).alert_policy; } /** @@ -1509,8 +1818,12 @@ export class AlertPolicyServiceClient { * A fully-qualified path representing organization_alert_policy_condition resource. * @returns {string} A string representing the condition. */ - matchConditionFromOrganizationAlertPolicyConditionName(organizationAlertPolicyConditionName: string) { - return this.pathTemplates.organizationAlertPolicyConditionPathTemplate.match(organizationAlertPolicyConditionName).condition; + matchConditionFromOrganizationAlertPolicyConditionName( + organizationAlertPolicyConditionName: string, + ) { + return this.pathTemplates.organizationAlertPolicyConditionPathTemplate.match( + organizationAlertPolicyConditionName, + ).condition; } /** @@ -1520,7 +1833,10 @@ export class AlertPolicyServiceClient { * @param {string} channel_descriptor * @returns {string} Resource name string. */ - organizationChannelDescriptorPath(organization:string,channelDescriptor:string) { + organizationChannelDescriptorPath( + organization: string, + channelDescriptor: string, + ) { return this.pathTemplates.organizationChannelDescriptorPathTemplate.render({ organization: organization, channel_descriptor: channelDescriptor, @@ -1534,8 +1850,12 @@ export class AlertPolicyServiceClient { * A fully-qualified path representing organization_channel_descriptor resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationChannelDescriptorName(organizationChannelDescriptorName: string) { - return this.pathTemplates.organizationChannelDescriptorPathTemplate.match(organizationChannelDescriptorName).organization; + matchOrganizationFromOrganizationChannelDescriptorName( + organizationChannelDescriptorName: string, + ) { + return this.pathTemplates.organizationChannelDescriptorPathTemplate.match( + organizationChannelDescriptorName, + ).organization; } /** @@ -1545,8 +1865,12 @@ export class AlertPolicyServiceClient { * A fully-qualified path representing organization_channel_descriptor resource. * @returns {string} A string representing the channel_descriptor. */ - matchChannelDescriptorFromOrganizationChannelDescriptorName(organizationChannelDescriptorName: string) { - return this.pathTemplates.organizationChannelDescriptorPathTemplate.match(organizationChannelDescriptorName).channel_descriptor; + matchChannelDescriptorFromOrganizationChannelDescriptorName( + organizationChannelDescriptorName: string, + ) { + return this.pathTemplates.organizationChannelDescriptorPathTemplate.match( + organizationChannelDescriptorName, + ).channel_descriptor; } /** @@ -1556,7 +1880,7 @@ export class AlertPolicyServiceClient { * @param {string} group * @returns {string} Resource name string. */ - organizationGroupPath(organization:string,group:string) { + organizationGroupPath(organization: string, group: string) { return this.pathTemplates.organizationGroupPathTemplate.render({ organization: organization, group: group, @@ -1571,7 +1895,9 @@ export class AlertPolicyServiceClient { * @returns {string} A string representing the organization. */ matchOrganizationFromOrganizationGroupName(organizationGroupName: string) { - return this.pathTemplates.organizationGroupPathTemplate.match(organizationGroupName).organization; + return this.pathTemplates.organizationGroupPathTemplate.match( + organizationGroupName, + ).organization; } /** @@ -1582,7 +1908,9 @@ export class AlertPolicyServiceClient { * @returns {string} A string representing the group. */ matchGroupFromOrganizationGroupName(organizationGroupName: string) { - return this.pathTemplates.organizationGroupPathTemplate.match(organizationGroupName).group; + return this.pathTemplates.organizationGroupPathTemplate.match( + organizationGroupName, + ).group; } /** @@ -1592,11 +1920,16 @@ export class AlertPolicyServiceClient { * @param {string} notification_channel * @returns {string} Resource name string. */ - organizationNotificationChannelPath(organization:string,notificationChannel:string) { - return this.pathTemplates.organizationNotificationChannelPathTemplate.render({ - organization: organization, - notification_channel: notificationChannel, - }); + organizationNotificationChannelPath( + organization: string, + notificationChannel: string, + ) { + return this.pathTemplates.organizationNotificationChannelPathTemplate.render( + { + organization: organization, + notification_channel: notificationChannel, + }, + ); } /** @@ -1606,8 +1939,12 @@ export class AlertPolicyServiceClient { * A fully-qualified path representing organization_notification_channel resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationNotificationChannelName(organizationNotificationChannelName: string) { - return this.pathTemplates.organizationNotificationChannelPathTemplate.match(organizationNotificationChannelName).organization; + matchOrganizationFromOrganizationNotificationChannelName( + organizationNotificationChannelName: string, + ) { + return this.pathTemplates.organizationNotificationChannelPathTemplate.match( + organizationNotificationChannelName, + ).organization; } /** @@ -1617,8 +1954,12 @@ export class AlertPolicyServiceClient { * A fully-qualified path representing organization_notification_channel resource. * @returns {string} A string representing the notification_channel. */ - matchNotificationChannelFromOrganizationNotificationChannelName(organizationNotificationChannelName: string) { - return this.pathTemplates.organizationNotificationChannelPathTemplate.match(organizationNotificationChannelName).notification_channel; + matchNotificationChannelFromOrganizationNotificationChannelName( + organizationNotificationChannelName: string, + ) { + return this.pathTemplates.organizationNotificationChannelPathTemplate.match( + organizationNotificationChannelName, + ).notification_channel; } /** @@ -1628,7 +1969,7 @@ export class AlertPolicyServiceClient { * @param {string} service * @returns {string} Resource name string. */ - organizationServicePath(organization:string,service:string) { + organizationServicePath(organization: string, service: string) { return this.pathTemplates.organizationServicePathTemplate.render({ organization: organization, service: service, @@ -1642,8 +1983,12 @@ export class AlertPolicyServiceClient { * A fully-qualified path representing organization_service resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationServiceName(organizationServiceName: string) { - return this.pathTemplates.organizationServicePathTemplate.match(organizationServiceName).organization; + matchOrganizationFromOrganizationServiceName( + organizationServiceName: string, + ) { + return this.pathTemplates.organizationServicePathTemplate.match( + organizationServiceName, + ).organization; } /** @@ -1654,7 +1999,9 @@ export class AlertPolicyServiceClient { * @returns {string} A string representing the service. */ matchServiceFromOrganizationServiceName(organizationServiceName: string) { - return this.pathTemplates.organizationServicePathTemplate.match(organizationServiceName).service; + return this.pathTemplates.organizationServicePathTemplate.match( + organizationServiceName, + ).service; } /** @@ -1665,12 +2012,18 @@ export class AlertPolicyServiceClient { * @param {string} service_level_objective * @returns {string} Resource name string. */ - organizationServiceServiceLevelObjectivePath(organization:string,service:string,serviceLevelObjective:string) { - return this.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.render({ - organization: organization, - service: service, - service_level_objective: serviceLevelObjective, - }); + organizationServiceServiceLevelObjectivePath( + organization: string, + service: string, + serviceLevelObjective: string, + ) { + return this.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.render( + { + organization: organization, + service: service, + service_level_objective: serviceLevelObjective, + }, + ); } /** @@ -1680,8 +2033,12 @@ export class AlertPolicyServiceClient { * A fully-qualified path representing organization_service_service_level_objective resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationServiceServiceLevelObjectiveName(organizationServiceServiceLevelObjectiveName: string) { - return this.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match(organizationServiceServiceLevelObjectiveName).organization; + matchOrganizationFromOrganizationServiceServiceLevelObjectiveName( + organizationServiceServiceLevelObjectiveName: string, + ) { + return this.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match( + organizationServiceServiceLevelObjectiveName, + ).organization; } /** @@ -1691,8 +2048,12 @@ export class AlertPolicyServiceClient { * A fully-qualified path representing organization_service_service_level_objective resource. * @returns {string} A string representing the service. */ - matchServiceFromOrganizationServiceServiceLevelObjectiveName(organizationServiceServiceLevelObjectiveName: string) { - return this.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match(organizationServiceServiceLevelObjectiveName).service; + matchServiceFromOrganizationServiceServiceLevelObjectiveName( + organizationServiceServiceLevelObjectiveName: string, + ) { + return this.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match( + organizationServiceServiceLevelObjectiveName, + ).service; } /** @@ -1702,8 +2063,12 @@ export class AlertPolicyServiceClient { * A fully-qualified path representing organization_service_service_level_objective resource. * @returns {string} A string representing the service_level_objective. */ - matchServiceLevelObjectiveFromOrganizationServiceServiceLevelObjectiveName(organizationServiceServiceLevelObjectiveName: string) { - return this.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match(organizationServiceServiceLevelObjectiveName).service_level_objective; + matchServiceLevelObjectiveFromOrganizationServiceServiceLevelObjectiveName( + organizationServiceServiceLevelObjectiveName: string, + ) { + return this.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match( + organizationServiceServiceLevelObjectiveName, + ).service_level_objective; } /** @@ -1713,7 +2078,10 @@ export class AlertPolicyServiceClient { * @param {string} uptime_check_config * @returns {string} Resource name string. */ - organizationUptimeCheckConfigPath(organization:string,uptimeCheckConfig:string) { + organizationUptimeCheckConfigPath( + organization: string, + uptimeCheckConfig: string, + ) { return this.pathTemplates.organizationUptimeCheckConfigPathTemplate.render({ organization: organization, uptime_check_config: uptimeCheckConfig, @@ -1727,8 +2095,12 @@ export class AlertPolicyServiceClient { * A fully-qualified path representing organization_uptime_check_config resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationUptimeCheckConfigName(organizationUptimeCheckConfigName: string) { - return this.pathTemplates.organizationUptimeCheckConfigPathTemplate.match(organizationUptimeCheckConfigName).organization; + matchOrganizationFromOrganizationUptimeCheckConfigName( + organizationUptimeCheckConfigName: string, + ) { + return this.pathTemplates.organizationUptimeCheckConfigPathTemplate.match( + organizationUptimeCheckConfigName, + ).organization; } /** @@ -1738,8 +2110,12 @@ export class AlertPolicyServiceClient { * A fully-qualified path representing organization_uptime_check_config resource. * @returns {string} A string representing the uptime_check_config. */ - matchUptimeCheckConfigFromOrganizationUptimeCheckConfigName(organizationUptimeCheckConfigName: string) { - return this.pathTemplates.organizationUptimeCheckConfigPathTemplate.match(organizationUptimeCheckConfigName).uptime_check_config; + matchUptimeCheckConfigFromOrganizationUptimeCheckConfigName( + organizationUptimeCheckConfigName: string, + ) { + return this.pathTemplates.organizationUptimeCheckConfigPathTemplate.match( + organizationUptimeCheckConfigName, + ).uptime_check_config; } /** @@ -1749,7 +2125,7 @@ export class AlertPolicyServiceClient { * @param {string} alert_policy * @returns {string} Resource name string. */ - projectAlertPolicyPath(project:string,alertPolicy:string) { + projectAlertPolicyPath(project: string, alertPolicy: string) { return this.pathTemplates.projectAlertPolicyPathTemplate.render({ project: project, alert_policy: alertPolicy, @@ -1764,7 +2140,9 @@ export class AlertPolicyServiceClient { * @returns {string} A string representing the project. */ matchProjectFromProjectAlertPolicyName(projectAlertPolicyName: string) { - return this.pathTemplates.projectAlertPolicyPathTemplate.match(projectAlertPolicyName).project; + return this.pathTemplates.projectAlertPolicyPathTemplate.match( + projectAlertPolicyName, + ).project; } /** @@ -1775,7 +2153,9 @@ export class AlertPolicyServiceClient { * @returns {string} A string representing the alert_policy. */ matchAlertPolicyFromProjectAlertPolicyName(projectAlertPolicyName: string) { - return this.pathTemplates.projectAlertPolicyPathTemplate.match(projectAlertPolicyName).alert_policy; + return this.pathTemplates.projectAlertPolicyPathTemplate.match( + projectAlertPolicyName, + ).alert_policy; } /** @@ -1786,7 +2166,11 @@ export class AlertPolicyServiceClient { * @param {string} condition * @returns {string} Resource name string. */ - projectAlertPolicyConditionPath(project:string,alertPolicy:string,condition:string) { + projectAlertPolicyConditionPath( + project: string, + alertPolicy: string, + condition: string, + ) { return this.pathTemplates.projectAlertPolicyConditionPathTemplate.render({ project: project, alert_policy: alertPolicy, @@ -1801,8 +2185,12 @@ export class AlertPolicyServiceClient { * A fully-qualified path representing project_alert_policy_condition resource. * @returns {string} A string representing the project. */ - matchProjectFromProjectAlertPolicyConditionName(projectAlertPolicyConditionName: string) { - return this.pathTemplates.projectAlertPolicyConditionPathTemplate.match(projectAlertPolicyConditionName).project; + matchProjectFromProjectAlertPolicyConditionName( + projectAlertPolicyConditionName: string, + ) { + return this.pathTemplates.projectAlertPolicyConditionPathTemplate.match( + projectAlertPolicyConditionName, + ).project; } /** @@ -1812,8 +2200,12 @@ export class AlertPolicyServiceClient { * A fully-qualified path representing project_alert_policy_condition resource. * @returns {string} A string representing the alert_policy. */ - matchAlertPolicyFromProjectAlertPolicyConditionName(projectAlertPolicyConditionName: string) { - return this.pathTemplates.projectAlertPolicyConditionPathTemplate.match(projectAlertPolicyConditionName).alert_policy; + matchAlertPolicyFromProjectAlertPolicyConditionName( + projectAlertPolicyConditionName: string, + ) { + return this.pathTemplates.projectAlertPolicyConditionPathTemplate.match( + projectAlertPolicyConditionName, + ).alert_policy; } /** @@ -1823,8 +2215,12 @@ export class AlertPolicyServiceClient { * A fully-qualified path representing project_alert_policy_condition resource. * @returns {string} A string representing the condition. */ - matchConditionFromProjectAlertPolicyConditionName(projectAlertPolicyConditionName: string) { - return this.pathTemplates.projectAlertPolicyConditionPathTemplate.match(projectAlertPolicyConditionName).condition; + matchConditionFromProjectAlertPolicyConditionName( + projectAlertPolicyConditionName: string, + ) { + return this.pathTemplates.projectAlertPolicyConditionPathTemplate.match( + projectAlertPolicyConditionName, + ).condition; } /** @@ -1834,7 +2230,7 @@ export class AlertPolicyServiceClient { * @param {string} channel_descriptor * @returns {string} Resource name string. */ - projectChannelDescriptorPath(project:string,channelDescriptor:string) { + projectChannelDescriptorPath(project: string, channelDescriptor: string) { return this.pathTemplates.projectChannelDescriptorPathTemplate.render({ project: project, channel_descriptor: channelDescriptor, @@ -1848,8 +2244,12 @@ export class AlertPolicyServiceClient { * A fully-qualified path representing project_channel_descriptor resource. * @returns {string} A string representing the project. */ - matchProjectFromProjectChannelDescriptorName(projectChannelDescriptorName: string) { - return this.pathTemplates.projectChannelDescriptorPathTemplate.match(projectChannelDescriptorName).project; + matchProjectFromProjectChannelDescriptorName( + projectChannelDescriptorName: string, + ) { + return this.pathTemplates.projectChannelDescriptorPathTemplate.match( + projectChannelDescriptorName, + ).project; } /** @@ -1859,8 +2259,12 @@ export class AlertPolicyServiceClient { * A fully-qualified path representing project_channel_descriptor resource. * @returns {string} A string representing the channel_descriptor. */ - matchChannelDescriptorFromProjectChannelDescriptorName(projectChannelDescriptorName: string) { - return this.pathTemplates.projectChannelDescriptorPathTemplate.match(projectChannelDescriptorName).channel_descriptor; + matchChannelDescriptorFromProjectChannelDescriptorName( + projectChannelDescriptorName: string, + ) { + return this.pathTemplates.projectChannelDescriptorPathTemplate.match( + projectChannelDescriptorName, + ).channel_descriptor; } /** @@ -1870,7 +2274,7 @@ export class AlertPolicyServiceClient { * @param {string} group * @returns {string} Resource name string. */ - projectGroupPath(project:string,group:string) { + projectGroupPath(project: string, group: string) { return this.pathTemplates.projectGroupPathTemplate.render({ project: project, group: group, @@ -1885,7 +2289,8 @@ export class AlertPolicyServiceClient { * @returns {string} A string representing the project. */ matchProjectFromProjectGroupName(projectGroupName: string) { - return this.pathTemplates.projectGroupPathTemplate.match(projectGroupName).project; + return this.pathTemplates.projectGroupPathTemplate.match(projectGroupName) + .project; } /** @@ -1896,7 +2301,8 @@ export class AlertPolicyServiceClient { * @returns {string} A string representing the group. */ matchGroupFromProjectGroupName(projectGroupName: string) { - return this.pathTemplates.projectGroupPathTemplate.match(projectGroupName).group; + return this.pathTemplates.projectGroupPathTemplate.match(projectGroupName) + .group; } /** @@ -1906,7 +2312,7 @@ export class AlertPolicyServiceClient { * @param {string} notification_channel * @returns {string} Resource name string. */ - projectNotificationChannelPath(project:string,notificationChannel:string) { + projectNotificationChannelPath(project: string, notificationChannel: string) { return this.pathTemplates.projectNotificationChannelPathTemplate.render({ project: project, notification_channel: notificationChannel, @@ -1920,8 +2326,12 @@ export class AlertPolicyServiceClient { * A fully-qualified path representing project_notification_channel resource. * @returns {string} A string representing the project. */ - matchProjectFromProjectNotificationChannelName(projectNotificationChannelName: string) { - return this.pathTemplates.projectNotificationChannelPathTemplate.match(projectNotificationChannelName).project; + matchProjectFromProjectNotificationChannelName( + projectNotificationChannelName: string, + ) { + return this.pathTemplates.projectNotificationChannelPathTemplate.match( + projectNotificationChannelName, + ).project; } /** @@ -1931,8 +2341,12 @@ export class AlertPolicyServiceClient { * A fully-qualified path representing project_notification_channel resource. * @returns {string} A string representing the notification_channel. */ - matchNotificationChannelFromProjectNotificationChannelName(projectNotificationChannelName: string) { - return this.pathTemplates.projectNotificationChannelPathTemplate.match(projectNotificationChannelName).notification_channel; + matchNotificationChannelFromProjectNotificationChannelName( + projectNotificationChannelName: string, + ) { + return this.pathTemplates.projectNotificationChannelPathTemplate.match( + projectNotificationChannelName, + ).notification_channel; } /** @@ -1942,7 +2356,7 @@ export class AlertPolicyServiceClient { * @param {string} service * @returns {string} Resource name string. */ - projectServicePath(project:string,service:string) { + projectServicePath(project: string, service: string) { return this.pathTemplates.projectServicePathTemplate.render({ project: project, service: service, @@ -1957,7 +2371,9 @@ export class AlertPolicyServiceClient { * @returns {string} A string representing the project. */ matchProjectFromProjectServiceName(projectServiceName: string) { - return this.pathTemplates.projectServicePathTemplate.match(projectServiceName).project; + return this.pathTemplates.projectServicePathTemplate.match( + projectServiceName, + ).project; } /** @@ -1968,7 +2384,9 @@ export class AlertPolicyServiceClient { * @returns {string} A string representing the service. */ matchServiceFromProjectServiceName(projectServiceName: string) { - return this.pathTemplates.projectServicePathTemplate.match(projectServiceName).service; + return this.pathTemplates.projectServicePathTemplate.match( + projectServiceName, + ).service; } /** @@ -1979,12 +2397,18 @@ export class AlertPolicyServiceClient { * @param {string} service_level_objective * @returns {string} Resource name string. */ - projectServiceServiceLevelObjectivePath(project:string,service:string,serviceLevelObjective:string) { - return this.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.render({ - project: project, - service: service, - service_level_objective: serviceLevelObjective, - }); + projectServiceServiceLevelObjectivePath( + project: string, + service: string, + serviceLevelObjective: string, + ) { + return this.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.render( + { + project: project, + service: service, + service_level_objective: serviceLevelObjective, + }, + ); } /** @@ -1994,8 +2418,12 @@ export class AlertPolicyServiceClient { * A fully-qualified path representing project_service_service_level_objective resource. * @returns {string} A string representing the project. */ - matchProjectFromProjectServiceServiceLevelObjectiveName(projectServiceServiceLevelObjectiveName: string) { - return this.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match(projectServiceServiceLevelObjectiveName).project; + matchProjectFromProjectServiceServiceLevelObjectiveName( + projectServiceServiceLevelObjectiveName: string, + ) { + return this.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match( + projectServiceServiceLevelObjectiveName, + ).project; } /** @@ -2005,8 +2433,12 @@ export class AlertPolicyServiceClient { * A fully-qualified path representing project_service_service_level_objective resource. * @returns {string} A string representing the service. */ - matchServiceFromProjectServiceServiceLevelObjectiveName(projectServiceServiceLevelObjectiveName: string) { - return this.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match(projectServiceServiceLevelObjectiveName).service; + matchServiceFromProjectServiceServiceLevelObjectiveName( + projectServiceServiceLevelObjectiveName: string, + ) { + return this.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match( + projectServiceServiceLevelObjectiveName, + ).service; } /** @@ -2016,8 +2448,12 @@ export class AlertPolicyServiceClient { * A fully-qualified path representing project_service_service_level_objective resource. * @returns {string} A string representing the service_level_objective. */ - matchServiceLevelObjectiveFromProjectServiceServiceLevelObjectiveName(projectServiceServiceLevelObjectiveName: string) { - return this.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match(projectServiceServiceLevelObjectiveName).service_level_objective; + matchServiceLevelObjectiveFromProjectServiceServiceLevelObjectiveName( + projectServiceServiceLevelObjectiveName: string, + ) { + return this.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match( + projectServiceServiceLevelObjectiveName, + ).service_level_objective; } /** @@ -2027,7 +2463,7 @@ export class AlertPolicyServiceClient { * @param {string} uptime_check_config * @returns {string} Resource name string. */ - projectUptimeCheckConfigPath(project:string,uptimeCheckConfig:string) { + projectUptimeCheckConfigPath(project: string, uptimeCheckConfig: string) { return this.pathTemplates.projectUptimeCheckConfigPathTemplate.render({ project: project, uptime_check_config: uptimeCheckConfig, @@ -2041,8 +2477,12 @@ export class AlertPolicyServiceClient { * A fully-qualified path representing project_uptime_check_config resource. * @returns {string} A string representing the project. */ - matchProjectFromProjectUptimeCheckConfigName(projectUptimeCheckConfigName: string) { - return this.pathTemplates.projectUptimeCheckConfigPathTemplate.match(projectUptimeCheckConfigName).project; + matchProjectFromProjectUptimeCheckConfigName( + projectUptimeCheckConfigName: string, + ) { + return this.pathTemplates.projectUptimeCheckConfigPathTemplate.match( + projectUptimeCheckConfigName, + ).project; } /** @@ -2052,8 +2492,12 @@ export class AlertPolicyServiceClient { * A fully-qualified path representing project_uptime_check_config resource. * @returns {string} A string representing the uptime_check_config. */ - matchUptimeCheckConfigFromProjectUptimeCheckConfigName(projectUptimeCheckConfigName: string) { - return this.pathTemplates.projectUptimeCheckConfigPathTemplate.match(projectUptimeCheckConfigName).uptime_check_config; + matchUptimeCheckConfigFromProjectUptimeCheckConfigName( + projectUptimeCheckConfigName: string, + ) { + return this.pathTemplates.projectUptimeCheckConfigPathTemplate.match( + projectUptimeCheckConfigName, + ).uptime_check_config; } /** @@ -2064,7 +2508,7 @@ export class AlertPolicyServiceClient { */ close(): Promise { if (this.alertPolicyServiceStub && !this._terminated) { - return this.alertPolicyServiceStub.then(stub => { + return this.alertPolicyServiceStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -2072,4 +2516,4 @@ export class AlertPolicyServiceClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/core/generator/gapic-generator-typescript/baselines/monitoring-esm/esm/src/v3/group_service_client.ts.baseline b/core/generator/gapic-generator-typescript/baselines/monitoring-esm/esm/src/v3/group_service_client.ts.baseline index d17af876d1ec..25ef6065dc10 100644 --- a/core/generator/gapic-generator-typescript/baselines/monitoring-esm/esm/src/v3/group_service_client.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/monitoring-esm/esm/src/v3/group_service_client.ts.baseline @@ -18,15 +18,22 @@ /* global window */ import * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions, PaginationCallback, GaxCall} from 'google-gax'; -import {Transform} from 'stream'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + PaginationCallback, + GaxCall, +} from 'google-gax'; +import { Transform } from 'stream'; // @ts-ignore import type * as protos from '../../../protos/protos.js'; import * as group_service_client_config from './group_service_client_config.json'; import fs from 'fs'; import path from 'path'; -import {fileURLToPath} from 'url'; -import {getJSON} from '../json-helper.cjs'; +import { fileURLToPath } from 'url'; +import { getJSON } from '../json-helper.cjs'; // @ts-ignore const dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -36,15 +43,15 @@ const dirname = path.dirname(fileURLToPath(import.meta.url)); * This file defines retry strategy and timeouts for all API methods in this library. */ const gapicConfig = getJSON( - path.join(dirname, 'group_service_client_config.json') + path.join(dirname, 'group_service_client_config.json'), ); const jsonProtos = getJSON( - path.join(dirname, '..', '..', '..', 'protos/protos.json') + path.join(dirname, '..', '..', '..', 'protos/protos.json'), ); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; const version = getJSON( - path.join(dirname, '..', '..', '..', '..', 'package.json') + path.join(dirname, '..', '..', '..', '..', 'package.json'), ).version; /** @@ -70,7 +77,7 @@ export class GroupServiceClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('monitoring'); @@ -82,9 +89,9 @@ export class GroupServiceClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; - groupServiceStub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; + groupServiceStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of GroupServiceClient. @@ -126,21 +133,42 @@ export class GroupServiceClient { * const client = new GroupServiceClient({fallback: 'rest'}, gax); * ``` */ - constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { // Ensure that options include all the required fields. const staticMembers = this.constructor as typeof GroupServiceClient; - if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { - throw new Error('Please set either universe_domain or universeDomain, but not both.'); + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); } - const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; - this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; this._servicePath = 'monitoring.' + this._universeDomain; - const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; - const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. if (servicePath !== this._servicePath && !('scopes' in opts)) { @@ -162,7 +190,7 @@ export class GroupServiceClient { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; @@ -179,10 +207,7 @@ export class GroupServiceClient { const isEsm = true; const isEsmString = isEsm ? '-esm' : '-cjs'; // Determine the client header string. - const clientHeader = [ - `gax/${this._gaxModule.version}`, - `gapic/${version}`, - ]; + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/{process.versions.node}${isEsmString}`); } else { @@ -190,7 +215,7 @@ export class GroupServiceClient { } if (!opts.fallback) { clientHeader.push(`grpc/${this._gaxGrpc.grpcVersion}`); - } else if (opts.fallback === 'rest' ) { + } else if (opts.fallback === 'rest') { clientHeader.push(`rest/${this._gaxGrpc.grpcVersion}`); } if (opts.libName && opts.libVersion) { @@ -198,83 +223,92 @@ export class GroupServiceClient { } // Load the applicable protos. - this._protos = this._gaxGrpc.loadProtoJSON(jsonProtos as gax.protobuf.INamespace); + this._protos = this._gaxGrpc.loadProtoJSON( + jsonProtos as gax.protobuf.INamespace, + ); // This API contains "path templates"; forward-slash-separated // identifiers to uniquely identify resources within the API. // Create useful helper objects for these. this.pathTemplates = { folderAlertPolicyPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/alertPolicies/{alert_policy}' + 'folders/{folder}/alertPolicies/{alert_policy}', ), folderAlertPolicyConditionPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/alertPolicies/{alert_policy}/conditions/{condition}' + 'folders/{folder}/alertPolicies/{alert_policy}/conditions/{condition}', ), folderChannelDescriptorPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/notificationChannelDescriptors/{channel_descriptor}' + 'folders/{folder}/notificationChannelDescriptors/{channel_descriptor}', ), folderGroupPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/groups/{group}' + 'folders/{folder}/groups/{group}', ), folderNotificationChannelPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/notificationChannels/{notification_channel}' + 'folders/{folder}/notificationChannels/{notification_channel}', ), folderServicePathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/services/{service}' - ), - folderServiceServiceLevelObjectivePathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/services/{service}/serviceLevelObjectives/{service_level_objective}' + 'folders/{folder}/services/{service}', ), + folderServiceServiceLevelObjectivePathTemplate: + new this._gaxModule.PathTemplate( + 'folders/{folder}/services/{service}/serviceLevelObjectives/{service_level_objective}', + ), folderUptimeCheckConfigPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/uptimeCheckConfigs/{uptime_check_config}' + 'folders/{folder}/uptimeCheckConfigs/{uptime_check_config}', ), organizationAlertPolicyPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/alertPolicies/{alert_policy}' - ), - organizationAlertPolicyConditionPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/alertPolicies/{alert_policy}/conditions/{condition}' - ), - organizationChannelDescriptorPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/notificationChannelDescriptors/{channel_descriptor}' + 'organizations/{organization}/alertPolicies/{alert_policy}', ), + organizationAlertPolicyConditionPathTemplate: + new this._gaxModule.PathTemplate( + 'organizations/{organization}/alertPolicies/{alert_policy}/conditions/{condition}', + ), + organizationChannelDescriptorPathTemplate: + new this._gaxModule.PathTemplate( + 'organizations/{organization}/notificationChannelDescriptors/{channel_descriptor}', + ), organizationGroupPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/groups/{group}' - ), - organizationNotificationChannelPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/notificationChannels/{notification_channel}' + 'organizations/{organization}/groups/{group}', ), + organizationNotificationChannelPathTemplate: + new this._gaxModule.PathTemplate( + 'organizations/{organization}/notificationChannels/{notification_channel}', + ), organizationServicePathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/services/{service}' - ), - organizationServiceServiceLevelObjectivePathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/services/{service}/serviceLevelObjectives/{service_level_objective}' - ), - organizationUptimeCheckConfigPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/uptimeCheckConfigs/{uptime_check_config}' + 'organizations/{organization}/services/{service}', ), + organizationServiceServiceLevelObjectivePathTemplate: + new this._gaxModule.PathTemplate( + 'organizations/{organization}/services/{service}/serviceLevelObjectives/{service_level_objective}', + ), + organizationUptimeCheckConfigPathTemplate: + new this._gaxModule.PathTemplate( + 'organizations/{organization}/uptimeCheckConfigs/{uptime_check_config}', + ), projectAlertPolicyPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/alertPolicies/{alert_policy}' + 'projects/{project}/alertPolicies/{alert_policy}', ), projectAlertPolicyConditionPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/alertPolicies/{alert_policy}/conditions/{condition}' + 'projects/{project}/alertPolicies/{alert_policy}/conditions/{condition}', ), projectChannelDescriptorPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/notificationChannelDescriptors/{channel_descriptor}' + 'projects/{project}/notificationChannelDescriptors/{channel_descriptor}', ), projectGroupPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/groups/{group}' + 'projects/{project}/groups/{group}', ), projectNotificationChannelPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/notificationChannels/{notification_channel}' + 'projects/{project}/notificationChannels/{notification_channel}', ), projectServicePathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/services/{service}' - ), - projectServiceServiceLevelObjectivePathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/services/{service}/serviceLevelObjectives/{service_level_objective}' + 'projects/{project}/services/{service}', ), + projectServiceServiceLevelObjectivePathTemplate: + new this._gaxModule.PathTemplate( + 'projects/{project}/services/{service}/serviceLevelObjectives/{service_level_objective}', + ), projectUptimeCheckConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/uptimeCheckConfigs/{uptime_check_config}' + 'projects/{project}/uptimeCheckConfigs/{uptime_check_config}', ), }; @@ -282,16 +316,25 @@ export class GroupServiceClient { // (e.g. 50 results at a time, with tokens to get subsequent // pages). Denote the keys used for pagination and results. this.descriptors.page = { - listGroups: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'group'), - listGroupMembers: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'members') + listGroups: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'group', + ), + listGroupMembers: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'members', + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.monitoring.v3.GroupService', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.monitoring.v3.GroupService', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + { 'x-goog-api-client': clientHeader.join(' ') }, + ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -322,37 +365,47 @@ export class GroupServiceClient { // Put together the "service stub" for // google.monitoring.v3.GroupService. this.groupServiceStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.monitoring.v3.GroupService') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.monitoring.v3.GroupService', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.monitoring.v3.GroupService, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts, + this._providedCustomServicePath, + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const groupServiceStubMethods = - ['listGroups', 'getGroup', 'createGroup', 'updateGroup', 'deleteGroup', 'listGroupMembers']; + const groupServiceStubMethods = [ + 'listGroups', + 'getGroup', + 'createGroup', + 'updateGroup', + 'deleteGroup', + 'listGroupMembers', + ]; for (const methodName of groupServiceStubMethods) { const callPromise = this.groupServiceStub.then( - stub => (...args: Array<{}>) => { - if (this._terminated) { - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error|null|undefined) => () => { + (stub) => + (...args: Array<{}>) => { + if (this._terminated) { + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { throw err; - }); + }, + ); - const descriptor = - this.descriptors.page[methodName] || - undefined; + const descriptor = this.descriptors.page[methodName] || undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -367,8 +420,14 @@ export class GroupServiceClient { * @returns {string} The DNS address for this service. */ static get servicePath() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'monitoring.googleapis.com'; } @@ -380,8 +439,14 @@ export class GroupServiceClient { * @returns {string} The DNS address for this service. */ static get apiEndpoint() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'monitoring.googleapis.com'; } @@ -415,7 +480,7 @@ export class GroupServiceClient { return [ 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/monitoring', - 'https://www.googleapis.com/auth/monitoring.read' + 'https://www.googleapis.com/auth/monitoring.read', ]; } @@ -425,8 +490,9 @@ export class GroupServiceClient { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId(callback?: Callback): - Promise|void { + getProjectId( + callback?: Callback, + ): Promise | void { if (callback) { this.auth.getProjectId(callback); return; @@ -437,494 +503,633 @@ export class GroupServiceClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Gets a single group. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The group to retrieve. The format is - * `"projects/{project_id_or_number}/groups/{group_id}"`. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.monitoring.v3.Group|Group}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v3/group_service.get_group.js - * region_tag:monitoring_v3_generated_GroupService_GetGroup_async - */ + /** + * Gets a single group. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The group to retrieve. The format is + * `"projects/{project_id_or_number}/groups/{group_id}"`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.monitoring.v3.Group|Group}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v3/group_service.get_group.js + * region_tag:monitoring_v3_generated_GroupService_GetGroup_async + */ getGroup( - request?: protos.google.monitoring.v3.IGetGroupRequest, - options?: CallOptions): - Promise<[ - protos.google.monitoring.v3.IGroup, - protos.google.monitoring.v3.IGetGroupRequest|undefined, {}|undefined - ]>; + request?: protos.google.monitoring.v3.IGetGroupRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.monitoring.v3.IGroup, + protos.google.monitoring.v3.IGetGroupRequest | undefined, + {} | undefined, + ] + >; getGroup( - request: protos.google.monitoring.v3.IGetGroupRequest, - options: CallOptions, - callback: Callback< - protos.google.monitoring.v3.IGroup, - protos.google.monitoring.v3.IGetGroupRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.IGetGroupRequest, + options: CallOptions, + callback: Callback< + protos.google.monitoring.v3.IGroup, + protos.google.monitoring.v3.IGetGroupRequest | null | undefined, + {} | null | undefined + >, + ): void; getGroup( - request: protos.google.monitoring.v3.IGetGroupRequest, - callback: Callback< - protos.google.monitoring.v3.IGroup, - protos.google.monitoring.v3.IGetGroupRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.IGetGroupRequest, + callback: Callback< + protos.google.monitoring.v3.IGroup, + protos.google.monitoring.v3.IGetGroupRequest | null | undefined, + {} | null | undefined + >, + ): void; getGroup( - request?: protos.google.monitoring.v3.IGetGroupRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.monitoring.v3.IGroup, - protos.google.monitoring.v3.IGetGroupRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.monitoring.v3.IGetGroupRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.monitoring.v3.IGroup, - protos.google.monitoring.v3.IGetGroupRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.monitoring.v3.IGroup, - protos.google.monitoring.v3.IGetGroupRequest|undefined, {}|undefined - ]>|void { + protos.google.monitoring.v3.IGetGroupRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.monitoring.v3.IGroup, + protos.google.monitoring.v3.IGetGroupRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.monitoring.v3.IGroup, + protos.google.monitoring.v3.IGetGroupRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getGroup request %j', request); - const wrappedCallback: Callback< - protos.google.monitoring.v3.IGroup, - protos.google.monitoring.v3.IGetGroupRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.monitoring.v3.IGroup, + protos.google.monitoring.v3.IGetGroupRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getGroup response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.getGroup(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.monitoring.v3.IGroup, - protos.google.monitoring.v3.IGetGroupRequest|undefined, {}|undefined - ]) => { - this._log.info('getGroup response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getGroup(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.monitoring.v3.IGroup, + protos.google.monitoring.v3.IGetGroupRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getGroup response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Creates a new group. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The project in which to create the group. The format is - * `"projects/{project_id_or_number}"`. - * @param {google.monitoring.v3.Group} request.group - * Required. A group definition. It is an error to define the `name` field because - * the system assigns the name. - * @param {boolean} request.validateOnly - * If true, validate this request but do not create the group. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.monitoring.v3.Group|Group}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v3/group_service.create_group.js - * region_tag:monitoring_v3_generated_GroupService_CreateGroup_async - */ + /** + * Creates a new group. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The project in which to create the group. The format is + * `"projects/{project_id_or_number}"`. + * @param {google.monitoring.v3.Group} request.group + * Required. A group definition. It is an error to define the `name` field because + * the system assigns the name. + * @param {boolean} request.validateOnly + * If true, validate this request but do not create the group. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.monitoring.v3.Group|Group}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v3/group_service.create_group.js + * region_tag:monitoring_v3_generated_GroupService_CreateGroup_async + */ createGroup( - request?: protos.google.monitoring.v3.ICreateGroupRequest, - options?: CallOptions): - Promise<[ - protos.google.monitoring.v3.IGroup, - protos.google.monitoring.v3.ICreateGroupRequest|undefined, {}|undefined - ]>; + request?: protos.google.monitoring.v3.ICreateGroupRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.monitoring.v3.IGroup, + protos.google.monitoring.v3.ICreateGroupRequest | undefined, + {} | undefined, + ] + >; createGroup( - request: protos.google.monitoring.v3.ICreateGroupRequest, - options: CallOptions, - callback: Callback< - protos.google.monitoring.v3.IGroup, - protos.google.monitoring.v3.ICreateGroupRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.ICreateGroupRequest, + options: CallOptions, + callback: Callback< + protos.google.monitoring.v3.IGroup, + protos.google.monitoring.v3.ICreateGroupRequest | null | undefined, + {} | null | undefined + >, + ): void; createGroup( - request: protos.google.monitoring.v3.ICreateGroupRequest, - callback: Callback< - protos.google.monitoring.v3.IGroup, - protos.google.monitoring.v3.ICreateGroupRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.ICreateGroupRequest, + callback: Callback< + protos.google.monitoring.v3.IGroup, + protos.google.monitoring.v3.ICreateGroupRequest | null | undefined, + {} | null | undefined + >, + ): void; createGroup( - request?: protos.google.monitoring.v3.ICreateGroupRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.monitoring.v3.IGroup, - protos.google.monitoring.v3.ICreateGroupRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.monitoring.v3.ICreateGroupRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.monitoring.v3.IGroup, - protos.google.monitoring.v3.ICreateGroupRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.monitoring.v3.IGroup, - protos.google.monitoring.v3.ICreateGroupRequest|undefined, {}|undefined - ]>|void { + protos.google.monitoring.v3.ICreateGroupRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.monitoring.v3.IGroup, + protos.google.monitoring.v3.ICreateGroupRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.monitoring.v3.IGroup, + protos.google.monitoring.v3.ICreateGroupRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('createGroup request %j', request); - const wrappedCallback: Callback< - protos.google.monitoring.v3.IGroup, - protos.google.monitoring.v3.ICreateGroupRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.monitoring.v3.IGroup, + protos.google.monitoring.v3.ICreateGroupRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createGroup response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.createGroup(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.monitoring.v3.IGroup, - protos.google.monitoring.v3.ICreateGroupRequest|undefined, {}|undefined - ]) => { - this._log.info('createGroup response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createGroup(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.monitoring.v3.IGroup, + protos.google.monitoring.v3.ICreateGroupRequest | undefined, + {} | undefined, + ]) => { + this._log.info('createGroup response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Updates an existing group. - * You can change any group attributes except `name`. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.monitoring.v3.Group} request.group - * Required. The new definition of the group. All fields of the existing group, - * excepting `name`, are replaced with the corresponding fields of this group. - * @param {boolean} request.validateOnly - * If true, validate this request but do not update the existing group. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.monitoring.v3.Group|Group}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v3/group_service.update_group.js - * region_tag:monitoring_v3_generated_GroupService_UpdateGroup_async - */ + /** + * Updates an existing group. + * You can change any group attributes except `name`. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.monitoring.v3.Group} request.group + * Required. The new definition of the group. All fields of the existing group, + * excepting `name`, are replaced with the corresponding fields of this group. + * @param {boolean} request.validateOnly + * If true, validate this request but do not update the existing group. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.monitoring.v3.Group|Group}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v3/group_service.update_group.js + * region_tag:monitoring_v3_generated_GroupService_UpdateGroup_async + */ updateGroup( - request?: protos.google.monitoring.v3.IUpdateGroupRequest, - options?: CallOptions): - Promise<[ - protos.google.monitoring.v3.IGroup, - protos.google.monitoring.v3.IUpdateGroupRequest|undefined, {}|undefined - ]>; + request?: protos.google.monitoring.v3.IUpdateGroupRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.monitoring.v3.IGroup, + protos.google.monitoring.v3.IUpdateGroupRequest | undefined, + {} | undefined, + ] + >; updateGroup( - request: protos.google.monitoring.v3.IUpdateGroupRequest, - options: CallOptions, - callback: Callback< - protos.google.monitoring.v3.IGroup, - protos.google.monitoring.v3.IUpdateGroupRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.IUpdateGroupRequest, + options: CallOptions, + callback: Callback< + protos.google.monitoring.v3.IGroup, + protos.google.monitoring.v3.IUpdateGroupRequest | null | undefined, + {} | null | undefined + >, + ): void; updateGroup( - request: protos.google.monitoring.v3.IUpdateGroupRequest, - callback: Callback< - protos.google.monitoring.v3.IGroup, - protos.google.monitoring.v3.IUpdateGroupRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.IUpdateGroupRequest, + callback: Callback< + protos.google.monitoring.v3.IGroup, + protos.google.monitoring.v3.IUpdateGroupRequest | null | undefined, + {} | null | undefined + >, + ): void; updateGroup( - request?: protos.google.monitoring.v3.IUpdateGroupRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.monitoring.v3.IGroup, - protos.google.monitoring.v3.IUpdateGroupRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.monitoring.v3.IUpdateGroupRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.monitoring.v3.IGroup, - protos.google.monitoring.v3.IUpdateGroupRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.monitoring.v3.IGroup, - protos.google.monitoring.v3.IUpdateGroupRequest|undefined, {}|undefined - ]>|void { + protos.google.monitoring.v3.IUpdateGroupRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.monitoring.v3.IGroup, + protos.google.monitoring.v3.IUpdateGroupRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.monitoring.v3.IGroup, + protos.google.monitoring.v3.IUpdateGroupRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'group.name': request.group!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'group.name': request.group!.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateGroup request %j', request); - const wrappedCallback: Callback< - protos.google.monitoring.v3.IGroup, - protos.google.monitoring.v3.IUpdateGroupRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.monitoring.v3.IGroup, + protos.google.monitoring.v3.IUpdateGroupRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateGroup response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.updateGroup(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.monitoring.v3.IGroup, - protos.google.monitoring.v3.IUpdateGroupRequest|undefined, {}|undefined - ]) => { - this._log.info('updateGroup response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateGroup(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.monitoring.v3.IGroup, + protos.google.monitoring.v3.IUpdateGroupRequest | undefined, + {} | undefined, + ]) => { + this._log.info('updateGroup response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Deletes an existing group. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The group to delete. The format is - * `"projects/{project_id_or_number}/groups/{group_id}"`. - * @param {boolean} request.recursive - * If this field is true, then the request means to delete a group with all - * its descendants. Otherwise, the request means to delete a group only when - * it has no descendants. The default value is false. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v3/group_service.delete_group.js - * region_tag:monitoring_v3_generated_GroupService_DeleteGroup_async - */ + /** + * Deletes an existing group. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The group to delete. The format is + * `"projects/{project_id_or_number}/groups/{group_id}"`. + * @param {boolean} request.recursive + * If this field is true, then the request means to delete a group with all + * its descendants. Otherwise, the request means to delete a group only when + * it has no descendants. The default value is false. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v3/group_service.delete_group.js + * region_tag:monitoring_v3_generated_GroupService_DeleteGroup_async + */ deleteGroup( - request?: protos.google.monitoring.v3.IDeleteGroupRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.IDeleteGroupRequest|undefined, {}|undefined - ]>; + request?: protos.google.monitoring.v3.IDeleteGroupRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.monitoring.v3.IDeleteGroupRequest | undefined, + {} | undefined, + ] + >; deleteGroup( - request: protos.google.monitoring.v3.IDeleteGroupRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.IDeleteGroupRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.IDeleteGroupRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.monitoring.v3.IDeleteGroupRequest | null | undefined, + {} | null | undefined + >, + ): void; deleteGroup( - request: protos.google.monitoring.v3.IDeleteGroupRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.IDeleteGroupRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.IDeleteGroupRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.monitoring.v3.IDeleteGroupRequest | null | undefined, + {} | null | undefined + >, + ): void; deleteGroup( - request?: protos.google.monitoring.v3.IDeleteGroupRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.monitoring.v3.IDeleteGroupRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.IDeleteGroupRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.IDeleteGroupRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.IDeleteGroupRequest|undefined, {}|undefined - ]>|void { + protos.google.monitoring.v3.IDeleteGroupRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + protos.google.monitoring.v3.IDeleteGroupRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.monitoring.v3.IDeleteGroupRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('deleteGroup request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.IDeleteGroupRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + protos.google.monitoring.v3.IDeleteGroupRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteGroup response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.deleteGroup(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.IDeleteGroupRequest|undefined, {}|undefined - ]) => { - this._log.info('deleteGroup response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteGroup(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.monitoring.v3.IDeleteGroupRequest | undefined, + {} | undefined, + ]) => { + this._log.info('deleteGroup response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } - /** - * Lists the existing groups. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The project whose groups are to be listed. The format is - * `"projects/{project_id_or_number}"`. - * @param {string} request.childrenOfGroup - * A group name: `"projects/{project_id_or_number}/groups/{group_id}"`. - * Returns groups whose `parentName` field contains the group - * name. If no groups have this parent, the results are empty. - * @param {string} request.ancestorsOfGroup - * A group name: `"projects/{project_id_or_number}/groups/{group_id}"`. - * Returns groups that are ancestors of the specified group. - * The groups are returned in order, starting with the immediate parent and - * ending with the most distant ancestor. If the specified group has no - * immediate parent, the results are empty. - * @param {string} request.descendantsOfGroup - * A group name: `"projects/{project_id_or_number}/groups/{group_id}"`. - * Returns the descendants of the specified group. This is a superset of - * the results returned by the `childrenOfGroup` filter, and includes - * children-of-children, and so forth. - * @param {number} request.pageSize - * A positive number that is the maximum number of results to return. - * @param {string} request.pageToken - * If this field is not empty then it must contain the `nextPageToken` value - * returned by a previous call to this method. Using this field causes the - * method to return additional results from the previous method call. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.monitoring.v3.Group|Group}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `listGroupsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Lists the existing groups. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The project whose groups are to be listed. The format is + * `"projects/{project_id_or_number}"`. + * @param {string} request.childrenOfGroup + * A group name: `"projects/{project_id_or_number}/groups/{group_id}"`. + * Returns groups whose `parentName` field contains the group + * name. If no groups have this parent, the results are empty. + * @param {string} request.ancestorsOfGroup + * A group name: `"projects/{project_id_or_number}/groups/{group_id}"`. + * Returns groups that are ancestors of the specified group. + * The groups are returned in order, starting with the immediate parent and + * ending with the most distant ancestor. If the specified group has no + * immediate parent, the results are empty. + * @param {string} request.descendantsOfGroup + * A group name: `"projects/{project_id_or_number}/groups/{group_id}"`. + * Returns the descendants of the specified group. This is a superset of + * the results returned by the `childrenOfGroup` filter, and includes + * children-of-children, and so forth. + * @param {number} request.pageSize + * A positive number that is the maximum number of results to return. + * @param {string} request.pageToken + * If this field is not empty then it must contain the `nextPageToken` value + * returned by a previous call to this method. Using this field causes the + * method to return additional results from the previous method call. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.monitoring.v3.Group|Group}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listGroupsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listGroups( - request?: protos.google.monitoring.v3.IListGroupsRequest, - options?: CallOptions): - Promise<[ - protos.google.monitoring.v3.IGroup[], - protos.google.monitoring.v3.IListGroupsRequest|null, - protos.google.monitoring.v3.IListGroupsResponse - ]>; + request?: protos.google.monitoring.v3.IListGroupsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.monitoring.v3.IGroup[], + protos.google.monitoring.v3.IListGroupsRequest | null, + protos.google.monitoring.v3.IListGroupsResponse, + ] + >; listGroups( - request: protos.google.monitoring.v3.IListGroupsRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.monitoring.v3.IListGroupsRequest, - protos.google.monitoring.v3.IListGroupsResponse|null|undefined, - protos.google.monitoring.v3.IGroup>): void; + request: protos.google.monitoring.v3.IListGroupsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.monitoring.v3.IListGroupsRequest, + protos.google.monitoring.v3.IListGroupsResponse | null | undefined, + protos.google.monitoring.v3.IGroup + >, + ): void; listGroups( - request: protos.google.monitoring.v3.IListGroupsRequest, - callback: PaginationCallback< - protos.google.monitoring.v3.IListGroupsRequest, - protos.google.monitoring.v3.IListGroupsResponse|null|undefined, - protos.google.monitoring.v3.IGroup>): void; + request: protos.google.monitoring.v3.IListGroupsRequest, + callback: PaginationCallback< + protos.google.monitoring.v3.IListGroupsRequest, + protos.google.monitoring.v3.IListGroupsResponse | null | undefined, + protos.google.monitoring.v3.IGroup + >, + ): void; listGroups( - request?: protos.google.monitoring.v3.IListGroupsRequest, - optionsOrCallback?: CallOptions|PaginationCallback< - protos.google.monitoring.v3.IListGroupsRequest, - protos.google.monitoring.v3.IListGroupsResponse|null|undefined, - protos.google.monitoring.v3.IGroup>, - callback?: PaginationCallback< + request?: protos.google.monitoring.v3.IListGroupsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.monitoring.v3.IListGroupsRequest, - protos.google.monitoring.v3.IListGroupsResponse|null|undefined, - protos.google.monitoring.v3.IGroup>): - Promise<[ - protos.google.monitoring.v3.IGroup[], - protos.google.monitoring.v3.IListGroupsRequest|null, - protos.google.monitoring.v3.IListGroupsResponse - ]>|void { + protos.google.monitoring.v3.IListGroupsResponse | null | undefined, + protos.google.monitoring.v3.IGroup + >, + callback?: PaginationCallback< + protos.google.monitoring.v3.IListGroupsRequest, + protos.google.monitoring.v3.IListGroupsResponse | null | undefined, + protos.google.monitoring.v3.IGroup + >, + ): Promise< + [ + protos.google.monitoring.v3.IGroup[], + protos.google.monitoring.v3.IListGroupsRequest | null, + protos.google.monitoring.v3.IListGroupsResponse, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.monitoring.v3.IListGroupsRequest, - protos.google.monitoring.v3.IListGroupsResponse|null|undefined, - protos.google.monitoring.v3.IGroup>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.monitoring.v3.IListGroupsRequest, + protos.google.monitoring.v3.IListGroupsResponse | null | undefined, + protos.google.monitoring.v3.IGroup + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listGroups values %j', values); callback!(error, values, nextPageRequest, rawResponse); @@ -933,241 +1138,264 @@ export class GroupServiceClient { this._log.info('listGroups request %j', request); return this.innerApiCalls .listGroups(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.monitoring.v3.IGroup[], - protos.google.monitoring.v3.IListGroupsRequest|null, - protos.google.monitoring.v3.IListGroupsResponse - ]) => { - this._log.info('listGroups values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.monitoring.v3.IGroup[], + protos.google.monitoring.v3.IListGroupsRequest | null, + protos.google.monitoring.v3.IListGroupsResponse, + ]) => { + this._log.info('listGroups values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listGroups`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The project whose groups are to be listed. The format is - * `"projects/{project_id_or_number}"`. - * @param {string} request.childrenOfGroup - * A group name: `"projects/{project_id_or_number}/groups/{group_id}"`. - * Returns groups whose `parentName` field contains the group - * name. If no groups have this parent, the results are empty. - * @param {string} request.ancestorsOfGroup - * A group name: `"projects/{project_id_or_number}/groups/{group_id}"`. - * Returns groups that are ancestors of the specified group. - * The groups are returned in order, starting with the immediate parent and - * ending with the most distant ancestor. If the specified group has no - * immediate parent, the results are empty. - * @param {string} request.descendantsOfGroup - * A group name: `"projects/{project_id_or_number}/groups/{group_id}"`. - * Returns the descendants of the specified group. This is a superset of - * the results returned by the `childrenOfGroup` filter, and includes - * children-of-children, and so forth. - * @param {number} request.pageSize - * A positive number that is the maximum number of results to return. - * @param {string} request.pageToken - * If this field is not empty then it must contain the `nextPageToken` value - * returned by a previous call to this method. Using this field causes the - * method to return additional results from the previous method call. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.monitoring.v3.Group|Group} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `listGroupsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `listGroups`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The project whose groups are to be listed. The format is + * `"projects/{project_id_or_number}"`. + * @param {string} request.childrenOfGroup + * A group name: `"projects/{project_id_or_number}/groups/{group_id}"`. + * Returns groups whose `parentName` field contains the group + * name. If no groups have this parent, the results are empty. + * @param {string} request.ancestorsOfGroup + * A group name: `"projects/{project_id_or_number}/groups/{group_id}"`. + * Returns groups that are ancestors of the specified group. + * The groups are returned in order, starting with the immediate parent and + * ending with the most distant ancestor. If the specified group has no + * immediate parent, the results are empty. + * @param {string} request.descendantsOfGroup + * A group name: `"projects/{project_id_or_number}/groups/{group_id}"`. + * Returns the descendants of the specified group. This is a superset of + * the results returned by the `childrenOfGroup` filter, and includes + * children-of-children, and so forth. + * @param {number} request.pageSize + * A positive number that is the maximum number of results to return. + * @param {string} request.pageToken + * If this field is not empty then it must contain the `nextPageToken` value + * returned by a previous call to this method. Using this field causes the + * method to return additional results from the previous method call. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.monitoring.v3.Group|Group} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listGroupsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listGroupsStream( - request?: protos.google.monitoring.v3.IListGroupsRequest, - options?: CallOptions): - Transform{ + request?: protos.google.monitoring.v3.IListGroupsRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); const defaultCallSettings = this._defaults['listGroups']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listGroups stream %j', request); return this.descriptors.page.listGroups.createStream( this.innerApiCalls.listGroups as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listGroups`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The project whose groups are to be listed. The format is - * `"projects/{project_id_or_number}"`. - * @param {string} request.childrenOfGroup - * A group name: `"projects/{project_id_or_number}/groups/{group_id}"`. - * Returns groups whose `parentName` field contains the group - * name. If no groups have this parent, the results are empty. - * @param {string} request.ancestorsOfGroup - * A group name: `"projects/{project_id_or_number}/groups/{group_id}"`. - * Returns groups that are ancestors of the specified group. - * The groups are returned in order, starting with the immediate parent and - * ending with the most distant ancestor. If the specified group has no - * immediate parent, the results are empty. - * @param {string} request.descendantsOfGroup - * A group name: `"projects/{project_id_or_number}/groups/{group_id}"`. - * Returns the descendants of the specified group. This is a superset of - * the results returned by the `childrenOfGroup` filter, and includes - * children-of-children, and so forth. - * @param {number} request.pageSize - * A positive number that is the maximum number of results to return. - * @param {string} request.pageToken - * If this field is not empty then it must contain the `nextPageToken` value - * returned by a previous call to this method. Using this field causes the - * method to return additional results from the previous method call. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.monitoring.v3.Group|Group}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v3/group_service.list_groups.js - * region_tag:monitoring_v3_generated_GroupService_ListGroups_async - */ + /** + * Equivalent to `listGroups`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The project whose groups are to be listed. The format is + * `"projects/{project_id_or_number}"`. + * @param {string} request.childrenOfGroup + * A group name: `"projects/{project_id_or_number}/groups/{group_id}"`. + * Returns groups whose `parentName` field contains the group + * name. If no groups have this parent, the results are empty. + * @param {string} request.ancestorsOfGroup + * A group name: `"projects/{project_id_or_number}/groups/{group_id}"`. + * Returns groups that are ancestors of the specified group. + * The groups are returned in order, starting with the immediate parent and + * ending with the most distant ancestor. If the specified group has no + * immediate parent, the results are empty. + * @param {string} request.descendantsOfGroup + * A group name: `"projects/{project_id_or_number}/groups/{group_id}"`. + * Returns the descendants of the specified group. This is a superset of + * the results returned by the `childrenOfGroup` filter, and includes + * children-of-children, and so forth. + * @param {number} request.pageSize + * A positive number that is the maximum number of results to return. + * @param {string} request.pageToken + * If this field is not empty then it must contain the `nextPageToken` value + * returned by a previous call to this method. Using this field causes the + * method to return additional results from the previous method call. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.monitoring.v3.Group|Group}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v3/group_service.list_groups.js + * region_tag:monitoring_v3_generated_GroupService_ListGroups_async + */ listGroupsAsync( - request?: protos.google.monitoring.v3.IListGroupsRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.monitoring.v3.IListGroupsRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); const defaultCallSettings = this._defaults['listGroups']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listGroups iterate %j', request); return this.descriptors.page.listGroups.asyncIterate( this.innerApiCalls['listGroups'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } - /** - * Lists the monitored resources that are members of a group. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The group whose members are listed. The format is - * `"projects/{project_id_or_number}/groups/{group_id}"`. - * @param {number} request.pageSize - * A positive number that is the maximum number of results to return. - * @param {string} request.pageToken - * If this field is not empty then it must contain the `nextPageToken` value - * returned by a previous call to this method. Using this field causes the - * method to return additional results from the previous method call. - * @param {string} request.filter - * An optional [list filter](/monitoring/api/learn_more#filtering) describing - * the members to be returned. The filter may reference the type, labels, and - * metadata of monitored resources that comprise the group. - * For example, to return only resources representing Compute Engine VM - * instances, use this filter: - * - * resource.type = "gce_instance" - * @param {google.monitoring.v3.TimeInterval} request.interval - * An optional time interval for which results should be returned. Only - * members that were part of the group during the specified interval are - * included in the response. If no interval is provided then the group - * membership over the last minute is returned. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.api.MonitoredResource|MonitoredResource}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `listGroupMembersAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Lists the monitored resources that are members of a group. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The group whose members are listed. The format is + * `"projects/{project_id_or_number}/groups/{group_id}"`. + * @param {number} request.pageSize + * A positive number that is the maximum number of results to return. + * @param {string} request.pageToken + * If this field is not empty then it must contain the `nextPageToken` value + * returned by a previous call to this method. Using this field causes the + * method to return additional results from the previous method call. + * @param {string} request.filter + * An optional [list filter](/monitoring/api/learn_more#filtering) describing + * the members to be returned. The filter may reference the type, labels, and + * metadata of monitored resources that comprise the group. + * For example, to return only resources representing Compute Engine VM + * instances, use this filter: + * + * resource.type = "gce_instance" + * @param {google.monitoring.v3.TimeInterval} request.interval + * An optional time interval for which results should be returned. Only + * members that were part of the group during the specified interval are + * included in the response. If no interval is provided then the group + * membership over the last minute is returned. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.api.MonitoredResource|MonitoredResource}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listGroupMembersAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listGroupMembers( - request?: protos.google.monitoring.v3.IListGroupMembersRequest, - options?: CallOptions): - Promise<[ - protos.google.api.IMonitoredResource[], - protos.google.monitoring.v3.IListGroupMembersRequest|null, - protos.google.monitoring.v3.IListGroupMembersResponse - ]>; + request?: protos.google.monitoring.v3.IListGroupMembersRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.api.IMonitoredResource[], + protos.google.monitoring.v3.IListGroupMembersRequest | null, + protos.google.monitoring.v3.IListGroupMembersResponse, + ] + >; listGroupMembers( - request: protos.google.monitoring.v3.IListGroupMembersRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.monitoring.v3.IListGroupMembersRequest, - protos.google.monitoring.v3.IListGroupMembersResponse|null|undefined, - protos.google.api.IMonitoredResource>): void; + request: protos.google.monitoring.v3.IListGroupMembersRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.monitoring.v3.IListGroupMembersRequest, + protos.google.monitoring.v3.IListGroupMembersResponse | null | undefined, + protos.google.api.IMonitoredResource + >, + ): void; listGroupMembers( - request: protos.google.monitoring.v3.IListGroupMembersRequest, - callback: PaginationCallback< - protos.google.monitoring.v3.IListGroupMembersRequest, - protos.google.monitoring.v3.IListGroupMembersResponse|null|undefined, - protos.google.api.IMonitoredResource>): void; + request: protos.google.monitoring.v3.IListGroupMembersRequest, + callback: PaginationCallback< + protos.google.monitoring.v3.IListGroupMembersRequest, + protos.google.monitoring.v3.IListGroupMembersResponse | null | undefined, + protos.google.api.IMonitoredResource + >, + ): void; listGroupMembers( - request?: protos.google.monitoring.v3.IListGroupMembersRequest, - optionsOrCallback?: CallOptions|PaginationCallback< + request?: protos.google.monitoring.v3.IListGroupMembersRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.monitoring.v3.IListGroupMembersRequest, - protos.google.monitoring.v3.IListGroupMembersResponse|null|undefined, - protos.google.api.IMonitoredResource>, - callback?: PaginationCallback< - protos.google.monitoring.v3.IListGroupMembersRequest, - protos.google.monitoring.v3.IListGroupMembersResponse|null|undefined, - protos.google.api.IMonitoredResource>): - Promise<[ - protos.google.api.IMonitoredResource[], - protos.google.monitoring.v3.IListGroupMembersRequest|null, - protos.google.monitoring.v3.IListGroupMembersResponse - ]>|void { + | protos.google.monitoring.v3.IListGroupMembersResponse + | null + | undefined, + protos.google.api.IMonitoredResource + >, + callback?: PaginationCallback< + protos.google.monitoring.v3.IListGroupMembersRequest, + protos.google.monitoring.v3.IListGroupMembersResponse | null | undefined, + protos.google.api.IMonitoredResource + >, + ): Promise< + [ + protos.google.api.IMonitoredResource[], + protos.google.monitoring.v3.IListGroupMembersRequest | null, + protos.google.monitoring.v3.IListGroupMembersResponse, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.monitoring.v3.IListGroupMembersRequest, - protos.google.monitoring.v3.IListGroupMembersResponse|null|undefined, - protos.google.api.IMonitoredResource>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.monitoring.v3.IListGroupMembersRequest, + | protos.google.monitoring.v3.IListGroupMembersResponse + | null + | undefined, + protos.google.api.IMonitoredResource + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listGroupMembers values %j', values); callback!(error, values, nextPageRequest, rawResponse); @@ -1176,138 +1404,142 @@ export class GroupServiceClient { this._log.info('listGroupMembers request %j', request); return this.innerApiCalls .listGroupMembers(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.api.IMonitoredResource[], - protos.google.monitoring.v3.IListGroupMembersRequest|null, - protos.google.monitoring.v3.IListGroupMembersResponse - ]) => { - this._log.info('listGroupMembers values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.api.IMonitoredResource[], + protos.google.monitoring.v3.IListGroupMembersRequest | null, + protos.google.monitoring.v3.IListGroupMembersResponse, + ]) => { + this._log.info('listGroupMembers values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listGroupMembers`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The group whose members are listed. The format is - * `"projects/{project_id_or_number}/groups/{group_id}"`. - * @param {number} request.pageSize - * A positive number that is the maximum number of results to return. - * @param {string} request.pageToken - * If this field is not empty then it must contain the `nextPageToken` value - * returned by a previous call to this method. Using this field causes the - * method to return additional results from the previous method call. - * @param {string} request.filter - * An optional [list filter](/monitoring/api/learn_more#filtering) describing - * the members to be returned. The filter may reference the type, labels, and - * metadata of monitored resources that comprise the group. - * For example, to return only resources representing Compute Engine VM - * instances, use this filter: - * - * resource.type = "gce_instance" - * @param {google.monitoring.v3.TimeInterval} request.interval - * An optional time interval for which results should be returned. Only - * members that were part of the group during the specified interval are - * included in the response. If no interval is provided then the group - * membership over the last minute is returned. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.api.MonitoredResource|MonitoredResource} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `listGroupMembersAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `listGroupMembers`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The group whose members are listed. The format is + * `"projects/{project_id_or_number}/groups/{group_id}"`. + * @param {number} request.pageSize + * A positive number that is the maximum number of results to return. + * @param {string} request.pageToken + * If this field is not empty then it must contain the `nextPageToken` value + * returned by a previous call to this method. Using this field causes the + * method to return additional results from the previous method call. + * @param {string} request.filter + * An optional [list filter](/monitoring/api/learn_more#filtering) describing + * the members to be returned. The filter may reference the type, labels, and + * metadata of monitored resources that comprise the group. + * For example, to return only resources representing Compute Engine VM + * instances, use this filter: + * + * resource.type = "gce_instance" + * @param {google.monitoring.v3.TimeInterval} request.interval + * An optional time interval for which results should be returned. Only + * members that were part of the group during the specified interval are + * included in the response. If no interval is provided then the group + * membership over the last minute is returned. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.api.MonitoredResource|MonitoredResource} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listGroupMembersAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listGroupMembersStream( - request?: protos.google.monitoring.v3.IListGroupMembersRequest, - options?: CallOptions): - Transform{ + request?: protos.google.monitoring.v3.IListGroupMembersRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); const defaultCallSettings = this._defaults['listGroupMembers']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listGroupMembers stream %j', request); return this.descriptors.page.listGroupMembers.createStream( this.innerApiCalls.listGroupMembers as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listGroupMembers`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The group whose members are listed. The format is - * `"projects/{project_id_or_number}/groups/{group_id}"`. - * @param {number} request.pageSize - * A positive number that is the maximum number of results to return. - * @param {string} request.pageToken - * If this field is not empty then it must contain the `nextPageToken` value - * returned by a previous call to this method. Using this field causes the - * method to return additional results from the previous method call. - * @param {string} request.filter - * An optional [list filter](/monitoring/api/learn_more#filtering) describing - * the members to be returned. The filter may reference the type, labels, and - * metadata of monitored resources that comprise the group. - * For example, to return only resources representing Compute Engine VM - * instances, use this filter: - * - * resource.type = "gce_instance" - * @param {google.monitoring.v3.TimeInterval} request.interval - * An optional time interval for which results should be returned. Only - * members that were part of the group during the specified interval are - * included in the response. If no interval is provided then the group - * membership over the last minute is returned. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.api.MonitoredResource|MonitoredResource}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v3/group_service.list_group_members.js - * region_tag:monitoring_v3_generated_GroupService_ListGroupMembers_async - */ + /** + * Equivalent to `listGroupMembers`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The group whose members are listed. The format is + * `"projects/{project_id_or_number}/groups/{group_id}"`. + * @param {number} request.pageSize + * A positive number that is the maximum number of results to return. + * @param {string} request.pageToken + * If this field is not empty then it must contain the `nextPageToken` value + * returned by a previous call to this method. Using this field causes the + * method to return additional results from the previous method call. + * @param {string} request.filter + * An optional [list filter](/monitoring/api/learn_more#filtering) describing + * the members to be returned. The filter may reference the type, labels, and + * metadata of monitored resources that comprise the group. + * For example, to return only resources representing Compute Engine VM + * instances, use this filter: + * + * resource.type = "gce_instance" + * @param {google.monitoring.v3.TimeInterval} request.interval + * An optional time interval for which results should be returned. Only + * members that were part of the group during the specified interval are + * included in the response. If no interval is provided then the group + * membership over the last minute is returned. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.api.MonitoredResource|MonitoredResource}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v3/group_service.list_group_members.js + * region_tag:monitoring_v3_generated_GroupService_ListGroupMembers_async + */ listGroupMembersAsync( - request?: protos.google.monitoring.v3.IListGroupMembersRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.monitoring.v3.IListGroupMembersRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); const defaultCallSettings = this._defaults['listGroupMembers']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listGroupMembers iterate %j', request); return this.descriptors.page.listGroupMembers.asyncIterate( this.innerApiCalls['listGroupMembers'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } // -------------------- @@ -1321,7 +1553,7 @@ export class GroupServiceClient { * @param {string} alert_policy * @returns {string} Resource name string. */ - folderAlertPolicyPath(folder:string,alertPolicy:string) { + folderAlertPolicyPath(folder: string, alertPolicy: string) { return this.pathTemplates.folderAlertPolicyPathTemplate.render({ folder: folder, alert_policy: alertPolicy, @@ -1336,7 +1568,9 @@ export class GroupServiceClient { * @returns {string} A string representing the folder. */ matchFolderFromFolderAlertPolicyName(folderAlertPolicyName: string) { - return this.pathTemplates.folderAlertPolicyPathTemplate.match(folderAlertPolicyName).folder; + return this.pathTemplates.folderAlertPolicyPathTemplate.match( + folderAlertPolicyName, + ).folder; } /** @@ -1347,7 +1581,9 @@ export class GroupServiceClient { * @returns {string} A string representing the alert_policy. */ matchAlertPolicyFromFolderAlertPolicyName(folderAlertPolicyName: string) { - return this.pathTemplates.folderAlertPolicyPathTemplate.match(folderAlertPolicyName).alert_policy; + return this.pathTemplates.folderAlertPolicyPathTemplate.match( + folderAlertPolicyName, + ).alert_policy; } /** @@ -1358,7 +1594,11 @@ export class GroupServiceClient { * @param {string} condition * @returns {string} Resource name string. */ - folderAlertPolicyConditionPath(folder:string,alertPolicy:string,condition:string) { + folderAlertPolicyConditionPath( + folder: string, + alertPolicy: string, + condition: string, + ) { return this.pathTemplates.folderAlertPolicyConditionPathTemplate.render({ folder: folder, alert_policy: alertPolicy, @@ -1373,8 +1613,12 @@ export class GroupServiceClient { * A fully-qualified path representing folder_alert_policy_condition resource. * @returns {string} A string representing the folder. */ - matchFolderFromFolderAlertPolicyConditionName(folderAlertPolicyConditionName: string) { - return this.pathTemplates.folderAlertPolicyConditionPathTemplate.match(folderAlertPolicyConditionName).folder; + matchFolderFromFolderAlertPolicyConditionName( + folderAlertPolicyConditionName: string, + ) { + return this.pathTemplates.folderAlertPolicyConditionPathTemplate.match( + folderAlertPolicyConditionName, + ).folder; } /** @@ -1384,8 +1628,12 @@ export class GroupServiceClient { * A fully-qualified path representing folder_alert_policy_condition resource. * @returns {string} A string representing the alert_policy. */ - matchAlertPolicyFromFolderAlertPolicyConditionName(folderAlertPolicyConditionName: string) { - return this.pathTemplates.folderAlertPolicyConditionPathTemplate.match(folderAlertPolicyConditionName).alert_policy; + matchAlertPolicyFromFolderAlertPolicyConditionName( + folderAlertPolicyConditionName: string, + ) { + return this.pathTemplates.folderAlertPolicyConditionPathTemplate.match( + folderAlertPolicyConditionName, + ).alert_policy; } /** @@ -1395,8 +1643,12 @@ export class GroupServiceClient { * A fully-qualified path representing folder_alert_policy_condition resource. * @returns {string} A string representing the condition. */ - matchConditionFromFolderAlertPolicyConditionName(folderAlertPolicyConditionName: string) { - return this.pathTemplates.folderAlertPolicyConditionPathTemplate.match(folderAlertPolicyConditionName).condition; + matchConditionFromFolderAlertPolicyConditionName( + folderAlertPolicyConditionName: string, + ) { + return this.pathTemplates.folderAlertPolicyConditionPathTemplate.match( + folderAlertPolicyConditionName, + ).condition; } /** @@ -1406,7 +1658,7 @@ export class GroupServiceClient { * @param {string} channel_descriptor * @returns {string} Resource name string. */ - folderChannelDescriptorPath(folder:string,channelDescriptor:string) { + folderChannelDescriptorPath(folder: string, channelDescriptor: string) { return this.pathTemplates.folderChannelDescriptorPathTemplate.render({ folder: folder, channel_descriptor: channelDescriptor, @@ -1420,8 +1672,12 @@ export class GroupServiceClient { * A fully-qualified path representing folder_channel_descriptor resource. * @returns {string} A string representing the folder. */ - matchFolderFromFolderChannelDescriptorName(folderChannelDescriptorName: string) { - return this.pathTemplates.folderChannelDescriptorPathTemplate.match(folderChannelDescriptorName).folder; + matchFolderFromFolderChannelDescriptorName( + folderChannelDescriptorName: string, + ) { + return this.pathTemplates.folderChannelDescriptorPathTemplate.match( + folderChannelDescriptorName, + ).folder; } /** @@ -1431,8 +1687,12 @@ export class GroupServiceClient { * A fully-qualified path representing folder_channel_descriptor resource. * @returns {string} A string representing the channel_descriptor. */ - matchChannelDescriptorFromFolderChannelDescriptorName(folderChannelDescriptorName: string) { - return this.pathTemplates.folderChannelDescriptorPathTemplate.match(folderChannelDescriptorName).channel_descriptor; + matchChannelDescriptorFromFolderChannelDescriptorName( + folderChannelDescriptorName: string, + ) { + return this.pathTemplates.folderChannelDescriptorPathTemplate.match( + folderChannelDescriptorName, + ).channel_descriptor; } /** @@ -1442,7 +1702,7 @@ export class GroupServiceClient { * @param {string} group * @returns {string} Resource name string. */ - folderGroupPath(folder:string,group:string) { + folderGroupPath(folder: string, group: string) { return this.pathTemplates.folderGroupPathTemplate.render({ folder: folder, group: group, @@ -1457,7 +1717,8 @@ export class GroupServiceClient { * @returns {string} A string representing the folder. */ matchFolderFromFolderGroupName(folderGroupName: string) { - return this.pathTemplates.folderGroupPathTemplate.match(folderGroupName).folder; + return this.pathTemplates.folderGroupPathTemplate.match(folderGroupName) + .folder; } /** @@ -1468,7 +1729,8 @@ export class GroupServiceClient { * @returns {string} A string representing the group. */ matchGroupFromFolderGroupName(folderGroupName: string) { - return this.pathTemplates.folderGroupPathTemplate.match(folderGroupName).group; + return this.pathTemplates.folderGroupPathTemplate.match(folderGroupName) + .group; } /** @@ -1478,7 +1740,7 @@ export class GroupServiceClient { * @param {string} notification_channel * @returns {string} Resource name string. */ - folderNotificationChannelPath(folder:string,notificationChannel:string) { + folderNotificationChannelPath(folder: string, notificationChannel: string) { return this.pathTemplates.folderNotificationChannelPathTemplate.render({ folder: folder, notification_channel: notificationChannel, @@ -1492,8 +1754,12 @@ export class GroupServiceClient { * A fully-qualified path representing folder_notification_channel resource. * @returns {string} A string representing the folder. */ - matchFolderFromFolderNotificationChannelName(folderNotificationChannelName: string) { - return this.pathTemplates.folderNotificationChannelPathTemplate.match(folderNotificationChannelName).folder; + matchFolderFromFolderNotificationChannelName( + folderNotificationChannelName: string, + ) { + return this.pathTemplates.folderNotificationChannelPathTemplate.match( + folderNotificationChannelName, + ).folder; } /** @@ -1503,8 +1769,12 @@ export class GroupServiceClient { * A fully-qualified path representing folder_notification_channel resource. * @returns {string} A string representing the notification_channel. */ - matchNotificationChannelFromFolderNotificationChannelName(folderNotificationChannelName: string) { - return this.pathTemplates.folderNotificationChannelPathTemplate.match(folderNotificationChannelName).notification_channel; + matchNotificationChannelFromFolderNotificationChannelName( + folderNotificationChannelName: string, + ) { + return this.pathTemplates.folderNotificationChannelPathTemplate.match( + folderNotificationChannelName, + ).notification_channel; } /** @@ -1514,7 +1784,7 @@ export class GroupServiceClient { * @param {string} service * @returns {string} Resource name string. */ - folderServicePath(folder:string,service:string) { + folderServicePath(folder: string, service: string) { return this.pathTemplates.folderServicePathTemplate.render({ folder: folder, service: service, @@ -1529,7 +1799,8 @@ export class GroupServiceClient { * @returns {string} A string representing the folder. */ matchFolderFromFolderServiceName(folderServiceName: string) { - return this.pathTemplates.folderServicePathTemplate.match(folderServiceName).folder; + return this.pathTemplates.folderServicePathTemplate.match(folderServiceName) + .folder; } /** @@ -1540,7 +1811,8 @@ export class GroupServiceClient { * @returns {string} A string representing the service. */ matchServiceFromFolderServiceName(folderServiceName: string) { - return this.pathTemplates.folderServicePathTemplate.match(folderServiceName).service; + return this.pathTemplates.folderServicePathTemplate.match(folderServiceName) + .service; } /** @@ -1551,12 +1823,18 @@ export class GroupServiceClient { * @param {string} service_level_objective * @returns {string} Resource name string. */ - folderServiceServiceLevelObjectivePath(folder:string,service:string,serviceLevelObjective:string) { - return this.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.render({ - folder: folder, - service: service, - service_level_objective: serviceLevelObjective, - }); + folderServiceServiceLevelObjectivePath( + folder: string, + service: string, + serviceLevelObjective: string, + ) { + return this.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.render( + { + folder: folder, + service: service, + service_level_objective: serviceLevelObjective, + }, + ); } /** @@ -1566,8 +1844,12 @@ export class GroupServiceClient { * A fully-qualified path representing folder_service_service_level_objective resource. * @returns {string} A string representing the folder. */ - matchFolderFromFolderServiceServiceLevelObjectiveName(folderServiceServiceLevelObjectiveName: string) { - return this.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match(folderServiceServiceLevelObjectiveName).folder; + matchFolderFromFolderServiceServiceLevelObjectiveName( + folderServiceServiceLevelObjectiveName: string, + ) { + return this.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match( + folderServiceServiceLevelObjectiveName, + ).folder; } /** @@ -1577,8 +1859,12 @@ export class GroupServiceClient { * A fully-qualified path representing folder_service_service_level_objective resource. * @returns {string} A string representing the service. */ - matchServiceFromFolderServiceServiceLevelObjectiveName(folderServiceServiceLevelObjectiveName: string) { - return this.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match(folderServiceServiceLevelObjectiveName).service; + matchServiceFromFolderServiceServiceLevelObjectiveName( + folderServiceServiceLevelObjectiveName: string, + ) { + return this.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match( + folderServiceServiceLevelObjectiveName, + ).service; } /** @@ -1588,8 +1874,12 @@ export class GroupServiceClient { * A fully-qualified path representing folder_service_service_level_objective resource. * @returns {string} A string representing the service_level_objective. */ - matchServiceLevelObjectiveFromFolderServiceServiceLevelObjectiveName(folderServiceServiceLevelObjectiveName: string) { - return this.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match(folderServiceServiceLevelObjectiveName).service_level_objective; + matchServiceLevelObjectiveFromFolderServiceServiceLevelObjectiveName( + folderServiceServiceLevelObjectiveName: string, + ) { + return this.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match( + folderServiceServiceLevelObjectiveName, + ).service_level_objective; } /** @@ -1599,7 +1889,7 @@ export class GroupServiceClient { * @param {string} uptime_check_config * @returns {string} Resource name string. */ - folderUptimeCheckConfigPath(folder:string,uptimeCheckConfig:string) { + folderUptimeCheckConfigPath(folder: string, uptimeCheckConfig: string) { return this.pathTemplates.folderUptimeCheckConfigPathTemplate.render({ folder: folder, uptime_check_config: uptimeCheckConfig, @@ -1613,8 +1903,12 @@ export class GroupServiceClient { * A fully-qualified path representing folder_uptime_check_config resource. * @returns {string} A string representing the folder. */ - matchFolderFromFolderUptimeCheckConfigName(folderUptimeCheckConfigName: string) { - return this.pathTemplates.folderUptimeCheckConfigPathTemplate.match(folderUptimeCheckConfigName).folder; + matchFolderFromFolderUptimeCheckConfigName( + folderUptimeCheckConfigName: string, + ) { + return this.pathTemplates.folderUptimeCheckConfigPathTemplate.match( + folderUptimeCheckConfigName, + ).folder; } /** @@ -1624,8 +1918,12 @@ export class GroupServiceClient { * A fully-qualified path representing folder_uptime_check_config resource. * @returns {string} A string representing the uptime_check_config. */ - matchUptimeCheckConfigFromFolderUptimeCheckConfigName(folderUptimeCheckConfigName: string) { - return this.pathTemplates.folderUptimeCheckConfigPathTemplate.match(folderUptimeCheckConfigName).uptime_check_config; + matchUptimeCheckConfigFromFolderUptimeCheckConfigName( + folderUptimeCheckConfigName: string, + ) { + return this.pathTemplates.folderUptimeCheckConfigPathTemplate.match( + folderUptimeCheckConfigName, + ).uptime_check_config; } /** @@ -1635,7 +1933,7 @@ export class GroupServiceClient { * @param {string} alert_policy * @returns {string} Resource name string. */ - organizationAlertPolicyPath(organization:string,alertPolicy:string) { + organizationAlertPolicyPath(organization: string, alertPolicy: string) { return this.pathTemplates.organizationAlertPolicyPathTemplate.render({ organization: organization, alert_policy: alertPolicy, @@ -1649,8 +1947,12 @@ export class GroupServiceClient { * A fully-qualified path representing organization_alert_policy resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationAlertPolicyName(organizationAlertPolicyName: string) { - return this.pathTemplates.organizationAlertPolicyPathTemplate.match(organizationAlertPolicyName).organization; + matchOrganizationFromOrganizationAlertPolicyName( + organizationAlertPolicyName: string, + ) { + return this.pathTemplates.organizationAlertPolicyPathTemplate.match( + organizationAlertPolicyName, + ).organization; } /** @@ -1660,8 +1962,12 @@ export class GroupServiceClient { * A fully-qualified path representing organization_alert_policy resource. * @returns {string} A string representing the alert_policy. */ - matchAlertPolicyFromOrganizationAlertPolicyName(organizationAlertPolicyName: string) { - return this.pathTemplates.organizationAlertPolicyPathTemplate.match(organizationAlertPolicyName).alert_policy; + matchAlertPolicyFromOrganizationAlertPolicyName( + organizationAlertPolicyName: string, + ) { + return this.pathTemplates.organizationAlertPolicyPathTemplate.match( + organizationAlertPolicyName, + ).alert_policy; } /** @@ -1672,12 +1978,18 @@ export class GroupServiceClient { * @param {string} condition * @returns {string} Resource name string. */ - organizationAlertPolicyConditionPath(organization:string,alertPolicy:string,condition:string) { - return this.pathTemplates.organizationAlertPolicyConditionPathTemplate.render({ - organization: organization, - alert_policy: alertPolicy, - condition: condition, - }); + organizationAlertPolicyConditionPath( + organization: string, + alertPolicy: string, + condition: string, + ) { + return this.pathTemplates.organizationAlertPolicyConditionPathTemplate.render( + { + organization: organization, + alert_policy: alertPolicy, + condition: condition, + }, + ); } /** @@ -1687,8 +1999,12 @@ export class GroupServiceClient { * A fully-qualified path representing organization_alert_policy_condition resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationAlertPolicyConditionName(organizationAlertPolicyConditionName: string) { - return this.pathTemplates.organizationAlertPolicyConditionPathTemplate.match(organizationAlertPolicyConditionName).organization; + matchOrganizationFromOrganizationAlertPolicyConditionName( + organizationAlertPolicyConditionName: string, + ) { + return this.pathTemplates.organizationAlertPolicyConditionPathTemplate.match( + organizationAlertPolicyConditionName, + ).organization; } /** @@ -1698,8 +2014,12 @@ export class GroupServiceClient { * A fully-qualified path representing organization_alert_policy_condition resource. * @returns {string} A string representing the alert_policy. */ - matchAlertPolicyFromOrganizationAlertPolicyConditionName(organizationAlertPolicyConditionName: string) { - return this.pathTemplates.organizationAlertPolicyConditionPathTemplate.match(organizationAlertPolicyConditionName).alert_policy; + matchAlertPolicyFromOrganizationAlertPolicyConditionName( + organizationAlertPolicyConditionName: string, + ) { + return this.pathTemplates.organizationAlertPolicyConditionPathTemplate.match( + organizationAlertPolicyConditionName, + ).alert_policy; } /** @@ -1709,8 +2029,12 @@ export class GroupServiceClient { * A fully-qualified path representing organization_alert_policy_condition resource. * @returns {string} A string representing the condition. */ - matchConditionFromOrganizationAlertPolicyConditionName(organizationAlertPolicyConditionName: string) { - return this.pathTemplates.organizationAlertPolicyConditionPathTemplate.match(organizationAlertPolicyConditionName).condition; + matchConditionFromOrganizationAlertPolicyConditionName( + organizationAlertPolicyConditionName: string, + ) { + return this.pathTemplates.organizationAlertPolicyConditionPathTemplate.match( + organizationAlertPolicyConditionName, + ).condition; } /** @@ -1720,7 +2044,10 @@ export class GroupServiceClient { * @param {string} channel_descriptor * @returns {string} Resource name string. */ - organizationChannelDescriptorPath(organization:string,channelDescriptor:string) { + organizationChannelDescriptorPath( + organization: string, + channelDescriptor: string, + ) { return this.pathTemplates.organizationChannelDescriptorPathTemplate.render({ organization: organization, channel_descriptor: channelDescriptor, @@ -1734,8 +2061,12 @@ export class GroupServiceClient { * A fully-qualified path representing organization_channel_descriptor resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationChannelDescriptorName(organizationChannelDescriptorName: string) { - return this.pathTemplates.organizationChannelDescriptorPathTemplate.match(organizationChannelDescriptorName).organization; + matchOrganizationFromOrganizationChannelDescriptorName( + organizationChannelDescriptorName: string, + ) { + return this.pathTemplates.organizationChannelDescriptorPathTemplate.match( + organizationChannelDescriptorName, + ).organization; } /** @@ -1745,8 +2076,12 @@ export class GroupServiceClient { * A fully-qualified path representing organization_channel_descriptor resource. * @returns {string} A string representing the channel_descriptor. */ - matchChannelDescriptorFromOrganizationChannelDescriptorName(organizationChannelDescriptorName: string) { - return this.pathTemplates.organizationChannelDescriptorPathTemplate.match(organizationChannelDescriptorName).channel_descriptor; + matchChannelDescriptorFromOrganizationChannelDescriptorName( + organizationChannelDescriptorName: string, + ) { + return this.pathTemplates.organizationChannelDescriptorPathTemplate.match( + organizationChannelDescriptorName, + ).channel_descriptor; } /** @@ -1756,7 +2091,7 @@ export class GroupServiceClient { * @param {string} group * @returns {string} Resource name string. */ - organizationGroupPath(organization:string,group:string) { + organizationGroupPath(organization: string, group: string) { return this.pathTemplates.organizationGroupPathTemplate.render({ organization: organization, group: group, @@ -1771,7 +2106,9 @@ export class GroupServiceClient { * @returns {string} A string representing the organization. */ matchOrganizationFromOrganizationGroupName(organizationGroupName: string) { - return this.pathTemplates.organizationGroupPathTemplate.match(organizationGroupName).organization; + return this.pathTemplates.organizationGroupPathTemplate.match( + organizationGroupName, + ).organization; } /** @@ -1782,7 +2119,9 @@ export class GroupServiceClient { * @returns {string} A string representing the group. */ matchGroupFromOrganizationGroupName(organizationGroupName: string) { - return this.pathTemplates.organizationGroupPathTemplate.match(organizationGroupName).group; + return this.pathTemplates.organizationGroupPathTemplate.match( + organizationGroupName, + ).group; } /** @@ -1792,11 +2131,16 @@ export class GroupServiceClient { * @param {string} notification_channel * @returns {string} Resource name string. */ - organizationNotificationChannelPath(organization:string,notificationChannel:string) { - return this.pathTemplates.organizationNotificationChannelPathTemplate.render({ - organization: organization, - notification_channel: notificationChannel, - }); + organizationNotificationChannelPath( + organization: string, + notificationChannel: string, + ) { + return this.pathTemplates.organizationNotificationChannelPathTemplate.render( + { + organization: organization, + notification_channel: notificationChannel, + }, + ); } /** @@ -1806,8 +2150,12 @@ export class GroupServiceClient { * A fully-qualified path representing organization_notification_channel resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationNotificationChannelName(organizationNotificationChannelName: string) { - return this.pathTemplates.organizationNotificationChannelPathTemplate.match(organizationNotificationChannelName).organization; + matchOrganizationFromOrganizationNotificationChannelName( + organizationNotificationChannelName: string, + ) { + return this.pathTemplates.organizationNotificationChannelPathTemplate.match( + organizationNotificationChannelName, + ).organization; } /** @@ -1817,8 +2165,12 @@ export class GroupServiceClient { * A fully-qualified path representing organization_notification_channel resource. * @returns {string} A string representing the notification_channel. */ - matchNotificationChannelFromOrganizationNotificationChannelName(organizationNotificationChannelName: string) { - return this.pathTemplates.organizationNotificationChannelPathTemplate.match(organizationNotificationChannelName).notification_channel; + matchNotificationChannelFromOrganizationNotificationChannelName( + organizationNotificationChannelName: string, + ) { + return this.pathTemplates.organizationNotificationChannelPathTemplate.match( + organizationNotificationChannelName, + ).notification_channel; } /** @@ -1828,7 +2180,7 @@ export class GroupServiceClient { * @param {string} service * @returns {string} Resource name string. */ - organizationServicePath(organization:string,service:string) { + organizationServicePath(organization: string, service: string) { return this.pathTemplates.organizationServicePathTemplate.render({ organization: organization, service: service, @@ -1842,8 +2194,12 @@ export class GroupServiceClient { * A fully-qualified path representing organization_service resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationServiceName(organizationServiceName: string) { - return this.pathTemplates.organizationServicePathTemplate.match(organizationServiceName).organization; + matchOrganizationFromOrganizationServiceName( + organizationServiceName: string, + ) { + return this.pathTemplates.organizationServicePathTemplate.match( + organizationServiceName, + ).organization; } /** @@ -1854,7 +2210,9 @@ export class GroupServiceClient { * @returns {string} A string representing the service. */ matchServiceFromOrganizationServiceName(organizationServiceName: string) { - return this.pathTemplates.organizationServicePathTemplate.match(organizationServiceName).service; + return this.pathTemplates.organizationServicePathTemplate.match( + organizationServiceName, + ).service; } /** @@ -1865,12 +2223,18 @@ export class GroupServiceClient { * @param {string} service_level_objective * @returns {string} Resource name string. */ - organizationServiceServiceLevelObjectivePath(organization:string,service:string,serviceLevelObjective:string) { - return this.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.render({ - organization: organization, - service: service, - service_level_objective: serviceLevelObjective, - }); + organizationServiceServiceLevelObjectivePath( + organization: string, + service: string, + serviceLevelObjective: string, + ) { + return this.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.render( + { + organization: organization, + service: service, + service_level_objective: serviceLevelObjective, + }, + ); } /** @@ -1880,8 +2244,12 @@ export class GroupServiceClient { * A fully-qualified path representing organization_service_service_level_objective resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationServiceServiceLevelObjectiveName(organizationServiceServiceLevelObjectiveName: string) { - return this.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match(organizationServiceServiceLevelObjectiveName).organization; + matchOrganizationFromOrganizationServiceServiceLevelObjectiveName( + organizationServiceServiceLevelObjectiveName: string, + ) { + return this.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match( + organizationServiceServiceLevelObjectiveName, + ).organization; } /** @@ -1891,8 +2259,12 @@ export class GroupServiceClient { * A fully-qualified path representing organization_service_service_level_objective resource. * @returns {string} A string representing the service. */ - matchServiceFromOrganizationServiceServiceLevelObjectiveName(organizationServiceServiceLevelObjectiveName: string) { - return this.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match(organizationServiceServiceLevelObjectiveName).service; + matchServiceFromOrganizationServiceServiceLevelObjectiveName( + organizationServiceServiceLevelObjectiveName: string, + ) { + return this.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match( + organizationServiceServiceLevelObjectiveName, + ).service; } /** @@ -1902,8 +2274,12 @@ export class GroupServiceClient { * A fully-qualified path representing organization_service_service_level_objective resource. * @returns {string} A string representing the service_level_objective. */ - matchServiceLevelObjectiveFromOrganizationServiceServiceLevelObjectiveName(organizationServiceServiceLevelObjectiveName: string) { - return this.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match(organizationServiceServiceLevelObjectiveName).service_level_objective; + matchServiceLevelObjectiveFromOrganizationServiceServiceLevelObjectiveName( + organizationServiceServiceLevelObjectiveName: string, + ) { + return this.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match( + organizationServiceServiceLevelObjectiveName, + ).service_level_objective; } /** @@ -1913,7 +2289,10 @@ export class GroupServiceClient { * @param {string} uptime_check_config * @returns {string} Resource name string. */ - organizationUptimeCheckConfigPath(organization:string,uptimeCheckConfig:string) { + organizationUptimeCheckConfigPath( + organization: string, + uptimeCheckConfig: string, + ) { return this.pathTemplates.organizationUptimeCheckConfigPathTemplate.render({ organization: organization, uptime_check_config: uptimeCheckConfig, @@ -1927,8 +2306,12 @@ export class GroupServiceClient { * A fully-qualified path representing organization_uptime_check_config resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationUptimeCheckConfigName(organizationUptimeCheckConfigName: string) { - return this.pathTemplates.organizationUptimeCheckConfigPathTemplate.match(organizationUptimeCheckConfigName).organization; + matchOrganizationFromOrganizationUptimeCheckConfigName( + organizationUptimeCheckConfigName: string, + ) { + return this.pathTemplates.organizationUptimeCheckConfigPathTemplate.match( + organizationUptimeCheckConfigName, + ).organization; } /** @@ -1938,8 +2321,12 @@ export class GroupServiceClient { * A fully-qualified path representing organization_uptime_check_config resource. * @returns {string} A string representing the uptime_check_config. */ - matchUptimeCheckConfigFromOrganizationUptimeCheckConfigName(organizationUptimeCheckConfigName: string) { - return this.pathTemplates.organizationUptimeCheckConfigPathTemplate.match(organizationUptimeCheckConfigName).uptime_check_config; + matchUptimeCheckConfigFromOrganizationUptimeCheckConfigName( + organizationUptimeCheckConfigName: string, + ) { + return this.pathTemplates.organizationUptimeCheckConfigPathTemplate.match( + organizationUptimeCheckConfigName, + ).uptime_check_config; } /** @@ -1949,7 +2336,7 @@ export class GroupServiceClient { * @param {string} alert_policy * @returns {string} Resource name string. */ - projectAlertPolicyPath(project:string,alertPolicy:string) { + projectAlertPolicyPath(project: string, alertPolicy: string) { return this.pathTemplates.projectAlertPolicyPathTemplate.render({ project: project, alert_policy: alertPolicy, @@ -1964,7 +2351,9 @@ export class GroupServiceClient { * @returns {string} A string representing the project. */ matchProjectFromProjectAlertPolicyName(projectAlertPolicyName: string) { - return this.pathTemplates.projectAlertPolicyPathTemplate.match(projectAlertPolicyName).project; + return this.pathTemplates.projectAlertPolicyPathTemplate.match( + projectAlertPolicyName, + ).project; } /** @@ -1975,7 +2364,9 @@ export class GroupServiceClient { * @returns {string} A string representing the alert_policy. */ matchAlertPolicyFromProjectAlertPolicyName(projectAlertPolicyName: string) { - return this.pathTemplates.projectAlertPolicyPathTemplate.match(projectAlertPolicyName).alert_policy; + return this.pathTemplates.projectAlertPolicyPathTemplate.match( + projectAlertPolicyName, + ).alert_policy; } /** @@ -1986,7 +2377,11 @@ export class GroupServiceClient { * @param {string} condition * @returns {string} Resource name string. */ - projectAlertPolicyConditionPath(project:string,alertPolicy:string,condition:string) { + projectAlertPolicyConditionPath( + project: string, + alertPolicy: string, + condition: string, + ) { return this.pathTemplates.projectAlertPolicyConditionPathTemplate.render({ project: project, alert_policy: alertPolicy, @@ -2001,8 +2396,12 @@ export class GroupServiceClient { * A fully-qualified path representing project_alert_policy_condition resource. * @returns {string} A string representing the project. */ - matchProjectFromProjectAlertPolicyConditionName(projectAlertPolicyConditionName: string) { - return this.pathTemplates.projectAlertPolicyConditionPathTemplate.match(projectAlertPolicyConditionName).project; + matchProjectFromProjectAlertPolicyConditionName( + projectAlertPolicyConditionName: string, + ) { + return this.pathTemplates.projectAlertPolicyConditionPathTemplate.match( + projectAlertPolicyConditionName, + ).project; } /** @@ -2012,8 +2411,12 @@ export class GroupServiceClient { * A fully-qualified path representing project_alert_policy_condition resource. * @returns {string} A string representing the alert_policy. */ - matchAlertPolicyFromProjectAlertPolicyConditionName(projectAlertPolicyConditionName: string) { - return this.pathTemplates.projectAlertPolicyConditionPathTemplate.match(projectAlertPolicyConditionName).alert_policy; + matchAlertPolicyFromProjectAlertPolicyConditionName( + projectAlertPolicyConditionName: string, + ) { + return this.pathTemplates.projectAlertPolicyConditionPathTemplate.match( + projectAlertPolicyConditionName, + ).alert_policy; } /** @@ -2023,8 +2426,12 @@ export class GroupServiceClient { * A fully-qualified path representing project_alert_policy_condition resource. * @returns {string} A string representing the condition. */ - matchConditionFromProjectAlertPolicyConditionName(projectAlertPolicyConditionName: string) { - return this.pathTemplates.projectAlertPolicyConditionPathTemplate.match(projectAlertPolicyConditionName).condition; + matchConditionFromProjectAlertPolicyConditionName( + projectAlertPolicyConditionName: string, + ) { + return this.pathTemplates.projectAlertPolicyConditionPathTemplate.match( + projectAlertPolicyConditionName, + ).condition; } /** @@ -2034,7 +2441,7 @@ export class GroupServiceClient { * @param {string} channel_descriptor * @returns {string} Resource name string. */ - projectChannelDescriptorPath(project:string,channelDescriptor:string) { + projectChannelDescriptorPath(project: string, channelDescriptor: string) { return this.pathTemplates.projectChannelDescriptorPathTemplate.render({ project: project, channel_descriptor: channelDescriptor, @@ -2048,8 +2455,12 @@ export class GroupServiceClient { * A fully-qualified path representing project_channel_descriptor resource. * @returns {string} A string representing the project. */ - matchProjectFromProjectChannelDescriptorName(projectChannelDescriptorName: string) { - return this.pathTemplates.projectChannelDescriptorPathTemplate.match(projectChannelDescriptorName).project; + matchProjectFromProjectChannelDescriptorName( + projectChannelDescriptorName: string, + ) { + return this.pathTemplates.projectChannelDescriptorPathTemplate.match( + projectChannelDescriptorName, + ).project; } /** @@ -2059,8 +2470,12 @@ export class GroupServiceClient { * A fully-qualified path representing project_channel_descriptor resource. * @returns {string} A string representing the channel_descriptor. */ - matchChannelDescriptorFromProjectChannelDescriptorName(projectChannelDescriptorName: string) { - return this.pathTemplates.projectChannelDescriptorPathTemplate.match(projectChannelDescriptorName).channel_descriptor; + matchChannelDescriptorFromProjectChannelDescriptorName( + projectChannelDescriptorName: string, + ) { + return this.pathTemplates.projectChannelDescriptorPathTemplate.match( + projectChannelDescriptorName, + ).channel_descriptor; } /** @@ -2070,7 +2485,7 @@ export class GroupServiceClient { * @param {string} group * @returns {string} Resource name string. */ - projectGroupPath(project:string,group:string) { + projectGroupPath(project: string, group: string) { return this.pathTemplates.projectGroupPathTemplate.render({ project: project, group: group, @@ -2085,7 +2500,8 @@ export class GroupServiceClient { * @returns {string} A string representing the project. */ matchProjectFromProjectGroupName(projectGroupName: string) { - return this.pathTemplates.projectGroupPathTemplate.match(projectGroupName).project; + return this.pathTemplates.projectGroupPathTemplate.match(projectGroupName) + .project; } /** @@ -2096,7 +2512,8 @@ export class GroupServiceClient { * @returns {string} A string representing the group. */ matchGroupFromProjectGroupName(projectGroupName: string) { - return this.pathTemplates.projectGroupPathTemplate.match(projectGroupName).group; + return this.pathTemplates.projectGroupPathTemplate.match(projectGroupName) + .group; } /** @@ -2106,7 +2523,7 @@ export class GroupServiceClient { * @param {string} notification_channel * @returns {string} Resource name string. */ - projectNotificationChannelPath(project:string,notificationChannel:string) { + projectNotificationChannelPath(project: string, notificationChannel: string) { return this.pathTemplates.projectNotificationChannelPathTemplate.render({ project: project, notification_channel: notificationChannel, @@ -2120,8 +2537,12 @@ export class GroupServiceClient { * A fully-qualified path representing project_notification_channel resource. * @returns {string} A string representing the project. */ - matchProjectFromProjectNotificationChannelName(projectNotificationChannelName: string) { - return this.pathTemplates.projectNotificationChannelPathTemplate.match(projectNotificationChannelName).project; + matchProjectFromProjectNotificationChannelName( + projectNotificationChannelName: string, + ) { + return this.pathTemplates.projectNotificationChannelPathTemplate.match( + projectNotificationChannelName, + ).project; } /** @@ -2131,8 +2552,12 @@ export class GroupServiceClient { * A fully-qualified path representing project_notification_channel resource. * @returns {string} A string representing the notification_channel. */ - matchNotificationChannelFromProjectNotificationChannelName(projectNotificationChannelName: string) { - return this.pathTemplates.projectNotificationChannelPathTemplate.match(projectNotificationChannelName).notification_channel; + matchNotificationChannelFromProjectNotificationChannelName( + projectNotificationChannelName: string, + ) { + return this.pathTemplates.projectNotificationChannelPathTemplate.match( + projectNotificationChannelName, + ).notification_channel; } /** @@ -2142,7 +2567,7 @@ export class GroupServiceClient { * @param {string} service * @returns {string} Resource name string. */ - projectServicePath(project:string,service:string) { + projectServicePath(project: string, service: string) { return this.pathTemplates.projectServicePathTemplate.render({ project: project, service: service, @@ -2157,7 +2582,9 @@ export class GroupServiceClient { * @returns {string} A string representing the project. */ matchProjectFromProjectServiceName(projectServiceName: string) { - return this.pathTemplates.projectServicePathTemplate.match(projectServiceName).project; + return this.pathTemplates.projectServicePathTemplate.match( + projectServiceName, + ).project; } /** @@ -2168,7 +2595,9 @@ export class GroupServiceClient { * @returns {string} A string representing the service. */ matchServiceFromProjectServiceName(projectServiceName: string) { - return this.pathTemplates.projectServicePathTemplate.match(projectServiceName).service; + return this.pathTemplates.projectServicePathTemplate.match( + projectServiceName, + ).service; } /** @@ -2179,12 +2608,18 @@ export class GroupServiceClient { * @param {string} service_level_objective * @returns {string} Resource name string. */ - projectServiceServiceLevelObjectivePath(project:string,service:string,serviceLevelObjective:string) { - return this.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.render({ - project: project, - service: service, - service_level_objective: serviceLevelObjective, - }); + projectServiceServiceLevelObjectivePath( + project: string, + service: string, + serviceLevelObjective: string, + ) { + return this.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.render( + { + project: project, + service: service, + service_level_objective: serviceLevelObjective, + }, + ); } /** @@ -2194,8 +2629,12 @@ export class GroupServiceClient { * A fully-qualified path representing project_service_service_level_objective resource. * @returns {string} A string representing the project. */ - matchProjectFromProjectServiceServiceLevelObjectiveName(projectServiceServiceLevelObjectiveName: string) { - return this.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match(projectServiceServiceLevelObjectiveName).project; + matchProjectFromProjectServiceServiceLevelObjectiveName( + projectServiceServiceLevelObjectiveName: string, + ) { + return this.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match( + projectServiceServiceLevelObjectiveName, + ).project; } /** @@ -2205,8 +2644,12 @@ export class GroupServiceClient { * A fully-qualified path representing project_service_service_level_objective resource. * @returns {string} A string representing the service. */ - matchServiceFromProjectServiceServiceLevelObjectiveName(projectServiceServiceLevelObjectiveName: string) { - return this.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match(projectServiceServiceLevelObjectiveName).service; + matchServiceFromProjectServiceServiceLevelObjectiveName( + projectServiceServiceLevelObjectiveName: string, + ) { + return this.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match( + projectServiceServiceLevelObjectiveName, + ).service; } /** @@ -2216,8 +2659,12 @@ export class GroupServiceClient { * A fully-qualified path representing project_service_service_level_objective resource. * @returns {string} A string representing the service_level_objective. */ - matchServiceLevelObjectiveFromProjectServiceServiceLevelObjectiveName(projectServiceServiceLevelObjectiveName: string) { - return this.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match(projectServiceServiceLevelObjectiveName).service_level_objective; + matchServiceLevelObjectiveFromProjectServiceServiceLevelObjectiveName( + projectServiceServiceLevelObjectiveName: string, + ) { + return this.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match( + projectServiceServiceLevelObjectiveName, + ).service_level_objective; } /** @@ -2227,7 +2674,7 @@ export class GroupServiceClient { * @param {string} uptime_check_config * @returns {string} Resource name string. */ - projectUptimeCheckConfigPath(project:string,uptimeCheckConfig:string) { + projectUptimeCheckConfigPath(project: string, uptimeCheckConfig: string) { return this.pathTemplates.projectUptimeCheckConfigPathTemplate.render({ project: project, uptime_check_config: uptimeCheckConfig, @@ -2241,8 +2688,12 @@ export class GroupServiceClient { * A fully-qualified path representing project_uptime_check_config resource. * @returns {string} A string representing the project. */ - matchProjectFromProjectUptimeCheckConfigName(projectUptimeCheckConfigName: string) { - return this.pathTemplates.projectUptimeCheckConfigPathTemplate.match(projectUptimeCheckConfigName).project; + matchProjectFromProjectUptimeCheckConfigName( + projectUptimeCheckConfigName: string, + ) { + return this.pathTemplates.projectUptimeCheckConfigPathTemplate.match( + projectUptimeCheckConfigName, + ).project; } /** @@ -2252,8 +2703,12 @@ export class GroupServiceClient { * A fully-qualified path representing project_uptime_check_config resource. * @returns {string} A string representing the uptime_check_config. */ - matchUptimeCheckConfigFromProjectUptimeCheckConfigName(projectUptimeCheckConfigName: string) { - return this.pathTemplates.projectUptimeCheckConfigPathTemplate.match(projectUptimeCheckConfigName).uptime_check_config; + matchUptimeCheckConfigFromProjectUptimeCheckConfigName( + projectUptimeCheckConfigName: string, + ) { + return this.pathTemplates.projectUptimeCheckConfigPathTemplate.match( + projectUptimeCheckConfigName, + ).uptime_check_config; } /** @@ -2264,7 +2719,7 @@ export class GroupServiceClient { */ close(): Promise { if (this.groupServiceStub && !this._terminated) { - return this.groupServiceStub.then(stub => { + return this.groupServiceStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -2272,4 +2727,4 @@ export class GroupServiceClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/core/generator/gapic-generator-typescript/baselines/monitoring-esm/esm/src/v3/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/monitoring-esm/esm/src/v3/index.ts.baseline index 90525166d49a..db812cd070ac 100644 --- a/core/generator/gapic-generator-typescript/baselines/monitoring-esm/esm/src/v3/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/monitoring-esm/esm/src/v3/index.ts.baseline @@ -16,9 +16,9 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -export {AlertPolicyServiceClient} from './alert_policy_service_client.js'; -export {GroupServiceClient} from './group_service_client.js'; -export {MetricServiceClient} from './metric_service_client.js'; -export {NotificationChannelServiceClient} from './notification_channel_service_client.js'; -export {ServiceMonitoringServiceClient} from './service_monitoring_service_client.js'; -export {UptimeCheckServiceClient} from './uptime_check_service_client.js'; +export { AlertPolicyServiceClient } from './alert_policy_service_client.js'; +export { GroupServiceClient } from './group_service_client.js'; +export { MetricServiceClient } from './metric_service_client.js'; +export { NotificationChannelServiceClient } from './notification_channel_service_client.js'; +export { ServiceMonitoringServiceClient } from './service_monitoring_service_client.js'; +export { UptimeCheckServiceClient } from './uptime_check_service_client.js'; diff --git a/core/generator/gapic-generator-typescript/baselines/monitoring-esm/esm/src/v3/metric_service_client.ts.baseline b/core/generator/gapic-generator-typescript/baselines/monitoring-esm/esm/src/v3/metric_service_client.ts.baseline index 20932e97b055..23a0217edd27 100644 --- a/core/generator/gapic-generator-typescript/baselines/monitoring-esm/esm/src/v3/metric_service_client.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/monitoring-esm/esm/src/v3/metric_service_client.ts.baseline @@ -18,15 +18,22 @@ /* global window */ import * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions, PaginationCallback, GaxCall} from 'google-gax'; -import {Transform} from 'stream'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + PaginationCallback, + GaxCall, +} from 'google-gax'; +import { Transform } from 'stream'; // @ts-ignore import type * as protos from '../../../protos/protos.js'; import * as metric_service_client_config from './metric_service_client_config.json'; import fs from 'fs'; import path from 'path'; -import {fileURLToPath} from 'url'; -import {getJSON} from '../json-helper.cjs'; +import { fileURLToPath } from 'url'; +import { getJSON } from '../json-helper.cjs'; // @ts-ignore const dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -36,15 +43,15 @@ const dirname = path.dirname(fileURLToPath(import.meta.url)); * This file defines retry strategy and timeouts for all API methods in this library. */ const gapicConfig = getJSON( - path.join(dirname, 'metric_service_client_config.json') + path.join(dirname, 'metric_service_client_config.json'), ); const jsonProtos = getJSON( - path.join(dirname, '..', '..', '..', 'protos/protos.json') + path.join(dirname, '..', '..', '..', 'protos/protos.json'), ); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; const version = getJSON( - path.join(dirname, '..', '..', '..', '..', 'package.json') + path.join(dirname, '..', '..', '..', '..', 'package.json'), ).version; /** @@ -60,7 +67,7 @@ export class MetricServiceClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('monitoring'); @@ -72,9 +79,9 @@ export class MetricServiceClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; - metricServiceStub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; + metricServiceStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of MetricServiceClient. @@ -116,21 +123,42 @@ export class MetricServiceClient { * const client = new MetricServiceClient({fallback: 'rest'}, gax); * ``` */ - constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { // Ensure that options include all the required fields. const staticMembers = this.constructor as typeof MetricServiceClient; - if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { - throw new Error('Please set either universe_domain or universeDomain, but not both.'); + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); } - const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; - this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; this._servicePath = 'monitoring.' + this._universeDomain; - const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; - const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. if (servicePath !== this._servicePath && !('scopes' in opts)) { @@ -152,7 +180,7 @@ export class MetricServiceClient { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; @@ -169,10 +197,7 @@ export class MetricServiceClient { const isEsm = true; const isEsmString = isEsm ? '-esm' : '-cjs'; // Determine the client header string. - const clientHeader = [ - `gax/${this._gaxModule.version}`, - `gapic/${version}`, - ]; + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/{process.versions.node}${isEsmString}`); } else { @@ -180,7 +205,7 @@ export class MetricServiceClient { } if (!opts.fallback) { clientHeader.push(`grpc/${this._gaxGrpc.grpcVersion}`); - } else if (opts.fallback === 'rest' ) { + } else if (opts.fallback === 'rest') { clientHeader.push(`rest/${this._gaxGrpc.grpcVersion}`); } if (opts.libName && opts.libVersion) { @@ -188,101 +213,114 @@ export class MetricServiceClient { } // Load the applicable protos. - this._protos = this._gaxGrpc.loadProtoJSON(jsonProtos as gax.protobuf.INamespace); + this._protos = this._gaxGrpc.loadProtoJSON( + jsonProtos as gax.protobuf.INamespace, + ); // This API contains "path templates"; forward-slash-separated // identifiers to uniquely identify resources within the API. // Create useful helper objects for these. this.pathTemplates = { folderAlertPolicyPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/alertPolicies/{alert_policy}' + 'folders/{folder}/alertPolicies/{alert_policy}', ), folderAlertPolicyConditionPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/alertPolicies/{alert_policy}/conditions/{condition}' + 'folders/{folder}/alertPolicies/{alert_policy}/conditions/{condition}', ), folderChannelDescriptorPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/notificationChannelDescriptors/{channel_descriptor}' + 'folders/{folder}/notificationChannelDescriptors/{channel_descriptor}', ), folderGroupPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/groups/{group}' + 'folders/{folder}/groups/{group}', ), folderMetricDescriptorPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/metricDescriptors/{metric_descriptor=**}' - ), - folderMonitoredResourceDescriptorPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/monitoredResourceDescriptors/{monitored_resource_descriptor}' + 'folders/{folder}/metricDescriptors/{metric_descriptor=**}', ), + folderMonitoredResourceDescriptorPathTemplate: + new this._gaxModule.PathTemplate( + 'folders/{folder}/monitoredResourceDescriptors/{monitored_resource_descriptor}', + ), folderNotificationChannelPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/notificationChannels/{notification_channel}' + 'folders/{folder}/notificationChannels/{notification_channel}', ), folderServicePathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/services/{service}' - ), - folderServiceServiceLevelObjectivePathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/services/{service}/serviceLevelObjectives/{service_level_objective}' + 'folders/{folder}/services/{service}', ), + folderServiceServiceLevelObjectivePathTemplate: + new this._gaxModule.PathTemplate( + 'folders/{folder}/services/{service}/serviceLevelObjectives/{service_level_objective}', + ), folderUptimeCheckConfigPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/uptimeCheckConfigs/{uptime_check_config}' + 'folders/{folder}/uptimeCheckConfigs/{uptime_check_config}', ), organizationAlertPolicyPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/alertPolicies/{alert_policy}' - ), - organizationAlertPolicyConditionPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/alertPolicies/{alert_policy}/conditions/{condition}' - ), - organizationChannelDescriptorPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/notificationChannelDescriptors/{channel_descriptor}' + 'organizations/{organization}/alertPolicies/{alert_policy}', ), + organizationAlertPolicyConditionPathTemplate: + new this._gaxModule.PathTemplate( + 'organizations/{organization}/alertPolicies/{alert_policy}/conditions/{condition}', + ), + organizationChannelDescriptorPathTemplate: + new this._gaxModule.PathTemplate( + 'organizations/{organization}/notificationChannelDescriptors/{channel_descriptor}', + ), organizationGroupPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/groups/{group}' - ), - organizationMetricDescriptorPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/metricDescriptors/{metric_descriptor=**}' - ), - organizationMonitoredResourceDescriptorPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/monitoredResourceDescriptors/{monitored_resource_descriptor}' - ), - organizationNotificationChannelPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/notificationChannels/{notification_channel}' + 'organizations/{organization}/groups/{group}', ), + organizationMetricDescriptorPathTemplate: + new this._gaxModule.PathTemplate( + 'organizations/{organization}/metricDescriptors/{metric_descriptor=**}', + ), + organizationMonitoredResourceDescriptorPathTemplate: + new this._gaxModule.PathTemplate( + 'organizations/{organization}/monitoredResourceDescriptors/{monitored_resource_descriptor}', + ), + organizationNotificationChannelPathTemplate: + new this._gaxModule.PathTemplate( + 'organizations/{organization}/notificationChannels/{notification_channel}', + ), organizationServicePathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/services/{service}' - ), - organizationServiceServiceLevelObjectivePathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/services/{service}/serviceLevelObjectives/{service_level_objective}' - ), - organizationUptimeCheckConfigPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/uptimeCheckConfigs/{uptime_check_config}' + 'organizations/{organization}/services/{service}', ), + organizationServiceServiceLevelObjectivePathTemplate: + new this._gaxModule.PathTemplate( + 'organizations/{organization}/services/{service}/serviceLevelObjectives/{service_level_objective}', + ), + organizationUptimeCheckConfigPathTemplate: + new this._gaxModule.PathTemplate( + 'organizations/{organization}/uptimeCheckConfigs/{uptime_check_config}', + ), projectAlertPolicyPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/alertPolicies/{alert_policy}' + 'projects/{project}/alertPolicies/{alert_policy}', ), projectAlertPolicyConditionPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/alertPolicies/{alert_policy}/conditions/{condition}' + 'projects/{project}/alertPolicies/{alert_policy}/conditions/{condition}', ), projectChannelDescriptorPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/notificationChannelDescriptors/{channel_descriptor}' + 'projects/{project}/notificationChannelDescriptors/{channel_descriptor}', ), projectGroupPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/groups/{group}' + 'projects/{project}/groups/{group}', ), projectMetricDescriptorPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/metricDescriptors/{metric_descriptor=**}' - ), - projectMonitoredResourceDescriptorPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/monitoredResourceDescriptors/{monitored_resource_descriptor}' + 'projects/{project}/metricDescriptors/{metric_descriptor=**}', ), + projectMonitoredResourceDescriptorPathTemplate: + new this._gaxModule.PathTemplate( + 'projects/{project}/monitoredResourceDescriptors/{monitored_resource_descriptor}', + ), projectNotificationChannelPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/notificationChannels/{notification_channel}' + 'projects/{project}/notificationChannels/{notification_channel}', ), projectServicePathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/services/{service}' - ), - projectServiceServiceLevelObjectivePathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/services/{service}/serviceLevelObjectives/{service_level_objective}' + 'projects/{project}/services/{service}', ), + projectServiceServiceLevelObjectivePathTemplate: + new this._gaxModule.PathTemplate( + 'projects/{project}/services/{service}/serviceLevelObjectives/{service_level_objective}', + ), projectUptimeCheckConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/uptimeCheckConfigs/{uptime_check_config}' + 'projects/{project}/uptimeCheckConfigs/{uptime_check_config}', ), }; @@ -290,18 +328,30 @@ export class MetricServiceClient { // (e.g. 50 results at a time, with tokens to get subsequent // pages). Denote the keys used for pagination and results. this.descriptors.page = { - listMonitoredResourceDescriptors: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'resourceDescriptors'), - listMetricDescriptors: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'metricDescriptors'), - listTimeSeries: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'timeSeries') + listMonitoredResourceDescriptors: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'resourceDescriptors', + ), + listMetricDescriptors: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'metricDescriptors', + ), + listTimeSeries: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'timeSeries', + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.monitoring.v3.MetricService', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.monitoring.v3.MetricService', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + { 'x-goog-api-client': clientHeader.join(' ') }, + ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -332,37 +382,49 @@ export class MetricServiceClient { // Put together the "service stub" for // google.monitoring.v3.MetricService. this.metricServiceStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.monitoring.v3.MetricService') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.monitoring.v3.MetricService', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.monitoring.v3.MetricService, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts, + this._providedCustomServicePath, + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const metricServiceStubMethods = - ['listMonitoredResourceDescriptors', 'getMonitoredResourceDescriptor', 'listMetricDescriptors', 'getMetricDescriptor', 'createMetricDescriptor', 'deleteMetricDescriptor', 'listTimeSeries', 'createTimeSeries']; + const metricServiceStubMethods = [ + 'listMonitoredResourceDescriptors', + 'getMonitoredResourceDescriptor', + 'listMetricDescriptors', + 'getMetricDescriptor', + 'createMetricDescriptor', + 'deleteMetricDescriptor', + 'listTimeSeries', + 'createTimeSeries', + ]; for (const methodName of metricServiceStubMethods) { const callPromise = this.metricServiceStub.then( - stub => (...args: Array<{}>) => { - if (this._terminated) { - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error|null|undefined) => () => { + (stub) => + (...args: Array<{}>) => { + if (this._terminated) { + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { throw err; - }); + }, + ); - const descriptor = - this.descriptors.page[methodName] || - undefined; + const descriptor = this.descriptors.page[methodName] || undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -377,8 +439,14 @@ export class MetricServiceClient { * @returns {string} The DNS address for this service. */ static get servicePath() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'monitoring.googleapis.com'; } @@ -390,8 +458,14 @@ export class MetricServiceClient { * @returns {string} The DNS address for this service. */ static get apiEndpoint() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'monitoring.googleapis.com'; } @@ -426,7 +500,7 @@ export class MetricServiceClient { 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/monitoring', 'https://www.googleapis.com/auth/monitoring.read', - 'https://www.googleapis.com/auth/monitoring.write' + 'https://www.googleapis.com/auth/monitoring.write', ]; } @@ -436,8 +510,9 @@ export class MetricServiceClient { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId(callback?: Callback): - Promise|void { + getProjectId( + callback?: Callback, + ): Promise | void { if (callback) { this.auth.getProjectId(callback); return; @@ -448,592 +523,837 @@ export class MetricServiceClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Gets a single monitored resource descriptor. This method does not require a Stackdriver account. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The monitored resource descriptor to get. The format is - * `"projects/{project_id_or_number}/monitoredResourceDescriptors/{resource_type}"`. - * The `{resource_type}` is a predefined type, such as - * `cloudsql_database`. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.api.MonitoredResourceDescriptor|MonitoredResourceDescriptor}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v3/metric_service.get_monitored_resource_descriptor.js - * region_tag:monitoring_v3_generated_MetricService_GetMonitoredResourceDescriptor_async - */ + /** + * Gets a single monitored resource descriptor. This method does not require a Stackdriver account. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The monitored resource descriptor to get. The format is + * `"projects/{project_id_or_number}/monitoredResourceDescriptors/{resource_type}"`. + * The `{resource_type}` is a predefined type, such as + * `cloudsql_database`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.api.MonitoredResourceDescriptor|MonitoredResourceDescriptor}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v3/metric_service.get_monitored_resource_descriptor.js + * region_tag:monitoring_v3_generated_MetricService_GetMonitoredResourceDescriptor_async + */ getMonitoredResourceDescriptor( - request?: protos.google.monitoring.v3.IGetMonitoredResourceDescriptorRequest, - options?: CallOptions): - Promise<[ - protos.google.api.IMonitoredResourceDescriptor, - protos.google.monitoring.v3.IGetMonitoredResourceDescriptorRequest|undefined, {}|undefined - ]>; + request?: protos.google.monitoring.v3.IGetMonitoredResourceDescriptorRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.api.IMonitoredResourceDescriptor, + ( + | protos.google.monitoring.v3.IGetMonitoredResourceDescriptorRequest + | undefined + ), + {} | undefined, + ] + >; getMonitoredResourceDescriptor( - request: protos.google.monitoring.v3.IGetMonitoredResourceDescriptorRequest, - options: CallOptions, - callback: Callback< - protos.google.api.IMonitoredResourceDescriptor, - protos.google.monitoring.v3.IGetMonitoredResourceDescriptorRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.IGetMonitoredResourceDescriptorRequest, + options: CallOptions, + callback: Callback< + protos.google.api.IMonitoredResourceDescriptor, + | protos.google.monitoring.v3.IGetMonitoredResourceDescriptorRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getMonitoredResourceDescriptor( - request: protos.google.monitoring.v3.IGetMonitoredResourceDescriptorRequest, - callback: Callback< - protos.google.api.IMonitoredResourceDescriptor, - protos.google.monitoring.v3.IGetMonitoredResourceDescriptorRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.IGetMonitoredResourceDescriptorRequest, + callback: Callback< + protos.google.api.IMonitoredResourceDescriptor, + | protos.google.monitoring.v3.IGetMonitoredResourceDescriptorRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getMonitoredResourceDescriptor( - request?: protos.google.monitoring.v3.IGetMonitoredResourceDescriptorRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.monitoring.v3.IGetMonitoredResourceDescriptorRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.api.IMonitoredResourceDescriptor, - protos.google.monitoring.v3.IGetMonitoredResourceDescriptorRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.api.IMonitoredResourceDescriptor, - protos.google.monitoring.v3.IGetMonitoredResourceDescriptorRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.api.IMonitoredResourceDescriptor, - protos.google.monitoring.v3.IGetMonitoredResourceDescriptorRequest|undefined, {}|undefined - ]>|void { + | protos.google.monitoring.v3.IGetMonitoredResourceDescriptorRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.api.IMonitoredResourceDescriptor, + | protos.google.monitoring.v3.IGetMonitoredResourceDescriptorRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.api.IMonitoredResourceDescriptor, + ( + | protos.google.monitoring.v3.IGetMonitoredResourceDescriptorRequest + | undefined + ), + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getMonitoredResourceDescriptor request %j', request); - const wrappedCallback: Callback< - protos.google.api.IMonitoredResourceDescriptor, - protos.google.monitoring.v3.IGetMonitoredResourceDescriptorRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.api.IMonitoredResourceDescriptor, + | protos.google.monitoring.v3.IGetMonitoredResourceDescriptorRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { - this._log.info('getMonitoredResourceDescriptor response %j', response); + this._log.info( + 'getMonitoredResourceDescriptor response %j', + response, + ); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.getMonitoredResourceDescriptor(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.api.IMonitoredResourceDescriptor, - protos.google.monitoring.v3.IGetMonitoredResourceDescriptorRequest|undefined, {}|undefined - ]) => { - this._log.info('getMonitoredResourceDescriptor response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getMonitoredResourceDescriptor(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.api.IMonitoredResourceDescriptor, + ( + | protos.google.monitoring.v3.IGetMonitoredResourceDescriptorRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info( + 'getMonitoredResourceDescriptor response %j', + response, + ); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Gets a single metric descriptor. This method does not require a Stackdriver account. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The metric descriptor on which to execute the request. The format is - * `"projects/{project_id_or_number}/metricDescriptors/{metric_id}"`. - * An example value of `{metric_id}` is - * `"compute.googleapis.com/instance/disk/read_bytes_count"`. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.api.MetricDescriptor|MetricDescriptor}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v3/metric_service.get_metric_descriptor.js - * region_tag:monitoring_v3_generated_MetricService_GetMetricDescriptor_async - */ + /** + * Gets a single metric descriptor. This method does not require a Stackdriver account. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The metric descriptor on which to execute the request. The format is + * `"projects/{project_id_or_number}/metricDescriptors/{metric_id}"`. + * An example value of `{metric_id}` is + * `"compute.googleapis.com/instance/disk/read_bytes_count"`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.api.MetricDescriptor|MetricDescriptor}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v3/metric_service.get_metric_descriptor.js + * region_tag:monitoring_v3_generated_MetricService_GetMetricDescriptor_async + */ getMetricDescriptor( - request?: protos.google.monitoring.v3.IGetMetricDescriptorRequest, - options?: CallOptions): - Promise<[ - protos.google.api.IMetricDescriptor, - protos.google.monitoring.v3.IGetMetricDescriptorRequest|undefined, {}|undefined - ]>; + request?: protos.google.monitoring.v3.IGetMetricDescriptorRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.api.IMetricDescriptor, + protos.google.monitoring.v3.IGetMetricDescriptorRequest | undefined, + {} | undefined, + ] + >; getMetricDescriptor( - request: protos.google.monitoring.v3.IGetMetricDescriptorRequest, - options: CallOptions, - callback: Callback< - protos.google.api.IMetricDescriptor, - protos.google.monitoring.v3.IGetMetricDescriptorRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.IGetMetricDescriptorRequest, + options: CallOptions, + callback: Callback< + protos.google.api.IMetricDescriptor, + | protos.google.monitoring.v3.IGetMetricDescriptorRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getMetricDescriptor( - request: protos.google.monitoring.v3.IGetMetricDescriptorRequest, - callback: Callback< - protos.google.api.IMetricDescriptor, - protos.google.monitoring.v3.IGetMetricDescriptorRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.IGetMetricDescriptorRequest, + callback: Callback< + protos.google.api.IMetricDescriptor, + | protos.google.monitoring.v3.IGetMetricDescriptorRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getMetricDescriptor( - request?: protos.google.monitoring.v3.IGetMetricDescriptorRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.api.IMetricDescriptor, - protos.google.monitoring.v3.IGetMetricDescriptorRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.monitoring.v3.IGetMetricDescriptorRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.api.IMetricDescriptor, - protos.google.monitoring.v3.IGetMetricDescriptorRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.api.IMetricDescriptor, - protos.google.monitoring.v3.IGetMetricDescriptorRequest|undefined, {}|undefined - ]>|void { + | protos.google.monitoring.v3.IGetMetricDescriptorRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.api.IMetricDescriptor, + | protos.google.monitoring.v3.IGetMetricDescriptorRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.api.IMetricDescriptor, + protos.google.monitoring.v3.IGetMetricDescriptorRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getMetricDescriptor request %j', request); - const wrappedCallback: Callback< - protos.google.api.IMetricDescriptor, - protos.google.monitoring.v3.IGetMetricDescriptorRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.api.IMetricDescriptor, + | protos.google.monitoring.v3.IGetMetricDescriptorRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getMetricDescriptor response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.getMetricDescriptor(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.api.IMetricDescriptor, - protos.google.monitoring.v3.IGetMetricDescriptorRequest|undefined, {}|undefined - ]) => { - this._log.info('getMetricDescriptor response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getMetricDescriptor(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.api.IMetricDescriptor, + protos.google.monitoring.v3.IGetMetricDescriptorRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getMetricDescriptor response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Creates a new metric descriptor. - * User-created metric descriptors define - * [custom metrics](/monitoring/custom-metrics). - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The project on which to execute the request. The format is - * `"projects/{project_id_or_number}"`. - * @param {google.api.MetricDescriptor} request.metricDescriptor - * Required. The new [custom metric](/monitoring/custom-metrics) - * descriptor. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.api.MetricDescriptor|MetricDescriptor}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v3/metric_service.create_metric_descriptor.js - * region_tag:monitoring_v3_generated_MetricService_CreateMetricDescriptor_async - */ + /** + * Creates a new metric descriptor. + * User-created metric descriptors define + * [custom metrics](/monitoring/custom-metrics). + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The project on which to execute the request. The format is + * `"projects/{project_id_or_number}"`. + * @param {google.api.MetricDescriptor} request.metricDescriptor + * Required. The new [custom metric](/monitoring/custom-metrics) + * descriptor. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.api.MetricDescriptor|MetricDescriptor}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v3/metric_service.create_metric_descriptor.js + * region_tag:monitoring_v3_generated_MetricService_CreateMetricDescriptor_async + */ createMetricDescriptor( - request?: protos.google.monitoring.v3.ICreateMetricDescriptorRequest, - options?: CallOptions): - Promise<[ - protos.google.api.IMetricDescriptor, - protos.google.monitoring.v3.ICreateMetricDescriptorRequest|undefined, {}|undefined - ]>; + request?: protos.google.monitoring.v3.ICreateMetricDescriptorRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.api.IMetricDescriptor, + protos.google.monitoring.v3.ICreateMetricDescriptorRequest | undefined, + {} | undefined, + ] + >; createMetricDescriptor( - request: protos.google.monitoring.v3.ICreateMetricDescriptorRequest, - options: CallOptions, - callback: Callback< - protos.google.api.IMetricDescriptor, - protos.google.monitoring.v3.ICreateMetricDescriptorRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.ICreateMetricDescriptorRequest, + options: CallOptions, + callback: Callback< + protos.google.api.IMetricDescriptor, + | protos.google.monitoring.v3.ICreateMetricDescriptorRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createMetricDescriptor( - request: protos.google.monitoring.v3.ICreateMetricDescriptorRequest, - callback: Callback< - protos.google.api.IMetricDescriptor, - protos.google.monitoring.v3.ICreateMetricDescriptorRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.ICreateMetricDescriptorRequest, + callback: Callback< + protos.google.api.IMetricDescriptor, + | protos.google.monitoring.v3.ICreateMetricDescriptorRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createMetricDescriptor( - request?: protos.google.monitoring.v3.ICreateMetricDescriptorRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.api.IMetricDescriptor, - protos.google.monitoring.v3.ICreateMetricDescriptorRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.monitoring.v3.ICreateMetricDescriptorRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.api.IMetricDescriptor, - protos.google.monitoring.v3.ICreateMetricDescriptorRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.api.IMetricDescriptor, - protos.google.monitoring.v3.ICreateMetricDescriptorRequest|undefined, {}|undefined - ]>|void { + | protos.google.monitoring.v3.ICreateMetricDescriptorRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.api.IMetricDescriptor, + | protos.google.monitoring.v3.ICreateMetricDescriptorRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.api.IMetricDescriptor, + protos.google.monitoring.v3.ICreateMetricDescriptorRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('createMetricDescriptor request %j', request); - const wrappedCallback: Callback< - protos.google.api.IMetricDescriptor, - protos.google.monitoring.v3.ICreateMetricDescriptorRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.api.IMetricDescriptor, + | protos.google.monitoring.v3.ICreateMetricDescriptorRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createMetricDescriptor response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.createMetricDescriptor(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.api.IMetricDescriptor, - protos.google.monitoring.v3.ICreateMetricDescriptorRequest|undefined, {}|undefined - ]) => { - this._log.info('createMetricDescriptor response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createMetricDescriptor(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.api.IMetricDescriptor, + ( + | protos.google.monitoring.v3.ICreateMetricDescriptorRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('createMetricDescriptor response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Deletes a metric descriptor. Only user-created - * [custom metrics](/monitoring/custom-metrics) can be deleted. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The metric descriptor on which to execute the request. The format is - * `"projects/{project_id_or_number}/metricDescriptors/{metric_id}"`. - * An example of `{metric_id}` is: - * `"custom.googleapis.com/my_test_metric"`. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v3/metric_service.delete_metric_descriptor.js - * region_tag:monitoring_v3_generated_MetricService_DeleteMetricDescriptor_async - */ + /** + * Deletes a metric descriptor. Only user-created + * [custom metrics](/monitoring/custom-metrics) can be deleted. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The metric descriptor on which to execute the request. The format is + * `"projects/{project_id_or_number}/metricDescriptors/{metric_id}"`. + * An example of `{metric_id}` is: + * `"custom.googleapis.com/my_test_metric"`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v3/metric_service.delete_metric_descriptor.js + * region_tag:monitoring_v3_generated_MetricService_DeleteMetricDescriptor_async + */ deleteMetricDescriptor( - request?: protos.google.monitoring.v3.IDeleteMetricDescriptorRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.IDeleteMetricDescriptorRequest|undefined, {}|undefined - ]>; + request?: protos.google.monitoring.v3.IDeleteMetricDescriptorRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.monitoring.v3.IDeleteMetricDescriptorRequest | undefined, + {} | undefined, + ] + >; deleteMetricDescriptor( - request: protos.google.monitoring.v3.IDeleteMetricDescriptorRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.IDeleteMetricDescriptorRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.IDeleteMetricDescriptorRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.monitoring.v3.IDeleteMetricDescriptorRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteMetricDescriptor( - request: protos.google.monitoring.v3.IDeleteMetricDescriptorRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.IDeleteMetricDescriptorRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.IDeleteMetricDescriptorRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.monitoring.v3.IDeleteMetricDescriptorRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteMetricDescriptor( - request?: protos.google.monitoring.v3.IDeleteMetricDescriptorRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.monitoring.v3.IDeleteMetricDescriptorRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.IDeleteMetricDescriptorRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.IDeleteMetricDescriptorRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.IDeleteMetricDescriptorRequest|undefined, {}|undefined - ]>|void { + | protos.google.monitoring.v3.IDeleteMetricDescriptorRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + | protos.google.monitoring.v3.IDeleteMetricDescriptorRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.monitoring.v3.IDeleteMetricDescriptorRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('deleteMetricDescriptor request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.IDeleteMetricDescriptorRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.monitoring.v3.IDeleteMetricDescriptorRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteMetricDescriptor response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.deleteMetricDescriptor(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.IDeleteMetricDescriptorRequest|undefined, {}|undefined - ]) => { - this._log.info('deleteMetricDescriptor response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteMetricDescriptor(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + ( + | protos.google.monitoring.v3.IDeleteMetricDescriptorRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('deleteMetricDescriptor response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Creates or adds data to one or more time series. - * The response is empty if all time series in the request were written. - * If any time series could not be written, a corresponding failure message is - * included in the error response. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The project on which to execute the request. The format is - * `"projects/{project_id_or_number}"`. - * @param {number[]} request.timeSeries - * Required. The new data to be added to a list of time series. - * Adds at most one data point to each of several time series. The new data - * point must be more recent than any other point in its time series. Each - * `TimeSeries` value must fully specify a unique time series by supplying - * all label values for the metric and the monitored resource. - * - * The maximum number of `TimeSeries` objects per `Create` request is 200. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v3/metric_service.create_time_series.js - * region_tag:monitoring_v3_generated_MetricService_CreateTimeSeries_async - */ + /** + * Creates or adds data to one or more time series. + * The response is empty if all time series in the request were written. + * If any time series could not be written, a corresponding failure message is + * included in the error response. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The project on which to execute the request. The format is + * `"projects/{project_id_or_number}"`. + * @param {number[]} request.timeSeries + * Required. The new data to be added to a list of time series. + * Adds at most one data point to each of several time series. The new data + * point must be more recent than any other point in its time series. Each + * `TimeSeries` value must fully specify a unique time series by supplying + * all label values for the metric and the monitored resource. + * + * The maximum number of `TimeSeries` objects per `Create` request is 200. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v3/metric_service.create_time_series.js + * region_tag:monitoring_v3_generated_MetricService_CreateTimeSeries_async + */ createTimeSeries( - request?: protos.google.monitoring.v3.ICreateTimeSeriesRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.ICreateTimeSeriesRequest|undefined, {}|undefined - ]>; + request?: protos.google.monitoring.v3.ICreateTimeSeriesRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.monitoring.v3.ICreateTimeSeriesRequest | undefined, + {} | undefined, + ] + >; createTimeSeries( - request: protos.google.monitoring.v3.ICreateTimeSeriesRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.ICreateTimeSeriesRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.ICreateTimeSeriesRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.monitoring.v3.ICreateTimeSeriesRequest | null | undefined, + {} | null | undefined + >, + ): void; createTimeSeries( - request: protos.google.monitoring.v3.ICreateTimeSeriesRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.ICreateTimeSeriesRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.ICreateTimeSeriesRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.monitoring.v3.ICreateTimeSeriesRequest | null | undefined, + {} | null | undefined + >, + ): void; createTimeSeries( - request?: protos.google.monitoring.v3.ICreateTimeSeriesRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.ICreateTimeSeriesRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.monitoring.v3.ICreateTimeSeriesRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.ICreateTimeSeriesRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.ICreateTimeSeriesRequest|undefined, {}|undefined - ]>|void { + | protos.google.monitoring.v3.ICreateTimeSeriesRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + protos.google.monitoring.v3.ICreateTimeSeriesRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.monitoring.v3.ICreateTimeSeriesRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('createTimeSeries request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.ICreateTimeSeriesRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.monitoring.v3.ICreateTimeSeriesRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createTimeSeries response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.createTimeSeries(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.ICreateTimeSeriesRequest|undefined, {}|undefined - ]) => { - this._log.info('createTimeSeries response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createTimeSeries(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.monitoring.v3.ICreateTimeSeriesRequest | undefined, + {} | undefined, + ]) => { + this._log.info('createTimeSeries response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } - /** - * Lists monitored resource descriptors that match a filter. This method does not require a Stackdriver account. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The project on which to execute the request. The format is - * `"projects/{project_id_or_number}"`. - * @param {string} request.filter - * An optional [filter](/monitoring/api/v3/filters) describing - * the descriptors to be returned. The filter can reference - * the descriptor's type and labels. For example, the - * following filter returns only Google Compute Engine descriptors - * that have an `id` label: - * - * resource.type = starts_with("gce_") AND resource.label:id - * @param {number} request.pageSize - * A positive number that is the maximum number of results to return. - * @param {string} request.pageToken - * If this field is not empty then it must contain the `nextPageToken` value - * returned by a previous call to this method. Using this field causes the - * method to return additional results from the previous method call. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.api.MonitoredResourceDescriptor|MonitoredResourceDescriptor}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `listMonitoredResourceDescriptorsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Lists monitored resource descriptors that match a filter. This method does not require a Stackdriver account. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The project on which to execute the request. The format is + * `"projects/{project_id_or_number}"`. + * @param {string} request.filter + * An optional [filter](/monitoring/api/v3/filters) describing + * the descriptors to be returned. The filter can reference + * the descriptor's type and labels. For example, the + * following filter returns only Google Compute Engine descriptors + * that have an `id` label: + * + * resource.type = starts_with("gce_") AND resource.label:id + * @param {number} request.pageSize + * A positive number that is the maximum number of results to return. + * @param {string} request.pageToken + * If this field is not empty then it must contain the `nextPageToken` value + * returned by a previous call to this method. Using this field causes the + * method to return additional results from the previous method call. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.api.MonitoredResourceDescriptor|MonitoredResourceDescriptor}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listMonitoredResourceDescriptorsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listMonitoredResourceDescriptors( - request?: protos.google.monitoring.v3.IListMonitoredResourceDescriptorsRequest, - options?: CallOptions): - Promise<[ - protos.google.api.IMonitoredResourceDescriptor[], - protos.google.monitoring.v3.IListMonitoredResourceDescriptorsRequest|null, - protos.google.monitoring.v3.IListMonitoredResourceDescriptorsResponse - ]>; + request?: protos.google.monitoring.v3.IListMonitoredResourceDescriptorsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.api.IMonitoredResourceDescriptor[], + protos.google.monitoring.v3.IListMonitoredResourceDescriptorsRequest | null, + protos.google.monitoring.v3.IListMonitoredResourceDescriptorsResponse, + ] + >; listMonitoredResourceDescriptors( - request: protos.google.monitoring.v3.IListMonitoredResourceDescriptorsRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.monitoring.v3.IListMonitoredResourceDescriptorsRequest, - protos.google.monitoring.v3.IListMonitoredResourceDescriptorsResponse|null|undefined, - protos.google.api.IMonitoredResourceDescriptor>): void; + request: protos.google.monitoring.v3.IListMonitoredResourceDescriptorsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.monitoring.v3.IListMonitoredResourceDescriptorsRequest, + | protos.google.monitoring.v3.IListMonitoredResourceDescriptorsResponse + | null + | undefined, + protos.google.api.IMonitoredResourceDescriptor + >, + ): void; listMonitoredResourceDescriptors( - request: protos.google.monitoring.v3.IListMonitoredResourceDescriptorsRequest, - callback: PaginationCallback< - protos.google.monitoring.v3.IListMonitoredResourceDescriptorsRequest, - protos.google.monitoring.v3.IListMonitoredResourceDescriptorsResponse|null|undefined, - protos.google.api.IMonitoredResourceDescriptor>): void; + request: protos.google.monitoring.v3.IListMonitoredResourceDescriptorsRequest, + callback: PaginationCallback< + protos.google.monitoring.v3.IListMonitoredResourceDescriptorsRequest, + | protos.google.monitoring.v3.IListMonitoredResourceDescriptorsResponse + | null + | undefined, + protos.google.api.IMonitoredResourceDescriptor + >, + ): void; listMonitoredResourceDescriptors( - request?: protos.google.monitoring.v3.IListMonitoredResourceDescriptorsRequest, - optionsOrCallback?: CallOptions|PaginationCallback< - protos.google.monitoring.v3.IListMonitoredResourceDescriptorsRequest, - protos.google.monitoring.v3.IListMonitoredResourceDescriptorsResponse|null|undefined, - protos.google.api.IMonitoredResourceDescriptor>, - callback?: PaginationCallback< + request?: protos.google.monitoring.v3.IListMonitoredResourceDescriptorsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.monitoring.v3.IListMonitoredResourceDescriptorsRequest, - protos.google.monitoring.v3.IListMonitoredResourceDescriptorsResponse|null|undefined, - protos.google.api.IMonitoredResourceDescriptor>): - Promise<[ - protos.google.api.IMonitoredResourceDescriptor[], - protos.google.monitoring.v3.IListMonitoredResourceDescriptorsRequest|null, - protos.google.monitoring.v3.IListMonitoredResourceDescriptorsResponse - ]>|void { + | protos.google.monitoring.v3.IListMonitoredResourceDescriptorsResponse + | null + | undefined, + protos.google.api.IMonitoredResourceDescriptor + >, + callback?: PaginationCallback< + protos.google.monitoring.v3.IListMonitoredResourceDescriptorsRequest, + | protos.google.monitoring.v3.IListMonitoredResourceDescriptorsResponse + | null + | undefined, + protos.google.api.IMonitoredResourceDescriptor + >, + ): Promise< + [ + protos.google.api.IMonitoredResourceDescriptor[], + protos.google.monitoring.v3.IListMonitoredResourceDescriptorsRequest | null, + protos.google.monitoring.v3.IListMonitoredResourceDescriptorsResponse, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.monitoring.v3.IListMonitoredResourceDescriptorsRequest, - protos.google.monitoring.v3.IListMonitoredResourceDescriptorsResponse|null|undefined, - protos.google.api.IMonitoredResourceDescriptor>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.monitoring.v3.IListMonitoredResourceDescriptorsRequest, + | protos.google.monitoring.v3.IListMonitoredResourceDescriptorsResponse + | null + | undefined, + protos.google.api.IMonitoredResourceDescriptor + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listMonitoredResourceDescriptors values %j', values); callback!(error, values, nextPageRequest, rawResponse); @@ -1042,223 +1362,257 @@ export class MetricServiceClient { this._log.info('listMonitoredResourceDescriptors request %j', request); return this.innerApiCalls .listMonitoredResourceDescriptors(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.api.IMonitoredResourceDescriptor[], - protos.google.monitoring.v3.IListMonitoredResourceDescriptorsRequest|null, - protos.google.monitoring.v3.IListMonitoredResourceDescriptorsResponse - ]) => { - this._log.info('listMonitoredResourceDescriptors values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.api.IMonitoredResourceDescriptor[], + protos.google.monitoring.v3.IListMonitoredResourceDescriptorsRequest | null, + protos.google.monitoring.v3.IListMonitoredResourceDescriptorsResponse, + ]) => { + this._log.info( + 'listMonitoredResourceDescriptors values %j', + response, + ); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listMonitoredResourceDescriptors`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The project on which to execute the request. The format is - * `"projects/{project_id_or_number}"`. - * @param {string} request.filter - * An optional [filter](/monitoring/api/v3/filters) describing - * the descriptors to be returned. The filter can reference - * the descriptor's type and labels. For example, the - * following filter returns only Google Compute Engine descriptors - * that have an `id` label: - * - * resource.type = starts_with("gce_") AND resource.label:id - * @param {number} request.pageSize - * A positive number that is the maximum number of results to return. - * @param {string} request.pageToken - * If this field is not empty then it must contain the `nextPageToken` value - * returned by a previous call to this method. Using this field causes the - * method to return additional results from the previous method call. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.api.MonitoredResourceDescriptor|MonitoredResourceDescriptor} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `listMonitoredResourceDescriptorsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `listMonitoredResourceDescriptors`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The project on which to execute the request. The format is + * `"projects/{project_id_or_number}"`. + * @param {string} request.filter + * An optional [filter](/monitoring/api/v3/filters) describing + * the descriptors to be returned. The filter can reference + * the descriptor's type and labels. For example, the + * following filter returns only Google Compute Engine descriptors + * that have an `id` label: + * + * resource.type = starts_with("gce_") AND resource.label:id + * @param {number} request.pageSize + * A positive number that is the maximum number of results to return. + * @param {string} request.pageToken + * If this field is not empty then it must contain the `nextPageToken` value + * returned by a previous call to this method. Using this field causes the + * method to return additional results from the previous method call. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.api.MonitoredResourceDescriptor|MonitoredResourceDescriptor} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listMonitoredResourceDescriptorsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listMonitoredResourceDescriptorsStream( - request?: protos.google.monitoring.v3.IListMonitoredResourceDescriptorsRequest, - options?: CallOptions): - Transform{ + request?: protos.google.monitoring.v3.IListMonitoredResourceDescriptorsRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', - }); - const defaultCallSettings = this._defaults['listMonitoredResourceDescriptors']; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + const defaultCallSettings = + this._defaults['listMonitoredResourceDescriptors']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listMonitoredResourceDescriptors stream %j', request); return this.descriptors.page.listMonitoredResourceDescriptors.createStream( this.innerApiCalls.listMonitoredResourceDescriptors as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listMonitoredResourceDescriptors`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The project on which to execute the request. The format is - * `"projects/{project_id_or_number}"`. - * @param {string} request.filter - * An optional [filter](/monitoring/api/v3/filters) describing - * the descriptors to be returned. The filter can reference - * the descriptor's type and labels. For example, the - * following filter returns only Google Compute Engine descriptors - * that have an `id` label: - * - * resource.type = starts_with("gce_") AND resource.label:id - * @param {number} request.pageSize - * A positive number that is the maximum number of results to return. - * @param {string} request.pageToken - * If this field is not empty then it must contain the `nextPageToken` value - * returned by a previous call to this method. Using this field causes the - * method to return additional results from the previous method call. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.api.MonitoredResourceDescriptor|MonitoredResourceDescriptor}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v3/metric_service.list_monitored_resource_descriptors.js - * region_tag:monitoring_v3_generated_MetricService_ListMonitoredResourceDescriptors_async - */ + /** + * Equivalent to `listMonitoredResourceDescriptors`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The project on which to execute the request. The format is + * `"projects/{project_id_or_number}"`. + * @param {string} request.filter + * An optional [filter](/monitoring/api/v3/filters) describing + * the descriptors to be returned. The filter can reference + * the descriptor's type and labels. For example, the + * following filter returns only Google Compute Engine descriptors + * that have an `id` label: + * + * resource.type = starts_with("gce_") AND resource.label:id + * @param {number} request.pageSize + * A positive number that is the maximum number of results to return. + * @param {string} request.pageToken + * If this field is not empty then it must contain the `nextPageToken` value + * returned by a previous call to this method. Using this field causes the + * method to return additional results from the previous method call. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.api.MonitoredResourceDescriptor|MonitoredResourceDescriptor}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v3/metric_service.list_monitored_resource_descriptors.js + * region_tag:monitoring_v3_generated_MetricService_ListMonitoredResourceDescriptors_async + */ listMonitoredResourceDescriptorsAsync( - request?: protos.google.monitoring.v3.IListMonitoredResourceDescriptorsRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.monitoring.v3.IListMonitoredResourceDescriptorsRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', - }); - const defaultCallSettings = this._defaults['listMonitoredResourceDescriptors']; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + const defaultCallSettings = + this._defaults['listMonitoredResourceDescriptors']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listMonitoredResourceDescriptors iterate %j', request); return this.descriptors.page.listMonitoredResourceDescriptors.asyncIterate( this.innerApiCalls['listMonitoredResourceDescriptors'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } - /** - * Lists metric descriptors that match a filter. This method does not require a Stackdriver account. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The project on which to execute the request. The format is - * `"projects/{project_id_or_number}"`. - * @param {string} request.filter - * If this field is empty, all custom and - * system-defined metric descriptors are returned. - * Otherwise, the [filter](/monitoring/api/v3/filters) - * specifies which metric descriptors are to be - * returned. For example, the following filter matches all - * [custom metrics](/monitoring/custom-metrics): - * - * metric.type = starts_with("custom.googleapis.com/") - * @param {number} request.pageSize - * A positive number that is the maximum number of results to return. - * @param {string} request.pageToken - * If this field is not empty then it must contain the `nextPageToken` value - * returned by a previous call to this method. Using this field causes the - * method to return additional results from the previous method call. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.api.MetricDescriptor|MetricDescriptor}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `listMetricDescriptorsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Lists metric descriptors that match a filter. This method does not require a Stackdriver account. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The project on which to execute the request. The format is + * `"projects/{project_id_or_number}"`. + * @param {string} request.filter + * If this field is empty, all custom and + * system-defined metric descriptors are returned. + * Otherwise, the [filter](/monitoring/api/v3/filters) + * specifies which metric descriptors are to be + * returned. For example, the following filter matches all + * [custom metrics](/monitoring/custom-metrics): + * + * metric.type = starts_with("custom.googleapis.com/") + * @param {number} request.pageSize + * A positive number that is the maximum number of results to return. + * @param {string} request.pageToken + * If this field is not empty then it must contain the `nextPageToken` value + * returned by a previous call to this method. Using this field causes the + * method to return additional results from the previous method call. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.api.MetricDescriptor|MetricDescriptor}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listMetricDescriptorsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listMetricDescriptors( - request?: protos.google.monitoring.v3.IListMetricDescriptorsRequest, - options?: CallOptions): - Promise<[ - protos.google.api.IMetricDescriptor[], - protos.google.monitoring.v3.IListMetricDescriptorsRequest|null, - protos.google.monitoring.v3.IListMetricDescriptorsResponse - ]>; + request?: protos.google.monitoring.v3.IListMetricDescriptorsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.api.IMetricDescriptor[], + protos.google.monitoring.v3.IListMetricDescriptorsRequest | null, + protos.google.monitoring.v3.IListMetricDescriptorsResponse, + ] + >; listMetricDescriptors( - request: protos.google.monitoring.v3.IListMetricDescriptorsRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.monitoring.v3.IListMetricDescriptorsRequest, - protos.google.monitoring.v3.IListMetricDescriptorsResponse|null|undefined, - protos.google.api.IMetricDescriptor>): void; + request: protos.google.monitoring.v3.IListMetricDescriptorsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.monitoring.v3.IListMetricDescriptorsRequest, + | protos.google.monitoring.v3.IListMetricDescriptorsResponse + | null + | undefined, + protos.google.api.IMetricDescriptor + >, + ): void; listMetricDescriptors( - request: protos.google.monitoring.v3.IListMetricDescriptorsRequest, - callback: PaginationCallback< - protos.google.monitoring.v3.IListMetricDescriptorsRequest, - protos.google.monitoring.v3.IListMetricDescriptorsResponse|null|undefined, - protos.google.api.IMetricDescriptor>): void; + request: protos.google.monitoring.v3.IListMetricDescriptorsRequest, + callback: PaginationCallback< + protos.google.monitoring.v3.IListMetricDescriptorsRequest, + | protos.google.monitoring.v3.IListMetricDescriptorsResponse + | null + | undefined, + protos.google.api.IMetricDescriptor + >, + ): void; listMetricDescriptors( - request?: protos.google.monitoring.v3.IListMetricDescriptorsRequest, - optionsOrCallback?: CallOptions|PaginationCallback< - protos.google.monitoring.v3.IListMetricDescriptorsRequest, - protos.google.monitoring.v3.IListMetricDescriptorsResponse|null|undefined, - protos.google.api.IMetricDescriptor>, - callback?: PaginationCallback< + request?: protos.google.monitoring.v3.IListMetricDescriptorsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.monitoring.v3.IListMetricDescriptorsRequest, - protos.google.monitoring.v3.IListMetricDescriptorsResponse|null|undefined, - protos.google.api.IMetricDescriptor>): - Promise<[ - protos.google.api.IMetricDescriptor[], - protos.google.monitoring.v3.IListMetricDescriptorsRequest|null, - protos.google.monitoring.v3.IListMetricDescriptorsResponse - ]>|void { + | protos.google.monitoring.v3.IListMetricDescriptorsResponse + | null + | undefined, + protos.google.api.IMetricDescriptor + >, + callback?: PaginationCallback< + protos.google.monitoring.v3.IListMetricDescriptorsRequest, + | protos.google.monitoring.v3.IListMetricDescriptorsResponse + | null + | undefined, + protos.google.api.IMetricDescriptor + >, + ): Promise< + [ + protos.google.api.IMetricDescriptor[], + protos.google.monitoring.v3.IListMetricDescriptorsRequest | null, + protos.google.monitoring.v3.IListMetricDescriptorsResponse, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.monitoring.v3.IListMetricDescriptorsRequest, - protos.google.monitoring.v3.IListMetricDescriptorsResponse|null|undefined, - protos.google.api.IMetricDescriptor>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.monitoring.v3.IListMetricDescriptorsRequest, + | protos.google.monitoring.v3.IListMetricDescriptorsResponse + | null + | undefined, + protos.google.api.IMetricDescriptor + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listMetricDescriptors values %j', values); callback!(error, values, nextPageRequest, rawResponse); @@ -1267,243 +1621,266 @@ export class MetricServiceClient { this._log.info('listMetricDescriptors request %j', request); return this.innerApiCalls .listMetricDescriptors(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.api.IMetricDescriptor[], - protos.google.monitoring.v3.IListMetricDescriptorsRequest|null, - protos.google.monitoring.v3.IListMetricDescriptorsResponse - ]) => { - this._log.info('listMetricDescriptors values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.api.IMetricDescriptor[], + protos.google.monitoring.v3.IListMetricDescriptorsRequest | null, + protos.google.monitoring.v3.IListMetricDescriptorsResponse, + ]) => { + this._log.info('listMetricDescriptors values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listMetricDescriptors`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The project on which to execute the request. The format is - * `"projects/{project_id_or_number}"`. - * @param {string} request.filter - * If this field is empty, all custom and - * system-defined metric descriptors are returned. - * Otherwise, the [filter](/monitoring/api/v3/filters) - * specifies which metric descriptors are to be - * returned. For example, the following filter matches all - * [custom metrics](/monitoring/custom-metrics): - * - * metric.type = starts_with("custom.googleapis.com/") - * @param {number} request.pageSize - * A positive number that is the maximum number of results to return. - * @param {string} request.pageToken - * If this field is not empty then it must contain the `nextPageToken` value - * returned by a previous call to this method. Using this field causes the - * method to return additional results from the previous method call. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.api.MetricDescriptor|MetricDescriptor} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `listMetricDescriptorsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `listMetricDescriptors`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The project on which to execute the request. The format is + * `"projects/{project_id_or_number}"`. + * @param {string} request.filter + * If this field is empty, all custom and + * system-defined metric descriptors are returned. + * Otherwise, the [filter](/monitoring/api/v3/filters) + * specifies which metric descriptors are to be + * returned. For example, the following filter matches all + * [custom metrics](/monitoring/custom-metrics): + * + * metric.type = starts_with("custom.googleapis.com/") + * @param {number} request.pageSize + * A positive number that is the maximum number of results to return. + * @param {string} request.pageToken + * If this field is not empty then it must contain the `nextPageToken` value + * returned by a previous call to this method. Using this field causes the + * method to return additional results from the previous method call. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.api.MetricDescriptor|MetricDescriptor} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listMetricDescriptorsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listMetricDescriptorsStream( - request?: protos.google.monitoring.v3.IListMetricDescriptorsRequest, - options?: CallOptions): - Transform{ + request?: protos.google.monitoring.v3.IListMetricDescriptorsRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); const defaultCallSettings = this._defaults['listMetricDescriptors']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listMetricDescriptors stream %j', request); return this.descriptors.page.listMetricDescriptors.createStream( this.innerApiCalls.listMetricDescriptors as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listMetricDescriptors`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The project on which to execute the request. The format is - * `"projects/{project_id_or_number}"`. - * @param {string} request.filter - * If this field is empty, all custom and - * system-defined metric descriptors are returned. - * Otherwise, the [filter](/monitoring/api/v3/filters) - * specifies which metric descriptors are to be - * returned. For example, the following filter matches all - * [custom metrics](/monitoring/custom-metrics): - * - * metric.type = starts_with("custom.googleapis.com/") - * @param {number} request.pageSize - * A positive number that is the maximum number of results to return. - * @param {string} request.pageToken - * If this field is not empty then it must contain the `nextPageToken` value - * returned by a previous call to this method. Using this field causes the - * method to return additional results from the previous method call. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.api.MetricDescriptor|MetricDescriptor}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v3/metric_service.list_metric_descriptors.js - * region_tag:monitoring_v3_generated_MetricService_ListMetricDescriptors_async - */ + /** + * Equivalent to `listMetricDescriptors`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The project on which to execute the request. The format is + * `"projects/{project_id_or_number}"`. + * @param {string} request.filter + * If this field is empty, all custom and + * system-defined metric descriptors are returned. + * Otherwise, the [filter](/monitoring/api/v3/filters) + * specifies which metric descriptors are to be + * returned. For example, the following filter matches all + * [custom metrics](/monitoring/custom-metrics): + * + * metric.type = starts_with("custom.googleapis.com/") + * @param {number} request.pageSize + * A positive number that is the maximum number of results to return. + * @param {string} request.pageToken + * If this field is not empty then it must contain the `nextPageToken` value + * returned by a previous call to this method. Using this field causes the + * method to return additional results from the previous method call. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.api.MetricDescriptor|MetricDescriptor}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v3/metric_service.list_metric_descriptors.js + * region_tag:monitoring_v3_generated_MetricService_ListMetricDescriptors_async + */ listMetricDescriptorsAsync( - request?: protos.google.monitoring.v3.IListMetricDescriptorsRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.monitoring.v3.IListMetricDescriptorsRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); const defaultCallSettings = this._defaults['listMetricDescriptors']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listMetricDescriptors iterate %j', request); return this.descriptors.page.listMetricDescriptors.asyncIterate( this.innerApiCalls['listMetricDescriptors'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } - /** - * Lists time series that match a filter. This method does not require a Stackdriver account. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The project on which to execute the request. The format is - * "projects/{project_id_or_number}". - * @param {string} request.filter - * Required. A [monitoring filter](/monitoring/api/v3/filters) that specifies which time - * series should be returned. The filter must specify a single metric type, - * and can additionally specify metric labels and other information. For - * example: - * - * metric.type = "compute.googleapis.com/instance/cpu/usage_time" AND - * metric.labels.instance_name = "my-instance-name" - * @param {google.monitoring.v3.TimeInterval} request.interval - * Required. The time interval for which results should be returned. Only time series - * that contain data points in the specified interval are included - * in the response. - * @param {google.monitoring.v3.Aggregation} request.aggregation - * Specifies the alignment of data points in individual time series as - * well as how to combine the retrieved time series across specified labels. - * - * By default (if no `aggregation` is explicitly specified), the raw time - * series data is returned. - * @param {string} request.orderBy - * Unsupported: must be left blank. The points in each time series are - * currently returned in reverse time order (most recent to oldest). - * @param {google.monitoring.v3.ListTimeSeriesRequest.TimeSeriesView} request.view - * Required. Specifies which information is returned about the time series. - * @param {number} request.pageSize - * A positive number that is the maximum number of results to return. If - * `page_size` is empty or more than 100,000 results, the effective - * `page_size` is 100,000 results. If `view` is set to `FULL`, this is the - * maximum number of `Points` returned. If `view` is set to `HEADERS`, this is - * the maximum number of `TimeSeries` returned. - * @param {string} request.pageToken - * If this field is not empty then it must contain the `nextPageToken` value - * returned by a previous call to this method. Using this field causes the - * method to return additional results from the previous method call. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.monitoring.v3.TimeSeries|TimeSeries}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `listTimeSeriesAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Lists time series that match a filter. This method does not require a Stackdriver account. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The project on which to execute the request. The format is + * "projects/{project_id_or_number}". + * @param {string} request.filter + * Required. A [monitoring filter](/monitoring/api/v3/filters) that specifies which time + * series should be returned. The filter must specify a single metric type, + * and can additionally specify metric labels and other information. For + * example: + * + * metric.type = "compute.googleapis.com/instance/cpu/usage_time" AND + * metric.labels.instance_name = "my-instance-name" + * @param {google.monitoring.v3.TimeInterval} request.interval + * Required. The time interval for which results should be returned. Only time series + * that contain data points in the specified interval are included + * in the response. + * @param {google.monitoring.v3.Aggregation} request.aggregation + * Specifies the alignment of data points in individual time series as + * well as how to combine the retrieved time series across specified labels. + * + * By default (if no `aggregation` is explicitly specified), the raw time + * series data is returned. + * @param {string} request.orderBy + * Unsupported: must be left blank. The points in each time series are + * currently returned in reverse time order (most recent to oldest). + * @param {google.monitoring.v3.ListTimeSeriesRequest.TimeSeriesView} request.view + * Required. Specifies which information is returned about the time series. + * @param {number} request.pageSize + * A positive number that is the maximum number of results to return. If + * `page_size` is empty or more than 100,000 results, the effective + * `page_size` is 100,000 results. If `view` is set to `FULL`, this is the + * maximum number of `Points` returned. If `view` is set to `HEADERS`, this is + * the maximum number of `TimeSeries` returned. + * @param {string} request.pageToken + * If this field is not empty then it must contain the `nextPageToken` value + * returned by a previous call to this method. Using this field causes the + * method to return additional results from the previous method call. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.monitoring.v3.TimeSeries|TimeSeries}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listTimeSeriesAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listTimeSeries( - request?: protos.google.monitoring.v3.IListTimeSeriesRequest, - options?: CallOptions): - Promise<[ - protos.google.monitoring.v3.ITimeSeries[], - protos.google.monitoring.v3.IListTimeSeriesRequest|null, - protos.google.monitoring.v3.IListTimeSeriesResponse - ]>; + request?: protos.google.monitoring.v3.IListTimeSeriesRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.monitoring.v3.ITimeSeries[], + protos.google.monitoring.v3.IListTimeSeriesRequest | null, + protos.google.monitoring.v3.IListTimeSeriesResponse, + ] + >; listTimeSeries( - request: protos.google.monitoring.v3.IListTimeSeriesRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.monitoring.v3.IListTimeSeriesRequest, - protos.google.monitoring.v3.IListTimeSeriesResponse|null|undefined, - protos.google.monitoring.v3.ITimeSeries>): void; + request: protos.google.monitoring.v3.IListTimeSeriesRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.monitoring.v3.IListTimeSeriesRequest, + protos.google.monitoring.v3.IListTimeSeriesResponse | null | undefined, + protos.google.monitoring.v3.ITimeSeries + >, + ): void; listTimeSeries( - request: protos.google.monitoring.v3.IListTimeSeriesRequest, - callback: PaginationCallback< - protos.google.monitoring.v3.IListTimeSeriesRequest, - protos.google.monitoring.v3.IListTimeSeriesResponse|null|undefined, - protos.google.monitoring.v3.ITimeSeries>): void; + request: protos.google.monitoring.v3.IListTimeSeriesRequest, + callback: PaginationCallback< + protos.google.monitoring.v3.IListTimeSeriesRequest, + protos.google.monitoring.v3.IListTimeSeriesResponse | null | undefined, + protos.google.monitoring.v3.ITimeSeries + >, + ): void; listTimeSeries( - request?: protos.google.monitoring.v3.IListTimeSeriesRequest, - optionsOrCallback?: CallOptions|PaginationCallback< + request?: protos.google.monitoring.v3.IListTimeSeriesRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.monitoring.v3.IListTimeSeriesRequest, - protos.google.monitoring.v3.IListTimeSeriesResponse|null|undefined, - protos.google.monitoring.v3.ITimeSeries>, - callback?: PaginationCallback< - protos.google.monitoring.v3.IListTimeSeriesRequest, - protos.google.monitoring.v3.IListTimeSeriesResponse|null|undefined, - protos.google.monitoring.v3.ITimeSeries>): - Promise<[ - protos.google.monitoring.v3.ITimeSeries[], - protos.google.monitoring.v3.IListTimeSeriesRequest|null, - protos.google.monitoring.v3.IListTimeSeriesResponse - ]>|void { + | protos.google.monitoring.v3.IListTimeSeriesResponse + | null + | undefined, + protos.google.monitoring.v3.ITimeSeries + >, + callback?: PaginationCallback< + protos.google.monitoring.v3.IListTimeSeriesRequest, + protos.google.monitoring.v3.IListTimeSeriesResponse | null | undefined, + protos.google.monitoring.v3.ITimeSeries + >, + ): Promise< + [ + protos.google.monitoring.v3.ITimeSeries[], + protos.google.monitoring.v3.IListTimeSeriesRequest | null, + protos.google.monitoring.v3.IListTimeSeriesResponse, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.monitoring.v3.IListTimeSeriesRequest, - protos.google.monitoring.v3.IListTimeSeriesResponse|null|undefined, - protos.google.monitoring.v3.ITimeSeries>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.monitoring.v3.IListTimeSeriesRequest, + | protos.google.monitoring.v3.IListTimeSeriesResponse + | null + | undefined, + protos.google.monitoring.v3.ITimeSeries + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listTimeSeries values %j', values); callback!(error, values, nextPageRequest, rawResponse); @@ -1512,166 +1889,170 @@ export class MetricServiceClient { this._log.info('listTimeSeries request %j', request); return this.innerApiCalls .listTimeSeries(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.monitoring.v3.ITimeSeries[], - protos.google.monitoring.v3.IListTimeSeriesRequest|null, - protos.google.monitoring.v3.IListTimeSeriesResponse - ]) => { - this._log.info('listTimeSeries values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.monitoring.v3.ITimeSeries[], + protos.google.monitoring.v3.IListTimeSeriesRequest | null, + protos.google.monitoring.v3.IListTimeSeriesResponse, + ]) => { + this._log.info('listTimeSeries values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listTimeSeries`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The project on which to execute the request. The format is - * "projects/{project_id_or_number}". - * @param {string} request.filter - * Required. A [monitoring filter](/monitoring/api/v3/filters) that specifies which time - * series should be returned. The filter must specify a single metric type, - * and can additionally specify metric labels and other information. For - * example: - * - * metric.type = "compute.googleapis.com/instance/cpu/usage_time" AND - * metric.labels.instance_name = "my-instance-name" - * @param {google.monitoring.v3.TimeInterval} request.interval - * Required. The time interval for which results should be returned. Only time series - * that contain data points in the specified interval are included - * in the response. - * @param {google.monitoring.v3.Aggregation} request.aggregation - * Specifies the alignment of data points in individual time series as - * well as how to combine the retrieved time series across specified labels. - * - * By default (if no `aggregation` is explicitly specified), the raw time - * series data is returned. - * @param {string} request.orderBy - * Unsupported: must be left blank. The points in each time series are - * currently returned in reverse time order (most recent to oldest). - * @param {google.monitoring.v3.ListTimeSeriesRequest.TimeSeriesView} request.view - * Required. Specifies which information is returned about the time series. - * @param {number} request.pageSize - * A positive number that is the maximum number of results to return. If - * `page_size` is empty or more than 100,000 results, the effective - * `page_size` is 100,000 results. If `view` is set to `FULL`, this is the - * maximum number of `Points` returned. If `view` is set to `HEADERS`, this is - * the maximum number of `TimeSeries` returned. - * @param {string} request.pageToken - * If this field is not empty then it must contain the `nextPageToken` value - * returned by a previous call to this method. Using this field causes the - * method to return additional results from the previous method call. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.monitoring.v3.TimeSeries|TimeSeries} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `listTimeSeriesAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `listTimeSeries`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The project on which to execute the request. The format is + * "projects/{project_id_or_number}". + * @param {string} request.filter + * Required. A [monitoring filter](/monitoring/api/v3/filters) that specifies which time + * series should be returned. The filter must specify a single metric type, + * and can additionally specify metric labels and other information. For + * example: + * + * metric.type = "compute.googleapis.com/instance/cpu/usage_time" AND + * metric.labels.instance_name = "my-instance-name" + * @param {google.monitoring.v3.TimeInterval} request.interval + * Required. The time interval for which results should be returned. Only time series + * that contain data points in the specified interval are included + * in the response. + * @param {google.monitoring.v3.Aggregation} request.aggregation + * Specifies the alignment of data points in individual time series as + * well as how to combine the retrieved time series across specified labels. + * + * By default (if no `aggregation` is explicitly specified), the raw time + * series data is returned. + * @param {string} request.orderBy + * Unsupported: must be left blank. The points in each time series are + * currently returned in reverse time order (most recent to oldest). + * @param {google.monitoring.v3.ListTimeSeriesRequest.TimeSeriesView} request.view + * Required. Specifies which information is returned about the time series. + * @param {number} request.pageSize + * A positive number that is the maximum number of results to return. If + * `page_size` is empty or more than 100,000 results, the effective + * `page_size` is 100,000 results. If `view` is set to `FULL`, this is the + * maximum number of `Points` returned. If `view` is set to `HEADERS`, this is + * the maximum number of `TimeSeries` returned. + * @param {string} request.pageToken + * If this field is not empty then it must contain the `nextPageToken` value + * returned by a previous call to this method. Using this field causes the + * method to return additional results from the previous method call. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.monitoring.v3.TimeSeries|TimeSeries} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listTimeSeriesAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listTimeSeriesStream( - request?: protos.google.monitoring.v3.IListTimeSeriesRequest, - options?: CallOptions): - Transform{ + request?: protos.google.monitoring.v3.IListTimeSeriesRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); const defaultCallSettings = this._defaults['listTimeSeries']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listTimeSeries stream %j', request); return this.descriptors.page.listTimeSeries.createStream( this.innerApiCalls.listTimeSeries as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listTimeSeries`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The project on which to execute the request. The format is - * "projects/{project_id_or_number}". - * @param {string} request.filter - * Required. A [monitoring filter](/monitoring/api/v3/filters) that specifies which time - * series should be returned. The filter must specify a single metric type, - * and can additionally specify metric labels and other information. For - * example: - * - * metric.type = "compute.googleapis.com/instance/cpu/usage_time" AND - * metric.labels.instance_name = "my-instance-name" - * @param {google.monitoring.v3.TimeInterval} request.interval - * Required. The time interval for which results should be returned. Only time series - * that contain data points in the specified interval are included - * in the response. - * @param {google.monitoring.v3.Aggregation} request.aggregation - * Specifies the alignment of data points in individual time series as - * well as how to combine the retrieved time series across specified labels. - * - * By default (if no `aggregation` is explicitly specified), the raw time - * series data is returned. - * @param {string} request.orderBy - * Unsupported: must be left blank. The points in each time series are - * currently returned in reverse time order (most recent to oldest). - * @param {google.monitoring.v3.ListTimeSeriesRequest.TimeSeriesView} request.view - * Required. Specifies which information is returned about the time series. - * @param {number} request.pageSize - * A positive number that is the maximum number of results to return. If - * `page_size` is empty or more than 100,000 results, the effective - * `page_size` is 100,000 results. If `view` is set to `FULL`, this is the - * maximum number of `Points` returned. If `view` is set to `HEADERS`, this is - * the maximum number of `TimeSeries` returned. - * @param {string} request.pageToken - * If this field is not empty then it must contain the `nextPageToken` value - * returned by a previous call to this method. Using this field causes the - * method to return additional results from the previous method call. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.monitoring.v3.TimeSeries|TimeSeries}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v3/metric_service.list_time_series.js - * region_tag:monitoring_v3_generated_MetricService_ListTimeSeries_async - */ + /** + * Equivalent to `listTimeSeries`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The project on which to execute the request. The format is + * "projects/{project_id_or_number}". + * @param {string} request.filter + * Required. A [monitoring filter](/monitoring/api/v3/filters) that specifies which time + * series should be returned. The filter must specify a single metric type, + * and can additionally specify metric labels and other information. For + * example: + * + * metric.type = "compute.googleapis.com/instance/cpu/usage_time" AND + * metric.labels.instance_name = "my-instance-name" + * @param {google.monitoring.v3.TimeInterval} request.interval + * Required. The time interval for which results should be returned. Only time series + * that contain data points in the specified interval are included + * in the response. + * @param {google.monitoring.v3.Aggregation} request.aggregation + * Specifies the alignment of data points in individual time series as + * well as how to combine the retrieved time series across specified labels. + * + * By default (if no `aggregation` is explicitly specified), the raw time + * series data is returned. + * @param {string} request.orderBy + * Unsupported: must be left blank. The points in each time series are + * currently returned in reverse time order (most recent to oldest). + * @param {google.monitoring.v3.ListTimeSeriesRequest.TimeSeriesView} request.view + * Required. Specifies which information is returned about the time series. + * @param {number} request.pageSize + * A positive number that is the maximum number of results to return. If + * `page_size` is empty or more than 100,000 results, the effective + * `page_size` is 100,000 results. If `view` is set to `FULL`, this is the + * maximum number of `Points` returned. If `view` is set to `HEADERS`, this is + * the maximum number of `TimeSeries` returned. + * @param {string} request.pageToken + * If this field is not empty then it must contain the `nextPageToken` value + * returned by a previous call to this method. Using this field causes the + * method to return additional results from the previous method call. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.monitoring.v3.TimeSeries|TimeSeries}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v3/metric_service.list_time_series.js + * region_tag:monitoring_v3_generated_MetricService_ListTimeSeries_async + */ listTimeSeriesAsync( - request?: protos.google.monitoring.v3.IListTimeSeriesRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.monitoring.v3.IListTimeSeriesRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); const defaultCallSettings = this._defaults['listTimeSeries']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listTimeSeries iterate %j', request); return this.descriptors.page.listTimeSeries.asyncIterate( this.innerApiCalls['listTimeSeries'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } // -------------------- @@ -1685,7 +2066,7 @@ export class MetricServiceClient { * @param {string} alert_policy * @returns {string} Resource name string. */ - folderAlertPolicyPath(folder:string,alertPolicy:string) { + folderAlertPolicyPath(folder: string, alertPolicy: string) { return this.pathTemplates.folderAlertPolicyPathTemplate.render({ folder: folder, alert_policy: alertPolicy, @@ -1700,7 +2081,9 @@ export class MetricServiceClient { * @returns {string} A string representing the folder. */ matchFolderFromFolderAlertPolicyName(folderAlertPolicyName: string) { - return this.pathTemplates.folderAlertPolicyPathTemplate.match(folderAlertPolicyName).folder; + return this.pathTemplates.folderAlertPolicyPathTemplate.match( + folderAlertPolicyName, + ).folder; } /** @@ -1711,7 +2094,9 @@ export class MetricServiceClient { * @returns {string} A string representing the alert_policy. */ matchAlertPolicyFromFolderAlertPolicyName(folderAlertPolicyName: string) { - return this.pathTemplates.folderAlertPolicyPathTemplate.match(folderAlertPolicyName).alert_policy; + return this.pathTemplates.folderAlertPolicyPathTemplate.match( + folderAlertPolicyName, + ).alert_policy; } /** @@ -1722,7 +2107,11 @@ export class MetricServiceClient { * @param {string} condition * @returns {string} Resource name string. */ - folderAlertPolicyConditionPath(folder:string,alertPolicy:string,condition:string) { + folderAlertPolicyConditionPath( + folder: string, + alertPolicy: string, + condition: string, + ) { return this.pathTemplates.folderAlertPolicyConditionPathTemplate.render({ folder: folder, alert_policy: alertPolicy, @@ -1737,8 +2126,12 @@ export class MetricServiceClient { * A fully-qualified path representing folder_alert_policy_condition resource. * @returns {string} A string representing the folder. */ - matchFolderFromFolderAlertPolicyConditionName(folderAlertPolicyConditionName: string) { - return this.pathTemplates.folderAlertPolicyConditionPathTemplate.match(folderAlertPolicyConditionName).folder; + matchFolderFromFolderAlertPolicyConditionName( + folderAlertPolicyConditionName: string, + ) { + return this.pathTemplates.folderAlertPolicyConditionPathTemplate.match( + folderAlertPolicyConditionName, + ).folder; } /** @@ -1748,8 +2141,12 @@ export class MetricServiceClient { * A fully-qualified path representing folder_alert_policy_condition resource. * @returns {string} A string representing the alert_policy. */ - matchAlertPolicyFromFolderAlertPolicyConditionName(folderAlertPolicyConditionName: string) { - return this.pathTemplates.folderAlertPolicyConditionPathTemplate.match(folderAlertPolicyConditionName).alert_policy; + matchAlertPolicyFromFolderAlertPolicyConditionName( + folderAlertPolicyConditionName: string, + ) { + return this.pathTemplates.folderAlertPolicyConditionPathTemplate.match( + folderAlertPolicyConditionName, + ).alert_policy; } /** @@ -1759,8 +2156,12 @@ export class MetricServiceClient { * A fully-qualified path representing folder_alert_policy_condition resource. * @returns {string} A string representing the condition. */ - matchConditionFromFolderAlertPolicyConditionName(folderAlertPolicyConditionName: string) { - return this.pathTemplates.folderAlertPolicyConditionPathTemplate.match(folderAlertPolicyConditionName).condition; + matchConditionFromFolderAlertPolicyConditionName( + folderAlertPolicyConditionName: string, + ) { + return this.pathTemplates.folderAlertPolicyConditionPathTemplate.match( + folderAlertPolicyConditionName, + ).condition; } /** @@ -1770,7 +2171,7 @@ export class MetricServiceClient { * @param {string} channel_descriptor * @returns {string} Resource name string. */ - folderChannelDescriptorPath(folder:string,channelDescriptor:string) { + folderChannelDescriptorPath(folder: string, channelDescriptor: string) { return this.pathTemplates.folderChannelDescriptorPathTemplate.render({ folder: folder, channel_descriptor: channelDescriptor, @@ -1784,8 +2185,12 @@ export class MetricServiceClient { * A fully-qualified path representing folder_channel_descriptor resource. * @returns {string} A string representing the folder. */ - matchFolderFromFolderChannelDescriptorName(folderChannelDescriptorName: string) { - return this.pathTemplates.folderChannelDescriptorPathTemplate.match(folderChannelDescriptorName).folder; + matchFolderFromFolderChannelDescriptorName( + folderChannelDescriptorName: string, + ) { + return this.pathTemplates.folderChannelDescriptorPathTemplate.match( + folderChannelDescriptorName, + ).folder; } /** @@ -1795,8 +2200,12 @@ export class MetricServiceClient { * A fully-qualified path representing folder_channel_descriptor resource. * @returns {string} A string representing the channel_descriptor. */ - matchChannelDescriptorFromFolderChannelDescriptorName(folderChannelDescriptorName: string) { - return this.pathTemplates.folderChannelDescriptorPathTemplate.match(folderChannelDescriptorName).channel_descriptor; + matchChannelDescriptorFromFolderChannelDescriptorName( + folderChannelDescriptorName: string, + ) { + return this.pathTemplates.folderChannelDescriptorPathTemplate.match( + folderChannelDescriptorName, + ).channel_descriptor; } /** @@ -1806,7 +2215,7 @@ export class MetricServiceClient { * @param {string} group * @returns {string} Resource name string. */ - folderGroupPath(folder:string,group:string) { + folderGroupPath(folder: string, group: string) { return this.pathTemplates.folderGroupPathTemplate.render({ folder: folder, group: group, @@ -1821,7 +2230,8 @@ export class MetricServiceClient { * @returns {string} A string representing the folder. */ matchFolderFromFolderGroupName(folderGroupName: string) { - return this.pathTemplates.folderGroupPathTemplate.match(folderGroupName).folder; + return this.pathTemplates.folderGroupPathTemplate.match(folderGroupName) + .folder; } /** @@ -1832,7 +2242,8 @@ export class MetricServiceClient { * @returns {string} A string representing the group. */ matchGroupFromFolderGroupName(folderGroupName: string) { - return this.pathTemplates.folderGroupPathTemplate.match(folderGroupName).group; + return this.pathTemplates.folderGroupPathTemplate.match(folderGroupName) + .group; } /** @@ -1842,7 +2253,7 @@ export class MetricServiceClient { * @param {string} metric_descriptor * @returns {string} Resource name string. */ - folderMetricDescriptorPath(folder:string,metricDescriptor:string) { + folderMetricDescriptorPath(folder: string, metricDescriptor: string) { return this.pathTemplates.folderMetricDescriptorPathTemplate.render({ folder: folder, metric_descriptor: metricDescriptor, @@ -1856,8 +2267,12 @@ export class MetricServiceClient { * A fully-qualified path representing folder_metric_descriptor resource. * @returns {string} A string representing the folder. */ - matchFolderFromFolderMetricDescriptorName(folderMetricDescriptorName: string) { - return this.pathTemplates.folderMetricDescriptorPathTemplate.match(folderMetricDescriptorName).folder; + matchFolderFromFolderMetricDescriptorName( + folderMetricDescriptorName: string, + ) { + return this.pathTemplates.folderMetricDescriptorPathTemplate.match( + folderMetricDescriptorName, + ).folder; } /** @@ -1867,8 +2282,12 @@ export class MetricServiceClient { * A fully-qualified path representing folder_metric_descriptor resource. * @returns {string} A string representing the metric_descriptor. */ - matchMetricDescriptorFromFolderMetricDescriptorName(folderMetricDescriptorName: string) { - return this.pathTemplates.folderMetricDescriptorPathTemplate.match(folderMetricDescriptorName).metric_descriptor; + matchMetricDescriptorFromFolderMetricDescriptorName( + folderMetricDescriptorName: string, + ) { + return this.pathTemplates.folderMetricDescriptorPathTemplate.match( + folderMetricDescriptorName, + ).metric_descriptor; } /** @@ -1878,11 +2297,16 @@ export class MetricServiceClient { * @param {string} monitored_resource_descriptor * @returns {string} Resource name string. */ - folderMonitoredResourceDescriptorPath(folder:string,monitoredResourceDescriptor:string) { - return this.pathTemplates.folderMonitoredResourceDescriptorPathTemplate.render({ - folder: folder, - monitored_resource_descriptor: monitoredResourceDescriptor, - }); + folderMonitoredResourceDescriptorPath( + folder: string, + monitoredResourceDescriptor: string, + ) { + return this.pathTemplates.folderMonitoredResourceDescriptorPathTemplate.render( + { + folder: folder, + monitored_resource_descriptor: monitoredResourceDescriptor, + }, + ); } /** @@ -1892,8 +2316,12 @@ export class MetricServiceClient { * A fully-qualified path representing folder_monitored_resource_descriptor resource. * @returns {string} A string representing the folder. */ - matchFolderFromFolderMonitoredResourceDescriptorName(folderMonitoredResourceDescriptorName: string) { - return this.pathTemplates.folderMonitoredResourceDescriptorPathTemplate.match(folderMonitoredResourceDescriptorName).folder; + matchFolderFromFolderMonitoredResourceDescriptorName( + folderMonitoredResourceDescriptorName: string, + ) { + return this.pathTemplates.folderMonitoredResourceDescriptorPathTemplate.match( + folderMonitoredResourceDescriptorName, + ).folder; } /** @@ -1903,8 +2331,12 @@ export class MetricServiceClient { * A fully-qualified path representing folder_monitored_resource_descriptor resource. * @returns {string} A string representing the monitored_resource_descriptor. */ - matchMonitoredResourceDescriptorFromFolderMonitoredResourceDescriptorName(folderMonitoredResourceDescriptorName: string) { - return this.pathTemplates.folderMonitoredResourceDescriptorPathTemplate.match(folderMonitoredResourceDescriptorName).monitored_resource_descriptor; + matchMonitoredResourceDescriptorFromFolderMonitoredResourceDescriptorName( + folderMonitoredResourceDescriptorName: string, + ) { + return this.pathTemplates.folderMonitoredResourceDescriptorPathTemplate.match( + folderMonitoredResourceDescriptorName, + ).monitored_resource_descriptor; } /** @@ -1914,7 +2346,7 @@ export class MetricServiceClient { * @param {string} notification_channel * @returns {string} Resource name string. */ - folderNotificationChannelPath(folder:string,notificationChannel:string) { + folderNotificationChannelPath(folder: string, notificationChannel: string) { return this.pathTemplates.folderNotificationChannelPathTemplate.render({ folder: folder, notification_channel: notificationChannel, @@ -1928,8 +2360,12 @@ export class MetricServiceClient { * A fully-qualified path representing folder_notification_channel resource. * @returns {string} A string representing the folder. */ - matchFolderFromFolderNotificationChannelName(folderNotificationChannelName: string) { - return this.pathTemplates.folderNotificationChannelPathTemplate.match(folderNotificationChannelName).folder; + matchFolderFromFolderNotificationChannelName( + folderNotificationChannelName: string, + ) { + return this.pathTemplates.folderNotificationChannelPathTemplate.match( + folderNotificationChannelName, + ).folder; } /** @@ -1939,8 +2375,12 @@ export class MetricServiceClient { * A fully-qualified path representing folder_notification_channel resource. * @returns {string} A string representing the notification_channel. */ - matchNotificationChannelFromFolderNotificationChannelName(folderNotificationChannelName: string) { - return this.pathTemplates.folderNotificationChannelPathTemplate.match(folderNotificationChannelName).notification_channel; + matchNotificationChannelFromFolderNotificationChannelName( + folderNotificationChannelName: string, + ) { + return this.pathTemplates.folderNotificationChannelPathTemplate.match( + folderNotificationChannelName, + ).notification_channel; } /** @@ -1950,7 +2390,7 @@ export class MetricServiceClient { * @param {string} service * @returns {string} Resource name string. */ - folderServicePath(folder:string,service:string) { + folderServicePath(folder: string, service: string) { return this.pathTemplates.folderServicePathTemplate.render({ folder: folder, service: service, @@ -1965,7 +2405,8 @@ export class MetricServiceClient { * @returns {string} A string representing the folder. */ matchFolderFromFolderServiceName(folderServiceName: string) { - return this.pathTemplates.folderServicePathTemplate.match(folderServiceName).folder; + return this.pathTemplates.folderServicePathTemplate.match(folderServiceName) + .folder; } /** @@ -1976,7 +2417,8 @@ export class MetricServiceClient { * @returns {string} A string representing the service. */ matchServiceFromFolderServiceName(folderServiceName: string) { - return this.pathTemplates.folderServicePathTemplate.match(folderServiceName).service; + return this.pathTemplates.folderServicePathTemplate.match(folderServiceName) + .service; } /** @@ -1987,12 +2429,18 @@ export class MetricServiceClient { * @param {string} service_level_objective * @returns {string} Resource name string. */ - folderServiceServiceLevelObjectivePath(folder:string,service:string,serviceLevelObjective:string) { - return this.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.render({ - folder: folder, - service: service, - service_level_objective: serviceLevelObjective, - }); + folderServiceServiceLevelObjectivePath( + folder: string, + service: string, + serviceLevelObjective: string, + ) { + return this.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.render( + { + folder: folder, + service: service, + service_level_objective: serviceLevelObjective, + }, + ); } /** @@ -2002,8 +2450,12 @@ export class MetricServiceClient { * A fully-qualified path representing folder_service_service_level_objective resource. * @returns {string} A string representing the folder. */ - matchFolderFromFolderServiceServiceLevelObjectiveName(folderServiceServiceLevelObjectiveName: string) { - return this.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match(folderServiceServiceLevelObjectiveName).folder; + matchFolderFromFolderServiceServiceLevelObjectiveName( + folderServiceServiceLevelObjectiveName: string, + ) { + return this.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match( + folderServiceServiceLevelObjectiveName, + ).folder; } /** @@ -2013,8 +2465,12 @@ export class MetricServiceClient { * A fully-qualified path representing folder_service_service_level_objective resource. * @returns {string} A string representing the service. */ - matchServiceFromFolderServiceServiceLevelObjectiveName(folderServiceServiceLevelObjectiveName: string) { - return this.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match(folderServiceServiceLevelObjectiveName).service; + matchServiceFromFolderServiceServiceLevelObjectiveName( + folderServiceServiceLevelObjectiveName: string, + ) { + return this.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match( + folderServiceServiceLevelObjectiveName, + ).service; } /** @@ -2024,8 +2480,12 @@ export class MetricServiceClient { * A fully-qualified path representing folder_service_service_level_objective resource. * @returns {string} A string representing the service_level_objective. */ - matchServiceLevelObjectiveFromFolderServiceServiceLevelObjectiveName(folderServiceServiceLevelObjectiveName: string) { - return this.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match(folderServiceServiceLevelObjectiveName).service_level_objective; + matchServiceLevelObjectiveFromFolderServiceServiceLevelObjectiveName( + folderServiceServiceLevelObjectiveName: string, + ) { + return this.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match( + folderServiceServiceLevelObjectiveName, + ).service_level_objective; } /** @@ -2035,7 +2495,7 @@ export class MetricServiceClient { * @param {string} uptime_check_config * @returns {string} Resource name string. */ - folderUptimeCheckConfigPath(folder:string,uptimeCheckConfig:string) { + folderUptimeCheckConfigPath(folder: string, uptimeCheckConfig: string) { return this.pathTemplates.folderUptimeCheckConfigPathTemplate.render({ folder: folder, uptime_check_config: uptimeCheckConfig, @@ -2049,8 +2509,12 @@ export class MetricServiceClient { * A fully-qualified path representing folder_uptime_check_config resource. * @returns {string} A string representing the folder. */ - matchFolderFromFolderUptimeCheckConfigName(folderUptimeCheckConfigName: string) { - return this.pathTemplates.folderUptimeCheckConfigPathTemplate.match(folderUptimeCheckConfigName).folder; + matchFolderFromFolderUptimeCheckConfigName( + folderUptimeCheckConfigName: string, + ) { + return this.pathTemplates.folderUptimeCheckConfigPathTemplate.match( + folderUptimeCheckConfigName, + ).folder; } /** @@ -2060,8 +2524,12 @@ export class MetricServiceClient { * A fully-qualified path representing folder_uptime_check_config resource. * @returns {string} A string representing the uptime_check_config. */ - matchUptimeCheckConfigFromFolderUptimeCheckConfigName(folderUptimeCheckConfigName: string) { - return this.pathTemplates.folderUptimeCheckConfigPathTemplate.match(folderUptimeCheckConfigName).uptime_check_config; + matchUptimeCheckConfigFromFolderUptimeCheckConfigName( + folderUptimeCheckConfigName: string, + ) { + return this.pathTemplates.folderUptimeCheckConfigPathTemplate.match( + folderUptimeCheckConfigName, + ).uptime_check_config; } /** @@ -2071,7 +2539,7 @@ export class MetricServiceClient { * @param {string} alert_policy * @returns {string} Resource name string. */ - organizationAlertPolicyPath(organization:string,alertPolicy:string) { + organizationAlertPolicyPath(organization: string, alertPolicy: string) { return this.pathTemplates.organizationAlertPolicyPathTemplate.render({ organization: organization, alert_policy: alertPolicy, @@ -2085,8 +2553,12 @@ export class MetricServiceClient { * A fully-qualified path representing organization_alert_policy resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationAlertPolicyName(organizationAlertPolicyName: string) { - return this.pathTemplates.organizationAlertPolicyPathTemplate.match(organizationAlertPolicyName).organization; + matchOrganizationFromOrganizationAlertPolicyName( + organizationAlertPolicyName: string, + ) { + return this.pathTemplates.organizationAlertPolicyPathTemplate.match( + organizationAlertPolicyName, + ).organization; } /** @@ -2096,8 +2568,12 @@ export class MetricServiceClient { * A fully-qualified path representing organization_alert_policy resource. * @returns {string} A string representing the alert_policy. */ - matchAlertPolicyFromOrganizationAlertPolicyName(organizationAlertPolicyName: string) { - return this.pathTemplates.organizationAlertPolicyPathTemplate.match(organizationAlertPolicyName).alert_policy; + matchAlertPolicyFromOrganizationAlertPolicyName( + organizationAlertPolicyName: string, + ) { + return this.pathTemplates.organizationAlertPolicyPathTemplate.match( + organizationAlertPolicyName, + ).alert_policy; } /** @@ -2108,12 +2584,18 @@ export class MetricServiceClient { * @param {string} condition * @returns {string} Resource name string. */ - organizationAlertPolicyConditionPath(organization:string,alertPolicy:string,condition:string) { - return this.pathTemplates.organizationAlertPolicyConditionPathTemplate.render({ - organization: organization, - alert_policy: alertPolicy, - condition: condition, - }); + organizationAlertPolicyConditionPath( + organization: string, + alertPolicy: string, + condition: string, + ) { + return this.pathTemplates.organizationAlertPolicyConditionPathTemplate.render( + { + organization: organization, + alert_policy: alertPolicy, + condition: condition, + }, + ); } /** @@ -2123,8 +2605,12 @@ export class MetricServiceClient { * A fully-qualified path representing organization_alert_policy_condition resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationAlertPolicyConditionName(organizationAlertPolicyConditionName: string) { - return this.pathTemplates.organizationAlertPolicyConditionPathTemplate.match(organizationAlertPolicyConditionName).organization; + matchOrganizationFromOrganizationAlertPolicyConditionName( + organizationAlertPolicyConditionName: string, + ) { + return this.pathTemplates.organizationAlertPolicyConditionPathTemplate.match( + organizationAlertPolicyConditionName, + ).organization; } /** @@ -2134,8 +2620,12 @@ export class MetricServiceClient { * A fully-qualified path representing organization_alert_policy_condition resource. * @returns {string} A string representing the alert_policy. */ - matchAlertPolicyFromOrganizationAlertPolicyConditionName(organizationAlertPolicyConditionName: string) { - return this.pathTemplates.organizationAlertPolicyConditionPathTemplate.match(organizationAlertPolicyConditionName).alert_policy; + matchAlertPolicyFromOrganizationAlertPolicyConditionName( + organizationAlertPolicyConditionName: string, + ) { + return this.pathTemplates.organizationAlertPolicyConditionPathTemplate.match( + organizationAlertPolicyConditionName, + ).alert_policy; } /** @@ -2145,8 +2635,12 @@ export class MetricServiceClient { * A fully-qualified path representing organization_alert_policy_condition resource. * @returns {string} A string representing the condition. */ - matchConditionFromOrganizationAlertPolicyConditionName(organizationAlertPolicyConditionName: string) { - return this.pathTemplates.organizationAlertPolicyConditionPathTemplate.match(organizationAlertPolicyConditionName).condition; + matchConditionFromOrganizationAlertPolicyConditionName( + organizationAlertPolicyConditionName: string, + ) { + return this.pathTemplates.organizationAlertPolicyConditionPathTemplate.match( + organizationAlertPolicyConditionName, + ).condition; } /** @@ -2156,7 +2650,10 @@ export class MetricServiceClient { * @param {string} channel_descriptor * @returns {string} Resource name string. */ - organizationChannelDescriptorPath(organization:string,channelDescriptor:string) { + organizationChannelDescriptorPath( + organization: string, + channelDescriptor: string, + ) { return this.pathTemplates.organizationChannelDescriptorPathTemplate.render({ organization: organization, channel_descriptor: channelDescriptor, @@ -2170,8 +2667,12 @@ export class MetricServiceClient { * A fully-qualified path representing organization_channel_descriptor resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationChannelDescriptorName(organizationChannelDescriptorName: string) { - return this.pathTemplates.organizationChannelDescriptorPathTemplate.match(organizationChannelDescriptorName).organization; + matchOrganizationFromOrganizationChannelDescriptorName( + organizationChannelDescriptorName: string, + ) { + return this.pathTemplates.organizationChannelDescriptorPathTemplate.match( + organizationChannelDescriptorName, + ).organization; } /** @@ -2181,8 +2682,12 @@ export class MetricServiceClient { * A fully-qualified path representing organization_channel_descriptor resource. * @returns {string} A string representing the channel_descriptor. */ - matchChannelDescriptorFromOrganizationChannelDescriptorName(organizationChannelDescriptorName: string) { - return this.pathTemplates.organizationChannelDescriptorPathTemplate.match(organizationChannelDescriptorName).channel_descriptor; + matchChannelDescriptorFromOrganizationChannelDescriptorName( + organizationChannelDescriptorName: string, + ) { + return this.pathTemplates.organizationChannelDescriptorPathTemplate.match( + organizationChannelDescriptorName, + ).channel_descriptor; } /** @@ -2192,7 +2697,7 @@ export class MetricServiceClient { * @param {string} group * @returns {string} Resource name string. */ - organizationGroupPath(organization:string,group:string) { + organizationGroupPath(organization: string, group: string) { return this.pathTemplates.organizationGroupPathTemplate.render({ organization: organization, group: group, @@ -2207,7 +2712,9 @@ export class MetricServiceClient { * @returns {string} A string representing the organization. */ matchOrganizationFromOrganizationGroupName(organizationGroupName: string) { - return this.pathTemplates.organizationGroupPathTemplate.match(organizationGroupName).organization; + return this.pathTemplates.organizationGroupPathTemplate.match( + organizationGroupName, + ).organization; } /** @@ -2218,7 +2725,9 @@ export class MetricServiceClient { * @returns {string} A string representing the group. */ matchGroupFromOrganizationGroupName(organizationGroupName: string) { - return this.pathTemplates.organizationGroupPathTemplate.match(organizationGroupName).group; + return this.pathTemplates.organizationGroupPathTemplate.match( + organizationGroupName, + ).group; } /** @@ -2228,7 +2737,10 @@ export class MetricServiceClient { * @param {string} metric_descriptor * @returns {string} Resource name string. */ - organizationMetricDescriptorPath(organization:string,metricDescriptor:string) { + organizationMetricDescriptorPath( + organization: string, + metricDescriptor: string, + ) { return this.pathTemplates.organizationMetricDescriptorPathTemplate.render({ organization: organization, metric_descriptor: metricDescriptor, @@ -2242,8 +2754,12 @@ export class MetricServiceClient { * A fully-qualified path representing organization_metric_descriptor resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationMetricDescriptorName(organizationMetricDescriptorName: string) { - return this.pathTemplates.organizationMetricDescriptorPathTemplate.match(organizationMetricDescriptorName).organization; + matchOrganizationFromOrganizationMetricDescriptorName( + organizationMetricDescriptorName: string, + ) { + return this.pathTemplates.organizationMetricDescriptorPathTemplate.match( + organizationMetricDescriptorName, + ).organization; } /** @@ -2253,8 +2769,12 @@ export class MetricServiceClient { * A fully-qualified path representing organization_metric_descriptor resource. * @returns {string} A string representing the metric_descriptor. */ - matchMetricDescriptorFromOrganizationMetricDescriptorName(organizationMetricDescriptorName: string) { - return this.pathTemplates.organizationMetricDescriptorPathTemplate.match(organizationMetricDescriptorName).metric_descriptor; + matchMetricDescriptorFromOrganizationMetricDescriptorName( + organizationMetricDescriptorName: string, + ) { + return this.pathTemplates.organizationMetricDescriptorPathTemplate.match( + organizationMetricDescriptorName, + ).metric_descriptor; } /** @@ -2264,11 +2784,16 @@ export class MetricServiceClient { * @param {string} monitored_resource_descriptor * @returns {string} Resource name string. */ - organizationMonitoredResourceDescriptorPath(organization:string,monitoredResourceDescriptor:string) { - return this.pathTemplates.organizationMonitoredResourceDescriptorPathTemplate.render({ - organization: organization, - monitored_resource_descriptor: monitoredResourceDescriptor, - }); + organizationMonitoredResourceDescriptorPath( + organization: string, + monitoredResourceDescriptor: string, + ) { + return this.pathTemplates.organizationMonitoredResourceDescriptorPathTemplate.render( + { + organization: organization, + monitored_resource_descriptor: monitoredResourceDescriptor, + }, + ); } /** @@ -2278,8 +2803,12 @@ export class MetricServiceClient { * A fully-qualified path representing organization_monitored_resource_descriptor resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationMonitoredResourceDescriptorName(organizationMonitoredResourceDescriptorName: string) { - return this.pathTemplates.organizationMonitoredResourceDescriptorPathTemplate.match(organizationMonitoredResourceDescriptorName).organization; + matchOrganizationFromOrganizationMonitoredResourceDescriptorName( + organizationMonitoredResourceDescriptorName: string, + ) { + return this.pathTemplates.organizationMonitoredResourceDescriptorPathTemplate.match( + organizationMonitoredResourceDescriptorName, + ).organization; } /** @@ -2289,8 +2818,12 @@ export class MetricServiceClient { * A fully-qualified path representing organization_monitored_resource_descriptor resource. * @returns {string} A string representing the monitored_resource_descriptor. */ - matchMonitoredResourceDescriptorFromOrganizationMonitoredResourceDescriptorName(organizationMonitoredResourceDescriptorName: string) { - return this.pathTemplates.organizationMonitoredResourceDescriptorPathTemplate.match(organizationMonitoredResourceDescriptorName).monitored_resource_descriptor; + matchMonitoredResourceDescriptorFromOrganizationMonitoredResourceDescriptorName( + organizationMonitoredResourceDescriptorName: string, + ) { + return this.pathTemplates.organizationMonitoredResourceDescriptorPathTemplate.match( + organizationMonitoredResourceDescriptorName, + ).monitored_resource_descriptor; } /** @@ -2300,11 +2833,16 @@ export class MetricServiceClient { * @param {string} notification_channel * @returns {string} Resource name string. */ - organizationNotificationChannelPath(organization:string,notificationChannel:string) { - return this.pathTemplates.organizationNotificationChannelPathTemplate.render({ - organization: organization, - notification_channel: notificationChannel, - }); + organizationNotificationChannelPath( + organization: string, + notificationChannel: string, + ) { + return this.pathTemplates.organizationNotificationChannelPathTemplate.render( + { + organization: organization, + notification_channel: notificationChannel, + }, + ); } /** @@ -2314,8 +2852,12 @@ export class MetricServiceClient { * A fully-qualified path representing organization_notification_channel resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationNotificationChannelName(organizationNotificationChannelName: string) { - return this.pathTemplates.organizationNotificationChannelPathTemplate.match(organizationNotificationChannelName).organization; + matchOrganizationFromOrganizationNotificationChannelName( + organizationNotificationChannelName: string, + ) { + return this.pathTemplates.organizationNotificationChannelPathTemplate.match( + organizationNotificationChannelName, + ).organization; } /** @@ -2325,8 +2867,12 @@ export class MetricServiceClient { * A fully-qualified path representing organization_notification_channel resource. * @returns {string} A string representing the notification_channel. */ - matchNotificationChannelFromOrganizationNotificationChannelName(organizationNotificationChannelName: string) { - return this.pathTemplates.organizationNotificationChannelPathTemplate.match(organizationNotificationChannelName).notification_channel; + matchNotificationChannelFromOrganizationNotificationChannelName( + organizationNotificationChannelName: string, + ) { + return this.pathTemplates.organizationNotificationChannelPathTemplate.match( + organizationNotificationChannelName, + ).notification_channel; } /** @@ -2336,7 +2882,7 @@ export class MetricServiceClient { * @param {string} service * @returns {string} Resource name string. */ - organizationServicePath(organization:string,service:string) { + organizationServicePath(organization: string, service: string) { return this.pathTemplates.organizationServicePathTemplate.render({ organization: organization, service: service, @@ -2350,8 +2896,12 @@ export class MetricServiceClient { * A fully-qualified path representing organization_service resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationServiceName(organizationServiceName: string) { - return this.pathTemplates.organizationServicePathTemplate.match(organizationServiceName).organization; + matchOrganizationFromOrganizationServiceName( + organizationServiceName: string, + ) { + return this.pathTemplates.organizationServicePathTemplate.match( + organizationServiceName, + ).organization; } /** @@ -2362,7 +2912,9 @@ export class MetricServiceClient { * @returns {string} A string representing the service. */ matchServiceFromOrganizationServiceName(organizationServiceName: string) { - return this.pathTemplates.organizationServicePathTemplate.match(organizationServiceName).service; + return this.pathTemplates.organizationServicePathTemplate.match( + organizationServiceName, + ).service; } /** @@ -2373,12 +2925,18 @@ export class MetricServiceClient { * @param {string} service_level_objective * @returns {string} Resource name string. */ - organizationServiceServiceLevelObjectivePath(organization:string,service:string,serviceLevelObjective:string) { - return this.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.render({ - organization: organization, - service: service, - service_level_objective: serviceLevelObjective, - }); + organizationServiceServiceLevelObjectivePath( + organization: string, + service: string, + serviceLevelObjective: string, + ) { + return this.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.render( + { + organization: organization, + service: service, + service_level_objective: serviceLevelObjective, + }, + ); } /** @@ -2388,8 +2946,12 @@ export class MetricServiceClient { * A fully-qualified path representing organization_service_service_level_objective resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationServiceServiceLevelObjectiveName(organizationServiceServiceLevelObjectiveName: string) { - return this.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match(organizationServiceServiceLevelObjectiveName).organization; + matchOrganizationFromOrganizationServiceServiceLevelObjectiveName( + organizationServiceServiceLevelObjectiveName: string, + ) { + return this.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match( + organizationServiceServiceLevelObjectiveName, + ).organization; } /** @@ -2399,8 +2961,12 @@ export class MetricServiceClient { * A fully-qualified path representing organization_service_service_level_objective resource. * @returns {string} A string representing the service. */ - matchServiceFromOrganizationServiceServiceLevelObjectiveName(organizationServiceServiceLevelObjectiveName: string) { - return this.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match(organizationServiceServiceLevelObjectiveName).service; + matchServiceFromOrganizationServiceServiceLevelObjectiveName( + organizationServiceServiceLevelObjectiveName: string, + ) { + return this.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match( + organizationServiceServiceLevelObjectiveName, + ).service; } /** @@ -2410,8 +2976,12 @@ export class MetricServiceClient { * A fully-qualified path representing organization_service_service_level_objective resource. * @returns {string} A string representing the service_level_objective. */ - matchServiceLevelObjectiveFromOrganizationServiceServiceLevelObjectiveName(organizationServiceServiceLevelObjectiveName: string) { - return this.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match(organizationServiceServiceLevelObjectiveName).service_level_objective; + matchServiceLevelObjectiveFromOrganizationServiceServiceLevelObjectiveName( + organizationServiceServiceLevelObjectiveName: string, + ) { + return this.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match( + organizationServiceServiceLevelObjectiveName, + ).service_level_objective; } /** @@ -2421,7 +2991,10 @@ export class MetricServiceClient { * @param {string} uptime_check_config * @returns {string} Resource name string. */ - organizationUptimeCheckConfigPath(organization:string,uptimeCheckConfig:string) { + organizationUptimeCheckConfigPath( + organization: string, + uptimeCheckConfig: string, + ) { return this.pathTemplates.organizationUptimeCheckConfigPathTemplate.render({ organization: organization, uptime_check_config: uptimeCheckConfig, @@ -2435,8 +3008,12 @@ export class MetricServiceClient { * A fully-qualified path representing organization_uptime_check_config resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationUptimeCheckConfigName(organizationUptimeCheckConfigName: string) { - return this.pathTemplates.organizationUptimeCheckConfigPathTemplate.match(organizationUptimeCheckConfigName).organization; + matchOrganizationFromOrganizationUptimeCheckConfigName( + organizationUptimeCheckConfigName: string, + ) { + return this.pathTemplates.organizationUptimeCheckConfigPathTemplate.match( + organizationUptimeCheckConfigName, + ).organization; } /** @@ -2446,8 +3023,12 @@ export class MetricServiceClient { * A fully-qualified path representing organization_uptime_check_config resource. * @returns {string} A string representing the uptime_check_config. */ - matchUptimeCheckConfigFromOrganizationUptimeCheckConfigName(organizationUptimeCheckConfigName: string) { - return this.pathTemplates.organizationUptimeCheckConfigPathTemplate.match(organizationUptimeCheckConfigName).uptime_check_config; + matchUptimeCheckConfigFromOrganizationUptimeCheckConfigName( + organizationUptimeCheckConfigName: string, + ) { + return this.pathTemplates.organizationUptimeCheckConfigPathTemplate.match( + organizationUptimeCheckConfigName, + ).uptime_check_config; } /** @@ -2457,7 +3038,7 @@ export class MetricServiceClient { * @param {string} alert_policy * @returns {string} Resource name string. */ - projectAlertPolicyPath(project:string,alertPolicy:string) { + projectAlertPolicyPath(project: string, alertPolicy: string) { return this.pathTemplates.projectAlertPolicyPathTemplate.render({ project: project, alert_policy: alertPolicy, @@ -2472,7 +3053,9 @@ export class MetricServiceClient { * @returns {string} A string representing the project. */ matchProjectFromProjectAlertPolicyName(projectAlertPolicyName: string) { - return this.pathTemplates.projectAlertPolicyPathTemplate.match(projectAlertPolicyName).project; + return this.pathTemplates.projectAlertPolicyPathTemplate.match( + projectAlertPolicyName, + ).project; } /** @@ -2483,7 +3066,9 @@ export class MetricServiceClient { * @returns {string} A string representing the alert_policy. */ matchAlertPolicyFromProjectAlertPolicyName(projectAlertPolicyName: string) { - return this.pathTemplates.projectAlertPolicyPathTemplate.match(projectAlertPolicyName).alert_policy; + return this.pathTemplates.projectAlertPolicyPathTemplate.match( + projectAlertPolicyName, + ).alert_policy; } /** @@ -2494,7 +3079,11 @@ export class MetricServiceClient { * @param {string} condition * @returns {string} Resource name string. */ - projectAlertPolicyConditionPath(project:string,alertPolicy:string,condition:string) { + projectAlertPolicyConditionPath( + project: string, + alertPolicy: string, + condition: string, + ) { return this.pathTemplates.projectAlertPolicyConditionPathTemplate.render({ project: project, alert_policy: alertPolicy, @@ -2509,8 +3098,12 @@ export class MetricServiceClient { * A fully-qualified path representing project_alert_policy_condition resource. * @returns {string} A string representing the project. */ - matchProjectFromProjectAlertPolicyConditionName(projectAlertPolicyConditionName: string) { - return this.pathTemplates.projectAlertPolicyConditionPathTemplate.match(projectAlertPolicyConditionName).project; + matchProjectFromProjectAlertPolicyConditionName( + projectAlertPolicyConditionName: string, + ) { + return this.pathTemplates.projectAlertPolicyConditionPathTemplate.match( + projectAlertPolicyConditionName, + ).project; } /** @@ -2520,8 +3113,12 @@ export class MetricServiceClient { * A fully-qualified path representing project_alert_policy_condition resource. * @returns {string} A string representing the alert_policy. */ - matchAlertPolicyFromProjectAlertPolicyConditionName(projectAlertPolicyConditionName: string) { - return this.pathTemplates.projectAlertPolicyConditionPathTemplate.match(projectAlertPolicyConditionName).alert_policy; + matchAlertPolicyFromProjectAlertPolicyConditionName( + projectAlertPolicyConditionName: string, + ) { + return this.pathTemplates.projectAlertPolicyConditionPathTemplate.match( + projectAlertPolicyConditionName, + ).alert_policy; } /** @@ -2531,8 +3128,12 @@ export class MetricServiceClient { * A fully-qualified path representing project_alert_policy_condition resource. * @returns {string} A string representing the condition. */ - matchConditionFromProjectAlertPolicyConditionName(projectAlertPolicyConditionName: string) { - return this.pathTemplates.projectAlertPolicyConditionPathTemplate.match(projectAlertPolicyConditionName).condition; + matchConditionFromProjectAlertPolicyConditionName( + projectAlertPolicyConditionName: string, + ) { + return this.pathTemplates.projectAlertPolicyConditionPathTemplate.match( + projectAlertPolicyConditionName, + ).condition; } /** @@ -2542,7 +3143,7 @@ export class MetricServiceClient { * @param {string} channel_descriptor * @returns {string} Resource name string. */ - projectChannelDescriptorPath(project:string,channelDescriptor:string) { + projectChannelDescriptorPath(project: string, channelDescriptor: string) { return this.pathTemplates.projectChannelDescriptorPathTemplate.render({ project: project, channel_descriptor: channelDescriptor, @@ -2556,8 +3157,12 @@ export class MetricServiceClient { * A fully-qualified path representing project_channel_descriptor resource. * @returns {string} A string representing the project. */ - matchProjectFromProjectChannelDescriptorName(projectChannelDescriptorName: string) { - return this.pathTemplates.projectChannelDescriptorPathTemplate.match(projectChannelDescriptorName).project; + matchProjectFromProjectChannelDescriptorName( + projectChannelDescriptorName: string, + ) { + return this.pathTemplates.projectChannelDescriptorPathTemplate.match( + projectChannelDescriptorName, + ).project; } /** @@ -2567,8 +3172,12 @@ export class MetricServiceClient { * A fully-qualified path representing project_channel_descriptor resource. * @returns {string} A string representing the channel_descriptor. */ - matchChannelDescriptorFromProjectChannelDescriptorName(projectChannelDescriptorName: string) { - return this.pathTemplates.projectChannelDescriptorPathTemplate.match(projectChannelDescriptorName).channel_descriptor; + matchChannelDescriptorFromProjectChannelDescriptorName( + projectChannelDescriptorName: string, + ) { + return this.pathTemplates.projectChannelDescriptorPathTemplate.match( + projectChannelDescriptorName, + ).channel_descriptor; } /** @@ -2578,7 +3187,7 @@ export class MetricServiceClient { * @param {string} group * @returns {string} Resource name string. */ - projectGroupPath(project:string,group:string) { + projectGroupPath(project: string, group: string) { return this.pathTemplates.projectGroupPathTemplate.render({ project: project, group: group, @@ -2593,7 +3202,8 @@ export class MetricServiceClient { * @returns {string} A string representing the project. */ matchProjectFromProjectGroupName(projectGroupName: string) { - return this.pathTemplates.projectGroupPathTemplate.match(projectGroupName).project; + return this.pathTemplates.projectGroupPathTemplate.match(projectGroupName) + .project; } /** @@ -2604,7 +3214,8 @@ export class MetricServiceClient { * @returns {string} A string representing the group. */ matchGroupFromProjectGroupName(projectGroupName: string) { - return this.pathTemplates.projectGroupPathTemplate.match(projectGroupName).group; + return this.pathTemplates.projectGroupPathTemplate.match(projectGroupName) + .group; } /** @@ -2614,7 +3225,7 @@ export class MetricServiceClient { * @param {string} metric_descriptor * @returns {string} Resource name string. */ - projectMetricDescriptorPath(project:string,metricDescriptor:string) { + projectMetricDescriptorPath(project: string, metricDescriptor: string) { return this.pathTemplates.projectMetricDescriptorPathTemplate.render({ project: project, metric_descriptor: metricDescriptor, @@ -2628,8 +3239,12 @@ export class MetricServiceClient { * A fully-qualified path representing project_metric_descriptor resource. * @returns {string} A string representing the project. */ - matchProjectFromProjectMetricDescriptorName(projectMetricDescriptorName: string) { - return this.pathTemplates.projectMetricDescriptorPathTemplate.match(projectMetricDescriptorName).project; + matchProjectFromProjectMetricDescriptorName( + projectMetricDescriptorName: string, + ) { + return this.pathTemplates.projectMetricDescriptorPathTemplate.match( + projectMetricDescriptorName, + ).project; } /** @@ -2639,8 +3254,12 @@ export class MetricServiceClient { * A fully-qualified path representing project_metric_descriptor resource. * @returns {string} A string representing the metric_descriptor. */ - matchMetricDescriptorFromProjectMetricDescriptorName(projectMetricDescriptorName: string) { - return this.pathTemplates.projectMetricDescriptorPathTemplate.match(projectMetricDescriptorName).metric_descriptor; + matchMetricDescriptorFromProjectMetricDescriptorName( + projectMetricDescriptorName: string, + ) { + return this.pathTemplates.projectMetricDescriptorPathTemplate.match( + projectMetricDescriptorName, + ).metric_descriptor; } /** @@ -2650,11 +3269,16 @@ export class MetricServiceClient { * @param {string} monitored_resource_descriptor * @returns {string} Resource name string. */ - projectMonitoredResourceDescriptorPath(project:string,monitoredResourceDescriptor:string) { - return this.pathTemplates.projectMonitoredResourceDescriptorPathTemplate.render({ - project: project, - monitored_resource_descriptor: monitoredResourceDescriptor, - }); + projectMonitoredResourceDescriptorPath( + project: string, + monitoredResourceDescriptor: string, + ) { + return this.pathTemplates.projectMonitoredResourceDescriptorPathTemplate.render( + { + project: project, + monitored_resource_descriptor: monitoredResourceDescriptor, + }, + ); } /** @@ -2664,8 +3288,12 @@ export class MetricServiceClient { * A fully-qualified path representing project_monitored_resource_descriptor resource. * @returns {string} A string representing the project. */ - matchProjectFromProjectMonitoredResourceDescriptorName(projectMonitoredResourceDescriptorName: string) { - return this.pathTemplates.projectMonitoredResourceDescriptorPathTemplate.match(projectMonitoredResourceDescriptorName).project; + matchProjectFromProjectMonitoredResourceDescriptorName( + projectMonitoredResourceDescriptorName: string, + ) { + return this.pathTemplates.projectMonitoredResourceDescriptorPathTemplate.match( + projectMonitoredResourceDescriptorName, + ).project; } /** @@ -2675,8 +3303,12 @@ export class MetricServiceClient { * A fully-qualified path representing project_monitored_resource_descriptor resource. * @returns {string} A string representing the monitored_resource_descriptor. */ - matchMonitoredResourceDescriptorFromProjectMonitoredResourceDescriptorName(projectMonitoredResourceDescriptorName: string) { - return this.pathTemplates.projectMonitoredResourceDescriptorPathTemplate.match(projectMonitoredResourceDescriptorName).monitored_resource_descriptor; + matchMonitoredResourceDescriptorFromProjectMonitoredResourceDescriptorName( + projectMonitoredResourceDescriptorName: string, + ) { + return this.pathTemplates.projectMonitoredResourceDescriptorPathTemplate.match( + projectMonitoredResourceDescriptorName, + ).monitored_resource_descriptor; } /** @@ -2686,7 +3318,7 @@ export class MetricServiceClient { * @param {string} notification_channel * @returns {string} Resource name string. */ - projectNotificationChannelPath(project:string,notificationChannel:string) { + projectNotificationChannelPath(project: string, notificationChannel: string) { return this.pathTemplates.projectNotificationChannelPathTemplate.render({ project: project, notification_channel: notificationChannel, @@ -2700,8 +3332,12 @@ export class MetricServiceClient { * A fully-qualified path representing project_notification_channel resource. * @returns {string} A string representing the project. */ - matchProjectFromProjectNotificationChannelName(projectNotificationChannelName: string) { - return this.pathTemplates.projectNotificationChannelPathTemplate.match(projectNotificationChannelName).project; + matchProjectFromProjectNotificationChannelName( + projectNotificationChannelName: string, + ) { + return this.pathTemplates.projectNotificationChannelPathTemplate.match( + projectNotificationChannelName, + ).project; } /** @@ -2711,8 +3347,12 @@ export class MetricServiceClient { * A fully-qualified path representing project_notification_channel resource. * @returns {string} A string representing the notification_channel. */ - matchNotificationChannelFromProjectNotificationChannelName(projectNotificationChannelName: string) { - return this.pathTemplates.projectNotificationChannelPathTemplate.match(projectNotificationChannelName).notification_channel; + matchNotificationChannelFromProjectNotificationChannelName( + projectNotificationChannelName: string, + ) { + return this.pathTemplates.projectNotificationChannelPathTemplate.match( + projectNotificationChannelName, + ).notification_channel; } /** @@ -2722,7 +3362,7 @@ export class MetricServiceClient { * @param {string} service * @returns {string} Resource name string. */ - projectServicePath(project:string,service:string) { + projectServicePath(project: string, service: string) { return this.pathTemplates.projectServicePathTemplate.render({ project: project, service: service, @@ -2737,7 +3377,9 @@ export class MetricServiceClient { * @returns {string} A string representing the project. */ matchProjectFromProjectServiceName(projectServiceName: string) { - return this.pathTemplates.projectServicePathTemplate.match(projectServiceName).project; + return this.pathTemplates.projectServicePathTemplate.match( + projectServiceName, + ).project; } /** @@ -2748,7 +3390,9 @@ export class MetricServiceClient { * @returns {string} A string representing the service. */ matchServiceFromProjectServiceName(projectServiceName: string) { - return this.pathTemplates.projectServicePathTemplate.match(projectServiceName).service; + return this.pathTemplates.projectServicePathTemplate.match( + projectServiceName, + ).service; } /** @@ -2759,12 +3403,18 @@ export class MetricServiceClient { * @param {string} service_level_objective * @returns {string} Resource name string. */ - projectServiceServiceLevelObjectivePath(project:string,service:string,serviceLevelObjective:string) { - return this.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.render({ - project: project, - service: service, - service_level_objective: serviceLevelObjective, - }); + projectServiceServiceLevelObjectivePath( + project: string, + service: string, + serviceLevelObjective: string, + ) { + return this.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.render( + { + project: project, + service: service, + service_level_objective: serviceLevelObjective, + }, + ); } /** @@ -2774,8 +3424,12 @@ export class MetricServiceClient { * A fully-qualified path representing project_service_service_level_objective resource. * @returns {string} A string representing the project. */ - matchProjectFromProjectServiceServiceLevelObjectiveName(projectServiceServiceLevelObjectiveName: string) { - return this.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match(projectServiceServiceLevelObjectiveName).project; + matchProjectFromProjectServiceServiceLevelObjectiveName( + projectServiceServiceLevelObjectiveName: string, + ) { + return this.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match( + projectServiceServiceLevelObjectiveName, + ).project; } /** @@ -2785,8 +3439,12 @@ export class MetricServiceClient { * A fully-qualified path representing project_service_service_level_objective resource. * @returns {string} A string representing the service. */ - matchServiceFromProjectServiceServiceLevelObjectiveName(projectServiceServiceLevelObjectiveName: string) { - return this.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match(projectServiceServiceLevelObjectiveName).service; + matchServiceFromProjectServiceServiceLevelObjectiveName( + projectServiceServiceLevelObjectiveName: string, + ) { + return this.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match( + projectServiceServiceLevelObjectiveName, + ).service; } /** @@ -2796,8 +3454,12 @@ export class MetricServiceClient { * A fully-qualified path representing project_service_service_level_objective resource. * @returns {string} A string representing the service_level_objective. */ - matchServiceLevelObjectiveFromProjectServiceServiceLevelObjectiveName(projectServiceServiceLevelObjectiveName: string) { - return this.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match(projectServiceServiceLevelObjectiveName).service_level_objective; + matchServiceLevelObjectiveFromProjectServiceServiceLevelObjectiveName( + projectServiceServiceLevelObjectiveName: string, + ) { + return this.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match( + projectServiceServiceLevelObjectiveName, + ).service_level_objective; } /** @@ -2807,7 +3469,7 @@ export class MetricServiceClient { * @param {string} uptime_check_config * @returns {string} Resource name string. */ - projectUptimeCheckConfigPath(project:string,uptimeCheckConfig:string) { + projectUptimeCheckConfigPath(project: string, uptimeCheckConfig: string) { return this.pathTemplates.projectUptimeCheckConfigPathTemplate.render({ project: project, uptime_check_config: uptimeCheckConfig, @@ -2821,8 +3483,12 @@ export class MetricServiceClient { * A fully-qualified path representing project_uptime_check_config resource. * @returns {string} A string representing the project. */ - matchProjectFromProjectUptimeCheckConfigName(projectUptimeCheckConfigName: string) { - return this.pathTemplates.projectUptimeCheckConfigPathTemplate.match(projectUptimeCheckConfigName).project; + matchProjectFromProjectUptimeCheckConfigName( + projectUptimeCheckConfigName: string, + ) { + return this.pathTemplates.projectUptimeCheckConfigPathTemplate.match( + projectUptimeCheckConfigName, + ).project; } /** @@ -2832,8 +3498,12 @@ export class MetricServiceClient { * A fully-qualified path representing project_uptime_check_config resource. * @returns {string} A string representing the uptime_check_config. */ - matchUptimeCheckConfigFromProjectUptimeCheckConfigName(projectUptimeCheckConfigName: string) { - return this.pathTemplates.projectUptimeCheckConfigPathTemplate.match(projectUptimeCheckConfigName).uptime_check_config; + matchUptimeCheckConfigFromProjectUptimeCheckConfigName( + projectUptimeCheckConfigName: string, + ) { + return this.pathTemplates.projectUptimeCheckConfigPathTemplate.match( + projectUptimeCheckConfigName, + ).uptime_check_config; } /** @@ -2844,7 +3514,7 @@ export class MetricServiceClient { */ close(): Promise { if (this.metricServiceStub && !this._terminated) { - return this.metricServiceStub.then(stub => { + return this.metricServiceStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -2852,4 +3522,4 @@ export class MetricServiceClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/core/generator/gapic-generator-typescript/baselines/monitoring-esm/esm/src/v3/notification_channel_service_client.ts.baseline b/core/generator/gapic-generator-typescript/baselines/monitoring-esm/esm/src/v3/notification_channel_service_client.ts.baseline index aaec51a6efb5..c1e026d215d6 100644 --- a/core/generator/gapic-generator-typescript/baselines/monitoring-esm/esm/src/v3/notification_channel_service_client.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/monitoring-esm/esm/src/v3/notification_channel_service_client.ts.baseline @@ -18,15 +18,22 @@ /* global window */ import * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions, PaginationCallback, GaxCall} from 'google-gax'; -import {Transform} from 'stream'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + PaginationCallback, + GaxCall, +} from 'google-gax'; +import { Transform } from 'stream'; // @ts-ignore import type * as protos from '../../../protos/protos.js'; import * as notification_channel_service_client_config from './notification_channel_service_client_config.json'; import fs from 'fs'; import path from 'path'; -import {fileURLToPath} from 'url'; -import {getJSON} from '../json-helper.cjs'; +import { fileURLToPath } from 'url'; +import { getJSON } from '../json-helper.cjs'; // @ts-ignore const dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -36,15 +43,15 @@ const dirname = path.dirname(fileURLToPath(import.meta.url)); * This file defines retry strategy and timeouts for all API methods in this library. */ const gapicConfig = getJSON( - path.join(dirname, 'notification_channel_service_client_config.json') + path.join(dirname, 'notification_channel_service_client_config.json'), ); const jsonProtos = getJSON( - path.join(dirname, '..', '..', '..', 'protos/protos.json') + path.join(dirname, '..', '..', '..', 'protos/protos.json'), ); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; const version = getJSON( - path.join(dirname, '..', '..', '..', '..', 'package.json') + path.join(dirname, '..', '..', '..', '..', 'package.json'), ).version; /** @@ -60,7 +67,7 @@ export class NotificationChannelServiceClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('monitoring'); @@ -72,9 +79,9 @@ export class NotificationChannelServiceClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; - notificationChannelServiceStub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; + notificationChannelServiceStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of NotificationChannelServiceClient. @@ -116,21 +123,43 @@ export class NotificationChannelServiceClient { * const client = new NotificationChannelServiceClient({fallback: 'rest'}, gax); * ``` */ - constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { // Ensure that options include all the required fields. - const staticMembers = this.constructor as typeof NotificationChannelServiceClient; - if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { - throw new Error('Please set either universe_domain or universeDomain, but not both.'); + const staticMembers = this + .constructor as typeof NotificationChannelServiceClient; + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); } - const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; - this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; this._servicePath = 'monitoring.' + this._universeDomain; - const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; - const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. if (servicePath !== this._servicePath && !('scopes' in opts)) { @@ -152,7 +181,7 @@ export class NotificationChannelServiceClient { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; @@ -169,10 +198,7 @@ export class NotificationChannelServiceClient { const isEsm = true; const isEsmString = isEsm ? '-esm' : '-cjs'; // Determine the client header string. - const clientHeader = [ - `gax/${this._gaxModule.version}`, - `gapic/${version}`, - ]; + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/{process.versions.node}${isEsmString}`); } else { @@ -180,7 +206,7 @@ export class NotificationChannelServiceClient { } if (!opts.fallback) { clientHeader.push(`grpc/${this._gaxGrpc.grpcVersion}`); - } else if (opts.fallback === 'rest' ) { + } else if (opts.fallback === 'rest') { clientHeader.push(`rest/${this._gaxGrpc.grpcVersion}`); } if (opts.libName && opts.libVersion) { @@ -188,83 +214,92 @@ export class NotificationChannelServiceClient { } // Load the applicable protos. - this._protos = this._gaxGrpc.loadProtoJSON(jsonProtos as gax.protobuf.INamespace); + this._protos = this._gaxGrpc.loadProtoJSON( + jsonProtos as gax.protobuf.INamespace, + ); // This API contains "path templates"; forward-slash-separated // identifiers to uniquely identify resources within the API. // Create useful helper objects for these. this.pathTemplates = { folderAlertPolicyPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/alertPolicies/{alert_policy}' + 'folders/{folder}/alertPolicies/{alert_policy}', ), folderAlertPolicyConditionPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/alertPolicies/{alert_policy}/conditions/{condition}' + 'folders/{folder}/alertPolicies/{alert_policy}/conditions/{condition}', ), folderChannelDescriptorPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/notificationChannelDescriptors/{channel_descriptor}' + 'folders/{folder}/notificationChannelDescriptors/{channel_descriptor}', ), folderGroupPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/groups/{group}' + 'folders/{folder}/groups/{group}', ), folderNotificationChannelPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/notificationChannels/{notification_channel}' + 'folders/{folder}/notificationChannels/{notification_channel}', ), folderServicePathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/services/{service}' - ), - folderServiceServiceLevelObjectivePathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/services/{service}/serviceLevelObjectives/{service_level_objective}' + 'folders/{folder}/services/{service}', ), + folderServiceServiceLevelObjectivePathTemplate: + new this._gaxModule.PathTemplate( + 'folders/{folder}/services/{service}/serviceLevelObjectives/{service_level_objective}', + ), folderUptimeCheckConfigPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/uptimeCheckConfigs/{uptime_check_config}' + 'folders/{folder}/uptimeCheckConfigs/{uptime_check_config}', ), organizationAlertPolicyPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/alertPolicies/{alert_policy}' - ), - organizationAlertPolicyConditionPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/alertPolicies/{alert_policy}/conditions/{condition}' - ), - organizationChannelDescriptorPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/notificationChannelDescriptors/{channel_descriptor}' + 'organizations/{organization}/alertPolicies/{alert_policy}', ), + organizationAlertPolicyConditionPathTemplate: + new this._gaxModule.PathTemplate( + 'organizations/{organization}/alertPolicies/{alert_policy}/conditions/{condition}', + ), + organizationChannelDescriptorPathTemplate: + new this._gaxModule.PathTemplate( + 'organizations/{organization}/notificationChannelDescriptors/{channel_descriptor}', + ), organizationGroupPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/groups/{group}' - ), - organizationNotificationChannelPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/notificationChannels/{notification_channel}' + 'organizations/{organization}/groups/{group}', ), + organizationNotificationChannelPathTemplate: + new this._gaxModule.PathTemplate( + 'organizations/{organization}/notificationChannels/{notification_channel}', + ), organizationServicePathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/services/{service}' - ), - organizationServiceServiceLevelObjectivePathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/services/{service}/serviceLevelObjectives/{service_level_objective}' - ), - organizationUptimeCheckConfigPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/uptimeCheckConfigs/{uptime_check_config}' + 'organizations/{organization}/services/{service}', ), + organizationServiceServiceLevelObjectivePathTemplate: + new this._gaxModule.PathTemplate( + 'organizations/{organization}/services/{service}/serviceLevelObjectives/{service_level_objective}', + ), + organizationUptimeCheckConfigPathTemplate: + new this._gaxModule.PathTemplate( + 'organizations/{organization}/uptimeCheckConfigs/{uptime_check_config}', + ), projectAlertPolicyPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/alertPolicies/{alert_policy}' + 'projects/{project}/alertPolicies/{alert_policy}', ), projectAlertPolicyConditionPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/alertPolicies/{alert_policy}/conditions/{condition}' + 'projects/{project}/alertPolicies/{alert_policy}/conditions/{condition}', ), projectChannelDescriptorPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/notificationChannelDescriptors/{channel_descriptor}' + 'projects/{project}/notificationChannelDescriptors/{channel_descriptor}', ), projectGroupPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/groups/{group}' + 'projects/{project}/groups/{group}', ), projectNotificationChannelPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/notificationChannels/{notification_channel}' + 'projects/{project}/notificationChannels/{notification_channel}', ), projectServicePathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/services/{service}' - ), - projectServiceServiceLevelObjectivePathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/services/{service}/serviceLevelObjectives/{service_level_objective}' + 'projects/{project}/services/{service}', ), + projectServiceServiceLevelObjectivePathTemplate: + new this._gaxModule.PathTemplate( + 'projects/{project}/services/{service}/serviceLevelObjectives/{service_level_objective}', + ), projectUptimeCheckConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/uptimeCheckConfigs/{uptime_check_config}' + 'projects/{project}/uptimeCheckConfigs/{uptime_check_config}', ), }; @@ -272,16 +307,25 @@ export class NotificationChannelServiceClient { // (e.g. 50 results at a time, with tokens to get subsequent // pages). Denote the keys used for pagination and results. this.descriptors.page = { - listNotificationChannelDescriptors: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'channelDescriptors'), - listNotificationChannels: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'notificationChannels') + listNotificationChannelDescriptors: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'channelDescriptors', + ), + listNotificationChannels: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'notificationChannels', + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.monitoring.v3.NotificationChannelService', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.monitoring.v3.NotificationChannelService', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + { 'x-goog-api-client': clientHeader.join(' ') }, + ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -312,37 +356,51 @@ export class NotificationChannelServiceClient { // Put together the "service stub" for // google.monitoring.v3.NotificationChannelService. this.notificationChannelServiceStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.monitoring.v3.NotificationChannelService') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.monitoring.v3.NotificationChannelService', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.monitoring.v3.NotificationChannelService, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts, + this._providedCustomServicePath, + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const notificationChannelServiceStubMethods = - ['listNotificationChannelDescriptors', 'getNotificationChannelDescriptor', 'listNotificationChannels', 'getNotificationChannel', 'createNotificationChannel', 'updateNotificationChannel', 'deleteNotificationChannel', 'sendNotificationChannelVerificationCode', 'getNotificationChannelVerificationCode', 'verifyNotificationChannel']; + const notificationChannelServiceStubMethods = [ + 'listNotificationChannelDescriptors', + 'getNotificationChannelDescriptor', + 'listNotificationChannels', + 'getNotificationChannel', + 'createNotificationChannel', + 'updateNotificationChannel', + 'deleteNotificationChannel', + 'sendNotificationChannelVerificationCode', + 'getNotificationChannelVerificationCode', + 'verifyNotificationChannel', + ]; for (const methodName of notificationChannelServiceStubMethods) { const callPromise = this.notificationChannelServiceStub.then( - stub => (...args: Array<{}>) => { - if (this._terminated) { - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error|null|undefined) => () => { + (stub) => + (...args: Array<{}>) => { + if (this._terminated) { + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { throw err; - }); + }, + ); - const descriptor = - this.descriptors.page[methodName] || - undefined; + const descriptor = this.descriptors.page[methodName] || undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -357,8 +415,14 @@ export class NotificationChannelServiceClient { * @returns {string} The DNS address for this service. */ static get servicePath() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'monitoring.googleapis.com'; } @@ -370,8 +434,14 @@ export class NotificationChannelServiceClient { * @returns {string} The DNS address for this service. */ static get apiEndpoint() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'monitoring.googleapis.com'; } @@ -405,7 +475,7 @@ export class NotificationChannelServiceClient { return [ 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/monitoring', - 'https://www.googleapis.com/auth/monitoring.read' + 'https://www.googleapis.com/auth/monitoring.read', ]; } @@ -415,8 +485,9 @@ export class NotificationChannelServiceClient { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId(callback?: Callback): - Promise|void { + getProjectId( + callback?: Callback, + ): Promise | void { if (callback) { this.auth.getProjectId(callback); return; @@ -427,1155 +498,1615 @@ export class NotificationChannelServiceClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Gets a single channel descriptor. The descriptor indicates which fields - * are expected / permitted for a notification channel of the given type. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The channel type for which to execute the request. The format is - * `projects/[PROJECT_ID]/notificationChannelDescriptors/{channel_type}`. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.monitoring.v3.NotificationChannelDescriptor|NotificationChannelDescriptor}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v3/notification_channel_service.get_notification_channel_descriptor.js - * region_tag:monitoring_v3_generated_NotificationChannelService_GetNotificationChannelDescriptor_async - */ + /** + * Gets a single channel descriptor. The descriptor indicates which fields + * are expected / permitted for a notification channel of the given type. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The channel type for which to execute the request. The format is + * `projects/[PROJECT_ID]/notificationChannelDescriptors/{channel_type}`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.monitoring.v3.NotificationChannelDescriptor|NotificationChannelDescriptor}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v3/notification_channel_service.get_notification_channel_descriptor.js + * region_tag:monitoring_v3_generated_NotificationChannelService_GetNotificationChannelDescriptor_async + */ getNotificationChannelDescriptor( - request?: protos.google.monitoring.v3.IGetNotificationChannelDescriptorRequest, - options?: CallOptions): - Promise<[ - protos.google.monitoring.v3.INotificationChannelDescriptor, - protos.google.monitoring.v3.IGetNotificationChannelDescriptorRequest|undefined, {}|undefined - ]>; + request?: protos.google.monitoring.v3.IGetNotificationChannelDescriptorRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.monitoring.v3.INotificationChannelDescriptor, + ( + | protos.google.monitoring.v3.IGetNotificationChannelDescriptorRequest + | undefined + ), + {} | undefined, + ] + >; getNotificationChannelDescriptor( - request: protos.google.monitoring.v3.IGetNotificationChannelDescriptorRequest, - options: CallOptions, - callback: Callback< - protos.google.monitoring.v3.INotificationChannelDescriptor, - protos.google.monitoring.v3.IGetNotificationChannelDescriptorRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.IGetNotificationChannelDescriptorRequest, + options: CallOptions, + callback: Callback< + protos.google.monitoring.v3.INotificationChannelDescriptor, + | protos.google.monitoring.v3.IGetNotificationChannelDescriptorRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getNotificationChannelDescriptor( - request: protos.google.monitoring.v3.IGetNotificationChannelDescriptorRequest, - callback: Callback< - protos.google.monitoring.v3.INotificationChannelDescriptor, - protos.google.monitoring.v3.IGetNotificationChannelDescriptorRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.IGetNotificationChannelDescriptorRequest, + callback: Callback< + protos.google.monitoring.v3.INotificationChannelDescriptor, + | protos.google.monitoring.v3.IGetNotificationChannelDescriptorRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getNotificationChannelDescriptor( - request?: protos.google.monitoring.v3.IGetNotificationChannelDescriptorRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.monitoring.v3.IGetNotificationChannelDescriptorRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.monitoring.v3.INotificationChannelDescriptor, - protos.google.monitoring.v3.IGetNotificationChannelDescriptorRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.monitoring.v3.INotificationChannelDescriptor, - protos.google.monitoring.v3.IGetNotificationChannelDescriptorRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.monitoring.v3.INotificationChannelDescriptor, - protos.google.monitoring.v3.IGetNotificationChannelDescriptorRequest|undefined, {}|undefined - ]>|void { + | protos.google.monitoring.v3.IGetNotificationChannelDescriptorRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.monitoring.v3.INotificationChannelDescriptor, + | protos.google.monitoring.v3.IGetNotificationChannelDescriptorRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.monitoring.v3.INotificationChannelDescriptor, + ( + | protos.google.monitoring.v3.IGetNotificationChannelDescriptorRequest + | undefined + ), + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getNotificationChannelDescriptor request %j', request); - const wrappedCallback: Callback< - protos.google.monitoring.v3.INotificationChannelDescriptor, - protos.google.monitoring.v3.IGetNotificationChannelDescriptorRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.monitoring.v3.INotificationChannelDescriptor, + | protos.google.monitoring.v3.IGetNotificationChannelDescriptorRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { - this._log.info('getNotificationChannelDescriptor response %j', response); + this._log.info( + 'getNotificationChannelDescriptor response %j', + response, + ); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.getNotificationChannelDescriptor(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.monitoring.v3.INotificationChannelDescriptor, - protos.google.monitoring.v3.IGetNotificationChannelDescriptorRequest|undefined, {}|undefined - ]) => { - this._log.info('getNotificationChannelDescriptor response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getNotificationChannelDescriptor(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.monitoring.v3.INotificationChannelDescriptor, + ( + | protos.google.monitoring.v3.IGetNotificationChannelDescriptorRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info( + 'getNotificationChannelDescriptor response %j', + response, + ); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Gets a single notification channel. The channel includes the relevant - * configuration details with which the channel was created. However, the - * response may truncate or omit passwords, API keys, or other private key - * matter and thus the response may not be 100% identical to the information - * that was supplied in the call to the create method. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The channel for which to execute the request. The format is - * `projects/[PROJECT_ID]/notificationChannels/[CHANNEL_ID]`. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.monitoring.v3.NotificationChannel|NotificationChannel}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v3/notification_channel_service.get_notification_channel.js - * region_tag:monitoring_v3_generated_NotificationChannelService_GetNotificationChannel_async - */ + /** + * Gets a single notification channel. The channel includes the relevant + * configuration details with which the channel was created. However, the + * response may truncate or omit passwords, API keys, or other private key + * matter and thus the response may not be 100% identical to the information + * that was supplied in the call to the create method. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The channel for which to execute the request. The format is + * `projects/[PROJECT_ID]/notificationChannels/[CHANNEL_ID]`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.monitoring.v3.NotificationChannel|NotificationChannel}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v3/notification_channel_service.get_notification_channel.js + * region_tag:monitoring_v3_generated_NotificationChannelService_GetNotificationChannel_async + */ getNotificationChannel( - request?: protos.google.monitoring.v3.IGetNotificationChannelRequest, - options?: CallOptions): - Promise<[ - protos.google.monitoring.v3.INotificationChannel, - protos.google.monitoring.v3.IGetNotificationChannelRequest|undefined, {}|undefined - ]>; + request?: protos.google.monitoring.v3.IGetNotificationChannelRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.monitoring.v3.INotificationChannel, + protos.google.monitoring.v3.IGetNotificationChannelRequest | undefined, + {} | undefined, + ] + >; getNotificationChannel( - request: protos.google.monitoring.v3.IGetNotificationChannelRequest, - options: CallOptions, - callback: Callback< - protos.google.monitoring.v3.INotificationChannel, - protos.google.monitoring.v3.IGetNotificationChannelRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.IGetNotificationChannelRequest, + options: CallOptions, + callback: Callback< + protos.google.monitoring.v3.INotificationChannel, + | protos.google.monitoring.v3.IGetNotificationChannelRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getNotificationChannel( - request: protos.google.monitoring.v3.IGetNotificationChannelRequest, - callback: Callback< - protos.google.monitoring.v3.INotificationChannel, - protos.google.monitoring.v3.IGetNotificationChannelRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.IGetNotificationChannelRequest, + callback: Callback< + protos.google.monitoring.v3.INotificationChannel, + | protos.google.monitoring.v3.IGetNotificationChannelRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getNotificationChannel( - request?: protos.google.monitoring.v3.IGetNotificationChannelRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.monitoring.v3.IGetNotificationChannelRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.monitoring.v3.INotificationChannel, - protos.google.monitoring.v3.IGetNotificationChannelRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.monitoring.v3.INotificationChannel, - protos.google.monitoring.v3.IGetNotificationChannelRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.monitoring.v3.INotificationChannel, - protos.google.monitoring.v3.IGetNotificationChannelRequest|undefined, {}|undefined - ]>|void { + | protos.google.monitoring.v3.IGetNotificationChannelRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.monitoring.v3.INotificationChannel, + | protos.google.monitoring.v3.IGetNotificationChannelRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.monitoring.v3.INotificationChannel, + protos.google.monitoring.v3.IGetNotificationChannelRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getNotificationChannel request %j', request); - const wrappedCallback: Callback< - protos.google.monitoring.v3.INotificationChannel, - protos.google.monitoring.v3.IGetNotificationChannelRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.monitoring.v3.INotificationChannel, + | protos.google.monitoring.v3.IGetNotificationChannelRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getNotificationChannel response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.getNotificationChannel(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.monitoring.v3.INotificationChannel, - protos.google.monitoring.v3.IGetNotificationChannelRequest|undefined, {}|undefined - ]) => { - this._log.info('getNotificationChannel response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getNotificationChannel(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.monitoring.v3.INotificationChannel, + ( + | protos.google.monitoring.v3.IGetNotificationChannelRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('getNotificationChannel response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Creates a new notification channel, representing a single notification - * endpoint such as an email address, SMS number, or PagerDuty service. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The project on which to execute the request. The format is: - * - * projects/[PROJECT_ID] - * - * Note that this names the container into which the channel will be - * written. This does not name the newly created channel. The resulting - * channel's name will have a normalized version of this field as a prefix, - * but will add `/notificationChannels/[CHANNEL_ID]` to identify the channel. - * @param {google.monitoring.v3.NotificationChannel} request.notificationChannel - * Required. The definition of the `NotificationChannel` to create. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.monitoring.v3.NotificationChannel|NotificationChannel}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v3/notification_channel_service.create_notification_channel.js - * region_tag:monitoring_v3_generated_NotificationChannelService_CreateNotificationChannel_async - */ + /** + * Creates a new notification channel, representing a single notification + * endpoint such as an email address, SMS number, or PagerDuty service. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The project on which to execute the request. The format is: + * + * projects/[PROJECT_ID] + * + * Note that this names the container into which the channel will be + * written. This does not name the newly created channel. The resulting + * channel's name will have a normalized version of this field as a prefix, + * but will add `/notificationChannels/[CHANNEL_ID]` to identify the channel. + * @param {google.monitoring.v3.NotificationChannel} request.notificationChannel + * Required. The definition of the `NotificationChannel` to create. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.monitoring.v3.NotificationChannel|NotificationChannel}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v3/notification_channel_service.create_notification_channel.js + * region_tag:monitoring_v3_generated_NotificationChannelService_CreateNotificationChannel_async + */ createNotificationChannel( - request?: protos.google.monitoring.v3.ICreateNotificationChannelRequest, - options?: CallOptions): - Promise<[ - protos.google.monitoring.v3.INotificationChannel, - protos.google.monitoring.v3.ICreateNotificationChannelRequest|undefined, {}|undefined - ]>; + request?: protos.google.monitoring.v3.ICreateNotificationChannelRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.monitoring.v3.INotificationChannel, + protos.google.monitoring.v3.ICreateNotificationChannelRequest | undefined, + {} | undefined, + ] + >; createNotificationChannel( - request: protos.google.monitoring.v3.ICreateNotificationChannelRequest, - options: CallOptions, - callback: Callback< - protos.google.monitoring.v3.INotificationChannel, - protos.google.monitoring.v3.ICreateNotificationChannelRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.ICreateNotificationChannelRequest, + options: CallOptions, + callback: Callback< + protos.google.monitoring.v3.INotificationChannel, + | protos.google.monitoring.v3.ICreateNotificationChannelRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createNotificationChannel( - request: protos.google.monitoring.v3.ICreateNotificationChannelRequest, - callback: Callback< - protos.google.monitoring.v3.INotificationChannel, - protos.google.monitoring.v3.ICreateNotificationChannelRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.ICreateNotificationChannelRequest, + callback: Callback< + protos.google.monitoring.v3.INotificationChannel, + | protos.google.monitoring.v3.ICreateNotificationChannelRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createNotificationChannel( - request?: protos.google.monitoring.v3.ICreateNotificationChannelRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.monitoring.v3.INotificationChannel, - protos.google.monitoring.v3.ICreateNotificationChannelRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.monitoring.v3.ICreateNotificationChannelRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.monitoring.v3.INotificationChannel, - protos.google.monitoring.v3.ICreateNotificationChannelRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.monitoring.v3.INotificationChannel, - protos.google.monitoring.v3.ICreateNotificationChannelRequest|undefined, {}|undefined - ]>|void { + | protos.google.monitoring.v3.ICreateNotificationChannelRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.monitoring.v3.INotificationChannel, + | protos.google.monitoring.v3.ICreateNotificationChannelRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.monitoring.v3.INotificationChannel, + protos.google.monitoring.v3.ICreateNotificationChannelRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('createNotificationChannel request %j', request); - const wrappedCallback: Callback< - protos.google.monitoring.v3.INotificationChannel, - protos.google.monitoring.v3.ICreateNotificationChannelRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.monitoring.v3.INotificationChannel, + | protos.google.monitoring.v3.ICreateNotificationChannelRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createNotificationChannel response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.createNotificationChannel(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.monitoring.v3.INotificationChannel, - protos.google.monitoring.v3.ICreateNotificationChannelRequest|undefined, {}|undefined - ]) => { - this._log.info('createNotificationChannel response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createNotificationChannel(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.monitoring.v3.INotificationChannel, + ( + | protos.google.monitoring.v3.ICreateNotificationChannelRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('createNotificationChannel response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Updates a notification channel. Fields not specified in the field mask - * remain unchanged. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.protobuf.FieldMask} request.updateMask - * The fields to update. - * @param {google.monitoring.v3.NotificationChannel} request.notificationChannel - * Required. A description of the changes to be applied to the specified - * notification channel. The description must provide a definition for - * fields to be updated; the names of these fields should also be - * included in the `update_mask`. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.monitoring.v3.NotificationChannel|NotificationChannel}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v3/notification_channel_service.update_notification_channel.js - * region_tag:monitoring_v3_generated_NotificationChannelService_UpdateNotificationChannel_async - */ + /** + * Updates a notification channel. Fields not specified in the field mask + * remain unchanged. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.protobuf.FieldMask} request.updateMask + * The fields to update. + * @param {google.monitoring.v3.NotificationChannel} request.notificationChannel + * Required. A description of the changes to be applied to the specified + * notification channel. The description must provide a definition for + * fields to be updated; the names of these fields should also be + * included in the `update_mask`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.monitoring.v3.NotificationChannel|NotificationChannel}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v3/notification_channel_service.update_notification_channel.js + * region_tag:monitoring_v3_generated_NotificationChannelService_UpdateNotificationChannel_async + */ updateNotificationChannel( - request?: protos.google.monitoring.v3.IUpdateNotificationChannelRequest, - options?: CallOptions): - Promise<[ - protos.google.monitoring.v3.INotificationChannel, - protos.google.monitoring.v3.IUpdateNotificationChannelRequest|undefined, {}|undefined - ]>; + request?: protos.google.monitoring.v3.IUpdateNotificationChannelRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.monitoring.v3.INotificationChannel, + protos.google.monitoring.v3.IUpdateNotificationChannelRequest | undefined, + {} | undefined, + ] + >; updateNotificationChannel( - request: protos.google.monitoring.v3.IUpdateNotificationChannelRequest, - options: CallOptions, - callback: Callback< - protos.google.monitoring.v3.INotificationChannel, - protos.google.monitoring.v3.IUpdateNotificationChannelRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.IUpdateNotificationChannelRequest, + options: CallOptions, + callback: Callback< + protos.google.monitoring.v3.INotificationChannel, + | protos.google.monitoring.v3.IUpdateNotificationChannelRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateNotificationChannel( - request: protos.google.monitoring.v3.IUpdateNotificationChannelRequest, - callback: Callback< - protos.google.monitoring.v3.INotificationChannel, - protos.google.monitoring.v3.IUpdateNotificationChannelRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.IUpdateNotificationChannelRequest, + callback: Callback< + protos.google.monitoring.v3.INotificationChannel, + | protos.google.monitoring.v3.IUpdateNotificationChannelRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateNotificationChannel( - request?: protos.google.monitoring.v3.IUpdateNotificationChannelRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.monitoring.v3.INotificationChannel, - protos.google.monitoring.v3.IUpdateNotificationChannelRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.monitoring.v3.IUpdateNotificationChannelRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.monitoring.v3.INotificationChannel, - protos.google.monitoring.v3.IUpdateNotificationChannelRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.monitoring.v3.INotificationChannel, - protos.google.monitoring.v3.IUpdateNotificationChannelRequest|undefined, {}|undefined - ]>|void { + | protos.google.monitoring.v3.IUpdateNotificationChannelRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.monitoring.v3.INotificationChannel, + | protos.google.monitoring.v3.IUpdateNotificationChannelRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.monitoring.v3.INotificationChannel, + protos.google.monitoring.v3.IUpdateNotificationChannelRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'notification_channel.name': request.notificationChannel!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'notification_channel.name': request.notificationChannel!.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateNotificationChannel request %j', request); - const wrappedCallback: Callback< - protos.google.monitoring.v3.INotificationChannel, - protos.google.monitoring.v3.IUpdateNotificationChannelRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.monitoring.v3.INotificationChannel, + | protos.google.monitoring.v3.IUpdateNotificationChannelRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateNotificationChannel response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.updateNotificationChannel(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.monitoring.v3.INotificationChannel, - protos.google.monitoring.v3.IUpdateNotificationChannelRequest|undefined, {}|undefined - ]) => { - this._log.info('updateNotificationChannel response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateNotificationChannel(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.monitoring.v3.INotificationChannel, + ( + | protos.google.monitoring.v3.IUpdateNotificationChannelRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('updateNotificationChannel response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Deletes a notification channel. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The channel for which to execute the request. The format is - * `projects/[PROJECT_ID]/notificationChannels/[CHANNEL_ID]`. - * @param {boolean} request.force - * If true, the notification channel will be deleted regardless of its - * use in alert policies (the policies will be updated to remove the - * channel). If false, channels that are still referenced by an existing - * alerting policy will fail to be deleted in a delete operation. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v3/notification_channel_service.delete_notification_channel.js - * region_tag:monitoring_v3_generated_NotificationChannelService_DeleteNotificationChannel_async - */ + /** + * Deletes a notification channel. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The channel for which to execute the request. The format is + * `projects/[PROJECT_ID]/notificationChannels/[CHANNEL_ID]`. + * @param {boolean} request.force + * If true, the notification channel will be deleted regardless of its + * use in alert policies (the policies will be updated to remove the + * channel). If false, channels that are still referenced by an existing + * alerting policy will fail to be deleted in a delete operation. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v3/notification_channel_service.delete_notification_channel.js + * region_tag:monitoring_v3_generated_NotificationChannelService_DeleteNotificationChannel_async + */ deleteNotificationChannel( - request?: protos.google.monitoring.v3.IDeleteNotificationChannelRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.IDeleteNotificationChannelRequest|undefined, {}|undefined - ]>; + request?: protos.google.monitoring.v3.IDeleteNotificationChannelRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.monitoring.v3.IDeleteNotificationChannelRequest | undefined, + {} | undefined, + ] + >; deleteNotificationChannel( - request: protos.google.monitoring.v3.IDeleteNotificationChannelRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.IDeleteNotificationChannelRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.IDeleteNotificationChannelRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.monitoring.v3.IDeleteNotificationChannelRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteNotificationChannel( - request: protos.google.monitoring.v3.IDeleteNotificationChannelRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.IDeleteNotificationChannelRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.IDeleteNotificationChannelRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.monitoring.v3.IDeleteNotificationChannelRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteNotificationChannel( - request?: protos.google.monitoring.v3.IDeleteNotificationChannelRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.monitoring.v3.IDeleteNotificationChannelRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.IDeleteNotificationChannelRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.IDeleteNotificationChannelRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.IDeleteNotificationChannelRequest|undefined, {}|undefined - ]>|void { + | protos.google.monitoring.v3.IDeleteNotificationChannelRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + | protos.google.monitoring.v3.IDeleteNotificationChannelRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.monitoring.v3.IDeleteNotificationChannelRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('deleteNotificationChannel request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.IDeleteNotificationChannelRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.monitoring.v3.IDeleteNotificationChannelRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteNotificationChannel response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.deleteNotificationChannel(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.IDeleteNotificationChannelRequest|undefined, {}|undefined - ]) => { - this._log.info('deleteNotificationChannel response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteNotificationChannel(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + ( + | protos.google.monitoring.v3.IDeleteNotificationChannelRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('deleteNotificationChannel response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Causes a verification code to be delivered to the channel. The code - * can then be supplied in `VerifyNotificationChannel` to verify the channel. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The notification channel to which to send a verification code. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v3/notification_channel_service.send_notification_channel_verification_code.js - * region_tag:monitoring_v3_generated_NotificationChannelService_SendNotificationChannelVerificationCode_async - */ + /** + * Causes a verification code to be delivered to the channel. The code + * can then be supplied in `VerifyNotificationChannel` to verify the channel. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The notification channel to which to send a verification code. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v3/notification_channel_service.send_notification_channel_verification_code.js + * region_tag:monitoring_v3_generated_NotificationChannelService_SendNotificationChannelVerificationCode_async + */ sendNotificationChannelVerificationCode( - request?: protos.google.monitoring.v3.ISendNotificationChannelVerificationCodeRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.ISendNotificationChannelVerificationCodeRequest|undefined, {}|undefined - ]>; + request?: protos.google.monitoring.v3.ISendNotificationChannelVerificationCodeRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.monitoring.v3.ISendNotificationChannelVerificationCodeRequest + | undefined + ), + {} | undefined, + ] + >; sendNotificationChannelVerificationCode( - request: protos.google.monitoring.v3.ISendNotificationChannelVerificationCodeRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.ISendNotificationChannelVerificationCodeRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.ISendNotificationChannelVerificationCodeRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.monitoring.v3.ISendNotificationChannelVerificationCodeRequest + | null + | undefined, + {} | null | undefined + >, + ): void; sendNotificationChannelVerificationCode( - request: protos.google.monitoring.v3.ISendNotificationChannelVerificationCodeRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.ISendNotificationChannelVerificationCodeRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.ISendNotificationChannelVerificationCodeRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.monitoring.v3.ISendNotificationChannelVerificationCodeRequest + | null + | undefined, + {} | null | undefined + >, + ): void; sendNotificationChannelVerificationCode( - request?: protos.google.monitoring.v3.ISendNotificationChannelVerificationCodeRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.monitoring.v3.ISendNotificationChannelVerificationCodeRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.ISendNotificationChannelVerificationCodeRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.ISendNotificationChannelVerificationCodeRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.ISendNotificationChannelVerificationCodeRequest|undefined, {}|undefined - ]>|void { + | protos.google.monitoring.v3.ISendNotificationChannelVerificationCodeRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + | protos.google.monitoring.v3.ISendNotificationChannelVerificationCodeRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.monitoring.v3.ISendNotificationChannelVerificationCodeRequest + | undefined + ), + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - this._log.info('sendNotificationChannelVerificationCode request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.ISendNotificationChannelVerificationCodeRequest|null|undefined, - {}|null|undefined>|undefined = callback + this._log.info( + 'sendNotificationChannelVerificationCode request %j', + request, + ); + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.monitoring.v3.ISendNotificationChannelVerificationCodeRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { - this._log.info('sendNotificationChannelVerificationCode response %j', response); + this._log.info( + 'sendNotificationChannelVerificationCode response %j', + response, + ); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.sendNotificationChannelVerificationCode(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.ISendNotificationChannelVerificationCodeRequest|undefined, {}|undefined - ]) => { - this._log.info('sendNotificationChannelVerificationCode response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .sendNotificationChannelVerificationCode( + request, + options, + wrappedCallback, + ) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + ( + | protos.google.monitoring.v3.ISendNotificationChannelVerificationCodeRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info( + 'sendNotificationChannelVerificationCode response %j', + response, + ); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Requests a verification code for an already verified channel that can then - * be used in a call to VerifyNotificationChannel() on a different channel - * with an equivalent identity in the same or in a different project. This - * makes it possible to copy a channel between projects without requiring - * manual reverification of the channel. If the channel is not in the - * verified state, this method will fail (in other words, this may only be - * used if the SendNotificationChannelVerificationCode and - * VerifyNotificationChannel paths have already been used to put the given - * channel into the verified state). - * - * There is no guarantee that the verification codes returned by this method - * will be of a similar structure or form as the ones that are delivered - * to the channel via SendNotificationChannelVerificationCode; while - * VerifyNotificationChannel() will recognize both the codes delivered via - * SendNotificationChannelVerificationCode() and returned from - * GetNotificationChannelVerificationCode(), it is typically the case that - * the verification codes delivered via - * SendNotificationChannelVerificationCode() will be shorter and also - * have a shorter expiration (e.g. codes such as "G-123456") whereas - * GetVerificationCode() will typically return a much longer, websafe base - * 64 encoded string that has a longer expiration time. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The notification channel for which a verification code is to be generated - * and retrieved. This must name a channel that is already verified; if - * the specified channel is not verified, the request will fail. - * @param {google.protobuf.Timestamp} request.expireTime - * The desired expiration time. If specified, the API will guarantee that - * the returned code will not be valid after the specified timestamp; - * however, the API cannot guarantee that the returned code will be - * valid for at least as long as the requested time (the API puts an upper - * bound on the amount of time for which a code may be valid). If omitted, - * a default expiration will be used, which may be less than the max - * permissible expiration (so specifying an expiration may extend the - * code's lifetime over omitting an expiration, even though the API does - * impose an upper limit on the maximum expiration that is permitted). - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.monitoring.v3.GetNotificationChannelVerificationCodeResponse|GetNotificationChannelVerificationCodeResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v3/notification_channel_service.get_notification_channel_verification_code.js - * region_tag:monitoring_v3_generated_NotificationChannelService_GetNotificationChannelVerificationCode_async - */ + /** + * Requests a verification code for an already verified channel that can then + * be used in a call to VerifyNotificationChannel() on a different channel + * with an equivalent identity in the same or in a different project. This + * makes it possible to copy a channel between projects without requiring + * manual reverification of the channel. If the channel is not in the + * verified state, this method will fail (in other words, this may only be + * used if the SendNotificationChannelVerificationCode and + * VerifyNotificationChannel paths have already been used to put the given + * channel into the verified state). + * + * There is no guarantee that the verification codes returned by this method + * will be of a similar structure or form as the ones that are delivered + * to the channel via SendNotificationChannelVerificationCode; while + * VerifyNotificationChannel() will recognize both the codes delivered via + * SendNotificationChannelVerificationCode() and returned from + * GetNotificationChannelVerificationCode(), it is typically the case that + * the verification codes delivered via + * SendNotificationChannelVerificationCode() will be shorter and also + * have a shorter expiration (e.g. codes such as "G-123456") whereas + * GetVerificationCode() will typically return a much longer, websafe base + * 64 encoded string that has a longer expiration time. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The notification channel for which a verification code is to be generated + * and retrieved. This must name a channel that is already verified; if + * the specified channel is not verified, the request will fail. + * @param {google.protobuf.Timestamp} request.expireTime + * The desired expiration time. If specified, the API will guarantee that + * the returned code will not be valid after the specified timestamp; + * however, the API cannot guarantee that the returned code will be + * valid for at least as long as the requested time (the API puts an upper + * bound on the amount of time for which a code may be valid). If omitted, + * a default expiration will be used, which may be less than the max + * permissible expiration (so specifying an expiration may extend the + * code's lifetime over omitting an expiration, even though the API does + * impose an upper limit on the maximum expiration that is permitted). + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.monitoring.v3.GetNotificationChannelVerificationCodeResponse|GetNotificationChannelVerificationCodeResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v3/notification_channel_service.get_notification_channel_verification_code.js + * region_tag:monitoring_v3_generated_NotificationChannelService_GetNotificationChannelVerificationCode_async + */ getNotificationChannelVerificationCode( - request?: protos.google.monitoring.v3.IGetNotificationChannelVerificationCodeRequest, - options?: CallOptions): - Promise<[ - protos.google.monitoring.v3.IGetNotificationChannelVerificationCodeResponse, - protos.google.monitoring.v3.IGetNotificationChannelVerificationCodeRequest|undefined, {}|undefined - ]>; + request?: protos.google.monitoring.v3.IGetNotificationChannelVerificationCodeRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.monitoring.v3.IGetNotificationChannelVerificationCodeResponse, + ( + | protos.google.monitoring.v3.IGetNotificationChannelVerificationCodeRequest + | undefined + ), + {} | undefined, + ] + >; getNotificationChannelVerificationCode( - request: protos.google.monitoring.v3.IGetNotificationChannelVerificationCodeRequest, - options: CallOptions, - callback: Callback< - protos.google.monitoring.v3.IGetNotificationChannelVerificationCodeResponse, - protos.google.monitoring.v3.IGetNotificationChannelVerificationCodeRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.IGetNotificationChannelVerificationCodeRequest, + options: CallOptions, + callback: Callback< + protos.google.monitoring.v3.IGetNotificationChannelVerificationCodeResponse, + | protos.google.monitoring.v3.IGetNotificationChannelVerificationCodeRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getNotificationChannelVerificationCode( - request: protos.google.monitoring.v3.IGetNotificationChannelVerificationCodeRequest, - callback: Callback< - protos.google.monitoring.v3.IGetNotificationChannelVerificationCodeResponse, - protos.google.monitoring.v3.IGetNotificationChannelVerificationCodeRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.IGetNotificationChannelVerificationCodeRequest, + callback: Callback< + protos.google.monitoring.v3.IGetNotificationChannelVerificationCodeResponse, + | protos.google.monitoring.v3.IGetNotificationChannelVerificationCodeRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getNotificationChannelVerificationCode( - request?: protos.google.monitoring.v3.IGetNotificationChannelVerificationCodeRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.monitoring.v3.IGetNotificationChannelVerificationCodeRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.monitoring.v3.IGetNotificationChannelVerificationCodeResponse, - protos.google.monitoring.v3.IGetNotificationChannelVerificationCodeRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.monitoring.v3.IGetNotificationChannelVerificationCodeResponse, - protos.google.monitoring.v3.IGetNotificationChannelVerificationCodeRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.monitoring.v3.IGetNotificationChannelVerificationCodeResponse, - protos.google.monitoring.v3.IGetNotificationChannelVerificationCodeRequest|undefined, {}|undefined - ]>|void { + | protos.google.monitoring.v3.IGetNotificationChannelVerificationCodeRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.monitoring.v3.IGetNotificationChannelVerificationCodeResponse, + | protos.google.monitoring.v3.IGetNotificationChannelVerificationCodeRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.monitoring.v3.IGetNotificationChannelVerificationCodeResponse, + ( + | protos.google.monitoring.v3.IGetNotificationChannelVerificationCodeRequest + | undefined + ), + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - this._log.info('getNotificationChannelVerificationCode request %j', request); - const wrappedCallback: Callback< - protos.google.monitoring.v3.IGetNotificationChannelVerificationCodeResponse, - protos.google.monitoring.v3.IGetNotificationChannelVerificationCodeRequest|null|undefined, - {}|null|undefined>|undefined = callback + this._log.info( + 'getNotificationChannelVerificationCode request %j', + request, + ); + const wrappedCallback: + | Callback< + protos.google.monitoring.v3.IGetNotificationChannelVerificationCodeResponse, + | protos.google.monitoring.v3.IGetNotificationChannelVerificationCodeRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { - this._log.info('getNotificationChannelVerificationCode response %j', response); + this._log.info( + 'getNotificationChannelVerificationCode response %j', + response, + ); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.getNotificationChannelVerificationCode(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.monitoring.v3.IGetNotificationChannelVerificationCodeResponse, - protos.google.monitoring.v3.IGetNotificationChannelVerificationCodeRequest|undefined, {}|undefined - ]) => { - this._log.info('getNotificationChannelVerificationCode response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getNotificationChannelVerificationCode(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.monitoring.v3.IGetNotificationChannelVerificationCodeResponse, + ( + | protos.google.monitoring.v3.IGetNotificationChannelVerificationCodeRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info( + 'getNotificationChannelVerificationCode response %j', + response, + ); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Verifies a `NotificationChannel` by proving receipt of the code - * delivered to the channel as a result of calling - * `SendNotificationChannelVerificationCode`. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The notification channel to verify. - * @param {string} request.code - * Required. The verification code that was delivered to the channel as - * a result of invoking the `SendNotificationChannelVerificationCode` API - * method or that was retrieved from a verified channel via - * `GetNotificationChannelVerificationCode`. For example, one might have - * "G-123456" or "TKNZGhhd2EyN3I1MnRnMjRv" (in general, one is only - * guaranteed that the code is valid UTF-8; one should not - * make any assumptions regarding the structure or format of the code). - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.monitoring.v3.NotificationChannel|NotificationChannel}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v3/notification_channel_service.verify_notification_channel.js - * region_tag:monitoring_v3_generated_NotificationChannelService_VerifyNotificationChannel_async - */ + /** + * Verifies a `NotificationChannel` by proving receipt of the code + * delivered to the channel as a result of calling + * `SendNotificationChannelVerificationCode`. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The notification channel to verify. + * @param {string} request.code + * Required. The verification code that was delivered to the channel as + * a result of invoking the `SendNotificationChannelVerificationCode` API + * method or that was retrieved from a verified channel via + * `GetNotificationChannelVerificationCode`. For example, one might have + * "G-123456" or "TKNZGhhd2EyN3I1MnRnMjRv" (in general, one is only + * guaranteed that the code is valid UTF-8; one should not + * make any assumptions regarding the structure or format of the code). + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.monitoring.v3.NotificationChannel|NotificationChannel}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v3/notification_channel_service.verify_notification_channel.js + * region_tag:monitoring_v3_generated_NotificationChannelService_VerifyNotificationChannel_async + */ verifyNotificationChannel( - request?: protos.google.monitoring.v3.IVerifyNotificationChannelRequest, - options?: CallOptions): - Promise<[ - protos.google.monitoring.v3.INotificationChannel, - protos.google.monitoring.v3.IVerifyNotificationChannelRequest|undefined, {}|undefined - ]>; + request?: protos.google.monitoring.v3.IVerifyNotificationChannelRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.monitoring.v3.INotificationChannel, + protos.google.monitoring.v3.IVerifyNotificationChannelRequest | undefined, + {} | undefined, + ] + >; verifyNotificationChannel( - request: protos.google.monitoring.v3.IVerifyNotificationChannelRequest, - options: CallOptions, - callback: Callback< - protos.google.monitoring.v3.INotificationChannel, - protos.google.monitoring.v3.IVerifyNotificationChannelRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.IVerifyNotificationChannelRequest, + options: CallOptions, + callback: Callback< + protos.google.monitoring.v3.INotificationChannel, + | protos.google.monitoring.v3.IVerifyNotificationChannelRequest + | null + | undefined, + {} | null | undefined + >, + ): void; verifyNotificationChannel( - request: protos.google.monitoring.v3.IVerifyNotificationChannelRequest, - callback: Callback< - protos.google.monitoring.v3.INotificationChannel, - protos.google.monitoring.v3.IVerifyNotificationChannelRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.IVerifyNotificationChannelRequest, + callback: Callback< + protos.google.monitoring.v3.INotificationChannel, + | protos.google.monitoring.v3.IVerifyNotificationChannelRequest + | null + | undefined, + {} | null | undefined + >, + ): void; verifyNotificationChannel( - request?: protos.google.monitoring.v3.IVerifyNotificationChannelRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.monitoring.v3.IVerifyNotificationChannelRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.monitoring.v3.INotificationChannel, - protos.google.monitoring.v3.IVerifyNotificationChannelRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.monitoring.v3.INotificationChannel, - protos.google.monitoring.v3.IVerifyNotificationChannelRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.monitoring.v3.INotificationChannel, - protos.google.monitoring.v3.IVerifyNotificationChannelRequest|undefined, {}|undefined - ]>|void { + | protos.google.monitoring.v3.IVerifyNotificationChannelRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.monitoring.v3.INotificationChannel, + | protos.google.monitoring.v3.IVerifyNotificationChannelRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.monitoring.v3.INotificationChannel, + protos.google.monitoring.v3.IVerifyNotificationChannelRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('verifyNotificationChannel request %j', request); - const wrappedCallback: Callback< - protos.google.monitoring.v3.INotificationChannel, - protos.google.monitoring.v3.IVerifyNotificationChannelRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.monitoring.v3.INotificationChannel, + | protos.google.monitoring.v3.IVerifyNotificationChannelRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('verifyNotificationChannel response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.verifyNotificationChannel(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.monitoring.v3.INotificationChannel, - protos.google.monitoring.v3.IVerifyNotificationChannelRequest|undefined, {}|undefined - ]) => { - this._log.info('verifyNotificationChannel response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .verifyNotificationChannel(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.monitoring.v3.INotificationChannel, + ( + | protos.google.monitoring.v3.IVerifyNotificationChannelRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('verifyNotificationChannel response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } - /** - * Lists the descriptors for supported channel types. The use of descriptors - * makes it possible for new channel types to be dynamically added. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The REST resource name of the parent from which to retrieve - * the notification channel descriptors. The expected syntax is: - * - * projects/[PROJECT_ID] - * - * Note that this names the parent container in which to look for the - * descriptors; to retrieve a single descriptor by name, use the - * {@link protos.google.monitoring.v3.NotificationChannelService.GetNotificationChannelDescriptor|GetNotificationChannelDescriptor} - * operation, instead. - * @param {number} request.pageSize - * The maximum number of results to return in a single response. If - * not set to a positive number, a reasonable value will be chosen by the - * service. - * @param {string} request.pageToken - * If non-empty, `page_token` must contain a value returned as the - * `next_page_token` in a previous response to request the next set - * of results. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.monitoring.v3.NotificationChannelDescriptor|NotificationChannelDescriptor}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `listNotificationChannelDescriptorsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Lists the descriptors for supported channel types. The use of descriptors + * makes it possible for new channel types to be dynamically added. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The REST resource name of the parent from which to retrieve + * the notification channel descriptors. The expected syntax is: + * + * projects/[PROJECT_ID] + * + * Note that this names the parent container in which to look for the + * descriptors; to retrieve a single descriptor by name, use the + * {@link protos.google.monitoring.v3.NotificationChannelService.GetNotificationChannelDescriptor|GetNotificationChannelDescriptor} + * operation, instead. + * @param {number} request.pageSize + * The maximum number of results to return in a single response. If + * not set to a positive number, a reasonable value will be chosen by the + * service. + * @param {string} request.pageToken + * If non-empty, `page_token` must contain a value returned as the + * `next_page_token` in a previous response to request the next set + * of results. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.monitoring.v3.NotificationChannelDescriptor|NotificationChannelDescriptor}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listNotificationChannelDescriptorsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listNotificationChannelDescriptors( - request?: protos.google.monitoring.v3.IListNotificationChannelDescriptorsRequest, - options?: CallOptions): - Promise<[ - protos.google.monitoring.v3.INotificationChannelDescriptor[], - protos.google.monitoring.v3.IListNotificationChannelDescriptorsRequest|null, - protos.google.monitoring.v3.IListNotificationChannelDescriptorsResponse - ]>; + request?: protos.google.monitoring.v3.IListNotificationChannelDescriptorsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.monitoring.v3.INotificationChannelDescriptor[], + protos.google.monitoring.v3.IListNotificationChannelDescriptorsRequest | null, + protos.google.monitoring.v3.IListNotificationChannelDescriptorsResponse, + ] + >; listNotificationChannelDescriptors( - request: protos.google.monitoring.v3.IListNotificationChannelDescriptorsRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.monitoring.v3.IListNotificationChannelDescriptorsRequest, - protos.google.monitoring.v3.IListNotificationChannelDescriptorsResponse|null|undefined, - protos.google.monitoring.v3.INotificationChannelDescriptor>): void; + request: protos.google.monitoring.v3.IListNotificationChannelDescriptorsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.monitoring.v3.IListNotificationChannelDescriptorsRequest, + | protos.google.monitoring.v3.IListNotificationChannelDescriptorsResponse + | null + | undefined, + protos.google.monitoring.v3.INotificationChannelDescriptor + >, + ): void; listNotificationChannelDescriptors( - request: protos.google.monitoring.v3.IListNotificationChannelDescriptorsRequest, - callback: PaginationCallback< - protos.google.monitoring.v3.IListNotificationChannelDescriptorsRequest, - protos.google.monitoring.v3.IListNotificationChannelDescriptorsResponse|null|undefined, - protos.google.monitoring.v3.INotificationChannelDescriptor>): void; + request: protos.google.monitoring.v3.IListNotificationChannelDescriptorsRequest, + callback: PaginationCallback< + protos.google.monitoring.v3.IListNotificationChannelDescriptorsRequest, + | protos.google.monitoring.v3.IListNotificationChannelDescriptorsResponse + | null + | undefined, + protos.google.monitoring.v3.INotificationChannelDescriptor + >, + ): void; listNotificationChannelDescriptors( - request?: protos.google.monitoring.v3.IListNotificationChannelDescriptorsRequest, - optionsOrCallback?: CallOptions|PaginationCallback< - protos.google.monitoring.v3.IListNotificationChannelDescriptorsRequest, - protos.google.monitoring.v3.IListNotificationChannelDescriptorsResponse|null|undefined, - protos.google.monitoring.v3.INotificationChannelDescriptor>, - callback?: PaginationCallback< + request?: protos.google.monitoring.v3.IListNotificationChannelDescriptorsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.monitoring.v3.IListNotificationChannelDescriptorsRequest, - protos.google.monitoring.v3.IListNotificationChannelDescriptorsResponse|null|undefined, - protos.google.monitoring.v3.INotificationChannelDescriptor>): - Promise<[ - protos.google.monitoring.v3.INotificationChannelDescriptor[], - protos.google.monitoring.v3.IListNotificationChannelDescriptorsRequest|null, - protos.google.monitoring.v3.IListNotificationChannelDescriptorsResponse - ]>|void { + | protos.google.monitoring.v3.IListNotificationChannelDescriptorsResponse + | null + | undefined, + protos.google.monitoring.v3.INotificationChannelDescriptor + >, + callback?: PaginationCallback< + protos.google.monitoring.v3.IListNotificationChannelDescriptorsRequest, + | protos.google.monitoring.v3.IListNotificationChannelDescriptorsResponse + | null + | undefined, + protos.google.monitoring.v3.INotificationChannelDescriptor + >, + ): Promise< + [ + protos.google.monitoring.v3.INotificationChannelDescriptor[], + protos.google.monitoring.v3.IListNotificationChannelDescriptorsRequest | null, + protos.google.monitoring.v3.IListNotificationChannelDescriptorsResponse, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.monitoring.v3.IListNotificationChannelDescriptorsRequest, - protos.google.monitoring.v3.IListNotificationChannelDescriptorsResponse|null|undefined, - protos.google.monitoring.v3.INotificationChannelDescriptor>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.monitoring.v3.IListNotificationChannelDescriptorsRequest, + | protos.google.monitoring.v3.IListNotificationChannelDescriptorsResponse + | null + | undefined, + protos.google.monitoring.v3.INotificationChannelDescriptor + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { - this._log.info('listNotificationChannelDescriptors values %j', values); + this._log.info( + 'listNotificationChannelDescriptors values %j', + values, + ); callback!(error, values, nextPageRequest, rawResponse); } : undefined; this._log.info('listNotificationChannelDescriptors request %j', request); return this.innerApiCalls .listNotificationChannelDescriptors(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.monitoring.v3.INotificationChannelDescriptor[], - protos.google.monitoring.v3.IListNotificationChannelDescriptorsRequest|null, - protos.google.monitoring.v3.IListNotificationChannelDescriptorsResponse - ]) => { - this._log.info('listNotificationChannelDescriptors values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.monitoring.v3.INotificationChannelDescriptor[], + protos.google.monitoring.v3.IListNotificationChannelDescriptorsRequest | null, + protos.google.monitoring.v3.IListNotificationChannelDescriptorsResponse, + ]) => { + this._log.info( + 'listNotificationChannelDescriptors values %j', + response, + ); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listNotificationChannelDescriptors`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The REST resource name of the parent from which to retrieve - * the notification channel descriptors. The expected syntax is: - * - * projects/[PROJECT_ID] - * - * Note that this names the parent container in which to look for the - * descriptors; to retrieve a single descriptor by name, use the - * {@link protos.google.monitoring.v3.NotificationChannelService.GetNotificationChannelDescriptor|GetNotificationChannelDescriptor} - * operation, instead. - * @param {number} request.pageSize - * The maximum number of results to return in a single response. If - * not set to a positive number, a reasonable value will be chosen by the - * service. - * @param {string} request.pageToken - * If non-empty, `page_token` must contain a value returned as the - * `next_page_token` in a previous response to request the next set - * of results. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.monitoring.v3.NotificationChannelDescriptor|NotificationChannelDescriptor} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `listNotificationChannelDescriptorsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `listNotificationChannelDescriptors`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The REST resource name of the parent from which to retrieve + * the notification channel descriptors. The expected syntax is: + * + * projects/[PROJECT_ID] + * + * Note that this names the parent container in which to look for the + * descriptors; to retrieve a single descriptor by name, use the + * {@link protos.google.monitoring.v3.NotificationChannelService.GetNotificationChannelDescriptor|GetNotificationChannelDescriptor} + * operation, instead. + * @param {number} request.pageSize + * The maximum number of results to return in a single response. If + * not set to a positive number, a reasonable value will be chosen by the + * service. + * @param {string} request.pageToken + * If non-empty, `page_token` must contain a value returned as the + * `next_page_token` in a previous response to request the next set + * of results. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.monitoring.v3.NotificationChannelDescriptor|NotificationChannelDescriptor} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listNotificationChannelDescriptorsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listNotificationChannelDescriptorsStream( - request?: protos.google.monitoring.v3.IListNotificationChannelDescriptorsRequest, - options?: CallOptions): - Transform{ + request?: protos.google.monitoring.v3.IListNotificationChannelDescriptorsRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', - }); - const defaultCallSettings = this._defaults['listNotificationChannelDescriptors']; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + const defaultCallSettings = + this._defaults['listNotificationChannelDescriptors']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listNotificationChannelDescriptors stream %j', request); return this.descriptors.page.listNotificationChannelDescriptors.createStream( this.innerApiCalls.listNotificationChannelDescriptors as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listNotificationChannelDescriptors`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The REST resource name of the parent from which to retrieve - * the notification channel descriptors. The expected syntax is: - * - * projects/[PROJECT_ID] - * - * Note that this names the parent container in which to look for the - * descriptors; to retrieve a single descriptor by name, use the - * {@link protos.google.monitoring.v3.NotificationChannelService.GetNotificationChannelDescriptor|GetNotificationChannelDescriptor} - * operation, instead. - * @param {number} request.pageSize - * The maximum number of results to return in a single response. If - * not set to a positive number, a reasonable value will be chosen by the - * service. - * @param {string} request.pageToken - * If non-empty, `page_token` must contain a value returned as the - * `next_page_token` in a previous response to request the next set - * of results. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.monitoring.v3.NotificationChannelDescriptor|NotificationChannelDescriptor}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v3/notification_channel_service.list_notification_channel_descriptors.js - * region_tag:monitoring_v3_generated_NotificationChannelService_ListNotificationChannelDescriptors_async - */ + /** + * Equivalent to `listNotificationChannelDescriptors`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The REST resource name of the parent from which to retrieve + * the notification channel descriptors. The expected syntax is: + * + * projects/[PROJECT_ID] + * + * Note that this names the parent container in which to look for the + * descriptors; to retrieve a single descriptor by name, use the + * {@link protos.google.monitoring.v3.NotificationChannelService.GetNotificationChannelDescriptor|GetNotificationChannelDescriptor} + * operation, instead. + * @param {number} request.pageSize + * The maximum number of results to return in a single response. If + * not set to a positive number, a reasonable value will be chosen by the + * service. + * @param {string} request.pageToken + * If non-empty, `page_token` must contain a value returned as the + * `next_page_token` in a previous response to request the next set + * of results. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.monitoring.v3.NotificationChannelDescriptor|NotificationChannelDescriptor}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v3/notification_channel_service.list_notification_channel_descriptors.js + * region_tag:monitoring_v3_generated_NotificationChannelService_ListNotificationChannelDescriptors_async + */ listNotificationChannelDescriptorsAsync( - request?: protos.google.monitoring.v3.IListNotificationChannelDescriptorsRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.monitoring.v3.IListNotificationChannelDescriptorsRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', - }); - const defaultCallSettings = this._defaults['listNotificationChannelDescriptors']; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + const defaultCallSettings = + this._defaults['listNotificationChannelDescriptors']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listNotificationChannelDescriptors iterate %j', request); return this.descriptors.page.listNotificationChannelDescriptors.asyncIterate( this.innerApiCalls['listNotificationChannelDescriptors'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } - /** - * Lists the notification channels that have been created for the project. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The project on which to execute the request. The format is - * `projects/[PROJECT_ID]`. That is, this names the container - * in which to look for the notification channels; it does not name a - * specific channel. To query a specific channel by REST resource name, use - * the - * {@link protos.google.monitoring.v3.NotificationChannelService.GetNotificationChannel|`GetNotificationChannel`} - * operation. - * @param {string} request.filter - * If provided, this field specifies the criteria that must be met by - * notification channels to be included in the response. - * - * For more details, see [sorting and - * filtering](/monitoring/api/v3/sorting-and-filtering). - * @param {string} request.orderBy - * A comma-separated list of fields by which to sort the result. Supports - * the same set of fields as in `filter`. Entries can be prefixed with - * a minus sign to sort in descending rather than ascending order. - * - * For more details, see [sorting and - * filtering](/monitoring/api/v3/sorting-and-filtering). - * @param {number} request.pageSize - * The maximum number of results to return in a single response. If - * not set to a positive number, a reasonable value will be chosen by the - * service. - * @param {string} request.pageToken - * If non-empty, `page_token` must contain a value returned as the - * `next_page_token` in a previous response to request the next set - * of results. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.monitoring.v3.NotificationChannel|NotificationChannel}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `listNotificationChannelsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Lists the notification channels that have been created for the project. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The project on which to execute the request. The format is + * `projects/[PROJECT_ID]`. That is, this names the container + * in which to look for the notification channels; it does not name a + * specific channel. To query a specific channel by REST resource name, use + * the + * {@link protos.google.monitoring.v3.NotificationChannelService.GetNotificationChannel|`GetNotificationChannel`} + * operation. + * @param {string} request.filter + * If provided, this field specifies the criteria that must be met by + * notification channels to be included in the response. + * + * For more details, see [sorting and + * filtering](/monitoring/api/v3/sorting-and-filtering). + * @param {string} request.orderBy + * A comma-separated list of fields by which to sort the result. Supports + * the same set of fields as in `filter`. Entries can be prefixed with + * a minus sign to sort in descending rather than ascending order. + * + * For more details, see [sorting and + * filtering](/monitoring/api/v3/sorting-and-filtering). + * @param {number} request.pageSize + * The maximum number of results to return in a single response. If + * not set to a positive number, a reasonable value will be chosen by the + * service. + * @param {string} request.pageToken + * If non-empty, `page_token` must contain a value returned as the + * `next_page_token` in a previous response to request the next set + * of results. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.monitoring.v3.NotificationChannel|NotificationChannel}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listNotificationChannelsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listNotificationChannels( - request?: protos.google.monitoring.v3.IListNotificationChannelsRequest, - options?: CallOptions): - Promise<[ - protos.google.monitoring.v3.INotificationChannel[], - protos.google.monitoring.v3.IListNotificationChannelsRequest|null, - protos.google.monitoring.v3.IListNotificationChannelsResponse - ]>; + request?: protos.google.monitoring.v3.IListNotificationChannelsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.monitoring.v3.INotificationChannel[], + protos.google.monitoring.v3.IListNotificationChannelsRequest | null, + protos.google.monitoring.v3.IListNotificationChannelsResponse, + ] + >; listNotificationChannels( - request: protos.google.monitoring.v3.IListNotificationChannelsRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.monitoring.v3.IListNotificationChannelsRequest, - protos.google.monitoring.v3.IListNotificationChannelsResponse|null|undefined, - protos.google.monitoring.v3.INotificationChannel>): void; + request: protos.google.monitoring.v3.IListNotificationChannelsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.monitoring.v3.IListNotificationChannelsRequest, + | protos.google.monitoring.v3.IListNotificationChannelsResponse + | null + | undefined, + protos.google.monitoring.v3.INotificationChannel + >, + ): void; listNotificationChannels( - request: protos.google.monitoring.v3.IListNotificationChannelsRequest, - callback: PaginationCallback< - protos.google.monitoring.v3.IListNotificationChannelsRequest, - protos.google.monitoring.v3.IListNotificationChannelsResponse|null|undefined, - protos.google.monitoring.v3.INotificationChannel>): void; + request: protos.google.monitoring.v3.IListNotificationChannelsRequest, + callback: PaginationCallback< + protos.google.monitoring.v3.IListNotificationChannelsRequest, + | protos.google.monitoring.v3.IListNotificationChannelsResponse + | null + | undefined, + protos.google.monitoring.v3.INotificationChannel + >, + ): void; listNotificationChannels( - request?: protos.google.monitoring.v3.IListNotificationChannelsRequest, - optionsOrCallback?: CallOptions|PaginationCallback< - protos.google.monitoring.v3.IListNotificationChannelsRequest, - protos.google.monitoring.v3.IListNotificationChannelsResponse|null|undefined, - protos.google.monitoring.v3.INotificationChannel>, - callback?: PaginationCallback< + request?: protos.google.monitoring.v3.IListNotificationChannelsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.monitoring.v3.IListNotificationChannelsRequest, - protos.google.monitoring.v3.IListNotificationChannelsResponse|null|undefined, - protos.google.monitoring.v3.INotificationChannel>): - Promise<[ - protos.google.monitoring.v3.INotificationChannel[], - protos.google.monitoring.v3.IListNotificationChannelsRequest|null, - protos.google.monitoring.v3.IListNotificationChannelsResponse - ]>|void { + | protos.google.monitoring.v3.IListNotificationChannelsResponse + | null + | undefined, + protos.google.monitoring.v3.INotificationChannel + >, + callback?: PaginationCallback< + protos.google.monitoring.v3.IListNotificationChannelsRequest, + | protos.google.monitoring.v3.IListNotificationChannelsResponse + | null + | undefined, + protos.google.monitoring.v3.INotificationChannel + >, + ): Promise< + [ + protos.google.monitoring.v3.INotificationChannel[], + protos.google.monitoring.v3.IListNotificationChannelsRequest | null, + protos.google.monitoring.v3.IListNotificationChannelsResponse, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.monitoring.v3.IListNotificationChannelsRequest, - protos.google.monitoring.v3.IListNotificationChannelsResponse|null|undefined, - protos.google.monitoring.v3.INotificationChannel>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.monitoring.v3.IListNotificationChannelsRequest, + | protos.google.monitoring.v3.IListNotificationChannelsResponse + | null + | undefined, + protos.google.monitoring.v3.INotificationChannel + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listNotificationChannels values %j', values); callback!(error, values, nextPageRequest, rawResponse); @@ -1584,152 +2115,156 @@ export class NotificationChannelServiceClient { this._log.info('listNotificationChannels request %j', request); return this.innerApiCalls .listNotificationChannels(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.monitoring.v3.INotificationChannel[], - protos.google.monitoring.v3.IListNotificationChannelsRequest|null, - protos.google.monitoring.v3.IListNotificationChannelsResponse - ]) => { - this._log.info('listNotificationChannels values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.monitoring.v3.INotificationChannel[], + protos.google.monitoring.v3.IListNotificationChannelsRequest | null, + protos.google.monitoring.v3.IListNotificationChannelsResponse, + ]) => { + this._log.info('listNotificationChannels values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listNotificationChannels`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The project on which to execute the request. The format is - * `projects/[PROJECT_ID]`. That is, this names the container - * in which to look for the notification channels; it does not name a - * specific channel. To query a specific channel by REST resource name, use - * the - * {@link protos.google.monitoring.v3.NotificationChannelService.GetNotificationChannel|`GetNotificationChannel`} - * operation. - * @param {string} request.filter - * If provided, this field specifies the criteria that must be met by - * notification channels to be included in the response. - * - * For more details, see [sorting and - * filtering](/monitoring/api/v3/sorting-and-filtering). - * @param {string} request.orderBy - * A comma-separated list of fields by which to sort the result. Supports - * the same set of fields as in `filter`. Entries can be prefixed with - * a minus sign to sort in descending rather than ascending order. - * - * For more details, see [sorting and - * filtering](/monitoring/api/v3/sorting-and-filtering). - * @param {number} request.pageSize - * The maximum number of results to return in a single response. If - * not set to a positive number, a reasonable value will be chosen by the - * service. - * @param {string} request.pageToken - * If non-empty, `page_token` must contain a value returned as the - * `next_page_token` in a previous response to request the next set - * of results. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.monitoring.v3.NotificationChannel|NotificationChannel} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `listNotificationChannelsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `listNotificationChannels`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The project on which to execute the request. The format is + * `projects/[PROJECT_ID]`. That is, this names the container + * in which to look for the notification channels; it does not name a + * specific channel. To query a specific channel by REST resource name, use + * the + * {@link protos.google.monitoring.v3.NotificationChannelService.GetNotificationChannel|`GetNotificationChannel`} + * operation. + * @param {string} request.filter + * If provided, this field specifies the criteria that must be met by + * notification channels to be included in the response. + * + * For more details, see [sorting and + * filtering](/monitoring/api/v3/sorting-and-filtering). + * @param {string} request.orderBy + * A comma-separated list of fields by which to sort the result. Supports + * the same set of fields as in `filter`. Entries can be prefixed with + * a minus sign to sort in descending rather than ascending order. + * + * For more details, see [sorting and + * filtering](/monitoring/api/v3/sorting-and-filtering). + * @param {number} request.pageSize + * The maximum number of results to return in a single response. If + * not set to a positive number, a reasonable value will be chosen by the + * service. + * @param {string} request.pageToken + * If non-empty, `page_token` must contain a value returned as the + * `next_page_token` in a previous response to request the next set + * of results. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.monitoring.v3.NotificationChannel|NotificationChannel} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listNotificationChannelsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listNotificationChannelsStream( - request?: protos.google.monitoring.v3.IListNotificationChannelsRequest, - options?: CallOptions): - Transform{ + request?: protos.google.monitoring.v3.IListNotificationChannelsRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); const defaultCallSettings = this._defaults['listNotificationChannels']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listNotificationChannels stream %j', request); return this.descriptors.page.listNotificationChannels.createStream( this.innerApiCalls.listNotificationChannels as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listNotificationChannels`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The project on which to execute the request. The format is - * `projects/[PROJECT_ID]`. That is, this names the container - * in which to look for the notification channels; it does not name a - * specific channel. To query a specific channel by REST resource name, use - * the - * {@link protos.google.monitoring.v3.NotificationChannelService.GetNotificationChannel|`GetNotificationChannel`} - * operation. - * @param {string} request.filter - * If provided, this field specifies the criteria that must be met by - * notification channels to be included in the response. - * - * For more details, see [sorting and - * filtering](/monitoring/api/v3/sorting-and-filtering). - * @param {string} request.orderBy - * A comma-separated list of fields by which to sort the result. Supports - * the same set of fields as in `filter`. Entries can be prefixed with - * a minus sign to sort in descending rather than ascending order. - * - * For more details, see [sorting and - * filtering](/monitoring/api/v3/sorting-and-filtering). - * @param {number} request.pageSize - * The maximum number of results to return in a single response. If - * not set to a positive number, a reasonable value will be chosen by the - * service. - * @param {string} request.pageToken - * If non-empty, `page_token` must contain a value returned as the - * `next_page_token` in a previous response to request the next set - * of results. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.monitoring.v3.NotificationChannel|NotificationChannel}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v3/notification_channel_service.list_notification_channels.js - * region_tag:monitoring_v3_generated_NotificationChannelService_ListNotificationChannels_async - */ + /** + * Equivalent to `listNotificationChannels`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The project on which to execute the request. The format is + * `projects/[PROJECT_ID]`. That is, this names the container + * in which to look for the notification channels; it does not name a + * specific channel. To query a specific channel by REST resource name, use + * the + * {@link protos.google.monitoring.v3.NotificationChannelService.GetNotificationChannel|`GetNotificationChannel`} + * operation. + * @param {string} request.filter + * If provided, this field specifies the criteria that must be met by + * notification channels to be included in the response. + * + * For more details, see [sorting and + * filtering](/monitoring/api/v3/sorting-and-filtering). + * @param {string} request.orderBy + * A comma-separated list of fields by which to sort the result. Supports + * the same set of fields as in `filter`. Entries can be prefixed with + * a minus sign to sort in descending rather than ascending order. + * + * For more details, see [sorting and + * filtering](/monitoring/api/v3/sorting-and-filtering). + * @param {number} request.pageSize + * The maximum number of results to return in a single response. If + * not set to a positive number, a reasonable value will be chosen by the + * service. + * @param {string} request.pageToken + * If non-empty, `page_token` must contain a value returned as the + * `next_page_token` in a previous response to request the next set + * of results. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.monitoring.v3.NotificationChannel|NotificationChannel}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v3/notification_channel_service.list_notification_channels.js + * region_tag:monitoring_v3_generated_NotificationChannelService_ListNotificationChannels_async + */ listNotificationChannelsAsync( - request?: protos.google.monitoring.v3.IListNotificationChannelsRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.monitoring.v3.IListNotificationChannelsRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); const defaultCallSettings = this._defaults['listNotificationChannels']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listNotificationChannels iterate %j', request); return this.descriptors.page.listNotificationChannels.asyncIterate( this.innerApiCalls['listNotificationChannels'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } // -------------------- @@ -1743,7 +2278,7 @@ export class NotificationChannelServiceClient { * @param {string} alert_policy * @returns {string} Resource name string. */ - folderAlertPolicyPath(folder:string,alertPolicy:string) { + folderAlertPolicyPath(folder: string, alertPolicy: string) { return this.pathTemplates.folderAlertPolicyPathTemplate.render({ folder: folder, alert_policy: alertPolicy, @@ -1758,7 +2293,9 @@ export class NotificationChannelServiceClient { * @returns {string} A string representing the folder. */ matchFolderFromFolderAlertPolicyName(folderAlertPolicyName: string) { - return this.pathTemplates.folderAlertPolicyPathTemplate.match(folderAlertPolicyName).folder; + return this.pathTemplates.folderAlertPolicyPathTemplate.match( + folderAlertPolicyName, + ).folder; } /** @@ -1769,7 +2306,9 @@ export class NotificationChannelServiceClient { * @returns {string} A string representing the alert_policy. */ matchAlertPolicyFromFolderAlertPolicyName(folderAlertPolicyName: string) { - return this.pathTemplates.folderAlertPolicyPathTemplate.match(folderAlertPolicyName).alert_policy; + return this.pathTemplates.folderAlertPolicyPathTemplate.match( + folderAlertPolicyName, + ).alert_policy; } /** @@ -1780,7 +2319,11 @@ export class NotificationChannelServiceClient { * @param {string} condition * @returns {string} Resource name string. */ - folderAlertPolicyConditionPath(folder:string,alertPolicy:string,condition:string) { + folderAlertPolicyConditionPath( + folder: string, + alertPolicy: string, + condition: string, + ) { return this.pathTemplates.folderAlertPolicyConditionPathTemplate.render({ folder: folder, alert_policy: alertPolicy, @@ -1795,8 +2338,12 @@ export class NotificationChannelServiceClient { * A fully-qualified path representing folder_alert_policy_condition resource. * @returns {string} A string representing the folder. */ - matchFolderFromFolderAlertPolicyConditionName(folderAlertPolicyConditionName: string) { - return this.pathTemplates.folderAlertPolicyConditionPathTemplate.match(folderAlertPolicyConditionName).folder; + matchFolderFromFolderAlertPolicyConditionName( + folderAlertPolicyConditionName: string, + ) { + return this.pathTemplates.folderAlertPolicyConditionPathTemplate.match( + folderAlertPolicyConditionName, + ).folder; } /** @@ -1806,8 +2353,12 @@ export class NotificationChannelServiceClient { * A fully-qualified path representing folder_alert_policy_condition resource. * @returns {string} A string representing the alert_policy. */ - matchAlertPolicyFromFolderAlertPolicyConditionName(folderAlertPolicyConditionName: string) { - return this.pathTemplates.folderAlertPolicyConditionPathTemplate.match(folderAlertPolicyConditionName).alert_policy; + matchAlertPolicyFromFolderAlertPolicyConditionName( + folderAlertPolicyConditionName: string, + ) { + return this.pathTemplates.folderAlertPolicyConditionPathTemplate.match( + folderAlertPolicyConditionName, + ).alert_policy; } /** @@ -1817,8 +2368,12 @@ export class NotificationChannelServiceClient { * A fully-qualified path representing folder_alert_policy_condition resource. * @returns {string} A string representing the condition. */ - matchConditionFromFolderAlertPolicyConditionName(folderAlertPolicyConditionName: string) { - return this.pathTemplates.folderAlertPolicyConditionPathTemplate.match(folderAlertPolicyConditionName).condition; + matchConditionFromFolderAlertPolicyConditionName( + folderAlertPolicyConditionName: string, + ) { + return this.pathTemplates.folderAlertPolicyConditionPathTemplate.match( + folderAlertPolicyConditionName, + ).condition; } /** @@ -1828,7 +2383,7 @@ export class NotificationChannelServiceClient { * @param {string} channel_descriptor * @returns {string} Resource name string. */ - folderChannelDescriptorPath(folder:string,channelDescriptor:string) { + folderChannelDescriptorPath(folder: string, channelDescriptor: string) { return this.pathTemplates.folderChannelDescriptorPathTemplate.render({ folder: folder, channel_descriptor: channelDescriptor, @@ -1842,8 +2397,12 @@ export class NotificationChannelServiceClient { * A fully-qualified path representing folder_channel_descriptor resource. * @returns {string} A string representing the folder. */ - matchFolderFromFolderChannelDescriptorName(folderChannelDescriptorName: string) { - return this.pathTemplates.folderChannelDescriptorPathTemplate.match(folderChannelDescriptorName).folder; + matchFolderFromFolderChannelDescriptorName( + folderChannelDescriptorName: string, + ) { + return this.pathTemplates.folderChannelDescriptorPathTemplate.match( + folderChannelDescriptorName, + ).folder; } /** @@ -1853,8 +2412,12 @@ export class NotificationChannelServiceClient { * A fully-qualified path representing folder_channel_descriptor resource. * @returns {string} A string representing the channel_descriptor. */ - matchChannelDescriptorFromFolderChannelDescriptorName(folderChannelDescriptorName: string) { - return this.pathTemplates.folderChannelDescriptorPathTemplate.match(folderChannelDescriptorName).channel_descriptor; + matchChannelDescriptorFromFolderChannelDescriptorName( + folderChannelDescriptorName: string, + ) { + return this.pathTemplates.folderChannelDescriptorPathTemplate.match( + folderChannelDescriptorName, + ).channel_descriptor; } /** @@ -1864,7 +2427,7 @@ export class NotificationChannelServiceClient { * @param {string} group * @returns {string} Resource name string. */ - folderGroupPath(folder:string,group:string) { + folderGroupPath(folder: string, group: string) { return this.pathTemplates.folderGroupPathTemplate.render({ folder: folder, group: group, @@ -1879,7 +2442,8 @@ export class NotificationChannelServiceClient { * @returns {string} A string representing the folder. */ matchFolderFromFolderGroupName(folderGroupName: string) { - return this.pathTemplates.folderGroupPathTemplate.match(folderGroupName).folder; + return this.pathTemplates.folderGroupPathTemplate.match(folderGroupName) + .folder; } /** @@ -1890,7 +2454,8 @@ export class NotificationChannelServiceClient { * @returns {string} A string representing the group. */ matchGroupFromFolderGroupName(folderGroupName: string) { - return this.pathTemplates.folderGroupPathTemplate.match(folderGroupName).group; + return this.pathTemplates.folderGroupPathTemplate.match(folderGroupName) + .group; } /** @@ -1900,7 +2465,7 @@ export class NotificationChannelServiceClient { * @param {string} notification_channel * @returns {string} Resource name string. */ - folderNotificationChannelPath(folder:string,notificationChannel:string) { + folderNotificationChannelPath(folder: string, notificationChannel: string) { return this.pathTemplates.folderNotificationChannelPathTemplate.render({ folder: folder, notification_channel: notificationChannel, @@ -1914,8 +2479,12 @@ export class NotificationChannelServiceClient { * A fully-qualified path representing folder_notification_channel resource. * @returns {string} A string representing the folder. */ - matchFolderFromFolderNotificationChannelName(folderNotificationChannelName: string) { - return this.pathTemplates.folderNotificationChannelPathTemplate.match(folderNotificationChannelName).folder; + matchFolderFromFolderNotificationChannelName( + folderNotificationChannelName: string, + ) { + return this.pathTemplates.folderNotificationChannelPathTemplate.match( + folderNotificationChannelName, + ).folder; } /** @@ -1925,8 +2494,12 @@ export class NotificationChannelServiceClient { * A fully-qualified path representing folder_notification_channel resource. * @returns {string} A string representing the notification_channel. */ - matchNotificationChannelFromFolderNotificationChannelName(folderNotificationChannelName: string) { - return this.pathTemplates.folderNotificationChannelPathTemplate.match(folderNotificationChannelName).notification_channel; + matchNotificationChannelFromFolderNotificationChannelName( + folderNotificationChannelName: string, + ) { + return this.pathTemplates.folderNotificationChannelPathTemplate.match( + folderNotificationChannelName, + ).notification_channel; } /** @@ -1936,7 +2509,7 @@ export class NotificationChannelServiceClient { * @param {string} service * @returns {string} Resource name string. */ - folderServicePath(folder:string,service:string) { + folderServicePath(folder: string, service: string) { return this.pathTemplates.folderServicePathTemplate.render({ folder: folder, service: service, @@ -1951,7 +2524,8 @@ export class NotificationChannelServiceClient { * @returns {string} A string representing the folder. */ matchFolderFromFolderServiceName(folderServiceName: string) { - return this.pathTemplates.folderServicePathTemplate.match(folderServiceName).folder; + return this.pathTemplates.folderServicePathTemplate.match(folderServiceName) + .folder; } /** @@ -1962,7 +2536,8 @@ export class NotificationChannelServiceClient { * @returns {string} A string representing the service. */ matchServiceFromFolderServiceName(folderServiceName: string) { - return this.pathTemplates.folderServicePathTemplate.match(folderServiceName).service; + return this.pathTemplates.folderServicePathTemplate.match(folderServiceName) + .service; } /** @@ -1973,12 +2548,18 @@ export class NotificationChannelServiceClient { * @param {string} service_level_objective * @returns {string} Resource name string. */ - folderServiceServiceLevelObjectivePath(folder:string,service:string,serviceLevelObjective:string) { - return this.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.render({ - folder: folder, - service: service, - service_level_objective: serviceLevelObjective, - }); + folderServiceServiceLevelObjectivePath( + folder: string, + service: string, + serviceLevelObjective: string, + ) { + return this.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.render( + { + folder: folder, + service: service, + service_level_objective: serviceLevelObjective, + }, + ); } /** @@ -1988,8 +2569,12 @@ export class NotificationChannelServiceClient { * A fully-qualified path representing folder_service_service_level_objective resource. * @returns {string} A string representing the folder. */ - matchFolderFromFolderServiceServiceLevelObjectiveName(folderServiceServiceLevelObjectiveName: string) { - return this.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match(folderServiceServiceLevelObjectiveName).folder; + matchFolderFromFolderServiceServiceLevelObjectiveName( + folderServiceServiceLevelObjectiveName: string, + ) { + return this.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match( + folderServiceServiceLevelObjectiveName, + ).folder; } /** @@ -1999,8 +2584,12 @@ export class NotificationChannelServiceClient { * A fully-qualified path representing folder_service_service_level_objective resource. * @returns {string} A string representing the service. */ - matchServiceFromFolderServiceServiceLevelObjectiveName(folderServiceServiceLevelObjectiveName: string) { - return this.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match(folderServiceServiceLevelObjectiveName).service; + matchServiceFromFolderServiceServiceLevelObjectiveName( + folderServiceServiceLevelObjectiveName: string, + ) { + return this.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match( + folderServiceServiceLevelObjectiveName, + ).service; } /** @@ -2010,8 +2599,12 @@ export class NotificationChannelServiceClient { * A fully-qualified path representing folder_service_service_level_objective resource. * @returns {string} A string representing the service_level_objective. */ - matchServiceLevelObjectiveFromFolderServiceServiceLevelObjectiveName(folderServiceServiceLevelObjectiveName: string) { - return this.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match(folderServiceServiceLevelObjectiveName).service_level_objective; + matchServiceLevelObjectiveFromFolderServiceServiceLevelObjectiveName( + folderServiceServiceLevelObjectiveName: string, + ) { + return this.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match( + folderServiceServiceLevelObjectiveName, + ).service_level_objective; } /** @@ -2021,7 +2614,7 @@ export class NotificationChannelServiceClient { * @param {string} uptime_check_config * @returns {string} Resource name string. */ - folderUptimeCheckConfigPath(folder:string,uptimeCheckConfig:string) { + folderUptimeCheckConfigPath(folder: string, uptimeCheckConfig: string) { return this.pathTemplates.folderUptimeCheckConfigPathTemplate.render({ folder: folder, uptime_check_config: uptimeCheckConfig, @@ -2035,8 +2628,12 @@ export class NotificationChannelServiceClient { * A fully-qualified path representing folder_uptime_check_config resource. * @returns {string} A string representing the folder. */ - matchFolderFromFolderUptimeCheckConfigName(folderUptimeCheckConfigName: string) { - return this.pathTemplates.folderUptimeCheckConfigPathTemplate.match(folderUptimeCheckConfigName).folder; + matchFolderFromFolderUptimeCheckConfigName( + folderUptimeCheckConfigName: string, + ) { + return this.pathTemplates.folderUptimeCheckConfigPathTemplate.match( + folderUptimeCheckConfigName, + ).folder; } /** @@ -2046,8 +2643,12 @@ export class NotificationChannelServiceClient { * A fully-qualified path representing folder_uptime_check_config resource. * @returns {string} A string representing the uptime_check_config. */ - matchUptimeCheckConfigFromFolderUptimeCheckConfigName(folderUptimeCheckConfigName: string) { - return this.pathTemplates.folderUptimeCheckConfigPathTemplate.match(folderUptimeCheckConfigName).uptime_check_config; + matchUptimeCheckConfigFromFolderUptimeCheckConfigName( + folderUptimeCheckConfigName: string, + ) { + return this.pathTemplates.folderUptimeCheckConfigPathTemplate.match( + folderUptimeCheckConfigName, + ).uptime_check_config; } /** @@ -2057,7 +2658,7 @@ export class NotificationChannelServiceClient { * @param {string} alert_policy * @returns {string} Resource name string. */ - organizationAlertPolicyPath(organization:string,alertPolicy:string) { + organizationAlertPolicyPath(organization: string, alertPolicy: string) { return this.pathTemplates.organizationAlertPolicyPathTemplate.render({ organization: organization, alert_policy: alertPolicy, @@ -2071,8 +2672,12 @@ export class NotificationChannelServiceClient { * A fully-qualified path representing organization_alert_policy resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationAlertPolicyName(organizationAlertPolicyName: string) { - return this.pathTemplates.organizationAlertPolicyPathTemplate.match(organizationAlertPolicyName).organization; + matchOrganizationFromOrganizationAlertPolicyName( + organizationAlertPolicyName: string, + ) { + return this.pathTemplates.organizationAlertPolicyPathTemplate.match( + organizationAlertPolicyName, + ).organization; } /** @@ -2082,8 +2687,12 @@ export class NotificationChannelServiceClient { * A fully-qualified path representing organization_alert_policy resource. * @returns {string} A string representing the alert_policy. */ - matchAlertPolicyFromOrganizationAlertPolicyName(organizationAlertPolicyName: string) { - return this.pathTemplates.organizationAlertPolicyPathTemplate.match(organizationAlertPolicyName).alert_policy; + matchAlertPolicyFromOrganizationAlertPolicyName( + organizationAlertPolicyName: string, + ) { + return this.pathTemplates.organizationAlertPolicyPathTemplate.match( + organizationAlertPolicyName, + ).alert_policy; } /** @@ -2094,12 +2703,18 @@ export class NotificationChannelServiceClient { * @param {string} condition * @returns {string} Resource name string. */ - organizationAlertPolicyConditionPath(organization:string,alertPolicy:string,condition:string) { - return this.pathTemplates.organizationAlertPolicyConditionPathTemplate.render({ - organization: organization, - alert_policy: alertPolicy, - condition: condition, - }); + organizationAlertPolicyConditionPath( + organization: string, + alertPolicy: string, + condition: string, + ) { + return this.pathTemplates.organizationAlertPolicyConditionPathTemplate.render( + { + organization: organization, + alert_policy: alertPolicy, + condition: condition, + }, + ); } /** @@ -2109,8 +2724,12 @@ export class NotificationChannelServiceClient { * A fully-qualified path representing organization_alert_policy_condition resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationAlertPolicyConditionName(organizationAlertPolicyConditionName: string) { - return this.pathTemplates.organizationAlertPolicyConditionPathTemplate.match(organizationAlertPolicyConditionName).organization; + matchOrganizationFromOrganizationAlertPolicyConditionName( + organizationAlertPolicyConditionName: string, + ) { + return this.pathTemplates.organizationAlertPolicyConditionPathTemplate.match( + organizationAlertPolicyConditionName, + ).organization; } /** @@ -2120,8 +2739,12 @@ export class NotificationChannelServiceClient { * A fully-qualified path representing organization_alert_policy_condition resource. * @returns {string} A string representing the alert_policy. */ - matchAlertPolicyFromOrganizationAlertPolicyConditionName(organizationAlertPolicyConditionName: string) { - return this.pathTemplates.organizationAlertPolicyConditionPathTemplate.match(organizationAlertPolicyConditionName).alert_policy; + matchAlertPolicyFromOrganizationAlertPolicyConditionName( + organizationAlertPolicyConditionName: string, + ) { + return this.pathTemplates.organizationAlertPolicyConditionPathTemplate.match( + organizationAlertPolicyConditionName, + ).alert_policy; } /** @@ -2131,8 +2754,12 @@ export class NotificationChannelServiceClient { * A fully-qualified path representing organization_alert_policy_condition resource. * @returns {string} A string representing the condition. */ - matchConditionFromOrganizationAlertPolicyConditionName(organizationAlertPolicyConditionName: string) { - return this.pathTemplates.organizationAlertPolicyConditionPathTemplate.match(organizationAlertPolicyConditionName).condition; + matchConditionFromOrganizationAlertPolicyConditionName( + organizationAlertPolicyConditionName: string, + ) { + return this.pathTemplates.organizationAlertPolicyConditionPathTemplate.match( + organizationAlertPolicyConditionName, + ).condition; } /** @@ -2142,7 +2769,10 @@ export class NotificationChannelServiceClient { * @param {string} channel_descriptor * @returns {string} Resource name string. */ - organizationChannelDescriptorPath(organization:string,channelDescriptor:string) { + organizationChannelDescriptorPath( + organization: string, + channelDescriptor: string, + ) { return this.pathTemplates.organizationChannelDescriptorPathTemplate.render({ organization: organization, channel_descriptor: channelDescriptor, @@ -2156,8 +2786,12 @@ export class NotificationChannelServiceClient { * A fully-qualified path representing organization_channel_descriptor resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationChannelDescriptorName(organizationChannelDescriptorName: string) { - return this.pathTemplates.organizationChannelDescriptorPathTemplate.match(organizationChannelDescriptorName).organization; + matchOrganizationFromOrganizationChannelDescriptorName( + organizationChannelDescriptorName: string, + ) { + return this.pathTemplates.organizationChannelDescriptorPathTemplate.match( + organizationChannelDescriptorName, + ).organization; } /** @@ -2167,8 +2801,12 @@ export class NotificationChannelServiceClient { * A fully-qualified path representing organization_channel_descriptor resource. * @returns {string} A string representing the channel_descriptor. */ - matchChannelDescriptorFromOrganizationChannelDescriptorName(organizationChannelDescriptorName: string) { - return this.pathTemplates.organizationChannelDescriptorPathTemplate.match(organizationChannelDescriptorName).channel_descriptor; + matchChannelDescriptorFromOrganizationChannelDescriptorName( + organizationChannelDescriptorName: string, + ) { + return this.pathTemplates.organizationChannelDescriptorPathTemplate.match( + organizationChannelDescriptorName, + ).channel_descriptor; } /** @@ -2178,7 +2816,7 @@ export class NotificationChannelServiceClient { * @param {string} group * @returns {string} Resource name string. */ - organizationGroupPath(organization:string,group:string) { + organizationGroupPath(organization: string, group: string) { return this.pathTemplates.organizationGroupPathTemplate.render({ organization: organization, group: group, @@ -2193,7 +2831,9 @@ export class NotificationChannelServiceClient { * @returns {string} A string representing the organization. */ matchOrganizationFromOrganizationGroupName(organizationGroupName: string) { - return this.pathTemplates.organizationGroupPathTemplate.match(organizationGroupName).organization; + return this.pathTemplates.organizationGroupPathTemplate.match( + organizationGroupName, + ).organization; } /** @@ -2204,7 +2844,9 @@ export class NotificationChannelServiceClient { * @returns {string} A string representing the group. */ matchGroupFromOrganizationGroupName(organizationGroupName: string) { - return this.pathTemplates.organizationGroupPathTemplate.match(organizationGroupName).group; + return this.pathTemplates.organizationGroupPathTemplate.match( + organizationGroupName, + ).group; } /** @@ -2214,11 +2856,16 @@ export class NotificationChannelServiceClient { * @param {string} notification_channel * @returns {string} Resource name string. */ - organizationNotificationChannelPath(organization:string,notificationChannel:string) { - return this.pathTemplates.organizationNotificationChannelPathTemplate.render({ - organization: organization, - notification_channel: notificationChannel, - }); + organizationNotificationChannelPath( + organization: string, + notificationChannel: string, + ) { + return this.pathTemplates.organizationNotificationChannelPathTemplate.render( + { + organization: organization, + notification_channel: notificationChannel, + }, + ); } /** @@ -2228,8 +2875,12 @@ export class NotificationChannelServiceClient { * A fully-qualified path representing organization_notification_channel resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationNotificationChannelName(organizationNotificationChannelName: string) { - return this.pathTemplates.organizationNotificationChannelPathTemplate.match(organizationNotificationChannelName).organization; + matchOrganizationFromOrganizationNotificationChannelName( + organizationNotificationChannelName: string, + ) { + return this.pathTemplates.organizationNotificationChannelPathTemplate.match( + organizationNotificationChannelName, + ).organization; } /** @@ -2239,8 +2890,12 @@ export class NotificationChannelServiceClient { * A fully-qualified path representing organization_notification_channel resource. * @returns {string} A string representing the notification_channel. */ - matchNotificationChannelFromOrganizationNotificationChannelName(organizationNotificationChannelName: string) { - return this.pathTemplates.organizationNotificationChannelPathTemplate.match(organizationNotificationChannelName).notification_channel; + matchNotificationChannelFromOrganizationNotificationChannelName( + organizationNotificationChannelName: string, + ) { + return this.pathTemplates.organizationNotificationChannelPathTemplate.match( + organizationNotificationChannelName, + ).notification_channel; } /** @@ -2250,7 +2905,7 @@ export class NotificationChannelServiceClient { * @param {string} service * @returns {string} Resource name string. */ - organizationServicePath(organization:string,service:string) { + organizationServicePath(organization: string, service: string) { return this.pathTemplates.organizationServicePathTemplate.render({ organization: organization, service: service, @@ -2264,8 +2919,12 @@ export class NotificationChannelServiceClient { * A fully-qualified path representing organization_service resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationServiceName(organizationServiceName: string) { - return this.pathTemplates.organizationServicePathTemplate.match(organizationServiceName).organization; + matchOrganizationFromOrganizationServiceName( + organizationServiceName: string, + ) { + return this.pathTemplates.organizationServicePathTemplate.match( + organizationServiceName, + ).organization; } /** @@ -2276,7 +2935,9 @@ export class NotificationChannelServiceClient { * @returns {string} A string representing the service. */ matchServiceFromOrganizationServiceName(organizationServiceName: string) { - return this.pathTemplates.organizationServicePathTemplate.match(organizationServiceName).service; + return this.pathTemplates.organizationServicePathTemplate.match( + organizationServiceName, + ).service; } /** @@ -2287,12 +2948,18 @@ export class NotificationChannelServiceClient { * @param {string} service_level_objective * @returns {string} Resource name string. */ - organizationServiceServiceLevelObjectivePath(organization:string,service:string,serviceLevelObjective:string) { - return this.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.render({ - organization: organization, - service: service, - service_level_objective: serviceLevelObjective, - }); + organizationServiceServiceLevelObjectivePath( + organization: string, + service: string, + serviceLevelObjective: string, + ) { + return this.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.render( + { + organization: organization, + service: service, + service_level_objective: serviceLevelObjective, + }, + ); } /** @@ -2302,8 +2969,12 @@ export class NotificationChannelServiceClient { * A fully-qualified path representing organization_service_service_level_objective resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationServiceServiceLevelObjectiveName(organizationServiceServiceLevelObjectiveName: string) { - return this.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match(organizationServiceServiceLevelObjectiveName).organization; + matchOrganizationFromOrganizationServiceServiceLevelObjectiveName( + organizationServiceServiceLevelObjectiveName: string, + ) { + return this.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match( + organizationServiceServiceLevelObjectiveName, + ).organization; } /** @@ -2313,8 +2984,12 @@ export class NotificationChannelServiceClient { * A fully-qualified path representing organization_service_service_level_objective resource. * @returns {string} A string representing the service. */ - matchServiceFromOrganizationServiceServiceLevelObjectiveName(organizationServiceServiceLevelObjectiveName: string) { - return this.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match(organizationServiceServiceLevelObjectiveName).service; + matchServiceFromOrganizationServiceServiceLevelObjectiveName( + organizationServiceServiceLevelObjectiveName: string, + ) { + return this.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match( + organizationServiceServiceLevelObjectiveName, + ).service; } /** @@ -2324,8 +2999,12 @@ export class NotificationChannelServiceClient { * A fully-qualified path representing organization_service_service_level_objective resource. * @returns {string} A string representing the service_level_objective. */ - matchServiceLevelObjectiveFromOrganizationServiceServiceLevelObjectiveName(organizationServiceServiceLevelObjectiveName: string) { - return this.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match(organizationServiceServiceLevelObjectiveName).service_level_objective; + matchServiceLevelObjectiveFromOrganizationServiceServiceLevelObjectiveName( + organizationServiceServiceLevelObjectiveName: string, + ) { + return this.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match( + organizationServiceServiceLevelObjectiveName, + ).service_level_objective; } /** @@ -2335,7 +3014,10 @@ export class NotificationChannelServiceClient { * @param {string} uptime_check_config * @returns {string} Resource name string. */ - organizationUptimeCheckConfigPath(organization:string,uptimeCheckConfig:string) { + organizationUptimeCheckConfigPath( + organization: string, + uptimeCheckConfig: string, + ) { return this.pathTemplates.organizationUptimeCheckConfigPathTemplate.render({ organization: organization, uptime_check_config: uptimeCheckConfig, @@ -2349,8 +3031,12 @@ export class NotificationChannelServiceClient { * A fully-qualified path representing organization_uptime_check_config resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationUptimeCheckConfigName(organizationUptimeCheckConfigName: string) { - return this.pathTemplates.organizationUptimeCheckConfigPathTemplate.match(organizationUptimeCheckConfigName).organization; + matchOrganizationFromOrganizationUptimeCheckConfigName( + organizationUptimeCheckConfigName: string, + ) { + return this.pathTemplates.organizationUptimeCheckConfigPathTemplate.match( + organizationUptimeCheckConfigName, + ).organization; } /** @@ -2360,8 +3046,12 @@ export class NotificationChannelServiceClient { * A fully-qualified path representing organization_uptime_check_config resource. * @returns {string} A string representing the uptime_check_config. */ - matchUptimeCheckConfigFromOrganizationUptimeCheckConfigName(organizationUptimeCheckConfigName: string) { - return this.pathTemplates.organizationUptimeCheckConfigPathTemplate.match(organizationUptimeCheckConfigName).uptime_check_config; + matchUptimeCheckConfigFromOrganizationUptimeCheckConfigName( + organizationUptimeCheckConfigName: string, + ) { + return this.pathTemplates.organizationUptimeCheckConfigPathTemplate.match( + organizationUptimeCheckConfigName, + ).uptime_check_config; } /** @@ -2371,7 +3061,7 @@ export class NotificationChannelServiceClient { * @param {string} alert_policy * @returns {string} Resource name string. */ - projectAlertPolicyPath(project:string,alertPolicy:string) { + projectAlertPolicyPath(project: string, alertPolicy: string) { return this.pathTemplates.projectAlertPolicyPathTemplate.render({ project: project, alert_policy: alertPolicy, @@ -2386,7 +3076,9 @@ export class NotificationChannelServiceClient { * @returns {string} A string representing the project. */ matchProjectFromProjectAlertPolicyName(projectAlertPolicyName: string) { - return this.pathTemplates.projectAlertPolicyPathTemplate.match(projectAlertPolicyName).project; + return this.pathTemplates.projectAlertPolicyPathTemplate.match( + projectAlertPolicyName, + ).project; } /** @@ -2397,7 +3089,9 @@ export class NotificationChannelServiceClient { * @returns {string} A string representing the alert_policy. */ matchAlertPolicyFromProjectAlertPolicyName(projectAlertPolicyName: string) { - return this.pathTemplates.projectAlertPolicyPathTemplate.match(projectAlertPolicyName).alert_policy; + return this.pathTemplates.projectAlertPolicyPathTemplate.match( + projectAlertPolicyName, + ).alert_policy; } /** @@ -2408,7 +3102,11 @@ export class NotificationChannelServiceClient { * @param {string} condition * @returns {string} Resource name string. */ - projectAlertPolicyConditionPath(project:string,alertPolicy:string,condition:string) { + projectAlertPolicyConditionPath( + project: string, + alertPolicy: string, + condition: string, + ) { return this.pathTemplates.projectAlertPolicyConditionPathTemplate.render({ project: project, alert_policy: alertPolicy, @@ -2423,8 +3121,12 @@ export class NotificationChannelServiceClient { * A fully-qualified path representing project_alert_policy_condition resource. * @returns {string} A string representing the project. */ - matchProjectFromProjectAlertPolicyConditionName(projectAlertPolicyConditionName: string) { - return this.pathTemplates.projectAlertPolicyConditionPathTemplate.match(projectAlertPolicyConditionName).project; + matchProjectFromProjectAlertPolicyConditionName( + projectAlertPolicyConditionName: string, + ) { + return this.pathTemplates.projectAlertPolicyConditionPathTemplate.match( + projectAlertPolicyConditionName, + ).project; } /** @@ -2434,8 +3136,12 @@ export class NotificationChannelServiceClient { * A fully-qualified path representing project_alert_policy_condition resource. * @returns {string} A string representing the alert_policy. */ - matchAlertPolicyFromProjectAlertPolicyConditionName(projectAlertPolicyConditionName: string) { - return this.pathTemplates.projectAlertPolicyConditionPathTemplate.match(projectAlertPolicyConditionName).alert_policy; + matchAlertPolicyFromProjectAlertPolicyConditionName( + projectAlertPolicyConditionName: string, + ) { + return this.pathTemplates.projectAlertPolicyConditionPathTemplate.match( + projectAlertPolicyConditionName, + ).alert_policy; } /** @@ -2445,8 +3151,12 @@ export class NotificationChannelServiceClient { * A fully-qualified path representing project_alert_policy_condition resource. * @returns {string} A string representing the condition. */ - matchConditionFromProjectAlertPolicyConditionName(projectAlertPolicyConditionName: string) { - return this.pathTemplates.projectAlertPolicyConditionPathTemplate.match(projectAlertPolicyConditionName).condition; + matchConditionFromProjectAlertPolicyConditionName( + projectAlertPolicyConditionName: string, + ) { + return this.pathTemplates.projectAlertPolicyConditionPathTemplate.match( + projectAlertPolicyConditionName, + ).condition; } /** @@ -2456,7 +3166,7 @@ export class NotificationChannelServiceClient { * @param {string} channel_descriptor * @returns {string} Resource name string. */ - projectChannelDescriptorPath(project:string,channelDescriptor:string) { + projectChannelDescriptorPath(project: string, channelDescriptor: string) { return this.pathTemplates.projectChannelDescriptorPathTemplate.render({ project: project, channel_descriptor: channelDescriptor, @@ -2470,8 +3180,12 @@ export class NotificationChannelServiceClient { * A fully-qualified path representing project_channel_descriptor resource. * @returns {string} A string representing the project. */ - matchProjectFromProjectChannelDescriptorName(projectChannelDescriptorName: string) { - return this.pathTemplates.projectChannelDescriptorPathTemplate.match(projectChannelDescriptorName).project; + matchProjectFromProjectChannelDescriptorName( + projectChannelDescriptorName: string, + ) { + return this.pathTemplates.projectChannelDescriptorPathTemplate.match( + projectChannelDescriptorName, + ).project; } /** @@ -2481,8 +3195,12 @@ export class NotificationChannelServiceClient { * A fully-qualified path representing project_channel_descriptor resource. * @returns {string} A string representing the channel_descriptor. */ - matchChannelDescriptorFromProjectChannelDescriptorName(projectChannelDescriptorName: string) { - return this.pathTemplates.projectChannelDescriptorPathTemplate.match(projectChannelDescriptorName).channel_descriptor; + matchChannelDescriptorFromProjectChannelDescriptorName( + projectChannelDescriptorName: string, + ) { + return this.pathTemplates.projectChannelDescriptorPathTemplate.match( + projectChannelDescriptorName, + ).channel_descriptor; } /** @@ -2492,7 +3210,7 @@ export class NotificationChannelServiceClient { * @param {string} group * @returns {string} Resource name string. */ - projectGroupPath(project:string,group:string) { + projectGroupPath(project: string, group: string) { return this.pathTemplates.projectGroupPathTemplate.render({ project: project, group: group, @@ -2507,7 +3225,8 @@ export class NotificationChannelServiceClient { * @returns {string} A string representing the project. */ matchProjectFromProjectGroupName(projectGroupName: string) { - return this.pathTemplates.projectGroupPathTemplate.match(projectGroupName).project; + return this.pathTemplates.projectGroupPathTemplate.match(projectGroupName) + .project; } /** @@ -2518,7 +3237,8 @@ export class NotificationChannelServiceClient { * @returns {string} A string representing the group. */ matchGroupFromProjectGroupName(projectGroupName: string) { - return this.pathTemplates.projectGroupPathTemplate.match(projectGroupName).group; + return this.pathTemplates.projectGroupPathTemplate.match(projectGroupName) + .group; } /** @@ -2528,7 +3248,7 @@ export class NotificationChannelServiceClient { * @param {string} notification_channel * @returns {string} Resource name string. */ - projectNotificationChannelPath(project:string,notificationChannel:string) { + projectNotificationChannelPath(project: string, notificationChannel: string) { return this.pathTemplates.projectNotificationChannelPathTemplate.render({ project: project, notification_channel: notificationChannel, @@ -2542,8 +3262,12 @@ export class NotificationChannelServiceClient { * A fully-qualified path representing project_notification_channel resource. * @returns {string} A string representing the project. */ - matchProjectFromProjectNotificationChannelName(projectNotificationChannelName: string) { - return this.pathTemplates.projectNotificationChannelPathTemplate.match(projectNotificationChannelName).project; + matchProjectFromProjectNotificationChannelName( + projectNotificationChannelName: string, + ) { + return this.pathTemplates.projectNotificationChannelPathTemplate.match( + projectNotificationChannelName, + ).project; } /** @@ -2553,8 +3277,12 @@ export class NotificationChannelServiceClient { * A fully-qualified path representing project_notification_channel resource. * @returns {string} A string representing the notification_channel. */ - matchNotificationChannelFromProjectNotificationChannelName(projectNotificationChannelName: string) { - return this.pathTemplates.projectNotificationChannelPathTemplate.match(projectNotificationChannelName).notification_channel; + matchNotificationChannelFromProjectNotificationChannelName( + projectNotificationChannelName: string, + ) { + return this.pathTemplates.projectNotificationChannelPathTemplate.match( + projectNotificationChannelName, + ).notification_channel; } /** @@ -2564,7 +3292,7 @@ export class NotificationChannelServiceClient { * @param {string} service * @returns {string} Resource name string. */ - projectServicePath(project:string,service:string) { + projectServicePath(project: string, service: string) { return this.pathTemplates.projectServicePathTemplate.render({ project: project, service: service, @@ -2579,7 +3307,9 @@ export class NotificationChannelServiceClient { * @returns {string} A string representing the project. */ matchProjectFromProjectServiceName(projectServiceName: string) { - return this.pathTemplates.projectServicePathTemplate.match(projectServiceName).project; + return this.pathTemplates.projectServicePathTemplate.match( + projectServiceName, + ).project; } /** @@ -2590,7 +3320,9 @@ export class NotificationChannelServiceClient { * @returns {string} A string representing the service. */ matchServiceFromProjectServiceName(projectServiceName: string) { - return this.pathTemplates.projectServicePathTemplate.match(projectServiceName).service; + return this.pathTemplates.projectServicePathTemplate.match( + projectServiceName, + ).service; } /** @@ -2601,12 +3333,18 @@ export class NotificationChannelServiceClient { * @param {string} service_level_objective * @returns {string} Resource name string. */ - projectServiceServiceLevelObjectivePath(project:string,service:string,serviceLevelObjective:string) { - return this.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.render({ - project: project, - service: service, - service_level_objective: serviceLevelObjective, - }); + projectServiceServiceLevelObjectivePath( + project: string, + service: string, + serviceLevelObjective: string, + ) { + return this.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.render( + { + project: project, + service: service, + service_level_objective: serviceLevelObjective, + }, + ); } /** @@ -2616,8 +3354,12 @@ export class NotificationChannelServiceClient { * A fully-qualified path representing project_service_service_level_objective resource. * @returns {string} A string representing the project. */ - matchProjectFromProjectServiceServiceLevelObjectiveName(projectServiceServiceLevelObjectiveName: string) { - return this.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match(projectServiceServiceLevelObjectiveName).project; + matchProjectFromProjectServiceServiceLevelObjectiveName( + projectServiceServiceLevelObjectiveName: string, + ) { + return this.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match( + projectServiceServiceLevelObjectiveName, + ).project; } /** @@ -2627,8 +3369,12 @@ export class NotificationChannelServiceClient { * A fully-qualified path representing project_service_service_level_objective resource. * @returns {string} A string representing the service. */ - matchServiceFromProjectServiceServiceLevelObjectiveName(projectServiceServiceLevelObjectiveName: string) { - return this.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match(projectServiceServiceLevelObjectiveName).service; + matchServiceFromProjectServiceServiceLevelObjectiveName( + projectServiceServiceLevelObjectiveName: string, + ) { + return this.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match( + projectServiceServiceLevelObjectiveName, + ).service; } /** @@ -2638,8 +3384,12 @@ export class NotificationChannelServiceClient { * A fully-qualified path representing project_service_service_level_objective resource. * @returns {string} A string representing the service_level_objective. */ - matchServiceLevelObjectiveFromProjectServiceServiceLevelObjectiveName(projectServiceServiceLevelObjectiveName: string) { - return this.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match(projectServiceServiceLevelObjectiveName).service_level_objective; + matchServiceLevelObjectiveFromProjectServiceServiceLevelObjectiveName( + projectServiceServiceLevelObjectiveName: string, + ) { + return this.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match( + projectServiceServiceLevelObjectiveName, + ).service_level_objective; } /** @@ -2649,7 +3399,7 @@ export class NotificationChannelServiceClient { * @param {string} uptime_check_config * @returns {string} Resource name string. */ - projectUptimeCheckConfigPath(project:string,uptimeCheckConfig:string) { + projectUptimeCheckConfigPath(project: string, uptimeCheckConfig: string) { return this.pathTemplates.projectUptimeCheckConfigPathTemplate.render({ project: project, uptime_check_config: uptimeCheckConfig, @@ -2663,8 +3413,12 @@ export class NotificationChannelServiceClient { * A fully-qualified path representing project_uptime_check_config resource. * @returns {string} A string representing the project. */ - matchProjectFromProjectUptimeCheckConfigName(projectUptimeCheckConfigName: string) { - return this.pathTemplates.projectUptimeCheckConfigPathTemplate.match(projectUptimeCheckConfigName).project; + matchProjectFromProjectUptimeCheckConfigName( + projectUptimeCheckConfigName: string, + ) { + return this.pathTemplates.projectUptimeCheckConfigPathTemplate.match( + projectUptimeCheckConfigName, + ).project; } /** @@ -2674,8 +3428,12 @@ export class NotificationChannelServiceClient { * A fully-qualified path representing project_uptime_check_config resource. * @returns {string} A string representing the uptime_check_config. */ - matchUptimeCheckConfigFromProjectUptimeCheckConfigName(projectUptimeCheckConfigName: string) { - return this.pathTemplates.projectUptimeCheckConfigPathTemplate.match(projectUptimeCheckConfigName).uptime_check_config; + matchUptimeCheckConfigFromProjectUptimeCheckConfigName( + projectUptimeCheckConfigName: string, + ) { + return this.pathTemplates.projectUptimeCheckConfigPathTemplate.match( + projectUptimeCheckConfigName, + ).uptime_check_config; } /** @@ -2686,7 +3444,7 @@ export class NotificationChannelServiceClient { */ close(): Promise { if (this.notificationChannelServiceStub && !this._terminated) { - return this.notificationChannelServiceStub.then(stub => { + return this.notificationChannelServiceStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -2694,4 +3452,4 @@ export class NotificationChannelServiceClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/core/generator/gapic-generator-typescript/baselines/monitoring-esm/esm/src/v3/service_monitoring_service_client.ts.baseline b/core/generator/gapic-generator-typescript/baselines/monitoring-esm/esm/src/v3/service_monitoring_service_client.ts.baseline index f0a2bf22c559..a86308d06de2 100644 --- a/core/generator/gapic-generator-typescript/baselines/monitoring-esm/esm/src/v3/service_monitoring_service_client.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/monitoring-esm/esm/src/v3/service_monitoring_service_client.ts.baseline @@ -18,15 +18,22 @@ /* global window */ import * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions, PaginationCallback, GaxCall} from 'google-gax'; -import {Transform} from 'stream'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + PaginationCallback, + GaxCall, +} from 'google-gax'; +import { Transform } from 'stream'; // @ts-ignore import type * as protos from '../../../protos/protos.js'; import * as service_monitoring_service_client_config from './service_monitoring_service_client_config.json'; import fs from 'fs'; import path from 'path'; -import {fileURLToPath} from 'url'; -import {getJSON} from '../json-helper.cjs'; +import { fileURLToPath } from 'url'; +import { getJSON } from '../json-helper.cjs'; // @ts-ignore const dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -36,15 +43,15 @@ const dirname = path.dirname(fileURLToPath(import.meta.url)); * This file defines retry strategy and timeouts for all API methods in this library. */ const gapicConfig = getJSON( - path.join(dirname, 'service_monitoring_service_client_config.json') + path.join(dirname, 'service_monitoring_service_client_config.json'), ); const jsonProtos = getJSON( - path.join(dirname, '..', '..', '..', 'protos/protos.json') + path.join(dirname, '..', '..', '..', 'protos/protos.json'), ); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; const version = getJSON( - path.join(dirname, '..', '..', '..', '..', 'package.json') + path.join(dirname, '..', '..', '..', '..', 'package.json'), ).version; /** @@ -62,7 +69,7 @@ export class ServiceMonitoringServiceClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('monitoring'); @@ -74,9 +81,9 @@ export class ServiceMonitoringServiceClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; - serviceMonitoringServiceStub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; + serviceMonitoringServiceStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of ServiceMonitoringServiceClient. @@ -118,21 +125,43 @@ export class ServiceMonitoringServiceClient { * const client = new ServiceMonitoringServiceClient({fallback: 'rest'}, gax); * ``` */ - constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { // Ensure that options include all the required fields. - const staticMembers = this.constructor as typeof ServiceMonitoringServiceClient; - if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { - throw new Error('Please set either universe_domain or universeDomain, but not both.'); + const staticMembers = this + .constructor as typeof ServiceMonitoringServiceClient; + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); } - const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; - this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; this._servicePath = 'monitoring.' + this._universeDomain; - const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; - const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. if (servicePath !== this._servicePath && !('scopes' in opts)) { @@ -154,7 +183,7 @@ export class ServiceMonitoringServiceClient { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; @@ -171,10 +200,7 @@ export class ServiceMonitoringServiceClient { const isEsm = true; const isEsmString = isEsm ? '-esm' : '-cjs'; // Determine the client header string. - const clientHeader = [ - `gax/${this._gaxModule.version}`, - `gapic/${version}`, - ]; + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/{process.versions.node}${isEsmString}`); } else { @@ -182,7 +208,7 @@ export class ServiceMonitoringServiceClient { } if (!opts.fallback) { clientHeader.push(`grpc/${this._gaxGrpc.grpcVersion}`); - } else if (opts.fallback === 'rest' ) { + } else if (opts.fallback === 'rest') { clientHeader.push(`rest/${this._gaxGrpc.grpcVersion}`); } if (opts.libName && opts.libVersion) { @@ -190,83 +216,92 @@ export class ServiceMonitoringServiceClient { } // Load the applicable protos. - this._protos = this._gaxGrpc.loadProtoJSON(jsonProtos as gax.protobuf.INamespace); + this._protos = this._gaxGrpc.loadProtoJSON( + jsonProtos as gax.protobuf.INamespace, + ); // This API contains "path templates"; forward-slash-separated // identifiers to uniquely identify resources within the API. // Create useful helper objects for these. this.pathTemplates = { folderAlertPolicyPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/alertPolicies/{alert_policy}' + 'folders/{folder}/alertPolicies/{alert_policy}', ), folderAlertPolicyConditionPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/alertPolicies/{alert_policy}/conditions/{condition}' + 'folders/{folder}/alertPolicies/{alert_policy}/conditions/{condition}', ), folderChannelDescriptorPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/notificationChannelDescriptors/{channel_descriptor}' + 'folders/{folder}/notificationChannelDescriptors/{channel_descriptor}', ), folderGroupPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/groups/{group}' + 'folders/{folder}/groups/{group}', ), folderNotificationChannelPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/notificationChannels/{notification_channel}' + 'folders/{folder}/notificationChannels/{notification_channel}', ), folderServicePathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/services/{service}' - ), - folderServiceServiceLevelObjectivePathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/services/{service}/serviceLevelObjectives/{service_level_objective}' + 'folders/{folder}/services/{service}', ), + folderServiceServiceLevelObjectivePathTemplate: + new this._gaxModule.PathTemplate( + 'folders/{folder}/services/{service}/serviceLevelObjectives/{service_level_objective}', + ), folderUptimeCheckConfigPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/uptimeCheckConfigs/{uptime_check_config}' + 'folders/{folder}/uptimeCheckConfigs/{uptime_check_config}', ), organizationAlertPolicyPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/alertPolicies/{alert_policy}' - ), - organizationAlertPolicyConditionPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/alertPolicies/{alert_policy}/conditions/{condition}' - ), - organizationChannelDescriptorPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/notificationChannelDescriptors/{channel_descriptor}' + 'organizations/{organization}/alertPolicies/{alert_policy}', ), + organizationAlertPolicyConditionPathTemplate: + new this._gaxModule.PathTemplate( + 'organizations/{organization}/alertPolicies/{alert_policy}/conditions/{condition}', + ), + organizationChannelDescriptorPathTemplate: + new this._gaxModule.PathTemplate( + 'organizations/{organization}/notificationChannelDescriptors/{channel_descriptor}', + ), organizationGroupPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/groups/{group}' - ), - organizationNotificationChannelPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/notificationChannels/{notification_channel}' + 'organizations/{organization}/groups/{group}', ), + organizationNotificationChannelPathTemplate: + new this._gaxModule.PathTemplate( + 'organizations/{organization}/notificationChannels/{notification_channel}', + ), organizationServicePathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/services/{service}' - ), - organizationServiceServiceLevelObjectivePathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/services/{service}/serviceLevelObjectives/{service_level_objective}' - ), - organizationUptimeCheckConfigPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/uptimeCheckConfigs/{uptime_check_config}' + 'organizations/{organization}/services/{service}', ), + organizationServiceServiceLevelObjectivePathTemplate: + new this._gaxModule.PathTemplate( + 'organizations/{organization}/services/{service}/serviceLevelObjectives/{service_level_objective}', + ), + organizationUptimeCheckConfigPathTemplate: + new this._gaxModule.PathTemplate( + 'organizations/{organization}/uptimeCheckConfigs/{uptime_check_config}', + ), projectAlertPolicyPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/alertPolicies/{alert_policy}' + 'projects/{project}/alertPolicies/{alert_policy}', ), projectAlertPolicyConditionPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/alertPolicies/{alert_policy}/conditions/{condition}' + 'projects/{project}/alertPolicies/{alert_policy}/conditions/{condition}', ), projectChannelDescriptorPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/notificationChannelDescriptors/{channel_descriptor}' + 'projects/{project}/notificationChannelDescriptors/{channel_descriptor}', ), projectGroupPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/groups/{group}' + 'projects/{project}/groups/{group}', ), projectNotificationChannelPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/notificationChannels/{notification_channel}' + 'projects/{project}/notificationChannels/{notification_channel}', ), projectServicePathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/services/{service}' - ), - projectServiceServiceLevelObjectivePathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/services/{service}/serviceLevelObjectives/{service_level_objective}' + 'projects/{project}/services/{service}', ), + projectServiceServiceLevelObjectivePathTemplate: + new this._gaxModule.PathTemplate( + 'projects/{project}/services/{service}/serviceLevelObjectives/{service_level_objective}', + ), projectUptimeCheckConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/uptimeCheckConfigs/{uptime_check_config}' + 'projects/{project}/uptimeCheckConfigs/{uptime_check_config}', ), }; @@ -274,16 +309,25 @@ export class ServiceMonitoringServiceClient { // (e.g. 50 results at a time, with tokens to get subsequent // pages). Denote the keys used for pagination and results. this.descriptors.page = { - listServices: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'services'), - listServiceLevelObjectives: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'serviceLevelObjectives') + listServices: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'services', + ), + listServiceLevelObjectives: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'serviceLevelObjectives', + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.monitoring.v3.ServiceMonitoringService', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.monitoring.v3.ServiceMonitoringService', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + { 'x-goog-api-client': clientHeader.join(' ') }, + ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -314,37 +358,51 @@ export class ServiceMonitoringServiceClient { // Put together the "service stub" for // google.monitoring.v3.ServiceMonitoringService. this.serviceMonitoringServiceStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.monitoring.v3.ServiceMonitoringService') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.monitoring.v3.ServiceMonitoringService', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.monitoring.v3.ServiceMonitoringService, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts, + this._providedCustomServicePath, + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const serviceMonitoringServiceStubMethods = - ['createService', 'getService', 'listServices', 'updateService', 'deleteService', 'createServiceLevelObjective', 'getServiceLevelObjective', 'listServiceLevelObjectives', 'updateServiceLevelObjective', 'deleteServiceLevelObjective']; + const serviceMonitoringServiceStubMethods = [ + 'createService', + 'getService', + 'listServices', + 'updateService', + 'deleteService', + 'createServiceLevelObjective', + 'getServiceLevelObjective', + 'listServiceLevelObjectives', + 'updateServiceLevelObjective', + 'deleteServiceLevelObjective', + ]; for (const methodName of serviceMonitoringServiceStubMethods) { const callPromise = this.serviceMonitoringServiceStub.then( - stub => (...args: Array<{}>) => { - if (this._terminated) { - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error|null|undefined) => () => { + (stub) => + (...args: Array<{}>) => { + if (this._terminated) { + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { throw err; - }); + }, + ); - const descriptor = - this.descriptors.page[methodName] || - undefined; + const descriptor = this.descriptors.page[methodName] || undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -359,8 +417,14 @@ export class ServiceMonitoringServiceClient { * @returns {string} The DNS address for this service. */ static get servicePath() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'monitoring.googleapis.com'; } @@ -372,8 +436,14 @@ export class ServiceMonitoringServiceClient { * @returns {string} The DNS address for this service. */ static get apiEndpoint() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'monitoring.googleapis.com'; } @@ -407,7 +477,7 @@ export class ServiceMonitoringServiceClient { return [ 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/monitoring', - 'https://www.googleapis.com/auth/monitoring.read' + 'https://www.googleapis.com/auth/monitoring.read', ]; } @@ -417,8 +487,9 @@ export class ServiceMonitoringServiceClient { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId(callback?: Callback): - Promise|void { + getProjectId( + callback?: Callback, + ): Promise | void { if (callback) { this.auth.getProjectId(callback); return; @@ -429,884 +500,1218 @@ export class ServiceMonitoringServiceClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Create a `Service`. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. Resource name of the parent workspace. - * Of the form `projects/{project_id}`. - * @param {string} request.serviceId - * Optional. The Service id to use for this Service. If omitted, an id will be - * generated instead. Must match the pattern [a-z0-9\-]+ - * @param {google.monitoring.v3.Service} request.service - * Required. The `Service` to create. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.monitoring.v3.Service|Service}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v3/service_monitoring_service.create_service.js - * region_tag:monitoring_v3_generated_ServiceMonitoringService_CreateService_async - */ + /** + * Create a `Service`. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Resource name of the parent workspace. + * Of the form `projects/{project_id}`. + * @param {string} request.serviceId + * Optional. The Service id to use for this Service. If omitted, an id will be + * generated instead. Must match the pattern [a-z0-9\-]+ + * @param {google.monitoring.v3.Service} request.service + * Required. The `Service` to create. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.monitoring.v3.Service|Service}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v3/service_monitoring_service.create_service.js + * region_tag:monitoring_v3_generated_ServiceMonitoringService_CreateService_async + */ createService( - request?: protos.google.monitoring.v3.ICreateServiceRequest, - options?: CallOptions): - Promise<[ - protos.google.monitoring.v3.IService, - protos.google.monitoring.v3.ICreateServiceRequest|undefined, {}|undefined - ]>; + request?: protos.google.monitoring.v3.ICreateServiceRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.monitoring.v3.IService, + protos.google.monitoring.v3.ICreateServiceRequest | undefined, + {} | undefined, + ] + >; createService( - request: protos.google.monitoring.v3.ICreateServiceRequest, - options: CallOptions, - callback: Callback< - protos.google.monitoring.v3.IService, - protos.google.monitoring.v3.ICreateServiceRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.ICreateServiceRequest, + options: CallOptions, + callback: Callback< + protos.google.monitoring.v3.IService, + protos.google.monitoring.v3.ICreateServiceRequest | null | undefined, + {} | null | undefined + >, + ): void; createService( - request: protos.google.monitoring.v3.ICreateServiceRequest, - callback: Callback< - protos.google.monitoring.v3.IService, - protos.google.monitoring.v3.ICreateServiceRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.ICreateServiceRequest, + callback: Callback< + protos.google.monitoring.v3.IService, + protos.google.monitoring.v3.ICreateServiceRequest | null | undefined, + {} | null | undefined + >, + ): void; createService( - request?: protos.google.monitoring.v3.ICreateServiceRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.monitoring.v3.ICreateServiceRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.monitoring.v3.IService, - protos.google.monitoring.v3.ICreateServiceRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.monitoring.v3.IService, - protos.google.monitoring.v3.ICreateServiceRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.monitoring.v3.IService, - protos.google.monitoring.v3.ICreateServiceRequest|undefined, {}|undefined - ]>|void { + protos.google.monitoring.v3.ICreateServiceRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.monitoring.v3.IService, + protos.google.monitoring.v3.ICreateServiceRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.monitoring.v3.IService, + protos.google.monitoring.v3.ICreateServiceRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('createService request %j', request); - const wrappedCallback: Callback< - protos.google.monitoring.v3.IService, - protos.google.monitoring.v3.ICreateServiceRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.monitoring.v3.IService, + protos.google.monitoring.v3.ICreateServiceRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createService response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.createService(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.monitoring.v3.IService, - protos.google.monitoring.v3.ICreateServiceRequest|undefined, {}|undefined - ]) => { - this._log.info('createService response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createService(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.monitoring.v3.IService, + protos.google.monitoring.v3.ICreateServiceRequest | undefined, + {} | undefined, + ]) => { + this._log.info('createService response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Get the named `Service`. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. Resource name of the `Service`. - * Of the form `projects/{project_id}/services/{service_id}`. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.monitoring.v3.Service|Service}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v3/service_monitoring_service.get_service.js - * region_tag:monitoring_v3_generated_ServiceMonitoringService_GetService_async - */ + /** + * Get the named `Service`. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Resource name of the `Service`. + * Of the form `projects/{project_id}/services/{service_id}`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.monitoring.v3.Service|Service}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v3/service_monitoring_service.get_service.js + * region_tag:monitoring_v3_generated_ServiceMonitoringService_GetService_async + */ getService( - request?: protos.google.monitoring.v3.IGetServiceRequest, - options?: CallOptions): - Promise<[ - protos.google.monitoring.v3.IService, - protos.google.monitoring.v3.IGetServiceRequest|undefined, {}|undefined - ]>; + request?: protos.google.monitoring.v3.IGetServiceRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.monitoring.v3.IService, + protos.google.monitoring.v3.IGetServiceRequest | undefined, + {} | undefined, + ] + >; getService( - request: protos.google.monitoring.v3.IGetServiceRequest, - options: CallOptions, - callback: Callback< - protos.google.monitoring.v3.IService, - protos.google.monitoring.v3.IGetServiceRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.IGetServiceRequest, + options: CallOptions, + callback: Callback< + protos.google.monitoring.v3.IService, + protos.google.monitoring.v3.IGetServiceRequest | null | undefined, + {} | null | undefined + >, + ): void; getService( - request: protos.google.monitoring.v3.IGetServiceRequest, - callback: Callback< - protos.google.monitoring.v3.IService, - protos.google.monitoring.v3.IGetServiceRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.IGetServiceRequest, + callback: Callback< + protos.google.monitoring.v3.IService, + protos.google.monitoring.v3.IGetServiceRequest | null | undefined, + {} | null | undefined + >, + ): void; getService( - request?: protos.google.monitoring.v3.IGetServiceRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.monitoring.v3.IService, - protos.google.monitoring.v3.IGetServiceRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.monitoring.v3.IGetServiceRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.monitoring.v3.IService, - protos.google.monitoring.v3.IGetServiceRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.monitoring.v3.IService, - protos.google.monitoring.v3.IGetServiceRequest|undefined, {}|undefined - ]>|void { + protos.google.monitoring.v3.IGetServiceRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.monitoring.v3.IService, + protos.google.monitoring.v3.IGetServiceRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.monitoring.v3.IService, + protos.google.monitoring.v3.IGetServiceRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getService request %j', request); - const wrappedCallback: Callback< - protos.google.monitoring.v3.IService, - protos.google.monitoring.v3.IGetServiceRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.monitoring.v3.IService, + protos.google.monitoring.v3.IGetServiceRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getService response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.getService(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.monitoring.v3.IService, - protos.google.monitoring.v3.IGetServiceRequest|undefined, {}|undefined - ]) => { - this._log.info('getService response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getService(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.monitoring.v3.IService, + protos.google.monitoring.v3.IGetServiceRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getService response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Update this `Service`. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.monitoring.v3.Service} request.service - * Required. The `Service` to draw updates from. - * The given `name` specifies the resource to update. - * @param {google.protobuf.FieldMask} request.updateMask - * A set of field paths defining which fields to use for the update. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.monitoring.v3.Service|Service}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v3/service_monitoring_service.update_service.js - * region_tag:monitoring_v3_generated_ServiceMonitoringService_UpdateService_async - */ + /** + * Update this `Service`. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.monitoring.v3.Service} request.service + * Required. The `Service` to draw updates from. + * The given `name` specifies the resource to update. + * @param {google.protobuf.FieldMask} request.updateMask + * A set of field paths defining which fields to use for the update. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.monitoring.v3.Service|Service}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v3/service_monitoring_service.update_service.js + * region_tag:monitoring_v3_generated_ServiceMonitoringService_UpdateService_async + */ updateService( - request?: protos.google.monitoring.v3.IUpdateServiceRequest, - options?: CallOptions): - Promise<[ - protos.google.monitoring.v3.IService, - protos.google.monitoring.v3.IUpdateServiceRequest|undefined, {}|undefined - ]>; + request?: protos.google.monitoring.v3.IUpdateServiceRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.monitoring.v3.IService, + protos.google.monitoring.v3.IUpdateServiceRequest | undefined, + {} | undefined, + ] + >; updateService( - request: protos.google.monitoring.v3.IUpdateServiceRequest, - options: CallOptions, - callback: Callback< - protos.google.monitoring.v3.IService, - protos.google.monitoring.v3.IUpdateServiceRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.IUpdateServiceRequest, + options: CallOptions, + callback: Callback< + protos.google.monitoring.v3.IService, + protos.google.monitoring.v3.IUpdateServiceRequest | null | undefined, + {} | null | undefined + >, + ): void; updateService( - request: protos.google.monitoring.v3.IUpdateServiceRequest, - callback: Callback< - protos.google.monitoring.v3.IService, - protos.google.monitoring.v3.IUpdateServiceRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.IUpdateServiceRequest, + callback: Callback< + protos.google.monitoring.v3.IService, + protos.google.monitoring.v3.IUpdateServiceRequest | null | undefined, + {} | null | undefined + >, + ): void; updateService( - request?: protos.google.monitoring.v3.IUpdateServiceRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.monitoring.v3.IService, - protos.google.monitoring.v3.IUpdateServiceRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.monitoring.v3.IUpdateServiceRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.monitoring.v3.IService, - protos.google.monitoring.v3.IUpdateServiceRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.monitoring.v3.IService, - protos.google.monitoring.v3.IUpdateServiceRequest|undefined, {}|undefined - ]>|void { + protos.google.monitoring.v3.IUpdateServiceRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.monitoring.v3.IService, + protos.google.monitoring.v3.IUpdateServiceRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.monitoring.v3.IService, + protos.google.monitoring.v3.IUpdateServiceRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'service.name': request.service!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'service.name': request.service!.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateService request %j', request); - const wrappedCallback: Callback< - protos.google.monitoring.v3.IService, - protos.google.monitoring.v3.IUpdateServiceRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.monitoring.v3.IService, + protos.google.monitoring.v3.IUpdateServiceRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateService response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.updateService(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.monitoring.v3.IService, - protos.google.monitoring.v3.IUpdateServiceRequest|undefined, {}|undefined - ]) => { - this._log.info('updateService response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateService(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.monitoring.v3.IService, + protos.google.monitoring.v3.IUpdateServiceRequest | undefined, + {} | undefined, + ]) => { + this._log.info('updateService response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Soft delete this `Service`. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. Resource name of the `Service` to delete. - * Of the form `projects/{project_id}/services/{service_id}`. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v3/service_monitoring_service.delete_service.js - * region_tag:monitoring_v3_generated_ServiceMonitoringService_DeleteService_async - */ + /** + * Soft delete this `Service`. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Resource name of the `Service` to delete. + * Of the form `projects/{project_id}/services/{service_id}`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v3/service_monitoring_service.delete_service.js + * region_tag:monitoring_v3_generated_ServiceMonitoringService_DeleteService_async + */ deleteService( - request?: protos.google.monitoring.v3.IDeleteServiceRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.IDeleteServiceRequest|undefined, {}|undefined - ]>; + request?: protos.google.monitoring.v3.IDeleteServiceRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.monitoring.v3.IDeleteServiceRequest | undefined, + {} | undefined, + ] + >; deleteService( - request: protos.google.monitoring.v3.IDeleteServiceRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.IDeleteServiceRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.IDeleteServiceRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.monitoring.v3.IDeleteServiceRequest | null | undefined, + {} | null | undefined + >, + ): void; deleteService( - request: protos.google.monitoring.v3.IDeleteServiceRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.IDeleteServiceRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.IDeleteServiceRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.monitoring.v3.IDeleteServiceRequest | null | undefined, + {} | null | undefined + >, + ): void; deleteService( - request?: protos.google.monitoring.v3.IDeleteServiceRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.monitoring.v3.IDeleteServiceRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.IDeleteServiceRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.IDeleteServiceRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.IDeleteServiceRequest|undefined, {}|undefined - ]>|void { + protos.google.monitoring.v3.IDeleteServiceRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + protos.google.monitoring.v3.IDeleteServiceRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.monitoring.v3.IDeleteServiceRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('deleteService request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.IDeleteServiceRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + protos.google.monitoring.v3.IDeleteServiceRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteService response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.deleteService(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.IDeleteServiceRequest|undefined, {}|undefined - ]) => { - this._log.info('deleteService response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteService(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.monitoring.v3.IDeleteServiceRequest | undefined, + {} | undefined, + ]) => { + this._log.info('deleteService response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Create a `ServiceLevelObjective` for the given `Service`. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. Resource name of the parent `Service`. - * Of the form `projects/{project_id}/services/{service_id}`. - * @param {string} request.serviceLevelObjectiveId - * Optional. The ServiceLevelObjective id to use for this - * ServiceLevelObjective. If omitted, an id will be generated instead. Must - * match the pattern [a-z0-9\-]+ - * @param {google.monitoring.v3.ServiceLevelObjective} request.serviceLevelObjective - * Required. The `ServiceLevelObjective` to create. - * The provided `name` will be respected if no `ServiceLevelObjective` exists - * with this name. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.monitoring.v3.ServiceLevelObjective|ServiceLevelObjective}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v3/service_monitoring_service.create_service_level_objective.js - * region_tag:monitoring_v3_generated_ServiceMonitoringService_CreateServiceLevelObjective_async - */ + /** + * Create a `ServiceLevelObjective` for the given `Service`. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Resource name of the parent `Service`. + * Of the form `projects/{project_id}/services/{service_id}`. + * @param {string} request.serviceLevelObjectiveId + * Optional. The ServiceLevelObjective id to use for this + * ServiceLevelObjective. If omitted, an id will be generated instead. Must + * match the pattern [a-z0-9\-]+ + * @param {google.monitoring.v3.ServiceLevelObjective} request.serviceLevelObjective + * Required. The `ServiceLevelObjective` to create. + * The provided `name` will be respected if no `ServiceLevelObjective` exists + * with this name. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.monitoring.v3.ServiceLevelObjective|ServiceLevelObjective}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v3/service_monitoring_service.create_service_level_objective.js + * region_tag:monitoring_v3_generated_ServiceMonitoringService_CreateServiceLevelObjective_async + */ createServiceLevelObjective( - request?: protos.google.monitoring.v3.ICreateServiceLevelObjectiveRequest, - options?: CallOptions): - Promise<[ - protos.google.monitoring.v3.IServiceLevelObjective, - protos.google.monitoring.v3.ICreateServiceLevelObjectiveRequest|undefined, {}|undefined - ]>; + request?: protos.google.monitoring.v3.ICreateServiceLevelObjectiveRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.monitoring.v3.IServiceLevelObjective, + ( + | protos.google.monitoring.v3.ICreateServiceLevelObjectiveRequest + | undefined + ), + {} | undefined, + ] + >; createServiceLevelObjective( - request: protos.google.monitoring.v3.ICreateServiceLevelObjectiveRequest, - options: CallOptions, - callback: Callback< - protos.google.monitoring.v3.IServiceLevelObjective, - protos.google.monitoring.v3.ICreateServiceLevelObjectiveRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.ICreateServiceLevelObjectiveRequest, + options: CallOptions, + callback: Callback< + protos.google.monitoring.v3.IServiceLevelObjective, + | protos.google.monitoring.v3.ICreateServiceLevelObjectiveRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createServiceLevelObjective( - request: protos.google.monitoring.v3.ICreateServiceLevelObjectiveRequest, - callback: Callback< - protos.google.monitoring.v3.IServiceLevelObjective, - protos.google.monitoring.v3.ICreateServiceLevelObjectiveRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.ICreateServiceLevelObjectiveRequest, + callback: Callback< + protos.google.monitoring.v3.IServiceLevelObjective, + | protos.google.monitoring.v3.ICreateServiceLevelObjectiveRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createServiceLevelObjective( - request?: protos.google.monitoring.v3.ICreateServiceLevelObjectiveRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.monitoring.v3.ICreateServiceLevelObjectiveRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.monitoring.v3.IServiceLevelObjective, - protos.google.monitoring.v3.ICreateServiceLevelObjectiveRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.monitoring.v3.IServiceLevelObjective, - protos.google.monitoring.v3.ICreateServiceLevelObjectiveRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.monitoring.v3.IServiceLevelObjective, - protos.google.monitoring.v3.ICreateServiceLevelObjectiveRequest|undefined, {}|undefined - ]>|void { + | protos.google.monitoring.v3.ICreateServiceLevelObjectiveRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.monitoring.v3.IServiceLevelObjective, + | protos.google.monitoring.v3.ICreateServiceLevelObjectiveRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.monitoring.v3.IServiceLevelObjective, + ( + | protos.google.monitoring.v3.ICreateServiceLevelObjectiveRequest + | undefined + ), + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('createServiceLevelObjective request %j', request); - const wrappedCallback: Callback< - protos.google.monitoring.v3.IServiceLevelObjective, - protos.google.monitoring.v3.ICreateServiceLevelObjectiveRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.monitoring.v3.IServiceLevelObjective, + | protos.google.monitoring.v3.ICreateServiceLevelObjectiveRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createServiceLevelObjective response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.createServiceLevelObjective(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.monitoring.v3.IServiceLevelObjective, - protos.google.monitoring.v3.ICreateServiceLevelObjectiveRequest|undefined, {}|undefined - ]) => { - this._log.info('createServiceLevelObjective response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createServiceLevelObjective(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.monitoring.v3.IServiceLevelObjective, + ( + | protos.google.monitoring.v3.ICreateServiceLevelObjectiveRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('createServiceLevelObjective response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Get a `ServiceLevelObjective` by name. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. Resource name of the `ServiceLevelObjective` to get. - * Of the form - * `projects/{project_id}/services/{service_id}/serviceLevelObjectives/{slo_name}`. - * @param {google.monitoring.v3.ServiceLevelObjective.View} request.view - * View of the `ServiceLevelObjective` to return. If `DEFAULT`, return the - * `ServiceLevelObjective` as originally defined. If `EXPLICIT` and the - * `ServiceLevelObjective` is defined in terms of a `BasicSli`, replace the - * `BasicSli` with a `RequestBasedSli` spelling out how the SLI is computed. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.monitoring.v3.ServiceLevelObjective|ServiceLevelObjective}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v3/service_monitoring_service.get_service_level_objective.js - * region_tag:monitoring_v3_generated_ServiceMonitoringService_GetServiceLevelObjective_async - */ + /** + * Get a `ServiceLevelObjective` by name. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Resource name of the `ServiceLevelObjective` to get. + * Of the form + * `projects/{project_id}/services/{service_id}/serviceLevelObjectives/{slo_name}`. + * @param {google.monitoring.v3.ServiceLevelObjective.View} request.view + * View of the `ServiceLevelObjective` to return. If `DEFAULT`, return the + * `ServiceLevelObjective` as originally defined. If `EXPLICIT` and the + * `ServiceLevelObjective` is defined in terms of a `BasicSli`, replace the + * `BasicSli` with a `RequestBasedSli` spelling out how the SLI is computed. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.monitoring.v3.ServiceLevelObjective|ServiceLevelObjective}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v3/service_monitoring_service.get_service_level_objective.js + * region_tag:monitoring_v3_generated_ServiceMonitoringService_GetServiceLevelObjective_async + */ getServiceLevelObjective( - request?: protos.google.monitoring.v3.IGetServiceLevelObjectiveRequest, - options?: CallOptions): - Promise<[ - protos.google.monitoring.v3.IServiceLevelObjective, - protos.google.monitoring.v3.IGetServiceLevelObjectiveRequest|undefined, {}|undefined - ]>; + request?: protos.google.monitoring.v3.IGetServiceLevelObjectiveRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.monitoring.v3.IServiceLevelObjective, + protos.google.monitoring.v3.IGetServiceLevelObjectiveRequest | undefined, + {} | undefined, + ] + >; getServiceLevelObjective( - request: protos.google.monitoring.v3.IGetServiceLevelObjectiveRequest, - options: CallOptions, - callback: Callback< - protos.google.monitoring.v3.IServiceLevelObjective, - protos.google.monitoring.v3.IGetServiceLevelObjectiveRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.IGetServiceLevelObjectiveRequest, + options: CallOptions, + callback: Callback< + protos.google.monitoring.v3.IServiceLevelObjective, + | protos.google.monitoring.v3.IGetServiceLevelObjectiveRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getServiceLevelObjective( - request: protos.google.monitoring.v3.IGetServiceLevelObjectiveRequest, - callback: Callback< - protos.google.monitoring.v3.IServiceLevelObjective, - protos.google.monitoring.v3.IGetServiceLevelObjectiveRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.IGetServiceLevelObjectiveRequest, + callback: Callback< + protos.google.monitoring.v3.IServiceLevelObjective, + | protos.google.monitoring.v3.IGetServiceLevelObjectiveRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getServiceLevelObjective( - request?: protos.google.monitoring.v3.IGetServiceLevelObjectiveRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.monitoring.v3.IServiceLevelObjective, - protos.google.monitoring.v3.IGetServiceLevelObjectiveRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.monitoring.v3.IGetServiceLevelObjectiveRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.monitoring.v3.IServiceLevelObjective, - protos.google.monitoring.v3.IGetServiceLevelObjectiveRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.monitoring.v3.IServiceLevelObjective, - protos.google.monitoring.v3.IGetServiceLevelObjectiveRequest|undefined, {}|undefined - ]>|void { + | protos.google.monitoring.v3.IGetServiceLevelObjectiveRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.monitoring.v3.IServiceLevelObjective, + | protos.google.monitoring.v3.IGetServiceLevelObjectiveRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.monitoring.v3.IServiceLevelObjective, + protos.google.monitoring.v3.IGetServiceLevelObjectiveRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getServiceLevelObjective request %j', request); - const wrappedCallback: Callback< - protos.google.monitoring.v3.IServiceLevelObjective, - protos.google.monitoring.v3.IGetServiceLevelObjectiveRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.monitoring.v3.IServiceLevelObjective, + | protos.google.monitoring.v3.IGetServiceLevelObjectiveRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getServiceLevelObjective response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.getServiceLevelObjective(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.monitoring.v3.IServiceLevelObjective, - protos.google.monitoring.v3.IGetServiceLevelObjectiveRequest|undefined, {}|undefined - ]) => { - this._log.info('getServiceLevelObjective response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getServiceLevelObjective(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.monitoring.v3.IServiceLevelObjective, + ( + | protos.google.monitoring.v3.IGetServiceLevelObjectiveRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('getServiceLevelObjective response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Update the given `ServiceLevelObjective`. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.monitoring.v3.ServiceLevelObjective} request.serviceLevelObjective - * Required. The `ServiceLevelObjective` to draw updates from. - * The given `name` specifies the resource to update. - * @param {google.protobuf.FieldMask} request.updateMask - * A set of field paths defining which fields to use for the update. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.monitoring.v3.ServiceLevelObjective|ServiceLevelObjective}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v3/service_monitoring_service.update_service_level_objective.js - * region_tag:monitoring_v3_generated_ServiceMonitoringService_UpdateServiceLevelObjective_async - */ + /** + * Update the given `ServiceLevelObjective`. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.monitoring.v3.ServiceLevelObjective} request.serviceLevelObjective + * Required. The `ServiceLevelObjective` to draw updates from. + * The given `name` specifies the resource to update. + * @param {google.protobuf.FieldMask} request.updateMask + * A set of field paths defining which fields to use for the update. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.monitoring.v3.ServiceLevelObjective|ServiceLevelObjective}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v3/service_monitoring_service.update_service_level_objective.js + * region_tag:monitoring_v3_generated_ServiceMonitoringService_UpdateServiceLevelObjective_async + */ updateServiceLevelObjective( - request?: protos.google.monitoring.v3.IUpdateServiceLevelObjectiveRequest, - options?: CallOptions): - Promise<[ - protos.google.monitoring.v3.IServiceLevelObjective, - protos.google.monitoring.v3.IUpdateServiceLevelObjectiveRequest|undefined, {}|undefined - ]>; + request?: protos.google.monitoring.v3.IUpdateServiceLevelObjectiveRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.monitoring.v3.IServiceLevelObjective, + ( + | protos.google.monitoring.v3.IUpdateServiceLevelObjectiveRequest + | undefined + ), + {} | undefined, + ] + >; updateServiceLevelObjective( - request: protos.google.monitoring.v3.IUpdateServiceLevelObjectiveRequest, - options: CallOptions, - callback: Callback< - protos.google.monitoring.v3.IServiceLevelObjective, - protos.google.monitoring.v3.IUpdateServiceLevelObjectiveRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.IUpdateServiceLevelObjectiveRequest, + options: CallOptions, + callback: Callback< + protos.google.monitoring.v3.IServiceLevelObjective, + | protos.google.monitoring.v3.IUpdateServiceLevelObjectiveRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateServiceLevelObjective( - request: protos.google.monitoring.v3.IUpdateServiceLevelObjectiveRequest, - callback: Callback< - protos.google.monitoring.v3.IServiceLevelObjective, - protos.google.monitoring.v3.IUpdateServiceLevelObjectiveRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.IUpdateServiceLevelObjectiveRequest, + callback: Callback< + protos.google.monitoring.v3.IServiceLevelObjective, + | protos.google.monitoring.v3.IUpdateServiceLevelObjectiveRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateServiceLevelObjective( - request?: protos.google.monitoring.v3.IUpdateServiceLevelObjectiveRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.monitoring.v3.IServiceLevelObjective, - protos.google.monitoring.v3.IUpdateServiceLevelObjectiveRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.monitoring.v3.IUpdateServiceLevelObjectiveRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.monitoring.v3.IServiceLevelObjective, - protos.google.monitoring.v3.IUpdateServiceLevelObjectiveRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.monitoring.v3.IServiceLevelObjective, - protos.google.monitoring.v3.IUpdateServiceLevelObjectiveRequest|undefined, {}|undefined - ]>|void { + | protos.google.monitoring.v3.IUpdateServiceLevelObjectiveRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.monitoring.v3.IServiceLevelObjective, + | protos.google.monitoring.v3.IUpdateServiceLevelObjectiveRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.monitoring.v3.IServiceLevelObjective, + ( + | protos.google.monitoring.v3.IUpdateServiceLevelObjectiveRequest + | undefined + ), + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'service_level_objective.name': request.serviceLevelObjective!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'service_level_objective.name': + request.serviceLevelObjective!.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateServiceLevelObjective request %j', request); - const wrappedCallback: Callback< - protos.google.monitoring.v3.IServiceLevelObjective, - protos.google.monitoring.v3.IUpdateServiceLevelObjectiveRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.monitoring.v3.IServiceLevelObjective, + | protos.google.monitoring.v3.IUpdateServiceLevelObjectiveRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateServiceLevelObjective response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.updateServiceLevelObjective(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.monitoring.v3.IServiceLevelObjective, - protos.google.monitoring.v3.IUpdateServiceLevelObjectiveRequest|undefined, {}|undefined - ]) => { - this._log.info('updateServiceLevelObjective response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateServiceLevelObjective(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.monitoring.v3.IServiceLevelObjective, + ( + | protos.google.monitoring.v3.IUpdateServiceLevelObjectiveRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('updateServiceLevelObjective response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Delete the given `ServiceLevelObjective`. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. Resource name of the `ServiceLevelObjective` to delete. - * Of the form - * `projects/{project_id}/services/{service_id}/serviceLevelObjectives/{slo_name}`. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v3/service_monitoring_service.delete_service_level_objective.js - * region_tag:monitoring_v3_generated_ServiceMonitoringService_DeleteServiceLevelObjective_async - */ + /** + * Delete the given `ServiceLevelObjective`. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Resource name of the `ServiceLevelObjective` to delete. + * Of the form + * `projects/{project_id}/services/{service_id}/serviceLevelObjectives/{slo_name}`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v3/service_monitoring_service.delete_service_level_objective.js + * region_tag:monitoring_v3_generated_ServiceMonitoringService_DeleteServiceLevelObjective_async + */ deleteServiceLevelObjective( - request?: protos.google.monitoring.v3.IDeleteServiceLevelObjectiveRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.IDeleteServiceLevelObjectiveRequest|undefined, {}|undefined - ]>; + request?: protos.google.monitoring.v3.IDeleteServiceLevelObjectiveRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.monitoring.v3.IDeleteServiceLevelObjectiveRequest + | undefined + ), + {} | undefined, + ] + >; deleteServiceLevelObjective( - request: protos.google.monitoring.v3.IDeleteServiceLevelObjectiveRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.IDeleteServiceLevelObjectiveRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.IDeleteServiceLevelObjectiveRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.monitoring.v3.IDeleteServiceLevelObjectiveRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteServiceLevelObjective( - request: protos.google.monitoring.v3.IDeleteServiceLevelObjectiveRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.IDeleteServiceLevelObjectiveRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.IDeleteServiceLevelObjectiveRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.monitoring.v3.IDeleteServiceLevelObjectiveRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteServiceLevelObjective( - request?: protos.google.monitoring.v3.IDeleteServiceLevelObjectiveRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.IDeleteServiceLevelObjectiveRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.monitoring.v3.IDeleteServiceLevelObjectiveRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.IDeleteServiceLevelObjectiveRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.IDeleteServiceLevelObjectiveRequest|undefined, {}|undefined - ]>|void { + | protos.google.monitoring.v3.IDeleteServiceLevelObjectiveRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + | protos.google.monitoring.v3.IDeleteServiceLevelObjectiveRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.monitoring.v3.IDeleteServiceLevelObjectiveRequest + | undefined + ), + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('deleteServiceLevelObjective request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.IDeleteServiceLevelObjectiveRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.monitoring.v3.IDeleteServiceLevelObjectiveRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteServiceLevelObjective response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.deleteServiceLevelObjective(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.IDeleteServiceLevelObjectiveRequest|undefined, {}|undefined - ]) => { - this._log.info('deleteServiceLevelObjective response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteServiceLevelObjective(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + ( + | protos.google.monitoring.v3.IDeleteServiceLevelObjectiveRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('deleteServiceLevelObjective response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } - /** - * List `Service`s for this workspace. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. Resource name of the parent `Workspace`. - * Of the form `projects/{project_id}`. - * @param {string} request.filter - * A filter specifying what `Service`s to return. The filter currently - * supports the following fields: - * - * - `identifier_case` - * - `app_engine.module_id` - * - `cloud_endpoints.service` - * - `cluster_istio.location` - * - `cluster_istio.cluster_name` - * - `cluster_istio.service_namespace` - * - `cluster_istio.service_name` - * - * `identifier_case` refers to which option in the identifier oneof is - * populated. For example, the filter `identifier_case = "CUSTOM"` would match - * all services with a value for the `custom` field. Valid options are - * "CUSTOM", "APP_ENGINE", "CLOUD_ENDPOINTS", and "CLUSTER_ISTIO". - * @param {number} request.pageSize - * A non-negative number that is the maximum number of results to return. - * When 0, use default page size. - * @param {string} request.pageToken - * If this field is not empty then it must contain the `nextPageToken` value - * returned by a previous call to this method. Using this field causes the - * method to return additional results from the previous method call. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.monitoring.v3.Service|Service}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `listServicesAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * List `Service`s for this workspace. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Resource name of the parent `Workspace`. + * Of the form `projects/{project_id}`. + * @param {string} request.filter + * A filter specifying what `Service`s to return. The filter currently + * supports the following fields: + * + * - `identifier_case` + * - `app_engine.module_id` + * - `cloud_endpoints.service` + * - `cluster_istio.location` + * - `cluster_istio.cluster_name` + * - `cluster_istio.service_namespace` + * - `cluster_istio.service_name` + * + * `identifier_case` refers to which option in the identifier oneof is + * populated. For example, the filter `identifier_case = "CUSTOM"` would match + * all services with a value for the `custom` field. Valid options are + * "CUSTOM", "APP_ENGINE", "CLOUD_ENDPOINTS", and "CLUSTER_ISTIO". + * @param {number} request.pageSize + * A non-negative number that is the maximum number of results to return. + * When 0, use default page size. + * @param {string} request.pageToken + * If this field is not empty then it must contain the `nextPageToken` value + * returned by a previous call to this method. Using this field causes the + * method to return additional results from the previous method call. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.monitoring.v3.Service|Service}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listServicesAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listServices( - request?: protos.google.monitoring.v3.IListServicesRequest, - options?: CallOptions): - Promise<[ - protos.google.monitoring.v3.IService[], - protos.google.monitoring.v3.IListServicesRequest|null, - protos.google.monitoring.v3.IListServicesResponse - ]>; + request?: protos.google.monitoring.v3.IListServicesRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.monitoring.v3.IService[], + protos.google.monitoring.v3.IListServicesRequest | null, + protos.google.monitoring.v3.IListServicesResponse, + ] + >; listServices( - request: protos.google.monitoring.v3.IListServicesRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.monitoring.v3.IListServicesRequest, - protos.google.monitoring.v3.IListServicesResponse|null|undefined, - protos.google.monitoring.v3.IService>): void; + request: protos.google.monitoring.v3.IListServicesRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.monitoring.v3.IListServicesRequest, + protos.google.monitoring.v3.IListServicesResponse | null | undefined, + protos.google.monitoring.v3.IService + >, + ): void; listServices( - request: protos.google.monitoring.v3.IListServicesRequest, - callback: PaginationCallback< - protos.google.monitoring.v3.IListServicesRequest, - protos.google.monitoring.v3.IListServicesResponse|null|undefined, - protos.google.monitoring.v3.IService>): void; + request: protos.google.monitoring.v3.IListServicesRequest, + callback: PaginationCallback< + protos.google.monitoring.v3.IListServicesRequest, + protos.google.monitoring.v3.IListServicesResponse | null | undefined, + protos.google.monitoring.v3.IService + >, + ): void; listServices( - request?: protos.google.monitoring.v3.IListServicesRequest, - optionsOrCallback?: CallOptions|PaginationCallback< - protos.google.monitoring.v3.IListServicesRequest, - protos.google.monitoring.v3.IListServicesResponse|null|undefined, - protos.google.monitoring.v3.IService>, - callback?: PaginationCallback< + request?: protos.google.monitoring.v3.IListServicesRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.monitoring.v3.IListServicesRequest, - protos.google.monitoring.v3.IListServicesResponse|null|undefined, - protos.google.monitoring.v3.IService>): - Promise<[ - protos.google.monitoring.v3.IService[], - protos.google.monitoring.v3.IListServicesRequest|null, - protos.google.monitoring.v3.IListServicesResponse - ]>|void { + protos.google.monitoring.v3.IListServicesResponse | null | undefined, + protos.google.monitoring.v3.IService + >, + callback?: PaginationCallback< + protos.google.monitoring.v3.IListServicesRequest, + protos.google.monitoring.v3.IListServicesResponse | null | undefined, + protos.google.monitoring.v3.IService + >, + ): Promise< + [ + protos.google.monitoring.v3.IService[], + protos.google.monitoring.v3.IListServicesRequest | null, + protos.google.monitoring.v3.IListServicesResponse, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.monitoring.v3.IListServicesRequest, - protos.google.monitoring.v3.IListServicesResponse|null|undefined, - protos.google.monitoring.v3.IService>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.monitoring.v3.IListServicesRequest, + protos.google.monitoring.v3.IListServicesResponse | null | undefined, + protos.google.monitoring.v3.IService + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listServices values %j', values); callback!(error, values, nextPageRequest, rawResponse); @@ -1315,240 +1720,269 @@ export class ServiceMonitoringServiceClient { this._log.info('listServices request %j', request); return this.innerApiCalls .listServices(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.monitoring.v3.IService[], - protos.google.monitoring.v3.IListServicesRequest|null, - protos.google.monitoring.v3.IListServicesResponse - ]) => { - this._log.info('listServices values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.monitoring.v3.IService[], + protos.google.monitoring.v3.IListServicesRequest | null, + protos.google.monitoring.v3.IListServicesResponse, + ]) => { + this._log.info('listServices values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listServices`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. Resource name of the parent `Workspace`. - * Of the form `projects/{project_id}`. - * @param {string} request.filter - * A filter specifying what `Service`s to return. The filter currently - * supports the following fields: - * - * - `identifier_case` - * - `app_engine.module_id` - * - `cloud_endpoints.service` - * - `cluster_istio.location` - * - `cluster_istio.cluster_name` - * - `cluster_istio.service_namespace` - * - `cluster_istio.service_name` - * - * `identifier_case` refers to which option in the identifier oneof is - * populated. For example, the filter `identifier_case = "CUSTOM"` would match - * all services with a value for the `custom` field. Valid options are - * "CUSTOM", "APP_ENGINE", "CLOUD_ENDPOINTS", and "CLUSTER_ISTIO". - * @param {number} request.pageSize - * A non-negative number that is the maximum number of results to return. - * When 0, use default page size. - * @param {string} request.pageToken - * If this field is not empty then it must contain the `nextPageToken` value - * returned by a previous call to this method. Using this field causes the - * method to return additional results from the previous method call. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.monitoring.v3.Service|Service} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `listServicesAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `listServices`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Resource name of the parent `Workspace`. + * Of the form `projects/{project_id}`. + * @param {string} request.filter + * A filter specifying what `Service`s to return. The filter currently + * supports the following fields: + * + * - `identifier_case` + * - `app_engine.module_id` + * - `cloud_endpoints.service` + * - `cluster_istio.location` + * - `cluster_istio.cluster_name` + * - `cluster_istio.service_namespace` + * - `cluster_istio.service_name` + * + * `identifier_case` refers to which option in the identifier oneof is + * populated. For example, the filter `identifier_case = "CUSTOM"` would match + * all services with a value for the `custom` field. Valid options are + * "CUSTOM", "APP_ENGINE", "CLOUD_ENDPOINTS", and "CLUSTER_ISTIO". + * @param {number} request.pageSize + * A non-negative number that is the maximum number of results to return. + * When 0, use default page size. + * @param {string} request.pageToken + * If this field is not empty then it must contain the `nextPageToken` value + * returned by a previous call to this method. Using this field causes the + * method to return additional results from the previous method call. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.monitoring.v3.Service|Service} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listServicesAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listServicesStream( - request?: protos.google.monitoring.v3.IListServicesRequest, - options?: CallOptions): - Transform{ + request?: protos.google.monitoring.v3.IListServicesRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); const defaultCallSettings = this._defaults['listServices']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listServices stream %j', request); return this.descriptors.page.listServices.createStream( this.innerApiCalls.listServices as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listServices`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. Resource name of the parent `Workspace`. - * Of the form `projects/{project_id}`. - * @param {string} request.filter - * A filter specifying what `Service`s to return. The filter currently - * supports the following fields: - * - * - `identifier_case` - * - `app_engine.module_id` - * - `cloud_endpoints.service` - * - `cluster_istio.location` - * - `cluster_istio.cluster_name` - * - `cluster_istio.service_namespace` - * - `cluster_istio.service_name` - * - * `identifier_case` refers to which option in the identifier oneof is - * populated. For example, the filter `identifier_case = "CUSTOM"` would match - * all services with a value for the `custom` field. Valid options are - * "CUSTOM", "APP_ENGINE", "CLOUD_ENDPOINTS", and "CLUSTER_ISTIO". - * @param {number} request.pageSize - * A non-negative number that is the maximum number of results to return. - * When 0, use default page size. - * @param {string} request.pageToken - * If this field is not empty then it must contain the `nextPageToken` value - * returned by a previous call to this method. Using this field causes the - * method to return additional results from the previous method call. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.monitoring.v3.Service|Service}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v3/service_monitoring_service.list_services.js - * region_tag:monitoring_v3_generated_ServiceMonitoringService_ListServices_async - */ + /** + * Equivalent to `listServices`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Resource name of the parent `Workspace`. + * Of the form `projects/{project_id}`. + * @param {string} request.filter + * A filter specifying what `Service`s to return. The filter currently + * supports the following fields: + * + * - `identifier_case` + * - `app_engine.module_id` + * - `cloud_endpoints.service` + * - `cluster_istio.location` + * - `cluster_istio.cluster_name` + * - `cluster_istio.service_namespace` + * - `cluster_istio.service_name` + * + * `identifier_case` refers to which option in the identifier oneof is + * populated. For example, the filter `identifier_case = "CUSTOM"` would match + * all services with a value for the `custom` field. Valid options are + * "CUSTOM", "APP_ENGINE", "CLOUD_ENDPOINTS", and "CLUSTER_ISTIO". + * @param {number} request.pageSize + * A non-negative number that is the maximum number of results to return. + * When 0, use default page size. + * @param {string} request.pageToken + * If this field is not empty then it must contain the `nextPageToken` value + * returned by a previous call to this method. Using this field causes the + * method to return additional results from the previous method call. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.monitoring.v3.Service|Service}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v3/service_monitoring_service.list_services.js + * region_tag:monitoring_v3_generated_ServiceMonitoringService_ListServices_async + */ listServicesAsync( - request?: protos.google.monitoring.v3.IListServicesRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.monitoring.v3.IListServicesRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); const defaultCallSettings = this._defaults['listServices']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listServices iterate %j', request); return this.descriptors.page.listServices.asyncIterate( this.innerApiCalls['listServices'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } - /** - * List the `ServiceLevelObjective`s for the given `Service`. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. Resource name of the parent `Service`. - * Of the form `projects/{project_id}/services/{service_id}`. - * @param {string} request.filter - * A filter specifying what `ServiceLevelObjective`s to return. - * @param {number} request.pageSize - * A non-negative number that is the maximum number of results to return. - * When 0, use default page size. - * @param {string} request.pageToken - * If this field is not empty then it must contain the `nextPageToken` value - * returned by a previous call to this method. Using this field causes the - * method to return additional results from the previous method call. - * @param {google.monitoring.v3.ServiceLevelObjective.View} request.view - * View of the `ServiceLevelObjective`s to return. If `DEFAULT`, return each - * `ServiceLevelObjective` as originally defined. If `EXPLICIT` and the - * `ServiceLevelObjective` is defined in terms of a `BasicSli`, replace the - * `BasicSli` with a `RequestBasedSli` spelling out how the SLI is computed. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.monitoring.v3.ServiceLevelObjective|ServiceLevelObjective}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `listServiceLevelObjectivesAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * List the `ServiceLevelObjective`s for the given `Service`. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Resource name of the parent `Service`. + * Of the form `projects/{project_id}/services/{service_id}`. + * @param {string} request.filter + * A filter specifying what `ServiceLevelObjective`s to return. + * @param {number} request.pageSize + * A non-negative number that is the maximum number of results to return. + * When 0, use default page size. + * @param {string} request.pageToken + * If this field is not empty then it must contain the `nextPageToken` value + * returned by a previous call to this method. Using this field causes the + * method to return additional results from the previous method call. + * @param {google.monitoring.v3.ServiceLevelObjective.View} request.view + * View of the `ServiceLevelObjective`s to return. If `DEFAULT`, return each + * `ServiceLevelObjective` as originally defined. If `EXPLICIT` and the + * `ServiceLevelObjective` is defined in terms of a `BasicSli`, replace the + * `BasicSli` with a `RequestBasedSli` spelling out how the SLI is computed. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.monitoring.v3.ServiceLevelObjective|ServiceLevelObjective}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listServiceLevelObjectivesAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listServiceLevelObjectives( - request?: protos.google.monitoring.v3.IListServiceLevelObjectivesRequest, - options?: CallOptions): - Promise<[ - protos.google.monitoring.v3.IServiceLevelObjective[], - protos.google.monitoring.v3.IListServiceLevelObjectivesRequest|null, - protos.google.monitoring.v3.IListServiceLevelObjectivesResponse - ]>; + request?: protos.google.monitoring.v3.IListServiceLevelObjectivesRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.monitoring.v3.IServiceLevelObjective[], + protos.google.monitoring.v3.IListServiceLevelObjectivesRequest | null, + protos.google.monitoring.v3.IListServiceLevelObjectivesResponse, + ] + >; listServiceLevelObjectives( - request: protos.google.monitoring.v3.IListServiceLevelObjectivesRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.monitoring.v3.IListServiceLevelObjectivesRequest, - protos.google.monitoring.v3.IListServiceLevelObjectivesResponse|null|undefined, - protos.google.monitoring.v3.IServiceLevelObjective>): void; + request: protos.google.monitoring.v3.IListServiceLevelObjectivesRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.monitoring.v3.IListServiceLevelObjectivesRequest, + | protos.google.monitoring.v3.IListServiceLevelObjectivesResponse + | null + | undefined, + protos.google.monitoring.v3.IServiceLevelObjective + >, + ): void; listServiceLevelObjectives( - request: protos.google.monitoring.v3.IListServiceLevelObjectivesRequest, - callback: PaginationCallback< - protos.google.monitoring.v3.IListServiceLevelObjectivesRequest, - protos.google.monitoring.v3.IListServiceLevelObjectivesResponse|null|undefined, - protos.google.monitoring.v3.IServiceLevelObjective>): void; + request: protos.google.monitoring.v3.IListServiceLevelObjectivesRequest, + callback: PaginationCallback< + protos.google.monitoring.v3.IListServiceLevelObjectivesRequest, + | protos.google.monitoring.v3.IListServiceLevelObjectivesResponse + | null + | undefined, + protos.google.monitoring.v3.IServiceLevelObjective + >, + ): void; listServiceLevelObjectives( - request?: protos.google.monitoring.v3.IListServiceLevelObjectivesRequest, - optionsOrCallback?: CallOptions|PaginationCallback< - protos.google.monitoring.v3.IListServiceLevelObjectivesRequest, - protos.google.monitoring.v3.IListServiceLevelObjectivesResponse|null|undefined, - protos.google.monitoring.v3.IServiceLevelObjective>, - callback?: PaginationCallback< + request?: protos.google.monitoring.v3.IListServiceLevelObjectivesRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.monitoring.v3.IListServiceLevelObjectivesRequest, - protos.google.monitoring.v3.IListServiceLevelObjectivesResponse|null|undefined, - protos.google.monitoring.v3.IServiceLevelObjective>): - Promise<[ - protos.google.monitoring.v3.IServiceLevelObjective[], - protos.google.monitoring.v3.IListServiceLevelObjectivesRequest|null, - protos.google.monitoring.v3.IListServiceLevelObjectivesResponse - ]>|void { + | protos.google.monitoring.v3.IListServiceLevelObjectivesResponse + | null + | undefined, + protos.google.monitoring.v3.IServiceLevelObjective + >, + callback?: PaginationCallback< + protos.google.monitoring.v3.IListServiceLevelObjectivesRequest, + | protos.google.monitoring.v3.IListServiceLevelObjectivesResponse + | null + | undefined, + protos.google.monitoring.v3.IServiceLevelObjective + >, + ): Promise< + [ + protos.google.monitoring.v3.IServiceLevelObjective[], + protos.google.monitoring.v3.IListServiceLevelObjectivesRequest | null, + protos.google.monitoring.v3.IListServiceLevelObjectivesResponse, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.monitoring.v3.IListServiceLevelObjectivesRequest, - protos.google.monitoring.v3.IListServiceLevelObjectivesResponse|null|undefined, - protos.google.monitoring.v3.IServiceLevelObjective>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.monitoring.v3.IListServiceLevelObjectivesRequest, + | protos.google.monitoring.v3.IListServiceLevelObjectivesResponse + | null + | undefined, + protos.google.monitoring.v3.IServiceLevelObjective + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listServiceLevelObjectives values %j', values); callback!(error, values, nextPageRequest, rawResponse); @@ -1557,128 +1991,132 @@ export class ServiceMonitoringServiceClient { this._log.info('listServiceLevelObjectives request %j', request); return this.innerApiCalls .listServiceLevelObjectives(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.monitoring.v3.IServiceLevelObjective[], - protos.google.monitoring.v3.IListServiceLevelObjectivesRequest|null, - protos.google.monitoring.v3.IListServiceLevelObjectivesResponse - ]) => { - this._log.info('listServiceLevelObjectives values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.monitoring.v3.IServiceLevelObjective[], + protos.google.monitoring.v3.IListServiceLevelObjectivesRequest | null, + protos.google.monitoring.v3.IListServiceLevelObjectivesResponse, + ]) => { + this._log.info('listServiceLevelObjectives values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listServiceLevelObjectives`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. Resource name of the parent `Service`. - * Of the form `projects/{project_id}/services/{service_id}`. - * @param {string} request.filter - * A filter specifying what `ServiceLevelObjective`s to return. - * @param {number} request.pageSize - * A non-negative number that is the maximum number of results to return. - * When 0, use default page size. - * @param {string} request.pageToken - * If this field is not empty then it must contain the `nextPageToken` value - * returned by a previous call to this method. Using this field causes the - * method to return additional results from the previous method call. - * @param {google.monitoring.v3.ServiceLevelObjective.View} request.view - * View of the `ServiceLevelObjective`s to return. If `DEFAULT`, return each - * `ServiceLevelObjective` as originally defined. If `EXPLICIT` and the - * `ServiceLevelObjective` is defined in terms of a `BasicSli`, replace the - * `BasicSli` with a `RequestBasedSli` spelling out how the SLI is computed. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.monitoring.v3.ServiceLevelObjective|ServiceLevelObjective} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `listServiceLevelObjectivesAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `listServiceLevelObjectives`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Resource name of the parent `Service`. + * Of the form `projects/{project_id}/services/{service_id}`. + * @param {string} request.filter + * A filter specifying what `ServiceLevelObjective`s to return. + * @param {number} request.pageSize + * A non-negative number that is the maximum number of results to return. + * When 0, use default page size. + * @param {string} request.pageToken + * If this field is not empty then it must contain the `nextPageToken` value + * returned by a previous call to this method. Using this field causes the + * method to return additional results from the previous method call. + * @param {google.monitoring.v3.ServiceLevelObjective.View} request.view + * View of the `ServiceLevelObjective`s to return. If `DEFAULT`, return each + * `ServiceLevelObjective` as originally defined. If `EXPLICIT` and the + * `ServiceLevelObjective` is defined in terms of a `BasicSli`, replace the + * `BasicSli` with a `RequestBasedSli` spelling out how the SLI is computed. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.monitoring.v3.ServiceLevelObjective|ServiceLevelObjective} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listServiceLevelObjectivesAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listServiceLevelObjectivesStream( - request?: protos.google.monitoring.v3.IListServiceLevelObjectivesRequest, - options?: CallOptions): - Transform{ + request?: protos.google.monitoring.v3.IListServiceLevelObjectivesRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); const defaultCallSettings = this._defaults['listServiceLevelObjectives']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listServiceLevelObjectives stream %j', request); return this.descriptors.page.listServiceLevelObjectives.createStream( this.innerApiCalls.listServiceLevelObjectives as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listServiceLevelObjectives`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. Resource name of the parent `Service`. - * Of the form `projects/{project_id}/services/{service_id}`. - * @param {string} request.filter - * A filter specifying what `ServiceLevelObjective`s to return. - * @param {number} request.pageSize - * A non-negative number that is the maximum number of results to return. - * When 0, use default page size. - * @param {string} request.pageToken - * If this field is not empty then it must contain the `nextPageToken` value - * returned by a previous call to this method. Using this field causes the - * method to return additional results from the previous method call. - * @param {google.monitoring.v3.ServiceLevelObjective.View} request.view - * View of the `ServiceLevelObjective`s to return. If `DEFAULT`, return each - * `ServiceLevelObjective` as originally defined. If `EXPLICIT` and the - * `ServiceLevelObjective` is defined in terms of a `BasicSli`, replace the - * `BasicSli` with a `RequestBasedSli` spelling out how the SLI is computed. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.monitoring.v3.ServiceLevelObjective|ServiceLevelObjective}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v3/service_monitoring_service.list_service_level_objectives.js - * region_tag:monitoring_v3_generated_ServiceMonitoringService_ListServiceLevelObjectives_async - */ + /** + * Equivalent to `listServiceLevelObjectives`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Resource name of the parent `Service`. + * Of the form `projects/{project_id}/services/{service_id}`. + * @param {string} request.filter + * A filter specifying what `ServiceLevelObjective`s to return. + * @param {number} request.pageSize + * A non-negative number that is the maximum number of results to return. + * When 0, use default page size. + * @param {string} request.pageToken + * If this field is not empty then it must contain the `nextPageToken` value + * returned by a previous call to this method. Using this field causes the + * method to return additional results from the previous method call. + * @param {google.monitoring.v3.ServiceLevelObjective.View} request.view + * View of the `ServiceLevelObjective`s to return. If `DEFAULT`, return each + * `ServiceLevelObjective` as originally defined. If `EXPLICIT` and the + * `ServiceLevelObjective` is defined in terms of a `BasicSli`, replace the + * `BasicSli` with a `RequestBasedSli` spelling out how the SLI is computed. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.monitoring.v3.ServiceLevelObjective|ServiceLevelObjective}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v3/service_monitoring_service.list_service_level_objectives.js + * region_tag:monitoring_v3_generated_ServiceMonitoringService_ListServiceLevelObjectives_async + */ listServiceLevelObjectivesAsync( - request?: protos.google.monitoring.v3.IListServiceLevelObjectivesRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.monitoring.v3.IListServiceLevelObjectivesRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); const defaultCallSettings = this._defaults['listServiceLevelObjectives']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listServiceLevelObjectives iterate %j', request); return this.descriptors.page.listServiceLevelObjectives.asyncIterate( this.innerApiCalls['listServiceLevelObjectives'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } // -------------------- @@ -1692,7 +2130,7 @@ export class ServiceMonitoringServiceClient { * @param {string} alert_policy * @returns {string} Resource name string. */ - folderAlertPolicyPath(folder:string,alertPolicy:string) { + folderAlertPolicyPath(folder: string, alertPolicy: string) { return this.pathTemplates.folderAlertPolicyPathTemplate.render({ folder: folder, alert_policy: alertPolicy, @@ -1707,7 +2145,9 @@ export class ServiceMonitoringServiceClient { * @returns {string} A string representing the folder. */ matchFolderFromFolderAlertPolicyName(folderAlertPolicyName: string) { - return this.pathTemplates.folderAlertPolicyPathTemplate.match(folderAlertPolicyName).folder; + return this.pathTemplates.folderAlertPolicyPathTemplate.match( + folderAlertPolicyName, + ).folder; } /** @@ -1718,7 +2158,9 @@ export class ServiceMonitoringServiceClient { * @returns {string} A string representing the alert_policy. */ matchAlertPolicyFromFolderAlertPolicyName(folderAlertPolicyName: string) { - return this.pathTemplates.folderAlertPolicyPathTemplate.match(folderAlertPolicyName).alert_policy; + return this.pathTemplates.folderAlertPolicyPathTemplate.match( + folderAlertPolicyName, + ).alert_policy; } /** @@ -1729,7 +2171,11 @@ export class ServiceMonitoringServiceClient { * @param {string} condition * @returns {string} Resource name string. */ - folderAlertPolicyConditionPath(folder:string,alertPolicy:string,condition:string) { + folderAlertPolicyConditionPath( + folder: string, + alertPolicy: string, + condition: string, + ) { return this.pathTemplates.folderAlertPolicyConditionPathTemplate.render({ folder: folder, alert_policy: alertPolicy, @@ -1744,8 +2190,12 @@ export class ServiceMonitoringServiceClient { * A fully-qualified path representing folder_alert_policy_condition resource. * @returns {string} A string representing the folder. */ - matchFolderFromFolderAlertPolicyConditionName(folderAlertPolicyConditionName: string) { - return this.pathTemplates.folderAlertPolicyConditionPathTemplate.match(folderAlertPolicyConditionName).folder; + matchFolderFromFolderAlertPolicyConditionName( + folderAlertPolicyConditionName: string, + ) { + return this.pathTemplates.folderAlertPolicyConditionPathTemplate.match( + folderAlertPolicyConditionName, + ).folder; } /** @@ -1755,8 +2205,12 @@ export class ServiceMonitoringServiceClient { * A fully-qualified path representing folder_alert_policy_condition resource. * @returns {string} A string representing the alert_policy. */ - matchAlertPolicyFromFolderAlertPolicyConditionName(folderAlertPolicyConditionName: string) { - return this.pathTemplates.folderAlertPolicyConditionPathTemplate.match(folderAlertPolicyConditionName).alert_policy; + matchAlertPolicyFromFolderAlertPolicyConditionName( + folderAlertPolicyConditionName: string, + ) { + return this.pathTemplates.folderAlertPolicyConditionPathTemplate.match( + folderAlertPolicyConditionName, + ).alert_policy; } /** @@ -1766,8 +2220,12 @@ export class ServiceMonitoringServiceClient { * A fully-qualified path representing folder_alert_policy_condition resource. * @returns {string} A string representing the condition. */ - matchConditionFromFolderAlertPolicyConditionName(folderAlertPolicyConditionName: string) { - return this.pathTemplates.folderAlertPolicyConditionPathTemplate.match(folderAlertPolicyConditionName).condition; + matchConditionFromFolderAlertPolicyConditionName( + folderAlertPolicyConditionName: string, + ) { + return this.pathTemplates.folderAlertPolicyConditionPathTemplate.match( + folderAlertPolicyConditionName, + ).condition; } /** @@ -1777,7 +2235,7 @@ export class ServiceMonitoringServiceClient { * @param {string} channel_descriptor * @returns {string} Resource name string. */ - folderChannelDescriptorPath(folder:string,channelDescriptor:string) { + folderChannelDescriptorPath(folder: string, channelDescriptor: string) { return this.pathTemplates.folderChannelDescriptorPathTemplate.render({ folder: folder, channel_descriptor: channelDescriptor, @@ -1791,8 +2249,12 @@ export class ServiceMonitoringServiceClient { * A fully-qualified path representing folder_channel_descriptor resource. * @returns {string} A string representing the folder. */ - matchFolderFromFolderChannelDescriptorName(folderChannelDescriptorName: string) { - return this.pathTemplates.folderChannelDescriptorPathTemplate.match(folderChannelDescriptorName).folder; + matchFolderFromFolderChannelDescriptorName( + folderChannelDescriptorName: string, + ) { + return this.pathTemplates.folderChannelDescriptorPathTemplate.match( + folderChannelDescriptorName, + ).folder; } /** @@ -1802,8 +2264,12 @@ export class ServiceMonitoringServiceClient { * A fully-qualified path representing folder_channel_descriptor resource. * @returns {string} A string representing the channel_descriptor. */ - matchChannelDescriptorFromFolderChannelDescriptorName(folderChannelDescriptorName: string) { - return this.pathTemplates.folderChannelDescriptorPathTemplate.match(folderChannelDescriptorName).channel_descriptor; + matchChannelDescriptorFromFolderChannelDescriptorName( + folderChannelDescriptorName: string, + ) { + return this.pathTemplates.folderChannelDescriptorPathTemplate.match( + folderChannelDescriptorName, + ).channel_descriptor; } /** @@ -1813,7 +2279,7 @@ export class ServiceMonitoringServiceClient { * @param {string} group * @returns {string} Resource name string. */ - folderGroupPath(folder:string,group:string) { + folderGroupPath(folder: string, group: string) { return this.pathTemplates.folderGroupPathTemplate.render({ folder: folder, group: group, @@ -1828,7 +2294,8 @@ export class ServiceMonitoringServiceClient { * @returns {string} A string representing the folder. */ matchFolderFromFolderGroupName(folderGroupName: string) { - return this.pathTemplates.folderGroupPathTemplate.match(folderGroupName).folder; + return this.pathTemplates.folderGroupPathTemplate.match(folderGroupName) + .folder; } /** @@ -1839,7 +2306,8 @@ export class ServiceMonitoringServiceClient { * @returns {string} A string representing the group. */ matchGroupFromFolderGroupName(folderGroupName: string) { - return this.pathTemplates.folderGroupPathTemplate.match(folderGroupName).group; + return this.pathTemplates.folderGroupPathTemplate.match(folderGroupName) + .group; } /** @@ -1849,7 +2317,7 @@ export class ServiceMonitoringServiceClient { * @param {string} notification_channel * @returns {string} Resource name string. */ - folderNotificationChannelPath(folder:string,notificationChannel:string) { + folderNotificationChannelPath(folder: string, notificationChannel: string) { return this.pathTemplates.folderNotificationChannelPathTemplate.render({ folder: folder, notification_channel: notificationChannel, @@ -1863,8 +2331,12 @@ export class ServiceMonitoringServiceClient { * A fully-qualified path representing folder_notification_channel resource. * @returns {string} A string representing the folder. */ - matchFolderFromFolderNotificationChannelName(folderNotificationChannelName: string) { - return this.pathTemplates.folderNotificationChannelPathTemplate.match(folderNotificationChannelName).folder; + matchFolderFromFolderNotificationChannelName( + folderNotificationChannelName: string, + ) { + return this.pathTemplates.folderNotificationChannelPathTemplate.match( + folderNotificationChannelName, + ).folder; } /** @@ -1874,8 +2346,12 @@ export class ServiceMonitoringServiceClient { * A fully-qualified path representing folder_notification_channel resource. * @returns {string} A string representing the notification_channel. */ - matchNotificationChannelFromFolderNotificationChannelName(folderNotificationChannelName: string) { - return this.pathTemplates.folderNotificationChannelPathTemplate.match(folderNotificationChannelName).notification_channel; + matchNotificationChannelFromFolderNotificationChannelName( + folderNotificationChannelName: string, + ) { + return this.pathTemplates.folderNotificationChannelPathTemplate.match( + folderNotificationChannelName, + ).notification_channel; } /** @@ -1885,7 +2361,7 @@ export class ServiceMonitoringServiceClient { * @param {string} service * @returns {string} Resource name string. */ - folderServicePath(folder:string,service:string) { + folderServicePath(folder: string, service: string) { return this.pathTemplates.folderServicePathTemplate.render({ folder: folder, service: service, @@ -1900,7 +2376,8 @@ export class ServiceMonitoringServiceClient { * @returns {string} A string representing the folder. */ matchFolderFromFolderServiceName(folderServiceName: string) { - return this.pathTemplates.folderServicePathTemplate.match(folderServiceName).folder; + return this.pathTemplates.folderServicePathTemplate.match(folderServiceName) + .folder; } /** @@ -1911,7 +2388,8 @@ export class ServiceMonitoringServiceClient { * @returns {string} A string representing the service. */ matchServiceFromFolderServiceName(folderServiceName: string) { - return this.pathTemplates.folderServicePathTemplate.match(folderServiceName).service; + return this.pathTemplates.folderServicePathTemplate.match(folderServiceName) + .service; } /** @@ -1922,12 +2400,18 @@ export class ServiceMonitoringServiceClient { * @param {string} service_level_objective * @returns {string} Resource name string. */ - folderServiceServiceLevelObjectivePath(folder:string,service:string,serviceLevelObjective:string) { - return this.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.render({ - folder: folder, - service: service, - service_level_objective: serviceLevelObjective, - }); + folderServiceServiceLevelObjectivePath( + folder: string, + service: string, + serviceLevelObjective: string, + ) { + return this.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.render( + { + folder: folder, + service: service, + service_level_objective: serviceLevelObjective, + }, + ); } /** @@ -1937,8 +2421,12 @@ export class ServiceMonitoringServiceClient { * A fully-qualified path representing folder_service_service_level_objective resource. * @returns {string} A string representing the folder. */ - matchFolderFromFolderServiceServiceLevelObjectiveName(folderServiceServiceLevelObjectiveName: string) { - return this.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match(folderServiceServiceLevelObjectiveName).folder; + matchFolderFromFolderServiceServiceLevelObjectiveName( + folderServiceServiceLevelObjectiveName: string, + ) { + return this.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match( + folderServiceServiceLevelObjectiveName, + ).folder; } /** @@ -1948,8 +2436,12 @@ export class ServiceMonitoringServiceClient { * A fully-qualified path representing folder_service_service_level_objective resource. * @returns {string} A string representing the service. */ - matchServiceFromFolderServiceServiceLevelObjectiveName(folderServiceServiceLevelObjectiveName: string) { - return this.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match(folderServiceServiceLevelObjectiveName).service; + matchServiceFromFolderServiceServiceLevelObjectiveName( + folderServiceServiceLevelObjectiveName: string, + ) { + return this.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match( + folderServiceServiceLevelObjectiveName, + ).service; } /** @@ -1959,8 +2451,12 @@ export class ServiceMonitoringServiceClient { * A fully-qualified path representing folder_service_service_level_objective resource. * @returns {string} A string representing the service_level_objective. */ - matchServiceLevelObjectiveFromFolderServiceServiceLevelObjectiveName(folderServiceServiceLevelObjectiveName: string) { - return this.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match(folderServiceServiceLevelObjectiveName).service_level_objective; + matchServiceLevelObjectiveFromFolderServiceServiceLevelObjectiveName( + folderServiceServiceLevelObjectiveName: string, + ) { + return this.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match( + folderServiceServiceLevelObjectiveName, + ).service_level_objective; } /** @@ -1970,7 +2466,7 @@ export class ServiceMonitoringServiceClient { * @param {string} uptime_check_config * @returns {string} Resource name string. */ - folderUptimeCheckConfigPath(folder:string,uptimeCheckConfig:string) { + folderUptimeCheckConfigPath(folder: string, uptimeCheckConfig: string) { return this.pathTemplates.folderUptimeCheckConfigPathTemplate.render({ folder: folder, uptime_check_config: uptimeCheckConfig, @@ -1984,8 +2480,12 @@ export class ServiceMonitoringServiceClient { * A fully-qualified path representing folder_uptime_check_config resource. * @returns {string} A string representing the folder. */ - matchFolderFromFolderUptimeCheckConfigName(folderUptimeCheckConfigName: string) { - return this.pathTemplates.folderUptimeCheckConfigPathTemplate.match(folderUptimeCheckConfigName).folder; + matchFolderFromFolderUptimeCheckConfigName( + folderUptimeCheckConfigName: string, + ) { + return this.pathTemplates.folderUptimeCheckConfigPathTemplate.match( + folderUptimeCheckConfigName, + ).folder; } /** @@ -1995,8 +2495,12 @@ export class ServiceMonitoringServiceClient { * A fully-qualified path representing folder_uptime_check_config resource. * @returns {string} A string representing the uptime_check_config. */ - matchUptimeCheckConfigFromFolderUptimeCheckConfigName(folderUptimeCheckConfigName: string) { - return this.pathTemplates.folderUptimeCheckConfigPathTemplate.match(folderUptimeCheckConfigName).uptime_check_config; + matchUptimeCheckConfigFromFolderUptimeCheckConfigName( + folderUptimeCheckConfigName: string, + ) { + return this.pathTemplates.folderUptimeCheckConfigPathTemplate.match( + folderUptimeCheckConfigName, + ).uptime_check_config; } /** @@ -2006,7 +2510,7 @@ export class ServiceMonitoringServiceClient { * @param {string} alert_policy * @returns {string} Resource name string. */ - organizationAlertPolicyPath(organization:string,alertPolicy:string) { + organizationAlertPolicyPath(organization: string, alertPolicy: string) { return this.pathTemplates.organizationAlertPolicyPathTemplate.render({ organization: organization, alert_policy: alertPolicy, @@ -2020,8 +2524,12 @@ export class ServiceMonitoringServiceClient { * A fully-qualified path representing organization_alert_policy resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationAlertPolicyName(organizationAlertPolicyName: string) { - return this.pathTemplates.organizationAlertPolicyPathTemplate.match(organizationAlertPolicyName).organization; + matchOrganizationFromOrganizationAlertPolicyName( + organizationAlertPolicyName: string, + ) { + return this.pathTemplates.organizationAlertPolicyPathTemplate.match( + organizationAlertPolicyName, + ).organization; } /** @@ -2031,8 +2539,12 @@ export class ServiceMonitoringServiceClient { * A fully-qualified path representing organization_alert_policy resource. * @returns {string} A string representing the alert_policy. */ - matchAlertPolicyFromOrganizationAlertPolicyName(organizationAlertPolicyName: string) { - return this.pathTemplates.organizationAlertPolicyPathTemplate.match(organizationAlertPolicyName).alert_policy; + matchAlertPolicyFromOrganizationAlertPolicyName( + organizationAlertPolicyName: string, + ) { + return this.pathTemplates.organizationAlertPolicyPathTemplate.match( + organizationAlertPolicyName, + ).alert_policy; } /** @@ -2043,12 +2555,18 @@ export class ServiceMonitoringServiceClient { * @param {string} condition * @returns {string} Resource name string. */ - organizationAlertPolicyConditionPath(organization:string,alertPolicy:string,condition:string) { - return this.pathTemplates.organizationAlertPolicyConditionPathTemplate.render({ - organization: organization, - alert_policy: alertPolicy, - condition: condition, - }); + organizationAlertPolicyConditionPath( + organization: string, + alertPolicy: string, + condition: string, + ) { + return this.pathTemplates.organizationAlertPolicyConditionPathTemplate.render( + { + organization: organization, + alert_policy: alertPolicy, + condition: condition, + }, + ); } /** @@ -2058,8 +2576,12 @@ export class ServiceMonitoringServiceClient { * A fully-qualified path representing organization_alert_policy_condition resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationAlertPolicyConditionName(organizationAlertPolicyConditionName: string) { - return this.pathTemplates.organizationAlertPolicyConditionPathTemplate.match(organizationAlertPolicyConditionName).organization; + matchOrganizationFromOrganizationAlertPolicyConditionName( + organizationAlertPolicyConditionName: string, + ) { + return this.pathTemplates.organizationAlertPolicyConditionPathTemplate.match( + organizationAlertPolicyConditionName, + ).organization; } /** @@ -2069,8 +2591,12 @@ export class ServiceMonitoringServiceClient { * A fully-qualified path representing organization_alert_policy_condition resource. * @returns {string} A string representing the alert_policy. */ - matchAlertPolicyFromOrganizationAlertPolicyConditionName(organizationAlertPolicyConditionName: string) { - return this.pathTemplates.organizationAlertPolicyConditionPathTemplate.match(organizationAlertPolicyConditionName).alert_policy; + matchAlertPolicyFromOrganizationAlertPolicyConditionName( + organizationAlertPolicyConditionName: string, + ) { + return this.pathTemplates.organizationAlertPolicyConditionPathTemplate.match( + organizationAlertPolicyConditionName, + ).alert_policy; } /** @@ -2080,8 +2606,12 @@ export class ServiceMonitoringServiceClient { * A fully-qualified path representing organization_alert_policy_condition resource. * @returns {string} A string representing the condition. */ - matchConditionFromOrganizationAlertPolicyConditionName(organizationAlertPolicyConditionName: string) { - return this.pathTemplates.organizationAlertPolicyConditionPathTemplate.match(organizationAlertPolicyConditionName).condition; + matchConditionFromOrganizationAlertPolicyConditionName( + organizationAlertPolicyConditionName: string, + ) { + return this.pathTemplates.organizationAlertPolicyConditionPathTemplate.match( + organizationAlertPolicyConditionName, + ).condition; } /** @@ -2091,7 +2621,10 @@ export class ServiceMonitoringServiceClient { * @param {string} channel_descriptor * @returns {string} Resource name string. */ - organizationChannelDescriptorPath(organization:string,channelDescriptor:string) { + organizationChannelDescriptorPath( + organization: string, + channelDescriptor: string, + ) { return this.pathTemplates.organizationChannelDescriptorPathTemplate.render({ organization: organization, channel_descriptor: channelDescriptor, @@ -2105,8 +2638,12 @@ export class ServiceMonitoringServiceClient { * A fully-qualified path representing organization_channel_descriptor resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationChannelDescriptorName(organizationChannelDescriptorName: string) { - return this.pathTemplates.organizationChannelDescriptorPathTemplate.match(organizationChannelDescriptorName).organization; + matchOrganizationFromOrganizationChannelDescriptorName( + organizationChannelDescriptorName: string, + ) { + return this.pathTemplates.organizationChannelDescriptorPathTemplate.match( + organizationChannelDescriptorName, + ).organization; } /** @@ -2116,8 +2653,12 @@ export class ServiceMonitoringServiceClient { * A fully-qualified path representing organization_channel_descriptor resource. * @returns {string} A string representing the channel_descriptor. */ - matchChannelDescriptorFromOrganizationChannelDescriptorName(organizationChannelDescriptorName: string) { - return this.pathTemplates.organizationChannelDescriptorPathTemplate.match(organizationChannelDescriptorName).channel_descriptor; + matchChannelDescriptorFromOrganizationChannelDescriptorName( + organizationChannelDescriptorName: string, + ) { + return this.pathTemplates.organizationChannelDescriptorPathTemplate.match( + organizationChannelDescriptorName, + ).channel_descriptor; } /** @@ -2127,7 +2668,7 @@ export class ServiceMonitoringServiceClient { * @param {string} group * @returns {string} Resource name string. */ - organizationGroupPath(organization:string,group:string) { + organizationGroupPath(organization: string, group: string) { return this.pathTemplates.organizationGroupPathTemplate.render({ organization: organization, group: group, @@ -2142,7 +2683,9 @@ export class ServiceMonitoringServiceClient { * @returns {string} A string representing the organization. */ matchOrganizationFromOrganizationGroupName(organizationGroupName: string) { - return this.pathTemplates.organizationGroupPathTemplate.match(organizationGroupName).organization; + return this.pathTemplates.organizationGroupPathTemplate.match( + organizationGroupName, + ).organization; } /** @@ -2153,7 +2696,9 @@ export class ServiceMonitoringServiceClient { * @returns {string} A string representing the group. */ matchGroupFromOrganizationGroupName(organizationGroupName: string) { - return this.pathTemplates.organizationGroupPathTemplate.match(organizationGroupName).group; + return this.pathTemplates.organizationGroupPathTemplate.match( + organizationGroupName, + ).group; } /** @@ -2163,11 +2708,16 @@ export class ServiceMonitoringServiceClient { * @param {string} notification_channel * @returns {string} Resource name string. */ - organizationNotificationChannelPath(organization:string,notificationChannel:string) { - return this.pathTemplates.organizationNotificationChannelPathTemplate.render({ - organization: organization, - notification_channel: notificationChannel, - }); + organizationNotificationChannelPath( + organization: string, + notificationChannel: string, + ) { + return this.pathTemplates.organizationNotificationChannelPathTemplate.render( + { + organization: organization, + notification_channel: notificationChannel, + }, + ); } /** @@ -2177,8 +2727,12 @@ export class ServiceMonitoringServiceClient { * A fully-qualified path representing organization_notification_channel resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationNotificationChannelName(organizationNotificationChannelName: string) { - return this.pathTemplates.organizationNotificationChannelPathTemplate.match(organizationNotificationChannelName).organization; + matchOrganizationFromOrganizationNotificationChannelName( + organizationNotificationChannelName: string, + ) { + return this.pathTemplates.organizationNotificationChannelPathTemplate.match( + organizationNotificationChannelName, + ).organization; } /** @@ -2188,8 +2742,12 @@ export class ServiceMonitoringServiceClient { * A fully-qualified path representing organization_notification_channel resource. * @returns {string} A string representing the notification_channel. */ - matchNotificationChannelFromOrganizationNotificationChannelName(organizationNotificationChannelName: string) { - return this.pathTemplates.organizationNotificationChannelPathTemplate.match(organizationNotificationChannelName).notification_channel; + matchNotificationChannelFromOrganizationNotificationChannelName( + organizationNotificationChannelName: string, + ) { + return this.pathTemplates.organizationNotificationChannelPathTemplate.match( + organizationNotificationChannelName, + ).notification_channel; } /** @@ -2199,7 +2757,7 @@ export class ServiceMonitoringServiceClient { * @param {string} service * @returns {string} Resource name string. */ - organizationServicePath(organization:string,service:string) { + organizationServicePath(organization: string, service: string) { return this.pathTemplates.organizationServicePathTemplate.render({ organization: organization, service: service, @@ -2213,8 +2771,12 @@ export class ServiceMonitoringServiceClient { * A fully-qualified path representing organization_service resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationServiceName(organizationServiceName: string) { - return this.pathTemplates.organizationServicePathTemplate.match(organizationServiceName).organization; + matchOrganizationFromOrganizationServiceName( + organizationServiceName: string, + ) { + return this.pathTemplates.organizationServicePathTemplate.match( + organizationServiceName, + ).organization; } /** @@ -2225,7 +2787,9 @@ export class ServiceMonitoringServiceClient { * @returns {string} A string representing the service. */ matchServiceFromOrganizationServiceName(organizationServiceName: string) { - return this.pathTemplates.organizationServicePathTemplate.match(organizationServiceName).service; + return this.pathTemplates.organizationServicePathTemplate.match( + organizationServiceName, + ).service; } /** @@ -2236,12 +2800,18 @@ export class ServiceMonitoringServiceClient { * @param {string} service_level_objective * @returns {string} Resource name string. */ - organizationServiceServiceLevelObjectivePath(organization:string,service:string,serviceLevelObjective:string) { - return this.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.render({ - organization: organization, - service: service, - service_level_objective: serviceLevelObjective, - }); + organizationServiceServiceLevelObjectivePath( + organization: string, + service: string, + serviceLevelObjective: string, + ) { + return this.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.render( + { + organization: organization, + service: service, + service_level_objective: serviceLevelObjective, + }, + ); } /** @@ -2251,8 +2821,12 @@ export class ServiceMonitoringServiceClient { * A fully-qualified path representing organization_service_service_level_objective resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationServiceServiceLevelObjectiveName(organizationServiceServiceLevelObjectiveName: string) { - return this.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match(organizationServiceServiceLevelObjectiveName).organization; + matchOrganizationFromOrganizationServiceServiceLevelObjectiveName( + organizationServiceServiceLevelObjectiveName: string, + ) { + return this.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match( + organizationServiceServiceLevelObjectiveName, + ).organization; } /** @@ -2262,8 +2836,12 @@ export class ServiceMonitoringServiceClient { * A fully-qualified path representing organization_service_service_level_objective resource. * @returns {string} A string representing the service. */ - matchServiceFromOrganizationServiceServiceLevelObjectiveName(organizationServiceServiceLevelObjectiveName: string) { - return this.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match(organizationServiceServiceLevelObjectiveName).service; + matchServiceFromOrganizationServiceServiceLevelObjectiveName( + organizationServiceServiceLevelObjectiveName: string, + ) { + return this.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match( + organizationServiceServiceLevelObjectiveName, + ).service; } /** @@ -2273,8 +2851,12 @@ export class ServiceMonitoringServiceClient { * A fully-qualified path representing organization_service_service_level_objective resource. * @returns {string} A string representing the service_level_objective. */ - matchServiceLevelObjectiveFromOrganizationServiceServiceLevelObjectiveName(organizationServiceServiceLevelObjectiveName: string) { - return this.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match(organizationServiceServiceLevelObjectiveName).service_level_objective; + matchServiceLevelObjectiveFromOrganizationServiceServiceLevelObjectiveName( + organizationServiceServiceLevelObjectiveName: string, + ) { + return this.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match( + organizationServiceServiceLevelObjectiveName, + ).service_level_objective; } /** @@ -2284,7 +2866,10 @@ export class ServiceMonitoringServiceClient { * @param {string} uptime_check_config * @returns {string} Resource name string. */ - organizationUptimeCheckConfigPath(organization:string,uptimeCheckConfig:string) { + organizationUptimeCheckConfigPath( + organization: string, + uptimeCheckConfig: string, + ) { return this.pathTemplates.organizationUptimeCheckConfigPathTemplate.render({ organization: organization, uptime_check_config: uptimeCheckConfig, @@ -2298,8 +2883,12 @@ export class ServiceMonitoringServiceClient { * A fully-qualified path representing organization_uptime_check_config resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationUptimeCheckConfigName(organizationUptimeCheckConfigName: string) { - return this.pathTemplates.organizationUptimeCheckConfigPathTemplate.match(organizationUptimeCheckConfigName).organization; + matchOrganizationFromOrganizationUptimeCheckConfigName( + organizationUptimeCheckConfigName: string, + ) { + return this.pathTemplates.organizationUptimeCheckConfigPathTemplate.match( + organizationUptimeCheckConfigName, + ).organization; } /** @@ -2309,8 +2898,12 @@ export class ServiceMonitoringServiceClient { * A fully-qualified path representing organization_uptime_check_config resource. * @returns {string} A string representing the uptime_check_config. */ - matchUptimeCheckConfigFromOrganizationUptimeCheckConfigName(organizationUptimeCheckConfigName: string) { - return this.pathTemplates.organizationUptimeCheckConfigPathTemplate.match(organizationUptimeCheckConfigName).uptime_check_config; + matchUptimeCheckConfigFromOrganizationUptimeCheckConfigName( + organizationUptimeCheckConfigName: string, + ) { + return this.pathTemplates.organizationUptimeCheckConfigPathTemplate.match( + organizationUptimeCheckConfigName, + ).uptime_check_config; } /** @@ -2320,7 +2913,7 @@ export class ServiceMonitoringServiceClient { * @param {string} alert_policy * @returns {string} Resource name string. */ - projectAlertPolicyPath(project:string,alertPolicy:string) { + projectAlertPolicyPath(project: string, alertPolicy: string) { return this.pathTemplates.projectAlertPolicyPathTemplate.render({ project: project, alert_policy: alertPolicy, @@ -2335,7 +2928,9 @@ export class ServiceMonitoringServiceClient { * @returns {string} A string representing the project. */ matchProjectFromProjectAlertPolicyName(projectAlertPolicyName: string) { - return this.pathTemplates.projectAlertPolicyPathTemplate.match(projectAlertPolicyName).project; + return this.pathTemplates.projectAlertPolicyPathTemplate.match( + projectAlertPolicyName, + ).project; } /** @@ -2346,7 +2941,9 @@ export class ServiceMonitoringServiceClient { * @returns {string} A string representing the alert_policy. */ matchAlertPolicyFromProjectAlertPolicyName(projectAlertPolicyName: string) { - return this.pathTemplates.projectAlertPolicyPathTemplate.match(projectAlertPolicyName).alert_policy; + return this.pathTemplates.projectAlertPolicyPathTemplate.match( + projectAlertPolicyName, + ).alert_policy; } /** @@ -2357,7 +2954,11 @@ export class ServiceMonitoringServiceClient { * @param {string} condition * @returns {string} Resource name string. */ - projectAlertPolicyConditionPath(project:string,alertPolicy:string,condition:string) { + projectAlertPolicyConditionPath( + project: string, + alertPolicy: string, + condition: string, + ) { return this.pathTemplates.projectAlertPolicyConditionPathTemplate.render({ project: project, alert_policy: alertPolicy, @@ -2372,8 +2973,12 @@ export class ServiceMonitoringServiceClient { * A fully-qualified path representing project_alert_policy_condition resource. * @returns {string} A string representing the project. */ - matchProjectFromProjectAlertPolicyConditionName(projectAlertPolicyConditionName: string) { - return this.pathTemplates.projectAlertPolicyConditionPathTemplate.match(projectAlertPolicyConditionName).project; + matchProjectFromProjectAlertPolicyConditionName( + projectAlertPolicyConditionName: string, + ) { + return this.pathTemplates.projectAlertPolicyConditionPathTemplate.match( + projectAlertPolicyConditionName, + ).project; } /** @@ -2383,8 +2988,12 @@ export class ServiceMonitoringServiceClient { * A fully-qualified path representing project_alert_policy_condition resource. * @returns {string} A string representing the alert_policy. */ - matchAlertPolicyFromProjectAlertPolicyConditionName(projectAlertPolicyConditionName: string) { - return this.pathTemplates.projectAlertPolicyConditionPathTemplate.match(projectAlertPolicyConditionName).alert_policy; + matchAlertPolicyFromProjectAlertPolicyConditionName( + projectAlertPolicyConditionName: string, + ) { + return this.pathTemplates.projectAlertPolicyConditionPathTemplate.match( + projectAlertPolicyConditionName, + ).alert_policy; } /** @@ -2394,8 +3003,12 @@ export class ServiceMonitoringServiceClient { * A fully-qualified path representing project_alert_policy_condition resource. * @returns {string} A string representing the condition. */ - matchConditionFromProjectAlertPolicyConditionName(projectAlertPolicyConditionName: string) { - return this.pathTemplates.projectAlertPolicyConditionPathTemplate.match(projectAlertPolicyConditionName).condition; + matchConditionFromProjectAlertPolicyConditionName( + projectAlertPolicyConditionName: string, + ) { + return this.pathTemplates.projectAlertPolicyConditionPathTemplate.match( + projectAlertPolicyConditionName, + ).condition; } /** @@ -2405,7 +3018,7 @@ export class ServiceMonitoringServiceClient { * @param {string} channel_descriptor * @returns {string} Resource name string. */ - projectChannelDescriptorPath(project:string,channelDescriptor:string) { + projectChannelDescriptorPath(project: string, channelDescriptor: string) { return this.pathTemplates.projectChannelDescriptorPathTemplate.render({ project: project, channel_descriptor: channelDescriptor, @@ -2419,8 +3032,12 @@ export class ServiceMonitoringServiceClient { * A fully-qualified path representing project_channel_descriptor resource. * @returns {string} A string representing the project. */ - matchProjectFromProjectChannelDescriptorName(projectChannelDescriptorName: string) { - return this.pathTemplates.projectChannelDescriptorPathTemplate.match(projectChannelDescriptorName).project; + matchProjectFromProjectChannelDescriptorName( + projectChannelDescriptorName: string, + ) { + return this.pathTemplates.projectChannelDescriptorPathTemplate.match( + projectChannelDescriptorName, + ).project; } /** @@ -2430,8 +3047,12 @@ export class ServiceMonitoringServiceClient { * A fully-qualified path representing project_channel_descriptor resource. * @returns {string} A string representing the channel_descriptor. */ - matchChannelDescriptorFromProjectChannelDescriptorName(projectChannelDescriptorName: string) { - return this.pathTemplates.projectChannelDescriptorPathTemplate.match(projectChannelDescriptorName).channel_descriptor; + matchChannelDescriptorFromProjectChannelDescriptorName( + projectChannelDescriptorName: string, + ) { + return this.pathTemplates.projectChannelDescriptorPathTemplate.match( + projectChannelDescriptorName, + ).channel_descriptor; } /** @@ -2441,7 +3062,7 @@ export class ServiceMonitoringServiceClient { * @param {string} group * @returns {string} Resource name string. */ - projectGroupPath(project:string,group:string) { + projectGroupPath(project: string, group: string) { return this.pathTemplates.projectGroupPathTemplate.render({ project: project, group: group, @@ -2456,7 +3077,8 @@ export class ServiceMonitoringServiceClient { * @returns {string} A string representing the project. */ matchProjectFromProjectGroupName(projectGroupName: string) { - return this.pathTemplates.projectGroupPathTemplate.match(projectGroupName).project; + return this.pathTemplates.projectGroupPathTemplate.match(projectGroupName) + .project; } /** @@ -2467,7 +3089,8 @@ export class ServiceMonitoringServiceClient { * @returns {string} A string representing the group. */ matchGroupFromProjectGroupName(projectGroupName: string) { - return this.pathTemplates.projectGroupPathTemplate.match(projectGroupName).group; + return this.pathTemplates.projectGroupPathTemplate.match(projectGroupName) + .group; } /** @@ -2477,7 +3100,7 @@ export class ServiceMonitoringServiceClient { * @param {string} notification_channel * @returns {string} Resource name string. */ - projectNotificationChannelPath(project:string,notificationChannel:string) { + projectNotificationChannelPath(project: string, notificationChannel: string) { return this.pathTemplates.projectNotificationChannelPathTemplate.render({ project: project, notification_channel: notificationChannel, @@ -2491,8 +3114,12 @@ export class ServiceMonitoringServiceClient { * A fully-qualified path representing project_notification_channel resource. * @returns {string} A string representing the project. */ - matchProjectFromProjectNotificationChannelName(projectNotificationChannelName: string) { - return this.pathTemplates.projectNotificationChannelPathTemplate.match(projectNotificationChannelName).project; + matchProjectFromProjectNotificationChannelName( + projectNotificationChannelName: string, + ) { + return this.pathTemplates.projectNotificationChannelPathTemplate.match( + projectNotificationChannelName, + ).project; } /** @@ -2502,8 +3129,12 @@ export class ServiceMonitoringServiceClient { * A fully-qualified path representing project_notification_channel resource. * @returns {string} A string representing the notification_channel. */ - matchNotificationChannelFromProjectNotificationChannelName(projectNotificationChannelName: string) { - return this.pathTemplates.projectNotificationChannelPathTemplate.match(projectNotificationChannelName).notification_channel; + matchNotificationChannelFromProjectNotificationChannelName( + projectNotificationChannelName: string, + ) { + return this.pathTemplates.projectNotificationChannelPathTemplate.match( + projectNotificationChannelName, + ).notification_channel; } /** @@ -2513,7 +3144,7 @@ export class ServiceMonitoringServiceClient { * @param {string} service * @returns {string} Resource name string. */ - projectServicePath(project:string,service:string) { + projectServicePath(project: string, service: string) { return this.pathTemplates.projectServicePathTemplate.render({ project: project, service: service, @@ -2528,7 +3159,9 @@ export class ServiceMonitoringServiceClient { * @returns {string} A string representing the project. */ matchProjectFromProjectServiceName(projectServiceName: string) { - return this.pathTemplates.projectServicePathTemplate.match(projectServiceName).project; + return this.pathTemplates.projectServicePathTemplate.match( + projectServiceName, + ).project; } /** @@ -2539,7 +3172,9 @@ export class ServiceMonitoringServiceClient { * @returns {string} A string representing the service. */ matchServiceFromProjectServiceName(projectServiceName: string) { - return this.pathTemplates.projectServicePathTemplate.match(projectServiceName).service; + return this.pathTemplates.projectServicePathTemplate.match( + projectServiceName, + ).service; } /** @@ -2550,12 +3185,18 @@ export class ServiceMonitoringServiceClient { * @param {string} service_level_objective * @returns {string} Resource name string. */ - projectServiceServiceLevelObjectivePath(project:string,service:string,serviceLevelObjective:string) { - return this.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.render({ - project: project, - service: service, - service_level_objective: serviceLevelObjective, - }); + projectServiceServiceLevelObjectivePath( + project: string, + service: string, + serviceLevelObjective: string, + ) { + return this.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.render( + { + project: project, + service: service, + service_level_objective: serviceLevelObjective, + }, + ); } /** @@ -2565,8 +3206,12 @@ export class ServiceMonitoringServiceClient { * A fully-qualified path representing project_service_service_level_objective resource. * @returns {string} A string representing the project. */ - matchProjectFromProjectServiceServiceLevelObjectiveName(projectServiceServiceLevelObjectiveName: string) { - return this.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match(projectServiceServiceLevelObjectiveName).project; + matchProjectFromProjectServiceServiceLevelObjectiveName( + projectServiceServiceLevelObjectiveName: string, + ) { + return this.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match( + projectServiceServiceLevelObjectiveName, + ).project; } /** @@ -2576,8 +3221,12 @@ export class ServiceMonitoringServiceClient { * A fully-qualified path representing project_service_service_level_objective resource. * @returns {string} A string representing the service. */ - matchServiceFromProjectServiceServiceLevelObjectiveName(projectServiceServiceLevelObjectiveName: string) { - return this.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match(projectServiceServiceLevelObjectiveName).service; + matchServiceFromProjectServiceServiceLevelObjectiveName( + projectServiceServiceLevelObjectiveName: string, + ) { + return this.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match( + projectServiceServiceLevelObjectiveName, + ).service; } /** @@ -2587,8 +3236,12 @@ export class ServiceMonitoringServiceClient { * A fully-qualified path representing project_service_service_level_objective resource. * @returns {string} A string representing the service_level_objective. */ - matchServiceLevelObjectiveFromProjectServiceServiceLevelObjectiveName(projectServiceServiceLevelObjectiveName: string) { - return this.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match(projectServiceServiceLevelObjectiveName).service_level_objective; + matchServiceLevelObjectiveFromProjectServiceServiceLevelObjectiveName( + projectServiceServiceLevelObjectiveName: string, + ) { + return this.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match( + projectServiceServiceLevelObjectiveName, + ).service_level_objective; } /** @@ -2598,7 +3251,7 @@ export class ServiceMonitoringServiceClient { * @param {string} uptime_check_config * @returns {string} Resource name string. */ - projectUptimeCheckConfigPath(project:string,uptimeCheckConfig:string) { + projectUptimeCheckConfigPath(project: string, uptimeCheckConfig: string) { return this.pathTemplates.projectUptimeCheckConfigPathTemplate.render({ project: project, uptime_check_config: uptimeCheckConfig, @@ -2612,8 +3265,12 @@ export class ServiceMonitoringServiceClient { * A fully-qualified path representing project_uptime_check_config resource. * @returns {string} A string representing the project. */ - matchProjectFromProjectUptimeCheckConfigName(projectUptimeCheckConfigName: string) { - return this.pathTemplates.projectUptimeCheckConfigPathTemplate.match(projectUptimeCheckConfigName).project; + matchProjectFromProjectUptimeCheckConfigName( + projectUptimeCheckConfigName: string, + ) { + return this.pathTemplates.projectUptimeCheckConfigPathTemplate.match( + projectUptimeCheckConfigName, + ).project; } /** @@ -2623,8 +3280,12 @@ export class ServiceMonitoringServiceClient { * A fully-qualified path representing project_uptime_check_config resource. * @returns {string} A string representing the uptime_check_config. */ - matchUptimeCheckConfigFromProjectUptimeCheckConfigName(projectUptimeCheckConfigName: string) { - return this.pathTemplates.projectUptimeCheckConfigPathTemplate.match(projectUptimeCheckConfigName).uptime_check_config; + matchUptimeCheckConfigFromProjectUptimeCheckConfigName( + projectUptimeCheckConfigName: string, + ) { + return this.pathTemplates.projectUptimeCheckConfigPathTemplate.match( + projectUptimeCheckConfigName, + ).uptime_check_config; } /** @@ -2635,7 +3296,7 @@ export class ServiceMonitoringServiceClient { */ close(): Promise { if (this.serviceMonitoringServiceStub && !this._terminated) { - return this.serviceMonitoringServiceStub.then(stub => { + return this.serviceMonitoringServiceStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -2643,4 +3304,4 @@ export class ServiceMonitoringServiceClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/core/generator/gapic-generator-typescript/baselines/monitoring-esm/esm/src/v3/uptime_check_service_client.ts.baseline b/core/generator/gapic-generator-typescript/baselines/monitoring-esm/esm/src/v3/uptime_check_service_client.ts.baseline index 4e00f5f15bd1..95cd138ef155 100644 --- a/core/generator/gapic-generator-typescript/baselines/monitoring-esm/esm/src/v3/uptime_check_service_client.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/monitoring-esm/esm/src/v3/uptime_check_service_client.ts.baseline @@ -18,15 +18,22 @@ /* global window */ import * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions, PaginationCallback, GaxCall} from 'google-gax'; -import {Transform} from 'stream'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + PaginationCallback, + GaxCall, +} from 'google-gax'; +import { Transform } from 'stream'; // @ts-ignore import type * as protos from '../../../protos/protos.js'; import * as uptime_check_service_client_config from './uptime_check_service_client_config.json'; import fs from 'fs'; import path from 'path'; -import {fileURLToPath} from 'url'; -import {getJSON} from '../json-helper.cjs'; +import { fileURLToPath } from 'url'; +import { getJSON } from '../json-helper.cjs'; // @ts-ignore const dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -36,15 +43,15 @@ const dirname = path.dirname(fileURLToPath(import.meta.url)); * This file defines retry strategy and timeouts for all API methods in this library. */ const gapicConfig = getJSON( - path.join(dirname, 'uptime_check_service_client_config.json') + path.join(dirname, 'uptime_check_service_client_config.json'), ); const jsonProtos = getJSON( - path.join(dirname, '..', '..', '..', 'protos/protos.json') + path.join(dirname, '..', '..', '..', 'protos/protos.json'), ); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; const version = getJSON( - path.join(dirname, '..', '..', '..', '..', 'package.json') + path.join(dirname, '..', '..', '..', '..', 'package.json'), ).version; /** @@ -66,7 +73,7 @@ export class UptimeCheckServiceClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('monitoring'); @@ -78,9 +85,9 @@ export class UptimeCheckServiceClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; - uptimeCheckServiceStub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; + uptimeCheckServiceStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of UptimeCheckServiceClient. @@ -122,21 +129,42 @@ export class UptimeCheckServiceClient { * const client = new UptimeCheckServiceClient({fallback: 'rest'}, gax); * ``` */ - constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { // Ensure that options include all the required fields. const staticMembers = this.constructor as typeof UptimeCheckServiceClient; - if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { - throw new Error('Please set either universe_domain or universeDomain, but not both.'); + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); } - const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; - this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; this._servicePath = 'monitoring.' + this._universeDomain; - const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; - const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. if (servicePath !== this._servicePath && !('scopes' in opts)) { @@ -158,7 +186,7 @@ export class UptimeCheckServiceClient { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; @@ -175,10 +203,7 @@ export class UptimeCheckServiceClient { const isEsm = true; const isEsmString = isEsm ? '-esm' : '-cjs'; // Determine the client header string. - const clientHeader = [ - `gax/${this._gaxModule.version}`, - `gapic/${version}`, - ]; + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/{process.versions.node}${isEsmString}`); } else { @@ -186,7 +211,7 @@ export class UptimeCheckServiceClient { } if (!opts.fallback) { clientHeader.push(`grpc/${this._gaxGrpc.grpcVersion}`); - } else if (opts.fallback === 'rest' ) { + } else if (opts.fallback === 'rest') { clientHeader.push(`rest/${this._gaxGrpc.grpcVersion}`); } if (opts.libName && opts.libVersion) { @@ -194,83 +219,92 @@ export class UptimeCheckServiceClient { } // Load the applicable protos. - this._protos = this._gaxGrpc.loadProtoJSON(jsonProtos as gax.protobuf.INamespace); + this._protos = this._gaxGrpc.loadProtoJSON( + jsonProtos as gax.protobuf.INamespace, + ); // This API contains "path templates"; forward-slash-separated // identifiers to uniquely identify resources within the API. // Create useful helper objects for these. this.pathTemplates = { folderAlertPolicyPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/alertPolicies/{alert_policy}' + 'folders/{folder}/alertPolicies/{alert_policy}', ), folderAlertPolicyConditionPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/alertPolicies/{alert_policy}/conditions/{condition}' + 'folders/{folder}/alertPolicies/{alert_policy}/conditions/{condition}', ), folderChannelDescriptorPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/notificationChannelDescriptors/{channel_descriptor}' + 'folders/{folder}/notificationChannelDescriptors/{channel_descriptor}', ), folderGroupPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/groups/{group}' + 'folders/{folder}/groups/{group}', ), folderNotificationChannelPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/notificationChannels/{notification_channel}' + 'folders/{folder}/notificationChannels/{notification_channel}', ), folderServicePathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/services/{service}' - ), - folderServiceServiceLevelObjectivePathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/services/{service}/serviceLevelObjectives/{service_level_objective}' + 'folders/{folder}/services/{service}', ), + folderServiceServiceLevelObjectivePathTemplate: + new this._gaxModule.PathTemplate( + 'folders/{folder}/services/{service}/serviceLevelObjectives/{service_level_objective}', + ), folderUptimeCheckConfigPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/uptimeCheckConfigs/{uptime_check_config}' + 'folders/{folder}/uptimeCheckConfigs/{uptime_check_config}', ), organizationAlertPolicyPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/alertPolicies/{alert_policy}' - ), - organizationAlertPolicyConditionPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/alertPolicies/{alert_policy}/conditions/{condition}' - ), - organizationChannelDescriptorPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/notificationChannelDescriptors/{channel_descriptor}' + 'organizations/{organization}/alertPolicies/{alert_policy}', ), + organizationAlertPolicyConditionPathTemplate: + new this._gaxModule.PathTemplate( + 'organizations/{organization}/alertPolicies/{alert_policy}/conditions/{condition}', + ), + organizationChannelDescriptorPathTemplate: + new this._gaxModule.PathTemplate( + 'organizations/{organization}/notificationChannelDescriptors/{channel_descriptor}', + ), organizationGroupPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/groups/{group}' - ), - organizationNotificationChannelPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/notificationChannels/{notification_channel}' + 'organizations/{organization}/groups/{group}', ), + organizationNotificationChannelPathTemplate: + new this._gaxModule.PathTemplate( + 'organizations/{organization}/notificationChannels/{notification_channel}', + ), organizationServicePathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/services/{service}' - ), - organizationServiceServiceLevelObjectivePathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/services/{service}/serviceLevelObjectives/{service_level_objective}' - ), - organizationUptimeCheckConfigPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/uptimeCheckConfigs/{uptime_check_config}' + 'organizations/{organization}/services/{service}', ), + organizationServiceServiceLevelObjectivePathTemplate: + new this._gaxModule.PathTemplate( + 'organizations/{organization}/services/{service}/serviceLevelObjectives/{service_level_objective}', + ), + organizationUptimeCheckConfigPathTemplate: + new this._gaxModule.PathTemplate( + 'organizations/{organization}/uptimeCheckConfigs/{uptime_check_config}', + ), projectAlertPolicyPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/alertPolicies/{alert_policy}' + 'projects/{project}/alertPolicies/{alert_policy}', ), projectAlertPolicyConditionPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/alertPolicies/{alert_policy}/conditions/{condition}' + 'projects/{project}/alertPolicies/{alert_policy}/conditions/{condition}', ), projectChannelDescriptorPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/notificationChannelDescriptors/{channel_descriptor}' + 'projects/{project}/notificationChannelDescriptors/{channel_descriptor}', ), projectGroupPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/groups/{group}' + 'projects/{project}/groups/{group}', ), projectNotificationChannelPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/notificationChannels/{notification_channel}' + 'projects/{project}/notificationChannels/{notification_channel}', ), projectServicePathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/services/{service}' - ), - projectServiceServiceLevelObjectivePathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/services/{service}/serviceLevelObjectives/{service_level_objective}' + 'projects/{project}/services/{service}', ), + projectServiceServiceLevelObjectivePathTemplate: + new this._gaxModule.PathTemplate( + 'projects/{project}/services/{service}/serviceLevelObjectives/{service_level_objective}', + ), projectUptimeCheckConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/uptimeCheckConfigs/{uptime_check_config}' + 'projects/{project}/uptimeCheckConfigs/{uptime_check_config}', ), }; @@ -278,16 +312,25 @@ export class UptimeCheckServiceClient { // (e.g. 50 results at a time, with tokens to get subsequent // pages). Denote the keys used for pagination and results. this.descriptors.page = { - listUptimeCheckConfigs: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'uptimeCheckConfigs'), - listUptimeCheckIps: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'uptimeCheckIps') + listUptimeCheckConfigs: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'uptimeCheckConfigs', + ), + listUptimeCheckIps: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'uptimeCheckIps', + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.monitoring.v3.UptimeCheckService', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.monitoring.v3.UptimeCheckService', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + { 'x-goog-api-client': clientHeader.join(' ') }, + ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -318,37 +361,47 @@ export class UptimeCheckServiceClient { // Put together the "service stub" for // google.monitoring.v3.UptimeCheckService. this.uptimeCheckServiceStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.monitoring.v3.UptimeCheckService') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.monitoring.v3.UptimeCheckService', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.monitoring.v3.UptimeCheckService, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts, + this._providedCustomServicePath, + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const uptimeCheckServiceStubMethods = - ['listUptimeCheckConfigs', 'getUptimeCheckConfig', 'createUptimeCheckConfig', 'updateUptimeCheckConfig', 'deleteUptimeCheckConfig', 'listUptimeCheckIps']; + const uptimeCheckServiceStubMethods = [ + 'listUptimeCheckConfigs', + 'getUptimeCheckConfig', + 'createUptimeCheckConfig', + 'updateUptimeCheckConfig', + 'deleteUptimeCheckConfig', + 'listUptimeCheckIps', + ]; for (const methodName of uptimeCheckServiceStubMethods) { const callPromise = this.uptimeCheckServiceStub.then( - stub => (...args: Array<{}>) => { - if (this._terminated) { - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error|null|undefined) => () => { + (stub) => + (...args: Array<{}>) => { + if (this._terminated) { + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { throw err; - }); + }, + ); - const descriptor = - this.descriptors.page[methodName] || - undefined; + const descriptor = this.descriptors.page[methodName] || undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -363,8 +416,14 @@ export class UptimeCheckServiceClient { * @returns {string} The DNS address for this service. */ static get servicePath() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'monitoring.googleapis.com'; } @@ -376,8 +435,14 @@ export class UptimeCheckServiceClient { * @returns {string} The DNS address for this service. */ static get apiEndpoint() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'monitoring.googleapis.com'; } @@ -411,7 +476,7 @@ export class UptimeCheckServiceClient { return [ 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/monitoring', - 'https://www.googleapis.com/auth/monitoring.read' + 'https://www.googleapis.com/auth/monitoring.read', ]; } @@ -421,8 +486,9 @@ export class UptimeCheckServiceClient { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId(callback?: Callback): - Promise|void { + getProjectId( + callback?: Callback, + ): Promise | void { if (callback) { this.auth.getProjectId(callback); return; @@ -433,492 +499,690 @@ export class UptimeCheckServiceClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Gets a single Uptime check configuration. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The Uptime check configuration to retrieve. The format - * is `projects/[PROJECT_ID]/uptimeCheckConfigs/[UPTIME_CHECK_ID]`. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.monitoring.v3.UptimeCheckConfig|UptimeCheckConfig}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v3/uptime_check_service.get_uptime_check_config.js - * region_tag:monitoring_v3_generated_UptimeCheckService_GetUptimeCheckConfig_async - */ + /** + * Gets a single Uptime check configuration. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The Uptime check configuration to retrieve. The format + * is `projects/[PROJECT_ID]/uptimeCheckConfigs/[UPTIME_CHECK_ID]`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.monitoring.v3.UptimeCheckConfig|UptimeCheckConfig}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v3/uptime_check_service.get_uptime_check_config.js + * region_tag:monitoring_v3_generated_UptimeCheckService_GetUptimeCheckConfig_async + */ getUptimeCheckConfig( - request?: protos.google.monitoring.v3.IGetUptimeCheckConfigRequest, - options?: CallOptions): - Promise<[ - protos.google.monitoring.v3.IUptimeCheckConfig, - protos.google.monitoring.v3.IGetUptimeCheckConfigRequest|undefined, {}|undefined - ]>; + request?: protos.google.monitoring.v3.IGetUptimeCheckConfigRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.monitoring.v3.IUptimeCheckConfig, + protos.google.monitoring.v3.IGetUptimeCheckConfigRequest | undefined, + {} | undefined, + ] + >; getUptimeCheckConfig( - request: protos.google.monitoring.v3.IGetUptimeCheckConfigRequest, - options: CallOptions, - callback: Callback< - protos.google.monitoring.v3.IUptimeCheckConfig, - protos.google.monitoring.v3.IGetUptimeCheckConfigRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.IGetUptimeCheckConfigRequest, + options: CallOptions, + callback: Callback< + protos.google.monitoring.v3.IUptimeCheckConfig, + | protos.google.monitoring.v3.IGetUptimeCheckConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getUptimeCheckConfig( - request: protos.google.monitoring.v3.IGetUptimeCheckConfigRequest, - callback: Callback< - protos.google.monitoring.v3.IUptimeCheckConfig, - protos.google.monitoring.v3.IGetUptimeCheckConfigRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.IGetUptimeCheckConfigRequest, + callback: Callback< + protos.google.monitoring.v3.IUptimeCheckConfig, + | protos.google.monitoring.v3.IGetUptimeCheckConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getUptimeCheckConfig( - request?: protos.google.monitoring.v3.IGetUptimeCheckConfigRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.monitoring.v3.IUptimeCheckConfig, - protos.google.monitoring.v3.IGetUptimeCheckConfigRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.monitoring.v3.IGetUptimeCheckConfigRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.monitoring.v3.IUptimeCheckConfig, - protos.google.monitoring.v3.IGetUptimeCheckConfigRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.monitoring.v3.IUptimeCheckConfig, - protos.google.monitoring.v3.IGetUptimeCheckConfigRequest|undefined, {}|undefined - ]>|void { + | protos.google.monitoring.v3.IGetUptimeCheckConfigRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.monitoring.v3.IUptimeCheckConfig, + | protos.google.monitoring.v3.IGetUptimeCheckConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.monitoring.v3.IUptimeCheckConfig, + protos.google.monitoring.v3.IGetUptimeCheckConfigRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getUptimeCheckConfig request %j', request); - const wrappedCallback: Callback< - protos.google.monitoring.v3.IUptimeCheckConfig, - protos.google.monitoring.v3.IGetUptimeCheckConfigRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.monitoring.v3.IUptimeCheckConfig, + | protos.google.monitoring.v3.IGetUptimeCheckConfigRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getUptimeCheckConfig response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.getUptimeCheckConfig(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.monitoring.v3.IUptimeCheckConfig, - protos.google.monitoring.v3.IGetUptimeCheckConfigRequest|undefined, {}|undefined - ]) => { - this._log.info('getUptimeCheckConfig response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getUptimeCheckConfig(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.monitoring.v3.IUptimeCheckConfig, + protos.google.monitoring.v3.IGetUptimeCheckConfigRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getUptimeCheckConfig response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Creates a new Uptime check configuration. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The project in which to create the Uptime check. The format - * is `projects/[PROJECT_ID]`. - * @param {google.monitoring.v3.UptimeCheckConfig} request.uptimeCheckConfig - * Required. The new Uptime check configuration. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.monitoring.v3.UptimeCheckConfig|UptimeCheckConfig}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v3/uptime_check_service.create_uptime_check_config.js - * region_tag:monitoring_v3_generated_UptimeCheckService_CreateUptimeCheckConfig_async - */ + /** + * Creates a new Uptime check configuration. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The project in which to create the Uptime check. The format + * is `projects/[PROJECT_ID]`. + * @param {google.monitoring.v3.UptimeCheckConfig} request.uptimeCheckConfig + * Required. The new Uptime check configuration. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.monitoring.v3.UptimeCheckConfig|UptimeCheckConfig}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v3/uptime_check_service.create_uptime_check_config.js + * region_tag:monitoring_v3_generated_UptimeCheckService_CreateUptimeCheckConfig_async + */ createUptimeCheckConfig( - request?: protos.google.monitoring.v3.ICreateUptimeCheckConfigRequest, - options?: CallOptions): - Promise<[ - protos.google.monitoring.v3.IUptimeCheckConfig, - protos.google.monitoring.v3.ICreateUptimeCheckConfigRequest|undefined, {}|undefined - ]>; + request?: protos.google.monitoring.v3.ICreateUptimeCheckConfigRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.monitoring.v3.IUptimeCheckConfig, + protos.google.monitoring.v3.ICreateUptimeCheckConfigRequest | undefined, + {} | undefined, + ] + >; createUptimeCheckConfig( - request: protos.google.monitoring.v3.ICreateUptimeCheckConfigRequest, - options: CallOptions, - callback: Callback< - protos.google.monitoring.v3.IUptimeCheckConfig, - protos.google.monitoring.v3.ICreateUptimeCheckConfigRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.ICreateUptimeCheckConfigRequest, + options: CallOptions, + callback: Callback< + protos.google.monitoring.v3.IUptimeCheckConfig, + | protos.google.monitoring.v3.ICreateUptimeCheckConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createUptimeCheckConfig( - request: protos.google.monitoring.v3.ICreateUptimeCheckConfigRequest, - callback: Callback< - protos.google.monitoring.v3.IUptimeCheckConfig, - protos.google.monitoring.v3.ICreateUptimeCheckConfigRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.ICreateUptimeCheckConfigRequest, + callback: Callback< + protos.google.monitoring.v3.IUptimeCheckConfig, + | protos.google.monitoring.v3.ICreateUptimeCheckConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createUptimeCheckConfig( - request?: protos.google.monitoring.v3.ICreateUptimeCheckConfigRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.monitoring.v3.IUptimeCheckConfig, - protos.google.monitoring.v3.ICreateUptimeCheckConfigRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.monitoring.v3.ICreateUptimeCheckConfigRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.monitoring.v3.IUptimeCheckConfig, - protos.google.monitoring.v3.ICreateUptimeCheckConfigRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.monitoring.v3.IUptimeCheckConfig, - protos.google.monitoring.v3.ICreateUptimeCheckConfigRequest|undefined, {}|undefined - ]>|void { + | protos.google.monitoring.v3.ICreateUptimeCheckConfigRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.monitoring.v3.IUptimeCheckConfig, + | protos.google.monitoring.v3.ICreateUptimeCheckConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.monitoring.v3.IUptimeCheckConfig, + protos.google.monitoring.v3.ICreateUptimeCheckConfigRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('createUptimeCheckConfig request %j', request); - const wrappedCallback: Callback< - protos.google.monitoring.v3.IUptimeCheckConfig, - protos.google.monitoring.v3.ICreateUptimeCheckConfigRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.monitoring.v3.IUptimeCheckConfig, + | protos.google.monitoring.v3.ICreateUptimeCheckConfigRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createUptimeCheckConfig response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.createUptimeCheckConfig(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.monitoring.v3.IUptimeCheckConfig, - protos.google.monitoring.v3.ICreateUptimeCheckConfigRequest|undefined, {}|undefined - ]) => { - this._log.info('createUptimeCheckConfig response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createUptimeCheckConfig(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.monitoring.v3.IUptimeCheckConfig, + ( + | protos.google.monitoring.v3.ICreateUptimeCheckConfigRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('createUptimeCheckConfig response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Updates an Uptime check configuration. You can either replace the entire - * configuration with a new one or replace only certain fields in the current - * configuration by specifying the fields to be updated via `updateMask`. - * Returns the updated configuration. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.protobuf.FieldMask} request.updateMask - * Optional. If present, only the listed fields in the current Uptime check - * configuration are updated with values from the new configuration. If this - * field is empty, then the current configuration is completely replaced with - * the new configuration. - * @param {google.monitoring.v3.UptimeCheckConfig} request.uptimeCheckConfig - * Required. If an `updateMask` has been specified, this field gives - * the values for the set of fields mentioned in the `updateMask`. If an - * `updateMask` has not been given, this Uptime check configuration replaces - * the current configuration. If a field is mentioned in `updateMask` but - * the corresonding field is omitted in this partial Uptime check - * configuration, it has the effect of deleting/clearing the field from the - * configuration on the server. - * - * The following fields can be updated: `display_name`, - * `http_check`, `tcp_check`, `timeout`, `content_matchers`, and - * `selected_regions`. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.monitoring.v3.UptimeCheckConfig|UptimeCheckConfig}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v3/uptime_check_service.update_uptime_check_config.js - * region_tag:monitoring_v3_generated_UptimeCheckService_UpdateUptimeCheckConfig_async - */ + /** + * Updates an Uptime check configuration. You can either replace the entire + * configuration with a new one or replace only certain fields in the current + * configuration by specifying the fields to be updated via `updateMask`. + * Returns the updated configuration. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.protobuf.FieldMask} request.updateMask + * Optional. If present, only the listed fields in the current Uptime check + * configuration are updated with values from the new configuration. If this + * field is empty, then the current configuration is completely replaced with + * the new configuration. + * @param {google.monitoring.v3.UptimeCheckConfig} request.uptimeCheckConfig + * Required. If an `updateMask` has been specified, this field gives + * the values for the set of fields mentioned in the `updateMask`. If an + * `updateMask` has not been given, this Uptime check configuration replaces + * the current configuration. If a field is mentioned in `updateMask` but + * the corresonding field is omitted in this partial Uptime check + * configuration, it has the effect of deleting/clearing the field from the + * configuration on the server. + * + * The following fields can be updated: `display_name`, + * `http_check`, `tcp_check`, `timeout`, `content_matchers`, and + * `selected_regions`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.monitoring.v3.UptimeCheckConfig|UptimeCheckConfig}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v3/uptime_check_service.update_uptime_check_config.js + * region_tag:monitoring_v3_generated_UptimeCheckService_UpdateUptimeCheckConfig_async + */ updateUptimeCheckConfig( - request?: protos.google.monitoring.v3.IUpdateUptimeCheckConfigRequest, - options?: CallOptions): - Promise<[ - protos.google.monitoring.v3.IUptimeCheckConfig, - protos.google.monitoring.v3.IUpdateUptimeCheckConfigRequest|undefined, {}|undefined - ]>; + request?: protos.google.monitoring.v3.IUpdateUptimeCheckConfigRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.monitoring.v3.IUptimeCheckConfig, + protos.google.monitoring.v3.IUpdateUptimeCheckConfigRequest | undefined, + {} | undefined, + ] + >; updateUptimeCheckConfig( - request: protos.google.monitoring.v3.IUpdateUptimeCheckConfigRequest, - options: CallOptions, - callback: Callback< - protos.google.monitoring.v3.IUptimeCheckConfig, - protos.google.monitoring.v3.IUpdateUptimeCheckConfigRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.IUpdateUptimeCheckConfigRequest, + options: CallOptions, + callback: Callback< + protos.google.monitoring.v3.IUptimeCheckConfig, + | protos.google.monitoring.v3.IUpdateUptimeCheckConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateUptimeCheckConfig( - request: protos.google.monitoring.v3.IUpdateUptimeCheckConfigRequest, - callback: Callback< - protos.google.monitoring.v3.IUptimeCheckConfig, - protos.google.monitoring.v3.IUpdateUptimeCheckConfigRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.IUpdateUptimeCheckConfigRequest, + callback: Callback< + protos.google.monitoring.v3.IUptimeCheckConfig, + | protos.google.monitoring.v3.IUpdateUptimeCheckConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateUptimeCheckConfig( - request?: protos.google.monitoring.v3.IUpdateUptimeCheckConfigRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.monitoring.v3.IUptimeCheckConfig, - protos.google.monitoring.v3.IUpdateUptimeCheckConfigRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.monitoring.v3.IUpdateUptimeCheckConfigRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.monitoring.v3.IUptimeCheckConfig, - protos.google.monitoring.v3.IUpdateUptimeCheckConfigRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.monitoring.v3.IUptimeCheckConfig, - protos.google.monitoring.v3.IUpdateUptimeCheckConfigRequest|undefined, {}|undefined - ]>|void { + | protos.google.monitoring.v3.IUpdateUptimeCheckConfigRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.monitoring.v3.IUptimeCheckConfig, + | protos.google.monitoring.v3.IUpdateUptimeCheckConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.monitoring.v3.IUptimeCheckConfig, + protos.google.monitoring.v3.IUpdateUptimeCheckConfigRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'uptime_check_config.name': request.uptimeCheckConfig!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'uptime_check_config.name': request.uptimeCheckConfig!.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateUptimeCheckConfig request %j', request); - const wrappedCallback: Callback< - protos.google.monitoring.v3.IUptimeCheckConfig, - protos.google.monitoring.v3.IUpdateUptimeCheckConfigRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.monitoring.v3.IUptimeCheckConfig, + | protos.google.monitoring.v3.IUpdateUptimeCheckConfigRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateUptimeCheckConfig response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.updateUptimeCheckConfig(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.monitoring.v3.IUptimeCheckConfig, - protos.google.monitoring.v3.IUpdateUptimeCheckConfigRequest|undefined, {}|undefined - ]) => { - this._log.info('updateUptimeCheckConfig response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateUptimeCheckConfig(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.monitoring.v3.IUptimeCheckConfig, + ( + | protos.google.monitoring.v3.IUpdateUptimeCheckConfigRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('updateUptimeCheckConfig response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Deletes an Uptime check configuration. Note that this method will fail - * if the Uptime check configuration is referenced by an alert policy or - * other dependent configs that would be rendered invalid by the deletion. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The Uptime check configuration to delete. The format - * is `projects/[PROJECT_ID]/uptimeCheckConfigs/[UPTIME_CHECK_ID]`. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v3/uptime_check_service.delete_uptime_check_config.js - * region_tag:monitoring_v3_generated_UptimeCheckService_DeleteUptimeCheckConfig_async - */ + /** + * Deletes an Uptime check configuration. Note that this method will fail + * if the Uptime check configuration is referenced by an alert policy or + * other dependent configs that would be rendered invalid by the deletion. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The Uptime check configuration to delete. The format + * is `projects/[PROJECT_ID]/uptimeCheckConfigs/[UPTIME_CHECK_ID]`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v3/uptime_check_service.delete_uptime_check_config.js + * region_tag:monitoring_v3_generated_UptimeCheckService_DeleteUptimeCheckConfig_async + */ deleteUptimeCheckConfig( - request?: protos.google.monitoring.v3.IDeleteUptimeCheckConfigRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.IDeleteUptimeCheckConfigRequest|undefined, {}|undefined - ]>; + request?: protos.google.monitoring.v3.IDeleteUptimeCheckConfigRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.monitoring.v3.IDeleteUptimeCheckConfigRequest | undefined, + {} | undefined, + ] + >; deleteUptimeCheckConfig( - request: protos.google.monitoring.v3.IDeleteUptimeCheckConfigRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.IDeleteUptimeCheckConfigRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.IDeleteUptimeCheckConfigRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.monitoring.v3.IDeleteUptimeCheckConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteUptimeCheckConfig( - request: protos.google.monitoring.v3.IDeleteUptimeCheckConfigRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.IDeleteUptimeCheckConfigRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.IDeleteUptimeCheckConfigRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.monitoring.v3.IDeleteUptimeCheckConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteUptimeCheckConfig( - request?: protos.google.monitoring.v3.IDeleteUptimeCheckConfigRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.IDeleteUptimeCheckConfigRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.monitoring.v3.IDeleteUptimeCheckConfigRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.IDeleteUptimeCheckConfigRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.IDeleteUptimeCheckConfigRequest|undefined, {}|undefined - ]>|void { + | protos.google.monitoring.v3.IDeleteUptimeCheckConfigRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + | protos.google.monitoring.v3.IDeleteUptimeCheckConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.monitoring.v3.IDeleteUptimeCheckConfigRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('deleteUptimeCheckConfig request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.IDeleteUptimeCheckConfigRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.monitoring.v3.IDeleteUptimeCheckConfigRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteUptimeCheckConfig response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.deleteUptimeCheckConfig(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.IDeleteUptimeCheckConfigRequest|undefined, {}|undefined - ]) => { - this._log.info('deleteUptimeCheckConfig response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteUptimeCheckConfig(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + ( + | protos.google.monitoring.v3.IDeleteUptimeCheckConfigRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('deleteUptimeCheckConfig response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } - /** - * Lists the existing valid Uptime check configurations for the project - * (leaving out any invalid configurations). - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The project whose Uptime check configurations are listed. The format - * is `projects/[PROJECT_ID]`. - * @param {number} request.pageSize - * The maximum number of results to return in a single response. The server - * may further constrain the maximum number of results returned in a single - * page. If the page_size is <=0, the server will decide the number of results - * to be returned. - * @param {string} request.pageToken - * If this field is not empty then it must contain the `nextPageToken` value - * returned by a previous call to this method. Using this field causes the - * method to return more results from the previous method call. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.monitoring.v3.UptimeCheckConfig|UptimeCheckConfig}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `listUptimeCheckConfigsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Lists the existing valid Uptime check configurations for the project + * (leaving out any invalid configurations). + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The project whose Uptime check configurations are listed. The format + * is `projects/[PROJECT_ID]`. + * @param {number} request.pageSize + * The maximum number of results to return in a single response. The server + * may further constrain the maximum number of results returned in a single + * page. If the page_size is <=0, the server will decide the number of results + * to be returned. + * @param {string} request.pageToken + * If this field is not empty then it must contain the `nextPageToken` value + * returned by a previous call to this method. Using this field causes the + * method to return more results from the previous method call. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.monitoring.v3.UptimeCheckConfig|UptimeCheckConfig}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listUptimeCheckConfigsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listUptimeCheckConfigs( - request?: protos.google.monitoring.v3.IListUptimeCheckConfigsRequest, - options?: CallOptions): - Promise<[ - protos.google.monitoring.v3.IUptimeCheckConfig[], - protos.google.monitoring.v3.IListUptimeCheckConfigsRequest|null, - protos.google.monitoring.v3.IListUptimeCheckConfigsResponse - ]>; + request?: protos.google.monitoring.v3.IListUptimeCheckConfigsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.monitoring.v3.IUptimeCheckConfig[], + protos.google.monitoring.v3.IListUptimeCheckConfigsRequest | null, + protos.google.monitoring.v3.IListUptimeCheckConfigsResponse, + ] + >; listUptimeCheckConfigs( - request: protos.google.monitoring.v3.IListUptimeCheckConfigsRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.monitoring.v3.IListUptimeCheckConfigsRequest, - protos.google.monitoring.v3.IListUptimeCheckConfigsResponse|null|undefined, - protos.google.monitoring.v3.IUptimeCheckConfig>): void; + request: protos.google.monitoring.v3.IListUptimeCheckConfigsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.monitoring.v3.IListUptimeCheckConfigsRequest, + | protos.google.monitoring.v3.IListUptimeCheckConfigsResponse + | null + | undefined, + protos.google.monitoring.v3.IUptimeCheckConfig + >, + ): void; listUptimeCheckConfigs( - request: protos.google.monitoring.v3.IListUptimeCheckConfigsRequest, - callback: PaginationCallback< - protos.google.monitoring.v3.IListUptimeCheckConfigsRequest, - protos.google.monitoring.v3.IListUptimeCheckConfigsResponse|null|undefined, - protos.google.monitoring.v3.IUptimeCheckConfig>): void; + request: protos.google.monitoring.v3.IListUptimeCheckConfigsRequest, + callback: PaginationCallback< + protos.google.monitoring.v3.IListUptimeCheckConfigsRequest, + | protos.google.monitoring.v3.IListUptimeCheckConfigsResponse + | null + | undefined, + protos.google.monitoring.v3.IUptimeCheckConfig + >, + ): void; listUptimeCheckConfigs( - request?: protos.google.monitoring.v3.IListUptimeCheckConfigsRequest, - optionsOrCallback?: CallOptions|PaginationCallback< - protos.google.monitoring.v3.IListUptimeCheckConfigsRequest, - protos.google.monitoring.v3.IListUptimeCheckConfigsResponse|null|undefined, - protos.google.monitoring.v3.IUptimeCheckConfig>, - callback?: PaginationCallback< + request?: protos.google.monitoring.v3.IListUptimeCheckConfigsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.monitoring.v3.IListUptimeCheckConfigsRequest, - protos.google.monitoring.v3.IListUptimeCheckConfigsResponse|null|undefined, - protos.google.monitoring.v3.IUptimeCheckConfig>): - Promise<[ - protos.google.monitoring.v3.IUptimeCheckConfig[], - protos.google.monitoring.v3.IListUptimeCheckConfigsRequest|null, - protos.google.monitoring.v3.IListUptimeCheckConfigsResponse - ]>|void { + | protos.google.monitoring.v3.IListUptimeCheckConfigsResponse + | null + | undefined, + protos.google.monitoring.v3.IUptimeCheckConfig + >, + callback?: PaginationCallback< + protos.google.monitoring.v3.IListUptimeCheckConfigsRequest, + | protos.google.monitoring.v3.IListUptimeCheckConfigsResponse + | null + | undefined, + protos.google.monitoring.v3.IUptimeCheckConfig + >, + ): Promise< + [ + protos.google.monitoring.v3.IUptimeCheckConfig[], + protos.google.monitoring.v3.IListUptimeCheckConfigsRequest | null, + protos.google.monitoring.v3.IListUptimeCheckConfigsResponse, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.monitoring.v3.IListUptimeCheckConfigsRequest, - protos.google.monitoring.v3.IListUptimeCheckConfigsResponse|null|undefined, - protos.google.monitoring.v3.IUptimeCheckConfig>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.monitoring.v3.IListUptimeCheckConfigsRequest, + | protos.google.monitoring.v3.IListUptimeCheckConfigsResponse + | null + | undefined, + protos.google.monitoring.v3.IUptimeCheckConfig + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listUptimeCheckConfigs values %j', values); callback!(error, values, nextPageRequest, rawResponse); @@ -927,201 +1191,231 @@ export class UptimeCheckServiceClient { this._log.info('listUptimeCheckConfigs request %j', request); return this.innerApiCalls .listUptimeCheckConfigs(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.monitoring.v3.IUptimeCheckConfig[], - protos.google.monitoring.v3.IListUptimeCheckConfigsRequest|null, - protos.google.monitoring.v3.IListUptimeCheckConfigsResponse - ]) => { - this._log.info('listUptimeCheckConfigs values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.monitoring.v3.IUptimeCheckConfig[], + protos.google.monitoring.v3.IListUptimeCheckConfigsRequest | null, + protos.google.monitoring.v3.IListUptimeCheckConfigsResponse, + ]) => { + this._log.info('listUptimeCheckConfigs values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listUptimeCheckConfigs`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The project whose Uptime check configurations are listed. The format - * is `projects/[PROJECT_ID]`. - * @param {number} request.pageSize - * The maximum number of results to return in a single response. The server - * may further constrain the maximum number of results returned in a single - * page. If the page_size is <=0, the server will decide the number of results - * to be returned. - * @param {string} request.pageToken - * If this field is not empty then it must contain the `nextPageToken` value - * returned by a previous call to this method. Using this field causes the - * method to return more results from the previous method call. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.monitoring.v3.UptimeCheckConfig|UptimeCheckConfig} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `listUptimeCheckConfigsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `listUptimeCheckConfigs`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The project whose Uptime check configurations are listed. The format + * is `projects/[PROJECT_ID]`. + * @param {number} request.pageSize + * The maximum number of results to return in a single response. The server + * may further constrain the maximum number of results returned in a single + * page. If the page_size is <=0, the server will decide the number of results + * to be returned. + * @param {string} request.pageToken + * If this field is not empty then it must contain the `nextPageToken` value + * returned by a previous call to this method. Using this field causes the + * method to return more results from the previous method call. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.monitoring.v3.UptimeCheckConfig|UptimeCheckConfig} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listUptimeCheckConfigsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listUptimeCheckConfigsStream( - request?: protos.google.monitoring.v3.IListUptimeCheckConfigsRequest, - options?: CallOptions): - Transform{ + request?: protos.google.monitoring.v3.IListUptimeCheckConfigsRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); const defaultCallSettings = this._defaults['listUptimeCheckConfigs']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listUptimeCheckConfigs stream %j', request); return this.descriptors.page.listUptimeCheckConfigs.createStream( this.innerApiCalls.listUptimeCheckConfigs as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listUptimeCheckConfigs`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The project whose Uptime check configurations are listed. The format - * is `projects/[PROJECT_ID]`. - * @param {number} request.pageSize - * The maximum number of results to return in a single response. The server - * may further constrain the maximum number of results returned in a single - * page. If the page_size is <=0, the server will decide the number of results - * to be returned. - * @param {string} request.pageToken - * If this field is not empty then it must contain the `nextPageToken` value - * returned by a previous call to this method. Using this field causes the - * method to return more results from the previous method call. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.monitoring.v3.UptimeCheckConfig|UptimeCheckConfig}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v3/uptime_check_service.list_uptime_check_configs.js - * region_tag:monitoring_v3_generated_UptimeCheckService_ListUptimeCheckConfigs_async - */ + /** + * Equivalent to `listUptimeCheckConfigs`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The project whose Uptime check configurations are listed. The format + * is `projects/[PROJECT_ID]`. + * @param {number} request.pageSize + * The maximum number of results to return in a single response. The server + * may further constrain the maximum number of results returned in a single + * page. If the page_size is <=0, the server will decide the number of results + * to be returned. + * @param {string} request.pageToken + * If this field is not empty then it must contain the `nextPageToken` value + * returned by a previous call to this method. Using this field causes the + * method to return more results from the previous method call. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.monitoring.v3.UptimeCheckConfig|UptimeCheckConfig}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v3/uptime_check_service.list_uptime_check_configs.js + * region_tag:monitoring_v3_generated_UptimeCheckService_ListUptimeCheckConfigs_async + */ listUptimeCheckConfigsAsync( - request?: protos.google.monitoring.v3.IListUptimeCheckConfigsRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.monitoring.v3.IListUptimeCheckConfigsRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); const defaultCallSettings = this._defaults['listUptimeCheckConfigs']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listUptimeCheckConfigs iterate %j', request); return this.descriptors.page.listUptimeCheckConfigs.asyncIterate( this.innerApiCalls['listUptimeCheckConfigs'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } - /** - * Returns the list of IP addresses that checkers run from - * - * @param {Object} request - * The request object that will be sent. - * @param {number} request.pageSize - * The maximum number of results to return in a single response. The server - * may further constrain the maximum number of results returned in a single - * page. If the page_size is <=0, the server will decide the number of results - * to be returned. - * NOTE: this field is not yet implemented - * @param {string} request.pageToken - * If this field is not empty then it must contain the `nextPageToken` value - * returned by a previous call to this method. Using this field causes the - * method to return more results from the previous method call. - * NOTE: this field is not yet implemented - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.monitoring.v3.UptimeCheckIp|UptimeCheckIp}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `listUptimeCheckIpsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Returns the list of IP addresses that checkers run from + * + * @param {Object} request + * The request object that will be sent. + * @param {number} request.pageSize + * The maximum number of results to return in a single response. The server + * may further constrain the maximum number of results returned in a single + * page. If the page_size is <=0, the server will decide the number of results + * to be returned. + * NOTE: this field is not yet implemented + * @param {string} request.pageToken + * If this field is not empty then it must contain the `nextPageToken` value + * returned by a previous call to this method. Using this field causes the + * method to return more results from the previous method call. + * NOTE: this field is not yet implemented + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.monitoring.v3.UptimeCheckIp|UptimeCheckIp}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listUptimeCheckIpsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listUptimeCheckIps( - request?: protos.google.monitoring.v3.IListUptimeCheckIpsRequest, - options?: CallOptions): - Promise<[ - protos.google.monitoring.v3.IUptimeCheckIp[], - protos.google.monitoring.v3.IListUptimeCheckIpsRequest|null, - protos.google.monitoring.v3.IListUptimeCheckIpsResponse - ]>; + request?: protos.google.monitoring.v3.IListUptimeCheckIpsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.monitoring.v3.IUptimeCheckIp[], + protos.google.monitoring.v3.IListUptimeCheckIpsRequest | null, + protos.google.monitoring.v3.IListUptimeCheckIpsResponse, + ] + >; listUptimeCheckIps( - request: protos.google.monitoring.v3.IListUptimeCheckIpsRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.monitoring.v3.IListUptimeCheckIpsRequest, - protos.google.monitoring.v3.IListUptimeCheckIpsResponse|null|undefined, - protos.google.monitoring.v3.IUptimeCheckIp>): void; + request: protos.google.monitoring.v3.IListUptimeCheckIpsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.monitoring.v3.IListUptimeCheckIpsRequest, + | protos.google.monitoring.v3.IListUptimeCheckIpsResponse + | null + | undefined, + protos.google.monitoring.v3.IUptimeCheckIp + >, + ): void; listUptimeCheckIps( - request: protos.google.monitoring.v3.IListUptimeCheckIpsRequest, - callback: PaginationCallback< - protos.google.monitoring.v3.IListUptimeCheckIpsRequest, - protos.google.monitoring.v3.IListUptimeCheckIpsResponse|null|undefined, - protos.google.monitoring.v3.IUptimeCheckIp>): void; + request: protos.google.monitoring.v3.IListUptimeCheckIpsRequest, + callback: PaginationCallback< + protos.google.monitoring.v3.IListUptimeCheckIpsRequest, + | protos.google.monitoring.v3.IListUptimeCheckIpsResponse + | null + | undefined, + protos.google.monitoring.v3.IUptimeCheckIp + >, + ): void; listUptimeCheckIps( - request?: protos.google.monitoring.v3.IListUptimeCheckIpsRequest, - optionsOrCallback?: CallOptions|PaginationCallback< + request?: protos.google.monitoring.v3.IListUptimeCheckIpsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.monitoring.v3.IListUptimeCheckIpsRequest, - protos.google.monitoring.v3.IListUptimeCheckIpsResponse|null|undefined, - protos.google.monitoring.v3.IUptimeCheckIp>, - callback?: PaginationCallback< - protos.google.monitoring.v3.IListUptimeCheckIpsRequest, - protos.google.monitoring.v3.IListUptimeCheckIpsResponse|null|undefined, - protos.google.monitoring.v3.IUptimeCheckIp>): - Promise<[ - protos.google.monitoring.v3.IUptimeCheckIp[], - protos.google.monitoring.v3.IListUptimeCheckIpsRequest|null, - protos.google.monitoring.v3.IListUptimeCheckIpsResponse - ]>|void { + | protos.google.monitoring.v3.IListUptimeCheckIpsResponse + | null + | undefined, + protos.google.monitoring.v3.IUptimeCheckIp + >, + callback?: PaginationCallback< + protos.google.monitoring.v3.IListUptimeCheckIpsRequest, + | protos.google.monitoring.v3.IListUptimeCheckIpsResponse + | null + | undefined, + protos.google.monitoring.v3.IUptimeCheckIp + >, + ): Promise< + [ + protos.google.monitoring.v3.IUptimeCheckIp[], + protos.google.monitoring.v3.IListUptimeCheckIpsRequest | null, + protos.google.monitoring.v3.IListUptimeCheckIpsResponse, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.monitoring.v3.IListUptimeCheckIpsRequest, - protos.google.monitoring.v3.IListUptimeCheckIpsResponse|null|undefined, - protos.google.monitoring.v3.IUptimeCheckIp>|undefined = callback + this.initialize().catch((err) => { + throw err; + }); + const wrappedCallback: + | PaginationCallback< + protos.google.monitoring.v3.IListUptimeCheckIpsRequest, + | protos.google.monitoring.v3.IListUptimeCheckIpsResponse + | null + | undefined, + protos.google.monitoring.v3.IUptimeCheckIp + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listUptimeCheckIps values %j', values); callback!(error, values, nextPageRequest, rawResponse); @@ -1130,106 +1424,112 @@ export class UptimeCheckServiceClient { this._log.info('listUptimeCheckIps request %j', request); return this.innerApiCalls .listUptimeCheckIps(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.monitoring.v3.IUptimeCheckIp[], - protos.google.monitoring.v3.IListUptimeCheckIpsRequest|null, - protos.google.monitoring.v3.IListUptimeCheckIpsResponse - ]) => { - this._log.info('listUptimeCheckIps values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.monitoring.v3.IUptimeCheckIp[], + protos.google.monitoring.v3.IListUptimeCheckIpsRequest | null, + protos.google.monitoring.v3.IListUptimeCheckIpsResponse, + ]) => { + this._log.info('listUptimeCheckIps values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listUptimeCheckIps`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {number} request.pageSize - * The maximum number of results to return in a single response. The server - * may further constrain the maximum number of results returned in a single - * page. If the page_size is <=0, the server will decide the number of results - * to be returned. - * NOTE: this field is not yet implemented - * @param {string} request.pageToken - * If this field is not empty then it must contain the `nextPageToken` value - * returned by a previous call to this method. Using this field causes the - * method to return more results from the previous method call. - * NOTE: this field is not yet implemented - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.monitoring.v3.UptimeCheckIp|UptimeCheckIp} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `listUptimeCheckIpsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `listUptimeCheckIps`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {number} request.pageSize + * The maximum number of results to return in a single response. The server + * may further constrain the maximum number of results returned in a single + * page. If the page_size is <=0, the server will decide the number of results + * to be returned. + * NOTE: this field is not yet implemented + * @param {string} request.pageToken + * If this field is not empty then it must contain the `nextPageToken` value + * returned by a previous call to this method. Using this field causes the + * method to return more results from the previous method call. + * NOTE: this field is not yet implemented + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.monitoring.v3.UptimeCheckIp|UptimeCheckIp} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listUptimeCheckIpsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listUptimeCheckIpsStream( - request?: protos.google.monitoring.v3.IListUptimeCheckIpsRequest, - options?: CallOptions): - Transform{ + request?: protos.google.monitoring.v3.IListUptimeCheckIpsRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; const defaultCallSettings = this._defaults['listUptimeCheckIps']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listUptimeCheckIps stream %j', request); return this.descriptors.page.listUptimeCheckIps.createStream( this.innerApiCalls.listUptimeCheckIps as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listUptimeCheckIps`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {number} request.pageSize - * The maximum number of results to return in a single response. The server - * may further constrain the maximum number of results returned in a single - * page. If the page_size is <=0, the server will decide the number of results - * to be returned. - * NOTE: this field is not yet implemented - * @param {string} request.pageToken - * If this field is not empty then it must contain the `nextPageToken` value - * returned by a previous call to this method. Using this field causes the - * method to return more results from the previous method call. - * NOTE: this field is not yet implemented - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.monitoring.v3.UptimeCheckIp|UptimeCheckIp}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v3/uptime_check_service.list_uptime_check_ips.js - * region_tag:monitoring_v3_generated_UptimeCheckService_ListUptimeCheckIps_async - */ + /** + * Equivalent to `listUptimeCheckIps`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {number} request.pageSize + * The maximum number of results to return in a single response. The server + * may further constrain the maximum number of results returned in a single + * page. If the page_size is <=0, the server will decide the number of results + * to be returned. + * NOTE: this field is not yet implemented + * @param {string} request.pageToken + * If this field is not empty then it must contain the `nextPageToken` value + * returned by a previous call to this method. Using this field causes the + * method to return more results from the previous method call. + * NOTE: this field is not yet implemented + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.monitoring.v3.UptimeCheckIp|UptimeCheckIp}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v3/uptime_check_service.list_uptime_check_ips.js + * region_tag:monitoring_v3_generated_UptimeCheckService_ListUptimeCheckIps_async + */ listUptimeCheckIpsAsync( - request?: protos.google.monitoring.v3.IListUptimeCheckIpsRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.monitoring.v3.IListUptimeCheckIpsRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; const defaultCallSettings = this._defaults['listUptimeCheckIps']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listUptimeCheckIps iterate %j', request); return this.descriptors.page.listUptimeCheckIps.asyncIterate( this.innerApiCalls['listUptimeCheckIps'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } // -------------------- @@ -1243,7 +1543,7 @@ export class UptimeCheckServiceClient { * @param {string} alert_policy * @returns {string} Resource name string. */ - folderAlertPolicyPath(folder:string,alertPolicy:string) { + folderAlertPolicyPath(folder: string, alertPolicy: string) { return this.pathTemplates.folderAlertPolicyPathTemplate.render({ folder: folder, alert_policy: alertPolicy, @@ -1258,7 +1558,9 @@ export class UptimeCheckServiceClient { * @returns {string} A string representing the folder. */ matchFolderFromFolderAlertPolicyName(folderAlertPolicyName: string) { - return this.pathTemplates.folderAlertPolicyPathTemplate.match(folderAlertPolicyName).folder; + return this.pathTemplates.folderAlertPolicyPathTemplate.match( + folderAlertPolicyName, + ).folder; } /** @@ -1269,7 +1571,9 @@ export class UptimeCheckServiceClient { * @returns {string} A string representing the alert_policy. */ matchAlertPolicyFromFolderAlertPolicyName(folderAlertPolicyName: string) { - return this.pathTemplates.folderAlertPolicyPathTemplate.match(folderAlertPolicyName).alert_policy; + return this.pathTemplates.folderAlertPolicyPathTemplate.match( + folderAlertPolicyName, + ).alert_policy; } /** @@ -1280,7 +1584,11 @@ export class UptimeCheckServiceClient { * @param {string} condition * @returns {string} Resource name string. */ - folderAlertPolicyConditionPath(folder:string,alertPolicy:string,condition:string) { + folderAlertPolicyConditionPath( + folder: string, + alertPolicy: string, + condition: string, + ) { return this.pathTemplates.folderAlertPolicyConditionPathTemplate.render({ folder: folder, alert_policy: alertPolicy, @@ -1295,8 +1603,12 @@ export class UptimeCheckServiceClient { * A fully-qualified path representing folder_alert_policy_condition resource. * @returns {string} A string representing the folder. */ - matchFolderFromFolderAlertPolicyConditionName(folderAlertPolicyConditionName: string) { - return this.pathTemplates.folderAlertPolicyConditionPathTemplate.match(folderAlertPolicyConditionName).folder; + matchFolderFromFolderAlertPolicyConditionName( + folderAlertPolicyConditionName: string, + ) { + return this.pathTemplates.folderAlertPolicyConditionPathTemplate.match( + folderAlertPolicyConditionName, + ).folder; } /** @@ -1306,8 +1618,12 @@ export class UptimeCheckServiceClient { * A fully-qualified path representing folder_alert_policy_condition resource. * @returns {string} A string representing the alert_policy. */ - matchAlertPolicyFromFolderAlertPolicyConditionName(folderAlertPolicyConditionName: string) { - return this.pathTemplates.folderAlertPolicyConditionPathTemplate.match(folderAlertPolicyConditionName).alert_policy; + matchAlertPolicyFromFolderAlertPolicyConditionName( + folderAlertPolicyConditionName: string, + ) { + return this.pathTemplates.folderAlertPolicyConditionPathTemplate.match( + folderAlertPolicyConditionName, + ).alert_policy; } /** @@ -1317,8 +1633,12 @@ export class UptimeCheckServiceClient { * A fully-qualified path representing folder_alert_policy_condition resource. * @returns {string} A string representing the condition. */ - matchConditionFromFolderAlertPolicyConditionName(folderAlertPolicyConditionName: string) { - return this.pathTemplates.folderAlertPolicyConditionPathTemplate.match(folderAlertPolicyConditionName).condition; + matchConditionFromFolderAlertPolicyConditionName( + folderAlertPolicyConditionName: string, + ) { + return this.pathTemplates.folderAlertPolicyConditionPathTemplate.match( + folderAlertPolicyConditionName, + ).condition; } /** @@ -1328,7 +1648,7 @@ export class UptimeCheckServiceClient { * @param {string} channel_descriptor * @returns {string} Resource name string. */ - folderChannelDescriptorPath(folder:string,channelDescriptor:string) { + folderChannelDescriptorPath(folder: string, channelDescriptor: string) { return this.pathTemplates.folderChannelDescriptorPathTemplate.render({ folder: folder, channel_descriptor: channelDescriptor, @@ -1342,8 +1662,12 @@ export class UptimeCheckServiceClient { * A fully-qualified path representing folder_channel_descriptor resource. * @returns {string} A string representing the folder. */ - matchFolderFromFolderChannelDescriptorName(folderChannelDescriptorName: string) { - return this.pathTemplates.folderChannelDescriptorPathTemplate.match(folderChannelDescriptorName).folder; + matchFolderFromFolderChannelDescriptorName( + folderChannelDescriptorName: string, + ) { + return this.pathTemplates.folderChannelDescriptorPathTemplate.match( + folderChannelDescriptorName, + ).folder; } /** @@ -1353,8 +1677,12 @@ export class UptimeCheckServiceClient { * A fully-qualified path representing folder_channel_descriptor resource. * @returns {string} A string representing the channel_descriptor. */ - matchChannelDescriptorFromFolderChannelDescriptorName(folderChannelDescriptorName: string) { - return this.pathTemplates.folderChannelDescriptorPathTemplate.match(folderChannelDescriptorName).channel_descriptor; + matchChannelDescriptorFromFolderChannelDescriptorName( + folderChannelDescriptorName: string, + ) { + return this.pathTemplates.folderChannelDescriptorPathTemplate.match( + folderChannelDescriptorName, + ).channel_descriptor; } /** @@ -1364,7 +1692,7 @@ export class UptimeCheckServiceClient { * @param {string} group * @returns {string} Resource name string. */ - folderGroupPath(folder:string,group:string) { + folderGroupPath(folder: string, group: string) { return this.pathTemplates.folderGroupPathTemplate.render({ folder: folder, group: group, @@ -1379,7 +1707,8 @@ export class UptimeCheckServiceClient { * @returns {string} A string representing the folder. */ matchFolderFromFolderGroupName(folderGroupName: string) { - return this.pathTemplates.folderGroupPathTemplate.match(folderGroupName).folder; + return this.pathTemplates.folderGroupPathTemplate.match(folderGroupName) + .folder; } /** @@ -1390,7 +1719,8 @@ export class UptimeCheckServiceClient { * @returns {string} A string representing the group. */ matchGroupFromFolderGroupName(folderGroupName: string) { - return this.pathTemplates.folderGroupPathTemplate.match(folderGroupName).group; + return this.pathTemplates.folderGroupPathTemplate.match(folderGroupName) + .group; } /** @@ -1400,7 +1730,7 @@ export class UptimeCheckServiceClient { * @param {string} notification_channel * @returns {string} Resource name string. */ - folderNotificationChannelPath(folder:string,notificationChannel:string) { + folderNotificationChannelPath(folder: string, notificationChannel: string) { return this.pathTemplates.folderNotificationChannelPathTemplate.render({ folder: folder, notification_channel: notificationChannel, @@ -1414,8 +1744,12 @@ export class UptimeCheckServiceClient { * A fully-qualified path representing folder_notification_channel resource. * @returns {string} A string representing the folder. */ - matchFolderFromFolderNotificationChannelName(folderNotificationChannelName: string) { - return this.pathTemplates.folderNotificationChannelPathTemplate.match(folderNotificationChannelName).folder; + matchFolderFromFolderNotificationChannelName( + folderNotificationChannelName: string, + ) { + return this.pathTemplates.folderNotificationChannelPathTemplate.match( + folderNotificationChannelName, + ).folder; } /** @@ -1425,8 +1759,12 @@ export class UptimeCheckServiceClient { * A fully-qualified path representing folder_notification_channel resource. * @returns {string} A string representing the notification_channel. */ - matchNotificationChannelFromFolderNotificationChannelName(folderNotificationChannelName: string) { - return this.pathTemplates.folderNotificationChannelPathTemplate.match(folderNotificationChannelName).notification_channel; + matchNotificationChannelFromFolderNotificationChannelName( + folderNotificationChannelName: string, + ) { + return this.pathTemplates.folderNotificationChannelPathTemplate.match( + folderNotificationChannelName, + ).notification_channel; } /** @@ -1436,7 +1774,7 @@ export class UptimeCheckServiceClient { * @param {string} service * @returns {string} Resource name string. */ - folderServicePath(folder:string,service:string) { + folderServicePath(folder: string, service: string) { return this.pathTemplates.folderServicePathTemplate.render({ folder: folder, service: service, @@ -1451,7 +1789,8 @@ export class UptimeCheckServiceClient { * @returns {string} A string representing the folder. */ matchFolderFromFolderServiceName(folderServiceName: string) { - return this.pathTemplates.folderServicePathTemplate.match(folderServiceName).folder; + return this.pathTemplates.folderServicePathTemplate.match(folderServiceName) + .folder; } /** @@ -1462,7 +1801,8 @@ export class UptimeCheckServiceClient { * @returns {string} A string representing the service. */ matchServiceFromFolderServiceName(folderServiceName: string) { - return this.pathTemplates.folderServicePathTemplate.match(folderServiceName).service; + return this.pathTemplates.folderServicePathTemplate.match(folderServiceName) + .service; } /** @@ -1473,12 +1813,18 @@ export class UptimeCheckServiceClient { * @param {string} service_level_objective * @returns {string} Resource name string. */ - folderServiceServiceLevelObjectivePath(folder:string,service:string,serviceLevelObjective:string) { - return this.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.render({ - folder: folder, - service: service, - service_level_objective: serviceLevelObjective, - }); + folderServiceServiceLevelObjectivePath( + folder: string, + service: string, + serviceLevelObjective: string, + ) { + return this.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.render( + { + folder: folder, + service: service, + service_level_objective: serviceLevelObjective, + }, + ); } /** @@ -1488,8 +1834,12 @@ export class UptimeCheckServiceClient { * A fully-qualified path representing folder_service_service_level_objective resource. * @returns {string} A string representing the folder. */ - matchFolderFromFolderServiceServiceLevelObjectiveName(folderServiceServiceLevelObjectiveName: string) { - return this.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match(folderServiceServiceLevelObjectiveName).folder; + matchFolderFromFolderServiceServiceLevelObjectiveName( + folderServiceServiceLevelObjectiveName: string, + ) { + return this.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match( + folderServiceServiceLevelObjectiveName, + ).folder; } /** @@ -1499,8 +1849,12 @@ export class UptimeCheckServiceClient { * A fully-qualified path representing folder_service_service_level_objective resource. * @returns {string} A string representing the service. */ - matchServiceFromFolderServiceServiceLevelObjectiveName(folderServiceServiceLevelObjectiveName: string) { - return this.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match(folderServiceServiceLevelObjectiveName).service; + matchServiceFromFolderServiceServiceLevelObjectiveName( + folderServiceServiceLevelObjectiveName: string, + ) { + return this.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match( + folderServiceServiceLevelObjectiveName, + ).service; } /** @@ -1510,8 +1864,12 @@ export class UptimeCheckServiceClient { * A fully-qualified path representing folder_service_service_level_objective resource. * @returns {string} A string representing the service_level_objective. */ - matchServiceLevelObjectiveFromFolderServiceServiceLevelObjectiveName(folderServiceServiceLevelObjectiveName: string) { - return this.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match(folderServiceServiceLevelObjectiveName).service_level_objective; + matchServiceLevelObjectiveFromFolderServiceServiceLevelObjectiveName( + folderServiceServiceLevelObjectiveName: string, + ) { + return this.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match( + folderServiceServiceLevelObjectiveName, + ).service_level_objective; } /** @@ -1521,7 +1879,7 @@ export class UptimeCheckServiceClient { * @param {string} uptime_check_config * @returns {string} Resource name string. */ - folderUptimeCheckConfigPath(folder:string,uptimeCheckConfig:string) { + folderUptimeCheckConfigPath(folder: string, uptimeCheckConfig: string) { return this.pathTemplates.folderUptimeCheckConfigPathTemplate.render({ folder: folder, uptime_check_config: uptimeCheckConfig, @@ -1535,8 +1893,12 @@ export class UptimeCheckServiceClient { * A fully-qualified path representing folder_uptime_check_config resource. * @returns {string} A string representing the folder. */ - matchFolderFromFolderUptimeCheckConfigName(folderUptimeCheckConfigName: string) { - return this.pathTemplates.folderUptimeCheckConfigPathTemplate.match(folderUptimeCheckConfigName).folder; + matchFolderFromFolderUptimeCheckConfigName( + folderUptimeCheckConfigName: string, + ) { + return this.pathTemplates.folderUptimeCheckConfigPathTemplate.match( + folderUptimeCheckConfigName, + ).folder; } /** @@ -1546,8 +1908,12 @@ export class UptimeCheckServiceClient { * A fully-qualified path representing folder_uptime_check_config resource. * @returns {string} A string representing the uptime_check_config. */ - matchUptimeCheckConfigFromFolderUptimeCheckConfigName(folderUptimeCheckConfigName: string) { - return this.pathTemplates.folderUptimeCheckConfigPathTemplate.match(folderUptimeCheckConfigName).uptime_check_config; + matchUptimeCheckConfigFromFolderUptimeCheckConfigName( + folderUptimeCheckConfigName: string, + ) { + return this.pathTemplates.folderUptimeCheckConfigPathTemplate.match( + folderUptimeCheckConfigName, + ).uptime_check_config; } /** @@ -1557,7 +1923,7 @@ export class UptimeCheckServiceClient { * @param {string} alert_policy * @returns {string} Resource name string. */ - organizationAlertPolicyPath(organization:string,alertPolicy:string) { + organizationAlertPolicyPath(organization: string, alertPolicy: string) { return this.pathTemplates.organizationAlertPolicyPathTemplate.render({ organization: organization, alert_policy: alertPolicy, @@ -1571,8 +1937,12 @@ export class UptimeCheckServiceClient { * A fully-qualified path representing organization_alert_policy resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationAlertPolicyName(organizationAlertPolicyName: string) { - return this.pathTemplates.organizationAlertPolicyPathTemplate.match(organizationAlertPolicyName).organization; + matchOrganizationFromOrganizationAlertPolicyName( + organizationAlertPolicyName: string, + ) { + return this.pathTemplates.organizationAlertPolicyPathTemplate.match( + organizationAlertPolicyName, + ).organization; } /** @@ -1582,8 +1952,12 @@ export class UptimeCheckServiceClient { * A fully-qualified path representing organization_alert_policy resource. * @returns {string} A string representing the alert_policy. */ - matchAlertPolicyFromOrganizationAlertPolicyName(organizationAlertPolicyName: string) { - return this.pathTemplates.organizationAlertPolicyPathTemplate.match(organizationAlertPolicyName).alert_policy; + matchAlertPolicyFromOrganizationAlertPolicyName( + organizationAlertPolicyName: string, + ) { + return this.pathTemplates.organizationAlertPolicyPathTemplate.match( + organizationAlertPolicyName, + ).alert_policy; } /** @@ -1594,12 +1968,18 @@ export class UptimeCheckServiceClient { * @param {string} condition * @returns {string} Resource name string. */ - organizationAlertPolicyConditionPath(organization:string,alertPolicy:string,condition:string) { - return this.pathTemplates.organizationAlertPolicyConditionPathTemplate.render({ - organization: organization, - alert_policy: alertPolicy, - condition: condition, - }); + organizationAlertPolicyConditionPath( + organization: string, + alertPolicy: string, + condition: string, + ) { + return this.pathTemplates.organizationAlertPolicyConditionPathTemplate.render( + { + organization: organization, + alert_policy: alertPolicy, + condition: condition, + }, + ); } /** @@ -1609,8 +1989,12 @@ export class UptimeCheckServiceClient { * A fully-qualified path representing organization_alert_policy_condition resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationAlertPolicyConditionName(organizationAlertPolicyConditionName: string) { - return this.pathTemplates.organizationAlertPolicyConditionPathTemplate.match(organizationAlertPolicyConditionName).organization; + matchOrganizationFromOrganizationAlertPolicyConditionName( + organizationAlertPolicyConditionName: string, + ) { + return this.pathTemplates.organizationAlertPolicyConditionPathTemplate.match( + organizationAlertPolicyConditionName, + ).organization; } /** @@ -1620,8 +2004,12 @@ export class UptimeCheckServiceClient { * A fully-qualified path representing organization_alert_policy_condition resource. * @returns {string} A string representing the alert_policy. */ - matchAlertPolicyFromOrganizationAlertPolicyConditionName(organizationAlertPolicyConditionName: string) { - return this.pathTemplates.organizationAlertPolicyConditionPathTemplate.match(organizationAlertPolicyConditionName).alert_policy; + matchAlertPolicyFromOrganizationAlertPolicyConditionName( + organizationAlertPolicyConditionName: string, + ) { + return this.pathTemplates.organizationAlertPolicyConditionPathTemplate.match( + organizationAlertPolicyConditionName, + ).alert_policy; } /** @@ -1631,8 +2019,12 @@ export class UptimeCheckServiceClient { * A fully-qualified path representing organization_alert_policy_condition resource. * @returns {string} A string representing the condition. */ - matchConditionFromOrganizationAlertPolicyConditionName(organizationAlertPolicyConditionName: string) { - return this.pathTemplates.organizationAlertPolicyConditionPathTemplate.match(organizationAlertPolicyConditionName).condition; + matchConditionFromOrganizationAlertPolicyConditionName( + organizationAlertPolicyConditionName: string, + ) { + return this.pathTemplates.organizationAlertPolicyConditionPathTemplate.match( + organizationAlertPolicyConditionName, + ).condition; } /** @@ -1642,7 +2034,10 @@ export class UptimeCheckServiceClient { * @param {string} channel_descriptor * @returns {string} Resource name string. */ - organizationChannelDescriptorPath(organization:string,channelDescriptor:string) { + organizationChannelDescriptorPath( + organization: string, + channelDescriptor: string, + ) { return this.pathTemplates.organizationChannelDescriptorPathTemplate.render({ organization: organization, channel_descriptor: channelDescriptor, @@ -1656,8 +2051,12 @@ export class UptimeCheckServiceClient { * A fully-qualified path representing organization_channel_descriptor resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationChannelDescriptorName(organizationChannelDescriptorName: string) { - return this.pathTemplates.organizationChannelDescriptorPathTemplate.match(organizationChannelDescriptorName).organization; + matchOrganizationFromOrganizationChannelDescriptorName( + organizationChannelDescriptorName: string, + ) { + return this.pathTemplates.organizationChannelDescriptorPathTemplate.match( + organizationChannelDescriptorName, + ).organization; } /** @@ -1667,8 +2066,12 @@ export class UptimeCheckServiceClient { * A fully-qualified path representing organization_channel_descriptor resource. * @returns {string} A string representing the channel_descriptor. */ - matchChannelDescriptorFromOrganizationChannelDescriptorName(organizationChannelDescriptorName: string) { - return this.pathTemplates.organizationChannelDescriptorPathTemplate.match(organizationChannelDescriptorName).channel_descriptor; + matchChannelDescriptorFromOrganizationChannelDescriptorName( + organizationChannelDescriptorName: string, + ) { + return this.pathTemplates.organizationChannelDescriptorPathTemplate.match( + organizationChannelDescriptorName, + ).channel_descriptor; } /** @@ -1678,7 +2081,7 @@ export class UptimeCheckServiceClient { * @param {string} group * @returns {string} Resource name string. */ - organizationGroupPath(organization:string,group:string) { + organizationGroupPath(organization: string, group: string) { return this.pathTemplates.organizationGroupPathTemplate.render({ organization: organization, group: group, @@ -1693,7 +2096,9 @@ export class UptimeCheckServiceClient { * @returns {string} A string representing the organization. */ matchOrganizationFromOrganizationGroupName(organizationGroupName: string) { - return this.pathTemplates.organizationGroupPathTemplate.match(organizationGroupName).organization; + return this.pathTemplates.organizationGroupPathTemplate.match( + organizationGroupName, + ).organization; } /** @@ -1704,7 +2109,9 @@ export class UptimeCheckServiceClient { * @returns {string} A string representing the group. */ matchGroupFromOrganizationGroupName(organizationGroupName: string) { - return this.pathTemplates.organizationGroupPathTemplate.match(organizationGroupName).group; + return this.pathTemplates.organizationGroupPathTemplate.match( + organizationGroupName, + ).group; } /** @@ -1714,11 +2121,16 @@ export class UptimeCheckServiceClient { * @param {string} notification_channel * @returns {string} Resource name string. */ - organizationNotificationChannelPath(organization:string,notificationChannel:string) { - return this.pathTemplates.organizationNotificationChannelPathTemplate.render({ - organization: organization, - notification_channel: notificationChannel, - }); + organizationNotificationChannelPath( + organization: string, + notificationChannel: string, + ) { + return this.pathTemplates.organizationNotificationChannelPathTemplate.render( + { + organization: organization, + notification_channel: notificationChannel, + }, + ); } /** @@ -1728,8 +2140,12 @@ export class UptimeCheckServiceClient { * A fully-qualified path representing organization_notification_channel resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationNotificationChannelName(organizationNotificationChannelName: string) { - return this.pathTemplates.organizationNotificationChannelPathTemplate.match(organizationNotificationChannelName).organization; + matchOrganizationFromOrganizationNotificationChannelName( + organizationNotificationChannelName: string, + ) { + return this.pathTemplates.organizationNotificationChannelPathTemplate.match( + organizationNotificationChannelName, + ).organization; } /** @@ -1739,8 +2155,12 @@ export class UptimeCheckServiceClient { * A fully-qualified path representing organization_notification_channel resource. * @returns {string} A string representing the notification_channel. */ - matchNotificationChannelFromOrganizationNotificationChannelName(organizationNotificationChannelName: string) { - return this.pathTemplates.organizationNotificationChannelPathTemplate.match(organizationNotificationChannelName).notification_channel; + matchNotificationChannelFromOrganizationNotificationChannelName( + organizationNotificationChannelName: string, + ) { + return this.pathTemplates.organizationNotificationChannelPathTemplate.match( + organizationNotificationChannelName, + ).notification_channel; } /** @@ -1750,7 +2170,7 @@ export class UptimeCheckServiceClient { * @param {string} service * @returns {string} Resource name string. */ - organizationServicePath(organization:string,service:string) { + organizationServicePath(organization: string, service: string) { return this.pathTemplates.organizationServicePathTemplate.render({ organization: organization, service: service, @@ -1764,8 +2184,12 @@ export class UptimeCheckServiceClient { * A fully-qualified path representing organization_service resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationServiceName(organizationServiceName: string) { - return this.pathTemplates.organizationServicePathTemplate.match(organizationServiceName).organization; + matchOrganizationFromOrganizationServiceName( + organizationServiceName: string, + ) { + return this.pathTemplates.organizationServicePathTemplate.match( + organizationServiceName, + ).organization; } /** @@ -1776,7 +2200,9 @@ export class UptimeCheckServiceClient { * @returns {string} A string representing the service. */ matchServiceFromOrganizationServiceName(organizationServiceName: string) { - return this.pathTemplates.organizationServicePathTemplate.match(organizationServiceName).service; + return this.pathTemplates.organizationServicePathTemplate.match( + organizationServiceName, + ).service; } /** @@ -1787,12 +2213,18 @@ export class UptimeCheckServiceClient { * @param {string} service_level_objective * @returns {string} Resource name string. */ - organizationServiceServiceLevelObjectivePath(organization:string,service:string,serviceLevelObjective:string) { - return this.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.render({ - organization: organization, - service: service, - service_level_objective: serviceLevelObjective, - }); + organizationServiceServiceLevelObjectivePath( + organization: string, + service: string, + serviceLevelObjective: string, + ) { + return this.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.render( + { + organization: organization, + service: service, + service_level_objective: serviceLevelObjective, + }, + ); } /** @@ -1802,8 +2234,12 @@ export class UptimeCheckServiceClient { * A fully-qualified path representing organization_service_service_level_objective resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationServiceServiceLevelObjectiveName(organizationServiceServiceLevelObjectiveName: string) { - return this.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match(organizationServiceServiceLevelObjectiveName).organization; + matchOrganizationFromOrganizationServiceServiceLevelObjectiveName( + organizationServiceServiceLevelObjectiveName: string, + ) { + return this.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match( + organizationServiceServiceLevelObjectiveName, + ).organization; } /** @@ -1813,8 +2249,12 @@ export class UptimeCheckServiceClient { * A fully-qualified path representing organization_service_service_level_objective resource. * @returns {string} A string representing the service. */ - matchServiceFromOrganizationServiceServiceLevelObjectiveName(organizationServiceServiceLevelObjectiveName: string) { - return this.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match(organizationServiceServiceLevelObjectiveName).service; + matchServiceFromOrganizationServiceServiceLevelObjectiveName( + organizationServiceServiceLevelObjectiveName: string, + ) { + return this.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match( + organizationServiceServiceLevelObjectiveName, + ).service; } /** @@ -1824,8 +2264,12 @@ export class UptimeCheckServiceClient { * A fully-qualified path representing organization_service_service_level_objective resource. * @returns {string} A string representing the service_level_objective. */ - matchServiceLevelObjectiveFromOrganizationServiceServiceLevelObjectiveName(organizationServiceServiceLevelObjectiveName: string) { - return this.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match(organizationServiceServiceLevelObjectiveName).service_level_objective; + matchServiceLevelObjectiveFromOrganizationServiceServiceLevelObjectiveName( + organizationServiceServiceLevelObjectiveName: string, + ) { + return this.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match( + organizationServiceServiceLevelObjectiveName, + ).service_level_objective; } /** @@ -1835,7 +2279,10 @@ export class UptimeCheckServiceClient { * @param {string} uptime_check_config * @returns {string} Resource name string. */ - organizationUptimeCheckConfigPath(organization:string,uptimeCheckConfig:string) { + organizationUptimeCheckConfigPath( + organization: string, + uptimeCheckConfig: string, + ) { return this.pathTemplates.organizationUptimeCheckConfigPathTemplate.render({ organization: organization, uptime_check_config: uptimeCheckConfig, @@ -1849,8 +2296,12 @@ export class UptimeCheckServiceClient { * A fully-qualified path representing organization_uptime_check_config resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationUptimeCheckConfigName(organizationUptimeCheckConfigName: string) { - return this.pathTemplates.organizationUptimeCheckConfigPathTemplate.match(organizationUptimeCheckConfigName).organization; + matchOrganizationFromOrganizationUptimeCheckConfigName( + organizationUptimeCheckConfigName: string, + ) { + return this.pathTemplates.organizationUptimeCheckConfigPathTemplate.match( + organizationUptimeCheckConfigName, + ).organization; } /** @@ -1860,8 +2311,12 @@ export class UptimeCheckServiceClient { * A fully-qualified path representing organization_uptime_check_config resource. * @returns {string} A string representing the uptime_check_config. */ - matchUptimeCheckConfigFromOrganizationUptimeCheckConfigName(organizationUptimeCheckConfigName: string) { - return this.pathTemplates.organizationUptimeCheckConfigPathTemplate.match(organizationUptimeCheckConfigName).uptime_check_config; + matchUptimeCheckConfigFromOrganizationUptimeCheckConfigName( + organizationUptimeCheckConfigName: string, + ) { + return this.pathTemplates.organizationUptimeCheckConfigPathTemplate.match( + organizationUptimeCheckConfigName, + ).uptime_check_config; } /** @@ -1871,7 +2326,7 @@ export class UptimeCheckServiceClient { * @param {string} alert_policy * @returns {string} Resource name string. */ - projectAlertPolicyPath(project:string,alertPolicy:string) { + projectAlertPolicyPath(project: string, alertPolicy: string) { return this.pathTemplates.projectAlertPolicyPathTemplate.render({ project: project, alert_policy: alertPolicy, @@ -1886,7 +2341,9 @@ export class UptimeCheckServiceClient { * @returns {string} A string representing the project. */ matchProjectFromProjectAlertPolicyName(projectAlertPolicyName: string) { - return this.pathTemplates.projectAlertPolicyPathTemplate.match(projectAlertPolicyName).project; + return this.pathTemplates.projectAlertPolicyPathTemplate.match( + projectAlertPolicyName, + ).project; } /** @@ -1897,7 +2354,9 @@ export class UptimeCheckServiceClient { * @returns {string} A string representing the alert_policy. */ matchAlertPolicyFromProjectAlertPolicyName(projectAlertPolicyName: string) { - return this.pathTemplates.projectAlertPolicyPathTemplate.match(projectAlertPolicyName).alert_policy; + return this.pathTemplates.projectAlertPolicyPathTemplate.match( + projectAlertPolicyName, + ).alert_policy; } /** @@ -1908,7 +2367,11 @@ export class UptimeCheckServiceClient { * @param {string} condition * @returns {string} Resource name string. */ - projectAlertPolicyConditionPath(project:string,alertPolicy:string,condition:string) { + projectAlertPolicyConditionPath( + project: string, + alertPolicy: string, + condition: string, + ) { return this.pathTemplates.projectAlertPolicyConditionPathTemplate.render({ project: project, alert_policy: alertPolicy, @@ -1923,8 +2386,12 @@ export class UptimeCheckServiceClient { * A fully-qualified path representing project_alert_policy_condition resource. * @returns {string} A string representing the project. */ - matchProjectFromProjectAlertPolicyConditionName(projectAlertPolicyConditionName: string) { - return this.pathTemplates.projectAlertPolicyConditionPathTemplate.match(projectAlertPolicyConditionName).project; + matchProjectFromProjectAlertPolicyConditionName( + projectAlertPolicyConditionName: string, + ) { + return this.pathTemplates.projectAlertPolicyConditionPathTemplate.match( + projectAlertPolicyConditionName, + ).project; } /** @@ -1934,8 +2401,12 @@ export class UptimeCheckServiceClient { * A fully-qualified path representing project_alert_policy_condition resource. * @returns {string} A string representing the alert_policy. */ - matchAlertPolicyFromProjectAlertPolicyConditionName(projectAlertPolicyConditionName: string) { - return this.pathTemplates.projectAlertPolicyConditionPathTemplate.match(projectAlertPolicyConditionName).alert_policy; + matchAlertPolicyFromProjectAlertPolicyConditionName( + projectAlertPolicyConditionName: string, + ) { + return this.pathTemplates.projectAlertPolicyConditionPathTemplate.match( + projectAlertPolicyConditionName, + ).alert_policy; } /** @@ -1945,8 +2416,12 @@ export class UptimeCheckServiceClient { * A fully-qualified path representing project_alert_policy_condition resource. * @returns {string} A string representing the condition. */ - matchConditionFromProjectAlertPolicyConditionName(projectAlertPolicyConditionName: string) { - return this.pathTemplates.projectAlertPolicyConditionPathTemplate.match(projectAlertPolicyConditionName).condition; + matchConditionFromProjectAlertPolicyConditionName( + projectAlertPolicyConditionName: string, + ) { + return this.pathTemplates.projectAlertPolicyConditionPathTemplate.match( + projectAlertPolicyConditionName, + ).condition; } /** @@ -1956,7 +2431,7 @@ export class UptimeCheckServiceClient { * @param {string} channel_descriptor * @returns {string} Resource name string. */ - projectChannelDescriptorPath(project:string,channelDescriptor:string) { + projectChannelDescriptorPath(project: string, channelDescriptor: string) { return this.pathTemplates.projectChannelDescriptorPathTemplate.render({ project: project, channel_descriptor: channelDescriptor, @@ -1970,8 +2445,12 @@ export class UptimeCheckServiceClient { * A fully-qualified path representing project_channel_descriptor resource. * @returns {string} A string representing the project. */ - matchProjectFromProjectChannelDescriptorName(projectChannelDescriptorName: string) { - return this.pathTemplates.projectChannelDescriptorPathTemplate.match(projectChannelDescriptorName).project; + matchProjectFromProjectChannelDescriptorName( + projectChannelDescriptorName: string, + ) { + return this.pathTemplates.projectChannelDescriptorPathTemplate.match( + projectChannelDescriptorName, + ).project; } /** @@ -1981,8 +2460,12 @@ export class UptimeCheckServiceClient { * A fully-qualified path representing project_channel_descriptor resource. * @returns {string} A string representing the channel_descriptor. */ - matchChannelDescriptorFromProjectChannelDescriptorName(projectChannelDescriptorName: string) { - return this.pathTemplates.projectChannelDescriptorPathTemplate.match(projectChannelDescriptorName).channel_descriptor; + matchChannelDescriptorFromProjectChannelDescriptorName( + projectChannelDescriptorName: string, + ) { + return this.pathTemplates.projectChannelDescriptorPathTemplate.match( + projectChannelDescriptorName, + ).channel_descriptor; } /** @@ -1992,7 +2475,7 @@ export class UptimeCheckServiceClient { * @param {string} group * @returns {string} Resource name string. */ - projectGroupPath(project:string,group:string) { + projectGroupPath(project: string, group: string) { return this.pathTemplates.projectGroupPathTemplate.render({ project: project, group: group, @@ -2007,7 +2490,8 @@ export class UptimeCheckServiceClient { * @returns {string} A string representing the project. */ matchProjectFromProjectGroupName(projectGroupName: string) { - return this.pathTemplates.projectGroupPathTemplate.match(projectGroupName).project; + return this.pathTemplates.projectGroupPathTemplate.match(projectGroupName) + .project; } /** @@ -2018,7 +2502,8 @@ export class UptimeCheckServiceClient { * @returns {string} A string representing the group. */ matchGroupFromProjectGroupName(projectGroupName: string) { - return this.pathTemplates.projectGroupPathTemplate.match(projectGroupName).group; + return this.pathTemplates.projectGroupPathTemplate.match(projectGroupName) + .group; } /** @@ -2028,7 +2513,7 @@ export class UptimeCheckServiceClient { * @param {string} notification_channel * @returns {string} Resource name string. */ - projectNotificationChannelPath(project:string,notificationChannel:string) { + projectNotificationChannelPath(project: string, notificationChannel: string) { return this.pathTemplates.projectNotificationChannelPathTemplate.render({ project: project, notification_channel: notificationChannel, @@ -2042,8 +2527,12 @@ export class UptimeCheckServiceClient { * A fully-qualified path representing project_notification_channel resource. * @returns {string} A string representing the project. */ - matchProjectFromProjectNotificationChannelName(projectNotificationChannelName: string) { - return this.pathTemplates.projectNotificationChannelPathTemplate.match(projectNotificationChannelName).project; + matchProjectFromProjectNotificationChannelName( + projectNotificationChannelName: string, + ) { + return this.pathTemplates.projectNotificationChannelPathTemplate.match( + projectNotificationChannelName, + ).project; } /** @@ -2053,8 +2542,12 @@ export class UptimeCheckServiceClient { * A fully-qualified path representing project_notification_channel resource. * @returns {string} A string representing the notification_channel. */ - matchNotificationChannelFromProjectNotificationChannelName(projectNotificationChannelName: string) { - return this.pathTemplates.projectNotificationChannelPathTemplate.match(projectNotificationChannelName).notification_channel; + matchNotificationChannelFromProjectNotificationChannelName( + projectNotificationChannelName: string, + ) { + return this.pathTemplates.projectNotificationChannelPathTemplate.match( + projectNotificationChannelName, + ).notification_channel; } /** @@ -2064,7 +2557,7 @@ export class UptimeCheckServiceClient { * @param {string} service * @returns {string} Resource name string. */ - projectServicePath(project:string,service:string) { + projectServicePath(project: string, service: string) { return this.pathTemplates.projectServicePathTemplate.render({ project: project, service: service, @@ -2079,7 +2572,9 @@ export class UptimeCheckServiceClient { * @returns {string} A string representing the project. */ matchProjectFromProjectServiceName(projectServiceName: string) { - return this.pathTemplates.projectServicePathTemplate.match(projectServiceName).project; + return this.pathTemplates.projectServicePathTemplate.match( + projectServiceName, + ).project; } /** @@ -2090,7 +2585,9 @@ export class UptimeCheckServiceClient { * @returns {string} A string representing the service. */ matchServiceFromProjectServiceName(projectServiceName: string) { - return this.pathTemplates.projectServicePathTemplate.match(projectServiceName).service; + return this.pathTemplates.projectServicePathTemplate.match( + projectServiceName, + ).service; } /** @@ -2101,12 +2598,18 @@ export class UptimeCheckServiceClient { * @param {string} service_level_objective * @returns {string} Resource name string. */ - projectServiceServiceLevelObjectivePath(project:string,service:string,serviceLevelObjective:string) { - return this.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.render({ - project: project, - service: service, - service_level_objective: serviceLevelObjective, - }); + projectServiceServiceLevelObjectivePath( + project: string, + service: string, + serviceLevelObjective: string, + ) { + return this.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.render( + { + project: project, + service: service, + service_level_objective: serviceLevelObjective, + }, + ); } /** @@ -2116,8 +2619,12 @@ export class UptimeCheckServiceClient { * A fully-qualified path representing project_service_service_level_objective resource. * @returns {string} A string representing the project. */ - matchProjectFromProjectServiceServiceLevelObjectiveName(projectServiceServiceLevelObjectiveName: string) { - return this.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match(projectServiceServiceLevelObjectiveName).project; + matchProjectFromProjectServiceServiceLevelObjectiveName( + projectServiceServiceLevelObjectiveName: string, + ) { + return this.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match( + projectServiceServiceLevelObjectiveName, + ).project; } /** @@ -2127,8 +2634,12 @@ export class UptimeCheckServiceClient { * A fully-qualified path representing project_service_service_level_objective resource. * @returns {string} A string representing the service. */ - matchServiceFromProjectServiceServiceLevelObjectiveName(projectServiceServiceLevelObjectiveName: string) { - return this.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match(projectServiceServiceLevelObjectiveName).service; + matchServiceFromProjectServiceServiceLevelObjectiveName( + projectServiceServiceLevelObjectiveName: string, + ) { + return this.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match( + projectServiceServiceLevelObjectiveName, + ).service; } /** @@ -2138,8 +2649,12 @@ export class UptimeCheckServiceClient { * A fully-qualified path representing project_service_service_level_objective resource. * @returns {string} A string representing the service_level_objective. */ - matchServiceLevelObjectiveFromProjectServiceServiceLevelObjectiveName(projectServiceServiceLevelObjectiveName: string) { - return this.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match(projectServiceServiceLevelObjectiveName).service_level_objective; + matchServiceLevelObjectiveFromProjectServiceServiceLevelObjectiveName( + projectServiceServiceLevelObjectiveName: string, + ) { + return this.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match( + projectServiceServiceLevelObjectiveName, + ).service_level_objective; } /** @@ -2149,7 +2664,7 @@ export class UptimeCheckServiceClient { * @param {string} uptime_check_config * @returns {string} Resource name string. */ - projectUptimeCheckConfigPath(project:string,uptimeCheckConfig:string) { + projectUptimeCheckConfigPath(project: string, uptimeCheckConfig: string) { return this.pathTemplates.projectUptimeCheckConfigPathTemplate.render({ project: project, uptime_check_config: uptimeCheckConfig, @@ -2163,8 +2678,12 @@ export class UptimeCheckServiceClient { * A fully-qualified path representing project_uptime_check_config resource. * @returns {string} A string representing the project. */ - matchProjectFromProjectUptimeCheckConfigName(projectUptimeCheckConfigName: string) { - return this.pathTemplates.projectUptimeCheckConfigPathTemplate.match(projectUptimeCheckConfigName).project; + matchProjectFromProjectUptimeCheckConfigName( + projectUptimeCheckConfigName: string, + ) { + return this.pathTemplates.projectUptimeCheckConfigPathTemplate.match( + projectUptimeCheckConfigName, + ).project; } /** @@ -2174,8 +2693,12 @@ export class UptimeCheckServiceClient { * A fully-qualified path representing project_uptime_check_config resource. * @returns {string} A string representing the uptime_check_config. */ - matchUptimeCheckConfigFromProjectUptimeCheckConfigName(projectUptimeCheckConfigName: string) { - return this.pathTemplates.projectUptimeCheckConfigPathTemplate.match(projectUptimeCheckConfigName).uptime_check_config; + matchUptimeCheckConfigFromProjectUptimeCheckConfigName( + projectUptimeCheckConfigName: string, + ) { + return this.pathTemplates.projectUptimeCheckConfigPathTemplate.match( + projectUptimeCheckConfigName, + ).uptime_check_config; } /** @@ -2186,7 +2709,7 @@ export class UptimeCheckServiceClient { */ close(): Promise { if (this.uptimeCheckServiceStub && !this._terminated) { - return this.uptimeCheckServiceStub.then(stub => { + return this.uptimeCheckServiceStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -2194,4 +2717,4 @@ export class UptimeCheckServiceClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/core/generator/gapic-generator-typescript/baselines/monitoring-esm/esm/system-test/fixtures/sample/src/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/monitoring-esm/esm/system-test/fixtures/sample/src/index.ts.baseline index 826cea87912e..10fdbcfbb6d7 100644 --- a/core/generator/gapic-generator-typescript/baselines/monitoring-esm/esm/system-test/fixtures/sample/src/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/monitoring-esm/esm/system-test/fixtures/sample/src/index.ts.baseline @@ -17,7 +17,14 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -import {AlertPolicyServiceClient, GroupServiceClient, MetricServiceClient, NotificationChannelServiceClient, ServiceMonitoringServiceClient, UptimeCheckServiceClient} from 'monitoring'; +import { + AlertPolicyServiceClient, + GroupServiceClient, + MetricServiceClient, + NotificationChannelServiceClient, + ServiceMonitoringServiceClient, + UptimeCheckServiceClient, +} from 'monitoring'; // check that the client class type name can be used function doStuffWithAlertPolicyServiceClient(client: AlertPolicyServiceClient) { @@ -29,10 +36,14 @@ function doStuffWithGroupServiceClient(client: GroupServiceClient) { function doStuffWithMetricServiceClient(client: MetricServiceClient) { client.close(); } -function doStuffWithNotificationChannelServiceClient(client: NotificationChannelServiceClient) { +function doStuffWithNotificationChannelServiceClient( + client: NotificationChannelServiceClient, +) { client.close(); } -function doStuffWithServiceMonitoringServiceClient(client: ServiceMonitoringServiceClient) { +function doStuffWithServiceMonitoringServiceClient( + client: ServiceMonitoringServiceClient, +) { client.close(); } function doStuffWithUptimeCheckServiceClient(client: UptimeCheckServiceClient) { @@ -50,7 +61,8 @@ function main() { const metricServiceClient = new MetricServiceClient(); doStuffWithMetricServiceClient(metricServiceClient); // check that the client instance can be created - const notificationChannelServiceClient = new NotificationChannelServiceClient(); + const notificationChannelServiceClient = + new NotificationChannelServiceClient(); doStuffWithNotificationChannelServiceClient(notificationChannelServiceClient); // check that the client instance can be created const serviceMonitoringServiceClient = new ServiceMonitoringServiceClient(); diff --git a/core/generator/gapic-generator-typescript/baselines/monitoring-esm/esm/system-test/install.ts.baseline b/core/generator/gapic-generator-typescript/baselines/monitoring-esm/esm/system-test/install.ts.baseline index e079c4fa1101..d109fdd8c97f 100644 --- a/core/generator/gapic-generator-typescript/baselines/monitoring-esm/esm/system-test/install.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/monitoring-esm/esm/system-test/install.ts.baseline @@ -16,40 +16,45 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -import {packNTest} from 'pack-n-play'; -import {readFileSync} from 'fs'; -import {describe, it} from 'mocha'; +import { packNTest } from 'pack-n-play'; +import { readFileSync } from 'fs'; +import { describe, it } from 'mocha'; describe('📦 pack-n-play test', () => { - it('TypeScript', async function() { + it('TypeScript', async function () { this.timeout(300000); await packNTest({ packageDir: process.cwd(), sample: { description: 'TypeScript user can use the type definitions', - ts: readFileSync('./esm/system-test/fixtures/sample/src/index.ts').toString() - } + ts: readFileSync( + './esm/system-test/fixtures/sample/src/index.ts', + ).toString(), + }, }); }); - it('ESM module', async function() { + it('ESM module', async function () { this.timeout(300000); await packNTest({ sample: { description: 'Should be able to import using ESM', - esm: readFileSync('./esm/system-test/fixtures/sample/src/index.js').toString(), + esm: readFileSync( + './esm/system-test/fixtures/sample/src/index.js', + ).toString(), }, }); }); - it('CJS module', async function() { + it('CJS module', async function () { this.timeout(300000); await packNTest({ sample: { description: 'Should be able to import using CJS', - cjs: readFileSync('./esm/system-test/fixtures/sample/src/index.cjs').toString(), + cjs: readFileSync( + './esm/system-test/fixtures/sample/src/index.cjs', + ).toString(), }, }); }); - }); diff --git a/core/generator/gapic-generator-typescript/baselines/monitoring-esm/esm/test/gapic_alert_policy_service_v3.ts.baseline b/core/generator/gapic-generator-typescript/baselines/monitoring-esm/esm/test/gapic_alert_policy_service_v3.ts.baseline index 9e9365388883..fe150956e279 100644 --- a/core/generator/gapic-generator-typescript/baselines/monitoring-esm/esm/test/gapic_alert_policy_service_v3.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/monitoring-esm/esm/test/gapic_alert_policy_service_v3.ts.baseline @@ -20,16 +20,16 @@ import * as protos from '../../protos/protos.js'; import assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as alertpolicyserviceModule from '../src/index.js'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; -import {protobuf} from 'google-gax'; +import { protobuf } from 'google-gax'; import fs from 'fs'; import path from 'path'; -import {fileURLToPath} from 'url'; +import { fileURLToPath } from 'url'; // @ts-ignore const dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -37,1878 +37,2768 @@ const dirname = path.dirname(fileURLToPath(import.meta.url)); // to fill in default values for request objects const root = protobuf.Root.fromJSON( JSON.parse( - fs.readFileSync(path.join(dirname, '..', '..', 'protos/protos.json'), 'utf8') - )) + fs.readFileSync( + path.join(dirname, '..', '..', 'protos/protos.json'), + 'utf8', + ), + ), +); // eslint-disable-next-line @typescript-eslint/no-unused-vars function getTypeDefaultValue(typeName: string, fields: string[]) { - let type = root.lookupType(typeName) as protobuf.Type; - for (const field of fields.slice(0, -1)) { - type = type?.fields[field]?.resolvedType as protobuf.Type; - } - return type?.fields[fields[fields.length - 1]]?.defaultValue ?? null; + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type?.fields[field]?.resolvedType as protobuf.Type; + } + return type?.fields[fields[fields.length - 1]]?.defaultValue ?? null; } function generateSampleMessage(instance: T) { - const filledObject = (instance.constructor as typeof protobuf.Message) - .toObject(instance as protobuf.Message, {defaults: true}); - return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, { defaults: true }); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; } function stubSimpleCall(response?: ResponseType, error?: Error) { - return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); } -function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { - return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +function stubSimpleCallWithCallback( + response?: ResponseType, + error?: Error, +) { + return error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); } -function stubPageStreamingCall(responses?: ResponseType[], error?: Error) { - const pagingStub = sinon.stub(); - if (responses) { - for (let i = 0; i < responses.length; ++i) { - pagingStub.onCall(i).callsArgWith(2, null, responses[i]); - } +function stubPageStreamingCall( + responses?: ResponseType[], + error?: Error, +) { + const pagingStub = sinon.stub(); + if (responses) { + for (let i = 0; i < responses.length; ++i) { + pagingStub.onCall(i).callsArgWith(2, null, responses[i]); } - const transformStub = error ? sinon.stub().callsArgWith(2, error) : pagingStub; - const mockStream = new PassThrough({ - objectMode: true, - transform: transformStub, - }); - // trigger as many responses as needed - if (responses) { - for (let i = 0; i < responses.length; ++i) { - setImmediate(() => { mockStream.write({}); }); - } - setImmediate(() => { mockStream.end(); }); - } else { - setImmediate(() => { mockStream.write({}); }); - setImmediate(() => { mockStream.end(); }); + } + const transformStub = error + ? sinon.stub().callsArgWith(2, error) + : pagingStub; + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + // trigger as many responses as needed + if (responses) { + for (let i = 0; i < responses.length; ++i) { + setImmediate(() => { + mockStream.write({}); + }); } - return sinon.stub().returns(mockStream); + setImmediate(() => { + mockStream.end(); + }); + } else { + setImmediate(() => { + mockStream.write({}); + }); + setImmediate(() => { + mockStream.end(); + }); + } + return sinon.stub().returns(mockStream); } -function stubAsyncIterationCall(responses?: ResponseType[], error?: Error) { - let counter = 0; - const asyncIterable = { - [Symbol.asyncIterator]() { - return { - async next() { - if (error) { - return Promise.reject(error); - } - if (counter >= responses!.length) { - return Promise.resolve({done: true, value: undefined}); - } - return Promise.resolve({done: false, value: responses![counter++]}); - } - }; - } - }; - return sinon.stub().returns(asyncIterable); +function stubAsyncIterationCall( + responses?: ResponseType[], + error?: Error, +) { + let counter = 0; + const asyncIterable = { + [Symbol.asyncIterator]() { + return { + async next() { + if (error) { + return Promise.reject(error); + } + if (counter >= responses!.length) { + return Promise.resolve({ done: true, value: undefined }); + } + return Promise.resolve({ done: false, value: responses![counter++] }); + }, + }; + }, + }; + return sinon.stub().returns(asyncIterable); } describe('v3.AlertPolicyServiceClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'monitoring.googleapis.com'); - }); - - it('has universeDomain', () => { - const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); - - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - it('throws DeprecationWarning if static servicePath is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const servicePath = alertpolicyserviceModule.v3.AlertPolicyServiceClient.servicePath; - assert.strictEqual(servicePath, 'monitoring.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = alertpolicyserviceModule.v3.AlertPolicyServiceClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'monitoring.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'monitoring.example.com'); - }); - - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'monitoring.example.com'); - }); - - if (typeof process === 'object' && 'env' in process) { - describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { - it('sets apiEndpoint from environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'monitoring.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - - it('value configured in code has priority over environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'monitoring.configured.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { new alertpolicyserviceModule.v3.AlertPolicyServiceClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); - - it('has port', () => { - const port = alertpolicyserviceModule.v3.AlertPolicyServiceClient.port; - assert(port); - assert(typeof port === 'number'); - }); - - it('should create a client with no option', () => { - const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient(); - assert(client); - }); - - it('should create a client with gRPC fallback', () => { - const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ - fallback: true, - }); - assert(client); - }); - - it('has initialize method and supports deferred initialization', async () => { - const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.alertPolicyServiceStub, undefined); - await client.initialize(); - assert(client.alertPolicyServiceStub); - }); - - it('has close method for the initialized client', done => { - const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.alertPolicyServiceStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); - - it('has close method for the non-initialized client', done => { - const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.alertPolicyServiceStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); - - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); - }); - - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId((err?: Error|null, projectId?: string|null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } - }); - }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'monitoring.googleapis.com'); }); - describe('getAlertPolicy', () => { - it('invokes getAlertPolicy without error', async () => { - const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.GetAlertPolicyRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.GetAlertPolicyRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.monitoring.v3.AlertPolicy() - ); - client.innerApiCalls.getAlertPolicy = stubSimpleCall(expectedResponse); - const [response] = await client.getAlertPolicy(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getAlertPolicy as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getAlertPolicy as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getAlertPolicy without error using callback', async () => { - const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.GetAlertPolicyRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.GetAlertPolicyRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.monitoring.v3.AlertPolicy() - ); - client.innerApiCalls.getAlertPolicy = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getAlertPolicy( - request, - (err?: Error|null, result?: protos.google.monitoring.v3.IAlertPolicy|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getAlertPolicy as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getAlertPolicy as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getAlertPolicy with error', async () => { - const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.GetAlertPolicyRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.GetAlertPolicyRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getAlertPolicy = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getAlertPolicy(request), expectedError); - const actualRequest = (client.innerApiCalls.getAlertPolicy as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getAlertPolicy as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getAlertPolicy with closed client', async () => { - const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.GetAlertPolicyRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.GetAlertPolicyRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getAlertPolicy(request), expectedError); - }); + it('has universeDomain', () => { + const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); }); - describe('createAlertPolicy', () => { - it('invokes createAlertPolicy without error', async () => { - const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.CreateAlertPolicyRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.CreateAlertPolicyRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.monitoring.v3.AlertPolicy() - ); - client.innerApiCalls.createAlertPolicy = stubSimpleCall(expectedResponse); - const [response] = await client.createAlertPolicy(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createAlertPolicy as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createAlertPolicy as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createAlertPolicy without error using callback', async () => { - const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.CreateAlertPolicyRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.CreateAlertPolicyRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.monitoring.v3.AlertPolicy() - ); - client.innerApiCalls.createAlertPolicy = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createAlertPolicy( - request, - (err?: Error|null, result?: protos.google.monitoring.v3.IAlertPolicy|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createAlertPolicy as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createAlertPolicy as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createAlertPolicy with error', async () => { - const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.CreateAlertPolicyRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.CreateAlertPolicyRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createAlertPolicy = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createAlertPolicy(request), expectedError); - const actualRequest = (client.innerApiCalls.createAlertPolicy as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createAlertPolicy as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createAlertPolicy with closed client', async () => { - const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.CreateAlertPolicyRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.CreateAlertPolicyRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createAlertPolicy(request), expectedError); - }); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = + alertpolicyserviceModule.v3.AlertPolicyServiceClient.servicePath; + assert.strictEqual(servicePath, 'monitoring.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + alertpolicyserviceModule.v3.AlertPolicyServiceClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'monitoring.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ + universeDomain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'monitoring.example.com'); }); - describe('deleteAlertPolicy', () => { - it('invokes deleteAlertPolicy without error', async () => { - const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.DeleteAlertPolicyRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.DeleteAlertPolicyRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteAlertPolicy = stubSimpleCall(expectedResponse); - const [response] = await client.deleteAlertPolicy(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteAlertPolicy as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteAlertPolicy as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ + universe_domain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'monitoring.example.com'); + }); - it('invokes deleteAlertPolicy without error using callback', async () => { - const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.DeleteAlertPolicyRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.DeleteAlertPolicyRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteAlertPolicy = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteAlertPolicy( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteAlertPolicy as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteAlertPolicy as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + if (typeof process === 'object' && 'env' in process) { + describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { + it('sets apiEndpoint from environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = + new alertpolicyserviceModule.v3.AlertPolicyServiceClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'monitoring.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - it('invokes deleteAlertPolicy with error', async () => { - const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.DeleteAlertPolicyRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.DeleteAlertPolicyRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteAlertPolicy = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteAlertPolicy(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteAlertPolicy as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteAlertPolicy as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('value configured in code has priority over environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = + new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ + universeDomain: 'configured.example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'monitoring.configured.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - - it('invokes deleteAlertPolicy with closed client', async () => { - const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.DeleteAlertPolicyRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.DeleteAlertPolicyRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteAlertPolicy(request), expectedError); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); }); - describe('updateAlertPolicy', () => { - it('invokes updateAlertPolicy without error', async () => { - const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.UpdateAlertPolicyRequest() - ); - request.alertPolicy ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.UpdateAlertPolicyRequest', ['alertPolicy', 'name']); - request.alertPolicy.name = defaultValue1; - const expectedHeaderRequestParams = `alert_policy.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.monitoring.v3.AlertPolicy() - ); - client.innerApiCalls.updateAlertPolicy = stubSimpleCall(expectedResponse); - const [response] = await client.updateAlertPolicy(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateAlertPolicy as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateAlertPolicy as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateAlertPolicy without error using callback', async () => { - const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.UpdateAlertPolicyRequest() - ); - request.alertPolicy ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.UpdateAlertPolicyRequest', ['alertPolicy', 'name']); - request.alertPolicy.name = defaultValue1; - const expectedHeaderRequestParams = `alert_policy.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.monitoring.v3.AlertPolicy() - ); - client.innerApiCalls.updateAlertPolicy = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateAlertPolicy( - request, - (err?: Error|null, result?: protos.google.monitoring.v3.IAlertPolicy|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateAlertPolicy as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateAlertPolicy as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has port', () => { + const port = alertpolicyserviceModule.v3.AlertPolicyServiceClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('invokes updateAlertPolicy with error', async () => { - const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.UpdateAlertPolicyRequest() - ); - request.alertPolicy ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.UpdateAlertPolicyRequest', ['alertPolicy', 'name']); - request.alertPolicy.name = defaultValue1; - const expectedHeaderRequestParams = `alert_policy.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateAlertPolicy = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateAlertPolicy(request), expectedError); - const actualRequest = (client.innerApiCalls.updateAlertPolicy as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateAlertPolicy as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('should create a client with no option', () => { + const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient(); + assert(client); + }); - it('invokes updateAlertPolicy with closed client', async () => { - const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.UpdateAlertPolicyRequest() - ); - request.alertPolicy ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.UpdateAlertPolicyRequest', ['alertPolicy', 'name']); - request.alertPolicy.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateAlertPolicy(request), expectedError); - }); + it('should create a client with gRPC fallback', () => { + const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ + fallback: true, + }); + assert(client); }); - describe('listAlertPolicies', () => { - it('invokes listAlertPolicies without error', async () => { - const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListAlertPoliciesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListAlertPoliciesRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.monitoring.v3.AlertPolicy()), - generateSampleMessage(new protos.google.monitoring.v3.AlertPolicy()), - generateSampleMessage(new protos.google.monitoring.v3.AlertPolicy()), - ]; - client.innerApiCalls.listAlertPolicies = stubSimpleCall(expectedResponse); - const [response] = await client.listAlertPolicies(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listAlertPolicies as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listAlertPolicies as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has initialize method and supports deferred initialization', async () => { + const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.alertPolicyServiceStub, undefined); + await client.initialize(); + assert(client.alertPolicyServiceStub); + }); - it('invokes listAlertPolicies without error using callback', async () => { - const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListAlertPoliciesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListAlertPoliciesRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.monitoring.v3.AlertPolicy()), - generateSampleMessage(new protos.google.monitoring.v3.AlertPolicy()), - generateSampleMessage(new protos.google.monitoring.v3.AlertPolicy()), - ]; - client.innerApiCalls.listAlertPolicies = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listAlertPolicies( - request, - (err?: Error|null, result?: protos.google.monitoring.v3.IAlertPolicy[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listAlertPolicies as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listAlertPolicies as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('has close method for the initialized client', (done) => { + const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.alertPolicyServiceStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes listAlertPolicies with error', async () => { - const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListAlertPoliciesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListAlertPoliciesRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listAlertPolicies = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listAlertPolicies(request), expectedError); - const actualRequest = (client.innerApiCalls.listAlertPolicies as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listAlertPolicies as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('has close method for the non-initialized client', (done) => { + const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.alertPolicyServiceStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes listAlertPoliciesStream without error', async () => { - const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListAlertPoliciesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListAlertPoliciesRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.monitoring.v3.AlertPolicy()), - generateSampleMessage(new protos.google.monitoring.v3.AlertPolicy()), - generateSampleMessage(new protos.google.monitoring.v3.AlertPolicy()), - ]; - client.descriptors.page.listAlertPolicies.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listAlertPoliciesStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.monitoring.v3.AlertPolicy[] = []; - stream.on('data', (response: protos.google.monitoring.v3.AlertPolicy) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.listAlertPolicies.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listAlertPolicies, request)); - assert( - (client.descriptors.page.listAlertPolicies.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + }); - it('invokes listAlertPoliciesStream with error', async () => { - const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListAlertPoliciesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListAlertPoliciesRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listAlertPolicies.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listAlertPoliciesStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.monitoring.v3.AlertPolicy[] = []; - stream.on('data', (response: protos.google.monitoring.v3.AlertPolicy) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listAlertPolicies.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listAlertPolicies, request)); - assert( - (client.descriptors.page.listAlertPolicies.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + }); + + describe('getAlertPolicy', () => { + it('invokes getAlertPolicy without error', async () => { + const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.GetAlertPolicyRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.GetAlertPolicyRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.monitoring.v3.AlertPolicy(), + ); + client.innerApiCalls.getAlertPolicy = stubSimpleCall(expectedResponse); + const [response] = await client.getAlertPolicy(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getAlertPolicy as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getAlertPolicy as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('uses async iteration with listAlertPolicies without error', async () => { - const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListAlertPoliciesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListAlertPoliciesRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.monitoring.v3.AlertPolicy()), - generateSampleMessage(new protos.google.monitoring.v3.AlertPolicy()), - generateSampleMessage(new protos.google.monitoring.v3.AlertPolicy()), - ]; - client.descriptors.page.listAlertPolicies.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.monitoring.v3.IAlertPolicy[] = []; - const iterable = client.listAlertPoliciesAsync(request); - for await (const resource of iterable) { - responses.push(resource!); + it('invokes getAlertPolicy without error using callback', async () => { + const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.GetAlertPolicyRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.GetAlertPolicyRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.monitoring.v3.AlertPolicy(), + ); + client.innerApiCalls.getAlertPolicy = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getAlertPolicy( + request, + ( + err?: Error | null, + result?: protos.google.monitoring.v3.IAlertPolicy | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listAlertPolicies.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listAlertPolicies.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); - - it('uses async iteration with listAlertPolicies with error', async () => { - const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListAlertPoliciesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListAlertPoliciesRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listAlertPolicies.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listAlertPoliciesAsync(request); - await assert.rejects(async () => { - const responses: protos.google.monitoring.v3.IAlertPolicy[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listAlertPolicies.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listAlertPolicies.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getAlertPolicy as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getAlertPolicy as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('Path templates', () => { - - describe('folderAlertPolicy', () => { - const fakePath = "/rendered/path/folderAlertPolicy"; - const expectedParameters = { - folder: "folderValue", - alert_policy: "alertPolicyValue", - }; - const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.folderAlertPolicyPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderAlertPolicyPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderAlertPolicyPath', () => { - const result = client.folderAlertPolicyPath("folderValue", "alertPolicyValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderAlertPolicyPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderAlertPolicyName', () => { - const result = client.matchFolderFromFolderAlertPolicyName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderAlertPolicyPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchAlertPolicyFromFolderAlertPolicyName', () => { - const result = client.matchAlertPolicyFromFolderAlertPolicyName(fakePath); - assert.strictEqual(result, "alertPolicyValue"); - assert((client.pathTemplates.folderAlertPolicyPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('folderAlertPolicyCondition', () => { - const fakePath = "/rendered/path/folderAlertPolicyCondition"; - const expectedParameters = { - folder: "folderValue", - alert_policy: "alertPolicyValue", - condition: "conditionValue", - }; - const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.folderAlertPolicyConditionPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderAlertPolicyConditionPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderAlertPolicyConditionPath', () => { - const result = client.folderAlertPolicyConditionPath("folderValue", "alertPolicyValue", "conditionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderAlertPolicyConditionPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderAlertPolicyConditionName', () => { - const result = client.matchFolderFromFolderAlertPolicyConditionName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderAlertPolicyConditionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchAlertPolicyFromFolderAlertPolicyConditionName', () => { - const result = client.matchAlertPolicyFromFolderAlertPolicyConditionName(fakePath); - assert.strictEqual(result, "alertPolicyValue"); - assert((client.pathTemplates.folderAlertPolicyConditionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchConditionFromFolderAlertPolicyConditionName', () => { - const result = client.matchConditionFromFolderAlertPolicyConditionName(fakePath); - assert.strictEqual(result, "conditionValue"); - assert((client.pathTemplates.folderAlertPolicyConditionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('folderChannelDescriptor', () => { - const fakePath = "/rendered/path/folderChannelDescriptor"; - const expectedParameters = { - folder: "folderValue", - channel_descriptor: "channelDescriptorValue", - }; - const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.folderChannelDescriptorPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderChannelDescriptorPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderChannelDescriptorPath', () => { - const result = client.folderChannelDescriptorPath("folderValue", "channelDescriptorValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderChannelDescriptorPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderChannelDescriptorName', () => { - const result = client.matchFolderFromFolderChannelDescriptorName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderChannelDescriptorPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchChannelDescriptorFromFolderChannelDescriptorName', () => { - const result = client.matchChannelDescriptorFromFolderChannelDescriptorName(fakePath); - assert.strictEqual(result, "channelDescriptorValue"); - assert((client.pathTemplates.folderChannelDescriptorPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('folderGroup', () => { - const fakePath = "/rendered/path/folderGroup"; - const expectedParameters = { - folder: "folderValue", - group: "groupValue", - }; - const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.folderGroupPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderGroupPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderGroupPath', () => { - const result = client.folderGroupPath("folderValue", "groupValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderGroupPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderGroupName', () => { - const result = client.matchFolderFromFolderGroupName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderGroupPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchGroupFromFolderGroupName', () => { - const result = client.matchGroupFromFolderGroupName(fakePath); - assert.strictEqual(result, "groupValue"); - assert((client.pathTemplates.folderGroupPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('folderNotificationChannel', () => { - const fakePath = "/rendered/path/folderNotificationChannel"; - const expectedParameters = { - folder: "folderValue", - notification_channel: "notificationChannelValue", - }; - const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.folderNotificationChannelPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderNotificationChannelPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderNotificationChannelPath', () => { - const result = client.folderNotificationChannelPath("folderValue", "notificationChannelValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderNotificationChannelPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderNotificationChannelName', () => { - const result = client.matchFolderFromFolderNotificationChannelName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderNotificationChannelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchNotificationChannelFromFolderNotificationChannelName', () => { - const result = client.matchNotificationChannelFromFolderNotificationChannelName(fakePath); - assert.strictEqual(result, "notificationChannelValue"); - assert((client.pathTemplates.folderNotificationChannelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('folderService', () => { - const fakePath = "/rendered/path/folderService"; - const expectedParameters = { - folder: "folderValue", - service: "serviceValue", - }; - const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.folderServicePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderServicePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderServicePath', () => { - const result = client.folderServicePath("folderValue", "serviceValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderServicePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderServiceName', () => { - const result = client.matchFolderFromFolderServiceName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderServicePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServiceFromFolderServiceName', () => { - const result = client.matchServiceFromFolderServiceName(fakePath); - assert.strictEqual(result, "serviceValue"); - assert((client.pathTemplates.folderServicePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('folderServiceServiceLevelObjective', () => { - const fakePath = "/rendered/path/folderServiceServiceLevelObjective"; - const expectedParameters = { - folder: "folderValue", - service: "serviceValue", - service_level_objective: "serviceLevelObjectiveValue", - }; - const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderServiceServiceLevelObjectivePath', () => { - const result = client.folderServiceServiceLevelObjectivePath("folderValue", "serviceValue", "serviceLevelObjectiveValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderServiceServiceLevelObjectiveName', () => { - const result = client.matchFolderFromFolderServiceServiceLevelObjectiveName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServiceFromFolderServiceServiceLevelObjectiveName', () => { - const result = client.matchServiceFromFolderServiceServiceLevelObjectiveName(fakePath); - assert.strictEqual(result, "serviceValue"); - assert((client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServiceLevelObjectiveFromFolderServiceServiceLevelObjectiveName', () => { - const result = client.matchServiceLevelObjectiveFromFolderServiceServiceLevelObjectiveName(fakePath); - assert.strictEqual(result, "serviceLevelObjectiveValue"); - assert((client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('folderUptimeCheckConfig', () => { - const fakePath = "/rendered/path/folderUptimeCheckConfig"; - const expectedParameters = { - folder: "folderValue", - uptime_check_config: "uptimeCheckConfigValue", - }; - const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.folderUptimeCheckConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderUptimeCheckConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderUptimeCheckConfigPath', () => { - const result = client.folderUptimeCheckConfigPath("folderValue", "uptimeCheckConfigValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderUptimeCheckConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderUptimeCheckConfigName', () => { - const result = client.matchFolderFromFolderUptimeCheckConfigName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderUptimeCheckConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchUptimeCheckConfigFromFolderUptimeCheckConfigName', () => { - const result = client.matchUptimeCheckConfigFromFolderUptimeCheckConfigName(fakePath); - assert.strictEqual(result, "uptimeCheckConfigValue"); - assert((client.pathTemplates.folderUptimeCheckConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('organizationAlertPolicy', () => { - const fakePath = "/rendered/path/organizationAlertPolicy"; - const expectedParameters = { - organization: "organizationValue", - alert_policy: "alertPolicyValue", - }; - const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.organizationAlertPolicyPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationAlertPolicyPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationAlertPolicyPath', () => { - const result = client.organizationAlertPolicyPath("organizationValue", "alertPolicyValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationAlertPolicyPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationAlertPolicyName', () => { - const result = client.matchOrganizationFromOrganizationAlertPolicyName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationAlertPolicyPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchAlertPolicyFromOrganizationAlertPolicyName', () => { - const result = client.matchAlertPolicyFromOrganizationAlertPolicyName(fakePath); - assert.strictEqual(result, "alertPolicyValue"); - assert((client.pathTemplates.organizationAlertPolicyPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('invokes getAlertPolicy with error', async () => { + const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.GetAlertPolicyRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.GetAlertPolicyRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getAlertPolicy = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getAlertPolicy(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getAlertPolicy as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getAlertPolicy as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - describe('organizationAlertPolicyCondition', () => { - const fakePath = "/rendered/path/organizationAlertPolicyCondition"; - const expectedParameters = { - organization: "organizationValue", - alert_policy: "alertPolicyValue", - condition: "conditionValue", - }; - const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.organizationAlertPolicyConditionPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationAlertPolicyConditionPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationAlertPolicyConditionPath', () => { - const result = client.organizationAlertPolicyConditionPath("organizationValue", "alertPolicyValue", "conditionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationAlertPolicyConditionPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + it('invokes getAlertPolicy with closed client', async () => { + const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.GetAlertPolicyRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.GetAlertPolicyRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getAlertPolicy(request), expectedError); + }); + }); + + describe('createAlertPolicy', () => { + it('invokes createAlertPolicy without error', async () => { + const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.CreateAlertPolicyRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.CreateAlertPolicyRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.monitoring.v3.AlertPolicy(), + ); + client.innerApiCalls.createAlertPolicy = stubSimpleCall(expectedResponse); + const [response] = await client.createAlertPolicy(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createAlertPolicy as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createAlertPolicy as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('matchOrganizationFromOrganizationAlertPolicyConditionName', () => { - const result = client.matchOrganizationFromOrganizationAlertPolicyConditionName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationAlertPolicyConditionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('invokes createAlertPolicy without error using callback', async () => { + const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.CreateAlertPolicyRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.CreateAlertPolicyRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.monitoring.v3.AlertPolicy(), + ); + client.innerApiCalls.createAlertPolicy = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createAlertPolicy( + request, + ( + err?: Error | null, + result?: protos.google.monitoring.v3.IAlertPolicy | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createAlertPolicy as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createAlertPolicy as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('matchAlertPolicyFromOrganizationAlertPolicyConditionName', () => { - const result = client.matchAlertPolicyFromOrganizationAlertPolicyConditionName(fakePath); - assert.strictEqual(result, "alertPolicyValue"); - assert((client.pathTemplates.organizationAlertPolicyConditionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('invokes createAlertPolicy with error', async () => { + const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.CreateAlertPolicyRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.CreateAlertPolicyRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createAlertPolicy = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.createAlertPolicy(request), expectedError); + const actualRequest = ( + client.innerApiCalls.createAlertPolicy as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createAlertPolicy as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('matchConditionFromOrganizationAlertPolicyConditionName', () => { - const result = client.matchConditionFromOrganizationAlertPolicyConditionName(fakePath); - assert.strictEqual(result, "conditionValue"); - assert((client.pathTemplates.organizationAlertPolicyConditionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('invokes createAlertPolicy with closed client', async () => { + const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.CreateAlertPolicyRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.CreateAlertPolicyRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.createAlertPolicy(request), expectedError); + }); + }); + + describe('deleteAlertPolicy', () => { + it('invokes deleteAlertPolicy without error', async () => { + const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.DeleteAlertPolicyRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.DeleteAlertPolicyRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteAlertPolicy = stubSimpleCall(expectedResponse); + const [response] = await client.deleteAlertPolicy(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteAlertPolicy as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteAlertPolicy as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - describe('organizationChannelDescriptor', () => { - const fakePath = "/rendered/path/organizationChannelDescriptor"; - const expectedParameters = { - organization: "organizationValue", - channel_descriptor: "channelDescriptorValue", - }; - const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.organizationChannelDescriptorPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationChannelDescriptorPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationChannelDescriptorPath', () => { - const result = client.organizationChannelDescriptorPath("organizationValue", "channelDescriptorValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationChannelDescriptorPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + it('invokes deleteAlertPolicy without error using callback', async () => { + const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.DeleteAlertPolicyRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.DeleteAlertPolicyRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteAlertPolicy = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteAlertPolicy( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteAlertPolicy as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteAlertPolicy as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('matchOrganizationFromOrganizationChannelDescriptorName', () => { - const result = client.matchOrganizationFromOrganizationChannelDescriptorName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationChannelDescriptorPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('invokes deleteAlertPolicy with error', async () => { + const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.DeleteAlertPolicyRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.DeleteAlertPolicyRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteAlertPolicy = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.deleteAlertPolicy(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteAlertPolicy as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteAlertPolicy as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('matchChannelDescriptorFromOrganizationChannelDescriptorName', () => { - const result = client.matchChannelDescriptorFromOrganizationChannelDescriptorName(fakePath); - assert.strictEqual(result, "channelDescriptorValue"); - assert((client.pathTemplates.organizationChannelDescriptorPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('invokes deleteAlertPolicy with closed client', async () => { + const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.DeleteAlertPolicyRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.DeleteAlertPolicyRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.deleteAlertPolicy(request), expectedError); + }); + }); + + describe('updateAlertPolicy', () => { + it('invokes updateAlertPolicy without error', async () => { + const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.UpdateAlertPolicyRequest(), + ); + request.alertPolicy ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.UpdateAlertPolicyRequest', + ['alertPolicy', 'name'], + ); + request.alertPolicy.name = defaultValue1; + const expectedHeaderRequestParams = `alert_policy.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.monitoring.v3.AlertPolicy(), + ); + client.innerApiCalls.updateAlertPolicy = stubSimpleCall(expectedResponse); + const [response] = await client.updateAlertPolicy(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateAlertPolicy as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateAlertPolicy as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - describe('organizationGroup', () => { - const fakePath = "/rendered/path/organizationGroup"; - const expectedParameters = { - organization: "organizationValue", - group: "groupValue", - }; - const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.organizationGroupPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationGroupPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationGroupPath', () => { - const result = client.organizationGroupPath("organizationValue", "groupValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationGroupPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + it('invokes updateAlertPolicy without error using callback', async () => { + const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.UpdateAlertPolicyRequest(), + ); + request.alertPolicy ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.UpdateAlertPolicyRequest', + ['alertPolicy', 'name'], + ); + request.alertPolicy.name = defaultValue1; + const expectedHeaderRequestParams = `alert_policy.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.monitoring.v3.AlertPolicy(), + ); + client.innerApiCalls.updateAlertPolicy = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateAlertPolicy( + request, + ( + err?: Error | null, + result?: protos.google.monitoring.v3.IAlertPolicy | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateAlertPolicy as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateAlertPolicy as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('matchOrganizationFromOrganizationGroupName', () => { - const result = client.matchOrganizationFromOrganizationGroupName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationGroupPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('invokes updateAlertPolicy with error', async () => { + const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.UpdateAlertPolicyRequest(), + ); + request.alertPolicy ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.UpdateAlertPolicyRequest', + ['alertPolicy', 'name'], + ); + request.alertPolicy.name = defaultValue1; + const expectedHeaderRequestParams = `alert_policy.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateAlertPolicy = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.updateAlertPolicy(request), expectedError); + const actualRequest = ( + client.innerApiCalls.updateAlertPolicy as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateAlertPolicy as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('matchGroupFromOrganizationGroupName', () => { - const result = client.matchGroupFromOrganizationGroupName(fakePath); - assert.strictEqual(result, "groupValue"); - assert((client.pathTemplates.organizationGroupPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('invokes updateAlertPolicy with closed client', async () => { + const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.UpdateAlertPolicyRequest(), + ); + request.alertPolicy ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.UpdateAlertPolicyRequest', + ['alertPolicy', 'name'], + ); + request.alertPolicy.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.updateAlertPolicy(request), expectedError); + }); + }); + + describe('listAlertPolicies', () => { + it('invokes listAlertPolicies without error', async () => { + const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListAlertPoliciesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListAlertPoliciesRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.monitoring.v3.AlertPolicy()), + generateSampleMessage(new protos.google.monitoring.v3.AlertPolicy()), + generateSampleMessage(new protos.google.monitoring.v3.AlertPolicy()), + ]; + client.innerApiCalls.listAlertPolicies = stubSimpleCall(expectedResponse); + const [response] = await client.listAlertPolicies(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listAlertPolicies as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listAlertPolicies as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - describe('organizationNotificationChannel', () => { - const fakePath = "/rendered/path/organizationNotificationChannel"; - const expectedParameters = { - organization: "organizationValue", - notification_channel: "notificationChannelValue", - }; - const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.organizationNotificationChannelPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationNotificationChannelPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationNotificationChannelPath', () => { - const result = client.organizationNotificationChannelPath("organizationValue", "notificationChannelValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationNotificationChannelPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + it('invokes listAlertPolicies without error using callback', async () => { + const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListAlertPoliciesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListAlertPoliciesRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.monitoring.v3.AlertPolicy()), + generateSampleMessage(new protos.google.monitoring.v3.AlertPolicy()), + generateSampleMessage(new protos.google.monitoring.v3.AlertPolicy()), + ]; + client.innerApiCalls.listAlertPolicies = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listAlertPolicies( + request, + ( + err?: Error | null, + result?: protos.google.monitoring.v3.IAlertPolicy[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listAlertPolicies as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listAlertPolicies as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('matchOrganizationFromOrganizationNotificationChannelName', () => { - const result = client.matchOrganizationFromOrganizationNotificationChannelName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationNotificationChannelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('invokes listAlertPolicies with error', async () => { + const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListAlertPoliciesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListAlertPoliciesRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listAlertPolicies = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listAlertPolicies(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listAlertPolicies as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listAlertPolicies as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('matchNotificationChannelFromOrganizationNotificationChannelName', () => { - const result = client.matchNotificationChannelFromOrganizationNotificationChannelName(fakePath); - assert.strictEqual(result, "notificationChannelValue"); - assert((client.pathTemplates.organizationNotificationChannelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('invokes listAlertPoliciesStream without error', async () => { + const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListAlertPoliciesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListAlertPoliciesRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.monitoring.v3.AlertPolicy()), + generateSampleMessage(new protos.google.monitoring.v3.AlertPolicy()), + generateSampleMessage(new protos.google.monitoring.v3.AlertPolicy()), + ]; + client.descriptors.page.listAlertPolicies.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listAlertPoliciesStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.monitoring.v3.AlertPolicy[] = []; + stream.on( + 'data', + (response: protos.google.monitoring.v3.AlertPolicy) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); }); - - describe('organizationService', () => { - const fakePath = "/rendered/path/organizationService"; - const expectedParameters = { - organization: "organizationValue", - service: "serviceValue", - }; - const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.organizationServicePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationServicePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationServicePath', () => { - const result = client.organizationServicePath("organizationValue", "serviceValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationServicePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationServiceName', () => { - const result = client.matchOrganizationFromOrganizationServiceName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationServicePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServiceFromOrganizationServiceName', () => { - const result = client.matchServiceFromOrganizationServiceName(fakePath); - assert.strictEqual(result, "serviceValue"); - assert((client.pathTemplates.organizationServicePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + stream.on('error', (err: Error) => { + reject(err); }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listAlertPolicies.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listAlertPolicies, request), + ); + assert( + (client.descriptors.page.listAlertPolicies.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - describe('organizationServiceServiceLevelObjective', () => { - const fakePath = "/rendered/path/organizationServiceServiceLevelObjective"; - const expectedParameters = { - organization: "organizationValue", - service: "serviceValue", - service_level_objective: "serviceLevelObjectiveValue", - }; - const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationServiceServiceLevelObjectivePath', () => { - const result = client.organizationServiceServiceLevelObjectivePath("organizationValue", "serviceValue", "serviceLevelObjectiveValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationServiceServiceLevelObjectiveName', () => { - const result = client.matchOrganizationFromOrganizationServiceServiceLevelObjectiveName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServiceFromOrganizationServiceServiceLevelObjectiveName', () => { - const result = client.matchServiceFromOrganizationServiceServiceLevelObjectiveName(fakePath); - assert.strictEqual(result, "serviceValue"); - assert((client.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServiceLevelObjectiveFromOrganizationServiceServiceLevelObjectiveName', () => { - const result = client.matchServiceLevelObjectiveFromOrganizationServiceServiceLevelObjectiveName(fakePath); - assert.strictEqual(result, "serviceLevelObjectiveValue"); - assert((client.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('invokes listAlertPoliciesStream with error', async () => { + const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListAlertPoliciesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListAlertPoliciesRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listAlertPolicies.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listAlertPoliciesStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.monitoring.v3.AlertPolicy[] = []; + stream.on( + 'data', + (response: protos.google.monitoring.v3.AlertPolicy) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); }); - - describe('organizationUptimeCheckConfig', () => { - const fakePath = "/rendered/path/organizationUptimeCheckConfig"; - const expectedParameters = { - organization: "organizationValue", - uptime_check_config: "uptimeCheckConfigValue", - }; - const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.organizationUptimeCheckConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationUptimeCheckConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationUptimeCheckConfigPath', () => { - const result = client.organizationUptimeCheckConfigPath("organizationValue", "uptimeCheckConfigValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationUptimeCheckConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationUptimeCheckConfigName', () => { - const result = client.matchOrganizationFromOrganizationUptimeCheckConfigName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationUptimeCheckConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchUptimeCheckConfigFromOrganizationUptimeCheckConfigName', () => { - const result = client.matchUptimeCheckConfigFromOrganizationUptimeCheckConfigName(fakePath); - assert.strictEqual(result, "uptimeCheckConfigValue"); - assert((client.pathTemplates.organizationUptimeCheckConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + stream.on('error', (err: Error) => { + reject(err); }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listAlertPolicies.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listAlertPolicies, request), + ); + assert( + (client.descriptors.page.listAlertPolicies.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - describe('projectAlertPolicy', () => { - const fakePath = "/rendered/path/projectAlertPolicy"; - const expectedParameters = { - project: "projectValue", - alert_policy: "alertPolicyValue", - }; - const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.projectAlertPolicyPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectAlertPolicyPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectAlertPolicyPath', () => { - const result = client.projectAlertPolicyPath("projectValue", "alertPolicyValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectAlertPolicyPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectAlertPolicyName', () => { - const result = client.matchProjectFromProjectAlertPolicyName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectAlertPolicyPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('uses async iteration with listAlertPolicies without error', async () => { + const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListAlertPoliciesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListAlertPoliciesRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.monitoring.v3.AlertPolicy()), + generateSampleMessage(new protos.google.monitoring.v3.AlertPolicy()), + generateSampleMessage(new protos.google.monitoring.v3.AlertPolicy()), + ]; + client.descriptors.page.listAlertPolicies.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.monitoring.v3.IAlertPolicy[] = []; + const iterable = client.listAlertPoliciesAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listAlertPolicies.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listAlertPolicies.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('matchAlertPolicyFromProjectAlertPolicyName', () => { - const result = client.matchAlertPolicyFromProjectAlertPolicyName(fakePath); - assert.strictEqual(result, "alertPolicyValue"); - assert((client.pathTemplates.projectAlertPolicyPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('uses async iteration with listAlertPolicies with error', async () => { + const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListAlertPoliciesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListAlertPoliciesRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listAlertPolicies.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listAlertPoliciesAsync(request); + await assert.rejects(async () => { + const responses: protos.google.monitoring.v3.IAlertPolicy[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listAlertPolicies.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listAlertPolicies.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + }); + + describe('Path templates', () => { + describe('folderAlertPolicy', () => { + const fakePath = '/rendered/path/folderAlertPolicy'; + const expectedParameters = { + folder: 'folderValue', + alert_policy: 'alertPolicyValue', + }; + const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.folderAlertPolicyPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderAlertPolicyPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderAlertPolicyPath', () => { + const result = client.folderAlertPolicyPath( + 'folderValue', + 'alertPolicyValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.folderAlertPolicyPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderAlertPolicyName', () => { + const result = client.matchFolderFromFolderAlertPolicyName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + ( + client.pathTemplates.folderAlertPolicyPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchAlertPolicyFromFolderAlertPolicyName', () => { + const result = + client.matchAlertPolicyFromFolderAlertPolicyName(fakePath); + assert.strictEqual(result, 'alertPolicyValue'); + assert( + ( + client.pathTemplates.folderAlertPolicyPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectAlertPolicyCondition', () => { - const fakePath = "/rendered/path/projectAlertPolicyCondition"; - const expectedParameters = { - project: "projectValue", - alert_policy: "alertPolicyValue", - condition: "conditionValue", - }; - const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.projectAlertPolicyConditionPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectAlertPolicyConditionPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectAlertPolicyConditionPath', () => { - const result = client.projectAlertPolicyConditionPath("projectValue", "alertPolicyValue", "conditionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectAlertPolicyConditionPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + describe('folderAlertPolicyCondition', () => { + const fakePath = '/rendered/path/folderAlertPolicyCondition'; + const expectedParameters = { + folder: 'folderValue', + alert_policy: 'alertPolicyValue', + condition: 'conditionValue', + }; + const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.folderAlertPolicyConditionPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderAlertPolicyConditionPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderAlertPolicyConditionPath', () => { + const result = client.folderAlertPolicyConditionPath( + 'folderValue', + 'alertPolicyValue', + 'conditionValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.folderAlertPolicyConditionPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderAlertPolicyConditionName', () => { + const result = + client.matchFolderFromFolderAlertPolicyConditionName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + ( + client.pathTemplates.folderAlertPolicyConditionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchAlertPolicyFromFolderAlertPolicyConditionName', () => { + const result = + client.matchAlertPolicyFromFolderAlertPolicyConditionName(fakePath); + assert.strictEqual(result, 'alertPolicyValue'); + assert( + ( + client.pathTemplates.folderAlertPolicyConditionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchConditionFromFolderAlertPolicyConditionName', () => { + const result = + client.matchConditionFromFolderAlertPolicyConditionName(fakePath); + assert.strictEqual(result, 'conditionValue'); + assert( + ( + client.pathTemplates.folderAlertPolicyConditionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchProjectFromProjectAlertPolicyConditionName', () => { - const result = client.matchProjectFromProjectAlertPolicyConditionName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectAlertPolicyConditionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('folderChannelDescriptor', () => { + const fakePath = '/rendered/path/folderChannelDescriptor'; + const expectedParameters = { + folder: 'folderValue', + channel_descriptor: 'channelDescriptorValue', + }; + const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.folderChannelDescriptorPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderChannelDescriptorPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderChannelDescriptorPath', () => { + const result = client.folderChannelDescriptorPath( + 'folderValue', + 'channelDescriptorValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.folderChannelDescriptorPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderChannelDescriptorName', () => { + const result = + client.matchFolderFromFolderChannelDescriptorName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + ( + client.pathTemplates.folderChannelDescriptorPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchChannelDescriptorFromFolderChannelDescriptorName', () => { + const result = + client.matchChannelDescriptorFromFolderChannelDescriptorName( + fakePath, + ); + assert.strictEqual(result, 'channelDescriptorValue'); + assert( + ( + client.pathTemplates.folderChannelDescriptorPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchAlertPolicyFromProjectAlertPolicyConditionName', () => { - const result = client.matchAlertPolicyFromProjectAlertPolicyConditionName(fakePath); - assert.strictEqual(result, "alertPolicyValue"); - assert((client.pathTemplates.projectAlertPolicyConditionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('folderGroup', () => { + const fakePath = '/rendered/path/folderGroup'; + const expectedParameters = { + folder: 'folderValue', + group: 'groupValue', + }; + const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.folderGroupPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderGroupPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderGroupPath', () => { + const result = client.folderGroupPath('folderValue', 'groupValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.folderGroupPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderGroupName', () => { + const result = client.matchFolderFromFolderGroupName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + (client.pathTemplates.folderGroupPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchGroupFromFolderGroupName', () => { + const result = client.matchGroupFromFolderGroupName(fakePath); + assert.strictEqual(result, 'groupValue'); + assert( + (client.pathTemplates.folderGroupPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchConditionFromProjectAlertPolicyConditionName', () => { - const result = client.matchConditionFromProjectAlertPolicyConditionName(fakePath); - assert.strictEqual(result, "conditionValue"); - assert((client.pathTemplates.projectAlertPolicyConditionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('folderNotificationChannel', () => { + const fakePath = '/rendered/path/folderNotificationChannel'; + const expectedParameters = { + folder: 'folderValue', + notification_channel: 'notificationChannelValue', + }; + const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.folderNotificationChannelPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderNotificationChannelPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderNotificationChannelPath', () => { + const result = client.folderNotificationChannelPath( + 'folderValue', + 'notificationChannelValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.folderNotificationChannelPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderNotificationChannelName', () => { + const result = + client.matchFolderFromFolderNotificationChannelName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + ( + client.pathTemplates.folderNotificationChannelPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchNotificationChannelFromFolderNotificationChannelName', () => { + const result = + client.matchNotificationChannelFromFolderNotificationChannelName( + fakePath, + ); + assert.strictEqual(result, 'notificationChannelValue'); + assert( + ( + client.pathTemplates.folderNotificationChannelPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectChannelDescriptor', () => { - const fakePath = "/rendered/path/projectChannelDescriptor"; - const expectedParameters = { - project: "projectValue", - channel_descriptor: "channelDescriptorValue", - }; - const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.projectChannelDescriptorPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectChannelDescriptorPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectChannelDescriptorPath', () => { - const result = client.projectChannelDescriptorPath("projectValue", "channelDescriptorValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectChannelDescriptorPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + describe('folderService', () => { + const fakePath = '/rendered/path/folderService'; + const expectedParameters = { + folder: 'folderValue', + service: 'serviceValue', + }; + const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.folderServicePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderServicePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderServicePath', () => { + const result = client.folderServicePath('folderValue', 'serviceValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.folderServicePathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderServiceName', () => { + const result = client.matchFolderFromFolderServiceName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + (client.pathTemplates.folderServicePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServiceFromFolderServiceName', () => { + const result = client.matchServiceFromFolderServiceName(fakePath); + assert.strictEqual(result, 'serviceValue'); + assert( + (client.pathTemplates.folderServicePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchProjectFromProjectChannelDescriptorName', () => { - const result = client.matchProjectFromProjectChannelDescriptorName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectChannelDescriptorPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('folderServiceServiceLevelObjective', () => { + const fakePath = '/rendered/path/folderServiceServiceLevelObjective'; + const expectedParameters = { + folder: 'folderValue', + service: 'serviceValue', + service_level_objective: 'serviceLevelObjectiveValue', + }; + const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('folderServiceServiceLevelObjectivePath', () => { + const result = client.folderServiceServiceLevelObjectivePath( + 'folderValue', + 'serviceValue', + 'serviceLevelObjectiveValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderServiceServiceLevelObjectiveName', () => { + const result = + client.matchFolderFromFolderServiceServiceLevelObjectiveName( + fakePath, + ); + assert.strictEqual(result, 'folderValue'); + assert( + ( + client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServiceFromFolderServiceServiceLevelObjectiveName', () => { + const result = + client.matchServiceFromFolderServiceServiceLevelObjectiveName( + fakePath, + ); + assert.strictEqual(result, 'serviceValue'); + assert( + ( + client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServiceLevelObjectiveFromFolderServiceServiceLevelObjectiveName', () => { + const result = + client.matchServiceLevelObjectiveFromFolderServiceServiceLevelObjectiveName( + fakePath, + ); + assert.strictEqual(result, 'serviceLevelObjectiveValue'); + assert( + ( + client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchChannelDescriptorFromProjectChannelDescriptorName', () => { - const result = client.matchChannelDescriptorFromProjectChannelDescriptorName(fakePath); - assert.strictEqual(result, "channelDescriptorValue"); - assert((client.pathTemplates.projectChannelDescriptorPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('folderUptimeCheckConfig', () => { + const fakePath = '/rendered/path/folderUptimeCheckConfig'; + const expectedParameters = { + folder: 'folderValue', + uptime_check_config: 'uptimeCheckConfigValue', + }; + const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.folderUptimeCheckConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderUptimeCheckConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderUptimeCheckConfigPath', () => { + const result = client.folderUptimeCheckConfigPath( + 'folderValue', + 'uptimeCheckConfigValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.folderUptimeCheckConfigPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderUptimeCheckConfigName', () => { + const result = + client.matchFolderFromFolderUptimeCheckConfigName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + ( + client.pathTemplates.folderUptimeCheckConfigPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchUptimeCheckConfigFromFolderUptimeCheckConfigName', () => { + const result = + client.matchUptimeCheckConfigFromFolderUptimeCheckConfigName( + fakePath, + ); + assert.strictEqual(result, 'uptimeCheckConfigValue'); + assert( + ( + client.pathTemplates.folderUptimeCheckConfigPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectGroup', () => { - const fakePath = "/rendered/path/projectGroup"; - const expectedParameters = { - project: "projectValue", - group: "groupValue", - }; - const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.projectGroupPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectGroupPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectGroupPath', () => { - const result = client.projectGroupPath("projectValue", "groupValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectGroupPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + describe('organizationAlertPolicy', () => { + const fakePath = '/rendered/path/organizationAlertPolicy'; + const expectedParameters = { + organization: 'organizationValue', + alert_policy: 'alertPolicyValue', + }; + const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.organizationAlertPolicyPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.organizationAlertPolicyPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('organizationAlertPolicyPath', () => { + const result = client.organizationAlertPolicyPath( + 'organizationValue', + 'alertPolicyValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationAlertPolicyPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationAlertPolicyName', () => { + const result = + client.matchOrganizationFromOrganizationAlertPolicyName(fakePath); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationAlertPolicyPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchAlertPolicyFromOrganizationAlertPolicyName', () => { + const result = + client.matchAlertPolicyFromOrganizationAlertPolicyName(fakePath); + assert.strictEqual(result, 'alertPolicyValue'); + assert( + ( + client.pathTemplates.organizationAlertPolicyPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchProjectFromProjectGroupName', () => { - const result = client.matchProjectFromProjectGroupName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectGroupPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('organizationAlertPolicyCondition', () => { + const fakePath = '/rendered/path/organizationAlertPolicyCondition'; + const expectedParameters = { + organization: 'organizationValue', + alert_policy: 'alertPolicyValue', + condition: 'conditionValue', + }; + const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.organizationAlertPolicyConditionPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.organizationAlertPolicyConditionPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('organizationAlertPolicyConditionPath', () => { + const result = client.organizationAlertPolicyConditionPath( + 'organizationValue', + 'alertPolicyValue', + 'conditionValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationAlertPolicyConditionPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationAlertPolicyConditionName', () => { + const result = + client.matchOrganizationFromOrganizationAlertPolicyConditionName( + fakePath, + ); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationAlertPolicyConditionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchAlertPolicyFromOrganizationAlertPolicyConditionName', () => { + const result = + client.matchAlertPolicyFromOrganizationAlertPolicyConditionName( + fakePath, + ); + assert.strictEqual(result, 'alertPolicyValue'); + assert( + ( + client.pathTemplates.organizationAlertPolicyConditionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchConditionFromOrganizationAlertPolicyConditionName', () => { + const result = + client.matchConditionFromOrganizationAlertPolicyConditionName( + fakePath, + ); + assert.strictEqual(result, 'conditionValue'); + assert( + ( + client.pathTemplates.organizationAlertPolicyConditionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchGroupFromProjectGroupName', () => { - const result = client.matchGroupFromProjectGroupName(fakePath); - assert.strictEqual(result, "groupValue"); - assert((client.pathTemplates.projectGroupPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('organizationChannelDescriptor', () => { + const fakePath = '/rendered/path/organizationChannelDescriptor'; + const expectedParameters = { + organization: 'organizationValue', + channel_descriptor: 'channelDescriptorValue', + }; + const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.organizationChannelDescriptorPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.organizationChannelDescriptorPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('organizationChannelDescriptorPath', () => { + const result = client.organizationChannelDescriptorPath( + 'organizationValue', + 'channelDescriptorValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationChannelDescriptorPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationChannelDescriptorName', () => { + const result = + client.matchOrganizationFromOrganizationChannelDescriptorName( + fakePath, + ); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationChannelDescriptorPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchChannelDescriptorFromOrganizationChannelDescriptorName', () => { + const result = + client.matchChannelDescriptorFromOrganizationChannelDescriptorName( + fakePath, + ); + assert.strictEqual(result, 'channelDescriptorValue'); + assert( + ( + client.pathTemplates.organizationChannelDescriptorPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectNotificationChannel', () => { - const fakePath = "/rendered/path/projectNotificationChannel"; - const expectedParameters = { - project: "projectValue", - notification_channel: "notificationChannelValue", - }; - const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.projectNotificationChannelPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectNotificationChannelPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectNotificationChannelPath', () => { - const result = client.projectNotificationChannelPath("projectValue", "notificationChannelValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectNotificationChannelPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + describe('organizationGroup', () => { + const fakePath = '/rendered/path/organizationGroup'; + const expectedParameters = { + organization: 'organizationValue', + group: 'groupValue', + }; + const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.organizationGroupPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.organizationGroupPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('organizationGroupPath', () => { + const result = client.organizationGroupPath( + 'organizationValue', + 'groupValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationGroupPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationGroupName', () => { + const result = + client.matchOrganizationFromOrganizationGroupName(fakePath); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationGroupPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchGroupFromOrganizationGroupName', () => { + const result = client.matchGroupFromOrganizationGroupName(fakePath); + assert.strictEqual(result, 'groupValue'); + assert( + ( + client.pathTemplates.organizationGroupPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchProjectFromProjectNotificationChannelName', () => { - const result = client.matchProjectFromProjectNotificationChannelName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectNotificationChannelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('organizationNotificationChannel', () => { + const fakePath = '/rendered/path/organizationNotificationChannel'; + const expectedParameters = { + organization: 'organizationValue', + notification_channel: 'notificationChannelValue', + }; + const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.organizationNotificationChannelPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.organizationNotificationChannelPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('organizationNotificationChannelPath', () => { + const result = client.organizationNotificationChannelPath( + 'organizationValue', + 'notificationChannelValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationNotificationChannelPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationNotificationChannelName', () => { + const result = + client.matchOrganizationFromOrganizationNotificationChannelName( + fakePath, + ); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationNotificationChannelPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchNotificationChannelFromOrganizationNotificationChannelName', () => { + const result = + client.matchNotificationChannelFromOrganizationNotificationChannelName( + fakePath, + ); + assert.strictEqual(result, 'notificationChannelValue'); + assert( + ( + client.pathTemplates.organizationNotificationChannelPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchNotificationChannelFromProjectNotificationChannelName', () => { - const result = client.matchNotificationChannelFromProjectNotificationChannelName(fakePath); - assert.strictEqual(result, "notificationChannelValue"); - assert((client.pathTemplates.projectNotificationChannelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('organizationService', () => { + const fakePath = '/rendered/path/organizationService'; + const expectedParameters = { + organization: 'organizationValue', + service: 'serviceValue', + }; + const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.organizationServicePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.organizationServicePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('organizationServicePath', () => { + const result = client.organizationServicePath( + 'organizationValue', + 'serviceValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationServicePathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationServiceName', () => { + const result = + client.matchOrganizationFromOrganizationServiceName(fakePath); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationServicePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServiceFromOrganizationServiceName', () => { + const result = client.matchServiceFromOrganizationServiceName(fakePath); + assert.strictEqual(result, 'serviceValue'); + assert( + ( + client.pathTemplates.organizationServicePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectService', () => { - const fakePath = "/rendered/path/projectService"; - const expectedParameters = { - project: "projectValue", - service: "serviceValue", - }; - const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.projectServicePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectServicePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectServicePath', () => { - const result = client.projectServicePath("projectValue", "serviceValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectServicePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + describe('organizationServiceServiceLevelObjective', () => { + const fakePath = + '/rendered/path/organizationServiceServiceLevelObjective'; + const expectedParameters = { + organization: 'organizationValue', + service: 'serviceValue', + service_level_objective: 'serviceLevelObjectiveValue', + }; + const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('organizationServiceServiceLevelObjectivePath', () => { + const result = client.organizationServiceServiceLevelObjectivePath( + 'organizationValue', + 'serviceValue', + 'serviceLevelObjectiveValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates + .organizationServiceServiceLevelObjectivePathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationServiceServiceLevelObjectiveName', () => { + const result = + client.matchOrganizationFromOrganizationServiceServiceLevelObjectiveName( + fakePath, + ); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates + .organizationServiceServiceLevelObjectivePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServiceFromOrganizationServiceServiceLevelObjectiveName', () => { + const result = + client.matchServiceFromOrganizationServiceServiceLevelObjectiveName( + fakePath, + ); + assert.strictEqual(result, 'serviceValue'); + assert( + ( + client.pathTemplates + .organizationServiceServiceLevelObjectivePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServiceLevelObjectiveFromOrganizationServiceServiceLevelObjectiveName', () => { + const result = + client.matchServiceLevelObjectiveFromOrganizationServiceServiceLevelObjectiveName( + fakePath, + ); + assert.strictEqual(result, 'serviceLevelObjectiveValue'); + assert( + ( + client.pathTemplates + .organizationServiceServiceLevelObjectivePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchProjectFromProjectServiceName', () => { - const result = client.matchProjectFromProjectServiceName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectServicePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('organizationUptimeCheckConfig', () => { + const fakePath = '/rendered/path/organizationUptimeCheckConfig'; + const expectedParameters = { + organization: 'organizationValue', + uptime_check_config: 'uptimeCheckConfigValue', + }; + const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.organizationUptimeCheckConfigPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.organizationUptimeCheckConfigPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('organizationUptimeCheckConfigPath', () => { + const result = client.organizationUptimeCheckConfigPath( + 'organizationValue', + 'uptimeCheckConfigValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationUptimeCheckConfigPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationUptimeCheckConfigName', () => { + const result = + client.matchOrganizationFromOrganizationUptimeCheckConfigName( + fakePath, + ); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationUptimeCheckConfigPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchUptimeCheckConfigFromOrganizationUptimeCheckConfigName', () => { + const result = + client.matchUptimeCheckConfigFromOrganizationUptimeCheckConfigName( + fakePath, + ); + assert.strictEqual(result, 'uptimeCheckConfigValue'); + assert( + ( + client.pathTemplates.organizationUptimeCheckConfigPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchServiceFromProjectServiceName', () => { - const result = client.matchServiceFromProjectServiceName(fakePath); - assert.strictEqual(result, "serviceValue"); - assert((client.pathTemplates.projectServicePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectAlertPolicy', () => { + const fakePath = '/rendered/path/projectAlertPolicy'; + const expectedParameters = { + project: 'projectValue', + alert_policy: 'alertPolicyValue', + }; + const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.projectAlertPolicyPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectAlertPolicyPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectAlertPolicyPath', () => { + const result = client.projectAlertPolicyPath( + 'projectValue', + 'alertPolicyValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.projectAlertPolicyPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectAlertPolicyName', () => { + const result = client.matchProjectFromProjectAlertPolicyName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.projectAlertPolicyPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchAlertPolicyFromProjectAlertPolicyName', () => { + const result = + client.matchAlertPolicyFromProjectAlertPolicyName(fakePath); + assert.strictEqual(result, 'alertPolicyValue'); + assert( + ( + client.pathTemplates.projectAlertPolicyPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectServiceServiceLevelObjective', () => { - const fakePath = "/rendered/path/projectServiceServiceLevelObjective"; - const expectedParameters = { - project: "projectValue", - service: "serviceValue", - service_level_objective: "serviceLevelObjectiveValue", - }; - const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectServiceServiceLevelObjectivePath', () => { - const result = client.projectServiceServiceLevelObjectivePath("projectValue", "serviceValue", "serviceLevelObjectiveValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + describe('projectAlertPolicyCondition', () => { + const fakePath = '/rendered/path/projectAlertPolicyCondition'; + const expectedParameters = { + project: 'projectValue', + alert_policy: 'alertPolicyValue', + condition: 'conditionValue', + }; + const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.projectAlertPolicyConditionPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.projectAlertPolicyConditionPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectAlertPolicyConditionPath', () => { + const result = client.projectAlertPolicyConditionPath( + 'projectValue', + 'alertPolicyValue', + 'conditionValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.projectAlertPolicyConditionPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectAlertPolicyConditionName', () => { + const result = + client.matchProjectFromProjectAlertPolicyConditionName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.projectAlertPolicyConditionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchAlertPolicyFromProjectAlertPolicyConditionName', () => { + const result = + client.matchAlertPolicyFromProjectAlertPolicyConditionName(fakePath); + assert.strictEqual(result, 'alertPolicyValue'); + assert( + ( + client.pathTemplates.projectAlertPolicyConditionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchConditionFromProjectAlertPolicyConditionName', () => { + const result = + client.matchConditionFromProjectAlertPolicyConditionName(fakePath); + assert.strictEqual(result, 'conditionValue'); + assert( + ( + client.pathTemplates.projectAlertPolicyConditionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchProjectFromProjectServiceServiceLevelObjectiveName', () => { - const result = client.matchProjectFromProjectServiceServiceLevelObjectiveName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('projectChannelDescriptor', () => { + const fakePath = '/rendered/path/projectChannelDescriptor'; + const expectedParameters = { + project: 'projectValue', + channel_descriptor: 'channelDescriptorValue', + }; + const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.projectChannelDescriptorPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectChannelDescriptorPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectChannelDescriptorPath', () => { + const result = client.projectChannelDescriptorPath( + 'projectValue', + 'channelDescriptorValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.projectChannelDescriptorPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectChannelDescriptorName', () => { + const result = + client.matchProjectFromProjectChannelDescriptorName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.projectChannelDescriptorPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchChannelDescriptorFromProjectChannelDescriptorName', () => { + const result = + client.matchChannelDescriptorFromProjectChannelDescriptorName( + fakePath, + ); + assert.strictEqual(result, 'channelDescriptorValue'); + assert( + ( + client.pathTemplates.projectChannelDescriptorPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchServiceFromProjectServiceServiceLevelObjectiveName', () => { - const result = client.matchServiceFromProjectServiceServiceLevelObjectiveName(fakePath); - assert.strictEqual(result, "serviceValue"); - assert((client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('projectGroup', () => { + const fakePath = '/rendered/path/projectGroup'; + const expectedParameters = { + project: 'projectValue', + group: 'groupValue', + }; + const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.projectGroupPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectGroupPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectGroupPath', () => { + const result = client.projectGroupPath('projectValue', 'groupValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.projectGroupPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectGroupName', () => { + const result = client.matchProjectFromProjectGroupName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.projectGroupPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchGroupFromProjectGroupName', () => { + const result = client.matchGroupFromProjectGroupName(fakePath); + assert.strictEqual(result, 'groupValue'); + assert( + (client.pathTemplates.projectGroupPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchServiceLevelObjectiveFromProjectServiceServiceLevelObjectiveName', () => { - const result = client.matchServiceLevelObjectiveFromProjectServiceServiceLevelObjectiveName(fakePath); - assert.strictEqual(result, "serviceLevelObjectiveValue"); - assert((client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectNotificationChannel', () => { + const fakePath = '/rendered/path/projectNotificationChannel'; + const expectedParameters = { + project: 'projectValue', + notification_channel: 'notificationChannelValue', + }; + const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.projectNotificationChannelPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectNotificationChannelPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectNotificationChannelPath', () => { + const result = client.projectNotificationChannelPath( + 'projectValue', + 'notificationChannelValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.projectNotificationChannelPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectNotificationChannelName', () => { + const result = + client.matchProjectFromProjectNotificationChannelName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.projectNotificationChannelPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchNotificationChannelFromProjectNotificationChannelName', () => { + const result = + client.matchNotificationChannelFromProjectNotificationChannelName( + fakePath, + ); + assert.strictEqual(result, 'notificationChannelValue'); + assert( + ( + client.pathTemplates.projectNotificationChannelPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectUptimeCheckConfig', () => { - const fakePath = "/rendered/path/projectUptimeCheckConfig"; - const expectedParameters = { - project: "projectValue", - uptime_check_config: "uptimeCheckConfigValue", - }; - const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.projectUptimeCheckConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectUptimeCheckConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectUptimeCheckConfigPath', () => { - const result = client.projectUptimeCheckConfigPath("projectValue", "uptimeCheckConfigValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectUptimeCheckConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + describe('projectService', () => { + const fakePath = '/rendered/path/projectService'; + const expectedParameters = { + project: 'projectValue', + service: 'serviceValue', + }; + const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.projectServicePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectServicePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectServicePath', () => { + const result = client.projectServicePath( + 'projectValue', + 'serviceValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.projectServicePathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectServiceName', () => { + const result = client.matchProjectFromProjectServiceName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.projectServicePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServiceFromProjectServiceName', () => { + const result = client.matchServiceFromProjectServiceName(fakePath); + assert.strictEqual(result, 'serviceValue'); + assert( + (client.pathTemplates.projectServicePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchProjectFromProjectUptimeCheckConfigName', () => { - const result = client.matchProjectFromProjectUptimeCheckConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectUptimeCheckConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('projectServiceServiceLevelObjective', () => { + const fakePath = '/rendered/path/projectServiceServiceLevelObjective'; + const expectedParameters = { + project: 'projectValue', + service: 'serviceValue', + service_level_objective: 'serviceLevelObjectiveValue', + }; + const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('projectServiceServiceLevelObjectivePath', () => { + const result = client.projectServiceServiceLevelObjectivePath( + 'projectValue', + 'serviceValue', + 'serviceLevelObjectiveValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectServiceServiceLevelObjectiveName', () => { + const result = + client.matchProjectFromProjectServiceServiceLevelObjectiveName( + fakePath, + ); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServiceFromProjectServiceServiceLevelObjectiveName', () => { + const result = + client.matchServiceFromProjectServiceServiceLevelObjectiveName( + fakePath, + ); + assert.strictEqual(result, 'serviceValue'); + assert( + ( + client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServiceLevelObjectiveFromProjectServiceServiceLevelObjectiveName', () => { + const result = + client.matchServiceLevelObjectiveFromProjectServiceServiceLevelObjectiveName( + fakePath, + ); + assert.strictEqual(result, 'serviceLevelObjectiveValue'); + assert( + ( + client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchUptimeCheckConfigFromProjectUptimeCheckConfigName', () => { - const result = client.matchUptimeCheckConfigFromProjectUptimeCheckConfigName(fakePath); - assert.strictEqual(result, "uptimeCheckConfigValue"); - assert((client.pathTemplates.projectUptimeCheckConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectUptimeCheckConfig', () => { + const fakePath = '/rendered/path/projectUptimeCheckConfig'; + const expectedParameters = { + project: 'projectValue', + uptime_check_config: 'uptimeCheckConfigValue', + }; + const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.projectUptimeCheckConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectUptimeCheckConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectUptimeCheckConfigPath', () => { + const result = client.projectUptimeCheckConfigPath( + 'projectValue', + 'uptimeCheckConfigValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.projectUptimeCheckConfigPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectUptimeCheckConfigName', () => { + const result = + client.matchProjectFromProjectUptimeCheckConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.projectUptimeCheckConfigPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchUptimeCheckConfigFromProjectUptimeCheckConfigName', () => { + const result = + client.matchUptimeCheckConfigFromProjectUptimeCheckConfigName( + fakePath, + ); + assert.strictEqual(result, 'uptimeCheckConfigValue'); + assert( + ( + client.pathTemplates.projectUptimeCheckConfigPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/core/generator/gapic-generator-typescript/baselines/monitoring-esm/esm/test/gapic_group_service_v3.ts.baseline b/core/generator/gapic-generator-typescript/baselines/monitoring-esm/esm/test/gapic_group_service_v3.ts.baseline index 16ae9b02f3ab..b94a66a12723 100644 --- a/core/generator/gapic-generator-typescript/baselines/monitoring-esm/esm/test/gapic_group_service_v3.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/monitoring-esm/esm/test/gapic_group_service_v3.ts.baseline @@ -20,16 +20,16 @@ import * as protos from '../../protos/protos.js'; import assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as groupserviceModule from '../src/index.js'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; -import {protobuf} from 'google-gax'; +import { protobuf } from 'google-gax'; import fs from 'fs'; import path from 'path'; -import {fileURLToPath} from 'url'; +import { fileURLToPath } from 'url'; // @ts-ignore const dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -37,2123 +37,3056 @@ const dirname = path.dirname(fileURLToPath(import.meta.url)); // to fill in default values for request objects const root = protobuf.Root.fromJSON( JSON.parse( - fs.readFileSync(path.join(dirname, '..', '..', 'protos/protos.json'), 'utf8') - )) + fs.readFileSync( + path.join(dirname, '..', '..', 'protos/protos.json'), + 'utf8', + ), + ), +); // eslint-disable-next-line @typescript-eslint/no-unused-vars function getTypeDefaultValue(typeName: string, fields: string[]) { - let type = root.lookupType(typeName) as protobuf.Type; - for (const field of fields.slice(0, -1)) { - type = type?.fields[field]?.resolvedType as protobuf.Type; - } - return type?.fields[fields[fields.length - 1]]?.defaultValue ?? null; + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type?.fields[field]?.resolvedType as protobuf.Type; + } + return type?.fields[fields[fields.length - 1]]?.defaultValue ?? null; } function generateSampleMessage(instance: T) { - const filledObject = (instance.constructor as typeof protobuf.Message) - .toObject(instance as protobuf.Message, {defaults: true}); - return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, { defaults: true }); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; } function stubSimpleCall(response?: ResponseType, error?: Error) { - return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); } -function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { - return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +function stubSimpleCallWithCallback( + response?: ResponseType, + error?: Error, +) { + return error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); } -function stubPageStreamingCall(responses?: ResponseType[], error?: Error) { - const pagingStub = sinon.stub(); - if (responses) { - for (let i = 0; i < responses.length; ++i) { - pagingStub.onCall(i).callsArgWith(2, null, responses[i]); - } +function stubPageStreamingCall( + responses?: ResponseType[], + error?: Error, +) { + const pagingStub = sinon.stub(); + if (responses) { + for (let i = 0; i < responses.length; ++i) { + pagingStub.onCall(i).callsArgWith(2, null, responses[i]); } - const transformStub = error ? sinon.stub().callsArgWith(2, error) : pagingStub; - const mockStream = new PassThrough({ - objectMode: true, - transform: transformStub, - }); - // trigger as many responses as needed - if (responses) { - for (let i = 0; i < responses.length; ++i) { - setImmediate(() => { mockStream.write({}); }); - } - setImmediate(() => { mockStream.end(); }); - } else { - setImmediate(() => { mockStream.write({}); }); - setImmediate(() => { mockStream.end(); }); + } + const transformStub = error + ? sinon.stub().callsArgWith(2, error) + : pagingStub; + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + // trigger as many responses as needed + if (responses) { + for (let i = 0; i < responses.length; ++i) { + setImmediate(() => { + mockStream.write({}); + }); } - return sinon.stub().returns(mockStream); + setImmediate(() => { + mockStream.end(); + }); + } else { + setImmediate(() => { + mockStream.write({}); + }); + setImmediate(() => { + mockStream.end(); + }); + } + return sinon.stub().returns(mockStream); } -function stubAsyncIterationCall(responses?: ResponseType[], error?: Error) { - let counter = 0; - const asyncIterable = { - [Symbol.asyncIterator]() { - return { - async next() { - if (error) { - return Promise.reject(error); - } - if (counter >= responses!.length) { - return Promise.resolve({done: true, value: undefined}); - } - return Promise.resolve({done: false, value: responses![counter++]}); - } - }; - } - }; - return sinon.stub().returns(asyncIterable); +function stubAsyncIterationCall( + responses?: ResponseType[], + error?: Error, +) { + let counter = 0; + const asyncIterable = { + [Symbol.asyncIterator]() { + return { + async next() { + if (error) { + return Promise.reject(error); + } + if (counter >= responses!.length) { + return Promise.resolve({ done: true, value: undefined }); + } + return Promise.resolve({ done: false, value: responses![counter++] }); + }, + }; + }, + }; + return sinon.stub().returns(asyncIterable); } describe('v3.GroupServiceClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new groupserviceModule.v3.GroupServiceClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'monitoring.googleapis.com'); - }); - - it('has universeDomain', () => { - const client = new groupserviceModule.v3.GroupServiceClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); - - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - it('throws DeprecationWarning if static servicePath is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const servicePath = groupserviceModule.v3.GroupServiceClient.servicePath; - assert.strictEqual(servicePath, 'monitoring.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = groupserviceModule.v3.GroupServiceClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'monitoring.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new groupserviceModule.v3.GroupServiceClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'monitoring.example.com'); - }); - - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new groupserviceModule.v3.GroupServiceClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'monitoring.example.com'); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new groupserviceModule.v3.GroupServiceClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'monitoring.googleapis.com'); + }); - if (typeof process === 'object' && 'env' in process) { - describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { - it('sets apiEndpoint from environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new groupserviceModule.v3.GroupServiceClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'monitoring.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - - it('value configured in code has priority over environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new groupserviceModule.v3.GroupServiceClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'monitoring.configured.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { new groupserviceModule.v3.GroupServiceClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); + it('has universeDomain', () => { + const client = new groupserviceModule.v3.GroupServiceClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - it('has port', () => { - const port = groupserviceModule.v3.GroupServiceClient.port; - assert(port); - assert(typeof port === 'number'); - }); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = + groupserviceModule.v3.GroupServiceClient.servicePath; + assert.strictEqual(servicePath, 'monitoring.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + groupserviceModule.v3.GroupServiceClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'monitoring.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = new groupserviceModule.v3.GroupServiceClient({ + universeDomain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'monitoring.example.com'); + }); - it('should create a client with no option', () => { - const client = new groupserviceModule.v3.GroupServiceClient(); - assert(client); - }); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = new groupserviceModule.v3.GroupServiceClient({ + universe_domain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'monitoring.example.com'); + }); - it('should create a client with gRPC fallback', () => { - const client = new groupserviceModule.v3.GroupServiceClient({ - fallback: true, - }); - assert(client); + if (typeof process === 'object' && 'env' in process) { + describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { + it('sets apiEndpoint from environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new groupserviceModule.v3.GroupServiceClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'monitoring.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } + }); + + it('value configured in code has priority over environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new groupserviceModule.v3.GroupServiceClient({ + universeDomain: 'configured.example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'monitoring.configured.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } + }); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new groupserviceModule.v3.GroupServiceClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); + }); - it('has initialize method and supports deferred initialization', async () => { - const client = new groupserviceModule.v3.GroupServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.groupServiceStub, undefined); - await client.initialize(); - assert(client.groupServiceStub); - }); + it('has port', () => { + const port = groupserviceModule.v3.GroupServiceClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('has close method for the initialized client', done => { - const client = new groupserviceModule.v3.GroupServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.groupServiceStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('should create a client with no option', () => { + const client = new groupserviceModule.v3.GroupServiceClient(); + assert(client); + }); - it('has close method for the non-initialized client', done => { - const client = new groupserviceModule.v3.GroupServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.groupServiceStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('should create a client with gRPC fallback', () => { + const client = new groupserviceModule.v3.GroupServiceClient({ + fallback: true, + }); + assert(client); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new groupserviceModule.v3.GroupServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); - }); + it('has initialize method and supports deferred initialization', async () => { + const client = new groupserviceModule.v3.GroupServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.groupServiceStub, undefined); + await client.initialize(); + assert(client.groupServiceStub); + }); - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new groupserviceModule.v3.GroupServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId((err?: Error|null, projectId?: string|null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } - }); - }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); + it('has close method for the initialized client', (done) => { + const client = new groupserviceModule.v3.GroupServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.groupServiceStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); }); - describe('getGroup', () => { - it('invokes getGroup without error', async () => { - const client = new groupserviceModule.v3.GroupServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.GetGroupRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.GetGroupRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.monitoring.v3.Group() - ); - client.innerApiCalls.getGroup = stubSimpleCall(expectedResponse); - const [response] = await client.getGroup(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getGroup as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getGroup as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('has close method for the non-initialized client', (done) => { + const client = new groupserviceModule.v3.GroupServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.groupServiceStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes getGroup without error using callback', async () => { - const client = new groupserviceModule.v3.GroupServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.GetGroupRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.GetGroupRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.monitoring.v3.Group() - ); - client.innerApiCalls.getGroup = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getGroup( - request, - (err?: Error|null, result?: protos.google.monitoring.v3.IGroup|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getGroup as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getGroup as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new groupserviceModule.v3.GroupServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + }); - it('invokes getGroup with error', async () => { - const client = new groupserviceModule.v3.GroupServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.GetGroupRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.GetGroupRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getGroup = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getGroup(request), expectedError); - const actualRequest = (client.innerApiCalls.getGroup as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getGroup as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new groupserviceModule.v3.GroupServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } + }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + }); + + describe('getGroup', () => { + it('invokes getGroup without error', async () => { + const client = new groupserviceModule.v3.GroupServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.GetGroupRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.GetGroupRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.monitoring.v3.Group(), + ); + client.innerApiCalls.getGroup = stubSimpleCall(expectedResponse); + const [response] = await client.getGroup(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getGroup as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getGroup as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getGroup with closed client', async () => { - const client = new groupserviceModule.v3.GroupServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.GetGroupRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.GetGroupRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getGroup(request), expectedError); - }); + it('invokes getGroup without error using callback', async () => { + const client = new groupserviceModule.v3.GroupServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.GetGroupRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.GetGroupRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.monitoring.v3.Group(), + ); + client.innerApiCalls.getGroup = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getGroup( + request, + ( + err?: Error | null, + result?: protos.google.monitoring.v3.IGroup | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getGroup as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getGroup as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('createGroup', () => { - it('invokes createGroup without error', async () => { - const client = new groupserviceModule.v3.GroupServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.CreateGroupRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.CreateGroupRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.monitoring.v3.Group() - ); - client.innerApiCalls.createGroup = stubSimpleCall(expectedResponse); - const [response] = await client.createGroup(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createGroup as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createGroup as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getGroup with error', async () => { + const client = new groupserviceModule.v3.GroupServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.GetGroupRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.GetGroupRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getGroup = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.getGroup(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getGroup as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getGroup as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createGroup without error using callback', async () => { - const client = new groupserviceModule.v3.GroupServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.CreateGroupRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.CreateGroupRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.monitoring.v3.Group() - ); - client.innerApiCalls.createGroup = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createGroup( - request, - (err?: Error|null, result?: protos.google.monitoring.v3.IGroup|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createGroup as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createGroup as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getGroup with closed client', async () => { + const client = new groupserviceModule.v3.GroupServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.GetGroupRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.GetGroupRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getGroup(request), expectedError); + }); + }); + + describe('createGroup', () => { + it('invokes createGroup without error', async () => { + const client = new groupserviceModule.v3.GroupServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.CreateGroupRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.CreateGroupRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.monitoring.v3.Group(), + ); + client.innerApiCalls.createGroup = stubSimpleCall(expectedResponse); + const [response] = await client.createGroup(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createGroup as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createGroup as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createGroup with error', async () => { - const client = new groupserviceModule.v3.GroupServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.CreateGroupRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.CreateGroupRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createGroup = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createGroup(request), expectedError); - const actualRequest = (client.innerApiCalls.createGroup as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createGroup as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createGroup without error using callback', async () => { + const client = new groupserviceModule.v3.GroupServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.CreateGroupRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.CreateGroupRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.monitoring.v3.Group(), + ); + client.innerApiCalls.createGroup = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createGroup( + request, + ( + err?: Error | null, + result?: protos.google.monitoring.v3.IGroup | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createGroup as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createGroup as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createGroup with closed client', async () => { - const client = new groupserviceModule.v3.GroupServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.CreateGroupRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.CreateGroupRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createGroup(request), expectedError); - }); + it('invokes createGroup with error', async () => { + const client = new groupserviceModule.v3.GroupServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.CreateGroupRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.CreateGroupRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createGroup = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.createGroup(request), expectedError); + const actualRequest = ( + client.innerApiCalls.createGroup as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createGroup as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('updateGroup', () => { - it('invokes updateGroup without error', async () => { - const client = new groupserviceModule.v3.GroupServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.UpdateGroupRequest() - ); - request.group ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.UpdateGroupRequest', ['group', 'name']); - request.group.name = defaultValue1; - const expectedHeaderRequestParams = `group.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.monitoring.v3.Group() - ); - client.innerApiCalls.updateGroup = stubSimpleCall(expectedResponse); - const [response] = await client.updateGroup(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateGroup as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateGroup as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createGroup with closed client', async () => { + const client = new groupserviceModule.v3.GroupServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.CreateGroupRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.CreateGroupRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.createGroup(request), expectedError); + }); + }); + + describe('updateGroup', () => { + it('invokes updateGroup without error', async () => { + const client = new groupserviceModule.v3.GroupServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.UpdateGroupRequest(), + ); + request.group ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.UpdateGroupRequest', + ['group', 'name'], + ); + request.group.name = defaultValue1; + const expectedHeaderRequestParams = `group.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.monitoring.v3.Group(), + ); + client.innerApiCalls.updateGroup = stubSimpleCall(expectedResponse); + const [response] = await client.updateGroup(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateGroup as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateGroup as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateGroup without error using callback', async () => { - const client = new groupserviceModule.v3.GroupServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.UpdateGroupRequest() - ); - request.group ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.UpdateGroupRequest', ['group', 'name']); - request.group.name = defaultValue1; - const expectedHeaderRequestParams = `group.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.monitoring.v3.Group() - ); - client.innerApiCalls.updateGroup = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateGroup( - request, - (err?: Error|null, result?: protos.google.monitoring.v3.IGroup|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateGroup as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateGroup as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateGroup without error using callback', async () => { + const client = new groupserviceModule.v3.GroupServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.UpdateGroupRequest(), + ); + request.group ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.UpdateGroupRequest', + ['group', 'name'], + ); + request.group.name = defaultValue1; + const expectedHeaderRequestParams = `group.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.monitoring.v3.Group(), + ); + client.innerApiCalls.updateGroup = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateGroup( + request, + ( + err?: Error | null, + result?: protos.google.monitoring.v3.IGroup | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateGroup as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateGroup as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateGroup with error', async () => { - const client = new groupserviceModule.v3.GroupServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.UpdateGroupRequest() - ); - request.group ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.UpdateGroupRequest', ['group', 'name']); - request.group.name = defaultValue1; - const expectedHeaderRequestParams = `group.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateGroup = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateGroup(request), expectedError); - const actualRequest = (client.innerApiCalls.updateGroup as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateGroup as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateGroup with error', async () => { + const client = new groupserviceModule.v3.GroupServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.UpdateGroupRequest(), + ); + request.group ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.UpdateGroupRequest', + ['group', 'name'], + ); + request.group.name = defaultValue1; + const expectedHeaderRequestParams = `group.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateGroup = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.updateGroup(request), expectedError); + const actualRequest = ( + client.innerApiCalls.updateGroup as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateGroup as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateGroup with closed client', async () => { - const client = new groupserviceModule.v3.GroupServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.UpdateGroupRequest() - ); - request.group ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.UpdateGroupRequest', ['group', 'name']); - request.group.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateGroup(request), expectedError); - }); + it('invokes updateGroup with closed client', async () => { + const client = new groupserviceModule.v3.GroupServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.UpdateGroupRequest(), + ); + request.group ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.UpdateGroupRequest', + ['group', 'name'], + ); + request.group.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.updateGroup(request), expectedError); + }); + }); + + describe('deleteGroup', () => { + it('invokes deleteGroup without error', async () => { + const client = new groupserviceModule.v3.GroupServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.DeleteGroupRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.DeleteGroupRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteGroup = stubSimpleCall(expectedResponse); + const [response] = await client.deleteGroup(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteGroup as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteGroup as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('deleteGroup', () => { - it('invokes deleteGroup without error', async () => { - const client = new groupserviceModule.v3.GroupServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.DeleteGroupRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.DeleteGroupRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteGroup = stubSimpleCall(expectedResponse); - const [response] = await client.deleteGroup(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteGroup as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteGroup as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteGroup without error using callback', async () => { + const client = new groupserviceModule.v3.GroupServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.DeleteGroupRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.DeleteGroupRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteGroup = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteGroup( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteGroup as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteGroup as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteGroup without error using callback', async () => { - const client = new groupserviceModule.v3.GroupServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.DeleteGroupRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.DeleteGroupRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteGroup = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteGroup( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteGroup as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteGroup as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteGroup with error', async () => { + const client = new groupserviceModule.v3.GroupServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.DeleteGroupRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.DeleteGroupRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteGroup = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.deleteGroup(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteGroup as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteGroup as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteGroup with error', async () => { - const client = new groupserviceModule.v3.GroupServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.DeleteGroupRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.DeleteGroupRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteGroup = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteGroup(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteGroup as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteGroup as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteGroup with closed client', async () => { + const client = new groupserviceModule.v3.GroupServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.DeleteGroupRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.DeleteGroupRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.deleteGroup(request), expectedError); + }); + }); + + describe('listGroups', () => { + it('invokes listGroups without error', async () => { + const client = new groupserviceModule.v3.GroupServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListGroupsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListGroupsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.monitoring.v3.Group()), + generateSampleMessage(new protos.google.monitoring.v3.Group()), + generateSampleMessage(new protos.google.monitoring.v3.Group()), + ]; + client.innerApiCalls.listGroups = stubSimpleCall(expectedResponse); + const [response] = await client.listGroups(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listGroups as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listGroups as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteGroup with closed client', async () => { - const client = new groupserviceModule.v3.GroupServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.DeleteGroupRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.DeleteGroupRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteGroup(request), expectedError); - }); + it('invokes listGroups without error using callback', async () => { + const client = new groupserviceModule.v3.GroupServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListGroupsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListGroupsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.monitoring.v3.Group()), + generateSampleMessage(new protos.google.monitoring.v3.Group()), + generateSampleMessage(new protos.google.monitoring.v3.Group()), + ]; + client.innerApiCalls.listGroups = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listGroups( + request, + ( + err?: Error | null, + result?: protos.google.monitoring.v3.IGroup[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listGroups as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listGroups as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('listGroups', () => { - it('invokes listGroups without error', async () => { - const client = new groupserviceModule.v3.GroupServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListGroupsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListGroupsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.monitoring.v3.Group()), - generateSampleMessage(new protos.google.monitoring.v3.Group()), - generateSampleMessage(new protos.google.monitoring.v3.Group()), - ]; - client.innerApiCalls.listGroups = stubSimpleCall(expectedResponse); - const [response] = await client.listGroups(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listGroups as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listGroups as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listGroups with error', async () => { + const client = new groupserviceModule.v3.GroupServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListGroupsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListGroupsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listGroups = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listGroups(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listGroups as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listGroups as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listGroups without error using callback', async () => { - const client = new groupserviceModule.v3.GroupServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListGroupsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListGroupsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.monitoring.v3.Group()), - generateSampleMessage(new protos.google.monitoring.v3.Group()), - generateSampleMessage(new protos.google.monitoring.v3.Group()), - ]; - client.innerApiCalls.listGroups = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listGroups( - request, - (err?: Error|null, result?: protos.google.monitoring.v3.IGroup[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listGroups as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listGroups as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listGroupsStream without error', async () => { + const client = new groupserviceModule.v3.GroupServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListGroupsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListGroupsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.monitoring.v3.Group()), + generateSampleMessage(new protos.google.monitoring.v3.Group()), + generateSampleMessage(new protos.google.monitoring.v3.Group()), + ]; + client.descriptors.page.listGroups.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listGroupsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.monitoring.v3.Group[] = []; + stream.on('data', (response: protos.google.monitoring.v3.Group) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listGroups.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listGroups, request), + ); + assert( + (client.descriptors.page.listGroups.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('invokes listGroups with error', async () => { - const client = new groupserviceModule.v3.GroupServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListGroupsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListGroupsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listGroups = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listGroups(request), expectedError); - const actualRequest = (client.innerApiCalls.listGroups as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listGroups as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listGroupsStream with error', async () => { + const client = new groupserviceModule.v3.GroupServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListGroupsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListGroupsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listGroups.createStream = stubPageStreamingCall( + undefined, + expectedError, + ); + const stream = client.listGroupsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.monitoring.v3.Group[] = []; + stream.on('data', (response: protos.google.monitoring.v3.Group) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listGroups.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listGroups, request), + ); + assert( + (client.descriptors.page.listGroups.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('invokes listGroupsStream without error', async () => { - const client = new groupserviceModule.v3.GroupServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListGroupsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListGroupsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.monitoring.v3.Group()), - generateSampleMessage(new protos.google.monitoring.v3.Group()), - generateSampleMessage(new protos.google.monitoring.v3.Group()), - ]; - client.descriptors.page.listGroups.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listGroupsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.monitoring.v3.Group[] = []; - stream.on('data', (response: protos.google.monitoring.v3.Group) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.listGroups.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listGroups, request)); - assert( - (client.descriptors.page.listGroups.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listGroups without error', async () => { + const client = new groupserviceModule.v3.GroupServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListGroupsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListGroupsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.monitoring.v3.Group()), + generateSampleMessage(new protos.google.monitoring.v3.Group()), + generateSampleMessage(new protos.google.monitoring.v3.Group()), + ]; + client.descriptors.page.listGroups.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.monitoring.v3.IGroup[] = []; + const iterable = client.listGroupsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + (client.descriptors.page.listGroups.asyncIterate as SinonStub).getCall( + 0, + ).args[1], + request, + ); + assert( + (client.descriptors.page.listGroups.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('invokes listGroupsStream with error', async () => { - const client = new groupserviceModule.v3.GroupServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListGroupsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListGroupsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listGroups.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listGroupsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.monitoring.v3.Group[] = []; - stream.on('data', (response: protos.google.monitoring.v3.Group) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listGroups.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listGroups, request)); - assert( - (client.descriptors.page.listGroups.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listGroups with error', async () => { + const client = new groupserviceModule.v3.GroupServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListGroupsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListGroupsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listGroups.asyncIterate = stubAsyncIterationCall( + undefined, + expectedError, + ); + const iterable = client.listGroupsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.monitoring.v3.IGroup[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + (client.descriptors.page.listGroups.asyncIterate as SinonStub).getCall( + 0, + ).args[1], + request, + ); + assert( + (client.descriptors.page.listGroups.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + }); + + describe('listGroupMembers', () => { + it('invokes listGroupMembers without error', async () => { + const client = new groupserviceModule.v3.GroupServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListGroupMembersRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListGroupMembersRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.api.MonitoredResource()), + generateSampleMessage(new protos.google.api.MonitoredResource()), + generateSampleMessage(new protos.google.api.MonitoredResource()), + ]; + client.innerApiCalls.listGroupMembers = stubSimpleCall(expectedResponse); + const [response] = await client.listGroupMembers(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listGroupMembers as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listGroupMembers as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('uses async iteration with listGroups without error', async () => { - const client = new groupserviceModule.v3.GroupServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListGroupsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListGroupsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.monitoring.v3.Group()), - generateSampleMessage(new protos.google.monitoring.v3.Group()), - generateSampleMessage(new protos.google.monitoring.v3.Group()), - ]; - client.descriptors.page.listGroups.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.monitoring.v3.IGroup[] = []; - const iterable = client.listGroupsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); + it('invokes listGroupMembers without error using callback', async () => { + const client = new groupserviceModule.v3.GroupServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListGroupMembersRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListGroupMembersRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.api.MonitoredResource()), + generateSampleMessage(new protos.google.api.MonitoredResource()), + generateSampleMessage(new protos.google.api.MonitoredResource()), + ]; + client.innerApiCalls.listGroupMembers = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listGroupMembers( + request, + ( + err?: Error | null, + result?: protos.google.api.IMonitoredResource[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listGroups.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listGroups.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); - - it('uses async iteration with listGroups with error', async () => { - const client = new groupserviceModule.v3.GroupServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListGroupsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListGroupsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listGroups.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listGroupsAsync(request); - await assert.rejects(async () => { - const responses: protos.google.monitoring.v3.IGroup[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listGroups.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listGroups.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listGroupMembers as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listGroupMembers as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('listGroupMembers', () => { - it('invokes listGroupMembers without error', async () => { - const client = new groupserviceModule.v3.GroupServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListGroupMembersRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListGroupMembersRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.api.MonitoredResource()), - generateSampleMessage(new protos.google.api.MonitoredResource()), - generateSampleMessage(new protos.google.api.MonitoredResource()), - ]; - client.innerApiCalls.listGroupMembers = stubSimpleCall(expectedResponse); - const [response] = await client.listGroupMembers(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listGroupMembers as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listGroupMembers as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listGroupMembers without error using callback', async () => { - const client = new groupserviceModule.v3.GroupServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListGroupMembersRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListGroupMembersRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.api.MonitoredResource()), - generateSampleMessage(new protos.google.api.MonitoredResource()), - generateSampleMessage(new protos.google.api.MonitoredResource()), - ]; - client.innerApiCalls.listGroupMembers = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listGroupMembers( - request, - (err?: Error|null, result?: protos.google.api.IMonitoredResource[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listGroupMembers as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listGroupMembers as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listGroupMembers with error', async () => { - const client = new groupserviceModule.v3.GroupServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListGroupMembersRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListGroupMembersRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listGroupMembers = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listGroupMembers(request), expectedError); - const actualRequest = (client.innerApiCalls.listGroupMembers as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listGroupMembers as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listGroupMembersStream without error', async () => { - const client = new groupserviceModule.v3.GroupServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListGroupMembersRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListGroupMembersRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.api.MonitoredResource()), - generateSampleMessage(new protos.google.api.MonitoredResource()), - generateSampleMessage(new protos.google.api.MonitoredResource()), - ]; - client.descriptors.page.listGroupMembers.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listGroupMembersStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.api.MonitoredResource[] = []; - stream.on('data', (response: protos.google.api.MonitoredResource) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.listGroupMembers.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listGroupMembers, request)); - assert( - (client.descriptors.page.listGroupMembers.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listGroupMembers with error', async () => { + const client = new groupserviceModule.v3.GroupServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListGroupMembersRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListGroupMembersRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listGroupMembers = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listGroupMembers(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listGroupMembers as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listGroupMembers as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listGroupMembersStream with error', async () => { - const client = new groupserviceModule.v3.GroupServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListGroupMembersRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListGroupMembersRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listGroupMembers.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listGroupMembersStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.api.MonitoredResource[] = []; - stream.on('data', (response: protos.google.api.MonitoredResource) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listGroupMembers.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listGroupMembers, request)); - assert( - (client.descriptors.page.listGroupMembers.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listGroupMembersStream without error', async () => { + const client = new groupserviceModule.v3.GroupServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListGroupMembersRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListGroupMembersRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.api.MonitoredResource()), + generateSampleMessage(new protos.google.api.MonitoredResource()), + generateSampleMessage(new protos.google.api.MonitoredResource()), + ]; + client.descriptors.page.listGroupMembers.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listGroupMembersStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.api.MonitoredResource[] = []; + stream.on('data', (response: protos.google.api.MonitoredResource) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listGroupMembers.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listGroupMembers, request), + ); + assert( + (client.descriptors.page.listGroupMembers.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('uses async iteration with listGroupMembers without error', async () => { - const client = new groupserviceModule.v3.GroupServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListGroupMembersRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListGroupMembersRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.api.MonitoredResource()), - generateSampleMessage(new protos.google.api.MonitoredResource()), - generateSampleMessage(new protos.google.api.MonitoredResource()), - ]; - client.descriptors.page.listGroupMembers.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.api.IMonitoredResource[] = []; - const iterable = client.listGroupMembersAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listGroupMembers.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listGroupMembers.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listGroupMembersStream with error', async () => { + const client = new groupserviceModule.v3.GroupServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListGroupMembersRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListGroupMembersRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listGroupMembers.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listGroupMembersStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.api.MonitoredResource[] = []; + stream.on('data', (response: protos.google.api.MonitoredResource) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listGroupMembers.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listGroupMembers, request), + ); + assert( + (client.descriptors.page.listGroupMembers.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('uses async iteration with listGroupMembers with error', async () => { - const client = new groupserviceModule.v3.GroupServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListGroupMembersRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListGroupMembersRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listGroupMembers.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listGroupMembersAsync(request); - await assert.rejects(async () => { - const responses: protos.google.api.IMonitoredResource[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listGroupMembers.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listGroupMembers.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listGroupMembers without error', async () => { + const client = new groupserviceModule.v3.GroupServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListGroupMembersRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListGroupMembersRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.api.MonitoredResource()), + generateSampleMessage(new protos.google.api.MonitoredResource()), + generateSampleMessage(new protos.google.api.MonitoredResource()), + ]; + client.descriptors.page.listGroupMembers.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.api.IMonitoredResource[] = []; + const iterable = client.listGroupMembersAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listGroupMembers.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listGroupMembers.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); }); - describe('Path templates', () => { - - describe('folderAlertPolicy', () => { - const fakePath = "/rendered/path/folderAlertPolicy"; - const expectedParameters = { - folder: "folderValue", - alert_policy: "alertPolicyValue", - }; - const client = new groupserviceModule.v3.GroupServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.folderAlertPolicyPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderAlertPolicyPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderAlertPolicyPath', () => { - const result = client.folderAlertPolicyPath("folderValue", "alertPolicyValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderAlertPolicyPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderAlertPolicyName', () => { - const result = client.matchFolderFromFolderAlertPolicyName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderAlertPolicyPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchAlertPolicyFromFolderAlertPolicyName', () => { - const result = client.matchAlertPolicyFromFolderAlertPolicyName(fakePath); - assert.strictEqual(result, "alertPolicyValue"); - assert((client.pathTemplates.folderAlertPolicyPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('uses async iteration with listGroupMembers with error', async () => { + const client = new groupserviceModule.v3.GroupServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListGroupMembersRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListGroupMembersRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listGroupMembers.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listGroupMembersAsync(request); + await assert.rejects(async () => { + const responses: protos.google.api.IMonitoredResource[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listGroupMembers.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listGroupMembers.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + }); + + describe('Path templates', () => { + describe('folderAlertPolicy', () => { + const fakePath = '/rendered/path/folderAlertPolicy'; + const expectedParameters = { + folder: 'folderValue', + alert_policy: 'alertPolicyValue', + }; + const client = new groupserviceModule.v3.GroupServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.folderAlertPolicyPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderAlertPolicyPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderAlertPolicyPath', () => { + const result = client.folderAlertPolicyPath( + 'folderValue', + 'alertPolicyValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.folderAlertPolicyPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderAlertPolicyName', () => { + const result = client.matchFolderFromFolderAlertPolicyName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + ( + client.pathTemplates.folderAlertPolicyPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchAlertPolicyFromFolderAlertPolicyName', () => { + const result = + client.matchAlertPolicyFromFolderAlertPolicyName(fakePath); + assert.strictEqual(result, 'alertPolicyValue'); + assert( + ( + client.pathTemplates.folderAlertPolicyPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('folderAlertPolicyCondition', () => { - const fakePath = "/rendered/path/folderAlertPolicyCondition"; - const expectedParameters = { - folder: "folderValue", - alert_policy: "alertPolicyValue", - condition: "conditionValue", - }; - const client = new groupserviceModule.v3.GroupServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.folderAlertPolicyConditionPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderAlertPolicyConditionPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderAlertPolicyConditionPath', () => { - const result = client.folderAlertPolicyConditionPath("folderValue", "alertPolicyValue", "conditionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderAlertPolicyConditionPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderAlertPolicyConditionName', () => { - const result = client.matchFolderFromFolderAlertPolicyConditionName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderAlertPolicyConditionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchAlertPolicyFromFolderAlertPolicyConditionName', () => { - const result = client.matchAlertPolicyFromFolderAlertPolicyConditionName(fakePath); - assert.strictEqual(result, "alertPolicyValue"); - assert((client.pathTemplates.folderAlertPolicyConditionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchConditionFromFolderAlertPolicyConditionName', () => { - const result = client.matchConditionFromFolderAlertPolicyConditionName(fakePath); - assert.strictEqual(result, "conditionValue"); - assert((client.pathTemplates.folderAlertPolicyConditionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('folderAlertPolicyCondition', () => { + const fakePath = '/rendered/path/folderAlertPolicyCondition'; + const expectedParameters = { + folder: 'folderValue', + alert_policy: 'alertPolicyValue', + condition: 'conditionValue', + }; + const client = new groupserviceModule.v3.GroupServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.folderAlertPolicyConditionPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderAlertPolicyConditionPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderAlertPolicyConditionPath', () => { + const result = client.folderAlertPolicyConditionPath( + 'folderValue', + 'alertPolicyValue', + 'conditionValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.folderAlertPolicyConditionPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderAlertPolicyConditionName', () => { + const result = + client.matchFolderFromFolderAlertPolicyConditionName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + ( + client.pathTemplates.folderAlertPolicyConditionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchAlertPolicyFromFolderAlertPolicyConditionName', () => { + const result = + client.matchAlertPolicyFromFolderAlertPolicyConditionName(fakePath); + assert.strictEqual(result, 'alertPolicyValue'); + assert( + ( + client.pathTemplates.folderAlertPolicyConditionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchConditionFromFolderAlertPolicyConditionName', () => { + const result = + client.matchConditionFromFolderAlertPolicyConditionName(fakePath); + assert.strictEqual(result, 'conditionValue'); + assert( + ( + client.pathTemplates.folderAlertPolicyConditionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('folderChannelDescriptor', () => { - const fakePath = "/rendered/path/folderChannelDescriptor"; - const expectedParameters = { - folder: "folderValue", - channel_descriptor: "channelDescriptorValue", - }; - const client = new groupserviceModule.v3.GroupServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.folderChannelDescriptorPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderChannelDescriptorPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderChannelDescriptorPath', () => { - const result = client.folderChannelDescriptorPath("folderValue", "channelDescriptorValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderChannelDescriptorPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderChannelDescriptorName', () => { - const result = client.matchFolderFromFolderChannelDescriptorName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderChannelDescriptorPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchChannelDescriptorFromFolderChannelDescriptorName', () => { - const result = client.matchChannelDescriptorFromFolderChannelDescriptorName(fakePath); - assert.strictEqual(result, "channelDescriptorValue"); - assert((client.pathTemplates.folderChannelDescriptorPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('folderChannelDescriptor', () => { + const fakePath = '/rendered/path/folderChannelDescriptor'; + const expectedParameters = { + folder: 'folderValue', + channel_descriptor: 'channelDescriptorValue', + }; + const client = new groupserviceModule.v3.GroupServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.folderChannelDescriptorPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderChannelDescriptorPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderChannelDescriptorPath', () => { + const result = client.folderChannelDescriptorPath( + 'folderValue', + 'channelDescriptorValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.folderChannelDescriptorPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderChannelDescriptorName', () => { + const result = + client.matchFolderFromFolderChannelDescriptorName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + ( + client.pathTemplates.folderChannelDescriptorPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchChannelDescriptorFromFolderChannelDescriptorName', () => { + const result = + client.matchChannelDescriptorFromFolderChannelDescriptorName( + fakePath, + ); + assert.strictEqual(result, 'channelDescriptorValue'); + assert( + ( + client.pathTemplates.folderChannelDescriptorPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('folderGroup', () => { - const fakePath = "/rendered/path/folderGroup"; - const expectedParameters = { - folder: "folderValue", - group: "groupValue", - }; - const client = new groupserviceModule.v3.GroupServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.folderGroupPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderGroupPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderGroupPath', () => { - const result = client.folderGroupPath("folderValue", "groupValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderGroupPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderGroupName', () => { - const result = client.matchFolderFromFolderGroupName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderGroupPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchGroupFromFolderGroupName', () => { - const result = client.matchGroupFromFolderGroupName(fakePath); - assert.strictEqual(result, "groupValue"); - assert((client.pathTemplates.folderGroupPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('folderGroup', () => { + const fakePath = '/rendered/path/folderGroup'; + const expectedParameters = { + folder: 'folderValue', + group: 'groupValue', + }; + const client = new groupserviceModule.v3.GroupServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.folderGroupPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderGroupPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderGroupPath', () => { + const result = client.folderGroupPath('folderValue', 'groupValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.folderGroupPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderGroupName', () => { + const result = client.matchFolderFromFolderGroupName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + (client.pathTemplates.folderGroupPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchGroupFromFolderGroupName', () => { + const result = client.matchGroupFromFolderGroupName(fakePath); + assert.strictEqual(result, 'groupValue'); + assert( + (client.pathTemplates.folderGroupPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('folderNotificationChannel', () => { - const fakePath = "/rendered/path/folderNotificationChannel"; - const expectedParameters = { - folder: "folderValue", - notification_channel: "notificationChannelValue", - }; - const client = new groupserviceModule.v3.GroupServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.folderNotificationChannelPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderNotificationChannelPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderNotificationChannelPath', () => { - const result = client.folderNotificationChannelPath("folderValue", "notificationChannelValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderNotificationChannelPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderNotificationChannelName', () => { - const result = client.matchFolderFromFolderNotificationChannelName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderNotificationChannelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchNotificationChannelFromFolderNotificationChannelName', () => { - const result = client.matchNotificationChannelFromFolderNotificationChannelName(fakePath); - assert.strictEqual(result, "notificationChannelValue"); - assert((client.pathTemplates.folderNotificationChannelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('folderNotificationChannel', () => { + const fakePath = '/rendered/path/folderNotificationChannel'; + const expectedParameters = { + folder: 'folderValue', + notification_channel: 'notificationChannelValue', + }; + const client = new groupserviceModule.v3.GroupServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.folderNotificationChannelPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderNotificationChannelPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderNotificationChannelPath', () => { + const result = client.folderNotificationChannelPath( + 'folderValue', + 'notificationChannelValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.folderNotificationChannelPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderNotificationChannelName', () => { + const result = + client.matchFolderFromFolderNotificationChannelName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + ( + client.pathTemplates.folderNotificationChannelPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchNotificationChannelFromFolderNotificationChannelName', () => { + const result = + client.matchNotificationChannelFromFolderNotificationChannelName( + fakePath, + ); + assert.strictEqual(result, 'notificationChannelValue'); + assert( + ( + client.pathTemplates.folderNotificationChannelPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('folderService', () => { - const fakePath = "/rendered/path/folderService"; - const expectedParameters = { - folder: "folderValue", - service: "serviceValue", - }; - const client = new groupserviceModule.v3.GroupServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.folderServicePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderServicePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderServicePath', () => { - const result = client.folderServicePath("folderValue", "serviceValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderServicePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderServiceName', () => { - const result = client.matchFolderFromFolderServiceName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderServicePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServiceFromFolderServiceName', () => { - const result = client.matchServiceFromFolderServiceName(fakePath); - assert.strictEqual(result, "serviceValue"); - assert((client.pathTemplates.folderServicePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('folderService', () => { + const fakePath = '/rendered/path/folderService'; + const expectedParameters = { + folder: 'folderValue', + service: 'serviceValue', + }; + const client = new groupserviceModule.v3.GroupServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.folderServicePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderServicePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderServicePath', () => { + const result = client.folderServicePath('folderValue', 'serviceValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.folderServicePathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderServiceName', () => { + const result = client.matchFolderFromFolderServiceName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + (client.pathTemplates.folderServicePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServiceFromFolderServiceName', () => { + const result = client.matchServiceFromFolderServiceName(fakePath); + assert.strictEqual(result, 'serviceValue'); + assert( + (client.pathTemplates.folderServicePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('folderServiceServiceLevelObjective', () => { - const fakePath = "/rendered/path/folderServiceServiceLevelObjective"; - const expectedParameters = { - folder: "folderValue", - service: "serviceValue", - service_level_objective: "serviceLevelObjectiveValue", - }; - const client = new groupserviceModule.v3.GroupServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderServiceServiceLevelObjectivePath', () => { - const result = client.folderServiceServiceLevelObjectivePath("folderValue", "serviceValue", "serviceLevelObjectiveValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderServiceServiceLevelObjectiveName', () => { - const result = client.matchFolderFromFolderServiceServiceLevelObjectiveName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServiceFromFolderServiceServiceLevelObjectiveName', () => { - const result = client.matchServiceFromFolderServiceServiceLevelObjectiveName(fakePath); - assert.strictEqual(result, "serviceValue"); - assert((client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServiceLevelObjectiveFromFolderServiceServiceLevelObjectiveName', () => { - const result = client.matchServiceLevelObjectiveFromFolderServiceServiceLevelObjectiveName(fakePath); - assert.strictEqual(result, "serviceLevelObjectiveValue"); - assert((client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('folderServiceServiceLevelObjective', () => { + const fakePath = '/rendered/path/folderServiceServiceLevelObjective'; + const expectedParameters = { + folder: 'folderValue', + service: 'serviceValue', + service_level_objective: 'serviceLevelObjectiveValue', + }; + const client = new groupserviceModule.v3.GroupServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('folderServiceServiceLevelObjectivePath', () => { + const result = client.folderServiceServiceLevelObjectivePath( + 'folderValue', + 'serviceValue', + 'serviceLevelObjectiveValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderServiceServiceLevelObjectiveName', () => { + const result = + client.matchFolderFromFolderServiceServiceLevelObjectiveName( + fakePath, + ); + assert.strictEqual(result, 'folderValue'); + assert( + ( + client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServiceFromFolderServiceServiceLevelObjectiveName', () => { + const result = + client.matchServiceFromFolderServiceServiceLevelObjectiveName( + fakePath, + ); + assert.strictEqual(result, 'serviceValue'); + assert( + ( + client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServiceLevelObjectiveFromFolderServiceServiceLevelObjectiveName', () => { + const result = + client.matchServiceLevelObjectiveFromFolderServiceServiceLevelObjectiveName( + fakePath, + ); + assert.strictEqual(result, 'serviceLevelObjectiveValue'); + assert( + ( + client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('folderUptimeCheckConfig', () => { - const fakePath = "/rendered/path/folderUptimeCheckConfig"; - const expectedParameters = { - folder: "folderValue", - uptime_check_config: "uptimeCheckConfigValue", - }; - const client = new groupserviceModule.v3.GroupServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.folderUptimeCheckConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderUptimeCheckConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderUptimeCheckConfigPath', () => { - const result = client.folderUptimeCheckConfigPath("folderValue", "uptimeCheckConfigValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderUptimeCheckConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderUptimeCheckConfigName', () => { - const result = client.matchFolderFromFolderUptimeCheckConfigName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderUptimeCheckConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchUptimeCheckConfigFromFolderUptimeCheckConfigName', () => { - const result = client.matchUptimeCheckConfigFromFolderUptimeCheckConfigName(fakePath); - assert.strictEqual(result, "uptimeCheckConfigValue"); - assert((client.pathTemplates.folderUptimeCheckConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('folderUptimeCheckConfig', () => { + const fakePath = '/rendered/path/folderUptimeCheckConfig'; + const expectedParameters = { + folder: 'folderValue', + uptime_check_config: 'uptimeCheckConfigValue', + }; + const client = new groupserviceModule.v3.GroupServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.folderUptimeCheckConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderUptimeCheckConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderUptimeCheckConfigPath', () => { + const result = client.folderUptimeCheckConfigPath( + 'folderValue', + 'uptimeCheckConfigValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.folderUptimeCheckConfigPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderUptimeCheckConfigName', () => { + const result = + client.matchFolderFromFolderUptimeCheckConfigName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + ( + client.pathTemplates.folderUptimeCheckConfigPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchUptimeCheckConfigFromFolderUptimeCheckConfigName', () => { + const result = + client.matchUptimeCheckConfigFromFolderUptimeCheckConfigName( + fakePath, + ); + assert.strictEqual(result, 'uptimeCheckConfigValue'); + assert( + ( + client.pathTemplates.folderUptimeCheckConfigPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('organizationAlertPolicy', () => { - const fakePath = "/rendered/path/organizationAlertPolicy"; - const expectedParameters = { - organization: "organizationValue", - alert_policy: "alertPolicyValue", - }; - const client = new groupserviceModule.v3.GroupServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.organizationAlertPolicyPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationAlertPolicyPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationAlertPolicyPath', () => { - const result = client.organizationAlertPolicyPath("organizationValue", "alertPolicyValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationAlertPolicyPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationAlertPolicyName', () => { - const result = client.matchOrganizationFromOrganizationAlertPolicyName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationAlertPolicyPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchAlertPolicyFromOrganizationAlertPolicyName', () => { - const result = client.matchAlertPolicyFromOrganizationAlertPolicyName(fakePath); - assert.strictEqual(result, "alertPolicyValue"); - assert((client.pathTemplates.organizationAlertPolicyPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('organizationAlertPolicy', () => { + const fakePath = '/rendered/path/organizationAlertPolicy'; + const expectedParameters = { + organization: 'organizationValue', + alert_policy: 'alertPolicyValue', + }; + const client = new groupserviceModule.v3.GroupServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.organizationAlertPolicyPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.organizationAlertPolicyPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('organizationAlertPolicyPath', () => { + const result = client.organizationAlertPolicyPath( + 'organizationValue', + 'alertPolicyValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationAlertPolicyPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationAlertPolicyName', () => { + const result = + client.matchOrganizationFromOrganizationAlertPolicyName(fakePath); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationAlertPolicyPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchAlertPolicyFromOrganizationAlertPolicyName', () => { + const result = + client.matchAlertPolicyFromOrganizationAlertPolicyName(fakePath); + assert.strictEqual(result, 'alertPolicyValue'); + assert( + ( + client.pathTemplates.organizationAlertPolicyPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('organizationAlertPolicyCondition', () => { - const fakePath = "/rendered/path/organizationAlertPolicyCondition"; - const expectedParameters = { - organization: "organizationValue", - alert_policy: "alertPolicyValue", - condition: "conditionValue", - }; - const client = new groupserviceModule.v3.GroupServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.organizationAlertPolicyConditionPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationAlertPolicyConditionPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationAlertPolicyConditionPath', () => { - const result = client.organizationAlertPolicyConditionPath("organizationValue", "alertPolicyValue", "conditionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationAlertPolicyConditionPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationAlertPolicyConditionName', () => { - const result = client.matchOrganizationFromOrganizationAlertPolicyConditionName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationAlertPolicyConditionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchAlertPolicyFromOrganizationAlertPolicyConditionName', () => { - const result = client.matchAlertPolicyFromOrganizationAlertPolicyConditionName(fakePath); - assert.strictEqual(result, "alertPolicyValue"); - assert((client.pathTemplates.organizationAlertPolicyConditionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchConditionFromOrganizationAlertPolicyConditionName', () => { - const result = client.matchConditionFromOrganizationAlertPolicyConditionName(fakePath); - assert.strictEqual(result, "conditionValue"); - assert((client.pathTemplates.organizationAlertPolicyConditionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('organizationAlertPolicyCondition', () => { + const fakePath = '/rendered/path/organizationAlertPolicyCondition'; + const expectedParameters = { + organization: 'organizationValue', + alert_policy: 'alertPolicyValue', + condition: 'conditionValue', + }; + const client = new groupserviceModule.v3.GroupServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.organizationAlertPolicyConditionPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.organizationAlertPolicyConditionPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('organizationAlertPolicyConditionPath', () => { + const result = client.organizationAlertPolicyConditionPath( + 'organizationValue', + 'alertPolicyValue', + 'conditionValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationAlertPolicyConditionPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationAlertPolicyConditionName', () => { + const result = + client.matchOrganizationFromOrganizationAlertPolicyConditionName( + fakePath, + ); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationAlertPolicyConditionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchAlertPolicyFromOrganizationAlertPolicyConditionName', () => { + const result = + client.matchAlertPolicyFromOrganizationAlertPolicyConditionName( + fakePath, + ); + assert.strictEqual(result, 'alertPolicyValue'); + assert( + ( + client.pathTemplates.organizationAlertPolicyConditionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchConditionFromOrganizationAlertPolicyConditionName', () => { + const result = + client.matchConditionFromOrganizationAlertPolicyConditionName( + fakePath, + ); + assert.strictEqual(result, 'conditionValue'); + assert( + ( + client.pathTemplates.organizationAlertPolicyConditionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('organizationChannelDescriptor', () => { - const fakePath = "/rendered/path/organizationChannelDescriptor"; - const expectedParameters = { - organization: "organizationValue", - channel_descriptor: "channelDescriptorValue", - }; - const client = new groupserviceModule.v3.GroupServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.organizationChannelDescriptorPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationChannelDescriptorPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationChannelDescriptorPath', () => { - const result = client.organizationChannelDescriptorPath("organizationValue", "channelDescriptorValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationChannelDescriptorPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationChannelDescriptorName', () => { - const result = client.matchOrganizationFromOrganizationChannelDescriptorName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationChannelDescriptorPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchChannelDescriptorFromOrganizationChannelDescriptorName', () => { - const result = client.matchChannelDescriptorFromOrganizationChannelDescriptorName(fakePath); - assert.strictEqual(result, "channelDescriptorValue"); - assert((client.pathTemplates.organizationChannelDescriptorPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('organizationChannelDescriptor', () => { + const fakePath = '/rendered/path/organizationChannelDescriptor'; + const expectedParameters = { + organization: 'organizationValue', + channel_descriptor: 'channelDescriptorValue', + }; + const client = new groupserviceModule.v3.GroupServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.organizationChannelDescriptorPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.organizationChannelDescriptorPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('organizationChannelDescriptorPath', () => { + const result = client.organizationChannelDescriptorPath( + 'organizationValue', + 'channelDescriptorValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationChannelDescriptorPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationChannelDescriptorName', () => { + const result = + client.matchOrganizationFromOrganizationChannelDescriptorName( + fakePath, + ); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationChannelDescriptorPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchChannelDescriptorFromOrganizationChannelDescriptorName', () => { + const result = + client.matchChannelDescriptorFromOrganizationChannelDescriptorName( + fakePath, + ); + assert.strictEqual(result, 'channelDescriptorValue'); + assert( + ( + client.pathTemplates.organizationChannelDescriptorPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('organizationGroup', () => { - const fakePath = "/rendered/path/organizationGroup"; - const expectedParameters = { - organization: "organizationValue", - group: "groupValue", - }; - const client = new groupserviceModule.v3.GroupServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.organizationGroupPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationGroupPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationGroupPath', () => { - const result = client.organizationGroupPath("organizationValue", "groupValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationGroupPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationGroupName', () => { - const result = client.matchOrganizationFromOrganizationGroupName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationGroupPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchGroupFromOrganizationGroupName', () => { - const result = client.matchGroupFromOrganizationGroupName(fakePath); - assert.strictEqual(result, "groupValue"); - assert((client.pathTemplates.organizationGroupPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('organizationGroup', () => { + const fakePath = '/rendered/path/organizationGroup'; + const expectedParameters = { + organization: 'organizationValue', + group: 'groupValue', + }; + const client = new groupserviceModule.v3.GroupServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.organizationGroupPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.organizationGroupPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('organizationGroupPath', () => { + const result = client.organizationGroupPath( + 'organizationValue', + 'groupValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationGroupPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationGroupName', () => { + const result = + client.matchOrganizationFromOrganizationGroupName(fakePath); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationGroupPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchGroupFromOrganizationGroupName', () => { + const result = client.matchGroupFromOrganizationGroupName(fakePath); + assert.strictEqual(result, 'groupValue'); + assert( + ( + client.pathTemplates.organizationGroupPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('organizationNotificationChannel', () => { - const fakePath = "/rendered/path/organizationNotificationChannel"; - const expectedParameters = { - organization: "organizationValue", - notification_channel: "notificationChannelValue", - }; - const client = new groupserviceModule.v3.GroupServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.organizationNotificationChannelPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationNotificationChannelPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationNotificationChannelPath', () => { - const result = client.organizationNotificationChannelPath("organizationValue", "notificationChannelValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationNotificationChannelPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationNotificationChannelName', () => { - const result = client.matchOrganizationFromOrganizationNotificationChannelName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationNotificationChannelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchNotificationChannelFromOrganizationNotificationChannelName', () => { - const result = client.matchNotificationChannelFromOrganizationNotificationChannelName(fakePath); - assert.strictEqual(result, "notificationChannelValue"); - assert((client.pathTemplates.organizationNotificationChannelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('organizationNotificationChannel', () => { + const fakePath = '/rendered/path/organizationNotificationChannel'; + const expectedParameters = { + organization: 'organizationValue', + notification_channel: 'notificationChannelValue', + }; + const client = new groupserviceModule.v3.GroupServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.organizationNotificationChannelPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.organizationNotificationChannelPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('organizationNotificationChannelPath', () => { + const result = client.organizationNotificationChannelPath( + 'organizationValue', + 'notificationChannelValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationNotificationChannelPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationNotificationChannelName', () => { + const result = + client.matchOrganizationFromOrganizationNotificationChannelName( + fakePath, + ); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationNotificationChannelPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchNotificationChannelFromOrganizationNotificationChannelName', () => { + const result = + client.matchNotificationChannelFromOrganizationNotificationChannelName( + fakePath, + ); + assert.strictEqual(result, 'notificationChannelValue'); + assert( + ( + client.pathTemplates.organizationNotificationChannelPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('organizationService', () => { - const fakePath = "/rendered/path/organizationService"; - const expectedParameters = { - organization: "organizationValue", - service: "serviceValue", - }; - const client = new groupserviceModule.v3.GroupServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.organizationServicePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationServicePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationServicePath', () => { - const result = client.organizationServicePath("organizationValue", "serviceValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationServicePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationServiceName', () => { - const result = client.matchOrganizationFromOrganizationServiceName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationServicePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServiceFromOrganizationServiceName', () => { - const result = client.matchServiceFromOrganizationServiceName(fakePath); - assert.strictEqual(result, "serviceValue"); - assert((client.pathTemplates.organizationServicePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('organizationService', () => { + const fakePath = '/rendered/path/organizationService'; + const expectedParameters = { + organization: 'organizationValue', + service: 'serviceValue', + }; + const client = new groupserviceModule.v3.GroupServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.organizationServicePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.organizationServicePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('organizationServicePath', () => { + const result = client.organizationServicePath( + 'organizationValue', + 'serviceValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationServicePathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationServiceName', () => { + const result = + client.matchOrganizationFromOrganizationServiceName(fakePath); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationServicePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServiceFromOrganizationServiceName', () => { + const result = client.matchServiceFromOrganizationServiceName(fakePath); + assert.strictEqual(result, 'serviceValue'); + assert( + ( + client.pathTemplates.organizationServicePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('organizationServiceServiceLevelObjective', () => { - const fakePath = "/rendered/path/organizationServiceServiceLevelObjective"; - const expectedParameters = { - organization: "organizationValue", - service: "serviceValue", - service_level_objective: "serviceLevelObjectiveValue", - }; - const client = new groupserviceModule.v3.GroupServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationServiceServiceLevelObjectivePath', () => { - const result = client.organizationServiceServiceLevelObjectivePath("organizationValue", "serviceValue", "serviceLevelObjectiveValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationServiceServiceLevelObjectiveName', () => { - const result = client.matchOrganizationFromOrganizationServiceServiceLevelObjectiveName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServiceFromOrganizationServiceServiceLevelObjectiveName', () => { - const result = client.matchServiceFromOrganizationServiceServiceLevelObjectiveName(fakePath); - assert.strictEqual(result, "serviceValue"); - assert((client.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServiceLevelObjectiveFromOrganizationServiceServiceLevelObjectiveName', () => { - const result = client.matchServiceLevelObjectiveFromOrganizationServiceServiceLevelObjectiveName(fakePath); - assert.strictEqual(result, "serviceLevelObjectiveValue"); - assert((client.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('organizationServiceServiceLevelObjective', () => { + const fakePath = + '/rendered/path/organizationServiceServiceLevelObjective'; + const expectedParameters = { + organization: 'organizationValue', + service: 'serviceValue', + service_level_objective: 'serviceLevelObjectiveValue', + }; + const client = new groupserviceModule.v3.GroupServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('organizationServiceServiceLevelObjectivePath', () => { + const result = client.organizationServiceServiceLevelObjectivePath( + 'organizationValue', + 'serviceValue', + 'serviceLevelObjectiveValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates + .organizationServiceServiceLevelObjectivePathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationServiceServiceLevelObjectiveName', () => { + const result = + client.matchOrganizationFromOrganizationServiceServiceLevelObjectiveName( + fakePath, + ); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates + .organizationServiceServiceLevelObjectivePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServiceFromOrganizationServiceServiceLevelObjectiveName', () => { + const result = + client.matchServiceFromOrganizationServiceServiceLevelObjectiveName( + fakePath, + ); + assert.strictEqual(result, 'serviceValue'); + assert( + ( + client.pathTemplates + .organizationServiceServiceLevelObjectivePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServiceLevelObjectiveFromOrganizationServiceServiceLevelObjectiveName', () => { + const result = + client.matchServiceLevelObjectiveFromOrganizationServiceServiceLevelObjectiveName( + fakePath, + ); + assert.strictEqual(result, 'serviceLevelObjectiveValue'); + assert( + ( + client.pathTemplates + .organizationServiceServiceLevelObjectivePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('organizationUptimeCheckConfig', () => { - const fakePath = "/rendered/path/organizationUptimeCheckConfig"; - const expectedParameters = { - organization: "organizationValue", - uptime_check_config: "uptimeCheckConfigValue", - }; - const client = new groupserviceModule.v3.GroupServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.organizationUptimeCheckConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationUptimeCheckConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationUptimeCheckConfigPath', () => { - const result = client.organizationUptimeCheckConfigPath("organizationValue", "uptimeCheckConfigValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationUptimeCheckConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationUptimeCheckConfigName', () => { - const result = client.matchOrganizationFromOrganizationUptimeCheckConfigName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationUptimeCheckConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchUptimeCheckConfigFromOrganizationUptimeCheckConfigName', () => { - const result = client.matchUptimeCheckConfigFromOrganizationUptimeCheckConfigName(fakePath); - assert.strictEqual(result, "uptimeCheckConfigValue"); - assert((client.pathTemplates.organizationUptimeCheckConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('organizationUptimeCheckConfig', () => { + const fakePath = '/rendered/path/organizationUptimeCheckConfig'; + const expectedParameters = { + organization: 'organizationValue', + uptime_check_config: 'uptimeCheckConfigValue', + }; + const client = new groupserviceModule.v3.GroupServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.organizationUptimeCheckConfigPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.organizationUptimeCheckConfigPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('organizationUptimeCheckConfigPath', () => { + const result = client.organizationUptimeCheckConfigPath( + 'organizationValue', + 'uptimeCheckConfigValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationUptimeCheckConfigPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationUptimeCheckConfigName', () => { + const result = + client.matchOrganizationFromOrganizationUptimeCheckConfigName( + fakePath, + ); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationUptimeCheckConfigPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchUptimeCheckConfigFromOrganizationUptimeCheckConfigName', () => { + const result = + client.matchUptimeCheckConfigFromOrganizationUptimeCheckConfigName( + fakePath, + ); + assert.strictEqual(result, 'uptimeCheckConfigValue'); + assert( + ( + client.pathTemplates.organizationUptimeCheckConfigPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectAlertPolicy', () => { - const fakePath = "/rendered/path/projectAlertPolicy"; - const expectedParameters = { - project: "projectValue", - alert_policy: "alertPolicyValue", - }; - const client = new groupserviceModule.v3.GroupServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.projectAlertPolicyPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectAlertPolicyPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectAlertPolicyPath', () => { - const result = client.projectAlertPolicyPath("projectValue", "alertPolicyValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectAlertPolicyPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectAlertPolicyName', () => { - const result = client.matchProjectFromProjectAlertPolicyName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectAlertPolicyPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchAlertPolicyFromProjectAlertPolicyName', () => { - const result = client.matchAlertPolicyFromProjectAlertPolicyName(fakePath); - assert.strictEqual(result, "alertPolicyValue"); - assert((client.pathTemplates.projectAlertPolicyPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectAlertPolicy', () => { + const fakePath = '/rendered/path/projectAlertPolicy'; + const expectedParameters = { + project: 'projectValue', + alert_policy: 'alertPolicyValue', + }; + const client = new groupserviceModule.v3.GroupServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.projectAlertPolicyPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectAlertPolicyPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectAlertPolicyPath', () => { + const result = client.projectAlertPolicyPath( + 'projectValue', + 'alertPolicyValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.projectAlertPolicyPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectAlertPolicyName', () => { + const result = client.matchProjectFromProjectAlertPolicyName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.projectAlertPolicyPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchAlertPolicyFromProjectAlertPolicyName', () => { + const result = + client.matchAlertPolicyFromProjectAlertPolicyName(fakePath); + assert.strictEqual(result, 'alertPolicyValue'); + assert( + ( + client.pathTemplates.projectAlertPolicyPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectAlertPolicyCondition', () => { - const fakePath = "/rendered/path/projectAlertPolicyCondition"; - const expectedParameters = { - project: "projectValue", - alert_policy: "alertPolicyValue", - condition: "conditionValue", - }; - const client = new groupserviceModule.v3.GroupServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.projectAlertPolicyConditionPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectAlertPolicyConditionPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectAlertPolicyConditionPath', () => { - const result = client.projectAlertPolicyConditionPath("projectValue", "alertPolicyValue", "conditionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectAlertPolicyConditionPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectAlertPolicyConditionName', () => { - const result = client.matchProjectFromProjectAlertPolicyConditionName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectAlertPolicyConditionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchAlertPolicyFromProjectAlertPolicyConditionName', () => { - const result = client.matchAlertPolicyFromProjectAlertPolicyConditionName(fakePath); - assert.strictEqual(result, "alertPolicyValue"); - assert((client.pathTemplates.projectAlertPolicyConditionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchConditionFromProjectAlertPolicyConditionName', () => { - const result = client.matchConditionFromProjectAlertPolicyConditionName(fakePath); - assert.strictEqual(result, "conditionValue"); - assert((client.pathTemplates.projectAlertPolicyConditionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectAlertPolicyCondition', () => { + const fakePath = '/rendered/path/projectAlertPolicyCondition'; + const expectedParameters = { + project: 'projectValue', + alert_policy: 'alertPolicyValue', + condition: 'conditionValue', + }; + const client = new groupserviceModule.v3.GroupServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.projectAlertPolicyConditionPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.projectAlertPolicyConditionPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectAlertPolicyConditionPath', () => { + const result = client.projectAlertPolicyConditionPath( + 'projectValue', + 'alertPolicyValue', + 'conditionValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.projectAlertPolicyConditionPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectAlertPolicyConditionName', () => { + const result = + client.matchProjectFromProjectAlertPolicyConditionName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.projectAlertPolicyConditionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchAlertPolicyFromProjectAlertPolicyConditionName', () => { + const result = + client.matchAlertPolicyFromProjectAlertPolicyConditionName(fakePath); + assert.strictEqual(result, 'alertPolicyValue'); + assert( + ( + client.pathTemplates.projectAlertPolicyConditionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchConditionFromProjectAlertPolicyConditionName', () => { + const result = + client.matchConditionFromProjectAlertPolicyConditionName(fakePath); + assert.strictEqual(result, 'conditionValue'); + assert( + ( + client.pathTemplates.projectAlertPolicyConditionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectChannelDescriptor', () => { - const fakePath = "/rendered/path/projectChannelDescriptor"; - const expectedParameters = { - project: "projectValue", - channel_descriptor: "channelDescriptorValue", - }; - const client = new groupserviceModule.v3.GroupServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.projectChannelDescriptorPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectChannelDescriptorPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectChannelDescriptorPath', () => { - const result = client.projectChannelDescriptorPath("projectValue", "channelDescriptorValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectChannelDescriptorPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectChannelDescriptorName', () => { - const result = client.matchProjectFromProjectChannelDescriptorName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectChannelDescriptorPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchChannelDescriptorFromProjectChannelDescriptorName', () => { - const result = client.matchChannelDescriptorFromProjectChannelDescriptorName(fakePath); - assert.strictEqual(result, "channelDescriptorValue"); - assert((client.pathTemplates.projectChannelDescriptorPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectChannelDescriptor', () => { + const fakePath = '/rendered/path/projectChannelDescriptor'; + const expectedParameters = { + project: 'projectValue', + channel_descriptor: 'channelDescriptorValue', + }; + const client = new groupserviceModule.v3.GroupServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.projectChannelDescriptorPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectChannelDescriptorPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectChannelDescriptorPath', () => { + const result = client.projectChannelDescriptorPath( + 'projectValue', + 'channelDescriptorValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.projectChannelDescriptorPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectChannelDescriptorName', () => { + const result = + client.matchProjectFromProjectChannelDescriptorName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.projectChannelDescriptorPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchChannelDescriptorFromProjectChannelDescriptorName', () => { + const result = + client.matchChannelDescriptorFromProjectChannelDescriptorName( + fakePath, + ); + assert.strictEqual(result, 'channelDescriptorValue'); + assert( + ( + client.pathTemplates.projectChannelDescriptorPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectGroup', () => { - const fakePath = "/rendered/path/projectGroup"; - const expectedParameters = { - project: "projectValue", - group: "groupValue", - }; - const client = new groupserviceModule.v3.GroupServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.projectGroupPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectGroupPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectGroupPath', () => { - const result = client.projectGroupPath("projectValue", "groupValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectGroupPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectGroupName', () => { - const result = client.matchProjectFromProjectGroupName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectGroupPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchGroupFromProjectGroupName', () => { - const result = client.matchGroupFromProjectGroupName(fakePath); - assert.strictEqual(result, "groupValue"); - assert((client.pathTemplates.projectGroupPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectGroup', () => { + const fakePath = '/rendered/path/projectGroup'; + const expectedParameters = { + project: 'projectValue', + group: 'groupValue', + }; + const client = new groupserviceModule.v3.GroupServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.projectGroupPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectGroupPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectGroupPath', () => { + const result = client.projectGroupPath('projectValue', 'groupValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.projectGroupPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectGroupName', () => { + const result = client.matchProjectFromProjectGroupName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.projectGroupPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchGroupFromProjectGroupName', () => { + const result = client.matchGroupFromProjectGroupName(fakePath); + assert.strictEqual(result, 'groupValue'); + assert( + (client.pathTemplates.projectGroupPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectNotificationChannel', () => { - const fakePath = "/rendered/path/projectNotificationChannel"; - const expectedParameters = { - project: "projectValue", - notification_channel: "notificationChannelValue", - }; - const client = new groupserviceModule.v3.GroupServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.projectNotificationChannelPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectNotificationChannelPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectNotificationChannelPath', () => { - const result = client.projectNotificationChannelPath("projectValue", "notificationChannelValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectNotificationChannelPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectNotificationChannelName', () => { - const result = client.matchProjectFromProjectNotificationChannelName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectNotificationChannelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchNotificationChannelFromProjectNotificationChannelName', () => { - const result = client.matchNotificationChannelFromProjectNotificationChannelName(fakePath); - assert.strictEqual(result, "notificationChannelValue"); - assert((client.pathTemplates.projectNotificationChannelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectNotificationChannel', () => { + const fakePath = '/rendered/path/projectNotificationChannel'; + const expectedParameters = { + project: 'projectValue', + notification_channel: 'notificationChannelValue', + }; + const client = new groupserviceModule.v3.GroupServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.projectNotificationChannelPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectNotificationChannelPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectNotificationChannelPath', () => { + const result = client.projectNotificationChannelPath( + 'projectValue', + 'notificationChannelValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.projectNotificationChannelPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectNotificationChannelName', () => { + const result = + client.matchProjectFromProjectNotificationChannelName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.projectNotificationChannelPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchNotificationChannelFromProjectNotificationChannelName', () => { + const result = + client.matchNotificationChannelFromProjectNotificationChannelName( + fakePath, + ); + assert.strictEqual(result, 'notificationChannelValue'); + assert( + ( + client.pathTemplates.projectNotificationChannelPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectService', () => { - const fakePath = "/rendered/path/projectService"; - const expectedParameters = { - project: "projectValue", - service: "serviceValue", - }; - const client = new groupserviceModule.v3.GroupServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.projectServicePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectServicePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectServicePath', () => { - const result = client.projectServicePath("projectValue", "serviceValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectServicePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectServiceName', () => { - const result = client.matchProjectFromProjectServiceName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectServicePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServiceFromProjectServiceName', () => { - const result = client.matchServiceFromProjectServiceName(fakePath); - assert.strictEqual(result, "serviceValue"); - assert((client.pathTemplates.projectServicePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectService', () => { + const fakePath = '/rendered/path/projectService'; + const expectedParameters = { + project: 'projectValue', + service: 'serviceValue', + }; + const client = new groupserviceModule.v3.GroupServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.projectServicePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectServicePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectServicePath', () => { + const result = client.projectServicePath( + 'projectValue', + 'serviceValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.projectServicePathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectServiceName', () => { + const result = client.matchProjectFromProjectServiceName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.projectServicePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServiceFromProjectServiceName', () => { + const result = client.matchServiceFromProjectServiceName(fakePath); + assert.strictEqual(result, 'serviceValue'); + assert( + (client.pathTemplates.projectServicePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectServiceServiceLevelObjective', () => { - const fakePath = "/rendered/path/projectServiceServiceLevelObjective"; - const expectedParameters = { - project: "projectValue", - service: "serviceValue", - service_level_objective: "serviceLevelObjectiveValue", - }; - const client = new groupserviceModule.v3.GroupServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectServiceServiceLevelObjectivePath', () => { - const result = client.projectServiceServiceLevelObjectivePath("projectValue", "serviceValue", "serviceLevelObjectiveValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectServiceServiceLevelObjectiveName', () => { - const result = client.matchProjectFromProjectServiceServiceLevelObjectiveName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServiceFromProjectServiceServiceLevelObjectiveName', () => { - const result = client.matchServiceFromProjectServiceServiceLevelObjectiveName(fakePath); - assert.strictEqual(result, "serviceValue"); - assert((client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServiceLevelObjectiveFromProjectServiceServiceLevelObjectiveName', () => { - const result = client.matchServiceLevelObjectiveFromProjectServiceServiceLevelObjectiveName(fakePath); - assert.strictEqual(result, "serviceLevelObjectiveValue"); - assert((client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectServiceServiceLevelObjective', () => { + const fakePath = '/rendered/path/projectServiceServiceLevelObjective'; + const expectedParameters = { + project: 'projectValue', + service: 'serviceValue', + service_level_objective: 'serviceLevelObjectiveValue', + }; + const client = new groupserviceModule.v3.GroupServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('projectServiceServiceLevelObjectivePath', () => { + const result = client.projectServiceServiceLevelObjectivePath( + 'projectValue', + 'serviceValue', + 'serviceLevelObjectiveValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectServiceServiceLevelObjectiveName', () => { + const result = + client.matchProjectFromProjectServiceServiceLevelObjectiveName( + fakePath, + ); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServiceFromProjectServiceServiceLevelObjectiveName', () => { + const result = + client.matchServiceFromProjectServiceServiceLevelObjectiveName( + fakePath, + ); + assert.strictEqual(result, 'serviceValue'); + assert( + ( + client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServiceLevelObjectiveFromProjectServiceServiceLevelObjectiveName', () => { + const result = + client.matchServiceLevelObjectiveFromProjectServiceServiceLevelObjectiveName( + fakePath, + ); + assert.strictEqual(result, 'serviceLevelObjectiveValue'); + assert( + ( + client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectUptimeCheckConfig', () => { - const fakePath = "/rendered/path/projectUptimeCheckConfig"; - const expectedParameters = { - project: "projectValue", - uptime_check_config: "uptimeCheckConfigValue", - }; - const client = new groupserviceModule.v3.GroupServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.projectUptimeCheckConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectUptimeCheckConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectUptimeCheckConfigPath', () => { - const result = client.projectUptimeCheckConfigPath("projectValue", "uptimeCheckConfigValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectUptimeCheckConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectUptimeCheckConfigName', () => { - const result = client.matchProjectFromProjectUptimeCheckConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectUptimeCheckConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchUptimeCheckConfigFromProjectUptimeCheckConfigName', () => { - const result = client.matchUptimeCheckConfigFromProjectUptimeCheckConfigName(fakePath); - assert.strictEqual(result, "uptimeCheckConfigValue"); - assert((client.pathTemplates.projectUptimeCheckConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectUptimeCheckConfig', () => { + const fakePath = '/rendered/path/projectUptimeCheckConfig'; + const expectedParameters = { + project: 'projectValue', + uptime_check_config: 'uptimeCheckConfigValue', + }; + const client = new groupserviceModule.v3.GroupServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.projectUptimeCheckConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectUptimeCheckConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectUptimeCheckConfigPath', () => { + const result = client.projectUptimeCheckConfigPath( + 'projectValue', + 'uptimeCheckConfigValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.projectUptimeCheckConfigPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectUptimeCheckConfigName', () => { + const result = + client.matchProjectFromProjectUptimeCheckConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.projectUptimeCheckConfigPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchUptimeCheckConfigFromProjectUptimeCheckConfigName', () => { + const result = + client.matchUptimeCheckConfigFromProjectUptimeCheckConfigName( + fakePath, + ); + assert.strictEqual(result, 'uptimeCheckConfigValue'); + assert( + ( + client.pathTemplates.projectUptimeCheckConfigPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/core/generator/gapic-generator-typescript/baselines/monitoring-esm/esm/test/gapic_metric_service_v3.ts.baseline b/core/generator/gapic-generator-typescript/baselines/monitoring-esm/esm/test/gapic_metric_service_v3.ts.baseline index d837dd6e58c0..957407448364 100644 --- a/core/generator/gapic-generator-typescript/baselines/monitoring-esm/esm/test/gapic_metric_service_v3.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/monitoring-esm/esm/test/gapic_metric_service_v3.ts.baseline @@ -20,16 +20,16 @@ import * as protos from '../../protos/protos.js'; import assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as metricserviceModule from '../src/index.js'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; -import {protobuf} from 'google-gax'; +import { protobuf } from 'google-gax'; import fs from 'fs'; import path from 'path'; -import {fileURLToPath} from 'url'; +import { fileURLToPath } from 'url'; // @ts-ignore const dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -37,2700 +37,3989 @@ const dirname = path.dirname(fileURLToPath(import.meta.url)); // to fill in default values for request objects const root = protobuf.Root.fromJSON( JSON.parse( - fs.readFileSync(path.join(dirname, '..', '..', 'protos/protos.json'), 'utf8') - )) + fs.readFileSync( + path.join(dirname, '..', '..', 'protos/protos.json'), + 'utf8', + ), + ), +); // eslint-disable-next-line @typescript-eslint/no-unused-vars function getTypeDefaultValue(typeName: string, fields: string[]) { - let type = root.lookupType(typeName) as protobuf.Type; - for (const field of fields.slice(0, -1)) { - type = type?.fields[field]?.resolvedType as protobuf.Type; - } - return type?.fields[fields[fields.length - 1]]?.defaultValue ?? null; + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type?.fields[field]?.resolvedType as protobuf.Type; + } + return type?.fields[fields[fields.length - 1]]?.defaultValue ?? null; } function generateSampleMessage(instance: T) { - const filledObject = (instance.constructor as typeof protobuf.Message) - .toObject(instance as protobuf.Message, {defaults: true}); - return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, { defaults: true }); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; } function stubSimpleCall(response?: ResponseType, error?: Error) { - return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); } -function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { - return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +function stubSimpleCallWithCallback( + response?: ResponseType, + error?: Error, +) { + return error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); } -function stubPageStreamingCall(responses?: ResponseType[], error?: Error) { - const pagingStub = sinon.stub(); - if (responses) { - for (let i = 0; i < responses.length; ++i) { - pagingStub.onCall(i).callsArgWith(2, null, responses[i]); - } +function stubPageStreamingCall( + responses?: ResponseType[], + error?: Error, +) { + const pagingStub = sinon.stub(); + if (responses) { + for (let i = 0; i < responses.length; ++i) { + pagingStub.onCall(i).callsArgWith(2, null, responses[i]); } - const transformStub = error ? sinon.stub().callsArgWith(2, error) : pagingStub; - const mockStream = new PassThrough({ - objectMode: true, - transform: transformStub, - }); - // trigger as many responses as needed - if (responses) { - for (let i = 0; i < responses.length; ++i) { - setImmediate(() => { mockStream.write({}); }); - } - setImmediate(() => { mockStream.end(); }); - } else { - setImmediate(() => { mockStream.write({}); }); - setImmediate(() => { mockStream.end(); }); + } + const transformStub = error + ? sinon.stub().callsArgWith(2, error) + : pagingStub; + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + // trigger as many responses as needed + if (responses) { + for (let i = 0; i < responses.length; ++i) { + setImmediate(() => { + mockStream.write({}); + }); } - return sinon.stub().returns(mockStream); + setImmediate(() => { + mockStream.end(); + }); + } else { + setImmediate(() => { + mockStream.write({}); + }); + setImmediate(() => { + mockStream.end(); + }); + } + return sinon.stub().returns(mockStream); } -function stubAsyncIterationCall(responses?: ResponseType[], error?: Error) { - let counter = 0; - const asyncIterable = { - [Symbol.asyncIterator]() { - return { - async next() { - if (error) { - return Promise.reject(error); - } - if (counter >= responses!.length) { - return Promise.resolve({done: true, value: undefined}); - } - return Promise.resolve({done: false, value: responses![counter++]}); - } - }; - } - }; - return sinon.stub().returns(asyncIterable); +function stubAsyncIterationCall( + responses?: ResponseType[], + error?: Error, +) { + let counter = 0; + const asyncIterable = { + [Symbol.asyncIterator]() { + return { + async next() { + if (error) { + return Promise.reject(error); + } + if (counter >= responses!.length) { + return Promise.resolve({ done: true, value: undefined }); + } + return Promise.resolve({ done: false, value: responses![counter++] }); + }, + }; + }, + }; + return sinon.stub().returns(asyncIterable); } describe('v3.MetricServiceClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new metricserviceModule.v3.MetricServiceClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'monitoring.googleapis.com'); - }); - - it('has universeDomain', () => { - const client = new metricserviceModule.v3.MetricServiceClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); - - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - it('throws DeprecationWarning if static servicePath is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const servicePath = metricserviceModule.v3.MetricServiceClient.servicePath; - assert.strictEqual(servicePath, 'monitoring.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = metricserviceModule.v3.MetricServiceClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'monitoring.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new metricserviceModule.v3.MetricServiceClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'monitoring.example.com'); - }); - - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new metricserviceModule.v3.MetricServiceClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'monitoring.example.com'); - }); - - if (typeof process === 'object' && 'env' in process) { - describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { - it('sets apiEndpoint from environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new metricserviceModule.v3.MetricServiceClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'monitoring.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - - it('value configured in code has priority over environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new metricserviceModule.v3.MetricServiceClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'monitoring.configured.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { new metricserviceModule.v3.MetricServiceClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new metricserviceModule.v3.MetricServiceClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'monitoring.googleapis.com'); + }); - it('has port', () => { - const port = metricserviceModule.v3.MetricServiceClient.port; - assert(port); - assert(typeof port === 'number'); - }); + it('has universeDomain', () => { + const client = new metricserviceModule.v3.MetricServiceClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - it('should create a client with no option', () => { - const client = new metricserviceModule.v3.MetricServiceClient(); - assert(client); - }); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = + metricserviceModule.v3.MetricServiceClient.servicePath; + assert.strictEqual(servicePath, 'monitoring.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + metricserviceModule.v3.MetricServiceClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'monitoring.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = new metricserviceModule.v3.MetricServiceClient({ + universeDomain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'monitoring.example.com'); + }); - it('should create a client with gRPC fallback', () => { - const client = new metricserviceModule.v3.MetricServiceClient({ - fallback: true, - }); - assert(client); - }); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = new metricserviceModule.v3.MetricServiceClient({ + universe_domain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'monitoring.example.com'); + }); - it('has initialize method and supports deferred initialization', async () => { - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.metricServiceStub, undefined); - await client.initialize(); - assert(client.metricServiceStub); + if (typeof process === 'object' && 'env' in process) { + describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { + it('sets apiEndpoint from environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new metricserviceModule.v3.MetricServiceClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'monitoring.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } + }); + + it('value configured in code has priority over environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new metricserviceModule.v3.MetricServiceClient({ + universeDomain: 'configured.example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'monitoring.configured.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } + }); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new metricserviceModule.v3.MetricServiceClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); + }); - it('has close method for the initialized client', done => { - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.metricServiceStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('has port', () => { + const port = metricserviceModule.v3.MetricServiceClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('has close method for the non-initialized client', done => { - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.metricServiceStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('should create a client with no option', () => { + const client = new metricserviceModule.v3.MetricServiceClient(); + assert(client); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); - }); + it('should create a client with gRPC fallback', () => { + const client = new metricserviceModule.v3.MetricServiceClient({ + fallback: true, + }); + assert(client); + }); - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId((err?: Error|null, projectId?: string|null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } - }); - }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); - }); + it('has initialize method and supports deferred initialization', async () => { + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.metricServiceStub, undefined); + await client.initialize(); + assert(client.metricServiceStub); }); - describe('getMonitoredResourceDescriptor', () => { - it('invokes getMonitoredResourceDescriptor without error', async () => { - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.GetMonitoredResourceDescriptorRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.GetMonitoredResourceDescriptorRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.api.MonitoredResourceDescriptor() - ); - client.innerApiCalls.getMonitoredResourceDescriptor = stubSimpleCall(expectedResponse); - const [response] = await client.getMonitoredResourceDescriptor(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getMonitoredResourceDescriptor as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getMonitoredResourceDescriptor as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('has close method for the initialized client', (done) => { + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.metricServiceStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes getMonitoredResourceDescriptor without error using callback', async () => { - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.GetMonitoredResourceDescriptorRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.GetMonitoredResourceDescriptorRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.api.MonitoredResourceDescriptor() - ); - client.innerApiCalls.getMonitoredResourceDescriptor = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getMonitoredResourceDescriptor( - request, - (err?: Error|null, result?: protos.google.api.IMonitoredResourceDescriptor|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getMonitoredResourceDescriptor as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getMonitoredResourceDescriptor as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('has close method for the non-initialized client', (done) => { + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.metricServiceStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes getMonitoredResourceDescriptor with error', async () => { - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.GetMonitoredResourceDescriptorRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.GetMonitoredResourceDescriptorRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getMonitoredResourceDescriptor = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getMonitoredResourceDescriptor(request), expectedError); - const actualRequest = (client.innerApiCalls.getMonitoredResourceDescriptor as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getMonitoredResourceDescriptor as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + }); - it('invokes getMonitoredResourceDescriptor with closed client', async () => { - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.GetMonitoredResourceDescriptorRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.GetMonitoredResourceDescriptorRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getMonitoredResourceDescriptor(request), expectedError); - }); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } + }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + }); + + describe('getMonitoredResourceDescriptor', () => { + it('invokes getMonitoredResourceDescriptor without error', async () => { + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.GetMonitoredResourceDescriptorRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.GetMonitoredResourceDescriptorRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.api.MonitoredResourceDescriptor(), + ); + client.innerApiCalls.getMonitoredResourceDescriptor = + stubSimpleCall(expectedResponse); + const [response] = await client.getMonitoredResourceDescriptor(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getMonitoredResourceDescriptor as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getMonitoredResourceDescriptor as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('getMetricDescriptor', () => { - it('invokes getMetricDescriptor without error', async () => { - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.GetMetricDescriptorRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.GetMetricDescriptorRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.api.MetricDescriptor() - ); - client.innerApiCalls.getMetricDescriptor = stubSimpleCall(expectedResponse); - const [response] = await client.getMetricDescriptor(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getMetricDescriptor as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getMetricDescriptor as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getMonitoredResourceDescriptor without error using callback', async () => { + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.GetMonitoredResourceDescriptorRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.GetMonitoredResourceDescriptorRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.api.MonitoredResourceDescriptor(), + ); + client.innerApiCalls.getMonitoredResourceDescriptor = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getMonitoredResourceDescriptor( + request, + ( + err?: Error | null, + result?: protos.google.api.IMonitoredResourceDescriptor | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getMonitoredResourceDescriptor as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getMonitoredResourceDescriptor as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getMetricDescriptor without error using callback', async () => { - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.GetMetricDescriptorRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.GetMetricDescriptorRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.api.MetricDescriptor() - ); - client.innerApiCalls.getMetricDescriptor = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getMetricDescriptor( - request, - (err?: Error|null, result?: protos.google.api.IMetricDescriptor|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getMetricDescriptor as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getMetricDescriptor as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getMonitoredResourceDescriptor with error', async () => { + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.GetMonitoredResourceDescriptorRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.GetMonitoredResourceDescriptorRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getMonitoredResourceDescriptor = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.getMonitoredResourceDescriptor(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.getMonitoredResourceDescriptor as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getMonitoredResourceDescriptor as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getMetricDescriptor with error', async () => { - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.GetMetricDescriptorRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.GetMetricDescriptorRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getMetricDescriptor = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getMetricDescriptor(request), expectedError); - const actualRequest = (client.innerApiCalls.getMetricDescriptor as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getMetricDescriptor as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getMonitoredResourceDescriptor with closed client', async () => { + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.GetMonitoredResourceDescriptorRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.GetMonitoredResourceDescriptorRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.getMonitoredResourceDescriptor(request), + expectedError, + ); + }); + }); + + describe('getMetricDescriptor', () => { + it('invokes getMetricDescriptor without error', async () => { + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.GetMetricDescriptorRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.GetMetricDescriptorRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.api.MetricDescriptor(), + ); + client.innerApiCalls.getMetricDescriptor = + stubSimpleCall(expectedResponse); + const [response] = await client.getMetricDescriptor(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getMetricDescriptor as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getMetricDescriptor as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getMetricDescriptor with closed client', async () => { - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.GetMetricDescriptorRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.GetMetricDescriptorRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getMetricDescriptor(request), expectedError); - }); + it('invokes getMetricDescriptor without error using callback', async () => { + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.GetMetricDescriptorRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.GetMetricDescriptorRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.api.MetricDescriptor(), + ); + client.innerApiCalls.getMetricDescriptor = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getMetricDescriptor( + request, + ( + err?: Error | null, + result?: protos.google.api.IMetricDescriptor | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getMetricDescriptor as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getMetricDescriptor as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('createMetricDescriptor', () => { - it('invokes createMetricDescriptor without error', async () => { - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.CreateMetricDescriptorRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.CreateMetricDescriptorRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.api.MetricDescriptor() - ); - client.innerApiCalls.createMetricDescriptor = stubSimpleCall(expectedResponse); - const [response] = await client.createMetricDescriptor(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createMetricDescriptor as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createMetricDescriptor as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getMetricDescriptor with error', async () => { + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.GetMetricDescriptorRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.GetMetricDescriptorRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getMetricDescriptor = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getMetricDescriptor(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getMetricDescriptor as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getMetricDescriptor as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createMetricDescriptor without error using callback', async () => { - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.CreateMetricDescriptorRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.CreateMetricDescriptorRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.api.MetricDescriptor() - ); - client.innerApiCalls.createMetricDescriptor = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createMetricDescriptor( - request, - (err?: Error|null, result?: protos.google.api.IMetricDescriptor|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createMetricDescriptor as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createMetricDescriptor as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getMetricDescriptor with closed client', async () => { + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.GetMetricDescriptorRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.GetMetricDescriptorRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getMetricDescriptor(request), expectedError); + }); + }); + + describe('createMetricDescriptor', () => { + it('invokes createMetricDescriptor without error', async () => { + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.CreateMetricDescriptorRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.CreateMetricDescriptorRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.api.MetricDescriptor(), + ); + client.innerApiCalls.createMetricDescriptor = + stubSimpleCall(expectedResponse); + const [response] = await client.createMetricDescriptor(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createMetricDescriptor as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createMetricDescriptor as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createMetricDescriptor with error', async () => { - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.CreateMetricDescriptorRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.CreateMetricDescriptorRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createMetricDescriptor = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createMetricDescriptor(request), expectedError); - const actualRequest = (client.innerApiCalls.createMetricDescriptor as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createMetricDescriptor as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createMetricDescriptor without error using callback', async () => { + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.CreateMetricDescriptorRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.CreateMetricDescriptorRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.api.MetricDescriptor(), + ); + client.innerApiCalls.createMetricDescriptor = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createMetricDescriptor( + request, + ( + err?: Error | null, + result?: protos.google.api.IMetricDescriptor | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createMetricDescriptor as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createMetricDescriptor as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createMetricDescriptor with closed client', async () => { - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.CreateMetricDescriptorRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.CreateMetricDescriptorRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createMetricDescriptor(request), expectedError); - }); + it('invokes createMetricDescriptor with error', async () => { + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.CreateMetricDescriptorRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.CreateMetricDescriptorRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createMetricDescriptor = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.createMetricDescriptor(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.createMetricDescriptor as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createMetricDescriptor as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('deleteMetricDescriptor', () => { - it('invokes deleteMetricDescriptor without error', async () => { - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.DeleteMetricDescriptorRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.DeleteMetricDescriptorRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteMetricDescriptor = stubSimpleCall(expectedResponse); - const [response] = await client.deleteMetricDescriptor(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteMetricDescriptor as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteMetricDescriptor as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createMetricDescriptor with closed client', async () => { + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.CreateMetricDescriptorRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.CreateMetricDescriptorRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.createMetricDescriptor(request), + expectedError, + ); + }); + }); + + describe('deleteMetricDescriptor', () => { + it('invokes deleteMetricDescriptor without error', async () => { + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.DeleteMetricDescriptorRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.DeleteMetricDescriptorRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteMetricDescriptor = + stubSimpleCall(expectedResponse); + const [response] = await client.deleteMetricDescriptor(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteMetricDescriptor as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteMetricDescriptor as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteMetricDescriptor without error using callback', async () => { - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.DeleteMetricDescriptorRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.DeleteMetricDescriptorRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteMetricDescriptor = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteMetricDescriptor( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteMetricDescriptor as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteMetricDescriptor as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteMetricDescriptor without error using callback', async () => { + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.DeleteMetricDescriptorRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.DeleteMetricDescriptorRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteMetricDescriptor = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteMetricDescriptor( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteMetricDescriptor as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteMetricDescriptor as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteMetricDescriptor with error', async () => { - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.DeleteMetricDescriptorRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.DeleteMetricDescriptorRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteMetricDescriptor = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteMetricDescriptor(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteMetricDescriptor as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteMetricDescriptor as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteMetricDescriptor with error', async () => { + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.DeleteMetricDescriptorRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.DeleteMetricDescriptorRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteMetricDescriptor = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.deleteMetricDescriptor(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.deleteMetricDescriptor as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteMetricDescriptor as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteMetricDescriptor with closed client', async () => { - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.DeleteMetricDescriptorRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.DeleteMetricDescriptorRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteMetricDescriptor(request), expectedError); - }); + it('invokes deleteMetricDescriptor with closed client', async () => { + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.DeleteMetricDescriptorRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.DeleteMetricDescriptorRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.deleteMetricDescriptor(request), + expectedError, + ); + }); + }); + + describe('createTimeSeries', () => { + it('invokes createTimeSeries without error', async () => { + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.CreateTimeSeriesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.CreateTimeSeriesRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.createTimeSeries = stubSimpleCall(expectedResponse); + const [response] = await client.createTimeSeries(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createTimeSeries as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createTimeSeries as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('createTimeSeries', () => { - it('invokes createTimeSeries without error', async () => { - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.CreateTimeSeriesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.CreateTimeSeriesRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.createTimeSeries = stubSimpleCall(expectedResponse); - const [response] = await client.createTimeSeries(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createTimeSeries as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createTimeSeries as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createTimeSeries without error using callback', async () => { + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.CreateTimeSeriesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.CreateTimeSeriesRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.createTimeSeries = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createTimeSeries( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createTimeSeries as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createTimeSeries as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createTimeSeries without error using callback', async () => { - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.CreateTimeSeriesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.CreateTimeSeriesRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.createTimeSeries = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createTimeSeries( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createTimeSeries as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createTimeSeries as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createTimeSeries with error', async () => { + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.CreateTimeSeriesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.CreateTimeSeriesRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createTimeSeries = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.createTimeSeries(request), expectedError); + const actualRequest = ( + client.innerApiCalls.createTimeSeries as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createTimeSeries as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createTimeSeries with error', async () => { - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.CreateTimeSeriesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.CreateTimeSeriesRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createTimeSeries = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createTimeSeries(request), expectedError); - const actualRequest = (client.innerApiCalls.createTimeSeries as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createTimeSeries as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createTimeSeries with closed client', async () => { + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.CreateTimeSeriesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.CreateTimeSeriesRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.createTimeSeries(request), expectedError); + }); + }); + + describe('listMonitoredResourceDescriptors', () => { + it('invokes listMonitoredResourceDescriptors without error', async () => { + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListMonitoredResourceDescriptorsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListMonitoredResourceDescriptorsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.api.MonitoredResourceDescriptor(), + ), + generateSampleMessage( + new protos.google.api.MonitoredResourceDescriptor(), + ), + generateSampleMessage( + new protos.google.api.MonitoredResourceDescriptor(), + ), + ]; + client.innerApiCalls.listMonitoredResourceDescriptors = + stubSimpleCall(expectedResponse); + const [response] = await client.listMonitoredResourceDescriptors(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listMonitoredResourceDescriptors as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listMonitoredResourceDescriptors as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createTimeSeries with closed client', async () => { - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.CreateTimeSeriesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.CreateTimeSeriesRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createTimeSeries(request), expectedError); - }); + it('invokes listMonitoredResourceDescriptors without error using callback', async () => { + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListMonitoredResourceDescriptorsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListMonitoredResourceDescriptorsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.api.MonitoredResourceDescriptor(), + ), + generateSampleMessage( + new protos.google.api.MonitoredResourceDescriptor(), + ), + generateSampleMessage( + new protos.google.api.MonitoredResourceDescriptor(), + ), + ]; + client.innerApiCalls.listMonitoredResourceDescriptors = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listMonitoredResourceDescriptors( + request, + ( + err?: Error | null, + result?: protos.google.api.IMonitoredResourceDescriptor[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listMonitoredResourceDescriptors as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listMonitoredResourceDescriptors as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('listMonitoredResourceDescriptors', () => { - it('invokes listMonitoredResourceDescriptors without error', async () => { - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListMonitoredResourceDescriptorsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListMonitoredResourceDescriptorsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.api.MonitoredResourceDescriptor()), - generateSampleMessage(new protos.google.api.MonitoredResourceDescriptor()), - generateSampleMessage(new protos.google.api.MonitoredResourceDescriptor()), - ]; - client.innerApiCalls.listMonitoredResourceDescriptors = stubSimpleCall(expectedResponse); - const [response] = await client.listMonitoredResourceDescriptors(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listMonitoredResourceDescriptors as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listMonitoredResourceDescriptors as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listMonitoredResourceDescriptors with error', async () => { + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListMonitoredResourceDescriptorsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListMonitoredResourceDescriptorsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listMonitoredResourceDescriptors = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.listMonitoredResourceDescriptors(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.listMonitoredResourceDescriptors as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listMonitoredResourceDescriptors as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listMonitoredResourceDescriptors without error using callback', async () => { - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListMonitoredResourceDescriptorsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListMonitoredResourceDescriptorsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.api.MonitoredResourceDescriptor()), - generateSampleMessage(new protos.google.api.MonitoredResourceDescriptor()), - generateSampleMessage(new protos.google.api.MonitoredResourceDescriptor()), - ]; - client.innerApiCalls.listMonitoredResourceDescriptors = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listMonitoredResourceDescriptors( - request, - (err?: Error|null, result?: protos.google.api.IMonitoredResourceDescriptor[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listMonitoredResourceDescriptors as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listMonitoredResourceDescriptors as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listMonitoredResourceDescriptorsStream without error', async () => { + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListMonitoredResourceDescriptorsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListMonitoredResourceDescriptorsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.api.MonitoredResourceDescriptor(), + ), + generateSampleMessage( + new protos.google.api.MonitoredResourceDescriptor(), + ), + generateSampleMessage( + new protos.google.api.MonitoredResourceDescriptor(), + ), + ]; + client.descriptors.page.listMonitoredResourceDescriptors.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listMonitoredResourceDescriptorsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.api.MonitoredResourceDescriptor[] = []; + stream.on( + 'data', + (response: protos.google.api.MonitoredResourceDescriptor) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + ( + client.descriptors.page.listMonitoredResourceDescriptors + .createStream as SinonStub + ) + .getCall(0) + .calledWith( + client.innerApiCalls.listMonitoredResourceDescriptors, + request, + ), + ); + assert( + ( + client.descriptors.page.listMonitoredResourceDescriptors + .createStream as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); - it('invokes listMonitoredResourceDescriptors with error', async () => { - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListMonitoredResourceDescriptorsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListMonitoredResourceDescriptorsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listMonitoredResourceDescriptors = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listMonitoredResourceDescriptors(request), expectedError); - const actualRequest = (client.innerApiCalls.listMonitoredResourceDescriptors as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listMonitoredResourceDescriptors as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listMonitoredResourceDescriptorsStream with error', async () => { + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListMonitoredResourceDescriptorsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListMonitoredResourceDescriptorsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listMonitoredResourceDescriptors.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listMonitoredResourceDescriptorsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.api.MonitoredResourceDescriptor[] = []; + stream.on( + 'data', + (response: protos.google.api.MonitoredResourceDescriptor) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + ( + client.descriptors.page.listMonitoredResourceDescriptors + .createStream as SinonStub + ) + .getCall(0) + .calledWith( + client.innerApiCalls.listMonitoredResourceDescriptors, + request, + ), + ); + assert( + ( + client.descriptors.page.listMonitoredResourceDescriptors + .createStream as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); - it('invokes listMonitoredResourceDescriptorsStream without error', async () => { - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListMonitoredResourceDescriptorsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListMonitoredResourceDescriptorsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.api.MonitoredResourceDescriptor()), - generateSampleMessage(new protos.google.api.MonitoredResourceDescriptor()), - generateSampleMessage(new protos.google.api.MonitoredResourceDescriptor()), - ]; - client.descriptors.page.listMonitoredResourceDescriptors.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listMonitoredResourceDescriptorsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.api.MonitoredResourceDescriptor[] = []; - stream.on('data', (response: protos.google.api.MonitoredResourceDescriptor) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.listMonitoredResourceDescriptors.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listMonitoredResourceDescriptors, request)); - assert( - (client.descriptors.page.listMonitoredResourceDescriptors.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listMonitoredResourceDescriptors without error', async () => { + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListMonitoredResourceDescriptorsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListMonitoredResourceDescriptorsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.api.MonitoredResourceDescriptor(), + ), + generateSampleMessage( + new protos.google.api.MonitoredResourceDescriptor(), + ), + generateSampleMessage( + new protos.google.api.MonitoredResourceDescriptor(), + ), + ]; + client.descriptors.page.listMonitoredResourceDescriptors.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.api.IMonitoredResourceDescriptor[] = []; + const iterable = client.listMonitoredResourceDescriptorsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listMonitoredResourceDescriptors + .asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + ( + client.descriptors.page.listMonitoredResourceDescriptors + .asyncIterate as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); - it('invokes listMonitoredResourceDescriptorsStream with error', async () => { - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListMonitoredResourceDescriptorsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListMonitoredResourceDescriptorsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listMonitoredResourceDescriptors.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listMonitoredResourceDescriptorsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.api.MonitoredResourceDescriptor[] = []; - stream.on('data', (response: protos.google.api.MonitoredResourceDescriptor) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listMonitoredResourceDescriptors.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listMonitoredResourceDescriptors, request)); - assert( - (client.descriptors.page.listMonitoredResourceDescriptors.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listMonitoredResourceDescriptors with error', async () => { + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListMonitoredResourceDescriptorsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListMonitoredResourceDescriptorsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listMonitoredResourceDescriptors.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listMonitoredResourceDescriptorsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.api.IMonitoredResourceDescriptor[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listMonitoredResourceDescriptors + .asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + ( + client.descriptors.page.listMonitoredResourceDescriptors + .asyncIterate as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); + }); + + describe('listMetricDescriptors', () => { + it('invokes listMetricDescriptors without error', async () => { + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListMetricDescriptorsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListMetricDescriptorsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.api.MetricDescriptor()), + generateSampleMessage(new protos.google.api.MetricDescriptor()), + generateSampleMessage(new protos.google.api.MetricDescriptor()), + ]; + client.innerApiCalls.listMetricDescriptors = + stubSimpleCall(expectedResponse); + const [response] = await client.listMetricDescriptors(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listMetricDescriptors as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listMetricDescriptors as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('uses async iteration with listMonitoredResourceDescriptors without error', async () => { - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListMonitoredResourceDescriptorsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListMonitoredResourceDescriptorsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.api.MonitoredResourceDescriptor()), - generateSampleMessage(new protos.google.api.MonitoredResourceDescriptor()), - generateSampleMessage(new protos.google.api.MonitoredResourceDescriptor()), - ]; - client.descriptors.page.listMonitoredResourceDescriptors.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.api.IMonitoredResourceDescriptor[] = []; - const iterable = client.listMonitoredResourceDescriptorsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); + it('invokes listMetricDescriptors without error using callback', async () => { + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListMetricDescriptorsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListMetricDescriptorsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.api.MetricDescriptor()), + generateSampleMessage(new protos.google.api.MetricDescriptor()), + generateSampleMessage(new protos.google.api.MetricDescriptor()), + ]; + client.innerApiCalls.listMetricDescriptors = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listMetricDescriptors( + request, + ( + err?: Error | null, + result?: protos.google.api.IMetricDescriptor[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listMonitoredResourceDescriptors.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listMonitoredResourceDescriptors.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); - - it('uses async iteration with listMonitoredResourceDescriptors with error', async () => { - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListMonitoredResourceDescriptorsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListMonitoredResourceDescriptorsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listMonitoredResourceDescriptors.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listMonitoredResourceDescriptorsAsync(request); - await assert.rejects(async () => { - const responses: protos.google.api.IMonitoredResourceDescriptor[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listMonitoredResourceDescriptors.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listMonitoredResourceDescriptors.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listMetricDescriptors as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listMetricDescriptors as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('listMetricDescriptors', () => { - it('invokes listMetricDescriptors without error', async () => { - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListMetricDescriptorsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListMetricDescriptorsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.api.MetricDescriptor()), - generateSampleMessage(new protos.google.api.MetricDescriptor()), - generateSampleMessage(new protos.google.api.MetricDescriptor()), - ]; - client.innerApiCalls.listMetricDescriptors = stubSimpleCall(expectedResponse); - const [response] = await client.listMetricDescriptors(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listMetricDescriptors as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listMetricDescriptors as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listMetricDescriptors with error', async () => { + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListMetricDescriptorsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListMetricDescriptorsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listMetricDescriptors = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.listMetricDescriptors(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.listMetricDescriptors as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listMetricDescriptors as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listMetricDescriptors without error using callback', async () => { - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListMetricDescriptorsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListMetricDescriptorsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.api.MetricDescriptor()), - generateSampleMessage(new protos.google.api.MetricDescriptor()), - generateSampleMessage(new protos.google.api.MetricDescriptor()), - ]; - client.innerApiCalls.listMetricDescriptors = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listMetricDescriptors( - request, - (err?: Error|null, result?: protos.google.api.IMetricDescriptor[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listMetricDescriptors as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listMetricDescriptors as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listMetricDescriptorsStream without error', async () => { + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListMetricDescriptorsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListMetricDescriptorsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.api.MetricDescriptor()), + generateSampleMessage(new protos.google.api.MetricDescriptor()), + generateSampleMessage(new protos.google.api.MetricDescriptor()), + ]; + client.descriptors.page.listMetricDescriptors.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listMetricDescriptorsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.api.MetricDescriptor[] = []; + stream.on('data', (response: protos.google.api.MetricDescriptor) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + ( + client.descriptors.page.listMetricDescriptors + .createStream as SinonStub + ) + .getCall(0) + .calledWith(client.innerApiCalls.listMetricDescriptors, request), + ); + assert( + ( + client.descriptors.page.listMetricDescriptors + .createStream as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); - it('invokes listMetricDescriptors with error', async () => { - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListMetricDescriptorsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListMetricDescriptorsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listMetricDescriptors = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listMetricDescriptors(request), expectedError); - const actualRequest = (client.innerApiCalls.listMetricDescriptors as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listMetricDescriptors as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listMetricDescriptorsStream with error', async () => { + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListMetricDescriptorsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListMetricDescriptorsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listMetricDescriptors.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listMetricDescriptorsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.api.MetricDescriptor[] = []; + stream.on('data', (response: protos.google.api.MetricDescriptor) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + ( + client.descriptors.page.listMetricDescriptors + .createStream as SinonStub + ) + .getCall(0) + .calledWith(client.innerApiCalls.listMetricDescriptors, request), + ); + assert( + ( + client.descriptors.page.listMetricDescriptors + .createStream as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); - it('invokes listMetricDescriptorsStream without error', async () => { - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListMetricDescriptorsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListMetricDescriptorsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.api.MetricDescriptor()), - generateSampleMessage(new protos.google.api.MetricDescriptor()), - generateSampleMessage(new protos.google.api.MetricDescriptor()), - ]; - client.descriptors.page.listMetricDescriptors.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listMetricDescriptorsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.api.MetricDescriptor[] = []; - stream.on('data', (response: protos.google.api.MetricDescriptor) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.listMetricDescriptors.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listMetricDescriptors, request)); - assert( - (client.descriptors.page.listMetricDescriptors.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listMetricDescriptors without error', async () => { + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListMetricDescriptorsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListMetricDescriptorsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.api.MetricDescriptor()), + generateSampleMessage(new protos.google.api.MetricDescriptor()), + generateSampleMessage(new protos.google.api.MetricDescriptor()), + ]; + client.descriptors.page.listMetricDescriptors.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.api.IMetricDescriptor[] = []; + const iterable = client.listMetricDescriptorsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listMetricDescriptors + .asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + ( + client.descriptors.page.listMetricDescriptors + .asyncIterate as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); - it('invokes listMetricDescriptorsStream with error', async () => { - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListMetricDescriptorsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListMetricDescriptorsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listMetricDescriptors.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listMetricDescriptorsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.api.MetricDescriptor[] = []; - stream.on('data', (response: protos.google.api.MetricDescriptor) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listMetricDescriptors.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listMetricDescriptors, request)); - assert( - (client.descriptors.page.listMetricDescriptors.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listMetricDescriptors with error', async () => { + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListMetricDescriptorsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListMetricDescriptorsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listMetricDescriptors.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listMetricDescriptorsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.api.IMetricDescriptor[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listMetricDescriptors + .asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + ( + client.descriptors.page.listMetricDescriptors + .asyncIterate as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); + }); + + describe('listTimeSeries', () => { + it('invokes listTimeSeries without error', async () => { + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListTimeSeriesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListTimeSeriesRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.monitoring.v3.TimeSeries()), + generateSampleMessage(new protos.google.monitoring.v3.TimeSeries()), + generateSampleMessage(new protos.google.monitoring.v3.TimeSeries()), + ]; + client.innerApiCalls.listTimeSeries = stubSimpleCall(expectedResponse); + const [response] = await client.listTimeSeries(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listTimeSeries as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listTimeSeries as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('uses async iteration with listMetricDescriptors without error', async () => { - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListMetricDescriptorsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListMetricDescriptorsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.api.MetricDescriptor()), - generateSampleMessage(new protos.google.api.MetricDescriptor()), - generateSampleMessage(new protos.google.api.MetricDescriptor()), - ]; - client.descriptors.page.listMetricDescriptors.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.api.IMetricDescriptor[] = []; - const iterable = client.listMetricDescriptorsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); + it('invokes listTimeSeries without error using callback', async () => { + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListTimeSeriesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListTimeSeriesRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.monitoring.v3.TimeSeries()), + generateSampleMessage(new protos.google.monitoring.v3.TimeSeries()), + generateSampleMessage(new protos.google.monitoring.v3.TimeSeries()), + ]; + client.innerApiCalls.listTimeSeries = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listTimeSeries( + request, + ( + err?: Error | null, + result?: protos.google.monitoring.v3.ITimeSeries[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listMetricDescriptors.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listMetricDescriptors.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); - - it('uses async iteration with listMetricDescriptors with error', async () => { - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListMetricDescriptorsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListMetricDescriptorsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listMetricDescriptors.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listMetricDescriptorsAsync(request); - await assert.rejects(async () => { - const responses: protos.google.api.IMetricDescriptor[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listMetricDescriptors.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listMetricDescriptors.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listTimeSeries as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listTimeSeries as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('listTimeSeries', () => { - it('invokes listTimeSeries without error', async () => { - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListTimeSeriesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListTimeSeriesRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.monitoring.v3.TimeSeries()), - generateSampleMessage(new protos.google.monitoring.v3.TimeSeries()), - generateSampleMessage(new protos.google.monitoring.v3.TimeSeries()), - ]; - client.innerApiCalls.listTimeSeries = stubSimpleCall(expectedResponse); - const [response] = await client.listTimeSeries(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listTimeSeries as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listTimeSeries as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listTimeSeries without error using callback', async () => { - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListTimeSeriesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListTimeSeriesRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.monitoring.v3.TimeSeries()), - generateSampleMessage(new protos.google.monitoring.v3.TimeSeries()), - generateSampleMessage(new protos.google.monitoring.v3.TimeSeries()), - ]; - client.innerApiCalls.listTimeSeries = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listTimeSeries( - request, - (err?: Error|null, result?: protos.google.monitoring.v3.ITimeSeries[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listTimeSeries as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listTimeSeries as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listTimeSeries with error', async () => { - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListTimeSeriesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListTimeSeriesRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listTimeSeries = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listTimeSeries(request), expectedError); - const actualRequest = (client.innerApiCalls.listTimeSeries as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listTimeSeries as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listTimeSeriesStream without error', async () => { - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListTimeSeriesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListTimeSeriesRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.monitoring.v3.TimeSeries()), - generateSampleMessage(new protos.google.monitoring.v3.TimeSeries()), - generateSampleMessage(new protos.google.monitoring.v3.TimeSeries()), - ]; - client.descriptors.page.listTimeSeries.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listTimeSeriesStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.monitoring.v3.TimeSeries[] = []; - stream.on('data', (response: protos.google.monitoring.v3.TimeSeries) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.listTimeSeries.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listTimeSeries, request)); - assert( - (client.descriptors.page.listTimeSeries.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listTimeSeries with error', async () => { + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListTimeSeriesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListTimeSeriesRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listTimeSeries = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listTimeSeries(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listTimeSeries as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listTimeSeries as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listTimeSeriesStream with error', async () => { - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListTimeSeriesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListTimeSeriesRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listTimeSeries.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listTimeSeriesStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.monitoring.v3.TimeSeries[] = []; - stream.on('data', (response: protos.google.monitoring.v3.TimeSeries) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listTimeSeries.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listTimeSeries, request)); - assert( - (client.descriptors.page.listTimeSeries.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listTimeSeriesStream without error', async () => { + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListTimeSeriesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListTimeSeriesRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.monitoring.v3.TimeSeries()), + generateSampleMessage(new protos.google.monitoring.v3.TimeSeries()), + generateSampleMessage(new protos.google.monitoring.v3.TimeSeries()), + ]; + client.descriptors.page.listTimeSeries.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listTimeSeriesStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.monitoring.v3.TimeSeries[] = []; + stream.on( + 'data', + (response: protos.google.monitoring.v3.TimeSeries) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listTimeSeries.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listTimeSeries, request), + ); + assert( + (client.descriptors.page.listTimeSeries.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('uses async iteration with listTimeSeries without error', async () => { - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListTimeSeriesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListTimeSeriesRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.monitoring.v3.TimeSeries()), - generateSampleMessage(new protos.google.monitoring.v3.TimeSeries()), - generateSampleMessage(new protos.google.monitoring.v3.TimeSeries()), - ]; - client.descriptors.page.listTimeSeries.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.monitoring.v3.ITimeSeries[] = []; - const iterable = client.listTimeSeriesAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listTimeSeries.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listTimeSeries.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listTimeSeriesStream with error', async () => { + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListTimeSeriesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListTimeSeriesRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listTimeSeries.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listTimeSeriesStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.monitoring.v3.TimeSeries[] = []; + stream.on( + 'data', + (response: protos.google.monitoring.v3.TimeSeries) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listTimeSeries.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listTimeSeries, request), + ); + assert( + (client.descriptors.page.listTimeSeries.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('uses async iteration with listTimeSeries with error', async () => { - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListTimeSeriesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListTimeSeriesRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listTimeSeries.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listTimeSeriesAsync(request); - await assert.rejects(async () => { - const responses: protos.google.monitoring.v3.ITimeSeries[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listTimeSeries.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listTimeSeries.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listTimeSeries without error', async () => { + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListTimeSeriesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListTimeSeriesRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.monitoring.v3.TimeSeries()), + generateSampleMessage(new protos.google.monitoring.v3.TimeSeries()), + generateSampleMessage(new protos.google.monitoring.v3.TimeSeries()), + ]; + client.descriptors.page.listTimeSeries.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.monitoring.v3.ITimeSeries[] = []; + const iterable = client.listTimeSeriesAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listTimeSeries.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listTimeSeries.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); }); - describe('Path templates', () => { - - describe('folderAlertPolicy', () => { - const fakePath = "/rendered/path/folderAlertPolicy"; - const expectedParameters = { - folder: "folderValue", - alert_policy: "alertPolicyValue", - }; - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.folderAlertPolicyPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderAlertPolicyPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderAlertPolicyPath', () => { - const result = client.folderAlertPolicyPath("folderValue", "alertPolicyValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderAlertPolicyPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderAlertPolicyName', () => { - const result = client.matchFolderFromFolderAlertPolicyName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderAlertPolicyPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchAlertPolicyFromFolderAlertPolicyName', () => { - const result = client.matchAlertPolicyFromFolderAlertPolicyName(fakePath); - assert.strictEqual(result, "alertPolicyValue"); - assert((client.pathTemplates.folderAlertPolicyPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('uses async iteration with listTimeSeries with error', async () => { + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListTimeSeriesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListTimeSeriesRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listTimeSeries.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listTimeSeriesAsync(request); + await assert.rejects(async () => { + const responses: protos.google.monitoring.v3.ITimeSeries[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listTimeSeries.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listTimeSeries.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + }); + + describe('Path templates', () => { + describe('folderAlertPolicy', () => { + const fakePath = '/rendered/path/folderAlertPolicy'; + const expectedParameters = { + folder: 'folderValue', + alert_policy: 'alertPolicyValue', + }; + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.folderAlertPolicyPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderAlertPolicyPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderAlertPolicyPath', () => { + const result = client.folderAlertPolicyPath( + 'folderValue', + 'alertPolicyValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.folderAlertPolicyPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderAlertPolicyName', () => { + const result = client.matchFolderFromFolderAlertPolicyName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + ( + client.pathTemplates.folderAlertPolicyPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchAlertPolicyFromFolderAlertPolicyName', () => { + const result = + client.matchAlertPolicyFromFolderAlertPolicyName(fakePath); + assert.strictEqual(result, 'alertPolicyValue'); + assert( + ( + client.pathTemplates.folderAlertPolicyPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('folderAlertPolicyCondition', () => { - const fakePath = "/rendered/path/folderAlertPolicyCondition"; - const expectedParameters = { - folder: "folderValue", - alert_policy: "alertPolicyValue", - condition: "conditionValue", - }; - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.folderAlertPolicyConditionPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderAlertPolicyConditionPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderAlertPolicyConditionPath', () => { - const result = client.folderAlertPolicyConditionPath("folderValue", "alertPolicyValue", "conditionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderAlertPolicyConditionPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderAlertPolicyConditionName', () => { - const result = client.matchFolderFromFolderAlertPolicyConditionName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderAlertPolicyConditionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchAlertPolicyFromFolderAlertPolicyConditionName', () => { - const result = client.matchAlertPolicyFromFolderAlertPolicyConditionName(fakePath); - assert.strictEqual(result, "alertPolicyValue"); - assert((client.pathTemplates.folderAlertPolicyConditionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchConditionFromFolderAlertPolicyConditionName', () => { - const result = client.matchConditionFromFolderAlertPolicyConditionName(fakePath); - assert.strictEqual(result, "conditionValue"); - assert((client.pathTemplates.folderAlertPolicyConditionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('folderAlertPolicyCondition', () => { + const fakePath = '/rendered/path/folderAlertPolicyCondition'; + const expectedParameters = { + folder: 'folderValue', + alert_policy: 'alertPolicyValue', + condition: 'conditionValue', + }; + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.folderAlertPolicyConditionPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderAlertPolicyConditionPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderAlertPolicyConditionPath', () => { + const result = client.folderAlertPolicyConditionPath( + 'folderValue', + 'alertPolicyValue', + 'conditionValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.folderAlertPolicyConditionPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderAlertPolicyConditionName', () => { + const result = + client.matchFolderFromFolderAlertPolicyConditionName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + ( + client.pathTemplates.folderAlertPolicyConditionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchAlertPolicyFromFolderAlertPolicyConditionName', () => { + const result = + client.matchAlertPolicyFromFolderAlertPolicyConditionName(fakePath); + assert.strictEqual(result, 'alertPolicyValue'); + assert( + ( + client.pathTemplates.folderAlertPolicyConditionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchConditionFromFolderAlertPolicyConditionName', () => { + const result = + client.matchConditionFromFolderAlertPolicyConditionName(fakePath); + assert.strictEqual(result, 'conditionValue'); + assert( + ( + client.pathTemplates.folderAlertPolicyConditionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('folderChannelDescriptor', () => { - const fakePath = "/rendered/path/folderChannelDescriptor"; - const expectedParameters = { - folder: "folderValue", - channel_descriptor: "channelDescriptorValue", - }; - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.folderChannelDescriptorPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderChannelDescriptorPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderChannelDescriptorPath', () => { - const result = client.folderChannelDescriptorPath("folderValue", "channelDescriptorValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderChannelDescriptorPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderChannelDescriptorName', () => { - const result = client.matchFolderFromFolderChannelDescriptorName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderChannelDescriptorPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchChannelDescriptorFromFolderChannelDescriptorName', () => { - const result = client.matchChannelDescriptorFromFolderChannelDescriptorName(fakePath); - assert.strictEqual(result, "channelDescriptorValue"); - assert((client.pathTemplates.folderChannelDescriptorPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('folderChannelDescriptor', () => { + const fakePath = '/rendered/path/folderChannelDescriptor'; + const expectedParameters = { + folder: 'folderValue', + channel_descriptor: 'channelDescriptorValue', + }; + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.folderChannelDescriptorPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderChannelDescriptorPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderChannelDescriptorPath', () => { + const result = client.folderChannelDescriptorPath( + 'folderValue', + 'channelDescriptorValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.folderChannelDescriptorPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderChannelDescriptorName', () => { + const result = + client.matchFolderFromFolderChannelDescriptorName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + ( + client.pathTemplates.folderChannelDescriptorPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchChannelDescriptorFromFolderChannelDescriptorName', () => { + const result = + client.matchChannelDescriptorFromFolderChannelDescriptorName( + fakePath, + ); + assert.strictEqual(result, 'channelDescriptorValue'); + assert( + ( + client.pathTemplates.folderChannelDescriptorPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('folderGroup', () => { - const fakePath = "/rendered/path/folderGroup"; - const expectedParameters = { - folder: "folderValue", - group: "groupValue", - }; - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.folderGroupPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderGroupPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderGroupPath', () => { - const result = client.folderGroupPath("folderValue", "groupValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderGroupPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderGroupName', () => { - const result = client.matchFolderFromFolderGroupName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderGroupPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchGroupFromFolderGroupName', () => { - const result = client.matchGroupFromFolderGroupName(fakePath); - assert.strictEqual(result, "groupValue"); - assert((client.pathTemplates.folderGroupPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('folderGroup', () => { + const fakePath = '/rendered/path/folderGroup'; + const expectedParameters = { + folder: 'folderValue', + group: 'groupValue', + }; + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.folderGroupPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderGroupPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderGroupPath', () => { + const result = client.folderGroupPath('folderValue', 'groupValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.folderGroupPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderGroupName', () => { + const result = client.matchFolderFromFolderGroupName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + (client.pathTemplates.folderGroupPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchGroupFromFolderGroupName', () => { + const result = client.matchGroupFromFolderGroupName(fakePath); + assert.strictEqual(result, 'groupValue'); + assert( + (client.pathTemplates.folderGroupPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('folderMetricDescriptor', () => { - const fakePath = "/rendered/path/folderMetricDescriptor"; - const expectedParameters = { - folder: "folderValue", - metric_descriptor: "metricDescriptorValue", - }; - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.folderMetricDescriptorPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderMetricDescriptorPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderMetricDescriptorPath', () => { - const result = client.folderMetricDescriptorPath("folderValue", "metricDescriptorValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderMetricDescriptorPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderMetricDescriptorName', () => { - const result = client.matchFolderFromFolderMetricDescriptorName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderMetricDescriptorPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchMetricDescriptorFromFolderMetricDescriptorName', () => { - const result = client.matchMetricDescriptorFromFolderMetricDescriptorName(fakePath); - assert.strictEqual(result, "metricDescriptorValue"); - assert((client.pathTemplates.folderMetricDescriptorPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('folderMetricDescriptor', () => { + const fakePath = '/rendered/path/folderMetricDescriptor'; + const expectedParameters = { + folder: 'folderValue', + metric_descriptor: 'metricDescriptorValue', + }; + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.folderMetricDescriptorPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderMetricDescriptorPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderMetricDescriptorPath', () => { + const result = client.folderMetricDescriptorPath( + 'folderValue', + 'metricDescriptorValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.folderMetricDescriptorPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderMetricDescriptorName', () => { + const result = + client.matchFolderFromFolderMetricDescriptorName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + ( + client.pathTemplates.folderMetricDescriptorPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchMetricDescriptorFromFolderMetricDescriptorName', () => { + const result = + client.matchMetricDescriptorFromFolderMetricDescriptorName(fakePath); + assert.strictEqual(result, 'metricDescriptorValue'); + assert( + ( + client.pathTemplates.folderMetricDescriptorPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('folderMonitoredResourceDescriptor', () => { - const fakePath = "/rendered/path/folderMonitoredResourceDescriptor"; - const expectedParameters = { - folder: "folderValue", - monitored_resource_descriptor: "monitoredResourceDescriptorValue", - }; - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.folderMonitoredResourceDescriptorPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderMonitoredResourceDescriptorPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderMonitoredResourceDescriptorPath', () => { - const result = client.folderMonitoredResourceDescriptorPath("folderValue", "monitoredResourceDescriptorValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderMonitoredResourceDescriptorPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderMonitoredResourceDescriptorName', () => { - const result = client.matchFolderFromFolderMonitoredResourceDescriptorName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderMonitoredResourceDescriptorPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchMonitoredResourceDescriptorFromFolderMonitoredResourceDescriptorName', () => { - const result = client.matchMonitoredResourceDescriptorFromFolderMonitoredResourceDescriptorName(fakePath); - assert.strictEqual(result, "monitoredResourceDescriptorValue"); - assert((client.pathTemplates.folderMonitoredResourceDescriptorPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('folderMonitoredResourceDescriptor', () => { + const fakePath = '/rendered/path/folderMonitoredResourceDescriptor'; + const expectedParameters = { + folder: 'folderValue', + monitored_resource_descriptor: 'monitoredResourceDescriptorValue', + }; + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.folderMonitoredResourceDescriptorPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.folderMonitoredResourceDescriptorPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('folderMonitoredResourceDescriptorPath', () => { + const result = client.folderMonitoredResourceDescriptorPath( + 'folderValue', + 'monitoredResourceDescriptorValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.folderMonitoredResourceDescriptorPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderMonitoredResourceDescriptorName', () => { + const result = + client.matchFolderFromFolderMonitoredResourceDescriptorName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + ( + client.pathTemplates.folderMonitoredResourceDescriptorPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchMonitoredResourceDescriptorFromFolderMonitoredResourceDescriptorName', () => { + const result = + client.matchMonitoredResourceDescriptorFromFolderMonitoredResourceDescriptorName( + fakePath, + ); + assert.strictEqual(result, 'monitoredResourceDescriptorValue'); + assert( + ( + client.pathTemplates.folderMonitoredResourceDescriptorPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('folderNotificationChannel', () => { - const fakePath = "/rendered/path/folderNotificationChannel"; - const expectedParameters = { - folder: "folderValue", - notification_channel: "notificationChannelValue", - }; - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.folderNotificationChannelPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderNotificationChannelPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderNotificationChannelPath', () => { - const result = client.folderNotificationChannelPath("folderValue", "notificationChannelValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderNotificationChannelPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderNotificationChannelName', () => { - const result = client.matchFolderFromFolderNotificationChannelName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderNotificationChannelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchNotificationChannelFromFolderNotificationChannelName', () => { - const result = client.matchNotificationChannelFromFolderNotificationChannelName(fakePath); - assert.strictEqual(result, "notificationChannelValue"); - assert((client.pathTemplates.folderNotificationChannelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('folderNotificationChannel', () => { + const fakePath = '/rendered/path/folderNotificationChannel'; + const expectedParameters = { + folder: 'folderValue', + notification_channel: 'notificationChannelValue', + }; + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.folderNotificationChannelPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderNotificationChannelPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderNotificationChannelPath', () => { + const result = client.folderNotificationChannelPath( + 'folderValue', + 'notificationChannelValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.folderNotificationChannelPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderNotificationChannelName', () => { + const result = + client.matchFolderFromFolderNotificationChannelName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + ( + client.pathTemplates.folderNotificationChannelPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchNotificationChannelFromFolderNotificationChannelName', () => { + const result = + client.matchNotificationChannelFromFolderNotificationChannelName( + fakePath, + ); + assert.strictEqual(result, 'notificationChannelValue'); + assert( + ( + client.pathTemplates.folderNotificationChannelPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('folderService', () => { - const fakePath = "/rendered/path/folderService"; - const expectedParameters = { - folder: "folderValue", - service: "serviceValue", - }; - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.folderServicePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderServicePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderServicePath', () => { - const result = client.folderServicePath("folderValue", "serviceValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderServicePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderServiceName', () => { - const result = client.matchFolderFromFolderServiceName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderServicePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServiceFromFolderServiceName', () => { - const result = client.matchServiceFromFolderServiceName(fakePath); - assert.strictEqual(result, "serviceValue"); - assert((client.pathTemplates.folderServicePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('folderService', () => { + const fakePath = '/rendered/path/folderService'; + const expectedParameters = { + folder: 'folderValue', + service: 'serviceValue', + }; + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.folderServicePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderServicePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderServicePath', () => { + const result = client.folderServicePath('folderValue', 'serviceValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.folderServicePathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderServiceName', () => { + const result = client.matchFolderFromFolderServiceName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + (client.pathTemplates.folderServicePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServiceFromFolderServiceName', () => { + const result = client.matchServiceFromFolderServiceName(fakePath); + assert.strictEqual(result, 'serviceValue'); + assert( + (client.pathTemplates.folderServicePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('folderServiceServiceLevelObjective', () => { - const fakePath = "/rendered/path/folderServiceServiceLevelObjective"; - const expectedParameters = { - folder: "folderValue", - service: "serviceValue", - service_level_objective: "serviceLevelObjectiveValue", - }; - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderServiceServiceLevelObjectivePath', () => { - const result = client.folderServiceServiceLevelObjectivePath("folderValue", "serviceValue", "serviceLevelObjectiveValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderServiceServiceLevelObjectiveName', () => { - const result = client.matchFolderFromFolderServiceServiceLevelObjectiveName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServiceFromFolderServiceServiceLevelObjectiveName', () => { - const result = client.matchServiceFromFolderServiceServiceLevelObjectiveName(fakePath); - assert.strictEqual(result, "serviceValue"); - assert((client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServiceLevelObjectiveFromFolderServiceServiceLevelObjectiveName', () => { - const result = client.matchServiceLevelObjectiveFromFolderServiceServiceLevelObjectiveName(fakePath); - assert.strictEqual(result, "serviceLevelObjectiveValue"); - assert((client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('folderServiceServiceLevelObjective', () => { + const fakePath = '/rendered/path/folderServiceServiceLevelObjective'; + const expectedParameters = { + folder: 'folderValue', + service: 'serviceValue', + service_level_objective: 'serviceLevelObjectiveValue', + }; + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('folderServiceServiceLevelObjectivePath', () => { + const result = client.folderServiceServiceLevelObjectivePath( + 'folderValue', + 'serviceValue', + 'serviceLevelObjectiveValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderServiceServiceLevelObjectiveName', () => { + const result = + client.matchFolderFromFolderServiceServiceLevelObjectiveName( + fakePath, + ); + assert.strictEqual(result, 'folderValue'); + assert( + ( + client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServiceFromFolderServiceServiceLevelObjectiveName', () => { + const result = + client.matchServiceFromFolderServiceServiceLevelObjectiveName( + fakePath, + ); + assert.strictEqual(result, 'serviceValue'); + assert( + ( + client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServiceLevelObjectiveFromFolderServiceServiceLevelObjectiveName', () => { + const result = + client.matchServiceLevelObjectiveFromFolderServiceServiceLevelObjectiveName( + fakePath, + ); + assert.strictEqual(result, 'serviceLevelObjectiveValue'); + assert( + ( + client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('folderUptimeCheckConfig', () => { - const fakePath = "/rendered/path/folderUptimeCheckConfig"; - const expectedParameters = { - folder: "folderValue", - uptime_check_config: "uptimeCheckConfigValue", - }; - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.folderUptimeCheckConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderUptimeCheckConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderUptimeCheckConfigPath', () => { - const result = client.folderUptimeCheckConfigPath("folderValue", "uptimeCheckConfigValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderUptimeCheckConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderUptimeCheckConfigName', () => { - const result = client.matchFolderFromFolderUptimeCheckConfigName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderUptimeCheckConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchUptimeCheckConfigFromFolderUptimeCheckConfigName', () => { - const result = client.matchUptimeCheckConfigFromFolderUptimeCheckConfigName(fakePath); - assert.strictEqual(result, "uptimeCheckConfigValue"); - assert((client.pathTemplates.folderUptimeCheckConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('folderUptimeCheckConfig', () => { + const fakePath = '/rendered/path/folderUptimeCheckConfig'; + const expectedParameters = { + folder: 'folderValue', + uptime_check_config: 'uptimeCheckConfigValue', + }; + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.folderUptimeCheckConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderUptimeCheckConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderUptimeCheckConfigPath', () => { + const result = client.folderUptimeCheckConfigPath( + 'folderValue', + 'uptimeCheckConfigValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.folderUptimeCheckConfigPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderUptimeCheckConfigName', () => { + const result = + client.matchFolderFromFolderUptimeCheckConfigName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + ( + client.pathTemplates.folderUptimeCheckConfigPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchUptimeCheckConfigFromFolderUptimeCheckConfigName', () => { + const result = + client.matchUptimeCheckConfigFromFolderUptimeCheckConfigName( + fakePath, + ); + assert.strictEqual(result, 'uptimeCheckConfigValue'); + assert( + ( + client.pathTemplates.folderUptimeCheckConfigPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('organizationAlertPolicy', () => { - const fakePath = "/rendered/path/organizationAlertPolicy"; - const expectedParameters = { - organization: "organizationValue", - alert_policy: "alertPolicyValue", - }; - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.organizationAlertPolicyPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationAlertPolicyPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationAlertPolicyPath', () => { - const result = client.organizationAlertPolicyPath("organizationValue", "alertPolicyValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationAlertPolicyPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationAlertPolicyName', () => { - const result = client.matchOrganizationFromOrganizationAlertPolicyName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationAlertPolicyPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchAlertPolicyFromOrganizationAlertPolicyName', () => { - const result = client.matchAlertPolicyFromOrganizationAlertPolicyName(fakePath); - assert.strictEqual(result, "alertPolicyValue"); - assert((client.pathTemplates.organizationAlertPolicyPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('organizationAlertPolicy', () => { + const fakePath = '/rendered/path/organizationAlertPolicy'; + const expectedParameters = { + organization: 'organizationValue', + alert_policy: 'alertPolicyValue', + }; + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.organizationAlertPolicyPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.organizationAlertPolicyPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('organizationAlertPolicyPath', () => { + const result = client.organizationAlertPolicyPath( + 'organizationValue', + 'alertPolicyValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationAlertPolicyPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationAlertPolicyName', () => { + const result = + client.matchOrganizationFromOrganizationAlertPolicyName(fakePath); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationAlertPolicyPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchAlertPolicyFromOrganizationAlertPolicyName', () => { + const result = + client.matchAlertPolicyFromOrganizationAlertPolicyName(fakePath); + assert.strictEqual(result, 'alertPolicyValue'); + assert( + ( + client.pathTemplates.organizationAlertPolicyPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('organizationAlertPolicyCondition', () => { - const fakePath = "/rendered/path/organizationAlertPolicyCondition"; - const expectedParameters = { - organization: "organizationValue", - alert_policy: "alertPolicyValue", - condition: "conditionValue", - }; - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.organizationAlertPolicyConditionPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationAlertPolicyConditionPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationAlertPolicyConditionPath', () => { - const result = client.organizationAlertPolicyConditionPath("organizationValue", "alertPolicyValue", "conditionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationAlertPolicyConditionPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationAlertPolicyConditionName', () => { - const result = client.matchOrganizationFromOrganizationAlertPolicyConditionName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationAlertPolicyConditionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchAlertPolicyFromOrganizationAlertPolicyConditionName', () => { - const result = client.matchAlertPolicyFromOrganizationAlertPolicyConditionName(fakePath); - assert.strictEqual(result, "alertPolicyValue"); - assert((client.pathTemplates.organizationAlertPolicyConditionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchConditionFromOrganizationAlertPolicyConditionName', () => { - const result = client.matchConditionFromOrganizationAlertPolicyConditionName(fakePath); - assert.strictEqual(result, "conditionValue"); - assert((client.pathTemplates.organizationAlertPolicyConditionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('organizationAlertPolicyCondition', () => { + const fakePath = '/rendered/path/organizationAlertPolicyCondition'; + const expectedParameters = { + organization: 'organizationValue', + alert_policy: 'alertPolicyValue', + condition: 'conditionValue', + }; + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.organizationAlertPolicyConditionPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.organizationAlertPolicyConditionPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('organizationAlertPolicyConditionPath', () => { + const result = client.organizationAlertPolicyConditionPath( + 'organizationValue', + 'alertPolicyValue', + 'conditionValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationAlertPolicyConditionPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationAlertPolicyConditionName', () => { + const result = + client.matchOrganizationFromOrganizationAlertPolicyConditionName( + fakePath, + ); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationAlertPolicyConditionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchAlertPolicyFromOrganizationAlertPolicyConditionName', () => { + const result = + client.matchAlertPolicyFromOrganizationAlertPolicyConditionName( + fakePath, + ); + assert.strictEqual(result, 'alertPolicyValue'); + assert( + ( + client.pathTemplates.organizationAlertPolicyConditionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchConditionFromOrganizationAlertPolicyConditionName', () => { + const result = + client.matchConditionFromOrganizationAlertPolicyConditionName( + fakePath, + ); + assert.strictEqual(result, 'conditionValue'); + assert( + ( + client.pathTemplates.organizationAlertPolicyConditionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('organizationChannelDescriptor', () => { - const fakePath = "/rendered/path/organizationChannelDescriptor"; - const expectedParameters = { - organization: "organizationValue", - channel_descriptor: "channelDescriptorValue", - }; - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.organizationChannelDescriptorPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationChannelDescriptorPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationChannelDescriptorPath', () => { - const result = client.organizationChannelDescriptorPath("organizationValue", "channelDescriptorValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationChannelDescriptorPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationChannelDescriptorName', () => { - const result = client.matchOrganizationFromOrganizationChannelDescriptorName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationChannelDescriptorPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchChannelDescriptorFromOrganizationChannelDescriptorName', () => { - const result = client.matchChannelDescriptorFromOrganizationChannelDescriptorName(fakePath); - assert.strictEqual(result, "channelDescriptorValue"); - assert((client.pathTemplates.organizationChannelDescriptorPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('organizationChannelDescriptor', () => { + const fakePath = '/rendered/path/organizationChannelDescriptor'; + const expectedParameters = { + organization: 'organizationValue', + channel_descriptor: 'channelDescriptorValue', + }; + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.organizationChannelDescriptorPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.organizationChannelDescriptorPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('organizationChannelDescriptorPath', () => { + const result = client.organizationChannelDescriptorPath( + 'organizationValue', + 'channelDescriptorValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationChannelDescriptorPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationChannelDescriptorName', () => { + const result = + client.matchOrganizationFromOrganizationChannelDescriptorName( + fakePath, + ); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationChannelDescriptorPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchChannelDescriptorFromOrganizationChannelDescriptorName', () => { + const result = + client.matchChannelDescriptorFromOrganizationChannelDescriptorName( + fakePath, + ); + assert.strictEqual(result, 'channelDescriptorValue'); + assert( + ( + client.pathTemplates.organizationChannelDescriptorPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('organizationGroup', () => { - const fakePath = "/rendered/path/organizationGroup"; - const expectedParameters = { - organization: "organizationValue", - group: "groupValue", - }; - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.organizationGroupPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationGroupPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationGroupPath', () => { - const result = client.organizationGroupPath("organizationValue", "groupValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationGroupPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationGroupName', () => { - const result = client.matchOrganizationFromOrganizationGroupName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationGroupPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchGroupFromOrganizationGroupName', () => { - const result = client.matchGroupFromOrganizationGroupName(fakePath); - assert.strictEqual(result, "groupValue"); - assert((client.pathTemplates.organizationGroupPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('organizationGroup', () => { + const fakePath = '/rendered/path/organizationGroup'; + const expectedParameters = { + organization: 'organizationValue', + group: 'groupValue', + }; + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.organizationGroupPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.organizationGroupPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('organizationGroupPath', () => { + const result = client.organizationGroupPath( + 'organizationValue', + 'groupValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationGroupPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationGroupName', () => { + const result = + client.matchOrganizationFromOrganizationGroupName(fakePath); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationGroupPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchGroupFromOrganizationGroupName', () => { + const result = client.matchGroupFromOrganizationGroupName(fakePath); + assert.strictEqual(result, 'groupValue'); + assert( + ( + client.pathTemplates.organizationGroupPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('organizationMetricDescriptor', () => { - const fakePath = "/rendered/path/organizationMetricDescriptor"; - const expectedParameters = { - organization: "organizationValue", - metric_descriptor: "metricDescriptorValue", - }; - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.organizationMetricDescriptorPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationMetricDescriptorPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationMetricDescriptorPath', () => { - const result = client.organizationMetricDescriptorPath("organizationValue", "metricDescriptorValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationMetricDescriptorPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationMetricDescriptorName', () => { - const result = client.matchOrganizationFromOrganizationMetricDescriptorName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationMetricDescriptorPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchMetricDescriptorFromOrganizationMetricDescriptorName', () => { - const result = client.matchMetricDescriptorFromOrganizationMetricDescriptorName(fakePath); - assert.strictEqual(result, "metricDescriptorValue"); - assert((client.pathTemplates.organizationMetricDescriptorPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('organizationMetricDescriptor', () => { + const fakePath = '/rendered/path/organizationMetricDescriptor'; + const expectedParameters = { + organization: 'organizationValue', + metric_descriptor: 'metricDescriptorValue', + }; + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.organizationMetricDescriptorPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.organizationMetricDescriptorPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('organizationMetricDescriptorPath', () => { + const result = client.organizationMetricDescriptorPath( + 'organizationValue', + 'metricDescriptorValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationMetricDescriptorPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationMetricDescriptorName', () => { + const result = + client.matchOrganizationFromOrganizationMetricDescriptorName( + fakePath, + ); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationMetricDescriptorPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchMetricDescriptorFromOrganizationMetricDescriptorName', () => { + const result = + client.matchMetricDescriptorFromOrganizationMetricDescriptorName( + fakePath, + ); + assert.strictEqual(result, 'metricDescriptorValue'); + assert( + ( + client.pathTemplates.organizationMetricDescriptorPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('organizationMonitoredResourceDescriptor', () => { - const fakePath = "/rendered/path/organizationMonitoredResourceDescriptor"; - const expectedParameters = { - organization: "organizationValue", - monitored_resource_descriptor: "monitoredResourceDescriptorValue", - }; - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.organizationMonitoredResourceDescriptorPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationMonitoredResourceDescriptorPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationMonitoredResourceDescriptorPath', () => { - const result = client.organizationMonitoredResourceDescriptorPath("organizationValue", "monitoredResourceDescriptorValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationMonitoredResourceDescriptorPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationMonitoredResourceDescriptorName', () => { - const result = client.matchOrganizationFromOrganizationMonitoredResourceDescriptorName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationMonitoredResourceDescriptorPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchMonitoredResourceDescriptorFromOrganizationMonitoredResourceDescriptorName', () => { - const result = client.matchMonitoredResourceDescriptorFromOrganizationMonitoredResourceDescriptorName(fakePath); - assert.strictEqual(result, "monitoredResourceDescriptorValue"); - assert((client.pathTemplates.organizationMonitoredResourceDescriptorPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('organizationMonitoredResourceDescriptor', () => { + const fakePath = '/rendered/path/organizationMonitoredResourceDescriptor'; + const expectedParameters = { + organization: 'organizationValue', + monitored_resource_descriptor: 'monitoredResourceDescriptorValue', + }; + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.organizationMonitoredResourceDescriptorPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.organizationMonitoredResourceDescriptorPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('organizationMonitoredResourceDescriptorPath', () => { + const result = client.organizationMonitoredResourceDescriptorPath( + 'organizationValue', + 'monitoredResourceDescriptorValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates + .organizationMonitoredResourceDescriptorPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationMonitoredResourceDescriptorName', () => { + const result = + client.matchOrganizationFromOrganizationMonitoredResourceDescriptorName( + fakePath, + ); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates + .organizationMonitoredResourceDescriptorPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchMonitoredResourceDescriptorFromOrganizationMonitoredResourceDescriptorName', () => { + const result = + client.matchMonitoredResourceDescriptorFromOrganizationMonitoredResourceDescriptorName( + fakePath, + ); + assert.strictEqual(result, 'monitoredResourceDescriptorValue'); + assert( + ( + client.pathTemplates + .organizationMonitoredResourceDescriptorPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('organizationNotificationChannel', () => { - const fakePath = "/rendered/path/organizationNotificationChannel"; - const expectedParameters = { - organization: "organizationValue", - notification_channel: "notificationChannelValue", - }; - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.organizationNotificationChannelPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationNotificationChannelPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationNotificationChannelPath', () => { - const result = client.organizationNotificationChannelPath("organizationValue", "notificationChannelValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationNotificationChannelPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationNotificationChannelName', () => { - const result = client.matchOrganizationFromOrganizationNotificationChannelName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationNotificationChannelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchNotificationChannelFromOrganizationNotificationChannelName', () => { - const result = client.matchNotificationChannelFromOrganizationNotificationChannelName(fakePath); - assert.strictEqual(result, "notificationChannelValue"); - assert((client.pathTemplates.organizationNotificationChannelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('organizationNotificationChannel', () => { + const fakePath = '/rendered/path/organizationNotificationChannel'; + const expectedParameters = { + organization: 'organizationValue', + notification_channel: 'notificationChannelValue', + }; + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.organizationNotificationChannelPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.organizationNotificationChannelPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('organizationNotificationChannelPath', () => { + const result = client.organizationNotificationChannelPath( + 'organizationValue', + 'notificationChannelValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationNotificationChannelPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationNotificationChannelName', () => { + const result = + client.matchOrganizationFromOrganizationNotificationChannelName( + fakePath, + ); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationNotificationChannelPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchNotificationChannelFromOrganizationNotificationChannelName', () => { + const result = + client.matchNotificationChannelFromOrganizationNotificationChannelName( + fakePath, + ); + assert.strictEqual(result, 'notificationChannelValue'); + assert( + ( + client.pathTemplates.organizationNotificationChannelPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('organizationService', () => { - const fakePath = "/rendered/path/organizationService"; - const expectedParameters = { - organization: "organizationValue", - service: "serviceValue", - }; - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.organizationServicePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationServicePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationServicePath', () => { - const result = client.organizationServicePath("organizationValue", "serviceValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationServicePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationServiceName', () => { - const result = client.matchOrganizationFromOrganizationServiceName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationServicePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServiceFromOrganizationServiceName', () => { - const result = client.matchServiceFromOrganizationServiceName(fakePath); - assert.strictEqual(result, "serviceValue"); - assert((client.pathTemplates.organizationServicePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('organizationService', () => { + const fakePath = '/rendered/path/organizationService'; + const expectedParameters = { + organization: 'organizationValue', + service: 'serviceValue', + }; + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.organizationServicePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.organizationServicePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('organizationServicePath', () => { + const result = client.organizationServicePath( + 'organizationValue', + 'serviceValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationServicePathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationServiceName', () => { + const result = + client.matchOrganizationFromOrganizationServiceName(fakePath); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationServicePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServiceFromOrganizationServiceName', () => { + const result = client.matchServiceFromOrganizationServiceName(fakePath); + assert.strictEqual(result, 'serviceValue'); + assert( + ( + client.pathTemplates.organizationServicePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('organizationServiceServiceLevelObjective', () => { - const fakePath = "/rendered/path/organizationServiceServiceLevelObjective"; - const expectedParameters = { - organization: "organizationValue", - service: "serviceValue", - service_level_objective: "serviceLevelObjectiveValue", - }; - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationServiceServiceLevelObjectivePath', () => { - const result = client.organizationServiceServiceLevelObjectivePath("organizationValue", "serviceValue", "serviceLevelObjectiveValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationServiceServiceLevelObjectiveName', () => { - const result = client.matchOrganizationFromOrganizationServiceServiceLevelObjectiveName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServiceFromOrganizationServiceServiceLevelObjectiveName', () => { - const result = client.matchServiceFromOrganizationServiceServiceLevelObjectiveName(fakePath); - assert.strictEqual(result, "serviceValue"); - assert((client.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServiceLevelObjectiveFromOrganizationServiceServiceLevelObjectiveName', () => { - const result = client.matchServiceLevelObjectiveFromOrganizationServiceServiceLevelObjectiveName(fakePath); - assert.strictEqual(result, "serviceLevelObjectiveValue"); - assert((client.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('organizationServiceServiceLevelObjective', () => { + const fakePath = + '/rendered/path/organizationServiceServiceLevelObjective'; + const expectedParameters = { + organization: 'organizationValue', + service: 'serviceValue', + service_level_objective: 'serviceLevelObjectiveValue', + }; + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('organizationServiceServiceLevelObjectivePath', () => { + const result = client.organizationServiceServiceLevelObjectivePath( + 'organizationValue', + 'serviceValue', + 'serviceLevelObjectiveValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates + .organizationServiceServiceLevelObjectivePathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationServiceServiceLevelObjectiveName', () => { + const result = + client.matchOrganizationFromOrganizationServiceServiceLevelObjectiveName( + fakePath, + ); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates + .organizationServiceServiceLevelObjectivePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServiceFromOrganizationServiceServiceLevelObjectiveName', () => { + const result = + client.matchServiceFromOrganizationServiceServiceLevelObjectiveName( + fakePath, + ); + assert.strictEqual(result, 'serviceValue'); + assert( + ( + client.pathTemplates + .organizationServiceServiceLevelObjectivePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServiceLevelObjectiveFromOrganizationServiceServiceLevelObjectiveName', () => { + const result = + client.matchServiceLevelObjectiveFromOrganizationServiceServiceLevelObjectiveName( + fakePath, + ); + assert.strictEqual(result, 'serviceLevelObjectiveValue'); + assert( + ( + client.pathTemplates + .organizationServiceServiceLevelObjectivePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('organizationUptimeCheckConfig', () => { - const fakePath = "/rendered/path/organizationUptimeCheckConfig"; - const expectedParameters = { - organization: "organizationValue", - uptime_check_config: "uptimeCheckConfigValue", - }; - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.organizationUptimeCheckConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationUptimeCheckConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationUptimeCheckConfigPath', () => { - const result = client.organizationUptimeCheckConfigPath("organizationValue", "uptimeCheckConfigValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationUptimeCheckConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationUptimeCheckConfigName', () => { - const result = client.matchOrganizationFromOrganizationUptimeCheckConfigName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationUptimeCheckConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchUptimeCheckConfigFromOrganizationUptimeCheckConfigName', () => { - const result = client.matchUptimeCheckConfigFromOrganizationUptimeCheckConfigName(fakePath); - assert.strictEqual(result, "uptimeCheckConfigValue"); - assert((client.pathTemplates.organizationUptimeCheckConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('organizationUptimeCheckConfig', () => { + const fakePath = '/rendered/path/organizationUptimeCheckConfig'; + const expectedParameters = { + organization: 'organizationValue', + uptime_check_config: 'uptimeCheckConfigValue', + }; + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.organizationUptimeCheckConfigPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.organizationUptimeCheckConfigPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('organizationUptimeCheckConfigPath', () => { + const result = client.organizationUptimeCheckConfigPath( + 'organizationValue', + 'uptimeCheckConfigValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationUptimeCheckConfigPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationUptimeCheckConfigName', () => { + const result = + client.matchOrganizationFromOrganizationUptimeCheckConfigName( + fakePath, + ); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationUptimeCheckConfigPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchUptimeCheckConfigFromOrganizationUptimeCheckConfigName', () => { + const result = + client.matchUptimeCheckConfigFromOrganizationUptimeCheckConfigName( + fakePath, + ); + assert.strictEqual(result, 'uptimeCheckConfigValue'); + assert( + ( + client.pathTemplates.organizationUptimeCheckConfigPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectAlertPolicy', () => { - const fakePath = "/rendered/path/projectAlertPolicy"; - const expectedParameters = { - project: "projectValue", - alert_policy: "alertPolicyValue", - }; - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.projectAlertPolicyPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectAlertPolicyPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectAlertPolicyPath', () => { - const result = client.projectAlertPolicyPath("projectValue", "alertPolicyValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectAlertPolicyPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectAlertPolicyName', () => { - const result = client.matchProjectFromProjectAlertPolicyName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectAlertPolicyPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchAlertPolicyFromProjectAlertPolicyName', () => { - const result = client.matchAlertPolicyFromProjectAlertPolicyName(fakePath); - assert.strictEqual(result, "alertPolicyValue"); - assert((client.pathTemplates.projectAlertPolicyPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectAlertPolicy', () => { + const fakePath = '/rendered/path/projectAlertPolicy'; + const expectedParameters = { + project: 'projectValue', + alert_policy: 'alertPolicyValue', + }; + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.projectAlertPolicyPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectAlertPolicyPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectAlertPolicyPath', () => { + const result = client.projectAlertPolicyPath( + 'projectValue', + 'alertPolicyValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.projectAlertPolicyPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectAlertPolicyName', () => { + const result = client.matchProjectFromProjectAlertPolicyName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.projectAlertPolicyPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchAlertPolicyFromProjectAlertPolicyName', () => { + const result = + client.matchAlertPolicyFromProjectAlertPolicyName(fakePath); + assert.strictEqual(result, 'alertPolicyValue'); + assert( + ( + client.pathTemplates.projectAlertPolicyPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectAlertPolicyCondition', () => { - const fakePath = "/rendered/path/projectAlertPolicyCondition"; - const expectedParameters = { - project: "projectValue", - alert_policy: "alertPolicyValue", - condition: "conditionValue", - }; - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.projectAlertPolicyConditionPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectAlertPolicyConditionPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectAlertPolicyConditionPath', () => { - const result = client.projectAlertPolicyConditionPath("projectValue", "alertPolicyValue", "conditionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectAlertPolicyConditionPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectAlertPolicyConditionName', () => { - const result = client.matchProjectFromProjectAlertPolicyConditionName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectAlertPolicyConditionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchAlertPolicyFromProjectAlertPolicyConditionName', () => { - const result = client.matchAlertPolicyFromProjectAlertPolicyConditionName(fakePath); - assert.strictEqual(result, "alertPolicyValue"); - assert((client.pathTemplates.projectAlertPolicyConditionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchConditionFromProjectAlertPolicyConditionName', () => { - const result = client.matchConditionFromProjectAlertPolicyConditionName(fakePath); - assert.strictEqual(result, "conditionValue"); - assert((client.pathTemplates.projectAlertPolicyConditionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectAlertPolicyCondition', () => { + const fakePath = '/rendered/path/projectAlertPolicyCondition'; + const expectedParameters = { + project: 'projectValue', + alert_policy: 'alertPolicyValue', + condition: 'conditionValue', + }; + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.projectAlertPolicyConditionPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.projectAlertPolicyConditionPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectAlertPolicyConditionPath', () => { + const result = client.projectAlertPolicyConditionPath( + 'projectValue', + 'alertPolicyValue', + 'conditionValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.projectAlertPolicyConditionPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectAlertPolicyConditionName', () => { + const result = + client.matchProjectFromProjectAlertPolicyConditionName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.projectAlertPolicyConditionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchAlertPolicyFromProjectAlertPolicyConditionName', () => { + const result = + client.matchAlertPolicyFromProjectAlertPolicyConditionName(fakePath); + assert.strictEqual(result, 'alertPolicyValue'); + assert( + ( + client.pathTemplates.projectAlertPolicyConditionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchConditionFromProjectAlertPolicyConditionName', () => { + const result = + client.matchConditionFromProjectAlertPolicyConditionName(fakePath); + assert.strictEqual(result, 'conditionValue'); + assert( + ( + client.pathTemplates.projectAlertPolicyConditionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectChannelDescriptor', () => { - const fakePath = "/rendered/path/projectChannelDescriptor"; - const expectedParameters = { - project: "projectValue", - channel_descriptor: "channelDescriptorValue", - }; - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.projectChannelDescriptorPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectChannelDescriptorPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectChannelDescriptorPath', () => { - const result = client.projectChannelDescriptorPath("projectValue", "channelDescriptorValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectChannelDescriptorPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectChannelDescriptorName', () => { - const result = client.matchProjectFromProjectChannelDescriptorName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectChannelDescriptorPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchChannelDescriptorFromProjectChannelDescriptorName', () => { - const result = client.matchChannelDescriptorFromProjectChannelDescriptorName(fakePath); - assert.strictEqual(result, "channelDescriptorValue"); - assert((client.pathTemplates.projectChannelDescriptorPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectChannelDescriptor', () => { + const fakePath = '/rendered/path/projectChannelDescriptor'; + const expectedParameters = { + project: 'projectValue', + channel_descriptor: 'channelDescriptorValue', + }; + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.projectChannelDescriptorPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectChannelDescriptorPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectChannelDescriptorPath', () => { + const result = client.projectChannelDescriptorPath( + 'projectValue', + 'channelDescriptorValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.projectChannelDescriptorPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectChannelDescriptorName', () => { + const result = + client.matchProjectFromProjectChannelDescriptorName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.projectChannelDescriptorPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchChannelDescriptorFromProjectChannelDescriptorName', () => { + const result = + client.matchChannelDescriptorFromProjectChannelDescriptorName( + fakePath, + ); + assert.strictEqual(result, 'channelDescriptorValue'); + assert( + ( + client.pathTemplates.projectChannelDescriptorPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectGroup', () => { - const fakePath = "/rendered/path/projectGroup"; - const expectedParameters = { - project: "projectValue", - group: "groupValue", - }; - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.projectGroupPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectGroupPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectGroupPath', () => { - const result = client.projectGroupPath("projectValue", "groupValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectGroupPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectGroupName', () => { - const result = client.matchProjectFromProjectGroupName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectGroupPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchGroupFromProjectGroupName', () => { - const result = client.matchGroupFromProjectGroupName(fakePath); - assert.strictEqual(result, "groupValue"); - assert((client.pathTemplates.projectGroupPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectGroup', () => { + const fakePath = '/rendered/path/projectGroup'; + const expectedParameters = { + project: 'projectValue', + group: 'groupValue', + }; + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.projectGroupPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectGroupPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectGroupPath', () => { + const result = client.projectGroupPath('projectValue', 'groupValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.projectGroupPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectGroupName', () => { + const result = client.matchProjectFromProjectGroupName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.projectGroupPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchGroupFromProjectGroupName', () => { + const result = client.matchGroupFromProjectGroupName(fakePath); + assert.strictEqual(result, 'groupValue'); + assert( + (client.pathTemplates.projectGroupPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectMetricDescriptor', () => { - const fakePath = "/rendered/path/projectMetricDescriptor"; - const expectedParameters = { - project: "projectValue", - metric_descriptor: "metricDescriptorValue", - }; - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.projectMetricDescriptorPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectMetricDescriptorPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectMetricDescriptorPath', () => { - const result = client.projectMetricDescriptorPath("projectValue", "metricDescriptorValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectMetricDescriptorPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectMetricDescriptorName', () => { - const result = client.matchProjectFromProjectMetricDescriptorName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectMetricDescriptorPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchMetricDescriptorFromProjectMetricDescriptorName', () => { - const result = client.matchMetricDescriptorFromProjectMetricDescriptorName(fakePath); - assert.strictEqual(result, "metricDescriptorValue"); - assert((client.pathTemplates.projectMetricDescriptorPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectMetricDescriptor', () => { + const fakePath = '/rendered/path/projectMetricDescriptor'; + const expectedParameters = { + project: 'projectValue', + metric_descriptor: 'metricDescriptorValue', + }; + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.projectMetricDescriptorPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectMetricDescriptorPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectMetricDescriptorPath', () => { + const result = client.projectMetricDescriptorPath( + 'projectValue', + 'metricDescriptorValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.projectMetricDescriptorPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectMetricDescriptorName', () => { + const result = + client.matchProjectFromProjectMetricDescriptorName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.projectMetricDescriptorPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchMetricDescriptorFromProjectMetricDescriptorName', () => { + const result = + client.matchMetricDescriptorFromProjectMetricDescriptorName(fakePath); + assert.strictEqual(result, 'metricDescriptorValue'); + assert( + ( + client.pathTemplates.projectMetricDescriptorPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectMonitoredResourceDescriptor', () => { - const fakePath = "/rendered/path/projectMonitoredResourceDescriptor"; - const expectedParameters = { - project: "projectValue", - monitored_resource_descriptor: "monitoredResourceDescriptorValue", - }; - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.projectMonitoredResourceDescriptorPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectMonitoredResourceDescriptorPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectMonitoredResourceDescriptorPath', () => { - const result = client.projectMonitoredResourceDescriptorPath("projectValue", "monitoredResourceDescriptorValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectMonitoredResourceDescriptorPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectMonitoredResourceDescriptorName', () => { - const result = client.matchProjectFromProjectMonitoredResourceDescriptorName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectMonitoredResourceDescriptorPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchMonitoredResourceDescriptorFromProjectMonitoredResourceDescriptorName', () => { - const result = client.matchMonitoredResourceDescriptorFromProjectMonitoredResourceDescriptorName(fakePath); - assert.strictEqual(result, "monitoredResourceDescriptorValue"); - assert((client.pathTemplates.projectMonitoredResourceDescriptorPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectMonitoredResourceDescriptor', () => { + const fakePath = '/rendered/path/projectMonitoredResourceDescriptor'; + const expectedParameters = { + project: 'projectValue', + monitored_resource_descriptor: 'monitoredResourceDescriptorValue', + }; + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.projectMonitoredResourceDescriptorPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.projectMonitoredResourceDescriptorPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('projectMonitoredResourceDescriptorPath', () => { + const result = client.projectMonitoredResourceDescriptorPath( + 'projectValue', + 'monitoredResourceDescriptorValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.projectMonitoredResourceDescriptorPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectMonitoredResourceDescriptorName', () => { + const result = + client.matchProjectFromProjectMonitoredResourceDescriptorName( + fakePath, + ); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.projectMonitoredResourceDescriptorPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchMonitoredResourceDescriptorFromProjectMonitoredResourceDescriptorName', () => { + const result = + client.matchMonitoredResourceDescriptorFromProjectMonitoredResourceDescriptorName( + fakePath, + ); + assert.strictEqual(result, 'monitoredResourceDescriptorValue'); + assert( + ( + client.pathTemplates.projectMonitoredResourceDescriptorPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectNotificationChannel', () => { - const fakePath = "/rendered/path/projectNotificationChannel"; - const expectedParameters = { - project: "projectValue", - notification_channel: "notificationChannelValue", - }; - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.projectNotificationChannelPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectNotificationChannelPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectNotificationChannelPath', () => { - const result = client.projectNotificationChannelPath("projectValue", "notificationChannelValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectNotificationChannelPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectNotificationChannelName', () => { - const result = client.matchProjectFromProjectNotificationChannelName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectNotificationChannelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchNotificationChannelFromProjectNotificationChannelName', () => { - const result = client.matchNotificationChannelFromProjectNotificationChannelName(fakePath); - assert.strictEqual(result, "notificationChannelValue"); - assert((client.pathTemplates.projectNotificationChannelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectNotificationChannel', () => { + const fakePath = '/rendered/path/projectNotificationChannel'; + const expectedParameters = { + project: 'projectValue', + notification_channel: 'notificationChannelValue', + }; + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.projectNotificationChannelPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectNotificationChannelPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectNotificationChannelPath', () => { + const result = client.projectNotificationChannelPath( + 'projectValue', + 'notificationChannelValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.projectNotificationChannelPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectNotificationChannelName', () => { + const result = + client.matchProjectFromProjectNotificationChannelName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.projectNotificationChannelPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchNotificationChannelFromProjectNotificationChannelName', () => { + const result = + client.matchNotificationChannelFromProjectNotificationChannelName( + fakePath, + ); + assert.strictEqual(result, 'notificationChannelValue'); + assert( + ( + client.pathTemplates.projectNotificationChannelPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectService', () => { - const fakePath = "/rendered/path/projectService"; - const expectedParameters = { - project: "projectValue", - service: "serviceValue", - }; - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.projectServicePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectServicePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectServicePath', () => { - const result = client.projectServicePath("projectValue", "serviceValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectServicePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectServiceName', () => { - const result = client.matchProjectFromProjectServiceName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectServicePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServiceFromProjectServiceName', () => { - const result = client.matchServiceFromProjectServiceName(fakePath); - assert.strictEqual(result, "serviceValue"); - assert((client.pathTemplates.projectServicePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectService', () => { + const fakePath = '/rendered/path/projectService'; + const expectedParameters = { + project: 'projectValue', + service: 'serviceValue', + }; + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.projectServicePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectServicePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectServicePath', () => { + const result = client.projectServicePath( + 'projectValue', + 'serviceValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.projectServicePathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectServiceName', () => { + const result = client.matchProjectFromProjectServiceName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.projectServicePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServiceFromProjectServiceName', () => { + const result = client.matchServiceFromProjectServiceName(fakePath); + assert.strictEqual(result, 'serviceValue'); + assert( + (client.pathTemplates.projectServicePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectServiceServiceLevelObjective', () => { - const fakePath = "/rendered/path/projectServiceServiceLevelObjective"; - const expectedParameters = { - project: "projectValue", - service: "serviceValue", - service_level_objective: "serviceLevelObjectiveValue", - }; - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectServiceServiceLevelObjectivePath', () => { - const result = client.projectServiceServiceLevelObjectivePath("projectValue", "serviceValue", "serviceLevelObjectiveValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectServiceServiceLevelObjectiveName', () => { - const result = client.matchProjectFromProjectServiceServiceLevelObjectiveName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServiceFromProjectServiceServiceLevelObjectiveName', () => { - const result = client.matchServiceFromProjectServiceServiceLevelObjectiveName(fakePath); - assert.strictEqual(result, "serviceValue"); - assert((client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServiceLevelObjectiveFromProjectServiceServiceLevelObjectiveName', () => { - const result = client.matchServiceLevelObjectiveFromProjectServiceServiceLevelObjectiveName(fakePath); - assert.strictEqual(result, "serviceLevelObjectiveValue"); - assert((client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectServiceServiceLevelObjective', () => { + const fakePath = '/rendered/path/projectServiceServiceLevelObjective'; + const expectedParameters = { + project: 'projectValue', + service: 'serviceValue', + service_level_objective: 'serviceLevelObjectiveValue', + }; + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('projectServiceServiceLevelObjectivePath', () => { + const result = client.projectServiceServiceLevelObjectivePath( + 'projectValue', + 'serviceValue', + 'serviceLevelObjectiveValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectServiceServiceLevelObjectiveName', () => { + const result = + client.matchProjectFromProjectServiceServiceLevelObjectiveName( + fakePath, + ); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServiceFromProjectServiceServiceLevelObjectiveName', () => { + const result = + client.matchServiceFromProjectServiceServiceLevelObjectiveName( + fakePath, + ); + assert.strictEqual(result, 'serviceValue'); + assert( + ( + client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServiceLevelObjectiveFromProjectServiceServiceLevelObjectiveName', () => { + const result = + client.matchServiceLevelObjectiveFromProjectServiceServiceLevelObjectiveName( + fakePath, + ); + assert.strictEqual(result, 'serviceLevelObjectiveValue'); + assert( + ( + client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectUptimeCheckConfig', () => { - const fakePath = "/rendered/path/projectUptimeCheckConfig"; - const expectedParameters = { - project: "projectValue", - uptime_check_config: "uptimeCheckConfigValue", - }; - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.projectUptimeCheckConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectUptimeCheckConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectUptimeCheckConfigPath', () => { - const result = client.projectUptimeCheckConfigPath("projectValue", "uptimeCheckConfigValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectUptimeCheckConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectUptimeCheckConfigName', () => { - const result = client.matchProjectFromProjectUptimeCheckConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectUptimeCheckConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchUptimeCheckConfigFromProjectUptimeCheckConfigName', () => { - const result = client.matchUptimeCheckConfigFromProjectUptimeCheckConfigName(fakePath); - assert.strictEqual(result, "uptimeCheckConfigValue"); - assert((client.pathTemplates.projectUptimeCheckConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectUptimeCheckConfig', () => { + const fakePath = '/rendered/path/projectUptimeCheckConfig'; + const expectedParameters = { + project: 'projectValue', + uptime_check_config: 'uptimeCheckConfigValue', + }; + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.projectUptimeCheckConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectUptimeCheckConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectUptimeCheckConfigPath', () => { + const result = client.projectUptimeCheckConfigPath( + 'projectValue', + 'uptimeCheckConfigValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.projectUptimeCheckConfigPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectUptimeCheckConfigName', () => { + const result = + client.matchProjectFromProjectUptimeCheckConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.projectUptimeCheckConfigPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchUptimeCheckConfigFromProjectUptimeCheckConfigName', () => { + const result = + client.matchUptimeCheckConfigFromProjectUptimeCheckConfigName( + fakePath, + ); + assert.strictEqual(result, 'uptimeCheckConfigValue'); + assert( + ( + client.pathTemplates.projectUptimeCheckConfigPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/core/generator/gapic-generator-typescript/baselines/monitoring-esm/esm/test/gapic_notification_channel_service_v3.ts.baseline b/core/generator/gapic-generator-typescript/baselines/monitoring-esm/esm/test/gapic_notification_channel_service_v3.ts.baseline index b8f5cbb4948e..05f88e91113e 100644 --- a/core/generator/gapic-generator-typescript/baselines/monitoring-esm/esm/test/gapic_notification_channel_service_v3.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/monitoring-esm/esm/test/gapic_notification_channel_service_v3.ts.baseline @@ -20,16 +20,16 @@ import * as protos from '../../protos/protos.js'; import assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as notificationchannelserviceModule from '../src/index.js'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; -import {protobuf} from 'google-gax'; +import { protobuf } from 'google-gax'; import fs from 'fs'; import path from 'path'; -import {fileURLToPath} from 'url'; +import { fileURLToPath } from 'url'; // @ts-ignore const dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -37,2555 +37,4007 @@ const dirname = path.dirname(fileURLToPath(import.meta.url)); // to fill in default values for request objects const root = protobuf.Root.fromJSON( JSON.parse( - fs.readFileSync(path.join(dirname, '..', '..', 'protos/protos.json'), 'utf8') - )) + fs.readFileSync( + path.join(dirname, '..', '..', 'protos/protos.json'), + 'utf8', + ), + ), +); // eslint-disable-next-line @typescript-eslint/no-unused-vars function getTypeDefaultValue(typeName: string, fields: string[]) { - let type = root.lookupType(typeName) as protobuf.Type; - for (const field of fields.slice(0, -1)) { - type = type?.fields[field]?.resolvedType as protobuf.Type; - } - return type?.fields[fields[fields.length - 1]]?.defaultValue ?? null; + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type?.fields[field]?.resolvedType as protobuf.Type; + } + return type?.fields[fields[fields.length - 1]]?.defaultValue ?? null; } function generateSampleMessage(instance: T) { - const filledObject = (instance.constructor as typeof protobuf.Message) - .toObject(instance as protobuf.Message, {defaults: true}); - return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, { defaults: true }); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; } function stubSimpleCall(response?: ResponseType, error?: Error) { - return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); } -function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { - return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +function stubSimpleCallWithCallback( + response?: ResponseType, + error?: Error, +) { + return error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); } -function stubPageStreamingCall(responses?: ResponseType[], error?: Error) { - const pagingStub = sinon.stub(); - if (responses) { - for (let i = 0; i < responses.length; ++i) { - pagingStub.onCall(i).callsArgWith(2, null, responses[i]); - } +function stubPageStreamingCall( + responses?: ResponseType[], + error?: Error, +) { + const pagingStub = sinon.stub(); + if (responses) { + for (let i = 0; i < responses.length; ++i) { + pagingStub.onCall(i).callsArgWith(2, null, responses[i]); } - const transformStub = error ? sinon.stub().callsArgWith(2, error) : pagingStub; - const mockStream = new PassThrough({ - objectMode: true, - transform: transformStub, - }); - // trigger as many responses as needed - if (responses) { - for (let i = 0; i < responses.length; ++i) { - setImmediate(() => { mockStream.write({}); }); - } - setImmediate(() => { mockStream.end(); }); - } else { - setImmediate(() => { mockStream.write({}); }); - setImmediate(() => { mockStream.end(); }); + } + const transformStub = error + ? sinon.stub().callsArgWith(2, error) + : pagingStub; + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + // trigger as many responses as needed + if (responses) { + for (let i = 0; i < responses.length; ++i) { + setImmediate(() => { + mockStream.write({}); + }); } - return sinon.stub().returns(mockStream); + setImmediate(() => { + mockStream.end(); + }); + } else { + setImmediate(() => { + mockStream.write({}); + }); + setImmediate(() => { + mockStream.end(); + }); + } + return sinon.stub().returns(mockStream); } -function stubAsyncIterationCall(responses?: ResponseType[], error?: Error) { - let counter = 0; - const asyncIterable = { - [Symbol.asyncIterator]() { - return { - async next() { - if (error) { - return Promise.reject(error); - } - if (counter >= responses!.length) { - return Promise.resolve({done: true, value: undefined}); - } - return Promise.resolve({done: false, value: responses![counter++]}); - } - }; - } - }; - return sinon.stub().returns(asyncIterable); +function stubAsyncIterationCall( + responses?: ResponseType[], + error?: Error, +) { + let counter = 0; + const asyncIterable = { + [Symbol.asyncIterator]() { + return { + async next() { + if (error) { + return Promise.reject(error); + } + if (counter >= responses!.length) { + return Promise.resolve({ done: true, value: undefined }); + } + return Promise.resolve({ done: false, value: responses![counter++] }); + }, + }; + }, + }; + return sinon.stub().returns(asyncIterable); } describe('v3.NotificationChannelServiceClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'monitoring.googleapis.com'); - }); - - it('has universeDomain', () => { - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); - - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - it('throws DeprecationWarning if static servicePath is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const servicePath = notificationchannelserviceModule.v3.NotificationChannelServiceClient.servicePath; - assert.strictEqual(servicePath, 'monitoring.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = notificationchannelserviceModule.v3.NotificationChannelServiceClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'monitoring.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'monitoring.example.com'); - }); - - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'monitoring.example.com'); - }); - - if (typeof process === 'object' && 'env' in process) { - describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { - it('sets apiEndpoint from environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'monitoring.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - - it('value configured in code has priority over environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'monitoring.configured.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { new notificationchannelserviceModule.v3.NotificationChannelServiceClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); - - it('has port', () => { - const port = notificationchannelserviceModule.v3.NotificationChannelServiceClient.port; - assert(port); - assert(typeof port === 'number'); - }); - - it('should create a client with no option', () => { - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient(); - assert(client); - }); - - it('should create a client with gRPC fallback', () => { - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - fallback: true, - }); - assert(client); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'monitoring.googleapis.com'); + }); - it('has initialize method and supports deferred initialization', async () => { - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.notificationChannelServiceStub, undefined); - await client.initialize(); - assert(client.notificationChannelServiceStub); - }); + it('has universeDomain', () => { + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - it('has close method for the initialized client', done => { - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.notificationChannelServiceStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = + notificationchannelserviceModule.v3.NotificationChannelServiceClient + .servicePath; + assert.strictEqual(servicePath, 'monitoring.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + notificationchannelserviceModule.v3.NotificationChannelServiceClient + .apiEndpoint; + assert.strictEqual(apiEndpoint, 'monitoring.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { universeDomain: 'example.com' }, + ); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'monitoring.example.com'); + }); - it('has close method for the non-initialized client', done => { - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.notificationChannelServiceStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { universe_domain: 'example.com' }, + ); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'monitoring.example.com'); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); - }); + if (typeof process === 'object' && 'env' in process) { + describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { + it('sets apiEndpoint from environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'monitoring.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } + }); + + it('value configured in code has priority over environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { universeDomain: 'configured.example.com' }, + ); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'monitoring.configured.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } + }); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { universe_domain: 'example.com', universeDomain: 'example.net' }, + ); + }); + }); - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId((err?: Error|null, projectId?: string|null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } - }); - }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); - }); + it('has port', () => { + const port = + notificationchannelserviceModule.v3.NotificationChannelServiceClient + .port; + assert(port); + assert(typeof port === 'number'); }); - describe('getNotificationChannelDescriptor', () => { - it('invokes getNotificationChannelDescriptor without error', async () => { - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.GetNotificationChannelDescriptorRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.GetNotificationChannelDescriptorRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.monitoring.v3.NotificationChannelDescriptor() - ); - client.innerApiCalls.getNotificationChannelDescriptor = stubSimpleCall(expectedResponse); - const [response] = await client.getNotificationChannelDescriptor(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getNotificationChannelDescriptor as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getNotificationChannelDescriptor as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('should create a client with no option', () => { + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient(); + assert(client); + }); - it('invokes getNotificationChannelDescriptor without error using callback', async () => { - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.GetNotificationChannelDescriptorRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.GetNotificationChannelDescriptorRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.monitoring.v3.NotificationChannelDescriptor() - ); - client.innerApiCalls.getNotificationChannelDescriptor = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getNotificationChannelDescriptor( - request, - (err?: Error|null, result?: protos.google.monitoring.v3.INotificationChannelDescriptor|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getNotificationChannelDescriptor as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getNotificationChannelDescriptor as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('should create a client with gRPC fallback', () => { + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + fallback: true, + }, + ); + assert(client); + }); - it('invokes getNotificationChannelDescriptor with error', async () => { - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.GetNotificationChannelDescriptorRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.GetNotificationChannelDescriptorRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getNotificationChannelDescriptor = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getNotificationChannelDescriptor(request), expectedError); - const actualRequest = (client.innerApiCalls.getNotificationChannelDescriptor as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getNotificationChannelDescriptor as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has initialize method and supports deferred initialization', async () => { + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + assert.strictEqual(client.notificationChannelServiceStub, undefined); + await client.initialize(); + assert(client.notificationChannelServiceStub); + }); - it('invokes getNotificationChannelDescriptor with closed client', async () => { - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.GetNotificationChannelDescriptorRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.GetNotificationChannelDescriptorRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getNotificationChannelDescriptor(request), expectedError); + it('has close method for the initialized client', (done) => { + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + client.initialize().catch((err) => { + throw err; + }); + assert(client.notificationChannelServiceStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); }); - describe('getNotificationChannel', () => { - it('invokes getNotificationChannel without error', async () => { - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.GetNotificationChannelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.GetNotificationChannelRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.monitoring.v3.NotificationChannel() - ); - client.innerApiCalls.getNotificationChannel = stubSimpleCall(expectedResponse); - const [response] = await client.getNotificationChannel(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getNotificationChannel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getNotificationChannel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('has close method for the non-initialized client', (done) => { + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + assert.strictEqual(client.notificationChannelServiceStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes getNotificationChannel without error using callback', async () => { - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.GetNotificationChannelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.GetNotificationChannelRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.monitoring.v3.NotificationChannel() - ); - client.innerApiCalls.getNotificationChannel = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getNotificationChannel( - request, - (err?: Error|null, result?: protos.google.monitoring.v3.INotificationChannel|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getNotificationChannel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getNotificationChannel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + }); - it('invokes getNotificationChannel with error', async () => { - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.GetNotificationChannelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.GetNotificationChannelRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getNotificationChannel = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getNotificationChannel(request), expectedError); - const actualRequest = (client.innerApiCalls.getNotificationChannel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getNotificationChannel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } + }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + }); + + describe('getNotificationChannelDescriptor', () => { + it('invokes getNotificationChannelDescriptor without error', async () => { + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.GetNotificationChannelDescriptorRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.GetNotificationChannelDescriptorRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.monitoring.v3.NotificationChannelDescriptor(), + ); + client.innerApiCalls.getNotificationChannelDescriptor = + stubSimpleCall(expectedResponse); + const [response] = await client.getNotificationChannelDescriptor(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getNotificationChannelDescriptor as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getNotificationChannelDescriptor as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getNotificationChannel with closed client', async () => { - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.GetNotificationChannelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.GetNotificationChannelRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getNotificationChannel(request), expectedError); - }); + it('invokes getNotificationChannelDescriptor without error using callback', async () => { + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.GetNotificationChannelDescriptorRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.GetNotificationChannelDescriptorRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.monitoring.v3.NotificationChannelDescriptor(), + ); + client.innerApiCalls.getNotificationChannelDescriptor = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getNotificationChannelDescriptor( + request, + ( + err?: Error | null, + result?: protos.google.monitoring.v3.INotificationChannelDescriptor | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getNotificationChannelDescriptor as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getNotificationChannelDescriptor as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('createNotificationChannel', () => { - it('invokes createNotificationChannel without error', async () => { - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.CreateNotificationChannelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.CreateNotificationChannelRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.monitoring.v3.NotificationChannel() - ); - client.innerApiCalls.createNotificationChannel = stubSimpleCall(expectedResponse); - const [response] = await client.createNotificationChannel(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createNotificationChannel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createNotificationChannel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getNotificationChannelDescriptor with error', async () => { + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.GetNotificationChannelDescriptorRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.GetNotificationChannelDescriptorRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getNotificationChannelDescriptor = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.getNotificationChannelDescriptor(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.getNotificationChannelDescriptor as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getNotificationChannelDescriptor as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createNotificationChannel without error using callback', async () => { - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.CreateNotificationChannelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.CreateNotificationChannelRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.monitoring.v3.NotificationChannel() - ); - client.innerApiCalls.createNotificationChannel = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createNotificationChannel( - request, - (err?: Error|null, result?: protos.google.monitoring.v3.INotificationChannel|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createNotificationChannel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createNotificationChannel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getNotificationChannelDescriptor with closed client', async () => { + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.GetNotificationChannelDescriptorRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.GetNotificationChannelDescriptorRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.getNotificationChannelDescriptor(request), + expectedError, + ); + }); + }); + + describe('getNotificationChannel', () => { + it('invokes getNotificationChannel without error', async () => { + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.GetNotificationChannelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.GetNotificationChannelRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.monitoring.v3.NotificationChannel(), + ); + client.innerApiCalls.getNotificationChannel = + stubSimpleCall(expectedResponse); + const [response] = await client.getNotificationChannel(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getNotificationChannel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getNotificationChannel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createNotificationChannel with error', async () => { - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.CreateNotificationChannelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.CreateNotificationChannelRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createNotificationChannel = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createNotificationChannel(request), expectedError); - const actualRequest = (client.innerApiCalls.createNotificationChannel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createNotificationChannel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getNotificationChannel without error using callback', async () => { + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.GetNotificationChannelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.GetNotificationChannelRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.monitoring.v3.NotificationChannel(), + ); + client.innerApiCalls.getNotificationChannel = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getNotificationChannel( + request, + ( + err?: Error | null, + result?: protos.google.monitoring.v3.INotificationChannel | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getNotificationChannel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getNotificationChannel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createNotificationChannel with closed client', async () => { - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.CreateNotificationChannelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.CreateNotificationChannelRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createNotificationChannel(request), expectedError); - }); + it('invokes getNotificationChannel with error', async () => { + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.GetNotificationChannelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.GetNotificationChannelRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getNotificationChannel = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.getNotificationChannel(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.getNotificationChannel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getNotificationChannel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('updateNotificationChannel', () => { - it('invokes updateNotificationChannel without error', async () => { - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.UpdateNotificationChannelRequest() - ); - request.notificationChannel ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.UpdateNotificationChannelRequest', ['notificationChannel', 'name']); - request.notificationChannel.name = defaultValue1; - const expectedHeaderRequestParams = `notification_channel.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.monitoring.v3.NotificationChannel() - ); - client.innerApiCalls.updateNotificationChannel = stubSimpleCall(expectedResponse); - const [response] = await client.updateNotificationChannel(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateNotificationChannel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateNotificationChannel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getNotificationChannel with closed client', async () => { + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.GetNotificationChannelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.GetNotificationChannelRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.getNotificationChannel(request), + expectedError, + ); + }); + }); + + describe('createNotificationChannel', () => { + it('invokes createNotificationChannel without error', async () => { + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.CreateNotificationChannelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.CreateNotificationChannelRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.monitoring.v3.NotificationChannel(), + ); + client.innerApiCalls.createNotificationChannel = + stubSimpleCall(expectedResponse); + const [response] = await client.createNotificationChannel(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createNotificationChannel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createNotificationChannel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateNotificationChannel without error using callback', async () => { - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.UpdateNotificationChannelRequest() - ); - request.notificationChannel ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.UpdateNotificationChannelRequest', ['notificationChannel', 'name']); - request.notificationChannel.name = defaultValue1; - const expectedHeaderRequestParams = `notification_channel.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.monitoring.v3.NotificationChannel() - ); - client.innerApiCalls.updateNotificationChannel = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateNotificationChannel( - request, - (err?: Error|null, result?: protos.google.monitoring.v3.INotificationChannel|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateNotificationChannel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateNotificationChannel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createNotificationChannel without error using callback', async () => { + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.CreateNotificationChannelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.CreateNotificationChannelRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.monitoring.v3.NotificationChannel(), + ); + client.innerApiCalls.createNotificationChannel = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createNotificationChannel( + request, + ( + err?: Error | null, + result?: protos.google.monitoring.v3.INotificationChannel | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createNotificationChannel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createNotificationChannel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateNotificationChannel with error', async () => { - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.UpdateNotificationChannelRequest() - ); - request.notificationChannel ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.UpdateNotificationChannelRequest', ['notificationChannel', 'name']); - request.notificationChannel.name = defaultValue1; - const expectedHeaderRequestParams = `notification_channel.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateNotificationChannel = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateNotificationChannel(request), expectedError); - const actualRequest = (client.innerApiCalls.updateNotificationChannel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateNotificationChannel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createNotificationChannel with error', async () => { + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.CreateNotificationChannelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.CreateNotificationChannelRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createNotificationChannel = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.createNotificationChannel(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.createNotificationChannel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createNotificationChannel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateNotificationChannel with closed client', async () => { - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.UpdateNotificationChannelRequest() - ); - request.notificationChannel ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.UpdateNotificationChannelRequest', ['notificationChannel', 'name']); - request.notificationChannel.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateNotificationChannel(request), expectedError); - }); + it('invokes createNotificationChannel with closed client', async () => { + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.CreateNotificationChannelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.CreateNotificationChannelRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.createNotificationChannel(request), + expectedError, + ); + }); + }); + + describe('updateNotificationChannel', () => { + it('invokes updateNotificationChannel without error', async () => { + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.UpdateNotificationChannelRequest(), + ); + request.notificationChannel ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.UpdateNotificationChannelRequest', + ['notificationChannel', 'name'], + ); + request.notificationChannel.name = defaultValue1; + const expectedHeaderRequestParams = `notification_channel.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.monitoring.v3.NotificationChannel(), + ); + client.innerApiCalls.updateNotificationChannel = + stubSimpleCall(expectedResponse); + const [response] = await client.updateNotificationChannel(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateNotificationChannel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateNotificationChannel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('deleteNotificationChannel', () => { - it('invokes deleteNotificationChannel without error', async () => { - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.DeleteNotificationChannelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.DeleteNotificationChannelRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteNotificationChannel = stubSimpleCall(expectedResponse); - const [response] = await client.deleteNotificationChannel(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteNotificationChannel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteNotificationChannel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateNotificationChannel without error using callback', async () => { + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.UpdateNotificationChannelRequest(), + ); + request.notificationChannel ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.UpdateNotificationChannelRequest', + ['notificationChannel', 'name'], + ); + request.notificationChannel.name = defaultValue1; + const expectedHeaderRequestParams = `notification_channel.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.monitoring.v3.NotificationChannel(), + ); + client.innerApiCalls.updateNotificationChannel = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateNotificationChannel( + request, + ( + err?: Error | null, + result?: protos.google.monitoring.v3.INotificationChannel | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateNotificationChannel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateNotificationChannel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteNotificationChannel without error using callback', async () => { - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.DeleteNotificationChannelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.DeleteNotificationChannelRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteNotificationChannel = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteNotificationChannel( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteNotificationChannel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteNotificationChannel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateNotificationChannel with error', async () => { + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.UpdateNotificationChannelRequest(), + ); + request.notificationChannel ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.UpdateNotificationChannelRequest', + ['notificationChannel', 'name'], + ); + request.notificationChannel.name = defaultValue1; + const expectedHeaderRequestParams = `notification_channel.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateNotificationChannel = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.updateNotificationChannel(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.updateNotificationChannel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateNotificationChannel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteNotificationChannel with error', async () => { - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.DeleteNotificationChannelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.DeleteNotificationChannelRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteNotificationChannel = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteNotificationChannel(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteNotificationChannel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteNotificationChannel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateNotificationChannel with closed client', async () => { + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.UpdateNotificationChannelRequest(), + ); + request.notificationChannel ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.UpdateNotificationChannelRequest', + ['notificationChannel', 'name'], + ); + request.notificationChannel.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.updateNotificationChannel(request), + expectedError, + ); + }); + }); + + describe('deleteNotificationChannel', () => { + it('invokes deleteNotificationChannel without error', async () => { + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.DeleteNotificationChannelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.DeleteNotificationChannelRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteNotificationChannel = + stubSimpleCall(expectedResponse); + const [response] = await client.deleteNotificationChannel(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteNotificationChannel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteNotificationChannel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteNotificationChannel with closed client', async () => { - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.DeleteNotificationChannelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.DeleteNotificationChannelRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteNotificationChannel(request), expectedError); - }); + it('invokes deleteNotificationChannel without error using callback', async () => { + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.DeleteNotificationChannelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.DeleteNotificationChannelRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteNotificationChannel = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteNotificationChannel( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteNotificationChannel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteNotificationChannel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('sendNotificationChannelVerificationCode', () => { - it('invokes sendNotificationChannelVerificationCode without error', async () => { - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.SendNotificationChannelVerificationCodeRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.SendNotificationChannelVerificationCodeRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.sendNotificationChannelVerificationCode = stubSimpleCall(expectedResponse); - const [response] = await client.sendNotificationChannelVerificationCode(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.sendNotificationChannelVerificationCode as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.sendNotificationChannelVerificationCode as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteNotificationChannel with error', async () => { + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.DeleteNotificationChannelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.DeleteNotificationChannelRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteNotificationChannel = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.deleteNotificationChannel(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.deleteNotificationChannel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteNotificationChannel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes sendNotificationChannelVerificationCode without error using callback', async () => { - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.SendNotificationChannelVerificationCodeRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.SendNotificationChannelVerificationCodeRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.sendNotificationChannelVerificationCode = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.sendNotificationChannelVerificationCode( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.sendNotificationChannelVerificationCode as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.sendNotificationChannelVerificationCode as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteNotificationChannel with closed client', async () => { + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.DeleteNotificationChannelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.DeleteNotificationChannelRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.deleteNotificationChannel(request), + expectedError, + ); + }); + }); + + describe('sendNotificationChannelVerificationCode', () => { + it('invokes sendNotificationChannelVerificationCode without error', async () => { + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.SendNotificationChannelVerificationCodeRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.SendNotificationChannelVerificationCodeRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.sendNotificationChannelVerificationCode = + stubSimpleCall(expectedResponse); + const [response] = + await client.sendNotificationChannelVerificationCode(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls + .sendNotificationChannelVerificationCode as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls + .sendNotificationChannelVerificationCode as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes sendNotificationChannelVerificationCode with error', async () => { - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.SendNotificationChannelVerificationCodeRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.SendNotificationChannelVerificationCodeRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.sendNotificationChannelVerificationCode = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.sendNotificationChannelVerificationCode(request), expectedError); - const actualRequest = (client.innerApiCalls.sendNotificationChannelVerificationCode as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.sendNotificationChannelVerificationCode as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes sendNotificationChannelVerificationCode without error using callback', async () => { + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.SendNotificationChannelVerificationCodeRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.SendNotificationChannelVerificationCodeRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.sendNotificationChannelVerificationCode = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.sendNotificationChannelVerificationCode( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls + .sendNotificationChannelVerificationCode as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls + .sendNotificationChannelVerificationCode as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes sendNotificationChannelVerificationCode with closed client', async () => { - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.SendNotificationChannelVerificationCodeRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.SendNotificationChannelVerificationCodeRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.sendNotificationChannelVerificationCode(request), expectedError); - }); + it('invokes sendNotificationChannelVerificationCode with error', async () => { + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.SendNotificationChannelVerificationCodeRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.SendNotificationChannelVerificationCodeRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.sendNotificationChannelVerificationCode = + stubSimpleCall(undefined, expectedError); + await assert.rejects( + client.sendNotificationChannelVerificationCode(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls + .sendNotificationChannelVerificationCode as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls + .sendNotificationChannelVerificationCode as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('getNotificationChannelVerificationCode', () => { - it('invokes getNotificationChannelVerificationCode without error', async () => { - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.GetNotificationChannelVerificationCodeRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.GetNotificationChannelVerificationCodeRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.monitoring.v3.GetNotificationChannelVerificationCodeResponse() - ); - client.innerApiCalls.getNotificationChannelVerificationCode = stubSimpleCall(expectedResponse); - const [response] = await client.getNotificationChannelVerificationCode(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getNotificationChannelVerificationCode as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getNotificationChannelVerificationCode as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes sendNotificationChannelVerificationCode with closed client', async () => { + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.SendNotificationChannelVerificationCodeRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.SendNotificationChannelVerificationCodeRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.sendNotificationChannelVerificationCode(request), + expectedError, + ); + }); + }); + + describe('getNotificationChannelVerificationCode', () => { + it('invokes getNotificationChannelVerificationCode without error', async () => { + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.GetNotificationChannelVerificationCodeRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.GetNotificationChannelVerificationCodeRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.monitoring.v3.GetNotificationChannelVerificationCodeResponse(), + ); + client.innerApiCalls.getNotificationChannelVerificationCode = + stubSimpleCall(expectedResponse); + const [response] = + await client.getNotificationChannelVerificationCode(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getNotificationChannelVerificationCode as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getNotificationChannelVerificationCode as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getNotificationChannelVerificationCode without error using callback', async () => { - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.GetNotificationChannelVerificationCodeRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.GetNotificationChannelVerificationCodeRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.monitoring.v3.GetNotificationChannelVerificationCodeResponse() - ); - client.innerApiCalls.getNotificationChannelVerificationCode = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getNotificationChannelVerificationCode( - request, - (err?: Error|null, result?: protos.google.monitoring.v3.IGetNotificationChannelVerificationCodeResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getNotificationChannelVerificationCode as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getNotificationChannelVerificationCode as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getNotificationChannelVerificationCode without error using callback', async () => { + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.GetNotificationChannelVerificationCodeRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.GetNotificationChannelVerificationCodeRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.monitoring.v3.GetNotificationChannelVerificationCodeResponse(), + ); + client.innerApiCalls.getNotificationChannelVerificationCode = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getNotificationChannelVerificationCode( + request, + ( + err?: Error | null, + result?: protos.google.monitoring.v3.IGetNotificationChannelVerificationCodeResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getNotificationChannelVerificationCode as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getNotificationChannelVerificationCode as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getNotificationChannelVerificationCode with error', async () => { - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.GetNotificationChannelVerificationCodeRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.GetNotificationChannelVerificationCodeRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getNotificationChannelVerificationCode = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getNotificationChannelVerificationCode(request), expectedError); - const actualRequest = (client.innerApiCalls.getNotificationChannelVerificationCode as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getNotificationChannelVerificationCode as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getNotificationChannelVerificationCode with error', async () => { + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.GetNotificationChannelVerificationCodeRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.GetNotificationChannelVerificationCodeRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getNotificationChannelVerificationCode = + stubSimpleCall(undefined, expectedError); + await assert.rejects( + client.getNotificationChannelVerificationCode(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.getNotificationChannelVerificationCode as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getNotificationChannelVerificationCode as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getNotificationChannelVerificationCode with closed client', async () => { - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.GetNotificationChannelVerificationCodeRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.GetNotificationChannelVerificationCodeRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getNotificationChannelVerificationCode(request), expectedError); - }); + it('invokes getNotificationChannelVerificationCode with closed client', async () => { + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.GetNotificationChannelVerificationCodeRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.GetNotificationChannelVerificationCodeRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.getNotificationChannelVerificationCode(request), + expectedError, + ); + }); + }); + + describe('verifyNotificationChannel', () => { + it('invokes verifyNotificationChannel without error', async () => { + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.VerifyNotificationChannelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.VerifyNotificationChannelRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.monitoring.v3.NotificationChannel(), + ); + client.innerApiCalls.verifyNotificationChannel = + stubSimpleCall(expectedResponse); + const [response] = await client.verifyNotificationChannel(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.verifyNotificationChannel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.verifyNotificationChannel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('verifyNotificationChannel', () => { - it('invokes verifyNotificationChannel without error', async () => { - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.VerifyNotificationChannelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.VerifyNotificationChannelRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.monitoring.v3.NotificationChannel() - ); - client.innerApiCalls.verifyNotificationChannel = stubSimpleCall(expectedResponse); - const [response] = await client.verifyNotificationChannel(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.verifyNotificationChannel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.verifyNotificationChannel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes verifyNotificationChannel without error using callback', async () => { + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.VerifyNotificationChannelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.VerifyNotificationChannelRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.monitoring.v3.NotificationChannel(), + ); + client.innerApiCalls.verifyNotificationChannel = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.verifyNotificationChannel( + request, + ( + err?: Error | null, + result?: protos.google.monitoring.v3.INotificationChannel | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.verifyNotificationChannel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.verifyNotificationChannel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes verifyNotificationChannel without error using callback', async () => { - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.VerifyNotificationChannelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.VerifyNotificationChannelRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.monitoring.v3.NotificationChannel() - ); - client.innerApiCalls.verifyNotificationChannel = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.verifyNotificationChannel( - request, - (err?: Error|null, result?: protos.google.monitoring.v3.INotificationChannel|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.verifyNotificationChannel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.verifyNotificationChannel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes verifyNotificationChannel with error', async () => { + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.VerifyNotificationChannelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.VerifyNotificationChannelRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.verifyNotificationChannel = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.verifyNotificationChannel(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.verifyNotificationChannel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.verifyNotificationChannel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes verifyNotificationChannel with error', async () => { - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.VerifyNotificationChannelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.VerifyNotificationChannelRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.verifyNotificationChannel = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.verifyNotificationChannel(request), expectedError); - const actualRequest = (client.innerApiCalls.verifyNotificationChannel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.verifyNotificationChannel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes verifyNotificationChannel with closed client', async () => { + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.VerifyNotificationChannelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.VerifyNotificationChannelRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.verifyNotificationChannel(request), + expectedError, + ); + }); + }); + + describe('listNotificationChannelDescriptors', () => { + it('invokes listNotificationChannelDescriptors without error', async () => { + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListNotificationChannelDescriptorsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListNotificationChannelDescriptorsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.monitoring.v3.NotificationChannelDescriptor(), + ), + generateSampleMessage( + new protos.google.monitoring.v3.NotificationChannelDescriptor(), + ), + generateSampleMessage( + new protos.google.monitoring.v3.NotificationChannelDescriptor(), + ), + ]; + client.innerApiCalls.listNotificationChannelDescriptors = + stubSimpleCall(expectedResponse); + const [response] = + await client.listNotificationChannelDescriptors(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listNotificationChannelDescriptors as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listNotificationChannelDescriptors as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes verifyNotificationChannel with closed client', async () => { - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.VerifyNotificationChannelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.VerifyNotificationChannelRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.verifyNotificationChannel(request), expectedError); - }); + it('invokes listNotificationChannelDescriptors without error using callback', async () => { + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListNotificationChannelDescriptorsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListNotificationChannelDescriptorsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.monitoring.v3.NotificationChannelDescriptor(), + ), + generateSampleMessage( + new protos.google.monitoring.v3.NotificationChannelDescriptor(), + ), + generateSampleMessage( + new protos.google.monitoring.v3.NotificationChannelDescriptor(), + ), + ]; + client.innerApiCalls.listNotificationChannelDescriptors = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listNotificationChannelDescriptors( + request, + ( + err?: Error | null, + result?: + | protos.google.monitoring.v3.INotificationChannelDescriptor[] + | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listNotificationChannelDescriptors as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listNotificationChannelDescriptors as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('listNotificationChannelDescriptors', () => { - it('invokes listNotificationChannelDescriptors without error', async () => { - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListNotificationChannelDescriptorsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListNotificationChannelDescriptorsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.monitoring.v3.NotificationChannelDescriptor()), - generateSampleMessage(new protos.google.monitoring.v3.NotificationChannelDescriptor()), - generateSampleMessage(new protos.google.monitoring.v3.NotificationChannelDescriptor()), - ]; - client.innerApiCalls.listNotificationChannelDescriptors = stubSimpleCall(expectedResponse); - const [response] = await client.listNotificationChannelDescriptors(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listNotificationChannelDescriptors as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listNotificationChannelDescriptors as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listNotificationChannelDescriptors with error', async () => { + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListNotificationChannelDescriptorsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListNotificationChannelDescriptorsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listNotificationChannelDescriptors = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.listNotificationChannelDescriptors(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.listNotificationChannelDescriptors as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listNotificationChannelDescriptors as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listNotificationChannelDescriptors without error using callback', async () => { - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListNotificationChannelDescriptorsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListNotificationChannelDescriptorsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.monitoring.v3.NotificationChannelDescriptor()), - generateSampleMessage(new protos.google.monitoring.v3.NotificationChannelDescriptor()), - generateSampleMessage(new protos.google.monitoring.v3.NotificationChannelDescriptor()), - ]; - client.innerApiCalls.listNotificationChannelDescriptors = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listNotificationChannelDescriptors( - request, - (err?: Error|null, result?: protos.google.monitoring.v3.INotificationChannelDescriptor[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listNotificationChannelDescriptors as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listNotificationChannelDescriptors as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listNotificationChannelDescriptorsStream without error', async () => { + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListNotificationChannelDescriptorsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListNotificationChannelDescriptorsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.monitoring.v3.NotificationChannelDescriptor(), + ), + generateSampleMessage( + new protos.google.monitoring.v3.NotificationChannelDescriptor(), + ), + generateSampleMessage( + new protos.google.monitoring.v3.NotificationChannelDescriptor(), + ), + ]; + client.descriptors.page.listNotificationChannelDescriptors.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listNotificationChannelDescriptorsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.monitoring.v3.NotificationChannelDescriptor[] = + []; + stream.on( + 'data', + ( + response: protos.google.monitoring.v3.NotificationChannelDescriptor, + ) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + ( + client.descriptors.page.listNotificationChannelDescriptors + .createStream as SinonStub + ) + .getCall(0) + .calledWith( + client.innerApiCalls.listNotificationChannelDescriptors, + request, + ), + ); + assert( + ( + client.descriptors.page.listNotificationChannelDescriptors + .createStream as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); - it('invokes listNotificationChannelDescriptors with error', async () => { - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListNotificationChannelDescriptorsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListNotificationChannelDescriptorsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listNotificationChannelDescriptors = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listNotificationChannelDescriptors(request), expectedError); - const actualRequest = (client.innerApiCalls.listNotificationChannelDescriptors as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listNotificationChannelDescriptors as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listNotificationChannelDescriptorsStream with error', async () => { + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListNotificationChannelDescriptorsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListNotificationChannelDescriptorsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listNotificationChannelDescriptors.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listNotificationChannelDescriptorsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.monitoring.v3.NotificationChannelDescriptor[] = + []; + stream.on( + 'data', + ( + response: protos.google.monitoring.v3.NotificationChannelDescriptor, + ) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + ( + client.descriptors.page.listNotificationChannelDescriptors + .createStream as SinonStub + ) + .getCall(0) + .calledWith( + client.innerApiCalls.listNotificationChannelDescriptors, + request, + ), + ); + assert( + ( + client.descriptors.page.listNotificationChannelDescriptors + .createStream as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); - it('invokes listNotificationChannelDescriptorsStream without error', async () => { - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListNotificationChannelDescriptorsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListNotificationChannelDescriptorsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.monitoring.v3.NotificationChannelDescriptor()), - generateSampleMessage(new protos.google.monitoring.v3.NotificationChannelDescriptor()), - generateSampleMessage(new protos.google.monitoring.v3.NotificationChannelDescriptor()), - ]; - client.descriptors.page.listNotificationChannelDescriptors.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listNotificationChannelDescriptorsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.monitoring.v3.NotificationChannelDescriptor[] = []; - stream.on('data', (response: protos.google.monitoring.v3.NotificationChannelDescriptor) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.listNotificationChannelDescriptors.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listNotificationChannelDescriptors, request)); - assert( - (client.descriptors.page.listNotificationChannelDescriptors.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listNotificationChannelDescriptors without error', async () => { + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListNotificationChannelDescriptorsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListNotificationChannelDescriptorsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.monitoring.v3.NotificationChannelDescriptor(), + ), + generateSampleMessage( + new protos.google.monitoring.v3.NotificationChannelDescriptor(), + ), + generateSampleMessage( + new protos.google.monitoring.v3.NotificationChannelDescriptor(), + ), + ]; + client.descriptors.page.listNotificationChannelDescriptors.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.monitoring.v3.INotificationChannelDescriptor[] = + []; + const iterable = client.listNotificationChannelDescriptorsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listNotificationChannelDescriptors + .asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + ( + client.descriptors.page.listNotificationChannelDescriptors + .asyncIterate as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); - it('invokes listNotificationChannelDescriptorsStream with error', async () => { - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListNotificationChannelDescriptorsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListNotificationChannelDescriptorsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listNotificationChannelDescriptors.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listNotificationChannelDescriptorsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.monitoring.v3.NotificationChannelDescriptor[] = []; - stream.on('data', (response: protos.google.monitoring.v3.NotificationChannelDescriptor) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listNotificationChannelDescriptors.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listNotificationChannelDescriptors, request)); - assert( - (client.descriptors.page.listNotificationChannelDescriptors.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listNotificationChannelDescriptors with error', async () => { + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListNotificationChannelDescriptorsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListNotificationChannelDescriptorsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listNotificationChannelDescriptors.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listNotificationChannelDescriptorsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.monitoring.v3.INotificationChannelDescriptor[] = + []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listNotificationChannelDescriptors + .asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + ( + client.descriptors.page.listNotificationChannelDescriptors + .asyncIterate as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); + }); + + describe('listNotificationChannels', () => { + it('invokes listNotificationChannels without error', async () => { + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListNotificationChannelsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListNotificationChannelsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.monitoring.v3.NotificationChannel(), + ), + generateSampleMessage( + new protos.google.monitoring.v3.NotificationChannel(), + ), + generateSampleMessage( + new protos.google.monitoring.v3.NotificationChannel(), + ), + ]; + client.innerApiCalls.listNotificationChannels = + stubSimpleCall(expectedResponse); + const [response] = await client.listNotificationChannels(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listNotificationChannels as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listNotificationChannels as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('uses async iteration with listNotificationChannelDescriptors without error', async () => { - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListNotificationChannelDescriptorsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListNotificationChannelDescriptorsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.monitoring.v3.NotificationChannelDescriptor()), - generateSampleMessage(new protos.google.monitoring.v3.NotificationChannelDescriptor()), - generateSampleMessage(new protos.google.monitoring.v3.NotificationChannelDescriptor()), - ]; - client.descriptors.page.listNotificationChannelDescriptors.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.monitoring.v3.INotificationChannelDescriptor[] = []; - const iterable = client.listNotificationChannelDescriptorsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); + it('invokes listNotificationChannels without error using callback', async () => { + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListNotificationChannelsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListNotificationChannelsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.monitoring.v3.NotificationChannel(), + ), + generateSampleMessage( + new protos.google.monitoring.v3.NotificationChannel(), + ), + generateSampleMessage( + new protos.google.monitoring.v3.NotificationChannel(), + ), + ]; + client.innerApiCalls.listNotificationChannels = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listNotificationChannels( + request, + ( + err?: Error | null, + result?: protos.google.monitoring.v3.INotificationChannel[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listNotificationChannelDescriptors.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listNotificationChannelDescriptors.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); - - it('uses async iteration with listNotificationChannelDescriptors with error', async () => { - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListNotificationChannelDescriptorsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListNotificationChannelDescriptorsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listNotificationChannelDescriptors.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listNotificationChannelDescriptorsAsync(request); - await assert.rejects(async () => { - const responses: protos.google.monitoring.v3.INotificationChannelDescriptor[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listNotificationChannelDescriptors.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listNotificationChannelDescriptors.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listNotificationChannels as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listNotificationChannels as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('listNotificationChannels', () => { - it('invokes listNotificationChannels without error', async () => { - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListNotificationChannelsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListNotificationChannelsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.monitoring.v3.NotificationChannel()), - generateSampleMessage(new protos.google.monitoring.v3.NotificationChannel()), - generateSampleMessage(new protos.google.monitoring.v3.NotificationChannel()), - ]; - client.innerApiCalls.listNotificationChannels = stubSimpleCall(expectedResponse); - const [response] = await client.listNotificationChannels(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listNotificationChannels as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listNotificationChannels as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listNotificationChannels without error using callback', async () => { - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListNotificationChannelsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListNotificationChannelsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.monitoring.v3.NotificationChannel()), - generateSampleMessage(new protos.google.monitoring.v3.NotificationChannel()), - generateSampleMessage(new protos.google.monitoring.v3.NotificationChannel()), - ]; - client.innerApiCalls.listNotificationChannels = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listNotificationChannels( - request, - (err?: Error|null, result?: protos.google.monitoring.v3.INotificationChannel[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listNotificationChannels as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listNotificationChannels as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listNotificationChannels with error', async () => { - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListNotificationChannelsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListNotificationChannelsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listNotificationChannels = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listNotificationChannels(request), expectedError); - const actualRequest = (client.innerApiCalls.listNotificationChannels as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listNotificationChannels as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listNotificationChannelsStream without error', async () => { - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListNotificationChannelsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListNotificationChannelsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.monitoring.v3.NotificationChannel()), - generateSampleMessage(new protos.google.monitoring.v3.NotificationChannel()), - generateSampleMessage(new protos.google.monitoring.v3.NotificationChannel()), - ]; - client.descriptors.page.listNotificationChannels.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listNotificationChannelsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.monitoring.v3.NotificationChannel[] = []; - stream.on('data', (response: protos.google.monitoring.v3.NotificationChannel) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.listNotificationChannels.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listNotificationChannels, request)); - assert( - (client.descriptors.page.listNotificationChannels.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listNotificationChannels with error', async () => { + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListNotificationChannelsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListNotificationChannelsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listNotificationChannels = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.listNotificationChannels(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.listNotificationChannels as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listNotificationChannels as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listNotificationChannelsStream with error', async () => { - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListNotificationChannelsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListNotificationChannelsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listNotificationChannels.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listNotificationChannelsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.monitoring.v3.NotificationChannel[] = []; - stream.on('data', (response: protos.google.monitoring.v3.NotificationChannel) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listNotificationChannels.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listNotificationChannels, request)); - assert( - (client.descriptors.page.listNotificationChannels.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listNotificationChannelsStream without error', async () => { + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListNotificationChannelsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListNotificationChannelsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.monitoring.v3.NotificationChannel(), + ), + generateSampleMessage( + new protos.google.monitoring.v3.NotificationChannel(), + ), + generateSampleMessage( + new protos.google.monitoring.v3.NotificationChannel(), + ), + ]; + client.descriptors.page.listNotificationChannels.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listNotificationChannelsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.monitoring.v3.NotificationChannel[] = []; + stream.on( + 'data', + (response: protos.google.monitoring.v3.NotificationChannel) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + ( + client.descriptors.page.listNotificationChannels + .createStream as SinonStub + ) + .getCall(0) + .calledWith(client.innerApiCalls.listNotificationChannels, request), + ); + assert( + ( + client.descriptors.page.listNotificationChannels + .createStream as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); - it('uses async iteration with listNotificationChannels without error', async () => { - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListNotificationChannelsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListNotificationChannelsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.monitoring.v3.NotificationChannel()), - generateSampleMessage(new protos.google.monitoring.v3.NotificationChannel()), - generateSampleMessage(new protos.google.monitoring.v3.NotificationChannel()), - ]; - client.descriptors.page.listNotificationChannels.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.monitoring.v3.INotificationChannel[] = []; - const iterable = client.listNotificationChannelsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listNotificationChannels.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listNotificationChannels.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listNotificationChannelsStream with error', async () => { + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListNotificationChannelsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListNotificationChannelsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listNotificationChannels.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listNotificationChannelsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.monitoring.v3.NotificationChannel[] = []; + stream.on( + 'data', + (response: protos.google.monitoring.v3.NotificationChannel) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + ( + client.descriptors.page.listNotificationChannels + .createStream as SinonStub + ) + .getCall(0) + .calledWith(client.innerApiCalls.listNotificationChannels, request), + ); + assert( + ( + client.descriptors.page.listNotificationChannels + .createStream as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); - it('uses async iteration with listNotificationChannels with error', async () => { - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListNotificationChannelsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListNotificationChannelsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listNotificationChannels.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listNotificationChannelsAsync(request); - await assert.rejects(async () => { - const responses: protos.google.monitoring.v3.INotificationChannel[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listNotificationChannels.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listNotificationChannels.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listNotificationChannels without error', async () => { + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListNotificationChannelsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListNotificationChannelsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.monitoring.v3.NotificationChannel(), + ), + generateSampleMessage( + new protos.google.monitoring.v3.NotificationChannel(), + ), + generateSampleMessage( + new protos.google.monitoring.v3.NotificationChannel(), + ), + ]; + client.descriptors.page.listNotificationChannels.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.monitoring.v3.INotificationChannel[] = []; + const iterable = client.listNotificationChannelsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listNotificationChannels + .asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + ( + client.descriptors.page.listNotificationChannels + .asyncIterate as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); }); - describe('Path templates', () => { - - describe('folderAlertPolicy', () => { - const fakePath = "/rendered/path/folderAlertPolicy"; - const expectedParameters = { - folder: "folderValue", - alert_policy: "alertPolicyValue", - }; - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.folderAlertPolicyPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderAlertPolicyPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderAlertPolicyPath', () => { - const result = client.folderAlertPolicyPath("folderValue", "alertPolicyValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderAlertPolicyPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderAlertPolicyName', () => { - const result = client.matchFolderFromFolderAlertPolicyName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderAlertPolicyPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchAlertPolicyFromFolderAlertPolicyName', () => { - const result = client.matchAlertPolicyFromFolderAlertPolicyName(fakePath); - assert.strictEqual(result, "alertPolicyValue"); - assert((client.pathTemplates.folderAlertPolicyPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('uses async iteration with listNotificationChannels with error', async () => { + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListNotificationChannelsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListNotificationChannelsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listNotificationChannels.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listNotificationChannelsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.monitoring.v3.INotificationChannel[] = + []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listNotificationChannels + .asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + ( + client.descriptors.page.listNotificationChannels + .asyncIterate as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); + }); + + describe('Path templates', () => { + describe('folderAlertPolicy', () => { + const fakePath = '/rendered/path/folderAlertPolicy'; + const expectedParameters = { + folder: 'folderValue', + alert_policy: 'alertPolicyValue', + }; + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.folderAlertPolicyPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderAlertPolicyPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderAlertPolicyPath', () => { + const result = client.folderAlertPolicyPath( + 'folderValue', + 'alertPolicyValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.folderAlertPolicyPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderAlertPolicyName', () => { + const result = client.matchFolderFromFolderAlertPolicyName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + ( + client.pathTemplates.folderAlertPolicyPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchAlertPolicyFromFolderAlertPolicyName', () => { + const result = + client.matchAlertPolicyFromFolderAlertPolicyName(fakePath); + assert.strictEqual(result, 'alertPolicyValue'); + assert( + ( + client.pathTemplates.folderAlertPolicyPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('folderAlertPolicyCondition', () => { - const fakePath = "/rendered/path/folderAlertPolicyCondition"; - const expectedParameters = { - folder: "folderValue", - alert_policy: "alertPolicyValue", - condition: "conditionValue", - }; - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.folderAlertPolicyConditionPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderAlertPolicyConditionPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderAlertPolicyConditionPath', () => { - const result = client.folderAlertPolicyConditionPath("folderValue", "alertPolicyValue", "conditionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderAlertPolicyConditionPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderAlertPolicyConditionName', () => { - const result = client.matchFolderFromFolderAlertPolicyConditionName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderAlertPolicyConditionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchAlertPolicyFromFolderAlertPolicyConditionName', () => { - const result = client.matchAlertPolicyFromFolderAlertPolicyConditionName(fakePath); - assert.strictEqual(result, "alertPolicyValue"); - assert((client.pathTemplates.folderAlertPolicyConditionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchConditionFromFolderAlertPolicyConditionName', () => { - const result = client.matchConditionFromFolderAlertPolicyConditionName(fakePath); - assert.strictEqual(result, "conditionValue"); - assert((client.pathTemplates.folderAlertPolicyConditionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('folderAlertPolicyCondition', () => { + const fakePath = '/rendered/path/folderAlertPolicyCondition'; + const expectedParameters = { + folder: 'folderValue', + alert_policy: 'alertPolicyValue', + condition: 'conditionValue', + }; + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.folderAlertPolicyConditionPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderAlertPolicyConditionPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderAlertPolicyConditionPath', () => { + const result = client.folderAlertPolicyConditionPath( + 'folderValue', + 'alertPolicyValue', + 'conditionValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.folderAlertPolicyConditionPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderAlertPolicyConditionName', () => { + const result = + client.matchFolderFromFolderAlertPolicyConditionName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + ( + client.pathTemplates.folderAlertPolicyConditionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchAlertPolicyFromFolderAlertPolicyConditionName', () => { + const result = + client.matchAlertPolicyFromFolderAlertPolicyConditionName(fakePath); + assert.strictEqual(result, 'alertPolicyValue'); + assert( + ( + client.pathTemplates.folderAlertPolicyConditionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchConditionFromFolderAlertPolicyConditionName', () => { + const result = + client.matchConditionFromFolderAlertPolicyConditionName(fakePath); + assert.strictEqual(result, 'conditionValue'); + assert( + ( + client.pathTemplates.folderAlertPolicyConditionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('folderChannelDescriptor', () => { - const fakePath = "/rendered/path/folderChannelDescriptor"; - const expectedParameters = { - folder: "folderValue", - channel_descriptor: "channelDescriptorValue", - }; - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.folderChannelDescriptorPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderChannelDescriptorPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderChannelDescriptorPath', () => { - const result = client.folderChannelDescriptorPath("folderValue", "channelDescriptorValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderChannelDescriptorPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderChannelDescriptorName', () => { - const result = client.matchFolderFromFolderChannelDescriptorName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderChannelDescriptorPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchChannelDescriptorFromFolderChannelDescriptorName', () => { - const result = client.matchChannelDescriptorFromFolderChannelDescriptorName(fakePath); - assert.strictEqual(result, "channelDescriptorValue"); - assert((client.pathTemplates.folderChannelDescriptorPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('folderChannelDescriptor', () => { + const fakePath = '/rendered/path/folderChannelDescriptor'; + const expectedParameters = { + folder: 'folderValue', + channel_descriptor: 'channelDescriptorValue', + }; + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.folderChannelDescriptorPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderChannelDescriptorPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderChannelDescriptorPath', () => { + const result = client.folderChannelDescriptorPath( + 'folderValue', + 'channelDescriptorValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.folderChannelDescriptorPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderChannelDescriptorName', () => { + const result = + client.matchFolderFromFolderChannelDescriptorName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + ( + client.pathTemplates.folderChannelDescriptorPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchChannelDescriptorFromFolderChannelDescriptorName', () => { + const result = + client.matchChannelDescriptorFromFolderChannelDescriptorName( + fakePath, + ); + assert.strictEqual(result, 'channelDescriptorValue'); + assert( + ( + client.pathTemplates.folderChannelDescriptorPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('folderGroup', () => { - const fakePath = "/rendered/path/folderGroup"; - const expectedParameters = { - folder: "folderValue", - group: "groupValue", - }; - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.folderGroupPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderGroupPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderGroupPath', () => { - const result = client.folderGroupPath("folderValue", "groupValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderGroupPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderGroupName', () => { - const result = client.matchFolderFromFolderGroupName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderGroupPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchGroupFromFolderGroupName', () => { - const result = client.matchGroupFromFolderGroupName(fakePath); - assert.strictEqual(result, "groupValue"); - assert((client.pathTemplates.folderGroupPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('folderGroup', () => { + const fakePath = '/rendered/path/folderGroup'; + const expectedParameters = { + folder: 'folderValue', + group: 'groupValue', + }; + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.folderGroupPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderGroupPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderGroupPath', () => { + const result = client.folderGroupPath('folderValue', 'groupValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.folderGroupPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderGroupName', () => { + const result = client.matchFolderFromFolderGroupName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + (client.pathTemplates.folderGroupPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchGroupFromFolderGroupName', () => { + const result = client.matchGroupFromFolderGroupName(fakePath); + assert.strictEqual(result, 'groupValue'); + assert( + (client.pathTemplates.folderGroupPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('folderNotificationChannel', () => { - const fakePath = "/rendered/path/folderNotificationChannel"; - const expectedParameters = { - folder: "folderValue", - notification_channel: "notificationChannelValue", - }; - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.folderNotificationChannelPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderNotificationChannelPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderNotificationChannelPath', () => { - const result = client.folderNotificationChannelPath("folderValue", "notificationChannelValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderNotificationChannelPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderNotificationChannelName', () => { - const result = client.matchFolderFromFolderNotificationChannelName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderNotificationChannelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchNotificationChannelFromFolderNotificationChannelName', () => { - const result = client.matchNotificationChannelFromFolderNotificationChannelName(fakePath); - assert.strictEqual(result, "notificationChannelValue"); - assert((client.pathTemplates.folderNotificationChannelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('folderNotificationChannel', () => { + const fakePath = '/rendered/path/folderNotificationChannel'; + const expectedParameters = { + folder: 'folderValue', + notification_channel: 'notificationChannelValue', + }; + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.folderNotificationChannelPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderNotificationChannelPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderNotificationChannelPath', () => { + const result = client.folderNotificationChannelPath( + 'folderValue', + 'notificationChannelValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.folderNotificationChannelPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderNotificationChannelName', () => { + const result = + client.matchFolderFromFolderNotificationChannelName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + ( + client.pathTemplates.folderNotificationChannelPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchNotificationChannelFromFolderNotificationChannelName', () => { + const result = + client.matchNotificationChannelFromFolderNotificationChannelName( + fakePath, + ); + assert.strictEqual(result, 'notificationChannelValue'); + assert( + ( + client.pathTemplates.folderNotificationChannelPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('folderService', () => { - const fakePath = "/rendered/path/folderService"; - const expectedParameters = { - folder: "folderValue", - service: "serviceValue", - }; - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.folderServicePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderServicePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderServicePath', () => { - const result = client.folderServicePath("folderValue", "serviceValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderServicePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderServiceName', () => { - const result = client.matchFolderFromFolderServiceName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderServicePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServiceFromFolderServiceName', () => { - const result = client.matchServiceFromFolderServiceName(fakePath); - assert.strictEqual(result, "serviceValue"); - assert((client.pathTemplates.folderServicePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('folderService', () => { + const fakePath = '/rendered/path/folderService'; + const expectedParameters = { + folder: 'folderValue', + service: 'serviceValue', + }; + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.folderServicePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderServicePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderServicePath', () => { + const result = client.folderServicePath('folderValue', 'serviceValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.folderServicePathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderServiceName', () => { + const result = client.matchFolderFromFolderServiceName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + (client.pathTemplates.folderServicePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServiceFromFolderServiceName', () => { + const result = client.matchServiceFromFolderServiceName(fakePath); + assert.strictEqual(result, 'serviceValue'); + assert( + (client.pathTemplates.folderServicePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('folderServiceServiceLevelObjective', () => { - const fakePath = "/rendered/path/folderServiceServiceLevelObjective"; - const expectedParameters = { - folder: "folderValue", - service: "serviceValue", - service_level_objective: "serviceLevelObjectiveValue", - }; - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderServiceServiceLevelObjectivePath', () => { - const result = client.folderServiceServiceLevelObjectivePath("folderValue", "serviceValue", "serviceLevelObjectiveValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderServiceServiceLevelObjectiveName', () => { - const result = client.matchFolderFromFolderServiceServiceLevelObjectiveName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServiceFromFolderServiceServiceLevelObjectiveName', () => { - const result = client.matchServiceFromFolderServiceServiceLevelObjectiveName(fakePath); - assert.strictEqual(result, "serviceValue"); - assert((client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServiceLevelObjectiveFromFolderServiceServiceLevelObjectiveName', () => { - const result = client.matchServiceLevelObjectiveFromFolderServiceServiceLevelObjectiveName(fakePath); - assert.strictEqual(result, "serviceLevelObjectiveValue"); - assert((client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('folderServiceServiceLevelObjective', () => { + const fakePath = '/rendered/path/folderServiceServiceLevelObjective'; + const expectedParameters = { + folder: 'folderValue', + service: 'serviceValue', + service_level_objective: 'serviceLevelObjectiveValue', + }; + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('folderServiceServiceLevelObjectivePath', () => { + const result = client.folderServiceServiceLevelObjectivePath( + 'folderValue', + 'serviceValue', + 'serviceLevelObjectiveValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderServiceServiceLevelObjectiveName', () => { + const result = + client.matchFolderFromFolderServiceServiceLevelObjectiveName( + fakePath, + ); + assert.strictEqual(result, 'folderValue'); + assert( + ( + client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServiceFromFolderServiceServiceLevelObjectiveName', () => { + const result = + client.matchServiceFromFolderServiceServiceLevelObjectiveName( + fakePath, + ); + assert.strictEqual(result, 'serviceValue'); + assert( + ( + client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServiceLevelObjectiveFromFolderServiceServiceLevelObjectiveName', () => { + const result = + client.matchServiceLevelObjectiveFromFolderServiceServiceLevelObjectiveName( + fakePath, + ); + assert.strictEqual(result, 'serviceLevelObjectiveValue'); + assert( + ( + client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('folderUptimeCheckConfig', () => { - const fakePath = "/rendered/path/folderUptimeCheckConfig"; - const expectedParameters = { - folder: "folderValue", - uptime_check_config: "uptimeCheckConfigValue", - }; - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.folderUptimeCheckConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderUptimeCheckConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderUptimeCheckConfigPath', () => { - const result = client.folderUptimeCheckConfigPath("folderValue", "uptimeCheckConfigValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderUptimeCheckConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderUptimeCheckConfigName', () => { - const result = client.matchFolderFromFolderUptimeCheckConfigName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderUptimeCheckConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchUptimeCheckConfigFromFolderUptimeCheckConfigName', () => { - const result = client.matchUptimeCheckConfigFromFolderUptimeCheckConfigName(fakePath); - assert.strictEqual(result, "uptimeCheckConfigValue"); - assert((client.pathTemplates.folderUptimeCheckConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('folderUptimeCheckConfig', () => { + const fakePath = '/rendered/path/folderUptimeCheckConfig'; + const expectedParameters = { + folder: 'folderValue', + uptime_check_config: 'uptimeCheckConfigValue', + }; + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.folderUptimeCheckConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderUptimeCheckConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderUptimeCheckConfigPath', () => { + const result = client.folderUptimeCheckConfigPath( + 'folderValue', + 'uptimeCheckConfigValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.folderUptimeCheckConfigPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderUptimeCheckConfigName', () => { + const result = + client.matchFolderFromFolderUptimeCheckConfigName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + ( + client.pathTemplates.folderUptimeCheckConfigPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchUptimeCheckConfigFromFolderUptimeCheckConfigName', () => { + const result = + client.matchUptimeCheckConfigFromFolderUptimeCheckConfigName( + fakePath, + ); + assert.strictEqual(result, 'uptimeCheckConfigValue'); + assert( + ( + client.pathTemplates.folderUptimeCheckConfigPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('organizationAlertPolicy', () => { - const fakePath = "/rendered/path/organizationAlertPolicy"; - const expectedParameters = { - organization: "organizationValue", - alert_policy: "alertPolicyValue", - }; - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.organizationAlertPolicyPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationAlertPolicyPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationAlertPolicyPath', () => { - const result = client.organizationAlertPolicyPath("organizationValue", "alertPolicyValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationAlertPolicyPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationAlertPolicyName', () => { - const result = client.matchOrganizationFromOrganizationAlertPolicyName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationAlertPolicyPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchAlertPolicyFromOrganizationAlertPolicyName', () => { - const result = client.matchAlertPolicyFromOrganizationAlertPolicyName(fakePath); - assert.strictEqual(result, "alertPolicyValue"); - assert((client.pathTemplates.organizationAlertPolicyPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('organizationAlertPolicy', () => { + const fakePath = '/rendered/path/organizationAlertPolicy'; + const expectedParameters = { + organization: 'organizationValue', + alert_policy: 'alertPolicyValue', + }; + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.organizationAlertPolicyPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.organizationAlertPolicyPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('organizationAlertPolicyPath', () => { + const result = client.organizationAlertPolicyPath( + 'organizationValue', + 'alertPolicyValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationAlertPolicyPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationAlertPolicyName', () => { + const result = + client.matchOrganizationFromOrganizationAlertPolicyName(fakePath); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationAlertPolicyPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchAlertPolicyFromOrganizationAlertPolicyName', () => { + const result = + client.matchAlertPolicyFromOrganizationAlertPolicyName(fakePath); + assert.strictEqual(result, 'alertPolicyValue'); + assert( + ( + client.pathTemplates.organizationAlertPolicyPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('organizationAlertPolicyCondition', () => { - const fakePath = "/rendered/path/organizationAlertPolicyCondition"; - const expectedParameters = { - organization: "organizationValue", - alert_policy: "alertPolicyValue", - condition: "conditionValue", - }; - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.organizationAlertPolicyConditionPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationAlertPolicyConditionPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationAlertPolicyConditionPath', () => { - const result = client.organizationAlertPolicyConditionPath("organizationValue", "alertPolicyValue", "conditionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationAlertPolicyConditionPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationAlertPolicyConditionName', () => { - const result = client.matchOrganizationFromOrganizationAlertPolicyConditionName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationAlertPolicyConditionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchAlertPolicyFromOrganizationAlertPolicyConditionName', () => { - const result = client.matchAlertPolicyFromOrganizationAlertPolicyConditionName(fakePath); - assert.strictEqual(result, "alertPolicyValue"); - assert((client.pathTemplates.organizationAlertPolicyConditionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchConditionFromOrganizationAlertPolicyConditionName', () => { - const result = client.matchConditionFromOrganizationAlertPolicyConditionName(fakePath); - assert.strictEqual(result, "conditionValue"); - assert((client.pathTemplates.organizationAlertPolicyConditionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('organizationAlertPolicyCondition', () => { + const fakePath = '/rendered/path/organizationAlertPolicyCondition'; + const expectedParameters = { + organization: 'organizationValue', + alert_policy: 'alertPolicyValue', + condition: 'conditionValue', + }; + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.organizationAlertPolicyConditionPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.organizationAlertPolicyConditionPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('organizationAlertPolicyConditionPath', () => { + const result = client.organizationAlertPolicyConditionPath( + 'organizationValue', + 'alertPolicyValue', + 'conditionValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationAlertPolicyConditionPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationAlertPolicyConditionName', () => { + const result = + client.matchOrganizationFromOrganizationAlertPolicyConditionName( + fakePath, + ); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationAlertPolicyConditionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchAlertPolicyFromOrganizationAlertPolicyConditionName', () => { + const result = + client.matchAlertPolicyFromOrganizationAlertPolicyConditionName( + fakePath, + ); + assert.strictEqual(result, 'alertPolicyValue'); + assert( + ( + client.pathTemplates.organizationAlertPolicyConditionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchConditionFromOrganizationAlertPolicyConditionName', () => { + const result = + client.matchConditionFromOrganizationAlertPolicyConditionName( + fakePath, + ); + assert.strictEqual(result, 'conditionValue'); + assert( + ( + client.pathTemplates.organizationAlertPolicyConditionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('organizationChannelDescriptor', () => { - const fakePath = "/rendered/path/organizationChannelDescriptor"; - const expectedParameters = { - organization: "organizationValue", - channel_descriptor: "channelDescriptorValue", - }; - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.organizationChannelDescriptorPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationChannelDescriptorPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationChannelDescriptorPath', () => { - const result = client.organizationChannelDescriptorPath("organizationValue", "channelDescriptorValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationChannelDescriptorPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationChannelDescriptorName', () => { - const result = client.matchOrganizationFromOrganizationChannelDescriptorName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationChannelDescriptorPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchChannelDescriptorFromOrganizationChannelDescriptorName', () => { - const result = client.matchChannelDescriptorFromOrganizationChannelDescriptorName(fakePath); - assert.strictEqual(result, "channelDescriptorValue"); - assert((client.pathTemplates.organizationChannelDescriptorPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('organizationChannelDescriptor', () => { + const fakePath = '/rendered/path/organizationChannelDescriptor'; + const expectedParameters = { + organization: 'organizationValue', + channel_descriptor: 'channelDescriptorValue', + }; + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.organizationChannelDescriptorPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.organizationChannelDescriptorPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('organizationChannelDescriptorPath', () => { + const result = client.organizationChannelDescriptorPath( + 'organizationValue', + 'channelDescriptorValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationChannelDescriptorPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationChannelDescriptorName', () => { + const result = + client.matchOrganizationFromOrganizationChannelDescriptorName( + fakePath, + ); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationChannelDescriptorPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchChannelDescriptorFromOrganizationChannelDescriptorName', () => { + const result = + client.matchChannelDescriptorFromOrganizationChannelDescriptorName( + fakePath, + ); + assert.strictEqual(result, 'channelDescriptorValue'); + assert( + ( + client.pathTemplates.organizationChannelDescriptorPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('organizationGroup', () => { - const fakePath = "/rendered/path/organizationGroup"; - const expectedParameters = { - organization: "organizationValue", - group: "groupValue", - }; - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.organizationGroupPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationGroupPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationGroupPath', () => { - const result = client.organizationGroupPath("organizationValue", "groupValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationGroupPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationGroupName', () => { - const result = client.matchOrganizationFromOrganizationGroupName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationGroupPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchGroupFromOrganizationGroupName', () => { - const result = client.matchGroupFromOrganizationGroupName(fakePath); - assert.strictEqual(result, "groupValue"); - assert((client.pathTemplates.organizationGroupPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('organizationGroup', () => { + const fakePath = '/rendered/path/organizationGroup'; + const expectedParameters = { + organization: 'organizationValue', + group: 'groupValue', + }; + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.organizationGroupPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.organizationGroupPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('organizationGroupPath', () => { + const result = client.organizationGroupPath( + 'organizationValue', + 'groupValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationGroupPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationGroupName', () => { + const result = + client.matchOrganizationFromOrganizationGroupName(fakePath); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationGroupPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchGroupFromOrganizationGroupName', () => { + const result = client.matchGroupFromOrganizationGroupName(fakePath); + assert.strictEqual(result, 'groupValue'); + assert( + ( + client.pathTemplates.organizationGroupPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('organizationNotificationChannel', () => { - const fakePath = "/rendered/path/organizationNotificationChannel"; - const expectedParameters = { - organization: "organizationValue", - notification_channel: "notificationChannelValue", - }; - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.organizationNotificationChannelPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationNotificationChannelPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationNotificationChannelPath', () => { - const result = client.organizationNotificationChannelPath("organizationValue", "notificationChannelValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationNotificationChannelPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationNotificationChannelName', () => { - const result = client.matchOrganizationFromOrganizationNotificationChannelName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationNotificationChannelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchNotificationChannelFromOrganizationNotificationChannelName', () => { - const result = client.matchNotificationChannelFromOrganizationNotificationChannelName(fakePath); - assert.strictEqual(result, "notificationChannelValue"); - assert((client.pathTemplates.organizationNotificationChannelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('organizationNotificationChannel', () => { + const fakePath = '/rendered/path/organizationNotificationChannel'; + const expectedParameters = { + organization: 'organizationValue', + notification_channel: 'notificationChannelValue', + }; + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.organizationNotificationChannelPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.organizationNotificationChannelPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('organizationNotificationChannelPath', () => { + const result = client.organizationNotificationChannelPath( + 'organizationValue', + 'notificationChannelValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationNotificationChannelPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationNotificationChannelName', () => { + const result = + client.matchOrganizationFromOrganizationNotificationChannelName( + fakePath, + ); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationNotificationChannelPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchNotificationChannelFromOrganizationNotificationChannelName', () => { + const result = + client.matchNotificationChannelFromOrganizationNotificationChannelName( + fakePath, + ); + assert.strictEqual(result, 'notificationChannelValue'); + assert( + ( + client.pathTemplates.organizationNotificationChannelPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('organizationService', () => { - const fakePath = "/rendered/path/organizationService"; - const expectedParameters = { - organization: "organizationValue", - service: "serviceValue", - }; - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.organizationServicePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationServicePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationServicePath', () => { - const result = client.organizationServicePath("organizationValue", "serviceValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationServicePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationServiceName', () => { - const result = client.matchOrganizationFromOrganizationServiceName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationServicePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServiceFromOrganizationServiceName', () => { - const result = client.matchServiceFromOrganizationServiceName(fakePath); - assert.strictEqual(result, "serviceValue"); - assert((client.pathTemplates.organizationServicePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('organizationService', () => { + const fakePath = '/rendered/path/organizationService'; + const expectedParameters = { + organization: 'organizationValue', + service: 'serviceValue', + }; + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.organizationServicePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.organizationServicePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('organizationServicePath', () => { + const result = client.organizationServicePath( + 'organizationValue', + 'serviceValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationServicePathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationServiceName', () => { + const result = + client.matchOrganizationFromOrganizationServiceName(fakePath); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationServicePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServiceFromOrganizationServiceName', () => { + const result = client.matchServiceFromOrganizationServiceName(fakePath); + assert.strictEqual(result, 'serviceValue'); + assert( + ( + client.pathTemplates.organizationServicePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('organizationServiceServiceLevelObjective', () => { - const fakePath = "/rendered/path/organizationServiceServiceLevelObjective"; - const expectedParameters = { - organization: "organizationValue", - service: "serviceValue", - service_level_objective: "serviceLevelObjectiveValue", - }; - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationServiceServiceLevelObjectivePath', () => { - const result = client.organizationServiceServiceLevelObjectivePath("organizationValue", "serviceValue", "serviceLevelObjectiveValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationServiceServiceLevelObjectiveName', () => { - const result = client.matchOrganizationFromOrganizationServiceServiceLevelObjectiveName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServiceFromOrganizationServiceServiceLevelObjectiveName', () => { - const result = client.matchServiceFromOrganizationServiceServiceLevelObjectiveName(fakePath); - assert.strictEqual(result, "serviceValue"); - assert((client.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServiceLevelObjectiveFromOrganizationServiceServiceLevelObjectiveName', () => { - const result = client.matchServiceLevelObjectiveFromOrganizationServiceServiceLevelObjectiveName(fakePath); - assert.strictEqual(result, "serviceLevelObjectiveValue"); - assert((client.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('organizationServiceServiceLevelObjective', () => { + const fakePath = + '/rendered/path/organizationServiceServiceLevelObjective'; + const expectedParameters = { + organization: 'organizationValue', + service: 'serviceValue', + service_level_objective: 'serviceLevelObjectiveValue', + }; + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('organizationServiceServiceLevelObjectivePath', () => { + const result = client.organizationServiceServiceLevelObjectivePath( + 'organizationValue', + 'serviceValue', + 'serviceLevelObjectiveValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates + .organizationServiceServiceLevelObjectivePathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationServiceServiceLevelObjectiveName', () => { + const result = + client.matchOrganizationFromOrganizationServiceServiceLevelObjectiveName( + fakePath, + ); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates + .organizationServiceServiceLevelObjectivePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServiceFromOrganizationServiceServiceLevelObjectiveName', () => { + const result = + client.matchServiceFromOrganizationServiceServiceLevelObjectiveName( + fakePath, + ); + assert.strictEqual(result, 'serviceValue'); + assert( + ( + client.pathTemplates + .organizationServiceServiceLevelObjectivePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServiceLevelObjectiveFromOrganizationServiceServiceLevelObjectiveName', () => { + const result = + client.matchServiceLevelObjectiveFromOrganizationServiceServiceLevelObjectiveName( + fakePath, + ); + assert.strictEqual(result, 'serviceLevelObjectiveValue'); + assert( + ( + client.pathTemplates + .organizationServiceServiceLevelObjectivePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('organizationUptimeCheckConfig', () => { - const fakePath = "/rendered/path/organizationUptimeCheckConfig"; - const expectedParameters = { - organization: "organizationValue", - uptime_check_config: "uptimeCheckConfigValue", - }; - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.organizationUptimeCheckConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationUptimeCheckConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationUptimeCheckConfigPath', () => { - const result = client.organizationUptimeCheckConfigPath("organizationValue", "uptimeCheckConfigValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationUptimeCheckConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationUptimeCheckConfigName', () => { - const result = client.matchOrganizationFromOrganizationUptimeCheckConfigName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationUptimeCheckConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchUptimeCheckConfigFromOrganizationUptimeCheckConfigName', () => { - const result = client.matchUptimeCheckConfigFromOrganizationUptimeCheckConfigName(fakePath); - assert.strictEqual(result, "uptimeCheckConfigValue"); - assert((client.pathTemplates.organizationUptimeCheckConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('organizationUptimeCheckConfig', () => { + const fakePath = '/rendered/path/organizationUptimeCheckConfig'; + const expectedParameters = { + organization: 'organizationValue', + uptime_check_config: 'uptimeCheckConfigValue', + }; + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.organizationUptimeCheckConfigPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.organizationUptimeCheckConfigPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('organizationUptimeCheckConfigPath', () => { + const result = client.organizationUptimeCheckConfigPath( + 'organizationValue', + 'uptimeCheckConfigValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationUptimeCheckConfigPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationUptimeCheckConfigName', () => { + const result = + client.matchOrganizationFromOrganizationUptimeCheckConfigName( + fakePath, + ); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationUptimeCheckConfigPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchUptimeCheckConfigFromOrganizationUptimeCheckConfigName', () => { + const result = + client.matchUptimeCheckConfigFromOrganizationUptimeCheckConfigName( + fakePath, + ); + assert.strictEqual(result, 'uptimeCheckConfigValue'); + assert( + ( + client.pathTemplates.organizationUptimeCheckConfigPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectAlertPolicy', () => { - const fakePath = "/rendered/path/projectAlertPolicy"; - const expectedParameters = { - project: "projectValue", - alert_policy: "alertPolicyValue", - }; - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.projectAlertPolicyPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectAlertPolicyPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectAlertPolicyPath', () => { - const result = client.projectAlertPolicyPath("projectValue", "alertPolicyValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectAlertPolicyPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectAlertPolicyName', () => { - const result = client.matchProjectFromProjectAlertPolicyName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectAlertPolicyPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchAlertPolicyFromProjectAlertPolicyName', () => { - const result = client.matchAlertPolicyFromProjectAlertPolicyName(fakePath); - assert.strictEqual(result, "alertPolicyValue"); - assert((client.pathTemplates.projectAlertPolicyPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectAlertPolicy', () => { + const fakePath = '/rendered/path/projectAlertPolicy'; + const expectedParameters = { + project: 'projectValue', + alert_policy: 'alertPolicyValue', + }; + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.projectAlertPolicyPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectAlertPolicyPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectAlertPolicyPath', () => { + const result = client.projectAlertPolicyPath( + 'projectValue', + 'alertPolicyValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.projectAlertPolicyPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectAlertPolicyName', () => { + const result = client.matchProjectFromProjectAlertPolicyName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.projectAlertPolicyPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchAlertPolicyFromProjectAlertPolicyName', () => { + const result = + client.matchAlertPolicyFromProjectAlertPolicyName(fakePath); + assert.strictEqual(result, 'alertPolicyValue'); + assert( + ( + client.pathTemplates.projectAlertPolicyPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectAlertPolicyCondition', () => { - const fakePath = "/rendered/path/projectAlertPolicyCondition"; - const expectedParameters = { - project: "projectValue", - alert_policy: "alertPolicyValue", - condition: "conditionValue", - }; - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.projectAlertPolicyConditionPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectAlertPolicyConditionPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectAlertPolicyConditionPath', () => { - const result = client.projectAlertPolicyConditionPath("projectValue", "alertPolicyValue", "conditionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectAlertPolicyConditionPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectAlertPolicyConditionName', () => { - const result = client.matchProjectFromProjectAlertPolicyConditionName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectAlertPolicyConditionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchAlertPolicyFromProjectAlertPolicyConditionName', () => { - const result = client.matchAlertPolicyFromProjectAlertPolicyConditionName(fakePath); - assert.strictEqual(result, "alertPolicyValue"); - assert((client.pathTemplates.projectAlertPolicyConditionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchConditionFromProjectAlertPolicyConditionName', () => { - const result = client.matchConditionFromProjectAlertPolicyConditionName(fakePath); - assert.strictEqual(result, "conditionValue"); - assert((client.pathTemplates.projectAlertPolicyConditionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectAlertPolicyCondition', () => { + const fakePath = '/rendered/path/projectAlertPolicyCondition'; + const expectedParameters = { + project: 'projectValue', + alert_policy: 'alertPolicyValue', + condition: 'conditionValue', + }; + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.projectAlertPolicyConditionPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.projectAlertPolicyConditionPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectAlertPolicyConditionPath', () => { + const result = client.projectAlertPolicyConditionPath( + 'projectValue', + 'alertPolicyValue', + 'conditionValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.projectAlertPolicyConditionPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectAlertPolicyConditionName', () => { + const result = + client.matchProjectFromProjectAlertPolicyConditionName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.projectAlertPolicyConditionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchAlertPolicyFromProjectAlertPolicyConditionName', () => { + const result = + client.matchAlertPolicyFromProjectAlertPolicyConditionName(fakePath); + assert.strictEqual(result, 'alertPolicyValue'); + assert( + ( + client.pathTemplates.projectAlertPolicyConditionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchConditionFromProjectAlertPolicyConditionName', () => { + const result = + client.matchConditionFromProjectAlertPolicyConditionName(fakePath); + assert.strictEqual(result, 'conditionValue'); + assert( + ( + client.pathTemplates.projectAlertPolicyConditionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectChannelDescriptor', () => { - const fakePath = "/rendered/path/projectChannelDescriptor"; - const expectedParameters = { - project: "projectValue", - channel_descriptor: "channelDescriptorValue", - }; - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.projectChannelDescriptorPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectChannelDescriptorPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectChannelDescriptorPath', () => { - const result = client.projectChannelDescriptorPath("projectValue", "channelDescriptorValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectChannelDescriptorPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectChannelDescriptorName', () => { - const result = client.matchProjectFromProjectChannelDescriptorName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectChannelDescriptorPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchChannelDescriptorFromProjectChannelDescriptorName', () => { - const result = client.matchChannelDescriptorFromProjectChannelDescriptorName(fakePath); - assert.strictEqual(result, "channelDescriptorValue"); - assert((client.pathTemplates.projectChannelDescriptorPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectChannelDescriptor', () => { + const fakePath = '/rendered/path/projectChannelDescriptor'; + const expectedParameters = { + project: 'projectValue', + channel_descriptor: 'channelDescriptorValue', + }; + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.projectChannelDescriptorPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectChannelDescriptorPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectChannelDescriptorPath', () => { + const result = client.projectChannelDescriptorPath( + 'projectValue', + 'channelDescriptorValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.projectChannelDescriptorPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectChannelDescriptorName', () => { + const result = + client.matchProjectFromProjectChannelDescriptorName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.projectChannelDescriptorPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchChannelDescriptorFromProjectChannelDescriptorName', () => { + const result = + client.matchChannelDescriptorFromProjectChannelDescriptorName( + fakePath, + ); + assert.strictEqual(result, 'channelDescriptorValue'); + assert( + ( + client.pathTemplates.projectChannelDescriptorPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectGroup', () => { - const fakePath = "/rendered/path/projectGroup"; - const expectedParameters = { - project: "projectValue", - group: "groupValue", - }; - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.projectGroupPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectGroupPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectGroupPath', () => { - const result = client.projectGroupPath("projectValue", "groupValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectGroupPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectGroupName', () => { - const result = client.matchProjectFromProjectGroupName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectGroupPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchGroupFromProjectGroupName', () => { - const result = client.matchGroupFromProjectGroupName(fakePath); - assert.strictEqual(result, "groupValue"); - assert((client.pathTemplates.projectGroupPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectGroup', () => { + const fakePath = '/rendered/path/projectGroup'; + const expectedParameters = { + project: 'projectValue', + group: 'groupValue', + }; + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.projectGroupPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectGroupPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectGroupPath', () => { + const result = client.projectGroupPath('projectValue', 'groupValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.projectGroupPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectGroupName', () => { + const result = client.matchProjectFromProjectGroupName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.projectGroupPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchGroupFromProjectGroupName', () => { + const result = client.matchGroupFromProjectGroupName(fakePath); + assert.strictEqual(result, 'groupValue'); + assert( + (client.pathTemplates.projectGroupPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectNotificationChannel', () => { - const fakePath = "/rendered/path/projectNotificationChannel"; - const expectedParameters = { - project: "projectValue", - notification_channel: "notificationChannelValue", - }; - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.projectNotificationChannelPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectNotificationChannelPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectNotificationChannelPath', () => { - const result = client.projectNotificationChannelPath("projectValue", "notificationChannelValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectNotificationChannelPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectNotificationChannelName', () => { - const result = client.matchProjectFromProjectNotificationChannelName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectNotificationChannelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchNotificationChannelFromProjectNotificationChannelName', () => { - const result = client.matchNotificationChannelFromProjectNotificationChannelName(fakePath); - assert.strictEqual(result, "notificationChannelValue"); - assert((client.pathTemplates.projectNotificationChannelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectNotificationChannel', () => { + const fakePath = '/rendered/path/projectNotificationChannel'; + const expectedParameters = { + project: 'projectValue', + notification_channel: 'notificationChannelValue', + }; + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.projectNotificationChannelPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectNotificationChannelPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectNotificationChannelPath', () => { + const result = client.projectNotificationChannelPath( + 'projectValue', + 'notificationChannelValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.projectNotificationChannelPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectNotificationChannelName', () => { + const result = + client.matchProjectFromProjectNotificationChannelName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.projectNotificationChannelPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchNotificationChannelFromProjectNotificationChannelName', () => { + const result = + client.matchNotificationChannelFromProjectNotificationChannelName( + fakePath, + ); + assert.strictEqual(result, 'notificationChannelValue'); + assert( + ( + client.pathTemplates.projectNotificationChannelPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectService', () => { - const fakePath = "/rendered/path/projectService"; - const expectedParameters = { - project: "projectValue", - service: "serviceValue", - }; - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.projectServicePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectServicePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectServicePath', () => { - const result = client.projectServicePath("projectValue", "serviceValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectServicePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectServiceName', () => { - const result = client.matchProjectFromProjectServiceName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectServicePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServiceFromProjectServiceName', () => { - const result = client.matchServiceFromProjectServiceName(fakePath); - assert.strictEqual(result, "serviceValue"); - assert((client.pathTemplates.projectServicePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectService', () => { + const fakePath = '/rendered/path/projectService'; + const expectedParameters = { + project: 'projectValue', + service: 'serviceValue', + }; + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.projectServicePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectServicePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectServicePath', () => { + const result = client.projectServicePath( + 'projectValue', + 'serviceValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.projectServicePathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectServiceName', () => { + const result = client.matchProjectFromProjectServiceName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.projectServicePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServiceFromProjectServiceName', () => { + const result = client.matchServiceFromProjectServiceName(fakePath); + assert.strictEqual(result, 'serviceValue'); + assert( + (client.pathTemplates.projectServicePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectServiceServiceLevelObjective', () => { - const fakePath = "/rendered/path/projectServiceServiceLevelObjective"; - const expectedParameters = { - project: "projectValue", - service: "serviceValue", - service_level_objective: "serviceLevelObjectiveValue", - }; - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectServiceServiceLevelObjectivePath', () => { - const result = client.projectServiceServiceLevelObjectivePath("projectValue", "serviceValue", "serviceLevelObjectiveValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectServiceServiceLevelObjectiveName', () => { - const result = client.matchProjectFromProjectServiceServiceLevelObjectiveName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServiceFromProjectServiceServiceLevelObjectiveName', () => { - const result = client.matchServiceFromProjectServiceServiceLevelObjectiveName(fakePath); - assert.strictEqual(result, "serviceValue"); - assert((client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServiceLevelObjectiveFromProjectServiceServiceLevelObjectiveName', () => { - const result = client.matchServiceLevelObjectiveFromProjectServiceServiceLevelObjectiveName(fakePath); - assert.strictEqual(result, "serviceLevelObjectiveValue"); - assert((client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectServiceServiceLevelObjective', () => { + const fakePath = '/rendered/path/projectServiceServiceLevelObjective'; + const expectedParameters = { + project: 'projectValue', + service: 'serviceValue', + service_level_objective: 'serviceLevelObjectiveValue', + }; + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('projectServiceServiceLevelObjectivePath', () => { + const result = client.projectServiceServiceLevelObjectivePath( + 'projectValue', + 'serviceValue', + 'serviceLevelObjectiveValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectServiceServiceLevelObjectiveName', () => { + const result = + client.matchProjectFromProjectServiceServiceLevelObjectiveName( + fakePath, + ); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServiceFromProjectServiceServiceLevelObjectiveName', () => { + const result = + client.matchServiceFromProjectServiceServiceLevelObjectiveName( + fakePath, + ); + assert.strictEqual(result, 'serviceValue'); + assert( + ( + client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServiceLevelObjectiveFromProjectServiceServiceLevelObjectiveName', () => { + const result = + client.matchServiceLevelObjectiveFromProjectServiceServiceLevelObjectiveName( + fakePath, + ); + assert.strictEqual(result, 'serviceLevelObjectiveValue'); + assert( + ( + client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectUptimeCheckConfig', () => { - const fakePath = "/rendered/path/projectUptimeCheckConfig"; - const expectedParameters = { - project: "projectValue", - uptime_check_config: "uptimeCheckConfigValue", - }; - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.projectUptimeCheckConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectUptimeCheckConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectUptimeCheckConfigPath', () => { - const result = client.projectUptimeCheckConfigPath("projectValue", "uptimeCheckConfigValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectUptimeCheckConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectUptimeCheckConfigName', () => { - const result = client.matchProjectFromProjectUptimeCheckConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectUptimeCheckConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchUptimeCheckConfigFromProjectUptimeCheckConfigName', () => { - const result = client.matchUptimeCheckConfigFromProjectUptimeCheckConfigName(fakePath); - assert.strictEqual(result, "uptimeCheckConfigValue"); - assert((client.pathTemplates.projectUptimeCheckConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectUptimeCheckConfig', () => { + const fakePath = '/rendered/path/projectUptimeCheckConfig'; + const expectedParameters = { + project: 'projectValue', + uptime_check_config: 'uptimeCheckConfigValue', + }; + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.projectUptimeCheckConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectUptimeCheckConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectUptimeCheckConfigPath', () => { + const result = client.projectUptimeCheckConfigPath( + 'projectValue', + 'uptimeCheckConfigValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.projectUptimeCheckConfigPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectUptimeCheckConfigName', () => { + const result = + client.matchProjectFromProjectUptimeCheckConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.projectUptimeCheckConfigPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchUptimeCheckConfigFromProjectUptimeCheckConfigName', () => { + const result = + client.matchUptimeCheckConfigFromProjectUptimeCheckConfigName( + fakePath, + ); + assert.strictEqual(result, 'uptimeCheckConfigValue'); + assert( + ( + client.pathTemplates.projectUptimeCheckConfigPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/core/generator/gapic-generator-typescript/baselines/monitoring-esm/esm/test/gapic_service_monitoring_service_v3.ts.baseline b/core/generator/gapic-generator-typescript/baselines/monitoring-esm/esm/test/gapic_service_monitoring_service_v3.ts.baseline index eaa15a638191..6f8ffb898ada 100644 --- a/core/generator/gapic-generator-typescript/baselines/monitoring-esm/esm/test/gapic_service_monitoring_service_v3.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/monitoring-esm/esm/test/gapic_service_monitoring_service_v3.ts.baseline @@ -20,16 +20,16 @@ import * as protos from '../../protos/protos.js'; import assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as servicemonitoringserviceModule from '../src/index.js'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; -import {protobuf} from 'google-gax'; +import { protobuf } from 'google-gax'; import fs from 'fs'; import path from 'path'; -import {fileURLToPath} from 'url'; +import { fileURLToPath } from 'url'; // @ts-ignore const dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -37,2559 +37,3763 @@ const dirname = path.dirname(fileURLToPath(import.meta.url)); // to fill in default values for request objects const root = protobuf.Root.fromJSON( JSON.parse( - fs.readFileSync(path.join(dirname, '..', '..', 'protos/protos.json'), 'utf8') - )) + fs.readFileSync( + path.join(dirname, '..', '..', 'protos/protos.json'), + 'utf8', + ), + ), +); // eslint-disable-next-line @typescript-eslint/no-unused-vars function getTypeDefaultValue(typeName: string, fields: string[]) { - let type = root.lookupType(typeName) as protobuf.Type; - for (const field of fields.slice(0, -1)) { - type = type?.fields[field]?.resolvedType as protobuf.Type; - } - return type?.fields[fields[fields.length - 1]]?.defaultValue ?? null; + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type?.fields[field]?.resolvedType as protobuf.Type; + } + return type?.fields[fields[fields.length - 1]]?.defaultValue ?? null; } function generateSampleMessage(instance: T) { - const filledObject = (instance.constructor as typeof protobuf.Message) - .toObject(instance as protobuf.Message, {defaults: true}); - return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, { defaults: true }); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; } function stubSimpleCall(response?: ResponseType, error?: Error) { - return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); } -function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { - return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +function stubSimpleCallWithCallback( + response?: ResponseType, + error?: Error, +) { + return error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); } -function stubPageStreamingCall(responses?: ResponseType[], error?: Error) { - const pagingStub = sinon.stub(); - if (responses) { - for (let i = 0; i < responses.length; ++i) { - pagingStub.onCall(i).callsArgWith(2, null, responses[i]); - } +function stubPageStreamingCall( + responses?: ResponseType[], + error?: Error, +) { + const pagingStub = sinon.stub(); + if (responses) { + for (let i = 0; i < responses.length; ++i) { + pagingStub.onCall(i).callsArgWith(2, null, responses[i]); } - const transformStub = error ? sinon.stub().callsArgWith(2, error) : pagingStub; - const mockStream = new PassThrough({ - objectMode: true, - transform: transformStub, - }); - // trigger as many responses as needed - if (responses) { - for (let i = 0; i < responses.length; ++i) { - setImmediate(() => { mockStream.write({}); }); - } - setImmediate(() => { mockStream.end(); }); - } else { - setImmediate(() => { mockStream.write({}); }); - setImmediate(() => { mockStream.end(); }); + } + const transformStub = error + ? sinon.stub().callsArgWith(2, error) + : pagingStub; + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + // trigger as many responses as needed + if (responses) { + for (let i = 0; i < responses.length; ++i) { + setImmediate(() => { + mockStream.write({}); + }); } - return sinon.stub().returns(mockStream); + setImmediate(() => { + mockStream.end(); + }); + } else { + setImmediate(() => { + mockStream.write({}); + }); + setImmediate(() => { + mockStream.end(); + }); + } + return sinon.stub().returns(mockStream); } -function stubAsyncIterationCall(responses?: ResponseType[], error?: Error) { - let counter = 0; - const asyncIterable = { - [Symbol.asyncIterator]() { - return { - async next() { - if (error) { - return Promise.reject(error); - } - if (counter >= responses!.length) { - return Promise.resolve({done: true, value: undefined}); - } - return Promise.resolve({done: false, value: responses![counter++]}); - } - }; - } - }; - return sinon.stub().returns(asyncIterable); +function stubAsyncIterationCall( + responses?: ResponseType[], + error?: Error, +) { + let counter = 0; + const asyncIterable = { + [Symbol.asyncIterator]() { + return { + async next() { + if (error) { + return Promise.reject(error); + } + if (counter >= responses!.length) { + return Promise.resolve({ done: true, value: undefined }); + } + return Promise.resolve({ done: false, value: responses![counter++] }); + }, + }; + }, + }; + return sinon.stub().returns(asyncIterable); } describe('v3.ServiceMonitoringServiceClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'monitoring.googleapis.com'); - }); - - it('has universeDomain', () => { - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); - - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - it('throws DeprecationWarning if static servicePath is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const servicePath = servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient.servicePath; - assert.strictEqual(servicePath, 'monitoring.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'monitoring.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'monitoring.example.com'); - }); - - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'monitoring.example.com'); - }); - - if (typeof process === 'object' && 'env' in process) { - describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { - it('sets apiEndpoint from environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'monitoring.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - - it('value configured in code has priority over environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'monitoring.configured.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); - - it('has port', () => { - const port = servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient.port; - assert(port); - assert(typeof port === 'number'); - }); - - it('should create a client with no option', () => { - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient(); - assert(client); - }); - - it('should create a client with gRPC fallback', () => { - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - fallback: true, - }); - assert(client); - }); - - it('has initialize method and supports deferred initialization', async () => { - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.serviceMonitoringServiceStub, undefined); - await client.initialize(); - assert(client.serviceMonitoringServiceStub); - }); - - it('has close method for the initialized client', done => { - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.serviceMonitoringServiceStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); - - it('has close method for the non-initialized client', done => { - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.serviceMonitoringServiceStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); - - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); - }); - - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId((err?: Error|null, projectId?: string|null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } - }); - }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); - }); - }); - - describe('createService', () => { - it('invokes createService without error', async () => { - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.CreateServiceRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.CreateServiceRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.monitoring.v3.Service() - ); - client.innerApiCalls.createService = stubSimpleCall(expectedResponse); - const [response] = await client.createService(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createService as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createService as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createService without error using callback', async () => { - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.CreateServiceRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.CreateServiceRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.monitoring.v3.Service() - ); - client.innerApiCalls.createService = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createService( - request, - (err?: Error|null, result?: protos.google.monitoring.v3.IService|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createService as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createService as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createService with error', async () => { - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.CreateServiceRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.CreateServiceRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createService = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createService(request), expectedError); - const actualRequest = (client.innerApiCalls.createService as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createService as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createService with closed client', async () => { - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.CreateServiceRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.CreateServiceRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createService(request), expectedError); - }); - }); - - describe('getService', () => { - it('invokes getService without error', async () => { - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.GetServiceRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.GetServiceRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.monitoring.v3.Service() - ); - client.innerApiCalls.getService = stubSimpleCall(expectedResponse); - const [response] = await client.getService(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getService as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getService as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getService without error using callback', async () => { - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.GetServiceRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.GetServiceRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.monitoring.v3.Service() - ); - client.innerApiCalls.getService = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getService( - request, - (err?: Error|null, result?: protos.google.monitoring.v3.IService|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getService as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getService as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getService with error', async () => { - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.GetServiceRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.GetServiceRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getService = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getService(request), expectedError); - const actualRequest = (client.innerApiCalls.getService as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getService as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getService with closed client', async () => { - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.GetServiceRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.GetServiceRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getService(request), expectedError); - }); - }); - - describe('updateService', () => { - it('invokes updateService without error', async () => { - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.UpdateServiceRequest() - ); - request.service ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.UpdateServiceRequest', ['service', 'name']); - request.service.name = defaultValue1; - const expectedHeaderRequestParams = `service.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.monitoring.v3.Service() - ); - client.innerApiCalls.updateService = stubSimpleCall(expectedResponse); - const [response] = await client.updateService(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateService as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateService as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateService without error using callback', async () => { - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.UpdateServiceRequest() - ); - request.service ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.UpdateServiceRequest', ['service', 'name']); - request.service.name = defaultValue1; - const expectedHeaderRequestParams = `service.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.monitoring.v3.Service() - ); - client.innerApiCalls.updateService = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateService( - request, - (err?: Error|null, result?: protos.google.monitoring.v3.IService|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateService as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateService as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateService with error', async () => { - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.UpdateServiceRequest() - ); - request.service ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.UpdateServiceRequest', ['service', 'name']); - request.service.name = defaultValue1; - const expectedHeaderRequestParams = `service.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateService = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateService(request), expectedError); - const actualRequest = (client.innerApiCalls.updateService as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateService as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateService with closed client', async () => { - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.UpdateServiceRequest() - ); - request.service ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.UpdateServiceRequest', ['service', 'name']); - request.service.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateService(request), expectedError); - }); - }); - - describe('deleteService', () => { - it('invokes deleteService without error', async () => { - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.DeleteServiceRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.DeleteServiceRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteService = stubSimpleCall(expectedResponse); - const [response] = await client.deleteService(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteService as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteService as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes deleteService without error using callback', async () => { - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.DeleteServiceRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.DeleteServiceRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteService = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteService( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteService as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteService as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes deleteService with error', async () => { - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.DeleteServiceRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.DeleteServiceRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteService = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteService(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteService as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteService as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes deleteService with closed client', async () => { - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.DeleteServiceRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.DeleteServiceRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteService(request), expectedError); - }); - }); - - describe('createServiceLevelObjective', () => { - it('invokes createServiceLevelObjective without error', async () => { - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.CreateServiceLevelObjectiveRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.CreateServiceLevelObjectiveRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.monitoring.v3.ServiceLevelObjective() - ); - client.innerApiCalls.createServiceLevelObjective = stubSimpleCall(expectedResponse); - const [response] = await client.createServiceLevelObjective(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createServiceLevelObjective as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createServiceLevelObjective as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createServiceLevelObjective without error using callback', async () => { - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.CreateServiceLevelObjectiveRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.CreateServiceLevelObjectiveRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.monitoring.v3.ServiceLevelObjective() - ); - client.innerApiCalls.createServiceLevelObjective = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createServiceLevelObjective( - request, - (err?: Error|null, result?: protos.google.monitoring.v3.IServiceLevelObjective|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createServiceLevelObjective as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createServiceLevelObjective as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createServiceLevelObjective with error', async () => { - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.CreateServiceLevelObjectiveRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.CreateServiceLevelObjectiveRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createServiceLevelObjective = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createServiceLevelObjective(request), expectedError); - const actualRequest = (client.innerApiCalls.createServiceLevelObjective as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createServiceLevelObjective as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createServiceLevelObjective with closed client', async () => { - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.CreateServiceLevelObjectiveRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.CreateServiceLevelObjectiveRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createServiceLevelObjective(request), expectedError); - }); - }); - - describe('getServiceLevelObjective', () => { - it('invokes getServiceLevelObjective without error', async () => { - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.GetServiceLevelObjectiveRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.GetServiceLevelObjectiveRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.monitoring.v3.ServiceLevelObjective() - ); - client.innerApiCalls.getServiceLevelObjective = stubSimpleCall(expectedResponse); - const [response] = await client.getServiceLevelObjective(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getServiceLevelObjective as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getServiceLevelObjective as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getServiceLevelObjective without error using callback', async () => { - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.GetServiceLevelObjectiveRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.GetServiceLevelObjectiveRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.monitoring.v3.ServiceLevelObjective() - ); - client.innerApiCalls.getServiceLevelObjective = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getServiceLevelObjective( - request, - (err?: Error|null, result?: protos.google.monitoring.v3.IServiceLevelObjective|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getServiceLevelObjective as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getServiceLevelObjective as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getServiceLevelObjective with error', async () => { - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.GetServiceLevelObjectiveRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.GetServiceLevelObjectiveRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getServiceLevelObjective = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getServiceLevelObjective(request), expectedError); - const actualRequest = (client.innerApiCalls.getServiceLevelObjective as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getServiceLevelObjective as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getServiceLevelObjective with closed client', async () => { - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.GetServiceLevelObjectiveRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.GetServiceLevelObjectiveRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getServiceLevelObjective(request), expectedError); - }); - }); - - describe('updateServiceLevelObjective', () => { - it('invokes updateServiceLevelObjective without error', async () => { - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.UpdateServiceLevelObjectiveRequest() - ); - request.serviceLevelObjective ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.UpdateServiceLevelObjectiveRequest', ['serviceLevelObjective', 'name']); - request.serviceLevelObjective.name = defaultValue1; - const expectedHeaderRequestParams = `service_level_objective.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.monitoring.v3.ServiceLevelObjective() - ); - client.innerApiCalls.updateServiceLevelObjective = stubSimpleCall(expectedResponse); - const [response] = await client.updateServiceLevelObjective(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateServiceLevelObjective as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateServiceLevelObjective as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateServiceLevelObjective without error using callback', async () => { - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.UpdateServiceLevelObjectiveRequest() - ); - request.serviceLevelObjective ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.UpdateServiceLevelObjectiveRequest', ['serviceLevelObjective', 'name']); - request.serviceLevelObjective.name = defaultValue1; - const expectedHeaderRequestParams = `service_level_objective.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.monitoring.v3.ServiceLevelObjective() - ); - client.innerApiCalls.updateServiceLevelObjective = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateServiceLevelObjective( - request, - (err?: Error|null, result?: protos.google.monitoring.v3.IServiceLevelObjective|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateServiceLevelObjective as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateServiceLevelObjective as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateServiceLevelObjective with error', async () => { - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.UpdateServiceLevelObjectiveRequest() - ); - request.serviceLevelObjective ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.UpdateServiceLevelObjectiveRequest', ['serviceLevelObjective', 'name']); - request.serviceLevelObjective.name = defaultValue1; - const expectedHeaderRequestParams = `service_level_objective.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateServiceLevelObjective = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateServiceLevelObjective(request), expectedError); - const actualRequest = (client.innerApiCalls.updateServiceLevelObjective as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateServiceLevelObjective as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateServiceLevelObjective with closed client', async () => { - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.UpdateServiceLevelObjectiveRequest() - ); - request.serviceLevelObjective ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.UpdateServiceLevelObjectiveRequest', ['serviceLevelObjective', 'name']); - request.serviceLevelObjective.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateServiceLevelObjective(request), expectedError); - }); - }); - - describe('deleteServiceLevelObjective', () => { - it('invokes deleteServiceLevelObjective without error', async () => { - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.DeleteServiceLevelObjectiveRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.DeleteServiceLevelObjectiveRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteServiceLevelObjective = stubSimpleCall(expectedResponse); - const [response] = await client.deleteServiceLevelObjective(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteServiceLevelObjective as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteServiceLevelObjective as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes deleteServiceLevelObjective without error using callback', async () => { - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.DeleteServiceLevelObjectiveRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.DeleteServiceLevelObjectiveRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteServiceLevelObjective = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteServiceLevelObjective( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteServiceLevelObjective as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteServiceLevelObjective as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes deleteServiceLevelObjective with error', async () => { - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.DeleteServiceLevelObjectiveRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.DeleteServiceLevelObjectiveRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteServiceLevelObjective = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteServiceLevelObjective(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteServiceLevelObjective as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteServiceLevelObjective as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes deleteServiceLevelObjective with closed client', async () => { - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.DeleteServiceLevelObjectiveRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.DeleteServiceLevelObjectiveRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteServiceLevelObjective(request), expectedError); - }); - }); - - describe('listServices', () => { - it('invokes listServices without error', async () => { - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListServicesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListServicesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.monitoring.v3.Service()), - generateSampleMessage(new protos.google.monitoring.v3.Service()), - generateSampleMessage(new protos.google.monitoring.v3.Service()), - ]; - client.innerApiCalls.listServices = stubSimpleCall(expectedResponse); - const [response] = await client.listServices(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listServices as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listServices as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listServices without error using callback', async () => { - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListServicesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListServicesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.monitoring.v3.Service()), - generateSampleMessage(new protos.google.monitoring.v3.Service()), - generateSampleMessage(new protos.google.monitoring.v3.Service()), - ]; - client.innerApiCalls.listServices = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listServices( - request, - (err?: Error|null, result?: protos.google.monitoring.v3.IService[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listServices as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listServices as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listServices with error', async () => { - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListServicesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListServicesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listServices = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listServices(request), expectedError); - const actualRequest = (client.innerApiCalls.listServices as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listServices as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listServicesStream without error', async () => { - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListServicesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListServicesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.monitoring.v3.Service()), - generateSampleMessage(new protos.google.monitoring.v3.Service()), - generateSampleMessage(new protos.google.monitoring.v3.Service()), - ]; - client.descriptors.page.listServices.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listServicesStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.monitoring.v3.Service[] = []; - stream.on('data', (response: protos.google.monitoring.v3.Service) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.listServices.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listServices, request)); - assert( - (client.descriptors.page.listServices.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'monitoring.googleapis.com'); + }); - it('invokes listServicesStream with error', async () => { - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListServicesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListServicesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listServices.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listServicesStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.monitoring.v3.Service[] = []; - stream.on('data', (response: protos.google.monitoring.v3.Service) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listServices.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listServices, request)); - assert( - (client.descriptors.page.listServices.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('has universeDomain', () => { + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - it('uses async iteration with listServices without error', async () => { - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListServicesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListServicesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.monitoring.v3.Service()), - generateSampleMessage(new protos.google.monitoring.v3.Service()), - generateSampleMessage(new protos.google.monitoring.v3.Service()), - ]; - client.descriptors.page.listServices.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.monitoring.v3.IService[] = []; - const iterable = client.listServicesAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listServices.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listServices.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = + servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient + .servicePath; + assert.strictEqual(servicePath, 'monitoring.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient + .apiEndpoint; + assert.strictEqual(apiEndpoint, 'monitoring.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + universeDomain: 'example.com', }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'monitoring.example.com'); + }); - it('uses async iteration with listServices with error', async () => { - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListServicesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListServicesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listServices.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listServicesAsync(request); - await assert.rejects(async () => { - const responses: protos.google.monitoring.v3.IService[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listServices.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listServices.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + universe_domain: 'example.com', }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'monitoring.example.com'); }); - describe('listServiceLevelObjectives', () => { - it('invokes listServiceLevelObjectives without error', async () => { - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListServiceLevelObjectivesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListServiceLevelObjectivesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.monitoring.v3.ServiceLevelObjective()), - generateSampleMessage(new protos.google.monitoring.v3.ServiceLevelObjective()), - generateSampleMessage(new protos.google.monitoring.v3.ServiceLevelObjective()), - ]; - client.innerApiCalls.listServiceLevelObjectives = stubSimpleCall(expectedResponse); - const [response] = await client.listServiceLevelObjectives(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listServiceLevelObjectives as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listServiceLevelObjectives as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listServiceLevelObjectives without error using callback', async () => { - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListServiceLevelObjectivesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListServiceLevelObjectivesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.monitoring.v3.ServiceLevelObjective()), - generateSampleMessage(new protos.google.monitoring.v3.ServiceLevelObjective()), - generateSampleMessage(new protos.google.monitoring.v3.ServiceLevelObjective()), - ]; - client.innerApiCalls.listServiceLevelObjectives = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listServiceLevelObjectives( - request, - (err?: Error|null, result?: protos.google.monitoring.v3.IServiceLevelObjective[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listServiceLevelObjectives as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listServiceLevelObjectives as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listServiceLevelObjectives with error', async () => { - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListServiceLevelObjectivesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListServiceLevelObjectivesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listServiceLevelObjectives = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listServiceLevelObjectives(request), expectedError); - const actualRequest = (client.innerApiCalls.listServiceLevelObjectives as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listServiceLevelObjectives as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listServiceLevelObjectivesStream without error', async () => { - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListServiceLevelObjectivesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListServiceLevelObjectivesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.monitoring.v3.ServiceLevelObjective()), - generateSampleMessage(new protos.google.monitoring.v3.ServiceLevelObjective()), - generateSampleMessage(new protos.google.monitoring.v3.ServiceLevelObjective()), - ]; - client.descriptors.page.listServiceLevelObjectives.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listServiceLevelObjectivesStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.monitoring.v3.ServiceLevelObjective[] = []; - stream.on('data', (response: protos.google.monitoring.v3.ServiceLevelObjective) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.listServiceLevelObjectives.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listServiceLevelObjectives, request)); - assert( - (client.descriptors.page.listServiceLevelObjectives.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); + if (typeof process === 'object' && 'env' in process) { + describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { + it('sets apiEndpoint from environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'monitoring.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } + }); + + it('value configured in code has priority over environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient( + { universeDomain: 'configured.example.com' }, + ); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'monitoring.configured.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } + }); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); + }); - it('invokes listServiceLevelObjectivesStream with error', async () => { - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListServiceLevelObjectivesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListServiceLevelObjectivesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listServiceLevelObjectives.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listServiceLevelObjectivesStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.monitoring.v3.ServiceLevelObjective[] = []; - stream.on('data', (response: protos.google.monitoring.v3.ServiceLevelObjective) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listServiceLevelObjectives.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listServiceLevelObjectives, request)); - assert( - (client.descriptors.page.listServiceLevelObjectives.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); + it('has port', () => { + const port = + servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient.port; + assert(port); + assert(typeof port === 'number'); + }); + + it('should create a client with no option', () => { + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient(); + assert(client); + }); + + it('should create a client with gRPC fallback', () => { + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + fallback: true, }); + assert(client); + }); - it('uses async iteration with listServiceLevelObjectives without error', async () => { - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListServiceLevelObjectivesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListServiceLevelObjectivesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.monitoring.v3.ServiceLevelObjective()), - generateSampleMessage(new protos.google.monitoring.v3.ServiceLevelObjective()), - generateSampleMessage(new protos.google.monitoring.v3.ServiceLevelObjective()), - ]; - client.descriptors.page.listServiceLevelObjectives.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.monitoring.v3.IServiceLevelObjective[] = []; - const iterable = client.listServiceLevelObjectivesAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listServiceLevelObjectives.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listServiceLevelObjectives.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); + it('has initialize method and supports deferred initialization', async () => { + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + assert.strictEqual(client.serviceMonitoringServiceStub, undefined); + await client.initialize(); + assert(client.serviceMonitoringServiceStub); + }); - it('uses async iteration with listServiceLevelObjectives with error', async () => { - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListServiceLevelObjectivesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListServiceLevelObjectivesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listServiceLevelObjectives.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listServiceLevelObjectivesAsync(request); - await assert.rejects(async () => { - const responses: protos.google.monitoring.v3.IServiceLevelObjective[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listServiceLevelObjectives.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listServiceLevelObjectives.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); + it('has close method for the initialized client', (done) => { + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.serviceMonitoringServiceStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); }); - describe('Path templates', () => { - - describe('folderAlertPolicy', () => { - const fakePath = "/rendered/path/folderAlertPolicy"; - const expectedParameters = { - folder: "folderValue", - alert_policy: "alertPolicyValue", - }; - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.folderAlertPolicyPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderAlertPolicyPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderAlertPolicyPath', () => { - const result = client.folderAlertPolicyPath("folderValue", "alertPolicyValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderAlertPolicyPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderAlertPolicyName', () => { - const result = client.matchFolderFromFolderAlertPolicyName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderAlertPolicyPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchAlertPolicyFromFolderAlertPolicyName', () => { - const result = client.matchAlertPolicyFromFolderAlertPolicyName(fakePath); - assert.strictEqual(result, "alertPolicyValue"); - assert((client.pathTemplates.folderAlertPolicyPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('folderAlertPolicyCondition', () => { - const fakePath = "/rendered/path/folderAlertPolicyCondition"; - const expectedParameters = { - folder: "folderValue", - alert_policy: "alertPolicyValue", - condition: "conditionValue", - }; - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.folderAlertPolicyConditionPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderAlertPolicyConditionPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderAlertPolicyConditionPath', () => { - const result = client.folderAlertPolicyConditionPath("folderValue", "alertPolicyValue", "conditionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderAlertPolicyConditionPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderAlertPolicyConditionName', () => { - const result = client.matchFolderFromFolderAlertPolicyConditionName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderAlertPolicyConditionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchAlertPolicyFromFolderAlertPolicyConditionName', () => { - const result = client.matchAlertPolicyFromFolderAlertPolicyConditionName(fakePath); - assert.strictEqual(result, "alertPolicyValue"); - assert((client.pathTemplates.folderAlertPolicyConditionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchConditionFromFolderAlertPolicyConditionName', () => { - const result = client.matchConditionFromFolderAlertPolicyConditionName(fakePath); - assert.strictEqual(result, "conditionValue"); - assert((client.pathTemplates.folderAlertPolicyConditionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('folderChannelDescriptor', () => { - const fakePath = "/rendered/path/folderChannelDescriptor"; - const expectedParameters = { - folder: "folderValue", - channel_descriptor: "channelDescriptorValue", - }; - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.folderChannelDescriptorPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderChannelDescriptorPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderChannelDescriptorPath', () => { - const result = client.folderChannelDescriptorPath("folderValue", "channelDescriptorValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderChannelDescriptorPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderChannelDescriptorName', () => { - const result = client.matchFolderFromFolderChannelDescriptorName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderChannelDescriptorPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchChannelDescriptorFromFolderChannelDescriptorName', () => { - const result = client.matchChannelDescriptorFromFolderChannelDescriptorName(fakePath); - assert.strictEqual(result, "channelDescriptorValue"); - assert((client.pathTemplates.folderChannelDescriptorPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('folderGroup', () => { - const fakePath = "/rendered/path/folderGroup"; - const expectedParameters = { - folder: "folderValue", - group: "groupValue", - }; - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.folderGroupPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderGroupPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderGroupPath', () => { - const result = client.folderGroupPath("folderValue", "groupValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderGroupPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderGroupName', () => { - const result = client.matchFolderFromFolderGroupName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderGroupPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchGroupFromFolderGroupName', () => { - const result = client.matchGroupFromFolderGroupName(fakePath); - assert.strictEqual(result, "groupValue"); - assert((client.pathTemplates.folderGroupPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('folderNotificationChannel', () => { - const fakePath = "/rendered/path/folderNotificationChannel"; - const expectedParameters = { - folder: "folderValue", - notification_channel: "notificationChannelValue", - }; - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.folderNotificationChannelPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderNotificationChannelPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderNotificationChannelPath', () => { - const result = client.folderNotificationChannelPath("folderValue", "notificationChannelValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderNotificationChannelPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderNotificationChannelName', () => { - const result = client.matchFolderFromFolderNotificationChannelName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderNotificationChannelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchNotificationChannelFromFolderNotificationChannelName', () => { - const result = client.matchNotificationChannelFromFolderNotificationChannelName(fakePath); - assert.strictEqual(result, "notificationChannelValue"); - assert((client.pathTemplates.folderNotificationChannelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('folderService', () => { - const fakePath = "/rendered/path/folderService"; - const expectedParameters = { - folder: "folderValue", - service: "serviceValue", - }; - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.folderServicePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderServicePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderServicePath', () => { - const result = client.folderServicePath("folderValue", "serviceValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderServicePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderServiceName', () => { - const result = client.matchFolderFromFolderServiceName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderServicePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServiceFromFolderServiceName', () => { - const result = client.matchServiceFromFolderServiceName(fakePath); - assert.strictEqual(result, "serviceValue"); - assert((client.pathTemplates.folderServicePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('folderServiceServiceLevelObjective', () => { - const fakePath = "/rendered/path/folderServiceServiceLevelObjective"; - const expectedParameters = { - folder: "folderValue", - service: "serviceValue", - service_level_objective: "serviceLevelObjectiveValue", - }; - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderServiceServiceLevelObjectivePath', () => { - const result = client.folderServiceServiceLevelObjectivePath("folderValue", "serviceValue", "serviceLevelObjectiveValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderServiceServiceLevelObjectiveName', () => { - const result = client.matchFolderFromFolderServiceServiceLevelObjectiveName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServiceFromFolderServiceServiceLevelObjectiveName', () => { - const result = client.matchServiceFromFolderServiceServiceLevelObjectiveName(fakePath); - assert.strictEqual(result, "serviceValue"); - assert((client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServiceLevelObjectiveFromFolderServiceServiceLevelObjectiveName', () => { - const result = client.matchServiceLevelObjectiveFromFolderServiceServiceLevelObjectiveName(fakePath); - assert.strictEqual(result, "serviceLevelObjectiveValue"); - assert((client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('folderUptimeCheckConfig', () => { - const fakePath = "/rendered/path/folderUptimeCheckConfig"; - const expectedParameters = { - folder: "folderValue", - uptime_check_config: "uptimeCheckConfigValue", - }; - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.folderUptimeCheckConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderUptimeCheckConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderUptimeCheckConfigPath', () => { - const result = client.folderUptimeCheckConfigPath("folderValue", "uptimeCheckConfigValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderUptimeCheckConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderUptimeCheckConfigName', () => { - const result = client.matchFolderFromFolderUptimeCheckConfigName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderUptimeCheckConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchUptimeCheckConfigFromFolderUptimeCheckConfigName', () => { - const result = client.matchUptimeCheckConfigFromFolderUptimeCheckConfigName(fakePath); - assert.strictEqual(result, "uptimeCheckConfigValue"); - assert((client.pathTemplates.folderUptimeCheckConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('organizationAlertPolicy', () => { - const fakePath = "/rendered/path/organizationAlertPolicy"; - const expectedParameters = { - organization: "organizationValue", - alert_policy: "alertPolicyValue", - }; - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.organizationAlertPolicyPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationAlertPolicyPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationAlertPolicyPath', () => { - const result = client.organizationAlertPolicyPath("organizationValue", "alertPolicyValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationAlertPolicyPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationAlertPolicyName', () => { - const result = client.matchOrganizationFromOrganizationAlertPolicyName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationAlertPolicyPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchAlertPolicyFromOrganizationAlertPolicyName', () => { - const result = client.matchAlertPolicyFromOrganizationAlertPolicyName(fakePath); - assert.strictEqual(result, "alertPolicyValue"); - assert((client.pathTemplates.organizationAlertPolicyPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('organizationAlertPolicyCondition', () => { - const fakePath = "/rendered/path/organizationAlertPolicyCondition"; - const expectedParameters = { - organization: "organizationValue", - alert_policy: "alertPolicyValue", - condition: "conditionValue", - }; - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.organizationAlertPolicyConditionPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationAlertPolicyConditionPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationAlertPolicyConditionPath', () => { - const result = client.organizationAlertPolicyConditionPath("organizationValue", "alertPolicyValue", "conditionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationAlertPolicyConditionPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationAlertPolicyConditionName', () => { - const result = client.matchOrganizationFromOrganizationAlertPolicyConditionName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationAlertPolicyConditionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchAlertPolicyFromOrganizationAlertPolicyConditionName', () => { - const result = client.matchAlertPolicyFromOrganizationAlertPolicyConditionName(fakePath); - assert.strictEqual(result, "alertPolicyValue"); - assert((client.pathTemplates.organizationAlertPolicyConditionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchConditionFromOrganizationAlertPolicyConditionName', () => { - const result = client.matchConditionFromOrganizationAlertPolicyConditionName(fakePath); - assert.strictEqual(result, "conditionValue"); - assert((client.pathTemplates.organizationAlertPolicyConditionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('organizationChannelDescriptor', () => { - const fakePath = "/rendered/path/organizationChannelDescriptor"; - const expectedParameters = { - organization: "organizationValue", - channel_descriptor: "channelDescriptorValue", - }; - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.organizationChannelDescriptorPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationChannelDescriptorPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationChannelDescriptorPath', () => { - const result = client.organizationChannelDescriptorPath("organizationValue", "channelDescriptorValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationChannelDescriptorPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationChannelDescriptorName', () => { - const result = client.matchOrganizationFromOrganizationChannelDescriptorName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationChannelDescriptorPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchChannelDescriptorFromOrganizationChannelDescriptorName', () => { - const result = client.matchChannelDescriptorFromOrganizationChannelDescriptorName(fakePath); - assert.strictEqual(result, "channelDescriptorValue"); - assert((client.pathTemplates.organizationChannelDescriptorPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('organizationGroup', () => { - const fakePath = "/rendered/path/organizationGroup"; - const expectedParameters = { - organization: "organizationValue", - group: "groupValue", - }; - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.organizationGroupPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationGroupPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationGroupPath', () => { - const result = client.organizationGroupPath("organizationValue", "groupValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationGroupPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationGroupName', () => { - const result = client.matchOrganizationFromOrganizationGroupName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationGroupPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchGroupFromOrganizationGroupName', () => { - const result = client.matchGroupFromOrganizationGroupName(fakePath); - assert.strictEqual(result, "groupValue"); - assert((client.pathTemplates.organizationGroupPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('organizationNotificationChannel', () => { - const fakePath = "/rendered/path/organizationNotificationChannel"; - const expectedParameters = { - organization: "organizationValue", - notification_channel: "notificationChannelValue", - }; - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.organizationNotificationChannelPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationNotificationChannelPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationNotificationChannelPath', () => { - const result = client.organizationNotificationChannelPath("organizationValue", "notificationChannelValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationNotificationChannelPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationNotificationChannelName', () => { - const result = client.matchOrganizationFromOrganizationNotificationChannelName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationNotificationChannelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchNotificationChannelFromOrganizationNotificationChannelName', () => { - const result = client.matchNotificationChannelFromOrganizationNotificationChannelName(fakePath); - assert.strictEqual(result, "notificationChannelValue"); - assert((client.pathTemplates.organizationNotificationChannelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('organizationService', () => { - const fakePath = "/rendered/path/organizationService"; - const expectedParameters = { - organization: "organizationValue", - service: "serviceValue", - }; - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.organizationServicePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationServicePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationServicePath', () => { - const result = client.organizationServicePath("organizationValue", "serviceValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationServicePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationServiceName', () => { - const result = client.matchOrganizationFromOrganizationServiceName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationServicePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServiceFromOrganizationServiceName', () => { - const result = client.matchServiceFromOrganizationServiceName(fakePath); - assert.strictEqual(result, "serviceValue"); - assert((client.pathTemplates.organizationServicePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('organizationServiceServiceLevelObjective', () => { - const fakePath = "/rendered/path/organizationServiceServiceLevelObjective"; - const expectedParameters = { - organization: "organizationValue", - service: "serviceValue", - service_level_objective: "serviceLevelObjectiveValue", - }; - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationServiceServiceLevelObjectivePath', () => { - const result = client.organizationServiceServiceLevelObjectivePath("organizationValue", "serviceValue", "serviceLevelObjectiveValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationServiceServiceLevelObjectiveName', () => { - const result = client.matchOrganizationFromOrganizationServiceServiceLevelObjectiveName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServiceFromOrganizationServiceServiceLevelObjectiveName', () => { - const result = client.matchServiceFromOrganizationServiceServiceLevelObjectiveName(fakePath); - assert.strictEqual(result, "serviceValue"); - assert((client.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServiceLevelObjectiveFromOrganizationServiceServiceLevelObjectiveName', () => { - const result = client.matchServiceLevelObjectiveFromOrganizationServiceServiceLevelObjectiveName(fakePath); - assert.strictEqual(result, "serviceLevelObjectiveValue"); - assert((client.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('organizationUptimeCheckConfig', () => { - const fakePath = "/rendered/path/organizationUptimeCheckConfig"; - const expectedParameters = { - organization: "organizationValue", - uptime_check_config: "uptimeCheckConfigValue", - }; - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.organizationUptimeCheckConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationUptimeCheckConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationUptimeCheckConfigPath', () => { - const result = client.organizationUptimeCheckConfigPath("organizationValue", "uptimeCheckConfigValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationUptimeCheckConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationUptimeCheckConfigName', () => { - const result = client.matchOrganizationFromOrganizationUptimeCheckConfigName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationUptimeCheckConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchUptimeCheckConfigFromOrganizationUptimeCheckConfigName', () => { - const result = client.matchUptimeCheckConfigFromOrganizationUptimeCheckConfigName(fakePath); - assert.strictEqual(result, "uptimeCheckConfigValue"); - assert((client.pathTemplates.organizationUptimeCheckConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('projectAlertPolicy', () => { - const fakePath = "/rendered/path/projectAlertPolicy"; - const expectedParameters = { - project: "projectValue", - alert_policy: "alertPolicyValue", - }; - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.projectAlertPolicyPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectAlertPolicyPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectAlertPolicyPath', () => { - const result = client.projectAlertPolicyPath("projectValue", "alertPolicyValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectAlertPolicyPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectAlertPolicyName', () => { - const result = client.matchProjectFromProjectAlertPolicyName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectAlertPolicyPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchAlertPolicyFromProjectAlertPolicyName', () => { - const result = client.matchAlertPolicyFromProjectAlertPolicyName(fakePath); - assert.strictEqual(result, "alertPolicyValue"); - assert((client.pathTemplates.projectAlertPolicyPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('projectAlertPolicyCondition', () => { - const fakePath = "/rendered/path/projectAlertPolicyCondition"; - const expectedParameters = { - project: "projectValue", - alert_policy: "alertPolicyValue", - condition: "conditionValue", - }; - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.projectAlertPolicyConditionPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectAlertPolicyConditionPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectAlertPolicyConditionPath', () => { - const result = client.projectAlertPolicyConditionPath("projectValue", "alertPolicyValue", "conditionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectAlertPolicyConditionPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectAlertPolicyConditionName', () => { - const result = client.matchProjectFromProjectAlertPolicyConditionName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectAlertPolicyConditionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchAlertPolicyFromProjectAlertPolicyConditionName', () => { - const result = client.matchAlertPolicyFromProjectAlertPolicyConditionName(fakePath); - assert.strictEqual(result, "alertPolicyValue"); - assert((client.pathTemplates.projectAlertPolicyConditionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchConditionFromProjectAlertPolicyConditionName', () => { - const result = client.matchConditionFromProjectAlertPolicyConditionName(fakePath); - assert.strictEqual(result, "conditionValue"); - assert((client.pathTemplates.projectAlertPolicyConditionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('projectChannelDescriptor', () => { - const fakePath = "/rendered/path/projectChannelDescriptor"; - const expectedParameters = { - project: "projectValue", - channel_descriptor: "channelDescriptorValue", - }; - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.projectChannelDescriptorPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectChannelDescriptorPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectChannelDescriptorPath', () => { - const result = client.projectChannelDescriptorPath("projectValue", "channelDescriptorValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectChannelDescriptorPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectChannelDescriptorName', () => { - const result = client.matchProjectFromProjectChannelDescriptorName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectChannelDescriptorPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchChannelDescriptorFromProjectChannelDescriptorName', () => { - const result = client.matchChannelDescriptorFromProjectChannelDescriptorName(fakePath); - assert.strictEqual(result, "channelDescriptorValue"); - assert((client.pathTemplates.projectChannelDescriptorPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('projectGroup', () => { - const fakePath = "/rendered/path/projectGroup"; - const expectedParameters = { - project: "projectValue", - group: "groupValue", - }; - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.projectGroupPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectGroupPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectGroupPath', () => { - const result = client.projectGroupPath("projectValue", "groupValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectGroupPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectGroupName', () => { - const result = client.matchProjectFromProjectGroupName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectGroupPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchGroupFromProjectGroupName', () => { - const result = client.matchGroupFromProjectGroupName(fakePath); - assert.strictEqual(result, "groupValue"); - assert((client.pathTemplates.projectGroupPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('projectNotificationChannel', () => { - const fakePath = "/rendered/path/projectNotificationChannel"; - const expectedParameters = { - project: "projectValue", - notification_channel: "notificationChannelValue", - }; - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.projectNotificationChannelPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectNotificationChannelPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectNotificationChannelPath', () => { - const result = client.projectNotificationChannelPath("projectValue", "notificationChannelValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectNotificationChannelPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectNotificationChannelName', () => { - const result = client.matchProjectFromProjectNotificationChannelName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectNotificationChannelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchNotificationChannelFromProjectNotificationChannelName', () => { - const result = client.matchNotificationChannelFromProjectNotificationChannelName(fakePath); - assert.strictEqual(result, "notificationChannelValue"); - assert((client.pathTemplates.projectNotificationChannelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('projectService', () => { - const fakePath = "/rendered/path/projectService"; - const expectedParameters = { - project: "projectValue", - service: "serviceValue", - }; - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.projectServicePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectServicePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectServicePath', () => { - const result = client.projectServicePath("projectValue", "serviceValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectServicePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectServiceName', () => { - const result = client.matchProjectFromProjectServiceName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectServicePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServiceFromProjectServiceName', () => { - const result = client.matchServiceFromProjectServiceName(fakePath); - assert.strictEqual(result, "serviceValue"); - assert((client.pathTemplates.projectServicePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('projectServiceServiceLevelObjective', () => { - const fakePath = "/rendered/path/projectServiceServiceLevelObjective"; - const expectedParameters = { - project: "projectValue", - service: "serviceValue", - service_level_objective: "serviceLevelObjectiveValue", - }; - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectServiceServiceLevelObjectivePath', () => { - const result = client.projectServiceServiceLevelObjectivePath("projectValue", "serviceValue", "serviceLevelObjectiveValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectServiceServiceLevelObjectiveName', () => { - const result = client.matchProjectFromProjectServiceServiceLevelObjectiveName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServiceFromProjectServiceServiceLevelObjectiveName', () => { - const result = client.matchServiceFromProjectServiceServiceLevelObjectiveName(fakePath); - assert.strictEqual(result, "serviceValue"); - assert((client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServiceLevelObjectiveFromProjectServiceServiceLevelObjectiveName', () => { - const result = client.matchServiceLevelObjectiveFromProjectServiceServiceLevelObjectiveName(fakePath); - assert.strictEqual(result, "serviceLevelObjectiveValue"); - assert((client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('projectUptimeCheckConfig', () => { - const fakePath = "/rendered/path/projectUptimeCheckConfig"; - const expectedParameters = { - project: "projectValue", - uptime_check_config: "uptimeCheckConfigValue", - }; - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.projectUptimeCheckConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectUptimeCheckConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectUptimeCheckConfigPath', () => { - const result = client.projectUptimeCheckConfigPath("projectValue", "uptimeCheckConfigValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectUptimeCheckConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectUptimeCheckConfigName', () => { - const result = client.matchProjectFromProjectUptimeCheckConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectUptimeCheckConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchUptimeCheckConfigFromProjectUptimeCheckConfigName', () => { - const result = client.matchUptimeCheckConfigFromProjectUptimeCheckConfigName(fakePath); - assert.strictEqual(result, "uptimeCheckConfigValue"); - assert((client.pathTemplates.projectUptimeCheckConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('has close method for the non-initialized client', (done) => { + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.serviceMonitoringServiceStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); }); + + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + }); + + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } + }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + }); + + describe('createService', () => { + it('invokes createService without error', async () => { + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.CreateServiceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.CreateServiceRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.monitoring.v3.Service(), + ); + client.innerApiCalls.createService = stubSimpleCall(expectedResponse); + const [response] = await client.createService(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createService as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createService as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createService without error using callback', async () => { + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.CreateServiceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.CreateServiceRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.monitoring.v3.Service(), + ); + client.innerApiCalls.createService = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createService( + request, + ( + err?: Error | null, + result?: protos.google.monitoring.v3.IService | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createService as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createService as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createService with error', async () => { + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.CreateServiceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.CreateServiceRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createService = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.createService(request), expectedError); + const actualRequest = ( + client.innerApiCalls.createService as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createService as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createService with closed client', async () => { + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.CreateServiceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.CreateServiceRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.createService(request), expectedError); + }); + }); + + describe('getService', () => { + it('invokes getService without error', async () => { + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.GetServiceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.GetServiceRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.monitoring.v3.Service(), + ); + client.innerApiCalls.getService = stubSimpleCall(expectedResponse); + const [response] = await client.getService(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getService as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getService as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getService without error using callback', async () => { + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.GetServiceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.GetServiceRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.monitoring.v3.Service(), + ); + client.innerApiCalls.getService = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getService( + request, + ( + err?: Error | null, + result?: protos.google.monitoring.v3.IService | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getService as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getService as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getService with error', async () => { + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.GetServiceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.GetServiceRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getService = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getService(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getService as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getService as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getService with closed client', async () => { + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.GetServiceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.GetServiceRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getService(request), expectedError); + }); + }); + + describe('updateService', () => { + it('invokes updateService without error', async () => { + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.UpdateServiceRequest(), + ); + request.service ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.UpdateServiceRequest', + ['service', 'name'], + ); + request.service.name = defaultValue1; + const expectedHeaderRequestParams = `service.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.monitoring.v3.Service(), + ); + client.innerApiCalls.updateService = stubSimpleCall(expectedResponse); + const [response] = await client.updateService(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateService as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateService as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateService without error using callback', async () => { + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.UpdateServiceRequest(), + ); + request.service ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.UpdateServiceRequest', + ['service', 'name'], + ); + request.service.name = defaultValue1; + const expectedHeaderRequestParams = `service.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.monitoring.v3.Service(), + ); + client.innerApiCalls.updateService = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateService( + request, + ( + err?: Error | null, + result?: protos.google.monitoring.v3.IService | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateService as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateService as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateService with error', async () => { + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.UpdateServiceRequest(), + ); + request.service ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.UpdateServiceRequest', + ['service', 'name'], + ); + request.service.name = defaultValue1; + const expectedHeaderRequestParams = `service.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateService = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.updateService(request), expectedError); + const actualRequest = ( + client.innerApiCalls.updateService as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateService as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateService with closed client', async () => { + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.UpdateServiceRequest(), + ); + request.service ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.UpdateServiceRequest', + ['service', 'name'], + ); + request.service.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.updateService(request), expectedError); + }); + }); + + describe('deleteService', () => { + it('invokes deleteService without error', async () => { + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.DeleteServiceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.DeleteServiceRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteService = stubSimpleCall(expectedResponse); + const [response] = await client.deleteService(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteService as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteService as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteService without error using callback', async () => { + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.DeleteServiceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.DeleteServiceRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteService = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteService( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteService as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteService as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteService with error', async () => { + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.DeleteServiceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.DeleteServiceRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteService = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.deleteService(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteService as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteService as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteService with closed client', async () => { + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.DeleteServiceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.DeleteServiceRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.deleteService(request), expectedError); + }); + }); + + describe('createServiceLevelObjective', () => { + it('invokes createServiceLevelObjective without error', async () => { + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.CreateServiceLevelObjectiveRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.CreateServiceLevelObjectiveRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.monitoring.v3.ServiceLevelObjective(), + ); + client.innerApiCalls.createServiceLevelObjective = + stubSimpleCall(expectedResponse); + const [response] = await client.createServiceLevelObjective(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createServiceLevelObjective as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createServiceLevelObjective as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createServiceLevelObjective without error using callback', async () => { + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.CreateServiceLevelObjectiveRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.CreateServiceLevelObjectiveRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.monitoring.v3.ServiceLevelObjective(), + ); + client.innerApiCalls.createServiceLevelObjective = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createServiceLevelObjective( + request, + ( + err?: Error | null, + result?: protos.google.monitoring.v3.IServiceLevelObjective | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createServiceLevelObjective as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createServiceLevelObjective as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createServiceLevelObjective with error', async () => { + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.CreateServiceLevelObjectiveRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.CreateServiceLevelObjectiveRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createServiceLevelObjective = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.createServiceLevelObjective(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.createServiceLevelObjective as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createServiceLevelObjective as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createServiceLevelObjective with closed client', async () => { + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.CreateServiceLevelObjectiveRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.CreateServiceLevelObjectiveRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.createServiceLevelObjective(request), + expectedError, + ); + }); + }); + + describe('getServiceLevelObjective', () => { + it('invokes getServiceLevelObjective without error', async () => { + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.GetServiceLevelObjectiveRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.GetServiceLevelObjectiveRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.monitoring.v3.ServiceLevelObjective(), + ); + client.innerApiCalls.getServiceLevelObjective = + stubSimpleCall(expectedResponse); + const [response] = await client.getServiceLevelObjective(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getServiceLevelObjective as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getServiceLevelObjective as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getServiceLevelObjective without error using callback', async () => { + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.GetServiceLevelObjectiveRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.GetServiceLevelObjectiveRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.monitoring.v3.ServiceLevelObjective(), + ); + client.innerApiCalls.getServiceLevelObjective = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getServiceLevelObjective( + request, + ( + err?: Error | null, + result?: protos.google.monitoring.v3.IServiceLevelObjective | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getServiceLevelObjective as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getServiceLevelObjective as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getServiceLevelObjective with error', async () => { + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.GetServiceLevelObjectiveRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.GetServiceLevelObjectiveRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getServiceLevelObjective = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.getServiceLevelObjective(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.getServiceLevelObjective as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getServiceLevelObjective as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getServiceLevelObjective with closed client', async () => { + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.GetServiceLevelObjectiveRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.GetServiceLevelObjectiveRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.getServiceLevelObjective(request), + expectedError, + ); + }); + }); + + describe('updateServiceLevelObjective', () => { + it('invokes updateServiceLevelObjective without error', async () => { + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.UpdateServiceLevelObjectiveRequest(), + ); + request.serviceLevelObjective ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.UpdateServiceLevelObjectiveRequest', + ['serviceLevelObjective', 'name'], + ); + request.serviceLevelObjective.name = defaultValue1; + const expectedHeaderRequestParams = `service_level_objective.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.monitoring.v3.ServiceLevelObjective(), + ); + client.innerApiCalls.updateServiceLevelObjective = + stubSimpleCall(expectedResponse); + const [response] = await client.updateServiceLevelObjective(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateServiceLevelObjective as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateServiceLevelObjective as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateServiceLevelObjective without error using callback', async () => { + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.UpdateServiceLevelObjectiveRequest(), + ); + request.serviceLevelObjective ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.UpdateServiceLevelObjectiveRequest', + ['serviceLevelObjective', 'name'], + ); + request.serviceLevelObjective.name = defaultValue1; + const expectedHeaderRequestParams = `service_level_objective.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.monitoring.v3.ServiceLevelObjective(), + ); + client.innerApiCalls.updateServiceLevelObjective = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateServiceLevelObjective( + request, + ( + err?: Error | null, + result?: protos.google.monitoring.v3.IServiceLevelObjective | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateServiceLevelObjective as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateServiceLevelObjective as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateServiceLevelObjective with error', async () => { + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.UpdateServiceLevelObjectiveRequest(), + ); + request.serviceLevelObjective ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.UpdateServiceLevelObjectiveRequest', + ['serviceLevelObjective', 'name'], + ); + request.serviceLevelObjective.name = defaultValue1; + const expectedHeaderRequestParams = `service_level_objective.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateServiceLevelObjective = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.updateServiceLevelObjective(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.updateServiceLevelObjective as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateServiceLevelObjective as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateServiceLevelObjective with closed client', async () => { + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.UpdateServiceLevelObjectiveRequest(), + ); + request.serviceLevelObjective ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.UpdateServiceLevelObjectiveRequest', + ['serviceLevelObjective', 'name'], + ); + request.serviceLevelObjective.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.updateServiceLevelObjective(request), + expectedError, + ); + }); + }); + + describe('deleteServiceLevelObjective', () => { + it('invokes deleteServiceLevelObjective without error', async () => { + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.DeleteServiceLevelObjectiveRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.DeleteServiceLevelObjectiveRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteServiceLevelObjective = + stubSimpleCall(expectedResponse); + const [response] = await client.deleteServiceLevelObjective(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteServiceLevelObjective as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteServiceLevelObjective as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteServiceLevelObjective without error using callback', async () => { + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.DeleteServiceLevelObjectiveRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.DeleteServiceLevelObjectiveRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteServiceLevelObjective = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteServiceLevelObjective( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteServiceLevelObjective as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteServiceLevelObjective as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteServiceLevelObjective with error', async () => { + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.DeleteServiceLevelObjectiveRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.DeleteServiceLevelObjectiveRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteServiceLevelObjective = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.deleteServiceLevelObjective(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.deleteServiceLevelObjective as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteServiceLevelObjective as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteServiceLevelObjective with closed client', async () => { + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.DeleteServiceLevelObjectiveRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.DeleteServiceLevelObjectiveRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.deleteServiceLevelObjective(request), + expectedError, + ); + }); + }); + + describe('listServices', () => { + it('invokes listServices without error', async () => { + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListServicesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListServicesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.monitoring.v3.Service()), + generateSampleMessage(new protos.google.monitoring.v3.Service()), + generateSampleMessage(new protos.google.monitoring.v3.Service()), + ]; + client.innerApiCalls.listServices = stubSimpleCall(expectedResponse); + const [response] = await client.listServices(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listServices as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listServices as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listServices without error using callback', async () => { + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListServicesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListServicesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.monitoring.v3.Service()), + generateSampleMessage(new protos.google.monitoring.v3.Service()), + generateSampleMessage(new protos.google.monitoring.v3.Service()), + ]; + client.innerApiCalls.listServices = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listServices( + request, + ( + err?: Error | null, + result?: protos.google.monitoring.v3.IService[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listServices as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listServices as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listServices with error', async () => { + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListServicesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListServicesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listServices = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listServices(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listServices as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listServices as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listServicesStream without error', async () => { + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListServicesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListServicesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.monitoring.v3.Service()), + generateSampleMessage(new protos.google.monitoring.v3.Service()), + generateSampleMessage(new protos.google.monitoring.v3.Service()), + ]; + client.descriptors.page.listServices.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listServicesStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.monitoring.v3.Service[] = []; + stream.on('data', (response: protos.google.monitoring.v3.Service) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listServices.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listServices, request), + ); + assert( + (client.descriptors.page.listServices.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + + it('invokes listServicesStream with error', async () => { + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListServicesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListServicesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listServices.createStream = stubPageStreamingCall( + undefined, + expectedError, + ); + const stream = client.listServicesStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.monitoring.v3.Service[] = []; + stream.on('data', (response: protos.google.monitoring.v3.Service) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listServices.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listServices, request), + ); + assert( + (client.descriptors.page.listServices.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + + it('uses async iteration with listServices without error', async () => { + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListServicesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListServicesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.monitoring.v3.Service()), + generateSampleMessage(new protos.google.monitoring.v3.Service()), + generateSampleMessage(new protos.google.monitoring.v3.Service()), + ]; + client.descriptors.page.listServices.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.monitoring.v3.IService[] = []; + const iterable = client.listServicesAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listServices.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listServices.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + + it('uses async iteration with listServices with error', async () => { + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListServicesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListServicesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listServices.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listServicesAsync(request); + await assert.rejects(async () => { + const responses: protos.google.monitoring.v3.IService[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listServices.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listServices.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + }); + + describe('listServiceLevelObjectives', () => { + it('invokes listServiceLevelObjectives without error', async () => { + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListServiceLevelObjectivesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListServiceLevelObjectivesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.monitoring.v3.ServiceLevelObjective(), + ), + generateSampleMessage( + new protos.google.monitoring.v3.ServiceLevelObjective(), + ), + generateSampleMessage( + new protos.google.monitoring.v3.ServiceLevelObjective(), + ), + ]; + client.innerApiCalls.listServiceLevelObjectives = + stubSimpleCall(expectedResponse); + const [response] = await client.listServiceLevelObjectives(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listServiceLevelObjectives as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listServiceLevelObjectives as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listServiceLevelObjectives without error using callback', async () => { + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListServiceLevelObjectivesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListServiceLevelObjectivesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.monitoring.v3.ServiceLevelObjective(), + ), + generateSampleMessage( + new protos.google.monitoring.v3.ServiceLevelObjective(), + ), + generateSampleMessage( + new protos.google.monitoring.v3.ServiceLevelObjective(), + ), + ]; + client.innerApiCalls.listServiceLevelObjectives = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listServiceLevelObjectives( + request, + ( + err?: Error | null, + result?: + | protos.google.monitoring.v3.IServiceLevelObjective[] + | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listServiceLevelObjectives as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listServiceLevelObjectives as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listServiceLevelObjectives with error', async () => { + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListServiceLevelObjectivesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListServiceLevelObjectivesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listServiceLevelObjectives = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.listServiceLevelObjectives(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.listServiceLevelObjectives as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listServiceLevelObjectives as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listServiceLevelObjectivesStream without error', async () => { + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListServiceLevelObjectivesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListServiceLevelObjectivesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.monitoring.v3.ServiceLevelObjective(), + ), + generateSampleMessage( + new protos.google.monitoring.v3.ServiceLevelObjective(), + ), + generateSampleMessage( + new protos.google.monitoring.v3.ServiceLevelObjective(), + ), + ]; + client.descriptors.page.listServiceLevelObjectives.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listServiceLevelObjectivesStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.monitoring.v3.ServiceLevelObjective[] = + []; + stream.on( + 'data', + (response: protos.google.monitoring.v3.ServiceLevelObjective) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + ( + client.descriptors.page.listServiceLevelObjectives + .createStream as SinonStub + ) + .getCall(0) + .calledWith(client.innerApiCalls.listServiceLevelObjectives, request), + ); + assert( + ( + client.descriptors.page.listServiceLevelObjectives + .createStream as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); + + it('invokes listServiceLevelObjectivesStream with error', async () => { + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListServiceLevelObjectivesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListServiceLevelObjectivesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listServiceLevelObjectives.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listServiceLevelObjectivesStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.monitoring.v3.ServiceLevelObjective[] = + []; + stream.on( + 'data', + (response: protos.google.monitoring.v3.ServiceLevelObjective) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + ( + client.descriptors.page.listServiceLevelObjectives + .createStream as SinonStub + ) + .getCall(0) + .calledWith(client.innerApiCalls.listServiceLevelObjectives, request), + ); + assert( + ( + client.descriptors.page.listServiceLevelObjectives + .createStream as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); + + it('uses async iteration with listServiceLevelObjectives without error', async () => { + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListServiceLevelObjectivesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListServiceLevelObjectivesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.monitoring.v3.ServiceLevelObjective(), + ), + generateSampleMessage( + new protos.google.monitoring.v3.ServiceLevelObjective(), + ), + generateSampleMessage( + new protos.google.monitoring.v3.ServiceLevelObjective(), + ), + ]; + client.descriptors.page.listServiceLevelObjectives.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.monitoring.v3.IServiceLevelObjective[] = + []; + const iterable = client.listServiceLevelObjectivesAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listServiceLevelObjectives + .asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + ( + client.descriptors.page.listServiceLevelObjectives + .asyncIterate as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); + + it('uses async iteration with listServiceLevelObjectives with error', async () => { + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListServiceLevelObjectivesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListServiceLevelObjectivesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listServiceLevelObjectives.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listServiceLevelObjectivesAsync(request); + await assert.rejects(async () => { + const responses: protos.google.monitoring.v3.IServiceLevelObjective[] = + []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listServiceLevelObjectives + .asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + ( + client.descriptors.page.listServiceLevelObjectives + .asyncIterate as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); + }); + + describe('Path templates', () => { + describe('folderAlertPolicy', () => { + const fakePath = '/rendered/path/folderAlertPolicy'; + const expectedParameters = { + folder: 'folderValue', + alert_policy: 'alertPolicyValue', + }; + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.folderAlertPolicyPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderAlertPolicyPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderAlertPolicyPath', () => { + const result = client.folderAlertPolicyPath( + 'folderValue', + 'alertPolicyValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.folderAlertPolicyPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderAlertPolicyName', () => { + const result = client.matchFolderFromFolderAlertPolicyName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + ( + client.pathTemplates.folderAlertPolicyPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchAlertPolicyFromFolderAlertPolicyName', () => { + const result = + client.matchAlertPolicyFromFolderAlertPolicyName(fakePath); + assert.strictEqual(result, 'alertPolicyValue'); + assert( + ( + client.pathTemplates.folderAlertPolicyPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); + + describe('folderAlertPolicyCondition', () => { + const fakePath = '/rendered/path/folderAlertPolicyCondition'; + const expectedParameters = { + folder: 'folderValue', + alert_policy: 'alertPolicyValue', + condition: 'conditionValue', + }; + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.folderAlertPolicyConditionPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderAlertPolicyConditionPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderAlertPolicyConditionPath', () => { + const result = client.folderAlertPolicyConditionPath( + 'folderValue', + 'alertPolicyValue', + 'conditionValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.folderAlertPolicyConditionPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderAlertPolicyConditionName', () => { + const result = + client.matchFolderFromFolderAlertPolicyConditionName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + ( + client.pathTemplates.folderAlertPolicyConditionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchAlertPolicyFromFolderAlertPolicyConditionName', () => { + const result = + client.matchAlertPolicyFromFolderAlertPolicyConditionName(fakePath); + assert.strictEqual(result, 'alertPolicyValue'); + assert( + ( + client.pathTemplates.folderAlertPolicyConditionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchConditionFromFolderAlertPolicyConditionName', () => { + const result = + client.matchConditionFromFolderAlertPolicyConditionName(fakePath); + assert.strictEqual(result, 'conditionValue'); + assert( + ( + client.pathTemplates.folderAlertPolicyConditionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); + + describe('folderChannelDescriptor', () => { + const fakePath = '/rendered/path/folderChannelDescriptor'; + const expectedParameters = { + folder: 'folderValue', + channel_descriptor: 'channelDescriptorValue', + }; + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.folderChannelDescriptorPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderChannelDescriptorPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderChannelDescriptorPath', () => { + const result = client.folderChannelDescriptorPath( + 'folderValue', + 'channelDescriptorValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.folderChannelDescriptorPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderChannelDescriptorName', () => { + const result = + client.matchFolderFromFolderChannelDescriptorName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + ( + client.pathTemplates.folderChannelDescriptorPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchChannelDescriptorFromFolderChannelDescriptorName', () => { + const result = + client.matchChannelDescriptorFromFolderChannelDescriptorName( + fakePath, + ); + assert.strictEqual(result, 'channelDescriptorValue'); + assert( + ( + client.pathTemplates.folderChannelDescriptorPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); + + describe('folderGroup', () => { + const fakePath = '/rendered/path/folderGroup'; + const expectedParameters = { + folder: 'folderValue', + group: 'groupValue', + }; + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.folderGroupPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderGroupPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderGroupPath', () => { + const result = client.folderGroupPath('folderValue', 'groupValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.folderGroupPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderGroupName', () => { + const result = client.matchFolderFromFolderGroupName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + (client.pathTemplates.folderGroupPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchGroupFromFolderGroupName', () => { + const result = client.matchGroupFromFolderGroupName(fakePath); + assert.strictEqual(result, 'groupValue'); + assert( + (client.pathTemplates.folderGroupPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); + + describe('folderNotificationChannel', () => { + const fakePath = '/rendered/path/folderNotificationChannel'; + const expectedParameters = { + folder: 'folderValue', + notification_channel: 'notificationChannelValue', + }; + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.folderNotificationChannelPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderNotificationChannelPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderNotificationChannelPath', () => { + const result = client.folderNotificationChannelPath( + 'folderValue', + 'notificationChannelValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.folderNotificationChannelPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderNotificationChannelName', () => { + const result = + client.matchFolderFromFolderNotificationChannelName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + ( + client.pathTemplates.folderNotificationChannelPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchNotificationChannelFromFolderNotificationChannelName', () => { + const result = + client.matchNotificationChannelFromFolderNotificationChannelName( + fakePath, + ); + assert.strictEqual(result, 'notificationChannelValue'); + assert( + ( + client.pathTemplates.folderNotificationChannelPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); + + describe('folderService', () => { + const fakePath = '/rendered/path/folderService'; + const expectedParameters = { + folder: 'folderValue', + service: 'serviceValue', + }; + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.folderServicePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderServicePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderServicePath', () => { + const result = client.folderServicePath('folderValue', 'serviceValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.folderServicePathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderServiceName', () => { + const result = client.matchFolderFromFolderServiceName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + (client.pathTemplates.folderServicePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServiceFromFolderServiceName', () => { + const result = client.matchServiceFromFolderServiceName(fakePath); + assert.strictEqual(result, 'serviceValue'); + assert( + (client.pathTemplates.folderServicePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); + + describe('folderServiceServiceLevelObjective', () => { + const fakePath = '/rendered/path/folderServiceServiceLevelObjective'; + const expectedParameters = { + folder: 'folderValue', + service: 'serviceValue', + service_level_objective: 'serviceLevelObjectiveValue', + }; + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('folderServiceServiceLevelObjectivePath', () => { + const result = client.folderServiceServiceLevelObjectivePath( + 'folderValue', + 'serviceValue', + 'serviceLevelObjectiveValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderServiceServiceLevelObjectiveName', () => { + const result = + client.matchFolderFromFolderServiceServiceLevelObjectiveName( + fakePath, + ); + assert.strictEqual(result, 'folderValue'); + assert( + ( + client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServiceFromFolderServiceServiceLevelObjectiveName', () => { + const result = + client.matchServiceFromFolderServiceServiceLevelObjectiveName( + fakePath, + ); + assert.strictEqual(result, 'serviceValue'); + assert( + ( + client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServiceLevelObjectiveFromFolderServiceServiceLevelObjectiveName', () => { + const result = + client.matchServiceLevelObjectiveFromFolderServiceServiceLevelObjectiveName( + fakePath, + ); + assert.strictEqual(result, 'serviceLevelObjectiveValue'); + assert( + ( + client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); + + describe('folderUptimeCheckConfig', () => { + const fakePath = '/rendered/path/folderUptimeCheckConfig'; + const expectedParameters = { + folder: 'folderValue', + uptime_check_config: 'uptimeCheckConfigValue', + }; + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.folderUptimeCheckConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderUptimeCheckConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderUptimeCheckConfigPath', () => { + const result = client.folderUptimeCheckConfigPath( + 'folderValue', + 'uptimeCheckConfigValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.folderUptimeCheckConfigPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderUptimeCheckConfigName', () => { + const result = + client.matchFolderFromFolderUptimeCheckConfigName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + ( + client.pathTemplates.folderUptimeCheckConfigPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchUptimeCheckConfigFromFolderUptimeCheckConfigName', () => { + const result = + client.matchUptimeCheckConfigFromFolderUptimeCheckConfigName( + fakePath, + ); + assert.strictEqual(result, 'uptimeCheckConfigValue'); + assert( + ( + client.pathTemplates.folderUptimeCheckConfigPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); + + describe('organizationAlertPolicy', () => { + const fakePath = '/rendered/path/organizationAlertPolicy'; + const expectedParameters = { + organization: 'organizationValue', + alert_policy: 'alertPolicyValue', + }; + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.organizationAlertPolicyPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.organizationAlertPolicyPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('organizationAlertPolicyPath', () => { + const result = client.organizationAlertPolicyPath( + 'organizationValue', + 'alertPolicyValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationAlertPolicyPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationAlertPolicyName', () => { + const result = + client.matchOrganizationFromOrganizationAlertPolicyName(fakePath); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationAlertPolicyPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchAlertPolicyFromOrganizationAlertPolicyName', () => { + const result = + client.matchAlertPolicyFromOrganizationAlertPolicyName(fakePath); + assert.strictEqual(result, 'alertPolicyValue'); + assert( + ( + client.pathTemplates.organizationAlertPolicyPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); + + describe('organizationAlertPolicyCondition', () => { + const fakePath = '/rendered/path/organizationAlertPolicyCondition'; + const expectedParameters = { + organization: 'organizationValue', + alert_policy: 'alertPolicyValue', + condition: 'conditionValue', + }; + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.organizationAlertPolicyConditionPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.organizationAlertPolicyConditionPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('organizationAlertPolicyConditionPath', () => { + const result = client.organizationAlertPolicyConditionPath( + 'organizationValue', + 'alertPolicyValue', + 'conditionValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationAlertPolicyConditionPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationAlertPolicyConditionName', () => { + const result = + client.matchOrganizationFromOrganizationAlertPolicyConditionName( + fakePath, + ); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationAlertPolicyConditionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchAlertPolicyFromOrganizationAlertPolicyConditionName', () => { + const result = + client.matchAlertPolicyFromOrganizationAlertPolicyConditionName( + fakePath, + ); + assert.strictEqual(result, 'alertPolicyValue'); + assert( + ( + client.pathTemplates.organizationAlertPolicyConditionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchConditionFromOrganizationAlertPolicyConditionName', () => { + const result = + client.matchConditionFromOrganizationAlertPolicyConditionName( + fakePath, + ); + assert.strictEqual(result, 'conditionValue'); + assert( + ( + client.pathTemplates.organizationAlertPolicyConditionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); + + describe('organizationChannelDescriptor', () => { + const fakePath = '/rendered/path/organizationChannelDescriptor'; + const expectedParameters = { + organization: 'organizationValue', + channel_descriptor: 'channelDescriptorValue', + }; + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.organizationChannelDescriptorPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.organizationChannelDescriptorPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('organizationChannelDescriptorPath', () => { + const result = client.organizationChannelDescriptorPath( + 'organizationValue', + 'channelDescriptorValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationChannelDescriptorPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationChannelDescriptorName', () => { + const result = + client.matchOrganizationFromOrganizationChannelDescriptorName( + fakePath, + ); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationChannelDescriptorPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchChannelDescriptorFromOrganizationChannelDescriptorName', () => { + const result = + client.matchChannelDescriptorFromOrganizationChannelDescriptorName( + fakePath, + ); + assert.strictEqual(result, 'channelDescriptorValue'); + assert( + ( + client.pathTemplates.organizationChannelDescriptorPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); + + describe('organizationGroup', () => { + const fakePath = '/rendered/path/organizationGroup'; + const expectedParameters = { + organization: 'organizationValue', + group: 'groupValue', + }; + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.organizationGroupPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.organizationGroupPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('organizationGroupPath', () => { + const result = client.organizationGroupPath( + 'organizationValue', + 'groupValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationGroupPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationGroupName', () => { + const result = + client.matchOrganizationFromOrganizationGroupName(fakePath); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationGroupPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchGroupFromOrganizationGroupName', () => { + const result = client.matchGroupFromOrganizationGroupName(fakePath); + assert.strictEqual(result, 'groupValue'); + assert( + ( + client.pathTemplates.organizationGroupPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); + + describe('organizationNotificationChannel', () => { + const fakePath = '/rendered/path/organizationNotificationChannel'; + const expectedParameters = { + organization: 'organizationValue', + notification_channel: 'notificationChannelValue', + }; + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.organizationNotificationChannelPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.organizationNotificationChannelPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('organizationNotificationChannelPath', () => { + const result = client.organizationNotificationChannelPath( + 'organizationValue', + 'notificationChannelValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationNotificationChannelPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationNotificationChannelName', () => { + const result = + client.matchOrganizationFromOrganizationNotificationChannelName( + fakePath, + ); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationNotificationChannelPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchNotificationChannelFromOrganizationNotificationChannelName', () => { + const result = + client.matchNotificationChannelFromOrganizationNotificationChannelName( + fakePath, + ); + assert.strictEqual(result, 'notificationChannelValue'); + assert( + ( + client.pathTemplates.organizationNotificationChannelPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); + + describe('organizationService', () => { + const fakePath = '/rendered/path/organizationService'; + const expectedParameters = { + organization: 'organizationValue', + service: 'serviceValue', + }; + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.organizationServicePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.organizationServicePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('organizationServicePath', () => { + const result = client.organizationServicePath( + 'organizationValue', + 'serviceValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationServicePathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationServiceName', () => { + const result = + client.matchOrganizationFromOrganizationServiceName(fakePath); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationServicePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServiceFromOrganizationServiceName', () => { + const result = client.matchServiceFromOrganizationServiceName(fakePath); + assert.strictEqual(result, 'serviceValue'); + assert( + ( + client.pathTemplates.organizationServicePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); + + describe('organizationServiceServiceLevelObjective', () => { + const fakePath = + '/rendered/path/organizationServiceServiceLevelObjective'; + const expectedParameters = { + organization: 'organizationValue', + service: 'serviceValue', + service_level_objective: 'serviceLevelObjectiveValue', + }; + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('organizationServiceServiceLevelObjectivePath', () => { + const result = client.organizationServiceServiceLevelObjectivePath( + 'organizationValue', + 'serviceValue', + 'serviceLevelObjectiveValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates + .organizationServiceServiceLevelObjectivePathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationServiceServiceLevelObjectiveName', () => { + const result = + client.matchOrganizationFromOrganizationServiceServiceLevelObjectiveName( + fakePath, + ); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates + .organizationServiceServiceLevelObjectivePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServiceFromOrganizationServiceServiceLevelObjectiveName', () => { + const result = + client.matchServiceFromOrganizationServiceServiceLevelObjectiveName( + fakePath, + ); + assert.strictEqual(result, 'serviceValue'); + assert( + ( + client.pathTemplates + .organizationServiceServiceLevelObjectivePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServiceLevelObjectiveFromOrganizationServiceServiceLevelObjectiveName', () => { + const result = + client.matchServiceLevelObjectiveFromOrganizationServiceServiceLevelObjectiveName( + fakePath, + ); + assert.strictEqual(result, 'serviceLevelObjectiveValue'); + assert( + ( + client.pathTemplates + .organizationServiceServiceLevelObjectivePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); + + describe('organizationUptimeCheckConfig', () => { + const fakePath = '/rendered/path/organizationUptimeCheckConfig'; + const expectedParameters = { + organization: 'organizationValue', + uptime_check_config: 'uptimeCheckConfigValue', + }; + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.organizationUptimeCheckConfigPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.organizationUptimeCheckConfigPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('organizationUptimeCheckConfigPath', () => { + const result = client.organizationUptimeCheckConfigPath( + 'organizationValue', + 'uptimeCheckConfigValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationUptimeCheckConfigPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationUptimeCheckConfigName', () => { + const result = + client.matchOrganizationFromOrganizationUptimeCheckConfigName( + fakePath, + ); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationUptimeCheckConfigPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchUptimeCheckConfigFromOrganizationUptimeCheckConfigName', () => { + const result = + client.matchUptimeCheckConfigFromOrganizationUptimeCheckConfigName( + fakePath, + ); + assert.strictEqual(result, 'uptimeCheckConfigValue'); + assert( + ( + client.pathTemplates.organizationUptimeCheckConfigPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); + + describe('projectAlertPolicy', () => { + const fakePath = '/rendered/path/projectAlertPolicy'; + const expectedParameters = { + project: 'projectValue', + alert_policy: 'alertPolicyValue', + }; + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.projectAlertPolicyPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectAlertPolicyPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectAlertPolicyPath', () => { + const result = client.projectAlertPolicyPath( + 'projectValue', + 'alertPolicyValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.projectAlertPolicyPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectAlertPolicyName', () => { + const result = client.matchProjectFromProjectAlertPolicyName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.projectAlertPolicyPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchAlertPolicyFromProjectAlertPolicyName', () => { + const result = + client.matchAlertPolicyFromProjectAlertPolicyName(fakePath); + assert.strictEqual(result, 'alertPolicyValue'); + assert( + ( + client.pathTemplates.projectAlertPolicyPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); + + describe('projectAlertPolicyCondition', () => { + const fakePath = '/rendered/path/projectAlertPolicyCondition'; + const expectedParameters = { + project: 'projectValue', + alert_policy: 'alertPolicyValue', + condition: 'conditionValue', + }; + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.projectAlertPolicyConditionPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.projectAlertPolicyConditionPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectAlertPolicyConditionPath', () => { + const result = client.projectAlertPolicyConditionPath( + 'projectValue', + 'alertPolicyValue', + 'conditionValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.projectAlertPolicyConditionPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectAlertPolicyConditionName', () => { + const result = + client.matchProjectFromProjectAlertPolicyConditionName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.projectAlertPolicyConditionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchAlertPolicyFromProjectAlertPolicyConditionName', () => { + const result = + client.matchAlertPolicyFromProjectAlertPolicyConditionName(fakePath); + assert.strictEqual(result, 'alertPolicyValue'); + assert( + ( + client.pathTemplates.projectAlertPolicyConditionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchConditionFromProjectAlertPolicyConditionName', () => { + const result = + client.matchConditionFromProjectAlertPolicyConditionName(fakePath); + assert.strictEqual(result, 'conditionValue'); + assert( + ( + client.pathTemplates.projectAlertPolicyConditionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); + + describe('projectChannelDescriptor', () => { + const fakePath = '/rendered/path/projectChannelDescriptor'; + const expectedParameters = { + project: 'projectValue', + channel_descriptor: 'channelDescriptorValue', + }; + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.projectChannelDescriptorPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectChannelDescriptorPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectChannelDescriptorPath', () => { + const result = client.projectChannelDescriptorPath( + 'projectValue', + 'channelDescriptorValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.projectChannelDescriptorPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectChannelDescriptorName', () => { + const result = + client.matchProjectFromProjectChannelDescriptorName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.projectChannelDescriptorPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchChannelDescriptorFromProjectChannelDescriptorName', () => { + const result = + client.matchChannelDescriptorFromProjectChannelDescriptorName( + fakePath, + ); + assert.strictEqual(result, 'channelDescriptorValue'); + assert( + ( + client.pathTemplates.projectChannelDescriptorPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); + + describe('projectGroup', () => { + const fakePath = '/rendered/path/projectGroup'; + const expectedParameters = { + project: 'projectValue', + group: 'groupValue', + }; + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.projectGroupPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectGroupPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectGroupPath', () => { + const result = client.projectGroupPath('projectValue', 'groupValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.projectGroupPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectGroupName', () => { + const result = client.matchProjectFromProjectGroupName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.projectGroupPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchGroupFromProjectGroupName', () => { + const result = client.matchGroupFromProjectGroupName(fakePath); + assert.strictEqual(result, 'groupValue'); + assert( + (client.pathTemplates.projectGroupPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); + + describe('projectNotificationChannel', () => { + const fakePath = '/rendered/path/projectNotificationChannel'; + const expectedParameters = { + project: 'projectValue', + notification_channel: 'notificationChannelValue', + }; + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.projectNotificationChannelPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectNotificationChannelPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectNotificationChannelPath', () => { + const result = client.projectNotificationChannelPath( + 'projectValue', + 'notificationChannelValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.projectNotificationChannelPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectNotificationChannelName', () => { + const result = + client.matchProjectFromProjectNotificationChannelName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.projectNotificationChannelPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchNotificationChannelFromProjectNotificationChannelName', () => { + const result = + client.matchNotificationChannelFromProjectNotificationChannelName( + fakePath, + ); + assert.strictEqual(result, 'notificationChannelValue'); + assert( + ( + client.pathTemplates.projectNotificationChannelPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); + + describe('projectService', () => { + const fakePath = '/rendered/path/projectService'; + const expectedParameters = { + project: 'projectValue', + service: 'serviceValue', + }; + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.projectServicePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectServicePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectServicePath', () => { + const result = client.projectServicePath( + 'projectValue', + 'serviceValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.projectServicePathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectServiceName', () => { + const result = client.matchProjectFromProjectServiceName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.projectServicePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServiceFromProjectServiceName', () => { + const result = client.matchServiceFromProjectServiceName(fakePath); + assert.strictEqual(result, 'serviceValue'); + assert( + (client.pathTemplates.projectServicePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); + + describe('projectServiceServiceLevelObjective', () => { + const fakePath = '/rendered/path/projectServiceServiceLevelObjective'; + const expectedParameters = { + project: 'projectValue', + service: 'serviceValue', + service_level_objective: 'serviceLevelObjectiveValue', + }; + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('projectServiceServiceLevelObjectivePath', () => { + const result = client.projectServiceServiceLevelObjectivePath( + 'projectValue', + 'serviceValue', + 'serviceLevelObjectiveValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectServiceServiceLevelObjectiveName', () => { + const result = + client.matchProjectFromProjectServiceServiceLevelObjectiveName( + fakePath, + ); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServiceFromProjectServiceServiceLevelObjectiveName', () => { + const result = + client.matchServiceFromProjectServiceServiceLevelObjectiveName( + fakePath, + ); + assert.strictEqual(result, 'serviceValue'); + assert( + ( + client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServiceLevelObjectiveFromProjectServiceServiceLevelObjectiveName', () => { + const result = + client.matchServiceLevelObjectiveFromProjectServiceServiceLevelObjectiveName( + fakePath, + ); + assert.strictEqual(result, 'serviceLevelObjectiveValue'); + assert( + ( + client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); + + describe('projectUptimeCheckConfig', () => { + const fakePath = '/rendered/path/projectUptimeCheckConfig'; + const expectedParameters = { + project: 'projectValue', + uptime_check_config: 'uptimeCheckConfigValue', + }; + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.projectUptimeCheckConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectUptimeCheckConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectUptimeCheckConfigPath', () => { + const result = client.projectUptimeCheckConfigPath( + 'projectValue', + 'uptimeCheckConfigValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.projectUptimeCheckConfigPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectUptimeCheckConfigName', () => { + const result = + client.matchProjectFromProjectUptimeCheckConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.projectUptimeCheckConfigPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchUptimeCheckConfigFromProjectUptimeCheckConfigName', () => { + const result = + client.matchUptimeCheckConfigFromProjectUptimeCheckConfigName( + fakePath, + ); + assert.strictEqual(result, 'uptimeCheckConfigValue'); + assert( + ( + client.pathTemplates.projectUptimeCheckConfigPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); + }); }); diff --git a/core/generator/gapic-generator-typescript/baselines/monitoring-esm/esm/test/gapic_uptime_check_service_v3.ts.baseline b/core/generator/gapic-generator-typescript/baselines/monitoring-esm/esm/test/gapic_uptime_check_service_v3.ts.baseline index 8c656b1300af..be87ec1f655e 100644 --- a/core/generator/gapic-generator-typescript/baselines/monitoring-esm/esm/test/gapic_uptime_check_service_v3.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/monitoring-esm/esm/test/gapic_uptime_check_service_v3.ts.baseline @@ -20,16 +20,16 @@ import * as protos from '../../protos/protos.js'; import assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as uptimecheckserviceModule from '../src/index.js'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; -import {protobuf} from 'google-gax'; +import { protobuf } from 'google-gax'; import fs from 'fs'; import path from 'path'; -import {fileURLToPath} from 'url'; +import { fileURLToPath } from 'url'; // @ts-ignore const dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -37,2053 +37,3046 @@ const dirname = path.dirname(fileURLToPath(import.meta.url)); // to fill in default values for request objects const root = protobuf.Root.fromJSON( JSON.parse( - fs.readFileSync(path.join(dirname, '..', '..', 'protos/protos.json'), 'utf8') - )) + fs.readFileSync( + path.join(dirname, '..', '..', 'protos/protos.json'), + 'utf8', + ), + ), +); // eslint-disable-next-line @typescript-eslint/no-unused-vars function getTypeDefaultValue(typeName: string, fields: string[]) { - let type = root.lookupType(typeName) as protobuf.Type; - for (const field of fields.slice(0, -1)) { - type = type?.fields[field]?.resolvedType as protobuf.Type; - } - return type?.fields[fields[fields.length - 1]]?.defaultValue ?? null; + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type?.fields[field]?.resolvedType as protobuf.Type; + } + return type?.fields[fields[fields.length - 1]]?.defaultValue ?? null; } function generateSampleMessage(instance: T) { - const filledObject = (instance.constructor as typeof protobuf.Message) - .toObject(instance as protobuf.Message, {defaults: true}); - return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, { defaults: true }); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; } function stubSimpleCall(response?: ResponseType, error?: Error) { - return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); } -function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { - return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +function stubSimpleCallWithCallback( + response?: ResponseType, + error?: Error, +) { + return error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); } -function stubPageStreamingCall(responses?: ResponseType[], error?: Error) { - const pagingStub = sinon.stub(); - if (responses) { - for (let i = 0; i < responses.length; ++i) { - pagingStub.onCall(i).callsArgWith(2, null, responses[i]); - } +function stubPageStreamingCall( + responses?: ResponseType[], + error?: Error, +) { + const pagingStub = sinon.stub(); + if (responses) { + for (let i = 0; i < responses.length; ++i) { + pagingStub.onCall(i).callsArgWith(2, null, responses[i]); } - const transformStub = error ? sinon.stub().callsArgWith(2, error) : pagingStub; - const mockStream = new PassThrough({ - objectMode: true, - transform: transformStub, - }); - // trigger as many responses as needed - if (responses) { - for (let i = 0; i < responses.length; ++i) { - setImmediate(() => { mockStream.write({}); }); - } - setImmediate(() => { mockStream.end(); }); - } else { - setImmediate(() => { mockStream.write({}); }); - setImmediate(() => { mockStream.end(); }); + } + const transformStub = error + ? sinon.stub().callsArgWith(2, error) + : pagingStub; + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + // trigger as many responses as needed + if (responses) { + for (let i = 0; i < responses.length; ++i) { + setImmediate(() => { + mockStream.write({}); + }); } - return sinon.stub().returns(mockStream); + setImmediate(() => { + mockStream.end(); + }); + } else { + setImmediate(() => { + mockStream.write({}); + }); + setImmediate(() => { + mockStream.end(); + }); + } + return sinon.stub().returns(mockStream); } -function stubAsyncIterationCall(responses?: ResponseType[], error?: Error) { - let counter = 0; - const asyncIterable = { - [Symbol.asyncIterator]() { - return { - async next() { - if (error) { - return Promise.reject(error); - } - if (counter >= responses!.length) { - return Promise.resolve({done: true, value: undefined}); - } - return Promise.resolve({done: false, value: responses![counter++]}); - } - }; - } - }; - return sinon.stub().returns(asyncIterable); +function stubAsyncIterationCall( + responses?: ResponseType[], + error?: Error, +) { + let counter = 0; + const asyncIterable = { + [Symbol.asyncIterator]() { + return { + async next() { + if (error) { + return Promise.reject(error); + } + if (counter >= responses!.length) { + return Promise.resolve({ done: true, value: undefined }); + } + return Promise.resolve({ done: false, value: responses![counter++] }); + }, + }; + }, + }; + return sinon.stub().returns(asyncIterable); } describe('v3.UptimeCheckServiceClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'monitoring.googleapis.com'); - }); - - it('has universeDomain', () => { - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); - - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - it('throws DeprecationWarning if static servicePath is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const servicePath = uptimecheckserviceModule.v3.UptimeCheckServiceClient.servicePath; - assert.strictEqual(servicePath, 'monitoring.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = uptimecheckserviceModule.v3.UptimeCheckServiceClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'monitoring.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'monitoring.example.com'); - }); - - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'monitoring.example.com'); - }); - - if (typeof process === 'object' && 'env' in process) { - describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { - it('sets apiEndpoint from environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'monitoring.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - - it('value configured in code has priority over environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'monitoring.configured.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { new uptimecheckserviceModule.v3.UptimeCheckServiceClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); - - it('has port', () => { - const port = uptimecheckserviceModule.v3.UptimeCheckServiceClient.port; - assert(port); - assert(typeof port === 'number'); - }); - - it('should create a client with no option', () => { - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient(); - assert(client); - }); - - it('should create a client with gRPC fallback', () => { - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ - fallback: true, - }); - assert(client); - }); - - it('has initialize method and supports deferred initialization', async () => { - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.uptimeCheckServiceStub, undefined); - await client.initialize(); - assert(client.uptimeCheckServiceStub); - }); - - it('has close method for the initialized client', done => { - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.uptimeCheckServiceStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); - - it('has close method for the non-initialized client', done => { - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.uptimeCheckServiceStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); - - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); - }); - - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId((err?: Error|null, projectId?: string|null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } - }); - }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'monitoring.googleapis.com'); }); - describe('getUptimeCheckConfig', () => { - it('invokes getUptimeCheckConfig without error', async () => { - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.GetUptimeCheckConfigRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.GetUptimeCheckConfigRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.monitoring.v3.UptimeCheckConfig() - ); - client.innerApiCalls.getUptimeCheckConfig = stubSimpleCall(expectedResponse); - const [response] = await client.getUptimeCheckConfig(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getUptimeCheckConfig as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getUptimeCheckConfig as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getUptimeCheckConfig without error using callback', async () => { - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.GetUptimeCheckConfigRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.GetUptimeCheckConfigRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.monitoring.v3.UptimeCheckConfig() - ); - client.innerApiCalls.getUptimeCheckConfig = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getUptimeCheckConfig( - request, - (err?: Error|null, result?: protos.google.monitoring.v3.IUptimeCheckConfig|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getUptimeCheckConfig as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getUptimeCheckConfig as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getUptimeCheckConfig with error', async () => { - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.GetUptimeCheckConfigRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.GetUptimeCheckConfigRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getUptimeCheckConfig = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getUptimeCheckConfig(request), expectedError); - const actualRequest = (client.innerApiCalls.getUptimeCheckConfig as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getUptimeCheckConfig as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getUptimeCheckConfig with closed client', async () => { - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.GetUptimeCheckConfigRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.GetUptimeCheckConfigRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getUptimeCheckConfig(request), expectedError); - }); + it('has universeDomain', () => { + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); }); - describe('createUptimeCheckConfig', () => { - it('invokes createUptimeCheckConfig without error', async () => { - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.CreateUptimeCheckConfigRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.CreateUptimeCheckConfigRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.monitoring.v3.UptimeCheckConfig() - ); - client.innerApiCalls.createUptimeCheckConfig = stubSimpleCall(expectedResponse); - const [response] = await client.createUptimeCheckConfig(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createUptimeCheckConfig as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createUptimeCheckConfig as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createUptimeCheckConfig without error using callback', async () => { - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.CreateUptimeCheckConfigRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.CreateUptimeCheckConfigRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.monitoring.v3.UptimeCheckConfig() - ); - client.innerApiCalls.createUptimeCheckConfig = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createUptimeCheckConfig( - request, - (err?: Error|null, result?: protos.google.monitoring.v3.IUptimeCheckConfig|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createUptimeCheckConfig as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createUptimeCheckConfig as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createUptimeCheckConfig with error', async () => { - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.CreateUptimeCheckConfigRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.CreateUptimeCheckConfigRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createUptimeCheckConfig = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createUptimeCheckConfig(request), expectedError); - const actualRequest = (client.innerApiCalls.createUptimeCheckConfig as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createUptimeCheckConfig as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createUptimeCheckConfig with closed client', async () => { - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.CreateUptimeCheckConfigRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.CreateUptimeCheckConfigRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createUptimeCheckConfig(request), expectedError); - }); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = + uptimecheckserviceModule.v3.UptimeCheckServiceClient.servicePath; + assert.strictEqual(servicePath, 'monitoring.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + uptimecheckserviceModule.v3.UptimeCheckServiceClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'monitoring.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + universeDomain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'monitoring.example.com'); }); - describe('updateUptimeCheckConfig', () => { - it('invokes updateUptimeCheckConfig without error', async () => { - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.UpdateUptimeCheckConfigRequest() - ); - request.uptimeCheckConfig ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.UpdateUptimeCheckConfigRequest', ['uptimeCheckConfig', 'name']); - request.uptimeCheckConfig.name = defaultValue1; - const expectedHeaderRequestParams = `uptime_check_config.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.monitoring.v3.UptimeCheckConfig() - ); - client.innerApiCalls.updateUptimeCheckConfig = stubSimpleCall(expectedResponse); - const [response] = await client.updateUptimeCheckConfig(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateUptimeCheckConfig as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateUptimeCheckConfig as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateUptimeCheckConfig without error using callback', async () => { - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.UpdateUptimeCheckConfigRequest() - ); - request.uptimeCheckConfig ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.UpdateUptimeCheckConfigRequest', ['uptimeCheckConfig', 'name']); - request.uptimeCheckConfig.name = defaultValue1; - const expectedHeaderRequestParams = `uptime_check_config.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.monitoring.v3.UptimeCheckConfig() - ); - client.innerApiCalls.updateUptimeCheckConfig = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateUptimeCheckConfig( - request, - (err?: Error|null, result?: protos.google.monitoring.v3.IUptimeCheckConfig|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateUptimeCheckConfig as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateUptimeCheckConfig as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateUptimeCheckConfig with error', async () => { - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.UpdateUptimeCheckConfigRequest() - ); - request.uptimeCheckConfig ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.UpdateUptimeCheckConfigRequest', ['uptimeCheckConfig', 'name']); - request.uptimeCheckConfig.name = defaultValue1; - const expectedHeaderRequestParams = `uptime_check_config.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateUptimeCheckConfig = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateUptimeCheckConfig(request), expectedError); - const actualRequest = (client.innerApiCalls.updateUptimeCheckConfig as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateUptimeCheckConfig as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateUptimeCheckConfig with closed client', async () => { - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.UpdateUptimeCheckConfigRequest() - ); - request.uptimeCheckConfig ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.UpdateUptimeCheckConfigRequest', ['uptimeCheckConfig', 'name']); - request.uptimeCheckConfig.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateUptimeCheckConfig(request), expectedError); - }); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + universe_domain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'monitoring.example.com'); }); - describe('deleteUptimeCheckConfig', () => { - it('invokes deleteUptimeCheckConfig without error', async () => { - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.DeleteUptimeCheckConfigRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.DeleteUptimeCheckConfigRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteUptimeCheckConfig = stubSimpleCall(expectedResponse); - const [response] = await client.deleteUptimeCheckConfig(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteUptimeCheckConfig as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteUptimeCheckConfig as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + if (typeof process === 'object' && 'env' in process) { + describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { + it('sets apiEndpoint from environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = + new uptimecheckserviceModule.v3.UptimeCheckServiceClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'monitoring.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } + }); + + it('value configured in code has priority over environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = + new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + universeDomain: 'configured.example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'monitoring.configured.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } + }); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); + }); - it('invokes deleteUptimeCheckConfig without error using callback', async () => { - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.DeleteUptimeCheckConfigRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.DeleteUptimeCheckConfigRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteUptimeCheckConfig = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteUptimeCheckConfig( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteUptimeCheckConfig as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteUptimeCheckConfig as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has port', () => { + const port = uptimecheckserviceModule.v3.UptimeCheckServiceClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('invokes deleteUptimeCheckConfig with error', async () => { - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.DeleteUptimeCheckConfigRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.DeleteUptimeCheckConfigRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteUptimeCheckConfig = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteUptimeCheckConfig(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteUptimeCheckConfig as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteUptimeCheckConfig as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('should create a client with no option', () => { + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient(); + assert(client); + }); - it('invokes deleteUptimeCheckConfig with closed client', async () => { - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.DeleteUptimeCheckConfigRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.DeleteUptimeCheckConfigRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteUptimeCheckConfig(request), expectedError); - }); + it('should create a client with gRPC fallback', () => { + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + fallback: true, + }); + assert(client); }); - describe('listUptimeCheckConfigs', () => { - it('invokes listUptimeCheckConfigs without error', async () => { - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListUptimeCheckConfigsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListUptimeCheckConfigsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.monitoring.v3.UptimeCheckConfig()), - generateSampleMessage(new protos.google.monitoring.v3.UptimeCheckConfig()), - generateSampleMessage(new protos.google.monitoring.v3.UptimeCheckConfig()), - ]; - client.innerApiCalls.listUptimeCheckConfigs = stubSimpleCall(expectedResponse); - const [response] = await client.listUptimeCheckConfigs(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listUptimeCheckConfigs as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listUptimeCheckConfigs as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has initialize method and supports deferred initialization', async () => { + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.uptimeCheckServiceStub, undefined); + await client.initialize(); + assert(client.uptimeCheckServiceStub); + }); - it('invokes listUptimeCheckConfigs without error using callback', async () => { - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListUptimeCheckConfigsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListUptimeCheckConfigsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.monitoring.v3.UptimeCheckConfig()), - generateSampleMessage(new protos.google.monitoring.v3.UptimeCheckConfig()), - generateSampleMessage(new protos.google.monitoring.v3.UptimeCheckConfig()), - ]; - client.innerApiCalls.listUptimeCheckConfigs = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listUptimeCheckConfigs( - request, - (err?: Error|null, result?: protos.google.monitoring.v3.IUptimeCheckConfig[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listUptimeCheckConfigs as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listUptimeCheckConfigs as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('has close method for the initialized client', (done) => { + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.uptimeCheckServiceStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes listUptimeCheckConfigs with error', async () => { - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListUptimeCheckConfigsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListUptimeCheckConfigsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listUptimeCheckConfigs = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listUptimeCheckConfigs(request), expectedError); - const actualRequest = (client.innerApiCalls.listUptimeCheckConfigs as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listUptimeCheckConfigs as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('has close method for the non-initialized client', (done) => { + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.uptimeCheckServiceStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes listUptimeCheckConfigsStream without error', async () => { - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListUptimeCheckConfigsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListUptimeCheckConfigsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.monitoring.v3.UptimeCheckConfig()), - generateSampleMessage(new protos.google.monitoring.v3.UptimeCheckConfig()), - generateSampleMessage(new protos.google.monitoring.v3.UptimeCheckConfig()), - ]; - client.descriptors.page.listUptimeCheckConfigs.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listUptimeCheckConfigsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.monitoring.v3.UptimeCheckConfig[] = []; - stream.on('data', (response: protos.google.monitoring.v3.UptimeCheckConfig) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.listUptimeCheckConfigs.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listUptimeCheckConfigs, request)); - assert( - (client.descriptors.page.listUptimeCheckConfigs.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + }); - it('invokes listUptimeCheckConfigsStream with error', async () => { - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListUptimeCheckConfigsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListUptimeCheckConfigsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listUptimeCheckConfigs.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listUptimeCheckConfigsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.monitoring.v3.UptimeCheckConfig[] = []; - stream.on('data', (response: protos.google.monitoring.v3.UptimeCheckConfig) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listUptimeCheckConfigs.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listUptimeCheckConfigs, request)); - assert( - (client.descriptors.page.listUptimeCheckConfigs.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } + }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + }); + + describe('getUptimeCheckConfig', () => { + it('invokes getUptimeCheckConfig without error', async () => { + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.GetUptimeCheckConfigRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.GetUptimeCheckConfigRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.monitoring.v3.UptimeCheckConfig(), + ); + client.innerApiCalls.getUptimeCheckConfig = + stubSimpleCall(expectedResponse); + const [response] = await client.getUptimeCheckConfig(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getUptimeCheckConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getUptimeCheckConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('uses async iteration with listUptimeCheckConfigs without error', async () => { - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListUptimeCheckConfigsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListUptimeCheckConfigsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.monitoring.v3.UptimeCheckConfig()), - generateSampleMessage(new protos.google.monitoring.v3.UptimeCheckConfig()), - generateSampleMessage(new protos.google.monitoring.v3.UptimeCheckConfig()), - ]; - client.descriptors.page.listUptimeCheckConfigs.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.monitoring.v3.IUptimeCheckConfig[] = []; - const iterable = client.listUptimeCheckConfigsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); + it('invokes getUptimeCheckConfig without error using callback', async () => { + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.GetUptimeCheckConfigRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.GetUptimeCheckConfigRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.monitoring.v3.UptimeCheckConfig(), + ); + client.innerApiCalls.getUptimeCheckConfig = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getUptimeCheckConfig( + request, + ( + err?: Error | null, + result?: protos.google.monitoring.v3.IUptimeCheckConfig | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listUptimeCheckConfigs.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listUptimeCheckConfigs.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); - - it('uses async iteration with listUptimeCheckConfigs with error', async () => { - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListUptimeCheckConfigsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListUptimeCheckConfigsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listUptimeCheckConfigs.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listUptimeCheckConfigsAsync(request); - await assert.rejects(async () => { - const responses: protos.google.monitoring.v3.IUptimeCheckConfig[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listUptimeCheckConfigs.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listUptimeCheckConfigs.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getUptimeCheckConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getUptimeCheckConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('listUptimeCheckIps', () => { - it('invokes listUptimeCheckIps without error', async () => { - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListUptimeCheckIpsRequest() - );const expectedResponse = [ - generateSampleMessage(new protos.google.monitoring.v3.UptimeCheckIp()), - generateSampleMessage(new protos.google.monitoring.v3.UptimeCheckIp()), - generateSampleMessage(new protos.google.monitoring.v3.UptimeCheckIp()), - ]; - client.innerApiCalls.listUptimeCheckIps = stubSimpleCall(expectedResponse); - const [response] = await client.listUptimeCheckIps(request); - assert.deepStrictEqual(response, expectedResponse); - }); - - it('invokes listUptimeCheckIps without error using callback', async () => { - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListUptimeCheckIpsRequest() - );const expectedResponse = [ - generateSampleMessage(new protos.google.monitoring.v3.UptimeCheckIp()), - generateSampleMessage(new protos.google.monitoring.v3.UptimeCheckIp()), - generateSampleMessage(new protos.google.monitoring.v3.UptimeCheckIp()), - ]; - client.innerApiCalls.listUptimeCheckIps = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listUptimeCheckIps( - request, - (err?: Error|null, result?: protos.google.monitoring.v3.IUptimeCheckIp[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); - - it('invokes listUptimeCheckIps with error', async () => { - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListUptimeCheckIpsRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.listUptimeCheckIps = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listUptimeCheckIps(request), expectedError); - }); - - it('invokes listUptimeCheckIpsStream without error', async () => { - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListUptimeCheckIpsRequest() - ); - const expectedResponse = [ - generateSampleMessage(new protos.google.monitoring.v3.UptimeCheckIp()), - generateSampleMessage(new protos.google.monitoring.v3.UptimeCheckIp()), - generateSampleMessage(new protos.google.monitoring.v3.UptimeCheckIp()), - ]; - client.descriptors.page.listUptimeCheckIps.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listUptimeCheckIpsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.monitoring.v3.UptimeCheckIp[] = []; - stream.on('data', (response: protos.google.monitoring.v3.UptimeCheckIp) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.listUptimeCheckIps.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listUptimeCheckIps, request)); - }); + it('invokes getUptimeCheckConfig with error', async () => { + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.GetUptimeCheckConfigRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.GetUptimeCheckConfigRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getUptimeCheckConfig = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getUptimeCheckConfig(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getUptimeCheckConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getUptimeCheckConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listUptimeCheckIpsStream with error', async () => { - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListUptimeCheckIpsRequest() - ); - const expectedError = new Error('expected'); - client.descriptors.page.listUptimeCheckIps.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listUptimeCheckIpsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.monitoring.v3.UptimeCheckIp[] = []; - stream.on('data', (response: protos.google.monitoring.v3.UptimeCheckIp) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listUptimeCheckIps.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listUptimeCheckIps, request)); - }); + it('invokes getUptimeCheckConfig with closed client', async () => { + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.GetUptimeCheckConfigRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.GetUptimeCheckConfigRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getUptimeCheckConfig(request), expectedError); + }); + }); + + describe('createUptimeCheckConfig', () => { + it('invokes createUptimeCheckConfig without error', async () => { + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.CreateUptimeCheckConfigRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.CreateUptimeCheckConfigRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.monitoring.v3.UptimeCheckConfig(), + ); + client.innerApiCalls.createUptimeCheckConfig = + stubSimpleCall(expectedResponse); + const [response] = await client.createUptimeCheckConfig(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createUptimeCheckConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createUptimeCheckConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('uses async iteration with listUptimeCheckIps without error', async () => { - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListUptimeCheckIpsRequest() - ); - const expectedResponse = [ - generateSampleMessage(new protos.google.monitoring.v3.UptimeCheckIp()), - generateSampleMessage(new protos.google.monitoring.v3.UptimeCheckIp()), - generateSampleMessage(new protos.google.monitoring.v3.UptimeCheckIp()), - ]; - client.descriptors.page.listUptimeCheckIps.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.monitoring.v3.IUptimeCheckIp[] = []; - const iterable = client.listUptimeCheckIpsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); + it('invokes createUptimeCheckConfig without error using callback', async () => { + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.CreateUptimeCheckConfigRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.CreateUptimeCheckConfigRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.monitoring.v3.UptimeCheckConfig(), + ); + client.innerApiCalls.createUptimeCheckConfig = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createUptimeCheckConfig( + request, + ( + err?: Error | null, + result?: protos.google.monitoring.v3.IUptimeCheckConfig | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listUptimeCheckIps.asyncIterate as SinonStub) - .getCall(0).args[1], request); - }); - - it('uses async iteration with listUptimeCheckIps with error', async () => { - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListUptimeCheckIpsRequest() - ); - const expectedError = new Error('expected'); - client.descriptors.page.listUptimeCheckIps.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listUptimeCheckIpsAsync(request); - await assert.rejects(async () => { - const responses: protos.google.monitoring.v3.IUptimeCheckIp[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listUptimeCheckIps.asyncIterate as SinonStub) - .getCall(0).args[1], request); - }); + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createUptimeCheckConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createUptimeCheckConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('Path templates', () => { - - describe('folderAlertPolicy', () => { - const fakePath = "/rendered/path/folderAlertPolicy"; - const expectedParameters = { - folder: "folderValue", - alert_policy: "alertPolicyValue", - }; - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.folderAlertPolicyPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderAlertPolicyPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderAlertPolicyPath', () => { - const result = client.folderAlertPolicyPath("folderValue", "alertPolicyValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderAlertPolicyPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderAlertPolicyName', () => { - const result = client.matchFolderFromFolderAlertPolicyName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderAlertPolicyPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchAlertPolicyFromFolderAlertPolicyName', () => { - const result = client.matchAlertPolicyFromFolderAlertPolicyName(fakePath); - assert.strictEqual(result, "alertPolicyValue"); - assert((client.pathTemplates.folderAlertPolicyPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('folderAlertPolicyCondition', () => { - const fakePath = "/rendered/path/folderAlertPolicyCondition"; - const expectedParameters = { - folder: "folderValue", - alert_policy: "alertPolicyValue", - condition: "conditionValue", - }; - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.folderAlertPolicyConditionPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderAlertPolicyConditionPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderAlertPolicyConditionPath', () => { - const result = client.folderAlertPolicyConditionPath("folderValue", "alertPolicyValue", "conditionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderAlertPolicyConditionPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderAlertPolicyConditionName', () => { - const result = client.matchFolderFromFolderAlertPolicyConditionName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderAlertPolicyConditionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchAlertPolicyFromFolderAlertPolicyConditionName', () => { - const result = client.matchAlertPolicyFromFolderAlertPolicyConditionName(fakePath); - assert.strictEqual(result, "alertPolicyValue"); - assert((client.pathTemplates.folderAlertPolicyConditionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchConditionFromFolderAlertPolicyConditionName', () => { - const result = client.matchConditionFromFolderAlertPolicyConditionName(fakePath); - assert.strictEqual(result, "conditionValue"); - assert((client.pathTemplates.folderAlertPolicyConditionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('folderChannelDescriptor', () => { - const fakePath = "/rendered/path/folderChannelDescriptor"; - const expectedParameters = { - folder: "folderValue", - channel_descriptor: "channelDescriptorValue", - }; - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.folderChannelDescriptorPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderChannelDescriptorPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderChannelDescriptorPath', () => { - const result = client.folderChannelDescriptorPath("folderValue", "channelDescriptorValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderChannelDescriptorPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderChannelDescriptorName', () => { - const result = client.matchFolderFromFolderChannelDescriptorName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderChannelDescriptorPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchChannelDescriptorFromFolderChannelDescriptorName', () => { - const result = client.matchChannelDescriptorFromFolderChannelDescriptorName(fakePath); - assert.strictEqual(result, "channelDescriptorValue"); - assert((client.pathTemplates.folderChannelDescriptorPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('folderGroup', () => { - const fakePath = "/rendered/path/folderGroup"; - const expectedParameters = { - folder: "folderValue", - group: "groupValue", - }; - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.folderGroupPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderGroupPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderGroupPath', () => { - const result = client.folderGroupPath("folderValue", "groupValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderGroupPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderGroupName', () => { - const result = client.matchFolderFromFolderGroupName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderGroupPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchGroupFromFolderGroupName', () => { - const result = client.matchGroupFromFolderGroupName(fakePath); - assert.strictEqual(result, "groupValue"); - assert((client.pathTemplates.folderGroupPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('folderNotificationChannel', () => { - const fakePath = "/rendered/path/folderNotificationChannel"; - const expectedParameters = { - folder: "folderValue", - notification_channel: "notificationChannelValue", - }; - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.folderNotificationChannelPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderNotificationChannelPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderNotificationChannelPath', () => { - const result = client.folderNotificationChannelPath("folderValue", "notificationChannelValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderNotificationChannelPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderNotificationChannelName', () => { - const result = client.matchFolderFromFolderNotificationChannelName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderNotificationChannelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchNotificationChannelFromFolderNotificationChannelName', () => { - const result = client.matchNotificationChannelFromFolderNotificationChannelName(fakePath); - assert.strictEqual(result, "notificationChannelValue"); - assert((client.pathTemplates.folderNotificationChannelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('folderService', () => { - const fakePath = "/rendered/path/folderService"; - const expectedParameters = { - folder: "folderValue", - service: "serviceValue", - }; - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.folderServicePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderServicePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderServicePath', () => { - const result = client.folderServicePath("folderValue", "serviceValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderServicePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderServiceName', () => { - const result = client.matchFolderFromFolderServiceName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderServicePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServiceFromFolderServiceName', () => { - const result = client.matchServiceFromFolderServiceName(fakePath); - assert.strictEqual(result, "serviceValue"); - assert((client.pathTemplates.folderServicePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('folderServiceServiceLevelObjective', () => { - const fakePath = "/rendered/path/folderServiceServiceLevelObjective"; - const expectedParameters = { - folder: "folderValue", - service: "serviceValue", - service_level_objective: "serviceLevelObjectiveValue", - }; - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderServiceServiceLevelObjectivePath', () => { - const result = client.folderServiceServiceLevelObjectivePath("folderValue", "serviceValue", "serviceLevelObjectiveValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderServiceServiceLevelObjectiveName', () => { - const result = client.matchFolderFromFolderServiceServiceLevelObjectiveName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServiceFromFolderServiceServiceLevelObjectiveName', () => { - const result = client.matchServiceFromFolderServiceServiceLevelObjectiveName(fakePath); - assert.strictEqual(result, "serviceValue"); - assert((client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServiceLevelObjectiveFromFolderServiceServiceLevelObjectiveName', () => { - const result = client.matchServiceLevelObjectiveFromFolderServiceServiceLevelObjectiveName(fakePath); - assert.strictEqual(result, "serviceLevelObjectiveValue"); - assert((client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('folderUptimeCheckConfig', () => { - const fakePath = "/rendered/path/folderUptimeCheckConfig"; - const expectedParameters = { - folder: "folderValue", - uptime_check_config: "uptimeCheckConfigValue", - }; - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.folderUptimeCheckConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderUptimeCheckConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderUptimeCheckConfigPath', () => { - const result = client.folderUptimeCheckConfigPath("folderValue", "uptimeCheckConfigValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderUptimeCheckConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderUptimeCheckConfigName', () => { - const result = client.matchFolderFromFolderUptimeCheckConfigName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderUptimeCheckConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchUptimeCheckConfigFromFolderUptimeCheckConfigName', () => { - const result = client.matchUptimeCheckConfigFromFolderUptimeCheckConfigName(fakePath); - assert.strictEqual(result, "uptimeCheckConfigValue"); - assert((client.pathTemplates.folderUptimeCheckConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('organizationAlertPolicy', () => { - const fakePath = "/rendered/path/organizationAlertPolicy"; - const expectedParameters = { - organization: "organizationValue", - alert_policy: "alertPolicyValue", - }; - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.organizationAlertPolicyPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationAlertPolicyPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationAlertPolicyPath', () => { - const result = client.organizationAlertPolicyPath("organizationValue", "alertPolicyValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationAlertPolicyPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationAlertPolicyName', () => { - const result = client.matchOrganizationFromOrganizationAlertPolicyName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationAlertPolicyPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchAlertPolicyFromOrganizationAlertPolicyName', () => { - const result = client.matchAlertPolicyFromOrganizationAlertPolicyName(fakePath); - assert.strictEqual(result, "alertPolicyValue"); - assert((client.pathTemplates.organizationAlertPolicyPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('organizationAlertPolicyCondition', () => { - const fakePath = "/rendered/path/organizationAlertPolicyCondition"; - const expectedParameters = { - organization: "organizationValue", - alert_policy: "alertPolicyValue", - condition: "conditionValue", - }; - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.organizationAlertPolicyConditionPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationAlertPolicyConditionPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationAlertPolicyConditionPath', () => { - const result = client.organizationAlertPolicyConditionPath("organizationValue", "alertPolicyValue", "conditionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationAlertPolicyConditionPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationAlertPolicyConditionName', () => { - const result = client.matchOrganizationFromOrganizationAlertPolicyConditionName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationAlertPolicyConditionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchAlertPolicyFromOrganizationAlertPolicyConditionName', () => { - const result = client.matchAlertPolicyFromOrganizationAlertPolicyConditionName(fakePath); - assert.strictEqual(result, "alertPolicyValue"); - assert((client.pathTemplates.organizationAlertPolicyConditionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchConditionFromOrganizationAlertPolicyConditionName', () => { - const result = client.matchConditionFromOrganizationAlertPolicyConditionName(fakePath); - assert.strictEqual(result, "conditionValue"); - assert((client.pathTemplates.organizationAlertPolicyConditionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('organizationChannelDescriptor', () => { - const fakePath = "/rendered/path/organizationChannelDescriptor"; - const expectedParameters = { - organization: "organizationValue", - channel_descriptor: "channelDescriptorValue", - }; - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.organizationChannelDescriptorPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationChannelDescriptorPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationChannelDescriptorPath', () => { - const result = client.organizationChannelDescriptorPath("organizationValue", "channelDescriptorValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationChannelDescriptorPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationChannelDescriptorName', () => { - const result = client.matchOrganizationFromOrganizationChannelDescriptorName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationChannelDescriptorPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchChannelDescriptorFromOrganizationChannelDescriptorName', () => { - const result = client.matchChannelDescriptorFromOrganizationChannelDescriptorName(fakePath); - assert.strictEqual(result, "channelDescriptorValue"); - assert((client.pathTemplates.organizationChannelDescriptorPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('invokes createUptimeCheckConfig with error', async () => { + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.CreateUptimeCheckConfigRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.CreateUptimeCheckConfigRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createUptimeCheckConfig = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.createUptimeCheckConfig(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.createUptimeCheckConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createUptimeCheckConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - describe('organizationGroup', () => { - const fakePath = "/rendered/path/organizationGroup"; - const expectedParameters = { - organization: "organizationValue", - group: "groupValue", - }; - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.organizationGroupPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationGroupPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationGroupPath', () => { - const result = client.organizationGroupPath("organizationValue", "groupValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationGroupPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + it('invokes createUptimeCheckConfig with closed client', async () => { + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.CreateUptimeCheckConfigRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.CreateUptimeCheckConfigRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.createUptimeCheckConfig(request), + expectedError, + ); + }); + }); + + describe('updateUptimeCheckConfig', () => { + it('invokes updateUptimeCheckConfig without error', async () => { + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.UpdateUptimeCheckConfigRequest(), + ); + request.uptimeCheckConfig ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.UpdateUptimeCheckConfigRequest', + ['uptimeCheckConfig', 'name'], + ); + request.uptimeCheckConfig.name = defaultValue1; + const expectedHeaderRequestParams = `uptime_check_config.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.monitoring.v3.UptimeCheckConfig(), + ); + client.innerApiCalls.updateUptimeCheckConfig = + stubSimpleCall(expectedResponse); + const [response] = await client.updateUptimeCheckConfig(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateUptimeCheckConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateUptimeCheckConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('matchOrganizationFromOrganizationGroupName', () => { - const result = client.matchOrganizationFromOrganizationGroupName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationGroupPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('invokes updateUptimeCheckConfig without error using callback', async () => { + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.UpdateUptimeCheckConfigRequest(), + ); + request.uptimeCheckConfig ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.UpdateUptimeCheckConfigRequest', + ['uptimeCheckConfig', 'name'], + ); + request.uptimeCheckConfig.name = defaultValue1; + const expectedHeaderRequestParams = `uptime_check_config.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.monitoring.v3.UptimeCheckConfig(), + ); + client.innerApiCalls.updateUptimeCheckConfig = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateUptimeCheckConfig( + request, + ( + err?: Error | null, + result?: protos.google.monitoring.v3.IUptimeCheckConfig | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateUptimeCheckConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateUptimeCheckConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('matchGroupFromOrganizationGroupName', () => { - const result = client.matchGroupFromOrganizationGroupName(fakePath); - assert.strictEqual(result, "groupValue"); - assert((client.pathTemplates.organizationGroupPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('invokes updateUptimeCheckConfig with error', async () => { + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.UpdateUptimeCheckConfigRequest(), + ); + request.uptimeCheckConfig ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.UpdateUptimeCheckConfigRequest', + ['uptimeCheckConfig', 'name'], + ); + request.uptimeCheckConfig.name = defaultValue1; + const expectedHeaderRequestParams = `uptime_check_config.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateUptimeCheckConfig = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.updateUptimeCheckConfig(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.updateUptimeCheckConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateUptimeCheckConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - describe('organizationNotificationChannel', () => { - const fakePath = "/rendered/path/organizationNotificationChannel"; - const expectedParameters = { - organization: "organizationValue", - notification_channel: "notificationChannelValue", - }; - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.organizationNotificationChannelPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationNotificationChannelPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationNotificationChannelPath', () => { - const result = client.organizationNotificationChannelPath("organizationValue", "notificationChannelValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationNotificationChannelPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + it('invokes updateUptimeCheckConfig with closed client', async () => { + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.UpdateUptimeCheckConfigRequest(), + ); + request.uptimeCheckConfig ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.UpdateUptimeCheckConfigRequest', + ['uptimeCheckConfig', 'name'], + ); + request.uptimeCheckConfig.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.updateUptimeCheckConfig(request), + expectedError, + ); + }); + }); + + describe('deleteUptimeCheckConfig', () => { + it('invokes deleteUptimeCheckConfig without error', async () => { + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.DeleteUptimeCheckConfigRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.DeleteUptimeCheckConfigRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteUptimeCheckConfig = + stubSimpleCall(expectedResponse); + const [response] = await client.deleteUptimeCheckConfig(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteUptimeCheckConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteUptimeCheckConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('matchOrganizationFromOrganizationNotificationChannelName', () => { - const result = client.matchOrganizationFromOrganizationNotificationChannelName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationNotificationChannelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('invokes deleteUptimeCheckConfig without error using callback', async () => { + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.DeleteUptimeCheckConfigRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.DeleteUptimeCheckConfigRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteUptimeCheckConfig = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteUptimeCheckConfig( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteUptimeCheckConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteUptimeCheckConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('matchNotificationChannelFromOrganizationNotificationChannelName', () => { - const result = client.matchNotificationChannelFromOrganizationNotificationChannelName(fakePath); - assert.strictEqual(result, "notificationChannelValue"); - assert((client.pathTemplates.organizationNotificationChannelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('invokes deleteUptimeCheckConfig with error', async () => { + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.DeleteUptimeCheckConfigRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.DeleteUptimeCheckConfigRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteUptimeCheckConfig = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.deleteUptimeCheckConfig(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.deleteUptimeCheckConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteUptimeCheckConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - describe('organizationService', () => { - const fakePath = "/rendered/path/organizationService"; - const expectedParameters = { - organization: "organizationValue", - service: "serviceValue", - }; - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.organizationServicePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationServicePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationServicePath', () => { - const result = client.organizationServicePath("organizationValue", "serviceValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationServicePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + it('invokes deleteUptimeCheckConfig with closed client', async () => { + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.DeleteUptimeCheckConfigRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.DeleteUptimeCheckConfigRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.deleteUptimeCheckConfig(request), + expectedError, + ); + }); + }); + + describe('listUptimeCheckConfigs', () => { + it('invokes listUptimeCheckConfigs without error', async () => { + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListUptimeCheckConfigsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListUptimeCheckConfigsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.monitoring.v3.UptimeCheckConfig(), + ), + generateSampleMessage( + new protos.google.monitoring.v3.UptimeCheckConfig(), + ), + generateSampleMessage( + new protos.google.monitoring.v3.UptimeCheckConfig(), + ), + ]; + client.innerApiCalls.listUptimeCheckConfigs = + stubSimpleCall(expectedResponse); + const [response] = await client.listUptimeCheckConfigs(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listUptimeCheckConfigs as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listUptimeCheckConfigs as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('matchOrganizationFromOrganizationServiceName', () => { - const result = client.matchOrganizationFromOrganizationServiceName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationServicePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('invokes listUptimeCheckConfigs without error using callback', async () => { + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListUptimeCheckConfigsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListUptimeCheckConfigsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.monitoring.v3.UptimeCheckConfig(), + ), + generateSampleMessage( + new protos.google.monitoring.v3.UptimeCheckConfig(), + ), + generateSampleMessage( + new protos.google.monitoring.v3.UptimeCheckConfig(), + ), + ]; + client.innerApiCalls.listUptimeCheckConfigs = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listUptimeCheckConfigs( + request, + ( + err?: Error | null, + result?: protos.google.monitoring.v3.IUptimeCheckConfig[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listUptimeCheckConfigs as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listUptimeCheckConfigs as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('matchServiceFromOrganizationServiceName', () => { - const result = client.matchServiceFromOrganizationServiceName(fakePath); - assert.strictEqual(result, "serviceValue"); - assert((client.pathTemplates.organizationServicePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('invokes listUptimeCheckConfigs with error', async () => { + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListUptimeCheckConfigsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListUptimeCheckConfigsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listUptimeCheckConfigs = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.listUptimeCheckConfigs(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.listUptimeCheckConfigs as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listUptimeCheckConfigs as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - describe('organizationServiceServiceLevelObjective', () => { - const fakePath = "/rendered/path/organizationServiceServiceLevelObjective"; - const expectedParameters = { - organization: "organizationValue", - service: "serviceValue", - service_level_objective: "serviceLevelObjectiveValue", - }; - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationServiceServiceLevelObjectivePath', () => { - const result = client.organizationServiceServiceLevelObjectivePath("organizationValue", "serviceValue", "serviceLevelObjectiveValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + it('invokes listUptimeCheckConfigsStream without error', async () => { + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListUptimeCheckConfigsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListUptimeCheckConfigsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.monitoring.v3.UptimeCheckConfig(), + ), + generateSampleMessage( + new protos.google.monitoring.v3.UptimeCheckConfig(), + ), + generateSampleMessage( + new protos.google.monitoring.v3.UptimeCheckConfig(), + ), + ]; + client.descriptors.page.listUptimeCheckConfigs.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listUptimeCheckConfigsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.monitoring.v3.UptimeCheckConfig[] = []; + stream.on( + 'data', + (response: protos.google.monitoring.v3.UptimeCheckConfig) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + ( + client.descriptors.page.listUptimeCheckConfigs + .createStream as SinonStub + ) + .getCall(0) + .calledWith(client.innerApiCalls.listUptimeCheckConfigs, request), + ); + assert( + ( + client.descriptors.page.listUptimeCheckConfigs + .createStream as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); - it('matchOrganizationFromOrganizationServiceServiceLevelObjectiveName', () => { - const result = client.matchOrganizationFromOrganizationServiceServiceLevelObjectiveName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('invokes listUptimeCheckConfigsStream with error', async () => { + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListUptimeCheckConfigsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListUptimeCheckConfigsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listUptimeCheckConfigs.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listUptimeCheckConfigsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.monitoring.v3.UptimeCheckConfig[] = []; + stream.on( + 'data', + (response: protos.google.monitoring.v3.UptimeCheckConfig) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + ( + client.descriptors.page.listUptimeCheckConfigs + .createStream as SinonStub + ) + .getCall(0) + .calledWith(client.innerApiCalls.listUptimeCheckConfigs, request), + ); + assert( + ( + client.descriptors.page.listUptimeCheckConfigs + .createStream as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); - it('matchServiceFromOrganizationServiceServiceLevelObjectiveName', () => { - const result = client.matchServiceFromOrganizationServiceServiceLevelObjectiveName(fakePath); - assert.strictEqual(result, "serviceValue"); - assert((client.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('uses async iteration with listUptimeCheckConfigs without error', async () => { + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListUptimeCheckConfigsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListUptimeCheckConfigsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.monitoring.v3.UptimeCheckConfig(), + ), + generateSampleMessage( + new protos.google.monitoring.v3.UptimeCheckConfig(), + ), + generateSampleMessage( + new protos.google.monitoring.v3.UptimeCheckConfig(), + ), + ]; + client.descriptors.page.listUptimeCheckConfigs.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.monitoring.v3.IUptimeCheckConfig[] = []; + const iterable = client.listUptimeCheckConfigsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listUptimeCheckConfigs + .asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + ( + client.descriptors.page.listUptimeCheckConfigs + .asyncIterate as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); - it('matchServiceLevelObjectiveFromOrganizationServiceServiceLevelObjectiveName', () => { - const result = client.matchServiceLevelObjectiveFromOrganizationServiceServiceLevelObjectiveName(fakePath); - assert.strictEqual(result, "serviceLevelObjectiveValue"); - assert((client.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('uses async iteration with listUptimeCheckConfigs with error', async () => { + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListUptimeCheckConfigsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListUptimeCheckConfigsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listUptimeCheckConfigs.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listUptimeCheckConfigsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.monitoring.v3.IUptimeCheckConfig[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listUptimeCheckConfigs + .asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + ( + client.descriptors.page.listUptimeCheckConfigs + .asyncIterate as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); + }); + + describe('listUptimeCheckIps', () => { + it('invokes listUptimeCheckIps without error', async () => { + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListUptimeCheckIpsRequest(), + ); + const expectedResponse = [ + generateSampleMessage(new protos.google.monitoring.v3.UptimeCheckIp()), + generateSampleMessage(new protos.google.monitoring.v3.UptimeCheckIp()), + generateSampleMessage(new protos.google.monitoring.v3.UptimeCheckIp()), + ]; + client.innerApiCalls.listUptimeCheckIps = + stubSimpleCall(expectedResponse); + const [response] = await client.listUptimeCheckIps(request); + assert.deepStrictEqual(response, expectedResponse); + }); - describe('organizationUptimeCheckConfig', () => { - const fakePath = "/rendered/path/organizationUptimeCheckConfig"; - const expectedParameters = { - organization: "organizationValue", - uptime_check_config: "uptimeCheckConfigValue", - }; - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.organizationUptimeCheckConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationUptimeCheckConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationUptimeCheckConfigPath', () => { - const result = client.organizationUptimeCheckConfigPath("organizationValue", "uptimeCheckConfigValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationUptimeCheckConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + it('invokes listUptimeCheckIps without error using callback', async () => { + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListUptimeCheckIpsRequest(), + ); + const expectedResponse = [ + generateSampleMessage(new protos.google.monitoring.v3.UptimeCheckIp()), + generateSampleMessage(new protos.google.monitoring.v3.UptimeCheckIp()), + generateSampleMessage(new protos.google.monitoring.v3.UptimeCheckIp()), + ]; + client.innerApiCalls.listUptimeCheckIps = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listUptimeCheckIps( + request, + ( + err?: Error | null, + result?: protos.google.monitoring.v3.IUptimeCheckIp[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); - it('matchOrganizationFromOrganizationUptimeCheckConfigName', () => { - const result = client.matchOrganizationFromOrganizationUptimeCheckConfigName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationUptimeCheckConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('invokes listUptimeCheckIps with error', async () => { + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListUptimeCheckIpsRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.listUptimeCheckIps = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listUptimeCheckIps(request), expectedError); + }); - it('matchUptimeCheckConfigFromOrganizationUptimeCheckConfigName', () => { - const result = client.matchUptimeCheckConfigFromOrganizationUptimeCheckConfigName(fakePath); - assert.strictEqual(result, "uptimeCheckConfigValue"); - assert((client.pathTemplates.organizationUptimeCheckConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('invokes listUptimeCheckIpsStream without error', async () => { + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListUptimeCheckIpsRequest(), + ); + const expectedResponse = [ + generateSampleMessage(new protos.google.monitoring.v3.UptimeCheckIp()), + generateSampleMessage(new protos.google.monitoring.v3.UptimeCheckIp()), + generateSampleMessage(new protos.google.monitoring.v3.UptimeCheckIp()), + ]; + client.descriptors.page.listUptimeCheckIps.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listUptimeCheckIpsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.monitoring.v3.UptimeCheckIp[] = []; + stream.on( + 'data', + (response: protos.google.monitoring.v3.UptimeCheckIp) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listUptimeCheckIps.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listUptimeCheckIps, request), + ); + }); - describe('projectAlertPolicy', () => { - const fakePath = "/rendered/path/projectAlertPolicy"; - const expectedParameters = { - project: "projectValue", - alert_policy: "alertPolicyValue", - }; - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.projectAlertPolicyPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectAlertPolicyPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectAlertPolicyPath', () => { - const result = client.projectAlertPolicyPath("projectValue", "alertPolicyValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectAlertPolicyPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + it('invokes listUptimeCheckIpsStream with error', async () => { + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListUptimeCheckIpsRequest(), + ); + const expectedError = new Error('expected'); + client.descriptors.page.listUptimeCheckIps.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listUptimeCheckIpsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.monitoring.v3.UptimeCheckIp[] = []; + stream.on( + 'data', + (response: protos.google.monitoring.v3.UptimeCheckIp) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listUptimeCheckIps.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listUptimeCheckIps, request), + ); + }); - it('matchProjectFromProjectAlertPolicyName', () => { - const result = client.matchProjectFromProjectAlertPolicyName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectAlertPolicyPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('uses async iteration with listUptimeCheckIps without error', async () => { + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListUptimeCheckIpsRequest(), + ); + const expectedResponse = [ + generateSampleMessage(new protos.google.monitoring.v3.UptimeCheckIp()), + generateSampleMessage(new protos.google.monitoring.v3.UptimeCheckIp()), + generateSampleMessage(new protos.google.monitoring.v3.UptimeCheckIp()), + ]; + client.descriptors.page.listUptimeCheckIps.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.monitoring.v3.IUptimeCheckIp[] = []; + const iterable = client.listUptimeCheckIpsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listUptimeCheckIps.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + }); - it('matchAlertPolicyFromProjectAlertPolicyName', () => { - const result = client.matchAlertPolicyFromProjectAlertPolicyName(fakePath); - assert.strictEqual(result, "alertPolicyValue"); - assert((client.pathTemplates.projectAlertPolicyPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('uses async iteration with listUptimeCheckIps with error', async () => { + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListUptimeCheckIpsRequest(), + ); + const expectedError = new Error('expected'); + client.descriptors.page.listUptimeCheckIps.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listUptimeCheckIpsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.monitoring.v3.IUptimeCheckIp[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listUptimeCheckIps.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + }); + }); + + describe('Path templates', () => { + describe('folderAlertPolicy', () => { + const fakePath = '/rendered/path/folderAlertPolicy'; + const expectedParameters = { + folder: 'folderValue', + alert_policy: 'alertPolicyValue', + }; + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.folderAlertPolicyPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderAlertPolicyPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderAlertPolicyPath', () => { + const result = client.folderAlertPolicyPath( + 'folderValue', + 'alertPolicyValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.folderAlertPolicyPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderAlertPolicyName', () => { + const result = client.matchFolderFromFolderAlertPolicyName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + ( + client.pathTemplates.folderAlertPolicyPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchAlertPolicyFromFolderAlertPolicyName', () => { + const result = + client.matchAlertPolicyFromFolderAlertPolicyName(fakePath); + assert.strictEqual(result, 'alertPolicyValue'); + assert( + ( + client.pathTemplates.folderAlertPolicyPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectAlertPolicyCondition', () => { - const fakePath = "/rendered/path/projectAlertPolicyCondition"; - const expectedParameters = { - project: "projectValue", - alert_policy: "alertPolicyValue", - condition: "conditionValue", - }; - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.projectAlertPolicyConditionPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectAlertPolicyConditionPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectAlertPolicyConditionPath', () => { - const result = client.projectAlertPolicyConditionPath("projectValue", "alertPolicyValue", "conditionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectAlertPolicyConditionPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + describe('folderAlertPolicyCondition', () => { + const fakePath = '/rendered/path/folderAlertPolicyCondition'; + const expectedParameters = { + folder: 'folderValue', + alert_policy: 'alertPolicyValue', + condition: 'conditionValue', + }; + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.folderAlertPolicyConditionPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderAlertPolicyConditionPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderAlertPolicyConditionPath', () => { + const result = client.folderAlertPolicyConditionPath( + 'folderValue', + 'alertPolicyValue', + 'conditionValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.folderAlertPolicyConditionPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderAlertPolicyConditionName', () => { + const result = + client.matchFolderFromFolderAlertPolicyConditionName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + ( + client.pathTemplates.folderAlertPolicyConditionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchAlertPolicyFromFolderAlertPolicyConditionName', () => { + const result = + client.matchAlertPolicyFromFolderAlertPolicyConditionName(fakePath); + assert.strictEqual(result, 'alertPolicyValue'); + assert( + ( + client.pathTemplates.folderAlertPolicyConditionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchConditionFromFolderAlertPolicyConditionName', () => { + const result = + client.matchConditionFromFolderAlertPolicyConditionName(fakePath); + assert.strictEqual(result, 'conditionValue'); + assert( + ( + client.pathTemplates.folderAlertPolicyConditionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchProjectFromProjectAlertPolicyConditionName', () => { - const result = client.matchProjectFromProjectAlertPolicyConditionName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectAlertPolicyConditionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('folderChannelDescriptor', () => { + const fakePath = '/rendered/path/folderChannelDescriptor'; + const expectedParameters = { + folder: 'folderValue', + channel_descriptor: 'channelDescriptorValue', + }; + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.folderChannelDescriptorPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderChannelDescriptorPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderChannelDescriptorPath', () => { + const result = client.folderChannelDescriptorPath( + 'folderValue', + 'channelDescriptorValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.folderChannelDescriptorPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderChannelDescriptorName', () => { + const result = + client.matchFolderFromFolderChannelDescriptorName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + ( + client.pathTemplates.folderChannelDescriptorPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchChannelDescriptorFromFolderChannelDescriptorName', () => { + const result = + client.matchChannelDescriptorFromFolderChannelDescriptorName( + fakePath, + ); + assert.strictEqual(result, 'channelDescriptorValue'); + assert( + ( + client.pathTemplates.folderChannelDescriptorPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchAlertPolicyFromProjectAlertPolicyConditionName', () => { - const result = client.matchAlertPolicyFromProjectAlertPolicyConditionName(fakePath); - assert.strictEqual(result, "alertPolicyValue"); - assert((client.pathTemplates.projectAlertPolicyConditionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('folderGroup', () => { + const fakePath = '/rendered/path/folderGroup'; + const expectedParameters = { + folder: 'folderValue', + group: 'groupValue', + }; + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.folderGroupPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderGroupPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderGroupPath', () => { + const result = client.folderGroupPath('folderValue', 'groupValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.folderGroupPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderGroupName', () => { + const result = client.matchFolderFromFolderGroupName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + (client.pathTemplates.folderGroupPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchGroupFromFolderGroupName', () => { + const result = client.matchGroupFromFolderGroupName(fakePath); + assert.strictEqual(result, 'groupValue'); + assert( + (client.pathTemplates.folderGroupPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchConditionFromProjectAlertPolicyConditionName', () => { - const result = client.matchConditionFromProjectAlertPolicyConditionName(fakePath); - assert.strictEqual(result, "conditionValue"); - assert((client.pathTemplates.projectAlertPolicyConditionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('folderNotificationChannel', () => { + const fakePath = '/rendered/path/folderNotificationChannel'; + const expectedParameters = { + folder: 'folderValue', + notification_channel: 'notificationChannelValue', + }; + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.folderNotificationChannelPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderNotificationChannelPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderNotificationChannelPath', () => { + const result = client.folderNotificationChannelPath( + 'folderValue', + 'notificationChannelValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.folderNotificationChannelPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderNotificationChannelName', () => { + const result = + client.matchFolderFromFolderNotificationChannelName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + ( + client.pathTemplates.folderNotificationChannelPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchNotificationChannelFromFolderNotificationChannelName', () => { + const result = + client.matchNotificationChannelFromFolderNotificationChannelName( + fakePath, + ); + assert.strictEqual(result, 'notificationChannelValue'); + assert( + ( + client.pathTemplates.folderNotificationChannelPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectChannelDescriptor', () => { - const fakePath = "/rendered/path/projectChannelDescriptor"; - const expectedParameters = { - project: "projectValue", - channel_descriptor: "channelDescriptorValue", - }; - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.projectChannelDescriptorPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectChannelDescriptorPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectChannelDescriptorPath', () => { - const result = client.projectChannelDescriptorPath("projectValue", "channelDescriptorValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectChannelDescriptorPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + describe('folderService', () => { + const fakePath = '/rendered/path/folderService'; + const expectedParameters = { + folder: 'folderValue', + service: 'serviceValue', + }; + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.folderServicePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderServicePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderServicePath', () => { + const result = client.folderServicePath('folderValue', 'serviceValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.folderServicePathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderServiceName', () => { + const result = client.matchFolderFromFolderServiceName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + (client.pathTemplates.folderServicePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServiceFromFolderServiceName', () => { + const result = client.matchServiceFromFolderServiceName(fakePath); + assert.strictEqual(result, 'serviceValue'); + assert( + (client.pathTemplates.folderServicePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchProjectFromProjectChannelDescriptorName', () => { - const result = client.matchProjectFromProjectChannelDescriptorName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectChannelDescriptorPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('folderServiceServiceLevelObjective', () => { + const fakePath = '/rendered/path/folderServiceServiceLevelObjective'; + const expectedParameters = { + folder: 'folderValue', + service: 'serviceValue', + service_level_objective: 'serviceLevelObjectiveValue', + }; + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('folderServiceServiceLevelObjectivePath', () => { + const result = client.folderServiceServiceLevelObjectivePath( + 'folderValue', + 'serviceValue', + 'serviceLevelObjectiveValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderServiceServiceLevelObjectiveName', () => { + const result = + client.matchFolderFromFolderServiceServiceLevelObjectiveName( + fakePath, + ); + assert.strictEqual(result, 'folderValue'); + assert( + ( + client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServiceFromFolderServiceServiceLevelObjectiveName', () => { + const result = + client.matchServiceFromFolderServiceServiceLevelObjectiveName( + fakePath, + ); + assert.strictEqual(result, 'serviceValue'); + assert( + ( + client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServiceLevelObjectiveFromFolderServiceServiceLevelObjectiveName', () => { + const result = + client.matchServiceLevelObjectiveFromFolderServiceServiceLevelObjectiveName( + fakePath, + ); + assert.strictEqual(result, 'serviceLevelObjectiveValue'); + assert( + ( + client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchChannelDescriptorFromProjectChannelDescriptorName', () => { - const result = client.matchChannelDescriptorFromProjectChannelDescriptorName(fakePath); - assert.strictEqual(result, "channelDescriptorValue"); - assert((client.pathTemplates.projectChannelDescriptorPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('folderUptimeCheckConfig', () => { + const fakePath = '/rendered/path/folderUptimeCheckConfig'; + const expectedParameters = { + folder: 'folderValue', + uptime_check_config: 'uptimeCheckConfigValue', + }; + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.folderUptimeCheckConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderUptimeCheckConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderUptimeCheckConfigPath', () => { + const result = client.folderUptimeCheckConfigPath( + 'folderValue', + 'uptimeCheckConfigValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.folderUptimeCheckConfigPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderUptimeCheckConfigName', () => { + const result = + client.matchFolderFromFolderUptimeCheckConfigName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + ( + client.pathTemplates.folderUptimeCheckConfigPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchUptimeCheckConfigFromFolderUptimeCheckConfigName', () => { + const result = + client.matchUptimeCheckConfigFromFolderUptimeCheckConfigName( + fakePath, + ); + assert.strictEqual(result, 'uptimeCheckConfigValue'); + assert( + ( + client.pathTemplates.folderUptimeCheckConfigPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectGroup', () => { - const fakePath = "/rendered/path/projectGroup"; - const expectedParameters = { - project: "projectValue", - group: "groupValue", - }; - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.projectGroupPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectGroupPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectGroupPath', () => { - const result = client.projectGroupPath("projectValue", "groupValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectGroupPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + describe('organizationAlertPolicy', () => { + const fakePath = '/rendered/path/organizationAlertPolicy'; + const expectedParameters = { + organization: 'organizationValue', + alert_policy: 'alertPolicyValue', + }; + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.organizationAlertPolicyPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.organizationAlertPolicyPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('organizationAlertPolicyPath', () => { + const result = client.organizationAlertPolicyPath( + 'organizationValue', + 'alertPolicyValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationAlertPolicyPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationAlertPolicyName', () => { + const result = + client.matchOrganizationFromOrganizationAlertPolicyName(fakePath); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationAlertPolicyPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchAlertPolicyFromOrganizationAlertPolicyName', () => { + const result = + client.matchAlertPolicyFromOrganizationAlertPolicyName(fakePath); + assert.strictEqual(result, 'alertPolicyValue'); + assert( + ( + client.pathTemplates.organizationAlertPolicyPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchProjectFromProjectGroupName', () => { - const result = client.matchProjectFromProjectGroupName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectGroupPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('organizationAlertPolicyCondition', () => { + const fakePath = '/rendered/path/organizationAlertPolicyCondition'; + const expectedParameters = { + organization: 'organizationValue', + alert_policy: 'alertPolicyValue', + condition: 'conditionValue', + }; + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.organizationAlertPolicyConditionPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.organizationAlertPolicyConditionPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('organizationAlertPolicyConditionPath', () => { + const result = client.organizationAlertPolicyConditionPath( + 'organizationValue', + 'alertPolicyValue', + 'conditionValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationAlertPolicyConditionPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationAlertPolicyConditionName', () => { + const result = + client.matchOrganizationFromOrganizationAlertPolicyConditionName( + fakePath, + ); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationAlertPolicyConditionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchAlertPolicyFromOrganizationAlertPolicyConditionName', () => { + const result = + client.matchAlertPolicyFromOrganizationAlertPolicyConditionName( + fakePath, + ); + assert.strictEqual(result, 'alertPolicyValue'); + assert( + ( + client.pathTemplates.organizationAlertPolicyConditionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchConditionFromOrganizationAlertPolicyConditionName', () => { + const result = + client.matchConditionFromOrganizationAlertPolicyConditionName( + fakePath, + ); + assert.strictEqual(result, 'conditionValue'); + assert( + ( + client.pathTemplates.organizationAlertPolicyConditionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchGroupFromProjectGroupName', () => { - const result = client.matchGroupFromProjectGroupName(fakePath); - assert.strictEqual(result, "groupValue"); - assert((client.pathTemplates.projectGroupPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('organizationChannelDescriptor', () => { + const fakePath = '/rendered/path/organizationChannelDescriptor'; + const expectedParameters = { + organization: 'organizationValue', + channel_descriptor: 'channelDescriptorValue', + }; + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.organizationChannelDescriptorPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.organizationChannelDescriptorPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('organizationChannelDescriptorPath', () => { + const result = client.organizationChannelDescriptorPath( + 'organizationValue', + 'channelDescriptorValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationChannelDescriptorPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationChannelDescriptorName', () => { + const result = + client.matchOrganizationFromOrganizationChannelDescriptorName( + fakePath, + ); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationChannelDescriptorPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchChannelDescriptorFromOrganizationChannelDescriptorName', () => { + const result = + client.matchChannelDescriptorFromOrganizationChannelDescriptorName( + fakePath, + ); + assert.strictEqual(result, 'channelDescriptorValue'); + assert( + ( + client.pathTemplates.organizationChannelDescriptorPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectNotificationChannel', () => { - const fakePath = "/rendered/path/projectNotificationChannel"; - const expectedParameters = { - project: "projectValue", - notification_channel: "notificationChannelValue", - }; - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.projectNotificationChannelPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectNotificationChannelPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectNotificationChannelPath', () => { - const result = client.projectNotificationChannelPath("projectValue", "notificationChannelValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectNotificationChannelPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + describe('organizationGroup', () => { + const fakePath = '/rendered/path/organizationGroup'; + const expectedParameters = { + organization: 'organizationValue', + group: 'groupValue', + }; + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.organizationGroupPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.organizationGroupPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('organizationGroupPath', () => { + const result = client.organizationGroupPath( + 'organizationValue', + 'groupValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationGroupPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationGroupName', () => { + const result = + client.matchOrganizationFromOrganizationGroupName(fakePath); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationGroupPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchGroupFromOrganizationGroupName', () => { + const result = client.matchGroupFromOrganizationGroupName(fakePath); + assert.strictEqual(result, 'groupValue'); + assert( + ( + client.pathTemplates.organizationGroupPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchProjectFromProjectNotificationChannelName', () => { - const result = client.matchProjectFromProjectNotificationChannelName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectNotificationChannelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('organizationNotificationChannel', () => { + const fakePath = '/rendered/path/organizationNotificationChannel'; + const expectedParameters = { + organization: 'organizationValue', + notification_channel: 'notificationChannelValue', + }; + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.organizationNotificationChannelPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.organizationNotificationChannelPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('organizationNotificationChannelPath', () => { + const result = client.organizationNotificationChannelPath( + 'organizationValue', + 'notificationChannelValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationNotificationChannelPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationNotificationChannelName', () => { + const result = + client.matchOrganizationFromOrganizationNotificationChannelName( + fakePath, + ); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationNotificationChannelPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchNotificationChannelFromOrganizationNotificationChannelName', () => { + const result = + client.matchNotificationChannelFromOrganizationNotificationChannelName( + fakePath, + ); + assert.strictEqual(result, 'notificationChannelValue'); + assert( + ( + client.pathTemplates.organizationNotificationChannelPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchNotificationChannelFromProjectNotificationChannelName', () => { - const result = client.matchNotificationChannelFromProjectNotificationChannelName(fakePath); - assert.strictEqual(result, "notificationChannelValue"); - assert((client.pathTemplates.projectNotificationChannelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('organizationService', () => { + const fakePath = '/rendered/path/organizationService'; + const expectedParameters = { + organization: 'organizationValue', + service: 'serviceValue', + }; + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.organizationServicePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.organizationServicePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('organizationServicePath', () => { + const result = client.organizationServicePath( + 'organizationValue', + 'serviceValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationServicePathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationServiceName', () => { + const result = + client.matchOrganizationFromOrganizationServiceName(fakePath); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationServicePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServiceFromOrganizationServiceName', () => { + const result = client.matchServiceFromOrganizationServiceName(fakePath); + assert.strictEqual(result, 'serviceValue'); + assert( + ( + client.pathTemplates.organizationServicePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectService', () => { - const fakePath = "/rendered/path/projectService"; - const expectedParameters = { - project: "projectValue", - service: "serviceValue", - }; - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.projectServicePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectServicePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectServicePath', () => { - const result = client.projectServicePath("projectValue", "serviceValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectServicePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + describe('organizationServiceServiceLevelObjective', () => { + const fakePath = + '/rendered/path/organizationServiceServiceLevelObjective'; + const expectedParameters = { + organization: 'organizationValue', + service: 'serviceValue', + service_level_objective: 'serviceLevelObjectiveValue', + }; + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('organizationServiceServiceLevelObjectivePath', () => { + const result = client.organizationServiceServiceLevelObjectivePath( + 'organizationValue', + 'serviceValue', + 'serviceLevelObjectiveValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates + .organizationServiceServiceLevelObjectivePathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationServiceServiceLevelObjectiveName', () => { + const result = + client.matchOrganizationFromOrganizationServiceServiceLevelObjectiveName( + fakePath, + ); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates + .organizationServiceServiceLevelObjectivePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServiceFromOrganizationServiceServiceLevelObjectiveName', () => { + const result = + client.matchServiceFromOrganizationServiceServiceLevelObjectiveName( + fakePath, + ); + assert.strictEqual(result, 'serviceValue'); + assert( + ( + client.pathTemplates + .organizationServiceServiceLevelObjectivePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServiceLevelObjectiveFromOrganizationServiceServiceLevelObjectiveName', () => { + const result = + client.matchServiceLevelObjectiveFromOrganizationServiceServiceLevelObjectiveName( + fakePath, + ); + assert.strictEqual(result, 'serviceLevelObjectiveValue'); + assert( + ( + client.pathTemplates + .organizationServiceServiceLevelObjectivePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchProjectFromProjectServiceName', () => { - const result = client.matchProjectFromProjectServiceName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectServicePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('organizationUptimeCheckConfig', () => { + const fakePath = '/rendered/path/organizationUptimeCheckConfig'; + const expectedParameters = { + organization: 'organizationValue', + uptime_check_config: 'uptimeCheckConfigValue', + }; + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.organizationUptimeCheckConfigPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.organizationUptimeCheckConfigPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('organizationUptimeCheckConfigPath', () => { + const result = client.organizationUptimeCheckConfigPath( + 'organizationValue', + 'uptimeCheckConfigValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationUptimeCheckConfigPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationUptimeCheckConfigName', () => { + const result = + client.matchOrganizationFromOrganizationUptimeCheckConfigName( + fakePath, + ); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationUptimeCheckConfigPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchUptimeCheckConfigFromOrganizationUptimeCheckConfigName', () => { + const result = + client.matchUptimeCheckConfigFromOrganizationUptimeCheckConfigName( + fakePath, + ); + assert.strictEqual(result, 'uptimeCheckConfigValue'); + assert( + ( + client.pathTemplates.organizationUptimeCheckConfigPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchServiceFromProjectServiceName', () => { - const result = client.matchServiceFromProjectServiceName(fakePath); - assert.strictEqual(result, "serviceValue"); - assert((client.pathTemplates.projectServicePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectAlertPolicy', () => { + const fakePath = '/rendered/path/projectAlertPolicy'; + const expectedParameters = { + project: 'projectValue', + alert_policy: 'alertPolicyValue', + }; + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.projectAlertPolicyPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectAlertPolicyPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectAlertPolicyPath', () => { + const result = client.projectAlertPolicyPath( + 'projectValue', + 'alertPolicyValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.projectAlertPolicyPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectAlertPolicyName', () => { + const result = client.matchProjectFromProjectAlertPolicyName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.projectAlertPolicyPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchAlertPolicyFromProjectAlertPolicyName', () => { + const result = + client.matchAlertPolicyFromProjectAlertPolicyName(fakePath); + assert.strictEqual(result, 'alertPolicyValue'); + assert( + ( + client.pathTemplates.projectAlertPolicyPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectServiceServiceLevelObjective', () => { - const fakePath = "/rendered/path/projectServiceServiceLevelObjective"; - const expectedParameters = { - project: "projectValue", - service: "serviceValue", - service_level_objective: "serviceLevelObjectiveValue", - }; - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectServiceServiceLevelObjectivePath', () => { - const result = client.projectServiceServiceLevelObjectivePath("projectValue", "serviceValue", "serviceLevelObjectiveValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + describe('projectAlertPolicyCondition', () => { + const fakePath = '/rendered/path/projectAlertPolicyCondition'; + const expectedParameters = { + project: 'projectValue', + alert_policy: 'alertPolicyValue', + condition: 'conditionValue', + }; + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.projectAlertPolicyConditionPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.projectAlertPolicyConditionPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectAlertPolicyConditionPath', () => { + const result = client.projectAlertPolicyConditionPath( + 'projectValue', + 'alertPolicyValue', + 'conditionValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.projectAlertPolicyConditionPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectAlertPolicyConditionName', () => { + const result = + client.matchProjectFromProjectAlertPolicyConditionName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.projectAlertPolicyConditionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchAlertPolicyFromProjectAlertPolicyConditionName', () => { + const result = + client.matchAlertPolicyFromProjectAlertPolicyConditionName(fakePath); + assert.strictEqual(result, 'alertPolicyValue'); + assert( + ( + client.pathTemplates.projectAlertPolicyConditionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchConditionFromProjectAlertPolicyConditionName', () => { + const result = + client.matchConditionFromProjectAlertPolicyConditionName(fakePath); + assert.strictEqual(result, 'conditionValue'); + assert( + ( + client.pathTemplates.projectAlertPolicyConditionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchProjectFromProjectServiceServiceLevelObjectiveName', () => { - const result = client.matchProjectFromProjectServiceServiceLevelObjectiveName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('projectChannelDescriptor', () => { + const fakePath = '/rendered/path/projectChannelDescriptor'; + const expectedParameters = { + project: 'projectValue', + channel_descriptor: 'channelDescriptorValue', + }; + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.projectChannelDescriptorPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectChannelDescriptorPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectChannelDescriptorPath', () => { + const result = client.projectChannelDescriptorPath( + 'projectValue', + 'channelDescriptorValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.projectChannelDescriptorPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectChannelDescriptorName', () => { + const result = + client.matchProjectFromProjectChannelDescriptorName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.projectChannelDescriptorPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchChannelDescriptorFromProjectChannelDescriptorName', () => { + const result = + client.matchChannelDescriptorFromProjectChannelDescriptorName( + fakePath, + ); + assert.strictEqual(result, 'channelDescriptorValue'); + assert( + ( + client.pathTemplates.projectChannelDescriptorPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchServiceFromProjectServiceServiceLevelObjectiveName', () => { - const result = client.matchServiceFromProjectServiceServiceLevelObjectiveName(fakePath); - assert.strictEqual(result, "serviceValue"); - assert((client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('projectGroup', () => { + const fakePath = '/rendered/path/projectGroup'; + const expectedParameters = { + project: 'projectValue', + group: 'groupValue', + }; + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.projectGroupPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectGroupPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectGroupPath', () => { + const result = client.projectGroupPath('projectValue', 'groupValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.projectGroupPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectGroupName', () => { + const result = client.matchProjectFromProjectGroupName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.projectGroupPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchGroupFromProjectGroupName', () => { + const result = client.matchGroupFromProjectGroupName(fakePath); + assert.strictEqual(result, 'groupValue'); + assert( + (client.pathTemplates.projectGroupPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchServiceLevelObjectiveFromProjectServiceServiceLevelObjectiveName', () => { - const result = client.matchServiceLevelObjectiveFromProjectServiceServiceLevelObjectiveName(fakePath); - assert.strictEqual(result, "serviceLevelObjectiveValue"); - assert((client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectNotificationChannel', () => { + const fakePath = '/rendered/path/projectNotificationChannel'; + const expectedParameters = { + project: 'projectValue', + notification_channel: 'notificationChannelValue', + }; + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.projectNotificationChannelPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectNotificationChannelPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectNotificationChannelPath', () => { + const result = client.projectNotificationChannelPath( + 'projectValue', + 'notificationChannelValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.projectNotificationChannelPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectNotificationChannelName', () => { + const result = + client.matchProjectFromProjectNotificationChannelName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.projectNotificationChannelPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchNotificationChannelFromProjectNotificationChannelName', () => { + const result = + client.matchNotificationChannelFromProjectNotificationChannelName( + fakePath, + ); + assert.strictEqual(result, 'notificationChannelValue'); + assert( + ( + client.pathTemplates.projectNotificationChannelPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectUptimeCheckConfig', () => { - const fakePath = "/rendered/path/projectUptimeCheckConfig"; - const expectedParameters = { - project: "projectValue", - uptime_check_config: "uptimeCheckConfigValue", - }; - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.projectUptimeCheckConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectUptimeCheckConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectUptimeCheckConfigPath', () => { - const result = client.projectUptimeCheckConfigPath("projectValue", "uptimeCheckConfigValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectUptimeCheckConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + describe('projectService', () => { + const fakePath = '/rendered/path/projectService'; + const expectedParameters = { + project: 'projectValue', + service: 'serviceValue', + }; + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.projectServicePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectServicePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectServicePath', () => { + const result = client.projectServicePath( + 'projectValue', + 'serviceValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.projectServicePathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectServiceName', () => { + const result = client.matchProjectFromProjectServiceName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.projectServicePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServiceFromProjectServiceName', () => { + const result = client.matchServiceFromProjectServiceName(fakePath); + assert.strictEqual(result, 'serviceValue'); + assert( + (client.pathTemplates.projectServicePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchProjectFromProjectUptimeCheckConfigName', () => { - const result = client.matchProjectFromProjectUptimeCheckConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectUptimeCheckConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('projectServiceServiceLevelObjective', () => { + const fakePath = '/rendered/path/projectServiceServiceLevelObjective'; + const expectedParameters = { + project: 'projectValue', + service: 'serviceValue', + service_level_objective: 'serviceLevelObjectiveValue', + }; + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('projectServiceServiceLevelObjectivePath', () => { + const result = client.projectServiceServiceLevelObjectivePath( + 'projectValue', + 'serviceValue', + 'serviceLevelObjectiveValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectServiceServiceLevelObjectiveName', () => { + const result = + client.matchProjectFromProjectServiceServiceLevelObjectiveName( + fakePath, + ); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServiceFromProjectServiceServiceLevelObjectiveName', () => { + const result = + client.matchServiceFromProjectServiceServiceLevelObjectiveName( + fakePath, + ); + assert.strictEqual(result, 'serviceValue'); + assert( + ( + client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServiceLevelObjectiveFromProjectServiceServiceLevelObjectiveName', () => { + const result = + client.matchServiceLevelObjectiveFromProjectServiceServiceLevelObjectiveName( + fakePath, + ); + assert.strictEqual(result, 'serviceLevelObjectiveValue'); + assert( + ( + client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchUptimeCheckConfigFromProjectUptimeCheckConfigName', () => { - const result = client.matchUptimeCheckConfigFromProjectUptimeCheckConfigName(fakePath); - assert.strictEqual(result, "uptimeCheckConfigValue"); - assert((client.pathTemplates.projectUptimeCheckConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectUptimeCheckConfig', () => { + const fakePath = '/rendered/path/projectUptimeCheckConfig'; + const expectedParameters = { + project: 'projectValue', + uptime_check_config: 'uptimeCheckConfigValue', + }; + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.projectUptimeCheckConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectUptimeCheckConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectUptimeCheckConfigPath', () => { + const result = client.projectUptimeCheckConfigPath( + 'projectValue', + 'uptimeCheckConfigValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.projectUptimeCheckConfigPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectUptimeCheckConfigName', () => { + const result = + client.matchProjectFromProjectUptimeCheckConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.projectUptimeCheckConfigPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchUptimeCheckConfigFromProjectUptimeCheckConfigName', () => { + const result = + client.matchUptimeCheckConfigFromProjectUptimeCheckConfigName( + fakePath, + ); + assert.strictEqual(result, 'uptimeCheckConfigValue'); + assert( + ( + client.pathTemplates.projectUptimeCheckConfigPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/core/generator/gapic-generator-typescript/baselines/monitoring/src/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/monitoring/src/index.ts.baseline index 73b0d989f697..dbe2ac332422 100644 --- a/core/generator/gapic-generator-typescript/baselines/monitoring/src/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/monitoring/src/index.ts.baseline @@ -29,7 +29,23 @@ const ServiceMonitoringServiceClient = v3.ServiceMonitoringServiceClient; type ServiceMonitoringServiceClient = v3.ServiceMonitoringServiceClient; const UptimeCheckServiceClient = v3.UptimeCheckServiceClient; type UptimeCheckServiceClient = v3.UptimeCheckServiceClient; -export {v3, AlertPolicyServiceClient, GroupServiceClient, MetricServiceClient, NotificationChannelServiceClient, ServiceMonitoringServiceClient, UptimeCheckServiceClient}; -export default {v3, AlertPolicyServiceClient, GroupServiceClient, MetricServiceClient, NotificationChannelServiceClient, ServiceMonitoringServiceClient, UptimeCheckServiceClient}; +export { + v3, + AlertPolicyServiceClient, + GroupServiceClient, + MetricServiceClient, + NotificationChannelServiceClient, + ServiceMonitoringServiceClient, + UptimeCheckServiceClient, +}; +export default { + v3, + AlertPolicyServiceClient, + GroupServiceClient, + MetricServiceClient, + NotificationChannelServiceClient, + ServiceMonitoringServiceClient, + UptimeCheckServiceClient, +}; import * as protos from '../protos/protos'; -export {protos} +export { protos }; diff --git a/core/generator/gapic-generator-typescript/baselines/monitoring/src/v3/alert_policy_service_client.ts.baseline b/core/generator/gapic-generator-typescript/baselines/monitoring/src/v3/alert_policy_service_client.ts.baseline index 4d2292783aea..6008352ba8d6 100644 --- a/core/generator/gapic-generator-typescript/baselines/monitoring/src/v3/alert_policy_service_client.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/monitoring/src/v3/alert_policy_service_client.ts.baseline @@ -18,11 +18,18 @@ /* global window */ import type * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions, PaginationCallback, GaxCall} from 'google-gax'; -import {Transform} from 'stream'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + PaginationCallback, + GaxCall, +} from 'google-gax'; +import { Transform } from 'stream'; import * as protos from '../../protos/protos'; import jsonProtos = require('../../protos/protos.json'); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; /** * Client JSON configuration object, loaded from @@ -52,7 +59,7 @@ export class AlertPolicyServiceClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('monitoring'); @@ -65,9 +72,9 @@ export class AlertPolicyServiceClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; - alertPolicyServiceStub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; + alertPolicyServiceStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of AlertPolicyServiceClient. @@ -108,21 +115,42 @@ export class AlertPolicyServiceClient { * const client = new AlertPolicyServiceClient({fallback: true}, gax); * ``` */ - constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { // Ensure that options include all the required fields. const staticMembers = this.constructor as typeof AlertPolicyServiceClient; - if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { - throw new Error('Please set either universe_domain or universeDomain, but not both.'); + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); } - const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; - this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; this._servicePath = 'monitoring.' + this._universeDomain; - const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; - const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. if (servicePath !== this._servicePath && !('scopes' in opts)) { @@ -144,7 +172,7 @@ export class AlertPolicyServiceClient { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; @@ -158,10 +186,7 @@ export class AlertPolicyServiceClient { } // Determine the client header string. - const clientHeader = [ - `gax/${this._gaxModule.version}`, - `gapic/${version}`, - ]; + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/${process.versions.node}`); } else { @@ -183,76 +208,83 @@ export class AlertPolicyServiceClient { // Create useful helper objects for these. this.pathTemplates = { folderAlertPolicyPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/alertPolicies/{alert_policy}' + 'folders/{folder}/alertPolicies/{alert_policy}', ), folderAlertPolicyConditionPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/alertPolicies/{alert_policy}/conditions/{condition}' + 'folders/{folder}/alertPolicies/{alert_policy}/conditions/{condition}', ), folderChannelDescriptorPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/notificationChannelDescriptors/{channel_descriptor}' + 'folders/{folder}/notificationChannelDescriptors/{channel_descriptor}', ), folderGroupPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/groups/{group}' + 'folders/{folder}/groups/{group}', ), folderNotificationChannelPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/notificationChannels/{notification_channel}' + 'folders/{folder}/notificationChannels/{notification_channel}', ), folderServicePathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/services/{service}' - ), - folderServiceServiceLevelObjectivePathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/services/{service}/serviceLevelObjectives/{service_level_objective}' + 'folders/{folder}/services/{service}', ), + folderServiceServiceLevelObjectivePathTemplate: + new this._gaxModule.PathTemplate( + 'folders/{folder}/services/{service}/serviceLevelObjectives/{service_level_objective}', + ), folderUptimeCheckConfigPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/uptimeCheckConfigs/{uptime_check_config}' + 'folders/{folder}/uptimeCheckConfigs/{uptime_check_config}', ), organizationAlertPolicyPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/alertPolicies/{alert_policy}' - ), - organizationAlertPolicyConditionPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/alertPolicies/{alert_policy}/conditions/{condition}' - ), - organizationChannelDescriptorPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/notificationChannelDescriptors/{channel_descriptor}' + 'organizations/{organization}/alertPolicies/{alert_policy}', ), + organizationAlertPolicyConditionPathTemplate: + new this._gaxModule.PathTemplate( + 'organizations/{organization}/alertPolicies/{alert_policy}/conditions/{condition}', + ), + organizationChannelDescriptorPathTemplate: + new this._gaxModule.PathTemplate( + 'organizations/{organization}/notificationChannelDescriptors/{channel_descriptor}', + ), organizationGroupPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/groups/{group}' - ), - organizationNotificationChannelPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/notificationChannels/{notification_channel}' + 'organizations/{organization}/groups/{group}', ), + organizationNotificationChannelPathTemplate: + new this._gaxModule.PathTemplate( + 'organizations/{organization}/notificationChannels/{notification_channel}', + ), organizationServicePathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/services/{service}' - ), - organizationServiceServiceLevelObjectivePathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/services/{service}/serviceLevelObjectives/{service_level_objective}' - ), - organizationUptimeCheckConfigPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/uptimeCheckConfigs/{uptime_check_config}' + 'organizations/{organization}/services/{service}', ), + organizationServiceServiceLevelObjectivePathTemplate: + new this._gaxModule.PathTemplate( + 'organizations/{organization}/services/{service}/serviceLevelObjectives/{service_level_objective}', + ), + organizationUptimeCheckConfigPathTemplate: + new this._gaxModule.PathTemplate( + 'organizations/{organization}/uptimeCheckConfigs/{uptime_check_config}', + ), projectAlertPolicyPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/alertPolicies/{alert_policy}' + 'projects/{project}/alertPolicies/{alert_policy}', ), projectAlertPolicyConditionPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/alertPolicies/{alert_policy}/conditions/{condition}' + 'projects/{project}/alertPolicies/{alert_policy}/conditions/{condition}', ), projectChannelDescriptorPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/notificationChannelDescriptors/{channel_descriptor}' + 'projects/{project}/notificationChannelDescriptors/{channel_descriptor}', ), projectGroupPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/groups/{group}' + 'projects/{project}/groups/{group}', ), projectNotificationChannelPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/notificationChannels/{notification_channel}' + 'projects/{project}/notificationChannels/{notification_channel}', ), projectServicePathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/services/{service}' - ), - projectServiceServiceLevelObjectivePathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/services/{service}/serviceLevelObjectives/{service_level_objective}' + 'projects/{project}/services/{service}', ), + projectServiceServiceLevelObjectivePathTemplate: + new this._gaxModule.PathTemplate( + 'projects/{project}/services/{service}/serviceLevelObjectives/{service_level_objective}', + ), projectUptimeCheckConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/uptimeCheckConfigs/{uptime_check_config}' + 'projects/{project}/uptimeCheckConfigs/{uptime_check_config}', ), }; @@ -260,14 +292,20 @@ export class AlertPolicyServiceClient { // (e.g. 50 results at a time, with tokens to get subsequent // pages). Denote the keys used for pagination and results. this.descriptors.page = { - listAlertPolicies: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'alertPolicies') + listAlertPolicies: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'alertPolicies', + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.monitoring.v3.AlertPolicyService', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.monitoring.v3.AlertPolicyService', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + { 'x-goog-api-client': clientHeader.join(' ') }, + ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -298,37 +336,46 @@ export class AlertPolicyServiceClient { // Put together the "service stub" for // google.monitoring.v3.AlertPolicyService. this.alertPolicyServiceStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.monitoring.v3.AlertPolicyService') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.monitoring.v3.AlertPolicyService', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.monitoring.v3.AlertPolicyService, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts, + this._providedCustomServicePath, + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const alertPolicyServiceStubMethods = - ['listAlertPolicies', 'getAlertPolicy', 'createAlertPolicy', 'deleteAlertPolicy', 'updateAlertPolicy']; + const alertPolicyServiceStubMethods = [ + 'listAlertPolicies', + 'getAlertPolicy', + 'createAlertPolicy', + 'deleteAlertPolicy', + 'updateAlertPolicy', + ]; for (const methodName of alertPolicyServiceStubMethods) { const callPromise = this.alertPolicyServiceStub.then( - stub => (...args: Array<{}>) => { - if (this._terminated) { - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error|null|undefined) => () => { + (stub) => + (...args: Array<{}>) => { + if (this._terminated) { + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { throw err; - }); + }, + ); - const descriptor = - this.descriptors.page[methodName] || - undefined; + const descriptor = this.descriptors.page[methodName] || undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -343,8 +390,14 @@ export class AlertPolicyServiceClient { * @returns {string} The DNS address for this service. */ static get servicePath() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'monitoring.googleapis.com'; } @@ -355,8 +408,14 @@ export class AlertPolicyServiceClient { * @returns {string} The DNS address for this service. */ static get apiEndpoint() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'monitoring.googleapis.com'; } @@ -390,7 +449,7 @@ export class AlertPolicyServiceClient { return [ 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/monitoring', - 'https://www.googleapis.com/auth/monitoring.read' + 'https://www.googleapis.com/auth/monitoring.read', ]; } @@ -400,8 +459,9 @@ export class AlertPolicyServiceClient { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId(callback?: Callback): - Promise|void { + getProjectId( + callback?: Callback, + ): Promise | void { if (callback) { this.auth.getProjectId(callback); return; @@ -412,532 +472,683 @@ export class AlertPolicyServiceClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Gets a single alerting policy. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The alerting policy to retrieve. The format is - * - * projects/[PROJECT_ID]/alertPolicies/[ALERT_POLICY_ID] - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.monitoring.v3.AlertPolicy|AlertPolicy}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v3/alert_policy_service.get_alert_policy.js - * region_tag:monitoring_v3_generated_AlertPolicyService_GetAlertPolicy_async - */ + /** + * Gets a single alerting policy. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The alerting policy to retrieve. The format is + * + * projects/[PROJECT_ID]/alertPolicies/[ALERT_POLICY_ID] + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.monitoring.v3.AlertPolicy|AlertPolicy}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v3/alert_policy_service.get_alert_policy.js + * region_tag:monitoring_v3_generated_AlertPolicyService_GetAlertPolicy_async + */ getAlertPolicy( - request?: protos.google.monitoring.v3.IGetAlertPolicyRequest, - options?: CallOptions): - Promise<[ - protos.google.monitoring.v3.IAlertPolicy, - protos.google.monitoring.v3.IGetAlertPolicyRequest|undefined, {}|undefined - ]>; + request?: protos.google.monitoring.v3.IGetAlertPolicyRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.monitoring.v3.IAlertPolicy, + protos.google.monitoring.v3.IGetAlertPolicyRequest | undefined, + {} | undefined, + ] + >; getAlertPolicy( - request: protos.google.monitoring.v3.IGetAlertPolicyRequest, - options: CallOptions, - callback: Callback< - protos.google.monitoring.v3.IAlertPolicy, - protos.google.monitoring.v3.IGetAlertPolicyRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.IGetAlertPolicyRequest, + options: CallOptions, + callback: Callback< + protos.google.monitoring.v3.IAlertPolicy, + protos.google.monitoring.v3.IGetAlertPolicyRequest | null | undefined, + {} | null | undefined + >, + ): void; getAlertPolicy( - request: protos.google.monitoring.v3.IGetAlertPolicyRequest, - callback: Callback< - protos.google.monitoring.v3.IAlertPolicy, - protos.google.monitoring.v3.IGetAlertPolicyRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.IGetAlertPolicyRequest, + callback: Callback< + protos.google.monitoring.v3.IAlertPolicy, + protos.google.monitoring.v3.IGetAlertPolicyRequest | null | undefined, + {} | null | undefined + >, + ): void; getAlertPolicy( - request?: protos.google.monitoring.v3.IGetAlertPolicyRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.monitoring.v3.IGetAlertPolicyRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.monitoring.v3.IAlertPolicy, - protos.google.monitoring.v3.IGetAlertPolicyRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.monitoring.v3.IAlertPolicy, - protos.google.monitoring.v3.IGetAlertPolicyRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.monitoring.v3.IAlertPolicy, - protos.google.monitoring.v3.IGetAlertPolicyRequest|undefined, {}|undefined - ]>|void { + protos.google.monitoring.v3.IGetAlertPolicyRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.monitoring.v3.IAlertPolicy, + protos.google.monitoring.v3.IGetAlertPolicyRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.monitoring.v3.IAlertPolicy, + protos.google.monitoring.v3.IGetAlertPolicyRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getAlertPolicy request %j', request); - const wrappedCallback: Callback< - protos.google.monitoring.v3.IAlertPolicy, - protos.google.monitoring.v3.IGetAlertPolicyRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.monitoring.v3.IAlertPolicy, + protos.google.monitoring.v3.IGetAlertPolicyRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getAlertPolicy response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getAlertPolicy(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.monitoring.v3.IAlertPolicy, - protos.google.monitoring.v3.IGetAlertPolicyRequest|undefined, - {}|undefined - ]) => { - this._log.info('getAlertPolicy response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getAlertPolicy(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.monitoring.v3.IAlertPolicy, + protos.google.monitoring.v3.IGetAlertPolicyRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getAlertPolicy response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Creates a new alerting policy. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The project in which to create the alerting policy. The format is - * `projects/[PROJECT_ID]`. - * - * Note that this field names the parent container in which the alerting - * policy will be written, not the name of the created policy. The alerting - * policy that is returned will have a name that contains a normalized - * representation of this name as a prefix but adds a suffix of the form - * `/alertPolicies/[POLICY_ID]`, identifying the policy in the container. - * @param {google.monitoring.v3.AlertPolicy} request.alertPolicy - * Required. The requested alerting policy. You should omit the `name` field in this - * policy. The name will be returned in the new policy, including - * a new [ALERT_POLICY_ID] value. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.monitoring.v3.AlertPolicy|AlertPolicy}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v3/alert_policy_service.create_alert_policy.js - * region_tag:monitoring_v3_generated_AlertPolicyService_CreateAlertPolicy_async - */ + /** + * Creates a new alerting policy. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The project in which to create the alerting policy. The format is + * `projects/[PROJECT_ID]`. + * + * Note that this field names the parent container in which the alerting + * policy will be written, not the name of the created policy. The alerting + * policy that is returned will have a name that contains a normalized + * representation of this name as a prefix but adds a suffix of the form + * `/alertPolicies/[POLICY_ID]`, identifying the policy in the container. + * @param {google.monitoring.v3.AlertPolicy} request.alertPolicy + * Required. The requested alerting policy. You should omit the `name` field in this + * policy. The name will be returned in the new policy, including + * a new [ALERT_POLICY_ID] value. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.monitoring.v3.AlertPolicy|AlertPolicy}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v3/alert_policy_service.create_alert_policy.js + * region_tag:monitoring_v3_generated_AlertPolicyService_CreateAlertPolicy_async + */ createAlertPolicy( - request?: protos.google.monitoring.v3.ICreateAlertPolicyRequest, - options?: CallOptions): - Promise<[ - protos.google.monitoring.v3.IAlertPolicy, - protos.google.monitoring.v3.ICreateAlertPolicyRequest|undefined, {}|undefined - ]>; + request?: protos.google.monitoring.v3.ICreateAlertPolicyRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.monitoring.v3.IAlertPolicy, + protos.google.monitoring.v3.ICreateAlertPolicyRequest | undefined, + {} | undefined, + ] + >; createAlertPolicy( - request: protos.google.monitoring.v3.ICreateAlertPolicyRequest, - options: CallOptions, - callback: Callback< - protos.google.monitoring.v3.IAlertPolicy, - protos.google.monitoring.v3.ICreateAlertPolicyRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.ICreateAlertPolicyRequest, + options: CallOptions, + callback: Callback< + protos.google.monitoring.v3.IAlertPolicy, + protos.google.monitoring.v3.ICreateAlertPolicyRequest | null | undefined, + {} | null | undefined + >, + ): void; createAlertPolicy( - request: protos.google.monitoring.v3.ICreateAlertPolicyRequest, - callback: Callback< - protos.google.monitoring.v3.IAlertPolicy, - protos.google.monitoring.v3.ICreateAlertPolicyRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.ICreateAlertPolicyRequest, + callback: Callback< + protos.google.monitoring.v3.IAlertPolicy, + protos.google.monitoring.v3.ICreateAlertPolicyRequest | null | undefined, + {} | null | undefined + >, + ): void; createAlertPolicy( - request?: protos.google.monitoring.v3.ICreateAlertPolicyRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.monitoring.v3.ICreateAlertPolicyRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.monitoring.v3.IAlertPolicy, - protos.google.monitoring.v3.ICreateAlertPolicyRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.monitoring.v3.IAlertPolicy, - protos.google.monitoring.v3.ICreateAlertPolicyRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.monitoring.v3.IAlertPolicy, - protos.google.monitoring.v3.ICreateAlertPolicyRequest|undefined, {}|undefined - ]>|void { + | protos.google.monitoring.v3.ICreateAlertPolicyRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.monitoring.v3.IAlertPolicy, + protos.google.monitoring.v3.ICreateAlertPolicyRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.monitoring.v3.IAlertPolicy, + protos.google.monitoring.v3.ICreateAlertPolicyRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('createAlertPolicy request %j', request); - const wrappedCallback: Callback< - protos.google.monitoring.v3.IAlertPolicy, - protos.google.monitoring.v3.ICreateAlertPolicyRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.monitoring.v3.IAlertPolicy, + | protos.google.monitoring.v3.ICreateAlertPolicyRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createAlertPolicy response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.createAlertPolicy(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.monitoring.v3.IAlertPolicy, - protos.google.monitoring.v3.ICreateAlertPolicyRequest|undefined, - {}|undefined - ]) => { - this._log.info('createAlertPolicy response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createAlertPolicy(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.monitoring.v3.IAlertPolicy, + protos.google.monitoring.v3.ICreateAlertPolicyRequest | undefined, + {} | undefined, + ]) => { + this._log.info('createAlertPolicy response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Deletes an alerting policy. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The alerting policy to delete. The format is: - * - * projects/[PROJECT_ID]/alertPolicies/[ALERT_POLICY_ID] - * - * For more information, see {@link protos.google.monitoring.v3.AlertPolicy|AlertPolicy}. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v3/alert_policy_service.delete_alert_policy.js - * region_tag:monitoring_v3_generated_AlertPolicyService_DeleteAlertPolicy_async - */ + /** + * Deletes an alerting policy. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The alerting policy to delete. The format is: + * + * projects/[PROJECT_ID]/alertPolicies/[ALERT_POLICY_ID] + * + * For more information, see {@link protos.google.monitoring.v3.AlertPolicy|AlertPolicy}. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v3/alert_policy_service.delete_alert_policy.js + * region_tag:monitoring_v3_generated_AlertPolicyService_DeleteAlertPolicy_async + */ deleteAlertPolicy( - request?: protos.google.monitoring.v3.IDeleteAlertPolicyRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.IDeleteAlertPolicyRequest|undefined, {}|undefined - ]>; + request?: protos.google.monitoring.v3.IDeleteAlertPolicyRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.monitoring.v3.IDeleteAlertPolicyRequest | undefined, + {} | undefined, + ] + >; deleteAlertPolicy( - request: protos.google.monitoring.v3.IDeleteAlertPolicyRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.IDeleteAlertPolicyRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.IDeleteAlertPolicyRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.monitoring.v3.IDeleteAlertPolicyRequest | null | undefined, + {} | null | undefined + >, + ): void; deleteAlertPolicy( - request: protos.google.monitoring.v3.IDeleteAlertPolicyRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.IDeleteAlertPolicyRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.IDeleteAlertPolicyRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.monitoring.v3.IDeleteAlertPolicyRequest | null | undefined, + {} | null | undefined + >, + ): void; deleteAlertPolicy( - request?: protos.google.monitoring.v3.IDeleteAlertPolicyRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.IDeleteAlertPolicyRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.monitoring.v3.IDeleteAlertPolicyRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.IDeleteAlertPolicyRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.IDeleteAlertPolicyRequest|undefined, {}|undefined - ]>|void { + | protos.google.monitoring.v3.IDeleteAlertPolicyRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + protos.google.monitoring.v3.IDeleteAlertPolicyRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.monitoring.v3.IDeleteAlertPolicyRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('deleteAlertPolicy request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.IDeleteAlertPolicyRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.monitoring.v3.IDeleteAlertPolicyRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteAlertPolicy response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.deleteAlertPolicy(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.IDeleteAlertPolicyRequest|undefined, - {}|undefined - ]) => { - this._log.info('deleteAlertPolicy response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteAlertPolicy(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.monitoring.v3.IDeleteAlertPolicyRequest | undefined, + {} | undefined, + ]) => { + this._log.info('deleteAlertPolicy response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Updates an alerting policy. You can either replace the entire policy with - * a new one or replace only certain fields in the current alerting policy by - * specifying the fields to be updated via `updateMask`. Returns the - * updated alerting policy. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.protobuf.FieldMask} request.updateMask - * Optional. A list of alerting policy field names. If this field is not - * empty, each listed field in the existing alerting policy is set to the - * value of the corresponding field in the supplied policy (`alert_policy`), - * or to the field's default value if the field is not in the supplied - * alerting policy. Fields not listed retain their previous value. - * - * Examples of valid field masks include `display_name`, `documentation`, - * `documentation.content`, `documentation.mime_type`, `user_labels`, - * `user_label.nameofkey`, `enabled`, `conditions`, `combiner`, etc. - * - * If this field is empty, then the supplied alerting policy replaces the - * existing policy. It is the same as deleting the existing policy and - * adding the supplied policy, except for the following: - * - * + The new policy will have the same `[ALERT_POLICY_ID]` as the former - * policy. This gives you continuity with the former policy in your - * notifications and incidents. - * + Conditions in the new policy will keep their former `[CONDITION_ID]` if - * the supplied condition includes the `name` field with that - * `[CONDITION_ID]`. If the supplied condition omits the `name` field, - * then a new `[CONDITION_ID]` is created. - * @param {google.monitoring.v3.AlertPolicy} request.alertPolicy - * Required. The updated alerting policy or the updated values for the - * fields listed in `update_mask`. - * If `update_mask` is not empty, any fields in this policy that are - * not in `update_mask` are ignored. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.monitoring.v3.AlertPolicy|AlertPolicy}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v3/alert_policy_service.update_alert_policy.js - * region_tag:monitoring_v3_generated_AlertPolicyService_UpdateAlertPolicy_async - */ + /** + * Updates an alerting policy. You can either replace the entire policy with + * a new one or replace only certain fields in the current alerting policy by + * specifying the fields to be updated via `updateMask`. Returns the + * updated alerting policy. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.protobuf.FieldMask} request.updateMask + * Optional. A list of alerting policy field names. If this field is not + * empty, each listed field in the existing alerting policy is set to the + * value of the corresponding field in the supplied policy (`alert_policy`), + * or to the field's default value if the field is not in the supplied + * alerting policy. Fields not listed retain their previous value. + * + * Examples of valid field masks include `display_name`, `documentation`, + * `documentation.content`, `documentation.mime_type`, `user_labels`, + * `user_label.nameofkey`, `enabled`, `conditions`, `combiner`, etc. + * + * If this field is empty, then the supplied alerting policy replaces the + * existing policy. It is the same as deleting the existing policy and + * adding the supplied policy, except for the following: + * + * + The new policy will have the same `[ALERT_POLICY_ID]` as the former + * policy. This gives you continuity with the former policy in your + * notifications and incidents. + * + Conditions in the new policy will keep their former `[CONDITION_ID]` if + * the supplied condition includes the `name` field with that + * `[CONDITION_ID]`. If the supplied condition omits the `name` field, + * then a new `[CONDITION_ID]` is created. + * @param {google.monitoring.v3.AlertPolicy} request.alertPolicy + * Required. The updated alerting policy or the updated values for the + * fields listed in `update_mask`. + * If `update_mask` is not empty, any fields in this policy that are + * not in `update_mask` are ignored. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.monitoring.v3.AlertPolicy|AlertPolicy}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v3/alert_policy_service.update_alert_policy.js + * region_tag:monitoring_v3_generated_AlertPolicyService_UpdateAlertPolicy_async + */ updateAlertPolicy( - request?: protos.google.monitoring.v3.IUpdateAlertPolicyRequest, - options?: CallOptions): - Promise<[ - protos.google.monitoring.v3.IAlertPolicy, - protos.google.monitoring.v3.IUpdateAlertPolicyRequest|undefined, {}|undefined - ]>; + request?: protos.google.monitoring.v3.IUpdateAlertPolicyRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.monitoring.v3.IAlertPolicy, + protos.google.monitoring.v3.IUpdateAlertPolicyRequest | undefined, + {} | undefined, + ] + >; updateAlertPolicy( - request: protos.google.monitoring.v3.IUpdateAlertPolicyRequest, - options: CallOptions, - callback: Callback< - protos.google.monitoring.v3.IAlertPolicy, - protos.google.monitoring.v3.IUpdateAlertPolicyRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.IUpdateAlertPolicyRequest, + options: CallOptions, + callback: Callback< + protos.google.monitoring.v3.IAlertPolicy, + protos.google.monitoring.v3.IUpdateAlertPolicyRequest | null | undefined, + {} | null | undefined + >, + ): void; updateAlertPolicy( - request: protos.google.monitoring.v3.IUpdateAlertPolicyRequest, - callback: Callback< - protos.google.monitoring.v3.IAlertPolicy, - protos.google.monitoring.v3.IUpdateAlertPolicyRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.IUpdateAlertPolicyRequest, + callback: Callback< + protos.google.monitoring.v3.IAlertPolicy, + protos.google.monitoring.v3.IUpdateAlertPolicyRequest | null | undefined, + {} | null | undefined + >, + ): void; updateAlertPolicy( - request?: protos.google.monitoring.v3.IUpdateAlertPolicyRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.monitoring.v3.IAlertPolicy, - protos.google.monitoring.v3.IUpdateAlertPolicyRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.monitoring.v3.IUpdateAlertPolicyRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.monitoring.v3.IAlertPolicy, - protos.google.monitoring.v3.IUpdateAlertPolicyRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.monitoring.v3.IAlertPolicy, - protos.google.monitoring.v3.IUpdateAlertPolicyRequest|undefined, {}|undefined - ]>|void { + | protos.google.monitoring.v3.IUpdateAlertPolicyRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.monitoring.v3.IAlertPolicy, + protos.google.monitoring.v3.IUpdateAlertPolicyRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.monitoring.v3.IAlertPolicy, + protos.google.monitoring.v3.IUpdateAlertPolicyRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'alert_policy.name': request.alertPolicy!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'alert_policy.name': request.alertPolicy!.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateAlertPolicy request %j', request); - const wrappedCallback: Callback< - protos.google.monitoring.v3.IAlertPolicy, - protos.google.monitoring.v3.IUpdateAlertPolicyRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.monitoring.v3.IAlertPolicy, + | protos.google.monitoring.v3.IUpdateAlertPolicyRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateAlertPolicy response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.updateAlertPolicy(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.monitoring.v3.IAlertPolicy, - protos.google.monitoring.v3.IUpdateAlertPolicyRequest|undefined, - {}|undefined - ]) => { - this._log.info('updateAlertPolicy response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateAlertPolicy(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.monitoring.v3.IAlertPolicy, + protos.google.monitoring.v3.IUpdateAlertPolicyRequest | undefined, + {} | undefined, + ]) => { + this._log.info('updateAlertPolicy response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } - /** - * Lists the existing alerting policies for the project. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The project whose alert policies are to be listed. The format is - * - * projects/[PROJECT_ID] - * - * Note that this field names the parent container in which the alerting - * policies to be listed are stored. To retrieve a single alerting policy - * by name, use the - * {@link protos.google.monitoring.v3.AlertPolicyService.GetAlertPolicy|GetAlertPolicy} - * operation, instead. - * @param {string} request.filter - * If provided, this field specifies the criteria that must be met by - * alert policies to be included in the response. - * - * For more details, see [sorting and - * filtering](/monitoring/api/v3/sorting-and-filtering). - * @param {string} request.orderBy - * A comma-separated list of fields by which to sort the result. Supports - * the same set of field references as the `filter` field. Entries can be - * prefixed with a minus sign to sort by the field in descending order. - * - * For more details, see [sorting and - * filtering](/monitoring/api/v3/sorting-and-filtering). - * @param {number} request.pageSize - * The maximum number of results to return in a single response. - * @param {string} request.pageToken - * If this field is not empty then it must contain the `nextPageToken` value - * returned by a previous call to this method. Using this field causes the - * method to return more results from the previous method call. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.monitoring.v3.AlertPolicy|AlertPolicy}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `listAlertPoliciesAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Lists the existing alerting policies for the project. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The project whose alert policies are to be listed. The format is + * + * projects/[PROJECT_ID] + * + * Note that this field names the parent container in which the alerting + * policies to be listed are stored. To retrieve a single alerting policy + * by name, use the + * {@link protos.google.monitoring.v3.AlertPolicyService.GetAlertPolicy|GetAlertPolicy} + * operation, instead. + * @param {string} request.filter + * If provided, this field specifies the criteria that must be met by + * alert policies to be included in the response. + * + * For more details, see [sorting and + * filtering](/monitoring/api/v3/sorting-and-filtering). + * @param {string} request.orderBy + * A comma-separated list of fields by which to sort the result. Supports + * the same set of field references as the `filter` field. Entries can be + * prefixed with a minus sign to sort by the field in descending order. + * + * For more details, see [sorting and + * filtering](/monitoring/api/v3/sorting-and-filtering). + * @param {number} request.pageSize + * The maximum number of results to return in a single response. + * @param {string} request.pageToken + * If this field is not empty then it must contain the `nextPageToken` value + * returned by a previous call to this method. Using this field causes the + * method to return more results from the previous method call. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.monitoring.v3.AlertPolicy|AlertPolicy}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listAlertPoliciesAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listAlertPolicies( - request?: protos.google.monitoring.v3.IListAlertPoliciesRequest, - options?: CallOptions): - Promise<[ - protos.google.monitoring.v3.IAlertPolicy[], - protos.google.monitoring.v3.IListAlertPoliciesRequest|null, - protos.google.monitoring.v3.IListAlertPoliciesResponse - ]>; + request?: protos.google.monitoring.v3.IListAlertPoliciesRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.monitoring.v3.IAlertPolicy[], + protos.google.monitoring.v3.IListAlertPoliciesRequest | null, + protos.google.monitoring.v3.IListAlertPoliciesResponse, + ] + >; listAlertPolicies( - request: protos.google.monitoring.v3.IListAlertPoliciesRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.monitoring.v3.IListAlertPoliciesRequest, - protos.google.monitoring.v3.IListAlertPoliciesResponse|null|undefined, - protos.google.monitoring.v3.IAlertPolicy>): void; + request: protos.google.monitoring.v3.IListAlertPoliciesRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.monitoring.v3.IListAlertPoliciesRequest, + protos.google.monitoring.v3.IListAlertPoliciesResponse | null | undefined, + protos.google.monitoring.v3.IAlertPolicy + >, + ): void; listAlertPolicies( - request: protos.google.monitoring.v3.IListAlertPoliciesRequest, - callback: PaginationCallback< - protos.google.monitoring.v3.IListAlertPoliciesRequest, - protos.google.monitoring.v3.IListAlertPoliciesResponse|null|undefined, - protos.google.monitoring.v3.IAlertPolicy>): void; + request: protos.google.monitoring.v3.IListAlertPoliciesRequest, + callback: PaginationCallback< + protos.google.monitoring.v3.IListAlertPoliciesRequest, + protos.google.monitoring.v3.IListAlertPoliciesResponse | null | undefined, + protos.google.monitoring.v3.IAlertPolicy + >, + ): void; listAlertPolicies( - request?: protos.google.monitoring.v3.IListAlertPoliciesRequest, - optionsOrCallback?: CallOptions|PaginationCallback< + request?: protos.google.monitoring.v3.IListAlertPoliciesRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.monitoring.v3.IListAlertPoliciesRequest, - protos.google.monitoring.v3.IListAlertPoliciesResponse|null|undefined, - protos.google.monitoring.v3.IAlertPolicy>, - callback?: PaginationCallback< - protos.google.monitoring.v3.IListAlertPoliciesRequest, - protos.google.monitoring.v3.IListAlertPoliciesResponse|null|undefined, - protos.google.monitoring.v3.IAlertPolicy>): - Promise<[ - protos.google.monitoring.v3.IAlertPolicy[], - protos.google.monitoring.v3.IListAlertPoliciesRequest|null, - protos.google.monitoring.v3.IListAlertPoliciesResponse - ]>|void { + | protos.google.monitoring.v3.IListAlertPoliciesResponse + | null + | undefined, + protos.google.monitoring.v3.IAlertPolicy + >, + callback?: PaginationCallback< + protos.google.monitoring.v3.IListAlertPoliciesRequest, + protos.google.monitoring.v3.IListAlertPoliciesResponse | null | undefined, + protos.google.monitoring.v3.IAlertPolicy + >, + ): Promise< + [ + protos.google.monitoring.v3.IAlertPolicy[], + protos.google.monitoring.v3.IListAlertPoliciesRequest | null, + protos.google.monitoring.v3.IListAlertPoliciesResponse, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.monitoring.v3.IListAlertPoliciesRequest, - protos.google.monitoring.v3.IListAlertPoliciesResponse|null|undefined, - protos.google.monitoring.v3.IAlertPolicy>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.monitoring.v3.IListAlertPoliciesRequest, + | protos.google.monitoring.v3.IListAlertPoliciesResponse + | null + | undefined, + protos.google.monitoring.v3.IAlertPolicy + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listAlertPolicies values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -946,152 +1157,156 @@ export class AlertPolicyServiceClient { this._log.info('listAlertPolicies request %j', request); return this.innerApiCalls .listAlertPolicies(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.monitoring.v3.IAlertPolicy[], - protos.google.monitoring.v3.IListAlertPoliciesRequest|null, - protos.google.monitoring.v3.IListAlertPoliciesResponse - ]) => { - this._log.info('listAlertPolicies values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.monitoring.v3.IAlertPolicy[], + protos.google.monitoring.v3.IListAlertPoliciesRequest | null, + protos.google.monitoring.v3.IListAlertPoliciesResponse, + ]) => { + this._log.info('listAlertPolicies values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listAlertPolicies`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The project whose alert policies are to be listed. The format is - * - * projects/[PROJECT_ID] - * - * Note that this field names the parent container in which the alerting - * policies to be listed are stored. To retrieve a single alerting policy - * by name, use the - * {@link protos.google.monitoring.v3.AlertPolicyService.GetAlertPolicy|GetAlertPolicy} - * operation, instead. - * @param {string} request.filter - * If provided, this field specifies the criteria that must be met by - * alert policies to be included in the response. - * - * For more details, see [sorting and - * filtering](/monitoring/api/v3/sorting-and-filtering). - * @param {string} request.orderBy - * A comma-separated list of fields by which to sort the result. Supports - * the same set of field references as the `filter` field. Entries can be - * prefixed with a minus sign to sort by the field in descending order. - * - * For more details, see [sorting and - * filtering](/monitoring/api/v3/sorting-and-filtering). - * @param {number} request.pageSize - * The maximum number of results to return in a single response. - * @param {string} request.pageToken - * If this field is not empty then it must contain the `nextPageToken` value - * returned by a previous call to this method. Using this field causes the - * method to return more results from the previous method call. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.monitoring.v3.AlertPolicy|AlertPolicy} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `listAlertPoliciesAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `listAlertPolicies`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The project whose alert policies are to be listed. The format is + * + * projects/[PROJECT_ID] + * + * Note that this field names the parent container in which the alerting + * policies to be listed are stored. To retrieve a single alerting policy + * by name, use the + * {@link protos.google.monitoring.v3.AlertPolicyService.GetAlertPolicy|GetAlertPolicy} + * operation, instead. + * @param {string} request.filter + * If provided, this field specifies the criteria that must be met by + * alert policies to be included in the response. + * + * For more details, see [sorting and + * filtering](/monitoring/api/v3/sorting-and-filtering). + * @param {string} request.orderBy + * A comma-separated list of fields by which to sort the result. Supports + * the same set of field references as the `filter` field. Entries can be + * prefixed with a minus sign to sort by the field in descending order. + * + * For more details, see [sorting and + * filtering](/monitoring/api/v3/sorting-and-filtering). + * @param {number} request.pageSize + * The maximum number of results to return in a single response. + * @param {string} request.pageToken + * If this field is not empty then it must contain the `nextPageToken` value + * returned by a previous call to this method. Using this field causes the + * method to return more results from the previous method call. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.monitoring.v3.AlertPolicy|AlertPolicy} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listAlertPoliciesAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listAlertPoliciesStream( - request?: protos.google.monitoring.v3.IListAlertPoliciesRequest, - options?: CallOptions): - Transform{ + request?: protos.google.monitoring.v3.IListAlertPoliciesRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); const defaultCallSettings = this._defaults['listAlertPolicies']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listAlertPolicies stream %j', request); return this.descriptors.page.listAlertPolicies.createStream( this.innerApiCalls.listAlertPolicies as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listAlertPolicies`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The project whose alert policies are to be listed. The format is - * - * projects/[PROJECT_ID] - * - * Note that this field names the parent container in which the alerting - * policies to be listed are stored. To retrieve a single alerting policy - * by name, use the - * {@link protos.google.monitoring.v3.AlertPolicyService.GetAlertPolicy|GetAlertPolicy} - * operation, instead. - * @param {string} request.filter - * If provided, this field specifies the criteria that must be met by - * alert policies to be included in the response. - * - * For more details, see [sorting and - * filtering](/monitoring/api/v3/sorting-and-filtering). - * @param {string} request.orderBy - * A comma-separated list of fields by which to sort the result. Supports - * the same set of field references as the `filter` field. Entries can be - * prefixed with a minus sign to sort by the field in descending order. - * - * For more details, see [sorting and - * filtering](/monitoring/api/v3/sorting-and-filtering). - * @param {number} request.pageSize - * The maximum number of results to return in a single response. - * @param {string} request.pageToken - * If this field is not empty then it must contain the `nextPageToken` value - * returned by a previous call to this method. Using this field causes the - * method to return more results from the previous method call. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.monitoring.v3.AlertPolicy|AlertPolicy}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v3/alert_policy_service.list_alert_policies.js - * region_tag:monitoring_v3_generated_AlertPolicyService_ListAlertPolicies_async - */ + /** + * Equivalent to `listAlertPolicies`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The project whose alert policies are to be listed. The format is + * + * projects/[PROJECT_ID] + * + * Note that this field names the parent container in which the alerting + * policies to be listed are stored. To retrieve a single alerting policy + * by name, use the + * {@link protos.google.monitoring.v3.AlertPolicyService.GetAlertPolicy|GetAlertPolicy} + * operation, instead. + * @param {string} request.filter + * If provided, this field specifies the criteria that must be met by + * alert policies to be included in the response. + * + * For more details, see [sorting and + * filtering](/monitoring/api/v3/sorting-and-filtering). + * @param {string} request.orderBy + * A comma-separated list of fields by which to sort the result. Supports + * the same set of field references as the `filter` field. Entries can be + * prefixed with a minus sign to sort by the field in descending order. + * + * For more details, see [sorting and + * filtering](/monitoring/api/v3/sorting-and-filtering). + * @param {number} request.pageSize + * The maximum number of results to return in a single response. + * @param {string} request.pageToken + * If this field is not empty then it must contain the `nextPageToken` value + * returned by a previous call to this method. Using this field causes the + * method to return more results from the previous method call. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.monitoring.v3.AlertPolicy|AlertPolicy}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v3/alert_policy_service.list_alert_policies.js + * region_tag:monitoring_v3_generated_AlertPolicyService_ListAlertPolicies_async + */ listAlertPoliciesAsync( - request?: protos.google.monitoring.v3.IListAlertPoliciesRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.monitoring.v3.IListAlertPoliciesRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); const defaultCallSettings = this._defaults['listAlertPolicies']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listAlertPolicies iterate %j', request); return this.descriptors.page.listAlertPolicies.asyncIterate( this.innerApiCalls['listAlertPolicies'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } // -------------------- @@ -1105,7 +1320,7 @@ export class AlertPolicyServiceClient { * @param {string} alert_policy * @returns {string} Resource name string. */ - folderAlertPolicyPath(folder:string,alertPolicy:string) { + folderAlertPolicyPath(folder: string, alertPolicy: string) { return this.pathTemplates.folderAlertPolicyPathTemplate.render({ folder: folder, alert_policy: alertPolicy, @@ -1120,7 +1335,9 @@ export class AlertPolicyServiceClient { * @returns {string} A string representing the folder. */ matchFolderFromFolderAlertPolicyName(folderAlertPolicyName: string) { - return this.pathTemplates.folderAlertPolicyPathTemplate.match(folderAlertPolicyName).folder; + return this.pathTemplates.folderAlertPolicyPathTemplate.match( + folderAlertPolicyName, + ).folder; } /** @@ -1131,7 +1348,9 @@ export class AlertPolicyServiceClient { * @returns {string} A string representing the alert_policy. */ matchAlertPolicyFromFolderAlertPolicyName(folderAlertPolicyName: string) { - return this.pathTemplates.folderAlertPolicyPathTemplate.match(folderAlertPolicyName).alert_policy; + return this.pathTemplates.folderAlertPolicyPathTemplate.match( + folderAlertPolicyName, + ).alert_policy; } /** @@ -1142,7 +1361,11 @@ export class AlertPolicyServiceClient { * @param {string} condition * @returns {string} Resource name string. */ - folderAlertPolicyConditionPath(folder:string,alertPolicy:string,condition:string) { + folderAlertPolicyConditionPath( + folder: string, + alertPolicy: string, + condition: string, + ) { return this.pathTemplates.folderAlertPolicyConditionPathTemplate.render({ folder: folder, alert_policy: alertPolicy, @@ -1157,8 +1380,12 @@ export class AlertPolicyServiceClient { * A fully-qualified path representing folder_alert_policy_condition resource. * @returns {string} A string representing the folder. */ - matchFolderFromFolderAlertPolicyConditionName(folderAlertPolicyConditionName: string) { - return this.pathTemplates.folderAlertPolicyConditionPathTemplate.match(folderAlertPolicyConditionName).folder; + matchFolderFromFolderAlertPolicyConditionName( + folderAlertPolicyConditionName: string, + ) { + return this.pathTemplates.folderAlertPolicyConditionPathTemplate.match( + folderAlertPolicyConditionName, + ).folder; } /** @@ -1168,8 +1395,12 @@ export class AlertPolicyServiceClient { * A fully-qualified path representing folder_alert_policy_condition resource. * @returns {string} A string representing the alert_policy. */ - matchAlertPolicyFromFolderAlertPolicyConditionName(folderAlertPolicyConditionName: string) { - return this.pathTemplates.folderAlertPolicyConditionPathTemplate.match(folderAlertPolicyConditionName).alert_policy; + matchAlertPolicyFromFolderAlertPolicyConditionName( + folderAlertPolicyConditionName: string, + ) { + return this.pathTemplates.folderAlertPolicyConditionPathTemplate.match( + folderAlertPolicyConditionName, + ).alert_policy; } /** @@ -1179,8 +1410,12 @@ export class AlertPolicyServiceClient { * A fully-qualified path representing folder_alert_policy_condition resource. * @returns {string} A string representing the condition. */ - matchConditionFromFolderAlertPolicyConditionName(folderAlertPolicyConditionName: string) { - return this.pathTemplates.folderAlertPolicyConditionPathTemplate.match(folderAlertPolicyConditionName).condition; + matchConditionFromFolderAlertPolicyConditionName( + folderAlertPolicyConditionName: string, + ) { + return this.pathTemplates.folderAlertPolicyConditionPathTemplate.match( + folderAlertPolicyConditionName, + ).condition; } /** @@ -1190,7 +1425,7 @@ export class AlertPolicyServiceClient { * @param {string} channel_descriptor * @returns {string} Resource name string. */ - folderChannelDescriptorPath(folder:string,channelDescriptor:string) { + folderChannelDescriptorPath(folder: string, channelDescriptor: string) { return this.pathTemplates.folderChannelDescriptorPathTemplate.render({ folder: folder, channel_descriptor: channelDescriptor, @@ -1204,8 +1439,12 @@ export class AlertPolicyServiceClient { * A fully-qualified path representing folder_channel_descriptor resource. * @returns {string} A string representing the folder. */ - matchFolderFromFolderChannelDescriptorName(folderChannelDescriptorName: string) { - return this.pathTemplates.folderChannelDescriptorPathTemplate.match(folderChannelDescriptorName).folder; + matchFolderFromFolderChannelDescriptorName( + folderChannelDescriptorName: string, + ) { + return this.pathTemplates.folderChannelDescriptorPathTemplate.match( + folderChannelDescriptorName, + ).folder; } /** @@ -1215,8 +1454,12 @@ export class AlertPolicyServiceClient { * A fully-qualified path representing folder_channel_descriptor resource. * @returns {string} A string representing the channel_descriptor. */ - matchChannelDescriptorFromFolderChannelDescriptorName(folderChannelDescriptorName: string) { - return this.pathTemplates.folderChannelDescriptorPathTemplate.match(folderChannelDescriptorName).channel_descriptor; + matchChannelDescriptorFromFolderChannelDescriptorName( + folderChannelDescriptorName: string, + ) { + return this.pathTemplates.folderChannelDescriptorPathTemplate.match( + folderChannelDescriptorName, + ).channel_descriptor; } /** @@ -1226,7 +1469,7 @@ export class AlertPolicyServiceClient { * @param {string} group * @returns {string} Resource name string. */ - folderGroupPath(folder:string,group:string) { + folderGroupPath(folder: string, group: string) { return this.pathTemplates.folderGroupPathTemplate.render({ folder: folder, group: group, @@ -1241,7 +1484,8 @@ export class AlertPolicyServiceClient { * @returns {string} A string representing the folder. */ matchFolderFromFolderGroupName(folderGroupName: string) { - return this.pathTemplates.folderGroupPathTemplate.match(folderGroupName).folder; + return this.pathTemplates.folderGroupPathTemplate.match(folderGroupName) + .folder; } /** @@ -1252,7 +1496,8 @@ export class AlertPolicyServiceClient { * @returns {string} A string representing the group. */ matchGroupFromFolderGroupName(folderGroupName: string) { - return this.pathTemplates.folderGroupPathTemplate.match(folderGroupName).group; + return this.pathTemplates.folderGroupPathTemplate.match(folderGroupName) + .group; } /** @@ -1262,7 +1507,7 @@ export class AlertPolicyServiceClient { * @param {string} notification_channel * @returns {string} Resource name string. */ - folderNotificationChannelPath(folder:string,notificationChannel:string) { + folderNotificationChannelPath(folder: string, notificationChannel: string) { return this.pathTemplates.folderNotificationChannelPathTemplate.render({ folder: folder, notification_channel: notificationChannel, @@ -1276,8 +1521,12 @@ export class AlertPolicyServiceClient { * A fully-qualified path representing folder_notification_channel resource. * @returns {string} A string representing the folder. */ - matchFolderFromFolderNotificationChannelName(folderNotificationChannelName: string) { - return this.pathTemplates.folderNotificationChannelPathTemplate.match(folderNotificationChannelName).folder; + matchFolderFromFolderNotificationChannelName( + folderNotificationChannelName: string, + ) { + return this.pathTemplates.folderNotificationChannelPathTemplate.match( + folderNotificationChannelName, + ).folder; } /** @@ -1287,8 +1536,12 @@ export class AlertPolicyServiceClient { * A fully-qualified path representing folder_notification_channel resource. * @returns {string} A string representing the notification_channel. */ - matchNotificationChannelFromFolderNotificationChannelName(folderNotificationChannelName: string) { - return this.pathTemplates.folderNotificationChannelPathTemplate.match(folderNotificationChannelName).notification_channel; + matchNotificationChannelFromFolderNotificationChannelName( + folderNotificationChannelName: string, + ) { + return this.pathTemplates.folderNotificationChannelPathTemplate.match( + folderNotificationChannelName, + ).notification_channel; } /** @@ -1298,7 +1551,7 @@ export class AlertPolicyServiceClient { * @param {string} service * @returns {string} Resource name string. */ - folderServicePath(folder:string,service:string) { + folderServicePath(folder: string, service: string) { return this.pathTemplates.folderServicePathTemplate.render({ folder: folder, service: service, @@ -1313,7 +1566,8 @@ export class AlertPolicyServiceClient { * @returns {string} A string representing the folder. */ matchFolderFromFolderServiceName(folderServiceName: string) { - return this.pathTemplates.folderServicePathTemplate.match(folderServiceName).folder; + return this.pathTemplates.folderServicePathTemplate.match(folderServiceName) + .folder; } /** @@ -1324,7 +1578,8 @@ export class AlertPolicyServiceClient { * @returns {string} A string representing the service. */ matchServiceFromFolderServiceName(folderServiceName: string) { - return this.pathTemplates.folderServicePathTemplate.match(folderServiceName).service; + return this.pathTemplates.folderServicePathTemplate.match(folderServiceName) + .service; } /** @@ -1335,12 +1590,18 @@ export class AlertPolicyServiceClient { * @param {string} service_level_objective * @returns {string} Resource name string. */ - folderServiceServiceLevelObjectivePath(folder:string,service:string,serviceLevelObjective:string) { - return this.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.render({ - folder: folder, - service: service, - service_level_objective: serviceLevelObjective, - }); + folderServiceServiceLevelObjectivePath( + folder: string, + service: string, + serviceLevelObjective: string, + ) { + return this.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.render( + { + folder: folder, + service: service, + service_level_objective: serviceLevelObjective, + }, + ); } /** @@ -1350,8 +1611,12 @@ export class AlertPolicyServiceClient { * A fully-qualified path representing folder_service_service_level_objective resource. * @returns {string} A string representing the folder. */ - matchFolderFromFolderServiceServiceLevelObjectiveName(folderServiceServiceLevelObjectiveName: string) { - return this.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match(folderServiceServiceLevelObjectiveName).folder; + matchFolderFromFolderServiceServiceLevelObjectiveName( + folderServiceServiceLevelObjectiveName: string, + ) { + return this.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match( + folderServiceServiceLevelObjectiveName, + ).folder; } /** @@ -1361,8 +1626,12 @@ export class AlertPolicyServiceClient { * A fully-qualified path representing folder_service_service_level_objective resource. * @returns {string} A string representing the service. */ - matchServiceFromFolderServiceServiceLevelObjectiveName(folderServiceServiceLevelObjectiveName: string) { - return this.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match(folderServiceServiceLevelObjectiveName).service; + matchServiceFromFolderServiceServiceLevelObjectiveName( + folderServiceServiceLevelObjectiveName: string, + ) { + return this.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match( + folderServiceServiceLevelObjectiveName, + ).service; } /** @@ -1372,8 +1641,12 @@ export class AlertPolicyServiceClient { * A fully-qualified path representing folder_service_service_level_objective resource. * @returns {string} A string representing the service_level_objective. */ - matchServiceLevelObjectiveFromFolderServiceServiceLevelObjectiveName(folderServiceServiceLevelObjectiveName: string) { - return this.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match(folderServiceServiceLevelObjectiveName).service_level_objective; + matchServiceLevelObjectiveFromFolderServiceServiceLevelObjectiveName( + folderServiceServiceLevelObjectiveName: string, + ) { + return this.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match( + folderServiceServiceLevelObjectiveName, + ).service_level_objective; } /** @@ -1383,7 +1656,7 @@ export class AlertPolicyServiceClient { * @param {string} uptime_check_config * @returns {string} Resource name string. */ - folderUptimeCheckConfigPath(folder:string,uptimeCheckConfig:string) { + folderUptimeCheckConfigPath(folder: string, uptimeCheckConfig: string) { return this.pathTemplates.folderUptimeCheckConfigPathTemplate.render({ folder: folder, uptime_check_config: uptimeCheckConfig, @@ -1397,8 +1670,12 @@ export class AlertPolicyServiceClient { * A fully-qualified path representing folder_uptime_check_config resource. * @returns {string} A string representing the folder. */ - matchFolderFromFolderUptimeCheckConfigName(folderUptimeCheckConfigName: string) { - return this.pathTemplates.folderUptimeCheckConfigPathTemplate.match(folderUptimeCheckConfigName).folder; + matchFolderFromFolderUptimeCheckConfigName( + folderUptimeCheckConfigName: string, + ) { + return this.pathTemplates.folderUptimeCheckConfigPathTemplate.match( + folderUptimeCheckConfigName, + ).folder; } /** @@ -1408,8 +1685,12 @@ export class AlertPolicyServiceClient { * A fully-qualified path representing folder_uptime_check_config resource. * @returns {string} A string representing the uptime_check_config. */ - matchUptimeCheckConfigFromFolderUptimeCheckConfigName(folderUptimeCheckConfigName: string) { - return this.pathTemplates.folderUptimeCheckConfigPathTemplate.match(folderUptimeCheckConfigName).uptime_check_config; + matchUptimeCheckConfigFromFolderUptimeCheckConfigName( + folderUptimeCheckConfigName: string, + ) { + return this.pathTemplates.folderUptimeCheckConfigPathTemplate.match( + folderUptimeCheckConfigName, + ).uptime_check_config; } /** @@ -1419,7 +1700,7 @@ export class AlertPolicyServiceClient { * @param {string} alert_policy * @returns {string} Resource name string. */ - organizationAlertPolicyPath(organization:string,alertPolicy:string) { + organizationAlertPolicyPath(organization: string, alertPolicy: string) { return this.pathTemplates.organizationAlertPolicyPathTemplate.render({ organization: organization, alert_policy: alertPolicy, @@ -1433,8 +1714,12 @@ export class AlertPolicyServiceClient { * A fully-qualified path representing organization_alert_policy resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationAlertPolicyName(organizationAlertPolicyName: string) { - return this.pathTemplates.organizationAlertPolicyPathTemplate.match(organizationAlertPolicyName).organization; + matchOrganizationFromOrganizationAlertPolicyName( + organizationAlertPolicyName: string, + ) { + return this.pathTemplates.organizationAlertPolicyPathTemplate.match( + organizationAlertPolicyName, + ).organization; } /** @@ -1444,8 +1729,12 @@ export class AlertPolicyServiceClient { * A fully-qualified path representing organization_alert_policy resource. * @returns {string} A string representing the alert_policy. */ - matchAlertPolicyFromOrganizationAlertPolicyName(organizationAlertPolicyName: string) { - return this.pathTemplates.organizationAlertPolicyPathTemplate.match(organizationAlertPolicyName).alert_policy; + matchAlertPolicyFromOrganizationAlertPolicyName( + organizationAlertPolicyName: string, + ) { + return this.pathTemplates.organizationAlertPolicyPathTemplate.match( + organizationAlertPolicyName, + ).alert_policy; } /** @@ -1456,12 +1745,18 @@ export class AlertPolicyServiceClient { * @param {string} condition * @returns {string} Resource name string. */ - organizationAlertPolicyConditionPath(organization:string,alertPolicy:string,condition:string) { - return this.pathTemplates.organizationAlertPolicyConditionPathTemplate.render({ - organization: organization, - alert_policy: alertPolicy, - condition: condition, - }); + organizationAlertPolicyConditionPath( + organization: string, + alertPolicy: string, + condition: string, + ) { + return this.pathTemplates.organizationAlertPolicyConditionPathTemplate.render( + { + organization: organization, + alert_policy: alertPolicy, + condition: condition, + }, + ); } /** @@ -1471,8 +1766,12 @@ export class AlertPolicyServiceClient { * A fully-qualified path representing organization_alert_policy_condition resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationAlertPolicyConditionName(organizationAlertPolicyConditionName: string) { - return this.pathTemplates.organizationAlertPolicyConditionPathTemplate.match(organizationAlertPolicyConditionName).organization; + matchOrganizationFromOrganizationAlertPolicyConditionName( + organizationAlertPolicyConditionName: string, + ) { + return this.pathTemplates.organizationAlertPolicyConditionPathTemplate.match( + organizationAlertPolicyConditionName, + ).organization; } /** @@ -1482,8 +1781,12 @@ export class AlertPolicyServiceClient { * A fully-qualified path representing organization_alert_policy_condition resource. * @returns {string} A string representing the alert_policy. */ - matchAlertPolicyFromOrganizationAlertPolicyConditionName(organizationAlertPolicyConditionName: string) { - return this.pathTemplates.organizationAlertPolicyConditionPathTemplate.match(organizationAlertPolicyConditionName).alert_policy; + matchAlertPolicyFromOrganizationAlertPolicyConditionName( + organizationAlertPolicyConditionName: string, + ) { + return this.pathTemplates.organizationAlertPolicyConditionPathTemplate.match( + organizationAlertPolicyConditionName, + ).alert_policy; } /** @@ -1493,8 +1796,12 @@ export class AlertPolicyServiceClient { * A fully-qualified path representing organization_alert_policy_condition resource. * @returns {string} A string representing the condition. */ - matchConditionFromOrganizationAlertPolicyConditionName(organizationAlertPolicyConditionName: string) { - return this.pathTemplates.organizationAlertPolicyConditionPathTemplate.match(organizationAlertPolicyConditionName).condition; + matchConditionFromOrganizationAlertPolicyConditionName( + organizationAlertPolicyConditionName: string, + ) { + return this.pathTemplates.organizationAlertPolicyConditionPathTemplate.match( + organizationAlertPolicyConditionName, + ).condition; } /** @@ -1504,7 +1811,10 @@ export class AlertPolicyServiceClient { * @param {string} channel_descriptor * @returns {string} Resource name string. */ - organizationChannelDescriptorPath(organization:string,channelDescriptor:string) { + organizationChannelDescriptorPath( + organization: string, + channelDescriptor: string, + ) { return this.pathTemplates.organizationChannelDescriptorPathTemplate.render({ organization: organization, channel_descriptor: channelDescriptor, @@ -1518,8 +1828,12 @@ export class AlertPolicyServiceClient { * A fully-qualified path representing organization_channel_descriptor resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationChannelDescriptorName(organizationChannelDescriptorName: string) { - return this.pathTemplates.organizationChannelDescriptorPathTemplate.match(organizationChannelDescriptorName).organization; + matchOrganizationFromOrganizationChannelDescriptorName( + organizationChannelDescriptorName: string, + ) { + return this.pathTemplates.organizationChannelDescriptorPathTemplate.match( + organizationChannelDescriptorName, + ).organization; } /** @@ -1529,8 +1843,12 @@ export class AlertPolicyServiceClient { * A fully-qualified path representing organization_channel_descriptor resource. * @returns {string} A string representing the channel_descriptor. */ - matchChannelDescriptorFromOrganizationChannelDescriptorName(organizationChannelDescriptorName: string) { - return this.pathTemplates.organizationChannelDescriptorPathTemplate.match(organizationChannelDescriptorName).channel_descriptor; + matchChannelDescriptorFromOrganizationChannelDescriptorName( + organizationChannelDescriptorName: string, + ) { + return this.pathTemplates.organizationChannelDescriptorPathTemplate.match( + organizationChannelDescriptorName, + ).channel_descriptor; } /** @@ -1540,7 +1858,7 @@ export class AlertPolicyServiceClient { * @param {string} group * @returns {string} Resource name string. */ - organizationGroupPath(organization:string,group:string) { + organizationGroupPath(organization: string, group: string) { return this.pathTemplates.organizationGroupPathTemplate.render({ organization: organization, group: group, @@ -1555,7 +1873,9 @@ export class AlertPolicyServiceClient { * @returns {string} A string representing the organization. */ matchOrganizationFromOrganizationGroupName(organizationGroupName: string) { - return this.pathTemplates.organizationGroupPathTemplate.match(organizationGroupName).organization; + return this.pathTemplates.organizationGroupPathTemplate.match( + organizationGroupName, + ).organization; } /** @@ -1566,7 +1886,9 @@ export class AlertPolicyServiceClient { * @returns {string} A string representing the group. */ matchGroupFromOrganizationGroupName(organizationGroupName: string) { - return this.pathTemplates.organizationGroupPathTemplate.match(organizationGroupName).group; + return this.pathTemplates.organizationGroupPathTemplate.match( + organizationGroupName, + ).group; } /** @@ -1576,11 +1898,16 @@ export class AlertPolicyServiceClient { * @param {string} notification_channel * @returns {string} Resource name string. */ - organizationNotificationChannelPath(organization:string,notificationChannel:string) { - return this.pathTemplates.organizationNotificationChannelPathTemplate.render({ - organization: organization, - notification_channel: notificationChannel, - }); + organizationNotificationChannelPath( + organization: string, + notificationChannel: string, + ) { + return this.pathTemplates.organizationNotificationChannelPathTemplate.render( + { + organization: organization, + notification_channel: notificationChannel, + }, + ); } /** @@ -1590,8 +1917,12 @@ export class AlertPolicyServiceClient { * A fully-qualified path representing organization_notification_channel resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationNotificationChannelName(organizationNotificationChannelName: string) { - return this.pathTemplates.organizationNotificationChannelPathTemplate.match(organizationNotificationChannelName).organization; + matchOrganizationFromOrganizationNotificationChannelName( + organizationNotificationChannelName: string, + ) { + return this.pathTemplates.organizationNotificationChannelPathTemplate.match( + organizationNotificationChannelName, + ).organization; } /** @@ -1601,8 +1932,12 @@ export class AlertPolicyServiceClient { * A fully-qualified path representing organization_notification_channel resource. * @returns {string} A string representing the notification_channel. */ - matchNotificationChannelFromOrganizationNotificationChannelName(organizationNotificationChannelName: string) { - return this.pathTemplates.organizationNotificationChannelPathTemplate.match(organizationNotificationChannelName).notification_channel; + matchNotificationChannelFromOrganizationNotificationChannelName( + organizationNotificationChannelName: string, + ) { + return this.pathTemplates.organizationNotificationChannelPathTemplate.match( + organizationNotificationChannelName, + ).notification_channel; } /** @@ -1612,7 +1947,7 @@ export class AlertPolicyServiceClient { * @param {string} service * @returns {string} Resource name string. */ - organizationServicePath(organization:string,service:string) { + organizationServicePath(organization: string, service: string) { return this.pathTemplates.organizationServicePathTemplate.render({ organization: organization, service: service, @@ -1626,8 +1961,12 @@ export class AlertPolicyServiceClient { * A fully-qualified path representing organization_service resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationServiceName(organizationServiceName: string) { - return this.pathTemplates.organizationServicePathTemplate.match(organizationServiceName).organization; + matchOrganizationFromOrganizationServiceName( + organizationServiceName: string, + ) { + return this.pathTemplates.organizationServicePathTemplate.match( + organizationServiceName, + ).organization; } /** @@ -1638,7 +1977,9 @@ export class AlertPolicyServiceClient { * @returns {string} A string representing the service. */ matchServiceFromOrganizationServiceName(organizationServiceName: string) { - return this.pathTemplates.organizationServicePathTemplate.match(organizationServiceName).service; + return this.pathTemplates.organizationServicePathTemplate.match( + organizationServiceName, + ).service; } /** @@ -1649,12 +1990,18 @@ export class AlertPolicyServiceClient { * @param {string} service_level_objective * @returns {string} Resource name string. */ - organizationServiceServiceLevelObjectivePath(organization:string,service:string,serviceLevelObjective:string) { - return this.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.render({ - organization: organization, - service: service, - service_level_objective: serviceLevelObjective, - }); + organizationServiceServiceLevelObjectivePath( + organization: string, + service: string, + serviceLevelObjective: string, + ) { + return this.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.render( + { + organization: organization, + service: service, + service_level_objective: serviceLevelObjective, + }, + ); } /** @@ -1664,8 +2011,12 @@ export class AlertPolicyServiceClient { * A fully-qualified path representing organization_service_service_level_objective resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationServiceServiceLevelObjectiveName(organizationServiceServiceLevelObjectiveName: string) { - return this.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match(organizationServiceServiceLevelObjectiveName).organization; + matchOrganizationFromOrganizationServiceServiceLevelObjectiveName( + organizationServiceServiceLevelObjectiveName: string, + ) { + return this.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match( + organizationServiceServiceLevelObjectiveName, + ).organization; } /** @@ -1675,8 +2026,12 @@ export class AlertPolicyServiceClient { * A fully-qualified path representing organization_service_service_level_objective resource. * @returns {string} A string representing the service. */ - matchServiceFromOrganizationServiceServiceLevelObjectiveName(organizationServiceServiceLevelObjectiveName: string) { - return this.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match(organizationServiceServiceLevelObjectiveName).service; + matchServiceFromOrganizationServiceServiceLevelObjectiveName( + organizationServiceServiceLevelObjectiveName: string, + ) { + return this.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match( + organizationServiceServiceLevelObjectiveName, + ).service; } /** @@ -1686,8 +2041,12 @@ export class AlertPolicyServiceClient { * A fully-qualified path representing organization_service_service_level_objective resource. * @returns {string} A string representing the service_level_objective. */ - matchServiceLevelObjectiveFromOrganizationServiceServiceLevelObjectiveName(organizationServiceServiceLevelObjectiveName: string) { - return this.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match(organizationServiceServiceLevelObjectiveName).service_level_objective; + matchServiceLevelObjectiveFromOrganizationServiceServiceLevelObjectiveName( + organizationServiceServiceLevelObjectiveName: string, + ) { + return this.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match( + organizationServiceServiceLevelObjectiveName, + ).service_level_objective; } /** @@ -1697,7 +2056,10 @@ export class AlertPolicyServiceClient { * @param {string} uptime_check_config * @returns {string} Resource name string. */ - organizationUptimeCheckConfigPath(organization:string,uptimeCheckConfig:string) { + organizationUptimeCheckConfigPath( + organization: string, + uptimeCheckConfig: string, + ) { return this.pathTemplates.organizationUptimeCheckConfigPathTemplate.render({ organization: organization, uptime_check_config: uptimeCheckConfig, @@ -1711,8 +2073,12 @@ export class AlertPolicyServiceClient { * A fully-qualified path representing organization_uptime_check_config resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationUptimeCheckConfigName(organizationUptimeCheckConfigName: string) { - return this.pathTemplates.organizationUptimeCheckConfigPathTemplate.match(organizationUptimeCheckConfigName).organization; + matchOrganizationFromOrganizationUptimeCheckConfigName( + organizationUptimeCheckConfigName: string, + ) { + return this.pathTemplates.organizationUptimeCheckConfigPathTemplate.match( + organizationUptimeCheckConfigName, + ).organization; } /** @@ -1722,8 +2088,12 @@ export class AlertPolicyServiceClient { * A fully-qualified path representing organization_uptime_check_config resource. * @returns {string} A string representing the uptime_check_config. */ - matchUptimeCheckConfigFromOrganizationUptimeCheckConfigName(organizationUptimeCheckConfigName: string) { - return this.pathTemplates.organizationUptimeCheckConfigPathTemplate.match(organizationUptimeCheckConfigName).uptime_check_config; + matchUptimeCheckConfigFromOrganizationUptimeCheckConfigName( + organizationUptimeCheckConfigName: string, + ) { + return this.pathTemplates.organizationUptimeCheckConfigPathTemplate.match( + organizationUptimeCheckConfigName, + ).uptime_check_config; } /** @@ -1733,7 +2103,7 @@ export class AlertPolicyServiceClient { * @param {string} alert_policy * @returns {string} Resource name string. */ - projectAlertPolicyPath(project:string,alertPolicy:string) { + projectAlertPolicyPath(project: string, alertPolicy: string) { return this.pathTemplates.projectAlertPolicyPathTemplate.render({ project: project, alert_policy: alertPolicy, @@ -1748,7 +2118,9 @@ export class AlertPolicyServiceClient { * @returns {string} A string representing the project. */ matchProjectFromProjectAlertPolicyName(projectAlertPolicyName: string) { - return this.pathTemplates.projectAlertPolicyPathTemplate.match(projectAlertPolicyName).project; + return this.pathTemplates.projectAlertPolicyPathTemplate.match( + projectAlertPolicyName, + ).project; } /** @@ -1759,7 +2131,9 @@ export class AlertPolicyServiceClient { * @returns {string} A string representing the alert_policy. */ matchAlertPolicyFromProjectAlertPolicyName(projectAlertPolicyName: string) { - return this.pathTemplates.projectAlertPolicyPathTemplate.match(projectAlertPolicyName).alert_policy; + return this.pathTemplates.projectAlertPolicyPathTemplate.match( + projectAlertPolicyName, + ).alert_policy; } /** @@ -1770,7 +2144,11 @@ export class AlertPolicyServiceClient { * @param {string} condition * @returns {string} Resource name string. */ - projectAlertPolicyConditionPath(project:string,alertPolicy:string,condition:string) { + projectAlertPolicyConditionPath( + project: string, + alertPolicy: string, + condition: string, + ) { return this.pathTemplates.projectAlertPolicyConditionPathTemplate.render({ project: project, alert_policy: alertPolicy, @@ -1785,8 +2163,12 @@ export class AlertPolicyServiceClient { * A fully-qualified path representing project_alert_policy_condition resource. * @returns {string} A string representing the project. */ - matchProjectFromProjectAlertPolicyConditionName(projectAlertPolicyConditionName: string) { - return this.pathTemplates.projectAlertPolicyConditionPathTemplate.match(projectAlertPolicyConditionName).project; + matchProjectFromProjectAlertPolicyConditionName( + projectAlertPolicyConditionName: string, + ) { + return this.pathTemplates.projectAlertPolicyConditionPathTemplate.match( + projectAlertPolicyConditionName, + ).project; } /** @@ -1796,8 +2178,12 @@ export class AlertPolicyServiceClient { * A fully-qualified path representing project_alert_policy_condition resource. * @returns {string} A string representing the alert_policy. */ - matchAlertPolicyFromProjectAlertPolicyConditionName(projectAlertPolicyConditionName: string) { - return this.pathTemplates.projectAlertPolicyConditionPathTemplate.match(projectAlertPolicyConditionName).alert_policy; + matchAlertPolicyFromProjectAlertPolicyConditionName( + projectAlertPolicyConditionName: string, + ) { + return this.pathTemplates.projectAlertPolicyConditionPathTemplate.match( + projectAlertPolicyConditionName, + ).alert_policy; } /** @@ -1807,8 +2193,12 @@ export class AlertPolicyServiceClient { * A fully-qualified path representing project_alert_policy_condition resource. * @returns {string} A string representing the condition. */ - matchConditionFromProjectAlertPolicyConditionName(projectAlertPolicyConditionName: string) { - return this.pathTemplates.projectAlertPolicyConditionPathTemplate.match(projectAlertPolicyConditionName).condition; + matchConditionFromProjectAlertPolicyConditionName( + projectAlertPolicyConditionName: string, + ) { + return this.pathTemplates.projectAlertPolicyConditionPathTemplate.match( + projectAlertPolicyConditionName, + ).condition; } /** @@ -1818,7 +2208,7 @@ export class AlertPolicyServiceClient { * @param {string} channel_descriptor * @returns {string} Resource name string. */ - projectChannelDescriptorPath(project:string,channelDescriptor:string) { + projectChannelDescriptorPath(project: string, channelDescriptor: string) { return this.pathTemplates.projectChannelDescriptorPathTemplate.render({ project: project, channel_descriptor: channelDescriptor, @@ -1832,8 +2222,12 @@ export class AlertPolicyServiceClient { * A fully-qualified path representing project_channel_descriptor resource. * @returns {string} A string representing the project. */ - matchProjectFromProjectChannelDescriptorName(projectChannelDescriptorName: string) { - return this.pathTemplates.projectChannelDescriptorPathTemplate.match(projectChannelDescriptorName).project; + matchProjectFromProjectChannelDescriptorName( + projectChannelDescriptorName: string, + ) { + return this.pathTemplates.projectChannelDescriptorPathTemplate.match( + projectChannelDescriptorName, + ).project; } /** @@ -1843,8 +2237,12 @@ export class AlertPolicyServiceClient { * A fully-qualified path representing project_channel_descriptor resource. * @returns {string} A string representing the channel_descriptor. */ - matchChannelDescriptorFromProjectChannelDescriptorName(projectChannelDescriptorName: string) { - return this.pathTemplates.projectChannelDescriptorPathTemplate.match(projectChannelDescriptorName).channel_descriptor; + matchChannelDescriptorFromProjectChannelDescriptorName( + projectChannelDescriptorName: string, + ) { + return this.pathTemplates.projectChannelDescriptorPathTemplate.match( + projectChannelDescriptorName, + ).channel_descriptor; } /** @@ -1854,7 +2252,7 @@ export class AlertPolicyServiceClient { * @param {string} group * @returns {string} Resource name string. */ - projectGroupPath(project:string,group:string) { + projectGroupPath(project: string, group: string) { return this.pathTemplates.projectGroupPathTemplate.render({ project: project, group: group, @@ -1869,7 +2267,8 @@ export class AlertPolicyServiceClient { * @returns {string} A string representing the project. */ matchProjectFromProjectGroupName(projectGroupName: string) { - return this.pathTemplates.projectGroupPathTemplate.match(projectGroupName).project; + return this.pathTemplates.projectGroupPathTemplate.match(projectGroupName) + .project; } /** @@ -1880,7 +2279,8 @@ export class AlertPolicyServiceClient { * @returns {string} A string representing the group. */ matchGroupFromProjectGroupName(projectGroupName: string) { - return this.pathTemplates.projectGroupPathTemplate.match(projectGroupName).group; + return this.pathTemplates.projectGroupPathTemplate.match(projectGroupName) + .group; } /** @@ -1890,7 +2290,7 @@ export class AlertPolicyServiceClient { * @param {string} notification_channel * @returns {string} Resource name string. */ - projectNotificationChannelPath(project:string,notificationChannel:string) { + projectNotificationChannelPath(project: string, notificationChannel: string) { return this.pathTemplates.projectNotificationChannelPathTemplate.render({ project: project, notification_channel: notificationChannel, @@ -1904,8 +2304,12 @@ export class AlertPolicyServiceClient { * A fully-qualified path representing project_notification_channel resource. * @returns {string} A string representing the project. */ - matchProjectFromProjectNotificationChannelName(projectNotificationChannelName: string) { - return this.pathTemplates.projectNotificationChannelPathTemplate.match(projectNotificationChannelName).project; + matchProjectFromProjectNotificationChannelName( + projectNotificationChannelName: string, + ) { + return this.pathTemplates.projectNotificationChannelPathTemplate.match( + projectNotificationChannelName, + ).project; } /** @@ -1915,8 +2319,12 @@ export class AlertPolicyServiceClient { * A fully-qualified path representing project_notification_channel resource. * @returns {string} A string representing the notification_channel. */ - matchNotificationChannelFromProjectNotificationChannelName(projectNotificationChannelName: string) { - return this.pathTemplates.projectNotificationChannelPathTemplate.match(projectNotificationChannelName).notification_channel; + matchNotificationChannelFromProjectNotificationChannelName( + projectNotificationChannelName: string, + ) { + return this.pathTemplates.projectNotificationChannelPathTemplate.match( + projectNotificationChannelName, + ).notification_channel; } /** @@ -1926,7 +2334,7 @@ export class AlertPolicyServiceClient { * @param {string} service * @returns {string} Resource name string. */ - projectServicePath(project:string,service:string) { + projectServicePath(project: string, service: string) { return this.pathTemplates.projectServicePathTemplate.render({ project: project, service: service, @@ -1941,7 +2349,9 @@ export class AlertPolicyServiceClient { * @returns {string} A string representing the project. */ matchProjectFromProjectServiceName(projectServiceName: string) { - return this.pathTemplates.projectServicePathTemplate.match(projectServiceName).project; + return this.pathTemplates.projectServicePathTemplate.match( + projectServiceName, + ).project; } /** @@ -1952,7 +2362,9 @@ export class AlertPolicyServiceClient { * @returns {string} A string representing the service. */ matchServiceFromProjectServiceName(projectServiceName: string) { - return this.pathTemplates.projectServicePathTemplate.match(projectServiceName).service; + return this.pathTemplates.projectServicePathTemplate.match( + projectServiceName, + ).service; } /** @@ -1963,12 +2375,18 @@ export class AlertPolicyServiceClient { * @param {string} service_level_objective * @returns {string} Resource name string. */ - projectServiceServiceLevelObjectivePath(project:string,service:string,serviceLevelObjective:string) { - return this.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.render({ - project: project, - service: service, - service_level_objective: serviceLevelObjective, - }); + projectServiceServiceLevelObjectivePath( + project: string, + service: string, + serviceLevelObjective: string, + ) { + return this.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.render( + { + project: project, + service: service, + service_level_objective: serviceLevelObjective, + }, + ); } /** @@ -1978,8 +2396,12 @@ export class AlertPolicyServiceClient { * A fully-qualified path representing project_service_service_level_objective resource. * @returns {string} A string representing the project. */ - matchProjectFromProjectServiceServiceLevelObjectiveName(projectServiceServiceLevelObjectiveName: string) { - return this.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match(projectServiceServiceLevelObjectiveName).project; + matchProjectFromProjectServiceServiceLevelObjectiveName( + projectServiceServiceLevelObjectiveName: string, + ) { + return this.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match( + projectServiceServiceLevelObjectiveName, + ).project; } /** @@ -1989,8 +2411,12 @@ export class AlertPolicyServiceClient { * A fully-qualified path representing project_service_service_level_objective resource. * @returns {string} A string representing the service. */ - matchServiceFromProjectServiceServiceLevelObjectiveName(projectServiceServiceLevelObjectiveName: string) { - return this.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match(projectServiceServiceLevelObjectiveName).service; + matchServiceFromProjectServiceServiceLevelObjectiveName( + projectServiceServiceLevelObjectiveName: string, + ) { + return this.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match( + projectServiceServiceLevelObjectiveName, + ).service; } /** @@ -2000,8 +2426,12 @@ export class AlertPolicyServiceClient { * A fully-qualified path representing project_service_service_level_objective resource. * @returns {string} A string representing the service_level_objective. */ - matchServiceLevelObjectiveFromProjectServiceServiceLevelObjectiveName(projectServiceServiceLevelObjectiveName: string) { - return this.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match(projectServiceServiceLevelObjectiveName).service_level_objective; + matchServiceLevelObjectiveFromProjectServiceServiceLevelObjectiveName( + projectServiceServiceLevelObjectiveName: string, + ) { + return this.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match( + projectServiceServiceLevelObjectiveName, + ).service_level_objective; } /** @@ -2011,7 +2441,7 @@ export class AlertPolicyServiceClient { * @param {string} uptime_check_config * @returns {string} Resource name string. */ - projectUptimeCheckConfigPath(project:string,uptimeCheckConfig:string) { + projectUptimeCheckConfigPath(project: string, uptimeCheckConfig: string) { return this.pathTemplates.projectUptimeCheckConfigPathTemplate.render({ project: project, uptime_check_config: uptimeCheckConfig, @@ -2025,8 +2455,12 @@ export class AlertPolicyServiceClient { * A fully-qualified path representing project_uptime_check_config resource. * @returns {string} A string representing the project. */ - matchProjectFromProjectUptimeCheckConfigName(projectUptimeCheckConfigName: string) { - return this.pathTemplates.projectUptimeCheckConfigPathTemplate.match(projectUptimeCheckConfigName).project; + matchProjectFromProjectUptimeCheckConfigName( + projectUptimeCheckConfigName: string, + ) { + return this.pathTemplates.projectUptimeCheckConfigPathTemplate.match( + projectUptimeCheckConfigName, + ).project; } /** @@ -2036,8 +2470,12 @@ export class AlertPolicyServiceClient { * A fully-qualified path representing project_uptime_check_config resource. * @returns {string} A string representing the uptime_check_config. */ - matchUptimeCheckConfigFromProjectUptimeCheckConfigName(projectUptimeCheckConfigName: string) { - return this.pathTemplates.projectUptimeCheckConfigPathTemplate.match(projectUptimeCheckConfigName).uptime_check_config; + matchUptimeCheckConfigFromProjectUptimeCheckConfigName( + projectUptimeCheckConfigName: string, + ) { + return this.pathTemplates.projectUptimeCheckConfigPathTemplate.match( + projectUptimeCheckConfigName, + ).uptime_check_config; } /** @@ -2048,7 +2486,7 @@ export class AlertPolicyServiceClient { */ close(): Promise { if (this.alertPolicyServiceStub && !this._terminated) { - return this.alertPolicyServiceStub.then(stub => { + return this.alertPolicyServiceStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -2056,4 +2494,4 @@ export class AlertPolicyServiceClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/core/generator/gapic-generator-typescript/baselines/monitoring/src/v3/group_service_client.ts.baseline b/core/generator/gapic-generator-typescript/baselines/monitoring/src/v3/group_service_client.ts.baseline index 0d118b5941c2..6dcc069ed8d3 100644 --- a/core/generator/gapic-generator-typescript/baselines/monitoring/src/v3/group_service_client.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/monitoring/src/v3/group_service_client.ts.baseline @@ -18,11 +18,18 @@ /* global window */ import type * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions, PaginationCallback, GaxCall} from 'google-gax'; -import {Transform} from 'stream'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + PaginationCallback, + GaxCall, +} from 'google-gax'; +import { Transform } from 'stream'; import * as protos from '../../protos/protos'; import jsonProtos = require('../../protos/protos.json'); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; /** * Client JSON configuration object, loaded from @@ -55,7 +62,7 @@ export class GroupServiceClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('monitoring'); @@ -68,9 +75,9 @@ export class GroupServiceClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; - groupServiceStub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; + groupServiceStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of GroupServiceClient. @@ -111,21 +118,42 @@ export class GroupServiceClient { * const client = new GroupServiceClient({fallback: true}, gax); * ``` */ - constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { // Ensure that options include all the required fields. const staticMembers = this.constructor as typeof GroupServiceClient; - if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { - throw new Error('Please set either universe_domain or universeDomain, but not both.'); + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); } - const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; - this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; this._servicePath = 'monitoring.' + this._universeDomain; - const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; - const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. if (servicePath !== this._servicePath && !('scopes' in opts)) { @@ -147,7 +175,7 @@ export class GroupServiceClient { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; @@ -161,10 +189,7 @@ export class GroupServiceClient { } // Determine the client header string. - const clientHeader = [ - `gax/${this._gaxModule.version}`, - `gapic/${version}`, - ]; + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/${process.versions.node}`); } else { @@ -186,76 +211,83 @@ export class GroupServiceClient { // Create useful helper objects for these. this.pathTemplates = { folderAlertPolicyPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/alertPolicies/{alert_policy}' + 'folders/{folder}/alertPolicies/{alert_policy}', ), folderAlertPolicyConditionPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/alertPolicies/{alert_policy}/conditions/{condition}' + 'folders/{folder}/alertPolicies/{alert_policy}/conditions/{condition}', ), folderChannelDescriptorPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/notificationChannelDescriptors/{channel_descriptor}' + 'folders/{folder}/notificationChannelDescriptors/{channel_descriptor}', ), folderGroupPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/groups/{group}' + 'folders/{folder}/groups/{group}', ), folderNotificationChannelPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/notificationChannels/{notification_channel}' + 'folders/{folder}/notificationChannels/{notification_channel}', ), folderServicePathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/services/{service}' - ), - folderServiceServiceLevelObjectivePathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/services/{service}/serviceLevelObjectives/{service_level_objective}' + 'folders/{folder}/services/{service}', ), + folderServiceServiceLevelObjectivePathTemplate: + new this._gaxModule.PathTemplate( + 'folders/{folder}/services/{service}/serviceLevelObjectives/{service_level_objective}', + ), folderUptimeCheckConfigPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/uptimeCheckConfigs/{uptime_check_config}' + 'folders/{folder}/uptimeCheckConfigs/{uptime_check_config}', ), organizationAlertPolicyPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/alertPolicies/{alert_policy}' - ), - organizationAlertPolicyConditionPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/alertPolicies/{alert_policy}/conditions/{condition}' - ), - organizationChannelDescriptorPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/notificationChannelDescriptors/{channel_descriptor}' + 'organizations/{organization}/alertPolicies/{alert_policy}', ), + organizationAlertPolicyConditionPathTemplate: + new this._gaxModule.PathTemplate( + 'organizations/{organization}/alertPolicies/{alert_policy}/conditions/{condition}', + ), + organizationChannelDescriptorPathTemplate: + new this._gaxModule.PathTemplate( + 'organizations/{organization}/notificationChannelDescriptors/{channel_descriptor}', + ), organizationGroupPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/groups/{group}' - ), - organizationNotificationChannelPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/notificationChannels/{notification_channel}' + 'organizations/{organization}/groups/{group}', ), + organizationNotificationChannelPathTemplate: + new this._gaxModule.PathTemplate( + 'organizations/{organization}/notificationChannels/{notification_channel}', + ), organizationServicePathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/services/{service}' - ), - organizationServiceServiceLevelObjectivePathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/services/{service}/serviceLevelObjectives/{service_level_objective}' - ), - organizationUptimeCheckConfigPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/uptimeCheckConfigs/{uptime_check_config}' + 'organizations/{organization}/services/{service}', ), + organizationServiceServiceLevelObjectivePathTemplate: + new this._gaxModule.PathTemplate( + 'organizations/{organization}/services/{service}/serviceLevelObjectives/{service_level_objective}', + ), + organizationUptimeCheckConfigPathTemplate: + new this._gaxModule.PathTemplate( + 'organizations/{organization}/uptimeCheckConfigs/{uptime_check_config}', + ), projectAlertPolicyPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/alertPolicies/{alert_policy}' + 'projects/{project}/alertPolicies/{alert_policy}', ), projectAlertPolicyConditionPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/alertPolicies/{alert_policy}/conditions/{condition}' + 'projects/{project}/alertPolicies/{alert_policy}/conditions/{condition}', ), projectChannelDescriptorPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/notificationChannelDescriptors/{channel_descriptor}' + 'projects/{project}/notificationChannelDescriptors/{channel_descriptor}', ), projectGroupPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/groups/{group}' + 'projects/{project}/groups/{group}', ), projectNotificationChannelPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/notificationChannels/{notification_channel}' + 'projects/{project}/notificationChannels/{notification_channel}', ), projectServicePathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/services/{service}' - ), - projectServiceServiceLevelObjectivePathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/services/{service}/serviceLevelObjectives/{service_level_objective}' + 'projects/{project}/services/{service}', ), + projectServiceServiceLevelObjectivePathTemplate: + new this._gaxModule.PathTemplate( + 'projects/{project}/services/{service}/serviceLevelObjectives/{service_level_objective}', + ), projectUptimeCheckConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/uptimeCheckConfigs/{uptime_check_config}' + 'projects/{project}/uptimeCheckConfigs/{uptime_check_config}', ), }; @@ -263,16 +295,25 @@ export class GroupServiceClient { // (e.g. 50 results at a time, with tokens to get subsequent // pages). Denote the keys used for pagination and results. this.descriptors.page = { - listGroups: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'group'), - listGroupMembers: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'members') + listGroups: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'group', + ), + listGroupMembers: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'members', + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.monitoring.v3.GroupService', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.monitoring.v3.GroupService', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + { 'x-goog-api-client': clientHeader.join(' ') }, + ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -303,37 +344,47 @@ export class GroupServiceClient { // Put together the "service stub" for // google.monitoring.v3.GroupService. this.groupServiceStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.monitoring.v3.GroupService') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.monitoring.v3.GroupService', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.monitoring.v3.GroupService, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts, + this._providedCustomServicePath, + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const groupServiceStubMethods = - ['listGroups', 'getGroup', 'createGroup', 'updateGroup', 'deleteGroup', 'listGroupMembers']; + const groupServiceStubMethods = [ + 'listGroups', + 'getGroup', + 'createGroup', + 'updateGroup', + 'deleteGroup', + 'listGroupMembers', + ]; for (const methodName of groupServiceStubMethods) { const callPromise = this.groupServiceStub.then( - stub => (...args: Array<{}>) => { - if (this._terminated) { - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error|null|undefined) => () => { + (stub) => + (...args: Array<{}>) => { + if (this._terminated) { + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { throw err; - }); + }, + ); - const descriptor = - this.descriptors.page[methodName] || - undefined; + const descriptor = this.descriptors.page[methodName] || undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -348,8 +399,14 @@ export class GroupServiceClient { * @returns {string} The DNS address for this service. */ static get servicePath() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'monitoring.googleapis.com'; } @@ -360,8 +417,14 @@ export class GroupServiceClient { * @returns {string} The DNS address for this service. */ static get apiEndpoint() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'monitoring.googleapis.com'; } @@ -395,7 +458,7 @@ export class GroupServiceClient { return [ 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/monitoring', - 'https://www.googleapis.com/auth/monitoring.read' + 'https://www.googleapis.com/auth/monitoring.read', ]; } @@ -405,8 +468,9 @@ export class GroupServiceClient { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId(callback?: Callback): - Promise|void { + getProjectId( + callback?: Callback, + ): Promise | void { if (callback) { this.auth.getProjectId(callback); return; @@ -417,498 +481,633 @@ export class GroupServiceClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Gets a single group. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The group to retrieve. The format is - * `"projects/{project_id_or_number}/groups/{group_id}"`. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.monitoring.v3.Group|Group}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v3/group_service.get_group.js - * region_tag:monitoring_v3_generated_GroupService_GetGroup_async - */ + /** + * Gets a single group. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The group to retrieve. The format is + * `"projects/{project_id_or_number}/groups/{group_id}"`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.monitoring.v3.Group|Group}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v3/group_service.get_group.js + * region_tag:monitoring_v3_generated_GroupService_GetGroup_async + */ getGroup( - request?: protos.google.monitoring.v3.IGetGroupRequest, - options?: CallOptions): - Promise<[ - protos.google.monitoring.v3.IGroup, - protos.google.monitoring.v3.IGetGroupRequest|undefined, {}|undefined - ]>; + request?: protos.google.monitoring.v3.IGetGroupRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.monitoring.v3.IGroup, + protos.google.monitoring.v3.IGetGroupRequest | undefined, + {} | undefined, + ] + >; getGroup( - request: protos.google.monitoring.v3.IGetGroupRequest, - options: CallOptions, - callback: Callback< - protos.google.monitoring.v3.IGroup, - protos.google.monitoring.v3.IGetGroupRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.IGetGroupRequest, + options: CallOptions, + callback: Callback< + protos.google.monitoring.v3.IGroup, + protos.google.monitoring.v3.IGetGroupRequest | null | undefined, + {} | null | undefined + >, + ): void; getGroup( - request: protos.google.monitoring.v3.IGetGroupRequest, - callback: Callback< - protos.google.monitoring.v3.IGroup, - protos.google.monitoring.v3.IGetGroupRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.IGetGroupRequest, + callback: Callback< + protos.google.monitoring.v3.IGroup, + protos.google.monitoring.v3.IGetGroupRequest | null | undefined, + {} | null | undefined + >, + ): void; getGroup( - request?: protos.google.monitoring.v3.IGetGroupRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.monitoring.v3.IGroup, - protos.google.monitoring.v3.IGetGroupRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.monitoring.v3.IGetGroupRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.monitoring.v3.IGroup, - protos.google.monitoring.v3.IGetGroupRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.monitoring.v3.IGroup, - protos.google.monitoring.v3.IGetGroupRequest|undefined, {}|undefined - ]>|void { + protos.google.monitoring.v3.IGetGroupRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.monitoring.v3.IGroup, + protos.google.monitoring.v3.IGetGroupRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.monitoring.v3.IGroup, + protos.google.monitoring.v3.IGetGroupRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getGroup request %j', request); - const wrappedCallback: Callback< - protos.google.monitoring.v3.IGroup, - protos.google.monitoring.v3.IGetGroupRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.monitoring.v3.IGroup, + protos.google.monitoring.v3.IGetGroupRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getGroup response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getGroup(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.monitoring.v3.IGroup, - protos.google.monitoring.v3.IGetGroupRequest|undefined, - {}|undefined - ]) => { - this._log.info('getGroup response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getGroup(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.monitoring.v3.IGroup, + protos.google.monitoring.v3.IGetGroupRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getGroup response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Creates a new group. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The project in which to create the group. The format is - * `"projects/{project_id_or_number}"`. - * @param {google.monitoring.v3.Group} request.group - * Required. A group definition. It is an error to define the `name` field because - * the system assigns the name. - * @param {boolean} request.validateOnly - * If true, validate this request but do not create the group. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.monitoring.v3.Group|Group}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v3/group_service.create_group.js - * region_tag:monitoring_v3_generated_GroupService_CreateGroup_async - */ + /** + * Creates a new group. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The project in which to create the group. The format is + * `"projects/{project_id_or_number}"`. + * @param {google.monitoring.v3.Group} request.group + * Required. A group definition. It is an error to define the `name` field because + * the system assigns the name. + * @param {boolean} request.validateOnly + * If true, validate this request but do not create the group. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.monitoring.v3.Group|Group}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v3/group_service.create_group.js + * region_tag:monitoring_v3_generated_GroupService_CreateGroup_async + */ createGroup( - request?: protos.google.monitoring.v3.ICreateGroupRequest, - options?: CallOptions): - Promise<[ - protos.google.monitoring.v3.IGroup, - protos.google.monitoring.v3.ICreateGroupRequest|undefined, {}|undefined - ]>; + request?: protos.google.monitoring.v3.ICreateGroupRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.monitoring.v3.IGroup, + protos.google.monitoring.v3.ICreateGroupRequest | undefined, + {} | undefined, + ] + >; createGroup( - request: protos.google.monitoring.v3.ICreateGroupRequest, - options: CallOptions, - callback: Callback< - protos.google.monitoring.v3.IGroup, - protos.google.monitoring.v3.ICreateGroupRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.ICreateGroupRequest, + options: CallOptions, + callback: Callback< + protos.google.monitoring.v3.IGroup, + protos.google.monitoring.v3.ICreateGroupRequest | null | undefined, + {} | null | undefined + >, + ): void; createGroup( - request: protos.google.monitoring.v3.ICreateGroupRequest, - callback: Callback< - protos.google.monitoring.v3.IGroup, - protos.google.monitoring.v3.ICreateGroupRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.ICreateGroupRequest, + callback: Callback< + protos.google.monitoring.v3.IGroup, + protos.google.monitoring.v3.ICreateGroupRequest | null | undefined, + {} | null | undefined + >, + ): void; createGroup( - request?: protos.google.monitoring.v3.ICreateGroupRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.monitoring.v3.ICreateGroupRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.monitoring.v3.IGroup, - protos.google.monitoring.v3.ICreateGroupRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.monitoring.v3.IGroup, - protos.google.monitoring.v3.ICreateGroupRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.monitoring.v3.IGroup, - protos.google.monitoring.v3.ICreateGroupRequest|undefined, {}|undefined - ]>|void { + protos.google.monitoring.v3.ICreateGroupRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.monitoring.v3.IGroup, + protos.google.monitoring.v3.ICreateGroupRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.monitoring.v3.IGroup, + protos.google.monitoring.v3.ICreateGroupRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('createGroup request %j', request); - const wrappedCallback: Callback< - protos.google.monitoring.v3.IGroup, - protos.google.monitoring.v3.ICreateGroupRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.monitoring.v3.IGroup, + protos.google.monitoring.v3.ICreateGroupRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createGroup response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.createGroup(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.monitoring.v3.IGroup, - protos.google.monitoring.v3.ICreateGroupRequest|undefined, - {}|undefined - ]) => { - this._log.info('createGroup response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createGroup(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.monitoring.v3.IGroup, + protos.google.monitoring.v3.ICreateGroupRequest | undefined, + {} | undefined, + ]) => { + this._log.info('createGroup response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Updates an existing group. - * You can change any group attributes except `name`. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.monitoring.v3.Group} request.group - * Required. The new definition of the group. All fields of the existing group, - * excepting `name`, are replaced with the corresponding fields of this group. - * @param {boolean} request.validateOnly - * If true, validate this request but do not update the existing group. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.monitoring.v3.Group|Group}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v3/group_service.update_group.js - * region_tag:monitoring_v3_generated_GroupService_UpdateGroup_async - */ + /** + * Updates an existing group. + * You can change any group attributes except `name`. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.monitoring.v3.Group} request.group + * Required. The new definition of the group. All fields of the existing group, + * excepting `name`, are replaced with the corresponding fields of this group. + * @param {boolean} request.validateOnly + * If true, validate this request but do not update the existing group. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.monitoring.v3.Group|Group}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v3/group_service.update_group.js + * region_tag:monitoring_v3_generated_GroupService_UpdateGroup_async + */ updateGroup( - request?: protos.google.monitoring.v3.IUpdateGroupRequest, - options?: CallOptions): - Promise<[ - protos.google.monitoring.v3.IGroup, - protos.google.monitoring.v3.IUpdateGroupRequest|undefined, {}|undefined - ]>; + request?: protos.google.monitoring.v3.IUpdateGroupRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.monitoring.v3.IGroup, + protos.google.monitoring.v3.IUpdateGroupRequest | undefined, + {} | undefined, + ] + >; updateGroup( - request: protos.google.monitoring.v3.IUpdateGroupRequest, - options: CallOptions, - callback: Callback< - protos.google.monitoring.v3.IGroup, - protos.google.monitoring.v3.IUpdateGroupRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.IUpdateGroupRequest, + options: CallOptions, + callback: Callback< + protos.google.monitoring.v3.IGroup, + protos.google.monitoring.v3.IUpdateGroupRequest | null | undefined, + {} | null | undefined + >, + ): void; updateGroup( - request: protos.google.monitoring.v3.IUpdateGroupRequest, - callback: Callback< - protos.google.monitoring.v3.IGroup, - protos.google.monitoring.v3.IUpdateGroupRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.IUpdateGroupRequest, + callback: Callback< + protos.google.monitoring.v3.IGroup, + protos.google.monitoring.v3.IUpdateGroupRequest | null | undefined, + {} | null | undefined + >, + ): void; updateGroup( - request?: protos.google.monitoring.v3.IUpdateGroupRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.monitoring.v3.IUpdateGroupRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.monitoring.v3.IGroup, - protos.google.monitoring.v3.IUpdateGroupRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.monitoring.v3.IGroup, - protos.google.monitoring.v3.IUpdateGroupRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.monitoring.v3.IGroup, - protos.google.monitoring.v3.IUpdateGroupRequest|undefined, {}|undefined - ]>|void { + protos.google.monitoring.v3.IUpdateGroupRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.monitoring.v3.IGroup, + protos.google.monitoring.v3.IUpdateGroupRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.monitoring.v3.IGroup, + protos.google.monitoring.v3.IUpdateGroupRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'group.name': request.group!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'group.name': request.group!.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateGroup request %j', request); - const wrappedCallback: Callback< - protos.google.monitoring.v3.IGroup, - protos.google.monitoring.v3.IUpdateGroupRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.monitoring.v3.IGroup, + protos.google.monitoring.v3.IUpdateGroupRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateGroup response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.updateGroup(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.monitoring.v3.IGroup, - protos.google.monitoring.v3.IUpdateGroupRequest|undefined, - {}|undefined - ]) => { - this._log.info('updateGroup response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateGroup(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.monitoring.v3.IGroup, + protos.google.monitoring.v3.IUpdateGroupRequest | undefined, + {} | undefined, + ]) => { + this._log.info('updateGroup response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Deletes an existing group. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The group to delete. The format is - * `"projects/{project_id_or_number}/groups/{group_id}"`. - * @param {boolean} request.recursive - * If this field is true, then the request means to delete a group with all - * its descendants. Otherwise, the request means to delete a group only when - * it has no descendants. The default value is false. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v3/group_service.delete_group.js - * region_tag:monitoring_v3_generated_GroupService_DeleteGroup_async - */ + /** + * Deletes an existing group. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The group to delete. The format is + * `"projects/{project_id_or_number}/groups/{group_id}"`. + * @param {boolean} request.recursive + * If this field is true, then the request means to delete a group with all + * its descendants. Otherwise, the request means to delete a group only when + * it has no descendants. The default value is false. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v3/group_service.delete_group.js + * region_tag:monitoring_v3_generated_GroupService_DeleteGroup_async + */ deleteGroup( - request?: protos.google.monitoring.v3.IDeleteGroupRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.IDeleteGroupRequest|undefined, {}|undefined - ]>; + request?: protos.google.monitoring.v3.IDeleteGroupRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.monitoring.v3.IDeleteGroupRequest | undefined, + {} | undefined, + ] + >; deleteGroup( - request: protos.google.monitoring.v3.IDeleteGroupRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.IDeleteGroupRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.IDeleteGroupRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.monitoring.v3.IDeleteGroupRequest | null | undefined, + {} | null | undefined + >, + ): void; deleteGroup( - request: protos.google.monitoring.v3.IDeleteGroupRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.IDeleteGroupRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.IDeleteGroupRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.monitoring.v3.IDeleteGroupRequest | null | undefined, + {} | null | undefined + >, + ): void; deleteGroup( - request?: protos.google.monitoring.v3.IDeleteGroupRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.IDeleteGroupRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.monitoring.v3.IDeleteGroupRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.IDeleteGroupRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.IDeleteGroupRequest|undefined, {}|undefined - ]>|void { + protos.google.monitoring.v3.IDeleteGroupRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + protos.google.monitoring.v3.IDeleteGroupRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.monitoring.v3.IDeleteGroupRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('deleteGroup request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.IDeleteGroupRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + protos.google.monitoring.v3.IDeleteGroupRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteGroup response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.deleteGroup(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.IDeleteGroupRequest|undefined, - {}|undefined - ]) => { - this._log.info('deleteGroup response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteGroup(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.monitoring.v3.IDeleteGroupRequest | undefined, + {} | undefined, + ]) => { + this._log.info('deleteGroup response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } - /** - * Lists the existing groups. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The project whose groups are to be listed. The format is - * `"projects/{project_id_or_number}"`. - * @param {string} request.childrenOfGroup - * A group name: `"projects/{project_id_or_number}/groups/{group_id}"`. - * Returns groups whose `parentName` field contains the group - * name. If no groups have this parent, the results are empty. - * @param {string} request.ancestorsOfGroup - * A group name: `"projects/{project_id_or_number}/groups/{group_id}"`. - * Returns groups that are ancestors of the specified group. - * The groups are returned in order, starting with the immediate parent and - * ending with the most distant ancestor. If the specified group has no - * immediate parent, the results are empty. - * @param {string} request.descendantsOfGroup - * A group name: `"projects/{project_id_or_number}/groups/{group_id}"`. - * Returns the descendants of the specified group. This is a superset of - * the results returned by the `childrenOfGroup` filter, and includes - * children-of-children, and so forth. - * @param {number} request.pageSize - * A positive number that is the maximum number of results to return. - * @param {string} request.pageToken - * If this field is not empty then it must contain the `nextPageToken` value - * returned by a previous call to this method. Using this field causes the - * method to return additional results from the previous method call. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.monitoring.v3.Group|Group}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `listGroupsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Lists the existing groups. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The project whose groups are to be listed. The format is + * `"projects/{project_id_or_number}"`. + * @param {string} request.childrenOfGroup + * A group name: `"projects/{project_id_or_number}/groups/{group_id}"`. + * Returns groups whose `parentName` field contains the group + * name. If no groups have this parent, the results are empty. + * @param {string} request.ancestorsOfGroup + * A group name: `"projects/{project_id_or_number}/groups/{group_id}"`. + * Returns groups that are ancestors of the specified group. + * The groups are returned in order, starting with the immediate parent and + * ending with the most distant ancestor. If the specified group has no + * immediate parent, the results are empty. + * @param {string} request.descendantsOfGroup + * A group name: `"projects/{project_id_or_number}/groups/{group_id}"`. + * Returns the descendants of the specified group. This is a superset of + * the results returned by the `childrenOfGroup` filter, and includes + * children-of-children, and so forth. + * @param {number} request.pageSize + * A positive number that is the maximum number of results to return. + * @param {string} request.pageToken + * If this field is not empty then it must contain the `nextPageToken` value + * returned by a previous call to this method. Using this field causes the + * method to return additional results from the previous method call. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.monitoring.v3.Group|Group}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listGroupsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listGroups( - request?: protos.google.monitoring.v3.IListGroupsRequest, - options?: CallOptions): - Promise<[ - protos.google.monitoring.v3.IGroup[], - protos.google.monitoring.v3.IListGroupsRequest|null, - protos.google.monitoring.v3.IListGroupsResponse - ]>; + request?: protos.google.monitoring.v3.IListGroupsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.monitoring.v3.IGroup[], + protos.google.monitoring.v3.IListGroupsRequest | null, + protos.google.monitoring.v3.IListGroupsResponse, + ] + >; listGroups( - request: protos.google.monitoring.v3.IListGroupsRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.monitoring.v3.IListGroupsRequest, - protos.google.monitoring.v3.IListGroupsResponse|null|undefined, - protos.google.monitoring.v3.IGroup>): void; + request: protos.google.monitoring.v3.IListGroupsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.monitoring.v3.IListGroupsRequest, + protos.google.monitoring.v3.IListGroupsResponse | null | undefined, + protos.google.monitoring.v3.IGroup + >, + ): void; listGroups( - request: protos.google.monitoring.v3.IListGroupsRequest, - callback: PaginationCallback< - protos.google.monitoring.v3.IListGroupsRequest, - protos.google.monitoring.v3.IListGroupsResponse|null|undefined, - protos.google.monitoring.v3.IGroup>): void; + request: protos.google.monitoring.v3.IListGroupsRequest, + callback: PaginationCallback< + protos.google.monitoring.v3.IListGroupsRequest, + protos.google.monitoring.v3.IListGroupsResponse | null | undefined, + protos.google.monitoring.v3.IGroup + >, + ): void; listGroups( - request?: protos.google.monitoring.v3.IListGroupsRequest, - optionsOrCallback?: CallOptions|PaginationCallback< - protos.google.monitoring.v3.IListGroupsRequest, - protos.google.monitoring.v3.IListGroupsResponse|null|undefined, - protos.google.monitoring.v3.IGroup>, - callback?: PaginationCallback< + request?: protos.google.monitoring.v3.IListGroupsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.monitoring.v3.IListGroupsRequest, - protos.google.monitoring.v3.IListGroupsResponse|null|undefined, - protos.google.monitoring.v3.IGroup>): - Promise<[ - protos.google.monitoring.v3.IGroup[], - protos.google.monitoring.v3.IListGroupsRequest|null, - protos.google.monitoring.v3.IListGroupsResponse - ]>|void { + protos.google.monitoring.v3.IListGroupsResponse | null | undefined, + protos.google.monitoring.v3.IGroup + >, + callback?: PaginationCallback< + protos.google.monitoring.v3.IListGroupsRequest, + protos.google.monitoring.v3.IListGroupsResponse | null | undefined, + protos.google.monitoring.v3.IGroup + >, + ): Promise< + [ + protos.google.monitoring.v3.IGroup[], + protos.google.monitoring.v3.IListGroupsRequest | null, + protos.google.monitoring.v3.IListGroupsResponse, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.monitoring.v3.IListGroupsRequest, - protos.google.monitoring.v3.IListGroupsResponse|null|undefined, - protos.google.monitoring.v3.IGroup>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.monitoring.v3.IListGroupsRequest, + protos.google.monitoring.v3.IListGroupsResponse | null | undefined, + protos.google.monitoring.v3.IGroup + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listGroups values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -917,241 +1116,264 @@ export class GroupServiceClient { this._log.info('listGroups request %j', request); return this.innerApiCalls .listGroups(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.monitoring.v3.IGroup[], - protos.google.monitoring.v3.IListGroupsRequest|null, - protos.google.monitoring.v3.IListGroupsResponse - ]) => { - this._log.info('listGroups values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.monitoring.v3.IGroup[], + protos.google.monitoring.v3.IListGroupsRequest | null, + protos.google.monitoring.v3.IListGroupsResponse, + ]) => { + this._log.info('listGroups values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listGroups`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The project whose groups are to be listed. The format is - * `"projects/{project_id_or_number}"`. - * @param {string} request.childrenOfGroup - * A group name: `"projects/{project_id_or_number}/groups/{group_id}"`. - * Returns groups whose `parentName` field contains the group - * name. If no groups have this parent, the results are empty. - * @param {string} request.ancestorsOfGroup - * A group name: `"projects/{project_id_or_number}/groups/{group_id}"`. - * Returns groups that are ancestors of the specified group. - * The groups are returned in order, starting with the immediate parent and - * ending with the most distant ancestor. If the specified group has no - * immediate parent, the results are empty. - * @param {string} request.descendantsOfGroup - * A group name: `"projects/{project_id_or_number}/groups/{group_id}"`. - * Returns the descendants of the specified group. This is a superset of - * the results returned by the `childrenOfGroup` filter, and includes - * children-of-children, and so forth. - * @param {number} request.pageSize - * A positive number that is the maximum number of results to return. - * @param {string} request.pageToken - * If this field is not empty then it must contain the `nextPageToken` value - * returned by a previous call to this method. Using this field causes the - * method to return additional results from the previous method call. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.monitoring.v3.Group|Group} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `listGroupsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `listGroups`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The project whose groups are to be listed. The format is + * `"projects/{project_id_or_number}"`. + * @param {string} request.childrenOfGroup + * A group name: `"projects/{project_id_or_number}/groups/{group_id}"`. + * Returns groups whose `parentName` field contains the group + * name. If no groups have this parent, the results are empty. + * @param {string} request.ancestorsOfGroup + * A group name: `"projects/{project_id_or_number}/groups/{group_id}"`. + * Returns groups that are ancestors of the specified group. + * The groups are returned in order, starting with the immediate parent and + * ending with the most distant ancestor. If the specified group has no + * immediate parent, the results are empty. + * @param {string} request.descendantsOfGroup + * A group name: `"projects/{project_id_or_number}/groups/{group_id}"`. + * Returns the descendants of the specified group. This is a superset of + * the results returned by the `childrenOfGroup` filter, and includes + * children-of-children, and so forth. + * @param {number} request.pageSize + * A positive number that is the maximum number of results to return. + * @param {string} request.pageToken + * If this field is not empty then it must contain the `nextPageToken` value + * returned by a previous call to this method. Using this field causes the + * method to return additional results from the previous method call. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.monitoring.v3.Group|Group} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listGroupsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listGroupsStream( - request?: protos.google.monitoring.v3.IListGroupsRequest, - options?: CallOptions): - Transform{ + request?: protos.google.monitoring.v3.IListGroupsRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); const defaultCallSettings = this._defaults['listGroups']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listGroups stream %j', request); return this.descriptors.page.listGroups.createStream( this.innerApiCalls.listGroups as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listGroups`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The project whose groups are to be listed. The format is - * `"projects/{project_id_or_number}"`. - * @param {string} request.childrenOfGroup - * A group name: `"projects/{project_id_or_number}/groups/{group_id}"`. - * Returns groups whose `parentName` field contains the group - * name. If no groups have this parent, the results are empty. - * @param {string} request.ancestorsOfGroup - * A group name: `"projects/{project_id_or_number}/groups/{group_id}"`. - * Returns groups that are ancestors of the specified group. - * The groups are returned in order, starting with the immediate parent and - * ending with the most distant ancestor. If the specified group has no - * immediate parent, the results are empty. - * @param {string} request.descendantsOfGroup - * A group name: `"projects/{project_id_or_number}/groups/{group_id}"`. - * Returns the descendants of the specified group. This is a superset of - * the results returned by the `childrenOfGroup` filter, and includes - * children-of-children, and so forth. - * @param {number} request.pageSize - * A positive number that is the maximum number of results to return. - * @param {string} request.pageToken - * If this field is not empty then it must contain the `nextPageToken` value - * returned by a previous call to this method. Using this field causes the - * method to return additional results from the previous method call. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.monitoring.v3.Group|Group}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v3/group_service.list_groups.js - * region_tag:monitoring_v3_generated_GroupService_ListGroups_async - */ + /** + * Equivalent to `listGroups`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The project whose groups are to be listed. The format is + * `"projects/{project_id_or_number}"`. + * @param {string} request.childrenOfGroup + * A group name: `"projects/{project_id_or_number}/groups/{group_id}"`. + * Returns groups whose `parentName` field contains the group + * name. If no groups have this parent, the results are empty. + * @param {string} request.ancestorsOfGroup + * A group name: `"projects/{project_id_or_number}/groups/{group_id}"`. + * Returns groups that are ancestors of the specified group. + * The groups are returned in order, starting with the immediate parent and + * ending with the most distant ancestor. If the specified group has no + * immediate parent, the results are empty. + * @param {string} request.descendantsOfGroup + * A group name: `"projects/{project_id_or_number}/groups/{group_id}"`. + * Returns the descendants of the specified group. This is a superset of + * the results returned by the `childrenOfGroup` filter, and includes + * children-of-children, and so forth. + * @param {number} request.pageSize + * A positive number that is the maximum number of results to return. + * @param {string} request.pageToken + * If this field is not empty then it must contain the `nextPageToken` value + * returned by a previous call to this method. Using this field causes the + * method to return additional results from the previous method call. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.monitoring.v3.Group|Group}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v3/group_service.list_groups.js + * region_tag:monitoring_v3_generated_GroupService_ListGroups_async + */ listGroupsAsync( - request?: protos.google.monitoring.v3.IListGroupsRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.monitoring.v3.IListGroupsRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); const defaultCallSettings = this._defaults['listGroups']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listGroups iterate %j', request); return this.descriptors.page.listGroups.asyncIterate( this.innerApiCalls['listGroups'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } - /** - * Lists the monitored resources that are members of a group. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The group whose members are listed. The format is - * `"projects/{project_id_or_number}/groups/{group_id}"`. - * @param {number} request.pageSize - * A positive number that is the maximum number of results to return. - * @param {string} request.pageToken - * If this field is not empty then it must contain the `nextPageToken` value - * returned by a previous call to this method. Using this field causes the - * method to return additional results from the previous method call. - * @param {string} request.filter - * An optional [list filter](/monitoring/api/learn_more#filtering) describing - * the members to be returned. The filter may reference the type, labels, and - * metadata of monitored resources that comprise the group. - * For example, to return only resources representing Compute Engine VM - * instances, use this filter: - * - * resource.type = "gce_instance" - * @param {google.monitoring.v3.TimeInterval} request.interval - * An optional time interval for which results should be returned. Only - * members that were part of the group during the specified interval are - * included in the response. If no interval is provided then the group - * membership over the last minute is returned. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.api.MonitoredResource|MonitoredResource}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `listGroupMembersAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Lists the monitored resources that are members of a group. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The group whose members are listed. The format is + * `"projects/{project_id_or_number}/groups/{group_id}"`. + * @param {number} request.pageSize + * A positive number that is the maximum number of results to return. + * @param {string} request.pageToken + * If this field is not empty then it must contain the `nextPageToken` value + * returned by a previous call to this method. Using this field causes the + * method to return additional results from the previous method call. + * @param {string} request.filter + * An optional [list filter](/monitoring/api/learn_more#filtering) describing + * the members to be returned. The filter may reference the type, labels, and + * metadata of monitored resources that comprise the group. + * For example, to return only resources representing Compute Engine VM + * instances, use this filter: + * + * resource.type = "gce_instance" + * @param {google.monitoring.v3.TimeInterval} request.interval + * An optional time interval for which results should be returned. Only + * members that were part of the group during the specified interval are + * included in the response. If no interval is provided then the group + * membership over the last minute is returned. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.api.MonitoredResource|MonitoredResource}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listGroupMembersAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listGroupMembers( - request?: protos.google.monitoring.v3.IListGroupMembersRequest, - options?: CallOptions): - Promise<[ - protos.google.api.IMonitoredResource[], - protos.google.monitoring.v3.IListGroupMembersRequest|null, - protos.google.monitoring.v3.IListGroupMembersResponse - ]>; + request?: protos.google.monitoring.v3.IListGroupMembersRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.api.IMonitoredResource[], + protos.google.monitoring.v3.IListGroupMembersRequest | null, + protos.google.monitoring.v3.IListGroupMembersResponse, + ] + >; listGroupMembers( - request: protos.google.monitoring.v3.IListGroupMembersRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.monitoring.v3.IListGroupMembersRequest, - protos.google.monitoring.v3.IListGroupMembersResponse|null|undefined, - protos.google.api.IMonitoredResource>): void; + request: protos.google.monitoring.v3.IListGroupMembersRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.monitoring.v3.IListGroupMembersRequest, + protos.google.monitoring.v3.IListGroupMembersResponse | null | undefined, + protos.google.api.IMonitoredResource + >, + ): void; listGroupMembers( - request: protos.google.monitoring.v3.IListGroupMembersRequest, - callback: PaginationCallback< - protos.google.monitoring.v3.IListGroupMembersRequest, - protos.google.monitoring.v3.IListGroupMembersResponse|null|undefined, - protos.google.api.IMonitoredResource>): void; + request: protos.google.monitoring.v3.IListGroupMembersRequest, + callback: PaginationCallback< + protos.google.monitoring.v3.IListGroupMembersRequest, + protos.google.monitoring.v3.IListGroupMembersResponse | null | undefined, + protos.google.api.IMonitoredResource + >, + ): void; listGroupMembers( - request?: protos.google.monitoring.v3.IListGroupMembersRequest, - optionsOrCallback?: CallOptions|PaginationCallback< + request?: protos.google.monitoring.v3.IListGroupMembersRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.monitoring.v3.IListGroupMembersRequest, - protos.google.monitoring.v3.IListGroupMembersResponse|null|undefined, - protos.google.api.IMonitoredResource>, - callback?: PaginationCallback< - protos.google.monitoring.v3.IListGroupMembersRequest, - protos.google.monitoring.v3.IListGroupMembersResponse|null|undefined, - protos.google.api.IMonitoredResource>): - Promise<[ - protos.google.api.IMonitoredResource[], - protos.google.monitoring.v3.IListGroupMembersRequest|null, - protos.google.monitoring.v3.IListGroupMembersResponse - ]>|void { + | protos.google.monitoring.v3.IListGroupMembersResponse + | null + | undefined, + protos.google.api.IMonitoredResource + >, + callback?: PaginationCallback< + protos.google.monitoring.v3.IListGroupMembersRequest, + protos.google.monitoring.v3.IListGroupMembersResponse | null | undefined, + protos.google.api.IMonitoredResource + >, + ): Promise< + [ + protos.google.api.IMonitoredResource[], + protos.google.monitoring.v3.IListGroupMembersRequest | null, + protos.google.monitoring.v3.IListGroupMembersResponse, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.monitoring.v3.IListGroupMembersRequest, - protos.google.monitoring.v3.IListGroupMembersResponse|null|undefined, - protos.google.api.IMonitoredResource>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.monitoring.v3.IListGroupMembersRequest, + | protos.google.monitoring.v3.IListGroupMembersResponse + | null + | undefined, + protos.google.api.IMonitoredResource + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listGroupMembers values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -1160,138 +1382,142 @@ export class GroupServiceClient { this._log.info('listGroupMembers request %j', request); return this.innerApiCalls .listGroupMembers(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.api.IMonitoredResource[], - protos.google.monitoring.v3.IListGroupMembersRequest|null, - protos.google.monitoring.v3.IListGroupMembersResponse - ]) => { - this._log.info('listGroupMembers values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.api.IMonitoredResource[], + protos.google.monitoring.v3.IListGroupMembersRequest | null, + protos.google.monitoring.v3.IListGroupMembersResponse, + ]) => { + this._log.info('listGroupMembers values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listGroupMembers`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The group whose members are listed. The format is - * `"projects/{project_id_or_number}/groups/{group_id}"`. - * @param {number} request.pageSize - * A positive number that is the maximum number of results to return. - * @param {string} request.pageToken - * If this field is not empty then it must contain the `nextPageToken` value - * returned by a previous call to this method. Using this field causes the - * method to return additional results from the previous method call. - * @param {string} request.filter - * An optional [list filter](/monitoring/api/learn_more#filtering) describing - * the members to be returned. The filter may reference the type, labels, and - * metadata of monitored resources that comprise the group. - * For example, to return only resources representing Compute Engine VM - * instances, use this filter: - * - * resource.type = "gce_instance" - * @param {google.monitoring.v3.TimeInterval} request.interval - * An optional time interval for which results should be returned. Only - * members that were part of the group during the specified interval are - * included in the response. If no interval is provided then the group - * membership over the last minute is returned. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.api.MonitoredResource|MonitoredResource} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `listGroupMembersAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `listGroupMembers`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The group whose members are listed. The format is + * `"projects/{project_id_or_number}/groups/{group_id}"`. + * @param {number} request.pageSize + * A positive number that is the maximum number of results to return. + * @param {string} request.pageToken + * If this field is not empty then it must contain the `nextPageToken` value + * returned by a previous call to this method. Using this field causes the + * method to return additional results from the previous method call. + * @param {string} request.filter + * An optional [list filter](/monitoring/api/learn_more#filtering) describing + * the members to be returned. The filter may reference the type, labels, and + * metadata of monitored resources that comprise the group. + * For example, to return only resources representing Compute Engine VM + * instances, use this filter: + * + * resource.type = "gce_instance" + * @param {google.monitoring.v3.TimeInterval} request.interval + * An optional time interval for which results should be returned. Only + * members that were part of the group during the specified interval are + * included in the response. If no interval is provided then the group + * membership over the last minute is returned. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.api.MonitoredResource|MonitoredResource} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listGroupMembersAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listGroupMembersStream( - request?: protos.google.monitoring.v3.IListGroupMembersRequest, - options?: CallOptions): - Transform{ + request?: protos.google.monitoring.v3.IListGroupMembersRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); const defaultCallSettings = this._defaults['listGroupMembers']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listGroupMembers stream %j', request); return this.descriptors.page.listGroupMembers.createStream( this.innerApiCalls.listGroupMembers as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listGroupMembers`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The group whose members are listed. The format is - * `"projects/{project_id_or_number}/groups/{group_id}"`. - * @param {number} request.pageSize - * A positive number that is the maximum number of results to return. - * @param {string} request.pageToken - * If this field is not empty then it must contain the `nextPageToken` value - * returned by a previous call to this method. Using this field causes the - * method to return additional results from the previous method call. - * @param {string} request.filter - * An optional [list filter](/monitoring/api/learn_more#filtering) describing - * the members to be returned. The filter may reference the type, labels, and - * metadata of monitored resources that comprise the group. - * For example, to return only resources representing Compute Engine VM - * instances, use this filter: - * - * resource.type = "gce_instance" - * @param {google.monitoring.v3.TimeInterval} request.interval - * An optional time interval for which results should be returned. Only - * members that were part of the group during the specified interval are - * included in the response. If no interval is provided then the group - * membership over the last minute is returned. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.api.MonitoredResource|MonitoredResource}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v3/group_service.list_group_members.js - * region_tag:monitoring_v3_generated_GroupService_ListGroupMembers_async - */ + /** + * Equivalent to `listGroupMembers`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The group whose members are listed. The format is + * `"projects/{project_id_or_number}/groups/{group_id}"`. + * @param {number} request.pageSize + * A positive number that is the maximum number of results to return. + * @param {string} request.pageToken + * If this field is not empty then it must contain the `nextPageToken` value + * returned by a previous call to this method. Using this field causes the + * method to return additional results from the previous method call. + * @param {string} request.filter + * An optional [list filter](/monitoring/api/learn_more#filtering) describing + * the members to be returned. The filter may reference the type, labels, and + * metadata of monitored resources that comprise the group. + * For example, to return only resources representing Compute Engine VM + * instances, use this filter: + * + * resource.type = "gce_instance" + * @param {google.monitoring.v3.TimeInterval} request.interval + * An optional time interval for which results should be returned. Only + * members that were part of the group during the specified interval are + * included in the response. If no interval is provided then the group + * membership over the last minute is returned. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.api.MonitoredResource|MonitoredResource}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v3/group_service.list_group_members.js + * region_tag:monitoring_v3_generated_GroupService_ListGroupMembers_async + */ listGroupMembersAsync( - request?: protos.google.monitoring.v3.IListGroupMembersRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.monitoring.v3.IListGroupMembersRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); const defaultCallSettings = this._defaults['listGroupMembers']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listGroupMembers iterate %j', request); return this.descriptors.page.listGroupMembers.asyncIterate( this.innerApiCalls['listGroupMembers'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } // -------------------- @@ -1305,7 +1531,7 @@ export class GroupServiceClient { * @param {string} alert_policy * @returns {string} Resource name string. */ - folderAlertPolicyPath(folder:string,alertPolicy:string) { + folderAlertPolicyPath(folder: string, alertPolicy: string) { return this.pathTemplates.folderAlertPolicyPathTemplate.render({ folder: folder, alert_policy: alertPolicy, @@ -1320,7 +1546,9 @@ export class GroupServiceClient { * @returns {string} A string representing the folder. */ matchFolderFromFolderAlertPolicyName(folderAlertPolicyName: string) { - return this.pathTemplates.folderAlertPolicyPathTemplate.match(folderAlertPolicyName).folder; + return this.pathTemplates.folderAlertPolicyPathTemplate.match( + folderAlertPolicyName, + ).folder; } /** @@ -1331,7 +1559,9 @@ export class GroupServiceClient { * @returns {string} A string representing the alert_policy. */ matchAlertPolicyFromFolderAlertPolicyName(folderAlertPolicyName: string) { - return this.pathTemplates.folderAlertPolicyPathTemplate.match(folderAlertPolicyName).alert_policy; + return this.pathTemplates.folderAlertPolicyPathTemplate.match( + folderAlertPolicyName, + ).alert_policy; } /** @@ -1342,7 +1572,11 @@ export class GroupServiceClient { * @param {string} condition * @returns {string} Resource name string. */ - folderAlertPolicyConditionPath(folder:string,alertPolicy:string,condition:string) { + folderAlertPolicyConditionPath( + folder: string, + alertPolicy: string, + condition: string, + ) { return this.pathTemplates.folderAlertPolicyConditionPathTemplate.render({ folder: folder, alert_policy: alertPolicy, @@ -1357,8 +1591,12 @@ export class GroupServiceClient { * A fully-qualified path representing folder_alert_policy_condition resource. * @returns {string} A string representing the folder. */ - matchFolderFromFolderAlertPolicyConditionName(folderAlertPolicyConditionName: string) { - return this.pathTemplates.folderAlertPolicyConditionPathTemplate.match(folderAlertPolicyConditionName).folder; + matchFolderFromFolderAlertPolicyConditionName( + folderAlertPolicyConditionName: string, + ) { + return this.pathTemplates.folderAlertPolicyConditionPathTemplate.match( + folderAlertPolicyConditionName, + ).folder; } /** @@ -1368,8 +1606,12 @@ export class GroupServiceClient { * A fully-qualified path representing folder_alert_policy_condition resource. * @returns {string} A string representing the alert_policy. */ - matchAlertPolicyFromFolderAlertPolicyConditionName(folderAlertPolicyConditionName: string) { - return this.pathTemplates.folderAlertPolicyConditionPathTemplate.match(folderAlertPolicyConditionName).alert_policy; + matchAlertPolicyFromFolderAlertPolicyConditionName( + folderAlertPolicyConditionName: string, + ) { + return this.pathTemplates.folderAlertPolicyConditionPathTemplate.match( + folderAlertPolicyConditionName, + ).alert_policy; } /** @@ -1379,8 +1621,12 @@ export class GroupServiceClient { * A fully-qualified path representing folder_alert_policy_condition resource. * @returns {string} A string representing the condition. */ - matchConditionFromFolderAlertPolicyConditionName(folderAlertPolicyConditionName: string) { - return this.pathTemplates.folderAlertPolicyConditionPathTemplate.match(folderAlertPolicyConditionName).condition; + matchConditionFromFolderAlertPolicyConditionName( + folderAlertPolicyConditionName: string, + ) { + return this.pathTemplates.folderAlertPolicyConditionPathTemplate.match( + folderAlertPolicyConditionName, + ).condition; } /** @@ -1390,7 +1636,7 @@ export class GroupServiceClient { * @param {string} channel_descriptor * @returns {string} Resource name string. */ - folderChannelDescriptorPath(folder:string,channelDescriptor:string) { + folderChannelDescriptorPath(folder: string, channelDescriptor: string) { return this.pathTemplates.folderChannelDescriptorPathTemplate.render({ folder: folder, channel_descriptor: channelDescriptor, @@ -1404,8 +1650,12 @@ export class GroupServiceClient { * A fully-qualified path representing folder_channel_descriptor resource. * @returns {string} A string representing the folder. */ - matchFolderFromFolderChannelDescriptorName(folderChannelDescriptorName: string) { - return this.pathTemplates.folderChannelDescriptorPathTemplate.match(folderChannelDescriptorName).folder; + matchFolderFromFolderChannelDescriptorName( + folderChannelDescriptorName: string, + ) { + return this.pathTemplates.folderChannelDescriptorPathTemplate.match( + folderChannelDescriptorName, + ).folder; } /** @@ -1415,8 +1665,12 @@ export class GroupServiceClient { * A fully-qualified path representing folder_channel_descriptor resource. * @returns {string} A string representing the channel_descriptor. */ - matchChannelDescriptorFromFolderChannelDescriptorName(folderChannelDescriptorName: string) { - return this.pathTemplates.folderChannelDescriptorPathTemplate.match(folderChannelDescriptorName).channel_descriptor; + matchChannelDescriptorFromFolderChannelDescriptorName( + folderChannelDescriptorName: string, + ) { + return this.pathTemplates.folderChannelDescriptorPathTemplate.match( + folderChannelDescriptorName, + ).channel_descriptor; } /** @@ -1426,7 +1680,7 @@ export class GroupServiceClient { * @param {string} group * @returns {string} Resource name string. */ - folderGroupPath(folder:string,group:string) { + folderGroupPath(folder: string, group: string) { return this.pathTemplates.folderGroupPathTemplate.render({ folder: folder, group: group, @@ -1441,7 +1695,8 @@ export class GroupServiceClient { * @returns {string} A string representing the folder. */ matchFolderFromFolderGroupName(folderGroupName: string) { - return this.pathTemplates.folderGroupPathTemplate.match(folderGroupName).folder; + return this.pathTemplates.folderGroupPathTemplate.match(folderGroupName) + .folder; } /** @@ -1452,7 +1707,8 @@ export class GroupServiceClient { * @returns {string} A string representing the group. */ matchGroupFromFolderGroupName(folderGroupName: string) { - return this.pathTemplates.folderGroupPathTemplate.match(folderGroupName).group; + return this.pathTemplates.folderGroupPathTemplate.match(folderGroupName) + .group; } /** @@ -1462,7 +1718,7 @@ export class GroupServiceClient { * @param {string} notification_channel * @returns {string} Resource name string. */ - folderNotificationChannelPath(folder:string,notificationChannel:string) { + folderNotificationChannelPath(folder: string, notificationChannel: string) { return this.pathTemplates.folderNotificationChannelPathTemplate.render({ folder: folder, notification_channel: notificationChannel, @@ -1476,8 +1732,12 @@ export class GroupServiceClient { * A fully-qualified path representing folder_notification_channel resource. * @returns {string} A string representing the folder. */ - matchFolderFromFolderNotificationChannelName(folderNotificationChannelName: string) { - return this.pathTemplates.folderNotificationChannelPathTemplate.match(folderNotificationChannelName).folder; + matchFolderFromFolderNotificationChannelName( + folderNotificationChannelName: string, + ) { + return this.pathTemplates.folderNotificationChannelPathTemplate.match( + folderNotificationChannelName, + ).folder; } /** @@ -1487,8 +1747,12 @@ export class GroupServiceClient { * A fully-qualified path representing folder_notification_channel resource. * @returns {string} A string representing the notification_channel. */ - matchNotificationChannelFromFolderNotificationChannelName(folderNotificationChannelName: string) { - return this.pathTemplates.folderNotificationChannelPathTemplate.match(folderNotificationChannelName).notification_channel; + matchNotificationChannelFromFolderNotificationChannelName( + folderNotificationChannelName: string, + ) { + return this.pathTemplates.folderNotificationChannelPathTemplate.match( + folderNotificationChannelName, + ).notification_channel; } /** @@ -1498,7 +1762,7 @@ export class GroupServiceClient { * @param {string} service * @returns {string} Resource name string. */ - folderServicePath(folder:string,service:string) { + folderServicePath(folder: string, service: string) { return this.pathTemplates.folderServicePathTemplate.render({ folder: folder, service: service, @@ -1513,7 +1777,8 @@ export class GroupServiceClient { * @returns {string} A string representing the folder. */ matchFolderFromFolderServiceName(folderServiceName: string) { - return this.pathTemplates.folderServicePathTemplate.match(folderServiceName).folder; + return this.pathTemplates.folderServicePathTemplate.match(folderServiceName) + .folder; } /** @@ -1524,7 +1789,8 @@ export class GroupServiceClient { * @returns {string} A string representing the service. */ matchServiceFromFolderServiceName(folderServiceName: string) { - return this.pathTemplates.folderServicePathTemplate.match(folderServiceName).service; + return this.pathTemplates.folderServicePathTemplate.match(folderServiceName) + .service; } /** @@ -1535,12 +1801,18 @@ export class GroupServiceClient { * @param {string} service_level_objective * @returns {string} Resource name string. */ - folderServiceServiceLevelObjectivePath(folder:string,service:string,serviceLevelObjective:string) { - return this.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.render({ - folder: folder, - service: service, - service_level_objective: serviceLevelObjective, - }); + folderServiceServiceLevelObjectivePath( + folder: string, + service: string, + serviceLevelObjective: string, + ) { + return this.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.render( + { + folder: folder, + service: service, + service_level_objective: serviceLevelObjective, + }, + ); } /** @@ -1550,8 +1822,12 @@ export class GroupServiceClient { * A fully-qualified path representing folder_service_service_level_objective resource. * @returns {string} A string representing the folder. */ - matchFolderFromFolderServiceServiceLevelObjectiveName(folderServiceServiceLevelObjectiveName: string) { - return this.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match(folderServiceServiceLevelObjectiveName).folder; + matchFolderFromFolderServiceServiceLevelObjectiveName( + folderServiceServiceLevelObjectiveName: string, + ) { + return this.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match( + folderServiceServiceLevelObjectiveName, + ).folder; } /** @@ -1561,8 +1837,12 @@ export class GroupServiceClient { * A fully-qualified path representing folder_service_service_level_objective resource. * @returns {string} A string representing the service. */ - matchServiceFromFolderServiceServiceLevelObjectiveName(folderServiceServiceLevelObjectiveName: string) { - return this.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match(folderServiceServiceLevelObjectiveName).service; + matchServiceFromFolderServiceServiceLevelObjectiveName( + folderServiceServiceLevelObjectiveName: string, + ) { + return this.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match( + folderServiceServiceLevelObjectiveName, + ).service; } /** @@ -1572,8 +1852,12 @@ export class GroupServiceClient { * A fully-qualified path representing folder_service_service_level_objective resource. * @returns {string} A string representing the service_level_objective. */ - matchServiceLevelObjectiveFromFolderServiceServiceLevelObjectiveName(folderServiceServiceLevelObjectiveName: string) { - return this.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match(folderServiceServiceLevelObjectiveName).service_level_objective; + matchServiceLevelObjectiveFromFolderServiceServiceLevelObjectiveName( + folderServiceServiceLevelObjectiveName: string, + ) { + return this.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match( + folderServiceServiceLevelObjectiveName, + ).service_level_objective; } /** @@ -1583,7 +1867,7 @@ export class GroupServiceClient { * @param {string} uptime_check_config * @returns {string} Resource name string. */ - folderUptimeCheckConfigPath(folder:string,uptimeCheckConfig:string) { + folderUptimeCheckConfigPath(folder: string, uptimeCheckConfig: string) { return this.pathTemplates.folderUptimeCheckConfigPathTemplate.render({ folder: folder, uptime_check_config: uptimeCheckConfig, @@ -1597,8 +1881,12 @@ export class GroupServiceClient { * A fully-qualified path representing folder_uptime_check_config resource. * @returns {string} A string representing the folder. */ - matchFolderFromFolderUptimeCheckConfigName(folderUptimeCheckConfigName: string) { - return this.pathTemplates.folderUptimeCheckConfigPathTemplate.match(folderUptimeCheckConfigName).folder; + matchFolderFromFolderUptimeCheckConfigName( + folderUptimeCheckConfigName: string, + ) { + return this.pathTemplates.folderUptimeCheckConfigPathTemplate.match( + folderUptimeCheckConfigName, + ).folder; } /** @@ -1608,8 +1896,12 @@ export class GroupServiceClient { * A fully-qualified path representing folder_uptime_check_config resource. * @returns {string} A string representing the uptime_check_config. */ - matchUptimeCheckConfigFromFolderUptimeCheckConfigName(folderUptimeCheckConfigName: string) { - return this.pathTemplates.folderUptimeCheckConfigPathTemplate.match(folderUptimeCheckConfigName).uptime_check_config; + matchUptimeCheckConfigFromFolderUptimeCheckConfigName( + folderUptimeCheckConfigName: string, + ) { + return this.pathTemplates.folderUptimeCheckConfigPathTemplate.match( + folderUptimeCheckConfigName, + ).uptime_check_config; } /** @@ -1619,7 +1911,7 @@ export class GroupServiceClient { * @param {string} alert_policy * @returns {string} Resource name string. */ - organizationAlertPolicyPath(organization:string,alertPolicy:string) { + organizationAlertPolicyPath(organization: string, alertPolicy: string) { return this.pathTemplates.organizationAlertPolicyPathTemplate.render({ organization: organization, alert_policy: alertPolicy, @@ -1633,8 +1925,12 @@ export class GroupServiceClient { * A fully-qualified path representing organization_alert_policy resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationAlertPolicyName(organizationAlertPolicyName: string) { - return this.pathTemplates.organizationAlertPolicyPathTemplate.match(organizationAlertPolicyName).organization; + matchOrganizationFromOrganizationAlertPolicyName( + organizationAlertPolicyName: string, + ) { + return this.pathTemplates.organizationAlertPolicyPathTemplate.match( + organizationAlertPolicyName, + ).organization; } /** @@ -1644,8 +1940,12 @@ export class GroupServiceClient { * A fully-qualified path representing organization_alert_policy resource. * @returns {string} A string representing the alert_policy. */ - matchAlertPolicyFromOrganizationAlertPolicyName(organizationAlertPolicyName: string) { - return this.pathTemplates.organizationAlertPolicyPathTemplate.match(organizationAlertPolicyName).alert_policy; + matchAlertPolicyFromOrganizationAlertPolicyName( + organizationAlertPolicyName: string, + ) { + return this.pathTemplates.organizationAlertPolicyPathTemplate.match( + organizationAlertPolicyName, + ).alert_policy; } /** @@ -1656,12 +1956,18 @@ export class GroupServiceClient { * @param {string} condition * @returns {string} Resource name string. */ - organizationAlertPolicyConditionPath(organization:string,alertPolicy:string,condition:string) { - return this.pathTemplates.organizationAlertPolicyConditionPathTemplate.render({ - organization: organization, - alert_policy: alertPolicy, - condition: condition, - }); + organizationAlertPolicyConditionPath( + organization: string, + alertPolicy: string, + condition: string, + ) { + return this.pathTemplates.organizationAlertPolicyConditionPathTemplate.render( + { + organization: organization, + alert_policy: alertPolicy, + condition: condition, + }, + ); } /** @@ -1671,8 +1977,12 @@ export class GroupServiceClient { * A fully-qualified path representing organization_alert_policy_condition resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationAlertPolicyConditionName(organizationAlertPolicyConditionName: string) { - return this.pathTemplates.organizationAlertPolicyConditionPathTemplate.match(organizationAlertPolicyConditionName).organization; + matchOrganizationFromOrganizationAlertPolicyConditionName( + organizationAlertPolicyConditionName: string, + ) { + return this.pathTemplates.organizationAlertPolicyConditionPathTemplate.match( + organizationAlertPolicyConditionName, + ).organization; } /** @@ -1682,8 +1992,12 @@ export class GroupServiceClient { * A fully-qualified path representing organization_alert_policy_condition resource. * @returns {string} A string representing the alert_policy. */ - matchAlertPolicyFromOrganizationAlertPolicyConditionName(organizationAlertPolicyConditionName: string) { - return this.pathTemplates.organizationAlertPolicyConditionPathTemplate.match(organizationAlertPolicyConditionName).alert_policy; + matchAlertPolicyFromOrganizationAlertPolicyConditionName( + organizationAlertPolicyConditionName: string, + ) { + return this.pathTemplates.organizationAlertPolicyConditionPathTemplate.match( + organizationAlertPolicyConditionName, + ).alert_policy; } /** @@ -1693,8 +2007,12 @@ export class GroupServiceClient { * A fully-qualified path representing organization_alert_policy_condition resource. * @returns {string} A string representing the condition. */ - matchConditionFromOrganizationAlertPolicyConditionName(organizationAlertPolicyConditionName: string) { - return this.pathTemplates.organizationAlertPolicyConditionPathTemplate.match(organizationAlertPolicyConditionName).condition; + matchConditionFromOrganizationAlertPolicyConditionName( + organizationAlertPolicyConditionName: string, + ) { + return this.pathTemplates.organizationAlertPolicyConditionPathTemplate.match( + organizationAlertPolicyConditionName, + ).condition; } /** @@ -1704,7 +2022,10 @@ export class GroupServiceClient { * @param {string} channel_descriptor * @returns {string} Resource name string. */ - organizationChannelDescriptorPath(organization:string,channelDescriptor:string) { + organizationChannelDescriptorPath( + organization: string, + channelDescriptor: string, + ) { return this.pathTemplates.organizationChannelDescriptorPathTemplate.render({ organization: organization, channel_descriptor: channelDescriptor, @@ -1718,8 +2039,12 @@ export class GroupServiceClient { * A fully-qualified path representing organization_channel_descriptor resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationChannelDescriptorName(organizationChannelDescriptorName: string) { - return this.pathTemplates.organizationChannelDescriptorPathTemplate.match(organizationChannelDescriptorName).organization; + matchOrganizationFromOrganizationChannelDescriptorName( + organizationChannelDescriptorName: string, + ) { + return this.pathTemplates.organizationChannelDescriptorPathTemplate.match( + organizationChannelDescriptorName, + ).organization; } /** @@ -1729,8 +2054,12 @@ export class GroupServiceClient { * A fully-qualified path representing organization_channel_descriptor resource. * @returns {string} A string representing the channel_descriptor. */ - matchChannelDescriptorFromOrganizationChannelDescriptorName(organizationChannelDescriptorName: string) { - return this.pathTemplates.organizationChannelDescriptorPathTemplate.match(organizationChannelDescriptorName).channel_descriptor; + matchChannelDescriptorFromOrganizationChannelDescriptorName( + organizationChannelDescriptorName: string, + ) { + return this.pathTemplates.organizationChannelDescriptorPathTemplate.match( + organizationChannelDescriptorName, + ).channel_descriptor; } /** @@ -1740,7 +2069,7 @@ export class GroupServiceClient { * @param {string} group * @returns {string} Resource name string. */ - organizationGroupPath(organization:string,group:string) { + organizationGroupPath(organization: string, group: string) { return this.pathTemplates.organizationGroupPathTemplate.render({ organization: organization, group: group, @@ -1755,7 +2084,9 @@ export class GroupServiceClient { * @returns {string} A string representing the organization. */ matchOrganizationFromOrganizationGroupName(organizationGroupName: string) { - return this.pathTemplates.organizationGroupPathTemplate.match(organizationGroupName).organization; + return this.pathTemplates.organizationGroupPathTemplate.match( + organizationGroupName, + ).organization; } /** @@ -1766,7 +2097,9 @@ export class GroupServiceClient { * @returns {string} A string representing the group. */ matchGroupFromOrganizationGroupName(organizationGroupName: string) { - return this.pathTemplates.organizationGroupPathTemplate.match(organizationGroupName).group; + return this.pathTemplates.organizationGroupPathTemplate.match( + organizationGroupName, + ).group; } /** @@ -1776,11 +2109,16 @@ export class GroupServiceClient { * @param {string} notification_channel * @returns {string} Resource name string. */ - organizationNotificationChannelPath(organization:string,notificationChannel:string) { - return this.pathTemplates.organizationNotificationChannelPathTemplate.render({ - organization: organization, - notification_channel: notificationChannel, - }); + organizationNotificationChannelPath( + organization: string, + notificationChannel: string, + ) { + return this.pathTemplates.organizationNotificationChannelPathTemplate.render( + { + organization: organization, + notification_channel: notificationChannel, + }, + ); } /** @@ -1790,8 +2128,12 @@ export class GroupServiceClient { * A fully-qualified path representing organization_notification_channel resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationNotificationChannelName(organizationNotificationChannelName: string) { - return this.pathTemplates.organizationNotificationChannelPathTemplate.match(organizationNotificationChannelName).organization; + matchOrganizationFromOrganizationNotificationChannelName( + organizationNotificationChannelName: string, + ) { + return this.pathTemplates.organizationNotificationChannelPathTemplate.match( + organizationNotificationChannelName, + ).organization; } /** @@ -1801,8 +2143,12 @@ export class GroupServiceClient { * A fully-qualified path representing organization_notification_channel resource. * @returns {string} A string representing the notification_channel. */ - matchNotificationChannelFromOrganizationNotificationChannelName(organizationNotificationChannelName: string) { - return this.pathTemplates.organizationNotificationChannelPathTemplate.match(organizationNotificationChannelName).notification_channel; + matchNotificationChannelFromOrganizationNotificationChannelName( + organizationNotificationChannelName: string, + ) { + return this.pathTemplates.organizationNotificationChannelPathTemplate.match( + organizationNotificationChannelName, + ).notification_channel; } /** @@ -1812,7 +2158,7 @@ export class GroupServiceClient { * @param {string} service * @returns {string} Resource name string. */ - organizationServicePath(organization:string,service:string) { + organizationServicePath(organization: string, service: string) { return this.pathTemplates.organizationServicePathTemplate.render({ organization: organization, service: service, @@ -1826,8 +2172,12 @@ export class GroupServiceClient { * A fully-qualified path representing organization_service resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationServiceName(organizationServiceName: string) { - return this.pathTemplates.organizationServicePathTemplate.match(organizationServiceName).organization; + matchOrganizationFromOrganizationServiceName( + organizationServiceName: string, + ) { + return this.pathTemplates.organizationServicePathTemplate.match( + organizationServiceName, + ).organization; } /** @@ -1838,7 +2188,9 @@ export class GroupServiceClient { * @returns {string} A string representing the service. */ matchServiceFromOrganizationServiceName(organizationServiceName: string) { - return this.pathTemplates.organizationServicePathTemplate.match(organizationServiceName).service; + return this.pathTemplates.organizationServicePathTemplate.match( + organizationServiceName, + ).service; } /** @@ -1849,12 +2201,18 @@ export class GroupServiceClient { * @param {string} service_level_objective * @returns {string} Resource name string. */ - organizationServiceServiceLevelObjectivePath(organization:string,service:string,serviceLevelObjective:string) { - return this.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.render({ - organization: organization, - service: service, - service_level_objective: serviceLevelObjective, - }); + organizationServiceServiceLevelObjectivePath( + organization: string, + service: string, + serviceLevelObjective: string, + ) { + return this.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.render( + { + organization: organization, + service: service, + service_level_objective: serviceLevelObjective, + }, + ); } /** @@ -1864,8 +2222,12 @@ export class GroupServiceClient { * A fully-qualified path representing organization_service_service_level_objective resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationServiceServiceLevelObjectiveName(organizationServiceServiceLevelObjectiveName: string) { - return this.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match(organizationServiceServiceLevelObjectiveName).organization; + matchOrganizationFromOrganizationServiceServiceLevelObjectiveName( + organizationServiceServiceLevelObjectiveName: string, + ) { + return this.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match( + organizationServiceServiceLevelObjectiveName, + ).organization; } /** @@ -1875,8 +2237,12 @@ export class GroupServiceClient { * A fully-qualified path representing organization_service_service_level_objective resource. * @returns {string} A string representing the service. */ - matchServiceFromOrganizationServiceServiceLevelObjectiveName(organizationServiceServiceLevelObjectiveName: string) { - return this.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match(organizationServiceServiceLevelObjectiveName).service; + matchServiceFromOrganizationServiceServiceLevelObjectiveName( + organizationServiceServiceLevelObjectiveName: string, + ) { + return this.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match( + organizationServiceServiceLevelObjectiveName, + ).service; } /** @@ -1886,8 +2252,12 @@ export class GroupServiceClient { * A fully-qualified path representing organization_service_service_level_objective resource. * @returns {string} A string representing the service_level_objective. */ - matchServiceLevelObjectiveFromOrganizationServiceServiceLevelObjectiveName(organizationServiceServiceLevelObjectiveName: string) { - return this.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match(organizationServiceServiceLevelObjectiveName).service_level_objective; + matchServiceLevelObjectiveFromOrganizationServiceServiceLevelObjectiveName( + organizationServiceServiceLevelObjectiveName: string, + ) { + return this.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match( + organizationServiceServiceLevelObjectiveName, + ).service_level_objective; } /** @@ -1897,7 +2267,10 @@ export class GroupServiceClient { * @param {string} uptime_check_config * @returns {string} Resource name string. */ - organizationUptimeCheckConfigPath(organization:string,uptimeCheckConfig:string) { + organizationUptimeCheckConfigPath( + organization: string, + uptimeCheckConfig: string, + ) { return this.pathTemplates.organizationUptimeCheckConfigPathTemplate.render({ organization: organization, uptime_check_config: uptimeCheckConfig, @@ -1911,8 +2284,12 @@ export class GroupServiceClient { * A fully-qualified path representing organization_uptime_check_config resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationUptimeCheckConfigName(organizationUptimeCheckConfigName: string) { - return this.pathTemplates.organizationUptimeCheckConfigPathTemplate.match(organizationUptimeCheckConfigName).organization; + matchOrganizationFromOrganizationUptimeCheckConfigName( + organizationUptimeCheckConfigName: string, + ) { + return this.pathTemplates.organizationUptimeCheckConfigPathTemplate.match( + organizationUptimeCheckConfigName, + ).organization; } /** @@ -1922,8 +2299,12 @@ export class GroupServiceClient { * A fully-qualified path representing organization_uptime_check_config resource. * @returns {string} A string representing the uptime_check_config. */ - matchUptimeCheckConfigFromOrganizationUptimeCheckConfigName(organizationUptimeCheckConfigName: string) { - return this.pathTemplates.organizationUptimeCheckConfigPathTemplate.match(organizationUptimeCheckConfigName).uptime_check_config; + matchUptimeCheckConfigFromOrganizationUptimeCheckConfigName( + organizationUptimeCheckConfigName: string, + ) { + return this.pathTemplates.organizationUptimeCheckConfigPathTemplate.match( + organizationUptimeCheckConfigName, + ).uptime_check_config; } /** @@ -1933,7 +2314,7 @@ export class GroupServiceClient { * @param {string} alert_policy * @returns {string} Resource name string. */ - projectAlertPolicyPath(project:string,alertPolicy:string) { + projectAlertPolicyPath(project: string, alertPolicy: string) { return this.pathTemplates.projectAlertPolicyPathTemplate.render({ project: project, alert_policy: alertPolicy, @@ -1948,7 +2329,9 @@ export class GroupServiceClient { * @returns {string} A string representing the project. */ matchProjectFromProjectAlertPolicyName(projectAlertPolicyName: string) { - return this.pathTemplates.projectAlertPolicyPathTemplate.match(projectAlertPolicyName).project; + return this.pathTemplates.projectAlertPolicyPathTemplate.match( + projectAlertPolicyName, + ).project; } /** @@ -1959,7 +2342,9 @@ export class GroupServiceClient { * @returns {string} A string representing the alert_policy. */ matchAlertPolicyFromProjectAlertPolicyName(projectAlertPolicyName: string) { - return this.pathTemplates.projectAlertPolicyPathTemplate.match(projectAlertPolicyName).alert_policy; + return this.pathTemplates.projectAlertPolicyPathTemplate.match( + projectAlertPolicyName, + ).alert_policy; } /** @@ -1970,7 +2355,11 @@ export class GroupServiceClient { * @param {string} condition * @returns {string} Resource name string. */ - projectAlertPolicyConditionPath(project:string,alertPolicy:string,condition:string) { + projectAlertPolicyConditionPath( + project: string, + alertPolicy: string, + condition: string, + ) { return this.pathTemplates.projectAlertPolicyConditionPathTemplate.render({ project: project, alert_policy: alertPolicy, @@ -1985,8 +2374,12 @@ export class GroupServiceClient { * A fully-qualified path representing project_alert_policy_condition resource. * @returns {string} A string representing the project. */ - matchProjectFromProjectAlertPolicyConditionName(projectAlertPolicyConditionName: string) { - return this.pathTemplates.projectAlertPolicyConditionPathTemplate.match(projectAlertPolicyConditionName).project; + matchProjectFromProjectAlertPolicyConditionName( + projectAlertPolicyConditionName: string, + ) { + return this.pathTemplates.projectAlertPolicyConditionPathTemplate.match( + projectAlertPolicyConditionName, + ).project; } /** @@ -1996,8 +2389,12 @@ export class GroupServiceClient { * A fully-qualified path representing project_alert_policy_condition resource. * @returns {string} A string representing the alert_policy. */ - matchAlertPolicyFromProjectAlertPolicyConditionName(projectAlertPolicyConditionName: string) { - return this.pathTemplates.projectAlertPolicyConditionPathTemplate.match(projectAlertPolicyConditionName).alert_policy; + matchAlertPolicyFromProjectAlertPolicyConditionName( + projectAlertPolicyConditionName: string, + ) { + return this.pathTemplates.projectAlertPolicyConditionPathTemplate.match( + projectAlertPolicyConditionName, + ).alert_policy; } /** @@ -2007,8 +2404,12 @@ export class GroupServiceClient { * A fully-qualified path representing project_alert_policy_condition resource. * @returns {string} A string representing the condition. */ - matchConditionFromProjectAlertPolicyConditionName(projectAlertPolicyConditionName: string) { - return this.pathTemplates.projectAlertPolicyConditionPathTemplate.match(projectAlertPolicyConditionName).condition; + matchConditionFromProjectAlertPolicyConditionName( + projectAlertPolicyConditionName: string, + ) { + return this.pathTemplates.projectAlertPolicyConditionPathTemplate.match( + projectAlertPolicyConditionName, + ).condition; } /** @@ -2018,7 +2419,7 @@ export class GroupServiceClient { * @param {string} channel_descriptor * @returns {string} Resource name string. */ - projectChannelDescriptorPath(project:string,channelDescriptor:string) { + projectChannelDescriptorPath(project: string, channelDescriptor: string) { return this.pathTemplates.projectChannelDescriptorPathTemplate.render({ project: project, channel_descriptor: channelDescriptor, @@ -2032,8 +2433,12 @@ export class GroupServiceClient { * A fully-qualified path representing project_channel_descriptor resource. * @returns {string} A string representing the project. */ - matchProjectFromProjectChannelDescriptorName(projectChannelDescriptorName: string) { - return this.pathTemplates.projectChannelDescriptorPathTemplate.match(projectChannelDescriptorName).project; + matchProjectFromProjectChannelDescriptorName( + projectChannelDescriptorName: string, + ) { + return this.pathTemplates.projectChannelDescriptorPathTemplate.match( + projectChannelDescriptorName, + ).project; } /** @@ -2043,8 +2448,12 @@ export class GroupServiceClient { * A fully-qualified path representing project_channel_descriptor resource. * @returns {string} A string representing the channel_descriptor. */ - matchChannelDescriptorFromProjectChannelDescriptorName(projectChannelDescriptorName: string) { - return this.pathTemplates.projectChannelDescriptorPathTemplate.match(projectChannelDescriptorName).channel_descriptor; + matchChannelDescriptorFromProjectChannelDescriptorName( + projectChannelDescriptorName: string, + ) { + return this.pathTemplates.projectChannelDescriptorPathTemplate.match( + projectChannelDescriptorName, + ).channel_descriptor; } /** @@ -2054,7 +2463,7 @@ export class GroupServiceClient { * @param {string} group * @returns {string} Resource name string. */ - projectGroupPath(project:string,group:string) { + projectGroupPath(project: string, group: string) { return this.pathTemplates.projectGroupPathTemplate.render({ project: project, group: group, @@ -2069,7 +2478,8 @@ export class GroupServiceClient { * @returns {string} A string representing the project. */ matchProjectFromProjectGroupName(projectGroupName: string) { - return this.pathTemplates.projectGroupPathTemplate.match(projectGroupName).project; + return this.pathTemplates.projectGroupPathTemplate.match(projectGroupName) + .project; } /** @@ -2080,7 +2490,8 @@ export class GroupServiceClient { * @returns {string} A string representing the group. */ matchGroupFromProjectGroupName(projectGroupName: string) { - return this.pathTemplates.projectGroupPathTemplate.match(projectGroupName).group; + return this.pathTemplates.projectGroupPathTemplate.match(projectGroupName) + .group; } /** @@ -2090,7 +2501,7 @@ export class GroupServiceClient { * @param {string} notification_channel * @returns {string} Resource name string. */ - projectNotificationChannelPath(project:string,notificationChannel:string) { + projectNotificationChannelPath(project: string, notificationChannel: string) { return this.pathTemplates.projectNotificationChannelPathTemplate.render({ project: project, notification_channel: notificationChannel, @@ -2104,8 +2515,12 @@ export class GroupServiceClient { * A fully-qualified path representing project_notification_channel resource. * @returns {string} A string representing the project. */ - matchProjectFromProjectNotificationChannelName(projectNotificationChannelName: string) { - return this.pathTemplates.projectNotificationChannelPathTemplate.match(projectNotificationChannelName).project; + matchProjectFromProjectNotificationChannelName( + projectNotificationChannelName: string, + ) { + return this.pathTemplates.projectNotificationChannelPathTemplate.match( + projectNotificationChannelName, + ).project; } /** @@ -2115,8 +2530,12 @@ export class GroupServiceClient { * A fully-qualified path representing project_notification_channel resource. * @returns {string} A string representing the notification_channel. */ - matchNotificationChannelFromProjectNotificationChannelName(projectNotificationChannelName: string) { - return this.pathTemplates.projectNotificationChannelPathTemplate.match(projectNotificationChannelName).notification_channel; + matchNotificationChannelFromProjectNotificationChannelName( + projectNotificationChannelName: string, + ) { + return this.pathTemplates.projectNotificationChannelPathTemplate.match( + projectNotificationChannelName, + ).notification_channel; } /** @@ -2126,7 +2545,7 @@ export class GroupServiceClient { * @param {string} service * @returns {string} Resource name string. */ - projectServicePath(project:string,service:string) { + projectServicePath(project: string, service: string) { return this.pathTemplates.projectServicePathTemplate.render({ project: project, service: service, @@ -2141,7 +2560,9 @@ export class GroupServiceClient { * @returns {string} A string representing the project. */ matchProjectFromProjectServiceName(projectServiceName: string) { - return this.pathTemplates.projectServicePathTemplate.match(projectServiceName).project; + return this.pathTemplates.projectServicePathTemplate.match( + projectServiceName, + ).project; } /** @@ -2152,7 +2573,9 @@ export class GroupServiceClient { * @returns {string} A string representing the service. */ matchServiceFromProjectServiceName(projectServiceName: string) { - return this.pathTemplates.projectServicePathTemplate.match(projectServiceName).service; + return this.pathTemplates.projectServicePathTemplate.match( + projectServiceName, + ).service; } /** @@ -2163,12 +2586,18 @@ export class GroupServiceClient { * @param {string} service_level_objective * @returns {string} Resource name string. */ - projectServiceServiceLevelObjectivePath(project:string,service:string,serviceLevelObjective:string) { - return this.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.render({ - project: project, - service: service, - service_level_objective: serviceLevelObjective, - }); + projectServiceServiceLevelObjectivePath( + project: string, + service: string, + serviceLevelObjective: string, + ) { + return this.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.render( + { + project: project, + service: service, + service_level_objective: serviceLevelObjective, + }, + ); } /** @@ -2178,8 +2607,12 @@ export class GroupServiceClient { * A fully-qualified path representing project_service_service_level_objective resource. * @returns {string} A string representing the project. */ - matchProjectFromProjectServiceServiceLevelObjectiveName(projectServiceServiceLevelObjectiveName: string) { - return this.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match(projectServiceServiceLevelObjectiveName).project; + matchProjectFromProjectServiceServiceLevelObjectiveName( + projectServiceServiceLevelObjectiveName: string, + ) { + return this.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match( + projectServiceServiceLevelObjectiveName, + ).project; } /** @@ -2189,8 +2622,12 @@ export class GroupServiceClient { * A fully-qualified path representing project_service_service_level_objective resource. * @returns {string} A string representing the service. */ - matchServiceFromProjectServiceServiceLevelObjectiveName(projectServiceServiceLevelObjectiveName: string) { - return this.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match(projectServiceServiceLevelObjectiveName).service; + matchServiceFromProjectServiceServiceLevelObjectiveName( + projectServiceServiceLevelObjectiveName: string, + ) { + return this.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match( + projectServiceServiceLevelObjectiveName, + ).service; } /** @@ -2200,8 +2637,12 @@ export class GroupServiceClient { * A fully-qualified path representing project_service_service_level_objective resource. * @returns {string} A string representing the service_level_objective. */ - matchServiceLevelObjectiveFromProjectServiceServiceLevelObjectiveName(projectServiceServiceLevelObjectiveName: string) { - return this.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match(projectServiceServiceLevelObjectiveName).service_level_objective; + matchServiceLevelObjectiveFromProjectServiceServiceLevelObjectiveName( + projectServiceServiceLevelObjectiveName: string, + ) { + return this.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match( + projectServiceServiceLevelObjectiveName, + ).service_level_objective; } /** @@ -2211,7 +2652,7 @@ export class GroupServiceClient { * @param {string} uptime_check_config * @returns {string} Resource name string. */ - projectUptimeCheckConfigPath(project:string,uptimeCheckConfig:string) { + projectUptimeCheckConfigPath(project: string, uptimeCheckConfig: string) { return this.pathTemplates.projectUptimeCheckConfigPathTemplate.render({ project: project, uptime_check_config: uptimeCheckConfig, @@ -2225,8 +2666,12 @@ export class GroupServiceClient { * A fully-qualified path representing project_uptime_check_config resource. * @returns {string} A string representing the project. */ - matchProjectFromProjectUptimeCheckConfigName(projectUptimeCheckConfigName: string) { - return this.pathTemplates.projectUptimeCheckConfigPathTemplate.match(projectUptimeCheckConfigName).project; + matchProjectFromProjectUptimeCheckConfigName( + projectUptimeCheckConfigName: string, + ) { + return this.pathTemplates.projectUptimeCheckConfigPathTemplate.match( + projectUptimeCheckConfigName, + ).project; } /** @@ -2236,8 +2681,12 @@ export class GroupServiceClient { * A fully-qualified path representing project_uptime_check_config resource. * @returns {string} A string representing the uptime_check_config. */ - matchUptimeCheckConfigFromProjectUptimeCheckConfigName(projectUptimeCheckConfigName: string) { - return this.pathTemplates.projectUptimeCheckConfigPathTemplate.match(projectUptimeCheckConfigName).uptime_check_config; + matchUptimeCheckConfigFromProjectUptimeCheckConfigName( + projectUptimeCheckConfigName: string, + ) { + return this.pathTemplates.projectUptimeCheckConfigPathTemplate.match( + projectUptimeCheckConfigName, + ).uptime_check_config; } /** @@ -2248,7 +2697,7 @@ export class GroupServiceClient { */ close(): Promise { if (this.groupServiceStub && !this._terminated) { - return this.groupServiceStub.then(stub => { + return this.groupServiceStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -2256,4 +2705,4 @@ export class GroupServiceClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/core/generator/gapic-generator-typescript/baselines/monitoring/src/v3/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/monitoring/src/v3/index.ts.baseline index aecf31897ee2..8d1242941089 100644 --- a/core/generator/gapic-generator-typescript/baselines/monitoring/src/v3/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/monitoring/src/v3/index.ts.baseline @@ -16,9 +16,9 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -export {AlertPolicyServiceClient} from './alert_policy_service_client'; -export {GroupServiceClient} from './group_service_client'; -export {MetricServiceClient} from './metric_service_client'; -export {NotificationChannelServiceClient} from './notification_channel_service_client'; -export {ServiceMonitoringServiceClient} from './service_monitoring_service_client'; -export {UptimeCheckServiceClient} from './uptime_check_service_client'; +export { AlertPolicyServiceClient } from './alert_policy_service_client'; +export { GroupServiceClient } from './group_service_client'; +export { MetricServiceClient } from './metric_service_client'; +export { NotificationChannelServiceClient } from './notification_channel_service_client'; +export { ServiceMonitoringServiceClient } from './service_monitoring_service_client'; +export { UptimeCheckServiceClient } from './uptime_check_service_client'; diff --git a/core/generator/gapic-generator-typescript/baselines/monitoring/src/v3/metric_service_client.ts.baseline b/core/generator/gapic-generator-typescript/baselines/monitoring/src/v3/metric_service_client.ts.baseline index ada6e2431f51..366954be465c 100644 --- a/core/generator/gapic-generator-typescript/baselines/monitoring/src/v3/metric_service_client.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/monitoring/src/v3/metric_service_client.ts.baseline @@ -18,11 +18,18 @@ /* global window */ import type * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions, PaginationCallback, GaxCall} from 'google-gax'; -import {Transform} from 'stream'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + PaginationCallback, + GaxCall, +} from 'google-gax'; +import { Transform } from 'stream'; import * as protos from '../../protos/protos'; import jsonProtos = require('../../protos/protos.json'); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; /** * Client JSON configuration object, loaded from @@ -45,7 +52,7 @@ export class MetricServiceClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('monitoring'); @@ -58,9 +65,9 @@ export class MetricServiceClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; - metricServiceStub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; + metricServiceStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of MetricServiceClient. @@ -101,21 +108,42 @@ export class MetricServiceClient { * const client = new MetricServiceClient({fallback: true}, gax); * ``` */ - constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { // Ensure that options include all the required fields. const staticMembers = this.constructor as typeof MetricServiceClient; - if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { - throw new Error('Please set either universe_domain or universeDomain, but not both.'); + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); } - const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; - this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; this._servicePath = 'monitoring.' + this._universeDomain; - const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; - const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. if (servicePath !== this._servicePath && !('scopes' in opts)) { @@ -137,7 +165,7 @@ export class MetricServiceClient { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; @@ -151,10 +179,7 @@ export class MetricServiceClient { } // Determine the client header string. - const clientHeader = [ - `gax/${this._gaxModule.version}`, - `gapic/${version}`, - ]; + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/${process.versions.node}`); } else { @@ -176,94 +201,105 @@ export class MetricServiceClient { // Create useful helper objects for these. this.pathTemplates = { folderAlertPolicyPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/alertPolicies/{alert_policy}' + 'folders/{folder}/alertPolicies/{alert_policy}', ), folderAlertPolicyConditionPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/alertPolicies/{alert_policy}/conditions/{condition}' + 'folders/{folder}/alertPolicies/{alert_policy}/conditions/{condition}', ), folderChannelDescriptorPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/notificationChannelDescriptors/{channel_descriptor}' + 'folders/{folder}/notificationChannelDescriptors/{channel_descriptor}', ), folderGroupPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/groups/{group}' + 'folders/{folder}/groups/{group}', ), folderMetricDescriptorPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/metricDescriptors/{metric_descriptor=**}' - ), - folderMonitoredResourceDescriptorPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/monitoredResourceDescriptors/{monitored_resource_descriptor}' + 'folders/{folder}/metricDescriptors/{metric_descriptor=**}', ), + folderMonitoredResourceDescriptorPathTemplate: + new this._gaxModule.PathTemplate( + 'folders/{folder}/monitoredResourceDescriptors/{monitored_resource_descriptor}', + ), folderNotificationChannelPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/notificationChannels/{notification_channel}' + 'folders/{folder}/notificationChannels/{notification_channel}', ), folderServicePathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/services/{service}' - ), - folderServiceServiceLevelObjectivePathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/services/{service}/serviceLevelObjectives/{service_level_objective}' + 'folders/{folder}/services/{service}', ), + folderServiceServiceLevelObjectivePathTemplate: + new this._gaxModule.PathTemplate( + 'folders/{folder}/services/{service}/serviceLevelObjectives/{service_level_objective}', + ), folderUptimeCheckConfigPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/uptimeCheckConfigs/{uptime_check_config}' + 'folders/{folder}/uptimeCheckConfigs/{uptime_check_config}', ), organizationAlertPolicyPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/alertPolicies/{alert_policy}' - ), - organizationAlertPolicyConditionPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/alertPolicies/{alert_policy}/conditions/{condition}' - ), - organizationChannelDescriptorPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/notificationChannelDescriptors/{channel_descriptor}' + 'organizations/{organization}/alertPolicies/{alert_policy}', ), + organizationAlertPolicyConditionPathTemplate: + new this._gaxModule.PathTemplate( + 'organizations/{organization}/alertPolicies/{alert_policy}/conditions/{condition}', + ), + organizationChannelDescriptorPathTemplate: + new this._gaxModule.PathTemplate( + 'organizations/{organization}/notificationChannelDescriptors/{channel_descriptor}', + ), organizationGroupPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/groups/{group}' - ), - organizationMetricDescriptorPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/metricDescriptors/{metric_descriptor=**}' - ), - organizationMonitoredResourceDescriptorPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/monitoredResourceDescriptors/{monitored_resource_descriptor}' - ), - organizationNotificationChannelPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/notificationChannels/{notification_channel}' + 'organizations/{organization}/groups/{group}', ), + organizationMetricDescriptorPathTemplate: + new this._gaxModule.PathTemplate( + 'organizations/{organization}/metricDescriptors/{metric_descriptor=**}', + ), + organizationMonitoredResourceDescriptorPathTemplate: + new this._gaxModule.PathTemplate( + 'organizations/{organization}/monitoredResourceDescriptors/{monitored_resource_descriptor}', + ), + organizationNotificationChannelPathTemplate: + new this._gaxModule.PathTemplate( + 'organizations/{organization}/notificationChannels/{notification_channel}', + ), organizationServicePathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/services/{service}' - ), - organizationServiceServiceLevelObjectivePathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/services/{service}/serviceLevelObjectives/{service_level_objective}' - ), - organizationUptimeCheckConfigPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/uptimeCheckConfigs/{uptime_check_config}' + 'organizations/{organization}/services/{service}', ), + organizationServiceServiceLevelObjectivePathTemplate: + new this._gaxModule.PathTemplate( + 'organizations/{organization}/services/{service}/serviceLevelObjectives/{service_level_objective}', + ), + organizationUptimeCheckConfigPathTemplate: + new this._gaxModule.PathTemplate( + 'organizations/{organization}/uptimeCheckConfigs/{uptime_check_config}', + ), projectAlertPolicyPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/alertPolicies/{alert_policy}' + 'projects/{project}/alertPolicies/{alert_policy}', ), projectAlertPolicyConditionPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/alertPolicies/{alert_policy}/conditions/{condition}' + 'projects/{project}/alertPolicies/{alert_policy}/conditions/{condition}', ), projectChannelDescriptorPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/notificationChannelDescriptors/{channel_descriptor}' + 'projects/{project}/notificationChannelDescriptors/{channel_descriptor}', ), projectGroupPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/groups/{group}' + 'projects/{project}/groups/{group}', ), projectMetricDescriptorPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/metricDescriptors/{metric_descriptor=**}' - ), - projectMonitoredResourceDescriptorPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/monitoredResourceDescriptors/{monitored_resource_descriptor}' + 'projects/{project}/metricDescriptors/{metric_descriptor=**}', ), + projectMonitoredResourceDescriptorPathTemplate: + new this._gaxModule.PathTemplate( + 'projects/{project}/monitoredResourceDescriptors/{monitored_resource_descriptor}', + ), projectNotificationChannelPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/notificationChannels/{notification_channel}' + 'projects/{project}/notificationChannels/{notification_channel}', ), projectServicePathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/services/{service}' - ), - projectServiceServiceLevelObjectivePathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/services/{service}/serviceLevelObjectives/{service_level_objective}' + 'projects/{project}/services/{service}', ), + projectServiceServiceLevelObjectivePathTemplate: + new this._gaxModule.PathTemplate( + 'projects/{project}/services/{service}/serviceLevelObjectives/{service_level_objective}', + ), projectUptimeCheckConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/uptimeCheckConfigs/{uptime_check_config}' + 'projects/{project}/uptimeCheckConfigs/{uptime_check_config}', ), }; @@ -271,18 +307,30 @@ export class MetricServiceClient { // (e.g. 50 results at a time, with tokens to get subsequent // pages). Denote the keys used for pagination and results. this.descriptors.page = { - listMonitoredResourceDescriptors: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'resourceDescriptors'), - listMetricDescriptors: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'metricDescriptors'), - listTimeSeries: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'timeSeries') + listMonitoredResourceDescriptors: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'resourceDescriptors', + ), + listMetricDescriptors: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'metricDescriptors', + ), + listTimeSeries: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'timeSeries', + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.monitoring.v3.MetricService', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.monitoring.v3.MetricService', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + { 'x-goog-api-client': clientHeader.join(' ') }, + ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -313,37 +361,49 @@ export class MetricServiceClient { // Put together the "service stub" for // google.monitoring.v3.MetricService. this.metricServiceStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.monitoring.v3.MetricService') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.monitoring.v3.MetricService', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.monitoring.v3.MetricService, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts, + this._providedCustomServicePath, + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const metricServiceStubMethods = - ['listMonitoredResourceDescriptors', 'getMonitoredResourceDescriptor', 'listMetricDescriptors', 'getMetricDescriptor', 'createMetricDescriptor', 'deleteMetricDescriptor', 'listTimeSeries', 'createTimeSeries']; + const metricServiceStubMethods = [ + 'listMonitoredResourceDescriptors', + 'getMonitoredResourceDescriptor', + 'listMetricDescriptors', + 'getMetricDescriptor', + 'createMetricDescriptor', + 'deleteMetricDescriptor', + 'listTimeSeries', + 'createTimeSeries', + ]; for (const methodName of metricServiceStubMethods) { const callPromise = this.metricServiceStub.then( - stub => (...args: Array<{}>) => { - if (this._terminated) { - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error|null|undefined) => () => { + (stub) => + (...args: Array<{}>) => { + if (this._terminated) { + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { throw err; - }); + }, + ); - const descriptor = - this.descriptors.page[methodName] || - undefined; + const descriptor = this.descriptors.page[methodName] || undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -358,8 +418,14 @@ export class MetricServiceClient { * @returns {string} The DNS address for this service. */ static get servicePath() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'monitoring.googleapis.com'; } @@ -370,8 +436,14 @@ export class MetricServiceClient { * @returns {string} The DNS address for this service. */ static get apiEndpoint() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'monitoring.googleapis.com'; } @@ -406,7 +478,7 @@ export class MetricServiceClient { 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/monitoring', 'https://www.googleapis.com/auth/monitoring.read', - 'https://www.googleapis.com/auth/monitoring.write' + 'https://www.googleapis.com/auth/monitoring.write', ]; } @@ -416,8 +488,9 @@ export class MetricServiceClient { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId(callback?: Callback): - Promise|void { + getProjectId( + callback?: Callback, + ): Promise | void { if (callback) { this.auth.getProjectId(callback); return; @@ -428,597 +501,837 @@ export class MetricServiceClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Gets a single monitored resource descriptor. This method does not require a Stackdriver account. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The monitored resource descriptor to get. The format is - * `"projects/{project_id_or_number}/monitoredResourceDescriptors/{resource_type}"`. - * The `{resource_type}` is a predefined type, such as - * `cloudsql_database`. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.api.MonitoredResourceDescriptor|MonitoredResourceDescriptor}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v3/metric_service.get_monitored_resource_descriptor.js - * region_tag:monitoring_v3_generated_MetricService_GetMonitoredResourceDescriptor_async - */ + /** + * Gets a single monitored resource descriptor. This method does not require a Stackdriver account. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The monitored resource descriptor to get. The format is + * `"projects/{project_id_or_number}/monitoredResourceDescriptors/{resource_type}"`. + * The `{resource_type}` is a predefined type, such as + * `cloudsql_database`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.api.MonitoredResourceDescriptor|MonitoredResourceDescriptor}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v3/metric_service.get_monitored_resource_descriptor.js + * region_tag:monitoring_v3_generated_MetricService_GetMonitoredResourceDescriptor_async + */ getMonitoredResourceDescriptor( - request?: protos.google.monitoring.v3.IGetMonitoredResourceDescriptorRequest, - options?: CallOptions): - Promise<[ - protos.google.api.IMonitoredResourceDescriptor, - protos.google.monitoring.v3.IGetMonitoredResourceDescriptorRequest|undefined, {}|undefined - ]>; + request?: protos.google.monitoring.v3.IGetMonitoredResourceDescriptorRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.api.IMonitoredResourceDescriptor, + ( + | protos.google.monitoring.v3.IGetMonitoredResourceDescriptorRequest + | undefined + ), + {} | undefined, + ] + >; getMonitoredResourceDescriptor( - request: protos.google.monitoring.v3.IGetMonitoredResourceDescriptorRequest, - options: CallOptions, - callback: Callback< - protos.google.api.IMonitoredResourceDescriptor, - protos.google.monitoring.v3.IGetMonitoredResourceDescriptorRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.IGetMonitoredResourceDescriptorRequest, + options: CallOptions, + callback: Callback< + protos.google.api.IMonitoredResourceDescriptor, + | protos.google.monitoring.v3.IGetMonitoredResourceDescriptorRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getMonitoredResourceDescriptor( - request: protos.google.monitoring.v3.IGetMonitoredResourceDescriptorRequest, - callback: Callback< - protos.google.api.IMonitoredResourceDescriptor, - protos.google.monitoring.v3.IGetMonitoredResourceDescriptorRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.IGetMonitoredResourceDescriptorRequest, + callback: Callback< + protos.google.api.IMonitoredResourceDescriptor, + | protos.google.monitoring.v3.IGetMonitoredResourceDescriptorRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getMonitoredResourceDescriptor( - request?: protos.google.monitoring.v3.IGetMonitoredResourceDescriptorRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.api.IMonitoredResourceDescriptor, - protos.google.monitoring.v3.IGetMonitoredResourceDescriptorRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.monitoring.v3.IGetMonitoredResourceDescriptorRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.api.IMonitoredResourceDescriptor, - protos.google.monitoring.v3.IGetMonitoredResourceDescriptorRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.api.IMonitoredResourceDescriptor, - protos.google.monitoring.v3.IGetMonitoredResourceDescriptorRequest|undefined, {}|undefined - ]>|void { + | protos.google.monitoring.v3.IGetMonitoredResourceDescriptorRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.api.IMonitoredResourceDescriptor, + | protos.google.monitoring.v3.IGetMonitoredResourceDescriptorRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.api.IMonitoredResourceDescriptor, + ( + | protos.google.monitoring.v3.IGetMonitoredResourceDescriptorRequest + | undefined + ), + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getMonitoredResourceDescriptor request %j', request); - const wrappedCallback: Callback< - protos.google.api.IMonitoredResourceDescriptor, - protos.google.monitoring.v3.IGetMonitoredResourceDescriptorRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.api.IMonitoredResourceDescriptor, + | protos.google.monitoring.v3.IGetMonitoredResourceDescriptorRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { - this._log.info('getMonitoredResourceDescriptor response %j', response); + this._log.info( + 'getMonitoredResourceDescriptor response %j', + response, + ); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getMonitoredResourceDescriptor(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.api.IMonitoredResourceDescriptor, - protos.google.monitoring.v3.IGetMonitoredResourceDescriptorRequest|undefined, - {}|undefined - ]) => { - this._log.info('getMonitoredResourceDescriptor response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getMonitoredResourceDescriptor(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.api.IMonitoredResourceDescriptor, + ( + | protos.google.monitoring.v3.IGetMonitoredResourceDescriptorRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info( + 'getMonitoredResourceDescriptor response %j', + response, + ); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Gets a single metric descriptor. This method does not require a Stackdriver account. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The metric descriptor on which to execute the request. The format is - * `"projects/{project_id_or_number}/metricDescriptors/{metric_id}"`. - * An example value of `{metric_id}` is - * `"compute.googleapis.com/instance/disk/read_bytes_count"`. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.api.MetricDescriptor|MetricDescriptor}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v3/metric_service.get_metric_descriptor.js - * region_tag:monitoring_v3_generated_MetricService_GetMetricDescriptor_async - */ + /** + * Gets a single metric descriptor. This method does not require a Stackdriver account. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The metric descriptor on which to execute the request. The format is + * `"projects/{project_id_or_number}/metricDescriptors/{metric_id}"`. + * An example value of `{metric_id}` is + * `"compute.googleapis.com/instance/disk/read_bytes_count"`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.api.MetricDescriptor|MetricDescriptor}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v3/metric_service.get_metric_descriptor.js + * region_tag:monitoring_v3_generated_MetricService_GetMetricDescriptor_async + */ getMetricDescriptor( - request?: protos.google.monitoring.v3.IGetMetricDescriptorRequest, - options?: CallOptions): - Promise<[ - protos.google.api.IMetricDescriptor, - protos.google.monitoring.v3.IGetMetricDescriptorRequest|undefined, {}|undefined - ]>; + request?: protos.google.monitoring.v3.IGetMetricDescriptorRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.api.IMetricDescriptor, + protos.google.monitoring.v3.IGetMetricDescriptorRequest | undefined, + {} | undefined, + ] + >; getMetricDescriptor( - request: protos.google.monitoring.v3.IGetMetricDescriptorRequest, - options: CallOptions, - callback: Callback< - protos.google.api.IMetricDescriptor, - protos.google.monitoring.v3.IGetMetricDescriptorRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.IGetMetricDescriptorRequest, + options: CallOptions, + callback: Callback< + protos.google.api.IMetricDescriptor, + | protos.google.monitoring.v3.IGetMetricDescriptorRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getMetricDescriptor( - request: protos.google.monitoring.v3.IGetMetricDescriptorRequest, - callback: Callback< - protos.google.api.IMetricDescriptor, - protos.google.monitoring.v3.IGetMetricDescriptorRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.IGetMetricDescriptorRequest, + callback: Callback< + protos.google.api.IMetricDescriptor, + | protos.google.monitoring.v3.IGetMetricDescriptorRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getMetricDescriptor( - request?: protos.google.monitoring.v3.IGetMetricDescriptorRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.monitoring.v3.IGetMetricDescriptorRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.api.IMetricDescriptor, - protos.google.monitoring.v3.IGetMetricDescriptorRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.api.IMetricDescriptor, - protos.google.monitoring.v3.IGetMetricDescriptorRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.api.IMetricDescriptor, - protos.google.monitoring.v3.IGetMetricDescriptorRequest|undefined, {}|undefined - ]>|void { + | protos.google.monitoring.v3.IGetMetricDescriptorRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.api.IMetricDescriptor, + | protos.google.monitoring.v3.IGetMetricDescriptorRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.api.IMetricDescriptor, + protos.google.monitoring.v3.IGetMetricDescriptorRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getMetricDescriptor request %j', request); - const wrappedCallback: Callback< - protos.google.api.IMetricDescriptor, - protos.google.monitoring.v3.IGetMetricDescriptorRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.api.IMetricDescriptor, + | protos.google.monitoring.v3.IGetMetricDescriptorRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getMetricDescriptor response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getMetricDescriptor(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.api.IMetricDescriptor, - protos.google.monitoring.v3.IGetMetricDescriptorRequest|undefined, - {}|undefined - ]) => { - this._log.info('getMetricDescriptor response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getMetricDescriptor(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.api.IMetricDescriptor, + protos.google.monitoring.v3.IGetMetricDescriptorRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getMetricDescriptor response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Creates a new metric descriptor. - * User-created metric descriptors define - * [custom metrics](/monitoring/custom-metrics). - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The project on which to execute the request. The format is - * `"projects/{project_id_or_number}"`. - * @param {google.api.MetricDescriptor} request.metricDescriptor - * Required. The new [custom metric](/monitoring/custom-metrics) - * descriptor. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.api.MetricDescriptor|MetricDescriptor}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v3/metric_service.create_metric_descriptor.js - * region_tag:monitoring_v3_generated_MetricService_CreateMetricDescriptor_async - */ + /** + * Creates a new metric descriptor. + * User-created metric descriptors define + * [custom metrics](/monitoring/custom-metrics). + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The project on which to execute the request. The format is + * `"projects/{project_id_or_number}"`. + * @param {google.api.MetricDescriptor} request.metricDescriptor + * Required. The new [custom metric](/monitoring/custom-metrics) + * descriptor. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.api.MetricDescriptor|MetricDescriptor}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v3/metric_service.create_metric_descriptor.js + * region_tag:monitoring_v3_generated_MetricService_CreateMetricDescriptor_async + */ createMetricDescriptor( - request?: protos.google.monitoring.v3.ICreateMetricDescriptorRequest, - options?: CallOptions): - Promise<[ - protos.google.api.IMetricDescriptor, - protos.google.monitoring.v3.ICreateMetricDescriptorRequest|undefined, {}|undefined - ]>; + request?: protos.google.monitoring.v3.ICreateMetricDescriptorRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.api.IMetricDescriptor, + protos.google.monitoring.v3.ICreateMetricDescriptorRequest | undefined, + {} | undefined, + ] + >; createMetricDescriptor( - request: protos.google.monitoring.v3.ICreateMetricDescriptorRequest, - options: CallOptions, - callback: Callback< - protos.google.api.IMetricDescriptor, - protos.google.monitoring.v3.ICreateMetricDescriptorRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.ICreateMetricDescriptorRequest, + options: CallOptions, + callback: Callback< + protos.google.api.IMetricDescriptor, + | protos.google.monitoring.v3.ICreateMetricDescriptorRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createMetricDescriptor( - request: protos.google.monitoring.v3.ICreateMetricDescriptorRequest, - callback: Callback< - protos.google.api.IMetricDescriptor, - protos.google.monitoring.v3.ICreateMetricDescriptorRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.ICreateMetricDescriptorRequest, + callback: Callback< + protos.google.api.IMetricDescriptor, + | protos.google.monitoring.v3.ICreateMetricDescriptorRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createMetricDescriptor( - request?: protos.google.monitoring.v3.ICreateMetricDescriptorRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.api.IMetricDescriptor, - protos.google.monitoring.v3.ICreateMetricDescriptorRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.monitoring.v3.ICreateMetricDescriptorRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.api.IMetricDescriptor, - protos.google.monitoring.v3.ICreateMetricDescriptorRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.api.IMetricDescriptor, - protos.google.monitoring.v3.ICreateMetricDescriptorRequest|undefined, {}|undefined - ]>|void { + | protos.google.monitoring.v3.ICreateMetricDescriptorRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.api.IMetricDescriptor, + | protos.google.monitoring.v3.ICreateMetricDescriptorRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.api.IMetricDescriptor, + protos.google.monitoring.v3.ICreateMetricDescriptorRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('createMetricDescriptor request %j', request); - const wrappedCallback: Callback< - protos.google.api.IMetricDescriptor, - protos.google.monitoring.v3.ICreateMetricDescriptorRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.api.IMetricDescriptor, + | protos.google.monitoring.v3.ICreateMetricDescriptorRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createMetricDescriptor response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.createMetricDescriptor(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.api.IMetricDescriptor, - protos.google.monitoring.v3.ICreateMetricDescriptorRequest|undefined, - {}|undefined - ]) => { - this._log.info('createMetricDescriptor response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createMetricDescriptor(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.api.IMetricDescriptor, + ( + | protos.google.monitoring.v3.ICreateMetricDescriptorRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('createMetricDescriptor response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Deletes a metric descriptor. Only user-created - * [custom metrics](/monitoring/custom-metrics) can be deleted. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The metric descriptor on which to execute the request. The format is - * `"projects/{project_id_or_number}/metricDescriptors/{metric_id}"`. - * An example of `{metric_id}` is: - * `"custom.googleapis.com/my_test_metric"`. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v3/metric_service.delete_metric_descriptor.js - * region_tag:monitoring_v3_generated_MetricService_DeleteMetricDescriptor_async - */ + /** + * Deletes a metric descriptor. Only user-created + * [custom metrics](/monitoring/custom-metrics) can be deleted. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The metric descriptor on which to execute the request. The format is + * `"projects/{project_id_or_number}/metricDescriptors/{metric_id}"`. + * An example of `{metric_id}` is: + * `"custom.googleapis.com/my_test_metric"`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v3/metric_service.delete_metric_descriptor.js + * region_tag:monitoring_v3_generated_MetricService_DeleteMetricDescriptor_async + */ deleteMetricDescriptor( - request?: protos.google.monitoring.v3.IDeleteMetricDescriptorRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.IDeleteMetricDescriptorRequest|undefined, {}|undefined - ]>; + request?: protos.google.monitoring.v3.IDeleteMetricDescriptorRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.monitoring.v3.IDeleteMetricDescriptorRequest | undefined, + {} | undefined, + ] + >; deleteMetricDescriptor( - request: protos.google.monitoring.v3.IDeleteMetricDescriptorRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.IDeleteMetricDescriptorRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.IDeleteMetricDescriptorRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.monitoring.v3.IDeleteMetricDescriptorRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteMetricDescriptor( - request: protos.google.monitoring.v3.IDeleteMetricDescriptorRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.IDeleteMetricDescriptorRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.IDeleteMetricDescriptorRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.monitoring.v3.IDeleteMetricDescriptorRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteMetricDescriptor( - request?: protos.google.monitoring.v3.IDeleteMetricDescriptorRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.IDeleteMetricDescriptorRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.monitoring.v3.IDeleteMetricDescriptorRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.IDeleteMetricDescriptorRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.IDeleteMetricDescriptorRequest|undefined, {}|undefined - ]>|void { + | protos.google.monitoring.v3.IDeleteMetricDescriptorRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + | protos.google.monitoring.v3.IDeleteMetricDescriptorRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.monitoring.v3.IDeleteMetricDescriptorRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('deleteMetricDescriptor request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.IDeleteMetricDescriptorRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.monitoring.v3.IDeleteMetricDescriptorRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteMetricDescriptor response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.deleteMetricDescriptor(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.IDeleteMetricDescriptorRequest|undefined, - {}|undefined - ]) => { - this._log.info('deleteMetricDescriptor response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteMetricDescriptor(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + ( + | protos.google.monitoring.v3.IDeleteMetricDescriptorRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('deleteMetricDescriptor response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Creates or adds data to one or more time series. - * The response is empty if all time series in the request were written. - * If any time series could not be written, a corresponding failure message is - * included in the error response. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The project on which to execute the request. The format is - * `"projects/{project_id_or_number}"`. - * @param {number[]} request.timeSeries - * Required. The new data to be added to a list of time series. - * Adds at most one data point to each of several time series. The new data - * point must be more recent than any other point in its time series. Each - * `TimeSeries` value must fully specify a unique time series by supplying - * all label values for the metric and the monitored resource. - * - * The maximum number of `TimeSeries` objects per `Create` request is 200. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v3/metric_service.create_time_series.js - * region_tag:monitoring_v3_generated_MetricService_CreateTimeSeries_async - */ + /** + * Creates or adds data to one or more time series. + * The response is empty if all time series in the request were written. + * If any time series could not be written, a corresponding failure message is + * included in the error response. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The project on which to execute the request. The format is + * `"projects/{project_id_or_number}"`. + * @param {number[]} request.timeSeries + * Required. The new data to be added to a list of time series. + * Adds at most one data point to each of several time series. The new data + * point must be more recent than any other point in its time series. Each + * `TimeSeries` value must fully specify a unique time series by supplying + * all label values for the metric and the monitored resource. + * + * The maximum number of `TimeSeries` objects per `Create` request is 200. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v3/metric_service.create_time_series.js + * region_tag:monitoring_v3_generated_MetricService_CreateTimeSeries_async + */ createTimeSeries( - request?: protos.google.monitoring.v3.ICreateTimeSeriesRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.ICreateTimeSeriesRequest|undefined, {}|undefined - ]>; + request?: protos.google.monitoring.v3.ICreateTimeSeriesRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.monitoring.v3.ICreateTimeSeriesRequest | undefined, + {} | undefined, + ] + >; createTimeSeries( - request: protos.google.monitoring.v3.ICreateTimeSeriesRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.ICreateTimeSeriesRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.ICreateTimeSeriesRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.monitoring.v3.ICreateTimeSeriesRequest | null | undefined, + {} | null | undefined + >, + ): void; createTimeSeries( - request: protos.google.monitoring.v3.ICreateTimeSeriesRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.ICreateTimeSeriesRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.ICreateTimeSeriesRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.monitoring.v3.ICreateTimeSeriesRequest | null | undefined, + {} | null | undefined + >, + ): void; createTimeSeries( - request?: protos.google.monitoring.v3.ICreateTimeSeriesRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.monitoring.v3.ICreateTimeSeriesRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.ICreateTimeSeriesRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.ICreateTimeSeriesRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.ICreateTimeSeriesRequest|undefined, {}|undefined - ]>|void { + | protos.google.monitoring.v3.ICreateTimeSeriesRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + protos.google.monitoring.v3.ICreateTimeSeriesRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.monitoring.v3.ICreateTimeSeriesRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('createTimeSeries request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.ICreateTimeSeriesRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.monitoring.v3.ICreateTimeSeriesRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createTimeSeries response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.createTimeSeries(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.ICreateTimeSeriesRequest|undefined, - {}|undefined - ]) => { - this._log.info('createTimeSeries response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createTimeSeries(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.monitoring.v3.ICreateTimeSeriesRequest | undefined, + {} | undefined, + ]) => { + this._log.info('createTimeSeries response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } - /** - * Lists monitored resource descriptors that match a filter. This method does not require a Stackdriver account. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The project on which to execute the request. The format is - * `"projects/{project_id_or_number}"`. - * @param {string} request.filter - * An optional [filter](/monitoring/api/v3/filters) describing - * the descriptors to be returned. The filter can reference - * the descriptor's type and labels. For example, the - * following filter returns only Google Compute Engine descriptors - * that have an `id` label: - * - * resource.type = starts_with("gce_") AND resource.label:id - * @param {number} request.pageSize - * A positive number that is the maximum number of results to return. - * @param {string} request.pageToken - * If this field is not empty then it must contain the `nextPageToken` value - * returned by a previous call to this method. Using this field causes the - * method to return additional results from the previous method call. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.api.MonitoredResourceDescriptor|MonitoredResourceDescriptor}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `listMonitoredResourceDescriptorsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Lists monitored resource descriptors that match a filter. This method does not require a Stackdriver account. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The project on which to execute the request. The format is + * `"projects/{project_id_or_number}"`. + * @param {string} request.filter + * An optional [filter](/monitoring/api/v3/filters) describing + * the descriptors to be returned. The filter can reference + * the descriptor's type and labels. For example, the + * following filter returns only Google Compute Engine descriptors + * that have an `id` label: + * + * resource.type = starts_with("gce_") AND resource.label:id + * @param {number} request.pageSize + * A positive number that is the maximum number of results to return. + * @param {string} request.pageToken + * If this field is not empty then it must contain the `nextPageToken` value + * returned by a previous call to this method. Using this field causes the + * method to return additional results from the previous method call. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.api.MonitoredResourceDescriptor|MonitoredResourceDescriptor}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listMonitoredResourceDescriptorsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listMonitoredResourceDescriptors( - request?: protos.google.monitoring.v3.IListMonitoredResourceDescriptorsRequest, - options?: CallOptions): - Promise<[ - protos.google.api.IMonitoredResourceDescriptor[], - protos.google.monitoring.v3.IListMonitoredResourceDescriptorsRequest|null, - protos.google.monitoring.v3.IListMonitoredResourceDescriptorsResponse - ]>; + request?: protos.google.monitoring.v3.IListMonitoredResourceDescriptorsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.api.IMonitoredResourceDescriptor[], + protos.google.monitoring.v3.IListMonitoredResourceDescriptorsRequest | null, + protos.google.monitoring.v3.IListMonitoredResourceDescriptorsResponse, + ] + >; listMonitoredResourceDescriptors( - request: protos.google.monitoring.v3.IListMonitoredResourceDescriptorsRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.monitoring.v3.IListMonitoredResourceDescriptorsRequest, - protos.google.monitoring.v3.IListMonitoredResourceDescriptorsResponse|null|undefined, - protos.google.api.IMonitoredResourceDescriptor>): void; + request: protos.google.monitoring.v3.IListMonitoredResourceDescriptorsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.monitoring.v3.IListMonitoredResourceDescriptorsRequest, + | protos.google.monitoring.v3.IListMonitoredResourceDescriptorsResponse + | null + | undefined, + protos.google.api.IMonitoredResourceDescriptor + >, + ): void; listMonitoredResourceDescriptors( - request: protos.google.monitoring.v3.IListMonitoredResourceDescriptorsRequest, - callback: PaginationCallback< - protos.google.monitoring.v3.IListMonitoredResourceDescriptorsRequest, - protos.google.monitoring.v3.IListMonitoredResourceDescriptorsResponse|null|undefined, - protos.google.api.IMonitoredResourceDescriptor>): void; + request: protos.google.monitoring.v3.IListMonitoredResourceDescriptorsRequest, + callback: PaginationCallback< + protos.google.monitoring.v3.IListMonitoredResourceDescriptorsRequest, + | protos.google.monitoring.v3.IListMonitoredResourceDescriptorsResponse + | null + | undefined, + protos.google.api.IMonitoredResourceDescriptor + >, + ): void; listMonitoredResourceDescriptors( - request?: protos.google.monitoring.v3.IListMonitoredResourceDescriptorsRequest, - optionsOrCallback?: CallOptions|PaginationCallback< + request?: protos.google.monitoring.v3.IListMonitoredResourceDescriptorsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.monitoring.v3.IListMonitoredResourceDescriptorsRequest, - protos.google.monitoring.v3.IListMonitoredResourceDescriptorsResponse|null|undefined, - protos.google.api.IMonitoredResourceDescriptor>, - callback?: PaginationCallback< - protos.google.monitoring.v3.IListMonitoredResourceDescriptorsRequest, - protos.google.monitoring.v3.IListMonitoredResourceDescriptorsResponse|null|undefined, - protos.google.api.IMonitoredResourceDescriptor>): - Promise<[ - protos.google.api.IMonitoredResourceDescriptor[], - protos.google.monitoring.v3.IListMonitoredResourceDescriptorsRequest|null, - protos.google.monitoring.v3.IListMonitoredResourceDescriptorsResponse - ]>|void { + | protos.google.monitoring.v3.IListMonitoredResourceDescriptorsResponse + | null + | undefined, + protos.google.api.IMonitoredResourceDescriptor + >, + callback?: PaginationCallback< + protos.google.monitoring.v3.IListMonitoredResourceDescriptorsRequest, + | protos.google.monitoring.v3.IListMonitoredResourceDescriptorsResponse + | null + | undefined, + protos.google.api.IMonitoredResourceDescriptor + >, + ): Promise< + [ + protos.google.api.IMonitoredResourceDescriptor[], + protos.google.monitoring.v3.IListMonitoredResourceDescriptorsRequest | null, + protos.google.monitoring.v3.IListMonitoredResourceDescriptorsResponse, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.monitoring.v3.IListMonitoredResourceDescriptorsRequest, - protos.google.monitoring.v3.IListMonitoredResourceDescriptorsResponse|null|undefined, - protos.google.api.IMonitoredResourceDescriptor>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.monitoring.v3.IListMonitoredResourceDescriptorsRequest, + | protos.google.monitoring.v3.IListMonitoredResourceDescriptorsResponse + | null + | undefined, + protos.google.api.IMonitoredResourceDescriptor + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listMonitoredResourceDescriptors values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -1027,223 +1340,257 @@ export class MetricServiceClient { this._log.info('listMonitoredResourceDescriptors request %j', request); return this.innerApiCalls .listMonitoredResourceDescriptors(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.api.IMonitoredResourceDescriptor[], - protos.google.monitoring.v3.IListMonitoredResourceDescriptorsRequest|null, - protos.google.monitoring.v3.IListMonitoredResourceDescriptorsResponse - ]) => { - this._log.info('listMonitoredResourceDescriptors values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.api.IMonitoredResourceDescriptor[], + protos.google.monitoring.v3.IListMonitoredResourceDescriptorsRequest | null, + protos.google.monitoring.v3.IListMonitoredResourceDescriptorsResponse, + ]) => { + this._log.info( + 'listMonitoredResourceDescriptors values %j', + response, + ); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listMonitoredResourceDescriptors`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The project on which to execute the request. The format is - * `"projects/{project_id_or_number}"`. - * @param {string} request.filter - * An optional [filter](/monitoring/api/v3/filters) describing - * the descriptors to be returned. The filter can reference - * the descriptor's type and labels. For example, the - * following filter returns only Google Compute Engine descriptors - * that have an `id` label: - * - * resource.type = starts_with("gce_") AND resource.label:id - * @param {number} request.pageSize - * A positive number that is the maximum number of results to return. - * @param {string} request.pageToken - * If this field is not empty then it must contain the `nextPageToken` value - * returned by a previous call to this method. Using this field causes the - * method to return additional results from the previous method call. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.api.MonitoredResourceDescriptor|MonitoredResourceDescriptor} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `listMonitoredResourceDescriptorsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `listMonitoredResourceDescriptors`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The project on which to execute the request. The format is + * `"projects/{project_id_or_number}"`. + * @param {string} request.filter + * An optional [filter](/monitoring/api/v3/filters) describing + * the descriptors to be returned. The filter can reference + * the descriptor's type and labels. For example, the + * following filter returns only Google Compute Engine descriptors + * that have an `id` label: + * + * resource.type = starts_with("gce_") AND resource.label:id + * @param {number} request.pageSize + * A positive number that is the maximum number of results to return. + * @param {string} request.pageToken + * If this field is not empty then it must contain the `nextPageToken` value + * returned by a previous call to this method. Using this field causes the + * method to return additional results from the previous method call. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.api.MonitoredResourceDescriptor|MonitoredResourceDescriptor} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listMonitoredResourceDescriptorsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listMonitoredResourceDescriptorsStream( - request?: protos.google.monitoring.v3.IListMonitoredResourceDescriptorsRequest, - options?: CallOptions): - Transform{ + request?: protos.google.monitoring.v3.IListMonitoredResourceDescriptorsRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', - }); - const defaultCallSettings = this._defaults['listMonitoredResourceDescriptors']; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + const defaultCallSettings = + this._defaults['listMonitoredResourceDescriptors']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listMonitoredResourceDescriptors stream %j', request); return this.descriptors.page.listMonitoredResourceDescriptors.createStream( this.innerApiCalls.listMonitoredResourceDescriptors as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listMonitoredResourceDescriptors`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The project on which to execute the request. The format is - * `"projects/{project_id_or_number}"`. - * @param {string} request.filter - * An optional [filter](/monitoring/api/v3/filters) describing - * the descriptors to be returned. The filter can reference - * the descriptor's type and labels. For example, the - * following filter returns only Google Compute Engine descriptors - * that have an `id` label: - * - * resource.type = starts_with("gce_") AND resource.label:id - * @param {number} request.pageSize - * A positive number that is the maximum number of results to return. - * @param {string} request.pageToken - * If this field is not empty then it must contain the `nextPageToken` value - * returned by a previous call to this method. Using this field causes the - * method to return additional results from the previous method call. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.api.MonitoredResourceDescriptor|MonitoredResourceDescriptor}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v3/metric_service.list_monitored_resource_descriptors.js - * region_tag:monitoring_v3_generated_MetricService_ListMonitoredResourceDescriptors_async - */ + /** + * Equivalent to `listMonitoredResourceDescriptors`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The project on which to execute the request. The format is + * `"projects/{project_id_or_number}"`. + * @param {string} request.filter + * An optional [filter](/monitoring/api/v3/filters) describing + * the descriptors to be returned. The filter can reference + * the descriptor's type and labels. For example, the + * following filter returns only Google Compute Engine descriptors + * that have an `id` label: + * + * resource.type = starts_with("gce_") AND resource.label:id + * @param {number} request.pageSize + * A positive number that is the maximum number of results to return. + * @param {string} request.pageToken + * If this field is not empty then it must contain the `nextPageToken` value + * returned by a previous call to this method. Using this field causes the + * method to return additional results from the previous method call. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.api.MonitoredResourceDescriptor|MonitoredResourceDescriptor}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v3/metric_service.list_monitored_resource_descriptors.js + * region_tag:monitoring_v3_generated_MetricService_ListMonitoredResourceDescriptors_async + */ listMonitoredResourceDescriptorsAsync( - request?: protos.google.monitoring.v3.IListMonitoredResourceDescriptorsRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.monitoring.v3.IListMonitoredResourceDescriptorsRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', - }); - const defaultCallSettings = this._defaults['listMonitoredResourceDescriptors']; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + const defaultCallSettings = + this._defaults['listMonitoredResourceDescriptors']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listMonitoredResourceDescriptors iterate %j', request); return this.descriptors.page.listMonitoredResourceDescriptors.asyncIterate( this.innerApiCalls['listMonitoredResourceDescriptors'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } - /** - * Lists metric descriptors that match a filter. This method does not require a Stackdriver account. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The project on which to execute the request. The format is - * `"projects/{project_id_or_number}"`. - * @param {string} request.filter - * If this field is empty, all custom and - * system-defined metric descriptors are returned. - * Otherwise, the [filter](/monitoring/api/v3/filters) - * specifies which metric descriptors are to be - * returned. For example, the following filter matches all - * [custom metrics](/monitoring/custom-metrics): - * - * metric.type = starts_with("custom.googleapis.com/") - * @param {number} request.pageSize - * A positive number that is the maximum number of results to return. - * @param {string} request.pageToken - * If this field is not empty then it must contain the `nextPageToken` value - * returned by a previous call to this method. Using this field causes the - * method to return additional results from the previous method call. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.api.MetricDescriptor|MetricDescriptor}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `listMetricDescriptorsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Lists metric descriptors that match a filter. This method does not require a Stackdriver account. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The project on which to execute the request. The format is + * `"projects/{project_id_or_number}"`. + * @param {string} request.filter + * If this field is empty, all custom and + * system-defined metric descriptors are returned. + * Otherwise, the [filter](/monitoring/api/v3/filters) + * specifies which metric descriptors are to be + * returned. For example, the following filter matches all + * [custom metrics](/monitoring/custom-metrics): + * + * metric.type = starts_with("custom.googleapis.com/") + * @param {number} request.pageSize + * A positive number that is the maximum number of results to return. + * @param {string} request.pageToken + * If this field is not empty then it must contain the `nextPageToken` value + * returned by a previous call to this method. Using this field causes the + * method to return additional results from the previous method call. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.api.MetricDescriptor|MetricDescriptor}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listMetricDescriptorsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listMetricDescriptors( - request?: protos.google.monitoring.v3.IListMetricDescriptorsRequest, - options?: CallOptions): - Promise<[ - protos.google.api.IMetricDescriptor[], - protos.google.monitoring.v3.IListMetricDescriptorsRequest|null, - protos.google.monitoring.v3.IListMetricDescriptorsResponse - ]>; + request?: protos.google.monitoring.v3.IListMetricDescriptorsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.api.IMetricDescriptor[], + protos.google.monitoring.v3.IListMetricDescriptorsRequest | null, + protos.google.monitoring.v3.IListMetricDescriptorsResponse, + ] + >; listMetricDescriptors( - request: protos.google.monitoring.v3.IListMetricDescriptorsRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.monitoring.v3.IListMetricDescriptorsRequest, - protos.google.monitoring.v3.IListMetricDescriptorsResponse|null|undefined, - protos.google.api.IMetricDescriptor>): void; + request: protos.google.monitoring.v3.IListMetricDescriptorsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.monitoring.v3.IListMetricDescriptorsRequest, + | protos.google.monitoring.v3.IListMetricDescriptorsResponse + | null + | undefined, + protos.google.api.IMetricDescriptor + >, + ): void; listMetricDescriptors( - request: protos.google.monitoring.v3.IListMetricDescriptorsRequest, - callback: PaginationCallback< - protos.google.monitoring.v3.IListMetricDescriptorsRequest, - protos.google.monitoring.v3.IListMetricDescriptorsResponse|null|undefined, - protos.google.api.IMetricDescriptor>): void; + request: protos.google.monitoring.v3.IListMetricDescriptorsRequest, + callback: PaginationCallback< + protos.google.monitoring.v3.IListMetricDescriptorsRequest, + | protos.google.monitoring.v3.IListMetricDescriptorsResponse + | null + | undefined, + protos.google.api.IMetricDescriptor + >, + ): void; listMetricDescriptors( - request?: protos.google.monitoring.v3.IListMetricDescriptorsRequest, - optionsOrCallback?: CallOptions|PaginationCallback< - protos.google.monitoring.v3.IListMetricDescriptorsRequest, - protos.google.monitoring.v3.IListMetricDescriptorsResponse|null|undefined, - protos.google.api.IMetricDescriptor>, - callback?: PaginationCallback< + request?: protos.google.monitoring.v3.IListMetricDescriptorsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.monitoring.v3.IListMetricDescriptorsRequest, - protos.google.monitoring.v3.IListMetricDescriptorsResponse|null|undefined, - protos.google.api.IMetricDescriptor>): - Promise<[ - protos.google.api.IMetricDescriptor[], - protos.google.monitoring.v3.IListMetricDescriptorsRequest|null, - protos.google.monitoring.v3.IListMetricDescriptorsResponse - ]>|void { + | protos.google.monitoring.v3.IListMetricDescriptorsResponse + | null + | undefined, + protos.google.api.IMetricDescriptor + >, + callback?: PaginationCallback< + protos.google.monitoring.v3.IListMetricDescriptorsRequest, + | protos.google.monitoring.v3.IListMetricDescriptorsResponse + | null + | undefined, + protos.google.api.IMetricDescriptor + >, + ): Promise< + [ + protos.google.api.IMetricDescriptor[], + protos.google.monitoring.v3.IListMetricDescriptorsRequest | null, + protos.google.monitoring.v3.IListMetricDescriptorsResponse, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.monitoring.v3.IListMetricDescriptorsRequest, - protos.google.monitoring.v3.IListMetricDescriptorsResponse|null|undefined, - protos.google.api.IMetricDescriptor>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.monitoring.v3.IListMetricDescriptorsRequest, + | protos.google.monitoring.v3.IListMetricDescriptorsResponse + | null + | undefined, + protos.google.api.IMetricDescriptor + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listMetricDescriptors values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -1252,243 +1599,266 @@ export class MetricServiceClient { this._log.info('listMetricDescriptors request %j', request); return this.innerApiCalls .listMetricDescriptors(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.api.IMetricDescriptor[], - protos.google.monitoring.v3.IListMetricDescriptorsRequest|null, - protos.google.monitoring.v3.IListMetricDescriptorsResponse - ]) => { - this._log.info('listMetricDescriptors values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.api.IMetricDescriptor[], + protos.google.monitoring.v3.IListMetricDescriptorsRequest | null, + protos.google.monitoring.v3.IListMetricDescriptorsResponse, + ]) => { + this._log.info('listMetricDescriptors values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listMetricDescriptors`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The project on which to execute the request. The format is - * `"projects/{project_id_or_number}"`. - * @param {string} request.filter - * If this field is empty, all custom and - * system-defined metric descriptors are returned. - * Otherwise, the [filter](/monitoring/api/v3/filters) - * specifies which metric descriptors are to be - * returned. For example, the following filter matches all - * [custom metrics](/monitoring/custom-metrics): - * - * metric.type = starts_with("custom.googleapis.com/") - * @param {number} request.pageSize - * A positive number that is the maximum number of results to return. - * @param {string} request.pageToken - * If this field is not empty then it must contain the `nextPageToken` value - * returned by a previous call to this method. Using this field causes the - * method to return additional results from the previous method call. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.api.MetricDescriptor|MetricDescriptor} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `listMetricDescriptorsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `listMetricDescriptors`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The project on which to execute the request. The format is + * `"projects/{project_id_or_number}"`. + * @param {string} request.filter + * If this field is empty, all custom and + * system-defined metric descriptors are returned. + * Otherwise, the [filter](/monitoring/api/v3/filters) + * specifies which metric descriptors are to be + * returned. For example, the following filter matches all + * [custom metrics](/monitoring/custom-metrics): + * + * metric.type = starts_with("custom.googleapis.com/") + * @param {number} request.pageSize + * A positive number that is the maximum number of results to return. + * @param {string} request.pageToken + * If this field is not empty then it must contain the `nextPageToken` value + * returned by a previous call to this method. Using this field causes the + * method to return additional results from the previous method call. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.api.MetricDescriptor|MetricDescriptor} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listMetricDescriptorsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listMetricDescriptorsStream( - request?: protos.google.monitoring.v3.IListMetricDescriptorsRequest, - options?: CallOptions): - Transform{ + request?: protos.google.monitoring.v3.IListMetricDescriptorsRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); const defaultCallSettings = this._defaults['listMetricDescriptors']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listMetricDescriptors stream %j', request); return this.descriptors.page.listMetricDescriptors.createStream( this.innerApiCalls.listMetricDescriptors as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listMetricDescriptors`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The project on which to execute the request. The format is - * `"projects/{project_id_or_number}"`. - * @param {string} request.filter - * If this field is empty, all custom and - * system-defined metric descriptors are returned. - * Otherwise, the [filter](/monitoring/api/v3/filters) - * specifies which metric descriptors are to be - * returned. For example, the following filter matches all - * [custom metrics](/monitoring/custom-metrics): - * - * metric.type = starts_with("custom.googleapis.com/") - * @param {number} request.pageSize - * A positive number that is the maximum number of results to return. - * @param {string} request.pageToken - * If this field is not empty then it must contain the `nextPageToken` value - * returned by a previous call to this method. Using this field causes the - * method to return additional results from the previous method call. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.api.MetricDescriptor|MetricDescriptor}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v3/metric_service.list_metric_descriptors.js - * region_tag:monitoring_v3_generated_MetricService_ListMetricDescriptors_async - */ + /** + * Equivalent to `listMetricDescriptors`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The project on which to execute the request. The format is + * `"projects/{project_id_or_number}"`. + * @param {string} request.filter + * If this field is empty, all custom and + * system-defined metric descriptors are returned. + * Otherwise, the [filter](/monitoring/api/v3/filters) + * specifies which metric descriptors are to be + * returned. For example, the following filter matches all + * [custom metrics](/monitoring/custom-metrics): + * + * metric.type = starts_with("custom.googleapis.com/") + * @param {number} request.pageSize + * A positive number that is the maximum number of results to return. + * @param {string} request.pageToken + * If this field is not empty then it must contain the `nextPageToken` value + * returned by a previous call to this method. Using this field causes the + * method to return additional results from the previous method call. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.api.MetricDescriptor|MetricDescriptor}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v3/metric_service.list_metric_descriptors.js + * region_tag:monitoring_v3_generated_MetricService_ListMetricDescriptors_async + */ listMetricDescriptorsAsync( - request?: protos.google.monitoring.v3.IListMetricDescriptorsRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.monitoring.v3.IListMetricDescriptorsRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); const defaultCallSettings = this._defaults['listMetricDescriptors']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listMetricDescriptors iterate %j', request); return this.descriptors.page.listMetricDescriptors.asyncIterate( this.innerApiCalls['listMetricDescriptors'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } - /** - * Lists time series that match a filter. This method does not require a Stackdriver account. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The project on which to execute the request. The format is - * "projects/{project_id_or_number}". - * @param {string} request.filter - * Required. A [monitoring filter](/monitoring/api/v3/filters) that specifies which time - * series should be returned. The filter must specify a single metric type, - * and can additionally specify metric labels and other information. For - * example: - * - * metric.type = "compute.googleapis.com/instance/cpu/usage_time" AND - * metric.labels.instance_name = "my-instance-name" - * @param {google.monitoring.v3.TimeInterval} request.interval - * Required. The time interval for which results should be returned. Only time series - * that contain data points in the specified interval are included - * in the response. - * @param {google.monitoring.v3.Aggregation} request.aggregation - * Specifies the alignment of data points in individual time series as - * well as how to combine the retrieved time series across specified labels. - * - * By default (if no `aggregation` is explicitly specified), the raw time - * series data is returned. - * @param {string} request.orderBy - * Unsupported: must be left blank. The points in each time series are - * currently returned in reverse time order (most recent to oldest). - * @param {google.monitoring.v3.ListTimeSeriesRequest.TimeSeriesView} request.view - * Required. Specifies which information is returned about the time series. - * @param {number} request.pageSize - * A positive number that is the maximum number of results to return. If - * `page_size` is empty or more than 100,000 results, the effective - * `page_size` is 100,000 results. If `view` is set to `FULL`, this is the - * maximum number of `Points` returned. If `view` is set to `HEADERS`, this is - * the maximum number of `TimeSeries` returned. - * @param {string} request.pageToken - * If this field is not empty then it must contain the `nextPageToken` value - * returned by a previous call to this method. Using this field causes the - * method to return additional results from the previous method call. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.monitoring.v3.TimeSeries|TimeSeries}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `listTimeSeriesAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Lists time series that match a filter. This method does not require a Stackdriver account. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The project on which to execute the request. The format is + * "projects/{project_id_or_number}". + * @param {string} request.filter + * Required. A [monitoring filter](/monitoring/api/v3/filters) that specifies which time + * series should be returned. The filter must specify a single metric type, + * and can additionally specify metric labels and other information. For + * example: + * + * metric.type = "compute.googleapis.com/instance/cpu/usage_time" AND + * metric.labels.instance_name = "my-instance-name" + * @param {google.monitoring.v3.TimeInterval} request.interval + * Required. The time interval for which results should be returned. Only time series + * that contain data points in the specified interval are included + * in the response. + * @param {google.monitoring.v3.Aggregation} request.aggregation + * Specifies the alignment of data points in individual time series as + * well as how to combine the retrieved time series across specified labels. + * + * By default (if no `aggregation` is explicitly specified), the raw time + * series data is returned. + * @param {string} request.orderBy + * Unsupported: must be left blank. The points in each time series are + * currently returned in reverse time order (most recent to oldest). + * @param {google.monitoring.v3.ListTimeSeriesRequest.TimeSeriesView} request.view + * Required. Specifies which information is returned about the time series. + * @param {number} request.pageSize + * A positive number that is the maximum number of results to return. If + * `page_size` is empty or more than 100,000 results, the effective + * `page_size` is 100,000 results. If `view` is set to `FULL`, this is the + * maximum number of `Points` returned. If `view` is set to `HEADERS`, this is + * the maximum number of `TimeSeries` returned. + * @param {string} request.pageToken + * If this field is not empty then it must contain the `nextPageToken` value + * returned by a previous call to this method. Using this field causes the + * method to return additional results from the previous method call. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.monitoring.v3.TimeSeries|TimeSeries}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listTimeSeriesAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listTimeSeries( - request?: protos.google.monitoring.v3.IListTimeSeriesRequest, - options?: CallOptions): - Promise<[ - protos.google.monitoring.v3.ITimeSeries[], - protos.google.monitoring.v3.IListTimeSeriesRequest|null, - protos.google.monitoring.v3.IListTimeSeriesResponse - ]>; + request?: protos.google.monitoring.v3.IListTimeSeriesRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.monitoring.v3.ITimeSeries[], + protos.google.monitoring.v3.IListTimeSeriesRequest | null, + protos.google.monitoring.v3.IListTimeSeriesResponse, + ] + >; listTimeSeries( - request: protos.google.monitoring.v3.IListTimeSeriesRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.monitoring.v3.IListTimeSeriesRequest, - protos.google.monitoring.v3.IListTimeSeriesResponse|null|undefined, - protos.google.monitoring.v3.ITimeSeries>): void; + request: protos.google.monitoring.v3.IListTimeSeriesRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.monitoring.v3.IListTimeSeriesRequest, + protos.google.monitoring.v3.IListTimeSeriesResponse | null | undefined, + protos.google.monitoring.v3.ITimeSeries + >, + ): void; listTimeSeries( - request: protos.google.monitoring.v3.IListTimeSeriesRequest, - callback: PaginationCallback< - protos.google.monitoring.v3.IListTimeSeriesRequest, - protos.google.monitoring.v3.IListTimeSeriesResponse|null|undefined, - protos.google.monitoring.v3.ITimeSeries>): void; + request: protos.google.monitoring.v3.IListTimeSeriesRequest, + callback: PaginationCallback< + protos.google.monitoring.v3.IListTimeSeriesRequest, + protos.google.monitoring.v3.IListTimeSeriesResponse | null | undefined, + protos.google.monitoring.v3.ITimeSeries + >, + ): void; listTimeSeries( - request?: protos.google.monitoring.v3.IListTimeSeriesRequest, - optionsOrCallback?: CallOptions|PaginationCallback< - protos.google.monitoring.v3.IListTimeSeriesRequest, - protos.google.monitoring.v3.IListTimeSeriesResponse|null|undefined, - protos.google.monitoring.v3.ITimeSeries>, - callback?: PaginationCallback< + request?: protos.google.monitoring.v3.IListTimeSeriesRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.monitoring.v3.IListTimeSeriesRequest, - protos.google.monitoring.v3.IListTimeSeriesResponse|null|undefined, - protos.google.monitoring.v3.ITimeSeries>): - Promise<[ - protos.google.monitoring.v3.ITimeSeries[], - protos.google.monitoring.v3.IListTimeSeriesRequest|null, - protos.google.monitoring.v3.IListTimeSeriesResponse - ]>|void { + | protos.google.monitoring.v3.IListTimeSeriesResponse + | null + | undefined, + protos.google.monitoring.v3.ITimeSeries + >, + callback?: PaginationCallback< + protos.google.monitoring.v3.IListTimeSeriesRequest, + protos.google.monitoring.v3.IListTimeSeriesResponse | null | undefined, + protos.google.monitoring.v3.ITimeSeries + >, + ): Promise< + [ + protos.google.monitoring.v3.ITimeSeries[], + protos.google.monitoring.v3.IListTimeSeriesRequest | null, + protos.google.monitoring.v3.IListTimeSeriesResponse, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.monitoring.v3.IListTimeSeriesRequest, - protos.google.monitoring.v3.IListTimeSeriesResponse|null|undefined, - protos.google.monitoring.v3.ITimeSeries>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.monitoring.v3.IListTimeSeriesRequest, + | protos.google.monitoring.v3.IListTimeSeriesResponse + | null + | undefined, + protos.google.monitoring.v3.ITimeSeries + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listTimeSeries values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -1497,166 +1867,170 @@ export class MetricServiceClient { this._log.info('listTimeSeries request %j', request); return this.innerApiCalls .listTimeSeries(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.monitoring.v3.ITimeSeries[], - protos.google.monitoring.v3.IListTimeSeriesRequest|null, - protos.google.monitoring.v3.IListTimeSeriesResponse - ]) => { - this._log.info('listTimeSeries values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.monitoring.v3.ITimeSeries[], + protos.google.monitoring.v3.IListTimeSeriesRequest | null, + protos.google.monitoring.v3.IListTimeSeriesResponse, + ]) => { + this._log.info('listTimeSeries values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listTimeSeries`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The project on which to execute the request. The format is - * "projects/{project_id_or_number}". - * @param {string} request.filter - * Required. A [monitoring filter](/monitoring/api/v3/filters) that specifies which time - * series should be returned. The filter must specify a single metric type, - * and can additionally specify metric labels and other information. For - * example: - * - * metric.type = "compute.googleapis.com/instance/cpu/usage_time" AND - * metric.labels.instance_name = "my-instance-name" - * @param {google.monitoring.v3.TimeInterval} request.interval - * Required. The time interval for which results should be returned. Only time series - * that contain data points in the specified interval are included - * in the response. - * @param {google.monitoring.v3.Aggregation} request.aggregation - * Specifies the alignment of data points in individual time series as - * well as how to combine the retrieved time series across specified labels. - * - * By default (if no `aggregation` is explicitly specified), the raw time - * series data is returned. - * @param {string} request.orderBy - * Unsupported: must be left blank. The points in each time series are - * currently returned in reverse time order (most recent to oldest). - * @param {google.monitoring.v3.ListTimeSeriesRequest.TimeSeriesView} request.view - * Required. Specifies which information is returned about the time series. - * @param {number} request.pageSize - * A positive number that is the maximum number of results to return. If - * `page_size` is empty or more than 100,000 results, the effective - * `page_size` is 100,000 results. If `view` is set to `FULL`, this is the - * maximum number of `Points` returned. If `view` is set to `HEADERS`, this is - * the maximum number of `TimeSeries` returned. - * @param {string} request.pageToken - * If this field is not empty then it must contain the `nextPageToken` value - * returned by a previous call to this method. Using this field causes the - * method to return additional results from the previous method call. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.monitoring.v3.TimeSeries|TimeSeries} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `listTimeSeriesAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `listTimeSeries`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The project on which to execute the request. The format is + * "projects/{project_id_or_number}". + * @param {string} request.filter + * Required. A [monitoring filter](/monitoring/api/v3/filters) that specifies which time + * series should be returned. The filter must specify a single metric type, + * and can additionally specify metric labels and other information. For + * example: + * + * metric.type = "compute.googleapis.com/instance/cpu/usage_time" AND + * metric.labels.instance_name = "my-instance-name" + * @param {google.monitoring.v3.TimeInterval} request.interval + * Required. The time interval for which results should be returned. Only time series + * that contain data points in the specified interval are included + * in the response. + * @param {google.monitoring.v3.Aggregation} request.aggregation + * Specifies the alignment of data points in individual time series as + * well as how to combine the retrieved time series across specified labels. + * + * By default (if no `aggregation` is explicitly specified), the raw time + * series data is returned. + * @param {string} request.orderBy + * Unsupported: must be left blank. The points in each time series are + * currently returned in reverse time order (most recent to oldest). + * @param {google.monitoring.v3.ListTimeSeriesRequest.TimeSeriesView} request.view + * Required. Specifies which information is returned about the time series. + * @param {number} request.pageSize + * A positive number that is the maximum number of results to return. If + * `page_size` is empty or more than 100,000 results, the effective + * `page_size` is 100,000 results. If `view` is set to `FULL`, this is the + * maximum number of `Points` returned. If `view` is set to `HEADERS`, this is + * the maximum number of `TimeSeries` returned. + * @param {string} request.pageToken + * If this field is not empty then it must contain the `nextPageToken` value + * returned by a previous call to this method. Using this field causes the + * method to return additional results from the previous method call. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.monitoring.v3.TimeSeries|TimeSeries} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listTimeSeriesAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listTimeSeriesStream( - request?: protos.google.monitoring.v3.IListTimeSeriesRequest, - options?: CallOptions): - Transform{ + request?: protos.google.monitoring.v3.IListTimeSeriesRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); const defaultCallSettings = this._defaults['listTimeSeries']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listTimeSeries stream %j', request); return this.descriptors.page.listTimeSeries.createStream( this.innerApiCalls.listTimeSeries as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listTimeSeries`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The project on which to execute the request. The format is - * "projects/{project_id_or_number}". - * @param {string} request.filter - * Required. A [monitoring filter](/monitoring/api/v3/filters) that specifies which time - * series should be returned. The filter must specify a single metric type, - * and can additionally specify metric labels and other information. For - * example: - * - * metric.type = "compute.googleapis.com/instance/cpu/usage_time" AND - * metric.labels.instance_name = "my-instance-name" - * @param {google.monitoring.v3.TimeInterval} request.interval - * Required. The time interval for which results should be returned. Only time series - * that contain data points in the specified interval are included - * in the response. - * @param {google.monitoring.v3.Aggregation} request.aggregation - * Specifies the alignment of data points in individual time series as - * well as how to combine the retrieved time series across specified labels. - * - * By default (if no `aggregation` is explicitly specified), the raw time - * series data is returned. - * @param {string} request.orderBy - * Unsupported: must be left blank. The points in each time series are - * currently returned in reverse time order (most recent to oldest). - * @param {google.monitoring.v3.ListTimeSeriesRequest.TimeSeriesView} request.view - * Required. Specifies which information is returned about the time series. - * @param {number} request.pageSize - * A positive number that is the maximum number of results to return. If - * `page_size` is empty or more than 100,000 results, the effective - * `page_size` is 100,000 results. If `view` is set to `FULL`, this is the - * maximum number of `Points` returned. If `view` is set to `HEADERS`, this is - * the maximum number of `TimeSeries` returned. - * @param {string} request.pageToken - * If this field is not empty then it must contain the `nextPageToken` value - * returned by a previous call to this method. Using this field causes the - * method to return additional results from the previous method call. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.monitoring.v3.TimeSeries|TimeSeries}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v3/metric_service.list_time_series.js - * region_tag:monitoring_v3_generated_MetricService_ListTimeSeries_async - */ + /** + * Equivalent to `listTimeSeries`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The project on which to execute the request. The format is + * "projects/{project_id_or_number}". + * @param {string} request.filter + * Required. A [monitoring filter](/monitoring/api/v3/filters) that specifies which time + * series should be returned. The filter must specify a single metric type, + * and can additionally specify metric labels and other information. For + * example: + * + * metric.type = "compute.googleapis.com/instance/cpu/usage_time" AND + * metric.labels.instance_name = "my-instance-name" + * @param {google.monitoring.v3.TimeInterval} request.interval + * Required. The time interval for which results should be returned. Only time series + * that contain data points in the specified interval are included + * in the response. + * @param {google.monitoring.v3.Aggregation} request.aggregation + * Specifies the alignment of data points in individual time series as + * well as how to combine the retrieved time series across specified labels. + * + * By default (if no `aggregation` is explicitly specified), the raw time + * series data is returned. + * @param {string} request.orderBy + * Unsupported: must be left blank. The points in each time series are + * currently returned in reverse time order (most recent to oldest). + * @param {google.monitoring.v3.ListTimeSeriesRequest.TimeSeriesView} request.view + * Required. Specifies which information is returned about the time series. + * @param {number} request.pageSize + * A positive number that is the maximum number of results to return. If + * `page_size` is empty or more than 100,000 results, the effective + * `page_size` is 100,000 results. If `view` is set to `FULL`, this is the + * maximum number of `Points` returned. If `view` is set to `HEADERS`, this is + * the maximum number of `TimeSeries` returned. + * @param {string} request.pageToken + * If this field is not empty then it must contain the `nextPageToken` value + * returned by a previous call to this method. Using this field causes the + * method to return additional results from the previous method call. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.monitoring.v3.TimeSeries|TimeSeries}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v3/metric_service.list_time_series.js + * region_tag:monitoring_v3_generated_MetricService_ListTimeSeries_async + */ listTimeSeriesAsync( - request?: protos.google.monitoring.v3.IListTimeSeriesRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.monitoring.v3.IListTimeSeriesRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); const defaultCallSettings = this._defaults['listTimeSeries']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listTimeSeries iterate %j', request); return this.descriptors.page.listTimeSeries.asyncIterate( this.innerApiCalls['listTimeSeries'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } // -------------------- @@ -1670,7 +2044,7 @@ export class MetricServiceClient { * @param {string} alert_policy * @returns {string} Resource name string. */ - folderAlertPolicyPath(folder:string,alertPolicy:string) { + folderAlertPolicyPath(folder: string, alertPolicy: string) { return this.pathTemplates.folderAlertPolicyPathTemplate.render({ folder: folder, alert_policy: alertPolicy, @@ -1685,7 +2059,9 @@ export class MetricServiceClient { * @returns {string} A string representing the folder. */ matchFolderFromFolderAlertPolicyName(folderAlertPolicyName: string) { - return this.pathTemplates.folderAlertPolicyPathTemplate.match(folderAlertPolicyName).folder; + return this.pathTemplates.folderAlertPolicyPathTemplate.match( + folderAlertPolicyName, + ).folder; } /** @@ -1696,7 +2072,9 @@ export class MetricServiceClient { * @returns {string} A string representing the alert_policy. */ matchAlertPolicyFromFolderAlertPolicyName(folderAlertPolicyName: string) { - return this.pathTemplates.folderAlertPolicyPathTemplate.match(folderAlertPolicyName).alert_policy; + return this.pathTemplates.folderAlertPolicyPathTemplate.match( + folderAlertPolicyName, + ).alert_policy; } /** @@ -1707,7 +2085,11 @@ export class MetricServiceClient { * @param {string} condition * @returns {string} Resource name string. */ - folderAlertPolicyConditionPath(folder:string,alertPolicy:string,condition:string) { + folderAlertPolicyConditionPath( + folder: string, + alertPolicy: string, + condition: string, + ) { return this.pathTemplates.folderAlertPolicyConditionPathTemplate.render({ folder: folder, alert_policy: alertPolicy, @@ -1722,8 +2104,12 @@ export class MetricServiceClient { * A fully-qualified path representing folder_alert_policy_condition resource. * @returns {string} A string representing the folder. */ - matchFolderFromFolderAlertPolicyConditionName(folderAlertPolicyConditionName: string) { - return this.pathTemplates.folderAlertPolicyConditionPathTemplate.match(folderAlertPolicyConditionName).folder; + matchFolderFromFolderAlertPolicyConditionName( + folderAlertPolicyConditionName: string, + ) { + return this.pathTemplates.folderAlertPolicyConditionPathTemplate.match( + folderAlertPolicyConditionName, + ).folder; } /** @@ -1733,8 +2119,12 @@ export class MetricServiceClient { * A fully-qualified path representing folder_alert_policy_condition resource. * @returns {string} A string representing the alert_policy. */ - matchAlertPolicyFromFolderAlertPolicyConditionName(folderAlertPolicyConditionName: string) { - return this.pathTemplates.folderAlertPolicyConditionPathTemplate.match(folderAlertPolicyConditionName).alert_policy; + matchAlertPolicyFromFolderAlertPolicyConditionName( + folderAlertPolicyConditionName: string, + ) { + return this.pathTemplates.folderAlertPolicyConditionPathTemplate.match( + folderAlertPolicyConditionName, + ).alert_policy; } /** @@ -1744,8 +2134,12 @@ export class MetricServiceClient { * A fully-qualified path representing folder_alert_policy_condition resource. * @returns {string} A string representing the condition. */ - matchConditionFromFolderAlertPolicyConditionName(folderAlertPolicyConditionName: string) { - return this.pathTemplates.folderAlertPolicyConditionPathTemplate.match(folderAlertPolicyConditionName).condition; + matchConditionFromFolderAlertPolicyConditionName( + folderAlertPolicyConditionName: string, + ) { + return this.pathTemplates.folderAlertPolicyConditionPathTemplate.match( + folderAlertPolicyConditionName, + ).condition; } /** @@ -1755,7 +2149,7 @@ export class MetricServiceClient { * @param {string} channel_descriptor * @returns {string} Resource name string. */ - folderChannelDescriptorPath(folder:string,channelDescriptor:string) { + folderChannelDescriptorPath(folder: string, channelDescriptor: string) { return this.pathTemplates.folderChannelDescriptorPathTemplate.render({ folder: folder, channel_descriptor: channelDescriptor, @@ -1769,8 +2163,12 @@ export class MetricServiceClient { * A fully-qualified path representing folder_channel_descriptor resource. * @returns {string} A string representing the folder. */ - matchFolderFromFolderChannelDescriptorName(folderChannelDescriptorName: string) { - return this.pathTemplates.folderChannelDescriptorPathTemplate.match(folderChannelDescriptorName).folder; + matchFolderFromFolderChannelDescriptorName( + folderChannelDescriptorName: string, + ) { + return this.pathTemplates.folderChannelDescriptorPathTemplate.match( + folderChannelDescriptorName, + ).folder; } /** @@ -1780,8 +2178,12 @@ export class MetricServiceClient { * A fully-qualified path representing folder_channel_descriptor resource. * @returns {string} A string representing the channel_descriptor. */ - matchChannelDescriptorFromFolderChannelDescriptorName(folderChannelDescriptorName: string) { - return this.pathTemplates.folderChannelDescriptorPathTemplate.match(folderChannelDescriptorName).channel_descriptor; + matchChannelDescriptorFromFolderChannelDescriptorName( + folderChannelDescriptorName: string, + ) { + return this.pathTemplates.folderChannelDescriptorPathTemplate.match( + folderChannelDescriptorName, + ).channel_descriptor; } /** @@ -1791,7 +2193,7 @@ export class MetricServiceClient { * @param {string} group * @returns {string} Resource name string. */ - folderGroupPath(folder:string,group:string) { + folderGroupPath(folder: string, group: string) { return this.pathTemplates.folderGroupPathTemplate.render({ folder: folder, group: group, @@ -1806,7 +2208,8 @@ export class MetricServiceClient { * @returns {string} A string representing the folder. */ matchFolderFromFolderGroupName(folderGroupName: string) { - return this.pathTemplates.folderGroupPathTemplate.match(folderGroupName).folder; + return this.pathTemplates.folderGroupPathTemplate.match(folderGroupName) + .folder; } /** @@ -1817,7 +2220,8 @@ export class MetricServiceClient { * @returns {string} A string representing the group. */ matchGroupFromFolderGroupName(folderGroupName: string) { - return this.pathTemplates.folderGroupPathTemplate.match(folderGroupName).group; + return this.pathTemplates.folderGroupPathTemplate.match(folderGroupName) + .group; } /** @@ -1827,7 +2231,7 @@ export class MetricServiceClient { * @param {string} metric_descriptor * @returns {string} Resource name string. */ - folderMetricDescriptorPath(folder:string,metricDescriptor:string) { + folderMetricDescriptorPath(folder: string, metricDescriptor: string) { return this.pathTemplates.folderMetricDescriptorPathTemplate.render({ folder: folder, metric_descriptor: metricDescriptor, @@ -1841,8 +2245,12 @@ export class MetricServiceClient { * A fully-qualified path representing folder_metric_descriptor resource. * @returns {string} A string representing the folder. */ - matchFolderFromFolderMetricDescriptorName(folderMetricDescriptorName: string) { - return this.pathTemplates.folderMetricDescriptorPathTemplate.match(folderMetricDescriptorName).folder; + matchFolderFromFolderMetricDescriptorName( + folderMetricDescriptorName: string, + ) { + return this.pathTemplates.folderMetricDescriptorPathTemplate.match( + folderMetricDescriptorName, + ).folder; } /** @@ -1852,8 +2260,12 @@ export class MetricServiceClient { * A fully-qualified path representing folder_metric_descriptor resource. * @returns {string} A string representing the metric_descriptor. */ - matchMetricDescriptorFromFolderMetricDescriptorName(folderMetricDescriptorName: string) { - return this.pathTemplates.folderMetricDescriptorPathTemplate.match(folderMetricDescriptorName).metric_descriptor; + matchMetricDescriptorFromFolderMetricDescriptorName( + folderMetricDescriptorName: string, + ) { + return this.pathTemplates.folderMetricDescriptorPathTemplate.match( + folderMetricDescriptorName, + ).metric_descriptor; } /** @@ -1863,11 +2275,16 @@ export class MetricServiceClient { * @param {string} monitored_resource_descriptor * @returns {string} Resource name string. */ - folderMonitoredResourceDescriptorPath(folder:string,monitoredResourceDescriptor:string) { - return this.pathTemplates.folderMonitoredResourceDescriptorPathTemplate.render({ - folder: folder, - monitored_resource_descriptor: monitoredResourceDescriptor, - }); + folderMonitoredResourceDescriptorPath( + folder: string, + monitoredResourceDescriptor: string, + ) { + return this.pathTemplates.folderMonitoredResourceDescriptorPathTemplate.render( + { + folder: folder, + monitored_resource_descriptor: monitoredResourceDescriptor, + }, + ); } /** @@ -1877,8 +2294,12 @@ export class MetricServiceClient { * A fully-qualified path representing folder_monitored_resource_descriptor resource. * @returns {string} A string representing the folder. */ - matchFolderFromFolderMonitoredResourceDescriptorName(folderMonitoredResourceDescriptorName: string) { - return this.pathTemplates.folderMonitoredResourceDescriptorPathTemplate.match(folderMonitoredResourceDescriptorName).folder; + matchFolderFromFolderMonitoredResourceDescriptorName( + folderMonitoredResourceDescriptorName: string, + ) { + return this.pathTemplates.folderMonitoredResourceDescriptorPathTemplate.match( + folderMonitoredResourceDescriptorName, + ).folder; } /** @@ -1888,8 +2309,12 @@ export class MetricServiceClient { * A fully-qualified path representing folder_monitored_resource_descriptor resource. * @returns {string} A string representing the monitored_resource_descriptor. */ - matchMonitoredResourceDescriptorFromFolderMonitoredResourceDescriptorName(folderMonitoredResourceDescriptorName: string) { - return this.pathTemplates.folderMonitoredResourceDescriptorPathTemplate.match(folderMonitoredResourceDescriptorName).monitored_resource_descriptor; + matchMonitoredResourceDescriptorFromFolderMonitoredResourceDescriptorName( + folderMonitoredResourceDescriptorName: string, + ) { + return this.pathTemplates.folderMonitoredResourceDescriptorPathTemplate.match( + folderMonitoredResourceDescriptorName, + ).monitored_resource_descriptor; } /** @@ -1899,7 +2324,7 @@ export class MetricServiceClient { * @param {string} notification_channel * @returns {string} Resource name string. */ - folderNotificationChannelPath(folder:string,notificationChannel:string) { + folderNotificationChannelPath(folder: string, notificationChannel: string) { return this.pathTemplates.folderNotificationChannelPathTemplate.render({ folder: folder, notification_channel: notificationChannel, @@ -1913,8 +2338,12 @@ export class MetricServiceClient { * A fully-qualified path representing folder_notification_channel resource. * @returns {string} A string representing the folder. */ - matchFolderFromFolderNotificationChannelName(folderNotificationChannelName: string) { - return this.pathTemplates.folderNotificationChannelPathTemplate.match(folderNotificationChannelName).folder; + matchFolderFromFolderNotificationChannelName( + folderNotificationChannelName: string, + ) { + return this.pathTemplates.folderNotificationChannelPathTemplate.match( + folderNotificationChannelName, + ).folder; } /** @@ -1924,8 +2353,12 @@ export class MetricServiceClient { * A fully-qualified path representing folder_notification_channel resource. * @returns {string} A string representing the notification_channel. */ - matchNotificationChannelFromFolderNotificationChannelName(folderNotificationChannelName: string) { - return this.pathTemplates.folderNotificationChannelPathTemplate.match(folderNotificationChannelName).notification_channel; + matchNotificationChannelFromFolderNotificationChannelName( + folderNotificationChannelName: string, + ) { + return this.pathTemplates.folderNotificationChannelPathTemplate.match( + folderNotificationChannelName, + ).notification_channel; } /** @@ -1935,7 +2368,7 @@ export class MetricServiceClient { * @param {string} service * @returns {string} Resource name string. */ - folderServicePath(folder:string,service:string) { + folderServicePath(folder: string, service: string) { return this.pathTemplates.folderServicePathTemplate.render({ folder: folder, service: service, @@ -1950,7 +2383,8 @@ export class MetricServiceClient { * @returns {string} A string representing the folder. */ matchFolderFromFolderServiceName(folderServiceName: string) { - return this.pathTemplates.folderServicePathTemplate.match(folderServiceName).folder; + return this.pathTemplates.folderServicePathTemplate.match(folderServiceName) + .folder; } /** @@ -1961,7 +2395,8 @@ export class MetricServiceClient { * @returns {string} A string representing the service. */ matchServiceFromFolderServiceName(folderServiceName: string) { - return this.pathTemplates.folderServicePathTemplate.match(folderServiceName).service; + return this.pathTemplates.folderServicePathTemplate.match(folderServiceName) + .service; } /** @@ -1972,12 +2407,18 @@ export class MetricServiceClient { * @param {string} service_level_objective * @returns {string} Resource name string. */ - folderServiceServiceLevelObjectivePath(folder:string,service:string,serviceLevelObjective:string) { - return this.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.render({ - folder: folder, - service: service, - service_level_objective: serviceLevelObjective, - }); + folderServiceServiceLevelObjectivePath( + folder: string, + service: string, + serviceLevelObjective: string, + ) { + return this.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.render( + { + folder: folder, + service: service, + service_level_objective: serviceLevelObjective, + }, + ); } /** @@ -1987,8 +2428,12 @@ export class MetricServiceClient { * A fully-qualified path representing folder_service_service_level_objective resource. * @returns {string} A string representing the folder. */ - matchFolderFromFolderServiceServiceLevelObjectiveName(folderServiceServiceLevelObjectiveName: string) { - return this.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match(folderServiceServiceLevelObjectiveName).folder; + matchFolderFromFolderServiceServiceLevelObjectiveName( + folderServiceServiceLevelObjectiveName: string, + ) { + return this.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match( + folderServiceServiceLevelObjectiveName, + ).folder; } /** @@ -1998,8 +2443,12 @@ export class MetricServiceClient { * A fully-qualified path representing folder_service_service_level_objective resource. * @returns {string} A string representing the service. */ - matchServiceFromFolderServiceServiceLevelObjectiveName(folderServiceServiceLevelObjectiveName: string) { - return this.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match(folderServiceServiceLevelObjectiveName).service; + matchServiceFromFolderServiceServiceLevelObjectiveName( + folderServiceServiceLevelObjectiveName: string, + ) { + return this.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match( + folderServiceServiceLevelObjectiveName, + ).service; } /** @@ -2009,8 +2458,12 @@ export class MetricServiceClient { * A fully-qualified path representing folder_service_service_level_objective resource. * @returns {string} A string representing the service_level_objective. */ - matchServiceLevelObjectiveFromFolderServiceServiceLevelObjectiveName(folderServiceServiceLevelObjectiveName: string) { - return this.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match(folderServiceServiceLevelObjectiveName).service_level_objective; + matchServiceLevelObjectiveFromFolderServiceServiceLevelObjectiveName( + folderServiceServiceLevelObjectiveName: string, + ) { + return this.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match( + folderServiceServiceLevelObjectiveName, + ).service_level_objective; } /** @@ -2020,7 +2473,7 @@ export class MetricServiceClient { * @param {string} uptime_check_config * @returns {string} Resource name string. */ - folderUptimeCheckConfigPath(folder:string,uptimeCheckConfig:string) { + folderUptimeCheckConfigPath(folder: string, uptimeCheckConfig: string) { return this.pathTemplates.folderUptimeCheckConfigPathTemplate.render({ folder: folder, uptime_check_config: uptimeCheckConfig, @@ -2034,8 +2487,12 @@ export class MetricServiceClient { * A fully-qualified path representing folder_uptime_check_config resource. * @returns {string} A string representing the folder. */ - matchFolderFromFolderUptimeCheckConfigName(folderUptimeCheckConfigName: string) { - return this.pathTemplates.folderUptimeCheckConfigPathTemplate.match(folderUptimeCheckConfigName).folder; + matchFolderFromFolderUptimeCheckConfigName( + folderUptimeCheckConfigName: string, + ) { + return this.pathTemplates.folderUptimeCheckConfigPathTemplate.match( + folderUptimeCheckConfigName, + ).folder; } /** @@ -2045,8 +2502,12 @@ export class MetricServiceClient { * A fully-qualified path representing folder_uptime_check_config resource. * @returns {string} A string representing the uptime_check_config. */ - matchUptimeCheckConfigFromFolderUptimeCheckConfigName(folderUptimeCheckConfigName: string) { - return this.pathTemplates.folderUptimeCheckConfigPathTemplate.match(folderUptimeCheckConfigName).uptime_check_config; + matchUptimeCheckConfigFromFolderUptimeCheckConfigName( + folderUptimeCheckConfigName: string, + ) { + return this.pathTemplates.folderUptimeCheckConfigPathTemplate.match( + folderUptimeCheckConfigName, + ).uptime_check_config; } /** @@ -2056,7 +2517,7 @@ export class MetricServiceClient { * @param {string} alert_policy * @returns {string} Resource name string. */ - organizationAlertPolicyPath(organization:string,alertPolicy:string) { + organizationAlertPolicyPath(organization: string, alertPolicy: string) { return this.pathTemplates.organizationAlertPolicyPathTemplate.render({ organization: organization, alert_policy: alertPolicy, @@ -2070,8 +2531,12 @@ export class MetricServiceClient { * A fully-qualified path representing organization_alert_policy resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationAlertPolicyName(organizationAlertPolicyName: string) { - return this.pathTemplates.organizationAlertPolicyPathTemplate.match(organizationAlertPolicyName).organization; + matchOrganizationFromOrganizationAlertPolicyName( + organizationAlertPolicyName: string, + ) { + return this.pathTemplates.organizationAlertPolicyPathTemplate.match( + organizationAlertPolicyName, + ).organization; } /** @@ -2081,8 +2546,12 @@ export class MetricServiceClient { * A fully-qualified path representing organization_alert_policy resource. * @returns {string} A string representing the alert_policy. */ - matchAlertPolicyFromOrganizationAlertPolicyName(organizationAlertPolicyName: string) { - return this.pathTemplates.organizationAlertPolicyPathTemplate.match(organizationAlertPolicyName).alert_policy; + matchAlertPolicyFromOrganizationAlertPolicyName( + organizationAlertPolicyName: string, + ) { + return this.pathTemplates.organizationAlertPolicyPathTemplate.match( + organizationAlertPolicyName, + ).alert_policy; } /** @@ -2093,12 +2562,18 @@ export class MetricServiceClient { * @param {string} condition * @returns {string} Resource name string. */ - organizationAlertPolicyConditionPath(organization:string,alertPolicy:string,condition:string) { - return this.pathTemplates.organizationAlertPolicyConditionPathTemplate.render({ - organization: organization, - alert_policy: alertPolicy, - condition: condition, - }); + organizationAlertPolicyConditionPath( + organization: string, + alertPolicy: string, + condition: string, + ) { + return this.pathTemplates.organizationAlertPolicyConditionPathTemplate.render( + { + organization: organization, + alert_policy: alertPolicy, + condition: condition, + }, + ); } /** @@ -2108,8 +2583,12 @@ export class MetricServiceClient { * A fully-qualified path representing organization_alert_policy_condition resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationAlertPolicyConditionName(organizationAlertPolicyConditionName: string) { - return this.pathTemplates.organizationAlertPolicyConditionPathTemplate.match(organizationAlertPolicyConditionName).organization; + matchOrganizationFromOrganizationAlertPolicyConditionName( + organizationAlertPolicyConditionName: string, + ) { + return this.pathTemplates.organizationAlertPolicyConditionPathTemplate.match( + organizationAlertPolicyConditionName, + ).organization; } /** @@ -2119,8 +2598,12 @@ export class MetricServiceClient { * A fully-qualified path representing organization_alert_policy_condition resource. * @returns {string} A string representing the alert_policy. */ - matchAlertPolicyFromOrganizationAlertPolicyConditionName(organizationAlertPolicyConditionName: string) { - return this.pathTemplates.organizationAlertPolicyConditionPathTemplate.match(organizationAlertPolicyConditionName).alert_policy; + matchAlertPolicyFromOrganizationAlertPolicyConditionName( + organizationAlertPolicyConditionName: string, + ) { + return this.pathTemplates.organizationAlertPolicyConditionPathTemplate.match( + organizationAlertPolicyConditionName, + ).alert_policy; } /** @@ -2130,8 +2613,12 @@ export class MetricServiceClient { * A fully-qualified path representing organization_alert_policy_condition resource. * @returns {string} A string representing the condition. */ - matchConditionFromOrganizationAlertPolicyConditionName(organizationAlertPolicyConditionName: string) { - return this.pathTemplates.organizationAlertPolicyConditionPathTemplate.match(organizationAlertPolicyConditionName).condition; + matchConditionFromOrganizationAlertPolicyConditionName( + organizationAlertPolicyConditionName: string, + ) { + return this.pathTemplates.organizationAlertPolicyConditionPathTemplate.match( + organizationAlertPolicyConditionName, + ).condition; } /** @@ -2141,7 +2628,10 @@ export class MetricServiceClient { * @param {string} channel_descriptor * @returns {string} Resource name string. */ - organizationChannelDescriptorPath(organization:string,channelDescriptor:string) { + organizationChannelDescriptorPath( + organization: string, + channelDescriptor: string, + ) { return this.pathTemplates.organizationChannelDescriptorPathTemplate.render({ organization: organization, channel_descriptor: channelDescriptor, @@ -2155,8 +2645,12 @@ export class MetricServiceClient { * A fully-qualified path representing organization_channel_descriptor resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationChannelDescriptorName(organizationChannelDescriptorName: string) { - return this.pathTemplates.organizationChannelDescriptorPathTemplate.match(organizationChannelDescriptorName).organization; + matchOrganizationFromOrganizationChannelDescriptorName( + organizationChannelDescriptorName: string, + ) { + return this.pathTemplates.organizationChannelDescriptorPathTemplate.match( + organizationChannelDescriptorName, + ).organization; } /** @@ -2166,8 +2660,12 @@ export class MetricServiceClient { * A fully-qualified path representing organization_channel_descriptor resource. * @returns {string} A string representing the channel_descriptor. */ - matchChannelDescriptorFromOrganizationChannelDescriptorName(organizationChannelDescriptorName: string) { - return this.pathTemplates.organizationChannelDescriptorPathTemplate.match(organizationChannelDescriptorName).channel_descriptor; + matchChannelDescriptorFromOrganizationChannelDescriptorName( + organizationChannelDescriptorName: string, + ) { + return this.pathTemplates.organizationChannelDescriptorPathTemplate.match( + organizationChannelDescriptorName, + ).channel_descriptor; } /** @@ -2177,7 +2675,7 @@ export class MetricServiceClient { * @param {string} group * @returns {string} Resource name string. */ - organizationGroupPath(organization:string,group:string) { + organizationGroupPath(organization: string, group: string) { return this.pathTemplates.organizationGroupPathTemplate.render({ organization: organization, group: group, @@ -2192,7 +2690,9 @@ export class MetricServiceClient { * @returns {string} A string representing the organization. */ matchOrganizationFromOrganizationGroupName(organizationGroupName: string) { - return this.pathTemplates.organizationGroupPathTemplate.match(organizationGroupName).organization; + return this.pathTemplates.organizationGroupPathTemplate.match( + organizationGroupName, + ).organization; } /** @@ -2203,7 +2703,9 @@ export class MetricServiceClient { * @returns {string} A string representing the group. */ matchGroupFromOrganizationGroupName(organizationGroupName: string) { - return this.pathTemplates.organizationGroupPathTemplate.match(organizationGroupName).group; + return this.pathTemplates.organizationGroupPathTemplate.match( + organizationGroupName, + ).group; } /** @@ -2213,7 +2715,10 @@ export class MetricServiceClient { * @param {string} metric_descriptor * @returns {string} Resource name string. */ - organizationMetricDescriptorPath(organization:string,metricDescriptor:string) { + organizationMetricDescriptorPath( + organization: string, + metricDescriptor: string, + ) { return this.pathTemplates.organizationMetricDescriptorPathTemplate.render({ organization: organization, metric_descriptor: metricDescriptor, @@ -2227,8 +2732,12 @@ export class MetricServiceClient { * A fully-qualified path representing organization_metric_descriptor resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationMetricDescriptorName(organizationMetricDescriptorName: string) { - return this.pathTemplates.organizationMetricDescriptorPathTemplate.match(organizationMetricDescriptorName).organization; + matchOrganizationFromOrganizationMetricDescriptorName( + organizationMetricDescriptorName: string, + ) { + return this.pathTemplates.organizationMetricDescriptorPathTemplate.match( + organizationMetricDescriptorName, + ).organization; } /** @@ -2238,8 +2747,12 @@ export class MetricServiceClient { * A fully-qualified path representing organization_metric_descriptor resource. * @returns {string} A string representing the metric_descriptor. */ - matchMetricDescriptorFromOrganizationMetricDescriptorName(organizationMetricDescriptorName: string) { - return this.pathTemplates.organizationMetricDescriptorPathTemplate.match(organizationMetricDescriptorName).metric_descriptor; + matchMetricDescriptorFromOrganizationMetricDescriptorName( + organizationMetricDescriptorName: string, + ) { + return this.pathTemplates.organizationMetricDescriptorPathTemplate.match( + organizationMetricDescriptorName, + ).metric_descriptor; } /** @@ -2249,11 +2762,16 @@ export class MetricServiceClient { * @param {string} monitored_resource_descriptor * @returns {string} Resource name string. */ - organizationMonitoredResourceDescriptorPath(organization:string,monitoredResourceDescriptor:string) { - return this.pathTemplates.organizationMonitoredResourceDescriptorPathTemplate.render({ - organization: organization, - monitored_resource_descriptor: monitoredResourceDescriptor, - }); + organizationMonitoredResourceDescriptorPath( + organization: string, + monitoredResourceDescriptor: string, + ) { + return this.pathTemplates.organizationMonitoredResourceDescriptorPathTemplate.render( + { + organization: organization, + monitored_resource_descriptor: monitoredResourceDescriptor, + }, + ); } /** @@ -2263,8 +2781,12 @@ export class MetricServiceClient { * A fully-qualified path representing organization_monitored_resource_descriptor resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationMonitoredResourceDescriptorName(organizationMonitoredResourceDescriptorName: string) { - return this.pathTemplates.organizationMonitoredResourceDescriptorPathTemplate.match(organizationMonitoredResourceDescriptorName).organization; + matchOrganizationFromOrganizationMonitoredResourceDescriptorName( + organizationMonitoredResourceDescriptorName: string, + ) { + return this.pathTemplates.organizationMonitoredResourceDescriptorPathTemplate.match( + organizationMonitoredResourceDescriptorName, + ).organization; } /** @@ -2274,8 +2796,12 @@ export class MetricServiceClient { * A fully-qualified path representing organization_monitored_resource_descriptor resource. * @returns {string} A string representing the monitored_resource_descriptor. */ - matchMonitoredResourceDescriptorFromOrganizationMonitoredResourceDescriptorName(organizationMonitoredResourceDescriptorName: string) { - return this.pathTemplates.organizationMonitoredResourceDescriptorPathTemplate.match(organizationMonitoredResourceDescriptorName).monitored_resource_descriptor; + matchMonitoredResourceDescriptorFromOrganizationMonitoredResourceDescriptorName( + organizationMonitoredResourceDescriptorName: string, + ) { + return this.pathTemplates.organizationMonitoredResourceDescriptorPathTemplate.match( + organizationMonitoredResourceDescriptorName, + ).monitored_resource_descriptor; } /** @@ -2285,11 +2811,16 @@ export class MetricServiceClient { * @param {string} notification_channel * @returns {string} Resource name string. */ - organizationNotificationChannelPath(organization:string,notificationChannel:string) { - return this.pathTemplates.organizationNotificationChannelPathTemplate.render({ - organization: organization, - notification_channel: notificationChannel, - }); + organizationNotificationChannelPath( + organization: string, + notificationChannel: string, + ) { + return this.pathTemplates.organizationNotificationChannelPathTemplate.render( + { + organization: organization, + notification_channel: notificationChannel, + }, + ); } /** @@ -2299,8 +2830,12 @@ export class MetricServiceClient { * A fully-qualified path representing organization_notification_channel resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationNotificationChannelName(organizationNotificationChannelName: string) { - return this.pathTemplates.organizationNotificationChannelPathTemplate.match(organizationNotificationChannelName).organization; + matchOrganizationFromOrganizationNotificationChannelName( + organizationNotificationChannelName: string, + ) { + return this.pathTemplates.organizationNotificationChannelPathTemplate.match( + organizationNotificationChannelName, + ).organization; } /** @@ -2310,8 +2845,12 @@ export class MetricServiceClient { * A fully-qualified path representing organization_notification_channel resource. * @returns {string} A string representing the notification_channel. */ - matchNotificationChannelFromOrganizationNotificationChannelName(organizationNotificationChannelName: string) { - return this.pathTemplates.organizationNotificationChannelPathTemplate.match(organizationNotificationChannelName).notification_channel; + matchNotificationChannelFromOrganizationNotificationChannelName( + organizationNotificationChannelName: string, + ) { + return this.pathTemplates.organizationNotificationChannelPathTemplate.match( + organizationNotificationChannelName, + ).notification_channel; } /** @@ -2321,7 +2860,7 @@ export class MetricServiceClient { * @param {string} service * @returns {string} Resource name string. */ - organizationServicePath(organization:string,service:string) { + organizationServicePath(organization: string, service: string) { return this.pathTemplates.organizationServicePathTemplate.render({ organization: organization, service: service, @@ -2335,8 +2874,12 @@ export class MetricServiceClient { * A fully-qualified path representing organization_service resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationServiceName(organizationServiceName: string) { - return this.pathTemplates.organizationServicePathTemplate.match(organizationServiceName).organization; + matchOrganizationFromOrganizationServiceName( + organizationServiceName: string, + ) { + return this.pathTemplates.organizationServicePathTemplate.match( + organizationServiceName, + ).organization; } /** @@ -2347,7 +2890,9 @@ export class MetricServiceClient { * @returns {string} A string representing the service. */ matchServiceFromOrganizationServiceName(organizationServiceName: string) { - return this.pathTemplates.organizationServicePathTemplate.match(organizationServiceName).service; + return this.pathTemplates.organizationServicePathTemplate.match( + organizationServiceName, + ).service; } /** @@ -2358,12 +2903,18 @@ export class MetricServiceClient { * @param {string} service_level_objective * @returns {string} Resource name string. */ - organizationServiceServiceLevelObjectivePath(organization:string,service:string,serviceLevelObjective:string) { - return this.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.render({ - organization: organization, - service: service, - service_level_objective: serviceLevelObjective, - }); + organizationServiceServiceLevelObjectivePath( + organization: string, + service: string, + serviceLevelObjective: string, + ) { + return this.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.render( + { + organization: organization, + service: service, + service_level_objective: serviceLevelObjective, + }, + ); } /** @@ -2373,8 +2924,12 @@ export class MetricServiceClient { * A fully-qualified path representing organization_service_service_level_objective resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationServiceServiceLevelObjectiveName(organizationServiceServiceLevelObjectiveName: string) { - return this.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match(organizationServiceServiceLevelObjectiveName).organization; + matchOrganizationFromOrganizationServiceServiceLevelObjectiveName( + organizationServiceServiceLevelObjectiveName: string, + ) { + return this.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match( + organizationServiceServiceLevelObjectiveName, + ).organization; } /** @@ -2384,8 +2939,12 @@ export class MetricServiceClient { * A fully-qualified path representing organization_service_service_level_objective resource. * @returns {string} A string representing the service. */ - matchServiceFromOrganizationServiceServiceLevelObjectiveName(organizationServiceServiceLevelObjectiveName: string) { - return this.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match(organizationServiceServiceLevelObjectiveName).service; + matchServiceFromOrganizationServiceServiceLevelObjectiveName( + organizationServiceServiceLevelObjectiveName: string, + ) { + return this.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match( + organizationServiceServiceLevelObjectiveName, + ).service; } /** @@ -2395,8 +2954,12 @@ export class MetricServiceClient { * A fully-qualified path representing organization_service_service_level_objective resource. * @returns {string} A string representing the service_level_objective. */ - matchServiceLevelObjectiveFromOrganizationServiceServiceLevelObjectiveName(organizationServiceServiceLevelObjectiveName: string) { - return this.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match(organizationServiceServiceLevelObjectiveName).service_level_objective; + matchServiceLevelObjectiveFromOrganizationServiceServiceLevelObjectiveName( + organizationServiceServiceLevelObjectiveName: string, + ) { + return this.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match( + organizationServiceServiceLevelObjectiveName, + ).service_level_objective; } /** @@ -2406,7 +2969,10 @@ export class MetricServiceClient { * @param {string} uptime_check_config * @returns {string} Resource name string. */ - organizationUptimeCheckConfigPath(organization:string,uptimeCheckConfig:string) { + organizationUptimeCheckConfigPath( + organization: string, + uptimeCheckConfig: string, + ) { return this.pathTemplates.organizationUptimeCheckConfigPathTemplate.render({ organization: organization, uptime_check_config: uptimeCheckConfig, @@ -2420,8 +2986,12 @@ export class MetricServiceClient { * A fully-qualified path representing organization_uptime_check_config resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationUptimeCheckConfigName(organizationUptimeCheckConfigName: string) { - return this.pathTemplates.organizationUptimeCheckConfigPathTemplate.match(organizationUptimeCheckConfigName).organization; + matchOrganizationFromOrganizationUptimeCheckConfigName( + organizationUptimeCheckConfigName: string, + ) { + return this.pathTemplates.organizationUptimeCheckConfigPathTemplate.match( + organizationUptimeCheckConfigName, + ).organization; } /** @@ -2431,8 +3001,12 @@ export class MetricServiceClient { * A fully-qualified path representing organization_uptime_check_config resource. * @returns {string} A string representing the uptime_check_config. */ - matchUptimeCheckConfigFromOrganizationUptimeCheckConfigName(organizationUptimeCheckConfigName: string) { - return this.pathTemplates.organizationUptimeCheckConfigPathTemplate.match(organizationUptimeCheckConfigName).uptime_check_config; + matchUptimeCheckConfigFromOrganizationUptimeCheckConfigName( + organizationUptimeCheckConfigName: string, + ) { + return this.pathTemplates.organizationUptimeCheckConfigPathTemplate.match( + organizationUptimeCheckConfigName, + ).uptime_check_config; } /** @@ -2442,7 +3016,7 @@ export class MetricServiceClient { * @param {string} alert_policy * @returns {string} Resource name string. */ - projectAlertPolicyPath(project:string,alertPolicy:string) { + projectAlertPolicyPath(project: string, alertPolicy: string) { return this.pathTemplates.projectAlertPolicyPathTemplate.render({ project: project, alert_policy: alertPolicy, @@ -2457,7 +3031,9 @@ export class MetricServiceClient { * @returns {string} A string representing the project. */ matchProjectFromProjectAlertPolicyName(projectAlertPolicyName: string) { - return this.pathTemplates.projectAlertPolicyPathTemplate.match(projectAlertPolicyName).project; + return this.pathTemplates.projectAlertPolicyPathTemplate.match( + projectAlertPolicyName, + ).project; } /** @@ -2468,7 +3044,9 @@ export class MetricServiceClient { * @returns {string} A string representing the alert_policy. */ matchAlertPolicyFromProjectAlertPolicyName(projectAlertPolicyName: string) { - return this.pathTemplates.projectAlertPolicyPathTemplate.match(projectAlertPolicyName).alert_policy; + return this.pathTemplates.projectAlertPolicyPathTemplate.match( + projectAlertPolicyName, + ).alert_policy; } /** @@ -2479,7 +3057,11 @@ export class MetricServiceClient { * @param {string} condition * @returns {string} Resource name string. */ - projectAlertPolicyConditionPath(project:string,alertPolicy:string,condition:string) { + projectAlertPolicyConditionPath( + project: string, + alertPolicy: string, + condition: string, + ) { return this.pathTemplates.projectAlertPolicyConditionPathTemplate.render({ project: project, alert_policy: alertPolicy, @@ -2494,8 +3076,12 @@ export class MetricServiceClient { * A fully-qualified path representing project_alert_policy_condition resource. * @returns {string} A string representing the project. */ - matchProjectFromProjectAlertPolicyConditionName(projectAlertPolicyConditionName: string) { - return this.pathTemplates.projectAlertPolicyConditionPathTemplate.match(projectAlertPolicyConditionName).project; + matchProjectFromProjectAlertPolicyConditionName( + projectAlertPolicyConditionName: string, + ) { + return this.pathTemplates.projectAlertPolicyConditionPathTemplate.match( + projectAlertPolicyConditionName, + ).project; } /** @@ -2505,8 +3091,12 @@ export class MetricServiceClient { * A fully-qualified path representing project_alert_policy_condition resource. * @returns {string} A string representing the alert_policy. */ - matchAlertPolicyFromProjectAlertPolicyConditionName(projectAlertPolicyConditionName: string) { - return this.pathTemplates.projectAlertPolicyConditionPathTemplate.match(projectAlertPolicyConditionName).alert_policy; + matchAlertPolicyFromProjectAlertPolicyConditionName( + projectAlertPolicyConditionName: string, + ) { + return this.pathTemplates.projectAlertPolicyConditionPathTemplate.match( + projectAlertPolicyConditionName, + ).alert_policy; } /** @@ -2516,8 +3106,12 @@ export class MetricServiceClient { * A fully-qualified path representing project_alert_policy_condition resource. * @returns {string} A string representing the condition. */ - matchConditionFromProjectAlertPolicyConditionName(projectAlertPolicyConditionName: string) { - return this.pathTemplates.projectAlertPolicyConditionPathTemplate.match(projectAlertPolicyConditionName).condition; + matchConditionFromProjectAlertPolicyConditionName( + projectAlertPolicyConditionName: string, + ) { + return this.pathTemplates.projectAlertPolicyConditionPathTemplate.match( + projectAlertPolicyConditionName, + ).condition; } /** @@ -2527,7 +3121,7 @@ export class MetricServiceClient { * @param {string} channel_descriptor * @returns {string} Resource name string. */ - projectChannelDescriptorPath(project:string,channelDescriptor:string) { + projectChannelDescriptorPath(project: string, channelDescriptor: string) { return this.pathTemplates.projectChannelDescriptorPathTemplate.render({ project: project, channel_descriptor: channelDescriptor, @@ -2541,8 +3135,12 @@ export class MetricServiceClient { * A fully-qualified path representing project_channel_descriptor resource. * @returns {string} A string representing the project. */ - matchProjectFromProjectChannelDescriptorName(projectChannelDescriptorName: string) { - return this.pathTemplates.projectChannelDescriptorPathTemplate.match(projectChannelDescriptorName).project; + matchProjectFromProjectChannelDescriptorName( + projectChannelDescriptorName: string, + ) { + return this.pathTemplates.projectChannelDescriptorPathTemplate.match( + projectChannelDescriptorName, + ).project; } /** @@ -2552,8 +3150,12 @@ export class MetricServiceClient { * A fully-qualified path representing project_channel_descriptor resource. * @returns {string} A string representing the channel_descriptor. */ - matchChannelDescriptorFromProjectChannelDescriptorName(projectChannelDescriptorName: string) { - return this.pathTemplates.projectChannelDescriptorPathTemplate.match(projectChannelDescriptorName).channel_descriptor; + matchChannelDescriptorFromProjectChannelDescriptorName( + projectChannelDescriptorName: string, + ) { + return this.pathTemplates.projectChannelDescriptorPathTemplate.match( + projectChannelDescriptorName, + ).channel_descriptor; } /** @@ -2563,7 +3165,7 @@ export class MetricServiceClient { * @param {string} group * @returns {string} Resource name string. */ - projectGroupPath(project:string,group:string) { + projectGroupPath(project: string, group: string) { return this.pathTemplates.projectGroupPathTemplate.render({ project: project, group: group, @@ -2578,7 +3180,8 @@ export class MetricServiceClient { * @returns {string} A string representing the project. */ matchProjectFromProjectGroupName(projectGroupName: string) { - return this.pathTemplates.projectGroupPathTemplate.match(projectGroupName).project; + return this.pathTemplates.projectGroupPathTemplate.match(projectGroupName) + .project; } /** @@ -2589,7 +3192,8 @@ export class MetricServiceClient { * @returns {string} A string representing the group. */ matchGroupFromProjectGroupName(projectGroupName: string) { - return this.pathTemplates.projectGroupPathTemplate.match(projectGroupName).group; + return this.pathTemplates.projectGroupPathTemplate.match(projectGroupName) + .group; } /** @@ -2599,7 +3203,7 @@ export class MetricServiceClient { * @param {string} metric_descriptor * @returns {string} Resource name string. */ - projectMetricDescriptorPath(project:string,metricDescriptor:string) { + projectMetricDescriptorPath(project: string, metricDescriptor: string) { return this.pathTemplates.projectMetricDescriptorPathTemplate.render({ project: project, metric_descriptor: metricDescriptor, @@ -2613,8 +3217,12 @@ export class MetricServiceClient { * A fully-qualified path representing project_metric_descriptor resource. * @returns {string} A string representing the project. */ - matchProjectFromProjectMetricDescriptorName(projectMetricDescriptorName: string) { - return this.pathTemplates.projectMetricDescriptorPathTemplate.match(projectMetricDescriptorName).project; + matchProjectFromProjectMetricDescriptorName( + projectMetricDescriptorName: string, + ) { + return this.pathTemplates.projectMetricDescriptorPathTemplate.match( + projectMetricDescriptorName, + ).project; } /** @@ -2624,8 +3232,12 @@ export class MetricServiceClient { * A fully-qualified path representing project_metric_descriptor resource. * @returns {string} A string representing the metric_descriptor. */ - matchMetricDescriptorFromProjectMetricDescriptorName(projectMetricDescriptorName: string) { - return this.pathTemplates.projectMetricDescriptorPathTemplate.match(projectMetricDescriptorName).metric_descriptor; + matchMetricDescriptorFromProjectMetricDescriptorName( + projectMetricDescriptorName: string, + ) { + return this.pathTemplates.projectMetricDescriptorPathTemplate.match( + projectMetricDescriptorName, + ).metric_descriptor; } /** @@ -2635,11 +3247,16 @@ export class MetricServiceClient { * @param {string} monitored_resource_descriptor * @returns {string} Resource name string. */ - projectMonitoredResourceDescriptorPath(project:string,monitoredResourceDescriptor:string) { - return this.pathTemplates.projectMonitoredResourceDescriptorPathTemplate.render({ - project: project, - monitored_resource_descriptor: monitoredResourceDescriptor, - }); + projectMonitoredResourceDescriptorPath( + project: string, + monitoredResourceDescriptor: string, + ) { + return this.pathTemplates.projectMonitoredResourceDescriptorPathTemplate.render( + { + project: project, + monitored_resource_descriptor: monitoredResourceDescriptor, + }, + ); } /** @@ -2649,8 +3266,12 @@ export class MetricServiceClient { * A fully-qualified path representing project_monitored_resource_descriptor resource. * @returns {string} A string representing the project. */ - matchProjectFromProjectMonitoredResourceDescriptorName(projectMonitoredResourceDescriptorName: string) { - return this.pathTemplates.projectMonitoredResourceDescriptorPathTemplate.match(projectMonitoredResourceDescriptorName).project; + matchProjectFromProjectMonitoredResourceDescriptorName( + projectMonitoredResourceDescriptorName: string, + ) { + return this.pathTemplates.projectMonitoredResourceDescriptorPathTemplate.match( + projectMonitoredResourceDescriptorName, + ).project; } /** @@ -2660,8 +3281,12 @@ export class MetricServiceClient { * A fully-qualified path representing project_monitored_resource_descriptor resource. * @returns {string} A string representing the monitored_resource_descriptor. */ - matchMonitoredResourceDescriptorFromProjectMonitoredResourceDescriptorName(projectMonitoredResourceDescriptorName: string) { - return this.pathTemplates.projectMonitoredResourceDescriptorPathTemplate.match(projectMonitoredResourceDescriptorName).monitored_resource_descriptor; + matchMonitoredResourceDescriptorFromProjectMonitoredResourceDescriptorName( + projectMonitoredResourceDescriptorName: string, + ) { + return this.pathTemplates.projectMonitoredResourceDescriptorPathTemplate.match( + projectMonitoredResourceDescriptorName, + ).monitored_resource_descriptor; } /** @@ -2671,7 +3296,7 @@ export class MetricServiceClient { * @param {string} notification_channel * @returns {string} Resource name string. */ - projectNotificationChannelPath(project:string,notificationChannel:string) { + projectNotificationChannelPath(project: string, notificationChannel: string) { return this.pathTemplates.projectNotificationChannelPathTemplate.render({ project: project, notification_channel: notificationChannel, @@ -2685,8 +3310,12 @@ export class MetricServiceClient { * A fully-qualified path representing project_notification_channel resource. * @returns {string} A string representing the project. */ - matchProjectFromProjectNotificationChannelName(projectNotificationChannelName: string) { - return this.pathTemplates.projectNotificationChannelPathTemplate.match(projectNotificationChannelName).project; + matchProjectFromProjectNotificationChannelName( + projectNotificationChannelName: string, + ) { + return this.pathTemplates.projectNotificationChannelPathTemplate.match( + projectNotificationChannelName, + ).project; } /** @@ -2696,8 +3325,12 @@ export class MetricServiceClient { * A fully-qualified path representing project_notification_channel resource. * @returns {string} A string representing the notification_channel. */ - matchNotificationChannelFromProjectNotificationChannelName(projectNotificationChannelName: string) { - return this.pathTemplates.projectNotificationChannelPathTemplate.match(projectNotificationChannelName).notification_channel; + matchNotificationChannelFromProjectNotificationChannelName( + projectNotificationChannelName: string, + ) { + return this.pathTemplates.projectNotificationChannelPathTemplate.match( + projectNotificationChannelName, + ).notification_channel; } /** @@ -2707,7 +3340,7 @@ export class MetricServiceClient { * @param {string} service * @returns {string} Resource name string. */ - projectServicePath(project:string,service:string) { + projectServicePath(project: string, service: string) { return this.pathTemplates.projectServicePathTemplate.render({ project: project, service: service, @@ -2722,7 +3355,9 @@ export class MetricServiceClient { * @returns {string} A string representing the project. */ matchProjectFromProjectServiceName(projectServiceName: string) { - return this.pathTemplates.projectServicePathTemplate.match(projectServiceName).project; + return this.pathTemplates.projectServicePathTemplate.match( + projectServiceName, + ).project; } /** @@ -2733,7 +3368,9 @@ export class MetricServiceClient { * @returns {string} A string representing the service. */ matchServiceFromProjectServiceName(projectServiceName: string) { - return this.pathTemplates.projectServicePathTemplate.match(projectServiceName).service; + return this.pathTemplates.projectServicePathTemplate.match( + projectServiceName, + ).service; } /** @@ -2744,12 +3381,18 @@ export class MetricServiceClient { * @param {string} service_level_objective * @returns {string} Resource name string. */ - projectServiceServiceLevelObjectivePath(project:string,service:string,serviceLevelObjective:string) { - return this.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.render({ - project: project, - service: service, - service_level_objective: serviceLevelObjective, - }); + projectServiceServiceLevelObjectivePath( + project: string, + service: string, + serviceLevelObjective: string, + ) { + return this.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.render( + { + project: project, + service: service, + service_level_objective: serviceLevelObjective, + }, + ); } /** @@ -2759,8 +3402,12 @@ export class MetricServiceClient { * A fully-qualified path representing project_service_service_level_objective resource. * @returns {string} A string representing the project. */ - matchProjectFromProjectServiceServiceLevelObjectiveName(projectServiceServiceLevelObjectiveName: string) { - return this.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match(projectServiceServiceLevelObjectiveName).project; + matchProjectFromProjectServiceServiceLevelObjectiveName( + projectServiceServiceLevelObjectiveName: string, + ) { + return this.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match( + projectServiceServiceLevelObjectiveName, + ).project; } /** @@ -2770,8 +3417,12 @@ export class MetricServiceClient { * A fully-qualified path representing project_service_service_level_objective resource. * @returns {string} A string representing the service. */ - matchServiceFromProjectServiceServiceLevelObjectiveName(projectServiceServiceLevelObjectiveName: string) { - return this.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match(projectServiceServiceLevelObjectiveName).service; + matchServiceFromProjectServiceServiceLevelObjectiveName( + projectServiceServiceLevelObjectiveName: string, + ) { + return this.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match( + projectServiceServiceLevelObjectiveName, + ).service; } /** @@ -2781,8 +3432,12 @@ export class MetricServiceClient { * A fully-qualified path representing project_service_service_level_objective resource. * @returns {string} A string representing the service_level_objective. */ - matchServiceLevelObjectiveFromProjectServiceServiceLevelObjectiveName(projectServiceServiceLevelObjectiveName: string) { - return this.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match(projectServiceServiceLevelObjectiveName).service_level_objective; + matchServiceLevelObjectiveFromProjectServiceServiceLevelObjectiveName( + projectServiceServiceLevelObjectiveName: string, + ) { + return this.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match( + projectServiceServiceLevelObjectiveName, + ).service_level_objective; } /** @@ -2792,7 +3447,7 @@ export class MetricServiceClient { * @param {string} uptime_check_config * @returns {string} Resource name string. */ - projectUptimeCheckConfigPath(project:string,uptimeCheckConfig:string) { + projectUptimeCheckConfigPath(project: string, uptimeCheckConfig: string) { return this.pathTemplates.projectUptimeCheckConfigPathTemplate.render({ project: project, uptime_check_config: uptimeCheckConfig, @@ -2806,8 +3461,12 @@ export class MetricServiceClient { * A fully-qualified path representing project_uptime_check_config resource. * @returns {string} A string representing the project. */ - matchProjectFromProjectUptimeCheckConfigName(projectUptimeCheckConfigName: string) { - return this.pathTemplates.projectUptimeCheckConfigPathTemplate.match(projectUptimeCheckConfigName).project; + matchProjectFromProjectUptimeCheckConfigName( + projectUptimeCheckConfigName: string, + ) { + return this.pathTemplates.projectUptimeCheckConfigPathTemplate.match( + projectUptimeCheckConfigName, + ).project; } /** @@ -2817,8 +3476,12 @@ export class MetricServiceClient { * A fully-qualified path representing project_uptime_check_config resource. * @returns {string} A string representing the uptime_check_config. */ - matchUptimeCheckConfigFromProjectUptimeCheckConfigName(projectUptimeCheckConfigName: string) { - return this.pathTemplates.projectUptimeCheckConfigPathTemplate.match(projectUptimeCheckConfigName).uptime_check_config; + matchUptimeCheckConfigFromProjectUptimeCheckConfigName( + projectUptimeCheckConfigName: string, + ) { + return this.pathTemplates.projectUptimeCheckConfigPathTemplate.match( + projectUptimeCheckConfigName, + ).uptime_check_config; } /** @@ -2829,7 +3492,7 @@ export class MetricServiceClient { */ close(): Promise { if (this.metricServiceStub && !this._terminated) { - return this.metricServiceStub.then(stub => { + return this.metricServiceStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -2837,4 +3500,4 @@ export class MetricServiceClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/core/generator/gapic-generator-typescript/baselines/monitoring/src/v3/notification_channel_service_client.ts.baseline b/core/generator/gapic-generator-typescript/baselines/monitoring/src/v3/notification_channel_service_client.ts.baseline index 09b5f8ce54ed..92571aab818e 100644 --- a/core/generator/gapic-generator-typescript/baselines/monitoring/src/v3/notification_channel_service_client.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/monitoring/src/v3/notification_channel_service_client.ts.baseline @@ -18,11 +18,18 @@ /* global window */ import type * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions, PaginationCallback, GaxCall} from 'google-gax'; -import {Transform} from 'stream'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + PaginationCallback, + GaxCall, +} from 'google-gax'; +import { Transform } from 'stream'; import * as protos from '../../protos/protos'; import jsonProtos = require('../../protos/protos.json'); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; /** * Client JSON configuration object, loaded from @@ -45,7 +52,7 @@ export class NotificationChannelServiceClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('monitoring'); @@ -58,9 +65,9 @@ export class NotificationChannelServiceClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; - notificationChannelServiceStub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; + notificationChannelServiceStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of NotificationChannelServiceClient. @@ -101,21 +108,43 @@ export class NotificationChannelServiceClient { * const client = new NotificationChannelServiceClient({fallback: true}, gax); * ``` */ - constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { // Ensure that options include all the required fields. - const staticMembers = this.constructor as typeof NotificationChannelServiceClient; - if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { - throw new Error('Please set either universe_domain or universeDomain, but not both.'); + const staticMembers = this + .constructor as typeof NotificationChannelServiceClient; + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); } - const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; - this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; this._servicePath = 'monitoring.' + this._universeDomain; - const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; - const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. if (servicePath !== this._servicePath && !('scopes' in opts)) { @@ -137,7 +166,7 @@ export class NotificationChannelServiceClient { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; @@ -151,10 +180,7 @@ export class NotificationChannelServiceClient { } // Determine the client header string. - const clientHeader = [ - `gax/${this._gaxModule.version}`, - `gapic/${version}`, - ]; + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/${process.versions.node}`); } else { @@ -176,76 +202,83 @@ export class NotificationChannelServiceClient { // Create useful helper objects for these. this.pathTemplates = { folderAlertPolicyPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/alertPolicies/{alert_policy}' + 'folders/{folder}/alertPolicies/{alert_policy}', ), folderAlertPolicyConditionPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/alertPolicies/{alert_policy}/conditions/{condition}' + 'folders/{folder}/alertPolicies/{alert_policy}/conditions/{condition}', ), folderChannelDescriptorPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/notificationChannelDescriptors/{channel_descriptor}' + 'folders/{folder}/notificationChannelDescriptors/{channel_descriptor}', ), folderGroupPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/groups/{group}' + 'folders/{folder}/groups/{group}', ), folderNotificationChannelPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/notificationChannels/{notification_channel}' + 'folders/{folder}/notificationChannels/{notification_channel}', ), folderServicePathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/services/{service}' - ), - folderServiceServiceLevelObjectivePathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/services/{service}/serviceLevelObjectives/{service_level_objective}' + 'folders/{folder}/services/{service}', ), + folderServiceServiceLevelObjectivePathTemplate: + new this._gaxModule.PathTemplate( + 'folders/{folder}/services/{service}/serviceLevelObjectives/{service_level_objective}', + ), folderUptimeCheckConfigPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/uptimeCheckConfigs/{uptime_check_config}' + 'folders/{folder}/uptimeCheckConfigs/{uptime_check_config}', ), organizationAlertPolicyPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/alertPolicies/{alert_policy}' - ), - organizationAlertPolicyConditionPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/alertPolicies/{alert_policy}/conditions/{condition}' - ), - organizationChannelDescriptorPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/notificationChannelDescriptors/{channel_descriptor}' + 'organizations/{organization}/alertPolicies/{alert_policy}', ), + organizationAlertPolicyConditionPathTemplate: + new this._gaxModule.PathTemplate( + 'organizations/{organization}/alertPolicies/{alert_policy}/conditions/{condition}', + ), + organizationChannelDescriptorPathTemplate: + new this._gaxModule.PathTemplate( + 'organizations/{organization}/notificationChannelDescriptors/{channel_descriptor}', + ), organizationGroupPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/groups/{group}' - ), - organizationNotificationChannelPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/notificationChannels/{notification_channel}' + 'organizations/{organization}/groups/{group}', ), + organizationNotificationChannelPathTemplate: + new this._gaxModule.PathTemplate( + 'organizations/{organization}/notificationChannels/{notification_channel}', + ), organizationServicePathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/services/{service}' - ), - organizationServiceServiceLevelObjectivePathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/services/{service}/serviceLevelObjectives/{service_level_objective}' - ), - organizationUptimeCheckConfigPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/uptimeCheckConfigs/{uptime_check_config}' + 'organizations/{organization}/services/{service}', ), + organizationServiceServiceLevelObjectivePathTemplate: + new this._gaxModule.PathTemplate( + 'organizations/{organization}/services/{service}/serviceLevelObjectives/{service_level_objective}', + ), + organizationUptimeCheckConfigPathTemplate: + new this._gaxModule.PathTemplate( + 'organizations/{organization}/uptimeCheckConfigs/{uptime_check_config}', + ), projectAlertPolicyPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/alertPolicies/{alert_policy}' + 'projects/{project}/alertPolicies/{alert_policy}', ), projectAlertPolicyConditionPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/alertPolicies/{alert_policy}/conditions/{condition}' + 'projects/{project}/alertPolicies/{alert_policy}/conditions/{condition}', ), projectChannelDescriptorPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/notificationChannelDescriptors/{channel_descriptor}' + 'projects/{project}/notificationChannelDescriptors/{channel_descriptor}', ), projectGroupPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/groups/{group}' + 'projects/{project}/groups/{group}', ), projectNotificationChannelPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/notificationChannels/{notification_channel}' + 'projects/{project}/notificationChannels/{notification_channel}', ), projectServicePathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/services/{service}' - ), - projectServiceServiceLevelObjectivePathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/services/{service}/serviceLevelObjectives/{service_level_objective}' + 'projects/{project}/services/{service}', ), + projectServiceServiceLevelObjectivePathTemplate: + new this._gaxModule.PathTemplate( + 'projects/{project}/services/{service}/serviceLevelObjectives/{service_level_objective}', + ), projectUptimeCheckConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/uptimeCheckConfigs/{uptime_check_config}' + 'projects/{project}/uptimeCheckConfigs/{uptime_check_config}', ), }; @@ -253,16 +286,25 @@ export class NotificationChannelServiceClient { // (e.g. 50 results at a time, with tokens to get subsequent // pages). Denote the keys used for pagination and results. this.descriptors.page = { - listNotificationChannelDescriptors: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'channelDescriptors'), - listNotificationChannels: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'notificationChannels') + listNotificationChannelDescriptors: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'channelDescriptors', + ), + listNotificationChannels: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'notificationChannels', + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.monitoring.v3.NotificationChannelService', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.monitoring.v3.NotificationChannelService', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + { 'x-goog-api-client': clientHeader.join(' ') }, + ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -293,37 +335,51 @@ export class NotificationChannelServiceClient { // Put together the "service stub" for // google.monitoring.v3.NotificationChannelService. this.notificationChannelServiceStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.monitoring.v3.NotificationChannelService') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.monitoring.v3.NotificationChannelService', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.monitoring.v3.NotificationChannelService, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts, + this._providedCustomServicePath, + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const notificationChannelServiceStubMethods = - ['listNotificationChannelDescriptors', 'getNotificationChannelDescriptor', 'listNotificationChannels', 'getNotificationChannel', 'createNotificationChannel', 'updateNotificationChannel', 'deleteNotificationChannel', 'sendNotificationChannelVerificationCode', 'getNotificationChannelVerificationCode', 'verifyNotificationChannel']; + const notificationChannelServiceStubMethods = [ + 'listNotificationChannelDescriptors', + 'getNotificationChannelDescriptor', + 'listNotificationChannels', + 'getNotificationChannel', + 'createNotificationChannel', + 'updateNotificationChannel', + 'deleteNotificationChannel', + 'sendNotificationChannelVerificationCode', + 'getNotificationChannelVerificationCode', + 'verifyNotificationChannel', + ]; for (const methodName of notificationChannelServiceStubMethods) { const callPromise = this.notificationChannelServiceStub.then( - stub => (...args: Array<{}>) => { - if (this._terminated) { - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error|null|undefined) => () => { + (stub) => + (...args: Array<{}>) => { + if (this._terminated) { + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { throw err; - }); + }, + ); - const descriptor = - this.descriptors.page[methodName] || - undefined; + const descriptor = this.descriptors.page[methodName] || undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -338,8 +394,14 @@ export class NotificationChannelServiceClient { * @returns {string} The DNS address for this service. */ static get servicePath() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'monitoring.googleapis.com'; } @@ -350,8 +412,14 @@ export class NotificationChannelServiceClient { * @returns {string} The DNS address for this service. */ static get apiEndpoint() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'monitoring.googleapis.com'; } @@ -385,7 +453,7 @@ export class NotificationChannelServiceClient { return [ 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/monitoring', - 'https://www.googleapis.com/auth/monitoring.read' + 'https://www.googleapis.com/auth/monitoring.read', ]; } @@ -395,8 +463,9 @@ export class NotificationChannelServiceClient { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId(callback?: Callback): - Promise|void { + getProjectId( + callback?: Callback, + ): Promise | void { if (callback) { this.auth.getProjectId(callback); return; @@ -407,1163 +476,1615 @@ export class NotificationChannelServiceClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Gets a single channel descriptor. The descriptor indicates which fields - * are expected / permitted for a notification channel of the given type. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The channel type for which to execute the request. The format is - * `projects/[PROJECT_ID]/notificationChannelDescriptors/{channel_type}`. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.monitoring.v3.NotificationChannelDescriptor|NotificationChannelDescriptor}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v3/notification_channel_service.get_notification_channel_descriptor.js - * region_tag:monitoring_v3_generated_NotificationChannelService_GetNotificationChannelDescriptor_async - */ + /** + * Gets a single channel descriptor. The descriptor indicates which fields + * are expected / permitted for a notification channel of the given type. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The channel type for which to execute the request. The format is + * `projects/[PROJECT_ID]/notificationChannelDescriptors/{channel_type}`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.monitoring.v3.NotificationChannelDescriptor|NotificationChannelDescriptor}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v3/notification_channel_service.get_notification_channel_descriptor.js + * region_tag:monitoring_v3_generated_NotificationChannelService_GetNotificationChannelDescriptor_async + */ getNotificationChannelDescriptor( - request?: protos.google.monitoring.v3.IGetNotificationChannelDescriptorRequest, - options?: CallOptions): - Promise<[ - protos.google.monitoring.v3.INotificationChannelDescriptor, - protos.google.monitoring.v3.IGetNotificationChannelDescriptorRequest|undefined, {}|undefined - ]>; + request?: protos.google.monitoring.v3.IGetNotificationChannelDescriptorRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.monitoring.v3.INotificationChannelDescriptor, + ( + | protos.google.monitoring.v3.IGetNotificationChannelDescriptorRequest + | undefined + ), + {} | undefined, + ] + >; getNotificationChannelDescriptor( - request: protos.google.monitoring.v3.IGetNotificationChannelDescriptorRequest, - options: CallOptions, - callback: Callback< - protos.google.monitoring.v3.INotificationChannelDescriptor, - protos.google.monitoring.v3.IGetNotificationChannelDescriptorRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.IGetNotificationChannelDescriptorRequest, + options: CallOptions, + callback: Callback< + protos.google.monitoring.v3.INotificationChannelDescriptor, + | protos.google.monitoring.v3.IGetNotificationChannelDescriptorRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getNotificationChannelDescriptor( - request: protos.google.monitoring.v3.IGetNotificationChannelDescriptorRequest, - callback: Callback< - protos.google.monitoring.v3.INotificationChannelDescriptor, - protos.google.monitoring.v3.IGetNotificationChannelDescriptorRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.IGetNotificationChannelDescriptorRequest, + callback: Callback< + protos.google.monitoring.v3.INotificationChannelDescriptor, + | protos.google.monitoring.v3.IGetNotificationChannelDescriptorRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getNotificationChannelDescriptor( - request?: protos.google.monitoring.v3.IGetNotificationChannelDescriptorRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.monitoring.v3.INotificationChannelDescriptor, - protos.google.monitoring.v3.IGetNotificationChannelDescriptorRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.monitoring.v3.IGetNotificationChannelDescriptorRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.monitoring.v3.INotificationChannelDescriptor, - protos.google.monitoring.v3.IGetNotificationChannelDescriptorRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.monitoring.v3.INotificationChannelDescriptor, - protos.google.monitoring.v3.IGetNotificationChannelDescriptorRequest|undefined, {}|undefined - ]>|void { + | protos.google.monitoring.v3.IGetNotificationChannelDescriptorRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.monitoring.v3.INotificationChannelDescriptor, + | protos.google.monitoring.v3.IGetNotificationChannelDescriptorRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.monitoring.v3.INotificationChannelDescriptor, + ( + | protos.google.monitoring.v3.IGetNotificationChannelDescriptorRequest + | undefined + ), + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getNotificationChannelDescriptor request %j', request); - const wrappedCallback: Callback< - protos.google.monitoring.v3.INotificationChannelDescriptor, - protos.google.monitoring.v3.IGetNotificationChannelDescriptorRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.monitoring.v3.INotificationChannelDescriptor, + | protos.google.monitoring.v3.IGetNotificationChannelDescriptorRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { - this._log.info('getNotificationChannelDescriptor response %j', response); + this._log.info( + 'getNotificationChannelDescriptor response %j', + response, + ); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getNotificationChannelDescriptor(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.monitoring.v3.INotificationChannelDescriptor, - protos.google.monitoring.v3.IGetNotificationChannelDescriptorRequest|undefined, - {}|undefined - ]) => { - this._log.info('getNotificationChannelDescriptor response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getNotificationChannelDescriptor(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.monitoring.v3.INotificationChannelDescriptor, + ( + | protos.google.monitoring.v3.IGetNotificationChannelDescriptorRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info( + 'getNotificationChannelDescriptor response %j', + response, + ); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Gets a single notification channel. The channel includes the relevant - * configuration details with which the channel was created. However, the - * response may truncate or omit passwords, API keys, or other private key - * matter and thus the response may not be 100% identical to the information - * that was supplied in the call to the create method. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The channel for which to execute the request. The format is - * `projects/[PROJECT_ID]/notificationChannels/[CHANNEL_ID]`. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.monitoring.v3.NotificationChannel|NotificationChannel}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v3/notification_channel_service.get_notification_channel.js - * region_tag:monitoring_v3_generated_NotificationChannelService_GetNotificationChannel_async - */ + /** + * Gets a single notification channel. The channel includes the relevant + * configuration details with which the channel was created. However, the + * response may truncate or omit passwords, API keys, or other private key + * matter and thus the response may not be 100% identical to the information + * that was supplied in the call to the create method. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The channel for which to execute the request. The format is + * `projects/[PROJECT_ID]/notificationChannels/[CHANNEL_ID]`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.monitoring.v3.NotificationChannel|NotificationChannel}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v3/notification_channel_service.get_notification_channel.js + * region_tag:monitoring_v3_generated_NotificationChannelService_GetNotificationChannel_async + */ getNotificationChannel( - request?: protos.google.monitoring.v3.IGetNotificationChannelRequest, - options?: CallOptions): - Promise<[ - protos.google.monitoring.v3.INotificationChannel, - protos.google.monitoring.v3.IGetNotificationChannelRequest|undefined, {}|undefined - ]>; + request?: protos.google.monitoring.v3.IGetNotificationChannelRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.monitoring.v3.INotificationChannel, + protos.google.monitoring.v3.IGetNotificationChannelRequest | undefined, + {} | undefined, + ] + >; getNotificationChannel( - request: protos.google.monitoring.v3.IGetNotificationChannelRequest, - options: CallOptions, - callback: Callback< - protos.google.monitoring.v3.INotificationChannel, - protos.google.monitoring.v3.IGetNotificationChannelRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.IGetNotificationChannelRequest, + options: CallOptions, + callback: Callback< + protos.google.monitoring.v3.INotificationChannel, + | protos.google.monitoring.v3.IGetNotificationChannelRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getNotificationChannel( - request: protos.google.monitoring.v3.IGetNotificationChannelRequest, - callback: Callback< - protos.google.monitoring.v3.INotificationChannel, - protos.google.monitoring.v3.IGetNotificationChannelRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.IGetNotificationChannelRequest, + callback: Callback< + protos.google.monitoring.v3.INotificationChannel, + | protos.google.monitoring.v3.IGetNotificationChannelRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getNotificationChannel( - request?: protos.google.monitoring.v3.IGetNotificationChannelRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.monitoring.v3.INotificationChannel, - protos.google.monitoring.v3.IGetNotificationChannelRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.monitoring.v3.IGetNotificationChannelRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.monitoring.v3.INotificationChannel, - protos.google.monitoring.v3.IGetNotificationChannelRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.monitoring.v3.INotificationChannel, - protos.google.monitoring.v3.IGetNotificationChannelRequest|undefined, {}|undefined - ]>|void { + | protos.google.monitoring.v3.IGetNotificationChannelRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.monitoring.v3.INotificationChannel, + | protos.google.monitoring.v3.IGetNotificationChannelRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.monitoring.v3.INotificationChannel, + protos.google.monitoring.v3.IGetNotificationChannelRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getNotificationChannel request %j', request); - const wrappedCallback: Callback< - protos.google.monitoring.v3.INotificationChannel, - protos.google.monitoring.v3.IGetNotificationChannelRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.monitoring.v3.INotificationChannel, + | protos.google.monitoring.v3.IGetNotificationChannelRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getNotificationChannel response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getNotificationChannel(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.monitoring.v3.INotificationChannel, - protos.google.monitoring.v3.IGetNotificationChannelRequest|undefined, - {}|undefined - ]) => { - this._log.info('getNotificationChannel response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getNotificationChannel(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.monitoring.v3.INotificationChannel, + ( + | protos.google.monitoring.v3.IGetNotificationChannelRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('getNotificationChannel response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Creates a new notification channel, representing a single notification - * endpoint such as an email address, SMS number, or PagerDuty service. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The project on which to execute the request. The format is: - * - * projects/[PROJECT_ID] - * - * Note that this names the container into which the channel will be - * written. This does not name the newly created channel. The resulting - * channel's name will have a normalized version of this field as a prefix, - * but will add `/notificationChannels/[CHANNEL_ID]` to identify the channel. - * @param {google.monitoring.v3.NotificationChannel} request.notificationChannel - * Required. The definition of the `NotificationChannel` to create. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.monitoring.v3.NotificationChannel|NotificationChannel}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v3/notification_channel_service.create_notification_channel.js - * region_tag:monitoring_v3_generated_NotificationChannelService_CreateNotificationChannel_async - */ + /** + * Creates a new notification channel, representing a single notification + * endpoint such as an email address, SMS number, or PagerDuty service. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The project on which to execute the request. The format is: + * + * projects/[PROJECT_ID] + * + * Note that this names the container into which the channel will be + * written. This does not name the newly created channel. The resulting + * channel's name will have a normalized version of this field as a prefix, + * but will add `/notificationChannels/[CHANNEL_ID]` to identify the channel. + * @param {google.monitoring.v3.NotificationChannel} request.notificationChannel + * Required. The definition of the `NotificationChannel` to create. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.monitoring.v3.NotificationChannel|NotificationChannel}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v3/notification_channel_service.create_notification_channel.js + * region_tag:monitoring_v3_generated_NotificationChannelService_CreateNotificationChannel_async + */ createNotificationChannel( - request?: protos.google.monitoring.v3.ICreateNotificationChannelRequest, - options?: CallOptions): - Promise<[ - protos.google.monitoring.v3.INotificationChannel, - protos.google.monitoring.v3.ICreateNotificationChannelRequest|undefined, {}|undefined - ]>; + request?: protos.google.monitoring.v3.ICreateNotificationChannelRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.monitoring.v3.INotificationChannel, + protos.google.monitoring.v3.ICreateNotificationChannelRequest | undefined, + {} | undefined, + ] + >; createNotificationChannel( - request: protos.google.monitoring.v3.ICreateNotificationChannelRequest, - options: CallOptions, - callback: Callback< - protos.google.monitoring.v3.INotificationChannel, - protos.google.monitoring.v3.ICreateNotificationChannelRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.ICreateNotificationChannelRequest, + options: CallOptions, + callback: Callback< + protos.google.monitoring.v3.INotificationChannel, + | protos.google.monitoring.v3.ICreateNotificationChannelRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createNotificationChannel( - request: protos.google.monitoring.v3.ICreateNotificationChannelRequest, - callback: Callback< - protos.google.monitoring.v3.INotificationChannel, - protos.google.monitoring.v3.ICreateNotificationChannelRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.ICreateNotificationChannelRequest, + callback: Callback< + protos.google.monitoring.v3.INotificationChannel, + | protos.google.monitoring.v3.ICreateNotificationChannelRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createNotificationChannel( - request?: protos.google.monitoring.v3.ICreateNotificationChannelRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.monitoring.v3.ICreateNotificationChannelRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.monitoring.v3.INotificationChannel, - protos.google.monitoring.v3.ICreateNotificationChannelRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.monitoring.v3.INotificationChannel, - protos.google.monitoring.v3.ICreateNotificationChannelRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.monitoring.v3.INotificationChannel, - protos.google.monitoring.v3.ICreateNotificationChannelRequest|undefined, {}|undefined - ]>|void { + | protos.google.monitoring.v3.ICreateNotificationChannelRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.monitoring.v3.INotificationChannel, + | protos.google.monitoring.v3.ICreateNotificationChannelRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.monitoring.v3.INotificationChannel, + protos.google.monitoring.v3.ICreateNotificationChannelRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('createNotificationChannel request %j', request); - const wrappedCallback: Callback< - protos.google.monitoring.v3.INotificationChannel, - protos.google.monitoring.v3.ICreateNotificationChannelRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.monitoring.v3.INotificationChannel, + | protos.google.monitoring.v3.ICreateNotificationChannelRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createNotificationChannel response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.createNotificationChannel(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.monitoring.v3.INotificationChannel, - protos.google.monitoring.v3.ICreateNotificationChannelRequest|undefined, - {}|undefined - ]) => { - this._log.info('createNotificationChannel response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createNotificationChannel(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.monitoring.v3.INotificationChannel, + ( + | protos.google.monitoring.v3.ICreateNotificationChannelRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('createNotificationChannel response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Updates a notification channel. Fields not specified in the field mask - * remain unchanged. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.protobuf.FieldMask} request.updateMask - * The fields to update. - * @param {google.monitoring.v3.NotificationChannel} request.notificationChannel - * Required. A description of the changes to be applied to the specified - * notification channel. The description must provide a definition for - * fields to be updated; the names of these fields should also be - * included in the `update_mask`. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.monitoring.v3.NotificationChannel|NotificationChannel}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v3/notification_channel_service.update_notification_channel.js - * region_tag:monitoring_v3_generated_NotificationChannelService_UpdateNotificationChannel_async - */ + /** + * Updates a notification channel. Fields not specified in the field mask + * remain unchanged. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.protobuf.FieldMask} request.updateMask + * The fields to update. + * @param {google.monitoring.v3.NotificationChannel} request.notificationChannel + * Required. A description of the changes to be applied to the specified + * notification channel. The description must provide a definition for + * fields to be updated; the names of these fields should also be + * included in the `update_mask`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.monitoring.v3.NotificationChannel|NotificationChannel}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v3/notification_channel_service.update_notification_channel.js + * region_tag:monitoring_v3_generated_NotificationChannelService_UpdateNotificationChannel_async + */ updateNotificationChannel( - request?: protos.google.monitoring.v3.IUpdateNotificationChannelRequest, - options?: CallOptions): - Promise<[ - protos.google.monitoring.v3.INotificationChannel, - protos.google.monitoring.v3.IUpdateNotificationChannelRequest|undefined, {}|undefined - ]>; + request?: protos.google.monitoring.v3.IUpdateNotificationChannelRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.monitoring.v3.INotificationChannel, + protos.google.monitoring.v3.IUpdateNotificationChannelRequest | undefined, + {} | undefined, + ] + >; updateNotificationChannel( - request: protos.google.monitoring.v3.IUpdateNotificationChannelRequest, - options: CallOptions, - callback: Callback< - protos.google.monitoring.v3.INotificationChannel, - protos.google.monitoring.v3.IUpdateNotificationChannelRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.IUpdateNotificationChannelRequest, + options: CallOptions, + callback: Callback< + protos.google.monitoring.v3.INotificationChannel, + | protos.google.monitoring.v3.IUpdateNotificationChannelRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateNotificationChannel( - request: protos.google.monitoring.v3.IUpdateNotificationChannelRequest, - callback: Callback< - protos.google.monitoring.v3.INotificationChannel, - protos.google.monitoring.v3.IUpdateNotificationChannelRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.IUpdateNotificationChannelRequest, + callback: Callback< + protos.google.monitoring.v3.INotificationChannel, + | protos.google.monitoring.v3.IUpdateNotificationChannelRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateNotificationChannel( - request?: protos.google.monitoring.v3.IUpdateNotificationChannelRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.monitoring.v3.IUpdateNotificationChannelRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.monitoring.v3.INotificationChannel, - protos.google.monitoring.v3.IUpdateNotificationChannelRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.monitoring.v3.INotificationChannel, - protos.google.monitoring.v3.IUpdateNotificationChannelRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.monitoring.v3.INotificationChannel, - protos.google.monitoring.v3.IUpdateNotificationChannelRequest|undefined, {}|undefined - ]>|void { + | protos.google.monitoring.v3.IUpdateNotificationChannelRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.monitoring.v3.INotificationChannel, + | protos.google.monitoring.v3.IUpdateNotificationChannelRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.monitoring.v3.INotificationChannel, + protos.google.monitoring.v3.IUpdateNotificationChannelRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'notification_channel.name': request.notificationChannel!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'notification_channel.name': request.notificationChannel!.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateNotificationChannel request %j', request); - const wrappedCallback: Callback< - protos.google.monitoring.v3.INotificationChannel, - protos.google.monitoring.v3.IUpdateNotificationChannelRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.monitoring.v3.INotificationChannel, + | protos.google.monitoring.v3.IUpdateNotificationChannelRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateNotificationChannel response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.updateNotificationChannel(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.monitoring.v3.INotificationChannel, - protos.google.monitoring.v3.IUpdateNotificationChannelRequest|undefined, - {}|undefined - ]) => { - this._log.info('updateNotificationChannel response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateNotificationChannel(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.monitoring.v3.INotificationChannel, + ( + | protos.google.monitoring.v3.IUpdateNotificationChannelRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('updateNotificationChannel response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Deletes a notification channel. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The channel for which to execute the request. The format is - * `projects/[PROJECT_ID]/notificationChannels/[CHANNEL_ID]`. - * @param {boolean} request.force - * If true, the notification channel will be deleted regardless of its - * use in alert policies (the policies will be updated to remove the - * channel). If false, channels that are still referenced by an existing - * alerting policy will fail to be deleted in a delete operation. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v3/notification_channel_service.delete_notification_channel.js - * region_tag:monitoring_v3_generated_NotificationChannelService_DeleteNotificationChannel_async - */ + /** + * Deletes a notification channel. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The channel for which to execute the request. The format is + * `projects/[PROJECT_ID]/notificationChannels/[CHANNEL_ID]`. + * @param {boolean} request.force + * If true, the notification channel will be deleted regardless of its + * use in alert policies (the policies will be updated to remove the + * channel). If false, channels that are still referenced by an existing + * alerting policy will fail to be deleted in a delete operation. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v3/notification_channel_service.delete_notification_channel.js + * region_tag:monitoring_v3_generated_NotificationChannelService_DeleteNotificationChannel_async + */ deleteNotificationChannel( - request?: protos.google.monitoring.v3.IDeleteNotificationChannelRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.IDeleteNotificationChannelRequest|undefined, {}|undefined - ]>; + request?: protos.google.monitoring.v3.IDeleteNotificationChannelRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.monitoring.v3.IDeleteNotificationChannelRequest | undefined, + {} | undefined, + ] + >; deleteNotificationChannel( - request: protos.google.monitoring.v3.IDeleteNotificationChannelRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.IDeleteNotificationChannelRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.IDeleteNotificationChannelRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.monitoring.v3.IDeleteNotificationChannelRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteNotificationChannel( - request: protos.google.monitoring.v3.IDeleteNotificationChannelRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.IDeleteNotificationChannelRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.IDeleteNotificationChannelRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.monitoring.v3.IDeleteNotificationChannelRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteNotificationChannel( - request?: protos.google.monitoring.v3.IDeleteNotificationChannelRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.IDeleteNotificationChannelRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.monitoring.v3.IDeleteNotificationChannelRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.IDeleteNotificationChannelRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.IDeleteNotificationChannelRequest|undefined, {}|undefined - ]>|void { + | protos.google.monitoring.v3.IDeleteNotificationChannelRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + | protos.google.monitoring.v3.IDeleteNotificationChannelRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.monitoring.v3.IDeleteNotificationChannelRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('deleteNotificationChannel request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.IDeleteNotificationChannelRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.monitoring.v3.IDeleteNotificationChannelRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteNotificationChannel response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.deleteNotificationChannel(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.IDeleteNotificationChannelRequest|undefined, - {}|undefined - ]) => { - this._log.info('deleteNotificationChannel response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteNotificationChannel(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + ( + | protos.google.monitoring.v3.IDeleteNotificationChannelRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('deleteNotificationChannel response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Causes a verification code to be delivered to the channel. The code - * can then be supplied in `VerifyNotificationChannel` to verify the channel. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The notification channel to which to send a verification code. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v3/notification_channel_service.send_notification_channel_verification_code.js - * region_tag:monitoring_v3_generated_NotificationChannelService_SendNotificationChannelVerificationCode_async - */ + /** + * Causes a verification code to be delivered to the channel. The code + * can then be supplied in `VerifyNotificationChannel` to verify the channel. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The notification channel to which to send a verification code. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v3/notification_channel_service.send_notification_channel_verification_code.js + * region_tag:monitoring_v3_generated_NotificationChannelService_SendNotificationChannelVerificationCode_async + */ sendNotificationChannelVerificationCode( - request?: protos.google.monitoring.v3.ISendNotificationChannelVerificationCodeRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.ISendNotificationChannelVerificationCodeRequest|undefined, {}|undefined - ]>; + request?: protos.google.monitoring.v3.ISendNotificationChannelVerificationCodeRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.monitoring.v3.ISendNotificationChannelVerificationCodeRequest + | undefined + ), + {} | undefined, + ] + >; sendNotificationChannelVerificationCode( - request: protos.google.monitoring.v3.ISendNotificationChannelVerificationCodeRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.ISendNotificationChannelVerificationCodeRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.ISendNotificationChannelVerificationCodeRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.monitoring.v3.ISendNotificationChannelVerificationCodeRequest + | null + | undefined, + {} | null | undefined + >, + ): void; sendNotificationChannelVerificationCode( - request: protos.google.monitoring.v3.ISendNotificationChannelVerificationCodeRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.ISendNotificationChannelVerificationCodeRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.ISendNotificationChannelVerificationCodeRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.monitoring.v3.ISendNotificationChannelVerificationCodeRequest + | null + | undefined, + {} | null | undefined + >, + ): void; sendNotificationChannelVerificationCode( - request?: protos.google.monitoring.v3.ISendNotificationChannelVerificationCodeRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.ISendNotificationChannelVerificationCodeRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.monitoring.v3.ISendNotificationChannelVerificationCodeRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.ISendNotificationChannelVerificationCodeRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.ISendNotificationChannelVerificationCodeRequest|undefined, {}|undefined - ]>|void { + | protos.google.monitoring.v3.ISendNotificationChannelVerificationCodeRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + | protos.google.monitoring.v3.ISendNotificationChannelVerificationCodeRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.monitoring.v3.ISendNotificationChannelVerificationCodeRequest + | undefined + ), + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - this._log.info('sendNotificationChannelVerificationCode request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.ISendNotificationChannelVerificationCodeRequest|null|undefined, - {}|null|undefined>|undefined = callback + this._log.info( + 'sendNotificationChannelVerificationCode request %j', + request, + ); + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.monitoring.v3.ISendNotificationChannelVerificationCodeRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { - this._log.info('sendNotificationChannelVerificationCode response %j', response); + this._log.info( + 'sendNotificationChannelVerificationCode response %j', + response, + ); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.sendNotificationChannelVerificationCode(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.ISendNotificationChannelVerificationCodeRequest|undefined, - {}|undefined - ]) => { - this._log.info('sendNotificationChannelVerificationCode response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .sendNotificationChannelVerificationCode( + request, + options, + wrappedCallback, + ) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + ( + | protos.google.monitoring.v3.ISendNotificationChannelVerificationCodeRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info( + 'sendNotificationChannelVerificationCode response %j', + response, + ); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Requests a verification code for an already verified channel that can then - * be used in a call to VerifyNotificationChannel() on a different channel - * with an equivalent identity in the same or in a different project. This - * makes it possible to copy a channel between projects without requiring - * manual reverification of the channel. If the channel is not in the - * verified state, this method will fail (in other words, this may only be - * used if the SendNotificationChannelVerificationCode and - * VerifyNotificationChannel paths have already been used to put the given - * channel into the verified state). - * - * There is no guarantee that the verification codes returned by this method - * will be of a similar structure or form as the ones that are delivered - * to the channel via SendNotificationChannelVerificationCode; while - * VerifyNotificationChannel() will recognize both the codes delivered via - * SendNotificationChannelVerificationCode() and returned from - * GetNotificationChannelVerificationCode(), it is typically the case that - * the verification codes delivered via - * SendNotificationChannelVerificationCode() will be shorter and also - * have a shorter expiration (e.g. codes such as "G-123456") whereas - * GetVerificationCode() will typically return a much longer, websafe base - * 64 encoded string that has a longer expiration time. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The notification channel for which a verification code is to be generated - * and retrieved. This must name a channel that is already verified; if - * the specified channel is not verified, the request will fail. - * @param {google.protobuf.Timestamp} request.expireTime - * The desired expiration time. If specified, the API will guarantee that - * the returned code will not be valid after the specified timestamp; - * however, the API cannot guarantee that the returned code will be - * valid for at least as long as the requested time (the API puts an upper - * bound on the amount of time for which a code may be valid). If omitted, - * a default expiration will be used, which may be less than the max - * permissible expiration (so specifying an expiration may extend the - * code's lifetime over omitting an expiration, even though the API does - * impose an upper limit on the maximum expiration that is permitted). - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.monitoring.v3.GetNotificationChannelVerificationCodeResponse|GetNotificationChannelVerificationCodeResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v3/notification_channel_service.get_notification_channel_verification_code.js - * region_tag:monitoring_v3_generated_NotificationChannelService_GetNotificationChannelVerificationCode_async - */ + /** + * Requests a verification code for an already verified channel that can then + * be used in a call to VerifyNotificationChannel() on a different channel + * with an equivalent identity in the same or in a different project. This + * makes it possible to copy a channel between projects without requiring + * manual reverification of the channel. If the channel is not in the + * verified state, this method will fail (in other words, this may only be + * used if the SendNotificationChannelVerificationCode and + * VerifyNotificationChannel paths have already been used to put the given + * channel into the verified state). + * + * There is no guarantee that the verification codes returned by this method + * will be of a similar structure or form as the ones that are delivered + * to the channel via SendNotificationChannelVerificationCode; while + * VerifyNotificationChannel() will recognize both the codes delivered via + * SendNotificationChannelVerificationCode() and returned from + * GetNotificationChannelVerificationCode(), it is typically the case that + * the verification codes delivered via + * SendNotificationChannelVerificationCode() will be shorter and also + * have a shorter expiration (e.g. codes such as "G-123456") whereas + * GetVerificationCode() will typically return a much longer, websafe base + * 64 encoded string that has a longer expiration time. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The notification channel for which a verification code is to be generated + * and retrieved. This must name a channel that is already verified; if + * the specified channel is not verified, the request will fail. + * @param {google.protobuf.Timestamp} request.expireTime + * The desired expiration time. If specified, the API will guarantee that + * the returned code will not be valid after the specified timestamp; + * however, the API cannot guarantee that the returned code will be + * valid for at least as long as the requested time (the API puts an upper + * bound on the amount of time for which a code may be valid). If omitted, + * a default expiration will be used, which may be less than the max + * permissible expiration (so specifying an expiration may extend the + * code's lifetime over omitting an expiration, even though the API does + * impose an upper limit on the maximum expiration that is permitted). + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.monitoring.v3.GetNotificationChannelVerificationCodeResponse|GetNotificationChannelVerificationCodeResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v3/notification_channel_service.get_notification_channel_verification_code.js + * region_tag:monitoring_v3_generated_NotificationChannelService_GetNotificationChannelVerificationCode_async + */ getNotificationChannelVerificationCode( - request?: protos.google.monitoring.v3.IGetNotificationChannelVerificationCodeRequest, - options?: CallOptions): - Promise<[ - protos.google.monitoring.v3.IGetNotificationChannelVerificationCodeResponse, - protos.google.monitoring.v3.IGetNotificationChannelVerificationCodeRequest|undefined, {}|undefined - ]>; + request?: protos.google.monitoring.v3.IGetNotificationChannelVerificationCodeRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.monitoring.v3.IGetNotificationChannelVerificationCodeResponse, + ( + | protos.google.monitoring.v3.IGetNotificationChannelVerificationCodeRequest + | undefined + ), + {} | undefined, + ] + >; getNotificationChannelVerificationCode( - request: protos.google.monitoring.v3.IGetNotificationChannelVerificationCodeRequest, - options: CallOptions, - callback: Callback< - protos.google.monitoring.v3.IGetNotificationChannelVerificationCodeResponse, - protos.google.monitoring.v3.IGetNotificationChannelVerificationCodeRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.IGetNotificationChannelVerificationCodeRequest, + options: CallOptions, + callback: Callback< + protos.google.monitoring.v3.IGetNotificationChannelVerificationCodeResponse, + | protos.google.monitoring.v3.IGetNotificationChannelVerificationCodeRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getNotificationChannelVerificationCode( - request: protos.google.monitoring.v3.IGetNotificationChannelVerificationCodeRequest, - callback: Callback< - protos.google.monitoring.v3.IGetNotificationChannelVerificationCodeResponse, - protos.google.monitoring.v3.IGetNotificationChannelVerificationCodeRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.IGetNotificationChannelVerificationCodeRequest, + callback: Callback< + protos.google.monitoring.v3.IGetNotificationChannelVerificationCodeResponse, + | protos.google.monitoring.v3.IGetNotificationChannelVerificationCodeRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getNotificationChannelVerificationCode( - request?: protos.google.monitoring.v3.IGetNotificationChannelVerificationCodeRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.monitoring.v3.IGetNotificationChannelVerificationCodeResponse, - protos.google.monitoring.v3.IGetNotificationChannelVerificationCodeRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.monitoring.v3.IGetNotificationChannelVerificationCodeRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.monitoring.v3.IGetNotificationChannelVerificationCodeResponse, - protos.google.monitoring.v3.IGetNotificationChannelVerificationCodeRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.monitoring.v3.IGetNotificationChannelVerificationCodeResponse, - protos.google.monitoring.v3.IGetNotificationChannelVerificationCodeRequest|undefined, {}|undefined - ]>|void { + | protos.google.monitoring.v3.IGetNotificationChannelVerificationCodeRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.monitoring.v3.IGetNotificationChannelVerificationCodeResponse, + | protos.google.monitoring.v3.IGetNotificationChannelVerificationCodeRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.monitoring.v3.IGetNotificationChannelVerificationCodeResponse, + ( + | protos.google.monitoring.v3.IGetNotificationChannelVerificationCodeRequest + | undefined + ), + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - this._log.info('getNotificationChannelVerificationCode request %j', request); - const wrappedCallback: Callback< - protos.google.monitoring.v3.IGetNotificationChannelVerificationCodeResponse, - protos.google.monitoring.v3.IGetNotificationChannelVerificationCodeRequest|null|undefined, - {}|null|undefined>|undefined = callback + this._log.info( + 'getNotificationChannelVerificationCode request %j', + request, + ); + const wrappedCallback: + | Callback< + protos.google.monitoring.v3.IGetNotificationChannelVerificationCodeResponse, + | protos.google.monitoring.v3.IGetNotificationChannelVerificationCodeRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { - this._log.info('getNotificationChannelVerificationCode response %j', response); + this._log.info( + 'getNotificationChannelVerificationCode response %j', + response, + ); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getNotificationChannelVerificationCode(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.monitoring.v3.IGetNotificationChannelVerificationCodeResponse, - protos.google.monitoring.v3.IGetNotificationChannelVerificationCodeRequest|undefined, - {}|undefined - ]) => { - this._log.info('getNotificationChannelVerificationCode response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getNotificationChannelVerificationCode(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.monitoring.v3.IGetNotificationChannelVerificationCodeResponse, + ( + | protos.google.monitoring.v3.IGetNotificationChannelVerificationCodeRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info( + 'getNotificationChannelVerificationCode response %j', + response, + ); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Verifies a `NotificationChannel` by proving receipt of the code - * delivered to the channel as a result of calling - * `SendNotificationChannelVerificationCode`. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The notification channel to verify. - * @param {string} request.code - * Required. The verification code that was delivered to the channel as - * a result of invoking the `SendNotificationChannelVerificationCode` API - * method or that was retrieved from a verified channel via - * `GetNotificationChannelVerificationCode`. For example, one might have - * "G-123456" or "TKNZGhhd2EyN3I1MnRnMjRv" (in general, one is only - * guaranteed that the code is valid UTF-8; one should not - * make any assumptions regarding the structure or format of the code). - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.monitoring.v3.NotificationChannel|NotificationChannel}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v3/notification_channel_service.verify_notification_channel.js - * region_tag:monitoring_v3_generated_NotificationChannelService_VerifyNotificationChannel_async - */ + /** + * Verifies a `NotificationChannel` by proving receipt of the code + * delivered to the channel as a result of calling + * `SendNotificationChannelVerificationCode`. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The notification channel to verify. + * @param {string} request.code + * Required. The verification code that was delivered to the channel as + * a result of invoking the `SendNotificationChannelVerificationCode` API + * method or that was retrieved from a verified channel via + * `GetNotificationChannelVerificationCode`. For example, one might have + * "G-123456" or "TKNZGhhd2EyN3I1MnRnMjRv" (in general, one is only + * guaranteed that the code is valid UTF-8; one should not + * make any assumptions regarding the structure or format of the code). + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.monitoring.v3.NotificationChannel|NotificationChannel}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v3/notification_channel_service.verify_notification_channel.js + * region_tag:monitoring_v3_generated_NotificationChannelService_VerifyNotificationChannel_async + */ verifyNotificationChannel( - request?: protos.google.monitoring.v3.IVerifyNotificationChannelRequest, - options?: CallOptions): - Promise<[ - protos.google.monitoring.v3.INotificationChannel, - protos.google.monitoring.v3.IVerifyNotificationChannelRequest|undefined, {}|undefined - ]>; + request?: protos.google.monitoring.v3.IVerifyNotificationChannelRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.monitoring.v3.INotificationChannel, + protos.google.monitoring.v3.IVerifyNotificationChannelRequest | undefined, + {} | undefined, + ] + >; verifyNotificationChannel( - request: protos.google.monitoring.v3.IVerifyNotificationChannelRequest, - options: CallOptions, - callback: Callback< - protos.google.monitoring.v3.INotificationChannel, - protos.google.monitoring.v3.IVerifyNotificationChannelRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.IVerifyNotificationChannelRequest, + options: CallOptions, + callback: Callback< + protos.google.monitoring.v3.INotificationChannel, + | protos.google.monitoring.v3.IVerifyNotificationChannelRequest + | null + | undefined, + {} | null | undefined + >, + ): void; verifyNotificationChannel( - request: protos.google.monitoring.v3.IVerifyNotificationChannelRequest, - callback: Callback< - protos.google.monitoring.v3.INotificationChannel, - protos.google.monitoring.v3.IVerifyNotificationChannelRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.IVerifyNotificationChannelRequest, + callback: Callback< + protos.google.monitoring.v3.INotificationChannel, + | protos.google.monitoring.v3.IVerifyNotificationChannelRequest + | null + | undefined, + {} | null | undefined + >, + ): void; verifyNotificationChannel( - request?: protos.google.monitoring.v3.IVerifyNotificationChannelRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.monitoring.v3.IVerifyNotificationChannelRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.monitoring.v3.INotificationChannel, - protos.google.monitoring.v3.IVerifyNotificationChannelRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.monitoring.v3.INotificationChannel, - protos.google.monitoring.v3.IVerifyNotificationChannelRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.monitoring.v3.INotificationChannel, - protos.google.monitoring.v3.IVerifyNotificationChannelRequest|undefined, {}|undefined - ]>|void { + | protos.google.monitoring.v3.IVerifyNotificationChannelRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.monitoring.v3.INotificationChannel, + | protos.google.monitoring.v3.IVerifyNotificationChannelRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.monitoring.v3.INotificationChannel, + protos.google.monitoring.v3.IVerifyNotificationChannelRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('verifyNotificationChannel request %j', request); - const wrappedCallback: Callback< - protos.google.monitoring.v3.INotificationChannel, - protos.google.monitoring.v3.IVerifyNotificationChannelRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.monitoring.v3.INotificationChannel, + | protos.google.monitoring.v3.IVerifyNotificationChannelRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('verifyNotificationChannel response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.verifyNotificationChannel(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.monitoring.v3.INotificationChannel, - protos.google.monitoring.v3.IVerifyNotificationChannelRequest|undefined, - {}|undefined - ]) => { - this._log.info('verifyNotificationChannel response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .verifyNotificationChannel(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.monitoring.v3.INotificationChannel, + ( + | protos.google.monitoring.v3.IVerifyNotificationChannelRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('verifyNotificationChannel response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } - /** - * Lists the descriptors for supported channel types. The use of descriptors - * makes it possible for new channel types to be dynamically added. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The REST resource name of the parent from which to retrieve - * the notification channel descriptors. The expected syntax is: - * - * projects/[PROJECT_ID] - * - * Note that this names the parent container in which to look for the - * descriptors; to retrieve a single descriptor by name, use the - * {@link protos.google.monitoring.v3.NotificationChannelService.GetNotificationChannelDescriptor|GetNotificationChannelDescriptor} - * operation, instead. - * @param {number} request.pageSize - * The maximum number of results to return in a single response. If - * not set to a positive number, a reasonable value will be chosen by the - * service. - * @param {string} request.pageToken - * If non-empty, `page_token` must contain a value returned as the - * `next_page_token` in a previous response to request the next set - * of results. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.monitoring.v3.NotificationChannelDescriptor|NotificationChannelDescriptor}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `listNotificationChannelDescriptorsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Lists the descriptors for supported channel types. The use of descriptors + * makes it possible for new channel types to be dynamically added. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The REST resource name of the parent from which to retrieve + * the notification channel descriptors. The expected syntax is: + * + * projects/[PROJECT_ID] + * + * Note that this names the parent container in which to look for the + * descriptors; to retrieve a single descriptor by name, use the + * {@link protos.google.monitoring.v3.NotificationChannelService.GetNotificationChannelDescriptor|GetNotificationChannelDescriptor} + * operation, instead. + * @param {number} request.pageSize + * The maximum number of results to return in a single response. If + * not set to a positive number, a reasonable value will be chosen by the + * service. + * @param {string} request.pageToken + * If non-empty, `page_token` must contain a value returned as the + * `next_page_token` in a previous response to request the next set + * of results. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.monitoring.v3.NotificationChannelDescriptor|NotificationChannelDescriptor}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listNotificationChannelDescriptorsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listNotificationChannelDescriptors( - request?: protos.google.monitoring.v3.IListNotificationChannelDescriptorsRequest, - options?: CallOptions): - Promise<[ - protos.google.monitoring.v3.INotificationChannelDescriptor[], - protos.google.monitoring.v3.IListNotificationChannelDescriptorsRequest|null, - protos.google.monitoring.v3.IListNotificationChannelDescriptorsResponse - ]>; + request?: protos.google.monitoring.v3.IListNotificationChannelDescriptorsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.monitoring.v3.INotificationChannelDescriptor[], + protos.google.monitoring.v3.IListNotificationChannelDescriptorsRequest | null, + protos.google.monitoring.v3.IListNotificationChannelDescriptorsResponse, + ] + >; listNotificationChannelDescriptors( - request: protos.google.monitoring.v3.IListNotificationChannelDescriptorsRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.monitoring.v3.IListNotificationChannelDescriptorsRequest, - protos.google.monitoring.v3.IListNotificationChannelDescriptorsResponse|null|undefined, - protos.google.monitoring.v3.INotificationChannelDescriptor>): void; + request: protos.google.monitoring.v3.IListNotificationChannelDescriptorsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.monitoring.v3.IListNotificationChannelDescriptorsRequest, + | protos.google.monitoring.v3.IListNotificationChannelDescriptorsResponse + | null + | undefined, + protos.google.monitoring.v3.INotificationChannelDescriptor + >, + ): void; listNotificationChannelDescriptors( - request: protos.google.monitoring.v3.IListNotificationChannelDescriptorsRequest, - callback: PaginationCallback< - protos.google.monitoring.v3.IListNotificationChannelDescriptorsRequest, - protos.google.monitoring.v3.IListNotificationChannelDescriptorsResponse|null|undefined, - protos.google.monitoring.v3.INotificationChannelDescriptor>): void; + request: protos.google.monitoring.v3.IListNotificationChannelDescriptorsRequest, + callback: PaginationCallback< + protos.google.monitoring.v3.IListNotificationChannelDescriptorsRequest, + | protos.google.monitoring.v3.IListNotificationChannelDescriptorsResponse + | null + | undefined, + protos.google.monitoring.v3.INotificationChannelDescriptor + >, + ): void; listNotificationChannelDescriptors( - request?: protos.google.monitoring.v3.IListNotificationChannelDescriptorsRequest, - optionsOrCallback?: CallOptions|PaginationCallback< - protos.google.monitoring.v3.IListNotificationChannelDescriptorsRequest, - protos.google.monitoring.v3.IListNotificationChannelDescriptorsResponse|null|undefined, - protos.google.monitoring.v3.INotificationChannelDescriptor>, - callback?: PaginationCallback< + request?: protos.google.monitoring.v3.IListNotificationChannelDescriptorsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.monitoring.v3.IListNotificationChannelDescriptorsRequest, - protos.google.monitoring.v3.IListNotificationChannelDescriptorsResponse|null|undefined, - protos.google.monitoring.v3.INotificationChannelDescriptor>): - Promise<[ - protos.google.monitoring.v3.INotificationChannelDescriptor[], - protos.google.monitoring.v3.IListNotificationChannelDescriptorsRequest|null, - protos.google.monitoring.v3.IListNotificationChannelDescriptorsResponse - ]>|void { + | protos.google.monitoring.v3.IListNotificationChannelDescriptorsResponse + | null + | undefined, + protos.google.monitoring.v3.INotificationChannelDescriptor + >, + callback?: PaginationCallback< + protos.google.monitoring.v3.IListNotificationChannelDescriptorsRequest, + | protos.google.monitoring.v3.IListNotificationChannelDescriptorsResponse + | null + | undefined, + protos.google.monitoring.v3.INotificationChannelDescriptor + >, + ): Promise< + [ + protos.google.monitoring.v3.INotificationChannelDescriptor[], + protos.google.monitoring.v3.IListNotificationChannelDescriptorsRequest | null, + protos.google.monitoring.v3.IListNotificationChannelDescriptorsResponse, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.monitoring.v3.IListNotificationChannelDescriptorsRequest, - protos.google.monitoring.v3.IListNotificationChannelDescriptorsResponse|null|undefined, - protos.google.monitoring.v3.INotificationChannelDescriptor>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.monitoring.v3.IListNotificationChannelDescriptorsRequest, + | protos.google.monitoring.v3.IListNotificationChannelDescriptorsResponse + | null + | undefined, + protos.google.monitoring.v3.INotificationChannelDescriptor + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { - this._log.info('listNotificationChannelDescriptors values %j', values); + this._log.info( + 'listNotificationChannelDescriptors values %j', + values, + ); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. } : undefined; this._log.info('listNotificationChannelDescriptors request %j', request); return this.innerApiCalls .listNotificationChannelDescriptors(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.monitoring.v3.INotificationChannelDescriptor[], - protos.google.monitoring.v3.IListNotificationChannelDescriptorsRequest|null, - protos.google.monitoring.v3.IListNotificationChannelDescriptorsResponse - ]) => { - this._log.info('listNotificationChannelDescriptors values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.monitoring.v3.INotificationChannelDescriptor[], + protos.google.monitoring.v3.IListNotificationChannelDescriptorsRequest | null, + protos.google.monitoring.v3.IListNotificationChannelDescriptorsResponse, + ]) => { + this._log.info( + 'listNotificationChannelDescriptors values %j', + response, + ); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listNotificationChannelDescriptors`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The REST resource name of the parent from which to retrieve - * the notification channel descriptors. The expected syntax is: - * - * projects/[PROJECT_ID] - * - * Note that this names the parent container in which to look for the - * descriptors; to retrieve a single descriptor by name, use the - * {@link protos.google.monitoring.v3.NotificationChannelService.GetNotificationChannelDescriptor|GetNotificationChannelDescriptor} - * operation, instead. - * @param {number} request.pageSize - * The maximum number of results to return in a single response. If - * not set to a positive number, a reasonable value will be chosen by the - * service. - * @param {string} request.pageToken - * If non-empty, `page_token` must contain a value returned as the - * `next_page_token` in a previous response to request the next set - * of results. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.monitoring.v3.NotificationChannelDescriptor|NotificationChannelDescriptor} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `listNotificationChannelDescriptorsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `listNotificationChannelDescriptors`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The REST resource name of the parent from which to retrieve + * the notification channel descriptors. The expected syntax is: + * + * projects/[PROJECT_ID] + * + * Note that this names the parent container in which to look for the + * descriptors; to retrieve a single descriptor by name, use the + * {@link protos.google.monitoring.v3.NotificationChannelService.GetNotificationChannelDescriptor|GetNotificationChannelDescriptor} + * operation, instead. + * @param {number} request.pageSize + * The maximum number of results to return in a single response. If + * not set to a positive number, a reasonable value will be chosen by the + * service. + * @param {string} request.pageToken + * If non-empty, `page_token` must contain a value returned as the + * `next_page_token` in a previous response to request the next set + * of results. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.monitoring.v3.NotificationChannelDescriptor|NotificationChannelDescriptor} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listNotificationChannelDescriptorsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listNotificationChannelDescriptorsStream( - request?: protos.google.monitoring.v3.IListNotificationChannelDescriptorsRequest, - options?: CallOptions): - Transform{ + request?: protos.google.monitoring.v3.IListNotificationChannelDescriptorsRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', - }); - const defaultCallSettings = this._defaults['listNotificationChannelDescriptors']; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + const defaultCallSettings = + this._defaults['listNotificationChannelDescriptors']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listNotificationChannelDescriptors stream %j', request); return this.descriptors.page.listNotificationChannelDescriptors.createStream( this.innerApiCalls.listNotificationChannelDescriptors as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listNotificationChannelDescriptors`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The REST resource name of the parent from which to retrieve - * the notification channel descriptors. The expected syntax is: - * - * projects/[PROJECT_ID] - * - * Note that this names the parent container in which to look for the - * descriptors; to retrieve a single descriptor by name, use the - * {@link protos.google.monitoring.v3.NotificationChannelService.GetNotificationChannelDescriptor|GetNotificationChannelDescriptor} - * operation, instead. - * @param {number} request.pageSize - * The maximum number of results to return in a single response. If - * not set to a positive number, a reasonable value will be chosen by the - * service. - * @param {string} request.pageToken - * If non-empty, `page_token` must contain a value returned as the - * `next_page_token` in a previous response to request the next set - * of results. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.monitoring.v3.NotificationChannelDescriptor|NotificationChannelDescriptor}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v3/notification_channel_service.list_notification_channel_descriptors.js - * region_tag:monitoring_v3_generated_NotificationChannelService_ListNotificationChannelDescriptors_async - */ + /** + * Equivalent to `listNotificationChannelDescriptors`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The REST resource name of the parent from which to retrieve + * the notification channel descriptors. The expected syntax is: + * + * projects/[PROJECT_ID] + * + * Note that this names the parent container in which to look for the + * descriptors; to retrieve a single descriptor by name, use the + * {@link protos.google.monitoring.v3.NotificationChannelService.GetNotificationChannelDescriptor|GetNotificationChannelDescriptor} + * operation, instead. + * @param {number} request.pageSize + * The maximum number of results to return in a single response. If + * not set to a positive number, a reasonable value will be chosen by the + * service. + * @param {string} request.pageToken + * If non-empty, `page_token` must contain a value returned as the + * `next_page_token` in a previous response to request the next set + * of results. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.monitoring.v3.NotificationChannelDescriptor|NotificationChannelDescriptor}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v3/notification_channel_service.list_notification_channel_descriptors.js + * region_tag:monitoring_v3_generated_NotificationChannelService_ListNotificationChannelDescriptors_async + */ listNotificationChannelDescriptorsAsync( - request?: protos.google.monitoring.v3.IListNotificationChannelDescriptorsRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.monitoring.v3.IListNotificationChannelDescriptorsRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', - }); - const defaultCallSettings = this._defaults['listNotificationChannelDescriptors']; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + const defaultCallSettings = + this._defaults['listNotificationChannelDescriptors']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listNotificationChannelDescriptors iterate %j', request); return this.descriptors.page.listNotificationChannelDescriptors.asyncIterate( this.innerApiCalls['listNotificationChannelDescriptors'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } - /** - * Lists the notification channels that have been created for the project. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The project on which to execute the request. The format is - * `projects/[PROJECT_ID]`. That is, this names the container - * in which to look for the notification channels; it does not name a - * specific channel. To query a specific channel by REST resource name, use - * the - * {@link protos.google.monitoring.v3.NotificationChannelService.GetNotificationChannel|`GetNotificationChannel`} - * operation. - * @param {string} request.filter - * If provided, this field specifies the criteria that must be met by - * notification channels to be included in the response. - * - * For more details, see [sorting and - * filtering](/monitoring/api/v3/sorting-and-filtering). - * @param {string} request.orderBy - * A comma-separated list of fields by which to sort the result. Supports - * the same set of fields as in `filter`. Entries can be prefixed with - * a minus sign to sort in descending rather than ascending order. - * - * For more details, see [sorting and - * filtering](/monitoring/api/v3/sorting-and-filtering). - * @param {number} request.pageSize - * The maximum number of results to return in a single response. If - * not set to a positive number, a reasonable value will be chosen by the - * service. - * @param {string} request.pageToken - * If non-empty, `page_token` must contain a value returned as the - * `next_page_token` in a previous response to request the next set - * of results. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.monitoring.v3.NotificationChannel|NotificationChannel}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `listNotificationChannelsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Lists the notification channels that have been created for the project. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The project on which to execute the request. The format is + * `projects/[PROJECT_ID]`. That is, this names the container + * in which to look for the notification channels; it does not name a + * specific channel. To query a specific channel by REST resource name, use + * the + * {@link protos.google.monitoring.v3.NotificationChannelService.GetNotificationChannel|`GetNotificationChannel`} + * operation. + * @param {string} request.filter + * If provided, this field specifies the criteria that must be met by + * notification channels to be included in the response. + * + * For more details, see [sorting and + * filtering](/monitoring/api/v3/sorting-and-filtering). + * @param {string} request.orderBy + * A comma-separated list of fields by which to sort the result. Supports + * the same set of fields as in `filter`. Entries can be prefixed with + * a minus sign to sort in descending rather than ascending order. + * + * For more details, see [sorting and + * filtering](/monitoring/api/v3/sorting-and-filtering). + * @param {number} request.pageSize + * The maximum number of results to return in a single response. If + * not set to a positive number, a reasonable value will be chosen by the + * service. + * @param {string} request.pageToken + * If non-empty, `page_token` must contain a value returned as the + * `next_page_token` in a previous response to request the next set + * of results. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.monitoring.v3.NotificationChannel|NotificationChannel}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listNotificationChannelsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listNotificationChannels( - request?: protos.google.monitoring.v3.IListNotificationChannelsRequest, - options?: CallOptions): - Promise<[ - protos.google.monitoring.v3.INotificationChannel[], - protos.google.monitoring.v3.IListNotificationChannelsRequest|null, - protos.google.monitoring.v3.IListNotificationChannelsResponse - ]>; + request?: protos.google.monitoring.v3.IListNotificationChannelsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.monitoring.v3.INotificationChannel[], + protos.google.monitoring.v3.IListNotificationChannelsRequest | null, + protos.google.monitoring.v3.IListNotificationChannelsResponse, + ] + >; listNotificationChannels( - request: protos.google.monitoring.v3.IListNotificationChannelsRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.monitoring.v3.IListNotificationChannelsRequest, - protos.google.monitoring.v3.IListNotificationChannelsResponse|null|undefined, - protos.google.monitoring.v3.INotificationChannel>): void; + request: protos.google.monitoring.v3.IListNotificationChannelsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.monitoring.v3.IListNotificationChannelsRequest, + | protos.google.monitoring.v3.IListNotificationChannelsResponse + | null + | undefined, + protos.google.monitoring.v3.INotificationChannel + >, + ): void; listNotificationChannels( - request: protos.google.monitoring.v3.IListNotificationChannelsRequest, - callback: PaginationCallback< - protos.google.monitoring.v3.IListNotificationChannelsRequest, - protos.google.monitoring.v3.IListNotificationChannelsResponse|null|undefined, - protos.google.monitoring.v3.INotificationChannel>): void; + request: protos.google.monitoring.v3.IListNotificationChannelsRequest, + callback: PaginationCallback< + protos.google.monitoring.v3.IListNotificationChannelsRequest, + | protos.google.monitoring.v3.IListNotificationChannelsResponse + | null + | undefined, + protos.google.monitoring.v3.INotificationChannel + >, + ): void; listNotificationChannels( - request?: protos.google.monitoring.v3.IListNotificationChannelsRequest, - optionsOrCallback?: CallOptions|PaginationCallback< - protos.google.monitoring.v3.IListNotificationChannelsRequest, - protos.google.monitoring.v3.IListNotificationChannelsResponse|null|undefined, - protos.google.monitoring.v3.INotificationChannel>, - callback?: PaginationCallback< + request?: protos.google.monitoring.v3.IListNotificationChannelsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.monitoring.v3.IListNotificationChannelsRequest, - protos.google.monitoring.v3.IListNotificationChannelsResponse|null|undefined, - protos.google.monitoring.v3.INotificationChannel>): - Promise<[ - protos.google.monitoring.v3.INotificationChannel[], - protos.google.monitoring.v3.IListNotificationChannelsRequest|null, - protos.google.monitoring.v3.IListNotificationChannelsResponse - ]>|void { + | protos.google.monitoring.v3.IListNotificationChannelsResponse + | null + | undefined, + protos.google.monitoring.v3.INotificationChannel + >, + callback?: PaginationCallback< + protos.google.monitoring.v3.IListNotificationChannelsRequest, + | protos.google.monitoring.v3.IListNotificationChannelsResponse + | null + | undefined, + protos.google.monitoring.v3.INotificationChannel + >, + ): Promise< + [ + protos.google.monitoring.v3.INotificationChannel[], + protos.google.monitoring.v3.IListNotificationChannelsRequest | null, + protos.google.monitoring.v3.IListNotificationChannelsResponse, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.monitoring.v3.IListNotificationChannelsRequest, - protos.google.monitoring.v3.IListNotificationChannelsResponse|null|undefined, - protos.google.monitoring.v3.INotificationChannel>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.monitoring.v3.IListNotificationChannelsRequest, + | protos.google.monitoring.v3.IListNotificationChannelsResponse + | null + | undefined, + protos.google.monitoring.v3.INotificationChannel + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listNotificationChannels values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -1572,152 +2093,156 @@ export class NotificationChannelServiceClient { this._log.info('listNotificationChannels request %j', request); return this.innerApiCalls .listNotificationChannels(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.monitoring.v3.INotificationChannel[], - protos.google.monitoring.v3.IListNotificationChannelsRequest|null, - protos.google.monitoring.v3.IListNotificationChannelsResponse - ]) => { - this._log.info('listNotificationChannels values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.monitoring.v3.INotificationChannel[], + protos.google.monitoring.v3.IListNotificationChannelsRequest | null, + protos.google.monitoring.v3.IListNotificationChannelsResponse, + ]) => { + this._log.info('listNotificationChannels values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listNotificationChannels`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The project on which to execute the request. The format is - * `projects/[PROJECT_ID]`. That is, this names the container - * in which to look for the notification channels; it does not name a - * specific channel. To query a specific channel by REST resource name, use - * the - * {@link protos.google.monitoring.v3.NotificationChannelService.GetNotificationChannel|`GetNotificationChannel`} - * operation. - * @param {string} request.filter - * If provided, this field specifies the criteria that must be met by - * notification channels to be included in the response. - * - * For more details, see [sorting and - * filtering](/monitoring/api/v3/sorting-and-filtering). - * @param {string} request.orderBy - * A comma-separated list of fields by which to sort the result. Supports - * the same set of fields as in `filter`. Entries can be prefixed with - * a minus sign to sort in descending rather than ascending order. - * - * For more details, see [sorting and - * filtering](/monitoring/api/v3/sorting-and-filtering). - * @param {number} request.pageSize - * The maximum number of results to return in a single response. If - * not set to a positive number, a reasonable value will be chosen by the - * service. - * @param {string} request.pageToken - * If non-empty, `page_token` must contain a value returned as the - * `next_page_token` in a previous response to request the next set - * of results. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.monitoring.v3.NotificationChannel|NotificationChannel} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `listNotificationChannelsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `listNotificationChannels`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The project on which to execute the request. The format is + * `projects/[PROJECT_ID]`. That is, this names the container + * in which to look for the notification channels; it does not name a + * specific channel. To query a specific channel by REST resource name, use + * the + * {@link protos.google.monitoring.v3.NotificationChannelService.GetNotificationChannel|`GetNotificationChannel`} + * operation. + * @param {string} request.filter + * If provided, this field specifies the criteria that must be met by + * notification channels to be included in the response. + * + * For more details, see [sorting and + * filtering](/monitoring/api/v3/sorting-and-filtering). + * @param {string} request.orderBy + * A comma-separated list of fields by which to sort the result. Supports + * the same set of fields as in `filter`. Entries can be prefixed with + * a minus sign to sort in descending rather than ascending order. + * + * For more details, see [sorting and + * filtering](/monitoring/api/v3/sorting-and-filtering). + * @param {number} request.pageSize + * The maximum number of results to return in a single response. If + * not set to a positive number, a reasonable value will be chosen by the + * service. + * @param {string} request.pageToken + * If non-empty, `page_token` must contain a value returned as the + * `next_page_token` in a previous response to request the next set + * of results. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.monitoring.v3.NotificationChannel|NotificationChannel} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listNotificationChannelsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listNotificationChannelsStream( - request?: protos.google.monitoring.v3.IListNotificationChannelsRequest, - options?: CallOptions): - Transform{ + request?: protos.google.monitoring.v3.IListNotificationChannelsRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); const defaultCallSettings = this._defaults['listNotificationChannels']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listNotificationChannels stream %j', request); return this.descriptors.page.listNotificationChannels.createStream( this.innerApiCalls.listNotificationChannels as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listNotificationChannels`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The project on which to execute the request. The format is - * `projects/[PROJECT_ID]`. That is, this names the container - * in which to look for the notification channels; it does not name a - * specific channel. To query a specific channel by REST resource name, use - * the - * {@link protos.google.monitoring.v3.NotificationChannelService.GetNotificationChannel|`GetNotificationChannel`} - * operation. - * @param {string} request.filter - * If provided, this field specifies the criteria that must be met by - * notification channels to be included in the response. - * - * For more details, see [sorting and - * filtering](/monitoring/api/v3/sorting-and-filtering). - * @param {string} request.orderBy - * A comma-separated list of fields by which to sort the result. Supports - * the same set of fields as in `filter`. Entries can be prefixed with - * a minus sign to sort in descending rather than ascending order. - * - * For more details, see [sorting and - * filtering](/monitoring/api/v3/sorting-and-filtering). - * @param {number} request.pageSize - * The maximum number of results to return in a single response. If - * not set to a positive number, a reasonable value will be chosen by the - * service. - * @param {string} request.pageToken - * If non-empty, `page_token` must contain a value returned as the - * `next_page_token` in a previous response to request the next set - * of results. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.monitoring.v3.NotificationChannel|NotificationChannel}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v3/notification_channel_service.list_notification_channels.js - * region_tag:monitoring_v3_generated_NotificationChannelService_ListNotificationChannels_async - */ + /** + * Equivalent to `listNotificationChannels`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The project on which to execute the request. The format is + * `projects/[PROJECT_ID]`. That is, this names the container + * in which to look for the notification channels; it does not name a + * specific channel. To query a specific channel by REST resource name, use + * the + * {@link protos.google.monitoring.v3.NotificationChannelService.GetNotificationChannel|`GetNotificationChannel`} + * operation. + * @param {string} request.filter + * If provided, this field specifies the criteria that must be met by + * notification channels to be included in the response. + * + * For more details, see [sorting and + * filtering](/monitoring/api/v3/sorting-and-filtering). + * @param {string} request.orderBy + * A comma-separated list of fields by which to sort the result. Supports + * the same set of fields as in `filter`. Entries can be prefixed with + * a minus sign to sort in descending rather than ascending order. + * + * For more details, see [sorting and + * filtering](/monitoring/api/v3/sorting-and-filtering). + * @param {number} request.pageSize + * The maximum number of results to return in a single response. If + * not set to a positive number, a reasonable value will be chosen by the + * service. + * @param {string} request.pageToken + * If non-empty, `page_token` must contain a value returned as the + * `next_page_token` in a previous response to request the next set + * of results. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.monitoring.v3.NotificationChannel|NotificationChannel}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v3/notification_channel_service.list_notification_channels.js + * region_tag:monitoring_v3_generated_NotificationChannelService_ListNotificationChannels_async + */ listNotificationChannelsAsync( - request?: protos.google.monitoring.v3.IListNotificationChannelsRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.monitoring.v3.IListNotificationChannelsRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); const defaultCallSettings = this._defaults['listNotificationChannels']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listNotificationChannels iterate %j', request); return this.descriptors.page.listNotificationChannels.asyncIterate( this.innerApiCalls['listNotificationChannels'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } // -------------------- @@ -1731,7 +2256,7 @@ export class NotificationChannelServiceClient { * @param {string} alert_policy * @returns {string} Resource name string. */ - folderAlertPolicyPath(folder:string,alertPolicy:string) { + folderAlertPolicyPath(folder: string, alertPolicy: string) { return this.pathTemplates.folderAlertPolicyPathTemplate.render({ folder: folder, alert_policy: alertPolicy, @@ -1746,7 +2271,9 @@ export class NotificationChannelServiceClient { * @returns {string} A string representing the folder. */ matchFolderFromFolderAlertPolicyName(folderAlertPolicyName: string) { - return this.pathTemplates.folderAlertPolicyPathTemplate.match(folderAlertPolicyName).folder; + return this.pathTemplates.folderAlertPolicyPathTemplate.match( + folderAlertPolicyName, + ).folder; } /** @@ -1757,7 +2284,9 @@ export class NotificationChannelServiceClient { * @returns {string} A string representing the alert_policy. */ matchAlertPolicyFromFolderAlertPolicyName(folderAlertPolicyName: string) { - return this.pathTemplates.folderAlertPolicyPathTemplate.match(folderAlertPolicyName).alert_policy; + return this.pathTemplates.folderAlertPolicyPathTemplate.match( + folderAlertPolicyName, + ).alert_policy; } /** @@ -1768,7 +2297,11 @@ export class NotificationChannelServiceClient { * @param {string} condition * @returns {string} Resource name string. */ - folderAlertPolicyConditionPath(folder:string,alertPolicy:string,condition:string) { + folderAlertPolicyConditionPath( + folder: string, + alertPolicy: string, + condition: string, + ) { return this.pathTemplates.folderAlertPolicyConditionPathTemplate.render({ folder: folder, alert_policy: alertPolicy, @@ -1783,8 +2316,12 @@ export class NotificationChannelServiceClient { * A fully-qualified path representing folder_alert_policy_condition resource. * @returns {string} A string representing the folder. */ - matchFolderFromFolderAlertPolicyConditionName(folderAlertPolicyConditionName: string) { - return this.pathTemplates.folderAlertPolicyConditionPathTemplate.match(folderAlertPolicyConditionName).folder; + matchFolderFromFolderAlertPolicyConditionName( + folderAlertPolicyConditionName: string, + ) { + return this.pathTemplates.folderAlertPolicyConditionPathTemplate.match( + folderAlertPolicyConditionName, + ).folder; } /** @@ -1794,8 +2331,12 @@ export class NotificationChannelServiceClient { * A fully-qualified path representing folder_alert_policy_condition resource. * @returns {string} A string representing the alert_policy. */ - matchAlertPolicyFromFolderAlertPolicyConditionName(folderAlertPolicyConditionName: string) { - return this.pathTemplates.folderAlertPolicyConditionPathTemplate.match(folderAlertPolicyConditionName).alert_policy; + matchAlertPolicyFromFolderAlertPolicyConditionName( + folderAlertPolicyConditionName: string, + ) { + return this.pathTemplates.folderAlertPolicyConditionPathTemplate.match( + folderAlertPolicyConditionName, + ).alert_policy; } /** @@ -1805,8 +2346,12 @@ export class NotificationChannelServiceClient { * A fully-qualified path representing folder_alert_policy_condition resource. * @returns {string} A string representing the condition. */ - matchConditionFromFolderAlertPolicyConditionName(folderAlertPolicyConditionName: string) { - return this.pathTemplates.folderAlertPolicyConditionPathTemplate.match(folderAlertPolicyConditionName).condition; + matchConditionFromFolderAlertPolicyConditionName( + folderAlertPolicyConditionName: string, + ) { + return this.pathTemplates.folderAlertPolicyConditionPathTemplate.match( + folderAlertPolicyConditionName, + ).condition; } /** @@ -1816,7 +2361,7 @@ export class NotificationChannelServiceClient { * @param {string} channel_descriptor * @returns {string} Resource name string. */ - folderChannelDescriptorPath(folder:string,channelDescriptor:string) { + folderChannelDescriptorPath(folder: string, channelDescriptor: string) { return this.pathTemplates.folderChannelDescriptorPathTemplate.render({ folder: folder, channel_descriptor: channelDescriptor, @@ -1830,8 +2375,12 @@ export class NotificationChannelServiceClient { * A fully-qualified path representing folder_channel_descriptor resource. * @returns {string} A string representing the folder. */ - matchFolderFromFolderChannelDescriptorName(folderChannelDescriptorName: string) { - return this.pathTemplates.folderChannelDescriptorPathTemplate.match(folderChannelDescriptorName).folder; + matchFolderFromFolderChannelDescriptorName( + folderChannelDescriptorName: string, + ) { + return this.pathTemplates.folderChannelDescriptorPathTemplate.match( + folderChannelDescriptorName, + ).folder; } /** @@ -1841,8 +2390,12 @@ export class NotificationChannelServiceClient { * A fully-qualified path representing folder_channel_descriptor resource. * @returns {string} A string representing the channel_descriptor. */ - matchChannelDescriptorFromFolderChannelDescriptorName(folderChannelDescriptorName: string) { - return this.pathTemplates.folderChannelDescriptorPathTemplate.match(folderChannelDescriptorName).channel_descriptor; + matchChannelDescriptorFromFolderChannelDescriptorName( + folderChannelDescriptorName: string, + ) { + return this.pathTemplates.folderChannelDescriptorPathTemplate.match( + folderChannelDescriptorName, + ).channel_descriptor; } /** @@ -1852,7 +2405,7 @@ export class NotificationChannelServiceClient { * @param {string} group * @returns {string} Resource name string. */ - folderGroupPath(folder:string,group:string) { + folderGroupPath(folder: string, group: string) { return this.pathTemplates.folderGroupPathTemplate.render({ folder: folder, group: group, @@ -1867,7 +2420,8 @@ export class NotificationChannelServiceClient { * @returns {string} A string representing the folder. */ matchFolderFromFolderGroupName(folderGroupName: string) { - return this.pathTemplates.folderGroupPathTemplate.match(folderGroupName).folder; + return this.pathTemplates.folderGroupPathTemplate.match(folderGroupName) + .folder; } /** @@ -1878,7 +2432,8 @@ export class NotificationChannelServiceClient { * @returns {string} A string representing the group. */ matchGroupFromFolderGroupName(folderGroupName: string) { - return this.pathTemplates.folderGroupPathTemplate.match(folderGroupName).group; + return this.pathTemplates.folderGroupPathTemplate.match(folderGroupName) + .group; } /** @@ -1888,7 +2443,7 @@ export class NotificationChannelServiceClient { * @param {string} notification_channel * @returns {string} Resource name string. */ - folderNotificationChannelPath(folder:string,notificationChannel:string) { + folderNotificationChannelPath(folder: string, notificationChannel: string) { return this.pathTemplates.folderNotificationChannelPathTemplate.render({ folder: folder, notification_channel: notificationChannel, @@ -1902,8 +2457,12 @@ export class NotificationChannelServiceClient { * A fully-qualified path representing folder_notification_channel resource. * @returns {string} A string representing the folder. */ - matchFolderFromFolderNotificationChannelName(folderNotificationChannelName: string) { - return this.pathTemplates.folderNotificationChannelPathTemplate.match(folderNotificationChannelName).folder; + matchFolderFromFolderNotificationChannelName( + folderNotificationChannelName: string, + ) { + return this.pathTemplates.folderNotificationChannelPathTemplate.match( + folderNotificationChannelName, + ).folder; } /** @@ -1913,8 +2472,12 @@ export class NotificationChannelServiceClient { * A fully-qualified path representing folder_notification_channel resource. * @returns {string} A string representing the notification_channel. */ - matchNotificationChannelFromFolderNotificationChannelName(folderNotificationChannelName: string) { - return this.pathTemplates.folderNotificationChannelPathTemplate.match(folderNotificationChannelName).notification_channel; + matchNotificationChannelFromFolderNotificationChannelName( + folderNotificationChannelName: string, + ) { + return this.pathTemplates.folderNotificationChannelPathTemplate.match( + folderNotificationChannelName, + ).notification_channel; } /** @@ -1924,7 +2487,7 @@ export class NotificationChannelServiceClient { * @param {string} service * @returns {string} Resource name string. */ - folderServicePath(folder:string,service:string) { + folderServicePath(folder: string, service: string) { return this.pathTemplates.folderServicePathTemplate.render({ folder: folder, service: service, @@ -1939,7 +2502,8 @@ export class NotificationChannelServiceClient { * @returns {string} A string representing the folder. */ matchFolderFromFolderServiceName(folderServiceName: string) { - return this.pathTemplates.folderServicePathTemplate.match(folderServiceName).folder; + return this.pathTemplates.folderServicePathTemplate.match(folderServiceName) + .folder; } /** @@ -1950,7 +2514,8 @@ export class NotificationChannelServiceClient { * @returns {string} A string representing the service. */ matchServiceFromFolderServiceName(folderServiceName: string) { - return this.pathTemplates.folderServicePathTemplate.match(folderServiceName).service; + return this.pathTemplates.folderServicePathTemplate.match(folderServiceName) + .service; } /** @@ -1961,12 +2526,18 @@ export class NotificationChannelServiceClient { * @param {string} service_level_objective * @returns {string} Resource name string. */ - folderServiceServiceLevelObjectivePath(folder:string,service:string,serviceLevelObjective:string) { - return this.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.render({ - folder: folder, - service: service, - service_level_objective: serviceLevelObjective, - }); + folderServiceServiceLevelObjectivePath( + folder: string, + service: string, + serviceLevelObjective: string, + ) { + return this.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.render( + { + folder: folder, + service: service, + service_level_objective: serviceLevelObjective, + }, + ); } /** @@ -1976,8 +2547,12 @@ export class NotificationChannelServiceClient { * A fully-qualified path representing folder_service_service_level_objective resource. * @returns {string} A string representing the folder. */ - matchFolderFromFolderServiceServiceLevelObjectiveName(folderServiceServiceLevelObjectiveName: string) { - return this.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match(folderServiceServiceLevelObjectiveName).folder; + matchFolderFromFolderServiceServiceLevelObjectiveName( + folderServiceServiceLevelObjectiveName: string, + ) { + return this.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match( + folderServiceServiceLevelObjectiveName, + ).folder; } /** @@ -1987,8 +2562,12 @@ export class NotificationChannelServiceClient { * A fully-qualified path representing folder_service_service_level_objective resource. * @returns {string} A string representing the service. */ - matchServiceFromFolderServiceServiceLevelObjectiveName(folderServiceServiceLevelObjectiveName: string) { - return this.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match(folderServiceServiceLevelObjectiveName).service; + matchServiceFromFolderServiceServiceLevelObjectiveName( + folderServiceServiceLevelObjectiveName: string, + ) { + return this.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match( + folderServiceServiceLevelObjectiveName, + ).service; } /** @@ -1998,8 +2577,12 @@ export class NotificationChannelServiceClient { * A fully-qualified path representing folder_service_service_level_objective resource. * @returns {string} A string representing the service_level_objective. */ - matchServiceLevelObjectiveFromFolderServiceServiceLevelObjectiveName(folderServiceServiceLevelObjectiveName: string) { - return this.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match(folderServiceServiceLevelObjectiveName).service_level_objective; + matchServiceLevelObjectiveFromFolderServiceServiceLevelObjectiveName( + folderServiceServiceLevelObjectiveName: string, + ) { + return this.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match( + folderServiceServiceLevelObjectiveName, + ).service_level_objective; } /** @@ -2009,7 +2592,7 @@ export class NotificationChannelServiceClient { * @param {string} uptime_check_config * @returns {string} Resource name string. */ - folderUptimeCheckConfigPath(folder:string,uptimeCheckConfig:string) { + folderUptimeCheckConfigPath(folder: string, uptimeCheckConfig: string) { return this.pathTemplates.folderUptimeCheckConfigPathTemplate.render({ folder: folder, uptime_check_config: uptimeCheckConfig, @@ -2023,8 +2606,12 @@ export class NotificationChannelServiceClient { * A fully-qualified path representing folder_uptime_check_config resource. * @returns {string} A string representing the folder. */ - matchFolderFromFolderUptimeCheckConfigName(folderUptimeCheckConfigName: string) { - return this.pathTemplates.folderUptimeCheckConfigPathTemplate.match(folderUptimeCheckConfigName).folder; + matchFolderFromFolderUptimeCheckConfigName( + folderUptimeCheckConfigName: string, + ) { + return this.pathTemplates.folderUptimeCheckConfigPathTemplate.match( + folderUptimeCheckConfigName, + ).folder; } /** @@ -2034,8 +2621,12 @@ export class NotificationChannelServiceClient { * A fully-qualified path representing folder_uptime_check_config resource. * @returns {string} A string representing the uptime_check_config. */ - matchUptimeCheckConfigFromFolderUptimeCheckConfigName(folderUptimeCheckConfigName: string) { - return this.pathTemplates.folderUptimeCheckConfigPathTemplate.match(folderUptimeCheckConfigName).uptime_check_config; + matchUptimeCheckConfigFromFolderUptimeCheckConfigName( + folderUptimeCheckConfigName: string, + ) { + return this.pathTemplates.folderUptimeCheckConfigPathTemplate.match( + folderUptimeCheckConfigName, + ).uptime_check_config; } /** @@ -2045,7 +2636,7 @@ export class NotificationChannelServiceClient { * @param {string} alert_policy * @returns {string} Resource name string. */ - organizationAlertPolicyPath(organization:string,alertPolicy:string) { + organizationAlertPolicyPath(organization: string, alertPolicy: string) { return this.pathTemplates.organizationAlertPolicyPathTemplate.render({ organization: organization, alert_policy: alertPolicy, @@ -2059,8 +2650,12 @@ export class NotificationChannelServiceClient { * A fully-qualified path representing organization_alert_policy resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationAlertPolicyName(organizationAlertPolicyName: string) { - return this.pathTemplates.organizationAlertPolicyPathTemplate.match(organizationAlertPolicyName).organization; + matchOrganizationFromOrganizationAlertPolicyName( + organizationAlertPolicyName: string, + ) { + return this.pathTemplates.organizationAlertPolicyPathTemplate.match( + organizationAlertPolicyName, + ).organization; } /** @@ -2070,8 +2665,12 @@ export class NotificationChannelServiceClient { * A fully-qualified path representing organization_alert_policy resource. * @returns {string} A string representing the alert_policy. */ - matchAlertPolicyFromOrganizationAlertPolicyName(organizationAlertPolicyName: string) { - return this.pathTemplates.organizationAlertPolicyPathTemplate.match(organizationAlertPolicyName).alert_policy; + matchAlertPolicyFromOrganizationAlertPolicyName( + organizationAlertPolicyName: string, + ) { + return this.pathTemplates.organizationAlertPolicyPathTemplate.match( + organizationAlertPolicyName, + ).alert_policy; } /** @@ -2082,12 +2681,18 @@ export class NotificationChannelServiceClient { * @param {string} condition * @returns {string} Resource name string. */ - organizationAlertPolicyConditionPath(organization:string,alertPolicy:string,condition:string) { - return this.pathTemplates.organizationAlertPolicyConditionPathTemplate.render({ - organization: organization, - alert_policy: alertPolicy, - condition: condition, - }); + organizationAlertPolicyConditionPath( + organization: string, + alertPolicy: string, + condition: string, + ) { + return this.pathTemplates.organizationAlertPolicyConditionPathTemplate.render( + { + organization: organization, + alert_policy: alertPolicy, + condition: condition, + }, + ); } /** @@ -2097,8 +2702,12 @@ export class NotificationChannelServiceClient { * A fully-qualified path representing organization_alert_policy_condition resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationAlertPolicyConditionName(organizationAlertPolicyConditionName: string) { - return this.pathTemplates.organizationAlertPolicyConditionPathTemplate.match(organizationAlertPolicyConditionName).organization; + matchOrganizationFromOrganizationAlertPolicyConditionName( + organizationAlertPolicyConditionName: string, + ) { + return this.pathTemplates.organizationAlertPolicyConditionPathTemplate.match( + organizationAlertPolicyConditionName, + ).organization; } /** @@ -2108,8 +2717,12 @@ export class NotificationChannelServiceClient { * A fully-qualified path representing organization_alert_policy_condition resource. * @returns {string} A string representing the alert_policy. */ - matchAlertPolicyFromOrganizationAlertPolicyConditionName(organizationAlertPolicyConditionName: string) { - return this.pathTemplates.organizationAlertPolicyConditionPathTemplate.match(organizationAlertPolicyConditionName).alert_policy; + matchAlertPolicyFromOrganizationAlertPolicyConditionName( + organizationAlertPolicyConditionName: string, + ) { + return this.pathTemplates.organizationAlertPolicyConditionPathTemplate.match( + organizationAlertPolicyConditionName, + ).alert_policy; } /** @@ -2119,8 +2732,12 @@ export class NotificationChannelServiceClient { * A fully-qualified path representing organization_alert_policy_condition resource. * @returns {string} A string representing the condition. */ - matchConditionFromOrganizationAlertPolicyConditionName(organizationAlertPolicyConditionName: string) { - return this.pathTemplates.organizationAlertPolicyConditionPathTemplate.match(organizationAlertPolicyConditionName).condition; + matchConditionFromOrganizationAlertPolicyConditionName( + organizationAlertPolicyConditionName: string, + ) { + return this.pathTemplates.organizationAlertPolicyConditionPathTemplate.match( + organizationAlertPolicyConditionName, + ).condition; } /** @@ -2130,7 +2747,10 @@ export class NotificationChannelServiceClient { * @param {string} channel_descriptor * @returns {string} Resource name string. */ - organizationChannelDescriptorPath(organization:string,channelDescriptor:string) { + organizationChannelDescriptorPath( + organization: string, + channelDescriptor: string, + ) { return this.pathTemplates.organizationChannelDescriptorPathTemplate.render({ organization: organization, channel_descriptor: channelDescriptor, @@ -2144,8 +2764,12 @@ export class NotificationChannelServiceClient { * A fully-qualified path representing organization_channel_descriptor resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationChannelDescriptorName(organizationChannelDescriptorName: string) { - return this.pathTemplates.organizationChannelDescriptorPathTemplate.match(organizationChannelDescriptorName).organization; + matchOrganizationFromOrganizationChannelDescriptorName( + organizationChannelDescriptorName: string, + ) { + return this.pathTemplates.organizationChannelDescriptorPathTemplate.match( + organizationChannelDescriptorName, + ).organization; } /** @@ -2155,8 +2779,12 @@ export class NotificationChannelServiceClient { * A fully-qualified path representing organization_channel_descriptor resource. * @returns {string} A string representing the channel_descriptor. */ - matchChannelDescriptorFromOrganizationChannelDescriptorName(organizationChannelDescriptorName: string) { - return this.pathTemplates.organizationChannelDescriptorPathTemplate.match(organizationChannelDescriptorName).channel_descriptor; + matchChannelDescriptorFromOrganizationChannelDescriptorName( + organizationChannelDescriptorName: string, + ) { + return this.pathTemplates.organizationChannelDescriptorPathTemplate.match( + organizationChannelDescriptorName, + ).channel_descriptor; } /** @@ -2166,7 +2794,7 @@ export class NotificationChannelServiceClient { * @param {string} group * @returns {string} Resource name string. */ - organizationGroupPath(organization:string,group:string) { + organizationGroupPath(organization: string, group: string) { return this.pathTemplates.organizationGroupPathTemplate.render({ organization: organization, group: group, @@ -2181,7 +2809,9 @@ export class NotificationChannelServiceClient { * @returns {string} A string representing the organization. */ matchOrganizationFromOrganizationGroupName(organizationGroupName: string) { - return this.pathTemplates.organizationGroupPathTemplate.match(organizationGroupName).organization; + return this.pathTemplates.organizationGroupPathTemplate.match( + organizationGroupName, + ).organization; } /** @@ -2192,7 +2822,9 @@ export class NotificationChannelServiceClient { * @returns {string} A string representing the group. */ matchGroupFromOrganizationGroupName(organizationGroupName: string) { - return this.pathTemplates.organizationGroupPathTemplate.match(organizationGroupName).group; + return this.pathTemplates.organizationGroupPathTemplate.match( + organizationGroupName, + ).group; } /** @@ -2202,11 +2834,16 @@ export class NotificationChannelServiceClient { * @param {string} notification_channel * @returns {string} Resource name string. */ - organizationNotificationChannelPath(organization:string,notificationChannel:string) { - return this.pathTemplates.organizationNotificationChannelPathTemplate.render({ - organization: organization, - notification_channel: notificationChannel, - }); + organizationNotificationChannelPath( + organization: string, + notificationChannel: string, + ) { + return this.pathTemplates.organizationNotificationChannelPathTemplate.render( + { + organization: organization, + notification_channel: notificationChannel, + }, + ); } /** @@ -2216,8 +2853,12 @@ export class NotificationChannelServiceClient { * A fully-qualified path representing organization_notification_channel resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationNotificationChannelName(organizationNotificationChannelName: string) { - return this.pathTemplates.organizationNotificationChannelPathTemplate.match(organizationNotificationChannelName).organization; + matchOrganizationFromOrganizationNotificationChannelName( + organizationNotificationChannelName: string, + ) { + return this.pathTemplates.organizationNotificationChannelPathTemplate.match( + organizationNotificationChannelName, + ).organization; } /** @@ -2227,8 +2868,12 @@ export class NotificationChannelServiceClient { * A fully-qualified path representing organization_notification_channel resource. * @returns {string} A string representing the notification_channel. */ - matchNotificationChannelFromOrganizationNotificationChannelName(organizationNotificationChannelName: string) { - return this.pathTemplates.organizationNotificationChannelPathTemplate.match(organizationNotificationChannelName).notification_channel; + matchNotificationChannelFromOrganizationNotificationChannelName( + organizationNotificationChannelName: string, + ) { + return this.pathTemplates.organizationNotificationChannelPathTemplate.match( + organizationNotificationChannelName, + ).notification_channel; } /** @@ -2238,7 +2883,7 @@ export class NotificationChannelServiceClient { * @param {string} service * @returns {string} Resource name string. */ - organizationServicePath(organization:string,service:string) { + organizationServicePath(organization: string, service: string) { return this.pathTemplates.organizationServicePathTemplate.render({ organization: organization, service: service, @@ -2252,8 +2897,12 @@ export class NotificationChannelServiceClient { * A fully-qualified path representing organization_service resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationServiceName(organizationServiceName: string) { - return this.pathTemplates.organizationServicePathTemplate.match(organizationServiceName).organization; + matchOrganizationFromOrganizationServiceName( + organizationServiceName: string, + ) { + return this.pathTemplates.organizationServicePathTemplate.match( + organizationServiceName, + ).organization; } /** @@ -2264,7 +2913,9 @@ export class NotificationChannelServiceClient { * @returns {string} A string representing the service. */ matchServiceFromOrganizationServiceName(organizationServiceName: string) { - return this.pathTemplates.organizationServicePathTemplate.match(organizationServiceName).service; + return this.pathTemplates.organizationServicePathTemplate.match( + organizationServiceName, + ).service; } /** @@ -2275,12 +2926,18 @@ export class NotificationChannelServiceClient { * @param {string} service_level_objective * @returns {string} Resource name string. */ - organizationServiceServiceLevelObjectivePath(organization:string,service:string,serviceLevelObjective:string) { - return this.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.render({ - organization: organization, - service: service, - service_level_objective: serviceLevelObjective, - }); + organizationServiceServiceLevelObjectivePath( + organization: string, + service: string, + serviceLevelObjective: string, + ) { + return this.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.render( + { + organization: organization, + service: service, + service_level_objective: serviceLevelObjective, + }, + ); } /** @@ -2290,8 +2947,12 @@ export class NotificationChannelServiceClient { * A fully-qualified path representing organization_service_service_level_objective resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationServiceServiceLevelObjectiveName(organizationServiceServiceLevelObjectiveName: string) { - return this.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match(organizationServiceServiceLevelObjectiveName).organization; + matchOrganizationFromOrganizationServiceServiceLevelObjectiveName( + organizationServiceServiceLevelObjectiveName: string, + ) { + return this.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match( + organizationServiceServiceLevelObjectiveName, + ).organization; } /** @@ -2301,8 +2962,12 @@ export class NotificationChannelServiceClient { * A fully-qualified path representing organization_service_service_level_objective resource. * @returns {string} A string representing the service. */ - matchServiceFromOrganizationServiceServiceLevelObjectiveName(organizationServiceServiceLevelObjectiveName: string) { - return this.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match(organizationServiceServiceLevelObjectiveName).service; + matchServiceFromOrganizationServiceServiceLevelObjectiveName( + organizationServiceServiceLevelObjectiveName: string, + ) { + return this.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match( + organizationServiceServiceLevelObjectiveName, + ).service; } /** @@ -2312,8 +2977,12 @@ export class NotificationChannelServiceClient { * A fully-qualified path representing organization_service_service_level_objective resource. * @returns {string} A string representing the service_level_objective. */ - matchServiceLevelObjectiveFromOrganizationServiceServiceLevelObjectiveName(organizationServiceServiceLevelObjectiveName: string) { - return this.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match(organizationServiceServiceLevelObjectiveName).service_level_objective; + matchServiceLevelObjectiveFromOrganizationServiceServiceLevelObjectiveName( + organizationServiceServiceLevelObjectiveName: string, + ) { + return this.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match( + organizationServiceServiceLevelObjectiveName, + ).service_level_objective; } /** @@ -2323,7 +2992,10 @@ export class NotificationChannelServiceClient { * @param {string} uptime_check_config * @returns {string} Resource name string. */ - organizationUptimeCheckConfigPath(organization:string,uptimeCheckConfig:string) { + organizationUptimeCheckConfigPath( + organization: string, + uptimeCheckConfig: string, + ) { return this.pathTemplates.organizationUptimeCheckConfigPathTemplate.render({ organization: organization, uptime_check_config: uptimeCheckConfig, @@ -2337,8 +3009,12 @@ export class NotificationChannelServiceClient { * A fully-qualified path representing organization_uptime_check_config resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationUptimeCheckConfigName(organizationUptimeCheckConfigName: string) { - return this.pathTemplates.organizationUptimeCheckConfigPathTemplate.match(organizationUptimeCheckConfigName).organization; + matchOrganizationFromOrganizationUptimeCheckConfigName( + organizationUptimeCheckConfigName: string, + ) { + return this.pathTemplates.organizationUptimeCheckConfigPathTemplate.match( + organizationUptimeCheckConfigName, + ).organization; } /** @@ -2348,8 +3024,12 @@ export class NotificationChannelServiceClient { * A fully-qualified path representing organization_uptime_check_config resource. * @returns {string} A string representing the uptime_check_config. */ - matchUptimeCheckConfigFromOrganizationUptimeCheckConfigName(organizationUptimeCheckConfigName: string) { - return this.pathTemplates.organizationUptimeCheckConfigPathTemplate.match(organizationUptimeCheckConfigName).uptime_check_config; + matchUptimeCheckConfigFromOrganizationUptimeCheckConfigName( + organizationUptimeCheckConfigName: string, + ) { + return this.pathTemplates.organizationUptimeCheckConfigPathTemplate.match( + organizationUptimeCheckConfigName, + ).uptime_check_config; } /** @@ -2359,7 +3039,7 @@ export class NotificationChannelServiceClient { * @param {string} alert_policy * @returns {string} Resource name string. */ - projectAlertPolicyPath(project:string,alertPolicy:string) { + projectAlertPolicyPath(project: string, alertPolicy: string) { return this.pathTemplates.projectAlertPolicyPathTemplate.render({ project: project, alert_policy: alertPolicy, @@ -2374,7 +3054,9 @@ export class NotificationChannelServiceClient { * @returns {string} A string representing the project. */ matchProjectFromProjectAlertPolicyName(projectAlertPolicyName: string) { - return this.pathTemplates.projectAlertPolicyPathTemplate.match(projectAlertPolicyName).project; + return this.pathTemplates.projectAlertPolicyPathTemplate.match( + projectAlertPolicyName, + ).project; } /** @@ -2385,7 +3067,9 @@ export class NotificationChannelServiceClient { * @returns {string} A string representing the alert_policy. */ matchAlertPolicyFromProjectAlertPolicyName(projectAlertPolicyName: string) { - return this.pathTemplates.projectAlertPolicyPathTemplate.match(projectAlertPolicyName).alert_policy; + return this.pathTemplates.projectAlertPolicyPathTemplate.match( + projectAlertPolicyName, + ).alert_policy; } /** @@ -2396,7 +3080,11 @@ export class NotificationChannelServiceClient { * @param {string} condition * @returns {string} Resource name string. */ - projectAlertPolicyConditionPath(project:string,alertPolicy:string,condition:string) { + projectAlertPolicyConditionPath( + project: string, + alertPolicy: string, + condition: string, + ) { return this.pathTemplates.projectAlertPolicyConditionPathTemplate.render({ project: project, alert_policy: alertPolicy, @@ -2411,8 +3099,12 @@ export class NotificationChannelServiceClient { * A fully-qualified path representing project_alert_policy_condition resource. * @returns {string} A string representing the project. */ - matchProjectFromProjectAlertPolicyConditionName(projectAlertPolicyConditionName: string) { - return this.pathTemplates.projectAlertPolicyConditionPathTemplate.match(projectAlertPolicyConditionName).project; + matchProjectFromProjectAlertPolicyConditionName( + projectAlertPolicyConditionName: string, + ) { + return this.pathTemplates.projectAlertPolicyConditionPathTemplate.match( + projectAlertPolicyConditionName, + ).project; } /** @@ -2422,8 +3114,12 @@ export class NotificationChannelServiceClient { * A fully-qualified path representing project_alert_policy_condition resource. * @returns {string} A string representing the alert_policy. */ - matchAlertPolicyFromProjectAlertPolicyConditionName(projectAlertPolicyConditionName: string) { - return this.pathTemplates.projectAlertPolicyConditionPathTemplate.match(projectAlertPolicyConditionName).alert_policy; + matchAlertPolicyFromProjectAlertPolicyConditionName( + projectAlertPolicyConditionName: string, + ) { + return this.pathTemplates.projectAlertPolicyConditionPathTemplate.match( + projectAlertPolicyConditionName, + ).alert_policy; } /** @@ -2433,8 +3129,12 @@ export class NotificationChannelServiceClient { * A fully-qualified path representing project_alert_policy_condition resource. * @returns {string} A string representing the condition. */ - matchConditionFromProjectAlertPolicyConditionName(projectAlertPolicyConditionName: string) { - return this.pathTemplates.projectAlertPolicyConditionPathTemplate.match(projectAlertPolicyConditionName).condition; + matchConditionFromProjectAlertPolicyConditionName( + projectAlertPolicyConditionName: string, + ) { + return this.pathTemplates.projectAlertPolicyConditionPathTemplate.match( + projectAlertPolicyConditionName, + ).condition; } /** @@ -2444,7 +3144,7 @@ export class NotificationChannelServiceClient { * @param {string} channel_descriptor * @returns {string} Resource name string. */ - projectChannelDescriptorPath(project:string,channelDescriptor:string) { + projectChannelDescriptorPath(project: string, channelDescriptor: string) { return this.pathTemplates.projectChannelDescriptorPathTemplate.render({ project: project, channel_descriptor: channelDescriptor, @@ -2458,8 +3158,12 @@ export class NotificationChannelServiceClient { * A fully-qualified path representing project_channel_descriptor resource. * @returns {string} A string representing the project. */ - matchProjectFromProjectChannelDescriptorName(projectChannelDescriptorName: string) { - return this.pathTemplates.projectChannelDescriptorPathTemplate.match(projectChannelDescriptorName).project; + matchProjectFromProjectChannelDescriptorName( + projectChannelDescriptorName: string, + ) { + return this.pathTemplates.projectChannelDescriptorPathTemplate.match( + projectChannelDescriptorName, + ).project; } /** @@ -2469,8 +3173,12 @@ export class NotificationChannelServiceClient { * A fully-qualified path representing project_channel_descriptor resource. * @returns {string} A string representing the channel_descriptor. */ - matchChannelDescriptorFromProjectChannelDescriptorName(projectChannelDescriptorName: string) { - return this.pathTemplates.projectChannelDescriptorPathTemplate.match(projectChannelDescriptorName).channel_descriptor; + matchChannelDescriptorFromProjectChannelDescriptorName( + projectChannelDescriptorName: string, + ) { + return this.pathTemplates.projectChannelDescriptorPathTemplate.match( + projectChannelDescriptorName, + ).channel_descriptor; } /** @@ -2480,7 +3188,7 @@ export class NotificationChannelServiceClient { * @param {string} group * @returns {string} Resource name string. */ - projectGroupPath(project:string,group:string) { + projectGroupPath(project: string, group: string) { return this.pathTemplates.projectGroupPathTemplate.render({ project: project, group: group, @@ -2495,7 +3203,8 @@ export class NotificationChannelServiceClient { * @returns {string} A string representing the project. */ matchProjectFromProjectGroupName(projectGroupName: string) { - return this.pathTemplates.projectGroupPathTemplate.match(projectGroupName).project; + return this.pathTemplates.projectGroupPathTemplate.match(projectGroupName) + .project; } /** @@ -2506,7 +3215,8 @@ export class NotificationChannelServiceClient { * @returns {string} A string representing the group. */ matchGroupFromProjectGroupName(projectGroupName: string) { - return this.pathTemplates.projectGroupPathTemplate.match(projectGroupName).group; + return this.pathTemplates.projectGroupPathTemplate.match(projectGroupName) + .group; } /** @@ -2516,7 +3226,7 @@ export class NotificationChannelServiceClient { * @param {string} notification_channel * @returns {string} Resource name string. */ - projectNotificationChannelPath(project:string,notificationChannel:string) { + projectNotificationChannelPath(project: string, notificationChannel: string) { return this.pathTemplates.projectNotificationChannelPathTemplate.render({ project: project, notification_channel: notificationChannel, @@ -2530,8 +3240,12 @@ export class NotificationChannelServiceClient { * A fully-qualified path representing project_notification_channel resource. * @returns {string} A string representing the project. */ - matchProjectFromProjectNotificationChannelName(projectNotificationChannelName: string) { - return this.pathTemplates.projectNotificationChannelPathTemplate.match(projectNotificationChannelName).project; + matchProjectFromProjectNotificationChannelName( + projectNotificationChannelName: string, + ) { + return this.pathTemplates.projectNotificationChannelPathTemplate.match( + projectNotificationChannelName, + ).project; } /** @@ -2541,8 +3255,12 @@ export class NotificationChannelServiceClient { * A fully-qualified path representing project_notification_channel resource. * @returns {string} A string representing the notification_channel. */ - matchNotificationChannelFromProjectNotificationChannelName(projectNotificationChannelName: string) { - return this.pathTemplates.projectNotificationChannelPathTemplate.match(projectNotificationChannelName).notification_channel; + matchNotificationChannelFromProjectNotificationChannelName( + projectNotificationChannelName: string, + ) { + return this.pathTemplates.projectNotificationChannelPathTemplate.match( + projectNotificationChannelName, + ).notification_channel; } /** @@ -2552,7 +3270,7 @@ export class NotificationChannelServiceClient { * @param {string} service * @returns {string} Resource name string. */ - projectServicePath(project:string,service:string) { + projectServicePath(project: string, service: string) { return this.pathTemplates.projectServicePathTemplate.render({ project: project, service: service, @@ -2567,7 +3285,9 @@ export class NotificationChannelServiceClient { * @returns {string} A string representing the project. */ matchProjectFromProjectServiceName(projectServiceName: string) { - return this.pathTemplates.projectServicePathTemplate.match(projectServiceName).project; + return this.pathTemplates.projectServicePathTemplate.match( + projectServiceName, + ).project; } /** @@ -2578,7 +3298,9 @@ export class NotificationChannelServiceClient { * @returns {string} A string representing the service. */ matchServiceFromProjectServiceName(projectServiceName: string) { - return this.pathTemplates.projectServicePathTemplate.match(projectServiceName).service; + return this.pathTemplates.projectServicePathTemplate.match( + projectServiceName, + ).service; } /** @@ -2589,12 +3311,18 @@ export class NotificationChannelServiceClient { * @param {string} service_level_objective * @returns {string} Resource name string. */ - projectServiceServiceLevelObjectivePath(project:string,service:string,serviceLevelObjective:string) { - return this.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.render({ - project: project, - service: service, - service_level_objective: serviceLevelObjective, - }); + projectServiceServiceLevelObjectivePath( + project: string, + service: string, + serviceLevelObjective: string, + ) { + return this.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.render( + { + project: project, + service: service, + service_level_objective: serviceLevelObjective, + }, + ); } /** @@ -2604,8 +3332,12 @@ export class NotificationChannelServiceClient { * A fully-qualified path representing project_service_service_level_objective resource. * @returns {string} A string representing the project. */ - matchProjectFromProjectServiceServiceLevelObjectiveName(projectServiceServiceLevelObjectiveName: string) { - return this.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match(projectServiceServiceLevelObjectiveName).project; + matchProjectFromProjectServiceServiceLevelObjectiveName( + projectServiceServiceLevelObjectiveName: string, + ) { + return this.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match( + projectServiceServiceLevelObjectiveName, + ).project; } /** @@ -2615,8 +3347,12 @@ export class NotificationChannelServiceClient { * A fully-qualified path representing project_service_service_level_objective resource. * @returns {string} A string representing the service. */ - matchServiceFromProjectServiceServiceLevelObjectiveName(projectServiceServiceLevelObjectiveName: string) { - return this.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match(projectServiceServiceLevelObjectiveName).service; + matchServiceFromProjectServiceServiceLevelObjectiveName( + projectServiceServiceLevelObjectiveName: string, + ) { + return this.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match( + projectServiceServiceLevelObjectiveName, + ).service; } /** @@ -2626,8 +3362,12 @@ export class NotificationChannelServiceClient { * A fully-qualified path representing project_service_service_level_objective resource. * @returns {string} A string representing the service_level_objective. */ - matchServiceLevelObjectiveFromProjectServiceServiceLevelObjectiveName(projectServiceServiceLevelObjectiveName: string) { - return this.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match(projectServiceServiceLevelObjectiveName).service_level_objective; + matchServiceLevelObjectiveFromProjectServiceServiceLevelObjectiveName( + projectServiceServiceLevelObjectiveName: string, + ) { + return this.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match( + projectServiceServiceLevelObjectiveName, + ).service_level_objective; } /** @@ -2637,7 +3377,7 @@ export class NotificationChannelServiceClient { * @param {string} uptime_check_config * @returns {string} Resource name string. */ - projectUptimeCheckConfigPath(project:string,uptimeCheckConfig:string) { + projectUptimeCheckConfigPath(project: string, uptimeCheckConfig: string) { return this.pathTemplates.projectUptimeCheckConfigPathTemplate.render({ project: project, uptime_check_config: uptimeCheckConfig, @@ -2651,8 +3391,12 @@ export class NotificationChannelServiceClient { * A fully-qualified path representing project_uptime_check_config resource. * @returns {string} A string representing the project. */ - matchProjectFromProjectUptimeCheckConfigName(projectUptimeCheckConfigName: string) { - return this.pathTemplates.projectUptimeCheckConfigPathTemplate.match(projectUptimeCheckConfigName).project; + matchProjectFromProjectUptimeCheckConfigName( + projectUptimeCheckConfigName: string, + ) { + return this.pathTemplates.projectUptimeCheckConfigPathTemplate.match( + projectUptimeCheckConfigName, + ).project; } /** @@ -2662,8 +3406,12 @@ export class NotificationChannelServiceClient { * A fully-qualified path representing project_uptime_check_config resource. * @returns {string} A string representing the uptime_check_config. */ - matchUptimeCheckConfigFromProjectUptimeCheckConfigName(projectUptimeCheckConfigName: string) { - return this.pathTemplates.projectUptimeCheckConfigPathTemplate.match(projectUptimeCheckConfigName).uptime_check_config; + matchUptimeCheckConfigFromProjectUptimeCheckConfigName( + projectUptimeCheckConfigName: string, + ) { + return this.pathTemplates.projectUptimeCheckConfigPathTemplate.match( + projectUptimeCheckConfigName, + ).uptime_check_config; } /** @@ -2674,7 +3422,7 @@ export class NotificationChannelServiceClient { */ close(): Promise { if (this.notificationChannelServiceStub && !this._terminated) { - return this.notificationChannelServiceStub.then(stub => { + return this.notificationChannelServiceStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -2682,4 +3430,4 @@ export class NotificationChannelServiceClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/core/generator/gapic-generator-typescript/baselines/monitoring/src/v3/service_monitoring_service_client.ts.baseline b/core/generator/gapic-generator-typescript/baselines/monitoring/src/v3/service_monitoring_service_client.ts.baseline index db1e2e3c8065..881ed52de191 100644 --- a/core/generator/gapic-generator-typescript/baselines/monitoring/src/v3/service_monitoring_service_client.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/monitoring/src/v3/service_monitoring_service_client.ts.baseline @@ -18,11 +18,18 @@ /* global window */ import type * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions, PaginationCallback, GaxCall} from 'google-gax'; -import {Transform} from 'stream'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + PaginationCallback, + GaxCall, +} from 'google-gax'; +import { Transform } from 'stream'; import * as protos from '../../protos/protos'; import jsonProtos = require('../../protos/protos.json'); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; /** * Client JSON configuration object, loaded from @@ -47,7 +54,7 @@ export class ServiceMonitoringServiceClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('monitoring'); @@ -60,9 +67,9 @@ export class ServiceMonitoringServiceClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; - serviceMonitoringServiceStub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; + serviceMonitoringServiceStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of ServiceMonitoringServiceClient. @@ -103,21 +110,43 @@ export class ServiceMonitoringServiceClient { * const client = new ServiceMonitoringServiceClient({fallback: true}, gax); * ``` */ - constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { // Ensure that options include all the required fields. - const staticMembers = this.constructor as typeof ServiceMonitoringServiceClient; - if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { - throw new Error('Please set either universe_domain or universeDomain, but not both.'); + const staticMembers = this + .constructor as typeof ServiceMonitoringServiceClient; + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); } - const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; - this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; this._servicePath = 'monitoring.' + this._universeDomain; - const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; - const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. if (servicePath !== this._servicePath && !('scopes' in opts)) { @@ -139,7 +168,7 @@ export class ServiceMonitoringServiceClient { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; @@ -153,10 +182,7 @@ export class ServiceMonitoringServiceClient { } // Determine the client header string. - const clientHeader = [ - `gax/${this._gaxModule.version}`, - `gapic/${version}`, - ]; + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/${process.versions.node}`); } else { @@ -178,76 +204,83 @@ export class ServiceMonitoringServiceClient { // Create useful helper objects for these. this.pathTemplates = { folderAlertPolicyPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/alertPolicies/{alert_policy}' + 'folders/{folder}/alertPolicies/{alert_policy}', ), folderAlertPolicyConditionPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/alertPolicies/{alert_policy}/conditions/{condition}' + 'folders/{folder}/alertPolicies/{alert_policy}/conditions/{condition}', ), folderChannelDescriptorPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/notificationChannelDescriptors/{channel_descriptor}' + 'folders/{folder}/notificationChannelDescriptors/{channel_descriptor}', ), folderGroupPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/groups/{group}' + 'folders/{folder}/groups/{group}', ), folderNotificationChannelPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/notificationChannels/{notification_channel}' + 'folders/{folder}/notificationChannels/{notification_channel}', ), folderServicePathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/services/{service}' - ), - folderServiceServiceLevelObjectivePathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/services/{service}/serviceLevelObjectives/{service_level_objective}' + 'folders/{folder}/services/{service}', ), + folderServiceServiceLevelObjectivePathTemplate: + new this._gaxModule.PathTemplate( + 'folders/{folder}/services/{service}/serviceLevelObjectives/{service_level_objective}', + ), folderUptimeCheckConfigPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/uptimeCheckConfigs/{uptime_check_config}' + 'folders/{folder}/uptimeCheckConfigs/{uptime_check_config}', ), organizationAlertPolicyPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/alertPolicies/{alert_policy}' - ), - organizationAlertPolicyConditionPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/alertPolicies/{alert_policy}/conditions/{condition}' - ), - organizationChannelDescriptorPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/notificationChannelDescriptors/{channel_descriptor}' + 'organizations/{organization}/alertPolicies/{alert_policy}', ), + organizationAlertPolicyConditionPathTemplate: + new this._gaxModule.PathTemplate( + 'organizations/{organization}/alertPolicies/{alert_policy}/conditions/{condition}', + ), + organizationChannelDescriptorPathTemplate: + new this._gaxModule.PathTemplate( + 'organizations/{organization}/notificationChannelDescriptors/{channel_descriptor}', + ), organizationGroupPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/groups/{group}' - ), - organizationNotificationChannelPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/notificationChannels/{notification_channel}' + 'organizations/{organization}/groups/{group}', ), + organizationNotificationChannelPathTemplate: + new this._gaxModule.PathTemplate( + 'organizations/{organization}/notificationChannels/{notification_channel}', + ), organizationServicePathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/services/{service}' - ), - organizationServiceServiceLevelObjectivePathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/services/{service}/serviceLevelObjectives/{service_level_objective}' - ), - organizationUptimeCheckConfigPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/uptimeCheckConfigs/{uptime_check_config}' + 'organizations/{organization}/services/{service}', ), + organizationServiceServiceLevelObjectivePathTemplate: + new this._gaxModule.PathTemplate( + 'organizations/{organization}/services/{service}/serviceLevelObjectives/{service_level_objective}', + ), + organizationUptimeCheckConfigPathTemplate: + new this._gaxModule.PathTemplate( + 'organizations/{organization}/uptimeCheckConfigs/{uptime_check_config}', + ), projectAlertPolicyPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/alertPolicies/{alert_policy}' + 'projects/{project}/alertPolicies/{alert_policy}', ), projectAlertPolicyConditionPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/alertPolicies/{alert_policy}/conditions/{condition}' + 'projects/{project}/alertPolicies/{alert_policy}/conditions/{condition}', ), projectChannelDescriptorPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/notificationChannelDescriptors/{channel_descriptor}' + 'projects/{project}/notificationChannelDescriptors/{channel_descriptor}', ), projectGroupPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/groups/{group}' + 'projects/{project}/groups/{group}', ), projectNotificationChannelPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/notificationChannels/{notification_channel}' + 'projects/{project}/notificationChannels/{notification_channel}', ), projectServicePathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/services/{service}' - ), - projectServiceServiceLevelObjectivePathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/services/{service}/serviceLevelObjectives/{service_level_objective}' + 'projects/{project}/services/{service}', ), + projectServiceServiceLevelObjectivePathTemplate: + new this._gaxModule.PathTemplate( + 'projects/{project}/services/{service}/serviceLevelObjectives/{service_level_objective}', + ), projectUptimeCheckConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/uptimeCheckConfigs/{uptime_check_config}' + 'projects/{project}/uptimeCheckConfigs/{uptime_check_config}', ), }; @@ -255,16 +288,25 @@ export class ServiceMonitoringServiceClient { // (e.g. 50 results at a time, with tokens to get subsequent // pages). Denote the keys used for pagination and results. this.descriptors.page = { - listServices: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'services'), - listServiceLevelObjectives: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'serviceLevelObjectives') + listServices: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'services', + ), + listServiceLevelObjectives: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'serviceLevelObjectives', + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.monitoring.v3.ServiceMonitoringService', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.monitoring.v3.ServiceMonitoringService', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + { 'x-goog-api-client': clientHeader.join(' ') }, + ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -295,37 +337,51 @@ export class ServiceMonitoringServiceClient { // Put together the "service stub" for // google.monitoring.v3.ServiceMonitoringService. this.serviceMonitoringServiceStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.monitoring.v3.ServiceMonitoringService') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.monitoring.v3.ServiceMonitoringService', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.monitoring.v3.ServiceMonitoringService, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts, + this._providedCustomServicePath, + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const serviceMonitoringServiceStubMethods = - ['createService', 'getService', 'listServices', 'updateService', 'deleteService', 'createServiceLevelObjective', 'getServiceLevelObjective', 'listServiceLevelObjectives', 'updateServiceLevelObjective', 'deleteServiceLevelObjective']; + const serviceMonitoringServiceStubMethods = [ + 'createService', + 'getService', + 'listServices', + 'updateService', + 'deleteService', + 'createServiceLevelObjective', + 'getServiceLevelObjective', + 'listServiceLevelObjectives', + 'updateServiceLevelObjective', + 'deleteServiceLevelObjective', + ]; for (const methodName of serviceMonitoringServiceStubMethods) { const callPromise = this.serviceMonitoringServiceStub.then( - stub => (...args: Array<{}>) => { - if (this._terminated) { - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error|null|undefined) => () => { + (stub) => + (...args: Array<{}>) => { + if (this._terminated) { + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { throw err; - }); + }, + ); - const descriptor = - this.descriptors.page[methodName] || - undefined; + const descriptor = this.descriptors.page[methodName] || undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -340,8 +396,14 @@ export class ServiceMonitoringServiceClient { * @returns {string} The DNS address for this service. */ static get servicePath() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'monitoring.googleapis.com'; } @@ -352,8 +414,14 @@ export class ServiceMonitoringServiceClient { * @returns {string} The DNS address for this service. */ static get apiEndpoint() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'monitoring.googleapis.com'; } @@ -387,7 +455,7 @@ export class ServiceMonitoringServiceClient { return [ 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/monitoring', - 'https://www.googleapis.com/auth/monitoring.read' + 'https://www.googleapis.com/auth/monitoring.read', ]; } @@ -397,8 +465,9 @@ export class ServiceMonitoringServiceClient { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId(callback?: Callback): - Promise|void { + getProjectId( + callback?: Callback, + ): Promise | void { if (callback) { this.auth.getProjectId(callback); return; @@ -409,892 +478,1218 @@ export class ServiceMonitoringServiceClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Create a `Service`. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. Resource name of the parent workspace. - * Of the form `projects/{project_id}`. - * @param {string} request.serviceId - * Optional. The Service id to use for this Service. If omitted, an id will be - * generated instead. Must match the pattern [a-z0-9\-]+ - * @param {google.monitoring.v3.Service} request.service - * Required. The `Service` to create. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.monitoring.v3.Service|Service}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v3/service_monitoring_service.create_service.js - * region_tag:monitoring_v3_generated_ServiceMonitoringService_CreateService_async - */ + /** + * Create a `Service`. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Resource name of the parent workspace. + * Of the form `projects/{project_id}`. + * @param {string} request.serviceId + * Optional. The Service id to use for this Service. If omitted, an id will be + * generated instead. Must match the pattern [a-z0-9\-]+ + * @param {google.monitoring.v3.Service} request.service + * Required. The `Service` to create. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.monitoring.v3.Service|Service}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v3/service_monitoring_service.create_service.js + * region_tag:monitoring_v3_generated_ServiceMonitoringService_CreateService_async + */ createService( - request?: protos.google.monitoring.v3.ICreateServiceRequest, - options?: CallOptions): - Promise<[ - protos.google.monitoring.v3.IService, - protos.google.monitoring.v3.ICreateServiceRequest|undefined, {}|undefined - ]>; + request?: protos.google.monitoring.v3.ICreateServiceRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.monitoring.v3.IService, + protos.google.monitoring.v3.ICreateServiceRequest | undefined, + {} | undefined, + ] + >; createService( - request: protos.google.monitoring.v3.ICreateServiceRequest, - options: CallOptions, - callback: Callback< - protos.google.monitoring.v3.IService, - protos.google.monitoring.v3.ICreateServiceRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.ICreateServiceRequest, + options: CallOptions, + callback: Callback< + protos.google.monitoring.v3.IService, + protos.google.monitoring.v3.ICreateServiceRequest | null | undefined, + {} | null | undefined + >, + ): void; createService( - request: protos.google.monitoring.v3.ICreateServiceRequest, - callback: Callback< - protos.google.monitoring.v3.IService, - protos.google.monitoring.v3.ICreateServiceRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.ICreateServiceRequest, + callback: Callback< + protos.google.monitoring.v3.IService, + protos.google.monitoring.v3.ICreateServiceRequest | null | undefined, + {} | null | undefined + >, + ): void; createService( - request?: protos.google.monitoring.v3.ICreateServiceRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.monitoring.v3.IService, - protos.google.monitoring.v3.ICreateServiceRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.monitoring.v3.ICreateServiceRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.monitoring.v3.IService, - protos.google.monitoring.v3.ICreateServiceRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.monitoring.v3.IService, - protos.google.monitoring.v3.ICreateServiceRequest|undefined, {}|undefined - ]>|void { + protos.google.monitoring.v3.ICreateServiceRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.monitoring.v3.IService, + protos.google.monitoring.v3.ICreateServiceRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.monitoring.v3.IService, + protos.google.monitoring.v3.ICreateServiceRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('createService request %j', request); - const wrappedCallback: Callback< - protos.google.monitoring.v3.IService, - protos.google.monitoring.v3.ICreateServiceRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.monitoring.v3.IService, + protos.google.monitoring.v3.ICreateServiceRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createService response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.createService(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.monitoring.v3.IService, - protos.google.monitoring.v3.ICreateServiceRequest|undefined, - {}|undefined - ]) => { - this._log.info('createService response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createService(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.monitoring.v3.IService, + protos.google.monitoring.v3.ICreateServiceRequest | undefined, + {} | undefined, + ]) => { + this._log.info('createService response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Get the named `Service`. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. Resource name of the `Service`. - * Of the form `projects/{project_id}/services/{service_id}`. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.monitoring.v3.Service|Service}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v3/service_monitoring_service.get_service.js - * region_tag:monitoring_v3_generated_ServiceMonitoringService_GetService_async - */ + /** + * Get the named `Service`. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Resource name of the `Service`. + * Of the form `projects/{project_id}/services/{service_id}`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.monitoring.v3.Service|Service}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v3/service_monitoring_service.get_service.js + * region_tag:monitoring_v3_generated_ServiceMonitoringService_GetService_async + */ getService( - request?: protos.google.monitoring.v3.IGetServiceRequest, - options?: CallOptions): - Promise<[ - protos.google.monitoring.v3.IService, - protos.google.monitoring.v3.IGetServiceRequest|undefined, {}|undefined - ]>; + request?: protos.google.monitoring.v3.IGetServiceRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.monitoring.v3.IService, + protos.google.monitoring.v3.IGetServiceRequest | undefined, + {} | undefined, + ] + >; getService( - request: protos.google.monitoring.v3.IGetServiceRequest, - options: CallOptions, - callback: Callback< - protos.google.monitoring.v3.IService, - protos.google.monitoring.v3.IGetServiceRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.IGetServiceRequest, + options: CallOptions, + callback: Callback< + protos.google.monitoring.v3.IService, + protos.google.monitoring.v3.IGetServiceRequest | null | undefined, + {} | null | undefined + >, + ): void; getService( - request: protos.google.monitoring.v3.IGetServiceRequest, - callback: Callback< - protos.google.monitoring.v3.IService, - protos.google.monitoring.v3.IGetServiceRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.IGetServiceRequest, + callback: Callback< + protos.google.monitoring.v3.IService, + protos.google.monitoring.v3.IGetServiceRequest | null | undefined, + {} | null | undefined + >, + ): void; getService( - request?: protos.google.monitoring.v3.IGetServiceRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.monitoring.v3.IGetServiceRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.monitoring.v3.IService, - protos.google.monitoring.v3.IGetServiceRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.monitoring.v3.IService, - protos.google.monitoring.v3.IGetServiceRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.monitoring.v3.IService, - protos.google.monitoring.v3.IGetServiceRequest|undefined, {}|undefined - ]>|void { + protos.google.monitoring.v3.IGetServiceRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.monitoring.v3.IService, + protos.google.monitoring.v3.IGetServiceRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.monitoring.v3.IService, + protos.google.monitoring.v3.IGetServiceRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getService request %j', request); - const wrappedCallback: Callback< - protos.google.monitoring.v3.IService, - protos.google.monitoring.v3.IGetServiceRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.monitoring.v3.IService, + protos.google.monitoring.v3.IGetServiceRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getService response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getService(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.monitoring.v3.IService, - protos.google.monitoring.v3.IGetServiceRequest|undefined, - {}|undefined - ]) => { - this._log.info('getService response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getService(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.monitoring.v3.IService, + protos.google.monitoring.v3.IGetServiceRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getService response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Update this `Service`. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.monitoring.v3.Service} request.service - * Required. The `Service` to draw updates from. - * The given `name` specifies the resource to update. - * @param {google.protobuf.FieldMask} request.updateMask - * A set of field paths defining which fields to use for the update. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.monitoring.v3.Service|Service}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v3/service_monitoring_service.update_service.js - * region_tag:monitoring_v3_generated_ServiceMonitoringService_UpdateService_async - */ + /** + * Update this `Service`. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.monitoring.v3.Service} request.service + * Required. The `Service` to draw updates from. + * The given `name` specifies the resource to update. + * @param {google.protobuf.FieldMask} request.updateMask + * A set of field paths defining which fields to use for the update. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.monitoring.v3.Service|Service}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v3/service_monitoring_service.update_service.js + * region_tag:monitoring_v3_generated_ServiceMonitoringService_UpdateService_async + */ updateService( - request?: protos.google.monitoring.v3.IUpdateServiceRequest, - options?: CallOptions): - Promise<[ - protos.google.monitoring.v3.IService, - protos.google.monitoring.v3.IUpdateServiceRequest|undefined, {}|undefined - ]>; + request?: protos.google.monitoring.v3.IUpdateServiceRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.monitoring.v3.IService, + protos.google.monitoring.v3.IUpdateServiceRequest | undefined, + {} | undefined, + ] + >; updateService( - request: protos.google.monitoring.v3.IUpdateServiceRequest, - options: CallOptions, - callback: Callback< - protos.google.monitoring.v3.IService, - protos.google.monitoring.v3.IUpdateServiceRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.IUpdateServiceRequest, + options: CallOptions, + callback: Callback< + protos.google.monitoring.v3.IService, + protos.google.monitoring.v3.IUpdateServiceRequest | null | undefined, + {} | null | undefined + >, + ): void; updateService( - request: protos.google.monitoring.v3.IUpdateServiceRequest, - callback: Callback< - protos.google.monitoring.v3.IService, - protos.google.monitoring.v3.IUpdateServiceRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.IUpdateServiceRequest, + callback: Callback< + protos.google.monitoring.v3.IService, + protos.google.monitoring.v3.IUpdateServiceRequest | null | undefined, + {} | null | undefined + >, + ): void; updateService( - request?: protos.google.monitoring.v3.IUpdateServiceRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.monitoring.v3.IService, - protos.google.monitoring.v3.IUpdateServiceRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.monitoring.v3.IUpdateServiceRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.monitoring.v3.IService, - protos.google.monitoring.v3.IUpdateServiceRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.monitoring.v3.IService, - protos.google.monitoring.v3.IUpdateServiceRequest|undefined, {}|undefined - ]>|void { + protos.google.monitoring.v3.IUpdateServiceRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.monitoring.v3.IService, + protos.google.monitoring.v3.IUpdateServiceRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.monitoring.v3.IService, + protos.google.monitoring.v3.IUpdateServiceRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'service.name': request.service!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'service.name': request.service!.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateService request %j', request); - const wrappedCallback: Callback< - protos.google.monitoring.v3.IService, - protos.google.monitoring.v3.IUpdateServiceRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.monitoring.v3.IService, + protos.google.monitoring.v3.IUpdateServiceRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateService response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.updateService(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.monitoring.v3.IService, - protos.google.monitoring.v3.IUpdateServiceRequest|undefined, - {}|undefined - ]) => { - this._log.info('updateService response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateService(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.monitoring.v3.IService, + protos.google.monitoring.v3.IUpdateServiceRequest | undefined, + {} | undefined, + ]) => { + this._log.info('updateService response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Soft delete this `Service`. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. Resource name of the `Service` to delete. - * Of the form `projects/{project_id}/services/{service_id}`. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v3/service_monitoring_service.delete_service.js - * region_tag:monitoring_v3_generated_ServiceMonitoringService_DeleteService_async - */ + /** + * Soft delete this `Service`. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Resource name of the `Service` to delete. + * Of the form `projects/{project_id}/services/{service_id}`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v3/service_monitoring_service.delete_service.js + * region_tag:monitoring_v3_generated_ServiceMonitoringService_DeleteService_async + */ deleteService( - request?: protos.google.monitoring.v3.IDeleteServiceRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.IDeleteServiceRequest|undefined, {}|undefined - ]>; + request?: protos.google.monitoring.v3.IDeleteServiceRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.monitoring.v3.IDeleteServiceRequest | undefined, + {} | undefined, + ] + >; deleteService( - request: protos.google.monitoring.v3.IDeleteServiceRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.IDeleteServiceRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.IDeleteServiceRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.monitoring.v3.IDeleteServiceRequest | null | undefined, + {} | null | undefined + >, + ): void; deleteService( - request: protos.google.monitoring.v3.IDeleteServiceRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.IDeleteServiceRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.IDeleteServiceRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.monitoring.v3.IDeleteServiceRequest | null | undefined, + {} | null | undefined + >, + ): void; deleteService( - request?: protos.google.monitoring.v3.IDeleteServiceRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.IDeleteServiceRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.monitoring.v3.IDeleteServiceRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.IDeleteServiceRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.IDeleteServiceRequest|undefined, {}|undefined - ]>|void { + protos.google.monitoring.v3.IDeleteServiceRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + protos.google.monitoring.v3.IDeleteServiceRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.monitoring.v3.IDeleteServiceRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('deleteService request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.IDeleteServiceRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + protos.google.monitoring.v3.IDeleteServiceRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteService response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.deleteService(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.IDeleteServiceRequest|undefined, - {}|undefined - ]) => { - this._log.info('deleteService response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteService(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.monitoring.v3.IDeleteServiceRequest | undefined, + {} | undefined, + ]) => { + this._log.info('deleteService response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Create a `ServiceLevelObjective` for the given `Service`. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. Resource name of the parent `Service`. - * Of the form `projects/{project_id}/services/{service_id}`. - * @param {string} request.serviceLevelObjectiveId - * Optional. The ServiceLevelObjective id to use for this - * ServiceLevelObjective. If omitted, an id will be generated instead. Must - * match the pattern [a-z0-9\-]+ - * @param {google.monitoring.v3.ServiceLevelObjective} request.serviceLevelObjective - * Required. The `ServiceLevelObjective` to create. - * The provided `name` will be respected if no `ServiceLevelObjective` exists - * with this name. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.monitoring.v3.ServiceLevelObjective|ServiceLevelObjective}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v3/service_monitoring_service.create_service_level_objective.js - * region_tag:monitoring_v3_generated_ServiceMonitoringService_CreateServiceLevelObjective_async - */ + /** + * Create a `ServiceLevelObjective` for the given `Service`. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Resource name of the parent `Service`. + * Of the form `projects/{project_id}/services/{service_id}`. + * @param {string} request.serviceLevelObjectiveId + * Optional. The ServiceLevelObjective id to use for this + * ServiceLevelObjective. If omitted, an id will be generated instead. Must + * match the pattern [a-z0-9\-]+ + * @param {google.monitoring.v3.ServiceLevelObjective} request.serviceLevelObjective + * Required. The `ServiceLevelObjective` to create. + * The provided `name` will be respected if no `ServiceLevelObjective` exists + * with this name. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.monitoring.v3.ServiceLevelObjective|ServiceLevelObjective}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v3/service_monitoring_service.create_service_level_objective.js + * region_tag:monitoring_v3_generated_ServiceMonitoringService_CreateServiceLevelObjective_async + */ createServiceLevelObjective( - request?: protos.google.monitoring.v3.ICreateServiceLevelObjectiveRequest, - options?: CallOptions): - Promise<[ - protos.google.monitoring.v3.IServiceLevelObjective, - protos.google.monitoring.v3.ICreateServiceLevelObjectiveRequest|undefined, {}|undefined - ]>; + request?: protos.google.monitoring.v3.ICreateServiceLevelObjectiveRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.monitoring.v3.IServiceLevelObjective, + ( + | protos.google.monitoring.v3.ICreateServiceLevelObjectiveRequest + | undefined + ), + {} | undefined, + ] + >; createServiceLevelObjective( - request: protos.google.monitoring.v3.ICreateServiceLevelObjectiveRequest, - options: CallOptions, - callback: Callback< - protos.google.monitoring.v3.IServiceLevelObjective, - protos.google.monitoring.v3.ICreateServiceLevelObjectiveRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.ICreateServiceLevelObjectiveRequest, + options: CallOptions, + callback: Callback< + protos.google.monitoring.v3.IServiceLevelObjective, + | protos.google.monitoring.v3.ICreateServiceLevelObjectiveRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createServiceLevelObjective( - request: protos.google.monitoring.v3.ICreateServiceLevelObjectiveRequest, - callback: Callback< - protos.google.monitoring.v3.IServiceLevelObjective, - protos.google.monitoring.v3.ICreateServiceLevelObjectiveRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.ICreateServiceLevelObjectiveRequest, + callback: Callback< + protos.google.monitoring.v3.IServiceLevelObjective, + | protos.google.monitoring.v3.ICreateServiceLevelObjectiveRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createServiceLevelObjective( - request?: protos.google.monitoring.v3.ICreateServiceLevelObjectiveRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.monitoring.v3.IServiceLevelObjective, - protos.google.monitoring.v3.ICreateServiceLevelObjectiveRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.monitoring.v3.ICreateServiceLevelObjectiveRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.monitoring.v3.IServiceLevelObjective, - protos.google.monitoring.v3.ICreateServiceLevelObjectiveRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.monitoring.v3.IServiceLevelObjective, - protos.google.monitoring.v3.ICreateServiceLevelObjectiveRequest|undefined, {}|undefined - ]>|void { + | protos.google.monitoring.v3.ICreateServiceLevelObjectiveRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.monitoring.v3.IServiceLevelObjective, + | protos.google.monitoring.v3.ICreateServiceLevelObjectiveRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.monitoring.v3.IServiceLevelObjective, + ( + | protos.google.monitoring.v3.ICreateServiceLevelObjectiveRequest + | undefined + ), + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('createServiceLevelObjective request %j', request); - const wrappedCallback: Callback< - protos.google.monitoring.v3.IServiceLevelObjective, - protos.google.monitoring.v3.ICreateServiceLevelObjectiveRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.monitoring.v3.IServiceLevelObjective, + | protos.google.monitoring.v3.ICreateServiceLevelObjectiveRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createServiceLevelObjective response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.createServiceLevelObjective(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.monitoring.v3.IServiceLevelObjective, - protos.google.monitoring.v3.ICreateServiceLevelObjectiveRequest|undefined, - {}|undefined - ]) => { - this._log.info('createServiceLevelObjective response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createServiceLevelObjective(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.monitoring.v3.IServiceLevelObjective, + ( + | protos.google.monitoring.v3.ICreateServiceLevelObjectiveRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('createServiceLevelObjective response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Get a `ServiceLevelObjective` by name. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. Resource name of the `ServiceLevelObjective` to get. - * Of the form - * `projects/{project_id}/services/{service_id}/serviceLevelObjectives/{slo_name}`. - * @param {google.monitoring.v3.ServiceLevelObjective.View} request.view - * View of the `ServiceLevelObjective` to return. If `DEFAULT`, return the - * `ServiceLevelObjective` as originally defined. If `EXPLICIT` and the - * `ServiceLevelObjective` is defined in terms of a `BasicSli`, replace the - * `BasicSli` with a `RequestBasedSli` spelling out how the SLI is computed. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.monitoring.v3.ServiceLevelObjective|ServiceLevelObjective}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v3/service_monitoring_service.get_service_level_objective.js - * region_tag:monitoring_v3_generated_ServiceMonitoringService_GetServiceLevelObjective_async - */ + /** + * Get a `ServiceLevelObjective` by name. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Resource name of the `ServiceLevelObjective` to get. + * Of the form + * `projects/{project_id}/services/{service_id}/serviceLevelObjectives/{slo_name}`. + * @param {google.monitoring.v3.ServiceLevelObjective.View} request.view + * View of the `ServiceLevelObjective` to return. If `DEFAULT`, return the + * `ServiceLevelObjective` as originally defined. If `EXPLICIT` and the + * `ServiceLevelObjective` is defined in terms of a `BasicSli`, replace the + * `BasicSli` with a `RequestBasedSli` spelling out how the SLI is computed. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.monitoring.v3.ServiceLevelObjective|ServiceLevelObjective}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v3/service_monitoring_service.get_service_level_objective.js + * region_tag:monitoring_v3_generated_ServiceMonitoringService_GetServiceLevelObjective_async + */ getServiceLevelObjective( - request?: protos.google.monitoring.v3.IGetServiceLevelObjectiveRequest, - options?: CallOptions): - Promise<[ - protos.google.monitoring.v3.IServiceLevelObjective, - protos.google.monitoring.v3.IGetServiceLevelObjectiveRequest|undefined, {}|undefined - ]>; + request?: protos.google.monitoring.v3.IGetServiceLevelObjectiveRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.monitoring.v3.IServiceLevelObjective, + protos.google.monitoring.v3.IGetServiceLevelObjectiveRequest | undefined, + {} | undefined, + ] + >; getServiceLevelObjective( - request: protos.google.monitoring.v3.IGetServiceLevelObjectiveRequest, - options: CallOptions, - callback: Callback< - protos.google.monitoring.v3.IServiceLevelObjective, - protos.google.monitoring.v3.IGetServiceLevelObjectiveRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.IGetServiceLevelObjectiveRequest, + options: CallOptions, + callback: Callback< + protos.google.monitoring.v3.IServiceLevelObjective, + | protos.google.monitoring.v3.IGetServiceLevelObjectiveRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getServiceLevelObjective( - request: protos.google.monitoring.v3.IGetServiceLevelObjectiveRequest, - callback: Callback< - protos.google.monitoring.v3.IServiceLevelObjective, - protos.google.monitoring.v3.IGetServiceLevelObjectiveRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.IGetServiceLevelObjectiveRequest, + callback: Callback< + protos.google.monitoring.v3.IServiceLevelObjective, + | protos.google.monitoring.v3.IGetServiceLevelObjectiveRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getServiceLevelObjective( - request?: protos.google.monitoring.v3.IGetServiceLevelObjectiveRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.monitoring.v3.IGetServiceLevelObjectiveRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.monitoring.v3.IServiceLevelObjective, - protos.google.monitoring.v3.IGetServiceLevelObjectiveRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.monitoring.v3.IServiceLevelObjective, - protos.google.monitoring.v3.IGetServiceLevelObjectiveRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.monitoring.v3.IServiceLevelObjective, - protos.google.monitoring.v3.IGetServiceLevelObjectiveRequest|undefined, {}|undefined - ]>|void { + | protos.google.monitoring.v3.IGetServiceLevelObjectiveRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.monitoring.v3.IServiceLevelObjective, + | protos.google.monitoring.v3.IGetServiceLevelObjectiveRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.monitoring.v3.IServiceLevelObjective, + protos.google.monitoring.v3.IGetServiceLevelObjectiveRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getServiceLevelObjective request %j', request); - const wrappedCallback: Callback< - protos.google.monitoring.v3.IServiceLevelObjective, - protos.google.monitoring.v3.IGetServiceLevelObjectiveRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.monitoring.v3.IServiceLevelObjective, + | protos.google.monitoring.v3.IGetServiceLevelObjectiveRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getServiceLevelObjective response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getServiceLevelObjective(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.monitoring.v3.IServiceLevelObjective, - protos.google.monitoring.v3.IGetServiceLevelObjectiveRequest|undefined, - {}|undefined - ]) => { - this._log.info('getServiceLevelObjective response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getServiceLevelObjective(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.monitoring.v3.IServiceLevelObjective, + ( + | protos.google.monitoring.v3.IGetServiceLevelObjectiveRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('getServiceLevelObjective response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Update the given `ServiceLevelObjective`. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.monitoring.v3.ServiceLevelObjective} request.serviceLevelObjective - * Required. The `ServiceLevelObjective` to draw updates from. - * The given `name` specifies the resource to update. - * @param {google.protobuf.FieldMask} request.updateMask - * A set of field paths defining which fields to use for the update. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.monitoring.v3.ServiceLevelObjective|ServiceLevelObjective}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v3/service_monitoring_service.update_service_level_objective.js - * region_tag:monitoring_v3_generated_ServiceMonitoringService_UpdateServiceLevelObjective_async - */ + /** + * Update the given `ServiceLevelObjective`. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.monitoring.v3.ServiceLevelObjective} request.serviceLevelObjective + * Required. The `ServiceLevelObjective` to draw updates from. + * The given `name` specifies the resource to update. + * @param {google.protobuf.FieldMask} request.updateMask + * A set of field paths defining which fields to use for the update. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.monitoring.v3.ServiceLevelObjective|ServiceLevelObjective}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v3/service_monitoring_service.update_service_level_objective.js + * region_tag:monitoring_v3_generated_ServiceMonitoringService_UpdateServiceLevelObjective_async + */ updateServiceLevelObjective( - request?: protos.google.monitoring.v3.IUpdateServiceLevelObjectiveRequest, - options?: CallOptions): - Promise<[ - protos.google.monitoring.v3.IServiceLevelObjective, - protos.google.monitoring.v3.IUpdateServiceLevelObjectiveRequest|undefined, {}|undefined - ]>; + request?: protos.google.monitoring.v3.IUpdateServiceLevelObjectiveRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.monitoring.v3.IServiceLevelObjective, + ( + | protos.google.monitoring.v3.IUpdateServiceLevelObjectiveRequest + | undefined + ), + {} | undefined, + ] + >; updateServiceLevelObjective( - request: protos.google.monitoring.v3.IUpdateServiceLevelObjectiveRequest, - options: CallOptions, - callback: Callback< - protos.google.monitoring.v3.IServiceLevelObjective, - protos.google.monitoring.v3.IUpdateServiceLevelObjectiveRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.IUpdateServiceLevelObjectiveRequest, + options: CallOptions, + callback: Callback< + protos.google.monitoring.v3.IServiceLevelObjective, + | protos.google.monitoring.v3.IUpdateServiceLevelObjectiveRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateServiceLevelObjective( - request: protos.google.monitoring.v3.IUpdateServiceLevelObjectiveRequest, - callback: Callback< - protos.google.monitoring.v3.IServiceLevelObjective, - protos.google.monitoring.v3.IUpdateServiceLevelObjectiveRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.IUpdateServiceLevelObjectiveRequest, + callback: Callback< + protos.google.monitoring.v3.IServiceLevelObjective, + | protos.google.monitoring.v3.IUpdateServiceLevelObjectiveRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateServiceLevelObjective( - request?: protos.google.monitoring.v3.IUpdateServiceLevelObjectiveRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.monitoring.v3.IUpdateServiceLevelObjectiveRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.monitoring.v3.IServiceLevelObjective, - protos.google.monitoring.v3.IUpdateServiceLevelObjectiveRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.monitoring.v3.IServiceLevelObjective, - protos.google.monitoring.v3.IUpdateServiceLevelObjectiveRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.monitoring.v3.IServiceLevelObjective, - protos.google.monitoring.v3.IUpdateServiceLevelObjectiveRequest|undefined, {}|undefined - ]>|void { + | protos.google.monitoring.v3.IUpdateServiceLevelObjectiveRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.monitoring.v3.IServiceLevelObjective, + | protos.google.monitoring.v3.IUpdateServiceLevelObjectiveRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.monitoring.v3.IServiceLevelObjective, + ( + | protos.google.monitoring.v3.IUpdateServiceLevelObjectiveRequest + | undefined + ), + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'service_level_objective.name': request.serviceLevelObjective!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'service_level_objective.name': + request.serviceLevelObjective!.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateServiceLevelObjective request %j', request); - const wrappedCallback: Callback< - protos.google.monitoring.v3.IServiceLevelObjective, - protos.google.monitoring.v3.IUpdateServiceLevelObjectiveRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.monitoring.v3.IServiceLevelObjective, + | protos.google.monitoring.v3.IUpdateServiceLevelObjectiveRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateServiceLevelObjective response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.updateServiceLevelObjective(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.monitoring.v3.IServiceLevelObjective, - protos.google.monitoring.v3.IUpdateServiceLevelObjectiveRequest|undefined, - {}|undefined - ]) => { - this._log.info('updateServiceLevelObjective response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateServiceLevelObjective(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.monitoring.v3.IServiceLevelObjective, + ( + | protos.google.monitoring.v3.IUpdateServiceLevelObjectiveRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('updateServiceLevelObjective response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Delete the given `ServiceLevelObjective`. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. Resource name of the `ServiceLevelObjective` to delete. - * Of the form - * `projects/{project_id}/services/{service_id}/serviceLevelObjectives/{slo_name}`. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v3/service_monitoring_service.delete_service_level_objective.js - * region_tag:monitoring_v3_generated_ServiceMonitoringService_DeleteServiceLevelObjective_async - */ + /** + * Delete the given `ServiceLevelObjective`. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Resource name of the `ServiceLevelObjective` to delete. + * Of the form + * `projects/{project_id}/services/{service_id}/serviceLevelObjectives/{slo_name}`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v3/service_monitoring_service.delete_service_level_objective.js + * region_tag:monitoring_v3_generated_ServiceMonitoringService_DeleteServiceLevelObjective_async + */ deleteServiceLevelObjective( - request?: protos.google.monitoring.v3.IDeleteServiceLevelObjectiveRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.IDeleteServiceLevelObjectiveRequest|undefined, {}|undefined - ]>; + request?: protos.google.monitoring.v3.IDeleteServiceLevelObjectiveRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.monitoring.v3.IDeleteServiceLevelObjectiveRequest + | undefined + ), + {} | undefined, + ] + >; deleteServiceLevelObjective( - request: protos.google.monitoring.v3.IDeleteServiceLevelObjectiveRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.IDeleteServiceLevelObjectiveRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.IDeleteServiceLevelObjectiveRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.monitoring.v3.IDeleteServiceLevelObjectiveRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteServiceLevelObjective( - request: protos.google.monitoring.v3.IDeleteServiceLevelObjectiveRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.IDeleteServiceLevelObjectiveRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.IDeleteServiceLevelObjectiveRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.monitoring.v3.IDeleteServiceLevelObjectiveRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteServiceLevelObjective( - request?: protos.google.monitoring.v3.IDeleteServiceLevelObjectiveRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.monitoring.v3.IDeleteServiceLevelObjectiveRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.IDeleteServiceLevelObjectiveRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.IDeleteServiceLevelObjectiveRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.IDeleteServiceLevelObjectiveRequest|undefined, {}|undefined - ]>|void { + | protos.google.monitoring.v3.IDeleteServiceLevelObjectiveRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + | protos.google.monitoring.v3.IDeleteServiceLevelObjectiveRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.monitoring.v3.IDeleteServiceLevelObjectiveRequest + | undefined + ), + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('deleteServiceLevelObjective request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.IDeleteServiceLevelObjectiveRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.monitoring.v3.IDeleteServiceLevelObjectiveRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteServiceLevelObjective response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.deleteServiceLevelObjective(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.IDeleteServiceLevelObjectiveRequest|undefined, - {}|undefined - ]) => { - this._log.info('deleteServiceLevelObjective response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteServiceLevelObjective(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + ( + | protos.google.monitoring.v3.IDeleteServiceLevelObjectiveRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('deleteServiceLevelObjective response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } - /** - * List `Service`s for this workspace. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. Resource name of the parent `Workspace`. - * Of the form `projects/{project_id}`. - * @param {string} request.filter - * A filter specifying what `Service`s to return. The filter currently - * supports the following fields: - * - * - `identifier_case` - * - `app_engine.module_id` - * - `cloud_endpoints.service` - * - `cluster_istio.location` - * - `cluster_istio.cluster_name` - * - `cluster_istio.service_namespace` - * - `cluster_istio.service_name` - * - * `identifier_case` refers to which option in the identifier oneof is - * populated. For example, the filter `identifier_case = "CUSTOM"` would match - * all services with a value for the `custom` field. Valid options are - * "CUSTOM", "APP_ENGINE", "CLOUD_ENDPOINTS", and "CLUSTER_ISTIO". - * @param {number} request.pageSize - * A non-negative number that is the maximum number of results to return. - * When 0, use default page size. - * @param {string} request.pageToken - * If this field is not empty then it must contain the `nextPageToken` value - * returned by a previous call to this method. Using this field causes the - * method to return additional results from the previous method call. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.monitoring.v3.Service|Service}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `listServicesAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * List `Service`s for this workspace. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Resource name of the parent `Workspace`. + * Of the form `projects/{project_id}`. + * @param {string} request.filter + * A filter specifying what `Service`s to return. The filter currently + * supports the following fields: + * + * - `identifier_case` + * - `app_engine.module_id` + * - `cloud_endpoints.service` + * - `cluster_istio.location` + * - `cluster_istio.cluster_name` + * - `cluster_istio.service_namespace` + * - `cluster_istio.service_name` + * + * `identifier_case` refers to which option in the identifier oneof is + * populated. For example, the filter `identifier_case = "CUSTOM"` would match + * all services with a value for the `custom` field. Valid options are + * "CUSTOM", "APP_ENGINE", "CLOUD_ENDPOINTS", and "CLUSTER_ISTIO". + * @param {number} request.pageSize + * A non-negative number that is the maximum number of results to return. + * When 0, use default page size. + * @param {string} request.pageToken + * If this field is not empty then it must contain the `nextPageToken` value + * returned by a previous call to this method. Using this field causes the + * method to return additional results from the previous method call. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.monitoring.v3.Service|Service}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listServicesAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listServices( - request?: protos.google.monitoring.v3.IListServicesRequest, - options?: CallOptions): - Promise<[ - protos.google.monitoring.v3.IService[], - protos.google.monitoring.v3.IListServicesRequest|null, - protos.google.monitoring.v3.IListServicesResponse - ]>; + request?: protos.google.monitoring.v3.IListServicesRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.monitoring.v3.IService[], + protos.google.monitoring.v3.IListServicesRequest | null, + protos.google.monitoring.v3.IListServicesResponse, + ] + >; listServices( - request: protos.google.monitoring.v3.IListServicesRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.monitoring.v3.IListServicesRequest, - protos.google.monitoring.v3.IListServicesResponse|null|undefined, - protos.google.monitoring.v3.IService>): void; + request: protos.google.monitoring.v3.IListServicesRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.monitoring.v3.IListServicesRequest, + protos.google.monitoring.v3.IListServicesResponse | null | undefined, + protos.google.monitoring.v3.IService + >, + ): void; listServices( - request: protos.google.monitoring.v3.IListServicesRequest, - callback: PaginationCallback< - protos.google.monitoring.v3.IListServicesRequest, - protos.google.monitoring.v3.IListServicesResponse|null|undefined, - protos.google.monitoring.v3.IService>): void; + request: protos.google.monitoring.v3.IListServicesRequest, + callback: PaginationCallback< + protos.google.monitoring.v3.IListServicesRequest, + protos.google.monitoring.v3.IListServicesResponse | null | undefined, + protos.google.monitoring.v3.IService + >, + ): void; listServices( - request?: protos.google.monitoring.v3.IListServicesRequest, - optionsOrCallback?: CallOptions|PaginationCallback< + request?: protos.google.monitoring.v3.IListServicesRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.monitoring.v3.IListServicesRequest, - protos.google.monitoring.v3.IListServicesResponse|null|undefined, - protos.google.monitoring.v3.IService>, - callback?: PaginationCallback< - protos.google.monitoring.v3.IListServicesRequest, - protos.google.monitoring.v3.IListServicesResponse|null|undefined, - protos.google.monitoring.v3.IService>): - Promise<[ - protos.google.monitoring.v3.IService[], - protos.google.monitoring.v3.IListServicesRequest|null, - protos.google.monitoring.v3.IListServicesResponse - ]>|void { + protos.google.monitoring.v3.IListServicesResponse | null | undefined, + protos.google.monitoring.v3.IService + >, + callback?: PaginationCallback< + protos.google.monitoring.v3.IListServicesRequest, + protos.google.monitoring.v3.IListServicesResponse | null | undefined, + protos.google.monitoring.v3.IService + >, + ): Promise< + [ + protos.google.monitoring.v3.IService[], + protos.google.monitoring.v3.IListServicesRequest | null, + protos.google.monitoring.v3.IListServicesResponse, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.monitoring.v3.IListServicesRequest, - protos.google.monitoring.v3.IListServicesResponse|null|undefined, - protos.google.monitoring.v3.IService>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.monitoring.v3.IListServicesRequest, + protos.google.monitoring.v3.IListServicesResponse | null | undefined, + protos.google.monitoring.v3.IService + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listServices values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -1303,240 +1698,269 @@ export class ServiceMonitoringServiceClient { this._log.info('listServices request %j', request); return this.innerApiCalls .listServices(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.monitoring.v3.IService[], - protos.google.monitoring.v3.IListServicesRequest|null, - protos.google.monitoring.v3.IListServicesResponse - ]) => { - this._log.info('listServices values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.monitoring.v3.IService[], + protos.google.monitoring.v3.IListServicesRequest | null, + protos.google.monitoring.v3.IListServicesResponse, + ]) => { + this._log.info('listServices values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listServices`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. Resource name of the parent `Workspace`. - * Of the form `projects/{project_id}`. - * @param {string} request.filter - * A filter specifying what `Service`s to return. The filter currently - * supports the following fields: - * - * - `identifier_case` - * - `app_engine.module_id` - * - `cloud_endpoints.service` - * - `cluster_istio.location` - * - `cluster_istio.cluster_name` - * - `cluster_istio.service_namespace` - * - `cluster_istio.service_name` - * - * `identifier_case` refers to which option in the identifier oneof is - * populated. For example, the filter `identifier_case = "CUSTOM"` would match - * all services with a value for the `custom` field. Valid options are - * "CUSTOM", "APP_ENGINE", "CLOUD_ENDPOINTS", and "CLUSTER_ISTIO". - * @param {number} request.pageSize - * A non-negative number that is the maximum number of results to return. - * When 0, use default page size. - * @param {string} request.pageToken - * If this field is not empty then it must contain the `nextPageToken` value - * returned by a previous call to this method. Using this field causes the - * method to return additional results from the previous method call. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.monitoring.v3.Service|Service} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `listServicesAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `listServices`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Resource name of the parent `Workspace`. + * Of the form `projects/{project_id}`. + * @param {string} request.filter + * A filter specifying what `Service`s to return. The filter currently + * supports the following fields: + * + * - `identifier_case` + * - `app_engine.module_id` + * - `cloud_endpoints.service` + * - `cluster_istio.location` + * - `cluster_istio.cluster_name` + * - `cluster_istio.service_namespace` + * - `cluster_istio.service_name` + * + * `identifier_case` refers to which option in the identifier oneof is + * populated. For example, the filter `identifier_case = "CUSTOM"` would match + * all services with a value for the `custom` field. Valid options are + * "CUSTOM", "APP_ENGINE", "CLOUD_ENDPOINTS", and "CLUSTER_ISTIO". + * @param {number} request.pageSize + * A non-negative number that is the maximum number of results to return. + * When 0, use default page size. + * @param {string} request.pageToken + * If this field is not empty then it must contain the `nextPageToken` value + * returned by a previous call to this method. Using this field causes the + * method to return additional results from the previous method call. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.monitoring.v3.Service|Service} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listServicesAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listServicesStream( - request?: protos.google.monitoring.v3.IListServicesRequest, - options?: CallOptions): - Transform{ + request?: protos.google.monitoring.v3.IListServicesRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); const defaultCallSettings = this._defaults['listServices']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listServices stream %j', request); return this.descriptors.page.listServices.createStream( this.innerApiCalls.listServices as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listServices`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. Resource name of the parent `Workspace`. - * Of the form `projects/{project_id}`. - * @param {string} request.filter - * A filter specifying what `Service`s to return. The filter currently - * supports the following fields: - * - * - `identifier_case` - * - `app_engine.module_id` - * - `cloud_endpoints.service` - * - `cluster_istio.location` - * - `cluster_istio.cluster_name` - * - `cluster_istio.service_namespace` - * - `cluster_istio.service_name` - * - * `identifier_case` refers to which option in the identifier oneof is - * populated. For example, the filter `identifier_case = "CUSTOM"` would match - * all services with a value for the `custom` field. Valid options are - * "CUSTOM", "APP_ENGINE", "CLOUD_ENDPOINTS", and "CLUSTER_ISTIO". - * @param {number} request.pageSize - * A non-negative number that is the maximum number of results to return. - * When 0, use default page size. - * @param {string} request.pageToken - * If this field is not empty then it must contain the `nextPageToken` value - * returned by a previous call to this method. Using this field causes the - * method to return additional results from the previous method call. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.monitoring.v3.Service|Service}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v3/service_monitoring_service.list_services.js - * region_tag:monitoring_v3_generated_ServiceMonitoringService_ListServices_async - */ + /** + * Equivalent to `listServices`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Resource name of the parent `Workspace`. + * Of the form `projects/{project_id}`. + * @param {string} request.filter + * A filter specifying what `Service`s to return. The filter currently + * supports the following fields: + * + * - `identifier_case` + * - `app_engine.module_id` + * - `cloud_endpoints.service` + * - `cluster_istio.location` + * - `cluster_istio.cluster_name` + * - `cluster_istio.service_namespace` + * - `cluster_istio.service_name` + * + * `identifier_case` refers to which option in the identifier oneof is + * populated. For example, the filter `identifier_case = "CUSTOM"` would match + * all services with a value for the `custom` field. Valid options are + * "CUSTOM", "APP_ENGINE", "CLOUD_ENDPOINTS", and "CLUSTER_ISTIO". + * @param {number} request.pageSize + * A non-negative number that is the maximum number of results to return. + * When 0, use default page size. + * @param {string} request.pageToken + * If this field is not empty then it must contain the `nextPageToken` value + * returned by a previous call to this method. Using this field causes the + * method to return additional results from the previous method call. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.monitoring.v3.Service|Service}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v3/service_monitoring_service.list_services.js + * region_tag:monitoring_v3_generated_ServiceMonitoringService_ListServices_async + */ listServicesAsync( - request?: protos.google.monitoring.v3.IListServicesRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.monitoring.v3.IListServicesRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); const defaultCallSettings = this._defaults['listServices']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listServices iterate %j', request); return this.descriptors.page.listServices.asyncIterate( this.innerApiCalls['listServices'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } - /** - * List the `ServiceLevelObjective`s for the given `Service`. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. Resource name of the parent `Service`. - * Of the form `projects/{project_id}/services/{service_id}`. - * @param {string} request.filter - * A filter specifying what `ServiceLevelObjective`s to return. - * @param {number} request.pageSize - * A non-negative number that is the maximum number of results to return. - * When 0, use default page size. - * @param {string} request.pageToken - * If this field is not empty then it must contain the `nextPageToken` value - * returned by a previous call to this method. Using this field causes the - * method to return additional results from the previous method call. - * @param {google.monitoring.v3.ServiceLevelObjective.View} request.view - * View of the `ServiceLevelObjective`s to return. If `DEFAULT`, return each - * `ServiceLevelObjective` as originally defined. If `EXPLICIT` and the - * `ServiceLevelObjective` is defined in terms of a `BasicSli`, replace the - * `BasicSli` with a `RequestBasedSli` spelling out how the SLI is computed. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.monitoring.v3.ServiceLevelObjective|ServiceLevelObjective}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `listServiceLevelObjectivesAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * List the `ServiceLevelObjective`s for the given `Service`. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Resource name of the parent `Service`. + * Of the form `projects/{project_id}/services/{service_id}`. + * @param {string} request.filter + * A filter specifying what `ServiceLevelObjective`s to return. + * @param {number} request.pageSize + * A non-negative number that is the maximum number of results to return. + * When 0, use default page size. + * @param {string} request.pageToken + * If this field is not empty then it must contain the `nextPageToken` value + * returned by a previous call to this method. Using this field causes the + * method to return additional results from the previous method call. + * @param {google.monitoring.v3.ServiceLevelObjective.View} request.view + * View of the `ServiceLevelObjective`s to return. If `DEFAULT`, return each + * `ServiceLevelObjective` as originally defined. If `EXPLICIT` and the + * `ServiceLevelObjective` is defined in terms of a `BasicSli`, replace the + * `BasicSli` with a `RequestBasedSli` spelling out how the SLI is computed. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.monitoring.v3.ServiceLevelObjective|ServiceLevelObjective}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listServiceLevelObjectivesAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listServiceLevelObjectives( - request?: protos.google.monitoring.v3.IListServiceLevelObjectivesRequest, - options?: CallOptions): - Promise<[ - protos.google.monitoring.v3.IServiceLevelObjective[], - protos.google.monitoring.v3.IListServiceLevelObjectivesRequest|null, - protos.google.monitoring.v3.IListServiceLevelObjectivesResponse - ]>; + request?: protos.google.monitoring.v3.IListServiceLevelObjectivesRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.monitoring.v3.IServiceLevelObjective[], + protos.google.monitoring.v3.IListServiceLevelObjectivesRequest | null, + protos.google.monitoring.v3.IListServiceLevelObjectivesResponse, + ] + >; listServiceLevelObjectives( - request: protos.google.monitoring.v3.IListServiceLevelObjectivesRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.monitoring.v3.IListServiceLevelObjectivesRequest, - protos.google.monitoring.v3.IListServiceLevelObjectivesResponse|null|undefined, - protos.google.monitoring.v3.IServiceLevelObjective>): void; + request: protos.google.monitoring.v3.IListServiceLevelObjectivesRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.monitoring.v3.IListServiceLevelObjectivesRequest, + | protos.google.monitoring.v3.IListServiceLevelObjectivesResponse + | null + | undefined, + protos.google.monitoring.v3.IServiceLevelObjective + >, + ): void; listServiceLevelObjectives( - request: protos.google.monitoring.v3.IListServiceLevelObjectivesRequest, - callback: PaginationCallback< - protos.google.monitoring.v3.IListServiceLevelObjectivesRequest, - protos.google.monitoring.v3.IListServiceLevelObjectivesResponse|null|undefined, - protos.google.monitoring.v3.IServiceLevelObjective>): void; + request: protos.google.monitoring.v3.IListServiceLevelObjectivesRequest, + callback: PaginationCallback< + protos.google.monitoring.v3.IListServiceLevelObjectivesRequest, + | protos.google.monitoring.v3.IListServiceLevelObjectivesResponse + | null + | undefined, + protos.google.monitoring.v3.IServiceLevelObjective + >, + ): void; listServiceLevelObjectives( - request?: protos.google.monitoring.v3.IListServiceLevelObjectivesRequest, - optionsOrCallback?: CallOptions|PaginationCallback< + request?: protos.google.monitoring.v3.IListServiceLevelObjectivesRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.monitoring.v3.IListServiceLevelObjectivesRequest, - protos.google.monitoring.v3.IListServiceLevelObjectivesResponse|null|undefined, - protos.google.monitoring.v3.IServiceLevelObjective>, - callback?: PaginationCallback< - protos.google.monitoring.v3.IListServiceLevelObjectivesRequest, - protos.google.monitoring.v3.IListServiceLevelObjectivesResponse|null|undefined, - protos.google.monitoring.v3.IServiceLevelObjective>): - Promise<[ - protos.google.monitoring.v3.IServiceLevelObjective[], - protos.google.monitoring.v3.IListServiceLevelObjectivesRequest|null, - protos.google.monitoring.v3.IListServiceLevelObjectivesResponse - ]>|void { + | protos.google.monitoring.v3.IListServiceLevelObjectivesResponse + | null + | undefined, + protos.google.monitoring.v3.IServiceLevelObjective + >, + callback?: PaginationCallback< + protos.google.monitoring.v3.IListServiceLevelObjectivesRequest, + | protos.google.monitoring.v3.IListServiceLevelObjectivesResponse + | null + | undefined, + protos.google.monitoring.v3.IServiceLevelObjective + >, + ): Promise< + [ + protos.google.monitoring.v3.IServiceLevelObjective[], + protos.google.monitoring.v3.IListServiceLevelObjectivesRequest | null, + protos.google.monitoring.v3.IListServiceLevelObjectivesResponse, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.monitoring.v3.IListServiceLevelObjectivesRequest, - protos.google.monitoring.v3.IListServiceLevelObjectivesResponse|null|undefined, - protos.google.monitoring.v3.IServiceLevelObjective>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.monitoring.v3.IListServiceLevelObjectivesRequest, + | protos.google.monitoring.v3.IListServiceLevelObjectivesResponse + | null + | undefined, + protos.google.monitoring.v3.IServiceLevelObjective + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listServiceLevelObjectives values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -1545,128 +1969,132 @@ export class ServiceMonitoringServiceClient { this._log.info('listServiceLevelObjectives request %j', request); return this.innerApiCalls .listServiceLevelObjectives(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.monitoring.v3.IServiceLevelObjective[], - protos.google.monitoring.v3.IListServiceLevelObjectivesRequest|null, - protos.google.monitoring.v3.IListServiceLevelObjectivesResponse - ]) => { - this._log.info('listServiceLevelObjectives values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.monitoring.v3.IServiceLevelObjective[], + protos.google.monitoring.v3.IListServiceLevelObjectivesRequest | null, + protos.google.monitoring.v3.IListServiceLevelObjectivesResponse, + ]) => { + this._log.info('listServiceLevelObjectives values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listServiceLevelObjectives`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. Resource name of the parent `Service`. - * Of the form `projects/{project_id}/services/{service_id}`. - * @param {string} request.filter - * A filter specifying what `ServiceLevelObjective`s to return. - * @param {number} request.pageSize - * A non-negative number that is the maximum number of results to return. - * When 0, use default page size. - * @param {string} request.pageToken - * If this field is not empty then it must contain the `nextPageToken` value - * returned by a previous call to this method. Using this field causes the - * method to return additional results from the previous method call. - * @param {google.monitoring.v3.ServiceLevelObjective.View} request.view - * View of the `ServiceLevelObjective`s to return. If `DEFAULT`, return each - * `ServiceLevelObjective` as originally defined. If `EXPLICIT` and the - * `ServiceLevelObjective` is defined in terms of a `BasicSli`, replace the - * `BasicSli` with a `RequestBasedSli` spelling out how the SLI is computed. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.monitoring.v3.ServiceLevelObjective|ServiceLevelObjective} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `listServiceLevelObjectivesAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `listServiceLevelObjectives`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Resource name of the parent `Service`. + * Of the form `projects/{project_id}/services/{service_id}`. + * @param {string} request.filter + * A filter specifying what `ServiceLevelObjective`s to return. + * @param {number} request.pageSize + * A non-negative number that is the maximum number of results to return. + * When 0, use default page size. + * @param {string} request.pageToken + * If this field is not empty then it must contain the `nextPageToken` value + * returned by a previous call to this method. Using this field causes the + * method to return additional results from the previous method call. + * @param {google.monitoring.v3.ServiceLevelObjective.View} request.view + * View of the `ServiceLevelObjective`s to return. If `DEFAULT`, return each + * `ServiceLevelObjective` as originally defined. If `EXPLICIT` and the + * `ServiceLevelObjective` is defined in terms of a `BasicSli`, replace the + * `BasicSli` with a `RequestBasedSli` spelling out how the SLI is computed. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.monitoring.v3.ServiceLevelObjective|ServiceLevelObjective} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listServiceLevelObjectivesAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listServiceLevelObjectivesStream( - request?: protos.google.monitoring.v3.IListServiceLevelObjectivesRequest, - options?: CallOptions): - Transform{ + request?: protos.google.monitoring.v3.IListServiceLevelObjectivesRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); const defaultCallSettings = this._defaults['listServiceLevelObjectives']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listServiceLevelObjectives stream %j', request); return this.descriptors.page.listServiceLevelObjectives.createStream( this.innerApiCalls.listServiceLevelObjectives as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listServiceLevelObjectives`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. Resource name of the parent `Service`. - * Of the form `projects/{project_id}/services/{service_id}`. - * @param {string} request.filter - * A filter specifying what `ServiceLevelObjective`s to return. - * @param {number} request.pageSize - * A non-negative number that is the maximum number of results to return. - * When 0, use default page size. - * @param {string} request.pageToken - * If this field is not empty then it must contain the `nextPageToken` value - * returned by a previous call to this method. Using this field causes the - * method to return additional results from the previous method call. - * @param {google.monitoring.v3.ServiceLevelObjective.View} request.view - * View of the `ServiceLevelObjective`s to return. If `DEFAULT`, return each - * `ServiceLevelObjective` as originally defined. If `EXPLICIT` and the - * `ServiceLevelObjective` is defined in terms of a `BasicSli`, replace the - * `BasicSli` with a `RequestBasedSli` spelling out how the SLI is computed. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.monitoring.v3.ServiceLevelObjective|ServiceLevelObjective}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v3/service_monitoring_service.list_service_level_objectives.js - * region_tag:monitoring_v3_generated_ServiceMonitoringService_ListServiceLevelObjectives_async - */ + /** + * Equivalent to `listServiceLevelObjectives`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Resource name of the parent `Service`. + * Of the form `projects/{project_id}/services/{service_id}`. + * @param {string} request.filter + * A filter specifying what `ServiceLevelObjective`s to return. + * @param {number} request.pageSize + * A non-negative number that is the maximum number of results to return. + * When 0, use default page size. + * @param {string} request.pageToken + * If this field is not empty then it must contain the `nextPageToken` value + * returned by a previous call to this method. Using this field causes the + * method to return additional results from the previous method call. + * @param {google.monitoring.v3.ServiceLevelObjective.View} request.view + * View of the `ServiceLevelObjective`s to return. If `DEFAULT`, return each + * `ServiceLevelObjective` as originally defined. If `EXPLICIT` and the + * `ServiceLevelObjective` is defined in terms of a `BasicSli`, replace the + * `BasicSli` with a `RequestBasedSli` spelling out how the SLI is computed. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.monitoring.v3.ServiceLevelObjective|ServiceLevelObjective}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v3/service_monitoring_service.list_service_level_objectives.js + * region_tag:monitoring_v3_generated_ServiceMonitoringService_ListServiceLevelObjectives_async + */ listServiceLevelObjectivesAsync( - request?: protos.google.monitoring.v3.IListServiceLevelObjectivesRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.monitoring.v3.IListServiceLevelObjectivesRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); const defaultCallSettings = this._defaults['listServiceLevelObjectives']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listServiceLevelObjectives iterate %j', request); return this.descriptors.page.listServiceLevelObjectives.asyncIterate( this.innerApiCalls['listServiceLevelObjectives'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } // -------------------- @@ -1680,7 +2108,7 @@ export class ServiceMonitoringServiceClient { * @param {string} alert_policy * @returns {string} Resource name string. */ - folderAlertPolicyPath(folder:string,alertPolicy:string) { + folderAlertPolicyPath(folder: string, alertPolicy: string) { return this.pathTemplates.folderAlertPolicyPathTemplate.render({ folder: folder, alert_policy: alertPolicy, @@ -1695,7 +2123,9 @@ export class ServiceMonitoringServiceClient { * @returns {string} A string representing the folder. */ matchFolderFromFolderAlertPolicyName(folderAlertPolicyName: string) { - return this.pathTemplates.folderAlertPolicyPathTemplate.match(folderAlertPolicyName).folder; + return this.pathTemplates.folderAlertPolicyPathTemplate.match( + folderAlertPolicyName, + ).folder; } /** @@ -1706,7 +2136,9 @@ export class ServiceMonitoringServiceClient { * @returns {string} A string representing the alert_policy. */ matchAlertPolicyFromFolderAlertPolicyName(folderAlertPolicyName: string) { - return this.pathTemplates.folderAlertPolicyPathTemplate.match(folderAlertPolicyName).alert_policy; + return this.pathTemplates.folderAlertPolicyPathTemplate.match( + folderAlertPolicyName, + ).alert_policy; } /** @@ -1717,7 +2149,11 @@ export class ServiceMonitoringServiceClient { * @param {string} condition * @returns {string} Resource name string. */ - folderAlertPolicyConditionPath(folder:string,alertPolicy:string,condition:string) { + folderAlertPolicyConditionPath( + folder: string, + alertPolicy: string, + condition: string, + ) { return this.pathTemplates.folderAlertPolicyConditionPathTemplate.render({ folder: folder, alert_policy: alertPolicy, @@ -1732,8 +2168,12 @@ export class ServiceMonitoringServiceClient { * A fully-qualified path representing folder_alert_policy_condition resource. * @returns {string} A string representing the folder. */ - matchFolderFromFolderAlertPolicyConditionName(folderAlertPolicyConditionName: string) { - return this.pathTemplates.folderAlertPolicyConditionPathTemplate.match(folderAlertPolicyConditionName).folder; + matchFolderFromFolderAlertPolicyConditionName( + folderAlertPolicyConditionName: string, + ) { + return this.pathTemplates.folderAlertPolicyConditionPathTemplate.match( + folderAlertPolicyConditionName, + ).folder; } /** @@ -1743,8 +2183,12 @@ export class ServiceMonitoringServiceClient { * A fully-qualified path representing folder_alert_policy_condition resource. * @returns {string} A string representing the alert_policy. */ - matchAlertPolicyFromFolderAlertPolicyConditionName(folderAlertPolicyConditionName: string) { - return this.pathTemplates.folderAlertPolicyConditionPathTemplate.match(folderAlertPolicyConditionName).alert_policy; + matchAlertPolicyFromFolderAlertPolicyConditionName( + folderAlertPolicyConditionName: string, + ) { + return this.pathTemplates.folderAlertPolicyConditionPathTemplate.match( + folderAlertPolicyConditionName, + ).alert_policy; } /** @@ -1754,8 +2198,12 @@ export class ServiceMonitoringServiceClient { * A fully-qualified path representing folder_alert_policy_condition resource. * @returns {string} A string representing the condition. */ - matchConditionFromFolderAlertPolicyConditionName(folderAlertPolicyConditionName: string) { - return this.pathTemplates.folderAlertPolicyConditionPathTemplate.match(folderAlertPolicyConditionName).condition; + matchConditionFromFolderAlertPolicyConditionName( + folderAlertPolicyConditionName: string, + ) { + return this.pathTemplates.folderAlertPolicyConditionPathTemplate.match( + folderAlertPolicyConditionName, + ).condition; } /** @@ -1765,7 +2213,7 @@ export class ServiceMonitoringServiceClient { * @param {string} channel_descriptor * @returns {string} Resource name string. */ - folderChannelDescriptorPath(folder:string,channelDescriptor:string) { + folderChannelDescriptorPath(folder: string, channelDescriptor: string) { return this.pathTemplates.folderChannelDescriptorPathTemplate.render({ folder: folder, channel_descriptor: channelDescriptor, @@ -1779,8 +2227,12 @@ export class ServiceMonitoringServiceClient { * A fully-qualified path representing folder_channel_descriptor resource. * @returns {string} A string representing the folder. */ - matchFolderFromFolderChannelDescriptorName(folderChannelDescriptorName: string) { - return this.pathTemplates.folderChannelDescriptorPathTemplate.match(folderChannelDescriptorName).folder; + matchFolderFromFolderChannelDescriptorName( + folderChannelDescriptorName: string, + ) { + return this.pathTemplates.folderChannelDescriptorPathTemplate.match( + folderChannelDescriptorName, + ).folder; } /** @@ -1790,8 +2242,12 @@ export class ServiceMonitoringServiceClient { * A fully-qualified path representing folder_channel_descriptor resource. * @returns {string} A string representing the channel_descriptor. */ - matchChannelDescriptorFromFolderChannelDescriptorName(folderChannelDescriptorName: string) { - return this.pathTemplates.folderChannelDescriptorPathTemplate.match(folderChannelDescriptorName).channel_descriptor; + matchChannelDescriptorFromFolderChannelDescriptorName( + folderChannelDescriptorName: string, + ) { + return this.pathTemplates.folderChannelDescriptorPathTemplate.match( + folderChannelDescriptorName, + ).channel_descriptor; } /** @@ -1801,7 +2257,7 @@ export class ServiceMonitoringServiceClient { * @param {string} group * @returns {string} Resource name string. */ - folderGroupPath(folder:string,group:string) { + folderGroupPath(folder: string, group: string) { return this.pathTemplates.folderGroupPathTemplate.render({ folder: folder, group: group, @@ -1816,7 +2272,8 @@ export class ServiceMonitoringServiceClient { * @returns {string} A string representing the folder. */ matchFolderFromFolderGroupName(folderGroupName: string) { - return this.pathTemplates.folderGroupPathTemplate.match(folderGroupName).folder; + return this.pathTemplates.folderGroupPathTemplate.match(folderGroupName) + .folder; } /** @@ -1827,7 +2284,8 @@ export class ServiceMonitoringServiceClient { * @returns {string} A string representing the group. */ matchGroupFromFolderGroupName(folderGroupName: string) { - return this.pathTemplates.folderGroupPathTemplate.match(folderGroupName).group; + return this.pathTemplates.folderGroupPathTemplate.match(folderGroupName) + .group; } /** @@ -1837,7 +2295,7 @@ export class ServiceMonitoringServiceClient { * @param {string} notification_channel * @returns {string} Resource name string. */ - folderNotificationChannelPath(folder:string,notificationChannel:string) { + folderNotificationChannelPath(folder: string, notificationChannel: string) { return this.pathTemplates.folderNotificationChannelPathTemplate.render({ folder: folder, notification_channel: notificationChannel, @@ -1851,8 +2309,12 @@ export class ServiceMonitoringServiceClient { * A fully-qualified path representing folder_notification_channel resource. * @returns {string} A string representing the folder. */ - matchFolderFromFolderNotificationChannelName(folderNotificationChannelName: string) { - return this.pathTemplates.folderNotificationChannelPathTemplate.match(folderNotificationChannelName).folder; + matchFolderFromFolderNotificationChannelName( + folderNotificationChannelName: string, + ) { + return this.pathTemplates.folderNotificationChannelPathTemplate.match( + folderNotificationChannelName, + ).folder; } /** @@ -1862,8 +2324,12 @@ export class ServiceMonitoringServiceClient { * A fully-qualified path representing folder_notification_channel resource. * @returns {string} A string representing the notification_channel. */ - matchNotificationChannelFromFolderNotificationChannelName(folderNotificationChannelName: string) { - return this.pathTemplates.folderNotificationChannelPathTemplate.match(folderNotificationChannelName).notification_channel; + matchNotificationChannelFromFolderNotificationChannelName( + folderNotificationChannelName: string, + ) { + return this.pathTemplates.folderNotificationChannelPathTemplate.match( + folderNotificationChannelName, + ).notification_channel; } /** @@ -1873,7 +2339,7 @@ export class ServiceMonitoringServiceClient { * @param {string} service * @returns {string} Resource name string. */ - folderServicePath(folder:string,service:string) { + folderServicePath(folder: string, service: string) { return this.pathTemplates.folderServicePathTemplate.render({ folder: folder, service: service, @@ -1888,7 +2354,8 @@ export class ServiceMonitoringServiceClient { * @returns {string} A string representing the folder. */ matchFolderFromFolderServiceName(folderServiceName: string) { - return this.pathTemplates.folderServicePathTemplate.match(folderServiceName).folder; + return this.pathTemplates.folderServicePathTemplate.match(folderServiceName) + .folder; } /** @@ -1899,7 +2366,8 @@ export class ServiceMonitoringServiceClient { * @returns {string} A string representing the service. */ matchServiceFromFolderServiceName(folderServiceName: string) { - return this.pathTemplates.folderServicePathTemplate.match(folderServiceName).service; + return this.pathTemplates.folderServicePathTemplate.match(folderServiceName) + .service; } /** @@ -1910,12 +2378,18 @@ export class ServiceMonitoringServiceClient { * @param {string} service_level_objective * @returns {string} Resource name string. */ - folderServiceServiceLevelObjectivePath(folder:string,service:string,serviceLevelObjective:string) { - return this.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.render({ - folder: folder, - service: service, - service_level_objective: serviceLevelObjective, - }); + folderServiceServiceLevelObjectivePath( + folder: string, + service: string, + serviceLevelObjective: string, + ) { + return this.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.render( + { + folder: folder, + service: service, + service_level_objective: serviceLevelObjective, + }, + ); } /** @@ -1925,8 +2399,12 @@ export class ServiceMonitoringServiceClient { * A fully-qualified path representing folder_service_service_level_objective resource. * @returns {string} A string representing the folder. */ - matchFolderFromFolderServiceServiceLevelObjectiveName(folderServiceServiceLevelObjectiveName: string) { - return this.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match(folderServiceServiceLevelObjectiveName).folder; + matchFolderFromFolderServiceServiceLevelObjectiveName( + folderServiceServiceLevelObjectiveName: string, + ) { + return this.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match( + folderServiceServiceLevelObjectiveName, + ).folder; } /** @@ -1936,8 +2414,12 @@ export class ServiceMonitoringServiceClient { * A fully-qualified path representing folder_service_service_level_objective resource. * @returns {string} A string representing the service. */ - matchServiceFromFolderServiceServiceLevelObjectiveName(folderServiceServiceLevelObjectiveName: string) { - return this.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match(folderServiceServiceLevelObjectiveName).service; + matchServiceFromFolderServiceServiceLevelObjectiveName( + folderServiceServiceLevelObjectiveName: string, + ) { + return this.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match( + folderServiceServiceLevelObjectiveName, + ).service; } /** @@ -1947,8 +2429,12 @@ export class ServiceMonitoringServiceClient { * A fully-qualified path representing folder_service_service_level_objective resource. * @returns {string} A string representing the service_level_objective. */ - matchServiceLevelObjectiveFromFolderServiceServiceLevelObjectiveName(folderServiceServiceLevelObjectiveName: string) { - return this.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match(folderServiceServiceLevelObjectiveName).service_level_objective; + matchServiceLevelObjectiveFromFolderServiceServiceLevelObjectiveName( + folderServiceServiceLevelObjectiveName: string, + ) { + return this.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match( + folderServiceServiceLevelObjectiveName, + ).service_level_objective; } /** @@ -1958,7 +2444,7 @@ export class ServiceMonitoringServiceClient { * @param {string} uptime_check_config * @returns {string} Resource name string. */ - folderUptimeCheckConfigPath(folder:string,uptimeCheckConfig:string) { + folderUptimeCheckConfigPath(folder: string, uptimeCheckConfig: string) { return this.pathTemplates.folderUptimeCheckConfigPathTemplate.render({ folder: folder, uptime_check_config: uptimeCheckConfig, @@ -1972,8 +2458,12 @@ export class ServiceMonitoringServiceClient { * A fully-qualified path representing folder_uptime_check_config resource. * @returns {string} A string representing the folder. */ - matchFolderFromFolderUptimeCheckConfigName(folderUptimeCheckConfigName: string) { - return this.pathTemplates.folderUptimeCheckConfigPathTemplate.match(folderUptimeCheckConfigName).folder; + matchFolderFromFolderUptimeCheckConfigName( + folderUptimeCheckConfigName: string, + ) { + return this.pathTemplates.folderUptimeCheckConfigPathTemplate.match( + folderUptimeCheckConfigName, + ).folder; } /** @@ -1983,8 +2473,12 @@ export class ServiceMonitoringServiceClient { * A fully-qualified path representing folder_uptime_check_config resource. * @returns {string} A string representing the uptime_check_config. */ - matchUptimeCheckConfigFromFolderUptimeCheckConfigName(folderUptimeCheckConfigName: string) { - return this.pathTemplates.folderUptimeCheckConfigPathTemplate.match(folderUptimeCheckConfigName).uptime_check_config; + matchUptimeCheckConfigFromFolderUptimeCheckConfigName( + folderUptimeCheckConfigName: string, + ) { + return this.pathTemplates.folderUptimeCheckConfigPathTemplate.match( + folderUptimeCheckConfigName, + ).uptime_check_config; } /** @@ -1994,7 +2488,7 @@ export class ServiceMonitoringServiceClient { * @param {string} alert_policy * @returns {string} Resource name string. */ - organizationAlertPolicyPath(organization:string,alertPolicy:string) { + organizationAlertPolicyPath(organization: string, alertPolicy: string) { return this.pathTemplates.organizationAlertPolicyPathTemplate.render({ organization: organization, alert_policy: alertPolicy, @@ -2008,8 +2502,12 @@ export class ServiceMonitoringServiceClient { * A fully-qualified path representing organization_alert_policy resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationAlertPolicyName(organizationAlertPolicyName: string) { - return this.pathTemplates.organizationAlertPolicyPathTemplate.match(organizationAlertPolicyName).organization; + matchOrganizationFromOrganizationAlertPolicyName( + organizationAlertPolicyName: string, + ) { + return this.pathTemplates.organizationAlertPolicyPathTemplate.match( + organizationAlertPolicyName, + ).organization; } /** @@ -2019,8 +2517,12 @@ export class ServiceMonitoringServiceClient { * A fully-qualified path representing organization_alert_policy resource. * @returns {string} A string representing the alert_policy. */ - matchAlertPolicyFromOrganizationAlertPolicyName(organizationAlertPolicyName: string) { - return this.pathTemplates.organizationAlertPolicyPathTemplate.match(organizationAlertPolicyName).alert_policy; + matchAlertPolicyFromOrganizationAlertPolicyName( + organizationAlertPolicyName: string, + ) { + return this.pathTemplates.organizationAlertPolicyPathTemplate.match( + organizationAlertPolicyName, + ).alert_policy; } /** @@ -2031,12 +2533,18 @@ export class ServiceMonitoringServiceClient { * @param {string} condition * @returns {string} Resource name string. */ - organizationAlertPolicyConditionPath(organization:string,alertPolicy:string,condition:string) { - return this.pathTemplates.organizationAlertPolicyConditionPathTemplate.render({ - organization: organization, - alert_policy: alertPolicy, - condition: condition, - }); + organizationAlertPolicyConditionPath( + organization: string, + alertPolicy: string, + condition: string, + ) { + return this.pathTemplates.organizationAlertPolicyConditionPathTemplate.render( + { + organization: organization, + alert_policy: alertPolicy, + condition: condition, + }, + ); } /** @@ -2046,8 +2554,12 @@ export class ServiceMonitoringServiceClient { * A fully-qualified path representing organization_alert_policy_condition resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationAlertPolicyConditionName(organizationAlertPolicyConditionName: string) { - return this.pathTemplates.organizationAlertPolicyConditionPathTemplate.match(organizationAlertPolicyConditionName).organization; + matchOrganizationFromOrganizationAlertPolicyConditionName( + organizationAlertPolicyConditionName: string, + ) { + return this.pathTemplates.organizationAlertPolicyConditionPathTemplate.match( + organizationAlertPolicyConditionName, + ).organization; } /** @@ -2057,8 +2569,12 @@ export class ServiceMonitoringServiceClient { * A fully-qualified path representing organization_alert_policy_condition resource. * @returns {string} A string representing the alert_policy. */ - matchAlertPolicyFromOrganizationAlertPolicyConditionName(organizationAlertPolicyConditionName: string) { - return this.pathTemplates.organizationAlertPolicyConditionPathTemplate.match(organizationAlertPolicyConditionName).alert_policy; + matchAlertPolicyFromOrganizationAlertPolicyConditionName( + organizationAlertPolicyConditionName: string, + ) { + return this.pathTemplates.organizationAlertPolicyConditionPathTemplate.match( + organizationAlertPolicyConditionName, + ).alert_policy; } /** @@ -2068,8 +2584,12 @@ export class ServiceMonitoringServiceClient { * A fully-qualified path representing organization_alert_policy_condition resource. * @returns {string} A string representing the condition. */ - matchConditionFromOrganizationAlertPolicyConditionName(organizationAlertPolicyConditionName: string) { - return this.pathTemplates.organizationAlertPolicyConditionPathTemplate.match(organizationAlertPolicyConditionName).condition; + matchConditionFromOrganizationAlertPolicyConditionName( + organizationAlertPolicyConditionName: string, + ) { + return this.pathTemplates.organizationAlertPolicyConditionPathTemplate.match( + organizationAlertPolicyConditionName, + ).condition; } /** @@ -2079,7 +2599,10 @@ export class ServiceMonitoringServiceClient { * @param {string} channel_descriptor * @returns {string} Resource name string. */ - organizationChannelDescriptorPath(organization:string,channelDescriptor:string) { + organizationChannelDescriptorPath( + organization: string, + channelDescriptor: string, + ) { return this.pathTemplates.organizationChannelDescriptorPathTemplate.render({ organization: organization, channel_descriptor: channelDescriptor, @@ -2093,8 +2616,12 @@ export class ServiceMonitoringServiceClient { * A fully-qualified path representing organization_channel_descriptor resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationChannelDescriptorName(organizationChannelDescriptorName: string) { - return this.pathTemplates.organizationChannelDescriptorPathTemplate.match(organizationChannelDescriptorName).organization; + matchOrganizationFromOrganizationChannelDescriptorName( + organizationChannelDescriptorName: string, + ) { + return this.pathTemplates.organizationChannelDescriptorPathTemplate.match( + organizationChannelDescriptorName, + ).organization; } /** @@ -2104,8 +2631,12 @@ export class ServiceMonitoringServiceClient { * A fully-qualified path representing organization_channel_descriptor resource. * @returns {string} A string representing the channel_descriptor. */ - matchChannelDescriptorFromOrganizationChannelDescriptorName(organizationChannelDescriptorName: string) { - return this.pathTemplates.organizationChannelDescriptorPathTemplate.match(organizationChannelDescriptorName).channel_descriptor; + matchChannelDescriptorFromOrganizationChannelDescriptorName( + organizationChannelDescriptorName: string, + ) { + return this.pathTemplates.organizationChannelDescriptorPathTemplate.match( + organizationChannelDescriptorName, + ).channel_descriptor; } /** @@ -2115,7 +2646,7 @@ export class ServiceMonitoringServiceClient { * @param {string} group * @returns {string} Resource name string. */ - organizationGroupPath(organization:string,group:string) { + organizationGroupPath(organization: string, group: string) { return this.pathTemplates.organizationGroupPathTemplate.render({ organization: organization, group: group, @@ -2130,7 +2661,9 @@ export class ServiceMonitoringServiceClient { * @returns {string} A string representing the organization. */ matchOrganizationFromOrganizationGroupName(organizationGroupName: string) { - return this.pathTemplates.organizationGroupPathTemplate.match(organizationGroupName).organization; + return this.pathTemplates.organizationGroupPathTemplate.match( + organizationGroupName, + ).organization; } /** @@ -2141,7 +2674,9 @@ export class ServiceMonitoringServiceClient { * @returns {string} A string representing the group. */ matchGroupFromOrganizationGroupName(organizationGroupName: string) { - return this.pathTemplates.organizationGroupPathTemplate.match(organizationGroupName).group; + return this.pathTemplates.organizationGroupPathTemplate.match( + organizationGroupName, + ).group; } /** @@ -2151,11 +2686,16 @@ export class ServiceMonitoringServiceClient { * @param {string} notification_channel * @returns {string} Resource name string. */ - organizationNotificationChannelPath(organization:string,notificationChannel:string) { - return this.pathTemplates.organizationNotificationChannelPathTemplate.render({ - organization: organization, - notification_channel: notificationChannel, - }); + organizationNotificationChannelPath( + organization: string, + notificationChannel: string, + ) { + return this.pathTemplates.organizationNotificationChannelPathTemplate.render( + { + organization: organization, + notification_channel: notificationChannel, + }, + ); } /** @@ -2165,8 +2705,12 @@ export class ServiceMonitoringServiceClient { * A fully-qualified path representing organization_notification_channel resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationNotificationChannelName(organizationNotificationChannelName: string) { - return this.pathTemplates.organizationNotificationChannelPathTemplate.match(organizationNotificationChannelName).organization; + matchOrganizationFromOrganizationNotificationChannelName( + organizationNotificationChannelName: string, + ) { + return this.pathTemplates.organizationNotificationChannelPathTemplate.match( + organizationNotificationChannelName, + ).organization; } /** @@ -2176,8 +2720,12 @@ export class ServiceMonitoringServiceClient { * A fully-qualified path representing organization_notification_channel resource. * @returns {string} A string representing the notification_channel. */ - matchNotificationChannelFromOrganizationNotificationChannelName(organizationNotificationChannelName: string) { - return this.pathTemplates.organizationNotificationChannelPathTemplate.match(organizationNotificationChannelName).notification_channel; + matchNotificationChannelFromOrganizationNotificationChannelName( + organizationNotificationChannelName: string, + ) { + return this.pathTemplates.organizationNotificationChannelPathTemplate.match( + organizationNotificationChannelName, + ).notification_channel; } /** @@ -2187,7 +2735,7 @@ export class ServiceMonitoringServiceClient { * @param {string} service * @returns {string} Resource name string. */ - organizationServicePath(organization:string,service:string) { + organizationServicePath(organization: string, service: string) { return this.pathTemplates.organizationServicePathTemplate.render({ organization: organization, service: service, @@ -2201,8 +2749,12 @@ export class ServiceMonitoringServiceClient { * A fully-qualified path representing organization_service resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationServiceName(organizationServiceName: string) { - return this.pathTemplates.organizationServicePathTemplate.match(organizationServiceName).organization; + matchOrganizationFromOrganizationServiceName( + organizationServiceName: string, + ) { + return this.pathTemplates.organizationServicePathTemplate.match( + organizationServiceName, + ).organization; } /** @@ -2213,7 +2765,9 @@ export class ServiceMonitoringServiceClient { * @returns {string} A string representing the service. */ matchServiceFromOrganizationServiceName(organizationServiceName: string) { - return this.pathTemplates.organizationServicePathTemplate.match(organizationServiceName).service; + return this.pathTemplates.organizationServicePathTemplate.match( + organizationServiceName, + ).service; } /** @@ -2224,12 +2778,18 @@ export class ServiceMonitoringServiceClient { * @param {string} service_level_objective * @returns {string} Resource name string. */ - organizationServiceServiceLevelObjectivePath(organization:string,service:string,serviceLevelObjective:string) { - return this.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.render({ - organization: organization, - service: service, - service_level_objective: serviceLevelObjective, - }); + organizationServiceServiceLevelObjectivePath( + organization: string, + service: string, + serviceLevelObjective: string, + ) { + return this.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.render( + { + organization: organization, + service: service, + service_level_objective: serviceLevelObjective, + }, + ); } /** @@ -2239,8 +2799,12 @@ export class ServiceMonitoringServiceClient { * A fully-qualified path representing organization_service_service_level_objective resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationServiceServiceLevelObjectiveName(organizationServiceServiceLevelObjectiveName: string) { - return this.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match(organizationServiceServiceLevelObjectiveName).organization; + matchOrganizationFromOrganizationServiceServiceLevelObjectiveName( + organizationServiceServiceLevelObjectiveName: string, + ) { + return this.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match( + organizationServiceServiceLevelObjectiveName, + ).organization; } /** @@ -2250,8 +2814,12 @@ export class ServiceMonitoringServiceClient { * A fully-qualified path representing organization_service_service_level_objective resource. * @returns {string} A string representing the service. */ - matchServiceFromOrganizationServiceServiceLevelObjectiveName(organizationServiceServiceLevelObjectiveName: string) { - return this.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match(organizationServiceServiceLevelObjectiveName).service; + matchServiceFromOrganizationServiceServiceLevelObjectiveName( + organizationServiceServiceLevelObjectiveName: string, + ) { + return this.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match( + organizationServiceServiceLevelObjectiveName, + ).service; } /** @@ -2261,8 +2829,12 @@ export class ServiceMonitoringServiceClient { * A fully-qualified path representing organization_service_service_level_objective resource. * @returns {string} A string representing the service_level_objective. */ - matchServiceLevelObjectiveFromOrganizationServiceServiceLevelObjectiveName(organizationServiceServiceLevelObjectiveName: string) { - return this.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match(organizationServiceServiceLevelObjectiveName).service_level_objective; + matchServiceLevelObjectiveFromOrganizationServiceServiceLevelObjectiveName( + organizationServiceServiceLevelObjectiveName: string, + ) { + return this.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match( + organizationServiceServiceLevelObjectiveName, + ).service_level_objective; } /** @@ -2272,7 +2844,10 @@ export class ServiceMonitoringServiceClient { * @param {string} uptime_check_config * @returns {string} Resource name string. */ - organizationUptimeCheckConfigPath(organization:string,uptimeCheckConfig:string) { + organizationUptimeCheckConfigPath( + organization: string, + uptimeCheckConfig: string, + ) { return this.pathTemplates.organizationUptimeCheckConfigPathTemplate.render({ organization: organization, uptime_check_config: uptimeCheckConfig, @@ -2286,8 +2861,12 @@ export class ServiceMonitoringServiceClient { * A fully-qualified path representing organization_uptime_check_config resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationUptimeCheckConfigName(organizationUptimeCheckConfigName: string) { - return this.pathTemplates.organizationUptimeCheckConfigPathTemplate.match(organizationUptimeCheckConfigName).organization; + matchOrganizationFromOrganizationUptimeCheckConfigName( + organizationUptimeCheckConfigName: string, + ) { + return this.pathTemplates.organizationUptimeCheckConfigPathTemplate.match( + organizationUptimeCheckConfigName, + ).organization; } /** @@ -2297,8 +2876,12 @@ export class ServiceMonitoringServiceClient { * A fully-qualified path representing organization_uptime_check_config resource. * @returns {string} A string representing the uptime_check_config. */ - matchUptimeCheckConfigFromOrganizationUptimeCheckConfigName(organizationUptimeCheckConfigName: string) { - return this.pathTemplates.organizationUptimeCheckConfigPathTemplate.match(organizationUptimeCheckConfigName).uptime_check_config; + matchUptimeCheckConfigFromOrganizationUptimeCheckConfigName( + organizationUptimeCheckConfigName: string, + ) { + return this.pathTemplates.organizationUptimeCheckConfigPathTemplate.match( + organizationUptimeCheckConfigName, + ).uptime_check_config; } /** @@ -2308,7 +2891,7 @@ export class ServiceMonitoringServiceClient { * @param {string} alert_policy * @returns {string} Resource name string. */ - projectAlertPolicyPath(project:string,alertPolicy:string) { + projectAlertPolicyPath(project: string, alertPolicy: string) { return this.pathTemplates.projectAlertPolicyPathTemplate.render({ project: project, alert_policy: alertPolicy, @@ -2323,7 +2906,9 @@ export class ServiceMonitoringServiceClient { * @returns {string} A string representing the project. */ matchProjectFromProjectAlertPolicyName(projectAlertPolicyName: string) { - return this.pathTemplates.projectAlertPolicyPathTemplate.match(projectAlertPolicyName).project; + return this.pathTemplates.projectAlertPolicyPathTemplate.match( + projectAlertPolicyName, + ).project; } /** @@ -2334,7 +2919,9 @@ export class ServiceMonitoringServiceClient { * @returns {string} A string representing the alert_policy. */ matchAlertPolicyFromProjectAlertPolicyName(projectAlertPolicyName: string) { - return this.pathTemplates.projectAlertPolicyPathTemplate.match(projectAlertPolicyName).alert_policy; + return this.pathTemplates.projectAlertPolicyPathTemplate.match( + projectAlertPolicyName, + ).alert_policy; } /** @@ -2345,7 +2932,11 @@ export class ServiceMonitoringServiceClient { * @param {string} condition * @returns {string} Resource name string. */ - projectAlertPolicyConditionPath(project:string,alertPolicy:string,condition:string) { + projectAlertPolicyConditionPath( + project: string, + alertPolicy: string, + condition: string, + ) { return this.pathTemplates.projectAlertPolicyConditionPathTemplate.render({ project: project, alert_policy: alertPolicy, @@ -2360,8 +2951,12 @@ export class ServiceMonitoringServiceClient { * A fully-qualified path representing project_alert_policy_condition resource. * @returns {string} A string representing the project. */ - matchProjectFromProjectAlertPolicyConditionName(projectAlertPolicyConditionName: string) { - return this.pathTemplates.projectAlertPolicyConditionPathTemplate.match(projectAlertPolicyConditionName).project; + matchProjectFromProjectAlertPolicyConditionName( + projectAlertPolicyConditionName: string, + ) { + return this.pathTemplates.projectAlertPolicyConditionPathTemplate.match( + projectAlertPolicyConditionName, + ).project; } /** @@ -2371,8 +2966,12 @@ export class ServiceMonitoringServiceClient { * A fully-qualified path representing project_alert_policy_condition resource. * @returns {string} A string representing the alert_policy. */ - matchAlertPolicyFromProjectAlertPolicyConditionName(projectAlertPolicyConditionName: string) { - return this.pathTemplates.projectAlertPolicyConditionPathTemplate.match(projectAlertPolicyConditionName).alert_policy; + matchAlertPolicyFromProjectAlertPolicyConditionName( + projectAlertPolicyConditionName: string, + ) { + return this.pathTemplates.projectAlertPolicyConditionPathTemplate.match( + projectAlertPolicyConditionName, + ).alert_policy; } /** @@ -2382,8 +2981,12 @@ export class ServiceMonitoringServiceClient { * A fully-qualified path representing project_alert_policy_condition resource. * @returns {string} A string representing the condition. */ - matchConditionFromProjectAlertPolicyConditionName(projectAlertPolicyConditionName: string) { - return this.pathTemplates.projectAlertPolicyConditionPathTemplate.match(projectAlertPolicyConditionName).condition; + matchConditionFromProjectAlertPolicyConditionName( + projectAlertPolicyConditionName: string, + ) { + return this.pathTemplates.projectAlertPolicyConditionPathTemplate.match( + projectAlertPolicyConditionName, + ).condition; } /** @@ -2393,7 +2996,7 @@ export class ServiceMonitoringServiceClient { * @param {string} channel_descriptor * @returns {string} Resource name string. */ - projectChannelDescriptorPath(project:string,channelDescriptor:string) { + projectChannelDescriptorPath(project: string, channelDescriptor: string) { return this.pathTemplates.projectChannelDescriptorPathTemplate.render({ project: project, channel_descriptor: channelDescriptor, @@ -2407,8 +3010,12 @@ export class ServiceMonitoringServiceClient { * A fully-qualified path representing project_channel_descriptor resource. * @returns {string} A string representing the project. */ - matchProjectFromProjectChannelDescriptorName(projectChannelDescriptorName: string) { - return this.pathTemplates.projectChannelDescriptorPathTemplate.match(projectChannelDescriptorName).project; + matchProjectFromProjectChannelDescriptorName( + projectChannelDescriptorName: string, + ) { + return this.pathTemplates.projectChannelDescriptorPathTemplate.match( + projectChannelDescriptorName, + ).project; } /** @@ -2418,8 +3025,12 @@ export class ServiceMonitoringServiceClient { * A fully-qualified path representing project_channel_descriptor resource. * @returns {string} A string representing the channel_descriptor. */ - matchChannelDescriptorFromProjectChannelDescriptorName(projectChannelDescriptorName: string) { - return this.pathTemplates.projectChannelDescriptorPathTemplate.match(projectChannelDescriptorName).channel_descriptor; + matchChannelDescriptorFromProjectChannelDescriptorName( + projectChannelDescriptorName: string, + ) { + return this.pathTemplates.projectChannelDescriptorPathTemplate.match( + projectChannelDescriptorName, + ).channel_descriptor; } /** @@ -2429,7 +3040,7 @@ export class ServiceMonitoringServiceClient { * @param {string} group * @returns {string} Resource name string. */ - projectGroupPath(project:string,group:string) { + projectGroupPath(project: string, group: string) { return this.pathTemplates.projectGroupPathTemplate.render({ project: project, group: group, @@ -2444,7 +3055,8 @@ export class ServiceMonitoringServiceClient { * @returns {string} A string representing the project. */ matchProjectFromProjectGroupName(projectGroupName: string) { - return this.pathTemplates.projectGroupPathTemplate.match(projectGroupName).project; + return this.pathTemplates.projectGroupPathTemplate.match(projectGroupName) + .project; } /** @@ -2455,7 +3067,8 @@ export class ServiceMonitoringServiceClient { * @returns {string} A string representing the group. */ matchGroupFromProjectGroupName(projectGroupName: string) { - return this.pathTemplates.projectGroupPathTemplate.match(projectGroupName).group; + return this.pathTemplates.projectGroupPathTemplate.match(projectGroupName) + .group; } /** @@ -2465,7 +3078,7 @@ export class ServiceMonitoringServiceClient { * @param {string} notification_channel * @returns {string} Resource name string. */ - projectNotificationChannelPath(project:string,notificationChannel:string) { + projectNotificationChannelPath(project: string, notificationChannel: string) { return this.pathTemplates.projectNotificationChannelPathTemplate.render({ project: project, notification_channel: notificationChannel, @@ -2479,8 +3092,12 @@ export class ServiceMonitoringServiceClient { * A fully-qualified path representing project_notification_channel resource. * @returns {string} A string representing the project. */ - matchProjectFromProjectNotificationChannelName(projectNotificationChannelName: string) { - return this.pathTemplates.projectNotificationChannelPathTemplate.match(projectNotificationChannelName).project; + matchProjectFromProjectNotificationChannelName( + projectNotificationChannelName: string, + ) { + return this.pathTemplates.projectNotificationChannelPathTemplate.match( + projectNotificationChannelName, + ).project; } /** @@ -2490,8 +3107,12 @@ export class ServiceMonitoringServiceClient { * A fully-qualified path representing project_notification_channel resource. * @returns {string} A string representing the notification_channel. */ - matchNotificationChannelFromProjectNotificationChannelName(projectNotificationChannelName: string) { - return this.pathTemplates.projectNotificationChannelPathTemplate.match(projectNotificationChannelName).notification_channel; + matchNotificationChannelFromProjectNotificationChannelName( + projectNotificationChannelName: string, + ) { + return this.pathTemplates.projectNotificationChannelPathTemplate.match( + projectNotificationChannelName, + ).notification_channel; } /** @@ -2501,7 +3122,7 @@ export class ServiceMonitoringServiceClient { * @param {string} service * @returns {string} Resource name string. */ - projectServicePath(project:string,service:string) { + projectServicePath(project: string, service: string) { return this.pathTemplates.projectServicePathTemplate.render({ project: project, service: service, @@ -2516,7 +3137,9 @@ export class ServiceMonitoringServiceClient { * @returns {string} A string representing the project. */ matchProjectFromProjectServiceName(projectServiceName: string) { - return this.pathTemplates.projectServicePathTemplate.match(projectServiceName).project; + return this.pathTemplates.projectServicePathTemplate.match( + projectServiceName, + ).project; } /** @@ -2527,7 +3150,9 @@ export class ServiceMonitoringServiceClient { * @returns {string} A string representing the service. */ matchServiceFromProjectServiceName(projectServiceName: string) { - return this.pathTemplates.projectServicePathTemplate.match(projectServiceName).service; + return this.pathTemplates.projectServicePathTemplate.match( + projectServiceName, + ).service; } /** @@ -2538,12 +3163,18 @@ export class ServiceMonitoringServiceClient { * @param {string} service_level_objective * @returns {string} Resource name string. */ - projectServiceServiceLevelObjectivePath(project:string,service:string,serviceLevelObjective:string) { - return this.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.render({ - project: project, - service: service, - service_level_objective: serviceLevelObjective, - }); + projectServiceServiceLevelObjectivePath( + project: string, + service: string, + serviceLevelObjective: string, + ) { + return this.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.render( + { + project: project, + service: service, + service_level_objective: serviceLevelObjective, + }, + ); } /** @@ -2553,8 +3184,12 @@ export class ServiceMonitoringServiceClient { * A fully-qualified path representing project_service_service_level_objective resource. * @returns {string} A string representing the project. */ - matchProjectFromProjectServiceServiceLevelObjectiveName(projectServiceServiceLevelObjectiveName: string) { - return this.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match(projectServiceServiceLevelObjectiveName).project; + matchProjectFromProjectServiceServiceLevelObjectiveName( + projectServiceServiceLevelObjectiveName: string, + ) { + return this.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match( + projectServiceServiceLevelObjectiveName, + ).project; } /** @@ -2564,8 +3199,12 @@ export class ServiceMonitoringServiceClient { * A fully-qualified path representing project_service_service_level_objective resource. * @returns {string} A string representing the service. */ - matchServiceFromProjectServiceServiceLevelObjectiveName(projectServiceServiceLevelObjectiveName: string) { - return this.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match(projectServiceServiceLevelObjectiveName).service; + matchServiceFromProjectServiceServiceLevelObjectiveName( + projectServiceServiceLevelObjectiveName: string, + ) { + return this.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match( + projectServiceServiceLevelObjectiveName, + ).service; } /** @@ -2575,8 +3214,12 @@ export class ServiceMonitoringServiceClient { * A fully-qualified path representing project_service_service_level_objective resource. * @returns {string} A string representing the service_level_objective. */ - matchServiceLevelObjectiveFromProjectServiceServiceLevelObjectiveName(projectServiceServiceLevelObjectiveName: string) { - return this.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match(projectServiceServiceLevelObjectiveName).service_level_objective; + matchServiceLevelObjectiveFromProjectServiceServiceLevelObjectiveName( + projectServiceServiceLevelObjectiveName: string, + ) { + return this.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match( + projectServiceServiceLevelObjectiveName, + ).service_level_objective; } /** @@ -2586,7 +3229,7 @@ export class ServiceMonitoringServiceClient { * @param {string} uptime_check_config * @returns {string} Resource name string. */ - projectUptimeCheckConfigPath(project:string,uptimeCheckConfig:string) { + projectUptimeCheckConfigPath(project: string, uptimeCheckConfig: string) { return this.pathTemplates.projectUptimeCheckConfigPathTemplate.render({ project: project, uptime_check_config: uptimeCheckConfig, @@ -2600,8 +3243,12 @@ export class ServiceMonitoringServiceClient { * A fully-qualified path representing project_uptime_check_config resource. * @returns {string} A string representing the project. */ - matchProjectFromProjectUptimeCheckConfigName(projectUptimeCheckConfigName: string) { - return this.pathTemplates.projectUptimeCheckConfigPathTemplate.match(projectUptimeCheckConfigName).project; + matchProjectFromProjectUptimeCheckConfigName( + projectUptimeCheckConfigName: string, + ) { + return this.pathTemplates.projectUptimeCheckConfigPathTemplate.match( + projectUptimeCheckConfigName, + ).project; } /** @@ -2611,8 +3258,12 @@ export class ServiceMonitoringServiceClient { * A fully-qualified path representing project_uptime_check_config resource. * @returns {string} A string representing the uptime_check_config. */ - matchUptimeCheckConfigFromProjectUptimeCheckConfigName(projectUptimeCheckConfigName: string) { - return this.pathTemplates.projectUptimeCheckConfigPathTemplate.match(projectUptimeCheckConfigName).uptime_check_config; + matchUptimeCheckConfigFromProjectUptimeCheckConfigName( + projectUptimeCheckConfigName: string, + ) { + return this.pathTemplates.projectUptimeCheckConfigPathTemplate.match( + projectUptimeCheckConfigName, + ).uptime_check_config; } /** @@ -2623,7 +3274,7 @@ export class ServiceMonitoringServiceClient { */ close(): Promise { if (this.serviceMonitoringServiceStub && !this._terminated) { - return this.serviceMonitoringServiceStub.then(stub => { + return this.serviceMonitoringServiceStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -2631,4 +3282,4 @@ export class ServiceMonitoringServiceClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/core/generator/gapic-generator-typescript/baselines/monitoring/src/v3/uptime_check_service_client.ts.baseline b/core/generator/gapic-generator-typescript/baselines/monitoring/src/v3/uptime_check_service_client.ts.baseline index 2b817761223a..6632352f4357 100644 --- a/core/generator/gapic-generator-typescript/baselines/monitoring/src/v3/uptime_check_service_client.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/monitoring/src/v3/uptime_check_service_client.ts.baseline @@ -18,11 +18,18 @@ /* global window */ import type * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions, PaginationCallback, GaxCall} from 'google-gax'; -import {Transform} from 'stream'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + PaginationCallback, + GaxCall, +} from 'google-gax'; +import { Transform } from 'stream'; import * as protos from '../../protos/protos'; import jsonProtos = require('../../protos/protos.json'); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; /** * Client JSON configuration object, loaded from @@ -51,7 +58,7 @@ export class UptimeCheckServiceClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('monitoring'); @@ -64,9 +71,9 @@ export class UptimeCheckServiceClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; - uptimeCheckServiceStub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; + uptimeCheckServiceStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of UptimeCheckServiceClient. @@ -107,21 +114,42 @@ export class UptimeCheckServiceClient { * const client = new UptimeCheckServiceClient({fallback: true}, gax); * ``` */ - constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { // Ensure that options include all the required fields. const staticMembers = this.constructor as typeof UptimeCheckServiceClient; - if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { - throw new Error('Please set either universe_domain or universeDomain, but not both.'); + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); } - const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; - this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; this._servicePath = 'monitoring.' + this._universeDomain; - const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; - const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. if (servicePath !== this._servicePath && !('scopes' in opts)) { @@ -143,7 +171,7 @@ export class UptimeCheckServiceClient { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; @@ -157,10 +185,7 @@ export class UptimeCheckServiceClient { } // Determine the client header string. - const clientHeader = [ - `gax/${this._gaxModule.version}`, - `gapic/${version}`, - ]; + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/${process.versions.node}`); } else { @@ -182,76 +207,83 @@ export class UptimeCheckServiceClient { // Create useful helper objects for these. this.pathTemplates = { folderAlertPolicyPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/alertPolicies/{alert_policy}' + 'folders/{folder}/alertPolicies/{alert_policy}', ), folderAlertPolicyConditionPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/alertPolicies/{alert_policy}/conditions/{condition}' + 'folders/{folder}/alertPolicies/{alert_policy}/conditions/{condition}', ), folderChannelDescriptorPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/notificationChannelDescriptors/{channel_descriptor}' + 'folders/{folder}/notificationChannelDescriptors/{channel_descriptor}', ), folderGroupPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/groups/{group}' + 'folders/{folder}/groups/{group}', ), folderNotificationChannelPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/notificationChannels/{notification_channel}' + 'folders/{folder}/notificationChannels/{notification_channel}', ), folderServicePathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/services/{service}' - ), - folderServiceServiceLevelObjectivePathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/services/{service}/serviceLevelObjectives/{service_level_objective}' + 'folders/{folder}/services/{service}', ), + folderServiceServiceLevelObjectivePathTemplate: + new this._gaxModule.PathTemplate( + 'folders/{folder}/services/{service}/serviceLevelObjectives/{service_level_objective}', + ), folderUptimeCheckConfigPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/uptimeCheckConfigs/{uptime_check_config}' + 'folders/{folder}/uptimeCheckConfigs/{uptime_check_config}', ), organizationAlertPolicyPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/alertPolicies/{alert_policy}' - ), - organizationAlertPolicyConditionPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/alertPolicies/{alert_policy}/conditions/{condition}' - ), - organizationChannelDescriptorPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/notificationChannelDescriptors/{channel_descriptor}' + 'organizations/{organization}/alertPolicies/{alert_policy}', ), + organizationAlertPolicyConditionPathTemplate: + new this._gaxModule.PathTemplate( + 'organizations/{organization}/alertPolicies/{alert_policy}/conditions/{condition}', + ), + organizationChannelDescriptorPathTemplate: + new this._gaxModule.PathTemplate( + 'organizations/{organization}/notificationChannelDescriptors/{channel_descriptor}', + ), organizationGroupPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/groups/{group}' - ), - organizationNotificationChannelPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/notificationChannels/{notification_channel}' + 'organizations/{organization}/groups/{group}', ), + organizationNotificationChannelPathTemplate: + new this._gaxModule.PathTemplate( + 'organizations/{organization}/notificationChannels/{notification_channel}', + ), organizationServicePathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/services/{service}' - ), - organizationServiceServiceLevelObjectivePathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/services/{service}/serviceLevelObjectives/{service_level_objective}' - ), - organizationUptimeCheckConfigPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/uptimeCheckConfigs/{uptime_check_config}' + 'organizations/{organization}/services/{service}', ), + organizationServiceServiceLevelObjectivePathTemplate: + new this._gaxModule.PathTemplate( + 'organizations/{organization}/services/{service}/serviceLevelObjectives/{service_level_objective}', + ), + organizationUptimeCheckConfigPathTemplate: + new this._gaxModule.PathTemplate( + 'organizations/{organization}/uptimeCheckConfigs/{uptime_check_config}', + ), projectAlertPolicyPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/alertPolicies/{alert_policy}' + 'projects/{project}/alertPolicies/{alert_policy}', ), projectAlertPolicyConditionPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/alertPolicies/{alert_policy}/conditions/{condition}' + 'projects/{project}/alertPolicies/{alert_policy}/conditions/{condition}', ), projectChannelDescriptorPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/notificationChannelDescriptors/{channel_descriptor}' + 'projects/{project}/notificationChannelDescriptors/{channel_descriptor}', ), projectGroupPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/groups/{group}' + 'projects/{project}/groups/{group}', ), projectNotificationChannelPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/notificationChannels/{notification_channel}' + 'projects/{project}/notificationChannels/{notification_channel}', ), projectServicePathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/services/{service}' - ), - projectServiceServiceLevelObjectivePathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/services/{service}/serviceLevelObjectives/{service_level_objective}' + 'projects/{project}/services/{service}', ), + projectServiceServiceLevelObjectivePathTemplate: + new this._gaxModule.PathTemplate( + 'projects/{project}/services/{service}/serviceLevelObjectives/{service_level_objective}', + ), projectUptimeCheckConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/uptimeCheckConfigs/{uptime_check_config}' + 'projects/{project}/uptimeCheckConfigs/{uptime_check_config}', ), }; @@ -259,16 +291,25 @@ export class UptimeCheckServiceClient { // (e.g. 50 results at a time, with tokens to get subsequent // pages). Denote the keys used for pagination and results. this.descriptors.page = { - listUptimeCheckConfigs: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'uptimeCheckConfigs'), - listUptimeCheckIps: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'uptimeCheckIps') + listUptimeCheckConfigs: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'uptimeCheckConfigs', + ), + listUptimeCheckIps: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'uptimeCheckIps', + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.monitoring.v3.UptimeCheckService', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.monitoring.v3.UptimeCheckService', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + { 'x-goog-api-client': clientHeader.join(' ') }, + ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -299,37 +340,47 @@ export class UptimeCheckServiceClient { // Put together the "service stub" for // google.monitoring.v3.UptimeCheckService. this.uptimeCheckServiceStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.monitoring.v3.UptimeCheckService') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.monitoring.v3.UptimeCheckService', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.monitoring.v3.UptimeCheckService, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts, + this._providedCustomServicePath, + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const uptimeCheckServiceStubMethods = - ['listUptimeCheckConfigs', 'getUptimeCheckConfig', 'createUptimeCheckConfig', 'updateUptimeCheckConfig', 'deleteUptimeCheckConfig', 'listUptimeCheckIps']; + const uptimeCheckServiceStubMethods = [ + 'listUptimeCheckConfigs', + 'getUptimeCheckConfig', + 'createUptimeCheckConfig', + 'updateUptimeCheckConfig', + 'deleteUptimeCheckConfig', + 'listUptimeCheckIps', + ]; for (const methodName of uptimeCheckServiceStubMethods) { const callPromise = this.uptimeCheckServiceStub.then( - stub => (...args: Array<{}>) => { - if (this._terminated) { - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error|null|undefined) => () => { + (stub) => + (...args: Array<{}>) => { + if (this._terminated) { + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { throw err; - }); + }, + ); - const descriptor = - this.descriptors.page[methodName] || - undefined; + const descriptor = this.descriptors.page[methodName] || undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -344,8 +395,14 @@ export class UptimeCheckServiceClient { * @returns {string} The DNS address for this service. */ static get servicePath() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'monitoring.googleapis.com'; } @@ -356,8 +413,14 @@ export class UptimeCheckServiceClient { * @returns {string} The DNS address for this service. */ static get apiEndpoint() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'monitoring.googleapis.com'; } @@ -391,7 +454,7 @@ export class UptimeCheckServiceClient { return [ 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/monitoring', - 'https://www.googleapis.com/auth/monitoring.read' + 'https://www.googleapis.com/auth/monitoring.read', ]; } @@ -401,8 +464,9 @@ export class UptimeCheckServiceClient { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId(callback?: Callback): - Promise|void { + getProjectId( + callback?: Callback, + ): Promise | void { if (callback) { this.auth.getProjectId(callback); return; @@ -413,496 +477,690 @@ export class UptimeCheckServiceClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Gets a single Uptime check configuration. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The Uptime check configuration to retrieve. The format - * is `projects/[PROJECT_ID]/uptimeCheckConfigs/[UPTIME_CHECK_ID]`. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.monitoring.v3.UptimeCheckConfig|UptimeCheckConfig}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v3/uptime_check_service.get_uptime_check_config.js - * region_tag:monitoring_v3_generated_UptimeCheckService_GetUptimeCheckConfig_async - */ + /** + * Gets a single Uptime check configuration. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The Uptime check configuration to retrieve. The format + * is `projects/[PROJECT_ID]/uptimeCheckConfigs/[UPTIME_CHECK_ID]`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.monitoring.v3.UptimeCheckConfig|UptimeCheckConfig}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v3/uptime_check_service.get_uptime_check_config.js + * region_tag:monitoring_v3_generated_UptimeCheckService_GetUptimeCheckConfig_async + */ getUptimeCheckConfig( - request?: protos.google.monitoring.v3.IGetUptimeCheckConfigRequest, - options?: CallOptions): - Promise<[ - protos.google.monitoring.v3.IUptimeCheckConfig, - protos.google.monitoring.v3.IGetUptimeCheckConfigRequest|undefined, {}|undefined - ]>; + request?: protos.google.monitoring.v3.IGetUptimeCheckConfigRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.monitoring.v3.IUptimeCheckConfig, + protos.google.monitoring.v3.IGetUptimeCheckConfigRequest | undefined, + {} | undefined, + ] + >; getUptimeCheckConfig( - request: protos.google.monitoring.v3.IGetUptimeCheckConfigRequest, - options: CallOptions, - callback: Callback< - protos.google.monitoring.v3.IUptimeCheckConfig, - protos.google.monitoring.v3.IGetUptimeCheckConfigRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.IGetUptimeCheckConfigRequest, + options: CallOptions, + callback: Callback< + protos.google.monitoring.v3.IUptimeCheckConfig, + | protos.google.monitoring.v3.IGetUptimeCheckConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getUptimeCheckConfig( - request: protos.google.monitoring.v3.IGetUptimeCheckConfigRequest, - callback: Callback< - protos.google.monitoring.v3.IUptimeCheckConfig, - protos.google.monitoring.v3.IGetUptimeCheckConfigRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.IGetUptimeCheckConfigRequest, + callback: Callback< + protos.google.monitoring.v3.IUptimeCheckConfig, + | protos.google.monitoring.v3.IGetUptimeCheckConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getUptimeCheckConfig( - request?: protos.google.monitoring.v3.IGetUptimeCheckConfigRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.monitoring.v3.IGetUptimeCheckConfigRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.monitoring.v3.IUptimeCheckConfig, - protos.google.monitoring.v3.IGetUptimeCheckConfigRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.monitoring.v3.IUptimeCheckConfig, - protos.google.monitoring.v3.IGetUptimeCheckConfigRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.monitoring.v3.IUptimeCheckConfig, - protos.google.monitoring.v3.IGetUptimeCheckConfigRequest|undefined, {}|undefined - ]>|void { + | protos.google.monitoring.v3.IGetUptimeCheckConfigRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.monitoring.v3.IUptimeCheckConfig, + | protos.google.monitoring.v3.IGetUptimeCheckConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.monitoring.v3.IUptimeCheckConfig, + protos.google.monitoring.v3.IGetUptimeCheckConfigRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getUptimeCheckConfig request %j', request); - const wrappedCallback: Callback< - protos.google.monitoring.v3.IUptimeCheckConfig, - protos.google.monitoring.v3.IGetUptimeCheckConfigRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.monitoring.v3.IUptimeCheckConfig, + | protos.google.monitoring.v3.IGetUptimeCheckConfigRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getUptimeCheckConfig response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getUptimeCheckConfig(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.monitoring.v3.IUptimeCheckConfig, - protos.google.monitoring.v3.IGetUptimeCheckConfigRequest|undefined, - {}|undefined - ]) => { - this._log.info('getUptimeCheckConfig response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getUptimeCheckConfig(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.monitoring.v3.IUptimeCheckConfig, + protos.google.monitoring.v3.IGetUptimeCheckConfigRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getUptimeCheckConfig response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Creates a new Uptime check configuration. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The project in which to create the Uptime check. The format - * is `projects/[PROJECT_ID]`. - * @param {google.monitoring.v3.UptimeCheckConfig} request.uptimeCheckConfig - * Required. The new Uptime check configuration. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.monitoring.v3.UptimeCheckConfig|UptimeCheckConfig}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v3/uptime_check_service.create_uptime_check_config.js - * region_tag:monitoring_v3_generated_UptimeCheckService_CreateUptimeCheckConfig_async - */ + /** + * Creates a new Uptime check configuration. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The project in which to create the Uptime check. The format + * is `projects/[PROJECT_ID]`. + * @param {google.monitoring.v3.UptimeCheckConfig} request.uptimeCheckConfig + * Required. The new Uptime check configuration. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.monitoring.v3.UptimeCheckConfig|UptimeCheckConfig}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v3/uptime_check_service.create_uptime_check_config.js + * region_tag:monitoring_v3_generated_UptimeCheckService_CreateUptimeCheckConfig_async + */ createUptimeCheckConfig( - request?: protos.google.monitoring.v3.ICreateUptimeCheckConfigRequest, - options?: CallOptions): - Promise<[ - protos.google.monitoring.v3.IUptimeCheckConfig, - protos.google.monitoring.v3.ICreateUptimeCheckConfigRequest|undefined, {}|undefined - ]>; + request?: protos.google.monitoring.v3.ICreateUptimeCheckConfigRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.monitoring.v3.IUptimeCheckConfig, + protos.google.monitoring.v3.ICreateUptimeCheckConfigRequest | undefined, + {} | undefined, + ] + >; createUptimeCheckConfig( - request: protos.google.monitoring.v3.ICreateUptimeCheckConfigRequest, - options: CallOptions, - callback: Callback< - protos.google.monitoring.v3.IUptimeCheckConfig, - protos.google.monitoring.v3.ICreateUptimeCheckConfigRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.ICreateUptimeCheckConfigRequest, + options: CallOptions, + callback: Callback< + protos.google.monitoring.v3.IUptimeCheckConfig, + | protos.google.monitoring.v3.ICreateUptimeCheckConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createUptimeCheckConfig( - request: protos.google.monitoring.v3.ICreateUptimeCheckConfigRequest, - callback: Callback< - protos.google.monitoring.v3.IUptimeCheckConfig, - protos.google.monitoring.v3.ICreateUptimeCheckConfigRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.ICreateUptimeCheckConfigRequest, + callback: Callback< + protos.google.monitoring.v3.IUptimeCheckConfig, + | protos.google.monitoring.v3.ICreateUptimeCheckConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createUptimeCheckConfig( - request?: protos.google.monitoring.v3.ICreateUptimeCheckConfigRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.monitoring.v3.ICreateUptimeCheckConfigRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.monitoring.v3.IUptimeCheckConfig, - protos.google.monitoring.v3.ICreateUptimeCheckConfigRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.monitoring.v3.IUptimeCheckConfig, - protos.google.monitoring.v3.ICreateUptimeCheckConfigRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.monitoring.v3.IUptimeCheckConfig, - protos.google.monitoring.v3.ICreateUptimeCheckConfigRequest|undefined, {}|undefined - ]>|void { + | protos.google.monitoring.v3.ICreateUptimeCheckConfigRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.monitoring.v3.IUptimeCheckConfig, + | protos.google.monitoring.v3.ICreateUptimeCheckConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.monitoring.v3.IUptimeCheckConfig, + protos.google.monitoring.v3.ICreateUptimeCheckConfigRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('createUptimeCheckConfig request %j', request); - const wrappedCallback: Callback< - protos.google.monitoring.v3.IUptimeCheckConfig, - protos.google.monitoring.v3.ICreateUptimeCheckConfigRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.monitoring.v3.IUptimeCheckConfig, + | protos.google.monitoring.v3.ICreateUptimeCheckConfigRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createUptimeCheckConfig response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.createUptimeCheckConfig(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.monitoring.v3.IUptimeCheckConfig, - protos.google.monitoring.v3.ICreateUptimeCheckConfigRequest|undefined, - {}|undefined - ]) => { - this._log.info('createUptimeCheckConfig response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createUptimeCheckConfig(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.monitoring.v3.IUptimeCheckConfig, + ( + | protos.google.monitoring.v3.ICreateUptimeCheckConfigRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('createUptimeCheckConfig response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Updates an Uptime check configuration. You can either replace the entire - * configuration with a new one or replace only certain fields in the current - * configuration by specifying the fields to be updated via `updateMask`. - * Returns the updated configuration. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.protobuf.FieldMask} request.updateMask - * Optional. If present, only the listed fields in the current Uptime check - * configuration are updated with values from the new configuration. If this - * field is empty, then the current configuration is completely replaced with - * the new configuration. - * @param {google.monitoring.v3.UptimeCheckConfig} request.uptimeCheckConfig - * Required. If an `updateMask` has been specified, this field gives - * the values for the set of fields mentioned in the `updateMask`. If an - * `updateMask` has not been given, this Uptime check configuration replaces - * the current configuration. If a field is mentioned in `updateMask` but - * the corresonding field is omitted in this partial Uptime check - * configuration, it has the effect of deleting/clearing the field from the - * configuration on the server. - * - * The following fields can be updated: `display_name`, - * `http_check`, `tcp_check`, `timeout`, `content_matchers`, and - * `selected_regions`. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.monitoring.v3.UptimeCheckConfig|UptimeCheckConfig}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v3/uptime_check_service.update_uptime_check_config.js - * region_tag:monitoring_v3_generated_UptimeCheckService_UpdateUptimeCheckConfig_async - */ + /** + * Updates an Uptime check configuration. You can either replace the entire + * configuration with a new one or replace only certain fields in the current + * configuration by specifying the fields to be updated via `updateMask`. + * Returns the updated configuration. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.protobuf.FieldMask} request.updateMask + * Optional. If present, only the listed fields in the current Uptime check + * configuration are updated with values from the new configuration. If this + * field is empty, then the current configuration is completely replaced with + * the new configuration. + * @param {google.monitoring.v3.UptimeCheckConfig} request.uptimeCheckConfig + * Required. If an `updateMask` has been specified, this field gives + * the values for the set of fields mentioned in the `updateMask`. If an + * `updateMask` has not been given, this Uptime check configuration replaces + * the current configuration. If a field is mentioned in `updateMask` but + * the corresonding field is omitted in this partial Uptime check + * configuration, it has the effect of deleting/clearing the field from the + * configuration on the server. + * + * The following fields can be updated: `display_name`, + * `http_check`, `tcp_check`, `timeout`, `content_matchers`, and + * `selected_regions`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.monitoring.v3.UptimeCheckConfig|UptimeCheckConfig}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v3/uptime_check_service.update_uptime_check_config.js + * region_tag:monitoring_v3_generated_UptimeCheckService_UpdateUptimeCheckConfig_async + */ updateUptimeCheckConfig( - request?: protos.google.monitoring.v3.IUpdateUptimeCheckConfigRequest, - options?: CallOptions): - Promise<[ - protos.google.monitoring.v3.IUptimeCheckConfig, - protos.google.monitoring.v3.IUpdateUptimeCheckConfigRequest|undefined, {}|undefined - ]>; + request?: protos.google.monitoring.v3.IUpdateUptimeCheckConfigRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.monitoring.v3.IUptimeCheckConfig, + protos.google.monitoring.v3.IUpdateUptimeCheckConfigRequest | undefined, + {} | undefined, + ] + >; updateUptimeCheckConfig( - request: protos.google.monitoring.v3.IUpdateUptimeCheckConfigRequest, - options: CallOptions, - callback: Callback< - protos.google.monitoring.v3.IUptimeCheckConfig, - protos.google.monitoring.v3.IUpdateUptimeCheckConfigRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.IUpdateUptimeCheckConfigRequest, + options: CallOptions, + callback: Callback< + protos.google.monitoring.v3.IUptimeCheckConfig, + | protos.google.monitoring.v3.IUpdateUptimeCheckConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateUptimeCheckConfig( - request: protos.google.monitoring.v3.IUpdateUptimeCheckConfigRequest, - callback: Callback< - protos.google.monitoring.v3.IUptimeCheckConfig, - protos.google.monitoring.v3.IUpdateUptimeCheckConfigRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.IUpdateUptimeCheckConfigRequest, + callback: Callback< + protos.google.monitoring.v3.IUptimeCheckConfig, + | protos.google.monitoring.v3.IUpdateUptimeCheckConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateUptimeCheckConfig( - request?: protos.google.monitoring.v3.IUpdateUptimeCheckConfigRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.monitoring.v3.IUpdateUptimeCheckConfigRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.monitoring.v3.IUptimeCheckConfig, - protos.google.monitoring.v3.IUpdateUptimeCheckConfigRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.monitoring.v3.IUptimeCheckConfig, - protos.google.monitoring.v3.IUpdateUptimeCheckConfigRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.monitoring.v3.IUptimeCheckConfig, - protos.google.monitoring.v3.IUpdateUptimeCheckConfigRequest|undefined, {}|undefined - ]>|void { + | protos.google.monitoring.v3.IUpdateUptimeCheckConfigRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.monitoring.v3.IUptimeCheckConfig, + | protos.google.monitoring.v3.IUpdateUptimeCheckConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.monitoring.v3.IUptimeCheckConfig, + protos.google.monitoring.v3.IUpdateUptimeCheckConfigRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'uptime_check_config.name': request.uptimeCheckConfig!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'uptime_check_config.name': request.uptimeCheckConfig!.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateUptimeCheckConfig request %j', request); - const wrappedCallback: Callback< - protos.google.monitoring.v3.IUptimeCheckConfig, - protos.google.monitoring.v3.IUpdateUptimeCheckConfigRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.monitoring.v3.IUptimeCheckConfig, + | protos.google.monitoring.v3.IUpdateUptimeCheckConfigRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateUptimeCheckConfig response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.updateUptimeCheckConfig(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.monitoring.v3.IUptimeCheckConfig, - protos.google.monitoring.v3.IUpdateUptimeCheckConfigRequest|undefined, - {}|undefined - ]) => { - this._log.info('updateUptimeCheckConfig response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateUptimeCheckConfig(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.monitoring.v3.IUptimeCheckConfig, + ( + | protos.google.monitoring.v3.IUpdateUptimeCheckConfigRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('updateUptimeCheckConfig response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Deletes an Uptime check configuration. Note that this method will fail - * if the Uptime check configuration is referenced by an alert policy or - * other dependent configs that would be rendered invalid by the deletion. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The Uptime check configuration to delete. The format - * is `projects/[PROJECT_ID]/uptimeCheckConfigs/[UPTIME_CHECK_ID]`. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v3/uptime_check_service.delete_uptime_check_config.js - * region_tag:monitoring_v3_generated_UptimeCheckService_DeleteUptimeCheckConfig_async - */ + /** + * Deletes an Uptime check configuration. Note that this method will fail + * if the Uptime check configuration is referenced by an alert policy or + * other dependent configs that would be rendered invalid by the deletion. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The Uptime check configuration to delete. The format + * is `projects/[PROJECT_ID]/uptimeCheckConfigs/[UPTIME_CHECK_ID]`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v3/uptime_check_service.delete_uptime_check_config.js + * region_tag:monitoring_v3_generated_UptimeCheckService_DeleteUptimeCheckConfig_async + */ deleteUptimeCheckConfig( - request?: protos.google.monitoring.v3.IDeleteUptimeCheckConfigRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.IDeleteUptimeCheckConfigRequest|undefined, {}|undefined - ]>; + request?: protos.google.monitoring.v3.IDeleteUptimeCheckConfigRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.monitoring.v3.IDeleteUptimeCheckConfigRequest | undefined, + {} | undefined, + ] + >; deleteUptimeCheckConfig( - request: protos.google.monitoring.v3.IDeleteUptimeCheckConfigRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.IDeleteUptimeCheckConfigRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.IDeleteUptimeCheckConfigRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.monitoring.v3.IDeleteUptimeCheckConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteUptimeCheckConfig( - request: protos.google.monitoring.v3.IDeleteUptimeCheckConfigRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.IDeleteUptimeCheckConfigRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.monitoring.v3.IDeleteUptimeCheckConfigRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.monitoring.v3.IDeleteUptimeCheckConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteUptimeCheckConfig( - request?: protos.google.monitoring.v3.IDeleteUptimeCheckConfigRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.monitoring.v3.IDeleteUptimeCheckConfigRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.IDeleteUptimeCheckConfigRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.IDeleteUptimeCheckConfigRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.IDeleteUptimeCheckConfigRequest|undefined, {}|undefined - ]>|void { + | protos.google.monitoring.v3.IDeleteUptimeCheckConfigRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + | protos.google.monitoring.v3.IDeleteUptimeCheckConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.monitoring.v3.IDeleteUptimeCheckConfigRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('deleteUptimeCheckConfig request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.IDeleteUptimeCheckConfigRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.monitoring.v3.IDeleteUptimeCheckConfigRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteUptimeCheckConfig response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.deleteUptimeCheckConfig(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.monitoring.v3.IDeleteUptimeCheckConfigRequest|undefined, - {}|undefined - ]) => { - this._log.info('deleteUptimeCheckConfig response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteUptimeCheckConfig(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + ( + | protos.google.monitoring.v3.IDeleteUptimeCheckConfigRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('deleteUptimeCheckConfig response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } - /** - * Lists the existing valid Uptime check configurations for the project - * (leaving out any invalid configurations). - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The project whose Uptime check configurations are listed. The format - * is `projects/[PROJECT_ID]`. - * @param {number} request.pageSize - * The maximum number of results to return in a single response. The server - * may further constrain the maximum number of results returned in a single - * page. If the page_size is <=0, the server will decide the number of results - * to be returned. - * @param {string} request.pageToken - * If this field is not empty then it must contain the `nextPageToken` value - * returned by a previous call to this method. Using this field causes the - * method to return more results from the previous method call. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.monitoring.v3.UptimeCheckConfig|UptimeCheckConfig}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `listUptimeCheckConfigsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Lists the existing valid Uptime check configurations for the project + * (leaving out any invalid configurations). + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The project whose Uptime check configurations are listed. The format + * is `projects/[PROJECT_ID]`. + * @param {number} request.pageSize + * The maximum number of results to return in a single response. The server + * may further constrain the maximum number of results returned in a single + * page. If the page_size is <=0, the server will decide the number of results + * to be returned. + * @param {string} request.pageToken + * If this field is not empty then it must contain the `nextPageToken` value + * returned by a previous call to this method. Using this field causes the + * method to return more results from the previous method call. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.monitoring.v3.UptimeCheckConfig|UptimeCheckConfig}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listUptimeCheckConfigsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listUptimeCheckConfigs( - request?: protos.google.monitoring.v3.IListUptimeCheckConfigsRequest, - options?: CallOptions): - Promise<[ - protos.google.monitoring.v3.IUptimeCheckConfig[], - protos.google.monitoring.v3.IListUptimeCheckConfigsRequest|null, - protos.google.monitoring.v3.IListUptimeCheckConfigsResponse - ]>; + request?: protos.google.monitoring.v3.IListUptimeCheckConfigsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.monitoring.v3.IUptimeCheckConfig[], + protos.google.monitoring.v3.IListUptimeCheckConfigsRequest | null, + protos.google.monitoring.v3.IListUptimeCheckConfigsResponse, + ] + >; listUptimeCheckConfigs( - request: protos.google.monitoring.v3.IListUptimeCheckConfigsRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.monitoring.v3.IListUptimeCheckConfigsRequest, - protos.google.monitoring.v3.IListUptimeCheckConfigsResponse|null|undefined, - protos.google.monitoring.v3.IUptimeCheckConfig>): void; + request: protos.google.monitoring.v3.IListUptimeCheckConfigsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.monitoring.v3.IListUptimeCheckConfigsRequest, + | protos.google.monitoring.v3.IListUptimeCheckConfigsResponse + | null + | undefined, + protos.google.monitoring.v3.IUptimeCheckConfig + >, + ): void; listUptimeCheckConfigs( - request: protos.google.monitoring.v3.IListUptimeCheckConfigsRequest, - callback: PaginationCallback< - protos.google.monitoring.v3.IListUptimeCheckConfigsRequest, - protos.google.monitoring.v3.IListUptimeCheckConfigsResponse|null|undefined, - protos.google.monitoring.v3.IUptimeCheckConfig>): void; + request: protos.google.monitoring.v3.IListUptimeCheckConfigsRequest, + callback: PaginationCallback< + protos.google.monitoring.v3.IListUptimeCheckConfigsRequest, + | protos.google.monitoring.v3.IListUptimeCheckConfigsResponse + | null + | undefined, + protos.google.monitoring.v3.IUptimeCheckConfig + >, + ): void; listUptimeCheckConfigs( - request?: protos.google.monitoring.v3.IListUptimeCheckConfigsRequest, - optionsOrCallback?: CallOptions|PaginationCallback< - protos.google.monitoring.v3.IListUptimeCheckConfigsRequest, - protos.google.monitoring.v3.IListUptimeCheckConfigsResponse|null|undefined, - protos.google.monitoring.v3.IUptimeCheckConfig>, - callback?: PaginationCallback< + request?: protos.google.monitoring.v3.IListUptimeCheckConfigsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.monitoring.v3.IListUptimeCheckConfigsRequest, - protos.google.monitoring.v3.IListUptimeCheckConfigsResponse|null|undefined, - protos.google.monitoring.v3.IUptimeCheckConfig>): - Promise<[ - protos.google.monitoring.v3.IUptimeCheckConfig[], - protos.google.monitoring.v3.IListUptimeCheckConfigsRequest|null, - protos.google.monitoring.v3.IListUptimeCheckConfigsResponse - ]>|void { + | protos.google.monitoring.v3.IListUptimeCheckConfigsResponse + | null + | undefined, + protos.google.monitoring.v3.IUptimeCheckConfig + >, + callback?: PaginationCallback< + protos.google.monitoring.v3.IListUptimeCheckConfigsRequest, + | protos.google.monitoring.v3.IListUptimeCheckConfigsResponse + | null + | undefined, + protos.google.monitoring.v3.IUptimeCheckConfig + >, + ): Promise< + [ + protos.google.monitoring.v3.IUptimeCheckConfig[], + protos.google.monitoring.v3.IListUptimeCheckConfigsRequest | null, + protos.google.monitoring.v3.IListUptimeCheckConfigsResponse, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.monitoring.v3.IListUptimeCheckConfigsRequest, - protos.google.monitoring.v3.IListUptimeCheckConfigsResponse|null|undefined, - protos.google.monitoring.v3.IUptimeCheckConfig>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.monitoring.v3.IListUptimeCheckConfigsRequest, + | protos.google.monitoring.v3.IListUptimeCheckConfigsResponse + | null + | undefined, + protos.google.monitoring.v3.IUptimeCheckConfig + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listUptimeCheckConfigs values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -911,201 +1169,231 @@ export class UptimeCheckServiceClient { this._log.info('listUptimeCheckConfigs request %j', request); return this.innerApiCalls .listUptimeCheckConfigs(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.monitoring.v3.IUptimeCheckConfig[], - protos.google.monitoring.v3.IListUptimeCheckConfigsRequest|null, - protos.google.monitoring.v3.IListUptimeCheckConfigsResponse - ]) => { - this._log.info('listUptimeCheckConfigs values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.monitoring.v3.IUptimeCheckConfig[], + protos.google.monitoring.v3.IListUptimeCheckConfigsRequest | null, + protos.google.monitoring.v3.IListUptimeCheckConfigsResponse, + ]) => { + this._log.info('listUptimeCheckConfigs values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listUptimeCheckConfigs`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The project whose Uptime check configurations are listed. The format - * is `projects/[PROJECT_ID]`. - * @param {number} request.pageSize - * The maximum number of results to return in a single response. The server - * may further constrain the maximum number of results returned in a single - * page. If the page_size is <=0, the server will decide the number of results - * to be returned. - * @param {string} request.pageToken - * If this field is not empty then it must contain the `nextPageToken` value - * returned by a previous call to this method. Using this field causes the - * method to return more results from the previous method call. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.monitoring.v3.UptimeCheckConfig|UptimeCheckConfig} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `listUptimeCheckConfigsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `listUptimeCheckConfigs`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The project whose Uptime check configurations are listed. The format + * is `projects/[PROJECT_ID]`. + * @param {number} request.pageSize + * The maximum number of results to return in a single response. The server + * may further constrain the maximum number of results returned in a single + * page. If the page_size is <=0, the server will decide the number of results + * to be returned. + * @param {string} request.pageToken + * If this field is not empty then it must contain the `nextPageToken` value + * returned by a previous call to this method. Using this field causes the + * method to return more results from the previous method call. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.monitoring.v3.UptimeCheckConfig|UptimeCheckConfig} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listUptimeCheckConfigsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listUptimeCheckConfigsStream( - request?: protos.google.monitoring.v3.IListUptimeCheckConfigsRequest, - options?: CallOptions): - Transform{ + request?: protos.google.monitoring.v3.IListUptimeCheckConfigsRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); const defaultCallSettings = this._defaults['listUptimeCheckConfigs']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listUptimeCheckConfigs stream %j', request); return this.descriptors.page.listUptimeCheckConfigs.createStream( this.innerApiCalls.listUptimeCheckConfigs as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listUptimeCheckConfigs`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The project whose Uptime check configurations are listed. The format - * is `projects/[PROJECT_ID]`. - * @param {number} request.pageSize - * The maximum number of results to return in a single response. The server - * may further constrain the maximum number of results returned in a single - * page. If the page_size is <=0, the server will decide the number of results - * to be returned. - * @param {string} request.pageToken - * If this field is not empty then it must contain the `nextPageToken` value - * returned by a previous call to this method. Using this field causes the - * method to return more results from the previous method call. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.monitoring.v3.UptimeCheckConfig|UptimeCheckConfig}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v3/uptime_check_service.list_uptime_check_configs.js - * region_tag:monitoring_v3_generated_UptimeCheckService_ListUptimeCheckConfigs_async - */ + /** + * Equivalent to `listUptimeCheckConfigs`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The project whose Uptime check configurations are listed. The format + * is `projects/[PROJECT_ID]`. + * @param {number} request.pageSize + * The maximum number of results to return in a single response. The server + * may further constrain the maximum number of results returned in a single + * page. If the page_size is <=0, the server will decide the number of results + * to be returned. + * @param {string} request.pageToken + * If this field is not empty then it must contain the `nextPageToken` value + * returned by a previous call to this method. Using this field causes the + * method to return more results from the previous method call. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.monitoring.v3.UptimeCheckConfig|UptimeCheckConfig}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v3/uptime_check_service.list_uptime_check_configs.js + * region_tag:monitoring_v3_generated_UptimeCheckService_ListUptimeCheckConfigs_async + */ listUptimeCheckConfigsAsync( - request?: protos.google.monitoring.v3.IListUptimeCheckConfigsRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.monitoring.v3.IListUptimeCheckConfigsRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); const defaultCallSettings = this._defaults['listUptimeCheckConfigs']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listUptimeCheckConfigs iterate %j', request); return this.descriptors.page.listUptimeCheckConfigs.asyncIterate( this.innerApiCalls['listUptimeCheckConfigs'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } - /** - * Returns the list of IP addresses that checkers run from - * - * @param {Object} request - * The request object that will be sent. - * @param {number} request.pageSize - * The maximum number of results to return in a single response. The server - * may further constrain the maximum number of results returned in a single - * page. If the page_size is <=0, the server will decide the number of results - * to be returned. - * NOTE: this field is not yet implemented - * @param {string} request.pageToken - * If this field is not empty then it must contain the `nextPageToken` value - * returned by a previous call to this method. Using this field causes the - * method to return more results from the previous method call. - * NOTE: this field is not yet implemented - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.monitoring.v3.UptimeCheckIp|UptimeCheckIp}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `listUptimeCheckIpsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Returns the list of IP addresses that checkers run from + * + * @param {Object} request + * The request object that will be sent. + * @param {number} request.pageSize + * The maximum number of results to return in a single response. The server + * may further constrain the maximum number of results returned in a single + * page. If the page_size is <=0, the server will decide the number of results + * to be returned. + * NOTE: this field is not yet implemented + * @param {string} request.pageToken + * If this field is not empty then it must contain the `nextPageToken` value + * returned by a previous call to this method. Using this field causes the + * method to return more results from the previous method call. + * NOTE: this field is not yet implemented + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.monitoring.v3.UptimeCheckIp|UptimeCheckIp}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listUptimeCheckIpsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listUptimeCheckIps( - request?: protos.google.monitoring.v3.IListUptimeCheckIpsRequest, - options?: CallOptions): - Promise<[ - protos.google.monitoring.v3.IUptimeCheckIp[], - protos.google.monitoring.v3.IListUptimeCheckIpsRequest|null, - protos.google.monitoring.v3.IListUptimeCheckIpsResponse - ]>; + request?: protos.google.monitoring.v3.IListUptimeCheckIpsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.monitoring.v3.IUptimeCheckIp[], + protos.google.monitoring.v3.IListUptimeCheckIpsRequest | null, + protos.google.monitoring.v3.IListUptimeCheckIpsResponse, + ] + >; listUptimeCheckIps( - request: protos.google.monitoring.v3.IListUptimeCheckIpsRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.monitoring.v3.IListUptimeCheckIpsRequest, - protos.google.monitoring.v3.IListUptimeCheckIpsResponse|null|undefined, - protos.google.monitoring.v3.IUptimeCheckIp>): void; + request: protos.google.monitoring.v3.IListUptimeCheckIpsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.monitoring.v3.IListUptimeCheckIpsRequest, + | protos.google.monitoring.v3.IListUptimeCheckIpsResponse + | null + | undefined, + protos.google.monitoring.v3.IUptimeCheckIp + >, + ): void; listUptimeCheckIps( - request: protos.google.monitoring.v3.IListUptimeCheckIpsRequest, - callback: PaginationCallback< - protos.google.monitoring.v3.IListUptimeCheckIpsRequest, - protos.google.monitoring.v3.IListUptimeCheckIpsResponse|null|undefined, - protos.google.monitoring.v3.IUptimeCheckIp>): void; + request: protos.google.monitoring.v3.IListUptimeCheckIpsRequest, + callback: PaginationCallback< + protos.google.monitoring.v3.IListUptimeCheckIpsRequest, + | protos.google.monitoring.v3.IListUptimeCheckIpsResponse + | null + | undefined, + protos.google.monitoring.v3.IUptimeCheckIp + >, + ): void; listUptimeCheckIps( - request?: protos.google.monitoring.v3.IListUptimeCheckIpsRequest, - optionsOrCallback?: CallOptions|PaginationCallback< + request?: protos.google.monitoring.v3.IListUptimeCheckIpsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.monitoring.v3.IListUptimeCheckIpsRequest, - protos.google.monitoring.v3.IListUptimeCheckIpsResponse|null|undefined, - protos.google.monitoring.v3.IUptimeCheckIp>, - callback?: PaginationCallback< - protos.google.monitoring.v3.IListUptimeCheckIpsRequest, - protos.google.monitoring.v3.IListUptimeCheckIpsResponse|null|undefined, - protos.google.monitoring.v3.IUptimeCheckIp>): - Promise<[ - protos.google.monitoring.v3.IUptimeCheckIp[], - protos.google.monitoring.v3.IListUptimeCheckIpsRequest|null, - protos.google.monitoring.v3.IListUptimeCheckIpsResponse - ]>|void { + | protos.google.monitoring.v3.IListUptimeCheckIpsResponse + | null + | undefined, + protos.google.monitoring.v3.IUptimeCheckIp + >, + callback?: PaginationCallback< + protos.google.monitoring.v3.IListUptimeCheckIpsRequest, + | protos.google.monitoring.v3.IListUptimeCheckIpsResponse + | null + | undefined, + protos.google.monitoring.v3.IUptimeCheckIp + >, + ): Promise< + [ + protos.google.monitoring.v3.IUptimeCheckIp[], + protos.google.monitoring.v3.IListUptimeCheckIpsRequest | null, + protos.google.monitoring.v3.IListUptimeCheckIpsResponse, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.monitoring.v3.IListUptimeCheckIpsRequest, - protos.google.monitoring.v3.IListUptimeCheckIpsResponse|null|undefined, - protos.google.monitoring.v3.IUptimeCheckIp>|undefined = callback + this.initialize().catch((err) => { + throw err; + }); + const wrappedCallback: + | PaginationCallback< + protos.google.monitoring.v3.IListUptimeCheckIpsRequest, + | protos.google.monitoring.v3.IListUptimeCheckIpsResponse + | null + | undefined, + protos.google.monitoring.v3.IUptimeCheckIp + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listUptimeCheckIps values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -1114,106 +1402,112 @@ export class UptimeCheckServiceClient { this._log.info('listUptimeCheckIps request %j', request); return this.innerApiCalls .listUptimeCheckIps(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.monitoring.v3.IUptimeCheckIp[], - protos.google.monitoring.v3.IListUptimeCheckIpsRequest|null, - protos.google.monitoring.v3.IListUptimeCheckIpsResponse - ]) => { - this._log.info('listUptimeCheckIps values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.monitoring.v3.IUptimeCheckIp[], + protos.google.monitoring.v3.IListUptimeCheckIpsRequest | null, + protos.google.monitoring.v3.IListUptimeCheckIpsResponse, + ]) => { + this._log.info('listUptimeCheckIps values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listUptimeCheckIps`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {number} request.pageSize - * The maximum number of results to return in a single response. The server - * may further constrain the maximum number of results returned in a single - * page. If the page_size is <=0, the server will decide the number of results - * to be returned. - * NOTE: this field is not yet implemented - * @param {string} request.pageToken - * If this field is not empty then it must contain the `nextPageToken` value - * returned by a previous call to this method. Using this field causes the - * method to return more results from the previous method call. - * NOTE: this field is not yet implemented - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.monitoring.v3.UptimeCheckIp|UptimeCheckIp} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `listUptimeCheckIpsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `listUptimeCheckIps`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {number} request.pageSize + * The maximum number of results to return in a single response. The server + * may further constrain the maximum number of results returned in a single + * page. If the page_size is <=0, the server will decide the number of results + * to be returned. + * NOTE: this field is not yet implemented + * @param {string} request.pageToken + * If this field is not empty then it must contain the `nextPageToken` value + * returned by a previous call to this method. Using this field causes the + * method to return more results from the previous method call. + * NOTE: this field is not yet implemented + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.monitoring.v3.UptimeCheckIp|UptimeCheckIp} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listUptimeCheckIpsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listUptimeCheckIpsStream( - request?: protos.google.monitoring.v3.IListUptimeCheckIpsRequest, - options?: CallOptions): - Transform{ + request?: protos.google.monitoring.v3.IListUptimeCheckIpsRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; const defaultCallSettings = this._defaults['listUptimeCheckIps']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listUptimeCheckIps stream %j', request); return this.descriptors.page.listUptimeCheckIps.createStream( this.innerApiCalls.listUptimeCheckIps as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listUptimeCheckIps`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {number} request.pageSize - * The maximum number of results to return in a single response. The server - * may further constrain the maximum number of results returned in a single - * page. If the page_size is <=0, the server will decide the number of results - * to be returned. - * NOTE: this field is not yet implemented - * @param {string} request.pageToken - * If this field is not empty then it must contain the `nextPageToken` value - * returned by a previous call to this method. Using this field causes the - * method to return more results from the previous method call. - * NOTE: this field is not yet implemented - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.monitoring.v3.UptimeCheckIp|UptimeCheckIp}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v3/uptime_check_service.list_uptime_check_ips.js - * region_tag:monitoring_v3_generated_UptimeCheckService_ListUptimeCheckIps_async - */ + /** + * Equivalent to `listUptimeCheckIps`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {number} request.pageSize + * The maximum number of results to return in a single response. The server + * may further constrain the maximum number of results returned in a single + * page. If the page_size is <=0, the server will decide the number of results + * to be returned. + * NOTE: this field is not yet implemented + * @param {string} request.pageToken + * If this field is not empty then it must contain the `nextPageToken` value + * returned by a previous call to this method. Using this field causes the + * method to return more results from the previous method call. + * NOTE: this field is not yet implemented + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.monitoring.v3.UptimeCheckIp|UptimeCheckIp}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v3/uptime_check_service.list_uptime_check_ips.js + * region_tag:monitoring_v3_generated_UptimeCheckService_ListUptimeCheckIps_async + */ listUptimeCheckIpsAsync( - request?: protos.google.monitoring.v3.IListUptimeCheckIpsRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.monitoring.v3.IListUptimeCheckIpsRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; const defaultCallSettings = this._defaults['listUptimeCheckIps']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listUptimeCheckIps iterate %j', request); return this.descriptors.page.listUptimeCheckIps.asyncIterate( this.innerApiCalls['listUptimeCheckIps'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } // -------------------- @@ -1227,7 +1521,7 @@ export class UptimeCheckServiceClient { * @param {string} alert_policy * @returns {string} Resource name string. */ - folderAlertPolicyPath(folder:string,alertPolicy:string) { + folderAlertPolicyPath(folder: string, alertPolicy: string) { return this.pathTemplates.folderAlertPolicyPathTemplate.render({ folder: folder, alert_policy: alertPolicy, @@ -1242,7 +1536,9 @@ export class UptimeCheckServiceClient { * @returns {string} A string representing the folder. */ matchFolderFromFolderAlertPolicyName(folderAlertPolicyName: string) { - return this.pathTemplates.folderAlertPolicyPathTemplate.match(folderAlertPolicyName).folder; + return this.pathTemplates.folderAlertPolicyPathTemplate.match( + folderAlertPolicyName, + ).folder; } /** @@ -1253,7 +1549,9 @@ export class UptimeCheckServiceClient { * @returns {string} A string representing the alert_policy. */ matchAlertPolicyFromFolderAlertPolicyName(folderAlertPolicyName: string) { - return this.pathTemplates.folderAlertPolicyPathTemplate.match(folderAlertPolicyName).alert_policy; + return this.pathTemplates.folderAlertPolicyPathTemplate.match( + folderAlertPolicyName, + ).alert_policy; } /** @@ -1264,7 +1562,11 @@ export class UptimeCheckServiceClient { * @param {string} condition * @returns {string} Resource name string. */ - folderAlertPolicyConditionPath(folder:string,alertPolicy:string,condition:string) { + folderAlertPolicyConditionPath( + folder: string, + alertPolicy: string, + condition: string, + ) { return this.pathTemplates.folderAlertPolicyConditionPathTemplate.render({ folder: folder, alert_policy: alertPolicy, @@ -1279,8 +1581,12 @@ export class UptimeCheckServiceClient { * A fully-qualified path representing folder_alert_policy_condition resource. * @returns {string} A string representing the folder. */ - matchFolderFromFolderAlertPolicyConditionName(folderAlertPolicyConditionName: string) { - return this.pathTemplates.folderAlertPolicyConditionPathTemplate.match(folderAlertPolicyConditionName).folder; + matchFolderFromFolderAlertPolicyConditionName( + folderAlertPolicyConditionName: string, + ) { + return this.pathTemplates.folderAlertPolicyConditionPathTemplate.match( + folderAlertPolicyConditionName, + ).folder; } /** @@ -1290,8 +1596,12 @@ export class UptimeCheckServiceClient { * A fully-qualified path representing folder_alert_policy_condition resource. * @returns {string} A string representing the alert_policy. */ - matchAlertPolicyFromFolderAlertPolicyConditionName(folderAlertPolicyConditionName: string) { - return this.pathTemplates.folderAlertPolicyConditionPathTemplate.match(folderAlertPolicyConditionName).alert_policy; + matchAlertPolicyFromFolderAlertPolicyConditionName( + folderAlertPolicyConditionName: string, + ) { + return this.pathTemplates.folderAlertPolicyConditionPathTemplate.match( + folderAlertPolicyConditionName, + ).alert_policy; } /** @@ -1301,8 +1611,12 @@ export class UptimeCheckServiceClient { * A fully-qualified path representing folder_alert_policy_condition resource. * @returns {string} A string representing the condition. */ - matchConditionFromFolderAlertPolicyConditionName(folderAlertPolicyConditionName: string) { - return this.pathTemplates.folderAlertPolicyConditionPathTemplate.match(folderAlertPolicyConditionName).condition; + matchConditionFromFolderAlertPolicyConditionName( + folderAlertPolicyConditionName: string, + ) { + return this.pathTemplates.folderAlertPolicyConditionPathTemplate.match( + folderAlertPolicyConditionName, + ).condition; } /** @@ -1312,7 +1626,7 @@ export class UptimeCheckServiceClient { * @param {string} channel_descriptor * @returns {string} Resource name string. */ - folderChannelDescriptorPath(folder:string,channelDescriptor:string) { + folderChannelDescriptorPath(folder: string, channelDescriptor: string) { return this.pathTemplates.folderChannelDescriptorPathTemplate.render({ folder: folder, channel_descriptor: channelDescriptor, @@ -1326,8 +1640,12 @@ export class UptimeCheckServiceClient { * A fully-qualified path representing folder_channel_descriptor resource. * @returns {string} A string representing the folder. */ - matchFolderFromFolderChannelDescriptorName(folderChannelDescriptorName: string) { - return this.pathTemplates.folderChannelDescriptorPathTemplate.match(folderChannelDescriptorName).folder; + matchFolderFromFolderChannelDescriptorName( + folderChannelDescriptorName: string, + ) { + return this.pathTemplates.folderChannelDescriptorPathTemplate.match( + folderChannelDescriptorName, + ).folder; } /** @@ -1337,8 +1655,12 @@ export class UptimeCheckServiceClient { * A fully-qualified path representing folder_channel_descriptor resource. * @returns {string} A string representing the channel_descriptor. */ - matchChannelDescriptorFromFolderChannelDescriptorName(folderChannelDescriptorName: string) { - return this.pathTemplates.folderChannelDescriptorPathTemplate.match(folderChannelDescriptorName).channel_descriptor; + matchChannelDescriptorFromFolderChannelDescriptorName( + folderChannelDescriptorName: string, + ) { + return this.pathTemplates.folderChannelDescriptorPathTemplate.match( + folderChannelDescriptorName, + ).channel_descriptor; } /** @@ -1348,7 +1670,7 @@ export class UptimeCheckServiceClient { * @param {string} group * @returns {string} Resource name string. */ - folderGroupPath(folder:string,group:string) { + folderGroupPath(folder: string, group: string) { return this.pathTemplates.folderGroupPathTemplate.render({ folder: folder, group: group, @@ -1363,7 +1685,8 @@ export class UptimeCheckServiceClient { * @returns {string} A string representing the folder. */ matchFolderFromFolderGroupName(folderGroupName: string) { - return this.pathTemplates.folderGroupPathTemplate.match(folderGroupName).folder; + return this.pathTemplates.folderGroupPathTemplate.match(folderGroupName) + .folder; } /** @@ -1374,7 +1697,8 @@ export class UptimeCheckServiceClient { * @returns {string} A string representing the group. */ matchGroupFromFolderGroupName(folderGroupName: string) { - return this.pathTemplates.folderGroupPathTemplate.match(folderGroupName).group; + return this.pathTemplates.folderGroupPathTemplate.match(folderGroupName) + .group; } /** @@ -1384,7 +1708,7 @@ export class UptimeCheckServiceClient { * @param {string} notification_channel * @returns {string} Resource name string. */ - folderNotificationChannelPath(folder:string,notificationChannel:string) { + folderNotificationChannelPath(folder: string, notificationChannel: string) { return this.pathTemplates.folderNotificationChannelPathTemplate.render({ folder: folder, notification_channel: notificationChannel, @@ -1398,8 +1722,12 @@ export class UptimeCheckServiceClient { * A fully-qualified path representing folder_notification_channel resource. * @returns {string} A string representing the folder. */ - matchFolderFromFolderNotificationChannelName(folderNotificationChannelName: string) { - return this.pathTemplates.folderNotificationChannelPathTemplate.match(folderNotificationChannelName).folder; + matchFolderFromFolderNotificationChannelName( + folderNotificationChannelName: string, + ) { + return this.pathTemplates.folderNotificationChannelPathTemplate.match( + folderNotificationChannelName, + ).folder; } /** @@ -1409,8 +1737,12 @@ export class UptimeCheckServiceClient { * A fully-qualified path representing folder_notification_channel resource. * @returns {string} A string representing the notification_channel. */ - matchNotificationChannelFromFolderNotificationChannelName(folderNotificationChannelName: string) { - return this.pathTemplates.folderNotificationChannelPathTemplate.match(folderNotificationChannelName).notification_channel; + matchNotificationChannelFromFolderNotificationChannelName( + folderNotificationChannelName: string, + ) { + return this.pathTemplates.folderNotificationChannelPathTemplate.match( + folderNotificationChannelName, + ).notification_channel; } /** @@ -1420,7 +1752,7 @@ export class UptimeCheckServiceClient { * @param {string} service * @returns {string} Resource name string. */ - folderServicePath(folder:string,service:string) { + folderServicePath(folder: string, service: string) { return this.pathTemplates.folderServicePathTemplate.render({ folder: folder, service: service, @@ -1435,7 +1767,8 @@ export class UptimeCheckServiceClient { * @returns {string} A string representing the folder. */ matchFolderFromFolderServiceName(folderServiceName: string) { - return this.pathTemplates.folderServicePathTemplate.match(folderServiceName).folder; + return this.pathTemplates.folderServicePathTemplate.match(folderServiceName) + .folder; } /** @@ -1446,7 +1779,8 @@ export class UptimeCheckServiceClient { * @returns {string} A string representing the service. */ matchServiceFromFolderServiceName(folderServiceName: string) { - return this.pathTemplates.folderServicePathTemplate.match(folderServiceName).service; + return this.pathTemplates.folderServicePathTemplate.match(folderServiceName) + .service; } /** @@ -1457,12 +1791,18 @@ export class UptimeCheckServiceClient { * @param {string} service_level_objective * @returns {string} Resource name string. */ - folderServiceServiceLevelObjectivePath(folder:string,service:string,serviceLevelObjective:string) { - return this.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.render({ - folder: folder, - service: service, - service_level_objective: serviceLevelObjective, - }); + folderServiceServiceLevelObjectivePath( + folder: string, + service: string, + serviceLevelObjective: string, + ) { + return this.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.render( + { + folder: folder, + service: service, + service_level_objective: serviceLevelObjective, + }, + ); } /** @@ -1472,8 +1812,12 @@ export class UptimeCheckServiceClient { * A fully-qualified path representing folder_service_service_level_objective resource. * @returns {string} A string representing the folder. */ - matchFolderFromFolderServiceServiceLevelObjectiveName(folderServiceServiceLevelObjectiveName: string) { - return this.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match(folderServiceServiceLevelObjectiveName).folder; + matchFolderFromFolderServiceServiceLevelObjectiveName( + folderServiceServiceLevelObjectiveName: string, + ) { + return this.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match( + folderServiceServiceLevelObjectiveName, + ).folder; } /** @@ -1483,8 +1827,12 @@ export class UptimeCheckServiceClient { * A fully-qualified path representing folder_service_service_level_objective resource. * @returns {string} A string representing the service. */ - matchServiceFromFolderServiceServiceLevelObjectiveName(folderServiceServiceLevelObjectiveName: string) { - return this.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match(folderServiceServiceLevelObjectiveName).service; + matchServiceFromFolderServiceServiceLevelObjectiveName( + folderServiceServiceLevelObjectiveName: string, + ) { + return this.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match( + folderServiceServiceLevelObjectiveName, + ).service; } /** @@ -1494,8 +1842,12 @@ export class UptimeCheckServiceClient { * A fully-qualified path representing folder_service_service_level_objective resource. * @returns {string} A string representing the service_level_objective. */ - matchServiceLevelObjectiveFromFolderServiceServiceLevelObjectiveName(folderServiceServiceLevelObjectiveName: string) { - return this.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match(folderServiceServiceLevelObjectiveName).service_level_objective; + matchServiceLevelObjectiveFromFolderServiceServiceLevelObjectiveName( + folderServiceServiceLevelObjectiveName: string, + ) { + return this.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match( + folderServiceServiceLevelObjectiveName, + ).service_level_objective; } /** @@ -1505,7 +1857,7 @@ export class UptimeCheckServiceClient { * @param {string} uptime_check_config * @returns {string} Resource name string. */ - folderUptimeCheckConfigPath(folder:string,uptimeCheckConfig:string) { + folderUptimeCheckConfigPath(folder: string, uptimeCheckConfig: string) { return this.pathTemplates.folderUptimeCheckConfigPathTemplate.render({ folder: folder, uptime_check_config: uptimeCheckConfig, @@ -1519,8 +1871,12 @@ export class UptimeCheckServiceClient { * A fully-qualified path representing folder_uptime_check_config resource. * @returns {string} A string representing the folder. */ - matchFolderFromFolderUptimeCheckConfigName(folderUptimeCheckConfigName: string) { - return this.pathTemplates.folderUptimeCheckConfigPathTemplate.match(folderUptimeCheckConfigName).folder; + matchFolderFromFolderUptimeCheckConfigName( + folderUptimeCheckConfigName: string, + ) { + return this.pathTemplates.folderUptimeCheckConfigPathTemplate.match( + folderUptimeCheckConfigName, + ).folder; } /** @@ -1530,8 +1886,12 @@ export class UptimeCheckServiceClient { * A fully-qualified path representing folder_uptime_check_config resource. * @returns {string} A string representing the uptime_check_config. */ - matchUptimeCheckConfigFromFolderUptimeCheckConfigName(folderUptimeCheckConfigName: string) { - return this.pathTemplates.folderUptimeCheckConfigPathTemplate.match(folderUptimeCheckConfigName).uptime_check_config; + matchUptimeCheckConfigFromFolderUptimeCheckConfigName( + folderUptimeCheckConfigName: string, + ) { + return this.pathTemplates.folderUptimeCheckConfigPathTemplate.match( + folderUptimeCheckConfigName, + ).uptime_check_config; } /** @@ -1541,7 +1901,7 @@ export class UptimeCheckServiceClient { * @param {string} alert_policy * @returns {string} Resource name string. */ - organizationAlertPolicyPath(organization:string,alertPolicy:string) { + organizationAlertPolicyPath(organization: string, alertPolicy: string) { return this.pathTemplates.organizationAlertPolicyPathTemplate.render({ organization: organization, alert_policy: alertPolicy, @@ -1555,8 +1915,12 @@ export class UptimeCheckServiceClient { * A fully-qualified path representing organization_alert_policy resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationAlertPolicyName(organizationAlertPolicyName: string) { - return this.pathTemplates.organizationAlertPolicyPathTemplate.match(organizationAlertPolicyName).organization; + matchOrganizationFromOrganizationAlertPolicyName( + organizationAlertPolicyName: string, + ) { + return this.pathTemplates.organizationAlertPolicyPathTemplate.match( + organizationAlertPolicyName, + ).organization; } /** @@ -1566,8 +1930,12 @@ export class UptimeCheckServiceClient { * A fully-qualified path representing organization_alert_policy resource. * @returns {string} A string representing the alert_policy. */ - matchAlertPolicyFromOrganizationAlertPolicyName(organizationAlertPolicyName: string) { - return this.pathTemplates.organizationAlertPolicyPathTemplate.match(organizationAlertPolicyName).alert_policy; + matchAlertPolicyFromOrganizationAlertPolicyName( + organizationAlertPolicyName: string, + ) { + return this.pathTemplates.organizationAlertPolicyPathTemplate.match( + organizationAlertPolicyName, + ).alert_policy; } /** @@ -1578,12 +1946,18 @@ export class UptimeCheckServiceClient { * @param {string} condition * @returns {string} Resource name string. */ - organizationAlertPolicyConditionPath(organization:string,alertPolicy:string,condition:string) { - return this.pathTemplates.organizationAlertPolicyConditionPathTemplate.render({ - organization: organization, - alert_policy: alertPolicy, - condition: condition, - }); + organizationAlertPolicyConditionPath( + organization: string, + alertPolicy: string, + condition: string, + ) { + return this.pathTemplates.organizationAlertPolicyConditionPathTemplate.render( + { + organization: organization, + alert_policy: alertPolicy, + condition: condition, + }, + ); } /** @@ -1593,8 +1967,12 @@ export class UptimeCheckServiceClient { * A fully-qualified path representing organization_alert_policy_condition resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationAlertPolicyConditionName(organizationAlertPolicyConditionName: string) { - return this.pathTemplates.organizationAlertPolicyConditionPathTemplate.match(organizationAlertPolicyConditionName).organization; + matchOrganizationFromOrganizationAlertPolicyConditionName( + organizationAlertPolicyConditionName: string, + ) { + return this.pathTemplates.organizationAlertPolicyConditionPathTemplate.match( + organizationAlertPolicyConditionName, + ).organization; } /** @@ -1604,8 +1982,12 @@ export class UptimeCheckServiceClient { * A fully-qualified path representing organization_alert_policy_condition resource. * @returns {string} A string representing the alert_policy. */ - matchAlertPolicyFromOrganizationAlertPolicyConditionName(organizationAlertPolicyConditionName: string) { - return this.pathTemplates.organizationAlertPolicyConditionPathTemplate.match(organizationAlertPolicyConditionName).alert_policy; + matchAlertPolicyFromOrganizationAlertPolicyConditionName( + organizationAlertPolicyConditionName: string, + ) { + return this.pathTemplates.organizationAlertPolicyConditionPathTemplate.match( + organizationAlertPolicyConditionName, + ).alert_policy; } /** @@ -1615,8 +1997,12 @@ export class UptimeCheckServiceClient { * A fully-qualified path representing organization_alert_policy_condition resource. * @returns {string} A string representing the condition. */ - matchConditionFromOrganizationAlertPolicyConditionName(organizationAlertPolicyConditionName: string) { - return this.pathTemplates.organizationAlertPolicyConditionPathTemplate.match(organizationAlertPolicyConditionName).condition; + matchConditionFromOrganizationAlertPolicyConditionName( + organizationAlertPolicyConditionName: string, + ) { + return this.pathTemplates.organizationAlertPolicyConditionPathTemplate.match( + organizationAlertPolicyConditionName, + ).condition; } /** @@ -1626,7 +2012,10 @@ export class UptimeCheckServiceClient { * @param {string} channel_descriptor * @returns {string} Resource name string. */ - organizationChannelDescriptorPath(organization:string,channelDescriptor:string) { + organizationChannelDescriptorPath( + organization: string, + channelDescriptor: string, + ) { return this.pathTemplates.organizationChannelDescriptorPathTemplate.render({ organization: organization, channel_descriptor: channelDescriptor, @@ -1640,8 +2029,12 @@ export class UptimeCheckServiceClient { * A fully-qualified path representing organization_channel_descriptor resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationChannelDescriptorName(organizationChannelDescriptorName: string) { - return this.pathTemplates.organizationChannelDescriptorPathTemplate.match(organizationChannelDescriptorName).organization; + matchOrganizationFromOrganizationChannelDescriptorName( + organizationChannelDescriptorName: string, + ) { + return this.pathTemplates.organizationChannelDescriptorPathTemplate.match( + organizationChannelDescriptorName, + ).organization; } /** @@ -1651,8 +2044,12 @@ export class UptimeCheckServiceClient { * A fully-qualified path representing organization_channel_descriptor resource. * @returns {string} A string representing the channel_descriptor. */ - matchChannelDescriptorFromOrganizationChannelDescriptorName(organizationChannelDescriptorName: string) { - return this.pathTemplates.organizationChannelDescriptorPathTemplate.match(organizationChannelDescriptorName).channel_descriptor; + matchChannelDescriptorFromOrganizationChannelDescriptorName( + organizationChannelDescriptorName: string, + ) { + return this.pathTemplates.organizationChannelDescriptorPathTemplate.match( + organizationChannelDescriptorName, + ).channel_descriptor; } /** @@ -1662,7 +2059,7 @@ export class UptimeCheckServiceClient { * @param {string} group * @returns {string} Resource name string. */ - organizationGroupPath(organization:string,group:string) { + organizationGroupPath(organization: string, group: string) { return this.pathTemplates.organizationGroupPathTemplate.render({ organization: organization, group: group, @@ -1677,7 +2074,9 @@ export class UptimeCheckServiceClient { * @returns {string} A string representing the organization. */ matchOrganizationFromOrganizationGroupName(organizationGroupName: string) { - return this.pathTemplates.organizationGroupPathTemplate.match(organizationGroupName).organization; + return this.pathTemplates.organizationGroupPathTemplate.match( + organizationGroupName, + ).organization; } /** @@ -1688,7 +2087,9 @@ export class UptimeCheckServiceClient { * @returns {string} A string representing the group. */ matchGroupFromOrganizationGroupName(organizationGroupName: string) { - return this.pathTemplates.organizationGroupPathTemplate.match(organizationGroupName).group; + return this.pathTemplates.organizationGroupPathTemplate.match( + organizationGroupName, + ).group; } /** @@ -1698,11 +2099,16 @@ export class UptimeCheckServiceClient { * @param {string} notification_channel * @returns {string} Resource name string. */ - organizationNotificationChannelPath(organization:string,notificationChannel:string) { - return this.pathTemplates.organizationNotificationChannelPathTemplate.render({ - organization: organization, - notification_channel: notificationChannel, - }); + organizationNotificationChannelPath( + organization: string, + notificationChannel: string, + ) { + return this.pathTemplates.organizationNotificationChannelPathTemplate.render( + { + organization: organization, + notification_channel: notificationChannel, + }, + ); } /** @@ -1712,8 +2118,12 @@ export class UptimeCheckServiceClient { * A fully-qualified path representing organization_notification_channel resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationNotificationChannelName(organizationNotificationChannelName: string) { - return this.pathTemplates.organizationNotificationChannelPathTemplate.match(organizationNotificationChannelName).organization; + matchOrganizationFromOrganizationNotificationChannelName( + organizationNotificationChannelName: string, + ) { + return this.pathTemplates.organizationNotificationChannelPathTemplate.match( + organizationNotificationChannelName, + ).organization; } /** @@ -1723,8 +2133,12 @@ export class UptimeCheckServiceClient { * A fully-qualified path representing organization_notification_channel resource. * @returns {string} A string representing the notification_channel. */ - matchNotificationChannelFromOrganizationNotificationChannelName(organizationNotificationChannelName: string) { - return this.pathTemplates.organizationNotificationChannelPathTemplate.match(organizationNotificationChannelName).notification_channel; + matchNotificationChannelFromOrganizationNotificationChannelName( + organizationNotificationChannelName: string, + ) { + return this.pathTemplates.organizationNotificationChannelPathTemplate.match( + organizationNotificationChannelName, + ).notification_channel; } /** @@ -1734,7 +2148,7 @@ export class UptimeCheckServiceClient { * @param {string} service * @returns {string} Resource name string. */ - organizationServicePath(organization:string,service:string) { + organizationServicePath(organization: string, service: string) { return this.pathTemplates.organizationServicePathTemplate.render({ organization: organization, service: service, @@ -1748,8 +2162,12 @@ export class UptimeCheckServiceClient { * A fully-qualified path representing organization_service resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationServiceName(organizationServiceName: string) { - return this.pathTemplates.organizationServicePathTemplate.match(organizationServiceName).organization; + matchOrganizationFromOrganizationServiceName( + organizationServiceName: string, + ) { + return this.pathTemplates.organizationServicePathTemplate.match( + organizationServiceName, + ).organization; } /** @@ -1760,7 +2178,9 @@ export class UptimeCheckServiceClient { * @returns {string} A string representing the service. */ matchServiceFromOrganizationServiceName(organizationServiceName: string) { - return this.pathTemplates.organizationServicePathTemplate.match(organizationServiceName).service; + return this.pathTemplates.organizationServicePathTemplate.match( + organizationServiceName, + ).service; } /** @@ -1771,12 +2191,18 @@ export class UptimeCheckServiceClient { * @param {string} service_level_objective * @returns {string} Resource name string. */ - organizationServiceServiceLevelObjectivePath(organization:string,service:string,serviceLevelObjective:string) { - return this.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.render({ - organization: organization, - service: service, - service_level_objective: serviceLevelObjective, - }); + organizationServiceServiceLevelObjectivePath( + organization: string, + service: string, + serviceLevelObjective: string, + ) { + return this.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.render( + { + organization: organization, + service: service, + service_level_objective: serviceLevelObjective, + }, + ); } /** @@ -1786,8 +2212,12 @@ export class UptimeCheckServiceClient { * A fully-qualified path representing organization_service_service_level_objective resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationServiceServiceLevelObjectiveName(organizationServiceServiceLevelObjectiveName: string) { - return this.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match(organizationServiceServiceLevelObjectiveName).organization; + matchOrganizationFromOrganizationServiceServiceLevelObjectiveName( + organizationServiceServiceLevelObjectiveName: string, + ) { + return this.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match( + organizationServiceServiceLevelObjectiveName, + ).organization; } /** @@ -1797,8 +2227,12 @@ export class UptimeCheckServiceClient { * A fully-qualified path representing organization_service_service_level_objective resource. * @returns {string} A string representing the service. */ - matchServiceFromOrganizationServiceServiceLevelObjectiveName(organizationServiceServiceLevelObjectiveName: string) { - return this.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match(organizationServiceServiceLevelObjectiveName).service; + matchServiceFromOrganizationServiceServiceLevelObjectiveName( + organizationServiceServiceLevelObjectiveName: string, + ) { + return this.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match( + organizationServiceServiceLevelObjectiveName, + ).service; } /** @@ -1808,8 +2242,12 @@ export class UptimeCheckServiceClient { * A fully-qualified path representing organization_service_service_level_objective resource. * @returns {string} A string representing the service_level_objective. */ - matchServiceLevelObjectiveFromOrganizationServiceServiceLevelObjectiveName(organizationServiceServiceLevelObjectiveName: string) { - return this.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match(organizationServiceServiceLevelObjectiveName).service_level_objective; + matchServiceLevelObjectiveFromOrganizationServiceServiceLevelObjectiveName( + organizationServiceServiceLevelObjectiveName: string, + ) { + return this.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match( + organizationServiceServiceLevelObjectiveName, + ).service_level_objective; } /** @@ -1819,7 +2257,10 @@ export class UptimeCheckServiceClient { * @param {string} uptime_check_config * @returns {string} Resource name string. */ - organizationUptimeCheckConfigPath(organization:string,uptimeCheckConfig:string) { + organizationUptimeCheckConfigPath( + organization: string, + uptimeCheckConfig: string, + ) { return this.pathTemplates.organizationUptimeCheckConfigPathTemplate.render({ organization: organization, uptime_check_config: uptimeCheckConfig, @@ -1833,8 +2274,12 @@ export class UptimeCheckServiceClient { * A fully-qualified path representing organization_uptime_check_config resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationUptimeCheckConfigName(organizationUptimeCheckConfigName: string) { - return this.pathTemplates.organizationUptimeCheckConfigPathTemplate.match(organizationUptimeCheckConfigName).organization; + matchOrganizationFromOrganizationUptimeCheckConfigName( + organizationUptimeCheckConfigName: string, + ) { + return this.pathTemplates.organizationUptimeCheckConfigPathTemplate.match( + organizationUptimeCheckConfigName, + ).organization; } /** @@ -1844,8 +2289,12 @@ export class UptimeCheckServiceClient { * A fully-qualified path representing organization_uptime_check_config resource. * @returns {string} A string representing the uptime_check_config. */ - matchUptimeCheckConfigFromOrganizationUptimeCheckConfigName(organizationUptimeCheckConfigName: string) { - return this.pathTemplates.organizationUptimeCheckConfigPathTemplate.match(organizationUptimeCheckConfigName).uptime_check_config; + matchUptimeCheckConfigFromOrganizationUptimeCheckConfigName( + organizationUptimeCheckConfigName: string, + ) { + return this.pathTemplates.organizationUptimeCheckConfigPathTemplate.match( + organizationUptimeCheckConfigName, + ).uptime_check_config; } /** @@ -1855,7 +2304,7 @@ export class UptimeCheckServiceClient { * @param {string} alert_policy * @returns {string} Resource name string. */ - projectAlertPolicyPath(project:string,alertPolicy:string) { + projectAlertPolicyPath(project: string, alertPolicy: string) { return this.pathTemplates.projectAlertPolicyPathTemplate.render({ project: project, alert_policy: alertPolicy, @@ -1870,7 +2319,9 @@ export class UptimeCheckServiceClient { * @returns {string} A string representing the project. */ matchProjectFromProjectAlertPolicyName(projectAlertPolicyName: string) { - return this.pathTemplates.projectAlertPolicyPathTemplate.match(projectAlertPolicyName).project; + return this.pathTemplates.projectAlertPolicyPathTemplate.match( + projectAlertPolicyName, + ).project; } /** @@ -1881,7 +2332,9 @@ export class UptimeCheckServiceClient { * @returns {string} A string representing the alert_policy. */ matchAlertPolicyFromProjectAlertPolicyName(projectAlertPolicyName: string) { - return this.pathTemplates.projectAlertPolicyPathTemplate.match(projectAlertPolicyName).alert_policy; + return this.pathTemplates.projectAlertPolicyPathTemplate.match( + projectAlertPolicyName, + ).alert_policy; } /** @@ -1892,7 +2345,11 @@ export class UptimeCheckServiceClient { * @param {string} condition * @returns {string} Resource name string. */ - projectAlertPolicyConditionPath(project:string,alertPolicy:string,condition:string) { + projectAlertPolicyConditionPath( + project: string, + alertPolicy: string, + condition: string, + ) { return this.pathTemplates.projectAlertPolicyConditionPathTemplate.render({ project: project, alert_policy: alertPolicy, @@ -1907,8 +2364,12 @@ export class UptimeCheckServiceClient { * A fully-qualified path representing project_alert_policy_condition resource. * @returns {string} A string representing the project. */ - matchProjectFromProjectAlertPolicyConditionName(projectAlertPolicyConditionName: string) { - return this.pathTemplates.projectAlertPolicyConditionPathTemplate.match(projectAlertPolicyConditionName).project; + matchProjectFromProjectAlertPolicyConditionName( + projectAlertPolicyConditionName: string, + ) { + return this.pathTemplates.projectAlertPolicyConditionPathTemplate.match( + projectAlertPolicyConditionName, + ).project; } /** @@ -1918,8 +2379,12 @@ export class UptimeCheckServiceClient { * A fully-qualified path representing project_alert_policy_condition resource. * @returns {string} A string representing the alert_policy. */ - matchAlertPolicyFromProjectAlertPolicyConditionName(projectAlertPolicyConditionName: string) { - return this.pathTemplates.projectAlertPolicyConditionPathTemplate.match(projectAlertPolicyConditionName).alert_policy; + matchAlertPolicyFromProjectAlertPolicyConditionName( + projectAlertPolicyConditionName: string, + ) { + return this.pathTemplates.projectAlertPolicyConditionPathTemplate.match( + projectAlertPolicyConditionName, + ).alert_policy; } /** @@ -1929,8 +2394,12 @@ export class UptimeCheckServiceClient { * A fully-qualified path representing project_alert_policy_condition resource. * @returns {string} A string representing the condition. */ - matchConditionFromProjectAlertPolicyConditionName(projectAlertPolicyConditionName: string) { - return this.pathTemplates.projectAlertPolicyConditionPathTemplate.match(projectAlertPolicyConditionName).condition; + matchConditionFromProjectAlertPolicyConditionName( + projectAlertPolicyConditionName: string, + ) { + return this.pathTemplates.projectAlertPolicyConditionPathTemplate.match( + projectAlertPolicyConditionName, + ).condition; } /** @@ -1940,7 +2409,7 @@ export class UptimeCheckServiceClient { * @param {string} channel_descriptor * @returns {string} Resource name string. */ - projectChannelDescriptorPath(project:string,channelDescriptor:string) { + projectChannelDescriptorPath(project: string, channelDescriptor: string) { return this.pathTemplates.projectChannelDescriptorPathTemplate.render({ project: project, channel_descriptor: channelDescriptor, @@ -1954,8 +2423,12 @@ export class UptimeCheckServiceClient { * A fully-qualified path representing project_channel_descriptor resource. * @returns {string} A string representing the project. */ - matchProjectFromProjectChannelDescriptorName(projectChannelDescriptorName: string) { - return this.pathTemplates.projectChannelDescriptorPathTemplate.match(projectChannelDescriptorName).project; + matchProjectFromProjectChannelDescriptorName( + projectChannelDescriptorName: string, + ) { + return this.pathTemplates.projectChannelDescriptorPathTemplate.match( + projectChannelDescriptorName, + ).project; } /** @@ -1965,8 +2438,12 @@ export class UptimeCheckServiceClient { * A fully-qualified path representing project_channel_descriptor resource. * @returns {string} A string representing the channel_descriptor. */ - matchChannelDescriptorFromProjectChannelDescriptorName(projectChannelDescriptorName: string) { - return this.pathTemplates.projectChannelDescriptorPathTemplate.match(projectChannelDescriptorName).channel_descriptor; + matchChannelDescriptorFromProjectChannelDescriptorName( + projectChannelDescriptorName: string, + ) { + return this.pathTemplates.projectChannelDescriptorPathTemplate.match( + projectChannelDescriptorName, + ).channel_descriptor; } /** @@ -1976,7 +2453,7 @@ export class UptimeCheckServiceClient { * @param {string} group * @returns {string} Resource name string. */ - projectGroupPath(project:string,group:string) { + projectGroupPath(project: string, group: string) { return this.pathTemplates.projectGroupPathTemplate.render({ project: project, group: group, @@ -1991,7 +2468,8 @@ export class UptimeCheckServiceClient { * @returns {string} A string representing the project. */ matchProjectFromProjectGroupName(projectGroupName: string) { - return this.pathTemplates.projectGroupPathTemplate.match(projectGroupName).project; + return this.pathTemplates.projectGroupPathTemplate.match(projectGroupName) + .project; } /** @@ -2002,7 +2480,8 @@ export class UptimeCheckServiceClient { * @returns {string} A string representing the group. */ matchGroupFromProjectGroupName(projectGroupName: string) { - return this.pathTemplates.projectGroupPathTemplate.match(projectGroupName).group; + return this.pathTemplates.projectGroupPathTemplate.match(projectGroupName) + .group; } /** @@ -2012,7 +2491,7 @@ export class UptimeCheckServiceClient { * @param {string} notification_channel * @returns {string} Resource name string. */ - projectNotificationChannelPath(project:string,notificationChannel:string) { + projectNotificationChannelPath(project: string, notificationChannel: string) { return this.pathTemplates.projectNotificationChannelPathTemplate.render({ project: project, notification_channel: notificationChannel, @@ -2026,8 +2505,12 @@ export class UptimeCheckServiceClient { * A fully-qualified path representing project_notification_channel resource. * @returns {string} A string representing the project. */ - matchProjectFromProjectNotificationChannelName(projectNotificationChannelName: string) { - return this.pathTemplates.projectNotificationChannelPathTemplate.match(projectNotificationChannelName).project; + matchProjectFromProjectNotificationChannelName( + projectNotificationChannelName: string, + ) { + return this.pathTemplates.projectNotificationChannelPathTemplate.match( + projectNotificationChannelName, + ).project; } /** @@ -2037,8 +2520,12 @@ export class UptimeCheckServiceClient { * A fully-qualified path representing project_notification_channel resource. * @returns {string} A string representing the notification_channel. */ - matchNotificationChannelFromProjectNotificationChannelName(projectNotificationChannelName: string) { - return this.pathTemplates.projectNotificationChannelPathTemplate.match(projectNotificationChannelName).notification_channel; + matchNotificationChannelFromProjectNotificationChannelName( + projectNotificationChannelName: string, + ) { + return this.pathTemplates.projectNotificationChannelPathTemplate.match( + projectNotificationChannelName, + ).notification_channel; } /** @@ -2048,7 +2535,7 @@ export class UptimeCheckServiceClient { * @param {string} service * @returns {string} Resource name string. */ - projectServicePath(project:string,service:string) { + projectServicePath(project: string, service: string) { return this.pathTemplates.projectServicePathTemplate.render({ project: project, service: service, @@ -2063,7 +2550,9 @@ export class UptimeCheckServiceClient { * @returns {string} A string representing the project. */ matchProjectFromProjectServiceName(projectServiceName: string) { - return this.pathTemplates.projectServicePathTemplate.match(projectServiceName).project; + return this.pathTemplates.projectServicePathTemplate.match( + projectServiceName, + ).project; } /** @@ -2074,7 +2563,9 @@ export class UptimeCheckServiceClient { * @returns {string} A string representing the service. */ matchServiceFromProjectServiceName(projectServiceName: string) { - return this.pathTemplates.projectServicePathTemplate.match(projectServiceName).service; + return this.pathTemplates.projectServicePathTemplate.match( + projectServiceName, + ).service; } /** @@ -2085,12 +2576,18 @@ export class UptimeCheckServiceClient { * @param {string} service_level_objective * @returns {string} Resource name string. */ - projectServiceServiceLevelObjectivePath(project:string,service:string,serviceLevelObjective:string) { - return this.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.render({ - project: project, - service: service, - service_level_objective: serviceLevelObjective, - }); + projectServiceServiceLevelObjectivePath( + project: string, + service: string, + serviceLevelObjective: string, + ) { + return this.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.render( + { + project: project, + service: service, + service_level_objective: serviceLevelObjective, + }, + ); } /** @@ -2100,8 +2597,12 @@ export class UptimeCheckServiceClient { * A fully-qualified path representing project_service_service_level_objective resource. * @returns {string} A string representing the project. */ - matchProjectFromProjectServiceServiceLevelObjectiveName(projectServiceServiceLevelObjectiveName: string) { - return this.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match(projectServiceServiceLevelObjectiveName).project; + matchProjectFromProjectServiceServiceLevelObjectiveName( + projectServiceServiceLevelObjectiveName: string, + ) { + return this.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match( + projectServiceServiceLevelObjectiveName, + ).project; } /** @@ -2111,8 +2612,12 @@ export class UptimeCheckServiceClient { * A fully-qualified path representing project_service_service_level_objective resource. * @returns {string} A string representing the service. */ - matchServiceFromProjectServiceServiceLevelObjectiveName(projectServiceServiceLevelObjectiveName: string) { - return this.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match(projectServiceServiceLevelObjectiveName).service; + matchServiceFromProjectServiceServiceLevelObjectiveName( + projectServiceServiceLevelObjectiveName: string, + ) { + return this.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match( + projectServiceServiceLevelObjectiveName, + ).service; } /** @@ -2122,8 +2627,12 @@ export class UptimeCheckServiceClient { * A fully-qualified path representing project_service_service_level_objective resource. * @returns {string} A string representing the service_level_objective. */ - matchServiceLevelObjectiveFromProjectServiceServiceLevelObjectiveName(projectServiceServiceLevelObjectiveName: string) { - return this.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match(projectServiceServiceLevelObjectiveName).service_level_objective; + matchServiceLevelObjectiveFromProjectServiceServiceLevelObjectiveName( + projectServiceServiceLevelObjectiveName: string, + ) { + return this.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match( + projectServiceServiceLevelObjectiveName, + ).service_level_objective; } /** @@ -2133,7 +2642,7 @@ export class UptimeCheckServiceClient { * @param {string} uptime_check_config * @returns {string} Resource name string. */ - projectUptimeCheckConfigPath(project:string,uptimeCheckConfig:string) { + projectUptimeCheckConfigPath(project: string, uptimeCheckConfig: string) { return this.pathTemplates.projectUptimeCheckConfigPathTemplate.render({ project: project, uptime_check_config: uptimeCheckConfig, @@ -2147,8 +2656,12 @@ export class UptimeCheckServiceClient { * A fully-qualified path representing project_uptime_check_config resource. * @returns {string} A string representing the project. */ - matchProjectFromProjectUptimeCheckConfigName(projectUptimeCheckConfigName: string) { - return this.pathTemplates.projectUptimeCheckConfigPathTemplate.match(projectUptimeCheckConfigName).project; + matchProjectFromProjectUptimeCheckConfigName( + projectUptimeCheckConfigName: string, + ) { + return this.pathTemplates.projectUptimeCheckConfigPathTemplate.match( + projectUptimeCheckConfigName, + ).project; } /** @@ -2158,8 +2671,12 @@ export class UptimeCheckServiceClient { * A fully-qualified path representing project_uptime_check_config resource. * @returns {string} A string representing the uptime_check_config. */ - matchUptimeCheckConfigFromProjectUptimeCheckConfigName(projectUptimeCheckConfigName: string) { - return this.pathTemplates.projectUptimeCheckConfigPathTemplate.match(projectUptimeCheckConfigName).uptime_check_config; + matchUptimeCheckConfigFromProjectUptimeCheckConfigName( + projectUptimeCheckConfigName: string, + ) { + return this.pathTemplates.projectUptimeCheckConfigPathTemplate.match( + projectUptimeCheckConfigName, + ).uptime_check_config; } /** @@ -2170,7 +2687,7 @@ export class UptimeCheckServiceClient { */ close(): Promise { if (this.uptimeCheckServiceStub && !this._terminated) { - return this.uptimeCheckServiceStub.then(stub => { + return this.uptimeCheckServiceStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -2178,4 +2695,4 @@ export class UptimeCheckServiceClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/core/generator/gapic-generator-typescript/baselines/monitoring/system-test/fixtures/sample/src/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/monitoring/system-test/fixtures/sample/src/index.ts.baseline index 561e2a128649..5fbd48949074 100644 --- a/core/generator/gapic-generator-typescript/baselines/monitoring/system-test/fixtures/sample/src/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/monitoring/system-test/fixtures/sample/src/index.ts.baseline @@ -16,7 +16,14 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -import {AlertPolicyServiceClient, GroupServiceClient, MetricServiceClient, NotificationChannelServiceClient, ServiceMonitoringServiceClient, UptimeCheckServiceClient} from 'monitoring'; +import { + AlertPolicyServiceClient, + GroupServiceClient, + MetricServiceClient, + NotificationChannelServiceClient, + ServiceMonitoringServiceClient, + UptimeCheckServiceClient, +} from 'monitoring'; // check that the client class type name can be used function doStuffWithAlertPolicyServiceClient(client: AlertPolicyServiceClient) { @@ -28,10 +35,14 @@ function doStuffWithGroupServiceClient(client: GroupServiceClient) { function doStuffWithMetricServiceClient(client: MetricServiceClient) { client.close(); } -function doStuffWithNotificationChannelServiceClient(client: NotificationChannelServiceClient) { +function doStuffWithNotificationChannelServiceClient( + client: NotificationChannelServiceClient, +) { client.close(); } -function doStuffWithServiceMonitoringServiceClient(client: ServiceMonitoringServiceClient) { +function doStuffWithServiceMonitoringServiceClient( + client: ServiceMonitoringServiceClient, +) { client.close(); } function doStuffWithUptimeCheckServiceClient(client: UptimeCheckServiceClient) { @@ -49,7 +60,8 @@ function main() { const metricServiceClient = new MetricServiceClient(); doStuffWithMetricServiceClient(metricServiceClient); // check that the client instance can be created - const notificationChannelServiceClient = new NotificationChannelServiceClient(); + const notificationChannelServiceClient = + new NotificationChannelServiceClient(); doStuffWithNotificationChannelServiceClient(notificationChannelServiceClient); // check that the client instance can be created const serviceMonitoringServiceClient = new ServiceMonitoringServiceClient(); diff --git a/core/generator/gapic-generator-typescript/baselines/monitoring/system-test/install.ts.baseline b/core/generator/gapic-generator-typescript/baselines/monitoring/system-test/install.ts.baseline index f66069aa3940..ccf167042d2e 100644 --- a/core/generator/gapic-generator-typescript/baselines/monitoring/system-test/install.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/monitoring/system-test/install.ts.baseline @@ -16,34 +16,36 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -import {packNTest} from 'pack-n-play'; -import {readFileSync} from 'fs'; -import {describe, it} from 'mocha'; +import { packNTest } from 'pack-n-play'; +import { readFileSync } from 'fs'; +import { describe, it } from 'mocha'; describe('📦 pack-n-play test', () => { - - it('TypeScript code', async function() { + it('TypeScript code', async function () { this.timeout(300000); const options = { packageDir: process.cwd(), sample: { description: 'TypeScript user can use the type definitions', - ts: readFileSync('./system-test/fixtures/sample/src/index.ts').toString() - } + ts: readFileSync( + './system-test/fixtures/sample/src/index.ts', + ).toString(), + }, }; await packNTest(options); }); - it('JavaScript code', async function() { + it('JavaScript code', async function () { this.timeout(300000); const options = { packageDir: process.cwd(), sample: { description: 'JavaScript user can use the library', - cjs: readFileSync('./system-test/fixtures/sample/src/index.js').toString() - } + cjs: readFileSync( + './system-test/fixtures/sample/src/index.js', + ).toString(), + }, }; await packNTest(options); }); - }); diff --git a/core/generator/gapic-generator-typescript/baselines/monitoring/test/gapic_alert_policy_service_v3.ts.baseline b/core/generator/gapic-generator-typescript/baselines/monitoring/test/gapic_alert_policy_service_v3.ts.baseline index ed8e28969ee3..a8ce0f6eae20 100644 --- a/core/generator/gapic-generator-typescript/baselines/monitoring/test/gapic_alert_policy_service_v3.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/monitoring/test/gapic_alert_policy_service_v3.ts.baseline @@ -19,1887 +19,2727 @@ import * as protos from '../protos/protos'; import * as assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as alertpolicyserviceModule from '../src'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; -import {protobuf} from 'google-gax'; +import { protobuf } from 'google-gax'; // Dynamically loaded proto JSON is needed to get the type information // to fill in default values for request objects -const root = protobuf.Root.fromJSON(require('../protos/protos.json')).resolveAll(); +const root = protobuf.Root.fromJSON( + require('../protos/protos.json'), +).resolveAll(); // eslint-disable-next-line @typescript-eslint/no-unused-vars function getTypeDefaultValue(typeName: string, fields: string[]) { - let type = root.lookupType(typeName) as protobuf.Type; - for (const field of fields.slice(0, -1)) { - type = type.fields[field]?.resolvedType as protobuf.Type; - } - return type.fields[fields[fields.length - 1]]?.defaultValue; + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type.fields[field]?.resolvedType as protobuf.Type; + } + return type.fields[fields[fields.length - 1]]?.defaultValue; } function generateSampleMessage(instance: T) { - const filledObject = (instance.constructor as typeof protobuf.Message) - .toObject(instance as protobuf.Message, {defaults: true}); - return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, { defaults: true }); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; } function stubSimpleCall(response?: ResponseType, error?: Error) { - return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); } -function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { - return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +function stubSimpleCallWithCallback( + response?: ResponseType, + error?: Error, +) { + return error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); } -function stubPageStreamingCall(responses?: ResponseType[], error?: Error) { - const pagingStub = sinon.stub(); - if (responses) { - for (let i = 0; i < responses.length; ++i) { - pagingStub.onCall(i).callsArgWith(2, null, responses[i]); - } +function stubPageStreamingCall( + responses?: ResponseType[], + error?: Error, +) { + const pagingStub = sinon.stub(); + if (responses) { + for (let i = 0; i < responses.length; ++i) { + pagingStub.onCall(i).callsArgWith(2, null, responses[i]); } - const transformStub = error ? sinon.stub().callsArgWith(2, error) : pagingStub; - const mockStream = new PassThrough({ - objectMode: true, - transform: transformStub, - }); - // trigger as many responses as needed - if (responses) { - for (let i = 0; i < responses.length; ++i) { - setImmediate(() => { mockStream.write({}); }); - } - setImmediate(() => { mockStream.end(); }); - } else { - setImmediate(() => { mockStream.write({}); }); - setImmediate(() => { mockStream.end(); }); + } + const transformStub = error + ? sinon.stub().callsArgWith(2, error) + : pagingStub; + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + // trigger as many responses as needed + if (responses) { + for (let i = 0; i < responses.length; ++i) { + setImmediate(() => { + mockStream.write({}); + }); } - return sinon.stub().returns(mockStream); + setImmediate(() => { + mockStream.end(); + }); + } else { + setImmediate(() => { + mockStream.write({}); + }); + setImmediate(() => { + mockStream.end(); + }); + } + return sinon.stub().returns(mockStream); } -function stubAsyncIterationCall(responses?: ResponseType[], error?: Error) { - let counter = 0; - const asyncIterable = { - [Symbol.asyncIterator]() { - return { - async next() { - if (error) { - return Promise.reject(error); - } - if (counter >= responses!.length) { - return Promise.resolve({done: true, value: undefined}); - } - return Promise.resolve({done: false, value: responses![counter++]}); - } - }; - } - }; - return sinon.stub().returns(asyncIterable); +function stubAsyncIterationCall( + responses?: ResponseType[], + error?: Error, +) { + let counter = 0; + const asyncIterable = { + [Symbol.asyncIterator]() { + return { + async next() { + if (error) { + return Promise.reject(error); + } + if (counter >= responses!.length) { + return Promise.resolve({ done: true, value: undefined }); + } + return Promise.resolve({ done: false, value: responses![counter++] }); + }, + }; + }, + }; + return sinon.stub().returns(asyncIterable); } describe('v3.AlertPolicyServiceClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'monitoring.googleapis.com'); - }); - - it('has universeDomain', () => { - const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); - - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - it('throws DeprecationWarning if static servicePath is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const servicePath = alertpolicyserviceModule.v3.AlertPolicyServiceClient.servicePath; - assert.strictEqual(servicePath, 'monitoring.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = alertpolicyserviceModule.v3.AlertPolicyServiceClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'monitoring.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'monitoring.example.com'); - }); - - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'monitoring.example.com'); - }); - - if (typeof process === 'object' && 'env' in process) { - describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { - it('sets apiEndpoint from environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'monitoring.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - - it('value configured in code has priority over environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'monitoring.configured.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { new alertpolicyserviceModule.v3.AlertPolicyServiceClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); - - it('has port', () => { - const port = alertpolicyserviceModule.v3.AlertPolicyServiceClient.port; - assert(port); - assert(typeof port === 'number'); - }); - - it('should create a client with no option', () => { - const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient(); - assert(client); - }); - - it('should create a client with gRPC fallback', () => { - const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ - fallback: true, - }); - assert(client); - }); - - it('has initialize method and supports deferred initialization', async () => { - const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.alertPolicyServiceStub, undefined); - await client.initialize(); - assert(client.alertPolicyServiceStub); - }); - - it('has close method for the initialized client', done => { - const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.alertPolicyServiceStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); - - it('has close method for the non-initialized client', done => { - const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.alertPolicyServiceStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); - - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); - }); - - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId((err?: Error|null, projectId?: string|null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } - }); - }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'monitoring.googleapis.com'); }); - describe('getAlertPolicy', () => { - it('invokes getAlertPolicy without error', async () => { - const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.GetAlertPolicyRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.GetAlertPolicyRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.monitoring.v3.AlertPolicy() - ); - client.innerApiCalls.getAlertPolicy = stubSimpleCall(expectedResponse); - const [response] = await client.getAlertPolicy(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getAlertPolicy as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getAlertPolicy as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getAlertPolicy without error using callback', async () => { - const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.GetAlertPolicyRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.GetAlertPolicyRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.monitoring.v3.AlertPolicy() - ); - client.innerApiCalls.getAlertPolicy = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getAlertPolicy( - request, - (err?: Error|null, result?: protos.google.monitoring.v3.IAlertPolicy|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getAlertPolicy as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getAlertPolicy as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getAlertPolicy with error', async () => { - const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.GetAlertPolicyRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.GetAlertPolicyRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getAlertPolicy = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getAlertPolicy(request), expectedError); - const actualRequest = (client.innerApiCalls.getAlertPolicy as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getAlertPolicy as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getAlertPolicy with closed client', async () => { - const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.GetAlertPolicyRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.GetAlertPolicyRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getAlertPolicy(request), expectedError); - }); + it('has universeDomain', () => { + const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); }); - describe('createAlertPolicy', () => { - it('invokes createAlertPolicy without error', async () => { - const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.CreateAlertPolicyRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.CreateAlertPolicyRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.monitoring.v3.AlertPolicy() - ); - client.innerApiCalls.createAlertPolicy = stubSimpleCall(expectedResponse); - const [response] = await client.createAlertPolicy(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createAlertPolicy as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createAlertPolicy as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createAlertPolicy without error using callback', async () => { - const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.CreateAlertPolicyRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.CreateAlertPolicyRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.monitoring.v3.AlertPolicy() - ); - client.innerApiCalls.createAlertPolicy = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createAlertPolicy( - request, - (err?: Error|null, result?: protos.google.monitoring.v3.IAlertPolicy|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createAlertPolicy as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createAlertPolicy as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createAlertPolicy with error', async () => { - const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.CreateAlertPolicyRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.CreateAlertPolicyRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createAlertPolicy = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createAlertPolicy(request), expectedError); - const actualRequest = (client.innerApiCalls.createAlertPolicy as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createAlertPolicy as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createAlertPolicy with closed client', async () => { - const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.CreateAlertPolicyRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.CreateAlertPolicyRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createAlertPolicy(request), expectedError); - }); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = + alertpolicyserviceModule.v3.AlertPolicyServiceClient.servicePath; + assert.strictEqual(servicePath, 'monitoring.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + alertpolicyserviceModule.v3.AlertPolicyServiceClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'monitoring.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ + universeDomain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'monitoring.example.com'); }); - describe('deleteAlertPolicy', () => { - it('invokes deleteAlertPolicy without error', async () => { - const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.DeleteAlertPolicyRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.DeleteAlertPolicyRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteAlertPolicy = stubSimpleCall(expectedResponse); - const [response] = await client.deleteAlertPolicy(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteAlertPolicy as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteAlertPolicy as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ + universe_domain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'monitoring.example.com'); + }); - it('invokes deleteAlertPolicy without error using callback', async () => { - const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.DeleteAlertPolicyRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.DeleteAlertPolicyRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteAlertPolicy = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteAlertPolicy( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteAlertPolicy as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteAlertPolicy as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + if (typeof process === 'object' && 'env' in process) { + describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { + it('sets apiEndpoint from environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = + new alertpolicyserviceModule.v3.AlertPolicyServiceClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'monitoring.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - it('invokes deleteAlertPolicy with error', async () => { - const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.DeleteAlertPolicyRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.DeleteAlertPolicyRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteAlertPolicy = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteAlertPolicy(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteAlertPolicy as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteAlertPolicy as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('value configured in code has priority over environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = + new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ + universeDomain: 'configured.example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'monitoring.configured.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - - it('invokes deleteAlertPolicy with closed client', async () => { - const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.DeleteAlertPolicyRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.DeleteAlertPolicyRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteAlertPolicy(request), expectedError); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); }); - describe('updateAlertPolicy', () => { - it('invokes updateAlertPolicy without error', async () => { - const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.UpdateAlertPolicyRequest() - ); - request.alertPolicy ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.UpdateAlertPolicyRequest', ['alertPolicy', 'name']); - request.alertPolicy.name = defaultValue1; - const expectedHeaderRequestParams = `alert_policy.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.monitoring.v3.AlertPolicy() - ); - client.innerApiCalls.updateAlertPolicy = stubSimpleCall(expectedResponse); - const [response] = await client.updateAlertPolicy(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateAlertPolicy as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateAlertPolicy as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateAlertPolicy without error using callback', async () => { - const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.UpdateAlertPolicyRequest() - ); - request.alertPolicy ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.UpdateAlertPolicyRequest', ['alertPolicy', 'name']); - request.alertPolicy.name = defaultValue1; - const expectedHeaderRequestParams = `alert_policy.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.monitoring.v3.AlertPolicy() - ); - client.innerApiCalls.updateAlertPolicy = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateAlertPolicy( - request, - (err?: Error|null, result?: protos.google.monitoring.v3.IAlertPolicy|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateAlertPolicy as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateAlertPolicy as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has port', () => { + const port = alertpolicyserviceModule.v3.AlertPolicyServiceClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('invokes updateAlertPolicy with error', async () => { - const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.UpdateAlertPolicyRequest() - ); - request.alertPolicy ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.UpdateAlertPolicyRequest', ['alertPolicy', 'name']); - request.alertPolicy.name = defaultValue1; - const expectedHeaderRequestParams = `alert_policy.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateAlertPolicy = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateAlertPolicy(request), expectedError); - const actualRequest = (client.innerApiCalls.updateAlertPolicy as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateAlertPolicy as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('should create a client with no option', () => { + const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient(); + assert(client); + }); - it('invokes updateAlertPolicy with closed client', async () => { - const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.UpdateAlertPolicyRequest() - ); - request.alertPolicy ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.UpdateAlertPolicyRequest', ['alertPolicy', 'name']); - request.alertPolicy.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateAlertPolicy(request), expectedError); - }); + it('should create a client with gRPC fallback', () => { + const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ + fallback: true, + }); + assert(client); }); - describe('listAlertPolicies', () => { - it('invokes listAlertPolicies without error', async () => { - const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListAlertPoliciesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListAlertPoliciesRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.monitoring.v3.AlertPolicy()), - generateSampleMessage(new protos.google.monitoring.v3.AlertPolicy()), - generateSampleMessage(new protos.google.monitoring.v3.AlertPolicy()), - ]; - client.innerApiCalls.listAlertPolicies = stubSimpleCall(expectedResponse); - const [response] = await client.listAlertPolicies(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listAlertPolicies as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listAlertPolicies as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has initialize method and supports deferred initialization', async () => { + const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.alertPolicyServiceStub, undefined); + await client.initialize(); + assert(client.alertPolicyServiceStub); + }); - it('invokes listAlertPolicies without error using callback', async () => { - const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListAlertPoliciesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListAlertPoliciesRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.monitoring.v3.AlertPolicy()), - generateSampleMessage(new protos.google.monitoring.v3.AlertPolicy()), - generateSampleMessage(new protos.google.monitoring.v3.AlertPolicy()), - ]; - client.innerApiCalls.listAlertPolicies = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listAlertPolicies( - request, - (err?: Error|null, result?: protos.google.monitoring.v3.IAlertPolicy[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listAlertPolicies as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listAlertPolicies as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('has close method for the initialized client', (done) => { + const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.alertPolicyServiceStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes listAlertPolicies with error', async () => { - const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListAlertPoliciesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListAlertPoliciesRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listAlertPolicies = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listAlertPolicies(request), expectedError); - const actualRequest = (client.innerApiCalls.listAlertPolicies as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listAlertPolicies as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('has close method for the non-initialized client', (done) => { + const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.alertPolicyServiceStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes listAlertPoliciesStream without error', async () => { - const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListAlertPoliciesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListAlertPoliciesRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.monitoring.v3.AlertPolicy()), - generateSampleMessage(new protos.google.monitoring.v3.AlertPolicy()), - generateSampleMessage(new protos.google.monitoring.v3.AlertPolicy()), - ]; - client.descriptors.page.listAlertPolicies.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listAlertPoliciesStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.monitoring.v3.AlertPolicy[] = []; - stream.on('data', (response: protos.google.monitoring.v3.AlertPolicy) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.listAlertPolicies.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listAlertPolicies, request)); - assert( - (client.descriptors.page.listAlertPolicies.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + }); - it('invokes listAlertPoliciesStream with error', async () => { - const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListAlertPoliciesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListAlertPoliciesRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listAlertPolicies.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listAlertPoliciesStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.monitoring.v3.AlertPolicy[] = []; - stream.on('data', (response: protos.google.monitoring.v3.AlertPolicy) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listAlertPolicies.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listAlertPolicies, request)); - assert( - (client.descriptors.page.listAlertPolicies.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + }); + + describe('getAlertPolicy', () => { + it('invokes getAlertPolicy without error', async () => { + const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.GetAlertPolicyRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.GetAlertPolicyRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.monitoring.v3.AlertPolicy(), + ); + client.innerApiCalls.getAlertPolicy = stubSimpleCall(expectedResponse); + const [response] = await client.getAlertPolicy(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getAlertPolicy as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getAlertPolicy as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('uses async iteration with listAlertPolicies without error', async () => { - const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListAlertPoliciesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListAlertPoliciesRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.monitoring.v3.AlertPolicy()), - generateSampleMessage(new protos.google.monitoring.v3.AlertPolicy()), - generateSampleMessage(new protos.google.monitoring.v3.AlertPolicy()), - ]; - client.descriptors.page.listAlertPolicies.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.monitoring.v3.IAlertPolicy[] = []; - const iterable = client.listAlertPoliciesAsync(request); - for await (const resource of iterable) { - responses.push(resource!); + it('invokes getAlertPolicy without error using callback', async () => { + const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.GetAlertPolicyRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.GetAlertPolicyRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.monitoring.v3.AlertPolicy(), + ); + client.innerApiCalls.getAlertPolicy = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getAlertPolicy( + request, + ( + err?: Error | null, + result?: protos.google.monitoring.v3.IAlertPolicy | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listAlertPolicies.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listAlertPolicies.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); - - it('uses async iteration with listAlertPolicies with error', async () => { - const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListAlertPoliciesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListAlertPoliciesRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listAlertPolicies.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listAlertPoliciesAsync(request); - await assert.rejects(async () => { - const responses: protos.google.monitoring.v3.IAlertPolicy[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listAlertPolicies.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listAlertPolicies.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getAlertPolicy as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getAlertPolicy as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('Path templates', () => { - - describe('folderAlertPolicy', async () => { - const fakePath = "/rendered/path/folderAlertPolicy"; - const expectedParameters = { - folder: "folderValue", - alert_policy: "alertPolicyValue", - }; - const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.folderAlertPolicyPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderAlertPolicyPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderAlertPolicyPath', () => { - const result = client.folderAlertPolicyPath("folderValue", "alertPolicyValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderAlertPolicyPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderAlertPolicyName', () => { - const result = client.matchFolderFromFolderAlertPolicyName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderAlertPolicyPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchAlertPolicyFromFolderAlertPolicyName', () => { - const result = client.matchAlertPolicyFromFolderAlertPolicyName(fakePath); - assert.strictEqual(result, "alertPolicyValue"); - assert((client.pathTemplates.folderAlertPolicyPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('folderAlertPolicyCondition', async () => { - const fakePath = "/rendered/path/folderAlertPolicyCondition"; - const expectedParameters = { - folder: "folderValue", - alert_policy: "alertPolicyValue", - condition: "conditionValue", - }; - const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.folderAlertPolicyConditionPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderAlertPolicyConditionPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderAlertPolicyConditionPath', () => { - const result = client.folderAlertPolicyConditionPath("folderValue", "alertPolicyValue", "conditionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderAlertPolicyConditionPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderAlertPolicyConditionName', () => { - const result = client.matchFolderFromFolderAlertPolicyConditionName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderAlertPolicyConditionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchAlertPolicyFromFolderAlertPolicyConditionName', () => { - const result = client.matchAlertPolicyFromFolderAlertPolicyConditionName(fakePath); - assert.strictEqual(result, "alertPolicyValue"); - assert((client.pathTemplates.folderAlertPolicyConditionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchConditionFromFolderAlertPolicyConditionName', () => { - const result = client.matchConditionFromFolderAlertPolicyConditionName(fakePath); - assert.strictEqual(result, "conditionValue"); - assert((client.pathTemplates.folderAlertPolicyConditionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('folderChannelDescriptor', async () => { - const fakePath = "/rendered/path/folderChannelDescriptor"; - const expectedParameters = { - folder: "folderValue", - channel_descriptor: "channelDescriptorValue", - }; - const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.folderChannelDescriptorPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderChannelDescriptorPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderChannelDescriptorPath', () => { - const result = client.folderChannelDescriptorPath("folderValue", "channelDescriptorValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderChannelDescriptorPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderChannelDescriptorName', () => { - const result = client.matchFolderFromFolderChannelDescriptorName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderChannelDescriptorPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchChannelDescriptorFromFolderChannelDescriptorName', () => { - const result = client.matchChannelDescriptorFromFolderChannelDescriptorName(fakePath); - assert.strictEqual(result, "channelDescriptorValue"); - assert((client.pathTemplates.folderChannelDescriptorPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('folderGroup', async () => { - const fakePath = "/rendered/path/folderGroup"; - const expectedParameters = { - folder: "folderValue", - group: "groupValue", - }; - const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.folderGroupPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderGroupPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderGroupPath', () => { - const result = client.folderGroupPath("folderValue", "groupValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderGroupPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderGroupName', () => { - const result = client.matchFolderFromFolderGroupName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderGroupPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchGroupFromFolderGroupName', () => { - const result = client.matchGroupFromFolderGroupName(fakePath); - assert.strictEqual(result, "groupValue"); - assert((client.pathTemplates.folderGroupPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('folderNotificationChannel', async () => { - const fakePath = "/rendered/path/folderNotificationChannel"; - const expectedParameters = { - folder: "folderValue", - notification_channel: "notificationChannelValue", - }; - const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.folderNotificationChannelPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderNotificationChannelPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderNotificationChannelPath', () => { - const result = client.folderNotificationChannelPath("folderValue", "notificationChannelValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderNotificationChannelPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderNotificationChannelName', () => { - const result = client.matchFolderFromFolderNotificationChannelName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderNotificationChannelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchNotificationChannelFromFolderNotificationChannelName', () => { - const result = client.matchNotificationChannelFromFolderNotificationChannelName(fakePath); - assert.strictEqual(result, "notificationChannelValue"); - assert((client.pathTemplates.folderNotificationChannelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('folderService', async () => { - const fakePath = "/rendered/path/folderService"; - const expectedParameters = { - folder: "folderValue", - service: "serviceValue", - }; - const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.folderServicePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderServicePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderServicePath', () => { - const result = client.folderServicePath("folderValue", "serviceValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderServicePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderServiceName', () => { - const result = client.matchFolderFromFolderServiceName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderServicePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServiceFromFolderServiceName', () => { - const result = client.matchServiceFromFolderServiceName(fakePath); - assert.strictEqual(result, "serviceValue"); - assert((client.pathTemplates.folderServicePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('folderServiceServiceLevelObjective', async () => { - const fakePath = "/rendered/path/folderServiceServiceLevelObjective"; - const expectedParameters = { - folder: "folderValue", - service: "serviceValue", - service_level_objective: "serviceLevelObjectiveValue", - }; - const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderServiceServiceLevelObjectivePath', () => { - const result = client.folderServiceServiceLevelObjectivePath("folderValue", "serviceValue", "serviceLevelObjectiveValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderServiceServiceLevelObjectiveName', () => { - const result = client.matchFolderFromFolderServiceServiceLevelObjectiveName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServiceFromFolderServiceServiceLevelObjectiveName', () => { - const result = client.matchServiceFromFolderServiceServiceLevelObjectiveName(fakePath); - assert.strictEqual(result, "serviceValue"); - assert((client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServiceLevelObjectiveFromFolderServiceServiceLevelObjectiveName', () => { - const result = client.matchServiceLevelObjectiveFromFolderServiceServiceLevelObjectiveName(fakePath); - assert.strictEqual(result, "serviceLevelObjectiveValue"); - assert((client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('folderUptimeCheckConfig', async () => { - const fakePath = "/rendered/path/folderUptimeCheckConfig"; - const expectedParameters = { - folder: "folderValue", - uptime_check_config: "uptimeCheckConfigValue", - }; - const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.folderUptimeCheckConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderUptimeCheckConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderUptimeCheckConfigPath', () => { - const result = client.folderUptimeCheckConfigPath("folderValue", "uptimeCheckConfigValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderUptimeCheckConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderUptimeCheckConfigName', () => { - const result = client.matchFolderFromFolderUptimeCheckConfigName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderUptimeCheckConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchUptimeCheckConfigFromFolderUptimeCheckConfigName', () => { - const result = client.matchUptimeCheckConfigFromFolderUptimeCheckConfigName(fakePath); - assert.strictEqual(result, "uptimeCheckConfigValue"); - assert((client.pathTemplates.folderUptimeCheckConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('organizationAlertPolicy', async () => { - const fakePath = "/rendered/path/organizationAlertPolicy"; - const expectedParameters = { - organization: "organizationValue", - alert_policy: "alertPolicyValue", - }; - const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.organizationAlertPolicyPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationAlertPolicyPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationAlertPolicyPath', () => { - const result = client.organizationAlertPolicyPath("organizationValue", "alertPolicyValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationAlertPolicyPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationAlertPolicyName', () => { - const result = client.matchOrganizationFromOrganizationAlertPolicyName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationAlertPolicyPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchAlertPolicyFromOrganizationAlertPolicyName', () => { - const result = client.matchAlertPolicyFromOrganizationAlertPolicyName(fakePath); - assert.strictEqual(result, "alertPolicyValue"); - assert((client.pathTemplates.organizationAlertPolicyPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('invokes getAlertPolicy with error', async () => { + const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.GetAlertPolicyRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.GetAlertPolicyRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getAlertPolicy = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getAlertPolicy(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getAlertPolicy as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getAlertPolicy as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - describe('organizationAlertPolicyCondition', async () => { - const fakePath = "/rendered/path/organizationAlertPolicyCondition"; - const expectedParameters = { - organization: "organizationValue", - alert_policy: "alertPolicyValue", - condition: "conditionValue", - }; - const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.organizationAlertPolicyConditionPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationAlertPolicyConditionPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationAlertPolicyConditionPath', () => { - const result = client.organizationAlertPolicyConditionPath("organizationValue", "alertPolicyValue", "conditionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationAlertPolicyConditionPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + it('invokes getAlertPolicy with closed client', async () => { + const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.GetAlertPolicyRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.GetAlertPolicyRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getAlertPolicy(request), expectedError); + }); + }); + + describe('createAlertPolicy', () => { + it('invokes createAlertPolicy without error', async () => { + const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.CreateAlertPolicyRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.CreateAlertPolicyRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.monitoring.v3.AlertPolicy(), + ); + client.innerApiCalls.createAlertPolicy = stubSimpleCall(expectedResponse); + const [response] = await client.createAlertPolicy(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createAlertPolicy as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createAlertPolicy as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('matchOrganizationFromOrganizationAlertPolicyConditionName', () => { - const result = client.matchOrganizationFromOrganizationAlertPolicyConditionName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationAlertPolicyConditionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('invokes createAlertPolicy without error using callback', async () => { + const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.CreateAlertPolicyRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.CreateAlertPolicyRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.monitoring.v3.AlertPolicy(), + ); + client.innerApiCalls.createAlertPolicy = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createAlertPolicy( + request, + ( + err?: Error | null, + result?: protos.google.monitoring.v3.IAlertPolicy | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createAlertPolicy as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createAlertPolicy as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('matchAlertPolicyFromOrganizationAlertPolicyConditionName', () => { - const result = client.matchAlertPolicyFromOrganizationAlertPolicyConditionName(fakePath); - assert.strictEqual(result, "alertPolicyValue"); - assert((client.pathTemplates.organizationAlertPolicyConditionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('invokes createAlertPolicy with error', async () => { + const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.CreateAlertPolicyRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.CreateAlertPolicyRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createAlertPolicy = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.createAlertPolicy(request), expectedError); + const actualRequest = ( + client.innerApiCalls.createAlertPolicy as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createAlertPolicy as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('matchConditionFromOrganizationAlertPolicyConditionName', () => { - const result = client.matchConditionFromOrganizationAlertPolicyConditionName(fakePath); - assert.strictEqual(result, "conditionValue"); - assert((client.pathTemplates.organizationAlertPolicyConditionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('invokes createAlertPolicy with closed client', async () => { + const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.CreateAlertPolicyRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.CreateAlertPolicyRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.createAlertPolicy(request), expectedError); + }); + }); + + describe('deleteAlertPolicy', () => { + it('invokes deleteAlertPolicy without error', async () => { + const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.DeleteAlertPolicyRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.DeleteAlertPolicyRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteAlertPolicy = stubSimpleCall(expectedResponse); + const [response] = await client.deleteAlertPolicy(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteAlertPolicy as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteAlertPolicy as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - describe('organizationChannelDescriptor', async () => { - const fakePath = "/rendered/path/organizationChannelDescriptor"; - const expectedParameters = { - organization: "organizationValue", - channel_descriptor: "channelDescriptorValue", - }; - const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.organizationChannelDescriptorPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationChannelDescriptorPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationChannelDescriptorPath', () => { - const result = client.organizationChannelDescriptorPath("organizationValue", "channelDescriptorValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationChannelDescriptorPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + it('invokes deleteAlertPolicy without error using callback', async () => { + const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.DeleteAlertPolicyRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.DeleteAlertPolicyRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteAlertPolicy = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteAlertPolicy( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteAlertPolicy as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteAlertPolicy as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('matchOrganizationFromOrganizationChannelDescriptorName', () => { - const result = client.matchOrganizationFromOrganizationChannelDescriptorName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationChannelDescriptorPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('invokes deleteAlertPolicy with error', async () => { + const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.DeleteAlertPolicyRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.DeleteAlertPolicyRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteAlertPolicy = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.deleteAlertPolicy(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteAlertPolicy as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteAlertPolicy as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('matchChannelDescriptorFromOrganizationChannelDescriptorName', () => { - const result = client.matchChannelDescriptorFromOrganizationChannelDescriptorName(fakePath); - assert.strictEqual(result, "channelDescriptorValue"); - assert((client.pathTemplates.organizationChannelDescriptorPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('invokes deleteAlertPolicy with closed client', async () => { + const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.DeleteAlertPolicyRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.DeleteAlertPolicyRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.deleteAlertPolicy(request), expectedError); + }); + }); + + describe('updateAlertPolicy', () => { + it('invokes updateAlertPolicy without error', async () => { + const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.UpdateAlertPolicyRequest(), + ); + request.alertPolicy ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.UpdateAlertPolicyRequest', + ['alertPolicy', 'name'], + ); + request.alertPolicy.name = defaultValue1; + const expectedHeaderRequestParams = `alert_policy.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.monitoring.v3.AlertPolicy(), + ); + client.innerApiCalls.updateAlertPolicy = stubSimpleCall(expectedResponse); + const [response] = await client.updateAlertPolicy(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateAlertPolicy as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateAlertPolicy as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - describe('organizationGroup', async () => { - const fakePath = "/rendered/path/organizationGroup"; - const expectedParameters = { - organization: "organizationValue", - group: "groupValue", - }; - const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.organizationGroupPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationGroupPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationGroupPath', () => { - const result = client.organizationGroupPath("organizationValue", "groupValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationGroupPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + it('invokes updateAlertPolicy without error using callback', async () => { + const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.UpdateAlertPolicyRequest(), + ); + request.alertPolicy ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.UpdateAlertPolicyRequest', + ['alertPolicy', 'name'], + ); + request.alertPolicy.name = defaultValue1; + const expectedHeaderRequestParams = `alert_policy.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.monitoring.v3.AlertPolicy(), + ); + client.innerApiCalls.updateAlertPolicy = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateAlertPolicy( + request, + ( + err?: Error | null, + result?: protos.google.monitoring.v3.IAlertPolicy | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateAlertPolicy as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateAlertPolicy as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('matchOrganizationFromOrganizationGroupName', () => { - const result = client.matchOrganizationFromOrganizationGroupName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationGroupPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('invokes updateAlertPolicy with error', async () => { + const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.UpdateAlertPolicyRequest(), + ); + request.alertPolicy ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.UpdateAlertPolicyRequest', + ['alertPolicy', 'name'], + ); + request.alertPolicy.name = defaultValue1; + const expectedHeaderRequestParams = `alert_policy.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateAlertPolicy = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.updateAlertPolicy(request), expectedError); + const actualRequest = ( + client.innerApiCalls.updateAlertPolicy as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateAlertPolicy as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('matchGroupFromOrganizationGroupName', () => { - const result = client.matchGroupFromOrganizationGroupName(fakePath); - assert.strictEqual(result, "groupValue"); - assert((client.pathTemplates.organizationGroupPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('invokes updateAlertPolicy with closed client', async () => { + const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.UpdateAlertPolicyRequest(), + ); + request.alertPolicy ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.UpdateAlertPolicyRequest', + ['alertPolicy', 'name'], + ); + request.alertPolicy.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.updateAlertPolicy(request), expectedError); + }); + }); + + describe('listAlertPolicies', () => { + it('invokes listAlertPolicies without error', async () => { + const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListAlertPoliciesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListAlertPoliciesRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.monitoring.v3.AlertPolicy()), + generateSampleMessage(new protos.google.monitoring.v3.AlertPolicy()), + generateSampleMessage(new protos.google.monitoring.v3.AlertPolicy()), + ]; + client.innerApiCalls.listAlertPolicies = stubSimpleCall(expectedResponse); + const [response] = await client.listAlertPolicies(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listAlertPolicies as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listAlertPolicies as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - describe('organizationNotificationChannel', async () => { - const fakePath = "/rendered/path/organizationNotificationChannel"; - const expectedParameters = { - organization: "organizationValue", - notification_channel: "notificationChannelValue", - }; - const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.organizationNotificationChannelPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationNotificationChannelPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationNotificationChannelPath', () => { - const result = client.organizationNotificationChannelPath("organizationValue", "notificationChannelValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationNotificationChannelPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + it('invokes listAlertPolicies without error using callback', async () => { + const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListAlertPoliciesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListAlertPoliciesRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.monitoring.v3.AlertPolicy()), + generateSampleMessage(new protos.google.monitoring.v3.AlertPolicy()), + generateSampleMessage(new protos.google.monitoring.v3.AlertPolicy()), + ]; + client.innerApiCalls.listAlertPolicies = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listAlertPolicies( + request, + ( + err?: Error | null, + result?: protos.google.monitoring.v3.IAlertPolicy[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listAlertPolicies as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listAlertPolicies as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('matchOrganizationFromOrganizationNotificationChannelName', () => { - const result = client.matchOrganizationFromOrganizationNotificationChannelName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationNotificationChannelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('invokes listAlertPolicies with error', async () => { + const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListAlertPoliciesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListAlertPoliciesRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listAlertPolicies = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listAlertPolicies(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listAlertPolicies as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listAlertPolicies as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('matchNotificationChannelFromOrganizationNotificationChannelName', () => { - const result = client.matchNotificationChannelFromOrganizationNotificationChannelName(fakePath); - assert.strictEqual(result, "notificationChannelValue"); - assert((client.pathTemplates.organizationNotificationChannelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('invokes listAlertPoliciesStream without error', async () => { + const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListAlertPoliciesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListAlertPoliciesRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.monitoring.v3.AlertPolicy()), + generateSampleMessage(new protos.google.monitoring.v3.AlertPolicy()), + generateSampleMessage(new protos.google.monitoring.v3.AlertPolicy()), + ]; + client.descriptors.page.listAlertPolicies.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listAlertPoliciesStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.monitoring.v3.AlertPolicy[] = []; + stream.on( + 'data', + (response: protos.google.monitoring.v3.AlertPolicy) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); }); - - describe('organizationService', async () => { - const fakePath = "/rendered/path/organizationService"; - const expectedParameters = { - organization: "organizationValue", - service: "serviceValue", - }; - const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.organizationServicePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationServicePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationServicePath', () => { - const result = client.organizationServicePath("organizationValue", "serviceValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationServicePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationServiceName', () => { - const result = client.matchOrganizationFromOrganizationServiceName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationServicePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServiceFromOrganizationServiceName', () => { - const result = client.matchServiceFromOrganizationServiceName(fakePath); - assert.strictEqual(result, "serviceValue"); - assert((client.pathTemplates.organizationServicePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + stream.on('error', (err: Error) => { + reject(err); }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listAlertPolicies.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listAlertPolicies, request), + ); + assert( + (client.descriptors.page.listAlertPolicies.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - describe('organizationServiceServiceLevelObjective', async () => { - const fakePath = "/rendered/path/organizationServiceServiceLevelObjective"; - const expectedParameters = { - organization: "organizationValue", - service: "serviceValue", - service_level_objective: "serviceLevelObjectiveValue", - }; - const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationServiceServiceLevelObjectivePath', () => { - const result = client.organizationServiceServiceLevelObjectivePath("organizationValue", "serviceValue", "serviceLevelObjectiveValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationServiceServiceLevelObjectiveName', () => { - const result = client.matchOrganizationFromOrganizationServiceServiceLevelObjectiveName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServiceFromOrganizationServiceServiceLevelObjectiveName', () => { - const result = client.matchServiceFromOrganizationServiceServiceLevelObjectiveName(fakePath); - assert.strictEqual(result, "serviceValue"); - assert((client.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServiceLevelObjectiveFromOrganizationServiceServiceLevelObjectiveName', () => { - const result = client.matchServiceLevelObjectiveFromOrganizationServiceServiceLevelObjectiveName(fakePath); - assert.strictEqual(result, "serviceLevelObjectiveValue"); - assert((client.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('invokes listAlertPoliciesStream with error', async () => { + const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListAlertPoliciesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListAlertPoliciesRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listAlertPolicies.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listAlertPoliciesStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.monitoring.v3.AlertPolicy[] = []; + stream.on( + 'data', + (response: protos.google.monitoring.v3.AlertPolicy) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); }); - - describe('organizationUptimeCheckConfig', async () => { - const fakePath = "/rendered/path/organizationUptimeCheckConfig"; - const expectedParameters = { - organization: "organizationValue", - uptime_check_config: "uptimeCheckConfigValue", - }; - const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.organizationUptimeCheckConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationUptimeCheckConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationUptimeCheckConfigPath', () => { - const result = client.organizationUptimeCheckConfigPath("organizationValue", "uptimeCheckConfigValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationUptimeCheckConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationUptimeCheckConfigName', () => { - const result = client.matchOrganizationFromOrganizationUptimeCheckConfigName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationUptimeCheckConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchUptimeCheckConfigFromOrganizationUptimeCheckConfigName', () => { - const result = client.matchUptimeCheckConfigFromOrganizationUptimeCheckConfigName(fakePath); - assert.strictEqual(result, "uptimeCheckConfigValue"); - assert((client.pathTemplates.organizationUptimeCheckConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + stream.on('error', (err: Error) => { + reject(err); }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listAlertPolicies.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listAlertPolicies, request), + ); + assert( + (client.descriptors.page.listAlertPolicies.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - describe('projectAlertPolicy', async () => { - const fakePath = "/rendered/path/projectAlertPolicy"; - const expectedParameters = { - project: "projectValue", - alert_policy: "alertPolicyValue", - }; - const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.projectAlertPolicyPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectAlertPolicyPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectAlertPolicyPath', () => { - const result = client.projectAlertPolicyPath("projectValue", "alertPolicyValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectAlertPolicyPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectAlertPolicyName', () => { - const result = client.matchProjectFromProjectAlertPolicyName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectAlertPolicyPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('uses async iteration with listAlertPolicies without error', async () => { + const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListAlertPoliciesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListAlertPoliciesRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.monitoring.v3.AlertPolicy()), + generateSampleMessage(new protos.google.monitoring.v3.AlertPolicy()), + generateSampleMessage(new protos.google.monitoring.v3.AlertPolicy()), + ]; + client.descriptors.page.listAlertPolicies.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.monitoring.v3.IAlertPolicy[] = []; + const iterable = client.listAlertPoliciesAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listAlertPolicies.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listAlertPolicies.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('matchAlertPolicyFromProjectAlertPolicyName', () => { - const result = client.matchAlertPolicyFromProjectAlertPolicyName(fakePath); - assert.strictEqual(result, "alertPolicyValue"); - assert((client.pathTemplates.projectAlertPolicyPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('uses async iteration with listAlertPolicies with error', async () => { + const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListAlertPoliciesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListAlertPoliciesRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listAlertPolicies.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listAlertPoliciesAsync(request); + await assert.rejects(async () => { + const responses: protos.google.monitoring.v3.IAlertPolicy[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listAlertPolicies.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listAlertPolicies.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + }); + + describe('Path templates', () => { + describe('folderAlertPolicy', async () => { + const fakePath = '/rendered/path/folderAlertPolicy'; + const expectedParameters = { + folder: 'folderValue', + alert_policy: 'alertPolicyValue', + }; + const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.folderAlertPolicyPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderAlertPolicyPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderAlertPolicyPath', () => { + const result = client.folderAlertPolicyPath( + 'folderValue', + 'alertPolicyValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.folderAlertPolicyPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderAlertPolicyName', () => { + const result = client.matchFolderFromFolderAlertPolicyName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + ( + client.pathTemplates.folderAlertPolicyPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchAlertPolicyFromFolderAlertPolicyName', () => { + const result = + client.matchAlertPolicyFromFolderAlertPolicyName(fakePath); + assert.strictEqual(result, 'alertPolicyValue'); + assert( + ( + client.pathTemplates.folderAlertPolicyPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectAlertPolicyCondition', async () => { - const fakePath = "/rendered/path/projectAlertPolicyCondition"; - const expectedParameters = { - project: "projectValue", - alert_policy: "alertPolicyValue", - condition: "conditionValue", - }; - const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.projectAlertPolicyConditionPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectAlertPolicyConditionPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectAlertPolicyConditionPath', () => { - const result = client.projectAlertPolicyConditionPath("projectValue", "alertPolicyValue", "conditionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectAlertPolicyConditionPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + describe('folderAlertPolicyCondition', async () => { + const fakePath = '/rendered/path/folderAlertPolicyCondition'; + const expectedParameters = { + folder: 'folderValue', + alert_policy: 'alertPolicyValue', + condition: 'conditionValue', + }; + const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.folderAlertPolicyConditionPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderAlertPolicyConditionPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderAlertPolicyConditionPath', () => { + const result = client.folderAlertPolicyConditionPath( + 'folderValue', + 'alertPolicyValue', + 'conditionValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.folderAlertPolicyConditionPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderAlertPolicyConditionName', () => { + const result = + client.matchFolderFromFolderAlertPolicyConditionName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + ( + client.pathTemplates.folderAlertPolicyConditionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchAlertPolicyFromFolderAlertPolicyConditionName', () => { + const result = + client.matchAlertPolicyFromFolderAlertPolicyConditionName(fakePath); + assert.strictEqual(result, 'alertPolicyValue'); + assert( + ( + client.pathTemplates.folderAlertPolicyConditionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchConditionFromFolderAlertPolicyConditionName', () => { + const result = + client.matchConditionFromFolderAlertPolicyConditionName(fakePath); + assert.strictEqual(result, 'conditionValue'); + assert( + ( + client.pathTemplates.folderAlertPolicyConditionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchProjectFromProjectAlertPolicyConditionName', () => { - const result = client.matchProjectFromProjectAlertPolicyConditionName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectAlertPolicyConditionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('folderChannelDescriptor', async () => { + const fakePath = '/rendered/path/folderChannelDescriptor'; + const expectedParameters = { + folder: 'folderValue', + channel_descriptor: 'channelDescriptorValue', + }; + const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.folderChannelDescriptorPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderChannelDescriptorPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderChannelDescriptorPath', () => { + const result = client.folderChannelDescriptorPath( + 'folderValue', + 'channelDescriptorValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.folderChannelDescriptorPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderChannelDescriptorName', () => { + const result = + client.matchFolderFromFolderChannelDescriptorName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + ( + client.pathTemplates.folderChannelDescriptorPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchChannelDescriptorFromFolderChannelDescriptorName', () => { + const result = + client.matchChannelDescriptorFromFolderChannelDescriptorName( + fakePath, + ); + assert.strictEqual(result, 'channelDescriptorValue'); + assert( + ( + client.pathTemplates.folderChannelDescriptorPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchAlertPolicyFromProjectAlertPolicyConditionName', () => { - const result = client.matchAlertPolicyFromProjectAlertPolicyConditionName(fakePath); - assert.strictEqual(result, "alertPolicyValue"); - assert((client.pathTemplates.projectAlertPolicyConditionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('folderGroup', async () => { + const fakePath = '/rendered/path/folderGroup'; + const expectedParameters = { + folder: 'folderValue', + group: 'groupValue', + }; + const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.folderGroupPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderGroupPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderGroupPath', () => { + const result = client.folderGroupPath('folderValue', 'groupValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.folderGroupPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderGroupName', () => { + const result = client.matchFolderFromFolderGroupName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + (client.pathTemplates.folderGroupPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchGroupFromFolderGroupName', () => { + const result = client.matchGroupFromFolderGroupName(fakePath); + assert.strictEqual(result, 'groupValue'); + assert( + (client.pathTemplates.folderGroupPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchConditionFromProjectAlertPolicyConditionName', () => { - const result = client.matchConditionFromProjectAlertPolicyConditionName(fakePath); - assert.strictEqual(result, "conditionValue"); - assert((client.pathTemplates.projectAlertPolicyConditionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('folderNotificationChannel', async () => { + const fakePath = '/rendered/path/folderNotificationChannel'; + const expectedParameters = { + folder: 'folderValue', + notification_channel: 'notificationChannelValue', + }; + const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.folderNotificationChannelPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderNotificationChannelPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderNotificationChannelPath', () => { + const result = client.folderNotificationChannelPath( + 'folderValue', + 'notificationChannelValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.folderNotificationChannelPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderNotificationChannelName', () => { + const result = + client.matchFolderFromFolderNotificationChannelName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + ( + client.pathTemplates.folderNotificationChannelPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchNotificationChannelFromFolderNotificationChannelName', () => { + const result = + client.matchNotificationChannelFromFolderNotificationChannelName( + fakePath, + ); + assert.strictEqual(result, 'notificationChannelValue'); + assert( + ( + client.pathTemplates.folderNotificationChannelPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectChannelDescriptor', async () => { - const fakePath = "/rendered/path/projectChannelDescriptor"; - const expectedParameters = { - project: "projectValue", - channel_descriptor: "channelDescriptorValue", - }; - const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.projectChannelDescriptorPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectChannelDescriptorPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectChannelDescriptorPath', () => { - const result = client.projectChannelDescriptorPath("projectValue", "channelDescriptorValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectChannelDescriptorPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + describe('folderService', async () => { + const fakePath = '/rendered/path/folderService'; + const expectedParameters = { + folder: 'folderValue', + service: 'serviceValue', + }; + const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.folderServicePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderServicePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderServicePath', () => { + const result = client.folderServicePath('folderValue', 'serviceValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.folderServicePathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderServiceName', () => { + const result = client.matchFolderFromFolderServiceName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + (client.pathTemplates.folderServicePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServiceFromFolderServiceName', () => { + const result = client.matchServiceFromFolderServiceName(fakePath); + assert.strictEqual(result, 'serviceValue'); + assert( + (client.pathTemplates.folderServicePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchProjectFromProjectChannelDescriptorName', () => { - const result = client.matchProjectFromProjectChannelDescriptorName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectChannelDescriptorPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('folderServiceServiceLevelObjective', async () => { + const fakePath = '/rendered/path/folderServiceServiceLevelObjective'; + const expectedParameters = { + folder: 'folderValue', + service: 'serviceValue', + service_level_objective: 'serviceLevelObjectiveValue', + }; + const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('folderServiceServiceLevelObjectivePath', () => { + const result = client.folderServiceServiceLevelObjectivePath( + 'folderValue', + 'serviceValue', + 'serviceLevelObjectiveValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderServiceServiceLevelObjectiveName', () => { + const result = + client.matchFolderFromFolderServiceServiceLevelObjectiveName( + fakePath, + ); + assert.strictEqual(result, 'folderValue'); + assert( + ( + client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServiceFromFolderServiceServiceLevelObjectiveName', () => { + const result = + client.matchServiceFromFolderServiceServiceLevelObjectiveName( + fakePath, + ); + assert.strictEqual(result, 'serviceValue'); + assert( + ( + client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServiceLevelObjectiveFromFolderServiceServiceLevelObjectiveName', () => { + const result = + client.matchServiceLevelObjectiveFromFolderServiceServiceLevelObjectiveName( + fakePath, + ); + assert.strictEqual(result, 'serviceLevelObjectiveValue'); + assert( + ( + client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchChannelDescriptorFromProjectChannelDescriptorName', () => { - const result = client.matchChannelDescriptorFromProjectChannelDescriptorName(fakePath); - assert.strictEqual(result, "channelDescriptorValue"); - assert((client.pathTemplates.projectChannelDescriptorPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('folderUptimeCheckConfig', async () => { + const fakePath = '/rendered/path/folderUptimeCheckConfig'; + const expectedParameters = { + folder: 'folderValue', + uptime_check_config: 'uptimeCheckConfigValue', + }; + const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.folderUptimeCheckConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderUptimeCheckConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderUptimeCheckConfigPath', () => { + const result = client.folderUptimeCheckConfigPath( + 'folderValue', + 'uptimeCheckConfigValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.folderUptimeCheckConfigPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderUptimeCheckConfigName', () => { + const result = + client.matchFolderFromFolderUptimeCheckConfigName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + ( + client.pathTemplates.folderUptimeCheckConfigPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchUptimeCheckConfigFromFolderUptimeCheckConfigName', () => { + const result = + client.matchUptimeCheckConfigFromFolderUptimeCheckConfigName( + fakePath, + ); + assert.strictEqual(result, 'uptimeCheckConfigValue'); + assert( + ( + client.pathTemplates.folderUptimeCheckConfigPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectGroup', async () => { - const fakePath = "/rendered/path/projectGroup"; - const expectedParameters = { - project: "projectValue", - group: "groupValue", - }; - const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.projectGroupPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectGroupPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectGroupPath', () => { - const result = client.projectGroupPath("projectValue", "groupValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectGroupPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + describe('organizationAlertPolicy', async () => { + const fakePath = '/rendered/path/organizationAlertPolicy'; + const expectedParameters = { + organization: 'organizationValue', + alert_policy: 'alertPolicyValue', + }; + const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.organizationAlertPolicyPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.organizationAlertPolicyPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('organizationAlertPolicyPath', () => { + const result = client.organizationAlertPolicyPath( + 'organizationValue', + 'alertPolicyValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationAlertPolicyPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationAlertPolicyName', () => { + const result = + client.matchOrganizationFromOrganizationAlertPolicyName(fakePath); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationAlertPolicyPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchAlertPolicyFromOrganizationAlertPolicyName', () => { + const result = + client.matchAlertPolicyFromOrganizationAlertPolicyName(fakePath); + assert.strictEqual(result, 'alertPolicyValue'); + assert( + ( + client.pathTemplates.organizationAlertPolicyPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchProjectFromProjectGroupName', () => { - const result = client.matchProjectFromProjectGroupName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectGroupPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('organizationAlertPolicyCondition', async () => { + const fakePath = '/rendered/path/organizationAlertPolicyCondition'; + const expectedParameters = { + organization: 'organizationValue', + alert_policy: 'alertPolicyValue', + condition: 'conditionValue', + }; + const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.organizationAlertPolicyConditionPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.organizationAlertPolicyConditionPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('organizationAlertPolicyConditionPath', () => { + const result = client.organizationAlertPolicyConditionPath( + 'organizationValue', + 'alertPolicyValue', + 'conditionValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationAlertPolicyConditionPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationAlertPolicyConditionName', () => { + const result = + client.matchOrganizationFromOrganizationAlertPolicyConditionName( + fakePath, + ); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationAlertPolicyConditionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchAlertPolicyFromOrganizationAlertPolicyConditionName', () => { + const result = + client.matchAlertPolicyFromOrganizationAlertPolicyConditionName( + fakePath, + ); + assert.strictEqual(result, 'alertPolicyValue'); + assert( + ( + client.pathTemplates.organizationAlertPolicyConditionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchConditionFromOrganizationAlertPolicyConditionName', () => { + const result = + client.matchConditionFromOrganizationAlertPolicyConditionName( + fakePath, + ); + assert.strictEqual(result, 'conditionValue'); + assert( + ( + client.pathTemplates.organizationAlertPolicyConditionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchGroupFromProjectGroupName', () => { - const result = client.matchGroupFromProjectGroupName(fakePath); - assert.strictEqual(result, "groupValue"); - assert((client.pathTemplates.projectGroupPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('organizationChannelDescriptor', async () => { + const fakePath = '/rendered/path/organizationChannelDescriptor'; + const expectedParameters = { + organization: 'organizationValue', + channel_descriptor: 'channelDescriptorValue', + }; + const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.organizationChannelDescriptorPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.organizationChannelDescriptorPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('organizationChannelDescriptorPath', () => { + const result = client.organizationChannelDescriptorPath( + 'organizationValue', + 'channelDescriptorValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationChannelDescriptorPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationChannelDescriptorName', () => { + const result = + client.matchOrganizationFromOrganizationChannelDescriptorName( + fakePath, + ); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationChannelDescriptorPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchChannelDescriptorFromOrganizationChannelDescriptorName', () => { + const result = + client.matchChannelDescriptorFromOrganizationChannelDescriptorName( + fakePath, + ); + assert.strictEqual(result, 'channelDescriptorValue'); + assert( + ( + client.pathTemplates.organizationChannelDescriptorPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectNotificationChannel', async () => { - const fakePath = "/rendered/path/projectNotificationChannel"; - const expectedParameters = { - project: "projectValue", - notification_channel: "notificationChannelValue", - }; - const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.projectNotificationChannelPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectNotificationChannelPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectNotificationChannelPath', () => { - const result = client.projectNotificationChannelPath("projectValue", "notificationChannelValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectNotificationChannelPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + describe('organizationGroup', async () => { + const fakePath = '/rendered/path/organizationGroup'; + const expectedParameters = { + organization: 'organizationValue', + group: 'groupValue', + }; + const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.organizationGroupPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.organizationGroupPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('organizationGroupPath', () => { + const result = client.organizationGroupPath( + 'organizationValue', + 'groupValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationGroupPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationGroupName', () => { + const result = + client.matchOrganizationFromOrganizationGroupName(fakePath); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationGroupPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchGroupFromOrganizationGroupName', () => { + const result = client.matchGroupFromOrganizationGroupName(fakePath); + assert.strictEqual(result, 'groupValue'); + assert( + ( + client.pathTemplates.organizationGroupPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchProjectFromProjectNotificationChannelName', () => { - const result = client.matchProjectFromProjectNotificationChannelName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectNotificationChannelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('organizationNotificationChannel', async () => { + const fakePath = '/rendered/path/organizationNotificationChannel'; + const expectedParameters = { + organization: 'organizationValue', + notification_channel: 'notificationChannelValue', + }; + const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.organizationNotificationChannelPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.organizationNotificationChannelPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('organizationNotificationChannelPath', () => { + const result = client.organizationNotificationChannelPath( + 'organizationValue', + 'notificationChannelValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationNotificationChannelPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationNotificationChannelName', () => { + const result = + client.matchOrganizationFromOrganizationNotificationChannelName( + fakePath, + ); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationNotificationChannelPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchNotificationChannelFromOrganizationNotificationChannelName', () => { + const result = + client.matchNotificationChannelFromOrganizationNotificationChannelName( + fakePath, + ); + assert.strictEqual(result, 'notificationChannelValue'); + assert( + ( + client.pathTemplates.organizationNotificationChannelPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchNotificationChannelFromProjectNotificationChannelName', () => { - const result = client.matchNotificationChannelFromProjectNotificationChannelName(fakePath); - assert.strictEqual(result, "notificationChannelValue"); - assert((client.pathTemplates.projectNotificationChannelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('organizationService', async () => { + const fakePath = '/rendered/path/organizationService'; + const expectedParameters = { + organization: 'organizationValue', + service: 'serviceValue', + }; + const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.organizationServicePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.organizationServicePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('organizationServicePath', () => { + const result = client.organizationServicePath( + 'organizationValue', + 'serviceValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationServicePathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationServiceName', () => { + const result = + client.matchOrganizationFromOrganizationServiceName(fakePath); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationServicePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServiceFromOrganizationServiceName', () => { + const result = client.matchServiceFromOrganizationServiceName(fakePath); + assert.strictEqual(result, 'serviceValue'); + assert( + ( + client.pathTemplates.organizationServicePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectService', async () => { - const fakePath = "/rendered/path/projectService"; - const expectedParameters = { - project: "projectValue", - service: "serviceValue", - }; - const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.projectServicePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectServicePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectServicePath', () => { - const result = client.projectServicePath("projectValue", "serviceValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectServicePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + describe('organizationServiceServiceLevelObjective', async () => { + const fakePath = + '/rendered/path/organizationServiceServiceLevelObjective'; + const expectedParameters = { + organization: 'organizationValue', + service: 'serviceValue', + service_level_objective: 'serviceLevelObjectiveValue', + }; + const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('organizationServiceServiceLevelObjectivePath', () => { + const result = client.organizationServiceServiceLevelObjectivePath( + 'organizationValue', + 'serviceValue', + 'serviceLevelObjectiveValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates + .organizationServiceServiceLevelObjectivePathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationServiceServiceLevelObjectiveName', () => { + const result = + client.matchOrganizationFromOrganizationServiceServiceLevelObjectiveName( + fakePath, + ); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates + .organizationServiceServiceLevelObjectivePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServiceFromOrganizationServiceServiceLevelObjectiveName', () => { + const result = + client.matchServiceFromOrganizationServiceServiceLevelObjectiveName( + fakePath, + ); + assert.strictEqual(result, 'serviceValue'); + assert( + ( + client.pathTemplates + .organizationServiceServiceLevelObjectivePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServiceLevelObjectiveFromOrganizationServiceServiceLevelObjectiveName', () => { + const result = + client.matchServiceLevelObjectiveFromOrganizationServiceServiceLevelObjectiveName( + fakePath, + ); + assert.strictEqual(result, 'serviceLevelObjectiveValue'); + assert( + ( + client.pathTemplates + .organizationServiceServiceLevelObjectivePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchProjectFromProjectServiceName', () => { - const result = client.matchProjectFromProjectServiceName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectServicePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('organizationUptimeCheckConfig', async () => { + const fakePath = '/rendered/path/organizationUptimeCheckConfig'; + const expectedParameters = { + organization: 'organizationValue', + uptime_check_config: 'uptimeCheckConfigValue', + }; + const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.organizationUptimeCheckConfigPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.organizationUptimeCheckConfigPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('organizationUptimeCheckConfigPath', () => { + const result = client.organizationUptimeCheckConfigPath( + 'organizationValue', + 'uptimeCheckConfigValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationUptimeCheckConfigPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationUptimeCheckConfigName', () => { + const result = + client.matchOrganizationFromOrganizationUptimeCheckConfigName( + fakePath, + ); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationUptimeCheckConfigPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchUptimeCheckConfigFromOrganizationUptimeCheckConfigName', () => { + const result = + client.matchUptimeCheckConfigFromOrganizationUptimeCheckConfigName( + fakePath, + ); + assert.strictEqual(result, 'uptimeCheckConfigValue'); + assert( + ( + client.pathTemplates.organizationUptimeCheckConfigPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchServiceFromProjectServiceName', () => { - const result = client.matchServiceFromProjectServiceName(fakePath); - assert.strictEqual(result, "serviceValue"); - assert((client.pathTemplates.projectServicePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectAlertPolicy', async () => { + const fakePath = '/rendered/path/projectAlertPolicy'; + const expectedParameters = { + project: 'projectValue', + alert_policy: 'alertPolicyValue', + }; + const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.projectAlertPolicyPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectAlertPolicyPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectAlertPolicyPath', () => { + const result = client.projectAlertPolicyPath( + 'projectValue', + 'alertPolicyValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.projectAlertPolicyPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectAlertPolicyName', () => { + const result = client.matchProjectFromProjectAlertPolicyName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.projectAlertPolicyPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchAlertPolicyFromProjectAlertPolicyName', () => { + const result = + client.matchAlertPolicyFromProjectAlertPolicyName(fakePath); + assert.strictEqual(result, 'alertPolicyValue'); + assert( + ( + client.pathTemplates.projectAlertPolicyPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectServiceServiceLevelObjective', async () => { - const fakePath = "/rendered/path/projectServiceServiceLevelObjective"; - const expectedParameters = { - project: "projectValue", - service: "serviceValue", - service_level_objective: "serviceLevelObjectiveValue", - }; - const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectServiceServiceLevelObjectivePath', () => { - const result = client.projectServiceServiceLevelObjectivePath("projectValue", "serviceValue", "serviceLevelObjectiveValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + describe('projectAlertPolicyCondition', async () => { + const fakePath = '/rendered/path/projectAlertPolicyCondition'; + const expectedParameters = { + project: 'projectValue', + alert_policy: 'alertPolicyValue', + condition: 'conditionValue', + }; + const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.projectAlertPolicyConditionPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.projectAlertPolicyConditionPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectAlertPolicyConditionPath', () => { + const result = client.projectAlertPolicyConditionPath( + 'projectValue', + 'alertPolicyValue', + 'conditionValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.projectAlertPolicyConditionPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectAlertPolicyConditionName', () => { + const result = + client.matchProjectFromProjectAlertPolicyConditionName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.projectAlertPolicyConditionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchAlertPolicyFromProjectAlertPolicyConditionName', () => { + const result = + client.matchAlertPolicyFromProjectAlertPolicyConditionName(fakePath); + assert.strictEqual(result, 'alertPolicyValue'); + assert( + ( + client.pathTemplates.projectAlertPolicyConditionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchConditionFromProjectAlertPolicyConditionName', () => { + const result = + client.matchConditionFromProjectAlertPolicyConditionName(fakePath); + assert.strictEqual(result, 'conditionValue'); + assert( + ( + client.pathTemplates.projectAlertPolicyConditionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchProjectFromProjectServiceServiceLevelObjectiveName', () => { - const result = client.matchProjectFromProjectServiceServiceLevelObjectiveName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('projectChannelDescriptor', async () => { + const fakePath = '/rendered/path/projectChannelDescriptor'; + const expectedParameters = { + project: 'projectValue', + channel_descriptor: 'channelDescriptorValue', + }; + const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.projectChannelDescriptorPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectChannelDescriptorPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectChannelDescriptorPath', () => { + const result = client.projectChannelDescriptorPath( + 'projectValue', + 'channelDescriptorValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.projectChannelDescriptorPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectChannelDescriptorName', () => { + const result = + client.matchProjectFromProjectChannelDescriptorName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.projectChannelDescriptorPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchChannelDescriptorFromProjectChannelDescriptorName', () => { + const result = + client.matchChannelDescriptorFromProjectChannelDescriptorName( + fakePath, + ); + assert.strictEqual(result, 'channelDescriptorValue'); + assert( + ( + client.pathTemplates.projectChannelDescriptorPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchServiceFromProjectServiceServiceLevelObjectiveName', () => { - const result = client.matchServiceFromProjectServiceServiceLevelObjectiveName(fakePath); - assert.strictEqual(result, "serviceValue"); - assert((client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('projectGroup', async () => { + const fakePath = '/rendered/path/projectGroup'; + const expectedParameters = { + project: 'projectValue', + group: 'groupValue', + }; + const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.projectGroupPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectGroupPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectGroupPath', () => { + const result = client.projectGroupPath('projectValue', 'groupValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.projectGroupPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectGroupName', () => { + const result = client.matchProjectFromProjectGroupName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.projectGroupPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchGroupFromProjectGroupName', () => { + const result = client.matchGroupFromProjectGroupName(fakePath); + assert.strictEqual(result, 'groupValue'); + assert( + (client.pathTemplates.projectGroupPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchServiceLevelObjectiveFromProjectServiceServiceLevelObjectiveName', () => { - const result = client.matchServiceLevelObjectiveFromProjectServiceServiceLevelObjectiveName(fakePath); - assert.strictEqual(result, "serviceLevelObjectiveValue"); - assert((client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectNotificationChannel', async () => { + const fakePath = '/rendered/path/projectNotificationChannel'; + const expectedParameters = { + project: 'projectValue', + notification_channel: 'notificationChannelValue', + }; + const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.projectNotificationChannelPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectNotificationChannelPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectNotificationChannelPath', () => { + const result = client.projectNotificationChannelPath( + 'projectValue', + 'notificationChannelValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.projectNotificationChannelPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectNotificationChannelName', () => { + const result = + client.matchProjectFromProjectNotificationChannelName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.projectNotificationChannelPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchNotificationChannelFromProjectNotificationChannelName', () => { + const result = + client.matchNotificationChannelFromProjectNotificationChannelName( + fakePath, + ); + assert.strictEqual(result, 'notificationChannelValue'); + assert( + ( + client.pathTemplates.projectNotificationChannelPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectUptimeCheckConfig', async () => { - const fakePath = "/rendered/path/projectUptimeCheckConfig"; - const expectedParameters = { - project: "projectValue", - uptime_check_config: "uptimeCheckConfigValue", - }; - const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.projectUptimeCheckConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectUptimeCheckConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectUptimeCheckConfigPath', () => { - const result = client.projectUptimeCheckConfigPath("projectValue", "uptimeCheckConfigValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectUptimeCheckConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + describe('projectService', async () => { + const fakePath = '/rendered/path/projectService'; + const expectedParameters = { + project: 'projectValue', + service: 'serviceValue', + }; + const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.projectServicePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectServicePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectServicePath', () => { + const result = client.projectServicePath( + 'projectValue', + 'serviceValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.projectServicePathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectServiceName', () => { + const result = client.matchProjectFromProjectServiceName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.projectServicePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServiceFromProjectServiceName', () => { + const result = client.matchServiceFromProjectServiceName(fakePath); + assert.strictEqual(result, 'serviceValue'); + assert( + (client.pathTemplates.projectServicePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchProjectFromProjectUptimeCheckConfigName', () => { - const result = client.matchProjectFromProjectUptimeCheckConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectUptimeCheckConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('projectServiceServiceLevelObjective', async () => { + const fakePath = '/rendered/path/projectServiceServiceLevelObjective'; + const expectedParameters = { + project: 'projectValue', + service: 'serviceValue', + service_level_objective: 'serviceLevelObjectiveValue', + }; + const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('projectServiceServiceLevelObjectivePath', () => { + const result = client.projectServiceServiceLevelObjectivePath( + 'projectValue', + 'serviceValue', + 'serviceLevelObjectiveValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectServiceServiceLevelObjectiveName', () => { + const result = + client.matchProjectFromProjectServiceServiceLevelObjectiveName( + fakePath, + ); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServiceFromProjectServiceServiceLevelObjectiveName', () => { + const result = + client.matchServiceFromProjectServiceServiceLevelObjectiveName( + fakePath, + ); + assert.strictEqual(result, 'serviceValue'); + assert( + ( + client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServiceLevelObjectiveFromProjectServiceServiceLevelObjectiveName', () => { + const result = + client.matchServiceLevelObjectiveFromProjectServiceServiceLevelObjectiveName( + fakePath, + ); + assert.strictEqual(result, 'serviceLevelObjectiveValue'); + assert( + ( + client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchUptimeCheckConfigFromProjectUptimeCheckConfigName', () => { - const result = client.matchUptimeCheckConfigFromProjectUptimeCheckConfigName(fakePath); - assert.strictEqual(result, "uptimeCheckConfigValue"); - assert((client.pathTemplates.projectUptimeCheckConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectUptimeCheckConfig', async () => { + const fakePath = '/rendered/path/projectUptimeCheckConfig'; + const expectedParameters = { + project: 'projectValue', + uptime_check_config: 'uptimeCheckConfigValue', + }; + const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.projectUptimeCheckConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectUptimeCheckConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectUptimeCheckConfigPath', () => { + const result = client.projectUptimeCheckConfigPath( + 'projectValue', + 'uptimeCheckConfigValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.projectUptimeCheckConfigPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectUptimeCheckConfigName', () => { + const result = + client.matchProjectFromProjectUptimeCheckConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.projectUptimeCheckConfigPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchUptimeCheckConfigFromProjectUptimeCheckConfigName', () => { + const result = + client.matchUptimeCheckConfigFromProjectUptimeCheckConfigName( + fakePath, + ); + assert.strictEqual(result, 'uptimeCheckConfigValue'); + assert( + ( + client.pathTemplates.projectUptimeCheckConfigPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/core/generator/gapic-generator-typescript/baselines/monitoring/test/gapic_group_service_v3.ts.baseline b/core/generator/gapic-generator-typescript/baselines/monitoring/test/gapic_group_service_v3.ts.baseline index cafd10a8379b..b675803947f6 100644 --- a/core/generator/gapic-generator-typescript/baselines/monitoring/test/gapic_group_service_v3.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/monitoring/test/gapic_group_service_v3.ts.baseline @@ -19,2132 +19,3015 @@ import * as protos from '../protos/protos'; import * as assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as groupserviceModule from '../src'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; -import {protobuf} from 'google-gax'; +import { protobuf } from 'google-gax'; // Dynamically loaded proto JSON is needed to get the type information // to fill in default values for request objects -const root = protobuf.Root.fromJSON(require('../protos/protos.json')).resolveAll(); +const root = protobuf.Root.fromJSON( + require('../protos/protos.json'), +).resolveAll(); // eslint-disable-next-line @typescript-eslint/no-unused-vars function getTypeDefaultValue(typeName: string, fields: string[]) { - let type = root.lookupType(typeName) as protobuf.Type; - for (const field of fields.slice(0, -1)) { - type = type.fields[field]?.resolvedType as protobuf.Type; - } - return type.fields[fields[fields.length - 1]]?.defaultValue; + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type.fields[field]?.resolvedType as protobuf.Type; + } + return type.fields[fields[fields.length - 1]]?.defaultValue; } function generateSampleMessage(instance: T) { - const filledObject = (instance.constructor as typeof protobuf.Message) - .toObject(instance as protobuf.Message, {defaults: true}); - return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, { defaults: true }); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; } function stubSimpleCall(response?: ResponseType, error?: Error) { - return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); } -function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { - return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +function stubSimpleCallWithCallback( + response?: ResponseType, + error?: Error, +) { + return error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); } -function stubPageStreamingCall(responses?: ResponseType[], error?: Error) { - const pagingStub = sinon.stub(); - if (responses) { - for (let i = 0; i < responses.length; ++i) { - pagingStub.onCall(i).callsArgWith(2, null, responses[i]); - } +function stubPageStreamingCall( + responses?: ResponseType[], + error?: Error, +) { + const pagingStub = sinon.stub(); + if (responses) { + for (let i = 0; i < responses.length; ++i) { + pagingStub.onCall(i).callsArgWith(2, null, responses[i]); } - const transformStub = error ? sinon.stub().callsArgWith(2, error) : pagingStub; - const mockStream = new PassThrough({ - objectMode: true, - transform: transformStub, - }); - // trigger as many responses as needed - if (responses) { - for (let i = 0; i < responses.length; ++i) { - setImmediate(() => { mockStream.write({}); }); - } - setImmediate(() => { mockStream.end(); }); - } else { - setImmediate(() => { mockStream.write({}); }); - setImmediate(() => { mockStream.end(); }); + } + const transformStub = error + ? sinon.stub().callsArgWith(2, error) + : pagingStub; + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + // trigger as many responses as needed + if (responses) { + for (let i = 0; i < responses.length; ++i) { + setImmediate(() => { + mockStream.write({}); + }); } - return sinon.stub().returns(mockStream); + setImmediate(() => { + mockStream.end(); + }); + } else { + setImmediate(() => { + mockStream.write({}); + }); + setImmediate(() => { + mockStream.end(); + }); + } + return sinon.stub().returns(mockStream); } -function stubAsyncIterationCall(responses?: ResponseType[], error?: Error) { - let counter = 0; - const asyncIterable = { - [Symbol.asyncIterator]() { - return { - async next() { - if (error) { - return Promise.reject(error); - } - if (counter >= responses!.length) { - return Promise.resolve({done: true, value: undefined}); - } - return Promise.resolve({done: false, value: responses![counter++]}); - } - }; - } - }; - return sinon.stub().returns(asyncIterable); +function stubAsyncIterationCall( + responses?: ResponseType[], + error?: Error, +) { + let counter = 0; + const asyncIterable = { + [Symbol.asyncIterator]() { + return { + async next() { + if (error) { + return Promise.reject(error); + } + if (counter >= responses!.length) { + return Promise.resolve({ done: true, value: undefined }); + } + return Promise.resolve({ done: false, value: responses![counter++] }); + }, + }; + }, + }; + return sinon.stub().returns(asyncIterable); } describe('v3.GroupServiceClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new groupserviceModule.v3.GroupServiceClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'monitoring.googleapis.com'); - }); - - it('has universeDomain', () => { - const client = new groupserviceModule.v3.GroupServiceClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); - - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - it('throws DeprecationWarning if static servicePath is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const servicePath = groupserviceModule.v3.GroupServiceClient.servicePath; - assert.strictEqual(servicePath, 'monitoring.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = groupserviceModule.v3.GroupServiceClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'monitoring.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new groupserviceModule.v3.GroupServiceClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'monitoring.example.com'); - }); - - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new groupserviceModule.v3.GroupServiceClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'monitoring.example.com'); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new groupserviceModule.v3.GroupServiceClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'monitoring.googleapis.com'); + }); - if (typeof process === 'object' && 'env' in process) { - describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { - it('sets apiEndpoint from environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new groupserviceModule.v3.GroupServiceClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'monitoring.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - - it('value configured in code has priority over environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new groupserviceModule.v3.GroupServiceClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'monitoring.configured.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { new groupserviceModule.v3.GroupServiceClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); + it('has universeDomain', () => { + const client = new groupserviceModule.v3.GroupServiceClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - it('has port', () => { - const port = groupserviceModule.v3.GroupServiceClient.port; - assert(port); - assert(typeof port === 'number'); - }); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = + groupserviceModule.v3.GroupServiceClient.servicePath; + assert.strictEqual(servicePath, 'monitoring.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + groupserviceModule.v3.GroupServiceClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'monitoring.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = new groupserviceModule.v3.GroupServiceClient({ + universeDomain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'monitoring.example.com'); + }); - it('should create a client with no option', () => { - const client = new groupserviceModule.v3.GroupServiceClient(); - assert(client); - }); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = new groupserviceModule.v3.GroupServiceClient({ + universe_domain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'monitoring.example.com'); + }); - it('should create a client with gRPC fallback', () => { - const client = new groupserviceModule.v3.GroupServiceClient({ - fallback: true, - }); - assert(client); + if (typeof process === 'object' && 'env' in process) { + describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { + it('sets apiEndpoint from environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new groupserviceModule.v3.GroupServiceClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'monitoring.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } + }); + + it('value configured in code has priority over environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new groupserviceModule.v3.GroupServiceClient({ + universeDomain: 'configured.example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'monitoring.configured.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } + }); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new groupserviceModule.v3.GroupServiceClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); + }); - it('has initialize method and supports deferred initialization', async () => { - const client = new groupserviceModule.v3.GroupServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.groupServiceStub, undefined); - await client.initialize(); - assert(client.groupServiceStub); - }); + it('has port', () => { + const port = groupserviceModule.v3.GroupServiceClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('has close method for the initialized client', done => { - const client = new groupserviceModule.v3.GroupServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.groupServiceStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('should create a client with no option', () => { + const client = new groupserviceModule.v3.GroupServiceClient(); + assert(client); + }); - it('has close method for the non-initialized client', done => { - const client = new groupserviceModule.v3.GroupServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.groupServiceStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('should create a client with gRPC fallback', () => { + const client = new groupserviceModule.v3.GroupServiceClient({ + fallback: true, + }); + assert(client); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new groupserviceModule.v3.GroupServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); - }); + it('has initialize method and supports deferred initialization', async () => { + const client = new groupserviceModule.v3.GroupServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.groupServiceStub, undefined); + await client.initialize(); + assert(client.groupServiceStub); + }); - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new groupserviceModule.v3.GroupServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId((err?: Error|null, projectId?: string|null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } - }); - }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); + it('has close method for the initialized client', (done) => { + const client = new groupserviceModule.v3.GroupServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.groupServiceStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); }); - describe('getGroup', () => { - it('invokes getGroup without error', async () => { - const client = new groupserviceModule.v3.GroupServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.GetGroupRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.GetGroupRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.monitoring.v3.Group() - ); - client.innerApiCalls.getGroup = stubSimpleCall(expectedResponse); - const [response] = await client.getGroup(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getGroup as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getGroup as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('has close method for the non-initialized client', (done) => { + const client = new groupserviceModule.v3.GroupServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.groupServiceStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes getGroup without error using callback', async () => { - const client = new groupserviceModule.v3.GroupServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.GetGroupRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.GetGroupRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.monitoring.v3.Group() - ); - client.innerApiCalls.getGroup = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getGroup( - request, - (err?: Error|null, result?: protos.google.monitoring.v3.IGroup|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getGroup as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getGroup as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new groupserviceModule.v3.GroupServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + }); - it('invokes getGroup with error', async () => { - const client = new groupserviceModule.v3.GroupServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.GetGroupRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.GetGroupRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getGroup = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getGroup(request), expectedError); - const actualRequest = (client.innerApiCalls.getGroup as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getGroup as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new groupserviceModule.v3.GroupServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } + }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + }); + + describe('getGroup', () => { + it('invokes getGroup without error', async () => { + const client = new groupserviceModule.v3.GroupServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.GetGroupRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.GetGroupRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.monitoring.v3.Group(), + ); + client.innerApiCalls.getGroup = stubSimpleCall(expectedResponse); + const [response] = await client.getGroup(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getGroup as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getGroup as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getGroup with closed client', async () => { - const client = new groupserviceModule.v3.GroupServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.GetGroupRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.GetGroupRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getGroup(request), expectedError); - }); + it('invokes getGroup without error using callback', async () => { + const client = new groupserviceModule.v3.GroupServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.GetGroupRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.GetGroupRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.monitoring.v3.Group(), + ); + client.innerApiCalls.getGroup = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getGroup( + request, + ( + err?: Error | null, + result?: protos.google.monitoring.v3.IGroup | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getGroup as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getGroup as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('createGroup', () => { - it('invokes createGroup without error', async () => { - const client = new groupserviceModule.v3.GroupServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.CreateGroupRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.CreateGroupRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.monitoring.v3.Group() - ); - client.innerApiCalls.createGroup = stubSimpleCall(expectedResponse); - const [response] = await client.createGroup(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createGroup as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createGroup as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getGroup with error', async () => { + const client = new groupserviceModule.v3.GroupServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.GetGroupRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.GetGroupRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getGroup = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.getGroup(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getGroup as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getGroup as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createGroup without error using callback', async () => { - const client = new groupserviceModule.v3.GroupServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.CreateGroupRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.CreateGroupRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.monitoring.v3.Group() - ); - client.innerApiCalls.createGroup = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createGroup( - request, - (err?: Error|null, result?: protos.google.monitoring.v3.IGroup|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createGroup as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createGroup as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getGroup with closed client', async () => { + const client = new groupserviceModule.v3.GroupServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.GetGroupRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.GetGroupRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getGroup(request), expectedError); + }); + }); + + describe('createGroup', () => { + it('invokes createGroup without error', async () => { + const client = new groupserviceModule.v3.GroupServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.CreateGroupRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.CreateGroupRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.monitoring.v3.Group(), + ); + client.innerApiCalls.createGroup = stubSimpleCall(expectedResponse); + const [response] = await client.createGroup(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createGroup as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createGroup as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createGroup with error', async () => { - const client = new groupserviceModule.v3.GroupServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.CreateGroupRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.CreateGroupRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createGroup = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createGroup(request), expectedError); - const actualRequest = (client.innerApiCalls.createGroup as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createGroup as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createGroup without error using callback', async () => { + const client = new groupserviceModule.v3.GroupServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.CreateGroupRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.CreateGroupRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.monitoring.v3.Group(), + ); + client.innerApiCalls.createGroup = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createGroup( + request, + ( + err?: Error | null, + result?: protos.google.monitoring.v3.IGroup | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createGroup as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createGroup as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createGroup with closed client', async () => { - const client = new groupserviceModule.v3.GroupServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.CreateGroupRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.CreateGroupRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createGroup(request), expectedError); - }); + it('invokes createGroup with error', async () => { + const client = new groupserviceModule.v3.GroupServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.CreateGroupRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.CreateGroupRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createGroup = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.createGroup(request), expectedError); + const actualRequest = ( + client.innerApiCalls.createGroup as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createGroup as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('updateGroup', () => { - it('invokes updateGroup without error', async () => { - const client = new groupserviceModule.v3.GroupServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.UpdateGroupRequest() - ); - request.group ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.UpdateGroupRequest', ['group', 'name']); - request.group.name = defaultValue1; - const expectedHeaderRequestParams = `group.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.monitoring.v3.Group() - ); - client.innerApiCalls.updateGroup = stubSimpleCall(expectedResponse); - const [response] = await client.updateGroup(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateGroup as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateGroup as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createGroup with closed client', async () => { + const client = new groupserviceModule.v3.GroupServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.CreateGroupRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.CreateGroupRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.createGroup(request), expectedError); + }); + }); + + describe('updateGroup', () => { + it('invokes updateGroup without error', async () => { + const client = new groupserviceModule.v3.GroupServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.UpdateGroupRequest(), + ); + request.group ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.UpdateGroupRequest', + ['group', 'name'], + ); + request.group.name = defaultValue1; + const expectedHeaderRequestParams = `group.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.monitoring.v3.Group(), + ); + client.innerApiCalls.updateGroup = stubSimpleCall(expectedResponse); + const [response] = await client.updateGroup(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateGroup as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateGroup as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateGroup without error using callback', async () => { - const client = new groupserviceModule.v3.GroupServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.UpdateGroupRequest() - ); - request.group ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.UpdateGroupRequest', ['group', 'name']); - request.group.name = defaultValue1; - const expectedHeaderRequestParams = `group.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.monitoring.v3.Group() - ); - client.innerApiCalls.updateGroup = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateGroup( - request, - (err?: Error|null, result?: protos.google.monitoring.v3.IGroup|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateGroup as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateGroup as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateGroup without error using callback', async () => { + const client = new groupserviceModule.v3.GroupServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.UpdateGroupRequest(), + ); + request.group ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.UpdateGroupRequest', + ['group', 'name'], + ); + request.group.name = defaultValue1; + const expectedHeaderRequestParams = `group.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.monitoring.v3.Group(), + ); + client.innerApiCalls.updateGroup = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateGroup( + request, + ( + err?: Error | null, + result?: protos.google.monitoring.v3.IGroup | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateGroup as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateGroup as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateGroup with error', async () => { - const client = new groupserviceModule.v3.GroupServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.UpdateGroupRequest() - ); - request.group ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.UpdateGroupRequest', ['group', 'name']); - request.group.name = defaultValue1; - const expectedHeaderRequestParams = `group.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateGroup = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateGroup(request), expectedError); - const actualRequest = (client.innerApiCalls.updateGroup as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateGroup as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateGroup with error', async () => { + const client = new groupserviceModule.v3.GroupServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.UpdateGroupRequest(), + ); + request.group ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.UpdateGroupRequest', + ['group', 'name'], + ); + request.group.name = defaultValue1; + const expectedHeaderRequestParams = `group.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateGroup = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.updateGroup(request), expectedError); + const actualRequest = ( + client.innerApiCalls.updateGroup as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateGroup as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateGroup with closed client', async () => { - const client = new groupserviceModule.v3.GroupServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.UpdateGroupRequest() - ); - request.group ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.UpdateGroupRequest', ['group', 'name']); - request.group.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateGroup(request), expectedError); - }); + it('invokes updateGroup with closed client', async () => { + const client = new groupserviceModule.v3.GroupServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.UpdateGroupRequest(), + ); + request.group ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.UpdateGroupRequest', + ['group', 'name'], + ); + request.group.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.updateGroup(request), expectedError); + }); + }); + + describe('deleteGroup', () => { + it('invokes deleteGroup without error', async () => { + const client = new groupserviceModule.v3.GroupServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.DeleteGroupRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.DeleteGroupRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteGroup = stubSimpleCall(expectedResponse); + const [response] = await client.deleteGroup(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteGroup as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteGroup as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('deleteGroup', () => { - it('invokes deleteGroup without error', async () => { - const client = new groupserviceModule.v3.GroupServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.DeleteGroupRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.DeleteGroupRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteGroup = stubSimpleCall(expectedResponse); - const [response] = await client.deleteGroup(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteGroup as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteGroup as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteGroup without error using callback', async () => { + const client = new groupserviceModule.v3.GroupServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.DeleteGroupRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.DeleteGroupRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteGroup = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteGroup( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteGroup as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteGroup as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteGroup without error using callback', async () => { - const client = new groupserviceModule.v3.GroupServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.DeleteGroupRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.DeleteGroupRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteGroup = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteGroup( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteGroup as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteGroup as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteGroup with error', async () => { + const client = new groupserviceModule.v3.GroupServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.DeleteGroupRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.DeleteGroupRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteGroup = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.deleteGroup(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteGroup as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteGroup as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteGroup with error', async () => { - const client = new groupserviceModule.v3.GroupServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.DeleteGroupRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.DeleteGroupRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteGroup = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteGroup(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteGroup as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteGroup as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteGroup with closed client', async () => { + const client = new groupserviceModule.v3.GroupServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.DeleteGroupRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.DeleteGroupRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.deleteGroup(request), expectedError); + }); + }); + + describe('listGroups', () => { + it('invokes listGroups without error', async () => { + const client = new groupserviceModule.v3.GroupServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListGroupsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListGroupsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.monitoring.v3.Group()), + generateSampleMessage(new protos.google.monitoring.v3.Group()), + generateSampleMessage(new protos.google.monitoring.v3.Group()), + ]; + client.innerApiCalls.listGroups = stubSimpleCall(expectedResponse); + const [response] = await client.listGroups(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listGroups as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listGroups as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteGroup with closed client', async () => { - const client = new groupserviceModule.v3.GroupServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.DeleteGroupRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.DeleteGroupRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteGroup(request), expectedError); - }); + it('invokes listGroups without error using callback', async () => { + const client = new groupserviceModule.v3.GroupServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListGroupsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListGroupsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.monitoring.v3.Group()), + generateSampleMessage(new protos.google.monitoring.v3.Group()), + generateSampleMessage(new protos.google.monitoring.v3.Group()), + ]; + client.innerApiCalls.listGroups = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listGroups( + request, + ( + err?: Error | null, + result?: protos.google.monitoring.v3.IGroup[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listGroups as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listGroups as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('listGroups', () => { - it('invokes listGroups without error', async () => { - const client = new groupserviceModule.v3.GroupServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListGroupsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListGroupsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.monitoring.v3.Group()), - generateSampleMessage(new protos.google.monitoring.v3.Group()), - generateSampleMessage(new protos.google.monitoring.v3.Group()), - ]; - client.innerApiCalls.listGroups = stubSimpleCall(expectedResponse); - const [response] = await client.listGroups(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listGroups as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listGroups as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listGroups with error', async () => { + const client = new groupserviceModule.v3.GroupServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListGroupsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListGroupsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listGroups = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listGroups(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listGroups as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listGroups as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listGroups without error using callback', async () => { - const client = new groupserviceModule.v3.GroupServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListGroupsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListGroupsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.monitoring.v3.Group()), - generateSampleMessage(new protos.google.monitoring.v3.Group()), - generateSampleMessage(new protos.google.monitoring.v3.Group()), - ]; - client.innerApiCalls.listGroups = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listGroups( - request, - (err?: Error|null, result?: protos.google.monitoring.v3.IGroup[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listGroups as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listGroups as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listGroupsStream without error', async () => { + const client = new groupserviceModule.v3.GroupServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListGroupsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListGroupsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.monitoring.v3.Group()), + generateSampleMessage(new protos.google.monitoring.v3.Group()), + generateSampleMessage(new protos.google.monitoring.v3.Group()), + ]; + client.descriptors.page.listGroups.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listGroupsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.monitoring.v3.Group[] = []; + stream.on('data', (response: protos.google.monitoring.v3.Group) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listGroups.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listGroups, request), + ); + assert( + (client.descriptors.page.listGroups.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('invokes listGroups with error', async () => { - const client = new groupserviceModule.v3.GroupServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListGroupsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListGroupsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listGroups = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listGroups(request), expectedError); - const actualRequest = (client.innerApiCalls.listGroups as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listGroups as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listGroupsStream with error', async () => { + const client = new groupserviceModule.v3.GroupServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListGroupsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListGroupsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listGroups.createStream = stubPageStreamingCall( + undefined, + expectedError, + ); + const stream = client.listGroupsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.monitoring.v3.Group[] = []; + stream.on('data', (response: protos.google.monitoring.v3.Group) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listGroups.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listGroups, request), + ); + assert( + (client.descriptors.page.listGroups.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('invokes listGroupsStream without error', async () => { - const client = new groupserviceModule.v3.GroupServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListGroupsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListGroupsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.monitoring.v3.Group()), - generateSampleMessage(new protos.google.monitoring.v3.Group()), - generateSampleMessage(new protos.google.monitoring.v3.Group()), - ]; - client.descriptors.page.listGroups.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listGroupsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.monitoring.v3.Group[] = []; - stream.on('data', (response: protos.google.monitoring.v3.Group) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.listGroups.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listGroups, request)); - assert( - (client.descriptors.page.listGroups.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listGroups without error', async () => { + const client = new groupserviceModule.v3.GroupServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListGroupsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListGroupsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.monitoring.v3.Group()), + generateSampleMessage(new protos.google.monitoring.v3.Group()), + generateSampleMessage(new protos.google.monitoring.v3.Group()), + ]; + client.descriptors.page.listGroups.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.monitoring.v3.IGroup[] = []; + const iterable = client.listGroupsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + (client.descriptors.page.listGroups.asyncIterate as SinonStub).getCall( + 0, + ).args[1], + request, + ); + assert( + (client.descriptors.page.listGroups.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('invokes listGroupsStream with error', async () => { - const client = new groupserviceModule.v3.GroupServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListGroupsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListGroupsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listGroups.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listGroupsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.monitoring.v3.Group[] = []; - stream.on('data', (response: protos.google.monitoring.v3.Group) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listGroups.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listGroups, request)); - assert( - (client.descriptors.page.listGroups.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listGroups with error', async () => { + const client = new groupserviceModule.v3.GroupServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListGroupsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListGroupsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listGroups.asyncIterate = stubAsyncIterationCall( + undefined, + expectedError, + ); + const iterable = client.listGroupsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.monitoring.v3.IGroup[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + (client.descriptors.page.listGroups.asyncIterate as SinonStub).getCall( + 0, + ).args[1], + request, + ); + assert( + (client.descriptors.page.listGroups.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + }); + + describe('listGroupMembers', () => { + it('invokes listGroupMembers without error', async () => { + const client = new groupserviceModule.v3.GroupServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListGroupMembersRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListGroupMembersRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.api.MonitoredResource()), + generateSampleMessage(new protos.google.api.MonitoredResource()), + generateSampleMessage(new protos.google.api.MonitoredResource()), + ]; + client.innerApiCalls.listGroupMembers = stubSimpleCall(expectedResponse); + const [response] = await client.listGroupMembers(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listGroupMembers as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listGroupMembers as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('uses async iteration with listGroups without error', async () => { - const client = new groupserviceModule.v3.GroupServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListGroupsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListGroupsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.monitoring.v3.Group()), - generateSampleMessage(new protos.google.monitoring.v3.Group()), - generateSampleMessage(new protos.google.monitoring.v3.Group()), - ]; - client.descriptors.page.listGroups.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.monitoring.v3.IGroup[] = []; - const iterable = client.listGroupsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); + it('invokes listGroupMembers without error using callback', async () => { + const client = new groupserviceModule.v3.GroupServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListGroupMembersRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListGroupMembersRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.api.MonitoredResource()), + generateSampleMessage(new protos.google.api.MonitoredResource()), + generateSampleMessage(new protos.google.api.MonitoredResource()), + ]; + client.innerApiCalls.listGroupMembers = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listGroupMembers( + request, + ( + err?: Error | null, + result?: protos.google.api.IMonitoredResource[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listGroups.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listGroups.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); - - it('uses async iteration with listGroups with error', async () => { - const client = new groupserviceModule.v3.GroupServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListGroupsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListGroupsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listGroups.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listGroupsAsync(request); - await assert.rejects(async () => { - const responses: protos.google.monitoring.v3.IGroup[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listGroups.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listGroups.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listGroupMembers as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listGroupMembers as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('listGroupMembers', () => { - it('invokes listGroupMembers without error', async () => { - const client = new groupserviceModule.v3.GroupServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListGroupMembersRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListGroupMembersRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.api.MonitoredResource()), - generateSampleMessage(new protos.google.api.MonitoredResource()), - generateSampleMessage(new protos.google.api.MonitoredResource()), - ]; - client.innerApiCalls.listGroupMembers = stubSimpleCall(expectedResponse); - const [response] = await client.listGroupMembers(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listGroupMembers as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listGroupMembers as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listGroupMembers without error using callback', async () => { - const client = new groupserviceModule.v3.GroupServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListGroupMembersRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListGroupMembersRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.api.MonitoredResource()), - generateSampleMessage(new protos.google.api.MonitoredResource()), - generateSampleMessage(new protos.google.api.MonitoredResource()), - ]; - client.innerApiCalls.listGroupMembers = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listGroupMembers( - request, - (err?: Error|null, result?: protos.google.api.IMonitoredResource[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listGroupMembers as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listGroupMembers as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listGroupMembers with error', async () => { - const client = new groupserviceModule.v3.GroupServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListGroupMembersRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListGroupMembersRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listGroupMembers = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listGroupMembers(request), expectedError); - const actualRequest = (client.innerApiCalls.listGroupMembers as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listGroupMembers as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listGroupMembersStream without error', async () => { - const client = new groupserviceModule.v3.GroupServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListGroupMembersRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListGroupMembersRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.api.MonitoredResource()), - generateSampleMessage(new protos.google.api.MonitoredResource()), - generateSampleMessage(new protos.google.api.MonitoredResource()), - ]; - client.descriptors.page.listGroupMembers.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listGroupMembersStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.api.MonitoredResource[] = []; - stream.on('data', (response: protos.google.api.MonitoredResource) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.listGroupMembers.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listGroupMembers, request)); - assert( - (client.descriptors.page.listGroupMembers.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listGroupMembers with error', async () => { + const client = new groupserviceModule.v3.GroupServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListGroupMembersRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListGroupMembersRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listGroupMembers = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listGroupMembers(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listGroupMembers as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listGroupMembers as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listGroupMembersStream with error', async () => { - const client = new groupserviceModule.v3.GroupServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListGroupMembersRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListGroupMembersRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listGroupMembers.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listGroupMembersStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.api.MonitoredResource[] = []; - stream.on('data', (response: protos.google.api.MonitoredResource) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listGroupMembers.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listGroupMembers, request)); - assert( - (client.descriptors.page.listGroupMembers.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listGroupMembersStream without error', async () => { + const client = new groupserviceModule.v3.GroupServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListGroupMembersRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListGroupMembersRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.api.MonitoredResource()), + generateSampleMessage(new protos.google.api.MonitoredResource()), + generateSampleMessage(new protos.google.api.MonitoredResource()), + ]; + client.descriptors.page.listGroupMembers.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listGroupMembersStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.api.MonitoredResource[] = []; + stream.on('data', (response: protos.google.api.MonitoredResource) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listGroupMembers.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listGroupMembers, request), + ); + assert( + (client.descriptors.page.listGroupMembers.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('uses async iteration with listGroupMembers without error', async () => { - const client = new groupserviceModule.v3.GroupServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListGroupMembersRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListGroupMembersRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.api.MonitoredResource()), - generateSampleMessage(new protos.google.api.MonitoredResource()), - generateSampleMessage(new protos.google.api.MonitoredResource()), - ]; - client.descriptors.page.listGroupMembers.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.api.IMonitoredResource[] = []; - const iterable = client.listGroupMembersAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listGroupMembers.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listGroupMembers.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listGroupMembersStream with error', async () => { + const client = new groupserviceModule.v3.GroupServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListGroupMembersRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListGroupMembersRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listGroupMembers.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listGroupMembersStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.api.MonitoredResource[] = []; + stream.on('data', (response: protos.google.api.MonitoredResource) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listGroupMembers.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listGroupMembers, request), + ); + assert( + (client.descriptors.page.listGroupMembers.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('uses async iteration with listGroupMembers with error', async () => { - const client = new groupserviceModule.v3.GroupServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListGroupMembersRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListGroupMembersRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listGroupMembers.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listGroupMembersAsync(request); - await assert.rejects(async () => { - const responses: protos.google.api.IMonitoredResource[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listGroupMembers.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listGroupMembers.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listGroupMembers without error', async () => { + const client = new groupserviceModule.v3.GroupServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListGroupMembersRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListGroupMembersRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.api.MonitoredResource()), + generateSampleMessage(new protos.google.api.MonitoredResource()), + generateSampleMessage(new protos.google.api.MonitoredResource()), + ]; + client.descriptors.page.listGroupMembers.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.api.IMonitoredResource[] = []; + const iterable = client.listGroupMembersAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listGroupMembers.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listGroupMembers.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); }); - describe('Path templates', () => { - - describe('folderAlertPolicy', async () => { - const fakePath = "/rendered/path/folderAlertPolicy"; - const expectedParameters = { - folder: "folderValue", - alert_policy: "alertPolicyValue", - }; - const client = new groupserviceModule.v3.GroupServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.folderAlertPolicyPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderAlertPolicyPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderAlertPolicyPath', () => { - const result = client.folderAlertPolicyPath("folderValue", "alertPolicyValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderAlertPolicyPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderAlertPolicyName', () => { - const result = client.matchFolderFromFolderAlertPolicyName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderAlertPolicyPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchAlertPolicyFromFolderAlertPolicyName', () => { - const result = client.matchAlertPolicyFromFolderAlertPolicyName(fakePath); - assert.strictEqual(result, "alertPolicyValue"); - assert((client.pathTemplates.folderAlertPolicyPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('uses async iteration with listGroupMembers with error', async () => { + const client = new groupserviceModule.v3.GroupServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListGroupMembersRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListGroupMembersRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listGroupMembers.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listGroupMembersAsync(request); + await assert.rejects(async () => { + const responses: protos.google.api.IMonitoredResource[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listGroupMembers.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listGroupMembers.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + }); + + describe('Path templates', () => { + describe('folderAlertPolicy', async () => { + const fakePath = '/rendered/path/folderAlertPolicy'; + const expectedParameters = { + folder: 'folderValue', + alert_policy: 'alertPolicyValue', + }; + const client = new groupserviceModule.v3.GroupServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.folderAlertPolicyPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderAlertPolicyPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderAlertPolicyPath', () => { + const result = client.folderAlertPolicyPath( + 'folderValue', + 'alertPolicyValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.folderAlertPolicyPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderAlertPolicyName', () => { + const result = client.matchFolderFromFolderAlertPolicyName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + ( + client.pathTemplates.folderAlertPolicyPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchAlertPolicyFromFolderAlertPolicyName', () => { + const result = + client.matchAlertPolicyFromFolderAlertPolicyName(fakePath); + assert.strictEqual(result, 'alertPolicyValue'); + assert( + ( + client.pathTemplates.folderAlertPolicyPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('folderAlertPolicyCondition', async () => { - const fakePath = "/rendered/path/folderAlertPolicyCondition"; - const expectedParameters = { - folder: "folderValue", - alert_policy: "alertPolicyValue", - condition: "conditionValue", - }; - const client = new groupserviceModule.v3.GroupServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.folderAlertPolicyConditionPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderAlertPolicyConditionPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderAlertPolicyConditionPath', () => { - const result = client.folderAlertPolicyConditionPath("folderValue", "alertPolicyValue", "conditionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderAlertPolicyConditionPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderAlertPolicyConditionName', () => { - const result = client.matchFolderFromFolderAlertPolicyConditionName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderAlertPolicyConditionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchAlertPolicyFromFolderAlertPolicyConditionName', () => { - const result = client.matchAlertPolicyFromFolderAlertPolicyConditionName(fakePath); - assert.strictEqual(result, "alertPolicyValue"); - assert((client.pathTemplates.folderAlertPolicyConditionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchConditionFromFolderAlertPolicyConditionName', () => { - const result = client.matchConditionFromFolderAlertPolicyConditionName(fakePath); - assert.strictEqual(result, "conditionValue"); - assert((client.pathTemplates.folderAlertPolicyConditionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('folderAlertPolicyCondition', async () => { + const fakePath = '/rendered/path/folderAlertPolicyCondition'; + const expectedParameters = { + folder: 'folderValue', + alert_policy: 'alertPolicyValue', + condition: 'conditionValue', + }; + const client = new groupserviceModule.v3.GroupServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.folderAlertPolicyConditionPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderAlertPolicyConditionPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderAlertPolicyConditionPath', () => { + const result = client.folderAlertPolicyConditionPath( + 'folderValue', + 'alertPolicyValue', + 'conditionValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.folderAlertPolicyConditionPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderAlertPolicyConditionName', () => { + const result = + client.matchFolderFromFolderAlertPolicyConditionName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + ( + client.pathTemplates.folderAlertPolicyConditionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchAlertPolicyFromFolderAlertPolicyConditionName', () => { + const result = + client.matchAlertPolicyFromFolderAlertPolicyConditionName(fakePath); + assert.strictEqual(result, 'alertPolicyValue'); + assert( + ( + client.pathTemplates.folderAlertPolicyConditionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchConditionFromFolderAlertPolicyConditionName', () => { + const result = + client.matchConditionFromFolderAlertPolicyConditionName(fakePath); + assert.strictEqual(result, 'conditionValue'); + assert( + ( + client.pathTemplates.folderAlertPolicyConditionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('folderChannelDescriptor', async () => { - const fakePath = "/rendered/path/folderChannelDescriptor"; - const expectedParameters = { - folder: "folderValue", - channel_descriptor: "channelDescriptorValue", - }; - const client = new groupserviceModule.v3.GroupServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.folderChannelDescriptorPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderChannelDescriptorPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderChannelDescriptorPath', () => { - const result = client.folderChannelDescriptorPath("folderValue", "channelDescriptorValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderChannelDescriptorPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderChannelDescriptorName', () => { - const result = client.matchFolderFromFolderChannelDescriptorName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderChannelDescriptorPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchChannelDescriptorFromFolderChannelDescriptorName', () => { - const result = client.matchChannelDescriptorFromFolderChannelDescriptorName(fakePath); - assert.strictEqual(result, "channelDescriptorValue"); - assert((client.pathTemplates.folderChannelDescriptorPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('folderChannelDescriptor', async () => { + const fakePath = '/rendered/path/folderChannelDescriptor'; + const expectedParameters = { + folder: 'folderValue', + channel_descriptor: 'channelDescriptorValue', + }; + const client = new groupserviceModule.v3.GroupServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.folderChannelDescriptorPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderChannelDescriptorPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderChannelDescriptorPath', () => { + const result = client.folderChannelDescriptorPath( + 'folderValue', + 'channelDescriptorValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.folderChannelDescriptorPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderChannelDescriptorName', () => { + const result = + client.matchFolderFromFolderChannelDescriptorName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + ( + client.pathTemplates.folderChannelDescriptorPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchChannelDescriptorFromFolderChannelDescriptorName', () => { + const result = + client.matchChannelDescriptorFromFolderChannelDescriptorName( + fakePath, + ); + assert.strictEqual(result, 'channelDescriptorValue'); + assert( + ( + client.pathTemplates.folderChannelDescriptorPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('folderGroup', async () => { - const fakePath = "/rendered/path/folderGroup"; - const expectedParameters = { - folder: "folderValue", - group: "groupValue", - }; - const client = new groupserviceModule.v3.GroupServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.folderGroupPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderGroupPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderGroupPath', () => { - const result = client.folderGroupPath("folderValue", "groupValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderGroupPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderGroupName', () => { - const result = client.matchFolderFromFolderGroupName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderGroupPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchGroupFromFolderGroupName', () => { - const result = client.matchGroupFromFolderGroupName(fakePath); - assert.strictEqual(result, "groupValue"); - assert((client.pathTemplates.folderGroupPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('folderGroup', async () => { + const fakePath = '/rendered/path/folderGroup'; + const expectedParameters = { + folder: 'folderValue', + group: 'groupValue', + }; + const client = new groupserviceModule.v3.GroupServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.folderGroupPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderGroupPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderGroupPath', () => { + const result = client.folderGroupPath('folderValue', 'groupValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.folderGroupPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderGroupName', () => { + const result = client.matchFolderFromFolderGroupName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + (client.pathTemplates.folderGroupPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchGroupFromFolderGroupName', () => { + const result = client.matchGroupFromFolderGroupName(fakePath); + assert.strictEqual(result, 'groupValue'); + assert( + (client.pathTemplates.folderGroupPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('folderNotificationChannel', async () => { - const fakePath = "/rendered/path/folderNotificationChannel"; - const expectedParameters = { - folder: "folderValue", - notification_channel: "notificationChannelValue", - }; - const client = new groupserviceModule.v3.GroupServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.folderNotificationChannelPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderNotificationChannelPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderNotificationChannelPath', () => { - const result = client.folderNotificationChannelPath("folderValue", "notificationChannelValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderNotificationChannelPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderNotificationChannelName', () => { - const result = client.matchFolderFromFolderNotificationChannelName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderNotificationChannelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchNotificationChannelFromFolderNotificationChannelName', () => { - const result = client.matchNotificationChannelFromFolderNotificationChannelName(fakePath); - assert.strictEqual(result, "notificationChannelValue"); - assert((client.pathTemplates.folderNotificationChannelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('folderNotificationChannel', async () => { + const fakePath = '/rendered/path/folderNotificationChannel'; + const expectedParameters = { + folder: 'folderValue', + notification_channel: 'notificationChannelValue', + }; + const client = new groupserviceModule.v3.GroupServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.folderNotificationChannelPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderNotificationChannelPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderNotificationChannelPath', () => { + const result = client.folderNotificationChannelPath( + 'folderValue', + 'notificationChannelValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.folderNotificationChannelPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderNotificationChannelName', () => { + const result = + client.matchFolderFromFolderNotificationChannelName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + ( + client.pathTemplates.folderNotificationChannelPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchNotificationChannelFromFolderNotificationChannelName', () => { + const result = + client.matchNotificationChannelFromFolderNotificationChannelName( + fakePath, + ); + assert.strictEqual(result, 'notificationChannelValue'); + assert( + ( + client.pathTemplates.folderNotificationChannelPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('folderService', async () => { - const fakePath = "/rendered/path/folderService"; - const expectedParameters = { - folder: "folderValue", - service: "serviceValue", - }; - const client = new groupserviceModule.v3.GroupServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.folderServicePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderServicePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderServicePath', () => { - const result = client.folderServicePath("folderValue", "serviceValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderServicePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderServiceName', () => { - const result = client.matchFolderFromFolderServiceName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderServicePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServiceFromFolderServiceName', () => { - const result = client.matchServiceFromFolderServiceName(fakePath); - assert.strictEqual(result, "serviceValue"); - assert((client.pathTemplates.folderServicePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('folderService', async () => { + const fakePath = '/rendered/path/folderService'; + const expectedParameters = { + folder: 'folderValue', + service: 'serviceValue', + }; + const client = new groupserviceModule.v3.GroupServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.folderServicePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderServicePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderServicePath', () => { + const result = client.folderServicePath('folderValue', 'serviceValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.folderServicePathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderServiceName', () => { + const result = client.matchFolderFromFolderServiceName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + (client.pathTemplates.folderServicePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServiceFromFolderServiceName', () => { + const result = client.matchServiceFromFolderServiceName(fakePath); + assert.strictEqual(result, 'serviceValue'); + assert( + (client.pathTemplates.folderServicePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('folderServiceServiceLevelObjective', async () => { - const fakePath = "/rendered/path/folderServiceServiceLevelObjective"; - const expectedParameters = { - folder: "folderValue", - service: "serviceValue", - service_level_objective: "serviceLevelObjectiveValue", - }; - const client = new groupserviceModule.v3.GroupServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderServiceServiceLevelObjectivePath', () => { - const result = client.folderServiceServiceLevelObjectivePath("folderValue", "serviceValue", "serviceLevelObjectiveValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderServiceServiceLevelObjectiveName', () => { - const result = client.matchFolderFromFolderServiceServiceLevelObjectiveName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServiceFromFolderServiceServiceLevelObjectiveName', () => { - const result = client.matchServiceFromFolderServiceServiceLevelObjectiveName(fakePath); - assert.strictEqual(result, "serviceValue"); - assert((client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServiceLevelObjectiveFromFolderServiceServiceLevelObjectiveName', () => { - const result = client.matchServiceLevelObjectiveFromFolderServiceServiceLevelObjectiveName(fakePath); - assert.strictEqual(result, "serviceLevelObjectiveValue"); - assert((client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('folderServiceServiceLevelObjective', async () => { + const fakePath = '/rendered/path/folderServiceServiceLevelObjective'; + const expectedParameters = { + folder: 'folderValue', + service: 'serviceValue', + service_level_objective: 'serviceLevelObjectiveValue', + }; + const client = new groupserviceModule.v3.GroupServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('folderServiceServiceLevelObjectivePath', () => { + const result = client.folderServiceServiceLevelObjectivePath( + 'folderValue', + 'serviceValue', + 'serviceLevelObjectiveValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderServiceServiceLevelObjectiveName', () => { + const result = + client.matchFolderFromFolderServiceServiceLevelObjectiveName( + fakePath, + ); + assert.strictEqual(result, 'folderValue'); + assert( + ( + client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServiceFromFolderServiceServiceLevelObjectiveName', () => { + const result = + client.matchServiceFromFolderServiceServiceLevelObjectiveName( + fakePath, + ); + assert.strictEqual(result, 'serviceValue'); + assert( + ( + client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServiceLevelObjectiveFromFolderServiceServiceLevelObjectiveName', () => { + const result = + client.matchServiceLevelObjectiveFromFolderServiceServiceLevelObjectiveName( + fakePath, + ); + assert.strictEqual(result, 'serviceLevelObjectiveValue'); + assert( + ( + client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('folderUptimeCheckConfig', async () => { - const fakePath = "/rendered/path/folderUptimeCheckConfig"; - const expectedParameters = { - folder: "folderValue", - uptime_check_config: "uptimeCheckConfigValue", - }; - const client = new groupserviceModule.v3.GroupServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.folderUptimeCheckConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderUptimeCheckConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderUptimeCheckConfigPath', () => { - const result = client.folderUptimeCheckConfigPath("folderValue", "uptimeCheckConfigValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderUptimeCheckConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderUptimeCheckConfigName', () => { - const result = client.matchFolderFromFolderUptimeCheckConfigName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderUptimeCheckConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchUptimeCheckConfigFromFolderUptimeCheckConfigName', () => { - const result = client.matchUptimeCheckConfigFromFolderUptimeCheckConfigName(fakePath); - assert.strictEqual(result, "uptimeCheckConfigValue"); - assert((client.pathTemplates.folderUptimeCheckConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('folderUptimeCheckConfig', async () => { + const fakePath = '/rendered/path/folderUptimeCheckConfig'; + const expectedParameters = { + folder: 'folderValue', + uptime_check_config: 'uptimeCheckConfigValue', + }; + const client = new groupserviceModule.v3.GroupServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.folderUptimeCheckConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderUptimeCheckConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderUptimeCheckConfigPath', () => { + const result = client.folderUptimeCheckConfigPath( + 'folderValue', + 'uptimeCheckConfigValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.folderUptimeCheckConfigPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderUptimeCheckConfigName', () => { + const result = + client.matchFolderFromFolderUptimeCheckConfigName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + ( + client.pathTemplates.folderUptimeCheckConfigPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchUptimeCheckConfigFromFolderUptimeCheckConfigName', () => { + const result = + client.matchUptimeCheckConfigFromFolderUptimeCheckConfigName( + fakePath, + ); + assert.strictEqual(result, 'uptimeCheckConfigValue'); + assert( + ( + client.pathTemplates.folderUptimeCheckConfigPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('organizationAlertPolicy', async () => { - const fakePath = "/rendered/path/organizationAlertPolicy"; - const expectedParameters = { - organization: "organizationValue", - alert_policy: "alertPolicyValue", - }; - const client = new groupserviceModule.v3.GroupServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.organizationAlertPolicyPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationAlertPolicyPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationAlertPolicyPath', () => { - const result = client.organizationAlertPolicyPath("organizationValue", "alertPolicyValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationAlertPolicyPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationAlertPolicyName', () => { - const result = client.matchOrganizationFromOrganizationAlertPolicyName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationAlertPolicyPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchAlertPolicyFromOrganizationAlertPolicyName', () => { - const result = client.matchAlertPolicyFromOrganizationAlertPolicyName(fakePath); - assert.strictEqual(result, "alertPolicyValue"); - assert((client.pathTemplates.organizationAlertPolicyPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('organizationAlertPolicy', async () => { + const fakePath = '/rendered/path/organizationAlertPolicy'; + const expectedParameters = { + organization: 'organizationValue', + alert_policy: 'alertPolicyValue', + }; + const client = new groupserviceModule.v3.GroupServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.organizationAlertPolicyPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.organizationAlertPolicyPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('organizationAlertPolicyPath', () => { + const result = client.organizationAlertPolicyPath( + 'organizationValue', + 'alertPolicyValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationAlertPolicyPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationAlertPolicyName', () => { + const result = + client.matchOrganizationFromOrganizationAlertPolicyName(fakePath); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationAlertPolicyPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchAlertPolicyFromOrganizationAlertPolicyName', () => { + const result = + client.matchAlertPolicyFromOrganizationAlertPolicyName(fakePath); + assert.strictEqual(result, 'alertPolicyValue'); + assert( + ( + client.pathTemplates.organizationAlertPolicyPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('organizationAlertPolicyCondition', async () => { - const fakePath = "/rendered/path/organizationAlertPolicyCondition"; - const expectedParameters = { - organization: "organizationValue", - alert_policy: "alertPolicyValue", - condition: "conditionValue", - }; - const client = new groupserviceModule.v3.GroupServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.organizationAlertPolicyConditionPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationAlertPolicyConditionPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationAlertPolicyConditionPath', () => { - const result = client.organizationAlertPolicyConditionPath("organizationValue", "alertPolicyValue", "conditionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationAlertPolicyConditionPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationAlertPolicyConditionName', () => { - const result = client.matchOrganizationFromOrganizationAlertPolicyConditionName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationAlertPolicyConditionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchAlertPolicyFromOrganizationAlertPolicyConditionName', () => { - const result = client.matchAlertPolicyFromOrganizationAlertPolicyConditionName(fakePath); - assert.strictEqual(result, "alertPolicyValue"); - assert((client.pathTemplates.organizationAlertPolicyConditionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchConditionFromOrganizationAlertPolicyConditionName', () => { - const result = client.matchConditionFromOrganizationAlertPolicyConditionName(fakePath); - assert.strictEqual(result, "conditionValue"); - assert((client.pathTemplates.organizationAlertPolicyConditionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('organizationAlertPolicyCondition', async () => { + const fakePath = '/rendered/path/organizationAlertPolicyCondition'; + const expectedParameters = { + organization: 'organizationValue', + alert_policy: 'alertPolicyValue', + condition: 'conditionValue', + }; + const client = new groupserviceModule.v3.GroupServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.organizationAlertPolicyConditionPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.organizationAlertPolicyConditionPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('organizationAlertPolicyConditionPath', () => { + const result = client.organizationAlertPolicyConditionPath( + 'organizationValue', + 'alertPolicyValue', + 'conditionValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationAlertPolicyConditionPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationAlertPolicyConditionName', () => { + const result = + client.matchOrganizationFromOrganizationAlertPolicyConditionName( + fakePath, + ); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationAlertPolicyConditionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchAlertPolicyFromOrganizationAlertPolicyConditionName', () => { + const result = + client.matchAlertPolicyFromOrganizationAlertPolicyConditionName( + fakePath, + ); + assert.strictEqual(result, 'alertPolicyValue'); + assert( + ( + client.pathTemplates.organizationAlertPolicyConditionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchConditionFromOrganizationAlertPolicyConditionName', () => { + const result = + client.matchConditionFromOrganizationAlertPolicyConditionName( + fakePath, + ); + assert.strictEqual(result, 'conditionValue'); + assert( + ( + client.pathTemplates.organizationAlertPolicyConditionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('organizationChannelDescriptor', async () => { - const fakePath = "/rendered/path/organizationChannelDescriptor"; - const expectedParameters = { - organization: "organizationValue", - channel_descriptor: "channelDescriptorValue", - }; - const client = new groupserviceModule.v3.GroupServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.organizationChannelDescriptorPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationChannelDescriptorPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationChannelDescriptorPath', () => { - const result = client.organizationChannelDescriptorPath("organizationValue", "channelDescriptorValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationChannelDescriptorPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationChannelDescriptorName', () => { - const result = client.matchOrganizationFromOrganizationChannelDescriptorName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationChannelDescriptorPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchChannelDescriptorFromOrganizationChannelDescriptorName', () => { - const result = client.matchChannelDescriptorFromOrganizationChannelDescriptorName(fakePath); - assert.strictEqual(result, "channelDescriptorValue"); - assert((client.pathTemplates.organizationChannelDescriptorPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('organizationChannelDescriptor', async () => { + const fakePath = '/rendered/path/organizationChannelDescriptor'; + const expectedParameters = { + organization: 'organizationValue', + channel_descriptor: 'channelDescriptorValue', + }; + const client = new groupserviceModule.v3.GroupServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.organizationChannelDescriptorPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.organizationChannelDescriptorPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('organizationChannelDescriptorPath', () => { + const result = client.organizationChannelDescriptorPath( + 'organizationValue', + 'channelDescriptorValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationChannelDescriptorPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationChannelDescriptorName', () => { + const result = + client.matchOrganizationFromOrganizationChannelDescriptorName( + fakePath, + ); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationChannelDescriptorPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchChannelDescriptorFromOrganizationChannelDescriptorName', () => { + const result = + client.matchChannelDescriptorFromOrganizationChannelDescriptorName( + fakePath, + ); + assert.strictEqual(result, 'channelDescriptorValue'); + assert( + ( + client.pathTemplates.organizationChannelDescriptorPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('organizationGroup', async () => { - const fakePath = "/rendered/path/organizationGroup"; - const expectedParameters = { - organization: "organizationValue", - group: "groupValue", - }; - const client = new groupserviceModule.v3.GroupServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.organizationGroupPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationGroupPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationGroupPath', () => { - const result = client.organizationGroupPath("organizationValue", "groupValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationGroupPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationGroupName', () => { - const result = client.matchOrganizationFromOrganizationGroupName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationGroupPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchGroupFromOrganizationGroupName', () => { - const result = client.matchGroupFromOrganizationGroupName(fakePath); - assert.strictEqual(result, "groupValue"); - assert((client.pathTemplates.organizationGroupPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('organizationGroup', async () => { + const fakePath = '/rendered/path/organizationGroup'; + const expectedParameters = { + organization: 'organizationValue', + group: 'groupValue', + }; + const client = new groupserviceModule.v3.GroupServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.organizationGroupPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.organizationGroupPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('organizationGroupPath', () => { + const result = client.organizationGroupPath( + 'organizationValue', + 'groupValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationGroupPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationGroupName', () => { + const result = + client.matchOrganizationFromOrganizationGroupName(fakePath); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationGroupPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchGroupFromOrganizationGroupName', () => { + const result = client.matchGroupFromOrganizationGroupName(fakePath); + assert.strictEqual(result, 'groupValue'); + assert( + ( + client.pathTemplates.organizationGroupPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('organizationNotificationChannel', async () => { - const fakePath = "/rendered/path/organizationNotificationChannel"; - const expectedParameters = { - organization: "organizationValue", - notification_channel: "notificationChannelValue", - }; - const client = new groupserviceModule.v3.GroupServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.organizationNotificationChannelPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationNotificationChannelPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationNotificationChannelPath', () => { - const result = client.organizationNotificationChannelPath("organizationValue", "notificationChannelValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationNotificationChannelPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationNotificationChannelName', () => { - const result = client.matchOrganizationFromOrganizationNotificationChannelName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationNotificationChannelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchNotificationChannelFromOrganizationNotificationChannelName', () => { - const result = client.matchNotificationChannelFromOrganizationNotificationChannelName(fakePath); - assert.strictEqual(result, "notificationChannelValue"); - assert((client.pathTemplates.organizationNotificationChannelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('organizationNotificationChannel', async () => { + const fakePath = '/rendered/path/organizationNotificationChannel'; + const expectedParameters = { + organization: 'organizationValue', + notification_channel: 'notificationChannelValue', + }; + const client = new groupserviceModule.v3.GroupServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.organizationNotificationChannelPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.organizationNotificationChannelPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('organizationNotificationChannelPath', () => { + const result = client.organizationNotificationChannelPath( + 'organizationValue', + 'notificationChannelValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationNotificationChannelPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationNotificationChannelName', () => { + const result = + client.matchOrganizationFromOrganizationNotificationChannelName( + fakePath, + ); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationNotificationChannelPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchNotificationChannelFromOrganizationNotificationChannelName', () => { + const result = + client.matchNotificationChannelFromOrganizationNotificationChannelName( + fakePath, + ); + assert.strictEqual(result, 'notificationChannelValue'); + assert( + ( + client.pathTemplates.organizationNotificationChannelPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('organizationService', async () => { - const fakePath = "/rendered/path/organizationService"; - const expectedParameters = { - organization: "organizationValue", - service: "serviceValue", - }; - const client = new groupserviceModule.v3.GroupServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.organizationServicePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationServicePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationServicePath', () => { - const result = client.organizationServicePath("organizationValue", "serviceValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationServicePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationServiceName', () => { - const result = client.matchOrganizationFromOrganizationServiceName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationServicePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServiceFromOrganizationServiceName', () => { - const result = client.matchServiceFromOrganizationServiceName(fakePath); - assert.strictEqual(result, "serviceValue"); - assert((client.pathTemplates.organizationServicePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('organizationService', async () => { + const fakePath = '/rendered/path/organizationService'; + const expectedParameters = { + organization: 'organizationValue', + service: 'serviceValue', + }; + const client = new groupserviceModule.v3.GroupServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.organizationServicePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.organizationServicePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('organizationServicePath', () => { + const result = client.organizationServicePath( + 'organizationValue', + 'serviceValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationServicePathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationServiceName', () => { + const result = + client.matchOrganizationFromOrganizationServiceName(fakePath); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationServicePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServiceFromOrganizationServiceName', () => { + const result = client.matchServiceFromOrganizationServiceName(fakePath); + assert.strictEqual(result, 'serviceValue'); + assert( + ( + client.pathTemplates.organizationServicePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('organizationServiceServiceLevelObjective', async () => { - const fakePath = "/rendered/path/organizationServiceServiceLevelObjective"; - const expectedParameters = { - organization: "organizationValue", - service: "serviceValue", - service_level_objective: "serviceLevelObjectiveValue", - }; - const client = new groupserviceModule.v3.GroupServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationServiceServiceLevelObjectivePath', () => { - const result = client.organizationServiceServiceLevelObjectivePath("organizationValue", "serviceValue", "serviceLevelObjectiveValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationServiceServiceLevelObjectiveName', () => { - const result = client.matchOrganizationFromOrganizationServiceServiceLevelObjectiveName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServiceFromOrganizationServiceServiceLevelObjectiveName', () => { - const result = client.matchServiceFromOrganizationServiceServiceLevelObjectiveName(fakePath); - assert.strictEqual(result, "serviceValue"); - assert((client.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServiceLevelObjectiveFromOrganizationServiceServiceLevelObjectiveName', () => { - const result = client.matchServiceLevelObjectiveFromOrganizationServiceServiceLevelObjectiveName(fakePath); - assert.strictEqual(result, "serviceLevelObjectiveValue"); - assert((client.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('organizationServiceServiceLevelObjective', async () => { + const fakePath = + '/rendered/path/organizationServiceServiceLevelObjective'; + const expectedParameters = { + organization: 'organizationValue', + service: 'serviceValue', + service_level_objective: 'serviceLevelObjectiveValue', + }; + const client = new groupserviceModule.v3.GroupServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('organizationServiceServiceLevelObjectivePath', () => { + const result = client.organizationServiceServiceLevelObjectivePath( + 'organizationValue', + 'serviceValue', + 'serviceLevelObjectiveValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates + .organizationServiceServiceLevelObjectivePathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationServiceServiceLevelObjectiveName', () => { + const result = + client.matchOrganizationFromOrganizationServiceServiceLevelObjectiveName( + fakePath, + ); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates + .organizationServiceServiceLevelObjectivePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServiceFromOrganizationServiceServiceLevelObjectiveName', () => { + const result = + client.matchServiceFromOrganizationServiceServiceLevelObjectiveName( + fakePath, + ); + assert.strictEqual(result, 'serviceValue'); + assert( + ( + client.pathTemplates + .organizationServiceServiceLevelObjectivePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServiceLevelObjectiveFromOrganizationServiceServiceLevelObjectiveName', () => { + const result = + client.matchServiceLevelObjectiveFromOrganizationServiceServiceLevelObjectiveName( + fakePath, + ); + assert.strictEqual(result, 'serviceLevelObjectiveValue'); + assert( + ( + client.pathTemplates + .organizationServiceServiceLevelObjectivePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('organizationUptimeCheckConfig', async () => { - const fakePath = "/rendered/path/organizationUptimeCheckConfig"; - const expectedParameters = { - organization: "organizationValue", - uptime_check_config: "uptimeCheckConfigValue", - }; - const client = new groupserviceModule.v3.GroupServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.organizationUptimeCheckConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationUptimeCheckConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationUptimeCheckConfigPath', () => { - const result = client.organizationUptimeCheckConfigPath("organizationValue", "uptimeCheckConfigValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationUptimeCheckConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationUptimeCheckConfigName', () => { - const result = client.matchOrganizationFromOrganizationUptimeCheckConfigName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationUptimeCheckConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchUptimeCheckConfigFromOrganizationUptimeCheckConfigName', () => { - const result = client.matchUptimeCheckConfigFromOrganizationUptimeCheckConfigName(fakePath); - assert.strictEqual(result, "uptimeCheckConfigValue"); - assert((client.pathTemplates.organizationUptimeCheckConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('organizationUptimeCheckConfig', async () => { + const fakePath = '/rendered/path/organizationUptimeCheckConfig'; + const expectedParameters = { + organization: 'organizationValue', + uptime_check_config: 'uptimeCheckConfigValue', + }; + const client = new groupserviceModule.v3.GroupServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.organizationUptimeCheckConfigPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.organizationUptimeCheckConfigPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('organizationUptimeCheckConfigPath', () => { + const result = client.organizationUptimeCheckConfigPath( + 'organizationValue', + 'uptimeCheckConfigValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationUptimeCheckConfigPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationUptimeCheckConfigName', () => { + const result = + client.matchOrganizationFromOrganizationUptimeCheckConfigName( + fakePath, + ); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationUptimeCheckConfigPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchUptimeCheckConfigFromOrganizationUptimeCheckConfigName', () => { + const result = + client.matchUptimeCheckConfigFromOrganizationUptimeCheckConfigName( + fakePath, + ); + assert.strictEqual(result, 'uptimeCheckConfigValue'); + assert( + ( + client.pathTemplates.organizationUptimeCheckConfigPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectAlertPolicy', async () => { - const fakePath = "/rendered/path/projectAlertPolicy"; - const expectedParameters = { - project: "projectValue", - alert_policy: "alertPolicyValue", - }; - const client = new groupserviceModule.v3.GroupServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.projectAlertPolicyPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectAlertPolicyPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectAlertPolicyPath', () => { - const result = client.projectAlertPolicyPath("projectValue", "alertPolicyValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectAlertPolicyPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectAlertPolicyName', () => { - const result = client.matchProjectFromProjectAlertPolicyName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectAlertPolicyPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchAlertPolicyFromProjectAlertPolicyName', () => { - const result = client.matchAlertPolicyFromProjectAlertPolicyName(fakePath); - assert.strictEqual(result, "alertPolicyValue"); - assert((client.pathTemplates.projectAlertPolicyPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectAlertPolicy', async () => { + const fakePath = '/rendered/path/projectAlertPolicy'; + const expectedParameters = { + project: 'projectValue', + alert_policy: 'alertPolicyValue', + }; + const client = new groupserviceModule.v3.GroupServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.projectAlertPolicyPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectAlertPolicyPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectAlertPolicyPath', () => { + const result = client.projectAlertPolicyPath( + 'projectValue', + 'alertPolicyValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.projectAlertPolicyPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectAlertPolicyName', () => { + const result = client.matchProjectFromProjectAlertPolicyName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.projectAlertPolicyPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchAlertPolicyFromProjectAlertPolicyName', () => { + const result = + client.matchAlertPolicyFromProjectAlertPolicyName(fakePath); + assert.strictEqual(result, 'alertPolicyValue'); + assert( + ( + client.pathTemplates.projectAlertPolicyPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectAlertPolicyCondition', async () => { - const fakePath = "/rendered/path/projectAlertPolicyCondition"; - const expectedParameters = { - project: "projectValue", - alert_policy: "alertPolicyValue", - condition: "conditionValue", - }; - const client = new groupserviceModule.v3.GroupServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.projectAlertPolicyConditionPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectAlertPolicyConditionPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectAlertPolicyConditionPath', () => { - const result = client.projectAlertPolicyConditionPath("projectValue", "alertPolicyValue", "conditionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectAlertPolicyConditionPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectAlertPolicyConditionName', () => { - const result = client.matchProjectFromProjectAlertPolicyConditionName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectAlertPolicyConditionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchAlertPolicyFromProjectAlertPolicyConditionName', () => { - const result = client.matchAlertPolicyFromProjectAlertPolicyConditionName(fakePath); - assert.strictEqual(result, "alertPolicyValue"); - assert((client.pathTemplates.projectAlertPolicyConditionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchConditionFromProjectAlertPolicyConditionName', () => { - const result = client.matchConditionFromProjectAlertPolicyConditionName(fakePath); - assert.strictEqual(result, "conditionValue"); - assert((client.pathTemplates.projectAlertPolicyConditionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectAlertPolicyCondition', async () => { + const fakePath = '/rendered/path/projectAlertPolicyCondition'; + const expectedParameters = { + project: 'projectValue', + alert_policy: 'alertPolicyValue', + condition: 'conditionValue', + }; + const client = new groupserviceModule.v3.GroupServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.projectAlertPolicyConditionPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.projectAlertPolicyConditionPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectAlertPolicyConditionPath', () => { + const result = client.projectAlertPolicyConditionPath( + 'projectValue', + 'alertPolicyValue', + 'conditionValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.projectAlertPolicyConditionPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectAlertPolicyConditionName', () => { + const result = + client.matchProjectFromProjectAlertPolicyConditionName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.projectAlertPolicyConditionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchAlertPolicyFromProjectAlertPolicyConditionName', () => { + const result = + client.matchAlertPolicyFromProjectAlertPolicyConditionName(fakePath); + assert.strictEqual(result, 'alertPolicyValue'); + assert( + ( + client.pathTemplates.projectAlertPolicyConditionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchConditionFromProjectAlertPolicyConditionName', () => { + const result = + client.matchConditionFromProjectAlertPolicyConditionName(fakePath); + assert.strictEqual(result, 'conditionValue'); + assert( + ( + client.pathTemplates.projectAlertPolicyConditionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectChannelDescriptor', async () => { - const fakePath = "/rendered/path/projectChannelDescriptor"; - const expectedParameters = { - project: "projectValue", - channel_descriptor: "channelDescriptorValue", - }; - const client = new groupserviceModule.v3.GroupServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.projectChannelDescriptorPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectChannelDescriptorPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectChannelDescriptorPath', () => { - const result = client.projectChannelDescriptorPath("projectValue", "channelDescriptorValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectChannelDescriptorPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectChannelDescriptorName', () => { - const result = client.matchProjectFromProjectChannelDescriptorName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectChannelDescriptorPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchChannelDescriptorFromProjectChannelDescriptorName', () => { - const result = client.matchChannelDescriptorFromProjectChannelDescriptorName(fakePath); - assert.strictEqual(result, "channelDescriptorValue"); - assert((client.pathTemplates.projectChannelDescriptorPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectChannelDescriptor', async () => { + const fakePath = '/rendered/path/projectChannelDescriptor'; + const expectedParameters = { + project: 'projectValue', + channel_descriptor: 'channelDescriptorValue', + }; + const client = new groupserviceModule.v3.GroupServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.projectChannelDescriptorPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectChannelDescriptorPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectChannelDescriptorPath', () => { + const result = client.projectChannelDescriptorPath( + 'projectValue', + 'channelDescriptorValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.projectChannelDescriptorPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectChannelDescriptorName', () => { + const result = + client.matchProjectFromProjectChannelDescriptorName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.projectChannelDescriptorPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchChannelDescriptorFromProjectChannelDescriptorName', () => { + const result = + client.matchChannelDescriptorFromProjectChannelDescriptorName( + fakePath, + ); + assert.strictEqual(result, 'channelDescriptorValue'); + assert( + ( + client.pathTemplates.projectChannelDescriptorPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectGroup', async () => { - const fakePath = "/rendered/path/projectGroup"; - const expectedParameters = { - project: "projectValue", - group: "groupValue", - }; - const client = new groupserviceModule.v3.GroupServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.projectGroupPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectGroupPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectGroupPath', () => { - const result = client.projectGroupPath("projectValue", "groupValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectGroupPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectGroupName', () => { - const result = client.matchProjectFromProjectGroupName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectGroupPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchGroupFromProjectGroupName', () => { - const result = client.matchGroupFromProjectGroupName(fakePath); - assert.strictEqual(result, "groupValue"); - assert((client.pathTemplates.projectGroupPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectGroup', async () => { + const fakePath = '/rendered/path/projectGroup'; + const expectedParameters = { + project: 'projectValue', + group: 'groupValue', + }; + const client = new groupserviceModule.v3.GroupServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.projectGroupPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectGroupPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectGroupPath', () => { + const result = client.projectGroupPath('projectValue', 'groupValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.projectGroupPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectGroupName', () => { + const result = client.matchProjectFromProjectGroupName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.projectGroupPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchGroupFromProjectGroupName', () => { + const result = client.matchGroupFromProjectGroupName(fakePath); + assert.strictEqual(result, 'groupValue'); + assert( + (client.pathTemplates.projectGroupPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectNotificationChannel', async () => { - const fakePath = "/rendered/path/projectNotificationChannel"; - const expectedParameters = { - project: "projectValue", - notification_channel: "notificationChannelValue", - }; - const client = new groupserviceModule.v3.GroupServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.projectNotificationChannelPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectNotificationChannelPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectNotificationChannelPath', () => { - const result = client.projectNotificationChannelPath("projectValue", "notificationChannelValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectNotificationChannelPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectNotificationChannelName', () => { - const result = client.matchProjectFromProjectNotificationChannelName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectNotificationChannelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchNotificationChannelFromProjectNotificationChannelName', () => { - const result = client.matchNotificationChannelFromProjectNotificationChannelName(fakePath); - assert.strictEqual(result, "notificationChannelValue"); - assert((client.pathTemplates.projectNotificationChannelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectNotificationChannel', async () => { + const fakePath = '/rendered/path/projectNotificationChannel'; + const expectedParameters = { + project: 'projectValue', + notification_channel: 'notificationChannelValue', + }; + const client = new groupserviceModule.v3.GroupServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.projectNotificationChannelPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectNotificationChannelPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectNotificationChannelPath', () => { + const result = client.projectNotificationChannelPath( + 'projectValue', + 'notificationChannelValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.projectNotificationChannelPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectNotificationChannelName', () => { + const result = + client.matchProjectFromProjectNotificationChannelName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.projectNotificationChannelPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchNotificationChannelFromProjectNotificationChannelName', () => { + const result = + client.matchNotificationChannelFromProjectNotificationChannelName( + fakePath, + ); + assert.strictEqual(result, 'notificationChannelValue'); + assert( + ( + client.pathTemplates.projectNotificationChannelPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectService', async () => { - const fakePath = "/rendered/path/projectService"; - const expectedParameters = { - project: "projectValue", - service: "serviceValue", - }; - const client = new groupserviceModule.v3.GroupServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.projectServicePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectServicePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectServicePath', () => { - const result = client.projectServicePath("projectValue", "serviceValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectServicePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectServiceName', () => { - const result = client.matchProjectFromProjectServiceName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectServicePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServiceFromProjectServiceName', () => { - const result = client.matchServiceFromProjectServiceName(fakePath); - assert.strictEqual(result, "serviceValue"); - assert((client.pathTemplates.projectServicePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectService', async () => { + const fakePath = '/rendered/path/projectService'; + const expectedParameters = { + project: 'projectValue', + service: 'serviceValue', + }; + const client = new groupserviceModule.v3.GroupServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.projectServicePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectServicePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectServicePath', () => { + const result = client.projectServicePath( + 'projectValue', + 'serviceValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.projectServicePathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectServiceName', () => { + const result = client.matchProjectFromProjectServiceName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.projectServicePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServiceFromProjectServiceName', () => { + const result = client.matchServiceFromProjectServiceName(fakePath); + assert.strictEqual(result, 'serviceValue'); + assert( + (client.pathTemplates.projectServicePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectServiceServiceLevelObjective', async () => { - const fakePath = "/rendered/path/projectServiceServiceLevelObjective"; - const expectedParameters = { - project: "projectValue", - service: "serviceValue", - service_level_objective: "serviceLevelObjectiveValue", - }; - const client = new groupserviceModule.v3.GroupServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectServiceServiceLevelObjectivePath', () => { - const result = client.projectServiceServiceLevelObjectivePath("projectValue", "serviceValue", "serviceLevelObjectiveValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectServiceServiceLevelObjectiveName', () => { - const result = client.matchProjectFromProjectServiceServiceLevelObjectiveName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServiceFromProjectServiceServiceLevelObjectiveName', () => { - const result = client.matchServiceFromProjectServiceServiceLevelObjectiveName(fakePath); - assert.strictEqual(result, "serviceValue"); - assert((client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServiceLevelObjectiveFromProjectServiceServiceLevelObjectiveName', () => { - const result = client.matchServiceLevelObjectiveFromProjectServiceServiceLevelObjectiveName(fakePath); - assert.strictEqual(result, "serviceLevelObjectiveValue"); - assert((client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectServiceServiceLevelObjective', async () => { + const fakePath = '/rendered/path/projectServiceServiceLevelObjective'; + const expectedParameters = { + project: 'projectValue', + service: 'serviceValue', + service_level_objective: 'serviceLevelObjectiveValue', + }; + const client = new groupserviceModule.v3.GroupServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('projectServiceServiceLevelObjectivePath', () => { + const result = client.projectServiceServiceLevelObjectivePath( + 'projectValue', + 'serviceValue', + 'serviceLevelObjectiveValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectServiceServiceLevelObjectiveName', () => { + const result = + client.matchProjectFromProjectServiceServiceLevelObjectiveName( + fakePath, + ); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServiceFromProjectServiceServiceLevelObjectiveName', () => { + const result = + client.matchServiceFromProjectServiceServiceLevelObjectiveName( + fakePath, + ); + assert.strictEqual(result, 'serviceValue'); + assert( + ( + client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServiceLevelObjectiveFromProjectServiceServiceLevelObjectiveName', () => { + const result = + client.matchServiceLevelObjectiveFromProjectServiceServiceLevelObjectiveName( + fakePath, + ); + assert.strictEqual(result, 'serviceLevelObjectiveValue'); + assert( + ( + client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectUptimeCheckConfig', async () => { - const fakePath = "/rendered/path/projectUptimeCheckConfig"; - const expectedParameters = { - project: "projectValue", - uptime_check_config: "uptimeCheckConfigValue", - }; - const client = new groupserviceModule.v3.GroupServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.projectUptimeCheckConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectUptimeCheckConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectUptimeCheckConfigPath', () => { - const result = client.projectUptimeCheckConfigPath("projectValue", "uptimeCheckConfigValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectUptimeCheckConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectUptimeCheckConfigName', () => { - const result = client.matchProjectFromProjectUptimeCheckConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectUptimeCheckConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchUptimeCheckConfigFromProjectUptimeCheckConfigName', () => { - const result = client.matchUptimeCheckConfigFromProjectUptimeCheckConfigName(fakePath); - assert.strictEqual(result, "uptimeCheckConfigValue"); - assert((client.pathTemplates.projectUptimeCheckConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectUptimeCheckConfig', async () => { + const fakePath = '/rendered/path/projectUptimeCheckConfig'; + const expectedParameters = { + project: 'projectValue', + uptime_check_config: 'uptimeCheckConfigValue', + }; + const client = new groupserviceModule.v3.GroupServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.projectUptimeCheckConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectUptimeCheckConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectUptimeCheckConfigPath', () => { + const result = client.projectUptimeCheckConfigPath( + 'projectValue', + 'uptimeCheckConfigValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.projectUptimeCheckConfigPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectUptimeCheckConfigName', () => { + const result = + client.matchProjectFromProjectUptimeCheckConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.projectUptimeCheckConfigPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchUptimeCheckConfigFromProjectUptimeCheckConfigName', () => { + const result = + client.matchUptimeCheckConfigFromProjectUptimeCheckConfigName( + fakePath, + ); + assert.strictEqual(result, 'uptimeCheckConfigValue'); + assert( + ( + client.pathTemplates.projectUptimeCheckConfigPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/core/generator/gapic-generator-typescript/baselines/monitoring/test/gapic_metric_service_v3.ts.baseline b/core/generator/gapic-generator-typescript/baselines/monitoring/test/gapic_metric_service_v3.ts.baseline index 931858146bc4..cde9e4e7be12 100644 --- a/core/generator/gapic-generator-typescript/baselines/monitoring/test/gapic_metric_service_v3.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/monitoring/test/gapic_metric_service_v3.ts.baseline @@ -19,2709 +19,3936 @@ import * as protos from '../protos/protos'; import * as assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as metricserviceModule from '../src'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; -import {protobuf} from 'google-gax'; +import { protobuf } from 'google-gax'; // Dynamically loaded proto JSON is needed to get the type information // to fill in default values for request objects -const root = protobuf.Root.fromJSON(require('../protos/protos.json')).resolveAll(); +const root = protobuf.Root.fromJSON( + require('../protos/protos.json'), +).resolveAll(); // eslint-disable-next-line @typescript-eslint/no-unused-vars function getTypeDefaultValue(typeName: string, fields: string[]) { - let type = root.lookupType(typeName) as protobuf.Type; - for (const field of fields.slice(0, -1)) { - type = type.fields[field]?.resolvedType as protobuf.Type; - } - return type.fields[fields[fields.length - 1]]?.defaultValue; + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type.fields[field]?.resolvedType as protobuf.Type; + } + return type.fields[fields[fields.length - 1]]?.defaultValue; } function generateSampleMessage(instance: T) { - const filledObject = (instance.constructor as typeof protobuf.Message) - .toObject(instance as protobuf.Message, {defaults: true}); - return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, { defaults: true }); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; } function stubSimpleCall(response?: ResponseType, error?: Error) { - return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); } -function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { - return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +function stubSimpleCallWithCallback( + response?: ResponseType, + error?: Error, +) { + return error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); } -function stubPageStreamingCall(responses?: ResponseType[], error?: Error) { - const pagingStub = sinon.stub(); - if (responses) { - for (let i = 0; i < responses.length; ++i) { - pagingStub.onCall(i).callsArgWith(2, null, responses[i]); - } +function stubPageStreamingCall( + responses?: ResponseType[], + error?: Error, +) { + const pagingStub = sinon.stub(); + if (responses) { + for (let i = 0; i < responses.length; ++i) { + pagingStub.onCall(i).callsArgWith(2, null, responses[i]); } - const transformStub = error ? sinon.stub().callsArgWith(2, error) : pagingStub; - const mockStream = new PassThrough({ - objectMode: true, - transform: transformStub, - }); - // trigger as many responses as needed - if (responses) { - for (let i = 0; i < responses.length; ++i) { - setImmediate(() => { mockStream.write({}); }); - } - setImmediate(() => { mockStream.end(); }); - } else { - setImmediate(() => { mockStream.write({}); }); - setImmediate(() => { mockStream.end(); }); + } + const transformStub = error + ? sinon.stub().callsArgWith(2, error) + : pagingStub; + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + // trigger as many responses as needed + if (responses) { + for (let i = 0; i < responses.length; ++i) { + setImmediate(() => { + mockStream.write({}); + }); } - return sinon.stub().returns(mockStream); + setImmediate(() => { + mockStream.end(); + }); + } else { + setImmediate(() => { + mockStream.write({}); + }); + setImmediate(() => { + mockStream.end(); + }); + } + return sinon.stub().returns(mockStream); } -function stubAsyncIterationCall(responses?: ResponseType[], error?: Error) { - let counter = 0; - const asyncIterable = { - [Symbol.asyncIterator]() { - return { - async next() { - if (error) { - return Promise.reject(error); - } - if (counter >= responses!.length) { - return Promise.resolve({done: true, value: undefined}); - } - return Promise.resolve({done: false, value: responses![counter++]}); - } - }; - } - }; - return sinon.stub().returns(asyncIterable); +function stubAsyncIterationCall( + responses?: ResponseType[], + error?: Error, +) { + let counter = 0; + const asyncIterable = { + [Symbol.asyncIterator]() { + return { + async next() { + if (error) { + return Promise.reject(error); + } + if (counter >= responses!.length) { + return Promise.resolve({ done: true, value: undefined }); + } + return Promise.resolve({ done: false, value: responses![counter++] }); + }, + }; + }, + }; + return sinon.stub().returns(asyncIterable); } describe('v3.MetricServiceClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new metricserviceModule.v3.MetricServiceClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'monitoring.googleapis.com'); - }); - - it('has universeDomain', () => { - const client = new metricserviceModule.v3.MetricServiceClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); - - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - it('throws DeprecationWarning if static servicePath is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const servicePath = metricserviceModule.v3.MetricServiceClient.servicePath; - assert.strictEqual(servicePath, 'monitoring.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = metricserviceModule.v3.MetricServiceClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'monitoring.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new metricserviceModule.v3.MetricServiceClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'monitoring.example.com'); - }); - - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new metricserviceModule.v3.MetricServiceClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'monitoring.example.com'); - }); - - if (typeof process === 'object' && 'env' in process) { - describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { - it('sets apiEndpoint from environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new metricserviceModule.v3.MetricServiceClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'monitoring.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - - it('value configured in code has priority over environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new metricserviceModule.v3.MetricServiceClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'monitoring.configured.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { new metricserviceModule.v3.MetricServiceClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new metricserviceModule.v3.MetricServiceClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'monitoring.googleapis.com'); + }); - it('has port', () => { - const port = metricserviceModule.v3.MetricServiceClient.port; - assert(port); - assert(typeof port === 'number'); - }); + it('has universeDomain', () => { + const client = new metricserviceModule.v3.MetricServiceClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - it('should create a client with no option', () => { - const client = new metricserviceModule.v3.MetricServiceClient(); - assert(client); - }); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = + metricserviceModule.v3.MetricServiceClient.servicePath; + assert.strictEqual(servicePath, 'monitoring.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + metricserviceModule.v3.MetricServiceClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'monitoring.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = new metricserviceModule.v3.MetricServiceClient({ + universeDomain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'monitoring.example.com'); + }); - it('should create a client with gRPC fallback', () => { - const client = new metricserviceModule.v3.MetricServiceClient({ - fallback: true, - }); - assert(client); - }); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = new metricserviceModule.v3.MetricServiceClient({ + universe_domain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'monitoring.example.com'); + }); - it('has initialize method and supports deferred initialization', async () => { - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.metricServiceStub, undefined); - await client.initialize(); - assert(client.metricServiceStub); + if (typeof process === 'object' && 'env' in process) { + describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { + it('sets apiEndpoint from environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new metricserviceModule.v3.MetricServiceClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'monitoring.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } + }); + + it('value configured in code has priority over environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new metricserviceModule.v3.MetricServiceClient({ + universeDomain: 'configured.example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'monitoring.configured.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } + }); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new metricserviceModule.v3.MetricServiceClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); + }); - it('has close method for the initialized client', done => { - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.metricServiceStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('has port', () => { + const port = metricserviceModule.v3.MetricServiceClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('has close method for the non-initialized client', done => { - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.metricServiceStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('should create a client with no option', () => { + const client = new metricserviceModule.v3.MetricServiceClient(); + assert(client); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); - }); + it('should create a client with gRPC fallback', () => { + const client = new metricserviceModule.v3.MetricServiceClient({ + fallback: true, + }); + assert(client); + }); - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId((err?: Error|null, projectId?: string|null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } - }); - }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); - }); + it('has initialize method and supports deferred initialization', async () => { + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.metricServiceStub, undefined); + await client.initialize(); + assert(client.metricServiceStub); }); - describe('getMonitoredResourceDescriptor', () => { - it('invokes getMonitoredResourceDescriptor without error', async () => { - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.GetMonitoredResourceDescriptorRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.GetMonitoredResourceDescriptorRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.api.MonitoredResourceDescriptor() - ); - client.innerApiCalls.getMonitoredResourceDescriptor = stubSimpleCall(expectedResponse); - const [response] = await client.getMonitoredResourceDescriptor(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getMonitoredResourceDescriptor as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getMonitoredResourceDescriptor as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('has close method for the initialized client', (done) => { + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.metricServiceStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes getMonitoredResourceDescriptor without error using callback', async () => { - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.GetMonitoredResourceDescriptorRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.GetMonitoredResourceDescriptorRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.api.MonitoredResourceDescriptor() - ); - client.innerApiCalls.getMonitoredResourceDescriptor = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getMonitoredResourceDescriptor( - request, - (err?: Error|null, result?: protos.google.api.IMonitoredResourceDescriptor|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getMonitoredResourceDescriptor as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getMonitoredResourceDescriptor as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('has close method for the non-initialized client', (done) => { + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.metricServiceStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes getMonitoredResourceDescriptor with error', async () => { - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.GetMonitoredResourceDescriptorRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.GetMonitoredResourceDescriptorRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getMonitoredResourceDescriptor = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getMonitoredResourceDescriptor(request), expectedError); - const actualRequest = (client.innerApiCalls.getMonitoredResourceDescriptor as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getMonitoredResourceDescriptor as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + }); - it('invokes getMonitoredResourceDescriptor with closed client', async () => { - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.GetMonitoredResourceDescriptorRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.GetMonitoredResourceDescriptorRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getMonitoredResourceDescriptor(request), expectedError); - }); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } + }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + }); + + describe('getMonitoredResourceDescriptor', () => { + it('invokes getMonitoredResourceDescriptor without error', async () => { + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.GetMonitoredResourceDescriptorRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.GetMonitoredResourceDescriptorRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.api.MonitoredResourceDescriptor(), + ); + client.innerApiCalls.getMonitoredResourceDescriptor = + stubSimpleCall(expectedResponse); + const [response] = await client.getMonitoredResourceDescriptor(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getMonitoredResourceDescriptor as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getMonitoredResourceDescriptor as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('getMetricDescriptor', () => { - it('invokes getMetricDescriptor without error', async () => { - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.GetMetricDescriptorRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.GetMetricDescriptorRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.api.MetricDescriptor() - ); - client.innerApiCalls.getMetricDescriptor = stubSimpleCall(expectedResponse); - const [response] = await client.getMetricDescriptor(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getMetricDescriptor as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getMetricDescriptor as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getMonitoredResourceDescriptor without error using callback', async () => { + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.GetMonitoredResourceDescriptorRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.GetMonitoredResourceDescriptorRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.api.MonitoredResourceDescriptor(), + ); + client.innerApiCalls.getMonitoredResourceDescriptor = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getMonitoredResourceDescriptor( + request, + ( + err?: Error | null, + result?: protos.google.api.IMonitoredResourceDescriptor | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getMonitoredResourceDescriptor as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getMonitoredResourceDescriptor as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getMetricDescriptor without error using callback', async () => { - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.GetMetricDescriptorRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.GetMetricDescriptorRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.api.MetricDescriptor() - ); - client.innerApiCalls.getMetricDescriptor = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getMetricDescriptor( - request, - (err?: Error|null, result?: protos.google.api.IMetricDescriptor|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getMetricDescriptor as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getMetricDescriptor as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getMonitoredResourceDescriptor with error', async () => { + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.GetMonitoredResourceDescriptorRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.GetMonitoredResourceDescriptorRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getMonitoredResourceDescriptor = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.getMonitoredResourceDescriptor(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.getMonitoredResourceDescriptor as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getMonitoredResourceDescriptor as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getMetricDescriptor with error', async () => { - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.GetMetricDescriptorRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.GetMetricDescriptorRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getMetricDescriptor = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getMetricDescriptor(request), expectedError); - const actualRequest = (client.innerApiCalls.getMetricDescriptor as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getMetricDescriptor as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getMonitoredResourceDescriptor with closed client', async () => { + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.GetMonitoredResourceDescriptorRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.GetMonitoredResourceDescriptorRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.getMonitoredResourceDescriptor(request), + expectedError, + ); + }); + }); + + describe('getMetricDescriptor', () => { + it('invokes getMetricDescriptor without error', async () => { + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.GetMetricDescriptorRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.GetMetricDescriptorRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.api.MetricDescriptor(), + ); + client.innerApiCalls.getMetricDescriptor = + stubSimpleCall(expectedResponse); + const [response] = await client.getMetricDescriptor(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getMetricDescriptor as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getMetricDescriptor as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getMetricDescriptor with closed client', async () => { - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.GetMetricDescriptorRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.GetMetricDescriptorRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getMetricDescriptor(request), expectedError); - }); + it('invokes getMetricDescriptor without error using callback', async () => { + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.GetMetricDescriptorRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.GetMetricDescriptorRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.api.MetricDescriptor(), + ); + client.innerApiCalls.getMetricDescriptor = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getMetricDescriptor( + request, + ( + err?: Error | null, + result?: protos.google.api.IMetricDescriptor | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getMetricDescriptor as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getMetricDescriptor as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('createMetricDescriptor', () => { - it('invokes createMetricDescriptor without error', async () => { - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.CreateMetricDescriptorRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.CreateMetricDescriptorRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.api.MetricDescriptor() - ); - client.innerApiCalls.createMetricDescriptor = stubSimpleCall(expectedResponse); - const [response] = await client.createMetricDescriptor(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createMetricDescriptor as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createMetricDescriptor as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getMetricDescriptor with error', async () => { + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.GetMetricDescriptorRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.GetMetricDescriptorRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getMetricDescriptor = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getMetricDescriptor(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getMetricDescriptor as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getMetricDescriptor as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createMetricDescriptor without error using callback', async () => { - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.CreateMetricDescriptorRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.CreateMetricDescriptorRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.api.MetricDescriptor() - ); - client.innerApiCalls.createMetricDescriptor = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createMetricDescriptor( - request, - (err?: Error|null, result?: protos.google.api.IMetricDescriptor|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createMetricDescriptor as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createMetricDescriptor as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getMetricDescriptor with closed client', async () => { + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.GetMetricDescriptorRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.GetMetricDescriptorRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getMetricDescriptor(request), expectedError); + }); + }); + + describe('createMetricDescriptor', () => { + it('invokes createMetricDescriptor without error', async () => { + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.CreateMetricDescriptorRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.CreateMetricDescriptorRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.api.MetricDescriptor(), + ); + client.innerApiCalls.createMetricDescriptor = + stubSimpleCall(expectedResponse); + const [response] = await client.createMetricDescriptor(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createMetricDescriptor as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createMetricDescriptor as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createMetricDescriptor with error', async () => { - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.CreateMetricDescriptorRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.CreateMetricDescriptorRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createMetricDescriptor = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createMetricDescriptor(request), expectedError); - const actualRequest = (client.innerApiCalls.createMetricDescriptor as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createMetricDescriptor as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createMetricDescriptor without error using callback', async () => { + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.CreateMetricDescriptorRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.CreateMetricDescriptorRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.api.MetricDescriptor(), + ); + client.innerApiCalls.createMetricDescriptor = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createMetricDescriptor( + request, + ( + err?: Error | null, + result?: protos.google.api.IMetricDescriptor | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createMetricDescriptor as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createMetricDescriptor as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createMetricDescriptor with closed client', async () => { - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.CreateMetricDescriptorRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.CreateMetricDescriptorRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createMetricDescriptor(request), expectedError); - }); + it('invokes createMetricDescriptor with error', async () => { + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.CreateMetricDescriptorRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.CreateMetricDescriptorRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createMetricDescriptor = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.createMetricDescriptor(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.createMetricDescriptor as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createMetricDescriptor as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('deleteMetricDescriptor', () => { - it('invokes deleteMetricDescriptor without error', async () => { - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.DeleteMetricDescriptorRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.DeleteMetricDescriptorRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteMetricDescriptor = stubSimpleCall(expectedResponse); - const [response] = await client.deleteMetricDescriptor(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteMetricDescriptor as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteMetricDescriptor as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createMetricDescriptor with closed client', async () => { + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.CreateMetricDescriptorRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.CreateMetricDescriptorRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.createMetricDescriptor(request), + expectedError, + ); + }); + }); + + describe('deleteMetricDescriptor', () => { + it('invokes deleteMetricDescriptor without error', async () => { + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.DeleteMetricDescriptorRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.DeleteMetricDescriptorRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteMetricDescriptor = + stubSimpleCall(expectedResponse); + const [response] = await client.deleteMetricDescriptor(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteMetricDescriptor as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteMetricDescriptor as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteMetricDescriptor without error using callback', async () => { - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.DeleteMetricDescriptorRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.DeleteMetricDescriptorRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteMetricDescriptor = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteMetricDescriptor( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteMetricDescriptor as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteMetricDescriptor as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteMetricDescriptor without error using callback', async () => { + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.DeleteMetricDescriptorRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.DeleteMetricDescriptorRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteMetricDescriptor = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteMetricDescriptor( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteMetricDescriptor as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteMetricDescriptor as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteMetricDescriptor with error', async () => { - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.DeleteMetricDescriptorRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.DeleteMetricDescriptorRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteMetricDescriptor = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteMetricDescriptor(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteMetricDescriptor as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteMetricDescriptor as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteMetricDescriptor with error', async () => { + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.DeleteMetricDescriptorRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.DeleteMetricDescriptorRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteMetricDescriptor = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.deleteMetricDescriptor(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.deleteMetricDescriptor as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteMetricDescriptor as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteMetricDescriptor with closed client', async () => { - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.DeleteMetricDescriptorRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.DeleteMetricDescriptorRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteMetricDescriptor(request), expectedError); - }); + it('invokes deleteMetricDescriptor with closed client', async () => { + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.DeleteMetricDescriptorRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.DeleteMetricDescriptorRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.deleteMetricDescriptor(request), + expectedError, + ); + }); + }); + + describe('createTimeSeries', () => { + it('invokes createTimeSeries without error', async () => { + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.CreateTimeSeriesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.CreateTimeSeriesRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.createTimeSeries = stubSimpleCall(expectedResponse); + const [response] = await client.createTimeSeries(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createTimeSeries as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createTimeSeries as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('createTimeSeries', () => { - it('invokes createTimeSeries without error', async () => { - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.CreateTimeSeriesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.CreateTimeSeriesRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.createTimeSeries = stubSimpleCall(expectedResponse); - const [response] = await client.createTimeSeries(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createTimeSeries as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createTimeSeries as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createTimeSeries without error using callback', async () => { + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.CreateTimeSeriesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.CreateTimeSeriesRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.createTimeSeries = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createTimeSeries( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createTimeSeries as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createTimeSeries as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createTimeSeries without error using callback', async () => { - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.CreateTimeSeriesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.CreateTimeSeriesRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.createTimeSeries = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createTimeSeries( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createTimeSeries as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createTimeSeries as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createTimeSeries with error', async () => { + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.CreateTimeSeriesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.CreateTimeSeriesRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createTimeSeries = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.createTimeSeries(request), expectedError); + const actualRequest = ( + client.innerApiCalls.createTimeSeries as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createTimeSeries as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createTimeSeries with error', async () => { - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.CreateTimeSeriesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.CreateTimeSeriesRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createTimeSeries = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createTimeSeries(request), expectedError); - const actualRequest = (client.innerApiCalls.createTimeSeries as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createTimeSeries as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createTimeSeries with closed client', async () => { + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.CreateTimeSeriesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.CreateTimeSeriesRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.createTimeSeries(request), expectedError); + }); + }); + + describe('listMonitoredResourceDescriptors', () => { + it('invokes listMonitoredResourceDescriptors without error', async () => { + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListMonitoredResourceDescriptorsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListMonitoredResourceDescriptorsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.api.MonitoredResourceDescriptor(), + ), + generateSampleMessage( + new protos.google.api.MonitoredResourceDescriptor(), + ), + generateSampleMessage( + new protos.google.api.MonitoredResourceDescriptor(), + ), + ]; + client.innerApiCalls.listMonitoredResourceDescriptors = + stubSimpleCall(expectedResponse); + const [response] = await client.listMonitoredResourceDescriptors(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listMonitoredResourceDescriptors as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listMonitoredResourceDescriptors as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createTimeSeries with closed client', async () => { - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.CreateTimeSeriesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.CreateTimeSeriesRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createTimeSeries(request), expectedError); - }); + it('invokes listMonitoredResourceDescriptors without error using callback', async () => { + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListMonitoredResourceDescriptorsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListMonitoredResourceDescriptorsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.api.MonitoredResourceDescriptor(), + ), + generateSampleMessage( + new protos.google.api.MonitoredResourceDescriptor(), + ), + generateSampleMessage( + new protos.google.api.MonitoredResourceDescriptor(), + ), + ]; + client.innerApiCalls.listMonitoredResourceDescriptors = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listMonitoredResourceDescriptors( + request, + ( + err?: Error | null, + result?: protos.google.api.IMonitoredResourceDescriptor[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listMonitoredResourceDescriptors as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listMonitoredResourceDescriptors as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('listMonitoredResourceDescriptors', () => { - it('invokes listMonitoredResourceDescriptors without error', async () => { - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListMonitoredResourceDescriptorsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListMonitoredResourceDescriptorsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.api.MonitoredResourceDescriptor()), - generateSampleMessage(new protos.google.api.MonitoredResourceDescriptor()), - generateSampleMessage(new protos.google.api.MonitoredResourceDescriptor()), - ]; - client.innerApiCalls.listMonitoredResourceDescriptors = stubSimpleCall(expectedResponse); - const [response] = await client.listMonitoredResourceDescriptors(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listMonitoredResourceDescriptors as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listMonitoredResourceDescriptors as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listMonitoredResourceDescriptors with error', async () => { + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListMonitoredResourceDescriptorsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListMonitoredResourceDescriptorsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listMonitoredResourceDescriptors = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.listMonitoredResourceDescriptors(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.listMonitoredResourceDescriptors as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listMonitoredResourceDescriptors as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listMonitoredResourceDescriptors without error using callback', async () => { - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListMonitoredResourceDescriptorsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListMonitoredResourceDescriptorsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.api.MonitoredResourceDescriptor()), - generateSampleMessage(new protos.google.api.MonitoredResourceDescriptor()), - generateSampleMessage(new protos.google.api.MonitoredResourceDescriptor()), - ]; - client.innerApiCalls.listMonitoredResourceDescriptors = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listMonitoredResourceDescriptors( - request, - (err?: Error|null, result?: protos.google.api.IMonitoredResourceDescriptor[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listMonitoredResourceDescriptors as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listMonitoredResourceDescriptors as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listMonitoredResourceDescriptorsStream without error', async () => { + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListMonitoredResourceDescriptorsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListMonitoredResourceDescriptorsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.api.MonitoredResourceDescriptor(), + ), + generateSampleMessage( + new protos.google.api.MonitoredResourceDescriptor(), + ), + generateSampleMessage( + new protos.google.api.MonitoredResourceDescriptor(), + ), + ]; + client.descriptors.page.listMonitoredResourceDescriptors.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listMonitoredResourceDescriptorsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.api.MonitoredResourceDescriptor[] = []; + stream.on( + 'data', + (response: protos.google.api.MonitoredResourceDescriptor) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + ( + client.descriptors.page.listMonitoredResourceDescriptors + .createStream as SinonStub + ) + .getCall(0) + .calledWith( + client.innerApiCalls.listMonitoredResourceDescriptors, + request, + ), + ); + assert( + ( + client.descriptors.page.listMonitoredResourceDescriptors + .createStream as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); - it('invokes listMonitoredResourceDescriptors with error', async () => { - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListMonitoredResourceDescriptorsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListMonitoredResourceDescriptorsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listMonitoredResourceDescriptors = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listMonitoredResourceDescriptors(request), expectedError); - const actualRequest = (client.innerApiCalls.listMonitoredResourceDescriptors as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listMonitoredResourceDescriptors as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listMonitoredResourceDescriptorsStream with error', async () => { + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListMonitoredResourceDescriptorsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListMonitoredResourceDescriptorsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listMonitoredResourceDescriptors.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listMonitoredResourceDescriptorsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.api.MonitoredResourceDescriptor[] = []; + stream.on( + 'data', + (response: protos.google.api.MonitoredResourceDescriptor) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + ( + client.descriptors.page.listMonitoredResourceDescriptors + .createStream as SinonStub + ) + .getCall(0) + .calledWith( + client.innerApiCalls.listMonitoredResourceDescriptors, + request, + ), + ); + assert( + ( + client.descriptors.page.listMonitoredResourceDescriptors + .createStream as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); - it('invokes listMonitoredResourceDescriptorsStream without error', async () => { - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListMonitoredResourceDescriptorsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListMonitoredResourceDescriptorsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.api.MonitoredResourceDescriptor()), - generateSampleMessage(new protos.google.api.MonitoredResourceDescriptor()), - generateSampleMessage(new protos.google.api.MonitoredResourceDescriptor()), - ]; - client.descriptors.page.listMonitoredResourceDescriptors.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listMonitoredResourceDescriptorsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.api.MonitoredResourceDescriptor[] = []; - stream.on('data', (response: protos.google.api.MonitoredResourceDescriptor) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.listMonitoredResourceDescriptors.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listMonitoredResourceDescriptors, request)); - assert( - (client.descriptors.page.listMonitoredResourceDescriptors.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listMonitoredResourceDescriptors without error', async () => { + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListMonitoredResourceDescriptorsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListMonitoredResourceDescriptorsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.api.MonitoredResourceDescriptor(), + ), + generateSampleMessage( + new protos.google.api.MonitoredResourceDescriptor(), + ), + generateSampleMessage( + new protos.google.api.MonitoredResourceDescriptor(), + ), + ]; + client.descriptors.page.listMonitoredResourceDescriptors.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.api.IMonitoredResourceDescriptor[] = []; + const iterable = client.listMonitoredResourceDescriptorsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listMonitoredResourceDescriptors + .asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + ( + client.descriptors.page.listMonitoredResourceDescriptors + .asyncIterate as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); - it('invokes listMonitoredResourceDescriptorsStream with error', async () => { - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListMonitoredResourceDescriptorsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListMonitoredResourceDescriptorsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listMonitoredResourceDescriptors.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listMonitoredResourceDescriptorsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.api.MonitoredResourceDescriptor[] = []; - stream.on('data', (response: protos.google.api.MonitoredResourceDescriptor) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listMonitoredResourceDescriptors.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listMonitoredResourceDescriptors, request)); - assert( - (client.descriptors.page.listMonitoredResourceDescriptors.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listMonitoredResourceDescriptors with error', async () => { + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListMonitoredResourceDescriptorsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListMonitoredResourceDescriptorsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listMonitoredResourceDescriptors.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listMonitoredResourceDescriptorsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.api.IMonitoredResourceDescriptor[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listMonitoredResourceDescriptors + .asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + ( + client.descriptors.page.listMonitoredResourceDescriptors + .asyncIterate as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); + }); + + describe('listMetricDescriptors', () => { + it('invokes listMetricDescriptors without error', async () => { + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListMetricDescriptorsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListMetricDescriptorsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.api.MetricDescriptor()), + generateSampleMessage(new protos.google.api.MetricDescriptor()), + generateSampleMessage(new protos.google.api.MetricDescriptor()), + ]; + client.innerApiCalls.listMetricDescriptors = + stubSimpleCall(expectedResponse); + const [response] = await client.listMetricDescriptors(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listMetricDescriptors as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listMetricDescriptors as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('uses async iteration with listMonitoredResourceDescriptors without error', async () => { - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListMonitoredResourceDescriptorsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListMonitoredResourceDescriptorsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.api.MonitoredResourceDescriptor()), - generateSampleMessage(new protos.google.api.MonitoredResourceDescriptor()), - generateSampleMessage(new protos.google.api.MonitoredResourceDescriptor()), - ]; - client.descriptors.page.listMonitoredResourceDescriptors.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.api.IMonitoredResourceDescriptor[] = []; - const iterable = client.listMonitoredResourceDescriptorsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); + it('invokes listMetricDescriptors without error using callback', async () => { + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListMetricDescriptorsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListMetricDescriptorsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.api.MetricDescriptor()), + generateSampleMessage(new protos.google.api.MetricDescriptor()), + generateSampleMessage(new protos.google.api.MetricDescriptor()), + ]; + client.innerApiCalls.listMetricDescriptors = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listMetricDescriptors( + request, + ( + err?: Error | null, + result?: protos.google.api.IMetricDescriptor[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listMonitoredResourceDescriptors.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listMonitoredResourceDescriptors.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); - - it('uses async iteration with listMonitoredResourceDescriptors with error', async () => { - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListMonitoredResourceDescriptorsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListMonitoredResourceDescriptorsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listMonitoredResourceDescriptors.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listMonitoredResourceDescriptorsAsync(request); - await assert.rejects(async () => { - const responses: protos.google.api.IMonitoredResourceDescriptor[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listMonitoredResourceDescriptors.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listMonitoredResourceDescriptors.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listMetricDescriptors as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listMetricDescriptors as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('listMetricDescriptors', () => { - it('invokes listMetricDescriptors without error', async () => { - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListMetricDescriptorsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListMetricDescriptorsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.api.MetricDescriptor()), - generateSampleMessage(new protos.google.api.MetricDescriptor()), - generateSampleMessage(new protos.google.api.MetricDescriptor()), - ]; - client.innerApiCalls.listMetricDescriptors = stubSimpleCall(expectedResponse); - const [response] = await client.listMetricDescriptors(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listMetricDescriptors as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listMetricDescriptors as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listMetricDescriptors with error', async () => { + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListMetricDescriptorsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListMetricDescriptorsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listMetricDescriptors = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.listMetricDescriptors(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.listMetricDescriptors as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listMetricDescriptors as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listMetricDescriptors without error using callback', async () => { - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListMetricDescriptorsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListMetricDescriptorsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.api.MetricDescriptor()), - generateSampleMessage(new protos.google.api.MetricDescriptor()), - generateSampleMessage(new protos.google.api.MetricDescriptor()), - ]; - client.innerApiCalls.listMetricDescriptors = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listMetricDescriptors( - request, - (err?: Error|null, result?: protos.google.api.IMetricDescriptor[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listMetricDescriptors as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listMetricDescriptors as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listMetricDescriptorsStream without error', async () => { + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListMetricDescriptorsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListMetricDescriptorsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.api.MetricDescriptor()), + generateSampleMessage(new protos.google.api.MetricDescriptor()), + generateSampleMessage(new protos.google.api.MetricDescriptor()), + ]; + client.descriptors.page.listMetricDescriptors.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listMetricDescriptorsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.api.MetricDescriptor[] = []; + stream.on('data', (response: protos.google.api.MetricDescriptor) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + ( + client.descriptors.page.listMetricDescriptors + .createStream as SinonStub + ) + .getCall(0) + .calledWith(client.innerApiCalls.listMetricDescriptors, request), + ); + assert( + ( + client.descriptors.page.listMetricDescriptors + .createStream as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); - it('invokes listMetricDescriptors with error', async () => { - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListMetricDescriptorsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListMetricDescriptorsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listMetricDescriptors = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listMetricDescriptors(request), expectedError); - const actualRequest = (client.innerApiCalls.listMetricDescriptors as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listMetricDescriptors as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listMetricDescriptorsStream with error', async () => { + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListMetricDescriptorsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListMetricDescriptorsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listMetricDescriptors.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listMetricDescriptorsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.api.MetricDescriptor[] = []; + stream.on('data', (response: protos.google.api.MetricDescriptor) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + ( + client.descriptors.page.listMetricDescriptors + .createStream as SinonStub + ) + .getCall(0) + .calledWith(client.innerApiCalls.listMetricDescriptors, request), + ); + assert( + ( + client.descriptors.page.listMetricDescriptors + .createStream as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); - it('invokes listMetricDescriptorsStream without error', async () => { - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListMetricDescriptorsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListMetricDescriptorsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.api.MetricDescriptor()), - generateSampleMessage(new protos.google.api.MetricDescriptor()), - generateSampleMessage(new protos.google.api.MetricDescriptor()), - ]; - client.descriptors.page.listMetricDescriptors.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listMetricDescriptorsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.api.MetricDescriptor[] = []; - stream.on('data', (response: protos.google.api.MetricDescriptor) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.listMetricDescriptors.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listMetricDescriptors, request)); - assert( - (client.descriptors.page.listMetricDescriptors.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listMetricDescriptors without error', async () => { + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListMetricDescriptorsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListMetricDescriptorsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.api.MetricDescriptor()), + generateSampleMessage(new protos.google.api.MetricDescriptor()), + generateSampleMessage(new protos.google.api.MetricDescriptor()), + ]; + client.descriptors.page.listMetricDescriptors.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.api.IMetricDescriptor[] = []; + const iterable = client.listMetricDescriptorsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listMetricDescriptors + .asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + ( + client.descriptors.page.listMetricDescriptors + .asyncIterate as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); - it('invokes listMetricDescriptorsStream with error', async () => { - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListMetricDescriptorsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListMetricDescriptorsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listMetricDescriptors.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listMetricDescriptorsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.api.MetricDescriptor[] = []; - stream.on('data', (response: protos.google.api.MetricDescriptor) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listMetricDescriptors.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listMetricDescriptors, request)); - assert( - (client.descriptors.page.listMetricDescriptors.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listMetricDescriptors with error', async () => { + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListMetricDescriptorsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListMetricDescriptorsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listMetricDescriptors.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listMetricDescriptorsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.api.IMetricDescriptor[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listMetricDescriptors + .asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + ( + client.descriptors.page.listMetricDescriptors + .asyncIterate as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); + }); + + describe('listTimeSeries', () => { + it('invokes listTimeSeries without error', async () => { + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListTimeSeriesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListTimeSeriesRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.monitoring.v3.TimeSeries()), + generateSampleMessage(new protos.google.monitoring.v3.TimeSeries()), + generateSampleMessage(new protos.google.monitoring.v3.TimeSeries()), + ]; + client.innerApiCalls.listTimeSeries = stubSimpleCall(expectedResponse); + const [response] = await client.listTimeSeries(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listTimeSeries as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listTimeSeries as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('uses async iteration with listMetricDescriptors without error', async () => { - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListMetricDescriptorsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListMetricDescriptorsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.api.MetricDescriptor()), - generateSampleMessage(new protos.google.api.MetricDescriptor()), - generateSampleMessage(new protos.google.api.MetricDescriptor()), - ]; - client.descriptors.page.listMetricDescriptors.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.api.IMetricDescriptor[] = []; - const iterable = client.listMetricDescriptorsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); + it('invokes listTimeSeries without error using callback', async () => { + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListTimeSeriesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListTimeSeriesRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.monitoring.v3.TimeSeries()), + generateSampleMessage(new protos.google.monitoring.v3.TimeSeries()), + generateSampleMessage(new protos.google.monitoring.v3.TimeSeries()), + ]; + client.innerApiCalls.listTimeSeries = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listTimeSeries( + request, + ( + err?: Error | null, + result?: protos.google.monitoring.v3.ITimeSeries[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listMetricDescriptors.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listMetricDescriptors.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); - - it('uses async iteration with listMetricDescriptors with error', async () => { - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListMetricDescriptorsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListMetricDescriptorsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listMetricDescriptors.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listMetricDescriptorsAsync(request); - await assert.rejects(async () => { - const responses: protos.google.api.IMetricDescriptor[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listMetricDescriptors.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listMetricDescriptors.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listTimeSeries as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listTimeSeries as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('listTimeSeries', () => { - it('invokes listTimeSeries without error', async () => { - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListTimeSeriesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListTimeSeriesRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.monitoring.v3.TimeSeries()), - generateSampleMessage(new protos.google.monitoring.v3.TimeSeries()), - generateSampleMessage(new protos.google.monitoring.v3.TimeSeries()), - ]; - client.innerApiCalls.listTimeSeries = stubSimpleCall(expectedResponse); - const [response] = await client.listTimeSeries(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listTimeSeries as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listTimeSeries as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listTimeSeries without error using callback', async () => { - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListTimeSeriesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListTimeSeriesRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.monitoring.v3.TimeSeries()), - generateSampleMessage(new protos.google.monitoring.v3.TimeSeries()), - generateSampleMessage(new protos.google.monitoring.v3.TimeSeries()), - ]; - client.innerApiCalls.listTimeSeries = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listTimeSeries( - request, - (err?: Error|null, result?: protos.google.monitoring.v3.ITimeSeries[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listTimeSeries as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listTimeSeries as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listTimeSeries with error', async () => { - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListTimeSeriesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListTimeSeriesRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listTimeSeries = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listTimeSeries(request), expectedError); - const actualRequest = (client.innerApiCalls.listTimeSeries as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listTimeSeries as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listTimeSeriesStream without error', async () => { - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListTimeSeriesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListTimeSeriesRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.monitoring.v3.TimeSeries()), - generateSampleMessage(new protos.google.monitoring.v3.TimeSeries()), - generateSampleMessage(new protos.google.monitoring.v3.TimeSeries()), - ]; - client.descriptors.page.listTimeSeries.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listTimeSeriesStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.monitoring.v3.TimeSeries[] = []; - stream.on('data', (response: protos.google.monitoring.v3.TimeSeries) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.listTimeSeries.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listTimeSeries, request)); - assert( - (client.descriptors.page.listTimeSeries.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listTimeSeries with error', async () => { + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListTimeSeriesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListTimeSeriesRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listTimeSeries = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listTimeSeries(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listTimeSeries as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listTimeSeries as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listTimeSeriesStream with error', async () => { - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListTimeSeriesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListTimeSeriesRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listTimeSeries.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listTimeSeriesStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.monitoring.v3.TimeSeries[] = []; - stream.on('data', (response: protos.google.monitoring.v3.TimeSeries) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listTimeSeries.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listTimeSeries, request)); - assert( - (client.descriptors.page.listTimeSeries.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listTimeSeriesStream without error', async () => { + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListTimeSeriesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListTimeSeriesRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.monitoring.v3.TimeSeries()), + generateSampleMessage(new protos.google.monitoring.v3.TimeSeries()), + generateSampleMessage(new protos.google.monitoring.v3.TimeSeries()), + ]; + client.descriptors.page.listTimeSeries.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listTimeSeriesStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.monitoring.v3.TimeSeries[] = []; + stream.on( + 'data', + (response: protos.google.monitoring.v3.TimeSeries) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listTimeSeries.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listTimeSeries, request), + ); + assert( + (client.descriptors.page.listTimeSeries.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('uses async iteration with listTimeSeries without error', async () => { - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListTimeSeriesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListTimeSeriesRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.monitoring.v3.TimeSeries()), - generateSampleMessage(new protos.google.monitoring.v3.TimeSeries()), - generateSampleMessage(new protos.google.monitoring.v3.TimeSeries()), - ]; - client.descriptors.page.listTimeSeries.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.monitoring.v3.ITimeSeries[] = []; - const iterable = client.listTimeSeriesAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listTimeSeries.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listTimeSeries.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listTimeSeriesStream with error', async () => { + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListTimeSeriesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListTimeSeriesRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listTimeSeries.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listTimeSeriesStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.monitoring.v3.TimeSeries[] = []; + stream.on( + 'data', + (response: protos.google.monitoring.v3.TimeSeries) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listTimeSeries.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listTimeSeries, request), + ); + assert( + (client.descriptors.page.listTimeSeries.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('uses async iteration with listTimeSeries with error', async () => { - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListTimeSeriesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListTimeSeriesRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listTimeSeries.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listTimeSeriesAsync(request); - await assert.rejects(async () => { - const responses: protos.google.monitoring.v3.ITimeSeries[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listTimeSeries.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listTimeSeries.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listTimeSeries without error', async () => { + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListTimeSeriesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListTimeSeriesRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.monitoring.v3.TimeSeries()), + generateSampleMessage(new protos.google.monitoring.v3.TimeSeries()), + generateSampleMessage(new protos.google.monitoring.v3.TimeSeries()), + ]; + client.descriptors.page.listTimeSeries.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.monitoring.v3.ITimeSeries[] = []; + const iterable = client.listTimeSeriesAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listTimeSeries.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listTimeSeries.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); }); - describe('Path templates', () => { - - describe('folderAlertPolicy', async () => { - const fakePath = "/rendered/path/folderAlertPolicy"; - const expectedParameters = { - folder: "folderValue", - alert_policy: "alertPolicyValue", - }; - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.folderAlertPolicyPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderAlertPolicyPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderAlertPolicyPath', () => { - const result = client.folderAlertPolicyPath("folderValue", "alertPolicyValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderAlertPolicyPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderAlertPolicyName', () => { - const result = client.matchFolderFromFolderAlertPolicyName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderAlertPolicyPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchAlertPolicyFromFolderAlertPolicyName', () => { - const result = client.matchAlertPolicyFromFolderAlertPolicyName(fakePath); - assert.strictEqual(result, "alertPolicyValue"); - assert((client.pathTemplates.folderAlertPolicyPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('uses async iteration with listTimeSeries with error', async () => { + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListTimeSeriesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListTimeSeriesRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listTimeSeries.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listTimeSeriesAsync(request); + await assert.rejects(async () => { + const responses: protos.google.monitoring.v3.ITimeSeries[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listTimeSeries.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listTimeSeries.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + }); + + describe('Path templates', () => { + describe('folderAlertPolicy', async () => { + const fakePath = '/rendered/path/folderAlertPolicy'; + const expectedParameters = { + folder: 'folderValue', + alert_policy: 'alertPolicyValue', + }; + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.folderAlertPolicyPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderAlertPolicyPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderAlertPolicyPath', () => { + const result = client.folderAlertPolicyPath( + 'folderValue', + 'alertPolicyValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.folderAlertPolicyPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderAlertPolicyName', () => { + const result = client.matchFolderFromFolderAlertPolicyName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + ( + client.pathTemplates.folderAlertPolicyPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchAlertPolicyFromFolderAlertPolicyName', () => { + const result = + client.matchAlertPolicyFromFolderAlertPolicyName(fakePath); + assert.strictEqual(result, 'alertPolicyValue'); + assert( + ( + client.pathTemplates.folderAlertPolicyPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('folderAlertPolicyCondition', async () => { - const fakePath = "/rendered/path/folderAlertPolicyCondition"; - const expectedParameters = { - folder: "folderValue", - alert_policy: "alertPolicyValue", - condition: "conditionValue", - }; - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.folderAlertPolicyConditionPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderAlertPolicyConditionPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderAlertPolicyConditionPath', () => { - const result = client.folderAlertPolicyConditionPath("folderValue", "alertPolicyValue", "conditionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderAlertPolicyConditionPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderAlertPolicyConditionName', () => { - const result = client.matchFolderFromFolderAlertPolicyConditionName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderAlertPolicyConditionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchAlertPolicyFromFolderAlertPolicyConditionName', () => { - const result = client.matchAlertPolicyFromFolderAlertPolicyConditionName(fakePath); - assert.strictEqual(result, "alertPolicyValue"); - assert((client.pathTemplates.folderAlertPolicyConditionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchConditionFromFolderAlertPolicyConditionName', () => { - const result = client.matchConditionFromFolderAlertPolicyConditionName(fakePath); - assert.strictEqual(result, "conditionValue"); - assert((client.pathTemplates.folderAlertPolicyConditionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('folderAlertPolicyCondition', async () => { + const fakePath = '/rendered/path/folderAlertPolicyCondition'; + const expectedParameters = { + folder: 'folderValue', + alert_policy: 'alertPolicyValue', + condition: 'conditionValue', + }; + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.folderAlertPolicyConditionPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderAlertPolicyConditionPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderAlertPolicyConditionPath', () => { + const result = client.folderAlertPolicyConditionPath( + 'folderValue', + 'alertPolicyValue', + 'conditionValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.folderAlertPolicyConditionPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderAlertPolicyConditionName', () => { + const result = + client.matchFolderFromFolderAlertPolicyConditionName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + ( + client.pathTemplates.folderAlertPolicyConditionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchAlertPolicyFromFolderAlertPolicyConditionName', () => { + const result = + client.matchAlertPolicyFromFolderAlertPolicyConditionName(fakePath); + assert.strictEqual(result, 'alertPolicyValue'); + assert( + ( + client.pathTemplates.folderAlertPolicyConditionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchConditionFromFolderAlertPolicyConditionName', () => { + const result = + client.matchConditionFromFolderAlertPolicyConditionName(fakePath); + assert.strictEqual(result, 'conditionValue'); + assert( + ( + client.pathTemplates.folderAlertPolicyConditionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('folderChannelDescriptor', async () => { - const fakePath = "/rendered/path/folderChannelDescriptor"; - const expectedParameters = { - folder: "folderValue", - channel_descriptor: "channelDescriptorValue", - }; - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.folderChannelDescriptorPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderChannelDescriptorPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderChannelDescriptorPath', () => { - const result = client.folderChannelDescriptorPath("folderValue", "channelDescriptorValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderChannelDescriptorPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderChannelDescriptorName', () => { - const result = client.matchFolderFromFolderChannelDescriptorName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderChannelDescriptorPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchChannelDescriptorFromFolderChannelDescriptorName', () => { - const result = client.matchChannelDescriptorFromFolderChannelDescriptorName(fakePath); - assert.strictEqual(result, "channelDescriptorValue"); - assert((client.pathTemplates.folderChannelDescriptorPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('folderChannelDescriptor', async () => { + const fakePath = '/rendered/path/folderChannelDescriptor'; + const expectedParameters = { + folder: 'folderValue', + channel_descriptor: 'channelDescriptorValue', + }; + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.folderChannelDescriptorPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderChannelDescriptorPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderChannelDescriptorPath', () => { + const result = client.folderChannelDescriptorPath( + 'folderValue', + 'channelDescriptorValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.folderChannelDescriptorPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderChannelDescriptorName', () => { + const result = + client.matchFolderFromFolderChannelDescriptorName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + ( + client.pathTemplates.folderChannelDescriptorPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchChannelDescriptorFromFolderChannelDescriptorName', () => { + const result = + client.matchChannelDescriptorFromFolderChannelDescriptorName( + fakePath, + ); + assert.strictEqual(result, 'channelDescriptorValue'); + assert( + ( + client.pathTemplates.folderChannelDescriptorPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('folderGroup', async () => { - const fakePath = "/rendered/path/folderGroup"; - const expectedParameters = { - folder: "folderValue", - group: "groupValue", - }; - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.folderGroupPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderGroupPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderGroupPath', () => { - const result = client.folderGroupPath("folderValue", "groupValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderGroupPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderGroupName', () => { - const result = client.matchFolderFromFolderGroupName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderGroupPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchGroupFromFolderGroupName', () => { - const result = client.matchGroupFromFolderGroupName(fakePath); - assert.strictEqual(result, "groupValue"); - assert((client.pathTemplates.folderGroupPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('folderGroup', async () => { + const fakePath = '/rendered/path/folderGroup'; + const expectedParameters = { + folder: 'folderValue', + group: 'groupValue', + }; + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.folderGroupPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderGroupPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderGroupPath', () => { + const result = client.folderGroupPath('folderValue', 'groupValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.folderGroupPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderGroupName', () => { + const result = client.matchFolderFromFolderGroupName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + (client.pathTemplates.folderGroupPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchGroupFromFolderGroupName', () => { + const result = client.matchGroupFromFolderGroupName(fakePath); + assert.strictEqual(result, 'groupValue'); + assert( + (client.pathTemplates.folderGroupPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('folderMetricDescriptor', async () => { - const fakePath = "/rendered/path/folderMetricDescriptor"; - const expectedParameters = { - folder: "folderValue", - metric_descriptor: "metricDescriptorValue", - }; - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.folderMetricDescriptorPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderMetricDescriptorPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderMetricDescriptorPath', () => { - const result = client.folderMetricDescriptorPath("folderValue", "metricDescriptorValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderMetricDescriptorPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderMetricDescriptorName', () => { - const result = client.matchFolderFromFolderMetricDescriptorName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderMetricDescriptorPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchMetricDescriptorFromFolderMetricDescriptorName', () => { - const result = client.matchMetricDescriptorFromFolderMetricDescriptorName(fakePath); - assert.strictEqual(result, "metricDescriptorValue"); - assert((client.pathTemplates.folderMetricDescriptorPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('folderMetricDescriptor', async () => { + const fakePath = '/rendered/path/folderMetricDescriptor'; + const expectedParameters = { + folder: 'folderValue', + metric_descriptor: 'metricDescriptorValue', + }; + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.folderMetricDescriptorPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderMetricDescriptorPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderMetricDescriptorPath', () => { + const result = client.folderMetricDescriptorPath( + 'folderValue', + 'metricDescriptorValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.folderMetricDescriptorPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderMetricDescriptorName', () => { + const result = + client.matchFolderFromFolderMetricDescriptorName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + ( + client.pathTemplates.folderMetricDescriptorPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchMetricDescriptorFromFolderMetricDescriptorName', () => { + const result = + client.matchMetricDescriptorFromFolderMetricDescriptorName(fakePath); + assert.strictEqual(result, 'metricDescriptorValue'); + assert( + ( + client.pathTemplates.folderMetricDescriptorPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('folderMonitoredResourceDescriptor', async () => { - const fakePath = "/rendered/path/folderMonitoredResourceDescriptor"; - const expectedParameters = { - folder: "folderValue", - monitored_resource_descriptor: "monitoredResourceDescriptorValue", - }; - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.folderMonitoredResourceDescriptorPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderMonitoredResourceDescriptorPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderMonitoredResourceDescriptorPath', () => { - const result = client.folderMonitoredResourceDescriptorPath("folderValue", "monitoredResourceDescriptorValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderMonitoredResourceDescriptorPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderMonitoredResourceDescriptorName', () => { - const result = client.matchFolderFromFolderMonitoredResourceDescriptorName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderMonitoredResourceDescriptorPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchMonitoredResourceDescriptorFromFolderMonitoredResourceDescriptorName', () => { - const result = client.matchMonitoredResourceDescriptorFromFolderMonitoredResourceDescriptorName(fakePath); - assert.strictEqual(result, "monitoredResourceDescriptorValue"); - assert((client.pathTemplates.folderMonitoredResourceDescriptorPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('folderMonitoredResourceDescriptor', async () => { + const fakePath = '/rendered/path/folderMonitoredResourceDescriptor'; + const expectedParameters = { + folder: 'folderValue', + monitored_resource_descriptor: 'monitoredResourceDescriptorValue', + }; + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.folderMonitoredResourceDescriptorPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.folderMonitoredResourceDescriptorPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('folderMonitoredResourceDescriptorPath', () => { + const result = client.folderMonitoredResourceDescriptorPath( + 'folderValue', + 'monitoredResourceDescriptorValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.folderMonitoredResourceDescriptorPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderMonitoredResourceDescriptorName', () => { + const result = + client.matchFolderFromFolderMonitoredResourceDescriptorName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + ( + client.pathTemplates.folderMonitoredResourceDescriptorPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchMonitoredResourceDescriptorFromFolderMonitoredResourceDescriptorName', () => { + const result = + client.matchMonitoredResourceDescriptorFromFolderMonitoredResourceDescriptorName( + fakePath, + ); + assert.strictEqual(result, 'monitoredResourceDescriptorValue'); + assert( + ( + client.pathTemplates.folderMonitoredResourceDescriptorPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('folderNotificationChannel', async () => { - const fakePath = "/rendered/path/folderNotificationChannel"; - const expectedParameters = { - folder: "folderValue", - notification_channel: "notificationChannelValue", - }; - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.folderNotificationChannelPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderNotificationChannelPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderNotificationChannelPath', () => { - const result = client.folderNotificationChannelPath("folderValue", "notificationChannelValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderNotificationChannelPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderNotificationChannelName', () => { - const result = client.matchFolderFromFolderNotificationChannelName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderNotificationChannelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchNotificationChannelFromFolderNotificationChannelName', () => { - const result = client.matchNotificationChannelFromFolderNotificationChannelName(fakePath); - assert.strictEqual(result, "notificationChannelValue"); - assert((client.pathTemplates.folderNotificationChannelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('folderNotificationChannel', async () => { + const fakePath = '/rendered/path/folderNotificationChannel'; + const expectedParameters = { + folder: 'folderValue', + notification_channel: 'notificationChannelValue', + }; + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.folderNotificationChannelPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderNotificationChannelPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderNotificationChannelPath', () => { + const result = client.folderNotificationChannelPath( + 'folderValue', + 'notificationChannelValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.folderNotificationChannelPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderNotificationChannelName', () => { + const result = + client.matchFolderFromFolderNotificationChannelName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + ( + client.pathTemplates.folderNotificationChannelPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchNotificationChannelFromFolderNotificationChannelName', () => { + const result = + client.matchNotificationChannelFromFolderNotificationChannelName( + fakePath, + ); + assert.strictEqual(result, 'notificationChannelValue'); + assert( + ( + client.pathTemplates.folderNotificationChannelPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('folderService', async () => { - const fakePath = "/rendered/path/folderService"; - const expectedParameters = { - folder: "folderValue", - service: "serviceValue", - }; - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.folderServicePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderServicePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderServicePath', () => { - const result = client.folderServicePath("folderValue", "serviceValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderServicePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderServiceName', () => { - const result = client.matchFolderFromFolderServiceName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderServicePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServiceFromFolderServiceName', () => { - const result = client.matchServiceFromFolderServiceName(fakePath); - assert.strictEqual(result, "serviceValue"); - assert((client.pathTemplates.folderServicePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('folderService', async () => { + const fakePath = '/rendered/path/folderService'; + const expectedParameters = { + folder: 'folderValue', + service: 'serviceValue', + }; + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.folderServicePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderServicePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderServicePath', () => { + const result = client.folderServicePath('folderValue', 'serviceValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.folderServicePathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderServiceName', () => { + const result = client.matchFolderFromFolderServiceName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + (client.pathTemplates.folderServicePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServiceFromFolderServiceName', () => { + const result = client.matchServiceFromFolderServiceName(fakePath); + assert.strictEqual(result, 'serviceValue'); + assert( + (client.pathTemplates.folderServicePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('folderServiceServiceLevelObjective', async () => { - const fakePath = "/rendered/path/folderServiceServiceLevelObjective"; - const expectedParameters = { - folder: "folderValue", - service: "serviceValue", - service_level_objective: "serviceLevelObjectiveValue", - }; - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderServiceServiceLevelObjectivePath', () => { - const result = client.folderServiceServiceLevelObjectivePath("folderValue", "serviceValue", "serviceLevelObjectiveValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderServiceServiceLevelObjectiveName', () => { - const result = client.matchFolderFromFolderServiceServiceLevelObjectiveName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServiceFromFolderServiceServiceLevelObjectiveName', () => { - const result = client.matchServiceFromFolderServiceServiceLevelObjectiveName(fakePath); - assert.strictEqual(result, "serviceValue"); - assert((client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServiceLevelObjectiveFromFolderServiceServiceLevelObjectiveName', () => { - const result = client.matchServiceLevelObjectiveFromFolderServiceServiceLevelObjectiveName(fakePath); - assert.strictEqual(result, "serviceLevelObjectiveValue"); - assert((client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('folderServiceServiceLevelObjective', async () => { + const fakePath = '/rendered/path/folderServiceServiceLevelObjective'; + const expectedParameters = { + folder: 'folderValue', + service: 'serviceValue', + service_level_objective: 'serviceLevelObjectiveValue', + }; + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('folderServiceServiceLevelObjectivePath', () => { + const result = client.folderServiceServiceLevelObjectivePath( + 'folderValue', + 'serviceValue', + 'serviceLevelObjectiveValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderServiceServiceLevelObjectiveName', () => { + const result = + client.matchFolderFromFolderServiceServiceLevelObjectiveName( + fakePath, + ); + assert.strictEqual(result, 'folderValue'); + assert( + ( + client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServiceFromFolderServiceServiceLevelObjectiveName', () => { + const result = + client.matchServiceFromFolderServiceServiceLevelObjectiveName( + fakePath, + ); + assert.strictEqual(result, 'serviceValue'); + assert( + ( + client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServiceLevelObjectiveFromFolderServiceServiceLevelObjectiveName', () => { + const result = + client.matchServiceLevelObjectiveFromFolderServiceServiceLevelObjectiveName( + fakePath, + ); + assert.strictEqual(result, 'serviceLevelObjectiveValue'); + assert( + ( + client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('folderUptimeCheckConfig', async () => { - const fakePath = "/rendered/path/folderUptimeCheckConfig"; - const expectedParameters = { - folder: "folderValue", - uptime_check_config: "uptimeCheckConfigValue", - }; - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.folderUptimeCheckConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderUptimeCheckConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderUptimeCheckConfigPath', () => { - const result = client.folderUptimeCheckConfigPath("folderValue", "uptimeCheckConfigValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderUptimeCheckConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderUptimeCheckConfigName', () => { - const result = client.matchFolderFromFolderUptimeCheckConfigName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderUptimeCheckConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchUptimeCheckConfigFromFolderUptimeCheckConfigName', () => { - const result = client.matchUptimeCheckConfigFromFolderUptimeCheckConfigName(fakePath); - assert.strictEqual(result, "uptimeCheckConfigValue"); - assert((client.pathTemplates.folderUptimeCheckConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('folderUptimeCheckConfig', async () => { + const fakePath = '/rendered/path/folderUptimeCheckConfig'; + const expectedParameters = { + folder: 'folderValue', + uptime_check_config: 'uptimeCheckConfigValue', + }; + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.folderUptimeCheckConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderUptimeCheckConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderUptimeCheckConfigPath', () => { + const result = client.folderUptimeCheckConfigPath( + 'folderValue', + 'uptimeCheckConfigValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.folderUptimeCheckConfigPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderUptimeCheckConfigName', () => { + const result = + client.matchFolderFromFolderUptimeCheckConfigName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + ( + client.pathTemplates.folderUptimeCheckConfigPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchUptimeCheckConfigFromFolderUptimeCheckConfigName', () => { + const result = + client.matchUptimeCheckConfigFromFolderUptimeCheckConfigName( + fakePath, + ); + assert.strictEqual(result, 'uptimeCheckConfigValue'); + assert( + ( + client.pathTemplates.folderUptimeCheckConfigPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('organizationAlertPolicy', async () => { - const fakePath = "/rendered/path/organizationAlertPolicy"; - const expectedParameters = { - organization: "organizationValue", - alert_policy: "alertPolicyValue", - }; - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.organizationAlertPolicyPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationAlertPolicyPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationAlertPolicyPath', () => { - const result = client.organizationAlertPolicyPath("organizationValue", "alertPolicyValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationAlertPolicyPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationAlertPolicyName', () => { - const result = client.matchOrganizationFromOrganizationAlertPolicyName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationAlertPolicyPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchAlertPolicyFromOrganizationAlertPolicyName', () => { - const result = client.matchAlertPolicyFromOrganizationAlertPolicyName(fakePath); - assert.strictEqual(result, "alertPolicyValue"); - assert((client.pathTemplates.organizationAlertPolicyPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('organizationAlertPolicy', async () => { + const fakePath = '/rendered/path/organizationAlertPolicy'; + const expectedParameters = { + organization: 'organizationValue', + alert_policy: 'alertPolicyValue', + }; + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.organizationAlertPolicyPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.organizationAlertPolicyPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('organizationAlertPolicyPath', () => { + const result = client.organizationAlertPolicyPath( + 'organizationValue', + 'alertPolicyValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationAlertPolicyPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationAlertPolicyName', () => { + const result = + client.matchOrganizationFromOrganizationAlertPolicyName(fakePath); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationAlertPolicyPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchAlertPolicyFromOrganizationAlertPolicyName', () => { + const result = + client.matchAlertPolicyFromOrganizationAlertPolicyName(fakePath); + assert.strictEqual(result, 'alertPolicyValue'); + assert( + ( + client.pathTemplates.organizationAlertPolicyPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('organizationAlertPolicyCondition', async () => { - const fakePath = "/rendered/path/organizationAlertPolicyCondition"; - const expectedParameters = { - organization: "organizationValue", - alert_policy: "alertPolicyValue", - condition: "conditionValue", - }; - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.organizationAlertPolicyConditionPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationAlertPolicyConditionPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationAlertPolicyConditionPath', () => { - const result = client.organizationAlertPolicyConditionPath("organizationValue", "alertPolicyValue", "conditionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationAlertPolicyConditionPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationAlertPolicyConditionName', () => { - const result = client.matchOrganizationFromOrganizationAlertPolicyConditionName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationAlertPolicyConditionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchAlertPolicyFromOrganizationAlertPolicyConditionName', () => { - const result = client.matchAlertPolicyFromOrganizationAlertPolicyConditionName(fakePath); - assert.strictEqual(result, "alertPolicyValue"); - assert((client.pathTemplates.organizationAlertPolicyConditionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchConditionFromOrganizationAlertPolicyConditionName', () => { - const result = client.matchConditionFromOrganizationAlertPolicyConditionName(fakePath); - assert.strictEqual(result, "conditionValue"); - assert((client.pathTemplates.organizationAlertPolicyConditionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('organizationAlertPolicyCondition', async () => { + const fakePath = '/rendered/path/organizationAlertPolicyCondition'; + const expectedParameters = { + organization: 'organizationValue', + alert_policy: 'alertPolicyValue', + condition: 'conditionValue', + }; + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.organizationAlertPolicyConditionPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.organizationAlertPolicyConditionPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('organizationAlertPolicyConditionPath', () => { + const result = client.organizationAlertPolicyConditionPath( + 'organizationValue', + 'alertPolicyValue', + 'conditionValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationAlertPolicyConditionPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationAlertPolicyConditionName', () => { + const result = + client.matchOrganizationFromOrganizationAlertPolicyConditionName( + fakePath, + ); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationAlertPolicyConditionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchAlertPolicyFromOrganizationAlertPolicyConditionName', () => { + const result = + client.matchAlertPolicyFromOrganizationAlertPolicyConditionName( + fakePath, + ); + assert.strictEqual(result, 'alertPolicyValue'); + assert( + ( + client.pathTemplates.organizationAlertPolicyConditionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchConditionFromOrganizationAlertPolicyConditionName', () => { + const result = + client.matchConditionFromOrganizationAlertPolicyConditionName( + fakePath, + ); + assert.strictEqual(result, 'conditionValue'); + assert( + ( + client.pathTemplates.organizationAlertPolicyConditionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('organizationChannelDescriptor', async () => { - const fakePath = "/rendered/path/organizationChannelDescriptor"; - const expectedParameters = { - organization: "organizationValue", - channel_descriptor: "channelDescriptorValue", - }; - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.organizationChannelDescriptorPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationChannelDescriptorPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationChannelDescriptorPath', () => { - const result = client.organizationChannelDescriptorPath("organizationValue", "channelDescriptorValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationChannelDescriptorPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationChannelDescriptorName', () => { - const result = client.matchOrganizationFromOrganizationChannelDescriptorName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationChannelDescriptorPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchChannelDescriptorFromOrganizationChannelDescriptorName', () => { - const result = client.matchChannelDescriptorFromOrganizationChannelDescriptorName(fakePath); - assert.strictEqual(result, "channelDescriptorValue"); - assert((client.pathTemplates.organizationChannelDescriptorPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('organizationChannelDescriptor', async () => { + const fakePath = '/rendered/path/organizationChannelDescriptor'; + const expectedParameters = { + organization: 'organizationValue', + channel_descriptor: 'channelDescriptorValue', + }; + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.organizationChannelDescriptorPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.organizationChannelDescriptorPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('organizationChannelDescriptorPath', () => { + const result = client.organizationChannelDescriptorPath( + 'organizationValue', + 'channelDescriptorValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationChannelDescriptorPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationChannelDescriptorName', () => { + const result = + client.matchOrganizationFromOrganizationChannelDescriptorName( + fakePath, + ); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationChannelDescriptorPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchChannelDescriptorFromOrganizationChannelDescriptorName', () => { + const result = + client.matchChannelDescriptorFromOrganizationChannelDescriptorName( + fakePath, + ); + assert.strictEqual(result, 'channelDescriptorValue'); + assert( + ( + client.pathTemplates.organizationChannelDescriptorPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('organizationGroup', async () => { - const fakePath = "/rendered/path/organizationGroup"; - const expectedParameters = { - organization: "organizationValue", - group: "groupValue", - }; - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.organizationGroupPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationGroupPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationGroupPath', () => { - const result = client.organizationGroupPath("organizationValue", "groupValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationGroupPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationGroupName', () => { - const result = client.matchOrganizationFromOrganizationGroupName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationGroupPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchGroupFromOrganizationGroupName', () => { - const result = client.matchGroupFromOrganizationGroupName(fakePath); - assert.strictEqual(result, "groupValue"); - assert((client.pathTemplates.organizationGroupPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('organizationGroup', async () => { + const fakePath = '/rendered/path/organizationGroup'; + const expectedParameters = { + organization: 'organizationValue', + group: 'groupValue', + }; + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.organizationGroupPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.organizationGroupPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('organizationGroupPath', () => { + const result = client.organizationGroupPath( + 'organizationValue', + 'groupValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationGroupPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationGroupName', () => { + const result = + client.matchOrganizationFromOrganizationGroupName(fakePath); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationGroupPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchGroupFromOrganizationGroupName', () => { + const result = client.matchGroupFromOrganizationGroupName(fakePath); + assert.strictEqual(result, 'groupValue'); + assert( + ( + client.pathTemplates.organizationGroupPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('organizationMetricDescriptor', async () => { - const fakePath = "/rendered/path/organizationMetricDescriptor"; - const expectedParameters = { - organization: "organizationValue", - metric_descriptor: "metricDescriptorValue", - }; - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.organizationMetricDescriptorPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationMetricDescriptorPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationMetricDescriptorPath', () => { - const result = client.organizationMetricDescriptorPath("organizationValue", "metricDescriptorValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationMetricDescriptorPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationMetricDescriptorName', () => { - const result = client.matchOrganizationFromOrganizationMetricDescriptorName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationMetricDescriptorPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchMetricDescriptorFromOrganizationMetricDescriptorName', () => { - const result = client.matchMetricDescriptorFromOrganizationMetricDescriptorName(fakePath); - assert.strictEqual(result, "metricDescriptorValue"); - assert((client.pathTemplates.organizationMetricDescriptorPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('organizationMetricDescriptor', async () => { + const fakePath = '/rendered/path/organizationMetricDescriptor'; + const expectedParameters = { + organization: 'organizationValue', + metric_descriptor: 'metricDescriptorValue', + }; + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.organizationMetricDescriptorPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.organizationMetricDescriptorPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('organizationMetricDescriptorPath', () => { + const result = client.organizationMetricDescriptorPath( + 'organizationValue', + 'metricDescriptorValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationMetricDescriptorPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationMetricDescriptorName', () => { + const result = + client.matchOrganizationFromOrganizationMetricDescriptorName( + fakePath, + ); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationMetricDescriptorPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchMetricDescriptorFromOrganizationMetricDescriptorName', () => { + const result = + client.matchMetricDescriptorFromOrganizationMetricDescriptorName( + fakePath, + ); + assert.strictEqual(result, 'metricDescriptorValue'); + assert( + ( + client.pathTemplates.organizationMetricDescriptorPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('organizationMonitoredResourceDescriptor', async () => { - const fakePath = "/rendered/path/organizationMonitoredResourceDescriptor"; - const expectedParameters = { - organization: "organizationValue", - monitored_resource_descriptor: "monitoredResourceDescriptorValue", - }; - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.organizationMonitoredResourceDescriptorPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationMonitoredResourceDescriptorPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationMonitoredResourceDescriptorPath', () => { - const result = client.organizationMonitoredResourceDescriptorPath("organizationValue", "monitoredResourceDescriptorValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationMonitoredResourceDescriptorPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationMonitoredResourceDescriptorName', () => { - const result = client.matchOrganizationFromOrganizationMonitoredResourceDescriptorName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationMonitoredResourceDescriptorPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchMonitoredResourceDescriptorFromOrganizationMonitoredResourceDescriptorName', () => { - const result = client.matchMonitoredResourceDescriptorFromOrganizationMonitoredResourceDescriptorName(fakePath); - assert.strictEqual(result, "monitoredResourceDescriptorValue"); - assert((client.pathTemplates.organizationMonitoredResourceDescriptorPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('organizationMonitoredResourceDescriptor', async () => { + const fakePath = '/rendered/path/organizationMonitoredResourceDescriptor'; + const expectedParameters = { + organization: 'organizationValue', + monitored_resource_descriptor: 'monitoredResourceDescriptorValue', + }; + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.organizationMonitoredResourceDescriptorPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.organizationMonitoredResourceDescriptorPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('organizationMonitoredResourceDescriptorPath', () => { + const result = client.organizationMonitoredResourceDescriptorPath( + 'organizationValue', + 'monitoredResourceDescriptorValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates + .organizationMonitoredResourceDescriptorPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationMonitoredResourceDescriptorName', () => { + const result = + client.matchOrganizationFromOrganizationMonitoredResourceDescriptorName( + fakePath, + ); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates + .organizationMonitoredResourceDescriptorPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchMonitoredResourceDescriptorFromOrganizationMonitoredResourceDescriptorName', () => { + const result = + client.matchMonitoredResourceDescriptorFromOrganizationMonitoredResourceDescriptorName( + fakePath, + ); + assert.strictEqual(result, 'monitoredResourceDescriptorValue'); + assert( + ( + client.pathTemplates + .organizationMonitoredResourceDescriptorPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('organizationNotificationChannel', async () => { - const fakePath = "/rendered/path/organizationNotificationChannel"; - const expectedParameters = { - organization: "organizationValue", - notification_channel: "notificationChannelValue", - }; - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.organizationNotificationChannelPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationNotificationChannelPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationNotificationChannelPath', () => { - const result = client.organizationNotificationChannelPath("organizationValue", "notificationChannelValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationNotificationChannelPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationNotificationChannelName', () => { - const result = client.matchOrganizationFromOrganizationNotificationChannelName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationNotificationChannelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchNotificationChannelFromOrganizationNotificationChannelName', () => { - const result = client.matchNotificationChannelFromOrganizationNotificationChannelName(fakePath); - assert.strictEqual(result, "notificationChannelValue"); - assert((client.pathTemplates.organizationNotificationChannelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('organizationNotificationChannel', async () => { + const fakePath = '/rendered/path/organizationNotificationChannel'; + const expectedParameters = { + organization: 'organizationValue', + notification_channel: 'notificationChannelValue', + }; + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.organizationNotificationChannelPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.organizationNotificationChannelPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('organizationNotificationChannelPath', () => { + const result = client.organizationNotificationChannelPath( + 'organizationValue', + 'notificationChannelValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationNotificationChannelPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationNotificationChannelName', () => { + const result = + client.matchOrganizationFromOrganizationNotificationChannelName( + fakePath, + ); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationNotificationChannelPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchNotificationChannelFromOrganizationNotificationChannelName', () => { + const result = + client.matchNotificationChannelFromOrganizationNotificationChannelName( + fakePath, + ); + assert.strictEqual(result, 'notificationChannelValue'); + assert( + ( + client.pathTemplates.organizationNotificationChannelPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('organizationService', async () => { - const fakePath = "/rendered/path/organizationService"; - const expectedParameters = { - organization: "organizationValue", - service: "serviceValue", - }; - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.organizationServicePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationServicePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationServicePath', () => { - const result = client.organizationServicePath("organizationValue", "serviceValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationServicePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationServiceName', () => { - const result = client.matchOrganizationFromOrganizationServiceName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationServicePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServiceFromOrganizationServiceName', () => { - const result = client.matchServiceFromOrganizationServiceName(fakePath); - assert.strictEqual(result, "serviceValue"); - assert((client.pathTemplates.organizationServicePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('organizationService', async () => { + const fakePath = '/rendered/path/organizationService'; + const expectedParameters = { + organization: 'organizationValue', + service: 'serviceValue', + }; + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.organizationServicePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.organizationServicePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('organizationServicePath', () => { + const result = client.organizationServicePath( + 'organizationValue', + 'serviceValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationServicePathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationServiceName', () => { + const result = + client.matchOrganizationFromOrganizationServiceName(fakePath); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationServicePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServiceFromOrganizationServiceName', () => { + const result = client.matchServiceFromOrganizationServiceName(fakePath); + assert.strictEqual(result, 'serviceValue'); + assert( + ( + client.pathTemplates.organizationServicePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('organizationServiceServiceLevelObjective', async () => { - const fakePath = "/rendered/path/organizationServiceServiceLevelObjective"; - const expectedParameters = { - organization: "organizationValue", - service: "serviceValue", - service_level_objective: "serviceLevelObjectiveValue", - }; - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationServiceServiceLevelObjectivePath', () => { - const result = client.organizationServiceServiceLevelObjectivePath("organizationValue", "serviceValue", "serviceLevelObjectiveValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationServiceServiceLevelObjectiveName', () => { - const result = client.matchOrganizationFromOrganizationServiceServiceLevelObjectiveName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServiceFromOrganizationServiceServiceLevelObjectiveName', () => { - const result = client.matchServiceFromOrganizationServiceServiceLevelObjectiveName(fakePath); - assert.strictEqual(result, "serviceValue"); - assert((client.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServiceLevelObjectiveFromOrganizationServiceServiceLevelObjectiveName', () => { - const result = client.matchServiceLevelObjectiveFromOrganizationServiceServiceLevelObjectiveName(fakePath); - assert.strictEqual(result, "serviceLevelObjectiveValue"); - assert((client.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('organizationServiceServiceLevelObjective', async () => { + const fakePath = + '/rendered/path/organizationServiceServiceLevelObjective'; + const expectedParameters = { + organization: 'organizationValue', + service: 'serviceValue', + service_level_objective: 'serviceLevelObjectiveValue', + }; + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('organizationServiceServiceLevelObjectivePath', () => { + const result = client.organizationServiceServiceLevelObjectivePath( + 'organizationValue', + 'serviceValue', + 'serviceLevelObjectiveValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates + .organizationServiceServiceLevelObjectivePathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationServiceServiceLevelObjectiveName', () => { + const result = + client.matchOrganizationFromOrganizationServiceServiceLevelObjectiveName( + fakePath, + ); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates + .organizationServiceServiceLevelObjectivePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServiceFromOrganizationServiceServiceLevelObjectiveName', () => { + const result = + client.matchServiceFromOrganizationServiceServiceLevelObjectiveName( + fakePath, + ); + assert.strictEqual(result, 'serviceValue'); + assert( + ( + client.pathTemplates + .organizationServiceServiceLevelObjectivePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServiceLevelObjectiveFromOrganizationServiceServiceLevelObjectiveName', () => { + const result = + client.matchServiceLevelObjectiveFromOrganizationServiceServiceLevelObjectiveName( + fakePath, + ); + assert.strictEqual(result, 'serviceLevelObjectiveValue'); + assert( + ( + client.pathTemplates + .organizationServiceServiceLevelObjectivePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('organizationUptimeCheckConfig', async () => { - const fakePath = "/rendered/path/organizationUptimeCheckConfig"; - const expectedParameters = { - organization: "organizationValue", - uptime_check_config: "uptimeCheckConfigValue", - }; - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.organizationUptimeCheckConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationUptimeCheckConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationUptimeCheckConfigPath', () => { - const result = client.organizationUptimeCheckConfigPath("organizationValue", "uptimeCheckConfigValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationUptimeCheckConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationUptimeCheckConfigName', () => { - const result = client.matchOrganizationFromOrganizationUptimeCheckConfigName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationUptimeCheckConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchUptimeCheckConfigFromOrganizationUptimeCheckConfigName', () => { - const result = client.matchUptimeCheckConfigFromOrganizationUptimeCheckConfigName(fakePath); - assert.strictEqual(result, "uptimeCheckConfigValue"); - assert((client.pathTemplates.organizationUptimeCheckConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('organizationUptimeCheckConfig', async () => { + const fakePath = '/rendered/path/organizationUptimeCheckConfig'; + const expectedParameters = { + organization: 'organizationValue', + uptime_check_config: 'uptimeCheckConfigValue', + }; + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.organizationUptimeCheckConfigPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.organizationUptimeCheckConfigPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('organizationUptimeCheckConfigPath', () => { + const result = client.organizationUptimeCheckConfigPath( + 'organizationValue', + 'uptimeCheckConfigValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationUptimeCheckConfigPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationUptimeCheckConfigName', () => { + const result = + client.matchOrganizationFromOrganizationUptimeCheckConfigName( + fakePath, + ); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationUptimeCheckConfigPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchUptimeCheckConfigFromOrganizationUptimeCheckConfigName', () => { + const result = + client.matchUptimeCheckConfigFromOrganizationUptimeCheckConfigName( + fakePath, + ); + assert.strictEqual(result, 'uptimeCheckConfigValue'); + assert( + ( + client.pathTemplates.organizationUptimeCheckConfigPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectAlertPolicy', async () => { - const fakePath = "/rendered/path/projectAlertPolicy"; - const expectedParameters = { - project: "projectValue", - alert_policy: "alertPolicyValue", - }; - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.projectAlertPolicyPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectAlertPolicyPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectAlertPolicyPath', () => { - const result = client.projectAlertPolicyPath("projectValue", "alertPolicyValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectAlertPolicyPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectAlertPolicyName', () => { - const result = client.matchProjectFromProjectAlertPolicyName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectAlertPolicyPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchAlertPolicyFromProjectAlertPolicyName', () => { - const result = client.matchAlertPolicyFromProjectAlertPolicyName(fakePath); - assert.strictEqual(result, "alertPolicyValue"); - assert((client.pathTemplates.projectAlertPolicyPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectAlertPolicy', async () => { + const fakePath = '/rendered/path/projectAlertPolicy'; + const expectedParameters = { + project: 'projectValue', + alert_policy: 'alertPolicyValue', + }; + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.projectAlertPolicyPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectAlertPolicyPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectAlertPolicyPath', () => { + const result = client.projectAlertPolicyPath( + 'projectValue', + 'alertPolicyValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.projectAlertPolicyPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectAlertPolicyName', () => { + const result = client.matchProjectFromProjectAlertPolicyName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.projectAlertPolicyPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchAlertPolicyFromProjectAlertPolicyName', () => { + const result = + client.matchAlertPolicyFromProjectAlertPolicyName(fakePath); + assert.strictEqual(result, 'alertPolicyValue'); + assert( + ( + client.pathTemplates.projectAlertPolicyPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectAlertPolicyCondition', async () => { - const fakePath = "/rendered/path/projectAlertPolicyCondition"; - const expectedParameters = { - project: "projectValue", - alert_policy: "alertPolicyValue", - condition: "conditionValue", - }; - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.projectAlertPolicyConditionPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectAlertPolicyConditionPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectAlertPolicyConditionPath', () => { - const result = client.projectAlertPolicyConditionPath("projectValue", "alertPolicyValue", "conditionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectAlertPolicyConditionPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectAlertPolicyConditionName', () => { - const result = client.matchProjectFromProjectAlertPolicyConditionName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectAlertPolicyConditionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchAlertPolicyFromProjectAlertPolicyConditionName', () => { - const result = client.matchAlertPolicyFromProjectAlertPolicyConditionName(fakePath); - assert.strictEqual(result, "alertPolicyValue"); - assert((client.pathTemplates.projectAlertPolicyConditionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchConditionFromProjectAlertPolicyConditionName', () => { - const result = client.matchConditionFromProjectAlertPolicyConditionName(fakePath); - assert.strictEqual(result, "conditionValue"); - assert((client.pathTemplates.projectAlertPolicyConditionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectAlertPolicyCondition', async () => { + const fakePath = '/rendered/path/projectAlertPolicyCondition'; + const expectedParameters = { + project: 'projectValue', + alert_policy: 'alertPolicyValue', + condition: 'conditionValue', + }; + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.projectAlertPolicyConditionPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.projectAlertPolicyConditionPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectAlertPolicyConditionPath', () => { + const result = client.projectAlertPolicyConditionPath( + 'projectValue', + 'alertPolicyValue', + 'conditionValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.projectAlertPolicyConditionPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectAlertPolicyConditionName', () => { + const result = + client.matchProjectFromProjectAlertPolicyConditionName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.projectAlertPolicyConditionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchAlertPolicyFromProjectAlertPolicyConditionName', () => { + const result = + client.matchAlertPolicyFromProjectAlertPolicyConditionName(fakePath); + assert.strictEqual(result, 'alertPolicyValue'); + assert( + ( + client.pathTemplates.projectAlertPolicyConditionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchConditionFromProjectAlertPolicyConditionName', () => { + const result = + client.matchConditionFromProjectAlertPolicyConditionName(fakePath); + assert.strictEqual(result, 'conditionValue'); + assert( + ( + client.pathTemplates.projectAlertPolicyConditionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectChannelDescriptor', async () => { - const fakePath = "/rendered/path/projectChannelDescriptor"; - const expectedParameters = { - project: "projectValue", - channel_descriptor: "channelDescriptorValue", - }; - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.projectChannelDescriptorPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectChannelDescriptorPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectChannelDescriptorPath', () => { - const result = client.projectChannelDescriptorPath("projectValue", "channelDescriptorValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectChannelDescriptorPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectChannelDescriptorName', () => { - const result = client.matchProjectFromProjectChannelDescriptorName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectChannelDescriptorPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchChannelDescriptorFromProjectChannelDescriptorName', () => { - const result = client.matchChannelDescriptorFromProjectChannelDescriptorName(fakePath); - assert.strictEqual(result, "channelDescriptorValue"); - assert((client.pathTemplates.projectChannelDescriptorPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectChannelDescriptor', async () => { + const fakePath = '/rendered/path/projectChannelDescriptor'; + const expectedParameters = { + project: 'projectValue', + channel_descriptor: 'channelDescriptorValue', + }; + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.projectChannelDescriptorPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectChannelDescriptorPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectChannelDescriptorPath', () => { + const result = client.projectChannelDescriptorPath( + 'projectValue', + 'channelDescriptorValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.projectChannelDescriptorPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectChannelDescriptorName', () => { + const result = + client.matchProjectFromProjectChannelDescriptorName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.projectChannelDescriptorPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchChannelDescriptorFromProjectChannelDescriptorName', () => { + const result = + client.matchChannelDescriptorFromProjectChannelDescriptorName( + fakePath, + ); + assert.strictEqual(result, 'channelDescriptorValue'); + assert( + ( + client.pathTemplates.projectChannelDescriptorPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectGroup', async () => { - const fakePath = "/rendered/path/projectGroup"; - const expectedParameters = { - project: "projectValue", - group: "groupValue", - }; - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.projectGroupPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectGroupPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectGroupPath', () => { - const result = client.projectGroupPath("projectValue", "groupValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectGroupPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectGroupName', () => { - const result = client.matchProjectFromProjectGroupName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectGroupPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchGroupFromProjectGroupName', () => { - const result = client.matchGroupFromProjectGroupName(fakePath); - assert.strictEqual(result, "groupValue"); - assert((client.pathTemplates.projectGroupPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectGroup', async () => { + const fakePath = '/rendered/path/projectGroup'; + const expectedParameters = { + project: 'projectValue', + group: 'groupValue', + }; + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.projectGroupPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectGroupPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectGroupPath', () => { + const result = client.projectGroupPath('projectValue', 'groupValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.projectGroupPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectGroupName', () => { + const result = client.matchProjectFromProjectGroupName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.projectGroupPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchGroupFromProjectGroupName', () => { + const result = client.matchGroupFromProjectGroupName(fakePath); + assert.strictEqual(result, 'groupValue'); + assert( + (client.pathTemplates.projectGroupPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectMetricDescriptor', async () => { - const fakePath = "/rendered/path/projectMetricDescriptor"; - const expectedParameters = { - project: "projectValue", - metric_descriptor: "metricDescriptorValue", - }; - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.projectMetricDescriptorPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectMetricDescriptorPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectMetricDescriptorPath', () => { - const result = client.projectMetricDescriptorPath("projectValue", "metricDescriptorValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectMetricDescriptorPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectMetricDescriptorName', () => { - const result = client.matchProjectFromProjectMetricDescriptorName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectMetricDescriptorPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchMetricDescriptorFromProjectMetricDescriptorName', () => { - const result = client.matchMetricDescriptorFromProjectMetricDescriptorName(fakePath); - assert.strictEqual(result, "metricDescriptorValue"); - assert((client.pathTemplates.projectMetricDescriptorPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectMetricDescriptor', async () => { + const fakePath = '/rendered/path/projectMetricDescriptor'; + const expectedParameters = { + project: 'projectValue', + metric_descriptor: 'metricDescriptorValue', + }; + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.projectMetricDescriptorPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectMetricDescriptorPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectMetricDescriptorPath', () => { + const result = client.projectMetricDescriptorPath( + 'projectValue', + 'metricDescriptorValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.projectMetricDescriptorPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectMetricDescriptorName', () => { + const result = + client.matchProjectFromProjectMetricDescriptorName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.projectMetricDescriptorPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchMetricDescriptorFromProjectMetricDescriptorName', () => { + const result = + client.matchMetricDescriptorFromProjectMetricDescriptorName(fakePath); + assert.strictEqual(result, 'metricDescriptorValue'); + assert( + ( + client.pathTemplates.projectMetricDescriptorPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectMonitoredResourceDescriptor', async () => { - const fakePath = "/rendered/path/projectMonitoredResourceDescriptor"; - const expectedParameters = { - project: "projectValue", - monitored_resource_descriptor: "monitoredResourceDescriptorValue", - }; - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.projectMonitoredResourceDescriptorPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectMonitoredResourceDescriptorPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectMonitoredResourceDescriptorPath', () => { - const result = client.projectMonitoredResourceDescriptorPath("projectValue", "monitoredResourceDescriptorValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectMonitoredResourceDescriptorPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectMonitoredResourceDescriptorName', () => { - const result = client.matchProjectFromProjectMonitoredResourceDescriptorName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectMonitoredResourceDescriptorPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchMonitoredResourceDescriptorFromProjectMonitoredResourceDescriptorName', () => { - const result = client.matchMonitoredResourceDescriptorFromProjectMonitoredResourceDescriptorName(fakePath); - assert.strictEqual(result, "monitoredResourceDescriptorValue"); - assert((client.pathTemplates.projectMonitoredResourceDescriptorPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectMonitoredResourceDescriptor', async () => { + const fakePath = '/rendered/path/projectMonitoredResourceDescriptor'; + const expectedParameters = { + project: 'projectValue', + monitored_resource_descriptor: 'monitoredResourceDescriptorValue', + }; + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.projectMonitoredResourceDescriptorPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.projectMonitoredResourceDescriptorPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('projectMonitoredResourceDescriptorPath', () => { + const result = client.projectMonitoredResourceDescriptorPath( + 'projectValue', + 'monitoredResourceDescriptorValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.projectMonitoredResourceDescriptorPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectMonitoredResourceDescriptorName', () => { + const result = + client.matchProjectFromProjectMonitoredResourceDescriptorName( + fakePath, + ); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.projectMonitoredResourceDescriptorPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchMonitoredResourceDescriptorFromProjectMonitoredResourceDescriptorName', () => { + const result = + client.matchMonitoredResourceDescriptorFromProjectMonitoredResourceDescriptorName( + fakePath, + ); + assert.strictEqual(result, 'monitoredResourceDescriptorValue'); + assert( + ( + client.pathTemplates.projectMonitoredResourceDescriptorPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectNotificationChannel', async () => { - const fakePath = "/rendered/path/projectNotificationChannel"; - const expectedParameters = { - project: "projectValue", - notification_channel: "notificationChannelValue", - }; - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.projectNotificationChannelPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectNotificationChannelPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectNotificationChannelPath', () => { - const result = client.projectNotificationChannelPath("projectValue", "notificationChannelValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectNotificationChannelPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectNotificationChannelName', () => { - const result = client.matchProjectFromProjectNotificationChannelName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectNotificationChannelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchNotificationChannelFromProjectNotificationChannelName', () => { - const result = client.matchNotificationChannelFromProjectNotificationChannelName(fakePath); - assert.strictEqual(result, "notificationChannelValue"); - assert((client.pathTemplates.projectNotificationChannelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectNotificationChannel', async () => { + const fakePath = '/rendered/path/projectNotificationChannel'; + const expectedParameters = { + project: 'projectValue', + notification_channel: 'notificationChannelValue', + }; + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.projectNotificationChannelPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectNotificationChannelPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectNotificationChannelPath', () => { + const result = client.projectNotificationChannelPath( + 'projectValue', + 'notificationChannelValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.projectNotificationChannelPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectNotificationChannelName', () => { + const result = + client.matchProjectFromProjectNotificationChannelName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.projectNotificationChannelPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchNotificationChannelFromProjectNotificationChannelName', () => { + const result = + client.matchNotificationChannelFromProjectNotificationChannelName( + fakePath, + ); + assert.strictEqual(result, 'notificationChannelValue'); + assert( + ( + client.pathTemplates.projectNotificationChannelPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectService', async () => { - const fakePath = "/rendered/path/projectService"; - const expectedParameters = { - project: "projectValue", - service: "serviceValue", - }; - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.projectServicePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectServicePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectServicePath', () => { - const result = client.projectServicePath("projectValue", "serviceValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectServicePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectServiceName', () => { - const result = client.matchProjectFromProjectServiceName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectServicePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServiceFromProjectServiceName', () => { - const result = client.matchServiceFromProjectServiceName(fakePath); - assert.strictEqual(result, "serviceValue"); - assert((client.pathTemplates.projectServicePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectService', async () => { + const fakePath = '/rendered/path/projectService'; + const expectedParameters = { + project: 'projectValue', + service: 'serviceValue', + }; + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.projectServicePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectServicePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectServicePath', () => { + const result = client.projectServicePath( + 'projectValue', + 'serviceValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.projectServicePathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectServiceName', () => { + const result = client.matchProjectFromProjectServiceName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.projectServicePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServiceFromProjectServiceName', () => { + const result = client.matchServiceFromProjectServiceName(fakePath); + assert.strictEqual(result, 'serviceValue'); + assert( + (client.pathTemplates.projectServicePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectServiceServiceLevelObjective', async () => { - const fakePath = "/rendered/path/projectServiceServiceLevelObjective"; - const expectedParameters = { - project: "projectValue", - service: "serviceValue", - service_level_objective: "serviceLevelObjectiveValue", - }; - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectServiceServiceLevelObjectivePath', () => { - const result = client.projectServiceServiceLevelObjectivePath("projectValue", "serviceValue", "serviceLevelObjectiveValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectServiceServiceLevelObjectiveName', () => { - const result = client.matchProjectFromProjectServiceServiceLevelObjectiveName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServiceFromProjectServiceServiceLevelObjectiveName', () => { - const result = client.matchServiceFromProjectServiceServiceLevelObjectiveName(fakePath); - assert.strictEqual(result, "serviceValue"); - assert((client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServiceLevelObjectiveFromProjectServiceServiceLevelObjectiveName', () => { - const result = client.matchServiceLevelObjectiveFromProjectServiceServiceLevelObjectiveName(fakePath); - assert.strictEqual(result, "serviceLevelObjectiveValue"); - assert((client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectServiceServiceLevelObjective', async () => { + const fakePath = '/rendered/path/projectServiceServiceLevelObjective'; + const expectedParameters = { + project: 'projectValue', + service: 'serviceValue', + service_level_objective: 'serviceLevelObjectiveValue', + }; + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('projectServiceServiceLevelObjectivePath', () => { + const result = client.projectServiceServiceLevelObjectivePath( + 'projectValue', + 'serviceValue', + 'serviceLevelObjectiveValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectServiceServiceLevelObjectiveName', () => { + const result = + client.matchProjectFromProjectServiceServiceLevelObjectiveName( + fakePath, + ); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServiceFromProjectServiceServiceLevelObjectiveName', () => { + const result = + client.matchServiceFromProjectServiceServiceLevelObjectiveName( + fakePath, + ); + assert.strictEqual(result, 'serviceValue'); + assert( + ( + client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServiceLevelObjectiveFromProjectServiceServiceLevelObjectiveName', () => { + const result = + client.matchServiceLevelObjectiveFromProjectServiceServiceLevelObjectiveName( + fakePath, + ); + assert.strictEqual(result, 'serviceLevelObjectiveValue'); + assert( + ( + client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectUptimeCheckConfig', async () => { - const fakePath = "/rendered/path/projectUptimeCheckConfig"; - const expectedParameters = { - project: "projectValue", - uptime_check_config: "uptimeCheckConfigValue", - }; - const client = new metricserviceModule.v3.MetricServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.projectUptimeCheckConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectUptimeCheckConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectUptimeCheckConfigPath', () => { - const result = client.projectUptimeCheckConfigPath("projectValue", "uptimeCheckConfigValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectUptimeCheckConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectUptimeCheckConfigName', () => { - const result = client.matchProjectFromProjectUptimeCheckConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectUptimeCheckConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchUptimeCheckConfigFromProjectUptimeCheckConfigName', () => { - const result = client.matchUptimeCheckConfigFromProjectUptimeCheckConfigName(fakePath); - assert.strictEqual(result, "uptimeCheckConfigValue"); - assert((client.pathTemplates.projectUptimeCheckConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectUptimeCheckConfig', async () => { + const fakePath = '/rendered/path/projectUptimeCheckConfig'; + const expectedParameters = { + project: 'projectValue', + uptime_check_config: 'uptimeCheckConfigValue', + }; + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.projectUptimeCheckConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectUptimeCheckConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectUptimeCheckConfigPath', () => { + const result = client.projectUptimeCheckConfigPath( + 'projectValue', + 'uptimeCheckConfigValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.projectUptimeCheckConfigPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectUptimeCheckConfigName', () => { + const result = + client.matchProjectFromProjectUptimeCheckConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.projectUptimeCheckConfigPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchUptimeCheckConfigFromProjectUptimeCheckConfigName', () => { + const result = + client.matchUptimeCheckConfigFromProjectUptimeCheckConfigName( + fakePath, + ); + assert.strictEqual(result, 'uptimeCheckConfigValue'); + assert( + ( + client.pathTemplates.projectUptimeCheckConfigPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/core/generator/gapic-generator-typescript/baselines/monitoring/test/gapic_notification_channel_service_v3.ts.baseline b/core/generator/gapic-generator-typescript/baselines/monitoring/test/gapic_notification_channel_service_v3.ts.baseline index 774957e9ee8d..ecf013dc4d79 100644 --- a/core/generator/gapic-generator-typescript/baselines/monitoring/test/gapic_notification_channel_service_v3.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/monitoring/test/gapic_notification_channel_service_v3.ts.baseline @@ -19,2564 +19,3966 @@ import * as protos from '../protos/protos'; import * as assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as notificationchannelserviceModule from '../src'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; -import {protobuf} from 'google-gax'; +import { protobuf } from 'google-gax'; // Dynamically loaded proto JSON is needed to get the type information // to fill in default values for request objects -const root = protobuf.Root.fromJSON(require('../protos/protos.json')).resolveAll(); +const root = protobuf.Root.fromJSON( + require('../protos/protos.json'), +).resolveAll(); // eslint-disable-next-line @typescript-eslint/no-unused-vars function getTypeDefaultValue(typeName: string, fields: string[]) { - let type = root.lookupType(typeName) as protobuf.Type; - for (const field of fields.slice(0, -1)) { - type = type.fields[field]?.resolvedType as protobuf.Type; - } - return type.fields[fields[fields.length - 1]]?.defaultValue; + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type.fields[field]?.resolvedType as protobuf.Type; + } + return type.fields[fields[fields.length - 1]]?.defaultValue; } function generateSampleMessage(instance: T) { - const filledObject = (instance.constructor as typeof protobuf.Message) - .toObject(instance as protobuf.Message, {defaults: true}); - return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, { defaults: true }); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; } function stubSimpleCall(response?: ResponseType, error?: Error) { - return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); } -function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { - return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +function stubSimpleCallWithCallback( + response?: ResponseType, + error?: Error, +) { + return error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); } -function stubPageStreamingCall(responses?: ResponseType[], error?: Error) { - const pagingStub = sinon.stub(); - if (responses) { - for (let i = 0; i < responses.length; ++i) { - pagingStub.onCall(i).callsArgWith(2, null, responses[i]); - } +function stubPageStreamingCall( + responses?: ResponseType[], + error?: Error, +) { + const pagingStub = sinon.stub(); + if (responses) { + for (let i = 0; i < responses.length; ++i) { + pagingStub.onCall(i).callsArgWith(2, null, responses[i]); } - const transformStub = error ? sinon.stub().callsArgWith(2, error) : pagingStub; - const mockStream = new PassThrough({ - objectMode: true, - transform: transformStub, - }); - // trigger as many responses as needed - if (responses) { - for (let i = 0; i < responses.length; ++i) { - setImmediate(() => { mockStream.write({}); }); - } - setImmediate(() => { mockStream.end(); }); - } else { - setImmediate(() => { mockStream.write({}); }); - setImmediate(() => { mockStream.end(); }); + } + const transformStub = error + ? sinon.stub().callsArgWith(2, error) + : pagingStub; + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + // trigger as many responses as needed + if (responses) { + for (let i = 0; i < responses.length; ++i) { + setImmediate(() => { + mockStream.write({}); + }); } - return sinon.stub().returns(mockStream); + setImmediate(() => { + mockStream.end(); + }); + } else { + setImmediate(() => { + mockStream.write({}); + }); + setImmediate(() => { + mockStream.end(); + }); + } + return sinon.stub().returns(mockStream); } -function stubAsyncIterationCall(responses?: ResponseType[], error?: Error) { - let counter = 0; - const asyncIterable = { - [Symbol.asyncIterator]() { - return { - async next() { - if (error) { - return Promise.reject(error); - } - if (counter >= responses!.length) { - return Promise.resolve({done: true, value: undefined}); - } - return Promise.resolve({done: false, value: responses![counter++]}); - } - }; - } - }; - return sinon.stub().returns(asyncIterable); +function stubAsyncIterationCall( + responses?: ResponseType[], + error?: Error, +) { + let counter = 0; + const asyncIterable = { + [Symbol.asyncIterator]() { + return { + async next() { + if (error) { + return Promise.reject(error); + } + if (counter >= responses!.length) { + return Promise.resolve({ done: true, value: undefined }); + } + return Promise.resolve({ done: false, value: responses![counter++] }); + }, + }; + }, + }; + return sinon.stub().returns(asyncIterable); } describe('v3.NotificationChannelServiceClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'monitoring.googleapis.com'); - }); - - it('has universeDomain', () => { - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); - - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - it('throws DeprecationWarning if static servicePath is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const servicePath = notificationchannelserviceModule.v3.NotificationChannelServiceClient.servicePath; - assert.strictEqual(servicePath, 'monitoring.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = notificationchannelserviceModule.v3.NotificationChannelServiceClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'monitoring.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'monitoring.example.com'); - }); - - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'monitoring.example.com'); - }); - - if (typeof process === 'object' && 'env' in process) { - describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { - it('sets apiEndpoint from environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'monitoring.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - - it('value configured in code has priority over environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'monitoring.configured.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { new notificationchannelserviceModule.v3.NotificationChannelServiceClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); - - it('has port', () => { - const port = notificationchannelserviceModule.v3.NotificationChannelServiceClient.port; - assert(port); - assert(typeof port === 'number'); - }); - - it('should create a client with no option', () => { - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient(); - assert(client); - }); - - it('should create a client with gRPC fallback', () => { - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - fallback: true, - }); - assert(client); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'monitoring.googleapis.com'); + }); - it('has initialize method and supports deferred initialization', async () => { - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.notificationChannelServiceStub, undefined); - await client.initialize(); - assert(client.notificationChannelServiceStub); - }); + it('has universeDomain', () => { + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - it('has close method for the initialized client', done => { - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.notificationChannelServiceStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = + notificationchannelserviceModule.v3.NotificationChannelServiceClient + .servicePath; + assert.strictEqual(servicePath, 'monitoring.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + notificationchannelserviceModule.v3.NotificationChannelServiceClient + .apiEndpoint; + assert.strictEqual(apiEndpoint, 'monitoring.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { universeDomain: 'example.com' }, + ); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'monitoring.example.com'); + }); - it('has close method for the non-initialized client', done => { - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.notificationChannelServiceStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { universe_domain: 'example.com' }, + ); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'monitoring.example.com'); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); - }); + if (typeof process === 'object' && 'env' in process) { + describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { + it('sets apiEndpoint from environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'monitoring.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } + }); + + it('value configured in code has priority over environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { universeDomain: 'configured.example.com' }, + ); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'monitoring.configured.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } + }); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { universe_domain: 'example.com', universeDomain: 'example.net' }, + ); + }); + }); - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId((err?: Error|null, projectId?: string|null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } - }); - }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); - }); + it('has port', () => { + const port = + notificationchannelserviceModule.v3.NotificationChannelServiceClient + .port; + assert(port); + assert(typeof port === 'number'); }); - describe('getNotificationChannelDescriptor', () => { - it('invokes getNotificationChannelDescriptor without error', async () => { - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.GetNotificationChannelDescriptorRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.GetNotificationChannelDescriptorRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.monitoring.v3.NotificationChannelDescriptor() - ); - client.innerApiCalls.getNotificationChannelDescriptor = stubSimpleCall(expectedResponse); - const [response] = await client.getNotificationChannelDescriptor(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getNotificationChannelDescriptor as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getNotificationChannelDescriptor as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('should create a client with no option', () => { + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient(); + assert(client); + }); - it('invokes getNotificationChannelDescriptor without error using callback', async () => { - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.GetNotificationChannelDescriptorRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.GetNotificationChannelDescriptorRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.monitoring.v3.NotificationChannelDescriptor() - ); - client.innerApiCalls.getNotificationChannelDescriptor = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getNotificationChannelDescriptor( - request, - (err?: Error|null, result?: protos.google.monitoring.v3.INotificationChannelDescriptor|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getNotificationChannelDescriptor as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getNotificationChannelDescriptor as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('should create a client with gRPC fallback', () => { + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + fallback: true, + }, + ); + assert(client); + }); - it('invokes getNotificationChannelDescriptor with error', async () => { - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.GetNotificationChannelDescriptorRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.GetNotificationChannelDescriptorRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getNotificationChannelDescriptor = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getNotificationChannelDescriptor(request), expectedError); - const actualRequest = (client.innerApiCalls.getNotificationChannelDescriptor as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getNotificationChannelDescriptor as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has initialize method and supports deferred initialization', async () => { + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + assert.strictEqual(client.notificationChannelServiceStub, undefined); + await client.initialize(); + assert(client.notificationChannelServiceStub); + }); - it('invokes getNotificationChannelDescriptor with closed client', async () => { - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.GetNotificationChannelDescriptorRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.GetNotificationChannelDescriptorRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getNotificationChannelDescriptor(request), expectedError); + it('has close method for the initialized client', (done) => { + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + client.initialize().catch((err) => { + throw err; + }); + assert(client.notificationChannelServiceStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); }); - describe('getNotificationChannel', () => { - it('invokes getNotificationChannel without error', async () => { - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.GetNotificationChannelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.GetNotificationChannelRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.monitoring.v3.NotificationChannel() - ); - client.innerApiCalls.getNotificationChannel = stubSimpleCall(expectedResponse); - const [response] = await client.getNotificationChannel(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getNotificationChannel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getNotificationChannel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('has close method for the non-initialized client', (done) => { + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + assert.strictEqual(client.notificationChannelServiceStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes getNotificationChannel without error using callback', async () => { - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.GetNotificationChannelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.GetNotificationChannelRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.monitoring.v3.NotificationChannel() - ); - client.innerApiCalls.getNotificationChannel = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getNotificationChannel( - request, - (err?: Error|null, result?: protos.google.monitoring.v3.INotificationChannel|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getNotificationChannel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getNotificationChannel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + }); - it('invokes getNotificationChannel with error', async () => { - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.GetNotificationChannelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.GetNotificationChannelRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getNotificationChannel = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getNotificationChannel(request), expectedError); - const actualRequest = (client.innerApiCalls.getNotificationChannel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getNotificationChannel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } + }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + }); + + describe('getNotificationChannelDescriptor', () => { + it('invokes getNotificationChannelDescriptor without error', async () => { + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.GetNotificationChannelDescriptorRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.GetNotificationChannelDescriptorRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.monitoring.v3.NotificationChannelDescriptor(), + ); + client.innerApiCalls.getNotificationChannelDescriptor = + stubSimpleCall(expectedResponse); + const [response] = await client.getNotificationChannelDescriptor(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getNotificationChannelDescriptor as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getNotificationChannelDescriptor as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getNotificationChannel with closed client', async () => { - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.GetNotificationChannelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.GetNotificationChannelRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getNotificationChannel(request), expectedError); - }); + it('invokes getNotificationChannelDescriptor without error using callback', async () => { + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.GetNotificationChannelDescriptorRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.GetNotificationChannelDescriptorRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.monitoring.v3.NotificationChannelDescriptor(), + ); + client.innerApiCalls.getNotificationChannelDescriptor = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getNotificationChannelDescriptor( + request, + ( + err?: Error | null, + result?: protos.google.monitoring.v3.INotificationChannelDescriptor | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getNotificationChannelDescriptor as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getNotificationChannelDescriptor as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('createNotificationChannel', () => { - it('invokes createNotificationChannel without error', async () => { - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.CreateNotificationChannelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.CreateNotificationChannelRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.monitoring.v3.NotificationChannel() - ); - client.innerApiCalls.createNotificationChannel = stubSimpleCall(expectedResponse); - const [response] = await client.createNotificationChannel(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createNotificationChannel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createNotificationChannel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getNotificationChannelDescriptor with error', async () => { + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.GetNotificationChannelDescriptorRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.GetNotificationChannelDescriptorRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getNotificationChannelDescriptor = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.getNotificationChannelDescriptor(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.getNotificationChannelDescriptor as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getNotificationChannelDescriptor as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createNotificationChannel without error using callback', async () => { - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.CreateNotificationChannelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.CreateNotificationChannelRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.monitoring.v3.NotificationChannel() - ); - client.innerApiCalls.createNotificationChannel = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createNotificationChannel( - request, - (err?: Error|null, result?: protos.google.monitoring.v3.INotificationChannel|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createNotificationChannel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createNotificationChannel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getNotificationChannelDescriptor with closed client', async () => { + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.GetNotificationChannelDescriptorRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.GetNotificationChannelDescriptorRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.getNotificationChannelDescriptor(request), + expectedError, + ); + }); + }); + + describe('getNotificationChannel', () => { + it('invokes getNotificationChannel without error', async () => { + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.GetNotificationChannelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.GetNotificationChannelRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.monitoring.v3.NotificationChannel(), + ); + client.innerApiCalls.getNotificationChannel = + stubSimpleCall(expectedResponse); + const [response] = await client.getNotificationChannel(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getNotificationChannel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getNotificationChannel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createNotificationChannel with error', async () => { - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.CreateNotificationChannelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.CreateNotificationChannelRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createNotificationChannel = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createNotificationChannel(request), expectedError); - const actualRequest = (client.innerApiCalls.createNotificationChannel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createNotificationChannel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getNotificationChannel without error using callback', async () => { + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.GetNotificationChannelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.GetNotificationChannelRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.monitoring.v3.NotificationChannel(), + ); + client.innerApiCalls.getNotificationChannel = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getNotificationChannel( + request, + ( + err?: Error | null, + result?: protos.google.monitoring.v3.INotificationChannel | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getNotificationChannel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getNotificationChannel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createNotificationChannel with closed client', async () => { - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.CreateNotificationChannelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.CreateNotificationChannelRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createNotificationChannel(request), expectedError); - }); + it('invokes getNotificationChannel with error', async () => { + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.GetNotificationChannelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.GetNotificationChannelRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getNotificationChannel = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.getNotificationChannel(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.getNotificationChannel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getNotificationChannel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('updateNotificationChannel', () => { - it('invokes updateNotificationChannel without error', async () => { - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.UpdateNotificationChannelRequest() - ); - request.notificationChannel ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.UpdateNotificationChannelRequest', ['notificationChannel', 'name']); - request.notificationChannel.name = defaultValue1; - const expectedHeaderRequestParams = `notification_channel.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.monitoring.v3.NotificationChannel() - ); - client.innerApiCalls.updateNotificationChannel = stubSimpleCall(expectedResponse); - const [response] = await client.updateNotificationChannel(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateNotificationChannel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateNotificationChannel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getNotificationChannel with closed client', async () => { + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.GetNotificationChannelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.GetNotificationChannelRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.getNotificationChannel(request), + expectedError, + ); + }); + }); + + describe('createNotificationChannel', () => { + it('invokes createNotificationChannel without error', async () => { + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.CreateNotificationChannelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.CreateNotificationChannelRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.monitoring.v3.NotificationChannel(), + ); + client.innerApiCalls.createNotificationChannel = + stubSimpleCall(expectedResponse); + const [response] = await client.createNotificationChannel(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createNotificationChannel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createNotificationChannel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateNotificationChannel without error using callback', async () => { - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.UpdateNotificationChannelRequest() - ); - request.notificationChannel ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.UpdateNotificationChannelRequest', ['notificationChannel', 'name']); - request.notificationChannel.name = defaultValue1; - const expectedHeaderRequestParams = `notification_channel.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.monitoring.v3.NotificationChannel() - ); - client.innerApiCalls.updateNotificationChannel = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateNotificationChannel( - request, - (err?: Error|null, result?: protos.google.monitoring.v3.INotificationChannel|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateNotificationChannel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateNotificationChannel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createNotificationChannel without error using callback', async () => { + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.CreateNotificationChannelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.CreateNotificationChannelRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.monitoring.v3.NotificationChannel(), + ); + client.innerApiCalls.createNotificationChannel = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createNotificationChannel( + request, + ( + err?: Error | null, + result?: protos.google.monitoring.v3.INotificationChannel | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createNotificationChannel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createNotificationChannel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateNotificationChannel with error', async () => { - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.UpdateNotificationChannelRequest() - ); - request.notificationChannel ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.UpdateNotificationChannelRequest', ['notificationChannel', 'name']); - request.notificationChannel.name = defaultValue1; - const expectedHeaderRequestParams = `notification_channel.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateNotificationChannel = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateNotificationChannel(request), expectedError); - const actualRequest = (client.innerApiCalls.updateNotificationChannel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateNotificationChannel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createNotificationChannel with error', async () => { + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.CreateNotificationChannelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.CreateNotificationChannelRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createNotificationChannel = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.createNotificationChannel(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.createNotificationChannel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createNotificationChannel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateNotificationChannel with closed client', async () => { - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.UpdateNotificationChannelRequest() - ); - request.notificationChannel ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.UpdateNotificationChannelRequest', ['notificationChannel', 'name']); - request.notificationChannel.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateNotificationChannel(request), expectedError); - }); + it('invokes createNotificationChannel with closed client', async () => { + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.CreateNotificationChannelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.CreateNotificationChannelRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.createNotificationChannel(request), + expectedError, + ); + }); + }); + + describe('updateNotificationChannel', () => { + it('invokes updateNotificationChannel without error', async () => { + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.UpdateNotificationChannelRequest(), + ); + request.notificationChannel ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.UpdateNotificationChannelRequest', + ['notificationChannel', 'name'], + ); + request.notificationChannel.name = defaultValue1; + const expectedHeaderRequestParams = `notification_channel.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.monitoring.v3.NotificationChannel(), + ); + client.innerApiCalls.updateNotificationChannel = + stubSimpleCall(expectedResponse); + const [response] = await client.updateNotificationChannel(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateNotificationChannel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateNotificationChannel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('deleteNotificationChannel', () => { - it('invokes deleteNotificationChannel without error', async () => { - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.DeleteNotificationChannelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.DeleteNotificationChannelRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteNotificationChannel = stubSimpleCall(expectedResponse); - const [response] = await client.deleteNotificationChannel(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteNotificationChannel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteNotificationChannel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateNotificationChannel without error using callback', async () => { + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.UpdateNotificationChannelRequest(), + ); + request.notificationChannel ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.UpdateNotificationChannelRequest', + ['notificationChannel', 'name'], + ); + request.notificationChannel.name = defaultValue1; + const expectedHeaderRequestParams = `notification_channel.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.monitoring.v3.NotificationChannel(), + ); + client.innerApiCalls.updateNotificationChannel = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateNotificationChannel( + request, + ( + err?: Error | null, + result?: protos.google.monitoring.v3.INotificationChannel | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateNotificationChannel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateNotificationChannel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteNotificationChannel without error using callback', async () => { - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.DeleteNotificationChannelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.DeleteNotificationChannelRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteNotificationChannel = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteNotificationChannel( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteNotificationChannel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteNotificationChannel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateNotificationChannel with error', async () => { + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.UpdateNotificationChannelRequest(), + ); + request.notificationChannel ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.UpdateNotificationChannelRequest', + ['notificationChannel', 'name'], + ); + request.notificationChannel.name = defaultValue1; + const expectedHeaderRequestParams = `notification_channel.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateNotificationChannel = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.updateNotificationChannel(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.updateNotificationChannel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateNotificationChannel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteNotificationChannel with error', async () => { - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.DeleteNotificationChannelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.DeleteNotificationChannelRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteNotificationChannel = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteNotificationChannel(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteNotificationChannel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteNotificationChannel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateNotificationChannel with closed client', async () => { + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.UpdateNotificationChannelRequest(), + ); + request.notificationChannel ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.UpdateNotificationChannelRequest', + ['notificationChannel', 'name'], + ); + request.notificationChannel.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.updateNotificationChannel(request), + expectedError, + ); + }); + }); + + describe('deleteNotificationChannel', () => { + it('invokes deleteNotificationChannel without error', async () => { + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.DeleteNotificationChannelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.DeleteNotificationChannelRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteNotificationChannel = + stubSimpleCall(expectedResponse); + const [response] = await client.deleteNotificationChannel(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteNotificationChannel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteNotificationChannel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteNotificationChannel with closed client', async () => { - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.DeleteNotificationChannelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.DeleteNotificationChannelRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteNotificationChannel(request), expectedError); - }); + it('invokes deleteNotificationChannel without error using callback', async () => { + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.DeleteNotificationChannelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.DeleteNotificationChannelRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteNotificationChannel = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteNotificationChannel( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteNotificationChannel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteNotificationChannel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('sendNotificationChannelVerificationCode', () => { - it('invokes sendNotificationChannelVerificationCode without error', async () => { - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.SendNotificationChannelVerificationCodeRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.SendNotificationChannelVerificationCodeRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.sendNotificationChannelVerificationCode = stubSimpleCall(expectedResponse); - const [response] = await client.sendNotificationChannelVerificationCode(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.sendNotificationChannelVerificationCode as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.sendNotificationChannelVerificationCode as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteNotificationChannel with error', async () => { + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.DeleteNotificationChannelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.DeleteNotificationChannelRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteNotificationChannel = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.deleteNotificationChannel(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.deleteNotificationChannel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteNotificationChannel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes sendNotificationChannelVerificationCode without error using callback', async () => { - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.SendNotificationChannelVerificationCodeRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.SendNotificationChannelVerificationCodeRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.sendNotificationChannelVerificationCode = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.sendNotificationChannelVerificationCode( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.sendNotificationChannelVerificationCode as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.sendNotificationChannelVerificationCode as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteNotificationChannel with closed client', async () => { + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.DeleteNotificationChannelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.DeleteNotificationChannelRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.deleteNotificationChannel(request), + expectedError, + ); + }); + }); + + describe('sendNotificationChannelVerificationCode', () => { + it('invokes sendNotificationChannelVerificationCode without error', async () => { + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.SendNotificationChannelVerificationCodeRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.SendNotificationChannelVerificationCodeRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.sendNotificationChannelVerificationCode = + stubSimpleCall(expectedResponse); + const [response] = + await client.sendNotificationChannelVerificationCode(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls + .sendNotificationChannelVerificationCode as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls + .sendNotificationChannelVerificationCode as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes sendNotificationChannelVerificationCode with error', async () => { - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.SendNotificationChannelVerificationCodeRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.SendNotificationChannelVerificationCodeRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.sendNotificationChannelVerificationCode = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.sendNotificationChannelVerificationCode(request), expectedError); - const actualRequest = (client.innerApiCalls.sendNotificationChannelVerificationCode as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.sendNotificationChannelVerificationCode as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes sendNotificationChannelVerificationCode without error using callback', async () => { + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.SendNotificationChannelVerificationCodeRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.SendNotificationChannelVerificationCodeRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.sendNotificationChannelVerificationCode = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.sendNotificationChannelVerificationCode( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls + .sendNotificationChannelVerificationCode as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls + .sendNotificationChannelVerificationCode as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes sendNotificationChannelVerificationCode with closed client', async () => { - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.SendNotificationChannelVerificationCodeRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.SendNotificationChannelVerificationCodeRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.sendNotificationChannelVerificationCode(request), expectedError); - }); + it('invokes sendNotificationChannelVerificationCode with error', async () => { + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.SendNotificationChannelVerificationCodeRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.SendNotificationChannelVerificationCodeRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.sendNotificationChannelVerificationCode = + stubSimpleCall(undefined, expectedError); + await assert.rejects( + client.sendNotificationChannelVerificationCode(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls + .sendNotificationChannelVerificationCode as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls + .sendNotificationChannelVerificationCode as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('getNotificationChannelVerificationCode', () => { - it('invokes getNotificationChannelVerificationCode without error', async () => { - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.GetNotificationChannelVerificationCodeRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.GetNotificationChannelVerificationCodeRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.monitoring.v3.GetNotificationChannelVerificationCodeResponse() - ); - client.innerApiCalls.getNotificationChannelVerificationCode = stubSimpleCall(expectedResponse); - const [response] = await client.getNotificationChannelVerificationCode(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getNotificationChannelVerificationCode as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getNotificationChannelVerificationCode as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes sendNotificationChannelVerificationCode with closed client', async () => { + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.SendNotificationChannelVerificationCodeRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.SendNotificationChannelVerificationCodeRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.sendNotificationChannelVerificationCode(request), + expectedError, + ); + }); + }); + + describe('getNotificationChannelVerificationCode', () => { + it('invokes getNotificationChannelVerificationCode without error', async () => { + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.GetNotificationChannelVerificationCodeRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.GetNotificationChannelVerificationCodeRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.monitoring.v3.GetNotificationChannelVerificationCodeResponse(), + ); + client.innerApiCalls.getNotificationChannelVerificationCode = + stubSimpleCall(expectedResponse); + const [response] = + await client.getNotificationChannelVerificationCode(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getNotificationChannelVerificationCode as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getNotificationChannelVerificationCode as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getNotificationChannelVerificationCode without error using callback', async () => { - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.GetNotificationChannelVerificationCodeRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.GetNotificationChannelVerificationCodeRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.monitoring.v3.GetNotificationChannelVerificationCodeResponse() - ); - client.innerApiCalls.getNotificationChannelVerificationCode = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getNotificationChannelVerificationCode( - request, - (err?: Error|null, result?: protos.google.monitoring.v3.IGetNotificationChannelVerificationCodeResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getNotificationChannelVerificationCode as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getNotificationChannelVerificationCode as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getNotificationChannelVerificationCode without error using callback', async () => { + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.GetNotificationChannelVerificationCodeRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.GetNotificationChannelVerificationCodeRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.monitoring.v3.GetNotificationChannelVerificationCodeResponse(), + ); + client.innerApiCalls.getNotificationChannelVerificationCode = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getNotificationChannelVerificationCode( + request, + ( + err?: Error | null, + result?: protos.google.monitoring.v3.IGetNotificationChannelVerificationCodeResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getNotificationChannelVerificationCode as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getNotificationChannelVerificationCode as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getNotificationChannelVerificationCode with error', async () => { - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.GetNotificationChannelVerificationCodeRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.GetNotificationChannelVerificationCodeRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getNotificationChannelVerificationCode = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getNotificationChannelVerificationCode(request), expectedError); - const actualRequest = (client.innerApiCalls.getNotificationChannelVerificationCode as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getNotificationChannelVerificationCode as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getNotificationChannelVerificationCode with error', async () => { + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.GetNotificationChannelVerificationCodeRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.GetNotificationChannelVerificationCodeRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getNotificationChannelVerificationCode = + stubSimpleCall(undefined, expectedError); + await assert.rejects( + client.getNotificationChannelVerificationCode(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.getNotificationChannelVerificationCode as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getNotificationChannelVerificationCode as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getNotificationChannelVerificationCode with closed client', async () => { - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.GetNotificationChannelVerificationCodeRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.GetNotificationChannelVerificationCodeRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getNotificationChannelVerificationCode(request), expectedError); - }); + it('invokes getNotificationChannelVerificationCode with closed client', async () => { + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.GetNotificationChannelVerificationCodeRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.GetNotificationChannelVerificationCodeRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.getNotificationChannelVerificationCode(request), + expectedError, + ); + }); + }); + + describe('verifyNotificationChannel', () => { + it('invokes verifyNotificationChannel without error', async () => { + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.VerifyNotificationChannelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.VerifyNotificationChannelRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.monitoring.v3.NotificationChannel(), + ); + client.innerApiCalls.verifyNotificationChannel = + stubSimpleCall(expectedResponse); + const [response] = await client.verifyNotificationChannel(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.verifyNotificationChannel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.verifyNotificationChannel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('verifyNotificationChannel', () => { - it('invokes verifyNotificationChannel without error', async () => { - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.VerifyNotificationChannelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.VerifyNotificationChannelRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.monitoring.v3.NotificationChannel() - ); - client.innerApiCalls.verifyNotificationChannel = stubSimpleCall(expectedResponse); - const [response] = await client.verifyNotificationChannel(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.verifyNotificationChannel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.verifyNotificationChannel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes verifyNotificationChannel without error using callback', async () => { + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.VerifyNotificationChannelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.VerifyNotificationChannelRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.monitoring.v3.NotificationChannel(), + ); + client.innerApiCalls.verifyNotificationChannel = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.verifyNotificationChannel( + request, + ( + err?: Error | null, + result?: protos.google.monitoring.v3.INotificationChannel | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.verifyNotificationChannel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.verifyNotificationChannel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes verifyNotificationChannel without error using callback', async () => { - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.VerifyNotificationChannelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.VerifyNotificationChannelRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.monitoring.v3.NotificationChannel() - ); - client.innerApiCalls.verifyNotificationChannel = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.verifyNotificationChannel( - request, - (err?: Error|null, result?: protos.google.monitoring.v3.INotificationChannel|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.verifyNotificationChannel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.verifyNotificationChannel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes verifyNotificationChannel with error', async () => { + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.VerifyNotificationChannelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.VerifyNotificationChannelRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.verifyNotificationChannel = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.verifyNotificationChannel(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.verifyNotificationChannel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.verifyNotificationChannel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes verifyNotificationChannel with error', async () => { - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.VerifyNotificationChannelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.VerifyNotificationChannelRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.verifyNotificationChannel = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.verifyNotificationChannel(request), expectedError); - const actualRequest = (client.innerApiCalls.verifyNotificationChannel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.verifyNotificationChannel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes verifyNotificationChannel with closed client', async () => { + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.VerifyNotificationChannelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.VerifyNotificationChannelRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.verifyNotificationChannel(request), + expectedError, + ); + }); + }); + + describe('listNotificationChannelDescriptors', () => { + it('invokes listNotificationChannelDescriptors without error', async () => { + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListNotificationChannelDescriptorsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListNotificationChannelDescriptorsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.monitoring.v3.NotificationChannelDescriptor(), + ), + generateSampleMessage( + new protos.google.monitoring.v3.NotificationChannelDescriptor(), + ), + generateSampleMessage( + new protos.google.monitoring.v3.NotificationChannelDescriptor(), + ), + ]; + client.innerApiCalls.listNotificationChannelDescriptors = + stubSimpleCall(expectedResponse); + const [response] = + await client.listNotificationChannelDescriptors(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listNotificationChannelDescriptors as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listNotificationChannelDescriptors as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes verifyNotificationChannel with closed client', async () => { - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.VerifyNotificationChannelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.VerifyNotificationChannelRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.verifyNotificationChannel(request), expectedError); - }); + it('invokes listNotificationChannelDescriptors without error using callback', async () => { + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListNotificationChannelDescriptorsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListNotificationChannelDescriptorsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.monitoring.v3.NotificationChannelDescriptor(), + ), + generateSampleMessage( + new protos.google.monitoring.v3.NotificationChannelDescriptor(), + ), + generateSampleMessage( + new protos.google.monitoring.v3.NotificationChannelDescriptor(), + ), + ]; + client.innerApiCalls.listNotificationChannelDescriptors = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listNotificationChannelDescriptors( + request, + ( + err?: Error | null, + result?: + | protos.google.monitoring.v3.INotificationChannelDescriptor[] + | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listNotificationChannelDescriptors as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listNotificationChannelDescriptors as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('listNotificationChannelDescriptors', () => { - it('invokes listNotificationChannelDescriptors without error', async () => { - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListNotificationChannelDescriptorsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListNotificationChannelDescriptorsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.monitoring.v3.NotificationChannelDescriptor()), - generateSampleMessage(new protos.google.monitoring.v3.NotificationChannelDescriptor()), - generateSampleMessage(new protos.google.monitoring.v3.NotificationChannelDescriptor()), - ]; - client.innerApiCalls.listNotificationChannelDescriptors = stubSimpleCall(expectedResponse); - const [response] = await client.listNotificationChannelDescriptors(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listNotificationChannelDescriptors as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listNotificationChannelDescriptors as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listNotificationChannelDescriptors with error', async () => { + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListNotificationChannelDescriptorsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListNotificationChannelDescriptorsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listNotificationChannelDescriptors = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.listNotificationChannelDescriptors(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.listNotificationChannelDescriptors as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listNotificationChannelDescriptors as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listNotificationChannelDescriptors without error using callback', async () => { - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListNotificationChannelDescriptorsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListNotificationChannelDescriptorsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.monitoring.v3.NotificationChannelDescriptor()), - generateSampleMessage(new protos.google.monitoring.v3.NotificationChannelDescriptor()), - generateSampleMessage(new protos.google.monitoring.v3.NotificationChannelDescriptor()), - ]; - client.innerApiCalls.listNotificationChannelDescriptors = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listNotificationChannelDescriptors( - request, - (err?: Error|null, result?: protos.google.monitoring.v3.INotificationChannelDescriptor[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listNotificationChannelDescriptors as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listNotificationChannelDescriptors as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listNotificationChannelDescriptorsStream without error', async () => { + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListNotificationChannelDescriptorsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListNotificationChannelDescriptorsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.monitoring.v3.NotificationChannelDescriptor(), + ), + generateSampleMessage( + new protos.google.monitoring.v3.NotificationChannelDescriptor(), + ), + generateSampleMessage( + new protos.google.monitoring.v3.NotificationChannelDescriptor(), + ), + ]; + client.descriptors.page.listNotificationChannelDescriptors.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listNotificationChannelDescriptorsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.monitoring.v3.NotificationChannelDescriptor[] = + []; + stream.on( + 'data', + ( + response: protos.google.monitoring.v3.NotificationChannelDescriptor, + ) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + ( + client.descriptors.page.listNotificationChannelDescriptors + .createStream as SinonStub + ) + .getCall(0) + .calledWith( + client.innerApiCalls.listNotificationChannelDescriptors, + request, + ), + ); + assert( + ( + client.descriptors.page.listNotificationChannelDescriptors + .createStream as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); - it('invokes listNotificationChannelDescriptors with error', async () => { - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListNotificationChannelDescriptorsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListNotificationChannelDescriptorsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listNotificationChannelDescriptors = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listNotificationChannelDescriptors(request), expectedError); - const actualRequest = (client.innerApiCalls.listNotificationChannelDescriptors as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listNotificationChannelDescriptors as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listNotificationChannelDescriptorsStream with error', async () => { + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListNotificationChannelDescriptorsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListNotificationChannelDescriptorsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listNotificationChannelDescriptors.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listNotificationChannelDescriptorsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.monitoring.v3.NotificationChannelDescriptor[] = + []; + stream.on( + 'data', + ( + response: protos.google.monitoring.v3.NotificationChannelDescriptor, + ) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + ( + client.descriptors.page.listNotificationChannelDescriptors + .createStream as SinonStub + ) + .getCall(0) + .calledWith( + client.innerApiCalls.listNotificationChannelDescriptors, + request, + ), + ); + assert( + ( + client.descriptors.page.listNotificationChannelDescriptors + .createStream as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); - it('invokes listNotificationChannelDescriptorsStream without error', async () => { - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListNotificationChannelDescriptorsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListNotificationChannelDescriptorsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.monitoring.v3.NotificationChannelDescriptor()), - generateSampleMessage(new protos.google.monitoring.v3.NotificationChannelDescriptor()), - generateSampleMessage(new protos.google.monitoring.v3.NotificationChannelDescriptor()), - ]; - client.descriptors.page.listNotificationChannelDescriptors.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listNotificationChannelDescriptorsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.monitoring.v3.NotificationChannelDescriptor[] = []; - stream.on('data', (response: protos.google.monitoring.v3.NotificationChannelDescriptor) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.listNotificationChannelDescriptors.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listNotificationChannelDescriptors, request)); - assert( - (client.descriptors.page.listNotificationChannelDescriptors.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listNotificationChannelDescriptors without error', async () => { + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListNotificationChannelDescriptorsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListNotificationChannelDescriptorsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.monitoring.v3.NotificationChannelDescriptor(), + ), + generateSampleMessage( + new protos.google.monitoring.v3.NotificationChannelDescriptor(), + ), + generateSampleMessage( + new protos.google.monitoring.v3.NotificationChannelDescriptor(), + ), + ]; + client.descriptors.page.listNotificationChannelDescriptors.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.monitoring.v3.INotificationChannelDescriptor[] = + []; + const iterable = client.listNotificationChannelDescriptorsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listNotificationChannelDescriptors + .asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + ( + client.descriptors.page.listNotificationChannelDescriptors + .asyncIterate as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); - it('invokes listNotificationChannelDescriptorsStream with error', async () => { - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListNotificationChannelDescriptorsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListNotificationChannelDescriptorsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listNotificationChannelDescriptors.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listNotificationChannelDescriptorsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.monitoring.v3.NotificationChannelDescriptor[] = []; - stream.on('data', (response: protos.google.monitoring.v3.NotificationChannelDescriptor) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listNotificationChannelDescriptors.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listNotificationChannelDescriptors, request)); - assert( - (client.descriptors.page.listNotificationChannelDescriptors.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listNotificationChannelDescriptors with error', async () => { + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListNotificationChannelDescriptorsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListNotificationChannelDescriptorsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listNotificationChannelDescriptors.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listNotificationChannelDescriptorsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.monitoring.v3.INotificationChannelDescriptor[] = + []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listNotificationChannelDescriptors + .asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + ( + client.descriptors.page.listNotificationChannelDescriptors + .asyncIterate as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); + }); + + describe('listNotificationChannels', () => { + it('invokes listNotificationChannels without error', async () => { + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListNotificationChannelsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListNotificationChannelsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.monitoring.v3.NotificationChannel(), + ), + generateSampleMessage( + new protos.google.monitoring.v3.NotificationChannel(), + ), + generateSampleMessage( + new protos.google.monitoring.v3.NotificationChannel(), + ), + ]; + client.innerApiCalls.listNotificationChannels = + stubSimpleCall(expectedResponse); + const [response] = await client.listNotificationChannels(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listNotificationChannels as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listNotificationChannels as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('uses async iteration with listNotificationChannelDescriptors without error', async () => { - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListNotificationChannelDescriptorsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListNotificationChannelDescriptorsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.monitoring.v3.NotificationChannelDescriptor()), - generateSampleMessage(new protos.google.monitoring.v3.NotificationChannelDescriptor()), - generateSampleMessage(new protos.google.monitoring.v3.NotificationChannelDescriptor()), - ]; - client.descriptors.page.listNotificationChannelDescriptors.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.monitoring.v3.INotificationChannelDescriptor[] = []; - const iterable = client.listNotificationChannelDescriptorsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); + it('invokes listNotificationChannels without error using callback', async () => { + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListNotificationChannelsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListNotificationChannelsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.monitoring.v3.NotificationChannel(), + ), + generateSampleMessage( + new protos.google.monitoring.v3.NotificationChannel(), + ), + generateSampleMessage( + new protos.google.monitoring.v3.NotificationChannel(), + ), + ]; + client.innerApiCalls.listNotificationChannels = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listNotificationChannels( + request, + ( + err?: Error | null, + result?: protos.google.monitoring.v3.INotificationChannel[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listNotificationChannelDescriptors.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listNotificationChannelDescriptors.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); - - it('uses async iteration with listNotificationChannelDescriptors with error', async () => { - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListNotificationChannelDescriptorsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListNotificationChannelDescriptorsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listNotificationChannelDescriptors.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listNotificationChannelDescriptorsAsync(request); - await assert.rejects(async () => { - const responses: protos.google.monitoring.v3.INotificationChannelDescriptor[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listNotificationChannelDescriptors.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listNotificationChannelDescriptors.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listNotificationChannels as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listNotificationChannels as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('listNotificationChannels', () => { - it('invokes listNotificationChannels without error', async () => { - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListNotificationChannelsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListNotificationChannelsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.monitoring.v3.NotificationChannel()), - generateSampleMessage(new protos.google.monitoring.v3.NotificationChannel()), - generateSampleMessage(new protos.google.monitoring.v3.NotificationChannel()), - ]; - client.innerApiCalls.listNotificationChannels = stubSimpleCall(expectedResponse); - const [response] = await client.listNotificationChannels(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listNotificationChannels as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listNotificationChannels as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listNotificationChannels without error using callback', async () => { - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListNotificationChannelsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListNotificationChannelsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.monitoring.v3.NotificationChannel()), - generateSampleMessage(new protos.google.monitoring.v3.NotificationChannel()), - generateSampleMessage(new protos.google.monitoring.v3.NotificationChannel()), - ]; - client.innerApiCalls.listNotificationChannels = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listNotificationChannels( - request, - (err?: Error|null, result?: protos.google.monitoring.v3.INotificationChannel[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listNotificationChannels as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listNotificationChannels as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listNotificationChannels with error', async () => { - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListNotificationChannelsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListNotificationChannelsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listNotificationChannels = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listNotificationChannels(request), expectedError); - const actualRequest = (client.innerApiCalls.listNotificationChannels as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listNotificationChannels as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listNotificationChannelsStream without error', async () => { - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListNotificationChannelsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListNotificationChannelsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.monitoring.v3.NotificationChannel()), - generateSampleMessage(new protos.google.monitoring.v3.NotificationChannel()), - generateSampleMessage(new protos.google.monitoring.v3.NotificationChannel()), - ]; - client.descriptors.page.listNotificationChannels.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listNotificationChannelsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.monitoring.v3.NotificationChannel[] = []; - stream.on('data', (response: protos.google.monitoring.v3.NotificationChannel) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.listNotificationChannels.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listNotificationChannels, request)); - assert( - (client.descriptors.page.listNotificationChannels.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listNotificationChannels with error', async () => { + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListNotificationChannelsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListNotificationChannelsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listNotificationChannels = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.listNotificationChannels(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.listNotificationChannels as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listNotificationChannels as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listNotificationChannelsStream with error', async () => { - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListNotificationChannelsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListNotificationChannelsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listNotificationChannels.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listNotificationChannelsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.monitoring.v3.NotificationChannel[] = []; - stream.on('data', (response: protos.google.monitoring.v3.NotificationChannel) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listNotificationChannels.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listNotificationChannels, request)); - assert( - (client.descriptors.page.listNotificationChannels.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listNotificationChannelsStream without error', async () => { + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListNotificationChannelsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListNotificationChannelsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.monitoring.v3.NotificationChannel(), + ), + generateSampleMessage( + new protos.google.monitoring.v3.NotificationChannel(), + ), + generateSampleMessage( + new protos.google.monitoring.v3.NotificationChannel(), + ), + ]; + client.descriptors.page.listNotificationChannels.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listNotificationChannelsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.monitoring.v3.NotificationChannel[] = []; + stream.on( + 'data', + (response: protos.google.monitoring.v3.NotificationChannel) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + ( + client.descriptors.page.listNotificationChannels + .createStream as SinonStub + ) + .getCall(0) + .calledWith(client.innerApiCalls.listNotificationChannels, request), + ); + assert( + ( + client.descriptors.page.listNotificationChannels + .createStream as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); - it('uses async iteration with listNotificationChannels without error', async () => { - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListNotificationChannelsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListNotificationChannelsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.monitoring.v3.NotificationChannel()), - generateSampleMessage(new protos.google.monitoring.v3.NotificationChannel()), - generateSampleMessage(new protos.google.monitoring.v3.NotificationChannel()), - ]; - client.descriptors.page.listNotificationChannels.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.monitoring.v3.INotificationChannel[] = []; - const iterable = client.listNotificationChannelsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listNotificationChannels.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listNotificationChannels.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listNotificationChannelsStream with error', async () => { + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListNotificationChannelsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListNotificationChannelsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listNotificationChannels.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listNotificationChannelsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.monitoring.v3.NotificationChannel[] = []; + stream.on( + 'data', + (response: protos.google.monitoring.v3.NotificationChannel) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + ( + client.descriptors.page.listNotificationChannels + .createStream as SinonStub + ) + .getCall(0) + .calledWith(client.innerApiCalls.listNotificationChannels, request), + ); + assert( + ( + client.descriptors.page.listNotificationChannels + .createStream as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); - it('uses async iteration with listNotificationChannels with error', async () => { - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListNotificationChannelsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListNotificationChannelsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listNotificationChannels.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listNotificationChannelsAsync(request); - await assert.rejects(async () => { - const responses: protos.google.monitoring.v3.INotificationChannel[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listNotificationChannels.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listNotificationChannels.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listNotificationChannels without error', async () => { + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListNotificationChannelsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListNotificationChannelsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.monitoring.v3.NotificationChannel(), + ), + generateSampleMessage( + new protos.google.monitoring.v3.NotificationChannel(), + ), + generateSampleMessage( + new protos.google.monitoring.v3.NotificationChannel(), + ), + ]; + client.descriptors.page.listNotificationChannels.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.monitoring.v3.INotificationChannel[] = []; + const iterable = client.listNotificationChannelsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listNotificationChannels + .asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + ( + client.descriptors.page.listNotificationChannels + .asyncIterate as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); }); - describe('Path templates', () => { - - describe('folderAlertPolicy', async () => { - const fakePath = "/rendered/path/folderAlertPolicy"; - const expectedParameters = { - folder: "folderValue", - alert_policy: "alertPolicyValue", - }; - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.folderAlertPolicyPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderAlertPolicyPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderAlertPolicyPath', () => { - const result = client.folderAlertPolicyPath("folderValue", "alertPolicyValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderAlertPolicyPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderAlertPolicyName', () => { - const result = client.matchFolderFromFolderAlertPolicyName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderAlertPolicyPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchAlertPolicyFromFolderAlertPolicyName', () => { - const result = client.matchAlertPolicyFromFolderAlertPolicyName(fakePath); - assert.strictEqual(result, "alertPolicyValue"); - assert((client.pathTemplates.folderAlertPolicyPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('uses async iteration with listNotificationChannels with error', async () => { + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListNotificationChannelsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListNotificationChannelsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listNotificationChannels.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listNotificationChannelsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.monitoring.v3.INotificationChannel[] = + []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listNotificationChannels + .asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + ( + client.descriptors.page.listNotificationChannels + .asyncIterate as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); + }); + + describe('Path templates', () => { + describe('folderAlertPolicy', async () => { + const fakePath = '/rendered/path/folderAlertPolicy'; + const expectedParameters = { + folder: 'folderValue', + alert_policy: 'alertPolicyValue', + }; + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + client.pathTemplates.folderAlertPolicyPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderAlertPolicyPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderAlertPolicyPath', () => { + const result = client.folderAlertPolicyPath( + 'folderValue', + 'alertPolicyValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.folderAlertPolicyPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderAlertPolicyName', () => { + const result = client.matchFolderFromFolderAlertPolicyName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + ( + client.pathTemplates.folderAlertPolicyPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchAlertPolicyFromFolderAlertPolicyName', () => { + const result = + client.matchAlertPolicyFromFolderAlertPolicyName(fakePath); + assert.strictEqual(result, 'alertPolicyValue'); + assert( + ( + client.pathTemplates.folderAlertPolicyPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('folderAlertPolicyCondition', async () => { - const fakePath = "/rendered/path/folderAlertPolicyCondition"; - const expectedParameters = { - folder: "folderValue", - alert_policy: "alertPolicyValue", - condition: "conditionValue", - }; - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.folderAlertPolicyConditionPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderAlertPolicyConditionPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderAlertPolicyConditionPath', () => { - const result = client.folderAlertPolicyConditionPath("folderValue", "alertPolicyValue", "conditionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderAlertPolicyConditionPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderAlertPolicyConditionName', () => { - const result = client.matchFolderFromFolderAlertPolicyConditionName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderAlertPolicyConditionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchAlertPolicyFromFolderAlertPolicyConditionName', () => { - const result = client.matchAlertPolicyFromFolderAlertPolicyConditionName(fakePath); - assert.strictEqual(result, "alertPolicyValue"); - assert((client.pathTemplates.folderAlertPolicyConditionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchConditionFromFolderAlertPolicyConditionName', () => { - const result = client.matchConditionFromFolderAlertPolicyConditionName(fakePath); - assert.strictEqual(result, "conditionValue"); - assert((client.pathTemplates.folderAlertPolicyConditionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('folderAlertPolicyCondition', async () => { + const fakePath = '/rendered/path/folderAlertPolicyCondition'; + const expectedParameters = { + folder: 'folderValue', + alert_policy: 'alertPolicyValue', + condition: 'conditionValue', + }; + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + client.pathTemplates.folderAlertPolicyConditionPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderAlertPolicyConditionPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderAlertPolicyConditionPath', () => { + const result = client.folderAlertPolicyConditionPath( + 'folderValue', + 'alertPolicyValue', + 'conditionValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.folderAlertPolicyConditionPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderAlertPolicyConditionName', () => { + const result = + client.matchFolderFromFolderAlertPolicyConditionName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + ( + client.pathTemplates.folderAlertPolicyConditionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchAlertPolicyFromFolderAlertPolicyConditionName', () => { + const result = + client.matchAlertPolicyFromFolderAlertPolicyConditionName(fakePath); + assert.strictEqual(result, 'alertPolicyValue'); + assert( + ( + client.pathTemplates.folderAlertPolicyConditionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchConditionFromFolderAlertPolicyConditionName', () => { + const result = + client.matchConditionFromFolderAlertPolicyConditionName(fakePath); + assert.strictEqual(result, 'conditionValue'); + assert( + ( + client.pathTemplates.folderAlertPolicyConditionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('folderChannelDescriptor', async () => { - const fakePath = "/rendered/path/folderChannelDescriptor"; - const expectedParameters = { - folder: "folderValue", - channel_descriptor: "channelDescriptorValue", - }; - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.folderChannelDescriptorPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderChannelDescriptorPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderChannelDescriptorPath', () => { - const result = client.folderChannelDescriptorPath("folderValue", "channelDescriptorValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderChannelDescriptorPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderChannelDescriptorName', () => { - const result = client.matchFolderFromFolderChannelDescriptorName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderChannelDescriptorPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchChannelDescriptorFromFolderChannelDescriptorName', () => { - const result = client.matchChannelDescriptorFromFolderChannelDescriptorName(fakePath); - assert.strictEqual(result, "channelDescriptorValue"); - assert((client.pathTemplates.folderChannelDescriptorPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('folderChannelDescriptor', async () => { + const fakePath = '/rendered/path/folderChannelDescriptor'; + const expectedParameters = { + folder: 'folderValue', + channel_descriptor: 'channelDescriptorValue', + }; + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + client.pathTemplates.folderChannelDescriptorPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderChannelDescriptorPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderChannelDescriptorPath', () => { + const result = client.folderChannelDescriptorPath( + 'folderValue', + 'channelDescriptorValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.folderChannelDescriptorPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderChannelDescriptorName', () => { + const result = + client.matchFolderFromFolderChannelDescriptorName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + ( + client.pathTemplates.folderChannelDescriptorPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchChannelDescriptorFromFolderChannelDescriptorName', () => { + const result = + client.matchChannelDescriptorFromFolderChannelDescriptorName( + fakePath, + ); + assert.strictEqual(result, 'channelDescriptorValue'); + assert( + ( + client.pathTemplates.folderChannelDescriptorPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('folderGroup', async () => { - const fakePath = "/rendered/path/folderGroup"; - const expectedParameters = { - folder: "folderValue", - group: "groupValue", - }; - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.folderGroupPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderGroupPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderGroupPath', () => { - const result = client.folderGroupPath("folderValue", "groupValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderGroupPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderGroupName', () => { - const result = client.matchFolderFromFolderGroupName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderGroupPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchGroupFromFolderGroupName', () => { - const result = client.matchGroupFromFolderGroupName(fakePath); - assert.strictEqual(result, "groupValue"); - assert((client.pathTemplates.folderGroupPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('folderGroup', async () => { + const fakePath = '/rendered/path/folderGroup'; + const expectedParameters = { + folder: 'folderValue', + group: 'groupValue', + }; + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + client.pathTemplates.folderGroupPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderGroupPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderGroupPath', () => { + const result = client.folderGroupPath('folderValue', 'groupValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.folderGroupPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderGroupName', () => { + const result = client.matchFolderFromFolderGroupName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + (client.pathTemplates.folderGroupPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchGroupFromFolderGroupName', () => { + const result = client.matchGroupFromFolderGroupName(fakePath); + assert.strictEqual(result, 'groupValue'); + assert( + (client.pathTemplates.folderGroupPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('folderNotificationChannel', async () => { - const fakePath = "/rendered/path/folderNotificationChannel"; - const expectedParameters = { - folder: "folderValue", - notification_channel: "notificationChannelValue", - }; - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.folderNotificationChannelPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderNotificationChannelPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderNotificationChannelPath', () => { - const result = client.folderNotificationChannelPath("folderValue", "notificationChannelValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderNotificationChannelPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderNotificationChannelName', () => { - const result = client.matchFolderFromFolderNotificationChannelName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderNotificationChannelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchNotificationChannelFromFolderNotificationChannelName', () => { - const result = client.matchNotificationChannelFromFolderNotificationChannelName(fakePath); - assert.strictEqual(result, "notificationChannelValue"); - assert((client.pathTemplates.folderNotificationChannelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('folderNotificationChannel', async () => { + const fakePath = '/rendered/path/folderNotificationChannel'; + const expectedParameters = { + folder: 'folderValue', + notification_channel: 'notificationChannelValue', + }; + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + client.pathTemplates.folderNotificationChannelPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderNotificationChannelPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderNotificationChannelPath', () => { + const result = client.folderNotificationChannelPath( + 'folderValue', + 'notificationChannelValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.folderNotificationChannelPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderNotificationChannelName', () => { + const result = + client.matchFolderFromFolderNotificationChannelName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + ( + client.pathTemplates.folderNotificationChannelPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchNotificationChannelFromFolderNotificationChannelName', () => { + const result = + client.matchNotificationChannelFromFolderNotificationChannelName( + fakePath, + ); + assert.strictEqual(result, 'notificationChannelValue'); + assert( + ( + client.pathTemplates.folderNotificationChannelPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('folderService', async () => { - const fakePath = "/rendered/path/folderService"; - const expectedParameters = { - folder: "folderValue", - service: "serviceValue", - }; - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.folderServicePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderServicePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderServicePath', () => { - const result = client.folderServicePath("folderValue", "serviceValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderServicePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderServiceName', () => { - const result = client.matchFolderFromFolderServiceName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderServicePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServiceFromFolderServiceName', () => { - const result = client.matchServiceFromFolderServiceName(fakePath); - assert.strictEqual(result, "serviceValue"); - assert((client.pathTemplates.folderServicePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('folderService', async () => { + const fakePath = '/rendered/path/folderService'; + const expectedParameters = { + folder: 'folderValue', + service: 'serviceValue', + }; + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + client.pathTemplates.folderServicePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderServicePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderServicePath', () => { + const result = client.folderServicePath('folderValue', 'serviceValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.folderServicePathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderServiceName', () => { + const result = client.matchFolderFromFolderServiceName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + (client.pathTemplates.folderServicePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServiceFromFolderServiceName', () => { + const result = client.matchServiceFromFolderServiceName(fakePath); + assert.strictEqual(result, 'serviceValue'); + assert( + (client.pathTemplates.folderServicePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('folderServiceServiceLevelObjective', async () => { - const fakePath = "/rendered/path/folderServiceServiceLevelObjective"; - const expectedParameters = { - folder: "folderValue", - service: "serviceValue", - service_level_objective: "serviceLevelObjectiveValue", - }; - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderServiceServiceLevelObjectivePath', () => { - const result = client.folderServiceServiceLevelObjectivePath("folderValue", "serviceValue", "serviceLevelObjectiveValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderServiceServiceLevelObjectiveName', () => { - const result = client.matchFolderFromFolderServiceServiceLevelObjectiveName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServiceFromFolderServiceServiceLevelObjectiveName', () => { - const result = client.matchServiceFromFolderServiceServiceLevelObjectiveName(fakePath); - assert.strictEqual(result, "serviceValue"); - assert((client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServiceLevelObjectiveFromFolderServiceServiceLevelObjectiveName', () => { - const result = client.matchServiceLevelObjectiveFromFolderServiceServiceLevelObjectiveName(fakePath); - assert.strictEqual(result, "serviceLevelObjectiveValue"); - assert((client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('folderServiceServiceLevelObjective', async () => { + const fakePath = '/rendered/path/folderServiceServiceLevelObjective'; + const expectedParameters = { + folder: 'folderValue', + service: 'serviceValue', + service_level_objective: 'serviceLevelObjectiveValue', + }; + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('folderServiceServiceLevelObjectivePath', () => { + const result = client.folderServiceServiceLevelObjectivePath( + 'folderValue', + 'serviceValue', + 'serviceLevelObjectiveValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderServiceServiceLevelObjectiveName', () => { + const result = + client.matchFolderFromFolderServiceServiceLevelObjectiveName( + fakePath, + ); + assert.strictEqual(result, 'folderValue'); + assert( + ( + client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServiceFromFolderServiceServiceLevelObjectiveName', () => { + const result = + client.matchServiceFromFolderServiceServiceLevelObjectiveName( + fakePath, + ); + assert.strictEqual(result, 'serviceValue'); + assert( + ( + client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServiceLevelObjectiveFromFolderServiceServiceLevelObjectiveName', () => { + const result = + client.matchServiceLevelObjectiveFromFolderServiceServiceLevelObjectiveName( + fakePath, + ); + assert.strictEqual(result, 'serviceLevelObjectiveValue'); + assert( + ( + client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('folderUptimeCheckConfig', async () => { - const fakePath = "/rendered/path/folderUptimeCheckConfig"; - const expectedParameters = { - folder: "folderValue", - uptime_check_config: "uptimeCheckConfigValue", - }; - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.folderUptimeCheckConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderUptimeCheckConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderUptimeCheckConfigPath', () => { - const result = client.folderUptimeCheckConfigPath("folderValue", "uptimeCheckConfigValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderUptimeCheckConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderUptimeCheckConfigName', () => { - const result = client.matchFolderFromFolderUptimeCheckConfigName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderUptimeCheckConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchUptimeCheckConfigFromFolderUptimeCheckConfigName', () => { - const result = client.matchUptimeCheckConfigFromFolderUptimeCheckConfigName(fakePath); - assert.strictEqual(result, "uptimeCheckConfigValue"); - assert((client.pathTemplates.folderUptimeCheckConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('folderUptimeCheckConfig', async () => { + const fakePath = '/rendered/path/folderUptimeCheckConfig'; + const expectedParameters = { + folder: 'folderValue', + uptime_check_config: 'uptimeCheckConfigValue', + }; + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + client.pathTemplates.folderUptimeCheckConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderUptimeCheckConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderUptimeCheckConfigPath', () => { + const result = client.folderUptimeCheckConfigPath( + 'folderValue', + 'uptimeCheckConfigValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.folderUptimeCheckConfigPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderUptimeCheckConfigName', () => { + const result = + client.matchFolderFromFolderUptimeCheckConfigName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + ( + client.pathTemplates.folderUptimeCheckConfigPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchUptimeCheckConfigFromFolderUptimeCheckConfigName', () => { + const result = + client.matchUptimeCheckConfigFromFolderUptimeCheckConfigName( + fakePath, + ); + assert.strictEqual(result, 'uptimeCheckConfigValue'); + assert( + ( + client.pathTemplates.folderUptimeCheckConfigPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('organizationAlertPolicy', async () => { - const fakePath = "/rendered/path/organizationAlertPolicy"; - const expectedParameters = { - organization: "organizationValue", - alert_policy: "alertPolicyValue", - }; - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.organizationAlertPolicyPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationAlertPolicyPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationAlertPolicyPath', () => { - const result = client.organizationAlertPolicyPath("organizationValue", "alertPolicyValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationAlertPolicyPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationAlertPolicyName', () => { - const result = client.matchOrganizationFromOrganizationAlertPolicyName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationAlertPolicyPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchAlertPolicyFromOrganizationAlertPolicyName', () => { - const result = client.matchAlertPolicyFromOrganizationAlertPolicyName(fakePath); - assert.strictEqual(result, "alertPolicyValue"); - assert((client.pathTemplates.organizationAlertPolicyPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('organizationAlertPolicy', async () => { + const fakePath = '/rendered/path/organizationAlertPolicy'; + const expectedParameters = { + organization: 'organizationValue', + alert_policy: 'alertPolicyValue', + }; + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + client.pathTemplates.organizationAlertPolicyPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.organizationAlertPolicyPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('organizationAlertPolicyPath', () => { + const result = client.organizationAlertPolicyPath( + 'organizationValue', + 'alertPolicyValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationAlertPolicyPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationAlertPolicyName', () => { + const result = + client.matchOrganizationFromOrganizationAlertPolicyName(fakePath); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationAlertPolicyPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchAlertPolicyFromOrganizationAlertPolicyName', () => { + const result = + client.matchAlertPolicyFromOrganizationAlertPolicyName(fakePath); + assert.strictEqual(result, 'alertPolicyValue'); + assert( + ( + client.pathTemplates.organizationAlertPolicyPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('organizationAlertPolicyCondition', async () => { - const fakePath = "/rendered/path/organizationAlertPolicyCondition"; - const expectedParameters = { - organization: "organizationValue", - alert_policy: "alertPolicyValue", - condition: "conditionValue", - }; - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.organizationAlertPolicyConditionPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationAlertPolicyConditionPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationAlertPolicyConditionPath', () => { - const result = client.organizationAlertPolicyConditionPath("organizationValue", "alertPolicyValue", "conditionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationAlertPolicyConditionPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationAlertPolicyConditionName', () => { - const result = client.matchOrganizationFromOrganizationAlertPolicyConditionName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationAlertPolicyConditionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchAlertPolicyFromOrganizationAlertPolicyConditionName', () => { - const result = client.matchAlertPolicyFromOrganizationAlertPolicyConditionName(fakePath); - assert.strictEqual(result, "alertPolicyValue"); - assert((client.pathTemplates.organizationAlertPolicyConditionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchConditionFromOrganizationAlertPolicyConditionName', () => { - const result = client.matchConditionFromOrganizationAlertPolicyConditionName(fakePath); - assert.strictEqual(result, "conditionValue"); - assert((client.pathTemplates.organizationAlertPolicyConditionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('organizationAlertPolicyCondition', async () => { + const fakePath = '/rendered/path/organizationAlertPolicyCondition'; + const expectedParameters = { + organization: 'organizationValue', + alert_policy: 'alertPolicyValue', + condition: 'conditionValue', + }; + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + client.pathTemplates.organizationAlertPolicyConditionPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.organizationAlertPolicyConditionPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('organizationAlertPolicyConditionPath', () => { + const result = client.organizationAlertPolicyConditionPath( + 'organizationValue', + 'alertPolicyValue', + 'conditionValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationAlertPolicyConditionPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationAlertPolicyConditionName', () => { + const result = + client.matchOrganizationFromOrganizationAlertPolicyConditionName( + fakePath, + ); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationAlertPolicyConditionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchAlertPolicyFromOrganizationAlertPolicyConditionName', () => { + const result = + client.matchAlertPolicyFromOrganizationAlertPolicyConditionName( + fakePath, + ); + assert.strictEqual(result, 'alertPolicyValue'); + assert( + ( + client.pathTemplates.organizationAlertPolicyConditionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchConditionFromOrganizationAlertPolicyConditionName', () => { + const result = + client.matchConditionFromOrganizationAlertPolicyConditionName( + fakePath, + ); + assert.strictEqual(result, 'conditionValue'); + assert( + ( + client.pathTemplates.organizationAlertPolicyConditionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('organizationChannelDescriptor', async () => { - const fakePath = "/rendered/path/organizationChannelDescriptor"; - const expectedParameters = { - organization: "organizationValue", - channel_descriptor: "channelDescriptorValue", - }; - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.organizationChannelDescriptorPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationChannelDescriptorPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationChannelDescriptorPath', () => { - const result = client.organizationChannelDescriptorPath("organizationValue", "channelDescriptorValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationChannelDescriptorPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationChannelDescriptorName', () => { - const result = client.matchOrganizationFromOrganizationChannelDescriptorName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationChannelDescriptorPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchChannelDescriptorFromOrganizationChannelDescriptorName', () => { - const result = client.matchChannelDescriptorFromOrganizationChannelDescriptorName(fakePath); - assert.strictEqual(result, "channelDescriptorValue"); - assert((client.pathTemplates.organizationChannelDescriptorPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('organizationChannelDescriptor', async () => { + const fakePath = '/rendered/path/organizationChannelDescriptor'; + const expectedParameters = { + organization: 'organizationValue', + channel_descriptor: 'channelDescriptorValue', + }; + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + client.pathTemplates.organizationChannelDescriptorPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.organizationChannelDescriptorPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('organizationChannelDescriptorPath', () => { + const result = client.organizationChannelDescriptorPath( + 'organizationValue', + 'channelDescriptorValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationChannelDescriptorPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationChannelDescriptorName', () => { + const result = + client.matchOrganizationFromOrganizationChannelDescriptorName( + fakePath, + ); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationChannelDescriptorPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchChannelDescriptorFromOrganizationChannelDescriptorName', () => { + const result = + client.matchChannelDescriptorFromOrganizationChannelDescriptorName( + fakePath, + ); + assert.strictEqual(result, 'channelDescriptorValue'); + assert( + ( + client.pathTemplates.organizationChannelDescriptorPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('organizationGroup', async () => { - const fakePath = "/rendered/path/organizationGroup"; - const expectedParameters = { - organization: "organizationValue", - group: "groupValue", - }; - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.organizationGroupPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationGroupPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationGroupPath', () => { - const result = client.organizationGroupPath("organizationValue", "groupValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationGroupPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationGroupName', () => { - const result = client.matchOrganizationFromOrganizationGroupName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationGroupPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchGroupFromOrganizationGroupName', () => { - const result = client.matchGroupFromOrganizationGroupName(fakePath); - assert.strictEqual(result, "groupValue"); - assert((client.pathTemplates.organizationGroupPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('organizationGroup', async () => { + const fakePath = '/rendered/path/organizationGroup'; + const expectedParameters = { + organization: 'organizationValue', + group: 'groupValue', + }; + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + client.pathTemplates.organizationGroupPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.organizationGroupPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('organizationGroupPath', () => { + const result = client.organizationGroupPath( + 'organizationValue', + 'groupValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationGroupPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationGroupName', () => { + const result = + client.matchOrganizationFromOrganizationGroupName(fakePath); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationGroupPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchGroupFromOrganizationGroupName', () => { + const result = client.matchGroupFromOrganizationGroupName(fakePath); + assert.strictEqual(result, 'groupValue'); + assert( + ( + client.pathTemplates.organizationGroupPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('organizationNotificationChannel', async () => { - const fakePath = "/rendered/path/organizationNotificationChannel"; - const expectedParameters = { - organization: "organizationValue", - notification_channel: "notificationChannelValue", - }; - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.organizationNotificationChannelPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationNotificationChannelPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationNotificationChannelPath', () => { - const result = client.organizationNotificationChannelPath("organizationValue", "notificationChannelValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationNotificationChannelPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationNotificationChannelName', () => { - const result = client.matchOrganizationFromOrganizationNotificationChannelName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationNotificationChannelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchNotificationChannelFromOrganizationNotificationChannelName', () => { - const result = client.matchNotificationChannelFromOrganizationNotificationChannelName(fakePath); - assert.strictEqual(result, "notificationChannelValue"); - assert((client.pathTemplates.organizationNotificationChannelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('organizationNotificationChannel', async () => { + const fakePath = '/rendered/path/organizationNotificationChannel'; + const expectedParameters = { + organization: 'organizationValue', + notification_channel: 'notificationChannelValue', + }; + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + client.pathTemplates.organizationNotificationChannelPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.organizationNotificationChannelPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('organizationNotificationChannelPath', () => { + const result = client.organizationNotificationChannelPath( + 'organizationValue', + 'notificationChannelValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationNotificationChannelPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationNotificationChannelName', () => { + const result = + client.matchOrganizationFromOrganizationNotificationChannelName( + fakePath, + ); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationNotificationChannelPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchNotificationChannelFromOrganizationNotificationChannelName', () => { + const result = + client.matchNotificationChannelFromOrganizationNotificationChannelName( + fakePath, + ); + assert.strictEqual(result, 'notificationChannelValue'); + assert( + ( + client.pathTemplates.organizationNotificationChannelPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('organizationService', async () => { - const fakePath = "/rendered/path/organizationService"; - const expectedParameters = { - organization: "organizationValue", - service: "serviceValue", - }; - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.organizationServicePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationServicePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationServicePath', () => { - const result = client.organizationServicePath("organizationValue", "serviceValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationServicePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationServiceName', () => { - const result = client.matchOrganizationFromOrganizationServiceName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationServicePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServiceFromOrganizationServiceName', () => { - const result = client.matchServiceFromOrganizationServiceName(fakePath); - assert.strictEqual(result, "serviceValue"); - assert((client.pathTemplates.organizationServicePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('organizationService', async () => { + const fakePath = '/rendered/path/organizationService'; + const expectedParameters = { + organization: 'organizationValue', + service: 'serviceValue', + }; + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + client.pathTemplates.organizationServicePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.organizationServicePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('organizationServicePath', () => { + const result = client.organizationServicePath( + 'organizationValue', + 'serviceValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationServicePathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationServiceName', () => { + const result = + client.matchOrganizationFromOrganizationServiceName(fakePath); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationServicePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServiceFromOrganizationServiceName', () => { + const result = client.matchServiceFromOrganizationServiceName(fakePath); + assert.strictEqual(result, 'serviceValue'); + assert( + ( + client.pathTemplates.organizationServicePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('organizationServiceServiceLevelObjective', async () => { - const fakePath = "/rendered/path/organizationServiceServiceLevelObjective"; - const expectedParameters = { - organization: "organizationValue", - service: "serviceValue", - service_level_objective: "serviceLevelObjectiveValue", - }; - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationServiceServiceLevelObjectivePath', () => { - const result = client.organizationServiceServiceLevelObjectivePath("organizationValue", "serviceValue", "serviceLevelObjectiveValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationServiceServiceLevelObjectiveName', () => { - const result = client.matchOrganizationFromOrganizationServiceServiceLevelObjectiveName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServiceFromOrganizationServiceServiceLevelObjectiveName', () => { - const result = client.matchServiceFromOrganizationServiceServiceLevelObjectiveName(fakePath); - assert.strictEqual(result, "serviceValue"); - assert((client.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServiceLevelObjectiveFromOrganizationServiceServiceLevelObjectiveName', () => { - const result = client.matchServiceLevelObjectiveFromOrganizationServiceServiceLevelObjectiveName(fakePath); - assert.strictEqual(result, "serviceLevelObjectiveValue"); - assert((client.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('organizationServiceServiceLevelObjective', async () => { + const fakePath = + '/rendered/path/organizationServiceServiceLevelObjective'; + const expectedParameters = { + organization: 'organizationValue', + service: 'serviceValue', + service_level_objective: 'serviceLevelObjectiveValue', + }; + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + client.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('organizationServiceServiceLevelObjectivePath', () => { + const result = client.organizationServiceServiceLevelObjectivePath( + 'organizationValue', + 'serviceValue', + 'serviceLevelObjectiveValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates + .organizationServiceServiceLevelObjectivePathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationServiceServiceLevelObjectiveName', () => { + const result = + client.matchOrganizationFromOrganizationServiceServiceLevelObjectiveName( + fakePath, + ); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates + .organizationServiceServiceLevelObjectivePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServiceFromOrganizationServiceServiceLevelObjectiveName', () => { + const result = + client.matchServiceFromOrganizationServiceServiceLevelObjectiveName( + fakePath, + ); + assert.strictEqual(result, 'serviceValue'); + assert( + ( + client.pathTemplates + .organizationServiceServiceLevelObjectivePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServiceLevelObjectiveFromOrganizationServiceServiceLevelObjectiveName', () => { + const result = + client.matchServiceLevelObjectiveFromOrganizationServiceServiceLevelObjectiveName( + fakePath, + ); + assert.strictEqual(result, 'serviceLevelObjectiveValue'); + assert( + ( + client.pathTemplates + .organizationServiceServiceLevelObjectivePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('organizationUptimeCheckConfig', async () => { - const fakePath = "/rendered/path/organizationUptimeCheckConfig"; - const expectedParameters = { - organization: "organizationValue", - uptime_check_config: "uptimeCheckConfigValue", - }; - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.organizationUptimeCheckConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationUptimeCheckConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationUptimeCheckConfigPath', () => { - const result = client.organizationUptimeCheckConfigPath("organizationValue", "uptimeCheckConfigValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationUptimeCheckConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationUptimeCheckConfigName', () => { - const result = client.matchOrganizationFromOrganizationUptimeCheckConfigName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationUptimeCheckConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchUptimeCheckConfigFromOrganizationUptimeCheckConfigName', () => { - const result = client.matchUptimeCheckConfigFromOrganizationUptimeCheckConfigName(fakePath); - assert.strictEqual(result, "uptimeCheckConfigValue"); - assert((client.pathTemplates.organizationUptimeCheckConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('organizationUptimeCheckConfig', async () => { + const fakePath = '/rendered/path/organizationUptimeCheckConfig'; + const expectedParameters = { + organization: 'organizationValue', + uptime_check_config: 'uptimeCheckConfigValue', + }; + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + client.pathTemplates.organizationUptimeCheckConfigPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.organizationUptimeCheckConfigPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('organizationUptimeCheckConfigPath', () => { + const result = client.organizationUptimeCheckConfigPath( + 'organizationValue', + 'uptimeCheckConfigValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationUptimeCheckConfigPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationUptimeCheckConfigName', () => { + const result = + client.matchOrganizationFromOrganizationUptimeCheckConfigName( + fakePath, + ); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationUptimeCheckConfigPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchUptimeCheckConfigFromOrganizationUptimeCheckConfigName', () => { + const result = + client.matchUptimeCheckConfigFromOrganizationUptimeCheckConfigName( + fakePath, + ); + assert.strictEqual(result, 'uptimeCheckConfigValue'); + assert( + ( + client.pathTemplates.organizationUptimeCheckConfigPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectAlertPolicy', async () => { - const fakePath = "/rendered/path/projectAlertPolicy"; - const expectedParameters = { - project: "projectValue", - alert_policy: "alertPolicyValue", - }; - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.projectAlertPolicyPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectAlertPolicyPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectAlertPolicyPath', () => { - const result = client.projectAlertPolicyPath("projectValue", "alertPolicyValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectAlertPolicyPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectAlertPolicyName', () => { - const result = client.matchProjectFromProjectAlertPolicyName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectAlertPolicyPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchAlertPolicyFromProjectAlertPolicyName', () => { - const result = client.matchAlertPolicyFromProjectAlertPolicyName(fakePath); - assert.strictEqual(result, "alertPolicyValue"); - assert((client.pathTemplates.projectAlertPolicyPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectAlertPolicy', async () => { + const fakePath = '/rendered/path/projectAlertPolicy'; + const expectedParameters = { + project: 'projectValue', + alert_policy: 'alertPolicyValue', + }; + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + client.pathTemplates.projectAlertPolicyPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectAlertPolicyPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectAlertPolicyPath', () => { + const result = client.projectAlertPolicyPath( + 'projectValue', + 'alertPolicyValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.projectAlertPolicyPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectAlertPolicyName', () => { + const result = client.matchProjectFromProjectAlertPolicyName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.projectAlertPolicyPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchAlertPolicyFromProjectAlertPolicyName', () => { + const result = + client.matchAlertPolicyFromProjectAlertPolicyName(fakePath); + assert.strictEqual(result, 'alertPolicyValue'); + assert( + ( + client.pathTemplates.projectAlertPolicyPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectAlertPolicyCondition', async () => { - const fakePath = "/rendered/path/projectAlertPolicyCondition"; - const expectedParameters = { - project: "projectValue", - alert_policy: "alertPolicyValue", - condition: "conditionValue", - }; - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.projectAlertPolicyConditionPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectAlertPolicyConditionPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectAlertPolicyConditionPath', () => { - const result = client.projectAlertPolicyConditionPath("projectValue", "alertPolicyValue", "conditionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectAlertPolicyConditionPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectAlertPolicyConditionName', () => { - const result = client.matchProjectFromProjectAlertPolicyConditionName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectAlertPolicyConditionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchAlertPolicyFromProjectAlertPolicyConditionName', () => { - const result = client.matchAlertPolicyFromProjectAlertPolicyConditionName(fakePath); - assert.strictEqual(result, "alertPolicyValue"); - assert((client.pathTemplates.projectAlertPolicyConditionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchConditionFromProjectAlertPolicyConditionName', () => { - const result = client.matchConditionFromProjectAlertPolicyConditionName(fakePath); - assert.strictEqual(result, "conditionValue"); - assert((client.pathTemplates.projectAlertPolicyConditionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectAlertPolicyCondition', async () => { + const fakePath = '/rendered/path/projectAlertPolicyCondition'; + const expectedParameters = { + project: 'projectValue', + alert_policy: 'alertPolicyValue', + condition: 'conditionValue', + }; + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + client.pathTemplates.projectAlertPolicyConditionPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.projectAlertPolicyConditionPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectAlertPolicyConditionPath', () => { + const result = client.projectAlertPolicyConditionPath( + 'projectValue', + 'alertPolicyValue', + 'conditionValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.projectAlertPolicyConditionPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectAlertPolicyConditionName', () => { + const result = + client.matchProjectFromProjectAlertPolicyConditionName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.projectAlertPolicyConditionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchAlertPolicyFromProjectAlertPolicyConditionName', () => { + const result = + client.matchAlertPolicyFromProjectAlertPolicyConditionName(fakePath); + assert.strictEqual(result, 'alertPolicyValue'); + assert( + ( + client.pathTemplates.projectAlertPolicyConditionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchConditionFromProjectAlertPolicyConditionName', () => { + const result = + client.matchConditionFromProjectAlertPolicyConditionName(fakePath); + assert.strictEqual(result, 'conditionValue'); + assert( + ( + client.pathTemplates.projectAlertPolicyConditionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectChannelDescriptor', async () => { - const fakePath = "/rendered/path/projectChannelDescriptor"; - const expectedParameters = { - project: "projectValue", - channel_descriptor: "channelDescriptorValue", - }; - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.projectChannelDescriptorPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectChannelDescriptorPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectChannelDescriptorPath', () => { - const result = client.projectChannelDescriptorPath("projectValue", "channelDescriptorValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectChannelDescriptorPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectChannelDescriptorName', () => { - const result = client.matchProjectFromProjectChannelDescriptorName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectChannelDescriptorPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchChannelDescriptorFromProjectChannelDescriptorName', () => { - const result = client.matchChannelDescriptorFromProjectChannelDescriptorName(fakePath); - assert.strictEqual(result, "channelDescriptorValue"); - assert((client.pathTemplates.projectChannelDescriptorPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectChannelDescriptor', async () => { + const fakePath = '/rendered/path/projectChannelDescriptor'; + const expectedParameters = { + project: 'projectValue', + channel_descriptor: 'channelDescriptorValue', + }; + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + client.pathTemplates.projectChannelDescriptorPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectChannelDescriptorPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectChannelDescriptorPath', () => { + const result = client.projectChannelDescriptorPath( + 'projectValue', + 'channelDescriptorValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.projectChannelDescriptorPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectChannelDescriptorName', () => { + const result = + client.matchProjectFromProjectChannelDescriptorName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.projectChannelDescriptorPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchChannelDescriptorFromProjectChannelDescriptorName', () => { + const result = + client.matchChannelDescriptorFromProjectChannelDescriptorName( + fakePath, + ); + assert.strictEqual(result, 'channelDescriptorValue'); + assert( + ( + client.pathTemplates.projectChannelDescriptorPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectGroup', async () => { - const fakePath = "/rendered/path/projectGroup"; - const expectedParameters = { - project: "projectValue", - group: "groupValue", - }; - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.projectGroupPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectGroupPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectGroupPath', () => { - const result = client.projectGroupPath("projectValue", "groupValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectGroupPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectGroupName', () => { - const result = client.matchProjectFromProjectGroupName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectGroupPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchGroupFromProjectGroupName', () => { - const result = client.matchGroupFromProjectGroupName(fakePath); - assert.strictEqual(result, "groupValue"); - assert((client.pathTemplates.projectGroupPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectGroup', async () => { + const fakePath = '/rendered/path/projectGroup'; + const expectedParameters = { + project: 'projectValue', + group: 'groupValue', + }; + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + client.pathTemplates.projectGroupPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectGroupPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectGroupPath', () => { + const result = client.projectGroupPath('projectValue', 'groupValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.projectGroupPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectGroupName', () => { + const result = client.matchProjectFromProjectGroupName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.projectGroupPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchGroupFromProjectGroupName', () => { + const result = client.matchGroupFromProjectGroupName(fakePath); + assert.strictEqual(result, 'groupValue'); + assert( + (client.pathTemplates.projectGroupPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectNotificationChannel', async () => { - const fakePath = "/rendered/path/projectNotificationChannel"; - const expectedParameters = { - project: "projectValue", - notification_channel: "notificationChannelValue", - }; - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.projectNotificationChannelPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectNotificationChannelPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectNotificationChannelPath', () => { - const result = client.projectNotificationChannelPath("projectValue", "notificationChannelValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectNotificationChannelPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectNotificationChannelName', () => { - const result = client.matchProjectFromProjectNotificationChannelName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectNotificationChannelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchNotificationChannelFromProjectNotificationChannelName', () => { - const result = client.matchNotificationChannelFromProjectNotificationChannelName(fakePath); - assert.strictEqual(result, "notificationChannelValue"); - assert((client.pathTemplates.projectNotificationChannelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectNotificationChannel', async () => { + const fakePath = '/rendered/path/projectNotificationChannel'; + const expectedParameters = { + project: 'projectValue', + notification_channel: 'notificationChannelValue', + }; + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + client.pathTemplates.projectNotificationChannelPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectNotificationChannelPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectNotificationChannelPath', () => { + const result = client.projectNotificationChannelPath( + 'projectValue', + 'notificationChannelValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.projectNotificationChannelPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectNotificationChannelName', () => { + const result = + client.matchProjectFromProjectNotificationChannelName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.projectNotificationChannelPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchNotificationChannelFromProjectNotificationChannelName', () => { + const result = + client.matchNotificationChannelFromProjectNotificationChannelName( + fakePath, + ); + assert.strictEqual(result, 'notificationChannelValue'); + assert( + ( + client.pathTemplates.projectNotificationChannelPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectService', async () => { - const fakePath = "/rendered/path/projectService"; - const expectedParameters = { - project: "projectValue", - service: "serviceValue", - }; - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.projectServicePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectServicePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectServicePath', () => { - const result = client.projectServicePath("projectValue", "serviceValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectServicePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectServiceName', () => { - const result = client.matchProjectFromProjectServiceName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectServicePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServiceFromProjectServiceName', () => { - const result = client.matchServiceFromProjectServiceName(fakePath); - assert.strictEqual(result, "serviceValue"); - assert((client.pathTemplates.projectServicePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectService', async () => { + const fakePath = '/rendered/path/projectService'; + const expectedParameters = { + project: 'projectValue', + service: 'serviceValue', + }; + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + client.pathTemplates.projectServicePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectServicePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectServicePath', () => { + const result = client.projectServicePath( + 'projectValue', + 'serviceValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.projectServicePathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectServiceName', () => { + const result = client.matchProjectFromProjectServiceName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.projectServicePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServiceFromProjectServiceName', () => { + const result = client.matchServiceFromProjectServiceName(fakePath); + assert.strictEqual(result, 'serviceValue'); + assert( + (client.pathTemplates.projectServicePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectServiceServiceLevelObjective', async () => { - const fakePath = "/rendered/path/projectServiceServiceLevelObjective"; - const expectedParameters = { - project: "projectValue", - service: "serviceValue", - service_level_objective: "serviceLevelObjectiveValue", - }; - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectServiceServiceLevelObjectivePath', () => { - const result = client.projectServiceServiceLevelObjectivePath("projectValue", "serviceValue", "serviceLevelObjectiveValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectServiceServiceLevelObjectiveName', () => { - const result = client.matchProjectFromProjectServiceServiceLevelObjectiveName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServiceFromProjectServiceServiceLevelObjectiveName', () => { - const result = client.matchServiceFromProjectServiceServiceLevelObjectiveName(fakePath); - assert.strictEqual(result, "serviceValue"); - assert((client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServiceLevelObjectiveFromProjectServiceServiceLevelObjectiveName', () => { - const result = client.matchServiceLevelObjectiveFromProjectServiceServiceLevelObjectiveName(fakePath); - assert.strictEqual(result, "serviceLevelObjectiveValue"); - assert((client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectServiceServiceLevelObjective', async () => { + const fakePath = '/rendered/path/projectServiceServiceLevelObjective'; + const expectedParameters = { + project: 'projectValue', + service: 'serviceValue', + service_level_objective: 'serviceLevelObjectiveValue', + }; + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('projectServiceServiceLevelObjectivePath', () => { + const result = client.projectServiceServiceLevelObjectivePath( + 'projectValue', + 'serviceValue', + 'serviceLevelObjectiveValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectServiceServiceLevelObjectiveName', () => { + const result = + client.matchProjectFromProjectServiceServiceLevelObjectiveName( + fakePath, + ); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServiceFromProjectServiceServiceLevelObjectiveName', () => { + const result = + client.matchServiceFromProjectServiceServiceLevelObjectiveName( + fakePath, + ); + assert.strictEqual(result, 'serviceValue'); + assert( + ( + client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServiceLevelObjectiveFromProjectServiceServiceLevelObjectiveName', () => { + const result = + client.matchServiceLevelObjectiveFromProjectServiceServiceLevelObjectiveName( + fakePath, + ); + assert.strictEqual(result, 'serviceLevelObjectiveValue'); + assert( + ( + client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectUptimeCheckConfig', async () => { - const fakePath = "/rendered/path/projectUptimeCheckConfig"; - const expectedParameters = { - project: "projectValue", - uptime_check_config: "uptimeCheckConfigValue", - }; - const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.projectUptimeCheckConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectUptimeCheckConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectUptimeCheckConfigPath', () => { - const result = client.projectUptimeCheckConfigPath("projectValue", "uptimeCheckConfigValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectUptimeCheckConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectUptimeCheckConfigName', () => { - const result = client.matchProjectFromProjectUptimeCheckConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectUptimeCheckConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchUptimeCheckConfigFromProjectUptimeCheckConfigName', () => { - const result = client.matchUptimeCheckConfigFromProjectUptimeCheckConfigName(fakePath); - assert.strictEqual(result, "uptimeCheckConfigValue"); - assert((client.pathTemplates.projectUptimeCheckConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectUptimeCheckConfig', async () => { + const fakePath = '/rendered/path/projectUptimeCheckConfig'; + const expectedParameters = { + project: 'projectValue', + uptime_check_config: 'uptimeCheckConfigValue', + }; + const client = + new notificationchannelserviceModule.v3.NotificationChannelServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + client.pathTemplates.projectUptimeCheckConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectUptimeCheckConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectUptimeCheckConfigPath', () => { + const result = client.projectUptimeCheckConfigPath( + 'projectValue', + 'uptimeCheckConfigValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.projectUptimeCheckConfigPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectUptimeCheckConfigName', () => { + const result = + client.matchProjectFromProjectUptimeCheckConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.projectUptimeCheckConfigPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchUptimeCheckConfigFromProjectUptimeCheckConfigName', () => { + const result = + client.matchUptimeCheckConfigFromProjectUptimeCheckConfigName( + fakePath, + ); + assert.strictEqual(result, 'uptimeCheckConfigValue'); + assert( + ( + client.pathTemplates.projectUptimeCheckConfigPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/core/generator/gapic-generator-typescript/baselines/monitoring/test/gapic_service_monitoring_service_v3.ts.baseline b/core/generator/gapic-generator-typescript/baselines/monitoring/test/gapic_service_monitoring_service_v3.ts.baseline index 27437ecc6284..f13b824a3e51 100644 --- a/core/generator/gapic-generator-typescript/baselines/monitoring/test/gapic_service_monitoring_service_v3.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/monitoring/test/gapic_service_monitoring_service_v3.ts.baseline @@ -19,2568 +19,3722 @@ import * as protos from '../protos/protos'; import * as assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as servicemonitoringserviceModule from '../src'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; -import {protobuf} from 'google-gax'; +import { protobuf } from 'google-gax'; // Dynamically loaded proto JSON is needed to get the type information // to fill in default values for request objects -const root = protobuf.Root.fromJSON(require('../protos/protos.json')).resolveAll(); +const root = protobuf.Root.fromJSON( + require('../protos/protos.json'), +).resolveAll(); // eslint-disable-next-line @typescript-eslint/no-unused-vars function getTypeDefaultValue(typeName: string, fields: string[]) { - let type = root.lookupType(typeName) as protobuf.Type; - for (const field of fields.slice(0, -1)) { - type = type.fields[field]?.resolvedType as protobuf.Type; - } - return type.fields[fields[fields.length - 1]]?.defaultValue; + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type.fields[field]?.resolvedType as protobuf.Type; + } + return type.fields[fields[fields.length - 1]]?.defaultValue; } function generateSampleMessage(instance: T) { - const filledObject = (instance.constructor as typeof protobuf.Message) - .toObject(instance as protobuf.Message, {defaults: true}); - return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, { defaults: true }); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; } function stubSimpleCall(response?: ResponseType, error?: Error) { - return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); } -function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { - return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +function stubSimpleCallWithCallback( + response?: ResponseType, + error?: Error, +) { + return error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); } -function stubPageStreamingCall(responses?: ResponseType[], error?: Error) { - const pagingStub = sinon.stub(); - if (responses) { - for (let i = 0; i < responses.length; ++i) { - pagingStub.onCall(i).callsArgWith(2, null, responses[i]); - } +function stubPageStreamingCall( + responses?: ResponseType[], + error?: Error, +) { + const pagingStub = sinon.stub(); + if (responses) { + for (let i = 0; i < responses.length; ++i) { + pagingStub.onCall(i).callsArgWith(2, null, responses[i]); } - const transformStub = error ? sinon.stub().callsArgWith(2, error) : pagingStub; - const mockStream = new PassThrough({ - objectMode: true, - transform: transformStub, - }); - // trigger as many responses as needed - if (responses) { - for (let i = 0; i < responses.length; ++i) { - setImmediate(() => { mockStream.write({}); }); - } - setImmediate(() => { mockStream.end(); }); - } else { - setImmediate(() => { mockStream.write({}); }); - setImmediate(() => { mockStream.end(); }); + } + const transformStub = error + ? sinon.stub().callsArgWith(2, error) + : pagingStub; + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + // trigger as many responses as needed + if (responses) { + for (let i = 0; i < responses.length; ++i) { + setImmediate(() => { + mockStream.write({}); + }); } - return sinon.stub().returns(mockStream); + setImmediate(() => { + mockStream.end(); + }); + } else { + setImmediate(() => { + mockStream.write({}); + }); + setImmediate(() => { + mockStream.end(); + }); + } + return sinon.stub().returns(mockStream); } -function stubAsyncIterationCall(responses?: ResponseType[], error?: Error) { - let counter = 0; - const asyncIterable = { - [Symbol.asyncIterator]() { - return { - async next() { - if (error) { - return Promise.reject(error); - } - if (counter >= responses!.length) { - return Promise.resolve({done: true, value: undefined}); - } - return Promise.resolve({done: false, value: responses![counter++]}); - } - }; - } - }; - return sinon.stub().returns(asyncIterable); +function stubAsyncIterationCall( + responses?: ResponseType[], + error?: Error, +) { + let counter = 0; + const asyncIterable = { + [Symbol.asyncIterator]() { + return { + async next() { + if (error) { + return Promise.reject(error); + } + if (counter >= responses!.length) { + return Promise.resolve({ done: true, value: undefined }); + } + return Promise.resolve({ done: false, value: responses![counter++] }); + }, + }; + }, + }; + return sinon.stub().returns(asyncIterable); } describe('v3.ServiceMonitoringServiceClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'monitoring.googleapis.com'); - }); - - it('has universeDomain', () => { - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); - - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - it('throws DeprecationWarning if static servicePath is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const servicePath = servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient.servicePath; - assert.strictEqual(servicePath, 'monitoring.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'monitoring.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'monitoring.example.com'); - }); - - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'monitoring.example.com'); - }); - - if (typeof process === 'object' && 'env' in process) { - describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { - it('sets apiEndpoint from environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'monitoring.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - - it('value configured in code has priority over environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'monitoring.configured.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); - - it('has port', () => { - const port = servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient.port; - assert(port); - assert(typeof port === 'number'); - }); - - it('should create a client with no option', () => { - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient(); - assert(client); - }); - - it('should create a client with gRPC fallback', () => { - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - fallback: true, - }); - assert(client); - }); - - it('has initialize method and supports deferred initialization', async () => { - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.serviceMonitoringServiceStub, undefined); - await client.initialize(); - assert(client.serviceMonitoringServiceStub); - }); - - it('has close method for the initialized client', done => { - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.serviceMonitoringServiceStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); - - it('has close method for the non-initialized client', done => { - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.serviceMonitoringServiceStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); - - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); - }); - - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId((err?: Error|null, projectId?: string|null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } - }); - }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); - }); - }); - - describe('createService', () => { - it('invokes createService without error', async () => { - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.CreateServiceRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.CreateServiceRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.monitoring.v3.Service() - ); - client.innerApiCalls.createService = stubSimpleCall(expectedResponse); - const [response] = await client.createService(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createService as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createService as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createService without error using callback', async () => { - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.CreateServiceRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.CreateServiceRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.monitoring.v3.Service() - ); - client.innerApiCalls.createService = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createService( - request, - (err?: Error|null, result?: protos.google.monitoring.v3.IService|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createService as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createService as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createService with error', async () => { - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.CreateServiceRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.CreateServiceRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createService = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createService(request), expectedError); - const actualRequest = (client.innerApiCalls.createService as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createService as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createService with closed client', async () => { - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.CreateServiceRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.CreateServiceRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createService(request), expectedError); - }); - }); - - describe('getService', () => { - it('invokes getService without error', async () => { - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.GetServiceRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.GetServiceRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.monitoring.v3.Service() - ); - client.innerApiCalls.getService = stubSimpleCall(expectedResponse); - const [response] = await client.getService(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getService as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getService as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getService without error using callback', async () => { - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.GetServiceRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.GetServiceRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.monitoring.v3.Service() - ); - client.innerApiCalls.getService = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getService( - request, - (err?: Error|null, result?: protos.google.monitoring.v3.IService|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getService as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getService as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getService with error', async () => { - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.GetServiceRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.GetServiceRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getService = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getService(request), expectedError); - const actualRequest = (client.innerApiCalls.getService as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getService as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getService with closed client', async () => { - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.GetServiceRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.GetServiceRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getService(request), expectedError); - }); - }); - - describe('updateService', () => { - it('invokes updateService without error', async () => { - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.UpdateServiceRequest() - ); - request.service ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.UpdateServiceRequest', ['service', 'name']); - request.service.name = defaultValue1; - const expectedHeaderRequestParams = `service.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.monitoring.v3.Service() - ); - client.innerApiCalls.updateService = stubSimpleCall(expectedResponse); - const [response] = await client.updateService(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateService as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateService as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateService without error using callback', async () => { - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.UpdateServiceRequest() - ); - request.service ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.UpdateServiceRequest', ['service', 'name']); - request.service.name = defaultValue1; - const expectedHeaderRequestParams = `service.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.monitoring.v3.Service() - ); - client.innerApiCalls.updateService = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateService( - request, - (err?: Error|null, result?: protos.google.monitoring.v3.IService|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateService as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateService as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateService with error', async () => { - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.UpdateServiceRequest() - ); - request.service ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.UpdateServiceRequest', ['service', 'name']); - request.service.name = defaultValue1; - const expectedHeaderRequestParams = `service.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateService = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateService(request), expectedError); - const actualRequest = (client.innerApiCalls.updateService as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateService as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateService with closed client', async () => { - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.UpdateServiceRequest() - ); - request.service ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.UpdateServiceRequest', ['service', 'name']); - request.service.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateService(request), expectedError); - }); - }); - - describe('deleteService', () => { - it('invokes deleteService without error', async () => { - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.DeleteServiceRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.DeleteServiceRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteService = stubSimpleCall(expectedResponse); - const [response] = await client.deleteService(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteService as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteService as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes deleteService without error using callback', async () => { - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.DeleteServiceRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.DeleteServiceRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteService = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteService( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteService as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteService as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes deleteService with error', async () => { - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.DeleteServiceRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.DeleteServiceRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteService = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteService(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteService as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteService as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes deleteService with closed client', async () => { - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.DeleteServiceRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.DeleteServiceRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteService(request), expectedError); - }); - }); - - describe('createServiceLevelObjective', () => { - it('invokes createServiceLevelObjective without error', async () => { - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.CreateServiceLevelObjectiveRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.CreateServiceLevelObjectiveRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.monitoring.v3.ServiceLevelObjective() - ); - client.innerApiCalls.createServiceLevelObjective = stubSimpleCall(expectedResponse); - const [response] = await client.createServiceLevelObjective(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createServiceLevelObjective as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createServiceLevelObjective as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createServiceLevelObjective without error using callback', async () => { - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.CreateServiceLevelObjectiveRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.CreateServiceLevelObjectiveRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.monitoring.v3.ServiceLevelObjective() - ); - client.innerApiCalls.createServiceLevelObjective = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createServiceLevelObjective( - request, - (err?: Error|null, result?: protos.google.monitoring.v3.IServiceLevelObjective|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createServiceLevelObjective as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createServiceLevelObjective as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createServiceLevelObjective with error', async () => { - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.CreateServiceLevelObjectiveRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.CreateServiceLevelObjectiveRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createServiceLevelObjective = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createServiceLevelObjective(request), expectedError); - const actualRequest = (client.innerApiCalls.createServiceLevelObjective as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createServiceLevelObjective as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createServiceLevelObjective with closed client', async () => { - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.CreateServiceLevelObjectiveRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.CreateServiceLevelObjectiveRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createServiceLevelObjective(request), expectedError); - }); - }); - - describe('getServiceLevelObjective', () => { - it('invokes getServiceLevelObjective without error', async () => { - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.GetServiceLevelObjectiveRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.GetServiceLevelObjectiveRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.monitoring.v3.ServiceLevelObjective() - ); - client.innerApiCalls.getServiceLevelObjective = stubSimpleCall(expectedResponse); - const [response] = await client.getServiceLevelObjective(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getServiceLevelObjective as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getServiceLevelObjective as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getServiceLevelObjective without error using callback', async () => { - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.GetServiceLevelObjectiveRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.GetServiceLevelObjectiveRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.monitoring.v3.ServiceLevelObjective() - ); - client.innerApiCalls.getServiceLevelObjective = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getServiceLevelObjective( - request, - (err?: Error|null, result?: protos.google.monitoring.v3.IServiceLevelObjective|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getServiceLevelObjective as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getServiceLevelObjective as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getServiceLevelObjective with error', async () => { - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.GetServiceLevelObjectiveRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.GetServiceLevelObjectiveRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getServiceLevelObjective = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getServiceLevelObjective(request), expectedError); - const actualRequest = (client.innerApiCalls.getServiceLevelObjective as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getServiceLevelObjective as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getServiceLevelObjective with closed client', async () => { - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.GetServiceLevelObjectiveRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.GetServiceLevelObjectiveRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getServiceLevelObjective(request), expectedError); - }); - }); - - describe('updateServiceLevelObjective', () => { - it('invokes updateServiceLevelObjective without error', async () => { - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.UpdateServiceLevelObjectiveRequest() - ); - request.serviceLevelObjective ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.UpdateServiceLevelObjectiveRequest', ['serviceLevelObjective', 'name']); - request.serviceLevelObjective.name = defaultValue1; - const expectedHeaderRequestParams = `service_level_objective.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.monitoring.v3.ServiceLevelObjective() - ); - client.innerApiCalls.updateServiceLevelObjective = stubSimpleCall(expectedResponse); - const [response] = await client.updateServiceLevelObjective(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateServiceLevelObjective as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateServiceLevelObjective as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateServiceLevelObjective without error using callback', async () => { - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.UpdateServiceLevelObjectiveRequest() - ); - request.serviceLevelObjective ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.UpdateServiceLevelObjectiveRequest', ['serviceLevelObjective', 'name']); - request.serviceLevelObjective.name = defaultValue1; - const expectedHeaderRequestParams = `service_level_objective.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.monitoring.v3.ServiceLevelObjective() - ); - client.innerApiCalls.updateServiceLevelObjective = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateServiceLevelObjective( - request, - (err?: Error|null, result?: protos.google.monitoring.v3.IServiceLevelObjective|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateServiceLevelObjective as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateServiceLevelObjective as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateServiceLevelObjective with error', async () => { - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.UpdateServiceLevelObjectiveRequest() - ); - request.serviceLevelObjective ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.UpdateServiceLevelObjectiveRequest', ['serviceLevelObjective', 'name']); - request.serviceLevelObjective.name = defaultValue1; - const expectedHeaderRequestParams = `service_level_objective.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateServiceLevelObjective = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateServiceLevelObjective(request), expectedError); - const actualRequest = (client.innerApiCalls.updateServiceLevelObjective as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateServiceLevelObjective as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateServiceLevelObjective with closed client', async () => { - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.UpdateServiceLevelObjectiveRequest() - ); - request.serviceLevelObjective ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.UpdateServiceLevelObjectiveRequest', ['serviceLevelObjective', 'name']); - request.serviceLevelObjective.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateServiceLevelObjective(request), expectedError); - }); - }); - - describe('deleteServiceLevelObjective', () => { - it('invokes deleteServiceLevelObjective without error', async () => { - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.DeleteServiceLevelObjectiveRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.DeleteServiceLevelObjectiveRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteServiceLevelObjective = stubSimpleCall(expectedResponse); - const [response] = await client.deleteServiceLevelObjective(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteServiceLevelObjective as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteServiceLevelObjective as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes deleteServiceLevelObjective without error using callback', async () => { - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.DeleteServiceLevelObjectiveRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.DeleteServiceLevelObjectiveRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteServiceLevelObjective = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteServiceLevelObjective( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteServiceLevelObjective as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteServiceLevelObjective as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes deleteServiceLevelObjective with error', async () => { - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.DeleteServiceLevelObjectiveRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.DeleteServiceLevelObjectiveRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteServiceLevelObjective = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteServiceLevelObjective(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteServiceLevelObjective as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteServiceLevelObjective as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes deleteServiceLevelObjective with closed client', async () => { - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.DeleteServiceLevelObjectiveRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.DeleteServiceLevelObjectiveRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteServiceLevelObjective(request), expectedError); - }); - }); - - describe('listServices', () => { - it('invokes listServices without error', async () => { - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListServicesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListServicesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.monitoring.v3.Service()), - generateSampleMessage(new protos.google.monitoring.v3.Service()), - generateSampleMessage(new protos.google.monitoring.v3.Service()), - ]; - client.innerApiCalls.listServices = stubSimpleCall(expectedResponse); - const [response] = await client.listServices(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listServices as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listServices as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listServices without error using callback', async () => { - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListServicesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListServicesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.monitoring.v3.Service()), - generateSampleMessage(new protos.google.monitoring.v3.Service()), - generateSampleMessage(new protos.google.monitoring.v3.Service()), - ]; - client.innerApiCalls.listServices = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listServices( - request, - (err?: Error|null, result?: protos.google.monitoring.v3.IService[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listServices as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listServices as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listServices with error', async () => { - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListServicesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListServicesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listServices = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listServices(request), expectedError); - const actualRequest = (client.innerApiCalls.listServices as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listServices as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listServicesStream without error', async () => { - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListServicesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListServicesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.monitoring.v3.Service()), - generateSampleMessage(new protos.google.monitoring.v3.Service()), - generateSampleMessage(new protos.google.monitoring.v3.Service()), - ]; - client.descriptors.page.listServices.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listServicesStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.monitoring.v3.Service[] = []; - stream.on('data', (response: protos.google.monitoring.v3.Service) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.listServices.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listServices, request)); - assert( - (client.descriptors.page.listServices.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'monitoring.googleapis.com'); + }); - it('invokes listServicesStream with error', async () => { - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListServicesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListServicesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listServices.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listServicesStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.monitoring.v3.Service[] = []; - stream.on('data', (response: protos.google.monitoring.v3.Service) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listServices.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listServices, request)); - assert( - (client.descriptors.page.listServices.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('has universeDomain', () => { + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - it('uses async iteration with listServices without error', async () => { - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListServicesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListServicesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.monitoring.v3.Service()), - generateSampleMessage(new protos.google.monitoring.v3.Service()), - generateSampleMessage(new protos.google.monitoring.v3.Service()), - ]; - client.descriptors.page.listServices.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.monitoring.v3.IService[] = []; - const iterable = client.listServicesAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listServices.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listServices.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = + servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient + .servicePath; + assert.strictEqual(servicePath, 'monitoring.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient + .apiEndpoint; + assert.strictEqual(apiEndpoint, 'monitoring.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + universeDomain: 'example.com', }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'monitoring.example.com'); + }); - it('uses async iteration with listServices with error', async () => { - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListServicesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListServicesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listServices.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listServicesAsync(request); - await assert.rejects(async () => { - const responses: protos.google.monitoring.v3.IService[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listServices.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listServices.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + universe_domain: 'example.com', }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'monitoring.example.com'); }); - describe('listServiceLevelObjectives', () => { - it('invokes listServiceLevelObjectives without error', async () => { - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListServiceLevelObjectivesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListServiceLevelObjectivesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.monitoring.v3.ServiceLevelObjective()), - generateSampleMessage(new protos.google.monitoring.v3.ServiceLevelObjective()), - generateSampleMessage(new protos.google.monitoring.v3.ServiceLevelObjective()), - ]; - client.innerApiCalls.listServiceLevelObjectives = stubSimpleCall(expectedResponse); - const [response] = await client.listServiceLevelObjectives(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listServiceLevelObjectives as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listServiceLevelObjectives as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listServiceLevelObjectives without error using callback', async () => { - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListServiceLevelObjectivesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListServiceLevelObjectivesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.monitoring.v3.ServiceLevelObjective()), - generateSampleMessage(new protos.google.monitoring.v3.ServiceLevelObjective()), - generateSampleMessage(new protos.google.monitoring.v3.ServiceLevelObjective()), - ]; - client.innerApiCalls.listServiceLevelObjectives = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listServiceLevelObjectives( - request, - (err?: Error|null, result?: protos.google.monitoring.v3.IServiceLevelObjective[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listServiceLevelObjectives as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listServiceLevelObjectives as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listServiceLevelObjectives with error', async () => { - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListServiceLevelObjectivesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListServiceLevelObjectivesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listServiceLevelObjectives = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listServiceLevelObjectives(request), expectedError); - const actualRequest = (client.innerApiCalls.listServiceLevelObjectives as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listServiceLevelObjectives as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listServiceLevelObjectivesStream without error', async () => { - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListServiceLevelObjectivesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListServiceLevelObjectivesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.monitoring.v3.ServiceLevelObjective()), - generateSampleMessage(new protos.google.monitoring.v3.ServiceLevelObjective()), - generateSampleMessage(new protos.google.monitoring.v3.ServiceLevelObjective()), - ]; - client.descriptors.page.listServiceLevelObjectives.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listServiceLevelObjectivesStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.monitoring.v3.ServiceLevelObjective[] = []; - stream.on('data', (response: protos.google.monitoring.v3.ServiceLevelObjective) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.listServiceLevelObjectives.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listServiceLevelObjectives, request)); - assert( - (client.descriptors.page.listServiceLevelObjectives.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); + if (typeof process === 'object' && 'env' in process) { + describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { + it('sets apiEndpoint from environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'monitoring.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } + }); + + it('value configured in code has priority over environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient( + { universeDomain: 'configured.example.com' }, + ); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'monitoring.configured.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } + }); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); + }); - it('invokes listServiceLevelObjectivesStream with error', async () => { - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListServiceLevelObjectivesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListServiceLevelObjectivesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listServiceLevelObjectives.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listServiceLevelObjectivesStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.monitoring.v3.ServiceLevelObjective[] = []; - stream.on('data', (response: protos.google.monitoring.v3.ServiceLevelObjective) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listServiceLevelObjectives.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listServiceLevelObjectives, request)); - assert( - (client.descriptors.page.listServiceLevelObjectives.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); + it('has port', () => { + const port = + servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient.port; + assert(port); + assert(typeof port === 'number'); + }); + + it('should create a client with no option', () => { + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient(); + assert(client); + }); + + it('should create a client with gRPC fallback', () => { + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + fallback: true, }); + assert(client); + }); - it('uses async iteration with listServiceLevelObjectives without error', async () => { - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListServiceLevelObjectivesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListServiceLevelObjectivesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.monitoring.v3.ServiceLevelObjective()), - generateSampleMessage(new protos.google.monitoring.v3.ServiceLevelObjective()), - generateSampleMessage(new protos.google.monitoring.v3.ServiceLevelObjective()), - ]; - client.descriptors.page.listServiceLevelObjectives.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.monitoring.v3.IServiceLevelObjective[] = []; - const iterable = client.listServiceLevelObjectivesAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listServiceLevelObjectives.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listServiceLevelObjectives.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); + it('has initialize method and supports deferred initialization', async () => { + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + assert.strictEqual(client.serviceMonitoringServiceStub, undefined); + await client.initialize(); + assert(client.serviceMonitoringServiceStub); + }); - it('uses async iteration with listServiceLevelObjectives with error', async () => { - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListServiceLevelObjectivesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListServiceLevelObjectivesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listServiceLevelObjectives.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listServiceLevelObjectivesAsync(request); - await assert.rejects(async () => { - const responses: protos.google.monitoring.v3.IServiceLevelObjective[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listServiceLevelObjectives.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listServiceLevelObjectives.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); + it('has close method for the initialized client', (done) => { + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.serviceMonitoringServiceStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); }); - describe('Path templates', () => { - - describe('folderAlertPolicy', async () => { - const fakePath = "/rendered/path/folderAlertPolicy"; - const expectedParameters = { - folder: "folderValue", - alert_policy: "alertPolicyValue", - }; - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.folderAlertPolicyPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderAlertPolicyPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderAlertPolicyPath', () => { - const result = client.folderAlertPolicyPath("folderValue", "alertPolicyValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderAlertPolicyPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderAlertPolicyName', () => { - const result = client.matchFolderFromFolderAlertPolicyName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderAlertPolicyPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchAlertPolicyFromFolderAlertPolicyName', () => { - const result = client.matchAlertPolicyFromFolderAlertPolicyName(fakePath); - assert.strictEqual(result, "alertPolicyValue"); - assert((client.pathTemplates.folderAlertPolicyPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('folderAlertPolicyCondition', async () => { - const fakePath = "/rendered/path/folderAlertPolicyCondition"; - const expectedParameters = { - folder: "folderValue", - alert_policy: "alertPolicyValue", - condition: "conditionValue", - }; - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.folderAlertPolicyConditionPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderAlertPolicyConditionPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderAlertPolicyConditionPath', () => { - const result = client.folderAlertPolicyConditionPath("folderValue", "alertPolicyValue", "conditionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderAlertPolicyConditionPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderAlertPolicyConditionName', () => { - const result = client.matchFolderFromFolderAlertPolicyConditionName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderAlertPolicyConditionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchAlertPolicyFromFolderAlertPolicyConditionName', () => { - const result = client.matchAlertPolicyFromFolderAlertPolicyConditionName(fakePath); - assert.strictEqual(result, "alertPolicyValue"); - assert((client.pathTemplates.folderAlertPolicyConditionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchConditionFromFolderAlertPolicyConditionName', () => { - const result = client.matchConditionFromFolderAlertPolicyConditionName(fakePath); - assert.strictEqual(result, "conditionValue"); - assert((client.pathTemplates.folderAlertPolicyConditionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('folderChannelDescriptor', async () => { - const fakePath = "/rendered/path/folderChannelDescriptor"; - const expectedParameters = { - folder: "folderValue", - channel_descriptor: "channelDescriptorValue", - }; - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.folderChannelDescriptorPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderChannelDescriptorPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderChannelDescriptorPath', () => { - const result = client.folderChannelDescriptorPath("folderValue", "channelDescriptorValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderChannelDescriptorPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderChannelDescriptorName', () => { - const result = client.matchFolderFromFolderChannelDescriptorName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderChannelDescriptorPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchChannelDescriptorFromFolderChannelDescriptorName', () => { - const result = client.matchChannelDescriptorFromFolderChannelDescriptorName(fakePath); - assert.strictEqual(result, "channelDescriptorValue"); - assert((client.pathTemplates.folderChannelDescriptorPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('folderGroup', async () => { - const fakePath = "/rendered/path/folderGroup"; - const expectedParameters = { - folder: "folderValue", - group: "groupValue", - }; - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.folderGroupPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderGroupPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderGroupPath', () => { - const result = client.folderGroupPath("folderValue", "groupValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderGroupPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderGroupName', () => { - const result = client.matchFolderFromFolderGroupName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderGroupPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchGroupFromFolderGroupName', () => { - const result = client.matchGroupFromFolderGroupName(fakePath); - assert.strictEqual(result, "groupValue"); - assert((client.pathTemplates.folderGroupPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('folderNotificationChannel', async () => { - const fakePath = "/rendered/path/folderNotificationChannel"; - const expectedParameters = { - folder: "folderValue", - notification_channel: "notificationChannelValue", - }; - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.folderNotificationChannelPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderNotificationChannelPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderNotificationChannelPath', () => { - const result = client.folderNotificationChannelPath("folderValue", "notificationChannelValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderNotificationChannelPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderNotificationChannelName', () => { - const result = client.matchFolderFromFolderNotificationChannelName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderNotificationChannelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchNotificationChannelFromFolderNotificationChannelName', () => { - const result = client.matchNotificationChannelFromFolderNotificationChannelName(fakePath); - assert.strictEqual(result, "notificationChannelValue"); - assert((client.pathTemplates.folderNotificationChannelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('folderService', async () => { - const fakePath = "/rendered/path/folderService"; - const expectedParameters = { - folder: "folderValue", - service: "serviceValue", - }; - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.folderServicePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderServicePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderServicePath', () => { - const result = client.folderServicePath("folderValue", "serviceValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderServicePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderServiceName', () => { - const result = client.matchFolderFromFolderServiceName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderServicePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServiceFromFolderServiceName', () => { - const result = client.matchServiceFromFolderServiceName(fakePath); - assert.strictEqual(result, "serviceValue"); - assert((client.pathTemplates.folderServicePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('folderServiceServiceLevelObjective', async () => { - const fakePath = "/rendered/path/folderServiceServiceLevelObjective"; - const expectedParameters = { - folder: "folderValue", - service: "serviceValue", - service_level_objective: "serviceLevelObjectiveValue", - }; - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderServiceServiceLevelObjectivePath', () => { - const result = client.folderServiceServiceLevelObjectivePath("folderValue", "serviceValue", "serviceLevelObjectiveValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderServiceServiceLevelObjectiveName', () => { - const result = client.matchFolderFromFolderServiceServiceLevelObjectiveName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServiceFromFolderServiceServiceLevelObjectiveName', () => { - const result = client.matchServiceFromFolderServiceServiceLevelObjectiveName(fakePath); - assert.strictEqual(result, "serviceValue"); - assert((client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServiceLevelObjectiveFromFolderServiceServiceLevelObjectiveName', () => { - const result = client.matchServiceLevelObjectiveFromFolderServiceServiceLevelObjectiveName(fakePath); - assert.strictEqual(result, "serviceLevelObjectiveValue"); - assert((client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('folderUptimeCheckConfig', async () => { - const fakePath = "/rendered/path/folderUptimeCheckConfig"; - const expectedParameters = { - folder: "folderValue", - uptime_check_config: "uptimeCheckConfigValue", - }; - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.folderUptimeCheckConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderUptimeCheckConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderUptimeCheckConfigPath', () => { - const result = client.folderUptimeCheckConfigPath("folderValue", "uptimeCheckConfigValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderUptimeCheckConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderUptimeCheckConfigName', () => { - const result = client.matchFolderFromFolderUptimeCheckConfigName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderUptimeCheckConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchUptimeCheckConfigFromFolderUptimeCheckConfigName', () => { - const result = client.matchUptimeCheckConfigFromFolderUptimeCheckConfigName(fakePath); - assert.strictEqual(result, "uptimeCheckConfigValue"); - assert((client.pathTemplates.folderUptimeCheckConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('organizationAlertPolicy', async () => { - const fakePath = "/rendered/path/organizationAlertPolicy"; - const expectedParameters = { - organization: "organizationValue", - alert_policy: "alertPolicyValue", - }; - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.organizationAlertPolicyPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationAlertPolicyPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationAlertPolicyPath', () => { - const result = client.organizationAlertPolicyPath("organizationValue", "alertPolicyValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationAlertPolicyPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationAlertPolicyName', () => { - const result = client.matchOrganizationFromOrganizationAlertPolicyName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationAlertPolicyPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchAlertPolicyFromOrganizationAlertPolicyName', () => { - const result = client.matchAlertPolicyFromOrganizationAlertPolicyName(fakePath); - assert.strictEqual(result, "alertPolicyValue"); - assert((client.pathTemplates.organizationAlertPolicyPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('organizationAlertPolicyCondition', async () => { - const fakePath = "/rendered/path/organizationAlertPolicyCondition"; - const expectedParameters = { - organization: "organizationValue", - alert_policy: "alertPolicyValue", - condition: "conditionValue", - }; - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.organizationAlertPolicyConditionPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationAlertPolicyConditionPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationAlertPolicyConditionPath', () => { - const result = client.organizationAlertPolicyConditionPath("organizationValue", "alertPolicyValue", "conditionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationAlertPolicyConditionPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationAlertPolicyConditionName', () => { - const result = client.matchOrganizationFromOrganizationAlertPolicyConditionName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationAlertPolicyConditionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchAlertPolicyFromOrganizationAlertPolicyConditionName', () => { - const result = client.matchAlertPolicyFromOrganizationAlertPolicyConditionName(fakePath); - assert.strictEqual(result, "alertPolicyValue"); - assert((client.pathTemplates.organizationAlertPolicyConditionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchConditionFromOrganizationAlertPolicyConditionName', () => { - const result = client.matchConditionFromOrganizationAlertPolicyConditionName(fakePath); - assert.strictEqual(result, "conditionValue"); - assert((client.pathTemplates.organizationAlertPolicyConditionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('organizationChannelDescriptor', async () => { - const fakePath = "/rendered/path/organizationChannelDescriptor"; - const expectedParameters = { - organization: "organizationValue", - channel_descriptor: "channelDescriptorValue", - }; - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.organizationChannelDescriptorPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationChannelDescriptorPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationChannelDescriptorPath', () => { - const result = client.organizationChannelDescriptorPath("organizationValue", "channelDescriptorValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationChannelDescriptorPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationChannelDescriptorName', () => { - const result = client.matchOrganizationFromOrganizationChannelDescriptorName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationChannelDescriptorPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchChannelDescriptorFromOrganizationChannelDescriptorName', () => { - const result = client.matchChannelDescriptorFromOrganizationChannelDescriptorName(fakePath); - assert.strictEqual(result, "channelDescriptorValue"); - assert((client.pathTemplates.organizationChannelDescriptorPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('organizationGroup', async () => { - const fakePath = "/rendered/path/organizationGroup"; - const expectedParameters = { - organization: "organizationValue", - group: "groupValue", - }; - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.organizationGroupPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationGroupPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationGroupPath', () => { - const result = client.organizationGroupPath("organizationValue", "groupValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationGroupPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationGroupName', () => { - const result = client.matchOrganizationFromOrganizationGroupName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationGroupPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchGroupFromOrganizationGroupName', () => { - const result = client.matchGroupFromOrganizationGroupName(fakePath); - assert.strictEqual(result, "groupValue"); - assert((client.pathTemplates.organizationGroupPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('organizationNotificationChannel', async () => { - const fakePath = "/rendered/path/organizationNotificationChannel"; - const expectedParameters = { - organization: "organizationValue", - notification_channel: "notificationChannelValue", - }; - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.organizationNotificationChannelPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationNotificationChannelPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationNotificationChannelPath', () => { - const result = client.organizationNotificationChannelPath("organizationValue", "notificationChannelValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationNotificationChannelPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationNotificationChannelName', () => { - const result = client.matchOrganizationFromOrganizationNotificationChannelName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationNotificationChannelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchNotificationChannelFromOrganizationNotificationChannelName', () => { - const result = client.matchNotificationChannelFromOrganizationNotificationChannelName(fakePath); - assert.strictEqual(result, "notificationChannelValue"); - assert((client.pathTemplates.organizationNotificationChannelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('organizationService', async () => { - const fakePath = "/rendered/path/organizationService"; - const expectedParameters = { - organization: "organizationValue", - service: "serviceValue", - }; - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.organizationServicePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationServicePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationServicePath', () => { - const result = client.organizationServicePath("organizationValue", "serviceValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationServicePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationServiceName', () => { - const result = client.matchOrganizationFromOrganizationServiceName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationServicePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServiceFromOrganizationServiceName', () => { - const result = client.matchServiceFromOrganizationServiceName(fakePath); - assert.strictEqual(result, "serviceValue"); - assert((client.pathTemplates.organizationServicePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('organizationServiceServiceLevelObjective', async () => { - const fakePath = "/rendered/path/organizationServiceServiceLevelObjective"; - const expectedParameters = { - organization: "organizationValue", - service: "serviceValue", - service_level_objective: "serviceLevelObjectiveValue", - }; - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationServiceServiceLevelObjectivePath', () => { - const result = client.organizationServiceServiceLevelObjectivePath("organizationValue", "serviceValue", "serviceLevelObjectiveValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationServiceServiceLevelObjectiveName', () => { - const result = client.matchOrganizationFromOrganizationServiceServiceLevelObjectiveName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServiceFromOrganizationServiceServiceLevelObjectiveName', () => { - const result = client.matchServiceFromOrganizationServiceServiceLevelObjectiveName(fakePath); - assert.strictEqual(result, "serviceValue"); - assert((client.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServiceLevelObjectiveFromOrganizationServiceServiceLevelObjectiveName', () => { - const result = client.matchServiceLevelObjectiveFromOrganizationServiceServiceLevelObjectiveName(fakePath); - assert.strictEqual(result, "serviceLevelObjectiveValue"); - assert((client.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('organizationUptimeCheckConfig', async () => { - const fakePath = "/rendered/path/organizationUptimeCheckConfig"; - const expectedParameters = { - organization: "organizationValue", - uptime_check_config: "uptimeCheckConfigValue", - }; - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.organizationUptimeCheckConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationUptimeCheckConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationUptimeCheckConfigPath', () => { - const result = client.organizationUptimeCheckConfigPath("organizationValue", "uptimeCheckConfigValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationUptimeCheckConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationUptimeCheckConfigName', () => { - const result = client.matchOrganizationFromOrganizationUptimeCheckConfigName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationUptimeCheckConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchUptimeCheckConfigFromOrganizationUptimeCheckConfigName', () => { - const result = client.matchUptimeCheckConfigFromOrganizationUptimeCheckConfigName(fakePath); - assert.strictEqual(result, "uptimeCheckConfigValue"); - assert((client.pathTemplates.organizationUptimeCheckConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('projectAlertPolicy', async () => { - const fakePath = "/rendered/path/projectAlertPolicy"; - const expectedParameters = { - project: "projectValue", - alert_policy: "alertPolicyValue", - }; - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.projectAlertPolicyPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectAlertPolicyPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectAlertPolicyPath', () => { - const result = client.projectAlertPolicyPath("projectValue", "alertPolicyValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectAlertPolicyPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectAlertPolicyName', () => { - const result = client.matchProjectFromProjectAlertPolicyName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectAlertPolicyPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchAlertPolicyFromProjectAlertPolicyName', () => { - const result = client.matchAlertPolicyFromProjectAlertPolicyName(fakePath); - assert.strictEqual(result, "alertPolicyValue"); - assert((client.pathTemplates.projectAlertPolicyPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('projectAlertPolicyCondition', async () => { - const fakePath = "/rendered/path/projectAlertPolicyCondition"; - const expectedParameters = { - project: "projectValue", - alert_policy: "alertPolicyValue", - condition: "conditionValue", - }; - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.projectAlertPolicyConditionPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectAlertPolicyConditionPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectAlertPolicyConditionPath', () => { - const result = client.projectAlertPolicyConditionPath("projectValue", "alertPolicyValue", "conditionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectAlertPolicyConditionPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectAlertPolicyConditionName', () => { - const result = client.matchProjectFromProjectAlertPolicyConditionName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectAlertPolicyConditionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchAlertPolicyFromProjectAlertPolicyConditionName', () => { - const result = client.matchAlertPolicyFromProjectAlertPolicyConditionName(fakePath); - assert.strictEqual(result, "alertPolicyValue"); - assert((client.pathTemplates.projectAlertPolicyConditionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchConditionFromProjectAlertPolicyConditionName', () => { - const result = client.matchConditionFromProjectAlertPolicyConditionName(fakePath); - assert.strictEqual(result, "conditionValue"); - assert((client.pathTemplates.projectAlertPolicyConditionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('projectChannelDescriptor', async () => { - const fakePath = "/rendered/path/projectChannelDescriptor"; - const expectedParameters = { - project: "projectValue", - channel_descriptor: "channelDescriptorValue", - }; - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.projectChannelDescriptorPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectChannelDescriptorPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectChannelDescriptorPath', () => { - const result = client.projectChannelDescriptorPath("projectValue", "channelDescriptorValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectChannelDescriptorPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectChannelDescriptorName', () => { - const result = client.matchProjectFromProjectChannelDescriptorName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectChannelDescriptorPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchChannelDescriptorFromProjectChannelDescriptorName', () => { - const result = client.matchChannelDescriptorFromProjectChannelDescriptorName(fakePath); - assert.strictEqual(result, "channelDescriptorValue"); - assert((client.pathTemplates.projectChannelDescriptorPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('projectGroup', async () => { - const fakePath = "/rendered/path/projectGroup"; - const expectedParameters = { - project: "projectValue", - group: "groupValue", - }; - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.projectGroupPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectGroupPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectGroupPath', () => { - const result = client.projectGroupPath("projectValue", "groupValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectGroupPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectGroupName', () => { - const result = client.matchProjectFromProjectGroupName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectGroupPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchGroupFromProjectGroupName', () => { - const result = client.matchGroupFromProjectGroupName(fakePath); - assert.strictEqual(result, "groupValue"); - assert((client.pathTemplates.projectGroupPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('projectNotificationChannel', async () => { - const fakePath = "/rendered/path/projectNotificationChannel"; - const expectedParameters = { - project: "projectValue", - notification_channel: "notificationChannelValue", - }; - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.projectNotificationChannelPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectNotificationChannelPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectNotificationChannelPath', () => { - const result = client.projectNotificationChannelPath("projectValue", "notificationChannelValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectNotificationChannelPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectNotificationChannelName', () => { - const result = client.matchProjectFromProjectNotificationChannelName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectNotificationChannelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchNotificationChannelFromProjectNotificationChannelName', () => { - const result = client.matchNotificationChannelFromProjectNotificationChannelName(fakePath); - assert.strictEqual(result, "notificationChannelValue"); - assert((client.pathTemplates.projectNotificationChannelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('projectService', async () => { - const fakePath = "/rendered/path/projectService"; - const expectedParameters = { - project: "projectValue", - service: "serviceValue", - }; - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.projectServicePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectServicePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectServicePath', () => { - const result = client.projectServicePath("projectValue", "serviceValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectServicePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectServiceName', () => { - const result = client.matchProjectFromProjectServiceName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectServicePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServiceFromProjectServiceName', () => { - const result = client.matchServiceFromProjectServiceName(fakePath); - assert.strictEqual(result, "serviceValue"); - assert((client.pathTemplates.projectServicePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('projectServiceServiceLevelObjective', async () => { - const fakePath = "/rendered/path/projectServiceServiceLevelObjective"; - const expectedParameters = { - project: "projectValue", - service: "serviceValue", - service_level_objective: "serviceLevelObjectiveValue", - }; - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectServiceServiceLevelObjectivePath', () => { - const result = client.projectServiceServiceLevelObjectivePath("projectValue", "serviceValue", "serviceLevelObjectiveValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectServiceServiceLevelObjectiveName', () => { - const result = client.matchProjectFromProjectServiceServiceLevelObjectiveName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServiceFromProjectServiceServiceLevelObjectiveName', () => { - const result = client.matchServiceFromProjectServiceServiceLevelObjectiveName(fakePath); - assert.strictEqual(result, "serviceValue"); - assert((client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServiceLevelObjectiveFromProjectServiceServiceLevelObjectiveName', () => { - const result = client.matchServiceLevelObjectiveFromProjectServiceServiceLevelObjectiveName(fakePath); - assert.strictEqual(result, "serviceLevelObjectiveValue"); - assert((client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('projectUptimeCheckConfig', async () => { - const fakePath = "/rendered/path/projectUptimeCheckConfig"; - const expectedParameters = { - project: "projectValue", - uptime_check_config: "uptimeCheckConfigValue", - }; - const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.projectUptimeCheckConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectUptimeCheckConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectUptimeCheckConfigPath', () => { - const result = client.projectUptimeCheckConfigPath("projectValue", "uptimeCheckConfigValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectUptimeCheckConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectUptimeCheckConfigName', () => { - const result = client.matchProjectFromProjectUptimeCheckConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectUptimeCheckConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchUptimeCheckConfigFromProjectUptimeCheckConfigName', () => { - const result = client.matchUptimeCheckConfigFromProjectUptimeCheckConfigName(fakePath); - assert.strictEqual(result, "uptimeCheckConfigValue"); - assert((client.pathTemplates.projectUptimeCheckConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('has close method for the non-initialized client', (done) => { + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.serviceMonitoringServiceStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); }); + + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + }); + + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } + }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + }); + + describe('createService', () => { + it('invokes createService without error', async () => { + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.CreateServiceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.CreateServiceRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.monitoring.v3.Service(), + ); + client.innerApiCalls.createService = stubSimpleCall(expectedResponse); + const [response] = await client.createService(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createService as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createService as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createService without error using callback', async () => { + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.CreateServiceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.CreateServiceRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.monitoring.v3.Service(), + ); + client.innerApiCalls.createService = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createService( + request, + ( + err?: Error | null, + result?: protos.google.monitoring.v3.IService | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createService as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createService as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createService with error', async () => { + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.CreateServiceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.CreateServiceRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createService = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.createService(request), expectedError); + const actualRequest = ( + client.innerApiCalls.createService as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createService as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createService with closed client', async () => { + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.CreateServiceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.CreateServiceRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.createService(request), expectedError); + }); + }); + + describe('getService', () => { + it('invokes getService without error', async () => { + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.GetServiceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.GetServiceRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.monitoring.v3.Service(), + ); + client.innerApiCalls.getService = stubSimpleCall(expectedResponse); + const [response] = await client.getService(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getService as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getService as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getService without error using callback', async () => { + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.GetServiceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.GetServiceRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.monitoring.v3.Service(), + ); + client.innerApiCalls.getService = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getService( + request, + ( + err?: Error | null, + result?: protos.google.monitoring.v3.IService | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getService as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getService as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getService with error', async () => { + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.GetServiceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.GetServiceRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getService = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getService(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getService as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getService as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getService with closed client', async () => { + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.GetServiceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.GetServiceRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getService(request), expectedError); + }); + }); + + describe('updateService', () => { + it('invokes updateService without error', async () => { + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.UpdateServiceRequest(), + ); + request.service ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.UpdateServiceRequest', + ['service', 'name'], + ); + request.service.name = defaultValue1; + const expectedHeaderRequestParams = `service.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.monitoring.v3.Service(), + ); + client.innerApiCalls.updateService = stubSimpleCall(expectedResponse); + const [response] = await client.updateService(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateService as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateService as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateService without error using callback', async () => { + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.UpdateServiceRequest(), + ); + request.service ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.UpdateServiceRequest', + ['service', 'name'], + ); + request.service.name = defaultValue1; + const expectedHeaderRequestParams = `service.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.monitoring.v3.Service(), + ); + client.innerApiCalls.updateService = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateService( + request, + ( + err?: Error | null, + result?: protos.google.monitoring.v3.IService | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateService as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateService as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateService with error', async () => { + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.UpdateServiceRequest(), + ); + request.service ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.UpdateServiceRequest', + ['service', 'name'], + ); + request.service.name = defaultValue1; + const expectedHeaderRequestParams = `service.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateService = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.updateService(request), expectedError); + const actualRequest = ( + client.innerApiCalls.updateService as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateService as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateService with closed client', async () => { + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.UpdateServiceRequest(), + ); + request.service ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.UpdateServiceRequest', + ['service', 'name'], + ); + request.service.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.updateService(request), expectedError); + }); + }); + + describe('deleteService', () => { + it('invokes deleteService without error', async () => { + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.DeleteServiceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.DeleteServiceRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteService = stubSimpleCall(expectedResponse); + const [response] = await client.deleteService(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteService as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteService as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteService without error using callback', async () => { + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.DeleteServiceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.DeleteServiceRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteService = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteService( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteService as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteService as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteService with error', async () => { + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.DeleteServiceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.DeleteServiceRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteService = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.deleteService(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteService as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteService as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteService with closed client', async () => { + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.DeleteServiceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.DeleteServiceRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.deleteService(request), expectedError); + }); + }); + + describe('createServiceLevelObjective', () => { + it('invokes createServiceLevelObjective without error', async () => { + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.CreateServiceLevelObjectiveRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.CreateServiceLevelObjectiveRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.monitoring.v3.ServiceLevelObjective(), + ); + client.innerApiCalls.createServiceLevelObjective = + stubSimpleCall(expectedResponse); + const [response] = await client.createServiceLevelObjective(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createServiceLevelObjective as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createServiceLevelObjective as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createServiceLevelObjective without error using callback', async () => { + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.CreateServiceLevelObjectiveRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.CreateServiceLevelObjectiveRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.monitoring.v3.ServiceLevelObjective(), + ); + client.innerApiCalls.createServiceLevelObjective = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createServiceLevelObjective( + request, + ( + err?: Error | null, + result?: protos.google.monitoring.v3.IServiceLevelObjective | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createServiceLevelObjective as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createServiceLevelObjective as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createServiceLevelObjective with error', async () => { + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.CreateServiceLevelObjectiveRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.CreateServiceLevelObjectiveRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createServiceLevelObjective = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.createServiceLevelObjective(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.createServiceLevelObjective as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createServiceLevelObjective as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createServiceLevelObjective with closed client', async () => { + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.CreateServiceLevelObjectiveRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.CreateServiceLevelObjectiveRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.createServiceLevelObjective(request), + expectedError, + ); + }); + }); + + describe('getServiceLevelObjective', () => { + it('invokes getServiceLevelObjective without error', async () => { + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.GetServiceLevelObjectiveRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.GetServiceLevelObjectiveRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.monitoring.v3.ServiceLevelObjective(), + ); + client.innerApiCalls.getServiceLevelObjective = + stubSimpleCall(expectedResponse); + const [response] = await client.getServiceLevelObjective(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getServiceLevelObjective as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getServiceLevelObjective as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getServiceLevelObjective without error using callback', async () => { + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.GetServiceLevelObjectiveRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.GetServiceLevelObjectiveRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.monitoring.v3.ServiceLevelObjective(), + ); + client.innerApiCalls.getServiceLevelObjective = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getServiceLevelObjective( + request, + ( + err?: Error | null, + result?: protos.google.monitoring.v3.IServiceLevelObjective | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getServiceLevelObjective as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getServiceLevelObjective as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getServiceLevelObjective with error', async () => { + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.GetServiceLevelObjectiveRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.GetServiceLevelObjectiveRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getServiceLevelObjective = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.getServiceLevelObjective(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.getServiceLevelObjective as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getServiceLevelObjective as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getServiceLevelObjective with closed client', async () => { + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.GetServiceLevelObjectiveRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.GetServiceLevelObjectiveRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.getServiceLevelObjective(request), + expectedError, + ); + }); + }); + + describe('updateServiceLevelObjective', () => { + it('invokes updateServiceLevelObjective without error', async () => { + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.UpdateServiceLevelObjectiveRequest(), + ); + request.serviceLevelObjective ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.UpdateServiceLevelObjectiveRequest', + ['serviceLevelObjective', 'name'], + ); + request.serviceLevelObjective.name = defaultValue1; + const expectedHeaderRequestParams = `service_level_objective.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.monitoring.v3.ServiceLevelObjective(), + ); + client.innerApiCalls.updateServiceLevelObjective = + stubSimpleCall(expectedResponse); + const [response] = await client.updateServiceLevelObjective(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateServiceLevelObjective as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateServiceLevelObjective as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateServiceLevelObjective without error using callback', async () => { + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.UpdateServiceLevelObjectiveRequest(), + ); + request.serviceLevelObjective ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.UpdateServiceLevelObjectiveRequest', + ['serviceLevelObjective', 'name'], + ); + request.serviceLevelObjective.name = defaultValue1; + const expectedHeaderRequestParams = `service_level_objective.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.monitoring.v3.ServiceLevelObjective(), + ); + client.innerApiCalls.updateServiceLevelObjective = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateServiceLevelObjective( + request, + ( + err?: Error | null, + result?: protos.google.monitoring.v3.IServiceLevelObjective | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateServiceLevelObjective as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateServiceLevelObjective as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateServiceLevelObjective with error', async () => { + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.UpdateServiceLevelObjectiveRequest(), + ); + request.serviceLevelObjective ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.UpdateServiceLevelObjectiveRequest', + ['serviceLevelObjective', 'name'], + ); + request.serviceLevelObjective.name = defaultValue1; + const expectedHeaderRequestParams = `service_level_objective.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateServiceLevelObjective = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.updateServiceLevelObjective(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.updateServiceLevelObjective as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateServiceLevelObjective as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateServiceLevelObjective with closed client', async () => { + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.UpdateServiceLevelObjectiveRequest(), + ); + request.serviceLevelObjective ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.UpdateServiceLevelObjectiveRequest', + ['serviceLevelObjective', 'name'], + ); + request.serviceLevelObjective.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.updateServiceLevelObjective(request), + expectedError, + ); + }); + }); + + describe('deleteServiceLevelObjective', () => { + it('invokes deleteServiceLevelObjective without error', async () => { + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.DeleteServiceLevelObjectiveRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.DeleteServiceLevelObjectiveRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteServiceLevelObjective = + stubSimpleCall(expectedResponse); + const [response] = await client.deleteServiceLevelObjective(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteServiceLevelObjective as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteServiceLevelObjective as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteServiceLevelObjective without error using callback', async () => { + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.DeleteServiceLevelObjectiveRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.DeleteServiceLevelObjectiveRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteServiceLevelObjective = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteServiceLevelObjective( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteServiceLevelObjective as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteServiceLevelObjective as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteServiceLevelObjective with error', async () => { + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.DeleteServiceLevelObjectiveRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.DeleteServiceLevelObjectiveRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteServiceLevelObjective = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.deleteServiceLevelObjective(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.deleteServiceLevelObjective as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteServiceLevelObjective as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteServiceLevelObjective with closed client', async () => { + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.DeleteServiceLevelObjectiveRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.DeleteServiceLevelObjectiveRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.deleteServiceLevelObjective(request), + expectedError, + ); + }); + }); + + describe('listServices', () => { + it('invokes listServices without error', async () => { + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListServicesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListServicesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.monitoring.v3.Service()), + generateSampleMessage(new protos.google.monitoring.v3.Service()), + generateSampleMessage(new protos.google.monitoring.v3.Service()), + ]; + client.innerApiCalls.listServices = stubSimpleCall(expectedResponse); + const [response] = await client.listServices(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listServices as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listServices as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listServices without error using callback', async () => { + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListServicesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListServicesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.monitoring.v3.Service()), + generateSampleMessage(new protos.google.monitoring.v3.Service()), + generateSampleMessage(new protos.google.monitoring.v3.Service()), + ]; + client.innerApiCalls.listServices = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listServices( + request, + ( + err?: Error | null, + result?: protos.google.monitoring.v3.IService[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listServices as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listServices as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listServices with error', async () => { + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListServicesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListServicesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listServices = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listServices(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listServices as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listServices as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listServicesStream without error', async () => { + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListServicesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListServicesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.monitoring.v3.Service()), + generateSampleMessage(new protos.google.monitoring.v3.Service()), + generateSampleMessage(new protos.google.monitoring.v3.Service()), + ]; + client.descriptors.page.listServices.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listServicesStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.monitoring.v3.Service[] = []; + stream.on('data', (response: protos.google.monitoring.v3.Service) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listServices.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listServices, request), + ); + assert( + (client.descriptors.page.listServices.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + + it('invokes listServicesStream with error', async () => { + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListServicesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListServicesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listServices.createStream = stubPageStreamingCall( + undefined, + expectedError, + ); + const stream = client.listServicesStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.monitoring.v3.Service[] = []; + stream.on('data', (response: protos.google.monitoring.v3.Service) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listServices.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listServices, request), + ); + assert( + (client.descriptors.page.listServices.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + + it('uses async iteration with listServices without error', async () => { + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListServicesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListServicesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.monitoring.v3.Service()), + generateSampleMessage(new protos.google.monitoring.v3.Service()), + generateSampleMessage(new protos.google.monitoring.v3.Service()), + ]; + client.descriptors.page.listServices.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.monitoring.v3.IService[] = []; + const iterable = client.listServicesAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listServices.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listServices.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + + it('uses async iteration with listServices with error', async () => { + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListServicesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListServicesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listServices.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listServicesAsync(request); + await assert.rejects(async () => { + const responses: protos.google.monitoring.v3.IService[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listServices.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listServices.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + }); + + describe('listServiceLevelObjectives', () => { + it('invokes listServiceLevelObjectives without error', async () => { + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListServiceLevelObjectivesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListServiceLevelObjectivesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.monitoring.v3.ServiceLevelObjective(), + ), + generateSampleMessage( + new protos.google.monitoring.v3.ServiceLevelObjective(), + ), + generateSampleMessage( + new protos.google.monitoring.v3.ServiceLevelObjective(), + ), + ]; + client.innerApiCalls.listServiceLevelObjectives = + stubSimpleCall(expectedResponse); + const [response] = await client.listServiceLevelObjectives(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listServiceLevelObjectives as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listServiceLevelObjectives as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listServiceLevelObjectives without error using callback', async () => { + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListServiceLevelObjectivesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListServiceLevelObjectivesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.monitoring.v3.ServiceLevelObjective(), + ), + generateSampleMessage( + new protos.google.monitoring.v3.ServiceLevelObjective(), + ), + generateSampleMessage( + new protos.google.monitoring.v3.ServiceLevelObjective(), + ), + ]; + client.innerApiCalls.listServiceLevelObjectives = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listServiceLevelObjectives( + request, + ( + err?: Error | null, + result?: + | protos.google.monitoring.v3.IServiceLevelObjective[] + | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listServiceLevelObjectives as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listServiceLevelObjectives as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listServiceLevelObjectives with error', async () => { + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListServiceLevelObjectivesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListServiceLevelObjectivesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listServiceLevelObjectives = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.listServiceLevelObjectives(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.listServiceLevelObjectives as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listServiceLevelObjectives as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listServiceLevelObjectivesStream without error', async () => { + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListServiceLevelObjectivesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListServiceLevelObjectivesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.monitoring.v3.ServiceLevelObjective(), + ), + generateSampleMessage( + new protos.google.monitoring.v3.ServiceLevelObjective(), + ), + generateSampleMessage( + new protos.google.monitoring.v3.ServiceLevelObjective(), + ), + ]; + client.descriptors.page.listServiceLevelObjectives.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listServiceLevelObjectivesStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.monitoring.v3.ServiceLevelObjective[] = + []; + stream.on( + 'data', + (response: protos.google.monitoring.v3.ServiceLevelObjective) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + ( + client.descriptors.page.listServiceLevelObjectives + .createStream as SinonStub + ) + .getCall(0) + .calledWith(client.innerApiCalls.listServiceLevelObjectives, request), + ); + assert( + ( + client.descriptors.page.listServiceLevelObjectives + .createStream as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); + + it('invokes listServiceLevelObjectivesStream with error', async () => { + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListServiceLevelObjectivesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListServiceLevelObjectivesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listServiceLevelObjectives.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listServiceLevelObjectivesStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.monitoring.v3.ServiceLevelObjective[] = + []; + stream.on( + 'data', + (response: protos.google.monitoring.v3.ServiceLevelObjective) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + ( + client.descriptors.page.listServiceLevelObjectives + .createStream as SinonStub + ) + .getCall(0) + .calledWith(client.innerApiCalls.listServiceLevelObjectives, request), + ); + assert( + ( + client.descriptors.page.listServiceLevelObjectives + .createStream as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); + + it('uses async iteration with listServiceLevelObjectives without error', async () => { + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListServiceLevelObjectivesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListServiceLevelObjectivesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.monitoring.v3.ServiceLevelObjective(), + ), + generateSampleMessage( + new protos.google.monitoring.v3.ServiceLevelObjective(), + ), + generateSampleMessage( + new protos.google.monitoring.v3.ServiceLevelObjective(), + ), + ]; + client.descriptors.page.listServiceLevelObjectives.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.monitoring.v3.IServiceLevelObjective[] = + []; + const iterable = client.listServiceLevelObjectivesAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listServiceLevelObjectives + .asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + ( + client.descriptors.page.listServiceLevelObjectives + .asyncIterate as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); + + it('uses async iteration with listServiceLevelObjectives with error', async () => { + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListServiceLevelObjectivesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListServiceLevelObjectivesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listServiceLevelObjectives.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listServiceLevelObjectivesAsync(request); + await assert.rejects(async () => { + const responses: protos.google.monitoring.v3.IServiceLevelObjective[] = + []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listServiceLevelObjectives + .asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + ( + client.descriptors.page.listServiceLevelObjectives + .asyncIterate as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); + }); + + describe('Path templates', () => { + describe('folderAlertPolicy', async () => { + const fakePath = '/rendered/path/folderAlertPolicy'; + const expectedParameters = { + folder: 'folderValue', + alert_policy: 'alertPolicyValue', + }; + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.folderAlertPolicyPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderAlertPolicyPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderAlertPolicyPath', () => { + const result = client.folderAlertPolicyPath( + 'folderValue', + 'alertPolicyValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.folderAlertPolicyPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderAlertPolicyName', () => { + const result = client.matchFolderFromFolderAlertPolicyName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + ( + client.pathTemplates.folderAlertPolicyPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchAlertPolicyFromFolderAlertPolicyName', () => { + const result = + client.matchAlertPolicyFromFolderAlertPolicyName(fakePath); + assert.strictEqual(result, 'alertPolicyValue'); + assert( + ( + client.pathTemplates.folderAlertPolicyPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); + + describe('folderAlertPolicyCondition', async () => { + const fakePath = '/rendered/path/folderAlertPolicyCondition'; + const expectedParameters = { + folder: 'folderValue', + alert_policy: 'alertPolicyValue', + condition: 'conditionValue', + }; + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.folderAlertPolicyConditionPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderAlertPolicyConditionPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderAlertPolicyConditionPath', () => { + const result = client.folderAlertPolicyConditionPath( + 'folderValue', + 'alertPolicyValue', + 'conditionValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.folderAlertPolicyConditionPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderAlertPolicyConditionName', () => { + const result = + client.matchFolderFromFolderAlertPolicyConditionName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + ( + client.pathTemplates.folderAlertPolicyConditionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchAlertPolicyFromFolderAlertPolicyConditionName', () => { + const result = + client.matchAlertPolicyFromFolderAlertPolicyConditionName(fakePath); + assert.strictEqual(result, 'alertPolicyValue'); + assert( + ( + client.pathTemplates.folderAlertPolicyConditionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchConditionFromFolderAlertPolicyConditionName', () => { + const result = + client.matchConditionFromFolderAlertPolicyConditionName(fakePath); + assert.strictEqual(result, 'conditionValue'); + assert( + ( + client.pathTemplates.folderAlertPolicyConditionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); + + describe('folderChannelDescriptor', async () => { + const fakePath = '/rendered/path/folderChannelDescriptor'; + const expectedParameters = { + folder: 'folderValue', + channel_descriptor: 'channelDescriptorValue', + }; + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.folderChannelDescriptorPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderChannelDescriptorPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderChannelDescriptorPath', () => { + const result = client.folderChannelDescriptorPath( + 'folderValue', + 'channelDescriptorValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.folderChannelDescriptorPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderChannelDescriptorName', () => { + const result = + client.matchFolderFromFolderChannelDescriptorName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + ( + client.pathTemplates.folderChannelDescriptorPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchChannelDescriptorFromFolderChannelDescriptorName', () => { + const result = + client.matchChannelDescriptorFromFolderChannelDescriptorName( + fakePath, + ); + assert.strictEqual(result, 'channelDescriptorValue'); + assert( + ( + client.pathTemplates.folderChannelDescriptorPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); + + describe('folderGroup', async () => { + const fakePath = '/rendered/path/folderGroup'; + const expectedParameters = { + folder: 'folderValue', + group: 'groupValue', + }; + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.folderGroupPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderGroupPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderGroupPath', () => { + const result = client.folderGroupPath('folderValue', 'groupValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.folderGroupPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderGroupName', () => { + const result = client.matchFolderFromFolderGroupName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + (client.pathTemplates.folderGroupPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchGroupFromFolderGroupName', () => { + const result = client.matchGroupFromFolderGroupName(fakePath); + assert.strictEqual(result, 'groupValue'); + assert( + (client.pathTemplates.folderGroupPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); + + describe('folderNotificationChannel', async () => { + const fakePath = '/rendered/path/folderNotificationChannel'; + const expectedParameters = { + folder: 'folderValue', + notification_channel: 'notificationChannelValue', + }; + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.folderNotificationChannelPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderNotificationChannelPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderNotificationChannelPath', () => { + const result = client.folderNotificationChannelPath( + 'folderValue', + 'notificationChannelValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.folderNotificationChannelPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderNotificationChannelName', () => { + const result = + client.matchFolderFromFolderNotificationChannelName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + ( + client.pathTemplates.folderNotificationChannelPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchNotificationChannelFromFolderNotificationChannelName', () => { + const result = + client.matchNotificationChannelFromFolderNotificationChannelName( + fakePath, + ); + assert.strictEqual(result, 'notificationChannelValue'); + assert( + ( + client.pathTemplates.folderNotificationChannelPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); + + describe('folderService', async () => { + const fakePath = '/rendered/path/folderService'; + const expectedParameters = { + folder: 'folderValue', + service: 'serviceValue', + }; + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.folderServicePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderServicePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderServicePath', () => { + const result = client.folderServicePath('folderValue', 'serviceValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.folderServicePathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderServiceName', () => { + const result = client.matchFolderFromFolderServiceName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + (client.pathTemplates.folderServicePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServiceFromFolderServiceName', () => { + const result = client.matchServiceFromFolderServiceName(fakePath); + assert.strictEqual(result, 'serviceValue'); + assert( + (client.pathTemplates.folderServicePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); + + describe('folderServiceServiceLevelObjective', async () => { + const fakePath = '/rendered/path/folderServiceServiceLevelObjective'; + const expectedParameters = { + folder: 'folderValue', + service: 'serviceValue', + service_level_objective: 'serviceLevelObjectiveValue', + }; + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('folderServiceServiceLevelObjectivePath', () => { + const result = client.folderServiceServiceLevelObjectivePath( + 'folderValue', + 'serviceValue', + 'serviceLevelObjectiveValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderServiceServiceLevelObjectiveName', () => { + const result = + client.matchFolderFromFolderServiceServiceLevelObjectiveName( + fakePath, + ); + assert.strictEqual(result, 'folderValue'); + assert( + ( + client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServiceFromFolderServiceServiceLevelObjectiveName', () => { + const result = + client.matchServiceFromFolderServiceServiceLevelObjectiveName( + fakePath, + ); + assert.strictEqual(result, 'serviceValue'); + assert( + ( + client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServiceLevelObjectiveFromFolderServiceServiceLevelObjectiveName', () => { + const result = + client.matchServiceLevelObjectiveFromFolderServiceServiceLevelObjectiveName( + fakePath, + ); + assert.strictEqual(result, 'serviceLevelObjectiveValue'); + assert( + ( + client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); + + describe('folderUptimeCheckConfig', async () => { + const fakePath = '/rendered/path/folderUptimeCheckConfig'; + const expectedParameters = { + folder: 'folderValue', + uptime_check_config: 'uptimeCheckConfigValue', + }; + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.folderUptimeCheckConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderUptimeCheckConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderUptimeCheckConfigPath', () => { + const result = client.folderUptimeCheckConfigPath( + 'folderValue', + 'uptimeCheckConfigValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.folderUptimeCheckConfigPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderUptimeCheckConfigName', () => { + const result = + client.matchFolderFromFolderUptimeCheckConfigName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + ( + client.pathTemplates.folderUptimeCheckConfigPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchUptimeCheckConfigFromFolderUptimeCheckConfigName', () => { + const result = + client.matchUptimeCheckConfigFromFolderUptimeCheckConfigName( + fakePath, + ); + assert.strictEqual(result, 'uptimeCheckConfigValue'); + assert( + ( + client.pathTemplates.folderUptimeCheckConfigPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); + + describe('organizationAlertPolicy', async () => { + const fakePath = '/rendered/path/organizationAlertPolicy'; + const expectedParameters = { + organization: 'organizationValue', + alert_policy: 'alertPolicyValue', + }; + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.organizationAlertPolicyPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.organizationAlertPolicyPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('organizationAlertPolicyPath', () => { + const result = client.organizationAlertPolicyPath( + 'organizationValue', + 'alertPolicyValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationAlertPolicyPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationAlertPolicyName', () => { + const result = + client.matchOrganizationFromOrganizationAlertPolicyName(fakePath); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationAlertPolicyPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchAlertPolicyFromOrganizationAlertPolicyName', () => { + const result = + client.matchAlertPolicyFromOrganizationAlertPolicyName(fakePath); + assert.strictEqual(result, 'alertPolicyValue'); + assert( + ( + client.pathTemplates.organizationAlertPolicyPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); + + describe('organizationAlertPolicyCondition', async () => { + const fakePath = '/rendered/path/organizationAlertPolicyCondition'; + const expectedParameters = { + organization: 'organizationValue', + alert_policy: 'alertPolicyValue', + condition: 'conditionValue', + }; + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.organizationAlertPolicyConditionPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.organizationAlertPolicyConditionPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('organizationAlertPolicyConditionPath', () => { + const result = client.organizationAlertPolicyConditionPath( + 'organizationValue', + 'alertPolicyValue', + 'conditionValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationAlertPolicyConditionPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationAlertPolicyConditionName', () => { + const result = + client.matchOrganizationFromOrganizationAlertPolicyConditionName( + fakePath, + ); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationAlertPolicyConditionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchAlertPolicyFromOrganizationAlertPolicyConditionName', () => { + const result = + client.matchAlertPolicyFromOrganizationAlertPolicyConditionName( + fakePath, + ); + assert.strictEqual(result, 'alertPolicyValue'); + assert( + ( + client.pathTemplates.organizationAlertPolicyConditionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchConditionFromOrganizationAlertPolicyConditionName', () => { + const result = + client.matchConditionFromOrganizationAlertPolicyConditionName( + fakePath, + ); + assert.strictEqual(result, 'conditionValue'); + assert( + ( + client.pathTemplates.organizationAlertPolicyConditionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); + + describe('organizationChannelDescriptor', async () => { + const fakePath = '/rendered/path/organizationChannelDescriptor'; + const expectedParameters = { + organization: 'organizationValue', + channel_descriptor: 'channelDescriptorValue', + }; + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.organizationChannelDescriptorPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.organizationChannelDescriptorPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('organizationChannelDescriptorPath', () => { + const result = client.organizationChannelDescriptorPath( + 'organizationValue', + 'channelDescriptorValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationChannelDescriptorPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationChannelDescriptorName', () => { + const result = + client.matchOrganizationFromOrganizationChannelDescriptorName( + fakePath, + ); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationChannelDescriptorPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchChannelDescriptorFromOrganizationChannelDescriptorName', () => { + const result = + client.matchChannelDescriptorFromOrganizationChannelDescriptorName( + fakePath, + ); + assert.strictEqual(result, 'channelDescriptorValue'); + assert( + ( + client.pathTemplates.organizationChannelDescriptorPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); + + describe('organizationGroup', async () => { + const fakePath = '/rendered/path/organizationGroup'; + const expectedParameters = { + organization: 'organizationValue', + group: 'groupValue', + }; + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.organizationGroupPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.organizationGroupPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('organizationGroupPath', () => { + const result = client.organizationGroupPath( + 'organizationValue', + 'groupValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationGroupPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationGroupName', () => { + const result = + client.matchOrganizationFromOrganizationGroupName(fakePath); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationGroupPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchGroupFromOrganizationGroupName', () => { + const result = client.matchGroupFromOrganizationGroupName(fakePath); + assert.strictEqual(result, 'groupValue'); + assert( + ( + client.pathTemplates.organizationGroupPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); + + describe('organizationNotificationChannel', async () => { + const fakePath = '/rendered/path/organizationNotificationChannel'; + const expectedParameters = { + organization: 'organizationValue', + notification_channel: 'notificationChannelValue', + }; + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.organizationNotificationChannelPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.organizationNotificationChannelPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('organizationNotificationChannelPath', () => { + const result = client.organizationNotificationChannelPath( + 'organizationValue', + 'notificationChannelValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationNotificationChannelPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationNotificationChannelName', () => { + const result = + client.matchOrganizationFromOrganizationNotificationChannelName( + fakePath, + ); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationNotificationChannelPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchNotificationChannelFromOrganizationNotificationChannelName', () => { + const result = + client.matchNotificationChannelFromOrganizationNotificationChannelName( + fakePath, + ); + assert.strictEqual(result, 'notificationChannelValue'); + assert( + ( + client.pathTemplates.organizationNotificationChannelPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); + + describe('organizationService', async () => { + const fakePath = '/rendered/path/organizationService'; + const expectedParameters = { + organization: 'organizationValue', + service: 'serviceValue', + }; + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.organizationServicePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.organizationServicePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('organizationServicePath', () => { + const result = client.organizationServicePath( + 'organizationValue', + 'serviceValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationServicePathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationServiceName', () => { + const result = + client.matchOrganizationFromOrganizationServiceName(fakePath); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationServicePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServiceFromOrganizationServiceName', () => { + const result = client.matchServiceFromOrganizationServiceName(fakePath); + assert.strictEqual(result, 'serviceValue'); + assert( + ( + client.pathTemplates.organizationServicePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); + + describe('organizationServiceServiceLevelObjective', async () => { + const fakePath = + '/rendered/path/organizationServiceServiceLevelObjective'; + const expectedParameters = { + organization: 'organizationValue', + service: 'serviceValue', + service_level_objective: 'serviceLevelObjectiveValue', + }; + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('organizationServiceServiceLevelObjectivePath', () => { + const result = client.organizationServiceServiceLevelObjectivePath( + 'organizationValue', + 'serviceValue', + 'serviceLevelObjectiveValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates + .organizationServiceServiceLevelObjectivePathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationServiceServiceLevelObjectiveName', () => { + const result = + client.matchOrganizationFromOrganizationServiceServiceLevelObjectiveName( + fakePath, + ); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates + .organizationServiceServiceLevelObjectivePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServiceFromOrganizationServiceServiceLevelObjectiveName', () => { + const result = + client.matchServiceFromOrganizationServiceServiceLevelObjectiveName( + fakePath, + ); + assert.strictEqual(result, 'serviceValue'); + assert( + ( + client.pathTemplates + .organizationServiceServiceLevelObjectivePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServiceLevelObjectiveFromOrganizationServiceServiceLevelObjectiveName', () => { + const result = + client.matchServiceLevelObjectiveFromOrganizationServiceServiceLevelObjectiveName( + fakePath, + ); + assert.strictEqual(result, 'serviceLevelObjectiveValue'); + assert( + ( + client.pathTemplates + .organizationServiceServiceLevelObjectivePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); + + describe('organizationUptimeCheckConfig', async () => { + const fakePath = '/rendered/path/organizationUptimeCheckConfig'; + const expectedParameters = { + organization: 'organizationValue', + uptime_check_config: 'uptimeCheckConfigValue', + }; + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.organizationUptimeCheckConfigPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.organizationUptimeCheckConfigPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('organizationUptimeCheckConfigPath', () => { + const result = client.organizationUptimeCheckConfigPath( + 'organizationValue', + 'uptimeCheckConfigValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationUptimeCheckConfigPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationUptimeCheckConfigName', () => { + const result = + client.matchOrganizationFromOrganizationUptimeCheckConfigName( + fakePath, + ); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationUptimeCheckConfigPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchUptimeCheckConfigFromOrganizationUptimeCheckConfigName', () => { + const result = + client.matchUptimeCheckConfigFromOrganizationUptimeCheckConfigName( + fakePath, + ); + assert.strictEqual(result, 'uptimeCheckConfigValue'); + assert( + ( + client.pathTemplates.organizationUptimeCheckConfigPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); + + describe('projectAlertPolicy', async () => { + const fakePath = '/rendered/path/projectAlertPolicy'; + const expectedParameters = { + project: 'projectValue', + alert_policy: 'alertPolicyValue', + }; + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.projectAlertPolicyPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectAlertPolicyPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectAlertPolicyPath', () => { + const result = client.projectAlertPolicyPath( + 'projectValue', + 'alertPolicyValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.projectAlertPolicyPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectAlertPolicyName', () => { + const result = client.matchProjectFromProjectAlertPolicyName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.projectAlertPolicyPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchAlertPolicyFromProjectAlertPolicyName', () => { + const result = + client.matchAlertPolicyFromProjectAlertPolicyName(fakePath); + assert.strictEqual(result, 'alertPolicyValue'); + assert( + ( + client.pathTemplates.projectAlertPolicyPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); + + describe('projectAlertPolicyCondition', async () => { + const fakePath = '/rendered/path/projectAlertPolicyCondition'; + const expectedParameters = { + project: 'projectValue', + alert_policy: 'alertPolicyValue', + condition: 'conditionValue', + }; + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.projectAlertPolicyConditionPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.projectAlertPolicyConditionPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectAlertPolicyConditionPath', () => { + const result = client.projectAlertPolicyConditionPath( + 'projectValue', + 'alertPolicyValue', + 'conditionValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.projectAlertPolicyConditionPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectAlertPolicyConditionName', () => { + const result = + client.matchProjectFromProjectAlertPolicyConditionName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.projectAlertPolicyConditionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchAlertPolicyFromProjectAlertPolicyConditionName', () => { + const result = + client.matchAlertPolicyFromProjectAlertPolicyConditionName(fakePath); + assert.strictEqual(result, 'alertPolicyValue'); + assert( + ( + client.pathTemplates.projectAlertPolicyConditionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchConditionFromProjectAlertPolicyConditionName', () => { + const result = + client.matchConditionFromProjectAlertPolicyConditionName(fakePath); + assert.strictEqual(result, 'conditionValue'); + assert( + ( + client.pathTemplates.projectAlertPolicyConditionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); + + describe('projectChannelDescriptor', async () => { + const fakePath = '/rendered/path/projectChannelDescriptor'; + const expectedParameters = { + project: 'projectValue', + channel_descriptor: 'channelDescriptorValue', + }; + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.projectChannelDescriptorPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectChannelDescriptorPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectChannelDescriptorPath', () => { + const result = client.projectChannelDescriptorPath( + 'projectValue', + 'channelDescriptorValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.projectChannelDescriptorPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectChannelDescriptorName', () => { + const result = + client.matchProjectFromProjectChannelDescriptorName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.projectChannelDescriptorPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchChannelDescriptorFromProjectChannelDescriptorName', () => { + const result = + client.matchChannelDescriptorFromProjectChannelDescriptorName( + fakePath, + ); + assert.strictEqual(result, 'channelDescriptorValue'); + assert( + ( + client.pathTemplates.projectChannelDescriptorPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); + + describe('projectGroup', async () => { + const fakePath = '/rendered/path/projectGroup'; + const expectedParameters = { + project: 'projectValue', + group: 'groupValue', + }; + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.projectGroupPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectGroupPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectGroupPath', () => { + const result = client.projectGroupPath('projectValue', 'groupValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.projectGroupPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectGroupName', () => { + const result = client.matchProjectFromProjectGroupName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.projectGroupPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchGroupFromProjectGroupName', () => { + const result = client.matchGroupFromProjectGroupName(fakePath); + assert.strictEqual(result, 'groupValue'); + assert( + (client.pathTemplates.projectGroupPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); + + describe('projectNotificationChannel', async () => { + const fakePath = '/rendered/path/projectNotificationChannel'; + const expectedParameters = { + project: 'projectValue', + notification_channel: 'notificationChannelValue', + }; + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.projectNotificationChannelPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectNotificationChannelPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectNotificationChannelPath', () => { + const result = client.projectNotificationChannelPath( + 'projectValue', + 'notificationChannelValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.projectNotificationChannelPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectNotificationChannelName', () => { + const result = + client.matchProjectFromProjectNotificationChannelName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.projectNotificationChannelPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchNotificationChannelFromProjectNotificationChannelName', () => { + const result = + client.matchNotificationChannelFromProjectNotificationChannelName( + fakePath, + ); + assert.strictEqual(result, 'notificationChannelValue'); + assert( + ( + client.pathTemplates.projectNotificationChannelPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); + + describe('projectService', async () => { + const fakePath = '/rendered/path/projectService'; + const expectedParameters = { + project: 'projectValue', + service: 'serviceValue', + }; + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.projectServicePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectServicePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectServicePath', () => { + const result = client.projectServicePath( + 'projectValue', + 'serviceValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.projectServicePathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectServiceName', () => { + const result = client.matchProjectFromProjectServiceName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.projectServicePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServiceFromProjectServiceName', () => { + const result = client.matchServiceFromProjectServiceName(fakePath); + assert.strictEqual(result, 'serviceValue'); + assert( + (client.pathTemplates.projectServicePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); + + describe('projectServiceServiceLevelObjective', async () => { + const fakePath = '/rendered/path/projectServiceServiceLevelObjective'; + const expectedParameters = { + project: 'projectValue', + service: 'serviceValue', + service_level_objective: 'serviceLevelObjectiveValue', + }; + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('projectServiceServiceLevelObjectivePath', () => { + const result = client.projectServiceServiceLevelObjectivePath( + 'projectValue', + 'serviceValue', + 'serviceLevelObjectiveValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectServiceServiceLevelObjectiveName', () => { + const result = + client.matchProjectFromProjectServiceServiceLevelObjectiveName( + fakePath, + ); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServiceFromProjectServiceServiceLevelObjectiveName', () => { + const result = + client.matchServiceFromProjectServiceServiceLevelObjectiveName( + fakePath, + ); + assert.strictEqual(result, 'serviceValue'); + assert( + ( + client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServiceLevelObjectiveFromProjectServiceServiceLevelObjectiveName', () => { + const result = + client.matchServiceLevelObjectiveFromProjectServiceServiceLevelObjectiveName( + fakePath, + ); + assert.strictEqual(result, 'serviceLevelObjectiveValue'); + assert( + ( + client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); + + describe('projectUptimeCheckConfig', async () => { + const fakePath = '/rendered/path/projectUptimeCheckConfig'; + const expectedParameters = { + project: 'projectValue', + uptime_check_config: 'uptimeCheckConfigValue', + }; + const client = + new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.projectUptimeCheckConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectUptimeCheckConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectUptimeCheckConfigPath', () => { + const result = client.projectUptimeCheckConfigPath( + 'projectValue', + 'uptimeCheckConfigValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.projectUptimeCheckConfigPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectUptimeCheckConfigName', () => { + const result = + client.matchProjectFromProjectUptimeCheckConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.projectUptimeCheckConfigPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchUptimeCheckConfigFromProjectUptimeCheckConfigName', () => { + const result = + client.matchUptimeCheckConfigFromProjectUptimeCheckConfigName( + fakePath, + ); + assert.strictEqual(result, 'uptimeCheckConfigValue'); + assert( + ( + client.pathTemplates.projectUptimeCheckConfigPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); + }); }); diff --git a/core/generator/gapic-generator-typescript/baselines/monitoring/test/gapic_uptime_check_service_v3.ts.baseline b/core/generator/gapic-generator-typescript/baselines/monitoring/test/gapic_uptime_check_service_v3.ts.baseline index 4893feec487c..6ae1b6ed5fd7 100644 --- a/core/generator/gapic-generator-typescript/baselines/monitoring/test/gapic_uptime_check_service_v3.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/monitoring/test/gapic_uptime_check_service_v3.ts.baseline @@ -19,2062 +19,3005 @@ import * as protos from '../protos/protos'; import * as assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as uptimecheckserviceModule from '../src'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; -import {protobuf} from 'google-gax'; +import { protobuf } from 'google-gax'; // Dynamically loaded proto JSON is needed to get the type information // to fill in default values for request objects -const root = protobuf.Root.fromJSON(require('../protos/protos.json')).resolveAll(); +const root = protobuf.Root.fromJSON( + require('../protos/protos.json'), +).resolveAll(); // eslint-disable-next-line @typescript-eslint/no-unused-vars function getTypeDefaultValue(typeName: string, fields: string[]) { - let type = root.lookupType(typeName) as protobuf.Type; - for (const field of fields.slice(0, -1)) { - type = type.fields[field]?.resolvedType as protobuf.Type; - } - return type.fields[fields[fields.length - 1]]?.defaultValue; + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type.fields[field]?.resolvedType as protobuf.Type; + } + return type.fields[fields[fields.length - 1]]?.defaultValue; } function generateSampleMessage(instance: T) { - const filledObject = (instance.constructor as typeof protobuf.Message) - .toObject(instance as protobuf.Message, {defaults: true}); - return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, { defaults: true }); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; } function stubSimpleCall(response?: ResponseType, error?: Error) { - return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); } -function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { - return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +function stubSimpleCallWithCallback( + response?: ResponseType, + error?: Error, +) { + return error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); } -function stubPageStreamingCall(responses?: ResponseType[], error?: Error) { - const pagingStub = sinon.stub(); - if (responses) { - for (let i = 0; i < responses.length; ++i) { - pagingStub.onCall(i).callsArgWith(2, null, responses[i]); - } +function stubPageStreamingCall( + responses?: ResponseType[], + error?: Error, +) { + const pagingStub = sinon.stub(); + if (responses) { + for (let i = 0; i < responses.length; ++i) { + pagingStub.onCall(i).callsArgWith(2, null, responses[i]); } - const transformStub = error ? sinon.stub().callsArgWith(2, error) : pagingStub; - const mockStream = new PassThrough({ - objectMode: true, - transform: transformStub, - }); - // trigger as many responses as needed - if (responses) { - for (let i = 0; i < responses.length; ++i) { - setImmediate(() => { mockStream.write({}); }); - } - setImmediate(() => { mockStream.end(); }); - } else { - setImmediate(() => { mockStream.write({}); }); - setImmediate(() => { mockStream.end(); }); + } + const transformStub = error + ? sinon.stub().callsArgWith(2, error) + : pagingStub; + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + // trigger as many responses as needed + if (responses) { + for (let i = 0; i < responses.length; ++i) { + setImmediate(() => { + mockStream.write({}); + }); } - return sinon.stub().returns(mockStream); + setImmediate(() => { + mockStream.end(); + }); + } else { + setImmediate(() => { + mockStream.write({}); + }); + setImmediate(() => { + mockStream.end(); + }); + } + return sinon.stub().returns(mockStream); } -function stubAsyncIterationCall(responses?: ResponseType[], error?: Error) { - let counter = 0; - const asyncIterable = { - [Symbol.asyncIterator]() { - return { - async next() { - if (error) { - return Promise.reject(error); - } - if (counter >= responses!.length) { - return Promise.resolve({done: true, value: undefined}); - } - return Promise.resolve({done: false, value: responses![counter++]}); - } - }; - } - }; - return sinon.stub().returns(asyncIterable); +function stubAsyncIterationCall( + responses?: ResponseType[], + error?: Error, +) { + let counter = 0; + const asyncIterable = { + [Symbol.asyncIterator]() { + return { + async next() { + if (error) { + return Promise.reject(error); + } + if (counter >= responses!.length) { + return Promise.resolve({ done: true, value: undefined }); + } + return Promise.resolve({ done: false, value: responses![counter++] }); + }, + }; + }, + }; + return sinon.stub().returns(asyncIterable); } describe('v3.UptimeCheckServiceClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'monitoring.googleapis.com'); - }); - - it('has universeDomain', () => { - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); - - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - it('throws DeprecationWarning if static servicePath is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const servicePath = uptimecheckserviceModule.v3.UptimeCheckServiceClient.servicePath; - assert.strictEqual(servicePath, 'monitoring.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = uptimecheckserviceModule.v3.UptimeCheckServiceClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'monitoring.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'monitoring.example.com'); - }); - - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'monitoring.example.com'); - }); - - if (typeof process === 'object' && 'env' in process) { - describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { - it('sets apiEndpoint from environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'monitoring.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - - it('value configured in code has priority over environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'monitoring.configured.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { new uptimecheckserviceModule.v3.UptimeCheckServiceClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); - - it('has port', () => { - const port = uptimecheckserviceModule.v3.UptimeCheckServiceClient.port; - assert(port); - assert(typeof port === 'number'); - }); - - it('should create a client with no option', () => { - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient(); - assert(client); - }); - - it('should create a client with gRPC fallback', () => { - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ - fallback: true, - }); - assert(client); - }); - - it('has initialize method and supports deferred initialization', async () => { - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.uptimeCheckServiceStub, undefined); - await client.initialize(); - assert(client.uptimeCheckServiceStub); - }); - - it('has close method for the initialized client', done => { - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.uptimeCheckServiceStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); - - it('has close method for the non-initialized client', done => { - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.uptimeCheckServiceStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); - - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); - }); - - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId((err?: Error|null, projectId?: string|null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } - }); - }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'monitoring.googleapis.com'); }); - describe('getUptimeCheckConfig', () => { - it('invokes getUptimeCheckConfig without error', async () => { - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.GetUptimeCheckConfigRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.GetUptimeCheckConfigRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.monitoring.v3.UptimeCheckConfig() - ); - client.innerApiCalls.getUptimeCheckConfig = stubSimpleCall(expectedResponse); - const [response] = await client.getUptimeCheckConfig(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getUptimeCheckConfig as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getUptimeCheckConfig as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getUptimeCheckConfig without error using callback', async () => { - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.GetUptimeCheckConfigRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.GetUptimeCheckConfigRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.monitoring.v3.UptimeCheckConfig() - ); - client.innerApiCalls.getUptimeCheckConfig = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getUptimeCheckConfig( - request, - (err?: Error|null, result?: protos.google.monitoring.v3.IUptimeCheckConfig|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getUptimeCheckConfig as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getUptimeCheckConfig as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getUptimeCheckConfig with error', async () => { - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.GetUptimeCheckConfigRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.GetUptimeCheckConfigRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getUptimeCheckConfig = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getUptimeCheckConfig(request), expectedError); - const actualRequest = (client.innerApiCalls.getUptimeCheckConfig as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getUptimeCheckConfig as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getUptimeCheckConfig with closed client', async () => { - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.GetUptimeCheckConfigRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.GetUptimeCheckConfigRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getUptimeCheckConfig(request), expectedError); - }); + it('has universeDomain', () => { + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); }); - describe('createUptimeCheckConfig', () => { - it('invokes createUptimeCheckConfig without error', async () => { - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.CreateUptimeCheckConfigRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.CreateUptimeCheckConfigRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.monitoring.v3.UptimeCheckConfig() - ); - client.innerApiCalls.createUptimeCheckConfig = stubSimpleCall(expectedResponse); - const [response] = await client.createUptimeCheckConfig(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createUptimeCheckConfig as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createUptimeCheckConfig as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createUptimeCheckConfig without error using callback', async () => { - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.CreateUptimeCheckConfigRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.CreateUptimeCheckConfigRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.monitoring.v3.UptimeCheckConfig() - ); - client.innerApiCalls.createUptimeCheckConfig = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createUptimeCheckConfig( - request, - (err?: Error|null, result?: protos.google.monitoring.v3.IUptimeCheckConfig|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createUptimeCheckConfig as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createUptimeCheckConfig as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createUptimeCheckConfig with error', async () => { - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.CreateUptimeCheckConfigRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.CreateUptimeCheckConfigRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createUptimeCheckConfig = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createUptimeCheckConfig(request), expectedError); - const actualRequest = (client.innerApiCalls.createUptimeCheckConfig as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createUptimeCheckConfig as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createUptimeCheckConfig with closed client', async () => { - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.CreateUptimeCheckConfigRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.CreateUptimeCheckConfigRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createUptimeCheckConfig(request), expectedError); - }); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = + uptimecheckserviceModule.v3.UptimeCheckServiceClient.servicePath; + assert.strictEqual(servicePath, 'monitoring.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + uptimecheckserviceModule.v3.UptimeCheckServiceClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'monitoring.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + universeDomain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'monitoring.example.com'); }); - describe('updateUptimeCheckConfig', () => { - it('invokes updateUptimeCheckConfig without error', async () => { - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.UpdateUptimeCheckConfigRequest() - ); - request.uptimeCheckConfig ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.UpdateUptimeCheckConfigRequest', ['uptimeCheckConfig', 'name']); - request.uptimeCheckConfig.name = defaultValue1; - const expectedHeaderRequestParams = `uptime_check_config.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.monitoring.v3.UptimeCheckConfig() - ); - client.innerApiCalls.updateUptimeCheckConfig = stubSimpleCall(expectedResponse); - const [response] = await client.updateUptimeCheckConfig(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateUptimeCheckConfig as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateUptimeCheckConfig as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateUptimeCheckConfig without error using callback', async () => { - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.UpdateUptimeCheckConfigRequest() - ); - request.uptimeCheckConfig ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.UpdateUptimeCheckConfigRequest', ['uptimeCheckConfig', 'name']); - request.uptimeCheckConfig.name = defaultValue1; - const expectedHeaderRequestParams = `uptime_check_config.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.monitoring.v3.UptimeCheckConfig() - ); - client.innerApiCalls.updateUptimeCheckConfig = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateUptimeCheckConfig( - request, - (err?: Error|null, result?: protos.google.monitoring.v3.IUptimeCheckConfig|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateUptimeCheckConfig as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateUptimeCheckConfig as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateUptimeCheckConfig with error', async () => { - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.UpdateUptimeCheckConfigRequest() - ); - request.uptimeCheckConfig ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.UpdateUptimeCheckConfigRequest', ['uptimeCheckConfig', 'name']); - request.uptimeCheckConfig.name = defaultValue1; - const expectedHeaderRequestParams = `uptime_check_config.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateUptimeCheckConfig = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateUptimeCheckConfig(request), expectedError); - const actualRequest = (client.innerApiCalls.updateUptimeCheckConfig as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateUptimeCheckConfig as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateUptimeCheckConfig with closed client', async () => { - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.UpdateUptimeCheckConfigRequest() - ); - request.uptimeCheckConfig ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.UpdateUptimeCheckConfigRequest', ['uptimeCheckConfig', 'name']); - request.uptimeCheckConfig.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateUptimeCheckConfig(request), expectedError); - }); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + universe_domain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'monitoring.example.com'); }); - describe('deleteUptimeCheckConfig', () => { - it('invokes deleteUptimeCheckConfig without error', async () => { - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.DeleteUptimeCheckConfigRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.DeleteUptimeCheckConfigRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteUptimeCheckConfig = stubSimpleCall(expectedResponse); - const [response] = await client.deleteUptimeCheckConfig(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteUptimeCheckConfig as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteUptimeCheckConfig as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + if (typeof process === 'object' && 'env' in process) { + describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { + it('sets apiEndpoint from environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = + new uptimecheckserviceModule.v3.UptimeCheckServiceClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'monitoring.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } + }); + + it('value configured in code has priority over environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = + new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + universeDomain: 'configured.example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'monitoring.configured.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } + }); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); + }); - it('invokes deleteUptimeCheckConfig without error using callback', async () => { - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.DeleteUptimeCheckConfigRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.DeleteUptimeCheckConfigRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteUptimeCheckConfig = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteUptimeCheckConfig( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteUptimeCheckConfig as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteUptimeCheckConfig as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has port', () => { + const port = uptimecheckserviceModule.v3.UptimeCheckServiceClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('invokes deleteUptimeCheckConfig with error', async () => { - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.DeleteUptimeCheckConfigRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.DeleteUptimeCheckConfigRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteUptimeCheckConfig = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteUptimeCheckConfig(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteUptimeCheckConfig as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteUptimeCheckConfig as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('should create a client with no option', () => { + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient(); + assert(client); + }); - it('invokes deleteUptimeCheckConfig with closed client', async () => { - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.DeleteUptimeCheckConfigRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.DeleteUptimeCheckConfigRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteUptimeCheckConfig(request), expectedError); - }); + it('should create a client with gRPC fallback', () => { + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + fallback: true, + }); + assert(client); }); - describe('listUptimeCheckConfigs', () => { - it('invokes listUptimeCheckConfigs without error', async () => { - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListUptimeCheckConfigsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListUptimeCheckConfigsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.monitoring.v3.UptimeCheckConfig()), - generateSampleMessage(new protos.google.monitoring.v3.UptimeCheckConfig()), - generateSampleMessage(new protos.google.monitoring.v3.UptimeCheckConfig()), - ]; - client.innerApiCalls.listUptimeCheckConfigs = stubSimpleCall(expectedResponse); - const [response] = await client.listUptimeCheckConfigs(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listUptimeCheckConfigs as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listUptimeCheckConfigs as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has initialize method and supports deferred initialization', async () => { + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.uptimeCheckServiceStub, undefined); + await client.initialize(); + assert(client.uptimeCheckServiceStub); + }); - it('invokes listUptimeCheckConfigs without error using callback', async () => { - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListUptimeCheckConfigsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListUptimeCheckConfigsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.monitoring.v3.UptimeCheckConfig()), - generateSampleMessage(new protos.google.monitoring.v3.UptimeCheckConfig()), - generateSampleMessage(new protos.google.monitoring.v3.UptimeCheckConfig()), - ]; - client.innerApiCalls.listUptimeCheckConfigs = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listUptimeCheckConfigs( - request, - (err?: Error|null, result?: protos.google.monitoring.v3.IUptimeCheckConfig[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listUptimeCheckConfigs as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listUptimeCheckConfigs as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('has close method for the initialized client', (done) => { + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.uptimeCheckServiceStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes listUptimeCheckConfigs with error', async () => { - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListUptimeCheckConfigsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListUptimeCheckConfigsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listUptimeCheckConfigs = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listUptimeCheckConfigs(request), expectedError); - const actualRequest = (client.innerApiCalls.listUptimeCheckConfigs as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listUptimeCheckConfigs as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('has close method for the non-initialized client', (done) => { + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.uptimeCheckServiceStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes listUptimeCheckConfigsStream without error', async () => { - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListUptimeCheckConfigsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListUptimeCheckConfigsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.monitoring.v3.UptimeCheckConfig()), - generateSampleMessage(new protos.google.monitoring.v3.UptimeCheckConfig()), - generateSampleMessage(new protos.google.monitoring.v3.UptimeCheckConfig()), - ]; - client.descriptors.page.listUptimeCheckConfigs.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listUptimeCheckConfigsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.monitoring.v3.UptimeCheckConfig[] = []; - stream.on('data', (response: protos.google.monitoring.v3.UptimeCheckConfig) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.listUptimeCheckConfigs.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listUptimeCheckConfigs, request)); - assert( - (client.descriptors.page.listUptimeCheckConfigs.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + }); - it('invokes listUptimeCheckConfigsStream with error', async () => { - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListUptimeCheckConfigsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListUptimeCheckConfigsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listUptimeCheckConfigs.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listUptimeCheckConfigsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.monitoring.v3.UptimeCheckConfig[] = []; - stream.on('data', (response: protos.google.monitoring.v3.UptimeCheckConfig) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listUptimeCheckConfigs.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listUptimeCheckConfigs, request)); - assert( - (client.descriptors.page.listUptimeCheckConfigs.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } + }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + }); + + describe('getUptimeCheckConfig', () => { + it('invokes getUptimeCheckConfig without error', async () => { + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.GetUptimeCheckConfigRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.GetUptimeCheckConfigRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.monitoring.v3.UptimeCheckConfig(), + ); + client.innerApiCalls.getUptimeCheckConfig = + stubSimpleCall(expectedResponse); + const [response] = await client.getUptimeCheckConfig(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getUptimeCheckConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getUptimeCheckConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('uses async iteration with listUptimeCheckConfigs without error', async () => { - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListUptimeCheckConfigsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListUptimeCheckConfigsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.monitoring.v3.UptimeCheckConfig()), - generateSampleMessage(new protos.google.monitoring.v3.UptimeCheckConfig()), - generateSampleMessage(new protos.google.monitoring.v3.UptimeCheckConfig()), - ]; - client.descriptors.page.listUptimeCheckConfigs.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.monitoring.v3.IUptimeCheckConfig[] = []; - const iterable = client.listUptimeCheckConfigsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); + it('invokes getUptimeCheckConfig without error using callback', async () => { + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.GetUptimeCheckConfigRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.GetUptimeCheckConfigRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.monitoring.v3.UptimeCheckConfig(), + ); + client.innerApiCalls.getUptimeCheckConfig = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getUptimeCheckConfig( + request, + ( + err?: Error | null, + result?: protos.google.monitoring.v3.IUptimeCheckConfig | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listUptimeCheckConfigs.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listUptimeCheckConfigs.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); - - it('uses async iteration with listUptimeCheckConfigs with error', async () => { - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListUptimeCheckConfigsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.monitoring.v3.ListUptimeCheckConfigsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listUptimeCheckConfigs.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listUptimeCheckConfigsAsync(request); - await assert.rejects(async () => { - const responses: protos.google.monitoring.v3.IUptimeCheckConfig[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listUptimeCheckConfigs.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listUptimeCheckConfigs.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getUptimeCheckConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getUptimeCheckConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('listUptimeCheckIps', () => { - it('invokes listUptimeCheckIps without error', async () => { - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListUptimeCheckIpsRequest() - );const expectedResponse = [ - generateSampleMessage(new protos.google.monitoring.v3.UptimeCheckIp()), - generateSampleMessage(new protos.google.monitoring.v3.UptimeCheckIp()), - generateSampleMessage(new protos.google.monitoring.v3.UptimeCheckIp()), - ]; - client.innerApiCalls.listUptimeCheckIps = stubSimpleCall(expectedResponse); - const [response] = await client.listUptimeCheckIps(request); - assert.deepStrictEqual(response, expectedResponse); - }); - - it('invokes listUptimeCheckIps without error using callback', async () => { - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListUptimeCheckIpsRequest() - );const expectedResponse = [ - generateSampleMessage(new protos.google.monitoring.v3.UptimeCheckIp()), - generateSampleMessage(new protos.google.monitoring.v3.UptimeCheckIp()), - generateSampleMessage(new protos.google.monitoring.v3.UptimeCheckIp()), - ]; - client.innerApiCalls.listUptimeCheckIps = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listUptimeCheckIps( - request, - (err?: Error|null, result?: protos.google.monitoring.v3.IUptimeCheckIp[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); - - it('invokes listUptimeCheckIps with error', async () => { - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListUptimeCheckIpsRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.listUptimeCheckIps = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listUptimeCheckIps(request), expectedError); - }); - - it('invokes listUptimeCheckIpsStream without error', async () => { - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListUptimeCheckIpsRequest() - ); - const expectedResponse = [ - generateSampleMessage(new protos.google.monitoring.v3.UptimeCheckIp()), - generateSampleMessage(new protos.google.monitoring.v3.UptimeCheckIp()), - generateSampleMessage(new protos.google.monitoring.v3.UptimeCheckIp()), - ]; - client.descriptors.page.listUptimeCheckIps.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listUptimeCheckIpsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.monitoring.v3.UptimeCheckIp[] = []; - stream.on('data', (response: protos.google.monitoring.v3.UptimeCheckIp) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.listUptimeCheckIps.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listUptimeCheckIps, request)); - }); + it('invokes getUptimeCheckConfig with error', async () => { + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.GetUptimeCheckConfigRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.GetUptimeCheckConfigRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getUptimeCheckConfig = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getUptimeCheckConfig(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getUptimeCheckConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getUptimeCheckConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listUptimeCheckIpsStream with error', async () => { - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListUptimeCheckIpsRequest() - ); - const expectedError = new Error('expected'); - client.descriptors.page.listUptimeCheckIps.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listUptimeCheckIpsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.monitoring.v3.UptimeCheckIp[] = []; - stream.on('data', (response: protos.google.monitoring.v3.UptimeCheckIp) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listUptimeCheckIps.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listUptimeCheckIps, request)); - }); + it('invokes getUptimeCheckConfig with closed client', async () => { + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.GetUptimeCheckConfigRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.GetUptimeCheckConfigRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getUptimeCheckConfig(request), expectedError); + }); + }); + + describe('createUptimeCheckConfig', () => { + it('invokes createUptimeCheckConfig without error', async () => { + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.CreateUptimeCheckConfigRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.CreateUptimeCheckConfigRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.monitoring.v3.UptimeCheckConfig(), + ); + client.innerApiCalls.createUptimeCheckConfig = + stubSimpleCall(expectedResponse); + const [response] = await client.createUptimeCheckConfig(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createUptimeCheckConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createUptimeCheckConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('uses async iteration with listUptimeCheckIps without error', async () => { - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListUptimeCheckIpsRequest() - ); - const expectedResponse = [ - generateSampleMessage(new protos.google.monitoring.v3.UptimeCheckIp()), - generateSampleMessage(new protos.google.monitoring.v3.UptimeCheckIp()), - generateSampleMessage(new protos.google.monitoring.v3.UptimeCheckIp()), - ]; - client.descriptors.page.listUptimeCheckIps.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.monitoring.v3.IUptimeCheckIp[] = []; - const iterable = client.listUptimeCheckIpsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); + it('invokes createUptimeCheckConfig without error using callback', async () => { + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.CreateUptimeCheckConfigRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.CreateUptimeCheckConfigRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.monitoring.v3.UptimeCheckConfig(), + ); + client.innerApiCalls.createUptimeCheckConfig = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createUptimeCheckConfig( + request, + ( + err?: Error | null, + result?: protos.google.monitoring.v3.IUptimeCheckConfig | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listUptimeCheckIps.asyncIterate as SinonStub) - .getCall(0).args[1], request); - }); - - it('uses async iteration with listUptimeCheckIps with error', async () => { - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.monitoring.v3.ListUptimeCheckIpsRequest() - ); - const expectedError = new Error('expected'); - client.descriptors.page.listUptimeCheckIps.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listUptimeCheckIpsAsync(request); - await assert.rejects(async () => { - const responses: protos.google.monitoring.v3.IUptimeCheckIp[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listUptimeCheckIps.asyncIterate as SinonStub) - .getCall(0).args[1], request); - }); + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createUptimeCheckConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createUptimeCheckConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('Path templates', () => { - - describe('folderAlertPolicy', async () => { - const fakePath = "/rendered/path/folderAlertPolicy"; - const expectedParameters = { - folder: "folderValue", - alert_policy: "alertPolicyValue", - }; - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.folderAlertPolicyPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderAlertPolicyPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderAlertPolicyPath', () => { - const result = client.folderAlertPolicyPath("folderValue", "alertPolicyValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderAlertPolicyPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderAlertPolicyName', () => { - const result = client.matchFolderFromFolderAlertPolicyName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderAlertPolicyPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchAlertPolicyFromFolderAlertPolicyName', () => { - const result = client.matchAlertPolicyFromFolderAlertPolicyName(fakePath); - assert.strictEqual(result, "alertPolicyValue"); - assert((client.pathTemplates.folderAlertPolicyPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('folderAlertPolicyCondition', async () => { - const fakePath = "/rendered/path/folderAlertPolicyCondition"; - const expectedParameters = { - folder: "folderValue", - alert_policy: "alertPolicyValue", - condition: "conditionValue", - }; - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.folderAlertPolicyConditionPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderAlertPolicyConditionPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderAlertPolicyConditionPath', () => { - const result = client.folderAlertPolicyConditionPath("folderValue", "alertPolicyValue", "conditionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderAlertPolicyConditionPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderAlertPolicyConditionName', () => { - const result = client.matchFolderFromFolderAlertPolicyConditionName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderAlertPolicyConditionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchAlertPolicyFromFolderAlertPolicyConditionName', () => { - const result = client.matchAlertPolicyFromFolderAlertPolicyConditionName(fakePath); - assert.strictEqual(result, "alertPolicyValue"); - assert((client.pathTemplates.folderAlertPolicyConditionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchConditionFromFolderAlertPolicyConditionName', () => { - const result = client.matchConditionFromFolderAlertPolicyConditionName(fakePath); - assert.strictEqual(result, "conditionValue"); - assert((client.pathTemplates.folderAlertPolicyConditionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('folderChannelDescriptor', async () => { - const fakePath = "/rendered/path/folderChannelDescriptor"; - const expectedParameters = { - folder: "folderValue", - channel_descriptor: "channelDescriptorValue", - }; - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.folderChannelDescriptorPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderChannelDescriptorPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderChannelDescriptorPath', () => { - const result = client.folderChannelDescriptorPath("folderValue", "channelDescriptorValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderChannelDescriptorPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderChannelDescriptorName', () => { - const result = client.matchFolderFromFolderChannelDescriptorName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderChannelDescriptorPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchChannelDescriptorFromFolderChannelDescriptorName', () => { - const result = client.matchChannelDescriptorFromFolderChannelDescriptorName(fakePath); - assert.strictEqual(result, "channelDescriptorValue"); - assert((client.pathTemplates.folderChannelDescriptorPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('folderGroup', async () => { - const fakePath = "/rendered/path/folderGroup"; - const expectedParameters = { - folder: "folderValue", - group: "groupValue", - }; - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.folderGroupPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderGroupPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderGroupPath', () => { - const result = client.folderGroupPath("folderValue", "groupValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderGroupPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderGroupName', () => { - const result = client.matchFolderFromFolderGroupName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderGroupPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchGroupFromFolderGroupName', () => { - const result = client.matchGroupFromFolderGroupName(fakePath); - assert.strictEqual(result, "groupValue"); - assert((client.pathTemplates.folderGroupPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('folderNotificationChannel', async () => { - const fakePath = "/rendered/path/folderNotificationChannel"; - const expectedParameters = { - folder: "folderValue", - notification_channel: "notificationChannelValue", - }; - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.folderNotificationChannelPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderNotificationChannelPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderNotificationChannelPath', () => { - const result = client.folderNotificationChannelPath("folderValue", "notificationChannelValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderNotificationChannelPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderNotificationChannelName', () => { - const result = client.matchFolderFromFolderNotificationChannelName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderNotificationChannelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchNotificationChannelFromFolderNotificationChannelName', () => { - const result = client.matchNotificationChannelFromFolderNotificationChannelName(fakePath); - assert.strictEqual(result, "notificationChannelValue"); - assert((client.pathTemplates.folderNotificationChannelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('folderService', async () => { - const fakePath = "/rendered/path/folderService"; - const expectedParameters = { - folder: "folderValue", - service: "serviceValue", - }; - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.folderServicePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderServicePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderServicePath', () => { - const result = client.folderServicePath("folderValue", "serviceValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderServicePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderServiceName', () => { - const result = client.matchFolderFromFolderServiceName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderServicePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServiceFromFolderServiceName', () => { - const result = client.matchServiceFromFolderServiceName(fakePath); - assert.strictEqual(result, "serviceValue"); - assert((client.pathTemplates.folderServicePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('folderServiceServiceLevelObjective', async () => { - const fakePath = "/rendered/path/folderServiceServiceLevelObjective"; - const expectedParameters = { - folder: "folderValue", - service: "serviceValue", - service_level_objective: "serviceLevelObjectiveValue", - }; - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderServiceServiceLevelObjectivePath', () => { - const result = client.folderServiceServiceLevelObjectivePath("folderValue", "serviceValue", "serviceLevelObjectiveValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderServiceServiceLevelObjectiveName', () => { - const result = client.matchFolderFromFolderServiceServiceLevelObjectiveName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServiceFromFolderServiceServiceLevelObjectiveName', () => { - const result = client.matchServiceFromFolderServiceServiceLevelObjectiveName(fakePath); - assert.strictEqual(result, "serviceValue"); - assert((client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServiceLevelObjectiveFromFolderServiceServiceLevelObjectiveName', () => { - const result = client.matchServiceLevelObjectiveFromFolderServiceServiceLevelObjectiveName(fakePath); - assert.strictEqual(result, "serviceLevelObjectiveValue"); - assert((client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('folderUptimeCheckConfig', async () => { - const fakePath = "/rendered/path/folderUptimeCheckConfig"; - const expectedParameters = { - folder: "folderValue", - uptime_check_config: "uptimeCheckConfigValue", - }; - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.folderUptimeCheckConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderUptimeCheckConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderUptimeCheckConfigPath', () => { - const result = client.folderUptimeCheckConfigPath("folderValue", "uptimeCheckConfigValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderUptimeCheckConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderUptimeCheckConfigName', () => { - const result = client.matchFolderFromFolderUptimeCheckConfigName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderUptimeCheckConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchUptimeCheckConfigFromFolderUptimeCheckConfigName', () => { - const result = client.matchUptimeCheckConfigFromFolderUptimeCheckConfigName(fakePath); - assert.strictEqual(result, "uptimeCheckConfigValue"); - assert((client.pathTemplates.folderUptimeCheckConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('organizationAlertPolicy', async () => { - const fakePath = "/rendered/path/organizationAlertPolicy"; - const expectedParameters = { - organization: "organizationValue", - alert_policy: "alertPolicyValue", - }; - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.organizationAlertPolicyPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationAlertPolicyPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationAlertPolicyPath', () => { - const result = client.organizationAlertPolicyPath("organizationValue", "alertPolicyValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationAlertPolicyPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationAlertPolicyName', () => { - const result = client.matchOrganizationFromOrganizationAlertPolicyName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationAlertPolicyPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchAlertPolicyFromOrganizationAlertPolicyName', () => { - const result = client.matchAlertPolicyFromOrganizationAlertPolicyName(fakePath); - assert.strictEqual(result, "alertPolicyValue"); - assert((client.pathTemplates.organizationAlertPolicyPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('organizationAlertPolicyCondition', async () => { - const fakePath = "/rendered/path/organizationAlertPolicyCondition"; - const expectedParameters = { - organization: "organizationValue", - alert_policy: "alertPolicyValue", - condition: "conditionValue", - }; - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.organizationAlertPolicyConditionPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationAlertPolicyConditionPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationAlertPolicyConditionPath', () => { - const result = client.organizationAlertPolicyConditionPath("organizationValue", "alertPolicyValue", "conditionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationAlertPolicyConditionPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationAlertPolicyConditionName', () => { - const result = client.matchOrganizationFromOrganizationAlertPolicyConditionName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationAlertPolicyConditionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchAlertPolicyFromOrganizationAlertPolicyConditionName', () => { - const result = client.matchAlertPolicyFromOrganizationAlertPolicyConditionName(fakePath); - assert.strictEqual(result, "alertPolicyValue"); - assert((client.pathTemplates.organizationAlertPolicyConditionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchConditionFromOrganizationAlertPolicyConditionName', () => { - const result = client.matchConditionFromOrganizationAlertPolicyConditionName(fakePath); - assert.strictEqual(result, "conditionValue"); - assert((client.pathTemplates.organizationAlertPolicyConditionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('organizationChannelDescriptor', async () => { - const fakePath = "/rendered/path/organizationChannelDescriptor"; - const expectedParameters = { - organization: "organizationValue", - channel_descriptor: "channelDescriptorValue", - }; - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.organizationChannelDescriptorPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationChannelDescriptorPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationChannelDescriptorPath', () => { - const result = client.organizationChannelDescriptorPath("organizationValue", "channelDescriptorValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationChannelDescriptorPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationChannelDescriptorName', () => { - const result = client.matchOrganizationFromOrganizationChannelDescriptorName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationChannelDescriptorPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchChannelDescriptorFromOrganizationChannelDescriptorName', () => { - const result = client.matchChannelDescriptorFromOrganizationChannelDescriptorName(fakePath); - assert.strictEqual(result, "channelDescriptorValue"); - assert((client.pathTemplates.organizationChannelDescriptorPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('invokes createUptimeCheckConfig with error', async () => { + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.CreateUptimeCheckConfigRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.CreateUptimeCheckConfigRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createUptimeCheckConfig = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.createUptimeCheckConfig(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.createUptimeCheckConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createUptimeCheckConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - describe('organizationGroup', async () => { - const fakePath = "/rendered/path/organizationGroup"; - const expectedParameters = { - organization: "organizationValue", - group: "groupValue", - }; - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.organizationGroupPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationGroupPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationGroupPath', () => { - const result = client.organizationGroupPath("organizationValue", "groupValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationGroupPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + it('invokes createUptimeCheckConfig with closed client', async () => { + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.CreateUptimeCheckConfigRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.CreateUptimeCheckConfigRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.createUptimeCheckConfig(request), + expectedError, + ); + }); + }); + + describe('updateUptimeCheckConfig', () => { + it('invokes updateUptimeCheckConfig without error', async () => { + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.UpdateUptimeCheckConfigRequest(), + ); + request.uptimeCheckConfig ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.UpdateUptimeCheckConfigRequest', + ['uptimeCheckConfig', 'name'], + ); + request.uptimeCheckConfig.name = defaultValue1; + const expectedHeaderRequestParams = `uptime_check_config.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.monitoring.v3.UptimeCheckConfig(), + ); + client.innerApiCalls.updateUptimeCheckConfig = + stubSimpleCall(expectedResponse); + const [response] = await client.updateUptimeCheckConfig(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateUptimeCheckConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateUptimeCheckConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('matchOrganizationFromOrganizationGroupName', () => { - const result = client.matchOrganizationFromOrganizationGroupName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationGroupPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('invokes updateUptimeCheckConfig without error using callback', async () => { + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.UpdateUptimeCheckConfigRequest(), + ); + request.uptimeCheckConfig ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.UpdateUptimeCheckConfigRequest', + ['uptimeCheckConfig', 'name'], + ); + request.uptimeCheckConfig.name = defaultValue1; + const expectedHeaderRequestParams = `uptime_check_config.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.monitoring.v3.UptimeCheckConfig(), + ); + client.innerApiCalls.updateUptimeCheckConfig = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateUptimeCheckConfig( + request, + ( + err?: Error | null, + result?: protos.google.monitoring.v3.IUptimeCheckConfig | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateUptimeCheckConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateUptimeCheckConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('matchGroupFromOrganizationGroupName', () => { - const result = client.matchGroupFromOrganizationGroupName(fakePath); - assert.strictEqual(result, "groupValue"); - assert((client.pathTemplates.organizationGroupPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('invokes updateUptimeCheckConfig with error', async () => { + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.UpdateUptimeCheckConfigRequest(), + ); + request.uptimeCheckConfig ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.UpdateUptimeCheckConfigRequest', + ['uptimeCheckConfig', 'name'], + ); + request.uptimeCheckConfig.name = defaultValue1; + const expectedHeaderRequestParams = `uptime_check_config.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateUptimeCheckConfig = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.updateUptimeCheckConfig(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.updateUptimeCheckConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateUptimeCheckConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - describe('organizationNotificationChannel', async () => { - const fakePath = "/rendered/path/organizationNotificationChannel"; - const expectedParameters = { - organization: "organizationValue", - notification_channel: "notificationChannelValue", - }; - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.organizationNotificationChannelPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationNotificationChannelPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationNotificationChannelPath', () => { - const result = client.organizationNotificationChannelPath("organizationValue", "notificationChannelValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationNotificationChannelPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + it('invokes updateUptimeCheckConfig with closed client', async () => { + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.UpdateUptimeCheckConfigRequest(), + ); + request.uptimeCheckConfig ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.UpdateUptimeCheckConfigRequest', + ['uptimeCheckConfig', 'name'], + ); + request.uptimeCheckConfig.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.updateUptimeCheckConfig(request), + expectedError, + ); + }); + }); + + describe('deleteUptimeCheckConfig', () => { + it('invokes deleteUptimeCheckConfig without error', async () => { + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.DeleteUptimeCheckConfigRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.DeleteUptimeCheckConfigRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteUptimeCheckConfig = + stubSimpleCall(expectedResponse); + const [response] = await client.deleteUptimeCheckConfig(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteUptimeCheckConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteUptimeCheckConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('matchOrganizationFromOrganizationNotificationChannelName', () => { - const result = client.matchOrganizationFromOrganizationNotificationChannelName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationNotificationChannelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('invokes deleteUptimeCheckConfig without error using callback', async () => { + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.DeleteUptimeCheckConfigRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.DeleteUptimeCheckConfigRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteUptimeCheckConfig = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteUptimeCheckConfig( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteUptimeCheckConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteUptimeCheckConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('matchNotificationChannelFromOrganizationNotificationChannelName', () => { - const result = client.matchNotificationChannelFromOrganizationNotificationChannelName(fakePath); - assert.strictEqual(result, "notificationChannelValue"); - assert((client.pathTemplates.organizationNotificationChannelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('invokes deleteUptimeCheckConfig with error', async () => { + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.DeleteUptimeCheckConfigRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.DeleteUptimeCheckConfigRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteUptimeCheckConfig = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.deleteUptimeCheckConfig(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.deleteUptimeCheckConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteUptimeCheckConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - describe('organizationService', async () => { - const fakePath = "/rendered/path/organizationService"; - const expectedParameters = { - organization: "organizationValue", - service: "serviceValue", - }; - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.organizationServicePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationServicePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationServicePath', () => { - const result = client.organizationServicePath("organizationValue", "serviceValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationServicePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + it('invokes deleteUptimeCheckConfig with closed client', async () => { + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.DeleteUptimeCheckConfigRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.DeleteUptimeCheckConfigRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.deleteUptimeCheckConfig(request), + expectedError, + ); + }); + }); + + describe('listUptimeCheckConfigs', () => { + it('invokes listUptimeCheckConfigs without error', async () => { + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListUptimeCheckConfigsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListUptimeCheckConfigsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.monitoring.v3.UptimeCheckConfig(), + ), + generateSampleMessage( + new protos.google.monitoring.v3.UptimeCheckConfig(), + ), + generateSampleMessage( + new protos.google.monitoring.v3.UptimeCheckConfig(), + ), + ]; + client.innerApiCalls.listUptimeCheckConfigs = + stubSimpleCall(expectedResponse); + const [response] = await client.listUptimeCheckConfigs(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listUptimeCheckConfigs as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listUptimeCheckConfigs as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('matchOrganizationFromOrganizationServiceName', () => { - const result = client.matchOrganizationFromOrganizationServiceName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationServicePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('invokes listUptimeCheckConfigs without error using callback', async () => { + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListUptimeCheckConfigsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListUptimeCheckConfigsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.monitoring.v3.UptimeCheckConfig(), + ), + generateSampleMessage( + new protos.google.monitoring.v3.UptimeCheckConfig(), + ), + generateSampleMessage( + new protos.google.monitoring.v3.UptimeCheckConfig(), + ), + ]; + client.innerApiCalls.listUptimeCheckConfigs = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listUptimeCheckConfigs( + request, + ( + err?: Error | null, + result?: protos.google.monitoring.v3.IUptimeCheckConfig[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listUptimeCheckConfigs as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listUptimeCheckConfigs as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('matchServiceFromOrganizationServiceName', () => { - const result = client.matchServiceFromOrganizationServiceName(fakePath); - assert.strictEqual(result, "serviceValue"); - assert((client.pathTemplates.organizationServicePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('invokes listUptimeCheckConfigs with error', async () => { + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListUptimeCheckConfigsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListUptimeCheckConfigsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listUptimeCheckConfigs = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.listUptimeCheckConfigs(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.listUptimeCheckConfigs as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listUptimeCheckConfigs as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - describe('organizationServiceServiceLevelObjective', async () => { - const fakePath = "/rendered/path/organizationServiceServiceLevelObjective"; - const expectedParameters = { - organization: "organizationValue", - service: "serviceValue", - service_level_objective: "serviceLevelObjectiveValue", - }; - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationServiceServiceLevelObjectivePath', () => { - const result = client.organizationServiceServiceLevelObjectivePath("organizationValue", "serviceValue", "serviceLevelObjectiveValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + it('invokes listUptimeCheckConfigsStream without error', async () => { + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListUptimeCheckConfigsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListUptimeCheckConfigsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.monitoring.v3.UptimeCheckConfig(), + ), + generateSampleMessage( + new protos.google.monitoring.v3.UptimeCheckConfig(), + ), + generateSampleMessage( + new protos.google.monitoring.v3.UptimeCheckConfig(), + ), + ]; + client.descriptors.page.listUptimeCheckConfigs.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listUptimeCheckConfigsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.monitoring.v3.UptimeCheckConfig[] = []; + stream.on( + 'data', + (response: protos.google.monitoring.v3.UptimeCheckConfig) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + ( + client.descriptors.page.listUptimeCheckConfigs + .createStream as SinonStub + ) + .getCall(0) + .calledWith(client.innerApiCalls.listUptimeCheckConfigs, request), + ); + assert( + ( + client.descriptors.page.listUptimeCheckConfigs + .createStream as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); - it('matchOrganizationFromOrganizationServiceServiceLevelObjectiveName', () => { - const result = client.matchOrganizationFromOrganizationServiceServiceLevelObjectiveName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('invokes listUptimeCheckConfigsStream with error', async () => { + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListUptimeCheckConfigsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListUptimeCheckConfigsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listUptimeCheckConfigs.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listUptimeCheckConfigsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.monitoring.v3.UptimeCheckConfig[] = []; + stream.on( + 'data', + (response: protos.google.monitoring.v3.UptimeCheckConfig) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + ( + client.descriptors.page.listUptimeCheckConfigs + .createStream as SinonStub + ) + .getCall(0) + .calledWith(client.innerApiCalls.listUptimeCheckConfigs, request), + ); + assert( + ( + client.descriptors.page.listUptimeCheckConfigs + .createStream as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); - it('matchServiceFromOrganizationServiceServiceLevelObjectiveName', () => { - const result = client.matchServiceFromOrganizationServiceServiceLevelObjectiveName(fakePath); - assert.strictEqual(result, "serviceValue"); - assert((client.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('uses async iteration with listUptimeCheckConfigs without error', async () => { + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListUptimeCheckConfigsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListUptimeCheckConfigsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.monitoring.v3.UptimeCheckConfig(), + ), + generateSampleMessage( + new protos.google.monitoring.v3.UptimeCheckConfig(), + ), + generateSampleMessage( + new protos.google.monitoring.v3.UptimeCheckConfig(), + ), + ]; + client.descriptors.page.listUptimeCheckConfigs.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.monitoring.v3.IUptimeCheckConfig[] = []; + const iterable = client.listUptimeCheckConfigsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listUptimeCheckConfigs + .asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + ( + client.descriptors.page.listUptimeCheckConfigs + .asyncIterate as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); - it('matchServiceLevelObjectiveFromOrganizationServiceServiceLevelObjectiveName', () => { - const result = client.matchServiceLevelObjectiveFromOrganizationServiceServiceLevelObjectiveName(fakePath); - assert.strictEqual(result, "serviceLevelObjectiveValue"); - assert((client.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('uses async iteration with listUptimeCheckConfigs with error', async () => { + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListUptimeCheckConfigsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.monitoring.v3.ListUptimeCheckConfigsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listUptimeCheckConfigs.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listUptimeCheckConfigsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.monitoring.v3.IUptimeCheckConfig[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listUptimeCheckConfigs + .asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + ( + client.descriptors.page.listUptimeCheckConfigs + .asyncIterate as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); + }); + + describe('listUptimeCheckIps', () => { + it('invokes listUptimeCheckIps without error', async () => { + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListUptimeCheckIpsRequest(), + ); + const expectedResponse = [ + generateSampleMessage(new protos.google.monitoring.v3.UptimeCheckIp()), + generateSampleMessage(new protos.google.monitoring.v3.UptimeCheckIp()), + generateSampleMessage(new protos.google.monitoring.v3.UptimeCheckIp()), + ]; + client.innerApiCalls.listUptimeCheckIps = + stubSimpleCall(expectedResponse); + const [response] = await client.listUptimeCheckIps(request); + assert.deepStrictEqual(response, expectedResponse); + }); - describe('organizationUptimeCheckConfig', async () => { - const fakePath = "/rendered/path/organizationUptimeCheckConfig"; - const expectedParameters = { - organization: "organizationValue", - uptime_check_config: "uptimeCheckConfigValue", - }; - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.organizationUptimeCheckConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationUptimeCheckConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationUptimeCheckConfigPath', () => { - const result = client.organizationUptimeCheckConfigPath("organizationValue", "uptimeCheckConfigValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationUptimeCheckConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + it('invokes listUptimeCheckIps without error using callback', async () => { + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListUptimeCheckIpsRequest(), + ); + const expectedResponse = [ + generateSampleMessage(new protos.google.monitoring.v3.UptimeCheckIp()), + generateSampleMessage(new protos.google.monitoring.v3.UptimeCheckIp()), + generateSampleMessage(new protos.google.monitoring.v3.UptimeCheckIp()), + ]; + client.innerApiCalls.listUptimeCheckIps = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listUptimeCheckIps( + request, + ( + err?: Error | null, + result?: protos.google.monitoring.v3.IUptimeCheckIp[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); - it('matchOrganizationFromOrganizationUptimeCheckConfigName', () => { - const result = client.matchOrganizationFromOrganizationUptimeCheckConfigName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationUptimeCheckConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('invokes listUptimeCheckIps with error', async () => { + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListUptimeCheckIpsRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.listUptimeCheckIps = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listUptimeCheckIps(request), expectedError); + }); - it('matchUptimeCheckConfigFromOrganizationUptimeCheckConfigName', () => { - const result = client.matchUptimeCheckConfigFromOrganizationUptimeCheckConfigName(fakePath); - assert.strictEqual(result, "uptimeCheckConfigValue"); - assert((client.pathTemplates.organizationUptimeCheckConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('invokes listUptimeCheckIpsStream without error', async () => { + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListUptimeCheckIpsRequest(), + ); + const expectedResponse = [ + generateSampleMessage(new protos.google.monitoring.v3.UptimeCheckIp()), + generateSampleMessage(new protos.google.monitoring.v3.UptimeCheckIp()), + generateSampleMessage(new protos.google.monitoring.v3.UptimeCheckIp()), + ]; + client.descriptors.page.listUptimeCheckIps.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listUptimeCheckIpsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.monitoring.v3.UptimeCheckIp[] = []; + stream.on( + 'data', + (response: protos.google.monitoring.v3.UptimeCheckIp) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listUptimeCheckIps.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listUptimeCheckIps, request), + ); + }); - describe('projectAlertPolicy', async () => { - const fakePath = "/rendered/path/projectAlertPolicy"; - const expectedParameters = { - project: "projectValue", - alert_policy: "alertPolicyValue", - }; - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.projectAlertPolicyPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectAlertPolicyPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectAlertPolicyPath', () => { - const result = client.projectAlertPolicyPath("projectValue", "alertPolicyValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectAlertPolicyPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + it('invokes listUptimeCheckIpsStream with error', async () => { + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListUptimeCheckIpsRequest(), + ); + const expectedError = new Error('expected'); + client.descriptors.page.listUptimeCheckIps.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listUptimeCheckIpsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.monitoring.v3.UptimeCheckIp[] = []; + stream.on( + 'data', + (response: protos.google.monitoring.v3.UptimeCheckIp) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listUptimeCheckIps.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listUptimeCheckIps, request), + ); + }); - it('matchProjectFromProjectAlertPolicyName', () => { - const result = client.matchProjectFromProjectAlertPolicyName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectAlertPolicyPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('uses async iteration with listUptimeCheckIps without error', async () => { + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListUptimeCheckIpsRequest(), + ); + const expectedResponse = [ + generateSampleMessage(new protos.google.monitoring.v3.UptimeCheckIp()), + generateSampleMessage(new protos.google.monitoring.v3.UptimeCheckIp()), + generateSampleMessage(new protos.google.monitoring.v3.UptimeCheckIp()), + ]; + client.descriptors.page.listUptimeCheckIps.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.monitoring.v3.IUptimeCheckIp[] = []; + const iterable = client.listUptimeCheckIpsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listUptimeCheckIps.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + }); - it('matchAlertPolicyFromProjectAlertPolicyName', () => { - const result = client.matchAlertPolicyFromProjectAlertPolicyName(fakePath); - assert.strictEqual(result, "alertPolicyValue"); - assert((client.pathTemplates.projectAlertPolicyPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('uses async iteration with listUptimeCheckIps with error', async () => { + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.monitoring.v3.ListUptimeCheckIpsRequest(), + ); + const expectedError = new Error('expected'); + client.descriptors.page.listUptimeCheckIps.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listUptimeCheckIpsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.monitoring.v3.IUptimeCheckIp[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listUptimeCheckIps.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + }); + }); + + describe('Path templates', () => { + describe('folderAlertPolicy', async () => { + const fakePath = '/rendered/path/folderAlertPolicy'; + const expectedParameters = { + folder: 'folderValue', + alert_policy: 'alertPolicyValue', + }; + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.folderAlertPolicyPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderAlertPolicyPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderAlertPolicyPath', () => { + const result = client.folderAlertPolicyPath( + 'folderValue', + 'alertPolicyValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.folderAlertPolicyPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderAlertPolicyName', () => { + const result = client.matchFolderFromFolderAlertPolicyName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + ( + client.pathTemplates.folderAlertPolicyPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchAlertPolicyFromFolderAlertPolicyName', () => { + const result = + client.matchAlertPolicyFromFolderAlertPolicyName(fakePath); + assert.strictEqual(result, 'alertPolicyValue'); + assert( + ( + client.pathTemplates.folderAlertPolicyPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectAlertPolicyCondition', async () => { - const fakePath = "/rendered/path/projectAlertPolicyCondition"; - const expectedParameters = { - project: "projectValue", - alert_policy: "alertPolicyValue", - condition: "conditionValue", - }; - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.projectAlertPolicyConditionPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectAlertPolicyConditionPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectAlertPolicyConditionPath', () => { - const result = client.projectAlertPolicyConditionPath("projectValue", "alertPolicyValue", "conditionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectAlertPolicyConditionPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + describe('folderAlertPolicyCondition', async () => { + const fakePath = '/rendered/path/folderAlertPolicyCondition'; + const expectedParameters = { + folder: 'folderValue', + alert_policy: 'alertPolicyValue', + condition: 'conditionValue', + }; + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.folderAlertPolicyConditionPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderAlertPolicyConditionPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderAlertPolicyConditionPath', () => { + const result = client.folderAlertPolicyConditionPath( + 'folderValue', + 'alertPolicyValue', + 'conditionValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.folderAlertPolicyConditionPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderAlertPolicyConditionName', () => { + const result = + client.matchFolderFromFolderAlertPolicyConditionName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + ( + client.pathTemplates.folderAlertPolicyConditionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchAlertPolicyFromFolderAlertPolicyConditionName', () => { + const result = + client.matchAlertPolicyFromFolderAlertPolicyConditionName(fakePath); + assert.strictEqual(result, 'alertPolicyValue'); + assert( + ( + client.pathTemplates.folderAlertPolicyConditionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchConditionFromFolderAlertPolicyConditionName', () => { + const result = + client.matchConditionFromFolderAlertPolicyConditionName(fakePath); + assert.strictEqual(result, 'conditionValue'); + assert( + ( + client.pathTemplates.folderAlertPolicyConditionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchProjectFromProjectAlertPolicyConditionName', () => { - const result = client.matchProjectFromProjectAlertPolicyConditionName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectAlertPolicyConditionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('folderChannelDescriptor', async () => { + const fakePath = '/rendered/path/folderChannelDescriptor'; + const expectedParameters = { + folder: 'folderValue', + channel_descriptor: 'channelDescriptorValue', + }; + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.folderChannelDescriptorPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderChannelDescriptorPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderChannelDescriptorPath', () => { + const result = client.folderChannelDescriptorPath( + 'folderValue', + 'channelDescriptorValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.folderChannelDescriptorPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderChannelDescriptorName', () => { + const result = + client.matchFolderFromFolderChannelDescriptorName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + ( + client.pathTemplates.folderChannelDescriptorPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchChannelDescriptorFromFolderChannelDescriptorName', () => { + const result = + client.matchChannelDescriptorFromFolderChannelDescriptorName( + fakePath, + ); + assert.strictEqual(result, 'channelDescriptorValue'); + assert( + ( + client.pathTemplates.folderChannelDescriptorPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchAlertPolicyFromProjectAlertPolicyConditionName', () => { - const result = client.matchAlertPolicyFromProjectAlertPolicyConditionName(fakePath); - assert.strictEqual(result, "alertPolicyValue"); - assert((client.pathTemplates.projectAlertPolicyConditionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('folderGroup', async () => { + const fakePath = '/rendered/path/folderGroup'; + const expectedParameters = { + folder: 'folderValue', + group: 'groupValue', + }; + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.folderGroupPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderGroupPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderGroupPath', () => { + const result = client.folderGroupPath('folderValue', 'groupValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.folderGroupPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderGroupName', () => { + const result = client.matchFolderFromFolderGroupName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + (client.pathTemplates.folderGroupPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchGroupFromFolderGroupName', () => { + const result = client.matchGroupFromFolderGroupName(fakePath); + assert.strictEqual(result, 'groupValue'); + assert( + (client.pathTemplates.folderGroupPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchConditionFromProjectAlertPolicyConditionName', () => { - const result = client.matchConditionFromProjectAlertPolicyConditionName(fakePath); - assert.strictEqual(result, "conditionValue"); - assert((client.pathTemplates.projectAlertPolicyConditionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('folderNotificationChannel', async () => { + const fakePath = '/rendered/path/folderNotificationChannel'; + const expectedParameters = { + folder: 'folderValue', + notification_channel: 'notificationChannelValue', + }; + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.folderNotificationChannelPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderNotificationChannelPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderNotificationChannelPath', () => { + const result = client.folderNotificationChannelPath( + 'folderValue', + 'notificationChannelValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.folderNotificationChannelPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderNotificationChannelName', () => { + const result = + client.matchFolderFromFolderNotificationChannelName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + ( + client.pathTemplates.folderNotificationChannelPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchNotificationChannelFromFolderNotificationChannelName', () => { + const result = + client.matchNotificationChannelFromFolderNotificationChannelName( + fakePath, + ); + assert.strictEqual(result, 'notificationChannelValue'); + assert( + ( + client.pathTemplates.folderNotificationChannelPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectChannelDescriptor', async () => { - const fakePath = "/rendered/path/projectChannelDescriptor"; - const expectedParameters = { - project: "projectValue", - channel_descriptor: "channelDescriptorValue", - }; - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.projectChannelDescriptorPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectChannelDescriptorPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectChannelDescriptorPath', () => { - const result = client.projectChannelDescriptorPath("projectValue", "channelDescriptorValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectChannelDescriptorPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + describe('folderService', async () => { + const fakePath = '/rendered/path/folderService'; + const expectedParameters = { + folder: 'folderValue', + service: 'serviceValue', + }; + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.folderServicePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderServicePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderServicePath', () => { + const result = client.folderServicePath('folderValue', 'serviceValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.folderServicePathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderServiceName', () => { + const result = client.matchFolderFromFolderServiceName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + (client.pathTemplates.folderServicePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServiceFromFolderServiceName', () => { + const result = client.matchServiceFromFolderServiceName(fakePath); + assert.strictEqual(result, 'serviceValue'); + assert( + (client.pathTemplates.folderServicePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchProjectFromProjectChannelDescriptorName', () => { - const result = client.matchProjectFromProjectChannelDescriptorName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectChannelDescriptorPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('folderServiceServiceLevelObjective', async () => { + const fakePath = '/rendered/path/folderServiceServiceLevelObjective'; + const expectedParameters = { + folder: 'folderValue', + service: 'serviceValue', + service_level_objective: 'serviceLevelObjectiveValue', + }; + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('folderServiceServiceLevelObjectivePath', () => { + const result = client.folderServiceServiceLevelObjectivePath( + 'folderValue', + 'serviceValue', + 'serviceLevelObjectiveValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderServiceServiceLevelObjectiveName', () => { + const result = + client.matchFolderFromFolderServiceServiceLevelObjectiveName( + fakePath, + ); + assert.strictEqual(result, 'folderValue'); + assert( + ( + client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServiceFromFolderServiceServiceLevelObjectiveName', () => { + const result = + client.matchServiceFromFolderServiceServiceLevelObjectiveName( + fakePath, + ); + assert.strictEqual(result, 'serviceValue'); + assert( + ( + client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServiceLevelObjectiveFromFolderServiceServiceLevelObjectiveName', () => { + const result = + client.matchServiceLevelObjectiveFromFolderServiceServiceLevelObjectiveName( + fakePath, + ); + assert.strictEqual(result, 'serviceLevelObjectiveValue'); + assert( + ( + client.pathTemplates.folderServiceServiceLevelObjectivePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchChannelDescriptorFromProjectChannelDescriptorName', () => { - const result = client.matchChannelDescriptorFromProjectChannelDescriptorName(fakePath); - assert.strictEqual(result, "channelDescriptorValue"); - assert((client.pathTemplates.projectChannelDescriptorPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('folderUptimeCheckConfig', async () => { + const fakePath = '/rendered/path/folderUptimeCheckConfig'; + const expectedParameters = { + folder: 'folderValue', + uptime_check_config: 'uptimeCheckConfigValue', + }; + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.folderUptimeCheckConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.folderUptimeCheckConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('folderUptimeCheckConfigPath', () => { + const result = client.folderUptimeCheckConfigPath( + 'folderValue', + 'uptimeCheckConfigValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.folderUptimeCheckConfigPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderUptimeCheckConfigName', () => { + const result = + client.matchFolderFromFolderUptimeCheckConfigName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + ( + client.pathTemplates.folderUptimeCheckConfigPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchUptimeCheckConfigFromFolderUptimeCheckConfigName', () => { + const result = + client.matchUptimeCheckConfigFromFolderUptimeCheckConfigName( + fakePath, + ); + assert.strictEqual(result, 'uptimeCheckConfigValue'); + assert( + ( + client.pathTemplates.folderUptimeCheckConfigPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectGroup', async () => { - const fakePath = "/rendered/path/projectGroup"; - const expectedParameters = { - project: "projectValue", - group: "groupValue", - }; - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.projectGroupPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectGroupPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectGroupPath', () => { - const result = client.projectGroupPath("projectValue", "groupValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectGroupPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + describe('organizationAlertPolicy', async () => { + const fakePath = '/rendered/path/organizationAlertPolicy'; + const expectedParameters = { + organization: 'organizationValue', + alert_policy: 'alertPolicyValue', + }; + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.organizationAlertPolicyPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.organizationAlertPolicyPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('organizationAlertPolicyPath', () => { + const result = client.organizationAlertPolicyPath( + 'organizationValue', + 'alertPolicyValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationAlertPolicyPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationAlertPolicyName', () => { + const result = + client.matchOrganizationFromOrganizationAlertPolicyName(fakePath); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationAlertPolicyPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchAlertPolicyFromOrganizationAlertPolicyName', () => { + const result = + client.matchAlertPolicyFromOrganizationAlertPolicyName(fakePath); + assert.strictEqual(result, 'alertPolicyValue'); + assert( + ( + client.pathTemplates.organizationAlertPolicyPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchProjectFromProjectGroupName', () => { - const result = client.matchProjectFromProjectGroupName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectGroupPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('organizationAlertPolicyCondition', async () => { + const fakePath = '/rendered/path/organizationAlertPolicyCondition'; + const expectedParameters = { + organization: 'organizationValue', + alert_policy: 'alertPolicyValue', + condition: 'conditionValue', + }; + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.organizationAlertPolicyConditionPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.organizationAlertPolicyConditionPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('organizationAlertPolicyConditionPath', () => { + const result = client.organizationAlertPolicyConditionPath( + 'organizationValue', + 'alertPolicyValue', + 'conditionValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationAlertPolicyConditionPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationAlertPolicyConditionName', () => { + const result = + client.matchOrganizationFromOrganizationAlertPolicyConditionName( + fakePath, + ); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationAlertPolicyConditionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchAlertPolicyFromOrganizationAlertPolicyConditionName', () => { + const result = + client.matchAlertPolicyFromOrganizationAlertPolicyConditionName( + fakePath, + ); + assert.strictEqual(result, 'alertPolicyValue'); + assert( + ( + client.pathTemplates.organizationAlertPolicyConditionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchConditionFromOrganizationAlertPolicyConditionName', () => { + const result = + client.matchConditionFromOrganizationAlertPolicyConditionName( + fakePath, + ); + assert.strictEqual(result, 'conditionValue'); + assert( + ( + client.pathTemplates.organizationAlertPolicyConditionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchGroupFromProjectGroupName', () => { - const result = client.matchGroupFromProjectGroupName(fakePath); - assert.strictEqual(result, "groupValue"); - assert((client.pathTemplates.projectGroupPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('organizationChannelDescriptor', async () => { + const fakePath = '/rendered/path/organizationChannelDescriptor'; + const expectedParameters = { + organization: 'organizationValue', + channel_descriptor: 'channelDescriptorValue', + }; + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.organizationChannelDescriptorPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.organizationChannelDescriptorPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('organizationChannelDescriptorPath', () => { + const result = client.organizationChannelDescriptorPath( + 'organizationValue', + 'channelDescriptorValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationChannelDescriptorPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationChannelDescriptorName', () => { + const result = + client.matchOrganizationFromOrganizationChannelDescriptorName( + fakePath, + ); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationChannelDescriptorPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchChannelDescriptorFromOrganizationChannelDescriptorName', () => { + const result = + client.matchChannelDescriptorFromOrganizationChannelDescriptorName( + fakePath, + ); + assert.strictEqual(result, 'channelDescriptorValue'); + assert( + ( + client.pathTemplates.organizationChannelDescriptorPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectNotificationChannel', async () => { - const fakePath = "/rendered/path/projectNotificationChannel"; - const expectedParameters = { - project: "projectValue", - notification_channel: "notificationChannelValue", - }; - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.projectNotificationChannelPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectNotificationChannelPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectNotificationChannelPath', () => { - const result = client.projectNotificationChannelPath("projectValue", "notificationChannelValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectNotificationChannelPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + describe('organizationGroup', async () => { + const fakePath = '/rendered/path/organizationGroup'; + const expectedParameters = { + organization: 'organizationValue', + group: 'groupValue', + }; + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.organizationGroupPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.organizationGroupPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('organizationGroupPath', () => { + const result = client.organizationGroupPath( + 'organizationValue', + 'groupValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationGroupPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationGroupName', () => { + const result = + client.matchOrganizationFromOrganizationGroupName(fakePath); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationGroupPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchGroupFromOrganizationGroupName', () => { + const result = client.matchGroupFromOrganizationGroupName(fakePath); + assert.strictEqual(result, 'groupValue'); + assert( + ( + client.pathTemplates.organizationGroupPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchProjectFromProjectNotificationChannelName', () => { - const result = client.matchProjectFromProjectNotificationChannelName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectNotificationChannelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('organizationNotificationChannel', async () => { + const fakePath = '/rendered/path/organizationNotificationChannel'; + const expectedParameters = { + organization: 'organizationValue', + notification_channel: 'notificationChannelValue', + }; + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.organizationNotificationChannelPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.organizationNotificationChannelPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('organizationNotificationChannelPath', () => { + const result = client.organizationNotificationChannelPath( + 'organizationValue', + 'notificationChannelValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationNotificationChannelPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationNotificationChannelName', () => { + const result = + client.matchOrganizationFromOrganizationNotificationChannelName( + fakePath, + ); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationNotificationChannelPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchNotificationChannelFromOrganizationNotificationChannelName', () => { + const result = + client.matchNotificationChannelFromOrganizationNotificationChannelName( + fakePath, + ); + assert.strictEqual(result, 'notificationChannelValue'); + assert( + ( + client.pathTemplates.organizationNotificationChannelPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchNotificationChannelFromProjectNotificationChannelName', () => { - const result = client.matchNotificationChannelFromProjectNotificationChannelName(fakePath); - assert.strictEqual(result, "notificationChannelValue"); - assert((client.pathTemplates.projectNotificationChannelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('organizationService', async () => { + const fakePath = '/rendered/path/organizationService'; + const expectedParameters = { + organization: 'organizationValue', + service: 'serviceValue', + }; + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.organizationServicePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.organizationServicePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('organizationServicePath', () => { + const result = client.organizationServicePath( + 'organizationValue', + 'serviceValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationServicePathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationServiceName', () => { + const result = + client.matchOrganizationFromOrganizationServiceName(fakePath); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationServicePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServiceFromOrganizationServiceName', () => { + const result = client.matchServiceFromOrganizationServiceName(fakePath); + assert.strictEqual(result, 'serviceValue'); + assert( + ( + client.pathTemplates.organizationServicePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectService', async () => { - const fakePath = "/rendered/path/projectService"; - const expectedParameters = { - project: "projectValue", - service: "serviceValue", - }; - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.projectServicePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectServicePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectServicePath', () => { - const result = client.projectServicePath("projectValue", "serviceValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectServicePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + describe('organizationServiceServiceLevelObjective', async () => { + const fakePath = + '/rendered/path/organizationServiceServiceLevelObjective'; + const expectedParameters = { + organization: 'organizationValue', + service: 'serviceValue', + service_level_objective: 'serviceLevelObjectiveValue', + }; + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.organizationServiceServiceLevelObjectivePathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('organizationServiceServiceLevelObjectivePath', () => { + const result = client.organizationServiceServiceLevelObjectivePath( + 'organizationValue', + 'serviceValue', + 'serviceLevelObjectiveValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates + .organizationServiceServiceLevelObjectivePathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationServiceServiceLevelObjectiveName', () => { + const result = + client.matchOrganizationFromOrganizationServiceServiceLevelObjectiveName( + fakePath, + ); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates + .organizationServiceServiceLevelObjectivePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServiceFromOrganizationServiceServiceLevelObjectiveName', () => { + const result = + client.matchServiceFromOrganizationServiceServiceLevelObjectiveName( + fakePath, + ); + assert.strictEqual(result, 'serviceValue'); + assert( + ( + client.pathTemplates + .organizationServiceServiceLevelObjectivePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServiceLevelObjectiveFromOrganizationServiceServiceLevelObjectiveName', () => { + const result = + client.matchServiceLevelObjectiveFromOrganizationServiceServiceLevelObjectiveName( + fakePath, + ); + assert.strictEqual(result, 'serviceLevelObjectiveValue'); + assert( + ( + client.pathTemplates + .organizationServiceServiceLevelObjectivePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchProjectFromProjectServiceName', () => { - const result = client.matchProjectFromProjectServiceName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectServicePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('organizationUptimeCheckConfig', async () => { + const fakePath = '/rendered/path/organizationUptimeCheckConfig'; + const expectedParameters = { + organization: 'organizationValue', + uptime_check_config: 'uptimeCheckConfigValue', + }; + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.organizationUptimeCheckConfigPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.organizationUptimeCheckConfigPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('organizationUptimeCheckConfigPath', () => { + const result = client.organizationUptimeCheckConfigPath( + 'organizationValue', + 'uptimeCheckConfigValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationUptimeCheckConfigPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationUptimeCheckConfigName', () => { + const result = + client.matchOrganizationFromOrganizationUptimeCheckConfigName( + fakePath, + ); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationUptimeCheckConfigPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchUptimeCheckConfigFromOrganizationUptimeCheckConfigName', () => { + const result = + client.matchUptimeCheckConfigFromOrganizationUptimeCheckConfigName( + fakePath, + ); + assert.strictEqual(result, 'uptimeCheckConfigValue'); + assert( + ( + client.pathTemplates.organizationUptimeCheckConfigPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchServiceFromProjectServiceName', () => { - const result = client.matchServiceFromProjectServiceName(fakePath); - assert.strictEqual(result, "serviceValue"); - assert((client.pathTemplates.projectServicePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectAlertPolicy', async () => { + const fakePath = '/rendered/path/projectAlertPolicy'; + const expectedParameters = { + project: 'projectValue', + alert_policy: 'alertPolicyValue', + }; + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.projectAlertPolicyPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectAlertPolicyPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectAlertPolicyPath', () => { + const result = client.projectAlertPolicyPath( + 'projectValue', + 'alertPolicyValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.projectAlertPolicyPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectAlertPolicyName', () => { + const result = client.matchProjectFromProjectAlertPolicyName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.projectAlertPolicyPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchAlertPolicyFromProjectAlertPolicyName', () => { + const result = + client.matchAlertPolicyFromProjectAlertPolicyName(fakePath); + assert.strictEqual(result, 'alertPolicyValue'); + assert( + ( + client.pathTemplates.projectAlertPolicyPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectServiceServiceLevelObjective', async () => { - const fakePath = "/rendered/path/projectServiceServiceLevelObjective"; - const expectedParameters = { - project: "projectValue", - service: "serviceValue", - service_level_objective: "serviceLevelObjectiveValue", - }; - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectServiceServiceLevelObjectivePath', () => { - const result = client.projectServiceServiceLevelObjectivePath("projectValue", "serviceValue", "serviceLevelObjectiveValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + describe('projectAlertPolicyCondition', async () => { + const fakePath = '/rendered/path/projectAlertPolicyCondition'; + const expectedParameters = { + project: 'projectValue', + alert_policy: 'alertPolicyValue', + condition: 'conditionValue', + }; + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.projectAlertPolicyConditionPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.projectAlertPolicyConditionPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectAlertPolicyConditionPath', () => { + const result = client.projectAlertPolicyConditionPath( + 'projectValue', + 'alertPolicyValue', + 'conditionValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.projectAlertPolicyConditionPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectAlertPolicyConditionName', () => { + const result = + client.matchProjectFromProjectAlertPolicyConditionName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.projectAlertPolicyConditionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchAlertPolicyFromProjectAlertPolicyConditionName', () => { + const result = + client.matchAlertPolicyFromProjectAlertPolicyConditionName(fakePath); + assert.strictEqual(result, 'alertPolicyValue'); + assert( + ( + client.pathTemplates.projectAlertPolicyConditionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchConditionFromProjectAlertPolicyConditionName', () => { + const result = + client.matchConditionFromProjectAlertPolicyConditionName(fakePath); + assert.strictEqual(result, 'conditionValue'); + assert( + ( + client.pathTemplates.projectAlertPolicyConditionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchProjectFromProjectServiceServiceLevelObjectiveName', () => { - const result = client.matchProjectFromProjectServiceServiceLevelObjectiveName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('projectChannelDescriptor', async () => { + const fakePath = '/rendered/path/projectChannelDescriptor'; + const expectedParameters = { + project: 'projectValue', + channel_descriptor: 'channelDescriptorValue', + }; + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.projectChannelDescriptorPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectChannelDescriptorPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectChannelDescriptorPath', () => { + const result = client.projectChannelDescriptorPath( + 'projectValue', + 'channelDescriptorValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.projectChannelDescriptorPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectChannelDescriptorName', () => { + const result = + client.matchProjectFromProjectChannelDescriptorName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.projectChannelDescriptorPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchChannelDescriptorFromProjectChannelDescriptorName', () => { + const result = + client.matchChannelDescriptorFromProjectChannelDescriptorName( + fakePath, + ); + assert.strictEqual(result, 'channelDescriptorValue'); + assert( + ( + client.pathTemplates.projectChannelDescriptorPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchServiceFromProjectServiceServiceLevelObjectiveName', () => { - const result = client.matchServiceFromProjectServiceServiceLevelObjectiveName(fakePath); - assert.strictEqual(result, "serviceValue"); - assert((client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('projectGroup', async () => { + const fakePath = '/rendered/path/projectGroup'; + const expectedParameters = { + project: 'projectValue', + group: 'groupValue', + }; + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.projectGroupPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectGroupPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectGroupPath', () => { + const result = client.projectGroupPath('projectValue', 'groupValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.projectGroupPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectGroupName', () => { + const result = client.matchProjectFromProjectGroupName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.projectGroupPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchGroupFromProjectGroupName', () => { + const result = client.matchGroupFromProjectGroupName(fakePath); + assert.strictEqual(result, 'groupValue'); + assert( + (client.pathTemplates.projectGroupPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchServiceLevelObjectiveFromProjectServiceServiceLevelObjectiveName', () => { - const result = client.matchServiceLevelObjectiveFromProjectServiceServiceLevelObjectiveName(fakePath); - assert.strictEqual(result, "serviceLevelObjectiveValue"); - assert((client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectNotificationChannel', async () => { + const fakePath = '/rendered/path/projectNotificationChannel'; + const expectedParameters = { + project: 'projectValue', + notification_channel: 'notificationChannelValue', + }; + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.projectNotificationChannelPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectNotificationChannelPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectNotificationChannelPath', () => { + const result = client.projectNotificationChannelPath( + 'projectValue', + 'notificationChannelValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.projectNotificationChannelPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectNotificationChannelName', () => { + const result = + client.matchProjectFromProjectNotificationChannelName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.projectNotificationChannelPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchNotificationChannelFromProjectNotificationChannelName', () => { + const result = + client.matchNotificationChannelFromProjectNotificationChannelName( + fakePath, + ); + assert.strictEqual(result, 'notificationChannelValue'); + assert( + ( + client.pathTemplates.projectNotificationChannelPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectUptimeCheckConfig', async () => { - const fakePath = "/rendered/path/projectUptimeCheckConfig"; - const expectedParameters = { - project: "projectValue", - uptime_check_config: "uptimeCheckConfigValue", - }; - const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.projectUptimeCheckConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectUptimeCheckConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectUptimeCheckConfigPath', () => { - const result = client.projectUptimeCheckConfigPath("projectValue", "uptimeCheckConfigValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectUptimeCheckConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + describe('projectService', async () => { + const fakePath = '/rendered/path/projectService'; + const expectedParameters = { + project: 'projectValue', + service: 'serviceValue', + }; + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.projectServicePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectServicePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectServicePath', () => { + const result = client.projectServicePath( + 'projectValue', + 'serviceValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.projectServicePathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectServiceName', () => { + const result = client.matchProjectFromProjectServiceName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.projectServicePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServiceFromProjectServiceName', () => { + const result = client.matchServiceFromProjectServiceName(fakePath); + assert.strictEqual(result, 'serviceValue'); + assert( + (client.pathTemplates.projectServicePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchProjectFromProjectUptimeCheckConfigName', () => { - const result = client.matchProjectFromProjectUptimeCheckConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectUptimeCheckConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('projectServiceServiceLevelObjective', async () => { + const fakePath = '/rendered/path/projectServiceServiceLevelObjective'; + const expectedParameters = { + project: 'projectValue', + service: 'serviceValue', + service_level_objective: 'serviceLevelObjectiveValue', + }; + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('projectServiceServiceLevelObjectivePath', () => { + const result = client.projectServiceServiceLevelObjectivePath( + 'projectValue', + 'serviceValue', + 'serviceLevelObjectiveValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectServiceServiceLevelObjectiveName', () => { + const result = + client.matchProjectFromProjectServiceServiceLevelObjectiveName( + fakePath, + ); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServiceFromProjectServiceServiceLevelObjectiveName', () => { + const result = + client.matchServiceFromProjectServiceServiceLevelObjectiveName( + fakePath, + ); + assert.strictEqual(result, 'serviceValue'); + assert( + ( + client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServiceLevelObjectiveFromProjectServiceServiceLevelObjectiveName', () => { + const result = + client.matchServiceLevelObjectiveFromProjectServiceServiceLevelObjectiveName( + fakePath, + ); + assert.strictEqual(result, 'serviceLevelObjectiveValue'); + assert( + ( + client.pathTemplates.projectServiceServiceLevelObjectivePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchUptimeCheckConfigFromProjectUptimeCheckConfigName', () => { - const result = client.matchUptimeCheckConfigFromProjectUptimeCheckConfigName(fakePath); - assert.strictEqual(result, "uptimeCheckConfigValue"); - assert((client.pathTemplates.projectUptimeCheckConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectUptimeCheckConfig', async () => { + const fakePath = '/rendered/path/projectUptimeCheckConfig'; + const expectedParameters = { + project: 'projectValue', + uptime_check_config: 'uptimeCheckConfigValue', + }; + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.projectUptimeCheckConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectUptimeCheckConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectUptimeCheckConfigPath', () => { + const result = client.projectUptimeCheckConfigPath( + 'projectValue', + 'uptimeCheckConfigValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.projectUptimeCheckConfigPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectUptimeCheckConfigName', () => { + const result = + client.matchProjectFromProjectUptimeCheckConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.projectUptimeCheckConfigPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchUptimeCheckConfigFromProjectUptimeCheckConfigName', () => { + const result = + client.matchUptimeCheckConfigFromProjectUptimeCheckConfigName( + fakePath, + ); + assert.strictEqual(result, 'uptimeCheckConfigValue'); + assert( + ( + client.pathTemplates.projectUptimeCheckConfigPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/core/generator/gapic-generator-typescript/baselines/naming-esm/esm/src/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/naming-esm/esm/src/index.ts.baseline index 98db848be491..c66610302ad3 100644 --- a/core/generator/gapic-generator-typescript/baselines/naming-esm/esm/src/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/naming-esm/esm/src/index.ts.baseline @@ -19,8 +19,8 @@ import * as v1beta1 from './v1beta1/index.js'; const NamingClient = v1beta1.NamingClient; type NamingClient = v1beta1.NamingClient; -export {v1beta1, NamingClient}; -export default {v1beta1, NamingClient}; +export { v1beta1, NamingClient }; +export default { v1beta1, NamingClient }; // @ts-ignore import * as protos from '../../protos/protos.js'; -export {protos} +export { protos }; diff --git a/core/generator/gapic-generator-typescript/baselines/naming-esm/esm/src/v1beta1/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/naming-esm/esm/src/v1beta1/index.ts.baseline index 683bf07138b2..915ab15926f9 100644 --- a/core/generator/gapic-generator-typescript/baselines/naming-esm/esm/src/v1beta1/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/naming-esm/esm/src/v1beta1/index.ts.baseline @@ -16,4 +16,4 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -export {NamingClient} from './naming_client.js'; +export { NamingClient } from './naming_client.js'; diff --git a/core/generator/gapic-generator-typescript/baselines/naming-esm/esm/src/v1beta1/naming_client.ts.baseline b/core/generator/gapic-generator-typescript/baselines/naming-esm/esm/src/v1beta1/naming_client.ts.baseline index 5020bf2e7fb8..84fc1e1f66bc 100644 --- a/core/generator/gapic-generator-typescript/baselines/naming-esm/esm/src/v1beta1/naming_client.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/naming-esm/esm/src/v1beta1/naming_client.ts.baseline @@ -18,15 +18,24 @@ /* global window */ import * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions, GrpcClientOptions, LROperation, PaginationCallback, GaxCall} from 'google-gax'; -import {Transform} from 'stream'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + GrpcClientOptions, + LROperation, + PaginationCallback, + GaxCall, +} from 'google-gax'; +import { Transform } from 'stream'; // @ts-ignore import type * as protos from '../../../protos/protos.js'; import * as naming_client_config from './naming_client_config.json'; import fs from 'fs'; import path from 'path'; -import {fileURLToPath} from 'url'; -import {getJSON} from '../json-helper.cjs'; +import { fileURLToPath } from 'url'; +import { getJSON } from '../json-helper.cjs'; // @ts-ignore const dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -35,16 +44,14 @@ const dirname = path.dirname(fileURLToPath(import.meta.url)); * `src/v1beta1/naming_client_config.json`. * This file defines retry strategy and timeouts for all API methods in this library. */ -const gapicConfig = getJSON( - path.join(dirname, 'naming_client_config.json') -); +const gapicConfig = getJSON(path.join(dirname, 'naming_client_config.json')); const jsonProtos = getJSON( - path.join(dirname, '..', '..', '..', 'protos/protos.json') + path.join(dirname, '..', '..', '..', 'protos/protos.json'), ); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; const version = getJSON( - path.join(dirname, '..', '..', '..', '..', 'package.json') + path.join(dirname, '..', '..', '..', '..', 'package.json'), ).version; /** @@ -59,7 +66,7 @@ export class NamingClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('naming'); @@ -71,10 +78,10 @@ export class NamingClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; operationsClient: gax.OperationsClient; - namingStub?: Promise<{[name: string]: Function}>; + namingStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of NamingClient. @@ -116,21 +123,42 @@ export class NamingClient { * const client = new NamingClient({fallback: 'rest'}, gax); * ``` */ - constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { // Ensure that options include all the required fields. const staticMembers = this.constructor as typeof NamingClient; - if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { - throw new Error('Please set either universe_domain or universeDomain, but not both.'); + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); } - const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; - this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; this._servicePath = 'localhost'; - const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port1; const clientConfig = opts?.clientConfig ?? {}; - const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. if (servicePath !== this._servicePath && !('scopes' in opts)) { @@ -152,7 +180,7 @@ export class NamingClient { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; @@ -169,10 +197,7 @@ export class NamingClient { const isEsm = true; const isEsmString = isEsm ? '-esm' : '-cjs'; // Determine the client header string. - const clientHeader = [ - `gax/${this._gaxModule.version}`, - `gapic/${version}`, - ]; + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/{process.versions.node}${isEsmString}`); } else { @@ -180,7 +205,7 @@ export class NamingClient { } if (!opts.fallback) { clientHeader.push(`grpc/${this._gaxGrpc.grpcVersion}`); - } else if (opts.fallback === 'rest' ) { + } else if (opts.fallback === 'rest') { clientHeader.push(`rest/${this._gaxGrpc.grpcVersion}`); } if (opts.libName && opts.libVersion) { @@ -188,17 +213,19 @@ export class NamingClient { } // Load the applicable protos. - this._protos = this._gaxGrpc.loadProtoJSON(jsonProtos as gax.protobuf.INamespace); + this._protos = this._gaxGrpc.loadProtoJSON( + jsonProtos as gax.protobuf.INamespace, + ); // This API contains "path templates"; forward-slash-separated // identifiers to uniquely identify resources within the API. // Create useful helper objects for these. this.pathTemplates = { projectExportPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/exports/{export}' + 'projects/{project}/exports/{export}', ), projectPackagePathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/packages/{package}' + 'projects/{project}/packages/{package}', ), }; @@ -206,8 +233,11 @@ export class NamingClient { // (e.g. 50 results at a time, with tokens to get subsequent // pages). Denote the keys used for pagination and results. this.descriptors.page = { - paginatedMethod: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'content') + paginatedMethod: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'content', + ), }; const protoFilesRoot = this._gaxModule.protobufFromJSON(jsonProtos); @@ -216,29 +246,37 @@ export class NamingClient { // rather than holding a request open. const lroOptions: GrpcClientOptions = { auth: this.auth, - grpc: 'grpc' in this._gaxGrpc ? this._gaxGrpc.grpc : undefined + grpc: 'grpc' in this._gaxGrpc ? this._gaxGrpc.grpc : undefined, }; if (opts.fallback === 'rest') { lroOptions.protoJson = protoFilesRoot; lroOptions.httpRules = []; } - this.operationsClient = this._gaxModule.lro(lroOptions).operationsClient(opts); + this.operationsClient = this._gaxModule + .lro(lroOptions) + .operationsClient(opts); const longRunningResponse = protoFilesRoot.lookup( - '.google.protobuf.Empty') as gax.protobuf.Type; + '.google.protobuf.Empty', + ) as gax.protobuf.Type; const longRunningMetadata = protoFilesRoot.lookup( - '.google.protobuf.Empty') as gax.protobuf.Type; + '.google.protobuf.Empty', + ) as gax.protobuf.Type; this.descriptors.longrunning = { longRunning: new this._gaxModule.LongrunningDescriptor( this.operationsClient, longRunningResponse.decode.bind(longRunningResponse), - longRunningMetadata.decode.bind(longRunningMetadata)) + longRunningMetadata.decode.bind(longRunningMetadata), + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.naming.v1beta1.Naming', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.naming.v1beta1.Naming', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + { 'x-goog-api-client': clientHeader.join(' ') }, + ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -269,28 +307,47 @@ export class NamingClient { // Put together the "service stub" for // google.naming.v1beta1.Naming. this.namingStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.naming.v1beta1.Naming') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.naming.v1beta1.Naming', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.naming.v1beta1.Naming, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts, + this._providedCustomServicePath, + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const namingStubMethods = - ['paginatedMethod', 'paginatedMethodStream', 'paginatedMethodAsync', 'longRunning', 'checkLongRunningProgress', 'initialize', 'servicePath', 'apiEndpoint', 'port', 'scopes', 'getProjectId', 'getReservedWord', 'createAbcdeSomething']; + const namingStubMethods = [ + 'paginatedMethod', + 'paginatedMethodStream', + 'paginatedMethodAsync', + 'longRunning', + 'checkLongRunningProgress', + 'initialize', + 'servicePath', + 'apiEndpoint', + 'port', + 'scopes', + 'getProjectId', + 'getReservedWord', + 'createAbcdeSomething', + ]; for (const methodName of namingStubMethods) { const callPromise = this.namingStub.then( - stub => (...args: Array<{}>) => { - if (this._terminated) { - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error|null|undefined) => () => { + (stub) => + (...args: Array<{}>) => { + if (this._terminated) { + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { throw err; - }); + }, + ); const descriptor = this.descriptors.page[methodName] || @@ -300,7 +357,7 @@ export class NamingClient { callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -315,8 +372,14 @@ export class NamingClient { * @returns {string} The DNS address for this service. */ static get servicePath1() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static servicePath1 is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath1 is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'localhost'; } @@ -328,8 +391,14 @@ export class NamingClient { * @returns {string} The DNS address for this service. */ static get apiEndpoint1() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static apiEndpoint1 is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint1 is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'localhost'; } @@ -369,8 +438,9 @@ export class NamingClient { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId1(callback?: Callback): - Promise|void { + getProjectId1( + callback?: Callback, + ): Promise | void { if (callback) { this.auth.getProjectId(callback); return; @@ -381,1118 +451,1539 @@ export class NamingClient { // ------------------- // -- Service calls -- // ------------------- -/** - * - * @param {Object} request - * The request object that will be sent. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/naming.paginated_method_stream.js - * region_tag:localhost_v1beta1_generated_Naming_PaginatedMethodStream_async - */ + /** + * + * @param {Object} request + * The request object that will be sent. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/naming.paginated_method_stream.js + * region_tag:localhost_v1beta1_generated_Naming_PaginatedMethodStream_async + */ paginatedMethodStream( - request?: protos.google.protobuf.IEmpty, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|undefined, {}|undefined - ]>; + request?: protos.google.protobuf.IEmpty, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | undefined, + {} | undefined, + ] + >; paginatedMethodStream( - request: protos.google.protobuf.IEmpty, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|null|undefined, - {}|null|undefined>): void; + request: protos.google.protobuf.IEmpty, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | null | undefined, + {} | null | undefined + >, + ): void; paginatedMethodStream( - request: protos.google.protobuf.IEmpty, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|null|undefined, - {}|null|undefined>): void; + request: protos.google.protobuf.IEmpty, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | null | undefined, + {} | null | undefined + >, + ): void; paginatedMethodStream( - request?: protos.google.protobuf.IEmpty, - optionsOrCallback?: CallOptions|Callback< - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.protobuf.IEmpty, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|undefined, {}|undefined - ]>|void { + protos.google.protobuf.IEmpty | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize1().catch(err => {throw err}); + this.initialize1().catch((err) => { + throw err; + }); this._log.info('paginatedMethodStream request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('paginatedMethodStream response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.paginatedMethodStream(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|undefined, {}|undefined - ]) => { - this._log.info('paginatedMethodStream response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .paginatedMethodStream(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | undefined, + {} | undefined, + ]) => { + this._log.info('paginatedMethodStream response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * - * @param {Object} request - * The request object that will be sent. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/naming.paginated_method_async.js - * region_tag:localhost_v1beta1_generated_Naming_PaginatedMethodAsync_async - */ + /** + * + * @param {Object} request + * The request object that will be sent. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/naming.paginated_method_async.js + * region_tag:localhost_v1beta1_generated_Naming_PaginatedMethodAsync_async + */ paginatedMethodAsync( - request?: protos.google.protobuf.IEmpty, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|undefined, {}|undefined - ]>; + request?: protos.google.protobuf.IEmpty, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | undefined, + {} | undefined, + ] + >; paginatedMethodAsync( - request: protos.google.protobuf.IEmpty, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|null|undefined, - {}|null|undefined>): void; + request: protos.google.protobuf.IEmpty, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | null | undefined, + {} | null | undefined + >, + ): void; paginatedMethodAsync( - request: protos.google.protobuf.IEmpty, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|null|undefined, - {}|null|undefined>): void; + request: protos.google.protobuf.IEmpty, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | null | undefined, + {} | null | undefined + >, + ): void; paginatedMethodAsync( - request?: protos.google.protobuf.IEmpty, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.protobuf.IEmpty, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|undefined, {}|undefined - ]>|void { + protos.google.protobuf.IEmpty | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize1().catch(err => {throw err}); + this.initialize1().catch((err) => { + throw err; + }); this._log.info('paginatedMethodAsync request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('paginatedMethodAsync response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.paginatedMethodAsync(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|undefined, {}|undefined - ]) => { - this._log.info('paginatedMethodAsync response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .paginatedMethodAsync(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | undefined, + {} | undefined, + ]) => { + this._log.info('paginatedMethodAsync response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * - * @param {Object} request - * The request object that will be sent. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/naming.check_long_running_progress.js - * region_tag:localhost_v1beta1_generated_Naming_CheckLongRunningProgress_async - */ + /** + * + * @param {Object} request + * The request object that will be sent. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/naming.check_long_running_progress.js + * region_tag:localhost_v1beta1_generated_Naming_CheckLongRunningProgress_async + */ checkLongRunningProgress( - request?: protos.google.protobuf.IEmpty, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|undefined, {}|undefined - ]>; + request?: protos.google.protobuf.IEmpty, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | undefined, + {} | undefined, + ] + >; checkLongRunningProgress( - request: protos.google.protobuf.IEmpty, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|null|undefined, - {}|null|undefined>): void; + request: protos.google.protobuf.IEmpty, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | null | undefined, + {} | null | undefined + >, + ): void; checkLongRunningProgress( - request: protos.google.protobuf.IEmpty, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|null|undefined, - {}|null|undefined>): void; + request: protos.google.protobuf.IEmpty, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | null | undefined, + {} | null | undefined + >, + ): void; checkLongRunningProgress( - request?: protos.google.protobuf.IEmpty, - optionsOrCallback?: CallOptions|Callback< - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.protobuf.IEmpty, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|undefined, {}|undefined - ]>|void { + protos.google.protobuf.IEmpty | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize1().catch(err => {throw err}); + this.initialize1().catch((err) => { + throw err; + }); this._log.info('checkLongRunningProgress request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('checkLongRunningProgress response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.checkLongRunningProgress(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|undefined, {}|undefined - ]) => { - this._log.info('checkLongRunningProgress response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .checkLongRunningProgress(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | undefined, + {} | undefined, + ]) => { + this._log.info('checkLongRunningProgress response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Problem #3: RPCs that conflict with auto-generated methods - * - * @param {Object} request - * The request object that will be sent. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/naming.initialize.js - * region_tag:localhost_v1beta1_generated_Naming_Initialize_async - */ + /** + * Problem #3: RPCs that conflict with auto-generated methods + * + * @param {Object} request + * The request object that will be sent. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/naming.initialize.js + * region_tag:localhost_v1beta1_generated_Naming_Initialize_async + */ initialize( - request?: protos.google.protobuf.IEmpty, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|undefined, {}|undefined - ]>; + request?: protos.google.protobuf.IEmpty, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | undefined, + {} | undefined, + ] + >; initialize( - request: protos.google.protobuf.IEmpty, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|null|undefined, - {}|null|undefined>): void; + request: protos.google.protobuf.IEmpty, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | null | undefined, + {} | null | undefined + >, + ): void; initialize( - request: protos.google.protobuf.IEmpty, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|null|undefined, - {}|null|undefined>): void; + request: protos.google.protobuf.IEmpty, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | null | undefined, + {} | null | undefined + >, + ): void; initialize( - request?: protos.google.protobuf.IEmpty, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.protobuf.IEmpty, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|undefined, {}|undefined - ]>|void { + protos.google.protobuf.IEmpty | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize1().catch(err => {throw err}); + this.initialize1().catch((err) => { + throw err; + }); this._log.info('initialize request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('initialize response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.initialize(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|undefined, {}|undefined - ]) => { - this._log.info('initialize response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .initialize(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | undefined, + {} | undefined, + ]) => { + this._log.info('initialize response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * - * @param {Object} request - * The request object that will be sent. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/naming.service_path.js - * region_tag:localhost_v1beta1_generated_Naming_ServicePath_async - */ + /** + * + * @param {Object} request + * The request object that will be sent. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/naming.service_path.js + * region_tag:localhost_v1beta1_generated_Naming_ServicePath_async + */ servicePath( - request?: protos.google.protobuf.IEmpty, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|undefined, {}|undefined - ]>; + request?: protos.google.protobuf.IEmpty, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | undefined, + {} | undefined, + ] + >; servicePath( - request: protos.google.protobuf.IEmpty, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|null|undefined, - {}|null|undefined>): void; + request: protos.google.protobuf.IEmpty, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | null | undefined, + {} | null | undefined + >, + ): void; servicePath( - request: protos.google.protobuf.IEmpty, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|null|undefined, - {}|null|undefined>): void; + request: protos.google.protobuf.IEmpty, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | null | undefined, + {} | null | undefined + >, + ): void; servicePath( - request?: protos.google.protobuf.IEmpty, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.protobuf.IEmpty, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|undefined, {}|undefined - ]>|void { + protos.google.protobuf.IEmpty | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize1().catch(err => {throw err}); + this.initialize1().catch((err) => { + throw err; + }); this._log.info('servicePath request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('servicePath response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.servicePath(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|undefined, {}|undefined - ]) => { - this._log.info('servicePath response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .servicePath(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | undefined, + {} | undefined, + ]) => { + this._log.info('servicePath response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * - * @param {Object} request - * The request object that will be sent. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/naming.api_endpoint.js - * region_tag:localhost_v1beta1_generated_Naming_ApiEndpoint_async - */ + /** + * + * @param {Object} request + * The request object that will be sent. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/naming.api_endpoint.js + * region_tag:localhost_v1beta1_generated_Naming_ApiEndpoint_async + */ apiEndpoint( - request?: protos.google.protobuf.IEmpty, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|undefined, {}|undefined - ]>; + request?: protos.google.protobuf.IEmpty, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | undefined, + {} | undefined, + ] + >; apiEndpoint( - request: protos.google.protobuf.IEmpty, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|null|undefined, - {}|null|undefined>): void; + request: protos.google.protobuf.IEmpty, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | null | undefined, + {} | null | undefined + >, + ): void; apiEndpoint( - request: protos.google.protobuf.IEmpty, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|null|undefined, - {}|null|undefined>): void; + request: protos.google.protobuf.IEmpty, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | null | undefined, + {} | null | undefined + >, + ): void; apiEndpoint( - request?: protos.google.protobuf.IEmpty, - optionsOrCallback?: CallOptions|Callback< - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.protobuf.IEmpty, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|undefined, {}|undefined - ]>|void { + protos.google.protobuf.IEmpty | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize1().catch(err => {throw err}); + this.initialize1().catch((err) => { + throw err; + }); this._log.info('apiEndpoint request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('apiEndpoint response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.apiEndpoint(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|undefined, {}|undefined - ]) => { - this._log.info('apiEndpoint response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .apiEndpoint(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | undefined, + {} | undefined, + ]) => { + this._log.info('apiEndpoint response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * - * @param {Object} request - * The request object that will be sent. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/naming.port.js - * region_tag:localhost_v1beta1_generated_Naming_Port_async - */ + /** + * + * @param {Object} request + * The request object that will be sent. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/naming.port.js + * region_tag:localhost_v1beta1_generated_Naming_Port_async + */ port( - request?: protos.google.protobuf.IEmpty, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|undefined, {}|undefined - ]>; + request?: protos.google.protobuf.IEmpty, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | undefined, + {} | undefined, + ] + >; port( - request: protos.google.protobuf.IEmpty, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|null|undefined, - {}|null|undefined>): void; + request: protos.google.protobuf.IEmpty, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | null | undefined, + {} | null | undefined + >, + ): void; port( - request: protos.google.protobuf.IEmpty, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|null|undefined, - {}|null|undefined>): void; + request: protos.google.protobuf.IEmpty, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | null | undefined, + {} | null | undefined + >, + ): void; port( - request?: protos.google.protobuf.IEmpty, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.protobuf.IEmpty, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|undefined, {}|undefined - ]>|void { + protos.google.protobuf.IEmpty | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize1().catch(err => {throw err}); + this.initialize1().catch((err) => { + throw err; + }); this._log.info('port request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('port response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.port(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|undefined, {}|undefined - ]) => { - this._log.info('port response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .port(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | undefined, + {} | undefined, + ]) => { + this._log.info('port response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * - * @param {Object} request - * The request object that will be sent. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/naming.scopes.js - * region_tag:localhost_v1beta1_generated_Naming_Scopes_async - */ + /** + * + * @param {Object} request + * The request object that will be sent. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/naming.scopes.js + * region_tag:localhost_v1beta1_generated_Naming_Scopes_async + */ scopes( - request?: protos.google.protobuf.IEmpty, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|undefined, {}|undefined - ]>; + request?: protos.google.protobuf.IEmpty, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | undefined, + {} | undefined, + ] + >; scopes( - request: protos.google.protobuf.IEmpty, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|null|undefined, - {}|null|undefined>): void; + request: protos.google.protobuf.IEmpty, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | null | undefined, + {} | null | undefined + >, + ): void; scopes( - request: protos.google.protobuf.IEmpty, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|null|undefined, - {}|null|undefined>): void; + request: protos.google.protobuf.IEmpty, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | null | undefined, + {} | null | undefined + >, + ): void; scopes( - request?: protos.google.protobuf.IEmpty, - optionsOrCallback?: CallOptions|Callback< - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.protobuf.IEmpty, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|undefined, {}|undefined - ]>|void { + protos.google.protobuf.IEmpty | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize1().catch(err => {throw err}); + this.initialize1().catch((err) => { + throw err; + }); this._log.info('scopes request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('scopes response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.scopes(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|undefined, {}|undefined - ]) => { - this._log.info('scopes response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .scopes(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | undefined, + {} | undefined, + ]) => { + this._log.info('scopes response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * - * @param {Object} request - * The request object that will be sent. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/naming.get_project_id.js - * region_tag:localhost_v1beta1_generated_Naming_getProjectId_async - */ + /** + * + * @param {Object} request + * The request object that will be sent. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/naming.get_project_id.js + * region_tag:localhost_v1beta1_generated_Naming_getProjectId_async + */ getProjectId( - request?: protos.google.protobuf.IEmpty, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|undefined, {}|undefined - ]>; + request?: protos.google.protobuf.IEmpty, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | undefined, + {} | undefined, + ] + >; getProjectId( - request: protos.google.protobuf.IEmpty, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|null|undefined, - {}|null|undefined>): void; + request: protos.google.protobuf.IEmpty, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | null | undefined, + {} | null | undefined + >, + ): void; getProjectId( - request: protos.google.protobuf.IEmpty, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|null|undefined, - {}|null|undefined>): void; + request: protos.google.protobuf.IEmpty, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | null | undefined, + {} | null | undefined + >, + ): void; getProjectId( - request?: protos.google.protobuf.IEmpty, - optionsOrCallback?: CallOptions|Callback< - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.protobuf.IEmpty, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|undefined, {}|undefined - ]>|void { + protos.google.protobuf.IEmpty | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize1().catch(err => {throw err}); + this.initialize1().catch((err) => { + throw err; + }); this._log.info('getProjectId request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getProjectId response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.getProjectId(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|undefined, {}|undefined - ]) => { - this._log.info('getProjectId response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getProjectId(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | undefined, + {} | undefined, + ]) => { + this._log.info('getProjectId response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.word - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.naming.v1beta1.ReservedWord|ReservedWord}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/naming.get_reserved_word.js - * region_tag:localhost_v1beta1_generated_Naming_getReservedWord_async - */ + /** + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.word + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.naming.v1beta1.ReservedWord|ReservedWord}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/naming.get_reserved_word.js + * region_tag:localhost_v1beta1_generated_Naming_getReservedWord_async + */ getReservedWord( - request?: protos.google.naming.v1beta1.IGetReservedWordRequest, - options?: CallOptions): - Promise<[ - protos.google.naming.v1beta1.IReservedWord, - protos.google.naming.v1beta1.IGetReservedWordRequest|undefined, {}|undefined - ]>; + request?: protos.google.naming.v1beta1.IGetReservedWordRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.naming.v1beta1.IReservedWord, + protos.google.naming.v1beta1.IGetReservedWordRequest | undefined, + {} | undefined, + ] + >; getReservedWord( - request: protos.google.naming.v1beta1.IGetReservedWordRequest, - options: CallOptions, - callback: Callback< - protos.google.naming.v1beta1.IReservedWord, - protos.google.naming.v1beta1.IGetReservedWordRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.naming.v1beta1.IGetReservedWordRequest, + options: CallOptions, + callback: Callback< + protos.google.naming.v1beta1.IReservedWord, + protos.google.naming.v1beta1.IGetReservedWordRequest | null | undefined, + {} | null | undefined + >, + ): void; getReservedWord( - request: protos.google.naming.v1beta1.IGetReservedWordRequest, - callback: Callback< - protos.google.naming.v1beta1.IReservedWord, - protos.google.naming.v1beta1.IGetReservedWordRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.naming.v1beta1.IGetReservedWordRequest, + callback: Callback< + protos.google.naming.v1beta1.IReservedWord, + protos.google.naming.v1beta1.IGetReservedWordRequest | null | undefined, + {} | null | undefined + >, + ): void; getReservedWord( - request?: protos.google.naming.v1beta1.IGetReservedWordRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.naming.v1beta1.IGetReservedWordRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.naming.v1beta1.IReservedWord, - protos.google.naming.v1beta1.IGetReservedWordRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.naming.v1beta1.IReservedWord, - protos.google.naming.v1beta1.IGetReservedWordRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.naming.v1beta1.IReservedWord, - protos.google.naming.v1beta1.IGetReservedWordRequest|undefined, {}|undefined - ]>|void { + | protos.google.naming.v1beta1.IGetReservedWordRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.naming.v1beta1.IReservedWord, + protos.google.naming.v1beta1.IGetReservedWordRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.naming.v1beta1.IReservedWord, + protos.google.naming.v1beta1.IGetReservedWordRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize1().catch(err => {throw err}); + this.initialize1().catch((err) => { + throw err; + }); this._log.info('getReservedWord request %j', request); - const wrappedCallback: Callback< - protos.google.naming.v1beta1.IReservedWord, - protos.google.naming.v1beta1.IGetReservedWordRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.naming.v1beta1.IReservedWord, + | protos.google.naming.v1beta1.IGetReservedWordRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getReservedWord response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.getReservedWord(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.naming.v1beta1.IReservedWord, - protos.google.naming.v1beta1.IGetReservedWordRequest|undefined, {}|undefined - ]) => { - this._log.info('getReservedWord response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getReservedWord(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.naming.v1beta1.IReservedWord, + protos.google.naming.v1beta1.IGetReservedWordRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getReservedWord response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * - * @param {Object} request - * The request object that will be sent. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/naming.create_a_b_c_d_e_something.js - * region_tag:localhost_v1beta1_generated_Naming_createABCDESomething_async - */ + /** + * + * @param {Object} request + * The request object that will be sent. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/naming.create_a_b_c_d_e_something.js + * region_tag:localhost_v1beta1_generated_Naming_createABCDESomething_async + */ createABCDESomething( - request?: protos.google.protobuf.IEmpty, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|undefined, {}|undefined - ]>; + request?: protos.google.protobuf.IEmpty, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | undefined, + {} | undefined, + ] + >; createABCDESomething( - request: protos.google.protobuf.IEmpty, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|null|undefined, - {}|null|undefined>): void; + request: protos.google.protobuf.IEmpty, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | null | undefined, + {} | null | undefined + >, + ): void; createABCDESomething( - request: protos.google.protobuf.IEmpty, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|null|undefined, - {}|null|undefined>): void; + request: protos.google.protobuf.IEmpty, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | null | undefined, + {} | null | undefined + >, + ): void; createABCDESomething( - request?: protos.google.protobuf.IEmpty, - optionsOrCallback?: CallOptions|Callback< - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.protobuf.IEmpty, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|undefined, {}|undefined - ]>|void { + protos.google.protobuf.IEmpty | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize1().catch(err => {throw err}); + this.initialize1().catch((err) => { + throw err; + }); this._log.info('createABCDESomething request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createABCDESomething response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.createAbcdeSomething(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|undefined, {}|undefined - ]) => { - this._log.info('createABCDESomething response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createAbcdeSomething(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | undefined, + {} | undefined, + ]) => { + this._log.info('createABCDESomething response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Problem #2: long running method generates extra method check*Progress() - * - * @param {Object} request - * The request object that will be sent. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing - * a long running operation. Its `promise()` method returns a promise - * you can `await` for. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/naming.long_running.js - * region_tag:localhost_v1beta1_generated_Naming_LongRunning_async - */ + /** + * Problem #2: long running method generates extra method check*Progress() + * + * @param {Object} request + * The request object that will be sent. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/naming.long_running.js + * region_tag:localhost_v1beta1_generated_Naming_LongRunning_async + */ longRunning( - request?: protos.google.protobuf.IEmpty, - options?: CallOptions): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>; + request?: protos.google.protobuf.IEmpty, + options?: CallOptions, + ): Promise< + [ + LROperation, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; longRunning( - request: protos.google.protobuf.IEmpty, - options: CallOptions, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.protobuf.IEmpty, + options: CallOptions, + callback: Callback< + LROperation, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; longRunning( - request: protos.google.protobuf.IEmpty, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.protobuf.IEmpty, + callback: Callback< + LROperation, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; longRunning( - request?: protos.google.protobuf.IEmpty, - optionsOrCallback?: CallOptions|Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>, - callback?: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>|void { + request?: protos.google.protobuf.IEmpty, + optionsOrCallback?: + | CallOptions + | Callback< + LROperation< + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + callback?: Callback< + LROperation, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + LROperation, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize1().catch(err => {throw err}); - const wrappedCallback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>|undefined = callback + this.initialize1().catch((err) => { + throw err; + }); + const wrappedCallback: + | Callback< + LROperation< + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, rawResponse, _) => { this._log.info('longRunning response %j', rawResponse); callback!(error, response, rawResponse, _); // We verified `callback` above. } : undefined; this._log.info('longRunning request %j', request); - return this.innerApiCalls.longRunning(request, options, wrappedCallback) - ?.then(([response, rawResponse, _]: [ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]) => { - this._log.info('longRunning response %j', rawResponse); - return [response, rawResponse, _]; - }); + return this.innerApiCalls + .longRunning(request, options, wrappedCallback) + ?.then( + ([response, rawResponse, _]: [ + LROperation< + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ]) => { + this._log.info('longRunning response %j', rawResponse); + return [response, rawResponse, _]; + }, + ); } -/** - * Check the status of the long running operation returned by `longRunning()`. - * @param {String} name - * The operation name that will be passed. - * @returns {Promise} - The promise which resolves to an object. - * The decoded operation object has result and metadata field to get information from. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/naming.long_running.js - * region_tag:localhost_v1beta1_generated_Naming_LongRunning_async - */ - async checkLongRunningProgress1(name: string): Promise>{ + /** + * Check the status of the long running operation returned by `longRunning()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/naming.long_running.js + * region_tag:localhost_v1beta1_generated_Naming_LongRunning_async + */ + async checkLongRunningProgress1( + name: string, + ): Promise< + LROperation + > { this._log.info('longRunning long-running'); - const request = new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest({name}); + const request = + new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( + { name }, + ); const [operation] = await this.operationsClient.getOperation(request); - const decodeOperation = new this._gaxModule.Operation(operation, this.descriptors.longrunning.longRunning, this._gaxModule.createDefaultBackoffSettings()); - return decodeOperation as LROperation; + const decodeOperation = new this._gaxModule.Operation( + operation, + this.descriptors.longrunning.longRunning, + this._gaxModule.createDefaultBackoffSettings(), + ); + return decodeOperation as LROperation< + protos.google.protobuf.Empty, + protos.google.protobuf.Empty + >; } - /** - * Problem #1: paginated method generates extra methods *Stream() and - * *Async(), which might conflict with unary methods with the same names. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.protobuf.Empty} request.content - * @param {number} request.pageSize - * @param {string} request.pageToken - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.protobuf.Empty|Empty}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `paginatedMethodAsync1()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Problem #1: paginated method generates extra methods *Stream() and + * *Async(), which might conflict with unary methods with the same names. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.protobuf.Empty} request.content + * @param {number} request.pageSize + * @param {string} request.pageToken + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.protobuf.Empty|Empty}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `paginatedMethodAsync1()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ paginatedMethod( - request?: protos.google.naming.v1beta1.IPaginatedMethodRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty[], - protos.google.naming.v1beta1.IPaginatedMethodRequest|null, - protos.google.naming.v1beta1.IPaginatedMethodResponse - ]>; + request?: protos.google.naming.v1beta1.IPaginatedMethodRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty[], + protos.google.naming.v1beta1.IPaginatedMethodRequest | null, + protos.google.naming.v1beta1.IPaginatedMethodResponse, + ] + >; paginatedMethod( - request: protos.google.naming.v1beta1.IPaginatedMethodRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.naming.v1beta1.IPaginatedMethodRequest, - protos.google.naming.v1beta1.IPaginatedMethodResponse|null|undefined, - protos.google.protobuf.IEmpty>): void; + request: protos.google.naming.v1beta1.IPaginatedMethodRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.naming.v1beta1.IPaginatedMethodRequest, + protos.google.naming.v1beta1.IPaginatedMethodResponse | null | undefined, + protos.google.protobuf.IEmpty + >, + ): void; paginatedMethod( - request: protos.google.naming.v1beta1.IPaginatedMethodRequest, - callback: PaginationCallback< - protos.google.naming.v1beta1.IPaginatedMethodRequest, - protos.google.naming.v1beta1.IPaginatedMethodResponse|null|undefined, - protos.google.protobuf.IEmpty>): void; + request: protos.google.naming.v1beta1.IPaginatedMethodRequest, + callback: PaginationCallback< + protos.google.naming.v1beta1.IPaginatedMethodRequest, + protos.google.naming.v1beta1.IPaginatedMethodResponse | null | undefined, + protos.google.protobuf.IEmpty + >, + ): void; paginatedMethod( - request?: protos.google.naming.v1beta1.IPaginatedMethodRequest, - optionsOrCallback?: CallOptions|PaginationCallback< - protos.google.naming.v1beta1.IPaginatedMethodRequest, - protos.google.naming.v1beta1.IPaginatedMethodResponse|null|undefined, - protos.google.protobuf.IEmpty>, - callback?: PaginationCallback< + request?: protos.google.naming.v1beta1.IPaginatedMethodRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.naming.v1beta1.IPaginatedMethodRequest, - protos.google.naming.v1beta1.IPaginatedMethodResponse|null|undefined, - protos.google.protobuf.IEmpty>): - Promise<[ - protos.google.protobuf.IEmpty[], - protos.google.naming.v1beta1.IPaginatedMethodRequest|null, - protos.google.naming.v1beta1.IPaginatedMethodResponse - ]>|void { + | protos.google.naming.v1beta1.IPaginatedMethodResponse + | null + | undefined, + protos.google.protobuf.IEmpty + >, + callback?: PaginationCallback< + protos.google.naming.v1beta1.IPaginatedMethodRequest, + protos.google.naming.v1beta1.IPaginatedMethodResponse | null | undefined, + protos.google.protobuf.IEmpty + >, + ): Promise< + [ + protos.google.protobuf.IEmpty[], + protos.google.naming.v1beta1.IPaginatedMethodRequest | null, + protos.google.naming.v1beta1.IPaginatedMethodResponse, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize1().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.naming.v1beta1.IPaginatedMethodRequest, - protos.google.naming.v1beta1.IPaginatedMethodResponse|null|undefined, - protos.google.protobuf.IEmpty>|undefined = callback + this.initialize1().catch((err) => { + throw err; + }); + const wrappedCallback: + | PaginationCallback< + protos.google.naming.v1beta1.IPaginatedMethodRequest, + | protos.google.naming.v1beta1.IPaginatedMethodResponse + | null + | undefined, + protos.google.protobuf.IEmpty + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('paginatedMethod values %j', values); callback!(error, values, nextPageRequest, rawResponse); @@ -1501,90 +1992,96 @@ export class NamingClient { this._log.info('paginatedMethod request %j', request); return this.innerApiCalls .paginatedMethod(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.protobuf.IEmpty[], - protos.google.naming.v1beta1.IPaginatedMethodRequest|null, - protos.google.naming.v1beta1.IPaginatedMethodResponse - ]) => { - this._log.info('paginatedMethod values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.protobuf.IEmpty[], + protos.google.naming.v1beta1.IPaginatedMethodRequest | null, + protos.google.naming.v1beta1.IPaginatedMethodResponse, + ]) => { + this._log.info('paginatedMethod values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `paginatedMethod`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {google.protobuf.Empty} request.content - * @param {number} request.pageSize - * @param {string} request.pageToken - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.protobuf.Empty|Empty} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `paginatedMethodAsync1()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `paginatedMethod`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {google.protobuf.Empty} request.content + * @param {number} request.pageSize + * @param {string} request.pageToken + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.protobuf.Empty|Empty} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `paginatedMethodAsync1()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ paginatedMethodStream1( - request?: protos.google.naming.v1beta1.IPaginatedMethodRequest, - options?: CallOptions): - Transform{ + request?: protos.google.naming.v1beta1.IPaginatedMethodRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; const defaultCallSettings = this._defaults['paginatedMethod']; const callSettings = defaultCallSettings.merge(options); - this.initialize1().catch(err => {throw err}); + this.initialize1().catch((err) => { + throw err; + }); this._log.info('paginatedMethod stream %j', request); return this.descriptors.page.paginatedMethod.createStream( this.innerApiCalls.paginatedMethod as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `paginatedMethod`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {google.protobuf.Empty} request.content - * @param {number} request.pageSize - * @param {string} request.pageToken - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.protobuf.Empty|Empty}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/naming.paginated_method.js - * region_tag:localhost_v1beta1_generated_Naming_PaginatedMethod_async - */ + /** + * Equivalent to `paginatedMethod`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {google.protobuf.Empty} request.content + * @param {number} request.pageSize + * @param {string} request.pageToken + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.protobuf.Empty|Empty}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/naming.paginated_method.js + * region_tag:localhost_v1beta1_generated_Naming_PaginatedMethod_async + */ paginatedMethodAsync1( - request?: protos.google.naming.v1beta1.IPaginatedMethodRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.naming.v1beta1.IPaginatedMethodRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; const defaultCallSettings = this._defaults['paginatedMethod']; const callSettings = defaultCallSettings.merge(options); - this.initialize1().catch(err => {throw err}); + this.initialize1().catch((err) => { + throw err; + }); this._log.info('paginatedMethod iterate %j', request); return this.descriptors.page.paginatedMethod.asyncIterate( this.innerApiCalls['paginatedMethod'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } // -------------------- @@ -1598,7 +2095,7 @@ export class NamingClient { * @param {string} exportParam * @returns {string} Resource name string. */ - projectExportPath(project:string,exportParam:string) { + projectExportPath(project: string, exportParam: string) { return this.pathTemplates.projectExportPathTemplate.render({ project: project, export: exportParam, @@ -1613,7 +2110,8 @@ export class NamingClient { * @returns {string} A string representing the project. */ matchProjectFromProjectExportName(projectExportName: string) { - return this.pathTemplates.projectExportPathTemplate.match(projectExportName).project; + return this.pathTemplates.projectExportPathTemplate.match(projectExportName) + .project; } /** @@ -1624,7 +2122,8 @@ export class NamingClient { * @returns {string} A string representing the export. */ matchExportFromProjectExportName(projectExportName: string) { - return this.pathTemplates.projectExportPathTemplate.match(projectExportName).export; + return this.pathTemplates.projectExportPathTemplate.match(projectExportName) + .export; } /** @@ -1634,7 +2133,7 @@ export class NamingClient { * @param {string} packageParam * @returns {string} Resource name string. */ - projectPackagePath(project:string,packageParam:string) { + projectPackagePath(project: string, packageParam: string) { return this.pathTemplates.projectPackagePathTemplate.render({ project: project, package: packageParam, @@ -1649,7 +2148,9 @@ export class NamingClient { * @returns {string} A string representing the project. */ matchProjectFromProjectPackageName(projectPackageName: string) { - return this.pathTemplates.projectPackagePathTemplate.match(projectPackageName).project; + return this.pathTemplates.projectPackagePathTemplate.match( + projectPackageName, + ).project; } /** @@ -1660,7 +2161,9 @@ export class NamingClient { * @returns {string} A string representing the package. */ matchPackageFromProjectPackageName(projectPackageName: string) { - return this.pathTemplates.projectPackagePathTemplate.match(projectPackageName).package; + return this.pathTemplates.projectPackagePathTemplate.match( + projectPackageName, + ).package; } /** @@ -1671,7 +2174,7 @@ export class NamingClient { */ close(): Promise { if (this.namingStub && !this._terminated) { - return this.namingStub.then(stub => { + return this.namingStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -1680,4 +2183,4 @@ export class NamingClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/core/generator/gapic-generator-typescript/baselines/naming-esm/esm/system-test/fixtures/sample/src/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/naming-esm/esm/system-test/fixtures/sample/src/index.ts.baseline index e40defab01d2..a84d4002f144 100644 --- a/core/generator/gapic-generator-typescript/baselines/naming-esm/esm/system-test/fixtures/sample/src/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/naming-esm/esm/system-test/fixtures/sample/src/index.ts.baseline @@ -17,7 +17,7 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -import {NamingClient} from 'naming'; +import { NamingClient } from 'naming'; // check that the client class type name can be used function doStuffWithNamingClient(client: NamingClient) { diff --git a/core/generator/gapic-generator-typescript/baselines/naming-esm/esm/system-test/install.ts.baseline b/core/generator/gapic-generator-typescript/baselines/naming-esm/esm/system-test/install.ts.baseline index e079c4fa1101..d109fdd8c97f 100644 --- a/core/generator/gapic-generator-typescript/baselines/naming-esm/esm/system-test/install.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/naming-esm/esm/system-test/install.ts.baseline @@ -16,40 +16,45 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -import {packNTest} from 'pack-n-play'; -import {readFileSync} from 'fs'; -import {describe, it} from 'mocha'; +import { packNTest } from 'pack-n-play'; +import { readFileSync } from 'fs'; +import { describe, it } from 'mocha'; describe('📦 pack-n-play test', () => { - it('TypeScript', async function() { + it('TypeScript', async function () { this.timeout(300000); await packNTest({ packageDir: process.cwd(), sample: { description: 'TypeScript user can use the type definitions', - ts: readFileSync('./esm/system-test/fixtures/sample/src/index.ts').toString() - } + ts: readFileSync( + './esm/system-test/fixtures/sample/src/index.ts', + ).toString(), + }, }); }); - it('ESM module', async function() { + it('ESM module', async function () { this.timeout(300000); await packNTest({ sample: { description: 'Should be able to import using ESM', - esm: readFileSync('./esm/system-test/fixtures/sample/src/index.js').toString(), + esm: readFileSync( + './esm/system-test/fixtures/sample/src/index.js', + ).toString(), }, }); }); - it('CJS module', async function() { + it('CJS module', async function () { this.timeout(300000); await packNTest({ sample: { description: 'Should be able to import using CJS', - cjs: readFileSync('./esm/system-test/fixtures/sample/src/index.cjs').toString(), + cjs: readFileSync( + './esm/system-test/fixtures/sample/src/index.cjs', + ).toString(), }, }); }); - }); diff --git a/core/generator/gapic-generator-typescript/baselines/naming-esm/esm/test/gapic_naming_v1beta1.ts.baseline b/core/generator/gapic-generator-typescript/baselines/naming-esm/esm/test/gapic_naming_v1beta1.ts.baseline index 559d526c38c8..b2347af65f81 100644 --- a/core/generator/gapic-generator-typescript/baselines/naming-esm/esm/test/gapic_naming_v1beta1.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/naming-esm/esm/test/gapic_naming_v1beta1.ts.baseline @@ -20,16 +20,16 @@ import * as protos from '../../protos/protos.js'; import assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as namingModule from '../src/index.js'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; -import {protobuf, LROperation, operationsProtos} from 'google-gax'; +import { protobuf, LROperation, operationsProtos } from 'google-gax'; import fs from 'fs'; import path from 'path'; -import {fileURLToPath} from 'url'; +import { fileURLToPath } from 'url'; // @ts-ignore const dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -37,1402 +37,1577 @@ const dirname = path.dirname(fileURLToPath(import.meta.url)); // to fill in default values for request objects const root = protobuf.Root.fromJSON( JSON.parse( - fs.readFileSync(path.join(dirname, '..', '..', 'protos/protos.json'), 'utf8') - )) + fs.readFileSync( + path.join(dirname, '..', '..', 'protos/protos.json'), + 'utf8', + ), + ), +); // eslint-disable-next-line @typescript-eslint/no-unused-vars function getTypeDefaultValue(typeName: string, fields: string[]) { - let type = root.lookupType(typeName) as protobuf.Type; - for (const field of fields.slice(0, -1)) { - type = type?.fields[field]?.resolvedType as protobuf.Type; - } - return type?.fields[fields[fields.length - 1]]?.defaultValue ?? null; + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type?.fields[field]?.resolvedType as protobuf.Type; + } + return type?.fields[fields[fields.length - 1]]?.defaultValue ?? null; } function generateSampleMessage(instance: T) { - const filledObject = (instance.constructor as typeof protobuf.Message) - .toObject(instance as protobuf.Message, {defaults: true}); - return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, { defaults: true }); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; } function stubSimpleCall(response?: ResponseType, error?: Error) { - return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); } -function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { - return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +function stubSimpleCallWithCallback( + response?: ResponseType, + error?: Error, +) { + return error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); } -function stubLongRunningCall(response?: ResponseType, callError?: Error, lroError?: Error) { - const innerStub = lroError ? sinon.stub().rejects(lroError) : sinon.stub().resolves([response]); - const mockOperation = { - promise: innerStub, - }; - return callError ? sinon.stub().rejects(callError) : sinon.stub().resolves([mockOperation]); +function stubLongRunningCall( + response?: ResponseType, + callError?: Error, + lroError?: Error, +) { + const innerStub = lroError + ? sinon.stub().rejects(lroError) + : sinon.stub().resolves([response]); + const mockOperation = { + promise: innerStub, + }; + return callError + ? sinon.stub().rejects(callError) + : sinon.stub().resolves([mockOperation]); } -function stubLongRunningCallWithCallback(response?: ResponseType, callError?: Error, lroError?: Error) { - const innerStub = lroError ? sinon.stub().rejects(lroError) : sinon.stub().resolves([response]); - const mockOperation = { - promise: innerStub, - }; - return callError ? sinon.stub().callsArgWith(2, callError) : sinon.stub().callsArgWith(2, null, mockOperation); +function stubLongRunningCallWithCallback( + response?: ResponseType, + callError?: Error, + lroError?: Error, +) { + const innerStub = lroError + ? sinon.stub().rejects(lroError) + : sinon.stub().resolves([response]); + const mockOperation = { + promise: innerStub, + }; + return callError + ? sinon.stub().callsArgWith(2, callError) + : sinon.stub().callsArgWith(2, null, mockOperation); } -function stubPageStreamingCall(responses?: ResponseType[], error?: Error) { - const pagingStub = sinon.stub(); - if (responses) { - for (let i = 0; i < responses.length; ++i) { - pagingStub.onCall(i).callsArgWith(2, null, responses[i]); - } +function stubPageStreamingCall( + responses?: ResponseType[], + error?: Error, +) { + const pagingStub = sinon.stub(); + if (responses) { + for (let i = 0; i < responses.length; ++i) { + pagingStub.onCall(i).callsArgWith(2, null, responses[i]); } - const transformStub = error ? sinon.stub().callsArgWith(2, error) : pagingStub; - const mockStream = new PassThrough({ - objectMode: true, - transform: transformStub, - }); - // trigger as many responses as needed - if (responses) { - for (let i = 0; i < responses.length; ++i) { - setImmediate(() => { mockStream.write({}); }); - } - setImmediate(() => { mockStream.end(); }); - } else { - setImmediate(() => { mockStream.write({}); }); - setImmediate(() => { mockStream.end(); }); + } + const transformStub = error + ? sinon.stub().callsArgWith(2, error) + : pagingStub; + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + // trigger as many responses as needed + if (responses) { + for (let i = 0; i < responses.length; ++i) { + setImmediate(() => { + mockStream.write({}); + }); } - return sinon.stub().returns(mockStream); + setImmediate(() => { + mockStream.end(); + }); + } else { + setImmediate(() => { + mockStream.write({}); + }); + setImmediate(() => { + mockStream.end(); + }); + } + return sinon.stub().returns(mockStream); } -function stubAsyncIterationCall(responses?: ResponseType[], error?: Error) { - let counter = 0; - const asyncIterable = { - [Symbol.asyncIterator]() { - return { - async next() { - if (error) { - return Promise.reject(error); - } - if (counter >= responses!.length) { - return Promise.resolve({done: true, value: undefined}); - } - return Promise.resolve({done: false, value: responses![counter++]}); - } - }; - } - }; - return sinon.stub().returns(asyncIterable); +function stubAsyncIterationCall( + responses?: ResponseType[], + error?: Error, +) { + let counter = 0; + const asyncIterable = { + [Symbol.asyncIterator]() { + return { + async next() { + if (error) { + return Promise.reject(error); + } + if (counter >= responses!.length) { + return Promise.resolve({ done: true, value: undefined }); + } + return Promise.resolve({ done: false, value: responses![counter++] }); + }, + }; + }, + }; + return sinon.stub().returns(asyncIterable); } describe('v1beta1.NamingClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new namingModule.v1beta1.NamingClient(); - const apiEndpoint = client.apiEndpoint1; - assert.strictEqual(apiEndpoint, 'localhost'); - }); - - it('has universeDomain', () => { - const client = new namingModule.v1beta1.NamingClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); - - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - it('throws DeprecationWarning if static servicePath1 is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const servicePath = namingModule.v1beta1.NamingClient.servicePath1; - assert.strictEqual(servicePath, 'localhost'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint1 is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = namingModule.v1beta1.NamingClient.apiEndpoint1; - assert.strictEqual(apiEndpoint, 'localhost'); - assert(stub.called); - stub.restore(); - }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { new namingModule.v1beta1.NamingClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); - - it('has port', () => { - const port = namingModule.v1beta1.NamingClient.port1; - assert(port); - assert(typeof port === 'number'); - }); - - it('should create a client with no option', () => { - const client = new namingModule.v1beta1.NamingClient(); - assert(client); - }); - - it('should create a client with gRPC fallback', () => { - const client = new namingModule.v1beta1.NamingClient({ - fallback: true, - }); - assert(client); - }); - - it('has initialize method and supports deferred initialization', async () => { - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.namingStub, undefined); - await client.initialize1(); - assert(client.namingStub); - }); - - it('has close method for the initialized client', done => { - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize1().catch(err => {throw err}); - assert(client.namingStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); - - it('has close method for the non-initialized client', done => { - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.namingStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); - - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId1(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); - }); - - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId1((err?: Error|null, projectId?: string|null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } - }); - }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new namingModule.v1beta1.NamingClient(); + const apiEndpoint = client.apiEndpoint1; + assert.strictEqual(apiEndpoint, 'localhost'); }); - describe('paginatedMethodStream', () => { - it('invokes paginatedMethodStream without error', async () => { - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize1(); - const request = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.paginatedMethodStream = stubSimpleCall(expectedResponse); - const [response] = await client.paginatedMethodStream(request); - assert.deepStrictEqual(response, expectedResponse); - }); - - it('invokes paginatedMethodStream without error using callback', async () => { - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize1(); - const request = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.paginatedMethodStream = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.paginatedMethodStream( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); - - it('invokes paginatedMethodStream with error', async () => { - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize1(); - const request = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.paginatedMethodStream = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.paginatedMethodStream(request), expectedError); - }); - - it('invokes paginatedMethodStream with closed client', async () => { - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize1(); - const request = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.paginatedMethodStream(request), expectedError); - }); + it('has universeDomain', () => { + const client = new namingModule.v1beta1.NamingClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); }); - describe('paginatedMethodAsync', () => { - it('invokes paginatedMethodAsync without error', async () => { - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize1(); - const request = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.paginatedMethodAsync = stubSimpleCall(expectedResponse); - const [response] = await client.paginatedMethodAsync(request); - assert.deepStrictEqual(response, expectedResponse); - }); - - it('invokes paginatedMethodAsync without error using callback', async () => { - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize1(); - const request = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.paginatedMethodAsync = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.paginatedMethodAsync( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath1 is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = namingModule.v1beta1.NamingClient.servicePath1; + assert.strictEqual(servicePath, 'localhost'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint1 is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = namingModule.v1beta1.NamingClient.apiEndpoint1; + assert.strictEqual(apiEndpoint, 'localhost'); + assert(stub.called); + stub.restore(); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new namingModule.v1beta1.NamingClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); + }); - it('invokes paginatedMethodAsync with error', async () => { - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize1(); - const request = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.paginatedMethodAsync = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.paginatedMethodAsync(request), expectedError); - }); + it('has port', () => { + const port = namingModule.v1beta1.NamingClient.port1; + assert(port); + assert(typeof port === 'number'); + }); - it('invokes paginatedMethodAsync with closed client', async () => { - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize1(); - const request = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.paginatedMethodAsync(request), expectedError); - }); + it('should create a client with no option', () => { + const client = new namingModule.v1beta1.NamingClient(); + assert(client); }); - describe('checkLongRunningProgress', () => { - it('invokes checkLongRunningProgress without error', async () => { - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize1(); - const request = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.checkLongRunningProgress = stubSimpleCall(expectedResponse); - const [response] = await client.checkLongRunningProgress(request); - assert.deepStrictEqual(response, expectedResponse); - }); + it('should create a client with gRPC fallback', () => { + const client = new namingModule.v1beta1.NamingClient({ + fallback: true, + }); + assert(client); + }); - it('invokes checkLongRunningProgress without error using callback', async () => { - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize1(); - const request = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.checkLongRunningProgress = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.checkLongRunningProgress( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); + it('has initialize method and supports deferred initialization', async () => { + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.namingStub, undefined); + await client.initialize1(); + assert(client.namingStub); + }); - it('invokes checkLongRunningProgress with error', async () => { - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize1(); - const request = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.checkLongRunningProgress = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.checkLongRunningProgress(request), expectedError); + it('has close method for the initialized client', (done) => { + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize1().catch((err) => { + throw err; + }); + assert(client.namingStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes checkLongRunningProgress with closed client', async () => { - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize1(); - const request = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.checkLongRunningProgress(request), expectedError); + it('has close method for the non-initialized client', (done) => { + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.namingStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); }); - describe('initialize', () => { - it('invokes initialize without error', async () => { - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize1(); - const request = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.initialize = stubSimpleCall(expectedResponse); - const [response] = await client.initialize(request); - assert.deepStrictEqual(response, expectedResponse); - }); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId1(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + }); - it('invokes initialize without error using callback', async () => { - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize1(); - const request = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.initialize = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.initialize( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId1( + (err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } + }, + ); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + }); + + describe('paginatedMethodStream', () => { + it('invokes paginatedMethodStream without error', async () => { + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize1(); + const request = generateSampleMessage(new protos.google.protobuf.Empty()); + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.paginatedMethodStream = + stubSimpleCall(expectedResponse); + const [response] = await client.paginatedMethodStream(request); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes initialize with error', async () => { - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize1(); - const request = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.initialize = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.initialize(request), expectedError); - }); + it('invokes paginatedMethodStream without error using callback', async () => { + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize1(); + const request = generateSampleMessage(new protos.google.protobuf.Empty()); + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.paginatedMethodStream = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.paginatedMethodStream( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes initialize with closed client', async () => { - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize1(); - const request = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.initialize(request), expectedError); - }); + it('invokes paginatedMethodStream with error', async () => { + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize1(); + const request = generateSampleMessage(new protos.google.protobuf.Empty()); + const expectedError = new Error('expected'); + client.innerApiCalls.paginatedMethodStream = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.paginatedMethodStream(request), + expectedError, + ); }); - describe('servicePath', () => { - it('invokes servicePath without error', async () => { - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize1(); - const request = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.servicePath = stubSimpleCall(expectedResponse); - const [response] = await client.servicePath(request); - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes paginatedMethodStream with closed client', async () => { + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize1(); + const request = generateSampleMessage(new protos.google.protobuf.Empty()); + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.paginatedMethodStream(request), + expectedError, + ); + }); + }); + + describe('paginatedMethodAsync', () => { + it('invokes paginatedMethodAsync without error', async () => { + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize1(); + const request = generateSampleMessage(new protos.google.protobuf.Empty()); + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.paginatedMethodAsync = + stubSimpleCall(expectedResponse); + const [response] = await client.paginatedMethodAsync(request); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes servicePath without error using callback', async () => { - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize1(); - const request = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.servicePath = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.servicePath( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes paginatedMethodAsync without error using callback', async () => { + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize1(); + const request = generateSampleMessage(new protos.google.protobuf.Empty()); + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.paginatedMethodAsync = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.paginatedMethodAsync( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes servicePath with error', async () => { - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize1(); - const request = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.servicePath = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.servicePath(request), expectedError); - }); + it('invokes paginatedMethodAsync with error', async () => { + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize1(); + const request = generateSampleMessage(new protos.google.protobuf.Empty()); + const expectedError = new Error('expected'); + client.innerApiCalls.paginatedMethodAsync = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.paginatedMethodAsync(request), expectedError); + }); - it('invokes servicePath with closed client', async () => { - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize1(); - const request = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.servicePath(request), expectedError); - }); + it('invokes paginatedMethodAsync with closed client', async () => { + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize1(); + const request = generateSampleMessage(new protos.google.protobuf.Empty()); + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.paginatedMethodAsync(request), expectedError); + }); + }); + + describe('checkLongRunningProgress', () => { + it('invokes checkLongRunningProgress without error', async () => { + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize1(); + const request = generateSampleMessage(new protos.google.protobuf.Empty()); + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.checkLongRunningProgress = + stubSimpleCall(expectedResponse); + const [response] = await client.checkLongRunningProgress(request); + assert.deepStrictEqual(response, expectedResponse); }); - describe('apiEndpoint', () => { - it('invokes apiEndpoint without error', async () => { - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize1(); - const request = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.apiEndpoint = stubSimpleCall(expectedResponse); - const [response] = await client.apiEndpoint(request); - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes checkLongRunningProgress without error using callback', async () => { + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize1(); + const request = generateSampleMessage(new protos.google.protobuf.Empty()); + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.checkLongRunningProgress = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.checkLongRunningProgress( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes apiEndpoint without error using callback', async () => { - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize1(); - const request = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.apiEndpoint = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.apiEndpoint( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes checkLongRunningProgress with error', async () => { + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize1(); + const request = generateSampleMessage(new protos.google.protobuf.Empty()); + const expectedError = new Error('expected'); + client.innerApiCalls.checkLongRunningProgress = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.checkLongRunningProgress(request), + expectedError, + ); + }); - it('invokes apiEndpoint with error', async () => { - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize1(); - const request = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.apiEndpoint = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.apiEndpoint(request), expectedError); - }); + it('invokes checkLongRunningProgress with closed client', async () => { + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize1(); + const request = generateSampleMessage(new protos.google.protobuf.Empty()); + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.checkLongRunningProgress(request), + expectedError, + ); + }); + }); + + describe('initialize', () => { + it('invokes initialize without error', async () => { + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize1(); + const request = generateSampleMessage(new protos.google.protobuf.Empty()); + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.initialize = stubSimpleCall(expectedResponse); + const [response] = await client.initialize(request); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes apiEndpoint with closed client', async () => { - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize1(); - const request = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.apiEndpoint(request), expectedError); - }); + it('invokes initialize without error using callback', async () => { + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize1(); + const request = generateSampleMessage(new protos.google.protobuf.Empty()); + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.initialize = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.initialize( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); }); - describe('port', () => { - it('invokes port without error', async () => { - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize1(); - const request = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.port = stubSimpleCall(expectedResponse); - const [response] = await client.port(request); - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes initialize with error', async () => { + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize1(); + const request = generateSampleMessage(new protos.google.protobuf.Empty()); + const expectedError = new Error('expected'); + client.innerApiCalls.initialize = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.initialize(request), expectedError); + }); - it('invokes port without error using callback', async () => { - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize1(); - const request = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.port = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.port( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes initialize with closed client', async () => { + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize1(); + const request = generateSampleMessage(new protos.google.protobuf.Empty()); + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.initialize(request), expectedError); + }); + }); + + describe('servicePath', () => { + it('invokes servicePath without error', async () => { + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize1(); + const request = generateSampleMessage(new protos.google.protobuf.Empty()); + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.servicePath = stubSimpleCall(expectedResponse); + const [response] = await client.servicePath(request); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes port with error', async () => { - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize1(); - const request = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.port = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.port(request), expectedError); - }); + it('invokes servicePath without error using callback', async () => { + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize1(); + const request = generateSampleMessage(new protos.google.protobuf.Empty()); + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.servicePath = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.servicePath( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes port with closed client', async () => { - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize1(); - const request = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.port(request), expectedError); - }); + it('invokes servicePath with error', async () => { + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize1(); + const request = generateSampleMessage(new protos.google.protobuf.Empty()); + const expectedError = new Error('expected'); + client.innerApiCalls.servicePath = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.servicePath(request), expectedError); }); - describe('scopes', () => { - it('invokes scopes without error', async () => { - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize1(); - const request = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.scopes = stubSimpleCall(expectedResponse); - const [response] = await client.scopes(request); - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes servicePath with closed client', async () => { + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize1(); + const request = generateSampleMessage(new protos.google.protobuf.Empty()); + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.servicePath(request), expectedError); + }); + }); + + describe('apiEndpoint', () => { + it('invokes apiEndpoint without error', async () => { + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize1(); + const request = generateSampleMessage(new protos.google.protobuf.Empty()); + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.apiEndpoint = stubSimpleCall(expectedResponse); + const [response] = await client.apiEndpoint(request); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes scopes without error using callback', async () => { - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize1(); - const request = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.scopes = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.scopes( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes apiEndpoint without error using callback', async () => { + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize1(); + const request = generateSampleMessage(new protos.google.protobuf.Empty()); + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.apiEndpoint = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.apiEndpoint( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes scopes with error', async () => { - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize1(); - const request = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.scopes = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.scopes(request), expectedError); - }); + it('invokes apiEndpoint with error', async () => { + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize1(); + const request = generateSampleMessage(new protos.google.protobuf.Empty()); + const expectedError = new Error('expected'); + client.innerApiCalls.apiEndpoint = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.apiEndpoint(request), expectedError); + }); - it('invokes scopes with closed client', async () => { - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize1(); - const request = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.scopes(request), expectedError); - }); + it('invokes apiEndpoint with closed client', async () => { + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize1(); + const request = generateSampleMessage(new protos.google.protobuf.Empty()); + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.apiEndpoint(request), expectedError); + }); + }); + + describe('port', () => { + it('invokes port without error', async () => { + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize1(); + const request = generateSampleMessage(new protos.google.protobuf.Empty()); + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.port = stubSimpleCall(expectedResponse); + const [response] = await client.port(request); + assert.deepStrictEqual(response, expectedResponse); }); - describe('getProjectId', () => { - it('invokes getProjectId without error', async () => { - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize1(); - const request = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.getProjectId = stubSimpleCall(expectedResponse); - const [response] = await client.getProjectId(request); - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes port without error using callback', async () => { + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize1(); + const request = generateSampleMessage(new protos.google.protobuf.Empty()); + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.port = stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.port( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes getProjectId without error using callback', async () => { - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize1(); - const request = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.getProjectId = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getProjectId( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes port with error', async () => { + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize1(); + const request = generateSampleMessage(new protos.google.protobuf.Empty()); + const expectedError = new Error('expected'); + client.innerApiCalls.port = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.port(request), expectedError); + }); - it('invokes getProjectId with error', async () => { - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize1(); - const request = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.getProjectId = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getProjectId(request), expectedError); - }); + it('invokes port with closed client', async () => { + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize1(); + const request = generateSampleMessage(new protos.google.protobuf.Empty()); + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.port(request), expectedError); + }); + }); + + describe('scopes', () => { + it('invokes scopes without error', async () => { + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize1(); + const request = generateSampleMessage(new protos.google.protobuf.Empty()); + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.scopes = stubSimpleCall(expectedResponse); + const [response] = await client.scopes(request); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes getProjectId with closed client', async () => { - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize1(); - const request = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getProjectId(request), expectedError); - }); + it('invokes scopes without error using callback', async () => { + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize1(); + const request = generateSampleMessage(new protos.google.protobuf.Empty()); + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.scopes = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.scopes( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); }); - describe('getReservedWord', () => { - it('invokes getReservedWord without error', async () => { - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize1(); - const request = generateSampleMessage( - new protos.google.naming.v1beta1.GetReservedWordRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.naming.v1beta1.ReservedWord() - ); - client.innerApiCalls.getReservedWord = stubSimpleCall(expectedResponse); - const [response] = await client.getReservedWord(request); - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes scopes with error', async () => { + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize1(); + const request = generateSampleMessage(new protos.google.protobuf.Empty()); + const expectedError = new Error('expected'); + client.innerApiCalls.scopes = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.scopes(request), expectedError); + }); - it('invokes getReservedWord without error using callback', async () => { - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize1(); - const request = generateSampleMessage( - new protos.google.naming.v1beta1.GetReservedWordRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.naming.v1beta1.ReservedWord() - ); - client.innerApiCalls.getReservedWord = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getReservedWord( - request, - (err?: Error|null, result?: protos.google.naming.v1beta1.IReservedWord|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes scopes with closed client', async () => { + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize1(); + const request = generateSampleMessage(new protos.google.protobuf.Empty()); + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.scopes(request), expectedError); + }); + }); + + describe('getProjectId', () => { + it('invokes getProjectId without error', async () => { + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize1(); + const request = generateSampleMessage(new protos.google.protobuf.Empty()); + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.getProjectId = stubSimpleCall(expectedResponse); + const [response] = await client.getProjectId(request); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes getReservedWord with error', async () => { - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize1(); - const request = generateSampleMessage( - new protos.google.naming.v1beta1.GetReservedWordRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.getReservedWord = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getReservedWord(request), expectedError); - }); + it('invokes getProjectId without error using callback', async () => { + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize1(); + const request = generateSampleMessage(new protos.google.protobuf.Empty()); + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.getProjectId = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getProjectId( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes getReservedWord with closed client', async () => { - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize1(); - const request = generateSampleMessage( - new protos.google.naming.v1beta1.GetReservedWordRequest() - ); - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getReservedWord(request), expectedError); - }); + it('invokes getProjectId with error', async () => { + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize1(); + const request = generateSampleMessage(new protos.google.protobuf.Empty()); + const expectedError = new Error('expected'); + client.innerApiCalls.getProjectId = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getProjectId(request), expectedError); }); - describe('createABCDESomething', () => { - it('invokes createABCDESomething without error', async () => { - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize1(); - const request = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.createAbcdeSomething = stubSimpleCall(expectedResponse); - const [response] = await client.createABCDESomething(request); - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes getProjectId with closed client', async () => { + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize1(); + const request = generateSampleMessage(new protos.google.protobuf.Empty()); + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getProjectId(request), expectedError); + }); + }); + + describe('getReservedWord', () => { + it('invokes getReservedWord without error', async () => { + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize1(); + const request = generateSampleMessage( + new protos.google.naming.v1beta1.GetReservedWordRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.naming.v1beta1.ReservedWord(), + ); + client.innerApiCalls.getReservedWord = stubSimpleCall(expectedResponse); + const [response] = await client.getReservedWord(request); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes createABCDESomething without error using callback', async () => { - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize1(); - const request = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.createAbcdeSomething = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createABCDESomething( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes getReservedWord without error using callback', async () => { + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize1(); + const request = generateSampleMessage( + new protos.google.naming.v1beta1.GetReservedWordRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.naming.v1beta1.ReservedWord(), + ); + client.innerApiCalls.getReservedWord = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getReservedWord( + request, + ( + err?: Error | null, + result?: protos.google.naming.v1beta1.IReservedWord | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes createABCDESomething with error', async () => { - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize1(); - const request = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.createAbcdeSomething = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createABCDESomething(request), expectedError); - }); + it('invokes getReservedWord with error', async () => { + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize1(); + const request = generateSampleMessage( + new protos.google.naming.v1beta1.GetReservedWordRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.getReservedWord = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getReservedWord(request), expectedError); + }); - it('invokes createABCDESomething with closed client', async () => { - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize1(); - const request = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createABCDESomething(request), expectedError); - }); + it('invokes getReservedWord with closed client', async () => { + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize1(); + const request = generateSampleMessage( + new protos.google.naming.v1beta1.GetReservedWordRequest(), + ); + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getReservedWord(request), expectedError); + }); + }); + + describe('createABCDESomething', () => { + it('invokes createABCDESomething without error', async () => { + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize1(); + const request = generateSampleMessage(new protos.google.protobuf.Empty()); + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.createAbcdeSomething = + stubSimpleCall(expectedResponse); + const [response] = await client.createABCDESomething(request); + assert.deepStrictEqual(response, expectedResponse); }); - describe('longRunning', () => { - it('invokes longRunning without error', async () => { - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize1(); - const request = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.longRunning = stubLongRunningCall(expectedResponse); - const [operation] = await client.longRunning(request); - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes createABCDESomething without error using callback', async () => { + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize1(); + const request = generateSampleMessage(new protos.google.protobuf.Empty()); + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.createAbcdeSomething = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createABCDESomething( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes longRunning without error using callback', async () => { - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize1(); - const request = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.longRunning = stubLongRunningCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.longRunning( - request, - (err?: Error|null, - result?: LROperation|null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const operation = await promise as LROperation; - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes createABCDESomething with error', async () => { + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize1(); + const request = generateSampleMessage(new protos.google.protobuf.Empty()); + const expectedError = new Error('expected'); + client.innerApiCalls.createAbcdeSomething = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.createABCDESomething(request), expectedError); + }); - it('invokes longRunning with call error', async () => { - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize1(); - const request = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.longRunning = stubLongRunningCall(undefined, expectedError); - await assert.rejects(client.longRunning(request), expectedError); - }); + it('invokes createABCDESomething with closed client', async () => { + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize1(); + const request = generateSampleMessage(new protos.google.protobuf.Empty()); + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.createABCDESomething(request), expectedError); + }); + }); + + describe('longRunning', () => { + it('invokes longRunning without error', async () => { + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize1(); + const request = generateSampleMessage(new protos.google.protobuf.Empty()); + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.longRunning = stubLongRunningCall(expectedResponse); + const [operation] = await client.longRunning(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes longRunning with LRO error', async () => { - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize1(); - const request = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.longRunning = stubLongRunningCall(undefined, undefined, expectedError); - const [operation] = await client.longRunning(request); - await assert.rejects(operation.promise(), expectedError); - }); + it('invokes longRunning without error using callback', async () => { + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize1(); + const request = generateSampleMessage(new protos.google.protobuf.Empty()); + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.longRunning = + stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.longRunning( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty + > | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const operation = (await promise) as LROperation< + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes checkLongRunningProgress1 without error', async () => { - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize1(); - const expectedResponse = generateSampleMessage( - new operationsProtos.google.longrunning.Operation() - ); - expectedResponse.name = 'test'; - expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; - expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')} - - client.operationsClient.getOperation = stubSimpleCall(expectedResponse); - const decodedOperation = await client.checkLongRunningProgress1(expectedResponse.name); - assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); - assert(decodedOperation.metadata); - assert((client.operationsClient.getOperation as SinonStub).getCall(0)); - }); + it('invokes longRunning with call error', async () => { + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize1(); + const request = generateSampleMessage(new protos.google.protobuf.Empty()); + const expectedError = new Error('expected'); + client.innerApiCalls.longRunning = stubLongRunningCall( + undefined, + expectedError, + ); + await assert.rejects(client.longRunning(request), expectedError); + }); - it('invokes checkLongRunningProgress1 with error', async () => { - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize1(); - const expectedError = new Error('expected'); - - client.operationsClient.getOperation = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.checkLongRunningProgress1(''), expectedError); - assert((client.operationsClient.getOperation as SinonStub) - .getCall(0)); - }); + it('invokes longRunning with LRO error', async () => { + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize1(); + const request = generateSampleMessage(new protos.google.protobuf.Empty()); + const expectedError = new Error('expected'); + client.innerApiCalls.longRunning = stubLongRunningCall( + undefined, + undefined, + expectedError, + ); + const [operation] = await client.longRunning(request); + await assert.rejects(operation.promise(), expectedError); }); - describe('paginatedMethod', () => { - it('invokes paginatedMethod without error', async () => { - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize1(); - const request = generateSampleMessage( - new protos.google.naming.v1beta1.PaginatedMethodRequest() - );const expectedResponse = [ - generateSampleMessage(new protos.google.protobuf.Empty()), - generateSampleMessage(new protos.google.protobuf.Empty()), - generateSampleMessage(new protos.google.protobuf.Empty()), - ]; - client.innerApiCalls.paginatedMethod = stubSimpleCall(expectedResponse); - const [response] = await client.paginatedMethod(request); - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes checkLongRunningProgress1 without error', async () => { + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize1(); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation(), + ); + expectedResponse.name = 'test'; + expectedResponse.response = { type_url: 'url', value: Buffer.from('') }; + expectedResponse.metadata = { type_url: 'url', value: Buffer.from('') }; + + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const decodedOperation = await client.checkLongRunningProgress1( + expectedResponse.name, + ); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); - it('invokes paginatedMethod without error using callback', async () => { - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize1(); - const request = generateSampleMessage( - new protos.google.naming.v1beta1.PaginatedMethodRequest() - );const expectedResponse = [ - generateSampleMessage(new protos.google.protobuf.Empty()), - generateSampleMessage(new protos.google.protobuf.Empty()), - generateSampleMessage(new protos.google.protobuf.Empty()), - ]; - client.innerApiCalls.paginatedMethod = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.paginatedMethod( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes checkLongRunningProgress1 with error', async () => { + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize1(); + const expectedError = new Error('expected'); + + client.operationsClient.getOperation = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.checkLongRunningProgress1(''), expectedError); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + }); + + describe('paginatedMethod', () => { + it('invokes paginatedMethod without error', async () => { + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize1(); + const request = generateSampleMessage( + new protos.google.naming.v1beta1.PaginatedMethodRequest(), + ); + const expectedResponse = [ + generateSampleMessage(new protos.google.protobuf.Empty()), + generateSampleMessage(new protos.google.protobuf.Empty()), + generateSampleMessage(new protos.google.protobuf.Empty()), + ]; + client.innerApiCalls.paginatedMethod = stubSimpleCall(expectedResponse); + const [response] = await client.paginatedMethod(request); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes paginatedMethod with error', async () => { - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize1(); - const request = generateSampleMessage( - new protos.google.naming.v1beta1.PaginatedMethodRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.paginatedMethod = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.paginatedMethod(request), expectedError); - }); + it('invokes paginatedMethod without error using callback', async () => { + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize1(); + const request = generateSampleMessage( + new protos.google.naming.v1beta1.PaginatedMethodRequest(), + ); + const expectedResponse = [ + generateSampleMessage(new protos.google.protobuf.Empty()), + generateSampleMessage(new protos.google.protobuf.Empty()), + generateSampleMessage(new protos.google.protobuf.Empty()), + ]; + client.innerApiCalls.paginatedMethod = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.paginatedMethod( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes paginatedMethodStream1 without error', async () => { - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize1(); - const request = generateSampleMessage( - new protos.google.naming.v1beta1.PaginatedMethodRequest() - ); - const expectedResponse = [ - generateSampleMessage(new protos.google.protobuf.Empty()), - generateSampleMessage(new protos.google.protobuf.Empty()), - generateSampleMessage(new protos.google.protobuf.Empty()), - ]; - client.descriptors.page.paginatedMethod.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.paginatedMethodStream1(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.protobuf.Empty[] = []; - stream.on('data', (response: protos.google.protobuf.Empty) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.paginatedMethod.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.paginatedMethod, request)); - }); + it('invokes paginatedMethod with error', async () => { + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize1(); + const request = generateSampleMessage( + new protos.google.naming.v1beta1.PaginatedMethodRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.paginatedMethod = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.paginatedMethod(request), expectedError); + }); - it('invokes paginatedMethodStream1 with error', async () => { - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize1(); - const request = generateSampleMessage( - new protos.google.naming.v1beta1.PaginatedMethodRequest() - ); - const expectedError = new Error('expected'); - client.descriptors.page.paginatedMethod.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.paginatedMethodStream1(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.protobuf.Empty[] = []; - stream.on('data', (response: protos.google.protobuf.Empty) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.paginatedMethod.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.paginatedMethod, request)); - }); + it('invokes paginatedMethodStream1 without error', async () => { + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize1(); + const request = generateSampleMessage( + new protos.google.naming.v1beta1.PaginatedMethodRequest(), + ); + const expectedResponse = [ + generateSampleMessage(new protos.google.protobuf.Empty()), + generateSampleMessage(new protos.google.protobuf.Empty()), + generateSampleMessage(new protos.google.protobuf.Empty()), + ]; + client.descriptors.page.paginatedMethod.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.paginatedMethodStream1(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.protobuf.Empty[] = []; + stream.on('data', (response: protos.google.protobuf.Empty) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.paginatedMethod.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.paginatedMethod, request), + ); + }); - it('uses async iteration with paginatedMethod without error', async () => { - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize1(); - const request = generateSampleMessage( - new protos.google.naming.v1beta1.PaginatedMethodRequest() - ); - const expectedResponse = [ - generateSampleMessage(new protos.google.protobuf.Empty()), - generateSampleMessage(new protos.google.protobuf.Empty()), - generateSampleMessage(new protos.google.protobuf.Empty()), - ]; - client.descriptors.page.paginatedMethod.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.protobuf.IEmpty[] = []; - const iterable = client.paginatedMethodAsync1(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.paginatedMethod.asyncIterate as SinonStub) - .getCall(0).args[1], request); - }); + it('invokes paginatedMethodStream1 with error', async () => { + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize1(); + const request = generateSampleMessage( + new protos.google.naming.v1beta1.PaginatedMethodRequest(), + ); + const expectedError = new Error('expected'); + client.descriptors.page.paginatedMethod.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.paginatedMethodStream1(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.protobuf.Empty[] = []; + stream.on('data', (response: protos.google.protobuf.Empty) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.paginatedMethod.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.paginatedMethod, request), + ); + }); - it('uses async iteration with paginatedMethod with error', async () => { - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize1(); - const request = generateSampleMessage( - new protos.google.naming.v1beta1.PaginatedMethodRequest() - ); - const expectedError = new Error('expected'); - client.descriptors.page.paginatedMethod.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.paginatedMethodAsync1(request); - await assert.rejects(async () => { - const responses: protos.google.protobuf.IEmpty[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.paginatedMethod.asyncIterate as SinonStub) - .getCall(0).args[1], request); - }); + it('uses async iteration with paginatedMethod without error', async () => { + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize1(); + const request = generateSampleMessage( + new protos.google.naming.v1beta1.PaginatedMethodRequest(), + ); + const expectedResponse = [ + generateSampleMessage(new protos.google.protobuf.Empty()), + generateSampleMessage(new protos.google.protobuf.Empty()), + generateSampleMessage(new protos.google.protobuf.Empty()), + ]; + client.descriptors.page.paginatedMethod.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.protobuf.IEmpty[] = []; + const iterable = client.paginatedMethodAsync1(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.paginatedMethod.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); }); - describe('Path templates', () => { - - describe('projectExport', () => { - const fakePath = "/rendered/path/projectExport"; - const expectedParameters = { - project: "projectValue", - export: "exportValue", - }; - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize1().catch(err => {throw err}); - client.pathTemplates.projectExportPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectExportPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectExportPath', () => { - const result = client.projectExportPath("projectValue", "exportValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectExportPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectExportName', () => { - const result = client.matchProjectFromProjectExportName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectExportPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchExportFromProjectExportName', () => { - const result = client.matchExportFromProjectExportName(fakePath); - assert.strictEqual(result, "exportValue"); - assert((client.pathTemplates.projectExportPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('uses async iteration with paginatedMethod with error', async () => { + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize1(); + const request = generateSampleMessage( + new protos.google.naming.v1beta1.PaginatedMethodRequest(), + ); + const expectedError = new Error('expected'); + client.descriptors.page.paginatedMethod.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.paginatedMethodAsync1(request); + await assert.rejects(async () => { + const responses: protos.google.protobuf.IEmpty[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.paginatedMethod.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + }); + }); + + describe('Path templates', () => { + describe('projectExport', () => { + const fakePath = '/rendered/path/projectExport'; + const expectedParameters = { + project: 'projectValue', + export: 'exportValue', + }; + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize1().catch((err) => { + throw err; + }); + client.pathTemplates.projectExportPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectExportPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectExportPath', () => { + const result = client.projectExportPath('projectValue', 'exportValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.projectExportPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectExportName', () => { + const result = client.matchProjectFromProjectExportName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.projectExportPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchExportFromProjectExportName', () => { + const result = client.matchExportFromProjectExportName(fakePath); + assert.strictEqual(result, 'exportValue'); + assert( + (client.pathTemplates.projectExportPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectPackage', () => { - const fakePath = "/rendered/path/projectPackage"; - const expectedParameters = { - project: "projectValue", - package: "packageValue", - }; - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize1().catch(err => {throw err}); - client.pathTemplates.projectPackagePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectPackagePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectPackagePath', () => { - const result = client.projectPackagePath("projectValue", "packageValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectPackagePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectPackageName', () => { - const result = client.matchProjectFromProjectPackageName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectPackagePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchPackageFromProjectPackageName', () => { - const result = client.matchPackageFromProjectPackageName(fakePath); - assert.strictEqual(result, "packageValue"); - assert((client.pathTemplates.projectPackagePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectPackage', () => { + const fakePath = '/rendered/path/projectPackage'; + const expectedParameters = { + project: 'projectValue', + package: 'packageValue', + }; + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize1().catch((err) => { + throw err; + }); + client.pathTemplates.projectPackagePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectPackagePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectPackagePath', () => { + const result = client.projectPackagePath( + 'projectValue', + 'packageValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.projectPackagePathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectPackageName', () => { + const result = client.matchProjectFromProjectPackageName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.projectPackagePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchPackageFromProjectPackageName', () => { + const result = client.matchPackageFromProjectPackageName(fakePath); + assert.strictEqual(result, 'packageValue'); + assert( + (client.pathTemplates.projectPackagePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/core/generator/gapic-generator-typescript/baselines/naming/src/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/naming/src/index.ts.baseline index a801f1255dde..472e2c56011f 100644 --- a/core/generator/gapic-generator-typescript/baselines/naming/src/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/naming/src/index.ts.baseline @@ -19,7 +19,7 @@ import * as v1beta1 from './v1beta1'; const NamingClient = v1beta1.NamingClient; type NamingClient = v1beta1.NamingClient; -export {v1beta1, NamingClient}; -export default {v1beta1, NamingClient}; +export { v1beta1, NamingClient }; +export default { v1beta1, NamingClient }; import * as protos from '../protos/protos'; -export {protos} +export { protos }; diff --git a/core/generator/gapic-generator-typescript/baselines/naming/src/v1beta1/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/naming/src/v1beta1/index.ts.baseline index 8f1ba3abce00..2d80d0e2ed96 100644 --- a/core/generator/gapic-generator-typescript/baselines/naming/src/v1beta1/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/naming/src/v1beta1/index.ts.baseline @@ -16,4 +16,4 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -export {NamingClient} from './naming_client'; +export { NamingClient } from './naming_client'; diff --git a/core/generator/gapic-generator-typescript/baselines/naming/src/v1beta1/naming_client.ts.baseline b/core/generator/gapic-generator-typescript/baselines/naming/src/v1beta1/naming_client.ts.baseline index 1410bbf39684..3211f90e6ff0 100644 --- a/core/generator/gapic-generator-typescript/baselines/naming/src/v1beta1/naming_client.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/naming/src/v1beta1/naming_client.ts.baseline @@ -18,11 +18,20 @@ /* global window */ import type * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions, GrpcClientOptions, LROperation, PaginationCallback, GaxCall} from 'google-gax'; -import {Transform} from 'stream'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + GrpcClientOptions, + LROperation, + PaginationCallback, + GaxCall, +} from 'google-gax'; +import { Transform } from 'stream'; import * as protos from '../../protos/protos'; import jsonProtos = require('../../protos/protos.json'); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; /** * Client JSON configuration object, loaded from @@ -44,7 +53,7 @@ export class NamingClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('naming'); @@ -57,10 +66,10 @@ export class NamingClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; operationsClient: gax.OperationsClient; - namingStub?: Promise<{[name: string]: Function}>; + namingStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of NamingClient. @@ -101,21 +110,42 @@ export class NamingClient { * const client = new NamingClient({fallback: true}, gax); * ``` */ - constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { // Ensure that options include all the required fields. const staticMembers = this.constructor as typeof NamingClient; - if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { - throw new Error('Please set either universe_domain or universeDomain, but not both.'); + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); } - const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; - this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; this._servicePath = 'localhost'; - const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port1; const clientConfig = opts?.clientConfig ?? {}; - const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. if (servicePath !== this._servicePath && !('scopes' in opts)) { @@ -137,7 +167,7 @@ export class NamingClient { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; @@ -151,10 +181,7 @@ export class NamingClient { } // Determine the client header string. - const clientHeader = [ - `gax/${this._gaxModule.version}`, - `gapic/${version}`, - ]; + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/${process.versions.node}`); } else { @@ -176,10 +203,10 @@ export class NamingClient { // Create useful helper objects for these. this.pathTemplates = { projectExportPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/exports/{export}' + 'projects/{project}/exports/{export}', ), projectPackagePathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/packages/{package}' + 'projects/{project}/packages/{package}', ), }; @@ -187,8 +214,11 @@ export class NamingClient { // (e.g. 50 results at a time, with tokens to get subsequent // pages). Denote the keys used for pagination and results. this.descriptors.page = { - paginatedMethod: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'content') + paginatedMethod: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'content', + ), }; const protoFilesRoot = this._gaxModule.protobufFromJSON(jsonProtos); @@ -197,29 +227,37 @@ export class NamingClient { // rather than holding a request open. const lroOptions: GrpcClientOptions = { auth: this.auth, - grpc: 'grpc' in this._gaxGrpc ? this._gaxGrpc.grpc : undefined + grpc: 'grpc' in this._gaxGrpc ? this._gaxGrpc.grpc : undefined, }; if (opts.fallback) { lroOptions.protoJson = protoFilesRoot; lroOptions.httpRules = []; } - this.operationsClient = this._gaxModule.lro(lroOptions).operationsClient(opts); + this.operationsClient = this._gaxModule + .lro(lroOptions) + .operationsClient(opts); const longRunningResponse = protoFilesRoot.lookup( - '.google.protobuf.Empty') as gax.protobuf.Type; + '.google.protobuf.Empty', + ) as gax.protobuf.Type; const longRunningMetadata = protoFilesRoot.lookup( - '.google.protobuf.Empty') as gax.protobuf.Type; + '.google.protobuf.Empty', + ) as gax.protobuf.Type; this.descriptors.longrunning = { longRunning: new this._gaxModule.LongrunningDescriptor( this.operationsClient, longRunningResponse.decode.bind(longRunningResponse), - longRunningMetadata.decode.bind(longRunningMetadata)) + longRunningMetadata.decode.bind(longRunningMetadata), + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.naming.v1beta1.Naming', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.naming.v1beta1.Naming', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + { 'x-goog-api-client': clientHeader.join(' ') }, + ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -250,28 +288,47 @@ export class NamingClient { // Put together the "service stub" for // google.naming.v1beta1.Naming. this.namingStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.naming.v1beta1.Naming') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.naming.v1beta1.Naming', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.naming.v1beta1.Naming, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts, + this._providedCustomServicePath, + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const namingStubMethods = - ['paginatedMethod', 'paginatedMethodStream', 'paginatedMethodAsync', 'longRunning', 'checkLongRunningProgress', 'initialize', 'servicePath', 'apiEndpoint', 'port', 'scopes', 'getProjectId', 'getReservedWord', 'createAbcdeSomething']; + const namingStubMethods = [ + 'paginatedMethod', + 'paginatedMethodStream', + 'paginatedMethodAsync', + 'longRunning', + 'checkLongRunningProgress', + 'initialize', + 'servicePath', + 'apiEndpoint', + 'port', + 'scopes', + 'getProjectId', + 'getReservedWord', + 'createAbcdeSomething', + ]; for (const methodName of namingStubMethods) { const callPromise = this.namingStub.then( - stub => (...args: Array<{}>) => { - if (this._terminated) { - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error|null|undefined) => () => { + (stub) => + (...args: Array<{}>) => { + if (this._terminated) { + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { throw err; - }); + }, + ); const descriptor = this.descriptors.page[methodName] || @@ -281,7 +338,7 @@ export class NamingClient { callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -296,8 +353,14 @@ export class NamingClient { * @returns {string} The DNS address for this service. */ static get servicePath1() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static servicePath1 is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath1 is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'localhost'; } @@ -308,8 +371,14 @@ export class NamingClient { * @returns {string} The DNS address for this service. */ static get apiEndpoint1() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static apiEndpoint1 is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint1 is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'localhost'; } @@ -349,8 +418,9 @@ export class NamingClient { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId1(callback?: Callback): - Promise|void { + getProjectId1( + callback?: Callback, + ): Promise | void { if (callback) { this.auth.getProjectId(callback); return; @@ -361,1129 +431,1539 @@ export class NamingClient { // ------------------- // -- Service calls -- // ------------------- -/** - * - * @param {Object} request - * The request object that will be sent. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/naming.paginated_method_stream.js - * region_tag:localhost_v1beta1_generated_Naming_PaginatedMethodStream_async - */ + /** + * + * @param {Object} request + * The request object that will be sent. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/naming.paginated_method_stream.js + * region_tag:localhost_v1beta1_generated_Naming_PaginatedMethodStream_async + */ paginatedMethodStream( - request?: protos.google.protobuf.IEmpty, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|undefined, {}|undefined - ]>; + request?: protos.google.protobuf.IEmpty, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | undefined, + {} | undefined, + ] + >; paginatedMethodStream( - request: protos.google.protobuf.IEmpty, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|null|undefined, - {}|null|undefined>): void; + request: protos.google.protobuf.IEmpty, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | null | undefined, + {} | null | undefined + >, + ): void; paginatedMethodStream( - request: protos.google.protobuf.IEmpty, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|null|undefined, - {}|null|undefined>): void; + request: protos.google.protobuf.IEmpty, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | null | undefined, + {} | null | undefined + >, + ): void; paginatedMethodStream( - request?: protos.google.protobuf.IEmpty, - optionsOrCallback?: CallOptions|Callback< - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.protobuf.IEmpty, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|undefined, {}|undefined - ]>|void { + protos.google.protobuf.IEmpty | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize1().catch(err => {throw err}); + this.initialize1().catch((err) => { + throw err; + }); this._log.info('paginatedMethodStream request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('paginatedMethodStream response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.paginatedMethodStream(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|undefined, - {}|undefined - ]) => { - this._log.info('paginatedMethodStream response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .paginatedMethodStream(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | undefined, + {} | undefined, + ]) => { + this._log.info('paginatedMethodStream response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * - * @param {Object} request - * The request object that will be sent. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/naming.paginated_method_async.js - * region_tag:localhost_v1beta1_generated_Naming_PaginatedMethodAsync_async - */ + /** + * + * @param {Object} request + * The request object that will be sent. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/naming.paginated_method_async.js + * region_tag:localhost_v1beta1_generated_Naming_PaginatedMethodAsync_async + */ paginatedMethodAsync( - request?: protos.google.protobuf.IEmpty, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|undefined, {}|undefined - ]>; + request?: protos.google.protobuf.IEmpty, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | undefined, + {} | undefined, + ] + >; paginatedMethodAsync( - request: protos.google.protobuf.IEmpty, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|null|undefined, - {}|null|undefined>): void; + request: protos.google.protobuf.IEmpty, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | null | undefined, + {} | null | undefined + >, + ): void; paginatedMethodAsync( - request: protos.google.protobuf.IEmpty, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|null|undefined, - {}|null|undefined>): void; + request: protos.google.protobuf.IEmpty, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | null | undefined, + {} | null | undefined + >, + ): void; paginatedMethodAsync( - request?: protos.google.protobuf.IEmpty, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.protobuf.IEmpty, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|undefined, {}|undefined - ]>|void { + protos.google.protobuf.IEmpty | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize1().catch(err => {throw err}); + this.initialize1().catch((err) => { + throw err; + }); this._log.info('paginatedMethodAsync request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('paginatedMethodAsync response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.paginatedMethodAsync(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|undefined, - {}|undefined - ]) => { - this._log.info('paginatedMethodAsync response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .paginatedMethodAsync(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | undefined, + {} | undefined, + ]) => { + this._log.info('paginatedMethodAsync response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * - * @param {Object} request - * The request object that will be sent. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/naming.check_long_running_progress.js - * region_tag:localhost_v1beta1_generated_Naming_CheckLongRunningProgress_async - */ + /** + * + * @param {Object} request + * The request object that will be sent. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/naming.check_long_running_progress.js + * region_tag:localhost_v1beta1_generated_Naming_CheckLongRunningProgress_async + */ checkLongRunningProgress( - request?: protos.google.protobuf.IEmpty, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|undefined, {}|undefined - ]>; + request?: protos.google.protobuf.IEmpty, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | undefined, + {} | undefined, + ] + >; checkLongRunningProgress( - request: protos.google.protobuf.IEmpty, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|null|undefined, - {}|null|undefined>): void; + request: protos.google.protobuf.IEmpty, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | null | undefined, + {} | null | undefined + >, + ): void; checkLongRunningProgress( - request: protos.google.protobuf.IEmpty, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|null|undefined, - {}|null|undefined>): void; + request: protos.google.protobuf.IEmpty, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | null | undefined, + {} | null | undefined + >, + ): void; checkLongRunningProgress( - request?: protos.google.protobuf.IEmpty, - optionsOrCallback?: CallOptions|Callback< - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.protobuf.IEmpty, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|undefined, {}|undefined - ]>|void { + protos.google.protobuf.IEmpty | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize1().catch(err => {throw err}); + this.initialize1().catch((err) => { + throw err; + }); this._log.info('checkLongRunningProgress request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('checkLongRunningProgress response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.checkLongRunningProgress(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|undefined, - {}|undefined - ]) => { - this._log.info('checkLongRunningProgress response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .checkLongRunningProgress(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | undefined, + {} | undefined, + ]) => { + this._log.info('checkLongRunningProgress response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Problem #3: RPCs that conflict with auto-generated methods - * - * @param {Object} request - * The request object that will be sent. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/naming.initialize.js - * region_tag:localhost_v1beta1_generated_Naming_Initialize_async - */ + /** + * Problem #3: RPCs that conflict with auto-generated methods + * + * @param {Object} request + * The request object that will be sent. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/naming.initialize.js + * region_tag:localhost_v1beta1_generated_Naming_Initialize_async + */ initialize( - request?: protos.google.protobuf.IEmpty, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|undefined, {}|undefined - ]>; + request?: protos.google.protobuf.IEmpty, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | undefined, + {} | undefined, + ] + >; initialize( - request: protos.google.protobuf.IEmpty, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|null|undefined, - {}|null|undefined>): void; + request: protos.google.protobuf.IEmpty, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | null | undefined, + {} | null | undefined + >, + ): void; initialize( - request: protos.google.protobuf.IEmpty, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|null|undefined, - {}|null|undefined>): void; + request: protos.google.protobuf.IEmpty, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | null | undefined, + {} | null | undefined + >, + ): void; initialize( - request?: protos.google.protobuf.IEmpty, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.protobuf.IEmpty, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|undefined, {}|undefined - ]>|void { + protos.google.protobuf.IEmpty | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize1().catch(err => {throw err}); + this.initialize1().catch((err) => { + throw err; + }); this._log.info('initialize request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('initialize response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.initialize(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|undefined, - {}|undefined - ]) => { - this._log.info('initialize response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .initialize(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | undefined, + {} | undefined, + ]) => { + this._log.info('initialize response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * - * @param {Object} request - * The request object that will be sent. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/naming.service_path.js - * region_tag:localhost_v1beta1_generated_Naming_ServicePath_async - */ + /** + * + * @param {Object} request + * The request object that will be sent. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/naming.service_path.js + * region_tag:localhost_v1beta1_generated_Naming_ServicePath_async + */ servicePath( - request?: protos.google.protobuf.IEmpty, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|undefined, {}|undefined - ]>; + request?: protos.google.protobuf.IEmpty, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | undefined, + {} | undefined, + ] + >; servicePath( - request: protos.google.protobuf.IEmpty, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|null|undefined, - {}|null|undefined>): void; + request: protos.google.protobuf.IEmpty, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | null | undefined, + {} | null | undefined + >, + ): void; servicePath( - request: protos.google.protobuf.IEmpty, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|null|undefined, - {}|null|undefined>): void; + request: protos.google.protobuf.IEmpty, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | null | undefined, + {} | null | undefined + >, + ): void; servicePath( - request?: protos.google.protobuf.IEmpty, - optionsOrCallback?: CallOptions|Callback< - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.protobuf.IEmpty, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|undefined, {}|undefined - ]>|void { + protos.google.protobuf.IEmpty | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize1().catch(err => {throw err}); + this.initialize1().catch((err) => { + throw err; + }); this._log.info('servicePath request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('servicePath response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.servicePath(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|undefined, - {}|undefined - ]) => { - this._log.info('servicePath response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .servicePath(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | undefined, + {} | undefined, + ]) => { + this._log.info('servicePath response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * - * @param {Object} request - * The request object that will be sent. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/naming.api_endpoint.js - * region_tag:localhost_v1beta1_generated_Naming_ApiEndpoint_async - */ + /** + * + * @param {Object} request + * The request object that will be sent. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/naming.api_endpoint.js + * region_tag:localhost_v1beta1_generated_Naming_ApiEndpoint_async + */ apiEndpoint( - request?: protos.google.protobuf.IEmpty, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|undefined, {}|undefined - ]>; + request?: protos.google.protobuf.IEmpty, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | undefined, + {} | undefined, + ] + >; apiEndpoint( - request: protos.google.protobuf.IEmpty, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|null|undefined, - {}|null|undefined>): void; + request: protos.google.protobuf.IEmpty, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | null | undefined, + {} | null | undefined + >, + ): void; apiEndpoint( - request: protos.google.protobuf.IEmpty, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|null|undefined, - {}|null|undefined>): void; + request: protos.google.protobuf.IEmpty, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | null | undefined, + {} | null | undefined + >, + ): void; apiEndpoint( - request?: protos.google.protobuf.IEmpty, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.protobuf.IEmpty, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|undefined, {}|undefined - ]>|void { + protos.google.protobuf.IEmpty | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize1().catch(err => {throw err}); + this.initialize1().catch((err) => { + throw err; + }); this._log.info('apiEndpoint request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('apiEndpoint response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.apiEndpoint(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|undefined, - {}|undefined - ]) => { - this._log.info('apiEndpoint response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .apiEndpoint(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | undefined, + {} | undefined, + ]) => { + this._log.info('apiEndpoint response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * - * @param {Object} request - * The request object that will be sent. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/naming.port.js - * region_tag:localhost_v1beta1_generated_Naming_Port_async - */ + /** + * + * @param {Object} request + * The request object that will be sent. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/naming.port.js + * region_tag:localhost_v1beta1_generated_Naming_Port_async + */ port( - request?: protos.google.protobuf.IEmpty, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|undefined, {}|undefined - ]>; + request?: protos.google.protobuf.IEmpty, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | undefined, + {} | undefined, + ] + >; port( - request: protos.google.protobuf.IEmpty, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|null|undefined, - {}|null|undefined>): void; + request: protos.google.protobuf.IEmpty, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | null | undefined, + {} | null | undefined + >, + ): void; port( - request: protos.google.protobuf.IEmpty, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|null|undefined, - {}|null|undefined>): void; + request: protos.google.protobuf.IEmpty, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | null | undefined, + {} | null | undefined + >, + ): void; port( - request?: protos.google.protobuf.IEmpty, - optionsOrCallback?: CallOptions|Callback< - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.protobuf.IEmpty, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|undefined, {}|undefined - ]>|void { + protos.google.protobuf.IEmpty | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize1().catch(err => {throw err}); + this.initialize1().catch((err) => { + throw err; + }); this._log.info('port request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('port response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.port(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|undefined, - {}|undefined - ]) => { - this._log.info('port response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .port(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | undefined, + {} | undefined, + ]) => { + this._log.info('port response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * - * @param {Object} request - * The request object that will be sent. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/naming.scopes.js - * region_tag:localhost_v1beta1_generated_Naming_Scopes_async - */ + /** + * + * @param {Object} request + * The request object that will be sent. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/naming.scopes.js + * region_tag:localhost_v1beta1_generated_Naming_Scopes_async + */ scopes( - request?: protos.google.protobuf.IEmpty, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|undefined, {}|undefined - ]>; + request?: protos.google.protobuf.IEmpty, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | undefined, + {} | undefined, + ] + >; scopes( - request: protos.google.protobuf.IEmpty, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|null|undefined, - {}|null|undefined>): void; + request: protos.google.protobuf.IEmpty, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | null | undefined, + {} | null | undefined + >, + ): void; scopes( - request: protos.google.protobuf.IEmpty, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|null|undefined, - {}|null|undefined>): void; + request: protos.google.protobuf.IEmpty, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | null | undefined, + {} | null | undefined + >, + ): void; scopes( - request?: protos.google.protobuf.IEmpty, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.protobuf.IEmpty, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|undefined, {}|undefined - ]>|void { + protos.google.protobuf.IEmpty | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize1().catch(err => {throw err}); + this.initialize1().catch((err) => { + throw err; + }); this._log.info('scopes request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('scopes response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.scopes(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|undefined, - {}|undefined - ]) => { - this._log.info('scopes response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .scopes(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | undefined, + {} | undefined, + ]) => { + this._log.info('scopes response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * - * @param {Object} request - * The request object that will be sent. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/naming.get_project_id.js - * region_tag:localhost_v1beta1_generated_Naming_getProjectId_async - */ + /** + * + * @param {Object} request + * The request object that will be sent. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/naming.get_project_id.js + * region_tag:localhost_v1beta1_generated_Naming_getProjectId_async + */ getProjectId( - request?: protos.google.protobuf.IEmpty, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|undefined, {}|undefined - ]>; + request?: protos.google.protobuf.IEmpty, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | undefined, + {} | undefined, + ] + >; getProjectId( - request: protos.google.protobuf.IEmpty, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|null|undefined, - {}|null|undefined>): void; + request: protos.google.protobuf.IEmpty, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | null | undefined, + {} | null | undefined + >, + ): void; getProjectId( - request: protos.google.protobuf.IEmpty, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|null|undefined, - {}|null|undefined>): void; + request: protos.google.protobuf.IEmpty, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | null | undefined, + {} | null | undefined + >, + ): void; getProjectId( - request?: protos.google.protobuf.IEmpty, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.protobuf.IEmpty, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|undefined, {}|undefined - ]>|void { + protos.google.protobuf.IEmpty | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize1().catch(err => {throw err}); + this.initialize1().catch((err) => { + throw err; + }); this._log.info('getProjectId request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getProjectId response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getProjectId(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|undefined, - {}|undefined - ]) => { - this._log.info('getProjectId response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getProjectId(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | undefined, + {} | undefined, + ]) => { + this._log.info('getProjectId response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.word - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.naming.v1beta1.ReservedWord|ReservedWord}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/naming.get_reserved_word.js - * region_tag:localhost_v1beta1_generated_Naming_getReservedWord_async - */ + /** + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.word + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.naming.v1beta1.ReservedWord|ReservedWord}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/naming.get_reserved_word.js + * region_tag:localhost_v1beta1_generated_Naming_getReservedWord_async + */ getReservedWord( - request?: protos.google.naming.v1beta1.IGetReservedWordRequest, - options?: CallOptions): - Promise<[ - protos.google.naming.v1beta1.IReservedWord, - protos.google.naming.v1beta1.IGetReservedWordRequest|undefined, {}|undefined - ]>; + request?: protos.google.naming.v1beta1.IGetReservedWordRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.naming.v1beta1.IReservedWord, + protos.google.naming.v1beta1.IGetReservedWordRequest | undefined, + {} | undefined, + ] + >; getReservedWord( - request: protos.google.naming.v1beta1.IGetReservedWordRequest, - options: CallOptions, - callback: Callback< - protos.google.naming.v1beta1.IReservedWord, - protos.google.naming.v1beta1.IGetReservedWordRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.naming.v1beta1.IGetReservedWordRequest, + options: CallOptions, + callback: Callback< + protos.google.naming.v1beta1.IReservedWord, + protos.google.naming.v1beta1.IGetReservedWordRequest | null | undefined, + {} | null | undefined + >, + ): void; getReservedWord( - request: protos.google.naming.v1beta1.IGetReservedWordRequest, - callback: Callback< - protos.google.naming.v1beta1.IReservedWord, - protos.google.naming.v1beta1.IGetReservedWordRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.naming.v1beta1.IGetReservedWordRequest, + callback: Callback< + protos.google.naming.v1beta1.IReservedWord, + protos.google.naming.v1beta1.IGetReservedWordRequest | null | undefined, + {} | null | undefined + >, + ): void; getReservedWord( - request?: protos.google.naming.v1beta1.IGetReservedWordRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.naming.v1beta1.IReservedWord, - protos.google.naming.v1beta1.IGetReservedWordRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.naming.v1beta1.IGetReservedWordRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.naming.v1beta1.IReservedWord, - protos.google.naming.v1beta1.IGetReservedWordRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.naming.v1beta1.IReservedWord, - protos.google.naming.v1beta1.IGetReservedWordRequest|undefined, {}|undefined - ]>|void { + | protos.google.naming.v1beta1.IGetReservedWordRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.naming.v1beta1.IReservedWord, + protos.google.naming.v1beta1.IGetReservedWordRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.naming.v1beta1.IReservedWord, + protos.google.naming.v1beta1.IGetReservedWordRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize1().catch(err => {throw err}); + this.initialize1().catch((err) => { + throw err; + }); this._log.info('getReservedWord request %j', request); - const wrappedCallback: Callback< - protos.google.naming.v1beta1.IReservedWord, - protos.google.naming.v1beta1.IGetReservedWordRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.naming.v1beta1.IReservedWord, + | protos.google.naming.v1beta1.IGetReservedWordRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getReservedWord response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getReservedWord(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.naming.v1beta1.IReservedWord, - protos.google.naming.v1beta1.IGetReservedWordRequest|undefined, - {}|undefined - ]) => { - this._log.info('getReservedWord response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getReservedWord(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.naming.v1beta1.IReservedWord, + protos.google.naming.v1beta1.IGetReservedWordRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getReservedWord response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * - * @param {Object} request - * The request object that will be sent. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/naming.create_a_b_c_d_e_something.js - * region_tag:localhost_v1beta1_generated_Naming_createABCDESomething_async - */ + /** + * + * @param {Object} request + * The request object that will be sent. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/naming.create_a_b_c_d_e_something.js + * region_tag:localhost_v1beta1_generated_Naming_createABCDESomething_async + */ createABCDESomething( - request?: protos.google.protobuf.IEmpty, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|undefined, {}|undefined - ]>; + request?: protos.google.protobuf.IEmpty, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | undefined, + {} | undefined, + ] + >; createABCDESomething( - request: protos.google.protobuf.IEmpty, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|null|undefined, - {}|null|undefined>): void; + request: protos.google.protobuf.IEmpty, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | null | undefined, + {} | null | undefined + >, + ): void; createABCDESomething( - request: protos.google.protobuf.IEmpty, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|null|undefined, - {}|null|undefined>): void; + request: protos.google.protobuf.IEmpty, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | null | undefined, + {} | null | undefined + >, + ): void; createABCDESomething( - request?: protos.google.protobuf.IEmpty, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.protobuf.IEmpty, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|undefined, {}|undefined - ]>|void { + protos.google.protobuf.IEmpty | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize1().catch(err => {throw err}); + this.initialize1().catch((err) => { + throw err; + }); this._log.info('createABCDESomething request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createABCDESomething response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.createAbcdeSomething(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.protobuf.IEmpty|undefined, - {}|undefined - ]) => { - this._log.info('createABCDESomething response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createAbcdeSomething(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty | undefined, + {} | undefined, + ]) => { + this._log.info('createABCDESomething response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Problem #2: long running method generates extra method check*Progress() - * - * @param {Object} request - * The request object that will be sent. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing - * a long running operation. Its `promise()` method returns a promise - * you can `await` for. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/naming.long_running.js - * region_tag:localhost_v1beta1_generated_Naming_LongRunning_async - */ + /** + * Problem #2: long running method generates extra method check*Progress() + * + * @param {Object} request + * The request object that will be sent. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/naming.long_running.js + * region_tag:localhost_v1beta1_generated_Naming_LongRunning_async + */ longRunning( - request?: protos.google.protobuf.IEmpty, - options?: CallOptions): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>; + request?: protos.google.protobuf.IEmpty, + options?: CallOptions, + ): Promise< + [ + LROperation, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; longRunning( - request: protos.google.protobuf.IEmpty, - options: CallOptions, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.protobuf.IEmpty, + options: CallOptions, + callback: Callback< + LROperation, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; longRunning( - request: protos.google.protobuf.IEmpty, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.protobuf.IEmpty, + callback: Callback< + LROperation, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; longRunning( - request?: protos.google.protobuf.IEmpty, - optionsOrCallback?: CallOptions|Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>, - callback?: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>|void { + request?: protos.google.protobuf.IEmpty, + optionsOrCallback?: + | CallOptions + | Callback< + LROperation< + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + callback?: Callback< + LROperation, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + LROperation, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize1().catch(err => {throw err}); - const wrappedCallback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>|undefined = callback + this.initialize1().catch((err) => { + throw err; + }); + const wrappedCallback: + | Callback< + LROperation< + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, rawResponse, _) => { this._log.info('longRunning response %j', rawResponse); callback!(error, response, rawResponse, _); // We verified callback above. } : undefined; this._log.info('longRunning request %j', request); - return this.innerApiCalls.longRunning(request, options, wrappedCallback) - ?.then(([response, rawResponse, _]: [ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]) => { - this._log.info('longRunning response %j', rawResponse); - return [response, rawResponse, _]; - }); + return this.innerApiCalls + .longRunning(request, options, wrappedCallback) + ?.then( + ([response, rawResponse, _]: [ + LROperation< + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ]) => { + this._log.info('longRunning response %j', rawResponse); + return [response, rawResponse, _]; + }, + ); } -/** - * Check the status of the long running operation returned by `longRunning()`. - * @param {String} name - * The operation name that will be passed. - * @returns {Promise} - The promise which resolves to an object. - * The decoded operation object has result and metadata field to get information from. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/naming.long_running.js - * region_tag:localhost_v1beta1_generated_Naming_LongRunning_async - */ - async checkLongRunningProgress1(name: string): Promise>{ + /** + * Check the status of the long running operation returned by `longRunning()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/naming.long_running.js + * region_tag:localhost_v1beta1_generated_Naming_LongRunning_async + */ + async checkLongRunningProgress1( + name: string, + ): Promise< + LROperation + > { this._log.info('longRunning long-running'); - const request = new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest({name}); + const request = + new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( + { name }, + ); const [operation] = await this.operationsClient.getOperation(request); - const decodeOperation = new this._gaxModule.Operation(operation, this.descriptors.longrunning.longRunning, this._gaxModule.createDefaultBackoffSettings()); - return decodeOperation as LROperation; + const decodeOperation = new this._gaxModule.Operation( + operation, + this.descriptors.longrunning.longRunning, + this._gaxModule.createDefaultBackoffSettings(), + ); + return decodeOperation as LROperation< + protos.google.protobuf.Empty, + protos.google.protobuf.Empty + >; } - /** - * Problem #1: paginated method generates extra methods *Stream() and - * *Async(), which might conflict with unary methods with the same names. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.protobuf.Empty} request.content - * @param {number} request.pageSize - * @param {string} request.pageToken - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.protobuf.Empty|Empty}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `paginatedMethodAsync1()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Problem #1: paginated method generates extra methods *Stream() and + * *Async(), which might conflict with unary methods with the same names. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.protobuf.Empty} request.content + * @param {number} request.pageSize + * @param {string} request.pageToken + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.protobuf.Empty|Empty}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `paginatedMethodAsync1()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ paginatedMethod( - request?: protos.google.naming.v1beta1.IPaginatedMethodRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty[], - protos.google.naming.v1beta1.IPaginatedMethodRequest|null, - protos.google.naming.v1beta1.IPaginatedMethodResponse - ]>; + request?: protos.google.naming.v1beta1.IPaginatedMethodRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty[], + protos.google.naming.v1beta1.IPaginatedMethodRequest | null, + protos.google.naming.v1beta1.IPaginatedMethodResponse, + ] + >; paginatedMethod( - request: protos.google.naming.v1beta1.IPaginatedMethodRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.naming.v1beta1.IPaginatedMethodRequest, - protos.google.naming.v1beta1.IPaginatedMethodResponse|null|undefined, - protos.google.protobuf.IEmpty>): void; + request: protos.google.naming.v1beta1.IPaginatedMethodRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.naming.v1beta1.IPaginatedMethodRequest, + protos.google.naming.v1beta1.IPaginatedMethodResponse | null | undefined, + protos.google.protobuf.IEmpty + >, + ): void; paginatedMethod( - request: protos.google.naming.v1beta1.IPaginatedMethodRequest, - callback: PaginationCallback< - protos.google.naming.v1beta1.IPaginatedMethodRequest, - protos.google.naming.v1beta1.IPaginatedMethodResponse|null|undefined, - protos.google.protobuf.IEmpty>): void; + request: protos.google.naming.v1beta1.IPaginatedMethodRequest, + callback: PaginationCallback< + protos.google.naming.v1beta1.IPaginatedMethodRequest, + protos.google.naming.v1beta1.IPaginatedMethodResponse | null | undefined, + protos.google.protobuf.IEmpty + >, + ): void; paginatedMethod( - request?: protos.google.naming.v1beta1.IPaginatedMethodRequest, - optionsOrCallback?: CallOptions|PaginationCallback< - protos.google.naming.v1beta1.IPaginatedMethodRequest, - protos.google.naming.v1beta1.IPaginatedMethodResponse|null|undefined, - protos.google.protobuf.IEmpty>, - callback?: PaginationCallback< + request?: protos.google.naming.v1beta1.IPaginatedMethodRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.naming.v1beta1.IPaginatedMethodRequest, - protos.google.naming.v1beta1.IPaginatedMethodResponse|null|undefined, - protos.google.protobuf.IEmpty>): - Promise<[ - protos.google.protobuf.IEmpty[], - protos.google.naming.v1beta1.IPaginatedMethodRequest|null, - protos.google.naming.v1beta1.IPaginatedMethodResponse - ]>|void { + | protos.google.naming.v1beta1.IPaginatedMethodResponse + | null + | undefined, + protos.google.protobuf.IEmpty + >, + callback?: PaginationCallback< + protos.google.naming.v1beta1.IPaginatedMethodRequest, + protos.google.naming.v1beta1.IPaginatedMethodResponse | null | undefined, + protos.google.protobuf.IEmpty + >, + ): Promise< + [ + protos.google.protobuf.IEmpty[], + protos.google.naming.v1beta1.IPaginatedMethodRequest | null, + protos.google.naming.v1beta1.IPaginatedMethodResponse, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize1().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.naming.v1beta1.IPaginatedMethodRequest, - protos.google.naming.v1beta1.IPaginatedMethodResponse|null|undefined, - protos.google.protobuf.IEmpty>|undefined = callback + this.initialize1().catch((err) => { + throw err; + }); + const wrappedCallback: + | PaginationCallback< + protos.google.naming.v1beta1.IPaginatedMethodRequest, + | protos.google.naming.v1beta1.IPaginatedMethodResponse + | null + | undefined, + protos.google.protobuf.IEmpty + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('paginatedMethod values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -1492,90 +1972,96 @@ export class NamingClient { this._log.info('paginatedMethod request %j', request); return this.innerApiCalls .paginatedMethod(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.protobuf.IEmpty[], - protos.google.naming.v1beta1.IPaginatedMethodRequest|null, - protos.google.naming.v1beta1.IPaginatedMethodResponse - ]) => { - this._log.info('paginatedMethod values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.protobuf.IEmpty[], + protos.google.naming.v1beta1.IPaginatedMethodRequest | null, + protos.google.naming.v1beta1.IPaginatedMethodResponse, + ]) => { + this._log.info('paginatedMethod values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `paginatedMethod`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {google.protobuf.Empty} request.content - * @param {number} request.pageSize - * @param {string} request.pageToken - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.protobuf.Empty|Empty} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `paginatedMethodAsync1()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `paginatedMethod`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {google.protobuf.Empty} request.content + * @param {number} request.pageSize + * @param {string} request.pageToken + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.protobuf.Empty|Empty} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `paginatedMethodAsync1()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ paginatedMethodStream1( - request?: protos.google.naming.v1beta1.IPaginatedMethodRequest, - options?: CallOptions): - Transform{ + request?: protos.google.naming.v1beta1.IPaginatedMethodRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; const defaultCallSettings = this._defaults['paginatedMethod']; const callSettings = defaultCallSettings.merge(options); - this.initialize1().catch(err => {throw err}); + this.initialize1().catch((err) => { + throw err; + }); this._log.info('paginatedMethod stream %j', request); return this.descriptors.page.paginatedMethod.createStream( this.innerApiCalls.paginatedMethod as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `paginatedMethod`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {google.protobuf.Empty} request.content - * @param {number} request.pageSize - * @param {string} request.pageToken - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.protobuf.Empty|Empty}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/naming.paginated_method.js - * region_tag:localhost_v1beta1_generated_Naming_PaginatedMethod_async - */ + /** + * Equivalent to `paginatedMethod`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {google.protobuf.Empty} request.content + * @param {number} request.pageSize + * @param {string} request.pageToken + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.protobuf.Empty|Empty}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/naming.paginated_method.js + * region_tag:localhost_v1beta1_generated_Naming_PaginatedMethod_async + */ paginatedMethodAsync1( - request?: protos.google.naming.v1beta1.IPaginatedMethodRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.naming.v1beta1.IPaginatedMethodRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; const defaultCallSettings = this._defaults['paginatedMethod']; const callSettings = defaultCallSettings.merge(options); - this.initialize1().catch(err => {throw err}); + this.initialize1().catch((err) => { + throw err; + }); this._log.info('paginatedMethod iterate %j', request); return this.descriptors.page.paginatedMethod.asyncIterate( this.innerApiCalls['paginatedMethod'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } // -------------------- @@ -1589,7 +2075,7 @@ export class NamingClient { * @param {string} exportParam * @returns {string} Resource name string. */ - projectExportPath(project:string,exportParam:string) { + projectExportPath(project: string, exportParam: string) { return this.pathTemplates.projectExportPathTemplate.render({ project: project, export: exportParam, @@ -1604,7 +2090,8 @@ export class NamingClient { * @returns {string} A string representing the project. */ matchProjectFromProjectExportName(projectExportName: string) { - return this.pathTemplates.projectExportPathTemplate.match(projectExportName).project; + return this.pathTemplates.projectExportPathTemplate.match(projectExportName) + .project; } /** @@ -1615,7 +2102,8 @@ export class NamingClient { * @returns {string} A string representing the export. */ matchExportFromProjectExportName(projectExportName: string) { - return this.pathTemplates.projectExportPathTemplate.match(projectExportName).export; + return this.pathTemplates.projectExportPathTemplate.match(projectExportName) + .export; } /** @@ -1625,7 +2113,7 @@ export class NamingClient { * @param {string} packageParam * @returns {string} Resource name string. */ - projectPackagePath(project:string,packageParam:string) { + projectPackagePath(project: string, packageParam: string) { return this.pathTemplates.projectPackagePathTemplate.render({ project: project, package: packageParam, @@ -1640,7 +2128,9 @@ export class NamingClient { * @returns {string} A string representing the project. */ matchProjectFromProjectPackageName(projectPackageName: string) { - return this.pathTemplates.projectPackagePathTemplate.match(projectPackageName).project; + return this.pathTemplates.projectPackagePathTemplate.match( + projectPackageName, + ).project; } /** @@ -1651,7 +2141,9 @@ export class NamingClient { * @returns {string} A string representing the package. */ matchPackageFromProjectPackageName(projectPackageName: string) { - return this.pathTemplates.projectPackagePathTemplate.match(projectPackageName).package; + return this.pathTemplates.projectPackagePathTemplate.match( + projectPackageName, + ).package; } /** @@ -1662,7 +2154,7 @@ export class NamingClient { */ close(): Promise { if (this.namingStub && !this._terminated) { - return this.namingStub.then(stub => { + return this.namingStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -1671,4 +2163,4 @@ export class NamingClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/core/generator/gapic-generator-typescript/baselines/naming/system-test/fixtures/sample/src/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/naming/system-test/fixtures/sample/src/index.ts.baseline index c8cd80a20a9a..856743e6efec 100644 --- a/core/generator/gapic-generator-typescript/baselines/naming/system-test/fixtures/sample/src/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/naming/system-test/fixtures/sample/src/index.ts.baseline @@ -16,7 +16,7 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -import {NamingClient} from 'naming'; +import { NamingClient } from 'naming'; // check that the client class type name can be used function doStuffWithNamingClient(client: NamingClient) { diff --git a/core/generator/gapic-generator-typescript/baselines/naming/system-test/install.ts.baseline b/core/generator/gapic-generator-typescript/baselines/naming/system-test/install.ts.baseline index f66069aa3940..ccf167042d2e 100644 --- a/core/generator/gapic-generator-typescript/baselines/naming/system-test/install.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/naming/system-test/install.ts.baseline @@ -16,34 +16,36 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -import {packNTest} from 'pack-n-play'; -import {readFileSync} from 'fs'; -import {describe, it} from 'mocha'; +import { packNTest } from 'pack-n-play'; +import { readFileSync } from 'fs'; +import { describe, it } from 'mocha'; describe('📦 pack-n-play test', () => { - - it('TypeScript code', async function() { + it('TypeScript code', async function () { this.timeout(300000); const options = { packageDir: process.cwd(), sample: { description: 'TypeScript user can use the type definitions', - ts: readFileSync('./system-test/fixtures/sample/src/index.ts').toString() - } + ts: readFileSync( + './system-test/fixtures/sample/src/index.ts', + ).toString(), + }, }; await packNTest(options); }); - it('JavaScript code', async function() { + it('JavaScript code', async function () { this.timeout(300000); const options = { packageDir: process.cwd(), sample: { description: 'JavaScript user can use the library', - cjs: readFileSync('./system-test/fixtures/sample/src/index.js').toString() - } + cjs: readFileSync( + './system-test/fixtures/sample/src/index.js', + ).toString(), + }, }; await packNTest(options); }); - }); diff --git a/core/generator/gapic-generator-typescript/baselines/naming/test/gapic_naming_v1beta1.ts.baseline b/core/generator/gapic-generator-typescript/baselines/naming/test/gapic_naming_v1beta1.ts.baseline index 47d84bea6500..b0a09e354cb7 100644 --- a/core/generator/gapic-generator-typescript/baselines/naming/test/gapic_naming_v1beta1.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/naming/test/gapic_naming_v1beta1.ts.baseline @@ -19,1411 +19,1580 @@ import * as protos from '../protos/protos'; import * as assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as namingModule from '../src'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; -import {protobuf, LROperation, operationsProtos} from 'google-gax'; +import { protobuf, LROperation, operationsProtos } from 'google-gax'; // Dynamically loaded proto JSON is needed to get the type information // to fill in default values for request objects -const root = protobuf.Root.fromJSON(require('../protos/protos.json')).resolveAll(); +const root = protobuf.Root.fromJSON( + require('../protos/protos.json'), +).resolveAll(); // eslint-disable-next-line @typescript-eslint/no-unused-vars function getTypeDefaultValue(typeName: string, fields: string[]) { - let type = root.lookupType(typeName) as protobuf.Type; - for (const field of fields.slice(0, -1)) { - type = type.fields[field]?.resolvedType as protobuf.Type; - } - return type.fields[fields[fields.length - 1]]?.defaultValue; + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type.fields[field]?.resolvedType as protobuf.Type; + } + return type.fields[fields[fields.length - 1]]?.defaultValue; } function generateSampleMessage(instance: T) { - const filledObject = (instance.constructor as typeof protobuf.Message) - .toObject(instance as protobuf.Message, {defaults: true}); - return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, { defaults: true }); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; } function stubSimpleCall(response?: ResponseType, error?: Error) { - return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); } -function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { - return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +function stubSimpleCallWithCallback( + response?: ResponseType, + error?: Error, +) { + return error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); } -function stubLongRunningCall(response?: ResponseType, callError?: Error, lroError?: Error) { - const innerStub = lroError ? sinon.stub().rejects(lroError) : sinon.stub().resolves([response]); - const mockOperation = { - promise: innerStub, - }; - return callError ? sinon.stub().rejects(callError) : sinon.stub().resolves([mockOperation]); +function stubLongRunningCall( + response?: ResponseType, + callError?: Error, + lroError?: Error, +) { + const innerStub = lroError + ? sinon.stub().rejects(lroError) + : sinon.stub().resolves([response]); + const mockOperation = { + promise: innerStub, + }; + return callError + ? sinon.stub().rejects(callError) + : sinon.stub().resolves([mockOperation]); } -function stubLongRunningCallWithCallback(response?: ResponseType, callError?: Error, lroError?: Error) { - const innerStub = lroError ? sinon.stub().rejects(lroError) : sinon.stub().resolves([response]); - const mockOperation = { - promise: innerStub, - }; - return callError ? sinon.stub().callsArgWith(2, callError) : sinon.stub().callsArgWith(2, null, mockOperation); +function stubLongRunningCallWithCallback( + response?: ResponseType, + callError?: Error, + lroError?: Error, +) { + const innerStub = lroError + ? sinon.stub().rejects(lroError) + : sinon.stub().resolves([response]); + const mockOperation = { + promise: innerStub, + }; + return callError + ? sinon.stub().callsArgWith(2, callError) + : sinon.stub().callsArgWith(2, null, mockOperation); } -function stubPageStreamingCall(responses?: ResponseType[], error?: Error) { - const pagingStub = sinon.stub(); - if (responses) { - for (let i = 0; i < responses.length; ++i) { - pagingStub.onCall(i).callsArgWith(2, null, responses[i]); - } +function stubPageStreamingCall( + responses?: ResponseType[], + error?: Error, +) { + const pagingStub = sinon.stub(); + if (responses) { + for (let i = 0; i < responses.length; ++i) { + pagingStub.onCall(i).callsArgWith(2, null, responses[i]); } - const transformStub = error ? sinon.stub().callsArgWith(2, error) : pagingStub; - const mockStream = new PassThrough({ - objectMode: true, - transform: transformStub, - }); - // trigger as many responses as needed - if (responses) { - for (let i = 0; i < responses.length; ++i) { - setImmediate(() => { mockStream.write({}); }); - } - setImmediate(() => { mockStream.end(); }); - } else { - setImmediate(() => { mockStream.write({}); }); - setImmediate(() => { mockStream.end(); }); + } + const transformStub = error + ? sinon.stub().callsArgWith(2, error) + : pagingStub; + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + // trigger as many responses as needed + if (responses) { + for (let i = 0; i < responses.length; ++i) { + setImmediate(() => { + mockStream.write({}); + }); } - return sinon.stub().returns(mockStream); + setImmediate(() => { + mockStream.end(); + }); + } else { + setImmediate(() => { + mockStream.write({}); + }); + setImmediate(() => { + mockStream.end(); + }); + } + return sinon.stub().returns(mockStream); } -function stubAsyncIterationCall(responses?: ResponseType[], error?: Error) { - let counter = 0; - const asyncIterable = { - [Symbol.asyncIterator]() { - return { - async next() { - if (error) { - return Promise.reject(error); - } - if (counter >= responses!.length) { - return Promise.resolve({done: true, value: undefined}); - } - return Promise.resolve({done: false, value: responses![counter++]}); - } - }; - } - }; - return sinon.stub().returns(asyncIterable); +function stubAsyncIterationCall( + responses?: ResponseType[], + error?: Error, +) { + let counter = 0; + const asyncIterable = { + [Symbol.asyncIterator]() { + return { + async next() { + if (error) { + return Promise.reject(error); + } + if (counter >= responses!.length) { + return Promise.resolve({ done: true, value: undefined }); + } + return Promise.resolve({ done: false, value: responses![counter++] }); + }, + }; + }, + }; + return sinon.stub().returns(asyncIterable); } describe('v1beta1.NamingClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new namingModule.v1beta1.NamingClient(); - const apiEndpoint = client.apiEndpoint1; - assert.strictEqual(apiEndpoint, 'localhost'); - }); - - it('has universeDomain', () => { - const client = new namingModule.v1beta1.NamingClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); - - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - it('throws DeprecationWarning if static servicePath1 is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const servicePath = namingModule.v1beta1.NamingClient.servicePath1; - assert.strictEqual(servicePath, 'localhost'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint1 is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = namingModule.v1beta1.NamingClient.apiEndpoint1; - assert.strictEqual(apiEndpoint, 'localhost'); - assert(stub.called); - stub.restore(); - }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { new namingModule.v1beta1.NamingClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); - - it('has port', () => { - const port = namingModule.v1beta1.NamingClient.port1; - assert(port); - assert(typeof port === 'number'); - }); - - it('should create a client with no option', () => { - const client = new namingModule.v1beta1.NamingClient(); - assert(client); - }); - - it('should create a client with gRPC fallback', () => { - const client = new namingModule.v1beta1.NamingClient({ - fallback: true, - }); - assert(client); - }); - - it('has initialize method and supports deferred initialization', async () => { - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.namingStub, undefined); - await client.initialize1(); - assert(client.namingStub); - }); - - it('has close method for the initialized client', done => { - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize1().catch(err => {throw err}); - assert(client.namingStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); - - it('has close method for the non-initialized client', done => { - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.namingStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); - - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId1(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); - }); - - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId1((err?: Error|null, projectId?: string|null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } - }); - }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new namingModule.v1beta1.NamingClient(); + const apiEndpoint = client.apiEndpoint1; + assert.strictEqual(apiEndpoint, 'localhost'); }); - describe('paginatedMethodStream', () => { - it('invokes paginatedMethodStream without error', async () => { - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize1(); - const request = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.paginatedMethodStream = stubSimpleCall(expectedResponse); - const [response] = await client.paginatedMethodStream(request); - assert.deepStrictEqual(response, expectedResponse); - }); - - it('invokes paginatedMethodStream without error using callback', async () => { - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize1(); - const request = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.paginatedMethodStream = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.paginatedMethodStream( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); - - it('invokes paginatedMethodStream with error', async () => { - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize1(); - const request = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.paginatedMethodStream = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.paginatedMethodStream(request), expectedError); - }); - - it('invokes paginatedMethodStream with closed client', async () => { - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize1(); - const request = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.paginatedMethodStream(request), expectedError); - }); + it('has universeDomain', () => { + const client = new namingModule.v1beta1.NamingClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); }); - describe('paginatedMethodAsync', () => { - it('invokes paginatedMethodAsync without error', async () => { - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize1(); - const request = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.paginatedMethodAsync = stubSimpleCall(expectedResponse); - const [response] = await client.paginatedMethodAsync(request); - assert.deepStrictEqual(response, expectedResponse); - }); - - it('invokes paginatedMethodAsync without error using callback', async () => { - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize1(); - const request = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.paginatedMethodAsync = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.paginatedMethodAsync( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath1 is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = namingModule.v1beta1.NamingClient.servicePath1; + assert.strictEqual(servicePath, 'localhost'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint1 is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = namingModule.v1beta1.NamingClient.apiEndpoint1; + assert.strictEqual(apiEndpoint, 'localhost'); + assert(stub.called); + stub.restore(); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new namingModule.v1beta1.NamingClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); + }); - it('invokes paginatedMethodAsync with error', async () => { - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize1(); - const request = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.paginatedMethodAsync = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.paginatedMethodAsync(request), expectedError); - }); + it('has port', () => { + const port = namingModule.v1beta1.NamingClient.port1; + assert(port); + assert(typeof port === 'number'); + }); - it('invokes paginatedMethodAsync with closed client', async () => { - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize1(); - const request = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.paginatedMethodAsync(request), expectedError); - }); + it('should create a client with no option', () => { + const client = new namingModule.v1beta1.NamingClient(); + assert(client); }); - describe('checkLongRunningProgress', () => { - it('invokes checkLongRunningProgress without error', async () => { - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize1(); - const request = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.checkLongRunningProgress = stubSimpleCall(expectedResponse); - const [response] = await client.checkLongRunningProgress(request); - assert.deepStrictEqual(response, expectedResponse); - }); + it('should create a client with gRPC fallback', () => { + const client = new namingModule.v1beta1.NamingClient({ + fallback: true, + }); + assert(client); + }); - it('invokes checkLongRunningProgress without error using callback', async () => { - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize1(); - const request = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.checkLongRunningProgress = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.checkLongRunningProgress( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); + it('has initialize method and supports deferred initialization', async () => { + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.namingStub, undefined); + await client.initialize1(); + assert(client.namingStub); + }); - it('invokes checkLongRunningProgress with error', async () => { - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize1(); - const request = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.checkLongRunningProgress = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.checkLongRunningProgress(request), expectedError); + it('has close method for the initialized client', (done) => { + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize1().catch((err) => { + throw err; + }); + assert(client.namingStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes checkLongRunningProgress with closed client', async () => { - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize1(); - const request = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.checkLongRunningProgress(request), expectedError); + it('has close method for the non-initialized client', (done) => { + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.namingStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); }); - describe('initialize', () => { - it('invokes initialize without error', async () => { - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize1(); - const request = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.initialize = stubSimpleCall(expectedResponse); - const [response] = await client.initialize(request); - assert.deepStrictEqual(response, expectedResponse); - }); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId1(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + }); - it('invokes initialize without error using callback', async () => { - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize1(); - const request = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.initialize = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.initialize( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId1( + (err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } + }, + ); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + }); + + describe('paginatedMethodStream', () => { + it('invokes paginatedMethodStream without error', async () => { + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize1(); + const request = generateSampleMessage(new protos.google.protobuf.Empty()); + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.paginatedMethodStream = + stubSimpleCall(expectedResponse); + const [response] = await client.paginatedMethodStream(request); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes initialize with error', async () => { - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize1(); - const request = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.initialize = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.initialize(request), expectedError); - }); + it('invokes paginatedMethodStream without error using callback', async () => { + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize1(); + const request = generateSampleMessage(new protos.google.protobuf.Empty()); + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.paginatedMethodStream = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.paginatedMethodStream( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes initialize with closed client', async () => { - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize1(); - const request = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.initialize(request), expectedError); - }); + it('invokes paginatedMethodStream with error', async () => { + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize1(); + const request = generateSampleMessage(new protos.google.protobuf.Empty()); + const expectedError = new Error('expected'); + client.innerApiCalls.paginatedMethodStream = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.paginatedMethodStream(request), + expectedError, + ); }); - describe('servicePath', () => { - it('invokes servicePath without error', async () => { - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize1(); - const request = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.servicePath = stubSimpleCall(expectedResponse); - const [response] = await client.servicePath(request); - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes paginatedMethodStream with closed client', async () => { + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize1(); + const request = generateSampleMessage(new protos.google.protobuf.Empty()); + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.paginatedMethodStream(request), + expectedError, + ); + }); + }); + + describe('paginatedMethodAsync', () => { + it('invokes paginatedMethodAsync without error', async () => { + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize1(); + const request = generateSampleMessage(new protos.google.protobuf.Empty()); + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.paginatedMethodAsync = + stubSimpleCall(expectedResponse); + const [response] = await client.paginatedMethodAsync(request); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes servicePath without error using callback', async () => { - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize1(); - const request = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.servicePath = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.servicePath( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes paginatedMethodAsync without error using callback', async () => { + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize1(); + const request = generateSampleMessage(new protos.google.protobuf.Empty()); + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.paginatedMethodAsync = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.paginatedMethodAsync( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes servicePath with error', async () => { - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize1(); - const request = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.servicePath = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.servicePath(request), expectedError); - }); + it('invokes paginatedMethodAsync with error', async () => { + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize1(); + const request = generateSampleMessage(new protos.google.protobuf.Empty()); + const expectedError = new Error('expected'); + client.innerApiCalls.paginatedMethodAsync = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.paginatedMethodAsync(request), expectedError); + }); - it('invokes servicePath with closed client', async () => { - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize1(); - const request = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.servicePath(request), expectedError); - }); + it('invokes paginatedMethodAsync with closed client', async () => { + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize1(); + const request = generateSampleMessage(new protos.google.protobuf.Empty()); + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.paginatedMethodAsync(request), expectedError); + }); + }); + + describe('checkLongRunningProgress', () => { + it('invokes checkLongRunningProgress without error', async () => { + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize1(); + const request = generateSampleMessage(new protos.google.protobuf.Empty()); + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.checkLongRunningProgress = + stubSimpleCall(expectedResponse); + const [response] = await client.checkLongRunningProgress(request); + assert.deepStrictEqual(response, expectedResponse); }); - describe('apiEndpoint', () => { - it('invokes apiEndpoint without error', async () => { - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize1(); - const request = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.apiEndpoint = stubSimpleCall(expectedResponse); - const [response] = await client.apiEndpoint(request); - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes checkLongRunningProgress without error using callback', async () => { + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize1(); + const request = generateSampleMessage(new protos.google.protobuf.Empty()); + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.checkLongRunningProgress = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.checkLongRunningProgress( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes apiEndpoint without error using callback', async () => { - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize1(); - const request = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.apiEndpoint = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.apiEndpoint( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes checkLongRunningProgress with error', async () => { + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize1(); + const request = generateSampleMessage(new protos.google.protobuf.Empty()); + const expectedError = new Error('expected'); + client.innerApiCalls.checkLongRunningProgress = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.checkLongRunningProgress(request), + expectedError, + ); + }); - it('invokes apiEndpoint with error', async () => { - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize1(); - const request = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.apiEndpoint = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.apiEndpoint(request), expectedError); - }); + it('invokes checkLongRunningProgress with closed client', async () => { + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize1(); + const request = generateSampleMessage(new protos.google.protobuf.Empty()); + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.checkLongRunningProgress(request), + expectedError, + ); + }); + }); + + describe('initialize', () => { + it('invokes initialize without error', async () => { + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize1(); + const request = generateSampleMessage(new protos.google.protobuf.Empty()); + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.initialize = stubSimpleCall(expectedResponse); + const [response] = await client.initialize(request); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes apiEndpoint with closed client', async () => { - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize1(); - const request = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.apiEndpoint(request), expectedError); - }); + it('invokes initialize without error using callback', async () => { + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize1(); + const request = generateSampleMessage(new protos.google.protobuf.Empty()); + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.initialize = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.initialize( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); }); - describe('port', () => { - it('invokes port without error', async () => { - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize1(); - const request = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.port = stubSimpleCall(expectedResponse); - const [response] = await client.port(request); - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes initialize with error', async () => { + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize1(); + const request = generateSampleMessage(new protos.google.protobuf.Empty()); + const expectedError = new Error('expected'); + client.innerApiCalls.initialize = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.initialize(request), expectedError); + }); - it('invokes port without error using callback', async () => { - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize1(); - const request = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.port = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.port( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes initialize with closed client', async () => { + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize1(); + const request = generateSampleMessage(new protos.google.protobuf.Empty()); + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.initialize(request), expectedError); + }); + }); + + describe('servicePath', () => { + it('invokes servicePath without error', async () => { + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize1(); + const request = generateSampleMessage(new protos.google.protobuf.Empty()); + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.servicePath = stubSimpleCall(expectedResponse); + const [response] = await client.servicePath(request); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes port with error', async () => { - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize1(); - const request = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.port = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.port(request), expectedError); - }); + it('invokes servicePath without error using callback', async () => { + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize1(); + const request = generateSampleMessage(new protos.google.protobuf.Empty()); + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.servicePath = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.servicePath( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes port with closed client', async () => { - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize1(); - const request = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.port(request), expectedError); - }); + it('invokes servicePath with error', async () => { + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize1(); + const request = generateSampleMessage(new protos.google.protobuf.Empty()); + const expectedError = new Error('expected'); + client.innerApiCalls.servicePath = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.servicePath(request), expectedError); }); - describe('scopes', () => { - it('invokes scopes without error', async () => { - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize1(); - const request = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.scopes = stubSimpleCall(expectedResponse); - const [response] = await client.scopes(request); - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes servicePath with closed client', async () => { + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize1(); + const request = generateSampleMessage(new protos.google.protobuf.Empty()); + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.servicePath(request), expectedError); + }); + }); + + describe('apiEndpoint', () => { + it('invokes apiEndpoint without error', async () => { + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize1(); + const request = generateSampleMessage(new protos.google.protobuf.Empty()); + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.apiEndpoint = stubSimpleCall(expectedResponse); + const [response] = await client.apiEndpoint(request); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes scopes without error using callback', async () => { - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize1(); - const request = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.scopes = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.scopes( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes apiEndpoint without error using callback', async () => { + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize1(); + const request = generateSampleMessage(new protos.google.protobuf.Empty()); + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.apiEndpoint = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.apiEndpoint( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes scopes with error', async () => { - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize1(); - const request = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.scopes = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.scopes(request), expectedError); - }); + it('invokes apiEndpoint with error', async () => { + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize1(); + const request = generateSampleMessage(new protos.google.protobuf.Empty()); + const expectedError = new Error('expected'); + client.innerApiCalls.apiEndpoint = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.apiEndpoint(request), expectedError); + }); - it('invokes scopes with closed client', async () => { - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize1(); - const request = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.scopes(request), expectedError); - }); + it('invokes apiEndpoint with closed client', async () => { + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize1(); + const request = generateSampleMessage(new protos.google.protobuf.Empty()); + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.apiEndpoint(request), expectedError); + }); + }); + + describe('port', () => { + it('invokes port without error', async () => { + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize1(); + const request = generateSampleMessage(new protos.google.protobuf.Empty()); + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.port = stubSimpleCall(expectedResponse); + const [response] = await client.port(request); + assert.deepStrictEqual(response, expectedResponse); }); - describe('getProjectId', () => { - it('invokes getProjectId without error', async () => { - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize1(); - const request = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.getProjectId = stubSimpleCall(expectedResponse); - const [response] = await client.getProjectId(request); - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes port without error using callback', async () => { + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize1(); + const request = generateSampleMessage(new protos.google.protobuf.Empty()); + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.port = stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.port( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes getProjectId without error using callback', async () => { - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize1(); - const request = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.getProjectId = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getProjectId( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes port with error', async () => { + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize1(); + const request = generateSampleMessage(new protos.google.protobuf.Empty()); + const expectedError = new Error('expected'); + client.innerApiCalls.port = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.port(request), expectedError); + }); - it('invokes getProjectId with error', async () => { - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize1(); - const request = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.getProjectId = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getProjectId(request), expectedError); - }); + it('invokes port with closed client', async () => { + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize1(); + const request = generateSampleMessage(new protos.google.protobuf.Empty()); + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.port(request), expectedError); + }); + }); + + describe('scopes', () => { + it('invokes scopes without error', async () => { + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize1(); + const request = generateSampleMessage(new protos.google.protobuf.Empty()); + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.scopes = stubSimpleCall(expectedResponse); + const [response] = await client.scopes(request); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes getProjectId with closed client', async () => { - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize1(); - const request = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getProjectId(request), expectedError); - }); + it('invokes scopes without error using callback', async () => { + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize1(); + const request = generateSampleMessage(new protos.google.protobuf.Empty()); + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.scopes = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.scopes( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); }); - describe('getReservedWord', () => { - it('invokes getReservedWord without error', async () => { - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize1(); - const request = generateSampleMessage( - new protos.google.naming.v1beta1.GetReservedWordRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.naming.v1beta1.ReservedWord() - ); - client.innerApiCalls.getReservedWord = stubSimpleCall(expectedResponse); - const [response] = await client.getReservedWord(request); - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes scopes with error', async () => { + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize1(); + const request = generateSampleMessage(new protos.google.protobuf.Empty()); + const expectedError = new Error('expected'); + client.innerApiCalls.scopes = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.scopes(request), expectedError); + }); - it('invokes getReservedWord without error using callback', async () => { - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize1(); - const request = generateSampleMessage( - new protos.google.naming.v1beta1.GetReservedWordRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.naming.v1beta1.ReservedWord() - ); - client.innerApiCalls.getReservedWord = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getReservedWord( - request, - (err?: Error|null, result?: protos.google.naming.v1beta1.IReservedWord|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes scopes with closed client', async () => { + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize1(); + const request = generateSampleMessage(new protos.google.protobuf.Empty()); + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.scopes(request), expectedError); + }); + }); + + describe('getProjectId', () => { + it('invokes getProjectId without error', async () => { + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize1(); + const request = generateSampleMessage(new protos.google.protobuf.Empty()); + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.getProjectId = stubSimpleCall(expectedResponse); + const [response] = await client.getProjectId(request); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes getReservedWord with error', async () => { - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize1(); - const request = generateSampleMessage( - new protos.google.naming.v1beta1.GetReservedWordRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.getReservedWord = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getReservedWord(request), expectedError); - }); + it('invokes getProjectId without error using callback', async () => { + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize1(); + const request = generateSampleMessage(new protos.google.protobuf.Empty()); + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.getProjectId = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getProjectId( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes getReservedWord with closed client', async () => { - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize1(); - const request = generateSampleMessage( - new protos.google.naming.v1beta1.GetReservedWordRequest() - ); - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getReservedWord(request), expectedError); - }); + it('invokes getProjectId with error', async () => { + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize1(); + const request = generateSampleMessage(new protos.google.protobuf.Empty()); + const expectedError = new Error('expected'); + client.innerApiCalls.getProjectId = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getProjectId(request), expectedError); }); - describe('createABCDESomething', () => { - it('invokes createABCDESomething without error', async () => { - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize1(); - const request = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.createAbcdeSomething = stubSimpleCall(expectedResponse); - const [response] = await client.createABCDESomething(request); - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes getProjectId with closed client', async () => { + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize1(); + const request = generateSampleMessage(new protos.google.protobuf.Empty()); + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getProjectId(request), expectedError); + }); + }); + + describe('getReservedWord', () => { + it('invokes getReservedWord without error', async () => { + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize1(); + const request = generateSampleMessage( + new protos.google.naming.v1beta1.GetReservedWordRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.naming.v1beta1.ReservedWord(), + ); + client.innerApiCalls.getReservedWord = stubSimpleCall(expectedResponse); + const [response] = await client.getReservedWord(request); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes createABCDESomething without error using callback', async () => { - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize1(); - const request = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.createAbcdeSomething = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createABCDESomething( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes getReservedWord without error using callback', async () => { + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize1(); + const request = generateSampleMessage( + new protos.google.naming.v1beta1.GetReservedWordRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.naming.v1beta1.ReservedWord(), + ); + client.innerApiCalls.getReservedWord = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getReservedWord( + request, + ( + err?: Error | null, + result?: protos.google.naming.v1beta1.IReservedWord | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes createABCDESomething with error', async () => { - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize1(); - const request = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.createAbcdeSomething = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createABCDESomething(request), expectedError); - }); + it('invokes getReservedWord with error', async () => { + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize1(); + const request = generateSampleMessage( + new protos.google.naming.v1beta1.GetReservedWordRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.getReservedWord = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getReservedWord(request), expectedError); + }); - it('invokes createABCDESomething with closed client', async () => { - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize1(); - const request = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createABCDESomething(request), expectedError); - }); + it('invokes getReservedWord with closed client', async () => { + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize1(); + const request = generateSampleMessage( + new protos.google.naming.v1beta1.GetReservedWordRequest(), + ); + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getReservedWord(request), expectedError); + }); + }); + + describe('createABCDESomething', () => { + it('invokes createABCDESomething without error', async () => { + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize1(); + const request = generateSampleMessage(new protos.google.protobuf.Empty()); + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.createAbcdeSomething = + stubSimpleCall(expectedResponse); + const [response] = await client.createABCDESomething(request); + assert.deepStrictEqual(response, expectedResponse); }); - describe('longRunning', () => { - it('invokes longRunning without error', async () => { - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize1(); - const request = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.longRunning = stubLongRunningCall(expectedResponse); - const [operation] = await client.longRunning(request); - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes createABCDESomething without error using callback', async () => { + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize1(); + const request = generateSampleMessage(new protos.google.protobuf.Empty()); + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.createAbcdeSomething = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createABCDESomething( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes longRunning without error using callback', async () => { - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize1(); - const request = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.longRunning = stubLongRunningCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.longRunning( - request, - (err?: Error|null, - result?: LROperation|null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const operation = await promise as LROperation; - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes createABCDESomething with error', async () => { + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize1(); + const request = generateSampleMessage(new protos.google.protobuf.Empty()); + const expectedError = new Error('expected'); + client.innerApiCalls.createAbcdeSomething = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.createABCDESomething(request), expectedError); + }); - it('invokes longRunning with call error', async () => { - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize1(); - const request = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.longRunning = stubLongRunningCall(undefined, expectedError); - await assert.rejects(client.longRunning(request), expectedError); - }); + it('invokes createABCDESomething with closed client', async () => { + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize1(); + const request = generateSampleMessage(new protos.google.protobuf.Empty()); + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.createABCDESomething(request), expectedError); + }); + }); + + describe('longRunning', () => { + it('invokes longRunning without error', async () => { + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize1(); + const request = generateSampleMessage(new protos.google.protobuf.Empty()); + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.longRunning = stubLongRunningCall(expectedResponse); + const [operation] = await client.longRunning(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes longRunning with LRO error', async () => { - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize1(); - const request = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.longRunning = stubLongRunningCall(undefined, undefined, expectedError); - const [operation] = await client.longRunning(request); - await assert.rejects(operation.promise(), expectedError); - }); + it('invokes longRunning without error using callback', async () => { + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize1(); + const request = generateSampleMessage(new protos.google.protobuf.Empty()); + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.longRunning = + stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.longRunning( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty + > | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const operation = (await promise) as LROperation< + protos.google.protobuf.IEmpty, + protos.google.protobuf.IEmpty + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes checkLongRunningProgress1 without error', async () => { - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize1(); - const expectedResponse = generateSampleMessage( - new operationsProtos.google.longrunning.Operation() - ); - expectedResponse.name = 'test'; - expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; - expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')} - - client.operationsClient.getOperation = stubSimpleCall(expectedResponse); - const decodedOperation = await client.checkLongRunningProgress1(expectedResponse.name); - assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); - assert(decodedOperation.metadata); - assert((client.operationsClient.getOperation as SinonStub).getCall(0)); - }); + it('invokes longRunning with call error', async () => { + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize1(); + const request = generateSampleMessage(new protos.google.protobuf.Empty()); + const expectedError = new Error('expected'); + client.innerApiCalls.longRunning = stubLongRunningCall( + undefined, + expectedError, + ); + await assert.rejects(client.longRunning(request), expectedError); + }); - it('invokes checkLongRunningProgress1 with error', async () => { - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize1(); - const expectedError = new Error('expected'); - - client.operationsClient.getOperation = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.checkLongRunningProgress1(''), expectedError); - assert((client.operationsClient.getOperation as SinonStub) - .getCall(0)); - }); + it('invokes longRunning with LRO error', async () => { + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize1(); + const request = generateSampleMessage(new protos.google.protobuf.Empty()); + const expectedError = new Error('expected'); + client.innerApiCalls.longRunning = stubLongRunningCall( + undefined, + undefined, + expectedError, + ); + const [operation] = await client.longRunning(request); + await assert.rejects(operation.promise(), expectedError); }); - describe('paginatedMethod', () => { - it('invokes paginatedMethod without error', async () => { - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize1(); - const request = generateSampleMessage( - new protos.google.naming.v1beta1.PaginatedMethodRequest() - );const expectedResponse = [ - generateSampleMessage(new protos.google.protobuf.Empty()), - generateSampleMessage(new protos.google.protobuf.Empty()), - generateSampleMessage(new protos.google.protobuf.Empty()), - ]; - client.innerApiCalls.paginatedMethod = stubSimpleCall(expectedResponse); - const [response] = await client.paginatedMethod(request); - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes checkLongRunningProgress1 without error', async () => { + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize1(); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation(), + ); + expectedResponse.name = 'test'; + expectedResponse.response = { type_url: 'url', value: Buffer.from('') }; + expectedResponse.metadata = { type_url: 'url', value: Buffer.from('') }; + + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const decodedOperation = await client.checkLongRunningProgress1( + expectedResponse.name, + ); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); - it('invokes paginatedMethod without error using callback', async () => { - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize1(); - const request = generateSampleMessage( - new protos.google.naming.v1beta1.PaginatedMethodRequest() - );const expectedResponse = [ - generateSampleMessage(new protos.google.protobuf.Empty()), - generateSampleMessage(new protos.google.protobuf.Empty()), - generateSampleMessage(new protos.google.protobuf.Empty()), - ]; - client.innerApiCalls.paginatedMethod = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.paginatedMethod( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes checkLongRunningProgress1 with error', async () => { + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize1(); + const expectedError = new Error('expected'); + + client.operationsClient.getOperation = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.checkLongRunningProgress1(''), expectedError); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + }); + + describe('paginatedMethod', () => { + it('invokes paginatedMethod without error', async () => { + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize1(); + const request = generateSampleMessage( + new protos.google.naming.v1beta1.PaginatedMethodRequest(), + ); + const expectedResponse = [ + generateSampleMessage(new protos.google.protobuf.Empty()), + generateSampleMessage(new protos.google.protobuf.Empty()), + generateSampleMessage(new protos.google.protobuf.Empty()), + ]; + client.innerApiCalls.paginatedMethod = stubSimpleCall(expectedResponse); + const [response] = await client.paginatedMethod(request); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes paginatedMethod with error', async () => { - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize1(); - const request = generateSampleMessage( - new protos.google.naming.v1beta1.PaginatedMethodRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.paginatedMethod = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.paginatedMethod(request), expectedError); - }); + it('invokes paginatedMethod without error using callback', async () => { + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize1(); + const request = generateSampleMessage( + new protos.google.naming.v1beta1.PaginatedMethodRequest(), + ); + const expectedResponse = [ + generateSampleMessage(new protos.google.protobuf.Empty()), + generateSampleMessage(new protos.google.protobuf.Empty()), + generateSampleMessage(new protos.google.protobuf.Empty()), + ]; + client.innerApiCalls.paginatedMethod = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.paginatedMethod( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes paginatedMethodStream1 without error', async () => { - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize1(); - const request = generateSampleMessage( - new protos.google.naming.v1beta1.PaginatedMethodRequest() - ); - const expectedResponse = [ - generateSampleMessage(new protos.google.protobuf.Empty()), - generateSampleMessage(new protos.google.protobuf.Empty()), - generateSampleMessage(new protos.google.protobuf.Empty()), - ]; - client.descriptors.page.paginatedMethod.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.paginatedMethodStream1(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.protobuf.Empty[] = []; - stream.on('data', (response: protos.google.protobuf.Empty) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.paginatedMethod.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.paginatedMethod, request)); - }); + it('invokes paginatedMethod with error', async () => { + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize1(); + const request = generateSampleMessage( + new protos.google.naming.v1beta1.PaginatedMethodRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.paginatedMethod = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.paginatedMethod(request), expectedError); + }); - it('invokes paginatedMethodStream1 with error', async () => { - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize1(); - const request = generateSampleMessage( - new protos.google.naming.v1beta1.PaginatedMethodRequest() - ); - const expectedError = new Error('expected'); - client.descriptors.page.paginatedMethod.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.paginatedMethodStream1(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.protobuf.Empty[] = []; - stream.on('data', (response: protos.google.protobuf.Empty) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.paginatedMethod.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.paginatedMethod, request)); - }); + it('invokes paginatedMethodStream1 without error', async () => { + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize1(); + const request = generateSampleMessage( + new protos.google.naming.v1beta1.PaginatedMethodRequest(), + ); + const expectedResponse = [ + generateSampleMessage(new protos.google.protobuf.Empty()), + generateSampleMessage(new protos.google.protobuf.Empty()), + generateSampleMessage(new protos.google.protobuf.Empty()), + ]; + client.descriptors.page.paginatedMethod.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.paginatedMethodStream1(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.protobuf.Empty[] = []; + stream.on('data', (response: protos.google.protobuf.Empty) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.paginatedMethod.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.paginatedMethod, request), + ); + }); - it('uses async iteration with paginatedMethod without error', async () => { - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize1(); - const request = generateSampleMessage( - new protos.google.naming.v1beta1.PaginatedMethodRequest() - ); - const expectedResponse = [ - generateSampleMessage(new protos.google.protobuf.Empty()), - generateSampleMessage(new protos.google.protobuf.Empty()), - generateSampleMessage(new protos.google.protobuf.Empty()), - ]; - client.descriptors.page.paginatedMethod.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.protobuf.IEmpty[] = []; - const iterable = client.paginatedMethodAsync1(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.paginatedMethod.asyncIterate as SinonStub) - .getCall(0).args[1], request); - }); + it('invokes paginatedMethodStream1 with error', async () => { + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize1(); + const request = generateSampleMessage( + new protos.google.naming.v1beta1.PaginatedMethodRequest(), + ); + const expectedError = new Error('expected'); + client.descriptors.page.paginatedMethod.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.paginatedMethodStream1(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.protobuf.Empty[] = []; + stream.on('data', (response: protos.google.protobuf.Empty) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.paginatedMethod.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.paginatedMethod, request), + ); + }); - it('uses async iteration with paginatedMethod with error', async () => { - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize1(); - const request = generateSampleMessage( - new protos.google.naming.v1beta1.PaginatedMethodRequest() - ); - const expectedError = new Error('expected'); - client.descriptors.page.paginatedMethod.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.paginatedMethodAsync1(request); - await assert.rejects(async () => { - const responses: protos.google.protobuf.IEmpty[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.paginatedMethod.asyncIterate as SinonStub) - .getCall(0).args[1], request); - }); + it('uses async iteration with paginatedMethod without error', async () => { + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize1(); + const request = generateSampleMessage( + new protos.google.naming.v1beta1.PaginatedMethodRequest(), + ); + const expectedResponse = [ + generateSampleMessage(new protos.google.protobuf.Empty()), + generateSampleMessage(new protos.google.protobuf.Empty()), + generateSampleMessage(new protos.google.protobuf.Empty()), + ]; + client.descriptors.page.paginatedMethod.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.protobuf.IEmpty[] = []; + const iterable = client.paginatedMethodAsync1(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.paginatedMethod.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); }); - describe('Path templates', () => { - - describe('projectExport', async () => { - const fakePath = "/rendered/path/projectExport"; - const expectedParameters = { - project: "projectValue", - export: "exportValue", - }; - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize1(); - client.pathTemplates.projectExportPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectExportPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectExportPath', () => { - const result = client.projectExportPath("projectValue", "exportValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectExportPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectExportName', () => { - const result = client.matchProjectFromProjectExportName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectExportPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchExportFromProjectExportName', () => { - const result = client.matchExportFromProjectExportName(fakePath); - assert.strictEqual(result, "exportValue"); - assert((client.pathTemplates.projectExportPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('uses async iteration with paginatedMethod with error', async () => { + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize1(); + const request = generateSampleMessage( + new protos.google.naming.v1beta1.PaginatedMethodRequest(), + ); + const expectedError = new Error('expected'); + client.descriptors.page.paginatedMethod.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.paginatedMethodAsync1(request); + await assert.rejects(async () => { + const responses: protos.google.protobuf.IEmpty[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.paginatedMethod.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + }); + }); + + describe('Path templates', () => { + describe('projectExport', async () => { + const fakePath = '/rendered/path/projectExport'; + const expectedParameters = { + project: 'projectValue', + export: 'exportValue', + }; + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize1(); + client.pathTemplates.projectExportPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectExportPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectExportPath', () => { + const result = client.projectExportPath('projectValue', 'exportValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.projectExportPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectExportName', () => { + const result = client.matchProjectFromProjectExportName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.projectExportPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchExportFromProjectExportName', () => { + const result = client.matchExportFromProjectExportName(fakePath); + assert.strictEqual(result, 'exportValue'); + assert( + (client.pathTemplates.projectExportPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectPackage', async () => { - const fakePath = "/rendered/path/projectPackage"; - const expectedParameters = { - project: "projectValue", - package: "packageValue", - }; - const client = new namingModule.v1beta1.NamingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize1(); - client.pathTemplates.projectPackagePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectPackagePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectPackagePath', () => { - const result = client.projectPackagePath("projectValue", "packageValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectPackagePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectPackageName', () => { - const result = client.matchProjectFromProjectPackageName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectPackagePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchPackageFromProjectPackageName', () => { - const result = client.matchPackageFromProjectPackageName(fakePath); - assert.strictEqual(result, "packageValue"); - assert((client.pathTemplates.projectPackagePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectPackage', async () => { + const fakePath = '/rendered/path/projectPackage'; + const expectedParameters = { + project: 'projectValue', + package: 'packageValue', + }; + const client = new namingModule.v1beta1.NamingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize1(); + client.pathTemplates.projectPackagePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectPackagePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectPackagePath', () => { + const result = client.projectPackagePath( + 'projectValue', + 'packageValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.projectPackagePathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectPackageName', () => { + const result = client.matchProjectFromProjectPackageName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.projectPackagePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchPackageFromProjectPackageName', () => { + const result = client.matchPackageFromProjectPackageName(fakePath); + assert.strictEqual(result, 'packageValue'); + assert( + (client.pathTemplates.projectPackagePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/core/generator/gapic-generator-typescript/baselines/redis-esm/esm/src/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/redis-esm/esm/src/index.ts.baseline index c280e9e22790..be7eab0c2662 100644 --- a/core/generator/gapic-generator-typescript/baselines/redis-esm/esm/src/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/redis-esm/esm/src/index.ts.baseline @@ -19,8 +19,8 @@ import * as v1beta1 from './v1beta1/index.js'; const CloudRedisClient = v1beta1.CloudRedisClient; type CloudRedisClient = v1beta1.CloudRedisClient; -export {v1beta1, CloudRedisClient}; -export default {v1beta1, CloudRedisClient}; +export { v1beta1, CloudRedisClient }; +export default { v1beta1, CloudRedisClient }; // @ts-ignore import * as protos from '../../protos/protos.js'; -export {protos} +export { protos }; diff --git a/core/generator/gapic-generator-typescript/baselines/redis-esm/esm/src/v1beta1/cloud_redis_client.ts.baseline b/core/generator/gapic-generator-typescript/baselines/redis-esm/esm/src/v1beta1/cloud_redis_client.ts.baseline index 2a96fdfee5ab..6263f709dea9 100644 --- a/core/generator/gapic-generator-typescript/baselines/redis-esm/esm/src/v1beta1/cloud_redis_client.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/redis-esm/esm/src/v1beta1/cloud_redis_client.ts.baseline @@ -18,15 +18,24 @@ /* global window */ import * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions, GrpcClientOptions, LROperation, PaginationCallback, GaxCall} from 'google-gax'; -import {Transform} from 'stream'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + GrpcClientOptions, + LROperation, + PaginationCallback, + GaxCall, +} from 'google-gax'; +import { Transform } from 'stream'; // @ts-ignore import type * as protos from '../../../protos/protos.js'; import * as cloud_redis_client_config from './cloud_redis_client_config.json'; import fs from 'fs'; import path from 'path'; -import {fileURLToPath} from 'url'; -import {getJSON} from '../json-helper.cjs'; +import { fileURLToPath } from 'url'; +import { getJSON } from '../json-helper.cjs'; // @ts-ignore const dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -36,15 +45,15 @@ const dirname = path.dirname(fileURLToPath(import.meta.url)); * This file defines retry strategy and timeouts for all API methods in this library. */ const gapicConfig = getJSON( - path.join(dirname, 'cloud_redis_client_config.json') + path.join(dirname, 'cloud_redis_client_config.json'), ); const jsonProtos = getJSON( - path.join(dirname, '..', '..', '..', 'protos/protos.json') + path.join(dirname, '..', '..', '..', 'protos/protos.json'), ); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; const version = getJSON( - path.join(dirname, '..', '..', '..', '..', 'package.json') + path.join(dirname, '..', '..', '..', '..', 'package.json'), ).version; /** @@ -73,7 +82,7 @@ export class CloudRedisClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('redis'); @@ -85,10 +94,10 @@ export class CloudRedisClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; operationsClient: gax.OperationsClient; - cloudRedisStub?: Promise<{[name: string]: Function}>; + cloudRedisStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of CloudRedisClient. @@ -130,21 +139,42 @@ export class CloudRedisClient { * const client = new CloudRedisClient({fallback: 'rest'}, gax); * ``` */ - constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { // Ensure that options include all the required fields. const staticMembers = this.constructor as typeof CloudRedisClient; - if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { - throw new Error('Please set either universe_domain or universeDomain, but not both.'); + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); } - const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; - this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; this._servicePath = 'redis.' + this._universeDomain; - const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; - const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. if (servicePath !== this._servicePath && !('scopes' in opts)) { @@ -166,7 +196,7 @@ export class CloudRedisClient { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; @@ -183,10 +213,7 @@ export class CloudRedisClient { const isEsm = true; const isEsmString = isEsm ? '-esm' : '-cjs'; // Determine the client header string. - const clientHeader = [ - `gax/${this._gaxModule.version}`, - `gapic/${version}`, - ]; + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/{process.versions.node}${isEsmString}`); } else { @@ -194,7 +221,7 @@ export class CloudRedisClient { } if (!opts.fallback) { clientHeader.push(`grpc/${this._gaxGrpc.grpcVersion}`); - } else if (opts.fallback === 'rest' ) { + } else if (opts.fallback === 'rest') { clientHeader.push(`rest/${this._gaxGrpc.grpcVersion}`); } if (opts.libName && opts.libVersion) { @@ -202,17 +229,19 @@ export class CloudRedisClient { } // Load the applicable protos. - this._protos = this._gaxGrpc.loadProtoJSON(jsonProtos as gax.protobuf.INamespace); + this._protos = this._gaxGrpc.loadProtoJSON( + jsonProtos as gax.protobuf.INamespace, + ); // This API contains "path templates"; forward-slash-separated // identifiers to uniquely identify resources within the API. // Create useful helper objects for these. this.pathTemplates = { instancePathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/instances/{instance}' + 'projects/{project}/locations/{location}/instances/{instance}', ), locationPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}' + 'projects/{project}/locations/{location}', ), }; @@ -220,8 +249,11 @@ export class CloudRedisClient { // (e.g. 50 results at a time, with tokens to get subsequent // pages). Denote the keys used for pagination and results. this.descriptors.page = { - listInstances: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'instances') + listInstances: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'instances', + ), }; const protoFilesRoot = this._gaxModule.protobufFromJSON(jsonProtos); @@ -230,69 +262,92 @@ export class CloudRedisClient { // rather than holding a request open. const lroOptions: GrpcClientOptions = { auth: this.auth, - grpc: 'grpc' in this._gaxGrpc ? this._gaxGrpc.grpc : undefined + grpc: 'grpc' in this._gaxGrpc ? this._gaxGrpc.grpc : undefined, }; if (opts.fallback === 'rest') { lroOptions.protoJson = protoFilesRoot; lroOptions.httpRules = []; } - this.operationsClient = this._gaxModule.lro(lroOptions).operationsClient(opts); + this.operationsClient = this._gaxModule + .lro(lroOptions) + .operationsClient(opts); const createInstanceResponse = protoFilesRoot.lookup( - '.google.cloud.redis.v1beta1.Instance') as gax.protobuf.Type; + '.google.cloud.redis.v1beta1.Instance', + ) as gax.protobuf.Type; const createInstanceMetadata = protoFilesRoot.lookup( - '.google.protobuf.Any') as gax.protobuf.Type; + '.google.protobuf.Any', + ) as gax.protobuf.Type; const updateInstanceResponse = protoFilesRoot.lookup( - '.google.cloud.redis.v1beta1.Instance') as gax.protobuf.Type; + '.google.cloud.redis.v1beta1.Instance', + ) as gax.protobuf.Type; const updateInstanceMetadata = protoFilesRoot.lookup( - '.google.protobuf.Any') as gax.protobuf.Type; + '.google.protobuf.Any', + ) as gax.protobuf.Type; const importInstanceResponse = protoFilesRoot.lookup( - '.google.cloud.redis.v1beta1.Instance') as gax.protobuf.Type; + '.google.cloud.redis.v1beta1.Instance', + ) as gax.protobuf.Type; const importInstanceMetadata = protoFilesRoot.lookup( - '.google.protobuf.Any') as gax.protobuf.Type; + '.google.protobuf.Any', + ) as gax.protobuf.Type; const exportInstanceResponse = protoFilesRoot.lookup( - '.google.cloud.redis.v1beta1.Instance') as gax.protobuf.Type; + '.google.cloud.redis.v1beta1.Instance', + ) as gax.protobuf.Type; const exportInstanceMetadata = protoFilesRoot.lookup( - '.google.protobuf.Any') as gax.protobuf.Type; + '.google.protobuf.Any', + ) as gax.protobuf.Type; const failoverInstanceResponse = protoFilesRoot.lookup( - '.google.cloud.redis.v1beta1.Instance') as gax.protobuf.Type; + '.google.cloud.redis.v1beta1.Instance', + ) as gax.protobuf.Type; const failoverInstanceMetadata = protoFilesRoot.lookup( - '.google.protobuf.Any') as gax.protobuf.Type; + '.google.protobuf.Any', + ) as gax.protobuf.Type; const deleteInstanceResponse = protoFilesRoot.lookup( - '.google.protobuf.Empty') as gax.protobuf.Type; + '.google.protobuf.Empty', + ) as gax.protobuf.Type; const deleteInstanceMetadata = protoFilesRoot.lookup( - '.google.protobuf.Any') as gax.protobuf.Type; + '.google.protobuf.Any', + ) as gax.protobuf.Type; this.descriptors.longrunning = { createInstance: new this._gaxModule.LongrunningDescriptor( this.operationsClient, createInstanceResponse.decode.bind(createInstanceResponse), - createInstanceMetadata.decode.bind(createInstanceMetadata)), + createInstanceMetadata.decode.bind(createInstanceMetadata), + ), updateInstance: new this._gaxModule.LongrunningDescriptor( this.operationsClient, updateInstanceResponse.decode.bind(updateInstanceResponse), - updateInstanceMetadata.decode.bind(updateInstanceMetadata)), + updateInstanceMetadata.decode.bind(updateInstanceMetadata), + ), importInstance: new this._gaxModule.LongrunningDescriptor( this.operationsClient, importInstanceResponse.decode.bind(importInstanceResponse), - importInstanceMetadata.decode.bind(importInstanceMetadata)), + importInstanceMetadata.decode.bind(importInstanceMetadata), + ), exportInstance: new this._gaxModule.LongrunningDescriptor( this.operationsClient, exportInstanceResponse.decode.bind(exportInstanceResponse), - exportInstanceMetadata.decode.bind(exportInstanceMetadata)), + exportInstanceMetadata.decode.bind(exportInstanceMetadata), + ), failoverInstance: new this._gaxModule.LongrunningDescriptor( this.operationsClient, failoverInstanceResponse.decode.bind(failoverInstanceResponse), - failoverInstanceMetadata.decode.bind(failoverInstanceMetadata)), + failoverInstanceMetadata.decode.bind(failoverInstanceMetadata), + ), deleteInstance: new this._gaxModule.LongrunningDescriptor( this.operationsClient, deleteInstanceResponse.decode.bind(deleteInstanceResponse), - deleteInstanceMetadata.decode.bind(deleteInstanceMetadata)) + deleteInstanceMetadata.decode.bind(deleteInstanceMetadata), + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.cloud.redis.v1beta1.CloudRedis', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.cloud.redis.v1beta1.CloudRedis', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + { 'x-goog-api-client': clientHeader.join(' ') }, + ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -323,28 +378,42 @@ export class CloudRedisClient { // Put together the "service stub" for // google.cloud.redis.v1beta1.CloudRedis. this.cloudRedisStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.cloud.redis.v1beta1.CloudRedis') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.cloud.redis.v1beta1.CloudRedis', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.cloud.redis.v1beta1.CloudRedis, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts, + this._providedCustomServicePath, + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const cloudRedisStubMethods = - ['listInstances', 'getInstance', 'createInstance', 'updateInstance', 'importInstance', 'exportInstance', 'failoverInstance', 'deleteInstance']; + const cloudRedisStubMethods = [ + 'listInstances', + 'getInstance', + 'createInstance', + 'updateInstance', + 'importInstance', + 'exportInstance', + 'failoverInstance', + 'deleteInstance', + ]; for (const methodName of cloudRedisStubMethods) { const callPromise = this.cloudRedisStub.then( - stub => (...args: Array<{}>) => { - if (this._terminated) { - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error|null|undefined) => () => { + (stub) => + (...args: Array<{}>) => { + if (this._terminated) { + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { throw err; - }); + }, + ); const descriptor = this.descriptors.page[methodName] || @@ -354,7 +423,7 @@ export class CloudRedisClient { callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -369,8 +438,14 @@ export class CloudRedisClient { * @returns {string} The DNS address for this service. */ static get servicePath() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'redis.googleapis.com'; } @@ -382,8 +457,14 @@ export class CloudRedisClient { * @returns {string} The DNS address for this service. */ static get apiEndpoint() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'redis.googleapis.com'; } @@ -414,9 +495,7 @@ export class CloudRedisClient { * @returns {string[]} List of default scopes. */ static get scopes() { - return [ - 'https://www.googleapis.com/auth/cloud-platform' - ]; + return ['https://www.googleapis.com/auth/cloud-platform']; } getProjectId(): Promise; @@ -425,8 +504,9 @@ export class CloudRedisClient { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId(callback?: Callback): - Promise|void { + getProjectId( + callback?: Callback, + ): Promise | void { if (callback) { this.auth.getProjectId(callback); return; @@ -437,908 +517,1322 @@ export class CloudRedisClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Gets the details of a specific Redis instance. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. Redis instance resource name using the form: - * `projects/{project_id}/locations/{location_id}/instances/{instance_id}` - * where `location_id` refers to a GCP region. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.redis.v1beta1.Instance|Instance}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/cloud_redis.get_instance.js - * region_tag:redis_v1beta1_generated_CloudRedis_GetInstance_async - */ + /** + * Gets the details of a specific Redis instance. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Redis instance resource name using the form: + * `projects/{project_id}/locations/{location_id}/instances/{instance_id}` + * where `location_id` refers to a GCP region. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.redis.v1beta1.Instance|Instance}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/cloud_redis.get_instance.js + * region_tag:redis_v1beta1_generated_CloudRedis_GetInstance_async + */ getInstance( - request?: protos.google.cloud.redis.v1beta1.IGetInstanceRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.redis.v1beta1.IInstance, - protos.google.cloud.redis.v1beta1.IGetInstanceRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.redis.v1beta1.IGetInstanceRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.redis.v1beta1.IInstance, + protos.google.cloud.redis.v1beta1.IGetInstanceRequest | undefined, + {} | undefined, + ] + >; getInstance( - request: protos.google.cloud.redis.v1beta1.IGetInstanceRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.redis.v1beta1.IInstance, - protos.google.cloud.redis.v1beta1.IGetInstanceRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.redis.v1beta1.IGetInstanceRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.redis.v1beta1.IInstance, + protos.google.cloud.redis.v1beta1.IGetInstanceRequest | null | undefined, + {} | null | undefined + >, + ): void; getInstance( - request: protos.google.cloud.redis.v1beta1.IGetInstanceRequest, - callback: Callback< - protos.google.cloud.redis.v1beta1.IInstance, - protos.google.cloud.redis.v1beta1.IGetInstanceRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.redis.v1beta1.IGetInstanceRequest, + callback: Callback< + protos.google.cloud.redis.v1beta1.IInstance, + protos.google.cloud.redis.v1beta1.IGetInstanceRequest | null | undefined, + {} | null | undefined + >, + ): void; getInstance( - request?: protos.google.cloud.redis.v1beta1.IGetInstanceRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.redis.v1beta1.IInstance, - protos.google.cloud.redis.v1beta1.IGetInstanceRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.redis.v1beta1.IGetInstanceRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.redis.v1beta1.IInstance, - protos.google.cloud.redis.v1beta1.IGetInstanceRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.redis.v1beta1.IInstance, - protos.google.cloud.redis.v1beta1.IGetInstanceRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.redis.v1beta1.IGetInstanceRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.redis.v1beta1.IInstance, + protos.google.cloud.redis.v1beta1.IGetInstanceRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.redis.v1beta1.IInstance, + protos.google.cloud.redis.v1beta1.IGetInstanceRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getInstance request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.redis.v1beta1.IInstance, - protos.google.cloud.redis.v1beta1.IGetInstanceRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.redis.v1beta1.IInstance, + | protos.google.cloud.redis.v1beta1.IGetInstanceRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getInstance response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.getInstance(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.redis.v1beta1.IInstance, - protos.google.cloud.redis.v1beta1.IGetInstanceRequest|undefined, {}|undefined - ]) => { - this._log.info('getInstance response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getInstance(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.redis.v1beta1.IInstance, + protos.google.cloud.redis.v1beta1.IGetInstanceRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getInstance response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Creates a Redis instance based on the specified tier and memory size. - * - * By default, the instance is accessible from the project's - * [default network](/compute/docs/networks-and-firewalls#networks). - * - * The creation is executed asynchronously and callers may check the returned - * operation to track its progress. Once the operation is completed the Redis - * instance will be fully functional. Completed longrunning.Operation will - * contain the new instance object in the response field. - * - * The returned operation is automatically deleted after a few hours, so there - * is no need to call DeleteOperation. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The resource name of the instance location using the form: - * `projects/{project_id}/locations/{location_id}` - * where `location_id` refers to a GCP region. - * @param {string} request.instanceId - * Required. The logical name of the Redis instance in the customer project - * with the following restrictions: - * - * * Must contain only lowercase letters, numbers, and hyphens. - * * Must start with a letter. - * * Must be between 1-40 characters. - * * Must end with a number or a letter. - * * Must be unique within the customer project / location - * @param {google.cloud.redis.v1beta1.Instance} request.instance - * Required. A Redis [Instance] resource - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing - * a long running operation. Its `promise()` method returns a promise - * you can `await` for. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/cloud_redis.create_instance.js - * region_tag:redis_v1beta1_generated_CloudRedis_CreateInstance_async - */ + /** + * Creates a Redis instance based on the specified tier and memory size. + * + * By default, the instance is accessible from the project's + * [default network](/compute/docs/networks-and-firewalls#networks). + * + * The creation is executed asynchronously and callers may check the returned + * operation to track its progress. Once the operation is completed the Redis + * instance will be fully functional. Completed longrunning.Operation will + * contain the new instance object in the response field. + * + * The returned operation is automatically deleted after a few hours, so there + * is no need to call DeleteOperation. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The resource name of the instance location using the form: + * `projects/{project_id}/locations/{location_id}` + * where `location_id` refers to a GCP region. + * @param {string} request.instanceId + * Required. The logical name of the Redis instance in the customer project + * with the following restrictions: + * + * * Must contain only lowercase letters, numbers, and hyphens. + * * Must start with a letter. + * * Must be between 1-40 characters. + * * Must end with a number or a letter. + * * Must be unique within the customer project / location + * @param {google.cloud.redis.v1beta1.Instance} request.instance + * Required. A Redis [Instance] resource + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/cloud_redis.create_instance.js + * region_tag:redis_v1beta1_generated_CloudRedis_CreateInstance_async + */ createInstance( - request?: protos.google.cloud.redis.v1beta1.ICreateInstanceRequest, - options?: CallOptions): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>; + request?: protos.google.cloud.redis.v1beta1.ICreateInstanceRequest, + options?: CallOptions, + ): Promise< + [ + LROperation< + protos.google.cloud.redis.v1beta1.IInstance, + protos.google.protobuf.IAny + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; createInstance( - request: protos.google.cloud.redis.v1beta1.ICreateInstanceRequest, - options: CallOptions, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.redis.v1beta1.ICreateInstanceRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.cloud.redis.v1beta1.IInstance, + protos.google.protobuf.IAny + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; createInstance( - request: protos.google.cloud.redis.v1beta1.ICreateInstanceRequest, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.redis.v1beta1.ICreateInstanceRequest, + callback: Callback< + LROperation< + protos.google.cloud.redis.v1beta1.IInstance, + protos.google.protobuf.IAny + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; createInstance( - request?: protos.google.cloud.redis.v1beta1.ICreateInstanceRequest, - optionsOrCallback?: CallOptions|Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>, - callback?: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>|void { + request?: protos.google.cloud.redis.v1beta1.ICreateInstanceRequest, + optionsOrCallback?: + | CallOptions + | Callback< + LROperation< + protos.google.cloud.redis.v1beta1.IInstance, + protos.google.protobuf.IAny + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + callback?: Callback< + LROperation< + protos.google.cloud.redis.v1beta1.IInstance, + protos.google.protobuf.IAny + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + LROperation< + protos.google.cloud.redis.v1beta1.IInstance, + protos.google.protobuf.IAny + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + LROperation< + protos.google.cloud.redis.v1beta1.IInstance, + protos.google.protobuf.IAny + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, rawResponse, _) => { this._log.info('createInstance response %j', rawResponse); callback!(error, response, rawResponse, _); // We verified `callback` above. } : undefined; this._log.info('createInstance request %j', request); - return this.innerApiCalls.createInstance(request, options, wrappedCallback) - ?.then(([response, rawResponse, _]: [ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]) => { - this._log.info('createInstance response %j', rawResponse); - return [response, rawResponse, _]; - }); + return this.innerApiCalls + .createInstance(request, options, wrappedCallback) + ?.then( + ([response, rawResponse, _]: [ + LROperation< + protos.google.cloud.redis.v1beta1.IInstance, + protos.google.protobuf.IAny + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ]) => { + this._log.info('createInstance response %j', rawResponse); + return [response, rawResponse, _]; + }, + ); } -/** - * Check the status of the long running operation returned by `createInstance()`. - * @param {String} name - * The operation name that will be passed. - * @returns {Promise} - The promise which resolves to an object. - * The decoded operation object has result and metadata field to get information from. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/cloud_redis.create_instance.js - * region_tag:redis_v1beta1_generated_CloudRedis_CreateInstance_async - */ - async checkCreateInstanceProgress(name: string): Promise>{ + /** + * Check the status of the long running operation returned by `createInstance()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/cloud_redis.create_instance.js + * region_tag:redis_v1beta1_generated_CloudRedis_CreateInstance_async + */ + async checkCreateInstanceProgress( + name: string, + ): Promise< + LROperation< + protos.google.cloud.redis.v1beta1.Instance, + protos.google.protobuf.Any + > + > { this._log.info('createInstance long-running'); - const request = new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest({name}); + const request = + new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( + { name }, + ); const [operation] = await this.operationsClient.getOperation(request); - const decodeOperation = new this._gaxModule.Operation(operation, this.descriptors.longrunning.createInstance, this._gaxModule.createDefaultBackoffSettings()); - return decodeOperation as LROperation; + const decodeOperation = new this._gaxModule.Operation( + operation, + this.descriptors.longrunning.createInstance, + this._gaxModule.createDefaultBackoffSettings(), + ); + return decodeOperation as LROperation< + protos.google.cloud.redis.v1beta1.Instance, + protos.google.protobuf.Any + >; } -/** - * Updates the metadata and configuration of a specific Redis instance. - * - * Completed longrunning.Operation will contain the new instance object - * in the response field. The returned operation is automatically deleted - * after a few hours, so there is no need to call DeleteOperation. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.protobuf.FieldMask} request.updateMask - * Required. Mask of fields to update. At least one path must be supplied in - * this field. The elements of the repeated paths field may only include these - * fields from {@link protos.google.cloud.redis.v1beta1.Instance|Instance}: - * - * * `displayName` - * * `labels` - * * `memorySizeGb` - * * `redisConfig` - * @param {google.cloud.redis.v1beta1.Instance} request.instance - * Required. Update description. - * Only fields specified in update_mask are updated. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing - * a long running operation. Its `promise()` method returns a promise - * you can `await` for. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/cloud_redis.update_instance.js - * region_tag:redis_v1beta1_generated_CloudRedis_UpdateInstance_async - */ + /** + * Updates the metadata and configuration of a specific Redis instance. + * + * Completed longrunning.Operation will contain the new instance object + * in the response field. The returned operation is automatically deleted + * after a few hours, so there is no need to call DeleteOperation. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.protobuf.FieldMask} request.updateMask + * Required. Mask of fields to update. At least one path must be supplied in + * this field. The elements of the repeated paths field may only include these + * fields from {@link protos.google.cloud.redis.v1beta1.Instance|Instance}: + * + * * `displayName` + * * `labels` + * * `memorySizeGb` + * * `redisConfig` + * @param {google.cloud.redis.v1beta1.Instance} request.instance + * Required. Update description. + * Only fields specified in update_mask are updated. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/cloud_redis.update_instance.js + * region_tag:redis_v1beta1_generated_CloudRedis_UpdateInstance_async + */ updateInstance( - request?: protos.google.cloud.redis.v1beta1.IUpdateInstanceRequest, - options?: CallOptions): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>; + request?: protos.google.cloud.redis.v1beta1.IUpdateInstanceRequest, + options?: CallOptions, + ): Promise< + [ + LROperation< + protos.google.cloud.redis.v1beta1.IInstance, + protos.google.protobuf.IAny + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; updateInstance( - request: protos.google.cloud.redis.v1beta1.IUpdateInstanceRequest, - options: CallOptions, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.redis.v1beta1.IUpdateInstanceRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.cloud.redis.v1beta1.IInstance, + protos.google.protobuf.IAny + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; updateInstance( - request: protos.google.cloud.redis.v1beta1.IUpdateInstanceRequest, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.redis.v1beta1.IUpdateInstanceRequest, + callback: Callback< + LROperation< + protos.google.cloud.redis.v1beta1.IInstance, + protos.google.protobuf.IAny + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; updateInstance( - request?: protos.google.cloud.redis.v1beta1.IUpdateInstanceRequest, - optionsOrCallback?: CallOptions|Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>, - callback?: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>|void { + request?: protos.google.cloud.redis.v1beta1.IUpdateInstanceRequest, + optionsOrCallback?: + | CallOptions + | Callback< + LROperation< + protos.google.cloud.redis.v1beta1.IInstance, + protos.google.protobuf.IAny + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + callback?: Callback< + LROperation< + protos.google.cloud.redis.v1beta1.IInstance, + protos.google.protobuf.IAny + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + LROperation< + protos.google.cloud.redis.v1beta1.IInstance, + protos.google.protobuf.IAny + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'instance.name': request.instance!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'instance.name': request.instance!.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + LROperation< + protos.google.cloud.redis.v1beta1.IInstance, + protos.google.protobuf.IAny + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, rawResponse, _) => { this._log.info('updateInstance response %j', rawResponse); callback!(error, response, rawResponse, _); // We verified `callback` above. } : undefined; this._log.info('updateInstance request %j', request); - return this.innerApiCalls.updateInstance(request, options, wrappedCallback) - ?.then(([response, rawResponse, _]: [ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]) => { - this._log.info('updateInstance response %j', rawResponse); - return [response, rawResponse, _]; - }); + return this.innerApiCalls + .updateInstance(request, options, wrappedCallback) + ?.then( + ([response, rawResponse, _]: [ + LROperation< + protos.google.cloud.redis.v1beta1.IInstance, + protos.google.protobuf.IAny + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ]) => { + this._log.info('updateInstance response %j', rawResponse); + return [response, rawResponse, _]; + }, + ); } -/** - * Check the status of the long running operation returned by `updateInstance()`. - * @param {String} name - * The operation name that will be passed. - * @returns {Promise} - The promise which resolves to an object. - * The decoded operation object has result and metadata field to get information from. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/cloud_redis.update_instance.js - * region_tag:redis_v1beta1_generated_CloudRedis_UpdateInstance_async - */ - async checkUpdateInstanceProgress(name: string): Promise>{ + /** + * Check the status of the long running operation returned by `updateInstance()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/cloud_redis.update_instance.js + * region_tag:redis_v1beta1_generated_CloudRedis_UpdateInstance_async + */ + async checkUpdateInstanceProgress( + name: string, + ): Promise< + LROperation< + protos.google.cloud.redis.v1beta1.Instance, + protos.google.protobuf.Any + > + > { this._log.info('updateInstance long-running'); - const request = new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest({name}); + const request = + new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( + { name }, + ); const [operation] = await this.operationsClient.getOperation(request); - const decodeOperation = new this._gaxModule.Operation(operation, this.descriptors.longrunning.updateInstance, this._gaxModule.createDefaultBackoffSettings()); - return decodeOperation as LROperation; + const decodeOperation = new this._gaxModule.Operation( + operation, + this.descriptors.longrunning.updateInstance, + this._gaxModule.createDefaultBackoffSettings(), + ); + return decodeOperation as LROperation< + protos.google.cloud.redis.v1beta1.Instance, + protos.google.protobuf.Any + >; } -/** - * Import a Redis RDB snapshot file from Cloud Storage into a Redis instance. - * - * Redis may stop serving during this operation. Instance state will be - * IMPORTING for entire operation. When complete, the instance will contain - * only data from the imported file. - * - * The returned operation is automatically deleted after a few hours, so - * there is no need to call DeleteOperation. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. Redis instance resource name using the form: - * `projects/{project_id}/locations/{location_id}/instances/{instance_id}` - * where `location_id` refers to a GCP region. - * @param {google.cloud.redis.v1beta1.InputConfig} request.inputConfig - * Required. Specify data to be imported. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing - * a long running operation. Its `promise()` method returns a promise - * you can `await` for. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/cloud_redis.import_instance.js - * region_tag:redis_v1beta1_generated_CloudRedis_ImportInstance_async - */ + /** + * Import a Redis RDB snapshot file from Cloud Storage into a Redis instance. + * + * Redis may stop serving during this operation. Instance state will be + * IMPORTING for entire operation. When complete, the instance will contain + * only data from the imported file. + * + * The returned operation is automatically deleted after a few hours, so + * there is no need to call DeleteOperation. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Redis instance resource name using the form: + * `projects/{project_id}/locations/{location_id}/instances/{instance_id}` + * where `location_id` refers to a GCP region. + * @param {google.cloud.redis.v1beta1.InputConfig} request.inputConfig + * Required. Specify data to be imported. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/cloud_redis.import_instance.js + * region_tag:redis_v1beta1_generated_CloudRedis_ImportInstance_async + */ importInstance( - request?: protos.google.cloud.redis.v1beta1.IImportInstanceRequest, - options?: CallOptions): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>; + request?: protos.google.cloud.redis.v1beta1.IImportInstanceRequest, + options?: CallOptions, + ): Promise< + [ + LROperation< + protos.google.cloud.redis.v1beta1.IInstance, + protos.google.protobuf.IAny + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; importInstance( - request: protos.google.cloud.redis.v1beta1.IImportInstanceRequest, - options: CallOptions, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.redis.v1beta1.IImportInstanceRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.cloud.redis.v1beta1.IInstance, + protos.google.protobuf.IAny + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; importInstance( - request: protos.google.cloud.redis.v1beta1.IImportInstanceRequest, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.redis.v1beta1.IImportInstanceRequest, + callback: Callback< + LROperation< + protos.google.cloud.redis.v1beta1.IInstance, + protos.google.protobuf.IAny + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; importInstance( - request?: protos.google.cloud.redis.v1beta1.IImportInstanceRequest, - optionsOrCallback?: CallOptions|Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>, - callback?: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>|void { + request?: protos.google.cloud.redis.v1beta1.IImportInstanceRequest, + optionsOrCallback?: + | CallOptions + | Callback< + LROperation< + protos.google.cloud.redis.v1beta1.IInstance, + protos.google.protobuf.IAny + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + callback?: Callback< + LROperation< + protos.google.cloud.redis.v1beta1.IInstance, + protos.google.protobuf.IAny + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + LROperation< + protos.google.cloud.redis.v1beta1.IInstance, + protos.google.protobuf.IAny + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + LROperation< + protos.google.cloud.redis.v1beta1.IInstance, + protos.google.protobuf.IAny + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, rawResponse, _) => { this._log.info('importInstance response %j', rawResponse); callback!(error, response, rawResponse, _); // We verified `callback` above. } : undefined; this._log.info('importInstance request %j', request); - return this.innerApiCalls.importInstance(request, options, wrappedCallback) - ?.then(([response, rawResponse, _]: [ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]) => { - this._log.info('importInstance response %j', rawResponse); - return [response, rawResponse, _]; - }); + return this.innerApiCalls + .importInstance(request, options, wrappedCallback) + ?.then( + ([response, rawResponse, _]: [ + LROperation< + protos.google.cloud.redis.v1beta1.IInstance, + protos.google.protobuf.IAny + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ]) => { + this._log.info('importInstance response %j', rawResponse); + return [response, rawResponse, _]; + }, + ); } -/** - * Check the status of the long running operation returned by `importInstance()`. - * @param {String} name - * The operation name that will be passed. - * @returns {Promise} - The promise which resolves to an object. - * The decoded operation object has result and metadata field to get information from. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/cloud_redis.import_instance.js - * region_tag:redis_v1beta1_generated_CloudRedis_ImportInstance_async - */ - async checkImportInstanceProgress(name: string): Promise>{ + /** + * Check the status of the long running operation returned by `importInstance()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/cloud_redis.import_instance.js + * region_tag:redis_v1beta1_generated_CloudRedis_ImportInstance_async + */ + async checkImportInstanceProgress( + name: string, + ): Promise< + LROperation< + protos.google.cloud.redis.v1beta1.Instance, + protos.google.protobuf.Any + > + > { this._log.info('importInstance long-running'); - const request = new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest({name}); + const request = + new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( + { name }, + ); const [operation] = await this.operationsClient.getOperation(request); - const decodeOperation = new this._gaxModule.Operation(operation, this.descriptors.longrunning.importInstance, this._gaxModule.createDefaultBackoffSettings()); - return decodeOperation as LROperation; + const decodeOperation = new this._gaxModule.Operation( + operation, + this.descriptors.longrunning.importInstance, + this._gaxModule.createDefaultBackoffSettings(), + ); + return decodeOperation as LROperation< + protos.google.cloud.redis.v1beta1.Instance, + protos.google.protobuf.Any + >; } -/** - * Export Redis instance data into a Redis RDB format file in Cloud Storage. - * - * Redis will continue serving during this operation. - * - * The returned operation is automatically deleted after a few hours, so - * there is no need to call DeleteOperation. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. Redis instance resource name using the form: - * `projects/{project_id}/locations/{location_id}/instances/{instance_id}` - * where `location_id` refers to a GCP region. - * @param {google.cloud.redis.v1beta1.OutputConfig} request.outputConfig - * Required. Specify data to be exported. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing - * a long running operation. Its `promise()` method returns a promise - * you can `await` for. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/cloud_redis.export_instance.js - * region_tag:redis_v1beta1_generated_CloudRedis_ExportInstance_async - */ + /** + * Export Redis instance data into a Redis RDB format file in Cloud Storage. + * + * Redis will continue serving during this operation. + * + * The returned operation is automatically deleted after a few hours, so + * there is no need to call DeleteOperation. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Redis instance resource name using the form: + * `projects/{project_id}/locations/{location_id}/instances/{instance_id}` + * where `location_id` refers to a GCP region. + * @param {google.cloud.redis.v1beta1.OutputConfig} request.outputConfig + * Required. Specify data to be exported. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/cloud_redis.export_instance.js + * region_tag:redis_v1beta1_generated_CloudRedis_ExportInstance_async + */ exportInstance( - request?: protos.google.cloud.redis.v1beta1.IExportInstanceRequest, - options?: CallOptions): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>; + request?: protos.google.cloud.redis.v1beta1.IExportInstanceRequest, + options?: CallOptions, + ): Promise< + [ + LROperation< + protos.google.cloud.redis.v1beta1.IInstance, + protos.google.protobuf.IAny + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; exportInstance( - request: protos.google.cloud.redis.v1beta1.IExportInstanceRequest, - options: CallOptions, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.redis.v1beta1.IExportInstanceRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.cloud.redis.v1beta1.IInstance, + protos.google.protobuf.IAny + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; exportInstance( - request: protos.google.cloud.redis.v1beta1.IExportInstanceRequest, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.redis.v1beta1.IExportInstanceRequest, + callback: Callback< + LROperation< + protos.google.cloud.redis.v1beta1.IInstance, + protos.google.protobuf.IAny + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; exportInstance( - request?: protos.google.cloud.redis.v1beta1.IExportInstanceRequest, - optionsOrCallback?: CallOptions|Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>, - callback?: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>|void { + request?: protos.google.cloud.redis.v1beta1.IExportInstanceRequest, + optionsOrCallback?: + | CallOptions + | Callback< + LROperation< + protos.google.cloud.redis.v1beta1.IInstance, + protos.google.protobuf.IAny + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + callback?: Callback< + LROperation< + protos.google.cloud.redis.v1beta1.IInstance, + protos.google.protobuf.IAny + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + LROperation< + protos.google.cloud.redis.v1beta1.IInstance, + protos.google.protobuf.IAny + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + LROperation< + protos.google.cloud.redis.v1beta1.IInstance, + protos.google.protobuf.IAny + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, rawResponse, _) => { this._log.info('exportInstance response %j', rawResponse); callback!(error, response, rawResponse, _); // We verified `callback` above. } : undefined; this._log.info('exportInstance request %j', request); - return this.innerApiCalls.exportInstance(request, options, wrappedCallback) - ?.then(([response, rawResponse, _]: [ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]) => { - this._log.info('exportInstance response %j', rawResponse); - return [response, rawResponse, _]; - }); + return this.innerApiCalls + .exportInstance(request, options, wrappedCallback) + ?.then( + ([response, rawResponse, _]: [ + LROperation< + protos.google.cloud.redis.v1beta1.IInstance, + protos.google.protobuf.IAny + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ]) => { + this._log.info('exportInstance response %j', rawResponse); + return [response, rawResponse, _]; + }, + ); } -/** - * Check the status of the long running operation returned by `exportInstance()`. - * @param {String} name - * The operation name that will be passed. - * @returns {Promise} - The promise which resolves to an object. - * The decoded operation object has result and metadata field to get information from. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/cloud_redis.export_instance.js - * region_tag:redis_v1beta1_generated_CloudRedis_ExportInstance_async - */ - async checkExportInstanceProgress(name: string): Promise>{ + /** + * Check the status of the long running operation returned by `exportInstance()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/cloud_redis.export_instance.js + * region_tag:redis_v1beta1_generated_CloudRedis_ExportInstance_async + */ + async checkExportInstanceProgress( + name: string, + ): Promise< + LROperation< + protos.google.cloud.redis.v1beta1.Instance, + protos.google.protobuf.Any + > + > { this._log.info('exportInstance long-running'); - const request = new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest({name}); + const request = + new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( + { name }, + ); const [operation] = await this.operationsClient.getOperation(request); - const decodeOperation = new this._gaxModule.Operation(operation, this.descriptors.longrunning.exportInstance, this._gaxModule.createDefaultBackoffSettings()); - return decodeOperation as LROperation; + const decodeOperation = new this._gaxModule.Operation( + operation, + this.descriptors.longrunning.exportInstance, + this._gaxModule.createDefaultBackoffSettings(), + ); + return decodeOperation as LROperation< + protos.google.cloud.redis.v1beta1.Instance, + protos.google.protobuf.Any + >; } -/** - * Initiates a failover of the master node to current replica node for a - * specific STANDARD tier Cloud Memorystore for Redis instance. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. Redis instance resource name using the form: - * `projects/{project_id}/locations/{location_id}/instances/{instance_id}` - * where `location_id` refers to a GCP region. - * @param {google.cloud.redis.v1beta1.FailoverInstanceRequest.DataProtectionMode} [request.dataProtectionMode] - * Optional. Available data protection modes that the user can choose. If it's - * unspecified, data protection mode will be LIMITED_DATA_LOSS by default. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing - * a long running operation. Its `promise()` method returns a promise - * you can `await` for. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/cloud_redis.failover_instance.js - * region_tag:redis_v1beta1_generated_CloudRedis_FailoverInstance_async - */ + /** + * Initiates a failover of the master node to current replica node for a + * specific STANDARD tier Cloud Memorystore for Redis instance. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Redis instance resource name using the form: + * `projects/{project_id}/locations/{location_id}/instances/{instance_id}` + * where `location_id` refers to a GCP region. + * @param {google.cloud.redis.v1beta1.FailoverInstanceRequest.DataProtectionMode} [request.dataProtectionMode] + * Optional. Available data protection modes that the user can choose. If it's + * unspecified, data protection mode will be LIMITED_DATA_LOSS by default. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/cloud_redis.failover_instance.js + * region_tag:redis_v1beta1_generated_CloudRedis_FailoverInstance_async + */ failoverInstance( - request?: protos.google.cloud.redis.v1beta1.IFailoverInstanceRequest, - options?: CallOptions): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>; + request?: protos.google.cloud.redis.v1beta1.IFailoverInstanceRequest, + options?: CallOptions, + ): Promise< + [ + LROperation< + protos.google.cloud.redis.v1beta1.IInstance, + protos.google.protobuf.IAny + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; failoverInstance( - request: protos.google.cloud.redis.v1beta1.IFailoverInstanceRequest, - options: CallOptions, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.redis.v1beta1.IFailoverInstanceRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.cloud.redis.v1beta1.IInstance, + protos.google.protobuf.IAny + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; failoverInstance( - request: protos.google.cloud.redis.v1beta1.IFailoverInstanceRequest, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.redis.v1beta1.IFailoverInstanceRequest, + callback: Callback< + LROperation< + protos.google.cloud.redis.v1beta1.IInstance, + protos.google.protobuf.IAny + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; failoverInstance( - request?: protos.google.cloud.redis.v1beta1.IFailoverInstanceRequest, - optionsOrCallback?: CallOptions|Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>, - callback?: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>|void { + request?: protos.google.cloud.redis.v1beta1.IFailoverInstanceRequest, + optionsOrCallback?: + | CallOptions + | Callback< + LROperation< + protos.google.cloud.redis.v1beta1.IInstance, + protos.google.protobuf.IAny + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + callback?: Callback< + LROperation< + protos.google.cloud.redis.v1beta1.IInstance, + protos.google.protobuf.IAny + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + LROperation< + protos.google.cloud.redis.v1beta1.IInstance, + protos.google.protobuf.IAny + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + LROperation< + protos.google.cloud.redis.v1beta1.IInstance, + protos.google.protobuf.IAny + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, rawResponse, _) => { this._log.info('failoverInstance response %j', rawResponse); callback!(error, response, rawResponse, _); // We verified `callback` above. } : undefined; this._log.info('failoverInstance request %j', request); - return this.innerApiCalls.failoverInstance(request, options, wrappedCallback) - ?.then(([response, rawResponse, _]: [ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]) => { - this._log.info('failoverInstance response %j', rawResponse); - return [response, rawResponse, _]; - }); + return this.innerApiCalls + .failoverInstance(request, options, wrappedCallback) + ?.then( + ([response, rawResponse, _]: [ + LROperation< + protos.google.cloud.redis.v1beta1.IInstance, + protos.google.protobuf.IAny + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ]) => { + this._log.info('failoverInstance response %j', rawResponse); + return [response, rawResponse, _]; + }, + ); } -/** - * Check the status of the long running operation returned by `failoverInstance()`. - * @param {String} name - * The operation name that will be passed. - * @returns {Promise} - The promise which resolves to an object. - * The decoded operation object has result and metadata field to get information from. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/cloud_redis.failover_instance.js - * region_tag:redis_v1beta1_generated_CloudRedis_FailoverInstance_async - */ - async checkFailoverInstanceProgress(name: string): Promise>{ + /** + * Check the status of the long running operation returned by `failoverInstance()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/cloud_redis.failover_instance.js + * region_tag:redis_v1beta1_generated_CloudRedis_FailoverInstance_async + */ + async checkFailoverInstanceProgress( + name: string, + ): Promise< + LROperation< + protos.google.cloud.redis.v1beta1.Instance, + protos.google.protobuf.Any + > + > { this._log.info('failoverInstance long-running'); - const request = new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest({name}); + const request = + new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( + { name }, + ); const [operation] = await this.operationsClient.getOperation(request); - const decodeOperation = new this._gaxModule.Operation(operation, this.descriptors.longrunning.failoverInstance, this._gaxModule.createDefaultBackoffSettings()); - return decodeOperation as LROperation; + const decodeOperation = new this._gaxModule.Operation( + operation, + this.descriptors.longrunning.failoverInstance, + this._gaxModule.createDefaultBackoffSettings(), + ); + return decodeOperation as LROperation< + protos.google.cloud.redis.v1beta1.Instance, + protos.google.protobuf.Any + >; } -/** - * Deletes a specific Redis instance. Instance stops serving and data is - * deleted. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. Redis instance resource name using the form: - * `projects/{project_id}/locations/{location_id}/instances/{instance_id}` - * where `location_id` refers to a GCP region. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing - * a long running operation. Its `promise()` method returns a promise - * you can `await` for. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/cloud_redis.delete_instance.js - * region_tag:redis_v1beta1_generated_CloudRedis_DeleteInstance_async - */ + /** + * Deletes a specific Redis instance. Instance stops serving and data is + * deleted. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Redis instance resource name using the form: + * `projects/{project_id}/locations/{location_id}/instances/{instance_id}` + * where `location_id` refers to a GCP region. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/cloud_redis.delete_instance.js + * region_tag:redis_v1beta1_generated_CloudRedis_DeleteInstance_async + */ deleteInstance( - request?: protos.google.cloud.redis.v1beta1.IDeleteInstanceRequest, - options?: CallOptions): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>; + request?: protos.google.cloud.redis.v1beta1.IDeleteInstanceRequest, + options?: CallOptions, + ): Promise< + [ + LROperation, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; deleteInstance( - request: protos.google.cloud.redis.v1beta1.IDeleteInstanceRequest, - options: CallOptions, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.redis.v1beta1.IDeleteInstanceRequest, + options: CallOptions, + callback: Callback< + LROperation, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; deleteInstance( - request: protos.google.cloud.redis.v1beta1.IDeleteInstanceRequest, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.redis.v1beta1.IDeleteInstanceRequest, + callback: Callback< + LROperation, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; deleteInstance( - request?: protos.google.cloud.redis.v1beta1.IDeleteInstanceRequest, - optionsOrCallback?: CallOptions|Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>, - callback?: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>|void { + request?: protos.google.cloud.redis.v1beta1.IDeleteInstanceRequest, + optionsOrCallback?: + | CallOptions + | Callback< + LROperation< + protos.google.protobuf.IEmpty, + protos.google.protobuf.IAny + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + callback?: Callback< + LROperation, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + LROperation, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + LROperation< + protos.google.protobuf.IEmpty, + protos.google.protobuf.IAny + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, rawResponse, _) => { this._log.info('deleteInstance response %j', rawResponse); callback!(error, response, rawResponse, _); // We verified `callback` above. } : undefined; this._log.info('deleteInstance request %j', request); - return this.innerApiCalls.deleteInstance(request, options, wrappedCallback) - ?.then(([response, rawResponse, _]: [ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]) => { - this._log.info('deleteInstance response %j', rawResponse); - return [response, rawResponse, _]; - }); + return this.innerApiCalls + .deleteInstance(request, options, wrappedCallback) + ?.then( + ([response, rawResponse, _]: [ + LROperation< + protos.google.protobuf.IEmpty, + protos.google.protobuf.IAny + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ]) => { + this._log.info('deleteInstance response %j', rawResponse); + return [response, rawResponse, _]; + }, + ); } -/** - * Check the status of the long running operation returned by `deleteInstance()`. - * @param {String} name - * The operation name that will be passed. - * @returns {Promise} - The promise which resolves to an object. - * The decoded operation object has result and metadata field to get information from. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/cloud_redis.delete_instance.js - * region_tag:redis_v1beta1_generated_CloudRedis_DeleteInstance_async - */ - async checkDeleteInstanceProgress(name: string): Promise>{ + /** + * Check the status of the long running operation returned by `deleteInstance()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/cloud_redis.delete_instance.js + * region_tag:redis_v1beta1_generated_CloudRedis_DeleteInstance_async + */ + async checkDeleteInstanceProgress( + name: string, + ): Promise< + LROperation + > { this._log.info('deleteInstance long-running'); - const request = new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest({name}); + const request = + new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( + { name }, + ); const [operation] = await this.operationsClient.getOperation(request); - const decodeOperation = new this._gaxModule.Operation(operation, this.descriptors.longrunning.deleteInstance, this._gaxModule.createDefaultBackoffSettings()); - return decodeOperation as LROperation; + const decodeOperation = new this._gaxModule.Operation( + operation, + this.descriptors.longrunning.deleteInstance, + this._gaxModule.createDefaultBackoffSettings(), + ); + return decodeOperation as LROperation< + protos.google.protobuf.Empty, + protos.google.protobuf.Any + >; } - /** - * Lists all Redis instances owned by a project in either the specified - * location (region) or all locations. - * - * The location should have the following format: - * * `projects/{project_id}/locations/{location_id}` - * - * If `location_id` is specified as `-` (wildcard), then all regions - * available to the project are queried, and the results are aggregated. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The resource name of the instance location using the form: - * `projects/{project_id}/locations/{location_id}` - * where `location_id` refers to a GCP region. - * @param {number} request.pageSize - * The maximum number of items to return. - * - * If not specified, a default value of 1000 will be used by the service. - * Regardless of the page_size value, the response may include a partial list - * and a caller should only rely on response's - * {@link protos.CloudRedis.ListInstancesResponse.next_page_token|next_page_token} - * to determine if there are more instances left to be queried. - * @param {string} request.pageToken - * The next_page_token value returned from a previous List request, - * if any. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.cloud.redis.v1beta1.Instance|Instance}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `listInstancesAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Lists all Redis instances owned by a project in either the specified + * location (region) or all locations. + * + * The location should have the following format: + * * `projects/{project_id}/locations/{location_id}` + * + * If `location_id` is specified as `-` (wildcard), then all regions + * available to the project are queried, and the results are aggregated. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The resource name of the instance location using the form: + * `projects/{project_id}/locations/{location_id}` + * where `location_id` refers to a GCP region. + * @param {number} request.pageSize + * The maximum number of items to return. + * + * If not specified, a default value of 1000 will be used by the service. + * Regardless of the page_size value, the response may include a partial list + * and a caller should only rely on response's + * {@link protos.CloudRedis.ListInstancesResponse.next_page_token|next_page_token} + * to determine if there are more instances left to be queried. + * @param {string} request.pageToken + * The next_page_token value returned from a previous List request, + * if any. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.cloud.redis.v1beta1.Instance|Instance}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listInstancesAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listInstances( - request?: protos.google.cloud.redis.v1beta1.IListInstancesRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.redis.v1beta1.IInstance[], - protos.google.cloud.redis.v1beta1.IListInstancesRequest|null, - protos.google.cloud.redis.v1beta1.IListInstancesResponse - ]>; + request?: protos.google.cloud.redis.v1beta1.IListInstancesRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.redis.v1beta1.IInstance[], + protos.google.cloud.redis.v1beta1.IListInstancesRequest | null, + protos.google.cloud.redis.v1beta1.IListInstancesResponse, + ] + >; listInstances( - request: protos.google.cloud.redis.v1beta1.IListInstancesRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.cloud.redis.v1beta1.IListInstancesRequest, - protos.google.cloud.redis.v1beta1.IListInstancesResponse|null|undefined, - protos.google.cloud.redis.v1beta1.IInstance>): void; + request: protos.google.cloud.redis.v1beta1.IListInstancesRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.cloud.redis.v1beta1.IListInstancesRequest, + | protos.google.cloud.redis.v1beta1.IListInstancesResponse + | null + | undefined, + protos.google.cloud.redis.v1beta1.IInstance + >, + ): void; listInstances( - request: protos.google.cloud.redis.v1beta1.IListInstancesRequest, - callback: PaginationCallback< - protos.google.cloud.redis.v1beta1.IListInstancesRequest, - protos.google.cloud.redis.v1beta1.IListInstancesResponse|null|undefined, - protos.google.cloud.redis.v1beta1.IInstance>): void; + request: protos.google.cloud.redis.v1beta1.IListInstancesRequest, + callback: PaginationCallback< + protos.google.cloud.redis.v1beta1.IListInstancesRequest, + | protos.google.cloud.redis.v1beta1.IListInstancesResponse + | null + | undefined, + protos.google.cloud.redis.v1beta1.IInstance + >, + ): void; listInstances( - request?: protos.google.cloud.redis.v1beta1.IListInstancesRequest, - optionsOrCallback?: CallOptions|PaginationCallback< - protos.google.cloud.redis.v1beta1.IListInstancesRequest, - protos.google.cloud.redis.v1beta1.IListInstancesResponse|null|undefined, - protos.google.cloud.redis.v1beta1.IInstance>, - callback?: PaginationCallback< + request?: protos.google.cloud.redis.v1beta1.IListInstancesRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.cloud.redis.v1beta1.IListInstancesRequest, - protos.google.cloud.redis.v1beta1.IListInstancesResponse|null|undefined, - protos.google.cloud.redis.v1beta1.IInstance>): - Promise<[ - protos.google.cloud.redis.v1beta1.IInstance[], - protos.google.cloud.redis.v1beta1.IListInstancesRequest|null, - protos.google.cloud.redis.v1beta1.IListInstancesResponse - ]>|void { + | protos.google.cloud.redis.v1beta1.IListInstancesResponse + | null + | undefined, + protos.google.cloud.redis.v1beta1.IInstance + >, + callback?: PaginationCallback< + protos.google.cloud.redis.v1beta1.IListInstancesRequest, + | protos.google.cloud.redis.v1beta1.IListInstancesResponse + | null + | undefined, + protos.google.cloud.redis.v1beta1.IInstance + >, + ): Promise< + [ + protos.google.cloud.redis.v1beta1.IInstance[], + protos.google.cloud.redis.v1beta1.IListInstancesRequest | null, + protos.google.cloud.redis.v1beta1.IListInstancesResponse, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.cloud.redis.v1beta1.IListInstancesRequest, - protos.google.cloud.redis.v1beta1.IListInstancesResponse|null|undefined, - protos.google.cloud.redis.v1beta1.IInstance>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.cloud.redis.v1beta1.IListInstancesRequest, + | protos.google.cloud.redis.v1beta1.IListInstancesResponse + | null + | undefined, + protos.google.cloud.redis.v1beta1.IInstance + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listInstances values %j', values); callback!(error, values, nextPageRequest, rawResponse); @@ -1347,127 +1841,131 @@ export class CloudRedisClient { this._log.info('listInstances request %j', request); return this.innerApiCalls .listInstances(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.cloud.redis.v1beta1.IInstance[], - protos.google.cloud.redis.v1beta1.IListInstancesRequest|null, - protos.google.cloud.redis.v1beta1.IListInstancesResponse - ]) => { - this._log.info('listInstances values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.cloud.redis.v1beta1.IInstance[], + protos.google.cloud.redis.v1beta1.IListInstancesRequest | null, + protos.google.cloud.redis.v1beta1.IListInstancesResponse, + ]) => { + this._log.info('listInstances values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listInstances`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The resource name of the instance location using the form: - * `projects/{project_id}/locations/{location_id}` - * where `location_id` refers to a GCP region. - * @param {number} request.pageSize - * The maximum number of items to return. - * - * If not specified, a default value of 1000 will be used by the service. - * Regardless of the page_size value, the response may include a partial list - * and a caller should only rely on response's - * {@link protos.CloudRedis.ListInstancesResponse.next_page_token|next_page_token} - * to determine if there are more instances left to be queried. - * @param {string} request.pageToken - * The next_page_token value returned from a previous List request, - * if any. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.cloud.redis.v1beta1.Instance|Instance} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `listInstancesAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `listInstances`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The resource name of the instance location using the form: + * `projects/{project_id}/locations/{location_id}` + * where `location_id` refers to a GCP region. + * @param {number} request.pageSize + * The maximum number of items to return. + * + * If not specified, a default value of 1000 will be used by the service. + * Regardless of the page_size value, the response may include a partial list + * and a caller should only rely on response's + * {@link protos.CloudRedis.ListInstancesResponse.next_page_token|next_page_token} + * to determine if there are more instances left to be queried. + * @param {string} request.pageToken + * The next_page_token value returned from a previous List request, + * if any. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.cloud.redis.v1beta1.Instance|Instance} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listInstancesAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listInstancesStream( - request?: protos.google.cloud.redis.v1beta1.IListInstancesRequest, - options?: CallOptions): - Transform{ + request?: protos.google.cloud.redis.v1beta1.IListInstancesRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); const defaultCallSettings = this._defaults['listInstances']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listInstances stream %j', request); return this.descriptors.page.listInstances.createStream( this.innerApiCalls.listInstances as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listInstances`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The resource name of the instance location using the form: - * `projects/{project_id}/locations/{location_id}` - * where `location_id` refers to a GCP region. - * @param {number} request.pageSize - * The maximum number of items to return. - * - * If not specified, a default value of 1000 will be used by the service. - * Regardless of the page_size value, the response may include a partial list - * and a caller should only rely on response's - * {@link protos.CloudRedis.ListInstancesResponse.next_page_token|next_page_token} - * to determine if there are more instances left to be queried. - * @param {string} request.pageToken - * The next_page_token value returned from a previous List request, - * if any. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.cloud.redis.v1beta1.Instance|Instance}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/cloud_redis.list_instances.js - * region_tag:redis_v1beta1_generated_CloudRedis_ListInstances_async - */ + /** + * Equivalent to `listInstances`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The resource name of the instance location using the form: + * `projects/{project_id}/locations/{location_id}` + * where `location_id` refers to a GCP region. + * @param {number} request.pageSize + * The maximum number of items to return. + * + * If not specified, a default value of 1000 will be used by the service. + * Regardless of the page_size value, the response may include a partial list + * and a caller should only rely on response's + * {@link protos.CloudRedis.ListInstancesResponse.next_page_token|next_page_token} + * to determine if there are more instances left to be queried. + * @param {string} request.pageToken + * The next_page_token value returned from a previous List request, + * if any. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.cloud.redis.v1beta1.Instance|Instance}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/cloud_redis.list_instances.js + * region_tag:redis_v1beta1_generated_CloudRedis_ListInstances_async + */ listInstancesAsync( - request?: protos.google.cloud.redis.v1beta1.IListInstancesRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.cloud.redis.v1beta1.IListInstancesRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); const defaultCallSettings = this._defaults['listInstances']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listInstances iterate %j', request); return this.descriptors.page.listInstances.asyncIterate( this.innerApiCalls['listInstances'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } -/** + /** * Gets the latest state of a long-running operation. Clients can use this * method to poll the operation result at intervals as recommended by the API * service. @@ -1510,22 +2008,22 @@ export class CloudRedisClient { protos.google.longrunning.Operation, protos.google.longrunning.GetOperationRequest, {} | null | undefined - > + >, ): Promise<[protos.google.longrunning.Operation]> { - let options: gax.CallOptions; - if (typeof optionsOrCallback === 'function' && callback === undefined) { - callback = optionsOrCallback; - options = {}; - } else { - options = optionsOrCallback as gax.CallOptions; - } - options = options || {}; - options.otherArgs = options.otherArgs || {}; - options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers['x-goog-request-params'] = - this._gaxModule.routingHeader.fromParams({ - name: request.name ?? '', - }); + let options: gax.CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as gax.CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); return this.operationsClient.getOperation(request, options, callback); } /** @@ -1560,15 +2058,15 @@ export class CloudRedisClient { */ listOperationsAsync( request: protos.google.longrunning.ListOperationsRequest, - options?: gax.CallOptions + options?: gax.CallOptions, ): AsyncIterable { - options = options || {}; - options.otherArgs = options.otherArgs || {}; - options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers['x-goog-request-params'] = - this._gaxModule.routingHeader.fromParams({ - name: request.name ?? '', - }); + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); return this.operationsClient.listOperationsAsync(request, options); } /** @@ -1602,7 +2100,7 @@ export class CloudRedisClient { * await client.cancelOperation({name: ''}); * ``` */ - cancelOperation( + cancelOperation( request: protos.google.longrunning.CancelOperationRequest, optionsOrCallback?: | gax.CallOptions @@ -1615,22 +2113,22 @@ export class CloudRedisClient { protos.google.longrunning.CancelOperationRequest, protos.google.protobuf.Empty, {} | undefined | null - > + >, ): Promise { - let options: gax.CallOptions; - if (typeof optionsOrCallback === 'function' && callback === undefined) { - callback = optionsOrCallback; - options = {}; - } else { - options = optionsOrCallback as gax.CallOptions; - } - options = options || {}; - options.otherArgs = options.otherArgs || {}; - options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers['x-goog-request-params'] = - this._gaxModule.routingHeader.fromParams({ - name: request.name ?? '', - }); + let options: gax.CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as gax.CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); return this.operationsClient.cancelOperation(request, options, callback); } /** @@ -1671,22 +2169,22 @@ export class CloudRedisClient { protos.google.protobuf.Empty, protos.google.longrunning.DeleteOperationRequest, {} | null | undefined - > + >, ): Promise { - let options: gax.CallOptions; - if (typeof optionsOrCallback === 'function' && callback === undefined) { - callback = optionsOrCallback; - options = {}; - } else { - options = optionsOrCallback as gax.CallOptions; - } - options = options || {}; - options.otherArgs = options.otherArgs || {}; - options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers['x-goog-request-params'] = - this._gaxModule.routingHeader.fromParams({ - name: request.name ?? '', - }); + let options: gax.CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as gax.CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); return this.operationsClient.deleteOperation(request, options, callback); } @@ -1702,7 +2200,7 @@ export class CloudRedisClient { * @param {string} instance * @returns {string} Resource name string. */ - instancePath(project:string,location:string,instance:string) { + instancePath(project: string, location: string, instance: string) { return this.pathTemplates.instancePathTemplate.render({ project: project, location: location, @@ -1750,7 +2248,7 @@ export class CloudRedisClient { * @param {string} location * @returns {string} Resource name string. */ - locationPath(project:string,location:string) { + locationPath(project: string, location: string) { return this.pathTemplates.locationPathTemplate.render({ project: project, location: location, @@ -1787,7 +2285,7 @@ export class CloudRedisClient { */ close(): Promise { if (this.cloudRedisStub && !this._terminated) { - return this.cloudRedisStub.then(stub => { + return this.cloudRedisStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -1796,4 +2294,4 @@ export class CloudRedisClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/core/generator/gapic-generator-typescript/baselines/redis-esm/esm/src/v1beta1/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/redis-esm/esm/src/v1beta1/index.ts.baseline index d802d85292de..8d3af0c2cece 100644 --- a/core/generator/gapic-generator-typescript/baselines/redis-esm/esm/src/v1beta1/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/redis-esm/esm/src/v1beta1/index.ts.baseline @@ -16,4 +16,4 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -export {CloudRedisClient} from './cloud_redis_client.js'; +export { CloudRedisClient } from './cloud_redis_client.js'; diff --git a/core/generator/gapic-generator-typescript/baselines/redis-esm/esm/system-test/fixtures/sample/src/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/redis-esm/esm/system-test/fixtures/sample/src/index.ts.baseline index d585e083599a..aaf4a0f7ec41 100644 --- a/core/generator/gapic-generator-typescript/baselines/redis-esm/esm/system-test/fixtures/sample/src/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/redis-esm/esm/system-test/fixtures/sample/src/index.ts.baseline @@ -17,7 +17,7 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -import {CloudRedisClient} from 'redis'; +import { CloudRedisClient } from 'redis'; // check that the client class type name can be used function doStuffWithCloudRedisClient(client: CloudRedisClient) { diff --git a/core/generator/gapic-generator-typescript/baselines/redis-esm/esm/system-test/install.ts.baseline b/core/generator/gapic-generator-typescript/baselines/redis-esm/esm/system-test/install.ts.baseline index e079c4fa1101..d109fdd8c97f 100644 --- a/core/generator/gapic-generator-typescript/baselines/redis-esm/esm/system-test/install.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/redis-esm/esm/system-test/install.ts.baseline @@ -16,40 +16,45 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -import {packNTest} from 'pack-n-play'; -import {readFileSync} from 'fs'; -import {describe, it} from 'mocha'; +import { packNTest } from 'pack-n-play'; +import { readFileSync } from 'fs'; +import { describe, it } from 'mocha'; describe('📦 pack-n-play test', () => { - it('TypeScript', async function() { + it('TypeScript', async function () { this.timeout(300000); await packNTest({ packageDir: process.cwd(), sample: { description: 'TypeScript user can use the type definitions', - ts: readFileSync('./esm/system-test/fixtures/sample/src/index.ts').toString() - } + ts: readFileSync( + './esm/system-test/fixtures/sample/src/index.ts', + ).toString(), + }, }); }); - it('ESM module', async function() { + it('ESM module', async function () { this.timeout(300000); await packNTest({ sample: { description: 'Should be able to import using ESM', - esm: readFileSync('./esm/system-test/fixtures/sample/src/index.js').toString(), + esm: readFileSync( + './esm/system-test/fixtures/sample/src/index.js', + ).toString(), }, }); }); - it('CJS module', async function() { + it('CJS module', async function () { this.timeout(300000); await packNTest({ sample: { description: 'Should be able to import using CJS', - cjs: readFileSync('./esm/system-test/fixtures/sample/src/index.cjs').toString(), + cjs: readFileSync( + './esm/system-test/fixtures/sample/src/index.cjs', + ).toString(), }, }); }); - }); diff --git a/core/generator/gapic-generator-typescript/baselines/redis-esm/esm/test/gapic_cloud_redis_v1beta1.ts.baseline b/core/generator/gapic-generator-typescript/baselines/redis-esm/esm/test/gapic_cloud_redis_v1beta1.ts.baseline index b3f5f20a0fa3..082a88dd1e90 100644 --- a/core/generator/gapic-generator-typescript/baselines/redis-esm/esm/test/gapic_cloud_redis_v1beta1.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/redis-esm/esm/test/gapic_cloud_redis_v1beta1.ts.baseline @@ -20,16 +20,16 @@ import * as protos from '../../protos/protos.js'; import assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as cloudredisModule from '../src/index.js'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; -import {protobuf, LROperation, operationsProtos} from 'google-gax'; +import { protobuf, LROperation, operationsProtos } from 'google-gax'; import fs from 'fs'; import path from 'path'; -import {fileURLToPath} from 'url'; +import { fileURLToPath } from 'url'; // @ts-ignore const dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -37,1873 +37,2361 @@ const dirname = path.dirname(fileURLToPath(import.meta.url)); // to fill in default values for request objects const root = protobuf.Root.fromJSON( JSON.parse( - fs.readFileSync(path.join(dirname, '..', '..', 'protos/protos.json'), 'utf8') - )) + fs.readFileSync( + path.join(dirname, '..', '..', 'protos/protos.json'), + 'utf8', + ), + ), +); // eslint-disable-next-line @typescript-eslint/no-unused-vars function getTypeDefaultValue(typeName: string, fields: string[]) { - let type = root.lookupType(typeName) as protobuf.Type; - for (const field of fields.slice(0, -1)) { - type = type?.fields[field]?.resolvedType as protobuf.Type; - } - return type?.fields[fields[fields.length - 1]]?.defaultValue ?? null; + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type?.fields[field]?.resolvedType as protobuf.Type; + } + return type?.fields[fields[fields.length - 1]]?.defaultValue ?? null; } function generateSampleMessage(instance: T) { - const filledObject = (instance.constructor as typeof protobuf.Message) - .toObject(instance as protobuf.Message, {defaults: true}); - return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, { defaults: true }); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; } function stubSimpleCall(response?: ResponseType, error?: Error) { - return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); } -function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { - return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +function stubSimpleCallWithCallback( + response?: ResponseType, + error?: Error, +) { + return error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); } -function stubLongRunningCall(response?: ResponseType, callError?: Error, lroError?: Error) { - const innerStub = lroError ? sinon.stub().rejects(lroError) : sinon.stub().resolves([response]); - const mockOperation = { - promise: innerStub, - }; - return callError ? sinon.stub().rejects(callError) : sinon.stub().resolves([mockOperation]); +function stubLongRunningCall( + response?: ResponseType, + callError?: Error, + lroError?: Error, +) { + const innerStub = lroError + ? sinon.stub().rejects(lroError) + : sinon.stub().resolves([response]); + const mockOperation = { + promise: innerStub, + }; + return callError + ? sinon.stub().rejects(callError) + : sinon.stub().resolves([mockOperation]); } -function stubLongRunningCallWithCallback(response?: ResponseType, callError?: Error, lroError?: Error) { - const innerStub = lroError ? sinon.stub().rejects(lroError) : sinon.stub().resolves([response]); - const mockOperation = { - promise: innerStub, - }; - return callError ? sinon.stub().callsArgWith(2, callError) : sinon.stub().callsArgWith(2, null, mockOperation); +function stubLongRunningCallWithCallback( + response?: ResponseType, + callError?: Error, + lroError?: Error, +) { + const innerStub = lroError + ? sinon.stub().rejects(lroError) + : sinon.stub().resolves([response]); + const mockOperation = { + promise: innerStub, + }; + return callError + ? sinon.stub().callsArgWith(2, callError) + : sinon.stub().callsArgWith(2, null, mockOperation); } -function stubPageStreamingCall(responses?: ResponseType[], error?: Error) { - const pagingStub = sinon.stub(); - if (responses) { - for (let i = 0; i < responses.length; ++i) { - pagingStub.onCall(i).callsArgWith(2, null, responses[i]); - } +function stubPageStreamingCall( + responses?: ResponseType[], + error?: Error, +) { + const pagingStub = sinon.stub(); + if (responses) { + for (let i = 0; i < responses.length; ++i) { + pagingStub.onCall(i).callsArgWith(2, null, responses[i]); } - const transformStub = error ? sinon.stub().callsArgWith(2, error) : pagingStub; - const mockStream = new PassThrough({ - objectMode: true, - transform: transformStub, - }); - // trigger as many responses as needed - if (responses) { - for (let i = 0; i < responses.length; ++i) { - setImmediate(() => { mockStream.write({}); }); - } - setImmediate(() => { mockStream.end(); }); - } else { - setImmediate(() => { mockStream.write({}); }); - setImmediate(() => { mockStream.end(); }); + } + const transformStub = error + ? sinon.stub().callsArgWith(2, error) + : pagingStub; + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + // trigger as many responses as needed + if (responses) { + for (let i = 0; i < responses.length; ++i) { + setImmediate(() => { + mockStream.write({}); + }); } - return sinon.stub().returns(mockStream); + setImmediate(() => { + mockStream.end(); + }); + } else { + setImmediate(() => { + mockStream.write({}); + }); + setImmediate(() => { + mockStream.end(); + }); + } + return sinon.stub().returns(mockStream); } -function stubAsyncIterationCall(responses?: ResponseType[], error?: Error) { - let counter = 0; - const asyncIterable = { - [Symbol.asyncIterator]() { - return { - async next() { - if (error) { - return Promise.reject(error); - } - if (counter >= responses!.length) { - return Promise.resolve({done: true, value: undefined}); - } - return Promise.resolve({done: false, value: responses![counter++]}); - } - }; - } - }; - return sinon.stub().returns(asyncIterable); +function stubAsyncIterationCall( + responses?: ResponseType[], + error?: Error, +) { + let counter = 0; + const asyncIterable = { + [Symbol.asyncIterator]() { + return { + async next() { + if (error) { + return Promise.reject(error); + } + if (counter >= responses!.length) { + return Promise.resolve({ done: true, value: undefined }); + } + return Promise.resolve({ done: false, value: responses![counter++] }); + }, + }; + }, + }; + return sinon.stub().returns(asyncIterable); } describe('v1beta1.CloudRedisClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'redis.googleapis.com'); - }); - - it('has universeDomain', () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); - - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - it('throws DeprecationWarning if static servicePath is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const servicePath = cloudredisModule.v1beta1.CloudRedisClient.servicePath; - assert.strictEqual(servicePath, 'redis.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = cloudredisModule.v1beta1.CloudRedisClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'redis.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'redis.example.com'); - }); - - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'redis.example.com'); - }); - - if (typeof process === 'object' && 'env' in process) { - describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { - it('sets apiEndpoint from environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new cloudredisModule.v1beta1.CloudRedisClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'redis.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - - it('value configured in code has priority over environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new cloudredisModule.v1beta1.CloudRedisClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'redis.configured.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { new cloudredisModule.v1beta1.CloudRedisClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); - - it('has port', () => { - const port = cloudredisModule.v1beta1.CloudRedisClient.port; - assert(port); - assert(typeof port === 'number'); - }); - - it('should create a client with no option', () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient(); - assert(client); - }); - - it('should create a client with gRPC fallback', () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - fallback: true, - }); - assert(client); - }); - - it('has initialize method and supports deferred initialization', async () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.cloudRedisStub, undefined); - await client.initialize(); - assert(client.cloudRedisStub); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'redis.googleapis.com'); + }); - it('has close method for the initialized client', done => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.cloudRedisStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('has universeDomain', () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - it('has close method for the non-initialized client', done => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.cloudRedisStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = + cloudredisModule.v1beta1.CloudRedisClient.servicePath; + assert.strictEqual(servicePath, 'redis.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + cloudredisModule.v1beta1.CloudRedisClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'redis.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + universeDomain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'redis.example.com'); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); - }); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + universe_domain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'redis.example.com'); + }); - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId((err?: Error|null, projectId?: string|null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } - }); - }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); + if (typeof process === 'object' && 'env' in process) { + describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { + it('sets apiEndpoint from environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new cloudredisModule.v1beta1.CloudRedisClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'redis.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } + }); + + it('value configured in code has priority over environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + universeDomain: 'configured.example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'redis.configured.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } + }); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new cloudredisModule.v1beta1.CloudRedisClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); }); - describe('getInstance', () => { - it('invokes getInstance without error', async () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.redis.v1beta1.GetInstanceRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.redis.v1beta1.GetInstanceRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.redis.v1beta1.Instance() - ); - client.innerApiCalls.getInstance = stubSimpleCall(expectedResponse); - const [response] = await client.getInstance(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getInstance as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getInstance as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has port', () => { + const port = cloudredisModule.v1beta1.CloudRedisClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('invokes getInstance without error using callback', async () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.redis.v1beta1.GetInstanceRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.redis.v1beta1.GetInstanceRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.redis.v1beta1.Instance() - ); - client.innerApiCalls.getInstance = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getInstance( - request, - (err?: Error|null, result?: protos.google.cloud.redis.v1beta1.IInstance|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getInstance as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getInstance as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('should create a client with no option', () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient(); + assert(client); + }); - it('invokes getInstance with error', async () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.redis.v1beta1.GetInstanceRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.redis.v1beta1.GetInstanceRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getInstance = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getInstance(request), expectedError); - const actualRequest = (client.innerApiCalls.getInstance as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getInstance as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('should create a client with gRPC fallback', () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + fallback: true, + }); + assert(client); + }); - it('invokes getInstance with closed client', async () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.redis.v1beta1.GetInstanceRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.redis.v1beta1.GetInstanceRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getInstance(request), expectedError); - }); + it('has initialize method and supports deferred initialization', async () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.cloudRedisStub, undefined); + await client.initialize(); + assert(client.cloudRedisStub); }); - describe('createInstance', () => { - it('invokes createInstance without error', async () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.redis.v1beta1.CreateInstanceRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.redis.v1beta1.CreateInstanceRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.createInstance = stubLongRunningCall(expectedResponse); - const [operation] = await client.createInstance(request); - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createInstance as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createInstance as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('has close method for the initialized client', (done) => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.cloudRedisStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes createInstance without error using callback', async () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.redis.v1beta1.CreateInstanceRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.redis.v1beta1.CreateInstanceRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.createInstance = stubLongRunningCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createInstance( - request, - (err?: Error|null, - result?: LROperation|null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const operation = await promise as LROperation; - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createInstance as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createInstance as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('has close method for the non-initialized client', (done) => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.cloudRedisStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes createInstance with call error', async () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.redis.v1beta1.CreateInstanceRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.redis.v1beta1.CreateInstanceRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createInstance = stubLongRunningCall(undefined, expectedError); - await assert.rejects(client.createInstance(request), expectedError); - const actualRequest = (client.innerApiCalls.createInstance as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createInstance as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + }); - it('invokes createInstance with LRO error', async () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.redis.v1beta1.CreateInstanceRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.redis.v1beta1.CreateInstanceRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createInstance = stubLongRunningCall(undefined, undefined, expectedError); - const [operation] = await client.createInstance(request); - await assert.rejects(operation.promise(), expectedError); - const actualRequest = (client.innerApiCalls.createInstance as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createInstance as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } + }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + }); + + describe('getInstance', () => { + it('invokes getInstance without error', async () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.redis.v1beta1.GetInstanceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.redis.v1beta1.GetInstanceRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.redis.v1beta1.Instance(), + ); + client.innerApiCalls.getInstance = stubSimpleCall(expectedResponse); + const [response] = await client.getInstance(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getInstance as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getInstance as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkCreateInstanceProgress without error', async () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedResponse = generateSampleMessage( - new operationsProtos.google.longrunning.Operation() - ); - expectedResponse.name = 'test'; - expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; - expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')} - - client.operationsClient.getOperation = stubSimpleCall(expectedResponse); - const decodedOperation = await client.checkCreateInstanceProgress(expectedResponse.name); - assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); - assert(decodedOperation.metadata); - assert((client.operationsClient.getOperation as SinonStub).getCall(0)); - }); + it('invokes getInstance without error using callback', async () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.redis.v1beta1.GetInstanceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.redis.v1beta1.GetInstanceRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.redis.v1beta1.Instance(), + ); + client.innerApiCalls.getInstance = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getInstance( + request, + ( + err?: Error | null, + result?: protos.google.cloud.redis.v1beta1.IInstance | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getInstance as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getInstance as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkCreateInstanceProgress with error', async () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedError = new Error('expected'); - - client.operationsClient.getOperation = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.checkCreateInstanceProgress(''), expectedError); - assert((client.operationsClient.getOperation as SinonStub) - .getCall(0)); - }); + it('invokes getInstance with error', async () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.redis.v1beta1.GetInstanceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.redis.v1beta1.GetInstanceRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getInstance = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getInstance(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getInstance as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getInstance as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('updateInstance', () => { - it('invokes updateInstance without error', async () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.redis.v1beta1.UpdateInstanceRequest() - ); - request.instance ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.redis.v1beta1.UpdateInstanceRequest', ['instance', 'name']); - request.instance.name = defaultValue1; - const expectedHeaderRequestParams = `instance.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.updateInstance = stubLongRunningCall(expectedResponse); - const [operation] = await client.updateInstance(request); - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateInstance as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateInstance as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getInstance with closed client', async () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.redis.v1beta1.GetInstanceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.redis.v1beta1.GetInstanceRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getInstance(request), expectedError); + }); + }); + + describe('createInstance', () => { + it('invokes createInstance without error', async () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.redis.v1beta1.CreateInstanceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.redis.v1beta1.CreateInstanceRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.createInstance = + stubLongRunningCall(expectedResponse); + const [operation] = await client.createInstance(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createInstance as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createInstance as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateInstance without error using callback', async () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.redis.v1beta1.UpdateInstanceRequest() - ); - request.instance ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.redis.v1beta1.UpdateInstanceRequest', ['instance', 'name']); - request.instance.name = defaultValue1; - const expectedHeaderRequestParams = `instance.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.updateInstance = stubLongRunningCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateInstance( - request, - (err?: Error|null, - result?: LROperation|null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const operation = await promise as LROperation; - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateInstance as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateInstance as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createInstance without error using callback', async () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.redis.v1beta1.CreateInstanceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.redis.v1beta1.CreateInstanceRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.createInstance = + stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createInstance( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.cloud.redis.v1beta1.IInstance, + protos.google.protobuf.IAny + > | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const operation = (await promise) as LROperation< + protos.google.cloud.redis.v1beta1.IInstance, + protos.google.protobuf.IAny + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createInstance as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createInstance as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateInstance with call error', async () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.redis.v1beta1.UpdateInstanceRequest() - ); - request.instance ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.redis.v1beta1.UpdateInstanceRequest', ['instance', 'name']); - request.instance.name = defaultValue1; - const expectedHeaderRequestParams = `instance.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateInstance = stubLongRunningCall(undefined, expectedError); - await assert.rejects(client.updateInstance(request), expectedError); - const actualRequest = (client.innerApiCalls.updateInstance as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateInstance as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createInstance with call error', async () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.redis.v1beta1.CreateInstanceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.redis.v1beta1.CreateInstanceRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createInstance = stubLongRunningCall( + undefined, + expectedError, + ); + await assert.rejects(client.createInstance(request), expectedError); + const actualRequest = ( + client.innerApiCalls.createInstance as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createInstance as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateInstance with LRO error', async () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.redis.v1beta1.UpdateInstanceRequest() - ); - request.instance ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.redis.v1beta1.UpdateInstanceRequest', ['instance', 'name']); - request.instance.name = defaultValue1; - const expectedHeaderRequestParams = `instance.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateInstance = stubLongRunningCall(undefined, undefined, expectedError); - const [operation] = await client.updateInstance(request); - await assert.rejects(operation.promise(), expectedError); - const actualRequest = (client.innerApiCalls.updateInstance as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateInstance as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createInstance with LRO error', async () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.redis.v1beta1.CreateInstanceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.redis.v1beta1.CreateInstanceRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createInstance = stubLongRunningCall( + undefined, + undefined, + expectedError, + ); + const [operation] = await client.createInstance(request); + await assert.rejects(operation.promise(), expectedError); + const actualRequest = ( + client.innerApiCalls.createInstance as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createInstance as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkUpdateInstanceProgress without error', async () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedResponse = generateSampleMessage( - new operationsProtos.google.longrunning.Operation() - ); - expectedResponse.name = 'test'; - expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; - expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')} - - client.operationsClient.getOperation = stubSimpleCall(expectedResponse); - const decodedOperation = await client.checkUpdateInstanceProgress(expectedResponse.name); - assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); - assert(decodedOperation.metadata); - assert((client.operationsClient.getOperation as SinonStub).getCall(0)); - }); + it('invokes checkCreateInstanceProgress without error', async () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation(), + ); + expectedResponse.name = 'test'; + expectedResponse.response = { type_url: 'url', value: Buffer.from('') }; + expectedResponse.metadata = { type_url: 'url', value: Buffer.from('') }; + + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const decodedOperation = await client.checkCreateInstanceProgress( + expectedResponse.name, + ); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); - it('invokes checkUpdateInstanceProgress with error', async () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedError = new Error('expected'); - - client.operationsClient.getOperation = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.checkUpdateInstanceProgress(''), expectedError); - assert((client.operationsClient.getOperation as SinonStub) - .getCall(0)); - }); + it('invokes checkCreateInstanceProgress with error', async () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const expectedError = new Error('expected'); + + client.operationsClient.getOperation = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.checkCreateInstanceProgress(''), + expectedError, + ); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + }); + + describe('updateInstance', () => { + it('invokes updateInstance without error', async () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.redis.v1beta1.UpdateInstanceRequest(), + ); + request.instance ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.redis.v1beta1.UpdateInstanceRequest', + ['instance', 'name'], + ); + request.instance.name = defaultValue1; + const expectedHeaderRequestParams = `instance.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.updateInstance = + stubLongRunningCall(expectedResponse); + const [operation] = await client.updateInstance(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateInstance as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateInstance as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('importInstance', () => { - it('invokes importInstance without error', async () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.redis.v1beta1.ImportInstanceRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.redis.v1beta1.ImportInstanceRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.importInstance = stubLongRunningCall(expectedResponse); - const [operation] = await client.importInstance(request); - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.importInstance as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.importInstance as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateInstance without error using callback', async () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.redis.v1beta1.UpdateInstanceRequest(), + ); + request.instance ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.redis.v1beta1.UpdateInstanceRequest', + ['instance', 'name'], + ); + request.instance.name = defaultValue1; + const expectedHeaderRequestParams = `instance.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.updateInstance = + stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateInstance( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.cloud.redis.v1beta1.IInstance, + protos.google.protobuf.IAny + > | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const operation = (await promise) as LROperation< + protos.google.cloud.redis.v1beta1.IInstance, + protos.google.protobuf.IAny + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateInstance as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateInstance as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes importInstance without error using callback', async () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.redis.v1beta1.ImportInstanceRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.redis.v1beta1.ImportInstanceRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.importInstance = stubLongRunningCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.importInstance( - request, - (err?: Error|null, - result?: LROperation|null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const operation = await promise as LROperation; - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.importInstance as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.importInstance as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateInstance with call error', async () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.redis.v1beta1.UpdateInstanceRequest(), + ); + request.instance ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.redis.v1beta1.UpdateInstanceRequest', + ['instance', 'name'], + ); + request.instance.name = defaultValue1; + const expectedHeaderRequestParams = `instance.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateInstance = stubLongRunningCall( + undefined, + expectedError, + ); + await assert.rejects(client.updateInstance(request), expectedError); + const actualRequest = ( + client.innerApiCalls.updateInstance as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateInstance as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes importInstance with call error', async () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.redis.v1beta1.ImportInstanceRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.redis.v1beta1.ImportInstanceRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.importInstance = stubLongRunningCall(undefined, expectedError); - await assert.rejects(client.importInstance(request), expectedError); - const actualRequest = (client.innerApiCalls.importInstance as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.importInstance as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateInstance with LRO error', async () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.redis.v1beta1.UpdateInstanceRequest(), + ); + request.instance ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.redis.v1beta1.UpdateInstanceRequest', + ['instance', 'name'], + ); + request.instance.name = defaultValue1; + const expectedHeaderRequestParams = `instance.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateInstance = stubLongRunningCall( + undefined, + undefined, + expectedError, + ); + const [operation] = await client.updateInstance(request); + await assert.rejects(operation.promise(), expectedError); + const actualRequest = ( + client.innerApiCalls.updateInstance as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateInstance as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes importInstance with LRO error', async () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.redis.v1beta1.ImportInstanceRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.redis.v1beta1.ImportInstanceRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.importInstance = stubLongRunningCall(undefined, undefined, expectedError); - const [operation] = await client.importInstance(request); - await assert.rejects(operation.promise(), expectedError); - const actualRequest = (client.innerApiCalls.importInstance as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.importInstance as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes checkUpdateInstanceProgress without error', async () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation(), + ); + expectedResponse.name = 'test'; + expectedResponse.response = { type_url: 'url', value: Buffer.from('') }; + expectedResponse.metadata = { type_url: 'url', value: Buffer.from('') }; + + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const decodedOperation = await client.checkUpdateInstanceProgress( + expectedResponse.name, + ); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); - it('invokes checkImportInstanceProgress without error', async () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedResponse = generateSampleMessage( - new operationsProtos.google.longrunning.Operation() - ); - expectedResponse.name = 'test'; - expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; - expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')} - - client.operationsClient.getOperation = stubSimpleCall(expectedResponse); - const decodedOperation = await client.checkImportInstanceProgress(expectedResponse.name); - assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); - assert(decodedOperation.metadata); - assert((client.operationsClient.getOperation as SinonStub).getCall(0)); - }); + it('invokes checkUpdateInstanceProgress with error', async () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const expectedError = new Error('expected'); + + client.operationsClient.getOperation = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.checkUpdateInstanceProgress(''), + expectedError, + ); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + }); + + describe('importInstance', () => { + it('invokes importInstance without error', async () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.redis.v1beta1.ImportInstanceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.redis.v1beta1.ImportInstanceRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.importInstance = + stubLongRunningCall(expectedResponse); + const [operation] = await client.importInstance(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.importInstance as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.importInstance as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkImportInstanceProgress with error', async () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedError = new Error('expected'); - - client.operationsClient.getOperation = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.checkImportInstanceProgress(''), expectedError); - assert((client.operationsClient.getOperation as SinonStub) - .getCall(0)); - }); + it('invokes importInstance without error using callback', async () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.redis.v1beta1.ImportInstanceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.redis.v1beta1.ImportInstanceRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.importInstance = + stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.importInstance( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.cloud.redis.v1beta1.IInstance, + protos.google.protobuf.IAny + > | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const operation = (await promise) as LROperation< + protos.google.cloud.redis.v1beta1.IInstance, + protos.google.protobuf.IAny + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.importInstance as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.importInstance as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('exportInstance', () => { - it('invokes exportInstance without error', async () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.redis.v1beta1.ExportInstanceRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.redis.v1beta1.ExportInstanceRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.exportInstance = stubLongRunningCall(expectedResponse); - const [operation] = await client.exportInstance(request); - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.exportInstance as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.exportInstance as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes importInstance with call error', async () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.redis.v1beta1.ImportInstanceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.redis.v1beta1.ImportInstanceRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.importInstance = stubLongRunningCall( + undefined, + expectedError, + ); + await assert.rejects(client.importInstance(request), expectedError); + const actualRequest = ( + client.innerApiCalls.importInstance as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.importInstance as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes exportInstance without error using callback', async () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.redis.v1beta1.ExportInstanceRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.redis.v1beta1.ExportInstanceRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.exportInstance = stubLongRunningCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.exportInstance( - request, - (err?: Error|null, - result?: LROperation|null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const operation = await promise as LROperation; - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.exportInstance as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.exportInstance as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes importInstance with LRO error', async () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.redis.v1beta1.ImportInstanceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.redis.v1beta1.ImportInstanceRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.importInstance = stubLongRunningCall( + undefined, + undefined, + expectedError, + ); + const [operation] = await client.importInstance(request); + await assert.rejects(operation.promise(), expectedError); + const actualRequest = ( + client.innerApiCalls.importInstance as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.importInstance as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes exportInstance with call error', async () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.redis.v1beta1.ExportInstanceRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.redis.v1beta1.ExportInstanceRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.exportInstance = stubLongRunningCall(undefined, expectedError); - await assert.rejects(client.exportInstance(request), expectedError); - const actualRequest = (client.innerApiCalls.exportInstance as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.exportInstance as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes checkImportInstanceProgress without error', async () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation(), + ); + expectedResponse.name = 'test'; + expectedResponse.response = { type_url: 'url', value: Buffer.from('') }; + expectedResponse.metadata = { type_url: 'url', value: Buffer.from('') }; + + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const decodedOperation = await client.checkImportInstanceProgress( + expectedResponse.name, + ); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); - it('invokes exportInstance with LRO error', async () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.redis.v1beta1.ExportInstanceRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.redis.v1beta1.ExportInstanceRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.exportInstance = stubLongRunningCall(undefined, undefined, expectedError); - const [operation] = await client.exportInstance(request); - await assert.rejects(operation.promise(), expectedError); - const actualRequest = (client.innerApiCalls.exportInstance as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.exportInstance as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes checkImportInstanceProgress with error', async () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const expectedError = new Error('expected'); + + client.operationsClient.getOperation = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.checkImportInstanceProgress(''), + expectedError, + ); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + }); + + describe('exportInstance', () => { + it('invokes exportInstance without error', async () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.redis.v1beta1.ExportInstanceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.redis.v1beta1.ExportInstanceRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.exportInstance = + stubLongRunningCall(expectedResponse); + const [operation] = await client.exportInstance(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.exportInstance as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.exportInstance as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkExportInstanceProgress without error', async () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedResponse = generateSampleMessage( - new operationsProtos.google.longrunning.Operation() - ); - expectedResponse.name = 'test'; - expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; - expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')} - - client.operationsClient.getOperation = stubSimpleCall(expectedResponse); - const decodedOperation = await client.checkExportInstanceProgress(expectedResponse.name); - assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); - assert(decodedOperation.metadata); - assert((client.operationsClient.getOperation as SinonStub).getCall(0)); - }); + it('invokes exportInstance without error using callback', async () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.redis.v1beta1.ExportInstanceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.redis.v1beta1.ExportInstanceRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.exportInstance = + stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.exportInstance( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.cloud.redis.v1beta1.IInstance, + protos.google.protobuf.IAny + > | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const operation = (await promise) as LROperation< + protos.google.cloud.redis.v1beta1.IInstance, + protos.google.protobuf.IAny + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.exportInstance as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.exportInstance as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkExportInstanceProgress with error', async () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedError = new Error('expected'); - - client.operationsClient.getOperation = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.checkExportInstanceProgress(''), expectedError); - assert((client.operationsClient.getOperation as SinonStub) - .getCall(0)); - }); + it('invokes exportInstance with call error', async () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.redis.v1beta1.ExportInstanceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.redis.v1beta1.ExportInstanceRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.exportInstance = stubLongRunningCall( + undefined, + expectedError, + ); + await assert.rejects(client.exportInstance(request), expectedError); + const actualRequest = ( + client.innerApiCalls.exportInstance as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.exportInstance as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('failoverInstance', () => { - it('invokes failoverInstance without error', async () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.redis.v1beta1.FailoverInstanceRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.redis.v1beta1.FailoverInstanceRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.failoverInstance = stubLongRunningCall(expectedResponse); - const [operation] = await client.failoverInstance(request); - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.failoverInstance as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.failoverInstance as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes exportInstance with LRO error', async () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.redis.v1beta1.ExportInstanceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.redis.v1beta1.ExportInstanceRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.exportInstance = stubLongRunningCall( + undefined, + undefined, + expectedError, + ); + const [operation] = await client.exportInstance(request); + await assert.rejects(operation.promise(), expectedError); + const actualRequest = ( + client.innerApiCalls.exportInstance as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.exportInstance as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes failoverInstance without error using callback', async () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.redis.v1beta1.FailoverInstanceRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.redis.v1beta1.FailoverInstanceRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.failoverInstance = stubLongRunningCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.failoverInstance( - request, - (err?: Error|null, - result?: LROperation|null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const operation = await promise as LROperation; - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.failoverInstance as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.failoverInstance as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes checkExportInstanceProgress without error', async () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation(), + ); + expectedResponse.name = 'test'; + expectedResponse.response = { type_url: 'url', value: Buffer.from('') }; + expectedResponse.metadata = { type_url: 'url', value: Buffer.from('') }; + + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const decodedOperation = await client.checkExportInstanceProgress( + expectedResponse.name, + ); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); - it('invokes failoverInstance with call error', async () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.redis.v1beta1.FailoverInstanceRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.redis.v1beta1.FailoverInstanceRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.failoverInstance = stubLongRunningCall(undefined, expectedError); - await assert.rejects(client.failoverInstance(request), expectedError); - const actualRequest = (client.innerApiCalls.failoverInstance as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.failoverInstance as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes checkExportInstanceProgress with error', async () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const expectedError = new Error('expected'); + + client.operationsClient.getOperation = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.checkExportInstanceProgress(''), + expectedError, + ); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + }); + + describe('failoverInstance', () => { + it('invokes failoverInstance without error', async () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.redis.v1beta1.FailoverInstanceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.redis.v1beta1.FailoverInstanceRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.failoverInstance = + stubLongRunningCall(expectedResponse); + const [operation] = await client.failoverInstance(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.failoverInstance as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.failoverInstance as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes failoverInstance with LRO error', async () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.redis.v1beta1.FailoverInstanceRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.redis.v1beta1.FailoverInstanceRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.failoverInstance = stubLongRunningCall(undefined, undefined, expectedError); - const [operation] = await client.failoverInstance(request); - await assert.rejects(operation.promise(), expectedError); - const actualRequest = (client.innerApiCalls.failoverInstance as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.failoverInstance as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes failoverInstance without error using callback', async () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.redis.v1beta1.FailoverInstanceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.redis.v1beta1.FailoverInstanceRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.failoverInstance = + stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.failoverInstance( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.cloud.redis.v1beta1.IInstance, + protos.google.protobuf.IAny + > | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const operation = (await promise) as LROperation< + protos.google.cloud.redis.v1beta1.IInstance, + protos.google.protobuf.IAny + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.failoverInstance as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.failoverInstance as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkFailoverInstanceProgress without error', async () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedResponse = generateSampleMessage( - new operationsProtos.google.longrunning.Operation() - ); - expectedResponse.name = 'test'; - expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; - expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')} - - client.operationsClient.getOperation = stubSimpleCall(expectedResponse); - const decodedOperation = await client.checkFailoverInstanceProgress(expectedResponse.name); - assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); - assert(decodedOperation.metadata); - assert((client.operationsClient.getOperation as SinonStub).getCall(0)); - }); + it('invokes failoverInstance with call error', async () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.redis.v1beta1.FailoverInstanceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.redis.v1beta1.FailoverInstanceRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.failoverInstance = stubLongRunningCall( + undefined, + expectedError, + ); + await assert.rejects(client.failoverInstance(request), expectedError); + const actualRequest = ( + client.innerApiCalls.failoverInstance as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.failoverInstance as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkFailoverInstanceProgress with error', async () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedError = new Error('expected'); - - client.operationsClient.getOperation = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.checkFailoverInstanceProgress(''), expectedError); - assert((client.operationsClient.getOperation as SinonStub) - .getCall(0)); - }); + it('invokes failoverInstance with LRO error', async () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.redis.v1beta1.FailoverInstanceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.redis.v1beta1.FailoverInstanceRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.failoverInstance = stubLongRunningCall( + undefined, + undefined, + expectedError, + ); + const [operation] = await client.failoverInstance(request); + await assert.rejects(operation.promise(), expectedError); + const actualRequest = ( + client.innerApiCalls.failoverInstance as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.failoverInstance as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('deleteInstance', () => { - it('invokes deleteInstance without error', async () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.redis.v1beta1.DeleteInstanceRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.redis.v1beta1.DeleteInstanceRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.deleteInstance = stubLongRunningCall(expectedResponse); - const [operation] = await client.deleteInstance(request); - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteInstance as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteInstance as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes checkFailoverInstanceProgress without error', async () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation(), + ); + expectedResponse.name = 'test'; + expectedResponse.response = { type_url: 'url', value: Buffer.from('') }; + expectedResponse.metadata = { type_url: 'url', value: Buffer.from('') }; + + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const decodedOperation = await client.checkFailoverInstanceProgress( + expectedResponse.name, + ); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); - it('invokes deleteInstance without error using callback', async () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.redis.v1beta1.DeleteInstanceRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.redis.v1beta1.DeleteInstanceRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.deleteInstance = stubLongRunningCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteInstance( - request, - (err?: Error|null, - result?: LROperation|null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const operation = await promise as LROperation; - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteInstance as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteInstance as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes checkFailoverInstanceProgress with error', async () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const expectedError = new Error('expected'); + + client.operationsClient.getOperation = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.checkFailoverInstanceProgress(''), + expectedError, + ); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + }); + + describe('deleteInstance', () => { + it('invokes deleteInstance without error', async () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.redis.v1beta1.DeleteInstanceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.redis.v1beta1.DeleteInstanceRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.deleteInstance = + stubLongRunningCall(expectedResponse); + const [operation] = await client.deleteInstance(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteInstance as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteInstance as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteInstance with call error', async () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.redis.v1beta1.DeleteInstanceRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.redis.v1beta1.DeleteInstanceRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteInstance = stubLongRunningCall(undefined, expectedError); - await assert.rejects(client.deleteInstance(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteInstance as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteInstance as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteInstance without error using callback', async () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.redis.v1beta1.DeleteInstanceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.redis.v1beta1.DeleteInstanceRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.deleteInstance = + stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteInstance( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.protobuf.IEmpty, + protos.google.protobuf.IAny + > | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const operation = (await promise) as LROperation< + protos.google.protobuf.IEmpty, + protos.google.protobuf.IAny + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteInstance as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteInstance as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteInstance with LRO error', async () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.redis.v1beta1.DeleteInstanceRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.redis.v1beta1.DeleteInstanceRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteInstance = stubLongRunningCall(undefined, undefined, expectedError); - const [operation] = await client.deleteInstance(request); - await assert.rejects(operation.promise(), expectedError); - const actualRequest = (client.innerApiCalls.deleteInstance as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteInstance as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteInstance with call error', async () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.redis.v1beta1.DeleteInstanceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.redis.v1beta1.DeleteInstanceRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteInstance = stubLongRunningCall( + undefined, + expectedError, + ); + await assert.rejects(client.deleteInstance(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteInstance as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteInstance as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkDeleteInstanceProgress without error', async () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedResponse = generateSampleMessage( - new operationsProtos.google.longrunning.Operation() - ); - expectedResponse.name = 'test'; - expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; - expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')} - - client.operationsClient.getOperation = stubSimpleCall(expectedResponse); - const decodedOperation = await client.checkDeleteInstanceProgress(expectedResponse.name); - assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); - assert(decodedOperation.metadata); - assert((client.operationsClient.getOperation as SinonStub).getCall(0)); - }); + it('invokes deleteInstance with LRO error', async () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.redis.v1beta1.DeleteInstanceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.redis.v1beta1.DeleteInstanceRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteInstance = stubLongRunningCall( + undefined, + undefined, + expectedError, + ); + const [operation] = await client.deleteInstance(request); + await assert.rejects(operation.promise(), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteInstance as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteInstance as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkDeleteInstanceProgress with error', async () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedError = new Error('expected'); - - client.operationsClient.getOperation = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.checkDeleteInstanceProgress(''), expectedError); - assert((client.operationsClient.getOperation as SinonStub) - .getCall(0)); - }); + it('invokes checkDeleteInstanceProgress without error', async () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation(), + ); + expectedResponse.name = 'test'; + expectedResponse.response = { type_url: 'url', value: Buffer.from('') }; + expectedResponse.metadata = { type_url: 'url', value: Buffer.from('') }; + + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const decodedOperation = await client.checkDeleteInstanceProgress( + expectedResponse.name, + ); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); }); - describe('listInstances', () => { - it('invokes listInstances without error', async () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.redis.v1beta1.ListInstancesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.redis.v1beta1.ListInstancesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.redis.v1beta1.Instance()), - generateSampleMessage(new protos.google.cloud.redis.v1beta1.Instance()), - generateSampleMessage(new protos.google.cloud.redis.v1beta1.Instance()), - ]; - client.innerApiCalls.listInstances = stubSimpleCall(expectedResponse); - const [response] = await client.listInstances(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listInstances as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listInstances as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes checkDeleteInstanceProgress with error', async () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const expectedError = new Error('expected'); + + client.operationsClient.getOperation = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.checkDeleteInstanceProgress(''), + expectedError, + ); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + }); + + describe('listInstances', () => { + it('invokes listInstances without error', async () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.redis.v1beta1.ListInstancesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.redis.v1beta1.ListInstancesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.redis.v1beta1.Instance()), + generateSampleMessage(new protos.google.cloud.redis.v1beta1.Instance()), + generateSampleMessage(new protos.google.cloud.redis.v1beta1.Instance()), + ]; + client.innerApiCalls.listInstances = stubSimpleCall(expectedResponse); + const [response] = await client.listInstances(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listInstances as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listInstances as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listInstances without error using callback', async () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.redis.v1beta1.ListInstancesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.redis.v1beta1.ListInstancesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.redis.v1beta1.Instance()), - generateSampleMessage(new protos.google.cloud.redis.v1beta1.Instance()), - generateSampleMessage(new protos.google.cloud.redis.v1beta1.Instance()), - ]; - client.innerApiCalls.listInstances = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listInstances( - request, - (err?: Error|null, result?: protos.google.cloud.redis.v1beta1.IInstance[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listInstances as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listInstances as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listInstances without error using callback', async () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.redis.v1beta1.ListInstancesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.redis.v1beta1.ListInstancesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.redis.v1beta1.Instance()), + generateSampleMessage(new protos.google.cloud.redis.v1beta1.Instance()), + generateSampleMessage(new protos.google.cloud.redis.v1beta1.Instance()), + ]; + client.innerApiCalls.listInstances = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listInstances( + request, + ( + err?: Error | null, + result?: protos.google.cloud.redis.v1beta1.IInstance[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listInstances as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listInstances as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listInstances with error', async () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.redis.v1beta1.ListInstancesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.redis.v1beta1.ListInstancesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listInstances = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listInstances(request), expectedError); - const actualRequest = (client.innerApiCalls.listInstances as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listInstances as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listInstances with error', async () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.redis.v1beta1.ListInstancesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.redis.v1beta1.ListInstancesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listInstances = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listInstances(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listInstances as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listInstances as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listInstancesStream without error', async () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.redis.v1beta1.ListInstancesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.redis.v1beta1.ListInstancesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.redis.v1beta1.Instance()), - generateSampleMessage(new protos.google.cloud.redis.v1beta1.Instance()), - generateSampleMessage(new protos.google.cloud.redis.v1beta1.Instance()), - ]; - client.descriptors.page.listInstances.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listInstancesStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.cloud.redis.v1beta1.Instance[] = []; - stream.on('data', (response: protos.google.cloud.redis.v1beta1.Instance) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.listInstances.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listInstances, request)); - assert( - (client.descriptors.page.listInstances.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listInstancesStream without error', async () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.redis.v1beta1.ListInstancesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.redis.v1beta1.ListInstancesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.redis.v1beta1.Instance()), + generateSampleMessage(new protos.google.cloud.redis.v1beta1.Instance()), + generateSampleMessage(new protos.google.cloud.redis.v1beta1.Instance()), + ]; + client.descriptors.page.listInstances.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listInstancesStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.cloud.redis.v1beta1.Instance[] = []; + stream.on( + 'data', + (response: protos.google.cloud.redis.v1beta1.Instance) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listInstances.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listInstances, request), + ); + assert( + (client.descriptors.page.listInstances.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('invokes listInstancesStream with error', async () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.redis.v1beta1.ListInstancesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.redis.v1beta1.ListInstancesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listInstances.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listInstancesStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.cloud.redis.v1beta1.Instance[] = []; - stream.on('data', (response: protos.google.cloud.redis.v1beta1.Instance) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listInstances.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listInstances, request)); - assert( - (client.descriptors.page.listInstances.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listInstancesStream with error', async () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.redis.v1beta1.ListInstancesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.redis.v1beta1.ListInstancesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listInstances.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listInstancesStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.cloud.redis.v1beta1.Instance[] = []; + stream.on( + 'data', + (response: protos.google.cloud.redis.v1beta1.Instance) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listInstances.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listInstances, request), + ); + assert( + (client.descriptors.page.listInstances.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('uses async iteration with listInstances without error', async () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.redis.v1beta1.ListInstancesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.redis.v1beta1.ListInstancesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.redis.v1beta1.Instance()), - generateSampleMessage(new protos.google.cloud.redis.v1beta1.Instance()), - generateSampleMessage(new protos.google.cloud.redis.v1beta1.Instance()), - ]; - client.descriptors.page.listInstances.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.cloud.redis.v1beta1.IInstance[] = []; - const iterable = client.listInstancesAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listInstances.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listInstances.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listInstances without error', async () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.redis.v1beta1.ListInstancesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.redis.v1beta1.ListInstancesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.redis.v1beta1.Instance()), + generateSampleMessage(new protos.google.cloud.redis.v1beta1.Instance()), + generateSampleMessage(new protos.google.cloud.redis.v1beta1.Instance()), + ]; + client.descriptors.page.listInstances.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.cloud.redis.v1beta1.IInstance[] = []; + const iterable = client.listInstancesAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listInstances.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listInstances.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('uses async iteration with listInstances with error', async () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.redis.v1beta1.ListInstancesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.redis.v1beta1.ListInstancesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listInstances.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listInstancesAsync(request); - await assert.rejects(async () => { - const responses: protos.google.cloud.redis.v1beta1.IInstance[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listInstances.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listInstances.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listInstances with error', async () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.redis.v1beta1.ListInstancesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.redis.v1beta1.ListInstancesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listInstances.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listInstancesAsync(request); + await assert.rejects(async () => { + const responses: protos.google.cloud.redis.v1beta1.IInstance[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listInstances.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listInstances.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); }); - describe('getOperation', () => { - it('invokes getOperation without error', async () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new operationsProtos.google.longrunning.GetOperationRequest() - ); - const expectedResponse = generateSampleMessage( - new operationsProtos.google.longrunning.Operation() - ); - client.operationsClient.getOperation = stubSimpleCall(expectedResponse); - const response = await client.getOperation(request); - assert.deepStrictEqual(response, [expectedResponse]); - assert((client.operationsClient.getOperation as SinonStub) - .getCall(0).calledWith(request) - ); - }); - it('invokes getOperation without error using callback', async () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - const request = generateSampleMessage( - new operationsProtos.google.longrunning.GetOperationRequest() - ); - const expectedResponse = generateSampleMessage( - new operationsProtos.google.longrunning.Operation() - ); - client.operationsClient.getOperation = sinon.stub().callsArgWith(2, null, expectedResponse); - const promise = new Promise((resolve, reject) => { - client.operationsClient.getOperation( - request, - undefined, - ( - err?: Error | null, - result?: operationsProtos.google.longrunning.Operation | null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }).catch(err => {throw err}); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - assert((client.operationsClient.getOperation as SinonStub) - .getCall(0)); - }); - it('invokes getOperation with error', async () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - const request = generateSampleMessage( - new operationsProtos.google.longrunning.GetOperationRequest() - ); - const expectedError = new Error('expected'); - client.operationsClient.getOperation = stubSimpleCall(undefined, expectedError); - await assert.rejects(async () => {await client.getOperation(request)}, expectedError); - assert((client.operationsClient.getOperation as SinonStub) - .getCall(0).calledWith(request)); - }); + }); + describe('getOperation', () => { + it('invokes getOperation without error', async () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new operationsProtos.google.longrunning.GetOperationRequest(), + ); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation(), + ); + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const response = await client.getOperation(request); + assert.deepStrictEqual(response, [expectedResponse]); + assert( + (client.operationsClient.getOperation as SinonStub) + .getCall(0) + .calledWith(request), + ); }); - describe('cancelOperation', () => { - it('invokes cancelOperation without error', async () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new operationsProtos.google.longrunning.CancelOperationRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.operationsClient.cancelOperation = stubSimpleCall(expectedResponse); - const response = await client.cancelOperation(request); - assert.deepStrictEqual(response, [expectedResponse]); - assert((client.operationsClient.cancelOperation as SinonStub) - .getCall(0).calledWith(request) - ); - }); - it('invokes cancelOperation without error using callback', async () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - const request = generateSampleMessage( - new operationsProtos.google.longrunning.CancelOperationRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.operationsClient.cancelOperation = sinon.stub().callsArgWith(2, null, expectedResponse); - const promise = new Promise((resolve, reject) => { - client.operationsClient.cancelOperation( - request, - undefined, - ( - err?: Error | null, - result?: protos.google.protobuf.Empty | null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }).catch(err => {throw err}); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - assert((client.operationsClient.cancelOperation as SinonStub) - .getCall(0)); - }); - it('invokes cancelOperation with error', async () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - const request = generateSampleMessage( - new operationsProtos.google.longrunning.CancelOperationRequest() - ); - const expectedError = new Error('expected'); - client.operationsClient.cancelOperation = stubSimpleCall(undefined, expectedError); - await assert.rejects(async () => {await client.cancelOperation(request)}, expectedError); - assert((client.operationsClient.cancelOperation as SinonStub) - .getCall(0).calledWith(request)); - }); + it('invokes getOperation without error using callback', async () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + const request = generateSampleMessage( + new operationsProtos.google.longrunning.GetOperationRequest(), + ); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation(), + ); + client.operationsClient.getOperation = sinon + .stub() + .callsArgWith(2, null, expectedResponse); + const promise = new Promise((resolve, reject) => { + client.operationsClient + .getOperation( + request, + undefined, + ( + err?: Error | null, + result?: operationsProtos.google.longrunning.Operation | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ) + .catch((err) => { + throw err; + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); }); - describe('deleteOperation', () => { - it('invokes deleteOperation without error', async () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new operationsProtos.google.longrunning.DeleteOperationRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.operationsClient.deleteOperation = stubSimpleCall(expectedResponse); - const response = await client.deleteOperation(request); - assert.deepStrictEqual(response, [expectedResponse]); - assert((client.operationsClient.deleteOperation as SinonStub) - .getCall(0).calledWith(request) - ); - }); - it('invokes deleteOperation without error using callback', async () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - const request = generateSampleMessage( - new operationsProtos.google.longrunning.DeleteOperationRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.operationsClient.deleteOperation = sinon.stub().callsArgWith(2, null, expectedResponse); - const promise = new Promise((resolve, reject) => { - client.operationsClient.deleteOperation( - request, - undefined, - ( - err?: Error | null, - result?: protos.google.protobuf.Empty | null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }).catch(err => {throw err}); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - assert((client.operationsClient.deleteOperation as SinonStub) - .getCall(0)); - }); - it('invokes deleteOperation with error', async () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - const request = generateSampleMessage( - new operationsProtos.google.longrunning.DeleteOperationRequest() - ); - const expectedError = new Error('expected'); - client.operationsClient.deleteOperation = stubSimpleCall(undefined, expectedError); - await assert.rejects(async () => {await client.deleteOperation(request)}, expectedError); - assert((client.operationsClient.deleteOperation as SinonStub) - .getCall(0).calledWith(request)); - }); + it('invokes getOperation with error', async () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + const request = generateSampleMessage( + new operationsProtos.google.longrunning.GetOperationRequest(), + ); + const expectedError = new Error('expected'); + client.operationsClient.getOperation = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(async () => { + await client.getOperation(request); + }, expectedError); + assert( + (client.operationsClient.getOperation as SinonStub) + .getCall(0) + .calledWith(request), + ); }); - describe('listOperationsAsync', () => { - it('uses async iteration with listOperations without error', async () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - const request = generateSampleMessage( - new operationsProtos.google.longrunning.ListOperationsRequest() - ); - const expectedResponse = [ - generateSampleMessage( - new operationsProtos.google.longrunning.ListOperationsResponse() - ), - generateSampleMessage( - new operationsProtos.google.longrunning.ListOperationsResponse() - ), - generateSampleMessage( - new operationsProtos.google.longrunning.ListOperationsResponse() - ), - ]; - client.operationsClient.descriptor.listOperations.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: operationsProtos.google.longrunning.IOperation[] = []; - const iterable = client.operationsClient.listOperationsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.operationsClient.descriptor.listOperations.asyncIterate as SinonStub) - .getCall(0).args[1], request); - }); - it('uses async iteration with listOperations with error', async () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new operationsProtos.google.longrunning.ListOperationsRequest() - ); - const expectedError = new Error('expected'); - client.operationsClient.descriptor.listOperations.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.operationsClient.listOperationsAsync(request); - await assert.rejects(async () => { - const responses: operationsProtos.google.longrunning.IOperation[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.operationsClient.descriptor.listOperations.asyncIterate as SinonStub) - .getCall(0).args[1], request); - }); + }); + describe('cancelOperation', () => { + it('invokes cancelOperation without error', async () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new operationsProtos.google.longrunning.CancelOperationRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.operationsClient.cancelOperation = + stubSimpleCall(expectedResponse); + const response = await client.cancelOperation(request); + assert.deepStrictEqual(response, [expectedResponse]); + assert( + (client.operationsClient.cancelOperation as SinonStub) + .getCall(0) + .calledWith(request), + ); + }); + it('invokes cancelOperation without error using callback', async () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + const request = generateSampleMessage( + new operationsProtos.google.longrunning.CancelOperationRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.operationsClient.cancelOperation = sinon + .stub() + .callsArgWith(2, null, expectedResponse); + const promise = new Promise((resolve, reject) => { + client.operationsClient + .cancelOperation( + request, + undefined, + ( + err?: Error | null, + result?: protos.google.protobuf.Empty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ) + .catch((err) => { + throw err; + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + assert((client.operationsClient.cancelOperation as SinonStub).getCall(0)); + }); + it('invokes cancelOperation with error', async () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + const request = generateSampleMessage( + new operationsProtos.google.longrunning.CancelOperationRequest(), + ); + const expectedError = new Error('expected'); + client.operationsClient.cancelOperation = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(async () => { + await client.cancelOperation(request); + }, expectedError); + assert( + (client.operationsClient.cancelOperation as SinonStub) + .getCall(0) + .calledWith(request), + ); + }); + }); + describe('deleteOperation', () => { + it('invokes deleteOperation without error', async () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new operationsProtos.google.longrunning.DeleteOperationRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.operationsClient.deleteOperation = + stubSimpleCall(expectedResponse); + const response = await client.deleteOperation(request); + assert.deepStrictEqual(response, [expectedResponse]); + assert( + (client.operationsClient.deleteOperation as SinonStub) + .getCall(0) + .calledWith(request), + ); + }); + it('invokes deleteOperation without error using callback', async () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + const request = generateSampleMessage( + new operationsProtos.google.longrunning.DeleteOperationRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.operationsClient.deleteOperation = sinon + .stub() + .callsArgWith(2, null, expectedResponse); + const promise = new Promise((resolve, reject) => { + client.operationsClient + .deleteOperation( + request, + undefined, + ( + err?: Error | null, + result?: protos.google.protobuf.Empty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ) + .catch((err) => { + throw err; + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + assert((client.operationsClient.deleteOperation as SinonStub).getCall(0)); + }); + it('invokes deleteOperation with error', async () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + const request = generateSampleMessage( + new operationsProtos.google.longrunning.DeleteOperationRequest(), + ); + const expectedError = new Error('expected'); + client.operationsClient.deleteOperation = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(async () => { + await client.deleteOperation(request); + }, expectedError); + assert( + (client.operationsClient.deleteOperation as SinonStub) + .getCall(0) + .calledWith(request), + ); + }); + }); + describe('listOperationsAsync', () => { + it('uses async iteration with listOperations without error', async () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + const request = generateSampleMessage( + new operationsProtos.google.longrunning.ListOperationsRequest(), + ); + const expectedResponse = [ + generateSampleMessage( + new operationsProtos.google.longrunning.ListOperationsResponse(), + ), + generateSampleMessage( + new operationsProtos.google.longrunning.ListOperationsResponse(), + ), + generateSampleMessage( + new operationsProtos.google.longrunning.ListOperationsResponse(), + ), + ]; + client.operationsClient.descriptor.listOperations.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: operationsProtos.google.longrunning.IOperation[] = []; + const iterable = client.operationsClient.listOperationsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.operationsClient.descriptor.listOperations + .asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + }); + it('uses async iteration with listOperations with error', async () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new operationsProtos.google.longrunning.ListOperationsRequest(), + ); + const expectedError = new Error('expected'); + client.operationsClient.descriptor.listOperations.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.operationsClient.listOperationsAsync(request); + await assert.rejects(async () => { + const responses: operationsProtos.google.longrunning.IOperation[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.operationsClient.descriptor.listOperations + .asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + }); + }); + + describe('Path templates', () => { + describe('instance', () => { + const fakePath = '/rendered/path/instance'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + instance: 'instanceValue', + }; + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.instancePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.instancePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('instancePath', () => { + const result = client.instancePath( + 'projectValue', + 'locationValue', + 'instanceValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.instancePathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromInstanceName', () => { + const result = client.matchProjectFromInstanceName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.instancePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromInstanceName', () => { + const result = client.matchLocationFromInstanceName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.instancePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchInstanceFromInstanceName', () => { + const result = client.matchInstanceFromInstanceName(fakePath); + assert.strictEqual(result, 'instanceValue'); + assert( + (client.pathTemplates.instancePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); - describe('Path templates', () => { - - describe('instance', () => { - const fakePath = "/rendered/path/instance"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - instance: "instanceValue", - }; - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.instancePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.instancePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('instancePath', () => { - const result = client.instancePath("projectValue", "locationValue", "instanceValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.instancePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromInstanceName', () => { - const result = client.matchProjectFromInstanceName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.instancePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromInstanceName', () => { - const result = client.matchLocationFromInstanceName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.instancePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchInstanceFromInstanceName', () => { - const result = client.matchInstanceFromInstanceName(fakePath); - assert.strictEqual(result, "instanceValue"); - assert((client.pathTemplates.instancePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('location', () => { - const fakePath = "/rendered/path/location"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - }; - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.locationPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.locationPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('locationPath', () => { - const result = client.locationPath("projectValue", "locationValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.locationPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromLocationName', () => { - const result = client.matchProjectFromLocationName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.locationPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromLocationName', () => { - const result = client.matchLocationFromLocationName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.locationPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('location', () => { + const fakePath = '/rendered/path/location'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + }; + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.locationPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.locationPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('locationPath', () => { + const result = client.locationPath('projectValue', 'locationValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.locationPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromLocationName', () => { + const result = client.matchProjectFromLocationName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.locationPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromLocationName', () => { + const result = client.matchLocationFromLocationName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.locationPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/core/generator/gapic-generator-typescript/baselines/redis/src/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/redis/src/index.ts.baseline index 1e69afad6583..cb32244c7793 100644 --- a/core/generator/gapic-generator-typescript/baselines/redis/src/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/redis/src/index.ts.baseline @@ -19,7 +19,7 @@ import * as v1beta1 from './v1beta1'; const CloudRedisClient = v1beta1.CloudRedisClient; type CloudRedisClient = v1beta1.CloudRedisClient; -export {v1beta1, CloudRedisClient}; -export default {v1beta1, CloudRedisClient}; +export { v1beta1, CloudRedisClient }; +export default { v1beta1, CloudRedisClient }; import * as protos from '../protos/protos'; -export {protos} +export { protos }; diff --git a/core/generator/gapic-generator-typescript/baselines/redis/src/v1beta1/cloud_redis_client.ts.baseline b/core/generator/gapic-generator-typescript/baselines/redis/src/v1beta1/cloud_redis_client.ts.baseline index 5aa29671579a..0b2058f1e38c 100644 --- a/core/generator/gapic-generator-typescript/baselines/redis/src/v1beta1/cloud_redis_client.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/redis/src/v1beta1/cloud_redis_client.ts.baseline @@ -18,11 +18,20 @@ /* global window */ import type * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions, GrpcClientOptions, LROperation, PaginationCallback, GaxCall} from 'google-gax'; -import {Transform} from 'stream'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + GrpcClientOptions, + LROperation, + PaginationCallback, + GaxCall, +} from 'google-gax'; +import { Transform } from 'stream'; import * as protos from '../../protos/protos'; import jsonProtos = require('../../protos/protos.json'); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; /** * Client JSON configuration object, loaded from @@ -58,7 +67,7 @@ export class CloudRedisClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('redis'); @@ -71,10 +80,10 @@ export class CloudRedisClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; operationsClient: gax.OperationsClient; - cloudRedisStub?: Promise<{[name: string]: Function}>; + cloudRedisStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of CloudRedisClient. @@ -115,21 +124,42 @@ export class CloudRedisClient { * const client = new CloudRedisClient({fallback: true}, gax); * ``` */ - constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { // Ensure that options include all the required fields. const staticMembers = this.constructor as typeof CloudRedisClient; - if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { - throw new Error('Please set either universe_domain or universeDomain, but not both.'); + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); } - const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; - this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; this._servicePath = 'redis.' + this._universeDomain; - const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; - const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. if (servicePath !== this._servicePath && !('scopes' in opts)) { @@ -151,7 +181,7 @@ export class CloudRedisClient { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; @@ -165,10 +195,7 @@ export class CloudRedisClient { } // Determine the client header string. - const clientHeader = [ - `gax/${this._gaxModule.version}`, - `gapic/${version}`, - ]; + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/${process.versions.node}`); } else { @@ -190,10 +217,10 @@ export class CloudRedisClient { // Create useful helper objects for these. this.pathTemplates = { instancePathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/instances/{instance}' + 'projects/{project}/locations/{location}/instances/{instance}', ), locationPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}' + 'projects/{project}/locations/{location}', ), }; @@ -201,8 +228,11 @@ export class CloudRedisClient { // (e.g. 50 results at a time, with tokens to get subsequent // pages). Denote the keys used for pagination and results. this.descriptors.page = { - listInstances: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'instances') + listInstances: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'instances', + ), }; const protoFilesRoot = this._gaxModule.protobufFromJSON(jsonProtos); @@ -211,69 +241,92 @@ export class CloudRedisClient { // rather than holding a request open. const lroOptions: GrpcClientOptions = { auth: this.auth, - grpc: 'grpc' in this._gaxGrpc ? this._gaxGrpc.grpc : undefined + grpc: 'grpc' in this._gaxGrpc ? this._gaxGrpc.grpc : undefined, }; if (opts.fallback) { lroOptions.protoJson = protoFilesRoot; lroOptions.httpRules = []; } - this.operationsClient = this._gaxModule.lro(lroOptions).operationsClient(opts); + this.operationsClient = this._gaxModule + .lro(lroOptions) + .operationsClient(opts); const createInstanceResponse = protoFilesRoot.lookup( - '.google.cloud.redis.v1beta1.Instance') as gax.protobuf.Type; + '.google.cloud.redis.v1beta1.Instance', + ) as gax.protobuf.Type; const createInstanceMetadata = protoFilesRoot.lookup( - '.google.protobuf.Any') as gax.protobuf.Type; + '.google.protobuf.Any', + ) as gax.protobuf.Type; const updateInstanceResponse = protoFilesRoot.lookup( - '.google.cloud.redis.v1beta1.Instance') as gax.protobuf.Type; + '.google.cloud.redis.v1beta1.Instance', + ) as gax.protobuf.Type; const updateInstanceMetadata = protoFilesRoot.lookup( - '.google.protobuf.Any') as gax.protobuf.Type; + '.google.protobuf.Any', + ) as gax.protobuf.Type; const importInstanceResponse = protoFilesRoot.lookup( - '.google.cloud.redis.v1beta1.Instance') as gax.protobuf.Type; + '.google.cloud.redis.v1beta1.Instance', + ) as gax.protobuf.Type; const importInstanceMetadata = protoFilesRoot.lookup( - '.google.protobuf.Any') as gax.protobuf.Type; + '.google.protobuf.Any', + ) as gax.protobuf.Type; const exportInstanceResponse = protoFilesRoot.lookup( - '.google.cloud.redis.v1beta1.Instance') as gax.protobuf.Type; + '.google.cloud.redis.v1beta1.Instance', + ) as gax.protobuf.Type; const exportInstanceMetadata = protoFilesRoot.lookup( - '.google.protobuf.Any') as gax.protobuf.Type; + '.google.protobuf.Any', + ) as gax.protobuf.Type; const failoverInstanceResponse = protoFilesRoot.lookup( - '.google.cloud.redis.v1beta1.Instance') as gax.protobuf.Type; + '.google.cloud.redis.v1beta1.Instance', + ) as gax.protobuf.Type; const failoverInstanceMetadata = protoFilesRoot.lookup( - '.google.protobuf.Any') as gax.protobuf.Type; + '.google.protobuf.Any', + ) as gax.protobuf.Type; const deleteInstanceResponse = protoFilesRoot.lookup( - '.google.protobuf.Empty') as gax.protobuf.Type; + '.google.protobuf.Empty', + ) as gax.protobuf.Type; const deleteInstanceMetadata = protoFilesRoot.lookup( - '.google.protobuf.Any') as gax.protobuf.Type; + '.google.protobuf.Any', + ) as gax.protobuf.Type; this.descriptors.longrunning = { createInstance: new this._gaxModule.LongrunningDescriptor( this.operationsClient, createInstanceResponse.decode.bind(createInstanceResponse), - createInstanceMetadata.decode.bind(createInstanceMetadata)), + createInstanceMetadata.decode.bind(createInstanceMetadata), + ), updateInstance: new this._gaxModule.LongrunningDescriptor( this.operationsClient, updateInstanceResponse.decode.bind(updateInstanceResponse), - updateInstanceMetadata.decode.bind(updateInstanceMetadata)), + updateInstanceMetadata.decode.bind(updateInstanceMetadata), + ), importInstance: new this._gaxModule.LongrunningDescriptor( this.operationsClient, importInstanceResponse.decode.bind(importInstanceResponse), - importInstanceMetadata.decode.bind(importInstanceMetadata)), + importInstanceMetadata.decode.bind(importInstanceMetadata), + ), exportInstance: new this._gaxModule.LongrunningDescriptor( this.operationsClient, exportInstanceResponse.decode.bind(exportInstanceResponse), - exportInstanceMetadata.decode.bind(exportInstanceMetadata)), + exportInstanceMetadata.decode.bind(exportInstanceMetadata), + ), failoverInstance: new this._gaxModule.LongrunningDescriptor( this.operationsClient, failoverInstanceResponse.decode.bind(failoverInstanceResponse), - failoverInstanceMetadata.decode.bind(failoverInstanceMetadata)), + failoverInstanceMetadata.decode.bind(failoverInstanceMetadata), + ), deleteInstance: new this._gaxModule.LongrunningDescriptor( this.operationsClient, deleteInstanceResponse.decode.bind(deleteInstanceResponse), - deleteInstanceMetadata.decode.bind(deleteInstanceMetadata)) + deleteInstanceMetadata.decode.bind(deleteInstanceMetadata), + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.cloud.redis.v1beta1.CloudRedis', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.cloud.redis.v1beta1.CloudRedis', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + { 'x-goog-api-client': clientHeader.join(' ') }, + ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -304,28 +357,42 @@ export class CloudRedisClient { // Put together the "service stub" for // google.cloud.redis.v1beta1.CloudRedis. this.cloudRedisStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.cloud.redis.v1beta1.CloudRedis') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.cloud.redis.v1beta1.CloudRedis', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.cloud.redis.v1beta1.CloudRedis, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts, + this._providedCustomServicePath, + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const cloudRedisStubMethods = - ['listInstances', 'getInstance', 'createInstance', 'updateInstance', 'importInstance', 'exportInstance', 'failoverInstance', 'deleteInstance']; + const cloudRedisStubMethods = [ + 'listInstances', + 'getInstance', + 'createInstance', + 'updateInstance', + 'importInstance', + 'exportInstance', + 'failoverInstance', + 'deleteInstance', + ]; for (const methodName of cloudRedisStubMethods) { const callPromise = this.cloudRedisStub.then( - stub => (...args: Array<{}>) => { - if (this._terminated) { - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error|null|undefined) => () => { + (stub) => + (...args: Array<{}>) => { + if (this._terminated) { + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { throw err; - }); + }, + ); const descriptor = this.descriptors.page[methodName] || @@ -335,7 +402,7 @@ export class CloudRedisClient { callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -350,8 +417,14 @@ export class CloudRedisClient { * @returns {string} The DNS address for this service. */ static get servicePath() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'redis.googleapis.com'; } @@ -362,8 +435,14 @@ export class CloudRedisClient { * @returns {string} The DNS address for this service. */ static get apiEndpoint() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'redis.googleapis.com'; } @@ -394,9 +473,7 @@ export class CloudRedisClient { * @returns {string[]} List of default scopes. */ static get scopes() { - return [ - 'https://www.googleapis.com/auth/cloud-platform' - ]; + return ['https://www.googleapis.com/auth/cloud-platform']; } getProjectId(): Promise; @@ -405,8 +482,9 @@ export class CloudRedisClient { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId(callback?: Callback): - Promise|void { + getProjectId( + callback?: Callback, + ): Promise | void { if (callback) { this.auth.getProjectId(callback); return; @@ -417,909 +495,1322 @@ export class CloudRedisClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Gets the details of a specific Redis instance. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. Redis instance resource name using the form: - * `projects/{project_id}/locations/{location_id}/instances/{instance_id}` - * where `location_id` refers to a GCP region. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.redis.v1beta1.Instance|Instance}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/cloud_redis.get_instance.js - * region_tag:redis_v1beta1_generated_CloudRedis_GetInstance_async - */ + /** + * Gets the details of a specific Redis instance. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Redis instance resource name using the form: + * `projects/{project_id}/locations/{location_id}/instances/{instance_id}` + * where `location_id` refers to a GCP region. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.redis.v1beta1.Instance|Instance}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/cloud_redis.get_instance.js + * region_tag:redis_v1beta1_generated_CloudRedis_GetInstance_async + */ getInstance( - request?: protos.google.cloud.redis.v1beta1.IGetInstanceRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.redis.v1beta1.IInstance, - protos.google.cloud.redis.v1beta1.IGetInstanceRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.redis.v1beta1.IGetInstanceRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.redis.v1beta1.IInstance, + protos.google.cloud.redis.v1beta1.IGetInstanceRequest | undefined, + {} | undefined, + ] + >; getInstance( - request: protos.google.cloud.redis.v1beta1.IGetInstanceRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.redis.v1beta1.IInstance, - protos.google.cloud.redis.v1beta1.IGetInstanceRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.redis.v1beta1.IGetInstanceRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.redis.v1beta1.IInstance, + protos.google.cloud.redis.v1beta1.IGetInstanceRequest | null | undefined, + {} | null | undefined + >, + ): void; getInstance( - request: protos.google.cloud.redis.v1beta1.IGetInstanceRequest, - callback: Callback< - protos.google.cloud.redis.v1beta1.IInstance, - protos.google.cloud.redis.v1beta1.IGetInstanceRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.redis.v1beta1.IGetInstanceRequest, + callback: Callback< + protos.google.cloud.redis.v1beta1.IInstance, + protos.google.cloud.redis.v1beta1.IGetInstanceRequest | null | undefined, + {} | null | undefined + >, + ): void; getInstance( - request?: protos.google.cloud.redis.v1beta1.IGetInstanceRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.redis.v1beta1.IInstance, - protos.google.cloud.redis.v1beta1.IGetInstanceRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.redis.v1beta1.IGetInstanceRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.redis.v1beta1.IInstance, - protos.google.cloud.redis.v1beta1.IGetInstanceRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.redis.v1beta1.IInstance, - protos.google.cloud.redis.v1beta1.IGetInstanceRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.redis.v1beta1.IGetInstanceRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.redis.v1beta1.IInstance, + protos.google.cloud.redis.v1beta1.IGetInstanceRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.redis.v1beta1.IInstance, + protos.google.cloud.redis.v1beta1.IGetInstanceRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getInstance request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.redis.v1beta1.IInstance, - protos.google.cloud.redis.v1beta1.IGetInstanceRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.redis.v1beta1.IInstance, + | protos.google.cloud.redis.v1beta1.IGetInstanceRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getInstance response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getInstance(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.redis.v1beta1.IInstance, - protos.google.cloud.redis.v1beta1.IGetInstanceRequest|undefined, - {}|undefined - ]) => { - this._log.info('getInstance response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getInstance(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.redis.v1beta1.IInstance, + protos.google.cloud.redis.v1beta1.IGetInstanceRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getInstance response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Creates a Redis instance based on the specified tier and memory size. - * - * By default, the instance is accessible from the project's - * [default network](/compute/docs/networks-and-firewalls#networks). - * - * The creation is executed asynchronously and callers may check the returned - * operation to track its progress. Once the operation is completed the Redis - * instance will be fully functional. Completed longrunning.Operation will - * contain the new instance object in the response field. - * - * The returned operation is automatically deleted after a few hours, so there - * is no need to call DeleteOperation. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The resource name of the instance location using the form: - * `projects/{project_id}/locations/{location_id}` - * where `location_id` refers to a GCP region. - * @param {string} request.instanceId - * Required. The logical name of the Redis instance in the customer project - * with the following restrictions: - * - * * Must contain only lowercase letters, numbers, and hyphens. - * * Must start with a letter. - * * Must be between 1-40 characters. - * * Must end with a number or a letter. - * * Must be unique within the customer project / location - * @param {google.cloud.redis.v1beta1.Instance} request.instance - * Required. A Redis [Instance] resource - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing - * a long running operation. Its `promise()` method returns a promise - * you can `await` for. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/cloud_redis.create_instance.js - * region_tag:redis_v1beta1_generated_CloudRedis_CreateInstance_async - */ + /** + * Creates a Redis instance based on the specified tier and memory size. + * + * By default, the instance is accessible from the project's + * [default network](/compute/docs/networks-and-firewalls#networks). + * + * The creation is executed asynchronously and callers may check the returned + * operation to track its progress. Once the operation is completed the Redis + * instance will be fully functional. Completed longrunning.Operation will + * contain the new instance object in the response field. + * + * The returned operation is automatically deleted after a few hours, so there + * is no need to call DeleteOperation. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The resource name of the instance location using the form: + * `projects/{project_id}/locations/{location_id}` + * where `location_id` refers to a GCP region. + * @param {string} request.instanceId + * Required. The logical name of the Redis instance in the customer project + * with the following restrictions: + * + * * Must contain only lowercase letters, numbers, and hyphens. + * * Must start with a letter. + * * Must be between 1-40 characters. + * * Must end with a number or a letter. + * * Must be unique within the customer project / location + * @param {google.cloud.redis.v1beta1.Instance} request.instance + * Required. A Redis [Instance] resource + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/cloud_redis.create_instance.js + * region_tag:redis_v1beta1_generated_CloudRedis_CreateInstance_async + */ createInstance( - request?: protos.google.cloud.redis.v1beta1.ICreateInstanceRequest, - options?: CallOptions): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>; + request?: protos.google.cloud.redis.v1beta1.ICreateInstanceRequest, + options?: CallOptions, + ): Promise< + [ + LROperation< + protos.google.cloud.redis.v1beta1.IInstance, + protos.google.protobuf.IAny + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; createInstance( - request: protos.google.cloud.redis.v1beta1.ICreateInstanceRequest, - options: CallOptions, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.redis.v1beta1.ICreateInstanceRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.cloud.redis.v1beta1.IInstance, + protos.google.protobuf.IAny + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; createInstance( - request: protos.google.cloud.redis.v1beta1.ICreateInstanceRequest, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.redis.v1beta1.ICreateInstanceRequest, + callback: Callback< + LROperation< + protos.google.cloud.redis.v1beta1.IInstance, + protos.google.protobuf.IAny + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; createInstance( - request?: protos.google.cloud.redis.v1beta1.ICreateInstanceRequest, - optionsOrCallback?: CallOptions|Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>, - callback?: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>|void { + request?: protos.google.cloud.redis.v1beta1.ICreateInstanceRequest, + optionsOrCallback?: + | CallOptions + | Callback< + LROperation< + protos.google.cloud.redis.v1beta1.IInstance, + protos.google.protobuf.IAny + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + callback?: Callback< + LROperation< + protos.google.cloud.redis.v1beta1.IInstance, + protos.google.protobuf.IAny + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + LROperation< + protos.google.cloud.redis.v1beta1.IInstance, + protos.google.protobuf.IAny + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + LROperation< + protos.google.cloud.redis.v1beta1.IInstance, + protos.google.protobuf.IAny + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, rawResponse, _) => { this._log.info('createInstance response %j', rawResponse); callback!(error, response, rawResponse, _); // We verified callback above. } : undefined; this._log.info('createInstance request %j', request); - return this.innerApiCalls.createInstance(request, options, wrappedCallback) - ?.then(([response, rawResponse, _]: [ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]) => { - this._log.info('createInstance response %j', rawResponse); - return [response, rawResponse, _]; - }); + return this.innerApiCalls + .createInstance(request, options, wrappedCallback) + ?.then( + ([response, rawResponse, _]: [ + LROperation< + protos.google.cloud.redis.v1beta1.IInstance, + protos.google.protobuf.IAny + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ]) => { + this._log.info('createInstance response %j', rawResponse); + return [response, rawResponse, _]; + }, + ); } -/** - * Check the status of the long running operation returned by `createInstance()`. - * @param {String} name - * The operation name that will be passed. - * @returns {Promise} - The promise which resolves to an object. - * The decoded operation object has result and metadata field to get information from. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/cloud_redis.create_instance.js - * region_tag:redis_v1beta1_generated_CloudRedis_CreateInstance_async - */ - async checkCreateInstanceProgress(name: string): Promise>{ + /** + * Check the status of the long running operation returned by `createInstance()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/cloud_redis.create_instance.js + * region_tag:redis_v1beta1_generated_CloudRedis_CreateInstance_async + */ + async checkCreateInstanceProgress( + name: string, + ): Promise< + LROperation< + protos.google.cloud.redis.v1beta1.Instance, + protos.google.protobuf.Any + > + > { this._log.info('createInstance long-running'); - const request = new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest({name}); + const request = + new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( + { name }, + ); const [operation] = await this.operationsClient.getOperation(request); - const decodeOperation = new this._gaxModule.Operation(operation, this.descriptors.longrunning.createInstance, this._gaxModule.createDefaultBackoffSettings()); - return decodeOperation as LROperation; + const decodeOperation = new this._gaxModule.Operation( + operation, + this.descriptors.longrunning.createInstance, + this._gaxModule.createDefaultBackoffSettings(), + ); + return decodeOperation as LROperation< + protos.google.cloud.redis.v1beta1.Instance, + protos.google.protobuf.Any + >; } -/** - * Updates the metadata and configuration of a specific Redis instance. - * - * Completed longrunning.Operation will contain the new instance object - * in the response field. The returned operation is automatically deleted - * after a few hours, so there is no need to call DeleteOperation. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.protobuf.FieldMask} request.updateMask - * Required. Mask of fields to update. At least one path must be supplied in - * this field. The elements of the repeated paths field may only include these - * fields from {@link protos.google.cloud.redis.v1beta1.Instance|Instance}: - * - * * `displayName` - * * `labels` - * * `memorySizeGb` - * * `redisConfig` - * @param {google.cloud.redis.v1beta1.Instance} request.instance - * Required. Update description. - * Only fields specified in update_mask are updated. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing - * a long running operation. Its `promise()` method returns a promise - * you can `await` for. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/cloud_redis.update_instance.js - * region_tag:redis_v1beta1_generated_CloudRedis_UpdateInstance_async - */ + /** + * Updates the metadata and configuration of a specific Redis instance. + * + * Completed longrunning.Operation will contain the new instance object + * in the response field. The returned operation is automatically deleted + * after a few hours, so there is no need to call DeleteOperation. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.protobuf.FieldMask} request.updateMask + * Required. Mask of fields to update. At least one path must be supplied in + * this field. The elements of the repeated paths field may only include these + * fields from {@link protos.google.cloud.redis.v1beta1.Instance|Instance}: + * + * * `displayName` + * * `labels` + * * `memorySizeGb` + * * `redisConfig` + * @param {google.cloud.redis.v1beta1.Instance} request.instance + * Required. Update description. + * Only fields specified in update_mask are updated. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/cloud_redis.update_instance.js + * region_tag:redis_v1beta1_generated_CloudRedis_UpdateInstance_async + */ updateInstance( - request?: protos.google.cloud.redis.v1beta1.IUpdateInstanceRequest, - options?: CallOptions): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>; + request?: protos.google.cloud.redis.v1beta1.IUpdateInstanceRequest, + options?: CallOptions, + ): Promise< + [ + LROperation< + protos.google.cloud.redis.v1beta1.IInstance, + protos.google.protobuf.IAny + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; updateInstance( - request: protos.google.cloud.redis.v1beta1.IUpdateInstanceRequest, - options: CallOptions, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.redis.v1beta1.IUpdateInstanceRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.cloud.redis.v1beta1.IInstance, + protos.google.protobuf.IAny + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; updateInstance( - request: protos.google.cloud.redis.v1beta1.IUpdateInstanceRequest, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.redis.v1beta1.IUpdateInstanceRequest, + callback: Callback< + LROperation< + protos.google.cloud.redis.v1beta1.IInstance, + protos.google.protobuf.IAny + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; updateInstance( - request?: protos.google.cloud.redis.v1beta1.IUpdateInstanceRequest, - optionsOrCallback?: CallOptions|Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>, - callback?: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>|void { + request?: protos.google.cloud.redis.v1beta1.IUpdateInstanceRequest, + optionsOrCallback?: + | CallOptions + | Callback< + LROperation< + protos.google.cloud.redis.v1beta1.IInstance, + protos.google.protobuf.IAny + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + callback?: Callback< + LROperation< + protos.google.cloud.redis.v1beta1.IInstance, + protos.google.protobuf.IAny + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + LROperation< + protos.google.cloud.redis.v1beta1.IInstance, + protos.google.protobuf.IAny + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'instance.name': request.instance!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'instance.name': request.instance!.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + LROperation< + protos.google.cloud.redis.v1beta1.IInstance, + protos.google.protobuf.IAny + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, rawResponse, _) => { this._log.info('updateInstance response %j', rawResponse); callback!(error, response, rawResponse, _); // We verified callback above. } : undefined; this._log.info('updateInstance request %j', request); - return this.innerApiCalls.updateInstance(request, options, wrappedCallback) - ?.then(([response, rawResponse, _]: [ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]) => { - this._log.info('updateInstance response %j', rawResponse); - return [response, rawResponse, _]; - }); + return this.innerApiCalls + .updateInstance(request, options, wrappedCallback) + ?.then( + ([response, rawResponse, _]: [ + LROperation< + protos.google.cloud.redis.v1beta1.IInstance, + protos.google.protobuf.IAny + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ]) => { + this._log.info('updateInstance response %j', rawResponse); + return [response, rawResponse, _]; + }, + ); } -/** - * Check the status of the long running operation returned by `updateInstance()`. - * @param {String} name - * The operation name that will be passed. - * @returns {Promise} - The promise which resolves to an object. - * The decoded operation object has result and metadata field to get information from. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/cloud_redis.update_instance.js - * region_tag:redis_v1beta1_generated_CloudRedis_UpdateInstance_async - */ - async checkUpdateInstanceProgress(name: string): Promise>{ + /** + * Check the status of the long running operation returned by `updateInstance()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/cloud_redis.update_instance.js + * region_tag:redis_v1beta1_generated_CloudRedis_UpdateInstance_async + */ + async checkUpdateInstanceProgress( + name: string, + ): Promise< + LROperation< + protos.google.cloud.redis.v1beta1.Instance, + protos.google.protobuf.Any + > + > { this._log.info('updateInstance long-running'); - const request = new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest({name}); + const request = + new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( + { name }, + ); const [operation] = await this.operationsClient.getOperation(request); - const decodeOperation = new this._gaxModule.Operation(operation, this.descriptors.longrunning.updateInstance, this._gaxModule.createDefaultBackoffSettings()); - return decodeOperation as LROperation; + const decodeOperation = new this._gaxModule.Operation( + operation, + this.descriptors.longrunning.updateInstance, + this._gaxModule.createDefaultBackoffSettings(), + ); + return decodeOperation as LROperation< + protos.google.cloud.redis.v1beta1.Instance, + protos.google.protobuf.Any + >; } -/** - * Import a Redis RDB snapshot file from Cloud Storage into a Redis instance. - * - * Redis may stop serving during this operation. Instance state will be - * IMPORTING for entire operation. When complete, the instance will contain - * only data from the imported file. - * - * The returned operation is automatically deleted after a few hours, so - * there is no need to call DeleteOperation. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. Redis instance resource name using the form: - * `projects/{project_id}/locations/{location_id}/instances/{instance_id}` - * where `location_id` refers to a GCP region. - * @param {google.cloud.redis.v1beta1.InputConfig} request.inputConfig - * Required. Specify data to be imported. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing - * a long running operation. Its `promise()` method returns a promise - * you can `await` for. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/cloud_redis.import_instance.js - * region_tag:redis_v1beta1_generated_CloudRedis_ImportInstance_async - */ + /** + * Import a Redis RDB snapshot file from Cloud Storage into a Redis instance. + * + * Redis may stop serving during this operation. Instance state will be + * IMPORTING for entire operation. When complete, the instance will contain + * only data from the imported file. + * + * The returned operation is automatically deleted after a few hours, so + * there is no need to call DeleteOperation. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Redis instance resource name using the form: + * `projects/{project_id}/locations/{location_id}/instances/{instance_id}` + * where `location_id` refers to a GCP region. + * @param {google.cloud.redis.v1beta1.InputConfig} request.inputConfig + * Required. Specify data to be imported. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/cloud_redis.import_instance.js + * region_tag:redis_v1beta1_generated_CloudRedis_ImportInstance_async + */ importInstance( - request?: protos.google.cloud.redis.v1beta1.IImportInstanceRequest, - options?: CallOptions): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>; + request?: protos.google.cloud.redis.v1beta1.IImportInstanceRequest, + options?: CallOptions, + ): Promise< + [ + LROperation< + protos.google.cloud.redis.v1beta1.IInstance, + protos.google.protobuf.IAny + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; importInstance( - request: protos.google.cloud.redis.v1beta1.IImportInstanceRequest, - options: CallOptions, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.redis.v1beta1.IImportInstanceRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.cloud.redis.v1beta1.IInstance, + protos.google.protobuf.IAny + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; importInstance( - request: protos.google.cloud.redis.v1beta1.IImportInstanceRequest, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.redis.v1beta1.IImportInstanceRequest, + callback: Callback< + LROperation< + protos.google.cloud.redis.v1beta1.IInstance, + protos.google.protobuf.IAny + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; importInstance( - request?: protos.google.cloud.redis.v1beta1.IImportInstanceRequest, - optionsOrCallback?: CallOptions|Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>, - callback?: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>|void { + request?: protos.google.cloud.redis.v1beta1.IImportInstanceRequest, + optionsOrCallback?: + | CallOptions + | Callback< + LROperation< + protos.google.cloud.redis.v1beta1.IInstance, + protos.google.protobuf.IAny + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + callback?: Callback< + LROperation< + protos.google.cloud.redis.v1beta1.IInstance, + protos.google.protobuf.IAny + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + LROperation< + protos.google.cloud.redis.v1beta1.IInstance, + protos.google.protobuf.IAny + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + LROperation< + protos.google.cloud.redis.v1beta1.IInstance, + protos.google.protobuf.IAny + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, rawResponse, _) => { this._log.info('importInstance response %j', rawResponse); callback!(error, response, rawResponse, _); // We verified callback above. } : undefined; this._log.info('importInstance request %j', request); - return this.innerApiCalls.importInstance(request, options, wrappedCallback) - ?.then(([response, rawResponse, _]: [ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]) => { - this._log.info('importInstance response %j', rawResponse); - return [response, rawResponse, _]; - }); + return this.innerApiCalls + .importInstance(request, options, wrappedCallback) + ?.then( + ([response, rawResponse, _]: [ + LROperation< + protos.google.cloud.redis.v1beta1.IInstance, + protos.google.protobuf.IAny + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ]) => { + this._log.info('importInstance response %j', rawResponse); + return [response, rawResponse, _]; + }, + ); } -/** - * Check the status of the long running operation returned by `importInstance()`. - * @param {String} name - * The operation name that will be passed. - * @returns {Promise} - The promise which resolves to an object. - * The decoded operation object has result and metadata field to get information from. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/cloud_redis.import_instance.js - * region_tag:redis_v1beta1_generated_CloudRedis_ImportInstance_async - */ - async checkImportInstanceProgress(name: string): Promise>{ + /** + * Check the status of the long running operation returned by `importInstance()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/cloud_redis.import_instance.js + * region_tag:redis_v1beta1_generated_CloudRedis_ImportInstance_async + */ + async checkImportInstanceProgress( + name: string, + ): Promise< + LROperation< + protos.google.cloud.redis.v1beta1.Instance, + protos.google.protobuf.Any + > + > { this._log.info('importInstance long-running'); - const request = new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest({name}); + const request = + new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( + { name }, + ); const [operation] = await this.operationsClient.getOperation(request); - const decodeOperation = new this._gaxModule.Operation(operation, this.descriptors.longrunning.importInstance, this._gaxModule.createDefaultBackoffSettings()); - return decodeOperation as LROperation; + const decodeOperation = new this._gaxModule.Operation( + operation, + this.descriptors.longrunning.importInstance, + this._gaxModule.createDefaultBackoffSettings(), + ); + return decodeOperation as LROperation< + protos.google.cloud.redis.v1beta1.Instance, + protos.google.protobuf.Any + >; } -/** - * Export Redis instance data into a Redis RDB format file in Cloud Storage. - * - * Redis will continue serving during this operation. - * - * The returned operation is automatically deleted after a few hours, so - * there is no need to call DeleteOperation. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. Redis instance resource name using the form: - * `projects/{project_id}/locations/{location_id}/instances/{instance_id}` - * where `location_id` refers to a GCP region. - * @param {google.cloud.redis.v1beta1.OutputConfig} request.outputConfig - * Required. Specify data to be exported. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing - * a long running operation. Its `promise()` method returns a promise - * you can `await` for. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/cloud_redis.export_instance.js - * region_tag:redis_v1beta1_generated_CloudRedis_ExportInstance_async - */ + /** + * Export Redis instance data into a Redis RDB format file in Cloud Storage. + * + * Redis will continue serving during this operation. + * + * The returned operation is automatically deleted after a few hours, so + * there is no need to call DeleteOperation. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Redis instance resource name using the form: + * `projects/{project_id}/locations/{location_id}/instances/{instance_id}` + * where `location_id` refers to a GCP region. + * @param {google.cloud.redis.v1beta1.OutputConfig} request.outputConfig + * Required. Specify data to be exported. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/cloud_redis.export_instance.js + * region_tag:redis_v1beta1_generated_CloudRedis_ExportInstance_async + */ exportInstance( - request?: protos.google.cloud.redis.v1beta1.IExportInstanceRequest, - options?: CallOptions): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>; + request?: protos.google.cloud.redis.v1beta1.IExportInstanceRequest, + options?: CallOptions, + ): Promise< + [ + LROperation< + protos.google.cloud.redis.v1beta1.IInstance, + protos.google.protobuf.IAny + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; exportInstance( - request: protos.google.cloud.redis.v1beta1.IExportInstanceRequest, - options: CallOptions, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.redis.v1beta1.IExportInstanceRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.cloud.redis.v1beta1.IInstance, + protos.google.protobuf.IAny + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; exportInstance( - request: protos.google.cloud.redis.v1beta1.IExportInstanceRequest, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.redis.v1beta1.IExportInstanceRequest, + callback: Callback< + LROperation< + protos.google.cloud.redis.v1beta1.IInstance, + protos.google.protobuf.IAny + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; exportInstance( - request?: protos.google.cloud.redis.v1beta1.IExportInstanceRequest, - optionsOrCallback?: CallOptions|Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>, - callback?: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>|void { + request?: protos.google.cloud.redis.v1beta1.IExportInstanceRequest, + optionsOrCallback?: + | CallOptions + | Callback< + LROperation< + protos.google.cloud.redis.v1beta1.IInstance, + protos.google.protobuf.IAny + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + callback?: Callback< + LROperation< + protos.google.cloud.redis.v1beta1.IInstance, + protos.google.protobuf.IAny + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + LROperation< + protos.google.cloud.redis.v1beta1.IInstance, + protos.google.protobuf.IAny + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + LROperation< + protos.google.cloud.redis.v1beta1.IInstance, + protos.google.protobuf.IAny + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, rawResponse, _) => { this._log.info('exportInstance response %j', rawResponse); callback!(error, response, rawResponse, _); // We verified callback above. } : undefined; this._log.info('exportInstance request %j', request); - return this.innerApiCalls.exportInstance(request, options, wrappedCallback) - ?.then(([response, rawResponse, _]: [ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]) => { - this._log.info('exportInstance response %j', rawResponse); - return [response, rawResponse, _]; - }); + return this.innerApiCalls + .exportInstance(request, options, wrappedCallback) + ?.then( + ([response, rawResponse, _]: [ + LROperation< + protos.google.cloud.redis.v1beta1.IInstance, + protos.google.protobuf.IAny + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ]) => { + this._log.info('exportInstance response %j', rawResponse); + return [response, rawResponse, _]; + }, + ); } -/** - * Check the status of the long running operation returned by `exportInstance()`. - * @param {String} name - * The operation name that will be passed. - * @returns {Promise} - The promise which resolves to an object. - * The decoded operation object has result and metadata field to get information from. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/cloud_redis.export_instance.js - * region_tag:redis_v1beta1_generated_CloudRedis_ExportInstance_async - */ - async checkExportInstanceProgress(name: string): Promise>{ + /** + * Check the status of the long running operation returned by `exportInstance()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/cloud_redis.export_instance.js + * region_tag:redis_v1beta1_generated_CloudRedis_ExportInstance_async + */ + async checkExportInstanceProgress( + name: string, + ): Promise< + LROperation< + protos.google.cloud.redis.v1beta1.Instance, + protos.google.protobuf.Any + > + > { this._log.info('exportInstance long-running'); - const request = new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest({name}); + const request = + new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( + { name }, + ); const [operation] = await this.operationsClient.getOperation(request); - const decodeOperation = new this._gaxModule.Operation(operation, this.descriptors.longrunning.exportInstance, this._gaxModule.createDefaultBackoffSettings()); - return decodeOperation as LROperation; + const decodeOperation = new this._gaxModule.Operation( + operation, + this.descriptors.longrunning.exportInstance, + this._gaxModule.createDefaultBackoffSettings(), + ); + return decodeOperation as LROperation< + protos.google.cloud.redis.v1beta1.Instance, + protos.google.protobuf.Any + >; } -/** - * Initiates a failover of the master node to current replica node for a - * specific STANDARD tier Cloud Memorystore for Redis instance. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. Redis instance resource name using the form: - * `projects/{project_id}/locations/{location_id}/instances/{instance_id}` - * where `location_id` refers to a GCP region. - * @param {google.cloud.redis.v1beta1.FailoverInstanceRequest.DataProtectionMode} [request.dataProtectionMode] - * Optional. Available data protection modes that the user can choose. If it's - * unspecified, data protection mode will be LIMITED_DATA_LOSS by default. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing - * a long running operation. Its `promise()` method returns a promise - * you can `await` for. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/cloud_redis.failover_instance.js - * region_tag:redis_v1beta1_generated_CloudRedis_FailoverInstance_async - */ + /** + * Initiates a failover of the master node to current replica node for a + * specific STANDARD tier Cloud Memorystore for Redis instance. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Redis instance resource name using the form: + * `projects/{project_id}/locations/{location_id}/instances/{instance_id}` + * where `location_id` refers to a GCP region. + * @param {google.cloud.redis.v1beta1.FailoverInstanceRequest.DataProtectionMode} [request.dataProtectionMode] + * Optional. Available data protection modes that the user can choose. If it's + * unspecified, data protection mode will be LIMITED_DATA_LOSS by default. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/cloud_redis.failover_instance.js + * region_tag:redis_v1beta1_generated_CloudRedis_FailoverInstance_async + */ failoverInstance( - request?: protos.google.cloud.redis.v1beta1.IFailoverInstanceRequest, - options?: CallOptions): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>; + request?: protos.google.cloud.redis.v1beta1.IFailoverInstanceRequest, + options?: CallOptions, + ): Promise< + [ + LROperation< + protos.google.cloud.redis.v1beta1.IInstance, + protos.google.protobuf.IAny + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; failoverInstance( - request: protos.google.cloud.redis.v1beta1.IFailoverInstanceRequest, - options: CallOptions, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.redis.v1beta1.IFailoverInstanceRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.cloud.redis.v1beta1.IInstance, + protos.google.protobuf.IAny + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; failoverInstance( - request: protos.google.cloud.redis.v1beta1.IFailoverInstanceRequest, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.redis.v1beta1.IFailoverInstanceRequest, + callback: Callback< + LROperation< + protos.google.cloud.redis.v1beta1.IInstance, + protos.google.protobuf.IAny + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; failoverInstance( - request?: protos.google.cloud.redis.v1beta1.IFailoverInstanceRequest, - optionsOrCallback?: CallOptions|Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>, - callback?: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>|void { + request?: protos.google.cloud.redis.v1beta1.IFailoverInstanceRequest, + optionsOrCallback?: + | CallOptions + | Callback< + LROperation< + protos.google.cloud.redis.v1beta1.IInstance, + protos.google.protobuf.IAny + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + callback?: Callback< + LROperation< + protos.google.cloud.redis.v1beta1.IInstance, + protos.google.protobuf.IAny + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + LROperation< + protos.google.cloud.redis.v1beta1.IInstance, + protos.google.protobuf.IAny + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + LROperation< + protos.google.cloud.redis.v1beta1.IInstance, + protos.google.protobuf.IAny + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, rawResponse, _) => { this._log.info('failoverInstance response %j', rawResponse); callback!(error, response, rawResponse, _); // We verified callback above. } : undefined; this._log.info('failoverInstance request %j', request); - return this.innerApiCalls.failoverInstance(request, options, wrappedCallback) - ?.then(([response, rawResponse, _]: [ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]) => { - this._log.info('failoverInstance response %j', rawResponse); - return [response, rawResponse, _]; - }); + return this.innerApiCalls + .failoverInstance(request, options, wrappedCallback) + ?.then( + ([response, rawResponse, _]: [ + LROperation< + protos.google.cloud.redis.v1beta1.IInstance, + protos.google.protobuf.IAny + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ]) => { + this._log.info('failoverInstance response %j', rawResponse); + return [response, rawResponse, _]; + }, + ); } -/** - * Check the status of the long running operation returned by `failoverInstance()`. - * @param {String} name - * The operation name that will be passed. - * @returns {Promise} - The promise which resolves to an object. - * The decoded operation object has result and metadata field to get information from. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/cloud_redis.failover_instance.js - * region_tag:redis_v1beta1_generated_CloudRedis_FailoverInstance_async - */ - async checkFailoverInstanceProgress(name: string): Promise>{ + /** + * Check the status of the long running operation returned by `failoverInstance()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/cloud_redis.failover_instance.js + * region_tag:redis_v1beta1_generated_CloudRedis_FailoverInstance_async + */ + async checkFailoverInstanceProgress( + name: string, + ): Promise< + LROperation< + protos.google.cloud.redis.v1beta1.Instance, + protos.google.protobuf.Any + > + > { this._log.info('failoverInstance long-running'); - const request = new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest({name}); + const request = + new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( + { name }, + ); const [operation] = await this.operationsClient.getOperation(request); - const decodeOperation = new this._gaxModule.Operation(operation, this.descriptors.longrunning.failoverInstance, this._gaxModule.createDefaultBackoffSettings()); - return decodeOperation as LROperation; + const decodeOperation = new this._gaxModule.Operation( + operation, + this.descriptors.longrunning.failoverInstance, + this._gaxModule.createDefaultBackoffSettings(), + ); + return decodeOperation as LROperation< + protos.google.cloud.redis.v1beta1.Instance, + protos.google.protobuf.Any + >; } -/** - * Deletes a specific Redis instance. Instance stops serving and data is - * deleted. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. Redis instance resource name using the form: - * `projects/{project_id}/locations/{location_id}/instances/{instance_id}` - * where `location_id` refers to a GCP region. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing - * a long running operation. Its `promise()` method returns a promise - * you can `await` for. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/cloud_redis.delete_instance.js - * region_tag:redis_v1beta1_generated_CloudRedis_DeleteInstance_async - */ + /** + * Deletes a specific Redis instance. Instance stops serving and data is + * deleted. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Redis instance resource name using the form: + * `projects/{project_id}/locations/{location_id}/instances/{instance_id}` + * where `location_id` refers to a GCP region. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/cloud_redis.delete_instance.js + * region_tag:redis_v1beta1_generated_CloudRedis_DeleteInstance_async + */ deleteInstance( - request?: protos.google.cloud.redis.v1beta1.IDeleteInstanceRequest, - options?: CallOptions): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>; + request?: protos.google.cloud.redis.v1beta1.IDeleteInstanceRequest, + options?: CallOptions, + ): Promise< + [ + LROperation, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; deleteInstance( - request: protos.google.cloud.redis.v1beta1.IDeleteInstanceRequest, - options: CallOptions, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.redis.v1beta1.IDeleteInstanceRequest, + options: CallOptions, + callback: Callback< + LROperation, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; deleteInstance( - request: protos.google.cloud.redis.v1beta1.IDeleteInstanceRequest, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.redis.v1beta1.IDeleteInstanceRequest, + callback: Callback< + LROperation, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; deleteInstance( - request?: protos.google.cloud.redis.v1beta1.IDeleteInstanceRequest, - optionsOrCallback?: CallOptions|Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>, - callback?: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>|void { + request?: protos.google.cloud.redis.v1beta1.IDeleteInstanceRequest, + optionsOrCallback?: + | CallOptions + | Callback< + LROperation< + protos.google.protobuf.IEmpty, + protos.google.protobuf.IAny + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + callback?: Callback< + LROperation, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + LROperation, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + LROperation< + protos.google.protobuf.IEmpty, + protos.google.protobuf.IAny + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, rawResponse, _) => { this._log.info('deleteInstance response %j', rawResponse); callback!(error, response, rawResponse, _); // We verified callback above. } : undefined; this._log.info('deleteInstance request %j', request); - return this.innerApiCalls.deleteInstance(request, options, wrappedCallback) - ?.then(([response, rawResponse, _]: [ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]) => { - this._log.info('deleteInstance response %j', rawResponse); - return [response, rawResponse, _]; - }); + return this.innerApiCalls + .deleteInstance(request, options, wrappedCallback) + ?.then( + ([response, rawResponse, _]: [ + LROperation< + protos.google.protobuf.IEmpty, + protos.google.protobuf.IAny + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ]) => { + this._log.info('deleteInstance response %j', rawResponse); + return [response, rawResponse, _]; + }, + ); } -/** - * Check the status of the long running operation returned by `deleteInstance()`. - * @param {String} name - * The operation name that will be passed. - * @returns {Promise} - The promise which resolves to an object. - * The decoded operation object has result and metadata field to get information from. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/cloud_redis.delete_instance.js - * region_tag:redis_v1beta1_generated_CloudRedis_DeleteInstance_async - */ - async checkDeleteInstanceProgress(name: string): Promise>{ + /** + * Check the status of the long running operation returned by `deleteInstance()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/cloud_redis.delete_instance.js + * region_tag:redis_v1beta1_generated_CloudRedis_DeleteInstance_async + */ + async checkDeleteInstanceProgress( + name: string, + ): Promise< + LROperation + > { this._log.info('deleteInstance long-running'); - const request = new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest({name}); + const request = + new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( + { name }, + ); const [operation] = await this.operationsClient.getOperation(request); - const decodeOperation = new this._gaxModule.Operation(operation, this.descriptors.longrunning.deleteInstance, this._gaxModule.createDefaultBackoffSettings()); - return decodeOperation as LROperation; + const decodeOperation = new this._gaxModule.Operation( + operation, + this.descriptors.longrunning.deleteInstance, + this._gaxModule.createDefaultBackoffSettings(), + ); + return decodeOperation as LROperation< + protos.google.protobuf.Empty, + protos.google.protobuf.Any + >; } - /** - * Lists all Redis instances owned by a project in either the specified - * location (region) or all locations. - * - * The location should have the following format: - * * `projects/{project_id}/locations/{location_id}` - * - * If `location_id` is specified as `-` (wildcard), then all regions - * available to the project are queried, and the results are aggregated. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The resource name of the instance location using the form: - * `projects/{project_id}/locations/{location_id}` - * where `location_id` refers to a GCP region. - * @param {number} request.pageSize - * The maximum number of items to return. - * - * If not specified, a default value of 1000 will be used by the service. - * Regardless of the page_size value, the response may include a partial list - * and a caller should only rely on response's - * {@link protos.CloudRedis.ListInstancesResponse.next_page_token|next_page_token} - * to determine if there are more instances left to be queried. - * @param {string} request.pageToken - * The next_page_token value returned from a previous List request, - * if any. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.cloud.redis.v1beta1.Instance|Instance}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `listInstancesAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Lists all Redis instances owned by a project in either the specified + * location (region) or all locations. + * + * The location should have the following format: + * * `projects/{project_id}/locations/{location_id}` + * + * If `location_id` is specified as `-` (wildcard), then all regions + * available to the project are queried, and the results are aggregated. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The resource name of the instance location using the form: + * `projects/{project_id}/locations/{location_id}` + * where `location_id` refers to a GCP region. + * @param {number} request.pageSize + * The maximum number of items to return. + * + * If not specified, a default value of 1000 will be used by the service. + * Regardless of the page_size value, the response may include a partial list + * and a caller should only rely on response's + * {@link protos.CloudRedis.ListInstancesResponse.next_page_token|next_page_token} + * to determine if there are more instances left to be queried. + * @param {string} request.pageToken + * The next_page_token value returned from a previous List request, + * if any. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.cloud.redis.v1beta1.Instance|Instance}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listInstancesAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listInstances( - request?: protos.google.cloud.redis.v1beta1.IListInstancesRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.redis.v1beta1.IInstance[], - protos.google.cloud.redis.v1beta1.IListInstancesRequest|null, - protos.google.cloud.redis.v1beta1.IListInstancesResponse - ]>; + request?: protos.google.cloud.redis.v1beta1.IListInstancesRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.redis.v1beta1.IInstance[], + protos.google.cloud.redis.v1beta1.IListInstancesRequest | null, + protos.google.cloud.redis.v1beta1.IListInstancesResponse, + ] + >; listInstances( - request: protos.google.cloud.redis.v1beta1.IListInstancesRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.cloud.redis.v1beta1.IListInstancesRequest, - protos.google.cloud.redis.v1beta1.IListInstancesResponse|null|undefined, - protos.google.cloud.redis.v1beta1.IInstance>): void; + request: protos.google.cloud.redis.v1beta1.IListInstancesRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.cloud.redis.v1beta1.IListInstancesRequest, + | protos.google.cloud.redis.v1beta1.IListInstancesResponse + | null + | undefined, + protos.google.cloud.redis.v1beta1.IInstance + >, + ): void; listInstances( - request: protos.google.cloud.redis.v1beta1.IListInstancesRequest, - callback: PaginationCallback< - protos.google.cloud.redis.v1beta1.IListInstancesRequest, - protos.google.cloud.redis.v1beta1.IListInstancesResponse|null|undefined, - protos.google.cloud.redis.v1beta1.IInstance>): void; + request: protos.google.cloud.redis.v1beta1.IListInstancesRequest, + callback: PaginationCallback< + protos.google.cloud.redis.v1beta1.IListInstancesRequest, + | protos.google.cloud.redis.v1beta1.IListInstancesResponse + | null + | undefined, + protos.google.cloud.redis.v1beta1.IInstance + >, + ): void; listInstances( - request?: protos.google.cloud.redis.v1beta1.IListInstancesRequest, - optionsOrCallback?: CallOptions|PaginationCallback< - protos.google.cloud.redis.v1beta1.IListInstancesRequest, - protos.google.cloud.redis.v1beta1.IListInstancesResponse|null|undefined, - protos.google.cloud.redis.v1beta1.IInstance>, - callback?: PaginationCallback< + request?: protos.google.cloud.redis.v1beta1.IListInstancesRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.cloud.redis.v1beta1.IListInstancesRequest, - protos.google.cloud.redis.v1beta1.IListInstancesResponse|null|undefined, - protos.google.cloud.redis.v1beta1.IInstance>): - Promise<[ - protos.google.cloud.redis.v1beta1.IInstance[], - protos.google.cloud.redis.v1beta1.IListInstancesRequest|null, - protos.google.cloud.redis.v1beta1.IListInstancesResponse - ]>|void { + | protos.google.cloud.redis.v1beta1.IListInstancesResponse + | null + | undefined, + protos.google.cloud.redis.v1beta1.IInstance + >, + callback?: PaginationCallback< + protos.google.cloud.redis.v1beta1.IListInstancesRequest, + | protos.google.cloud.redis.v1beta1.IListInstancesResponse + | null + | undefined, + protos.google.cloud.redis.v1beta1.IInstance + >, + ): Promise< + [ + protos.google.cloud.redis.v1beta1.IInstance[], + protos.google.cloud.redis.v1beta1.IListInstancesRequest | null, + protos.google.cloud.redis.v1beta1.IListInstancesResponse, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.cloud.redis.v1beta1.IListInstancesRequest, - protos.google.cloud.redis.v1beta1.IListInstancesResponse|null|undefined, - protos.google.cloud.redis.v1beta1.IInstance>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.cloud.redis.v1beta1.IListInstancesRequest, + | protos.google.cloud.redis.v1beta1.IListInstancesResponse + | null + | undefined, + protos.google.cloud.redis.v1beta1.IInstance + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listInstances values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -1328,127 +1819,131 @@ export class CloudRedisClient { this._log.info('listInstances request %j', request); return this.innerApiCalls .listInstances(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.cloud.redis.v1beta1.IInstance[], - protos.google.cloud.redis.v1beta1.IListInstancesRequest|null, - protos.google.cloud.redis.v1beta1.IListInstancesResponse - ]) => { - this._log.info('listInstances values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.cloud.redis.v1beta1.IInstance[], + protos.google.cloud.redis.v1beta1.IListInstancesRequest | null, + protos.google.cloud.redis.v1beta1.IListInstancesResponse, + ]) => { + this._log.info('listInstances values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listInstances`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The resource name of the instance location using the form: - * `projects/{project_id}/locations/{location_id}` - * where `location_id` refers to a GCP region. - * @param {number} request.pageSize - * The maximum number of items to return. - * - * If not specified, a default value of 1000 will be used by the service. - * Regardless of the page_size value, the response may include a partial list - * and a caller should only rely on response's - * {@link protos.CloudRedis.ListInstancesResponse.next_page_token|next_page_token} - * to determine if there are more instances left to be queried. - * @param {string} request.pageToken - * The next_page_token value returned from a previous List request, - * if any. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.cloud.redis.v1beta1.Instance|Instance} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `listInstancesAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `listInstances`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The resource name of the instance location using the form: + * `projects/{project_id}/locations/{location_id}` + * where `location_id` refers to a GCP region. + * @param {number} request.pageSize + * The maximum number of items to return. + * + * If not specified, a default value of 1000 will be used by the service. + * Regardless of the page_size value, the response may include a partial list + * and a caller should only rely on response's + * {@link protos.CloudRedis.ListInstancesResponse.next_page_token|next_page_token} + * to determine if there are more instances left to be queried. + * @param {string} request.pageToken + * The next_page_token value returned from a previous List request, + * if any. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.cloud.redis.v1beta1.Instance|Instance} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listInstancesAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listInstancesStream( - request?: protos.google.cloud.redis.v1beta1.IListInstancesRequest, - options?: CallOptions): - Transform{ + request?: protos.google.cloud.redis.v1beta1.IListInstancesRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); const defaultCallSettings = this._defaults['listInstances']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listInstances stream %j', request); return this.descriptors.page.listInstances.createStream( this.innerApiCalls.listInstances as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listInstances`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The resource name of the instance location using the form: - * `projects/{project_id}/locations/{location_id}` - * where `location_id` refers to a GCP region. - * @param {number} request.pageSize - * The maximum number of items to return. - * - * If not specified, a default value of 1000 will be used by the service. - * Regardless of the page_size value, the response may include a partial list - * and a caller should only rely on response's - * {@link protos.CloudRedis.ListInstancesResponse.next_page_token|next_page_token} - * to determine if there are more instances left to be queried. - * @param {string} request.pageToken - * The next_page_token value returned from a previous List request, - * if any. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.cloud.redis.v1beta1.Instance|Instance}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/cloud_redis.list_instances.js - * region_tag:redis_v1beta1_generated_CloudRedis_ListInstances_async - */ + /** + * Equivalent to `listInstances`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The resource name of the instance location using the form: + * `projects/{project_id}/locations/{location_id}` + * where `location_id` refers to a GCP region. + * @param {number} request.pageSize + * The maximum number of items to return. + * + * If not specified, a default value of 1000 will be used by the service. + * Regardless of the page_size value, the response may include a partial list + * and a caller should only rely on response's + * {@link protos.CloudRedis.ListInstancesResponse.next_page_token|next_page_token} + * to determine if there are more instances left to be queried. + * @param {string} request.pageToken + * The next_page_token value returned from a previous List request, + * if any. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.cloud.redis.v1beta1.Instance|Instance}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/cloud_redis.list_instances.js + * region_tag:redis_v1beta1_generated_CloudRedis_ListInstances_async + */ listInstancesAsync( - request?: protos.google.cloud.redis.v1beta1.IListInstancesRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.cloud.redis.v1beta1.IListInstancesRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); const defaultCallSettings = this._defaults['listInstances']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listInstances iterate %j', request); return this.descriptors.page.listInstances.asyncIterate( this.innerApiCalls['listInstances'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } -/** + /** * Gets the latest state of a long-running operation. Clients can use this * method to poll the operation result at intervals as recommended by the API * service. @@ -1491,22 +1986,22 @@ export class CloudRedisClient { protos.google.longrunning.Operation, protos.google.longrunning.GetOperationRequest, {} | null | undefined - > + >, ): Promise<[protos.google.longrunning.Operation]> { - let options: gax.CallOptions; - if (typeof optionsOrCallback === 'function' && callback === undefined) { - callback = optionsOrCallback; - options = {}; - } else { - options = optionsOrCallback as gax.CallOptions; - } - options = options || {}; - options.otherArgs = options.otherArgs || {}; - options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers['x-goog-request-params'] = - this._gaxModule.routingHeader.fromParams({ - name: request.name ?? '', - }); + let options: gax.CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as gax.CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); return this.operationsClient.getOperation(request, options, callback); } /** @@ -1541,15 +2036,15 @@ export class CloudRedisClient { */ listOperationsAsync( request: protos.google.longrunning.ListOperationsRequest, - options?: gax.CallOptions + options?: gax.CallOptions, ): AsyncIterable { - options = options || {}; - options.otherArgs = options.otherArgs || {}; - options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers['x-goog-request-params'] = - this._gaxModule.routingHeader.fromParams({ - name: request.name ?? '', - }); + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); return this.operationsClient.listOperationsAsync(request, options); } /** @@ -1583,7 +2078,7 @@ export class CloudRedisClient { * await client.cancelOperation({name: ''}); * ``` */ - cancelOperation( + cancelOperation( request: protos.google.longrunning.CancelOperationRequest, optionsOrCallback?: | gax.CallOptions @@ -1596,22 +2091,22 @@ export class CloudRedisClient { protos.google.longrunning.CancelOperationRequest, protos.google.protobuf.Empty, {} | undefined | null - > + >, ): Promise { - let options: gax.CallOptions; - if (typeof optionsOrCallback === 'function' && callback === undefined) { - callback = optionsOrCallback; - options = {}; - } else { - options = optionsOrCallback as gax.CallOptions; - } - options = options || {}; - options.otherArgs = options.otherArgs || {}; - options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers['x-goog-request-params'] = - this._gaxModule.routingHeader.fromParams({ - name: request.name ?? '', - }); + let options: gax.CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as gax.CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); return this.operationsClient.cancelOperation(request, options, callback); } /** @@ -1652,22 +2147,22 @@ export class CloudRedisClient { protos.google.protobuf.Empty, protos.google.longrunning.DeleteOperationRequest, {} | null | undefined - > + >, ): Promise { - let options: gax.CallOptions; - if (typeof optionsOrCallback === 'function' && callback === undefined) { - callback = optionsOrCallback; - options = {}; - } else { - options = optionsOrCallback as gax.CallOptions; - } - options = options || {}; - options.otherArgs = options.otherArgs || {}; - options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers['x-goog-request-params'] = - this._gaxModule.routingHeader.fromParams({ - name: request.name ?? '', - }); + let options: gax.CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as gax.CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); return this.operationsClient.deleteOperation(request, options, callback); } @@ -1683,7 +2178,7 @@ export class CloudRedisClient { * @param {string} instance * @returns {string} Resource name string. */ - instancePath(project:string,location:string,instance:string) { + instancePath(project: string, location: string, instance: string) { return this.pathTemplates.instancePathTemplate.render({ project: project, location: location, @@ -1731,7 +2226,7 @@ export class CloudRedisClient { * @param {string} location * @returns {string} Resource name string. */ - locationPath(project:string,location:string) { + locationPath(project: string, location: string) { return this.pathTemplates.locationPathTemplate.render({ project: project, location: location, @@ -1768,7 +2263,7 @@ export class CloudRedisClient { */ close(): Promise { if (this.cloudRedisStub && !this._terminated) { - return this.cloudRedisStub.then(stub => { + return this.cloudRedisStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -1777,4 +2272,4 @@ export class CloudRedisClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/core/generator/gapic-generator-typescript/baselines/redis/src/v1beta1/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/redis/src/v1beta1/index.ts.baseline index 6e57dc3915dd..7fde8f4375a4 100644 --- a/core/generator/gapic-generator-typescript/baselines/redis/src/v1beta1/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/redis/src/v1beta1/index.ts.baseline @@ -16,4 +16,4 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -export {CloudRedisClient} from './cloud_redis_client'; +export { CloudRedisClient } from './cloud_redis_client'; diff --git a/core/generator/gapic-generator-typescript/baselines/redis/system-test/fixtures/sample/src/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/redis/system-test/fixtures/sample/src/index.ts.baseline index 5ca80129b7e0..8b2db962a5db 100644 --- a/core/generator/gapic-generator-typescript/baselines/redis/system-test/fixtures/sample/src/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/redis/system-test/fixtures/sample/src/index.ts.baseline @@ -16,7 +16,7 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -import {CloudRedisClient} from 'redis'; +import { CloudRedisClient } from 'redis'; // check that the client class type name can be used function doStuffWithCloudRedisClient(client: CloudRedisClient) { diff --git a/core/generator/gapic-generator-typescript/baselines/redis/system-test/install.ts.baseline b/core/generator/gapic-generator-typescript/baselines/redis/system-test/install.ts.baseline index f66069aa3940..ccf167042d2e 100644 --- a/core/generator/gapic-generator-typescript/baselines/redis/system-test/install.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/redis/system-test/install.ts.baseline @@ -16,34 +16,36 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -import {packNTest} from 'pack-n-play'; -import {readFileSync} from 'fs'; -import {describe, it} from 'mocha'; +import { packNTest } from 'pack-n-play'; +import { readFileSync } from 'fs'; +import { describe, it } from 'mocha'; describe('📦 pack-n-play test', () => { - - it('TypeScript code', async function() { + it('TypeScript code', async function () { this.timeout(300000); const options = { packageDir: process.cwd(), sample: { description: 'TypeScript user can use the type definitions', - ts: readFileSync('./system-test/fixtures/sample/src/index.ts').toString() - } + ts: readFileSync( + './system-test/fixtures/sample/src/index.ts', + ).toString(), + }, }; await packNTest(options); }); - it('JavaScript code', async function() { + it('JavaScript code', async function () { this.timeout(300000); const options = { packageDir: process.cwd(), sample: { description: 'JavaScript user can use the library', - cjs: readFileSync('./system-test/fixtures/sample/src/index.js').toString() - } + cjs: readFileSync( + './system-test/fixtures/sample/src/index.js', + ).toString(), + }, }; await packNTest(options); }); - }); diff --git a/core/generator/gapic-generator-typescript/baselines/redis/test/gapic_cloud_redis_v1beta1.ts.baseline b/core/generator/gapic-generator-typescript/baselines/redis/test/gapic_cloud_redis_v1beta1.ts.baseline index 37c85361962e..7099a8cf6b8f 100644 --- a/core/generator/gapic-generator-typescript/baselines/redis/test/gapic_cloud_redis_v1beta1.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/redis/test/gapic_cloud_redis_v1beta1.ts.baseline @@ -19,1882 +19,2364 @@ import * as protos from '../protos/protos'; import * as assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as cloudredisModule from '../src'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; -import {protobuf, LROperation, operationsProtos} from 'google-gax'; +import { protobuf, LROperation, operationsProtos } from 'google-gax'; // Dynamically loaded proto JSON is needed to get the type information // to fill in default values for request objects -const root = protobuf.Root.fromJSON(require('../protos/protos.json')).resolveAll(); +const root = protobuf.Root.fromJSON( + require('../protos/protos.json'), +).resolveAll(); // eslint-disable-next-line @typescript-eslint/no-unused-vars function getTypeDefaultValue(typeName: string, fields: string[]) { - let type = root.lookupType(typeName) as protobuf.Type; - for (const field of fields.slice(0, -1)) { - type = type.fields[field]?.resolvedType as protobuf.Type; - } - return type.fields[fields[fields.length - 1]]?.defaultValue; + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type.fields[field]?.resolvedType as protobuf.Type; + } + return type.fields[fields[fields.length - 1]]?.defaultValue; } function generateSampleMessage(instance: T) { - const filledObject = (instance.constructor as typeof protobuf.Message) - .toObject(instance as protobuf.Message, {defaults: true}); - return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, { defaults: true }); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; } function stubSimpleCall(response?: ResponseType, error?: Error) { - return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); } -function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { - return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +function stubSimpleCallWithCallback( + response?: ResponseType, + error?: Error, +) { + return error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); } -function stubLongRunningCall(response?: ResponseType, callError?: Error, lroError?: Error) { - const innerStub = lroError ? sinon.stub().rejects(lroError) : sinon.stub().resolves([response]); - const mockOperation = { - promise: innerStub, - }; - return callError ? sinon.stub().rejects(callError) : sinon.stub().resolves([mockOperation]); +function stubLongRunningCall( + response?: ResponseType, + callError?: Error, + lroError?: Error, +) { + const innerStub = lroError + ? sinon.stub().rejects(lroError) + : sinon.stub().resolves([response]); + const mockOperation = { + promise: innerStub, + }; + return callError + ? sinon.stub().rejects(callError) + : sinon.stub().resolves([mockOperation]); } -function stubLongRunningCallWithCallback(response?: ResponseType, callError?: Error, lroError?: Error) { - const innerStub = lroError ? sinon.stub().rejects(lroError) : sinon.stub().resolves([response]); - const mockOperation = { - promise: innerStub, - }; - return callError ? sinon.stub().callsArgWith(2, callError) : sinon.stub().callsArgWith(2, null, mockOperation); +function stubLongRunningCallWithCallback( + response?: ResponseType, + callError?: Error, + lroError?: Error, +) { + const innerStub = lroError + ? sinon.stub().rejects(lroError) + : sinon.stub().resolves([response]); + const mockOperation = { + promise: innerStub, + }; + return callError + ? sinon.stub().callsArgWith(2, callError) + : sinon.stub().callsArgWith(2, null, mockOperation); } -function stubPageStreamingCall(responses?: ResponseType[], error?: Error) { - const pagingStub = sinon.stub(); - if (responses) { - for (let i = 0; i < responses.length; ++i) { - pagingStub.onCall(i).callsArgWith(2, null, responses[i]); - } +function stubPageStreamingCall( + responses?: ResponseType[], + error?: Error, +) { + const pagingStub = sinon.stub(); + if (responses) { + for (let i = 0; i < responses.length; ++i) { + pagingStub.onCall(i).callsArgWith(2, null, responses[i]); } - const transformStub = error ? sinon.stub().callsArgWith(2, error) : pagingStub; - const mockStream = new PassThrough({ - objectMode: true, - transform: transformStub, - }); - // trigger as many responses as needed - if (responses) { - for (let i = 0; i < responses.length; ++i) { - setImmediate(() => { mockStream.write({}); }); - } - setImmediate(() => { mockStream.end(); }); - } else { - setImmediate(() => { mockStream.write({}); }); - setImmediate(() => { mockStream.end(); }); + } + const transformStub = error + ? sinon.stub().callsArgWith(2, error) + : pagingStub; + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + // trigger as many responses as needed + if (responses) { + for (let i = 0; i < responses.length; ++i) { + setImmediate(() => { + mockStream.write({}); + }); } - return sinon.stub().returns(mockStream); + setImmediate(() => { + mockStream.end(); + }); + } else { + setImmediate(() => { + mockStream.write({}); + }); + setImmediate(() => { + mockStream.end(); + }); + } + return sinon.stub().returns(mockStream); } -function stubAsyncIterationCall(responses?: ResponseType[], error?: Error) { - let counter = 0; - const asyncIterable = { - [Symbol.asyncIterator]() { - return { - async next() { - if (error) { - return Promise.reject(error); - } - if (counter >= responses!.length) { - return Promise.resolve({done: true, value: undefined}); - } - return Promise.resolve({done: false, value: responses![counter++]}); - } - }; - } - }; - return sinon.stub().returns(asyncIterable); +function stubAsyncIterationCall( + responses?: ResponseType[], + error?: Error, +) { + let counter = 0; + const asyncIterable = { + [Symbol.asyncIterator]() { + return { + async next() { + if (error) { + return Promise.reject(error); + } + if (counter >= responses!.length) { + return Promise.resolve({ done: true, value: undefined }); + } + return Promise.resolve({ done: false, value: responses![counter++] }); + }, + }; + }, + }; + return sinon.stub().returns(asyncIterable); } describe('v1beta1.CloudRedisClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'redis.googleapis.com'); - }); - - it('has universeDomain', () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); - - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - it('throws DeprecationWarning if static servicePath is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const servicePath = cloudredisModule.v1beta1.CloudRedisClient.servicePath; - assert.strictEqual(servicePath, 'redis.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = cloudredisModule.v1beta1.CloudRedisClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'redis.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'redis.example.com'); - }); - - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'redis.example.com'); - }); - - if (typeof process === 'object' && 'env' in process) { - describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { - it('sets apiEndpoint from environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new cloudredisModule.v1beta1.CloudRedisClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'redis.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - - it('value configured in code has priority over environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new cloudredisModule.v1beta1.CloudRedisClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'redis.configured.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { new cloudredisModule.v1beta1.CloudRedisClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); - - it('has port', () => { - const port = cloudredisModule.v1beta1.CloudRedisClient.port; - assert(port); - assert(typeof port === 'number'); - }); - - it('should create a client with no option', () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient(); - assert(client); - }); - - it('should create a client with gRPC fallback', () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - fallback: true, - }); - assert(client); - }); - - it('has initialize method and supports deferred initialization', async () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.cloudRedisStub, undefined); - await client.initialize(); - assert(client.cloudRedisStub); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'redis.googleapis.com'); + }); - it('has close method for the initialized client', done => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.cloudRedisStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('has universeDomain', () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - it('has close method for the non-initialized client', done => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.cloudRedisStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = + cloudredisModule.v1beta1.CloudRedisClient.servicePath; + assert.strictEqual(servicePath, 'redis.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + cloudredisModule.v1beta1.CloudRedisClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'redis.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + universeDomain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'redis.example.com'); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); - }); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + universe_domain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'redis.example.com'); + }); - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId((err?: Error|null, projectId?: string|null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } - }); - }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); + if (typeof process === 'object' && 'env' in process) { + describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { + it('sets apiEndpoint from environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new cloudredisModule.v1beta1.CloudRedisClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'redis.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } + }); + + it('value configured in code has priority over environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + universeDomain: 'configured.example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'redis.configured.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } + }); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new cloudredisModule.v1beta1.CloudRedisClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); }); - describe('getInstance', () => { - it('invokes getInstance without error', async () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.redis.v1beta1.GetInstanceRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.redis.v1beta1.GetInstanceRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.redis.v1beta1.Instance() - ); - client.innerApiCalls.getInstance = stubSimpleCall(expectedResponse); - const [response] = await client.getInstance(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getInstance as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getInstance as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has port', () => { + const port = cloudredisModule.v1beta1.CloudRedisClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('invokes getInstance without error using callback', async () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.redis.v1beta1.GetInstanceRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.redis.v1beta1.GetInstanceRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.redis.v1beta1.Instance() - ); - client.innerApiCalls.getInstance = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getInstance( - request, - (err?: Error|null, result?: protos.google.cloud.redis.v1beta1.IInstance|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getInstance as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getInstance as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('should create a client with no option', () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient(); + assert(client); + }); - it('invokes getInstance with error', async () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.redis.v1beta1.GetInstanceRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.redis.v1beta1.GetInstanceRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getInstance = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getInstance(request), expectedError); - const actualRequest = (client.innerApiCalls.getInstance as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getInstance as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('should create a client with gRPC fallback', () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + fallback: true, + }); + assert(client); + }); - it('invokes getInstance with closed client', async () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.redis.v1beta1.GetInstanceRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.redis.v1beta1.GetInstanceRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getInstance(request), expectedError); - }); + it('has initialize method and supports deferred initialization', async () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.cloudRedisStub, undefined); + await client.initialize(); + assert(client.cloudRedisStub); }); - describe('createInstance', () => { - it('invokes createInstance without error', async () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.redis.v1beta1.CreateInstanceRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.redis.v1beta1.CreateInstanceRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.createInstance = stubLongRunningCall(expectedResponse); - const [operation] = await client.createInstance(request); - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createInstance as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createInstance as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('has close method for the initialized client', (done) => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.cloudRedisStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes createInstance without error using callback', async () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.redis.v1beta1.CreateInstanceRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.redis.v1beta1.CreateInstanceRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.createInstance = stubLongRunningCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createInstance( - request, - (err?: Error|null, - result?: LROperation|null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const operation = await promise as LROperation; - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createInstance as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createInstance as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('has close method for the non-initialized client', (done) => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.cloudRedisStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes createInstance with call error', async () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.redis.v1beta1.CreateInstanceRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.redis.v1beta1.CreateInstanceRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createInstance = stubLongRunningCall(undefined, expectedError); - await assert.rejects(client.createInstance(request), expectedError); - const actualRequest = (client.innerApiCalls.createInstance as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createInstance as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + }); - it('invokes createInstance with LRO error', async () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.redis.v1beta1.CreateInstanceRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.redis.v1beta1.CreateInstanceRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createInstance = stubLongRunningCall(undefined, undefined, expectedError); - const [operation] = await client.createInstance(request); - await assert.rejects(operation.promise(), expectedError); - const actualRequest = (client.innerApiCalls.createInstance as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createInstance as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } + }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + }); + + describe('getInstance', () => { + it('invokes getInstance without error', async () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.redis.v1beta1.GetInstanceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.redis.v1beta1.GetInstanceRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.redis.v1beta1.Instance(), + ); + client.innerApiCalls.getInstance = stubSimpleCall(expectedResponse); + const [response] = await client.getInstance(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getInstance as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getInstance as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkCreateInstanceProgress without error', async () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedResponse = generateSampleMessage( - new operationsProtos.google.longrunning.Operation() - ); - expectedResponse.name = 'test'; - expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; - expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')} - - client.operationsClient.getOperation = stubSimpleCall(expectedResponse); - const decodedOperation = await client.checkCreateInstanceProgress(expectedResponse.name); - assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); - assert(decodedOperation.metadata); - assert((client.operationsClient.getOperation as SinonStub).getCall(0)); - }); + it('invokes getInstance without error using callback', async () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.redis.v1beta1.GetInstanceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.redis.v1beta1.GetInstanceRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.redis.v1beta1.Instance(), + ); + client.innerApiCalls.getInstance = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getInstance( + request, + ( + err?: Error | null, + result?: protos.google.cloud.redis.v1beta1.IInstance | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getInstance as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getInstance as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkCreateInstanceProgress with error', async () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedError = new Error('expected'); - - client.operationsClient.getOperation = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.checkCreateInstanceProgress(''), expectedError); - assert((client.operationsClient.getOperation as SinonStub) - .getCall(0)); - }); + it('invokes getInstance with error', async () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.redis.v1beta1.GetInstanceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.redis.v1beta1.GetInstanceRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getInstance = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getInstance(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getInstance as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getInstance as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('updateInstance', () => { - it('invokes updateInstance without error', async () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.redis.v1beta1.UpdateInstanceRequest() - ); - request.instance ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.redis.v1beta1.UpdateInstanceRequest', ['instance', 'name']); - request.instance.name = defaultValue1; - const expectedHeaderRequestParams = `instance.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.updateInstance = stubLongRunningCall(expectedResponse); - const [operation] = await client.updateInstance(request); - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateInstance as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateInstance as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getInstance with closed client', async () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.redis.v1beta1.GetInstanceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.redis.v1beta1.GetInstanceRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getInstance(request), expectedError); + }); + }); + + describe('createInstance', () => { + it('invokes createInstance without error', async () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.redis.v1beta1.CreateInstanceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.redis.v1beta1.CreateInstanceRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.createInstance = + stubLongRunningCall(expectedResponse); + const [operation] = await client.createInstance(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createInstance as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createInstance as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateInstance without error using callback', async () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.redis.v1beta1.UpdateInstanceRequest() - ); - request.instance ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.redis.v1beta1.UpdateInstanceRequest', ['instance', 'name']); - request.instance.name = defaultValue1; - const expectedHeaderRequestParams = `instance.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.updateInstance = stubLongRunningCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateInstance( - request, - (err?: Error|null, - result?: LROperation|null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const operation = await promise as LROperation; - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateInstance as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateInstance as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createInstance without error using callback', async () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.redis.v1beta1.CreateInstanceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.redis.v1beta1.CreateInstanceRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.createInstance = + stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createInstance( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.cloud.redis.v1beta1.IInstance, + protos.google.protobuf.IAny + > | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const operation = (await promise) as LROperation< + protos.google.cloud.redis.v1beta1.IInstance, + protos.google.protobuf.IAny + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createInstance as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createInstance as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateInstance with call error', async () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.redis.v1beta1.UpdateInstanceRequest() - ); - request.instance ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.redis.v1beta1.UpdateInstanceRequest', ['instance', 'name']); - request.instance.name = defaultValue1; - const expectedHeaderRequestParams = `instance.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateInstance = stubLongRunningCall(undefined, expectedError); - await assert.rejects(client.updateInstance(request), expectedError); - const actualRequest = (client.innerApiCalls.updateInstance as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateInstance as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createInstance with call error', async () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.redis.v1beta1.CreateInstanceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.redis.v1beta1.CreateInstanceRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createInstance = stubLongRunningCall( + undefined, + expectedError, + ); + await assert.rejects(client.createInstance(request), expectedError); + const actualRequest = ( + client.innerApiCalls.createInstance as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createInstance as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateInstance with LRO error', async () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.redis.v1beta1.UpdateInstanceRequest() - ); - request.instance ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.redis.v1beta1.UpdateInstanceRequest', ['instance', 'name']); - request.instance.name = defaultValue1; - const expectedHeaderRequestParams = `instance.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateInstance = stubLongRunningCall(undefined, undefined, expectedError); - const [operation] = await client.updateInstance(request); - await assert.rejects(operation.promise(), expectedError); - const actualRequest = (client.innerApiCalls.updateInstance as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateInstance as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createInstance with LRO error', async () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.redis.v1beta1.CreateInstanceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.redis.v1beta1.CreateInstanceRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createInstance = stubLongRunningCall( + undefined, + undefined, + expectedError, + ); + const [operation] = await client.createInstance(request); + await assert.rejects(operation.promise(), expectedError); + const actualRequest = ( + client.innerApiCalls.createInstance as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createInstance as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkUpdateInstanceProgress without error', async () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedResponse = generateSampleMessage( - new operationsProtos.google.longrunning.Operation() - ); - expectedResponse.name = 'test'; - expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; - expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')} - - client.operationsClient.getOperation = stubSimpleCall(expectedResponse); - const decodedOperation = await client.checkUpdateInstanceProgress(expectedResponse.name); - assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); - assert(decodedOperation.metadata); - assert((client.operationsClient.getOperation as SinonStub).getCall(0)); - }); + it('invokes checkCreateInstanceProgress without error', async () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation(), + ); + expectedResponse.name = 'test'; + expectedResponse.response = { type_url: 'url', value: Buffer.from('') }; + expectedResponse.metadata = { type_url: 'url', value: Buffer.from('') }; + + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const decodedOperation = await client.checkCreateInstanceProgress( + expectedResponse.name, + ); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); - it('invokes checkUpdateInstanceProgress with error', async () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedError = new Error('expected'); - - client.operationsClient.getOperation = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.checkUpdateInstanceProgress(''), expectedError); - assert((client.operationsClient.getOperation as SinonStub) - .getCall(0)); - }); + it('invokes checkCreateInstanceProgress with error', async () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const expectedError = new Error('expected'); + + client.operationsClient.getOperation = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.checkCreateInstanceProgress(''), + expectedError, + ); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + }); + + describe('updateInstance', () => { + it('invokes updateInstance without error', async () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.redis.v1beta1.UpdateInstanceRequest(), + ); + request.instance ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.redis.v1beta1.UpdateInstanceRequest', + ['instance', 'name'], + ); + request.instance.name = defaultValue1; + const expectedHeaderRequestParams = `instance.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.updateInstance = + stubLongRunningCall(expectedResponse); + const [operation] = await client.updateInstance(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateInstance as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateInstance as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('importInstance', () => { - it('invokes importInstance without error', async () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.redis.v1beta1.ImportInstanceRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.redis.v1beta1.ImportInstanceRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.importInstance = stubLongRunningCall(expectedResponse); - const [operation] = await client.importInstance(request); - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.importInstance as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.importInstance as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateInstance without error using callback', async () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.redis.v1beta1.UpdateInstanceRequest(), + ); + request.instance ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.redis.v1beta1.UpdateInstanceRequest', + ['instance', 'name'], + ); + request.instance.name = defaultValue1; + const expectedHeaderRequestParams = `instance.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.updateInstance = + stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateInstance( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.cloud.redis.v1beta1.IInstance, + protos.google.protobuf.IAny + > | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const operation = (await promise) as LROperation< + protos.google.cloud.redis.v1beta1.IInstance, + protos.google.protobuf.IAny + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateInstance as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateInstance as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes importInstance without error using callback', async () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.redis.v1beta1.ImportInstanceRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.redis.v1beta1.ImportInstanceRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.importInstance = stubLongRunningCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.importInstance( - request, - (err?: Error|null, - result?: LROperation|null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const operation = await promise as LROperation; - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.importInstance as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.importInstance as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateInstance with call error', async () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.redis.v1beta1.UpdateInstanceRequest(), + ); + request.instance ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.redis.v1beta1.UpdateInstanceRequest', + ['instance', 'name'], + ); + request.instance.name = defaultValue1; + const expectedHeaderRequestParams = `instance.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateInstance = stubLongRunningCall( + undefined, + expectedError, + ); + await assert.rejects(client.updateInstance(request), expectedError); + const actualRequest = ( + client.innerApiCalls.updateInstance as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateInstance as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes importInstance with call error', async () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.redis.v1beta1.ImportInstanceRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.redis.v1beta1.ImportInstanceRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.importInstance = stubLongRunningCall(undefined, expectedError); - await assert.rejects(client.importInstance(request), expectedError); - const actualRequest = (client.innerApiCalls.importInstance as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.importInstance as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateInstance with LRO error', async () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.redis.v1beta1.UpdateInstanceRequest(), + ); + request.instance ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.redis.v1beta1.UpdateInstanceRequest', + ['instance', 'name'], + ); + request.instance.name = defaultValue1; + const expectedHeaderRequestParams = `instance.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateInstance = stubLongRunningCall( + undefined, + undefined, + expectedError, + ); + const [operation] = await client.updateInstance(request); + await assert.rejects(operation.promise(), expectedError); + const actualRequest = ( + client.innerApiCalls.updateInstance as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateInstance as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes importInstance with LRO error', async () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.redis.v1beta1.ImportInstanceRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.redis.v1beta1.ImportInstanceRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.importInstance = stubLongRunningCall(undefined, undefined, expectedError); - const [operation] = await client.importInstance(request); - await assert.rejects(operation.promise(), expectedError); - const actualRequest = (client.innerApiCalls.importInstance as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.importInstance as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes checkUpdateInstanceProgress without error', async () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation(), + ); + expectedResponse.name = 'test'; + expectedResponse.response = { type_url: 'url', value: Buffer.from('') }; + expectedResponse.metadata = { type_url: 'url', value: Buffer.from('') }; + + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const decodedOperation = await client.checkUpdateInstanceProgress( + expectedResponse.name, + ); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); - it('invokes checkImportInstanceProgress without error', async () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedResponse = generateSampleMessage( - new operationsProtos.google.longrunning.Operation() - ); - expectedResponse.name = 'test'; - expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; - expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')} - - client.operationsClient.getOperation = stubSimpleCall(expectedResponse); - const decodedOperation = await client.checkImportInstanceProgress(expectedResponse.name); - assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); - assert(decodedOperation.metadata); - assert((client.operationsClient.getOperation as SinonStub).getCall(0)); - }); + it('invokes checkUpdateInstanceProgress with error', async () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const expectedError = new Error('expected'); + + client.operationsClient.getOperation = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.checkUpdateInstanceProgress(''), + expectedError, + ); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + }); + + describe('importInstance', () => { + it('invokes importInstance without error', async () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.redis.v1beta1.ImportInstanceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.redis.v1beta1.ImportInstanceRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.importInstance = + stubLongRunningCall(expectedResponse); + const [operation] = await client.importInstance(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.importInstance as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.importInstance as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkImportInstanceProgress with error', async () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedError = new Error('expected'); - - client.operationsClient.getOperation = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.checkImportInstanceProgress(''), expectedError); - assert((client.operationsClient.getOperation as SinonStub) - .getCall(0)); - }); + it('invokes importInstance without error using callback', async () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.redis.v1beta1.ImportInstanceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.redis.v1beta1.ImportInstanceRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.importInstance = + stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.importInstance( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.cloud.redis.v1beta1.IInstance, + protos.google.protobuf.IAny + > | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const operation = (await promise) as LROperation< + protos.google.cloud.redis.v1beta1.IInstance, + protos.google.protobuf.IAny + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.importInstance as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.importInstance as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('exportInstance', () => { - it('invokes exportInstance without error', async () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.redis.v1beta1.ExportInstanceRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.redis.v1beta1.ExportInstanceRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.exportInstance = stubLongRunningCall(expectedResponse); - const [operation] = await client.exportInstance(request); - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.exportInstance as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.exportInstance as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes importInstance with call error', async () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.redis.v1beta1.ImportInstanceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.redis.v1beta1.ImportInstanceRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.importInstance = stubLongRunningCall( + undefined, + expectedError, + ); + await assert.rejects(client.importInstance(request), expectedError); + const actualRequest = ( + client.innerApiCalls.importInstance as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.importInstance as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes exportInstance without error using callback', async () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.redis.v1beta1.ExportInstanceRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.redis.v1beta1.ExportInstanceRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.exportInstance = stubLongRunningCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.exportInstance( - request, - (err?: Error|null, - result?: LROperation|null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const operation = await promise as LROperation; - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.exportInstance as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.exportInstance as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes importInstance with LRO error', async () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.redis.v1beta1.ImportInstanceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.redis.v1beta1.ImportInstanceRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.importInstance = stubLongRunningCall( + undefined, + undefined, + expectedError, + ); + const [operation] = await client.importInstance(request); + await assert.rejects(operation.promise(), expectedError); + const actualRequest = ( + client.innerApiCalls.importInstance as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.importInstance as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes exportInstance with call error', async () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.redis.v1beta1.ExportInstanceRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.redis.v1beta1.ExportInstanceRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.exportInstance = stubLongRunningCall(undefined, expectedError); - await assert.rejects(client.exportInstance(request), expectedError); - const actualRequest = (client.innerApiCalls.exportInstance as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.exportInstance as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes checkImportInstanceProgress without error', async () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation(), + ); + expectedResponse.name = 'test'; + expectedResponse.response = { type_url: 'url', value: Buffer.from('') }; + expectedResponse.metadata = { type_url: 'url', value: Buffer.from('') }; + + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const decodedOperation = await client.checkImportInstanceProgress( + expectedResponse.name, + ); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); - it('invokes exportInstance with LRO error', async () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.redis.v1beta1.ExportInstanceRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.redis.v1beta1.ExportInstanceRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.exportInstance = stubLongRunningCall(undefined, undefined, expectedError); - const [operation] = await client.exportInstance(request); - await assert.rejects(operation.promise(), expectedError); - const actualRequest = (client.innerApiCalls.exportInstance as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.exportInstance as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes checkImportInstanceProgress with error', async () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const expectedError = new Error('expected'); + + client.operationsClient.getOperation = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.checkImportInstanceProgress(''), + expectedError, + ); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + }); + + describe('exportInstance', () => { + it('invokes exportInstance without error', async () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.redis.v1beta1.ExportInstanceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.redis.v1beta1.ExportInstanceRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.exportInstance = + stubLongRunningCall(expectedResponse); + const [operation] = await client.exportInstance(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.exportInstance as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.exportInstance as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkExportInstanceProgress without error', async () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedResponse = generateSampleMessage( - new operationsProtos.google.longrunning.Operation() - ); - expectedResponse.name = 'test'; - expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; - expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')} - - client.operationsClient.getOperation = stubSimpleCall(expectedResponse); - const decodedOperation = await client.checkExportInstanceProgress(expectedResponse.name); - assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); - assert(decodedOperation.metadata); - assert((client.operationsClient.getOperation as SinonStub).getCall(0)); - }); + it('invokes exportInstance without error using callback', async () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.redis.v1beta1.ExportInstanceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.redis.v1beta1.ExportInstanceRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.exportInstance = + stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.exportInstance( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.cloud.redis.v1beta1.IInstance, + protos.google.protobuf.IAny + > | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const operation = (await promise) as LROperation< + protos.google.cloud.redis.v1beta1.IInstance, + protos.google.protobuf.IAny + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.exportInstance as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.exportInstance as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkExportInstanceProgress with error', async () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedError = new Error('expected'); - - client.operationsClient.getOperation = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.checkExportInstanceProgress(''), expectedError); - assert((client.operationsClient.getOperation as SinonStub) - .getCall(0)); - }); + it('invokes exportInstance with call error', async () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.redis.v1beta1.ExportInstanceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.redis.v1beta1.ExportInstanceRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.exportInstance = stubLongRunningCall( + undefined, + expectedError, + ); + await assert.rejects(client.exportInstance(request), expectedError); + const actualRequest = ( + client.innerApiCalls.exportInstance as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.exportInstance as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('failoverInstance', () => { - it('invokes failoverInstance without error', async () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.redis.v1beta1.FailoverInstanceRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.redis.v1beta1.FailoverInstanceRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.failoverInstance = stubLongRunningCall(expectedResponse); - const [operation] = await client.failoverInstance(request); - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.failoverInstance as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.failoverInstance as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes exportInstance with LRO error', async () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.redis.v1beta1.ExportInstanceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.redis.v1beta1.ExportInstanceRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.exportInstance = stubLongRunningCall( + undefined, + undefined, + expectedError, + ); + const [operation] = await client.exportInstance(request); + await assert.rejects(operation.promise(), expectedError); + const actualRequest = ( + client.innerApiCalls.exportInstance as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.exportInstance as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes failoverInstance without error using callback', async () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.redis.v1beta1.FailoverInstanceRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.redis.v1beta1.FailoverInstanceRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.failoverInstance = stubLongRunningCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.failoverInstance( - request, - (err?: Error|null, - result?: LROperation|null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const operation = await promise as LROperation; - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.failoverInstance as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.failoverInstance as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes checkExportInstanceProgress without error', async () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation(), + ); + expectedResponse.name = 'test'; + expectedResponse.response = { type_url: 'url', value: Buffer.from('') }; + expectedResponse.metadata = { type_url: 'url', value: Buffer.from('') }; + + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const decodedOperation = await client.checkExportInstanceProgress( + expectedResponse.name, + ); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); - it('invokes failoverInstance with call error', async () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.redis.v1beta1.FailoverInstanceRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.redis.v1beta1.FailoverInstanceRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.failoverInstance = stubLongRunningCall(undefined, expectedError); - await assert.rejects(client.failoverInstance(request), expectedError); - const actualRequest = (client.innerApiCalls.failoverInstance as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.failoverInstance as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes checkExportInstanceProgress with error', async () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const expectedError = new Error('expected'); + + client.operationsClient.getOperation = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.checkExportInstanceProgress(''), + expectedError, + ); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + }); + + describe('failoverInstance', () => { + it('invokes failoverInstance without error', async () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.redis.v1beta1.FailoverInstanceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.redis.v1beta1.FailoverInstanceRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.failoverInstance = + stubLongRunningCall(expectedResponse); + const [operation] = await client.failoverInstance(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.failoverInstance as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.failoverInstance as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes failoverInstance with LRO error', async () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.redis.v1beta1.FailoverInstanceRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.redis.v1beta1.FailoverInstanceRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.failoverInstance = stubLongRunningCall(undefined, undefined, expectedError); - const [operation] = await client.failoverInstance(request); - await assert.rejects(operation.promise(), expectedError); - const actualRequest = (client.innerApiCalls.failoverInstance as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.failoverInstance as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes failoverInstance without error using callback', async () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.redis.v1beta1.FailoverInstanceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.redis.v1beta1.FailoverInstanceRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.failoverInstance = + stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.failoverInstance( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.cloud.redis.v1beta1.IInstance, + protos.google.protobuf.IAny + > | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const operation = (await promise) as LROperation< + protos.google.cloud.redis.v1beta1.IInstance, + protos.google.protobuf.IAny + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.failoverInstance as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.failoverInstance as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkFailoverInstanceProgress without error', async () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedResponse = generateSampleMessage( - new operationsProtos.google.longrunning.Operation() - ); - expectedResponse.name = 'test'; - expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; - expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')} - - client.operationsClient.getOperation = stubSimpleCall(expectedResponse); - const decodedOperation = await client.checkFailoverInstanceProgress(expectedResponse.name); - assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); - assert(decodedOperation.metadata); - assert((client.operationsClient.getOperation as SinonStub).getCall(0)); - }); + it('invokes failoverInstance with call error', async () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.redis.v1beta1.FailoverInstanceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.redis.v1beta1.FailoverInstanceRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.failoverInstance = stubLongRunningCall( + undefined, + expectedError, + ); + await assert.rejects(client.failoverInstance(request), expectedError); + const actualRequest = ( + client.innerApiCalls.failoverInstance as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.failoverInstance as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkFailoverInstanceProgress with error', async () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedError = new Error('expected'); - - client.operationsClient.getOperation = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.checkFailoverInstanceProgress(''), expectedError); - assert((client.operationsClient.getOperation as SinonStub) - .getCall(0)); - }); + it('invokes failoverInstance with LRO error', async () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.redis.v1beta1.FailoverInstanceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.redis.v1beta1.FailoverInstanceRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.failoverInstance = stubLongRunningCall( + undefined, + undefined, + expectedError, + ); + const [operation] = await client.failoverInstance(request); + await assert.rejects(operation.promise(), expectedError); + const actualRequest = ( + client.innerApiCalls.failoverInstance as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.failoverInstance as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('deleteInstance', () => { - it('invokes deleteInstance without error', async () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.redis.v1beta1.DeleteInstanceRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.redis.v1beta1.DeleteInstanceRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.deleteInstance = stubLongRunningCall(expectedResponse); - const [operation] = await client.deleteInstance(request); - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteInstance as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteInstance as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes checkFailoverInstanceProgress without error', async () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation(), + ); + expectedResponse.name = 'test'; + expectedResponse.response = { type_url: 'url', value: Buffer.from('') }; + expectedResponse.metadata = { type_url: 'url', value: Buffer.from('') }; + + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const decodedOperation = await client.checkFailoverInstanceProgress( + expectedResponse.name, + ); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); - it('invokes deleteInstance without error using callback', async () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.redis.v1beta1.DeleteInstanceRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.redis.v1beta1.DeleteInstanceRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.deleteInstance = stubLongRunningCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteInstance( - request, - (err?: Error|null, - result?: LROperation|null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const operation = await promise as LROperation; - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteInstance as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteInstance as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes checkFailoverInstanceProgress with error', async () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const expectedError = new Error('expected'); + + client.operationsClient.getOperation = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.checkFailoverInstanceProgress(''), + expectedError, + ); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + }); + + describe('deleteInstance', () => { + it('invokes deleteInstance without error', async () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.redis.v1beta1.DeleteInstanceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.redis.v1beta1.DeleteInstanceRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.deleteInstance = + stubLongRunningCall(expectedResponse); + const [operation] = await client.deleteInstance(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteInstance as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteInstance as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteInstance with call error', async () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.redis.v1beta1.DeleteInstanceRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.redis.v1beta1.DeleteInstanceRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteInstance = stubLongRunningCall(undefined, expectedError); - await assert.rejects(client.deleteInstance(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteInstance as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteInstance as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteInstance without error using callback', async () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.redis.v1beta1.DeleteInstanceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.redis.v1beta1.DeleteInstanceRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.deleteInstance = + stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteInstance( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.protobuf.IEmpty, + protos.google.protobuf.IAny + > | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const operation = (await promise) as LROperation< + protos.google.protobuf.IEmpty, + protos.google.protobuf.IAny + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteInstance as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteInstance as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteInstance with LRO error', async () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.redis.v1beta1.DeleteInstanceRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.redis.v1beta1.DeleteInstanceRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteInstance = stubLongRunningCall(undefined, undefined, expectedError); - const [operation] = await client.deleteInstance(request); - await assert.rejects(operation.promise(), expectedError); - const actualRequest = (client.innerApiCalls.deleteInstance as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteInstance as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteInstance with call error', async () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.redis.v1beta1.DeleteInstanceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.redis.v1beta1.DeleteInstanceRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteInstance = stubLongRunningCall( + undefined, + expectedError, + ); + await assert.rejects(client.deleteInstance(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteInstance as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteInstance as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkDeleteInstanceProgress without error', async () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedResponse = generateSampleMessage( - new operationsProtos.google.longrunning.Operation() - ); - expectedResponse.name = 'test'; - expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; - expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')} - - client.operationsClient.getOperation = stubSimpleCall(expectedResponse); - const decodedOperation = await client.checkDeleteInstanceProgress(expectedResponse.name); - assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); - assert(decodedOperation.metadata); - assert((client.operationsClient.getOperation as SinonStub).getCall(0)); - }); + it('invokes deleteInstance with LRO error', async () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.redis.v1beta1.DeleteInstanceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.redis.v1beta1.DeleteInstanceRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteInstance = stubLongRunningCall( + undefined, + undefined, + expectedError, + ); + const [operation] = await client.deleteInstance(request); + await assert.rejects(operation.promise(), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteInstance as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteInstance as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkDeleteInstanceProgress with error', async () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedError = new Error('expected'); - - client.operationsClient.getOperation = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.checkDeleteInstanceProgress(''), expectedError); - assert((client.operationsClient.getOperation as SinonStub) - .getCall(0)); - }); + it('invokes checkDeleteInstanceProgress without error', async () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation(), + ); + expectedResponse.name = 'test'; + expectedResponse.response = { type_url: 'url', value: Buffer.from('') }; + expectedResponse.metadata = { type_url: 'url', value: Buffer.from('') }; + + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const decodedOperation = await client.checkDeleteInstanceProgress( + expectedResponse.name, + ); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); }); - describe('listInstances', () => { - it('invokes listInstances without error', async () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.redis.v1beta1.ListInstancesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.redis.v1beta1.ListInstancesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.redis.v1beta1.Instance()), - generateSampleMessage(new protos.google.cloud.redis.v1beta1.Instance()), - generateSampleMessage(new protos.google.cloud.redis.v1beta1.Instance()), - ]; - client.innerApiCalls.listInstances = stubSimpleCall(expectedResponse); - const [response] = await client.listInstances(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listInstances as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listInstances as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes checkDeleteInstanceProgress with error', async () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const expectedError = new Error('expected'); + + client.operationsClient.getOperation = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.checkDeleteInstanceProgress(''), + expectedError, + ); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + }); + + describe('listInstances', () => { + it('invokes listInstances without error', async () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.redis.v1beta1.ListInstancesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.redis.v1beta1.ListInstancesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.redis.v1beta1.Instance()), + generateSampleMessage(new protos.google.cloud.redis.v1beta1.Instance()), + generateSampleMessage(new protos.google.cloud.redis.v1beta1.Instance()), + ]; + client.innerApiCalls.listInstances = stubSimpleCall(expectedResponse); + const [response] = await client.listInstances(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listInstances as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listInstances as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listInstances without error using callback', async () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.redis.v1beta1.ListInstancesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.redis.v1beta1.ListInstancesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.redis.v1beta1.Instance()), - generateSampleMessage(new protos.google.cloud.redis.v1beta1.Instance()), - generateSampleMessage(new protos.google.cloud.redis.v1beta1.Instance()), - ]; - client.innerApiCalls.listInstances = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listInstances( - request, - (err?: Error|null, result?: protos.google.cloud.redis.v1beta1.IInstance[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listInstances as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listInstances as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listInstances without error using callback', async () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.redis.v1beta1.ListInstancesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.redis.v1beta1.ListInstancesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.redis.v1beta1.Instance()), + generateSampleMessage(new protos.google.cloud.redis.v1beta1.Instance()), + generateSampleMessage(new protos.google.cloud.redis.v1beta1.Instance()), + ]; + client.innerApiCalls.listInstances = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listInstances( + request, + ( + err?: Error | null, + result?: protos.google.cloud.redis.v1beta1.IInstance[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listInstances as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listInstances as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listInstances with error', async () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.redis.v1beta1.ListInstancesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.redis.v1beta1.ListInstancesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listInstances = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listInstances(request), expectedError); - const actualRequest = (client.innerApiCalls.listInstances as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listInstances as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listInstances with error', async () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.redis.v1beta1.ListInstancesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.redis.v1beta1.ListInstancesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listInstances = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listInstances(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listInstances as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listInstances as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listInstancesStream without error', async () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.redis.v1beta1.ListInstancesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.redis.v1beta1.ListInstancesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.redis.v1beta1.Instance()), - generateSampleMessage(new protos.google.cloud.redis.v1beta1.Instance()), - generateSampleMessage(new protos.google.cloud.redis.v1beta1.Instance()), - ]; - client.descriptors.page.listInstances.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listInstancesStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.cloud.redis.v1beta1.Instance[] = []; - stream.on('data', (response: protos.google.cloud.redis.v1beta1.Instance) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.listInstances.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listInstances, request)); - assert( - (client.descriptors.page.listInstances.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listInstancesStream without error', async () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.redis.v1beta1.ListInstancesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.redis.v1beta1.ListInstancesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.redis.v1beta1.Instance()), + generateSampleMessage(new protos.google.cloud.redis.v1beta1.Instance()), + generateSampleMessage(new protos.google.cloud.redis.v1beta1.Instance()), + ]; + client.descriptors.page.listInstances.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listInstancesStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.cloud.redis.v1beta1.Instance[] = []; + stream.on( + 'data', + (response: protos.google.cloud.redis.v1beta1.Instance) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listInstances.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listInstances, request), + ); + assert( + (client.descriptors.page.listInstances.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('invokes listInstancesStream with error', async () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.redis.v1beta1.ListInstancesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.redis.v1beta1.ListInstancesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listInstances.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listInstancesStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.cloud.redis.v1beta1.Instance[] = []; - stream.on('data', (response: protos.google.cloud.redis.v1beta1.Instance) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listInstances.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listInstances, request)); - assert( - (client.descriptors.page.listInstances.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listInstancesStream with error', async () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.redis.v1beta1.ListInstancesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.redis.v1beta1.ListInstancesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listInstances.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listInstancesStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.cloud.redis.v1beta1.Instance[] = []; + stream.on( + 'data', + (response: protos.google.cloud.redis.v1beta1.Instance) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listInstances.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listInstances, request), + ); + assert( + (client.descriptors.page.listInstances.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('uses async iteration with listInstances without error', async () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.redis.v1beta1.ListInstancesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.redis.v1beta1.ListInstancesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.redis.v1beta1.Instance()), - generateSampleMessage(new protos.google.cloud.redis.v1beta1.Instance()), - generateSampleMessage(new protos.google.cloud.redis.v1beta1.Instance()), - ]; - client.descriptors.page.listInstances.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.cloud.redis.v1beta1.IInstance[] = []; - const iterable = client.listInstancesAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listInstances.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listInstances.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listInstances without error', async () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.redis.v1beta1.ListInstancesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.redis.v1beta1.ListInstancesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.redis.v1beta1.Instance()), + generateSampleMessage(new protos.google.cloud.redis.v1beta1.Instance()), + generateSampleMessage(new protos.google.cloud.redis.v1beta1.Instance()), + ]; + client.descriptors.page.listInstances.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.cloud.redis.v1beta1.IInstance[] = []; + const iterable = client.listInstancesAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listInstances.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listInstances.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('uses async iteration with listInstances with error', async () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.redis.v1beta1.ListInstancesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.redis.v1beta1.ListInstancesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listInstances.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listInstancesAsync(request); - await assert.rejects(async () => { - const responses: protos.google.cloud.redis.v1beta1.IInstance[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listInstances.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listInstances.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listInstances with error', async () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.redis.v1beta1.ListInstancesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.redis.v1beta1.ListInstancesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listInstances.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listInstancesAsync(request); + await assert.rejects(async () => { + const responses: protos.google.cloud.redis.v1beta1.IInstance[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listInstances.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listInstances.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); }); - describe('getOperation', () => { - it('invokes getOperation without error', async () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new operationsProtos.google.longrunning.GetOperationRequest() - ); - const expectedResponse = generateSampleMessage( - new operationsProtos.google.longrunning.Operation() - ); - client.operationsClient.getOperation = stubSimpleCall(expectedResponse); - const response = await client.getOperation(request); - assert.deepStrictEqual(response, [expectedResponse]); - assert((client.operationsClient.getOperation as SinonStub) - .getCall(0).calledWith(request) - ); - }); - it('invokes getOperation without error using callback', async () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - const request = generateSampleMessage( - new operationsProtos.google.longrunning.GetOperationRequest() - ); - const expectedResponse = generateSampleMessage( - new operationsProtos.google.longrunning.Operation() - ); - client.operationsClient.getOperation = sinon.stub().callsArgWith(2, null, expectedResponse); - const promise = new Promise((resolve, reject) => { - client.operationsClient.getOperation( - request, - undefined, - ( - err?: Error | null, - result?: operationsProtos.google.longrunning.Operation | null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }).catch(err => {throw err}); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - assert((client.operationsClient.getOperation as SinonStub) - .getCall(0)); - }); - it('invokes getOperation with error', async () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - const request = generateSampleMessage( - new operationsProtos.google.longrunning.GetOperationRequest() - ); - const expectedError = new Error('expected'); - client.operationsClient.getOperation = stubSimpleCall(undefined, expectedError); - await assert.rejects(async () => {await client.getOperation(request)}, expectedError); - assert((client.operationsClient.getOperation as SinonStub) - .getCall(0).calledWith(request)); - }); + }); + describe('getOperation', () => { + it('invokes getOperation without error', async () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new operationsProtos.google.longrunning.GetOperationRequest(), + ); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation(), + ); + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const response = await client.getOperation(request); + assert.deepStrictEqual(response, [expectedResponse]); + assert( + (client.operationsClient.getOperation as SinonStub) + .getCall(0) + .calledWith(request), + ); }); - describe('cancelOperation', () => { - it('invokes cancelOperation without error', async () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new operationsProtos.google.longrunning.CancelOperationRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.operationsClient.cancelOperation = stubSimpleCall(expectedResponse); - const response = await client.cancelOperation(request); - assert.deepStrictEqual(response, [expectedResponse]); - assert((client.operationsClient.cancelOperation as SinonStub) - .getCall(0).calledWith(request) - ); - }); - it('invokes cancelOperation without error using callback', async () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - const request = generateSampleMessage( - new operationsProtos.google.longrunning.CancelOperationRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.operationsClient.cancelOperation = sinon.stub().callsArgWith(2, null, expectedResponse); - const promise = new Promise((resolve, reject) => { - client.operationsClient.cancelOperation( - request, - undefined, - ( - err?: Error | null, - result?: protos.google.protobuf.Empty | null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }).catch(err => {throw err}); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - assert((client.operationsClient.cancelOperation as SinonStub) - .getCall(0)); - }); - it('invokes cancelOperation with error', async () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - const request = generateSampleMessage( - new operationsProtos.google.longrunning.CancelOperationRequest() - ); - const expectedError = new Error('expected'); - client.operationsClient.cancelOperation = stubSimpleCall(undefined, expectedError); - await assert.rejects(async () => {await client.cancelOperation(request)}, expectedError); - assert((client.operationsClient.cancelOperation as SinonStub) - .getCall(0).calledWith(request)); - }); + it('invokes getOperation without error using callback', async () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + const request = generateSampleMessage( + new operationsProtos.google.longrunning.GetOperationRequest(), + ); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation(), + ); + client.operationsClient.getOperation = sinon + .stub() + .callsArgWith(2, null, expectedResponse); + const promise = new Promise((resolve, reject) => { + client.operationsClient + .getOperation( + request, + undefined, + ( + err?: Error | null, + result?: operationsProtos.google.longrunning.Operation | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ) + .catch((err) => { + throw err; + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); }); - describe('deleteOperation', () => { - it('invokes deleteOperation without error', async () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new operationsProtos.google.longrunning.DeleteOperationRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.operationsClient.deleteOperation = stubSimpleCall(expectedResponse); - const response = await client.deleteOperation(request); - assert.deepStrictEqual(response, [expectedResponse]); - assert((client.operationsClient.deleteOperation as SinonStub) - .getCall(0).calledWith(request) - ); - }); - it('invokes deleteOperation without error using callback', async () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - const request = generateSampleMessage( - new operationsProtos.google.longrunning.DeleteOperationRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.operationsClient.deleteOperation = sinon.stub().callsArgWith(2, null, expectedResponse); - const promise = new Promise((resolve, reject) => { - client.operationsClient.deleteOperation( - request, - undefined, - ( - err?: Error | null, - result?: protos.google.protobuf.Empty | null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }).catch(err => {throw err}); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - assert((client.operationsClient.deleteOperation as SinonStub) - .getCall(0)); - }); - it('invokes deleteOperation with error', async () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - const request = generateSampleMessage( - new operationsProtos.google.longrunning.DeleteOperationRequest() - ); - const expectedError = new Error('expected'); - client.operationsClient.deleteOperation = stubSimpleCall(undefined, expectedError); - await assert.rejects(async () => {await client.deleteOperation(request)}, expectedError); - assert((client.operationsClient.deleteOperation as SinonStub) - .getCall(0).calledWith(request)); - }); + it('invokes getOperation with error', async () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + const request = generateSampleMessage( + new operationsProtos.google.longrunning.GetOperationRequest(), + ); + const expectedError = new Error('expected'); + client.operationsClient.getOperation = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(async () => { + await client.getOperation(request); + }, expectedError); + assert( + (client.operationsClient.getOperation as SinonStub) + .getCall(0) + .calledWith(request), + ); }); - describe('listOperationsAsync', () => { - it('uses async iteration with listOperations without error', async () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - const request = generateSampleMessage( - new operationsProtos.google.longrunning.ListOperationsRequest() - ); - const expectedResponse = [ - generateSampleMessage( - new operationsProtos.google.longrunning.ListOperationsResponse() - ), - generateSampleMessage( - new operationsProtos.google.longrunning.ListOperationsResponse() - ), - generateSampleMessage( - new operationsProtos.google.longrunning.ListOperationsResponse() - ), - ]; - client.operationsClient.descriptor.listOperations.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: operationsProtos.google.longrunning.IOperation[] = []; - const iterable = client.operationsClient.listOperationsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.operationsClient.descriptor.listOperations.asyncIterate as SinonStub) - .getCall(0).args[1], request); - }); - it('uses async iteration with listOperations with error', async () => { - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new operationsProtos.google.longrunning.ListOperationsRequest() - ); - const expectedError = new Error('expected'); - client.operationsClient.descriptor.listOperations.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.operationsClient.listOperationsAsync(request); - await assert.rejects(async () => { - const responses: operationsProtos.google.longrunning.IOperation[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.operationsClient.descriptor.listOperations.asyncIterate as SinonStub) - .getCall(0).args[1], request); - }); + }); + describe('cancelOperation', () => { + it('invokes cancelOperation without error', async () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new operationsProtos.google.longrunning.CancelOperationRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.operationsClient.cancelOperation = + stubSimpleCall(expectedResponse); + const response = await client.cancelOperation(request); + assert.deepStrictEqual(response, [expectedResponse]); + assert( + (client.operationsClient.cancelOperation as SinonStub) + .getCall(0) + .calledWith(request), + ); + }); + it('invokes cancelOperation without error using callback', async () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + const request = generateSampleMessage( + new operationsProtos.google.longrunning.CancelOperationRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.operationsClient.cancelOperation = sinon + .stub() + .callsArgWith(2, null, expectedResponse); + const promise = new Promise((resolve, reject) => { + client.operationsClient + .cancelOperation( + request, + undefined, + ( + err?: Error | null, + result?: protos.google.protobuf.Empty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ) + .catch((err) => { + throw err; + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + assert((client.operationsClient.cancelOperation as SinonStub).getCall(0)); + }); + it('invokes cancelOperation with error', async () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + const request = generateSampleMessage( + new operationsProtos.google.longrunning.CancelOperationRequest(), + ); + const expectedError = new Error('expected'); + client.operationsClient.cancelOperation = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(async () => { + await client.cancelOperation(request); + }, expectedError); + assert( + (client.operationsClient.cancelOperation as SinonStub) + .getCall(0) + .calledWith(request), + ); + }); + }); + describe('deleteOperation', () => { + it('invokes deleteOperation without error', async () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new operationsProtos.google.longrunning.DeleteOperationRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.operationsClient.deleteOperation = + stubSimpleCall(expectedResponse); + const response = await client.deleteOperation(request); + assert.deepStrictEqual(response, [expectedResponse]); + assert( + (client.operationsClient.deleteOperation as SinonStub) + .getCall(0) + .calledWith(request), + ); + }); + it('invokes deleteOperation without error using callback', async () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + const request = generateSampleMessage( + new operationsProtos.google.longrunning.DeleteOperationRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.operationsClient.deleteOperation = sinon + .stub() + .callsArgWith(2, null, expectedResponse); + const promise = new Promise((resolve, reject) => { + client.operationsClient + .deleteOperation( + request, + undefined, + ( + err?: Error | null, + result?: protos.google.protobuf.Empty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ) + .catch((err) => { + throw err; + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + assert((client.operationsClient.deleteOperation as SinonStub).getCall(0)); + }); + it('invokes deleteOperation with error', async () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + const request = generateSampleMessage( + new operationsProtos.google.longrunning.DeleteOperationRequest(), + ); + const expectedError = new Error('expected'); + client.operationsClient.deleteOperation = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(async () => { + await client.deleteOperation(request); + }, expectedError); + assert( + (client.operationsClient.deleteOperation as SinonStub) + .getCall(0) + .calledWith(request), + ); + }); + }); + describe('listOperationsAsync', () => { + it('uses async iteration with listOperations without error', async () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + const request = generateSampleMessage( + new operationsProtos.google.longrunning.ListOperationsRequest(), + ); + const expectedResponse = [ + generateSampleMessage( + new operationsProtos.google.longrunning.ListOperationsResponse(), + ), + generateSampleMessage( + new operationsProtos.google.longrunning.ListOperationsResponse(), + ), + generateSampleMessage( + new operationsProtos.google.longrunning.ListOperationsResponse(), + ), + ]; + client.operationsClient.descriptor.listOperations.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: operationsProtos.google.longrunning.IOperation[] = []; + const iterable = client.operationsClient.listOperationsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.operationsClient.descriptor.listOperations + .asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + }); + it('uses async iteration with listOperations with error', async () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new operationsProtos.google.longrunning.ListOperationsRequest(), + ); + const expectedError = new Error('expected'); + client.operationsClient.descriptor.listOperations.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.operationsClient.listOperationsAsync(request); + await assert.rejects(async () => { + const responses: operationsProtos.google.longrunning.IOperation[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.operationsClient.descriptor.listOperations + .asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + }); + }); + + describe('Path templates', () => { + describe('instance', async () => { + const fakePath = '/rendered/path/instance'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + instance: 'instanceValue', + }; + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.instancePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.instancePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('instancePath', () => { + const result = client.instancePath( + 'projectValue', + 'locationValue', + 'instanceValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.instancePathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromInstanceName', () => { + const result = client.matchProjectFromInstanceName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.instancePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromInstanceName', () => { + const result = client.matchLocationFromInstanceName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.instancePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchInstanceFromInstanceName', () => { + const result = client.matchInstanceFromInstanceName(fakePath); + assert.strictEqual(result, 'instanceValue'); + assert( + (client.pathTemplates.instancePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); - describe('Path templates', () => { - - describe('instance', async () => { - const fakePath = "/rendered/path/instance"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - instance: "instanceValue", - }; - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.instancePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.instancePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('instancePath', () => { - const result = client.instancePath("projectValue", "locationValue", "instanceValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.instancePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromInstanceName', () => { - const result = client.matchProjectFromInstanceName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.instancePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromInstanceName', () => { - const result = client.matchLocationFromInstanceName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.instancePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchInstanceFromInstanceName', () => { - const result = client.matchInstanceFromInstanceName(fakePath); - assert.strictEqual(result, "instanceValue"); - assert((client.pathTemplates.instancePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('location', async () => { - const fakePath = "/rendered/path/location"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - }; - const client = new cloudredisModule.v1beta1.CloudRedisClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.locationPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.locationPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('locationPath', () => { - const result = client.locationPath("projectValue", "locationValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.locationPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromLocationName', () => { - const result = client.matchProjectFromLocationName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.locationPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromLocationName', () => { - const result = client.matchLocationFromLocationName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.locationPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('location', async () => { + const fakePath = '/rendered/path/location'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + }; + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.locationPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.locationPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('locationPath', () => { + const result = client.locationPath('projectValue', 'locationValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.locationPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromLocationName', () => { + const result = client.matchProjectFromLocationName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.locationPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromLocationName', () => { + const result = client.matchLocationFromLocationName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.locationPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/src/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/src/index.ts.baseline index 6a9662eafa83..996de65e6df3 100644 --- a/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/src/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/src/index.ts.baseline @@ -27,12 +27,16 @@ const CompletionServiceClient = v2alpha.CompletionServiceClient; type CompletionServiceClient = v2alpha.CompletionServiceClient; const ControlServiceClient = v2alpha.ControlServiceClient; type ControlServiceClient = v2alpha.ControlServiceClient; -const ConversationalSearchServiceClient = v2alpha.ConversationalSearchServiceClient; -type ConversationalSearchServiceClient = v2alpha.ConversationalSearchServiceClient; +const ConversationalSearchServiceClient = + v2alpha.ConversationalSearchServiceClient; +type ConversationalSearchServiceClient = + v2alpha.ConversationalSearchServiceClient; const GenerativeQuestionServiceClient = v2alpha.GenerativeQuestionServiceClient; type GenerativeQuestionServiceClient = v2alpha.GenerativeQuestionServiceClient; -const MerchantCenterAccountLinkServiceClient = v2alpha.MerchantCenterAccountLinkServiceClient; -type MerchantCenterAccountLinkServiceClient = v2alpha.MerchantCenterAccountLinkServiceClient; +const MerchantCenterAccountLinkServiceClient = + v2alpha.MerchantCenterAccountLinkServiceClient; +type MerchantCenterAccountLinkServiceClient = + v2alpha.MerchantCenterAccountLinkServiceClient; const ModelServiceClient = v2alpha.ModelServiceClient; type ModelServiceClient = v2alpha.ModelServiceClient; const PredictionServiceClient = v2alpha.PredictionServiceClient; @@ -47,8 +51,42 @@ const ServingConfigServiceClient = v2alpha.ServingConfigServiceClient; type ServingConfigServiceClient = v2alpha.ServingConfigServiceClient; const UserEventServiceClient = v2alpha.UserEventServiceClient; type UserEventServiceClient = v2alpha.UserEventServiceClient; -export {v2alpha, AnalyticsServiceClient, BranchServiceClient, CatalogServiceClient, CompletionServiceClient, ControlServiceClient, ConversationalSearchServiceClient, GenerativeQuestionServiceClient, MerchantCenterAccountLinkServiceClient, ModelServiceClient, PredictionServiceClient, ProductServiceClient, ProjectServiceClient, SearchServiceClient, ServingConfigServiceClient, UserEventServiceClient}; -export default {v2alpha, AnalyticsServiceClient, BranchServiceClient, CatalogServiceClient, CompletionServiceClient, ControlServiceClient, ConversationalSearchServiceClient, GenerativeQuestionServiceClient, MerchantCenterAccountLinkServiceClient, ModelServiceClient, PredictionServiceClient, ProductServiceClient, ProjectServiceClient, SearchServiceClient, ServingConfigServiceClient, UserEventServiceClient}; +export { + v2alpha, + AnalyticsServiceClient, + BranchServiceClient, + CatalogServiceClient, + CompletionServiceClient, + ControlServiceClient, + ConversationalSearchServiceClient, + GenerativeQuestionServiceClient, + MerchantCenterAccountLinkServiceClient, + ModelServiceClient, + PredictionServiceClient, + ProductServiceClient, + ProjectServiceClient, + SearchServiceClient, + ServingConfigServiceClient, + UserEventServiceClient, +}; +export default { + v2alpha, + AnalyticsServiceClient, + BranchServiceClient, + CatalogServiceClient, + CompletionServiceClient, + ControlServiceClient, + ConversationalSearchServiceClient, + GenerativeQuestionServiceClient, + MerchantCenterAccountLinkServiceClient, + ModelServiceClient, + PredictionServiceClient, + ProductServiceClient, + ProjectServiceClient, + SearchServiceClient, + ServingConfigServiceClient, + UserEventServiceClient, +}; // @ts-ignore import * as protos from '../../protos/protos.js'; -export {protos} +export { protos }; diff --git a/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/src/v2alpha/analytics_service_client.ts.baseline b/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/src/v2alpha/analytics_service_client.ts.baseline index 54c15438c652..b542d8f76c6d 100644 --- a/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/src/v2alpha/analytics_service_client.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/src/v2alpha/analytics_service_client.ts.baseline @@ -18,15 +18,22 @@ /* global window */ import * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions, GrpcClientOptions, LROperation} from 'google-gax'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + GrpcClientOptions, + LROperation, +} from 'google-gax'; // @ts-ignore import type * as protos from '../../../protos/protos.js'; import * as analytics_service_client_config from './analytics_service_client_config.json'; import fs from 'fs'; import path from 'path'; -import {fileURLToPath} from 'url'; -import {getJSON} from '../json-helper.cjs'; +import { fileURLToPath } from 'url'; +import { getJSON } from '../json-helper.cjs'; // @ts-ignore const dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -36,15 +43,15 @@ const dirname = path.dirname(fileURLToPath(import.meta.url)); * This file defines retry strategy and timeouts for all API methods in this library. */ const gapicConfig = getJSON( - path.join(dirname, 'analytics_service_client_config.json') + path.join(dirname, 'analytics_service_client_config.json'), ); const jsonProtos = getJSON( - path.join(dirname, '..', '..', '..', 'protos/protos.json') + path.join(dirname, '..', '..', '..', 'protos/protos.json'), ); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; const version = getJSON( - path.join(dirname, '..', '..', '..', '..', 'package.json') + path.join(dirname, '..', '..', '..', '..', 'package.json'), ).version; /** @@ -60,7 +67,7 @@ export class AnalyticsServiceClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('retail'); @@ -72,10 +79,10 @@ export class AnalyticsServiceClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; operationsClient: gax.OperationsClient; - analyticsServiceStub?: Promise<{[name: string]: Function}>; + analyticsServiceStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of AnalyticsServiceClient. @@ -117,21 +124,42 @@ export class AnalyticsServiceClient { * const client = new AnalyticsServiceClient({fallback: 'rest'}, gax); * ``` */ - constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { // Ensure that options include all the required fields. const staticMembers = this.constructor as typeof AnalyticsServiceClient; - if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { - throw new Error('Please set either universe_domain or universeDomain, but not both.'); + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); } - const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; - this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; this._servicePath = 'retail.' + this._universeDomain; - const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; - const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. if (servicePath !== this._servicePath && !('scopes' in opts)) { @@ -153,7 +181,7 @@ export class AnalyticsServiceClient { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; @@ -170,10 +198,7 @@ export class AnalyticsServiceClient { const isEsm = true; const isEsmString = isEsm ? '-esm' : '-cjs'; // Determine the client header string. - const clientHeader = [ - `gax/${this._gaxModule.version}`, - `gapic/${version}`, - ]; + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/{process.versions.node}${isEsmString}`); } else { @@ -181,7 +206,7 @@ export class AnalyticsServiceClient { } if (!opts.fallback) { clientHeader.push(`grpc/${this._gaxGrpc.grpcVersion}`); - } else if (opts.fallback === 'rest' ) { + } else if (opts.fallback === 'rest') { clientHeader.push(`rest/${this._gaxGrpc.grpcVersion}`); } if (opts.libName && opts.libVersion) { @@ -189,47 +214,49 @@ export class AnalyticsServiceClient { } // Load the applicable protos. - this._protos = this._gaxGrpc.loadProtoJSON(jsonProtos as gax.protobuf.INamespace); + this._protos = this._gaxGrpc.loadProtoJSON( + jsonProtos as gax.protobuf.INamespace, + ); // This API contains "path templates"; forward-slash-separated // identifiers to uniquely identify resources within the API. // Create useful helper objects for these. this.pathTemplates = { alertConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/alertConfig' + 'projects/{project}/alertConfig', ), attributesConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/attributesConfig' + 'projects/{project}/locations/{location}/catalogs/{catalog}/attributesConfig', ), branchPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}', ), catalogPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}' + 'projects/{project}/locations/{location}/catalogs/{catalog}', ), completionConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/completionConfig' + 'projects/{project}/locations/{location}/catalogs/{catalog}/completionConfig', ), controlPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/controls/{control}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/controls/{control}', ), loggingConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/loggingConfig' + 'projects/{project}/loggingConfig', ), merchantCenterAccountLinkPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/merchantCenterAccountLinks/{merchant_center_account_link}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/merchantCenterAccountLinks/{merchant_center_account_link}', ), modelPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/models/{model}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/models/{model}', ), productPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}', ), retailProjectPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/retailProject' + 'projects/{project}/retailProject', ), servingConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/servingConfigs/{serving_config}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/servingConfigs/{serving_config}', ), }; @@ -239,31 +266,64 @@ export class AnalyticsServiceClient { // rather than holding a request open. const lroOptions: GrpcClientOptions = { auth: this.auth, - grpc: 'grpc' in this._gaxGrpc ? this._gaxGrpc.grpc : undefined + grpc: 'grpc' in this._gaxGrpc ? this._gaxGrpc.grpc : undefined, }; if (opts.fallback === 'rest') { lroOptions.protoJson = protoFilesRoot; - lroOptions.httpRules = [{selector: 'google.longrunning.Operations.GetOperation',get: '/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*/operations/*}',additional_bindings: [{get: '/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*/places/*/operations/*}',},{get: '/v2alpha/{name=projects/*/locations/*/catalogs/*/operations/*}',},{get: '/v2alpha/{name=projects/*/locations/*/operations/*}',},{get: '/v2alpha/{name=projects/*/operations/*}',}], - },{selector: 'google.longrunning.Operations.ListOperations',get: '/v2alpha/{name=projects/*/locations/*/catalogs/*}/operations',additional_bindings: [{get: '/v2alpha/{name=projects/*/locations/*}/operations',},{get: '/v2alpha/{name=projects/*}/operations',}], - }]; + lroOptions.httpRules = [ + { + selector: 'google.longrunning.Operations.GetOperation', + get: '/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*/operations/*}', + additional_bindings: [ + { + get: '/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*/places/*/operations/*}', + }, + { + get: '/v2alpha/{name=projects/*/locations/*/catalogs/*/operations/*}', + }, + { get: '/v2alpha/{name=projects/*/locations/*/operations/*}' }, + { get: '/v2alpha/{name=projects/*/operations/*}' }, + ], + }, + { + selector: 'google.longrunning.Operations.ListOperations', + get: '/v2alpha/{name=projects/*/locations/*/catalogs/*}/operations', + additional_bindings: [ + { get: '/v2alpha/{name=projects/*/locations/*}/operations' }, + { get: '/v2alpha/{name=projects/*}/operations' }, + ], + }, + ]; } - this.operationsClient = this._gaxModule.lro(lroOptions).operationsClient(opts); + this.operationsClient = this._gaxModule + .lro(lroOptions) + .operationsClient(opts); const exportAnalyticsMetricsResponse = protoFilesRoot.lookup( - '.google.cloud.retail.v2alpha.ExportAnalyticsMetricsResponse') as gax.protobuf.Type; + '.google.cloud.retail.v2alpha.ExportAnalyticsMetricsResponse', + ) as gax.protobuf.Type; const exportAnalyticsMetricsMetadata = protoFilesRoot.lookup( - '.google.cloud.retail.v2alpha.ExportMetadata') as gax.protobuf.Type; + '.google.cloud.retail.v2alpha.ExportMetadata', + ) as gax.protobuf.Type; this.descriptors.longrunning = { exportAnalyticsMetrics: new this._gaxModule.LongrunningDescriptor( this.operationsClient, - exportAnalyticsMetricsResponse.decode.bind(exportAnalyticsMetricsResponse), - exportAnalyticsMetricsMetadata.decode.bind(exportAnalyticsMetricsMetadata)) + exportAnalyticsMetricsResponse.decode.bind( + exportAnalyticsMetricsResponse, + ), + exportAnalyticsMetricsMetadata.decode.bind( + exportAnalyticsMetricsMetadata, + ), + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.cloud.retail.v2alpha.AnalyticsService', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.cloud.retail.v2alpha.AnalyticsService', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + { 'x-goog-api-client': clientHeader.join(' ') }, + ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -294,37 +354,40 @@ export class AnalyticsServiceClient { // Put together the "service stub" for // google.cloud.retail.v2alpha.AnalyticsService. this.analyticsServiceStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.cloud.retail.v2alpha.AnalyticsService') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.cloud.retail.v2alpha.AnalyticsService', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.cloud.retail.v2alpha.AnalyticsService, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts, + this._providedCustomServicePath, + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const analyticsServiceStubMethods = - ['exportAnalyticsMetrics']; + const analyticsServiceStubMethods = ['exportAnalyticsMetrics']; for (const methodName of analyticsServiceStubMethods) { const callPromise = this.analyticsServiceStub.then( - stub => (...args: Array<{}>) => { - if (this._terminated) { - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error|null|undefined) => () => { + (stub) => + (...args: Array<{}>) => { + if (this._terminated) { + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { throw err; - }); + }, + ); - const descriptor = - this.descriptors.longrunning[methodName] || - undefined; + const descriptor = this.descriptors.longrunning[methodName] || undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -339,8 +402,14 @@ export class AnalyticsServiceClient { * @returns {string} The DNS address for this service. */ static get servicePath() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'retail.googleapis.com'; } @@ -352,8 +421,14 @@ export class AnalyticsServiceClient { * @returns {string} The DNS address for this service. */ static get apiEndpoint() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'retail.googleapis.com'; } @@ -384,9 +459,7 @@ export class AnalyticsServiceClient { * @returns {string[]} List of default scopes. */ static get scopes() { - return [ - 'https://www.googleapis.com/auth/cloud-platform' - ]; + return ['https://www.googleapis.com/auth/cloud-platform']; } getProjectId(): Promise; @@ -395,8 +468,9 @@ export class AnalyticsServiceClient { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId(callback?: Callback): - Promise|void { + getProjectId( + callback?: Callback, + ): Promise | void { if (callback) { this.auth.getProjectId(callback); return; @@ -408,136 +482,198 @@ export class AnalyticsServiceClient { // -- Service calls -- // ------------------- -/** - * Exports analytics metrics. - * - * `Operation.response` is of type `ExportAnalyticsMetricsResponse`. - * `Operation.metadata` is of type `ExportMetadata`. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.catalog - * Required. Full resource name of the parent catalog. - * Expected format: `projects/* /locations/* /catalogs/*` - * @param {google.cloud.retail.v2alpha.OutputConfig} request.outputConfig - * Required. The output location of the data. - * @param {string} request.filter - * A filtering expression to specify restrictions on returned metrics. - * The expression is a sequence of terms. Each term applies a restriction to - * the returned metrics. Use this expression to restrict results to a - * specific time range. - * - * Currently we expect only one types of fields: - * - * * `timestamp`: This can be specified twice, once with a - * less than operator and once with a greater than operator. The - * `timestamp` restriction should result in one, contiguous, valid, - * `timestamp` range. - * - * Some examples of valid filters expressions: - * - * * Example 1: `timestamp > "2012-04-23T18:25:43.511Z" - * timestamp < "2012-04-23T18:30:43.511Z"` - * * Example 2: `timestamp > "2012-04-23T18:25:43.511Z"` - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing - * a long running operation. Its `promise()` method returns a promise - * you can `await` for. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/analytics_service.export_analytics_metrics.js - * region_tag:retail_v2alpha_generated_AnalyticsService_ExportAnalyticsMetrics_async - */ + /** + * Exports analytics metrics. + * + * `Operation.response` is of type `ExportAnalyticsMetricsResponse`. + * `Operation.metadata` is of type `ExportMetadata`. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.catalog + * Required. Full resource name of the parent catalog. + * Expected format: `projects/* /locations/* /catalogs/*` + * @param {google.cloud.retail.v2alpha.OutputConfig} request.outputConfig + * Required. The output location of the data. + * @param {string} request.filter + * A filtering expression to specify restrictions on returned metrics. + * The expression is a sequence of terms. Each term applies a restriction to + * the returned metrics. Use this expression to restrict results to a + * specific time range. + * + * Currently we expect only one types of fields: + * + * * `timestamp`: This can be specified twice, once with a + * less than operator and once with a greater than operator. The + * `timestamp` restriction should result in one, contiguous, valid, + * `timestamp` range. + * + * Some examples of valid filters expressions: + * + * * Example 1: `timestamp > "2012-04-23T18:25:43.511Z" + * timestamp < "2012-04-23T18:30:43.511Z"` + * * Example 2: `timestamp > "2012-04-23T18:25:43.511Z"` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/analytics_service.export_analytics_metrics.js + * region_tag:retail_v2alpha_generated_AnalyticsService_ExportAnalyticsMetrics_async + */ exportAnalyticsMetrics( - request?: protos.google.cloud.retail.v2alpha.IExportAnalyticsMetricsRequest, - options?: CallOptions): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.IExportAnalyticsMetricsRequest, + options?: CallOptions, + ): Promise< + [ + LROperation< + protos.google.cloud.retail.v2alpha.IExportAnalyticsMetricsResponse, + protos.google.cloud.retail.v2alpha.IExportMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; exportAnalyticsMetrics( - request: protos.google.cloud.retail.v2alpha.IExportAnalyticsMetricsRequest, - options: CallOptions, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IExportAnalyticsMetricsRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IExportAnalyticsMetricsResponse, + protos.google.cloud.retail.v2alpha.IExportMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; exportAnalyticsMetrics( - request: protos.google.cloud.retail.v2alpha.IExportAnalyticsMetricsRequest, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IExportAnalyticsMetricsRequest, + callback: Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IExportAnalyticsMetricsResponse, + protos.google.cloud.retail.v2alpha.IExportMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; exportAnalyticsMetrics( - request?: protos.google.cloud.retail.v2alpha.IExportAnalyticsMetricsRequest, - optionsOrCallback?: CallOptions|Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>, - callback?: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>|void { + request?: protos.google.cloud.retail.v2alpha.IExportAnalyticsMetricsRequest, + optionsOrCallback?: + | CallOptions + | Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IExportAnalyticsMetricsResponse, + protos.google.cloud.retail.v2alpha.IExportMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + callback?: Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IExportAnalyticsMetricsResponse, + protos.google.cloud.retail.v2alpha.IExportMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + LROperation< + protos.google.cloud.retail.v2alpha.IExportAnalyticsMetricsResponse, + protos.google.cloud.retail.v2alpha.IExportMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'catalog': request.catalog ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + catalog: request.catalog ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IExportAnalyticsMetricsResponse, + protos.google.cloud.retail.v2alpha.IExportMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, rawResponse, _) => { this._log.info('exportAnalyticsMetrics response %j', rawResponse); callback!(error, response, rawResponse, _); // We verified `callback` above. } : undefined; this._log.info('exportAnalyticsMetrics request %j', request); - return this.innerApiCalls.exportAnalyticsMetrics(request, options, wrappedCallback) - ?.then(([response, rawResponse, _]: [ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]) => { - this._log.info('exportAnalyticsMetrics response %j', rawResponse); - return [response, rawResponse, _]; - }); + return this.innerApiCalls + .exportAnalyticsMetrics(request, options, wrappedCallback) + ?.then( + ([response, rawResponse, _]: [ + LROperation< + protos.google.cloud.retail.v2alpha.IExportAnalyticsMetricsResponse, + protos.google.cloud.retail.v2alpha.IExportMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ]) => { + this._log.info('exportAnalyticsMetrics response %j', rawResponse); + return [response, rawResponse, _]; + }, + ); } -/** - * Check the status of the long running operation returned by `exportAnalyticsMetrics()`. - * @param {String} name - * The operation name that will be passed. - * @returns {Promise} - The promise which resolves to an object. - * The decoded operation object has result and metadata field to get information from. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/analytics_service.export_analytics_metrics.js - * region_tag:retail_v2alpha_generated_AnalyticsService_ExportAnalyticsMetrics_async - */ - async checkExportAnalyticsMetricsProgress(name: string): Promise>{ + /** + * Check the status of the long running operation returned by `exportAnalyticsMetrics()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/analytics_service.export_analytics_metrics.js + * region_tag:retail_v2alpha_generated_AnalyticsService_ExportAnalyticsMetrics_async + */ + async checkExportAnalyticsMetricsProgress( + name: string, + ): Promise< + LROperation< + protos.google.cloud.retail.v2alpha.ExportAnalyticsMetricsResponse, + protos.google.cloud.retail.v2alpha.ExportMetadata + > + > { this._log.info('exportAnalyticsMetrics long-running'); - const request = new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest({name}); + const request = + new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( + { name }, + ); const [operation] = await this.operationsClient.getOperation(request); - const decodeOperation = new this._gaxModule.Operation(operation, this.descriptors.longrunning.exportAnalyticsMetrics, this._gaxModule.createDefaultBackoffSettings()); - return decodeOperation as LROperation; + const decodeOperation = new this._gaxModule.Operation( + operation, + this.descriptors.longrunning.exportAnalyticsMetrics, + this._gaxModule.createDefaultBackoffSettings(), + ); + return decodeOperation as LROperation< + protos.google.cloud.retail.v2alpha.ExportAnalyticsMetricsResponse, + protos.google.cloud.retail.v2alpha.ExportMetadata + >; } // -------------------- // -- Path templates -- @@ -549,7 +685,7 @@ export class AnalyticsServiceClient { * @param {string} project * @returns {string} Resource name string. */ - alertConfigPath(project:string) { + alertConfigPath(project: string) { return this.pathTemplates.alertConfigPathTemplate.render({ project: project, }); @@ -563,7 +699,8 @@ export class AnalyticsServiceClient { * @returns {string} A string representing the project. */ matchProjectFromAlertConfigName(alertConfigName: string) { - return this.pathTemplates.alertConfigPathTemplate.match(alertConfigName).project; + return this.pathTemplates.alertConfigPathTemplate.match(alertConfigName) + .project; } /** @@ -574,7 +711,7 @@ export class AnalyticsServiceClient { * @param {string} catalog * @returns {string} Resource name string. */ - attributesConfigPath(project:string,location:string,catalog:string) { + attributesConfigPath(project: string, location: string, catalog: string) { return this.pathTemplates.attributesConfigPathTemplate.render({ project: project, location: location, @@ -590,7 +727,9 @@ export class AnalyticsServiceClient { * @returns {string} A string representing the project. */ matchProjectFromAttributesConfigName(attributesConfigName: string) { - return this.pathTemplates.attributesConfigPathTemplate.match(attributesConfigName).project; + return this.pathTemplates.attributesConfigPathTemplate.match( + attributesConfigName, + ).project; } /** @@ -601,7 +740,9 @@ export class AnalyticsServiceClient { * @returns {string} A string representing the location. */ matchLocationFromAttributesConfigName(attributesConfigName: string) { - return this.pathTemplates.attributesConfigPathTemplate.match(attributesConfigName).location; + return this.pathTemplates.attributesConfigPathTemplate.match( + attributesConfigName, + ).location; } /** @@ -612,7 +753,9 @@ export class AnalyticsServiceClient { * @returns {string} A string representing the catalog. */ matchCatalogFromAttributesConfigName(attributesConfigName: string) { - return this.pathTemplates.attributesConfigPathTemplate.match(attributesConfigName).catalog; + return this.pathTemplates.attributesConfigPathTemplate.match( + attributesConfigName, + ).catalog; } /** @@ -624,7 +767,12 @@ export class AnalyticsServiceClient { * @param {string} branch * @returns {string} Resource name string. */ - branchPath(project:string,location:string,catalog:string,branch:string) { + branchPath( + project: string, + location: string, + catalog: string, + branch: string, + ) { return this.pathTemplates.branchPathTemplate.render({ project: project, location: location, @@ -685,7 +833,7 @@ export class AnalyticsServiceClient { * @param {string} catalog * @returns {string} Resource name string. */ - catalogPath(project:string,location:string,catalog:string) { + catalogPath(project: string, location: string, catalog: string) { return this.pathTemplates.catalogPathTemplate.render({ project: project, location: location, @@ -734,7 +882,7 @@ export class AnalyticsServiceClient { * @param {string} catalog * @returns {string} Resource name string. */ - completionConfigPath(project:string,location:string,catalog:string) { + completionConfigPath(project: string, location: string, catalog: string) { return this.pathTemplates.completionConfigPathTemplate.render({ project: project, location: location, @@ -750,7 +898,9 @@ export class AnalyticsServiceClient { * @returns {string} A string representing the project. */ matchProjectFromCompletionConfigName(completionConfigName: string) { - return this.pathTemplates.completionConfigPathTemplate.match(completionConfigName).project; + return this.pathTemplates.completionConfigPathTemplate.match( + completionConfigName, + ).project; } /** @@ -761,7 +911,9 @@ export class AnalyticsServiceClient { * @returns {string} A string representing the location. */ matchLocationFromCompletionConfigName(completionConfigName: string) { - return this.pathTemplates.completionConfigPathTemplate.match(completionConfigName).location; + return this.pathTemplates.completionConfigPathTemplate.match( + completionConfigName, + ).location; } /** @@ -772,7 +924,9 @@ export class AnalyticsServiceClient { * @returns {string} A string representing the catalog. */ matchCatalogFromCompletionConfigName(completionConfigName: string) { - return this.pathTemplates.completionConfigPathTemplate.match(completionConfigName).catalog; + return this.pathTemplates.completionConfigPathTemplate.match( + completionConfigName, + ).catalog; } /** @@ -784,7 +938,12 @@ export class AnalyticsServiceClient { * @param {string} control * @returns {string} Resource name string. */ - controlPath(project:string,location:string,catalog:string,control:string) { + controlPath( + project: string, + location: string, + catalog: string, + control: string, + ) { return this.pathTemplates.controlPathTemplate.render({ project: project, location: location, @@ -843,7 +1002,7 @@ export class AnalyticsServiceClient { * @param {string} project * @returns {string} Resource name string. */ - loggingConfigPath(project:string) { + loggingConfigPath(project: string) { return this.pathTemplates.loggingConfigPathTemplate.render({ project: project, }); @@ -857,7 +1016,8 @@ export class AnalyticsServiceClient { * @returns {string} A string representing the project. */ matchProjectFromLoggingConfigName(loggingConfigName: string) { - return this.pathTemplates.loggingConfigPathTemplate.match(loggingConfigName).project; + return this.pathTemplates.loggingConfigPathTemplate.match(loggingConfigName) + .project; } /** @@ -869,7 +1029,12 @@ export class AnalyticsServiceClient { * @param {string} merchant_center_account_link * @returns {string} Resource name string. */ - merchantCenterAccountLinkPath(project:string,location:string,catalog:string,merchantCenterAccountLink:string) { + merchantCenterAccountLinkPath( + project: string, + location: string, + catalog: string, + merchantCenterAccountLink: string, + ) { return this.pathTemplates.merchantCenterAccountLinkPathTemplate.render({ project: project, location: location, @@ -885,8 +1050,12 @@ export class AnalyticsServiceClient { * A fully-qualified path representing MerchantCenterAccountLink resource. * @returns {string} A string representing the project. */ - matchProjectFromMerchantCenterAccountLinkName(merchantCenterAccountLinkName: string) { - return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match(merchantCenterAccountLinkName).project; + matchProjectFromMerchantCenterAccountLinkName( + merchantCenterAccountLinkName: string, + ) { + return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match( + merchantCenterAccountLinkName, + ).project; } /** @@ -896,8 +1065,12 @@ export class AnalyticsServiceClient { * A fully-qualified path representing MerchantCenterAccountLink resource. * @returns {string} A string representing the location. */ - matchLocationFromMerchantCenterAccountLinkName(merchantCenterAccountLinkName: string) { - return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match(merchantCenterAccountLinkName).location; + matchLocationFromMerchantCenterAccountLinkName( + merchantCenterAccountLinkName: string, + ) { + return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match( + merchantCenterAccountLinkName, + ).location; } /** @@ -907,8 +1080,12 @@ export class AnalyticsServiceClient { * A fully-qualified path representing MerchantCenterAccountLink resource. * @returns {string} A string representing the catalog. */ - matchCatalogFromMerchantCenterAccountLinkName(merchantCenterAccountLinkName: string) { - return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match(merchantCenterAccountLinkName).catalog; + matchCatalogFromMerchantCenterAccountLinkName( + merchantCenterAccountLinkName: string, + ) { + return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match( + merchantCenterAccountLinkName, + ).catalog; } /** @@ -918,8 +1095,12 @@ export class AnalyticsServiceClient { * A fully-qualified path representing MerchantCenterAccountLink resource. * @returns {string} A string representing the merchant_center_account_link. */ - matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName(merchantCenterAccountLinkName: string) { - return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match(merchantCenterAccountLinkName).merchant_center_account_link; + matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName( + merchantCenterAccountLinkName: string, + ) { + return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match( + merchantCenterAccountLinkName, + ).merchant_center_account_link; } /** @@ -931,7 +1112,7 @@ export class AnalyticsServiceClient { * @param {string} model * @returns {string} Resource name string. */ - modelPath(project:string,location:string,catalog:string,model:string) { + modelPath(project: string, location: string, catalog: string, model: string) { return this.pathTemplates.modelPathTemplate.render({ project: project, location: location, @@ -994,7 +1175,13 @@ export class AnalyticsServiceClient { * @param {string} product * @returns {string} Resource name string. */ - productPath(project:string,location:string,catalog:string,branch:string,product:string) { + productPath( + project: string, + location: string, + catalog: string, + branch: string, + product: string, + ) { return this.pathTemplates.productPathTemplate.render({ project: project, location: location, @@ -1065,7 +1252,7 @@ export class AnalyticsServiceClient { * @param {string} project * @returns {string} Resource name string. */ - retailProjectPath(project:string) { + retailProjectPath(project: string) { return this.pathTemplates.retailProjectPathTemplate.render({ project: project, }); @@ -1079,7 +1266,8 @@ export class AnalyticsServiceClient { * @returns {string} A string representing the project. */ matchProjectFromRetailProjectName(retailProjectName: string) { - return this.pathTemplates.retailProjectPathTemplate.match(retailProjectName).project; + return this.pathTemplates.retailProjectPathTemplate.match(retailProjectName) + .project; } /** @@ -1091,7 +1279,12 @@ export class AnalyticsServiceClient { * @param {string} serving_config * @returns {string} Resource name string. */ - servingConfigPath(project:string,location:string,catalog:string,servingConfig:string) { + servingConfigPath( + project: string, + location: string, + catalog: string, + servingConfig: string, + ) { return this.pathTemplates.servingConfigPathTemplate.render({ project: project, location: location, @@ -1108,7 +1301,8 @@ export class AnalyticsServiceClient { * @returns {string} A string representing the project. */ matchProjectFromServingConfigName(servingConfigName: string) { - return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName).project; + return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName) + .project; } /** @@ -1119,7 +1313,8 @@ export class AnalyticsServiceClient { * @returns {string} A string representing the location. */ matchLocationFromServingConfigName(servingConfigName: string) { - return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName).location; + return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName) + .location; } /** @@ -1130,7 +1325,8 @@ export class AnalyticsServiceClient { * @returns {string} A string representing the catalog. */ matchCatalogFromServingConfigName(servingConfigName: string) { - return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName).catalog; + return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName) + .catalog; } /** @@ -1141,7 +1337,8 @@ export class AnalyticsServiceClient { * @returns {string} A string representing the serving_config. */ matchServingConfigFromServingConfigName(servingConfigName: string) { - return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName).serving_config; + return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName) + .serving_config; } /** @@ -1152,7 +1349,7 @@ export class AnalyticsServiceClient { */ close(): Promise { if (this.analyticsServiceStub && !this._terminated) { - return this.analyticsServiceStub.then(stub => { + return this.analyticsServiceStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -1161,4 +1358,4 @@ export class AnalyticsServiceClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/src/v2alpha/branch_service_client.ts.baseline b/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/src/v2alpha/branch_service_client.ts.baseline index ff2581330a0f..4c90f8115c9d 100644 --- a/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/src/v2alpha/branch_service_client.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/src/v2alpha/branch_service_client.ts.baseline @@ -18,15 +18,20 @@ /* global window */ import * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions} from 'google-gax'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, +} from 'google-gax'; // @ts-ignore import type * as protos from '../../../protos/protos.js'; import * as branch_service_client_config from './branch_service_client_config.json'; import fs from 'fs'; import path from 'path'; -import {fileURLToPath} from 'url'; -import {getJSON} from '../json-helper.cjs'; +import { fileURLToPath } from 'url'; +import { getJSON } from '../json-helper.cjs'; // @ts-ignore const dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -36,15 +41,15 @@ const dirname = path.dirname(fileURLToPath(import.meta.url)); * This file defines retry strategy and timeouts for all API methods in this library. */ const gapicConfig = getJSON( - path.join(dirname, 'branch_service_client_config.json') + path.join(dirname, 'branch_service_client_config.json'), ); const jsonProtos = getJSON( - path.join(dirname, '..', '..', '..', 'protos/protos.json') + path.join(dirname, '..', '..', '..', 'protos/protos.json'), ); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; const version = getJSON( - path.join(dirname, '..', '..', '..', '..', 'package.json') + path.join(dirname, '..', '..', '..', '..', 'package.json'), ).version; /** @@ -65,7 +70,7 @@ export class BranchServiceClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('retail'); @@ -77,9 +82,9 @@ export class BranchServiceClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; - branchServiceStub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; + branchServiceStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of BranchServiceClient. @@ -121,21 +126,42 @@ export class BranchServiceClient { * const client = new BranchServiceClient({fallback: 'rest'}, gax); * ``` */ - constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { // Ensure that options include all the required fields. const staticMembers = this.constructor as typeof BranchServiceClient; - if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { - throw new Error('Please set either universe_domain or universeDomain, but not both.'); + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); } - const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; - this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; this._servicePath = 'retail.' + this._universeDomain; - const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; - const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. if (servicePath !== this._servicePath && !('scopes' in opts)) { @@ -157,7 +183,7 @@ export class BranchServiceClient { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; @@ -174,10 +200,7 @@ export class BranchServiceClient { const isEsm = true; const isEsmString = isEsm ? '-esm' : '-cjs'; // Determine the client header string. - const clientHeader = [ - `gax/${this._gaxModule.version}`, - `gapic/${version}`, - ]; + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/{process.versions.node}${isEsmString}`); } else { @@ -185,7 +208,7 @@ export class BranchServiceClient { } if (!opts.fallback) { clientHeader.push(`grpc/${this._gaxGrpc.grpcVersion}`); - } else if (opts.fallback === 'rest' ) { + } else if (opts.fallback === 'rest') { clientHeader.push(`rest/${this._gaxGrpc.grpcVersion}`); } if (opts.libName && opts.libVersion) { @@ -193,54 +216,59 @@ export class BranchServiceClient { } // Load the applicable protos. - this._protos = this._gaxGrpc.loadProtoJSON(jsonProtos as gax.protobuf.INamespace); + this._protos = this._gaxGrpc.loadProtoJSON( + jsonProtos as gax.protobuf.INamespace, + ); // This API contains "path templates"; forward-slash-separated // identifiers to uniquely identify resources within the API. // Create useful helper objects for these. this.pathTemplates = { alertConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/alertConfig' + 'projects/{project}/alertConfig', ), attributesConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/attributesConfig' + 'projects/{project}/locations/{location}/catalogs/{catalog}/attributesConfig', ), branchPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}', ), catalogPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}' + 'projects/{project}/locations/{location}/catalogs/{catalog}', ), completionConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/completionConfig' + 'projects/{project}/locations/{location}/catalogs/{catalog}/completionConfig', ), controlPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/controls/{control}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/controls/{control}', ), loggingConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/loggingConfig' + 'projects/{project}/loggingConfig', ), merchantCenterAccountLinkPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/merchantCenterAccountLinks/{merchant_center_account_link}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/merchantCenterAccountLinks/{merchant_center_account_link}', ), modelPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/models/{model}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/models/{model}', ), productPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}', ), retailProjectPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/retailProject' + 'projects/{project}/retailProject', ), servingConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/servingConfigs/{serving_config}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/servingConfigs/{serving_config}', ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.cloud.retail.v2alpha.BranchService', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.cloud.retail.v2alpha.BranchService', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + { 'x-goog-api-client': clientHeader.join(' ') }, + ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -271,36 +299,40 @@ export class BranchServiceClient { // Put together the "service stub" for // google.cloud.retail.v2alpha.BranchService. this.branchServiceStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.cloud.retail.v2alpha.BranchService') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.cloud.retail.v2alpha.BranchService', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.cloud.retail.v2alpha.BranchService, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts, + this._providedCustomServicePath, + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const branchServiceStubMethods = - ['listBranches', 'getBranch']; + const branchServiceStubMethods = ['listBranches', 'getBranch']; for (const methodName of branchServiceStubMethods) { const callPromise = this.branchServiceStub.then( - stub => (...args: Array<{}>) => { - if (this._terminated) { - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error|null|undefined) => () => { + (stub) => + (...args: Array<{}>) => { + if (this._terminated) { + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { throw err; - }); + }, + ); - const descriptor = - undefined; + const descriptor = undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -315,8 +347,14 @@ export class BranchServiceClient { * @returns {string} The DNS address for this service. */ static get servicePath() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'retail.googleapis.com'; } @@ -328,8 +366,14 @@ export class BranchServiceClient { * @returns {string} The DNS address for this service. */ static get apiEndpoint() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'retail.googleapis.com'; } @@ -360,9 +404,7 @@ export class BranchServiceClient { * @returns {string[]} List of default scopes. */ static get scopes() { - return [ - 'https://www.googleapis.com/auth/cloud-platform' - ]; + return ['https://www.googleapis.com/auth/cloud-platform']; } getProjectId(): Promise; @@ -371,8 +413,9 @@ export class BranchServiceClient { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId(callback?: Callback): - Promise|void { + getProjectId( + callback?: Callback, + ): Promise | void { if (callback) { this.auth.getProjectId(callback); return; @@ -383,206 +426,282 @@ export class BranchServiceClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Lists all instances of {@link protos.google.cloud.retail.v2alpha.Branch|Branch} under - * the specified parent {@link protos.google.cloud.retail.v2alpha.Catalog|Catalog}. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent catalog resource name. - * @param {google.cloud.retail.v2alpha.BranchView} request.view - * The view to apply to the returned - * {@link protos.google.cloud.retail.v2alpha.Branch|Branch}. Defaults to - * [Branch.BranchView.BASIC] if unspecified. - * See documentation of fields of {@link protos.google.cloud.retail.v2alpha.Branch|Branch} - * to find what fields are excluded from BASIC view. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.ListBranchesResponse|ListBranchesResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/branch_service.list_branches.js - * region_tag:retail_v2alpha_generated_BranchService_ListBranches_async - */ + /** + * Lists all instances of {@link protos.google.cloud.retail.v2alpha.Branch|Branch} under + * the specified parent {@link protos.google.cloud.retail.v2alpha.Catalog|Catalog}. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent catalog resource name. + * @param {google.cloud.retail.v2alpha.BranchView} request.view + * The view to apply to the returned + * {@link protos.google.cloud.retail.v2alpha.Branch|Branch}. Defaults to + * [Branch.BranchView.BASIC] if unspecified. + * See documentation of fields of {@link protos.google.cloud.retail.v2alpha.Branch|Branch} + * to find what fields are excluded from BASIC view. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.ListBranchesResponse|ListBranchesResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/branch_service.list_branches.js + * region_tag:retail_v2alpha_generated_BranchService_ListBranches_async + */ listBranches( - request?: protos.google.cloud.retail.v2alpha.IListBranchesRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.retail.v2alpha.IListBranchesResponse, - protos.google.cloud.retail.v2alpha.IListBranchesRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.IListBranchesRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IListBranchesResponse, + protos.google.cloud.retail.v2alpha.IListBranchesRequest | undefined, + {} | undefined, + ] + >; listBranches( - request: protos.google.cloud.retail.v2alpha.IListBranchesRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.retail.v2alpha.IListBranchesResponse, - protos.google.cloud.retail.v2alpha.IListBranchesRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IListBranchesRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.retail.v2alpha.IListBranchesResponse, + | protos.google.cloud.retail.v2alpha.IListBranchesRequest + | null + | undefined, + {} | null | undefined + >, + ): void; listBranches( - request: protos.google.cloud.retail.v2alpha.IListBranchesRequest, - callback: Callback< - protos.google.cloud.retail.v2alpha.IListBranchesResponse, - protos.google.cloud.retail.v2alpha.IListBranchesRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IListBranchesRequest, + callback: Callback< + protos.google.cloud.retail.v2alpha.IListBranchesResponse, + | protos.google.cloud.retail.v2alpha.IListBranchesRequest + | null + | undefined, + {} | null | undefined + >, + ): void; listBranches( - request?: protos.google.cloud.retail.v2alpha.IListBranchesRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.retail.v2alpha.IListBranchesResponse, - protos.google.cloud.retail.v2alpha.IListBranchesRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.retail.v2alpha.IListBranchesRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.retail.v2alpha.IListBranchesResponse, - protos.google.cloud.retail.v2alpha.IListBranchesRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.retail.v2alpha.IListBranchesResponse, - protos.google.cloud.retail.v2alpha.IListBranchesRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.retail.v2alpha.IListBranchesRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.retail.v2alpha.IListBranchesResponse, + | protos.google.cloud.retail.v2alpha.IListBranchesRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IListBranchesResponse, + protos.google.cloud.retail.v2alpha.IListBranchesRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('listBranches request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.retail.v2alpha.IListBranchesResponse, - protos.google.cloud.retail.v2alpha.IListBranchesRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.retail.v2alpha.IListBranchesResponse, + | protos.google.cloud.retail.v2alpha.IListBranchesRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('listBranches response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.listBranches(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.retail.v2alpha.IListBranchesResponse, - protos.google.cloud.retail.v2alpha.IListBranchesRequest|undefined, {}|undefined - ]) => { - this._log.info('listBranches response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .listBranches(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.retail.v2alpha.IListBranchesResponse, + protos.google.cloud.retail.v2alpha.IListBranchesRequest | undefined, + {} | undefined, + ]) => { + this._log.info('listBranches response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Retrieves a {@link protos.google.cloud.retail.v2alpha.Branch|Branch}. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The name of the branch to retrieve. - * Format: - * `projects/* /locations/global/catalogs/default_catalog/branches/some_branch_id`. - * - * "default_branch" can be used as a special branch_id, it returns the - * default branch that has been set for the catalog. - * @param {google.cloud.retail.v2alpha.BranchView} request.view - * The view to apply to the returned - * {@link protos.google.cloud.retail.v2alpha.Branch|Branch}. Defaults to - * [Branch.BranchView.BASIC] if unspecified. - * See documentation of fields of {@link protos.google.cloud.retail.v2alpha.Branch|Branch} - * to find what fields are excluded from BASIC view. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.Branch|Branch}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/branch_service.get_branch.js - * region_tag:retail_v2alpha_generated_BranchService_GetBranch_async - */ + /** + * Retrieves a {@link protos.google.cloud.retail.v2alpha.Branch|Branch}. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The name of the branch to retrieve. + * Format: + * `projects/* /locations/global/catalogs/default_catalog/branches/some_branch_id`. + * + * "default_branch" can be used as a special branch_id, it returns the + * default branch that has been set for the catalog. + * @param {google.cloud.retail.v2alpha.BranchView} request.view + * The view to apply to the returned + * {@link protos.google.cloud.retail.v2alpha.Branch|Branch}. Defaults to + * [Branch.BranchView.BASIC] if unspecified. + * See documentation of fields of {@link protos.google.cloud.retail.v2alpha.Branch|Branch} + * to find what fields are excluded from BASIC view. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.Branch|Branch}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/branch_service.get_branch.js + * region_tag:retail_v2alpha_generated_BranchService_GetBranch_async + */ getBranch( - request?: protos.google.cloud.retail.v2alpha.IGetBranchRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.retail.v2alpha.IBranch, - protos.google.cloud.retail.v2alpha.IGetBranchRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.IGetBranchRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IBranch, + protos.google.cloud.retail.v2alpha.IGetBranchRequest | undefined, + {} | undefined, + ] + >; getBranch( - request: protos.google.cloud.retail.v2alpha.IGetBranchRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.retail.v2alpha.IBranch, - protos.google.cloud.retail.v2alpha.IGetBranchRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IGetBranchRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.retail.v2alpha.IBranch, + protos.google.cloud.retail.v2alpha.IGetBranchRequest | null | undefined, + {} | null | undefined + >, + ): void; getBranch( - request: protos.google.cloud.retail.v2alpha.IGetBranchRequest, - callback: Callback< - protos.google.cloud.retail.v2alpha.IBranch, - protos.google.cloud.retail.v2alpha.IGetBranchRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IGetBranchRequest, + callback: Callback< + protos.google.cloud.retail.v2alpha.IBranch, + protos.google.cloud.retail.v2alpha.IGetBranchRequest | null | undefined, + {} | null | undefined + >, + ): void; getBranch( - request?: protos.google.cloud.retail.v2alpha.IGetBranchRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.retail.v2alpha.IBranch, - protos.google.cloud.retail.v2alpha.IGetBranchRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.retail.v2alpha.IGetBranchRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.retail.v2alpha.IBranch, - protos.google.cloud.retail.v2alpha.IGetBranchRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.retail.v2alpha.IBranch, - protos.google.cloud.retail.v2alpha.IGetBranchRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.retail.v2alpha.IGetBranchRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.retail.v2alpha.IBranch, + protos.google.cloud.retail.v2alpha.IGetBranchRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IBranch, + protos.google.cloud.retail.v2alpha.IGetBranchRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getBranch request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.retail.v2alpha.IBranch, - protos.google.cloud.retail.v2alpha.IGetBranchRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.retail.v2alpha.IBranch, + | protos.google.cloud.retail.v2alpha.IGetBranchRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getBranch response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.getBranch(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.retail.v2alpha.IBranch, - protos.google.cloud.retail.v2alpha.IGetBranchRequest|undefined, {}|undefined - ]) => { - this._log.info('getBranch response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getBranch(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.retail.v2alpha.IBranch, + protos.google.cloud.retail.v2alpha.IGetBranchRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getBranch response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); @@ -598,7 +717,7 @@ export class BranchServiceClient { * @param {string} project * @returns {string} Resource name string. */ - alertConfigPath(project:string) { + alertConfigPath(project: string) { return this.pathTemplates.alertConfigPathTemplate.render({ project: project, }); @@ -612,7 +731,8 @@ export class BranchServiceClient { * @returns {string} A string representing the project. */ matchProjectFromAlertConfigName(alertConfigName: string) { - return this.pathTemplates.alertConfigPathTemplate.match(alertConfigName).project; + return this.pathTemplates.alertConfigPathTemplate.match(alertConfigName) + .project; } /** @@ -623,7 +743,7 @@ export class BranchServiceClient { * @param {string} catalog * @returns {string} Resource name string. */ - attributesConfigPath(project:string,location:string,catalog:string) { + attributesConfigPath(project: string, location: string, catalog: string) { return this.pathTemplates.attributesConfigPathTemplate.render({ project: project, location: location, @@ -639,7 +759,9 @@ export class BranchServiceClient { * @returns {string} A string representing the project. */ matchProjectFromAttributesConfigName(attributesConfigName: string) { - return this.pathTemplates.attributesConfigPathTemplate.match(attributesConfigName).project; + return this.pathTemplates.attributesConfigPathTemplate.match( + attributesConfigName, + ).project; } /** @@ -650,7 +772,9 @@ export class BranchServiceClient { * @returns {string} A string representing the location. */ matchLocationFromAttributesConfigName(attributesConfigName: string) { - return this.pathTemplates.attributesConfigPathTemplate.match(attributesConfigName).location; + return this.pathTemplates.attributesConfigPathTemplate.match( + attributesConfigName, + ).location; } /** @@ -661,7 +785,9 @@ export class BranchServiceClient { * @returns {string} A string representing the catalog. */ matchCatalogFromAttributesConfigName(attributesConfigName: string) { - return this.pathTemplates.attributesConfigPathTemplate.match(attributesConfigName).catalog; + return this.pathTemplates.attributesConfigPathTemplate.match( + attributesConfigName, + ).catalog; } /** @@ -673,7 +799,12 @@ export class BranchServiceClient { * @param {string} branch * @returns {string} Resource name string. */ - branchPath(project:string,location:string,catalog:string,branch:string) { + branchPath( + project: string, + location: string, + catalog: string, + branch: string, + ) { return this.pathTemplates.branchPathTemplate.render({ project: project, location: location, @@ -734,7 +865,7 @@ export class BranchServiceClient { * @param {string} catalog * @returns {string} Resource name string. */ - catalogPath(project:string,location:string,catalog:string) { + catalogPath(project: string, location: string, catalog: string) { return this.pathTemplates.catalogPathTemplate.render({ project: project, location: location, @@ -783,7 +914,7 @@ export class BranchServiceClient { * @param {string} catalog * @returns {string} Resource name string. */ - completionConfigPath(project:string,location:string,catalog:string) { + completionConfigPath(project: string, location: string, catalog: string) { return this.pathTemplates.completionConfigPathTemplate.render({ project: project, location: location, @@ -799,7 +930,9 @@ export class BranchServiceClient { * @returns {string} A string representing the project. */ matchProjectFromCompletionConfigName(completionConfigName: string) { - return this.pathTemplates.completionConfigPathTemplate.match(completionConfigName).project; + return this.pathTemplates.completionConfigPathTemplate.match( + completionConfigName, + ).project; } /** @@ -810,7 +943,9 @@ export class BranchServiceClient { * @returns {string} A string representing the location. */ matchLocationFromCompletionConfigName(completionConfigName: string) { - return this.pathTemplates.completionConfigPathTemplate.match(completionConfigName).location; + return this.pathTemplates.completionConfigPathTemplate.match( + completionConfigName, + ).location; } /** @@ -821,7 +956,9 @@ export class BranchServiceClient { * @returns {string} A string representing the catalog. */ matchCatalogFromCompletionConfigName(completionConfigName: string) { - return this.pathTemplates.completionConfigPathTemplate.match(completionConfigName).catalog; + return this.pathTemplates.completionConfigPathTemplate.match( + completionConfigName, + ).catalog; } /** @@ -833,7 +970,12 @@ export class BranchServiceClient { * @param {string} control * @returns {string} Resource name string. */ - controlPath(project:string,location:string,catalog:string,control:string) { + controlPath( + project: string, + location: string, + catalog: string, + control: string, + ) { return this.pathTemplates.controlPathTemplate.render({ project: project, location: location, @@ -892,7 +1034,7 @@ export class BranchServiceClient { * @param {string} project * @returns {string} Resource name string. */ - loggingConfigPath(project:string) { + loggingConfigPath(project: string) { return this.pathTemplates.loggingConfigPathTemplate.render({ project: project, }); @@ -906,7 +1048,8 @@ export class BranchServiceClient { * @returns {string} A string representing the project. */ matchProjectFromLoggingConfigName(loggingConfigName: string) { - return this.pathTemplates.loggingConfigPathTemplate.match(loggingConfigName).project; + return this.pathTemplates.loggingConfigPathTemplate.match(loggingConfigName) + .project; } /** @@ -918,7 +1061,12 @@ export class BranchServiceClient { * @param {string} merchant_center_account_link * @returns {string} Resource name string. */ - merchantCenterAccountLinkPath(project:string,location:string,catalog:string,merchantCenterAccountLink:string) { + merchantCenterAccountLinkPath( + project: string, + location: string, + catalog: string, + merchantCenterAccountLink: string, + ) { return this.pathTemplates.merchantCenterAccountLinkPathTemplate.render({ project: project, location: location, @@ -934,8 +1082,12 @@ export class BranchServiceClient { * A fully-qualified path representing MerchantCenterAccountLink resource. * @returns {string} A string representing the project. */ - matchProjectFromMerchantCenterAccountLinkName(merchantCenterAccountLinkName: string) { - return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match(merchantCenterAccountLinkName).project; + matchProjectFromMerchantCenterAccountLinkName( + merchantCenterAccountLinkName: string, + ) { + return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match( + merchantCenterAccountLinkName, + ).project; } /** @@ -945,8 +1097,12 @@ export class BranchServiceClient { * A fully-qualified path representing MerchantCenterAccountLink resource. * @returns {string} A string representing the location. */ - matchLocationFromMerchantCenterAccountLinkName(merchantCenterAccountLinkName: string) { - return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match(merchantCenterAccountLinkName).location; + matchLocationFromMerchantCenterAccountLinkName( + merchantCenterAccountLinkName: string, + ) { + return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match( + merchantCenterAccountLinkName, + ).location; } /** @@ -956,8 +1112,12 @@ export class BranchServiceClient { * A fully-qualified path representing MerchantCenterAccountLink resource. * @returns {string} A string representing the catalog. */ - matchCatalogFromMerchantCenterAccountLinkName(merchantCenterAccountLinkName: string) { - return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match(merchantCenterAccountLinkName).catalog; + matchCatalogFromMerchantCenterAccountLinkName( + merchantCenterAccountLinkName: string, + ) { + return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match( + merchantCenterAccountLinkName, + ).catalog; } /** @@ -967,8 +1127,12 @@ export class BranchServiceClient { * A fully-qualified path representing MerchantCenterAccountLink resource. * @returns {string} A string representing the merchant_center_account_link. */ - matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName(merchantCenterAccountLinkName: string) { - return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match(merchantCenterAccountLinkName).merchant_center_account_link; + matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName( + merchantCenterAccountLinkName: string, + ) { + return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match( + merchantCenterAccountLinkName, + ).merchant_center_account_link; } /** @@ -980,7 +1144,7 @@ export class BranchServiceClient { * @param {string} model * @returns {string} Resource name string. */ - modelPath(project:string,location:string,catalog:string,model:string) { + modelPath(project: string, location: string, catalog: string, model: string) { return this.pathTemplates.modelPathTemplate.render({ project: project, location: location, @@ -1043,7 +1207,13 @@ export class BranchServiceClient { * @param {string} product * @returns {string} Resource name string. */ - productPath(project:string,location:string,catalog:string,branch:string,product:string) { + productPath( + project: string, + location: string, + catalog: string, + branch: string, + product: string, + ) { return this.pathTemplates.productPathTemplate.render({ project: project, location: location, @@ -1114,7 +1284,7 @@ export class BranchServiceClient { * @param {string} project * @returns {string} Resource name string. */ - retailProjectPath(project:string) { + retailProjectPath(project: string) { return this.pathTemplates.retailProjectPathTemplate.render({ project: project, }); @@ -1128,7 +1298,8 @@ export class BranchServiceClient { * @returns {string} A string representing the project. */ matchProjectFromRetailProjectName(retailProjectName: string) { - return this.pathTemplates.retailProjectPathTemplate.match(retailProjectName).project; + return this.pathTemplates.retailProjectPathTemplate.match(retailProjectName) + .project; } /** @@ -1140,7 +1311,12 @@ export class BranchServiceClient { * @param {string} serving_config * @returns {string} Resource name string. */ - servingConfigPath(project:string,location:string,catalog:string,servingConfig:string) { + servingConfigPath( + project: string, + location: string, + catalog: string, + servingConfig: string, + ) { return this.pathTemplates.servingConfigPathTemplate.render({ project: project, location: location, @@ -1157,7 +1333,8 @@ export class BranchServiceClient { * @returns {string} A string representing the project. */ matchProjectFromServingConfigName(servingConfigName: string) { - return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName).project; + return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName) + .project; } /** @@ -1168,7 +1345,8 @@ export class BranchServiceClient { * @returns {string} A string representing the location. */ matchLocationFromServingConfigName(servingConfigName: string) { - return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName).location; + return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName) + .location; } /** @@ -1179,7 +1357,8 @@ export class BranchServiceClient { * @returns {string} A string representing the catalog. */ matchCatalogFromServingConfigName(servingConfigName: string) { - return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName).catalog; + return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName) + .catalog; } /** @@ -1190,7 +1369,8 @@ export class BranchServiceClient { * @returns {string} A string representing the serving_config. */ matchServingConfigFromServingConfigName(servingConfigName: string) { - return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName).serving_config; + return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName) + .serving_config; } /** @@ -1201,7 +1381,7 @@ export class BranchServiceClient { */ close(): Promise { if (this.branchServiceStub && !this._terminated) { - return this.branchServiceStub.then(stub => { + return this.branchServiceStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -1209,4 +1389,4 @@ export class BranchServiceClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/src/v2alpha/catalog_service_client.ts.baseline b/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/src/v2alpha/catalog_service_client.ts.baseline index 34ffc508aefa..3c342e516f4a 100644 --- a/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/src/v2alpha/catalog_service_client.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/src/v2alpha/catalog_service_client.ts.baseline @@ -18,15 +18,22 @@ /* global window */ import * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions, PaginationCallback, GaxCall} from 'google-gax'; -import {Transform} from 'stream'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + PaginationCallback, + GaxCall, +} from 'google-gax'; +import { Transform } from 'stream'; // @ts-ignore import type * as protos from '../../../protos/protos.js'; import * as catalog_service_client_config from './catalog_service_client_config.json'; import fs from 'fs'; import path from 'path'; -import {fileURLToPath} from 'url'; -import {getJSON} from '../json-helper.cjs'; +import { fileURLToPath } from 'url'; +import { getJSON } from '../json-helper.cjs'; // @ts-ignore const dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -36,15 +43,15 @@ const dirname = path.dirname(fileURLToPath(import.meta.url)); * This file defines retry strategy and timeouts for all API methods in this library. */ const gapicConfig = getJSON( - path.join(dirname, 'catalog_service_client_config.json') + path.join(dirname, 'catalog_service_client_config.json'), ); const jsonProtos = getJSON( - path.join(dirname, '..', '..', '..', 'protos/protos.json') + path.join(dirname, '..', '..', '..', 'protos/protos.json'), ); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; const version = getJSON( - path.join(dirname, '..', '..', '..', '..', 'package.json') + path.join(dirname, '..', '..', '..', '..', 'package.json'), ).version; /** @@ -59,7 +66,7 @@ export class CatalogServiceClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('retail'); @@ -71,9 +78,9 @@ export class CatalogServiceClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; - catalogServiceStub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; + catalogServiceStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of CatalogServiceClient. @@ -115,21 +122,42 @@ export class CatalogServiceClient { * const client = new CatalogServiceClient({fallback: 'rest'}, gax); * ``` */ - constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { // Ensure that options include all the required fields. const staticMembers = this.constructor as typeof CatalogServiceClient; - if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { - throw new Error('Please set either universe_domain or universeDomain, but not both.'); + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); } - const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; - this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; this._servicePath = 'retail.' + this._universeDomain; - const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; - const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. if (servicePath !== this._servicePath && !('scopes' in opts)) { @@ -151,7 +179,7 @@ export class CatalogServiceClient { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; @@ -168,10 +196,7 @@ export class CatalogServiceClient { const isEsm = true; const isEsmString = isEsm ? '-esm' : '-cjs'; // Determine the client header string. - const clientHeader = [ - `gax/${this._gaxModule.version}`, - `gapic/${version}`, - ]; + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/{process.versions.node}${isEsmString}`); } else { @@ -179,7 +204,7 @@ export class CatalogServiceClient { } if (!opts.fallback) { clientHeader.push(`grpc/${this._gaxGrpc.grpcVersion}`); - } else if (opts.fallback === 'rest' ) { + } else if (opts.fallback === 'rest') { clientHeader.push(`rest/${this._gaxGrpc.grpcVersion}`); } if (opts.libName && opts.libVersion) { @@ -187,50 +212,52 @@ export class CatalogServiceClient { } // Load the applicable protos. - this._protos = this._gaxGrpc.loadProtoJSON(jsonProtos as gax.protobuf.INamespace); + this._protos = this._gaxGrpc.loadProtoJSON( + jsonProtos as gax.protobuf.INamespace, + ); // This API contains "path templates"; forward-slash-separated // identifiers to uniquely identify resources within the API. // Create useful helper objects for these. this.pathTemplates = { alertConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/alertConfig' + 'projects/{project}/alertConfig', ), attributesConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/attributesConfig' + 'projects/{project}/locations/{location}/catalogs/{catalog}/attributesConfig', ), branchPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}', ), catalogPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}' + 'projects/{project}/locations/{location}/catalogs/{catalog}', ), completionConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/completionConfig' + 'projects/{project}/locations/{location}/catalogs/{catalog}/completionConfig', ), controlPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/controls/{control}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/controls/{control}', ), locationPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}' + 'projects/{project}/locations/{location}', ), loggingConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/loggingConfig' + 'projects/{project}/loggingConfig', ), merchantCenterAccountLinkPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/merchantCenterAccountLinks/{merchant_center_account_link}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/merchantCenterAccountLinks/{merchant_center_account_link}', ), modelPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/models/{model}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/models/{model}', ), productPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}', ), retailProjectPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/retailProject' + 'projects/{project}/retailProject', ), servingConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/servingConfigs/{serving_config}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/servingConfigs/{serving_config}', ), }; @@ -238,14 +265,20 @@ export class CatalogServiceClient { // (e.g. 50 results at a time, with tokens to get subsequent // pages). Denote the keys used for pagination and results. this.descriptors.page = { - listCatalogs: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'catalogs') + listCatalogs: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'catalogs', + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.cloud.retail.v2alpha.CatalogService', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.cloud.retail.v2alpha.CatalogService', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + { 'x-goog-api-client': clientHeader.join(' ') }, + ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -276,37 +309,53 @@ export class CatalogServiceClient { // Put together the "service stub" for // google.cloud.retail.v2alpha.CatalogService. this.catalogServiceStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.cloud.retail.v2alpha.CatalogService') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.cloud.retail.v2alpha.CatalogService', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.cloud.retail.v2alpha.CatalogService, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts, + this._providedCustomServicePath, + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const catalogServiceStubMethods = - ['listCatalogs', 'updateCatalog', 'setDefaultBranch', 'getDefaultBranch', 'getCompletionConfig', 'updateCompletionConfig', 'getAttributesConfig', 'updateAttributesConfig', 'addCatalogAttribute', 'removeCatalogAttribute', 'batchRemoveCatalogAttributes', 'replaceCatalogAttribute']; + const catalogServiceStubMethods = [ + 'listCatalogs', + 'updateCatalog', + 'setDefaultBranch', + 'getDefaultBranch', + 'getCompletionConfig', + 'updateCompletionConfig', + 'getAttributesConfig', + 'updateAttributesConfig', + 'addCatalogAttribute', + 'removeCatalogAttribute', + 'batchRemoveCatalogAttributes', + 'replaceCatalogAttribute', + ]; for (const methodName of catalogServiceStubMethods) { const callPromise = this.catalogServiceStub.then( - stub => (...args: Array<{}>) => { - if (this._terminated) { - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error|null|undefined) => () => { + (stub) => + (...args: Array<{}>) => { + if (this._terminated) { + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { throw err; - }); + }, + ); - const descriptor = - this.descriptors.page[methodName] || - undefined; + const descriptor = this.descriptors.page[methodName] || undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -321,8 +370,14 @@ export class CatalogServiceClient { * @returns {string} The DNS address for this service. */ static get servicePath() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'retail.googleapis.com'; } @@ -334,8 +389,14 @@ export class CatalogServiceClient { * @returns {string} The DNS address for this service. */ static get apiEndpoint() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'retail.googleapis.com'; } @@ -366,9 +427,7 @@ export class CatalogServiceClient { * @returns {string[]} List of default scopes. */ static get scopes() { - return [ - 'https://www.googleapis.com/auth/cloud-platform' - ]; + return ['https://www.googleapis.com/auth/cloud-platform']; } getProjectId(): Promise; @@ -377,8 +436,9 @@ export class CatalogServiceClient { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId(callback?: Callback): - Promise|void { + getProjectId( + callback?: Callback, + ): Promise | void { if (callback) { this.auth.getProjectId(callback); return; @@ -389,1284 +449,1838 @@ export class CatalogServiceClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Updates the {@link protos.google.cloud.retail.v2alpha.Catalog|Catalog}s. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.cloud.retail.v2alpha.Catalog} request.catalog - * Required. The {@link protos.google.cloud.retail.v2alpha.Catalog|Catalog} to update. - * - * If the caller does not have permission to update the - * {@link protos.google.cloud.retail.v2alpha.Catalog|Catalog}, regardless of whether or - * not it exists, a PERMISSION_DENIED error is returned. - * - * If the {@link protos.google.cloud.retail.v2alpha.Catalog|Catalog} to update does not - * exist, a NOT_FOUND error is returned. - * @param {google.protobuf.FieldMask} request.updateMask - * Indicates which fields in the provided - * {@link protos.google.cloud.retail.v2alpha.Catalog|Catalog} to update. - * - * If an unsupported or unknown field is provided, an INVALID_ARGUMENT error - * is returned. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.Catalog|Catalog}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/catalog_service.update_catalog.js - * region_tag:retail_v2alpha_generated_CatalogService_UpdateCatalog_async - */ + /** + * Updates the {@link protos.google.cloud.retail.v2alpha.Catalog|Catalog}s. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.cloud.retail.v2alpha.Catalog} request.catalog + * Required. The {@link protos.google.cloud.retail.v2alpha.Catalog|Catalog} to update. + * + * If the caller does not have permission to update the + * {@link protos.google.cloud.retail.v2alpha.Catalog|Catalog}, regardless of whether or + * not it exists, a PERMISSION_DENIED error is returned. + * + * If the {@link protos.google.cloud.retail.v2alpha.Catalog|Catalog} to update does not + * exist, a NOT_FOUND error is returned. + * @param {google.protobuf.FieldMask} request.updateMask + * Indicates which fields in the provided + * {@link protos.google.cloud.retail.v2alpha.Catalog|Catalog} to update. + * + * If an unsupported or unknown field is provided, an INVALID_ARGUMENT error + * is returned. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.Catalog|Catalog}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/catalog_service.update_catalog.js + * region_tag:retail_v2alpha_generated_CatalogService_UpdateCatalog_async + */ updateCatalog( - request?: protos.google.cloud.retail.v2alpha.IUpdateCatalogRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.retail.v2alpha.ICatalog, - protos.google.cloud.retail.v2alpha.IUpdateCatalogRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.IUpdateCatalogRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.ICatalog, + protos.google.cloud.retail.v2alpha.IUpdateCatalogRequest | undefined, + {} | undefined, + ] + >; updateCatalog( - request: protos.google.cloud.retail.v2alpha.IUpdateCatalogRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.retail.v2alpha.ICatalog, - protos.google.cloud.retail.v2alpha.IUpdateCatalogRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IUpdateCatalogRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.retail.v2alpha.ICatalog, + | protos.google.cloud.retail.v2alpha.IUpdateCatalogRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateCatalog( - request: protos.google.cloud.retail.v2alpha.IUpdateCatalogRequest, - callback: Callback< - protos.google.cloud.retail.v2alpha.ICatalog, - protos.google.cloud.retail.v2alpha.IUpdateCatalogRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IUpdateCatalogRequest, + callback: Callback< + protos.google.cloud.retail.v2alpha.ICatalog, + | protos.google.cloud.retail.v2alpha.IUpdateCatalogRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateCatalog( - request?: protos.google.cloud.retail.v2alpha.IUpdateCatalogRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.retail.v2alpha.ICatalog, - protos.google.cloud.retail.v2alpha.IUpdateCatalogRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.retail.v2alpha.IUpdateCatalogRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.retail.v2alpha.ICatalog, - protos.google.cloud.retail.v2alpha.IUpdateCatalogRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.retail.v2alpha.ICatalog, - protos.google.cloud.retail.v2alpha.IUpdateCatalogRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.retail.v2alpha.IUpdateCatalogRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.retail.v2alpha.ICatalog, + | protos.google.cloud.retail.v2alpha.IUpdateCatalogRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.ICatalog, + protos.google.cloud.retail.v2alpha.IUpdateCatalogRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'catalog.name': request.catalog!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'catalog.name': request.catalog!.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateCatalog request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.retail.v2alpha.ICatalog, - protos.google.cloud.retail.v2alpha.IUpdateCatalogRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.retail.v2alpha.ICatalog, + | protos.google.cloud.retail.v2alpha.IUpdateCatalogRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateCatalog response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.updateCatalog(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.retail.v2alpha.ICatalog, - protos.google.cloud.retail.v2alpha.IUpdateCatalogRequest|undefined, {}|undefined - ]) => { - this._log.info('updateCatalog response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateCatalog(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.retail.v2alpha.ICatalog, + protos.google.cloud.retail.v2alpha.IUpdateCatalogRequest | undefined, + {} | undefined, + ]) => { + this._log.info('updateCatalog response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Set a specified branch id as default branch. API methods such as - * {@link protos.google.cloud.retail.v2alpha.SearchService.Search|SearchService.Search}, - * {@link protos.google.cloud.retail.v2alpha.ProductService.GetProduct|ProductService.GetProduct}, - * {@link protos.google.cloud.retail.v2alpha.ProductService.ListProducts|ProductService.ListProducts} - * will treat requests using "default_branch" to the actual branch id set as - * default. - * - * For example, if `projects/* /locations/* /catalogs/* /branches/1` is set as - * default, setting - * {@link protos.google.cloud.retail.v2alpha.SearchRequest.branch|SearchRequest.branch} to - * `projects/* /locations/* /catalogs/* /branches/default_branch` is equivalent - * to setting - * {@link protos.google.cloud.retail.v2alpha.SearchRequest.branch|SearchRequest.branch} to - * `projects/* /locations/* /catalogs/* /branches/1`. - * - * Using multiple branches can be useful when developers would like - * to have a staging branch to test and verify for future usage. When it - * becomes ready, developers switch on the staging branch using this API - * while keeping using - * `projects/* /locations/* /catalogs/* /branches/default_branch` as - * {@link protos.google.cloud.retail.v2alpha.SearchRequest.branch|SearchRequest.branch} to - * route the traffic to this staging branch. - * - * CAUTION: If you have live predict/search traffic, switching the default - * branch could potentially cause outages if the ID space of the new branch - * is very different from the old one. - * - * More specifically: - * - * * PredictionService will only return product IDs from branch {newBranch}. - * * SearchService will only return product IDs from branch {newBranch} - * (if branch is not explicitly set). - * * UserEventService will only join events with products from branch - * {newBranch}. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.catalog - * Full resource name of the catalog, such as - * `projects/* /locations/global/catalogs/default_catalog`. - * @param {string} request.branchId - * The final component of the resource name of a branch. - * - * This field must be one of "0", "1" or "2". Otherwise, an INVALID_ARGUMENT - * error is returned. - * - * If there are no sufficient active products in the targeted branch and - * {@link protos.google.cloud.retail.v2alpha.SetDefaultBranchRequest.force|force} is not - * set, a FAILED_PRECONDITION error is returned. - * @param {string} request.note - * Some note on this request, this can be retrieved by - * {@link protos.google.cloud.retail.v2alpha.CatalogService.GetDefaultBranch|CatalogService.GetDefaultBranch} - * before next valid default branch set occurs. - * - * This field must be a UTF-8 encoded string with a length limit of 1,000 - * characters. Otherwise, an INVALID_ARGUMENT error is returned. - * @param {boolean} request.force - * If set to true, it permits switching to a branch with - * {@link protos.google.cloud.retail.v2alpha.SetDefaultBranchRequest.branch_id|branch_id} - * even if it has no sufficient active products. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/catalog_service.set_default_branch.js - * region_tag:retail_v2alpha_generated_CatalogService_SetDefaultBranch_async - */ + /** + * Set a specified branch id as default branch. API methods such as + * {@link protos.google.cloud.retail.v2alpha.SearchService.Search|SearchService.Search}, + * {@link protos.google.cloud.retail.v2alpha.ProductService.GetProduct|ProductService.GetProduct}, + * {@link protos.google.cloud.retail.v2alpha.ProductService.ListProducts|ProductService.ListProducts} + * will treat requests using "default_branch" to the actual branch id set as + * default. + * + * For example, if `projects/* /locations/* /catalogs/* /branches/1` is set as + * default, setting + * {@link protos.google.cloud.retail.v2alpha.SearchRequest.branch|SearchRequest.branch} to + * `projects/* /locations/* /catalogs/* /branches/default_branch` is equivalent + * to setting + * {@link protos.google.cloud.retail.v2alpha.SearchRequest.branch|SearchRequest.branch} to + * `projects/* /locations/* /catalogs/* /branches/1`. + * + * Using multiple branches can be useful when developers would like + * to have a staging branch to test and verify for future usage. When it + * becomes ready, developers switch on the staging branch using this API + * while keeping using + * `projects/* /locations/* /catalogs/* /branches/default_branch` as + * {@link protos.google.cloud.retail.v2alpha.SearchRequest.branch|SearchRequest.branch} to + * route the traffic to this staging branch. + * + * CAUTION: If you have live predict/search traffic, switching the default + * branch could potentially cause outages if the ID space of the new branch + * is very different from the old one. + * + * More specifically: + * + * * PredictionService will only return product IDs from branch {newBranch}. + * * SearchService will only return product IDs from branch {newBranch} + * (if branch is not explicitly set). + * * UserEventService will only join events with products from branch + * {newBranch}. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.catalog + * Full resource name of the catalog, such as + * `projects/* /locations/global/catalogs/default_catalog`. + * @param {string} request.branchId + * The final component of the resource name of a branch. + * + * This field must be one of "0", "1" or "2". Otherwise, an INVALID_ARGUMENT + * error is returned. + * + * If there are no sufficient active products in the targeted branch and + * {@link protos.google.cloud.retail.v2alpha.SetDefaultBranchRequest.force|force} is not + * set, a FAILED_PRECONDITION error is returned. + * @param {string} request.note + * Some note on this request, this can be retrieved by + * {@link protos.google.cloud.retail.v2alpha.CatalogService.GetDefaultBranch|CatalogService.GetDefaultBranch} + * before next valid default branch set occurs. + * + * This field must be a UTF-8 encoded string with a length limit of 1,000 + * characters. Otherwise, an INVALID_ARGUMENT error is returned. + * @param {boolean} request.force + * If set to true, it permits switching to a branch with + * {@link protos.google.cloud.retail.v2alpha.SetDefaultBranchRequest.branch_id|branch_id} + * even if it has no sufficient active products. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/catalog_service.set_default_branch.js + * region_tag:retail_v2alpha_generated_CatalogService_SetDefaultBranch_async + */ setDefaultBranch( - request?: protos.google.cloud.retail.v2alpha.ISetDefaultBranchRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.cloud.retail.v2alpha.ISetDefaultBranchRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.ISetDefaultBranchRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.cloud.retail.v2alpha.ISetDefaultBranchRequest | undefined, + {} | undefined, + ] + >; setDefaultBranch( - request: protos.google.cloud.retail.v2alpha.ISetDefaultBranchRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.cloud.retail.v2alpha.ISetDefaultBranchRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.ISetDefaultBranchRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.cloud.retail.v2alpha.ISetDefaultBranchRequest + | null + | undefined, + {} | null | undefined + >, + ): void; setDefaultBranch( - request: protos.google.cloud.retail.v2alpha.ISetDefaultBranchRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.cloud.retail.v2alpha.ISetDefaultBranchRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.ISetDefaultBranchRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.cloud.retail.v2alpha.ISetDefaultBranchRequest + | null + | undefined, + {} | null | undefined + >, + ): void; setDefaultBranch( - request?: protos.google.cloud.retail.v2alpha.ISetDefaultBranchRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.cloud.retail.v2alpha.ISetDefaultBranchRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.cloud.retail.v2alpha.ISetDefaultBranchRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.protobuf.IEmpty, - protos.google.cloud.retail.v2alpha.ISetDefaultBranchRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.cloud.retail.v2alpha.ISetDefaultBranchRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.retail.v2alpha.ISetDefaultBranchRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + | protos.google.cloud.retail.v2alpha.ISetDefaultBranchRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.cloud.retail.v2alpha.ISetDefaultBranchRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'catalog': request.catalog ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + catalog: request.catalog ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('setDefaultBranch request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.cloud.retail.v2alpha.ISetDefaultBranchRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.cloud.retail.v2alpha.ISetDefaultBranchRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('setDefaultBranch response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.setDefaultBranch(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.cloud.retail.v2alpha.ISetDefaultBranchRequest|undefined, {}|undefined - ]) => { - this._log.info('setDefaultBranch response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .setDefaultBranch(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + ( + | protos.google.cloud.retail.v2alpha.ISetDefaultBranchRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('setDefaultBranch response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Get which branch is currently default branch set by - * {@link protos.google.cloud.retail.v2alpha.CatalogService.SetDefaultBranch|CatalogService.SetDefaultBranch} - * method under a specified parent catalog. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.catalog - * The parent catalog resource name, such as - * `projects/* /locations/global/catalogs/default_catalog`. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.GetDefaultBranchResponse|GetDefaultBranchResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/catalog_service.get_default_branch.js - * region_tag:retail_v2alpha_generated_CatalogService_GetDefaultBranch_async - */ + /** + * Get which branch is currently default branch set by + * {@link protos.google.cloud.retail.v2alpha.CatalogService.SetDefaultBranch|CatalogService.SetDefaultBranch} + * method under a specified parent catalog. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.catalog + * The parent catalog resource name, such as + * `projects/* /locations/global/catalogs/default_catalog`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.GetDefaultBranchResponse|GetDefaultBranchResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/catalog_service.get_default_branch.js + * region_tag:retail_v2alpha_generated_CatalogService_GetDefaultBranch_async + */ getDefaultBranch( - request?: protos.google.cloud.retail.v2alpha.IGetDefaultBranchRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.retail.v2alpha.IGetDefaultBranchResponse, - protos.google.cloud.retail.v2alpha.IGetDefaultBranchRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.IGetDefaultBranchRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IGetDefaultBranchResponse, + protos.google.cloud.retail.v2alpha.IGetDefaultBranchRequest | undefined, + {} | undefined, + ] + >; getDefaultBranch( - request: protos.google.cloud.retail.v2alpha.IGetDefaultBranchRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.retail.v2alpha.IGetDefaultBranchResponse, - protos.google.cloud.retail.v2alpha.IGetDefaultBranchRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IGetDefaultBranchRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.retail.v2alpha.IGetDefaultBranchResponse, + | protos.google.cloud.retail.v2alpha.IGetDefaultBranchRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getDefaultBranch( - request: protos.google.cloud.retail.v2alpha.IGetDefaultBranchRequest, - callback: Callback< - protos.google.cloud.retail.v2alpha.IGetDefaultBranchResponse, - protos.google.cloud.retail.v2alpha.IGetDefaultBranchRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IGetDefaultBranchRequest, + callback: Callback< + protos.google.cloud.retail.v2alpha.IGetDefaultBranchResponse, + | protos.google.cloud.retail.v2alpha.IGetDefaultBranchRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getDefaultBranch( - request?: protos.google.cloud.retail.v2alpha.IGetDefaultBranchRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.retail.v2alpha.IGetDefaultBranchResponse, - protos.google.cloud.retail.v2alpha.IGetDefaultBranchRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.retail.v2alpha.IGetDefaultBranchRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.retail.v2alpha.IGetDefaultBranchResponse, - protos.google.cloud.retail.v2alpha.IGetDefaultBranchRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.retail.v2alpha.IGetDefaultBranchResponse, - protos.google.cloud.retail.v2alpha.IGetDefaultBranchRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.retail.v2alpha.IGetDefaultBranchRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.retail.v2alpha.IGetDefaultBranchResponse, + | protos.google.cloud.retail.v2alpha.IGetDefaultBranchRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IGetDefaultBranchResponse, + protos.google.cloud.retail.v2alpha.IGetDefaultBranchRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'catalog': request.catalog ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + catalog: request.catalog ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getDefaultBranch request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.retail.v2alpha.IGetDefaultBranchResponse, - protos.google.cloud.retail.v2alpha.IGetDefaultBranchRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.retail.v2alpha.IGetDefaultBranchResponse, + | protos.google.cloud.retail.v2alpha.IGetDefaultBranchRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getDefaultBranch response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.getDefaultBranch(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.retail.v2alpha.IGetDefaultBranchResponse, - protos.google.cloud.retail.v2alpha.IGetDefaultBranchRequest|undefined, {}|undefined - ]) => { - this._log.info('getDefaultBranch response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getDefaultBranch(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.retail.v2alpha.IGetDefaultBranchResponse, + ( + | protos.google.cloud.retail.v2alpha.IGetDefaultBranchRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('getDefaultBranch response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Gets a {@link protos.google.cloud.retail.v2alpha.CompletionConfig|CompletionConfig}. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. Full CompletionConfig resource name. Format: - * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/completionConfig` - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.CompletionConfig|CompletionConfig}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/catalog_service.get_completion_config.js - * region_tag:retail_v2alpha_generated_CatalogService_GetCompletionConfig_async - */ + /** + * Gets a {@link protos.google.cloud.retail.v2alpha.CompletionConfig|CompletionConfig}. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Full CompletionConfig resource name. Format: + * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/completionConfig` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.CompletionConfig|CompletionConfig}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/catalog_service.get_completion_config.js + * region_tag:retail_v2alpha_generated_CatalogService_GetCompletionConfig_async + */ getCompletionConfig( - request?: protos.google.cloud.retail.v2alpha.IGetCompletionConfigRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.retail.v2alpha.ICompletionConfig, - protos.google.cloud.retail.v2alpha.IGetCompletionConfigRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.IGetCompletionConfigRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.ICompletionConfig, + ( + | protos.google.cloud.retail.v2alpha.IGetCompletionConfigRequest + | undefined + ), + {} | undefined, + ] + >; getCompletionConfig( - request: protos.google.cloud.retail.v2alpha.IGetCompletionConfigRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.retail.v2alpha.ICompletionConfig, - protos.google.cloud.retail.v2alpha.IGetCompletionConfigRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IGetCompletionConfigRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.retail.v2alpha.ICompletionConfig, + | protos.google.cloud.retail.v2alpha.IGetCompletionConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getCompletionConfig( - request: protos.google.cloud.retail.v2alpha.IGetCompletionConfigRequest, - callback: Callback< - protos.google.cloud.retail.v2alpha.ICompletionConfig, - protos.google.cloud.retail.v2alpha.IGetCompletionConfigRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IGetCompletionConfigRequest, + callback: Callback< + protos.google.cloud.retail.v2alpha.ICompletionConfig, + | protos.google.cloud.retail.v2alpha.IGetCompletionConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getCompletionConfig( - request?: protos.google.cloud.retail.v2alpha.IGetCompletionConfigRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.retail.v2alpha.ICompletionConfig, - protos.google.cloud.retail.v2alpha.IGetCompletionConfigRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.retail.v2alpha.IGetCompletionConfigRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.retail.v2alpha.ICompletionConfig, - protos.google.cloud.retail.v2alpha.IGetCompletionConfigRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.retail.v2alpha.ICompletionConfig, - protos.google.cloud.retail.v2alpha.IGetCompletionConfigRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.retail.v2alpha.IGetCompletionConfigRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.retail.v2alpha.ICompletionConfig, + | protos.google.cloud.retail.v2alpha.IGetCompletionConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.ICompletionConfig, + ( + | protos.google.cloud.retail.v2alpha.IGetCompletionConfigRequest + | undefined + ), + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getCompletionConfig request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.retail.v2alpha.ICompletionConfig, - protos.google.cloud.retail.v2alpha.IGetCompletionConfigRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.retail.v2alpha.ICompletionConfig, + | protos.google.cloud.retail.v2alpha.IGetCompletionConfigRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getCompletionConfig response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.getCompletionConfig(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.retail.v2alpha.ICompletionConfig, - protos.google.cloud.retail.v2alpha.IGetCompletionConfigRequest|undefined, {}|undefined - ]) => { - this._log.info('getCompletionConfig response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getCompletionConfig(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.retail.v2alpha.ICompletionConfig, + ( + | protos.google.cloud.retail.v2alpha.IGetCompletionConfigRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('getCompletionConfig response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Updates the - * {@link protos.google.cloud.retail.v2alpha.CompletionConfig|CompletionConfig}s. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.cloud.retail.v2alpha.CompletionConfig} request.completionConfig - * Required. The - * {@link protos.google.cloud.retail.v2alpha.CompletionConfig|CompletionConfig} to update. - * - * If the caller does not have permission to update the - * {@link protos.google.cloud.retail.v2alpha.CompletionConfig|CompletionConfig}, then a - * PERMISSION_DENIED error is returned. - * - * If the {@link protos.google.cloud.retail.v2alpha.CompletionConfig|CompletionConfig} to - * update does not exist, a NOT_FOUND error is returned. - * @param {google.protobuf.FieldMask} request.updateMask - * Indicates which fields in the provided - * {@link protos.google.cloud.retail.v2alpha.CompletionConfig|CompletionConfig} to update. - * The following are the only supported fields: - * - * * {@link protos.google.cloud.retail.v2alpha.CompletionConfig.matching_order|CompletionConfig.matching_order} - * * {@link protos.google.cloud.retail.v2alpha.CompletionConfig.max_suggestions|CompletionConfig.max_suggestions} - * * {@link protos.google.cloud.retail.v2alpha.CompletionConfig.min_prefix_length|CompletionConfig.min_prefix_length} - * * {@link protos.google.cloud.retail.v2alpha.CompletionConfig.auto_learning|CompletionConfig.auto_learning} - * - * If not set, all supported fields are updated. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.CompletionConfig|CompletionConfig}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/catalog_service.update_completion_config.js - * region_tag:retail_v2alpha_generated_CatalogService_UpdateCompletionConfig_async - */ + /** + * Updates the + * {@link protos.google.cloud.retail.v2alpha.CompletionConfig|CompletionConfig}s. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.cloud.retail.v2alpha.CompletionConfig} request.completionConfig + * Required. The + * {@link protos.google.cloud.retail.v2alpha.CompletionConfig|CompletionConfig} to update. + * + * If the caller does not have permission to update the + * {@link protos.google.cloud.retail.v2alpha.CompletionConfig|CompletionConfig}, then a + * PERMISSION_DENIED error is returned. + * + * If the {@link protos.google.cloud.retail.v2alpha.CompletionConfig|CompletionConfig} to + * update does not exist, a NOT_FOUND error is returned. + * @param {google.protobuf.FieldMask} request.updateMask + * Indicates which fields in the provided + * {@link protos.google.cloud.retail.v2alpha.CompletionConfig|CompletionConfig} to update. + * The following are the only supported fields: + * + * * {@link protos.google.cloud.retail.v2alpha.CompletionConfig.matching_order|CompletionConfig.matching_order} + * * {@link protos.google.cloud.retail.v2alpha.CompletionConfig.max_suggestions|CompletionConfig.max_suggestions} + * * {@link protos.google.cloud.retail.v2alpha.CompletionConfig.min_prefix_length|CompletionConfig.min_prefix_length} + * * {@link protos.google.cloud.retail.v2alpha.CompletionConfig.auto_learning|CompletionConfig.auto_learning} + * + * If not set, all supported fields are updated. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.CompletionConfig|CompletionConfig}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/catalog_service.update_completion_config.js + * region_tag:retail_v2alpha_generated_CatalogService_UpdateCompletionConfig_async + */ updateCompletionConfig( - request?: protos.google.cloud.retail.v2alpha.IUpdateCompletionConfigRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.retail.v2alpha.ICompletionConfig, - protos.google.cloud.retail.v2alpha.IUpdateCompletionConfigRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.IUpdateCompletionConfigRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.ICompletionConfig, + ( + | protos.google.cloud.retail.v2alpha.IUpdateCompletionConfigRequest + | undefined + ), + {} | undefined, + ] + >; updateCompletionConfig( - request: protos.google.cloud.retail.v2alpha.IUpdateCompletionConfigRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.retail.v2alpha.ICompletionConfig, - protos.google.cloud.retail.v2alpha.IUpdateCompletionConfigRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IUpdateCompletionConfigRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.retail.v2alpha.ICompletionConfig, + | protos.google.cloud.retail.v2alpha.IUpdateCompletionConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateCompletionConfig( - request: protos.google.cloud.retail.v2alpha.IUpdateCompletionConfigRequest, - callback: Callback< - protos.google.cloud.retail.v2alpha.ICompletionConfig, - protos.google.cloud.retail.v2alpha.IUpdateCompletionConfigRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IUpdateCompletionConfigRequest, + callback: Callback< + protos.google.cloud.retail.v2alpha.ICompletionConfig, + | protos.google.cloud.retail.v2alpha.IUpdateCompletionConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateCompletionConfig( - request?: protos.google.cloud.retail.v2alpha.IUpdateCompletionConfigRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.cloud.retail.v2alpha.IUpdateCompletionConfigRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.retail.v2alpha.ICompletionConfig, - protos.google.cloud.retail.v2alpha.IUpdateCompletionConfigRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.cloud.retail.v2alpha.ICompletionConfig, - protos.google.cloud.retail.v2alpha.IUpdateCompletionConfigRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.retail.v2alpha.ICompletionConfig, - protos.google.cloud.retail.v2alpha.IUpdateCompletionConfigRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.retail.v2alpha.IUpdateCompletionConfigRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.retail.v2alpha.ICompletionConfig, + | protos.google.cloud.retail.v2alpha.IUpdateCompletionConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.ICompletionConfig, + ( + | protos.google.cloud.retail.v2alpha.IUpdateCompletionConfigRequest + | undefined + ), + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'completion_config.name': request.completionConfig!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'completion_config.name': request.completionConfig!.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateCompletionConfig request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.retail.v2alpha.ICompletionConfig, - protos.google.cloud.retail.v2alpha.IUpdateCompletionConfigRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.retail.v2alpha.ICompletionConfig, + | protos.google.cloud.retail.v2alpha.IUpdateCompletionConfigRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateCompletionConfig response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.updateCompletionConfig(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.retail.v2alpha.ICompletionConfig, - protos.google.cloud.retail.v2alpha.IUpdateCompletionConfigRequest|undefined, {}|undefined - ]) => { - this._log.info('updateCompletionConfig response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateCompletionConfig(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.retail.v2alpha.ICompletionConfig, + ( + | protos.google.cloud.retail.v2alpha.IUpdateCompletionConfigRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('updateCompletionConfig response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Gets an {@link protos.google.cloud.retail.v2alpha.AttributesConfig|AttributesConfig}. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. Full AttributesConfig resource name. Format: - * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/attributesConfig` - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.AttributesConfig|AttributesConfig}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/catalog_service.get_attributes_config.js - * region_tag:retail_v2alpha_generated_CatalogService_GetAttributesConfig_async - */ + /** + * Gets an {@link protos.google.cloud.retail.v2alpha.AttributesConfig|AttributesConfig}. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Full AttributesConfig resource name. Format: + * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/attributesConfig` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.AttributesConfig|AttributesConfig}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/catalog_service.get_attributes_config.js + * region_tag:retail_v2alpha_generated_CatalogService_GetAttributesConfig_async + */ getAttributesConfig( - request?: protos.google.cloud.retail.v2alpha.IGetAttributesConfigRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.retail.v2alpha.IAttributesConfig, - protos.google.cloud.retail.v2alpha.IGetAttributesConfigRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.IGetAttributesConfigRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IAttributesConfig, + ( + | protos.google.cloud.retail.v2alpha.IGetAttributesConfigRequest + | undefined + ), + {} | undefined, + ] + >; getAttributesConfig( - request: protos.google.cloud.retail.v2alpha.IGetAttributesConfigRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.retail.v2alpha.IAttributesConfig, - protos.google.cloud.retail.v2alpha.IGetAttributesConfigRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IGetAttributesConfigRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.retail.v2alpha.IAttributesConfig, + | protos.google.cloud.retail.v2alpha.IGetAttributesConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getAttributesConfig( - request: protos.google.cloud.retail.v2alpha.IGetAttributesConfigRequest, - callback: Callback< - protos.google.cloud.retail.v2alpha.IAttributesConfig, - protos.google.cloud.retail.v2alpha.IGetAttributesConfigRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IGetAttributesConfigRequest, + callback: Callback< + protos.google.cloud.retail.v2alpha.IAttributesConfig, + | protos.google.cloud.retail.v2alpha.IGetAttributesConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getAttributesConfig( - request?: protos.google.cloud.retail.v2alpha.IGetAttributesConfigRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.retail.v2alpha.IAttributesConfig, - protos.google.cloud.retail.v2alpha.IGetAttributesConfigRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.retail.v2alpha.IGetAttributesConfigRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.retail.v2alpha.IAttributesConfig, - protos.google.cloud.retail.v2alpha.IGetAttributesConfigRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.retail.v2alpha.IAttributesConfig, - protos.google.cloud.retail.v2alpha.IGetAttributesConfigRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.retail.v2alpha.IGetAttributesConfigRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.retail.v2alpha.IAttributesConfig, + | protos.google.cloud.retail.v2alpha.IGetAttributesConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IAttributesConfig, + ( + | protos.google.cloud.retail.v2alpha.IGetAttributesConfigRequest + | undefined + ), + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getAttributesConfig request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.retail.v2alpha.IAttributesConfig, - protos.google.cloud.retail.v2alpha.IGetAttributesConfigRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.retail.v2alpha.IAttributesConfig, + | protos.google.cloud.retail.v2alpha.IGetAttributesConfigRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getAttributesConfig response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.getAttributesConfig(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.retail.v2alpha.IAttributesConfig, - protos.google.cloud.retail.v2alpha.IGetAttributesConfigRequest|undefined, {}|undefined - ]) => { - this._log.info('getAttributesConfig response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getAttributesConfig(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.retail.v2alpha.IAttributesConfig, + ( + | protos.google.cloud.retail.v2alpha.IGetAttributesConfigRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('getAttributesConfig response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Updates the - * {@link protos.google.cloud.retail.v2alpha.AttributesConfig|AttributesConfig}. - * - * The catalog attributes in the request will be updated in the catalog, or - * inserted if they do not exist. Existing catalog attributes not included in - * the request will remain unchanged. Attributes that are assigned to - * products, but do not exist at the catalog level, are always included in the - * response. The product attribute is assigned default values for missing - * catalog attribute fields, e.g., searchable and dynamic facetable options. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.cloud.retail.v2alpha.AttributesConfig} request.attributesConfig - * Required. The - * {@link protos.google.cloud.retail.v2alpha.AttributesConfig|AttributesConfig} to update. - * @param {google.protobuf.FieldMask} request.updateMask - * Indicates which fields in the provided - * {@link protos.google.cloud.retail.v2alpha.AttributesConfig|AttributesConfig} to update. - * The following is the only supported field: - * - * * {@link protos.google.cloud.retail.v2alpha.AttributesConfig.catalog_attributes|AttributesConfig.catalog_attributes} - * - * If not set, all supported fields are updated. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.AttributesConfig|AttributesConfig}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/catalog_service.update_attributes_config.js - * region_tag:retail_v2alpha_generated_CatalogService_UpdateAttributesConfig_async - */ + /** + * Updates the + * {@link protos.google.cloud.retail.v2alpha.AttributesConfig|AttributesConfig}. + * + * The catalog attributes in the request will be updated in the catalog, or + * inserted if they do not exist. Existing catalog attributes not included in + * the request will remain unchanged. Attributes that are assigned to + * products, but do not exist at the catalog level, are always included in the + * response. The product attribute is assigned default values for missing + * catalog attribute fields, e.g., searchable and dynamic facetable options. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.cloud.retail.v2alpha.AttributesConfig} request.attributesConfig + * Required. The + * {@link protos.google.cloud.retail.v2alpha.AttributesConfig|AttributesConfig} to update. + * @param {google.protobuf.FieldMask} request.updateMask + * Indicates which fields in the provided + * {@link protos.google.cloud.retail.v2alpha.AttributesConfig|AttributesConfig} to update. + * The following is the only supported field: + * + * * {@link protos.google.cloud.retail.v2alpha.AttributesConfig.catalog_attributes|AttributesConfig.catalog_attributes} + * + * If not set, all supported fields are updated. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.AttributesConfig|AttributesConfig}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/catalog_service.update_attributes_config.js + * region_tag:retail_v2alpha_generated_CatalogService_UpdateAttributesConfig_async + */ updateAttributesConfig( - request?: protos.google.cloud.retail.v2alpha.IUpdateAttributesConfigRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.retail.v2alpha.IAttributesConfig, - protos.google.cloud.retail.v2alpha.IUpdateAttributesConfigRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.IUpdateAttributesConfigRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IAttributesConfig, + ( + | protos.google.cloud.retail.v2alpha.IUpdateAttributesConfigRequest + | undefined + ), + {} | undefined, + ] + >; updateAttributesConfig( - request: protos.google.cloud.retail.v2alpha.IUpdateAttributesConfigRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.retail.v2alpha.IAttributesConfig, - protos.google.cloud.retail.v2alpha.IUpdateAttributesConfigRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IUpdateAttributesConfigRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.retail.v2alpha.IAttributesConfig, + | protos.google.cloud.retail.v2alpha.IUpdateAttributesConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateAttributesConfig( - request: protos.google.cloud.retail.v2alpha.IUpdateAttributesConfigRequest, - callback: Callback< - protos.google.cloud.retail.v2alpha.IAttributesConfig, - protos.google.cloud.retail.v2alpha.IUpdateAttributesConfigRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IUpdateAttributesConfigRequest, + callback: Callback< + protos.google.cloud.retail.v2alpha.IAttributesConfig, + | protos.google.cloud.retail.v2alpha.IUpdateAttributesConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateAttributesConfig( - request?: protos.google.cloud.retail.v2alpha.IUpdateAttributesConfigRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.retail.v2alpha.IAttributesConfig, - protos.google.cloud.retail.v2alpha.IUpdateAttributesConfigRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.retail.v2alpha.IUpdateAttributesConfigRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.retail.v2alpha.IAttributesConfig, - protos.google.cloud.retail.v2alpha.IUpdateAttributesConfigRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.retail.v2alpha.IAttributesConfig, - protos.google.cloud.retail.v2alpha.IUpdateAttributesConfigRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.retail.v2alpha.IUpdateAttributesConfigRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.retail.v2alpha.IAttributesConfig, + | protos.google.cloud.retail.v2alpha.IUpdateAttributesConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IAttributesConfig, + ( + | protos.google.cloud.retail.v2alpha.IUpdateAttributesConfigRequest + | undefined + ), + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'attributes_config.name': request.attributesConfig!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'attributes_config.name': request.attributesConfig!.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateAttributesConfig request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.retail.v2alpha.IAttributesConfig, - protos.google.cloud.retail.v2alpha.IUpdateAttributesConfigRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.retail.v2alpha.IAttributesConfig, + | protos.google.cloud.retail.v2alpha.IUpdateAttributesConfigRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateAttributesConfig response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.updateAttributesConfig(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.retail.v2alpha.IAttributesConfig, - protos.google.cloud.retail.v2alpha.IUpdateAttributesConfigRequest|undefined, {}|undefined - ]) => { - this._log.info('updateAttributesConfig response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateAttributesConfig(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.retail.v2alpha.IAttributesConfig, + ( + | protos.google.cloud.retail.v2alpha.IUpdateAttributesConfigRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('updateAttributesConfig response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Adds the specified - * {@link protos.google.cloud.retail.v2alpha.CatalogAttribute|CatalogAttribute} to the - * {@link protos.google.cloud.retail.v2alpha.AttributesConfig|AttributesConfig}. - * - * If the {@link protos.google.cloud.retail.v2alpha.CatalogAttribute|CatalogAttribute} to - * add already exists, an ALREADY_EXISTS error is returned. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.attributesConfig - * Required. Full AttributesConfig resource name. Format: - * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/attributesConfig` - * @param {google.cloud.retail.v2alpha.CatalogAttribute} request.catalogAttribute - * Required. The - * {@link protos.google.cloud.retail.v2alpha.CatalogAttribute|CatalogAttribute} to add. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.AttributesConfig|AttributesConfig}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/catalog_service.add_catalog_attribute.js - * region_tag:retail_v2alpha_generated_CatalogService_AddCatalogAttribute_async - */ + /** + * Adds the specified + * {@link protos.google.cloud.retail.v2alpha.CatalogAttribute|CatalogAttribute} to the + * {@link protos.google.cloud.retail.v2alpha.AttributesConfig|AttributesConfig}. + * + * If the {@link protos.google.cloud.retail.v2alpha.CatalogAttribute|CatalogAttribute} to + * add already exists, an ALREADY_EXISTS error is returned. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.attributesConfig + * Required. Full AttributesConfig resource name. Format: + * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/attributesConfig` + * @param {google.cloud.retail.v2alpha.CatalogAttribute} request.catalogAttribute + * Required. The + * {@link protos.google.cloud.retail.v2alpha.CatalogAttribute|CatalogAttribute} to add. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.AttributesConfig|AttributesConfig}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/catalog_service.add_catalog_attribute.js + * region_tag:retail_v2alpha_generated_CatalogService_AddCatalogAttribute_async + */ addCatalogAttribute( - request?: protos.google.cloud.retail.v2alpha.IAddCatalogAttributeRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.retail.v2alpha.IAttributesConfig, - protos.google.cloud.retail.v2alpha.IAddCatalogAttributeRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.IAddCatalogAttributeRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IAttributesConfig, + ( + | protos.google.cloud.retail.v2alpha.IAddCatalogAttributeRequest + | undefined + ), + {} | undefined, + ] + >; addCatalogAttribute( - request: protos.google.cloud.retail.v2alpha.IAddCatalogAttributeRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.retail.v2alpha.IAttributesConfig, - protos.google.cloud.retail.v2alpha.IAddCatalogAttributeRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IAddCatalogAttributeRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.retail.v2alpha.IAttributesConfig, + | protos.google.cloud.retail.v2alpha.IAddCatalogAttributeRequest + | null + | undefined, + {} | null | undefined + >, + ): void; addCatalogAttribute( - request: protos.google.cloud.retail.v2alpha.IAddCatalogAttributeRequest, - callback: Callback< - protos.google.cloud.retail.v2alpha.IAttributesConfig, - protos.google.cloud.retail.v2alpha.IAddCatalogAttributeRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IAddCatalogAttributeRequest, + callback: Callback< + protos.google.cloud.retail.v2alpha.IAttributesConfig, + | protos.google.cloud.retail.v2alpha.IAddCatalogAttributeRequest + | null + | undefined, + {} | null | undefined + >, + ): void; addCatalogAttribute( - request?: protos.google.cloud.retail.v2alpha.IAddCatalogAttributeRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.retail.v2alpha.IAttributesConfig, - protos.google.cloud.retail.v2alpha.IAddCatalogAttributeRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.retail.v2alpha.IAddCatalogAttributeRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.retail.v2alpha.IAttributesConfig, - protos.google.cloud.retail.v2alpha.IAddCatalogAttributeRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.retail.v2alpha.IAttributesConfig, - protos.google.cloud.retail.v2alpha.IAddCatalogAttributeRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.retail.v2alpha.IAddCatalogAttributeRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.retail.v2alpha.IAttributesConfig, + | protos.google.cloud.retail.v2alpha.IAddCatalogAttributeRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IAttributesConfig, + ( + | protos.google.cloud.retail.v2alpha.IAddCatalogAttributeRequest + | undefined + ), + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'attributes_config': request.attributesConfig ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + attributes_config: request.attributesConfig ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('addCatalogAttribute request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.retail.v2alpha.IAttributesConfig, - protos.google.cloud.retail.v2alpha.IAddCatalogAttributeRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.retail.v2alpha.IAttributesConfig, + | protos.google.cloud.retail.v2alpha.IAddCatalogAttributeRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('addCatalogAttribute response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.addCatalogAttribute(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.retail.v2alpha.IAttributesConfig, - protos.google.cloud.retail.v2alpha.IAddCatalogAttributeRequest|undefined, {}|undefined - ]) => { - this._log.info('addCatalogAttribute response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .addCatalogAttribute(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.retail.v2alpha.IAttributesConfig, + ( + | protos.google.cloud.retail.v2alpha.IAddCatalogAttributeRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('addCatalogAttribute response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Removes the specified - * {@link protos.google.cloud.retail.v2alpha.CatalogAttribute|CatalogAttribute} from the - * {@link protos.google.cloud.retail.v2alpha.AttributesConfig|AttributesConfig}. - * - * If the {@link protos.google.cloud.retail.v2alpha.CatalogAttribute|CatalogAttribute} to - * remove does not exist, a NOT_FOUND error is returned. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.attributesConfig - * Required. Full AttributesConfig resource name. Format: - * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/attributesConfig` - * @param {string} request.key - * Required. The attribute name key of the - * {@link protos.google.cloud.retail.v2alpha.CatalogAttribute|CatalogAttribute} to remove. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.AttributesConfig|AttributesConfig}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/catalog_service.remove_catalog_attribute.js - * region_tag:retail_v2alpha_generated_CatalogService_RemoveCatalogAttribute_async - */ + /** + * Removes the specified + * {@link protos.google.cloud.retail.v2alpha.CatalogAttribute|CatalogAttribute} from the + * {@link protos.google.cloud.retail.v2alpha.AttributesConfig|AttributesConfig}. + * + * If the {@link protos.google.cloud.retail.v2alpha.CatalogAttribute|CatalogAttribute} to + * remove does not exist, a NOT_FOUND error is returned. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.attributesConfig + * Required. Full AttributesConfig resource name. Format: + * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/attributesConfig` + * @param {string} request.key + * Required. The attribute name key of the + * {@link protos.google.cloud.retail.v2alpha.CatalogAttribute|CatalogAttribute} to remove. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.AttributesConfig|AttributesConfig}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/catalog_service.remove_catalog_attribute.js + * region_tag:retail_v2alpha_generated_CatalogService_RemoveCatalogAttribute_async + */ removeCatalogAttribute( - request?: protos.google.cloud.retail.v2alpha.IRemoveCatalogAttributeRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.retail.v2alpha.IAttributesConfig, - protos.google.cloud.retail.v2alpha.IRemoveCatalogAttributeRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.IRemoveCatalogAttributeRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IAttributesConfig, + ( + | protos.google.cloud.retail.v2alpha.IRemoveCatalogAttributeRequest + | undefined + ), + {} | undefined, + ] + >; removeCatalogAttribute( - request: protos.google.cloud.retail.v2alpha.IRemoveCatalogAttributeRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.retail.v2alpha.IAttributesConfig, - protos.google.cloud.retail.v2alpha.IRemoveCatalogAttributeRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IRemoveCatalogAttributeRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.retail.v2alpha.IAttributesConfig, + | protos.google.cloud.retail.v2alpha.IRemoveCatalogAttributeRequest + | null + | undefined, + {} | null | undefined + >, + ): void; removeCatalogAttribute( - request: protos.google.cloud.retail.v2alpha.IRemoveCatalogAttributeRequest, - callback: Callback< - protos.google.cloud.retail.v2alpha.IAttributesConfig, - protos.google.cloud.retail.v2alpha.IRemoveCatalogAttributeRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IRemoveCatalogAttributeRequest, + callback: Callback< + protos.google.cloud.retail.v2alpha.IAttributesConfig, + | protos.google.cloud.retail.v2alpha.IRemoveCatalogAttributeRequest + | null + | undefined, + {} | null | undefined + >, + ): void; removeCatalogAttribute( - request?: protos.google.cloud.retail.v2alpha.IRemoveCatalogAttributeRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.retail.v2alpha.IAttributesConfig, - protos.google.cloud.retail.v2alpha.IRemoveCatalogAttributeRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.retail.v2alpha.IRemoveCatalogAttributeRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.retail.v2alpha.IAttributesConfig, - protos.google.cloud.retail.v2alpha.IRemoveCatalogAttributeRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.retail.v2alpha.IAttributesConfig, - protos.google.cloud.retail.v2alpha.IRemoveCatalogAttributeRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.retail.v2alpha.IRemoveCatalogAttributeRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.retail.v2alpha.IAttributesConfig, + | protos.google.cloud.retail.v2alpha.IRemoveCatalogAttributeRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IAttributesConfig, + ( + | protos.google.cloud.retail.v2alpha.IRemoveCatalogAttributeRequest + | undefined + ), + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'attributes_config': request.attributesConfig ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + attributes_config: request.attributesConfig ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('removeCatalogAttribute request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.retail.v2alpha.IAttributesConfig, - protos.google.cloud.retail.v2alpha.IRemoveCatalogAttributeRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.retail.v2alpha.IAttributesConfig, + | protos.google.cloud.retail.v2alpha.IRemoveCatalogAttributeRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('removeCatalogAttribute response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.removeCatalogAttribute(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.retail.v2alpha.IAttributesConfig, - protos.google.cloud.retail.v2alpha.IRemoveCatalogAttributeRequest|undefined, {}|undefined - ]) => { - this._log.info('removeCatalogAttribute response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .removeCatalogAttribute(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.retail.v2alpha.IAttributesConfig, + ( + | protos.google.cloud.retail.v2alpha.IRemoveCatalogAttributeRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('removeCatalogAttribute response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Removes all specified - * {@link protos.google.cloud.retail.v2alpha.CatalogAttribute|CatalogAttribute}s from the - * {@link protos.google.cloud.retail.v2alpha.AttributesConfig|AttributesConfig}. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.attributesConfig - * Required. The attributes config resource shared by all catalog attributes - * being deleted. Format: - * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/attributesConfig` - * @param {string[]} request.attributeKeys - * Required. The attribute name keys of the - * {@link protos.google.cloud.retail.v2alpha.CatalogAttribute|CatalogAttribute}s to - * delete. A maximum of 1000 catalog attributes can be deleted in a batch. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.BatchRemoveCatalogAttributesResponse|BatchRemoveCatalogAttributesResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/catalog_service.batch_remove_catalog_attributes.js - * region_tag:retail_v2alpha_generated_CatalogService_BatchRemoveCatalogAttributes_async - */ + /** + * Removes all specified + * {@link protos.google.cloud.retail.v2alpha.CatalogAttribute|CatalogAttribute}s from the + * {@link protos.google.cloud.retail.v2alpha.AttributesConfig|AttributesConfig}. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.attributesConfig + * Required. The attributes config resource shared by all catalog attributes + * being deleted. Format: + * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/attributesConfig` + * @param {string[]} request.attributeKeys + * Required. The attribute name keys of the + * {@link protos.google.cloud.retail.v2alpha.CatalogAttribute|CatalogAttribute}s to + * delete. A maximum of 1000 catalog attributes can be deleted in a batch. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.BatchRemoveCatalogAttributesResponse|BatchRemoveCatalogAttributesResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/catalog_service.batch_remove_catalog_attributes.js + * region_tag:retail_v2alpha_generated_CatalogService_BatchRemoveCatalogAttributes_async + */ batchRemoveCatalogAttributes( - request?: protos.google.cloud.retail.v2alpha.IBatchRemoveCatalogAttributesRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.retail.v2alpha.IBatchRemoveCatalogAttributesResponse, - protos.google.cloud.retail.v2alpha.IBatchRemoveCatalogAttributesRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.IBatchRemoveCatalogAttributesRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IBatchRemoveCatalogAttributesResponse, + ( + | protos.google.cloud.retail.v2alpha.IBatchRemoveCatalogAttributesRequest + | undefined + ), + {} | undefined, + ] + >; batchRemoveCatalogAttributes( - request: protos.google.cloud.retail.v2alpha.IBatchRemoveCatalogAttributesRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.retail.v2alpha.IBatchRemoveCatalogAttributesResponse, - protos.google.cloud.retail.v2alpha.IBatchRemoveCatalogAttributesRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IBatchRemoveCatalogAttributesRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.retail.v2alpha.IBatchRemoveCatalogAttributesResponse, + | protos.google.cloud.retail.v2alpha.IBatchRemoveCatalogAttributesRequest + | null + | undefined, + {} | null | undefined + >, + ): void; batchRemoveCatalogAttributes( - request: protos.google.cloud.retail.v2alpha.IBatchRemoveCatalogAttributesRequest, - callback: Callback< - protos.google.cloud.retail.v2alpha.IBatchRemoveCatalogAttributesResponse, - protos.google.cloud.retail.v2alpha.IBatchRemoveCatalogAttributesRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IBatchRemoveCatalogAttributesRequest, + callback: Callback< + protos.google.cloud.retail.v2alpha.IBatchRemoveCatalogAttributesResponse, + | protos.google.cloud.retail.v2alpha.IBatchRemoveCatalogAttributesRequest + | null + | undefined, + {} | null | undefined + >, + ): void; batchRemoveCatalogAttributes( - request?: protos.google.cloud.retail.v2alpha.IBatchRemoveCatalogAttributesRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.cloud.retail.v2alpha.IBatchRemoveCatalogAttributesRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.retail.v2alpha.IBatchRemoveCatalogAttributesResponse, - protos.google.cloud.retail.v2alpha.IBatchRemoveCatalogAttributesRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.cloud.retail.v2alpha.IBatchRemoveCatalogAttributesResponse, - protos.google.cloud.retail.v2alpha.IBatchRemoveCatalogAttributesRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.retail.v2alpha.IBatchRemoveCatalogAttributesResponse, - protos.google.cloud.retail.v2alpha.IBatchRemoveCatalogAttributesRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.retail.v2alpha.IBatchRemoveCatalogAttributesRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.retail.v2alpha.IBatchRemoveCatalogAttributesResponse, + | protos.google.cloud.retail.v2alpha.IBatchRemoveCatalogAttributesRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IBatchRemoveCatalogAttributesResponse, + ( + | protos.google.cloud.retail.v2alpha.IBatchRemoveCatalogAttributesRequest + | undefined + ), + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'attributes_config': request.attributesConfig ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + attributes_config: request.attributesConfig ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('batchRemoveCatalogAttributes request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.retail.v2alpha.IBatchRemoveCatalogAttributesResponse, - protos.google.cloud.retail.v2alpha.IBatchRemoveCatalogAttributesRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.retail.v2alpha.IBatchRemoveCatalogAttributesResponse, + | protos.google.cloud.retail.v2alpha.IBatchRemoveCatalogAttributesRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('batchRemoveCatalogAttributes response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.batchRemoveCatalogAttributes(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.retail.v2alpha.IBatchRemoveCatalogAttributesResponse, - protos.google.cloud.retail.v2alpha.IBatchRemoveCatalogAttributesRequest|undefined, {}|undefined - ]) => { - this._log.info('batchRemoveCatalogAttributes response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .batchRemoveCatalogAttributes(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.retail.v2alpha.IBatchRemoveCatalogAttributesResponse, + ( + | protos.google.cloud.retail.v2alpha.IBatchRemoveCatalogAttributesRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('batchRemoveCatalogAttributes response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Replaces the specified - * {@link protos.google.cloud.retail.v2alpha.CatalogAttribute|CatalogAttribute} in the - * {@link protos.google.cloud.retail.v2alpha.AttributesConfig|AttributesConfig} by - * updating the catalog attribute with the same - * {@link protos.google.cloud.retail.v2alpha.CatalogAttribute.key|CatalogAttribute.key}. - * - * If the {@link protos.google.cloud.retail.v2alpha.CatalogAttribute|CatalogAttribute} to - * replace does not exist, a NOT_FOUND error is returned. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.attributesConfig - * Required. Full AttributesConfig resource name. Format: - * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/attributesConfig` - * @param {google.cloud.retail.v2alpha.CatalogAttribute} request.catalogAttribute - * Required. The updated - * {@link protos.google.cloud.retail.v2alpha.CatalogAttribute|CatalogAttribute}. - * @param {google.protobuf.FieldMask} request.updateMask - * Indicates which fields in the provided - * {@link protos.google.cloud.retail.v2alpha.CatalogAttribute|CatalogAttribute} to update. - * The following are NOT supported: - * - * * {@link protos.google.cloud.retail.v2alpha.CatalogAttribute.key|CatalogAttribute.key} - * - * If not set, all supported fields are updated. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.AttributesConfig|AttributesConfig}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/catalog_service.replace_catalog_attribute.js - * region_tag:retail_v2alpha_generated_CatalogService_ReplaceCatalogAttribute_async - */ + /** + * Replaces the specified + * {@link protos.google.cloud.retail.v2alpha.CatalogAttribute|CatalogAttribute} in the + * {@link protos.google.cloud.retail.v2alpha.AttributesConfig|AttributesConfig} by + * updating the catalog attribute with the same + * {@link protos.google.cloud.retail.v2alpha.CatalogAttribute.key|CatalogAttribute.key}. + * + * If the {@link protos.google.cloud.retail.v2alpha.CatalogAttribute|CatalogAttribute} to + * replace does not exist, a NOT_FOUND error is returned. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.attributesConfig + * Required. Full AttributesConfig resource name. Format: + * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/attributesConfig` + * @param {google.cloud.retail.v2alpha.CatalogAttribute} request.catalogAttribute + * Required. The updated + * {@link protos.google.cloud.retail.v2alpha.CatalogAttribute|CatalogAttribute}. + * @param {google.protobuf.FieldMask} request.updateMask + * Indicates which fields in the provided + * {@link protos.google.cloud.retail.v2alpha.CatalogAttribute|CatalogAttribute} to update. + * The following are NOT supported: + * + * * {@link protos.google.cloud.retail.v2alpha.CatalogAttribute.key|CatalogAttribute.key} + * + * If not set, all supported fields are updated. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.AttributesConfig|AttributesConfig}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/catalog_service.replace_catalog_attribute.js + * region_tag:retail_v2alpha_generated_CatalogService_ReplaceCatalogAttribute_async + */ replaceCatalogAttribute( - request?: protos.google.cloud.retail.v2alpha.IReplaceCatalogAttributeRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.retail.v2alpha.IAttributesConfig, - protos.google.cloud.retail.v2alpha.IReplaceCatalogAttributeRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.IReplaceCatalogAttributeRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IAttributesConfig, + ( + | protos.google.cloud.retail.v2alpha.IReplaceCatalogAttributeRequest + | undefined + ), + {} | undefined, + ] + >; replaceCatalogAttribute( - request: protos.google.cloud.retail.v2alpha.IReplaceCatalogAttributeRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.retail.v2alpha.IAttributesConfig, - protos.google.cloud.retail.v2alpha.IReplaceCatalogAttributeRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IReplaceCatalogAttributeRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.retail.v2alpha.IAttributesConfig, + | protos.google.cloud.retail.v2alpha.IReplaceCatalogAttributeRequest + | null + | undefined, + {} | null | undefined + >, + ): void; replaceCatalogAttribute( - request: protos.google.cloud.retail.v2alpha.IReplaceCatalogAttributeRequest, - callback: Callback< - protos.google.cloud.retail.v2alpha.IAttributesConfig, - protos.google.cloud.retail.v2alpha.IReplaceCatalogAttributeRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IReplaceCatalogAttributeRequest, + callback: Callback< + protos.google.cloud.retail.v2alpha.IAttributesConfig, + | protos.google.cloud.retail.v2alpha.IReplaceCatalogAttributeRequest + | null + | undefined, + {} | null | undefined + >, + ): void; replaceCatalogAttribute( - request?: protos.google.cloud.retail.v2alpha.IReplaceCatalogAttributeRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.cloud.retail.v2alpha.IReplaceCatalogAttributeRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.retail.v2alpha.IAttributesConfig, - protos.google.cloud.retail.v2alpha.IReplaceCatalogAttributeRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.cloud.retail.v2alpha.IAttributesConfig, - protos.google.cloud.retail.v2alpha.IReplaceCatalogAttributeRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.retail.v2alpha.IAttributesConfig, - protos.google.cloud.retail.v2alpha.IReplaceCatalogAttributeRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.retail.v2alpha.IReplaceCatalogAttributeRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.retail.v2alpha.IAttributesConfig, + | protos.google.cloud.retail.v2alpha.IReplaceCatalogAttributeRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IAttributesConfig, + ( + | protos.google.cloud.retail.v2alpha.IReplaceCatalogAttributeRequest + | undefined + ), + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'attributes_config': request.attributesConfig ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + attributes_config: request.attributesConfig ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('replaceCatalogAttribute request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.retail.v2alpha.IAttributesConfig, - protos.google.cloud.retail.v2alpha.IReplaceCatalogAttributeRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.retail.v2alpha.IAttributesConfig, + | protos.google.cloud.retail.v2alpha.IReplaceCatalogAttributeRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('replaceCatalogAttribute response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.replaceCatalogAttribute(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.retail.v2alpha.IAttributesConfig, - protos.google.cloud.retail.v2alpha.IReplaceCatalogAttributeRequest|undefined, {}|undefined - ]) => { - this._log.info('replaceCatalogAttribute response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .replaceCatalogAttribute(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.retail.v2alpha.IAttributesConfig, + ( + | protos.google.cloud.retail.v2alpha.IReplaceCatalogAttributeRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('replaceCatalogAttribute response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } - /** - * Lists all the {@link protos.google.cloud.retail.v2alpha.Catalog|Catalog}s associated - * with the project. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The account resource name with an associated location. - * - * If the caller does not have permission to list - * {@link protos.google.cloud.retail.v2alpha.Catalog|Catalog}s under this location, - * regardless of whether or not this location exists, a PERMISSION_DENIED - * error is returned. - * @param {number} request.pageSize - * Maximum number of {@link protos.google.cloud.retail.v2alpha.Catalog|Catalog}s to - * return. If unspecified, defaults to 50. The maximum allowed value is 1000. - * Values above 1000 will be coerced to 1000. - * - * If this field is negative, an INVALID_ARGUMENT is returned. - * @param {string} request.pageToken - * A page token - * {@link protos.google.cloud.retail.v2alpha.ListCatalogsResponse.next_page_token|ListCatalogsResponse.next_page_token}, - * received from a previous - * {@link protos.google.cloud.retail.v2alpha.CatalogService.ListCatalogs|CatalogService.ListCatalogs} - * call. Provide this to retrieve the subsequent page. - * - * When paginating, all other parameters provided to - * {@link protos.google.cloud.retail.v2alpha.CatalogService.ListCatalogs|CatalogService.ListCatalogs} - * must match the call that provided the page token. Otherwise, an - * INVALID_ARGUMENT error is returned. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.cloud.retail.v2alpha.Catalog|Catalog}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `listCatalogsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Lists all the {@link protos.google.cloud.retail.v2alpha.Catalog|Catalog}s associated + * with the project. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The account resource name with an associated location. + * + * If the caller does not have permission to list + * {@link protos.google.cloud.retail.v2alpha.Catalog|Catalog}s under this location, + * regardless of whether or not this location exists, a PERMISSION_DENIED + * error is returned. + * @param {number} request.pageSize + * Maximum number of {@link protos.google.cloud.retail.v2alpha.Catalog|Catalog}s to + * return. If unspecified, defaults to 50. The maximum allowed value is 1000. + * Values above 1000 will be coerced to 1000. + * + * If this field is negative, an INVALID_ARGUMENT is returned. + * @param {string} request.pageToken + * A page token + * {@link protos.google.cloud.retail.v2alpha.ListCatalogsResponse.next_page_token|ListCatalogsResponse.next_page_token}, + * received from a previous + * {@link protos.google.cloud.retail.v2alpha.CatalogService.ListCatalogs|CatalogService.ListCatalogs} + * call. Provide this to retrieve the subsequent page. + * + * When paginating, all other parameters provided to + * {@link protos.google.cloud.retail.v2alpha.CatalogService.ListCatalogs|CatalogService.ListCatalogs} + * must match the call that provided the page token. Otherwise, an + * INVALID_ARGUMENT error is returned. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.cloud.retail.v2alpha.Catalog|Catalog}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listCatalogsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listCatalogs( - request?: protos.google.cloud.retail.v2alpha.IListCatalogsRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.retail.v2alpha.ICatalog[], - protos.google.cloud.retail.v2alpha.IListCatalogsRequest|null, - protos.google.cloud.retail.v2alpha.IListCatalogsResponse - ]>; + request?: protos.google.cloud.retail.v2alpha.IListCatalogsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.ICatalog[], + protos.google.cloud.retail.v2alpha.IListCatalogsRequest | null, + protos.google.cloud.retail.v2alpha.IListCatalogsResponse, + ] + >; listCatalogs( - request: protos.google.cloud.retail.v2alpha.IListCatalogsRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.cloud.retail.v2alpha.IListCatalogsRequest, - protos.google.cloud.retail.v2alpha.IListCatalogsResponse|null|undefined, - protos.google.cloud.retail.v2alpha.ICatalog>): void; + request: protos.google.cloud.retail.v2alpha.IListCatalogsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.cloud.retail.v2alpha.IListCatalogsRequest, + | protos.google.cloud.retail.v2alpha.IListCatalogsResponse + | null + | undefined, + protos.google.cloud.retail.v2alpha.ICatalog + >, + ): void; listCatalogs( - request: protos.google.cloud.retail.v2alpha.IListCatalogsRequest, - callback: PaginationCallback< - protos.google.cloud.retail.v2alpha.IListCatalogsRequest, - protos.google.cloud.retail.v2alpha.IListCatalogsResponse|null|undefined, - protos.google.cloud.retail.v2alpha.ICatalog>): void; + request: protos.google.cloud.retail.v2alpha.IListCatalogsRequest, + callback: PaginationCallback< + protos.google.cloud.retail.v2alpha.IListCatalogsRequest, + | protos.google.cloud.retail.v2alpha.IListCatalogsResponse + | null + | undefined, + protos.google.cloud.retail.v2alpha.ICatalog + >, + ): void; listCatalogs( - request?: protos.google.cloud.retail.v2alpha.IListCatalogsRequest, - optionsOrCallback?: CallOptions|PaginationCallback< - protos.google.cloud.retail.v2alpha.IListCatalogsRequest, - protos.google.cloud.retail.v2alpha.IListCatalogsResponse|null|undefined, - protos.google.cloud.retail.v2alpha.ICatalog>, - callback?: PaginationCallback< + request?: protos.google.cloud.retail.v2alpha.IListCatalogsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.cloud.retail.v2alpha.IListCatalogsRequest, - protos.google.cloud.retail.v2alpha.IListCatalogsResponse|null|undefined, - protos.google.cloud.retail.v2alpha.ICatalog>): - Promise<[ - protos.google.cloud.retail.v2alpha.ICatalog[], - protos.google.cloud.retail.v2alpha.IListCatalogsRequest|null, - protos.google.cloud.retail.v2alpha.IListCatalogsResponse - ]>|void { + | protos.google.cloud.retail.v2alpha.IListCatalogsResponse + | null + | undefined, + protos.google.cloud.retail.v2alpha.ICatalog + >, + callback?: PaginationCallback< + protos.google.cloud.retail.v2alpha.IListCatalogsRequest, + | protos.google.cloud.retail.v2alpha.IListCatalogsResponse + | null + | undefined, + protos.google.cloud.retail.v2alpha.ICatalog + >, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.ICatalog[], + protos.google.cloud.retail.v2alpha.IListCatalogsRequest | null, + protos.google.cloud.retail.v2alpha.IListCatalogsResponse, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.cloud.retail.v2alpha.IListCatalogsRequest, - protos.google.cloud.retail.v2alpha.IListCatalogsResponse|null|undefined, - protos.google.cloud.retail.v2alpha.ICatalog>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.cloud.retail.v2alpha.IListCatalogsRequest, + | protos.google.cloud.retail.v2alpha.IListCatalogsResponse + | null + | undefined, + protos.google.cloud.retail.v2alpha.ICatalog + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listCatalogs values %j', values); callback!(error, values, nextPageRequest, rawResponse); @@ -1675,142 +2289,146 @@ export class CatalogServiceClient { this._log.info('listCatalogs request %j', request); return this.innerApiCalls .listCatalogs(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.cloud.retail.v2alpha.ICatalog[], - protos.google.cloud.retail.v2alpha.IListCatalogsRequest|null, - protos.google.cloud.retail.v2alpha.IListCatalogsResponse - ]) => { - this._log.info('listCatalogs values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.cloud.retail.v2alpha.ICatalog[], + protos.google.cloud.retail.v2alpha.IListCatalogsRequest | null, + protos.google.cloud.retail.v2alpha.IListCatalogsResponse, + ]) => { + this._log.info('listCatalogs values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listCatalogs`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The account resource name with an associated location. - * - * If the caller does not have permission to list - * {@link protos.google.cloud.retail.v2alpha.Catalog|Catalog}s under this location, - * regardless of whether or not this location exists, a PERMISSION_DENIED - * error is returned. - * @param {number} request.pageSize - * Maximum number of {@link protos.google.cloud.retail.v2alpha.Catalog|Catalog}s to - * return. If unspecified, defaults to 50. The maximum allowed value is 1000. - * Values above 1000 will be coerced to 1000. - * - * If this field is negative, an INVALID_ARGUMENT is returned. - * @param {string} request.pageToken - * A page token - * {@link protos.google.cloud.retail.v2alpha.ListCatalogsResponse.next_page_token|ListCatalogsResponse.next_page_token}, - * received from a previous - * {@link protos.google.cloud.retail.v2alpha.CatalogService.ListCatalogs|CatalogService.ListCatalogs} - * call. Provide this to retrieve the subsequent page. - * - * When paginating, all other parameters provided to - * {@link protos.google.cloud.retail.v2alpha.CatalogService.ListCatalogs|CatalogService.ListCatalogs} - * must match the call that provided the page token. Otherwise, an - * INVALID_ARGUMENT error is returned. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.cloud.retail.v2alpha.Catalog|Catalog} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `listCatalogsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `listCatalogs`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The account resource name with an associated location. + * + * If the caller does not have permission to list + * {@link protos.google.cloud.retail.v2alpha.Catalog|Catalog}s under this location, + * regardless of whether or not this location exists, a PERMISSION_DENIED + * error is returned. + * @param {number} request.pageSize + * Maximum number of {@link protos.google.cloud.retail.v2alpha.Catalog|Catalog}s to + * return. If unspecified, defaults to 50. The maximum allowed value is 1000. + * Values above 1000 will be coerced to 1000. + * + * If this field is negative, an INVALID_ARGUMENT is returned. + * @param {string} request.pageToken + * A page token + * {@link protos.google.cloud.retail.v2alpha.ListCatalogsResponse.next_page_token|ListCatalogsResponse.next_page_token}, + * received from a previous + * {@link protos.google.cloud.retail.v2alpha.CatalogService.ListCatalogs|CatalogService.ListCatalogs} + * call. Provide this to retrieve the subsequent page. + * + * When paginating, all other parameters provided to + * {@link protos.google.cloud.retail.v2alpha.CatalogService.ListCatalogs|CatalogService.ListCatalogs} + * must match the call that provided the page token. Otherwise, an + * INVALID_ARGUMENT error is returned. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.cloud.retail.v2alpha.Catalog|Catalog} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listCatalogsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listCatalogsStream( - request?: protos.google.cloud.retail.v2alpha.IListCatalogsRequest, - options?: CallOptions): - Transform{ + request?: protos.google.cloud.retail.v2alpha.IListCatalogsRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); const defaultCallSettings = this._defaults['listCatalogs']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listCatalogs stream %j', request); return this.descriptors.page.listCatalogs.createStream( this.innerApiCalls.listCatalogs as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listCatalogs`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The account resource name with an associated location. - * - * If the caller does not have permission to list - * {@link protos.google.cloud.retail.v2alpha.Catalog|Catalog}s under this location, - * regardless of whether or not this location exists, a PERMISSION_DENIED - * error is returned. - * @param {number} request.pageSize - * Maximum number of {@link protos.google.cloud.retail.v2alpha.Catalog|Catalog}s to - * return. If unspecified, defaults to 50. The maximum allowed value is 1000. - * Values above 1000 will be coerced to 1000. - * - * If this field is negative, an INVALID_ARGUMENT is returned. - * @param {string} request.pageToken - * A page token - * {@link protos.google.cloud.retail.v2alpha.ListCatalogsResponse.next_page_token|ListCatalogsResponse.next_page_token}, - * received from a previous - * {@link protos.google.cloud.retail.v2alpha.CatalogService.ListCatalogs|CatalogService.ListCatalogs} - * call. Provide this to retrieve the subsequent page. - * - * When paginating, all other parameters provided to - * {@link protos.google.cloud.retail.v2alpha.CatalogService.ListCatalogs|CatalogService.ListCatalogs} - * must match the call that provided the page token. Otherwise, an - * INVALID_ARGUMENT error is returned. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.cloud.retail.v2alpha.Catalog|Catalog}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/catalog_service.list_catalogs.js - * region_tag:retail_v2alpha_generated_CatalogService_ListCatalogs_async - */ + /** + * Equivalent to `listCatalogs`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The account resource name with an associated location. + * + * If the caller does not have permission to list + * {@link protos.google.cloud.retail.v2alpha.Catalog|Catalog}s under this location, + * regardless of whether or not this location exists, a PERMISSION_DENIED + * error is returned. + * @param {number} request.pageSize + * Maximum number of {@link protos.google.cloud.retail.v2alpha.Catalog|Catalog}s to + * return. If unspecified, defaults to 50. The maximum allowed value is 1000. + * Values above 1000 will be coerced to 1000. + * + * If this field is negative, an INVALID_ARGUMENT is returned. + * @param {string} request.pageToken + * A page token + * {@link protos.google.cloud.retail.v2alpha.ListCatalogsResponse.next_page_token|ListCatalogsResponse.next_page_token}, + * received from a previous + * {@link protos.google.cloud.retail.v2alpha.CatalogService.ListCatalogs|CatalogService.ListCatalogs} + * call. Provide this to retrieve the subsequent page. + * + * When paginating, all other parameters provided to + * {@link protos.google.cloud.retail.v2alpha.CatalogService.ListCatalogs|CatalogService.ListCatalogs} + * must match the call that provided the page token. Otherwise, an + * INVALID_ARGUMENT error is returned. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.cloud.retail.v2alpha.Catalog|Catalog}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/catalog_service.list_catalogs.js + * region_tag:retail_v2alpha_generated_CatalogService_ListCatalogs_async + */ listCatalogsAsync( - request?: protos.google.cloud.retail.v2alpha.IListCatalogsRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.cloud.retail.v2alpha.IListCatalogsRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); const defaultCallSettings = this._defaults['listCatalogs']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listCatalogs iterate %j', request); return this.descriptors.page.listCatalogs.asyncIterate( this.innerApiCalls['listCatalogs'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } // -------------------- @@ -1823,7 +2441,7 @@ export class CatalogServiceClient { * @param {string} project * @returns {string} Resource name string. */ - alertConfigPath(project:string) { + alertConfigPath(project: string) { return this.pathTemplates.alertConfigPathTemplate.render({ project: project, }); @@ -1837,7 +2455,8 @@ export class CatalogServiceClient { * @returns {string} A string representing the project. */ matchProjectFromAlertConfigName(alertConfigName: string) { - return this.pathTemplates.alertConfigPathTemplate.match(alertConfigName).project; + return this.pathTemplates.alertConfigPathTemplate.match(alertConfigName) + .project; } /** @@ -1848,7 +2467,7 @@ export class CatalogServiceClient { * @param {string} catalog * @returns {string} Resource name string. */ - attributesConfigPath(project:string,location:string,catalog:string) { + attributesConfigPath(project: string, location: string, catalog: string) { return this.pathTemplates.attributesConfigPathTemplate.render({ project: project, location: location, @@ -1864,7 +2483,9 @@ export class CatalogServiceClient { * @returns {string} A string representing the project. */ matchProjectFromAttributesConfigName(attributesConfigName: string) { - return this.pathTemplates.attributesConfigPathTemplate.match(attributesConfigName).project; + return this.pathTemplates.attributesConfigPathTemplate.match( + attributesConfigName, + ).project; } /** @@ -1875,7 +2496,9 @@ export class CatalogServiceClient { * @returns {string} A string representing the location. */ matchLocationFromAttributesConfigName(attributesConfigName: string) { - return this.pathTemplates.attributesConfigPathTemplate.match(attributesConfigName).location; + return this.pathTemplates.attributesConfigPathTemplate.match( + attributesConfigName, + ).location; } /** @@ -1886,7 +2509,9 @@ export class CatalogServiceClient { * @returns {string} A string representing the catalog. */ matchCatalogFromAttributesConfigName(attributesConfigName: string) { - return this.pathTemplates.attributesConfigPathTemplate.match(attributesConfigName).catalog; + return this.pathTemplates.attributesConfigPathTemplate.match( + attributesConfigName, + ).catalog; } /** @@ -1898,7 +2523,12 @@ export class CatalogServiceClient { * @param {string} branch * @returns {string} Resource name string. */ - branchPath(project:string,location:string,catalog:string,branch:string) { + branchPath( + project: string, + location: string, + catalog: string, + branch: string, + ) { return this.pathTemplates.branchPathTemplate.render({ project: project, location: location, @@ -1959,7 +2589,7 @@ export class CatalogServiceClient { * @param {string} catalog * @returns {string} Resource name string. */ - catalogPath(project:string,location:string,catalog:string) { + catalogPath(project: string, location: string, catalog: string) { return this.pathTemplates.catalogPathTemplate.render({ project: project, location: location, @@ -2008,7 +2638,7 @@ export class CatalogServiceClient { * @param {string} catalog * @returns {string} Resource name string. */ - completionConfigPath(project:string,location:string,catalog:string) { + completionConfigPath(project: string, location: string, catalog: string) { return this.pathTemplates.completionConfigPathTemplate.render({ project: project, location: location, @@ -2024,7 +2654,9 @@ export class CatalogServiceClient { * @returns {string} A string representing the project. */ matchProjectFromCompletionConfigName(completionConfigName: string) { - return this.pathTemplates.completionConfigPathTemplate.match(completionConfigName).project; + return this.pathTemplates.completionConfigPathTemplate.match( + completionConfigName, + ).project; } /** @@ -2035,7 +2667,9 @@ export class CatalogServiceClient { * @returns {string} A string representing the location. */ matchLocationFromCompletionConfigName(completionConfigName: string) { - return this.pathTemplates.completionConfigPathTemplate.match(completionConfigName).location; + return this.pathTemplates.completionConfigPathTemplate.match( + completionConfigName, + ).location; } /** @@ -2046,7 +2680,9 @@ export class CatalogServiceClient { * @returns {string} A string representing the catalog. */ matchCatalogFromCompletionConfigName(completionConfigName: string) { - return this.pathTemplates.completionConfigPathTemplate.match(completionConfigName).catalog; + return this.pathTemplates.completionConfigPathTemplate.match( + completionConfigName, + ).catalog; } /** @@ -2058,7 +2694,12 @@ export class CatalogServiceClient { * @param {string} control * @returns {string} Resource name string. */ - controlPath(project:string,location:string,catalog:string,control:string) { + controlPath( + project: string, + location: string, + catalog: string, + control: string, + ) { return this.pathTemplates.controlPathTemplate.render({ project: project, location: location, @@ -2118,7 +2759,7 @@ export class CatalogServiceClient { * @param {string} location * @returns {string} Resource name string. */ - locationPath(project:string,location:string) { + locationPath(project: string, location: string) { return this.pathTemplates.locationPathTemplate.render({ project: project, location: location, @@ -2153,7 +2794,7 @@ export class CatalogServiceClient { * @param {string} project * @returns {string} Resource name string. */ - loggingConfigPath(project:string) { + loggingConfigPath(project: string) { return this.pathTemplates.loggingConfigPathTemplate.render({ project: project, }); @@ -2167,7 +2808,8 @@ export class CatalogServiceClient { * @returns {string} A string representing the project. */ matchProjectFromLoggingConfigName(loggingConfigName: string) { - return this.pathTemplates.loggingConfigPathTemplate.match(loggingConfigName).project; + return this.pathTemplates.loggingConfigPathTemplate.match(loggingConfigName) + .project; } /** @@ -2179,7 +2821,12 @@ export class CatalogServiceClient { * @param {string} merchant_center_account_link * @returns {string} Resource name string. */ - merchantCenterAccountLinkPath(project:string,location:string,catalog:string,merchantCenterAccountLink:string) { + merchantCenterAccountLinkPath( + project: string, + location: string, + catalog: string, + merchantCenterAccountLink: string, + ) { return this.pathTemplates.merchantCenterAccountLinkPathTemplate.render({ project: project, location: location, @@ -2195,8 +2842,12 @@ export class CatalogServiceClient { * A fully-qualified path representing MerchantCenterAccountLink resource. * @returns {string} A string representing the project. */ - matchProjectFromMerchantCenterAccountLinkName(merchantCenterAccountLinkName: string) { - return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match(merchantCenterAccountLinkName).project; + matchProjectFromMerchantCenterAccountLinkName( + merchantCenterAccountLinkName: string, + ) { + return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match( + merchantCenterAccountLinkName, + ).project; } /** @@ -2206,8 +2857,12 @@ export class CatalogServiceClient { * A fully-qualified path representing MerchantCenterAccountLink resource. * @returns {string} A string representing the location. */ - matchLocationFromMerchantCenterAccountLinkName(merchantCenterAccountLinkName: string) { - return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match(merchantCenterAccountLinkName).location; + matchLocationFromMerchantCenterAccountLinkName( + merchantCenterAccountLinkName: string, + ) { + return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match( + merchantCenterAccountLinkName, + ).location; } /** @@ -2217,8 +2872,12 @@ export class CatalogServiceClient { * A fully-qualified path representing MerchantCenterAccountLink resource. * @returns {string} A string representing the catalog. */ - matchCatalogFromMerchantCenterAccountLinkName(merchantCenterAccountLinkName: string) { - return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match(merchantCenterAccountLinkName).catalog; + matchCatalogFromMerchantCenterAccountLinkName( + merchantCenterAccountLinkName: string, + ) { + return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match( + merchantCenterAccountLinkName, + ).catalog; } /** @@ -2228,8 +2887,12 @@ export class CatalogServiceClient { * A fully-qualified path representing MerchantCenterAccountLink resource. * @returns {string} A string representing the merchant_center_account_link. */ - matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName(merchantCenterAccountLinkName: string) { - return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match(merchantCenterAccountLinkName).merchant_center_account_link; + matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName( + merchantCenterAccountLinkName: string, + ) { + return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match( + merchantCenterAccountLinkName, + ).merchant_center_account_link; } /** @@ -2241,7 +2904,7 @@ export class CatalogServiceClient { * @param {string} model * @returns {string} Resource name string. */ - modelPath(project:string,location:string,catalog:string,model:string) { + modelPath(project: string, location: string, catalog: string, model: string) { return this.pathTemplates.modelPathTemplate.render({ project: project, location: location, @@ -2304,7 +2967,13 @@ export class CatalogServiceClient { * @param {string} product * @returns {string} Resource name string. */ - productPath(project:string,location:string,catalog:string,branch:string,product:string) { + productPath( + project: string, + location: string, + catalog: string, + branch: string, + product: string, + ) { return this.pathTemplates.productPathTemplate.render({ project: project, location: location, @@ -2375,7 +3044,7 @@ export class CatalogServiceClient { * @param {string} project * @returns {string} Resource name string. */ - retailProjectPath(project:string) { + retailProjectPath(project: string) { return this.pathTemplates.retailProjectPathTemplate.render({ project: project, }); @@ -2389,7 +3058,8 @@ export class CatalogServiceClient { * @returns {string} A string representing the project. */ matchProjectFromRetailProjectName(retailProjectName: string) { - return this.pathTemplates.retailProjectPathTemplate.match(retailProjectName).project; + return this.pathTemplates.retailProjectPathTemplate.match(retailProjectName) + .project; } /** @@ -2401,7 +3071,12 @@ export class CatalogServiceClient { * @param {string} serving_config * @returns {string} Resource name string. */ - servingConfigPath(project:string,location:string,catalog:string,servingConfig:string) { + servingConfigPath( + project: string, + location: string, + catalog: string, + servingConfig: string, + ) { return this.pathTemplates.servingConfigPathTemplate.render({ project: project, location: location, @@ -2418,7 +3093,8 @@ export class CatalogServiceClient { * @returns {string} A string representing the project. */ matchProjectFromServingConfigName(servingConfigName: string) { - return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName).project; + return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName) + .project; } /** @@ -2429,7 +3105,8 @@ export class CatalogServiceClient { * @returns {string} A string representing the location. */ matchLocationFromServingConfigName(servingConfigName: string) { - return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName).location; + return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName) + .location; } /** @@ -2440,7 +3117,8 @@ export class CatalogServiceClient { * @returns {string} A string representing the catalog. */ matchCatalogFromServingConfigName(servingConfigName: string) { - return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName).catalog; + return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName) + .catalog; } /** @@ -2451,7 +3129,8 @@ export class CatalogServiceClient { * @returns {string} A string representing the serving_config. */ matchServingConfigFromServingConfigName(servingConfigName: string) { - return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName).serving_config; + return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName) + .serving_config; } /** @@ -2462,7 +3141,7 @@ export class CatalogServiceClient { */ close(): Promise { if (this.catalogServiceStub && !this._terminated) { - return this.catalogServiceStub.then(stub => { + return this.catalogServiceStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -2470,4 +3149,4 @@ export class CatalogServiceClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/src/v2alpha/completion_service_client.ts.baseline b/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/src/v2alpha/completion_service_client.ts.baseline index 330e4256222b..75f5bcd75a6b 100644 --- a/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/src/v2alpha/completion_service_client.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/src/v2alpha/completion_service_client.ts.baseline @@ -18,15 +18,22 @@ /* global window */ import * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions, GrpcClientOptions, LROperation} from 'google-gax'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + GrpcClientOptions, + LROperation, +} from 'google-gax'; // @ts-ignore import type * as protos from '../../../protos/protos.js'; import * as completion_service_client_config from './completion_service_client_config.json'; import fs from 'fs'; import path from 'path'; -import {fileURLToPath} from 'url'; -import {getJSON} from '../json-helper.cjs'; +import { fileURLToPath } from 'url'; +import { getJSON } from '../json-helper.cjs'; // @ts-ignore const dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -36,15 +43,15 @@ const dirname = path.dirname(fileURLToPath(import.meta.url)); * This file defines retry strategy and timeouts for all API methods in this library. */ const gapicConfig = getJSON( - path.join(dirname, 'completion_service_client_config.json') + path.join(dirname, 'completion_service_client_config.json'), ); const jsonProtos = getJSON( - path.join(dirname, '..', '..', '..', 'protos/protos.json') + path.join(dirname, '..', '..', '..', 'protos/protos.json'), ); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; const version = getJSON( - path.join(dirname, '..', '..', '..', '..', 'package.json') + path.join(dirname, '..', '..', '..', '..', 'package.json'), ).version; /** @@ -62,7 +69,7 @@ export class CompletionServiceClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('retail'); @@ -74,10 +81,10 @@ export class CompletionServiceClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; operationsClient: gax.OperationsClient; - completionServiceStub?: Promise<{[name: string]: Function}>; + completionServiceStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of CompletionServiceClient. @@ -119,21 +126,42 @@ export class CompletionServiceClient { * const client = new CompletionServiceClient({fallback: 'rest'}, gax); * ``` */ - constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { // Ensure that options include all the required fields. const staticMembers = this.constructor as typeof CompletionServiceClient; - if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { - throw new Error('Please set either universe_domain or universeDomain, but not both.'); + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); } - const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; - this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; this._servicePath = 'retail.' + this._universeDomain; - const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; - const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. if (servicePath !== this._servicePath && !('scopes' in opts)) { @@ -155,7 +183,7 @@ export class CompletionServiceClient { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; @@ -172,10 +200,7 @@ export class CompletionServiceClient { const isEsm = true; const isEsmString = isEsm ? '-esm' : '-cjs'; // Determine the client header string. - const clientHeader = [ - `gax/${this._gaxModule.version}`, - `gapic/${version}`, - ]; + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/{process.versions.node}${isEsmString}`); } else { @@ -183,7 +208,7 @@ export class CompletionServiceClient { } if (!opts.fallback) { clientHeader.push(`grpc/${this._gaxGrpc.grpcVersion}`); - } else if (opts.fallback === 'rest' ) { + } else if (opts.fallback === 'rest') { clientHeader.push(`rest/${this._gaxGrpc.grpcVersion}`); } if (opts.libName && opts.libVersion) { @@ -191,47 +216,49 @@ export class CompletionServiceClient { } // Load the applicable protos. - this._protos = this._gaxGrpc.loadProtoJSON(jsonProtos as gax.protobuf.INamespace); + this._protos = this._gaxGrpc.loadProtoJSON( + jsonProtos as gax.protobuf.INamespace, + ); // This API contains "path templates"; forward-slash-separated // identifiers to uniquely identify resources within the API. // Create useful helper objects for these. this.pathTemplates = { alertConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/alertConfig' + 'projects/{project}/alertConfig', ), attributesConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/attributesConfig' + 'projects/{project}/locations/{location}/catalogs/{catalog}/attributesConfig', ), branchPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}', ), catalogPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}' + 'projects/{project}/locations/{location}/catalogs/{catalog}', ), completionConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/completionConfig' + 'projects/{project}/locations/{location}/catalogs/{catalog}/completionConfig', ), controlPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/controls/{control}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/controls/{control}', ), loggingConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/loggingConfig' + 'projects/{project}/loggingConfig', ), merchantCenterAccountLinkPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/merchantCenterAccountLinks/{merchant_center_account_link}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/merchantCenterAccountLinks/{merchant_center_account_link}', ), modelPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/models/{model}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/models/{model}', ), productPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}', ), retailProjectPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/retailProject' + 'projects/{project}/retailProject', ), servingConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/servingConfigs/{serving_config}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/servingConfigs/{serving_config}', ), }; @@ -241,31 +268,60 @@ export class CompletionServiceClient { // rather than holding a request open. const lroOptions: GrpcClientOptions = { auth: this.auth, - grpc: 'grpc' in this._gaxGrpc ? this._gaxGrpc.grpc : undefined + grpc: 'grpc' in this._gaxGrpc ? this._gaxGrpc.grpc : undefined, }; if (opts.fallback === 'rest') { lroOptions.protoJson = protoFilesRoot; - lroOptions.httpRules = [{selector: 'google.longrunning.Operations.GetOperation',get: '/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*/operations/*}',additional_bindings: [{get: '/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*/places/*/operations/*}',},{get: '/v2alpha/{name=projects/*/locations/*/catalogs/*/operations/*}',},{get: '/v2alpha/{name=projects/*/locations/*/operations/*}',},{get: '/v2alpha/{name=projects/*/operations/*}',}], - },{selector: 'google.longrunning.Operations.ListOperations',get: '/v2alpha/{name=projects/*/locations/*/catalogs/*}/operations',additional_bindings: [{get: '/v2alpha/{name=projects/*/locations/*}/operations',},{get: '/v2alpha/{name=projects/*}/operations',}], - }]; + lroOptions.httpRules = [ + { + selector: 'google.longrunning.Operations.GetOperation', + get: '/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*/operations/*}', + additional_bindings: [ + { + get: '/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*/places/*/operations/*}', + }, + { + get: '/v2alpha/{name=projects/*/locations/*/catalogs/*/operations/*}', + }, + { get: '/v2alpha/{name=projects/*/locations/*/operations/*}' }, + { get: '/v2alpha/{name=projects/*/operations/*}' }, + ], + }, + { + selector: 'google.longrunning.Operations.ListOperations', + get: '/v2alpha/{name=projects/*/locations/*/catalogs/*}/operations', + additional_bindings: [ + { get: '/v2alpha/{name=projects/*/locations/*}/operations' }, + { get: '/v2alpha/{name=projects/*}/operations' }, + ], + }, + ]; } - this.operationsClient = this._gaxModule.lro(lroOptions).operationsClient(opts); + this.operationsClient = this._gaxModule + .lro(lroOptions) + .operationsClient(opts); const importCompletionDataResponse = protoFilesRoot.lookup( - '.google.cloud.retail.v2alpha.ImportCompletionDataResponse') as gax.protobuf.Type; + '.google.cloud.retail.v2alpha.ImportCompletionDataResponse', + ) as gax.protobuf.Type; const importCompletionDataMetadata = protoFilesRoot.lookup( - '.google.cloud.retail.v2alpha.ImportMetadata') as gax.protobuf.Type; + '.google.cloud.retail.v2alpha.ImportMetadata', + ) as gax.protobuf.Type; this.descriptors.longrunning = { importCompletionData: new this._gaxModule.LongrunningDescriptor( this.operationsClient, importCompletionDataResponse.decode.bind(importCompletionDataResponse), - importCompletionDataMetadata.decode.bind(importCompletionDataMetadata)) + importCompletionDataMetadata.decode.bind(importCompletionDataMetadata), + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.cloud.retail.v2alpha.CompletionService', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.cloud.retail.v2alpha.CompletionService', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + { 'x-goog-api-client': clientHeader.join(' ') }, + ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -296,37 +352,43 @@ export class CompletionServiceClient { // Put together the "service stub" for // google.cloud.retail.v2alpha.CompletionService. this.completionServiceStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.cloud.retail.v2alpha.CompletionService') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.cloud.retail.v2alpha.CompletionService', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.cloud.retail.v2alpha.CompletionService, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts, + this._providedCustomServicePath, + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const completionServiceStubMethods = - ['completeQuery', 'importCompletionData']; + const completionServiceStubMethods = [ + 'completeQuery', + 'importCompletionData', + ]; for (const methodName of completionServiceStubMethods) { const callPromise = this.completionServiceStub.then( - stub => (...args: Array<{}>) => { - if (this._terminated) { - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error|null|undefined) => () => { + (stub) => + (...args: Array<{}>) => { + if (this._terminated) { + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { throw err; - }); + }, + ); - const descriptor = - this.descriptors.longrunning[methodName] || - undefined; + const descriptor = this.descriptors.longrunning[methodName] || undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -341,8 +403,14 @@ export class CompletionServiceClient { * @returns {string} The DNS address for this service. */ static get servicePath() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'retail.googleapis.com'; } @@ -354,8 +422,14 @@ export class CompletionServiceClient { * @returns {string} The DNS address for this service. */ static get apiEndpoint() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'retail.googleapis.com'; } @@ -386,9 +460,7 @@ export class CompletionServiceClient { * @returns {string[]} List of default scopes. */ static get scopes() { - return [ - 'https://www.googleapis.com/auth/cloud-platform' - ]; + return ['https://www.googleapis.com/auth/cloud-platform']; } getProjectId(): Promise; @@ -397,8 +469,9 @@ export class CompletionServiceClient { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId(callback?: Callback): - Promise|void { + getProjectId( + callback?: Callback, + ): Promise | void { if (callback) { this.auth.getProjectId(callback); return; @@ -409,307 +482,410 @@ export class CompletionServiceClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Completes the specified prefix with keyword suggestions. - * - * This feature is only available for users who have Retail Search enabled. - * Enable Retail Search on Cloud Console before using this feature. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.catalog - * Required. Catalog for which the completion is performed. - * - * Full resource name of catalog, such as - * `projects/* /locations/global/catalogs/default_catalog`. - * @param {string} request.query - * Required. The query used to generate suggestions. - * - * The maximum number of allowed characters is 255. - * @param {string} request.visitorId - * Recommended field. A unique identifier for tracking visitors. For example, - * this could be implemented with an HTTP cookie, which should be able to - * uniquely identify a visitor on a single device. This unique identifier - * should not change if the visitor logs in or out of the website. - * - * The field must be a UTF-8 encoded string with a length limit of 128 - * characters. Otherwise, an INVALID_ARGUMENT error is returned. - * @param {string[]} request.languageCodes - * Note that this field applies for `user-data` dataset only. For requests - * with `cloud-retail` dataset, setting this field has no effect. - * - * The language filters applied to the output suggestions. If set, it should - * contain the language of the query. If not set, suggestions are returned - * without considering language restrictions. This is the BCP-47 language - * code, such as "en-US" or "sr-Latn". For more information, see [Tags for - * Identifying Languages](https://tools.ietf.org/html/bcp47). The maximum - * number of language codes is 3. - * @param {string} request.deviceType - * The device type context for completion suggestions. We recommend that you - * leave this field empty. - * - * It can apply different suggestions on different device types, e.g. - * `DESKTOP`, `MOBILE`. If it is empty, the suggestions are across all device - * types. - * - * Supported formats: - * - * * `UNKNOWN_DEVICE_TYPE` - * - * * `DESKTOP` - * - * * `MOBILE` - * - * * A customized string starts with `OTHER_`, e.g. `OTHER_IPHONE`. - * @param {string} request.dataset - * Determines which dataset to use for fetching completion. "user-data" will - * use the dataset imported through - * {@link protos.google.cloud.retail.v2alpha.CompletionService.ImportCompletionData|CompletionService.ImportCompletionData}. - * `cloud-retail` will use the dataset generated by Cloud Retail based on user - * events. If left empty, completions will be fetched from the `user-data` - * dataset. - * - * Current supported values: - * - * * user-data - * - * * cloud-retail: - * This option requires enabling auto-learning function first. See - * [guidelines](https://cloud.google.com/retail/docs/completion-overview#generated-completion-dataset). - * @param {number} request.maxSuggestions - * Completion max suggestions. If left unset or set to 0, then will fallback - * to the configured value - * {@link protos.google.cloud.retail.v2alpha.CompletionConfig.max_suggestions|CompletionConfig.max_suggestions}. - * - * The maximum allowed max suggestions is 20. If it is set higher, it will be - * capped by 20. - * @param {boolean} request.enableAttributeSuggestions - * If true, attribute suggestions are enabled and provided in the response. - * - * This field is only available for the `cloud-retail` dataset. - * @param {string} request.entity - * The entity for customers who run multiple entities, domains, sites, or - * regions, for example, `Google US`, `Google Ads`, `Waymo`, - * `google.com`, `youtube.com`, etc. - * If this is set, it must be an exact match with - * {@link protos.google.cloud.retail.v2alpha.UserEvent.entity|UserEvent.entity} to get - * per-entity autocomplete results. This field will be applied to - * `completion_results` only. It has no effect on the `attribute_results`. - * Also, this entity should be limited to 256 characters, if too long, it will - * be truncated to 256 characters in both generation and serving time, and may - * lead to mis-match. To ensure it works, please set the entity with string - * within 256 characters. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.CompleteQueryResponse|CompleteQueryResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/completion_service.complete_query.js - * region_tag:retail_v2alpha_generated_CompletionService_CompleteQuery_async - */ + /** + * Completes the specified prefix with keyword suggestions. + * + * This feature is only available for users who have Retail Search enabled. + * Enable Retail Search on Cloud Console before using this feature. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.catalog + * Required. Catalog for which the completion is performed. + * + * Full resource name of catalog, such as + * `projects/* /locations/global/catalogs/default_catalog`. + * @param {string} request.query + * Required. The query used to generate suggestions. + * + * The maximum number of allowed characters is 255. + * @param {string} request.visitorId + * Recommended field. A unique identifier for tracking visitors. For example, + * this could be implemented with an HTTP cookie, which should be able to + * uniquely identify a visitor on a single device. This unique identifier + * should not change if the visitor logs in or out of the website. + * + * The field must be a UTF-8 encoded string with a length limit of 128 + * characters. Otherwise, an INVALID_ARGUMENT error is returned. + * @param {string[]} request.languageCodes + * Note that this field applies for `user-data` dataset only. For requests + * with `cloud-retail` dataset, setting this field has no effect. + * + * The language filters applied to the output suggestions. If set, it should + * contain the language of the query. If not set, suggestions are returned + * without considering language restrictions. This is the BCP-47 language + * code, such as "en-US" or "sr-Latn". For more information, see [Tags for + * Identifying Languages](https://tools.ietf.org/html/bcp47). The maximum + * number of language codes is 3. + * @param {string} request.deviceType + * The device type context for completion suggestions. We recommend that you + * leave this field empty. + * + * It can apply different suggestions on different device types, e.g. + * `DESKTOP`, `MOBILE`. If it is empty, the suggestions are across all device + * types. + * + * Supported formats: + * + * * `UNKNOWN_DEVICE_TYPE` + * + * * `DESKTOP` + * + * * `MOBILE` + * + * * A customized string starts with `OTHER_`, e.g. `OTHER_IPHONE`. + * @param {string} request.dataset + * Determines which dataset to use for fetching completion. "user-data" will + * use the dataset imported through + * {@link protos.google.cloud.retail.v2alpha.CompletionService.ImportCompletionData|CompletionService.ImportCompletionData}. + * `cloud-retail` will use the dataset generated by Cloud Retail based on user + * events. If left empty, completions will be fetched from the `user-data` + * dataset. + * + * Current supported values: + * + * * user-data + * + * * cloud-retail: + * This option requires enabling auto-learning function first. See + * [guidelines](https://cloud.google.com/retail/docs/completion-overview#generated-completion-dataset). + * @param {number} request.maxSuggestions + * Completion max suggestions. If left unset or set to 0, then will fallback + * to the configured value + * {@link protos.google.cloud.retail.v2alpha.CompletionConfig.max_suggestions|CompletionConfig.max_suggestions}. + * + * The maximum allowed max suggestions is 20. If it is set higher, it will be + * capped by 20. + * @param {boolean} request.enableAttributeSuggestions + * If true, attribute suggestions are enabled and provided in the response. + * + * This field is only available for the `cloud-retail` dataset. + * @param {string} request.entity + * The entity for customers who run multiple entities, domains, sites, or + * regions, for example, `Google US`, `Google Ads`, `Waymo`, + * `google.com`, `youtube.com`, etc. + * If this is set, it must be an exact match with + * {@link protos.google.cloud.retail.v2alpha.UserEvent.entity|UserEvent.entity} to get + * per-entity autocomplete results. This field will be applied to + * `completion_results` only. It has no effect on the `attribute_results`. + * Also, this entity should be limited to 256 characters, if too long, it will + * be truncated to 256 characters in both generation and serving time, and may + * lead to mis-match. To ensure it works, please set the entity with string + * within 256 characters. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.CompleteQueryResponse|CompleteQueryResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/completion_service.complete_query.js + * region_tag:retail_v2alpha_generated_CompletionService_CompleteQuery_async + */ completeQuery( - request?: protos.google.cloud.retail.v2alpha.ICompleteQueryRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.retail.v2alpha.ICompleteQueryResponse, - protos.google.cloud.retail.v2alpha.ICompleteQueryRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.ICompleteQueryRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.ICompleteQueryResponse, + protos.google.cloud.retail.v2alpha.ICompleteQueryRequest | undefined, + {} | undefined, + ] + >; completeQuery( - request: protos.google.cloud.retail.v2alpha.ICompleteQueryRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.retail.v2alpha.ICompleteQueryResponse, - protos.google.cloud.retail.v2alpha.ICompleteQueryRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.ICompleteQueryRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.retail.v2alpha.ICompleteQueryResponse, + | protos.google.cloud.retail.v2alpha.ICompleteQueryRequest + | null + | undefined, + {} | null | undefined + >, + ): void; completeQuery( - request: protos.google.cloud.retail.v2alpha.ICompleteQueryRequest, - callback: Callback< - protos.google.cloud.retail.v2alpha.ICompleteQueryResponse, - protos.google.cloud.retail.v2alpha.ICompleteQueryRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.ICompleteQueryRequest, + callback: Callback< + protos.google.cloud.retail.v2alpha.ICompleteQueryResponse, + | protos.google.cloud.retail.v2alpha.ICompleteQueryRequest + | null + | undefined, + {} | null | undefined + >, + ): void; completeQuery( - request?: protos.google.cloud.retail.v2alpha.ICompleteQueryRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.cloud.retail.v2alpha.ICompleteQueryRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.retail.v2alpha.ICompleteQueryResponse, - protos.google.cloud.retail.v2alpha.ICompleteQueryRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.cloud.retail.v2alpha.ICompleteQueryResponse, - protos.google.cloud.retail.v2alpha.ICompleteQueryRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.retail.v2alpha.ICompleteQueryResponse, - protos.google.cloud.retail.v2alpha.ICompleteQueryRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.retail.v2alpha.ICompleteQueryRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.retail.v2alpha.ICompleteQueryResponse, + | protos.google.cloud.retail.v2alpha.ICompleteQueryRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.ICompleteQueryResponse, + protos.google.cloud.retail.v2alpha.ICompleteQueryRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'catalog': request.catalog ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + catalog: request.catalog ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('completeQuery request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.retail.v2alpha.ICompleteQueryResponse, - protos.google.cloud.retail.v2alpha.ICompleteQueryRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.retail.v2alpha.ICompleteQueryResponse, + | protos.google.cloud.retail.v2alpha.ICompleteQueryRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('completeQuery response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.completeQuery(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.retail.v2alpha.ICompleteQueryResponse, - protos.google.cloud.retail.v2alpha.ICompleteQueryRequest|undefined, {}|undefined - ]) => { - this._log.info('completeQuery response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .completeQuery(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.retail.v2alpha.ICompleteQueryResponse, + protos.google.cloud.retail.v2alpha.ICompleteQueryRequest | undefined, + {} | undefined, + ]) => { + this._log.info('completeQuery response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Bulk import of processed completion dataset. - * - * Request processing is asynchronous. Partial updating is not supported. - * - * The operation is successfully finished only after the imported suggestions - * are indexed successfully and ready for serving. The process takes hours. - * - * This feature is only available for users who have Retail Search enabled. - * Enable Retail Search on Cloud Console before using this feature. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The catalog which the suggestions dataset belongs to. - * - * Format: `projects/1234/locations/global/catalogs/default_catalog`. - * @param {google.cloud.retail.v2alpha.CompletionDataInputConfig} request.inputConfig - * Required. The desired input location of the data. - * @param {string} request.notificationPubsubTopic - * Pub/Sub topic for receiving notification. If this field is set, - * when the import is finished, a notification is sent to - * specified Pub/Sub topic. The message data is JSON string of a - * {@link protos.google.longrunning.Operation|Operation}. - * Format of the Pub/Sub topic is `projects/{project}/topics/{topic}`. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing - * a long running operation. Its `promise()` method returns a promise - * you can `await` for. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/completion_service.import_completion_data.js - * region_tag:retail_v2alpha_generated_CompletionService_ImportCompletionData_async - */ + /** + * Bulk import of processed completion dataset. + * + * Request processing is asynchronous. Partial updating is not supported. + * + * The operation is successfully finished only after the imported suggestions + * are indexed successfully and ready for serving. The process takes hours. + * + * This feature is only available for users who have Retail Search enabled. + * Enable Retail Search on Cloud Console before using this feature. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The catalog which the suggestions dataset belongs to. + * + * Format: `projects/1234/locations/global/catalogs/default_catalog`. + * @param {google.cloud.retail.v2alpha.CompletionDataInputConfig} request.inputConfig + * Required. The desired input location of the data. + * @param {string} request.notificationPubsubTopic + * Pub/Sub topic for receiving notification. If this field is set, + * when the import is finished, a notification is sent to + * specified Pub/Sub topic. The message data is JSON string of a + * {@link protos.google.longrunning.Operation|Operation}. + * Format of the Pub/Sub topic is `projects/{project}/topics/{topic}`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/completion_service.import_completion_data.js + * region_tag:retail_v2alpha_generated_CompletionService_ImportCompletionData_async + */ importCompletionData( - request?: protos.google.cloud.retail.v2alpha.IImportCompletionDataRequest, - options?: CallOptions): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.IImportCompletionDataRequest, + options?: CallOptions, + ): Promise< + [ + LROperation< + protos.google.cloud.retail.v2alpha.IImportCompletionDataResponse, + protos.google.cloud.retail.v2alpha.IImportMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; importCompletionData( - request: protos.google.cloud.retail.v2alpha.IImportCompletionDataRequest, - options: CallOptions, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IImportCompletionDataRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IImportCompletionDataResponse, + protos.google.cloud.retail.v2alpha.IImportMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; importCompletionData( - request: protos.google.cloud.retail.v2alpha.IImportCompletionDataRequest, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IImportCompletionDataRequest, + callback: Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IImportCompletionDataResponse, + protos.google.cloud.retail.v2alpha.IImportMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; importCompletionData( - request?: protos.google.cloud.retail.v2alpha.IImportCompletionDataRequest, - optionsOrCallback?: CallOptions|Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>, - callback?: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>|void { + request?: protos.google.cloud.retail.v2alpha.IImportCompletionDataRequest, + optionsOrCallback?: + | CallOptions + | Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IImportCompletionDataResponse, + protos.google.cloud.retail.v2alpha.IImportMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + callback?: Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IImportCompletionDataResponse, + protos.google.cloud.retail.v2alpha.IImportMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + LROperation< + protos.google.cloud.retail.v2alpha.IImportCompletionDataResponse, + protos.google.cloud.retail.v2alpha.IImportMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IImportCompletionDataResponse, + protos.google.cloud.retail.v2alpha.IImportMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, rawResponse, _) => { this._log.info('importCompletionData response %j', rawResponse); callback!(error, response, rawResponse, _); // We verified `callback` above. } : undefined; this._log.info('importCompletionData request %j', request); - return this.innerApiCalls.importCompletionData(request, options, wrappedCallback) - ?.then(([response, rawResponse, _]: [ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]) => { - this._log.info('importCompletionData response %j', rawResponse); - return [response, rawResponse, _]; - }); + return this.innerApiCalls + .importCompletionData(request, options, wrappedCallback) + ?.then( + ([response, rawResponse, _]: [ + LROperation< + protos.google.cloud.retail.v2alpha.IImportCompletionDataResponse, + protos.google.cloud.retail.v2alpha.IImportMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ]) => { + this._log.info('importCompletionData response %j', rawResponse); + return [response, rawResponse, _]; + }, + ); } -/** - * Check the status of the long running operation returned by `importCompletionData()`. - * @param {String} name - * The operation name that will be passed. - * @returns {Promise} - The promise which resolves to an object. - * The decoded operation object has result and metadata field to get information from. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/completion_service.import_completion_data.js - * region_tag:retail_v2alpha_generated_CompletionService_ImportCompletionData_async - */ - async checkImportCompletionDataProgress(name: string): Promise>{ + /** + * Check the status of the long running operation returned by `importCompletionData()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/completion_service.import_completion_data.js + * region_tag:retail_v2alpha_generated_CompletionService_ImportCompletionData_async + */ + async checkImportCompletionDataProgress( + name: string, + ): Promise< + LROperation< + protos.google.cloud.retail.v2alpha.ImportCompletionDataResponse, + protos.google.cloud.retail.v2alpha.ImportMetadata + > + > { this._log.info('importCompletionData long-running'); - const request = new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest({name}); + const request = + new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( + { name }, + ); const [operation] = await this.operationsClient.getOperation(request); - const decodeOperation = new this._gaxModule.Operation(operation, this.descriptors.longrunning.importCompletionData, this._gaxModule.createDefaultBackoffSettings()); - return decodeOperation as LROperation; + const decodeOperation = new this._gaxModule.Operation( + operation, + this.descriptors.longrunning.importCompletionData, + this._gaxModule.createDefaultBackoffSettings(), + ); + return decodeOperation as LROperation< + protos.google.cloud.retail.v2alpha.ImportCompletionDataResponse, + protos.google.cloud.retail.v2alpha.ImportMetadata + >; } // -------------------- // -- Path templates -- @@ -721,7 +897,7 @@ export class CompletionServiceClient { * @param {string} project * @returns {string} Resource name string. */ - alertConfigPath(project:string) { + alertConfigPath(project: string) { return this.pathTemplates.alertConfigPathTemplate.render({ project: project, }); @@ -735,7 +911,8 @@ export class CompletionServiceClient { * @returns {string} A string representing the project. */ matchProjectFromAlertConfigName(alertConfigName: string) { - return this.pathTemplates.alertConfigPathTemplate.match(alertConfigName).project; + return this.pathTemplates.alertConfigPathTemplate.match(alertConfigName) + .project; } /** @@ -746,7 +923,7 @@ export class CompletionServiceClient { * @param {string} catalog * @returns {string} Resource name string. */ - attributesConfigPath(project:string,location:string,catalog:string) { + attributesConfigPath(project: string, location: string, catalog: string) { return this.pathTemplates.attributesConfigPathTemplate.render({ project: project, location: location, @@ -762,7 +939,9 @@ export class CompletionServiceClient { * @returns {string} A string representing the project. */ matchProjectFromAttributesConfigName(attributesConfigName: string) { - return this.pathTemplates.attributesConfigPathTemplate.match(attributesConfigName).project; + return this.pathTemplates.attributesConfigPathTemplate.match( + attributesConfigName, + ).project; } /** @@ -773,7 +952,9 @@ export class CompletionServiceClient { * @returns {string} A string representing the location. */ matchLocationFromAttributesConfigName(attributesConfigName: string) { - return this.pathTemplates.attributesConfigPathTemplate.match(attributesConfigName).location; + return this.pathTemplates.attributesConfigPathTemplate.match( + attributesConfigName, + ).location; } /** @@ -784,7 +965,9 @@ export class CompletionServiceClient { * @returns {string} A string representing the catalog. */ matchCatalogFromAttributesConfigName(attributesConfigName: string) { - return this.pathTemplates.attributesConfigPathTemplate.match(attributesConfigName).catalog; + return this.pathTemplates.attributesConfigPathTemplate.match( + attributesConfigName, + ).catalog; } /** @@ -796,7 +979,12 @@ export class CompletionServiceClient { * @param {string} branch * @returns {string} Resource name string. */ - branchPath(project:string,location:string,catalog:string,branch:string) { + branchPath( + project: string, + location: string, + catalog: string, + branch: string, + ) { return this.pathTemplates.branchPathTemplate.render({ project: project, location: location, @@ -857,7 +1045,7 @@ export class CompletionServiceClient { * @param {string} catalog * @returns {string} Resource name string. */ - catalogPath(project:string,location:string,catalog:string) { + catalogPath(project: string, location: string, catalog: string) { return this.pathTemplates.catalogPathTemplate.render({ project: project, location: location, @@ -906,7 +1094,7 @@ export class CompletionServiceClient { * @param {string} catalog * @returns {string} Resource name string. */ - completionConfigPath(project:string,location:string,catalog:string) { + completionConfigPath(project: string, location: string, catalog: string) { return this.pathTemplates.completionConfigPathTemplate.render({ project: project, location: location, @@ -922,7 +1110,9 @@ export class CompletionServiceClient { * @returns {string} A string representing the project. */ matchProjectFromCompletionConfigName(completionConfigName: string) { - return this.pathTemplates.completionConfigPathTemplate.match(completionConfigName).project; + return this.pathTemplates.completionConfigPathTemplate.match( + completionConfigName, + ).project; } /** @@ -933,7 +1123,9 @@ export class CompletionServiceClient { * @returns {string} A string representing the location. */ matchLocationFromCompletionConfigName(completionConfigName: string) { - return this.pathTemplates.completionConfigPathTemplate.match(completionConfigName).location; + return this.pathTemplates.completionConfigPathTemplate.match( + completionConfigName, + ).location; } /** @@ -944,7 +1136,9 @@ export class CompletionServiceClient { * @returns {string} A string representing the catalog. */ matchCatalogFromCompletionConfigName(completionConfigName: string) { - return this.pathTemplates.completionConfigPathTemplate.match(completionConfigName).catalog; + return this.pathTemplates.completionConfigPathTemplate.match( + completionConfigName, + ).catalog; } /** @@ -956,7 +1150,12 @@ export class CompletionServiceClient { * @param {string} control * @returns {string} Resource name string. */ - controlPath(project:string,location:string,catalog:string,control:string) { + controlPath( + project: string, + location: string, + catalog: string, + control: string, + ) { return this.pathTemplates.controlPathTemplate.render({ project: project, location: location, @@ -1015,7 +1214,7 @@ export class CompletionServiceClient { * @param {string} project * @returns {string} Resource name string. */ - loggingConfigPath(project:string) { + loggingConfigPath(project: string) { return this.pathTemplates.loggingConfigPathTemplate.render({ project: project, }); @@ -1029,7 +1228,8 @@ export class CompletionServiceClient { * @returns {string} A string representing the project. */ matchProjectFromLoggingConfigName(loggingConfigName: string) { - return this.pathTemplates.loggingConfigPathTemplate.match(loggingConfigName).project; + return this.pathTemplates.loggingConfigPathTemplate.match(loggingConfigName) + .project; } /** @@ -1041,7 +1241,12 @@ export class CompletionServiceClient { * @param {string} merchant_center_account_link * @returns {string} Resource name string. */ - merchantCenterAccountLinkPath(project:string,location:string,catalog:string,merchantCenterAccountLink:string) { + merchantCenterAccountLinkPath( + project: string, + location: string, + catalog: string, + merchantCenterAccountLink: string, + ) { return this.pathTemplates.merchantCenterAccountLinkPathTemplate.render({ project: project, location: location, @@ -1057,8 +1262,12 @@ export class CompletionServiceClient { * A fully-qualified path representing MerchantCenterAccountLink resource. * @returns {string} A string representing the project. */ - matchProjectFromMerchantCenterAccountLinkName(merchantCenterAccountLinkName: string) { - return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match(merchantCenterAccountLinkName).project; + matchProjectFromMerchantCenterAccountLinkName( + merchantCenterAccountLinkName: string, + ) { + return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match( + merchantCenterAccountLinkName, + ).project; } /** @@ -1068,8 +1277,12 @@ export class CompletionServiceClient { * A fully-qualified path representing MerchantCenterAccountLink resource. * @returns {string} A string representing the location. */ - matchLocationFromMerchantCenterAccountLinkName(merchantCenterAccountLinkName: string) { - return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match(merchantCenterAccountLinkName).location; + matchLocationFromMerchantCenterAccountLinkName( + merchantCenterAccountLinkName: string, + ) { + return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match( + merchantCenterAccountLinkName, + ).location; } /** @@ -1079,8 +1292,12 @@ export class CompletionServiceClient { * A fully-qualified path representing MerchantCenterAccountLink resource. * @returns {string} A string representing the catalog. */ - matchCatalogFromMerchantCenterAccountLinkName(merchantCenterAccountLinkName: string) { - return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match(merchantCenterAccountLinkName).catalog; + matchCatalogFromMerchantCenterAccountLinkName( + merchantCenterAccountLinkName: string, + ) { + return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match( + merchantCenterAccountLinkName, + ).catalog; } /** @@ -1090,8 +1307,12 @@ export class CompletionServiceClient { * A fully-qualified path representing MerchantCenterAccountLink resource. * @returns {string} A string representing the merchant_center_account_link. */ - matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName(merchantCenterAccountLinkName: string) { - return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match(merchantCenterAccountLinkName).merchant_center_account_link; + matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName( + merchantCenterAccountLinkName: string, + ) { + return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match( + merchantCenterAccountLinkName, + ).merchant_center_account_link; } /** @@ -1103,7 +1324,7 @@ export class CompletionServiceClient { * @param {string} model * @returns {string} Resource name string. */ - modelPath(project:string,location:string,catalog:string,model:string) { + modelPath(project: string, location: string, catalog: string, model: string) { return this.pathTemplates.modelPathTemplate.render({ project: project, location: location, @@ -1166,7 +1387,13 @@ export class CompletionServiceClient { * @param {string} product * @returns {string} Resource name string. */ - productPath(project:string,location:string,catalog:string,branch:string,product:string) { + productPath( + project: string, + location: string, + catalog: string, + branch: string, + product: string, + ) { return this.pathTemplates.productPathTemplate.render({ project: project, location: location, @@ -1237,7 +1464,7 @@ export class CompletionServiceClient { * @param {string} project * @returns {string} Resource name string. */ - retailProjectPath(project:string) { + retailProjectPath(project: string) { return this.pathTemplates.retailProjectPathTemplate.render({ project: project, }); @@ -1251,7 +1478,8 @@ export class CompletionServiceClient { * @returns {string} A string representing the project. */ matchProjectFromRetailProjectName(retailProjectName: string) { - return this.pathTemplates.retailProjectPathTemplate.match(retailProjectName).project; + return this.pathTemplates.retailProjectPathTemplate.match(retailProjectName) + .project; } /** @@ -1263,7 +1491,12 @@ export class CompletionServiceClient { * @param {string} serving_config * @returns {string} Resource name string. */ - servingConfigPath(project:string,location:string,catalog:string,servingConfig:string) { + servingConfigPath( + project: string, + location: string, + catalog: string, + servingConfig: string, + ) { return this.pathTemplates.servingConfigPathTemplate.render({ project: project, location: location, @@ -1280,7 +1513,8 @@ export class CompletionServiceClient { * @returns {string} A string representing the project. */ matchProjectFromServingConfigName(servingConfigName: string) { - return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName).project; + return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName) + .project; } /** @@ -1291,7 +1525,8 @@ export class CompletionServiceClient { * @returns {string} A string representing the location. */ matchLocationFromServingConfigName(servingConfigName: string) { - return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName).location; + return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName) + .location; } /** @@ -1302,7 +1537,8 @@ export class CompletionServiceClient { * @returns {string} A string representing the catalog. */ matchCatalogFromServingConfigName(servingConfigName: string) { - return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName).catalog; + return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName) + .catalog; } /** @@ -1313,7 +1549,8 @@ export class CompletionServiceClient { * @returns {string} A string representing the serving_config. */ matchServingConfigFromServingConfigName(servingConfigName: string) { - return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName).serving_config; + return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName) + .serving_config; } /** @@ -1324,7 +1561,7 @@ export class CompletionServiceClient { */ close(): Promise { if (this.completionServiceStub && !this._terminated) { - return this.completionServiceStub.then(stub => { + return this.completionServiceStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -1333,4 +1570,4 @@ export class CompletionServiceClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/src/v2alpha/control_service_client.ts.baseline b/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/src/v2alpha/control_service_client.ts.baseline index d84c175f4916..bde54a4a0908 100644 --- a/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/src/v2alpha/control_service_client.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/src/v2alpha/control_service_client.ts.baseline @@ -18,15 +18,22 @@ /* global window */ import * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions, PaginationCallback, GaxCall} from 'google-gax'; -import {Transform} from 'stream'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + PaginationCallback, + GaxCall, +} from 'google-gax'; +import { Transform } from 'stream'; // @ts-ignore import type * as protos from '../../../protos/protos.js'; import * as control_service_client_config from './control_service_client_config.json'; import fs from 'fs'; import path from 'path'; -import {fileURLToPath} from 'url'; -import {getJSON} from '../json-helper.cjs'; +import { fileURLToPath } from 'url'; +import { getJSON } from '../json-helper.cjs'; // @ts-ignore const dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -36,15 +43,15 @@ const dirname = path.dirname(fileURLToPath(import.meta.url)); * This file defines retry strategy and timeouts for all API methods in this library. */ const gapicConfig = getJSON( - path.join(dirname, 'control_service_client_config.json') + path.join(dirname, 'control_service_client_config.json'), ); const jsonProtos = getJSON( - path.join(dirname, '..', '..', '..', 'protos/protos.json') + path.join(dirname, '..', '..', '..', 'protos/protos.json'), ); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; const version = getJSON( - path.join(dirname, '..', '..', '..', '..', 'package.json') + path.join(dirname, '..', '..', '..', '..', 'package.json'), ).version; /** @@ -59,7 +66,7 @@ export class ControlServiceClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('retail'); @@ -71,9 +78,9 @@ export class ControlServiceClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; - controlServiceStub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; + controlServiceStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of ControlServiceClient. @@ -115,21 +122,42 @@ export class ControlServiceClient { * const client = new ControlServiceClient({fallback: 'rest'}, gax); * ``` */ - constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { // Ensure that options include all the required fields. const staticMembers = this.constructor as typeof ControlServiceClient; - if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { - throw new Error('Please set either universe_domain or universeDomain, but not both.'); + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); } - const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; - this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; this._servicePath = 'retail.' + this._universeDomain; - const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; - const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. if (servicePath !== this._servicePath && !('scopes' in opts)) { @@ -151,7 +179,7 @@ export class ControlServiceClient { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; @@ -168,10 +196,7 @@ export class ControlServiceClient { const isEsm = true; const isEsmString = isEsm ? '-esm' : '-cjs'; // Determine the client header string. - const clientHeader = [ - `gax/${this._gaxModule.version}`, - `gapic/${version}`, - ]; + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/{process.versions.node}${isEsmString}`); } else { @@ -179,7 +204,7 @@ export class ControlServiceClient { } if (!opts.fallback) { clientHeader.push(`grpc/${this._gaxGrpc.grpcVersion}`); - } else if (opts.fallback === 'rest' ) { + } else if (opts.fallback === 'rest') { clientHeader.push(`rest/${this._gaxGrpc.grpcVersion}`); } if (opts.libName && opts.libVersion) { @@ -187,47 +212,49 @@ export class ControlServiceClient { } // Load the applicable protos. - this._protos = this._gaxGrpc.loadProtoJSON(jsonProtos as gax.protobuf.INamespace); + this._protos = this._gaxGrpc.loadProtoJSON( + jsonProtos as gax.protobuf.INamespace, + ); // This API contains "path templates"; forward-slash-separated // identifiers to uniquely identify resources within the API. // Create useful helper objects for these. this.pathTemplates = { alertConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/alertConfig' + 'projects/{project}/alertConfig', ), attributesConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/attributesConfig' + 'projects/{project}/locations/{location}/catalogs/{catalog}/attributesConfig', ), branchPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}', ), catalogPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}' + 'projects/{project}/locations/{location}/catalogs/{catalog}', ), completionConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/completionConfig' + 'projects/{project}/locations/{location}/catalogs/{catalog}/completionConfig', ), controlPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/controls/{control}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/controls/{control}', ), loggingConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/loggingConfig' + 'projects/{project}/loggingConfig', ), merchantCenterAccountLinkPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/merchantCenterAccountLinks/{merchant_center_account_link}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/merchantCenterAccountLinks/{merchant_center_account_link}', ), modelPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/models/{model}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/models/{model}', ), productPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}', ), retailProjectPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/retailProject' + 'projects/{project}/retailProject', ), servingConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/servingConfigs/{serving_config}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/servingConfigs/{serving_config}', ), }; @@ -235,14 +262,20 @@ export class ControlServiceClient { // (e.g. 50 results at a time, with tokens to get subsequent // pages). Denote the keys used for pagination and results. this.descriptors.page = { - listControls: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'controls') + listControls: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'controls', + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.cloud.retail.v2alpha.ControlService', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.cloud.retail.v2alpha.ControlService', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + { 'x-goog-api-client': clientHeader.join(' ') }, + ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -273,37 +306,46 @@ export class ControlServiceClient { // Put together the "service stub" for // google.cloud.retail.v2alpha.ControlService. this.controlServiceStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.cloud.retail.v2alpha.ControlService') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.cloud.retail.v2alpha.ControlService', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.cloud.retail.v2alpha.ControlService, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts, + this._providedCustomServicePath, + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const controlServiceStubMethods = - ['createControl', 'deleteControl', 'updateControl', 'getControl', 'listControls']; + const controlServiceStubMethods = [ + 'createControl', + 'deleteControl', + 'updateControl', + 'getControl', + 'listControls', + ]; for (const methodName of controlServiceStubMethods) { const callPromise = this.controlServiceStub.then( - stub => (...args: Array<{}>) => { - if (this._terminated) { - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error|null|undefined) => () => { + (stub) => + (...args: Array<{}>) => { + if (this._terminated) { + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { throw err; - }); + }, + ); - const descriptor = - this.descriptors.page[methodName] || - undefined; + const descriptor = this.descriptors.page[methodName] || undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -318,8 +360,14 @@ export class ControlServiceClient { * @returns {string} The DNS address for this service. */ static get servicePath() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'retail.googleapis.com'; } @@ -331,8 +379,14 @@ export class ControlServiceClient { * @returns {string} The DNS address for this service. */ static get apiEndpoint() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'retail.googleapis.com'; } @@ -363,9 +417,7 @@ export class ControlServiceClient { * @returns {string[]} List of default scopes. */ static get scopes() { - return [ - 'https://www.googleapis.com/auth/cloud-platform' - ]; + return ['https://www.googleapis.com/auth/cloud-platform']; } getProjectId(): Promise; @@ -374,8 +426,9 @@ export class ControlServiceClient { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId(callback?: Callback): - Promise|void { + getProjectId( + callback?: Callback, + ): Promise | void { if (callback) { this.auth.getProjectId(callback); return; @@ -386,501 +439,684 @@ export class ControlServiceClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Creates a Control. - * - * If the {@link protos.google.cloud.retail.v2alpha.Control|Control} to create already - * exists, an ALREADY_EXISTS error is returned. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. Full resource name of parent catalog. Format: - * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}` - * @param {google.cloud.retail.v2alpha.Control} request.control - * Required. The Control to create. - * @param {string} request.controlId - * Required. The ID to use for the Control, which will become the final - * component of the Control's resource name. - * - * This value should be 4-63 characters, and valid characters - * are /{@link protos.0-9|a-z}-_/. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.Control|Control}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/control_service.create_control.js - * region_tag:retail_v2alpha_generated_ControlService_CreateControl_async - */ + /** + * Creates a Control. + * + * If the {@link protos.google.cloud.retail.v2alpha.Control|Control} to create already + * exists, an ALREADY_EXISTS error is returned. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Full resource name of parent catalog. Format: + * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}` + * @param {google.cloud.retail.v2alpha.Control} request.control + * Required. The Control to create. + * @param {string} request.controlId + * Required. The ID to use for the Control, which will become the final + * component of the Control's resource name. + * + * This value should be 4-63 characters, and valid characters + * are /{@link protos.0-9|a-z}-_/. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.Control|Control}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/control_service.create_control.js + * region_tag:retail_v2alpha_generated_ControlService_CreateControl_async + */ createControl( - request?: protos.google.cloud.retail.v2alpha.ICreateControlRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.retail.v2alpha.IControl, - protos.google.cloud.retail.v2alpha.ICreateControlRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.ICreateControlRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IControl, + protos.google.cloud.retail.v2alpha.ICreateControlRequest | undefined, + {} | undefined, + ] + >; createControl( - request: protos.google.cloud.retail.v2alpha.ICreateControlRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.retail.v2alpha.IControl, - protos.google.cloud.retail.v2alpha.ICreateControlRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.ICreateControlRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.retail.v2alpha.IControl, + | protos.google.cloud.retail.v2alpha.ICreateControlRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createControl( - request: protos.google.cloud.retail.v2alpha.ICreateControlRequest, - callback: Callback< - protos.google.cloud.retail.v2alpha.IControl, - protos.google.cloud.retail.v2alpha.ICreateControlRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.ICreateControlRequest, + callback: Callback< + protos.google.cloud.retail.v2alpha.IControl, + | protos.google.cloud.retail.v2alpha.ICreateControlRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createControl( - request?: protos.google.cloud.retail.v2alpha.ICreateControlRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.retail.v2alpha.IControl, - protos.google.cloud.retail.v2alpha.ICreateControlRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.retail.v2alpha.ICreateControlRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.retail.v2alpha.IControl, - protos.google.cloud.retail.v2alpha.ICreateControlRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.retail.v2alpha.IControl, - protos.google.cloud.retail.v2alpha.ICreateControlRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.retail.v2alpha.ICreateControlRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.retail.v2alpha.IControl, + | protos.google.cloud.retail.v2alpha.ICreateControlRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IControl, + protos.google.cloud.retail.v2alpha.ICreateControlRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('createControl request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.retail.v2alpha.IControl, - protos.google.cloud.retail.v2alpha.ICreateControlRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.retail.v2alpha.IControl, + | protos.google.cloud.retail.v2alpha.ICreateControlRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createControl response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.createControl(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.retail.v2alpha.IControl, - protos.google.cloud.retail.v2alpha.ICreateControlRequest|undefined, {}|undefined - ]) => { - this._log.info('createControl response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createControl(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.retail.v2alpha.IControl, + protos.google.cloud.retail.v2alpha.ICreateControlRequest | undefined, + {} | undefined, + ]) => { + this._log.info('createControl response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Deletes a Control. - * - * If the {@link protos.google.cloud.retail.v2alpha.Control|Control} to delete does not - * exist, a NOT_FOUND error is returned. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The resource name of the Control to delete. Format: - * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/controls/{control_id}` - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/control_service.delete_control.js - * region_tag:retail_v2alpha_generated_ControlService_DeleteControl_async - */ + /** + * Deletes a Control. + * + * If the {@link protos.google.cloud.retail.v2alpha.Control|Control} to delete does not + * exist, a NOT_FOUND error is returned. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The resource name of the Control to delete. Format: + * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/controls/{control_id}` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/control_service.delete_control.js + * region_tag:retail_v2alpha_generated_ControlService_DeleteControl_async + */ deleteControl( - request?: protos.google.cloud.retail.v2alpha.IDeleteControlRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.cloud.retail.v2alpha.IDeleteControlRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.IDeleteControlRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.cloud.retail.v2alpha.IDeleteControlRequest | undefined, + {} | undefined, + ] + >; deleteControl( - request: protos.google.cloud.retail.v2alpha.IDeleteControlRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.cloud.retail.v2alpha.IDeleteControlRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IDeleteControlRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.cloud.retail.v2alpha.IDeleteControlRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteControl( - request: protos.google.cloud.retail.v2alpha.IDeleteControlRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.cloud.retail.v2alpha.IDeleteControlRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IDeleteControlRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.cloud.retail.v2alpha.IDeleteControlRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteControl( - request?: protos.google.cloud.retail.v2alpha.IDeleteControlRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.protobuf.IEmpty, - protos.google.cloud.retail.v2alpha.IDeleteControlRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.retail.v2alpha.IDeleteControlRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.cloud.retail.v2alpha.IDeleteControlRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.cloud.retail.v2alpha.IDeleteControlRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.retail.v2alpha.IDeleteControlRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + | protos.google.cloud.retail.v2alpha.IDeleteControlRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.cloud.retail.v2alpha.IDeleteControlRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('deleteControl request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.cloud.retail.v2alpha.IDeleteControlRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.cloud.retail.v2alpha.IDeleteControlRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteControl response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.deleteControl(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.cloud.retail.v2alpha.IDeleteControlRequest|undefined, {}|undefined - ]) => { - this._log.info('deleteControl response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteControl(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.cloud.retail.v2alpha.IDeleteControlRequest | undefined, + {} | undefined, + ]) => { + this._log.info('deleteControl response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Updates a Control. - * - * {@link protos.google.cloud.retail.v2alpha.Control|Control} cannot be set to a different - * oneof field, if so an INVALID_ARGUMENT is returned. If the - * {@link protos.google.cloud.retail.v2alpha.Control|Control} to update does not exist, a - * NOT_FOUND error is returned. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.cloud.retail.v2alpha.Control} request.control - * Required. The Control to update. - * @param {google.protobuf.FieldMask} request.updateMask - * Indicates which fields in the provided - * {@link protos.google.cloud.retail.v2alpha.Control|Control} to update. The following are - * NOT supported: - * - * * {@link protos.google.cloud.retail.v2alpha.Control.name|Control.name} - * - * If not set or empty, all supported fields are updated. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.Control|Control}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/control_service.update_control.js - * region_tag:retail_v2alpha_generated_ControlService_UpdateControl_async - */ + /** + * Updates a Control. + * + * {@link protos.google.cloud.retail.v2alpha.Control|Control} cannot be set to a different + * oneof field, if so an INVALID_ARGUMENT is returned. If the + * {@link protos.google.cloud.retail.v2alpha.Control|Control} to update does not exist, a + * NOT_FOUND error is returned. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.cloud.retail.v2alpha.Control} request.control + * Required. The Control to update. + * @param {google.protobuf.FieldMask} request.updateMask + * Indicates which fields in the provided + * {@link protos.google.cloud.retail.v2alpha.Control|Control} to update. The following are + * NOT supported: + * + * * {@link protos.google.cloud.retail.v2alpha.Control.name|Control.name} + * + * If not set or empty, all supported fields are updated. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.Control|Control}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/control_service.update_control.js + * region_tag:retail_v2alpha_generated_ControlService_UpdateControl_async + */ updateControl( - request?: protos.google.cloud.retail.v2alpha.IUpdateControlRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.retail.v2alpha.IControl, - protos.google.cloud.retail.v2alpha.IUpdateControlRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.IUpdateControlRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IControl, + protos.google.cloud.retail.v2alpha.IUpdateControlRequest | undefined, + {} | undefined, + ] + >; updateControl( - request: protos.google.cloud.retail.v2alpha.IUpdateControlRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.retail.v2alpha.IControl, - protos.google.cloud.retail.v2alpha.IUpdateControlRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IUpdateControlRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.retail.v2alpha.IControl, + | protos.google.cloud.retail.v2alpha.IUpdateControlRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateControl( - request: protos.google.cloud.retail.v2alpha.IUpdateControlRequest, - callback: Callback< - protos.google.cloud.retail.v2alpha.IControl, - protos.google.cloud.retail.v2alpha.IUpdateControlRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IUpdateControlRequest, + callback: Callback< + protos.google.cloud.retail.v2alpha.IControl, + | protos.google.cloud.retail.v2alpha.IUpdateControlRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateControl( - request?: protos.google.cloud.retail.v2alpha.IUpdateControlRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.retail.v2alpha.IControl, - protos.google.cloud.retail.v2alpha.IUpdateControlRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.retail.v2alpha.IUpdateControlRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.retail.v2alpha.IControl, - protos.google.cloud.retail.v2alpha.IUpdateControlRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.retail.v2alpha.IControl, - protos.google.cloud.retail.v2alpha.IUpdateControlRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.retail.v2alpha.IUpdateControlRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.retail.v2alpha.IControl, + | protos.google.cloud.retail.v2alpha.IUpdateControlRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IControl, + protos.google.cloud.retail.v2alpha.IUpdateControlRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'control.name': request.control!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'control.name': request.control!.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateControl request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.retail.v2alpha.IControl, - protos.google.cloud.retail.v2alpha.IUpdateControlRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.retail.v2alpha.IControl, + | protos.google.cloud.retail.v2alpha.IUpdateControlRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateControl response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.updateControl(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.retail.v2alpha.IControl, - protos.google.cloud.retail.v2alpha.IUpdateControlRequest|undefined, {}|undefined - ]) => { - this._log.info('updateControl response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateControl(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.retail.v2alpha.IControl, + protos.google.cloud.retail.v2alpha.IUpdateControlRequest | undefined, + {} | undefined, + ]) => { + this._log.info('updateControl response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Gets a Control. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The resource name of the Control to get. Format: - * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/controls/{control_id}` - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.Control|Control}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/control_service.get_control.js - * region_tag:retail_v2alpha_generated_ControlService_GetControl_async - */ + /** + * Gets a Control. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The resource name of the Control to get. Format: + * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/controls/{control_id}` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.Control|Control}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/control_service.get_control.js + * region_tag:retail_v2alpha_generated_ControlService_GetControl_async + */ getControl( - request?: protos.google.cloud.retail.v2alpha.IGetControlRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.retail.v2alpha.IControl, - protos.google.cloud.retail.v2alpha.IGetControlRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.IGetControlRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IControl, + protos.google.cloud.retail.v2alpha.IGetControlRequest | undefined, + {} | undefined, + ] + >; getControl( - request: protos.google.cloud.retail.v2alpha.IGetControlRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.retail.v2alpha.IControl, - protos.google.cloud.retail.v2alpha.IGetControlRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IGetControlRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.retail.v2alpha.IControl, + protos.google.cloud.retail.v2alpha.IGetControlRequest | null | undefined, + {} | null | undefined + >, + ): void; getControl( - request: protos.google.cloud.retail.v2alpha.IGetControlRequest, - callback: Callback< - protos.google.cloud.retail.v2alpha.IControl, - protos.google.cloud.retail.v2alpha.IGetControlRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IGetControlRequest, + callback: Callback< + protos.google.cloud.retail.v2alpha.IControl, + protos.google.cloud.retail.v2alpha.IGetControlRequest | null | undefined, + {} | null | undefined + >, + ): void; getControl( - request?: protos.google.cloud.retail.v2alpha.IGetControlRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.retail.v2alpha.IControl, - protos.google.cloud.retail.v2alpha.IGetControlRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.retail.v2alpha.IGetControlRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.retail.v2alpha.IControl, - protos.google.cloud.retail.v2alpha.IGetControlRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.retail.v2alpha.IControl, - protos.google.cloud.retail.v2alpha.IGetControlRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.retail.v2alpha.IGetControlRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.retail.v2alpha.IControl, + protos.google.cloud.retail.v2alpha.IGetControlRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IControl, + protos.google.cloud.retail.v2alpha.IGetControlRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getControl request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.retail.v2alpha.IControl, - protos.google.cloud.retail.v2alpha.IGetControlRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.retail.v2alpha.IControl, + | protos.google.cloud.retail.v2alpha.IGetControlRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getControl response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.getControl(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.retail.v2alpha.IControl, - protos.google.cloud.retail.v2alpha.IGetControlRequest|undefined, {}|undefined - ]) => { - this._log.info('getControl response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getControl(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.retail.v2alpha.IControl, + protos.google.cloud.retail.v2alpha.IGetControlRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getControl response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } - /** - * Lists all Controls by their parent - * {@link protos.google.cloud.retail.v2alpha.Catalog|Catalog}. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The catalog resource name. Format: - * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}` - * @param {number} [request.pageSize] - * Optional. Maximum number of results to return. If unspecified, defaults - * to 50. Max allowed value is 1000. - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous `ListControls` call. - * Provide this to retrieve the subsequent page. - * @param {string} [request.filter] - * Optional. A filter to apply on the list results. Supported features: - * - * * List all the products under the parent branch if - * {@link protos.google.cloud.retail.v2alpha.ListControlsRequest.filter|filter} is unset. - * * List controls that are used in a single ServingConfig: - * 'serving_config = "boosted_home_page_cvr"' - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.cloud.retail.v2alpha.Control|Control}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `listControlsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Lists all Controls by their parent + * {@link protos.google.cloud.retail.v2alpha.Catalog|Catalog}. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The catalog resource name. Format: + * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}` + * @param {number} [request.pageSize] + * Optional. Maximum number of results to return. If unspecified, defaults + * to 50. Max allowed value is 1000. + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListControls` call. + * Provide this to retrieve the subsequent page. + * @param {string} [request.filter] + * Optional. A filter to apply on the list results. Supported features: + * + * * List all the products under the parent branch if + * {@link protos.google.cloud.retail.v2alpha.ListControlsRequest.filter|filter} is unset. + * * List controls that are used in a single ServingConfig: + * 'serving_config = "boosted_home_page_cvr"' + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.cloud.retail.v2alpha.Control|Control}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listControlsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listControls( - request?: protos.google.cloud.retail.v2alpha.IListControlsRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.retail.v2alpha.IControl[], - protos.google.cloud.retail.v2alpha.IListControlsRequest|null, - protos.google.cloud.retail.v2alpha.IListControlsResponse - ]>; + request?: protos.google.cloud.retail.v2alpha.IListControlsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IControl[], + protos.google.cloud.retail.v2alpha.IListControlsRequest | null, + protos.google.cloud.retail.v2alpha.IListControlsResponse, + ] + >; listControls( - request: protos.google.cloud.retail.v2alpha.IListControlsRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.cloud.retail.v2alpha.IListControlsRequest, - protos.google.cloud.retail.v2alpha.IListControlsResponse|null|undefined, - protos.google.cloud.retail.v2alpha.IControl>): void; + request: protos.google.cloud.retail.v2alpha.IListControlsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.cloud.retail.v2alpha.IListControlsRequest, + | protos.google.cloud.retail.v2alpha.IListControlsResponse + | null + | undefined, + protos.google.cloud.retail.v2alpha.IControl + >, + ): void; listControls( - request: protos.google.cloud.retail.v2alpha.IListControlsRequest, - callback: PaginationCallback< - protos.google.cloud.retail.v2alpha.IListControlsRequest, - protos.google.cloud.retail.v2alpha.IListControlsResponse|null|undefined, - protos.google.cloud.retail.v2alpha.IControl>): void; + request: protos.google.cloud.retail.v2alpha.IListControlsRequest, + callback: PaginationCallback< + protos.google.cloud.retail.v2alpha.IListControlsRequest, + | protos.google.cloud.retail.v2alpha.IListControlsResponse + | null + | undefined, + protos.google.cloud.retail.v2alpha.IControl + >, + ): void; listControls( - request?: protos.google.cloud.retail.v2alpha.IListControlsRequest, - optionsOrCallback?: CallOptions|PaginationCallback< + request?: protos.google.cloud.retail.v2alpha.IListControlsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.cloud.retail.v2alpha.IListControlsRequest, - protos.google.cloud.retail.v2alpha.IListControlsResponse|null|undefined, - protos.google.cloud.retail.v2alpha.IControl>, - callback?: PaginationCallback< - protos.google.cloud.retail.v2alpha.IListControlsRequest, - protos.google.cloud.retail.v2alpha.IListControlsResponse|null|undefined, - protos.google.cloud.retail.v2alpha.IControl>): - Promise<[ - protos.google.cloud.retail.v2alpha.IControl[], - protos.google.cloud.retail.v2alpha.IListControlsRequest|null, - protos.google.cloud.retail.v2alpha.IListControlsResponse - ]>|void { + | protos.google.cloud.retail.v2alpha.IListControlsResponse + | null + | undefined, + protos.google.cloud.retail.v2alpha.IControl + >, + callback?: PaginationCallback< + protos.google.cloud.retail.v2alpha.IListControlsRequest, + | protos.google.cloud.retail.v2alpha.IListControlsResponse + | null + | undefined, + protos.google.cloud.retail.v2alpha.IControl + >, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IControl[], + protos.google.cloud.retail.v2alpha.IListControlsRequest | null, + protos.google.cloud.retail.v2alpha.IListControlsResponse, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.cloud.retail.v2alpha.IListControlsRequest, - protos.google.cloud.retail.v2alpha.IListControlsResponse|null|undefined, - protos.google.cloud.retail.v2alpha.IControl>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.cloud.retail.v2alpha.IListControlsRequest, + | protos.google.cloud.retail.v2alpha.IListControlsResponse + | null + | undefined, + protos.google.cloud.retail.v2alpha.IControl + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listControls values %j', values); callback!(error, values, nextPageRequest, rawResponse); @@ -889,126 +1125,130 @@ export class ControlServiceClient { this._log.info('listControls request %j', request); return this.innerApiCalls .listControls(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.cloud.retail.v2alpha.IControl[], - protos.google.cloud.retail.v2alpha.IListControlsRequest|null, - protos.google.cloud.retail.v2alpha.IListControlsResponse - ]) => { - this._log.info('listControls values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.cloud.retail.v2alpha.IControl[], + protos.google.cloud.retail.v2alpha.IListControlsRequest | null, + protos.google.cloud.retail.v2alpha.IListControlsResponse, + ]) => { + this._log.info('listControls values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listControls`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The catalog resource name. Format: - * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}` - * @param {number} [request.pageSize] - * Optional. Maximum number of results to return. If unspecified, defaults - * to 50. Max allowed value is 1000. - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous `ListControls` call. - * Provide this to retrieve the subsequent page. - * @param {string} [request.filter] - * Optional. A filter to apply on the list results. Supported features: - * - * * List all the products under the parent branch if - * {@link protos.google.cloud.retail.v2alpha.ListControlsRequest.filter|filter} is unset. - * * List controls that are used in a single ServingConfig: - * 'serving_config = "boosted_home_page_cvr"' - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.cloud.retail.v2alpha.Control|Control} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `listControlsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `listControls`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The catalog resource name. Format: + * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}` + * @param {number} [request.pageSize] + * Optional. Maximum number of results to return. If unspecified, defaults + * to 50. Max allowed value is 1000. + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListControls` call. + * Provide this to retrieve the subsequent page. + * @param {string} [request.filter] + * Optional. A filter to apply on the list results. Supported features: + * + * * List all the products under the parent branch if + * {@link protos.google.cloud.retail.v2alpha.ListControlsRequest.filter|filter} is unset. + * * List controls that are used in a single ServingConfig: + * 'serving_config = "boosted_home_page_cvr"' + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.cloud.retail.v2alpha.Control|Control} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listControlsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listControlsStream( - request?: protos.google.cloud.retail.v2alpha.IListControlsRequest, - options?: CallOptions): - Transform{ + request?: protos.google.cloud.retail.v2alpha.IListControlsRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); const defaultCallSettings = this._defaults['listControls']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listControls stream %j', request); return this.descriptors.page.listControls.createStream( this.innerApiCalls.listControls as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listControls`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The catalog resource name. Format: - * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}` - * @param {number} [request.pageSize] - * Optional. Maximum number of results to return. If unspecified, defaults - * to 50. Max allowed value is 1000. - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous `ListControls` call. - * Provide this to retrieve the subsequent page. - * @param {string} [request.filter] - * Optional. A filter to apply on the list results. Supported features: - * - * * List all the products under the parent branch if - * {@link protos.google.cloud.retail.v2alpha.ListControlsRequest.filter|filter} is unset. - * * List controls that are used in a single ServingConfig: - * 'serving_config = "boosted_home_page_cvr"' - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.cloud.retail.v2alpha.Control|Control}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/control_service.list_controls.js - * region_tag:retail_v2alpha_generated_ControlService_ListControls_async - */ + /** + * Equivalent to `listControls`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The catalog resource name. Format: + * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}` + * @param {number} [request.pageSize] + * Optional. Maximum number of results to return. If unspecified, defaults + * to 50. Max allowed value is 1000. + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListControls` call. + * Provide this to retrieve the subsequent page. + * @param {string} [request.filter] + * Optional. A filter to apply on the list results. Supported features: + * + * * List all the products under the parent branch if + * {@link protos.google.cloud.retail.v2alpha.ListControlsRequest.filter|filter} is unset. + * * List controls that are used in a single ServingConfig: + * 'serving_config = "boosted_home_page_cvr"' + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.cloud.retail.v2alpha.Control|Control}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/control_service.list_controls.js + * region_tag:retail_v2alpha_generated_ControlService_ListControls_async + */ listControlsAsync( - request?: protos.google.cloud.retail.v2alpha.IListControlsRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.cloud.retail.v2alpha.IListControlsRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); const defaultCallSettings = this._defaults['listControls']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listControls iterate %j', request); return this.descriptors.page.listControls.asyncIterate( this.innerApiCalls['listControls'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } // -------------------- @@ -1021,7 +1261,7 @@ export class ControlServiceClient { * @param {string} project * @returns {string} Resource name string. */ - alertConfigPath(project:string) { + alertConfigPath(project: string) { return this.pathTemplates.alertConfigPathTemplate.render({ project: project, }); @@ -1035,7 +1275,8 @@ export class ControlServiceClient { * @returns {string} A string representing the project. */ matchProjectFromAlertConfigName(alertConfigName: string) { - return this.pathTemplates.alertConfigPathTemplate.match(alertConfigName).project; + return this.pathTemplates.alertConfigPathTemplate.match(alertConfigName) + .project; } /** @@ -1046,7 +1287,7 @@ export class ControlServiceClient { * @param {string} catalog * @returns {string} Resource name string. */ - attributesConfigPath(project:string,location:string,catalog:string) { + attributesConfigPath(project: string, location: string, catalog: string) { return this.pathTemplates.attributesConfigPathTemplate.render({ project: project, location: location, @@ -1062,7 +1303,9 @@ export class ControlServiceClient { * @returns {string} A string representing the project. */ matchProjectFromAttributesConfigName(attributesConfigName: string) { - return this.pathTemplates.attributesConfigPathTemplate.match(attributesConfigName).project; + return this.pathTemplates.attributesConfigPathTemplate.match( + attributesConfigName, + ).project; } /** @@ -1073,7 +1316,9 @@ export class ControlServiceClient { * @returns {string} A string representing the location. */ matchLocationFromAttributesConfigName(attributesConfigName: string) { - return this.pathTemplates.attributesConfigPathTemplate.match(attributesConfigName).location; + return this.pathTemplates.attributesConfigPathTemplate.match( + attributesConfigName, + ).location; } /** @@ -1084,7 +1329,9 @@ export class ControlServiceClient { * @returns {string} A string representing the catalog. */ matchCatalogFromAttributesConfigName(attributesConfigName: string) { - return this.pathTemplates.attributesConfigPathTemplate.match(attributesConfigName).catalog; + return this.pathTemplates.attributesConfigPathTemplate.match( + attributesConfigName, + ).catalog; } /** @@ -1096,7 +1343,12 @@ export class ControlServiceClient { * @param {string} branch * @returns {string} Resource name string. */ - branchPath(project:string,location:string,catalog:string,branch:string) { + branchPath( + project: string, + location: string, + catalog: string, + branch: string, + ) { return this.pathTemplates.branchPathTemplate.render({ project: project, location: location, @@ -1157,7 +1409,7 @@ export class ControlServiceClient { * @param {string} catalog * @returns {string} Resource name string. */ - catalogPath(project:string,location:string,catalog:string) { + catalogPath(project: string, location: string, catalog: string) { return this.pathTemplates.catalogPathTemplate.render({ project: project, location: location, @@ -1206,7 +1458,7 @@ export class ControlServiceClient { * @param {string} catalog * @returns {string} Resource name string. */ - completionConfigPath(project:string,location:string,catalog:string) { + completionConfigPath(project: string, location: string, catalog: string) { return this.pathTemplates.completionConfigPathTemplate.render({ project: project, location: location, @@ -1222,7 +1474,9 @@ export class ControlServiceClient { * @returns {string} A string representing the project. */ matchProjectFromCompletionConfigName(completionConfigName: string) { - return this.pathTemplates.completionConfigPathTemplate.match(completionConfigName).project; + return this.pathTemplates.completionConfigPathTemplate.match( + completionConfigName, + ).project; } /** @@ -1233,7 +1487,9 @@ export class ControlServiceClient { * @returns {string} A string representing the location. */ matchLocationFromCompletionConfigName(completionConfigName: string) { - return this.pathTemplates.completionConfigPathTemplate.match(completionConfigName).location; + return this.pathTemplates.completionConfigPathTemplate.match( + completionConfigName, + ).location; } /** @@ -1244,7 +1500,9 @@ export class ControlServiceClient { * @returns {string} A string representing the catalog. */ matchCatalogFromCompletionConfigName(completionConfigName: string) { - return this.pathTemplates.completionConfigPathTemplate.match(completionConfigName).catalog; + return this.pathTemplates.completionConfigPathTemplate.match( + completionConfigName, + ).catalog; } /** @@ -1256,7 +1514,12 @@ export class ControlServiceClient { * @param {string} control * @returns {string} Resource name string. */ - controlPath(project:string,location:string,catalog:string,control:string) { + controlPath( + project: string, + location: string, + catalog: string, + control: string, + ) { return this.pathTemplates.controlPathTemplate.render({ project: project, location: location, @@ -1315,7 +1578,7 @@ export class ControlServiceClient { * @param {string} project * @returns {string} Resource name string. */ - loggingConfigPath(project:string) { + loggingConfigPath(project: string) { return this.pathTemplates.loggingConfigPathTemplate.render({ project: project, }); @@ -1329,7 +1592,8 @@ export class ControlServiceClient { * @returns {string} A string representing the project. */ matchProjectFromLoggingConfigName(loggingConfigName: string) { - return this.pathTemplates.loggingConfigPathTemplate.match(loggingConfigName).project; + return this.pathTemplates.loggingConfigPathTemplate.match(loggingConfigName) + .project; } /** @@ -1341,7 +1605,12 @@ export class ControlServiceClient { * @param {string} merchant_center_account_link * @returns {string} Resource name string. */ - merchantCenterAccountLinkPath(project:string,location:string,catalog:string,merchantCenterAccountLink:string) { + merchantCenterAccountLinkPath( + project: string, + location: string, + catalog: string, + merchantCenterAccountLink: string, + ) { return this.pathTemplates.merchantCenterAccountLinkPathTemplate.render({ project: project, location: location, @@ -1357,8 +1626,12 @@ export class ControlServiceClient { * A fully-qualified path representing MerchantCenterAccountLink resource. * @returns {string} A string representing the project. */ - matchProjectFromMerchantCenterAccountLinkName(merchantCenterAccountLinkName: string) { - return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match(merchantCenterAccountLinkName).project; + matchProjectFromMerchantCenterAccountLinkName( + merchantCenterAccountLinkName: string, + ) { + return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match( + merchantCenterAccountLinkName, + ).project; } /** @@ -1368,8 +1641,12 @@ export class ControlServiceClient { * A fully-qualified path representing MerchantCenterAccountLink resource. * @returns {string} A string representing the location. */ - matchLocationFromMerchantCenterAccountLinkName(merchantCenterAccountLinkName: string) { - return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match(merchantCenterAccountLinkName).location; + matchLocationFromMerchantCenterAccountLinkName( + merchantCenterAccountLinkName: string, + ) { + return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match( + merchantCenterAccountLinkName, + ).location; } /** @@ -1379,8 +1656,12 @@ export class ControlServiceClient { * A fully-qualified path representing MerchantCenterAccountLink resource. * @returns {string} A string representing the catalog. */ - matchCatalogFromMerchantCenterAccountLinkName(merchantCenterAccountLinkName: string) { - return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match(merchantCenterAccountLinkName).catalog; + matchCatalogFromMerchantCenterAccountLinkName( + merchantCenterAccountLinkName: string, + ) { + return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match( + merchantCenterAccountLinkName, + ).catalog; } /** @@ -1390,8 +1671,12 @@ export class ControlServiceClient { * A fully-qualified path representing MerchantCenterAccountLink resource. * @returns {string} A string representing the merchant_center_account_link. */ - matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName(merchantCenterAccountLinkName: string) { - return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match(merchantCenterAccountLinkName).merchant_center_account_link; + matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName( + merchantCenterAccountLinkName: string, + ) { + return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match( + merchantCenterAccountLinkName, + ).merchant_center_account_link; } /** @@ -1403,7 +1688,7 @@ export class ControlServiceClient { * @param {string} model * @returns {string} Resource name string. */ - modelPath(project:string,location:string,catalog:string,model:string) { + modelPath(project: string, location: string, catalog: string, model: string) { return this.pathTemplates.modelPathTemplate.render({ project: project, location: location, @@ -1466,7 +1751,13 @@ export class ControlServiceClient { * @param {string} product * @returns {string} Resource name string. */ - productPath(project:string,location:string,catalog:string,branch:string,product:string) { + productPath( + project: string, + location: string, + catalog: string, + branch: string, + product: string, + ) { return this.pathTemplates.productPathTemplate.render({ project: project, location: location, @@ -1537,7 +1828,7 @@ export class ControlServiceClient { * @param {string} project * @returns {string} Resource name string. */ - retailProjectPath(project:string) { + retailProjectPath(project: string) { return this.pathTemplates.retailProjectPathTemplate.render({ project: project, }); @@ -1551,7 +1842,8 @@ export class ControlServiceClient { * @returns {string} A string representing the project. */ matchProjectFromRetailProjectName(retailProjectName: string) { - return this.pathTemplates.retailProjectPathTemplate.match(retailProjectName).project; + return this.pathTemplates.retailProjectPathTemplate.match(retailProjectName) + .project; } /** @@ -1563,7 +1855,12 @@ export class ControlServiceClient { * @param {string} serving_config * @returns {string} Resource name string. */ - servingConfigPath(project:string,location:string,catalog:string,servingConfig:string) { + servingConfigPath( + project: string, + location: string, + catalog: string, + servingConfig: string, + ) { return this.pathTemplates.servingConfigPathTemplate.render({ project: project, location: location, @@ -1580,7 +1877,8 @@ export class ControlServiceClient { * @returns {string} A string representing the project. */ matchProjectFromServingConfigName(servingConfigName: string) { - return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName).project; + return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName) + .project; } /** @@ -1591,7 +1889,8 @@ export class ControlServiceClient { * @returns {string} A string representing the location. */ matchLocationFromServingConfigName(servingConfigName: string) { - return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName).location; + return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName) + .location; } /** @@ -1602,7 +1901,8 @@ export class ControlServiceClient { * @returns {string} A string representing the catalog. */ matchCatalogFromServingConfigName(servingConfigName: string) { - return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName).catalog; + return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName) + .catalog; } /** @@ -1613,7 +1913,8 @@ export class ControlServiceClient { * @returns {string} A string representing the serving_config. */ matchServingConfigFromServingConfigName(servingConfigName: string) { - return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName).serving_config; + return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName) + .serving_config; } /** @@ -1624,7 +1925,7 @@ export class ControlServiceClient { */ close(): Promise { if (this.controlServiceStub && !this._terminated) { - return this.controlServiceStub.then(stub => { + return this.controlServiceStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -1632,4 +1933,4 @@ export class ControlServiceClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/src/v2alpha/conversational_search_service_client.ts.baseline b/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/src/v2alpha/conversational_search_service_client.ts.baseline index 88820210e6f8..fac8f6705f12 100644 --- a/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/src/v2alpha/conversational_search_service_client.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/src/v2alpha/conversational_search_service_client.ts.baseline @@ -18,15 +18,20 @@ /* global window */ import * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions} from 'google-gax'; -import {PassThrough} from 'stream'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, +} from 'google-gax'; +import { PassThrough } from 'stream'; // @ts-ignore import type * as protos from '../../../protos/protos.js'; import * as conversational_search_service_client_config from './conversational_search_service_client_config.json'; import fs from 'fs'; import path from 'path'; -import {fileURLToPath} from 'url'; -import {getJSON} from '../json-helper.cjs'; +import { fileURLToPath } from 'url'; +import { getJSON } from '../json-helper.cjs'; // @ts-ignore const dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -36,15 +41,15 @@ const dirname = path.dirname(fileURLToPath(import.meta.url)); * This file defines retry strategy and timeouts for all API methods in this library. */ const gapicConfig = getJSON( - path.join(dirname, 'conversational_search_service_client_config.json') + path.join(dirname, 'conversational_search_service_client_config.json'), ); const jsonProtos = getJSON( - path.join(dirname, '..', '..', '..', 'protos/protos.json') + path.join(dirname, '..', '..', '..', 'protos/protos.json'), ); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; const version = getJSON( - path.join(dirname, '..', '..', '..', '..', 'package.json') + path.join(dirname, '..', '..', '..', '..', 'package.json'), ).version; /** @@ -63,7 +68,7 @@ export class ConversationalSearchServiceClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('retail'); @@ -75,9 +80,9 @@ export class ConversationalSearchServiceClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; - conversationalSearchServiceStub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; + conversationalSearchServiceStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of ConversationalSearchServiceClient. @@ -119,21 +124,43 @@ export class ConversationalSearchServiceClient { * const client = new ConversationalSearchServiceClient({fallback: 'rest'}, gax); * ``` */ - constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { // Ensure that options include all the required fields. - const staticMembers = this.constructor as typeof ConversationalSearchServiceClient; - if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { - throw new Error('Please set either universe_domain or universeDomain, but not both.'); + const staticMembers = this + .constructor as typeof ConversationalSearchServiceClient; + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); } - const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; - this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; this._servicePath = 'retail.' + this._universeDomain; - const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; - const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. if (servicePath !== this._servicePath && !('scopes' in opts)) { @@ -155,7 +182,7 @@ export class ConversationalSearchServiceClient { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; @@ -172,10 +199,7 @@ export class ConversationalSearchServiceClient { const isEsm = true; const isEsmString = isEsm ? '-esm' : '-cjs'; // Determine the client header string. - const clientHeader = [ - `gax/${this._gaxModule.version}`, - `gapic/${version}`, - ]; + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/{process.versions.node}${isEsmString}`); } else { @@ -183,7 +207,7 @@ export class ConversationalSearchServiceClient { } if (!opts.fallback) { clientHeader.push(`grpc/${this._gaxGrpc.grpcVersion}`); - } else if (opts.fallback === 'rest' ) { + } else if (opts.fallback === 'rest') { clientHeader.push(`rest/${this._gaxGrpc.grpcVersion}`); } if (opts.libName && opts.libVersion) { @@ -191,60 +215,69 @@ export class ConversationalSearchServiceClient { } // Load the applicable protos. - this._protos = this._gaxGrpc.loadProtoJSON(jsonProtos as gax.protobuf.INamespace); + this._protos = this._gaxGrpc.loadProtoJSON( + jsonProtos as gax.protobuf.INamespace, + ); // This API contains "path templates"; forward-slash-separated // identifiers to uniquely identify resources within the API. // Create useful helper objects for these. this.pathTemplates = { alertConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/alertConfig' + 'projects/{project}/alertConfig', ), attributesConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/attributesConfig' + 'projects/{project}/locations/{location}/catalogs/{catalog}/attributesConfig', ), branchPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}', ), catalogPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}' + 'projects/{project}/locations/{location}/catalogs/{catalog}', ), completionConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/completionConfig' + 'projects/{project}/locations/{location}/catalogs/{catalog}/completionConfig', ), controlPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/controls/{control}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/controls/{control}', ), loggingConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/loggingConfig' + 'projects/{project}/loggingConfig', ), merchantCenterAccountLinkPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/merchantCenterAccountLinks/{merchant_center_account_link}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/merchantCenterAccountLinks/{merchant_center_account_link}', ), modelPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/models/{model}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/models/{model}', ), productPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}', ), retailProjectPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/retailProject' + 'projects/{project}/retailProject', ), servingConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/servingConfigs/{serving_config}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/servingConfigs/{serving_config}', ), }; // Some of the methods on this service provide streaming responses. // Provide descriptors for these. this.descriptors.stream = { - conversationalSearch: new this._gaxModule.StreamDescriptor(this._gaxModule.StreamType.SERVER_STREAMING, !!opts.fallback, !!opts.gaxServerStreamingRetries) + conversationalSearch: new this._gaxModule.StreamDescriptor( + this._gaxModule.StreamType.SERVER_STREAMING, + !!opts.fallback, + !!opts.gaxServerStreamingRetries, + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.cloud.retail.v2alpha.ConversationalSearchService', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.cloud.retail.v2alpha.ConversationalSearchService', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + { 'x-goog-api-client': clientHeader.join(' ') }, + ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -275,44 +308,53 @@ export class ConversationalSearchServiceClient { // Put together the "service stub" for // google.cloud.retail.v2alpha.ConversationalSearchService. this.conversationalSearchServiceStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.cloud.retail.v2alpha.ConversationalSearchService') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any - (this._protos as any).google.cloud.retail.v2alpha.ConversationalSearchService, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.cloud.retail.v2alpha.ConversationalSearchService', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any + (this._protos as any).google.cloud.retail.v2alpha + .ConversationalSearchService, + this._opts, + this._providedCustomServicePath, + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const conversationalSearchServiceStubMethods = - ['conversationalSearch']; + const conversationalSearchServiceStubMethods = ['conversationalSearch']; for (const methodName of conversationalSearchServiceStubMethods) { const callPromise = this.conversationalSearchServiceStub.then( - stub => (...args: Array<{}>) => { - if (this._terminated) { - if (methodName in this.descriptors.stream) { - const stream = new PassThrough({objectMode: true}); - setImmediate(() => { - stream.emit('error', new this._gaxModule.GoogleError('The client has already been closed.')); - }); - return stream; + (stub) => + (...args: Array<{}>) => { + if (this._terminated) { + if (methodName in this.descriptors.stream) { + const stream = new PassThrough({ objectMode: true }); + setImmediate(() => { + stream.emit( + 'error', + new this._gaxModule.GoogleError( + 'The client has already been closed.', + ), + ); + }); + return stream; + } + return Promise.reject('The client has already been closed.'); } - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error|null|undefined) => () => { + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { throw err; - }); + }, + ); - const descriptor = - this.descriptors.stream[methodName] || - undefined; + const descriptor = this.descriptors.stream[methodName] || undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -327,8 +369,14 @@ export class ConversationalSearchServiceClient { * @returns {string} The DNS address for this service. */ static get servicePath() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'retail.googleapis.com'; } @@ -340,8 +388,14 @@ export class ConversationalSearchServiceClient { * @returns {string} The DNS address for this service. */ static get apiEndpoint() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'retail.googleapis.com'; } @@ -372,9 +426,7 @@ export class ConversationalSearchServiceClient { * @returns {string[]} List of default scopes. */ static get scopes() { - return [ - 'https://www.googleapis.com/auth/cloud-platform' - ]; + return ['https://www.googleapis.com/auth/cloud-platform']; } getProjectId(): Promise; @@ -383,8 +435,9 @@ export class ConversationalSearchServiceClient { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId(callback?: Callback): - Promise|void { + getProjectId( + callback?: Callback, + ): Promise | void { if (callback) { this.auth.getProjectId(callback); return; @@ -396,92 +449,93 @@ export class ConversationalSearchServiceClient { // -- Service calls -- // ------------------- -/** - * Performs a conversational search. - * - * This feature is only available for users who have Conversational Search - * enabled. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.placement - * Required. The resource name of the search engine placement, such as - * `projects/* /locations/global/catalogs/default_catalog/placements/default_search` - * or - * `projects/* /locations/global/catalogs/default_catalog/servingConfigs/default_serving_config` - * This field is used to identify the serving config name and the set - * of models that will be used to make the search. - * @param {string} request.branch - * Required. The branch resource name, such as - * `projects/* /locations/global/catalogs/default_catalog/branches/0`. - * - * Use "default_branch" as the branch ID or leave this field empty, to search - * products under the default branch. - * @param {string} [request.query] - * Optional. Raw search query to be searched for. - * - * If this field is empty, the request is considered a category browsing - * request. - * @param {string[]} [request.pageCategories] - * Optional. The categories associated with a category page. Must be set for - * category navigation queries to achieve good search quality. The format - * should be the same as - * {@link protos.google.cloud.retail.v2alpha.UserEvent.page_categories|UserEvent.page_categories}; - * - * To represent full path of category, use '>' sign to separate different - * hierarchies. If '>' is part of the category name, replace it with - * other character(s). - * - * Category pages include special pages such as sales or promotions. For - * instance, a special sale page may have the category hierarchy: - * "pageCategories" : ["Sales > 2017 Black Friday Deals"]. - * @param {string} [request.conversationId] - * Optional. This field specifies the conversation id, which maintains the - * state of the conversation between client side and server side. Use the - * value from the previous - * {@link protos.google.cloud.retail.v2alpha.ConversationalSearchResponse.conversation_id|ConversationalSearchResponse.conversation_id}. - * For the initial request, this should be empty. - * @param {google.cloud.retail.v2alpha.ConversationalSearchRequest.SearchParams} [request.searchParams] - * Optional. Search parameters. - * @param {string} request.visitorId - * Required. A unique identifier for tracking visitors. For example, this - * could be implemented with an HTTP cookie, which should be able to uniquely - * identify a visitor on a single device. This unique identifier should not - * change if the visitor logs in or out of the website. - * - * This should be the same identifier as - * {@link protos.google.cloud.retail.v2alpha.UserEvent.visitor_id|UserEvent.visitor_id}. - * - * The field must be a UTF-8 encoded string with a length limit of 128 - * characters. Otherwise, an INVALID_ARGUMENT error is returned. - * @param {google.cloud.retail.v2alpha.UserInfo} [request.userInfo] - * Optional. User information. - * @param {google.cloud.retail.v2alpha.ConversationalSearchRequest.ConversationalFilteringSpec} [request.conversationalFilteringSpec] - * Optional. This field specifies all conversational filtering related - * parameters. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits {@link protos.google.cloud.retail.v2alpha.ConversationalSearchResponse|ConversationalSearchResponse} on 'data' event. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#server-streaming | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/conversational_search_service.conversational_search.js - * region_tag:retail_v2alpha_generated_ConversationalSearchService_ConversationalSearch_async - */ + /** + * Performs a conversational search. + * + * This feature is only available for users who have Conversational Search + * enabled. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.placement + * Required. The resource name of the search engine placement, such as + * `projects/* /locations/global/catalogs/default_catalog/placements/default_search` + * or + * `projects/* /locations/global/catalogs/default_catalog/servingConfigs/default_serving_config` + * This field is used to identify the serving config name and the set + * of models that will be used to make the search. + * @param {string} request.branch + * Required. The branch resource name, such as + * `projects/* /locations/global/catalogs/default_catalog/branches/0`. + * + * Use "default_branch" as the branch ID or leave this field empty, to search + * products under the default branch. + * @param {string} [request.query] + * Optional. Raw search query to be searched for. + * + * If this field is empty, the request is considered a category browsing + * request. + * @param {string[]} [request.pageCategories] + * Optional. The categories associated with a category page. Must be set for + * category navigation queries to achieve good search quality. The format + * should be the same as + * {@link protos.google.cloud.retail.v2alpha.UserEvent.page_categories|UserEvent.page_categories}; + * + * To represent full path of category, use '>' sign to separate different + * hierarchies. If '>' is part of the category name, replace it with + * other character(s). + * + * Category pages include special pages such as sales or promotions. For + * instance, a special sale page may have the category hierarchy: + * "pageCategories" : ["Sales > 2017 Black Friday Deals"]. + * @param {string} [request.conversationId] + * Optional. This field specifies the conversation id, which maintains the + * state of the conversation between client side and server side. Use the + * value from the previous + * {@link protos.google.cloud.retail.v2alpha.ConversationalSearchResponse.conversation_id|ConversationalSearchResponse.conversation_id}. + * For the initial request, this should be empty. + * @param {google.cloud.retail.v2alpha.ConversationalSearchRequest.SearchParams} [request.searchParams] + * Optional. Search parameters. + * @param {string} request.visitorId + * Required. A unique identifier for tracking visitors. For example, this + * could be implemented with an HTTP cookie, which should be able to uniquely + * identify a visitor on a single device. This unique identifier should not + * change if the visitor logs in or out of the website. + * + * This should be the same identifier as + * {@link protos.google.cloud.retail.v2alpha.UserEvent.visitor_id|UserEvent.visitor_id}. + * + * The field must be a UTF-8 encoded string with a length limit of 128 + * characters. Otherwise, an INVALID_ARGUMENT error is returned. + * @param {google.cloud.retail.v2alpha.UserInfo} [request.userInfo] + * Optional. User information. + * @param {google.cloud.retail.v2alpha.ConversationalSearchRequest.ConversationalFilteringSpec} [request.conversationalFilteringSpec] + * Optional. This field specifies all conversational filtering related + * parameters. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits {@link protos.google.cloud.retail.v2alpha.ConversationalSearchResponse|ConversationalSearchResponse} on 'data' event. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#server-streaming | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/conversational_search_service.conversational_search.js + * region_tag:retail_v2alpha_generated_ConversationalSearchService_ConversationalSearch_async + */ conversationalSearch( - request?: protos.google.cloud.retail.v2alpha.IConversationalSearchRequest, - options?: CallOptions): - gax.CancellableStream{ + request?: protos.google.cloud.retail.v2alpha.IConversationalSearchRequest, + options?: CallOptions, + ): gax.CancellableStream { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'placement': request.placement ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + placement: request.placement ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('conversationalSearch stream %j', options); return this.innerApiCalls.conversationalSearch(request, options); } @@ -496,7 +550,7 @@ export class ConversationalSearchServiceClient { * @param {string} project * @returns {string} Resource name string. */ - alertConfigPath(project:string) { + alertConfigPath(project: string) { return this.pathTemplates.alertConfigPathTemplate.render({ project: project, }); @@ -510,7 +564,8 @@ export class ConversationalSearchServiceClient { * @returns {string} A string representing the project. */ matchProjectFromAlertConfigName(alertConfigName: string) { - return this.pathTemplates.alertConfigPathTemplate.match(alertConfigName).project; + return this.pathTemplates.alertConfigPathTemplate.match(alertConfigName) + .project; } /** @@ -521,7 +576,7 @@ export class ConversationalSearchServiceClient { * @param {string} catalog * @returns {string} Resource name string. */ - attributesConfigPath(project:string,location:string,catalog:string) { + attributesConfigPath(project: string, location: string, catalog: string) { return this.pathTemplates.attributesConfigPathTemplate.render({ project: project, location: location, @@ -537,7 +592,9 @@ export class ConversationalSearchServiceClient { * @returns {string} A string representing the project. */ matchProjectFromAttributesConfigName(attributesConfigName: string) { - return this.pathTemplates.attributesConfigPathTemplate.match(attributesConfigName).project; + return this.pathTemplates.attributesConfigPathTemplate.match( + attributesConfigName, + ).project; } /** @@ -548,7 +605,9 @@ export class ConversationalSearchServiceClient { * @returns {string} A string representing the location. */ matchLocationFromAttributesConfigName(attributesConfigName: string) { - return this.pathTemplates.attributesConfigPathTemplate.match(attributesConfigName).location; + return this.pathTemplates.attributesConfigPathTemplate.match( + attributesConfigName, + ).location; } /** @@ -559,7 +618,9 @@ export class ConversationalSearchServiceClient { * @returns {string} A string representing the catalog. */ matchCatalogFromAttributesConfigName(attributesConfigName: string) { - return this.pathTemplates.attributesConfigPathTemplate.match(attributesConfigName).catalog; + return this.pathTemplates.attributesConfigPathTemplate.match( + attributesConfigName, + ).catalog; } /** @@ -571,7 +632,12 @@ export class ConversationalSearchServiceClient { * @param {string} branch * @returns {string} Resource name string. */ - branchPath(project:string,location:string,catalog:string,branch:string) { + branchPath( + project: string, + location: string, + catalog: string, + branch: string, + ) { return this.pathTemplates.branchPathTemplate.render({ project: project, location: location, @@ -632,7 +698,7 @@ export class ConversationalSearchServiceClient { * @param {string} catalog * @returns {string} Resource name string. */ - catalogPath(project:string,location:string,catalog:string) { + catalogPath(project: string, location: string, catalog: string) { return this.pathTemplates.catalogPathTemplate.render({ project: project, location: location, @@ -681,7 +747,7 @@ export class ConversationalSearchServiceClient { * @param {string} catalog * @returns {string} Resource name string. */ - completionConfigPath(project:string,location:string,catalog:string) { + completionConfigPath(project: string, location: string, catalog: string) { return this.pathTemplates.completionConfigPathTemplate.render({ project: project, location: location, @@ -697,7 +763,9 @@ export class ConversationalSearchServiceClient { * @returns {string} A string representing the project. */ matchProjectFromCompletionConfigName(completionConfigName: string) { - return this.pathTemplates.completionConfigPathTemplate.match(completionConfigName).project; + return this.pathTemplates.completionConfigPathTemplate.match( + completionConfigName, + ).project; } /** @@ -708,7 +776,9 @@ export class ConversationalSearchServiceClient { * @returns {string} A string representing the location. */ matchLocationFromCompletionConfigName(completionConfigName: string) { - return this.pathTemplates.completionConfigPathTemplate.match(completionConfigName).location; + return this.pathTemplates.completionConfigPathTemplate.match( + completionConfigName, + ).location; } /** @@ -719,7 +789,9 @@ export class ConversationalSearchServiceClient { * @returns {string} A string representing the catalog. */ matchCatalogFromCompletionConfigName(completionConfigName: string) { - return this.pathTemplates.completionConfigPathTemplate.match(completionConfigName).catalog; + return this.pathTemplates.completionConfigPathTemplate.match( + completionConfigName, + ).catalog; } /** @@ -731,7 +803,12 @@ export class ConversationalSearchServiceClient { * @param {string} control * @returns {string} Resource name string. */ - controlPath(project:string,location:string,catalog:string,control:string) { + controlPath( + project: string, + location: string, + catalog: string, + control: string, + ) { return this.pathTemplates.controlPathTemplate.render({ project: project, location: location, @@ -790,7 +867,7 @@ export class ConversationalSearchServiceClient { * @param {string} project * @returns {string} Resource name string. */ - loggingConfigPath(project:string) { + loggingConfigPath(project: string) { return this.pathTemplates.loggingConfigPathTemplate.render({ project: project, }); @@ -804,7 +881,8 @@ export class ConversationalSearchServiceClient { * @returns {string} A string representing the project. */ matchProjectFromLoggingConfigName(loggingConfigName: string) { - return this.pathTemplates.loggingConfigPathTemplate.match(loggingConfigName).project; + return this.pathTemplates.loggingConfigPathTemplate.match(loggingConfigName) + .project; } /** @@ -816,7 +894,12 @@ export class ConversationalSearchServiceClient { * @param {string} merchant_center_account_link * @returns {string} Resource name string. */ - merchantCenterAccountLinkPath(project:string,location:string,catalog:string,merchantCenterAccountLink:string) { + merchantCenterAccountLinkPath( + project: string, + location: string, + catalog: string, + merchantCenterAccountLink: string, + ) { return this.pathTemplates.merchantCenterAccountLinkPathTemplate.render({ project: project, location: location, @@ -832,8 +915,12 @@ export class ConversationalSearchServiceClient { * A fully-qualified path representing MerchantCenterAccountLink resource. * @returns {string} A string representing the project. */ - matchProjectFromMerchantCenterAccountLinkName(merchantCenterAccountLinkName: string) { - return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match(merchantCenterAccountLinkName).project; + matchProjectFromMerchantCenterAccountLinkName( + merchantCenterAccountLinkName: string, + ) { + return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match( + merchantCenterAccountLinkName, + ).project; } /** @@ -843,8 +930,12 @@ export class ConversationalSearchServiceClient { * A fully-qualified path representing MerchantCenterAccountLink resource. * @returns {string} A string representing the location. */ - matchLocationFromMerchantCenterAccountLinkName(merchantCenterAccountLinkName: string) { - return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match(merchantCenterAccountLinkName).location; + matchLocationFromMerchantCenterAccountLinkName( + merchantCenterAccountLinkName: string, + ) { + return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match( + merchantCenterAccountLinkName, + ).location; } /** @@ -854,8 +945,12 @@ export class ConversationalSearchServiceClient { * A fully-qualified path representing MerchantCenterAccountLink resource. * @returns {string} A string representing the catalog. */ - matchCatalogFromMerchantCenterAccountLinkName(merchantCenterAccountLinkName: string) { - return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match(merchantCenterAccountLinkName).catalog; + matchCatalogFromMerchantCenterAccountLinkName( + merchantCenterAccountLinkName: string, + ) { + return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match( + merchantCenterAccountLinkName, + ).catalog; } /** @@ -865,8 +960,12 @@ export class ConversationalSearchServiceClient { * A fully-qualified path representing MerchantCenterAccountLink resource. * @returns {string} A string representing the merchant_center_account_link. */ - matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName(merchantCenterAccountLinkName: string) { - return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match(merchantCenterAccountLinkName).merchant_center_account_link; + matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName( + merchantCenterAccountLinkName: string, + ) { + return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match( + merchantCenterAccountLinkName, + ).merchant_center_account_link; } /** @@ -878,7 +977,7 @@ export class ConversationalSearchServiceClient { * @param {string} model * @returns {string} Resource name string. */ - modelPath(project:string,location:string,catalog:string,model:string) { + modelPath(project: string, location: string, catalog: string, model: string) { return this.pathTemplates.modelPathTemplate.render({ project: project, location: location, @@ -941,7 +1040,13 @@ export class ConversationalSearchServiceClient { * @param {string} product * @returns {string} Resource name string. */ - productPath(project:string,location:string,catalog:string,branch:string,product:string) { + productPath( + project: string, + location: string, + catalog: string, + branch: string, + product: string, + ) { return this.pathTemplates.productPathTemplate.render({ project: project, location: location, @@ -1012,7 +1117,7 @@ export class ConversationalSearchServiceClient { * @param {string} project * @returns {string} Resource name string. */ - retailProjectPath(project:string) { + retailProjectPath(project: string) { return this.pathTemplates.retailProjectPathTemplate.render({ project: project, }); @@ -1026,7 +1131,8 @@ export class ConversationalSearchServiceClient { * @returns {string} A string representing the project. */ matchProjectFromRetailProjectName(retailProjectName: string) { - return this.pathTemplates.retailProjectPathTemplate.match(retailProjectName).project; + return this.pathTemplates.retailProjectPathTemplate.match(retailProjectName) + .project; } /** @@ -1038,7 +1144,12 @@ export class ConversationalSearchServiceClient { * @param {string} serving_config * @returns {string} Resource name string. */ - servingConfigPath(project:string,location:string,catalog:string,servingConfig:string) { + servingConfigPath( + project: string, + location: string, + catalog: string, + servingConfig: string, + ) { return this.pathTemplates.servingConfigPathTemplate.render({ project: project, location: location, @@ -1055,7 +1166,8 @@ export class ConversationalSearchServiceClient { * @returns {string} A string representing the project. */ matchProjectFromServingConfigName(servingConfigName: string) { - return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName).project; + return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName) + .project; } /** @@ -1066,7 +1178,8 @@ export class ConversationalSearchServiceClient { * @returns {string} A string representing the location. */ matchLocationFromServingConfigName(servingConfigName: string) { - return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName).location; + return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName) + .location; } /** @@ -1077,7 +1190,8 @@ export class ConversationalSearchServiceClient { * @returns {string} A string representing the catalog. */ matchCatalogFromServingConfigName(servingConfigName: string) { - return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName).catalog; + return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName) + .catalog; } /** @@ -1088,7 +1202,8 @@ export class ConversationalSearchServiceClient { * @returns {string} A string representing the serving_config. */ matchServingConfigFromServingConfigName(servingConfigName: string) { - return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName).serving_config; + return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName) + .serving_config; } /** @@ -1099,7 +1214,7 @@ export class ConversationalSearchServiceClient { */ close(): Promise { if (this.conversationalSearchServiceStub && !this._terminated) { - return this.conversationalSearchServiceStub.then(stub => { + return this.conversationalSearchServiceStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -1107,4 +1222,4 @@ export class ConversationalSearchServiceClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/src/v2alpha/generative_question_service_client.ts.baseline b/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/src/v2alpha/generative_question_service_client.ts.baseline index 3d6c782f1ea5..6fa0644a3cd4 100644 --- a/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/src/v2alpha/generative_question_service_client.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/src/v2alpha/generative_question_service_client.ts.baseline @@ -18,15 +18,20 @@ /* global window */ import * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions} from 'google-gax'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, +} from 'google-gax'; // @ts-ignore import type * as protos from '../../../protos/protos.js'; import * as generative_question_service_client_config from './generative_question_service_client_config.json'; import fs from 'fs'; import path from 'path'; -import {fileURLToPath} from 'url'; -import {getJSON} from '../json-helper.cjs'; +import { fileURLToPath } from 'url'; +import { getJSON } from '../json-helper.cjs'; // @ts-ignore const dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -36,15 +41,15 @@ const dirname = path.dirname(fileURLToPath(import.meta.url)); * This file defines retry strategy and timeouts for all API methods in this library. */ const gapicConfig = getJSON( - path.join(dirname, 'generative_question_service_client_config.json') + path.join(dirname, 'generative_question_service_client_config.json'), ); const jsonProtos = getJSON( - path.join(dirname, '..', '..', '..', 'protos/protos.json') + path.join(dirname, '..', '..', '..', 'protos/protos.json'), ); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; const version = getJSON( - path.join(dirname, '..', '..', '..', '..', 'package.json') + path.join(dirname, '..', '..', '..', '..', 'package.json'), ).version; /** @@ -59,7 +64,7 @@ export class GenerativeQuestionServiceClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('retail'); @@ -71,9 +76,9 @@ export class GenerativeQuestionServiceClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; - generativeQuestionServiceStub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; + generativeQuestionServiceStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of GenerativeQuestionServiceClient. @@ -115,21 +120,43 @@ export class GenerativeQuestionServiceClient { * const client = new GenerativeQuestionServiceClient({fallback: 'rest'}, gax); * ``` */ - constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { // Ensure that options include all the required fields. - const staticMembers = this.constructor as typeof GenerativeQuestionServiceClient; - if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { - throw new Error('Please set either universe_domain or universeDomain, but not both.'); + const staticMembers = this + .constructor as typeof GenerativeQuestionServiceClient; + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); } - const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; - this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; this._servicePath = 'retail.' + this._universeDomain; - const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; - const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. if (servicePath !== this._servicePath && !('scopes' in opts)) { @@ -151,7 +178,7 @@ export class GenerativeQuestionServiceClient { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; @@ -168,10 +195,7 @@ export class GenerativeQuestionServiceClient { const isEsm = true; const isEsmString = isEsm ? '-esm' : '-cjs'; // Determine the client header string. - const clientHeader = [ - `gax/${this._gaxModule.version}`, - `gapic/${version}`, - ]; + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/{process.versions.node}${isEsmString}`); } else { @@ -179,7 +203,7 @@ export class GenerativeQuestionServiceClient { } if (!opts.fallback) { clientHeader.push(`grpc/${this._gaxGrpc.grpcVersion}`); - } else if (opts.fallback === 'rest' ) { + } else if (opts.fallback === 'rest') { clientHeader.push(`rest/${this._gaxGrpc.grpcVersion}`); } if (opts.libName && opts.libVersion) { @@ -187,54 +211,59 @@ export class GenerativeQuestionServiceClient { } // Load the applicable protos. - this._protos = this._gaxGrpc.loadProtoJSON(jsonProtos as gax.protobuf.INamespace); + this._protos = this._gaxGrpc.loadProtoJSON( + jsonProtos as gax.protobuf.INamespace, + ); // This API contains "path templates"; forward-slash-separated // identifiers to uniquely identify resources within the API. // Create useful helper objects for these. this.pathTemplates = { alertConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/alertConfig' + 'projects/{project}/alertConfig', ), attributesConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/attributesConfig' + 'projects/{project}/locations/{location}/catalogs/{catalog}/attributesConfig', ), branchPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}', ), catalogPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}' + 'projects/{project}/locations/{location}/catalogs/{catalog}', ), completionConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/completionConfig' + 'projects/{project}/locations/{location}/catalogs/{catalog}/completionConfig', ), controlPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/controls/{control}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/controls/{control}', ), loggingConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/loggingConfig' + 'projects/{project}/loggingConfig', ), merchantCenterAccountLinkPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/merchantCenterAccountLinks/{merchant_center_account_link}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/merchantCenterAccountLinks/{merchant_center_account_link}', ), modelPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/models/{model}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/models/{model}', ), productPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}', ), retailProjectPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/retailProject' + 'projects/{project}/retailProject', ), servingConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/servingConfigs/{serving_config}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/servingConfigs/{serving_config}', ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.cloud.retail.v2alpha.GenerativeQuestionService', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.cloud.retail.v2alpha.GenerativeQuestionService', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + { 'x-goog-api-client': clientHeader.join(' ') }, + ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -265,36 +294,47 @@ export class GenerativeQuestionServiceClient { // Put together the "service stub" for // google.cloud.retail.v2alpha.GenerativeQuestionService. this.generativeQuestionServiceStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.cloud.retail.v2alpha.GenerativeQuestionService') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any - (this._protos as any).google.cloud.retail.v2alpha.GenerativeQuestionService, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.cloud.retail.v2alpha.GenerativeQuestionService', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any + (this._protos as any).google.cloud.retail.v2alpha + .GenerativeQuestionService, + this._opts, + this._providedCustomServicePath, + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const generativeQuestionServiceStubMethods = - ['updateGenerativeQuestionsFeatureConfig', 'getGenerativeQuestionsFeatureConfig', 'listGenerativeQuestionConfigs', 'updateGenerativeQuestionConfig', 'batchUpdateGenerativeQuestionConfigs']; + const generativeQuestionServiceStubMethods = [ + 'updateGenerativeQuestionsFeatureConfig', + 'getGenerativeQuestionsFeatureConfig', + 'listGenerativeQuestionConfigs', + 'updateGenerativeQuestionConfig', + 'batchUpdateGenerativeQuestionConfigs', + ]; for (const methodName of generativeQuestionServiceStubMethods) { const callPromise = this.generativeQuestionServiceStub.then( - stub => (...args: Array<{}>) => { - if (this._terminated) { - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error|null|undefined) => () => { + (stub) => + (...args: Array<{}>) => { + if (this._terminated) { + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { throw err; - }); + }, + ); - const descriptor = - undefined; + const descriptor = undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -309,8 +349,14 @@ export class GenerativeQuestionServiceClient { * @returns {string} The DNS address for this service. */ static get servicePath() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'retail.googleapis.com'; } @@ -322,8 +368,14 @@ export class GenerativeQuestionServiceClient { * @returns {string} The DNS address for this service. */ static get apiEndpoint() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'retail.googleapis.com'; } @@ -354,9 +406,7 @@ export class GenerativeQuestionServiceClient { * @returns {string[]} List of default scopes. */ static get scopes() { - return [ - 'https://www.googleapis.com/auth/cloud-platform' - ]; + return ['https://www.googleapis.com/auth/cloud-platform']; } getProjectId(): Promise; @@ -365,8 +415,9 @@ export class GenerativeQuestionServiceClient { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId(callback?: Callback): - Promise|void { + getProjectId( + callback?: Callback, + ): Promise | void { if (callback) { this.auth.getProjectId(callback); return; @@ -377,486 +428,765 @@ export class GenerativeQuestionServiceClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Manages overal generative question feature state -- enables toggling - * feature on and off. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.cloud.retail.v2alpha.GenerativeQuestionsFeatureConfig} request.generativeQuestionsFeatureConfig - * Required. The configuration managing the feature state. - * @param {google.protobuf.FieldMask} [request.updateMask] - * Optional. Indicates which fields in the provided - * {@link protos.google.cloud.retail.v2alpha.GenerativeQuestionsFeatureConfig|GenerativeQuestionsFeatureConfig} - * to update. If not set or empty, all supported fields are updated. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.GenerativeQuestionsFeatureConfig|GenerativeQuestionsFeatureConfig}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/generative_question_service.update_generative_questions_feature_config.js - * region_tag:retail_v2alpha_generated_GenerativeQuestionService_UpdateGenerativeQuestionsFeatureConfig_async - */ + /** + * Manages overal generative question feature state -- enables toggling + * feature on and off. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.cloud.retail.v2alpha.GenerativeQuestionsFeatureConfig} request.generativeQuestionsFeatureConfig + * Required. The configuration managing the feature state. + * @param {google.protobuf.FieldMask} [request.updateMask] + * Optional. Indicates which fields in the provided + * {@link protos.google.cloud.retail.v2alpha.GenerativeQuestionsFeatureConfig|GenerativeQuestionsFeatureConfig} + * to update. If not set or empty, all supported fields are updated. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.GenerativeQuestionsFeatureConfig|GenerativeQuestionsFeatureConfig}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/generative_question_service.update_generative_questions_feature_config.js + * region_tag:retail_v2alpha_generated_GenerativeQuestionService_UpdateGenerativeQuestionsFeatureConfig_async + */ updateGenerativeQuestionsFeatureConfig( - request?: protos.google.cloud.retail.v2alpha.IUpdateGenerativeQuestionsFeatureConfigRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.retail.v2alpha.IGenerativeQuestionsFeatureConfig, - protos.google.cloud.retail.v2alpha.IUpdateGenerativeQuestionsFeatureConfigRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.IUpdateGenerativeQuestionsFeatureConfigRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IGenerativeQuestionsFeatureConfig, + ( + | protos.google.cloud.retail.v2alpha.IUpdateGenerativeQuestionsFeatureConfigRequest + | undefined + ), + {} | undefined, + ] + >; updateGenerativeQuestionsFeatureConfig( - request: protos.google.cloud.retail.v2alpha.IUpdateGenerativeQuestionsFeatureConfigRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.retail.v2alpha.IGenerativeQuestionsFeatureConfig, - protos.google.cloud.retail.v2alpha.IUpdateGenerativeQuestionsFeatureConfigRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IUpdateGenerativeQuestionsFeatureConfigRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.retail.v2alpha.IGenerativeQuestionsFeatureConfig, + | protos.google.cloud.retail.v2alpha.IUpdateGenerativeQuestionsFeatureConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateGenerativeQuestionsFeatureConfig( - request: protos.google.cloud.retail.v2alpha.IUpdateGenerativeQuestionsFeatureConfigRequest, - callback: Callback< - protos.google.cloud.retail.v2alpha.IGenerativeQuestionsFeatureConfig, - protos.google.cloud.retail.v2alpha.IUpdateGenerativeQuestionsFeatureConfigRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IUpdateGenerativeQuestionsFeatureConfigRequest, + callback: Callback< + protos.google.cloud.retail.v2alpha.IGenerativeQuestionsFeatureConfig, + | protos.google.cloud.retail.v2alpha.IUpdateGenerativeQuestionsFeatureConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateGenerativeQuestionsFeatureConfig( - request?: protos.google.cloud.retail.v2alpha.IUpdateGenerativeQuestionsFeatureConfigRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.retail.v2alpha.IGenerativeQuestionsFeatureConfig, - protos.google.cloud.retail.v2alpha.IUpdateGenerativeQuestionsFeatureConfigRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.retail.v2alpha.IUpdateGenerativeQuestionsFeatureConfigRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.retail.v2alpha.IGenerativeQuestionsFeatureConfig, - protos.google.cloud.retail.v2alpha.IUpdateGenerativeQuestionsFeatureConfigRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.retail.v2alpha.IGenerativeQuestionsFeatureConfig, - protos.google.cloud.retail.v2alpha.IUpdateGenerativeQuestionsFeatureConfigRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.retail.v2alpha.IUpdateGenerativeQuestionsFeatureConfigRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.retail.v2alpha.IGenerativeQuestionsFeatureConfig, + | protos.google.cloud.retail.v2alpha.IUpdateGenerativeQuestionsFeatureConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IGenerativeQuestionsFeatureConfig, + ( + | protos.google.cloud.retail.v2alpha.IUpdateGenerativeQuestionsFeatureConfigRequest + | undefined + ), + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'generative_questions_feature_config.catalog': request.generativeQuestionsFeatureConfig!.catalog ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'generative_questions_feature_config.catalog': + request.generativeQuestionsFeatureConfig!.catalog ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - this._log.info('updateGenerativeQuestionsFeatureConfig request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.retail.v2alpha.IGenerativeQuestionsFeatureConfig, - protos.google.cloud.retail.v2alpha.IUpdateGenerativeQuestionsFeatureConfigRequest|null|undefined, - {}|null|undefined>|undefined = callback + this._log.info( + 'updateGenerativeQuestionsFeatureConfig request %j', + request, + ); + const wrappedCallback: + | Callback< + protos.google.cloud.retail.v2alpha.IGenerativeQuestionsFeatureConfig, + | protos.google.cloud.retail.v2alpha.IUpdateGenerativeQuestionsFeatureConfigRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { - this._log.info('updateGenerativeQuestionsFeatureConfig response %j', response); + this._log.info( + 'updateGenerativeQuestionsFeatureConfig response %j', + response, + ); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.updateGenerativeQuestionsFeatureConfig(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.retail.v2alpha.IGenerativeQuestionsFeatureConfig, - protos.google.cloud.retail.v2alpha.IUpdateGenerativeQuestionsFeatureConfigRequest|undefined, {}|undefined - ]) => { - this._log.info('updateGenerativeQuestionsFeatureConfig response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateGenerativeQuestionsFeatureConfig(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.retail.v2alpha.IGenerativeQuestionsFeatureConfig, + ( + | protos.google.cloud.retail.v2alpha.IUpdateGenerativeQuestionsFeatureConfigRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info( + 'updateGenerativeQuestionsFeatureConfig response %j', + response, + ); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Manages overal generative question feature state -- enables toggling - * feature on and off. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.catalog - * Required. Resource name of the parent catalog. - * Format: projects/{project}/locations/{location}/catalogs/{catalog} - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.GenerativeQuestionsFeatureConfig|GenerativeQuestionsFeatureConfig}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/generative_question_service.get_generative_questions_feature_config.js - * region_tag:retail_v2alpha_generated_GenerativeQuestionService_GetGenerativeQuestionsFeatureConfig_async - */ + /** + * Manages overal generative question feature state -- enables toggling + * feature on and off. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.catalog + * Required. Resource name of the parent catalog. + * Format: projects/{project}/locations/{location}/catalogs/{catalog} + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.GenerativeQuestionsFeatureConfig|GenerativeQuestionsFeatureConfig}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/generative_question_service.get_generative_questions_feature_config.js + * region_tag:retail_v2alpha_generated_GenerativeQuestionService_GetGenerativeQuestionsFeatureConfig_async + */ getGenerativeQuestionsFeatureConfig( - request?: protos.google.cloud.retail.v2alpha.IGetGenerativeQuestionsFeatureConfigRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.retail.v2alpha.IGenerativeQuestionsFeatureConfig, - protos.google.cloud.retail.v2alpha.IGetGenerativeQuestionsFeatureConfigRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.IGetGenerativeQuestionsFeatureConfigRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IGenerativeQuestionsFeatureConfig, + ( + | protos.google.cloud.retail.v2alpha.IGetGenerativeQuestionsFeatureConfigRequest + | undefined + ), + {} | undefined, + ] + >; getGenerativeQuestionsFeatureConfig( - request: protos.google.cloud.retail.v2alpha.IGetGenerativeQuestionsFeatureConfigRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.retail.v2alpha.IGenerativeQuestionsFeatureConfig, - protos.google.cloud.retail.v2alpha.IGetGenerativeQuestionsFeatureConfigRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IGetGenerativeQuestionsFeatureConfigRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.retail.v2alpha.IGenerativeQuestionsFeatureConfig, + | protos.google.cloud.retail.v2alpha.IGetGenerativeQuestionsFeatureConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getGenerativeQuestionsFeatureConfig( - request: protos.google.cloud.retail.v2alpha.IGetGenerativeQuestionsFeatureConfigRequest, - callback: Callback< - protos.google.cloud.retail.v2alpha.IGenerativeQuestionsFeatureConfig, - protos.google.cloud.retail.v2alpha.IGetGenerativeQuestionsFeatureConfigRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IGetGenerativeQuestionsFeatureConfigRequest, + callback: Callback< + protos.google.cloud.retail.v2alpha.IGenerativeQuestionsFeatureConfig, + | protos.google.cloud.retail.v2alpha.IGetGenerativeQuestionsFeatureConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getGenerativeQuestionsFeatureConfig( - request?: protos.google.cloud.retail.v2alpha.IGetGenerativeQuestionsFeatureConfigRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.retail.v2alpha.IGenerativeQuestionsFeatureConfig, - protos.google.cloud.retail.v2alpha.IGetGenerativeQuestionsFeatureConfigRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.retail.v2alpha.IGetGenerativeQuestionsFeatureConfigRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.retail.v2alpha.IGenerativeQuestionsFeatureConfig, - protos.google.cloud.retail.v2alpha.IGetGenerativeQuestionsFeatureConfigRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.retail.v2alpha.IGenerativeQuestionsFeatureConfig, - protos.google.cloud.retail.v2alpha.IGetGenerativeQuestionsFeatureConfigRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.retail.v2alpha.IGetGenerativeQuestionsFeatureConfigRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.retail.v2alpha.IGenerativeQuestionsFeatureConfig, + | protos.google.cloud.retail.v2alpha.IGetGenerativeQuestionsFeatureConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IGenerativeQuestionsFeatureConfig, + ( + | protos.google.cloud.retail.v2alpha.IGetGenerativeQuestionsFeatureConfigRequest + | undefined + ), + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'catalog': request.catalog ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + catalog: request.catalog ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getGenerativeQuestionsFeatureConfig request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.retail.v2alpha.IGenerativeQuestionsFeatureConfig, - protos.google.cloud.retail.v2alpha.IGetGenerativeQuestionsFeatureConfigRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.retail.v2alpha.IGenerativeQuestionsFeatureConfig, + | protos.google.cloud.retail.v2alpha.IGetGenerativeQuestionsFeatureConfigRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { - this._log.info('getGenerativeQuestionsFeatureConfig response %j', response); + this._log.info( + 'getGenerativeQuestionsFeatureConfig response %j', + response, + ); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.getGenerativeQuestionsFeatureConfig(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.retail.v2alpha.IGenerativeQuestionsFeatureConfig, - protos.google.cloud.retail.v2alpha.IGetGenerativeQuestionsFeatureConfigRequest|undefined, {}|undefined - ]) => { - this._log.info('getGenerativeQuestionsFeatureConfig response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getGenerativeQuestionsFeatureConfig(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.retail.v2alpha.IGenerativeQuestionsFeatureConfig, + ( + | protos.google.cloud.retail.v2alpha.IGetGenerativeQuestionsFeatureConfigRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info( + 'getGenerativeQuestionsFeatureConfig response %j', + response, + ); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Returns all questions for a given catalog. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. Resource name of the parent catalog. - * Format: projects/{project}/locations/{location}/catalogs/{catalog} - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.ListGenerativeQuestionConfigsResponse|ListGenerativeQuestionConfigsResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/generative_question_service.list_generative_question_configs.js - * region_tag:retail_v2alpha_generated_GenerativeQuestionService_ListGenerativeQuestionConfigs_async - */ + /** + * Returns all questions for a given catalog. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Resource name of the parent catalog. + * Format: projects/{project}/locations/{location}/catalogs/{catalog} + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.ListGenerativeQuestionConfigsResponse|ListGenerativeQuestionConfigsResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/generative_question_service.list_generative_question_configs.js + * region_tag:retail_v2alpha_generated_GenerativeQuestionService_ListGenerativeQuestionConfigs_async + */ listGenerativeQuestionConfigs( - request?: protos.google.cloud.retail.v2alpha.IListGenerativeQuestionConfigsRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.retail.v2alpha.IListGenerativeQuestionConfigsResponse, - protos.google.cloud.retail.v2alpha.IListGenerativeQuestionConfigsRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.IListGenerativeQuestionConfigsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IListGenerativeQuestionConfigsResponse, + ( + | protos.google.cloud.retail.v2alpha.IListGenerativeQuestionConfigsRequest + | undefined + ), + {} | undefined, + ] + >; listGenerativeQuestionConfigs( - request: protos.google.cloud.retail.v2alpha.IListGenerativeQuestionConfigsRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.retail.v2alpha.IListGenerativeQuestionConfigsResponse, - protos.google.cloud.retail.v2alpha.IListGenerativeQuestionConfigsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IListGenerativeQuestionConfigsRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.retail.v2alpha.IListGenerativeQuestionConfigsResponse, + | protos.google.cloud.retail.v2alpha.IListGenerativeQuestionConfigsRequest + | null + | undefined, + {} | null | undefined + >, + ): void; listGenerativeQuestionConfigs( - request: protos.google.cloud.retail.v2alpha.IListGenerativeQuestionConfigsRequest, - callback: Callback< - protos.google.cloud.retail.v2alpha.IListGenerativeQuestionConfigsResponse, - protos.google.cloud.retail.v2alpha.IListGenerativeQuestionConfigsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IListGenerativeQuestionConfigsRequest, + callback: Callback< + protos.google.cloud.retail.v2alpha.IListGenerativeQuestionConfigsResponse, + | protos.google.cloud.retail.v2alpha.IListGenerativeQuestionConfigsRequest + | null + | undefined, + {} | null | undefined + >, + ): void; listGenerativeQuestionConfigs( - request?: protos.google.cloud.retail.v2alpha.IListGenerativeQuestionConfigsRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.cloud.retail.v2alpha.IListGenerativeQuestionConfigsRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.retail.v2alpha.IListGenerativeQuestionConfigsResponse, - protos.google.cloud.retail.v2alpha.IListGenerativeQuestionConfigsRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.cloud.retail.v2alpha.IListGenerativeQuestionConfigsResponse, - protos.google.cloud.retail.v2alpha.IListGenerativeQuestionConfigsRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.retail.v2alpha.IListGenerativeQuestionConfigsResponse, - protos.google.cloud.retail.v2alpha.IListGenerativeQuestionConfigsRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.retail.v2alpha.IListGenerativeQuestionConfigsRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.retail.v2alpha.IListGenerativeQuestionConfigsResponse, + | protos.google.cloud.retail.v2alpha.IListGenerativeQuestionConfigsRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IListGenerativeQuestionConfigsResponse, + ( + | protos.google.cloud.retail.v2alpha.IListGenerativeQuestionConfigsRequest + | undefined + ), + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('listGenerativeQuestionConfigs request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.retail.v2alpha.IListGenerativeQuestionConfigsResponse, - protos.google.cloud.retail.v2alpha.IListGenerativeQuestionConfigsRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.retail.v2alpha.IListGenerativeQuestionConfigsResponse, + | protos.google.cloud.retail.v2alpha.IListGenerativeQuestionConfigsRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('listGenerativeQuestionConfigs response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.listGenerativeQuestionConfigs(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.retail.v2alpha.IListGenerativeQuestionConfigsResponse, - protos.google.cloud.retail.v2alpha.IListGenerativeQuestionConfigsRequest|undefined, {}|undefined - ]) => { - this._log.info('listGenerativeQuestionConfigs response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .listGenerativeQuestionConfigs(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.retail.v2alpha.IListGenerativeQuestionConfigsResponse, + ( + | protos.google.cloud.retail.v2alpha.IListGenerativeQuestionConfigsRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('listGenerativeQuestionConfigs response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Allows management of individual questions. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.cloud.retail.v2alpha.GenerativeQuestionConfig} request.generativeQuestionConfig - * Required. The question to update. - * @param {google.protobuf.FieldMask} [request.updateMask] - * Optional. Indicates which fields in the provided - * {@link protos.google.cloud.retail.v2alpha.GenerativeQuestionConfig|GenerativeQuestionConfig} - * to update. The following are NOT supported: - * - * * {@link protos.google.cloud.retail.v2alpha.GenerativeQuestionConfig.frequency|GenerativeQuestionConfig.frequency} - * - * If not set or empty, all supported fields are updated. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.GenerativeQuestionConfig|GenerativeQuestionConfig}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/generative_question_service.update_generative_question_config.js - * region_tag:retail_v2alpha_generated_GenerativeQuestionService_UpdateGenerativeQuestionConfig_async - */ + /** + * Allows management of individual questions. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.cloud.retail.v2alpha.GenerativeQuestionConfig} request.generativeQuestionConfig + * Required. The question to update. + * @param {google.protobuf.FieldMask} [request.updateMask] + * Optional. Indicates which fields in the provided + * {@link protos.google.cloud.retail.v2alpha.GenerativeQuestionConfig|GenerativeQuestionConfig} + * to update. The following are NOT supported: + * + * * {@link protos.google.cloud.retail.v2alpha.GenerativeQuestionConfig.frequency|GenerativeQuestionConfig.frequency} + * + * If not set or empty, all supported fields are updated. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.GenerativeQuestionConfig|GenerativeQuestionConfig}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/generative_question_service.update_generative_question_config.js + * region_tag:retail_v2alpha_generated_GenerativeQuestionService_UpdateGenerativeQuestionConfig_async + */ updateGenerativeQuestionConfig( - request?: protos.google.cloud.retail.v2alpha.IUpdateGenerativeQuestionConfigRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.retail.v2alpha.IGenerativeQuestionConfig, - protos.google.cloud.retail.v2alpha.IUpdateGenerativeQuestionConfigRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.IUpdateGenerativeQuestionConfigRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IGenerativeQuestionConfig, + ( + | protos.google.cloud.retail.v2alpha.IUpdateGenerativeQuestionConfigRequest + | undefined + ), + {} | undefined, + ] + >; updateGenerativeQuestionConfig( - request: protos.google.cloud.retail.v2alpha.IUpdateGenerativeQuestionConfigRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.retail.v2alpha.IGenerativeQuestionConfig, - protos.google.cloud.retail.v2alpha.IUpdateGenerativeQuestionConfigRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IUpdateGenerativeQuestionConfigRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.retail.v2alpha.IGenerativeQuestionConfig, + | protos.google.cloud.retail.v2alpha.IUpdateGenerativeQuestionConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateGenerativeQuestionConfig( - request: protos.google.cloud.retail.v2alpha.IUpdateGenerativeQuestionConfigRequest, - callback: Callback< - protos.google.cloud.retail.v2alpha.IGenerativeQuestionConfig, - protos.google.cloud.retail.v2alpha.IUpdateGenerativeQuestionConfigRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IUpdateGenerativeQuestionConfigRequest, + callback: Callback< + protos.google.cloud.retail.v2alpha.IGenerativeQuestionConfig, + | protos.google.cloud.retail.v2alpha.IUpdateGenerativeQuestionConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateGenerativeQuestionConfig( - request?: protos.google.cloud.retail.v2alpha.IUpdateGenerativeQuestionConfigRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.retail.v2alpha.IGenerativeQuestionConfig, - protos.google.cloud.retail.v2alpha.IUpdateGenerativeQuestionConfigRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.retail.v2alpha.IUpdateGenerativeQuestionConfigRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.retail.v2alpha.IGenerativeQuestionConfig, - protos.google.cloud.retail.v2alpha.IUpdateGenerativeQuestionConfigRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.retail.v2alpha.IGenerativeQuestionConfig, - protos.google.cloud.retail.v2alpha.IUpdateGenerativeQuestionConfigRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.retail.v2alpha.IUpdateGenerativeQuestionConfigRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.retail.v2alpha.IGenerativeQuestionConfig, + | protos.google.cloud.retail.v2alpha.IUpdateGenerativeQuestionConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IGenerativeQuestionConfig, + ( + | protos.google.cloud.retail.v2alpha.IUpdateGenerativeQuestionConfigRequest + | undefined + ), + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'generative_question_config.catalog': request.generativeQuestionConfig!.catalog ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'generative_question_config.catalog': + request.generativeQuestionConfig!.catalog ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateGenerativeQuestionConfig request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.retail.v2alpha.IGenerativeQuestionConfig, - protos.google.cloud.retail.v2alpha.IUpdateGenerativeQuestionConfigRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.retail.v2alpha.IGenerativeQuestionConfig, + | protos.google.cloud.retail.v2alpha.IUpdateGenerativeQuestionConfigRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { - this._log.info('updateGenerativeQuestionConfig response %j', response); + this._log.info( + 'updateGenerativeQuestionConfig response %j', + response, + ); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.updateGenerativeQuestionConfig(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.retail.v2alpha.IGenerativeQuestionConfig, - protos.google.cloud.retail.v2alpha.IUpdateGenerativeQuestionConfigRequest|undefined, {}|undefined - ]) => { - this._log.info('updateGenerativeQuestionConfig response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateGenerativeQuestionConfig(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.retail.v2alpha.IGenerativeQuestionConfig, + ( + | protos.google.cloud.retail.v2alpha.IUpdateGenerativeQuestionConfigRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info( + 'updateGenerativeQuestionConfig response %j', + response, + ); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Allows management of multiple questions. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} [request.parent] - * Optional. Resource name of the parent catalog. - * Format: projects/{project}/locations/{location}/catalogs/{catalog} - * @param {number[]} request.requests - * Required. The updates question configs. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.BatchUpdateGenerativeQuestionConfigsResponse|BatchUpdateGenerativeQuestionConfigsResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/generative_question_service.batch_update_generative_question_configs.js - * region_tag:retail_v2alpha_generated_GenerativeQuestionService_BatchUpdateGenerativeQuestionConfigs_async - */ + /** + * Allows management of multiple questions. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} [request.parent] + * Optional. Resource name of the parent catalog. + * Format: projects/{project}/locations/{location}/catalogs/{catalog} + * @param {number[]} request.requests + * Required. The updates question configs. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.BatchUpdateGenerativeQuestionConfigsResponse|BatchUpdateGenerativeQuestionConfigsResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/generative_question_service.batch_update_generative_question_configs.js + * region_tag:retail_v2alpha_generated_GenerativeQuestionService_BatchUpdateGenerativeQuestionConfigs_async + */ batchUpdateGenerativeQuestionConfigs( - request?: protos.google.cloud.retail.v2alpha.IBatchUpdateGenerativeQuestionConfigsRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.retail.v2alpha.IBatchUpdateGenerativeQuestionConfigsResponse, - protos.google.cloud.retail.v2alpha.IBatchUpdateGenerativeQuestionConfigsRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.IBatchUpdateGenerativeQuestionConfigsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IBatchUpdateGenerativeQuestionConfigsResponse, + ( + | protos.google.cloud.retail.v2alpha.IBatchUpdateGenerativeQuestionConfigsRequest + | undefined + ), + {} | undefined, + ] + >; batchUpdateGenerativeQuestionConfigs( - request: protos.google.cloud.retail.v2alpha.IBatchUpdateGenerativeQuestionConfigsRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.retail.v2alpha.IBatchUpdateGenerativeQuestionConfigsResponse, - protos.google.cloud.retail.v2alpha.IBatchUpdateGenerativeQuestionConfigsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IBatchUpdateGenerativeQuestionConfigsRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.retail.v2alpha.IBatchUpdateGenerativeQuestionConfigsResponse, + | protos.google.cloud.retail.v2alpha.IBatchUpdateGenerativeQuestionConfigsRequest + | null + | undefined, + {} | null | undefined + >, + ): void; batchUpdateGenerativeQuestionConfigs( - request: protos.google.cloud.retail.v2alpha.IBatchUpdateGenerativeQuestionConfigsRequest, - callback: Callback< - protos.google.cloud.retail.v2alpha.IBatchUpdateGenerativeQuestionConfigsResponse, - protos.google.cloud.retail.v2alpha.IBatchUpdateGenerativeQuestionConfigsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IBatchUpdateGenerativeQuestionConfigsRequest, + callback: Callback< + protos.google.cloud.retail.v2alpha.IBatchUpdateGenerativeQuestionConfigsResponse, + | protos.google.cloud.retail.v2alpha.IBatchUpdateGenerativeQuestionConfigsRequest + | null + | undefined, + {} | null | undefined + >, + ): void; batchUpdateGenerativeQuestionConfigs( - request?: protos.google.cloud.retail.v2alpha.IBatchUpdateGenerativeQuestionConfigsRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.cloud.retail.v2alpha.IBatchUpdateGenerativeQuestionConfigsRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.retail.v2alpha.IBatchUpdateGenerativeQuestionConfigsResponse, - protos.google.cloud.retail.v2alpha.IBatchUpdateGenerativeQuestionConfigsRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.cloud.retail.v2alpha.IBatchUpdateGenerativeQuestionConfigsResponse, - protos.google.cloud.retail.v2alpha.IBatchUpdateGenerativeQuestionConfigsRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.retail.v2alpha.IBatchUpdateGenerativeQuestionConfigsResponse, - protos.google.cloud.retail.v2alpha.IBatchUpdateGenerativeQuestionConfigsRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.retail.v2alpha.IBatchUpdateGenerativeQuestionConfigsRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.retail.v2alpha.IBatchUpdateGenerativeQuestionConfigsResponse, + | protos.google.cloud.retail.v2alpha.IBatchUpdateGenerativeQuestionConfigsRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IBatchUpdateGenerativeQuestionConfigsResponse, + ( + | protos.google.cloud.retail.v2alpha.IBatchUpdateGenerativeQuestionConfigsRequest + | undefined + ), + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('batchUpdateGenerativeQuestionConfigs request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.retail.v2alpha.IBatchUpdateGenerativeQuestionConfigsResponse, - protos.google.cloud.retail.v2alpha.IBatchUpdateGenerativeQuestionConfigsRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.retail.v2alpha.IBatchUpdateGenerativeQuestionConfigsResponse, + | protos.google.cloud.retail.v2alpha.IBatchUpdateGenerativeQuestionConfigsRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { - this._log.info('batchUpdateGenerativeQuestionConfigs response %j', response); + this._log.info( + 'batchUpdateGenerativeQuestionConfigs response %j', + response, + ); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.batchUpdateGenerativeQuestionConfigs(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.retail.v2alpha.IBatchUpdateGenerativeQuestionConfigsResponse, - protos.google.cloud.retail.v2alpha.IBatchUpdateGenerativeQuestionConfigsRequest|undefined, {}|undefined - ]) => { - this._log.info('batchUpdateGenerativeQuestionConfigs response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .batchUpdateGenerativeQuestionConfigs(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.retail.v2alpha.IBatchUpdateGenerativeQuestionConfigsResponse, + ( + | protos.google.cloud.retail.v2alpha.IBatchUpdateGenerativeQuestionConfigsRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info( + 'batchUpdateGenerativeQuestionConfigs response %j', + response, + ); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); @@ -872,7 +1202,7 @@ export class GenerativeQuestionServiceClient { * @param {string} project * @returns {string} Resource name string. */ - alertConfigPath(project:string) { + alertConfigPath(project: string) { return this.pathTemplates.alertConfigPathTemplate.render({ project: project, }); @@ -886,7 +1216,8 @@ export class GenerativeQuestionServiceClient { * @returns {string} A string representing the project. */ matchProjectFromAlertConfigName(alertConfigName: string) { - return this.pathTemplates.alertConfigPathTemplate.match(alertConfigName).project; + return this.pathTemplates.alertConfigPathTemplate.match(alertConfigName) + .project; } /** @@ -897,7 +1228,7 @@ export class GenerativeQuestionServiceClient { * @param {string} catalog * @returns {string} Resource name string. */ - attributesConfigPath(project:string,location:string,catalog:string) { + attributesConfigPath(project: string, location: string, catalog: string) { return this.pathTemplates.attributesConfigPathTemplate.render({ project: project, location: location, @@ -913,7 +1244,9 @@ export class GenerativeQuestionServiceClient { * @returns {string} A string representing the project. */ matchProjectFromAttributesConfigName(attributesConfigName: string) { - return this.pathTemplates.attributesConfigPathTemplate.match(attributesConfigName).project; + return this.pathTemplates.attributesConfigPathTemplate.match( + attributesConfigName, + ).project; } /** @@ -924,7 +1257,9 @@ export class GenerativeQuestionServiceClient { * @returns {string} A string representing the location. */ matchLocationFromAttributesConfigName(attributesConfigName: string) { - return this.pathTemplates.attributesConfigPathTemplate.match(attributesConfigName).location; + return this.pathTemplates.attributesConfigPathTemplate.match( + attributesConfigName, + ).location; } /** @@ -935,7 +1270,9 @@ export class GenerativeQuestionServiceClient { * @returns {string} A string representing the catalog. */ matchCatalogFromAttributesConfigName(attributesConfigName: string) { - return this.pathTemplates.attributesConfigPathTemplate.match(attributesConfigName).catalog; + return this.pathTemplates.attributesConfigPathTemplate.match( + attributesConfigName, + ).catalog; } /** @@ -947,7 +1284,12 @@ export class GenerativeQuestionServiceClient { * @param {string} branch * @returns {string} Resource name string. */ - branchPath(project:string,location:string,catalog:string,branch:string) { + branchPath( + project: string, + location: string, + catalog: string, + branch: string, + ) { return this.pathTemplates.branchPathTemplate.render({ project: project, location: location, @@ -1008,7 +1350,7 @@ export class GenerativeQuestionServiceClient { * @param {string} catalog * @returns {string} Resource name string. */ - catalogPath(project:string,location:string,catalog:string) { + catalogPath(project: string, location: string, catalog: string) { return this.pathTemplates.catalogPathTemplate.render({ project: project, location: location, @@ -1057,7 +1399,7 @@ export class GenerativeQuestionServiceClient { * @param {string} catalog * @returns {string} Resource name string. */ - completionConfigPath(project:string,location:string,catalog:string) { + completionConfigPath(project: string, location: string, catalog: string) { return this.pathTemplates.completionConfigPathTemplate.render({ project: project, location: location, @@ -1073,7 +1415,9 @@ export class GenerativeQuestionServiceClient { * @returns {string} A string representing the project. */ matchProjectFromCompletionConfigName(completionConfigName: string) { - return this.pathTemplates.completionConfigPathTemplate.match(completionConfigName).project; + return this.pathTemplates.completionConfigPathTemplate.match( + completionConfigName, + ).project; } /** @@ -1084,7 +1428,9 @@ export class GenerativeQuestionServiceClient { * @returns {string} A string representing the location. */ matchLocationFromCompletionConfigName(completionConfigName: string) { - return this.pathTemplates.completionConfigPathTemplate.match(completionConfigName).location; + return this.pathTemplates.completionConfigPathTemplate.match( + completionConfigName, + ).location; } /** @@ -1095,7 +1441,9 @@ export class GenerativeQuestionServiceClient { * @returns {string} A string representing the catalog. */ matchCatalogFromCompletionConfigName(completionConfigName: string) { - return this.pathTemplates.completionConfigPathTemplate.match(completionConfigName).catalog; + return this.pathTemplates.completionConfigPathTemplate.match( + completionConfigName, + ).catalog; } /** @@ -1107,7 +1455,12 @@ export class GenerativeQuestionServiceClient { * @param {string} control * @returns {string} Resource name string. */ - controlPath(project:string,location:string,catalog:string,control:string) { + controlPath( + project: string, + location: string, + catalog: string, + control: string, + ) { return this.pathTemplates.controlPathTemplate.render({ project: project, location: location, @@ -1166,7 +1519,7 @@ export class GenerativeQuestionServiceClient { * @param {string} project * @returns {string} Resource name string. */ - loggingConfigPath(project:string) { + loggingConfigPath(project: string) { return this.pathTemplates.loggingConfigPathTemplate.render({ project: project, }); @@ -1180,7 +1533,8 @@ export class GenerativeQuestionServiceClient { * @returns {string} A string representing the project. */ matchProjectFromLoggingConfigName(loggingConfigName: string) { - return this.pathTemplates.loggingConfigPathTemplate.match(loggingConfigName).project; + return this.pathTemplates.loggingConfigPathTemplate.match(loggingConfigName) + .project; } /** @@ -1192,7 +1546,12 @@ export class GenerativeQuestionServiceClient { * @param {string} merchant_center_account_link * @returns {string} Resource name string. */ - merchantCenterAccountLinkPath(project:string,location:string,catalog:string,merchantCenterAccountLink:string) { + merchantCenterAccountLinkPath( + project: string, + location: string, + catalog: string, + merchantCenterAccountLink: string, + ) { return this.pathTemplates.merchantCenterAccountLinkPathTemplate.render({ project: project, location: location, @@ -1208,8 +1567,12 @@ export class GenerativeQuestionServiceClient { * A fully-qualified path representing MerchantCenterAccountLink resource. * @returns {string} A string representing the project. */ - matchProjectFromMerchantCenterAccountLinkName(merchantCenterAccountLinkName: string) { - return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match(merchantCenterAccountLinkName).project; + matchProjectFromMerchantCenterAccountLinkName( + merchantCenterAccountLinkName: string, + ) { + return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match( + merchantCenterAccountLinkName, + ).project; } /** @@ -1219,8 +1582,12 @@ export class GenerativeQuestionServiceClient { * A fully-qualified path representing MerchantCenterAccountLink resource. * @returns {string} A string representing the location. */ - matchLocationFromMerchantCenterAccountLinkName(merchantCenterAccountLinkName: string) { - return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match(merchantCenterAccountLinkName).location; + matchLocationFromMerchantCenterAccountLinkName( + merchantCenterAccountLinkName: string, + ) { + return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match( + merchantCenterAccountLinkName, + ).location; } /** @@ -1230,8 +1597,12 @@ export class GenerativeQuestionServiceClient { * A fully-qualified path representing MerchantCenterAccountLink resource. * @returns {string} A string representing the catalog. */ - matchCatalogFromMerchantCenterAccountLinkName(merchantCenterAccountLinkName: string) { - return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match(merchantCenterAccountLinkName).catalog; + matchCatalogFromMerchantCenterAccountLinkName( + merchantCenterAccountLinkName: string, + ) { + return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match( + merchantCenterAccountLinkName, + ).catalog; } /** @@ -1241,8 +1612,12 @@ export class GenerativeQuestionServiceClient { * A fully-qualified path representing MerchantCenterAccountLink resource. * @returns {string} A string representing the merchant_center_account_link. */ - matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName(merchantCenterAccountLinkName: string) { - return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match(merchantCenterAccountLinkName).merchant_center_account_link; + matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName( + merchantCenterAccountLinkName: string, + ) { + return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match( + merchantCenterAccountLinkName, + ).merchant_center_account_link; } /** @@ -1254,7 +1629,7 @@ export class GenerativeQuestionServiceClient { * @param {string} model * @returns {string} Resource name string. */ - modelPath(project:string,location:string,catalog:string,model:string) { + modelPath(project: string, location: string, catalog: string, model: string) { return this.pathTemplates.modelPathTemplate.render({ project: project, location: location, @@ -1317,7 +1692,13 @@ export class GenerativeQuestionServiceClient { * @param {string} product * @returns {string} Resource name string. */ - productPath(project:string,location:string,catalog:string,branch:string,product:string) { + productPath( + project: string, + location: string, + catalog: string, + branch: string, + product: string, + ) { return this.pathTemplates.productPathTemplate.render({ project: project, location: location, @@ -1388,7 +1769,7 @@ export class GenerativeQuestionServiceClient { * @param {string} project * @returns {string} Resource name string. */ - retailProjectPath(project:string) { + retailProjectPath(project: string) { return this.pathTemplates.retailProjectPathTemplate.render({ project: project, }); @@ -1402,7 +1783,8 @@ export class GenerativeQuestionServiceClient { * @returns {string} A string representing the project. */ matchProjectFromRetailProjectName(retailProjectName: string) { - return this.pathTemplates.retailProjectPathTemplate.match(retailProjectName).project; + return this.pathTemplates.retailProjectPathTemplate.match(retailProjectName) + .project; } /** @@ -1414,7 +1796,12 @@ export class GenerativeQuestionServiceClient { * @param {string} serving_config * @returns {string} Resource name string. */ - servingConfigPath(project:string,location:string,catalog:string,servingConfig:string) { + servingConfigPath( + project: string, + location: string, + catalog: string, + servingConfig: string, + ) { return this.pathTemplates.servingConfigPathTemplate.render({ project: project, location: location, @@ -1431,7 +1818,8 @@ export class GenerativeQuestionServiceClient { * @returns {string} A string representing the project. */ matchProjectFromServingConfigName(servingConfigName: string) { - return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName).project; + return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName) + .project; } /** @@ -1442,7 +1830,8 @@ export class GenerativeQuestionServiceClient { * @returns {string} A string representing the location. */ matchLocationFromServingConfigName(servingConfigName: string) { - return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName).location; + return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName) + .location; } /** @@ -1453,7 +1842,8 @@ export class GenerativeQuestionServiceClient { * @returns {string} A string representing the catalog. */ matchCatalogFromServingConfigName(servingConfigName: string) { - return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName).catalog; + return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName) + .catalog; } /** @@ -1464,7 +1854,8 @@ export class GenerativeQuestionServiceClient { * @returns {string} A string representing the serving_config. */ matchServingConfigFromServingConfigName(servingConfigName: string) { - return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName).serving_config; + return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName) + .serving_config; } /** @@ -1475,7 +1866,7 @@ export class GenerativeQuestionServiceClient { */ close(): Promise { if (this.generativeQuestionServiceStub && !this._terminated) { - return this.generativeQuestionServiceStub.then(stub => { + return this.generativeQuestionServiceStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -1483,4 +1874,4 @@ export class GenerativeQuestionServiceClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/src/v2alpha/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/src/v2alpha/index.ts.baseline index 54e41a8c063c..5cdaf5182abe 100644 --- a/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/src/v2alpha/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/src/v2alpha/index.ts.baseline @@ -16,18 +16,18 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -export {AnalyticsServiceClient} from './analytics_service_client.js'; -export {BranchServiceClient} from './branch_service_client.js'; -export {CatalogServiceClient} from './catalog_service_client.js'; -export {CompletionServiceClient} from './completion_service_client.js'; -export {ControlServiceClient} from './control_service_client.js'; -export {ConversationalSearchServiceClient} from './conversational_search_service_client.js'; -export {GenerativeQuestionServiceClient} from './generative_question_service_client.js'; -export {MerchantCenterAccountLinkServiceClient} from './merchant_center_account_link_service_client.js'; -export {ModelServiceClient} from './model_service_client.js'; -export {PredictionServiceClient} from './prediction_service_client.js'; -export {ProductServiceClient} from './product_service_client.js'; -export {ProjectServiceClient} from './project_service_client.js'; -export {SearchServiceClient} from './search_service_client.js'; -export {ServingConfigServiceClient} from './serving_config_service_client.js'; -export {UserEventServiceClient} from './user_event_service_client.js'; +export { AnalyticsServiceClient } from './analytics_service_client.js'; +export { BranchServiceClient } from './branch_service_client.js'; +export { CatalogServiceClient } from './catalog_service_client.js'; +export { CompletionServiceClient } from './completion_service_client.js'; +export { ControlServiceClient } from './control_service_client.js'; +export { ConversationalSearchServiceClient } from './conversational_search_service_client.js'; +export { GenerativeQuestionServiceClient } from './generative_question_service_client.js'; +export { MerchantCenterAccountLinkServiceClient } from './merchant_center_account_link_service_client.js'; +export { ModelServiceClient } from './model_service_client.js'; +export { PredictionServiceClient } from './prediction_service_client.js'; +export { ProductServiceClient } from './product_service_client.js'; +export { ProjectServiceClient } from './project_service_client.js'; +export { SearchServiceClient } from './search_service_client.js'; +export { ServingConfigServiceClient } from './serving_config_service_client.js'; +export { UserEventServiceClient } from './user_event_service_client.js'; diff --git a/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/src/v2alpha/merchant_center_account_link_service_client.ts.baseline b/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/src/v2alpha/merchant_center_account_link_service_client.ts.baseline index 2acee956f67e..acec6d5c5dca 100644 --- a/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/src/v2alpha/merchant_center_account_link_service_client.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/src/v2alpha/merchant_center_account_link_service_client.ts.baseline @@ -18,15 +18,22 @@ /* global window */ import * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions, GrpcClientOptions, LROperation} from 'google-gax'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + GrpcClientOptions, + LROperation, +} from 'google-gax'; // @ts-ignore import type * as protos from '../../../protos/protos.js'; import * as merchant_center_account_link_service_client_config from './merchant_center_account_link_service_client_config.json'; import fs from 'fs'; import path from 'path'; -import {fileURLToPath} from 'url'; -import {getJSON} from '../json-helper.cjs'; +import { fileURLToPath } from 'url'; +import { getJSON } from '../json-helper.cjs'; // @ts-ignore const dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -36,15 +43,15 @@ const dirname = path.dirname(fileURLToPath(import.meta.url)); * This file defines retry strategy and timeouts for all API methods in this library. */ const gapicConfig = getJSON( - path.join(dirname, 'merchant_center_account_link_service_client_config.json') + path.join(dirname, 'merchant_center_account_link_service_client_config.json'), ); const jsonProtos = getJSON( - path.join(dirname, '..', '..', '..', 'protos/protos.json') + path.join(dirname, '..', '..', '..', 'protos/protos.json'), ); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; const version = getJSON( - path.join(dirname, '..', '..', '..', '..', 'package.json') + path.join(dirname, '..', '..', '..', '..', 'package.json'), ).version; /** @@ -59,7 +66,7 @@ export class MerchantCenterAccountLinkServiceClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('retail'); @@ -71,10 +78,10 @@ export class MerchantCenterAccountLinkServiceClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; operationsClient: gax.OperationsClient; - merchantCenterAccountLinkServiceStub?: Promise<{[name: string]: Function}>; + merchantCenterAccountLinkServiceStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of MerchantCenterAccountLinkServiceClient. @@ -116,21 +123,43 @@ export class MerchantCenterAccountLinkServiceClient { * const client = new MerchantCenterAccountLinkServiceClient({fallback: 'rest'}, gax); * ``` */ - constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { // Ensure that options include all the required fields. - const staticMembers = this.constructor as typeof MerchantCenterAccountLinkServiceClient; - if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { - throw new Error('Please set either universe_domain or universeDomain, but not both.'); + const staticMembers = this + .constructor as typeof MerchantCenterAccountLinkServiceClient; + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); } - const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; - this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; this._servicePath = 'retail.' + this._universeDomain; - const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; - const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. if (servicePath !== this._servicePath && !('scopes' in opts)) { @@ -152,7 +181,7 @@ export class MerchantCenterAccountLinkServiceClient { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; @@ -169,10 +198,7 @@ export class MerchantCenterAccountLinkServiceClient { const isEsm = true; const isEsmString = isEsm ? '-esm' : '-cjs'; // Determine the client header string. - const clientHeader = [ - `gax/${this._gaxModule.version}`, - `gapic/${version}`, - ]; + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/{process.versions.node}${isEsmString}`); } else { @@ -180,7 +206,7 @@ export class MerchantCenterAccountLinkServiceClient { } if (!opts.fallback) { clientHeader.push(`grpc/${this._gaxGrpc.grpcVersion}`); - } else if (opts.fallback === 'rest' ) { + } else if (opts.fallback === 'rest') { clientHeader.push(`rest/${this._gaxGrpc.grpcVersion}`); } if (opts.libName && opts.libVersion) { @@ -188,47 +214,49 @@ export class MerchantCenterAccountLinkServiceClient { } // Load the applicable protos. - this._protos = this._gaxGrpc.loadProtoJSON(jsonProtos as gax.protobuf.INamespace); + this._protos = this._gaxGrpc.loadProtoJSON( + jsonProtos as gax.protobuf.INamespace, + ); // This API contains "path templates"; forward-slash-separated // identifiers to uniquely identify resources within the API. // Create useful helper objects for these. this.pathTemplates = { alertConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/alertConfig' + 'projects/{project}/alertConfig', ), attributesConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/attributesConfig' + 'projects/{project}/locations/{location}/catalogs/{catalog}/attributesConfig', ), branchPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}', ), catalogPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}' + 'projects/{project}/locations/{location}/catalogs/{catalog}', ), completionConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/completionConfig' + 'projects/{project}/locations/{location}/catalogs/{catalog}/completionConfig', ), controlPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/controls/{control}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/controls/{control}', ), loggingConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/loggingConfig' + 'projects/{project}/loggingConfig', ), merchantCenterAccountLinkPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/merchantCenterAccountLinks/{merchant_center_account_link}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/merchantCenterAccountLinks/{merchant_center_account_link}', ), modelPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/models/{model}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/models/{model}', ), productPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}', ), retailProjectPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/retailProject' + 'projects/{project}/retailProject', ), servingConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/servingConfigs/{serving_config}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/servingConfigs/{serving_config}', ), }; @@ -238,31 +266,65 @@ export class MerchantCenterAccountLinkServiceClient { // rather than holding a request open. const lroOptions: GrpcClientOptions = { auth: this.auth, - grpc: 'grpc' in this._gaxGrpc ? this._gaxGrpc.grpc : undefined + grpc: 'grpc' in this._gaxGrpc ? this._gaxGrpc.grpc : undefined, }; if (opts.fallback === 'rest') { lroOptions.protoJson = protoFilesRoot; - lroOptions.httpRules = [{selector: 'google.longrunning.Operations.GetOperation',get: '/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*/operations/*}',additional_bindings: [{get: '/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*/places/*/operations/*}',},{get: '/v2alpha/{name=projects/*/locations/*/catalogs/*/operations/*}',},{get: '/v2alpha/{name=projects/*/locations/*/operations/*}',},{get: '/v2alpha/{name=projects/*/operations/*}',}], - },{selector: 'google.longrunning.Operations.ListOperations',get: '/v2alpha/{name=projects/*/locations/*/catalogs/*}/operations',additional_bindings: [{get: '/v2alpha/{name=projects/*/locations/*}/operations',},{get: '/v2alpha/{name=projects/*}/operations',}], - }]; + lroOptions.httpRules = [ + { + selector: 'google.longrunning.Operations.GetOperation', + get: '/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*/operations/*}', + additional_bindings: [ + { + get: '/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*/places/*/operations/*}', + }, + { + get: '/v2alpha/{name=projects/*/locations/*/catalogs/*/operations/*}', + }, + { get: '/v2alpha/{name=projects/*/locations/*/operations/*}' }, + { get: '/v2alpha/{name=projects/*/operations/*}' }, + ], + }, + { + selector: 'google.longrunning.Operations.ListOperations', + get: '/v2alpha/{name=projects/*/locations/*/catalogs/*}/operations', + additional_bindings: [ + { get: '/v2alpha/{name=projects/*/locations/*}/operations' }, + { get: '/v2alpha/{name=projects/*}/operations' }, + ], + }, + ]; } - this.operationsClient = this._gaxModule.lro(lroOptions).operationsClient(opts); + this.operationsClient = this._gaxModule + .lro(lroOptions) + .operationsClient(opts); const createMerchantCenterAccountLinkResponse = protoFilesRoot.lookup( - '.google.cloud.retail.v2alpha.MerchantCenterAccountLink') as gax.protobuf.Type; + '.google.cloud.retail.v2alpha.MerchantCenterAccountLink', + ) as gax.protobuf.Type; const createMerchantCenterAccountLinkMetadata = protoFilesRoot.lookup( - '.google.cloud.retail.v2alpha.CreateMerchantCenterAccountLinkMetadata') as gax.protobuf.Type; + '.google.cloud.retail.v2alpha.CreateMerchantCenterAccountLinkMetadata', + ) as gax.protobuf.Type; this.descriptors.longrunning = { - createMerchantCenterAccountLink: new this._gaxModule.LongrunningDescriptor( - this.operationsClient, - createMerchantCenterAccountLinkResponse.decode.bind(createMerchantCenterAccountLinkResponse), - createMerchantCenterAccountLinkMetadata.decode.bind(createMerchantCenterAccountLinkMetadata)) + createMerchantCenterAccountLink: + new this._gaxModule.LongrunningDescriptor( + this.operationsClient, + createMerchantCenterAccountLinkResponse.decode.bind( + createMerchantCenterAccountLinkResponse, + ), + createMerchantCenterAccountLinkMetadata.decode.bind( + createMerchantCenterAccountLinkMetadata, + ), + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.cloud.retail.v2alpha.MerchantCenterAccountLinkService', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.cloud.retail.v2alpha.MerchantCenterAccountLinkService', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + { 'x-goog-api-client': clientHeader.join(' ') }, + ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -293,37 +355,45 @@ export class MerchantCenterAccountLinkServiceClient { // Put together the "service stub" for // google.cloud.retail.v2alpha.MerchantCenterAccountLinkService. this.merchantCenterAccountLinkServiceStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.cloud.retail.v2alpha.MerchantCenterAccountLinkService') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any - (this._protos as any).google.cloud.retail.v2alpha.MerchantCenterAccountLinkService, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.cloud.retail.v2alpha.MerchantCenterAccountLinkService', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any + (this._protos as any).google.cloud.retail.v2alpha + .MerchantCenterAccountLinkService, + this._opts, + this._providedCustomServicePath, + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const merchantCenterAccountLinkServiceStubMethods = - ['listMerchantCenterAccountLinks', 'createMerchantCenterAccountLink', 'deleteMerchantCenterAccountLink']; + const merchantCenterAccountLinkServiceStubMethods = [ + 'listMerchantCenterAccountLinks', + 'createMerchantCenterAccountLink', + 'deleteMerchantCenterAccountLink', + ]; for (const methodName of merchantCenterAccountLinkServiceStubMethods) { const callPromise = this.merchantCenterAccountLinkServiceStub.then( - stub => (...args: Array<{}>) => { - if (this._terminated) { - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error|null|undefined) => () => { + (stub) => + (...args: Array<{}>) => { + if (this._terminated) { + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { throw err; - }); + }, + ); - const descriptor = - this.descriptors.longrunning[methodName] || - undefined; + const descriptor = this.descriptors.longrunning[methodName] || undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -338,8 +408,14 @@ export class MerchantCenterAccountLinkServiceClient { * @returns {string} The DNS address for this service. */ static get servicePath() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'retail.googleapis.com'; } @@ -351,8 +427,14 @@ export class MerchantCenterAccountLinkServiceClient { * @returns {string} The DNS address for this service. */ static get apiEndpoint() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'retail.googleapis.com'; } @@ -383,9 +465,7 @@ export class MerchantCenterAccountLinkServiceClient { * @returns {string[]} List of default scopes. */ static get scopes() { - return [ - 'https://www.googleapis.com/auth/cloud-platform' - ]; + return ['https://www.googleapis.com/auth/cloud-platform']; } getProjectId(): Promise; @@ -394,8 +474,9 @@ export class MerchantCenterAccountLinkServiceClient { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId(callback?: Callback): - Promise|void { + getProjectId( + callback?: Callback, + ): Promise | void { if (callback) { this.auth.getProjectId(callback); return; @@ -406,320 +487,500 @@ export class MerchantCenterAccountLinkServiceClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Lists all - * {@link protos.google.cloud.retail.v2alpha.MerchantCenterAccountLink|MerchantCenterAccountLink}s - * under the specified parent {@link protos.google.cloud.retail.v2alpha.Catalog|Catalog}. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent Catalog of the resource. - * It must match this format: - * `projects/{PROJECT_NUMBER}/locations/global/catalogs/{CATALOG_ID}` - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.ListMerchantCenterAccountLinksResponse|ListMerchantCenterAccountLinksResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/merchant_center_account_link_service.list_merchant_center_account_links.js - * region_tag:retail_v2alpha_generated_MerchantCenterAccountLinkService_ListMerchantCenterAccountLinks_async - */ + /** + * Lists all + * {@link protos.google.cloud.retail.v2alpha.MerchantCenterAccountLink|MerchantCenterAccountLink}s + * under the specified parent {@link protos.google.cloud.retail.v2alpha.Catalog|Catalog}. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent Catalog of the resource. + * It must match this format: + * `projects/{PROJECT_NUMBER}/locations/global/catalogs/{CATALOG_ID}` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.ListMerchantCenterAccountLinksResponse|ListMerchantCenterAccountLinksResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/merchant_center_account_link_service.list_merchant_center_account_links.js + * region_tag:retail_v2alpha_generated_MerchantCenterAccountLinkService_ListMerchantCenterAccountLinks_async + */ listMerchantCenterAccountLinks( - request?: protos.google.cloud.retail.v2alpha.IListMerchantCenterAccountLinksRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.retail.v2alpha.IListMerchantCenterAccountLinksResponse, - protos.google.cloud.retail.v2alpha.IListMerchantCenterAccountLinksRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.IListMerchantCenterAccountLinksRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IListMerchantCenterAccountLinksResponse, + ( + | protos.google.cloud.retail.v2alpha.IListMerchantCenterAccountLinksRequest + | undefined + ), + {} | undefined, + ] + >; listMerchantCenterAccountLinks( - request: protos.google.cloud.retail.v2alpha.IListMerchantCenterAccountLinksRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.retail.v2alpha.IListMerchantCenterAccountLinksResponse, - protos.google.cloud.retail.v2alpha.IListMerchantCenterAccountLinksRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IListMerchantCenterAccountLinksRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.retail.v2alpha.IListMerchantCenterAccountLinksResponse, + | protos.google.cloud.retail.v2alpha.IListMerchantCenterAccountLinksRequest + | null + | undefined, + {} | null | undefined + >, + ): void; listMerchantCenterAccountLinks( - request: protos.google.cloud.retail.v2alpha.IListMerchantCenterAccountLinksRequest, - callback: Callback< - protos.google.cloud.retail.v2alpha.IListMerchantCenterAccountLinksResponse, - protos.google.cloud.retail.v2alpha.IListMerchantCenterAccountLinksRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IListMerchantCenterAccountLinksRequest, + callback: Callback< + protos.google.cloud.retail.v2alpha.IListMerchantCenterAccountLinksResponse, + | protos.google.cloud.retail.v2alpha.IListMerchantCenterAccountLinksRequest + | null + | undefined, + {} | null | undefined + >, + ): void; listMerchantCenterAccountLinks( - request?: protos.google.cloud.retail.v2alpha.IListMerchantCenterAccountLinksRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.cloud.retail.v2alpha.IListMerchantCenterAccountLinksRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.retail.v2alpha.IListMerchantCenterAccountLinksResponse, - protos.google.cloud.retail.v2alpha.IListMerchantCenterAccountLinksRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.cloud.retail.v2alpha.IListMerchantCenterAccountLinksResponse, - protos.google.cloud.retail.v2alpha.IListMerchantCenterAccountLinksRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.retail.v2alpha.IListMerchantCenterAccountLinksResponse, - protos.google.cloud.retail.v2alpha.IListMerchantCenterAccountLinksRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.retail.v2alpha.IListMerchantCenterAccountLinksRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.retail.v2alpha.IListMerchantCenterAccountLinksResponse, + | protos.google.cloud.retail.v2alpha.IListMerchantCenterAccountLinksRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IListMerchantCenterAccountLinksResponse, + ( + | protos.google.cloud.retail.v2alpha.IListMerchantCenterAccountLinksRequest + | undefined + ), + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('listMerchantCenterAccountLinks request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.retail.v2alpha.IListMerchantCenterAccountLinksResponse, - protos.google.cloud.retail.v2alpha.IListMerchantCenterAccountLinksRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.retail.v2alpha.IListMerchantCenterAccountLinksResponse, + | protos.google.cloud.retail.v2alpha.IListMerchantCenterAccountLinksRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { - this._log.info('listMerchantCenterAccountLinks response %j', response); + this._log.info( + 'listMerchantCenterAccountLinks response %j', + response, + ); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.listMerchantCenterAccountLinks(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.retail.v2alpha.IListMerchantCenterAccountLinksResponse, - protos.google.cloud.retail.v2alpha.IListMerchantCenterAccountLinksRequest|undefined, {}|undefined - ]) => { - this._log.info('listMerchantCenterAccountLinks response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .listMerchantCenterAccountLinks(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.retail.v2alpha.IListMerchantCenterAccountLinksResponse, + ( + | protos.google.cloud.retail.v2alpha.IListMerchantCenterAccountLinksRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info( + 'listMerchantCenterAccountLinks response %j', + response, + ); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Deletes a - * {@link protos.google.cloud.retail.v2alpha.MerchantCenterAccountLink|MerchantCenterAccountLink}. - * If the - * {@link protos.google.cloud.retail.v2alpha.MerchantCenterAccountLink|MerchantCenterAccountLink} - * to delete does not exist, a NOT_FOUND error is returned. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. Full resource name. Format: - * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/merchantCenterAccountLinks/{merchant_center_account_link_id}` - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/merchant_center_account_link_service.delete_merchant_center_account_link.js - * region_tag:retail_v2alpha_generated_MerchantCenterAccountLinkService_DeleteMerchantCenterAccountLink_async - */ + /** + * Deletes a + * {@link protos.google.cloud.retail.v2alpha.MerchantCenterAccountLink|MerchantCenterAccountLink}. + * If the + * {@link protos.google.cloud.retail.v2alpha.MerchantCenterAccountLink|MerchantCenterAccountLink} + * to delete does not exist, a NOT_FOUND error is returned. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Full resource name. Format: + * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/merchantCenterAccountLinks/{merchant_center_account_link_id}` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/merchant_center_account_link_service.delete_merchant_center_account_link.js + * region_tag:retail_v2alpha_generated_MerchantCenterAccountLinkService_DeleteMerchantCenterAccountLink_async + */ deleteMerchantCenterAccountLink( - request?: protos.google.cloud.retail.v2alpha.IDeleteMerchantCenterAccountLinkRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.cloud.retail.v2alpha.IDeleteMerchantCenterAccountLinkRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.IDeleteMerchantCenterAccountLinkRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.cloud.retail.v2alpha.IDeleteMerchantCenterAccountLinkRequest + | undefined + ), + {} | undefined, + ] + >; deleteMerchantCenterAccountLink( - request: protos.google.cloud.retail.v2alpha.IDeleteMerchantCenterAccountLinkRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.cloud.retail.v2alpha.IDeleteMerchantCenterAccountLinkRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IDeleteMerchantCenterAccountLinkRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.cloud.retail.v2alpha.IDeleteMerchantCenterAccountLinkRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteMerchantCenterAccountLink( - request: protos.google.cloud.retail.v2alpha.IDeleteMerchantCenterAccountLinkRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.cloud.retail.v2alpha.IDeleteMerchantCenterAccountLinkRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IDeleteMerchantCenterAccountLinkRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.cloud.retail.v2alpha.IDeleteMerchantCenterAccountLinkRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteMerchantCenterAccountLink( - request?: protos.google.cloud.retail.v2alpha.IDeleteMerchantCenterAccountLinkRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.protobuf.IEmpty, - protos.google.cloud.retail.v2alpha.IDeleteMerchantCenterAccountLinkRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.retail.v2alpha.IDeleteMerchantCenterAccountLinkRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.cloud.retail.v2alpha.IDeleteMerchantCenterAccountLinkRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.cloud.retail.v2alpha.IDeleteMerchantCenterAccountLinkRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.retail.v2alpha.IDeleteMerchantCenterAccountLinkRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + | protos.google.cloud.retail.v2alpha.IDeleteMerchantCenterAccountLinkRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.cloud.retail.v2alpha.IDeleteMerchantCenterAccountLinkRequest + | undefined + ), + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('deleteMerchantCenterAccountLink request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.cloud.retail.v2alpha.IDeleteMerchantCenterAccountLinkRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.cloud.retail.v2alpha.IDeleteMerchantCenterAccountLinkRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { - this._log.info('deleteMerchantCenterAccountLink response %j', response); + this._log.info( + 'deleteMerchantCenterAccountLink response %j', + response, + ); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.deleteMerchantCenterAccountLink(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.cloud.retail.v2alpha.IDeleteMerchantCenterAccountLinkRequest|undefined, {}|undefined - ]) => { - this._log.info('deleteMerchantCenterAccountLink response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteMerchantCenterAccountLink(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + ( + | protos.google.cloud.retail.v2alpha.IDeleteMerchantCenterAccountLinkRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info( + 'deleteMerchantCenterAccountLink response %j', + response, + ); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Creates a - * {@link protos.google.cloud.retail.v2alpha.MerchantCenterAccountLink|MerchantCenterAccountLink}. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The branch resource where this MerchantCenterAccountLink will be - * created. Format: - * `projects/{PROJECT_NUMBER}/locations/global/catalogs/{CATALOG_ID}` - * @param {google.cloud.retail.v2alpha.MerchantCenterAccountLink} request.merchantCenterAccountLink - * Required. The - * {@link protos.google.cloud.retail.v2alpha.MerchantCenterAccountLink|MerchantCenterAccountLink} - * to create. - * - * If the caller does not have permission to create the - * {@link protos.google.cloud.retail.v2alpha.MerchantCenterAccountLink|MerchantCenterAccountLink}, - * regardless of whether or not it exists, a PERMISSION_DENIED error is - * returned. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing - * a long running operation. Its `promise()` method returns a promise - * you can `await` for. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/merchant_center_account_link_service.create_merchant_center_account_link.js - * region_tag:retail_v2alpha_generated_MerchantCenterAccountLinkService_CreateMerchantCenterAccountLink_async - */ + /** + * Creates a + * {@link protos.google.cloud.retail.v2alpha.MerchantCenterAccountLink|MerchantCenterAccountLink}. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The branch resource where this MerchantCenterAccountLink will be + * created. Format: + * `projects/{PROJECT_NUMBER}/locations/global/catalogs/{CATALOG_ID}` + * @param {google.cloud.retail.v2alpha.MerchantCenterAccountLink} request.merchantCenterAccountLink + * Required. The + * {@link protos.google.cloud.retail.v2alpha.MerchantCenterAccountLink|MerchantCenterAccountLink} + * to create. + * + * If the caller does not have permission to create the + * {@link protos.google.cloud.retail.v2alpha.MerchantCenterAccountLink|MerchantCenterAccountLink}, + * regardless of whether or not it exists, a PERMISSION_DENIED error is + * returned. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/merchant_center_account_link_service.create_merchant_center_account_link.js + * region_tag:retail_v2alpha_generated_MerchantCenterAccountLinkService_CreateMerchantCenterAccountLink_async + */ createMerchantCenterAccountLink( - request?: protos.google.cloud.retail.v2alpha.ICreateMerchantCenterAccountLinkRequest, - options?: CallOptions): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.ICreateMerchantCenterAccountLinkRequest, + options?: CallOptions, + ): Promise< + [ + LROperation< + protos.google.cloud.retail.v2alpha.IMerchantCenterAccountLink, + protos.google.cloud.retail.v2alpha.ICreateMerchantCenterAccountLinkMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; createMerchantCenterAccountLink( - request: protos.google.cloud.retail.v2alpha.ICreateMerchantCenterAccountLinkRequest, - options: CallOptions, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.ICreateMerchantCenterAccountLinkRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IMerchantCenterAccountLink, + protos.google.cloud.retail.v2alpha.ICreateMerchantCenterAccountLinkMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; createMerchantCenterAccountLink( - request: protos.google.cloud.retail.v2alpha.ICreateMerchantCenterAccountLinkRequest, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.ICreateMerchantCenterAccountLinkRequest, + callback: Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IMerchantCenterAccountLink, + protos.google.cloud.retail.v2alpha.ICreateMerchantCenterAccountLinkMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; createMerchantCenterAccountLink( - request?: protos.google.cloud.retail.v2alpha.ICreateMerchantCenterAccountLinkRequest, - optionsOrCallback?: CallOptions|Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>, - callback?: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>|void { + request?: protos.google.cloud.retail.v2alpha.ICreateMerchantCenterAccountLinkRequest, + optionsOrCallback?: + | CallOptions + | Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IMerchantCenterAccountLink, + protos.google.cloud.retail.v2alpha.ICreateMerchantCenterAccountLinkMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + callback?: Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IMerchantCenterAccountLink, + protos.google.cloud.retail.v2alpha.ICreateMerchantCenterAccountLinkMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + LROperation< + protos.google.cloud.retail.v2alpha.IMerchantCenterAccountLink, + protos.google.cloud.retail.v2alpha.ICreateMerchantCenterAccountLinkMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IMerchantCenterAccountLink, + protos.google.cloud.retail.v2alpha.ICreateMerchantCenterAccountLinkMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, rawResponse, _) => { - this._log.info('createMerchantCenterAccountLink response %j', rawResponse); + this._log.info( + 'createMerchantCenterAccountLink response %j', + rawResponse, + ); callback!(error, response, rawResponse, _); // We verified `callback` above. } : undefined; this._log.info('createMerchantCenterAccountLink request %j', request); - return this.innerApiCalls.createMerchantCenterAccountLink(request, options, wrappedCallback) - ?.then(([response, rawResponse, _]: [ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]) => { - this._log.info('createMerchantCenterAccountLink response %j', rawResponse); - return [response, rawResponse, _]; - }); + return this.innerApiCalls + .createMerchantCenterAccountLink(request, options, wrappedCallback) + ?.then( + ([response, rawResponse, _]: [ + LROperation< + protos.google.cloud.retail.v2alpha.IMerchantCenterAccountLink, + protos.google.cloud.retail.v2alpha.ICreateMerchantCenterAccountLinkMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ]) => { + this._log.info( + 'createMerchantCenterAccountLink response %j', + rawResponse, + ); + return [response, rawResponse, _]; + }, + ); } -/** - * Check the status of the long running operation returned by `createMerchantCenterAccountLink()`. - * @param {String} name - * The operation name that will be passed. - * @returns {Promise} - The promise which resolves to an object. - * The decoded operation object has result and metadata field to get information from. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/merchant_center_account_link_service.create_merchant_center_account_link.js - * region_tag:retail_v2alpha_generated_MerchantCenterAccountLinkService_CreateMerchantCenterAccountLink_async - */ - async checkCreateMerchantCenterAccountLinkProgress(name: string): Promise>{ + /** + * Check the status of the long running operation returned by `createMerchantCenterAccountLink()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/merchant_center_account_link_service.create_merchant_center_account_link.js + * region_tag:retail_v2alpha_generated_MerchantCenterAccountLinkService_CreateMerchantCenterAccountLink_async + */ + async checkCreateMerchantCenterAccountLinkProgress( + name: string, + ): Promise< + LROperation< + protos.google.cloud.retail.v2alpha.MerchantCenterAccountLink, + protos.google.cloud.retail.v2alpha.CreateMerchantCenterAccountLinkMetadata + > + > { this._log.info('createMerchantCenterAccountLink long-running'); - const request = new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest({name}); + const request = + new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( + { name }, + ); const [operation] = await this.operationsClient.getOperation(request); - const decodeOperation = new this._gaxModule.Operation(operation, this.descriptors.longrunning.createMerchantCenterAccountLink, this._gaxModule.createDefaultBackoffSettings()); - return decodeOperation as LROperation; + const decodeOperation = new this._gaxModule.Operation( + operation, + this.descriptors.longrunning.createMerchantCenterAccountLink, + this._gaxModule.createDefaultBackoffSettings(), + ); + return decodeOperation as LROperation< + protos.google.cloud.retail.v2alpha.MerchantCenterAccountLink, + protos.google.cloud.retail.v2alpha.CreateMerchantCenterAccountLinkMetadata + >; } // -------------------- // -- Path templates -- @@ -731,7 +992,7 @@ export class MerchantCenterAccountLinkServiceClient { * @param {string} project * @returns {string} Resource name string. */ - alertConfigPath(project:string) { + alertConfigPath(project: string) { return this.pathTemplates.alertConfigPathTemplate.render({ project: project, }); @@ -745,7 +1006,8 @@ export class MerchantCenterAccountLinkServiceClient { * @returns {string} A string representing the project. */ matchProjectFromAlertConfigName(alertConfigName: string) { - return this.pathTemplates.alertConfigPathTemplate.match(alertConfigName).project; + return this.pathTemplates.alertConfigPathTemplate.match(alertConfigName) + .project; } /** @@ -756,7 +1018,7 @@ export class MerchantCenterAccountLinkServiceClient { * @param {string} catalog * @returns {string} Resource name string. */ - attributesConfigPath(project:string,location:string,catalog:string) { + attributesConfigPath(project: string, location: string, catalog: string) { return this.pathTemplates.attributesConfigPathTemplate.render({ project: project, location: location, @@ -772,7 +1034,9 @@ export class MerchantCenterAccountLinkServiceClient { * @returns {string} A string representing the project. */ matchProjectFromAttributesConfigName(attributesConfigName: string) { - return this.pathTemplates.attributesConfigPathTemplate.match(attributesConfigName).project; + return this.pathTemplates.attributesConfigPathTemplate.match( + attributesConfigName, + ).project; } /** @@ -783,7 +1047,9 @@ export class MerchantCenterAccountLinkServiceClient { * @returns {string} A string representing the location. */ matchLocationFromAttributesConfigName(attributesConfigName: string) { - return this.pathTemplates.attributesConfigPathTemplate.match(attributesConfigName).location; + return this.pathTemplates.attributesConfigPathTemplate.match( + attributesConfigName, + ).location; } /** @@ -794,7 +1060,9 @@ export class MerchantCenterAccountLinkServiceClient { * @returns {string} A string representing the catalog. */ matchCatalogFromAttributesConfigName(attributesConfigName: string) { - return this.pathTemplates.attributesConfigPathTemplate.match(attributesConfigName).catalog; + return this.pathTemplates.attributesConfigPathTemplate.match( + attributesConfigName, + ).catalog; } /** @@ -806,7 +1074,12 @@ export class MerchantCenterAccountLinkServiceClient { * @param {string} branch * @returns {string} Resource name string. */ - branchPath(project:string,location:string,catalog:string,branch:string) { + branchPath( + project: string, + location: string, + catalog: string, + branch: string, + ) { return this.pathTemplates.branchPathTemplate.render({ project: project, location: location, @@ -867,7 +1140,7 @@ export class MerchantCenterAccountLinkServiceClient { * @param {string} catalog * @returns {string} Resource name string. */ - catalogPath(project:string,location:string,catalog:string) { + catalogPath(project: string, location: string, catalog: string) { return this.pathTemplates.catalogPathTemplate.render({ project: project, location: location, @@ -916,7 +1189,7 @@ export class MerchantCenterAccountLinkServiceClient { * @param {string} catalog * @returns {string} Resource name string. */ - completionConfigPath(project:string,location:string,catalog:string) { + completionConfigPath(project: string, location: string, catalog: string) { return this.pathTemplates.completionConfigPathTemplate.render({ project: project, location: location, @@ -932,7 +1205,9 @@ export class MerchantCenterAccountLinkServiceClient { * @returns {string} A string representing the project. */ matchProjectFromCompletionConfigName(completionConfigName: string) { - return this.pathTemplates.completionConfigPathTemplate.match(completionConfigName).project; + return this.pathTemplates.completionConfigPathTemplate.match( + completionConfigName, + ).project; } /** @@ -943,7 +1218,9 @@ export class MerchantCenterAccountLinkServiceClient { * @returns {string} A string representing the location. */ matchLocationFromCompletionConfigName(completionConfigName: string) { - return this.pathTemplates.completionConfigPathTemplate.match(completionConfigName).location; + return this.pathTemplates.completionConfigPathTemplate.match( + completionConfigName, + ).location; } /** @@ -954,7 +1231,9 @@ export class MerchantCenterAccountLinkServiceClient { * @returns {string} A string representing the catalog. */ matchCatalogFromCompletionConfigName(completionConfigName: string) { - return this.pathTemplates.completionConfigPathTemplate.match(completionConfigName).catalog; + return this.pathTemplates.completionConfigPathTemplate.match( + completionConfigName, + ).catalog; } /** @@ -966,7 +1245,12 @@ export class MerchantCenterAccountLinkServiceClient { * @param {string} control * @returns {string} Resource name string. */ - controlPath(project:string,location:string,catalog:string,control:string) { + controlPath( + project: string, + location: string, + catalog: string, + control: string, + ) { return this.pathTemplates.controlPathTemplate.render({ project: project, location: location, @@ -1025,7 +1309,7 @@ export class MerchantCenterAccountLinkServiceClient { * @param {string} project * @returns {string} Resource name string. */ - loggingConfigPath(project:string) { + loggingConfigPath(project: string) { return this.pathTemplates.loggingConfigPathTemplate.render({ project: project, }); @@ -1039,7 +1323,8 @@ export class MerchantCenterAccountLinkServiceClient { * @returns {string} A string representing the project. */ matchProjectFromLoggingConfigName(loggingConfigName: string) { - return this.pathTemplates.loggingConfigPathTemplate.match(loggingConfigName).project; + return this.pathTemplates.loggingConfigPathTemplate.match(loggingConfigName) + .project; } /** @@ -1051,7 +1336,12 @@ export class MerchantCenterAccountLinkServiceClient { * @param {string} merchant_center_account_link * @returns {string} Resource name string. */ - merchantCenterAccountLinkPath(project:string,location:string,catalog:string,merchantCenterAccountLink:string) { + merchantCenterAccountLinkPath( + project: string, + location: string, + catalog: string, + merchantCenterAccountLink: string, + ) { return this.pathTemplates.merchantCenterAccountLinkPathTemplate.render({ project: project, location: location, @@ -1067,8 +1357,12 @@ export class MerchantCenterAccountLinkServiceClient { * A fully-qualified path representing MerchantCenterAccountLink resource. * @returns {string} A string representing the project. */ - matchProjectFromMerchantCenterAccountLinkName(merchantCenterAccountLinkName: string) { - return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match(merchantCenterAccountLinkName).project; + matchProjectFromMerchantCenterAccountLinkName( + merchantCenterAccountLinkName: string, + ) { + return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match( + merchantCenterAccountLinkName, + ).project; } /** @@ -1078,8 +1372,12 @@ export class MerchantCenterAccountLinkServiceClient { * A fully-qualified path representing MerchantCenterAccountLink resource. * @returns {string} A string representing the location. */ - matchLocationFromMerchantCenterAccountLinkName(merchantCenterAccountLinkName: string) { - return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match(merchantCenterAccountLinkName).location; + matchLocationFromMerchantCenterAccountLinkName( + merchantCenterAccountLinkName: string, + ) { + return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match( + merchantCenterAccountLinkName, + ).location; } /** @@ -1089,8 +1387,12 @@ export class MerchantCenterAccountLinkServiceClient { * A fully-qualified path representing MerchantCenterAccountLink resource. * @returns {string} A string representing the catalog. */ - matchCatalogFromMerchantCenterAccountLinkName(merchantCenterAccountLinkName: string) { - return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match(merchantCenterAccountLinkName).catalog; + matchCatalogFromMerchantCenterAccountLinkName( + merchantCenterAccountLinkName: string, + ) { + return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match( + merchantCenterAccountLinkName, + ).catalog; } /** @@ -1100,8 +1402,12 @@ export class MerchantCenterAccountLinkServiceClient { * A fully-qualified path representing MerchantCenterAccountLink resource. * @returns {string} A string representing the merchant_center_account_link. */ - matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName(merchantCenterAccountLinkName: string) { - return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match(merchantCenterAccountLinkName).merchant_center_account_link; + matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName( + merchantCenterAccountLinkName: string, + ) { + return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match( + merchantCenterAccountLinkName, + ).merchant_center_account_link; } /** @@ -1113,7 +1419,7 @@ export class MerchantCenterAccountLinkServiceClient { * @param {string} model * @returns {string} Resource name string. */ - modelPath(project:string,location:string,catalog:string,model:string) { + modelPath(project: string, location: string, catalog: string, model: string) { return this.pathTemplates.modelPathTemplate.render({ project: project, location: location, @@ -1176,7 +1482,13 @@ export class MerchantCenterAccountLinkServiceClient { * @param {string} product * @returns {string} Resource name string. */ - productPath(project:string,location:string,catalog:string,branch:string,product:string) { + productPath( + project: string, + location: string, + catalog: string, + branch: string, + product: string, + ) { return this.pathTemplates.productPathTemplate.render({ project: project, location: location, @@ -1247,7 +1559,7 @@ export class MerchantCenterAccountLinkServiceClient { * @param {string} project * @returns {string} Resource name string. */ - retailProjectPath(project:string) { + retailProjectPath(project: string) { return this.pathTemplates.retailProjectPathTemplate.render({ project: project, }); @@ -1261,7 +1573,8 @@ export class MerchantCenterAccountLinkServiceClient { * @returns {string} A string representing the project. */ matchProjectFromRetailProjectName(retailProjectName: string) { - return this.pathTemplates.retailProjectPathTemplate.match(retailProjectName).project; + return this.pathTemplates.retailProjectPathTemplate.match(retailProjectName) + .project; } /** @@ -1273,7 +1586,12 @@ export class MerchantCenterAccountLinkServiceClient { * @param {string} serving_config * @returns {string} Resource name string. */ - servingConfigPath(project:string,location:string,catalog:string,servingConfig:string) { + servingConfigPath( + project: string, + location: string, + catalog: string, + servingConfig: string, + ) { return this.pathTemplates.servingConfigPathTemplate.render({ project: project, location: location, @@ -1290,7 +1608,8 @@ export class MerchantCenterAccountLinkServiceClient { * @returns {string} A string representing the project. */ matchProjectFromServingConfigName(servingConfigName: string) { - return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName).project; + return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName) + .project; } /** @@ -1301,7 +1620,8 @@ export class MerchantCenterAccountLinkServiceClient { * @returns {string} A string representing the location. */ matchLocationFromServingConfigName(servingConfigName: string) { - return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName).location; + return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName) + .location; } /** @@ -1312,7 +1632,8 @@ export class MerchantCenterAccountLinkServiceClient { * @returns {string} A string representing the catalog. */ matchCatalogFromServingConfigName(servingConfigName: string) { - return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName).catalog; + return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName) + .catalog; } /** @@ -1323,7 +1644,8 @@ export class MerchantCenterAccountLinkServiceClient { * @returns {string} A string representing the serving_config. */ matchServingConfigFromServingConfigName(servingConfigName: string) { - return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName).serving_config; + return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName) + .serving_config; } /** @@ -1334,7 +1656,7 @@ export class MerchantCenterAccountLinkServiceClient { */ close(): Promise { if (this.merchantCenterAccountLinkServiceStub && !this._terminated) { - return this.merchantCenterAccountLinkServiceStub.then(stub => { + return this.merchantCenterAccountLinkServiceStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -1343,4 +1665,4 @@ export class MerchantCenterAccountLinkServiceClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/src/v2alpha/model_service_client.ts.baseline b/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/src/v2alpha/model_service_client.ts.baseline index 5b46fe83ea38..2d72da2f7fad 100644 --- a/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/src/v2alpha/model_service_client.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/src/v2alpha/model_service_client.ts.baseline @@ -18,15 +18,24 @@ /* global window */ import * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions, GrpcClientOptions, LROperation, PaginationCallback, GaxCall} from 'google-gax'; -import {Transform} from 'stream'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + GrpcClientOptions, + LROperation, + PaginationCallback, + GaxCall, +} from 'google-gax'; +import { Transform } from 'stream'; // @ts-ignore import type * as protos from '../../../protos/protos.js'; import * as model_service_client_config from './model_service_client_config.json'; import fs from 'fs'; import path from 'path'; -import {fileURLToPath} from 'url'; -import {getJSON} from '../json-helper.cjs'; +import { fileURLToPath } from 'url'; +import { getJSON } from '../json-helper.cjs'; // @ts-ignore const dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -36,15 +45,15 @@ const dirname = path.dirname(fileURLToPath(import.meta.url)); * This file defines retry strategy and timeouts for all API methods in this library. */ const gapicConfig = getJSON( - path.join(dirname, 'model_service_client_config.json') + path.join(dirname, 'model_service_client_config.json'), ); const jsonProtos = getJSON( - path.join(dirname, '..', '..', '..', 'protos/protos.json') + path.join(dirname, '..', '..', '..', 'protos/protos.json'), ); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; const version = getJSON( - path.join(dirname, '..', '..', '..', '..', 'package.json') + path.join(dirname, '..', '..', '..', '..', 'package.json'), ).version; /** @@ -70,7 +79,7 @@ export class ModelServiceClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('retail'); @@ -82,10 +91,10 @@ export class ModelServiceClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; operationsClient: gax.OperationsClient; - modelServiceStub?: Promise<{[name: string]: Function}>; + modelServiceStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of ModelServiceClient. @@ -127,21 +136,42 @@ export class ModelServiceClient { * const client = new ModelServiceClient({fallback: 'rest'}, gax); * ``` */ - constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { // Ensure that options include all the required fields. const staticMembers = this.constructor as typeof ModelServiceClient; - if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { - throw new Error('Please set either universe_domain or universeDomain, but not both.'); + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); } - const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; - this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; this._servicePath = 'retail.' + this._universeDomain; - const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; - const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. if (servicePath !== this._servicePath && !('scopes' in opts)) { @@ -163,7 +193,7 @@ export class ModelServiceClient { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; @@ -180,10 +210,7 @@ export class ModelServiceClient { const isEsm = true; const isEsmString = isEsm ? '-esm' : '-cjs'; // Determine the client header string. - const clientHeader = [ - `gax/${this._gaxModule.version}`, - `gapic/${version}`, - ]; + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/{process.versions.node}${isEsmString}`); } else { @@ -191,7 +218,7 @@ export class ModelServiceClient { } if (!opts.fallback) { clientHeader.push(`grpc/${this._gaxGrpc.grpcVersion}`); - } else if (opts.fallback === 'rest' ) { + } else if (opts.fallback === 'rest') { clientHeader.push(`rest/${this._gaxGrpc.grpcVersion}`); } if (opts.libName && opts.libVersion) { @@ -199,47 +226,49 @@ export class ModelServiceClient { } // Load the applicable protos. - this._protos = this._gaxGrpc.loadProtoJSON(jsonProtos as gax.protobuf.INamespace); + this._protos = this._gaxGrpc.loadProtoJSON( + jsonProtos as gax.protobuf.INamespace, + ); // This API contains "path templates"; forward-slash-separated // identifiers to uniquely identify resources within the API. // Create useful helper objects for these. this.pathTemplates = { alertConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/alertConfig' + 'projects/{project}/alertConfig', ), attributesConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/attributesConfig' + 'projects/{project}/locations/{location}/catalogs/{catalog}/attributesConfig', ), branchPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}', ), catalogPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}' + 'projects/{project}/locations/{location}/catalogs/{catalog}', ), completionConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/completionConfig' + 'projects/{project}/locations/{location}/catalogs/{catalog}/completionConfig', ), controlPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/controls/{control}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/controls/{control}', ), loggingConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/loggingConfig' + 'projects/{project}/loggingConfig', ), merchantCenterAccountLinkPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/merchantCenterAccountLinks/{merchant_center_account_link}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/merchantCenterAccountLinks/{merchant_center_account_link}', ), modelPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/models/{model}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/models/{model}', ), productPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}', ), retailProjectPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/retailProject' + 'projects/{project}/retailProject', ), servingConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/servingConfigs/{serving_config}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/servingConfigs/{serving_config}', ), }; @@ -247,8 +276,11 @@ export class ModelServiceClient { // (e.g. 50 results at a time, with tokens to get subsequent // pages). Denote the keys used for pagination and results. this.descriptors.page = { - listModels: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'models') + listModels: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'models', + ), }; const protoFilesRoot = this._gaxModule.protobufFromJSON(jsonProtos); @@ -257,39 +289,71 @@ export class ModelServiceClient { // rather than holding a request open. const lroOptions: GrpcClientOptions = { auth: this.auth, - grpc: 'grpc' in this._gaxGrpc ? this._gaxGrpc.grpc : undefined + grpc: 'grpc' in this._gaxGrpc ? this._gaxGrpc.grpc : undefined, }; if (opts.fallback === 'rest') { lroOptions.protoJson = protoFilesRoot; - lroOptions.httpRules = [{selector: 'google.longrunning.Operations.GetOperation',get: '/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*/operations/*}',additional_bindings: [{get: '/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*/places/*/operations/*}',},{get: '/v2alpha/{name=projects/*/locations/*/catalogs/*/operations/*}',},{get: '/v2alpha/{name=projects/*/locations/*/operations/*}',},{get: '/v2alpha/{name=projects/*/operations/*}',}], - },{selector: 'google.longrunning.Operations.ListOperations',get: '/v2alpha/{name=projects/*/locations/*/catalogs/*}/operations',additional_bindings: [{get: '/v2alpha/{name=projects/*/locations/*}/operations',},{get: '/v2alpha/{name=projects/*}/operations',}], - }]; + lroOptions.httpRules = [ + { + selector: 'google.longrunning.Operations.GetOperation', + get: '/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*/operations/*}', + additional_bindings: [ + { + get: '/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*/places/*/operations/*}', + }, + { + get: '/v2alpha/{name=projects/*/locations/*/catalogs/*/operations/*}', + }, + { get: '/v2alpha/{name=projects/*/locations/*/operations/*}' }, + { get: '/v2alpha/{name=projects/*/operations/*}' }, + ], + }, + { + selector: 'google.longrunning.Operations.ListOperations', + get: '/v2alpha/{name=projects/*/locations/*/catalogs/*}/operations', + additional_bindings: [ + { get: '/v2alpha/{name=projects/*/locations/*}/operations' }, + { get: '/v2alpha/{name=projects/*}/operations' }, + ], + }, + ]; } - this.operationsClient = this._gaxModule.lro(lroOptions).operationsClient(opts); + this.operationsClient = this._gaxModule + .lro(lroOptions) + .operationsClient(opts); const createModelResponse = protoFilesRoot.lookup( - '.google.cloud.retail.v2alpha.Model') as gax.protobuf.Type; + '.google.cloud.retail.v2alpha.Model', + ) as gax.protobuf.Type; const createModelMetadata = protoFilesRoot.lookup( - '.google.cloud.retail.v2alpha.CreateModelMetadata') as gax.protobuf.Type; + '.google.cloud.retail.v2alpha.CreateModelMetadata', + ) as gax.protobuf.Type; const tuneModelResponse = protoFilesRoot.lookup( - '.google.cloud.retail.v2alpha.TuneModelResponse') as gax.protobuf.Type; + '.google.cloud.retail.v2alpha.TuneModelResponse', + ) as gax.protobuf.Type; const tuneModelMetadata = protoFilesRoot.lookup( - '.google.cloud.retail.v2alpha.TuneModelMetadata') as gax.protobuf.Type; + '.google.cloud.retail.v2alpha.TuneModelMetadata', + ) as gax.protobuf.Type; this.descriptors.longrunning = { createModel: new this._gaxModule.LongrunningDescriptor( this.operationsClient, createModelResponse.decode.bind(createModelResponse), - createModelMetadata.decode.bind(createModelMetadata)), + createModelMetadata.decode.bind(createModelMetadata), + ), tuneModel: new this._gaxModule.LongrunningDescriptor( this.operationsClient, tuneModelResponse.decode.bind(tuneModelResponse), - tuneModelMetadata.decode.bind(tuneModelMetadata)) + tuneModelMetadata.decode.bind(tuneModelMetadata), + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.cloud.retail.v2alpha.ModelService', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.cloud.retail.v2alpha.ModelService', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + { 'x-goog-api-client': clientHeader.join(' ') }, + ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -320,28 +384,42 @@ export class ModelServiceClient { // Put together the "service stub" for // google.cloud.retail.v2alpha.ModelService. this.modelServiceStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.cloud.retail.v2alpha.ModelService') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.cloud.retail.v2alpha.ModelService', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.cloud.retail.v2alpha.ModelService, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts, + this._providedCustomServicePath, + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const modelServiceStubMethods = - ['createModel', 'getModel', 'pauseModel', 'resumeModel', 'deleteModel', 'listModels', 'updateModel', 'tuneModel']; + const modelServiceStubMethods = [ + 'createModel', + 'getModel', + 'pauseModel', + 'resumeModel', + 'deleteModel', + 'listModels', + 'updateModel', + 'tuneModel', + ]; for (const methodName of modelServiceStubMethods) { const callPromise = this.modelServiceStub.then( - stub => (...args: Array<{}>) => { - if (this._terminated) { - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error|null|undefined) => () => { + (stub) => + (...args: Array<{}>) => { + if (this._terminated) { + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { throw err; - }); + }, + ); const descriptor = this.descriptors.page[methodName] || @@ -351,7 +429,7 @@ export class ModelServiceClient { callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -366,8 +444,14 @@ export class ModelServiceClient { * @returns {string} The DNS address for this service. */ static get servicePath() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'retail.googleapis.com'; } @@ -379,8 +463,14 @@ export class ModelServiceClient { * @returns {string} The DNS address for this service. */ static get apiEndpoint() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'retail.googleapis.com'; } @@ -411,9 +501,7 @@ export class ModelServiceClient { * @returns {string[]} List of default scopes. */ static get scopes() { - return [ - 'https://www.googleapis.com/auth/cloud-platform' - ]; + return ['https://www.googleapis.com/auth/cloud-platform']; } getProjectId(): Promise; @@ -422,8 +510,9 @@ export class ModelServiceClient { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId(callback?: Callback): - Promise|void { + getProjectId( + callback?: Callback, + ): Promise | void { if (callback) { this.auth.getProjectId(callback); return; @@ -434,795 +523,1113 @@ export class ModelServiceClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Gets a model. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The resource name of the - * {@link protos.google.cloud.retail.v2alpha.Model|Model} to get. Format: - * `projects/{project_number}/locations/{location_id}/catalogs/{catalog}/models/{model_id}` - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.Model|Model}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/model_service.get_model.js - * region_tag:retail_v2alpha_generated_ModelService_GetModel_async - */ + /** + * Gets a model. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The resource name of the + * {@link protos.google.cloud.retail.v2alpha.Model|Model} to get. Format: + * `projects/{project_number}/locations/{location_id}/catalogs/{catalog}/models/{model_id}` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.Model|Model}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/model_service.get_model.js + * region_tag:retail_v2alpha_generated_ModelService_GetModel_async + */ getModel( - request?: protos.google.cloud.retail.v2alpha.IGetModelRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.retail.v2alpha.IModel, - protos.google.cloud.retail.v2alpha.IGetModelRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.IGetModelRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IModel, + protos.google.cloud.retail.v2alpha.IGetModelRequest | undefined, + {} | undefined, + ] + >; getModel( - request: protos.google.cloud.retail.v2alpha.IGetModelRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.retail.v2alpha.IModel, - protos.google.cloud.retail.v2alpha.IGetModelRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IGetModelRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.retail.v2alpha.IModel, + protos.google.cloud.retail.v2alpha.IGetModelRequest | null | undefined, + {} | null | undefined + >, + ): void; getModel( - request: protos.google.cloud.retail.v2alpha.IGetModelRequest, - callback: Callback< - protos.google.cloud.retail.v2alpha.IModel, - protos.google.cloud.retail.v2alpha.IGetModelRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IGetModelRequest, + callback: Callback< + protos.google.cloud.retail.v2alpha.IModel, + protos.google.cloud.retail.v2alpha.IGetModelRequest | null | undefined, + {} | null | undefined + >, + ): void; getModel( - request?: protos.google.cloud.retail.v2alpha.IGetModelRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.retail.v2alpha.IModel, - protos.google.cloud.retail.v2alpha.IGetModelRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.retail.v2alpha.IGetModelRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.retail.v2alpha.IModel, - protos.google.cloud.retail.v2alpha.IGetModelRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.retail.v2alpha.IModel, - protos.google.cloud.retail.v2alpha.IGetModelRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.retail.v2alpha.IGetModelRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.retail.v2alpha.IModel, + protos.google.cloud.retail.v2alpha.IGetModelRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IModel, + protos.google.cloud.retail.v2alpha.IGetModelRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getModel request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.retail.v2alpha.IModel, - protos.google.cloud.retail.v2alpha.IGetModelRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.retail.v2alpha.IModel, + | protos.google.cloud.retail.v2alpha.IGetModelRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getModel response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.getModel(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.retail.v2alpha.IModel, - protos.google.cloud.retail.v2alpha.IGetModelRequest|undefined, {}|undefined - ]) => { - this._log.info('getModel response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getModel(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.retail.v2alpha.IModel, + protos.google.cloud.retail.v2alpha.IGetModelRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getModel response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Pauses the training of an existing model. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The name of the model to pause. - * Format: - * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/models/{model_id}` - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.Model|Model}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/model_service.pause_model.js - * region_tag:retail_v2alpha_generated_ModelService_PauseModel_async - */ + /** + * Pauses the training of an existing model. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The name of the model to pause. + * Format: + * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/models/{model_id}` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.Model|Model}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/model_service.pause_model.js + * region_tag:retail_v2alpha_generated_ModelService_PauseModel_async + */ pauseModel( - request?: protos.google.cloud.retail.v2alpha.IPauseModelRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.retail.v2alpha.IModel, - protos.google.cloud.retail.v2alpha.IPauseModelRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.IPauseModelRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IModel, + protos.google.cloud.retail.v2alpha.IPauseModelRequest | undefined, + {} | undefined, + ] + >; pauseModel( - request: protos.google.cloud.retail.v2alpha.IPauseModelRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.retail.v2alpha.IModel, - protos.google.cloud.retail.v2alpha.IPauseModelRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IPauseModelRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.retail.v2alpha.IModel, + protos.google.cloud.retail.v2alpha.IPauseModelRequest | null | undefined, + {} | null | undefined + >, + ): void; pauseModel( - request: protos.google.cloud.retail.v2alpha.IPauseModelRequest, - callback: Callback< - protos.google.cloud.retail.v2alpha.IModel, - protos.google.cloud.retail.v2alpha.IPauseModelRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IPauseModelRequest, + callback: Callback< + protos.google.cloud.retail.v2alpha.IModel, + protos.google.cloud.retail.v2alpha.IPauseModelRequest | null | undefined, + {} | null | undefined + >, + ): void; pauseModel( - request?: protos.google.cloud.retail.v2alpha.IPauseModelRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.cloud.retail.v2alpha.IPauseModelRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.retail.v2alpha.IModel, - protos.google.cloud.retail.v2alpha.IPauseModelRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.cloud.retail.v2alpha.IModel, - protos.google.cloud.retail.v2alpha.IPauseModelRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.retail.v2alpha.IModel, - protos.google.cloud.retail.v2alpha.IPauseModelRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.retail.v2alpha.IPauseModelRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.retail.v2alpha.IModel, + protos.google.cloud.retail.v2alpha.IPauseModelRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IModel, + protos.google.cloud.retail.v2alpha.IPauseModelRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('pauseModel request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.retail.v2alpha.IModel, - protos.google.cloud.retail.v2alpha.IPauseModelRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.retail.v2alpha.IModel, + | protos.google.cloud.retail.v2alpha.IPauseModelRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('pauseModel response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.pauseModel(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.retail.v2alpha.IModel, - protos.google.cloud.retail.v2alpha.IPauseModelRequest|undefined, {}|undefined - ]) => { - this._log.info('pauseModel response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .pauseModel(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.retail.v2alpha.IModel, + protos.google.cloud.retail.v2alpha.IPauseModelRequest | undefined, + {} | undefined, + ]) => { + this._log.info('pauseModel response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Resumes the training of an existing model. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The name of the model to resume. - * Format: - * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/models/{model_id}` - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.Model|Model}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/model_service.resume_model.js - * region_tag:retail_v2alpha_generated_ModelService_ResumeModel_async - */ + /** + * Resumes the training of an existing model. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The name of the model to resume. + * Format: + * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/models/{model_id}` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.Model|Model}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/model_service.resume_model.js + * region_tag:retail_v2alpha_generated_ModelService_ResumeModel_async + */ resumeModel( - request?: protos.google.cloud.retail.v2alpha.IResumeModelRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.retail.v2alpha.IModel, - protos.google.cloud.retail.v2alpha.IResumeModelRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.IResumeModelRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IModel, + protos.google.cloud.retail.v2alpha.IResumeModelRequest | undefined, + {} | undefined, + ] + >; resumeModel( - request: protos.google.cloud.retail.v2alpha.IResumeModelRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.retail.v2alpha.IModel, - protos.google.cloud.retail.v2alpha.IResumeModelRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IResumeModelRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.retail.v2alpha.IModel, + protos.google.cloud.retail.v2alpha.IResumeModelRequest | null | undefined, + {} | null | undefined + >, + ): void; resumeModel( - request: protos.google.cloud.retail.v2alpha.IResumeModelRequest, - callback: Callback< - protos.google.cloud.retail.v2alpha.IModel, - protos.google.cloud.retail.v2alpha.IResumeModelRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IResumeModelRequest, + callback: Callback< + protos.google.cloud.retail.v2alpha.IModel, + protos.google.cloud.retail.v2alpha.IResumeModelRequest | null | undefined, + {} | null | undefined + >, + ): void; resumeModel( - request?: protos.google.cloud.retail.v2alpha.IResumeModelRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.retail.v2alpha.IModel, - protos.google.cloud.retail.v2alpha.IResumeModelRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.retail.v2alpha.IResumeModelRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.retail.v2alpha.IModel, - protos.google.cloud.retail.v2alpha.IResumeModelRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.retail.v2alpha.IModel, - protos.google.cloud.retail.v2alpha.IResumeModelRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.retail.v2alpha.IResumeModelRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.retail.v2alpha.IModel, + protos.google.cloud.retail.v2alpha.IResumeModelRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IModel, + protos.google.cloud.retail.v2alpha.IResumeModelRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('resumeModel request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.retail.v2alpha.IModel, - protos.google.cloud.retail.v2alpha.IResumeModelRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.retail.v2alpha.IModel, + | protos.google.cloud.retail.v2alpha.IResumeModelRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('resumeModel response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.resumeModel(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.retail.v2alpha.IModel, - protos.google.cloud.retail.v2alpha.IResumeModelRequest|undefined, {}|undefined - ]) => { - this._log.info('resumeModel response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .resumeModel(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.retail.v2alpha.IModel, + protos.google.cloud.retail.v2alpha.IResumeModelRequest | undefined, + {} | undefined, + ]) => { + this._log.info('resumeModel response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Deletes an existing model. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The resource name of the - * {@link protos.google.cloud.retail.v2alpha.Model|Model} to delete. Format: - * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/models/{model_id}` - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/model_service.delete_model.js - * region_tag:retail_v2alpha_generated_ModelService_DeleteModel_async - */ + /** + * Deletes an existing model. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The resource name of the + * {@link protos.google.cloud.retail.v2alpha.Model|Model} to delete. Format: + * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/models/{model_id}` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/model_service.delete_model.js + * region_tag:retail_v2alpha_generated_ModelService_DeleteModel_async + */ deleteModel( - request?: protos.google.cloud.retail.v2alpha.IDeleteModelRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.cloud.retail.v2alpha.IDeleteModelRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.IDeleteModelRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.cloud.retail.v2alpha.IDeleteModelRequest | undefined, + {} | undefined, + ] + >; deleteModel( - request: protos.google.cloud.retail.v2alpha.IDeleteModelRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.cloud.retail.v2alpha.IDeleteModelRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IDeleteModelRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.cloud.retail.v2alpha.IDeleteModelRequest | null | undefined, + {} | null | undefined + >, + ): void; deleteModel( - request: protos.google.cloud.retail.v2alpha.IDeleteModelRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.cloud.retail.v2alpha.IDeleteModelRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IDeleteModelRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.cloud.retail.v2alpha.IDeleteModelRequest | null | undefined, + {} | null | undefined + >, + ): void; deleteModel( - request?: protos.google.cloud.retail.v2alpha.IDeleteModelRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.protobuf.IEmpty, - protos.google.cloud.retail.v2alpha.IDeleteModelRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.retail.v2alpha.IDeleteModelRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.cloud.retail.v2alpha.IDeleteModelRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.cloud.retail.v2alpha.IDeleteModelRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.retail.v2alpha.IDeleteModelRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + protos.google.cloud.retail.v2alpha.IDeleteModelRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.cloud.retail.v2alpha.IDeleteModelRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('deleteModel request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.cloud.retail.v2alpha.IDeleteModelRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.cloud.retail.v2alpha.IDeleteModelRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteModel response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.deleteModel(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.cloud.retail.v2alpha.IDeleteModelRequest|undefined, {}|undefined - ]) => { - this._log.info('deleteModel response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteModel(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.cloud.retail.v2alpha.IDeleteModelRequest | undefined, + {} | undefined, + ]) => { + this._log.info('deleteModel response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Update of model metadata. Only fields that - * currently can be updated are: `filtering_option` and - * `periodic_tuning_state`. - * If other values are provided, this API method ignores them. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.cloud.retail.v2alpha.Model} request.model - * Required. The body of the updated - * {@link protos.google.cloud.retail.v2alpha.Model|Model}. - * @param {google.protobuf.FieldMask} [request.updateMask] - * Optional. Indicates which fields in the provided 'model' to - * update. If not set, by default updates all fields. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.Model|Model}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/model_service.update_model.js - * region_tag:retail_v2alpha_generated_ModelService_UpdateModel_async - */ + /** + * Update of model metadata. Only fields that + * currently can be updated are: `filtering_option` and + * `periodic_tuning_state`. + * If other values are provided, this API method ignores them. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.cloud.retail.v2alpha.Model} request.model + * Required. The body of the updated + * {@link protos.google.cloud.retail.v2alpha.Model|Model}. + * @param {google.protobuf.FieldMask} [request.updateMask] + * Optional. Indicates which fields in the provided 'model' to + * update. If not set, by default updates all fields. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.Model|Model}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/model_service.update_model.js + * region_tag:retail_v2alpha_generated_ModelService_UpdateModel_async + */ updateModel( - request?: protos.google.cloud.retail.v2alpha.IUpdateModelRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.retail.v2alpha.IModel, - protos.google.cloud.retail.v2alpha.IUpdateModelRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.IUpdateModelRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IModel, + protos.google.cloud.retail.v2alpha.IUpdateModelRequest | undefined, + {} | undefined, + ] + >; updateModel( - request: protos.google.cloud.retail.v2alpha.IUpdateModelRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.retail.v2alpha.IModel, - protos.google.cloud.retail.v2alpha.IUpdateModelRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IUpdateModelRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.retail.v2alpha.IModel, + protos.google.cloud.retail.v2alpha.IUpdateModelRequest | null | undefined, + {} | null | undefined + >, + ): void; updateModel( - request: protos.google.cloud.retail.v2alpha.IUpdateModelRequest, - callback: Callback< - protos.google.cloud.retail.v2alpha.IModel, - protos.google.cloud.retail.v2alpha.IUpdateModelRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IUpdateModelRequest, + callback: Callback< + protos.google.cloud.retail.v2alpha.IModel, + protos.google.cloud.retail.v2alpha.IUpdateModelRequest | null | undefined, + {} | null | undefined + >, + ): void; updateModel( - request?: protos.google.cloud.retail.v2alpha.IUpdateModelRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.cloud.retail.v2alpha.IUpdateModelRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.retail.v2alpha.IModel, - protos.google.cloud.retail.v2alpha.IUpdateModelRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.cloud.retail.v2alpha.IModel, - protos.google.cloud.retail.v2alpha.IUpdateModelRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.retail.v2alpha.IModel, - protos.google.cloud.retail.v2alpha.IUpdateModelRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.retail.v2alpha.IUpdateModelRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.retail.v2alpha.IModel, + protos.google.cloud.retail.v2alpha.IUpdateModelRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IModel, + protos.google.cloud.retail.v2alpha.IUpdateModelRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'model.name': request.model!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'model.name': request.model!.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateModel request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.retail.v2alpha.IModel, - protos.google.cloud.retail.v2alpha.IUpdateModelRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.retail.v2alpha.IModel, + | protos.google.cloud.retail.v2alpha.IUpdateModelRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateModel response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.updateModel(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.retail.v2alpha.IModel, - protos.google.cloud.retail.v2alpha.IUpdateModelRequest|undefined, {}|undefined - ]) => { - this._log.info('updateModel response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateModel(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.retail.v2alpha.IModel, + protos.google.cloud.retail.v2alpha.IUpdateModelRequest | undefined, + {} | undefined, + ]) => { + this._log.info('updateModel response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Creates a new model. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent resource under which to create the model. Format: - * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}` - * @param {google.cloud.retail.v2alpha.Model} request.model - * Required. The payload of the {@link protos.google.cloud.retail.v2alpha.Model|Model} to - * create. - * @param {boolean} [request.dryRun] - * Optional. Whether to run a dry run to validate the request (without - * actually creating the model). - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing - * a long running operation. Its `promise()` method returns a promise - * you can `await` for. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/model_service.create_model.js - * region_tag:retail_v2alpha_generated_ModelService_CreateModel_async - */ + /** + * Creates a new model. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource under which to create the model. Format: + * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}` + * @param {google.cloud.retail.v2alpha.Model} request.model + * Required. The payload of the {@link protos.google.cloud.retail.v2alpha.Model|Model} to + * create. + * @param {boolean} [request.dryRun] + * Optional. Whether to run a dry run to validate the request (without + * actually creating the model). + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/model_service.create_model.js + * region_tag:retail_v2alpha_generated_ModelService_CreateModel_async + */ createModel( - request?: protos.google.cloud.retail.v2alpha.ICreateModelRequest, - options?: CallOptions): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.ICreateModelRequest, + options?: CallOptions, + ): Promise< + [ + LROperation< + protos.google.cloud.retail.v2alpha.IModel, + protos.google.cloud.retail.v2alpha.ICreateModelMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; createModel( - request: protos.google.cloud.retail.v2alpha.ICreateModelRequest, - options: CallOptions, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.ICreateModelRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IModel, + protos.google.cloud.retail.v2alpha.ICreateModelMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; createModel( - request: protos.google.cloud.retail.v2alpha.ICreateModelRequest, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.ICreateModelRequest, + callback: Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IModel, + protos.google.cloud.retail.v2alpha.ICreateModelMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; createModel( - request?: protos.google.cloud.retail.v2alpha.ICreateModelRequest, - optionsOrCallback?: CallOptions|Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>, - callback?: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>|void { + request?: protos.google.cloud.retail.v2alpha.ICreateModelRequest, + optionsOrCallback?: + | CallOptions + | Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IModel, + protos.google.cloud.retail.v2alpha.ICreateModelMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + callback?: Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IModel, + protos.google.cloud.retail.v2alpha.ICreateModelMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + LROperation< + protos.google.cloud.retail.v2alpha.IModel, + protos.google.cloud.retail.v2alpha.ICreateModelMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IModel, + protos.google.cloud.retail.v2alpha.ICreateModelMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, rawResponse, _) => { this._log.info('createModel response %j', rawResponse); callback!(error, response, rawResponse, _); // We verified `callback` above. } : undefined; this._log.info('createModel request %j', request); - return this.innerApiCalls.createModel(request, options, wrappedCallback) - ?.then(([response, rawResponse, _]: [ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]) => { - this._log.info('createModel response %j', rawResponse); - return [response, rawResponse, _]; - }); + return this.innerApiCalls + .createModel(request, options, wrappedCallback) + ?.then( + ([response, rawResponse, _]: [ + LROperation< + protos.google.cloud.retail.v2alpha.IModel, + protos.google.cloud.retail.v2alpha.ICreateModelMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ]) => { + this._log.info('createModel response %j', rawResponse); + return [response, rawResponse, _]; + }, + ); } -/** - * Check the status of the long running operation returned by `createModel()`. - * @param {String} name - * The operation name that will be passed. - * @returns {Promise} - The promise which resolves to an object. - * The decoded operation object has result and metadata field to get information from. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/model_service.create_model.js - * region_tag:retail_v2alpha_generated_ModelService_CreateModel_async - */ - async checkCreateModelProgress(name: string): Promise>{ + /** + * Check the status of the long running operation returned by `createModel()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/model_service.create_model.js + * region_tag:retail_v2alpha_generated_ModelService_CreateModel_async + */ + async checkCreateModelProgress( + name: string, + ): Promise< + LROperation< + protos.google.cloud.retail.v2alpha.Model, + protos.google.cloud.retail.v2alpha.CreateModelMetadata + > + > { this._log.info('createModel long-running'); - const request = new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest({name}); + const request = + new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( + { name }, + ); const [operation] = await this.operationsClient.getOperation(request); - const decodeOperation = new this._gaxModule.Operation(operation, this.descriptors.longrunning.createModel, this._gaxModule.createDefaultBackoffSettings()); - return decodeOperation as LROperation; + const decodeOperation = new this._gaxModule.Operation( + operation, + this.descriptors.longrunning.createModel, + this._gaxModule.createDefaultBackoffSettings(), + ); + return decodeOperation as LROperation< + protos.google.cloud.retail.v2alpha.Model, + protos.google.cloud.retail.v2alpha.CreateModelMetadata + >; } -/** - * Tunes an existing model. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The resource name of the model to tune. - * Format: - * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/models/{model_id}` - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing - * a long running operation. Its `promise()` method returns a promise - * you can `await` for. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/model_service.tune_model.js - * region_tag:retail_v2alpha_generated_ModelService_TuneModel_async - */ + /** + * Tunes an existing model. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The resource name of the model to tune. + * Format: + * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/models/{model_id}` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/model_service.tune_model.js + * region_tag:retail_v2alpha_generated_ModelService_TuneModel_async + */ tuneModel( - request?: protos.google.cloud.retail.v2alpha.ITuneModelRequest, - options?: CallOptions): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.ITuneModelRequest, + options?: CallOptions, + ): Promise< + [ + LROperation< + protos.google.cloud.retail.v2alpha.ITuneModelResponse, + protos.google.cloud.retail.v2alpha.ITuneModelMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; tuneModel( - request: protos.google.cloud.retail.v2alpha.ITuneModelRequest, - options: CallOptions, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.ITuneModelRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.cloud.retail.v2alpha.ITuneModelResponse, + protos.google.cloud.retail.v2alpha.ITuneModelMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; tuneModel( - request: protos.google.cloud.retail.v2alpha.ITuneModelRequest, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.ITuneModelRequest, + callback: Callback< + LROperation< + protos.google.cloud.retail.v2alpha.ITuneModelResponse, + protos.google.cloud.retail.v2alpha.ITuneModelMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; tuneModel( - request?: protos.google.cloud.retail.v2alpha.ITuneModelRequest, - optionsOrCallback?: CallOptions|Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>, - callback?: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>|void { + request?: protos.google.cloud.retail.v2alpha.ITuneModelRequest, + optionsOrCallback?: + | CallOptions + | Callback< + LROperation< + protos.google.cloud.retail.v2alpha.ITuneModelResponse, + protos.google.cloud.retail.v2alpha.ITuneModelMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + callback?: Callback< + LROperation< + protos.google.cloud.retail.v2alpha.ITuneModelResponse, + protos.google.cloud.retail.v2alpha.ITuneModelMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + LROperation< + protos.google.cloud.retail.v2alpha.ITuneModelResponse, + protos.google.cloud.retail.v2alpha.ITuneModelMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + LROperation< + protos.google.cloud.retail.v2alpha.ITuneModelResponse, + protos.google.cloud.retail.v2alpha.ITuneModelMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, rawResponse, _) => { this._log.info('tuneModel response %j', rawResponse); callback!(error, response, rawResponse, _); // We verified `callback` above. } : undefined; this._log.info('tuneModel request %j', request); - return this.innerApiCalls.tuneModel(request, options, wrappedCallback) - ?.then(([response, rawResponse, _]: [ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]) => { - this._log.info('tuneModel response %j', rawResponse); - return [response, rawResponse, _]; - }); + return this.innerApiCalls + .tuneModel(request, options, wrappedCallback) + ?.then( + ([response, rawResponse, _]: [ + LROperation< + protos.google.cloud.retail.v2alpha.ITuneModelResponse, + protos.google.cloud.retail.v2alpha.ITuneModelMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ]) => { + this._log.info('tuneModel response %j', rawResponse); + return [response, rawResponse, _]; + }, + ); } -/** - * Check the status of the long running operation returned by `tuneModel()`. - * @param {String} name - * The operation name that will be passed. - * @returns {Promise} - The promise which resolves to an object. - * The decoded operation object has result and metadata field to get information from. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/model_service.tune_model.js - * region_tag:retail_v2alpha_generated_ModelService_TuneModel_async - */ - async checkTuneModelProgress(name: string): Promise>{ + /** + * Check the status of the long running operation returned by `tuneModel()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/model_service.tune_model.js + * region_tag:retail_v2alpha_generated_ModelService_TuneModel_async + */ + async checkTuneModelProgress( + name: string, + ): Promise< + LROperation< + protos.google.cloud.retail.v2alpha.TuneModelResponse, + protos.google.cloud.retail.v2alpha.TuneModelMetadata + > + > { this._log.info('tuneModel long-running'); - const request = new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest({name}); + const request = + new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( + { name }, + ); const [operation] = await this.operationsClient.getOperation(request); - const decodeOperation = new this._gaxModule.Operation(operation, this.descriptors.longrunning.tuneModel, this._gaxModule.createDefaultBackoffSettings()); - return decodeOperation as LROperation; + const decodeOperation = new this._gaxModule.Operation( + operation, + this.descriptors.longrunning.tuneModel, + this._gaxModule.createDefaultBackoffSettings(), + ); + return decodeOperation as LROperation< + protos.google.cloud.retail.v2alpha.TuneModelResponse, + protos.google.cloud.retail.v2alpha.TuneModelMetadata + >; } - /** - * Lists all the models linked to this event store. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent for which to list models. - * Format: - * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}` - * @param {number} [request.pageSize] - * Optional. Maximum number of results to return. If unspecified, defaults - * to 50. Max allowed value is 1000. - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous `ListModels` - * call. Provide this to retrieve the subsequent page. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.cloud.retail.v2alpha.Model|Model}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `listModelsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Lists all the models linked to this event store. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent for which to list models. + * Format: + * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}` + * @param {number} [request.pageSize] + * Optional. Maximum number of results to return. If unspecified, defaults + * to 50. Max allowed value is 1000. + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListModels` + * call. Provide this to retrieve the subsequent page. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.cloud.retail.v2alpha.Model|Model}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listModelsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listModels( - request?: protos.google.cloud.retail.v2alpha.IListModelsRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.retail.v2alpha.IModel[], - protos.google.cloud.retail.v2alpha.IListModelsRequest|null, - protos.google.cloud.retail.v2alpha.IListModelsResponse - ]>; + request?: protos.google.cloud.retail.v2alpha.IListModelsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IModel[], + protos.google.cloud.retail.v2alpha.IListModelsRequest | null, + protos.google.cloud.retail.v2alpha.IListModelsResponse, + ] + >; listModels( - request: protos.google.cloud.retail.v2alpha.IListModelsRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.cloud.retail.v2alpha.IListModelsRequest, - protos.google.cloud.retail.v2alpha.IListModelsResponse|null|undefined, - protos.google.cloud.retail.v2alpha.IModel>): void; + request: protos.google.cloud.retail.v2alpha.IListModelsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.cloud.retail.v2alpha.IListModelsRequest, + protos.google.cloud.retail.v2alpha.IListModelsResponse | null | undefined, + protos.google.cloud.retail.v2alpha.IModel + >, + ): void; listModels( - request: protos.google.cloud.retail.v2alpha.IListModelsRequest, - callback: PaginationCallback< - protos.google.cloud.retail.v2alpha.IListModelsRequest, - protos.google.cloud.retail.v2alpha.IListModelsResponse|null|undefined, - protos.google.cloud.retail.v2alpha.IModel>): void; + request: protos.google.cloud.retail.v2alpha.IListModelsRequest, + callback: PaginationCallback< + protos.google.cloud.retail.v2alpha.IListModelsRequest, + protos.google.cloud.retail.v2alpha.IListModelsResponse | null | undefined, + protos.google.cloud.retail.v2alpha.IModel + >, + ): void; listModels( - request?: protos.google.cloud.retail.v2alpha.IListModelsRequest, - optionsOrCallback?: CallOptions|PaginationCallback< - protos.google.cloud.retail.v2alpha.IListModelsRequest, - protos.google.cloud.retail.v2alpha.IListModelsResponse|null|undefined, - protos.google.cloud.retail.v2alpha.IModel>, - callback?: PaginationCallback< + request?: protos.google.cloud.retail.v2alpha.IListModelsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.cloud.retail.v2alpha.IListModelsRequest, - protos.google.cloud.retail.v2alpha.IListModelsResponse|null|undefined, - protos.google.cloud.retail.v2alpha.IModel>): - Promise<[ - protos.google.cloud.retail.v2alpha.IModel[], - protos.google.cloud.retail.v2alpha.IListModelsRequest|null, - protos.google.cloud.retail.v2alpha.IListModelsResponse - ]>|void { + | protos.google.cloud.retail.v2alpha.IListModelsResponse + | null + | undefined, + protos.google.cloud.retail.v2alpha.IModel + >, + callback?: PaginationCallback< + protos.google.cloud.retail.v2alpha.IListModelsRequest, + protos.google.cloud.retail.v2alpha.IListModelsResponse | null | undefined, + protos.google.cloud.retail.v2alpha.IModel + >, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IModel[], + protos.google.cloud.retail.v2alpha.IListModelsRequest | null, + protos.google.cloud.retail.v2alpha.IListModelsResponse, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.cloud.retail.v2alpha.IListModelsRequest, - protos.google.cloud.retail.v2alpha.IListModelsResponse|null|undefined, - protos.google.cloud.retail.v2alpha.IModel>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.cloud.retail.v2alpha.IListModelsRequest, + | protos.google.cloud.retail.v2alpha.IListModelsResponse + | null + | undefined, + protos.google.cloud.retail.v2alpha.IModel + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listModels values %j', values); callback!(error, values, nextPageRequest, rawResponse); @@ -1231,114 +1638,118 @@ export class ModelServiceClient { this._log.info('listModels request %j', request); return this.innerApiCalls .listModels(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.cloud.retail.v2alpha.IModel[], - protos.google.cloud.retail.v2alpha.IListModelsRequest|null, - protos.google.cloud.retail.v2alpha.IListModelsResponse - ]) => { - this._log.info('listModels values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.cloud.retail.v2alpha.IModel[], + protos.google.cloud.retail.v2alpha.IListModelsRequest | null, + protos.google.cloud.retail.v2alpha.IListModelsResponse, + ]) => { + this._log.info('listModels values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listModels`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent for which to list models. - * Format: - * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}` - * @param {number} [request.pageSize] - * Optional. Maximum number of results to return. If unspecified, defaults - * to 50. Max allowed value is 1000. - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous `ListModels` - * call. Provide this to retrieve the subsequent page. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.cloud.retail.v2alpha.Model|Model} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `listModelsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `listModels`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent for which to list models. + * Format: + * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}` + * @param {number} [request.pageSize] + * Optional. Maximum number of results to return. If unspecified, defaults + * to 50. Max allowed value is 1000. + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListModels` + * call. Provide this to retrieve the subsequent page. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.cloud.retail.v2alpha.Model|Model} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listModelsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listModelsStream( - request?: protos.google.cloud.retail.v2alpha.IListModelsRequest, - options?: CallOptions): - Transform{ + request?: protos.google.cloud.retail.v2alpha.IListModelsRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); const defaultCallSettings = this._defaults['listModels']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listModels stream %j', request); return this.descriptors.page.listModels.createStream( this.innerApiCalls.listModels as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listModels`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent for which to list models. - * Format: - * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}` - * @param {number} [request.pageSize] - * Optional. Maximum number of results to return. If unspecified, defaults - * to 50. Max allowed value is 1000. - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous `ListModels` - * call. Provide this to retrieve the subsequent page. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.cloud.retail.v2alpha.Model|Model}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/model_service.list_models.js - * region_tag:retail_v2alpha_generated_ModelService_ListModels_async - */ + /** + * Equivalent to `listModels`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent for which to list models. + * Format: + * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}` + * @param {number} [request.pageSize] + * Optional. Maximum number of results to return. If unspecified, defaults + * to 50. Max allowed value is 1000. + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListModels` + * call. Provide this to retrieve the subsequent page. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.cloud.retail.v2alpha.Model|Model}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/model_service.list_models.js + * region_tag:retail_v2alpha_generated_ModelService_ListModels_async + */ listModelsAsync( - request?: protos.google.cloud.retail.v2alpha.IListModelsRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.cloud.retail.v2alpha.IListModelsRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); const defaultCallSettings = this._defaults['listModels']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listModels iterate %j', request); return this.descriptors.page.listModels.asyncIterate( this.innerApiCalls['listModels'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } // -------------------- @@ -1351,7 +1762,7 @@ export class ModelServiceClient { * @param {string} project * @returns {string} Resource name string. */ - alertConfigPath(project:string) { + alertConfigPath(project: string) { return this.pathTemplates.alertConfigPathTemplate.render({ project: project, }); @@ -1365,7 +1776,8 @@ export class ModelServiceClient { * @returns {string} A string representing the project. */ matchProjectFromAlertConfigName(alertConfigName: string) { - return this.pathTemplates.alertConfigPathTemplate.match(alertConfigName).project; + return this.pathTemplates.alertConfigPathTemplate.match(alertConfigName) + .project; } /** @@ -1376,7 +1788,7 @@ export class ModelServiceClient { * @param {string} catalog * @returns {string} Resource name string. */ - attributesConfigPath(project:string,location:string,catalog:string) { + attributesConfigPath(project: string, location: string, catalog: string) { return this.pathTemplates.attributesConfigPathTemplate.render({ project: project, location: location, @@ -1392,7 +1804,9 @@ export class ModelServiceClient { * @returns {string} A string representing the project. */ matchProjectFromAttributesConfigName(attributesConfigName: string) { - return this.pathTemplates.attributesConfigPathTemplate.match(attributesConfigName).project; + return this.pathTemplates.attributesConfigPathTemplate.match( + attributesConfigName, + ).project; } /** @@ -1403,7 +1817,9 @@ export class ModelServiceClient { * @returns {string} A string representing the location. */ matchLocationFromAttributesConfigName(attributesConfigName: string) { - return this.pathTemplates.attributesConfigPathTemplate.match(attributesConfigName).location; + return this.pathTemplates.attributesConfigPathTemplate.match( + attributesConfigName, + ).location; } /** @@ -1414,7 +1830,9 @@ export class ModelServiceClient { * @returns {string} A string representing the catalog. */ matchCatalogFromAttributesConfigName(attributesConfigName: string) { - return this.pathTemplates.attributesConfigPathTemplate.match(attributesConfigName).catalog; + return this.pathTemplates.attributesConfigPathTemplate.match( + attributesConfigName, + ).catalog; } /** @@ -1426,7 +1844,12 @@ export class ModelServiceClient { * @param {string} branch * @returns {string} Resource name string. */ - branchPath(project:string,location:string,catalog:string,branch:string) { + branchPath( + project: string, + location: string, + catalog: string, + branch: string, + ) { return this.pathTemplates.branchPathTemplate.render({ project: project, location: location, @@ -1487,7 +1910,7 @@ export class ModelServiceClient { * @param {string} catalog * @returns {string} Resource name string. */ - catalogPath(project:string,location:string,catalog:string) { + catalogPath(project: string, location: string, catalog: string) { return this.pathTemplates.catalogPathTemplate.render({ project: project, location: location, @@ -1536,7 +1959,7 @@ export class ModelServiceClient { * @param {string} catalog * @returns {string} Resource name string. */ - completionConfigPath(project:string,location:string,catalog:string) { + completionConfigPath(project: string, location: string, catalog: string) { return this.pathTemplates.completionConfigPathTemplate.render({ project: project, location: location, @@ -1552,7 +1975,9 @@ export class ModelServiceClient { * @returns {string} A string representing the project. */ matchProjectFromCompletionConfigName(completionConfigName: string) { - return this.pathTemplates.completionConfigPathTemplate.match(completionConfigName).project; + return this.pathTemplates.completionConfigPathTemplate.match( + completionConfigName, + ).project; } /** @@ -1563,7 +1988,9 @@ export class ModelServiceClient { * @returns {string} A string representing the location. */ matchLocationFromCompletionConfigName(completionConfigName: string) { - return this.pathTemplates.completionConfigPathTemplate.match(completionConfigName).location; + return this.pathTemplates.completionConfigPathTemplate.match( + completionConfigName, + ).location; } /** @@ -1574,7 +2001,9 @@ export class ModelServiceClient { * @returns {string} A string representing the catalog. */ matchCatalogFromCompletionConfigName(completionConfigName: string) { - return this.pathTemplates.completionConfigPathTemplate.match(completionConfigName).catalog; + return this.pathTemplates.completionConfigPathTemplate.match( + completionConfigName, + ).catalog; } /** @@ -1586,7 +2015,12 @@ export class ModelServiceClient { * @param {string} control * @returns {string} Resource name string. */ - controlPath(project:string,location:string,catalog:string,control:string) { + controlPath( + project: string, + location: string, + catalog: string, + control: string, + ) { return this.pathTemplates.controlPathTemplate.render({ project: project, location: location, @@ -1645,7 +2079,7 @@ export class ModelServiceClient { * @param {string} project * @returns {string} Resource name string. */ - loggingConfigPath(project:string) { + loggingConfigPath(project: string) { return this.pathTemplates.loggingConfigPathTemplate.render({ project: project, }); @@ -1659,7 +2093,8 @@ export class ModelServiceClient { * @returns {string} A string representing the project. */ matchProjectFromLoggingConfigName(loggingConfigName: string) { - return this.pathTemplates.loggingConfigPathTemplate.match(loggingConfigName).project; + return this.pathTemplates.loggingConfigPathTemplate.match(loggingConfigName) + .project; } /** @@ -1671,7 +2106,12 @@ export class ModelServiceClient { * @param {string} merchant_center_account_link * @returns {string} Resource name string. */ - merchantCenterAccountLinkPath(project:string,location:string,catalog:string,merchantCenterAccountLink:string) { + merchantCenterAccountLinkPath( + project: string, + location: string, + catalog: string, + merchantCenterAccountLink: string, + ) { return this.pathTemplates.merchantCenterAccountLinkPathTemplate.render({ project: project, location: location, @@ -1687,8 +2127,12 @@ export class ModelServiceClient { * A fully-qualified path representing MerchantCenterAccountLink resource. * @returns {string} A string representing the project. */ - matchProjectFromMerchantCenterAccountLinkName(merchantCenterAccountLinkName: string) { - return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match(merchantCenterAccountLinkName).project; + matchProjectFromMerchantCenterAccountLinkName( + merchantCenterAccountLinkName: string, + ) { + return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match( + merchantCenterAccountLinkName, + ).project; } /** @@ -1698,8 +2142,12 @@ export class ModelServiceClient { * A fully-qualified path representing MerchantCenterAccountLink resource. * @returns {string} A string representing the location. */ - matchLocationFromMerchantCenterAccountLinkName(merchantCenterAccountLinkName: string) { - return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match(merchantCenterAccountLinkName).location; + matchLocationFromMerchantCenterAccountLinkName( + merchantCenterAccountLinkName: string, + ) { + return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match( + merchantCenterAccountLinkName, + ).location; } /** @@ -1709,8 +2157,12 @@ export class ModelServiceClient { * A fully-qualified path representing MerchantCenterAccountLink resource. * @returns {string} A string representing the catalog. */ - matchCatalogFromMerchantCenterAccountLinkName(merchantCenterAccountLinkName: string) { - return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match(merchantCenterAccountLinkName).catalog; + matchCatalogFromMerchantCenterAccountLinkName( + merchantCenterAccountLinkName: string, + ) { + return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match( + merchantCenterAccountLinkName, + ).catalog; } /** @@ -1720,8 +2172,12 @@ export class ModelServiceClient { * A fully-qualified path representing MerchantCenterAccountLink resource. * @returns {string} A string representing the merchant_center_account_link. */ - matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName(merchantCenterAccountLinkName: string) { - return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match(merchantCenterAccountLinkName).merchant_center_account_link; + matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName( + merchantCenterAccountLinkName: string, + ) { + return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match( + merchantCenterAccountLinkName, + ).merchant_center_account_link; } /** @@ -1733,7 +2189,7 @@ export class ModelServiceClient { * @param {string} model * @returns {string} Resource name string. */ - modelPath(project:string,location:string,catalog:string,model:string) { + modelPath(project: string, location: string, catalog: string, model: string) { return this.pathTemplates.modelPathTemplate.render({ project: project, location: location, @@ -1796,7 +2252,13 @@ export class ModelServiceClient { * @param {string} product * @returns {string} Resource name string. */ - productPath(project:string,location:string,catalog:string,branch:string,product:string) { + productPath( + project: string, + location: string, + catalog: string, + branch: string, + product: string, + ) { return this.pathTemplates.productPathTemplate.render({ project: project, location: location, @@ -1867,7 +2329,7 @@ export class ModelServiceClient { * @param {string} project * @returns {string} Resource name string. */ - retailProjectPath(project:string) { + retailProjectPath(project: string) { return this.pathTemplates.retailProjectPathTemplate.render({ project: project, }); @@ -1881,7 +2343,8 @@ export class ModelServiceClient { * @returns {string} A string representing the project. */ matchProjectFromRetailProjectName(retailProjectName: string) { - return this.pathTemplates.retailProjectPathTemplate.match(retailProjectName).project; + return this.pathTemplates.retailProjectPathTemplate.match(retailProjectName) + .project; } /** @@ -1893,7 +2356,12 @@ export class ModelServiceClient { * @param {string} serving_config * @returns {string} Resource name string. */ - servingConfigPath(project:string,location:string,catalog:string,servingConfig:string) { + servingConfigPath( + project: string, + location: string, + catalog: string, + servingConfig: string, + ) { return this.pathTemplates.servingConfigPathTemplate.render({ project: project, location: location, @@ -1910,7 +2378,8 @@ export class ModelServiceClient { * @returns {string} A string representing the project. */ matchProjectFromServingConfigName(servingConfigName: string) { - return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName).project; + return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName) + .project; } /** @@ -1921,7 +2390,8 @@ export class ModelServiceClient { * @returns {string} A string representing the location. */ matchLocationFromServingConfigName(servingConfigName: string) { - return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName).location; + return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName) + .location; } /** @@ -1932,7 +2402,8 @@ export class ModelServiceClient { * @returns {string} A string representing the catalog. */ matchCatalogFromServingConfigName(servingConfigName: string) { - return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName).catalog; + return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName) + .catalog; } /** @@ -1943,7 +2414,8 @@ export class ModelServiceClient { * @returns {string} A string representing the serving_config. */ matchServingConfigFromServingConfigName(servingConfigName: string) { - return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName).serving_config; + return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName) + .serving_config; } /** @@ -1954,7 +2426,7 @@ export class ModelServiceClient { */ close(): Promise { if (this.modelServiceStub && !this._terminated) { - return this.modelServiceStub.then(stub => { + return this.modelServiceStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -1963,4 +2435,4 @@ export class ModelServiceClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/src/v2alpha/prediction_service_client.ts.baseline b/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/src/v2alpha/prediction_service_client.ts.baseline index 8d59a986cc28..bd3096d91dad 100644 --- a/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/src/v2alpha/prediction_service_client.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/src/v2alpha/prediction_service_client.ts.baseline @@ -18,15 +18,20 @@ /* global window */ import * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions} from 'google-gax'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, +} from 'google-gax'; // @ts-ignore import type * as protos from '../../../protos/protos.js'; import * as prediction_service_client_config from './prediction_service_client_config.json'; import fs from 'fs'; import path from 'path'; -import {fileURLToPath} from 'url'; -import {getJSON} from '../json-helper.cjs'; +import { fileURLToPath } from 'url'; +import { getJSON } from '../json-helper.cjs'; // @ts-ignore const dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -36,15 +41,15 @@ const dirname = path.dirname(fileURLToPath(import.meta.url)); * This file defines retry strategy and timeouts for all API methods in this library. */ const gapicConfig = getJSON( - path.join(dirname, 'prediction_service_client_config.json') + path.join(dirname, 'prediction_service_client_config.json'), ); const jsonProtos = getJSON( - path.join(dirname, '..', '..', '..', 'protos/protos.json') + path.join(dirname, '..', '..', '..', 'protos/protos.json'), ); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; const version = getJSON( - path.join(dirname, '..', '..', '..', '..', 'package.json') + path.join(dirname, '..', '..', '..', '..', 'package.json'), ).version; /** @@ -59,7 +64,7 @@ export class PredictionServiceClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('retail'); @@ -71,9 +76,9 @@ export class PredictionServiceClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; - predictionServiceStub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; + predictionServiceStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of PredictionServiceClient. @@ -115,21 +120,42 @@ export class PredictionServiceClient { * const client = new PredictionServiceClient({fallback: 'rest'}, gax); * ``` */ - constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { // Ensure that options include all the required fields. const staticMembers = this.constructor as typeof PredictionServiceClient; - if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { - throw new Error('Please set either universe_domain or universeDomain, but not both.'); + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); } - const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; - this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; this._servicePath = 'retail.' + this._universeDomain; - const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; - const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. if (servicePath !== this._servicePath && !('scopes' in opts)) { @@ -151,7 +177,7 @@ export class PredictionServiceClient { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; @@ -168,10 +194,7 @@ export class PredictionServiceClient { const isEsm = true; const isEsmString = isEsm ? '-esm' : '-cjs'; // Determine the client header string. - const clientHeader = [ - `gax/${this._gaxModule.version}`, - `gapic/${version}`, - ]; + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/{process.versions.node}${isEsmString}`); } else { @@ -179,7 +202,7 @@ export class PredictionServiceClient { } if (!opts.fallback) { clientHeader.push(`grpc/${this._gaxGrpc.grpcVersion}`); - } else if (opts.fallback === 'rest' ) { + } else if (opts.fallback === 'rest') { clientHeader.push(`rest/${this._gaxGrpc.grpcVersion}`); } if (opts.libName && opts.libVersion) { @@ -187,54 +210,59 @@ export class PredictionServiceClient { } // Load the applicable protos. - this._protos = this._gaxGrpc.loadProtoJSON(jsonProtos as gax.protobuf.INamespace); + this._protos = this._gaxGrpc.loadProtoJSON( + jsonProtos as gax.protobuf.INamespace, + ); // This API contains "path templates"; forward-slash-separated // identifiers to uniquely identify resources within the API. // Create useful helper objects for these. this.pathTemplates = { alertConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/alertConfig' + 'projects/{project}/alertConfig', ), attributesConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/attributesConfig' + 'projects/{project}/locations/{location}/catalogs/{catalog}/attributesConfig', ), branchPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}', ), catalogPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}' + 'projects/{project}/locations/{location}/catalogs/{catalog}', ), completionConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/completionConfig' + 'projects/{project}/locations/{location}/catalogs/{catalog}/completionConfig', ), controlPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/controls/{control}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/controls/{control}', ), loggingConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/loggingConfig' + 'projects/{project}/loggingConfig', ), merchantCenterAccountLinkPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/merchantCenterAccountLinks/{merchant_center_account_link}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/merchantCenterAccountLinks/{merchant_center_account_link}', ), modelPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/models/{model}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/models/{model}', ), productPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}', ), retailProjectPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/retailProject' + 'projects/{project}/retailProject', ), servingConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/servingConfigs/{serving_config}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/servingConfigs/{serving_config}', ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.cloud.retail.v2alpha.PredictionService', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.cloud.retail.v2alpha.PredictionService', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + { 'x-goog-api-client': clientHeader.join(' ') }, + ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -265,36 +293,40 @@ export class PredictionServiceClient { // Put together the "service stub" for // google.cloud.retail.v2alpha.PredictionService. this.predictionServiceStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.cloud.retail.v2alpha.PredictionService') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.cloud.retail.v2alpha.PredictionService', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.cloud.retail.v2alpha.PredictionService, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts, + this._providedCustomServicePath, + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const predictionServiceStubMethods = - ['predict']; + const predictionServiceStubMethods = ['predict']; for (const methodName of predictionServiceStubMethods) { const callPromise = this.predictionServiceStub.then( - stub => (...args: Array<{}>) => { - if (this._terminated) { - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error|null|undefined) => () => { + (stub) => + (...args: Array<{}>) => { + if (this._terminated) { + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { throw err; - }); + }, + ); - const descriptor = - undefined; + const descriptor = undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -309,8 +341,14 @@ export class PredictionServiceClient { * @returns {string} The DNS address for this service. */ static get servicePath() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'retail.googleapis.com'; } @@ -322,8 +360,14 @@ export class PredictionServiceClient { * @returns {string} The DNS address for this service. */ static get apiEndpoint() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'retail.googleapis.com'; } @@ -354,9 +398,7 @@ export class PredictionServiceClient { * @returns {string[]} List of default scopes. */ static get scopes() { - return [ - 'https://www.googleapis.com/auth/cloud-platform' - ]; + return ['https://www.googleapis.com/auth/cloud-platform']; } getProjectId(): Promise; @@ -365,8 +407,9 @@ export class PredictionServiceClient { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId(callback?: Callback): - Promise|void { + getProjectId( + callback?: Callback, + ): Promise | void { if (callback) { this.auth.getProjectId(callback); return; @@ -377,221 +420,252 @@ export class PredictionServiceClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Makes a recommendation prediction. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.placement - * Required. Full resource name of the format: - * `{placement=projects/* /locations/global/catalogs/default_catalog/servingConfigs/*}` - * or - * `{placement=projects/* /locations/global/catalogs/default_catalog/placements/*}`. - * We recommend using the `servingConfigs` resource. `placements` is a legacy - * resource. - * The ID of the Recommendations AI serving config or placement. - * Before you can request predictions from your model, you must create at - * least one serving config or placement for it. For more information, see - * [Manage serving configs] - * (https://cloud.google.com/retail/docs/manage-configs). - * - * The full list of available serving configs can be seen at - * https://console.cloud.google.com/ai/retail/catalogs/default_catalog/configs - * @param {google.cloud.retail.v2alpha.UserEvent} request.userEvent - * Required. Context about the user, what they are looking at and what action - * they took to trigger the predict request. Note that this user event detail - * won't be ingested to userEvent logs. Thus, a separate userEvent write - * request is required for event logging. - * - * Don't set - * {@link protos.google.cloud.retail.v2alpha.UserEvent.visitor_id|UserEvent.visitor_id} or - * {@link protos.google.cloud.retail.v2alpha.UserInfo.user_id|UserInfo.user_id} to the - * same fixed ID for different users. If you are trying to receive - * non-personalized recommendations (not recommended; this can negatively - * impact model performance), instead set - * {@link protos.google.cloud.retail.v2alpha.UserEvent.visitor_id|UserEvent.visitor_id} to - * a random unique ID and leave - * {@link protos.google.cloud.retail.v2alpha.UserInfo.user_id|UserInfo.user_id} unset. - * @param {number} request.pageSize - * Maximum number of results to return. Set this property to the number of - * prediction results needed. If zero, the service will choose a reasonable - * default. The maximum allowed value is 100. Values above 100 will be coerced - * to 100. - * @param {string} request.pageToken - * This field is not used; leave it unset. - * @param {string} request.filter - * Filter for restricting prediction results with a length limit of 5,000 - * characters. Accepts values for tags and the `filterOutOfStockItems` flag. - * - * * Tag expressions. Restricts predictions to products that match all of the - * specified tags. Boolean operators `OR` and `NOT` are supported if the - * expression is enclosed in parentheses, and must be separated from the - * tag values by a space. `-"tagA"` is also supported and is equivalent to - * `NOT "tagA"`. Tag values must be double quoted UTF-8 encoded strings - * with a size limit of 1,000 characters. - * - * Note: "Recently viewed" models don't support tag filtering at the - * moment. - * - * * filterOutOfStockItems. Restricts predictions to products that do not - * have a - * stockState value of OUT_OF_STOCK. - * - * Examples: - * - * * tag=("Red" OR "Blue") tag="New-Arrival" tag=(NOT "promotional") - * * filterOutOfStockItems tag=(-"promotional") - * * filterOutOfStockItems - * - * If your filter blocks all prediction results, the API will return *no* - * results. If instead you want empty result sets to return generic - * (unfiltered) popular products, set `strictFiltering` to False in - * `PredictRequest.params`. Note that the API will never return items with - * storageStatus of "EXPIRED" or "DELETED" regardless of filter choices. - * - * If `filterSyntaxV2` is set to true under the `params` field, then - * attribute-based expressions are expected instead of the above described - * tag-based syntax. Examples: - * - * * (colors: ANY("Red", "Blue")) AND NOT (categories: ANY("Phones")) - * * (availability: ANY("IN_STOCK")) AND - * (colors: ANY("Red") OR categories: ANY("Phones")) - * - * For more information, see - * [Filter recommendations](https://cloud.google.com/retail/docs/filter-recs). - * @param {boolean} request.validateOnly - * Use validate only mode for this prediction query. If set to true, a - * dummy model will be used that returns arbitrary products. - * Note that the validate only mode should only be used for testing the API, - * or if the model is not ready. - * @param {number[]} request.params - * Additional domain specific parameters for the predictions. - * - * Allowed values: - * - * * `returnProduct`: Boolean. If set to true, the associated product - * object will be returned in the `results.metadata` field in the - * prediction response. - * * `returnScore`: Boolean. If set to true, the prediction 'score' - * corresponding to each returned product will be set in the - * `results.metadata` field in the prediction response. The given - * 'score' indicates the probability of a product being clicked/purchased - * given the user's context and history. - * * `strictFiltering`: Boolean. True by default. If set to false, the service - * will return generic (unfiltered) popular products instead of empty if - * your filter blocks all prediction results. - * * `priceRerankLevel`: String. Default empty. If set to be non-empty, then - * it needs to be one of {'no-price-reranking', 'low-price-reranking', - * 'medium-price-reranking', 'high-price-reranking'}. This gives - * request-level control and adjusts prediction results based on product - * price. - * * `diversityLevel`: String. Default empty. If set to be non-empty, then - * it needs to be one of {'no-diversity', 'low-diversity', - * 'medium-diversity', 'high-diversity', 'auto-diversity'}. This gives - * request-level control and adjusts prediction results based on product - * category. - * * `filterSyntaxV2`: Boolean. False by default. If set to true, the `filter` - * field is interpreteted according to the new, attribute-based syntax. - * @param {number[]} request.labels - * The labels applied to a resource must meet the following requirements: - * - * * Each resource can have multiple labels, up to a maximum of 64. - * * Each label must be a key-value pair. - * * Keys have a minimum length of 1 character and a maximum length of 63 - * characters and cannot be empty. Values can be empty and have a maximum - * length of 63 characters. - * * Keys and values can contain only lowercase letters, numeric characters, - * underscores, and dashes. All characters must use UTF-8 encoding, and - * international characters are allowed. - * * The key portion of a label must be unique. However, you can use the same - * key with multiple resources. - * * Keys must start with a lowercase letter or international character. - * - * See [Google Cloud - * Document](https://cloud.google.com/resource-manager/docs/creating-managing-labels#requirements) - * for more details. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.PredictResponse|PredictResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/prediction_service.predict.js - * region_tag:retail_v2alpha_generated_PredictionService_Predict_async - */ + /** + * Makes a recommendation prediction. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.placement + * Required. Full resource name of the format: + * `{placement=projects/* /locations/global/catalogs/default_catalog/servingConfigs/*}` + * or + * `{placement=projects/* /locations/global/catalogs/default_catalog/placements/*}`. + * We recommend using the `servingConfigs` resource. `placements` is a legacy + * resource. + * The ID of the Recommendations AI serving config or placement. + * Before you can request predictions from your model, you must create at + * least one serving config or placement for it. For more information, see + * [Manage serving configs] + * (https://cloud.google.com/retail/docs/manage-configs). + * + * The full list of available serving configs can be seen at + * https://console.cloud.google.com/ai/retail/catalogs/default_catalog/configs + * @param {google.cloud.retail.v2alpha.UserEvent} request.userEvent + * Required. Context about the user, what they are looking at and what action + * they took to trigger the predict request. Note that this user event detail + * won't be ingested to userEvent logs. Thus, a separate userEvent write + * request is required for event logging. + * + * Don't set + * {@link protos.google.cloud.retail.v2alpha.UserEvent.visitor_id|UserEvent.visitor_id} or + * {@link protos.google.cloud.retail.v2alpha.UserInfo.user_id|UserInfo.user_id} to the + * same fixed ID for different users. If you are trying to receive + * non-personalized recommendations (not recommended; this can negatively + * impact model performance), instead set + * {@link protos.google.cloud.retail.v2alpha.UserEvent.visitor_id|UserEvent.visitor_id} to + * a random unique ID and leave + * {@link protos.google.cloud.retail.v2alpha.UserInfo.user_id|UserInfo.user_id} unset. + * @param {number} request.pageSize + * Maximum number of results to return. Set this property to the number of + * prediction results needed. If zero, the service will choose a reasonable + * default. The maximum allowed value is 100. Values above 100 will be coerced + * to 100. + * @param {string} request.pageToken + * This field is not used; leave it unset. + * @param {string} request.filter + * Filter for restricting prediction results with a length limit of 5,000 + * characters. Accepts values for tags and the `filterOutOfStockItems` flag. + * + * * Tag expressions. Restricts predictions to products that match all of the + * specified tags. Boolean operators `OR` and `NOT` are supported if the + * expression is enclosed in parentheses, and must be separated from the + * tag values by a space. `-"tagA"` is also supported and is equivalent to + * `NOT "tagA"`. Tag values must be double quoted UTF-8 encoded strings + * with a size limit of 1,000 characters. + * + * Note: "Recently viewed" models don't support tag filtering at the + * moment. + * + * * filterOutOfStockItems. Restricts predictions to products that do not + * have a + * stockState value of OUT_OF_STOCK. + * + * Examples: + * + * * tag=("Red" OR "Blue") tag="New-Arrival" tag=(NOT "promotional") + * * filterOutOfStockItems tag=(-"promotional") + * * filterOutOfStockItems + * + * If your filter blocks all prediction results, the API will return *no* + * results. If instead you want empty result sets to return generic + * (unfiltered) popular products, set `strictFiltering` to False in + * `PredictRequest.params`. Note that the API will never return items with + * storageStatus of "EXPIRED" or "DELETED" regardless of filter choices. + * + * If `filterSyntaxV2` is set to true under the `params` field, then + * attribute-based expressions are expected instead of the above described + * tag-based syntax. Examples: + * + * * (colors: ANY("Red", "Blue")) AND NOT (categories: ANY("Phones")) + * * (availability: ANY("IN_STOCK")) AND + * (colors: ANY("Red") OR categories: ANY("Phones")) + * + * For more information, see + * [Filter recommendations](https://cloud.google.com/retail/docs/filter-recs). + * @param {boolean} request.validateOnly + * Use validate only mode for this prediction query. If set to true, a + * dummy model will be used that returns arbitrary products. + * Note that the validate only mode should only be used for testing the API, + * or if the model is not ready. + * @param {number[]} request.params + * Additional domain specific parameters for the predictions. + * + * Allowed values: + * + * * `returnProduct`: Boolean. If set to true, the associated product + * object will be returned in the `results.metadata` field in the + * prediction response. + * * `returnScore`: Boolean. If set to true, the prediction 'score' + * corresponding to each returned product will be set in the + * `results.metadata` field in the prediction response. The given + * 'score' indicates the probability of a product being clicked/purchased + * given the user's context and history. + * * `strictFiltering`: Boolean. True by default. If set to false, the service + * will return generic (unfiltered) popular products instead of empty if + * your filter blocks all prediction results. + * * `priceRerankLevel`: String. Default empty. If set to be non-empty, then + * it needs to be one of {'no-price-reranking', 'low-price-reranking', + * 'medium-price-reranking', 'high-price-reranking'}. This gives + * request-level control and adjusts prediction results based on product + * price. + * * `diversityLevel`: String. Default empty. If set to be non-empty, then + * it needs to be one of {'no-diversity', 'low-diversity', + * 'medium-diversity', 'high-diversity', 'auto-diversity'}. This gives + * request-level control and adjusts prediction results based on product + * category. + * * `filterSyntaxV2`: Boolean. False by default. If set to true, the `filter` + * field is interpreteted according to the new, attribute-based syntax. + * @param {number[]} request.labels + * The labels applied to a resource must meet the following requirements: + * + * * Each resource can have multiple labels, up to a maximum of 64. + * * Each label must be a key-value pair. + * * Keys have a minimum length of 1 character and a maximum length of 63 + * characters and cannot be empty. Values can be empty and have a maximum + * length of 63 characters. + * * Keys and values can contain only lowercase letters, numeric characters, + * underscores, and dashes. All characters must use UTF-8 encoding, and + * international characters are allowed. + * * The key portion of a label must be unique. However, you can use the same + * key with multiple resources. + * * Keys must start with a lowercase letter or international character. + * + * See [Google Cloud + * Document](https://cloud.google.com/resource-manager/docs/creating-managing-labels#requirements) + * for more details. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.PredictResponse|PredictResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/prediction_service.predict.js + * region_tag:retail_v2alpha_generated_PredictionService_Predict_async + */ predict( - request?: protos.google.cloud.retail.v2alpha.IPredictRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.retail.v2alpha.IPredictResponse, - protos.google.cloud.retail.v2alpha.IPredictRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.IPredictRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IPredictResponse, + protos.google.cloud.retail.v2alpha.IPredictRequest | undefined, + {} | undefined, + ] + >; predict( - request: protos.google.cloud.retail.v2alpha.IPredictRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.retail.v2alpha.IPredictResponse, - protos.google.cloud.retail.v2alpha.IPredictRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IPredictRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.retail.v2alpha.IPredictResponse, + protos.google.cloud.retail.v2alpha.IPredictRequest | null | undefined, + {} | null | undefined + >, + ): void; predict( - request: protos.google.cloud.retail.v2alpha.IPredictRequest, - callback: Callback< - protos.google.cloud.retail.v2alpha.IPredictResponse, - protos.google.cloud.retail.v2alpha.IPredictRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IPredictRequest, + callback: Callback< + protos.google.cloud.retail.v2alpha.IPredictResponse, + protos.google.cloud.retail.v2alpha.IPredictRequest | null | undefined, + {} | null | undefined + >, + ): void; predict( - request?: protos.google.cloud.retail.v2alpha.IPredictRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.retail.v2alpha.IPredictResponse, - protos.google.cloud.retail.v2alpha.IPredictRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.retail.v2alpha.IPredictRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.retail.v2alpha.IPredictResponse, - protos.google.cloud.retail.v2alpha.IPredictRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.retail.v2alpha.IPredictResponse, - protos.google.cloud.retail.v2alpha.IPredictRequest|undefined, {}|undefined - ]>|void { + protos.google.cloud.retail.v2alpha.IPredictRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.retail.v2alpha.IPredictResponse, + protos.google.cloud.retail.v2alpha.IPredictRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IPredictResponse, + protos.google.cloud.retail.v2alpha.IPredictRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'placement': request.placement ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + placement: request.placement ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('predict request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.retail.v2alpha.IPredictResponse, - protos.google.cloud.retail.v2alpha.IPredictRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.retail.v2alpha.IPredictResponse, + protos.google.cloud.retail.v2alpha.IPredictRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('predict response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.predict(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.retail.v2alpha.IPredictResponse, - protos.google.cloud.retail.v2alpha.IPredictRequest|undefined, {}|undefined - ]) => { - this._log.info('predict response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .predict(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.retail.v2alpha.IPredictResponse, + protos.google.cloud.retail.v2alpha.IPredictRequest | undefined, + {} | undefined, + ]) => { + this._log.info('predict response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); @@ -607,7 +681,7 @@ export class PredictionServiceClient { * @param {string} project * @returns {string} Resource name string. */ - alertConfigPath(project:string) { + alertConfigPath(project: string) { return this.pathTemplates.alertConfigPathTemplate.render({ project: project, }); @@ -621,7 +695,8 @@ export class PredictionServiceClient { * @returns {string} A string representing the project. */ matchProjectFromAlertConfigName(alertConfigName: string) { - return this.pathTemplates.alertConfigPathTemplate.match(alertConfigName).project; + return this.pathTemplates.alertConfigPathTemplate.match(alertConfigName) + .project; } /** @@ -632,7 +707,7 @@ export class PredictionServiceClient { * @param {string} catalog * @returns {string} Resource name string. */ - attributesConfigPath(project:string,location:string,catalog:string) { + attributesConfigPath(project: string, location: string, catalog: string) { return this.pathTemplates.attributesConfigPathTemplate.render({ project: project, location: location, @@ -648,7 +723,9 @@ export class PredictionServiceClient { * @returns {string} A string representing the project. */ matchProjectFromAttributesConfigName(attributesConfigName: string) { - return this.pathTemplates.attributesConfigPathTemplate.match(attributesConfigName).project; + return this.pathTemplates.attributesConfigPathTemplate.match( + attributesConfigName, + ).project; } /** @@ -659,7 +736,9 @@ export class PredictionServiceClient { * @returns {string} A string representing the location. */ matchLocationFromAttributesConfigName(attributesConfigName: string) { - return this.pathTemplates.attributesConfigPathTemplate.match(attributesConfigName).location; + return this.pathTemplates.attributesConfigPathTemplate.match( + attributesConfigName, + ).location; } /** @@ -670,7 +749,9 @@ export class PredictionServiceClient { * @returns {string} A string representing the catalog. */ matchCatalogFromAttributesConfigName(attributesConfigName: string) { - return this.pathTemplates.attributesConfigPathTemplate.match(attributesConfigName).catalog; + return this.pathTemplates.attributesConfigPathTemplate.match( + attributesConfigName, + ).catalog; } /** @@ -682,7 +763,12 @@ export class PredictionServiceClient { * @param {string} branch * @returns {string} Resource name string. */ - branchPath(project:string,location:string,catalog:string,branch:string) { + branchPath( + project: string, + location: string, + catalog: string, + branch: string, + ) { return this.pathTemplates.branchPathTemplate.render({ project: project, location: location, @@ -743,7 +829,7 @@ export class PredictionServiceClient { * @param {string} catalog * @returns {string} Resource name string. */ - catalogPath(project:string,location:string,catalog:string) { + catalogPath(project: string, location: string, catalog: string) { return this.pathTemplates.catalogPathTemplate.render({ project: project, location: location, @@ -792,7 +878,7 @@ export class PredictionServiceClient { * @param {string} catalog * @returns {string} Resource name string. */ - completionConfigPath(project:string,location:string,catalog:string) { + completionConfigPath(project: string, location: string, catalog: string) { return this.pathTemplates.completionConfigPathTemplate.render({ project: project, location: location, @@ -808,7 +894,9 @@ export class PredictionServiceClient { * @returns {string} A string representing the project. */ matchProjectFromCompletionConfigName(completionConfigName: string) { - return this.pathTemplates.completionConfigPathTemplate.match(completionConfigName).project; + return this.pathTemplates.completionConfigPathTemplate.match( + completionConfigName, + ).project; } /** @@ -819,7 +907,9 @@ export class PredictionServiceClient { * @returns {string} A string representing the location. */ matchLocationFromCompletionConfigName(completionConfigName: string) { - return this.pathTemplates.completionConfigPathTemplate.match(completionConfigName).location; + return this.pathTemplates.completionConfigPathTemplate.match( + completionConfigName, + ).location; } /** @@ -830,7 +920,9 @@ export class PredictionServiceClient { * @returns {string} A string representing the catalog. */ matchCatalogFromCompletionConfigName(completionConfigName: string) { - return this.pathTemplates.completionConfigPathTemplate.match(completionConfigName).catalog; + return this.pathTemplates.completionConfigPathTemplate.match( + completionConfigName, + ).catalog; } /** @@ -842,7 +934,12 @@ export class PredictionServiceClient { * @param {string} control * @returns {string} Resource name string. */ - controlPath(project:string,location:string,catalog:string,control:string) { + controlPath( + project: string, + location: string, + catalog: string, + control: string, + ) { return this.pathTemplates.controlPathTemplate.render({ project: project, location: location, @@ -901,7 +998,7 @@ export class PredictionServiceClient { * @param {string} project * @returns {string} Resource name string. */ - loggingConfigPath(project:string) { + loggingConfigPath(project: string) { return this.pathTemplates.loggingConfigPathTemplate.render({ project: project, }); @@ -915,7 +1012,8 @@ export class PredictionServiceClient { * @returns {string} A string representing the project. */ matchProjectFromLoggingConfigName(loggingConfigName: string) { - return this.pathTemplates.loggingConfigPathTemplate.match(loggingConfigName).project; + return this.pathTemplates.loggingConfigPathTemplate.match(loggingConfigName) + .project; } /** @@ -927,7 +1025,12 @@ export class PredictionServiceClient { * @param {string} merchant_center_account_link * @returns {string} Resource name string. */ - merchantCenterAccountLinkPath(project:string,location:string,catalog:string,merchantCenterAccountLink:string) { + merchantCenterAccountLinkPath( + project: string, + location: string, + catalog: string, + merchantCenterAccountLink: string, + ) { return this.pathTemplates.merchantCenterAccountLinkPathTemplate.render({ project: project, location: location, @@ -943,8 +1046,12 @@ export class PredictionServiceClient { * A fully-qualified path representing MerchantCenterAccountLink resource. * @returns {string} A string representing the project. */ - matchProjectFromMerchantCenterAccountLinkName(merchantCenterAccountLinkName: string) { - return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match(merchantCenterAccountLinkName).project; + matchProjectFromMerchantCenterAccountLinkName( + merchantCenterAccountLinkName: string, + ) { + return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match( + merchantCenterAccountLinkName, + ).project; } /** @@ -954,8 +1061,12 @@ export class PredictionServiceClient { * A fully-qualified path representing MerchantCenterAccountLink resource. * @returns {string} A string representing the location. */ - matchLocationFromMerchantCenterAccountLinkName(merchantCenterAccountLinkName: string) { - return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match(merchantCenterAccountLinkName).location; + matchLocationFromMerchantCenterAccountLinkName( + merchantCenterAccountLinkName: string, + ) { + return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match( + merchantCenterAccountLinkName, + ).location; } /** @@ -965,8 +1076,12 @@ export class PredictionServiceClient { * A fully-qualified path representing MerchantCenterAccountLink resource. * @returns {string} A string representing the catalog. */ - matchCatalogFromMerchantCenterAccountLinkName(merchantCenterAccountLinkName: string) { - return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match(merchantCenterAccountLinkName).catalog; + matchCatalogFromMerchantCenterAccountLinkName( + merchantCenterAccountLinkName: string, + ) { + return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match( + merchantCenterAccountLinkName, + ).catalog; } /** @@ -976,8 +1091,12 @@ export class PredictionServiceClient { * A fully-qualified path representing MerchantCenterAccountLink resource. * @returns {string} A string representing the merchant_center_account_link. */ - matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName(merchantCenterAccountLinkName: string) { - return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match(merchantCenterAccountLinkName).merchant_center_account_link; + matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName( + merchantCenterAccountLinkName: string, + ) { + return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match( + merchantCenterAccountLinkName, + ).merchant_center_account_link; } /** @@ -989,7 +1108,7 @@ export class PredictionServiceClient { * @param {string} model * @returns {string} Resource name string. */ - modelPath(project:string,location:string,catalog:string,model:string) { + modelPath(project: string, location: string, catalog: string, model: string) { return this.pathTemplates.modelPathTemplate.render({ project: project, location: location, @@ -1052,7 +1171,13 @@ export class PredictionServiceClient { * @param {string} product * @returns {string} Resource name string. */ - productPath(project:string,location:string,catalog:string,branch:string,product:string) { + productPath( + project: string, + location: string, + catalog: string, + branch: string, + product: string, + ) { return this.pathTemplates.productPathTemplate.render({ project: project, location: location, @@ -1123,7 +1248,7 @@ export class PredictionServiceClient { * @param {string} project * @returns {string} Resource name string. */ - retailProjectPath(project:string) { + retailProjectPath(project: string) { return this.pathTemplates.retailProjectPathTemplate.render({ project: project, }); @@ -1137,7 +1262,8 @@ export class PredictionServiceClient { * @returns {string} A string representing the project. */ matchProjectFromRetailProjectName(retailProjectName: string) { - return this.pathTemplates.retailProjectPathTemplate.match(retailProjectName).project; + return this.pathTemplates.retailProjectPathTemplate.match(retailProjectName) + .project; } /** @@ -1149,7 +1275,12 @@ export class PredictionServiceClient { * @param {string} serving_config * @returns {string} Resource name string. */ - servingConfigPath(project:string,location:string,catalog:string,servingConfig:string) { + servingConfigPath( + project: string, + location: string, + catalog: string, + servingConfig: string, + ) { return this.pathTemplates.servingConfigPathTemplate.render({ project: project, location: location, @@ -1166,7 +1297,8 @@ export class PredictionServiceClient { * @returns {string} A string representing the project. */ matchProjectFromServingConfigName(servingConfigName: string) { - return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName).project; + return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName) + .project; } /** @@ -1177,7 +1309,8 @@ export class PredictionServiceClient { * @returns {string} A string representing the location. */ matchLocationFromServingConfigName(servingConfigName: string) { - return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName).location; + return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName) + .location; } /** @@ -1188,7 +1321,8 @@ export class PredictionServiceClient { * @returns {string} A string representing the catalog. */ matchCatalogFromServingConfigName(servingConfigName: string) { - return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName).catalog; + return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName) + .catalog; } /** @@ -1199,7 +1333,8 @@ export class PredictionServiceClient { * @returns {string} A string representing the serving_config. */ matchServingConfigFromServingConfigName(servingConfigName: string) { - return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName).serving_config; + return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName) + .serving_config; } /** @@ -1210,7 +1345,7 @@ export class PredictionServiceClient { */ close(): Promise { if (this.predictionServiceStub && !this._terminated) { - return this.predictionServiceStub.then(stub => { + return this.predictionServiceStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -1218,4 +1353,4 @@ export class PredictionServiceClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/src/v2alpha/product_service_client.ts.baseline b/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/src/v2alpha/product_service_client.ts.baseline index ed837e7029ca..df64f6564bbe 100644 --- a/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/src/v2alpha/product_service_client.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/src/v2alpha/product_service_client.ts.baseline @@ -18,15 +18,24 @@ /* global window */ import * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions, GrpcClientOptions, LROperation, PaginationCallback, GaxCall} from 'google-gax'; -import {Transform} from 'stream'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + GrpcClientOptions, + LROperation, + PaginationCallback, + GaxCall, +} from 'google-gax'; +import { Transform } from 'stream'; // @ts-ignore import type * as protos from '../../../protos/protos.js'; import * as product_service_client_config from './product_service_client_config.json'; import fs from 'fs'; import path from 'path'; -import {fileURLToPath} from 'url'; -import {getJSON} from '../json-helper.cjs'; +import { fileURLToPath } from 'url'; +import { getJSON } from '../json-helper.cjs'; // @ts-ignore const dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -36,15 +45,15 @@ const dirname = path.dirname(fileURLToPath(import.meta.url)); * This file defines retry strategy and timeouts for all API methods in this library. */ const gapicConfig = getJSON( - path.join(dirname, 'product_service_client_config.json') + path.join(dirname, 'product_service_client_config.json'), ); const jsonProtos = getJSON( - path.join(dirname, '..', '..', '..', 'protos/protos.json') + path.join(dirname, '..', '..', '..', 'protos/protos.json'), ); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; const version = getJSON( - path.join(dirname, '..', '..', '..', '..', 'package.json') + path.join(dirname, '..', '..', '..', '..', 'package.json'), ).version; /** @@ -60,7 +69,7 @@ export class ProductServiceClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('retail'); @@ -72,10 +81,10 @@ export class ProductServiceClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; operationsClient: gax.OperationsClient; - productServiceStub?: Promise<{[name: string]: Function}>; + productServiceStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of ProductServiceClient. @@ -117,21 +126,42 @@ export class ProductServiceClient { * const client = new ProductServiceClient({fallback: 'rest'}, gax); * ``` */ - constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { // Ensure that options include all the required fields. const staticMembers = this.constructor as typeof ProductServiceClient; - if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { - throw new Error('Please set either universe_domain or universeDomain, but not both.'); + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); } - const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; - this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; this._servicePath = 'retail.' + this._universeDomain; - const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; - const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. if (servicePath !== this._servicePath && !('scopes' in opts)) { @@ -153,7 +183,7 @@ export class ProductServiceClient { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; @@ -170,10 +200,7 @@ export class ProductServiceClient { const isEsm = true; const isEsmString = isEsm ? '-esm' : '-cjs'; // Determine the client header string. - const clientHeader = [ - `gax/${this._gaxModule.version}`, - `gapic/${version}`, - ]; + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/{process.versions.node}${isEsmString}`); } else { @@ -181,7 +208,7 @@ export class ProductServiceClient { } if (!opts.fallback) { clientHeader.push(`grpc/${this._gaxGrpc.grpcVersion}`); - } else if (opts.fallback === 'rest' ) { + } else if (opts.fallback === 'rest') { clientHeader.push(`rest/${this._gaxGrpc.grpcVersion}`); } if (opts.libName && opts.libVersion) { @@ -189,47 +216,49 @@ export class ProductServiceClient { } // Load the applicable protos. - this._protos = this._gaxGrpc.loadProtoJSON(jsonProtos as gax.protobuf.INamespace); + this._protos = this._gaxGrpc.loadProtoJSON( + jsonProtos as gax.protobuf.INamespace, + ); // This API contains "path templates"; forward-slash-separated // identifiers to uniquely identify resources within the API. // Create useful helper objects for these. this.pathTemplates = { alertConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/alertConfig' + 'projects/{project}/alertConfig', ), attributesConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/attributesConfig' + 'projects/{project}/locations/{location}/catalogs/{catalog}/attributesConfig', ), branchPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}', ), catalogPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}' + 'projects/{project}/locations/{location}/catalogs/{catalog}', ), completionConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/completionConfig' + 'projects/{project}/locations/{location}/catalogs/{catalog}/completionConfig', ), controlPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/controls/{control}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/controls/{control}', ), loggingConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/loggingConfig' + 'projects/{project}/loggingConfig', ), merchantCenterAccountLinkPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/merchantCenterAccountLinks/{merchant_center_account_link}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/merchantCenterAccountLinks/{merchant_center_account_link}', ), modelPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/models/{model}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/models/{model}', ), productPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}', ), retailProjectPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/retailProject' + 'projects/{project}/retailProject', ), servingConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/servingConfigs/{serving_config}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/servingConfigs/{serving_config}', ), }; @@ -237,8 +266,11 @@ export class ProductServiceClient { // (e.g. 50 results at a time, with tokens to get subsequent // pages). Denote the keys used for pagination and results. this.descriptors.page = { - listProducts: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'products') + listProducts: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'products', + ), }; const protoFilesRoot = this._gaxModule.protobufFromJSON(jsonProtos); @@ -247,87 +279,145 @@ export class ProductServiceClient { // rather than holding a request open. const lroOptions: GrpcClientOptions = { auth: this.auth, - grpc: 'grpc' in this._gaxGrpc ? this._gaxGrpc.grpc : undefined + grpc: 'grpc' in this._gaxGrpc ? this._gaxGrpc.grpc : undefined, }; if (opts.fallback === 'rest') { lroOptions.protoJson = protoFilesRoot; - lroOptions.httpRules = [{selector: 'google.longrunning.Operations.GetOperation',get: '/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*/operations/*}',additional_bindings: [{get: '/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*/places/*/operations/*}',},{get: '/v2alpha/{name=projects/*/locations/*/catalogs/*/operations/*}',},{get: '/v2alpha/{name=projects/*/locations/*/operations/*}',},{get: '/v2alpha/{name=projects/*/operations/*}',}], - },{selector: 'google.longrunning.Operations.ListOperations',get: '/v2alpha/{name=projects/*/locations/*/catalogs/*}/operations',additional_bindings: [{get: '/v2alpha/{name=projects/*/locations/*}/operations',},{get: '/v2alpha/{name=projects/*}/operations',}], - }]; + lroOptions.httpRules = [ + { + selector: 'google.longrunning.Operations.GetOperation', + get: '/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*/operations/*}', + additional_bindings: [ + { + get: '/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*/places/*/operations/*}', + }, + { + get: '/v2alpha/{name=projects/*/locations/*/catalogs/*/operations/*}', + }, + { get: '/v2alpha/{name=projects/*/locations/*/operations/*}' }, + { get: '/v2alpha/{name=projects/*/operations/*}' }, + ], + }, + { + selector: 'google.longrunning.Operations.ListOperations', + get: '/v2alpha/{name=projects/*/locations/*/catalogs/*}/operations', + additional_bindings: [ + { get: '/v2alpha/{name=projects/*/locations/*}/operations' }, + { get: '/v2alpha/{name=projects/*}/operations' }, + ], + }, + ]; } - this.operationsClient = this._gaxModule.lro(lroOptions).operationsClient(opts); + this.operationsClient = this._gaxModule + .lro(lroOptions) + .operationsClient(opts); const purgeProductsResponse = protoFilesRoot.lookup( - '.google.cloud.retail.v2alpha.PurgeProductsResponse') as gax.protobuf.Type; + '.google.cloud.retail.v2alpha.PurgeProductsResponse', + ) as gax.protobuf.Type; const purgeProductsMetadata = protoFilesRoot.lookup( - '.google.cloud.retail.v2alpha.PurgeProductsMetadata') as gax.protobuf.Type; + '.google.cloud.retail.v2alpha.PurgeProductsMetadata', + ) as gax.protobuf.Type; const importProductsResponse = protoFilesRoot.lookup( - '.google.cloud.retail.v2alpha.ImportProductsResponse') as gax.protobuf.Type; + '.google.cloud.retail.v2alpha.ImportProductsResponse', + ) as gax.protobuf.Type; const importProductsMetadata = protoFilesRoot.lookup( - '.google.cloud.retail.v2alpha.ImportMetadata') as gax.protobuf.Type; + '.google.cloud.retail.v2alpha.ImportMetadata', + ) as gax.protobuf.Type; const exportProductsResponse = protoFilesRoot.lookup( - '.google.cloud.retail.v2alpha.ExportProductsResponse') as gax.protobuf.Type; + '.google.cloud.retail.v2alpha.ExportProductsResponse', + ) as gax.protobuf.Type; const exportProductsMetadata = protoFilesRoot.lookup( - '.google.cloud.retail.v2alpha.ExportMetadata') as gax.protobuf.Type; + '.google.cloud.retail.v2alpha.ExportMetadata', + ) as gax.protobuf.Type; const setInventoryResponse = protoFilesRoot.lookup( - '.google.cloud.retail.v2alpha.SetInventoryResponse') as gax.protobuf.Type; + '.google.cloud.retail.v2alpha.SetInventoryResponse', + ) as gax.protobuf.Type; const setInventoryMetadata = protoFilesRoot.lookup( - '.google.cloud.retail.v2alpha.SetInventoryMetadata') as gax.protobuf.Type; + '.google.cloud.retail.v2alpha.SetInventoryMetadata', + ) as gax.protobuf.Type; const addFulfillmentPlacesResponse = protoFilesRoot.lookup( - '.google.cloud.retail.v2alpha.AddFulfillmentPlacesResponse') as gax.protobuf.Type; + '.google.cloud.retail.v2alpha.AddFulfillmentPlacesResponse', + ) as gax.protobuf.Type; const addFulfillmentPlacesMetadata = protoFilesRoot.lookup( - '.google.cloud.retail.v2alpha.AddFulfillmentPlacesMetadata') as gax.protobuf.Type; + '.google.cloud.retail.v2alpha.AddFulfillmentPlacesMetadata', + ) as gax.protobuf.Type; const removeFulfillmentPlacesResponse = protoFilesRoot.lookup( - '.google.cloud.retail.v2alpha.RemoveFulfillmentPlacesResponse') as gax.protobuf.Type; + '.google.cloud.retail.v2alpha.RemoveFulfillmentPlacesResponse', + ) as gax.protobuf.Type; const removeFulfillmentPlacesMetadata = protoFilesRoot.lookup( - '.google.cloud.retail.v2alpha.RemoveFulfillmentPlacesMetadata') as gax.protobuf.Type; + '.google.cloud.retail.v2alpha.RemoveFulfillmentPlacesMetadata', + ) as gax.protobuf.Type; const addLocalInventoriesResponse = protoFilesRoot.lookup( - '.google.cloud.retail.v2alpha.AddLocalInventoriesResponse') as gax.protobuf.Type; + '.google.cloud.retail.v2alpha.AddLocalInventoriesResponse', + ) as gax.protobuf.Type; const addLocalInventoriesMetadata = protoFilesRoot.lookup( - '.google.cloud.retail.v2alpha.AddLocalInventoriesMetadata') as gax.protobuf.Type; + '.google.cloud.retail.v2alpha.AddLocalInventoriesMetadata', + ) as gax.protobuf.Type; const removeLocalInventoriesResponse = protoFilesRoot.lookup( - '.google.cloud.retail.v2alpha.RemoveLocalInventoriesResponse') as gax.protobuf.Type; + '.google.cloud.retail.v2alpha.RemoveLocalInventoriesResponse', + ) as gax.protobuf.Type; const removeLocalInventoriesMetadata = protoFilesRoot.lookup( - '.google.cloud.retail.v2alpha.RemoveLocalInventoriesMetadata') as gax.protobuf.Type; + '.google.cloud.retail.v2alpha.RemoveLocalInventoriesMetadata', + ) as gax.protobuf.Type; this.descriptors.longrunning = { purgeProducts: new this._gaxModule.LongrunningDescriptor( this.operationsClient, purgeProductsResponse.decode.bind(purgeProductsResponse), - purgeProductsMetadata.decode.bind(purgeProductsMetadata)), + purgeProductsMetadata.decode.bind(purgeProductsMetadata), + ), importProducts: new this._gaxModule.LongrunningDescriptor( this.operationsClient, importProductsResponse.decode.bind(importProductsResponse), - importProductsMetadata.decode.bind(importProductsMetadata)), + importProductsMetadata.decode.bind(importProductsMetadata), + ), exportProducts: new this._gaxModule.LongrunningDescriptor( this.operationsClient, exportProductsResponse.decode.bind(exportProductsResponse), - exportProductsMetadata.decode.bind(exportProductsMetadata)), + exportProductsMetadata.decode.bind(exportProductsMetadata), + ), setInventory: new this._gaxModule.LongrunningDescriptor( this.operationsClient, setInventoryResponse.decode.bind(setInventoryResponse), - setInventoryMetadata.decode.bind(setInventoryMetadata)), + setInventoryMetadata.decode.bind(setInventoryMetadata), + ), addFulfillmentPlaces: new this._gaxModule.LongrunningDescriptor( this.operationsClient, addFulfillmentPlacesResponse.decode.bind(addFulfillmentPlacesResponse), - addFulfillmentPlacesMetadata.decode.bind(addFulfillmentPlacesMetadata)), + addFulfillmentPlacesMetadata.decode.bind(addFulfillmentPlacesMetadata), + ), removeFulfillmentPlaces: new this._gaxModule.LongrunningDescriptor( this.operationsClient, - removeFulfillmentPlacesResponse.decode.bind(removeFulfillmentPlacesResponse), - removeFulfillmentPlacesMetadata.decode.bind(removeFulfillmentPlacesMetadata)), + removeFulfillmentPlacesResponse.decode.bind( + removeFulfillmentPlacesResponse, + ), + removeFulfillmentPlacesMetadata.decode.bind( + removeFulfillmentPlacesMetadata, + ), + ), addLocalInventories: new this._gaxModule.LongrunningDescriptor( this.operationsClient, addLocalInventoriesResponse.decode.bind(addLocalInventoriesResponse), - addLocalInventoriesMetadata.decode.bind(addLocalInventoriesMetadata)), + addLocalInventoriesMetadata.decode.bind(addLocalInventoriesMetadata), + ), removeLocalInventories: new this._gaxModule.LongrunningDescriptor( this.operationsClient, - removeLocalInventoriesResponse.decode.bind(removeLocalInventoriesResponse), - removeLocalInventoriesMetadata.decode.bind(removeLocalInventoriesMetadata)) + removeLocalInventoriesResponse.decode.bind( + removeLocalInventoriesResponse, + ), + removeLocalInventoriesMetadata.decode.bind( + removeLocalInventoriesMetadata, + ), + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.cloud.retail.v2alpha.ProductService', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.cloud.retail.v2alpha.ProductService', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + { 'x-goog-api-client': clientHeader.join(' ') }, + ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -358,28 +448,47 @@ export class ProductServiceClient { // Put together the "service stub" for // google.cloud.retail.v2alpha.ProductService. this.productServiceStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.cloud.retail.v2alpha.ProductService') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.cloud.retail.v2alpha.ProductService', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.cloud.retail.v2alpha.ProductService, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts, + this._providedCustomServicePath, + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const productServiceStubMethods = - ['createProduct', 'getProduct', 'listProducts', 'updateProduct', 'deleteProduct', 'purgeProducts', 'importProducts', 'exportProducts', 'setInventory', 'addFulfillmentPlaces', 'removeFulfillmentPlaces', 'addLocalInventories', 'removeLocalInventories']; + const productServiceStubMethods = [ + 'createProduct', + 'getProduct', + 'listProducts', + 'updateProduct', + 'deleteProduct', + 'purgeProducts', + 'importProducts', + 'exportProducts', + 'setInventory', + 'addFulfillmentPlaces', + 'removeFulfillmentPlaces', + 'addLocalInventories', + 'removeLocalInventories', + ]; for (const methodName of productServiceStubMethods) { const callPromise = this.productServiceStub.then( - stub => (...args: Array<{}>) => { - if (this._terminated) { - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error|null|undefined) => () => { + (stub) => + (...args: Array<{}>) => { + if (this._terminated) { + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { throw err; - }); + }, + ); const descriptor = this.descriptors.page[methodName] || @@ -389,7 +498,7 @@ export class ProductServiceClient { callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -404,8 +513,14 @@ export class ProductServiceClient { * @returns {string} The DNS address for this service. */ static get servicePath() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'retail.googleapis.com'; } @@ -417,8 +532,14 @@ export class ProductServiceClient { * @returns {string} The DNS address for this service. */ static get apiEndpoint() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'retail.googleapis.com'; } @@ -449,9 +570,7 @@ export class ProductServiceClient { * @returns {string[]} List of default scopes. */ static get scopes() { - return [ - 'https://www.googleapis.com/auth/cloud-platform' - ]; + return ['https://www.googleapis.com/auth/cloud-platform']; } getProjectId(): Promise; @@ -460,8 +579,9 @@ export class ProductServiceClient { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId(callback?: Callback): - Promise|void { + getProjectId( + callback?: Callback, + ): Promise | void { if (callback) { this.auth.getProjectId(callback); return; @@ -472,2032 +592,2711 @@ export class ProductServiceClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Creates a {@link protos.google.cloud.retail.v2alpha.Product|Product}. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent catalog resource name, such as - * `projects/* /locations/global/catalogs/default_catalog/branches/default_branch`. - * @param {google.cloud.retail.v2alpha.Product} request.product - * Required. The {@link protos.google.cloud.retail.v2alpha.Product|Product} to create. - * @param {string} request.productId - * Required. The ID to use for the - * {@link protos.google.cloud.retail.v2alpha.Product|Product}, which will become the final - * component of the {@link protos.google.cloud.retail.v2alpha.Product.name|Product.name}. - * - * If the caller does not have permission to create the - * {@link protos.google.cloud.retail.v2alpha.Product|Product}, regardless of whether or - * not it exists, a PERMISSION_DENIED error is returned. - * - * This field must be unique among all - * {@link protos.google.cloud.retail.v2alpha.Product|Product}s with the same - * {@link protos.google.cloud.retail.v2alpha.CreateProductRequest.parent|parent}. - * Otherwise, an ALREADY_EXISTS error is returned. - * - * This field must be a UTF-8 encoded string with a length limit of 128 - * characters. Otherwise, an INVALID_ARGUMENT error is returned. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.Product|Product}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/product_service.create_product.js - * region_tag:retail_v2alpha_generated_ProductService_CreateProduct_async - */ + /** + * Creates a {@link protos.google.cloud.retail.v2alpha.Product|Product}. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent catalog resource name, such as + * `projects/* /locations/global/catalogs/default_catalog/branches/default_branch`. + * @param {google.cloud.retail.v2alpha.Product} request.product + * Required. The {@link protos.google.cloud.retail.v2alpha.Product|Product} to create. + * @param {string} request.productId + * Required. The ID to use for the + * {@link protos.google.cloud.retail.v2alpha.Product|Product}, which will become the final + * component of the {@link protos.google.cloud.retail.v2alpha.Product.name|Product.name}. + * + * If the caller does not have permission to create the + * {@link protos.google.cloud.retail.v2alpha.Product|Product}, regardless of whether or + * not it exists, a PERMISSION_DENIED error is returned. + * + * This field must be unique among all + * {@link protos.google.cloud.retail.v2alpha.Product|Product}s with the same + * {@link protos.google.cloud.retail.v2alpha.CreateProductRequest.parent|parent}. + * Otherwise, an ALREADY_EXISTS error is returned. + * + * This field must be a UTF-8 encoded string with a length limit of 128 + * characters. Otherwise, an INVALID_ARGUMENT error is returned. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.Product|Product}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/product_service.create_product.js + * region_tag:retail_v2alpha_generated_ProductService_CreateProduct_async + */ createProduct( - request?: protos.google.cloud.retail.v2alpha.ICreateProductRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.retail.v2alpha.IProduct, - protos.google.cloud.retail.v2alpha.ICreateProductRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.ICreateProductRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IProduct, + protos.google.cloud.retail.v2alpha.ICreateProductRequest | undefined, + {} | undefined, + ] + >; createProduct( - request: protos.google.cloud.retail.v2alpha.ICreateProductRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.retail.v2alpha.IProduct, - protos.google.cloud.retail.v2alpha.ICreateProductRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.ICreateProductRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.retail.v2alpha.IProduct, + | protos.google.cloud.retail.v2alpha.ICreateProductRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createProduct( - request: protos.google.cloud.retail.v2alpha.ICreateProductRequest, - callback: Callback< - protos.google.cloud.retail.v2alpha.IProduct, - protos.google.cloud.retail.v2alpha.ICreateProductRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.ICreateProductRequest, + callback: Callback< + protos.google.cloud.retail.v2alpha.IProduct, + | protos.google.cloud.retail.v2alpha.ICreateProductRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createProduct( - request?: protos.google.cloud.retail.v2alpha.ICreateProductRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.retail.v2alpha.IProduct, - protos.google.cloud.retail.v2alpha.ICreateProductRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.retail.v2alpha.ICreateProductRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.retail.v2alpha.IProduct, - protos.google.cloud.retail.v2alpha.ICreateProductRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.retail.v2alpha.IProduct, - protos.google.cloud.retail.v2alpha.ICreateProductRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.retail.v2alpha.ICreateProductRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.retail.v2alpha.IProduct, + | protos.google.cloud.retail.v2alpha.ICreateProductRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IProduct, + protos.google.cloud.retail.v2alpha.ICreateProductRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('createProduct request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.retail.v2alpha.IProduct, - protos.google.cloud.retail.v2alpha.ICreateProductRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.retail.v2alpha.IProduct, + | protos.google.cloud.retail.v2alpha.ICreateProductRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createProduct response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.createProduct(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.retail.v2alpha.IProduct, - protos.google.cloud.retail.v2alpha.ICreateProductRequest|undefined, {}|undefined - ]) => { - this._log.info('createProduct response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createProduct(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.retail.v2alpha.IProduct, + protos.google.cloud.retail.v2alpha.ICreateProductRequest | undefined, + {} | undefined, + ]) => { + this._log.info('createProduct response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Gets a {@link protos.google.cloud.retail.v2alpha.Product|Product}. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. Full resource name of - * {@link protos.google.cloud.retail.v2alpha.Product|Product}, such as - * `projects/* /locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id`. - * - * If the caller does not have permission to access the - * {@link protos.google.cloud.retail.v2alpha.Product|Product}, regardless of whether or - * not it exists, a PERMISSION_DENIED error is returned. - * - * If the requested {@link protos.google.cloud.retail.v2alpha.Product|Product} does not - * exist, a NOT_FOUND error is returned. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.Product|Product}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/product_service.get_product.js - * region_tag:retail_v2alpha_generated_ProductService_GetProduct_async - */ + /** + * Gets a {@link protos.google.cloud.retail.v2alpha.Product|Product}. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Full resource name of + * {@link protos.google.cloud.retail.v2alpha.Product|Product}, such as + * `projects/* /locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id`. + * + * If the caller does not have permission to access the + * {@link protos.google.cloud.retail.v2alpha.Product|Product}, regardless of whether or + * not it exists, a PERMISSION_DENIED error is returned. + * + * If the requested {@link protos.google.cloud.retail.v2alpha.Product|Product} does not + * exist, a NOT_FOUND error is returned. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.Product|Product}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/product_service.get_product.js + * region_tag:retail_v2alpha_generated_ProductService_GetProduct_async + */ getProduct( - request?: protos.google.cloud.retail.v2alpha.IGetProductRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.retail.v2alpha.IProduct, - protos.google.cloud.retail.v2alpha.IGetProductRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.IGetProductRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IProduct, + protos.google.cloud.retail.v2alpha.IGetProductRequest | undefined, + {} | undefined, + ] + >; getProduct( - request: protos.google.cloud.retail.v2alpha.IGetProductRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.retail.v2alpha.IProduct, - protos.google.cloud.retail.v2alpha.IGetProductRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IGetProductRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.retail.v2alpha.IProduct, + protos.google.cloud.retail.v2alpha.IGetProductRequest | null | undefined, + {} | null | undefined + >, + ): void; getProduct( - request: protos.google.cloud.retail.v2alpha.IGetProductRequest, - callback: Callback< - protos.google.cloud.retail.v2alpha.IProduct, - protos.google.cloud.retail.v2alpha.IGetProductRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IGetProductRequest, + callback: Callback< + protos.google.cloud.retail.v2alpha.IProduct, + protos.google.cloud.retail.v2alpha.IGetProductRequest | null | undefined, + {} | null | undefined + >, + ): void; getProduct( - request?: protos.google.cloud.retail.v2alpha.IGetProductRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.retail.v2alpha.IProduct, - protos.google.cloud.retail.v2alpha.IGetProductRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.retail.v2alpha.IGetProductRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.retail.v2alpha.IProduct, - protos.google.cloud.retail.v2alpha.IGetProductRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.retail.v2alpha.IProduct, - protos.google.cloud.retail.v2alpha.IGetProductRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.retail.v2alpha.IGetProductRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.retail.v2alpha.IProduct, + protos.google.cloud.retail.v2alpha.IGetProductRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IProduct, + protos.google.cloud.retail.v2alpha.IGetProductRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getProduct request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.retail.v2alpha.IProduct, - protos.google.cloud.retail.v2alpha.IGetProductRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.retail.v2alpha.IProduct, + | protos.google.cloud.retail.v2alpha.IGetProductRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getProduct response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.getProduct(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.retail.v2alpha.IProduct, - protos.google.cloud.retail.v2alpha.IGetProductRequest|undefined, {}|undefined - ]) => { - this._log.info('getProduct response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getProduct(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.retail.v2alpha.IProduct, + protos.google.cloud.retail.v2alpha.IGetProductRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getProduct response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Updates a {@link protos.google.cloud.retail.v2alpha.Product|Product}. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.cloud.retail.v2alpha.Product} request.product - * Required. The product to update/create. - * - * If the caller does not have permission to update the - * {@link protos.google.cloud.retail.v2alpha.Product|Product}, regardless of whether or - * not it exists, a PERMISSION_DENIED error is returned. - * - * If the {@link protos.google.cloud.retail.v2alpha.Product|Product} to update does not - * exist and - * {@link protos.google.cloud.retail.v2alpha.UpdateProductRequest.allow_missing|allow_missing} - * is not set, a NOT_FOUND error is returned. - * @param {google.protobuf.FieldMask} request.updateMask - * Indicates which fields in the provided - * {@link protos.google.cloud.retail.v2alpha.Product|Product} to update. The immutable and - * output only fields are NOT supported. If not set, all supported fields (the - * fields that are neither immutable nor output only) are updated. - * - * If an unsupported or unknown field is provided, an INVALID_ARGUMENT error - * is returned. - * - * The attribute key can be updated by setting the mask path as - * "attributes.${key_name}". If a key name is present in the mask but not in - * the patching product from the request, this key will be deleted after the - * update. - * @param {boolean} request.allowMissing - * If set to true, and the {@link protos.google.cloud.retail.v2alpha.Product|Product} is - * not found, a new {@link protos.google.cloud.retail.v2alpha.Product|Product} will be - * created. In this situation, `update_mask` is ignored. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.Product|Product}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/product_service.update_product.js - * region_tag:retail_v2alpha_generated_ProductService_UpdateProduct_async - */ + /** + * Updates a {@link protos.google.cloud.retail.v2alpha.Product|Product}. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.cloud.retail.v2alpha.Product} request.product + * Required. The product to update/create. + * + * If the caller does not have permission to update the + * {@link protos.google.cloud.retail.v2alpha.Product|Product}, regardless of whether or + * not it exists, a PERMISSION_DENIED error is returned. + * + * If the {@link protos.google.cloud.retail.v2alpha.Product|Product} to update does not + * exist and + * {@link protos.google.cloud.retail.v2alpha.UpdateProductRequest.allow_missing|allow_missing} + * is not set, a NOT_FOUND error is returned. + * @param {google.protobuf.FieldMask} request.updateMask + * Indicates which fields in the provided + * {@link protos.google.cloud.retail.v2alpha.Product|Product} to update. The immutable and + * output only fields are NOT supported. If not set, all supported fields (the + * fields that are neither immutable nor output only) are updated. + * + * If an unsupported or unknown field is provided, an INVALID_ARGUMENT error + * is returned. + * + * The attribute key can be updated by setting the mask path as + * "attributes.${key_name}". If a key name is present in the mask but not in + * the patching product from the request, this key will be deleted after the + * update. + * @param {boolean} request.allowMissing + * If set to true, and the {@link protos.google.cloud.retail.v2alpha.Product|Product} is + * not found, a new {@link protos.google.cloud.retail.v2alpha.Product|Product} will be + * created. In this situation, `update_mask` is ignored. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.Product|Product}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/product_service.update_product.js + * region_tag:retail_v2alpha_generated_ProductService_UpdateProduct_async + */ updateProduct( - request?: protos.google.cloud.retail.v2alpha.IUpdateProductRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.retail.v2alpha.IProduct, - protos.google.cloud.retail.v2alpha.IUpdateProductRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.IUpdateProductRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IProduct, + protos.google.cloud.retail.v2alpha.IUpdateProductRequest | undefined, + {} | undefined, + ] + >; updateProduct( - request: protos.google.cloud.retail.v2alpha.IUpdateProductRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.retail.v2alpha.IProduct, - protos.google.cloud.retail.v2alpha.IUpdateProductRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IUpdateProductRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.retail.v2alpha.IProduct, + | protos.google.cloud.retail.v2alpha.IUpdateProductRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateProduct( - request: protos.google.cloud.retail.v2alpha.IUpdateProductRequest, - callback: Callback< - protos.google.cloud.retail.v2alpha.IProduct, - protos.google.cloud.retail.v2alpha.IUpdateProductRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IUpdateProductRequest, + callback: Callback< + protos.google.cloud.retail.v2alpha.IProduct, + | protos.google.cloud.retail.v2alpha.IUpdateProductRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateProduct( - request?: protos.google.cloud.retail.v2alpha.IUpdateProductRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.retail.v2alpha.IProduct, - protos.google.cloud.retail.v2alpha.IUpdateProductRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.retail.v2alpha.IUpdateProductRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.retail.v2alpha.IProduct, - protos.google.cloud.retail.v2alpha.IUpdateProductRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.retail.v2alpha.IProduct, - protos.google.cloud.retail.v2alpha.IUpdateProductRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.retail.v2alpha.IUpdateProductRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.retail.v2alpha.IProduct, + | protos.google.cloud.retail.v2alpha.IUpdateProductRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IProduct, + protos.google.cloud.retail.v2alpha.IUpdateProductRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'product.name': request.product!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'product.name': request.product!.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateProduct request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.retail.v2alpha.IProduct, - protos.google.cloud.retail.v2alpha.IUpdateProductRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.retail.v2alpha.IProduct, + | protos.google.cloud.retail.v2alpha.IUpdateProductRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateProduct response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.updateProduct(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.retail.v2alpha.IProduct, - protos.google.cloud.retail.v2alpha.IUpdateProductRequest|undefined, {}|undefined - ]) => { - this._log.info('updateProduct response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateProduct(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.retail.v2alpha.IProduct, + protos.google.cloud.retail.v2alpha.IUpdateProductRequest | undefined, + {} | undefined, + ]) => { + this._log.info('updateProduct response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Deletes a {@link protos.google.cloud.retail.v2alpha.Product|Product}. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. Full resource name of - * {@link protos.google.cloud.retail.v2alpha.Product|Product}, such as - * `projects/* /locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id`. - * - * If the caller does not have permission to delete the - * {@link protos.google.cloud.retail.v2alpha.Product|Product}, regardless of whether or - * not it exists, a PERMISSION_DENIED error is returned. - * - * If the {@link protos.google.cloud.retail.v2alpha.Product|Product} to delete does not - * exist, a NOT_FOUND error is returned. - * - * The {@link protos.google.cloud.retail.v2alpha.Product|Product} to delete can neither be - * a - * {@link protos.google.cloud.retail.v2alpha.Product.Type.COLLECTION|Product.Type.COLLECTION} - * {@link protos.google.cloud.retail.v2alpha.Product|Product} member nor a - * {@link protos.google.cloud.retail.v2alpha.Product.Type.PRIMARY|Product.Type.PRIMARY} - * {@link protos.google.cloud.retail.v2alpha.Product|Product} with more than one - * {@link protos.google.cloud.retail.v2alpha.Product.Type.VARIANT|variants}. Otherwise, an - * INVALID_ARGUMENT error is returned. - * - * All inventory information for the named - * {@link protos.google.cloud.retail.v2alpha.Product|Product} will be deleted. - * @param {boolean} request.force - * This value only applies to the case when the target product is of type - * PRIMARY. - * When deleting a product of VARIANT/COLLECTION type, this value - * will be ignored. - * When set to true, the subsequent variant products will be - * deleted. - * When set to false, if the primary product has active variant products, an - * error will be returned. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/product_service.delete_product.js - * region_tag:retail_v2alpha_generated_ProductService_DeleteProduct_async - */ + /** + * Deletes a {@link protos.google.cloud.retail.v2alpha.Product|Product}. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Full resource name of + * {@link protos.google.cloud.retail.v2alpha.Product|Product}, such as + * `projects/* /locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id`. + * + * If the caller does not have permission to delete the + * {@link protos.google.cloud.retail.v2alpha.Product|Product}, regardless of whether or + * not it exists, a PERMISSION_DENIED error is returned. + * + * If the {@link protos.google.cloud.retail.v2alpha.Product|Product} to delete does not + * exist, a NOT_FOUND error is returned. + * + * The {@link protos.google.cloud.retail.v2alpha.Product|Product} to delete can neither be + * a + * {@link protos.google.cloud.retail.v2alpha.Product.Type.COLLECTION|Product.Type.COLLECTION} + * {@link protos.google.cloud.retail.v2alpha.Product|Product} member nor a + * {@link protos.google.cloud.retail.v2alpha.Product.Type.PRIMARY|Product.Type.PRIMARY} + * {@link protos.google.cloud.retail.v2alpha.Product|Product} with more than one + * {@link protos.google.cloud.retail.v2alpha.Product.Type.VARIANT|variants}. Otherwise, an + * INVALID_ARGUMENT error is returned. + * + * All inventory information for the named + * {@link protos.google.cloud.retail.v2alpha.Product|Product} will be deleted. + * @param {boolean} request.force + * This value only applies to the case when the target product is of type + * PRIMARY. + * When deleting a product of VARIANT/COLLECTION type, this value + * will be ignored. + * When set to true, the subsequent variant products will be + * deleted. + * When set to false, if the primary product has active variant products, an + * error will be returned. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/product_service.delete_product.js + * region_tag:retail_v2alpha_generated_ProductService_DeleteProduct_async + */ deleteProduct( - request?: protos.google.cloud.retail.v2alpha.IDeleteProductRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.cloud.retail.v2alpha.IDeleteProductRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.IDeleteProductRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.cloud.retail.v2alpha.IDeleteProductRequest | undefined, + {} | undefined, + ] + >; deleteProduct( - request: protos.google.cloud.retail.v2alpha.IDeleteProductRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.cloud.retail.v2alpha.IDeleteProductRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IDeleteProductRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.cloud.retail.v2alpha.IDeleteProductRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteProduct( - request: protos.google.cloud.retail.v2alpha.IDeleteProductRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.cloud.retail.v2alpha.IDeleteProductRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IDeleteProductRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.cloud.retail.v2alpha.IDeleteProductRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteProduct( - request?: protos.google.cloud.retail.v2alpha.IDeleteProductRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.protobuf.IEmpty, - protos.google.cloud.retail.v2alpha.IDeleteProductRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.retail.v2alpha.IDeleteProductRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.cloud.retail.v2alpha.IDeleteProductRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.cloud.retail.v2alpha.IDeleteProductRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.retail.v2alpha.IDeleteProductRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + | protos.google.cloud.retail.v2alpha.IDeleteProductRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.cloud.retail.v2alpha.IDeleteProductRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('deleteProduct request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.cloud.retail.v2alpha.IDeleteProductRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.cloud.retail.v2alpha.IDeleteProductRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteProduct response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.deleteProduct(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.cloud.retail.v2alpha.IDeleteProductRequest|undefined, {}|undefined - ]) => { - this._log.info('deleteProduct response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteProduct(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.cloud.retail.v2alpha.IDeleteProductRequest | undefined, + {} | undefined, + ]) => { + this._log.info('deleteProduct response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Permanently deletes all selected - * {@link protos.google.cloud.retail.v2alpha.Product|Product}s under a branch. - * - * This process is asynchronous. If the request is valid, the removal will be - * enqueued and processed offline. Depending on the number of - * {@link protos.google.cloud.retail.v2alpha.Product|Product}s, this operation could take - * hours to complete. Before the operation completes, some - * {@link protos.google.cloud.retail.v2alpha.Product|Product}s may still be returned by - * {@link protos.google.cloud.retail.v2alpha.ProductService.GetProduct|ProductService.GetProduct} - * or - * {@link protos.google.cloud.retail.v2alpha.ProductService.ListProducts|ProductService.ListProducts}. - * - * Depending on the number of {@link protos.google.cloud.retail.v2alpha.Product|Product}s, - * this operation could take hours to complete. To get a sample of - * {@link protos.google.cloud.retail.v2alpha.Product|Product}s that would be deleted, set - * {@link protos.google.cloud.retail.v2alpha.PurgeProductsRequest.force|PurgeProductsRequest.force} - * to false. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The resource name of the branch under which the products are - * created. The format is - * `projects/${projectId}/locations/global/catalogs/${catalogId}/branches/${branchId}` - * @param {string} request.filter - * Required. The filter string to specify the products to be deleted with a - * length limit of 5,000 characters. - * - * Empty string filter is not allowed. "*" implies delete all items in a - * branch. - * - * The eligible fields for filtering are: - * - * * `availability`: Double quoted - * {@link protos.google.cloud.retail.v2alpha.Product.availability|Product.availability} - * string. - * * `create_time` : in ISO 8601 "zulu" format. - * - * Supported syntax: - * - * * Comparators (">", "<", ">=", "<=", "="). - * Examples: - * * create_time <= "2015-02-13T17:05:46Z" - * * availability = "IN_STOCK" - * - * * Conjunctions ("AND") - * Examples: - * * create_time <= "2015-02-13T17:05:46Z" AND availability = "PREORDER" - * - * * Disjunctions ("OR") - * Examples: - * * create_time <= "2015-02-13T17:05:46Z" OR availability = "IN_STOCK" - * - * * Can support nested queries. - * Examples: - * * (create_time <= "2015-02-13T17:05:46Z" AND availability = "PREORDER") - * OR (create_time >= "2015-02-14T13:03:32Z" AND availability = "IN_STOCK") - * - * * Filter Limits: - * * Filter should not contain more than 6 conditions. - * * Max nesting depth should not exceed 2 levels. - * - * Examples queries: - * * Delete back order products created before a timestamp. - * create_time <= "2015-02-13T17:05:46Z" OR availability = "BACKORDER" - * @param {boolean} request.force - * Actually perform the purge. - * If `force` is set to false, the method will return the expected purge count - * without deleting any products. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing - * a long running operation. Its `promise()` method returns a promise - * you can `await` for. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/product_service.purge_products.js - * region_tag:retail_v2alpha_generated_ProductService_PurgeProducts_async - */ + /** + * Permanently deletes all selected + * {@link protos.google.cloud.retail.v2alpha.Product|Product}s under a branch. + * + * This process is asynchronous. If the request is valid, the removal will be + * enqueued and processed offline. Depending on the number of + * {@link protos.google.cloud.retail.v2alpha.Product|Product}s, this operation could take + * hours to complete. Before the operation completes, some + * {@link protos.google.cloud.retail.v2alpha.Product|Product}s may still be returned by + * {@link protos.google.cloud.retail.v2alpha.ProductService.GetProduct|ProductService.GetProduct} + * or + * {@link protos.google.cloud.retail.v2alpha.ProductService.ListProducts|ProductService.ListProducts}. + * + * Depending on the number of {@link protos.google.cloud.retail.v2alpha.Product|Product}s, + * this operation could take hours to complete. To get a sample of + * {@link protos.google.cloud.retail.v2alpha.Product|Product}s that would be deleted, set + * {@link protos.google.cloud.retail.v2alpha.PurgeProductsRequest.force|PurgeProductsRequest.force} + * to false. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The resource name of the branch under which the products are + * created. The format is + * `projects/${projectId}/locations/global/catalogs/${catalogId}/branches/${branchId}` + * @param {string} request.filter + * Required. The filter string to specify the products to be deleted with a + * length limit of 5,000 characters. + * + * Empty string filter is not allowed. "*" implies delete all items in a + * branch. + * + * The eligible fields for filtering are: + * + * * `availability`: Double quoted + * {@link protos.google.cloud.retail.v2alpha.Product.availability|Product.availability} + * string. + * * `create_time` : in ISO 8601 "zulu" format. + * + * Supported syntax: + * + * * Comparators (">", "<", ">=", "<=", "="). + * Examples: + * * create_time <= "2015-02-13T17:05:46Z" + * * availability = "IN_STOCK" + * + * * Conjunctions ("AND") + * Examples: + * * create_time <= "2015-02-13T17:05:46Z" AND availability = "PREORDER" + * + * * Disjunctions ("OR") + * Examples: + * * create_time <= "2015-02-13T17:05:46Z" OR availability = "IN_STOCK" + * + * * Can support nested queries. + * Examples: + * * (create_time <= "2015-02-13T17:05:46Z" AND availability = "PREORDER") + * OR (create_time >= "2015-02-14T13:03:32Z" AND availability = "IN_STOCK") + * + * * Filter Limits: + * * Filter should not contain more than 6 conditions. + * * Max nesting depth should not exceed 2 levels. + * + * Examples queries: + * * Delete back order products created before a timestamp. + * create_time <= "2015-02-13T17:05:46Z" OR availability = "BACKORDER" + * @param {boolean} request.force + * Actually perform the purge. + * If `force` is set to false, the method will return the expected purge count + * without deleting any products. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/product_service.purge_products.js + * region_tag:retail_v2alpha_generated_ProductService_PurgeProducts_async + */ purgeProducts( - request?: protos.google.cloud.retail.v2alpha.IPurgeProductsRequest, - options?: CallOptions): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.IPurgeProductsRequest, + options?: CallOptions, + ): Promise< + [ + LROperation< + protos.google.cloud.retail.v2alpha.IPurgeProductsResponse, + protos.google.cloud.retail.v2alpha.IPurgeProductsMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; purgeProducts( - request: protos.google.cloud.retail.v2alpha.IPurgeProductsRequest, - options: CallOptions, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IPurgeProductsRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IPurgeProductsResponse, + protos.google.cloud.retail.v2alpha.IPurgeProductsMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; purgeProducts( - request: protos.google.cloud.retail.v2alpha.IPurgeProductsRequest, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IPurgeProductsRequest, + callback: Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IPurgeProductsResponse, + protos.google.cloud.retail.v2alpha.IPurgeProductsMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; purgeProducts( - request?: protos.google.cloud.retail.v2alpha.IPurgeProductsRequest, - optionsOrCallback?: CallOptions|Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>, - callback?: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>|void { + request?: protos.google.cloud.retail.v2alpha.IPurgeProductsRequest, + optionsOrCallback?: + | CallOptions + | Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IPurgeProductsResponse, + protos.google.cloud.retail.v2alpha.IPurgeProductsMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + callback?: Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IPurgeProductsResponse, + protos.google.cloud.retail.v2alpha.IPurgeProductsMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + LROperation< + protos.google.cloud.retail.v2alpha.IPurgeProductsResponse, + protos.google.cloud.retail.v2alpha.IPurgeProductsMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IPurgeProductsResponse, + protos.google.cloud.retail.v2alpha.IPurgeProductsMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, rawResponse, _) => { this._log.info('purgeProducts response %j', rawResponse); callback!(error, response, rawResponse, _); // We verified `callback` above. } : undefined; this._log.info('purgeProducts request %j', request); - return this.innerApiCalls.purgeProducts(request, options, wrappedCallback) - ?.then(([response, rawResponse, _]: [ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]) => { - this._log.info('purgeProducts response %j', rawResponse); - return [response, rawResponse, _]; - }); + return this.innerApiCalls + .purgeProducts(request, options, wrappedCallback) + ?.then( + ([response, rawResponse, _]: [ + LROperation< + protos.google.cloud.retail.v2alpha.IPurgeProductsResponse, + protos.google.cloud.retail.v2alpha.IPurgeProductsMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ]) => { + this._log.info('purgeProducts response %j', rawResponse); + return [response, rawResponse, _]; + }, + ); } -/** - * Check the status of the long running operation returned by `purgeProducts()`. - * @param {String} name - * The operation name that will be passed. - * @returns {Promise} - The promise which resolves to an object. - * The decoded operation object has result and metadata field to get information from. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/product_service.purge_products.js - * region_tag:retail_v2alpha_generated_ProductService_PurgeProducts_async - */ - async checkPurgeProductsProgress(name: string): Promise>{ + /** + * Check the status of the long running operation returned by `purgeProducts()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/product_service.purge_products.js + * region_tag:retail_v2alpha_generated_ProductService_PurgeProducts_async + */ + async checkPurgeProductsProgress( + name: string, + ): Promise< + LROperation< + protos.google.cloud.retail.v2alpha.PurgeProductsResponse, + protos.google.cloud.retail.v2alpha.PurgeProductsMetadata + > + > { this._log.info('purgeProducts long-running'); - const request = new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest({name}); + const request = + new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( + { name }, + ); const [operation] = await this.operationsClient.getOperation(request); - const decodeOperation = new this._gaxModule.Operation(operation, this.descriptors.longrunning.purgeProducts, this._gaxModule.createDefaultBackoffSettings()); - return decodeOperation as LROperation; + const decodeOperation = new this._gaxModule.Operation( + operation, + this.descriptors.longrunning.purgeProducts, + this._gaxModule.createDefaultBackoffSettings(), + ); + return decodeOperation as LROperation< + protos.google.cloud.retail.v2alpha.PurgeProductsResponse, + protos.google.cloud.retail.v2alpha.PurgeProductsMetadata + >; } -/** - * Bulk import of multiple {@link protos.google.cloud.retail.v2alpha.Product|Product}s. - * - * Request processing may be synchronous. - * Non-existing items are created. - * - * Note that it is possible for a subset of the - * {@link protos.google.cloud.retail.v2alpha.Product|Product}s to be successfully updated. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. - * `projects/1234/locations/global/catalogs/default_catalog/branches/default_branch` - * - * If no updateMask is specified, requires products.create permission. - * If updateMask is specified, requires products.update permission. - * @param {string} request.requestId - * Deprecated. This field has no effect. - * @param {google.cloud.retail.v2alpha.ProductInputConfig} request.inputConfig - * Required. The desired input location of the data. - * @param {google.cloud.retail.v2alpha.ImportErrorsConfig} request.errorsConfig - * The desired location of errors incurred during the Import. - * @param {google.protobuf.FieldMask} request.updateMask - * Indicates which fields in the provided imported `products` to update. If - * not set, all fields are updated. If provided, only the existing product - * fields are updated. Missing products will not be created. - * @param {google.cloud.retail.v2alpha.ImportProductsRequest.ReconciliationMode} request.reconciliationMode - * The mode of reconciliation between existing products and the products to be - * imported. Defaults to - * {@link protos.google.cloud.retail.v2alpha.ImportProductsRequest.ReconciliationMode.INCREMENTAL|ReconciliationMode.INCREMENTAL}. - * @param {string} request.notificationPubsubTopic - * Full Pub/Sub topic name for receiving notification. If this field is set, - * when the import is finished, a notification is sent to - * specified Pub/Sub topic. The message data is JSON string of a - * {@link protos.google.longrunning.Operation|Operation}. - * - * Format of the Pub/Sub topic is `projects/{project}/topics/{topic}`. It has - * to be within the same project as - * {@link protos.google.cloud.retail.v2alpha.ImportProductsRequest.parent|ImportProductsRequest.parent}. - * Make sure that both - * `cloud-retail-customer-data-access@system.gserviceaccount.com` and - * `service-@gcp-sa-retail.iam.gserviceaccount.com` - * have the `pubsub.topics.publish` IAM permission on the topic. - * - * Only supported when - * {@link protos.google.cloud.retail.v2alpha.ImportProductsRequest.reconciliation_mode|ImportProductsRequest.reconciliation_mode} - * is set to `FULL`. - * @param {boolean} request.skipDefaultBranchProtection - * If true, this performs the FULL import even if it would delete a large - * proportion of the products in the default branch, which could potentially - * cause outages if you have live predict/search traffic. - * - * Only supported when - * {@link protos.google.cloud.retail.v2alpha.ImportProductsRequest.reconciliation_mode|ImportProductsRequest.reconciliation_mode} - * is set to `FULL`. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing - * a long running operation. Its `promise()` method returns a promise - * you can `await` for. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/product_service.import_products.js - * region_tag:retail_v2alpha_generated_ProductService_ImportProducts_async - */ + /** + * Bulk import of multiple {@link protos.google.cloud.retail.v2alpha.Product|Product}s. + * + * Request processing may be synchronous. + * Non-existing items are created. + * + * Note that it is possible for a subset of the + * {@link protos.google.cloud.retail.v2alpha.Product|Product}s to be successfully updated. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. + * `projects/1234/locations/global/catalogs/default_catalog/branches/default_branch` + * + * If no updateMask is specified, requires products.create permission. + * If updateMask is specified, requires products.update permission. + * @param {string} request.requestId + * Deprecated. This field has no effect. + * @param {google.cloud.retail.v2alpha.ProductInputConfig} request.inputConfig + * Required. The desired input location of the data. + * @param {google.cloud.retail.v2alpha.ImportErrorsConfig} request.errorsConfig + * The desired location of errors incurred during the Import. + * @param {google.protobuf.FieldMask} request.updateMask + * Indicates which fields in the provided imported `products` to update. If + * not set, all fields are updated. If provided, only the existing product + * fields are updated. Missing products will not be created. + * @param {google.cloud.retail.v2alpha.ImportProductsRequest.ReconciliationMode} request.reconciliationMode + * The mode of reconciliation between existing products and the products to be + * imported. Defaults to + * {@link protos.google.cloud.retail.v2alpha.ImportProductsRequest.ReconciliationMode.INCREMENTAL|ReconciliationMode.INCREMENTAL}. + * @param {string} request.notificationPubsubTopic + * Full Pub/Sub topic name for receiving notification. If this field is set, + * when the import is finished, a notification is sent to + * specified Pub/Sub topic. The message data is JSON string of a + * {@link protos.google.longrunning.Operation|Operation}. + * + * Format of the Pub/Sub topic is `projects/{project}/topics/{topic}`. It has + * to be within the same project as + * {@link protos.google.cloud.retail.v2alpha.ImportProductsRequest.parent|ImportProductsRequest.parent}. + * Make sure that both + * `cloud-retail-customer-data-access@system.gserviceaccount.com` and + * `service-@gcp-sa-retail.iam.gserviceaccount.com` + * have the `pubsub.topics.publish` IAM permission on the topic. + * + * Only supported when + * {@link protos.google.cloud.retail.v2alpha.ImportProductsRequest.reconciliation_mode|ImportProductsRequest.reconciliation_mode} + * is set to `FULL`. + * @param {boolean} request.skipDefaultBranchProtection + * If true, this performs the FULL import even if it would delete a large + * proportion of the products in the default branch, which could potentially + * cause outages if you have live predict/search traffic. + * + * Only supported when + * {@link protos.google.cloud.retail.v2alpha.ImportProductsRequest.reconciliation_mode|ImportProductsRequest.reconciliation_mode} + * is set to `FULL`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/product_service.import_products.js + * region_tag:retail_v2alpha_generated_ProductService_ImportProducts_async + */ importProducts( - request?: protos.google.cloud.retail.v2alpha.IImportProductsRequest, - options?: CallOptions): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.IImportProductsRequest, + options?: CallOptions, + ): Promise< + [ + LROperation< + protos.google.cloud.retail.v2alpha.IImportProductsResponse, + protos.google.cloud.retail.v2alpha.IImportMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; importProducts( - request: protos.google.cloud.retail.v2alpha.IImportProductsRequest, - options: CallOptions, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IImportProductsRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IImportProductsResponse, + protos.google.cloud.retail.v2alpha.IImportMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; importProducts( - request: protos.google.cloud.retail.v2alpha.IImportProductsRequest, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IImportProductsRequest, + callback: Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IImportProductsResponse, + protos.google.cloud.retail.v2alpha.IImportMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; importProducts( - request?: protos.google.cloud.retail.v2alpha.IImportProductsRequest, - optionsOrCallback?: CallOptions|Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>, - callback?: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>|void { + request?: protos.google.cloud.retail.v2alpha.IImportProductsRequest, + optionsOrCallback?: + | CallOptions + | Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IImportProductsResponse, + protos.google.cloud.retail.v2alpha.IImportMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + callback?: Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IImportProductsResponse, + protos.google.cloud.retail.v2alpha.IImportMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + LROperation< + protos.google.cloud.retail.v2alpha.IImportProductsResponse, + protos.google.cloud.retail.v2alpha.IImportMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IImportProductsResponse, + protos.google.cloud.retail.v2alpha.IImportMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, rawResponse, _) => { this._log.info('importProducts response %j', rawResponse); callback!(error, response, rawResponse, _); // We verified `callback` above. } : undefined; this._log.info('importProducts request %j', request); - return this.innerApiCalls.importProducts(request, options, wrappedCallback) - ?.then(([response, rawResponse, _]: [ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]) => { - this._log.info('importProducts response %j', rawResponse); - return [response, rawResponse, _]; - }); + return this.innerApiCalls + .importProducts(request, options, wrappedCallback) + ?.then( + ([response, rawResponse, _]: [ + LROperation< + protos.google.cloud.retail.v2alpha.IImportProductsResponse, + protos.google.cloud.retail.v2alpha.IImportMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ]) => { + this._log.info('importProducts response %j', rawResponse); + return [response, rawResponse, _]; + }, + ); } -/** - * Check the status of the long running operation returned by `importProducts()`. - * @param {String} name - * The operation name that will be passed. - * @returns {Promise} - The promise which resolves to an object. - * The decoded operation object has result and metadata field to get information from. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/product_service.import_products.js - * region_tag:retail_v2alpha_generated_ProductService_ImportProducts_async - */ - async checkImportProductsProgress(name: string): Promise>{ + /** + * Check the status of the long running operation returned by `importProducts()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/product_service.import_products.js + * region_tag:retail_v2alpha_generated_ProductService_ImportProducts_async + */ + async checkImportProductsProgress( + name: string, + ): Promise< + LROperation< + protos.google.cloud.retail.v2alpha.ImportProductsResponse, + protos.google.cloud.retail.v2alpha.ImportMetadata + > + > { this._log.info('importProducts long-running'); - const request = new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest({name}); + const request = + new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( + { name }, + ); const [operation] = await this.operationsClient.getOperation(request); - const decodeOperation = new this._gaxModule.Operation(operation, this.descriptors.longrunning.importProducts, this._gaxModule.createDefaultBackoffSettings()); - return decodeOperation as LROperation; + const decodeOperation = new this._gaxModule.Operation( + operation, + this.descriptors.longrunning.importProducts, + this._gaxModule.createDefaultBackoffSettings(), + ); + return decodeOperation as LROperation< + protos.google.cloud.retail.v2alpha.ImportProductsResponse, + protos.google.cloud.retail.v2alpha.ImportMetadata + >; } -/** - * Exports multiple {@link protos.google.cloud.retail.v2alpha.Product|Product}s. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. Resource name of a {@link protos.google.cloud.retail.v2alpha.Branch|Branch}, - * and `default_branch` for branch_id component is supported. For example - * `projects/1234/locations/global/catalogs/default_catalog/branches/default_branch` - * @param {google.cloud.retail.v2alpha.OutputConfig} request.outputConfig - * Required. The output location of the data. - * @param {string} request.filter - * A filtering expression to specify restrictions on returned events. - * The expression is a sequence of terms. Each term applies a restriction to - * the returned products. Use this expression to restrict results to a - * specific time range, tag, or stock state or to filter products by product - * type. - * For example, `lastModifiedTime > "2012-04-23T18:25:43.511Z" - * lastModifiedTime<"2012-04-23T18:25:43.511Z" productType=primary` - * - * We expect only four types of fields: - * - * * `lastModifiedTime`: This can be specified twice, once with a - * less than operator and once with a greater than operator. The - * `lastModifiedTime` restriction should result in one, contiguous, - * valid, last-modified, time range. - * - * * `productType`: Supported values are `primary` and `variant`. The - * Boolean operators `OR` and `NOT` are supported if the expression is - * enclosed in parentheses and must be separated from the - * `productType` values by a space. - * - * * `availability`: Supported values are `IN_STOCK`, `OUT_OF_STOCK`, - * `PREORDER`, and `BACKORDER`. Boolean operators `OR` and `NOT` are - * supported if the expression is enclosed in parentheses and must be - * separated from the `availability` values by a space. - * - * * `Tag expressions`: Restricts output to products that match all of the - * specified tags. Boolean operators `OR` and `NOT` are supported if the - * expression is enclosed in parentheses and the operators are separated - * from the tag values by a space. Also supported is '`-"tagA"`', which - * is equivalent to '`NOT "tagA"`'. Tag values must be double-quoted, - * UTF-8 encoded strings and have a size limit of 1,000 characters. - * - * Some examples of valid filters expressions: - * - * * Example 1: `lastModifiedTime > "2012-04-23T18:25:43.511Z" - * lastModifiedTime < "2012-04-23T18:30:43.511Z"` - * * Example 2: `lastModifiedTime > "2012-04-23T18:25:43.511Z" - * productType = "variant"` - * * Example 3: `tag=("Red" OR "Blue") tag="New-Arrival" - * tag=(NOT "promotional") - * productType = "primary" lastModifiedTime < - * "2018-04-23T18:30:43.511Z"` - * * Example 4: `lastModifiedTime > "2012-04-23T18:25:43.511Z"` - * * Example 5: `availability = (IN_STOCK OR BACKORDER)` - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing - * a long running operation. Its `promise()` method returns a promise - * you can `await` for. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/product_service.export_products.js - * region_tag:retail_v2alpha_generated_ProductService_ExportProducts_async - */ + /** + * Exports multiple {@link protos.google.cloud.retail.v2alpha.Product|Product}s. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Resource name of a {@link protos.google.cloud.retail.v2alpha.Branch|Branch}, + * and `default_branch` for branch_id component is supported. For example + * `projects/1234/locations/global/catalogs/default_catalog/branches/default_branch` + * @param {google.cloud.retail.v2alpha.OutputConfig} request.outputConfig + * Required. The output location of the data. + * @param {string} request.filter + * A filtering expression to specify restrictions on returned events. + * The expression is a sequence of terms. Each term applies a restriction to + * the returned products. Use this expression to restrict results to a + * specific time range, tag, or stock state or to filter products by product + * type. + * For example, `lastModifiedTime > "2012-04-23T18:25:43.511Z" + * lastModifiedTime<"2012-04-23T18:25:43.511Z" productType=primary` + * + * We expect only four types of fields: + * + * * `lastModifiedTime`: This can be specified twice, once with a + * less than operator and once with a greater than operator. The + * `lastModifiedTime` restriction should result in one, contiguous, + * valid, last-modified, time range. + * + * * `productType`: Supported values are `primary` and `variant`. The + * Boolean operators `OR` and `NOT` are supported if the expression is + * enclosed in parentheses and must be separated from the + * `productType` values by a space. + * + * * `availability`: Supported values are `IN_STOCK`, `OUT_OF_STOCK`, + * `PREORDER`, and `BACKORDER`. Boolean operators `OR` and `NOT` are + * supported if the expression is enclosed in parentheses and must be + * separated from the `availability` values by a space. + * + * * `Tag expressions`: Restricts output to products that match all of the + * specified tags. Boolean operators `OR` and `NOT` are supported if the + * expression is enclosed in parentheses and the operators are separated + * from the tag values by a space. Also supported is '`-"tagA"`', which + * is equivalent to '`NOT "tagA"`'. Tag values must be double-quoted, + * UTF-8 encoded strings and have a size limit of 1,000 characters. + * + * Some examples of valid filters expressions: + * + * * Example 1: `lastModifiedTime > "2012-04-23T18:25:43.511Z" + * lastModifiedTime < "2012-04-23T18:30:43.511Z"` + * * Example 2: `lastModifiedTime > "2012-04-23T18:25:43.511Z" + * productType = "variant"` + * * Example 3: `tag=("Red" OR "Blue") tag="New-Arrival" + * tag=(NOT "promotional") + * productType = "primary" lastModifiedTime < + * "2018-04-23T18:30:43.511Z"` + * * Example 4: `lastModifiedTime > "2012-04-23T18:25:43.511Z"` + * * Example 5: `availability = (IN_STOCK OR BACKORDER)` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/product_service.export_products.js + * region_tag:retail_v2alpha_generated_ProductService_ExportProducts_async + */ exportProducts( - request?: protos.google.cloud.retail.v2alpha.IExportProductsRequest, - options?: CallOptions): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.IExportProductsRequest, + options?: CallOptions, + ): Promise< + [ + LROperation< + protos.google.cloud.retail.v2alpha.IExportProductsResponse, + protos.google.cloud.retail.v2alpha.IExportMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; exportProducts( - request: protos.google.cloud.retail.v2alpha.IExportProductsRequest, - options: CallOptions, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IExportProductsRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IExportProductsResponse, + protos.google.cloud.retail.v2alpha.IExportMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; exportProducts( - request: protos.google.cloud.retail.v2alpha.IExportProductsRequest, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IExportProductsRequest, + callback: Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IExportProductsResponse, + protos.google.cloud.retail.v2alpha.IExportMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; exportProducts( - request?: protos.google.cloud.retail.v2alpha.IExportProductsRequest, - optionsOrCallback?: CallOptions|Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>, - callback?: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>|void { + request?: protos.google.cloud.retail.v2alpha.IExportProductsRequest, + optionsOrCallback?: + | CallOptions + | Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IExportProductsResponse, + protos.google.cloud.retail.v2alpha.IExportMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + callback?: Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IExportProductsResponse, + protos.google.cloud.retail.v2alpha.IExportMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + LROperation< + protos.google.cloud.retail.v2alpha.IExportProductsResponse, + protos.google.cloud.retail.v2alpha.IExportMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IExportProductsResponse, + protos.google.cloud.retail.v2alpha.IExportMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, rawResponse, _) => { this._log.info('exportProducts response %j', rawResponse); callback!(error, response, rawResponse, _); // We verified `callback` above. } : undefined; this._log.info('exportProducts request %j', request); - return this.innerApiCalls.exportProducts(request, options, wrappedCallback) - ?.then(([response, rawResponse, _]: [ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]) => { - this._log.info('exportProducts response %j', rawResponse); - return [response, rawResponse, _]; - }); + return this.innerApiCalls + .exportProducts(request, options, wrappedCallback) + ?.then( + ([response, rawResponse, _]: [ + LROperation< + protos.google.cloud.retail.v2alpha.IExportProductsResponse, + protos.google.cloud.retail.v2alpha.IExportMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ]) => { + this._log.info('exportProducts response %j', rawResponse); + return [response, rawResponse, _]; + }, + ); } -/** - * Check the status of the long running operation returned by `exportProducts()`. - * @param {String} name - * The operation name that will be passed. - * @returns {Promise} - The promise which resolves to an object. - * The decoded operation object has result and metadata field to get information from. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/product_service.export_products.js - * region_tag:retail_v2alpha_generated_ProductService_ExportProducts_async - */ - async checkExportProductsProgress(name: string): Promise>{ + /** + * Check the status of the long running operation returned by `exportProducts()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/product_service.export_products.js + * region_tag:retail_v2alpha_generated_ProductService_ExportProducts_async + */ + async checkExportProductsProgress( + name: string, + ): Promise< + LROperation< + protos.google.cloud.retail.v2alpha.ExportProductsResponse, + protos.google.cloud.retail.v2alpha.ExportMetadata + > + > { this._log.info('exportProducts long-running'); - const request = new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest({name}); + const request = + new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( + { name }, + ); const [operation] = await this.operationsClient.getOperation(request); - const decodeOperation = new this._gaxModule.Operation(operation, this.descriptors.longrunning.exportProducts, this._gaxModule.createDefaultBackoffSettings()); - return decodeOperation as LROperation; + const decodeOperation = new this._gaxModule.Operation( + operation, + this.descriptors.longrunning.exportProducts, + this._gaxModule.createDefaultBackoffSettings(), + ); + return decodeOperation as LROperation< + protos.google.cloud.retail.v2alpha.ExportProductsResponse, + protos.google.cloud.retail.v2alpha.ExportMetadata + >; } -/** - * Updates inventory information for a - * {@link protos.google.cloud.retail.v2alpha.Product|Product} while respecting the last - * update timestamps of each inventory field. - * - * This process is asynchronous and does not require the - * {@link protos.google.cloud.retail.v2alpha.Product|Product} to exist before updating - * fulfillment information. If the request is valid, the update is enqueued - * and processed downstream. As a consequence, when a response is returned, - * updates are not immediately manifested in the - * {@link protos.google.cloud.retail.v2alpha.Product|Product} queried by - * {@link protos.google.cloud.retail.v2alpha.ProductService.GetProduct|ProductService.GetProduct} - * or - * {@link protos.google.cloud.retail.v2alpha.ProductService.ListProducts|ProductService.ListProducts}. - * - * When inventory is updated with - * {@link protos.google.cloud.retail.v2alpha.ProductService.CreateProduct|ProductService.CreateProduct} - * and - * {@link protos.google.cloud.retail.v2alpha.ProductService.UpdateProduct|ProductService.UpdateProduct}, - * the specified inventory field value(s) overwrite any existing value(s) - * while ignoring the last update time for this field. Furthermore, the last - * update times for the specified inventory fields are overwritten by the - * times of the - * {@link protos.google.cloud.retail.v2alpha.ProductService.CreateProduct|ProductService.CreateProduct} - * or - * {@link protos.google.cloud.retail.v2alpha.ProductService.UpdateProduct|ProductService.UpdateProduct} - * request. - * - * If no inventory fields are set in - * {@link protos.google.cloud.retail.v2alpha.CreateProductRequest.product|CreateProductRequest.product}, - * then any pre-existing inventory information for this product is used. - * - * If no inventory fields are set in - * {@link protos.google.cloud.retail.v2alpha.SetInventoryRequest.set_mask|SetInventoryRequest.set_mask}, - * then any existing inventory information is preserved. - * - * Pre-existing inventory information can only be updated with - * {@link protos.google.cloud.retail.v2alpha.ProductService.SetInventory|ProductService.SetInventory}, - * {@link protos.google.cloud.retail.v2alpha.ProductService.AddFulfillmentPlaces|ProductService.AddFulfillmentPlaces}, - * and - * {@link protos.google.cloud.retail.v2alpha.ProductService.RemoveFulfillmentPlaces|ProductService.RemoveFulfillmentPlaces}. - * - * The returned {@link protos.google.longrunning.Operation|Operation}s is obsolete after - * one day, and the {@link protos.google.longrunning.Operations.GetOperation|GetOperation} - * API returns `NOT_FOUND` afterwards. - * - * If conflicting updates are issued, the - * {@link protos.google.longrunning.Operation|Operation}s associated with the stale - * updates are not marked as {@link protos.google.longrunning.Operation.done|done} until - * they are obsolete. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.cloud.retail.v2alpha.Product} request.inventory - * Required. The inventory information to update. The allowable fields to - * update are: - * - * * {@link protos.google.cloud.retail.v2alpha.Product.price_info|Product.price_info} - * * {@link protos.google.cloud.retail.v2alpha.Product.availability|Product.availability} - * * {@link protos.google.cloud.retail.v2alpha.Product.available_quantity|Product.available_quantity} - * * {@link protos.google.cloud.retail.v2alpha.Product.fulfillment_info|Product.fulfillment_info} - * The updated inventory fields must be specified in - * {@link protos.google.cloud.retail.v2alpha.SetInventoryRequest.set_mask|SetInventoryRequest.set_mask}. - * - * If - * {@link protos.google.cloud.retail.v2alpha.Product.name|SetInventoryRequest.inventory.name} - * is empty or invalid, an INVALID_ARGUMENT error is returned. - * - * If the caller does not have permission to update the - * {@link protos.google.cloud.retail.v2alpha.Product|Product} named in - * {@link protos.google.cloud.retail.v2alpha.Product.name|Product.name}, regardless of - * whether or not it exists, a PERMISSION_DENIED error is returned. - * - * If the {@link protos.google.cloud.retail.v2alpha.Product|Product} to update does not - * have existing inventory information, the provided inventory information - * will be inserted. - * - * If the {@link protos.google.cloud.retail.v2alpha.Product|Product} to update has - * existing inventory information, the provided inventory information will be - * merged while respecting the last update time for each inventory field, - * using the provided or default value for - * {@link protos.google.cloud.retail.v2alpha.SetInventoryRequest.set_time|SetInventoryRequest.set_time}. - * - * The caller can replace place IDs for a subset of fulfillment types in the - * following ways: - * - * * Adds "fulfillment_info" in - * {@link protos.google.cloud.retail.v2alpha.SetInventoryRequest.set_mask|SetInventoryRequest.set_mask} - * * Specifies only the desired fulfillment types and corresponding place IDs - * to update in - * {@link protos.google.cloud.retail.v2alpha.Product.fulfillment_info|SetInventoryRequest.inventory.fulfillment_info} - * - * The caller can clear all place IDs from a subset of fulfillment types in - * the following ways: - * - * * Adds "fulfillment_info" in - * {@link protos.google.cloud.retail.v2alpha.SetInventoryRequest.set_mask|SetInventoryRequest.set_mask} - * * Specifies only the desired fulfillment types to clear in - * {@link protos.google.cloud.retail.v2alpha.Product.fulfillment_info|SetInventoryRequest.inventory.fulfillment_info} - * * Checks that only the desired fulfillment info types have empty - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.place_ids|SetInventoryRequest.inventory.fulfillment_info.place_ids} - * - * The last update time is recorded for the following inventory fields: - * * {@link protos.google.cloud.retail.v2alpha.Product.price_info|Product.price_info} - * * {@link protos.google.cloud.retail.v2alpha.Product.availability|Product.availability} - * * {@link protos.google.cloud.retail.v2alpha.Product.available_quantity|Product.available_quantity} - * * {@link protos.google.cloud.retail.v2alpha.Product.fulfillment_info|Product.fulfillment_info} - * - * If a full overwrite of inventory information while ignoring timestamps is - * needed, - * {@link protos.google.cloud.retail.v2alpha.ProductService.UpdateProduct|ProductService.UpdateProduct} - * should be invoked instead. - * @param {google.protobuf.FieldMask} request.setMask - * Indicates which inventory fields in the provided - * {@link protos.google.cloud.retail.v2alpha.Product|Product} to update. - * - * At least one field must be provided. - * - * If an unsupported or unknown field is provided, an INVALID_ARGUMENT error - * is returned and the entire update will be ignored. - * @param {google.protobuf.Timestamp} request.setTime - * The time when the request is issued, used to prevent - * out-of-order updates on inventory fields with the last update time - * recorded. If not provided, the internal system time will be used. - * @param {boolean} request.allowMissing - * If set to true, and the {@link protos.google.cloud.retail.v2alpha.Product|Product} with - * name {@link protos.google.cloud.retail.v2alpha.Product.name|Product.name} is not found, - * the inventory update will still be processed and retained for at most 1 day - * until the {@link protos.google.cloud.retail.v2alpha.Product|Product} is created. If set - * to false, a NOT_FOUND error is returned if the - * {@link protos.google.cloud.retail.v2alpha.Product|Product} is not found. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing - * a long running operation. Its `promise()` method returns a promise - * you can `await` for. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/product_service.set_inventory.js - * region_tag:retail_v2alpha_generated_ProductService_SetInventory_async - */ + /** + * Updates inventory information for a + * {@link protos.google.cloud.retail.v2alpha.Product|Product} while respecting the last + * update timestamps of each inventory field. + * + * This process is asynchronous and does not require the + * {@link protos.google.cloud.retail.v2alpha.Product|Product} to exist before updating + * fulfillment information. If the request is valid, the update is enqueued + * and processed downstream. As a consequence, when a response is returned, + * updates are not immediately manifested in the + * {@link protos.google.cloud.retail.v2alpha.Product|Product} queried by + * {@link protos.google.cloud.retail.v2alpha.ProductService.GetProduct|ProductService.GetProduct} + * or + * {@link protos.google.cloud.retail.v2alpha.ProductService.ListProducts|ProductService.ListProducts}. + * + * When inventory is updated with + * {@link protos.google.cloud.retail.v2alpha.ProductService.CreateProduct|ProductService.CreateProduct} + * and + * {@link protos.google.cloud.retail.v2alpha.ProductService.UpdateProduct|ProductService.UpdateProduct}, + * the specified inventory field value(s) overwrite any existing value(s) + * while ignoring the last update time for this field. Furthermore, the last + * update times for the specified inventory fields are overwritten by the + * times of the + * {@link protos.google.cloud.retail.v2alpha.ProductService.CreateProduct|ProductService.CreateProduct} + * or + * {@link protos.google.cloud.retail.v2alpha.ProductService.UpdateProduct|ProductService.UpdateProduct} + * request. + * + * If no inventory fields are set in + * {@link protos.google.cloud.retail.v2alpha.CreateProductRequest.product|CreateProductRequest.product}, + * then any pre-existing inventory information for this product is used. + * + * If no inventory fields are set in + * {@link protos.google.cloud.retail.v2alpha.SetInventoryRequest.set_mask|SetInventoryRequest.set_mask}, + * then any existing inventory information is preserved. + * + * Pre-existing inventory information can only be updated with + * {@link protos.google.cloud.retail.v2alpha.ProductService.SetInventory|ProductService.SetInventory}, + * {@link protos.google.cloud.retail.v2alpha.ProductService.AddFulfillmentPlaces|ProductService.AddFulfillmentPlaces}, + * and + * {@link protos.google.cloud.retail.v2alpha.ProductService.RemoveFulfillmentPlaces|ProductService.RemoveFulfillmentPlaces}. + * + * The returned {@link protos.google.longrunning.Operation|Operation}s is obsolete after + * one day, and the {@link protos.google.longrunning.Operations.GetOperation|GetOperation} + * API returns `NOT_FOUND` afterwards. + * + * If conflicting updates are issued, the + * {@link protos.google.longrunning.Operation|Operation}s associated with the stale + * updates are not marked as {@link protos.google.longrunning.Operation.done|done} until + * they are obsolete. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.cloud.retail.v2alpha.Product} request.inventory + * Required. The inventory information to update. The allowable fields to + * update are: + * + * * {@link protos.google.cloud.retail.v2alpha.Product.price_info|Product.price_info} + * * {@link protos.google.cloud.retail.v2alpha.Product.availability|Product.availability} + * * {@link protos.google.cloud.retail.v2alpha.Product.available_quantity|Product.available_quantity} + * * {@link protos.google.cloud.retail.v2alpha.Product.fulfillment_info|Product.fulfillment_info} + * The updated inventory fields must be specified in + * {@link protos.google.cloud.retail.v2alpha.SetInventoryRequest.set_mask|SetInventoryRequest.set_mask}. + * + * If + * {@link protos.google.cloud.retail.v2alpha.Product.name|SetInventoryRequest.inventory.name} + * is empty or invalid, an INVALID_ARGUMENT error is returned. + * + * If the caller does not have permission to update the + * {@link protos.google.cloud.retail.v2alpha.Product|Product} named in + * {@link protos.google.cloud.retail.v2alpha.Product.name|Product.name}, regardless of + * whether or not it exists, a PERMISSION_DENIED error is returned. + * + * If the {@link protos.google.cloud.retail.v2alpha.Product|Product} to update does not + * have existing inventory information, the provided inventory information + * will be inserted. + * + * If the {@link protos.google.cloud.retail.v2alpha.Product|Product} to update has + * existing inventory information, the provided inventory information will be + * merged while respecting the last update time for each inventory field, + * using the provided or default value for + * {@link protos.google.cloud.retail.v2alpha.SetInventoryRequest.set_time|SetInventoryRequest.set_time}. + * + * The caller can replace place IDs for a subset of fulfillment types in the + * following ways: + * + * * Adds "fulfillment_info" in + * {@link protos.google.cloud.retail.v2alpha.SetInventoryRequest.set_mask|SetInventoryRequest.set_mask} + * * Specifies only the desired fulfillment types and corresponding place IDs + * to update in + * {@link protos.google.cloud.retail.v2alpha.Product.fulfillment_info|SetInventoryRequest.inventory.fulfillment_info} + * + * The caller can clear all place IDs from a subset of fulfillment types in + * the following ways: + * + * * Adds "fulfillment_info" in + * {@link protos.google.cloud.retail.v2alpha.SetInventoryRequest.set_mask|SetInventoryRequest.set_mask} + * * Specifies only the desired fulfillment types to clear in + * {@link protos.google.cloud.retail.v2alpha.Product.fulfillment_info|SetInventoryRequest.inventory.fulfillment_info} + * * Checks that only the desired fulfillment info types have empty + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.place_ids|SetInventoryRequest.inventory.fulfillment_info.place_ids} + * + * The last update time is recorded for the following inventory fields: + * * {@link protos.google.cloud.retail.v2alpha.Product.price_info|Product.price_info} + * * {@link protos.google.cloud.retail.v2alpha.Product.availability|Product.availability} + * * {@link protos.google.cloud.retail.v2alpha.Product.available_quantity|Product.available_quantity} + * * {@link protos.google.cloud.retail.v2alpha.Product.fulfillment_info|Product.fulfillment_info} + * + * If a full overwrite of inventory information while ignoring timestamps is + * needed, + * {@link protos.google.cloud.retail.v2alpha.ProductService.UpdateProduct|ProductService.UpdateProduct} + * should be invoked instead. + * @param {google.protobuf.FieldMask} request.setMask + * Indicates which inventory fields in the provided + * {@link protos.google.cloud.retail.v2alpha.Product|Product} to update. + * + * At least one field must be provided. + * + * If an unsupported or unknown field is provided, an INVALID_ARGUMENT error + * is returned and the entire update will be ignored. + * @param {google.protobuf.Timestamp} request.setTime + * The time when the request is issued, used to prevent + * out-of-order updates on inventory fields with the last update time + * recorded. If not provided, the internal system time will be used. + * @param {boolean} request.allowMissing + * If set to true, and the {@link protos.google.cloud.retail.v2alpha.Product|Product} with + * name {@link protos.google.cloud.retail.v2alpha.Product.name|Product.name} is not found, + * the inventory update will still be processed and retained for at most 1 day + * until the {@link protos.google.cloud.retail.v2alpha.Product|Product} is created. If set + * to false, a NOT_FOUND error is returned if the + * {@link protos.google.cloud.retail.v2alpha.Product|Product} is not found. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/product_service.set_inventory.js + * region_tag:retail_v2alpha_generated_ProductService_SetInventory_async + */ setInventory( - request?: protos.google.cloud.retail.v2alpha.ISetInventoryRequest, - options?: CallOptions): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.ISetInventoryRequest, + options?: CallOptions, + ): Promise< + [ + LROperation< + protos.google.cloud.retail.v2alpha.ISetInventoryResponse, + protos.google.cloud.retail.v2alpha.ISetInventoryMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; setInventory( - request: protos.google.cloud.retail.v2alpha.ISetInventoryRequest, - options: CallOptions, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.ISetInventoryRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.cloud.retail.v2alpha.ISetInventoryResponse, + protos.google.cloud.retail.v2alpha.ISetInventoryMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; setInventory( - request: protos.google.cloud.retail.v2alpha.ISetInventoryRequest, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.ISetInventoryRequest, + callback: Callback< + LROperation< + protos.google.cloud.retail.v2alpha.ISetInventoryResponse, + protos.google.cloud.retail.v2alpha.ISetInventoryMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; setInventory( - request?: protos.google.cloud.retail.v2alpha.ISetInventoryRequest, - optionsOrCallback?: CallOptions|Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>, - callback?: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>|void { + request?: protos.google.cloud.retail.v2alpha.ISetInventoryRequest, + optionsOrCallback?: + | CallOptions + | Callback< + LROperation< + protos.google.cloud.retail.v2alpha.ISetInventoryResponse, + protos.google.cloud.retail.v2alpha.ISetInventoryMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + callback?: Callback< + LROperation< + protos.google.cloud.retail.v2alpha.ISetInventoryResponse, + protos.google.cloud.retail.v2alpha.ISetInventoryMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + LROperation< + protos.google.cloud.retail.v2alpha.ISetInventoryResponse, + protos.google.cloud.retail.v2alpha.ISetInventoryMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'inventory.name': request.inventory!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'inventory.name': request.inventory!.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + LROperation< + protos.google.cloud.retail.v2alpha.ISetInventoryResponse, + protos.google.cloud.retail.v2alpha.ISetInventoryMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, rawResponse, _) => { this._log.info('setInventory response %j', rawResponse); callback!(error, response, rawResponse, _); // We verified `callback` above. } : undefined; this._log.info('setInventory request %j', request); - return this.innerApiCalls.setInventory(request, options, wrappedCallback) - ?.then(([response, rawResponse, _]: [ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]) => { - this._log.info('setInventory response %j', rawResponse); - return [response, rawResponse, _]; - }); + return this.innerApiCalls + .setInventory(request, options, wrappedCallback) + ?.then( + ([response, rawResponse, _]: [ + LROperation< + protos.google.cloud.retail.v2alpha.ISetInventoryResponse, + protos.google.cloud.retail.v2alpha.ISetInventoryMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ]) => { + this._log.info('setInventory response %j', rawResponse); + return [response, rawResponse, _]; + }, + ); } -/** - * Check the status of the long running operation returned by `setInventory()`. - * @param {String} name - * The operation name that will be passed. - * @returns {Promise} - The promise which resolves to an object. - * The decoded operation object has result and metadata field to get information from. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/product_service.set_inventory.js - * region_tag:retail_v2alpha_generated_ProductService_SetInventory_async - */ - async checkSetInventoryProgress(name: string): Promise>{ + /** + * Check the status of the long running operation returned by `setInventory()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/product_service.set_inventory.js + * region_tag:retail_v2alpha_generated_ProductService_SetInventory_async + */ + async checkSetInventoryProgress( + name: string, + ): Promise< + LROperation< + protos.google.cloud.retail.v2alpha.SetInventoryResponse, + protos.google.cloud.retail.v2alpha.SetInventoryMetadata + > + > { this._log.info('setInventory long-running'); - const request = new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest({name}); + const request = + new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( + { name }, + ); const [operation] = await this.operationsClient.getOperation(request); - const decodeOperation = new this._gaxModule.Operation(operation, this.descriptors.longrunning.setInventory, this._gaxModule.createDefaultBackoffSettings()); - return decodeOperation as LROperation; + const decodeOperation = new this._gaxModule.Operation( + operation, + this.descriptors.longrunning.setInventory, + this._gaxModule.createDefaultBackoffSettings(), + ); + return decodeOperation as LROperation< + protos.google.cloud.retail.v2alpha.SetInventoryResponse, + protos.google.cloud.retail.v2alpha.SetInventoryMetadata + >; } -/** - * We recommend that you use the - * {@link protos.google.cloud.retail.v2alpha.ProductService.AddLocalInventories|ProductService.AddLocalInventories} - * method instead of the - * {@link protos.google.cloud.retail.v2alpha.ProductService.AddFulfillmentPlaces|ProductService.AddFulfillmentPlaces} - * method. - * {@link protos.google.cloud.retail.v2alpha.ProductService.AddLocalInventories|ProductService.AddLocalInventories} - * achieves the same results but provides more fine-grained control over - * ingesting local inventory data. - * - * Incrementally adds place IDs to - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.place_ids|Product.fulfillment_info.place_ids}. - * - * This process is asynchronous and does not require the - * {@link protos.google.cloud.retail.v2alpha.Product|Product} to exist before updating - * fulfillment information. If the request is valid, the update will be - * enqueued and processed downstream. As a consequence, when a response is - * returned, the added place IDs are not immediately manifested in the - * {@link protos.google.cloud.retail.v2alpha.Product|Product} queried by - * {@link protos.google.cloud.retail.v2alpha.ProductService.GetProduct|ProductService.GetProduct} - * or - * {@link protos.google.cloud.retail.v2alpha.ProductService.ListProducts|ProductService.ListProducts}. - * - * The returned {@link protos.google.longrunning.Operation|Operation}s will be obsolete - * after 1 day, and {@link protos.google.longrunning.Operations.GetOperation|GetOperation} - * API will return NOT_FOUND afterwards. - * - * If conflicting updates are issued, the - * {@link protos.google.longrunning.Operation|Operation}s associated with the stale - * updates will not be marked as {@link protos.google.longrunning.Operation.done|done} - * until being obsolete. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.product - * Required. Full resource name of - * {@link protos.google.cloud.retail.v2alpha.Product|Product}, such as - * `projects/* /locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id`. - * - * If the caller does not have permission to access the - * {@link protos.google.cloud.retail.v2alpha.Product|Product}, regardless of whether or - * not it exists, a PERMISSION_DENIED error is returned. - * @param {string} request.type - * Required. The fulfillment type, including commonly used types (such as - * pickup in store and same day delivery), and custom types. - * - * Supported values: - * - * * "pickup-in-store" - * * "ship-to-store" - * * "same-day-delivery" - * * "next-day-delivery" - * * "custom-type-1" - * * "custom-type-2" - * * "custom-type-3" - * * "custom-type-4" - * * "custom-type-5" - * - * If this field is set to an invalid value other than these, an - * INVALID_ARGUMENT error is returned. - * - * This field directly corresponds to - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.type|Product.fulfillment_info.type}. - * @param {string[]} request.placeIds - * Required. The IDs for this - * {@link protos.google.cloud.retail.v2alpha.AddFulfillmentPlacesRequest.type|type}, such - * as the store IDs for "pickup-in-store" or the region IDs for - * "same-day-delivery" to be added for this - * {@link protos.google.cloud.retail.v2alpha.AddFulfillmentPlacesRequest.type|type}. - * Duplicate IDs will be automatically ignored. - * - * At least 1 value is required, and a maximum of 2000 values are allowed. - * Each value must be a string with a length limit of 10 characters, matching - * the pattern `[a-zA-Z0-9_-]+`, such as "store1" or "REGION-2". Otherwise, an - * INVALID_ARGUMENT error is returned. - * - * If the total number of place IDs exceeds 2000 for this - * {@link protos.google.cloud.retail.v2alpha.AddFulfillmentPlacesRequest.type|type} after - * adding, then the update will be rejected. - * @param {google.protobuf.Timestamp} request.addTime - * The time when the fulfillment updates are issued, used to prevent - * out-of-order updates on fulfillment information. If not provided, the - * internal system time will be used. - * @param {boolean} request.allowMissing - * If set to true, and the {@link protos.google.cloud.retail.v2alpha.Product|Product} is - * not found, the fulfillment information will still be processed and retained - * for at most 1 day and processed once the - * {@link protos.google.cloud.retail.v2alpha.Product|Product} is created. If set to false, - * a NOT_FOUND error is returned if the - * {@link protos.google.cloud.retail.v2alpha.Product|Product} is not found. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing - * a long running operation. Its `promise()` method returns a promise - * you can `await` for. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/product_service.add_fulfillment_places.js - * region_tag:retail_v2alpha_generated_ProductService_AddFulfillmentPlaces_async - */ + /** + * We recommend that you use the + * {@link protos.google.cloud.retail.v2alpha.ProductService.AddLocalInventories|ProductService.AddLocalInventories} + * method instead of the + * {@link protos.google.cloud.retail.v2alpha.ProductService.AddFulfillmentPlaces|ProductService.AddFulfillmentPlaces} + * method. + * {@link protos.google.cloud.retail.v2alpha.ProductService.AddLocalInventories|ProductService.AddLocalInventories} + * achieves the same results but provides more fine-grained control over + * ingesting local inventory data. + * + * Incrementally adds place IDs to + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.place_ids|Product.fulfillment_info.place_ids}. + * + * This process is asynchronous and does not require the + * {@link protos.google.cloud.retail.v2alpha.Product|Product} to exist before updating + * fulfillment information. If the request is valid, the update will be + * enqueued and processed downstream. As a consequence, when a response is + * returned, the added place IDs are not immediately manifested in the + * {@link protos.google.cloud.retail.v2alpha.Product|Product} queried by + * {@link protos.google.cloud.retail.v2alpha.ProductService.GetProduct|ProductService.GetProduct} + * or + * {@link protos.google.cloud.retail.v2alpha.ProductService.ListProducts|ProductService.ListProducts}. + * + * The returned {@link protos.google.longrunning.Operation|Operation}s will be obsolete + * after 1 day, and {@link protos.google.longrunning.Operations.GetOperation|GetOperation} + * API will return NOT_FOUND afterwards. + * + * If conflicting updates are issued, the + * {@link protos.google.longrunning.Operation|Operation}s associated with the stale + * updates will not be marked as {@link protos.google.longrunning.Operation.done|done} + * until being obsolete. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.product + * Required. Full resource name of + * {@link protos.google.cloud.retail.v2alpha.Product|Product}, such as + * `projects/* /locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id`. + * + * If the caller does not have permission to access the + * {@link protos.google.cloud.retail.v2alpha.Product|Product}, regardless of whether or + * not it exists, a PERMISSION_DENIED error is returned. + * @param {string} request.type + * Required. The fulfillment type, including commonly used types (such as + * pickup in store and same day delivery), and custom types. + * + * Supported values: + * + * * "pickup-in-store" + * * "ship-to-store" + * * "same-day-delivery" + * * "next-day-delivery" + * * "custom-type-1" + * * "custom-type-2" + * * "custom-type-3" + * * "custom-type-4" + * * "custom-type-5" + * + * If this field is set to an invalid value other than these, an + * INVALID_ARGUMENT error is returned. + * + * This field directly corresponds to + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.type|Product.fulfillment_info.type}. + * @param {string[]} request.placeIds + * Required. The IDs for this + * {@link protos.google.cloud.retail.v2alpha.AddFulfillmentPlacesRequest.type|type}, such + * as the store IDs for "pickup-in-store" or the region IDs for + * "same-day-delivery" to be added for this + * {@link protos.google.cloud.retail.v2alpha.AddFulfillmentPlacesRequest.type|type}. + * Duplicate IDs will be automatically ignored. + * + * At least 1 value is required, and a maximum of 2000 values are allowed. + * Each value must be a string with a length limit of 10 characters, matching + * the pattern `[a-zA-Z0-9_-]+`, such as "store1" or "REGION-2". Otherwise, an + * INVALID_ARGUMENT error is returned. + * + * If the total number of place IDs exceeds 2000 for this + * {@link protos.google.cloud.retail.v2alpha.AddFulfillmentPlacesRequest.type|type} after + * adding, then the update will be rejected. + * @param {google.protobuf.Timestamp} request.addTime + * The time when the fulfillment updates are issued, used to prevent + * out-of-order updates on fulfillment information. If not provided, the + * internal system time will be used. + * @param {boolean} request.allowMissing + * If set to true, and the {@link protos.google.cloud.retail.v2alpha.Product|Product} is + * not found, the fulfillment information will still be processed and retained + * for at most 1 day and processed once the + * {@link protos.google.cloud.retail.v2alpha.Product|Product} is created. If set to false, + * a NOT_FOUND error is returned if the + * {@link protos.google.cloud.retail.v2alpha.Product|Product} is not found. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/product_service.add_fulfillment_places.js + * region_tag:retail_v2alpha_generated_ProductService_AddFulfillmentPlaces_async + */ addFulfillmentPlaces( - request?: protos.google.cloud.retail.v2alpha.IAddFulfillmentPlacesRequest, - options?: CallOptions): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.IAddFulfillmentPlacesRequest, + options?: CallOptions, + ): Promise< + [ + LROperation< + protos.google.cloud.retail.v2alpha.IAddFulfillmentPlacesResponse, + protos.google.cloud.retail.v2alpha.IAddFulfillmentPlacesMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; addFulfillmentPlaces( - request: protos.google.cloud.retail.v2alpha.IAddFulfillmentPlacesRequest, - options: CallOptions, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IAddFulfillmentPlacesRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IAddFulfillmentPlacesResponse, + protos.google.cloud.retail.v2alpha.IAddFulfillmentPlacesMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; addFulfillmentPlaces( - request: protos.google.cloud.retail.v2alpha.IAddFulfillmentPlacesRequest, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IAddFulfillmentPlacesRequest, + callback: Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IAddFulfillmentPlacesResponse, + protos.google.cloud.retail.v2alpha.IAddFulfillmentPlacesMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; addFulfillmentPlaces( - request?: protos.google.cloud.retail.v2alpha.IAddFulfillmentPlacesRequest, - optionsOrCallback?: CallOptions|Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>, - callback?: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>|void { + request?: protos.google.cloud.retail.v2alpha.IAddFulfillmentPlacesRequest, + optionsOrCallback?: + | CallOptions + | Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IAddFulfillmentPlacesResponse, + protos.google.cloud.retail.v2alpha.IAddFulfillmentPlacesMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + callback?: Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IAddFulfillmentPlacesResponse, + protos.google.cloud.retail.v2alpha.IAddFulfillmentPlacesMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + LROperation< + protos.google.cloud.retail.v2alpha.IAddFulfillmentPlacesResponse, + protos.google.cloud.retail.v2alpha.IAddFulfillmentPlacesMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'product': request.product ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + product: request.product ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IAddFulfillmentPlacesResponse, + protos.google.cloud.retail.v2alpha.IAddFulfillmentPlacesMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, rawResponse, _) => { this._log.info('addFulfillmentPlaces response %j', rawResponse); callback!(error, response, rawResponse, _); // We verified `callback` above. } : undefined; this._log.info('addFulfillmentPlaces request %j', request); - return this.innerApiCalls.addFulfillmentPlaces(request, options, wrappedCallback) - ?.then(([response, rawResponse, _]: [ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]) => { - this._log.info('addFulfillmentPlaces response %j', rawResponse); - return [response, rawResponse, _]; - }); + return this.innerApiCalls + .addFulfillmentPlaces(request, options, wrappedCallback) + ?.then( + ([response, rawResponse, _]: [ + LROperation< + protos.google.cloud.retail.v2alpha.IAddFulfillmentPlacesResponse, + protos.google.cloud.retail.v2alpha.IAddFulfillmentPlacesMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ]) => { + this._log.info('addFulfillmentPlaces response %j', rawResponse); + return [response, rawResponse, _]; + }, + ); } -/** - * Check the status of the long running operation returned by `addFulfillmentPlaces()`. - * @param {String} name - * The operation name that will be passed. - * @returns {Promise} - The promise which resolves to an object. - * The decoded operation object has result and metadata field to get information from. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/product_service.add_fulfillment_places.js - * region_tag:retail_v2alpha_generated_ProductService_AddFulfillmentPlaces_async - */ - async checkAddFulfillmentPlacesProgress(name: string): Promise>{ + /** + * Check the status of the long running operation returned by `addFulfillmentPlaces()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/product_service.add_fulfillment_places.js + * region_tag:retail_v2alpha_generated_ProductService_AddFulfillmentPlaces_async + */ + async checkAddFulfillmentPlacesProgress( + name: string, + ): Promise< + LROperation< + protos.google.cloud.retail.v2alpha.AddFulfillmentPlacesResponse, + protos.google.cloud.retail.v2alpha.AddFulfillmentPlacesMetadata + > + > { this._log.info('addFulfillmentPlaces long-running'); - const request = new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest({name}); + const request = + new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( + { name }, + ); const [operation] = await this.operationsClient.getOperation(request); - const decodeOperation = new this._gaxModule.Operation(operation, this.descriptors.longrunning.addFulfillmentPlaces, this._gaxModule.createDefaultBackoffSettings()); - return decodeOperation as LROperation; + const decodeOperation = new this._gaxModule.Operation( + operation, + this.descriptors.longrunning.addFulfillmentPlaces, + this._gaxModule.createDefaultBackoffSettings(), + ); + return decodeOperation as LROperation< + protos.google.cloud.retail.v2alpha.AddFulfillmentPlacesResponse, + protos.google.cloud.retail.v2alpha.AddFulfillmentPlacesMetadata + >; } -/** - * We recommend that you use the - * {@link protos.google.cloud.retail.v2alpha.ProductService.RemoveLocalInventories|ProductService.RemoveLocalInventories} - * method instead of the - * {@link protos.google.cloud.retail.v2alpha.ProductService.RemoveFulfillmentPlaces|ProductService.RemoveFulfillmentPlaces} - * method. - * {@link protos.google.cloud.retail.v2alpha.ProductService.RemoveLocalInventories|ProductService.RemoveLocalInventories} - * achieves the same results but provides more fine-grained control over - * ingesting local inventory data. - * - * Incrementally removes place IDs from a - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.place_ids|Product.fulfillment_info.place_ids}. - * - * This process is asynchronous and does not require the - * {@link protos.google.cloud.retail.v2alpha.Product|Product} to exist before updating - * fulfillment information. If the request is valid, the update will be - * enqueued and processed downstream. As a consequence, when a response is - * returned, the removed place IDs are not immediately manifested in the - * {@link protos.google.cloud.retail.v2alpha.Product|Product} queried by - * {@link protos.google.cloud.retail.v2alpha.ProductService.GetProduct|ProductService.GetProduct} - * or - * {@link protos.google.cloud.retail.v2alpha.ProductService.ListProducts|ProductService.ListProducts}. - * - * The returned {@link protos.google.longrunning.Operation|Operation}s will be obsolete - * after 1 day, and {@link protos.google.longrunning.Operations.GetOperation|GetOperation} - * API will return NOT_FOUND afterwards. - * - * If conflicting updates are issued, the - * {@link protos.google.longrunning.Operation|Operation}s associated with the stale - * updates will not be marked as {@link protos.google.longrunning.Operation.done|done} - * until being obsolete. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.product - * Required. Full resource name of - * {@link protos.google.cloud.retail.v2alpha.Product|Product}, such as - * `projects/* /locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id`. - * - * If the caller does not have permission to access the - * {@link protos.google.cloud.retail.v2alpha.Product|Product}, regardless of whether or - * not it exists, a PERMISSION_DENIED error is returned. - * @param {string} request.type - * Required. The fulfillment type, including commonly used types (such as - * pickup in store and same day delivery), and custom types. - * - * Supported values: - * - * * "pickup-in-store" - * * "ship-to-store" - * * "same-day-delivery" - * * "next-day-delivery" - * * "custom-type-1" - * * "custom-type-2" - * * "custom-type-3" - * * "custom-type-4" - * * "custom-type-5" - * - * If this field is set to an invalid value other than these, an - * INVALID_ARGUMENT error is returned. - * - * This field directly corresponds to - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.type|Product.fulfillment_info.type}. - * @param {string[]} request.placeIds - * Required. The IDs for this - * {@link protos.google.cloud.retail.v2alpha.RemoveFulfillmentPlacesRequest.type|type}, - * such as the store IDs for "pickup-in-store" or the region IDs for - * "same-day-delivery", to be removed for this - * {@link protos.google.cloud.retail.v2alpha.RemoveFulfillmentPlacesRequest.type|type}. - * - * At least 1 value is required, and a maximum of 2000 values are allowed. - * Each value must be a string with a length limit of 10 characters, matching - * the pattern `[a-zA-Z0-9_-]+`, such as "store1" or "REGION-2". Otherwise, an - * INVALID_ARGUMENT error is returned. - * @param {google.protobuf.Timestamp} request.removeTime - * The time when the fulfillment updates are issued, used to prevent - * out-of-order updates on fulfillment information. If not provided, the - * internal system time will be used. - * @param {boolean} request.allowMissing - * If set to true, and the {@link protos.google.cloud.retail.v2alpha.Product|Product} is - * not found, the fulfillment information will still be processed and retained - * for at most 1 day and processed once the - * {@link protos.google.cloud.retail.v2alpha.Product|Product} is created. If set to false, - * a NOT_FOUND error is returned if the - * {@link protos.google.cloud.retail.v2alpha.Product|Product} is not found. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing - * a long running operation. Its `promise()` method returns a promise - * you can `await` for. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/product_service.remove_fulfillment_places.js - * region_tag:retail_v2alpha_generated_ProductService_RemoveFulfillmentPlaces_async - */ + /** + * We recommend that you use the + * {@link protos.google.cloud.retail.v2alpha.ProductService.RemoveLocalInventories|ProductService.RemoveLocalInventories} + * method instead of the + * {@link protos.google.cloud.retail.v2alpha.ProductService.RemoveFulfillmentPlaces|ProductService.RemoveFulfillmentPlaces} + * method. + * {@link protos.google.cloud.retail.v2alpha.ProductService.RemoveLocalInventories|ProductService.RemoveLocalInventories} + * achieves the same results but provides more fine-grained control over + * ingesting local inventory data. + * + * Incrementally removes place IDs from a + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.place_ids|Product.fulfillment_info.place_ids}. + * + * This process is asynchronous and does not require the + * {@link protos.google.cloud.retail.v2alpha.Product|Product} to exist before updating + * fulfillment information. If the request is valid, the update will be + * enqueued and processed downstream. As a consequence, when a response is + * returned, the removed place IDs are not immediately manifested in the + * {@link protos.google.cloud.retail.v2alpha.Product|Product} queried by + * {@link protos.google.cloud.retail.v2alpha.ProductService.GetProduct|ProductService.GetProduct} + * or + * {@link protos.google.cloud.retail.v2alpha.ProductService.ListProducts|ProductService.ListProducts}. + * + * The returned {@link protos.google.longrunning.Operation|Operation}s will be obsolete + * after 1 day, and {@link protos.google.longrunning.Operations.GetOperation|GetOperation} + * API will return NOT_FOUND afterwards. + * + * If conflicting updates are issued, the + * {@link protos.google.longrunning.Operation|Operation}s associated with the stale + * updates will not be marked as {@link protos.google.longrunning.Operation.done|done} + * until being obsolete. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.product + * Required. Full resource name of + * {@link protos.google.cloud.retail.v2alpha.Product|Product}, such as + * `projects/* /locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id`. + * + * If the caller does not have permission to access the + * {@link protos.google.cloud.retail.v2alpha.Product|Product}, regardless of whether or + * not it exists, a PERMISSION_DENIED error is returned. + * @param {string} request.type + * Required. The fulfillment type, including commonly used types (such as + * pickup in store and same day delivery), and custom types. + * + * Supported values: + * + * * "pickup-in-store" + * * "ship-to-store" + * * "same-day-delivery" + * * "next-day-delivery" + * * "custom-type-1" + * * "custom-type-2" + * * "custom-type-3" + * * "custom-type-4" + * * "custom-type-5" + * + * If this field is set to an invalid value other than these, an + * INVALID_ARGUMENT error is returned. + * + * This field directly corresponds to + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.type|Product.fulfillment_info.type}. + * @param {string[]} request.placeIds + * Required. The IDs for this + * {@link protos.google.cloud.retail.v2alpha.RemoveFulfillmentPlacesRequest.type|type}, + * such as the store IDs for "pickup-in-store" or the region IDs for + * "same-day-delivery", to be removed for this + * {@link protos.google.cloud.retail.v2alpha.RemoveFulfillmentPlacesRequest.type|type}. + * + * At least 1 value is required, and a maximum of 2000 values are allowed. + * Each value must be a string with a length limit of 10 characters, matching + * the pattern `[a-zA-Z0-9_-]+`, such as "store1" or "REGION-2". Otherwise, an + * INVALID_ARGUMENT error is returned. + * @param {google.protobuf.Timestamp} request.removeTime + * The time when the fulfillment updates are issued, used to prevent + * out-of-order updates on fulfillment information. If not provided, the + * internal system time will be used. + * @param {boolean} request.allowMissing + * If set to true, and the {@link protos.google.cloud.retail.v2alpha.Product|Product} is + * not found, the fulfillment information will still be processed and retained + * for at most 1 day and processed once the + * {@link protos.google.cloud.retail.v2alpha.Product|Product} is created. If set to false, + * a NOT_FOUND error is returned if the + * {@link protos.google.cloud.retail.v2alpha.Product|Product} is not found. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/product_service.remove_fulfillment_places.js + * region_tag:retail_v2alpha_generated_ProductService_RemoveFulfillmentPlaces_async + */ removeFulfillmentPlaces( - request?: protos.google.cloud.retail.v2alpha.IRemoveFulfillmentPlacesRequest, - options?: CallOptions): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.IRemoveFulfillmentPlacesRequest, + options?: CallOptions, + ): Promise< + [ + LROperation< + protos.google.cloud.retail.v2alpha.IRemoveFulfillmentPlacesResponse, + protos.google.cloud.retail.v2alpha.IRemoveFulfillmentPlacesMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; removeFulfillmentPlaces( - request: protos.google.cloud.retail.v2alpha.IRemoveFulfillmentPlacesRequest, - options: CallOptions, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IRemoveFulfillmentPlacesRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IRemoveFulfillmentPlacesResponse, + protos.google.cloud.retail.v2alpha.IRemoveFulfillmentPlacesMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; removeFulfillmentPlaces( - request: protos.google.cloud.retail.v2alpha.IRemoveFulfillmentPlacesRequest, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IRemoveFulfillmentPlacesRequest, + callback: Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IRemoveFulfillmentPlacesResponse, + protos.google.cloud.retail.v2alpha.IRemoveFulfillmentPlacesMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; removeFulfillmentPlaces( - request?: protos.google.cloud.retail.v2alpha.IRemoveFulfillmentPlacesRequest, - optionsOrCallback?: CallOptions|Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>, - callback?: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>|void { + request?: protos.google.cloud.retail.v2alpha.IRemoveFulfillmentPlacesRequest, + optionsOrCallback?: + | CallOptions + | Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IRemoveFulfillmentPlacesResponse, + protos.google.cloud.retail.v2alpha.IRemoveFulfillmentPlacesMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + callback?: Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IRemoveFulfillmentPlacesResponse, + protos.google.cloud.retail.v2alpha.IRemoveFulfillmentPlacesMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + LROperation< + protos.google.cloud.retail.v2alpha.IRemoveFulfillmentPlacesResponse, + protos.google.cloud.retail.v2alpha.IRemoveFulfillmentPlacesMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'product': request.product ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + product: request.product ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IRemoveFulfillmentPlacesResponse, + protos.google.cloud.retail.v2alpha.IRemoveFulfillmentPlacesMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, rawResponse, _) => { this._log.info('removeFulfillmentPlaces response %j', rawResponse); callback!(error, response, rawResponse, _); // We verified `callback` above. } : undefined; this._log.info('removeFulfillmentPlaces request %j', request); - return this.innerApiCalls.removeFulfillmentPlaces(request, options, wrappedCallback) - ?.then(([response, rawResponse, _]: [ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]) => { - this._log.info('removeFulfillmentPlaces response %j', rawResponse); - return [response, rawResponse, _]; - }); + return this.innerApiCalls + .removeFulfillmentPlaces(request, options, wrappedCallback) + ?.then( + ([response, rawResponse, _]: [ + LROperation< + protos.google.cloud.retail.v2alpha.IRemoveFulfillmentPlacesResponse, + protos.google.cloud.retail.v2alpha.IRemoveFulfillmentPlacesMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ]) => { + this._log.info('removeFulfillmentPlaces response %j', rawResponse); + return [response, rawResponse, _]; + }, + ); } -/** - * Check the status of the long running operation returned by `removeFulfillmentPlaces()`. - * @param {String} name - * The operation name that will be passed. - * @returns {Promise} - The promise which resolves to an object. - * The decoded operation object has result and metadata field to get information from. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/product_service.remove_fulfillment_places.js - * region_tag:retail_v2alpha_generated_ProductService_RemoveFulfillmentPlaces_async - */ - async checkRemoveFulfillmentPlacesProgress(name: string): Promise>{ + /** + * Check the status of the long running operation returned by `removeFulfillmentPlaces()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/product_service.remove_fulfillment_places.js + * region_tag:retail_v2alpha_generated_ProductService_RemoveFulfillmentPlaces_async + */ + async checkRemoveFulfillmentPlacesProgress( + name: string, + ): Promise< + LROperation< + protos.google.cloud.retail.v2alpha.RemoveFulfillmentPlacesResponse, + protos.google.cloud.retail.v2alpha.RemoveFulfillmentPlacesMetadata + > + > { this._log.info('removeFulfillmentPlaces long-running'); - const request = new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest({name}); + const request = + new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( + { name }, + ); const [operation] = await this.operationsClient.getOperation(request); - const decodeOperation = new this._gaxModule.Operation(operation, this.descriptors.longrunning.removeFulfillmentPlaces, this._gaxModule.createDefaultBackoffSettings()); - return decodeOperation as LROperation; + const decodeOperation = new this._gaxModule.Operation( + operation, + this.descriptors.longrunning.removeFulfillmentPlaces, + this._gaxModule.createDefaultBackoffSettings(), + ); + return decodeOperation as LROperation< + protos.google.cloud.retail.v2alpha.RemoveFulfillmentPlacesResponse, + protos.google.cloud.retail.v2alpha.RemoveFulfillmentPlacesMetadata + >; } -/** - * Updates local inventory information for a - * {@link protos.google.cloud.retail.v2alpha.Product|Product} at a list of places, while - * respecting the last update timestamps of each inventory field. - * - * This process is asynchronous and does not require the - * {@link protos.google.cloud.retail.v2alpha.Product|Product} to exist before updating - * inventory information. If the request is valid, the update will be enqueued - * and processed downstream. As a consequence, when a response is returned, - * updates are not immediately manifested in the - * {@link protos.google.cloud.retail.v2alpha.Product|Product} queried by - * {@link protos.google.cloud.retail.v2alpha.ProductService.GetProduct|ProductService.GetProduct} - * or - * {@link protos.google.cloud.retail.v2alpha.ProductService.ListProducts|ProductService.ListProducts}. - * - * Local inventory information can only be modified using this method. - * {@link protos.google.cloud.retail.v2alpha.ProductService.CreateProduct|ProductService.CreateProduct} - * and - * {@link protos.google.cloud.retail.v2alpha.ProductService.UpdateProduct|ProductService.UpdateProduct} - * has no effect on local inventories. - * - * The returned {@link protos.google.longrunning.Operation|Operation}s will be obsolete - * after 1 day, and {@link protos.google.longrunning.Operations.GetOperation|GetOperation} - * API will return NOT_FOUND afterwards. - * - * If conflicting updates are issued, the - * {@link protos.google.longrunning.Operation|Operation}s associated with the stale - * updates will not be marked as {@link protos.google.longrunning.Operation.done|done} - * until being obsolete. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.product - * Required. Full resource name of - * {@link protos.google.cloud.retail.v2alpha.Product|Product}, such as - * `projects/* /locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id`. - * - * If the caller does not have permission to access the - * {@link protos.google.cloud.retail.v2alpha.Product|Product}, regardless of whether or - * not it exists, a PERMISSION_DENIED error is returned. - * @param {number[]} request.localInventories - * Required. A list of inventory information at difference places. Each place - * is identified by its place ID. At most 3000 inventories are allowed per - * request. - * @param {google.protobuf.FieldMask} request.addMask - * Indicates which inventory fields in the provided list of - * {@link protos.google.cloud.retail.v2alpha.LocalInventory|LocalInventory} to update. The - * field is updated to the provided value. - * - * If a field is set while the place does not have a previous local inventory, - * the local inventory at that store is created. - * - * If a field is set while the value of that field is not provided, the - * original field value, if it exists, is deleted. - * - * If the mask is not set or set with empty paths, all inventory fields will - * be updated. - * - * If an unsupported or unknown field is provided, an INVALID_ARGUMENT error - * is returned and the entire update will be ignored. - * @param {google.protobuf.Timestamp} request.addTime - * The time when the inventory updates are issued. Used to prevent - * out-of-order updates on local inventory fields. If not provided, the - * internal system time will be used. - * @param {boolean} request.allowMissing - * If set to true, and the {@link protos.google.cloud.retail.v2alpha.Product|Product} is - * not found, the local inventory will still be processed and retained for at - * most 1 day and processed once the - * {@link protos.google.cloud.retail.v2alpha.Product|Product} is created. If set to false, - * a NOT_FOUND error is returned if the - * {@link protos.google.cloud.retail.v2alpha.Product|Product} is not found. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing - * a long running operation. Its `promise()` method returns a promise - * you can `await` for. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/product_service.add_local_inventories.js - * region_tag:retail_v2alpha_generated_ProductService_AddLocalInventories_async - */ + /** + * Updates local inventory information for a + * {@link protos.google.cloud.retail.v2alpha.Product|Product} at a list of places, while + * respecting the last update timestamps of each inventory field. + * + * This process is asynchronous and does not require the + * {@link protos.google.cloud.retail.v2alpha.Product|Product} to exist before updating + * inventory information. If the request is valid, the update will be enqueued + * and processed downstream. As a consequence, when a response is returned, + * updates are not immediately manifested in the + * {@link protos.google.cloud.retail.v2alpha.Product|Product} queried by + * {@link protos.google.cloud.retail.v2alpha.ProductService.GetProduct|ProductService.GetProduct} + * or + * {@link protos.google.cloud.retail.v2alpha.ProductService.ListProducts|ProductService.ListProducts}. + * + * Local inventory information can only be modified using this method. + * {@link protos.google.cloud.retail.v2alpha.ProductService.CreateProduct|ProductService.CreateProduct} + * and + * {@link protos.google.cloud.retail.v2alpha.ProductService.UpdateProduct|ProductService.UpdateProduct} + * has no effect on local inventories. + * + * The returned {@link protos.google.longrunning.Operation|Operation}s will be obsolete + * after 1 day, and {@link protos.google.longrunning.Operations.GetOperation|GetOperation} + * API will return NOT_FOUND afterwards. + * + * If conflicting updates are issued, the + * {@link protos.google.longrunning.Operation|Operation}s associated with the stale + * updates will not be marked as {@link protos.google.longrunning.Operation.done|done} + * until being obsolete. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.product + * Required. Full resource name of + * {@link protos.google.cloud.retail.v2alpha.Product|Product}, such as + * `projects/* /locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id`. + * + * If the caller does not have permission to access the + * {@link protos.google.cloud.retail.v2alpha.Product|Product}, regardless of whether or + * not it exists, a PERMISSION_DENIED error is returned. + * @param {number[]} request.localInventories + * Required. A list of inventory information at difference places. Each place + * is identified by its place ID. At most 3000 inventories are allowed per + * request. + * @param {google.protobuf.FieldMask} request.addMask + * Indicates which inventory fields in the provided list of + * {@link protos.google.cloud.retail.v2alpha.LocalInventory|LocalInventory} to update. The + * field is updated to the provided value. + * + * If a field is set while the place does not have a previous local inventory, + * the local inventory at that store is created. + * + * If a field is set while the value of that field is not provided, the + * original field value, if it exists, is deleted. + * + * If the mask is not set or set with empty paths, all inventory fields will + * be updated. + * + * If an unsupported or unknown field is provided, an INVALID_ARGUMENT error + * is returned and the entire update will be ignored. + * @param {google.protobuf.Timestamp} request.addTime + * The time when the inventory updates are issued. Used to prevent + * out-of-order updates on local inventory fields. If not provided, the + * internal system time will be used. + * @param {boolean} request.allowMissing + * If set to true, and the {@link protos.google.cloud.retail.v2alpha.Product|Product} is + * not found, the local inventory will still be processed and retained for at + * most 1 day and processed once the + * {@link protos.google.cloud.retail.v2alpha.Product|Product} is created. If set to false, + * a NOT_FOUND error is returned if the + * {@link protos.google.cloud.retail.v2alpha.Product|Product} is not found. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/product_service.add_local_inventories.js + * region_tag:retail_v2alpha_generated_ProductService_AddLocalInventories_async + */ addLocalInventories( - request?: protos.google.cloud.retail.v2alpha.IAddLocalInventoriesRequest, - options?: CallOptions): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.IAddLocalInventoriesRequest, + options?: CallOptions, + ): Promise< + [ + LROperation< + protos.google.cloud.retail.v2alpha.IAddLocalInventoriesResponse, + protos.google.cloud.retail.v2alpha.IAddLocalInventoriesMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; addLocalInventories( - request: protos.google.cloud.retail.v2alpha.IAddLocalInventoriesRequest, - options: CallOptions, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IAddLocalInventoriesRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IAddLocalInventoriesResponse, + protos.google.cloud.retail.v2alpha.IAddLocalInventoriesMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; addLocalInventories( - request: protos.google.cloud.retail.v2alpha.IAddLocalInventoriesRequest, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IAddLocalInventoriesRequest, + callback: Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IAddLocalInventoriesResponse, + protos.google.cloud.retail.v2alpha.IAddLocalInventoriesMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; addLocalInventories( - request?: protos.google.cloud.retail.v2alpha.IAddLocalInventoriesRequest, - optionsOrCallback?: CallOptions|Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>, - callback?: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>|void { + request?: protos.google.cloud.retail.v2alpha.IAddLocalInventoriesRequest, + optionsOrCallback?: + | CallOptions + | Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IAddLocalInventoriesResponse, + protos.google.cloud.retail.v2alpha.IAddLocalInventoriesMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + callback?: Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IAddLocalInventoriesResponse, + protos.google.cloud.retail.v2alpha.IAddLocalInventoriesMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + LROperation< + protos.google.cloud.retail.v2alpha.IAddLocalInventoriesResponse, + protos.google.cloud.retail.v2alpha.IAddLocalInventoriesMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'product': request.product ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + product: request.product ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IAddLocalInventoriesResponse, + protos.google.cloud.retail.v2alpha.IAddLocalInventoriesMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, rawResponse, _) => { this._log.info('addLocalInventories response %j', rawResponse); callback!(error, response, rawResponse, _); // We verified `callback` above. } : undefined; this._log.info('addLocalInventories request %j', request); - return this.innerApiCalls.addLocalInventories(request, options, wrappedCallback) - ?.then(([response, rawResponse, _]: [ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]) => { - this._log.info('addLocalInventories response %j', rawResponse); - return [response, rawResponse, _]; - }); + return this.innerApiCalls + .addLocalInventories(request, options, wrappedCallback) + ?.then( + ([response, rawResponse, _]: [ + LROperation< + protos.google.cloud.retail.v2alpha.IAddLocalInventoriesResponse, + protos.google.cloud.retail.v2alpha.IAddLocalInventoriesMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ]) => { + this._log.info('addLocalInventories response %j', rawResponse); + return [response, rawResponse, _]; + }, + ); } -/** - * Check the status of the long running operation returned by `addLocalInventories()`. - * @param {String} name - * The operation name that will be passed. - * @returns {Promise} - The promise which resolves to an object. - * The decoded operation object has result and metadata field to get information from. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/product_service.add_local_inventories.js - * region_tag:retail_v2alpha_generated_ProductService_AddLocalInventories_async - */ - async checkAddLocalInventoriesProgress(name: string): Promise>{ + /** + * Check the status of the long running operation returned by `addLocalInventories()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/product_service.add_local_inventories.js + * region_tag:retail_v2alpha_generated_ProductService_AddLocalInventories_async + */ + async checkAddLocalInventoriesProgress( + name: string, + ): Promise< + LROperation< + protos.google.cloud.retail.v2alpha.AddLocalInventoriesResponse, + protos.google.cloud.retail.v2alpha.AddLocalInventoriesMetadata + > + > { this._log.info('addLocalInventories long-running'); - const request = new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest({name}); + const request = + new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( + { name }, + ); const [operation] = await this.operationsClient.getOperation(request); - const decodeOperation = new this._gaxModule.Operation(operation, this.descriptors.longrunning.addLocalInventories, this._gaxModule.createDefaultBackoffSettings()); - return decodeOperation as LROperation; + const decodeOperation = new this._gaxModule.Operation( + operation, + this.descriptors.longrunning.addLocalInventories, + this._gaxModule.createDefaultBackoffSettings(), + ); + return decodeOperation as LROperation< + protos.google.cloud.retail.v2alpha.AddLocalInventoriesResponse, + protos.google.cloud.retail.v2alpha.AddLocalInventoriesMetadata + >; } -/** - * Remove local inventory information for a - * {@link protos.google.cloud.retail.v2alpha.Product|Product} at a list of places at a - * removal timestamp. - * - * This process is asynchronous. If the request is valid, the removal will be - * enqueued and processed downstream. As a consequence, when a response is - * returned, removals are not immediately manifested in the - * {@link protos.google.cloud.retail.v2alpha.Product|Product} queried by - * {@link protos.google.cloud.retail.v2alpha.ProductService.GetProduct|ProductService.GetProduct} - * or - * {@link protos.google.cloud.retail.v2alpha.ProductService.ListProducts|ProductService.ListProducts}. - * - * Local inventory information can only be removed using this method. - * {@link protos.google.cloud.retail.v2alpha.ProductService.CreateProduct|ProductService.CreateProduct} - * and - * {@link protos.google.cloud.retail.v2alpha.ProductService.UpdateProduct|ProductService.UpdateProduct} - * has no effect on local inventories. - * - * The returned {@link protos.google.longrunning.Operation|Operation}s will be obsolete - * after 1 day, and {@link protos.google.longrunning.Operations.GetOperation|GetOperation} - * API will return NOT_FOUND afterwards. - * - * If conflicting updates are issued, the - * {@link protos.google.longrunning.Operation|Operation}s associated with the stale - * updates will not be marked as {@link protos.google.longrunning.Operation.done|done} - * until being obsolete. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.product - * Required. Full resource name of - * {@link protos.google.cloud.retail.v2alpha.Product|Product}, such as - * `projects/* /locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id`. - * - * If the caller does not have permission to access the - * {@link protos.google.cloud.retail.v2alpha.Product|Product}, regardless of whether or - * not it exists, a PERMISSION_DENIED error is returned. - * @param {string[]} request.placeIds - * Required. A list of place IDs to have their inventory deleted. - * At most 3000 place IDs are allowed per request. - * @param {google.protobuf.Timestamp} request.removeTime - * The time when the inventory deletions are issued. Used to prevent - * out-of-order updates and deletions on local inventory fields. If not - * provided, the internal system time will be used. - * @param {boolean} request.allowMissing - * If set to true, and the {@link protos.google.cloud.retail.v2alpha.Product|Product} is - * not found, the local inventory removal request will still be processed and - * retained for at most 1 day and processed once the - * {@link protos.google.cloud.retail.v2alpha.Product|Product} is created. If set to false, - * a NOT_FOUND error is returned if the - * {@link protos.google.cloud.retail.v2alpha.Product|Product} is not found. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing - * a long running operation. Its `promise()` method returns a promise - * you can `await` for. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/product_service.remove_local_inventories.js - * region_tag:retail_v2alpha_generated_ProductService_RemoveLocalInventories_async - */ + /** + * Remove local inventory information for a + * {@link protos.google.cloud.retail.v2alpha.Product|Product} at a list of places at a + * removal timestamp. + * + * This process is asynchronous. If the request is valid, the removal will be + * enqueued and processed downstream. As a consequence, when a response is + * returned, removals are not immediately manifested in the + * {@link protos.google.cloud.retail.v2alpha.Product|Product} queried by + * {@link protos.google.cloud.retail.v2alpha.ProductService.GetProduct|ProductService.GetProduct} + * or + * {@link protos.google.cloud.retail.v2alpha.ProductService.ListProducts|ProductService.ListProducts}. + * + * Local inventory information can only be removed using this method. + * {@link protos.google.cloud.retail.v2alpha.ProductService.CreateProduct|ProductService.CreateProduct} + * and + * {@link protos.google.cloud.retail.v2alpha.ProductService.UpdateProduct|ProductService.UpdateProduct} + * has no effect on local inventories. + * + * The returned {@link protos.google.longrunning.Operation|Operation}s will be obsolete + * after 1 day, and {@link protos.google.longrunning.Operations.GetOperation|GetOperation} + * API will return NOT_FOUND afterwards. + * + * If conflicting updates are issued, the + * {@link protos.google.longrunning.Operation|Operation}s associated with the stale + * updates will not be marked as {@link protos.google.longrunning.Operation.done|done} + * until being obsolete. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.product + * Required. Full resource name of + * {@link protos.google.cloud.retail.v2alpha.Product|Product}, such as + * `projects/* /locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id`. + * + * If the caller does not have permission to access the + * {@link protos.google.cloud.retail.v2alpha.Product|Product}, regardless of whether or + * not it exists, a PERMISSION_DENIED error is returned. + * @param {string[]} request.placeIds + * Required. A list of place IDs to have their inventory deleted. + * At most 3000 place IDs are allowed per request. + * @param {google.protobuf.Timestamp} request.removeTime + * The time when the inventory deletions are issued. Used to prevent + * out-of-order updates and deletions on local inventory fields. If not + * provided, the internal system time will be used. + * @param {boolean} request.allowMissing + * If set to true, and the {@link protos.google.cloud.retail.v2alpha.Product|Product} is + * not found, the local inventory removal request will still be processed and + * retained for at most 1 day and processed once the + * {@link protos.google.cloud.retail.v2alpha.Product|Product} is created. If set to false, + * a NOT_FOUND error is returned if the + * {@link protos.google.cloud.retail.v2alpha.Product|Product} is not found. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/product_service.remove_local_inventories.js + * region_tag:retail_v2alpha_generated_ProductService_RemoveLocalInventories_async + */ removeLocalInventories( - request?: protos.google.cloud.retail.v2alpha.IRemoveLocalInventoriesRequest, - options?: CallOptions): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.IRemoveLocalInventoriesRequest, + options?: CallOptions, + ): Promise< + [ + LROperation< + protos.google.cloud.retail.v2alpha.IRemoveLocalInventoriesResponse, + protos.google.cloud.retail.v2alpha.IRemoveLocalInventoriesMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; removeLocalInventories( - request: protos.google.cloud.retail.v2alpha.IRemoveLocalInventoriesRequest, - options: CallOptions, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IRemoveLocalInventoriesRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IRemoveLocalInventoriesResponse, + protos.google.cloud.retail.v2alpha.IRemoveLocalInventoriesMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; removeLocalInventories( - request: protos.google.cloud.retail.v2alpha.IRemoveLocalInventoriesRequest, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IRemoveLocalInventoriesRequest, + callback: Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IRemoveLocalInventoriesResponse, + protos.google.cloud.retail.v2alpha.IRemoveLocalInventoriesMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; removeLocalInventories( - request?: protos.google.cloud.retail.v2alpha.IRemoveLocalInventoriesRequest, - optionsOrCallback?: CallOptions|Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>, - callback?: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>|void { + request?: protos.google.cloud.retail.v2alpha.IRemoveLocalInventoriesRequest, + optionsOrCallback?: + | CallOptions + | Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IRemoveLocalInventoriesResponse, + protos.google.cloud.retail.v2alpha.IRemoveLocalInventoriesMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + callback?: Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IRemoveLocalInventoriesResponse, + protos.google.cloud.retail.v2alpha.IRemoveLocalInventoriesMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + LROperation< + protos.google.cloud.retail.v2alpha.IRemoveLocalInventoriesResponse, + protos.google.cloud.retail.v2alpha.IRemoveLocalInventoriesMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'product': request.product ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + product: request.product ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IRemoveLocalInventoriesResponse, + protos.google.cloud.retail.v2alpha.IRemoveLocalInventoriesMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, rawResponse, _) => { this._log.info('removeLocalInventories response %j', rawResponse); callback!(error, response, rawResponse, _); // We verified `callback` above. } : undefined; this._log.info('removeLocalInventories request %j', request); - return this.innerApiCalls.removeLocalInventories(request, options, wrappedCallback) - ?.then(([response, rawResponse, _]: [ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]) => { - this._log.info('removeLocalInventories response %j', rawResponse); - return [response, rawResponse, _]; - }); + return this.innerApiCalls + .removeLocalInventories(request, options, wrappedCallback) + ?.then( + ([response, rawResponse, _]: [ + LROperation< + protos.google.cloud.retail.v2alpha.IRemoveLocalInventoriesResponse, + protos.google.cloud.retail.v2alpha.IRemoveLocalInventoriesMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ]) => { + this._log.info('removeLocalInventories response %j', rawResponse); + return [response, rawResponse, _]; + }, + ); } -/** - * Check the status of the long running operation returned by `removeLocalInventories()`. - * @param {String} name - * The operation name that will be passed. - * @returns {Promise} - The promise which resolves to an object. - * The decoded operation object has result and metadata field to get information from. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/product_service.remove_local_inventories.js - * region_tag:retail_v2alpha_generated_ProductService_RemoveLocalInventories_async - */ - async checkRemoveLocalInventoriesProgress(name: string): Promise>{ + /** + * Check the status of the long running operation returned by `removeLocalInventories()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/product_service.remove_local_inventories.js + * region_tag:retail_v2alpha_generated_ProductService_RemoveLocalInventories_async + */ + async checkRemoveLocalInventoriesProgress( + name: string, + ): Promise< + LROperation< + protos.google.cloud.retail.v2alpha.RemoveLocalInventoriesResponse, + protos.google.cloud.retail.v2alpha.RemoveLocalInventoriesMetadata + > + > { this._log.info('removeLocalInventories long-running'); - const request = new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest({name}); + const request = + new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( + { name }, + ); const [operation] = await this.operationsClient.getOperation(request); - const decodeOperation = new this._gaxModule.Operation(operation, this.descriptors.longrunning.removeLocalInventories, this._gaxModule.createDefaultBackoffSettings()); - return decodeOperation as LROperation; - } - /** - * Gets a list of {@link protos.google.cloud.retail.v2alpha.Product|Product}s. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent branch resource name, such as - * `projects/* /locations/global/catalogs/default_catalog/branches/0`. Use - * `default_branch` as the branch ID, to list products under the default - * branch. - * - * If the caller does not have permission to list - * {@link protos.google.cloud.retail.v2alpha.Product|Product}s under this branch, - * regardless of whether or not this branch exists, a PERMISSION_DENIED error - * is returned. - * @param {number} request.pageSize - * Maximum number of {@link protos.google.cloud.retail.v2alpha.Product|Product}s to - * return. If unspecified, defaults to 100. The maximum allowed value is 1000. - * Values above 1000 will be coerced to 1000. - * - * If this field is negative, an INVALID_ARGUMENT error is returned. - * @param {string} request.pageToken - * A page token - * {@link protos.google.cloud.retail.v2alpha.ListProductsResponse.next_page_token|ListProductsResponse.next_page_token}, - * received from a previous - * {@link protos.google.cloud.retail.v2alpha.ProductService.ListProducts|ProductService.ListProducts} - * call. Provide this to retrieve the subsequent page. - * - * When paginating, all other parameters provided to - * {@link protos.google.cloud.retail.v2alpha.ProductService.ListProducts|ProductService.ListProducts} - * must match the call that provided the page token. Otherwise, an - * INVALID_ARGUMENT error is returned. - * @param {string} request.filter - * A filter to apply on the list results. Supported features: - * - * * List all the products under the parent branch if - * {@link protos.google.cloud.retail.v2alpha.ListProductsRequest.filter|filter} is unset. - * * List - * {@link protos.google.cloud.retail.v2alpha.Product.Type.VARIANT|Product.Type.VARIANT} - * {@link protos.google.cloud.retail.v2alpha.Product|Product}s sharing the same - * {@link protos.google.cloud.retail.v2alpha.Product.Type.PRIMARY|Product.Type.PRIMARY} - * {@link protos.google.cloud.retail.v2alpha.Product|Product}. For example: - * `primary_product_id = "some_product_id"` - * * List {@link protos.google.cloud.retail.v2alpha.Product|Product}s bundled in a - * {@link protos.google.cloud.retail.v2alpha.Product.Type.COLLECTION|Product.Type.COLLECTION} - * {@link protos.google.cloud.retail.v2alpha.Product|Product}. - * For example: - * `collection_product_id = "some_product_id"` - * * List {@link protos.google.cloud.retail.v2alpha.Product|Product}s with a partibular - * type. For example: - * `type = "PRIMARY"` - * `type = "VARIANT"` - * `type = "COLLECTION"` - * - * If the field is unrecognizable, an INVALID_ARGUMENT error is returned. - * - * If the specified - * {@link protos.google.cloud.retail.v2alpha.Product.Type.PRIMARY|Product.Type.PRIMARY} - * {@link protos.google.cloud.retail.v2alpha.Product|Product} or - * {@link protos.google.cloud.retail.v2alpha.Product.Type.COLLECTION|Product.Type.COLLECTION} - * {@link protos.google.cloud.retail.v2alpha.Product|Product} does not exist, a NOT_FOUND - * error is returned. - * @param {google.protobuf.FieldMask} request.readMask - * The fields of {@link protos.google.cloud.retail.v2alpha.Product|Product} to return in - * the responses. If not set or empty, the following fields are returned: - * - * * {@link protos.google.cloud.retail.v2alpha.Product.name|Product.name} - * * {@link protos.google.cloud.retail.v2alpha.Product.id|Product.id} - * * {@link protos.google.cloud.retail.v2alpha.Product.title|Product.title} - * * {@link protos.google.cloud.retail.v2alpha.Product.uri|Product.uri} - * * {@link protos.google.cloud.retail.v2alpha.Product.images|Product.images} - * * {@link protos.google.cloud.retail.v2alpha.Product.price_info|Product.price_info} - * * {@link protos.google.cloud.retail.v2alpha.Product.brands|Product.brands} - * - * If "*" is provided, all fields are returned. - * {@link protos.google.cloud.retail.v2alpha.Product.name|Product.name} is always returned - * no matter what mask is set. - * - * If an unsupported or unknown field is provided, an INVALID_ARGUMENT error - * is returned. - * @param {boolean} request.requireTotalSize - * If true and - * {@link protos.google.cloud.retail.v2alpha.ListProductsRequest.page_token|page_token} is - * empty, - * {@link protos.google.cloud.retail.v2alpha.ListProductsResponse.total_size|ListProductsResponse.total_size} - * is set to the total count of matched items irrespective of pagination. - * - * Notice that setting this field to true affects the performance. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.cloud.retail.v2alpha.Product|Product}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `listProductsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + const decodeOperation = new this._gaxModule.Operation( + operation, + this.descriptors.longrunning.removeLocalInventories, + this._gaxModule.createDefaultBackoffSettings(), + ); + return decodeOperation as LROperation< + protos.google.cloud.retail.v2alpha.RemoveLocalInventoriesResponse, + protos.google.cloud.retail.v2alpha.RemoveLocalInventoriesMetadata + >; + } + /** + * Gets a list of {@link protos.google.cloud.retail.v2alpha.Product|Product}s. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent branch resource name, such as + * `projects/* /locations/global/catalogs/default_catalog/branches/0`. Use + * `default_branch` as the branch ID, to list products under the default + * branch. + * + * If the caller does not have permission to list + * {@link protos.google.cloud.retail.v2alpha.Product|Product}s under this branch, + * regardless of whether or not this branch exists, a PERMISSION_DENIED error + * is returned. + * @param {number} request.pageSize + * Maximum number of {@link protos.google.cloud.retail.v2alpha.Product|Product}s to + * return. If unspecified, defaults to 100. The maximum allowed value is 1000. + * Values above 1000 will be coerced to 1000. + * + * If this field is negative, an INVALID_ARGUMENT error is returned. + * @param {string} request.pageToken + * A page token + * {@link protos.google.cloud.retail.v2alpha.ListProductsResponse.next_page_token|ListProductsResponse.next_page_token}, + * received from a previous + * {@link protos.google.cloud.retail.v2alpha.ProductService.ListProducts|ProductService.ListProducts} + * call. Provide this to retrieve the subsequent page. + * + * When paginating, all other parameters provided to + * {@link protos.google.cloud.retail.v2alpha.ProductService.ListProducts|ProductService.ListProducts} + * must match the call that provided the page token. Otherwise, an + * INVALID_ARGUMENT error is returned. + * @param {string} request.filter + * A filter to apply on the list results. Supported features: + * + * * List all the products under the parent branch if + * {@link protos.google.cloud.retail.v2alpha.ListProductsRequest.filter|filter} is unset. + * * List + * {@link protos.google.cloud.retail.v2alpha.Product.Type.VARIANT|Product.Type.VARIANT} + * {@link protos.google.cloud.retail.v2alpha.Product|Product}s sharing the same + * {@link protos.google.cloud.retail.v2alpha.Product.Type.PRIMARY|Product.Type.PRIMARY} + * {@link protos.google.cloud.retail.v2alpha.Product|Product}. For example: + * `primary_product_id = "some_product_id"` + * * List {@link protos.google.cloud.retail.v2alpha.Product|Product}s bundled in a + * {@link protos.google.cloud.retail.v2alpha.Product.Type.COLLECTION|Product.Type.COLLECTION} + * {@link protos.google.cloud.retail.v2alpha.Product|Product}. + * For example: + * `collection_product_id = "some_product_id"` + * * List {@link protos.google.cloud.retail.v2alpha.Product|Product}s with a partibular + * type. For example: + * `type = "PRIMARY"` + * `type = "VARIANT"` + * `type = "COLLECTION"` + * + * If the field is unrecognizable, an INVALID_ARGUMENT error is returned. + * + * If the specified + * {@link protos.google.cloud.retail.v2alpha.Product.Type.PRIMARY|Product.Type.PRIMARY} + * {@link protos.google.cloud.retail.v2alpha.Product|Product} or + * {@link protos.google.cloud.retail.v2alpha.Product.Type.COLLECTION|Product.Type.COLLECTION} + * {@link protos.google.cloud.retail.v2alpha.Product|Product} does not exist, a NOT_FOUND + * error is returned. + * @param {google.protobuf.FieldMask} request.readMask + * The fields of {@link protos.google.cloud.retail.v2alpha.Product|Product} to return in + * the responses. If not set or empty, the following fields are returned: + * + * * {@link protos.google.cloud.retail.v2alpha.Product.name|Product.name} + * * {@link protos.google.cloud.retail.v2alpha.Product.id|Product.id} + * * {@link protos.google.cloud.retail.v2alpha.Product.title|Product.title} + * * {@link protos.google.cloud.retail.v2alpha.Product.uri|Product.uri} + * * {@link protos.google.cloud.retail.v2alpha.Product.images|Product.images} + * * {@link protos.google.cloud.retail.v2alpha.Product.price_info|Product.price_info} + * * {@link protos.google.cloud.retail.v2alpha.Product.brands|Product.brands} + * + * If "*" is provided, all fields are returned. + * {@link protos.google.cloud.retail.v2alpha.Product.name|Product.name} is always returned + * no matter what mask is set. + * + * If an unsupported or unknown field is provided, an INVALID_ARGUMENT error + * is returned. + * @param {boolean} request.requireTotalSize + * If true and + * {@link protos.google.cloud.retail.v2alpha.ListProductsRequest.page_token|page_token} is + * empty, + * {@link protos.google.cloud.retail.v2alpha.ListProductsResponse.total_size|ListProductsResponse.total_size} + * is set to the total count of matched items irrespective of pagination. + * + * Notice that setting this field to true affects the performance. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.cloud.retail.v2alpha.Product|Product}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listProductsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listProducts( - request?: protos.google.cloud.retail.v2alpha.IListProductsRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.retail.v2alpha.IProduct[], - protos.google.cloud.retail.v2alpha.IListProductsRequest|null, - protos.google.cloud.retail.v2alpha.IListProductsResponse - ]>; + request?: protos.google.cloud.retail.v2alpha.IListProductsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IProduct[], + protos.google.cloud.retail.v2alpha.IListProductsRequest | null, + protos.google.cloud.retail.v2alpha.IListProductsResponse, + ] + >; listProducts( - request: protos.google.cloud.retail.v2alpha.IListProductsRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.cloud.retail.v2alpha.IListProductsRequest, - protos.google.cloud.retail.v2alpha.IListProductsResponse|null|undefined, - protos.google.cloud.retail.v2alpha.IProduct>): void; + request: protos.google.cloud.retail.v2alpha.IListProductsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.cloud.retail.v2alpha.IListProductsRequest, + | protos.google.cloud.retail.v2alpha.IListProductsResponse + | null + | undefined, + protos.google.cloud.retail.v2alpha.IProduct + >, + ): void; listProducts( - request: protos.google.cloud.retail.v2alpha.IListProductsRequest, - callback: PaginationCallback< - protos.google.cloud.retail.v2alpha.IListProductsRequest, - protos.google.cloud.retail.v2alpha.IListProductsResponse|null|undefined, - protos.google.cloud.retail.v2alpha.IProduct>): void; + request: protos.google.cloud.retail.v2alpha.IListProductsRequest, + callback: PaginationCallback< + protos.google.cloud.retail.v2alpha.IListProductsRequest, + | protos.google.cloud.retail.v2alpha.IListProductsResponse + | null + | undefined, + protos.google.cloud.retail.v2alpha.IProduct + >, + ): void; listProducts( - request?: protos.google.cloud.retail.v2alpha.IListProductsRequest, - optionsOrCallback?: CallOptions|PaginationCallback< + request?: protos.google.cloud.retail.v2alpha.IListProductsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.cloud.retail.v2alpha.IListProductsRequest, - protos.google.cloud.retail.v2alpha.IListProductsResponse|null|undefined, - protos.google.cloud.retail.v2alpha.IProduct>, - callback?: PaginationCallback< - protos.google.cloud.retail.v2alpha.IListProductsRequest, - protos.google.cloud.retail.v2alpha.IListProductsResponse|null|undefined, - protos.google.cloud.retail.v2alpha.IProduct>): - Promise<[ - protos.google.cloud.retail.v2alpha.IProduct[], - protos.google.cloud.retail.v2alpha.IListProductsRequest|null, - protos.google.cloud.retail.v2alpha.IListProductsResponse - ]>|void { + | protos.google.cloud.retail.v2alpha.IListProductsResponse + | null + | undefined, + protos.google.cloud.retail.v2alpha.IProduct + >, + callback?: PaginationCallback< + protos.google.cloud.retail.v2alpha.IListProductsRequest, + | protos.google.cloud.retail.v2alpha.IListProductsResponse + | null + | undefined, + protos.google.cloud.retail.v2alpha.IProduct + >, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IProduct[], + protos.google.cloud.retail.v2alpha.IListProductsRequest | null, + protos.google.cloud.retail.v2alpha.IListProductsResponse, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.cloud.retail.v2alpha.IListProductsRequest, - protos.google.cloud.retail.v2alpha.IListProductsResponse|null|undefined, - protos.google.cloud.retail.v2alpha.IProduct>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.cloud.retail.v2alpha.IListProductsRequest, + | protos.google.cloud.retail.v2alpha.IListProductsResponse + | null + | undefined, + protos.google.cloud.retail.v2alpha.IProduct + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listProducts values %j', values); callback!(error, values, nextPageRequest, rawResponse); @@ -2506,260 +3305,264 @@ export class ProductServiceClient { this._log.info('listProducts request %j', request); return this.innerApiCalls .listProducts(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.cloud.retail.v2alpha.IProduct[], - protos.google.cloud.retail.v2alpha.IListProductsRequest|null, - protos.google.cloud.retail.v2alpha.IListProductsResponse - ]) => { - this._log.info('listProducts values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.cloud.retail.v2alpha.IProduct[], + protos.google.cloud.retail.v2alpha.IListProductsRequest | null, + protos.google.cloud.retail.v2alpha.IListProductsResponse, + ]) => { + this._log.info('listProducts values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listProducts`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent branch resource name, such as - * `projects/* /locations/global/catalogs/default_catalog/branches/0`. Use - * `default_branch` as the branch ID, to list products under the default - * branch. - * - * If the caller does not have permission to list - * {@link protos.google.cloud.retail.v2alpha.Product|Product}s under this branch, - * regardless of whether or not this branch exists, a PERMISSION_DENIED error - * is returned. - * @param {number} request.pageSize - * Maximum number of {@link protos.google.cloud.retail.v2alpha.Product|Product}s to - * return. If unspecified, defaults to 100. The maximum allowed value is 1000. - * Values above 1000 will be coerced to 1000. - * - * If this field is negative, an INVALID_ARGUMENT error is returned. - * @param {string} request.pageToken - * A page token - * {@link protos.google.cloud.retail.v2alpha.ListProductsResponse.next_page_token|ListProductsResponse.next_page_token}, - * received from a previous - * {@link protos.google.cloud.retail.v2alpha.ProductService.ListProducts|ProductService.ListProducts} - * call. Provide this to retrieve the subsequent page. - * - * When paginating, all other parameters provided to - * {@link protos.google.cloud.retail.v2alpha.ProductService.ListProducts|ProductService.ListProducts} - * must match the call that provided the page token. Otherwise, an - * INVALID_ARGUMENT error is returned. - * @param {string} request.filter - * A filter to apply on the list results. Supported features: - * - * * List all the products under the parent branch if - * {@link protos.google.cloud.retail.v2alpha.ListProductsRequest.filter|filter} is unset. - * * List - * {@link protos.google.cloud.retail.v2alpha.Product.Type.VARIANT|Product.Type.VARIANT} - * {@link protos.google.cloud.retail.v2alpha.Product|Product}s sharing the same - * {@link protos.google.cloud.retail.v2alpha.Product.Type.PRIMARY|Product.Type.PRIMARY} - * {@link protos.google.cloud.retail.v2alpha.Product|Product}. For example: - * `primary_product_id = "some_product_id"` - * * List {@link protos.google.cloud.retail.v2alpha.Product|Product}s bundled in a - * {@link protos.google.cloud.retail.v2alpha.Product.Type.COLLECTION|Product.Type.COLLECTION} - * {@link protos.google.cloud.retail.v2alpha.Product|Product}. - * For example: - * `collection_product_id = "some_product_id"` - * * List {@link protos.google.cloud.retail.v2alpha.Product|Product}s with a partibular - * type. For example: - * `type = "PRIMARY"` - * `type = "VARIANT"` - * `type = "COLLECTION"` - * - * If the field is unrecognizable, an INVALID_ARGUMENT error is returned. - * - * If the specified - * {@link protos.google.cloud.retail.v2alpha.Product.Type.PRIMARY|Product.Type.PRIMARY} - * {@link protos.google.cloud.retail.v2alpha.Product|Product} or - * {@link protos.google.cloud.retail.v2alpha.Product.Type.COLLECTION|Product.Type.COLLECTION} - * {@link protos.google.cloud.retail.v2alpha.Product|Product} does not exist, a NOT_FOUND - * error is returned. - * @param {google.protobuf.FieldMask} request.readMask - * The fields of {@link protos.google.cloud.retail.v2alpha.Product|Product} to return in - * the responses. If not set or empty, the following fields are returned: - * - * * {@link protos.google.cloud.retail.v2alpha.Product.name|Product.name} - * * {@link protos.google.cloud.retail.v2alpha.Product.id|Product.id} - * * {@link protos.google.cloud.retail.v2alpha.Product.title|Product.title} - * * {@link protos.google.cloud.retail.v2alpha.Product.uri|Product.uri} - * * {@link protos.google.cloud.retail.v2alpha.Product.images|Product.images} - * * {@link protos.google.cloud.retail.v2alpha.Product.price_info|Product.price_info} - * * {@link protos.google.cloud.retail.v2alpha.Product.brands|Product.brands} - * - * If "*" is provided, all fields are returned. - * {@link protos.google.cloud.retail.v2alpha.Product.name|Product.name} is always returned - * no matter what mask is set. - * - * If an unsupported or unknown field is provided, an INVALID_ARGUMENT error - * is returned. - * @param {boolean} request.requireTotalSize - * If true and - * {@link protos.google.cloud.retail.v2alpha.ListProductsRequest.page_token|page_token} is - * empty, - * {@link protos.google.cloud.retail.v2alpha.ListProductsResponse.total_size|ListProductsResponse.total_size} - * is set to the total count of matched items irrespective of pagination. - * - * Notice that setting this field to true affects the performance. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.cloud.retail.v2alpha.Product|Product} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `listProductsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `listProducts`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent branch resource name, such as + * `projects/* /locations/global/catalogs/default_catalog/branches/0`. Use + * `default_branch` as the branch ID, to list products under the default + * branch. + * + * If the caller does not have permission to list + * {@link protos.google.cloud.retail.v2alpha.Product|Product}s under this branch, + * regardless of whether or not this branch exists, a PERMISSION_DENIED error + * is returned. + * @param {number} request.pageSize + * Maximum number of {@link protos.google.cloud.retail.v2alpha.Product|Product}s to + * return. If unspecified, defaults to 100. The maximum allowed value is 1000. + * Values above 1000 will be coerced to 1000. + * + * If this field is negative, an INVALID_ARGUMENT error is returned. + * @param {string} request.pageToken + * A page token + * {@link protos.google.cloud.retail.v2alpha.ListProductsResponse.next_page_token|ListProductsResponse.next_page_token}, + * received from a previous + * {@link protos.google.cloud.retail.v2alpha.ProductService.ListProducts|ProductService.ListProducts} + * call. Provide this to retrieve the subsequent page. + * + * When paginating, all other parameters provided to + * {@link protos.google.cloud.retail.v2alpha.ProductService.ListProducts|ProductService.ListProducts} + * must match the call that provided the page token. Otherwise, an + * INVALID_ARGUMENT error is returned. + * @param {string} request.filter + * A filter to apply on the list results. Supported features: + * + * * List all the products under the parent branch if + * {@link protos.google.cloud.retail.v2alpha.ListProductsRequest.filter|filter} is unset. + * * List + * {@link protos.google.cloud.retail.v2alpha.Product.Type.VARIANT|Product.Type.VARIANT} + * {@link protos.google.cloud.retail.v2alpha.Product|Product}s sharing the same + * {@link protos.google.cloud.retail.v2alpha.Product.Type.PRIMARY|Product.Type.PRIMARY} + * {@link protos.google.cloud.retail.v2alpha.Product|Product}. For example: + * `primary_product_id = "some_product_id"` + * * List {@link protos.google.cloud.retail.v2alpha.Product|Product}s bundled in a + * {@link protos.google.cloud.retail.v2alpha.Product.Type.COLLECTION|Product.Type.COLLECTION} + * {@link protos.google.cloud.retail.v2alpha.Product|Product}. + * For example: + * `collection_product_id = "some_product_id"` + * * List {@link protos.google.cloud.retail.v2alpha.Product|Product}s with a partibular + * type. For example: + * `type = "PRIMARY"` + * `type = "VARIANT"` + * `type = "COLLECTION"` + * + * If the field is unrecognizable, an INVALID_ARGUMENT error is returned. + * + * If the specified + * {@link protos.google.cloud.retail.v2alpha.Product.Type.PRIMARY|Product.Type.PRIMARY} + * {@link protos.google.cloud.retail.v2alpha.Product|Product} or + * {@link protos.google.cloud.retail.v2alpha.Product.Type.COLLECTION|Product.Type.COLLECTION} + * {@link protos.google.cloud.retail.v2alpha.Product|Product} does not exist, a NOT_FOUND + * error is returned. + * @param {google.protobuf.FieldMask} request.readMask + * The fields of {@link protos.google.cloud.retail.v2alpha.Product|Product} to return in + * the responses. If not set or empty, the following fields are returned: + * + * * {@link protos.google.cloud.retail.v2alpha.Product.name|Product.name} + * * {@link protos.google.cloud.retail.v2alpha.Product.id|Product.id} + * * {@link protos.google.cloud.retail.v2alpha.Product.title|Product.title} + * * {@link protos.google.cloud.retail.v2alpha.Product.uri|Product.uri} + * * {@link protos.google.cloud.retail.v2alpha.Product.images|Product.images} + * * {@link protos.google.cloud.retail.v2alpha.Product.price_info|Product.price_info} + * * {@link protos.google.cloud.retail.v2alpha.Product.brands|Product.brands} + * + * If "*" is provided, all fields are returned. + * {@link protos.google.cloud.retail.v2alpha.Product.name|Product.name} is always returned + * no matter what mask is set. + * + * If an unsupported or unknown field is provided, an INVALID_ARGUMENT error + * is returned. + * @param {boolean} request.requireTotalSize + * If true and + * {@link protos.google.cloud.retail.v2alpha.ListProductsRequest.page_token|page_token} is + * empty, + * {@link protos.google.cloud.retail.v2alpha.ListProductsResponse.total_size|ListProductsResponse.total_size} + * is set to the total count of matched items irrespective of pagination. + * + * Notice that setting this field to true affects the performance. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.cloud.retail.v2alpha.Product|Product} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listProductsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listProductsStream( - request?: protos.google.cloud.retail.v2alpha.IListProductsRequest, - options?: CallOptions): - Transform{ + request?: protos.google.cloud.retail.v2alpha.IListProductsRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); const defaultCallSettings = this._defaults['listProducts']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listProducts stream %j', request); return this.descriptors.page.listProducts.createStream( this.innerApiCalls.listProducts as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listProducts`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent branch resource name, such as - * `projects/* /locations/global/catalogs/default_catalog/branches/0`. Use - * `default_branch` as the branch ID, to list products under the default - * branch. - * - * If the caller does not have permission to list - * {@link protos.google.cloud.retail.v2alpha.Product|Product}s under this branch, - * regardless of whether or not this branch exists, a PERMISSION_DENIED error - * is returned. - * @param {number} request.pageSize - * Maximum number of {@link protos.google.cloud.retail.v2alpha.Product|Product}s to - * return. If unspecified, defaults to 100. The maximum allowed value is 1000. - * Values above 1000 will be coerced to 1000. - * - * If this field is negative, an INVALID_ARGUMENT error is returned. - * @param {string} request.pageToken - * A page token - * {@link protos.google.cloud.retail.v2alpha.ListProductsResponse.next_page_token|ListProductsResponse.next_page_token}, - * received from a previous - * {@link protos.google.cloud.retail.v2alpha.ProductService.ListProducts|ProductService.ListProducts} - * call. Provide this to retrieve the subsequent page. - * - * When paginating, all other parameters provided to - * {@link protos.google.cloud.retail.v2alpha.ProductService.ListProducts|ProductService.ListProducts} - * must match the call that provided the page token. Otherwise, an - * INVALID_ARGUMENT error is returned. - * @param {string} request.filter - * A filter to apply on the list results. Supported features: - * - * * List all the products under the parent branch if - * {@link protos.google.cloud.retail.v2alpha.ListProductsRequest.filter|filter} is unset. - * * List - * {@link protos.google.cloud.retail.v2alpha.Product.Type.VARIANT|Product.Type.VARIANT} - * {@link protos.google.cloud.retail.v2alpha.Product|Product}s sharing the same - * {@link protos.google.cloud.retail.v2alpha.Product.Type.PRIMARY|Product.Type.PRIMARY} - * {@link protos.google.cloud.retail.v2alpha.Product|Product}. For example: - * `primary_product_id = "some_product_id"` - * * List {@link protos.google.cloud.retail.v2alpha.Product|Product}s bundled in a - * {@link protos.google.cloud.retail.v2alpha.Product.Type.COLLECTION|Product.Type.COLLECTION} - * {@link protos.google.cloud.retail.v2alpha.Product|Product}. - * For example: - * `collection_product_id = "some_product_id"` - * * List {@link protos.google.cloud.retail.v2alpha.Product|Product}s with a partibular - * type. For example: - * `type = "PRIMARY"` - * `type = "VARIANT"` - * `type = "COLLECTION"` - * - * If the field is unrecognizable, an INVALID_ARGUMENT error is returned. - * - * If the specified - * {@link protos.google.cloud.retail.v2alpha.Product.Type.PRIMARY|Product.Type.PRIMARY} - * {@link protos.google.cloud.retail.v2alpha.Product|Product} or - * {@link protos.google.cloud.retail.v2alpha.Product.Type.COLLECTION|Product.Type.COLLECTION} - * {@link protos.google.cloud.retail.v2alpha.Product|Product} does not exist, a NOT_FOUND - * error is returned. - * @param {google.protobuf.FieldMask} request.readMask - * The fields of {@link protos.google.cloud.retail.v2alpha.Product|Product} to return in - * the responses. If not set or empty, the following fields are returned: - * - * * {@link protos.google.cloud.retail.v2alpha.Product.name|Product.name} - * * {@link protos.google.cloud.retail.v2alpha.Product.id|Product.id} - * * {@link protos.google.cloud.retail.v2alpha.Product.title|Product.title} - * * {@link protos.google.cloud.retail.v2alpha.Product.uri|Product.uri} - * * {@link protos.google.cloud.retail.v2alpha.Product.images|Product.images} - * * {@link protos.google.cloud.retail.v2alpha.Product.price_info|Product.price_info} - * * {@link protos.google.cloud.retail.v2alpha.Product.brands|Product.brands} - * - * If "*" is provided, all fields are returned. - * {@link protos.google.cloud.retail.v2alpha.Product.name|Product.name} is always returned - * no matter what mask is set. - * - * If an unsupported or unknown field is provided, an INVALID_ARGUMENT error - * is returned. - * @param {boolean} request.requireTotalSize - * If true and - * {@link protos.google.cloud.retail.v2alpha.ListProductsRequest.page_token|page_token} is - * empty, - * {@link protos.google.cloud.retail.v2alpha.ListProductsResponse.total_size|ListProductsResponse.total_size} - * is set to the total count of matched items irrespective of pagination. - * - * Notice that setting this field to true affects the performance. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.cloud.retail.v2alpha.Product|Product}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/product_service.list_products.js - * region_tag:retail_v2alpha_generated_ProductService_ListProducts_async - */ + /** + * Equivalent to `listProducts`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent branch resource name, such as + * `projects/* /locations/global/catalogs/default_catalog/branches/0`. Use + * `default_branch` as the branch ID, to list products under the default + * branch. + * + * If the caller does not have permission to list + * {@link protos.google.cloud.retail.v2alpha.Product|Product}s under this branch, + * regardless of whether or not this branch exists, a PERMISSION_DENIED error + * is returned. + * @param {number} request.pageSize + * Maximum number of {@link protos.google.cloud.retail.v2alpha.Product|Product}s to + * return. If unspecified, defaults to 100. The maximum allowed value is 1000. + * Values above 1000 will be coerced to 1000. + * + * If this field is negative, an INVALID_ARGUMENT error is returned. + * @param {string} request.pageToken + * A page token + * {@link protos.google.cloud.retail.v2alpha.ListProductsResponse.next_page_token|ListProductsResponse.next_page_token}, + * received from a previous + * {@link protos.google.cloud.retail.v2alpha.ProductService.ListProducts|ProductService.ListProducts} + * call. Provide this to retrieve the subsequent page. + * + * When paginating, all other parameters provided to + * {@link protos.google.cloud.retail.v2alpha.ProductService.ListProducts|ProductService.ListProducts} + * must match the call that provided the page token. Otherwise, an + * INVALID_ARGUMENT error is returned. + * @param {string} request.filter + * A filter to apply on the list results. Supported features: + * + * * List all the products under the parent branch if + * {@link protos.google.cloud.retail.v2alpha.ListProductsRequest.filter|filter} is unset. + * * List + * {@link protos.google.cloud.retail.v2alpha.Product.Type.VARIANT|Product.Type.VARIANT} + * {@link protos.google.cloud.retail.v2alpha.Product|Product}s sharing the same + * {@link protos.google.cloud.retail.v2alpha.Product.Type.PRIMARY|Product.Type.PRIMARY} + * {@link protos.google.cloud.retail.v2alpha.Product|Product}. For example: + * `primary_product_id = "some_product_id"` + * * List {@link protos.google.cloud.retail.v2alpha.Product|Product}s bundled in a + * {@link protos.google.cloud.retail.v2alpha.Product.Type.COLLECTION|Product.Type.COLLECTION} + * {@link protos.google.cloud.retail.v2alpha.Product|Product}. + * For example: + * `collection_product_id = "some_product_id"` + * * List {@link protos.google.cloud.retail.v2alpha.Product|Product}s with a partibular + * type. For example: + * `type = "PRIMARY"` + * `type = "VARIANT"` + * `type = "COLLECTION"` + * + * If the field is unrecognizable, an INVALID_ARGUMENT error is returned. + * + * If the specified + * {@link protos.google.cloud.retail.v2alpha.Product.Type.PRIMARY|Product.Type.PRIMARY} + * {@link protos.google.cloud.retail.v2alpha.Product|Product} or + * {@link protos.google.cloud.retail.v2alpha.Product.Type.COLLECTION|Product.Type.COLLECTION} + * {@link protos.google.cloud.retail.v2alpha.Product|Product} does not exist, a NOT_FOUND + * error is returned. + * @param {google.protobuf.FieldMask} request.readMask + * The fields of {@link protos.google.cloud.retail.v2alpha.Product|Product} to return in + * the responses. If not set or empty, the following fields are returned: + * + * * {@link protos.google.cloud.retail.v2alpha.Product.name|Product.name} + * * {@link protos.google.cloud.retail.v2alpha.Product.id|Product.id} + * * {@link protos.google.cloud.retail.v2alpha.Product.title|Product.title} + * * {@link protos.google.cloud.retail.v2alpha.Product.uri|Product.uri} + * * {@link protos.google.cloud.retail.v2alpha.Product.images|Product.images} + * * {@link protos.google.cloud.retail.v2alpha.Product.price_info|Product.price_info} + * * {@link protos.google.cloud.retail.v2alpha.Product.brands|Product.brands} + * + * If "*" is provided, all fields are returned. + * {@link protos.google.cloud.retail.v2alpha.Product.name|Product.name} is always returned + * no matter what mask is set. + * + * If an unsupported or unknown field is provided, an INVALID_ARGUMENT error + * is returned. + * @param {boolean} request.requireTotalSize + * If true and + * {@link protos.google.cloud.retail.v2alpha.ListProductsRequest.page_token|page_token} is + * empty, + * {@link protos.google.cloud.retail.v2alpha.ListProductsResponse.total_size|ListProductsResponse.total_size} + * is set to the total count of matched items irrespective of pagination. + * + * Notice that setting this field to true affects the performance. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.cloud.retail.v2alpha.Product|Product}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/product_service.list_products.js + * region_tag:retail_v2alpha_generated_ProductService_ListProducts_async + */ listProductsAsync( - request?: protos.google.cloud.retail.v2alpha.IListProductsRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.cloud.retail.v2alpha.IListProductsRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); const defaultCallSettings = this._defaults['listProducts']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listProducts iterate %j', request); return this.descriptors.page.listProducts.asyncIterate( this.innerApiCalls['listProducts'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } // -------------------- @@ -2772,7 +3575,7 @@ export class ProductServiceClient { * @param {string} project * @returns {string} Resource name string. */ - alertConfigPath(project:string) { + alertConfigPath(project: string) { return this.pathTemplates.alertConfigPathTemplate.render({ project: project, }); @@ -2786,7 +3589,8 @@ export class ProductServiceClient { * @returns {string} A string representing the project. */ matchProjectFromAlertConfigName(alertConfigName: string) { - return this.pathTemplates.alertConfigPathTemplate.match(alertConfigName).project; + return this.pathTemplates.alertConfigPathTemplate.match(alertConfigName) + .project; } /** @@ -2797,7 +3601,7 @@ export class ProductServiceClient { * @param {string} catalog * @returns {string} Resource name string. */ - attributesConfigPath(project:string,location:string,catalog:string) { + attributesConfigPath(project: string, location: string, catalog: string) { return this.pathTemplates.attributesConfigPathTemplate.render({ project: project, location: location, @@ -2813,7 +3617,9 @@ export class ProductServiceClient { * @returns {string} A string representing the project. */ matchProjectFromAttributesConfigName(attributesConfigName: string) { - return this.pathTemplates.attributesConfigPathTemplate.match(attributesConfigName).project; + return this.pathTemplates.attributesConfigPathTemplate.match( + attributesConfigName, + ).project; } /** @@ -2824,7 +3630,9 @@ export class ProductServiceClient { * @returns {string} A string representing the location. */ matchLocationFromAttributesConfigName(attributesConfigName: string) { - return this.pathTemplates.attributesConfigPathTemplate.match(attributesConfigName).location; + return this.pathTemplates.attributesConfigPathTemplate.match( + attributesConfigName, + ).location; } /** @@ -2835,7 +3643,9 @@ export class ProductServiceClient { * @returns {string} A string representing the catalog. */ matchCatalogFromAttributesConfigName(attributesConfigName: string) { - return this.pathTemplates.attributesConfigPathTemplate.match(attributesConfigName).catalog; + return this.pathTemplates.attributesConfigPathTemplate.match( + attributesConfigName, + ).catalog; } /** @@ -2847,7 +3657,12 @@ export class ProductServiceClient { * @param {string} branch * @returns {string} Resource name string. */ - branchPath(project:string,location:string,catalog:string,branch:string) { + branchPath( + project: string, + location: string, + catalog: string, + branch: string, + ) { return this.pathTemplates.branchPathTemplate.render({ project: project, location: location, @@ -2908,7 +3723,7 @@ export class ProductServiceClient { * @param {string} catalog * @returns {string} Resource name string. */ - catalogPath(project:string,location:string,catalog:string) { + catalogPath(project: string, location: string, catalog: string) { return this.pathTemplates.catalogPathTemplate.render({ project: project, location: location, @@ -2957,7 +3772,7 @@ export class ProductServiceClient { * @param {string} catalog * @returns {string} Resource name string. */ - completionConfigPath(project:string,location:string,catalog:string) { + completionConfigPath(project: string, location: string, catalog: string) { return this.pathTemplates.completionConfigPathTemplate.render({ project: project, location: location, @@ -2973,7 +3788,9 @@ export class ProductServiceClient { * @returns {string} A string representing the project. */ matchProjectFromCompletionConfigName(completionConfigName: string) { - return this.pathTemplates.completionConfigPathTemplate.match(completionConfigName).project; + return this.pathTemplates.completionConfigPathTemplate.match( + completionConfigName, + ).project; } /** @@ -2984,7 +3801,9 @@ export class ProductServiceClient { * @returns {string} A string representing the location. */ matchLocationFromCompletionConfigName(completionConfigName: string) { - return this.pathTemplates.completionConfigPathTemplate.match(completionConfigName).location; + return this.pathTemplates.completionConfigPathTemplate.match( + completionConfigName, + ).location; } /** @@ -2995,7 +3814,9 @@ export class ProductServiceClient { * @returns {string} A string representing the catalog. */ matchCatalogFromCompletionConfigName(completionConfigName: string) { - return this.pathTemplates.completionConfigPathTemplate.match(completionConfigName).catalog; + return this.pathTemplates.completionConfigPathTemplate.match( + completionConfigName, + ).catalog; } /** @@ -3007,7 +3828,12 @@ export class ProductServiceClient { * @param {string} control * @returns {string} Resource name string. */ - controlPath(project:string,location:string,catalog:string,control:string) { + controlPath( + project: string, + location: string, + catalog: string, + control: string, + ) { return this.pathTemplates.controlPathTemplate.render({ project: project, location: location, @@ -3066,7 +3892,7 @@ export class ProductServiceClient { * @param {string} project * @returns {string} Resource name string. */ - loggingConfigPath(project:string) { + loggingConfigPath(project: string) { return this.pathTemplates.loggingConfigPathTemplate.render({ project: project, }); @@ -3080,7 +3906,8 @@ export class ProductServiceClient { * @returns {string} A string representing the project. */ matchProjectFromLoggingConfigName(loggingConfigName: string) { - return this.pathTemplates.loggingConfigPathTemplate.match(loggingConfigName).project; + return this.pathTemplates.loggingConfigPathTemplate.match(loggingConfigName) + .project; } /** @@ -3092,7 +3919,12 @@ export class ProductServiceClient { * @param {string} merchant_center_account_link * @returns {string} Resource name string. */ - merchantCenterAccountLinkPath(project:string,location:string,catalog:string,merchantCenterAccountLink:string) { + merchantCenterAccountLinkPath( + project: string, + location: string, + catalog: string, + merchantCenterAccountLink: string, + ) { return this.pathTemplates.merchantCenterAccountLinkPathTemplate.render({ project: project, location: location, @@ -3108,8 +3940,12 @@ export class ProductServiceClient { * A fully-qualified path representing MerchantCenterAccountLink resource. * @returns {string} A string representing the project. */ - matchProjectFromMerchantCenterAccountLinkName(merchantCenterAccountLinkName: string) { - return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match(merchantCenterAccountLinkName).project; + matchProjectFromMerchantCenterAccountLinkName( + merchantCenterAccountLinkName: string, + ) { + return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match( + merchantCenterAccountLinkName, + ).project; } /** @@ -3119,8 +3955,12 @@ export class ProductServiceClient { * A fully-qualified path representing MerchantCenterAccountLink resource. * @returns {string} A string representing the location. */ - matchLocationFromMerchantCenterAccountLinkName(merchantCenterAccountLinkName: string) { - return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match(merchantCenterAccountLinkName).location; + matchLocationFromMerchantCenterAccountLinkName( + merchantCenterAccountLinkName: string, + ) { + return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match( + merchantCenterAccountLinkName, + ).location; } /** @@ -3130,8 +3970,12 @@ export class ProductServiceClient { * A fully-qualified path representing MerchantCenterAccountLink resource. * @returns {string} A string representing the catalog. */ - matchCatalogFromMerchantCenterAccountLinkName(merchantCenterAccountLinkName: string) { - return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match(merchantCenterAccountLinkName).catalog; + matchCatalogFromMerchantCenterAccountLinkName( + merchantCenterAccountLinkName: string, + ) { + return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match( + merchantCenterAccountLinkName, + ).catalog; } /** @@ -3141,8 +3985,12 @@ export class ProductServiceClient { * A fully-qualified path representing MerchantCenterAccountLink resource. * @returns {string} A string representing the merchant_center_account_link. */ - matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName(merchantCenterAccountLinkName: string) { - return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match(merchantCenterAccountLinkName).merchant_center_account_link; + matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName( + merchantCenterAccountLinkName: string, + ) { + return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match( + merchantCenterAccountLinkName, + ).merchant_center_account_link; } /** @@ -3154,7 +4002,7 @@ export class ProductServiceClient { * @param {string} model * @returns {string} Resource name string. */ - modelPath(project:string,location:string,catalog:string,model:string) { + modelPath(project: string, location: string, catalog: string, model: string) { return this.pathTemplates.modelPathTemplate.render({ project: project, location: location, @@ -3217,7 +4065,13 @@ export class ProductServiceClient { * @param {string} product * @returns {string} Resource name string. */ - productPath(project:string,location:string,catalog:string,branch:string,product:string) { + productPath( + project: string, + location: string, + catalog: string, + branch: string, + product: string, + ) { return this.pathTemplates.productPathTemplate.render({ project: project, location: location, @@ -3288,7 +4142,7 @@ export class ProductServiceClient { * @param {string} project * @returns {string} Resource name string. */ - retailProjectPath(project:string) { + retailProjectPath(project: string) { return this.pathTemplates.retailProjectPathTemplate.render({ project: project, }); @@ -3302,7 +4156,8 @@ export class ProductServiceClient { * @returns {string} A string representing the project. */ matchProjectFromRetailProjectName(retailProjectName: string) { - return this.pathTemplates.retailProjectPathTemplate.match(retailProjectName).project; + return this.pathTemplates.retailProjectPathTemplate.match(retailProjectName) + .project; } /** @@ -3314,7 +4169,12 @@ export class ProductServiceClient { * @param {string} serving_config * @returns {string} Resource name string. */ - servingConfigPath(project:string,location:string,catalog:string,servingConfig:string) { + servingConfigPath( + project: string, + location: string, + catalog: string, + servingConfig: string, + ) { return this.pathTemplates.servingConfigPathTemplate.render({ project: project, location: location, @@ -3331,7 +4191,8 @@ export class ProductServiceClient { * @returns {string} A string representing the project. */ matchProjectFromServingConfigName(servingConfigName: string) { - return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName).project; + return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName) + .project; } /** @@ -3342,7 +4203,8 @@ export class ProductServiceClient { * @returns {string} A string representing the location. */ matchLocationFromServingConfigName(servingConfigName: string) { - return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName).location; + return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName) + .location; } /** @@ -3353,7 +4215,8 @@ export class ProductServiceClient { * @returns {string} A string representing the catalog. */ matchCatalogFromServingConfigName(servingConfigName: string) { - return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName).catalog; + return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName) + .catalog; } /** @@ -3364,7 +4227,8 @@ export class ProductServiceClient { * @returns {string} A string representing the serving_config. */ matchServingConfigFromServingConfigName(servingConfigName: string) { - return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName).serving_config; + return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName) + .serving_config; } /** @@ -3375,7 +4239,7 @@ export class ProductServiceClient { */ close(): Promise { if (this.productServiceStub && !this._terminated) { - return this.productServiceStub.then(stub => { + return this.productServiceStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -3384,4 +4248,4 @@ export class ProductServiceClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/src/v2alpha/project_service_client.ts.baseline b/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/src/v2alpha/project_service_client.ts.baseline index 9ec5e1615f23..cdb23e737e55 100644 --- a/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/src/v2alpha/project_service_client.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/src/v2alpha/project_service_client.ts.baseline @@ -18,15 +18,22 @@ /* global window */ import * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions, GrpcClientOptions, LROperation} from 'google-gax'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + GrpcClientOptions, + LROperation, +} from 'google-gax'; // @ts-ignore import type * as protos from '../../../protos/protos.js'; import * as project_service_client_config from './project_service_client_config.json'; import fs from 'fs'; import path from 'path'; -import {fileURLToPath} from 'url'; -import {getJSON} from '../json-helper.cjs'; +import { fileURLToPath } from 'url'; +import { getJSON } from '../json-helper.cjs'; // @ts-ignore const dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -36,15 +43,15 @@ const dirname = path.dirname(fileURLToPath(import.meta.url)); * This file defines retry strategy and timeouts for all API methods in this library. */ const gapicConfig = getJSON( - path.join(dirname, 'project_service_client_config.json') + path.join(dirname, 'project_service_client_config.json'), ); const jsonProtos = getJSON( - path.join(dirname, '..', '..', '..', 'protos/protos.json') + path.join(dirname, '..', '..', '..', 'protos/protos.json'), ); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; const version = getJSON( - path.join(dirname, '..', '..', '..', '..', 'package.json') + path.join(dirname, '..', '..', '..', '..', 'package.json'), ).version; /** @@ -59,7 +66,7 @@ export class ProjectServiceClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('retail'); @@ -71,10 +78,10 @@ export class ProjectServiceClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; operationsClient: gax.OperationsClient; - projectServiceStub?: Promise<{[name: string]: Function}>; + projectServiceStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of ProjectServiceClient. @@ -116,21 +123,42 @@ export class ProjectServiceClient { * const client = new ProjectServiceClient({fallback: 'rest'}, gax); * ``` */ - constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { // Ensure that options include all the required fields. const staticMembers = this.constructor as typeof ProjectServiceClient; - if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { - throw new Error('Please set either universe_domain or universeDomain, but not both.'); + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); } - const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; - this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; this._servicePath = 'retail.' + this._universeDomain; - const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; - const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. if (servicePath !== this._servicePath && !('scopes' in opts)) { @@ -152,7 +180,7 @@ export class ProjectServiceClient { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; @@ -169,10 +197,7 @@ export class ProjectServiceClient { const isEsm = true; const isEsmString = isEsm ? '-esm' : '-cjs'; // Determine the client header string. - const clientHeader = [ - `gax/${this._gaxModule.version}`, - `gapic/${version}`, - ]; + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/{process.versions.node}${isEsmString}`); } else { @@ -180,7 +205,7 @@ export class ProjectServiceClient { } if (!opts.fallback) { clientHeader.push(`grpc/${this._gaxGrpc.grpcVersion}`); - } else if (opts.fallback === 'rest' ) { + } else if (opts.fallback === 'rest') { clientHeader.push(`rest/${this._gaxGrpc.grpcVersion}`); } if (opts.libName && opts.libVersion) { @@ -188,50 +213,52 @@ export class ProjectServiceClient { } // Load the applicable protos. - this._protos = this._gaxGrpc.loadProtoJSON(jsonProtos as gax.protobuf.INamespace); + this._protos = this._gaxGrpc.loadProtoJSON( + jsonProtos as gax.protobuf.INamespace, + ); // This API contains "path templates"; forward-slash-separated // identifiers to uniquely identify resources within the API. // Create useful helper objects for these. this.pathTemplates = { alertConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/alertConfig' + 'projects/{project}/alertConfig', ), attributesConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/attributesConfig' + 'projects/{project}/locations/{location}/catalogs/{catalog}/attributesConfig', ), branchPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}', ), catalogPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}' + 'projects/{project}/locations/{location}/catalogs/{catalog}', ), completionConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/completionConfig' + 'projects/{project}/locations/{location}/catalogs/{catalog}/completionConfig', ), controlPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/controls/{control}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/controls/{control}', ), loggingConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/loggingConfig' + 'projects/{project}/loggingConfig', ), merchantCenterAccountLinkPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/merchantCenterAccountLinks/{merchant_center_account_link}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/merchantCenterAccountLinks/{merchant_center_account_link}', ), modelPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/models/{model}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/models/{model}', ), productPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}', ), projectPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}' + 'projects/{project}', ), retailProjectPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/retailProject' + 'projects/{project}/retailProject', ), servingConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/servingConfigs/{serving_config}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/servingConfigs/{serving_config}', ), }; @@ -241,31 +268,60 @@ export class ProjectServiceClient { // rather than holding a request open. const lroOptions: GrpcClientOptions = { auth: this.auth, - grpc: 'grpc' in this._gaxGrpc ? this._gaxGrpc.grpc : undefined + grpc: 'grpc' in this._gaxGrpc ? this._gaxGrpc.grpc : undefined, }; if (opts.fallback === 'rest') { lroOptions.protoJson = protoFilesRoot; - lroOptions.httpRules = [{selector: 'google.longrunning.Operations.GetOperation',get: '/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*/operations/*}',additional_bindings: [{get: '/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*/places/*/operations/*}',},{get: '/v2alpha/{name=projects/*/locations/*/catalogs/*/operations/*}',},{get: '/v2alpha/{name=projects/*/locations/*/operations/*}',},{get: '/v2alpha/{name=projects/*/operations/*}',}], - },{selector: 'google.longrunning.Operations.ListOperations',get: '/v2alpha/{name=projects/*/locations/*/catalogs/*}/operations',additional_bindings: [{get: '/v2alpha/{name=projects/*/locations/*}/operations',},{get: '/v2alpha/{name=projects/*}/operations',}], - }]; + lroOptions.httpRules = [ + { + selector: 'google.longrunning.Operations.GetOperation', + get: '/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*/operations/*}', + additional_bindings: [ + { + get: '/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*/places/*/operations/*}', + }, + { + get: '/v2alpha/{name=projects/*/locations/*/catalogs/*/operations/*}', + }, + { get: '/v2alpha/{name=projects/*/locations/*/operations/*}' }, + { get: '/v2alpha/{name=projects/*/operations/*}' }, + ], + }, + { + selector: 'google.longrunning.Operations.ListOperations', + get: '/v2alpha/{name=projects/*/locations/*/catalogs/*}/operations', + additional_bindings: [ + { get: '/v2alpha/{name=projects/*/locations/*}/operations' }, + { get: '/v2alpha/{name=projects/*}/operations' }, + ], + }, + ]; } - this.operationsClient = this._gaxModule.lro(lroOptions).operationsClient(opts); + this.operationsClient = this._gaxModule + .lro(lroOptions) + .operationsClient(opts); const enrollSolutionResponse = protoFilesRoot.lookup( - '.google.cloud.retail.v2alpha.EnrollSolutionResponse') as gax.protobuf.Type; + '.google.cloud.retail.v2alpha.EnrollSolutionResponse', + ) as gax.protobuf.Type; const enrollSolutionMetadata = protoFilesRoot.lookup( - '.google.cloud.retail.v2alpha.EnrollSolutionMetadata') as gax.protobuf.Type; + '.google.cloud.retail.v2alpha.EnrollSolutionMetadata', + ) as gax.protobuf.Type; this.descriptors.longrunning = { enrollSolution: new this._gaxModule.LongrunningDescriptor( this.operationsClient, enrollSolutionResponse.decode.bind(enrollSolutionResponse), - enrollSolutionMetadata.decode.bind(enrollSolutionMetadata)) + enrollSolutionMetadata.decode.bind(enrollSolutionMetadata), + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.cloud.retail.v2alpha.ProjectService', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.cloud.retail.v2alpha.ProjectService', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + { 'x-goog-api-client': clientHeader.join(' ') }, + ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -296,37 +352,49 @@ export class ProjectServiceClient { // Put together the "service stub" for // google.cloud.retail.v2alpha.ProjectService. this.projectServiceStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.cloud.retail.v2alpha.ProjectService') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.cloud.retail.v2alpha.ProjectService', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.cloud.retail.v2alpha.ProjectService, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts, + this._providedCustomServicePath, + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const projectServiceStubMethods = - ['getProject', 'acceptTerms', 'enrollSolution', 'listEnrolledSolutions', 'getLoggingConfig', 'updateLoggingConfig', 'getAlertConfig', 'updateAlertConfig']; + const projectServiceStubMethods = [ + 'getProject', + 'acceptTerms', + 'enrollSolution', + 'listEnrolledSolutions', + 'getLoggingConfig', + 'updateLoggingConfig', + 'getAlertConfig', + 'updateAlertConfig', + ]; for (const methodName of projectServiceStubMethods) { const callPromise = this.projectServiceStub.then( - stub => (...args: Array<{}>) => { - if (this._terminated) { - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error|null|undefined) => () => { + (stub) => + (...args: Array<{}>) => { + if (this._terminated) { + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { throw err; - }); + }, + ); - const descriptor = - this.descriptors.longrunning[methodName] || - undefined; + const descriptor = this.descriptors.longrunning[methodName] || undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -341,8 +409,14 @@ export class ProjectServiceClient { * @returns {string} The DNS address for this service. */ static get servicePath() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'retail.googleapis.com'; } @@ -354,8 +428,14 @@ export class ProjectServiceClient { * @returns {string} The DNS address for this service. */ static get apiEndpoint() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'retail.googleapis.com'; } @@ -386,9 +466,7 @@ export class ProjectServiceClient { * @returns {string[]} List of default scopes. */ static get scopes() { - return [ - 'https://www.googleapis.com/auth/cloud-platform' - ]; + return ['https://www.googleapis.com/auth/cloud-platform']; } getProjectId(): Promise; @@ -397,8 +475,9 @@ export class ProjectServiceClient { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId(callback?: Callback): - Promise|void { + getProjectId( + callback?: Callback, + ): Promise | void { if (callback) { this.auth.getProjectId(callback); return; @@ -409,817 +488,1178 @@ export class ProjectServiceClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Gets the project. - * - * Throws `NOT_FOUND` if the project wasn't initialized for the Retail API - * service. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. Full resource name of the project. Format: - * `projects/{project_number_or_id}/retailProject` - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.Project|Project}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/project_service.get_project.js - * region_tag:retail_v2alpha_generated_ProjectService_GetProject_async - */ + /** + * Gets the project. + * + * Throws `NOT_FOUND` if the project wasn't initialized for the Retail API + * service. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Full resource name of the project. Format: + * `projects/{project_number_or_id}/retailProject` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.Project|Project}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/project_service.get_project.js + * region_tag:retail_v2alpha_generated_ProjectService_GetProject_async + */ getProject( - request?: protos.google.cloud.retail.v2alpha.IGetProjectRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.retail.v2alpha.IProject, - protos.google.cloud.retail.v2alpha.IGetProjectRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.IGetProjectRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IProject, + protos.google.cloud.retail.v2alpha.IGetProjectRequest | undefined, + {} | undefined, + ] + >; getProject( - request: protos.google.cloud.retail.v2alpha.IGetProjectRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.retail.v2alpha.IProject, - protos.google.cloud.retail.v2alpha.IGetProjectRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IGetProjectRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.retail.v2alpha.IProject, + protos.google.cloud.retail.v2alpha.IGetProjectRequest | null | undefined, + {} | null | undefined + >, + ): void; getProject( - request: protos.google.cloud.retail.v2alpha.IGetProjectRequest, - callback: Callback< - protos.google.cloud.retail.v2alpha.IProject, - protos.google.cloud.retail.v2alpha.IGetProjectRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IGetProjectRequest, + callback: Callback< + protos.google.cloud.retail.v2alpha.IProject, + protos.google.cloud.retail.v2alpha.IGetProjectRequest | null | undefined, + {} | null | undefined + >, + ): void; getProject( - request?: protos.google.cloud.retail.v2alpha.IGetProjectRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.retail.v2alpha.IProject, - protos.google.cloud.retail.v2alpha.IGetProjectRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.retail.v2alpha.IGetProjectRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.retail.v2alpha.IProject, - protos.google.cloud.retail.v2alpha.IGetProjectRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.retail.v2alpha.IProject, - protos.google.cloud.retail.v2alpha.IGetProjectRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.retail.v2alpha.IGetProjectRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.retail.v2alpha.IProject, + protos.google.cloud.retail.v2alpha.IGetProjectRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IProject, + protos.google.cloud.retail.v2alpha.IGetProjectRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getProject request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.retail.v2alpha.IProject, - protos.google.cloud.retail.v2alpha.IGetProjectRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.retail.v2alpha.IProject, + | protos.google.cloud.retail.v2alpha.IGetProjectRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getProject response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.getProject(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.retail.v2alpha.IProject, - protos.google.cloud.retail.v2alpha.IGetProjectRequest|undefined, {}|undefined - ]) => { - this._log.info('getProject response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getProject(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.retail.v2alpha.IProject, + protos.google.cloud.retail.v2alpha.IGetProjectRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getProject response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Accepts service terms for this project. - * By making requests to this API, you agree to the terms of service linked - * below. - * https://cloud.google.com/retail/data-use-terms - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.project - * Required. Full resource name of the project. Format: - * `projects/{project_number_or_id}/retailProject` - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.Project|Project}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/project_service.accept_terms.js - * region_tag:retail_v2alpha_generated_ProjectService_AcceptTerms_async - */ + /** + * Accepts service terms for this project. + * By making requests to this API, you agree to the terms of service linked + * below. + * https://cloud.google.com/retail/data-use-terms + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.project + * Required. Full resource name of the project. Format: + * `projects/{project_number_or_id}/retailProject` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.Project|Project}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/project_service.accept_terms.js + * region_tag:retail_v2alpha_generated_ProjectService_AcceptTerms_async + */ acceptTerms( - request?: protos.google.cloud.retail.v2alpha.IAcceptTermsRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.retail.v2alpha.IProject, - protos.google.cloud.retail.v2alpha.IAcceptTermsRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.IAcceptTermsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IProject, + protos.google.cloud.retail.v2alpha.IAcceptTermsRequest | undefined, + {} | undefined, + ] + >; acceptTerms( - request: protos.google.cloud.retail.v2alpha.IAcceptTermsRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.retail.v2alpha.IProject, - protos.google.cloud.retail.v2alpha.IAcceptTermsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IAcceptTermsRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.retail.v2alpha.IProject, + protos.google.cloud.retail.v2alpha.IAcceptTermsRequest | null | undefined, + {} | null | undefined + >, + ): void; acceptTerms( - request: protos.google.cloud.retail.v2alpha.IAcceptTermsRequest, - callback: Callback< - protos.google.cloud.retail.v2alpha.IProject, - protos.google.cloud.retail.v2alpha.IAcceptTermsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IAcceptTermsRequest, + callback: Callback< + protos.google.cloud.retail.v2alpha.IProject, + protos.google.cloud.retail.v2alpha.IAcceptTermsRequest | null | undefined, + {} | null | undefined + >, + ): void; acceptTerms( - request?: protos.google.cloud.retail.v2alpha.IAcceptTermsRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.cloud.retail.v2alpha.IAcceptTermsRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.retail.v2alpha.IProject, - protos.google.cloud.retail.v2alpha.IAcceptTermsRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.cloud.retail.v2alpha.IProject, - protos.google.cloud.retail.v2alpha.IAcceptTermsRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.retail.v2alpha.IProject, - protos.google.cloud.retail.v2alpha.IAcceptTermsRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.retail.v2alpha.IAcceptTermsRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.retail.v2alpha.IProject, + protos.google.cloud.retail.v2alpha.IAcceptTermsRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IProject, + protos.google.cloud.retail.v2alpha.IAcceptTermsRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'project': request.project ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + project: request.project ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('acceptTerms request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.retail.v2alpha.IProject, - protos.google.cloud.retail.v2alpha.IAcceptTermsRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.retail.v2alpha.IProject, + | protos.google.cloud.retail.v2alpha.IAcceptTermsRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('acceptTerms response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.acceptTerms(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.retail.v2alpha.IProject, - protos.google.cloud.retail.v2alpha.IAcceptTermsRequest|undefined, {}|undefined - ]) => { - this._log.info('acceptTerms response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .acceptTerms(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.retail.v2alpha.IProject, + protos.google.cloud.retail.v2alpha.IAcceptTermsRequest | undefined, + {} | undefined, + ]) => { + this._log.info('acceptTerms response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Lists all the retail API solutions the project has enrolled. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. Full resource name of parent. Format: - * `projects/{project_number_or_id}` - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.ListEnrolledSolutionsResponse|ListEnrolledSolutionsResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/project_service.list_enrolled_solutions.js - * region_tag:retail_v2alpha_generated_ProjectService_ListEnrolledSolutions_async - */ + /** + * Lists all the retail API solutions the project has enrolled. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Full resource name of parent. Format: + * `projects/{project_number_or_id}` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.ListEnrolledSolutionsResponse|ListEnrolledSolutionsResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/project_service.list_enrolled_solutions.js + * region_tag:retail_v2alpha_generated_ProjectService_ListEnrolledSolutions_async + */ listEnrolledSolutions( - request?: protos.google.cloud.retail.v2alpha.IListEnrolledSolutionsRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.retail.v2alpha.IListEnrolledSolutionsResponse, - protos.google.cloud.retail.v2alpha.IListEnrolledSolutionsRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.IListEnrolledSolutionsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IListEnrolledSolutionsResponse, + ( + | protos.google.cloud.retail.v2alpha.IListEnrolledSolutionsRequest + | undefined + ), + {} | undefined, + ] + >; listEnrolledSolutions( - request: protos.google.cloud.retail.v2alpha.IListEnrolledSolutionsRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.retail.v2alpha.IListEnrolledSolutionsResponse, - protos.google.cloud.retail.v2alpha.IListEnrolledSolutionsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IListEnrolledSolutionsRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.retail.v2alpha.IListEnrolledSolutionsResponse, + | protos.google.cloud.retail.v2alpha.IListEnrolledSolutionsRequest + | null + | undefined, + {} | null | undefined + >, + ): void; listEnrolledSolutions( - request: protos.google.cloud.retail.v2alpha.IListEnrolledSolutionsRequest, - callback: Callback< - protos.google.cloud.retail.v2alpha.IListEnrolledSolutionsResponse, - protos.google.cloud.retail.v2alpha.IListEnrolledSolutionsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IListEnrolledSolutionsRequest, + callback: Callback< + protos.google.cloud.retail.v2alpha.IListEnrolledSolutionsResponse, + | protos.google.cloud.retail.v2alpha.IListEnrolledSolutionsRequest + | null + | undefined, + {} | null | undefined + >, + ): void; listEnrolledSolutions( - request?: protos.google.cloud.retail.v2alpha.IListEnrolledSolutionsRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.cloud.retail.v2alpha.IListEnrolledSolutionsRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.retail.v2alpha.IListEnrolledSolutionsResponse, - protos.google.cloud.retail.v2alpha.IListEnrolledSolutionsRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.cloud.retail.v2alpha.IListEnrolledSolutionsResponse, - protos.google.cloud.retail.v2alpha.IListEnrolledSolutionsRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.retail.v2alpha.IListEnrolledSolutionsResponse, - protos.google.cloud.retail.v2alpha.IListEnrolledSolutionsRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.retail.v2alpha.IListEnrolledSolutionsRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.retail.v2alpha.IListEnrolledSolutionsResponse, + | protos.google.cloud.retail.v2alpha.IListEnrolledSolutionsRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IListEnrolledSolutionsResponse, + ( + | protos.google.cloud.retail.v2alpha.IListEnrolledSolutionsRequest + | undefined + ), + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('listEnrolledSolutions request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.retail.v2alpha.IListEnrolledSolutionsResponse, - protos.google.cloud.retail.v2alpha.IListEnrolledSolutionsRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.retail.v2alpha.IListEnrolledSolutionsResponse, + | protos.google.cloud.retail.v2alpha.IListEnrolledSolutionsRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('listEnrolledSolutions response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.listEnrolledSolutions(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.retail.v2alpha.IListEnrolledSolutionsResponse, - protos.google.cloud.retail.v2alpha.IListEnrolledSolutionsRequest|undefined, {}|undefined - ]) => { - this._log.info('listEnrolledSolutions response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .listEnrolledSolutions(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.retail.v2alpha.IListEnrolledSolutionsResponse, + ( + | protos.google.cloud.retail.v2alpha.IListEnrolledSolutionsRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('listEnrolledSolutions response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Gets the {@link protos.google.cloud.retail.v2alpha.LoggingConfig|LoggingConfig} of the - * requested project. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. Full LoggingConfig resource name. Format: - * projects/{project_number}/loggingConfig - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.LoggingConfig|LoggingConfig}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/project_service.get_logging_config.js - * region_tag:retail_v2alpha_generated_ProjectService_GetLoggingConfig_async - */ + /** + * Gets the {@link protos.google.cloud.retail.v2alpha.LoggingConfig|LoggingConfig} of the + * requested project. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Full LoggingConfig resource name. Format: + * projects/{project_number}/loggingConfig + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.LoggingConfig|LoggingConfig}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/project_service.get_logging_config.js + * region_tag:retail_v2alpha_generated_ProjectService_GetLoggingConfig_async + */ getLoggingConfig( - request?: protos.google.cloud.retail.v2alpha.IGetLoggingConfigRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.retail.v2alpha.ILoggingConfig, - protos.google.cloud.retail.v2alpha.IGetLoggingConfigRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.IGetLoggingConfigRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.ILoggingConfig, + protos.google.cloud.retail.v2alpha.IGetLoggingConfigRequest | undefined, + {} | undefined, + ] + >; getLoggingConfig( - request: protos.google.cloud.retail.v2alpha.IGetLoggingConfigRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.retail.v2alpha.ILoggingConfig, - protos.google.cloud.retail.v2alpha.IGetLoggingConfigRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IGetLoggingConfigRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.retail.v2alpha.ILoggingConfig, + | protos.google.cloud.retail.v2alpha.IGetLoggingConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getLoggingConfig( - request: protos.google.cloud.retail.v2alpha.IGetLoggingConfigRequest, - callback: Callback< - protos.google.cloud.retail.v2alpha.ILoggingConfig, - protos.google.cloud.retail.v2alpha.IGetLoggingConfigRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IGetLoggingConfigRequest, + callback: Callback< + protos.google.cloud.retail.v2alpha.ILoggingConfig, + | protos.google.cloud.retail.v2alpha.IGetLoggingConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getLoggingConfig( - request?: protos.google.cloud.retail.v2alpha.IGetLoggingConfigRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.cloud.retail.v2alpha.IGetLoggingConfigRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.retail.v2alpha.ILoggingConfig, - protos.google.cloud.retail.v2alpha.IGetLoggingConfigRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.cloud.retail.v2alpha.ILoggingConfig, - protos.google.cloud.retail.v2alpha.IGetLoggingConfigRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.retail.v2alpha.ILoggingConfig, - protos.google.cloud.retail.v2alpha.IGetLoggingConfigRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.retail.v2alpha.IGetLoggingConfigRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.retail.v2alpha.ILoggingConfig, + | protos.google.cloud.retail.v2alpha.IGetLoggingConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.ILoggingConfig, + protos.google.cloud.retail.v2alpha.IGetLoggingConfigRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getLoggingConfig request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.retail.v2alpha.ILoggingConfig, - protos.google.cloud.retail.v2alpha.IGetLoggingConfigRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.retail.v2alpha.ILoggingConfig, + | protos.google.cloud.retail.v2alpha.IGetLoggingConfigRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getLoggingConfig response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.getLoggingConfig(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.retail.v2alpha.ILoggingConfig, - protos.google.cloud.retail.v2alpha.IGetLoggingConfigRequest|undefined, {}|undefined - ]) => { - this._log.info('getLoggingConfig response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getLoggingConfig(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.retail.v2alpha.ILoggingConfig, + ( + | protos.google.cloud.retail.v2alpha.IGetLoggingConfigRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('getLoggingConfig response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Updates the {@link protos.google.cloud.retail.v2alpha.LoggingConfig|LoggingConfig} of - * the requested project. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.cloud.retail.v2alpha.LoggingConfig} request.loggingConfig - * Required. The {@link protos.google.cloud.retail.v2alpha.LoggingConfig|LoggingConfig} to - * update. - * - * If the caller does not have permission to update the - * {@link protos.google.cloud.retail.v2alpha.LoggingConfig|LoggingConfig}, then a - * PERMISSION_DENIED error is returned. - * - * If the {@link protos.google.cloud.retail.v2alpha.LoggingConfig|LoggingConfig} to update - * does not exist, a NOT_FOUND error is returned. - * @param {google.protobuf.FieldMask} request.updateMask - * Indicates which fields in the provided - * {@link protos.google.cloud.retail.v2alpha.LoggingConfig|LoggingConfig} to update. The - * following are the only supported fields: - * - * * {@link protos.google.cloud.retail.v2alpha.LoggingConfig.default_log_generation_rule|LoggingConfig.default_log_generation_rule} - * * {@link protos.google.cloud.retail.v2alpha.LoggingConfig.service_log_generation_rules|LoggingConfig.service_log_generation_rules} - * - * If not set, all supported fields are updated. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.LoggingConfig|LoggingConfig}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/project_service.update_logging_config.js - * region_tag:retail_v2alpha_generated_ProjectService_UpdateLoggingConfig_async - */ + /** + * Updates the {@link protos.google.cloud.retail.v2alpha.LoggingConfig|LoggingConfig} of + * the requested project. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.cloud.retail.v2alpha.LoggingConfig} request.loggingConfig + * Required. The {@link protos.google.cloud.retail.v2alpha.LoggingConfig|LoggingConfig} to + * update. + * + * If the caller does not have permission to update the + * {@link protos.google.cloud.retail.v2alpha.LoggingConfig|LoggingConfig}, then a + * PERMISSION_DENIED error is returned. + * + * If the {@link protos.google.cloud.retail.v2alpha.LoggingConfig|LoggingConfig} to update + * does not exist, a NOT_FOUND error is returned. + * @param {google.protobuf.FieldMask} request.updateMask + * Indicates which fields in the provided + * {@link protos.google.cloud.retail.v2alpha.LoggingConfig|LoggingConfig} to update. The + * following are the only supported fields: + * + * * {@link protos.google.cloud.retail.v2alpha.LoggingConfig.default_log_generation_rule|LoggingConfig.default_log_generation_rule} + * * {@link protos.google.cloud.retail.v2alpha.LoggingConfig.service_log_generation_rules|LoggingConfig.service_log_generation_rules} + * + * If not set, all supported fields are updated. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.LoggingConfig|LoggingConfig}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/project_service.update_logging_config.js + * region_tag:retail_v2alpha_generated_ProjectService_UpdateLoggingConfig_async + */ updateLoggingConfig( - request?: protos.google.cloud.retail.v2alpha.IUpdateLoggingConfigRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.retail.v2alpha.ILoggingConfig, - protos.google.cloud.retail.v2alpha.IUpdateLoggingConfigRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.IUpdateLoggingConfigRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.ILoggingConfig, + ( + | protos.google.cloud.retail.v2alpha.IUpdateLoggingConfigRequest + | undefined + ), + {} | undefined, + ] + >; updateLoggingConfig( - request: protos.google.cloud.retail.v2alpha.IUpdateLoggingConfigRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.retail.v2alpha.ILoggingConfig, - protos.google.cloud.retail.v2alpha.IUpdateLoggingConfigRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IUpdateLoggingConfigRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.retail.v2alpha.ILoggingConfig, + | protos.google.cloud.retail.v2alpha.IUpdateLoggingConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateLoggingConfig( - request: protos.google.cloud.retail.v2alpha.IUpdateLoggingConfigRequest, - callback: Callback< - protos.google.cloud.retail.v2alpha.ILoggingConfig, - protos.google.cloud.retail.v2alpha.IUpdateLoggingConfigRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IUpdateLoggingConfigRequest, + callback: Callback< + protos.google.cloud.retail.v2alpha.ILoggingConfig, + | protos.google.cloud.retail.v2alpha.IUpdateLoggingConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateLoggingConfig( - request?: protos.google.cloud.retail.v2alpha.IUpdateLoggingConfigRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.retail.v2alpha.ILoggingConfig, - protos.google.cloud.retail.v2alpha.IUpdateLoggingConfigRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.retail.v2alpha.IUpdateLoggingConfigRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.retail.v2alpha.ILoggingConfig, - protos.google.cloud.retail.v2alpha.IUpdateLoggingConfigRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.retail.v2alpha.ILoggingConfig, - protos.google.cloud.retail.v2alpha.IUpdateLoggingConfigRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.retail.v2alpha.IUpdateLoggingConfigRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.retail.v2alpha.ILoggingConfig, + | protos.google.cloud.retail.v2alpha.IUpdateLoggingConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.ILoggingConfig, + ( + | protos.google.cloud.retail.v2alpha.IUpdateLoggingConfigRequest + | undefined + ), + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'logging_config.name': request.loggingConfig!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'logging_config.name': request.loggingConfig!.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateLoggingConfig request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.retail.v2alpha.ILoggingConfig, - protos.google.cloud.retail.v2alpha.IUpdateLoggingConfigRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.retail.v2alpha.ILoggingConfig, + | protos.google.cloud.retail.v2alpha.IUpdateLoggingConfigRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateLoggingConfig response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.updateLoggingConfig(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.retail.v2alpha.ILoggingConfig, - protos.google.cloud.retail.v2alpha.IUpdateLoggingConfigRequest|undefined, {}|undefined - ]) => { - this._log.info('updateLoggingConfig response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateLoggingConfig(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.retail.v2alpha.ILoggingConfig, + ( + | protos.google.cloud.retail.v2alpha.IUpdateLoggingConfigRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('updateLoggingConfig response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Get the {@link protos.google.cloud.retail.v2alpha.AlertConfig|AlertConfig} of the - * requested project. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. Full AlertConfig resource name. Format: - * projects/{project_number}/alertConfig - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.AlertConfig|AlertConfig}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/project_service.get_alert_config.js - * region_tag:retail_v2alpha_generated_ProjectService_GetAlertConfig_async - */ + /** + * Get the {@link protos.google.cloud.retail.v2alpha.AlertConfig|AlertConfig} of the + * requested project. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Full AlertConfig resource name. Format: + * projects/{project_number}/alertConfig + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.AlertConfig|AlertConfig}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/project_service.get_alert_config.js + * region_tag:retail_v2alpha_generated_ProjectService_GetAlertConfig_async + */ getAlertConfig( - request?: protos.google.cloud.retail.v2alpha.IGetAlertConfigRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.retail.v2alpha.IAlertConfig, - protos.google.cloud.retail.v2alpha.IGetAlertConfigRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.IGetAlertConfigRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IAlertConfig, + protos.google.cloud.retail.v2alpha.IGetAlertConfigRequest | undefined, + {} | undefined, + ] + >; getAlertConfig( - request: protos.google.cloud.retail.v2alpha.IGetAlertConfigRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.retail.v2alpha.IAlertConfig, - protos.google.cloud.retail.v2alpha.IGetAlertConfigRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IGetAlertConfigRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.retail.v2alpha.IAlertConfig, + | protos.google.cloud.retail.v2alpha.IGetAlertConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getAlertConfig( - request: protos.google.cloud.retail.v2alpha.IGetAlertConfigRequest, - callback: Callback< - protos.google.cloud.retail.v2alpha.IAlertConfig, - protos.google.cloud.retail.v2alpha.IGetAlertConfigRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IGetAlertConfigRequest, + callback: Callback< + protos.google.cloud.retail.v2alpha.IAlertConfig, + | protos.google.cloud.retail.v2alpha.IGetAlertConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getAlertConfig( - request?: protos.google.cloud.retail.v2alpha.IGetAlertConfigRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.retail.v2alpha.IAlertConfig, - protos.google.cloud.retail.v2alpha.IGetAlertConfigRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.retail.v2alpha.IGetAlertConfigRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.retail.v2alpha.IAlertConfig, - protos.google.cloud.retail.v2alpha.IGetAlertConfigRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.retail.v2alpha.IAlertConfig, - protos.google.cloud.retail.v2alpha.IGetAlertConfigRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.retail.v2alpha.IGetAlertConfigRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.retail.v2alpha.IAlertConfig, + | protos.google.cloud.retail.v2alpha.IGetAlertConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IAlertConfig, + protos.google.cloud.retail.v2alpha.IGetAlertConfigRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getAlertConfig request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.retail.v2alpha.IAlertConfig, - protos.google.cloud.retail.v2alpha.IGetAlertConfigRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.retail.v2alpha.IAlertConfig, + | protos.google.cloud.retail.v2alpha.IGetAlertConfigRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getAlertConfig response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.getAlertConfig(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.retail.v2alpha.IAlertConfig, - protos.google.cloud.retail.v2alpha.IGetAlertConfigRequest|undefined, {}|undefined - ]) => { - this._log.info('getAlertConfig response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getAlertConfig(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.retail.v2alpha.IAlertConfig, + protos.google.cloud.retail.v2alpha.IGetAlertConfigRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getAlertConfig response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Update the alert config of the requested project. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.cloud.retail.v2alpha.AlertConfig} request.alertConfig - * Required. The {@link protos.google.cloud.retail.v2alpha.AlertConfig|AlertConfig} to - * update. - * - * If the caller does not have permission to update the - * {@link protos.google.cloud.retail.v2alpha.AlertConfig|AlertConfig}, then a - * PERMISSION_DENIED error is returned. - * - * If the {@link protos.google.cloud.retail.v2alpha.AlertConfig|AlertConfig} to update - * does not exist, a NOT_FOUND error is returned. - * @param {google.protobuf.FieldMask} request.updateMask - * Indicates which fields in the provided - * {@link protos.google.cloud.retail.v2alpha.AlertConfig|AlertConfig} to update. If not - * set, all supported fields are updated. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.AlertConfig|AlertConfig}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/project_service.update_alert_config.js - * region_tag:retail_v2alpha_generated_ProjectService_UpdateAlertConfig_async - */ + /** + * Update the alert config of the requested project. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.cloud.retail.v2alpha.AlertConfig} request.alertConfig + * Required. The {@link protos.google.cloud.retail.v2alpha.AlertConfig|AlertConfig} to + * update. + * + * If the caller does not have permission to update the + * {@link protos.google.cloud.retail.v2alpha.AlertConfig|AlertConfig}, then a + * PERMISSION_DENIED error is returned. + * + * If the {@link protos.google.cloud.retail.v2alpha.AlertConfig|AlertConfig} to update + * does not exist, a NOT_FOUND error is returned. + * @param {google.protobuf.FieldMask} request.updateMask + * Indicates which fields in the provided + * {@link protos.google.cloud.retail.v2alpha.AlertConfig|AlertConfig} to update. If not + * set, all supported fields are updated. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.AlertConfig|AlertConfig}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/project_service.update_alert_config.js + * region_tag:retail_v2alpha_generated_ProjectService_UpdateAlertConfig_async + */ updateAlertConfig( - request?: protos.google.cloud.retail.v2alpha.IUpdateAlertConfigRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.retail.v2alpha.IAlertConfig, - protos.google.cloud.retail.v2alpha.IUpdateAlertConfigRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.IUpdateAlertConfigRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IAlertConfig, + protos.google.cloud.retail.v2alpha.IUpdateAlertConfigRequest | undefined, + {} | undefined, + ] + >; updateAlertConfig( - request: protos.google.cloud.retail.v2alpha.IUpdateAlertConfigRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.retail.v2alpha.IAlertConfig, - protos.google.cloud.retail.v2alpha.IUpdateAlertConfigRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IUpdateAlertConfigRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.retail.v2alpha.IAlertConfig, + | protos.google.cloud.retail.v2alpha.IUpdateAlertConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateAlertConfig( - request: protos.google.cloud.retail.v2alpha.IUpdateAlertConfigRequest, - callback: Callback< - protos.google.cloud.retail.v2alpha.IAlertConfig, - protos.google.cloud.retail.v2alpha.IUpdateAlertConfigRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IUpdateAlertConfigRequest, + callback: Callback< + protos.google.cloud.retail.v2alpha.IAlertConfig, + | protos.google.cloud.retail.v2alpha.IUpdateAlertConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateAlertConfig( - request?: protos.google.cloud.retail.v2alpha.IUpdateAlertConfigRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.retail.v2alpha.IAlertConfig, - protos.google.cloud.retail.v2alpha.IUpdateAlertConfigRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.retail.v2alpha.IUpdateAlertConfigRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.retail.v2alpha.IAlertConfig, - protos.google.cloud.retail.v2alpha.IUpdateAlertConfigRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.retail.v2alpha.IAlertConfig, - protos.google.cloud.retail.v2alpha.IUpdateAlertConfigRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.retail.v2alpha.IUpdateAlertConfigRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.retail.v2alpha.IAlertConfig, + | protos.google.cloud.retail.v2alpha.IUpdateAlertConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IAlertConfig, + protos.google.cloud.retail.v2alpha.IUpdateAlertConfigRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'alert_config.name': request.alertConfig!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'alert_config.name': request.alertConfig!.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateAlertConfig request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.retail.v2alpha.IAlertConfig, - protos.google.cloud.retail.v2alpha.IUpdateAlertConfigRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.retail.v2alpha.IAlertConfig, + | protos.google.cloud.retail.v2alpha.IUpdateAlertConfigRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateAlertConfig response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.updateAlertConfig(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.retail.v2alpha.IAlertConfig, - protos.google.cloud.retail.v2alpha.IUpdateAlertConfigRequest|undefined, {}|undefined - ]) => { - this._log.info('updateAlertConfig response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateAlertConfig(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.retail.v2alpha.IAlertConfig, + ( + | protos.google.cloud.retail.v2alpha.IUpdateAlertConfigRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('updateAlertConfig response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * The method enrolls a solution of type [Retail - * Search][google.cloud.retail.v2alpha.SolutionType.SOLUTION_TYPE_SEARCH] - * into a project. - * - * The [Recommendations AI solution - * type][google.cloud.retail.v2alpha.SolutionType.SOLUTION_TYPE_RECOMMENDATION] - * is enrolled by default when your project enables Retail API, so you don't - * need to call the enrollSolution method for recommendations. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.project - * Required. Full resource name of parent. Format: - * `projects/{project_number_or_id}` - * @param {google.cloud.retail.v2alpha.SolutionType} request.solution - * Required. Solution to enroll. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing - * a long running operation. Its `promise()` method returns a promise - * you can `await` for. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/project_service.enroll_solution.js - * region_tag:retail_v2alpha_generated_ProjectService_EnrollSolution_async - */ + /** + * The method enrolls a solution of type [Retail + * Search][google.cloud.retail.v2alpha.SolutionType.SOLUTION_TYPE_SEARCH] + * into a project. + * + * The [Recommendations AI solution + * type][google.cloud.retail.v2alpha.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + * is enrolled by default when your project enables Retail API, so you don't + * need to call the enrollSolution method for recommendations. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.project + * Required. Full resource name of parent. Format: + * `projects/{project_number_or_id}` + * @param {google.cloud.retail.v2alpha.SolutionType} request.solution + * Required. Solution to enroll. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/project_service.enroll_solution.js + * region_tag:retail_v2alpha_generated_ProjectService_EnrollSolution_async + */ enrollSolution( - request?: protos.google.cloud.retail.v2alpha.IEnrollSolutionRequest, - options?: CallOptions): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.IEnrollSolutionRequest, + options?: CallOptions, + ): Promise< + [ + LROperation< + protos.google.cloud.retail.v2alpha.IEnrollSolutionResponse, + protos.google.cloud.retail.v2alpha.IEnrollSolutionMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; enrollSolution( - request: protos.google.cloud.retail.v2alpha.IEnrollSolutionRequest, - options: CallOptions, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IEnrollSolutionRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IEnrollSolutionResponse, + protos.google.cloud.retail.v2alpha.IEnrollSolutionMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; enrollSolution( - request: protos.google.cloud.retail.v2alpha.IEnrollSolutionRequest, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IEnrollSolutionRequest, + callback: Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IEnrollSolutionResponse, + protos.google.cloud.retail.v2alpha.IEnrollSolutionMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; enrollSolution( - request?: protos.google.cloud.retail.v2alpha.IEnrollSolutionRequest, - optionsOrCallback?: CallOptions|Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>, - callback?: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>|void { + request?: protos.google.cloud.retail.v2alpha.IEnrollSolutionRequest, + optionsOrCallback?: + | CallOptions + | Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IEnrollSolutionResponse, + protos.google.cloud.retail.v2alpha.IEnrollSolutionMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + callback?: Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IEnrollSolutionResponse, + protos.google.cloud.retail.v2alpha.IEnrollSolutionMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + LROperation< + protos.google.cloud.retail.v2alpha.IEnrollSolutionResponse, + protos.google.cloud.retail.v2alpha.IEnrollSolutionMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'project': request.project ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + project: request.project ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IEnrollSolutionResponse, + protos.google.cloud.retail.v2alpha.IEnrollSolutionMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, rawResponse, _) => { this._log.info('enrollSolution response %j', rawResponse); callback!(error, response, rawResponse, _); // We verified `callback` above. } : undefined; this._log.info('enrollSolution request %j', request); - return this.innerApiCalls.enrollSolution(request, options, wrappedCallback) - ?.then(([response, rawResponse, _]: [ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]) => { - this._log.info('enrollSolution response %j', rawResponse); - return [response, rawResponse, _]; - }); + return this.innerApiCalls + .enrollSolution(request, options, wrappedCallback) + ?.then( + ([response, rawResponse, _]: [ + LROperation< + protos.google.cloud.retail.v2alpha.IEnrollSolutionResponse, + protos.google.cloud.retail.v2alpha.IEnrollSolutionMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ]) => { + this._log.info('enrollSolution response %j', rawResponse); + return [response, rawResponse, _]; + }, + ); } -/** - * Check the status of the long running operation returned by `enrollSolution()`. - * @param {String} name - * The operation name that will be passed. - * @returns {Promise} - The promise which resolves to an object. - * The decoded operation object has result and metadata field to get information from. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/project_service.enroll_solution.js - * region_tag:retail_v2alpha_generated_ProjectService_EnrollSolution_async - */ - async checkEnrollSolutionProgress(name: string): Promise>{ + /** + * Check the status of the long running operation returned by `enrollSolution()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/project_service.enroll_solution.js + * region_tag:retail_v2alpha_generated_ProjectService_EnrollSolution_async + */ + async checkEnrollSolutionProgress( + name: string, + ): Promise< + LROperation< + protos.google.cloud.retail.v2alpha.EnrollSolutionResponse, + protos.google.cloud.retail.v2alpha.EnrollSolutionMetadata + > + > { this._log.info('enrollSolution long-running'); - const request = new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest({name}); + const request = + new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( + { name }, + ); const [operation] = await this.operationsClient.getOperation(request); - const decodeOperation = new this._gaxModule.Operation(operation, this.descriptors.longrunning.enrollSolution, this._gaxModule.createDefaultBackoffSettings()); - return decodeOperation as LROperation; + const decodeOperation = new this._gaxModule.Operation( + operation, + this.descriptors.longrunning.enrollSolution, + this._gaxModule.createDefaultBackoffSettings(), + ); + return decodeOperation as LROperation< + protos.google.cloud.retail.v2alpha.EnrollSolutionResponse, + protos.google.cloud.retail.v2alpha.EnrollSolutionMetadata + >; } // -------------------- // -- Path templates -- @@ -1231,7 +1671,7 @@ export class ProjectServiceClient { * @param {string} project * @returns {string} Resource name string. */ - alertConfigPath(project:string) { + alertConfigPath(project: string) { return this.pathTemplates.alertConfigPathTemplate.render({ project: project, }); @@ -1245,7 +1685,8 @@ export class ProjectServiceClient { * @returns {string} A string representing the project. */ matchProjectFromAlertConfigName(alertConfigName: string) { - return this.pathTemplates.alertConfigPathTemplate.match(alertConfigName).project; + return this.pathTemplates.alertConfigPathTemplate.match(alertConfigName) + .project; } /** @@ -1256,7 +1697,7 @@ export class ProjectServiceClient { * @param {string} catalog * @returns {string} Resource name string. */ - attributesConfigPath(project:string,location:string,catalog:string) { + attributesConfigPath(project: string, location: string, catalog: string) { return this.pathTemplates.attributesConfigPathTemplate.render({ project: project, location: location, @@ -1272,7 +1713,9 @@ export class ProjectServiceClient { * @returns {string} A string representing the project. */ matchProjectFromAttributesConfigName(attributesConfigName: string) { - return this.pathTemplates.attributesConfigPathTemplate.match(attributesConfigName).project; + return this.pathTemplates.attributesConfigPathTemplate.match( + attributesConfigName, + ).project; } /** @@ -1283,7 +1726,9 @@ export class ProjectServiceClient { * @returns {string} A string representing the location. */ matchLocationFromAttributesConfigName(attributesConfigName: string) { - return this.pathTemplates.attributesConfigPathTemplate.match(attributesConfigName).location; + return this.pathTemplates.attributesConfigPathTemplate.match( + attributesConfigName, + ).location; } /** @@ -1294,7 +1739,9 @@ export class ProjectServiceClient { * @returns {string} A string representing the catalog. */ matchCatalogFromAttributesConfigName(attributesConfigName: string) { - return this.pathTemplates.attributesConfigPathTemplate.match(attributesConfigName).catalog; + return this.pathTemplates.attributesConfigPathTemplate.match( + attributesConfigName, + ).catalog; } /** @@ -1306,7 +1753,12 @@ export class ProjectServiceClient { * @param {string} branch * @returns {string} Resource name string. */ - branchPath(project:string,location:string,catalog:string,branch:string) { + branchPath( + project: string, + location: string, + catalog: string, + branch: string, + ) { return this.pathTemplates.branchPathTemplate.render({ project: project, location: location, @@ -1367,7 +1819,7 @@ export class ProjectServiceClient { * @param {string} catalog * @returns {string} Resource name string. */ - catalogPath(project:string,location:string,catalog:string) { + catalogPath(project: string, location: string, catalog: string) { return this.pathTemplates.catalogPathTemplate.render({ project: project, location: location, @@ -1416,7 +1868,7 @@ export class ProjectServiceClient { * @param {string} catalog * @returns {string} Resource name string. */ - completionConfigPath(project:string,location:string,catalog:string) { + completionConfigPath(project: string, location: string, catalog: string) { return this.pathTemplates.completionConfigPathTemplate.render({ project: project, location: location, @@ -1432,7 +1884,9 @@ export class ProjectServiceClient { * @returns {string} A string representing the project. */ matchProjectFromCompletionConfigName(completionConfigName: string) { - return this.pathTemplates.completionConfigPathTemplate.match(completionConfigName).project; + return this.pathTemplates.completionConfigPathTemplate.match( + completionConfigName, + ).project; } /** @@ -1443,7 +1897,9 @@ export class ProjectServiceClient { * @returns {string} A string representing the location. */ matchLocationFromCompletionConfigName(completionConfigName: string) { - return this.pathTemplates.completionConfigPathTemplate.match(completionConfigName).location; + return this.pathTemplates.completionConfigPathTemplate.match( + completionConfigName, + ).location; } /** @@ -1454,7 +1910,9 @@ export class ProjectServiceClient { * @returns {string} A string representing the catalog. */ matchCatalogFromCompletionConfigName(completionConfigName: string) { - return this.pathTemplates.completionConfigPathTemplate.match(completionConfigName).catalog; + return this.pathTemplates.completionConfigPathTemplate.match( + completionConfigName, + ).catalog; } /** @@ -1466,7 +1924,12 @@ export class ProjectServiceClient { * @param {string} control * @returns {string} Resource name string. */ - controlPath(project:string,location:string,catalog:string,control:string) { + controlPath( + project: string, + location: string, + catalog: string, + control: string, + ) { return this.pathTemplates.controlPathTemplate.render({ project: project, location: location, @@ -1525,7 +1988,7 @@ export class ProjectServiceClient { * @param {string} project * @returns {string} Resource name string. */ - loggingConfigPath(project:string) { + loggingConfigPath(project: string) { return this.pathTemplates.loggingConfigPathTemplate.render({ project: project, }); @@ -1539,7 +2002,8 @@ export class ProjectServiceClient { * @returns {string} A string representing the project. */ matchProjectFromLoggingConfigName(loggingConfigName: string) { - return this.pathTemplates.loggingConfigPathTemplate.match(loggingConfigName).project; + return this.pathTemplates.loggingConfigPathTemplate.match(loggingConfigName) + .project; } /** @@ -1551,7 +2015,12 @@ export class ProjectServiceClient { * @param {string} merchant_center_account_link * @returns {string} Resource name string. */ - merchantCenterAccountLinkPath(project:string,location:string,catalog:string,merchantCenterAccountLink:string) { + merchantCenterAccountLinkPath( + project: string, + location: string, + catalog: string, + merchantCenterAccountLink: string, + ) { return this.pathTemplates.merchantCenterAccountLinkPathTemplate.render({ project: project, location: location, @@ -1567,8 +2036,12 @@ export class ProjectServiceClient { * A fully-qualified path representing MerchantCenterAccountLink resource. * @returns {string} A string representing the project. */ - matchProjectFromMerchantCenterAccountLinkName(merchantCenterAccountLinkName: string) { - return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match(merchantCenterAccountLinkName).project; + matchProjectFromMerchantCenterAccountLinkName( + merchantCenterAccountLinkName: string, + ) { + return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match( + merchantCenterAccountLinkName, + ).project; } /** @@ -1578,8 +2051,12 @@ export class ProjectServiceClient { * A fully-qualified path representing MerchantCenterAccountLink resource. * @returns {string} A string representing the location. */ - matchLocationFromMerchantCenterAccountLinkName(merchantCenterAccountLinkName: string) { - return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match(merchantCenterAccountLinkName).location; + matchLocationFromMerchantCenterAccountLinkName( + merchantCenterAccountLinkName: string, + ) { + return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match( + merchantCenterAccountLinkName, + ).location; } /** @@ -1589,8 +2066,12 @@ export class ProjectServiceClient { * A fully-qualified path representing MerchantCenterAccountLink resource. * @returns {string} A string representing the catalog. */ - matchCatalogFromMerchantCenterAccountLinkName(merchantCenterAccountLinkName: string) { - return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match(merchantCenterAccountLinkName).catalog; + matchCatalogFromMerchantCenterAccountLinkName( + merchantCenterAccountLinkName: string, + ) { + return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match( + merchantCenterAccountLinkName, + ).catalog; } /** @@ -1600,8 +2081,12 @@ export class ProjectServiceClient { * A fully-qualified path representing MerchantCenterAccountLink resource. * @returns {string} A string representing the merchant_center_account_link. */ - matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName(merchantCenterAccountLinkName: string) { - return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match(merchantCenterAccountLinkName).merchant_center_account_link; + matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName( + merchantCenterAccountLinkName: string, + ) { + return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match( + merchantCenterAccountLinkName, + ).merchant_center_account_link; } /** @@ -1613,7 +2098,7 @@ export class ProjectServiceClient { * @param {string} model * @returns {string} Resource name string. */ - modelPath(project:string,location:string,catalog:string,model:string) { + modelPath(project: string, location: string, catalog: string, model: string) { return this.pathTemplates.modelPathTemplate.render({ project: project, location: location, @@ -1676,7 +2161,13 @@ export class ProjectServiceClient { * @param {string} product * @returns {string} Resource name string. */ - productPath(project:string,location:string,catalog:string,branch:string,product:string) { + productPath( + project: string, + location: string, + catalog: string, + branch: string, + product: string, + ) { return this.pathTemplates.productPathTemplate.render({ project: project, location: location, @@ -1747,7 +2238,7 @@ export class ProjectServiceClient { * @param {string} project * @returns {string} Resource name string. */ - projectPath(project:string) { + projectPath(project: string) { return this.pathTemplates.projectPathTemplate.render({ project: project, }); @@ -1770,7 +2261,7 @@ export class ProjectServiceClient { * @param {string} project * @returns {string} Resource name string. */ - retailProjectPath(project:string) { + retailProjectPath(project: string) { return this.pathTemplates.retailProjectPathTemplate.render({ project: project, }); @@ -1784,7 +2275,8 @@ export class ProjectServiceClient { * @returns {string} A string representing the project. */ matchProjectFromRetailProjectName(retailProjectName: string) { - return this.pathTemplates.retailProjectPathTemplate.match(retailProjectName).project; + return this.pathTemplates.retailProjectPathTemplate.match(retailProjectName) + .project; } /** @@ -1796,7 +2288,12 @@ export class ProjectServiceClient { * @param {string} serving_config * @returns {string} Resource name string. */ - servingConfigPath(project:string,location:string,catalog:string,servingConfig:string) { + servingConfigPath( + project: string, + location: string, + catalog: string, + servingConfig: string, + ) { return this.pathTemplates.servingConfigPathTemplate.render({ project: project, location: location, @@ -1813,7 +2310,8 @@ export class ProjectServiceClient { * @returns {string} A string representing the project. */ matchProjectFromServingConfigName(servingConfigName: string) { - return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName).project; + return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName) + .project; } /** @@ -1824,7 +2322,8 @@ export class ProjectServiceClient { * @returns {string} A string representing the location. */ matchLocationFromServingConfigName(servingConfigName: string) { - return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName).location; + return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName) + .location; } /** @@ -1835,7 +2334,8 @@ export class ProjectServiceClient { * @returns {string} A string representing the catalog. */ matchCatalogFromServingConfigName(servingConfigName: string) { - return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName).catalog; + return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName) + .catalog; } /** @@ -1846,7 +2346,8 @@ export class ProjectServiceClient { * @returns {string} A string representing the serving_config. */ matchServingConfigFromServingConfigName(servingConfigName: string) { - return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName).serving_config; + return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName) + .serving_config; } /** @@ -1857,7 +2358,7 @@ export class ProjectServiceClient { */ close(): Promise { if (this.projectServiceStub && !this._terminated) { - return this.projectServiceStub.then(stub => { + return this.projectServiceStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -1866,4 +2367,4 @@ export class ProjectServiceClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/src/v2alpha/search_service_client.ts.baseline b/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/src/v2alpha/search_service_client.ts.baseline index c4d120af3ba1..e0b13abe0251 100644 --- a/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/src/v2alpha/search_service_client.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/src/v2alpha/search_service_client.ts.baseline @@ -18,15 +18,22 @@ /* global window */ import * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions, PaginationCallback, GaxCall} from 'google-gax'; -import {Transform} from 'stream'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + PaginationCallback, + GaxCall, +} from 'google-gax'; +import { Transform } from 'stream'; // @ts-ignore import type * as protos from '../../../protos/protos.js'; import * as search_service_client_config from './search_service_client_config.json'; import fs from 'fs'; import path from 'path'; -import {fileURLToPath} from 'url'; -import {getJSON} from '../json-helper.cjs'; +import { fileURLToPath } from 'url'; +import { getJSON } from '../json-helper.cjs'; // @ts-ignore const dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -36,15 +43,15 @@ const dirname = path.dirname(fileURLToPath(import.meta.url)); * This file defines retry strategy and timeouts for all API methods in this library. */ const gapicConfig = getJSON( - path.join(dirname, 'search_service_client_config.json') + path.join(dirname, 'search_service_client_config.json'), ); const jsonProtos = getJSON( - path.join(dirname, '..', '..', '..', 'protos/protos.json') + path.join(dirname, '..', '..', '..', 'protos/protos.json'), ); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; const version = getJSON( - path.join(dirname, '..', '..', '..', '..', 'package.json') + path.join(dirname, '..', '..', '..', '..', 'package.json'), ).version; /** @@ -62,7 +69,7 @@ export class SearchServiceClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('retail'); @@ -74,9 +81,9 @@ export class SearchServiceClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; - searchServiceStub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; + searchServiceStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of SearchServiceClient. @@ -118,21 +125,42 @@ export class SearchServiceClient { * const client = new SearchServiceClient({fallback: 'rest'}, gax); * ``` */ - constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { // Ensure that options include all the required fields. const staticMembers = this.constructor as typeof SearchServiceClient; - if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { - throw new Error('Please set either universe_domain or universeDomain, but not both.'); + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); } - const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; - this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; this._servicePath = 'retail.' + this._universeDomain; - const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; - const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. if (servicePath !== this._servicePath && !('scopes' in opts)) { @@ -154,7 +182,7 @@ export class SearchServiceClient { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; @@ -171,10 +199,7 @@ export class SearchServiceClient { const isEsm = true; const isEsmString = isEsm ? '-esm' : '-cjs'; // Determine the client header string. - const clientHeader = [ - `gax/${this._gaxModule.version}`, - `gapic/${version}`, - ]; + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/{process.versions.node}${isEsmString}`); } else { @@ -182,7 +207,7 @@ export class SearchServiceClient { } if (!opts.fallback) { clientHeader.push(`grpc/${this._gaxGrpc.grpcVersion}`); - } else if (opts.fallback === 'rest' ) { + } else if (opts.fallback === 'rest') { clientHeader.push(`rest/${this._gaxGrpc.grpcVersion}`); } if (opts.libName && opts.libVersion) { @@ -190,50 +215,52 @@ export class SearchServiceClient { } // Load the applicable protos. - this._protos = this._gaxGrpc.loadProtoJSON(jsonProtos as gax.protobuf.INamespace); + this._protos = this._gaxGrpc.loadProtoJSON( + jsonProtos as gax.protobuf.INamespace, + ); // This API contains "path templates"; forward-slash-separated // identifiers to uniquely identify resources within the API. // Create useful helper objects for these. this.pathTemplates = { alertConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/alertConfig' + 'projects/{project}/alertConfig', ), attributesConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/attributesConfig' + 'projects/{project}/locations/{location}/catalogs/{catalog}/attributesConfig', ), branchPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}', ), catalogPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}' + 'projects/{project}/locations/{location}/catalogs/{catalog}', ), completionConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/completionConfig' + 'projects/{project}/locations/{location}/catalogs/{catalog}/completionConfig', ), controlPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/controls/{control}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/controls/{control}', ), experimentPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/experiments/{experiment}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/experiments/{experiment}', ), loggingConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/loggingConfig' + 'projects/{project}/loggingConfig', ), merchantCenterAccountLinkPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/merchantCenterAccountLinks/{merchant_center_account_link}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/merchantCenterAccountLinks/{merchant_center_account_link}', ), modelPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/models/{model}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/models/{model}', ), productPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}', ), retailProjectPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/retailProject' + 'projects/{project}/retailProject', ), servingConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/servingConfigs/{serving_config}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/servingConfigs/{serving_config}', ), }; @@ -241,14 +268,20 @@ export class SearchServiceClient { // (e.g. 50 results at a time, with tokens to get subsequent // pages). Denote the keys used for pagination and results. this.descriptors.page = { - search: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'results') + search: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'results', + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.cloud.retail.v2alpha.SearchService', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.cloud.retail.v2alpha.SearchService', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + { 'x-goog-api-client': clientHeader.join(' ') }, + ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -279,37 +312,40 @@ export class SearchServiceClient { // Put together the "service stub" for // google.cloud.retail.v2alpha.SearchService. this.searchServiceStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.cloud.retail.v2alpha.SearchService') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.cloud.retail.v2alpha.SearchService', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.cloud.retail.v2alpha.SearchService, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts, + this._providedCustomServicePath, + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const searchServiceStubMethods = - ['search']; + const searchServiceStubMethods = ['search']; for (const methodName of searchServiceStubMethods) { const callPromise = this.searchServiceStub.then( - stub => (...args: Array<{}>) => { - if (this._terminated) { - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error|null|undefined) => () => { + (stub) => + (...args: Array<{}>) => { + if (this._terminated) { + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { throw err; - }); + }, + ); - const descriptor = - this.descriptors.page[methodName] || - undefined; + const descriptor = this.descriptors.page[methodName] || undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -324,8 +360,14 @@ export class SearchServiceClient { * @returns {string} The DNS address for this service. */ static get servicePath() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'retail.googleapis.com'; } @@ -337,8 +379,14 @@ export class SearchServiceClient { * @returns {string} The DNS address for this service. */ static get apiEndpoint() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'retail.googleapis.com'; } @@ -369,9 +417,7 @@ export class SearchServiceClient { * @returns {string[]} List of default scopes. */ static get scopes() { - return [ - 'https://www.googleapis.com/auth/cloud-platform' - ]; + return ['https://www.googleapis.com/auth/cloud-platform']; } getProjectId(): Promise; @@ -380,8 +426,9 @@ export class SearchServiceClient { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId(callback?: Callback): - Promise|void { + getProjectId( + callback?: Callback, + ): Promise | void { if (callback) { this.auth.getProjectId(callback); return; @@ -393,384 +440,399 @@ export class SearchServiceClient { // -- Service calls -- // ------------------- - /** - * Performs a search. - * - * This feature is only available for users who have Retail Search enabled. - * Enable Retail Search on Cloud Console before using this feature. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.placement - * Required. The resource name of the Retail Search serving config, such as - * `projects/* /locations/global/catalogs/default_catalog/servingConfigs/default_serving_config` - * or the name of the legacy placement resource, such as - * `projects/* /locations/global/catalogs/default_catalog/placements/default_search`. - * This field is used to identify the serving config name and the set - * of models that are used to make the search. - * @param {string} request.branch - * The branch resource name, such as - * `projects/* /locations/global/catalogs/default_catalog/branches/0`. - * - * Use "default_branch" as the branch ID or leave this field empty, to search - * products under the default branch. - * @param {string} request.query - * Raw search query. - * - * If this field is empty, the request is considered a category browsing - * request and returned results are based on - * {@link protos.google.cloud.retail.v2alpha.SearchRequest.filter|filter} and - * {@link protos.google.cloud.retail.v2alpha.SearchRequest.page_categories|page_categories}. - * @param {string} request.visitorId - * Required. A unique identifier for tracking visitors. For example, this - * could be implemented with an HTTP cookie, which should be able to uniquely - * identify a visitor on a single device. This unique identifier should not - * change if the visitor logs in or out of the website. - * - * This should be the same identifier as - * {@link protos.google.cloud.retail.v2alpha.UserEvent.visitor_id|UserEvent.visitor_id}. - * - * The field must be a UTF-8 encoded string with a length limit of 128 - * characters. Otherwise, an INVALID_ARGUMENT error is returned. - * @param {google.cloud.retail.v2alpha.UserInfo} request.userInfo - * User information. - * @param {number} request.pageSize - * Maximum number of {@link protos.google.cloud.retail.v2alpha.Product|Product}s to - * return. If unspecified, defaults to a reasonable value. The maximum allowed - * value is 120. Values above 120 will be coerced to 120. - * - * If this field is negative, an INVALID_ARGUMENT is returned. - * @param {string} request.pageToken - * A page token - * {@link protos.google.cloud.retail.v2alpha.SearchResponse.next_page_token|SearchResponse.next_page_token}, - * received from a previous - * {@link protos.google.cloud.retail.v2alpha.SearchService.Search|SearchService.Search} - * call. Provide this to retrieve the subsequent page. - * - * When paginating, all other parameters provided to - * {@link protos.google.cloud.retail.v2alpha.SearchService.Search|SearchService.Search} - * must match the call that provided the page token. Otherwise, an - * INVALID_ARGUMENT error is returned. - * @param {number} request.offset - * A 0-indexed integer that specifies the current offset (that is, starting - * result location, amongst the - * {@link protos.google.cloud.retail.v2alpha.Product|Product}s deemed by the API as - * relevant) in search results. This field is only considered if - * {@link protos.google.cloud.retail.v2alpha.SearchRequest.page_token|page_token} is - * unset. - * - * If this field is negative, an INVALID_ARGUMENT is returned. - * @param {string} request.filter - * The filter syntax consists of an expression language for constructing a - * predicate from one or more fields of the products being filtered. Filter - * expression is case-sensitive. For more information, see - * [Filter](https://cloud.google.com/retail/docs/filter-and-order#filter). - * - * If this field is unrecognizable, an INVALID_ARGUMENT is returned. - * @param {string} request.canonicalFilter - * The default filter that is applied when a user performs a search without - * checking any filters on the search page. - * - * The filter applied to every search request when quality improvement such as - * query expansion is needed. In the case a query does not have a sufficient - * amount of results this filter will be used to determine whether or not to - * enable the query expansion flow. The original filter will still be used for - * the query expanded search. - * This field is strongly recommended to achieve high search quality. - * - * For more information about filter syntax, see - * {@link protos.google.cloud.retail.v2alpha.SearchRequest.filter|SearchRequest.filter}. - * @param {string} request.orderBy - * The order in which products are returned. Products can be ordered by - * a field in an {@link protos.google.cloud.retail.v2alpha.Product|Product} object. Leave - * it unset if ordered by relevance. OrderBy expression is case-sensitive. For - * more information, see - * [Order](https://cloud.google.com/retail/docs/filter-and-order#order). - * - * If this field is unrecognizable, an INVALID_ARGUMENT is returned. - * @param {number[]} request.facetSpecs - * Facet specifications for faceted search. If empty, no facets are returned. - * - * A maximum of 200 values are allowed. Otherwise, an INVALID_ARGUMENT error - * is returned. - * @param {google.cloud.retail.v2alpha.SearchRequest.DynamicFacetSpec} request.dynamicFacetSpec - * Deprecated. Refer to https://cloud.google.com/retail/docs/configs#dynamic - * to enable dynamic facets. Do not set this field. - * - * The specification for dynamically generated facets. Notice that only - * textual facets can be dynamically generated. - * @param {google.cloud.retail.v2alpha.SearchRequest.BoostSpec} request.boostSpec - * Boost specification to boost certain products. For more information, see - * [Boost results](https://cloud.google.com/retail/docs/boosting). - * - * Notice that if both - * {@link protos.google.cloud.retail.v2alpha.ServingConfig.boost_control_ids|ServingConfig.boost_control_ids} - * and - * {@link protos.google.cloud.retail.v2alpha.SearchRequest.boost_spec|SearchRequest.boost_spec} - * are set, the boost conditions from both places are evaluated. If a search - * request matches multiple boost conditions, the final boost score is equal - * to the sum of the boost scores from all matched boost conditions. - * @param {google.cloud.retail.v2alpha.SearchRequest.QueryExpansionSpec} request.queryExpansionSpec - * The query expansion specification that specifies the conditions under which - * query expansion occurs. For more information, see [Query - * expansion](https://cloud.google.com/retail/docs/result-size#query_expansion). - * @param {google.cloud.retail.v2alpha.SearchRequest.RelevanceThreshold} request.relevanceThreshold - * The relevance threshold of the search results. - * - * Defaults to - * {@link protos.google.cloud.retail.v2alpha.SearchRequest.RelevanceThreshold.HIGH|RelevanceThreshold.HIGH}, - * which means only the most relevant results are shown, and the least number - * of results are returned. For more information, see [Adjust result - * size](https://cloud.google.com/retail/docs/result-size#relevance_thresholding). - * @param {string[]} request.variantRollupKeys - * The keys to fetch and rollup the matching - * {@link protos.google.cloud.retail.v2alpha.Product.Type.VARIANT|variant} - * {@link protos.google.cloud.retail.v2alpha.Product|Product}s attributes, - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo|FulfillmentInfo} or - * {@link protos.google.cloud.retail.v2alpha.LocalInventory|LocalInventory}s attributes. - * The attributes from all the matching - * {@link protos.google.cloud.retail.v2alpha.Product.Type.VARIANT|variant} - * {@link protos.google.cloud.retail.v2alpha.Product|Product}s or - * {@link protos.google.cloud.retail.v2alpha.LocalInventory|LocalInventory}s are merged - * and de-duplicated. Notice that rollup attributes will lead to extra query - * latency. Maximum number of keys is 30. - * - * For {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo|FulfillmentInfo}, a - * fulfillment type and a fulfillment ID must be provided in the format of - * "fulfillmentType.fulfillmentId". E.g., in "pickupInStore.store123", - * "pickupInStore" is fulfillment type and "store123" is the store ID. - * - * Supported keys are: - * - * * colorFamilies - * * price - * * originalPrice - * * discount - * * variantId - * * inventory(place_id,price) - * * inventory(place_id,original_price) - * * inventory(place_id,attributes.key), where key is any key in the - * {@link protos.google.cloud.retail.v2alpha.LocalInventory.attributes|Product.local_inventories.attributes} - * map. - * * attributes.key, where key is any key in the - * {@link protos.google.cloud.retail.v2alpha.Product.attributes|Product.attributes} map. - * * pickupInStore.id, where id is any - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.place_ids|FulfillmentInfo.place_ids} - * for - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.type|FulfillmentInfo.type} - * "pickup-in-store". - * * shipToStore.id, where id is any - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.place_ids|FulfillmentInfo.place_ids} - * for - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.type|FulfillmentInfo.type} - * "ship-to-store". - * * sameDayDelivery.id, where id is any - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.place_ids|FulfillmentInfo.place_ids} - * for - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.type|FulfillmentInfo.type} - * "same-day-delivery". - * * nextDayDelivery.id, where id is any - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.place_ids|FulfillmentInfo.place_ids} - * for - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.type|FulfillmentInfo.type} - * "next-day-delivery". - * * customFulfillment1.id, where id is any - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.place_ids|FulfillmentInfo.place_ids} - * for - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.type|FulfillmentInfo.type} - * "custom-type-1". - * * customFulfillment2.id, where id is any - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.place_ids|FulfillmentInfo.place_ids} - * for - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.type|FulfillmentInfo.type} - * "custom-type-2". - * * customFulfillment3.id, where id is any - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.place_ids|FulfillmentInfo.place_ids} - * for - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.type|FulfillmentInfo.type} - * "custom-type-3". - * * customFulfillment4.id, where id is any - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.place_ids|FulfillmentInfo.place_ids} - * for - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.type|FulfillmentInfo.type} - * "custom-type-4". - * * customFulfillment5.id, where id is any - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.place_ids|FulfillmentInfo.place_ids} - * for - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.type|FulfillmentInfo.type} - * "custom-type-5". - * - * If this field is set to an invalid value other than these, an - * INVALID_ARGUMENT error is returned. - * @param {string[]} request.pageCategories - * The categories associated with a category page. Must be set for category - * navigation queries to achieve good search quality. The format should be - * the same as - * {@link protos.google.cloud.retail.v2alpha.UserEvent.page_categories|UserEvent.page_categories}; - * - * To represent full path of category, use '>' sign to separate different - * hierarchies. If '>' is part of the category name, replace it with - * other character(s). - * - * Category pages include special pages such as sales or promotions. For - * instance, a special sale page may have the category hierarchy: - * "pageCategories" : ["Sales > 2017 Black Friday Deals"]. - * @param {google.cloud.retail.v2alpha.SearchRequest.SearchMode} request.searchMode - * The search mode of the search request. If not specified, a single search - * request triggers both product search and faceted search. - * @param {google.cloud.retail.v2alpha.SearchRequest.PersonalizationSpec} request.personalizationSpec - * The specification for personalization. - * - * Notice that if both - * {@link protos.google.cloud.retail.v2alpha.ServingConfig.personalization_spec|ServingConfig.personalization_spec} - * and - * {@link protos.google.cloud.retail.v2alpha.SearchRequest.personalization_spec|SearchRequest.personalization_spec} - * are set. - * {@link protos.google.cloud.retail.v2alpha.SearchRequest.personalization_spec|SearchRequest.personalization_spec} - * will override - * {@link protos.google.cloud.retail.v2alpha.ServingConfig.personalization_spec|ServingConfig.personalization_spec}. - * @param {number[]} request.labels - * The labels applied to a resource must meet the following requirements: - * - * * Each resource can have multiple labels, up to a maximum of 64. - * * Each label must be a key-value pair. - * * Keys have a minimum length of 1 character and a maximum length of 63 - * characters and cannot be empty. Values can be empty and have a maximum - * length of 63 characters. - * * Keys and values can contain only lowercase letters, numeric characters, - * underscores, and dashes. All characters must use UTF-8 encoding, and - * international characters are allowed. - * * The key portion of a label must be unique. However, you can use the same - * key with multiple resources. - * * Keys must start with a lowercase letter or international character. - * - * For more information, see [Requirements for - * labels](https://cloud.google.com/resource-manager/docs/creating-managing-labels#requirements) - * in the Resource Manager documentation. - * @param {google.cloud.retail.v2alpha.SearchRequest.SpellCorrectionSpec} request.spellCorrectionSpec - * The spell correction specification that specifies the mode under - * which spell correction will take effect. - * @param {string} request.entity - * The entity for customers that may run multiple different entities, domains, - * sites or regions, for example, `Google US`, `Google Ads`, `Waymo`, - * `google.com`, `youtube.com`, etc. - * If this is set, it should be exactly matched with - * {@link protos.google.cloud.retail.v2alpha.UserEvent.entity|UserEvent.entity} to get - * search results boosted by entity. - * @param {google.cloud.retail.v2alpha.SearchRequest.ConversationalSearchSpec} [request.conversationalSearchSpec] - * Optional. This field specifies all conversational related parameters - * addition to traditional retail search. - * @param {google.cloud.retail.v2alpha.SearchRequest.TileNavigationSpec} [request.tileNavigationSpec] - * Optional. This field specifies tile navigation related parameters. - * @param {string} [request.languageCode] - * Optional. The BCP-47 language code, such as "en-US" or "sr-Latn" - * [list](https://www.unicode.org/cldr/charts/46/summary/root.html). For more - * information, see [Standardized codes](https://google.aip.dev/143). This - * field helps to better interpret the query. If a value isn't specified, the - * query language code is automatically detected, which may not be accurate. - * @param {string} [request.regionCode] - * Optional. The Unicode country/region code (CLDR) of a location, such as - * "US" and "419" - * [list](https://www.unicode.org/cldr/charts/46/supplemental/territory_information.html). - * For more information, see [Standardized codes](https://google.aip.dev/143). - * If set, then results will be boosted based on the region_code provided. - * @param {string} [request.placeId] - * Optional. An id corresponding to a place, such as a store id or region id. - * When specified, we use the price from the local inventory with the matching - * product's - * {@link protos.google.cloud.retail.v2alpha.LocalInventory.place_id|LocalInventory.place_id} - * for revenue optimization. - * @param {number[]} [request.userAttributes] - * Optional. The user attributes that could be used for personalization of - * search results. - * * Populate at most 100 key-value pairs per query. - * * Only supports string keys and repeated string values. - * * Duplcate keys are not allowed within a single query. - * - * Example: - * user_attributes: [ - * { key: "pets" - * value { - * values: "dog" - * values: "cat" - * } - * }, - * { key: "state" - * value { - * values: "CA" - * } - * } - * ] - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.cloud.retail.v2alpha.SearchResponse.SearchResult|SearchResult}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `searchAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Performs a search. + * + * This feature is only available for users who have Retail Search enabled. + * Enable Retail Search on Cloud Console before using this feature. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.placement + * Required. The resource name of the Retail Search serving config, such as + * `projects/* /locations/global/catalogs/default_catalog/servingConfigs/default_serving_config` + * or the name of the legacy placement resource, such as + * `projects/* /locations/global/catalogs/default_catalog/placements/default_search`. + * This field is used to identify the serving config name and the set + * of models that are used to make the search. + * @param {string} request.branch + * The branch resource name, such as + * `projects/* /locations/global/catalogs/default_catalog/branches/0`. + * + * Use "default_branch" as the branch ID or leave this field empty, to search + * products under the default branch. + * @param {string} request.query + * Raw search query. + * + * If this field is empty, the request is considered a category browsing + * request and returned results are based on + * {@link protos.google.cloud.retail.v2alpha.SearchRequest.filter|filter} and + * {@link protos.google.cloud.retail.v2alpha.SearchRequest.page_categories|page_categories}. + * @param {string} request.visitorId + * Required. A unique identifier for tracking visitors. For example, this + * could be implemented with an HTTP cookie, which should be able to uniquely + * identify a visitor on a single device. This unique identifier should not + * change if the visitor logs in or out of the website. + * + * This should be the same identifier as + * {@link protos.google.cloud.retail.v2alpha.UserEvent.visitor_id|UserEvent.visitor_id}. + * + * The field must be a UTF-8 encoded string with a length limit of 128 + * characters. Otherwise, an INVALID_ARGUMENT error is returned. + * @param {google.cloud.retail.v2alpha.UserInfo} request.userInfo + * User information. + * @param {number} request.pageSize + * Maximum number of {@link protos.google.cloud.retail.v2alpha.Product|Product}s to + * return. If unspecified, defaults to a reasonable value. The maximum allowed + * value is 120. Values above 120 will be coerced to 120. + * + * If this field is negative, an INVALID_ARGUMENT is returned. + * @param {string} request.pageToken + * A page token + * {@link protos.google.cloud.retail.v2alpha.SearchResponse.next_page_token|SearchResponse.next_page_token}, + * received from a previous + * {@link protos.google.cloud.retail.v2alpha.SearchService.Search|SearchService.Search} + * call. Provide this to retrieve the subsequent page. + * + * When paginating, all other parameters provided to + * {@link protos.google.cloud.retail.v2alpha.SearchService.Search|SearchService.Search} + * must match the call that provided the page token. Otherwise, an + * INVALID_ARGUMENT error is returned. + * @param {number} request.offset + * A 0-indexed integer that specifies the current offset (that is, starting + * result location, amongst the + * {@link protos.google.cloud.retail.v2alpha.Product|Product}s deemed by the API as + * relevant) in search results. This field is only considered if + * {@link protos.google.cloud.retail.v2alpha.SearchRequest.page_token|page_token} is + * unset. + * + * If this field is negative, an INVALID_ARGUMENT is returned. + * @param {string} request.filter + * The filter syntax consists of an expression language for constructing a + * predicate from one or more fields of the products being filtered. Filter + * expression is case-sensitive. For more information, see + * [Filter](https://cloud.google.com/retail/docs/filter-and-order#filter). + * + * If this field is unrecognizable, an INVALID_ARGUMENT is returned. + * @param {string} request.canonicalFilter + * The default filter that is applied when a user performs a search without + * checking any filters on the search page. + * + * The filter applied to every search request when quality improvement such as + * query expansion is needed. In the case a query does not have a sufficient + * amount of results this filter will be used to determine whether or not to + * enable the query expansion flow. The original filter will still be used for + * the query expanded search. + * This field is strongly recommended to achieve high search quality. + * + * For more information about filter syntax, see + * {@link protos.google.cloud.retail.v2alpha.SearchRequest.filter|SearchRequest.filter}. + * @param {string} request.orderBy + * The order in which products are returned. Products can be ordered by + * a field in an {@link protos.google.cloud.retail.v2alpha.Product|Product} object. Leave + * it unset if ordered by relevance. OrderBy expression is case-sensitive. For + * more information, see + * [Order](https://cloud.google.com/retail/docs/filter-and-order#order). + * + * If this field is unrecognizable, an INVALID_ARGUMENT is returned. + * @param {number[]} request.facetSpecs + * Facet specifications for faceted search. If empty, no facets are returned. + * + * A maximum of 200 values are allowed. Otherwise, an INVALID_ARGUMENT error + * is returned. + * @param {google.cloud.retail.v2alpha.SearchRequest.DynamicFacetSpec} request.dynamicFacetSpec + * Deprecated. Refer to https://cloud.google.com/retail/docs/configs#dynamic + * to enable dynamic facets. Do not set this field. + * + * The specification for dynamically generated facets. Notice that only + * textual facets can be dynamically generated. + * @param {google.cloud.retail.v2alpha.SearchRequest.BoostSpec} request.boostSpec + * Boost specification to boost certain products. For more information, see + * [Boost results](https://cloud.google.com/retail/docs/boosting). + * + * Notice that if both + * {@link protos.google.cloud.retail.v2alpha.ServingConfig.boost_control_ids|ServingConfig.boost_control_ids} + * and + * {@link protos.google.cloud.retail.v2alpha.SearchRequest.boost_spec|SearchRequest.boost_spec} + * are set, the boost conditions from both places are evaluated. If a search + * request matches multiple boost conditions, the final boost score is equal + * to the sum of the boost scores from all matched boost conditions. + * @param {google.cloud.retail.v2alpha.SearchRequest.QueryExpansionSpec} request.queryExpansionSpec + * The query expansion specification that specifies the conditions under which + * query expansion occurs. For more information, see [Query + * expansion](https://cloud.google.com/retail/docs/result-size#query_expansion). + * @param {google.cloud.retail.v2alpha.SearchRequest.RelevanceThreshold} request.relevanceThreshold + * The relevance threshold of the search results. + * + * Defaults to + * {@link protos.google.cloud.retail.v2alpha.SearchRequest.RelevanceThreshold.HIGH|RelevanceThreshold.HIGH}, + * which means only the most relevant results are shown, and the least number + * of results are returned. For more information, see [Adjust result + * size](https://cloud.google.com/retail/docs/result-size#relevance_thresholding). + * @param {string[]} request.variantRollupKeys + * The keys to fetch and rollup the matching + * {@link protos.google.cloud.retail.v2alpha.Product.Type.VARIANT|variant} + * {@link protos.google.cloud.retail.v2alpha.Product|Product}s attributes, + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo|FulfillmentInfo} or + * {@link protos.google.cloud.retail.v2alpha.LocalInventory|LocalInventory}s attributes. + * The attributes from all the matching + * {@link protos.google.cloud.retail.v2alpha.Product.Type.VARIANT|variant} + * {@link protos.google.cloud.retail.v2alpha.Product|Product}s or + * {@link protos.google.cloud.retail.v2alpha.LocalInventory|LocalInventory}s are merged + * and de-duplicated. Notice that rollup attributes will lead to extra query + * latency. Maximum number of keys is 30. + * + * For {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo|FulfillmentInfo}, a + * fulfillment type and a fulfillment ID must be provided in the format of + * "fulfillmentType.fulfillmentId". E.g., in "pickupInStore.store123", + * "pickupInStore" is fulfillment type and "store123" is the store ID. + * + * Supported keys are: + * + * * colorFamilies + * * price + * * originalPrice + * * discount + * * variantId + * * inventory(place_id,price) + * * inventory(place_id,original_price) + * * inventory(place_id,attributes.key), where key is any key in the + * {@link protos.google.cloud.retail.v2alpha.LocalInventory.attributes|Product.local_inventories.attributes} + * map. + * * attributes.key, where key is any key in the + * {@link protos.google.cloud.retail.v2alpha.Product.attributes|Product.attributes} map. + * * pickupInStore.id, where id is any + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.place_ids|FulfillmentInfo.place_ids} + * for + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.type|FulfillmentInfo.type} + * "pickup-in-store". + * * shipToStore.id, where id is any + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.place_ids|FulfillmentInfo.place_ids} + * for + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.type|FulfillmentInfo.type} + * "ship-to-store". + * * sameDayDelivery.id, where id is any + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.place_ids|FulfillmentInfo.place_ids} + * for + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.type|FulfillmentInfo.type} + * "same-day-delivery". + * * nextDayDelivery.id, where id is any + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.place_ids|FulfillmentInfo.place_ids} + * for + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.type|FulfillmentInfo.type} + * "next-day-delivery". + * * customFulfillment1.id, where id is any + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.place_ids|FulfillmentInfo.place_ids} + * for + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.type|FulfillmentInfo.type} + * "custom-type-1". + * * customFulfillment2.id, where id is any + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.place_ids|FulfillmentInfo.place_ids} + * for + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.type|FulfillmentInfo.type} + * "custom-type-2". + * * customFulfillment3.id, where id is any + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.place_ids|FulfillmentInfo.place_ids} + * for + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.type|FulfillmentInfo.type} + * "custom-type-3". + * * customFulfillment4.id, where id is any + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.place_ids|FulfillmentInfo.place_ids} + * for + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.type|FulfillmentInfo.type} + * "custom-type-4". + * * customFulfillment5.id, where id is any + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.place_ids|FulfillmentInfo.place_ids} + * for + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.type|FulfillmentInfo.type} + * "custom-type-5". + * + * If this field is set to an invalid value other than these, an + * INVALID_ARGUMENT error is returned. + * @param {string[]} request.pageCategories + * The categories associated with a category page. Must be set for category + * navigation queries to achieve good search quality. The format should be + * the same as + * {@link protos.google.cloud.retail.v2alpha.UserEvent.page_categories|UserEvent.page_categories}; + * + * To represent full path of category, use '>' sign to separate different + * hierarchies. If '>' is part of the category name, replace it with + * other character(s). + * + * Category pages include special pages such as sales or promotions. For + * instance, a special sale page may have the category hierarchy: + * "pageCategories" : ["Sales > 2017 Black Friday Deals"]. + * @param {google.cloud.retail.v2alpha.SearchRequest.SearchMode} request.searchMode + * The search mode of the search request. If not specified, a single search + * request triggers both product search and faceted search. + * @param {google.cloud.retail.v2alpha.SearchRequest.PersonalizationSpec} request.personalizationSpec + * The specification for personalization. + * + * Notice that if both + * {@link protos.google.cloud.retail.v2alpha.ServingConfig.personalization_spec|ServingConfig.personalization_spec} + * and + * {@link protos.google.cloud.retail.v2alpha.SearchRequest.personalization_spec|SearchRequest.personalization_spec} + * are set. + * {@link protos.google.cloud.retail.v2alpha.SearchRequest.personalization_spec|SearchRequest.personalization_spec} + * will override + * {@link protos.google.cloud.retail.v2alpha.ServingConfig.personalization_spec|ServingConfig.personalization_spec}. + * @param {number[]} request.labels + * The labels applied to a resource must meet the following requirements: + * + * * Each resource can have multiple labels, up to a maximum of 64. + * * Each label must be a key-value pair. + * * Keys have a minimum length of 1 character and a maximum length of 63 + * characters and cannot be empty. Values can be empty and have a maximum + * length of 63 characters. + * * Keys and values can contain only lowercase letters, numeric characters, + * underscores, and dashes. All characters must use UTF-8 encoding, and + * international characters are allowed. + * * The key portion of a label must be unique. However, you can use the same + * key with multiple resources. + * * Keys must start with a lowercase letter or international character. + * + * For more information, see [Requirements for + * labels](https://cloud.google.com/resource-manager/docs/creating-managing-labels#requirements) + * in the Resource Manager documentation. + * @param {google.cloud.retail.v2alpha.SearchRequest.SpellCorrectionSpec} request.spellCorrectionSpec + * The spell correction specification that specifies the mode under + * which spell correction will take effect. + * @param {string} request.entity + * The entity for customers that may run multiple different entities, domains, + * sites or regions, for example, `Google US`, `Google Ads`, `Waymo`, + * `google.com`, `youtube.com`, etc. + * If this is set, it should be exactly matched with + * {@link protos.google.cloud.retail.v2alpha.UserEvent.entity|UserEvent.entity} to get + * search results boosted by entity. + * @param {google.cloud.retail.v2alpha.SearchRequest.ConversationalSearchSpec} [request.conversationalSearchSpec] + * Optional. This field specifies all conversational related parameters + * addition to traditional retail search. + * @param {google.cloud.retail.v2alpha.SearchRequest.TileNavigationSpec} [request.tileNavigationSpec] + * Optional. This field specifies tile navigation related parameters. + * @param {string} [request.languageCode] + * Optional. The BCP-47 language code, such as "en-US" or "sr-Latn" + * [list](https://www.unicode.org/cldr/charts/46/summary/root.html). For more + * information, see [Standardized codes](https://google.aip.dev/143). This + * field helps to better interpret the query. If a value isn't specified, the + * query language code is automatically detected, which may not be accurate. + * @param {string} [request.regionCode] + * Optional. The Unicode country/region code (CLDR) of a location, such as + * "US" and "419" + * [list](https://www.unicode.org/cldr/charts/46/supplemental/territory_information.html). + * For more information, see [Standardized codes](https://google.aip.dev/143). + * If set, then results will be boosted based on the region_code provided. + * @param {string} [request.placeId] + * Optional. An id corresponding to a place, such as a store id or region id. + * When specified, we use the price from the local inventory with the matching + * product's + * {@link protos.google.cloud.retail.v2alpha.LocalInventory.place_id|LocalInventory.place_id} + * for revenue optimization. + * @param {number[]} [request.userAttributes] + * Optional. The user attributes that could be used for personalization of + * search results. + * * Populate at most 100 key-value pairs per query. + * * Only supports string keys and repeated string values. + * * Duplcate keys are not allowed within a single query. + * + * Example: + * user_attributes: [ + * { key: "pets" + * value { + * values: "dog" + * values: "cat" + * } + * }, + * { key: "state" + * value { + * values: "CA" + * } + * } + * ] + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.cloud.retail.v2alpha.SearchResponse.SearchResult|SearchResult}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `searchAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ search( - request?: protos.google.cloud.retail.v2alpha.ISearchRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.retail.v2alpha.SearchResponse.ISearchResult[], - protos.google.cloud.retail.v2alpha.ISearchRequest|null, - protos.google.cloud.retail.v2alpha.ISearchResponse - ]>; + request?: protos.google.cloud.retail.v2alpha.ISearchRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.SearchResponse.ISearchResult[], + protos.google.cloud.retail.v2alpha.ISearchRequest | null, + protos.google.cloud.retail.v2alpha.ISearchResponse, + ] + >; search( - request: protos.google.cloud.retail.v2alpha.ISearchRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.cloud.retail.v2alpha.ISearchRequest, - protos.google.cloud.retail.v2alpha.ISearchResponse|null|undefined, - protos.google.cloud.retail.v2alpha.SearchResponse.ISearchResult>): void; + request: protos.google.cloud.retail.v2alpha.ISearchRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.cloud.retail.v2alpha.ISearchRequest, + protos.google.cloud.retail.v2alpha.ISearchResponse | null | undefined, + protos.google.cloud.retail.v2alpha.SearchResponse.ISearchResult + >, + ): void; search( - request: protos.google.cloud.retail.v2alpha.ISearchRequest, - callback: PaginationCallback< - protos.google.cloud.retail.v2alpha.ISearchRequest, - protos.google.cloud.retail.v2alpha.ISearchResponse|null|undefined, - protos.google.cloud.retail.v2alpha.SearchResponse.ISearchResult>): void; + request: protos.google.cloud.retail.v2alpha.ISearchRequest, + callback: PaginationCallback< + protos.google.cloud.retail.v2alpha.ISearchRequest, + protos.google.cloud.retail.v2alpha.ISearchResponse | null | undefined, + protos.google.cloud.retail.v2alpha.SearchResponse.ISearchResult + >, + ): void; search( - request?: protos.google.cloud.retail.v2alpha.ISearchRequest, - optionsOrCallback?: CallOptions|PaginationCallback< - protos.google.cloud.retail.v2alpha.ISearchRequest, - protos.google.cloud.retail.v2alpha.ISearchResponse|null|undefined, - protos.google.cloud.retail.v2alpha.SearchResponse.ISearchResult>, - callback?: PaginationCallback< + request?: protos.google.cloud.retail.v2alpha.ISearchRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.cloud.retail.v2alpha.ISearchRequest, - protos.google.cloud.retail.v2alpha.ISearchResponse|null|undefined, - protos.google.cloud.retail.v2alpha.SearchResponse.ISearchResult>): - Promise<[ - protos.google.cloud.retail.v2alpha.SearchResponse.ISearchResult[], - protos.google.cloud.retail.v2alpha.ISearchRequest|null, - protos.google.cloud.retail.v2alpha.ISearchResponse - ]>|void { + protos.google.cloud.retail.v2alpha.ISearchResponse | null | undefined, + protos.google.cloud.retail.v2alpha.SearchResponse.ISearchResult + >, + callback?: PaginationCallback< + protos.google.cloud.retail.v2alpha.ISearchRequest, + protos.google.cloud.retail.v2alpha.ISearchResponse | null | undefined, + protos.google.cloud.retail.v2alpha.SearchResponse.ISearchResult + >, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.SearchResponse.ISearchResult[], + protos.google.cloud.retail.v2alpha.ISearchRequest | null, + protos.google.cloud.retail.v2alpha.ISearchResponse, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'placement': request.placement ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + placement: request.placement ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.cloud.retail.v2alpha.ISearchRequest, - protos.google.cloud.retail.v2alpha.ISearchResponse|null|undefined, - protos.google.cloud.retail.v2alpha.SearchResponse.ISearchResult>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.cloud.retail.v2alpha.ISearchRequest, + protos.google.cloud.retail.v2alpha.ISearchResponse | null | undefined, + protos.google.cloud.retail.v2alpha.SearchResponse.ISearchResult + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('search values %j', values); callback!(error, values, nextPageRequest, rawResponse); @@ -779,694 +841,698 @@ export class SearchServiceClient { this._log.info('search request %j', request); return this.innerApiCalls .search(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.cloud.retail.v2alpha.SearchResponse.ISearchResult[], - protos.google.cloud.retail.v2alpha.ISearchRequest|null, - protos.google.cloud.retail.v2alpha.ISearchResponse - ]) => { - this._log.info('search values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.cloud.retail.v2alpha.SearchResponse.ISearchResult[], + protos.google.cloud.retail.v2alpha.ISearchRequest | null, + protos.google.cloud.retail.v2alpha.ISearchResponse, + ]) => { + this._log.info('search values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `search`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.placement - * Required. The resource name of the Retail Search serving config, such as - * `projects/* /locations/global/catalogs/default_catalog/servingConfigs/default_serving_config` - * or the name of the legacy placement resource, such as - * `projects/* /locations/global/catalogs/default_catalog/placements/default_search`. - * This field is used to identify the serving config name and the set - * of models that are used to make the search. - * @param {string} request.branch - * The branch resource name, such as - * `projects/* /locations/global/catalogs/default_catalog/branches/0`. - * - * Use "default_branch" as the branch ID or leave this field empty, to search - * products under the default branch. - * @param {string} request.query - * Raw search query. - * - * If this field is empty, the request is considered a category browsing - * request and returned results are based on - * {@link protos.google.cloud.retail.v2alpha.SearchRequest.filter|filter} and - * {@link protos.google.cloud.retail.v2alpha.SearchRequest.page_categories|page_categories}. - * @param {string} request.visitorId - * Required. A unique identifier for tracking visitors. For example, this - * could be implemented with an HTTP cookie, which should be able to uniquely - * identify a visitor on a single device. This unique identifier should not - * change if the visitor logs in or out of the website. - * - * This should be the same identifier as - * {@link protos.google.cloud.retail.v2alpha.UserEvent.visitor_id|UserEvent.visitor_id}. - * - * The field must be a UTF-8 encoded string with a length limit of 128 - * characters. Otherwise, an INVALID_ARGUMENT error is returned. - * @param {google.cloud.retail.v2alpha.UserInfo} request.userInfo - * User information. - * @param {number} request.pageSize - * Maximum number of {@link protos.google.cloud.retail.v2alpha.Product|Product}s to - * return. If unspecified, defaults to a reasonable value. The maximum allowed - * value is 120. Values above 120 will be coerced to 120. - * - * If this field is negative, an INVALID_ARGUMENT is returned. - * @param {string} request.pageToken - * A page token - * {@link protos.google.cloud.retail.v2alpha.SearchResponse.next_page_token|SearchResponse.next_page_token}, - * received from a previous - * {@link protos.google.cloud.retail.v2alpha.SearchService.Search|SearchService.Search} - * call. Provide this to retrieve the subsequent page. - * - * When paginating, all other parameters provided to - * {@link protos.google.cloud.retail.v2alpha.SearchService.Search|SearchService.Search} - * must match the call that provided the page token. Otherwise, an - * INVALID_ARGUMENT error is returned. - * @param {number} request.offset - * A 0-indexed integer that specifies the current offset (that is, starting - * result location, amongst the - * {@link protos.google.cloud.retail.v2alpha.Product|Product}s deemed by the API as - * relevant) in search results. This field is only considered if - * {@link protos.google.cloud.retail.v2alpha.SearchRequest.page_token|page_token} is - * unset. - * - * If this field is negative, an INVALID_ARGUMENT is returned. - * @param {string} request.filter - * The filter syntax consists of an expression language for constructing a - * predicate from one or more fields of the products being filtered. Filter - * expression is case-sensitive. For more information, see - * [Filter](https://cloud.google.com/retail/docs/filter-and-order#filter). - * - * If this field is unrecognizable, an INVALID_ARGUMENT is returned. - * @param {string} request.canonicalFilter - * The default filter that is applied when a user performs a search without - * checking any filters on the search page. - * - * The filter applied to every search request when quality improvement such as - * query expansion is needed. In the case a query does not have a sufficient - * amount of results this filter will be used to determine whether or not to - * enable the query expansion flow. The original filter will still be used for - * the query expanded search. - * This field is strongly recommended to achieve high search quality. - * - * For more information about filter syntax, see - * {@link protos.google.cloud.retail.v2alpha.SearchRequest.filter|SearchRequest.filter}. - * @param {string} request.orderBy - * The order in which products are returned. Products can be ordered by - * a field in an {@link protos.google.cloud.retail.v2alpha.Product|Product} object. Leave - * it unset if ordered by relevance. OrderBy expression is case-sensitive. For - * more information, see - * [Order](https://cloud.google.com/retail/docs/filter-and-order#order). - * - * If this field is unrecognizable, an INVALID_ARGUMENT is returned. - * @param {number[]} request.facetSpecs - * Facet specifications for faceted search. If empty, no facets are returned. - * - * A maximum of 200 values are allowed. Otherwise, an INVALID_ARGUMENT error - * is returned. - * @param {google.cloud.retail.v2alpha.SearchRequest.DynamicFacetSpec} request.dynamicFacetSpec - * Deprecated. Refer to https://cloud.google.com/retail/docs/configs#dynamic - * to enable dynamic facets. Do not set this field. - * - * The specification for dynamically generated facets. Notice that only - * textual facets can be dynamically generated. - * @param {google.cloud.retail.v2alpha.SearchRequest.BoostSpec} request.boostSpec - * Boost specification to boost certain products. For more information, see - * [Boost results](https://cloud.google.com/retail/docs/boosting). - * - * Notice that if both - * {@link protos.google.cloud.retail.v2alpha.ServingConfig.boost_control_ids|ServingConfig.boost_control_ids} - * and - * {@link protos.google.cloud.retail.v2alpha.SearchRequest.boost_spec|SearchRequest.boost_spec} - * are set, the boost conditions from both places are evaluated. If a search - * request matches multiple boost conditions, the final boost score is equal - * to the sum of the boost scores from all matched boost conditions. - * @param {google.cloud.retail.v2alpha.SearchRequest.QueryExpansionSpec} request.queryExpansionSpec - * The query expansion specification that specifies the conditions under which - * query expansion occurs. For more information, see [Query - * expansion](https://cloud.google.com/retail/docs/result-size#query_expansion). - * @param {google.cloud.retail.v2alpha.SearchRequest.RelevanceThreshold} request.relevanceThreshold - * The relevance threshold of the search results. - * - * Defaults to - * {@link protos.google.cloud.retail.v2alpha.SearchRequest.RelevanceThreshold.HIGH|RelevanceThreshold.HIGH}, - * which means only the most relevant results are shown, and the least number - * of results are returned. For more information, see [Adjust result - * size](https://cloud.google.com/retail/docs/result-size#relevance_thresholding). - * @param {string[]} request.variantRollupKeys - * The keys to fetch and rollup the matching - * {@link protos.google.cloud.retail.v2alpha.Product.Type.VARIANT|variant} - * {@link protos.google.cloud.retail.v2alpha.Product|Product}s attributes, - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo|FulfillmentInfo} or - * {@link protos.google.cloud.retail.v2alpha.LocalInventory|LocalInventory}s attributes. - * The attributes from all the matching - * {@link protos.google.cloud.retail.v2alpha.Product.Type.VARIANT|variant} - * {@link protos.google.cloud.retail.v2alpha.Product|Product}s or - * {@link protos.google.cloud.retail.v2alpha.LocalInventory|LocalInventory}s are merged - * and de-duplicated. Notice that rollup attributes will lead to extra query - * latency. Maximum number of keys is 30. - * - * For {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo|FulfillmentInfo}, a - * fulfillment type and a fulfillment ID must be provided in the format of - * "fulfillmentType.fulfillmentId". E.g., in "pickupInStore.store123", - * "pickupInStore" is fulfillment type and "store123" is the store ID. - * - * Supported keys are: - * - * * colorFamilies - * * price - * * originalPrice - * * discount - * * variantId - * * inventory(place_id,price) - * * inventory(place_id,original_price) - * * inventory(place_id,attributes.key), where key is any key in the - * {@link protos.google.cloud.retail.v2alpha.LocalInventory.attributes|Product.local_inventories.attributes} - * map. - * * attributes.key, where key is any key in the - * {@link protos.google.cloud.retail.v2alpha.Product.attributes|Product.attributes} map. - * * pickupInStore.id, where id is any - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.place_ids|FulfillmentInfo.place_ids} - * for - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.type|FulfillmentInfo.type} - * "pickup-in-store". - * * shipToStore.id, where id is any - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.place_ids|FulfillmentInfo.place_ids} - * for - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.type|FulfillmentInfo.type} - * "ship-to-store". - * * sameDayDelivery.id, where id is any - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.place_ids|FulfillmentInfo.place_ids} - * for - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.type|FulfillmentInfo.type} - * "same-day-delivery". - * * nextDayDelivery.id, where id is any - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.place_ids|FulfillmentInfo.place_ids} - * for - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.type|FulfillmentInfo.type} - * "next-day-delivery". - * * customFulfillment1.id, where id is any - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.place_ids|FulfillmentInfo.place_ids} - * for - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.type|FulfillmentInfo.type} - * "custom-type-1". - * * customFulfillment2.id, where id is any - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.place_ids|FulfillmentInfo.place_ids} - * for - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.type|FulfillmentInfo.type} - * "custom-type-2". - * * customFulfillment3.id, where id is any - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.place_ids|FulfillmentInfo.place_ids} - * for - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.type|FulfillmentInfo.type} - * "custom-type-3". - * * customFulfillment4.id, where id is any - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.place_ids|FulfillmentInfo.place_ids} - * for - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.type|FulfillmentInfo.type} - * "custom-type-4". - * * customFulfillment5.id, where id is any - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.place_ids|FulfillmentInfo.place_ids} - * for - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.type|FulfillmentInfo.type} - * "custom-type-5". - * - * If this field is set to an invalid value other than these, an - * INVALID_ARGUMENT error is returned. - * @param {string[]} request.pageCategories - * The categories associated with a category page. Must be set for category - * navigation queries to achieve good search quality. The format should be - * the same as - * {@link protos.google.cloud.retail.v2alpha.UserEvent.page_categories|UserEvent.page_categories}; - * - * To represent full path of category, use '>' sign to separate different - * hierarchies. If '>' is part of the category name, replace it with - * other character(s). - * - * Category pages include special pages such as sales or promotions. For - * instance, a special sale page may have the category hierarchy: - * "pageCategories" : ["Sales > 2017 Black Friday Deals"]. - * @param {google.cloud.retail.v2alpha.SearchRequest.SearchMode} request.searchMode - * The search mode of the search request. If not specified, a single search - * request triggers both product search and faceted search. - * @param {google.cloud.retail.v2alpha.SearchRequest.PersonalizationSpec} request.personalizationSpec - * The specification for personalization. - * - * Notice that if both - * {@link protos.google.cloud.retail.v2alpha.ServingConfig.personalization_spec|ServingConfig.personalization_spec} - * and - * {@link protos.google.cloud.retail.v2alpha.SearchRequest.personalization_spec|SearchRequest.personalization_spec} - * are set. - * {@link protos.google.cloud.retail.v2alpha.SearchRequest.personalization_spec|SearchRequest.personalization_spec} - * will override - * {@link protos.google.cloud.retail.v2alpha.ServingConfig.personalization_spec|ServingConfig.personalization_spec}. - * @param {number[]} request.labels - * The labels applied to a resource must meet the following requirements: - * - * * Each resource can have multiple labels, up to a maximum of 64. - * * Each label must be a key-value pair. - * * Keys have a minimum length of 1 character and a maximum length of 63 - * characters and cannot be empty. Values can be empty and have a maximum - * length of 63 characters. - * * Keys and values can contain only lowercase letters, numeric characters, - * underscores, and dashes. All characters must use UTF-8 encoding, and - * international characters are allowed. - * * The key portion of a label must be unique. However, you can use the same - * key with multiple resources. - * * Keys must start with a lowercase letter or international character. - * - * For more information, see [Requirements for - * labels](https://cloud.google.com/resource-manager/docs/creating-managing-labels#requirements) - * in the Resource Manager documentation. - * @param {google.cloud.retail.v2alpha.SearchRequest.SpellCorrectionSpec} request.spellCorrectionSpec - * The spell correction specification that specifies the mode under - * which spell correction will take effect. - * @param {string} request.entity - * The entity for customers that may run multiple different entities, domains, - * sites or regions, for example, `Google US`, `Google Ads`, `Waymo`, - * `google.com`, `youtube.com`, etc. - * If this is set, it should be exactly matched with - * {@link protos.google.cloud.retail.v2alpha.UserEvent.entity|UserEvent.entity} to get - * search results boosted by entity. - * @param {google.cloud.retail.v2alpha.SearchRequest.ConversationalSearchSpec} [request.conversationalSearchSpec] - * Optional. This field specifies all conversational related parameters - * addition to traditional retail search. - * @param {google.cloud.retail.v2alpha.SearchRequest.TileNavigationSpec} [request.tileNavigationSpec] - * Optional. This field specifies tile navigation related parameters. - * @param {string} [request.languageCode] - * Optional. The BCP-47 language code, such as "en-US" or "sr-Latn" - * [list](https://www.unicode.org/cldr/charts/46/summary/root.html). For more - * information, see [Standardized codes](https://google.aip.dev/143). This - * field helps to better interpret the query. If a value isn't specified, the - * query language code is automatically detected, which may not be accurate. - * @param {string} [request.regionCode] - * Optional. The Unicode country/region code (CLDR) of a location, such as - * "US" and "419" - * [list](https://www.unicode.org/cldr/charts/46/supplemental/territory_information.html). - * For more information, see [Standardized codes](https://google.aip.dev/143). - * If set, then results will be boosted based on the region_code provided. - * @param {string} [request.placeId] - * Optional. An id corresponding to a place, such as a store id or region id. - * When specified, we use the price from the local inventory with the matching - * product's - * {@link protos.google.cloud.retail.v2alpha.LocalInventory.place_id|LocalInventory.place_id} - * for revenue optimization. - * @param {number[]} [request.userAttributes] - * Optional. The user attributes that could be used for personalization of - * search results. - * * Populate at most 100 key-value pairs per query. - * * Only supports string keys and repeated string values. - * * Duplcate keys are not allowed within a single query. - * - * Example: - * user_attributes: [ - * { key: "pets" - * value { - * values: "dog" - * values: "cat" - * } - * }, - * { key: "state" - * value { - * values: "CA" - * } - * } - * ] - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.cloud.retail.v2alpha.SearchResponse.SearchResult|SearchResult} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `searchAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `search`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.placement + * Required. The resource name of the Retail Search serving config, such as + * `projects/* /locations/global/catalogs/default_catalog/servingConfigs/default_serving_config` + * or the name of the legacy placement resource, such as + * `projects/* /locations/global/catalogs/default_catalog/placements/default_search`. + * This field is used to identify the serving config name and the set + * of models that are used to make the search. + * @param {string} request.branch + * The branch resource name, such as + * `projects/* /locations/global/catalogs/default_catalog/branches/0`. + * + * Use "default_branch" as the branch ID or leave this field empty, to search + * products under the default branch. + * @param {string} request.query + * Raw search query. + * + * If this field is empty, the request is considered a category browsing + * request and returned results are based on + * {@link protos.google.cloud.retail.v2alpha.SearchRequest.filter|filter} and + * {@link protos.google.cloud.retail.v2alpha.SearchRequest.page_categories|page_categories}. + * @param {string} request.visitorId + * Required. A unique identifier for tracking visitors. For example, this + * could be implemented with an HTTP cookie, which should be able to uniquely + * identify a visitor on a single device. This unique identifier should not + * change if the visitor logs in or out of the website. + * + * This should be the same identifier as + * {@link protos.google.cloud.retail.v2alpha.UserEvent.visitor_id|UserEvent.visitor_id}. + * + * The field must be a UTF-8 encoded string with a length limit of 128 + * characters. Otherwise, an INVALID_ARGUMENT error is returned. + * @param {google.cloud.retail.v2alpha.UserInfo} request.userInfo + * User information. + * @param {number} request.pageSize + * Maximum number of {@link protos.google.cloud.retail.v2alpha.Product|Product}s to + * return. If unspecified, defaults to a reasonable value. The maximum allowed + * value is 120. Values above 120 will be coerced to 120. + * + * If this field is negative, an INVALID_ARGUMENT is returned. + * @param {string} request.pageToken + * A page token + * {@link protos.google.cloud.retail.v2alpha.SearchResponse.next_page_token|SearchResponse.next_page_token}, + * received from a previous + * {@link protos.google.cloud.retail.v2alpha.SearchService.Search|SearchService.Search} + * call. Provide this to retrieve the subsequent page. + * + * When paginating, all other parameters provided to + * {@link protos.google.cloud.retail.v2alpha.SearchService.Search|SearchService.Search} + * must match the call that provided the page token. Otherwise, an + * INVALID_ARGUMENT error is returned. + * @param {number} request.offset + * A 0-indexed integer that specifies the current offset (that is, starting + * result location, amongst the + * {@link protos.google.cloud.retail.v2alpha.Product|Product}s deemed by the API as + * relevant) in search results. This field is only considered if + * {@link protos.google.cloud.retail.v2alpha.SearchRequest.page_token|page_token} is + * unset. + * + * If this field is negative, an INVALID_ARGUMENT is returned. + * @param {string} request.filter + * The filter syntax consists of an expression language for constructing a + * predicate from one or more fields of the products being filtered. Filter + * expression is case-sensitive. For more information, see + * [Filter](https://cloud.google.com/retail/docs/filter-and-order#filter). + * + * If this field is unrecognizable, an INVALID_ARGUMENT is returned. + * @param {string} request.canonicalFilter + * The default filter that is applied when a user performs a search without + * checking any filters on the search page. + * + * The filter applied to every search request when quality improvement such as + * query expansion is needed. In the case a query does not have a sufficient + * amount of results this filter will be used to determine whether or not to + * enable the query expansion flow. The original filter will still be used for + * the query expanded search. + * This field is strongly recommended to achieve high search quality. + * + * For more information about filter syntax, see + * {@link protos.google.cloud.retail.v2alpha.SearchRequest.filter|SearchRequest.filter}. + * @param {string} request.orderBy + * The order in which products are returned. Products can be ordered by + * a field in an {@link protos.google.cloud.retail.v2alpha.Product|Product} object. Leave + * it unset if ordered by relevance. OrderBy expression is case-sensitive. For + * more information, see + * [Order](https://cloud.google.com/retail/docs/filter-and-order#order). + * + * If this field is unrecognizable, an INVALID_ARGUMENT is returned. + * @param {number[]} request.facetSpecs + * Facet specifications for faceted search. If empty, no facets are returned. + * + * A maximum of 200 values are allowed. Otherwise, an INVALID_ARGUMENT error + * is returned. + * @param {google.cloud.retail.v2alpha.SearchRequest.DynamicFacetSpec} request.dynamicFacetSpec + * Deprecated. Refer to https://cloud.google.com/retail/docs/configs#dynamic + * to enable dynamic facets. Do not set this field. + * + * The specification for dynamically generated facets. Notice that only + * textual facets can be dynamically generated. + * @param {google.cloud.retail.v2alpha.SearchRequest.BoostSpec} request.boostSpec + * Boost specification to boost certain products. For more information, see + * [Boost results](https://cloud.google.com/retail/docs/boosting). + * + * Notice that if both + * {@link protos.google.cloud.retail.v2alpha.ServingConfig.boost_control_ids|ServingConfig.boost_control_ids} + * and + * {@link protos.google.cloud.retail.v2alpha.SearchRequest.boost_spec|SearchRequest.boost_spec} + * are set, the boost conditions from both places are evaluated. If a search + * request matches multiple boost conditions, the final boost score is equal + * to the sum of the boost scores from all matched boost conditions. + * @param {google.cloud.retail.v2alpha.SearchRequest.QueryExpansionSpec} request.queryExpansionSpec + * The query expansion specification that specifies the conditions under which + * query expansion occurs. For more information, see [Query + * expansion](https://cloud.google.com/retail/docs/result-size#query_expansion). + * @param {google.cloud.retail.v2alpha.SearchRequest.RelevanceThreshold} request.relevanceThreshold + * The relevance threshold of the search results. + * + * Defaults to + * {@link protos.google.cloud.retail.v2alpha.SearchRequest.RelevanceThreshold.HIGH|RelevanceThreshold.HIGH}, + * which means only the most relevant results are shown, and the least number + * of results are returned. For more information, see [Adjust result + * size](https://cloud.google.com/retail/docs/result-size#relevance_thresholding). + * @param {string[]} request.variantRollupKeys + * The keys to fetch and rollup the matching + * {@link protos.google.cloud.retail.v2alpha.Product.Type.VARIANT|variant} + * {@link protos.google.cloud.retail.v2alpha.Product|Product}s attributes, + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo|FulfillmentInfo} or + * {@link protos.google.cloud.retail.v2alpha.LocalInventory|LocalInventory}s attributes. + * The attributes from all the matching + * {@link protos.google.cloud.retail.v2alpha.Product.Type.VARIANT|variant} + * {@link protos.google.cloud.retail.v2alpha.Product|Product}s or + * {@link protos.google.cloud.retail.v2alpha.LocalInventory|LocalInventory}s are merged + * and de-duplicated. Notice that rollup attributes will lead to extra query + * latency. Maximum number of keys is 30. + * + * For {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo|FulfillmentInfo}, a + * fulfillment type and a fulfillment ID must be provided in the format of + * "fulfillmentType.fulfillmentId". E.g., in "pickupInStore.store123", + * "pickupInStore" is fulfillment type and "store123" is the store ID. + * + * Supported keys are: + * + * * colorFamilies + * * price + * * originalPrice + * * discount + * * variantId + * * inventory(place_id,price) + * * inventory(place_id,original_price) + * * inventory(place_id,attributes.key), where key is any key in the + * {@link protos.google.cloud.retail.v2alpha.LocalInventory.attributes|Product.local_inventories.attributes} + * map. + * * attributes.key, where key is any key in the + * {@link protos.google.cloud.retail.v2alpha.Product.attributes|Product.attributes} map. + * * pickupInStore.id, where id is any + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.place_ids|FulfillmentInfo.place_ids} + * for + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.type|FulfillmentInfo.type} + * "pickup-in-store". + * * shipToStore.id, where id is any + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.place_ids|FulfillmentInfo.place_ids} + * for + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.type|FulfillmentInfo.type} + * "ship-to-store". + * * sameDayDelivery.id, where id is any + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.place_ids|FulfillmentInfo.place_ids} + * for + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.type|FulfillmentInfo.type} + * "same-day-delivery". + * * nextDayDelivery.id, where id is any + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.place_ids|FulfillmentInfo.place_ids} + * for + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.type|FulfillmentInfo.type} + * "next-day-delivery". + * * customFulfillment1.id, where id is any + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.place_ids|FulfillmentInfo.place_ids} + * for + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.type|FulfillmentInfo.type} + * "custom-type-1". + * * customFulfillment2.id, where id is any + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.place_ids|FulfillmentInfo.place_ids} + * for + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.type|FulfillmentInfo.type} + * "custom-type-2". + * * customFulfillment3.id, where id is any + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.place_ids|FulfillmentInfo.place_ids} + * for + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.type|FulfillmentInfo.type} + * "custom-type-3". + * * customFulfillment4.id, where id is any + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.place_ids|FulfillmentInfo.place_ids} + * for + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.type|FulfillmentInfo.type} + * "custom-type-4". + * * customFulfillment5.id, where id is any + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.place_ids|FulfillmentInfo.place_ids} + * for + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.type|FulfillmentInfo.type} + * "custom-type-5". + * + * If this field is set to an invalid value other than these, an + * INVALID_ARGUMENT error is returned. + * @param {string[]} request.pageCategories + * The categories associated with a category page. Must be set for category + * navigation queries to achieve good search quality. The format should be + * the same as + * {@link protos.google.cloud.retail.v2alpha.UserEvent.page_categories|UserEvent.page_categories}; + * + * To represent full path of category, use '>' sign to separate different + * hierarchies. If '>' is part of the category name, replace it with + * other character(s). + * + * Category pages include special pages such as sales or promotions. For + * instance, a special sale page may have the category hierarchy: + * "pageCategories" : ["Sales > 2017 Black Friday Deals"]. + * @param {google.cloud.retail.v2alpha.SearchRequest.SearchMode} request.searchMode + * The search mode of the search request. If not specified, a single search + * request triggers both product search and faceted search. + * @param {google.cloud.retail.v2alpha.SearchRequest.PersonalizationSpec} request.personalizationSpec + * The specification for personalization. + * + * Notice that if both + * {@link protos.google.cloud.retail.v2alpha.ServingConfig.personalization_spec|ServingConfig.personalization_spec} + * and + * {@link protos.google.cloud.retail.v2alpha.SearchRequest.personalization_spec|SearchRequest.personalization_spec} + * are set. + * {@link protos.google.cloud.retail.v2alpha.SearchRequest.personalization_spec|SearchRequest.personalization_spec} + * will override + * {@link protos.google.cloud.retail.v2alpha.ServingConfig.personalization_spec|ServingConfig.personalization_spec}. + * @param {number[]} request.labels + * The labels applied to a resource must meet the following requirements: + * + * * Each resource can have multiple labels, up to a maximum of 64. + * * Each label must be a key-value pair. + * * Keys have a minimum length of 1 character and a maximum length of 63 + * characters and cannot be empty. Values can be empty and have a maximum + * length of 63 characters. + * * Keys and values can contain only lowercase letters, numeric characters, + * underscores, and dashes. All characters must use UTF-8 encoding, and + * international characters are allowed. + * * The key portion of a label must be unique. However, you can use the same + * key with multiple resources. + * * Keys must start with a lowercase letter or international character. + * + * For more information, see [Requirements for + * labels](https://cloud.google.com/resource-manager/docs/creating-managing-labels#requirements) + * in the Resource Manager documentation. + * @param {google.cloud.retail.v2alpha.SearchRequest.SpellCorrectionSpec} request.spellCorrectionSpec + * The spell correction specification that specifies the mode under + * which spell correction will take effect. + * @param {string} request.entity + * The entity for customers that may run multiple different entities, domains, + * sites or regions, for example, `Google US`, `Google Ads`, `Waymo`, + * `google.com`, `youtube.com`, etc. + * If this is set, it should be exactly matched with + * {@link protos.google.cloud.retail.v2alpha.UserEvent.entity|UserEvent.entity} to get + * search results boosted by entity. + * @param {google.cloud.retail.v2alpha.SearchRequest.ConversationalSearchSpec} [request.conversationalSearchSpec] + * Optional. This field specifies all conversational related parameters + * addition to traditional retail search. + * @param {google.cloud.retail.v2alpha.SearchRequest.TileNavigationSpec} [request.tileNavigationSpec] + * Optional. This field specifies tile navigation related parameters. + * @param {string} [request.languageCode] + * Optional. The BCP-47 language code, such as "en-US" or "sr-Latn" + * [list](https://www.unicode.org/cldr/charts/46/summary/root.html). For more + * information, see [Standardized codes](https://google.aip.dev/143). This + * field helps to better interpret the query. If a value isn't specified, the + * query language code is automatically detected, which may not be accurate. + * @param {string} [request.regionCode] + * Optional. The Unicode country/region code (CLDR) of a location, such as + * "US" and "419" + * [list](https://www.unicode.org/cldr/charts/46/supplemental/territory_information.html). + * For more information, see [Standardized codes](https://google.aip.dev/143). + * If set, then results will be boosted based on the region_code provided. + * @param {string} [request.placeId] + * Optional. An id corresponding to a place, such as a store id or region id. + * When specified, we use the price from the local inventory with the matching + * product's + * {@link protos.google.cloud.retail.v2alpha.LocalInventory.place_id|LocalInventory.place_id} + * for revenue optimization. + * @param {number[]} [request.userAttributes] + * Optional. The user attributes that could be used for personalization of + * search results. + * * Populate at most 100 key-value pairs per query. + * * Only supports string keys and repeated string values. + * * Duplcate keys are not allowed within a single query. + * + * Example: + * user_attributes: [ + * { key: "pets" + * value { + * values: "dog" + * values: "cat" + * } + * }, + * { key: "state" + * value { + * values: "CA" + * } + * } + * ] + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.cloud.retail.v2alpha.SearchResponse.SearchResult|SearchResult} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `searchAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ searchStream( - request?: protos.google.cloud.retail.v2alpha.ISearchRequest, - options?: CallOptions): - Transform{ + request?: protos.google.cloud.retail.v2alpha.ISearchRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'placement': request.placement ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + placement: request.placement ?? '', + }); const defaultCallSettings = this._defaults['search']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('search stream %j', request); return this.descriptors.page.search.createStream( this.innerApiCalls.search as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `search`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.placement - * Required. The resource name of the Retail Search serving config, such as - * `projects/* /locations/global/catalogs/default_catalog/servingConfigs/default_serving_config` - * or the name of the legacy placement resource, such as - * `projects/* /locations/global/catalogs/default_catalog/placements/default_search`. - * This field is used to identify the serving config name and the set - * of models that are used to make the search. - * @param {string} request.branch - * The branch resource name, such as - * `projects/* /locations/global/catalogs/default_catalog/branches/0`. - * - * Use "default_branch" as the branch ID or leave this field empty, to search - * products under the default branch. - * @param {string} request.query - * Raw search query. - * - * If this field is empty, the request is considered a category browsing - * request and returned results are based on - * {@link protos.google.cloud.retail.v2alpha.SearchRequest.filter|filter} and - * {@link protos.google.cloud.retail.v2alpha.SearchRequest.page_categories|page_categories}. - * @param {string} request.visitorId - * Required. A unique identifier for tracking visitors. For example, this - * could be implemented with an HTTP cookie, which should be able to uniquely - * identify a visitor on a single device. This unique identifier should not - * change if the visitor logs in or out of the website. - * - * This should be the same identifier as - * {@link protos.google.cloud.retail.v2alpha.UserEvent.visitor_id|UserEvent.visitor_id}. - * - * The field must be a UTF-8 encoded string with a length limit of 128 - * characters. Otherwise, an INVALID_ARGUMENT error is returned. - * @param {google.cloud.retail.v2alpha.UserInfo} request.userInfo - * User information. - * @param {number} request.pageSize - * Maximum number of {@link protos.google.cloud.retail.v2alpha.Product|Product}s to - * return. If unspecified, defaults to a reasonable value. The maximum allowed - * value is 120. Values above 120 will be coerced to 120. - * - * If this field is negative, an INVALID_ARGUMENT is returned. - * @param {string} request.pageToken - * A page token - * {@link protos.google.cloud.retail.v2alpha.SearchResponse.next_page_token|SearchResponse.next_page_token}, - * received from a previous - * {@link protos.google.cloud.retail.v2alpha.SearchService.Search|SearchService.Search} - * call. Provide this to retrieve the subsequent page. - * - * When paginating, all other parameters provided to - * {@link protos.google.cloud.retail.v2alpha.SearchService.Search|SearchService.Search} - * must match the call that provided the page token. Otherwise, an - * INVALID_ARGUMENT error is returned. - * @param {number} request.offset - * A 0-indexed integer that specifies the current offset (that is, starting - * result location, amongst the - * {@link protos.google.cloud.retail.v2alpha.Product|Product}s deemed by the API as - * relevant) in search results. This field is only considered if - * {@link protos.google.cloud.retail.v2alpha.SearchRequest.page_token|page_token} is - * unset. - * - * If this field is negative, an INVALID_ARGUMENT is returned. - * @param {string} request.filter - * The filter syntax consists of an expression language for constructing a - * predicate from one or more fields of the products being filtered. Filter - * expression is case-sensitive. For more information, see - * [Filter](https://cloud.google.com/retail/docs/filter-and-order#filter). - * - * If this field is unrecognizable, an INVALID_ARGUMENT is returned. - * @param {string} request.canonicalFilter - * The default filter that is applied when a user performs a search without - * checking any filters on the search page. - * - * The filter applied to every search request when quality improvement such as - * query expansion is needed. In the case a query does not have a sufficient - * amount of results this filter will be used to determine whether or not to - * enable the query expansion flow. The original filter will still be used for - * the query expanded search. - * This field is strongly recommended to achieve high search quality. - * - * For more information about filter syntax, see - * {@link protos.google.cloud.retail.v2alpha.SearchRequest.filter|SearchRequest.filter}. - * @param {string} request.orderBy - * The order in which products are returned. Products can be ordered by - * a field in an {@link protos.google.cloud.retail.v2alpha.Product|Product} object. Leave - * it unset if ordered by relevance. OrderBy expression is case-sensitive. For - * more information, see - * [Order](https://cloud.google.com/retail/docs/filter-and-order#order). - * - * If this field is unrecognizable, an INVALID_ARGUMENT is returned. - * @param {number[]} request.facetSpecs - * Facet specifications for faceted search. If empty, no facets are returned. - * - * A maximum of 200 values are allowed. Otherwise, an INVALID_ARGUMENT error - * is returned. - * @param {google.cloud.retail.v2alpha.SearchRequest.DynamicFacetSpec} request.dynamicFacetSpec - * Deprecated. Refer to https://cloud.google.com/retail/docs/configs#dynamic - * to enable dynamic facets. Do not set this field. - * - * The specification for dynamically generated facets. Notice that only - * textual facets can be dynamically generated. - * @param {google.cloud.retail.v2alpha.SearchRequest.BoostSpec} request.boostSpec - * Boost specification to boost certain products. For more information, see - * [Boost results](https://cloud.google.com/retail/docs/boosting). - * - * Notice that if both - * {@link protos.google.cloud.retail.v2alpha.ServingConfig.boost_control_ids|ServingConfig.boost_control_ids} - * and - * {@link protos.google.cloud.retail.v2alpha.SearchRequest.boost_spec|SearchRequest.boost_spec} - * are set, the boost conditions from both places are evaluated. If a search - * request matches multiple boost conditions, the final boost score is equal - * to the sum of the boost scores from all matched boost conditions. - * @param {google.cloud.retail.v2alpha.SearchRequest.QueryExpansionSpec} request.queryExpansionSpec - * The query expansion specification that specifies the conditions under which - * query expansion occurs. For more information, see [Query - * expansion](https://cloud.google.com/retail/docs/result-size#query_expansion). - * @param {google.cloud.retail.v2alpha.SearchRequest.RelevanceThreshold} request.relevanceThreshold - * The relevance threshold of the search results. - * - * Defaults to - * {@link protos.google.cloud.retail.v2alpha.SearchRequest.RelevanceThreshold.HIGH|RelevanceThreshold.HIGH}, - * which means only the most relevant results are shown, and the least number - * of results are returned. For more information, see [Adjust result - * size](https://cloud.google.com/retail/docs/result-size#relevance_thresholding). - * @param {string[]} request.variantRollupKeys - * The keys to fetch and rollup the matching - * {@link protos.google.cloud.retail.v2alpha.Product.Type.VARIANT|variant} - * {@link protos.google.cloud.retail.v2alpha.Product|Product}s attributes, - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo|FulfillmentInfo} or - * {@link protos.google.cloud.retail.v2alpha.LocalInventory|LocalInventory}s attributes. - * The attributes from all the matching - * {@link protos.google.cloud.retail.v2alpha.Product.Type.VARIANT|variant} - * {@link protos.google.cloud.retail.v2alpha.Product|Product}s or - * {@link protos.google.cloud.retail.v2alpha.LocalInventory|LocalInventory}s are merged - * and de-duplicated. Notice that rollup attributes will lead to extra query - * latency. Maximum number of keys is 30. - * - * For {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo|FulfillmentInfo}, a - * fulfillment type and a fulfillment ID must be provided in the format of - * "fulfillmentType.fulfillmentId". E.g., in "pickupInStore.store123", - * "pickupInStore" is fulfillment type and "store123" is the store ID. - * - * Supported keys are: - * - * * colorFamilies - * * price - * * originalPrice - * * discount - * * variantId - * * inventory(place_id,price) - * * inventory(place_id,original_price) - * * inventory(place_id,attributes.key), where key is any key in the - * {@link protos.google.cloud.retail.v2alpha.LocalInventory.attributes|Product.local_inventories.attributes} - * map. - * * attributes.key, where key is any key in the - * {@link protos.google.cloud.retail.v2alpha.Product.attributes|Product.attributes} map. - * * pickupInStore.id, where id is any - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.place_ids|FulfillmentInfo.place_ids} - * for - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.type|FulfillmentInfo.type} - * "pickup-in-store". - * * shipToStore.id, where id is any - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.place_ids|FulfillmentInfo.place_ids} - * for - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.type|FulfillmentInfo.type} - * "ship-to-store". - * * sameDayDelivery.id, where id is any - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.place_ids|FulfillmentInfo.place_ids} - * for - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.type|FulfillmentInfo.type} - * "same-day-delivery". - * * nextDayDelivery.id, where id is any - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.place_ids|FulfillmentInfo.place_ids} - * for - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.type|FulfillmentInfo.type} - * "next-day-delivery". - * * customFulfillment1.id, where id is any - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.place_ids|FulfillmentInfo.place_ids} - * for - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.type|FulfillmentInfo.type} - * "custom-type-1". - * * customFulfillment2.id, where id is any - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.place_ids|FulfillmentInfo.place_ids} - * for - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.type|FulfillmentInfo.type} - * "custom-type-2". - * * customFulfillment3.id, where id is any - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.place_ids|FulfillmentInfo.place_ids} - * for - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.type|FulfillmentInfo.type} - * "custom-type-3". - * * customFulfillment4.id, where id is any - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.place_ids|FulfillmentInfo.place_ids} - * for - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.type|FulfillmentInfo.type} - * "custom-type-4". - * * customFulfillment5.id, where id is any - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.place_ids|FulfillmentInfo.place_ids} - * for - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.type|FulfillmentInfo.type} - * "custom-type-5". - * - * If this field is set to an invalid value other than these, an - * INVALID_ARGUMENT error is returned. - * @param {string[]} request.pageCategories - * The categories associated with a category page. Must be set for category - * navigation queries to achieve good search quality. The format should be - * the same as - * {@link protos.google.cloud.retail.v2alpha.UserEvent.page_categories|UserEvent.page_categories}; - * - * To represent full path of category, use '>' sign to separate different - * hierarchies. If '>' is part of the category name, replace it with - * other character(s). - * - * Category pages include special pages such as sales or promotions. For - * instance, a special sale page may have the category hierarchy: - * "pageCategories" : ["Sales > 2017 Black Friday Deals"]. - * @param {google.cloud.retail.v2alpha.SearchRequest.SearchMode} request.searchMode - * The search mode of the search request. If not specified, a single search - * request triggers both product search and faceted search. - * @param {google.cloud.retail.v2alpha.SearchRequest.PersonalizationSpec} request.personalizationSpec - * The specification for personalization. - * - * Notice that if both - * {@link protos.google.cloud.retail.v2alpha.ServingConfig.personalization_spec|ServingConfig.personalization_spec} - * and - * {@link protos.google.cloud.retail.v2alpha.SearchRequest.personalization_spec|SearchRequest.personalization_spec} - * are set. - * {@link protos.google.cloud.retail.v2alpha.SearchRequest.personalization_spec|SearchRequest.personalization_spec} - * will override - * {@link protos.google.cloud.retail.v2alpha.ServingConfig.personalization_spec|ServingConfig.personalization_spec}. - * @param {number[]} request.labels - * The labels applied to a resource must meet the following requirements: - * - * * Each resource can have multiple labels, up to a maximum of 64. - * * Each label must be a key-value pair. - * * Keys have a minimum length of 1 character and a maximum length of 63 - * characters and cannot be empty. Values can be empty and have a maximum - * length of 63 characters. - * * Keys and values can contain only lowercase letters, numeric characters, - * underscores, and dashes. All characters must use UTF-8 encoding, and - * international characters are allowed. - * * The key portion of a label must be unique. However, you can use the same - * key with multiple resources. - * * Keys must start with a lowercase letter or international character. - * - * For more information, see [Requirements for - * labels](https://cloud.google.com/resource-manager/docs/creating-managing-labels#requirements) - * in the Resource Manager documentation. - * @param {google.cloud.retail.v2alpha.SearchRequest.SpellCorrectionSpec} request.spellCorrectionSpec - * The spell correction specification that specifies the mode under - * which spell correction will take effect. - * @param {string} request.entity - * The entity for customers that may run multiple different entities, domains, - * sites or regions, for example, `Google US`, `Google Ads`, `Waymo`, - * `google.com`, `youtube.com`, etc. - * If this is set, it should be exactly matched with - * {@link protos.google.cloud.retail.v2alpha.UserEvent.entity|UserEvent.entity} to get - * search results boosted by entity. - * @param {google.cloud.retail.v2alpha.SearchRequest.ConversationalSearchSpec} [request.conversationalSearchSpec] - * Optional. This field specifies all conversational related parameters - * addition to traditional retail search. - * @param {google.cloud.retail.v2alpha.SearchRequest.TileNavigationSpec} [request.tileNavigationSpec] - * Optional. This field specifies tile navigation related parameters. - * @param {string} [request.languageCode] - * Optional. The BCP-47 language code, such as "en-US" or "sr-Latn" - * [list](https://www.unicode.org/cldr/charts/46/summary/root.html). For more - * information, see [Standardized codes](https://google.aip.dev/143). This - * field helps to better interpret the query. If a value isn't specified, the - * query language code is automatically detected, which may not be accurate. - * @param {string} [request.regionCode] - * Optional. The Unicode country/region code (CLDR) of a location, such as - * "US" and "419" - * [list](https://www.unicode.org/cldr/charts/46/supplemental/territory_information.html). - * For more information, see [Standardized codes](https://google.aip.dev/143). - * If set, then results will be boosted based on the region_code provided. - * @param {string} [request.placeId] - * Optional. An id corresponding to a place, such as a store id or region id. - * When specified, we use the price from the local inventory with the matching - * product's - * {@link protos.google.cloud.retail.v2alpha.LocalInventory.place_id|LocalInventory.place_id} - * for revenue optimization. - * @param {number[]} [request.userAttributes] - * Optional. The user attributes that could be used for personalization of - * search results. - * * Populate at most 100 key-value pairs per query. - * * Only supports string keys and repeated string values. - * * Duplcate keys are not allowed within a single query. - * - * Example: - * user_attributes: [ - * { key: "pets" - * value { - * values: "dog" - * values: "cat" - * } - * }, - * { key: "state" - * value { - * values: "CA" - * } - * } - * ] - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.cloud.retail.v2alpha.SearchResponse.SearchResult|SearchResult}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/search_service.search.js - * region_tag:retail_v2alpha_generated_SearchService_Search_async - */ + /** + * Equivalent to `search`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.placement + * Required. The resource name of the Retail Search serving config, such as + * `projects/* /locations/global/catalogs/default_catalog/servingConfigs/default_serving_config` + * or the name of the legacy placement resource, such as + * `projects/* /locations/global/catalogs/default_catalog/placements/default_search`. + * This field is used to identify the serving config name and the set + * of models that are used to make the search. + * @param {string} request.branch + * The branch resource name, such as + * `projects/* /locations/global/catalogs/default_catalog/branches/0`. + * + * Use "default_branch" as the branch ID or leave this field empty, to search + * products under the default branch. + * @param {string} request.query + * Raw search query. + * + * If this field is empty, the request is considered a category browsing + * request and returned results are based on + * {@link protos.google.cloud.retail.v2alpha.SearchRequest.filter|filter} and + * {@link protos.google.cloud.retail.v2alpha.SearchRequest.page_categories|page_categories}. + * @param {string} request.visitorId + * Required. A unique identifier for tracking visitors. For example, this + * could be implemented with an HTTP cookie, which should be able to uniquely + * identify a visitor on a single device. This unique identifier should not + * change if the visitor logs in or out of the website. + * + * This should be the same identifier as + * {@link protos.google.cloud.retail.v2alpha.UserEvent.visitor_id|UserEvent.visitor_id}. + * + * The field must be a UTF-8 encoded string with a length limit of 128 + * characters. Otherwise, an INVALID_ARGUMENT error is returned. + * @param {google.cloud.retail.v2alpha.UserInfo} request.userInfo + * User information. + * @param {number} request.pageSize + * Maximum number of {@link protos.google.cloud.retail.v2alpha.Product|Product}s to + * return. If unspecified, defaults to a reasonable value. The maximum allowed + * value is 120. Values above 120 will be coerced to 120. + * + * If this field is negative, an INVALID_ARGUMENT is returned. + * @param {string} request.pageToken + * A page token + * {@link protos.google.cloud.retail.v2alpha.SearchResponse.next_page_token|SearchResponse.next_page_token}, + * received from a previous + * {@link protos.google.cloud.retail.v2alpha.SearchService.Search|SearchService.Search} + * call. Provide this to retrieve the subsequent page. + * + * When paginating, all other parameters provided to + * {@link protos.google.cloud.retail.v2alpha.SearchService.Search|SearchService.Search} + * must match the call that provided the page token. Otherwise, an + * INVALID_ARGUMENT error is returned. + * @param {number} request.offset + * A 0-indexed integer that specifies the current offset (that is, starting + * result location, amongst the + * {@link protos.google.cloud.retail.v2alpha.Product|Product}s deemed by the API as + * relevant) in search results. This field is only considered if + * {@link protos.google.cloud.retail.v2alpha.SearchRequest.page_token|page_token} is + * unset. + * + * If this field is negative, an INVALID_ARGUMENT is returned. + * @param {string} request.filter + * The filter syntax consists of an expression language for constructing a + * predicate from one or more fields of the products being filtered. Filter + * expression is case-sensitive. For more information, see + * [Filter](https://cloud.google.com/retail/docs/filter-and-order#filter). + * + * If this field is unrecognizable, an INVALID_ARGUMENT is returned. + * @param {string} request.canonicalFilter + * The default filter that is applied when a user performs a search without + * checking any filters on the search page. + * + * The filter applied to every search request when quality improvement such as + * query expansion is needed. In the case a query does not have a sufficient + * amount of results this filter will be used to determine whether or not to + * enable the query expansion flow. The original filter will still be used for + * the query expanded search. + * This field is strongly recommended to achieve high search quality. + * + * For more information about filter syntax, see + * {@link protos.google.cloud.retail.v2alpha.SearchRequest.filter|SearchRequest.filter}. + * @param {string} request.orderBy + * The order in which products are returned. Products can be ordered by + * a field in an {@link protos.google.cloud.retail.v2alpha.Product|Product} object. Leave + * it unset if ordered by relevance. OrderBy expression is case-sensitive. For + * more information, see + * [Order](https://cloud.google.com/retail/docs/filter-and-order#order). + * + * If this field is unrecognizable, an INVALID_ARGUMENT is returned. + * @param {number[]} request.facetSpecs + * Facet specifications for faceted search. If empty, no facets are returned. + * + * A maximum of 200 values are allowed. Otherwise, an INVALID_ARGUMENT error + * is returned. + * @param {google.cloud.retail.v2alpha.SearchRequest.DynamicFacetSpec} request.dynamicFacetSpec + * Deprecated. Refer to https://cloud.google.com/retail/docs/configs#dynamic + * to enable dynamic facets. Do not set this field. + * + * The specification for dynamically generated facets. Notice that only + * textual facets can be dynamically generated. + * @param {google.cloud.retail.v2alpha.SearchRequest.BoostSpec} request.boostSpec + * Boost specification to boost certain products. For more information, see + * [Boost results](https://cloud.google.com/retail/docs/boosting). + * + * Notice that if both + * {@link protos.google.cloud.retail.v2alpha.ServingConfig.boost_control_ids|ServingConfig.boost_control_ids} + * and + * {@link protos.google.cloud.retail.v2alpha.SearchRequest.boost_spec|SearchRequest.boost_spec} + * are set, the boost conditions from both places are evaluated. If a search + * request matches multiple boost conditions, the final boost score is equal + * to the sum of the boost scores from all matched boost conditions. + * @param {google.cloud.retail.v2alpha.SearchRequest.QueryExpansionSpec} request.queryExpansionSpec + * The query expansion specification that specifies the conditions under which + * query expansion occurs. For more information, see [Query + * expansion](https://cloud.google.com/retail/docs/result-size#query_expansion). + * @param {google.cloud.retail.v2alpha.SearchRequest.RelevanceThreshold} request.relevanceThreshold + * The relevance threshold of the search results. + * + * Defaults to + * {@link protos.google.cloud.retail.v2alpha.SearchRequest.RelevanceThreshold.HIGH|RelevanceThreshold.HIGH}, + * which means only the most relevant results are shown, and the least number + * of results are returned. For more information, see [Adjust result + * size](https://cloud.google.com/retail/docs/result-size#relevance_thresholding). + * @param {string[]} request.variantRollupKeys + * The keys to fetch and rollup the matching + * {@link protos.google.cloud.retail.v2alpha.Product.Type.VARIANT|variant} + * {@link protos.google.cloud.retail.v2alpha.Product|Product}s attributes, + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo|FulfillmentInfo} or + * {@link protos.google.cloud.retail.v2alpha.LocalInventory|LocalInventory}s attributes. + * The attributes from all the matching + * {@link protos.google.cloud.retail.v2alpha.Product.Type.VARIANT|variant} + * {@link protos.google.cloud.retail.v2alpha.Product|Product}s or + * {@link protos.google.cloud.retail.v2alpha.LocalInventory|LocalInventory}s are merged + * and de-duplicated. Notice that rollup attributes will lead to extra query + * latency. Maximum number of keys is 30. + * + * For {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo|FulfillmentInfo}, a + * fulfillment type and a fulfillment ID must be provided in the format of + * "fulfillmentType.fulfillmentId". E.g., in "pickupInStore.store123", + * "pickupInStore" is fulfillment type and "store123" is the store ID. + * + * Supported keys are: + * + * * colorFamilies + * * price + * * originalPrice + * * discount + * * variantId + * * inventory(place_id,price) + * * inventory(place_id,original_price) + * * inventory(place_id,attributes.key), where key is any key in the + * {@link protos.google.cloud.retail.v2alpha.LocalInventory.attributes|Product.local_inventories.attributes} + * map. + * * attributes.key, where key is any key in the + * {@link protos.google.cloud.retail.v2alpha.Product.attributes|Product.attributes} map. + * * pickupInStore.id, where id is any + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.place_ids|FulfillmentInfo.place_ids} + * for + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.type|FulfillmentInfo.type} + * "pickup-in-store". + * * shipToStore.id, where id is any + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.place_ids|FulfillmentInfo.place_ids} + * for + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.type|FulfillmentInfo.type} + * "ship-to-store". + * * sameDayDelivery.id, where id is any + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.place_ids|FulfillmentInfo.place_ids} + * for + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.type|FulfillmentInfo.type} + * "same-day-delivery". + * * nextDayDelivery.id, where id is any + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.place_ids|FulfillmentInfo.place_ids} + * for + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.type|FulfillmentInfo.type} + * "next-day-delivery". + * * customFulfillment1.id, where id is any + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.place_ids|FulfillmentInfo.place_ids} + * for + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.type|FulfillmentInfo.type} + * "custom-type-1". + * * customFulfillment2.id, where id is any + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.place_ids|FulfillmentInfo.place_ids} + * for + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.type|FulfillmentInfo.type} + * "custom-type-2". + * * customFulfillment3.id, where id is any + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.place_ids|FulfillmentInfo.place_ids} + * for + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.type|FulfillmentInfo.type} + * "custom-type-3". + * * customFulfillment4.id, where id is any + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.place_ids|FulfillmentInfo.place_ids} + * for + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.type|FulfillmentInfo.type} + * "custom-type-4". + * * customFulfillment5.id, where id is any + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.place_ids|FulfillmentInfo.place_ids} + * for + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.type|FulfillmentInfo.type} + * "custom-type-5". + * + * If this field is set to an invalid value other than these, an + * INVALID_ARGUMENT error is returned. + * @param {string[]} request.pageCategories + * The categories associated with a category page. Must be set for category + * navigation queries to achieve good search quality. The format should be + * the same as + * {@link protos.google.cloud.retail.v2alpha.UserEvent.page_categories|UserEvent.page_categories}; + * + * To represent full path of category, use '>' sign to separate different + * hierarchies. If '>' is part of the category name, replace it with + * other character(s). + * + * Category pages include special pages such as sales or promotions. For + * instance, a special sale page may have the category hierarchy: + * "pageCategories" : ["Sales > 2017 Black Friday Deals"]. + * @param {google.cloud.retail.v2alpha.SearchRequest.SearchMode} request.searchMode + * The search mode of the search request. If not specified, a single search + * request triggers both product search and faceted search. + * @param {google.cloud.retail.v2alpha.SearchRequest.PersonalizationSpec} request.personalizationSpec + * The specification for personalization. + * + * Notice that if both + * {@link protos.google.cloud.retail.v2alpha.ServingConfig.personalization_spec|ServingConfig.personalization_spec} + * and + * {@link protos.google.cloud.retail.v2alpha.SearchRequest.personalization_spec|SearchRequest.personalization_spec} + * are set. + * {@link protos.google.cloud.retail.v2alpha.SearchRequest.personalization_spec|SearchRequest.personalization_spec} + * will override + * {@link protos.google.cloud.retail.v2alpha.ServingConfig.personalization_spec|ServingConfig.personalization_spec}. + * @param {number[]} request.labels + * The labels applied to a resource must meet the following requirements: + * + * * Each resource can have multiple labels, up to a maximum of 64. + * * Each label must be a key-value pair. + * * Keys have a minimum length of 1 character and a maximum length of 63 + * characters and cannot be empty. Values can be empty and have a maximum + * length of 63 characters. + * * Keys and values can contain only lowercase letters, numeric characters, + * underscores, and dashes. All characters must use UTF-8 encoding, and + * international characters are allowed. + * * The key portion of a label must be unique. However, you can use the same + * key with multiple resources. + * * Keys must start with a lowercase letter or international character. + * + * For more information, see [Requirements for + * labels](https://cloud.google.com/resource-manager/docs/creating-managing-labels#requirements) + * in the Resource Manager documentation. + * @param {google.cloud.retail.v2alpha.SearchRequest.SpellCorrectionSpec} request.spellCorrectionSpec + * The spell correction specification that specifies the mode under + * which spell correction will take effect. + * @param {string} request.entity + * The entity for customers that may run multiple different entities, domains, + * sites or regions, for example, `Google US`, `Google Ads`, `Waymo`, + * `google.com`, `youtube.com`, etc. + * If this is set, it should be exactly matched with + * {@link protos.google.cloud.retail.v2alpha.UserEvent.entity|UserEvent.entity} to get + * search results boosted by entity. + * @param {google.cloud.retail.v2alpha.SearchRequest.ConversationalSearchSpec} [request.conversationalSearchSpec] + * Optional. This field specifies all conversational related parameters + * addition to traditional retail search. + * @param {google.cloud.retail.v2alpha.SearchRequest.TileNavigationSpec} [request.tileNavigationSpec] + * Optional. This field specifies tile navigation related parameters. + * @param {string} [request.languageCode] + * Optional. The BCP-47 language code, such as "en-US" or "sr-Latn" + * [list](https://www.unicode.org/cldr/charts/46/summary/root.html). For more + * information, see [Standardized codes](https://google.aip.dev/143). This + * field helps to better interpret the query. If a value isn't specified, the + * query language code is automatically detected, which may not be accurate. + * @param {string} [request.regionCode] + * Optional. The Unicode country/region code (CLDR) of a location, such as + * "US" and "419" + * [list](https://www.unicode.org/cldr/charts/46/supplemental/territory_information.html). + * For more information, see [Standardized codes](https://google.aip.dev/143). + * If set, then results will be boosted based on the region_code provided. + * @param {string} [request.placeId] + * Optional. An id corresponding to a place, such as a store id or region id. + * When specified, we use the price from the local inventory with the matching + * product's + * {@link protos.google.cloud.retail.v2alpha.LocalInventory.place_id|LocalInventory.place_id} + * for revenue optimization. + * @param {number[]} [request.userAttributes] + * Optional. The user attributes that could be used for personalization of + * search results. + * * Populate at most 100 key-value pairs per query. + * * Only supports string keys and repeated string values. + * * Duplcate keys are not allowed within a single query. + * + * Example: + * user_attributes: [ + * { key: "pets" + * value { + * values: "dog" + * values: "cat" + * } + * }, + * { key: "state" + * value { + * values: "CA" + * } + * } + * ] + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.cloud.retail.v2alpha.SearchResponse.SearchResult|SearchResult}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/search_service.search.js + * region_tag:retail_v2alpha_generated_SearchService_Search_async + */ searchAsync( - request?: protos.google.cloud.retail.v2alpha.ISearchRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.cloud.retail.v2alpha.ISearchRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'placement': request.placement ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + placement: request.placement ?? '', + }); const defaultCallSettings = this._defaults['search']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('search iterate %j', request); return this.descriptors.page.search.asyncIterate( this.innerApiCalls['search'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } // -------------------- @@ -1479,7 +1545,7 @@ export class SearchServiceClient { * @param {string} project * @returns {string} Resource name string. */ - alertConfigPath(project:string) { + alertConfigPath(project: string) { return this.pathTemplates.alertConfigPathTemplate.render({ project: project, }); @@ -1493,7 +1559,8 @@ export class SearchServiceClient { * @returns {string} A string representing the project. */ matchProjectFromAlertConfigName(alertConfigName: string) { - return this.pathTemplates.alertConfigPathTemplate.match(alertConfigName).project; + return this.pathTemplates.alertConfigPathTemplate.match(alertConfigName) + .project; } /** @@ -1504,7 +1571,7 @@ export class SearchServiceClient { * @param {string} catalog * @returns {string} Resource name string. */ - attributesConfigPath(project:string,location:string,catalog:string) { + attributesConfigPath(project: string, location: string, catalog: string) { return this.pathTemplates.attributesConfigPathTemplate.render({ project: project, location: location, @@ -1520,7 +1587,9 @@ export class SearchServiceClient { * @returns {string} A string representing the project. */ matchProjectFromAttributesConfigName(attributesConfigName: string) { - return this.pathTemplates.attributesConfigPathTemplate.match(attributesConfigName).project; + return this.pathTemplates.attributesConfigPathTemplate.match( + attributesConfigName, + ).project; } /** @@ -1531,7 +1600,9 @@ export class SearchServiceClient { * @returns {string} A string representing the location. */ matchLocationFromAttributesConfigName(attributesConfigName: string) { - return this.pathTemplates.attributesConfigPathTemplate.match(attributesConfigName).location; + return this.pathTemplates.attributesConfigPathTemplate.match( + attributesConfigName, + ).location; } /** @@ -1542,7 +1613,9 @@ export class SearchServiceClient { * @returns {string} A string representing the catalog. */ matchCatalogFromAttributesConfigName(attributesConfigName: string) { - return this.pathTemplates.attributesConfigPathTemplate.match(attributesConfigName).catalog; + return this.pathTemplates.attributesConfigPathTemplate.match( + attributesConfigName, + ).catalog; } /** @@ -1554,7 +1627,12 @@ export class SearchServiceClient { * @param {string} branch * @returns {string} Resource name string. */ - branchPath(project:string,location:string,catalog:string,branch:string) { + branchPath( + project: string, + location: string, + catalog: string, + branch: string, + ) { return this.pathTemplates.branchPathTemplate.render({ project: project, location: location, @@ -1615,7 +1693,7 @@ export class SearchServiceClient { * @param {string} catalog * @returns {string} Resource name string. */ - catalogPath(project:string,location:string,catalog:string) { + catalogPath(project: string, location: string, catalog: string) { return this.pathTemplates.catalogPathTemplate.render({ project: project, location: location, @@ -1664,7 +1742,7 @@ export class SearchServiceClient { * @param {string} catalog * @returns {string} Resource name string. */ - completionConfigPath(project:string,location:string,catalog:string) { + completionConfigPath(project: string, location: string, catalog: string) { return this.pathTemplates.completionConfigPathTemplate.render({ project: project, location: location, @@ -1680,7 +1758,9 @@ export class SearchServiceClient { * @returns {string} A string representing the project. */ matchProjectFromCompletionConfigName(completionConfigName: string) { - return this.pathTemplates.completionConfigPathTemplate.match(completionConfigName).project; + return this.pathTemplates.completionConfigPathTemplate.match( + completionConfigName, + ).project; } /** @@ -1691,7 +1771,9 @@ export class SearchServiceClient { * @returns {string} A string representing the location. */ matchLocationFromCompletionConfigName(completionConfigName: string) { - return this.pathTemplates.completionConfigPathTemplate.match(completionConfigName).location; + return this.pathTemplates.completionConfigPathTemplate.match( + completionConfigName, + ).location; } /** @@ -1702,7 +1784,9 @@ export class SearchServiceClient { * @returns {string} A string representing the catalog. */ matchCatalogFromCompletionConfigName(completionConfigName: string) { - return this.pathTemplates.completionConfigPathTemplate.match(completionConfigName).catalog; + return this.pathTemplates.completionConfigPathTemplate.match( + completionConfigName, + ).catalog; } /** @@ -1714,7 +1798,12 @@ export class SearchServiceClient { * @param {string} control * @returns {string} Resource name string. */ - controlPath(project:string,location:string,catalog:string,control:string) { + controlPath( + project: string, + location: string, + catalog: string, + control: string, + ) { return this.pathTemplates.controlPathTemplate.render({ project: project, location: location, @@ -1776,7 +1865,12 @@ export class SearchServiceClient { * @param {string} experiment * @returns {string} Resource name string. */ - experimentPath(project:string,location:string,catalog:string,experiment:string) { + experimentPath( + project: string, + location: string, + catalog: string, + experiment: string, + ) { return this.pathTemplates.experimentPathTemplate.render({ project: project, location: location, @@ -1793,7 +1887,8 @@ export class SearchServiceClient { * @returns {string} A string representing the project. */ matchProjectFromExperimentName(experimentName: string) { - return this.pathTemplates.experimentPathTemplate.match(experimentName).project; + return this.pathTemplates.experimentPathTemplate.match(experimentName) + .project; } /** @@ -1804,7 +1899,8 @@ export class SearchServiceClient { * @returns {string} A string representing the location. */ matchLocationFromExperimentName(experimentName: string) { - return this.pathTemplates.experimentPathTemplate.match(experimentName).location; + return this.pathTemplates.experimentPathTemplate.match(experimentName) + .location; } /** @@ -1815,7 +1911,8 @@ export class SearchServiceClient { * @returns {string} A string representing the catalog. */ matchCatalogFromExperimentName(experimentName: string) { - return this.pathTemplates.experimentPathTemplate.match(experimentName).catalog; + return this.pathTemplates.experimentPathTemplate.match(experimentName) + .catalog; } /** @@ -1826,7 +1923,8 @@ export class SearchServiceClient { * @returns {string} A string representing the experiment. */ matchExperimentFromExperimentName(experimentName: string) { - return this.pathTemplates.experimentPathTemplate.match(experimentName).experiment; + return this.pathTemplates.experimentPathTemplate.match(experimentName) + .experiment; } /** @@ -1835,7 +1933,7 @@ export class SearchServiceClient { * @param {string} project * @returns {string} Resource name string. */ - loggingConfigPath(project:string) { + loggingConfigPath(project: string) { return this.pathTemplates.loggingConfigPathTemplate.render({ project: project, }); @@ -1849,7 +1947,8 @@ export class SearchServiceClient { * @returns {string} A string representing the project. */ matchProjectFromLoggingConfigName(loggingConfigName: string) { - return this.pathTemplates.loggingConfigPathTemplate.match(loggingConfigName).project; + return this.pathTemplates.loggingConfigPathTemplate.match(loggingConfigName) + .project; } /** @@ -1861,7 +1960,12 @@ export class SearchServiceClient { * @param {string} merchant_center_account_link * @returns {string} Resource name string. */ - merchantCenterAccountLinkPath(project:string,location:string,catalog:string,merchantCenterAccountLink:string) { + merchantCenterAccountLinkPath( + project: string, + location: string, + catalog: string, + merchantCenterAccountLink: string, + ) { return this.pathTemplates.merchantCenterAccountLinkPathTemplate.render({ project: project, location: location, @@ -1877,8 +1981,12 @@ export class SearchServiceClient { * A fully-qualified path representing MerchantCenterAccountLink resource. * @returns {string} A string representing the project. */ - matchProjectFromMerchantCenterAccountLinkName(merchantCenterAccountLinkName: string) { - return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match(merchantCenterAccountLinkName).project; + matchProjectFromMerchantCenterAccountLinkName( + merchantCenterAccountLinkName: string, + ) { + return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match( + merchantCenterAccountLinkName, + ).project; } /** @@ -1888,8 +1996,12 @@ export class SearchServiceClient { * A fully-qualified path representing MerchantCenterAccountLink resource. * @returns {string} A string representing the location. */ - matchLocationFromMerchantCenterAccountLinkName(merchantCenterAccountLinkName: string) { - return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match(merchantCenterAccountLinkName).location; + matchLocationFromMerchantCenterAccountLinkName( + merchantCenterAccountLinkName: string, + ) { + return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match( + merchantCenterAccountLinkName, + ).location; } /** @@ -1899,8 +2011,12 @@ export class SearchServiceClient { * A fully-qualified path representing MerchantCenterAccountLink resource. * @returns {string} A string representing the catalog. */ - matchCatalogFromMerchantCenterAccountLinkName(merchantCenterAccountLinkName: string) { - return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match(merchantCenterAccountLinkName).catalog; + matchCatalogFromMerchantCenterAccountLinkName( + merchantCenterAccountLinkName: string, + ) { + return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match( + merchantCenterAccountLinkName, + ).catalog; } /** @@ -1910,8 +2026,12 @@ export class SearchServiceClient { * A fully-qualified path representing MerchantCenterAccountLink resource. * @returns {string} A string representing the merchant_center_account_link. */ - matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName(merchantCenterAccountLinkName: string) { - return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match(merchantCenterAccountLinkName).merchant_center_account_link; + matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName( + merchantCenterAccountLinkName: string, + ) { + return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match( + merchantCenterAccountLinkName, + ).merchant_center_account_link; } /** @@ -1923,7 +2043,7 @@ export class SearchServiceClient { * @param {string} model * @returns {string} Resource name string. */ - modelPath(project:string,location:string,catalog:string,model:string) { + modelPath(project: string, location: string, catalog: string, model: string) { return this.pathTemplates.modelPathTemplate.render({ project: project, location: location, @@ -1986,7 +2106,13 @@ export class SearchServiceClient { * @param {string} product * @returns {string} Resource name string. */ - productPath(project:string,location:string,catalog:string,branch:string,product:string) { + productPath( + project: string, + location: string, + catalog: string, + branch: string, + product: string, + ) { return this.pathTemplates.productPathTemplate.render({ project: project, location: location, @@ -2057,7 +2183,7 @@ export class SearchServiceClient { * @param {string} project * @returns {string} Resource name string. */ - retailProjectPath(project:string) { + retailProjectPath(project: string) { return this.pathTemplates.retailProjectPathTemplate.render({ project: project, }); @@ -2071,7 +2197,8 @@ export class SearchServiceClient { * @returns {string} A string representing the project. */ matchProjectFromRetailProjectName(retailProjectName: string) { - return this.pathTemplates.retailProjectPathTemplate.match(retailProjectName).project; + return this.pathTemplates.retailProjectPathTemplate.match(retailProjectName) + .project; } /** @@ -2083,7 +2210,12 @@ export class SearchServiceClient { * @param {string} serving_config * @returns {string} Resource name string. */ - servingConfigPath(project:string,location:string,catalog:string,servingConfig:string) { + servingConfigPath( + project: string, + location: string, + catalog: string, + servingConfig: string, + ) { return this.pathTemplates.servingConfigPathTemplate.render({ project: project, location: location, @@ -2100,7 +2232,8 @@ export class SearchServiceClient { * @returns {string} A string representing the project. */ matchProjectFromServingConfigName(servingConfigName: string) { - return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName).project; + return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName) + .project; } /** @@ -2111,7 +2244,8 @@ export class SearchServiceClient { * @returns {string} A string representing the location. */ matchLocationFromServingConfigName(servingConfigName: string) { - return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName).location; + return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName) + .location; } /** @@ -2122,7 +2256,8 @@ export class SearchServiceClient { * @returns {string} A string representing the catalog. */ matchCatalogFromServingConfigName(servingConfigName: string) { - return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName).catalog; + return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName) + .catalog; } /** @@ -2133,7 +2268,8 @@ export class SearchServiceClient { * @returns {string} A string representing the serving_config. */ matchServingConfigFromServingConfigName(servingConfigName: string) { - return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName).serving_config; + return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName) + .serving_config; } /** @@ -2144,7 +2280,7 @@ export class SearchServiceClient { */ close(): Promise { if (this.searchServiceStub && !this._terminated) { - return this.searchServiceStub.then(stub => { + return this.searchServiceStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -2152,4 +2288,4 @@ export class SearchServiceClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/src/v2alpha/serving_config_service_client.ts.baseline b/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/src/v2alpha/serving_config_service_client.ts.baseline index 1c15ebee1c9f..fb28034905f1 100644 --- a/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/src/v2alpha/serving_config_service_client.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/src/v2alpha/serving_config_service_client.ts.baseline @@ -18,15 +18,22 @@ /* global window */ import * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions, PaginationCallback, GaxCall} from 'google-gax'; -import {Transform} from 'stream'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + PaginationCallback, + GaxCall, +} from 'google-gax'; +import { Transform } from 'stream'; // @ts-ignore import type * as protos from '../../../protos/protos.js'; import * as serving_config_service_client_config from './serving_config_service_client_config.json'; import fs from 'fs'; import path from 'path'; -import {fileURLToPath} from 'url'; -import {getJSON} from '../json-helper.cjs'; +import { fileURLToPath } from 'url'; +import { getJSON } from '../json-helper.cjs'; // @ts-ignore const dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -36,15 +43,15 @@ const dirname = path.dirname(fileURLToPath(import.meta.url)); * This file defines retry strategy and timeouts for all API methods in this library. */ const gapicConfig = getJSON( - path.join(dirname, 'serving_config_service_client_config.json') + path.join(dirname, 'serving_config_service_client_config.json'), ); const jsonProtos = getJSON( - path.join(dirname, '..', '..', '..', 'protos/protos.json') + path.join(dirname, '..', '..', '..', 'protos/protos.json'), ); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; const version = getJSON( - path.join(dirname, '..', '..', '..', '..', 'package.json') + path.join(dirname, '..', '..', '..', '..', 'package.json'), ).version; /** @@ -59,7 +66,7 @@ export class ServingConfigServiceClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('retail'); @@ -71,9 +78,9 @@ export class ServingConfigServiceClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; - servingConfigServiceStub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; + servingConfigServiceStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of ServingConfigServiceClient. @@ -115,21 +122,42 @@ export class ServingConfigServiceClient { * const client = new ServingConfigServiceClient({fallback: 'rest'}, gax); * ``` */ - constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { // Ensure that options include all the required fields. const staticMembers = this.constructor as typeof ServingConfigServiceClient; - if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { - throw new Error('Please set either universe_domain or universeDomain, but not both.'); + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); } - const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; - this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; this._servicePath = 'retail.' + this._universeDomain; - const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; - const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. if (servicePath !== this._servicePath && !('scopes' in opts)) { @@ -151,7 +179,7 @@ export class ServingConfigServiceClient { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; @@ -168,10 +196,7 @@ export class ServingConfigServiceClient { const isEsm = true; const isEsmString = isEsm ? '-esm' : '-cjs'; // Determine the client header string. - const clientHeader = [ - `gax/${this._gaxModule.version}`, - `gapic/${version}`, - ]; + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/{process.versions.node}${isEsmString}`); } else { @@ -179,7 +204,7 @@ export class ServingConfigServiceClient { } if (!opts.fallback) { clientHeader.push(`grpc/${this._gaxGrpc.grpcVersion}`); - } else if (opts.fallback === 'rest' ) { + } else if (opts.fallback === 'rest') { clientHeader.push(`rest/${this._gaxGrpc.grpcVersion}`); } if (opts.libName && opts.libVersion) { @@ -187,47 +212,49 @@ export class ServingConfigServiceClient { } // Load the applicable protos. - this._protos = this._gaxGrpc.loadProtoJSON(jsonProtos as gax.protobuf.INamespace); + this._protos = this._gaxGrpc.loadProtoJSON( + jsonProtos as gax.protobuf.INamespace, + ); // This API contains "path templates"; forward-slash-separated // identifiers to uniquely identify resources within the API. // Create useful helper objects for these. this.pathTemplates = { alertConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/alertConfig' + 'projects/{project}/alertConfig', ), attributesConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/attributesConfig' + 'projects/{project}/locations/{location}/catalogs/{catalog}/attributesConfig', ), branchPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}', ), catalogPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}' + 'projects/{project}/locations/{location}/catalogs/{catalog}', ), completionConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/completionConfig' + 'projects/{project}/locations/{location}/catalogs/{catalog}/completionConfig', ), controlPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/controls/{control}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/controls/{control}', ), loggingConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/loggingConfig' + 'projects/{project}/loggingConfig', ), merchantCenterAccountLinkPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/merchantCenterAccountLinks/{merchant_center_account_link}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/merchantCenterAccountLinks/{merchant_center_account_link}', ), modelPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/models/{model}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/models/{model}', ), productPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}', ), retailProjectPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/retailProject' + 'projects/{project}/retailProject', ), servingConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/servingConfigs/{serving_config}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/servingConfigs/{serving_config}', ), }; @@ -235,14 +262,20 @@ export class ServingConfigServiceClient { // (e.g. 50 results at a time, with tokens to get subsequent // pages). Denote the keys used for pagination and results. this.descriptors.page = { - listServingConfigs: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'servingConfigs') + listServingConfigs: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'servingConfigs', + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.cloud.retail.v2alpha.ServingConfigService', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.cloud.retail.v2alpha.ServingConfigService', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + { 'x-goog-api-client': clientHeader.join(' ') }, + ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -273,37 +306,49 @@ export class ServingConfigServiceClient { // Put together the "service stub" for // google.cloud.retail.v2alpha.ServingConfigService. this.servingConfigServiceStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.cloud.retail.v2alpha.ServingConfigService') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any - (this._protos as any).google.cloud.retail.v2alpha.ServingConfigService, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.cloud.retail.v2alpha.ServingConfigService', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any + (this._protos as any).google.cloud.retail.v2alpha + .ServingConfigService, + this._opts, + this._providedCustomServicePath, + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const servingConfigServiceStubMethods = - ['createServingConfig', 'deleteServingConfig', 'updateServingConfig', 'getServingConfig', 'listServingConfigs', 'addControl', 'removeControl']; + const servingConfigServiceStubMethods = [ + 'createServingConfig', + 'deleteServingConfig', + 'updateServingConfig', + 'getServingConfig', + 'listServingConfigs', + 'addControl', + 'removeControl', + ]; for (const methodName of servingConfigServiceStubMethods) { const callPromise = this.servingConfigServiceStub.then( - stub => (...args: Array<{}>) => { - if (this._terminated) { - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error|null|undefined) => () => { + (stub) => + (...args: Array<{}>) => { + if (this._terminated) { + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { throw err; - }); + }, + ); - const descriptor = - this.descriptors.page[methodName] || - undefined; + const descriptor = this.descriptors.page[methodName] || undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -318,8 +363,14 @@ export class ServingConfigServiceClient { * @returns {string} The DNS address for this service. */ static get servicePath() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'retail.googleapis.com'; } @@ -331,8 +382,14 @@ export class ServingConfigServiceClient { * @returns {string} The DNS address for this service. */ static get apiEndpoint() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'retail.googleapis.com'; } @@ -363,9 +420,7 @@ export class ServingConfigServiceClient { * @returns {string[]} List of default scopes. */ static get scopes() { - return [ - 'https://www.googleapis.com/auth/cloud-platform' - ]; + return ['https://www.googleapis.com/auth/cloud-platform']; } getProjectId(): Promise; @@ -374,8 +429,9 @@ export class ServingConfigServiceClient { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId(callback?: Callback): - Promise|void { + getProjectId( + callback?: Callback, + ): Promise | void { if (callback) { this.auth.getProjectId(callback); return; @@ -386,695 +442,990 @@ export class ServingConfigServiceClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Creates a ServingConfig. - * - * A maximum of 100 - * {@link protos.google.cloud.retail.v2alpha.ServingConfig|ServingConfig}s are allowed in - * a {@link protos.google.cloud.retail.v2alpha.Catalog|Catalog}, otherwise a - * FAILED_PRECONDITION error is returned. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. Full resource name of parent. Format: - * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}` - * @param {google.cloud.retail.v2alpha.ServingConfig} request.servingConfig - * Required. The ServingConfig to create. - * @param {string} request.servingConfigId - * Required. The ID to use for the ServingConfig, which will become the final - * component of the ServingConfig's resource name. - * - * This value should be 4-63 characters, and valid characters - * are /{@link protos.0-9|a-z}-_/. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.ServingConfig|ServingConfig}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/serving_config_service.create_serving_config.js - * region_tag:retail_v2alpha_generated_ServingConfigService_CreateServingConfig_async - */ + /** + * Creates a ServingConfig. + * + * A maximum of 100 + * {@link protos.google.cloud.retail.v2alpha.ServingConfig|ServingConfig}s are allowed in + * a {@link protos.google.cloud.retail.v2alpha.Catalog|Catalog}, otherwise a + * FAILED_PRECONDITION error is returned. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Full resource name of parent. Format: + * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}` + * @param {google.cloud.retail.v2alpha.ServingConfig} request.servingConfig + * Required. The ServingConfig to create. + * @param {string} request.servingConfigId + * Required. The ID to use for the ServingConfig, which will become the final + * component of the ServingConfig's resource name. + * + * This value should be 4-63 characters, and valid characters + * are /{@link protos.0-9|a-z}-_/. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.ServingConfig|ServingConfig}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/serving_config_service.create_serving_config.js + * region_tag:retail_v2alpha_generated_ServingConfigService_CreateServingConfig_async + */ createServingConfig( - request?: protos.google.cloud.retail.v2alpha.ICreateServingConfigRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.retail.v2alpha.IServingConfig, - protos.google.cloud.retail.v2alpha.ICreateServingConfigRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.ICreateServingConfigRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IServingConfig, + ( + | protos.google.cloud.retail.v2alpha.ICreateServingConfigRequest + | undefined + ), + {} | undefined, + ] + >; createServingConfig( - request: protos.google.cloud.retail.v2alpha.ICreateServingConfigRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.retail.v2alpha.IServingConfig, - protos.google.cloud.retail.v2alpha.ICreateServingConfigRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.ICreateServingConfigRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.retail.v2alpha.IServingConfig, + | protos.google.cloud.retail.v2alpha.ICreateServingConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createServingConfig( - request: protos.google.cloud.retail.v2alpha.ICreateServingConfigRequest, - callback: Callback< - protos.google.cloud.retail.v2alpha.IServingConfig, - protos.google.cloud.retail.v2alpha.ICreateServingConfigRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.ICreateServingConfigRequest, + callback: Callback< + protos.google.cloud.retail.v2alpha.IServingConfig, + | protos.google.cloud.retail.v2alpha.ICreateServingConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createServingConfig( - request?: protos.google.cloud.retail.v2alpha.ICreateServingConfigRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.cloud.retail.v2alpha.ICreateServingConfigRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.retail.v2alpha.IServingConfig, - protos.google.cloud.retail.v2alpha.ICreateServingConfigRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.cloud.retail.v2alpha.IServingConfig, - protos.google.cloud.retail.v2alpha.ICreateServingConfigRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.retail.v2alpha.IServingConfig, - protos.google.cloud.retail.v2alpha.ICreateServingConfigRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.retail.v2alpha.ICreateServingConfigRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.retail.v2alpha.IServingConfig, + | protos.google.cloud.retail.v2alpha.ICreateServingConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IServingConfig, + ( + | protos.google.cloud.retail.v2alpha.ICreateServingConfigRequest + | undefined + ), + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('createServingConfig request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.retail.v2alpha.IServingConfig, - protos.google.cloud.retail.v2alpha.ICreateServingConfigRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.retail.v2alpha.IServingConfig, + | protos.google.cloud.retail.v2alpha.ICreateServingConfigRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createServingConfig response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.createServingConfig(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.retail.v2alpha.IServingConfig, - protos.google.cloud.retail.v2alpha.ICreateServingConfigRequest|undefined, {}|undefined - ]) => { - this._log.info('createServingConfig response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createServingConfig(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.retail.v2alpha.IServingConfig, + ( + | protos.google.cloud.retail.v2alpha.ICreateServingConfigRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('createServingConfig response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Deletes a ServingConfig. - * - * Returns a NotFound error if the ServingConfig does not exist. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The resource name of the ServingConfig to delete. Format: - * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id}` - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/serving_config_service.delete_serving_config.js - * region_tag:retail_v2alpha_generated_ServingConfigService_DeleteServingConfig_async - */ + /** + * Deletes a ServingConfig. + * + * Returns a NotFound error if the ServingConfig does not exist. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The resource name of the ServingConfig to delete. Format: + * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id}` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/serving_config_service.delete_serving_config.js + * region_tag:retail_v2alpha_generated_ServingConfigService_DeleteServingConfig_async + */ deleteServingConfig( - request?: protos.google.cloud.retail.v2alpha.IDeleteServingConfigRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.cloud.retail.v2alpha.IDeleteServingConfigRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.IDeleteServingConfigRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.cloud.retail.v2alpha.IDeleteServingConfigRequest + | undefined + ), + {} | undefined, + ] + >; deleteServingConfig( - request: protos.google.cloud.retail.v2alpha.IDeleteServingConfigRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.cloud.retail.v2alpha.IDeleteServingConfigRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IDeleteServingConfigRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.cloud.retail.v2alpha.IDeleteServingConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteServingConfig( - request: protos.google.cloud.retail.v2alpha.IDeleteServingConfigRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.cloud.retail.v2alpha.IDeleteServingConfigRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IDeleteServingConfigRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.cloud.retail.v2alpha.IDeleteServingConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteServingConfig( - request?: protos.google.cloud.retail.v2alpha.IDeleteServingConfigRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.cloud.retail.v2alpha.IDeleteServingConfigRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.cloud.retail.v2alpha.IDeleteServingConfigRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.protobuf.IEmpty, - protos.google.cloud.retail.v2alpha.IDeleteServingConfigRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.cloud.retail.v2alpha.IDeleteServingConfigRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.retail.v2alpha.IDeleteServingConfigRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + | protos.google.cloud.retail.v2alpha.IDeleteServingConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.cloud.retail.v2alpha.IDeleteServingConfigRequest + | undefined + ), + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('deleteServingConfig request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.cloud.retail.v2alpha.IDeleteServingConfigRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.cloud.retail.v2alpha.IDeleteServingConfigRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteServingConfig response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.deleteServingConfig(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.cloud.retail.v2alpha.IDeleteServingConfigRequest|undefined, {}|undefined - ]) => { - this._log.info('deleteServingConfig response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteServingConfig(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + ( + | protos.google.cloud.retail.v2alpha.IDeleteServingConfigRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('deleteServingConfig response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Updates a ServingConfig. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.cloud.retail.v2alpha.ServingConfig} request.servingConfig - * Required. The ServingConfig to update. - * @param {google.protobuf.FieldMask} request.updateMask - * Indicates which fields in the provided - * {@link protos.google.cloud.retail.v2alpha.ServingConfig|ServingConfig} to update. The - * following are NOT supported: - * - * * {@link protos.google.cloud.retail.v2alpha.ServingConfig.name|ServingConfig.name} - * - * If not set, all supported fields are updated. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.ServingConfig|ServingConfig}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/serving_config_service.update_serving_config.js - * region_tag:retail_v2alpha_generated_ServingConfigService_UpdateServingConfig_async - */ + /** + * Updates a ServingConfig. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.cloud.retail.v2alpha.ServingConfig} request.servingConfig + * Required. The ServingConfig to update. + * @param {google.protobuf.FieldMask} request.updateMask + * Indicates which fields in the provided + * {@link protos.google.cloud.retail.v2alpha.ServingConfig|ServingConfig} to update. The + * following are NOT supported: + * + * * {@link protos.google.cloud.retail.v2alpha.ServingConfig.name|ServingConfig.name} + * + * If not set, all supported fields are updated. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.ServingConfig|ServingConfig}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/serving_config_service.update_serving_config.js + * region_tag:retail_v2alpha_generated_ServingConfigService_UpdateServingConfig_async + */ updateServingConfig( - request?: protos.google.cloud.retail.v2alpha.IUpdateServingConfigRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.retail.v2alpha.IServingConfig, - protos.google.cloud.retail.v2alpha.IUpdateServingConfigRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.IUpdateServingConfigRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IServingConfig, + ( + | protos.google.cloud.retail.v2alpha.IUpdateServingConfigRequest + | undefined + ), + {} | undefined, + ] + >; updateServingConfig( - request: protos.google.cloud.retail.v2alpha.IUpdateServingConfigRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.retail.v2alpha.IServingConfig, - protos.google.cloud.retail.v2alpha.IUpdateServingConfigRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IUpdateServingConfigRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.retail.v2alpha.IServingConfig, + | protos.google.cloud.retail.v2alpha.IUpdateServingConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateServingConfig( - request: protos.google.cloud.retail.v2alpha.IUpdateServingConfigRequest, - callback: Callback< - protos.google.cloud.retail.v2alpha.IServingConfig, - protos.google.cloud.retail.v2alpha.IUpdateServingConfigRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IUpdateServingConfigRequest, + callback: Callback< + protos.google.cloud.retail.v2alpha.IServingConfig, + | protos.google.cloud.retail.v2alpha.IUpdateServingConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateServingConfig( - request?: protos.google.cloud.retail.v2alpha.IUpdateServingConfigRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.retail.v2alpha.IServingConfig, - protos.google.cloud.retail.v2alpha.IUpdateServingConfigRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.retail.v2alpha.IUpdateServingConfigRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.retail.v2alpha.IServingConfig, - protos.google.cloud.retail.v2alpha.IUpdateServingConfigRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.retail.v2alpha.IServingConfig, - protos.google.cloud.retail.v2alpha.IUpdateServingConfigRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.retail.v2alpha.IUpdateServingConfigRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.retail.v2alpha.IServingConfig, + | protos.google.cloud.retail.v2alpha.IUpdateServingConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IServingConfig, + ( + | protos.google.cloud.retail.v2alpha.IUpdateServingConfigRequest + | undefined + ), + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'serving_config.name': request.servingConfig!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'serving_config.name': request.servingConfig!.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateServingConfig request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.retail.v2alpha.IServingConfig, - protos.google.cloud.retail.v2alpha.IUpdateServingConfigRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.retail.v2alpha.IServingConfig, + | protos.google.cloud.retail.v2alpha.IUpdateServingConfigRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateServingConfig response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.updateServingConfig(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.retail.v2alpha.IServingConfig, - protos.google.cloud.retail.v2alpha.IUpdateServingConfigRequest|undefined, {}|undefined - ]) => { - this._log.info('updateServingConfig response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateServingConfig(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.retail.v2alpha.IServingConfig, + ( + | protos.google.cloud.retail.v2alpha.IUpdateServingConfigRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('updateServingConfig response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Gets a ServingConfig. - * - * Returns a NotFound error if the ServingConfig does not exist. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The resource name of the ServingConfig to get. Format: - * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id}` - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.ServingConfig|ServingConfig}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/serving_config_service.get_serving_config.js - * region_tag:retail_v2alpha_generated_ServingConfigService_GetServingConfig_async - */ + /** + * Gets a ServingConfig. + * + * Returns a NotFound error if the ServingConfig does not exist. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The resource name of the ServingConfig to get. Format: + * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id}` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.ServingConfig|ServingConfig}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/serving_config_service.get_serving_config.js + * region_tag:retail_v2alpha_generated_ServingConfigService_GetServingConfig_async + */ getServingConfig( - request?: protos.google.cloud.retail.v2alpha.IGetServingConfigRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.retail.v2alpha.IServingConfig, - protos.google.cloud.retail.v2alpha.IGetServingConfigRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.IGetServingConfigRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IServingConfig, + protos.google.cloud.retail.v2alpha.IGetServingConfigRequest | undefined, + {} | undefined, + ] + >; getServingConfig( - request: protos.google.cloud.retail.v2alpha.IGetServingConfigRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.retail.v2alpha.IServingConfig, - protos.google.cloud.retail.v2alpha.IGetServingConfigRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IGetServingConfigRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.retail.v2alpha.IServingConfig, + | protos.google.cloud.retail.v2alpha.IGetServingConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getServingConfig( - request: protos.google.cloud.retail.v2alpha.IGetServingConfigRequest, - callback: Callback< - protos.google.cloud.retail.v2alpha.IServingConfig, - protos.google.cloud.retail.v2alpha.IGetServingConfigRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IGetServingConfigRequest, + callback: Callback< + protos.google.cloud.retail.v2alpha.IServingConfig, + | protos.google.cloud.retail.v2alpha.IGetServingConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getServingConfig( - request?: protos.google.cloud.retail.v2alpha.IGetServingConfigRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.cloud.retail.v2alpha.IGetServingConfigRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.retail.v2alpha.IServingConfig, - protos.google.cloud.retail.v2alpha.IGetServingConfigRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.cloud.retail.v2alpha.IServingConfig, - protos.google.cloud.retail.v2alpha.IGetServingConfigRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.retail.v2alpha.IServingConfig, - protos.google.cloud.retail.v2alpha.IGetServingConfigRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.retail.v2alpha.IGetServingConfigRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.retail.v2alpha.IServingConfig, + | protos.google.cloud.retail.v2alpha.IGetServingConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IServingConfig, + protos.google.cloud.retail.v2alpha.IGetServingConfigRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getServingConfig request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.retail.v2alpha.IServingConfig, - protos.google.cloud.retail.v2alpha.IGetServingConfigRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.retail.v2alpha.IServingConfig, + | protos.google.cloud.retail.v2alpha.IGetServingConfigRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getServingConfig response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.getServingConfig(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.retail.v2alpha.IServingConfig, - protos.google.cloud.retail.v2alpha.IGetServingConfigRequest|undefined, {}|undefined - ]) => { - this._log.info('getServingConfig response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getServingConfig(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.retail.v2alpha.IServingConfig, + ( + | protos.google.cloud.retail.v2alpha.IGetServingConfigRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('getServingConfig response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Enables a Control on the specified ServingConfig. - * The control is added in the last position of the list of controls - * it belongs to (e.g. if it's a facet spec control it will be applied - * in the last position of servingConfig.facetSpecIds) - * Returns a ALREADY_EXISTS error if the control has already been applied. - * Returns a FAILED_PRECONDITION error if the addition could exceed maximum - * number of control allowed for that type of control. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.servingConfig - * Required. The source ServingConfig resource name . Format: - * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id}` - * @param {string} request.controlId - * Required. The id of the control to apply. Assumed to be in the same catalog - * as the serving config - if id is not found a NOT_FOUND error is returned. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.ServingConfig|ServingConfig}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/serving_config_service.add_control.js - * region_tag:retail_v2alpha_generated_ServingConfigService_AddControl_async - */ + /** + * Enables a Control on the specified ServingConfig. + * The control is added in the last position of the list of controls + * it belongs to (e.g. if it's a facet spec control it will be applied + * in the last position of servingConfig.facetSpecIds) + * Returns a ALREADY_EXISTS error if the control has already been applied. + * Returns a FAILED_PRECONDITION error if the addition could exceed maximum + * number of control allowed for that type of control. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.servingConfig + * Required. The source ServingConfig resource name . Format: + * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id}` + * @param {string} request.controlId + * Required. The id of the control to apply. Assumed to be in the same catalog + * as the serving config - if id is not found a NOT_FOUND error is returned. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.ServingConfig|ServingConfig}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/serving_config_service.add_control.js + * region_tag:retail_v2alpha_generated_ServingConfigService_AddControl_async + */ addControl( - request?: protos.google.cloud.retail.v2alpha.IAddControlRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.retail.v2alpha.IServingConfig, - protos.google.cloud.retail.v2alpha.IAddControlRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.IAddControlRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IServingConfig, + protos.google.cloud.retail.v2alpha.IAddControlRequest | undefined, + {} | undefined, + ] + >; addControl( - request: protos.google.cloud.retail.v2alpha.IAddControlRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.retail.v2alpha.IServingConfig, - protos.google.cloud.retail.v2alpha.IAddControlRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IAddControlRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.retail.v2alpha.IServingConfig, + protos.google.cloud.retail.v2alpha.IAddControlRequest | null | undefined, + {} | null | undefined + >, + ): void; addControl( - request: protos.google.cloud.retail.v2alpha.IAddControlRequest, - callback: Callback< - protos.google.cloud.retail.v2alpha.IServingConfig, - protos.google.cloud.retail.v2alpha.IAddControlRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IAddControlRequest, + callback: Callback< + protos.google.cloud.retail.v2alpha.IServingConfig, + protos.google.cloud.retail.v2alpha.IAddControlRequest | null | undefined, + {} | null | undefined + >, + ): void; addControl( - request?: protos.google.cloud.retail.v2alpha.IAddControlRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.retail.v2alpha.IServingConfig, - protos.google.cloud.retail.v2alpha.IAddControlRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.retail.v2alpha.IAddControlRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.retail.v2alpha.IServingConfig, - protos.google.cloud.retail.v2alpha.IAddControlRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.retail.v2alpha.IServingConfig, - protos.google.cloud.retail.v2alpha.IAddControlRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.retail.v2alpha.IAddControlRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.retail.v2alpha.IServingConfig, + protos.google.cloud.retail.v2alpha.IAddControlRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IServingConfig, + protos.google.cloud.retail.v2alpha.IAddControlRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'serving_config': request.servingConfig ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + serving_config: request.servingConfig ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('addControl request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.retail.v2alpha.IServingConfig, - protos.google.cloud.retail.v2alpha.IAddControlRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.retail.v2alpha.IServingConfig, + | protos.google.cloud.retail.v2alpha.IAddControlRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('addControl response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.addControl(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.retail.v2alpha.IServingConfig, - protos.google.cloud.retail.v2alpha.IAddControlRequest|undefined, {}|undefined - ]) => { - this._log.info('addControl response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .addControl(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.retail.v2alpha.IServingConfig, + protos.google.cloud.retail.v2alpha.IAddControlRequest | undefined, + {} | undefined, + ]) => { + this._log.info('addControl response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Disables a Control on the specified ServingConfig. - * The control is removed from the ServingConfig. - * Returns a NOT_FOUND error if the Control is not enabled for the - * ServingConfig. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.servingConfig - * Required. The source ServingConfig resource name . Format: - * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id}` - * @param {string} request.controlId - * Required. The id of the control to apply. Assumed to be in the same catalog - * as the serving config. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.ServingConfig|ServingConfig}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/serving_config_service.remove_control.js - * region_tag:retail_v2alpha_generated_ServingConfigService_RemoveControl_async - */ + /** + * Disables a Control on the specified ServingConfig. + * The control is removed from the ServingConfig. + * Returns a NOT_FOUND error if the Control is not enabled for the + * ServingConfig. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.servingConfig + * Required. The source ServingConfig resource name . Format: + * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id}` + * @param {string} request.controlId + * Required. The id of the control to apply. Assumed to be in the same catalog + * as the serving config. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.ServingConfig|ServingConfig}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/serving_config_service.remove_control.js + * region_tag:retail_v2alpha_generated_ServingConfigService_RemoveControl_async + */ removeControl( - request?: protos.google.cloud.retail.v2alpha.IRemoveControlRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.retail.v2alpha.IServingConfig, - protos.google.cloud.retail.v2alpha.IRemoveControlRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.IRemoveControlRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IServingConfig, + protos.google.cloud.retail.v2alpha.IRemoveControlRequest | undefined, + {} | undefined, + ] + >; removeControl( - request: protos.google.cloud.retail.v2alpha.IRemoveControlRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.retail.v2alpha.IServingConfig, - protos.google.cloud.retail.v2alpha.IRemoveControlRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IRemoveControlRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.retail.v2alpha.IServingConfig, + | protos.google.cloud.retail.v2alpha.IRemoveControlRequest + | null + | undefined, + {} | null | undefined + >, + ): void; removeControl( - request: protos.google.cloud.retail.v2alpha.IRemoveControlRequest, - callback: Callback< - protos.google.cloud.retail.v2alpha.IServingConfig, - protos.google.cloud.retail.v2alpha.IRemoveControlRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IRemoveControlRequest, + callback: Callback< + protos.google.cloud.retail.v2alpha.IServingConfig, + | protos.google.cloud.retail.v2alpha.IRemoveControlRequest + | null + | undefined, + {} | null | undefined + >, + ): void; removeControl( - request?: protos.google.cloud.retail.v2alpha.IRemoveControlRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.cloud.retail.v2alpha.IRemoveControlRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.retail.v2alpha.IServingConfig, - protos.google.cloud.retail.v2alpha.IRemoveControlRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.cloud.retail.v2alpha.IServingConfig, - protos.google.cloud.retail.v2alpha.IRemoveControlRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.retail.v2alpha.IServingConfig, - protos.google.cloud.retail.v2alpha.IRemoveControlRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.retail.v2alpha.IRemoveControlRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.retail.v2alpha.IServingConfig, + | protos.google.cloud.retail.v2alpha.IRemoveControlRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IServingConfig, + protos.google.cloud.retail.v2alpha.IRemoveControlRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'serving_config': request.servingConfig ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + serving_config: request.servingConfig ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('removeControl request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.retail.v2alpha.IServingConfig, - protos.google.cloud.retail.v2alpha.IRemoveControlRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.retail.v2alpha.IServingConfig, + | protos.google.cloud.retail.v2alpha.IRemoveControlRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('removeControl response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.removeControl(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.retail.v2alpha.IServingConfig, - protos.google.cloud.retail.v2alpha.IRemoveControlRequest|undefined, {}|undefined - ]) => { - this._log.info('removeControl response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .removeControl(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.retail.v2alpha.IServingConfig, + protos.google.cloud.retail.v2alpha.IRemoveControlRequest | undefined, + {} | undefined, + ]) => { + this._log.info('removeControl response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } - /** - * Lists all ServingConfigs linked to this catalog. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The catalog resource name. Format: - * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}` - * @param {number} [request.pageSize] - * Optional. Maximum number of results to return. If unspecified, defaults - * to 100. If a value greater than 100 is provided, at most 100 results are - * returned. - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous `ListServingConfigs` call. - * Provide this to retrieve the subsequent page. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.cloud.retail.v2alpha.ServingConfig|ServingConfig}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `listServingConfigsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Lists all ServingConfigs linked to this catalog. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The catalog resource name. Format: + * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}` + * @param {number} [request.pageSize] + * Optional. Maximum number of results to return. If unspecified, defaults + * to 100. If a value greater than 100 is provided, at most 100 results are + * returned. + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListServingConfigs` call. + * Provide this to retrieve the subsequent page. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.cloud.retail.v2alpha.ServingConfig|ServingConfig}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listServingConfigsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listServingConfigs( - request?: protos.google.cloud.retail.v2alpha.IListServingConfigsRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.retail.v2alpha.IServingConfig[], - protos.google.cloud.retail.v2alpha.IListServingConfigsRequest|null, - protos.google.cloud.retail.v2alpha.IListServingConfigsResponse - ]>; + request?: protos.google.cloud.retail.v2alpha.IListServingConfigsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IServingConfig[], + protos.google.cloud.retail.v2alpha.IListServingConfigsRequest | null, + protos.google.cloud.retail.v2alpha.IListServingConfigsResponse, + ] + >; listServingConfigs( - request: protos.google.cloud.retail.v2alpha.IListServingConfigsRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.cloud.retail.v2alpha.IListServingConfigsRequest, - protos.google.cloud.retail.v2alpha.IListServingConfigsResponse|null|undefined, - protos.google.cloud.retail.v2alpha.IServingConfig>): void; + request: protos.google.cloud.retail.v2alpha.IListServingConfigsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.cloud.retail.v2alpha.IListServingConfigsRequest, + | protos.google.cloud.retail.v2alpha.IListServingConfigsResponse + | null + | undefined, + protos.google.cloud.retail.v2alpha.IServingConfig + >, + ): void; listServingConfigs( - request: protos.google.cloud.retail.v2alpha.IListServingConfigsRequest, - callback: PaginationCallback< - protos.google.cloud.retail.v2alpha.IListServingConfigsRequest, - protos.google.cloud.retail.v2alpha.IListServingConfigsResponse|null|undefined, - protos.google.cloud.retail.v2alpha.IServingConfig>): void; + request: protos.google.cloud.retail.v2alpha.IListServingConfigsRequest, + callback: PaginationCallback< + protos.google.cloud.retail.v2alpha.IListServingConfigsRequest, + | protos.google.cloud.retail.v2alpha.IListServingConfigsResponse + | null + | undefined, + protos.google.cloud.retail.v2alpha.IServingConfig + >, + ): void; listServingConfigs( - request?: protos.google.cloud.retail.v2alpha.IListServingConfigsRequest, - optionsOrCallback?: CallOptions|PaginationCallback< + request?: protos.google.cloud.retail.v2alpha.IListServingConfigsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.cloud.retail.v2alpha.IListServingConfigsRequest, - protos.google.cloud.retail.v2alpha.IListServingConfigsResponse|null|undefined, - protos.google.cloud.retail.v2alpha.IServingConfig>, - callback?: PaginationCallback< - protos.google.cloud.retail.v2alpha.IListServingConfigsRequest, - protos.google.cloud.retail.v2alpha.IListServingConfigsResponse|null|undefined, - protos.google.cloud.retail.v2alpha.IServingConfig>): - Promise<[ - protos.google.cloud.retail.v2alpha.IServingConfig[], - protos.google.cloud.retail.v2alpha.IListServingConfigsRequest|null, - protos.google.cloud.retail.v2alpha.IListServingConfigsResponse - ]>|void { + | protos.google.cloud.retail.v2alpha.IListServingConfigsResponse + | null + | undefined, + protos.google.cloud.retail.v2alpha.IServingConfig + >, + callback?: PaginationCallback< + protos.google.cloud.retail.v2alpha.IListServingConfigsRequest, + | protos.google.cloud.retail.v2alpha.IListServingConfigsResponse + | null + | undefined, + protos.google.cloud.retail.v2alpha.IServingConfig + >, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IServingConfig[], + protos.google.cloud.retail.v2alpha.IListServingConfigsRequest | null, + protos.google.cloud.retail.v2alpha.IListServingConfigsResponse, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.cloud.retail.v2alpha.IListServingConfigsRequest, - protos.google.cloud.retail.v2alpha.IListServingConfigsResponse|null|undefined, - protos.google.cloud.retail.v2alpha.IServingConfig>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.cloud.retail.v2alpha.IListServingConfigsRequest, + | protos.google.cloud.retail.v2alpha.IListServingConfigsResponse + | null + | undefined, + protos.google.cloud.retail.v2alpha.IServingConfig + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listServingConfigs values %j', values); callback!(error, values, nextPageRequest, rawResponse); @@ -1083,114 +1434,118 @@ export class ServingConfigServiceClient { this._log.info('listServingConfigs request %j', request); return this.innerApiCalls .listServingConfigs(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.cloud.retail.v2alpha.IServingConfig[], - protos.google.cloud.retail.v2alpha.IListServingConfigsRequest|null, - protos.google.cloud.retail.v2alpha.IListServingConfigsResponse - ]) => { - this._log.info('listServingConfigs values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.cloud.retail.v2alpha.IServingConfig[], + protos.google.cloud.retail.v2alpha.IListServingConfigsRequest | null, + protos.google.cloud.retail.v2alpha.IListServingConfigsResponse, + ]) => { + this._log.info('listServingConfigs values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listServingConfigs`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The catalog resource name. Format: - * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}` - * @param {number} [request.pageSize] - * Optional. Maximum number of results to return. If unspecified, defaults - * to 100. If a value greater than 100 is provided, at most 100 results are - * returned. - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous `ListServingConfigs` call. - * Provide this to retrieve the subsequent page. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.cloud.retail.v2alpha.ServingConfig|ServingConfig} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `listServingConfigsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `listServingConfigs`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The catalog resource name. Format: + * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}` + * @param {number} [request.pageSize] + * Optional. Maximum number of results to return. If unspecified, defaults + * to 100. If a value greater than 100 is provided, at most 100 results are + * returned. + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListServingConfigs` call. + * Provide this to retrieve the subsequent page. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.cloud.retail.v2alpha.ServingConfig|ServingConfig} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listServingConfigsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listServingConfigsStream( - request?: protos.google.cloud.retail.v2alpha.IListServingConfigsRequest, - options?: CallOptions): - Transform{ + request?: protos.google.cloud.retail.v2alpha.IListServingConfigsRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); const defaultCallSettings = this._defaults['listServingConfigs']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listServingConfigs stream %j', request); return this.descriptors.page.listServingConfigs.createStream( this.innerApiCalls.listServingConfigs as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listServingConfigs`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The catalog resource name. Format: - * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}` - * @param {number} [request.pageSize] - * Optional. Maximum number of results to return. If unspecified, defaults - * to 100. If a value greater than 100 is provided, at most 100 results are - * returned. - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous `ListServingConfigs` call. - * Provide this to retrieve the subsequent page. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.cloud.retail.v2alpha.ServingConfig|ServingConfig}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/serving_config_service.list_serving_configs.js - * region_tag:retail_v2alpha_generated_ServingConfigService_ListServingConfigs_async - */ + /** + * Equivalent to `listServingConfigs`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The catalog resource name. Format: + * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}` + * @param {number} [request.pageSize] + * Optional. Maximum number of results to return. If unspecified, defaults + * to 100. If a value greater than 100 is provided, at most 100 results are + * returned. + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListServingConfigs` call. + * Provide this to retrieve the subsequent page. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.cloud.retail.v2alpha.ServingConfig|ServingConfig}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/serving_config_service.list_serving_configs.js + * region_tag:retail_v2alpha_generated_ServingConfigService_ListServingConfigs_async + */ listServingConfigsAsync( - request?: protos.google.cloud.retail.v2alpha.IListServingConfigsRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.cloud.retail.v2alpha.IListServingConfigsRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); const defaultCallSettings = this._defaults['listServingConfigs']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listServingConfigs iterate %j', request); return this.descriptors.page.listServingConfigs.asyncIterate( this.innerApiCalls['listServingConfigs'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } // -------------------- @@ -1203,7 +1558,7 @@ export class ServingConfigServiceClient { * @param {string} project * @returns {string} Resource name string. */ - alertConfigPath(project:string) { + alertConfigPath(project: string) { return this.pathTemplates.alertConfigPathTemplate.render({ project: project, }); @@ -1217,7 +1572,8 @@ export class ServingConfigServiceClient { * @returns {string} A string representing the project. */ matchProjectFromAlertConfigName(alertConfigName: string) { - return this.pathTemplates.alertConfigPathTemplate.match(alertConfigName).project; + return this.pathTemplates.alertConfigPathTemplate.match(alertConfigName) + .project; } /** @@ -1228,7 +1584,7 @@ export class ServingConfigServiceClient { * @param {string} catalog * @returns {string} Resource name string. */ - attributesConfigPath(project:string,location:string,catalog:string) { + attributesConfigPath(project: string, location: string, catalog: string) { return this.pathTemplates.attributesConfigPathTemplate.render({ project: project, location: location, @@ -1244,7 +1600,9 @@ export class ServingConfigServiceClient { * @returns {string} A string representing the project. */ matchProjectFromAttributesConfigName(attributesConfigName: string) { - return this.pathTemplates.attributesConfigPathTemplate.match(attributesConfigName).project; + return this.pathTemplates.attributesConfigPathTemplate.match( + attributesConfigName, + ).project; } /** @@ -1255,7 +1613,9 @@ export class ServingConfigServiceClient { * @returns {string} A string representing the location. */ matchLocationFromAttributesConfigName(attributesConfigName: string) { - return this.pathTemplates.attributesConfigPathTemplate.match(attributesConfigName).location; + return this.pathTemplates.attributesConfigPathTemplate.match( + attributesConfigName, + ).location; } /** @@ -1266,7 +1626,9 @@ export class ServingConfigServiceClient { * @returns {string} A string representing the catalog. */ matchCatalogFromAttributesConfigName(attributesConfigName: string) { - return this.pathTemplates.attributesConfigPathTemplate.match(attributesConfigName).catalog; + return this.pathTemplates.attributesConfigPathTemplate.match( + attributesConfigName, + ).catalog; } /** @@ -1278,7 +1640,12 @@ export class ServingConfigServiceClient { * @param {string} branch * @returns {string} Resource name string. */ - branchPath(project:string,location:string,catalog:string,branch:string) { + branchPath( + project: string, + location: string, + catalog: string, + branch: string, + ) { return this.pathTemplates.branchPathTemplate.render({ project: project, location: location, @@ -1339,7 +1706,7 @@ export class ServingConfigServiceClient { * @param {string} catalog * @returns {string} Resource name string. */ - catalogPath(project:string,location:string,catalog:string) { + catalogPath(project: string, location: string, catalog: string) { return this.pathTemplates.catalogPathTemplate.render({ project: project, location: location, @@ -1388,7 +1755,7 @@ export class ServingConfigServiceClient { * @param {string} catalog * @returns {string} Resource name string. */ - completionConfigPath(project:string,location:string,catalog:string) { + completionConfigPath(project: string, location: string, catalog: string) { return this.pathTemplates.completionConfigPathTemplate.render({ project: project, location: location, @@ -1404,7 +1771,9 @@ export class ServingConfigServiceClient { * @returns {string} A string representing the project. */ matchProjectFromCompletionConfigName(completionConfigName: string) { - return this.pathTemplates.completionConfigPathTemplate.match(completionConfigName).project; + return this.pathTemplates.completionConfigPathTemplate.match( + completionConfigName, + ).project; } /** @@ -1415,7 +1784,9 @@ export class ServingConfigServiceClient { * @returns {string} A string representing the location. */ matchLocationFromCompletionConfigName(completionConfigName: string) { - return this.pathTemplates.completionConfigPathTemplate.match(completionConfigName).location; + return this.pathTemplates.completionConfigPathTemplate.match( + completionConfigName, + ).location; } /** @@ -1426,7 +1797,9 @@ export class ServingConfigServiceClient { * @returns {string} A string representing the catalog. */ matchCatalogFromCompletionConfigName(completionConfigName: string) { - return this.pathTemplates.completionConfigPathTemplate.match(completionConfigName).catalog; + return this.pathTemplates.completionConfigPathTemplate.match( + completionConfigName, + ).catalog; } /** @@ -1438,7 +1811,12 @@ export class ServingConfigServiceClient { * @param {string} control * @returns {string} Resource name string. */ - controlPath(project:string,location:string,catalog:string,control:string) { + controlPath( + project: string, + location: string, + catalog: string, + control: string, + ) { return this.pathTemplates.controlPathTemplate.render({ project: project, location: location, @@ -1497,7 +1875,7 @@ export class ServingConfigServiceClient { * @param {string} project * @returns {string} Resource name string. */ - loggingConfigPath(project:string) { + loggingConfigPath(project: string) { return this.pathTemplates.loggingConfigPathTemplate.render({ project: project, }); @@ -1511,7 +1889,8 @@ export class ServingConfigServiceClient { * @returns {string} A string representing the project. */ matchProjectFromLoggingConfigName(loggingConfigName: string) { - return this.pathTemplates.loggingConfigPathTemplate.match(loggingConfigName).project; + return this.pathTemplates.loggingConfigPathTemplate.match(loggingConfigName) + .project; } /** @@ -1523,7 +1902,12 @@ export class ServingConfigServiceClient { * @param {string} merchant_center_account_link * @returns {string} Resource name string. */ - merchantCenterAccountLinkPath(project:string,location:string,catalog:string,merchantCenterAccountLink:string) { + merchantCenterAccountLinkPath( + project: string, + location: string, + catalog: string, + merchantCenterAccountLink: string, + ) { return this.pathTemplates.merchantCenterAccountLinkPathTemplate.render({ project: project, location: location, @@ -1539,8 +1923,12 @@ export class ServingConfigServiceClient { * A fully-qualified path representing MerchantCenterAccountLink resource. * @returns {string} A string representing the project. */ - matchProjectFromMerchantCenterAccountLinkName(merchantCenterAccountLinkName: string) { - return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match(merchantCenterAccountLinkName).project; + matchProjectFromMerchantCenterAccountLinkName( + merchantCenterAccountLinkName: string, + ) { + return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match( + merchantCenterAccountLinkName, + ).project; } /** @@ -1550,8 +1938,12 @@ export class ServingConfigServiceClient { * A fully-qualified path representing MerchantCenterAccountLink resource. * @returns {string} A string representing the location. */ - matchLocationFromMerchantCenterAccountLinkName(merchantCenterAccountLinkName: string) { - return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match(merchantCenterAccountLinkName).location; + matchLocationFromMerchantCenterAccountLinkName( + merchantCenterAccountLinkName: string, + ) { + return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match( + merchantCenterAccountLinkName, + ).location; } /** @@ -1561,8 +1953,12 @@ export class ServingConfigServiceClient { * A fully-qualified path representing MerchantCenterAccountLink resource. * @returns {string} A string representing the catalog. */ - matchCatalogFromMerchantCenterAccountLinkName(merchantCenterAccountLinkName: string) { - return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match(merchantCenterAccountLinkName).catalog; + matchCatalogFromMerchantCenterAccountLinkName( + merchantCenterAccountLinkName: string, + ) { + return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match( + merchantCenterAccountLinkName, + ).catalog; } /** @@ -1572,8 +1968,12 @@ export class ServingConfigServiceClient { * A fully-qualified path representing MerchantCenterAccountLink resource. * @returns {string} A string representing the merchant_center_account_link. */ - matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName(merchantCenterAccountLinkName: string) { - return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match(merchantCenterAccountLinkName).merchant_center_account_link; + matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName( + merchantCenterAccountLinkName: string, + ) { + return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match( + merchantCenterAccountLinkName, + ).merchant_center_account_link; } /** @@ -1585,7 +1985,7 @@ export class ServingConfigServiceClient { * @param {string} model * @returns {string} Resource name string. */ - modelPath(project:string,location:string,catalog:string,model:string) { + modelPath(project: string, location: string, catalog: string, model: string) { return this.pathTemplates.modelPathTemplate.render({ project: project, location: location, @@ -1648,7 +2048,13 @@ export class ServingConfigServiceClient { * @param {string} product * @returns {string} Resource name string. */ - productPath(project:string,location:string,catalog:string,branch:string,product:string) { + productPath( + project: string, + location: string, + catalog: string, + branch: string, + product: string, + ) { return this.pathTemplates.productPathTemplate.render({ project: project, location: location, @@ -1719,7 +2125,7 @@ export class ServingConfigServiceClient { * @param {string} project * @returns {string} Resource name string. */ - retailProjectPath(project:string) { + retailProjectPath(project: string) { return this.pathTemplates.retailProjectPathTemplate.render({ project: project, }); @@ -1733,7 +2139,8 @@ export class ServingConfigServiceClient { * @returns {string} A string representing the project. */ matchProjectFromRetailProjectName(retailProjectName: string) { - return this.pathTemplates.retailProjectPathTemplate.match(retailProjectName).project; + return this.pathTemplates.retailProjectPathTemplate.match(retailProjectName) + .project; } /** @@ -1745,7 +2152,12 @@ export class ServingConfigServiceClient { * @param {string} serving_config * @returns {string} Resource name string. */ - servingConfigPath(project:string,location:string,catalog:string,servingConfig:string) { + servingConfigPath( + project: string, + location: string, + catalog: string, + servingConfig: string, + ) { return this.pathTemplates.servingConfigPathTemplate.render({ project: project, location: location, @@ -1762,7 +2174,8 @@ export class ServingConfigServiceClient { * @returns {string} A string representing the project. */ matchProjectFromServingConfigName(servingConfigName: string) { - return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName).project; + return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName) + .project; } /** @@ -1773,7 +2186,8 @@ export class ServingConfigServiceClient { * @returns {string} A string representing the location. */ matchLocationFromServingConfigName(servingConfigName: string) { - return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName).location; + return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName) + .location; } /** @@ -1784,7 +2198,8 @@ export class ServingConfigServiceClient { * @returns {string} A string representing the catalog. */ matchCatalogFromServingConfigName(servingConfigName: string) { - return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName).catalog; + return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName) + .catalog; } /** @@ -1795,7 +2210,8 @@ export class ServingConfigServiceClient { * @returns {string} A string representing the serving_config. */ matchServingConfigFromServingConfigName(servingConfigName: string) { - return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName).serving_config; + return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName) + .serving_config; } /** @@ -1806,7 +2222,7 @@ export class ServingConfigServiceClient { */ close(): Promise { if (this.servingConfigServiceStub && !this._terminated) { - return this.servingConfigServiceStub.then(stub => { + return this.servingConfigServiceStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -1814,4 +2230,4 @@ export class ServingConfigServiceClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/src/v2alpha/user_event_service_client.ts.baseline b/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/src/v2alpha/user_event_service_client.ts.baseline index 71e7127cac1e..07bce9645e48 100644 --- a/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/src/v2alpha/user_event_service_client.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/src/v2alpha/user_event_service_client.ts.baseline @@ -18,15 +18,22 @@ /* global window */ import * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions, GrpcClientOptions, LROperation} from 'google-gax'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + GrpcClientOptions, + LROperation, +} from 'google-gax'; // @ts-ignore import type * as protos from '../../../protos/protos.js'; import * as user_event_service_client_config from './user_event_service_client_config.json'; import fs from 'fs'; import path from 'path'; -import {fileURLToPath} from 'url'; -import {getJSON} from '../json-helper.cjs'; +import { fileURLToPath } from 'url'; +import { getJSON } from '../json-helper.cjs'; // @ts-ignore const dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -36,15 +43,15 @@ const dirname = path.dirname(fileURLToPath(import.meta.url)); * This file defines retry strategy and timeouts for all API methods in this library. */ const gapicConfig = getJSON( - path.join(dirname, 'user_event_service_client_config.json') + path.join(dirname, 'user_event_service_client_config.json'), ); const jsonProtos = getJSON( - path.join(dirname, '..', '..', '..', 'protos/protos.json') + path.join(dirname, '..', '..', '..', 'protos/protos.json'), ); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; const version = getJSON( - path.join(dirname, '..', '..', '..', '..', 'package.json') + path.join(dirname, '..', '..', '..', '..', 'package.json'), ).version; /** @@ -59,7 +66,7 @@ export class UserEventServiceClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('retail'); @@ -71,10 +78,10 @@ export class UserEventServiceClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; operationsClient: gax.OperationsClient; - userEventServiceStub?: Promise<{[name: string]: Function}>; + userEventServiceStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of UserEventServiceClient. @@ -116,21 +123,42 @@ export class UserEventServiceClient { * const client = new UserEventServiceClient({fallback: 'rest'}, gax); * ``` */ - constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { // Ensure that options include all the required fields. const staticMembers = this.constructor as typeof UserEventServiceClient; - if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { - throw new Error('Please set either universe_domain or universeDomain, but not both.'); + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); } - const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; - this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; this._servicePath = 'retail.' + this._universeDomain; - const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; - const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. if (servicePath !== this._servicePath && !('scopes' in opts)) { @@ -152,7 +180,7 @@ export class UserEventServiceClient { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; @@ -169,10 +197,7 @@ export class UserEventServiceClient { const isEsm = true; const isEsmString = isEsm ? '-esm' : '-cjs'; // Determine the client header string. - const clientHeader = [ - `gax/${this._gaxModule.version}`, - `gapic/${version}`, - ]; + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/{process.versions.node}${isEsmString}`); } else { @@ -180,7 +205,7 @@ export class UserEventServiceClient { } if (!opts.fallback) { clientHeader.push(`grpc/${this._gaxGrpc.grpcVersion}`); - } else if (opts.fallback === 'rest' ) { + } else if (opts.fallback === 'rest') { clientHeader.push(`rest/${this._gaxGrpc.grpcVersion}`); } if (opts.libName && opts.libVersion) { @@ -188,47 +213,49 @@ export class UserEventServiceClient { } // Load the applicable protos. - this._protos = this._gaxGrpc.loadProtoJSON(jsonProtos as gax.protobuf.INamespace); + this._protos = this._gaxGrpc.loadProtoJSON( + jsonProtos as gax.protobuf.INamespace, + ); // This API contains "path templates"; forward-slash-separated // identifiers to uniquely identify resources within the API. // Create useful helper objects for these. this.pathTemplates = { alertConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/alertConfig' + 'projects/{project}/alertConfig', ), attributesConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/attributesConfig' + 'projects/{project}/locations/{location}/catalogs/{catalog}/attributesConfig', ), branchPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}', ), catalogPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}' + 'projects/{project}/locations/{location}/catalogs/{catalog}', ), completionConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/completionConfig' + 'projects/{project}/locations/{location}/catalogs/{catalog}/completionConfig', ), controlPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/controls/{control}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/controls/{control}', ), loggingConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/loggingConfig' + 'projects/{project}/loggingConfig', ), merchantCenterAccountLinkPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/merchantCenterAccountLinks/{merchant_center_account_link}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/merchantCenterAccountLinks/{merchant_center_account_link}', ), modelPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/models/{model}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/models/{model}', ), productPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}', ), retailProjectPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/retailProject' + 'projects/{project}/retailProject', ), servingConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/servingConfigs/{serving_config}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/servingConfigs/{serving_config}', ), }; @@ -238,55 +265,93 @@ export class UserEventServiceClient { // rather than holding a request open. const lroOptions: GrpcClientOptions = { auth: this.auth, - grpc: 'grpc' in this._gaxGrpc ? this._gaxGrpc.grpc : undefined + grpc: 'grpc' in this._gaxGrpc ? this._gaxGrpc.grpc : undefined, }; if (opts.fallback === 'rest') { lroOptions.protoJson = protoFilesRoot; - lroOptions.httpRules = [{selector: 'google.longrunning.Operations.GetOperation',get: '/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*/operations/*}',additional_bindings: [{get: '/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*/places/*/operations/*}',},{get: '/v2alpha/{name=projects/*/locations/*/catalogs/*/operations/*}',},{get: '/v2alpha/{name=projects/*/locations/*/operations/*}',},{get: '/v2alpha/{name=projects/*/operations/*}',}], - },{selector: 'google.longrunning.Operations.ListOperations',get: '/v2alpha/{name=projects/*/locations/*/catalogs/*}/operations',additional_bindings: [{get: '/v2alpha/{name=projects/*/locations/*}/operations',},{get: '/v2alpha/{name=projects/*}/operations',}], - }]; + lroOptions.httpRules = [ + { + selector: 'google.longrunning.Operations.GetOperation', + get: '/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*/operations/*}', + additional_bindings: [ + { + get: '/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*/places/*/operations/*}', + }, + { + get: '/v2alpha/{name=projects/*/locations/*/catalogs/*/operations/*}', + }, + { get: '/v2alpha/{name=projects/*/locations/*/operations/*}' }, + { get: '/v2alpha/{name=projects/*/operations/*}' }, + ], + }, + { + selector: 'google.longrunning.Operations.ListOperations', + get: '/v2alpha/{name=projects/*/locations/*/catalogs/*}/operations', + additional_bindings: [ + { get: '/v2alpha/{name=projects/*/locations/*}/operations' }, + { get: '/v2alpha/{name=projects/*}/operations' }, + ], + }, + ]; } - this.operationsClient = this._gaxModule.lro(lroOptions).operationsClient(opts); + this.operationsClient = this._gaxModule + .lro(lroOptions) + .operationsClient(opts); const purgeUserEventsResponse = protoFilesRoot.lookup( - '.google.cloud.retail.v2alpha.PurgeUserEventsResponse') as gax.protobuf.Type; + '.google.cloud.retail.v2alpha.PurgeUserEventsResponse', + ) as gax.protobuf.Type; const purgeUserEventsMetadata = protoFilesRoot.lookup( - '.google.cloud.retail.v2alpha.PurgeMetadata') as gax.protobuf.Type; + '.google.cloud.retail.v2alpha.PurgeMetadata', + ) as gax.protobuf.Type; const importUserEventsResponse = protoFilesRoot.lookup( - '.google.cloud.retail.v2alpha.ImportUserEventsResponse') as gax.protobuf.Type; + '.google.cloud.retail.v2alpha.ImportUserEventsResponse', + ) as gax.protobuf.Type; const importUserEventsMetadata = protoFilesRoot.lookup( - '.google.cloud.retail.v2alpha.ImportMetadata') as gax.protobuf.Type; + '.google.cloud.retail.v2alpha.ImportMetadata', + ) as gax.protobuf.Type; const exportUserEventsResponse = protoFilesRoot.lookup( - '.google.cloud.retail.v2alpha.ExportUserEventsResponse') as gax.protobuf.Type; + '.google.cloud.retail.v2alpha.ExportUserEventsResponse', + ) as gax.protobuf.Type; const exportUserEventsMetadata = protoFilesRoot.lookup( - '.google.cloud.retail.v2alpha.ExportMetadata') as gax.protobuf.Type; + '.google.cloud.retail.v2alpha.ExportMetadata', + ) as gax.protobuf.Type; const rejoinUserEventsResponse = protoFilesRoot.lookup( - '.google.cloud.retail.v2alpha.RejoinUserEventsResponse') as gax.protobuf.Type; + '.google.cloud.retail.v2alpha.RejoinUserEventsResponse', + ) as gax.protobuf.Type; const rejoinUserEventsMetadata = protoFilesRoot.lookup( - '.google.cloud.retail.v2alpha.RejoinUserEventsMetadata') as gax.protobuf.Type; + '.google.cloud.retail.v2alpha.RejoinUserEventsMetadata', + ) as gax.protobuf.Type; this.descriptors.longrunning = { purgeUserEvents: new this._gaxModule.LongrunningDescriptor( this.operationsClient, purgeUserEventsResponse.decode.bind(purgeUserEventsResponse), - purgeUserEventsMetadata.decode.bind(purgeUserEventsMetadata)), + purgeUserEventsMetadata.decode.bind(purgeUserEventsMetadata), + ), importUserEvents: new this._gaxModule.LongrunningDescriptor( this.operationsClient, importUserEventsResponse.decode.bind(importUserEventsResponse), - importUserEventsMetadata.decode.bind(importUserEventsMetadata)), + importUserEventsMetadata.decode.bind(importUserEventsMetadata), + ), exportUserEvents: new this._gaxModule.LongrunningDescriptor( this.operationsClient, exportUserEventsResponse.decode.bind(exportUserEventsResponse), - exportUserEventsMetadata.decode.bind(exportUserEventsMetadata)), + exportUserEventsMetadata.decode.bind(exportUserEventsMetadata), + ), rejoinUserEvents: new this._gaxModule.LongrunningDescriptor( this.operationsClient, rejoinUserEventsResponse.decode.bind(rejoinUserEventsResponse), - rejoinUserEventsMetadata.decode.bind(rejoinUserEventsMetadata)) + rejoinUserEventsMetadata.decode.bind(rejoinUserEventsMetadata), + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.cloud.retail.v2alpha.UserEventService', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.cloud.retail.v2alpha.UserEventService', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + { 'x-goog-api-client': clientHeader.join(' ') }, + ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -317,37 +382,47 @@ export class UserEventServiceClient { // Put together the "service stub" for // google.cloud.retail.v2alpha.UserEventService. this.userEventServiceStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.cloud.retail.v2alpha.UserEventService') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.cloud.retail.v2alpha.UserEventService', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.cloud.retail.v2alpha.UserEventService, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts, + this._providedCustomServicePath, + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const userEventServiceStubMethods = - ['writeUserEvent', 'collectUserEvent', 'purgeUserEvents', 'importUserEvents', 'exportUserEvents', 'rejoinUserEvents']; + const userEventServiceStubMethods = [ + 'writeUserEvent', + 'collectUserEvent', + 'purgeUserEvents', + 'importUserEvents', + 'exportUserEvents', + 'rejoinUserEvents', + ]; for (const methodName of userEventServiceStubMethods) { const callPromise = this.userEventServiceStub.then( - stub => (...args: Array<{}>) => { - if (this._terminated) { - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error|null|undefined) => () => { + (stub) => + (...args: Array<{}>) => { + if (this._terminated) { + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { throw err; - }); + }, + ); - const descriptor = - this.descriptors.longrunning[methodName] || - undefined; + const descriptor = this.descriptors.longrunning[methodName] || undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -362,8 +437,14 @@ export class UserEventServiceClient { * @returns {string} The DNS address for this service. */ static get servicePath() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'retail.googleapis.com'; } @@ -375,8 +456,14 @@ export class UserEventServiceClient { * @returns {string} The DNS address for this service. */ static get apiEndpoint() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'retail.googleapis.com'; } @@ -407,9 +494,7 @@ export class UserEventServiceClient { * @returns {string[]} List of default scopes. */ static get scopes() { - return [ - 'https://www.googleapis.com/auth/cloud-platform' - ]; + return ['https://www.googleapis.com/auth/cloud-platform']; } getProjectId(): Promise; @@ -418,8 +503,9 @@ export class UserEventServiceClient { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId(callback?: Callback): - Promise|void { + getProjectId( + callback?: Callback, + ): Promise | void { if (callback) { this.auth.getProjectId(callback); return; @@ -430,757 +516,1090 @@ export class UserEventServiceClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Writes a single user event. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent catalog resource name, such as - * `projects/1234/locations/global/catalogs/default_catalog`. - * @param {google.cloud.retail.v2alpha.UserEvent} request.userEvent - * Required. User event to write. - * @param {boolean} request.writeAsync - * If set to true, the user event will be written asynchronously after - * validation, and the API will respond without waiting for the write. - * Therefore, silent failures can occur even if the API returns success. In - * case of silent failures, error messages can be found in Stackdriver logs. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.UserEvent|UserEvent}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/user_event_service.write_user_event.js - * region_tag:retail_v2alpha_generated_UserEventService_WriteUserEvent_async - */ + /** + * Writes a single user event. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent catalog resource name, such as + * `projects/1234/locations/global/catalogs/default_catalog`. + * @param {google.cloud.retail.v2alpha.UserEvent} request.userEvent + * Required. User event to write. + * @param {boolean} request.writeAsync + * If set to true, the user event will be written asynchronously after + * validation, and the API will respond without waiting for the write. + * Therefore, silent failures can occur even if the API returns success. In + * case of silent failures, error messages can be found in Stackdriver logs. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.UserEvent|UserEvent}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/user_event_service.write_user_event.js + * region_tag:retail_v2alpha_generated_UserEventService_WriteUserEvent_async + */ writeUserEvent( - request?: protos.google.cloud.retail.v2alpha.IWriteUserEventRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.retail.v2alpha.IUserEvent, - protos.google.cloud.retail.v2alpha.IWriteUserEventRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.IWriteUserEventRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IUserEvent, + protos.google.cloud.retail.v2alpha.IWriteUserEventRequest | undefined, + {} | undefined, + ] + >; writeUserEvent( - request: protos.google.cloud.retail.v2alpha.IWriteUserEventRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.retail.v2alpha.IUserEvent, - protos.google.cloud.retail.v2alpha.IWriteUserEventRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IWriteUserEventRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.retail.v2alpha.IUserEvent, + | protos.google.cloud.retail.v2alpha.IWriteUserEventRequest + | null + | undefined, + {} | null | undefined + >, + ): void; writeUserEvent( - request: protos.google.cloud.retail.v2alpha.IWriteUserEventRequest, - callback: Callback< - protos.google.cloud.retail.v2alpha.IUserEvent, - protos.google.cloud.retail.v2alpha.IWriteUserEventRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IWriteUserEventRequest, + callback: Callback< + protos.google.cloud.retail.v2alpha.IUserEvent, + | protos.google.cloud.retail.v2alpha.IWriteUserEventRequest + | null + | undefined, + {} | null | undefined + >, + ): void; writeUserEvent( - request?: protos.google.cloud.retail.v2alpha.IWriteUserEventRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.cloud.retail.v2alpha.IWriteUserEventRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.retail.v2alpha.IUserEvent, - protos.google.cloud.retail.v2alpha.IWriteUserEventRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.cloud.retail.v2alpha.IUserEvent, - protos.google.cloud.retail.v2alpha.IWriteUserEventRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.retail.v2alpha.IUserEvent, - protos.google.cloud.retail.v2alpha.IWriteUserEventRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.retail.v2alpha.IWriteUserEventRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.retail.v2alpha.IUserEvent, + | protos.google.cloud.retail.v2alpha.IWriteUserEventRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IUserEvent, + protos.google.cloud.retail.v2alpha.IWriteUserEventRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('writeUserEvent request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.retail.v2alpha.IUserEvent, - protos.google.cloud.retail.v2alpha.IWriteUserEventRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.retail.v2alpha.IUserEvent, + | protos.google.cloud.retail.v2alpha.IWriteUserEventRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('writeUserEvent response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.writeUserEvent(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.retail.v2alpha.IUserEvent, - protos.google.cloud.retail.v2alpha.IWriteUserEventRequest|undefined, {}|undefined - ]) => { - this._log.info('writeUserEvent response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .writeUserEvent(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.retail.v2alpha.IUserEvent, + protos.google.cloud.retail.v2alpha.IWriteUserEventRequest | undefined, + {} | undefined, + ]) => { + this._log.info('writeUserEvent response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Writes a single user event from the browser. - * - * For larger user event payload over 16 KB, the POST method should be used - * instead, otherwise a 400 Bad Request error is returned. - * - * This method is used only by the Retail API JavaScript pixel and Google Tag - * Manager. Users should not call this method directly. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.prebuiltRule - * The prebuilt rule name that can convert a specific type of raw_json. - * For example: "ga4_bq" rule for the GA4 user event schema. - * @param {string} request.parent - * Required. The parent catalog name, such as - * `projects/1234/locations/global/catalogs/default_catalog`. - * @param {string} request.userEvent - * Required. URL encoded UserEvent proto with a length limit of 2,000,000 - * characters. - * @param {string} request.uri - * The URL including cgi-parameters but excluding the hash fragment with a - * length limit of 5,000 characters. This is often more useful than the - * referer URL, because many browsers only send the domain for 3rd party - * requests. - * @param {number} request.ets - * The event timestamp in milliseconds. This prevents browser caching of - * otherwise identical get requests. The name is abbreviated to reduce the - * payload bytes. - * @param {string} request.rawJson - * An arbitrary serialized JSON string that contains necessary information - * that can comprise a user event. When this field is specified, the - * user_event field will be ignored. Note: line-delimited JSON is not - * supported, a single JSON only. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.api.HttpBody|HttpBody}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/user_event_service.collect_user_event.js - * region_tag:retail_v2alpha_generated_UserEventService_CollectUserEvent_async - */ + /** + * Writes a single user event from the browser. + * + * For larger user event payload over 16 KB, the POST method should be used + * instead, otherwise a 400 Bad Request error is returned. + * + * This method is used only by the Retail API JavaScript pixel and Google Tag + * Manager. Users should not call this method directly. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.prebuiltRule + * The prebuilt rule name that can convert a specific type of raw_json. + * For example: "ga4_bq" rule for the GA4 user event schema. + * @param {string} request.parent + * Required. The parent catalog name, such as + * `projects/1234/locations/global/catalogs/default_catalog`. + * @param {string} request.userEvent + * Required. URL encoded UserEvent proto with a length limit of 2,000,000 + * characters. + * @param {string} request.uri + * The URL including cgi-parameters but excluding the hash fragment with a + * length limit of 5,000 characters. This is often more useful than the + * referer URL, because many browsers only send the domain for 3rd party + * requests. + * @param {number} request.ets + * The event timestamp in milliseconds. This prevents browser caching of + * otherwise identical get requests. The name is abbreviated to reduce the + * payload bytes. + * @param {string} request.rawJson + * An arbitrary serialized JSON string that contains necessary information + * that can comprise a user event. When this field is specified, the + * user_event field will be ignored. Note: line-delimited JSON is not + * supported, a single JSON only. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.api.HttpBody|HttpBody}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/user_event_service.collect_user_event.js + * region_tag:retail_v2alpha_generated_UserEventService_CollectUserEvent_async + */ collectUserEvent( - request?: protos.google.cloud.retail.v2alpha.ICollectUserEventRequest, - options?: CallOptions): - Promise<[ - protos.google.api.IHttpBody, - protos.google.cloud.retail.v2alpha.ICollectUserEventRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.ICollectUserEventRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.api.IHttpBody, + protos.google.cloud.retail.v2alpha.ICollectUserEventRequest | undefined, + {} | undefined, + ] + >; collectUserEvent( - request: protos.google.cloud.retail.v2alpha.ICollectUserEventRequest, - options: CallOptions, - callback: Callback< - protos.google.api.IHttpBody, - protos.google.cloud.retail.v2alpha.ICollectUserEventRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.ICollectUserEventRequest, + options: CallOptions, + callback: Callback< + protos.google.api.IHttpBody, + | protos.google.cloud.retail.v2alpha.ICollectUserEventRequest + | null + | undefined, + {} | null | undefined + >, + ): void; collectUserEvent( - request: protos.google.cloud.retail.v2alpha.ICollectUserEventRequest, - callback: Callback< - protos.google.api.IHttpBody, - protos.google.cloud.retail.v2alpha.ICollectUserEventRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.ICollectUserEventRequest, + callback: Callback< + protos.google.api.IHttpBody, + | protos.google.cloud.retail.v2alpha.ICollectUserEventRequest + | null + | undefined, + {} | null | undefined + >, + ): void; collectUserEvent( - request?: protos.google.cloud.retail.v2alpha.ICollectUserEventRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.api.IHttpBody, - protos.google.cloud.retail.v2alpha.ICollectUserEventRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.retail.v2alpha.ICollectUserEventRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.api.IHttpBody, - protos.google.cloud.retail.v2alpha.ICollectUserEventRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.api.IHttpBody, - protos.google.cloud.retail.v2alpha.ICollectUserEventRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.retail.v2alpha.ICollectUserEventRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.api.IHttpBody, + | protos.google.cloud.retail.v2alpha.ICollectUserEventRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.api.IHttpBody, + protos.google.cloud.retail.v2alpha.ICollectUserEventRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('collectUserEvent request %j', request); - const wrappedCallback: Callback< - protos.google.api.IHttpBody, - protos.google.cloud.retail.v2alpha.ICollectUserEventRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.api.IHttpBody, + | protos.google.cloud.retail.v2alpha.ICollectUserEventRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('collectUserEvent response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.collectUserEvent(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.api.IHttpBody, - protos.google.cloud.retail.v2alpha.ICollectUserEventRequest|undefined, {}|undefined - ]) => { - this._log.info('collectUserEvent response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .collectUserEvent(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.api.IHttpBody, + ( + | protos.google.cloud.retail.v2alpha.ICollectUserEventRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('collectUserEvent response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Deletes permanently all user events specified by the filter provided. - * Depending on the number of events specified by the filter, this operation - * could take hours or days to complete. To test a filter, use the list - * command first. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The resource name of the catalog under which the events are - * created. The format is - * `projects/${projectId}/locations/global/catalogs/${catalogId}` - * @param {string} request.filter - * Required. The filter string to specify the events to be deleted with a - * length limit of 5,000 characters. Empty string filter is not allowed. The - * eligible fields for filtering are: - * - * * `eventType`: Double quoted - * {@link protos.google.cloud.retail.v2alpha.UserEvent.event_type|UserEvent.event_type} - * string. - * * `eventTime`: in ISO 8601 "zulu" format. - * * `visitorId`: Double quoted string. Specifying this will delete all - * events associated with a visitor. - * * `userId`: Double quoted string. Specifying this will delete all events - * associated with a user. - * - * Examples: - * - * * Deleting all events in a time range: - * `eventTime > "2012-04-23T18:25:43.511Z" - * eventTime < "2012-04-23T18:30:43.511Z"` - * * Deleting specific eventType in time range: - * `eventTime > "2012-04-23T18:25:43.511Z" eventType = "detail-page-view"` - * * Deleting all events for a specific visitor: - * `visitorId = "visitor1024"` - * - * The filtering fields are assumed to have an implicit AND. - * @param {boolean} request.force - * Actually perform the purge. - * If `force` is set to false, the method will return the expected purge count - * without deleting any user events. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing - * a long running operation. Its `promise()` method returns a promise - * you can `await` for. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/user_event_service.purge_user_events.js - * region_tag:retail_v2alpha_generated_UserEventService_PurgeUserEvents_async - */ + /** + * Deletes permanently all user events specified by the filter provided. + * Depending on the number of events specified by the filter, this operation + * could take hours or days to complete. To test a filter, use the list + * command first. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The resource name of the catalog under which the events are + * created. The format is + * `projects/${projectId}/locations/global/catalogs/${catalogId}` + * @param {string} request.filter + * Required. The filter string to specify the events to be deleted with a + * length limit of 5,000 characters. Empty string filter is not allowed. The + * eligible fields for filtering are: + * + * * `eventType`: Double quoted + * {@link protos.google.cloud.retail.v2alpha.UserEvent.event_type|UserEvent.event_type} + * string. + * * `eventTime`: in ISO 8601 "zulu" format. + * * `visitorId`: Double quoted string. Specifying this will delete all + * events associated with a visitor. + * * `userId`: Double quoted string. Specifying this will delete all events + * associated with a user. + * + * Examples: + * + * * Deleting all events in a time range: + * `eventTime > "2012-04-23T18:25:43.511Z" + * eventTime < "2012-04-23T18:30:43.511Z"` + * * Deleting specific eventType in time range: + * `eventTime > "2012-04-23T18:25:43.511Z" eventType = "detail-page-view"` + * * Deleting all events for a specific visitor: + * `visitorId = "visitor1024"` + * + * The filtering fields are assumed to have an implicit AND. + * @param {boolean} request.force + * Actually perform the purge. + * If `force` is set to false, the method will return the expected purge count + * without deleting any user events. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/user_event_service.purge_user_events.js + * region_tag:retail_v2alpha_generated_UserEventService_PurgeUserEvents_async + */ purgeUserEvents( - request?: protos.google.cloud.retail.v2alpha.IPurgeUserEventsRequest, - options?: CallOptions): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.IPurgeUserEventsRequest, + options?: CallOptions, + ): Promise< + [ + LROperation< + protos.google.cloud.retail.v2alpha.IPurgeUserEventsResponse, + protos.google.cloud.retail.v2alpha.IPurgeMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; purgeUserEvents( - request: protos.google.cloud.retail.v2alpha.IPurgeUserEventsRequest, - options: CallOptions, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IPurgeUserEventsRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IPurgeUserEventsResponse, + protos.google.cloud.retail.v2alpha.IPurgeMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; purgeUserEvents( - request: protos.google.cloud.retail.v2alpha.IPurgeUserEventsRequest, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IPurgeUserEventsRequest, + callback: Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IPurgeUserEventsResponse, + protos.google.cloud.retail.v2alpha.IPurgeMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; purgeUserEvents( - request?: protos.google.cloud.retail.v2alpha.IPurgeUserEventsRequest, - optionsOrCallback?: CallOptions|Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>, - callback?: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>|void { + request?: protos.google.cloud.retail.v2alpha.IPurgeUserEventsRequest, + optionsOrCallback?: + | CallOptions + | Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IPurgeUserEventsResponse, + protos.google.cloud.retail.v2alpha.IPurgeMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + callback?: Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IPurgeUserEventsResponse, + protos.google.cloud.retail.v2alpha.IPurgeMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + LROperation< + protos.google.cloud.retail.v2alpha.IPurgeUserEventsResponse, + protos.google.cloud.retail.v2alpha.IPurgeMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IPurgeUserEventsResponse, + protos.google.cloud.retail.v2alpha.IPurgeMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, rawResponse, _) => { this._log.info('purgeUserEvents response %j', rawResponse); callback!(error, response, rawResponse, _); // We verified `callback` above. } : undefined; this._log.info('purgeUserEvents request %j', request); - return this.innerApiCalls.purgeUserEvents(request, options, wrappedCallback) - ?.then(([response, rawResponse, _]: [ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]) => { - this._log.info('purgeUserEvents response %j', rawResponse); - return [response, rawResponse, _]; - }); + return this.innerApiCalls + .purgeUserEvents(request, options, wrappedCallback) + ?.then( + ([response, rawResponse, _]: [ + LROperation< + protos.google.cloud.retail.v2alpha.IPurgeUserEventsResponse, + protos.google.cloud.retail.v2alpha.IPurgeMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ]) => { + this._log.info('purgeUserEvents response %j', rawResponse); + return [response, rawResponse, _]; + }, + ); } -/** - * Check the status of the long running operation returned by `purgeUserEvents()`. - * @param {String} name - * The operation name that will be passed. - * @returns {Promise} - The promise which resolves to an object. - * The decoded operation object has result and metadata field to get information from. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/user_event_service.purge_user_events.js - * region_tag:retail_v2alpha_generated_UserEventService_PurgeUserEvents_async - */ - async checkPurgeUserEventsProgress(name: string): Promise>{ + /** + * Check the status of the long running operation returned by `purgeUserEvents()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/user_event_service.purge_user_events.js + * region_tag:retail_v2alpha_generated_UserEventService_PurgeUserEvents_async + */ + async checkPurgeUserEventsProgress( + name: string, + ): Promise< + LROperation< + protos.google.cloud.retail.v2alpha.PurgeUserEventsResponse, + protos.google.cloud.retail.v2alpha.PurgeMetadata + > + > { this._log.info('purgeUserEvents long-running'); - const request = new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest({name}); + const request = + new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( + { name }, + ); const [operation] = await this.operationsClient.getOperation(request); - const decodeOperation = new this._gaxModule.Operation(operation, this.descriptors.longrunning.purgeUserEvents, this._gaxModule.createDefaultBackoffSettings()); - return decodeOperation as LROperation; + const decodeOperation = new this._gaxModule.Operation( + operation, + this.descriptors.longrunning.purgeUserEvents, + this._gaxModule.createDefaultBackoffSettings(), + ); + return decodeOperation as LROperation< + protos.google.cloud.retail.v2alpha.PurgeUserEventsResponse, + protos.google.cloud.retail.v2alpha.PurgeMetadata + >; } -/** - * Bulk import of User events. Request processing might be - * synchronous. Events that already exist are skipped. - * Use this method for backfilling historical user events. - * - * `Operation.response` is of type `ImportResponse`. Note that it is - * possible for a subset of the items to be successfully inserted. - * `Operation.metadata` is of type `ImportMetadata`. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. `projects/1234/locations/global/catalogs/default_catalog` - * @param {google.cloud.retail.v2alpha.UserEventInputConfig} request.inputConfig - * Required. The desired input location of the data. - * @param {google.cloud.retail.v2alpha.ImportErrorsConfig} request.errorsConfig - * The desired location of errors incurred during the Import. Cannot be set - * for inline user event imports. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing - * a long running operation. Its `promise()` method returns a promise - * you can `await` for. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/user_event_service.import_user_events.js - * region_tag:retail_v2alpha_generated_UserEventService_ImportUserEvents_async - */ + /** + * Bulk import of User events. Request processing might be + * synchronous. Events that already exist are skipped. + * Use this method for backfilling historical user events. + * + * `Operation.response` is of type `ImportResponse`. Note that it is + * possible for a subset of the items to be successfully inserted. + * `Operation.metadata` is of type `ImportMetadata`. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. `projects/1234/locations/global/catalogs/default_catalog` + * @param {google.cloud.retail.v2alpha.UserEventInputConfig} request.inputConfig + * Required. The desired input location of the data. + * @param {google.cloud.retail.v2alpha.ImportErrorsConfig} request.errorsConfig + * The desired location of errors incurred during the Import. Cannot be set + * for inline user event imports. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/user_event_service.import_user_events.js + * region_tag:retail_v2alpha_generated_UserEventService_ImportUserEvents_async + */ importUserEvents( - request?: protos.google.cloud.retail.v2alpha.IImportUserEventsRequest, - options?: CallOptions): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.IImportUserEventsRequest, + options?: CallOptions, + ): Promise< + [ + LROperation< + protos.google.cloud.retail.v2alpha.IImportUserEventsResponse, + protos.google.cloud.retail.v2alpha.IImportMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; importUserEvents( - request: protos.google.cloud.retail.v2alpha.IImportUserEventsRequest, - options: CallOptions, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IImportUserEventsRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IImportUserEventsResponse, + protos.google.cloud.retail.v2alpha.IImportMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; importUserEvents( - request: protos.google.cloud.retail.v2alpha.IImportUserEventsRequest, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IImportUserEventsRequest, + callback: Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IImportUserEventsResponse, + protos.google.cloud.retail.v2alpha.IImportMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; importUserEvents( - request?: protos.google.cloud.retail.v2alpha.IImportUserEventsRequest, - optionsOrCallback?: CallOptions|Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>, - callback?: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>|void { + request?: protos.google.cloud.retail.v2alpha.IImportUserEventsRequest, + optionsOrCallback?: + | CallOptions + | Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IImportUserEventsResponse, + protos.google.cloud.retail.v2alpha.IImportMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + callback?: Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IImportUserEventsResponse, + protos.google.cloud.retail.v2alpha.IImportMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + LROperation< + protos.google.cloud.retail.v2alpha.IImportUserEventsResponse, + protos.google.cloud.retail.v2alpha.IImportMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IImportUserEventsResponse, + protos.google.cloud.retail.v2alpha.IImportMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, rawResponse, _) => { this._log.info('importUserEvents response %j', rawResponse); callback!(error, response, rawResponse, _); // We verified `callback` above. } : undefined; this._log.info('importUserEvents request %j', request); - return this.innerApiCalls.importUserEvents(request, options, wrappedCallback) - ?.then(([response, rawResponse, _]: [ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]) => { - this._log.info('importUserEvents response %j', rawResponse); - return [response, rawResponse, _]; - }); + return this.innerApiCalls + .importUserEvents(request, options, wrappedCallback) + ?.then( + ([response, rawResponse, _]: [ + LROperation< + protos.google.cloud.retail.v2alpha.IImportUserEventsResponse, + protos.google.cloud.retail.v2alpha.IImportMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ]) => { + this._log.info('importUserEvents response %j', rawResponse); + return [response, rawResponse, _]; + }, + ); } -/** - * Check the status of the long running operation returned by `importUserEvents()`. - * @param {String} name - * The operation name that will be passed. - * @returns {Promise} - The promise which resolves to an object. - * The decoded operation object has result and metadata field to get information from. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/user_event_service.import_user_events.js - * region_tag:retail_v2alpha_generated_UserEventService_ImportUserEvents_async - */ - async checkImportUserEventsProgress(name: string): Promise>{ + /** + * Check the status of the long running operation returned by `importUserEvents()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/user_event_service.import_user_events.js + * region_tag:retail_v2alpha_generated_UserEventService_ImportUserEvents_async + */ + async checkImportUserEventsProgress( + name: string, + ): Promise< + LROperation< + protos.google.cloud.retail.v2alpha.ImportUserEventsResponse, + protos.google.cloud.retail.v2alpha.ImportMetadata + > + > { this._log.info('importUserEvents long-running'); - const request = new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest({name}); + const request = + new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( + { name }, + ); const [operation] = await this.operationsClient.getOperation(request); - const decodeOperation = new this._gaxModule.Operation(operation, this.descriptors.longrunning.importUserEvents, this._gaxModule.createDefaultBackoffSettings()); - return decodeOperation as LROperation; + const decodeOperation = new this._gaxModule.Operation( + operation, + this.descriptors.longrunning.importUserEvents, + this._gaxModule.createDefaultBackoffSettings(), + ); + return decodeOperation as LROperation< + protos.google.cloud.retail.v2alpha.ImportUserEventsResponse, + protos.google.cloud.retail.v2alpha.ImportMetadata + >; } -/** - * Exports user events. - * - * `Operation.response` is of type `ExportResponse`. - * `Operation.metadata` is of type `ExportMetadata`. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. Resource name of a - * {@link protos.google.cloud.retail.v2alpha.Catalog|Catalog}. For example - * `projects/1234/locations/global/catalogs/default_catalog` - * @param {google.cloud.retail.v2alpha.OutputConfig} request.outputConfig - * Required. The output location of the data. - * @param {string} request.filter - * A filtering expression to specify restrictions on returned events. - * The expression is a sequence of terms. Each term applies a restriction to - * the returned user events. Use this expression to restrict results to a - * specific time range or to filter events by eventType. - * For example, `eventTime > "2012-04-23T18:25:43.511Z" - * eventsMissingCatalogItems eventTime<"2012-04-23T18:25:43.511Z" - * eventType=search` - * - * We expect only three types of fields: - * - * * `eventTime`: This can be specified twice, once with a - * less than operator and once with a greater than operator. The - * `eventTime` restriction should result in one, contiguous, valid, - * `eventTime` range. - * - * * `eventType`: Boolean operators `OR` and `NOT` are supported if the - * expression is enclosed in parentheses and the operators are separated - * from the tag values by a space. - * - * * `eventsMissingCatalogItems`: This restricts results - * to events for which catalog items were not found in the catalog. The - * default behavior is to return only those events for which catalog - * items were found. - * - * Some examples of valid filters expressions: - * - * * Example 1: `eventTime > "2012-04-23T18:25:43.511Z" - * eventTime < "2012-04-23T18:30:43.511Z"` - * * Example 2: `eventTime > "2012-04-23T18:25:43.511Z" - * eventType = detail-page-view` - * * Example 3: `eventsMissingCatalogItems - * eventType = (NOT search) eventTime < - * "2018-04-23T18:30:43.511Z"` - * * Example 4: `eventTime > "2012-04-23T18:25:43.511Z"` - * * Example 5: `eventType = (detail-page-view OR search)` - * * Example 6: `eventsMissingCatalogItems` - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing - * a long running operation. Its `promise()` method returns a promise - * you can `await` for. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/user_event_service.export_user_events.js - * region_tag:retail_v2alpha_generated_UserEventService_ExportUserEvents_async - */ + /** + * Exports user events. + * + * `Operation.response` is of type `ExportResponse`. + * `Operation.metadata` is of type `ExportMetadata`. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Resource name of a + * {@link protos.google.cloud.retail.v2alpha.Catalog|Catalog}. For example + * `projects/1234/locations/global/catalogs/default_catalog` + * @param {google.cloud.retail.v2alpha.OutputConfig} request.outputConfig + * Required. The output location of the data. + * @param {string} request.filter + * A filtering expression to specify restrictions on returned events. + * The expression is a sequence of terms. Each term applies a restriction to + * the returned user events. Use this expression to restrict results to a + * specific time range or to filter events by eventType. + * For example, `eventTime > "2012-04-23T18:25:43.511Z" + * eventsMissingCatalogItems eventTime<"2012-04-23T18:25:43.511Z" + * eventType=search` + * + * We expect only three types of fields: + * + * * `eventTime`: This can be specified twice, once with a + * less than operator and once with a greater than operator. The + * `eventTime` restriction should result in one, contiguous, valid, + * `eventTime` range. + * + * * `eventType`: Boolean operators `OR` and `NOT` are supported if the + * expression is enclosed in parentheses and the operators are separated + * from the tag values by a space. + * + * * `eventsMissingCatalogItems`: This restricts results + * to events for which catalog items were not found in the catalog. The + * default behavior is to return only those events for which catalog + * items were found. + * + * Some examples of valid filters expressions: + * + * * Example 1: `eventTime > "2012-04-23T18:25:43.511Z" + * eventTime < "2012-04-23T18:30:43.511Z"` + * * Example 2: `eventTime > "2012-04-23T18:25:43.511Z" + * eventType = detail-page-view` + * * Example 3: `eventsMissingCatalogItems + * eventType = (NOT search) eventTime < + * "2018-04-23T18:30:43.511Z"` + * * Example 4: `eventTime > "2012-04-23T18:25:43.511Z"` + * * Example 5: `eventType = (detail-page-view OR search)` + * * Example 6: `eventsMissingCatalogItems` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/user_event_service.export_user_events.js + * region_tag:retail_v2alpha_generated_UserEventService_ExportUserEvents_async + */ exportUserEvents( - request?: protos.google.cloud.retail.v2alpha.IExportUserEventsRequest, - options?: CallOptions): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.IExportUserEventsRequest, + options?: CallOptions, + ): Promise< + [ + LROperation< + protos.google.cloud.retail.v2alpha.IExportUserEventsResponse, + protos.google.cloud.retail.v2alpha.IExportMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; exportUserEvents( - request: protos.google.cloud.retail.v2alpha.IExportUserEventsRequest, - options: CallOptions, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IExportUserEventsRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IExportUserEventsResponse, + protos.google.cloud.retail.v2alpha.IExportMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; exportUserEvents( - request: protos.google.cloud.retail.v2alpha.IExportUserEventsRequest, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IExportUserEventsRequest, + callback: Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IExportUserEventsResponse, + protos.google.cloud.retail.v2alpha.IExportMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; exportUserEvents( - request?: protos.google.cloud.retail.v2alpha.IExportUserEventsRequest, - optionsOrCallback?: CallOptions|Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>, - callback?: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>|void { + request?: protos.google.cloud.retail.v2alpha.IExportUserEventsRequest, + optionsOrCallback?: + | CallOptions + | Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IExportUserEventsResponse, + protos.google.cloud.retail.v2alpha.IExportMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + callback?: Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IExportUserEventsResponse, + protos.google.cloud.retail.v2alpha.IExportMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + LROperation< + protos.google.cloud.retail.v2alpha.IExportUserEventsResponse, + protos.google.cloud.retail.v2alpha.IExportMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IExportUserEventsResponse, + protos.google.cloud.retail.v2alpha.IExportMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, rawResponse, _) => { this._log.info('exportUserEvents response %j', rawResponse); callback!(error, response, rawResponse, _); // We verified `callback` above. } : undefined; this._log.info('exportUserEvents request %j', request); - return this.innerApiCalls.exportUserEvents(request, options, wrappedCallback) - ?.then(([response, rawResponse, _]: [ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]) => { - this._log.info('exportUserEvents response %j', rawResponse); - return [response, rawResponse, _]; - }); + return this.innerApiCalls + .exportUserEvents(request, options, wrappedCallback) + ?.then( + ([response, rawResponse, _]: [ + LROperation< + protos.google.cloud.retail.v2alpha.IExportUserEventsResponse, + protos.google.cloud.retail.v2alpha.IExportMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ]) => { + this._log.info('exportUserEvents response %j', rawResponse); + return [response, rawResponse, _]; + }, + ); } -/** - * Check the status of the long running operation returned by `exportUserEvents()`. - * @param {String} name - * The operation name that will be passed. - * @returns {Promise} - The promise which resolves to an object. - * The decoded operation object has result and metadata field to get information from. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/user_event_service.export_user_events.js - * region_tag:retail_v2alpha_generated_UserEventService_ExportUserEvents_async - */ - async checkExportUserEventsProgress(name: string): Promise>{ + /** + * Check the status of the long running operation returned by `exportUserEvents()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/user_event_service.export_user_events.js + * region_tag:retail_v2alpha_generated_UserEventService_ExportUserEvents_async + */ + async checkExportUserEventsProgress( + name: string, + ): Promise< + LROperation< + protos.google.cloud.retail.v2alpha.ExportUserEventsResponse, + protos.google.cloud.retail.v2alpha.ExportMetadata + > + > { this._log.info('exportUserEvents long-running'); - const request = new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest({name}); + const request = + new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( + { name }, + ); const [operation] = await this.operationsClient.getOperation(request); - const decodeOperation = new this._gaxModule.Operation(operation, this.descriptors.longrunning.exportUserEvents, this._gaxModule.createDefaultBackoffSettings()); - return decodeOperation as LROperation; + const decodeOperation = new this._gaxModule.Operation( + operation, + this.descriptors.longrunning.exportUserEvents, + this._gaxModule.createDefaultBackoffSettings(), + ); + return decodeOperation as LROperation< + protos.google.cloud.retail.v2alpha.ExportUserEventsResponse, + protos.google.cloud.retail.v2alpha.ExportMetadata + >; } -/** - * Starts a user-event rejoin operation with latest product catalog. Events - * are not annotated with detailed product information for products that are - * missing from the catalog when the user event is ingested. These - * events are stored as unjoined events with limited usage on training and - * serving. You can use this method to start a join operation on specified - * events with the latest version of product catalog. You can also use this - * method to correct events joined with the wrong product catalog. A rejoin - * operation can take hours or days to complete. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent catalog resource name, such as - * `projects/1234/locations/global/catalogs/default_catalog`. - * @param {google.cloud.retail.v2alpha.RejoinUserEventsRequest.UserEventRejoinScope} request.userEventRejoinScope - * The type of the user event rejoin to define the scope and range of the user - * events to be rejoined with the latest product catalog. Defaults to - * `USER_EVENT_REJOIN_SCOPE_UNSPECIFIED` if this field is not set, or set to - * an invalid integer value. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing - * a long running operation. Its `promise()` method returns a promise - * you can `await` for. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/user_event_service.rejoin_user_events.js - * region_tag:retail_v2alpha_generated_UserEventService_RejoinUserEvents_async - */ + /** + * Starts a user-event rejoin operation with latest product catalog. Events + * are not annotated with detailed product information for products that are + * missing from the catalog when the user event is ingested. These + * events are stored as unjoined events with limited usage on training and + * serving. You can use this method to start a join operation on specified + * events with the latest version of product catalog. You can also use this + * method to correct events joined with the wrong product catalog. A rejoin + * operation can take hours or days to complete. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent catalog resource name, such as + * `projects/1234/locations/global/catalogs/default_catalog`. + * @param {google.cloud.retail.v2alpha.RejoinUserEventsRequest.UserEventRejoinScope} request.userEventRejoinScope + * The type of the user event rejoin to define the scope and range of the user + * events to be rejoined with the latest product catalog. Defaults to + * `USER_EVENT_REJOIN_SCOPE_UNSPECIFIED` if this field is not set, or set to + * an invalid integer value. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/user_event_service.rejoin_user_events.js + * region_tag:retail_v2alpha_generated_UserEventService_RejoinUserEvents_async + */ rejoinUserEvents( - request?: protos.google.cloud.retail.v2alpha.IRejoinUserEventsRequest, - options?: CallOptions): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.IRejoinUserEventsRequest, + options?: CallOptions, + ): Promise< + [ + LROperation< + protos.google.cloud.retail.v2alpha.IRejoinUserEventsResponse, + protos.google.cloud.retail.v2alpha.IRejoinUserEventsMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; rejoinUserEvents( - request: protos.google.cloud.retail.v2alpha.IRejoinUserEventsRequest, - options: CallOptions, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IRejoinUserEventsRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IRejoinUserEventsResponse, + protos.google.cloud.retail.v2alpha.IRejoinUserEventsMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; rejoinUserEvents( - request: protos.google.cloud.retail.v2alpha.IRejoinUserEventsRequest, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IRejoinUserEventsRequest, + callback: Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IRejoinUserEventsResponse, + protos.google.cloud.retail.v2alpha.IRejoinUserEventsMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; rejoinUserEvents( - request?: protos.google.cloud.retail.v2alpha.IRejoinUserEventsRequest, - optionsOrCallback?: CallOptions|Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>, - callback?: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>|void { + request?: protos.google.cloud.retail.v2alpha.IRejoinUserEventsRequest, + optionsOrCallback?: + | CallOptions + | Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IRejoinUserEventsResponse, + protos.google.cloud.retail.v2alpha.IRejoinUserEventsMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + callback?: Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IRejoinUserEventsResponse, + protos.google.cloud.retail.v2alpha.IRejoinUserEventsMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + LROperation< + protos.google.cloud.retail.v2alpha.IRejoinUserEventsResponse, + protos.google.cloud.retail.v2alpha.IRejoinUserEventsMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IRejoinUserEventsResponse, + protos.google.cloud.retail.v2alpha.IRejoinUserEventsMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, rawResponse, _) => { this._log.info('rejoinUserEvents response %j', rawResponse); callback!(error, response, rawResponse, _); // We verified `callback` above. } : undefined; this._log.info('rejoinUserEvents request %j', request); - return this.innerApiCalls.rejoinUserEvents(request, options, wrappedCallback) - ?.then(([response, rawResponse, _]: [ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]) => { - this._log.info('rejoinUserEvents response %j', rawResponse); - return [response, rawResponse, _]; - }); + return this.innerApiCalls + .rejoinUserEvents(request, options, wrappedCallback) + ?.then( + ([response, rawResponse, _]: [ + LROperation< + protos.google.cloud.retail.v2alpha.IRejoinUserEventsResponse, + protos.google.cloud.retail.v2alpha.IRejoinUserEventsMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ]) => { + this._log.info('rejoinUserEvents response %j', rawResponse); + return [response, rawResponse, _]; + }, + ); } -/** - * Check the status of the long running operation returned by `rejoinUserEvents()`. - * @param {String} name - * The operation name that will be passed. - * @returns {Promise} - The promise which resolves to an object. - * The decoded operation object has result and metadata field to get information from. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/user_event_service.rejoin_user_events.js - * region_tag:retail_v2alpha_generated_UserEventService_RejoinUserEvents_async - */ - async checkRejoinUserEventsProgress(name: string): Promise>{ + /** + * Check the status of the long running operation returned by `rejoinUserEvents()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/user_event_service.rejoin_user_events.js + * region_tag:retail_v2alpha_generated_UserEventService_RejoinUserEvents_async + */ + async checkRejoinUserEventsProgress( + name: string, + ): Promise< + LROperation< + protos.google.cloud.retail.v2alpha.RejoinUserEventsResponse, + protos.google.cloud.retail.v2alpha.RejoinUserEventsMetadata + > + > { this._log.info('rejoinUserEvents long-running'); - const request = new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest({name}); + const request = + new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( + { name }, + ); const [operation] = await this.operationsClient.getOperation(request); - const decodeOperation = new this._gaxModule.Operation(operation, this.descriptors.longrunning.rejoinUserEvents, this._gaxModule.createDefaultBackoffSettings()); - return decodeOperation as LROperation; + const decodeOperation = new this._gaxModule.Operation( + operation, + this.descriptors.longrunning.rejoinUserEvents, + this._gaxModule.createDefaultBackoffSettings(), + ); + return decodeOperation as LROperation< + protos.google.cloud.retail.v2alpha.RejoinUserEventsResponse, + protos.google.cloud.retail.v2alpha.RejoinUserEventsMetadata + >; } // -------------------- // -- Path templates -- @@ -1192,7 +1611,7 @@ export class UserEventServiceClient { * @param {string} project * @returns {string} Resource name string. */ - alertConfigPath(project:string) { + alertConfigPath(project: string) { return this.pathTemplates.alertConfigPathTemplate.render({ project: project, }); @@ -1206,7 +1625,8 @@ export class UserEventServiceClient { * @returns {string} A string representing the project. */ matchProjectFromAlertConfigName(alertConfigName: string) { - return this.pathTemplates.alertConfigPathTemplate.match(alertConfigName).project; + return this.pathTemplates.alertConfigPathTemplate.match(alertConfigName) + .project; } /** @@ -1217,7 +1637,7 @@ export class UserEventServiceClient { * @param {string} catalog * @returns {string} Resource name string. */ - attributesConfigPath(project:string,location:string,catalog:string) { + attributesConfigPath(project: string, location: string, catalog: string) { return this.pathTemplates.attributesConfigPathTemplate.render({ project: project, location: location, @@ -1233,7 +1653,9 @@ export class UserEventServiceClient { * @returns {string} A string representing the project. */ matchProjectFromAttributesConfigName(attributesConfigName: string) { - return this.pathTemplates.attributesConfigPathTemplate.match(attributesConfigName).project; + return this.pathTemplates.attributesConfigPathTemplate.match( + attributesConfigName, + ).project; } /** @@ -1244,7 +1666,9 @@ export class UserEventServiceClient { * @returns {string} A string representing the location. */ matchLocationFromAttributesConfigName(attributesConfigName: string) { - return this.pathTemplates.attributesConfigPathTemplate.match(attributesConfigName).location; + return this.pathTemplates.attributesConfigPathTemplate.match( + attributesConfigName, + ).location; } /** @@ -1255,7 +1679,9 @@ export class UserEventServiceClient { * @returns {string} A string representing the catalog. */ matchCatalogFromAttributesConfigName(attributesConfigName: string) { - return this.pathTemplates.attributesConfigPathTemplate.match(attributesConfigName).catalog; + return this.pathTemplates.attributesConfigPathTemplate.match( + attributesConfigName, + ).catalog; } /** @@ -1267,7 +1693,12 @@ export class UserEventServiceClient { * @param {string} branch * @returns {string} Resource name string. */ - branchPath(project:string,location:string,catalog:string,branch:string) { + branchPath( + project: string, + location: string, + catalog: string, + branch: string, + ) { return this.pathTemplates.branchPathTemplate.render({ project: project, location: location, @@ -1328,7 +1759,7 @@ export class UserEventServiceClient { * @param {string} catalog * @returns {string} Resource name string. */ - catalogPath(project:string,location:string,catalog:string) { + catalogPath(project: string, location: string, catalog: string) { return this.pathTemplates.catalogPathTemplate.render({ project: project, location: location, @@ -1377,7 +1808,7 @@ export class UserEventServiceClient { * @param {string} catalog * @returns {string} Resource name string. */ - completionConfigPath(project:string,location:string,catalog:string) { + completionConfigPath(project: string, location: string, catalog: string) { return this.pathTemplates.completionConfigPathTemplate.render({ project: project, location: location, @@ -1393,7 +1824,9 @@ export class UserEventServiceClient { * @returns {string} A string representing the project. */ matchProjectFromCompletionConfigName(completionConfigName: string) { - return this.pathTemplates.completionConfigPathTemplate.match(completionConfigName).project; + return this.pathTemplates.completionConfigPathTemplate.match( + completionConfigName, + ).project; } /** @@ -1404,7 +1837,9 @@ export class UserEventServiceClient { * @returns {string} A string representing the location. */ matchLocationFromCompletionConfigName(completionConfigName: string) { - return this.pathTemplates.completionConfigPathTemplate.match(completionConfigName).location; + return this.pathTemplates.completionConfigPathTemplate.match( + completionConfigName, + ).location; } /** @@ -1415,7 +1850,9 @@ export class UserEventServiceClient { * @returns {string} A string representing the catalog. */ matchCatalogFromCompletionConfigName(completionConfigName: string) { - return this.pathTemplates.completionConfigPathTemplate.match(completionConfigName).catalog; + return this.pathTemplates.completionConfigPathTemplate.match( + completionConfigName, + ).catalog; } /** @@ -1427,7 +1864,12 @@ export class UserEventServiceClient { * @param {string} control * @returns {string} Resource name string. */ - controlPath(project:string,location:string,catalog:string,control:string) { + controlPath( + project: string, + location: string, + catalog: string, + control: string, + ) { return this.pathTemplates.controlPathTemplate.render({ project: project, location: location, @@ -1486,7 +1928,7 @@ export class UserEventServiceClient { * @param {string} project * @returns {string} Resource name string. */ - loggingConfigPath(project:string) { + loggingConfigPath(project: string) { return this.pathTemplates.loggingConfigPathTemplate.render({ project: project, }); @@ -1500,7 +1942,8 @@ export class UserEventServiceClient { * @returns {string} A string representing the project. */ matchProjectFromLoggingConfigName(loggingConfigName: string) { - return this.pathTemplates.loggingConfigPathTemplate.match(loggingConfigName).project; + return this.pathTemplates.loggingConfigPathTemplate.match(loggingConfigName) + .project; } /** @@ -1512,7 +1955,12 @@ export class UserEventServiceClient { * @param {string} merchant_center_account_link * @returns {string} Resource name string. */ - merchantCenterAccountLinkPath(project:string,location:string,catalog:string,merchantCenterAccountLink:string) { + merchantCenterAccountLinkPath( + project: string, + location: string, + catalog: string, + merchantCenterAccountLink: string, + ) { return this.pathTemplates.merchantCenterAccountLinkPathTemplate.render({ project: project, location: location, @@ -1528,8 +1976,12 @@ export class UserEventServiceClient { * A fully-qualified path representing MerchantCenterAccountLink resource. * @returns {string} A string representing the project. */ - matchProjectFromMerchantCenterAccountLinkName(merchantCenterAccountLinkName: string) { - return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match(merchantCenterAccountLinkName).project; + matchProjectFromMerchantCenterAccountLinkName( + merchantCenterAccountLinkName: string, + ) { + return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match( + merchantCenterAccountLinkName, + ).project; } /** @@ -1539,8 +1991,12 @@ export class UserEventServiceClient { * A fully-qualified path representing MerchantCenterAccountLink resource. * @returns {string} A string representing the location. */ - matchLocationFromMerchantCenterAccountLinkName(merchantCenterAccountLinkName: string) { - return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match(merchantCenterAccountLinkName).location; + matchLocationFromMerchantCenterAccountLinkName( + merchantCenterAccountLinkName: string, + ) { + return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match( + merchantCenterAccountLinkName, + ).location; } /** @@ -1550,8 +2006,12 @@ export class UserEventServiceClient { * A fully-qualified path representing MerchantCenterAccountLink resource. * @returns {string} A string representing the catalog. */ - matchCatalogFromMerchantCenterAccountLinkName(merchantCenterAccountLinkName: string) { - return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match(merchantCenterAccountLinkName).catalog; + matchCatalogFromMerchantCenterAccountLinkName( + merchantCenterAccountLinkName: string, + ) { + return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match( + merchantCenterAccountLinkName, + ).catalog; } /** @@ -1561,8 +2021,12 @@ export class UserEventServiceClient { * A fully-qualified path representing MerchantCenterAccountLink resource. * @returns {string} A string representing the merchant_center_account_link. */ - matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName(merchantCenterAccountLinkName: string) { - return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match(merchantCenterAccountLinkName).merchant_center_account_link; + matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName( + merchantCenterAccountLinkName: string, + ) { + return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match( + merchantCenterAccountLinkName, + ).merchant_center_account_link; } /** @@ -1574,7 +2038,7 @@ export class UserEventServiceClient { * @param {string} model * @returns {string} Resource name string. */ - modelPath(project:string,location:string,catalog:string,model:string) { + modelPath(project: string, location: string, catalog: string, model: string) { return this.pathTemplates.modelPathTemplate.render({ project: project, location: location, @@ -1637,7 +2101,13 @@ export class UserEventServiceClient { * @param {string} product * @returns {string} Resource name string. */ - productPath(project:string,location:string,catalog:string,branch:string,product:string) { + productPath( + project: string, + location: string, + catalog: string, + branch: string, + product: string, + ) { return this.pathTemplates.productPathTemplate.render({ project: project, location: location, @@ -1708,7 +2178,7 @@ export class UserEventServiceClient { * @param {string} project * @returns {string} Resource name string. */ - retailProjectPath(project:string) { + retailProjectPath(project: string) { return this.pathTemplates.retailProjectPathTemplate.render({ project: project, }); @@ -1722,7 +2192,8 @@ export class UserEventServiceClient { * @returns {string} A string representing the project. */ matchProjectFromRetailProjectName(retailProjectName: string) { - return this.pathTemplates.retailProjectPathTemplate.match(retailProjectName).project; + return this.pathTemplates.retailProjectPathTemplate.match(retailProjectName) + .project; } /** @@ -1734,7 +2205,12 @@ export class UserEventServiceClient { * @param {string} serving_config * @returns {string} Resource name string. */ - servingConfigPath(project:string,location:string,catalog:string,servingConfig:string) { + servingConfigPath( + project: string, + location: string, + catalog: string, + servingConfig: string, + ) { return this.pathTemplates.servingConfigPathTemplate.render({ project: project, location: location, @@ -1751,7 +2227,8 @@ export class UserEventServiceClient { * @returns {string} A string representing the project. */ matchProjectFromServingConfigName(servingConfigName: string) { - return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName).project; + return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName) + .project; } /** @@ -1762,7 +2239,8 @@ export class UserEventServiceClient { * @returns {string} A string representing the location. */ matchLocationFromServingConfigName(servingConfigName: string) { - return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName).location; + return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName) + .location; } /** @@ -1773,7 +2251,8 @@ export class UserEventServiceClient { * @returns {string} A string representing the catalog. */ matchCatalogFromServingConfigName(servingConfigName: string) { - return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName).catalog; + return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName) + .catalog; } /** @@ -1784,7 +2263,8 @@ export class UserEventServiceClient { * @returns {string} A string representing the serving_config. */ matchServingConfigFromServingConfigName(servingConfigName: string) { - return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName).serving_config; + return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName) + .serving_config; } /** @@ -1795,7 +2275,7 @@ export class UserEventServiceClient { */ close(): Promise { if (this.userEventServiceStub && !this._terminated) { - return this.userEventServiceStub.then(stub => { + return this.userEventServiceStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -1804,4 +2284,4 @@ export class UserEventServiceClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/system-test/fixtures/sample/src/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/system-test/fixtures/sample/src/index.ts.baseline index bdba7b07a3bf..207a24e007ef 100644 --- a/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/system-test/fixtures/sample/src/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/system-test/fixtures/sample/src/index.ts.baseline @@ -17,7 +17,23 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -import {AnalyticsServiceClient, BranchServiceClient, CatalogServiceClient, CompletionServiceClient, ControlServiceClient, ConversationalSearchServiceClient, GenerativeQuestionServiceClient, MerchantCenterAccountLinkServiceClient, ModelServiceClient, PredictionServiceClient, ProductServiceClient, ProjectServiceClient, SearchServiceClient, ServingConfigServiceClient, UserEventServiceClient} from 'retail'; +import { + AnalyticsServiceClient, + BranchServiceClient, + CatalogServiceClient, + CompletionServiceClient, + ControlServiceClient, + ConversationalSearchServiceClient, + GenerativeQuestionServiceClient, + MerchantCenterAccountLinkServiceClient, + ModelServiceClient, + PredictionServiceClient, + ProductServiceClient, + ProjectServiceClient, + SearchServiceClient, + ServingConfigServiceClient, + UserEventServiceClient, +} from 'retail'; // check that the client class type name can be used function doStuffWithAnalyticsServiceClient(client: AnalyticsServiceClient) { @@ -35,13 +51,19 @@ function doStuffWithCompletionServiceClient(client: CompletionServiceClient) { function doStuffWithControlServiceClient(client: ControlServiceClient) { client.close(); } -function doStuffWithConversationalSearchServiceClient(client: ConversationalSearchServiceClient) { +function doStuffWithConversationalSearchServiceClient( + client: ConversationalSearchServiceClient, +) { client.close(); } -function doStuffWithGenerativeQuestionServiceClient(client: GenerativeQuestionServiceClient) { +function doStuffWithGenerativeQuestionServiceClient( + client: GenerativeQuestionServiceClient, +) { client.close(); } -function doStuffWithMerchantCenterAccountLinkServiceClient(client: MerchantCenterAccountLinkServiceClient) { +function doStuffWithMerchantCenterAccountLinkServiceClient( + client: MerchantCenterAccountLinkServiceClient, +) { client.close(); } function doStuffWithModelServiceClient(client: ModelServiceClient) { @@ -59,7 +81,9 @@ function doStuffWithProjectServiceClient(client: ProjectServiceClient) { function doStuffWithSearchServiceClient(client: SearchServiceClient) { client.close(); } -function doStuffWithServingConfigServiceClient(client: ServingConfigServiceClient) { +function doStuffWithServingConfigServiceClient( + client: ServingConfigServiceClient, +) { client.close(); } function doStuffWithUserEventServiceClient(client: UserEventServiceClient) { @@ -83,14 +107,20 @@ function main() { const controlServiceClient = new ControlServiceClient(); doStuffWithControlServiceClient(controlServiceClient); // check that the client instance can be created - const conversationalSearchServiceClient = new ConversationalSearchServiceClient(); - doStuffWithConversationalSearchServiceClient(conversationalSearchServiceClient); + const conversationalSearchServiceClient = + new ConversationalSearchServiceClient(); + doStuffWithConversationalSearchServiceClient( + conversationalSearchServiceClient, + ); // check that the client instance can be created const generativeQuestionServiceClient = new GenerativeQuestionServiceClient(); doStuffWithGenerativeQuestionServiceClient(generativeQuestionServiceClient); // check that the client instance can be created - const merchantCenterAccountLinkServiceClient = new MerchantCenterAccountLinkServiceClient(); - doStuffWithMerchantCenterAccountLinkServiceClient(merchantCenterAccountLinkServiceClient); + const merchantCenterAccountLinkServiceClient = + new MerchantCenterAccountLinkServiceClient(); + doStuffWithMerchantCenterAccountLinkServiceClient( + merchantCenterAccountLinkServiceClient, + ); // check that the client instance can be created const modelServiceClient = new ModelServiceClient(); doStuffWithModelServiceClient(modelServiceClient); diff --git a/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/system-test/install.ts.baseline b/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/system-test/install.ts.baseline index e079c4fa1101..d109fdd8c97f 100644 --- a/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/system-test/install.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/system-test/install.ts.baseline @@ -16,40 +16,45 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -import {packNTest} from 'pack-n-play'; -import {readFileSync} from 'fs'; -import {describe, it} from 'mocha'; +import { packNTest } from 'pack-n-play'; +import { readFileSync } from 'fs'; +import { describe, it } from 'mocha'; describe('📦 pack-n-play test', () => { - it('TypeScript', async function() { + it('TypeScript', async function () { this.timeout(300000); await packNTest({ packageDir: process.cwd(), sample: { description: 'TypeScript user can use the type definitions', - ts: readFileSync('./esm/system-test/fixtures/sample/src/index.ts').toString() - } + ts: readFileSync( + './esm/system-test/fixtures/sample/src/index.ts', + ).toString(), + }, }); }); - it('ESM module', async function() { + it('ESM module', async function () { this.timeout(300000); await packNTest({ sample: { description: 'Should be able to import using ESM', - esm: readFileSync('./esm/system-test/fixtures/sample/src/index.js').toString(), + esm: readFileSync( + './esm/system-test/fixtures/sample/src/index.js', + ).toString(), }, }); }); - it('CJS module', async function() { + it('CJS module', async function () { this.timeout(300000); await packNTest({ sample: { description: 'Should be able to import using CJS', - cjs: readFileSync('./esm/system-test/fixtures/sample/src/index.cjs').toString(), + cjs: readFileSync( + './esm/system-test/fixtures/sample/src/index.cjs', + ).toString(), }, }); }); - }); diff --git a/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/test/gapic_analytics_service_v2alpha.ts.baseline b/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/test/gapic_analytics_service_v2alpha.ts.baseline index 8a505ca00160..65619f495f32 100644 --- a/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/test/gapic_analytics_service_v2alpha.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/test/gapic_analytics_service_v2alpha.ts.baseline @@ -20,14 +20,14 @@ import * as protos from '../../protos/protos.js'; import assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as analyticsserviceModule from '../src/index.js'; -import {protobuf, LROperation, operationsProtos} from 'google-gax'; +import { protobuf, LROperation, operationsProtos } from 'google-gax'; import fs from 'fs'; import path from 'path'; -import {fileURLToPath} from 'url'; +import { fileURLToPath } from 'url'; // @ts-ignore const dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -35,918 +35,1285 @@ const dirname = path.dirname(fileURLToPath(import.meta.url)); // to fill in default values for request objects const root = protobuf.Root.fromJSON( JSON.parse( - fs.readFileSync(path.join(dirname, '..', '..', 'protos/protos.json'), 'utf8') - )) + fs.readFileSync( + path.join(dirname, '..', '..', 'protos/protos.json'), + 'utf8', + ), + ), +); // eslint-disable-next-line @typescript-eslint/no-unused-vars function getTypeDefaultValue(typeName: string, fields: string[]) { - let type = root.lookupType(typeName) as protobuf.Type; - for (const field of fields.slice(0, -1)) { - type = type?.fields[field]?.resolvedType as protobuf.Type; - } - return type?.fields[fields[fields.length - 1]]?.defaultValue ?? null; + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type?.fields[field]?.resolvedType as protobuf.Type; + } + return type?.fields[fields[fields.length - 1]]?.defaultValue ?? null; } function generateSampleMessage(instance: T) { - const filledObject = (instance.constructor as typeof protobuf.Message) - .toObject(instance as protobuf.Message, {defaults: true}); - return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, { defaults: true }); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; } function stubSimpleCall(response?: ResponseType, error?: Error) { - return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); } -function stubLongRunningCall(response?: ResponseType, callError?: Error, lroError?: Error) { - const innerStub = lroError ? sinon.stub().rejects(lroError) : sinon.stub().resolves([response]); - const mockOperation = { - promise: innerStub, - }; - return callError ? sinon.stub().rejects(callError) : sinon.stub().resolves([mockOperation]); +function stubLongRunningCall( + response?: ResponseType, + callError?: Error, + lroError?: Error, +) { + const innerStub = lroError + ? sinon.stub().rejects(lroError) + : sinon.stub().resolves([response]); + const mockOperation = { + promise: innerStub, + }; + return callError + ? sinon.stub().rejects(callError) + : sinon.stub().resolves([mockOperation]); } -function stubLongRunningCallWithCallback(response?: ResponseType, callError?: Error, lroError?: Error) { - const innerStub = lroError ? sinon.stub().rejects(lroError) : sinon.stub().resolves([response]); - const mockOperation = { - promise: innerStub, - }; - return callError ? sinon.stub().callsArgWith(2, callError) : sinon.stub().callsArgWith(2, null, mockOperation); +function stubLongRunningCallWithCallback( + response?: ResponseType, + callError?: Error, + lroError?: Error, +) { + const innerStub = lroError + ? sinon.stub().rejects(lroError) + : sinon.stub().resolves([response]); + const mockOperation = { + promise: innerStub, + }; + return callError + ? sinon.stub().callsArgWith(2, callError) + : sinon.stub().callsArgWith(2, null, mockOperation); } describe('v2alpha.AnalyticsServiceClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new analyticsserviceModule.v2alpha.AnalyticsServiceClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'retail.googleapis.com'); - }); - - it('has universeDomain', () => { - const client = new analyticsserviceModule.v2alpha.AnalyticsServiceClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); - - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - it('throws DeprecationWarning if static servicePath is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const servicePath = analyticsserviceModule.v2alpha.AnalyticsServiceClient.servicePath; - assert.strictEqual(servicePath, 'retail.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = analyticsserviceModule.v2alpha.AnalyticsServiceClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'retail.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new analyticsserviceModule.v2alpha.AnalyticsServiceClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'retail.example.com'); - }); - - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new analyticsserviceModule.v2alpha.AnalyticsServiceClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'retail.example.com'); - }); - - if (typeof process === 'object' && 'env' in process) { - describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { - it('sets apiEndpoint from environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new analyticsserviceModule.v2alpha.AnalyticsServiceClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'retail.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - - it('value configured in code has priority over environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new analyticsserviceModule.v2alpha.AnalyticsServiceClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'retail.configured.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { new analyticsserviceModule.v2alpha.AnalyticsServiceClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); - - it('has port', () => { - const port = analyticsserviceModule.v2alpha.AnalyticsServiceClient.port; - assert(port); - assert(typeof port === 'number'); - }); - - it('should create a client with no option', () => { - const client = new analyticsserviceModule.v2alpha.AnalyticsServiceClient(); - assert(client); - }); - - it('should create a client with gRPC fallback', () => { - const client = new analyticsserviceModule.v2alpha.AnalyticsServiceClient({ - fallback: true, - }); - assert(client); - }); - - it('has initialize method and supports deferred initialization', async () => { - const client = new analyticsserviceModule.v2alpha.AnalyticsServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.analyticsServiceStub, undefined); - await client.initialize(); - assert(client.analyticsServiceStub); - }); - - it('has close method for the initialized client', done => { - const client = new analyticsserviceModule.v2alpha.AnalyticsServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.analyticsServiceStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); - - it('has close method for the non-initialized client', done => { - const client = new analyticsserviceModule.v2alpha.AnalyticsServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.analyticsServiceStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); - - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new analyticsserviceModule.v2alpha.AnalyticsServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); - }); - - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new analyticsserviceModule.v2alpha.AnalyticsServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId((err?: Error|null, projectId?: string|null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } - }); - }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = + new analyticsserviceModule.v2alpha.AnalyticsServiceClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'retail.googleapis.com'); }); - describe('exportAnalyticsMetrics', () => { - it('invokes exportAnalyticsMetrics without error', async () => { - const client = new analyticsserviceModule.v2alpha.AnalyticsServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ExportAnalyticsMetricsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ExportAnalyticsMetricsRequest', ['catalog']); - request.catalog = defaultValue1; - const expectedHeaderRequestParams = `catalog=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.exportAnalyticsMetrics = stubLongRunningCall(expectedResponse); - const [operation] = await client.exportAnalyticsMetrics(request); - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.exportAnalyticsMetrics as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.exportAnalyticsMetrics as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes exportAnalyticsMetrics without error using callback', async () => { - const client = new analyticsserviceModule.v2alpha.AnalyticsServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ExportAnalyticsMetricsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ExportAnalyticsMetricsRequest', ['catalog']); - request.catalog = defaultValue1; - const expectedHeaderRequestParams = `catalog=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.exportAnalyticsMetrics = stubLongRunningCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.exportAnalyticsMetrics( - request, - (err?: Error|null, - result?: LROperation|null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const operation = await promise as LROperation; - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.exportAnalyticsMetrics as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.exportAnalyticsMetrics as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes exportAnalyticsMetrics with call error', async () => { - const client = new analyticsserviceModule.v2alpha.AnalyticsServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ExportAnalyticsMetricsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ExportAnalyticsMetricsRequest', ['catalog']); - request.catalog = defaultValue1; - const expectedHeaderRequestParams = `catalog=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.exportAnalyticsMetrics = stubLongRunningCall(undefined, expectedError); - await assert.rejects(client.exportAnalyticsMetrics(request), expectedError); - const actualRequest = (client.innerApiCalls.exportAnalyticsMetrics as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.exportAnalyticsMetrics as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes exportAnalyticsMetrics with LRO error', async () => { - const client = new analyticsserviceModule.v2alpha.AnalyticsServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ExportAnalyticsMetricsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ExportAnalyticsMetricsRequest', ['catalog']); - request.catalog = defaultValue1; - const expectedHeaderRequestParams = `catalog=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.exportAnalyticsMetrics = stubLongRunningCall(undefined, undefined, expectedError); - const [operation] = await client.exportAnalyticsMetrics(request); - await assert.rejects(operation.promise(), expectedError); - const actualRequest = (client.innerApiCalls.exportAnalyticsMetrics as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.exportAnalyticsMetrics as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes checkExportAnalyticsMetricsProgress without error', async () => { - const client = new analyticsserviceModule.v2alpha.AnalyticsServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedResponse = generateSampleMessage( - new operationsProtos.google.longrunning.Operation() - ); - expectedResponse.name = 'test'; - expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; - expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')} - - client.operationsClient.getOperation = stubSimpleCall(expectedResponse); - const decodedOperation = await client.checkExportAnalyticsMetricsProgress(expectedResponse.name); - assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); - assert(decodedOperation.metadata); - assert((client.operationsClient.getOperation as SinonStub).getCall(0)); - }); - - it('invokes checkExportAnalyticsMetricsProgress with error', async () => { - const client = new analyticsserviceModule.v2alpha.AnalyticsServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedError = new Error('expected'); - - client.operationsClient.getOperation = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.checkExportAnalyticsMetricsProgress(''), expectedError); - assert((client.operationsClient.getOperation as SinonStub) - .getCall(0)); - }); + it('has universeDomain', () => { + const client = + new analyticsserviceModule.v2alpha.AnalyticsServiceClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); }); - describe('Path templates', () => { - - describe('alertConfig', () => { - const fakePath = "/rendered/path/alertConfig"; - const expectedParameters = { - project: "projectValue", - }; - const client = new analyticsserviceModule.v2alpha.AnalyticsServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.alertConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.alertConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('alertConfigPath', () => { - const result = client.alertConfigPath("projectValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.alertConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromAlertConfigName', () => { - const result = client.matchProjectFromAlertConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.alertConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('attributesConfig', () => { - const fakePath = "/rendered/path/attributesConfig"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - }; - const client = new analyticsserviceModule.v2alpha.AnalyticsServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.attributesConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.attributesConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('attributesConfigPath', () => { - const result = client.attributesConfigPath("projectValue", "locationValue", "catalogValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.attributesConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromAttributesConfigName', () => { - const result = client.matchProjectFromAttributesConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = + analyticsserviceModule.v2alpha.AnalyticsServiceClient.servicePath; + assert.strictEqual(servicePath, 'retail.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + analyticsserviceModule.v2alpha.AnalyticsServiceClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'retail.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = new analyticsserviceModule.v2alpha.AnalyticsServiceClient({ + universeDomain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'retail.example.com'); + }); - it('matchLocationFromAttributesConfigName', () => { - const result = client.matchLocationFromAttributesConfigName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = new analyticsserviceModule.v2alpha.AnalyticsServiceClient({ + universe_domain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'retail.example.com'); + }); - it('matchCatalogFromAttributesConfigName', () => { - const result = client.matchCatalogFromAttributesConfigName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + if (typeof process === 'object' && 'env' in process) { + describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { + it('sets apiEndpoint from environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = + new analyticsserviceModule.v2alpha.AnalyticsServiceClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'retail.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - describe('branch', () => { - const fakePath = "/rendered/path/branch"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - branch: "branchValue", - }; - const client = new analyticsserviceModule.v2alpha.AnalyticsServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.branchPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.branchPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('branchPath', () => { - const result = client.branchPath("projectValue", "locationValue", "catalogValue", "branchValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.branchPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromBranchName', () => { - const result = client.matchProjectFromBranchName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.branchPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromBranchName', () => { - const result = client.matchLocationFromBranchName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.branchPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromBranchName', () => { - const result = client.matchCatalogFromBranchName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.branchPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBranchFromBranchName', () => { - const result = client.matchBranchFromBranchName(fakePath); - assert.strictEqual(result, "branchValue"); - assert((client.pathTemplates.branchPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('value configured in code has priority over environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = + new analyticsserviceModule.v2alpha.AnalyticsServiceClient({ + universeDomain: 'configured.example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'retail.configured.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - - describe('catalog', () => { - const fakePath = "/rendered/path/catalog"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - }; - const client = new analyticsserviceModule.v2alpha.AnalyticsServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.catalogPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.catalogPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('catalogPath', () => { - const result = client.catalogPath("projectValue", "locationValue", "catalogValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.catalogPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromCatalogName', () => { - const result = client.matchProjectFromCatalogName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.catalogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromCatalogName', () => { - const result = client.matchLocationFromCatalogName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.catalogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromCatalogName', () => { - const result = client.matchCatalogFromCatalogName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.catalogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('completionConfig', () => { - const fakePath = "/rendered/path/completionConfig"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - }; - const client = new analyticsserviceModule.v2alpha.AnalyticsServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.completionConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.completionConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('completionConfigPath', () => { - const result = client.completionConfigPath("projectValue", "locationValue", "catalogValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.completionConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromCompletionConfigName', () => { - const result = client.matchProjectFromCompletionConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.completionConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromCompletionConfigName', () => { - const result = client.matchLocationFromCompletionConfigName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.completionConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromCompletionConfigName', () => { - const result = client.matchCatalogFromCompletionConfigName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.completionConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new analyticsserviceModule.v2alpha.AnalyticsServiceClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); + }); - describe('control', () => { - const fakePath = "/rendered/path/control"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - control: "controlValue", - }; - const client = new analyticsserviceModule.v2alpha.AnalyticsServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.controlPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.controlPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('controlPath', () => { - const result = client.controlPath("projectValue", "locationValue", "catalogValue", "controlValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.controlPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + it('has port', () => { + const port = analyticsserviceModule.v2alpha.AnalyticsServiceClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('matchProjectFromControlName', () => { - const result = client.matchProjectFromControlName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.controlPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('should create a client with no option', () => { + const client = + new analyticsserviceModule.v2alpha.AnalyticsServiceClient(); + assert(client); + }); - it('matchLocationFromControlName', () => { - const result = client.matchLocationFromControlName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.controlPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('should create a client with gRPC fallback', () => { + const client = new analyticsserviceModule.v2alpha.AnalyticsServiceClient({ + fallback: true, + }); + assert(client); + }); - it('matchCatalogFromControlName', () => { - const result = client.matchCatalogFromControlName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.controlPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('has initialize method and supports deferred initialization', async () => { + const client = new analyticsserviceModule.v2alpha.AnalyticsServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.analyticsServiceStub, undefined); + await client.initialize(); + assert(client.analyticsServiceStub); + }); - it('matchControlFromControlName', () => { - const result = client.matchControlFromControlName(fakePath); - assert.strictEqual(result, "controlValue"); - assert((client.pathTemplates.controlPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('has close method for the initialized client', (done) => { + const client = new analyticsserviceModule.v2alpha.AnalyticsServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.analyticsServiceStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - describe('loggingConfig', () => { - const fakePath = "/rendered/path/loggingConfig"; - const expectedParameters = { - project: "projectValue", - }; - const client = new analyticsserviceModule.v2alpha.AnalyticsServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.loggingConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.loggingConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('loggingConfigPath', () => { - const result = client.loggingConfigPath("projectValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.loggingConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromLoggingConfigName', () => { - const result = client.matchProjectFromLoggingConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.loggingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('has close method for the non-initialized client', (done) => { + const client = new analyticsserviceModule.v2alpha.AnalyticsServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.analyticsServiceStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - describe('merchantCenterAccountLink', () => { - const fakePath = "/rendered/path/merchantCenterAccountLink"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - merchant_center_account_link: "merchantCenterAccountLinkValue", - }; - const client = new analyticsserviceModule.v2alpha.AnalyticsServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.merchantCenterAccountLinkPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.merchantCenterAccountLinkPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('merchantCenterAccountLinkPath', () => { - const result = client.merchantCenterAccountLinkPath("projectValue", "locationValue", "catalogValue", "merchantCenterAccountLinkValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromMerchantCenterAccountLinkName', () => { - const result = client.matchProjectFromMerchantCenterAccountLinkName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromMerchantCenterAccountLinkName', () => { - const result = client.matchLocationFromMerchantCenterAccountLinkName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromMerchantCenterAccountLinkName', () => { - const result = client.matchCatalogFromMerchantCenterAccountLinkName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new analyticsserviceModule.v2alpha.AnalyticsServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + }); - it('matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName', () => { - const result = client.matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName(fakePath); - assert.strictEqual(result, "merchantCenterAccountLinkValue"); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new analyticsserviceModule.v2alpha.AnalyticsServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + }); + + describe('exportAnalyticsMetrics', () => { + it('invokes exportAnalyticsMetrics without error', async () => { + const client = new analyticsserviceModule.v2alpha.AnalyticsServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ExportAnalyticsMetricsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ExportAnalyticsMetricsRequest', + ['catalog'], + ); + request.catalog = defaultValue1; + const expectedHeaderRequestParams = `catalog=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.exportAnalyticsMetrics = + stubLongRunningCall(expectedResponse); + const [operation] = await client.exportAnalyticsMetrics(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.exportAnalyticsMetrics as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.exportAnalyticsMetrics as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - describe('model', () => { - const fakePath = "/rendered/path/model"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - model: "modelValue", - }; - const client = new analyticsserviceModule.v2alpha.AnalyticsServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.modelPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.modelPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('modelPath', () => { - const result = client.modelPath("projectValue", "locationValue", "catalogValue", "modelValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.modelPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromModelName', () => { - const result = client.matchProjectFromModelName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromModelName', () => { - const result = client.matchLocationFromModelName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('invokes exportAnalyticsMetrics without error using callback', async () => { + const client = new analyticsserviceModule.v2alpha.AnalyticsServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ExportAnalyticsMetricsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ExportAnalyticsMetricsRequest', + ['catalog'], + ); + request.catalog = defaultValue1; + const expectedHeaderRequestParams = `catalog=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.exportAnalyticsMetrics = + stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.exportAnalyticsMetrics( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.cloud.retail.v2alpha.IExportAnalyticsMetricsResponse, + protos.google.cloud.retail.v2alpha.IExportMetadata + > | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const operation = (await promise) as LROperation< + protos.google.cloud.retail.v2alpha.IExportAnalyticsMetricsResponse, + protos.google.cloud.retail.v2alpha.IExportMetadata + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.exportAnalyticsMetrics as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.exportAnalyticsMetrics as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('matchCatalogFromModelName', () => { - const result = client.matchCatalogFromModelName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('invokes exportAnalyticsMetrics with call error', async () => { + const client = new analyticsserviceModule.v2alpha.AnalyticsServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ExportAnalyticsMetricsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ExportAnalyticsMetricsRequest', + ['catalog'], + ); + request.catalog = defaultValue1; + const expectedHeaderRequestParams = `catalog=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.exportAnalyticsMetrics = stubLongRunningCall( + undefined, + expectedError, + ); + await assert.rejects( + client.exportAnalyticsMetrics(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.exportAnalyticsMetrics as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.exportAnalyticsMetrics as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('matchModelFromModelName', () => { - const result = client.matchModelFromModelName(fakePath); - assert.strictEqual(result, "modelValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('invokes exportAnalyticsMetrics with LRO error', async () => { + const client = new analyticsserviceModule.v2alpha.AnalyticsServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ExportAnalyticsMetricsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ExportAnalyticsMetricsRequest', + ['catalog'], + ); + request.catalog = defaultValue1; + const expectedHeaderRequestParams = `catalog=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.exportAnalyticsMetrics = stubLongRunningCall( + undefined, + undefined, + expectedError, + ); + const [operation] = await client.exportAnalyticsMetrics(request); + await assert.rejects(operation.promise(), expectedError); + const actualRequest = ( + client.innerApiCalls.exportAnalyticsMetrics as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.exportAnalyticsMetrics as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - describe('product', () => { - const fakePath = "/rendered/path/product"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - branch: "branchValue", - product: "productValue", - }; - const client = new analyticsserviceModule.v2alpha.AnalyticsServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.productPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.productPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('productPath', () => { - const result = client.productPath("projectValue", "locationValue", "catalogValue", "branchValue", "productValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.productPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + it('invokes checkExportAnalyticsMetricsProgress without error', async () => { + const client = new analyticsserviceModule.v2alpha.AnalyticsServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation(), + ); + expectedResponse.name = 'test'; + expectedResponse.response = { type_url: 'url', value: Buffer.from('') }; + expectedResponse.metadata = { type_url: 'url', value: Buffer.from('') }; + + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const decodedOperation = await client.checkExportAnalyticsMetricsProgress( + expectedResponse.name, + ); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); - it('matchProjectFromProductName', () => { - const result = client.matchProjectFromProductName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('invokes checkExportAnalyticsMetricsProgress with error', async () => { + const client = new analyticsserviceModule.v2alpha.AnalyticsServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const expectedError = new Error('expected'); + + client.operationsClient.getOperation = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.checkExportAnalyticsMetricsProgress(''), + expectedError, + ); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + }); + + describe('Path templates', () => { + describe('alertConfig', () => { + const fakePath = '/rendered/path/alertConfig'; + const expectedParameters = { + project: 'projectValue', + }; + const client = new analyticsserviceModule.v2alpha.AnalyticsServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.alertConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.alertConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('alertConfigPath', () => { + const result = client.alertConfigPath('projectValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.alertConfigPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromAlertConfigName', () => { + const result = client.matchProjectFromAlertConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.alertConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchLocationFromProductName', () => { - const result = client.matchLocationFromProductName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('attributesConfig', () => { + const fakePath = '/rendered/path/attributesConfig'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + }; + const client = new analyticsserviceModule.v2alpha.AnalyticsServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.attributesConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.attributesConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('attributesConfigPath', () => { + const result = client.attributesConfigPath( + 'projectValue', + 'locationValue', + 'catalogValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.attributesConfigPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromAttributesConfigName', () => { + const result = client.matchProjectFromAttributesConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromAttributesConfigName', () => { + const result = client.matchLocationFromAttributesConfigName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromAttributesConfigName', () => { + const result = client.matchCatalogFromAttributesConfigName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchCatalogFromProductName', () => { - const result = client.matchCatalogFromProductName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('branch', () => { + const fakePath = '/rendered/path/branch'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + branch: 'branchValue', + }; + const client = new analyticsserviceModule.v2alpha.AnalyticsServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.branchPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.branchPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('branchPath', () => { + const result = client.branchPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'branchValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.branchPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromBranchName', () => { + const result = client.matchProjectFromBranchName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.branchPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromBranchName', () => { + const result = client.matchLocationFromBranchName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.branchPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromBranchName', () => { + const result = client.matchCatalogFromBranchName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.branchPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBranchFromBranchName', () => { + const result = client.matchBranchFromBranchName(fakePath); + assert.strictEqual(result, 'branchValue'); + assert( + (client.pathTemplates.branchPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchBranchFromProductName', () => { - const result = client.matchBranchFromProductName(fakePath); - assert.strictEqual(result, "branchValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('catalog', () => { + const fakePath = '/rendered/path/catalog'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + }; + const client = new analyticsserviceModule.v2alpha.AnalyticsServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.catalogPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.catalogPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('catalogPath', () => { + const result = client.catalogPath( + 'projectValue', + 'locationValue', + 'catalogValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.catalogPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromCatalogName', () => { + const result = client.matchProjectFromCatalogName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.catalogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromCatalogName', () => { + const result = client.matchLocationFromCatalogName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.catalogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromCatalogName', () => { + const result = client.matchCatalogFromCatalogName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.catalogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchProductFromProductName', () => { - const result = client.matchProductFromProductName(fakePath); - assert.strictEqual(result, "productValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('completionConfig', () => { + const fakePath = '/rendered/path/completionConfig'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + }; + const client = new analyticsserviceModule.v2alpha.AnalyticsServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.completionConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.completionConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('completionConfigPath', () => { + const result = client.completionConfigPath( + 'projectValue', + 'locationValue', + 'catalogValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.completionConfigPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromCompletionConfigName', () => { + const result = client.matchProjectFromCompletionConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.completionConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromCompletionConfigName', () => { + const result = client.matchLocationFromCompletionConfigName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.completionConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromCompletionConfigName', () => { + const result = client.matchCatalogFromCompletionConfigName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.completionConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('retailProject', () => { - const fakePath = "/rendered/path/retailProject"; - const expectedParameters = { - project: "projectValue", - }; - const client = new analyticsserviceModule.v2alpha.AnalyticsServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.retailProjectPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.retailProjectPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('retailProjectPath', () => { - const result = client.retailProjectPath("projectValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.retailProjectPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + describe('control', () => { + const fakePath = '/rendered/path/control'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + control: 'controlValue', + }; + const client = new analyticsserviceModule.v2alpha.AnalyticsServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.controlPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.controlPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('controlPath', () => { + const result = client.controlPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'controlValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.controlPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromControlName', () => { + const result = client.matchProjectFromControlName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.controlPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromControlName', () => { + const result = client.matchLocationFromControlName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.controlPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromControlName', () => { + const result = client.matchCatalogFromControlName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.controlPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchControlFromControlName', () => { + const result = client.matchControlFromControlName(fakePath); + assert.strictEqual(result, 'controlValue'); + assert( + (client.pathTemplates.controlPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchProjectFromRetailProjectName', () => { - const result = client.matchProjectFromRetailProjectName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.retailProjectPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('loggingConfig', () => { + const fakePath = '/rendered/path/loggingConfig'; + const expectedParameters = { + project: 'projectValue', + }; + const client = new analyticsserviceModule.v2alpha.AnalyticsServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.loggingConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.loggingConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('loggingConfigPath', () => { + const result = client.loggingConfigPath('projectValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.loggingConfigPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromLoggingConfigName', () => { + const result = client.matchProjectFromLoggingConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.loggingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('servingConfig', () => { - const fakePath = "/rendered/path/servingConfig"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - serving_config: "servingConfigValue", - }; - const client = new analyticsserviceModule.v2alpha.AnalyticsServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.servingConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.servingConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('servingConfigPath', () => { - const result = client.servingConfigPath("projectValue", "locationValue", "catalogValue", "servingConfigValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.servingConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + describe('merchantCenterAccountLink', () => { + const fakePath = '/rendered/path/merchantCenterAccountLink'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + merchant_center_account_link: 'merchantCenterAccountLinkValue', + }; + const client = new analyticsserviceModule.v2alpha.AnalyticsServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.merchantCenterAccountLinkPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.merchantCenterAccountLinkPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('merchantCenterAccountLinkPath', () => { + const result = client.merchantCenterAccountLinkPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'merchantCenterAccountLinkValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromMerchantCenterAccountLinkName', () => { + const result = + client.matchProjectFromMerchantCenterAccountLinkName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromMerchantCenterAccountLinkName', () => { + const result = + client.matchLocationFromMerchantCenterAccountLinkName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromMerchantCenterAccountLinkName', () => { + const result = + client.matchCatalogFromMerchantCenterAccountLinkName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName', () => { + const result = + client.matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName( + fakePath, + ); + assert.strictEqual(result, 'merchantCenterAccountLinkValue'); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchProjectFromServingConfigName', () => { - const result = client.matchProjectFromServingConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.servingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('model', () => { + const fakePath = '/rendered/path/model'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + model: 'modelValue', + }; + const client = new analyticsserviceModule.v2alpha.AnalyticsServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.modelPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.modelPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('modelPath', () => { + const result = client.modelPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'modelValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.modelPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromModelName', () => { + const result = client.matchProjectFromModelName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromModelName', () => { + const result = client.matchLocationFromModelName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromModelName', () => { + const result = client.matchCatalogFromModelName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchModelFromModelName', () => { + const result = client.matchModelFromModelName(fakePath); + assert.strictEqual(result, 'modelValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchLocationFromServingConfigName', () => { - const result = client.matchLocationFromServingConfigName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.servingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('product', () => { + const fakePath = '/rendered/path/product'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + branch: 'branchValue', + product: 'productValue', + }; + const client = new analyticsserviceModule.v2alpha.AnalyticsServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.productPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.productPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('productPath', () => { + const result = client.productPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'branchValue', + 'productValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.productPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProductName', () => { + const result = client.matchProjectFromProductName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromProductName', () => { + const result = client.matchLocationFromProductName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromProductName', () => { + const result = client.matchCatalogFromProductName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBranchFromProductName', () => { + const result = client.matchBranchFromProductName(fakePath); + assert.strictEqual(result, 'branchValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchProductFromProductName', () => { + const result = client.matchProductFromProductName(fakePath); + assert.strictEqual(result, 'productValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchCatalogFromServingConfigName', () => { - const result = client.matchCatalogFromServingConfigName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.servingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('retailProject', () => { + const fakePath = '/rendered/path/retailProject'; + const expectedParameters = { + project: 'projectValue', + }; + const client = new analyticsserviceModule.v2alpha.AnalyticsServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.retailProjectPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.retailProjectPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('retailProjectPath', () => { + const result = client.retailProjectPath('projectValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.retailProjectPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromRetailProjectName', () => { + const result = client.matchProjectFromRetailProjectName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.retailProjectPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchServingConfigFromServingConfigName', () => { - const result = client.matchServingConfigFromServingConfigName(fakePath); - assert.strictEqual(result, "servingConfigValue"); - assert((client.pathTemplates.servingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('servingConfig', () => { + const fakePath = '/rendered/path/servingConfig'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + serving_config: 'servingConfigValue', + }; + const client = new analyticsserviceModule.v2alpha.AnalyticsServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.servingConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.servingConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('servingConfigPath', () => { + const result = client.servingConfigPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'servingConfigValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.servingConfigPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromServingConfigName', () => { + const result = client.matchProjectFromServingConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.servingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromServingConfigName', () => { + const result = client.matchLocationFromServingConfigName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.servingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromServingConfigName', () => { + const result = client.matchCatalogFromServingConfigName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.servingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServingConfigFromServingConfigName', () => { + const result = client.matchServingConfigFromServingConfigName(fakePath); + assert.strictEqual(result, 'servingConfigValue'); + assert( + (client.pathTemplates.servingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/test/gapic_branch_service_v2alpha.ts.baseline b/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/test/gapic_branch_service_v2alpha.ts.baseline index 1e29cd127728..88f426cfcc93 100644 --- a/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/test/gapic_branch_service_v2alpha.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/test/gapic_branch_service_v2alpha.ts.baseline @@ -20,14 +20,14 @@ import * as protos from '../../protos/protos.js'; import assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as branchserviceModule from '../src/index.js'; -import {protobuf} from 'google-gax'; +import { protobuf } from 'google-gax'; import fs from 'fs'; import path from 'path'; -import {fileURLToPath} from 'url'; +import { fileURLToPath } from 'url'; // @ts-ignore const dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -35,968 +35,1321 @@ const dirname = path.dirname(fileURLToPath(import.meta.url)); // to fill in default values for request objects const root = protobuf.Root.fromJSON( JSON.parse( - fs.readFileSync(path.join(dirname, '..', '..', 'protos/protos.json'), 'utf8') - )) + fs.readFileSync( + path.join(dirname, '..', '..', 'protos/protos.json'), + 'utf8', + ), + ), +); // eslint-disable-next-line @typescript-eslint/no-unused-vars function getTypeDefaultValue(typeName: string, fields: string[]) { - let type = root.lookupType(typeName) as protobuf.Type; - for (const field of fields.slice(0, -1)) { - type = type?.fields[field]?.resolvedType as protobuf.Type; - } - return type?.fields[fields[fields.length - 1]]?.defaultValue ?? null; + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type?.fields[field]?.resolvedType as protobuf.Type; + } + return type?.fields[fields[fields.length - 1]]?.defaultValue ?? null; } function generateSampleMessage(instance: T) { - const filledObject = (instance.constructor as typeof protobuf.Message) - .toObject(instance as protobuf.Message, {defaults: true}); - return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, { defaults: true }); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; } function stubSimpleCall(response?: ResponseType, error?: Error) { - return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); } -function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { - return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +function stubSimpleCallWithCallback( + response?: ResponseType, + error?: Error, +) { + return error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); } describe('v2alpha.BranchServiceClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new branchserviceModule.v2alpha.BranchServiceClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'retail.googleapis.com'); - }); - - it('has universeDomain', () => { - const client = new branchserviceModule.v2alpha.BranchServiceClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new branchserviceModule.v2alpha.BranchServiceClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'retail.googleapis.com'); + }); - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - it('throws DeprecationWarning if static servicePath is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const servicePath = branchserviceModule.v2alpha.BranchServiceClient.servicePath; - assert.strictEqual(servicePath, 'retail.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = branchserviceModule.v2alpha.BranchServiceClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'retail.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new branchserviceModule.v2alpha.BranchServiceClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'retail.example.com'); - }); + it('has universeDomain', () => { + const client = new branchserviceModule.v2alpha.BranchServiceClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new branchserviceModule.v2alpha.BranchServiceClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'retail.example.com'); - }); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = + branchserviceModule.v2alpha.BranchServiceClient.servicePath; + assert.strictEqual(servicePath, 'retail.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + branchserviceModule.v2alpha.BranchServiceClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'retail.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = new branchserviceModule.v2alpha.BranchServiceClient({ + universeDomain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'retail.example.com'); + }); - if (typeof process === 'object' && 'env' in process) { - describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { - it('sets apiEndpoint from environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new branchserviceModule.v2alpha.BranchServiceClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'retail.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - - it('value configured in code has priority over environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new branchserviceModule.v2alpha.BranchServiceClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'retail.configured.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { new branchserviceModule.v2alpha.BranchServiceClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = new branchserviceModule.v2alpha.BranchServiceClient({ + universe_domain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'retail.example.com'); + }); - it('has port', () => { - const port = branchserviceModule.v2alpha.BranchServiceClient.port; - assert(port); - assert(typeof port === 'number'); + if (typeof process === 'object' && 'env' in process) { + describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { + it('sets apiEndpoint from environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new branchserviceModule.v2alpha.BranchServiceClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'retail.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - it('should create a client with no option', () => { - const client = new branchserviceModule.v2alpha.BranchServiceClient(); - assert(client); + it('value configured in code has priority over environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new branchserviceModule.v2alpha.BranchServiceClient({ + universeDomain: 'configured.example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'retail.configured.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - - it('should create a client with gRPC fallback', () => { - const client = new branchserviceModule.v2alpha.BranchServiceClient({ - fallback: true, - }); - assert(client); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new branchserviceModule.v2alpha.BranchServiceClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); + }); - it('has initialize method and supports deferred initialization', async () => { - const client = new branchserviceModule.v2alpha.BranchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.branchServiceStub, undefined); - await client.initialize(); - assert(client.branchServiceStub); - }); + it('has port', () => { + const port = branchserviceModule.v2alpha.BranchServiceClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('has close method for the initialized client', done => { - const client = new branchserviceModule.v2alpha.BranchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.branchServiceStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('should create a client with no option', () => { + const client = new branchserviceModule.v2alpha.BranchServiceClient(); + assert(client); + }); - it('has close method for the non-initialized client', done => { - const client = new branchserviceModule.v2alpha.BranchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.branchServiceStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('should create a client with gRPC fallback', () => { + const client = new branchserviceModule.v2alpha.BranchServiceClient({ + fallback: true, + }); + assert(client); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new branchserviceModule.v2alpha.BranchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); - }); + it('has initialize method and supports deferred initialization', async () => { + const client = new branchserviceModule.v2alpha.BranchServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.branchServiceStub, undefined); + await client.initialize(); + assert(client.branchServiceStub); + }); - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new branchserviceModule.v2alpha.BranchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId((err?: Error|null, projectId?: string|null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } - }); - }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); + it('has close method for the initialized client', (done) => { + const client = new branchserviceModule.v2alpha.BranchServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.branchServiceStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); }); - describe('listBranches', () => { - it('invokes listBranches without error', async () => { - const client = new branchserviceModule.v2alpha.BranchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ListBranchesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ListBranchesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ListBranchesResponse() - ); - client.innerApiCalls.listBranches = stubSimpleCall(expectedResponse); - const [response] = await client.listBranches(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listBranches as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listBranches as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('has close method for the non-initialized client', (done) => { + const client = new branchserviceModule.v2alpha.BranchServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.branchServiceStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes listBranches without error using callback', async () => { - const client = new branchserviceModule.v2alpha.BranchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ListBranchesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ListBranchesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ListBranchesResponse() - ); - client.innerApiCalls.listBranches = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listBranches( - request, - (err?: Error|null, result?: protos.google.cloud.retail.v2alpha.IListBranchesResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listBranches as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listBranches as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new branchserviceModule.v2alpha.BranchServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + }); - it('invokes listBranches with error', async () => { - const client = new branchserviceModule.v2alpha.BranchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ListBranchesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ListBranchesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listBranches = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listBranches(request), expectedError); - const actualRequest = (client.innerApiCalls.listBranches as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listBranches as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new branchserviceModule.v2alpha.BranchServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + }); + + describe('listBranches', () => { + it('invokes listBranches without error', async () => { + const client = new branchserviceModule.v2alpha.BranchServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ListBranchesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ListBranchesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ListBranchesResponse(), + ); + client.innerApiCalls.listBranches = stubSimpleCall(expectedResponse); + const [response] = await client.listBranches(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listBranches as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listBranches as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listBranches with closed client', async () => { - const client = new branchserviceModule.v2alpha.BranchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ListBranchesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ListBranchesRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.listBranches(request), expectedError); - }); + it('invokes listBranches without error using callback', async () => { + const client = new branchserviceModule.v2alpha.BranchServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ListBranchesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ListBranchesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ListBranchesResponse(), + ); + client.innerApiCalls.listBranches = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listBranches( + request, + ( + err?: Error | null, + result?: protos.google.cloud.retail.v2alpha.IListBranchesResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listBranches as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listBranches as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('getBranch', () => { - it('invokes getBranch without error', async () => { - const client = new branchserviceModule.v2alpha.BranchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.GetBranchRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.GetBranchRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.Branch() - ); - client.innerApiCalls.getBranch = stubSimpleCall(expectedResponse); - const [response] = await client.getBranch(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getBranch as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getBranch as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listBranches with error', async () => { + const client = new branchserviceModule.v2alpha.BranchServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ListBranchesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ListBranchesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listBranches = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listBranches(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listBranches as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listBranches as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getBranch without error using callback', async () => { - const client = new branchserviceModule.v2alpha.BranchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.GetBranchRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.GetBranchRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.Branch() - ); - client.innerApiCalls.getBranch = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getBranch( - request, - (err?: Error|null, result?: protos.google.cloud.retail.v2alpha.IBranch|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getBranch as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getBranch as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listBranches with closed client', async () => { + const client = new branchserviceModule.v2alpha.BranchServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ListBranchesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ListBranchesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.listBranches(request), expectedError); + }); + }); + + describe('getBranch', () => { + it('invokes getBranch without error', async () => { + const client = new branchserviceModule.v2alpha.BranchServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.GetBranchRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.GetBranchRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.Branch(), + ); + client.innerApiCalls.getBranch = stubSimpleCall(expectedResponse); + const [response] = await client.getBranch(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getBranch as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getBranch as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getBranch with error', async () => { - const client = new branchserviceModule.v2alpha.BranchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.GetBranchRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.GetBranchRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getBranch = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getBranch(request), expectedError); - const actualRequest = (client.innerApiCalls.getBranch as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getBranch as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getBranch without error using callback', async () => { + const client = new branchserviceModule.v2alpha.BranchServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.GetBranchRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.GetBranchRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.Branch(), + ); + client.innerApiCalls.getBranch = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getBranch( + request, + ( + err?: Error | null, + result?: protos.google.cloud.retail.v2alpha.IBranch | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getBranch as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getBranch as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getBranch with closed client', async () => { - const client = new branchserviceModule.v2alpha.BranchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.GetBranchRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.GetBranchRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getBranch(request), expectedError); - }); + it('invokes getBranch with error', async () => { + const client = new branchserviceModule.v2alpha.BranchServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.GetBranchRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.GetBranchRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getBranch = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.getBranch(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getBranch as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getBranch as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('Path templates', () => { - - describe('alertConfig', () => { - const fakePath = "/rendered/path/alertConfig"; - const expectedParameters = { - project: "projectValue", - }; - const client = new branchserviceModule.v2alpha.BranchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.alertConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.alertConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('alertConfigPath', () => { - const result = client.alertConfigPath("projectValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.alertConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromAlertConfigName', () => { - const result = client.matchProjectFromAlertConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.alertConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('invokes getBranch with closed client', async () => { + const client = new branchserviceModule.v2alpha.BranchServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.GetBranchRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.GetBranchRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getBranch(request), expectedError); + }); + }); + + describe('Path templates', () => { + describe('alertConfig', () => { + const fakePath = '/rendered/path/alertConfig'; + const expectedParameters = { + project: 'projectValue', + }; + const client = new branchserviceModule.v2alpha.BranchServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.alertConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.alertConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('alertConfigPath', () => { + const result = client.alertConfigPath('projectValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.alertConfigPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromAlertConfigName', () => { + const result = client.matchProjectFromAlertConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.alertConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('attributesConfig', () => { - const fakePath = "/rendered/path/attributesConfig"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - }; - const client = new branchserviceModule.v2alpha.BranchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.attributesConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.attributesConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('attributesConfigPath', () => { - const result = client.attributesConfigPath("projectValue", "locationValue", "catalogValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.attributesConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromAttributesConfigName', () => { - const result = client.matchProjectFromAttributesConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromAttributesConfigName', () => { - const result = client.matchLocationFromAttributesConfigName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromAttributesConfigName', () => { - const result = client.matchCatalogFromAttributesConfigName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('attributesConfig', () => { + const fakePath = '/rendered/path/attributesConfig'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + }; + const client = new branchserviceModule.v2alpha.BranchServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.attributesConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.attributesConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('attributesConfigPath', () => { + const result = client.attributesConfigPath( + 'projectValue', + 'locationValue', + 'catalogValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.attributesConfigPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromAttributesConfigName', () => { + const result = client.matchProjectFromAttributesConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromAttributesConfigName', () => { + const result = client.matchLocationFromAttributesConfigName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromAttributesConfigName', () => { + const result = client.matchCatalogFromAttributesConfigName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('branch', () => { - const fakePath = "/rendered/path/branch"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - branch: "branchValue", - }; - const client = new branchserviceModule.v2alpha.BranchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.branchPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.branchPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('branchPath', () => { - const result = client.branchPath("projectValue", "locationValue", "catalogValue", "branchValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.branchPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromBranchName', () => { - const result = client.matchProjectFromBranchName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.branchPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromBranchName', () => { - const result = client.matchLocationFromBranchName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.branchPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromBranchName', () => { - const result = client.matchCatalogFromBranchName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.branchPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBranchFromBranchName', () => { - const result = client.matchBranchFromBranchName(fakePath); - assert.strictEqual(result, "branchValue"); - assert((client.pathTemplates.branchPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('branch', () => { + const fakePath = '/rendered/path/branch'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + branch: 'branchValue', + }; + const client = new branchserviceModule.v2alpha.BranchServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.branchPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.branchPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('branchPath', () => { + const result = client.branchPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'branchValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.branchPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromBranchName', () => { + const result = client.matchProjectFromBranchName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.branchPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromBranchName', () => { + const result = client.matchLocationFromBranchName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.branchPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromBranchName', () => { + const result = client.matchCatalogFromBranchName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.branchPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBranchFromBranchName', () => { + const result = client.matchBranchFromBranchName(fakePath); + assert.strictEqual(result, 'branchValue'); + assert( + (client.pathTemplates.branchPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('catalog', () => { - const fakePath = "/rendered/path/catalog"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - }; - const client = new branchserviceModule.v2alpha.BranchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.catalogPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.catalogPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('catalogPath', () => { - const result = client.catalogPath("projectValue", "locationValue", "catalogValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.catalogPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromCatalogName', () => { - const result = client.matchProjectFromCatalogName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.catalogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromCatalogName', () => { - const result = client.matchLocationFromCatalogName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.catalogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromCatalogName', () => { - const result = client.matchCatalogFromCatalogName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.catalogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('catalog', () => { + const fakePath = '/rendered/path/catalog'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + }; + const client = new branchserviceModule.v2alpha.BranchServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.catalogPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.catalogPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('catalogPath', () => { + const result = client.catalogPath( + 'projectValue', + 'locationValue', + 'catalogValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.catalogPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromCatalogName', () => { + const result = client.matchProjectFromCatalogName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.catalogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromCatalogName', () => { + const result = client.matchLocationFromCatalogName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.catalogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromCatalogName', () => { + const result = client.matchCatalogFromCatalogName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.catalogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('completionConfig', () => { - const fakePath = "/rendered/path/completionConfig"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - }; - const client = new branchserviceModule.v2alpha.BranchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.completionConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.completionConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('completionConfigPath', () => { - const result = client.completionConfigPath("projectValue", "locationValue", "catalogValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.completionConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromCompletionConfigName', () => { - const result = client.matchProjectFromCompletionConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.completionConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromCompletionConfigName', () => { - const result = client.matchLocationFromCompletionConfigName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.completionConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromCompletionConfigName', () => { - const result = client.matchCatalogFromCompletionConfigName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.completionConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('completionConfig', () => { + const fakePath = '/rendered/path/completionConfig'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + }; + const client = new branchserviceModule.v2alpha.BranchServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.completionConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.completionConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('completionConfigPath', () => { + const result = client.completionConfigPath( + 'projectValue', + 'locationValue', + 'catalogValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.completionConfigPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromCompletionConfigName', () => { + const result = client.matchProjectFromCompletionConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.completionConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromCompletionConfigName', () => { + const result = client.matchLocationFromCompletionConfigName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.completionConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromCompletionConfigName', () => { + const result = client.matchCatalogFromCompletionConfigName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.completionConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('control', () => { - const fakePath = "/rendered/path/control"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - control: "controlValue", - }; - const client = new branchserviceModule.v2alpha.BranchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.controlPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.controlPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('controlPath', () => { - const result = client.controlPath("projectValue", "locationValue", "catalogValue", "controlValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.controlPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromControlName', () => { - const result = client.matchProjectFromControlName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.controlPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromControlName', () => { - const result = client.matchLocationFromControlName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.controlPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromControlName', () => { - const result = client.matchCatalogFromControlName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.controlPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchControlFromControlName', () => { - const result = client.matchControlFromControlName(fakePath); - assert.strictEqual(result, "controlValue"); - assert((client.pathTemplates.controlPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('control', () => { + const fakePath = '/rendered/path/control'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + control: 'controlValue', + }; + const client = new branchserviceModule.v2alpha.BranchServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.controlPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.controlPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('controlPath', () => { + const result = client.controlPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'controlValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.controlPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromControlName', () => { + const result = client.matchProjectFromControlName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.controlPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromControlName', () => { + const result = client.matchLocationFromControlName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.controlPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromControlName', () => { + const result = client.matchCatalogFromControlName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.controlPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchControlFromControlName', () => { + const result = client.matchControlFromControlName(fakePath); + assert.strictEqual(result, 'controlValue'); + assert( + (client.pathTemplates.controlPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('loggingConfig', () => { - const fakePath = "/rendered/path/loggingConfig"; - const expectedParameters = { - project: "projectValue", - }; - const client = new branchserviceModule.v2alpha.BranchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.loggingConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.loggingConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('loggingConfigPath', () => { - const result = client.loggingConfigPath("projectValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.loggingConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromLoggingConfigName', () => { - const result = client.matchProjectFromLoggingConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.loggingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('loggingConfig', () => { + const fakePath = '/rendered/path/loggingConfig'; + const expectedParameters = { + project: 'projectValue', + }; + const client = new branchserviceModule.v2alpha.BranchServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.loggingConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.loggingConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('loggingConfigPath', () => { + const result = client.loggingConfigPath('projectValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.loggingConfigPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromLoggingConfigName', () => { + const result = client.matchProjectFromLoggingConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.loggingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('merchantCenterAccountLink', () => { - const fakePath = "/rendered/path/merchantCenterAccountLink"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - merchant_center_account_link: "merchantCenterAccountLinkValue", - }; - const client = new branchserviceModule.v2alpha.BranchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.merchantCenterAccountLinkPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.merchantCenterAccountLinkPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('merchantCenterAccountLinkPath', () => { - const result = client.merchantCenterAccountLinkPath("projectValue", "locationValue", "catalogValue", "merchantCenterAccountLinkValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromMerchantCenterAccountLinkName', () => { - const result = client.matchProjectFromMerchantCenterAccountLinkName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromMerchantCenterAccountLinkName', () => { - const result = client.matchLocationFromMerchantCenterAccountLinkName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromMerchantCenterAccountLinkName', () => { - const result = client.matchCatalogFromMerchantCenterAccountLinkName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName', () => { - const result = client.matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName(fakePath); - assert.strictEqual(result, "merchantCenterAccountLinkValue"); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('merchantCenterAccountLink', () => { + const fakePath = '/rendered/path/merchantCenterAccountLink'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + merchant_center_account_link: 'merchantCenterAccountLinkValue', + }; + const client = new branchserviceModule.v2alpha.BranchServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.merchantCenterAccountLinkPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.merchantCenterAccountLinkPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('merchantCenterAccountLinkPath', () => { + const result = client.merchantCenterAccountLinkPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'merchantCenterAccountLinkValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromMerchantCenterAccountLinkName', () => { + const result = + client.matchProjectFromMerchantCenterAccountLinkName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromMerchantCenterAccountLinkName', () => { + const result = + client.matchLocationFromMerchantCenterAccountLinkName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromMerchantCenterAccountLinkName', () => { + const result = + client.matchCatalogFromMerchantCenterAccountLinkName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName', () => { + const result = + client.matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName( + fakePath, + ); + assert.strictEqual(result, 'merchantCenterAccountLinkValue'); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('model', () => { - const fakePath = "/rendered/path/model"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - model: "modelValue", - }; - const client = new branchserviceModule.v2alpha.BranchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.modelPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.modelPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('modelPath', () => { - const result = client.modelPath("projectValue", "locationValue", "catalogValue", "modelValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.modelPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromModelName', () => { - const result = client.matchProjectFromModelName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromModelName', () => { - const result = client.matchLocationFromModelName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromModelName', () => { - const result = client.matchCatalogFromModelName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchModelFromModelName', () => { - const result = client.matchModelFromModelName(fakePath); - assert.strictEqual(result, "modelValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('model', () => { + const fakePath = '/rendered/path/model'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + model: 'modelValue', + }; + const client = new branchserviceModule.v2alpha.BranchServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.modelPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.modelPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('modelPath', () => { + const result = client.modelPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'modelValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.modelPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromModelName', () => { + const result = client.matchProjectFromModelName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromModelName', () => { + const result = client.matchLocationFromModelName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromModelName', () => { + const result = client.matchCatalogFromModelName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchModelFromModelName', () => { + const result = client.matchModelFromModelName(fakePath); + assert.strictEqual(result, 'modelValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('product', () => { - const fakePath = "/rendered/path/product"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - branch: "branchValue", - product: "productValue", - }; - const client = new branchserviceModule.v2alpha.BranchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.productPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.productPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('productPath', () => { - const result = client.productPath("projectValue", "locationValue", "catalogValue", "branchValue", "productValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.productPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProductName', () => { - const result = client.matchProjectFromProductName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromProductName', () => { - const result = client.matchLocationFromProductName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromProductName', () => { - const result = client.matchCatalogFromProductName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBranchFromProductName', () => { - const result = client.matchBranchFromProductName(fakePath); - assert.strictEqual(result, "branchValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchProductFromProductName', () => { - const result = client.matchProductFromProductName(fakePath); - assert.strictEqual(result, "productValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('product', () => { + const fakePath = '/rendered/path/product'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + branch: 'branchValue', + product: 'productValue', + }; + const client = new branchserviceModule.v2alpha.BranchServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.productPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.productPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('productPath', () => { + const result = client.productPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'branchValue', + 'productValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.productPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProductName', () => { + const result = client.matchProjectFromProductName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromProductName', () => { + const result = client.matchLocationFromProductName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromProductName', () => { + const result = client.matchCatalogFromProductName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBranchFromProductName', () => { + const result = client.matchBranchFromProductName(fakePath); + assert.strictEqual(result, 'branchValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchProductFromProductName', () => { + const result = client.matchProductFromProductName(fakePath); + assert.strictEqual(result, 'productValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('retailProject', () => { - const fakePath = "/rendered/path/retailProject"; - const expectedParameters = { - project: "projectValue", - }; - const client = new branchserviceModule.v2alpha.BranchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.retailProjectPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.retailProjectPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('retailProjectPath', () => { - const result = client.retailProjectPath("projectValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.retailProjectPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromRetailProjectName', () => { - const result = client.matchProjectFromRetailProjectName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.retailProjectPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('retailProject', () => { + const fakePath = '/rendered/path/retailProject'; + const expectedParameters = { + project: 'projectValue', + }; + const client = new branchserviceModule.v2alpha.BranchServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.retailProjectPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.retailProjectPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('retailProjectPath', () => { + const result = client.retailProjectPath('projectValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.retailProjectPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromRetailProjectName', () => { + const result = client.matchProjectFromRetailProjectName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.retailProjectPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('servingConfig', () => { - const fakePath = "/rendered/path/servingConfig"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - serving_config: "servingConfigValue", - }; - const client = new branchserviceModule.v2alpha.BranchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.servingConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.servingConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('servingConfigPath', () => { - const result = client.servingConfigPath("projectValue", "locationValue", "catalogValue", "servingConfigValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.servingConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromServingConfigName', () => { - const result = client.matchProjectFromServingConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.servingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromServingConfigName', () => { - const result = client.matchLocationFromServingConfigName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.servingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromServingConfigName', () => { - const result = client.matchCatalogFromServingConfigName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.servingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServingConfigFromServingConfigName', () => { - const result = client.matchServingConfigFromServingConfigName(fakePath); - assert.strictEqual(result, "servingConfigValue"); - assert((client.pathTemplates.servingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('servingConfig', () => { + const fakePath = '/rendered/path/servingConfig'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + serving_config: 'servingConfigValue', + }; + const client = new branchserviceModule.v2alpha.BranchServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.servingConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.servingConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('servingConfigPath', () => { + const result = client.servingConfigPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'servingConfigValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.servingConfigPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromServingConfigName', () => { + const result = client.matchProjectFromServingConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.servingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromServingConfigName', () => { + const result = client.matchLocationFromServingConfigName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.servingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromServingConfigName', () => { + const result = client.matchCatalogFromServingConfigName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.servingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServingConfigFromServingConfigName', () => { + const result = client.matchServingConfigFromServingConfigName(fakePath); + assert.strictEqual(result, 'servingConfigValue'); + assert( + (client.pathTemplates.servingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/test/gapic_catalog_service_v2alpha.ts.baseline b/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/test/gapic_catalog_service_v2alpha.ts.baseline index 38dc32adbca3..ec665adb5f15 100644 --- a/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/test/gapic_catalog_service_v2alpha.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/test/gapic_catalog_service_v2alpha.ts.baseline @@ -20,16 +20,16 @@ import * as protos from '../../protos/protos.js'; import assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as catalogserviceModule from '../src/index.js'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; -import {protobuf} from 'google-gax'; +import { protobuf } from 'google-gax'; import fs from 'fs'; import path from 'path'; -import {fileURLToPath} from 'url'; +import { fileURLToPath } from 'url'; // @ts-ignore const dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -37,2280 +37,2978 @@ const dirname = path.dirname(fileURLToPath(import.meta.url)); // to fill in default values for request objects const root = protobuf.Root.fromJSON( JSON.parse( - fs.readFileSync(path.join(dirname, '..', '..', 'protos/protos.json'), 'utf8') - )) + fs.readFileSync( + path.join(dirname, '..', '..', 'protos/protos.json'), + 'utf8', + ), + ), +); // eslint-disable-next-line @typescript-eslint/no-unused-vars function getTypeDefaultValue(typeName: string, fields: string[]) { - let type = root.lookupType(typeName) as protobuf.Type; - for (const field of fields.slice(0, -1)) { - type = type?.fields[field]?.resolvedType as protobuf.Type; - } - return type?.fields[fields[fields.length - 1]]?.defaultValue ?? null; + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type?.fields[field]?.resolvedType as protobuf.Type; + } + return type?.fields[fields[fields.length - 1]]?.defaultValue ?? null; } function generateSampleMessage(instance: T) { - const filledObject = (instance.constructor as typeof protobuf.Message) - .toObject(instance as protobuf.Message, {defaults: true}); - return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, { defaults: true }); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; } function stubSimpleCall(response?: ResponseType, error?: Error) { - return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); } -function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { - return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +function stubSimpleCallWithCallback( + response?: ResponseType, + error?: Error, +) { + return error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); } -function stubPageStreamingCall(responses?: ResponseType[], error?: Error) { - const pagingStub = sinon.stub(); - if (responses) { - for (let i = 0; i < responses.length; ++i) { - pagingStub.onCall(i).callsArgWith(2, null, responses[i]); - } +function stubPageStreamingCall( + responses?: ResponseType[], + error?: Error, +) { + const pagingStub = sinon.stub(); + if (responses) { + for (let i = 0; i < responses.length; ++i) { + pagingStub.onCall(i).callsArgWith(2, null, responses[i]); } - const transformStub = error ? sinon.stub().callsArgWith(2, error) : pagingStub; - const mockStream = new PassThrough({ - objectMode: true, - transform: transformStub, - }); - // trigger as many responses as needed - if (responses) { - for (let i = 0; i < responses.length; ++i) { - setImmediate(() => { mockStream.write({}); }); - } - setImmediate(() => { mockStream.end(); }); - } else { - setImmediate(() => { mockStream.write({}); }); - setImmediate(() => { mockStream.end(); }); + } + const transformStub = error + ? sinon.stub().callsArgWith(2, error) + : pagingStub; + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + // trigger as many responses as needed + if (responses) { + for (let i = 0; i < responses.length; ++i) { + setImmediate(() => { + mockStream.write({}); + }); } - return sinon.stub().returns(mockStream); + setImmediate(() => { + mockStream.end(); + }); + } else { + setImmediate(() => { + mockStream.write({}); + }); + setImmediate(() => { + mockStream.end(); + }); + } + return sinon.stub().returns(mockStream); } -function stubAsyncIterationCall(responses?: ResponseType[], error?: Error) { - let counter = 0; - const asyncIterable = { - [Symbol.asyncIterator]() { - return { - async next() { - if (error) { - return Promise.reject(error); - } - if (counter >= responses!.length) { - return Promise.resolve({done: true, value: undefined}); - } - return Promise.resolve({done: false, value: responses![counter++]}); - } - }; - } - }; - return sinon.stub().returns(asyncIterable); +function stubAsyncIterationCall( + responses?: ResponseType[], + error?: Error, +) { + let counter = 0; + const asyncIterable = { + [Symbol.asyncIterator]() { + return { + async next() { + if (error) { + return Promise.reject(error); + } + if (counter >= responses!.length) { + return Promise.resolve({ done: true, value: undefined }); + } + return Promise.resolve({ done: false, value: responses![counter++] }); + }, + }; + }, + }; + return sinon.stub().returns(asyncIterable); } describe('v2alpha.CatalogServiceClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new catalogserviceModule.v2alpha.CatalogServiceClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'retail.googleapis.com'); - }); - - it('has universeDomain', () => { - const client = new catalogserviceModule.v2alpha.CatalogServiceClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); - - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - it('throws DeprecationWarning if static servicePath is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const servicePath = catalogserviceModule.v2alpha.CatalogServiceClient.servicePath; - assert.strictEqual(servicePath, 'retail.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = catalogserviceModule.v2alpha.CatalogServiceClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'retail.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'retail.example.com'); - }); - - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'retail.example.com'); - }); - - if (typeof process === 'object' && 'env' in process) { - describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { - it('sets apiEndpoint from environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new catalogserviceModule.v2alpha.CatalogServiceClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'retail.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - - it('value configured in code has priority over environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'retail.configured.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { new catalogserviceModule.v2alpha.CatalogServiceClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); - - it('has port', () => { - const port = catalogserviceModule.v2alpha.CatalogServiceClient.port; - assert(port); - assert(typeof port === 'number'); - }); - - it('should create a client with no option', () => { - const client = new catalogserviceModule.v2alpha.CatalogServiceClient(); - assert(client); - }); - - it('should create a client with gRPC fallback', () => { - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - fallback: true, - }); - assert(client); - }); - - it('has initialize method and supports deferred initialization', async () => { - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.catalogServiceStub, undefined); - await client.initialize(); - assert(client.catalogServiceStub); - }); - - it('has close method for the initialized client', done => { - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.catalogServiceStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); - - it('has close method for the non-initialized client', done => { - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.catalogServiceStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); - - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); - }); - - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId((err?: Error|null, projectId?: string|null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } - }); - }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new catalogserviceModule.v2alpha.CatalogServiceClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'retail.googleapis.com'); }); - describe('updateCatalog', () => { - it('invokes updateCatalog without error', async () => { - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.UpdateCatalogRequest() - ); - request.catalog ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.UpdateCatalogRequest', ['catalog', 'name']); - request.catalog.name = defaultValue1; - const expectedHeaderRequestParams = `catalog.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.Catalog() - ); - client.innerApiCalls.updateCatalog = stubSimpleCall(expectedResponse); - const [response] = await client.updateCatalog(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateCatalog as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateCatalog as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateCatalog without error using callback', async () => { - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.UpdateCatalogRequest() - ); - request.catalog ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.UpdateCatalogRequest', ['catalog', 'name']); - request.catalog.name = defaultValue1; - const expectedHeaderRequestParams = `catalog.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.Catalog() - ); - client.innerApiCalls.updateCatalog = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateCatalog( - request, - (err?: Error|null, result?: protos.google.cloud.retail.v2alpha.ICatalog|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateCatalog as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateCatalog as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has universeDomain', () => { + const client = new catalogserviceModule.v2alpha.CatalogServiceClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - it('invokes updateCatalog with error', async () => { - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.UpdateCatalogRequest() - ); - request.catalog ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.UpdateCatalogRequest', ['catalog', 'name']); - request.catalog.name = defaultValue1; - const expectedHeaderRequestParams = `catalog.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateCatalog = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateCatalog(request), expectedError); - const actualRequest = (client.innerApiCalls.updateCatalog as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateCatalog as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = + catalogserviceModule.v2alpha.CatalogServiceClient.servicePath; + assert.strictEqual(servicePath, 'retail.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + catalogserviceModule.v2alpha.CatalogServiceClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'retail.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + universeDomain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'retail.example.com'); + }); - it('invokes updateCatalog with closed client', async () => { - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.UpdateCatalogRequest() - ); - request.catalog ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.UpdateCatalogRequest', ['catalog', 'name']); - request.catalog.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateCatalog(request), expectedError); - }); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + universe_domain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'retail.example.com'); }); - describe('setDefaultBranch', () => { - it('invokes setDefaultBranch without error', async () => { - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.SetDefaultBranchRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.SetDefaultBranchRequest', ['catalog']); - request.catalog = defaultValue1; - const expectedHeaderRequestParams = `catalog=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.setDefaultBranch = stubSimpleCall(expectedResponse); - const [response] = await client.setDefaultBranch(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.setDefaultBranch as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.setDefaultBranch as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + if (typeof process === 'object' && 'env' in process) { + describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { + it('sets apiEndpoint from environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = + new catalogserviceModule.v2alpha.CatalogServiceClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'retail.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } + }); + + it('value configured in code has priority over environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + universeDomain: 'configured.example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'retail.configured.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } + }); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new catalogserviceModule.v2alpha.CatalogServiceClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); + }); - it('invokes setDefaultBranch without error using callback', async () => { - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.SetDefaultBranchRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.SetDefaultBranchRequest', ['catalog']); - request.catalog = defaultValue1; - const expectedHeaderRequestParams = `catalog=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.setDefaultBranch = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.setDefaultBranch( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.setDefaultBranch as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.setDefaultBranch as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has port', () => { + const port = catalogserviceModule.v2alpha.CatalogServiceClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('invokes setDefaultBranch with error', async () => { - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.SetDefaultBranchRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.SetDefaultBranchRequest', ['catalog']); - request.catalog = defaultValue1; - const expectedHeaderRequestParams = `catalog=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.setDefaultBranch = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.setDefaultBranch(request), expectedError); - const actualRequest = (client.innerApiCalls.setDefaultBranch as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.setDefaultBranch as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('should create a client with no option', () => { + const client = new catalogserviceModule.v2alpha.CatalogServiceClient(); + assert(client); + }); - it('invokes setDefaultBranch with closed client', async () => { - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.SetDefaultBranchRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.SetDefaultBranchRequest', ['catalog']); - request.catalog = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.setDefaultBranch(request), expectedError); - }); + it('should create a client with gRPC fallback', () => { + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + fallback: true, + }); + assert(client); }); - describe('getDefaultBranch', () => { - it('invokes getDefaultBranch without error', async () => { - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.GetDefaultBranchRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.GetDefaultBranchRequest', ['catalog']); - request.catalog = defaultValue1; - const expectedHeaderRequestParams = `catalog=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.GetDefaultBranchResponse() - ); - client.innerApiCalls.getDefaultBranch = stubSimpleCall(expectedResponse); - const [response] = await client.getDefaultBranch(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getDefaultBranch as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getDefaultBranch as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has initialize method and supports deferred initialization', async () => { + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.catalogServiceStub, undefined); + await client.initialize(); + assert(client.catalogServiceStub); + }); - it('invokes getDefaultBranch without error using callback', async () => { - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.GetDefaultBranchRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.GetDefaultBranchRequest', ['catalog']); - request.catalog = defaultValue1; - const expectedHeaderRequestParams = `catalog=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.GetDefaultBranchResponse() - ); - client.innerApiCalls.getDefaultBranch = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getDefaultBranch( - request, - (err?: Error|null, result?: protos.google.cloud.retail.v2alpha.IGetDefaultBranchResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getDefaultBranch as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getDefaultBranch as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('has close method for the initialized client', (done) => { + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.catalogServiceStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes getDefaultBranch with error', async () => { - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.GetDefaultBranchRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.GetDefaultBranchRequest', ['catalog']); - request.catalog = defaultValue1; - const expectedHeaderRequestParams = `catalog=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getDefaultBranch = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getDefaultBranch(request), expectedError); - const actualRequest = (client.innerApiCalls.getDefaultBranch as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getDefaultBranch as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('has close method for the non-initialized client', (done) => { + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.catalogServiceStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes getDefaultBranch with closed client', async () => { - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.GetDefaultBranchRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.GetDefaultBranchRequest', ['catalog']); - request.catalog = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getDefaultBranch(request), expectedError); - }); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); }); - describe('getCompletionConfig', () => { - it('invokes getCompletionConfig without error', async () => { - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.GetCompletionConfigRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.GetCompletionConfigRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.CompletionConfig() - ); - client.innerApiCalls.getCompletionConfig = stubSimpleCall(expectedResponse); - const [response] = await client.getCompletionConfig(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getCompletionConfig as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getCompletionConfig as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } + }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + }); + + describe('updateCatalog', () => { + it('invokes updateCatalog without error', async () => { + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.UpdateCatalogRequest(), + ); + request.catalog ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.UpdateCatalogRequest', + ['catalog', 'name'], + ); + request.catalog.name = defaultValue1; + const expectedHeaderRequestParams = `catalog.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.Catalog(), + ); + client.innerApiCalls.updateCatalog = stubSimpleCall(expectedResponse); + const [response] = await client.updateCatalog(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateCatalog as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateCatalog as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getCompletionConfig without error using callback', async () => { - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.GetCompletionConfigRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.GetCompletionConfigRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.CompletionConfig() - ); - client.innerApiCalls.getCompletionConfig = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getCompletionConfig( - request, - (err?: Error|null, result?: protos.google.cloud.retail.v2alpha.ICompletionConfig|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getCompletionConfig as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getCompletionConfig as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateCatalog without error using callback', async () => { + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.UpdateCatalogRequest(), + ); + request.catalog ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.UpdateCatalogRequest', + ['catalog', 'name'], + ); + request.catalog.name = defaultValue1; + const expectedHeaderRequestParams = `catalog.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.Catalog(), + ); + client.innerApiCalls.updateCatalog = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateCatalog( + request, + ( + err?: Error | null, + result?: protos.google.cloud.retail.v2alpha.ICatalog | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateCatalog as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateCatalog as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getCompletionConfig with error', async () => { - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.GetCompletionConfigRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.GetCompletionConfigRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getCompletionConfig = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getCompletionConfig(request), expectedError); - const actualRequest = (client.innerApiCalls.getCompletionConfig as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getCompletionConfig as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateCatalog with error', async () => { + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.UpdateCatalogRequest(), + ); + request.catalog ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.UpdateCatalogRequest', + ['catalog', 'name'], + ); + request.catalog.name = defaultValue1; + const expectedHeaderRequestParams = `catalog.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateCatalog = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.updateCatalog(request), expectedError); + const actualRequest = ( + client.innerApiCalls.updateCatalog as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateCatalog as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getCompletionConfig with closed client', async () => { - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.GetCompletionConfigRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.GetCompletionConfigRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getCompletionConfig(request), expectedError); - }); + it('invokes updateCatalog with closed client', async () => { + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.UpdateCatalogRequest(), + ); + request.catalog ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.UpdateCatalogRequest', + ['catalog', 'name'], + ); + request.catalog.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.updateCatalog(request), expectedError); + }); + }); + + describe('setDefaultBranch', () => { + it('invokes setDefaultBranch without error', async () => { + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.SetDefaultBranchRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.SetDefaultBranchRequest', + ['catalog'], + ); + request.catalog = defaultValue1; + const expectedHeaderRequestParams = `catalog=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.setDefaultBranch = stubSimpleCall(expectedResponse); + const [response] = await client.setDefaultBranch(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.setDefaultBranch as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.setDefaultBranch as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('updateCompletionConfig', () => { - it('invokes updateCompletionConfig without error', async () => { - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.UpdateCompletionConfigRequest() - ); - request.completionConfig ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.UpdateCompletionConfigRequest', ['completionConfig', 'name']); - request.completionConfig.name = defaultValue1; - const expectedHeaderRequestParams = `completion_config.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.CompletionConfig() - ); - client.innerApiCalls.updateCompletionConfig = stubSimpleCall(expectedResponse); - const [response] = await client.updateCompletionConfig(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateCompletionConfig as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateCompletionConfig as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes setDefaultBranch without error using callback', async () => { + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.SetDefaultBranchRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.SetDefaultBranchRequest', + ['catalog'], + ); + request.catalog = defaultValue1; + const expectedHeaderRequestParams = `catalog=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.setDefaultBranch = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.setDefaultBranch( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.setDefaultBranch as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.setDefaultBranch as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateCompletionConfig without error using callback', async () => { - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.UpdateCompletionConfigRequest() - ); - request.completionConfig ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.UpdateCompletionConfigRequest', ['completionConfig', 'name']); - request.completionConfig.name = defaultValue1; - const expectedHeaderRequestParams = `completion_config.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.CompletionConfig() - ); - client.innerApiCalls.updateCompletionConfig = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateCompletionConfig( - request, - (err?: Error|null, result?: protos.google.cloud.retail.v2alpha.ICompletionConfig|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateCompletionConfig as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateCompletionConfig as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes setDefaultBranch with error', async () => { + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.SetDefaultBranchRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.SetDefaultBranchRequest', + ['catalog'], + ); + request.catalog = defaultValue1; + const expectedHeaderRequestParams = `catalog=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.setDefaultBranch = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.setDefaultBranch(request), expectedError); + const actualRequest = ( + client.innerApiCalls.setDefaultBranch as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.setDefaultBranch as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateCompletionConfig with error', async () => { - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.UpdateCompletionConfigRequest() - ); - request.completionConfig ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.UpdateCompletionConfigRequest', ['completionConfig', 'name']); - request.completionConfig.name = defaultValue1; - const expectedHeaderRequestParams = `completion_config.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateCompletionConfig = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateCompletionConfig(request), expectedError); - const actualRequest = (client.innerApiCalls.updateCompletionConfig as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateCompletionConfig as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes setDefaultBranch with closed client', async () => { + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.SetDefaultBranchRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.SetDefaultBranchRequest', + ['catalog'], + ); + request.catalog = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.setDefaultBranch(request), expectedError); + }); + }); + + describe('getDefaultBranch', () => { + it('invokes getDefaultBranch without error', async () => { + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.GetDefaultBranchRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.GetDefaultBranchRequest', + ['catalog'], + ); + request.catalog = defaultValue1; + const expectedHeaderRequestParams = `catalog=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.GetDefaultBranchResponse(), + ); + client.innerApiCalls.getDefaultBranch = stubSimpleCall(expectedResponse); + const [response] = await client.getDefaultBranch(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getDefaultBranch as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getDefaultBranch as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateCompletionConfig with closed client', async () => { - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.UpdateCompletionConfigRequest() - ); - request.completionConfig ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.UpdateCompletionConfigRequest', ['completionConfig', 'name']); - request.completionConfig.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateCompletionConfig(request), expectedError); - }); + it('invokes getDefaultBranch without error using callback', async () => { + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.GetDefaultBranchRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.GetDefaultBranchRequest', + ['catalog'], + ); + request.catalog = defaultValue1; + const expectedHeaderRequestParams = `catalog=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.GetDefaultBranchResponse(), + ); + client.innerApiCalls.getDefaultBranch = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getDefaultBranch( + request, + ( + err?: Error | null, + result?: protos.google.cloud.retail.v2alpha.IGetDefaultBranchResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getDefaultBranch as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getDefaultBranch as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('getAttributesConfig', () => { - it('invokes getAttributesConfig without error', async () => { - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.GetAttributesConfigRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.GetAttributesConfigRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.AttributesConfig() - ); - client.innerApiCalls.getAttributesConfig = stubSimpleCall(expectedResponse); - const [response] = await client.getAttributesConfig(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getAttributesConfig as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getAttributesConfig as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getDefaultBranch with error', async () => { + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.GetDefaultBranchRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.GetDefaultBranchRequest', + ['catalog'], + ); + request.catalog = defaultValue1; + const expectedHeaderRequestParams = `catalog=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getDefaultBranch = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getDefaultBranch(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getDefaultBranch as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getDefaultBranch as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getAttributesConfig without error using callback', async () => { - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.GetAttributesConfigRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.GetAttributesConfigRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.AttributesConfig() - ); - client.innerApiCalls.getAttributesConfig = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getAttributesConfig( - request, - (err?: Error|null, result?: protos.google.cloud.retail.v2alpha.IAttributesConfig|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getAttributesConfig as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getAttributesConfig as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getDefaultBranch with closed client', async () => { + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.GetDefaultBranchRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.GetDefaultBranchRequest', + ['catalog'], + ); + request.catalog = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getDefaultBranch(request), expectedError); + }); + }); + + describe('getCompletionConfig', () => { + it('invokes getCompletionConfig without error', async () => { + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.GetCompletionConfigRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.GetCompletionConfigRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.CompletionConfig(), + ); + client.innerApiCalls.getCompletionConfig = + stubSimpleCall(expectedResponse); + const [response] = await client.getCompletionConfig(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getCompletionConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getCompletionConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getAttributesConfig with error', async () => { - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.GetAttributesConfigRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.GetAttributesConfigRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getAttributesConfig = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getAttributesConfig(request), expectedError); - const actualRequest = (client.innerApiCalls.getAttributesConfig as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getAttributesConfig as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getCompletionConfig without error using callback', async () => { + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.GetCompletionConfigRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.GetCompletionConfigRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.CompletionConfig(), + ); + client.innerApiCalls.getCompletionConfig = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getCompletionConfig( + request, + ( + err?: Error | null, + result?: protos.google.cloud.retail.v2alpha.ICompletionConfig | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getCompletionConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getCompletionConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getAttributesConfig with closed client', async () => { - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.GetAttributesConfigRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.GetAttributesConfigRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getAttributesConfig(request), expectedError); - }); + it('invokes getCompletionConfig with error', async () => { + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.GetCompletionConfigRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.GetCompletionConfigRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getCompletionConfig = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getCompletionConfig(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getCompletionConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getCompletionConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('updateAttributesConfig', () => { - it('invokes updateAttributesConfig without error', async () => { - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.UpdateAttributesConfigRequest() - ); - request.attributesConfig ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.UpdateAttributesConfigRequest', ['attributesConfig', 'name']); - request.attributesConfig.name = defaultValue1; - const expectedHeaderRequestParams = `attributes_config.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.AttributesConfig() - ); - client.innerApiCalls.updateAttributesConfig = stubSimpleCall(expectedResponse); - const [response] = await client.updateAttributesConfig(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateAttributesConfig as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateAttributesConfig as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getCompletionConfig with closed client', async () => { + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.GetCompletionConfigRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.GetCompletionConfigRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getCompletionConfig(request), expectedError); + }); + }); + + describe('updateCompletionConfig', () => { + it('invokes updateCompletionConfig without error', async () => { + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.UpdateCompletionConfigRequest(), + ); + request.completionConfig ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.UpdateCompletionConfigRequest', + ['completionConfig', 'name'], + ); + request.completionConfig.name = defaultValue1; + const expectedHeaderRequestParams = `completion_config.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.CompletionConfig(), + ); + client.innerApiCalls.updateCompletionConfig = + stubSimpleCall(expectedResponse); + const [response] = await client.updateCompletionConfig(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateCompletionConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateCompletionConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateAttributesConfig without error using callback', async () => { - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.UpdateAttributesConfigRequest() - ); - request.attributesConfig ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.UpdateAttributesConfigRequest', ['attributesConfig', 'name']); - request.attributesConfig.name = defaultValue1; - const expectedHeaderRequestParams = `attributes_config.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.AttributesConfig() - ); - client.innerApiCalls.updateAttributesConfig = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateAttributesConfig( - request, - (err?: Error|null, result?: protos.google.cloud.retail.v2alpha.IAttributesConfig|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateAttributesConfig as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateAttributesConfig as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateCompletionConfig without error using callback', async () => { + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.UpdateCompletionConfigRequest(), + ); + request.completionConfig ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.UpdateCompletionConfigRequest', + ['completionConfig', 'name'], + ); + request.completionConfig.name = defaultValue1; + const expectedHeaderRequestParams = `completion_config.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.CompletionConfig(), + ); + client.innerApiCalls.updateCompletionConfig = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateCompletionConfig( + request, + ( + err?: Error | null, + result?: protos.google.cloud.retail.v2alpha.ICompletionConfig | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateCompletionConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateCompletionConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateAttributesConfig with error', async () => { - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.UpdateAttributesConfigRequest() - ); - request.attributesConfig ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.UpdateAttributesConfigRequest', ['attributesConfig', 'name']); - request.attributesConfig.name = defaultValue1; - const expectedHeaderRequestParams = `attributes_config.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateAttributesConfig = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateAttributesConfig(request), expectedError); - const actualRequest = (client.innerApiCalls.updateAttributesConfig as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateAttributesConfig as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateCompletionConfig with error', async () => { + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.UpdateCompletionConfigRequest(), + ); + request.completionConfig ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.UpdateCompletionConfigRequest', + ['completionConfig', 'name'], + ); + request.completionConfig.name = defaultValue1; + const expectedHeaderRequestParams = `completion_config.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateCompletionConfig = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.updateCompletionConfig(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.updateCompletionConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateCompletionConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateAttributesConfig with closed client', async () => { - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.UpdateAttributesConfigRequest() - ); - request.attributesConfig ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.UpdateAttributesConfigRequest', ['attributesConfig', 'name']); - request.attributesConfig.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateAttributesConfig(request), expectedError); - }); + it('invokes updateCompletionConfig with closed client', async () => { + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.UpdateCompletionConfigRequest(), + ); + request.completionConfig ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.UpdateCompletionConfigRequest', + ['completionConfig', 'name'], + ); + request.completionConfig.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.updateCompletionConfig(request), + expectedError, + ); + }); + }); + + describe('getAttributesConfig', () => { + it('invokes getAttributesConfig without error', async () => { + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.GetAttributesConfigRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.GetAttributesConfigRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.AttributesConfig(), + ); + client.innerApiCalls.getAttributesConfig = + stubSimpleCall(expectedResponse); + const [response] = await client.getAttributesConfig(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getAttributesConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getAttributesConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('addCatalogAttribute', () => { - it('invokes addCatalogAttribute without error', async () => { - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.AddCatalogAttributeRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.AddCatalogAttributeRequest', ['attributesConfig']); - request.attributesConfig = defaultValue1; - const expectedHeaderRequestParams = `attributes_config=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.AttributesConfig() - ); - client.innerApiCalls.addCatalogAttribute = stubSimpleCall(expectedResponse); - const [response] = await client.addCatalogAttribute(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.addCatalogAttribute as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.addCatalogAttribute as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getAttributesConfig without error using callback', async () => { + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.GetAttributesConfigRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.GetAttributesConfigRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.AttributesConfig(), + ); + client.innerApiCalls.getAttributesConfig = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getAttributesConfig( + request, + ( + err?: Error | null, + result?: protos.google.cloud.retail.v2alpha.IAttributesConfig | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getAttributesConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getAttributesConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes addCatalogAttribute without error using callback', async () => { - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.AddCatalogAttributeRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.AddCatalogAttributeRequest', ['attributesConfig']); - request.attributesConfig = defaultValue1; - const expectedHeaderRequestParams = `attributes_config=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.AttributesConfig() - ); - client.innerApiCalls.addCatalogAttribute = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.addCatalogAttribute( - request, - (err?: Error|null, result?: protos.google.cloud.retail.v2alpha.IAttributesConfig|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.addCatalogAttribute as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.addCatalogAttribute as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getAttributesConfig with error', async () => { + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.GetAttributesConfigRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.GetAttributesConfigRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getAttributesConfig = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getAttributesConfig(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getAttributesConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getAttributesConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes addCatalogAttribute with error', async () => { - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.AddCatalogAttributeRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.AddCatalogAttributeRequest', ['attributesConfig']); - request.attributesConfig = defaultValue1; - const expectedHeaderRequestParams = `attributes_config=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.addCatalogAttribute = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.addCatalogAttribute(request), expectedError); - const actualRequest = (client.innerApiCalls.addCatalogAttribute as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.addCatalogAttribute as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getAttributesConfig with closed client', async () => { + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.GetAttributesConfigRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.GetAttributesConfigRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getAttributesConfig(request), expectedError); + }); + }); + + describe('updateAttributesConfig', () => { + it('invokes updateAttributesConfig without error', async () => { + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.UpdateAttributesConfigRequest(), + ); + request.attributesConfig ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.UpdateAttributesConfigRequest', + ['attributesConfig', 'name'], + ); + request.attributesConfig.name = defaultValue1; + const expectedHeaderRequestParams = `attributes_config.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.AttributesConfig(), + ); + client.innerApiCalls.updateAttributesConfig = + stubSimpleCall(expectedResponse); + const [response] = await client.updateAttributesConfig(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateAttributesConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateAttributesConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes addCatalogAttribute with closed client', async () => { - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.AddCatalogAttributeRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.AddCatalogAttributeRequest', ['attributesConfig']); - request.attributesConfig = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.addCatalogAttribute(request), expectedError); - }); + it('invokes updateAttributesConfig without error using callback', async () => { + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.UpdateAttributesConfigRequest(), + ); + request.attributesConfig ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.UpdateAttributesConfigRequest', + ['attributesConfig', 'name'], + ); + request.attributesConfig.name = defaultValue1; + const expectedHeaderRequestParams = `attributes_config.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.AttributesConfig(), + ); + client.innerApiCalls.updateAttributesConfig = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateAttributesConfig( + request, + ( + err?: Error | null, + result?: protos.google.cloud.retail.v2alpha.IAttributesConfig | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateAttributesConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateAttributesConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('removeCatalogAttribute', () => { - it('invokes removeCatalogAttribute without error', async () => { - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.RemoveCatalogAttributeRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.RemoveCatalogAttributeRequest', ['attributesConfig']); - request.attributesConfig = defaultValue1; - const expectedHeaderRequestParams = `attributes_config=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.AttributesConfig() - ); - client.innerApiCalls.removeCatalogAttribute = stubSimpleCall(expectedResponse); - const [response] = await client.removeCatalogAttribute(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.removeCatalogAttribute as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.removeCatalogAttribute as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateAttributesConfig with error', async () => { + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.UpdateAttributesConfigRequest(), + ); + request.attributesConfig ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.UpdateAttributesConfigRequest', + ['attributesConfig', 'name'], + ); + request.attributesConfig.name = defaultValue1; + const expectedHeaderRequestParams = `attributes_config.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateAttributesConfig = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.updateAttributesConfig(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.updateAttributesConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateAttributesConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes removeCatalogAttribute without error using callback', async () => { - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.RemoveCatalogAttributeRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.RemoveCatalogAttributeRequest', ['attributesConfig']); - request.attributesConfig = defaultValue1; - const expectedHeaderRequestParams = `attributes_config=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.AttributesConfig() - ); - client.innerApiCalls.removeCatalogAttribute = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.removeCatalogAttribute( - request, - (err?: Error|null, result?: protos.google.cloud.retail.v2alpha.IAttributesConfig|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.removeCatalogAttribute as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.removeCatalogAttribute as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateAttributesConfig with closed client', async () => { + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.UpdateAttributesConfigRequest(), + ); + request.attributesConfig ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.UpdateAttributesConfigRequest', + ['attributesConfig', 'name'], + ); + request.attributesConfig.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.updateAttributesConfig(request), + expectedError, + ); + }); + }); + + describe('addCatalogAttribute', () => { + it('invokes addCatalogAttribute without error', async () => { + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.AddCatalogAttributeRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.AddCatalogAttributeRequest', + ['attributesConfig'], + ); + request.attributesConfig = defaultValue1; + const expectedHeaderRequestParams = `attributes_config=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.AttributesConfig(), + ); + client.innerApiCalls.addCatalogAttribute = + stubSimpleCall(expectedResponse); + const [response] = await client.addCatalogAttribute(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.addCatalogAttribute as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.addCatalogAttribute as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes removeCatalogAttribute with error', async () => { - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.RemoveCatalogAttributeRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.RemoveCatalogAttributeRequest', ['attributesConfig']); - request.attributesConfig = defaultValue1; - const expectedHeaderRequestParams = `attributes_config=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.removeCatalogAttribute = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.removeCatalogAttribute(request), expectedError); - const actualRequest = (client.innerApiCalls.removeCatalogAttribute as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.removeCatalogAttribute as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes addCatalogAttribute without error using callback', async () => { + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.AddCatalogAttributeRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.AddCatalogAttributeRequest', + ['attributesConfig'], + ); + request.attributesConfig = defaultValue1; + const expectedHeaderRequestParams = `attributes_config=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.AttributesConfig(), + ); + client.innerApiCalls.addCatalogAttribute = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.addCatalogAttribute( + request, + ( + err?: Error | null, + result?: protos.google.cloud.retail.v2alpha.IAttributesConfig | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.addCatalogAttribute as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.addCatalogAttribute as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes removeCatalogAttribute with closed client', async () => { - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.RemoveCatalogAttributeRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.RemoveCatalogAttributeRequest', ['attributesConfig']); - request.attributesConfig = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.removeCatalogAttribute(request), expectedError); - }); + it('invokes addCatalogAttribute with error', async () => { + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.AddCatalogAttributeRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.AddCatalogAttributeRequest', + ['attributesConfig'], + ); + request.attributesConfig = defaultValue1; + const expectedHeaderRequestParams = `attributes_config=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.addCatalogAttribute = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.addCatalogAttribute(request), expectedError); + const actualRequest = ( + client.innerApiCalls.addCatalogAttribute as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.addCatalogAttribute as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('batchRemoveCatalogAttributes', () => { - it('invokes batchRemoveCatalogAttributes without error', async () => { - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.BatchRemoveCatalogAttributesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.BatchRemoveCatalogAttributesRequest', ['attributesConfig']); - request.attributesConfig = defaultValue1; - const expectedHeaderRequestParams = `attributes_config=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.BatchRemoveCatalogAttributesResponse() - ); - client.innerApiCalls.batchRemoveCatalogAttributes = stubSimpleCall(expectedResponse); - const [response] = await client.batchRemoveCatalogAttributes(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.batchRemoveCatalogAttributes as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.batchRemoveCatalogAttributes as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes addCatalogAttribute with closed client', async () => { + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.AddCatalogAttributeRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.AddCatalogAttributeRequest', + ['attributesConfig'], + ); + request.attributesConfig = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.addCatalogAttribute(request), expectedError); + }); + }); + + describe('removeCatalogAttribute', () => { + it('invokes removeCatalogAttribute without error', async () => { + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.RemoveCatalogAttributeRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.RemoveCatalogAttributeRequest', + ['attributesConfig'], + ); + request.attributesConfig = defaultValue1; + const expectedHeaderRequestParams = `attributes_config=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.AttributesConfig(), + ); + client.innerApiCalls.removeCatalogAttribute = + stubSimpleCall(expectedResponse); + const [response] = await client.removeCatalogAttribute(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.removeCatalogAttribute as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.removeCatalogAttribute as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes batchRemoveCatalogAttributes without error using callback', async () => { - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.BatchRemoveCatalogAttributesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.BatchRemoveCatalogAttributesRequest', ['attributesConfig']); - request.attributesConfig = defaultValue1; - const expectedHeaderRequestParams = `attributes_config=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.BatchRemoveCatalogAttributesResponse() - ); - client.innerApiCalls.batchRemoveCatalogAttributes = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.batchRemoveCatalogAttributes( - request, - (err?: Error|null, result?: protos.google.cloud.retail.v2alpha.IBatchRemoveCatalogAttributesResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.batchRemoveCatalogAttributes as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.batchRemoveCatalogAttributes as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes removeCatalogAttribute without error using callback', async () => { + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.RemoveCatalogAttributeRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.RemoveCatalogAttributeRequest', + ['attributesConfig'], + ); + request.attributesConfig = defaultValue1; + const expectedHeaderRequestParams = `attributes_config=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.AttributesConfig(), + ); + client.innerApiCalls.removeCatalogAttribute = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.removeCatalogAttribute( + request, + ( + err?: Error | null, + result?: protos.google.cloud.retail.v2alpha.IAttributesConfig | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.removeCatalogAttribute as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.removeCatalogAttribute as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes batchRemoveCatalogAttributes with error', async () => { - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.BatchRemoveCatalogAttributesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.BatchRemoveCatalogAttributesRequest', ['attributesConfig']); - request.attributesConfig = defaultValue1; - const expectedHeaderRequestParams = `attributes_config=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.batchRemoveCatalogAttributes = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.batchRemoveCatalogAttributes(request), expectedError); - const actualRequest = (client.innerApiCalls.batchRemoveCatalogAttributes as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.batchRemoveCatalogAttributes as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes removeCatalogAttribute with error', async () => { + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.RemoveCatalogAttributeRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.RemoveCatalogAttributeRequest', + ['attributesConfig'], + ); + request.attributesConfig = defaultValue1; + const expectedHeaderRequestParams = `attributes_config=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.removeCatalogAttribute = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.removeCatalogAttribute(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.removeCatalogAttribute as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.removeCatalogAttribute as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes batchRemoveCatalogAttributes with closed client', async () => { - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.BatchRemoveCatalogAttributesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.BatchRemoveCatalogAttributesRequest', ['attributesConfig']); - request.attributesConfig = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.batchRemoveCatalogAttributes(request), expectedError); - }); + it('invokes removeCatalogAttribute with closed client', async () => { + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.RemoveCatalogAttributeRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.RemoveCatalogAttributeRequest', + ['attributesConfig'], + ); + request.attributesConfig = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.removeCatalogAttribute(request), + expectedError, + ); + }); + }); + + describe('batchRemoveCatalogAttributes', () => { + it('invokes batchRemoveCatalogAttributes without error', async () => { + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.BatchRemoveCatalogAttributesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.BatchRemoveCatalogAttributesRequest', + ['attributesConfig'], + ); + request.attributesConfig = defaultValue1; + const expectedHeaderRequestParams = `attributes_config=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.BatchRemoveCatalogAttributesResponse(), + ); + client.innerApiCalls.batchRemoveCatalogAttributes = + stubSimpleCall(expectedResponse); + const [response] = await client.batchRemoveCatalogAttributes(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.batchRemoveCatalogAttributes as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.batchRemoveCatalogAttributes as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('replaceCatalogAttribute', () => { - it('invokes replaceCatalogAttribute without error', async () => { - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ReplaceCatalogAttributeRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ReplaceCatalogAttributeRequest', ['attributesConfig']); - request.attributesConfig = defaultValue1; - const expectedHeaderRequestParams = `attributes_config=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.AttributesConfig() - ); - client.innerApiCalls.replaceCatalogAttribute = stubSimpleCall(expectedResponse); - const [response] = await client.replaceCatalogAttribute(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.replaceCatalogAttribute as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.replaceCatalogAttribute as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes batchRemoveCatalogAttributes without error using callback', async () => { + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.BatchRemoveCatalogAttributesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.BatchRemoveCatalogAttributesRequest', + ['attributesConfig'], + ); + request.attributesConfig = defaultValue1; + const expectedHeaderRequestParams = `attributes_config=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.BatchRemoveCatalogAttributesResponse(), + ); + client.innerApiCalls.batchRemoveCatalogAttributes = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.batchRemoveCatalogAttributes( + request, + ( + err?: Error | null, + result?: protos.google.cloud.retail.v2alpha.IBatchRemoveCatalogAttributesResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.batchRemoveCatalogAttributes as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.batchRemoveCatalogAttributes as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes replaceCatalogAttribute without error using callback', async () => { - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ReplaceCatalogAttributeRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ReplaceCatalogAttributeRequest', ['attributesConfig']); - request.attributesConfig = defaultValue1; - const expectedHeaderRequestParams = `attributes_config=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.AttributesConfig() - ); - client.innerApiCalls.replaceCatalogAttribute = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.replaceCatalogAttribute( - request, - (err?: Error|null, result?: protos.google.cloud.retail.v2alpha.IAttributesConfig|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.replaceCatalogAttribute as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.replaceCatalogAttribute as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes batchRemoveCatalogAttributes with error', async () => { + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.BatchRemoveCatalogAttributesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.BatchRemoveCatalogAttributesRequest', + ['attributesConfig'], + ); + request.attributesConfig = defaultValue1; + const expectedHeaderRequestParams = `attributes_config=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.batchRemoveCatalogAttributes = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.batchRemoveCatalogAttributes(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.batchRemoveCatalogAttributes as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.batchRemoveCatalogAttributes as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes replaceCatalogAttribute with error', async () => { - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ReplaceCatalogAttributeRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ReplaceCatalogAttributeRequest', ['attributesConfig']); - request.attributesConfig = defaultValue1; - const expectedHeaderRequestParams = `attributes_config=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.replaceCatalogAttribute = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.replaceCatalogAttribute(request), expectedError); - const actualRequest = (client.innerApiCalls.replaceCatalogAttribute as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.replaceCatalogAttribute as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes batchRemoveCatalogAttributes with closed client', async () => { + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.BatchRemoveCatalogAttributesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.BatchRemoveCatalogAttributesRequest', + ['attributesConfig'], + ); + request.attributesConfig = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.batchRemoveCatalogAttributes(request), + expectedError, + ); + }); + }); + + describe('replaceCatalogAttribute', () => { + it('invokes replaceCatalogAttribute without error', async () => { + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ReplaceCatalogAttributeRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ReplaceCatalogAttributeRequest', + ['attributesConfig'], + ); + request.attributesConfig = defaultValue1; + const expectedHeaderRequestParams = `attributes_config=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.AttributesConfig(), + ); + client.innerApiCalls.replaceCatalogAttribute = + stubSimpleCall(expectedResponse); + const [response] = await client.replaceCatalogAttribute(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.replaceCatalogAttribute as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.replaceCatalogAttribute as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes replaceCatalogAttribute with closed client', async () => { - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ReplaceCatalogAttributeRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ReplaceCatalogAttributeRequest', ['attributesConfig']); - request.attributesConfig = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.replaceCatalogAttribute(request), expectedError); - }); + it('invokes replaceCatalogAttribute without error using callback', async () => { + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ReplaceCatalogAttributeRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ReplaceCatalogAttributeRequest', + ['attributesConfig'], + ); + request.attributesConfig = defaultValue1; + const expectedHeaderRequestParams = `attributes_config=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.AttributesConfig(), + ); + client.innerApiCalls.replaceCatalogAttribute = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.replaceCatalogAttribute( + request, + ( + err?: Error | null, + result?: protos.google.cloud.retail.v2alpha.IAttributesConfig | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.replaceCatalogAttribute as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.replaceCatalogAttribute as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('listCatalogs', () => { - it('invokes listCatalogs without error', async () => { - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ListCatalogsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ListCatalogsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.retail.v2alpha.Catalog()), - generateSampleMessage(new protos.google.cloud.retail.v2alpha.Catalog()), - generateSampleMessage(new protos.google.cloud.retail.v2alpha.Catalog()), - ]; - client.innerApiCalls.listCatalogs = stubSimpleCall(expectedResponse); - const [response] = await client.listCatalogs(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listCatalogs as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listCatalogs as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes replaceCatalogAttribute with error', async () => { + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ReplaceCatalogAttributeRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ReplaceCatalogAttributeRequest', + ['attributesConfig'], + ); + request.attributesConfig = defaultValue1; + const expectedHeaderRequestParams = `attributes_config=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.replaceCatalogAttribute = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.replaceCatalogAttribute(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.replaceCatalogAttribute as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.replaceCatalogAttribute as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listCatalogs without error using callback', async () => { - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ListCatalogsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ListCatalogsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.retail.v2alpha.Catalog()), - generateSampleMessage(new protos.google.cloud.retail.v2alpha.Catalog()), - generateSampleMessage(new protos.google.cloud.retail.v2alpha.Catalog()), - ]; - client.innerApiCalls.listCatalogs = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listCatalogs( - request, - (err?: Error|null, result?: protos.google.cloud.retail.v2alpha.ICatalog[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listCatalogs as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listCatalogs as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes replaceCatalogAttribute with closed client', async () => { + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ReplaceCatalogAttributeRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ReplaceCatalogAttributeRequest', + ['attributesConfig'], + ); + request.attributesConfig = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.replaceCatalogAttribute(request), + expectedError, + ); + }); + }); + + describe('listCatalogs', () => { + it('invokes listCatalogs without error', async () => { + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ListCatalogsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ListCatalogsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.retail.v2alpha.Catalog()), + generateSampleMessage(new protos.google.cloud.retail.v2alpha.Catalog()), + generateSampleMessage(new protos.google.cloud.retail.v2alpha.Catalog()), + ]; + client.innerApiCalls.listCatalogs = stubSimpleCall(expectedResponse); + const [response] = await client.listCatalogs(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listCatalogs as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listCatalogs as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listCatalogs with error', async () => { - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ListCatalogsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ListCatalogsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listCatalogs = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listCatalogs(request), expectedError); - const actualRequest = (client.innerApiCalls.listCatalogs as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listCatalogs as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listCatalogs without error using callback', async () => { + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ListCatalogsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ListCatalogsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.retail.v2alpha.Catalog()), + generateSampleMessage(new protos.google.cloud.retail.v2alpha.Catalog()), + generateSampleMessage(new protos.google.cloud.retail.v2alpha.Catalog()), + ]; + client.innerApiCalls.listCatalogs = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listCatalogs( + request, + ( + err?: Error | null, + result?: protos.google.cloud.retail.v2alpha.ICatalog[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listCatalogs as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listCatalogs as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listCatalogsStream without error', async () => { - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ListCatalogsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ListCatalogsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.retail.v2alpha.Catalog()), - generateSampleMessage(new protos.google.cloud.retail.v2alpha.Catalog()), - generateSampleMessage(new protos.google.cloud.retail.v2alpha.Catalog()), - ]; - client.descriptors.page.listCatalogs.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listCatalogsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.cloud.retail.v2alpha.Catalog[] = []; - stream.on('data', (response: protos.google.cloud.retail.v2alpha.Catalog) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.listCatalogs.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listCatalogs, request)); - assert( - (client.descriptors.page.listCatalogs.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listCatalogs with error', async () => { + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ListCatalogsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ListCatalogsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listCatalogs = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listCatalogs(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listCatalogs as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listCatalogs as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listCatalogsStream with error', async () => { - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ListCatalogsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ListCatalogsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listCatalogs.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listCatalogsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.cloud.retail.v2alpha.Catalog[] = []; - stream.on('data', (response: protos.google.cloud.retail.v2alpha.Catalog) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listCatalogs.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listCatalogs, request)); - assert( - (client.descriptors.page.listCatalogs.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listCatalogsStream without error', async () => { + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ListCatalogsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ListCatalogsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.retail.v2alpha.Catalog()), + generateSampleMessage(new protos.google.cloud.retail.v2alpha.Catalog()), + generateSampleMessage(new protos.google.cloud.retail.v2alpha.Catalog()), + ]; + client.descriptors.page.listCatalogs.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listCatalogsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.cloud.retail.v2alpha.Catalog[] = []; + stream.on( + 'data', + (response: protos.google.cloud.retail.v2alpha.Catalog) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listCatalogs.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listCatalogs, request), + ); + assert( + (client.descriptors.page.listCatalogs.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('uses async iteration with listCatalogs without error', async () => { - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ListCatalogsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ListCatalogsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.retail.v2alpha.Catalog()), - generateSampleMessage(new protos.google.cloud.retail.v2alpha.Catalog()), - generateSampleMessage(new protos.google.cloud.retail.v2alpha.Catalog()), - ]; - client.descriptors.page.listCatalogs.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.cloud.retail.v2alpha.ICatalog[] = []; - const iterable = client.listCatalogsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listCatalogs.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listCatalogs.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listCatalogsStream with error', async () => { + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ListCatalogsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ListCatalogsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listCatalogs.createStream = stubPageStreamingCall( + undefined, + expectedError, + ); + const stream = client.listCatalogsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.cloud.retail.v2alpha.Catalog[] = []; + stream.on( + 'data', + (response: protos.google.cloud.retail.v2alpha.Catalog) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listCatalogs.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listCatalogs, request), + ); + assert( + (client.descriptors.page.listCatalogs.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('uses async iteration with listCatalogs with error', async () => { - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ListCatalogsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ListCatalogsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listCatalogs.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listCatalogsAsync(request); - await assert.rejects(async () => { - const responses: protos.google.cloud.retail.v2alpha.ICatalog[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listCatalogs.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listCatalogs.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listCatalogs without error', async () => { + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ListCatalogsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ListCatalogsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.retail.v2alpha.Catalog()), + generateSampleMessage(new protos.google.cloud.retail.v2alpha.Catalog()), + generateSampleMessage(new protos.google.cloud.retail.v2alpha.Catalog()), + ]; + client.descriptors.page.listCatalogs.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.cloud.retail.v2alpha.ICatalog[] = []; + const iterable = client.listCatalogsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listCatalogs.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listCatalogs.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); }); - describe('Path templates', () => { - - describe('alertConfig', () => { - const fakePath = "/rendered/path/alertConfig"; - const expectedParameters = { - project: "projectValue", - }; - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.alertConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.alertConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('alertConfigPath', () => { - const result = client.alertConfigPath("projectValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.alertConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromAlertConfigName', () => { - const result = client.matchProjectFromAlertConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.alertConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('uses async iteration with listCatalogs with error', async () => { + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ListCatalogsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ListCatalogsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listCatalogs.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listCatalogsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.cloud.retail.v2alpha.ICatalog[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listCatalogs.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listCatalogs.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + }); + + describe('Path templates', () => { + describe('alertConfig', () => { + const fakePath = '/rendered/path/alertConfig'; + const expectedParameters = { + project: 'projectValue', + }; + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.alertConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.alertConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('alertConfigPath', () => { + const result = client.alertConfigPath('projectValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.alertConfigPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromAlertConfigName', () => { + const result = client.matchProjectFromAlertConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.alertConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('attributesConfig', () => { - const fakePath = "/rendered/path/attributesConfig"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - }; - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.attributesConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.attributesConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('attributesConfigPath', () => { - const result = client.attributesConfigPath("projectValue", "locationValue", "catalogValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.attributesConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromAttributesConfigName', () => { - const result = client.matchProjectFromAttributesConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromAttributesConfigName', () => { - const result = client.matchLocationFromAttributesConfigName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromAttributesConfigName', () => { - const result = client.matchCatalogFromAttributesConfigName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('attributesConfig', () => { + const fakePath = '/rendered/path/attributesConfig'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + }; + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.attributesConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.attributesConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('attributesConfigPath', () => { + const result = client.attributesConfigPath( + 'projectValue', + 'locationValue', + 'catalogValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.attributesConfigPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromAttributesConfigName', () => { + const result = client.matchProjectFromAttributesConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromAttributesConfigName', () => { + const result = client.matchLocationFromAttributesConfigName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromAttributesConfigName', () => { + const result = client.matchCatalogFromAttributesConfigName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('branch', () => { - const fakePath = "/rendered/path/branch"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - branch: "branchValue", - }; - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.branchPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.branchPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('branchPath', () => { - const result = client.branchPath("projectValue", "locationValue", "catalogValue", "branchValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.branchPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromBranchName', () => { - const result = client.matchProjectFromBranchName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.branchPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromBranchName', () => { - const result = client.matchLocationFromBranchName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.branchPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromBranchName', () => { - const result = client.matchCatalogFromBranchName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.branchPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBranchFromBranchName', () => { - const result = client.matchBranchFromBranchName(fakePath); - assert.strictEqual(result, "branchValue"); - assert((client.pathTemplates.branchPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('branch', () => { + const fakePath = '/rendered/path/branch'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + branch: 'branchValue', + }; + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.branchPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.branchPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('branchPath', () => { + const result = client.branchPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'branchValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.branchPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromBranchName', () => { + const result = client.matchProjectFromBranchName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.branchPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromBranchName', () => { + const result = client.matchLocationFromBranchName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.branchPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromBranchName', () => { + const result = client.matchCatalogFromBranchName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.branchPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBranchFromBranchName', () => { + const result = client.matchBranchFromBranchName(fakePath); + assert.strictEqual(result, 'branchValue'); + assert( + (client.pathTemplates.branchPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('catalog', () => { - const fakePath = "/rendered/path/catalog"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - }; - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.catalogPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.catalogPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('catalogPath', () => { - const result = client.catalogPath("projectValue", "locationValue", "catalogValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.catalogPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromCatalogName', () => { - const result = client.matchProjectFromCatalogName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.catalogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromCatalogName', () => { - const result = client.matchLocationFromCatalogName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.catalogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromCatalogName', () => { - const result = client.matchCatalogFromCatalogName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.catalogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('catalog', () => { + const fakePath = '/rendered/path/catalog'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + }; + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.catalogPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.catalogPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('catalogPath', () => { + const result = client.catalogPath( + 'projectValue', + 'locationValue', + 'catalogValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.catalogPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromCatalogName', () => { + const result = client.matchProjectFromCatalogName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.catalogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromCatalogName', () => { + const result = client.matchLocationFromCatalogName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.catalogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromCatalogName', () => { + const result = client.matchCatalogFromCatalogName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.catalogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('completionConfig', () => { - const fakePath = "/rendered/path/completionConfig"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - }; - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.completionConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.completionConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('completionConfigPath', () => { - const result = client.completionConfigPath("projectValue", "locationValue", "catalogValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.completionConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromCompletionConfigName', () => { - const result = client.matchProjectFromCompletionConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.completionConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromCompletionConfigName', () => { - const result = client.matchLocationFromCompletionConfigName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.completionConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromCompletionConfigName', () => { - const result = client.matchCatalogFromCompletionConfigName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.completionConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('completionConfig', () => { + const fakePath = '/rendered/path/completionConfig'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + }; + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.completionConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.completionConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('completionConfigPath', () => { + const result = client.completionConfigPath( + 'projectValue', + 'locationValue', + 'catalogValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.completionConfigPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromCompletionConfigName', () => { + const result = client.matchProjectFromCompletionConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.completionConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromCompletionConfigName', () => { + const result = client.matchLocationFromCompletionConfigName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.completionConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromCompletionConfigName', () => { + const result = client.matchCatalogFromCompletionConfigName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.completionConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('control', () => { - const fakePath = "/rendered/path/control"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - control: "controlValue", - }; - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.controlPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.controlPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('controlPath', () => { - const result = client.controlPath("projectValue", "locationValue", "catalogValue", "controlValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.controlPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromControlName', () => { - const result = client.matchProjectFromControlName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.controlPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromControlName', () => { - const result = client.matchLocationFromControlName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.controlPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromControlName', () => { - const result = client.matchCatalogFromControlName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.controlPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchControlFromControlName', () => { - const result = client.matchControlFromControlName(fakePath); - assert.strictEqual(result, "controlValue"); - assert((client.pathTemplates.controlPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('control', () => { + const fakePath = '/rendered/path/control'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + control: 'controlValue', + }; + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.controlPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.controlPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('controlPath', () => { + const result = client.controlPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'controlValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.controlPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromControlName', () => { + const result = client.matchProjectFromControlName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.controlPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromControlName', () => { + const result = client.matchLocationFromControlName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.controlPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromControlName', () => { + const result = client.matchCatalogFromControlName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.controlPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchControlFromControlName', () => { + const result = client.matchControlFromControlName(fakePath); + assert.strictEqual(result, 'controlValue'); + assert( + (client.pathTemplates.controlPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('location', () => { - const fakePath = "/rendered/path/location"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - }; - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.locationPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.locationPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('locationPath', () => { - const result = client.locationPath("projectValue", "locationValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.locationPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromLocationName', () => { - const result = client.matchProjectFromLocationName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.locationPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromLocationName', () => { - const result = client.matchLocationFromLocationName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.locationPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('location', () => { + const fakePath = '/rendered/path/location'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + }; + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.locationPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.locationPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('locationPath', () => { + const result = client.locationPath('projectValue', 'locationValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.locationPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromLocationName', () => { + const result = client.matchProjectFromLocationName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.locationPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromLocationName', () => { + const result = client.matchLocationFromLocationName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.locationPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('loggingConfig', () => { - const fakePath = "/rendered/path/loggingConfig"; - const expectedParameters = { - project: "projectValue", - }; - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.loggingConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.loggingConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('loggingConfigPath', () => { - const result = client.loggingConfigPath("projectValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.loggingConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromLoggingConfigName', () => { - const result = client.matchProjectFromLoggingConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.loggingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('loggingConfig', () => { + const fakePath = '/rendered/path/loggingConfig'; + const expectedParameters = { + project: 'projectValue', + }; + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.loggingConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.loggingConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('loggingConfigPath', () => { + const result = client.loggingConfigPath('projectValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.loggingConfigPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromLoggingConfigName', () => { + const result = client.matchProjectFromLoggingConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.loggingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('merchantCenterAccountLink', () => { - const fakePath = "/rendered/path/merchantCenterAccountLink"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - merchant_center_account_link: "merchantCenterAccountLinkValue", - }; - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.merchantCenterAccountLinkPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.merchantCenterAccountLinkPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('merchantCenterAccountLinkPath', () => { - const result = client.merchantCenterAccountLinkPath("projectValue", "locationValue", "catalogValue", "merchantCenterAccountLinkValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromMerchantCenterAccountLinkName', () => { - const result = client.matchProjectFromMerchantCenterAccountLinkName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromMerchantCenterAccountLinkName', () => { - const result = client.matchLocationFromMerchantCenterAccountLinkName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromMerchantCenterAccountLinkName', () => { - const result = client.matchCatalogFromMerchantCenterAccountLinkName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName', () => { - const result = client.matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName(fakePath); - assert.strictEqual(result, "merchantCenterAccountLinkValue"); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('merchantCenterAccountLink', () => { + const fakePath = '/rendered/path/merchantCenterAccountLink'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + merchant_center_account_link: 'merchantCenterAccountLinkValue', + }; + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.merchantCenterAccountLinkPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.merchantCenterAccountLinkPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('merchantCenterAccountLinkPath', () => { + const result = client.merchantCenterAccountLinkPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'merchantCenterAccountLinkValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromMerchantCenterAccountLinkName', () => { + const result = + client.matchProjectFromMerchantCenterAccountLinkName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromMerchantCenterAccountLinkName', () => { + const result = + client.matchLocationFromMerchantCenterAccountLinkName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromMerchantCenterAccountLinkName', () => { + const result = + client.matchCatalogFromMerchantCenterAccountLinkName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName', () => { + const result = + client.matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName( + fakePath, + ); + assert.strictEqual(result, 'merchantCenterAccountLinkValue'); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('model', () => { - const fakePath = "/rendered/path/model"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - model: "modelValue", - }; - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.modelPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.modelPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('modelPath', () => { - const result = client.modelPath("projectValue", "locationValue", "catalogValue", "modelValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.modelPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromModelName', () => { - const result = client.matchProjectFromModelName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromModelName', () => { - const result = client.matchLocationFromModelName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromModelName', () => { - const result = client.matchCatalogFromModelName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchModelFromModelName', () => { - const result = client.matchModelFromModelName(fakePath); - assert.strictEqual(result, "modelValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('model', () => { + const fakePath = '/rendered/path/model'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + model: 'modelValue', + }; + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.modelPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.modelPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('modelPath', () => { + const result = client.modelPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'modelValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.modelPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromModelName', () => { + const result = client.matchProjectFromModelName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromModelName', () => { + const result = client.matchLocationFromModelName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromModelName', () => { + const result = client.matchCatalogFromModelName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchModelFromModelName', () => { + const result = client.matchModelFromModelName(fakePath); + assert.strictEqual(result, 'modelValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('product', () => { - const fakePath = "/rendered/path/product"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - branch: "branchValue", - product: "productValue", - }; - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.productPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.productPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('productPath', () => { - const result = client.productPath("projectValue", "locationValue", "catalogValue", "branchValue", "productValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.productPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProductName', () => { - const result = client.matchProjectFromProductName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromProductName', () => { - const result = client.matchLocationFromProductName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromProductName', () => { - const result = client.matchCatalogFromProductName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBranchFromProductName', () => { - const result = client.matchBranchFromProductName(fakePath); - assert.strictEqual(result, "branchValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchProductFromProductName', () => { - const result = client.matchProductFromProductName(fakePath); - assert.strictEqual(result, "productValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('product', () => { + const fakePath = '/rendered/path/product'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + branch: 'branchValue', + product: 'productValue', + }; + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.productPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.productPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('productPath', () => { + const result = client.productPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'branchValue', + 'productValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.productPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProductName', () => { + const result = client.matchProjectFromProductName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromProductName', () => { + const result = client.matchLocationFromProductName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromProductName', () => { + const result = client.matchCatalogFromProductName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBranchFromProductName', () => { + const result = client.matchBranchFromProductName(fakePath); + assert.strictEqual(result, 'branchValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchProductFromProductName', () => { + const result = client.matchProductFromProductName(fakePath); + assert.strictEqual(result, 'productValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('retailProject', () => { - const fakePath = "/rendered/path/retailProject"; - const expectedParameters = { - project: "projectValue", - }; - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.retailProjectPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.retailProjectPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('retailProjectPath', () => { - const result = client.retailProjectPath("projectValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.retailProjectPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromRetailProjectName', () => { - const result = client.matchProjectFromRetailProjectName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.retailProjectPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('retailProject', () => { + const fakePath = '/rendered/path/retailProject'; + const expectedParameters = { + project: 'projectValue', + }; + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.retailProjectPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.retailProjectPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('retailProjectPath', () => { + const result = client.retailProjectPath('projectValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.retailProjectPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromRetailProjectName', () => { + const result = client.matchProjectFromRetailProjectName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.retailProjectPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('servingConfig', () => { - const fakePath = "/rendered/path/servingConfig"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - serving_config: "servingConfigValue", - }; - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.servingConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.servingConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('servingConfigPath', () => { - const result = client.servingConfigPath("projectValue", "locationValue", "catalogValue", "servingConfigValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.servingConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromServingConfigName', () => { - const result = client.matchProjectFromServingConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.servingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromServingConfigName', () => { - const result = client.matchLocationFromServingConfigName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.servingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromServingConfigName', () => { - const result = client.matchCatalogFromServingConfigName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.servingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServingConfigFromServingConfigName', () => { - const result = client.matchServingConfigFromServingConfigName(fakePath); - assert.strictEqual(result, "servingConfigValue"); - assert((client.pathTemplates.servingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('servingConfig', () => { + const fakePath = '/rendered/path/servingConfig'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + serving_config: 'servingConfigValue', + }; + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.servingConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.servingConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('servingConfigPath', () => { + const result = client.servingConfigPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'servingConfigValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.servingConfigPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromServingConfigName', () => { + const result = client.matchProjectFromServingConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.servingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromServingConfigName', () => { + const result = client.matchLocationFromServingConfigName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.servingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromServingConfigName', () => { + const result = client.matchCatalogFromServingConfigName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.servingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServingConfigFromServingConfigName', () => { + const result = client.matchServingConfigFromServingConfigName(fakePath); + assert.strictEqual(result, 'servingConfigValue'); + assert( + (client.pathTemplates.servingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/test/gapic_completion_service_v2alpha.ts.baseline b/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/test/gapic_completion_service_v2alpha.ts.baseline index 5ff69dc5b518..1951c6a98289 100644 --- a/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/test/gapic_completion_service_v2alpha.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/test/gapic_completion_service_v2alpha.ts.baseline @@ -20,14 +20,14 @@ import * as protos from '../../protos/protos.js'; import assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as completionserviceModule from '../src/index.js'; -import {protobuf, LROperation, operationsProtos} from 'google-gax'; +import { protobuf, LROperation, operationsProtos } from 'google-gax'; import fs from 'fs'; import path from 'path'; -import {fileURLToPath} from 'url'; +import { fileURLToPath } from 'url'; // @ts-ignore const dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -35,1030 +35,1453 @@ const dirname = path.dirname(fileURLToPath(import.meta.url)); // to fill in default values for request objects const root = protobuf.Root.fromJSON( JSON.parse( - fs.readFileSync(path.join(dirname, '..', '..', 'protos/protos.json'), 'utf8') - )) + fs.readFileSync( + path.join(dirname, '..', '..', 'protos/protos.json'), + 'utf8', + ), + ), +); // eslint-disable-next-line @typescript-eslint/no-unused-vars function getTypeDefaultValue(typeName: string, fields: string[]) { - let type = root.lookupType(typeName) as protobuf.Type; - for (const field of fields.slice(0, -1)) { - type = type?.fields[field]?.resolvedType as protobuf.Type; - } - return type?.fields[fields[fields.length - 1]]?.defaultValue ?? null; + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type?.fields[field]?.resolvedType as protobuf.Type; + } + return type?.fields[fields[fields.length - 1]]?.defaultValue ?? null; } function generateSampleMessage(instance: T) { - const filledObject = (instance.constructor as typeof protobuf.Message) - .toObject(instance as protobuf.Message, {defaults: true}); - return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, { defaults: true }); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; } function stubSimpleCall(response?: ResponseType, error?: Error) { - return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); } -function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { - return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +function stubSimpleCallWithCallback( + response?: ResponseType, + error?: Error, +) { + return error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); } -function stubLongRunningCall(response?: ResponseType, callError?: Error, lroError?: Error) { - const innerStub = lroError ? sinon.stub().rejects(lroError) : sinon.stub().resolves([response]); - const mockOperation = { - promise: innerStub, - }; - return callError ? sinon.stub().rejects(callError) : sinon.stub().resolves([mockOperation]); +function stubLongRunningCall( + response?: ResponseType, + callError?: Error, + lroError?: Error, +) { + const innerStub = lroError + ? sinon.stub().rejects(lroError) + : sinon.stub().resolves([response]); + const mockOperation = { + promise: innerStub, + }; + return callError + ? sinon.stub().rejects(callError) + : sinon.stub().resolves([mockOperation]); } -function stubLongRunningCallWithCallback(response?: ResponseType, callError?: Error, lroError?: Error) { - const innerStub = lroError ? sinon.stub().rejects(lroError) : sinon.stub().resolves([response]); - const mockOperation = { - promise: innerStub, - }; - return callError ? sinon.stub().callsArgWith(2, callError) : sinon.stub().callsArgWith(2, null, mockOperation); +function stubLongRunningCallWithCallback( + response?: ResponseType, + callError?: Error, + lroError?: Error, +) { + const innerStub = lroError + ? sinon.stub().rejects(lroError) + : sinon.stub().resolves([response]); + const mockOperation = { + promise: innerStub, + }; + return callError + ? sinon.stub().callsArgWith(2, callError) + : sinon.stub().callsArgWith(2, null, mockOperation); } describe('v2alpha.CompletionServiceClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new completionserviceModule.v2alpha.CompletionServiceClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'retail.googleapis.com'); - }); - - it('has universeDomain', () => { - const client = new completionserviceModule.v2alpha.CompletionServiceClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = + new completionserviceModule.v2alpha.CompletionServiceClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'retail.googleapis.com'); + }); - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - it('throws DeprecationWarning if static servicePath is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const servicePath = completionserviceModule.v2alpha.CompletionServiceClient.servicePath; - assert.strictEqual(servicePath, 'retail.googleapis.com'); - assert(stub.called); - stub.restore(); - }); + it('has universeDomain', () => { + const client = + new completionserviceModule.v2alpha.CompletionServiceClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = completionserviceModule.v2alpha.CompletionServiceClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'retail.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new completionserviceModule.v2alpha.CompletionServiceClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'retail.example.com'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = + completionserviceModule.v2alpha.CompletionServiceClient.servicePath; + assert.strictEqual(servicePath, 'retail.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + completionserviceModule.v2alpha.CompletionServiceClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'retail.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = + new completionserviceModule.v2alpha.CompletionServiceClient({ + universeDomain: 'example.com', }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'retail.example.com'); + }); - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new completionserviceModule.v2alpha.CompletionServiceClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'retail.example.com'); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = + new completionserviceModule.v2alpha.CompletionServiceClient({ + universe_domain: 'example.com', }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'retail.example.com'); + }); - if (typeof process === 'object' && 'env' in process) { - describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { - it('sets apiEndpoint from environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new completionserviceModule.v2alpha.CompletionServiceClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'retail.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - - it('value configured in code has priority over environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new completionserviceModule.v2alpha.CompletionServiceClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'retail.configured.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { new completionserviceModule.v2alpha.CompletionServiceClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); + if (typeof process === 'object' && 'env' in process) { + describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { + it('sets apiEndpoint from environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = + new completionserviceModule.v2alpha.CompletionServiceClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'retail.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - it('has port', () => { - const port = completionserviceModule.v2alpha.CompletionServiceClient.port; - assert(port); - assert(typeof port === 'number'); + it('value configured in code has priority over environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = + new completionserviceModule.v2alpha.CompletionServiceClient({ + universeDomain: 'configured.example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'retail.configured.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - - it('should create a client with no option', () => { - const client = new completionserviceModule.v2alpha.CompletionServiceClient(); - assert(client); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new completionserviceModule.v2alpha.CompletionServiceClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); + }); - it('should create a client with gRPC fallback', () => { - const client = new completionserviceModule.v2alpha.CompletionServiceClient({ - fallback: true, - }); - assert(client); - }); + it('has port', () => { + const port = completionserviceModule.v2alpha.CompletionServiceClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('has initialize method and supports deferred initialization', async () => { - const client = new completionserviceModule.v2alpha.CompletionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.completionServiceStub, undefined); - await client.initialize(); - assert(client.completionServiceStub); - }); + it('should create a client with no option', () => { + const client = + new completionserviceModule.v2alpha.CompletionServiceClient(); + assert(client); + }); - it('has close method for the initialized client', done => { - const client = new completionserviceModule.v2alpha.CompletionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.completionServiceStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); + it('should create a client with gRPC fallback', () => { + const client = + new completionserviceModule.v2alpha.CompletionServiceClient({ + fallback: true, }); + assert(client); + }); - it('has close method for the non-initialized client', done => { - const client = new completionserviceModule.v2alpha.CompletionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.completionServiceStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); + it('has initialize method and supports deferred initialization', async () => { + const client = + new completionserviceModule.v2alpha.CompletionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + assert.strictEqual(client.completionServiceStub, undefined); + await client.initialize(); + assert(client.completionServiceStub); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new completionserviceModule.v2alpha.CompletionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + it('has close method for the initialized client', (done) => { + const client = + new completionserviceModule.v2alpha.CompletionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); - - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new completionserviceModule.v2alpha.CompletionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId((err?: Error|null, projectId?: string|null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } - }); - }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); + client.initialize().catch((err) => { + throw err; + }); + assert(client.completionServiceStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); }); - describe('completeQuery', () => { - it('invokes completeQuery without error', async () => { - const client = new completionserviceModule.v2alpha.CompletionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.CompleteQueryRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.CompleteQueryRequest', ['catalog']); - request.catalog = defaultValue1; - const expectedHeaderRequestParams = `catalog=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.CompleteQueryResponse() - ); - client.innerApiCalls.completeQuery = stubSimpleCall(expectedResponse); - const [response] = await client.completeQuery(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.completeQuery as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.completeQuery as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('has close method for the non-initialized client', (done) => { + const client = + new completionserviceModule.v2alpha.CompletionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); - - it('invokes completeQuery without error using callback', async () => { - const client = new completionserviceModule.v2alpha.CompletionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.CompleteQueryRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.CompleteQueryRequest', ['catalog']); - request.catalog = defaultValue1; - const expectedHeaderRequestParams = `catalog=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.CompleteQueryResponse() - ); - client.innerApiCalls.completeQuery = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.completeQuery( - request, - (err?: Error|null, result?: protos.google.cloud.retail.v2alpha.ICompleteQueryResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.completeQuery as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.completeQuery as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + assert.strictEqual(client.completionServiceStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes completeQuery with error', async () => { - const client = new completionserviceModule.v2alpha.CompletionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.CompleteQueryRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.CompleteQueryRequest', ['catalog']); - request.catalog = defaultValue1; - const expectedHeaderRequestParams = `catalog=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.completeQuery = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.completeQuery(request), expectedError); - const actualRequest = (client.innerApiCalls.completeQuery as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.completeQuery as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = + new completionserviceModule.v2alpha.CompletionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + }); - it('invokes completeQuery with closed client', async () => { - const client = new completionserviceModule.v2alpha.CompletionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.CompleteQueryRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.CompleteQueryRequest', ['catalog']); - request.catalog = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.completeQuery(request), expectedError); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = + new completionserviceModule.v2alpha.CompletionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } + }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); }); - - describe('importCompletionData', () => { - it('invokes importCompletionData without error', async () => { - const client = new completionserviceModule.v2alpha.CompletionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ImportCompletionDataRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ImportCompletionDataRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.importCompletionData = stubLongRunningCall(expectedResponse); - const [operation] = await client.importCompletionData(request); - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.importCompletionData as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.importCompletionData as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + describe('completeQuery', () => { + it('invokes completeQuery without error', async () => { + const client = + new completionserviceModule.v2alpha.CompletionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.CompleteQueryRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.CompleteQueryRequest', + ['catalog'], + ); + request.catalog = defaultValue1; + const expectedHeaderRequestParams = `catalog=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.CompleteQueryResponse(), + ); + client.innerApiCalls.completeQuery = stubSimpleCall(expectedResponse); + const [response] = await client.completeQuery(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.completeQuery as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.completeQuery as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes importCompletionData without error using callback', async () => { - const client = new completionserviceModule.v2alpha.CompletionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ImportCompletionDataRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ImportCompletionDataRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.importCompletionData = stubLongRunningCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.importCompletionData( - request, - (err?: Error|null, - result?: LROperation|null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const operation = await promise as LROperation; - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.importCompletionData as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.importCompletionData as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes completeQuery without error using callback', async () => { + const client = + new completionserviceModule.v2alpha.CompletionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.CompleteQueryRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.CompleteQueryRequest', + ['catalog'], + ); + request.catalog = defaultValue1; + const expectedHeaderRequestParams = `catalog=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.CompleteQueryResponse(), + ); + client.innerApiCalls.completeQuery = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.completeQuery( + request, + ( + err?: Error | null, + result?: protos.google.cloud.retail.v2alpha.ICompleteQueryResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.completeQuery as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.completeQuery as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes importCompletionData with call error', async () => { - const client = new completionserviceModule.v2alpha.CompletionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ImportCompletionDataRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ImportCompletionDataRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.importCompletionData = stubLongRunningCall(undefined, expectedError); - await assert.rejects(client.importCompletionData(request), expectedError); - const actualRequest = (client.innerApiCalls.importCompletionData as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.importCompletionData as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes completeQuery with error', async () => { + const client = + new completionserviceModule.v2alpha.CompletionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.CompleteQueryRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.CompleteQueryRequest', + ['catalog'], + ); + request.catalog = defaultValue1; + const expectedHeaderRequestParams = `catalog=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.completeQuery = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.completeQuery(request), expectedError); + const actualRequest = ( + client.innerApiCalls.completeQuery as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.completeQuery as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes importCompletionData with LRO error', async () => { - const client = new completionserviceModule.v2alpha.CompletionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ImportCompletionDataRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ImportCompletionDataRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.importCompletionData = stubLongRunningCall(undefined, undefined, expectedError); - const [operation] = await client.importCompletionData(request); - await assert.rejects(operation.promise(), expectedError); - const actualRequest = (client.innerApiCalls.importCompletionData as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.importCompletionData as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes completeQuery with closed client', async () => { + const client = + new completionserviceModule.v2alpha.CompletionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); - - it('invokes checkImportCompletionDataProgress without error', async () => { - const client = new completionserviceModule.v2alpha.CompletionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedResponse = generateSampleMessage( - new operationsProtos.google.longrunning.Operation() - ); - expectedResponse.name = 'test'; - expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; - expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')} - - client.operationsClient.getOperation = stubSimpleCall(expectedResponse); - const decodedOperation = await client.checkImportCompletionDataProgress(expectedResponse.name); - assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); - assert(decodedOperation.metadata); - assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.CompleteQueryRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.CompleteQueryRequest', + ['catalog'], + ); + request.catalog = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.completeQuery(request), expectedError); + }); + }); + + describe('importCompletionData', () => { + it('invokes importCompletionData without error', async () => { + const client = + new completionserviceModule.v2alpha.CompletionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ImportCompletionDataRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ImportCompletionDataRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.importCompletionData = + stubLongRunningCall(expectedResponse); + const [operation] = await client.importCompletionData(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.importCompletionData as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.importCompletionData as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkImportCompletionDataProgress with error', async () => { - const client = new completionserviceModule.v2alpha.CompletionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedError = new Error('expected'); - - client.operationsClient.getOperation = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.checkImportCompletionDataProgress(''), expectedError); - assert((client.operationsClient.getOperation as SinonStub) - .getCall(0)); + it('invokes importCompletionData without error using callback', async () => { + const client = + new completionserviceModule.v2alpha.CompletionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ImportCompletionDataRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ImportCompletionDataRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.importCompletionData = + stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.importCompletionData( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.cloud.retail.v2alpha.IImportCompletionDataResponse, + protos.google.cloud.retail.v2alpha.IImportMetadata + > | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const operation = (await promise) as LROperation< + protos.google.cloud.retail.v2alpha.IImportCompletionDataResponse, + protos.google.cloud.retail.v2alpha.IImportMetadata + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.importCompletionData as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.importCompletionData as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('Path templates', () => { - - describe('alertConfig', () => { - const fakePath = "/rendered/path/alertConfig"; - const expectedParameters = { - project: "projectValue", - }; - const client = new completionserviceModule.v2alpha.CompletionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.alertConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.alertConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('alertConfigPath', () => { - const result = client.alertConfigPath("projectValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.alertConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromAlertConfigName', () => { - const result = client.matchProjectFromAlertConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.alertConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('invokes importCompletionData with call error', async () => { + const client = + new completionserviceModule.v2alpha.CompletionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ImportCompletionDataRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ImportCompletionDataRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.importCompletionData = stubLongRunningCall( + undefined, + expectedError, + ); + await assert.rejects(client.importCompletionData(request), expectedError); + const actualRequest = ( + client.innerApiCalls.importCompletionData as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.importCompletionData as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - describe('attributesConfig', () => { - const fakePath = "/rendered/path/attributesConfig"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - }; - const client = new completionserviceModule.v2alpha.CompletionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.attributesConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.attributesConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('attributesConfigPath', () => { - const result = client.attributesConfigPath("projectValue", "locationValue", "catalogValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.attributesConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromAttributesConfigName', () => { - const result = client.matchProjectFromAttributesConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromAttributesConfigName', () => { - const result = client.matchLocationFromAttributesConfigName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromAttributesConfigName', () => { - const result = client.matchCatalogFromAttributesConfigName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('invokes importCompletionData with LRO error', async () => { + const client = + new completionserviceModule.v2alpha.CompletionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ImportCompletionDataRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ImportCompletionDataRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.importCompletionData = stubLongRunningCall( + undefined, + undefined, + expectedError, + ); + const [operation] = await client.importCompletionData(request); + await assert.rejects(operation.promise(), expectedError); + const actualRequest = ( + client.innerApiCalls.importCompletionData as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.importCompletionData as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - describe('branch', () => { - const fakePath = "/rendered/path/branch"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - branch: "branchValue", - }; - const client = new completionserviceModule.v2alpha.CompletionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.branchPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.branchPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('branchPath', () => { - const result = client.branchPath("projectValue", "locationValue", "catalogValue", "branchValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.branchPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromBranchName', () => { - const result = client.matchProjectFromBranchName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.branchPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromBranchName', () => { - const result = client.matchLocationFromBranchName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.branchPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromBranchName', () => { - const result = client.matchCatalogFromBranchName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.branchPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBranchFromBranchName', () => { - const result = client.matchBranchFromBranchName(fakePath); - assert.strictEqual(result, "branchValue"); - assert((client.pathTemplates.branchPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('invokes checkImportCompletionDataProgress without error', async () => { + const client = + new completionserviceModule.v2alpha.CompletionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation(), + ); + expectedResponse.name = 'test'; + expectedResponse.response = { type_url: 'url', value: Buffer.from('') }; + expectedResponse.metadata = { type_url: 'url', value: Buffer.from('') }; + + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const decodedOperation = await client.checkImportCompletionDataProgress( + expectedResponse.name, + ); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); - describe('catalog', () => { - const fakePath = "/rendered/path/catalog"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - }; - const client = new completionserviceModule.v2alpha.CompletionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.catalogPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.catalogPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('catalogPath', () => { - const result = client.catalogPath("projectValue", "locationValue", "catalogValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.catalogPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromCatalogName', () => { - const result = client.matchProjectFromCatalogName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.catalogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromCatalogName', () => { - const result = client.matchLocationFromCatalogName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.catalogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromCatalogName', () => { - const result = client.matchCatalogFromCatalogName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.catalogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('invokes checkImportCompletionDataProgress with error', async () => { + const client = + new completionserviceModule.v2alpha.CompletionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); - - describe('completionConfig', () => { - const fakePath = "/rendered/path/completionConfig"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - }; - const client = new completionserviceModule.v2alpha.CompletionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.completionConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.completionConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('completionConfigPath', () => { - const result = client.completionConfigPath("projectValue", "locationValue", "catalogValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.completionConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromCompletionConfigName', () => { - const result = client.matchProjectFromCompletionConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.completionConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromCompletionConfigName', () => { - const result = client.matchLocationFromCompletionConfigName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.completionConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromCompletionConfigName', () => { - const result = client.matchCatalogFromCompletionConfigName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.completionConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + await client.initialize(); + const expectedError = new Error('expected'); + + client.operationsClient.getOperation = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.checkImportCompletionDataProgress(''), + expectedError, + ); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + }); + + describe('Path templates', () => { + describe('alertConfig', () => { + const fakePath = '/rendered/path/alertConfig'; + const expectedParameters = { + project: 'projectValue', + }; + const client = + new completionserviceModule.v2alpha.CompletionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.alertConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.alertConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('alertConfigPath', () => { + const result = client.alertConfigPath('projectValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.alertConfigPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromAlertConfigName', () => { + const result = client.matchProjectFromAlertConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.alertConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('control', () => { - const fakePath = "/rendered/path/control"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - control: "controlValue", - }; - const client = new completionserviceModule.v2alpha.CompletionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.controlPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.controlPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('controlPath', () => { - const result = client.controlPath("projectValue", "locationValue", "catalogValue", "controlValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.controlPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromControlName', () => { - const result = client.matchProjectFromControlName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.controlPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromControlName', () => { - const result = client.matchLocationFromControlName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.controlPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromControlName', () => { - const result = client.matchCatalogFromControlName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.controlPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchControlFromControlName', () => { - const result = client.matchControlFromControlName(fakePath); - assert.strictEqual(result, "controlValue"); - assert((client.pathTemplates.controlPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('attributesConfig', () => { + const fakePath = '/rendered/path/attributesConfig'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + }; + const client = + new completionserviceModule.v2alpha.CompletionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.attributesConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.attributesConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('attributesConfigPath', () => { + const result = client.attributesConfigPath( + 'projectValue', + 'locationValue', + 'catalogValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.attributesConfigPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromAttributesConfigName', () => { + const result = client.matchProjectFromAttributesConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromAttributesConfigName', () => { + const result = client.matchLocationFromAttributesConfigName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromAttributesConfigName', () => { + const result = client.matchCatalogFromAttributesConfigName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('loggingConfig', () => { - const fakePath = "/rendered/path/loggingConfig"; - const expectedParameters = { - project: "projectValue", - }; - const client = new completionserviceModule.v2alpha.CompletionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.loggingConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.loggingConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('loggingConfigPath', () => { - const result = client.loggingConfigPath("projectValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.loggingConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromLoggingConfigName', () => { - const result = client.matchProjectFromLoggingConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.loggingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('branch', () => { + const fakePath = '/rendered/path/branch'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + branch: 'branchValue', + }; + const client = + new completionserviceModule.v2alpha.CompletionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.branchPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.branchPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('branchPath', () => { + const result = client.branchPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'branchValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.branchPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromBranchName', () => { + const result = client.matchProjectFromBranchName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.branchPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromBranchName', () => { + const result = client.matchLocationFromBranchName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.branchPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromBranchName', () => { + const result = client.matchCatalogFromBranchName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.branchPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBranchFromBranchName', () => { + const result = client.matchBranchFromBranchName(fakePath); + assert.strictEqual(result, 'branchValue'); + assert( + (client.pathTemplates.branchPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('merchantCenterAccountLink', () => { - const fakePath = "/rendered/path/merchantCenterAccountLink"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - merchant_center_account_link: "merchantCenterAccountLinkValue", - }; - const client = new completionserviceModule.v2alpha.CompletionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.merchantCenterAccountLinkPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.merchantCenterAccountLinkPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('merchantCenterAccountLinkPath', () => { - const result = client.merchantCenterAccountLinkPath("projectValue", "locationValue", "catalogValue", "merchantCenterAccountLinkValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromMerchantCenterAccountLinkName', () => { - const result = client.matchProjectFromMerchantCenterAccountLinkName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromMerchantCenterAccountLinkName', () => { - const result = client.matchLocationFromMerchantCenterAccountLinkName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromMerchantCenterAccountLinkName', () => { - const result = client.matchCatalogFromMerchantCenterAccountLinkName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName', () => { - const result = client.matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName(fakePath); - assert.strictEqual(result, "merchantCenterAccountLinkValue"); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('catalog', () => { + const fakePath = '/rendered/path/catalog'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + }; + const client = + new completionserviceModule.v2alpha.CompletionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.catalogPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.catalogPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('catalogPath', () => { + const result = client.catalogPath( + 'projectValue', + 'locationValue', + 'catalogValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.catalogPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromCatalogName', () => { + const result = client.matchProjectFromCatalogName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.catalogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromCatalogName', () => { + const result = client.matchLocationFromCatalogName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.catalogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromCatalogName', () => { + const result = client.matchCatalogFromCatalogName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.catalogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('model', () => { - const fakePath = "/rendered/path/model"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - model: "modelValue", - }; - const client = new completionserviceModule.v2alpha.CompletionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.modelPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.modelPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('modelPath', () => { - const result = client.modelPath("projectValue", "locationValue", "catalogValue", "modelValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.modelPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromModelName', () => { - const result = client.matchProjectFromModelName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromModelName', () => { - const result = client.matchLocationFromModelName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromModelName', () => { - const result = client.matchCatalogFromModelName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchModelFromModelName', () => { - const result = client.matchModelFromModelName(fakePath); - assert.strictEqual(result, "modelValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('completionConfig', () => { + const fakePath = '/rendered/path/completionConfig'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + }; + const client = + new completionserviceModule.v2alpha.CompletionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.completionConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.completionConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('completionConfigPath', () => { + const result = client.completionConfigPath( + 'projectValue', + 'locationValue', + 'catalogValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.completionConfigPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromCompletionConfigName', () => { + const result = client.matchProjectFromCompletionConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.completionConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromCompletionConfigName', () => { + const result = client.matchLocationFromCompletionConfigName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.completionConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromCompletionConfigName', () => { + const result = client.matchCatalogFromCompletionConfigName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.completionConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('product', () => { - const fakePath = "/rendered/path/product"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - branch: "branchValue", - product: "productValue", - }; - const client = new completionserviceModule.v2alpha.CompletionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.productPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.productPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('productPath', () => { - const result = client.productPath("projectValue", "locationValue", "catalogValue", "branchValue", "productValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.productPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProductName', () => { - const result = client.matchProjectFromProductName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromProductName', () => { - const result = client.matchLocationFromProductName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromProductName', () => { - const result = client.matchCatalogFromProductName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBranchFromProductName', () => { - const result = client.matchBranchFromProductName(fakePath); - assert.strictEqual(result, "branchValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchProductFromProductName', () => { - const result = client.matchProductFromProductName(fakePath); - assert.strictEqual(result, "productValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('control', () => { + const fakePath = '/rendered/path/control'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + control: 'controlValue', + }; + const client = + new completionserviceModule.v2alpha.CompletionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.controlPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.controlPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('controlPath', () => { + const result = client.controlPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'controlValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.controlPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromControlName', () => { + const result = client.matchProjectFromControlName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.controlPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromControlName', () => { + const result = client.matchLocationFromControlName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.controlPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromControlName', () => { + const result = client.matchCatalogFromControlName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.controlPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchControlFromControlName', () => { + const result = client.matchControlFromControlName(fakePath); + assert.strictEqual(result, 'controlValue'); + assert( + (client.pathTemplates.controlPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('retailProject', () => { - const fakePath = "/rendered/path/retailProject"; - const expectedParameters = { - project: "projectValue", - }; - const client = new completionserviceModule.v2alpha.CompletionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.retailProjectPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.retailProjectPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('retailProjectPath', () => { - const result = client.retailProjectPath("projectValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.retailProjectPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromRetailProjectName', () => { - const result = client.matchProjectFromRetailProjectName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.retailProjectPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('loggingConfig', () => { + const fakePath = '/rendered/path/loggingConfig'; + const expectedParameters = { + project: 'projectValue', + }; + const client = + new completionserviceModule.v2alpha.CompletionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.loggingConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.loggingConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('loggingConfigPath', () => { + const result = client.loggingConfigPath('projectValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.loggingConfigPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromLoggingConfigName', () => { + const result = client.matchProjectFromLoggingConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.loggingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('servingConfig', () => { - const fakePath = "/rendered/path/servingConfig"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - serving_config: "servingConfigValue", - }; - const client = new completionserviceModule.v2alpha.CompletionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.servingConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.servingConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('servingConfigPath', () => { - const result = client.servingConfigPath("projectValue", "locationValue", "catalogValue", "servingConfigValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.servingConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + describe('merchantCenterAccountLink', () => { + const fakePath = '/rendered/path/merchantCenterAccountLink'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + merchant_center_account_link: 'merchantCenterAccountLinkValue', + }; + const client = + new completionserviceModule.v2alpha.CompletionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.merchantCenterAccountLinkPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.merchantCenterAccountLinkPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('merchantCenterAccountLinkPath', () => { + const result = client.merchantCenterAccountLinkPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'merchantCenterAccountLinkValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromMerchantCenterAccountLinkName', () => { + const result = + client.matchProjectFromMerchantCenterAccountLinkName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromMerchantCenterAccountLinkName', () => { + const result = + client.matchLocationFromMerchantCenterAccountLinkName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromMerchantCenterAccountLinkName', () => { + const result = + client.matchCatalogFromMerchantCenterAccountLinkName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName', () => { + const result = + client.matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName( + fakePath, + ); + assert.strictEqual(result, 'merchantCenterAccountLinkValue'); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchProjectFromServingConfigName', () => { - const result = client.matchProjectFromServingConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.servingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('model', () => { + const fakePath = '/rendered/path/model'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + model: 'modelValue', + }; + const client = + new completionserviceModule.v2alpha.CompletionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.modelPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.modelPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('modelPath', () => { + const result = client.modelPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'modelValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.modelPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromModelName', () => { + const result = client.matchProjectFromModelName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromModelName', () => { + const result = client.matchLocationFromModelName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromModelName', () => { + const result = client.matchCatalogFromModelName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchModelFromModelName', () => { + const result = client.matchModelFromModelName(fakePath); + assert.strictEqual(result, 'modelValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchLocationFromServingConfigName', () => { - const result = client.matchLocationFromServingConfigName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.servingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('product', () => { + const fakePath = '/rendered/path/product'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + branch: 'branchValue', + product: 'productValue', + }; + const client = + new completionserviceModule.v2alpha.CompletionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.productPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.productPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('productPath', () => { + const result = client.productPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'branchValue', + 'productValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.productPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProductName', () => { + const result = client.matchProjectFromProductName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromProductName', () => { + const result = client.matchLocationFromProductName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromProductName', () => { + const result = client.matchCatalogFromProductName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBranchFromProductName', () => { + const result = client.matchBranchFromProductName(fakePath); + assert.strictEqual(result, 'branchValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchProductFromProductName', () => { + const result = client.matchProductFromProductName(fakePath); + assert.strictEqual(result, 'productValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchCatalogFromServingConfigName', () => { - const result = client.matchCatalogFromServingConfigName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.servingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('retailProject', () => { + const fakePath = '/rendered/path/retailProject'; + const expectedParameters = { + project: 'projectValue', + }; + const client = + new completionserviceModule.v2alpha.CompletionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.retailProjectPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.retailProjectPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('retailProjectPath', () => { + const result = client.retailProjectPath('projectValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.retailProjectPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromRetailProjectName', () => { + const result = client.matchProjectFromRetailProjectName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.retailProjectPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchServingConfigFromServingConfigName', () => { - const result = client.matchServingConfigFromServingConfigName(fakePath); - assert.strictEqual(result, "servingConfigValue"); - assert((client.pathTemplates.servingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('servingConfig', () => { + const fakePath = '/rendered/path/servingConfig'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + serving_config: 'servingConfigValue', + }; + const client = + new completionserviceModule.v2alpha.CompletionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.servingConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.servingConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('servingConfigPath', () => { + const result = client.servingConfigPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'servingConfigValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.servingConfigPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromServingConfigName', () => { + const result = client.matchProjectFromServingConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.servingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromServingConfigName', () => { + const result = client.matchLocationFromServingConfigName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.servingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromServingConfigName', () => { + const result = client.matchCatalogFromServingConfigName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.servingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServingConfigFromServingConfigName', () => { + const result = client.matchServingConfigFromServingConfigName(fakePath); + assert.strictEqual(result, 'servingConfigValue'); + assert( + (client.pathTemplates.servingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/test/gapic_control_service_v2alpha.ts.baseline b/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/test/gapic_control_service_v2alpha.ts.baseline index f25a690821f2..32e3ba378bf9 100644 --- a/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/test/gapic_control_service_v2alpha.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/test/gapic_control_service_v2alpha.ts.baseline @@ -20,16 +20,16 @@ import * as protos from '../../protos/protos.js'; import assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as controlserviceModule from '../src/index.js'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; -import {protobuf} from 'google-gax'; +import { protobuf } from 'google-gax'; import fs from 'fs'; import path from 'path'; -import {fileURLToPath} from 'url'; +import { fileURLToPath } from 'url'; // @ts-ignore const dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -37,1478 +37,1957 @@ const dirname = path.dirname(fileURLToPath(import.meta.url)); // to fill in default values for request objects const root = protobuf.Root.fromJSON( JSON.parse( - fs.readFileSync(path.join(dirname, '..', '..', 'protos/protos.json'), 'utf8') - )) + fs.readFileSync( + path.join(dirname, '..', '..', 'protos/protos.json'), + 'utf8', + ), + ), +); // eslint-disable-next-line @typescript-eslint/no-unused-vars function getTypeDefaultValue(typeName: string, fields: string[]) { - let type = root.lookupType(typeName) as protobuf.Type; - for (const field of fields.slice(0, -1)) { - type = type?.fields[field]?.resolvedType as protobuf.Type; - } - return type?.fields[fields[fields.length - 1]]?.defaultValue ?? null; + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type?.fields[field]?.resolvedType as protobuf.Type; + } + return type?.fields[fields[fields.length - 1]]?.defaultValue ?? null; } function generateSampleMessage(instance: T) { - const filledObject = (instance.constructor as typeof protobuf.Message) - .toObject(instance as protobuf.Message, {defaults: true}); - return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, { defaults: true }); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; } function stubSimpleCall(response?: ResponseType, error?: Error) { - return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); } -function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { - return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +function stubSimpleCallWithCallback( + response?: ResponseType, + error?: Error, +) { + return error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); } -function stubPageStreamingCall(responses?: ResponseType[], error?: Error) { - const pagingStub = sinon.stub(); - if (responses) { - for (let i = 0; i < responses.length; ++i) { - pagingStub.onCall(i).callsArgWith(2, null, responses[i]); - } +function stubPageStreamingCall( + responses?: ResponseType[], + error?: Error, +) { + const pagingStub = sinon.stub(); + if (responses) { + for (let i = 0; i < responses.length; ++i) { + pagingStub.onCall(i).callsArgWith(2, null, responses[i]); } - const transformStub = error ? sinon.stub().callsArgWith(2, error) : pagingStub; - const mockStream = new PassThrough({ - objectMode: true, - transform: transformStub, - }); - // trigger as many responses as needed - if (responses) { - for (let i = 0; i < responses.length; ++i) { - setImmediate(() => { mockStream.write({}); }); - } - setImmediate(() => { mockStream.end(); }); - } else { - setImmediate(() => { mockStream.write({}); }); - setImmediate(() => { mockStream.end(); }); + } + const transformStub = error + ? sinon.stub().callsArgWith(2, error) + : pagingStub; + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + // trigger as many responses as needed + if (responses) { + for (let i = 0; i < responses.length; ++i) { + setImmediate(() => { + mockStream.write({}); + }); } - return sinon.stub().returns(mockStream); + setImmediate(() => { + mockStream.end(); + }); + } else { + setImmediate(() => { + mockStream.write({}); + }); + setImmediate(() => { + mockStream.end(); + }); + } + return sinon.stub().returns(mockStream); } -function stubAsyncIterationCall(responses?: ResponseType[], error?: Error) { - let counter = 0; - const asyncIterable = { - [Symbol.asyncIterator]() { - return { - async next() { - if (error) { - return Promise.reject(error); - } - if (counter >= responses!.length) { - return Promise.resolve({done: true, value: undefined}); - } - return Promise.resolve({done: false, value: responses![counter++]}); - } - }; - } - }; - return sinon.stub().returns(asyncIterable); +function stubAsyncIterationCall( + responses?: ResponseType[], + error?: Error, +) { + let counter = 0; + const asyncIterable = { + [Symbol.asyncIterator]() { + return { + async next() { + if (error) { + return Promise.reject(error); + } + if (counter >= responses!.length) { + return Promise.resolve({ done: true, value: undefined }); + } + return Promise.resolve({ done: false, value: responses![counter++] }); + }, + }; + }, + }; + return sinon.stub().returns(asyncIterable); } describe('v2alpha.ControlServiceClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new controlserviceModule.v2alpha.ControlServiceClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'retail.googleapis.com'); - }); - - it('has universeDomain', () => { - const client = new controlserviceModule.v2alpha.ControlServiceClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); - - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - it('throws DeprecationWarning if static servicePath is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const servicePath = controlserviceModule.v2alpha.ControlServiceClient.servicePath; - assert.strictEqual(servicePath, 'retail.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = controlserviceModule.v2alpha.ControlServiceClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'retail.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new controlserviceModule.v2alpha.ControlServiceClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'retail.example.com'); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new controlserviceModule.v2alpha.ControlServiceClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'retail.googleapis.com'); + }); - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new controlserviceModule.v2alpha.ControlServiceClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'retail.example.com'); - }); + it('has universeDomain', () => { + const client = new controlserviceModule.v2alpha.ControlServiceClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - if (typeof process === 'object' && 'env' in process) { - describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { - it('sets apiEndpoint from environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new controlserviceModule.v2alpha.ControlServiceClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'retail.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - - it('value configured in code has priority over environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new controlserviceModule.v2alpha.ControlServiceClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'retail.configured.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { new controlserviceModule.v2alpha.ControlServiceClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = + controlserviceModule.v2alpha.ControlServiceClient.servicePath; + assert.strictEqual(servicePath, 'retail.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + controlserviceModule.v2alpha.ControlServiceClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'retail.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = new controlserviceModule.v2alpha.ControlServiceClient({ + universeDomain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'retail.example.com'); + }); - it('has port', () => { - const port = controlserviceModule.v2alpha.ControlServiceClient.port; - assert(port); - assert(typeof port === 'number'); - }); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = new controlserviceModule.v2alpha.ControlServiceClient({ + universe_domain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'retail.example.com'); + }); - it('should create a client with no option', () => { - const client = new controlserviceModule.v2alpha.ControlServiceClient(); - assert(client); + if (typeof process === 'object' && 'env' in process) { + describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { + it('sets apiEndpoint from environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = + new controlserviceModule.v2alpha.ControlServiceClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'retail.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - it('should create a client with gRPC fallback', () => { - const client = new controlserviceModule.v2alpha.ControlServiceClient({ - fallback: true, - }); - assert(client); + it('value configured in code has priority over environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new controlserviceModule.v2alpha.ControlServiceClient({ + universeDomain: 'configured.example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'retail.configured.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - - it('has initialize method and supports deferred initialization', async () => { - const client = new controlserviceModule.v2alpha.ControlServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.controlServiceStub, undefined); - await client.initialize(); - assert(client.controlServiceStub); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new controlserviceModule.v2alpha.ControlServiceClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); + }); - it('has close method for the initialized client', done => { - const client = new controlserviceModule.v2alpha.ControlServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.controlServiceStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('has port', () => { + const port = controlserviceModule.v2alpha.ControlServiceClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('has close method for the non-initialized client', done => { - const client = new controlserviceModule.v2alpha.ControlServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.controlServiceStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('should create a client with no option', () => { + const client = new controlserviceModule.v2alpha.ControlServiceClient(); + assert(client); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new controlserviceModule.v2alpha.ControlServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); - }); + it('should create a client with gRPC fallback', () => { + const client = new controlserviceModule.v2alpha.ControlServiceClient({ + fallback: true, + }); + assert(client); + }); - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new controlserviceModule.v2alpha.ControlServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId((err?: Error|null, projectId?: string|null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } - }); - }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); - }); + it('has initialize method and supports deferred initialization', async () => { + const client = new controlserviceModule.v2alpha.ControlServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.controlServiceStub, undefined); + await client.initialize(); + assert(client.controlServiceStub); }); - describe('createControl', () => { - it('invokes createControl without error', async () => { - const client = new controlserviceModule.v2alpha.ControlServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.CreateControlRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.CreateControlRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.Control() - ); - client.innerApiCalls.createControl = stubSimpleCall(expectedResponse); - const [response] = await client.createControl(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createControl as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createControl as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('has close method for the initialized client', (done) => { + const client = new controlserviceModule.v2alpha.ControlServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.controlServiceStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes createControl without error using callback', async () => { - const client = new controlserviceModule.v2alpha.ControlServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.CreateControlRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.CreateControlRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.Control() - ); - client.innerApiCalls.createControl = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createControl( - request, - (err?: Error|null, result?: protos.google.cloud.retail.v2alpha.IControl|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createControl as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createControl as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('has close method for the non-initialized client', (done) => { + const client = new controlserviceModule.v2alpha.ControlServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.controlServiceStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes createControl with error', async () => { - const client = new controlserviceModule.v2alpha.ControlServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.CreateControlRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.CreateControlRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createControl = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createControl(request), expectedError); - const actualRequest = (client.innerApiCalls.createControl as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createControl as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new controlserviceModule.v2alpha.ControlServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + }); - it('invokes createControl with closed client', async () => { - const client = new controlserviceModule.v2alpha.ControlServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.CreateControlRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.CreateControlRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createControl(request), expectedError); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new controlserviceModule.v2alpha.ControlServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + }); + + describe('createControl', () => { + it('invokes createControl without error', async () => { + const client = new controlserviceModule.v2alpha.ControlServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.CreateControlRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.CreateControlRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.Control(), + ); + client.innerApiCalls.createControl = stubSimpleCall(expectedResponse); + const [response] = await client.createControl(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createControl as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createControl as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('deleteControl', () => { - it('invokes deleteControl without error', async () => { - const client = new controlserviceModule.v2alpha.ControlServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.DeleteControlRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.DeleteControlRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteControl = stubSimpleCall(expectedResponse); - const [response] = await client.deleteControl(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteControl as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteControl as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createControl without error using callback', async () => { + const client = new controlserviceModule.v2alpha.ControlServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.CreateControlRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.CreateControlRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.Control(), + ); + client.innerApiCalls.createControl = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createControl( + request, + ( + err?: Error | null, + result?: protos.google.cloud.retail.v2alpha.IControl | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createControl as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createControl as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteControl without error using callback', async () => { - const client = new controlserviceModule.v2alpha.ControlServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.DeleteControlRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.DeleteControlRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteControl = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteControl( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteControl as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteControl as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createControl with error', async () => { + const client = new controlserviceModule.v2alpha.ControlServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.CreateControlRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.CreateControlRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createControl = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.createControl(request), expectedError); + const actualRequest = ( + client.innerApiCalls.createControl as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createControl as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteControl with error', async () => { - const client = new controlserviceModule.v2alpha.ControlServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.DeleteControlRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.DeleteControlRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteControl = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteControl(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteControl as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteControl as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createControl with closed client', async () => { + const client = new controlserviceModule.v2alpha.ControlServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.CreateControlRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.CreateControlRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.createControl(request), expectedError); + }); + }); + + describe('deleteControl', () => { + it('invokes deleteControl without error', async () => { + const client = new controlserviceModule.v2alpha.ControlServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.DeleteControlRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.DeleteControlRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteControl = stubSimpleCall(expectedResponse); + const [response] = await client.deleteControl(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteControl as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteControl as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteControl with closed client', async () => { - const client = new controlserviceModule.v2alpha.ControlServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.DeleteControlRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.DeleteControlRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteControl(request), expectedError); - }); + it('invokes deleteControl without error using callback', async () => { + const client = new controlserviceModule.v2alpha.ControlServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.DeleteControlRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.DeleteControlRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteControl = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteControl( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteControl as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteControl as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('updateControl', () => { - it('invokes updateControl without error', async () => { - const client = new controlserviceModule.v2alpha.ControlServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.UpdateControlRequest() - ); - request.control ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.UpdateControlRequest', ['control', 'name']); - request.control.name = defaultValue1; - const expectedHeaderRequestParams = `control.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.Control() - ); - client.innerApiCalls.updateControl = stubSimpleCall(expectedResponse); - const [response] = await client.updateControl(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateControl as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateControl as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteControl with error', async () => { + const client = new controlserviceModule.v2alpha.ControlServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.DeleteControlRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.DeleteControlRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteControl = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.deleteControl(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteControl as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteControl as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateControl without error using callback', async () => { - const client = new controlserviceModule.v2alpha.ControlServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.UpdateControlRequest() - ); - request.control ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.UpdateControlRequest', ['control', 'name']); - request.control.name = defaultValue1; - const expectedHeaderRequestParams = `control.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.Control() - ); - client.innerApiCalls.updateControl = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateControl( - request, - (err?: Error|null, result?: protos.google.cloud.retail.v2alpha.IControl|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateControl as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateControl as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteControl with closed client', async () => { + const client = new controlserviceModule.v2alpha.ControlServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.DeleteControlRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.DeleteControlRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.deleteControl(request), expectedError); + }); + }); + + describe('updateControl', () => { + it('invokes updateControl without error', async () => { + const client = new controlserviceModule.v2alpha.ControlServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.UpdateControlRequest(), + ); + request.control ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.UpdateControlRequest', + ['control', 'name'], + ); + request.control.name = defaultValue1; + const expectedHeaderRequestParams = `control.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.Control(), + ); + client.innerApiCalls.updateControl = stubSimpleCall(expectedResponse); + const [response] = await client.updateControl(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateControl as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateControl as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateControl with error', async () => { - const client = new controlserviceModule.v2alpha.ControlServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.UpdateControlRequest() - ); - request.control ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.UpdateControlRequest', ['control', 'name']); - request.control.name = defaultValue1; - const expectedHeaderRequestParams = `control.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateControl = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateControl(request), expectedError); - const actualRequest = (client.innerApiCalls.updateControl as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateControl as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateControl without error using callback', async () => { + const client = new controlserviceModule.v2alpha.ControlServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.UpdateControlRequest(), + ); + request.control ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.UpdateControlRequest', + ['control', 'name'], + ); + request.control.name = defaultValue1; + const expectedHeaderRequestParams = `control.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.Control(), + ); + client.innerApiCalls.updateControl = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateControl( + request, + ( + err?: Error | null, + result?: protos.google.cloud.retail.v2alpha.IControl | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateControl as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateControl as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateControl with closed client', async () => { - const client = new controlserviceModule.v2alpha.ControlServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.UpdateControlRequest() - ); - request.control ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.UpdateControlRequest', ['control', 'name']); - request.control.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateControl(request), expectedError); - }); + it('invokes updateControl with error', async () => { + const client = new controlserviceModule.v2alpha.ControlServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.UpdateControlRequest(), + ); + request.control ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.UpdateControlRequest', + ['control', 'name'], + ); + request.control.name = defaultValue1; + const expectedHeaderRequestParams = `control.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateControl = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.updateControl(request), expectedError); + const actualRequest = ( + client.innerApiCalls.updateControl as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateControl as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('getControl', () => { - it('invokes getControl without error', async () => { - const client = new controlserviceModule.v2alpha.ControlServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.GetControlRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.GetControlRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.Control() - ); - client.innerApiCalls.getControl = stubSimpleCall(expectedResponse); - const [response] = await client.getControl(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getControl as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getControl as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateControl with closed client', async () => { + const client = new controlserviceModule.v2alpha.ControlServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.UpdateControlRequest(), + ); + request.control ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.UpdateControlRequest', + ['control', 'name'], + ); + request.control.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.updateControl(request), expectedError); + }); + }); + + describe('getControl', () => { + it('invokes getControl without error', async () => { + const client = new controlserviceModule.v2alpha.ControlServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.GetControlRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.GetControlRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.Control(), + ); + client.innerApiCalls.getControl = stubSimpleCall(expectedResponse); + const [response] = await client.getControl(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getControl as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getControl as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getControl without error using callback', async () => { - const client = new controlserviceModule.v2alpha.ControlServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.GetControlRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.GetControlRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.Control() - ); - client.innerApiCalls.getControl = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getControl( - request, - (err?: Error|null, result?: protos.google.cloud.retail.v2alpha.IControl|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getControl as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getControl as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getControl without error using callback', async () => { + const client = new controlserviceModule.v2alpha.ControlServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.GetControlRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.GetControlRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.Control(), + ); + client.innerApiCalls.getControl = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getControl( + request, + ( + err?: Error | null, + result?: protos.google.cloud.retail.v2alpha.IControl | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getControl as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getControl as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getControl with error', async () => { - const client = new controlserviceModule.v2alpha.ControlServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.GetControlRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.GetControlRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getControl = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getControl(request), expectedError); - const actualRequest = (client.innerApiCalls.getControl as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getControl as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getControl with error', async () => { + const client = new controlserviceModule.v2alpha.ControlServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.GetControlRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.GetControlRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getControl = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getControl(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getControl as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getControl as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getControl with closed client', async () => { - const client = new controlserviceModule.v2alpha.ControlServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.GetControlRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.GetControlRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getControl(request), expectedError); - }); + it('invokes getControl with closed client', async () => { + const client = new controlserviceModule.v2alpha.ControlServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.GetControlRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.GetControlRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getControl(request), expectedError); + }); + }); + + describe('listControls', () => { + it('invokes listControls without error', async () => { + const client = new controlserviceModule.v2alpha.ControlServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ListControlsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ListControlsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.retail.v2alpha.Control()), + generateSampleMessage(new protos.google.cloud.retail.v2alpha.Control()), + generateSampleMessage(new protos.google.cloud.retail.v2alpha.Control()), + ]; + client.innerApiCalls.listControls = stubSimpleCall(expectedResponse); + const [response] = await client.listControls(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listControls as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listControls as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('listControls', () => { - it('invokes listControls without error', async () => { - const client = new controlserviceModule.v2alpha.ControlServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ListControlsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ListControlsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.retail.v2alpha.Control()), - generateSampleMessage(new protos.google.cloud.retail.v2alpha.Control()), - generateSampleMessage(new protos.google.cloud.retail.v2alpha.Control()), - ]; - client.innerApiCalls.listControls = stubSimpleCall(expectedResponse); - const [response] = await client.listControls(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listControls as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listControls as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listControls without error using callback', async () => { + const client = new controlserviceModule.v2alpha.ControlServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ListControlsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ListControlsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.retail.v2alpha.Control()), + generateSampleMessage(new protos.google.cloud.retail.v2alpha.Control()), + generateSampleMessage(new protos.google.cloud.retail.v2alpha.Control()), + ]; + client.innerApiCalls.listControls = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listControls( + request, + ( + err?: Error | null, + result?: protos.google.cloud.retail.v2alpha.IControl[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listControls as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listControls as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listControls without error using callback', async () => { - const client = new controlserviceModule.v2alpha.ControlServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ListControlsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ListControlsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.retail.v2alpha.Control()), - generateSampleMessage(new protos.google.cloud.retail.v2alpha.Control()), - generateSampleMessage(new protos.google.cloud.retail.v2alpha.Control()), - ]; - client.innerApiCalls.listControls = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listControls( - request, - (err?: Error|null, result?: protos.google.cloud.retail.v2alpha.IControl[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listControls as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listControls as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listControls with error', async () => { + const client = new controlserviceModule.v2alpha.ControlServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ListControlsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ListControlsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listControls = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listControls(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listControls as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listControls as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listControls with error', async () => { - const client = new controlserviceModule.v2alpha.ControlServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ListControlsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ListControlsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listControls = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listControls(request), expectedError); - const actualRequest = (client.innerApiCalls.listControls as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listControls as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes listControlsStream without error', async () => { + const client = new controlserviceModule.v2alpha.ControlServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ListControlsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ListControlsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.retail.v2alpha.Control()), + generateSampleMessage(new protos.google.cloud.retail.v2alpha.Control()), + generateSampleMessage(new protos.google.cloud.retail.v2alpha.Control()), + ]; + client.descriptors.page.listControls.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listControlsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.cloud.retail.v2alpha.Control[] = []; + stream.on( + 'data', + (response: protos.google.cloud.retail.v2alpha.Control) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); }); - - it('invokes listControlsStream without error', async () => { - const client = new controlserviceModule.v2alpha.ControlServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ListControlsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ListControlsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.retail.v2alpha.Control()), - generateSampleMessage(new protos.google.cloud.retail.v2alpha.Control()), - generateSampleMessage(new protos.google.cloud.retail.v2alpha.Control()), - ]; - client.descriptors.page.listControls.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listControlsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.cloud.retail.v2alpha.Control[] = []; - stream.on('data', (response: protos.google.cloud.retail.v2alpha.Control) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.listControls.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listControls, request)); - assert( - (client.descriptors.page.listControls.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); + stream.on('error', (err: Error) => { + reject(err); }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listControls.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listControls, request), + ); + assert( + (client.descriptors.page.listControls.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('invokes listControlsStream with error', async () => { - const client = new controlserviceModule.v2alpha.ControlServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ListControlsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ListControlsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listControls.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listControlsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.cloud.retail.v2alpha.Control[] = []; - stream.on('data', (response: protos.google.cloud.retail.v2alpha.Control) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listControls.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listControls, request)); - assert( - (client.descriptors.page.listControls.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); + it('invokes listControlsStream with error', async () => { + const client = new controlserviceModule.v2alpha.ControlServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ListControlsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ListControlsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listControls.createStream = stubPageStreamingCall( + undefined, + expectedError, + ); + const stream = client.listControlsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.cloud.retail.v2alpha.Control[] = []; + stream.on( + 'data', + (response: protos.google.cloud.retail.v2alpha.Control) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); }); - - it('uses async iteration with listControls without error', async () => { - const client = new controlserviceModule.v2alpha.ControlServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ListControlsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ListControlsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.retail.v2alpha.Control()), - generateSampleMessage(new protos.google.cloud.retail.v2alpha.Control()), - generateSampleMessage(new protos.google.cloud.retail.v2alpha.Control()), - ]; - client.descriptors.page.listControls.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.cloud.retail.v2alpha.IControl[] = []; - const iterable = client.listControlsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listControls.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listControls.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); + stream.on('error', (err: Error) => { + reject(err); }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listControls.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listControls, request), + ); + assert( + (client.descriptors.page.listControls.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('uses async iteration with listControls with error', async () => { - const client = new controlserviceModule.v2alpha.ControlServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ListControlsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ListControlsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listControls.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listControlsAsync(request); - await assert.rejects(async () => { - const responses: protos.google.cloud.retail.v2alpha.IControl[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listControls.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listControls.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listControls without error', async () => { + const client = new controlserviceModule.v2alpha.ControlServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ListControlsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ListControlsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.retail.v2alpha.Control()), + generateSampleMessage(new protos.google.cloud.retail.v2alpha.Control()), + generateSampleMessage(new protos.google.cloud.retail.v2alpha.Control()), + ]; + client.descriptors.page.listControls.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.cloud.retail.v2alpha.IControl[] = []; + const iterable = client.listControlsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listControls.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listControls.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); }); - describe('Path templates', () => { - - describe('alertConfig', () => { - const fakePath = "/rendered/path/alertConfig"; - const expectedParameters = { - project: "projectValue", - }; - const client = new controlserviceModule.v2alpha.ControlServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.alertConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.alertConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('alertConfigPath', () => { - const result = client.alertConfigPath("projectValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.alertConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromAlertConfigName', () => { - const result = client.matchProjectFromAlertConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.alertConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('uses async iteration with listControls with error', async () => { + const client = new controlserviceModule.v2alpha.ControlServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ListControlsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ListControlsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listControls.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listControlsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.cloud.retail.v2alpha.IControl[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listControls.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listControls.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + }); + + describe('Path templates', () => { + describe('alertConfig', () => { + const fakePath = '/rendered/path/alertConfig'; + const expectedParameters = { + project: 'projectValue', + }; + const client = new controlserviceModule.v2alpha.ControlServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.alertConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.alertConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('alertConfigPath', () => { + const result = client.alertConfigPath('projectValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.alertConfigPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromAlertConfigName', () => { + const result = client.matchProjectFromAlertConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.alertConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('attributesConfig', () => { - const fakePath = "/rendered/path/attributesConfig"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - }; - const client = new controlserviceModule.v2alpha.ControlServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.attributesConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.attributesConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('attributesConfigPath', () => { - const result = client.attributesConfigPath("projectValue", "locationValue", "catalogValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.attributesConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromAttributesConfigName', () => { - const result = client.matchProjectFromAttributesConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromAttributesConfigName', () => { - const result = client.matchLocationFromAttributesConfigName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromAttributesConfigName', () => { - const result = client.matchCatalogFromAttributesConfigName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('attributesConfig', () => { + const fakePath = '/rendered/path/attributesConfig'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + }; + const client = new controlserviceModule.v2alpha.ControlServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.attributesConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.attributesConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('attributesConfigPath', () => { + const result = client.attributesConfigPath( + 'projectValue', + 'locationValue', + 'catalogValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.attributesConfigPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromAttributesConfigName', () => { + const result = client.matchProjectFromAttributesConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromAttributesConfigName', () => { + const result = client.matchLocationFromAttributesConfigName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromAttributesConfigName', () => { + const result = client.matchCatalogFromAttributesConfigName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('branch', () => { - const fakePath = "/rendered/path/branch"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - branch: "branchValue", - }; - const client = new controlserviceModule.v2alpha.ControlServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.branchPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.branchPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('branchPath', () => { - const result = client.branchPath("projectValue", "locationValue", "catalogValue", "branchValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.branchPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromBranchName', () => { - const result = client.matchProjectFromBranchName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.branchPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromBranchName', () => { - const result = client.matchLocationFromBranchName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.branchPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromBranchName', () => { - const result = client.matchCatalogFromBranchName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.branchPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBranchFromBranchName', () => { - const result = client.matchBranchFromBranchName(fakePath); - assert.strictEqual(result, "branchValue"); - assert((client.pathTemplates.branchPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('branch', () => { + const fakePath = '/rendered/path/branch'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + branch: 'branchValue', + }; + const client = new controlserviceModule.v2alpha.ControlServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.branchPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.branchPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('branchPath', () => { + const result = client.branchPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'branchValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.branchPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromBranchName', () => { + const result = client.matchProjectFromBranchName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.branchPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromBranchName', () => { + const result = client.matchLocationFromBranchName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.branchPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromBranchName', () => { + const result = client.matchCatalogFromBranchName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.branchPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBranchFromBranchName', () => { + const result = client.matchBranchFromBranchName(fakePath); + assert.strictEqual(result, 'branchValue'); + assert( + (client.pathTemplates.branchPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('catalog', () => { - const fakePath = "/rendered/path/catalog"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - }; - const client = new controlserviceModule.v2alpha.ControlServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.catalogPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.catalogPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('catalogPath', () => { - const result = client.catalogPath("projectValue", "locationValue", "catalogValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.catalogPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromCatalogName', () => { - const result = client.matchProjectFromCatalogName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.catalogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromCatalogName', () => { - const result = client.matchLocationFromCatalogName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.catalogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromCatalogName', () => { - const result = client.matchCatalogFromCatalogName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.catalogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('catalog', () => { + const fakePath = '/rendered/path/catalog'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + }; + const client = new controlserviceModule.v2alpha.ControlServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.catalogPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.catalogPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('catalogPath', () => { + const result = client.catalogPath( + 'projectValue', + 'locationValue', + 'catalogValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.catalogPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromCatalogName', () => { + const result = client.matchProjectFromCatalogName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.catalogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromCatalogName', () => { + const result = client.matchLocationFromCatalogName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.catalogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromCatalogName', () => { + const result = client.matchCatalogFromCatalogName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.catalogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('completionConfig', () => { - const fakePath = "/rendered/path/completionConfig"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - }; - const client = new controlserviceModule.v2alpha.ControlServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.completionConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.completionConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('completionConfigPath', () => { - const result = client.completionConfigPath("projectValue", "locationValue", "catalogValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.completionConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromCompletionConfigName', () => { - const result = client.matchProjectFromCompletionConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.completionConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromCompletionConfigName', () => { - const result = client.matchLocationFromCompletionConfigName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.completionConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromCompletionConfigName', () => { - const result = client.matchCatalogFromCompletionConfigName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.completionConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('completionConfig', () => { + const fakePath = '/rendered/path/completionConfig'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + }; + const client = new controlserviceModule.v2alpha.ControlServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.completionConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.completionConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('completionConfigPath', () => { + const result = client.completionConfigPath( + 'projectValue', + 'locationValue', + 'catalogValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.completionConfigPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromCompletionConfigName', () => { + const result = client.matchProjectFromCompletionConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.completionConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromCompletionConfigName', () => { + const result = client.matchLocationFromCompletionConfigName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.completionConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromCompletionConfigName', () => { + const result = client.matchCatalogFromCompletionConfigName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.completionConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('control', () => { - const fakePath = "/rendered/path/control"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - control: "controlValue", - }; - const client = new controlserviceModule.v2alpha.ControlServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.controlPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.controlPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('controlPath', () => { - const result = client.controlPath("projectValue", "locationValue", "catalogValue", "controlValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.controlPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromControlName', () => { - const result = client.matchProjectFromControlName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.controlPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromControlName', () => { - const result = client.matchLocationFromControlName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.controlPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromControlName', () => { - const result = client.matchCatalogFromControlName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.controlPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchControlFromControlName', () => { - const result = client.matchControlFromControlName(fakePath); - assert.strictEqual(result, "controlValue"); - assert((client.pathTemplates.controlPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('control', () => { + const fakePath = '/rendered/path/control'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + control: 'controlValue', + }; + const client = new controlserviceModule.v2alpha.ControlServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.controlPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.controlPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('controlPath', () => { + const result = client.controlPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'controlValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.controlPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromControlName', () => { + const result = client.matchProjectFromControlName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.controlPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromControlName', () => { + const result = client.matchLocationFromControlName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.controlPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromControlName', () => { + const result = client.matchCatalogFromControlName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.controlPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchControlFromControlName', () => { + const result = client.matchControlFromControlName(fakePath); + assert.strictEqual(result, 'controlValue'); + assert( + (client.pathTemplates.controlPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('loggingConfig', () => { - const fakePath = "/rendered/path/loggingConfig"; - const expectedParameters = { - project: "projectValue", - }; - const client = new controlserviceModule.v2alpha.ControlServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.loggingConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.loggingConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('loggingConfigPath', () => { - const result = client.loggingConfigPath("projectValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.loggingConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromLoggingConfigName', () => { - const result = client.matchProjectFromLoggingConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.loggingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('loggingConfig', () => { + const fakePath = '/rendered/path/loggingConfig'; + const expectedParameters = { + project: 'projectValue', + }; + const client = new controlserviceModule.v2alpha.ControlServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.loggingConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.loggingConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('loggingConfigPath', () => { + const result = client.loggingConfigPath('projectValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.loggingConfigPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromLoggingConfigName', () => { + const result = client.matchProjectFromLoggingConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.loggingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('merchantCenterAccountLink', () => { - const fakePath = "/rendered/path/merchantCenterAccountLink"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - merchant_center_account_link: "merchantCenterAccountLinkValue", - }; - const client = new controlserviceModule.v2alpha.ControlServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.merchantCenterAccountLinkPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.merchantCenterAccountLinkPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('merchantCenterAccountLinkPath', () => { - const result = client.merchantCenterAccountLinkPath("projectValue", "locationValue", "catalogValue", "merchantCenterAccountLinkValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromMerchantCenterAccountLinkName', () => { - const result = client.matchProjectFromMerchantCenterAccountLinkName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromMerchantCenterAccountLinkName', () => { - const result = client.matchLocationFromMerchantCenterAccountLinkName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromMerchantCenterAccountLinkName', () => { - const result = client.matchCatalogFromMerchantCenterAccountLinkName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName', () => { - const result = client.matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName(fakePath); - assert.strictEqual(result, "merchantCenterAccountLinkValue"); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('merchantCenterAccountLink', () => { + const fakePath = '/rendered/path/merchantCenterAccountLink'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + merchant_center_account_link: 'merchantCenterAccountLinkValue', + }; + const client = new controlserviceModule.v2alpha.ControlServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.merchantCenterAccountLinkPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.merchantCenterAccountLinkPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('merchantCenterAccountLinkPath', () => { + const result = client.merchantCenterAccountLinkPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'merchantCenterAccountLinkValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromMerchantCenterAccountLinkName', () => { + const result = + client.matchProjectFromMerchantCenterAccountLinkName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromMerchantCenterAccountLinkName', () => { + const result = + client.matchLocationFromMerchantCenterAccountLinkName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromMerchantCenterAccountLinkName', () => { + const result = + client.matchCatalogFromMerchantCenterAccountLinkName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName', () => { + const result = + client.matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName( + fakePath, + ); + assert.strictEqual(result, 'merchantCenterAccountLinkValue'); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('model', () => { - const fakePath = "/rendered/path/model"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - model: "modelValue", - }; - const client = new controlserviceModule.v2alpha.ControlServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.modelPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.modelPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('modelPath', () => { - const result = client.modelPath("projectValue", "locationValue", "catalogValue", "modelValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.modelPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromModelName', () => { - const result = client.matchProjectFromModelName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromModelName', () => { - const result = client.matchLocationFromModelName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromModelName', () => { - const result = client.matchCatalogFromModelName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchModelFromModelName', () => { - const result = client.matchModelFromModelName(fakePath); - assert.strictEqual(result, "modelValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('model', () => { + const fakePath = '/rendered/path/model'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + model: 'modelValue', + }; + const client = new controlserviceModule.v2alpha.ControlServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.modelPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.modelPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('modelPath', () => { + const result = client.modelPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'modelValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.modelPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromModelName', () => { + const result = client.matchProjectFromModelName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromModelName', () => { + const result = client.matchLocationFromModelName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromModelName', () => { + const result = client.matchCatalogFromModelName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchModelFromModelName', () => { + const result = client.matchModelFromModelName(fakePath); + assert.strictEqual(result, 'modelValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('product', () => { - const fakePath = "/rendered/path/product"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - branch: "branchValue", - product: "productValue", - }; - const client = new controlserviceModule.v2alpha.ControlServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.productPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.productPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('productPath', () => { - const result = client.productPath("projectValue", "locationValue", "catalogValue", "branchValue", "productValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.productPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProductName', () => { - const result = client.matchProjectFromProductName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromProductName', () => { - const result = client.matchLocationFromProductName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromProductName', () => { - const result = client.matchCatalogFromProductName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBranchFromProductName', () => { - const result = client.matchBranchFromProductName(fakePath); - assert.strictEqual(result, "branchValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchProductFromProductName', () => { - const result = client.matchProductFromProductName(fakePath); - assert.strictEqual(result, "productValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('product', () => { + const fakePath = '/rendered/path/product'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + branch: 'branchValue', + product: 'productValue', + }; + const client = new controlserviceModule.v2alpha.ControlServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.productPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.productPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('productPath', () => { + const result = client.productPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'branchValue', + 'productValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.productPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProductName', () => { + const result = client.matchProjectFromProductName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromProductName', () => { + const result = client.matchLocationFromProductName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromProductName', () => { + const result = client.matchCatalogFromProductName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBranchFromProductName', () => { + const result = client.matchBranchFromProductName(fakePath); + assert.strictEqual(result, 'branchValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchProductFromProductName', () => { + const result = client.matchProductFromProductName(fakePath); + assert.strictEqual(result, 'productValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('retailProject', () => { - const fakePath = "/rendered/path/retailProject"; - const expectedParameters = { - project: "projectValue", - }; - const client = new controlserviceModule.v2alpha.ControlServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.retailProjectPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.retailProjectPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('retailProjectPath', () => { - const result = client.retailProjectPath("projectValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.retailProjectPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromRetailProjectName', () => { - const result = client.matchProjectFromRetailProjectName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.retailProjectPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('retailProject', () => { + const fakePath = '/rendered/path/retailProject'; + const expectedParameters = { + project: 'projectValue', + }; + const client = new controlserviceModule.v2alpha.ControlServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.retailProjectPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.retailProjectPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('retailProjectPath', () => { + const result = client.retailProjectPath('projectValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.retailProjectPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromRetailProjectName', () => { + const result = client.matchProjectFromRetailProjectName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.retailProjectPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('servingConfig', () => { - const fakePath = "/rendered/path/servingConfig"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - serving_config: "servingConfigValue", - }; - const client = new controlserviceModule.v2alpha.ControlServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.servingConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.servingConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('servingConfigPath', () => { - const result = client.servingConfigPath("projectValue", "locationValue", "catalogValue", "servingConfigValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.servingConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromServingConfigName', () => { - const result = client.matchProjectFromServingConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.servingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromServingConfigName', () => { - const result = client.matchLocationFromServingConfigName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.servingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromServingConfigName', () => { - const result = client.matchCatalogFromServingConfigName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.servingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServingConfigFromServingConfigName', () => { - const result = client.matchServingConfigFromServingConfigName(fakePath); - assert.strictEqual(result, "servingConfigValue"); - assert((client.pathTemplates.servingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('servingConfig', () => { + const fakePath = '/rendered/path/servingConfig'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + serving_config: 'servingConfigValue', + }; + const client = new controlserviceModule.v2alpha.ControlServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.servingConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.servingConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('servingConfigPath', () => { + const result = client.servingConfigPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'servingConfigValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.servingConfigPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromServingConfigName', () => { + const result = client.matchProjectFromServingConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.servingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromServingConfigName', () => { + const result = client.matchLocationFromServingConfigName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.servingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromServingConfigName', () => { + const result = client.matchCatalogFromServingConfigName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.servingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServingConfigFromServingConfigName', () => { + const result = client.matchServingConfigFromServingConfigName(fakePath); + assert.strictEqual(result, 'servingConfigValue'); + assert( + (client.pathTemplates.servingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/test/gapic_conversational_search_service_v2alpha.ts.baseline b/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/test/gapic_conversational_search_service_v2alpha.ts.baseline index 2c252f952650..102367c0818d 100644 --- a/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/test/gapic_conversational_search_service_v2alpha.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/test/gapic_conversational_search_service_v2alpha.ts.baseline @@ -20,16 +20,16 @@ import * as protos from '../../protos/protos.js'; import assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as conversationalsearchserviceModule from '../src/index.js'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; -import {protobuf} from 'google-gax'; +import { protobuf } from 'google-gax'; import fs from 'fs'; import path from 'path'; -import {fileURLToPath} from 'url'; +import { fileURLToPath } from 'url'; // @ts-ignore const dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -37,895 +37,1327 @@ const dirname = path.dirname(fileURLToPath(import.meta.url)); // to fill in default values for request objects const root = protobuf.Root.fromJSON( JSON.parse( - fs.readFileSync(path.join(dirname, '..', '..', 'protos/protos.json'), 'utf8') - )) + fs.readFileSync( + path.join(dirname, '..', '..', 'protos/protos.json'), + 'utf8', + ), + ), +); // eslint-disable-next-line @typescript-eslint/no-unused-vars function getTypeDefaultValue(typeName: string, fields: string[]) { - let type = root.lookupType(typeName) as protobuf.Type; - for (const field of fields.slice(0, -1)) { - type = type?.fields[field]?.resolvedType as protobuf.Type; - } - return type?.fields[fields[fields.length - 1]]?.defaultValue ?? null; + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type?.fields[field]?.resolvedType as protobuf.Type; + } + return type?.fields[fields[fields.length - 1]]?.defaultValue ?? null; } function generateSampleMessage(instance: T) { - const filledObject = (instance.constructor as typeof protobuf.Message) - .toObject(instance as protobuf.Message, {defaults: true}); - return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, { defaults: true }); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; } -function stubServerStreamingCall(response?: ResponseType, error?: Error) { - const transformStub = error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); - const mockStream = new PassThrough({ - objectMode: true, - transform: transformStub, - }); - // write something to the stream to trigger transformStub and send the response back to the client - setImmediate(() => { mockStream.write({}); }); - setImmediate(() => { mockStream.end(); }); - return sinon.stub().returns(mockStream); +function stubServerStreamingCall( + response?: ResponseType, + error?: Error, +) { + const transformStub = error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + // write something to the stream to trigger transformStub and send the response back to the client + setImmediate(() => { + mockStream.write({}); + }); + setImmediate(() => { + mockStream.end(); + }); + return sinon.stub().returns(mockStream); } describe('v2alpha.ConversationalSearchServiceClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'retail.googleapis.com'); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = + new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'retail.googleapis.com'); + }); - it('has universeDomain', () => { - const client = new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); + it('has universeDomain', () => { + const client = + new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - it('throws DeprecationWarning if static servicePath is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const servicePath = conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient.servicePath; - assert.strictEqual(servicePath, 'retail.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'retail.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'retail.example.com'); - }); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = + conversationalsearchserviceModule.v2alpha + .ConversationalSearchServiceClient.servicePath; + assert.strictEqual(servicePath, 'retail.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + conversationalsearchserviceModule.v2alpha + .ConversationalSearchServiceClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'retail.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = + new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient( + { universeDomain: 'example.com' }, + ); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'retail.example.com'); + }); - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'retail.example.com'); - }); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = + new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient( + { universe_domain: 'example.com' }, + ); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'retail.example.com'); + }); - if (typeof process === 'object' && 'env' in process) { - describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { - it('sets apiEndpoint from environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'retail.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - - it('value configured in code has priority over environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'retail.configured.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); + if (typeof process === 'object' && 'env' in process) { + describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { + it('sets apiEndpoint from environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = + new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'retail.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - it('has port', () => { - const port = conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient.port; - assert(port); - assert(typeof port === 'number'); + it('value configured in code has priority over environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = + new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient( + { universeDomain: 'configured.example.com' }, + ); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'retail.configured.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient( + { universe_domain: 'example.com', universeDomain: 'example.net' }, + ); + }); + }); - it('should create a client with no option', () => { - const client = new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient(); - assert(client); - }); + it('has port', () => { + const port = + conversationalsearchserviceModule.v2alpha + .ConversationalSearchServiceClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('should create a client with gRPC fallback', () => { - const client = new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient({ - fallback: true, - }); - assert(client); - }); + it('should create a client with no option', () => { + const client = + new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient(); + assert(client); + }); - it('has initialize method and supports deferred initialization', async () => { - const client = new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.conversationalSearchServiceStub, undefined); - await client.initialize(); - assert(client.conversationalSearchServiceStub); - }); + it('should create a client with gRPC fallback', () => { + const client = + new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient( + { + fallback: true, + }, + ); + assert(client); + }); - it('has close method for the initialized client', done => { - const client = new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.conversationalSearchServiceStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('has initialize method and supports deferred initialization', async () => { + const client = + new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + assert.strictEqual(client.conversationalSearchServiceStub, undefined); + await client.initialize(); + assert(client.conversationalSearchServiceStub); + }); - it('has close method for the non-initialized client', done => { - const client = new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.conversationalSearchServiceStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); + it('has close method for the initialized client', (done) => { + const client = + new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + client.initialize().catch((err) => { + throw err; + }); + assert(client.conversationalSearchServiceStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + it('has close method for the non-initialized client', (done) => { + const client = + new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + assert.strictEqual(client.conversationalSearchServiceStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId((err?: Error|null, projectId?: string|null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } - }); - }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); - }); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = + new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); }); - describe('conversationalSearch', () => { - it('invokes conversationalSearch without error', async () => { - const client = new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ConversationalSearchRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ConversationalSearchRequest', ['placement']); - request.placement = defaultValue1; - const expectedHeaderRequestParams = `placement=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ConversationalSearchResponse() - ); - client.innerApiCalls.conversationalSearch = stubServerStreamingCall(expectedResponse); - const stream = client.conversationalSearch(request); - const promise = new Promise((resolve, reject) => { - stream.on('data', (response: protos.google.cloud.retail.v2alpha.ConversationalSearchResponse) => { - resolve(response); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.conversationalSearch as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.conversationalSearch as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = + new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } }); - - it('invokes conversationalSearch without error and gaxServerStreamingRetries enabled', async () => { - const client = new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ConversationalSearchRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ConversationalSearchRequest', ['placement']); - request.placement = defaultValue1; - const expectedHeaderRequestParams = `placement=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ConversationalSearchResponse() - ); - client.innerApiCalls.conversationalSearch = stubServerStreamingCall(expectedResponse); - const stream = client.conversationalSearch(request); - const promise = new Promise((resolve, reject) => { - stream.on('data', (response: protos.google.cloud.retail.v2alpha.ConversationalSearchResponse) => { - resolve(response); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.conversationalSearch as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.conversationalSearch as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + }); + + describe('conversationalSearch', () => { + it('invokes conversationalSearch without error', async () => { + const client = + new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ConversationalSearchRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ConversationalSearchRequest', + ['placement'], + ); + request.placement = defaultValue1; + const expectedHeaderRequestParams = `placement=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ConversationalSearchResponse(), + ); + client.innerApiCalls.conversationalSearch = + stubServerStreamingCall(expectedResponse); + const stream = client.conversationalSearch(request); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + ( + response: protos.google.cloud.retail.v2alpha.ConversationalSearchResponse, + ) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.conversationalSearch as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.conversationalSearch as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes conversationalSearch with error', async () => { - const client = new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ConversationalSearchRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ConversationalSearchRequest', ['placement']); - request.placement = defaultValue1; - const expectedHeaderRequestParams = `placement=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.conversationalSearch = stubServerStreamingCall(undefined, expectedError); - const stream = client.conversationalSearch(request); - const promise = new Promise((resolve, reject) => { - stream.on('data', (response: protos.google.cloud.retail.v2alpha.ConversationalSearchResponse) => { - resolve(response); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - const actualRequest = (client.innerApiCalls.conversationalSearch as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.conversationalSearch as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes conversationalSearch without error and gaxServerStreamingRetries enabled', async () => { + const client = + new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ConversationalSearchRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ConversationalSearchRequest', + ['placement'], + ); + request.placement = defaultValue1; + const expectedHeaderRequestParams = `placement=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ConversationalSearchResponse(), + ); + client.innerApiCalls.conversationalSearch = + stubServerStreamingCall(expectedResponse); + const stream = client.conversationalSearch(request); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + ( + response: protos.google.cloud.retail.v2alpha.ConversationalSearchResponse, + ) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.conversationalSearch as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.conversationalSearch as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes conversationalSearch with closed client', async () => { - const client = new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ConversationalSearchRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ConversationalSearchRequest', ['placement']); - request.placement = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - const stream = client.conversationalSearch(request, {retryRequestOptions: {noResponseRetries: 0}}); - const promise = new Promise((resolve, reject) => { - stream.on('data', (response: protos.google.cloud.retail.v2alpha.ConversationalSearchResponse) => { - resolve(response); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - }); - it('should create a client with gaxServerStreamingRetries enabled', () => { - const client = new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient({ - gaxServerStreamingRetries: true, - }); - assert(client); + it('invokes conversationalSearch with error', async () => { + const client = + new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ConversationalSearchRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ConversationalSearchRequest', + ['placement'], + ); + request.placement = defaultValue1; + const expectedHeaderRequestParams = `placement=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.conversationalSearch = stubServerStreamingCall( + undefined, + expectedError, + ); + const stream = client.conversationalSearch(request); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + ( + response: protos.google.cloud.retail.v2alpha.ConversationalSearchResponse, + ) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); }); + }); + await assert.rejects(promise, expectedError); + const actualRequest = ( + client.innerApiCalls.conversationalSearch as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.conversationalSearch as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('Path templates', () => { - - describe('alertConfig', () => { - const fakePath = "/rendered/path/alertConfig"; - const expectedParameters = { - project: "projectValue", - }; - const client = new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.alertConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.alertConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('alertConfigPath', () => { - const result = client.alertConfigPath("projectValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.alertConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromAlertConfigName', () => { - const result = client.matchProjectFromAlertConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.alertConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('invokes conversationalSearch with closed client', async () => { + const client = + new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ConversationalSearchRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ConversationalSearchRequest', + ['placement'], + ); + request.placement = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + const stream = client.conversationalSearch(request, { + retryRequestOptions: { noResponseRetries: 0 }, + }); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + ( + response: protos.google.cloud.retail.v2alpha.ConversationalSearchResponse, + ) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); }); + }); + await assert.rejects(promise, expectedError); + }); + it('should create a client with gaxServerStreamingRetries enabled', () => { + const client = + new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient( + { + gaxServerStreamingRetries: true, + }, + ); + assert(client); + }); + }); + + describe('Path templates', () => { + describe('alertConfig', () => { + const fakePath = '/rendered/path/alertConfig'; + const expectedParameters = { + project: 'projectValue', + }; + const client = + new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.alertConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.alertConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('alertConfigPath', () => { + const result = client.alertConfigPath('projectValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.alertConfigPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromAlertConfigName', () => { + const result = client.matchProjectFromAlertConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.alertConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('attributesConfig', () => { - const fakePath = "/rendered/path/attributesConfig"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - }; - const client = new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.attributesConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.attributesConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('attributesConfigPath', () => { - const result = client.attributesConfigPath("projectValue", "locationValue", "catalogValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.attributesConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromAttributesConfigName', () => { - const result = client.matchProjectFromAttributesConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromAttributesConfigName', () => { - const result = client.matchLocationFromAttributesConfigName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromAttributesConfigName', () => { - const result = client.matchCatalogFromAttributesConfigName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('attributesConfig', () => { + const fakePath = '/rendered/path/attributesConfig'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + }; + const client = + new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.attributesConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.attributesConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('attributesConfigPath', () => { + const result = client.attributesConfigPath( + 'projectValue', + 'locationValue', + 'catalogValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.attributesConfigPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromAttributesConfigName', () => { + const result = client.matchProjectFromAttributesConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromAttributesConfigName', () => { + const result = client.matchLocationFromAttributesConfigName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromAttributesConfigName', () => { + const result = client.matchCatalogFromAttributesConfigName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('branch', () => { - const fakePath = "/rendered/path/branch"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - branch: "branchValue", - }; - const client = new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.branchPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.branchPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('branchPath', () => { - const result = client.branchPath("projectValue", "locationValue", "catalogValue", "branchValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.branchPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromBranchName', () => { - const result = client.matchProjectFromBranchName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.branchPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromBranchName', () => { - const result = client.matchLocationFromBranchName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.branchPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromBranchName', () => { - const result = client.matchCatalogFromBranchName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.branchPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBranchFromBranchName', () => { - const result = client.matchBranchFromBranchName(fakePath); - assert.strictEqual(result, "branchValue"); - assert((client.pathTemplates.branchPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('branch', () => { + const fakePath = '/rendered/path/branch'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + branch: 'branchValue', + }; + const client = + new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.branchPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.branchPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('branchPath', () => { + const result = client.branchPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'branchValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.branchPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromBranchName', () => { + const result = client.matchProjectFromBranchName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.branchPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromBranchName', () => { + const result = client.matchLocationFromBranchName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.branchPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromBranchName', () => { + const result = client.matchCatalogFromBranchName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.branchPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBranchFromBranchName', () => { + const result = client.matchBranchFromBranchName(fakePath); + assert.strictEqual(result, 'branchValue'); + assert( + (client.pathTemplates.branchPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('catalog', () => { - const fakePath = "/rendered/path/catalog"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - }; - const client = new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.catalogPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.catalogPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('catalogPath', () => { - const result = client.catalogPath("projectValue", "locationValue", "catalogValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.catalogPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromCatalogName', () => { - const result = client.matchProjectFromCatalogName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.catalogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromCatalogName', () => { - const result = client.matchLocationFromCatalogName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.catalogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromCatalogName', () => { - const result = client.matchCatalogFromCatalogName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.catalogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('catalog', () => { + const fakePath = '/rendered/path/catalog'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + }; + const client = + new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.catalogPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.catalogPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('catalogPath', () => { + const result = client.catalogPath( + 'projectValue', + 'locationValue', + 'catalogValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.catalogPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromCatalogName', () => { + const result = client.matchProjectFromCatalogName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.catalogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromCatalogName', () => { + const result = client.matchLocationFromCatalogName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.catalogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromCatalogName', () => { + const result = client.matchCatalogFromCatalogName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.catalogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('completionConfig', () => { - const fakePath = "/rendered/path/completionConfig"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - }; - const client = new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.completionConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.completionConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('completionConfigPath', () => { - const result = client.completionConfigPath("projectValue", "locationValue", "catalogValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.completionConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromCompletionConfigName', () => { - const result = client.matchProjectFromCompletionConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.completionConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromCompletionConfigName', () => { - const result = client.matchLocationFromCompletionConfigName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.completionConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromCompletionConfigName', () => { - const result = client.matchCatalogFromCompletionConfigName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.completionConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('completionConfig', () => { + const fakePath = '/rendered/path/completionConfig'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + }; + const client = + new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.completionConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.completionConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('completionConfigPath', () => { + const result = client.completionConfigPath( + 'projectValue', + 'locationValue', + 'catalogValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.completionConfigPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromCompletionConfigName', () => { + const result = client.matchProjectFromCompletionConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.completionConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromCompletionConfigName', () => { + const result = client.matchLocationFromCompletionConfigName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.completionConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromCompletionConfigName', () => { + const result = client.matchCatalogFromCompletionConfigName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.completionConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('control', () => { - const fakePath = "/rendered/path/control"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - control: "controlValue", - }; - const client = new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.controlPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.controlPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('controlPath', () => { - const result = client.controlPath("projectValue", "locationValue", "catalogValue", "controlValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.controlPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromControlName', () => { - const result = client.matchProjectFromControlName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.controlPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromControlName', () => { - const result = client.matchLocationFromControlName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.controlPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromControlName', () => { - const result = client.matchCatalogFromControlName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.controlPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchControlFromControlName', () => { - const result = client.matchControlFromControlName(fakePath); - assert.strictEqual(result, "controlValue"); - assert((client.pathTemplates.controlPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('control', () => { + const fakePath = '/rendered/path/control'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + control: 'controlValue', + }; + const client = + new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.controlPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.controlPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('controlPath', () => { + const result = client.controlPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'controlValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.controlPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromControlName', () => { + const result = client.matchProjectFromControlName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.controlPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromControlName', () => { + const result = client.matchLocationFromControlName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.controlPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromControlName', () => { + const result = client.matchCatalogFromControlName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.controlPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchControlFromControlName', () => { + const result = client.matchControlFromControlName(fakePath); + assert.strictEqual(result, 'controlValue'); + assert( + (client.pathTemplates.controlPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('loggingConfig', () => { - const fakePath = "/rendered/path/loggingConfig"; - const expectedParameters = { - project: "projectValue", - }; - const client = new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.loggingConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.loggingConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('loggingConfigPath', () => { - const result = client.loggingConfigPath("projectValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.loggingConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromLoggingConfigName', () => { - const result = client.matchProjectFromLoggingConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.loggingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('loggingConfig', () => { + const fakePath = '/rendered/path/loggingConfig'; + const expectedParameters = { + project: 'projectValue', + }; + const client = + new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.loggingConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.loggingConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('loggingConfigPath', () => { + const result = client.loggingConfigPath('projectValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.loggingConfigPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromLoggingConfigName', () => { + const result = client.matchProjectFromLoggingConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.loggingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('merchantCenterAccountLink', () => { - const fakePath = "/rendered/path/merchantCenterAccountLink"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - merchant_center_account_link: "merchantCenterAccountLinkValue", - }; - const client = new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.merchantCenterAccountLinkPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.merchantCenterAccountLinkPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('merchantCenterAccountLinkPath', () => { - const result = client.merchantCenterAccountLinkPath("projectValue", "locationValue", "catalogValue", "merchantCenterAccountLinkValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromMerchantCenterAccountLinkName', () => { - const result = client.matchProjectFromMerchantCenterAccountLinkName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromMerchantCenterAccountLinkName', () => { - const result = client.matchLocationFromMerchantCenterAccountLinkName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromMerchantCenterAccountLinkName', () => { - const result = client.matchCatalogFromMerchantCenterAccountLinkName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName', () => { - const result = client.matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName(fakePath); - assert.strictEqual(result, "merchantCenterAccountLinkValue"); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('merchantCenterAccountLink', () => { + const fakePath = '/rendered/path/merchantCenterAccountLink'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + merchant_center_account_link: 'merchantCenterAccountLinkValue', + }; + const client = + new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.merchantCenterAccountLinkPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.merchantCenterAccountLinkPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('merchantCenterAccountLinkPath', () => { + const result = client.merchantCenterAccountLinkPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'merchantCenterAccountLinkValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromMerchantCenterAccountLinkName', () => { + const result = + client.matchProjectFromMerchantCenterAccountLinkName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromMerchantCenterAccountLinkName', () => { + const result = + client.matchLocationFromMerchantCenterAccountLinkName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromMerchantCenterAccountLinkName', () => { + const result = + client.matchCatalogFromMerchantCenterAccountLinkName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName', () => { + const result = + client.matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName( + fakePath, + ); + assert.strictEqual(result, 'merchantCenterAccountLinkValue'); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('model', () => { - const fakePath = "/rendered/path/model"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - model: "modelValue", - }; - const client = new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.modelPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.modelPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('modelPath', () => { - const result = client.modelPath("projectValue", "locationValue", "catalogValue", "modelValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.modelPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromModelName', () => { - const result = client.matchProjectFromModelName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromModelName', () => { - const result = client.matchLocationFromModelName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromModelName', () => { - const result = client.matchCatalogFromModelName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchModelFromModelName', () => { - const result = client.matchModelFromModelName(fakePath); - assert.strictEqual(result, "modelValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('model', () => { + const fakePath = '/rendered/path/model'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + model: 'modelValue', + }; + const client = + new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.modelPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.modelPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('modelPath', () => { + const result = client.modelPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'modelValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.modelPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromModelName', () => { + const result = client.matchProjectFromModelName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromModelName', () => { + const result = client.matchLocationFromModelName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromModelName', () => { + const result = client.matchCatalogFromModelName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchModelFromModelName', () => { + const result = client.matchModelFromModelName(fakePath); + assert.strictEqual(result, 'modelValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('product', () => { - const fakePath = "/rendered/path/product"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - branch: "branchValue", - product: "productValue", - }; - const client = new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.productPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.productPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('productPath', () => { - const result = client.productPath("projectValue", "locationValue", "catalogValue", "branchValue", "productValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.productPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProductName', () => { - const result = client.matchProjectFromProductName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromProductName', () => { - const result = client.matchLocationFromProductName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromProductName', () => { - const result = client.matchCatalogFromProductName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBranchFromProductName', () => { - const result = client.matchBranchFromProductName(fakePath); - assert.strictEqual(result, "branchValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchProductFromProductName', () => { - const result = client.matchProductFromProductName(fakePath); - assert.strictEqual(result, "productValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('product', () => { + const fakePath = '/rendered/path/product'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + branch: 'branchValue', + product: 'productValue', + }; + const client = + new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.productPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.productPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('productPath', () => { + const result = client.productPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'branchValue', + 'productValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.productPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProductName', () => { + const result = client.matchProjectFromProductName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromProductName', () => { + const result = client.matchLocationFromProductName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromProductName', () => { + const result = client.matchCatalogFromProductName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBranchFromProductName', () => { + const result = client.matchBranchFromProductName(fakePath); + assert.strictEqual(result, 'branchValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchProductFromProductName', () => { + const result = client.matchProductFromProductName(fakePath); + assert.strictEqual(result, 'productValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('retailProject', () => { - const fakePath = "/rendered/path/retailProject"; - const expectedParameters = { - project: "projectValue", - }; - const client = new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.retailProjectPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.retailProjectPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('retailProjectPath', () => { - const result = client.retailProjectPath("projectValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.retailProjectPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromRetailProjectName', () => { - const result = client.matchProjectFromRetailProjectName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.retailProjectPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('retailProject', () => { + const fakePath = '/rendered/path/retailProject'; + const expectedParameters = { + project: 'projectValue', + }; + const client = + new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.retailProjectPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.retailProjectPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('retailProjectPath', () => { + const result = client.retailProjectPath('projectValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.retailProjectPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromRetailProjectName', () => { + const result = client.matchProjectFromRetailProjectName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.retailProjectPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('servingConfig', () => { - const fakePath = "/rendered/path/servingConfig"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - serving_config: "servingConfigValue", - }; - const client = new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.servingConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.servingConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('servingConfigPath', () => { - const result = client.servingConfigPath("projectValue", "locationValue", "catalogValue", "servingConfigValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.servingConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromServingConfigName', () => { - const result = client.matchProjectFromServingConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.servingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromServingConfigName', () => { - const result = client.matchLocationFromServingConfigName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.servingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromServingConfigName', () => { - const result = client.matchCatalogFromServingConfigName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.servingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServingConfigFromServingConfigName', () => { - const result = client.matchServingConfigFromServingConfigName(fakePath); - assert.strictEqual(result, "servingConfigValue"); - assert((client.pathTemplates.servingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('servingConfig', () => { + const fakePath = '/rendered/path/servingConfig'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + serving_config: 'servingConfigValue', + }; + const client = + new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.servingConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.servingConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('servingConfigPath', () => { + const result = client.servingConfigPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'servingConfigValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.servingConfigPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromServingConfigName', () => { + const result = client.matchProjectFromServingConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.servingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromServingConfigName', () => { + const result = client.matchLocationFromServingConfigName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.servingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromServingConfigName', () => { + const result = client.matchCatalogFromServingConfigName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.servingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServingConfigFromServingConfigName', () => { + const result = client.matchServingConfigFromServingConfigName(fakePath); + assert.strictEqual(result, 'servingConfigValue'); + assert( + (client.pathTemplates.servingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/test/gapic_generative_question_service_v2alpha.ts.baseline b/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/test/gapic_generative_question_service_v2alpha.ts.baseline index 57b41985a21f..891b57d3c43e 100644 --- a/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/test/gapic_generative_question_service_v2alpha.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/test/gapic_generative_question_service_v2alpha.ts.baseline @@ -20,14 +20,14 @@ import * as protos from '../../protos/protos.js'; import assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as generativequestionserviceModule from '../src/index.js'; -import {protobuf} from 'google-gax'; +import { protobuf } from 'google-gax'; import fs from 'fs'; import path from 'path'; -import {fileURLToPath} from 'url'; +import { fileURLToPath } from 'url'; // @ts-ignore const dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -35,1300 +35,1886 @@ const dirname = path.dirname(fileURLToPath(import.meta.url)); // to fill in default values for request objects const root = protobuf.Root.fromJSON( JSON.parse( - fs.readFileSync(path.join(dirname, '..', '..', 'protos/protos.json'), 'utf8') - )) + fs.readFileSync( + path.join(dirname, '..', '..', 'protos/protos.json'), + 'utf8', + ), + ), +); // eslint-disable-next-line @typescript-eslint/no-unused-vars function getTypeDefaultValue(typeName: string, fields: string[]) { - let type = root.lookupType(typeName) as protobuf.Type; - for (const field of fields.slice(0, -1)) { - type = type?.fields[field]?.resolvedType as protobuf.Type; - } - return type?.fields[fields[fields.length - 1]]?.defaultValue ?? null; + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type?.fields[field]?.resolvedType as protobuf.Type; + } + return type?.fields[fields[fields.length - 1]]?.defaultValue ?? null; } function generateSampleMessage(instance: T) { - const filledObject = (instance.constructor as typeof protobuf.Message) - .toObject(instance as protobuf.Message, {defaults: true}); - return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, { defaults: true }); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; } function stubSimpleCall(response?: ResponseType, error?: Error) { - return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); } -function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { - return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +function stubSimpleCallWithCallback( + response?: ResponseType, + error?: Error, +) { + return error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); } describe('v2alpha.GenerativeQuestionServiceClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'retail.googleapis.com'); - }); - - it('has universeDomain', () => { - const client = new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); - - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - it('throws DeprecationWarning if static servicePath is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const servicePath = generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient.servicePath; - assert.strictEqual(servicePath, 'retail.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'retail.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'retail.example.com'); - }); - - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'retail.example.com'); - }); - - if (typeof process === 'object' && 'env' in process) { - describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { - it('sets apiEndpoint from environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'retail.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - - it('value configured in code has priority over environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'retail.configured.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); - - it('has port', () => { - const port = generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient.port; - assert(port); - assert(typeof port === 'number'); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = + new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'retail.googleapis.com'); + }); - it('should create a client with no option', () => { - const client = new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient(); - assert(client); - }); + it('has universeDomain', () => { + const client = + new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - it('should create a client with gRPC fallback', () => { - const client = new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient({ - fallback: true, - }); - assert(client); - }); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = + generativequestionserviceModule.v2alpha + .GenerativeQuestionServiceClient.servicePath; + assert.strictEqual(servicePath, 'retail.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + generativequestionserviceModule.v2alpha + .GenerativeQuestionServiceClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'retail.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = + new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient( + { universeDomain: 'example.com' }, + ); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'retail.example.com'); + }); - it('has initialize method and supports deferred initialization', async () => { - const client = new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.generativeQuestionServiceStub, undefined); - await client.initialize(); - assert(client.generativeQuestionServiceStub); - }); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = + new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient( + { universe_domain: 'example.com' }, + ); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'retail.example.com'); + }); - it('has close method for the initialized client', done => { - const client = new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.generativeQuestionServiceStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); + if (typeof process === 'object' && 'env' in process) { + describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { + it('sets apiEndpoint from environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = + new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'retail.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - it('has close method for the non-initialized client', done => { - const client = new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.generativeQuestionServiceStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); + it('value configured in code has priority over environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = + new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient( + { universeDomain: 'configured.example.com' }, + ); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'retail.configured.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient( + { universe_domain: 'example.com', universeDomain: 'example.net' }, + ); + }); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); - }); + it('has port', () => { + const port = + generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient + .port; + assert(port); + assert(typeof port === 'number'); + }); - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId((err?: Error|null, projectId?: string|null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } - }); - }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); - }); + it('should create a client with no option', () => { + const client = + new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient(); + assert(client); }); - describe('updateGenerativeQuestionsFeatureConfig', () => { - it('invokes updateGenerativeQuestionsFeatureConfig without error', async () => { - const client = new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.UpdateGenerativeQuestionsFeatureConfigRequest() - ); - request.generativeQuestionsFeatureConfig ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.UpdateGenerativeQuestionsFeatureConfigRequest', ['generativeQuestionsFeatureConfig', 'catalog']); - request.generativeQuestionsFeatureConfig.catalog = defaultValue1; - const expectedHeaderRequestParams = `generative_questions_feature_config.catalog=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.GenerativeQuestionsFeatureConfig() - ); - client.innerApiCalls.updateGenerativeQuestionsFeatureConfig = stubSimpleCall(expectedResponse); - const [response] = await client.updateGenerativeQuestionsFeatureConfig(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateGenerativeQuestionsFeatureConfig as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateGenerativeQuestionsFeatureConfig as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('should create a client with gRPC fallback', () => { + const client = + new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient( + { + fallback: true, + }, + ); + assert(client); + }); - it('invokes updateGenerativeQuestionsFeatureConfig without error using callback', async () => { - const client = new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.UpdateGenerativeQuestionsFeatureConfigRequest() - ); - request.generativeQuestionsFeatureConfig ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.UpdateGenerativeQuestionsFeatureConfigRequest', ['generativeQuestionsFeatureConfig', 'catalog']); - request.generativeQuestionsFeatureConfig.catalog = defaultValue1; - const expectedHeaderRequestParams = `generative_questions_feature_config.catalog=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.GenerativeQuestionsFeatureConfig() - ); - client.innerApiCalls.updateGenerativeQuestionsFeatureConfig = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateGenerativeQuestionsFeatureConfig( - request, - (err?: Error|null, result?: protos.google.cloud.retail.v2alpha.IGenerativeQuestionsFeatureConfig|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateGenerativeQuestionsFeatureConfig as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateGenerativeQuestionsFeatureConfig as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has initialize method and supports deferred initialization', async () => { + const client = + new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + assert.strictEqual(client.generativeQuestionServiceStub, undefined); + await client.initialize(); + assert(client.generativeQuestionServiceStub); + }); - it('invokes updateGenerativeQuestionsFeatureConfig with error', async () => { - const client = new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.UpdateGenerativeQuestionsFeatureConfigRequest() - ); - request.generativeQuestionsFeatureConfig ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.UpdateGenerativeQuestionsFeatureConfigRequest', ['generativeQuestionsFeatureConfig', 'catalog']); - request.generativeQuestionsFeatureConfig.catalog = defaultValue1; - const expectedHeaderRequestParams = `generative_questions_feature_config.catalog=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateGenerativeQuestionsFeatureConfig = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateGenerativeQuestionsFeatureConfig(request), expectedError); - const actualRequest = (client.innerApiCalls.updateGenerativeQuestionsFeatureConfig as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateGenerativeQuestionsFeatureConfig as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('has close method for the initialized client', (done) => { + const client = + new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + client.initialize().catch((err) => { + throw err; + }); + assert(client.generativeQuestionServiceStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes updateGenerativeQuestionsFeatureConfig with closed client', async () => { - const client = new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.UpdateGenerativeQuestionsFeatureConfigRequest() - ); - request.generativeQuestionsFeatureConfig ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.UpdateGenerativeQuestionsFeatureConfigRequest', ['generativeQuestionsFeatureConfig', 'catalog']); - request.generativeQuestionsFeatureConfig.catalog = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateGenerativeQuestionsFeatureConfig(request), expectedError); + it('has close method for the non-initialized client', (done) => { + const client = + new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + assert.strictEqual(client.generativeQuestionServiceStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); }); - describe('getGenerativeQuestionsFeatureConfig', () => { - it('invokes getGenerativeQuestionsFeatureConfig without error', async () => { - const client = new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.GetGenerativeQuestionsFeatureConfigRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.GetGenerativeQuestionsFeatureConfigRequest', ['catalog']); - request.catalog = defaultValue1; - const expectedHeaderRequestParams = `catalog=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.GenerativeQuestionsFeatureConfig() - ); - client.innerApiCalls.getGenerativeQuestionsFeatureConfig = stubSimpleCall(expectedResponse); - const [response] = await client.getGenerativeQuestionsFeatureConfig(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getGenerativeQuestionsFeatureConfig as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getGenerativeQuestionsFeatureConfig as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = + new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + }); - it('invokes getGenerativeQuestionsFeatureConfig without error using callback', async () => { - const client = new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.GetGenerativeQuestionsFeatureConfigRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.GetGenerativeQuestionsFeatureConfigRequest', ['catalog']); - request.catalog = defaultValue1; - const expectedHeaderRequestParams = `catalog=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.GenerativeQuestionsFeatureConfig() - ); - client.innerApiCalls.getGenerativeQuestionsFeatureConfig = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getGenerativeQuestionsFeatureConfig( - request, - (err?: Error|null, result?: protos.google.cloud.retail.v2alpha.IGenerativeQuestionsFeatureConfig|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getGenerativeQuestionsFeatureConfig as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getGenerativeQuestionsFeatureConfig as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = + new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + }); + + describe('updateGenerativeQuestionsFeatureConfig', () => { + it('invokes updateGenerativeQuestionsFeatureConfig without error', async () => { + const client = + new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.UpdateGenerativeQuestionsFeatureConfigRequest(), + ); + request.generativeQuestionsFeatureConfig ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.UpdateGenerativeQuestionsFeatureConfigRequest', + ['generativeQuestionsFeatureConfig', 'catalog'], + ); + request.generativeQuestionsFeatureConfig.catalog = defaultValue1; + const expectedHeaderRequestParams = `generative_questions_feature_config.catalog=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.GenerativeQuestionsFeatureConfig(), + ); + client.innerApiCalls.updateGenerativeQuestionsFeatureConfig = + stubSimpleCall(expectedResponse); + const [response] = + await client.updateGenerativeQuestionsFeatureConfig(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateGenerativeQuestionsFeatureConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateGenerativeQuestionsFeatureConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getGenerativeQuestionsFeatureConfig with error', async () => { - const client = new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.GetGenerativeQuestionsFeatureConfigRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.GetGenerativeQuestionsFeatureConfigRequest', ['catalog']); - request.catalog = defaultValue1; - const expectedHeaderRequestParams = `catalog=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getGenerativeQuestionsFeatureConfig = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getGenerativeQuestionsFeatureConfig(request), expectedError); - const actualRequest = (client.innerApiCalls.getGenerativeQuestionsFeatureConfig as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getGenerativeQuestionsFeatureConfig as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateGenerativeQuestionsFeatureConfig without error using callback', async () => { + const client = + new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.UpdateGenerativeQuestionsFeatureConfigRequest(), + ); + request.generativeQuestionsFeatureConfig ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.UpdateGenerativeQuestionsFeatureConfigRequest', + ['generativeQuestionsFeatureConfig', 'catalog'], + ); + request.generativeQuestionsFeatureConfig.catalog = defaultValue1; + const expectedHeaderRequestParams = `generative_questions_feature_config.catalog=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.GenerativeQuestionsFeatureConfig(), + ); + client.innerApiCalls.updateGenerativeQuestionsFeatureConfig = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateGenerativeQuestionsFeatureConfig( + request, + ( + err?: Error | null, + result?: protos.google.cloud.retail.v2alpha.IGenerativeQuestionsFeatureConfig | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateGenerativeQuestionsFeatureConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateGenerativeQuestionsFeatureConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getGenerativeQuestionsFeatureConfig with closed client', async () => { - const client = new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.GetGenerativeQuestionsFeatureConfigRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.GetGenerativeQuestionsFeatureConfigRequest', ['catalog']); - request.catalog = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getGenerativeQuestionsFeatureConfig(request), expectedError); - }); + it('invokes updateGenerativeQuestionsFeatureConfig with error', async () => { + const client = + new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.UpdateGenerativeQuestionsFeatureConfigRequest(), + ); + request.generativeQuestionsFeatureConfig ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.UpdateGenerativeQuestionsFeatureConfigRequest', + ['generativeQuestionsFeatureConfig', 'catalog'], + ); + request.generativeQuestionsFeatureConfig.catalog = defaultValue1; + const expectedHeaderRequestParams = `generative_questions_feature_config.catalog=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateGenerativeQuestionsFeatureConfig = + stubSimpleCall(undefined, expectedError); + await assert.rejects( + client.updateGenerativeQuestionsFeatureConfig(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.updateGenerativeQuestionsFeatureConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateGenerativeQuestionsFeatureConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('listGenerativeQuestionConfigs', () => { - it('invokes listGenerativeQuestionConfigs without error', async () => { - const client = new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ListGenerativeQuestionConfigsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ListGenerativeQuestionConfigsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ListGenerativeQuestionConfigsResponse() - ); - client.innerApiCalls.listGenerativeQuestionConfigs = stubSimpleCall(expectedResponse); - const [response] = await client.listGenerativeQuestionConfigs(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listGenerativeQuestionConfigs as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listGenerativeQuestionConfigs as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateGenerativeQuestionsFeatureConfig with closed client', async () => { + const client = + new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.UpdateGenerativeQuestionsFeatureConfigRequest(), + ); + request.generativeQuestionsFeatureConfig ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.UpdateGenerativeQuestionsFeatureConfigRequest', + ['generativeQuestionsFeatureConfig', 'catalog'], + ); + request.generativeQuestionsFeatureConfig.catalog = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.updateGenerativeQuestionsFeatureConfig(request), + expectedError, + ); + }); + }); + + describe('getGenerativeQuestionsFeatureConfig', () => { + it('invokes getGenerativeQuestionsFeatureConfig without error', async () => { + const client = + new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.GetGenerativeQuestionsFeatureConfigRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.GetGenerativeQuestionsFeatureConfigRequest', + ['catalog'], + ); + request.catalog = defaultValue1; + const expectedHeaderRequestParams = `catalog=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.GenerativeQuestionsFeatureConfig(), + ); + client.innerApiCalls.getGenerativeQuestionsFeatureConfig = + stubSimpleCall(expectedResponse); + const [response] = + await client.getGenerativeQuestionsFeatureConfig(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getGenerativeQuestionsFeatureConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getGenerativeQuestionsFeatureConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listGenerativeQuestionConfigs without error using callback', async () => { - const client = new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ListGenerativeQuestionConfigsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ListGenerativeQuestionConfigsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ListGenerativeQuestionConfigsResponse() - ); - client.innerApiCalls.listGenerativeQuestionConfigs = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listGenerativeQuestionConfigs( - request, - (err?: Error|null, result?: protos.google.cloud.retail.v2alpha.IListGenerativeQuestionConfigsResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listGenerativeQuestionConfigs as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listGenerativeQuestionConfigs as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getGenerativeQuestionsFeatureConfig without error using callback', async () => { + const client = + new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.GetGenerativeQuestionsFeatureConfigRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.GetGenerativeQuestionsFeatureConfigRequest', + ['catalog'], + ); + request.catalog = defaultValue1; + const expectedHeaderRequestParams = `catalog=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.GenerativeQuestionsFeatureConfig(), + ); + client.innerApiCalls.getGenerativeQuestionsFeatureConfig = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getGenerativeQuestionsFeatureConfig( + request, + ( + err?: Error | null, + result?: protos.google.cloud.retail.v2alpha.IGenerativeQuestionsFeatureConfig | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getGenerativeQuestionsFeatureConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getGenerativeQuestionsFeatureConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listGenerativeQuestionConfigs with error', async () => { - const client = new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ListGenerativeQuestionConfigsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ListGenerativeQuestionConfigsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listGenerativeQuestionConfigs = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listGenerativeQuestionConfigs(request), expectedError); - const actualRequest = (client.innerApiCalls.listGenerativeQuestionConfigs as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listGenerativeQuestionConfigs as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getGenerativeQuestionsFeatureConfig with error', async () => { + const client = + new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.GetGenerativeQuestionsFeatureConfigRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.GetGenerativeQuestionsFeatureConfigRequest', + ['catalog'], + ); + request.catalog = defaultValue1; + const expectedHeaderRequestParams = `catalog=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getGenerativeQuestionsFeatureConfig = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.getGenerativeQuestionsFeatureConfig(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.getGenerativeQuestionsFeatureConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getGenerativeQuestionsFeatureConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listGenerativeQuestionConfigs with closed client', async () => { - const client = new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ListGenerativeQuestionConfigsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ListGenerativeQuestionConfigsRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.listGenerativeQuestionConfigs(request), expectedError); - }); + it('invokes getGenerativeQuestionsFeatureConfig with closed client', async () => { + const client = + new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.GetGenerativeQuestionsFeatureConfigRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.GetGenerativeQuestionsFeatureConfigRequest', + ['catalog'], + ); + request.catalog = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.getGenerativeQuestionsFeatureConfig(request), + expectedError, + ); + }); + }); + + describe('listGenerativeQuestionConfigs', () => { + it('invokes listGenerativeQuestionConfigs without error', async () => { + const client = + new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ListGenerativeQuestionConfigsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ListGenerativeQuestionConfigsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ListGenerativeQuestionConfigsResponse(), + ); + client.innerApiCalls.listGenerativeQuestionConfigs = + stubSimpleCall(expectedResponse); + const [response] = await client.listGenerativeQuestionConfigs(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listGenerativeQuestionConfigs as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listGenerativeQuestionConfigs as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('updateGenerativeQuestionConfig', () => { - it('invokes updateGenerativeQuestionConfig without error', async () => { - const client = new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.UpdateGenerativeQuestionConfigRequest() - ); - request.generativeQuestionConfig ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.UpdateGenerativeQuestionConfigRequest', ['generativeQuestionConfig', 'catalog']); - request.generativeQuestionConfig.catalog = defaultValue1; - const expectedHeaderRequestParams = `generative_question_config.catalog=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.GenerativeQuestionConfig() - ); - client.innerApiCalls.updateGenerativeQuestionConfig = stubSimpleCall(expectedResponse); - const [response] = await client.updateGenerativeQuestionConfig(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateGenerativeQuestionConfig as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateGenerativeQuestionConfig as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listGenerativeQuestionConfigs without error using callback', async () => { + const client = + new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ListGenerativeQuestionConfigsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ListGenerativeQuestionConfigsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ListGenerativeQuestionConfigsResponse(), + ); + client.innerApiCalls.listGenerativeQuestionConfigs = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listGenerativeQuestionConfigs( + request, + ( + err?: Error | null, + result?: protos.google.cloud.retail.v2alpha.IListGenerativeQuestionConfigsResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listGenerativeQuestionConfigs as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listGenerativeQuestionConfigs as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateGenerativeQuestionConfig without error using callback', async () => { - const client = new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.UpdateGenerativeQuestionConfigRequest() - ); - request.generativeQuestionConfig ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.UpdateGenerativeQuestionConfigRequest', ['generativeQuestionConfig', 'catalog']); - request.generativeQuestionConfig.catalog = defaultValue1; - const expectedHeaderRequestParams = `generative_question_config.catalog=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.GenerativeQuestionConfig() - ); - client.innerApiCalls.updateGenerativeQuestionConfig = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateGenerativeQuestionConfig( - request, - (err?: Error|null, result?: protos.google.cloud.retail.v2alpha.IGenerativeQuestionConfig|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateGenerativeQuestionConfig as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateGenerativeQuestionConfig as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listGenerativeQuestionConfigs with error', async () => { + const client = + new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ListGenerativeQuestionConfigsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ListGenerativeQuestionConfigsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listGenerativeQuestionConfigs = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.listGenerativeQuestionConfigs(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.listGenerativeQuestionConfigs as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listGenerativeQuestionConfigs as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateGenerativeQuestionConfig with error', async () => { - const client = new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.UpdateGenerativeQuestionConfigRequest() - ); - request.generativeQuestionConfig ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.UpdateGenerativeQuestionConfigRequest', ['generativeQuestionConfig', 'catalog']); - request.generativeQuestionConfig.catalog = defaultValue1; - const expectedHeaderRequestParams = `generative_question_config.catalog=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateGenerativeQuestionConfig = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateGenerativeQuestionConfig(request), expectedError); - const actualRequest = (client.innerApiCalls.updateGenerativeQuestionConfig as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateGenerativeQuestionConfig as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listGenerativeQuestionConfigs with closed client', async () => { + const client = + new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ListGenerativeQuestionConfigsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ListGenerativeQuestionConfigsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.listGenerativeQuestionConfigs(request), + expectedError, + ); + }); + }); + + describe('updateGenerativeQuestionConfig', () => { + it('invokes updateGenerativeQuestionConfig without error', async () => { + const client = + new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.UpdateGenerativeQuestionConfigRequest(), + ); + request.generativeQuestionConfig ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.UpdateGenerativeQuestionConfigRequest', + ['generativeQuestionConfig', 'catalog'], + ); + request.generativeQuestionConfig.catalog = defaultValue1; + const expectedHeaderRequestParams = `generative_question_config.catalog=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.GenerativeQuestionConfig(), + ); + client.innerApiCalls.updateGenerativeQuestionConfig = + stubSimpleCall(expectedResponse); + const [response] = await client.updateGenerativeQuestionConfig(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateGenerativeQuestionConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateGenerativeQuestionConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateGenerativeQuestionConfig with closed client', async () => { - const client = new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.UpdateGenerativeQuestionConfigRequest() - ); - request.generativeQuestionConfig ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.UpdateGenerativeQuestionConfigRequest', ['generativeQuestionConfig', 'catalog']); - request.generativeQuestionConfig.catalog = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateGenerativeQuestionConfig(request), expectedError); - }); + it('invokes updateGenerativeQuestionConfig without error using callback', async () => { + const client = + new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.UpdateGenerativeQuestionConfigRequest(), + ); + request.generativeQuestionConfig ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.UpdateGenerativeQuestionConfigRequest', + ['generativeQuestionConfig', 'catalog'], + ); + request.generativeQuestionConfig.catalog = defaultValue1; + const expectedHeaderRequestParams = `generative_question_config.catalog=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.GenerativeQuestionConfig(), + ); + client.innerApiCalls.updateGenerativeQuestionConfig = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateGenerativeQuestionConfig( + request, + ( + err?: Error | null, + result?: protos.google.cloud.retail.v2alpha.IGenerativeQuestionConfig | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateGenerativeQuestionConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateGenerativeQuestionConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('batchUpdateGenerativeQuestionConfigs', () => { - it('invokes batchUpdateGenerativeQuestionConfigs without error', async () => { - const client = new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.BatchUpdateGenerativeQuestionConfigsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.BatchUpdateGenerativeQuestionConfigsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.BatchUpdateGenerativeQuestionConfigsResponse() - ); - client.innerApiCalls.batchUpdateGenerativeQuestionConfigs = stubSimpleCall(expectedResponse); - const [response] = await client.batchUpdateGenerativeQuestionConfigs(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.batchUpdateGenerativeQuestionConfigs as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.batchUpdateGenerativeQuestionConfigs as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateGenerativeQuestionConfig with error', async () => { + const client = + new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.UpdateGenerativeQuestionConfigRequest(), + ); + request.generativeQuestionConfig ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.UpdateGenerativeQuestionConfigRequest', + ['generativeQuestionConfig', 'catalog'], + ); + request.generativeQuestionConfig.catalog = defaultValue1; + const expectedHeaderRequestParams = `generative_question_config.catalog=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateGenerativeQuestionConfig = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.updateGenerativeQuestionConfig(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.updateGenerativeQuestionConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateGenerativeQuestionConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes batchUpdateGenerativeQuestionConfigs without error using callback', async () => { - const client = new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.BatchUpdateGenerativeQuestionConfigsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.BatchUpdateGenerativeQuestionConfigsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.BatchUpdateGenerativeQuestionConfigsResponse() - ); - client.innerApiCalls.batchUpdateGenerativeQuestionConfigs = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.batchUpdateGenerativeQuestionConfigs( - request, - (err?: Error|null, result?: protos.google.cloud.retail.v2alpha.IBatchUpdateGenerativeQuestionConfigsResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.batchUpdateGenerativeQuestionConfigs as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.batchUpdateGenerativeQuestionConfigs as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateGenerativeQuestionConfig with closed client', async () => { + const client = + new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.UpdateGenerativeQuestionConfigRequest(), + ); + request.generativeQuestionConfig ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.UpdateGenerativeQuestionConfigRequest', + ['generativeQuestionConfig', 'catalog'], + ); + request.generativeQuestionConfig.catalog = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.updateGenerativeQuestionConfig(request), + expectedError, + ); + }); + }); + + describe('batchUpdateGenerativeQuestionConfigs', () => { + it('invokes batchUpdateGenerativeQuestionConfigs without error', async () => { + const client = + new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.BatchUpdateGenerativeQuestionConfigsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.BatchUpdateGenerativeQuestionConfigsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.BatchUpdateGenerativeQuestionConfigsResponse(), + ); + client.innerApiCalls.batchUpdateGenerativeQuestionConfigs = + stubSimpleCall(expectedResponse); + const [response] = + await client.batchUpdateGenerativeQuestionConfigs(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.batchUpdateGenerativeQuestionConfigs as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.batchUpdateGenerativeQuestionConfigs as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes batchUpdateGenerativeQuestionConfigs with error', async () => { - const client = new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.BatchUpdateGenerativeQuestionConfigsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.BatchUpdateGenerativeQuestionConfigsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.batchUpdateGenerativeQuestionConfigs = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.batchUpdateGenerativeQuestionConfigs(request), expectedError); - const actualRequest = (client.innerApiCalls.batchUpdateGenerativeQuestionConfigs as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.batchUpdateGenerativeQuestionConfigs as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes batchUpdateGenerativeQuestionConfigs without error using callback', async () => { + const client = + new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.BatchUpdateGenerativeQuestionConfigsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.BatchUpdateGenerativeQuestionConfigsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.BatchUpdateGenerativeQuestionConfigsResponse(), + ); + client.innerApiCalls.batchUpdateGenerativeQuestionConfigs = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.batchUpdateGenerativeQuestionConfigs( + request, + ( + err?: Error | null, + result?: protos.google.cloud.retail.v2alpha.IBatchUpdateGenerativeQuestionConfigsResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.batchUpdateGenerativeQuestionConfigs as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.batchUpdateGenerativeQuestionConfigs as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes batchUpdateGenerativeQuestionConfigs with closed client', async () => { - const client = new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.BatchUpdateGenerativeQuestionConfigsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.BatchUpdateGenerativeQuestionConfigsRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.batchUpdateGenerativeQuestionConfigs(request), expectedError); - }); + it('invokes batchUpdateGenerativeQuestionConfigs with error', async () => { + const client = + new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.BatchUpdateGenerativeQuestionConfigsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.BatchUpdateGenerativeQuestionConfigsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.batchUpdateGenerativeQuestionConfigs = + stubSimpleCall(undefined, expectedError); + await assert.rejects( + client.batchUpdateGenerativeQuestionConfigs(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.batchUpdateGenerativeQuestionConfigs as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.batchUpdateGenerativeQuestionConfigs as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('Path templates', () => { - - describe('alertConfig', () => { - const fakePath = "/rendered/path/alertConfig"; - const expectedParameters = { - project: "projectValue", - }; - const client = new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.alertConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.alertConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('alertConfigPath', () => { - const result = client.alertConfigPath("projectValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.alertConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromAlertConfigName', () => { - const result = client.matchProjectFromAlertConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.alertConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('invokes batchUpdateGenerativeQuestionConfigs with closed client', async () => { + const client = + new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.BatchUpdateGenerativeQuestionConfigsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.BatchUpdateGenerativeQuestionConfigsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.batchUpdateGenerativeQuestionConfigs(request), + expectedError, + ); + }); + }); + + describe('Path templates', () => { + describe('alertConfig', () => { + const fakePath = '/rendered/path/alertConfig'; + const expectedParameters = { + project: 'projectValue', + }; + const client = + new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.alertConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.alertConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('alertConfigPath', () => { + const result = client.alertConfigPath('projectValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.alertConfigPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromAlertConfigName', () => { + const result = client.matchProjectFromAlertConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.alertConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('attributesConfig', () => { - const fakePath = "/rendered/path/attributesConfig"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - }; - const client = new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.attributesConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.attributesConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('attributesConfigPath', () => { - const result = client.attributesConfigPath("projectValue", "locationValue", "catalogValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.attributesConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromAttributesConfigName', () => { - const result = client.matchProjectFromAttributesConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromAttributesConfigName', () => { - const result = client.matchLocationFromAttributesConfigName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromAttributesConfigName', () => { - const result = client.matchCatalogFromAttributesConfigName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('attributesConfig', () => { + const fakePath = '/rendered/path/attributesConfig'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + }; + const client = + new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.attributesConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.attributesConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('attributesConfigPath', () => { + const result = client.attributesConfigPath( + 'projectValue', + 'locationValue', + 'catalogValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.attributesConfigPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromAttributesConfigName', () => { + const result = client.matchProjectFromAttributesConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromAttributesConfigName', () => { + const result = client.matchLocationFromAttributesConfigName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromAttributesConfigName', () => { + const result = client.matchCatalogFromAttributesConfigName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('branch', () => { - const fakePath = "/rendered/path/branch"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - branch: "branchValue", - }; - const client = new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.branchPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.branchPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('branchPath', () => { - const result = client.branchPath("projectValue", "locationValue", "catalogValue", "branchValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.branchPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromBranchName', () => { - const result = client.matchProjectFromBranchName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.branchPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromBranchName', () => { - const result = client.matchLocationFromBranchName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.branchPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromBranchName', () => { - const result = client.matchCatalogFromBranchName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.branchPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBranchFromBranchName', () => { - const result = client.matchBranchFromBranchName(fakePath); - assert.strictEqual(result, "branchValue"); - assert((client.pathTemplates.branchPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('branch', () => { + const fakePath = '/rendered/path/branch'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + branch: 'branchValue', + }; + const client = + new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.branchPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.branchPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('branchPath', () => { + const result = client.branchPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'branchValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.branchPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromBranchName', () => { + const result = client.matchProjectFromBranchName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.branchPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromBranchName', () => { + const result = client.matchLocationFromBranchName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.branchPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromBranchName', () => { + const result = client.matchCatalogFromBranchName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.branchPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBranchFromBranchName', () => { + const result = client.matchBranchFromBranchName(fakePath); + assert.strictEqual(result, 'branchValue'); + assert( + (client.pathTemplates.branchPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('catalog', () => { - const fakePath = "/rendered/path/catalog"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - }; - const client = new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.catalogPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.catalogPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('catalogPath', () => { - const result = client.catalogPath("projectValue", "locationValue", "catalogValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.catalogPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromCatalogName', () => { - const result = client.matchProjectFromCatalogName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.catalogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromCatalogName', () => { - const result = client.matchLocationFromCatalogName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.catalogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromCatalogName', () => { - const result = client.matchCatalogFromCatalogName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.catalogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('catalog', () => { + const fakePath = '/rendered/path/catalog'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + }; + const client = + new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.catalogPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.catalogPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('catalogPath', () => { + const result = client.catalogPath( + 'projectValue', + 'locationValue', + 'catalogValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.catalogPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromCatalogName', () => { + const result = client.matchProjectFromCatalogName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.catalogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromCatalogName', () => { + const result = client.matchLocationFromCatalogName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.catalogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromCatalogName', () => { + const result = client.matchCatalogFromCatalogName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.catalogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('completionConfig', () => { - const fakePath = "/rendered/path/completionConfig"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - }; - const client = new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.completionConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.completionConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('completionConfigPath', () => { - const result = client.completionConfigPath("projectValue", "locationValue", "catalogValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.completionConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromCompletionConfigName', () => { - const result = client.matchProjectFromCompletionConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.completionConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromCompletionConfigName', () => { - const result = client.matchLocationFromCompletionConfigName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.completionConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromCompletionConfigName', () => { - const result = client.matchCatalogFromCompletionConfigName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.completionConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('completionConfig', () => { + const fakePath = '/rendered/path/completionConfig'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + }; + const client = + new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.completionConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.completionConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('completionConfigPath', () => { + const result = client.completionConfigPath( + 'projectValue', + 'locationValue', + 'catalogValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.completionConfigPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromCompletionConfigName', () => { + const result = client.matchProjectFromCompletionConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.completionConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromCompletionConfigName', () => { + const result = client.matchLocationFromCompletionConfigName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.completionConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromCompletionConfigName', () => { + const result = client.matchCatalogFromCompletionConfigName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.completionConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('control', () => { - const fakePath = "/rendered/path/control"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - control: "controlValue", - }; - const client = new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.controlPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.controlPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('controlPath', () => { - const result = client.controlPath("projectValue", "locationValue", "catalogValue", "controlValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.controlPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromControlName', () => { - const result = client.matchProjectFromControlName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.controlPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromControlName', () => { - const result = client.matchLocationFromControlName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.controlPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromControlName', () => { - const result = client.matchCatalogFromControlName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.controlPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchControlFromControlName', () => { - const result = client.matchControlFromControlName(fakePath); - assert.strictEqual(result, "controlValue"); - assert((client.pathTemplates.controlPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('control', () => { + const fakePath = '/rendered/path/control'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + control: 'controlValue', + }; + const client = + new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.controlPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.controlPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('controlPath', () => { + const result = client.controlPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'controlValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.controlPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromControlName', () => { + const result = client.matchProjectFromControlName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.controlPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromControlName', () => { + const result = client.matchLocationFromControlName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.controlPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromControlName', () => { + const result = client.matchCatalogFromControlName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.controlPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchControlFromControlName', () => { + const result = client.matchControlFromControlName(fakePath); + assert.strictEqual(result, 'controlValue'); + assert( + (client.pathTemplates.controlPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('loggingConfig', () => { - const fakePath = "/rendered/path/loggingConfig"; - const expectedParameters = { - project: "projectValue", - }; - const client = new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.loggingConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.loggingConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('loggingConfigPath', () => { - const result = client.loggingConfigPath("projectValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.loggingConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromLoggingConfigName', () => { - const result = client.matchProjectFromLoggingConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.loggingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('loggingConfig', () => { + const fakePath = '/rendered/path/loggingConfig'; + const expectedParameters = { + project: 'projectValue', + }; + const client = + new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.loggingConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.loggingConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('loggingConfigPath', () => { + const result = client.loggingConfigPath('projectValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.loggingConfigPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromLoggingConfigName', () => { + const result = client.matchProjectFromLoggingConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.loggingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('merchantCenterAccountLink', () => { - const fakePath = "/rendered/path/merchantCenterAccountLink"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - merchant_center_account_link: "merchantCenterAccountLinkValue", - }; - const client = new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.merchantCenterAccountLinkPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.merchantCenterAccountLinkPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('merchantCenterAccountLinkPath', () => { - const result = client.merchantCenterAccountLinkPath("projectValue", "locationValue", "catalogValue", "merchantCenterAccountLinkValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromMerchantCenterAccountLinkName', () => { - const result = client.matchProjectFromMerchantCenterAccountLinkName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromMerchantCenterAccountLinkName', () => { - const result = client.matchLocationFromMerchantCenterAccountLinkName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromMerchantCenterAccountLinkName', () => { - const result = client.matchCatalogFromMerchantCenterAccountLinkName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName', () => { - const result = client.matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName(fakePath); - assert.strictEqual(result, "merchantCenterAccountLinkValue"); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('merchantCenterAccountLink', () => { + const fakePath = '/rendered/path/merchantCenterAccountLink'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + merchant_center_account_link: 'merchantCenterAccountLinkValue', + }; + const client = + new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.merchantCenterAccountLinkPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.merchantCenterAccountLinkPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('merchantCenterAccountLinkPath', () => { + const result = client.merchantCenterAccountLinkPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'merchantCenterAccountLinkValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromMerchantCenterAccountLinkName', () => { + const result = + client.matchProjectFromMerchantCenterAccountLinkName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromMerchantCenterAccountLinkName', () => { + const result = + client.matchLocationFromMerchantCenterAccountLinkName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromMerchantCenterAccountLinkName', () => { + const result = + client.matchCatalogFromMerchantCenterAccountLinkName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName', () => { + const result = + client.matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName( + fakePath, + ); + assert.strictEqual(result, 'merchantCenterAccountLinkValue'); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('model', () => { - const fakePath = "/rendered/path/model"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - model: "modelValue", - }; - const client = new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.modelPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.modelPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('modelPath', () => { - const result = client.modelPath("projectValue", "locationValue", "catalogValue", "modelValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.modelPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromModelName', () => { - const result = client.matchProjectFromModelName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromModelName', () => { - const result = client.matchLocationFromModelName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromModelName', () => { - const result = client.matchCatalogFromModelName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchModelFromModelName', () => { - const result = client.matchModelFromModelName(fakePath); - assert.strictEqual(result, "modelValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('model', () => { + const fakePath = '/rendered/path/model'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + model: 'modelValue', + }; + const client = + new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.modelPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.modelPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('modelPath', () => { + const result = client.modelPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'modelValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.modelPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromModelName', () => { + const result = client.matchProjectFromModelName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromModelName', () => { + const result = client.matchLocationFromModelName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromModelName', () => { + const result = client.matchCatalogFromModelName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchModelFromModelName', () => { + const result = client.matchModelFromModelName(fakePath); + assert.strictEqual(result, 'modelValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('product', () => { - const fakePath = "/rendered/path/product"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - branch: "branchValue", - product: "productValue", - }; - const client = new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.productPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.productPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('productPath', () => { - const result = client.productPath("projectValue", "locationValue", "catalogValue", "branchValue", "productValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.productPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProductName', () => { - const result = client.matchProjectFromProductName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromProductName', () => { - const result = client.matchLocationFromProductName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromProductName', () => { - const result = client.matchCatalogFromProductName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBranchFromProductName', () => { - const result = client.matchBranchFromProductName(fakePath); - assert.strictEqual(result, "branchValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchProductFromProductName', () => { - const result = client.matchProductFromProductName(fakePath); - assert.strictEqual(result, "productValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('product', () => { + const fakePath = '/rendered/path/product'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + branch: 'branchValue', + product: 'productValue', + }; + const client = + new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.productPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.productPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('productPath', () => { + const result = client.productPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'branchValue', + 'productValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.productPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProductName', () => { + const result = client.matchProjectFromProductName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromProductName', () => { + const result = client.matchLocationFromProductName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromProductName', () => { + const result = client.matchCatalogFromProductName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBranchFromProductName', () => { + const result = client.matchBranchFromProductName(fakePath); + assert.strictEqual(result, 'branchValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchProductFromProductName', () => { + const result = client.matchProductFromProductName(fakePath); + assert.strictEqual(result, 'productValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('retailProject', () => { - const fakePath = "/rendered/path/retailProject"; - const expectedParameters = { - project: "projectValue", - }; - const client = new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.retailProjectPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.retailProjectPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('retailProjectPath', () => { - const result = client.retailProjectPath("projectValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.retailProjectPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromRetailProjectName', () => { - const result = client.matchProjectFromRetailProjectName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.retailProjectPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('retailProject', () => { + const fakePath = '/rendered/path/retailProject'; + const expectedParameters = { + project: 'projectValue', + }; + const client = + new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.retailProjectPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.retailProjectPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('retailProjectPath', () => { + const result = client.retailProjectPath('projectValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.retailProjectPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromRetailProjectName', () => { + const result = client.matchProjectFromRetailProjectName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.retailProjectPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('servingConfig', () => { - const fakePath = "/rendered/path/servingConfig"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - serving_config: "servingConfigValue", - }; - const client = new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.servingConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.servingConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('servingConfigPath', () => { - const result = client.servingConfigPath("projectValue", "locationValue", "catalogValue", "servingConfigValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.servingConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromServingConfigName', () => { - const result = client.matchProjectFromServingConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.servingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromServingConfigName', () => { - const result = client.matchLocationFromServingConfigName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.servingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromServingConfigName', () => { - const result = client.matchCatalogFromServingConfigName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.servingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServingConfigFromServingConfigName', () => { - const result = client.matchServingConfigFromServingConfigName(fakePath); - assert.strictEqual(result, "servingConfigValue"); - assert((client.pathTemplates.servingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('servingConfig', () => { + const fakePath = '/rendered/path/servingConfig'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + serving_config: 'servingConfigValue', + }; + const client = + new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.servingConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.servingConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('servingConfigPath', () => { + const result = client.servingConfigPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'servingConfigValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.servingConfigPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromServingConfigName', () => { + const result = client.matchProjectFromServingConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.servingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromServingConfigName', () => { + const result = client.matchLocationFromServingConfigName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.servingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromServingConfigName', () => { + const result = client.matchCatalogFromServingConfigName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.servingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServingConfigFromServingConfigName', () => { + const result = client.matchServingConfigFromServingConfigName(fakePath); + assert.strictEqual(result, 'servingConfigValue'); + assert( + (client.pathTemplates.servingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/test/gapic_merchant_center_account_link_service_v2alpha.ts.baseline b/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/test/gapic_merchant_center_account_link_service_v2alpha.ts.baseline index d186919c1d11..4af10805cf96 100644 --- a/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/test/gapic_merchant_center_account_link_service_v2alpha.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/test/gapic_merchant_center_account_link_service_v2alpha.ts.baseline @@ -20,14 +20,14 @@ import * as protos from '../../protos/protos.js'; import assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as merchantcenteraccountlinkserviceModule from '../src/index.js'; -import {protobuf, LROperation, operationsProtos} from 'google-gax'; +import { protobuf, LROperation, operationsProtos } from 'google-gax'; import fs from 'fs'; import path from 'path'; -import {fileURLToPath} from 'url'; +import { fileURLToPath } from 'url'; // @ts-ignore const dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -35,1138 +35,1675 @@ const dirname = path.dirname(fileURLToPath(import.meta.url)); // to fill in default values for request objects const root = protobuf.Root.fromJSON( JSON.parse( - fs.readFileSync(path.join(dirname, '..', '..', 'protos/protos.json'), 'utf8') - )) + fs.readFileSync( + path.join(dirname, '..', '..', 'protos/protos.json'), + 'utf8', + ), + ), +); // eslint-disable-next-line @typescript-eslint/no-unused-vars function getTypeDefaultValue(typeName: string, fields: string[]) { - let type = root.lookupType(typeName) as protobuf.Type; - for (const field of fields.slice(0, -1)) { - type = type?.fields[field]?.resolvedType as protobuf.Type; - } - return type?.fields[fields[fields.length - 1]]?.defaultValue ?? null; + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type?.fields[field]?.resolvedType as protobuf.Type; + } + return type?.fields[fields[fields.length - 1]]?.defaultValue ?? null; } function generateSampleMessage(instance: T) { - const filledObject = (instance.constructor as typeof protobuf.Message) - .toObject(instance as protobuf.Message, {defaults: true}); - return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, { defaults: true }); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; } function stubSimpleCall(response?: ResponseType, error?: Error) { - return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); } -function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { - return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +function stubSimpleCallWithCallback( + response?: ResponseType, + error?: Error, +) { + return error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); } -function stubLongRunningCall(response?: ResponseType, callError?: Error, lroError?: Error) { - const innerStub = lroError ? sinon.stub().rejects(lroError) : sinon.stub().resolves([response]); - const mockOperation = { - promise: innerStub, - }; - return callError ? sinon.stub().rejects(callError) : sinon.stub().resolves([mockOperation]); +function stubLongRunningCall( + response?: ResponseType, + callError?: Error, + lroError?: Error, +) { + const innerStub = lroError + ? sinon.stub().rejects(lroError) + : sinon.stub().resolves([response]); + const mockOperation = { + promise: innerStub, + }; + return callError + ? sinon.stub().rejects(callError) + : sinon.stub().resolves([mockOperation]); } -function stubLongRunningCallWithCallback(response?: ResponseType, callError?: Error, lroError?: Error) { - const innerStub = lroError ? sinon.stub().rejects(lroError) : sinon.stub().resolves([response]); - const mockOperation = { - promise: innerStub, - }; - return callError ? sinon.stub().callsArgWith(2, callError) : sinon.stub().callsArgWith(2, null, mockOperation); +function stubLongRunningCallWithCallback( + response?: ResponseType, + callError?: Error, + lroError?: Error, +) { + const innerStub = lroError + ? sinon.stub().rejects(lroError) + : sinon.stub().resolves([response]); + const mockOperation = { + promise: innerStub, + }; + return callError + ? sinon.stub().callsArgWith(2, callError) + : sinon.stub().callsArgWith(2, null, mockOperation); } describe('v2alpha.MerchantCenterAccountLinkServiceClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'retail.googleapis.com'); - }); - - it('has universeDomain', () => { - const client = new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); - - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - it('throws DeprecationWarning if static servicePath is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const servicePath = merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient.servicePath; - assert.strictEqual(servicePath, 'retail.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'retail.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'retail.example.com'); - }); - - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'retail.example.com'); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = + new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'retail.googleapis.com'); + }); - if (typeof process === 'object' && 'env' in process) { - describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { - it('sets apiEndpoint from environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'retail.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - - it('value configured in code has priority over environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'retail.configured.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); + it('has universeDomain', () => { + const client = + new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - it('has port', () => { - const port = merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient.port; - assert(port); - assert(typeof port === 'number'); - }); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = + merchantcenteraccountlinkserviceModule.v2alpha + .MerchantCenterAccountLinkServiceClient.servicePath; + assert.strictEqual(servicePath, 'retail.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + merchantcenteraccountlinkserviceModule.v2alpha + .MerchantCenterAccountLinkServiceClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'retail.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = + new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient( + { universeDomain: 'example.com' }, + ); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'retail.example.com'); + }); - it('should create a client with no option', () => { - const client = new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient(); - assert(client); - }); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = + new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient( + { universe_domain: 'example.com' }, + ); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'retail.example.com'); + }); - it('should create a client with gRPC fallback', () => { - const client = new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient({ - fallback: true, - }); - assert(client); + if (typeof process === 'object' && 'env' in process) { + describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { + it('sets apiEndpoint from environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = + new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'retail.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - it('has initialize method and supports deferred initialization', async () => { - const client = new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.merchantCenterAccountLinkServiceStub, undefined); - await client.initialize(); - assert(client.merchantCenterAccountLinkServiceStub); + it('value configured in code has priority over environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = + new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient( + { universeDomain: 'configured.example.com' }, + ); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'retail.configured.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient( + { universe_domain: 'example.com', universeDomain: 'example.net' }, + ); + }); + }); - it('has close method for the initialized client', done => { - const client = new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.merchantCenterAccountLinkServiceStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('has port', () => { + const port = + merchantcenteraccountlinkserviceModule.v2alpha + .MerchantCenterAccountLinkServiceClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('has close method for the non-initialized client', done => { - const client = new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.merchantCenterAccountLinkServiceStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('should create a client with no option', () => { + const client = + new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient(); + assert(client); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); - }); + it('should create a client with gRPC fallback', () => { + const client = + new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient( + { + fallback: true, + }, + ); + assert(client); + }); - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId((err?: Error|null, projectId?: string|null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } - }); - }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); - }); + it('has initialize method and supports deferred initialization', async () => { + const client = + new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + assert.strictEqual( + client.merchantCenterAccountLinkServiceStub, + undefined, + ); + await client.initialize(); + assert(client.merchantCenterAccountLinkServiceStub); }); - describe('listMerchantCenterAccountLinks', () => { - it('invokes listMerchantCenterAccountLinks without error', async () => { - const client = new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ListMerchantCenterAccountLinksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ListMerchantCenterAccountLinksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ListMerchantCenterAccountLinksResponse() - ); - client.innerApiCalls.listMerchantCenterAccountLinks = stubSimpleCall(expectedResponse); - const [response] = await client.listMerchantCenterAccountLinks(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listMerchantCenterAccountLinks as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listMerchantCenterAccountLinks as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('has close method for the initialized client', (done) => { + const client = + new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + client.initialize().catch((err) => { + throw err; + }); + assert(client.merchantCenterAccountLinkServiceStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes listMerchantCenterAccountLinks without error using callback', async () => { - const client = new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ListMerchantCenterAccountLinksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ListMerchantCenterAccountLinksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ListMerchantCenterAccountLinksResponse() - ); - client.innerApiCalls.listMerchantCenterAccountLinks = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listMerchantCenterAccountLinks( - request, - (err?: Error|null, result?: protos.google.cloud.retail.v2alpha.IListMerchantCenterAccountLinksResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listMerchantCenterAccountLinks as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listMerchantCenterAccountLinks as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('has close method for the non-initialized client', (done) => { + const client = + new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + assert.strictEqual( + client.merchantCenterAccountLinkServiceStub, + undefined, + ); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes listMerchantCenterAccountLinks with error', async () => { - const client = new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ListMerchantCenterAccountLinksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ListMerchantCenterAccountLinksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listMerchantCenterAccountLinks = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listMerchantCenterAccountLinks(request), expectedError); - const actualRequest = (client.innerApiCalls.listMerchantCenterAccountLinks as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listMerchantCenterAccountLinks as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = + new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + }); - it('invokes listMerchantCenterAccountLinks with closed client', async () => { - const client = new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ListMerchantCenterAccountLinksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ListMerchantCenterAccountLinksRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.listMerchantCenterAccountLinks(request), expectedError); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = + new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + }); + + describe('listMerchantCenterAccountLinks', () => { + it('invokes listMerchantCenterAccountLinks without error', async () => { + const client = + new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ListMerchantCenterAccountLinksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ListMerchantCenterAccountLinksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ListMerchantCenterAccountLinksResponse(), + ); + client.innerApiCalls.listMerchantCenterAccountLinks = + stubSimpleCall(expectedResponse); + const [response] = await client.listMerchantCenterAccountLinks(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listMerchantCenterAccountLinks as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listMerchantCenterAccountLinks as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('deleteMerchantCenterAccountLink', () => { - it('invokes deleteMerchantCenterAccountLink without error', async () => { - const client = new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.DeleteMerchantCenterAccountLinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.DeleteMerchantCenterAccountLinkRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteMerchantCenterAccountLink = stubSimpleCall(expectedResponse); - const [response] = await client.deleteMerchantCenterAccountLink(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteMerchantCenterAccountLink as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteMerchantCenterAccountLink as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listMerchantCenterAccountLinks without error using callback', async () => { + const client = + new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ListMerchantCenterAccountLinksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ListMerchantCenterAccountLinksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ListMerchantCenterAccountLinksResponse(), + ); + client.innerApiCalls.listMerchantCenterAccountLinks = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listMerchantCenterAccountLinks( + request, + ( + err?: Error | null, + result?: protos.google.cloud.retail.v2alpha.IListMerchantCenterAccountLinksResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listMerchantCenterAccountLinks as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listMerchantCenterAccountLinks as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteMerchantCenterAccountLink without error using callback', async () => { - const client = new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.DeleteMerchantCenterAccountLinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.DeleteMerchantCenterAccountLinkRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteMerchantCenterAccountLink = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteMerchantCenterAccountLink( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteMerchantCenterAccountLink as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteMerchantCenterAccountLink as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listMerchantCenterAccountLinks with error', async () => { + const client = + new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ListMerchantCenterAccountLinksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ListMerchantCenterAccountLinksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listMerchantCenterAccountLinks = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.listMerchantCenterAccountLinks(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.listMerchantCenterAccountLinks as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listMerchantCenterAccountLinks as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteMerchantCenterAccountLink with error', async () => { - const client = new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.DeleteMerchantCenterAccountLinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.DeleteMerchantCenterAccountLinkRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteMerchantCenterAccountLink = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteMerchantCenterAccountLink(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteMerchantCenterAccountLink as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteMerchantCenterAccountLink as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listMerchantCenterAccountLinks with closed client', async () => { + const client = + new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ListMerchantCenterAccountLinksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ListMerchantCenterAccountLinksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.listMerchantCenterAccountLinks(request), + expectedError, + ); + }); + }); + + describe('deleteMerchantCenterAccountLink', () => { + it('invokes deleteMerchantCenterAccountLink without error', async () => { + const client = + new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.DeleteMerchantCenterAccountLinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.DeleteMerchantCenterAccountLinkRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteMerchantCenterAccountLink = + stubSimpleCall(expectedResponse); + const [response] = await client.deleteMerchantCenterAccountLink(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteMerchantCenterAccountLink as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteMerchantCenterAccountLink as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteMerchantCenterAccountLink with closed client', async () => { - const client = new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.DeleteMerchantCenterAccountLinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.DeleteMerchantCenterAccountLinkRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteMerchantCenterAccountLink(request), expectedError); - }); + it('invokes deleteMerchantCenterAccountLink without error using callback', async () => { + const client = + new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.DeleteMerchantCenterAccountLinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.DeleteMerchantCenterAccountLinkRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteMerchantCenterAccountLink = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteMerchantCenterAccountLink( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteMerchantCenterAccountLink as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteMerchantCenterAccountLink as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('createMerchantCenterAccountLink', () => { - it('invokes createMerchantCenterAccountLink without error', async () => { - const client = new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.CreateMerchantCenterAccountLinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.CreateMerchantCenterAccountLinkRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.createMerchantCenterAccountLink = stubLongRunningCall(expectedResponse); - const [operation] = await client.createMerchantCenterAccountLink(request); - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createMerchantCenterAccountLink as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createMerchantCenterAccountLink as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteMerchantCenterAccountLink with error', async () => { + const client = + new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.DeleteMerchantCenterAccountLinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.DeleteMerchantCenterAccountLinkRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteMerchantCenterAccountLink = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.deleteMerchantCenterAccountLink(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.deleteMerchantCenterAccountLink as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteMerchantCenterAccountLink as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createMerchantCenterAccountLink without error using callback', async () => { - const client = new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.CreateMerchantCenterAccountLinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.CreateMerchantCenterAccountLinkRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.createMerchantCenterAccountLink = stubLongRunningCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createMerchantCenterAccountLink( - request, - (err?: Error|null, - result?: LROperation|null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const operation = await promise as LROperation; - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createMerchantCenterAccountLink as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createMerchantCenterAccountLink as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteMerchantCenterAccountLink with closed client', async () => { + const client = + new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.DeleteMerchantCenterAccountLinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.DeleteMerchantCenterAccountLinkRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.deleteMerchantCenterAccountLink(request), + expectedError, + ); + }); + }); + + describe('createMerchantCenterAccountLink', () => { + it('invokes createMerchantCenterAccountLink without error', async () => { + const client = + new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.CreateMerchantCenterAccountLinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.CreateMerchantCenterAccountLinkRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.createMerchantCenterAccountLink = + stubLongRunningCall(expectedResponse); + const [operation] = await client.createMerchantCenterAccountLink(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createMerchantCenterAccountLink as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createMerchantCenterAccountLink as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createMerchantCenterAccountLink with call error', async () => { - const client = new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.CreateMerchantCenterAccountLinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.CreateMerchantCenterAccountLinkRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createMerchantCenterAccountLink = stubLongRunningCall(undefined, expectedError); - await assert.rejects(client.createMerchantCenterAccountLink(request), expectedError); - const actualRequest = (client.innerApiCalls.createMerchantCenterAccountLink as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createMerchantCenterAccountLink as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createMerchantCenterAccountLink without error using callback', async () => { + const client = + new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.CreateMerchantCenterAccountLinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.CreateMerchantCenterAccountLinkRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.createMerchantCenterAccountLink = + stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createMerchantCenterAccountLink( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.cloud.retail.v2alpha.IMerchantCenterAccountLink, + protos.google.cloud.retail.v2alpha.ICreateMerchantCenterAccountLinkMetadata + > | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const operation = (await promise) as LROperation< + protos.google.cloud.retail.v2alpha.IMerchantCenterAccountLink, + protos.google.cloud.retail.v2alpha.ICreateMerchantCenterAccountLinkMetadata + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createMerchantCenterAccountLink as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createMerchantCenterAccountLink as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createMerchantCenterAccountLink with LRO error', async () => { - const client = new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.CreateMerchantCenterAccountLinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.CreateMerchantCenterAccountLinkRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createMerchantCenterAccountLink = stubLongRunningCall(undefined, undefined, expectedError); - const [operation] = await client.createMerchantCenterAccountLink(request); - await assert.rejects(operation.promise(), expectedError); - const actualRequest = (client.innerApiCalls.createMerchantCenterAccountLink as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createMerchantCenterAccountLink as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createMerchantCenterAccountLink with call error', async () => { + const client = + new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.CreateMerchantCenterAccountLinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.CreateMerchantCenterAccountLinkRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createMerchantCenterAccountLink = + stubLongRunningCall(undefined, expectedError); + await assert.rejects( + client.createMerchantCenterAccountLink(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.createMerchantCenterAccountLink as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createMerchantCenterAccountLink as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkCreateMerchantCenterAccountLinkProgress without error', async () => { - const client = new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedResponse = generateSampleMessage( - new operationsProtos.google.longrunning.Operation() - ); - expectedResponse.name = 'test'; - expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; - expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')} - - client.operationsClient.getOperation = stubSimpleCall(expectedResponse); - const decodedOperation = await client.checkCreateMerchantCenterAccountLinkProgress(expectedResponse.name); - assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); - assert(decodedOperation.metadata); - assert((client.operationsClient.getOperation as SinonStub).getCall(0)); - }); + it('invokes createMerchantCenterAccountLink with LRO error', async () => { + const client = + new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.CreateMerchantCenterAccountLinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.CreateMerchantCenterAccountLinkRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createMerchantCenterAccountLink = + stubLongRunningCall(undefined, undefined, expectedError); + const [operation] = await client.createMerchantCenterAccountLink(request); + await assert.rejects(operation.promise(), expectedError); + const actualRequest = ( + client.innerApiCalls.createMerchantCenterAccountLink as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createMerchantCenterAccountLink as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkCreateMerchantCenterAccountLinkProgress with error', async () => { - const client = new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedError = new Error('expected'); - - client.operationsClient.getOperation = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.checkCreateMerchantCenterAccountLinkProgress(''), expectedError); - assert((client.operationsClient.getOperation as SinonStub) - .getCall(0)); - }); + it('invokes checkCreateMerchantCenterAccountLinkProgress without error', async () => { + const client = + new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation(), + ); + expectedResponse.name = 'test'; + expectedResponse.response = { type_url: 'url', value: Buffer.from('') }; + expectedResponse.metadata = { type_url: 'url', value: Buffer.from('') }; + + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const decodedOperation = + await client.checkCreateMerchantCenterAccountLinkProgress( + expectedResponse.name, + ); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); }); - describe('Path templates', () => { - - describe('alertConfig', () => { - const fakePath = "/rendered/path/alertConfig"; - const expectedParameters = { - project: "projectValue", - }; - const client = new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.alertConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.alertConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('alertConfigPath', () => { - const result = client.alertConfigPath("projectValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.alertConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromAlertConfigName', () => { - const result = client.matchProjectFromAlertConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.alertConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('invokes checkCreateMerchantCenterAccountLinkProgress with error', async () => { + const client = + new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const expectedError = new Error('expected'); + + client.operationsClient.getOperation = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.checkCreateMerchantCenterAccountLinkProgress(''), + expectedError, + ); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + }); + + describe('Path templates', () => { + describe('alertConfig', () => { + const fakePath = '/rendered/path/alertConfig'; + const expectedParameters = { + project: 'projectValue', + }; + const client = + new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.alertConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.alertConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('alertConfigPath', () => { + const result = client.alertConfigPath('projectValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.alertConfigPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromAlertConfigName', () => { + const result = client.matchProjectFromAlertConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.alertConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('attributesConfig', () => { - const fakePath = "/rendered/path/attributesConfig"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - }; - const client = new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.attributesConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.attributesConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('attributesConfigPath', () => { - const result = client.attributesConfigPath("projectValue", "locationValue", "catalogValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.attributesConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromAttributesConfigName', () => { - const result = client.matchProjectFromAttributesConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromAttributesConfigName', () => { - const result = client.matchLocationFromAttributesConfigName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromAttributesConfigName', () => { - const result = client.matchCatalogFromAttributesConfigName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('attributesConfig', () => { + const fakePath = '/rendered/path/attributesConfig'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + }; + const client = + new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.attributesConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.attributesConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('attributesConfigPath', () => { + const result = client.attributesConfigPath( + 'projectValue', + 'locationValue', + 'catalogValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.attributesConfigPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromAttributesConfigName', () => { + const result = client.matchProjectFromAttributesConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromAttributesConfigName', () => { + const result = client.matchLocationFromAttributesConfigName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromAttributesConfigName', () => { + const result = client.matchCatalogFromAttributesConfigName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('branch', () => { - const fakePath = "/rendered/path/branch"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - branch: "branchValue", - }; - const client = new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.branchPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.branchPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('branchPath', () => { - const result = client.branchPath("projectValue", "locationValue", "catalogValue", "branchValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.branchPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromBranchName', () => { - const result = client.matchProjectFromBranchName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.branchPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromBranchName', () => { - const result = client.matchLocationFromBranchName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.branchPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromBranchName', () => { - const result = client.matchCatalogFromBranchName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.branchPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBranchFromBranchName', () => { - const result = client.matchBranchFromBranchName(fakePath); - assert.strictEqual(result, "branchValue"); - assert((client.pathTemplates.branchPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('branch', () => { + const fakePath = '/rendered/path/branch'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + branch: 'branchValue', + }; + const client = + new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.branchPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.branchPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('branchPath', () => { + const result = client.branchPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'branchValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.branchPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromBranchName', () => { + const result = client.matchProjectFromBranchName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.branchPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromBranchName', () => { + const result = client.matchLocationFromBranchName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.branchPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromBranchName', () => { + const result = client.matchCatalogFromBranchName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.branchPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBranchFromBranchName', () => { + const result = client.matchBranchFromBranchName(fakePath); + assert.strictEqual(result, 'branchValue'); + assert( + (client.pathTemplates.branchPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('catalog', () => { - const fakePath = "/rendered/path/catalog"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - }; - const client = new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.catalogPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.catalogPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('catalogPath', () => { - const result = client.catalogPath("projectValue", "locationValue", "catalogValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.catalogPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromCatalogName', () => { - const result = client.matchProjectFromCatalogName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.catalogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromCatalogName', () => { - const result = client.matchLocationFromCatalogName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.catalogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromCatalogName', () => { - const result = client.matchCatalogFromCatalogName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.catalogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('catalog', () => { + const fakePath = '/rendered/path/catalog'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + }; + const client = + new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.catalogPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.catalogPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('catalogPath', () => { + const result = client.catalogPath( + 'projectValue', + 'locationValue', + 'catalogValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.catalogPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromCatalogName', () => { + const result = client.matchProjectFromCatalogName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.catalogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromCatalogName', () => { + const result = client.matchLocationFromCatalogName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.catalogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromCatalogName', () => { + const result = client.matchCatalogFromCatalogName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.catalogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('completionConfig', () => { - const fakePath = "/rendered/path/completionConfig"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - }; - const client = new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.completionConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.completionConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('completionConfigPath', () => { - const result = client.completionConfigPath("projectValue", "locationValue", "catalogValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.completionConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromCompletionConfigName', () => { - const result = client.matchProjectFromCompletionConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.completionConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromCompletionConfigName', () => { - const result = client.matchLocationFromCompletionConfigName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.completionConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromCompletionConfigName', () => { - const result = client.matchCatalogFromCompletionConfigName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.completionConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('completionConfig', () => { + const fakePath = '/rendered/path/completionConfig'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + }; + const client = + new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.completionConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.completionConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('completionConfigPath', () => { + const result = client.completionConfigPath( + 'projectValue', + 'locationValue', + 'catalogValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.completionConfigPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromCompletionConfigName', () => { + const result = client.matchProjectFromCompletionConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.completionConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromCompletionConfigName', () => { + const result = client.matchLocationFromCompletionConfigName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.completionConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromCompletionConfigName', () => { + const result = client.matchCatalogFromCompletionConfigName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.completionConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('control', () => { - const fakePath = "/rendered/path/control"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - control: "controlValue", - }; - const client = new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.controlPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.controlPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('controlPath', () => { - const result = client.controlPath("projectValue", "locationValue", "catalogValue", "controlValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.controlPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromControlName', () => { - const result = client.matchProjectFromControlName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.controlPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromControlName', () => { - const result = client.matchLocationFromControlName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.controlPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromControlName', () => { - const result = client.matchCatalogFromControlName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.controlPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchControlFromControlName', () => { - const result = client.matchControlFromControlName(fakePath); - assert.strictEqual(result, "controlValue"); - assert((client.pathTemplates.controlPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('control', () => { + const fakePath = '/rendered/path/control'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + control: 'controlValue', + }; + const client = + new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.controlPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.controlPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('controlPath', () => { + const result = client.controlPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'controlValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.controlPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromControlName', () => { + const result = client.matchProjectFromControlName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.controlPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromControlName', () => { + const result = client.matchLocationFromControlName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.controlPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromControlName', () => { + const result = client.matchCatalogFromControlName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.controlPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchControlFromControlName', () => { + const result = client.matchControlFromControlName(fakePath); + assert.strictEqual(result, 'controlValue'); + assert( + (client.pathTemplates.controlPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('loggingConfig', () => { - const fakePath = "/rendered/path/loggingConfig"; - const expectedParameters = { - project: "projectValue", - }; - const client = new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.loggingConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.loggingConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('loggingConfigPath', () => { - const result = client.loggingConfigPath("projectValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.loggingConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromLoggingConfigName', () => { - const result = client.matchProjectFromLoggingConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.loggingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('loggingConfig', () => { + const fakePath = '/rendered/path/loggingConfig'; + const expectedParameters = { + project: 'projectValue', + }; + const client = + new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.loggingConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.loggingConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('loggingConfigPath', () => { + const result = client.loggingConfigPath('projectValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.loggingConfigPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromLoggingConfigName', () => { + const result = client.matchProjectFromLoggingConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.loggingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('merchantCenterAccountLink', () => { - const fakePath = "/rendered/path/merchantCenterAccountLink"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - merchant_center_account_link: "merchantCenterAccountLinkValue", - }; - const client = new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.merchantCenterAccountLinkPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.merchantCenterAccountLinkPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('merchantCenterAccountLinkPath', () => { - const result = client.merchantCenterAccountLinkPath("projectValue", "locationValue", "catalogValue", "merchantCenterAccountLinkValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromMerchantCenterAccountLinkName', () => { - const result = client.matchProjectFromMerchantCenterAccountLinkName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromMerchantCenterAccountLinkName', () => { - const result = client.matchLocationFromMerchantCenterAccountLinkName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromMerchantCenterAccountLinkName', () => { - const result = client.matchCatalogFromMerchantCenterAccountLinkName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName', () => { - const result = client.matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName(fakePath); - assert.strictEqual(result, "merchantCenterAccountLinkValue"); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('merchantCenterAccountLink', () => { + const fakePath = '/rendered/path/merchantCenterAccountLink'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + merchant_center_account_link: 'merchantCenterAccountLinkValue', + }; + const client = + new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.merchantCenterAccountLinkPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.merchantCenterAccountLinkPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('merchantCenterAccountLinkPath', () => { + const result = client.merchantCenterAccountLinkPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'merchantCenterAccountLinkValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromMerchantCenterAccountLinkName', () => { + const result = + client.matchProjectFromMerchantCenterAccountLinkName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromMerchantCenterAccountLinkName', () => { + const result = + client.matchLocationFromMerchantCenterAccountLinkName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromMerchantCenterAccountLinkName', () => { + const result = + client.matchCatalogFromMerchantCenterAccountLinkName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName', () => { + const result = + client.matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName( + fakePath, + ); + assert.strictEqual(result, 'merchantCenterAccountLinkValue'); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('model', () => { - const fakePath = "/rendered/path/model"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - model: "modelValue", - }; - const client = new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.modelPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.modelPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('modelPath', () => { - const result = client.modelPath("projectValue", "locationValue", "catalogValue", "modelValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.modelPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromModelName', () => { - const result = client.matchProjectFromModelName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromModelName', () => { - const result = client.matchLocationFromModelName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromModelName', () => { - const result = client.matchCatalogFromModelName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchModelFromModelName', () => { - const result = client.matchModelFromModelName(fakePath); - assert.strictEqual(result, "modelValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('model', () => { + const fakePath = '/rendered/path/model'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + model: 'modelValue', + }; + const client = + new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.modelPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.modelPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('modelPath', () => { + const result = client.modelPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'modelValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.modelPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromModelName', () => { + const result = client.matchProjectFromModelName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromModelName', () => { + const result = client.matchLocationFromModelName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromModelName', () => { + const result = client.matchCatalogFromModelName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchModelFromModelName', () => { + const result = client.matchModelFromModelName(fakePath); + assert.strictEqual(result, 'modelValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('product', () => { - const fakePath = "/rendered/path/product"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - branch: "branchValue", - product: "productValue", - }; - const client = new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.productPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.productPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('productPath', () => { - const result = client.productPath("projectValue", "locationValue", "catalogValue", "branchValue", "productValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.productPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProductName', () => { - const result = client.matchProjectFromProductName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromProductName', () => { - const result = client.matchLocationFromProductName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromProductName', () => { - const result = client.matchCatalogFromProductName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBranchFromProductName', () => { - const result = client.matchBranchFromProductName(fakePath); - assert.strictEqual(result, "branchValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchProductFromProductName', () => { - const result = client.matchProductFromProductName(fakePath); - assert.strictEqual(result, "productValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('product', () => { + const fakePath = '/rendered/path/product'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + branch: 'branchValue', + product: 'productValue', + }; + const client = + new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.productPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.productPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('productPath', () => { + const result = client.productPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'branchValue', + 'productValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.productPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProductName', () => { + const result = client.matchProjectFromProductName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromProductName', () => { + const result = client.matchLocationFromProductName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromProductName', () => { + const result = client.matchCatalogFromProductName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBranchFromProductName', () => { + const result = client.matchBranchFromProductName(fakePath); + assert.strictEqual(result, 'branchValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchProductFromProductName', () => { + const result = client.matchProductFromProductName(fakePath); + assert.strictEqual(result, 'productValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('retailProject', () => { - const fakePath = "/rendered/path/retailProject"; - const expectedParameters = { - project: "projectValue", - }; - const client = new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.retailProjectPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.retailProjectPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('retailProjectPath', () => { - const result = client.retailProjectPath("projectValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.retailProjectPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromRetailProjectName', () => { - const result = client.matchProjectFromRetailProjectName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.retailProjectPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('retailProject', () => { + const fakePath = '/rendered/path/retailProject'; + const expectedParameters = { + project: 'projectValue', + }; + const client = + new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.retailProjectPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.retailProjectPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('retailProjectPath', () => { + const result = client.retailProjectPath('projectValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.retailProjectPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromRetailProjectName', () => { + const result = client.matchProjectFromRetailProjectName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.retailProjectPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('servingConfig', () => { - const fakePath = "/rendered/path/servingConfig"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - serving_config: "servingConfigValue", - }; - const client = new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.servingConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.servingConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('servingConfigPath', () => { - const result = client.servingConfigPath("projectValue", "locationValue", "catalogValue", "servingConfigValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.servingConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromServingConfigName', () => { - const result = client.matchProjectFromServingConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.servingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromServingConfigName', () => { - const result = client.matchLocationFromServingConfigName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.servingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromServingConfigName', () => { - const result = client.matchCatalogFromServingConfigName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.servingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServingConfigFromServingConfigName', () => { - const result = client.matchServingConfigFromServingConfigName(fakePath); - assert.strictEqual(result, "servingConfigValue"); - assert((client.pathTemplates.servingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('servingConfig', () => { + const fakePath = '/rendered/path/servingConfig'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + serving_config: 'servingConfigValue', + }; + const client = + new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.servingConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.servingConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('servingConfigPath', () => { + const result = client.servingConfigPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'servingConfigValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.servingConfigPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromServingConfigName', () => { + const result = client.matchProjectFromServingConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.servingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromServingConfigName', () => { + const result = client.matchLocationFromServingConfigName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.servingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromServingConfigName', () => { + const result = client.matchCatalogFromServingConfigName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.servingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServingConfigFromServingConfigName', () => { + const result = client.matchServingConfigFromServingConfigName(fakePath); + assert.strictEqual(result, 'servingConfigValue'); + assert( + (client.pathTemplates.servingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/test/gapic_model_service_v2alpha.ts.baseline b/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/test/gapic_model_service_v2alpha.ts.baseline index 05617e930de0..011cc9721e1a 100644 --- a/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/test/gapic_model_service_v2alpha.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/test/gapic_model_service_v2alpha.ts.baseline @@ -20,16 +20,16 @@ import * as protos from '../../protos/protos.js'; import assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as modelserviceModule from '../src/index.js'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; -import {protobuf, LROperation, operationsProtos} from 'google-gax'; +import { protobuf, LROperation, operationsProtos } from 'google-gax'; import fs from 'fs'; import path from 'path'; -import {fileURLToPath} from 'url'; +import { fileURLToPath } from 'url'; // @ts-ignore const dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -37,1910 +37,2499 @@ const dirname = path.dirname(fileURLToPath(import.meta.url)); // to fill in default values for request objects const root = protobuf.Root.fromJSON( JSON.parse( - fs.readFileSync(path.join(dirname, '..', '..', 'protos/protos.json'), 'utf8') - )) + fs.readFileSync( + path.join(dirname, '..', '..', 'protos/protos.json'), + 'utf8', + ), + ), +); // eslint-disable-next-line @typescript-eslint/no-unused-vars function getTypeDefaultValue(typeName: string, fields: string[]) { - let type = root.lookupType(typeName) as protobuf.Type; - for (const field of fields.slice(0, -1)) { - type = type?.fields[field]?.resolvedType as protobuf.Type; - } - return type?.fields[fields[fields.length - 1]]?.defaultValue ?? null; + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type?.fields[field]?.resolvedType as protobuf.Type; + } + return type?.fields[fields[fields.length - 1]]?.defaultValue ?? null; } function generateSampleMessage(instance: T) { - const filledObject = (instance.constructor as typeof protobuf.Message) - .toObject(instance as protobuf.Message, {defaults: true}); - return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, { defaults: true }); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; } function stubSimpleCall(response?: ResponseType, error?: Error) { - return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); } -function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { - return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +function stubSimpleCallWithCallback( + response?: ResponseType, + error?: Error, +) { + return error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); } -function stubLongRunningCall(response?: ResponseType, callError?: Error, lroError?: Error) { - const innerStub = lroError ? sinon.stub().rejects(lroError) : sinon.stub().resolves([response]); - const mockOperation = { - promise: innerStub, - }; - return callError ? sinon.stub().rejects(callError) : sinon.stub().resolves([mockOperation]); +function stubLongRunningCall( + response?: ResponseType, + callError?: Error, + lroError?: Error, +) { + const innerStub = lroError + ? sinon.stub().rejects(lroError) + : sinon.stub().resolves([response]); + const mockOperation = { + promise: innerStub, + }; + return callError + ? sinon.stub().rejects(callError) + : sinon.stub().resolves([mockOperation]); } -function stubLongRunningCallWithCallback(response?: ResponseType, callError?: Error, lroError?: Error) { - const innerStub = lroError ? sinon.stub().rejects(lroError) : sinon.stub().resolves([response]); - const mockOperation = { - promise: innerStub, - }; - return callError ? sinon.stub().callsArgWith(2, callError) : sinon.stub().callsArgWith(2, null, mockOperation); +function stubLongRunningCallWithCallback( + response?: ResponseType, + callError?: Error, + lroError?: Error, +) { + const innerStub = lroError + ? sinon.stub().rejects(lroError) + : sinon.stub().resolves([response]); + const mockOperation = { + promise: innerStub, + }; + return callError + ? sinon.stub().callsArgWith(2, callError) + : sinon.stub().callsArgWith(2, null, mockOperation); } -function stubPageStreamingCall(responses?: ResponseType[], error?: Error) { - const pagingStub = sinon.stub(); - if (responses) { - for (let i = 0; i < responses.length; ++i) { - pagingStub.onCall(i).callsArgWith(2, null, responses[i]); - } +function stubPageStreamingCall( + responses?: ResponseType[], + error?: Error, +) { + const pagingStub = sinon.stub(); + if (responses) { + for (let i = 0; i < responses.length; ++i) { + pagingStub.onCall(i).callsArgWith(2, null, responses[i]); } - const transformStub = error ? sinon.stub().callsArgWith(2, error) : pagingStub; - const mockStream = new PassThrough({ - objectMode: true, - transform: transformStub, - }); - // trigger as many responses as needed - if (responses) { - for (let i = 0; i < responses.length; ++i) { - setImmediate(() => { mockStream.write({}); }); - } - setImmediate(() => { mockStream.end(); }); - } else { - setImmediate(() => { mockStream.write({}); }); - setImmediate(() => { mockStream.end(); }); + } + const transformStub = error + ? sinon.stub().callsArgWith(2, error) + : pagingStub; + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + // trigger as many responses as needed + if (responses) { + for (let i = 0; i < responses.length; ++i) { + setImmediate(() => { + mockStream.write({}); + }); } - return sinon.stub().returns(mockStream); + setImmediate(() => { + mockStream.end(); + }); + } else { + setImmediate(() => { + mockStream.write({}); + }); + setImmediate(() => { + mockStream.end(); + }); + } + return sinon.stub().returns(mockStream); } -function stubAsyncIterationCall(responses?: ResponseType[], error?: Error) { - let counter = 0; - const asyncIterable = { - [Symbol.asyncIterator]() { - return { - async next() { - if (error) { - return Promise.reject(error); - } - if (counter >= responses!.length) { - return Promise.resolve({done: true, value: undefined}); - } - return Promise.resolve({done: false, value: responses![counter++]}); - } - }; - } - }; - return sinon.stub().returns(asyncIterable); +function stubAsyncIterationCall( + responses?: ResponseType[], + error?: Error, +) { + let counter = 0; + const asyncIterable = { + [Symbol.asyncIterator]() { + return { + async next() { + if (error) { + return Promise.reject(error); + } + if (counter >= responses!.length) { + return Promise.resolve({ done: true, value: undefined }); + } + return Promise.resolve({ done: false, value: responses![counter++] }); + }, + }; + }, + }; + return sinon.stub().returns(asyncIterable); } describe('v2alpha.ModelServiceClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new modelserviceModule.v2alpha.ModelServiceClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'retail.googleapis.com'); - }); - - it('has universeDomain', () => { - const client = new modelserviceModule.v2alpha.ModelServiceClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); - - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - it('throws DeprecationWarning if static servicePath is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const servicePath = modelserviceModule.v2alpha.ModelServiceClient.servicePath; - assert.strictEqual(servicePath, 'retail.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = modelserviceModule.v2alpha.ModelServiceClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'retail.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new modelserviceModule.v2alpha.ModelServiceClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'retail.example.com'); - }); - - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new modelserviceModule.v2alpha.ModelServiceClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'retail.example.com'); - }); - - if (typeof process === 'object' && 'env' in process) { - describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { - it('sets apiEndpoint from environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new modelserviceModule.v2alpha.ModelServiceClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'retail.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - - it('value configured in code has priority over environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new modelserviceModule.v2alpha.ModelServiceClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'retail.configured.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { new modelserviceModule.v2alpha.ModelServiceClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); - - it('has port', () => { - const port = modelserviceModule.v2alpha.ModelServiceClient.port; - assert(port); - assert(typeof port === 'number'); - }); - - it('should create a client with no option', () => { - const client = new modelserviceModule.v2alpha.ModelServiceClient(); - assert(client); - }); - - it('should create a client with gRPC fallback', () => { - const client = new modelserviceModule.v2alpha.ModelServiceClient({ - fallback: true, - }); - assert(client); - }); - - it('has initialize method and supports deferred initialization', async () => { - const client = new modelserviceModule.v2alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.modelServiceStub, undefined); - await client.initialize(); - assert(client.modelServiceStub); - }); - - it('has close method for the initialized client', done => { - const client = new modelserviceModule.v2alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.modelServiceStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new modelserviceModule.v2alpha.ModelServiceClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'retail.googleapis.com'); + }); - it('has close method for the non-initialized client', done => { - const client = new modelserviceModule.v2alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.modelServiceStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('has universeDomain', () => { + const client = new modelserviceModule.v2alpha.ModelServiceClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new modelserviceModule.v2alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); - }); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = + modelserviceModule.v2alpha.ModelServiceClient.servicePath; + assert.strictEqual(servicePath, 'retail.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + modelserviceModule.v2alpha.ModelServiceClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'retail.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = new modelserviceModule.v2alpha.ModelServiceClient({ + universeDomain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'retail.example.com'); + }); - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new modelserviceModule.v2alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId((err?: Error|null, projectId?: string|null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } - }); - }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); - }); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = new modelserviceModule.v2alpha.ModelServiceClient({ + universe_domain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'retail.example.com'); }); - describe('getModel', () => { - it('invokes getModel without error', async () => { - const client = new modelserviceModule.v2alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.GetModelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.GetModelRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.Model() - ); - client.innerApiCalls.getModel = stubSimpleCall(expectedResponse); - const [response] = await client.getModel(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getModel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getModel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + if (typeof process === 'object' && 'env' in process) { + describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { + it('sets apiEndpoint from environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new modelserviceModule.v2alpha.ModelServiceClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'retail.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } + }); + + it('value configured in code has priority over environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new modelserviceModule.v2alpha.ModelServiceClient({ + universeDomain: 'configured.example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'retail.configured.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } + }); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new modelserviceModule.v2alpha.ModelServiceClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); + }); - it('invokes getModel without error using callback', async () => { - const client = new modelserviceModule.v2alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.GetModelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.GetModelRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.Model() - ); - client.innerApiCalls.getModel = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getModel( - request, - (err?: Error|null, result?: protos.google.cloud.retail.v2alpha.IModel|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getModel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getModel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has port', () => { + const port = modelserviceModule.v2alpha.ModelServiceClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('invokes getModel with error', async () => { - const client = new modelserviceModule.v2alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.GetModelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.GetModelRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getModel = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getModel(request), expectedError); - const actualRequest = (client.innerApiCalls.getModel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getModel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('should create a client with no option', () => { + const client = new modelserviceModule.v2alpha.ModelServiceClient(); + assert(client); + }); - it('invokes getModel with closed client', async () => { - const client = new modelserviceModule.v2alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.GetModelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.GetModelRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getModel(request), expectedError); - }); + it('should create a client with gRPC fallback', () => { + const client = new modelserviceModule.v2alpha.ModelServiceClient({ + fallback: true, + }); + assert(client); }); - describe('pauseModel', () => { - it('invokes pauseModel without error', async () => { - const client = new modelserviceModule.v2alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.PauseModelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.PauseModelRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.Model() - ); - client.innerApiCalls.pauseModel = stubSimpleCall(expectedResponse); - const [response] = await client.pauseModel(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.pauseModel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.pauseModel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has initialize method and supports deferred initialization', async () => { + const client = new modelserviceModule.v2alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.modelServiceStub, undefined); + await client.initialize(); + assert(client.modelServiceStub); + }); - it('invokes pauseModel without error using callback', async () => { - const client = new modelserviceModule.v2alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.PauseModelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.PauseModelRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.Model() - ); - client.innerApiCalls.pauseModel = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.pauseModel( - request, - (err?: Error|null, result?: protos.google.cloud.retail.v2alpha.IModel|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.pauseModel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.pauseModel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('has close method for the initialized client', (done) => { + const client = new modelserviceModule.v2alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.modelServiceStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes pauseModel with error', async () => { - const client = new modelserviceModule.v2alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.PauseModelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.PauseModelRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.pauseModel = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.pauseModel(request), expectedError); - const actualRequest = (client.innerApiCalls.pauseModel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.pauseModel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('has close method for the non-initialized client', (done) => { + const client = new modelserviceModule.v2alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.modelServiceStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes pauseModel with closed client', async () => { - const client = new modelserviceModule.v2alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.PauseModelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.PauseModelRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.pauseModel(request), expectedError); - }); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new modelserviceModule.v2alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); }); - describe('resumeModel', () => { - it('invokes resumeModel without error', async () => { - const client = new modelserviceModule.v2alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ResumeModelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ResumeModelRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.Model() - ); - client.innerApiCalls.resumeModel = stubSimpleCall(expectedResponse); - const [response] = await client.resumeModel(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.resumeModel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.resumeModel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new modelserviceModule.v2alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } + }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + }); + + describe('getModel', () => { + it('invokes getModel without error', async () => { + const client = new modelserviceModule.v2alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.GetModelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.GetModelRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.Model(), + ); + client.innerApiCalls.getModel = stubSimpleCall(expectedResponse); + const [response] = await client.getModel(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getModel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getModel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes resumeModel without error using callback', async () => { - const client = new modelserviceModule.v2alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ResumeModelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ResumeModelRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.Model() - ); - client.innerApiCalls.resumeModel = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.resumeModel( - request, - (err?: Error|null, result?: protos.google.cloud.retail.v2alpha.IModel|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.resumeModel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.resumeModel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getModel without error using callback', async () => { + const client = new modelserviceModule.v2alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.GetModelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.GetModelRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.Model(), + ); + client.innerApiCalls.getModel = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getModel( + request, + ( + err?: Error | null, + result?: protos.google.cloud.retail.v2alpha.IModel | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getModel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getModel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes resumeModel with error', async () => { - const client = new modelserviceModule.v2alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ResumeModelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ResumeModelRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.resumeModel = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.resumeModel(request), expectedError); - const actualRequest = (client.innerApiCalls.resumeModel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.resumeModel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getModel with error', async () => { + const client = new modelserviceModule.v2alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.GetModelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.GetModelRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getModel = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.getModel(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getModel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getModel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes resumeModel with closed client', async () => { - const client = new modelserviceModule.v2alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ResumeModelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ResumeModelRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.resumeModel(request), expectedError); - }); + it('invokes getModel with closed client', async () => { + const client = new modelserviceModule.v2alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.GetModelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.GetModelRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getModel(request), expectedError); + }); + }); + + describe('pauseModel', () => { + it('invokes pauseModel without error', async () => { + const client = new modelserviceModule.v2alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.PauseModelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.PauseModelRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.Model(), + ); + client.innerApiCalls.pauseModel = stubSimpleCall(expectedResponse); + const [response] = await client.pauseModel(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.pauseModel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.pauseModel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('deleteModel', () => { - it('invokes deleteModel without error', async () => { - const client = new modelserviceModule.v2alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.DeleteModelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.DeleteModelRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteModel = stubSimpleCall(expectedResponse); - const [response] = await client.deleteModel(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteModel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteModel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes pauseModel without error using callback', async () => { + const client = new modelserviceModule.v2alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.PauseModelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.PauseModelRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.Model(), + ); + client.innerApiCalls.pauseModel = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.pauseModel( + request, + ( + err?: Error | null, + result?: protos.google.cloud.retail.v2alpha.IModel | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.pauseModel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.pauseModel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteModel without error using callback', async () => { - const client = new modelserviceModule.v2alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.DeleteModelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.DeleteModelRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteModel = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteModel( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteModel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteModel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes pauseModel with error', async () => { + const client = new modelserviceModule.v2alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.PauseModelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.PauseModelRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.pauseModel = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.pauseModel(request), expectedError); + const actualRequest = ( + client.innerApiCalls.pauseModel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.pauseModel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteModel with error', async () => { - const client = new modelserviceModule.v2alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.DeleteModelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.DeleteModelRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteModel = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteModel(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteModel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteModel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes pauseModel with closed client', async () => { + const client = new modelserviceModule.v2alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.PauseModelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.PauseModelRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.pauseModel(request), expectedError); + }); + }); + + describe('resumeModel', () => { + it('invokes resumeModel without error', async () => { + const client = new modelserviceModule.v2alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ResumeModelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ResumeModelRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.Model(), + ); + client.innerApiCalls.resumeModel = stubSimpleCall(expectedResponse); + const [response] = await client.resumeModel(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.resumeModel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.resumeModel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteModel with closed client', async () => { - const client = new modelserviceModule.v2alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.DeleteModelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.DeleteModelRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteModel(request), expectedError); - }); + it('invokes resumeModel without error using callback', async () => { + const client = new modelserviceModule.v2alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ResumeModelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ResumeModelRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.Model(), + ); + client.innerApiCalls.resumeModel = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.resumeModel( + request, + ( + err?: Error | null, + result?: protos.google.cloud.retail.v2alpha.IModel | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.resumeModel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.resumeModel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('updateModel', () => { - it('invokes updateModel without error', async () => { - const client = new modelserviceModule.v2alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.UpdateModelRequest() - ); - request.model ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.UpdateModelRequest', ['model', 'name']); - request.model.name = defaultValue1; - const expectedHeaderRequestParams = `model.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.Model() - ); - client.innerApiCalls.updateModel = stubSimpleCall(expectedResponse); - const [response] = await client.updateModel(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateModel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateModel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes resumeModel with error', async () => { + const client = new modelserviceModule.v2alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ResumeModelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ResumeModelRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.resumeModel = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.resumeModel(request), expectedError); + const actualRequest = ( + client.innerApiCalls.resumeModel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.resumeModel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateModel without error using callback', async () => { - const client = new modelserviceModule.v2alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.UpdateModelRequest() - ); - request.model ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.UpdateModelRequest', ['model', 'name']); - request.model.name = defaultValue1; - const expectedHeaderRequestParams = `model.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.Model() - ); - client.innerApiCalls.updateModel = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateModel( - request, - (err?: Error|null, result?: protos.google.cloud.retail.v2alpha.IModel|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateModel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateModel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes resumeModel with closed client', async () => { + const client = new modelserviceModule.v2alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ResumeModelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ResumeModelRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.resumeModel(request), expectedError); + }); + }); + + describe('deleteModel', () => { + it('invokes deleteModel without error', async () => { + const client = new modelserviceModule.v2alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.DeleteModelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.DeleteModelRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteModel = stubSimpleCall(expectedResponse); + const [response] = await client.deleteModel(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteModel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteModel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateModel with error', async () => { - const client = new modelserviceModule.v2alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.UpdateModelRequest() - ); - request.model ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.UpdateModelRequest', ['model', 'name']); - request.model.name = defaultValue1; - const expectedHeaderRequestParams = `model.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateModel = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateModel(request), expectedError); - const actualRequest = (client.innerApiCalls.updateModel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateModel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteModel without error using callback', async () => { + const client = new modelserviceModule.v2alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.DeleteModelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.DeleteModelRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteModel = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteModel( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteModel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteModel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateModel with closed client', async () => { - const client = new modelserviceModule.v2alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.UpdateModelRequest() - ); - request.model ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.UpdateModelRequest', ['model', 'name']); - request.model.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateModel(request), expectedError); - }); + it('invokes deleteModel with error', async () => { + const client = new modelserviceModule.v2alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.DeleteModelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.DeleteModelRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteModel = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.deleteModel(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteModel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteModel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('createModel', () => { - it('invokes createModel without error', async () => { - const client = new modelserviceModule.v2alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.CreateModelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.CreateModelRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.createModel = stubLongRunningCall(expectedResponse); - const [operation] = await client.createModel(request); - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createModel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createModel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteModel with closed client', async () => { + const client = new modelserviceModule.v2alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.DeleteModelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.DeleteModelRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.deleteModel(request), expectedError); + }); + }); + + describe('updateModel', () => { + it('invokes updateModel without error', async () => { + const client = new modelserviceModule.v2alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.UpdateModelRequest(), + ); + request.model ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.UpdateModelRequest', + ['model', 'name'], + ); + request.model.name = defaultValue1; + const expectedHeaderRequestParams = `model.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.Model(), + ); + client.innerApiCalls.updateModel = stubSimpleCall(expectedResponse); + const [response] = await client.updateModel(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateModel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateModel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createModel without error using callback', async () => { - const client = new modelserviceModule.v2alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.CreateModelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.CreateModelRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.createModel = stubLongRunningCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createModel( - request, - (err?: Error|null, - result?: LROperation|null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const operation = await promise as LROperation; - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createModel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createModel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateModel without error using callback', async () => { + const client = new modelserviceModule.v2alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.UpdateModelRequest(), + ); + request.model ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.UpdateModelRequest', + ['model', 'name'], + ); + request.model.name = defaultValue1; + const expectedHeaderRequestParams = `model.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.Model(), + ); + client.innerApiCalls.updateModel = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateModel( + request, + ( + err?: Error | null, + result?: protos.google.cloud.retail.v2alpha.IModel | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateModel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateModel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createModel with call error', async () => { - const client = new modelserviceModule.v2alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.CreateModelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.CreateModelRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createModel = stubLongRunningCall(undefined, expectedError); - await assert.rejects(client.createModel(request), expectedError); - const actualRequest = (client.innerApiCalls.createModel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createModel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateModel with error', async () => { + const client = new modelserviceModule.v2alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.UpdateModelRequest(), + ); + request.model ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.UpdateModelRequest', + ['model', 'name'], + ); + request.model.name = defaultValue1; + const expectedHeaderRequestParams = `model.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateModel = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.updateModel(request), expectedError); + const actualRequest = ( + client.innerApiCalls.updateModel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateModel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createModel with LRO error', async () => { - const client = new modelserviceModule.v2alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.CreateModelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.CreateModelRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createModel = stubLongRunningCall(undefined, undefined, expectedError); - const [operation] = await client.createModel(request); - await assert.rejects(operation.promise(), expectedError); - const actualRequest = (client.innerApiCalls.createModel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createModel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateModel with closed client', async () => { + const client = new modelserviceModule.v2alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.UpdateModelRequest(), + ); + request.model ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.UpdateModelRequest', + ['model', 'name'], + ); + request.model.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.updateModel(request), expectedError); + }); + }); + + describe('createModel', () => { + it('invokes createModel without error', async () => { + const client = new modelserviceModule.v2alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.CreateModelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.CreateModelRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.createModel = stubLongRunningCall(expectedResponse); + const [operation] = await client.createModel(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createModel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createModel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkCreateModelProgress without error', async () => { - const client = new modelserviceModule.v2alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedResponse = generateSampleMessage( - new operationsProtos.google.longrunning.Operation() - ); - expectedResponse.name = 'test'; - expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; - expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')} - - client.operationsClient.getOperation = stubSimpleCall(expectedResponse); - const decodedOperation = await client.checkCreateModelProgress(expectedResponse.name); - assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); - assert(decodedOperation.metadata); - assert((client.operationsClient.getOperation as SinonStub).getCall(0)); - }); + it('invokes createModel without error using callback', async () => { + const client = new modelserviceModule.v2alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.CreateModelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.CreateModelRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.createModel = + stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createModel( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.cloud.retail.v2alpha.IModel, + protos.google.cloud.retail.v2alpha.ICreateModelMetadata + > | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const operation = (await promise) as LROperation< + protos.google.cloud.retail.v2alpha.IModel, + protos.google.cloud.retail.v2alpha.ICreateModelMetadata + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createModel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createModel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkCreateModelProgress with error', async () => { - const client = new modelserviceModule.v2alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedError = new Error('expected'); - - client.operationsClient.getOperation = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.checkCreateModelProgress(''), expectedError); - assert((client.operationsClient.getOperation as SinonStub) - .getCall(0)); - }); + it('invokes createModel with call error', async () => { + const client = new modelserviceModule.v2alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.CreateModelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.CreateModelRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createModel = stubLongRunningCall( + undefined, + expectedError, + ); + await assert.rejects(client.createModel(request), expectedError); + const actualRequest = ( + client.innerApiCalls.createModel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createModel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('tuneModel', () => { - it('invokes tuneModel without error', async () => { - const client = new modelserviceModule.v2alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.TuneModelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.TuneModelRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.tuneModel = stubLongRunningCall(expectedResponse); - const [operation] = await client.tuneModel(request); - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.tuneModel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.tuneModel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createModel with LRO error', async () => { + const client = new modelserviceModule.v2alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.CreateModelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.CreateModelRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createModel = stubLongRunningCall( + undefined, + undefined, + expectedError, + ); + const [operation] = await client.createModel(request); + await assert.rejects(operation.promise(), expectedError); + const actualRequest = ( + client.innerApiCalls.createModel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createModel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes tuneModel without error using callback', async () => { - const client = new modelserviceModule.v2alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.TuneModelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.TuneModelRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.tuneModel = stubLongRunningCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.tuneModel( - request, - (err?: Error|null, - result?: LROperation|null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const operation = await promise as LROperation; - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.tuneModel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.tuneModel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes checkCreateModelProgress without error', async () => { + const client = new modelserviceModule.v2alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation(), + ); + expectedResponse.name = 'test'; + expectedResponse.response = { type_url: 'url', value: Buffer.from('') }; + expectedResponse.metadata = { type_url: 'url', value: Buffer.from('') }; + + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const decodedOperation = await client.checkCreateModelProgress( + expectedResponse.name, + ); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); - it('invokes tuneModel with call error', async () => { - const client = new modelserviceModule.v2alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.TuneModelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.TuneModelRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.tuneModel = stubLongRunningCall(undefined, expectedError); - await assert.rejects(client.tuneModel(request), expectedError); - const actualRequest = (client.innerApiCalls.tuneModel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.tuneModel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes checkCreateModelProgress with error', async () => { + const client = new modelserviceModule.v2alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const expectedError = new Error('expected'); + + client.operationsClient.getOperation = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.checkCreateModelProgress(''), expectedError); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + }); + + describe('tuneModel', () => { + it('invokes tuneModel without error', async () => { + const client = new modelserviceModule.v2alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.TuneModelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.TuneModelRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.tuneModel = stubLongRunningCall(expectedResponse); + const [operation] = await client.tuneModel(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.tuneModel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.tuneModel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes tuneModel with LRO error', async () => { - const client = new modelserviceModule.v2alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.TuneModelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.TuneModelRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.tuneModel = stubLongRunningCall(undefined, undefined, expectedError); - const [operation] = await client.tuneModel(request); - await assert.rejects(operation.promise(), expectedError); - const actualRequest = (client.innerApiCalls.tuneModel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.tuneModel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes tuneModel without error using callback', async () => { + const client = new modelserviceModule.v2alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.TuneModelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.TuneModelRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.tuneModel = + stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.tuneModel( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.cloud.retail.v2alpha.ITuneModelResponse, + protos.google.cloud.retail.v2alpha.ITuneModelMetadata + > | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const operation = (await promise) as LROperation< + protos.google.cloud.retail.v2alpha.ITuneModelResponse, + protos.google.cloud.retail.v2alpha.ITuneModelMetadata + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.tuneModel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.tuneModel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkTuneModelProgress without error', async () => { - const client = new modelserviceModule.v2alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedResponse = generateSampleMessage( - new operationsProtos.google.longrunning.Operation() - ); - expectedResponse.name = 'test'; - expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; - expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')} - - client.operationsClient.getOperation = stubSimpleCall(expectedResponse); - const decodedOperation = await client.checkTuneModelProgress(expectedResponse.name); - assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); - assert(decodedOperation.metadata); - assert((client.operationsClient.getOperation as SinonStub).getCall(0)); - }); + it('invokes tuneModel with call error', async () => { + const client = new modelserviceModule.v2alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.TuneModelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.TuneModelRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.tuneModel = stubLongRunningCall( + undefined, + expectedError, + ); + await assert.rejects(client.tuneModel(request), expectedError); + const actualRequest = ( + client.innerApiCalls.tuneModel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.tuneModel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkTuneModelProgress with error', async () => { - const client = new modelserviceModule.v2alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedError = new Error('expected'); - - client.operationsClient.getOperation = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.checkTuneModelProgress(''), expectedError); - assert((client.operationsClient.getOperation as SinonStub) - .getCall(0)); - }); + it('invokes tuneModel with LRO error', async () => { + const client = new modelserviceModule.v2alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.TuneModelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.TuneModelRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.tuneModel = stubLongRunningCall( + undefined, + undefined, + expectedError, + ); + const [operation] = await client.tuneModel(request); + await assert.rejects(operation.promise(), expectedError); + const actualRequest = ( + client.innerApiCalls.tuneModel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.tuneModel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('listModels', () => { - it('invokes listModels without error', async () => { - const client = new modelserviceModule.v2alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ListModelsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ListModelsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.retail.v2alpha.Model()), - generateSampleMessage(new protos.google.cloud.retail.v2alpha.Model()), - generateSampleMessage(new protos.google.cloud.retail.v2alpha.Model()), - ]; - client.innerApiCalls.listModels = stubSimpleCall(expectedResponse); - const [response] = await client.listModels(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listModels as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listModels as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes checkTuneModelProgress without error', async () => { + const client = new modelserviceModule.v2alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation(), + ); + expectedResponse.name = 'test'; + expectedResponse.response = { type_url: 'url', value: Buffer.from('') }; + expectedResponse.metadata = { type_url: 'url', value: Buffer.from('') }; + + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const decodedOperation = await client.checkTuneModelProgress( + expectedResponse.name, + ); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); - it('invokes listModels without error using callback', async () => { - const client = new modelserviceModule.v2alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ListModelsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ListModelsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.retail.v2alpha.Model()), - generateSampleMessage(new protos.google.cloud.retail.v2alpha.Model()), - generateSampleMessage(new protos.google.cloud.retail.v2alpha.Model()), - ]; - client.innerApiCalls.listModels = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listModels( - request, - (err?: Error|null, result?: protos.google.cloud.retail.v2alpha.IModel[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listModels as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listModels as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes checkTuneModelProgress with error', async () => { + const client = new modelserviceModule.v2alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const expectedError = new Error('expected'); + + client.operationsClient.getOperation = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.checkTuneModelProgress(''), expectedError); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + }); + + describe('listModels', () => { + it('invokes listModels without error', async () => { + const client = new modelserviceModule.v2alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ListModelsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ListModelsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.retail.v2alpha.Model()), + generateSampleMessage(new protos.google.cloud.retail.v2alpha.Model()), + generateSampleMessage(new protos.google.cloud.retail.v2alpha.Model()), + ]; + client.innerApiCalls.listModels = stubSimpleCall(expectedResponse); + const [response] = await client.listModels(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listModels as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listModels as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listModels with error', async () => { - const client = new modelserviceModule.v2alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ListModelsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ListModelsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listModels = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listModels(request), expectedError); - const actualRequest = (client.innerApiCalls.listModels as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listModels as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listModels without error using callback', async () => { + const client = new modelserviceModule.v2alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ListModelsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ListModelsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.retail.v2alpha.Model()), + generateSampleMessage(new protos.google.cloud.retail.v2alpha.Model()), + generateSampleMessage(new protos.google.cloud.retail.v2alpha.Model()), + ]; + client.innerApiCalls.listModels = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listModels( + request, + ( + err?: Error | null, + result?: protos.google.cloud.retail.v2alpha.IModel[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listModels as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listModels as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listModelsStream without error', async () => { - const client = new modelserviceModule.v2alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ListModelsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ListModelsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.retail.v2alpha.Model()), - generateSampleMessage(new protos.google.cloud.retail.v2alpha.Model()), - generateSampleMessage(new protos.google.cloud.retail.v2alpha.Model()), - ]; - client.descriptors.page.listModels.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listModelsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.cloud.retail.v2alpha.Model[] = []; - stream.on('data', (response: protos.google.cloud.retail.v2alpha.Model) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.listModels.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listModels, request)); - assert( - (client.descriptors.page.listModels.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listModels with error', async () => { + const client = new modelserviceModule.v2alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ListModelsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ListModelsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listModels = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listModels(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listModels as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listModels as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listModelsStream with error', async () => { - const client = new modelserviceModule.v2alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ListModelsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ListModelsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listModels.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listModelsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.cloud.retail.v2alpha.Model[] = []; - stream.on('data', (response: protos.google.cloud.retail.v2alpha.Model) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listModels.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listModels, request)); - assert( - (client.descriptors.page.listModels.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listModelsStream without error', async () => { + const client = new modelserviceModule.v2alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ListModelsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ListModelsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.retail.v2alpha.Model()), + generateSampleMessage(new protos.google.cloud.retail.v2alpha.Model()), + generateSampleMessage(new protos.google.cloud.retail.v2alpha.Model()), + ]; + client.descriptors.page.listModels.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listModelsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.cloud.retail.v2alpha.Model[] = []; + stream.on( + 'data', + (response: protos.google.cloud.retail.v2alpha.Model) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listModels.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listModels, request), + ); + assert( + (client.descriptors.page.listModels.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('uses async iteration with listModels without error', async () => { - const client = new modelserviceModule.v2alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ListModelsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ListModelsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.retail.v2alpha.Model()), - generateSampleMessage(new protos.google.cloud.retail.v2alpha.Model()), - generateSampleMessage(new protos.google.cloud.retail.v2alpha.Model()), - ]; - client.descriptors.page.listModels.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.cloud.retail.v2alpha.IModel[] = []; - const iterable = client.listModelsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listModels.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listModels.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listModelsStream with error', async () => { + const client = new modelserviceModule.v2alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ListModelsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ListModelsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listModels.createStream = stubPageStreamingCall( + undefined, + expectedError, + ); + const stream = client.listModelsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.cloud.retail.v2alpha.Model[] = []; + stream.on( + 'data', + (response: protos.google.cloud.retail.v2alpha.Model) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listModels.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listModels, request), + ); + assert( + (client.descriptors.page.listModels.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('uses async iteration with listModels with error', async () => { - const client = new modelserviceModule.v2alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ListModelsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ListModelsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listModels.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listModelsAsync(request); - await assert.rejects(async () => { - const responses: protos.google.cloud.retail.v2alpha.IModel[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listModels.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listModels.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listModels without error', async () => { + const client = new modelserviceModule.v2alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ListModelsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ListModelsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.retail.v2alpha.Model()), + generateSampleMessage(new protos.google.cloud.retail.v2alpha.Model()), + generateSampleMessage(new protos.google.cloud.retail.v2alpha.Model()), + ]; + client.descriptors.page.listModels.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.cloud.retail.v2alpha.IModel[] = []; + const iterable = client.listModelsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + (client.descriptors.page.listModels.asyncIterate as SinonStub).getCall( + 0, + ).args[1], + request, + ); + assert( + (client.descriptors.page.listModels.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); }); - describe('Path templates', () => { - - describe('alertConfig', () => { - const fakePath = "/rendered/path/alertConfig"; - const expectedParameters = { - project: "projectValue", - }; - const client = new modelserviceModule.v2alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.alertConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.alertConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('alertConfigPath', () => { - const result = client.alertConfigPath("projectValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.alertConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromAlertConfigName', () => { - const result = client.matchProjectFromAlertConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.alertConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('uses async iteration with listModels with error', async () => { + const client = new modelserviceModule.v2alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ListModelsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ListModelsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listModels.asyncIterate = stubAsyncIterationCall( + undefined, + expectedError, + ); + const iterable = client.listModelsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.cloud.retail.v2alpha.IModel[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + (client.descriptors.page.listModels.asyncIterate as SinonStub).getCall( + 0, + ).args[1], + request, + ); + assert( + (client.descriptors.page.listModels.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + }); + + describe('Path templates', () => { + describe('alertConfig', () => { + const fakePath = '/rendered/path/alertConfig'; + const expectedParameters = { + project: 'projectValue', + }; + const client = new modelserviceModule.v2alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.alertConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.alertConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('alertConfigPath', () => { + const result = client.alertConfigPath('projectValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.alertConfigPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromAlertConfigName', () => { + const result = client.matchProjectFromAlertConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.alertConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('attributesConfig', () => { - const fakePath = "/rendered/path/attributesConfig"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - }; - const client = new modelserviceModule.v2alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.attributesConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.attributesConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('attributesConfigPath', () => { - const result = client.attributesConfigPath("projectValue", "locationValue", "catalogValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.attributesConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromAttributesConfigName', () => { - const result = client.matchProjectFromAttributesConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromAttributesConfigName', () => { - const result = client.matchLocationFromAttributesConfigName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromAttributesConfigName', () => { - const result = client.matchCatalogFromAttributesConfigName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('attributesConfig', () => { + const fakePath = '/rendered/path/attributesConfig'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + }; + const client = new modelserviceModule.v2alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.attributesConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.attributesConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('attributesConfigPath', () => { + const result = client.attributesConfigPath( + 'projectValue', + 'locationValue', + 'catalogValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.attributesConfigPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromAttributesConfigName', () => { + const result = client.matchProjectFromAttributesConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromAttributesConfigName', () => { + const result = client.matchLocationFromAttributesConfigName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromAttributesConfigName', () => { + const result = client.matchCatalogFromAttributesConfigName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('branch', () => { - const fakePath = "/rendered/path/branch"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - branch: "branchValue", - }; - const client = new modelserviceModule.v2alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.branchPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.branchPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('branchPath', () => { - const result = client.branchPath("projectValue", "locationValue", "catalogValue", "branchValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.branchPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromBranchName', () => { - const result = client.matchProjectFromBranchName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.branchPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromBranchName', () => { - const result = client.matchLocationFromBranchName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.branchPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromBranchName', () => { - const result = client.matchCatalogFromBranchName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.branchPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBranchFromBranchName', () => { - const result = client.matchBranchFromBranchName(fakePath); - assert.strictEqual(result, "branchValue"); - assert((client.pathTemplates.branchPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('branch', () => { + const fakePath = '/rendered/path/branch'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + branch: 'branchValue', + }; + const client = new modelserviceModule.v2alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.branchPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.branchPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('branchPath', () => { + const result = client.branchPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'branchValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.branchPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromBranchName', () => { + const result = client.matchProjectFromBranchName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.branchPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromBranchName', () => { + const result = client.matchLocationFromBranchName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.branchPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromBranchName', () => { + const result = client.matchCatalogFromBranchName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.branchPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBranchFromBranchName', () => { + const result = client.matchBranchFromBranchName(fakePath); + assert.strictEqual(result, 'branchValue'); + assert( + (client.pathTemplates.branchPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('catalog', () => { - const fakePath = "/rendered/path/catalog"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - }; - const client = new modelserviceModule.v2alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.catalogPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.catalogPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('catalogPath', () => { - const result = client.catalogPath("projectValue", "locationValue", "catalogValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.catalogPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromCatalogName', () => { - const result = client.matchProjectFromCatalogName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.catalogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromCatalogName', () => { - const result = client.matchLocationFromCatalogName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.catalogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromCatalogName', () => { - const result = client.matchCatalogFromCatalogName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.catalogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('catalog', () => { + const fakePath = '/rendered/path/catalog'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + }; + const client = new modelserviceModule.v2alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.catalogPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.catalogPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('catalogPath', () => { + const result = client.catalogPath( + 'projectValue', + 'locationValue', + 'catalogValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.catalogPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromCatalogName', () => { + const result = client.matchProjectFromCatalogName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.catalogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromCatalogName', () => { + const result = client.matchLocationFromCatalogName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.catalogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromCatalogName', () => { + const result = client.matchCatalogFromCatalogName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.catalogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('completionConfig', () => { - const fakePath = "/rendered/path/completionConfig"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - }; - const client = new modelserviceModule.v2alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.completionConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.completionConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('completionConfigPath', () => { - const result = client.completionConfigPath("projectValue", "locationValue", "catalogValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.completionConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromCompletionConfigName', () => { - const result = client.matchProjectFromCompletionConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.completionConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromCompletionConfigName', () => { - const result = client.matchLocationFromCompletionConfigName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.completionConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromCompletionConfigName', () => { - const result = client.matchCatalogFromCompletionConfigName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.completionConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('completionConfig', () => { + const fakePath = '/rendered/path/completionConfig'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + }; + const client = new modelserviceModule.v2alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.completionConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.completionConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('completionConfigPath', () => { + const result = client.completionConfigPath( + 'projectValue', + 'locationValue', + 'catalogValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.completionConfigPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromCompletionConfigName', () => { + const result = client.matchProjectFromCompletionConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.completionConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromCompletionConfigName', () => { + const result = client.matchLocationFromCompletionConfigName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.completionConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromCompletionConfigName', () => { + const result = client.matchCatalogFromCompletionConfigName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.completionConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('control', () => { - const fakePath = "/rendered/path/control"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - control: "controlValue", - }; - const client = new modelserviceModule.v2alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.controlPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.controlPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('controlPath', () => { - const result = client.controlPath("projectValue", "locationValue", "catalogValue", "controlValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.controlPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromControlName', () => { - const result = client.matchProjectFromControlName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.controlPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromControlName', () => { - const result = client.matchLocationFromControlName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.controlPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromControlName', () => { - const result = client.matchCatalogFromControlName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.controlPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchControlFromControlName', () => { - const result = client.matchControlFromControlName(fakePath); - assert.strictEqual(result, "controlValue"); - assert((client.pathTemplates.controlPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('control', () => { + const fakePath = '/rendered/path/control'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + control: 'controlValue', + }; + const client = new modelserviceModule.v2alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.controlPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.controlPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('controlPath', () => { + const result = client.controlPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'controlValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.controlPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromControlName', () => { + const result = client.matchProjectFromControlName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.controlPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromControlName', () => { + const result = client.matchLocationFromControlName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.controlPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromControlName', () => { + const result = client.matchCatalogFromControlName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.controlPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchControlFromControlName', () => { + const result = client.matchControlFromControlName(fakePath); + assert.strictEqual(result, 'controlValue'); + assert( + (client.pathTemplates.controlPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('loggingConfig', () => { - const fakePath = "/rendered/path/loggingConfig"; - const expectedParameters = { - project: "projectValue", - }; - const client = new modelserviceModule.v2alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.loggingConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.loggingConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('loggingConfigPath', () => { - const result = client.loggingConfigPath("projectValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.loggingConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromLoggingConfigName', () => { - const result = client.matchProjectFromLoggingConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.loggingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('loggingConfig', () => { + const fakePath = '/rendered/path/loggingConfig'; + const expectedParameters = { + project: 'projectValue', + }; + const client = new modelserviceModule.v2alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.loggingConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.loggingConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('loggingConfigPath', () => { + const result = client.loggingConfigPath('projectValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.loggingConfigPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromLoggingConfigName', () => { + const result = client.matchProjectFromLoggingConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.loggingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('merchantCenterAccountLink', () => { - const fakePath = "/rendered/path/merchantCenterAccountLink"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - merchant_center_account_link: "merchantCenterAccountLinkValue", - }; - const client = new modelserviceModule.v2alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.merchantCenterAccountLinkPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.merchantCenterAccountLinkPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('merchantCenterAccountLinkPath', () => { - const result = client.merchantCenterAccountLinkPath("projectValue", "locationValue", "catalogValue", "merchantCenterAccountLinkValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromMerchantCenterAccountLinkName', () => { - const result = client.matchProjectFromMerchantCenterAccountLinkName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromMerchantCenterAccountLinkName', () => { - const result = client.matchLocationFromMerchantCenterAccountLinkName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromMerchantCenterAccountLinkName', () => { - const result = client.matchCatalogFromMerchantCenterAccountLinkName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName', () => { - const result = client.matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName(fakePath); - assert.strictEqual(result, "merchantCenterAccountLinkValue"); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('merchantCenterAccountLink', () => { + const fakePath = '/rendered/path/merchantCenterAccountLink'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + merchant_center_account_link: 'merchantCenterAccountLinkValue', + }; + const client = new modelserviceModule.v2alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.merchantCenterAccountLinkPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.merchantCenterAccountLinkPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('merchantCenterAccountLinkPath', () => { + const result = client.merchantCenterAccountLinkPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'merchantCenterAccountLinkValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromMerchantCenterAccountLinkName', () => { + const result = + client.matchProjectFromMerchantCenterAccountLinkName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromMerchantCenterAccountLinkName', () => { + const result = + client.matchLocationFromMerchantCenterAccountLinkName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromMerchantCenterAccountLinkName', () => { + const result = + client.matchCatalogFromMerchantCenterAccountLinkName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName', () => { + const result = + client.matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName( + fakePath, + ); + assert.strictEqual(result, 'merchantCenterAccountLinkValue'); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('model', () => { - const fakePath = "/rendered/path/model"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - model: "modelValue", - }; - const client = new modelserviceModule.v2alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.modelPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.modelPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('modelPath', () => { - const result = client.modelPath("projectValue", "locationValue", "catalogValue", "modelValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.modelPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromModelName', () => { - const result = client.matchProjectFromModelName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromModelName', () => { - const result = client.matchLocationFromModelName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromModelName', () => { - const result = client.matchCatalogFromModelName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchModelFromModelName', () => { - const result = client.matchModelFromModelName(fakePath); - assert.strictEqual(result, "modelValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('model', () => { + const fakePath = '/rendered/path/model'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + model: 'modelValue', + }; + const client = new modelserviceModule.v2alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.modelPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.modelPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('modelPath', () => { + const result = client.modelPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'modelValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.modelPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromModelName', () => { + const result = client.matchProjectFromModelName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromModelName', () => { + const result = client.matchLocationFromModelName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromModelName', () => { + const result = client.matchCatalogFromModelName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchModelFromModelName', () => { + const result = client.matchModelFromModelName(fakePath); + assert.strictEqual(result, 'modelValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('product', () => { - const fakePath = "/rendered/path/product"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - branch: "branchValue", - product: "productValue", - }; - const client = new modelserviceModule.v2alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.productPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.productPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('productPath', () => { - const result = client.productPath("projectValue", "locationValue", "catalogValue", "branchValue", "productValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.productPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProductName', () => { - const result = client.matchProjectFromProductName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromProductName', () => { - const result = client.matchLocationFromProductName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromProductName', () => { - const result = client.matchCatalogFromProductName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBranchFromProductName', () => { - const result = client.matchBranchFromProductName(fakePath); - assert.strictEqual(result, "branchValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchProductFromProductName', () => { - const result = client.matchProductFromProductName(fakePath); - assert.strictEqual(result, "productValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('product', () => { + const fakePath = '/rendered/path/product'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + branch: 'branchValue', + product: 'productValue', + }; + const client = new modelserviceModule.v2alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.productPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.productPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('productPath', () => { + const result = client.productPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'branchValue', + 'productValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.productPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProductName', () => { + const result = client.matchProjectFromProductName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromProductName', () => { + const result = client.matchLocationFromProductName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromProductName', () => { + const result = client.matchCatalogFromProductName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBranchFromProductName', () => { + const result = client.matchBranchFromProductName(fakePath); + assert.strictEqual(result, 'branchValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchProductFromProductName', () => { + const result = client.matchProductFromProductName(fakePath); + assert.strictEqual(result, 'productValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('retailProject', () => { - const fakePath = "/rendered/path/retailProject"; - const expectedParameters = { - project: "projectValue", - }; - const client = new modelserviceModule.v2alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.retailProjectPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.retailProjectPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('retailProjectPath', () => { - const result = client.retailProjectPath("projectValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.retailProjectPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromRetailProjectName', () => { - const result = client.matchProjectFromRetailProjectName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.retailProjectPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('retailProject', () => { + const fakePath = '/rendered/path/retailProject'; + const expectedParameters = { + project: 'projectValue', + }; + const client = new modelserviceModule.v2alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.retailProjectPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.retailProjectPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('retailProjectPath', () => { + const result = client.retailProjectPath('projectValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.retailProjectPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromRetailProjectName', () => { + const result = client.matchProjectFromRetailProjectName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.retailProjectPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('servingConfig', () => { - const fakePath = "/rendered/path/servingConfig"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - serving_config: "servingConfigValue", - }; - const client = new modelserviceModule.v2alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.servingConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.servingConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('servingConfigPath', () => { - const result = client.servingConfigPath("projectValue", "locationValue", "catalogValue", "servingConfigValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.servingConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromServingConfigName', () => { - const result = client.matchProjectFromServingConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.servingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromServingConfigName', () => { - const result = client.matchLocationFromServingConfigName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.servingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromServingConfigName', () => { - const result = client.matchCatalogFromServingConfigName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.servingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServingConfigFromServingConfigName', () => { - const result = client.matchServingConfigFromServingConfigName(fakePath); - assert.strictEqual(result, "servingConfigValue"); - assert((client.pathTemplates.servingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('servingConfig', () => { + const fakePath = '/rendered/path/servingConfig'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + serving_config: 'servingConfigValue', + }; + const client = new modelserviceModule.v2alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.servingConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.servingConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('servingConfigPath', () => { + const result = client.servingConfigPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'servingConfigValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.servingConfigPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromServingConfigName', () => { + const result = client.matchProjectFromServingConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.servingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromServingConfigName', () => { + const result = client.matchLocationFromServingConfigName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.servingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromServingConfigName', () => { + const result = client.matchCatalogFromServingConfigName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.servingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServingConfigFromServingConfigName', () => { + const result = client.matchServingConfigFromServingConfigName(fakePath); + assert.strictEqual(result, 'servingConfigValue'); + assert( + (client.pathTemplates.servingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/test/gapic_prediction_service_v2alpha.ts.baseline b/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/test/gapic_prediction_service_v2alpha.ts.baseline index eca48b4b3719..1ffbab95c9c1 100644 --- a/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/test/gapic_prediction_service_v2alpha.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/test/gapic_prediction_service_v2alpha.ts.baseline @@ -20,14 +20,14 @@ import * as protos from '../../protos/protos.js'; import assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as predictionserviceModule from '../src/index.js'; -import {protobuf} from 'google-gax'; +import { protobuf } from 'google-gax'; import fs from 'fs'; import path from 'path'; -import {fileURLToPath} from 'url'; +import { fileURLToPath } from 'url'; // @ts-ignore const dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -35,860 +35,1218 @@ const dirname = path.dirname(fileURLToPath(import.meta.url)); // to fill in default values for request objects const root = protobuf.Root.fromJSON( JSON.parse( - fs.readFileSync(path.join(dirname, '..', '..', 'protos/protos.json'), 'utf8') - )) + fs.readFileSync( + path.join(dirname, '..', '..', 'protos/protos.json'), + 'utf8', + ), + ), +); // eslint-disable-next-line @typescript-eslint/no-unused-vars function getTypeDefaultValue(typeName: string, fields: string[]) { - let type = root.lookupType(typeName) as protobuf.Type; - for (const field of fields.slice(0, -1)) { - type = type?.fields[field]?.resolvedType as protobuf.Type; - } - return type?.fields[fields[fields.length - 1]]?.defaultValue ?? null; + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type?.fields[field]?.resolvedType as protobuf.Type; + } + return type?.fields[fields[fields.length - 1]]?.defaultValue ?? null; } function generateSampleMessage(instance: T) { - const filledObject = (instance.constructor as typeof protobuf.Message) - .toObject(instance as protobuf.Message, {defaults: true}); - return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, { defaults: true }); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; } function stubSimpleCall(response?: ResponseType, error?: Error) { - return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); } -function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { - return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +function stubSimpleCallWithCallback( + response?: ResponseType, + error?: Error, +) { + return error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); } describe('v2alpha.PredictionServiceClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new predictionserviceModule.v2alpha.PredictionServiceClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'retail.googleapis.com'); - }); - - it('has universeDomain', () => { - const client = new predictionserviceModule.v2alpha.PredictionServiceClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = + new predictionserviceModule.v2alpha.PredictionServiceClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'retail.googleapis.com'); + }); - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - it('throws DeprecationWarning if static servicePath is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const servicePath = predictionserviceModule.v2alpha.PredictionServiceClient.servicePath; - assert.strictEqual(servicePath, 'retail.googleapis.com'); - assert(stub.called); - stub.restore(); - }); + it('has universeDomain', () => { + const client = + new predictionserviceModule.v2alpha.PredictionServiceClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = predictionserviceModule.v2alpha.PredictionServiceClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'retail.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new predictionserviceModule.v2alpha.PredictionServiceClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'retail.example.com'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = + predictionserviceModule.v2alpha.PredictionServiceClient.servicePath; + assert.strictEqual(servicePath, 'retail.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + predictionserviceModule.v2alpha.PredictionServiceClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'retail.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = + new predictionserviceModule.v2alpha.PredictionServiceClient({ + universeDomain: 'example.com', }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'retail.example.com'); + }); - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new predictionserviceModule.v2alpha.PredictionServiceClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'retail.example.com'); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = + new predictionserviceModule.v2alpha.PredictionServiceClient({ + universe_domain: 'example.com', }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'retail.example.com'); + }); - if (typeof process === 'object' && 'env' in process) { - describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { - it('sets apiEndpoint from environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new predictionserviceModule.v2alpha.PredictionServiceClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'retail.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - - it('value configured in code has priority over environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new predictionserviceModule.v2alpha.PredictionServiceClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'retail.configured.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { new predictionserviceModule.v2alpha.PredictionServiceClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); + if (typeof process === 'object' && 'env' in process) { + describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { + it('sets apiEndpoint from environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = + new predictionserviceModule.v2alpha.PredictionServiceClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'retail.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - it('has port', () => { - const port = predictionserviceModule.v2alpha.PredictionServiceClient.port; - assert(port); - assert(typeof port === 'number'); + it('value configured in code has priority over environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = + new predictionserviceModule.v2alpha.PredictionServiceClient({ + universeDomain: 'configured.example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'retail.configured.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - - it('should create a client with no option', () => { - const client = new predictionserviceModule.v2alpha.PredictionServiceClient(); - assert(client); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new predictionserviceModule.v2alpha.PredictionServiceClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); + }); - it('should create a client with gRPC fallback', () => { - const client = new predictionserviceModule.v2alpha.PredictionServiceClient({ - fallback: true, - }); - assert(client); - }); + it('has port', () => { + const port = predictionserviceModule.v2alpha.PredictionServiceClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('has initialize method and supports deferred initialization', async () => { - const client = new predictionserviceModule.v2alpha.PredictionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.predictionServiceStub, undefined); - await client.initialize(); - assert(client.predictionServiceStub); - }); + it('should create a client with no option', () => { + const client = + new predictionserviceModule.v2alpha.PredictionServiceClient(); + assert(client); + }); - it('has close method for the initialized client', done => { - const client = new predictionserviceModule.v2alpha.PredictionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.predictionServiceStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); + it('should create a client with gRPC fallback', () => { + const client = + new predictionserviceModule.v2alpha.PredictionServiceClient({ + fallback: true, }); + assert(client); + }); - it('has close method for the non-initialized client', done => { - const client = new predictionserviceModule.v2alpha.PredictionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.predictionServiceStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); + it('has initialize method and supports deferred initialization', async () => { + const client = + new predictionserviceModule.v2alpha.PredictionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + assert.strictEqual(client.predictionServiceStub, undefined); + await client.initialize(); + assert(client.predictionServiceStub); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new predictionserviceModule.v2alpha.PredictionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + it('has close method for the initialized client', (done) => { + const client = + new predictionserviceModule.v2alpha.PredictionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); - - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new predictionserviceModule.v2alpha.PredictionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId((err?: Error|null, projectId?: string|null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } - }); - }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); + client.initialize().catch((err) => { + throw err; + }); + assert(client.predictionServiceStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); }); - describe('predict', () => { - it('invokes predict without error', async () => { - const client = new predictionserviceModule.v2alpha.PredictionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.PredictRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.PredictRequest', ['placement']); - request.placement = defaultValue1; - const expectedHeaderRequestParams = `placement=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.PredictResponse() - ); - client.innerApiCalls.predict = stubSimpleCall(expectedResponse); - const [response] = await client.predict(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.predict as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.predict as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('has close method for the non-initialized client', (done) => { + const client = + new predictionserviceModule.v2alpha.PredictionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); - - it('invokes predict without error using callback', async () => { - const client = new predictionserviceModule.v2alpha.PredictionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.PredictRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.PredictRequest', ['placement']); - request.placement = defaultValue1; - const expectedHeaderRequestParams = `placement=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.PredictResponse() - ); - client.innerApiCalls.predict = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.predict( - request, - (err?: Error|null, result?: protos.google.cloud.retail.v2alpha.IPredictResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.predict as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.predict as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + assert.strictEqual(client.predictionServiceStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes predict with error', async () => { - const client = new predictionserviceModule.v2alpha.PredictionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.PredictRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.PredictRequest', ['placement']); - request.placement = defaultValue1; - const expectedHeaderRequestParams = `placement=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.predict = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.predict(request), expectedError); - const actualRequest = (client.innerApiCalls.predict as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.predict as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = + new predictionserviceModule.v2alpha.PredictionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + }); - it('invokes predict with closed client', async () => { - const client = new predictionserviceModule.v2alpha.PredictionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.PredictRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.PredictRequest', ['placement']); - request.placement = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.predict(request), expectedError); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = + new predictionserviceModule.v2alpha.PredictionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } + }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); }); - - describe('Path templates', () => { - - describe('alertConfig', () => { - const fakePath = "/rendered/path/alertConfig"; - const expectedParameters = { - project: "projectValue", - }; - const client = new predictionserviceModule.v2alpha.PredictionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.alertConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.alertConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('alertConfigPath', () => { - const result = client.alertConfigPath("projectValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.alertConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromAlertConfigName', () => { - const result = client.matchProjectFromAlertConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.alertConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + }); + + describe('predict', () => { + it('invokes predict without error', async () => { + const client = + new predictionserviceModule.v2alpha.PredictionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.PredictRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.PredictRequest', + ['placement'], + ); + request.placement = defaultValue1; + const expectedHeaderRequestParams = `placement=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.PredictResponse(), + ); + client.innerApiCalls.predict = stubSimpleCall(expectedResponse); + const [response] = await client.predict(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.predict as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.predict as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - describe('attributesConfig', () => { - const fakePath = "/rendered/path/attributesConfig"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - }; - const client = new predictionserviceModule.v2alpha.PredictionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.attributesConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.attributesConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('attributesConfigPath', () => { - const result = client.attributesConfigPath("projectValue", "locationValue", "catalogValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.attributesConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromAttributesConfigName', () => { - const result = client.matchProjectFromAttributesConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromAttributesConfigName', () => { - const result = client.matchLocationFromAttributesConfigName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromAttributesConfigName', () => { - const result = client.matchCatalogFromAttributesConfigName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('invokes predict without error using callback', async () => { + const client = + new predictionserviceModule.v2alpha.PredictionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.PredictRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.PredictRequest', + ['placement'], + ); + request.placement = defaultValue1; + const expectedHeaderRequestParams = `placement=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.PredictResponse(), + ); + client.innerApiCalls.predict = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.predict( + request, + ( + err?: Error | null, + result?: protos.google.cloud.retail.v2alpha.IPredictResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.predict as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.predict as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - describe('branch', () => { - const fakePath = "/rendered/path/branch"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - branch: "branchValue", - }; - const client = new predictionserviceModule.v2alpha.PredictionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.branchPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.branchPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('branchPath', () => { - const result = client.branchPath("projectValue", "locationValue", "catalogValue", "branchValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.branchPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromBranchName', () => { - const result = client.matchProjectFromBranchName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.branchPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromBranchName', () => { - const result = client.matchLocationFromBranchName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.branchPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromBranchName', () => { - const result = client.matchCatalogFromBranchName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.branchPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBranchFromBranchName', () => { - const result = client.matchBranchFromBranchName(fakePath); - assert.strictEqual(result, "branchValue"); - assert((client.pathTemplates.branchPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('invokes predict with error', async () => { + const client = + new predictionserviceModule.v2alpha.PredictionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.PredictRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.PredictRequest', + ['placement'], + ); + request.placement = defaultValue1; + const expectedHeaderRequestParams = `placement=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.predict = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.predict(request), expectedError); + const actualRequest = (client.innerApiCalls.predict as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.predict as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - describe('catalog', () => { - const fakePath = "/rendered/path/catalog"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - }; - const client = new predictionserviceModule.v2alpha.PredictionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.catalogPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.catalogPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('catalogPath', () => { - const result = client.catalogPath("projectValue", "locationValue", "catalogValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.catalogPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromCatalogName', () => { - const result = client.matchProjectFromCatalogName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.catalogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromCatalogName', () => { - const result = client.matchLocationFromCatalogName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.catalogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromCatalogName', () => { - const result = client.matchCatalogFromCatalogName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.catalogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('invokes predict with closed client', async () => { + const client = + new predictionserviceModule.v2alpha.PredictionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); - - describe('completionConfig', () => { - const fakePath = "/rendered/path/completionConfig"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - }; - const client = new predictionserviceModule.v2alpha.PredictionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.completionConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.completionConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('completionConfigPath', () => { - const result = client.completionConfigPath("projectValue", "locationValue", "catalogValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.completionConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromCompletionConfigName', () => { - const result = client.matchProjectFromCompletionConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.completionConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromCompletionConfigName', () => { - const result = client.matchLocationFromCompletionConfigName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.completionConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromCompletionConfigName', () => { - const result = client.matchCatalogFromCompletionConfigName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.completionConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.PredictRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.PredictRequest', + ['placement'], + ); + request.placement = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.predict(request), expectedError); + }); + }); + + describe('Path templates', () => { + describe('alertConfig', () => { + const fakePath = '/rendered/path/alertConfig'; + const expectedParameters = { + project: 'projectValue', + }; + const client = + new predictionserviceModule.v2alpha.PredictionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.alertConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.alertConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('alertConfigPath', () => { + const result = client.alertConfigPath('projectValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.alertConfigPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromAlertConfigName', () => { + const result = client.matchProjectFromAlertConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.alertConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('control', () => { - const fakePath = "/rendered/path/control"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - control: "controlValue", - }; - const client = new predictionserviceModule.v2alpha.PredictionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.controlPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.controlPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('controlPath', () => { - const result = client.controlPath("projectValue", "locationValue", "catalogValue", "controlValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.controlPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromControlName', () => { - const result = client.matchProjectFromControlName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.controlPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromControlName', () => { - const result = client.matchLocationFromControlName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.controlPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromControlName', () => { - const result = client.matchCatalogFromControlName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.controlPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchControlFromControlName', () => { - const result = client.matchControlFromControlName(fakePath); - assert.strictEqual(result, "controlValue"); - assert((client.pathTemplates.controlPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('attributesConfig', () => { + const fakePath = '/rendered/path/attributesConfig'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + }; + const client = + new predictionserviceModule.v2alpha.PredictionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.attributesConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.attributesConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('attributesConfigPath', () => { + const result = client.attributesConfigPath( + 'projectValue', + 'locationValue', + 'catalogValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.attributesConfigPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromAttributesConfigName', () => { + const result = client.matchProjectFromAttributesConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromAttributesConfigName', () => { + const result = client.matchLocationFromAttributesConfigName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromAttributesConfigName', () => { + const result = client.matchCatalogFromAttributesConfigName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('loggingConfig', () => { - const fakePath = "/rendered/path/loggingConfig"; - const expectedParameters = { - project: "projectValue", - }; - const client = new predictionserviceModule.v2alpha.PredictionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.loggingConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.loggingConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('loggingConfigPath', () => { - const result = client.loggingConfigPath("projectValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.loggingConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromLoggingConfigName', () => { - const result = client.matchProjectFromLoggingConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.loggingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('branch', () => { + const fakePath = '/rendered/path/branch'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + branch: 'branchValue', + }; + const client = + new predictionserviceModule.v2alpha.PredictionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.branchPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.branchPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('branchPath', () => { + const result = client.branchPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'branchValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.branchPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromBranchName', () => { + const result = client.matchProjectFromBranchName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.branchPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromBranchName', () => { + const result = client.matchLocationFromBranchName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.branchPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromBranchName', () => { + const result = client.matchCatalogFromBranchName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.branchPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBranchFromBranchName', () => { + const result = client.matchBranchFromBranchName(fakePath); + assert.strictEqual(result, 'branchValue'); + assert( + (client.pathTemplates.branchPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('merchantCenterAccountLink', () => { - const fakePath = "/rendered/path/merchantCenterAccountLink"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - merchant_center_account_link: "merchantCenterAccountLinkValue", - }; - const client = new predictionserviceModule.v2alpha.PredictionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.merchantCenterAccountLinkPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.merchantCenterAccountLinkPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('merchantCenterAccountLinkPath', () => { - const result = client.merchantCenterAccountLinkPath("projectValue", "locationValue", "catalogValue", "merchantCenterAccountLinkValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromMerchantCenterAccountLinkName', () => { - const result = client.matchProjectFromMerchantCenterAccountLinkName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromMerchantCenterAccountLinkName', () => { - const result = client.matchLocationFromMerchantCenterAccountLinkName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromMerchantCenterAccountLinkName', () => { - const result = client.matchCatalogFromMerchantCenterAccountLinkName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName', () => { - const result = client.matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName(fakePath); - assert.strictEqual(result, "merchantCenterAccountLinkValue"); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('catalog', () => { + const fakePath = '/rendered/path/catalog'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + }; + const client = + new predictionserviceModule.v2alpha.PredictionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.catalogPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.catalogPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('catalogPath', () => { + const result = client.catalogPath( + 'projectValue', + 'locationValue', + 'catalogValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.catalogPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromCatalogName', () => { + const result = client.matchProjectFromCatalogName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.catalogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromCatalogName', () => { + const result = client.matchLocationFromCatalogName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.catalogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromCatalogName', () => { + const result = client.matchCatalogFromCatalogName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.catalogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('model', () => { - const fakePath = "/rendered/path/model"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - model: "modelValue", - }; - const client = new predictionserviceModule.v2alpha.PredictionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.modelPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.modelPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('modelPath', () => { - const result = client.modelPath("projectValue", "locationValue", "catalogValue", "modelValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.modelPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromModelName', () => { - const result = client.matchProjectFromModelName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromModelName', () => { - const result = client.matchLocationFromModelName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromModelName', () => { - const result = client.matchCatalogFromModelName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchModelFromModelName', () => { - const result = client.matchModelFromModelName(fakePath); - assert.strictEqual(result, "modelValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('completionConfig', () => { + const fakePath = '/rendered/path/completionConfig'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + }; + const client = + new predictionserviceModule.v2alpha.PredictionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.completionConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.completionConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('completionConfigPath', () => { + const result = client.completionConfigPath( + 'projectValue', + 'locationValue', + 'catalogValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.completionConfigPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromCompletionConfigName', () => { + const result = client.matchProjectFromCompletionConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.completionConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromCompletionConfigName', () => { + const result = client.matchLocationFromCompletionConfigName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.completionConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromCompletionConfigName', () => { + const result = client.matchCatalogFromCompletionConfigName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.completionConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('product', () => { - const fakePath = "/rendered/path/product"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - branch: "branchValue", - product: "productValue", - }; - const client = new predictionserviceModule.v2alpha.PredictionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.productPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.productPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('productPath', () => { - const result = client.productPath("projectValue", "locationValue", "catalogValue", "branchValue", "productValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.productPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProductName', () => { - const result = client.matchProjectFromProductName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromProductName', () => { - const result = client.matchLocationFromProductName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromProductName', () => { - const result = client.matchCatalogFromProductName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBranchFromProductName', () => { - const result = client.matchBranchFromProductName(fakePath); - assert.strictEqual(result, "branchValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchProductFromProductName', () => { - const result = client.matchProductFromProductName(fakePath); - assert.strictEqual(result, "productValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('control', () => { + const fakePath = '/rendered/path/control'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + control: 'controlValue', + }; + const client = + new predictionserviceModule.v2alpha.PredictionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.controlPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.controlPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('controlPath', () => { + const result = client.controlPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'controlValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.controlPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromControlName', () => { + const result = client.matchProjectFromControlName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.controlPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromControlName', () => { + const result = client.matchLocationFromControlName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.controlPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromControlName', () => { + const result = client.matchCatalogFromControlName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.controlPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchControlFromControlName', () => { + const result = client.matchControlFromControlName(fakePath); + assert.strictEqual(result, 'controlValue'); + assert( + (client.pathTemplates.controlPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('retailProject', () => { - const fakePath = "/rendered/path/retailProject"; - const expectedParameters = { - project: "projectValue", - }; - const client = new predictionserviceModule.v2alpha.PredictionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.retailProjectPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.retailProjectPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('retailProjectPath', () => { - const result = client.retailProjectPath("projectValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.retailProjectPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromRetailProjectName', () => { - const result = client.matchProjectFromRetailProjectName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.retailProjectPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('loggingConfig', () => { + const fakePath = '/rendered/path/loggingConfig'; + const expectedParameters = { + project: 'projectValue', + }; + const client = + new predictionserviceModule.v2alpha.PredictionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.loggingConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.loggingConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('loggingConfigPath', () => { + const result = client.loggingConfigPath('projectValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.loggingConfigPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromLoggingConfigName', () => { + const result = client.matchProjectFromLoggingConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.loggingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('servingConfig', () => { - const fakePath = "/rendered/path/servingConfig"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - serving_config: "servingConfigValue", - }; - const client = new predictionserviceModule.v2alpha.PredictionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.servingConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.servingConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('servingConfigPath', () => { - const result = client.servingConfigPath("projectValue", "locationValue", "catalogValue", "servingConfigValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.servingConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + describe('merchantCenterAccountLink', () => { + const fakePath = '/rendered/path/merchantCenterAccountLink'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + merchant_center_account_link: 'merchantCenterAccountLinkValue', + }; + const client = + new predictionserviceModule.v2alpha.PredictionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.merchantCenterAccountLinkPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.merchantCenterAccountLinkPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('merchantCenterAccountLinkPath', () => { + const result = client.merchantCenterAccountLinkPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'merchantCenterAccountLinkValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromMerchantCenterAccountLinkName', () => { + const result = + client.matchProjectFromMerchantCenterAccountLinkName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromMerchantCenterAccountLinkName', () => { + const result = + client.matchLocationFromMerchantCenterAccountLinkName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromMerchantCenterAccountLinkName', () => { + const result = + client.matchCatalogFromMerchantCenterAccountLinkName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName', () => { + const result = + client.matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName( + fakePath, + ); + assert.strictEqual(result, 'merchantCenterAccountLinkValue'); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchProjectFromServingConfigName', () => { - const result = client.matchProjectFromServingConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.servingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('model', () => { + const fakePath = '/rendered/path/model'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + model: 'modelValue', + }; + const client = + new predictionserviceModule.v2alpha.PredictionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.modelPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.modelPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('modelPath', () => { + const result = client.modelPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'modelValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.modelPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromModelName', () => { + const result = client.matchProjectFromModelName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromModelName', () => { + const result = client.matchLocationFromModelName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromModelName', () => { + const result = client.matchCatalogFromModelName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchModelFromModelName', () => { + const result = client.matchModelFromModelName(fakePath); + assert.strictEqual(result, 'modelValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchLocationFromServingConfigName', () => { - const result = client.matchLocationFromServingConfigName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.servingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('product', () => { + const fakePath = '/rendered/path/product'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + branch: 'branchValue', + product: 'productValue', + }; + const client = + new predictionserviceModule.v2alpha.PredictionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.productPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.productPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('productPath', () => { + const result = client.productPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'branchValue', + 'productValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.productPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProductName', () => { + const result = client.matchProjectFromProductName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromProductName', () => { + const result = client.matchLocationFromProductName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromProductName', () => { + const result = client.matchCatalogFromProductName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBranchFromProductName', () => { + const result = client.matchBranchFromProductName(fakePath); + assert.strictEqual(result, 'branchValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchProductFromProductName', () => { + const result = client.matchProductFromProductName(fakePath); + assert.strictEqual(result, 'productValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchCatalogFromServingConfigName', () => { - const result = client.matchCatalogFromServingConfigName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.servingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('retailProject', () => { + const fakePath = '/rendered/path/retailProject'; + const expectedParameters = { + project: 'projectValue', + }; + const client = + new predictionserviceModule.v2alpha.PredictionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.retailProjectPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.retailProjectPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('retailProjectPath', () => { + const result = client.retailProjectPath('projectValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.retailProjectPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromRetailProjectName', () => { + const result = client.matchProjectFromRetailProjectName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.retailProjectPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchServingConfigFromServingConfigName', () => { - const result = client.matchServingConfigFromServingConfigName(fakePath); - assert.strictEqual(result, "servingConfigValue"); - assert((client.pathTemplates.servingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('servingConfig', () => { + const fakePath = '/rendered/path/servingConfig'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + serving_config: 'servingConfigValue', + }; + const client = + new predictionserviceModule.v2alpha.PredictionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.servingConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.servingConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('servingConfigPath', () => { + const result = client.servingConfigPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'servingConfigValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.servingConfigPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromServingConfigName', () => { + const result = client.matchProjectFromServingConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.servingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromServingConfigName', () => { + const result = client.matchLocationFromServingConfigName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.servingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromServingConfigName', () => { + const result = client.matchCatalogFromServingConfigName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.servingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServingConfigFromServingConfigName', () => { + const result = client.matchServingConfigFromServingConfigName(fakePath); + assert.strictEqual(result, 'servingConfigValue'); + assert( + (client.pathTemplates.servingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/test/gapic_product_service_v2alpha.ts.baseline b/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/test/gapic_product_service_v2alpha.ts.baseline index 0d4fddb425d3..439dfaf76d95 100644 --- a/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/test/gapic_product_service_v2alpha.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/test/gapic_product_service_v2alpha.ts.baseline @@ -20,16 +20,16 @@ import * as protos from '../../protos/protos.js'; import assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as productserviceModule from '../src/index.js'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; -import {protobuf, LROperation, operationsProtos} from 'google-gax'; +import { protobuf, LROperation, operationsProtos } from 'google-gax'; import fs from 'fs'; import path from 'path'; -import {fileURLToPath} from 'url'; +import { fileURLToPath } from 'url'; // @ts-ignore const dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -37,2730 +37,3548 @@ const dirname = path.dirname(fileURLToPath(import.meta.url)); // to fill in default values for request objects const root = protobuf.Root.fromJSON( JSON.parse( - fs.readFileSync(path.join(dirname, '..', '..', 'protos/protos.json'), 'utf8') - )) + fs.readFileSync( + path.join(dirname, '..', '..', 'protos/protos.json'), + 'utf8', + ), + ), +); // eslint-disable-next-line @typescript-eslint/no-unused-vars function getTypeDefaultValue(typeName: string, fields: string[]) { - let type = root.lookupType(typeName) as protobuf.Type; - for (const field of fields.slice(0, -1)) { - type = type?.fields[field]?.resolvedType as protobuf.Type; - } - return type?.fields[fields[fields.length - 1]]?.defaultValue ?? null; + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type?.fields[field]?.resolvedType as protobuf.Type; + } + return type?.fields[fields[fields.length - 1]]?.defaultValue ?? null; } function generateSampleMessage(instance: T) { - const filledObject = (instance.constructor as typeof protobuf.Message) - .toObject(instance as protobuf.Message, {defaults: true}); - return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, { defaults: true }); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; } function stubSimpleCall(response?: ResponseType, error?: Error) { - return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); } -function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { - return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +function stubSimpleCallWithCallback( + response?: ResponseType, + error?: Error, +) { + return error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); } -function stubLongRunningCall(response?: ResponseType, callError?: Error, lroError?: Error) { - const innerStub = lroError ? sinon.stub().rejects(lroError) : sinon.stub().resolves([response]); - const mockOperation = { - promise: innerStub, - }; - return callError ? sinon.stub().rejects(callError) : sinon.stub().resolves([mockOperation]); +function stubLongRunningCall( + response?: ResponseType, + callError?: Error, + lroError?: Error, +) { + const innerStub = lroError + ? sinon.stub().rejects(lroError) + : sinon.stub().resolves([response]); + const mockOperation = { + promise: innerStub, + }; + return callError + ? sinon.stub().rejects(callError) + : sinon.stub().resolves([mockOperation]); } -function stubLongRunningCallWithCallback(response?: ResponseType, callError?: Error, lroError?: Error) { - const innerStub = lroError ? sinon.stub().rejects(lroError) : sinon.stub().resolves([response]); - const mockOperation = { - promise: innerStub, - }; - return callError ? sinon.stub().callsArgWith(2, callError) : sinon.stub().callsArgWith(2, null, mockOperation); +function stubLongRunningCallWithCallback( + response?: ResponseType, + callError?: Error, + lroError?: Error, +) { + const innerStub = lroError + ? sinon.stub().rejects(lroError) + : sinon.stub().resolves([response]); + const mockOperation = { + promise: innerStub, + }; + return callError + ? sinon.stub().callsArgWith(2, callError) + : sinon.stub().callsArgWith(2, null, mockOperation); } -function stubPageStreamingCall(responses?: ResponseType[], error?: Error) { - const pagingStub = sinon.stub(); - if (responses) { - for (let i = 0; i < responses.length; ++i) { - pagingStub.onCall(i).callsArgWith(2, null, responses[i]); - } +function stubPageStreamingCall( + responses?: ResponseType[], + error?: Error, +) { + const pagingStub = sinon.stub(); + if (responses) { + for (let i = 0; i < responses.length; ++i) { + pagingStub.onCall(i).callsArgWith(2, null, responses[i]); } - const transformStub = error ? sinon.stub().callsArgWith(2, error) : pagingStub; - const mockStream = new PassThrough({ - objectMode: true, - transform: transformStub, - }); - // trigger as many responses as needed - if (responses) { - for (let i = 0; i < responses.length; ++i) { - setImmediate(() => { mockStream.write({}); }); - } - setImmediate(() => { mockStream.end(); }); - } else { - setImmediate(() => { mockStream.write({}); }); - setImmediate(() => { mockStream.end(); }); + } + const transformStub = error + ? sinon.stub().callsArgWith(2, error) + : pagingStub; + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + // trigger as many responses as needed + if (responses) { + for (let i = 0; i < responses.length; ++i) { + setImmediate(() => { + mockStream.write({}); + }); } - return sinon.stub().returns(mockStream); + setImmediate(() => { + mockStream.end(); + }); + } else { + setImmediate(() => { + mockStream.write({}); + }); + setImmediate(() => { + mockStream.end(); + }); + } + return sinon.stub().returns(mockStream); } -function stubAsyncIterationCall(responses?: ResponseType[], error?: Error) { - let counter = 0; - const asyncIterable = { - [Symbol.asyncIterator]() { - return { - async next() { - if (error) { - return Promise.reject(error); - } - if (counter >= responses!.length) { - return Promise.resolve({done: true, value: undefined}); - } - return Promise.resolve({done: false, value: responses![counter++]}); - } - }; - } - }; - return sinon.stub().returns(asyncIterable); +function stubAsyncIterationCall( + responses?: ResponseType[], + error?: Error, +) { + let counter = 0; + const asyncIterable = { + [Symbol.asyncIterator]() { + return { + async next() { + if (error) { + return Promise.reject(error); + } + if (counter >= responses!.length) { + return Promise.resolve({ done: true, value: undefined }); + } + return Promise.resolve({ done: false, value: responses![counter++] }); + }, + }; + }, + }; + return sinon.stub().returns(asyncIterable); } describe('v2alpha.ProductServiceClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new productserviceModule.v2alpha.ProductServiceClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'retail.googleapis.com'); - }); - - it('has universeDomain', () => { - const client = new productserviceModule.v2alpha.ProductServiceClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); - - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - it('throws DeprecationWarning if static servicePath is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const servicePath = productserviceModule.v2alpha.ProductServiceClient.servicePath; - assert.strictEqual(servicePath, 'retail.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = productserviceModule.v2alpha.ProductServiceClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'retail.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'retail.example.com'); - }); - - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'retail.example.com'); - }); - - if (typeof process === 'object' && 'env' in process) { - describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { - it('sets apiEndpoint from environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new productserviceModule.v2alpha.ProductServiceClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'retail.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - - it('value configured in code has priority over environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new productserviceModule.v2alpha.ProductServiceClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'retail.configured.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { new productserviceModule.v2alpha.ProductServiceClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); - - it('has port', () => { - const port = productserviceModule.v2alpha.ProductServiceClient.port; - assert(port); - assert(typeof port === 'number'); - }); - - it('should create a client with no option', () => { - const client = new productserviceModule.v2alpha.ProductServiceClient(); - assert(client); - }); - - it('should create a client with gRPC fallback', () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - fallback: true, - }); - assert(client); - }); - - it('has initialize method and supports deferred initialization', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.productServiceStub, undefined); - await client.initialize(); - assert(client.productServiceStub); - }); - - it('has close method for the initialized client', done => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.productServiceStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); - - it('has close method for the non-initialized client', done => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.productServiceStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); - - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); - }); - - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId((err?: Error|null, projectId?: string|null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } - }); - }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new productserviceModule.v2alpha.ProductServiceClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'retail.googleapis.com'); }); - describe('createProduct', () => { - it('invokes createProduct without error', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.CreateProductRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.CreateProductRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.Product() - ); - client.innerApiCalls.createProduct = stubSimpleCall(expectedResponse); - const [response] = await client.createProduct(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createProduct as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createProduct as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createProduct without error using callback', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.CreateProductRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.CreateProductRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.Product() - ); - client.innerApiCalls.createProduct = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createProduct( - request, - (err?: Error|null, result?: protos.google.cloud.retail.v2alpha.IProduct|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createProduct as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createProduct as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createProduct with error', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.CreateProductRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.CreateProductRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createProduct = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createProduct(request), expectedError); - const actualRequest = (client.innerApiCalls.createProduct as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createProduct as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has universeDomain', () => { + const client = new productserviceModule.v2alpha.ProductServiceClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - it('invokes createProduct with closed client', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.CreateProductRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.CreateProductRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createProduct(request), expectedError); - }); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = + productserviceModule.v2alpha.ProductServiceClient.servicePath; + assert.strictEqual(servicePath, 'retail.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + productserviceModule.v2alpha.ProductServiceClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'retail.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + universeDomain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'retail.example.com'); }); - describe('getProduct', () => { - it('invokes getProduct without error', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.GetProductRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.GetProductRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.Product() - ); - client.innerApiCalls.getProduct = stubSimpleCall(expectedResponse); - const [response] = await client.getProduct(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getProduct as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getProduct as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + universe_domain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'retail.example.com'); + }); - it('invokes getProduct without error using callback', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.GetProductRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.GetProductRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.Product() - ); - client.innerApiCalls.getProduct = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getProduct( - request, - (err?: Error|null, result?: protos.google.cloud.retail.v2alpha.IProduct|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getProduct as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getProduct as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + if (typeof process === 'object' && 'env' in process) { + describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { + it('sets apiEndpoint from environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = + new productserviceModule.v2alpha.ProductServiceClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'retail.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } + }); + + it('value configured in code has priority over environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new productserviceModule.v2alpha.ProductServiceClient({ + universeDomain: 'configured.example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'retail.configured.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } + }); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new productserviceModule.v2alpha.ProductServiceClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); + }); - it('invokes getProduct with error', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.GetProductRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.GetProductRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getProduct = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getProduct(request), expectedError); - const actualRequest = (client.innerApiCalls.getProduct as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getProduct as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has port', () => { + const port = productserviceModule.v2alpha.ProductServiceClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('invokes getProduct with closed client', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.GetProductRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.GetProductRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getProduct(request), expectedError); - }); + it('should create a client with no option', () => { + const client = new productserviceModule.v2alpha.ProductServiceClient(); + assert(client); }); - describe('updateProduct', () => { - it('invokes updateProduct without error', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.UpdateProductRequest() - ); - request.product ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.UpdateProductRequest', ['product', 'name']); - request.product.name = defaultValue1; - const expectedHeaderRequestParams = `product.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.Product() - ); - client.innerApiCalls.updateProduct = stubSimpleCall(expectedResponse); - const [response] = await client.updateProduct(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateProduct as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateProduct as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('should create a client with gRPC fallback', () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + fallback: true, + }); + assert(client); + }); - it('invokes updateProduct without error using callback', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.UpdateProductRequest() - ); - request.product ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.UpdateProductRequest', ['product', 'name']); - request.product.name = defaultValue1; - const expectedHeaderRequestParams = `product.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.Product() - ); - client.innerApiCalls.updateProduct = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateProduct( - request, - (err?: Error|null, result?: protos.google.cloud.retail.v2alpha.IProduct|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateProduct as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateProduct as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has initialize method and supports deferred initialization', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.productServiceStub, undefined); + await client.initialize(); + assert(client.productServiceStub); + }); - it('invokes updateProduct with error', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.UpdateProductRequest() - ); - request.product ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.UpdateProductRequest', ['product', 'name']); - request.product.name = defaultValue1; - const expectedHeaderRequestParams = `product.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateProduct = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateProduct(request), expectedError); - const actualRequest = (client.innerApiCalls.updateProduct as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateProduct as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('has close method for the initialized client', (done) => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.productServiceStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes updateProduct with closed client', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.UpdateProductRequest() - ); - request.product ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.UpdateProductRequest', ['product', 'name']); - request.product.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateProduct(request), expectedError); + it('has close method for the non-initialized client', (done) => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.productServiceStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); }); - describe('deleteProduct', () => { - it('invokes deleteProduct without error', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.DeleteProductRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.DeleteProductRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteProduct = stubSimpleCall(expectedResponse); - const [response] = await client.deleteProduct(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteProduct as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteProduct as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + }); - it('invokes deleteProduct without error using callback', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.DeleteProductRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.DeleteProductRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteProduct = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteProduct( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteProduct as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteProduct as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } + }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + }); + + describe('createProduct', () => { + it('invokes createProduct without error', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.CreateProductRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.CreateProductRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.Product(), + ); + client.innerApiCalls.createProduct = stubSimpleCall(expectedResponse); + const [response] = await client.createProduct(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createProduct as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createProduct as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteProduct with error', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.DeleteProductRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.DeleteProductRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteProduct = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteProduct(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteProduct as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteProduct as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createProduct without error using callback', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.CreateProductRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.CreateProductRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.Product(), + ); + client.innerApiCalls.createProduct = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createProduct( + request, + ( + err?: Error | null, + result?: protos.google.cloud.retail.v2alpha.IProduct | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createProduct as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createProduct as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteProduct with closed client', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.DeleteProductRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.DeleteProductRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteProduct(request), expectedError); - }); + it('invokes createProduct with error', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.CreateProductRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.CreateProductRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createProduct = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.createProduct(request), expectedError); + const actualRequest = ( + client.innerApiCalls.createProduct as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createProduct as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('purgeProducts', () => { - it('invokes purgeProducts without error', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.PurgeProductsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.PurgeProductsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.purgeProducts = stubLongRunningCall(expectedResponse); - const [operation] = await client.purgeProducts(request); - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.purgeProducts as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.purgeProducts as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createProduct with closed client', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.CreateProductRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.CreateProductRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.createProduct(request), expectedError); + }); + }); + + describe('getProduct', () => { + it('invokes getProduct without error', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.GetProductRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.GetProductRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.Product(), + ); + client.innerApiCalls.getProduct = stubSimpleCall(expectedResponse); + const [response] = await client.getProduct(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getProduct as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getProduct as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes purgeProducts without error using callback', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.PurgeProductsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.PurgeProductsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.purgeProducts = stubLongRunningCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.purgeProducts( - request, - (err?: Error|null, - result?: LROperation|null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const operation = await promise as LROperation; - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.purgeProducts as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.purgeProducts as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getProduct without error using callback', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.GetProductRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.GetProductRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.Product(), + ); + client.innerApiCalls.getProduct = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getProduct( + request, + ( + err?: Error | null, + result?: protos.google.cloud.retail.v2alpha.IProduct | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getProduct as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getProduct as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes purgeProducts with call error', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.PurgeProductsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.PurgeProductsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.purgeProducts = stubLongRunningCall(undefined, expectedError); - await assert.rejects(client.purgeProducts(request), expectedError); - const actualRequest = (client.innerApiCalls.purgeProducts as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.purgeProducts as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getProduct with error', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.GetProductRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.GetProductRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getProduct = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getProduct(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getProduct as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getProduct as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes purgeProducts with LRO error', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.PurgeProductsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.PurgeProductsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.purgeProducts = stubLongRunningCall(undefined, undefined, expectedError); - const [operation] = await client.purgeProducts(request); - await assert.rejects(operation.promise(), expectedError); - const actualRequest = (client.innerApiCalls.purgeProducts as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.purgeProducts as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getProduct with closed client', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.GetProductRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.GetProductRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getProduct(request), expectedError); + }); + }); + + describe('updateProduct', () => { + it('invokes updateProduct without error', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.UpdateProductRequest(), + ); + request.product ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.UpdateProductRequest', + ['product', 'name'], + ); + request.product.name = defaultValue1; + const expectedHeaderRequestParams = `product.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.Product(), + ); + client.innerApiCalls.updateProduct = stubSimpleCall(expectedResponse); + const [response] = await client.updateProduct(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateProduct as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateProduct as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkPurgeProductsProgress without error', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedResponse = generateSampleMessage( - new operationsProtos.google.longrunning.Operation() - ); - expectedResponse.name = 'test'; - expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; - expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')} - - client.operationsClient.getOperation = stubSimpleCall(expectedResponse); - const decodedOperation = await client.checkPurgeProductsProgress(expectedResponse.name); - assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); - assert(decodedOperation.metadata); - assert((client.operationsClient.getOperation as SinonStub).getCall(0)); - }); + it('invokes updateProduct without error using callback', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.UpdateProductRequest(), + ); + request.product ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.UpdateProductRequest', + ['product', 'name'], + ); + request.product.name = defaultValue1; + const expectedHeaderRequestParams = `product.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.Product(), + ); + client.innerApiCalls.updateProduct = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateProduct( + request, + ( + err?: Error | null, + result?: protos.google.cloud.retail.v2alpha.IProduct | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateProduct as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateProduct as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkPurgeProductsProgress with error', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedError = new Error('expected'); - - client.operationsClient.getOperation = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.checkPurgeProductsProgress(''), expectedError); - assert((client.operationsClient.getOperation as SinonStub) - .getCall(0)); - }); + it('invokes updateProduct with error', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.UpdateProductRequest(), + ); + request.product ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.UpdateProductRequest', + ['product', 'name'], + ); + request.product.name = defaultValue1; + const expectedHeaderRequestParams = `product.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateProduct = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.updateProduct(request), expectedError); + const actualRequest = ( + client.innerApiCalls.updateProduct as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateProduct as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('importProducts', () => { - it('invokes importProducts without error', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ImportProductsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ImportProductsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.importProducts = stubLongRunningCall(expectedResponse); - const [operation] = await client.importProducts(request); - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.importProducts as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.importProducts as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateProduct with closed client', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.UpdateProductRequest(), + ); + request.product ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.UpdateProductRequest', + ['product', 'name'], + ); + request.product.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.updateProduct(request), expectedError); + }); + }); + + describe('deleteProduct', () => { + it('invokes deleteProduct without error', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.DeleteProductRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.DeleteProductRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteProduct = stubSimpleCall(expectedResponse); + const [response] = await client.deleteProduct(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteProduct as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteProduct as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes importProducts without error using callback', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ImportProductsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ImportProductsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.importProducts = stubLongRunningCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.importProducts( - request, - (err?: Error|null, - result?: LROperation|null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const operation = await promise as LROperation; - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.importProducts as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.importProducts as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteProduct without error using callback', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.DeleteProductRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.DeleteProductRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteProduct = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteProduct( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteProduct as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteProduct as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes importProducts with call error', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ImportProductsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ImportProductsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.importProducts = stubLongRunningCall(undefined, expectedError); - await assert.rejects(client.importProducts(request), expectedError); - const actualRequest = (client.innerApiCalls.importProducts as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.importProducts as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteProduct with error', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.DeleteProductRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.DeleteProductRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteProduct = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.deleteProduct(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteProduct as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteProduct as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes importProducts with LRO error', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ImportProductsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ImportProductsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.importProducts = stubLongRunningCall(undefined, undefined, expectedError); - const [operation] = await client.importProducts(request); - await assert.rejects(operation.promise(), expectedError); - const actualRequest = (client.innerApiCalls.importProducts as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.importProducts as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteProduct with closed client', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.DeleteProductRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.DeleteProductRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.deleteProduct(request), expectedError); + }); + }); + + describe('purgeProducts', () => { + it('invokes purgeProducts without error', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.PurgeProductsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.PurgeProductsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.purgeProducts = + stubLongRunningCall(expectedResponse); + const [operation] = await client.purgeProducts(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.purgeProducts as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.purgeProducts as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkImportProductsProgress without error', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedResponse = generateSampleMessage( - new operationsProtos.google.longrunning.Operation() - ); - expectedResponse.name = 'test'; - expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; - expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')} - - client.operationsClient.getOperation = stubSimpleCall(expectedResponse); - const decodedOperation = await client.checkImportProductsProgress(expectedResponse.name); - assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); - assert(decodedOperation.metadata); - assert((client.operationsClient.getOperation as SinonStub).getCall(0)); - }); + it('invokes purgeProducts without error using callback', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.PurgeProductsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.PurgeProductsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.purgeProducts = + stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.purgeProducts( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.cloud.retail.v2alpha.IPurgeProductsResponse, + protos.google.cloud.retail.v2alpha.IPurgeProductsMetadata + > | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const operation = (await promise) as LROperation< + protos.google.cloud.retail.v2alpha.IPurgeProductsResponse, + protos.google.cloud.retail.v2alpha.IPurgeProductsMetadata + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.purgeProducts as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.purgeProducts as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkImportProductsProgress with error', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedError = new Error('expected'); - - client.operationsClient.getOperation = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.checkImportProductsProgress(''), expectedError); - assert((client.operationsClient.getOperation as SinonStub) - .getCall(0)); - }); + it('invokes purgeProducts with call error', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.PurgeProductsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.PurgeProductsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.purgeProducts = stubLongRunningCall( + undefined, + expectedError, + ); + await assert.rejects(client.purgeProducts(request), expectedError); + const actualRequest = ( + client.innerApiCalls.purgeProducts as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.purgeProducts as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('exportProducts', () => { - it('invokes exportProducts without error', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ExportProductsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ExportProductsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.exportProducts = stubLongRunningCall(expectedResponse); - const [operation] = await client.exportProducts(request); - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.exportProducts as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.exportProducts as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes purgeProducts with LRO error', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.PurgeProductsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.PurgeProductsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.purgeProducts = stubLongRunningCall( + undefined, + undefined, + expectedError, + ); + const [operation] = await client.purgeProducts(request); + await assert.rejects(operation.promise(), expectedError); + const actualRequest = ( + client.innerApiCalls.purgeProducts as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.purgeProducts as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes exportProducts without error using callback', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ExportProductsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ExportProductsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.exportProducts = stubLongRunningCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.exportProducts( - request, - (err?: Error|null, - result?: LROperation|null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const operation = await promise as LROperation; - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.exportProducts as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.exportProducts as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes checkPurgeProductsProgress without error', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation(), + ); + expectedResponse.name = 'test'; + expectedResponse.response = { type_url: 'url', value: Buffer.from('') }; + expectedResponse.metadata = { type_url: 'url', value: Buffer.from('') }; + + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const decodedOperation = await client.checkPurgeProductsProgress( + expectedResponse.name, + ); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); - it('invokes exportProducts with call error', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ExportProductsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ExportProductsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.exportProducts = stubLongRunningCall(undefined, expectedError); - await assert.rejects(client.exportProducts(request), expectedError); - const actualRequest = (client.innerApiCalls.exportProducts as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.exportProducts as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes checkPurgeProductsProgress with error', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const expectedError = new Error('expected'); + + client.operationsClient.getOperation = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.checkPurgeProductsProgress(''), + expectedError, + ); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + }); + + describe('importProducts', () => { + it('invokes importProducts without error', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ImportProductsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ImportProductsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.importProducts = + stubLongRunningCall(expectedResponse); + const [operation] = await client.importProducts(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.importProducts as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.importProducts as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes exportProducts with LRO error', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ExportProductsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ExportProductsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.exportProducts = stubLongRunningCall(undefined, undefined, expectedError); - const [operation] = await client.exportProducts(request); - await assert.rejects(operation.promise(), expectedError); - const actualRequest = (client.innerApiCalls.exportProducts as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.exportProducts as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes importProducts without error using callback', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ImportProductsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ImportProductsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.importProducts = + stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.importProducts( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.cloud.retail.v2alpha.IImportProductsResponse, + protos.google.cloud.retail.v2alpha.IImportMetadata + > | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const operation = (await promise) as LROperation< + protos.google.cloud.retail.v2alpha.IImportProductsResponse, + protos.google.cloud.retail.v2alpha.IImportMetadata + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.importProducts as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.importProducts as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkExportProductsProgress without error', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedResponse = generateSampleMessage( - new operationsProtos.google.longrunning.Operation() - ); - expectedResponse.name = 'test'; - expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; - expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')} - - client.operationsClient.getOperation = stubSimpleCall(expectedResponse); - const decodedOperation = await client.checkExportProductsProgress(expectedResponse.name); - assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); - assert(decodedOperation.metadata); - assert((client.operationsClient.getOperation as SinonStub).getCall(0)); - }); + it('invokes importProducts with call error', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ImportProductsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ImportProductsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.importProducts = stubLongRunningCall( + undefined, + expectedError, + ); + await assert.rejects(client.importProducts(request), expectedError); + const actualRequest = ( + client.innerApiCalls.importProducts as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.importProducts as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkExportProductsProgress with error', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedError = new Error('expected'); - - client.operationsClient.getOperation = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.checkExportProductsProgress(''), expectedError); - assert((client.operationsClient.getOperation as SinonStub) - .getCall(0)); - }); + it('invokes importProducts with LRO error', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ImportProductsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ImportProductsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.importProducts = stubLongRunningCall( + undefined, + undefined, + expectedError, + ); + const [operation] = await client.importProducts(request); + await assert.rejects(operation.promise(), expectedError); + const actualRequest = ( + client.innerApiCalls.importProducts as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.importProducts as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('setInventory', () => { - it('invokes setInventory without error', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.SetInventoryRequest() - ); - request.inventory ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.SetInventoryRequest', ['inventory', 'name']); - request.inventory.name = defaultValue1; - const expectedHeaderRequestParams = `inventory.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.setInventory = stubLongRunningCall(expectedResponse); - const [operation] = await client.setInventory(request); - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.setInventory as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.setInventory as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes checkImportProductsProgress without error', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation(), + ); + expectedResponse.name = 'test'; + expectedResponse.response = { type_url: 'url', value: Buffer.from('') }; + expectedResponse.metadata = { type_url: 'url', value: Buffer.from('') }; + + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const decodedOperation = await client.checkImportProductsProgress( + expectedResponse.name, + ); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); - it('invokes setInventory without error using callback', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.SetInventoryRequest() - ); - request.inventory ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.SetInventoryRequest', ['inventory', 'name']); - request.inventory.name = defaultValue1; - const expectedHeaderRequestParams = `inventory.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.setInventory = stubLongRunningCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.setInventory( - request, - (err?: Error|null, - result?: LROperation|null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const operation = await promise as LROperation; - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.setInventory as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.setInventory as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes checkImportProductsProgress with error', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const expectedError = new Error('expected'); + + client.operationsClient.getOperation = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.checkImportProductsProgress(''), + expectedError, + ); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + }); + + describe('exportProducts', () => { + it('invokes exportProducts without error', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ExportProductsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ExportProductsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.exportProducts = + stubLongRunningCall(expectedResponse); + const [operation] = await client.exportProducts(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.exportProducts as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.exportProducts as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes setInventory with call error', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.SetInventoryRequest() - ); - request.inventory ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.SetInventoryRequest', ['inventory', 'name']); - request.inventory.name = defaultValue1; - const expectedHeaderRequestParams = `inventory.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.setInventory = stubLongRunningCall(undefined, expectedError); - await assert.rejects(client.setInventory(request), expectedError); - const actualRequest = (client.innerApiCalls.setInventory as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.setInventory as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes exportProducts without error using callback', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ExportProductsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ExportProductsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.exportProducts = + stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.exportProducts( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.cloud.retail.v2alpha.IExportProductsResponse, + protos.google.cloud.retail.v2alpha.IExportMetadata + > | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const operation = (await promise) as LROperation< + protos.google.cloud.retail.v2alpha.IExportProductsResponse, + protos.google.cloud.retail.v2alpha.IExportMetadata + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.exportProducts as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.exportProducts as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes setInventory with LRO error', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.SetInventoryRequest() - ); - request.inventory ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.SetInventoryRequest', ['inventory', 'name']); - request.inventory.name = defaultValue1; - const expectedHeaderRequestParams = `inventory.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.setInventory = stubLongRunningCall(undefined, undefined, expectedError); - const [operation] = await client.setInventory(request); - await assert.rejects(operation.promise(), expectedError); - const actualRequest = (client.innerApiCalls.setInventory as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.setInventory as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes exportProducts with call error', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ExportProductsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ExportProductsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.exportProducts = stubLongRunningCall( + undefined, + expectedError, + ); + await assert.rejects(client.exportProducts(request), expectedError); + const actualRequest = ( + client.innerApiCalls.exportProducts as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.exportProducts as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkSetInventoryProgress without error', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedResponse = generateSampleMessage( - new operationsProtos.google.longrunning.Operation() - ); - expectedResponse.name = 'test'; - expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; - expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')} - - client.operationsClient.getOperation = stubSimpleCall(expectedResponse); - const decodedOperation = await client.checkSetInventoryProgress(expectedResponse.name); - assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); - assert(decodedOperation.metadata); - assert((client.operationsClient.getOperation as SinonStub).getCall(0)); - }); + it('invokes exportProducts with LRO error', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ExportProductsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ExportProductsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.exportProducts = stubLongRunningCall( + undefined, + undefined, + expectedError, + ); + const [operation] = await client.exportProducts(request); + await assert.rejects(operation.promise(), expectedError); + const actualRequest = ( + client.innerApiCalls.exportProducts as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.exportProducts as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkSetInventoryProgress with error', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedError = new Error('expected'); - - client.operationsClient.getOperation = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.checkSetInventoryProgress(''), expectedError); - assert((client.operationsClient.getOperation as SinonStub) - .getCall(0)); - }); + it('invokes checkExportProductsProgress without error', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation(), + ); + expectedResponse.name = 'test'; + expectedResponse.response = { type_url: 'url', value: Buffer.from('') }; + expectedResponse.metadata = { type_url: 'url', value: Buffer.from('') }; + + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const decodedOperation = await client.checkExportProductsProgress( + expectedResponse.name, + ); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); }); - describe('addFulfillmentPlaces', () => { - it('invokes addFulfillmentPlaces without error', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.AddFulfillmentPlacesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.AddFulfillmentPlacesRequest', ['product']); - request.product = defaultValue1; - const expectedHeaderRequestParams = `product=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.addFulfillmentPlaces = stubLongRunningCall(expectedResponse); - const [operation] = await client.addFulfillmentPlaces(request); - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.addFulfillmentPlaces as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.addFulfillmentPlaces as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes checkExportProductsProgress with error', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const expectedError = new Error('expected'); + + client.operationsClient.getOperation = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.checkExportProductsProgress(''), + expectedError, + ); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + }); + + describe('setInventory', () => { + it('invokes setInventory without error', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.SetInventoryRequest(), + ); + request.inventory ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.SetInventoryRequest', + ['inventory', 'name'], + ); + request.inventory.name = defaultValue1; + const expectedHeaderRequestParams = `inventory.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.setInventory = stubLongRunningCall(expectedResponse); + const [operation] = await client.setInventory(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.setInventory as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.setInventory as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes addFulfillmentPlaces without error using callback', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.AddFulfillmentPlacesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.AddFulfillmentPlacesRequest', ['product']); - request.product = defaultValue1; - const expectedHeaderRequestParams = `product=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.addFulfillmentPlaces = stubLongRunningCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.addFulfillmentPlaces( - request, - (err?: Error|null, - result?: LROperation|null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const operation = await promise as LROperation; - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.addFulfillmentPlaces as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.addFulfillmentPlaces as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes setInventory without error using callback', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.SetInventoryRequest(), + ); + request.inventory ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.SetInventoryRequest', + ['inventory', 'name'], + ); + request.inventory.name = defaultValue1; + const expectedHeaderRequestParams = `inventory.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.setInventory = + stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.setInventory( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.cloud.retail.v2alpha.ISetInventoryResponse, + protos.google.cloud.retail.v2alpha.ISetInventoryMetadata + > | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const operation = (await promise) as LROperation< + protos.google.cloud.retail.v2alpha.ISetInventoryResponse, + protos.google.cloud.retail.v2alpha.ISetInventoryMetadata + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.setInventory as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.setInventory as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes addFulfillmentPlaces with call error', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.AddFulfillmentPlacesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.AddFulfillmentPlacesRequest', ['product']); - request.product = defaultValue1; - const expectedHeaderRequestParams = `product=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.addFulfillmentPlaces = stubLongRunningCall(undefined, expectedError); - await assert.rejects(client.addFulfillmentPlaces(request), expectedError); - const actualRequest = (client.innerApiCalls.addFulfillmentPlaces as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.addFulfillmentPlaces as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes setInventory with call error', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.SetInventoryRequest(), + ); + request.inventory ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.SetInventoryRequest', + ['inventory', 'name'], + ); + request.inventory.name = defaultValue1; + const expectedHeaderRequestParams = `inventory.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.setInventory = stubLongRunningCall( + undefined, + expectedError, + ); + await assert.rejects(client.setInventory(request), expectedError); + const actualRequest = ( + client.innerApiCalls.setInventory as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.setInventory as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes addFulfillmentPlaces with LRO error', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.AddFulfillmentPlacesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.AddFulfillmentPlacesRequest', ['product']); - request.product = defaultValue1; - const expectedHeaderRequestParams = `product=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.addFulfillmentPlaces = stubLongRunningCall(undefined, undefined, expectedError); - const [operation] = await client.addFulfillmentPlaces(request); - await assert.rejects(operation.promise(), expectedError); - const actualRequest = (client.innerApiCalls.addFulfillmentPlaces as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.addFulfillmentPlaces as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes setInventory with LRO error', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.SetInventoryRequest(), + ); + request.inventory ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.SetInventoryRequest', + ['inventory', 'name'], + ); + request.inventory.name = defaultValue1; + const expectedHeaderRequestParams = `inventory.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.setInventory = stubLongRunningCall( + undefined, + undefined, + expectedError, + ); + const [operation] = await client.setInventory(request); + await assert.rejects(operation.promise(), expectedError); + const actualRequest = ( + client.innerApiCalls.setInventory as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.setInventory as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkAddFulfillmentPlacesProgress without error', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedResponse = generateSampleMessage( - new operationsProtos.google.longrunning.Operation() - ); - expectedResponse.name = 'test'; - expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; - expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')} - - client.operationsClient.getOperation = stubSimpleCall(expectedResponse); - const decodedOperation = await client.checkAddFulfillmentPlacesProgress(expectedResponse.name); - assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); - assert(decodedOperation.metadata); - assert((client.operationsClient.getOperation as SinonStub).getCall(0)); - }); + it('invokes checkSetInventoryProgress without error', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation(), + ); + expectedResponse.name = 'test'; + expectedResponse.response = { type_url: 'url', value: Buffer.from('') }; + expectedResponse.metadata = { type_url: 'url', value: Buffer.from('') }; + + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const decodedOperation = await client.checkSetInventoryProgress( + expectedResponse.name, + ); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); - it('invokes checkAddFulfillmentPlacesProgress with error', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedError = new Error('expected'); - - client.operationsClient.getOperation = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.checkAddFulfillmentPlacesProgress(''), expectedError); - assert((client.operationsClient.getOperation as SinonStub) - .getCall(0)); - }); + it('invokes checkSetInventoryProgress with error', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const expectedError = new Error('expected'); + + client.operationsClient.getOperation = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.checkSetInventoryProgress(''), expectedError); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + }); + + describe('addFulfillmentPlaces', () => { + it('invokes addFulfillmentPlaces without error', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.AddFulfillmentPlacesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.AddFulfillmentPlacesRequest', + ['product'], + ); + request.product = defaultValue1; + const expectedHeaderRequestParams = `product=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.addFulfillmentPlaces = + stubLongRunningCall(expectedResponse); + const [operation] = await client.addFulfillmentPlaces(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.addFulfillmentPlaces as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.addFulfillmentPlaces as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('removeFulfillmentPlaces', () => { - it('invokes removeFulfillmentPlaces without error', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.RemoveFulfillmentPlacesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.RemoveFulfillmentPlacesRequest', ['product']); - request.product = defaultValue1; - const expectedHeaderRequestParams = `product=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.removeFulfillmentPlaces = stubLongRunningCall(expectedResponse); - const [operation] = await client.removeFulfillmentPlaces(request); - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.removeFulfillmentPlaces as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.removeFulfillmentPlaces as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes addFulfillmentPlaces without error using callback', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.AddFulfillmentPlacesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.AddFulfillmentPlacesRequest', + ['product'], + ); + request.product = defaultValue1; + const expectedHeaderRequestParams = `product=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.addFulfillmentPlaces = + stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.addFulfillmentPlaces( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.cloud.retail.v2alpha.IAddFulfillmentPlacesResponse, + protos.google.cloud.retail.v2alpha.IAddFulfillmentPlacesMetadata + > | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const operation = (await promise) as LROperation< + protos.google.cloud.retail.v2alpha.IAddFulfillmentPlacesResponse, + protos.google.cloud.retail.v2alpha.IAddFulfillmentPlacesMetadata + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.addFulfillmentPlaces as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.addFulfillmentPlaces as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes removeFulfillmentPlaces without error using callback', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.RemoveFulfillmentPlacesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.RemoveFulfillmentPlacesRequest', ['product']); - request.product = defaultValue1; - const expectedHeaderRequestParams = `product=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.removeFulfillmentPlaces = stubLongRunningCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.removeFulfillmentPlaces( - request, - (err?: Error|null, - result?: LROperation|null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const operation = await promise as LROperation; - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.removeFulfillmentPlaces as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.removeFulfillmentPlaces as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes addFulfillmentPlaces with call error', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.AddFulfillmentPlacesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.AddFulfillmentPlacesRequest', + ['product'], + ); + request.product = defaultValue1; + const expectedHeaderRequestParams = `product=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.addFulfillmentPlaces = stubLongRunningCall( + undefined, + expectedError, + ); + await assert.rejects(client.addFulfillmentPlaces(request), expectedError); + const actualRequest = ( + client.innerApiCalls.addFulfillmentPlaces as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.addFulfillmentPlaces as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes removeFulfillmentPlaces with call error', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.RemoveFulfillmentPlacesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.RemoveFulfillmentPlacesRequest', ['product']); - request.product = defaultValue1; - const expectedHeaderRequestParams = `product=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.removeFulfillmentPlaces = stubLongRunningCall(undefined, expectedError); - await assert.rejects(client.removeFulfillmentPlaces(request), expectedError); - const actualRequest = (client.innerApiCalls.removeFulfillmentPlaces as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.removeFulfillmentPlaces as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes addFulfillmentPlaces with LRO error', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.AddFulfillmentPlacesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.AddFulfillmentPlacesRequest', + ['product'], + ); + request.product = defaultValue1; + const expectedHeaderRequestParams = `product=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.addFulfillmentPlaces = stubLongRunningCall( + undefined, + undefined, + expectedError, + ); + const [operation] = await client.addFulfillmentPlaces(request); + await assert.rejects(operation.promise(), expectedError); + const actualRequest = ( + client.innerApiCalls.addFulfillmentPlaces as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.addFulfillmentPlaces as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes removeFulfillmentPlaces with LRO error', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.RemoveFulfillmentPlacesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.RemoveFulfillmentPlacesRequest', ['product']); - request.product = defaultValue1; - const expectedHeaderRequestParams = `product=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.removeFulfillmentPlaces = stubLongRunningCall(undefined, undefined, expectedError); - const [operation] = await client.removeFulfillmentPlaces(request); - await assert.rejects(operation.promise(), expectedError); - const actualRequest = (client.innerApiCalls.removeFulfillmentPlaces as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.removeFulfillmentPlaces as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes checkAddFulfillmentPlacesProgress without error', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation(), + ); + expectedResponse.name = 'test'; + expectedResponse.response = { type_url: 'url', value: Buffer.from('') }; + expectedResponse.metadata = { type_url: 'url', value: Buffer.from('') }; + + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const decodedOperation = await client.checkAddFulfillmentPlacesProgress( + expectedResponse.name, + ); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); - it('invokes checkRemoveFulfillmentPlacesProgress without error', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedResponse = generateSampleMessage( - new operationsProtos.google.longrunning.Operation() - ); - expectedResponse.name = 'test'; - expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; - expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')} - - client.operationsClient.getOperation = stubSimpleCall(expectedResponse); - const decodedOperation = await client.checkRemoveFulfillmentPlacesProgress(expectedResponse.name); - assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); - assert(decodedOperation.metadata); - assert((client.operationsClient.getOperation as SinonStub).getCall(0)); - }); + it('invokes checkAddFulfillmentPlacesProgress with error', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const expectedError = new Error('expected'); + + client.operationsClient.getOperation = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.checkAddFulfillmentPlacesProgress(''), + expectedError, + ); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + }); + + describe('removeFulfillmentPlaces', () => { + it('invokes removeFulfillmentPlaces without error', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.RemoveFulfillmentPlacesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.RemoveFulfillmentPlacesRequest', + ['product'], + ); + request.product = defaultValue1; + const expectedHeaderRequestParams = `product=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.removeFulfillmentPlaces = + stubLongRunningCall(expectedResponse); + const [operation] = await client.removeFulfillmentPlaces(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.removeFulfillmentPlaces as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.removeFulfillmentPlaces as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkRemoveFulfillmentPlacesProgress with error', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedError = new Error('expected'); - - client.operationsClient.getOperation = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.checkRemoveFulfillmentPlacesProgress(''), expectedError); - assert((client.operationsClient.getOperation as SinonStub) - .getCall(0)); - }); + it('invokes removeFulfillmentPlaces without error using callback', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.RemoveFulfillmentPlacesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.RemoveFulfillmentPlacesRequest', + ['product'], + ); + request.product = defaultValue1; + const expectedHeaderRequestParams = `product=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.removeFulfillmentPlaces = + stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.removeFulfillmentPlaces( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.cloud.retail.v2alpha.IRemoveFulfillmentPlacesResponse, + protos.google.cloud.retail.v2alpha.IRemoveFulfillmentPlacesMetadata + > | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const operation = (await promise) as LROperation< + protos.google.cloud.retail.v2alpha.IRemoveFulfillmentPlacesResponse, + protos.google.cloud.retail.v2alpha.IRemoveFulfillmentPlacesMetadata + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.removeFulfillmentPlaces as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.removeFulfillmentPlaces as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('addLocalInventories', () => { - it('invokes addLocalInventories without error', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.AddLocalInventoriesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.AddLocalInventoriesRequest', ['product']); - request.product = defaultValue1; - const expectedHeaderRequestParams = `product=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.addLocalInventories = stubLongRunningCall(expectedResponse); - const [operation] = await client.addLocalInventories(request); - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.addLocalInventories as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.addLocalInventories as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes removeFulfillmentPlaces with call error', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.RemoveFulfillmentPlacesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.RemoveFulfillmentPlacesRequest', + ['product'], + ); + request.product = defaultValue1; + const expectedHeaderRequestParams = `product=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.removeFulfillmentPlaces = stubLongRunningCall( + undefined, + expectedError, + ); + await assert.rejects( + client.removeFulfillmentPlaces(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.removeFulfillmentPlaces as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.removeFulfillmentPlaces as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes addLocalInventories without error using callback', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.AddLocalInventoriesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.AddLocalInventoriesRequest', ['product']); - request.product = defaultValue1; - const expectedHeaderRequestParams = `product=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.addLocalInventories = stubLongRunningCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.addLocalInventories( - request, - (err?: Error|null, - result?: LROperation|null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const operation = await promise as LROperation; - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.addLocalInventories as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.addLocalInventories as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes removeFulfillmentPlaces with LRO error', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.RemoveFulfillmentPlacesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.RemoveFulfillmentPlacesRequest', + ['product'], + ); + request.product = defaultValue1; + const expectedHeaderRequestParams = `product=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.removeFulfillmentPlaces = stubLongRunningCall( + undefined, + undefined, + expectedError, + ); + const [operation] = await client.removeFulfillmentPlaces(request); + await assert.rejects(operation.promise(), expectedError); + const actualRequest = ( + client.innerApiCalls.removeFulfillmentPlaces as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.removeFulfillmentPlaces as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes addLocalInventories with call error', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.AddLocalInventoriesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.AddLocalInventoriesRequest', ['product']); - request.product = defaultValue1; - const expectedHeaderRequestParams = `product=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.addLocalInventories = stubLongRunningCall(undefined, expectedError); - await assert.rejects(client.addLocalInventories(request), expectedError); - const actualRequest = (client.innerApiCalls.addLocalInventories as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.addLocalInventories as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes checkRemoveFulfillmentPlacesProgress without error', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation(), + ); + expectedResponse.name = 'test'; + expectedResponse.response = { type_url: 'url', value: Buffer.from('') }; + expectedResponse.metadata = { type_url: 'url', value: Buffer.from('') }; + + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const decodedOperation = + await client.checkRemoveFulfillmentPlacesProgress( + expectedResponse.name, + ); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); - it('invokes addLocalInventories with LRO error', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.AddLocalInventoriesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.AddLocalInventoriesRequest', ['product']); - request.product = defaultValue1; - const expectedHeaderRequestParams = `product=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.addLocalInventories = stubLongRunningCall(undefined, undefined, expectedError); - const [operation] = await client.addLocalInventories(request); - await assert.rejects(operation.promise(), expectedError); - const actualRequest = (client.innerApiCalls.addLocalInventories as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.addLocalInventories as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes checkRemoveFulfillmentPlacesProgress with error', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const expectedError = new Error('expected'); + + client.operationsClient.getOperation = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.checkRemoveFulfillmentPlacesProgress(''), + expectedError, + ); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + }); + + describe('addLocalInventories', () => { + it('invokes addLocalInventories without error', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.AddLocalInventoriesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.AddLocalInventoriesRequest', + ['product'], + ); + request.product = defaultValue1; + const expectedHeaderRequestParams = `product=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.addLocalInventories = + stubLongRunningCall(expectedResponse); + const [operation] = await client.addLocalInventories(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.addLocalInventories as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.addLocalInventories as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkAddLocalInventoriesProgress without error', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedResponse = generateSampleMessage( - new operationsProtos.google.longrunning.Operation() - ); - expectedResponse.name = 'test'; - expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; - expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')} - - client.operationsClient.getOperation = stubSimpleCall(expectedResponse); - const decodedOperation = await client.checkAddLocalInventoriesProgress(expectedResponse.name); - assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); - assert(decodedOperation.metadata); - assert((client.operationsClient.getOperation as SinonStub).getCall(0)); - }); + it('invokes addLocalInventories without error using callback', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.AddLocalInventoriesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.AddLocalInventoriesRequest', + ['product'], + ); + request.product = defaultValue1; + const expectedHeaderRequestParams = `product=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.addLocalInventories = + stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.addLocalInventories( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.cloud.retail.v2alpha.IAddLocalInventoriesResponse, + protos.google.cloud.retail.v2alpha.IAddLocalInventoriesMetadata + > | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const operation = (await promise) as LROperation< + protos.google.cloud.retail.v2alpha.IAddLocalInventoriesResponse, + protos.google.cloud.retail.v2alpha.IAddLocalInventoriesMetadata + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.addLocalInventories as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.addLocalInventories as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkAddLocalInventoriesProgress with error', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedError = new Error('expected'); - - client.operationsClient.getOperation = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.checkAddLocalInventoriesProgress(''), expectedError); - assert((client.operationsClient.getOperation as SinonStub) - .getCall(0)); - }); + it('invokes addLocalInventories with call error', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.AddLocalInventoriesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.AddLocalInventoriesRequest', + ['product'], + ); + request.product = defaultValue1; + const expectedHeaderRequestParams = `product=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.addLocalInventories = stubLongRunningCall( + undefined, + expectedError, + ); + await assert.rejects(client.addLocalInventories(request), expectedError); + const actualRequest = ( + client.innerApiCalls.addLocalInventories as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.addLocalInventories as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('removeLocalInventories', () => { - it('invokes removeLocalInventories without error', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.RemoveLocalInventoriesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.RemoveLocalInventoriesRequest', ['product']); - request.product = defaultValue1; - const expectedHeaderRequestParams = `product=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.removeLocalInventories = stubLongRunningCall(expectedResponse); - const [operation] = await client.removeLocalInventories(request); - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.removeLocalInventories as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.removeLocalInventories as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes addLocalInventories with LRO error', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.AddLocalInventoriesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.AddLocalInventoriesRequest', + ['product'], + ); + request.product = defaultValue1; + const expectedHeaderRequestParams = `product=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.addLocalInventories = stubLongRunningCall( + undefined, + undefined, + expectedError, + ); + const [operation] = await client.addLocalInventories(request); + await assert.rejects(operation.promise(), expectedError); + const actualRequest = ( + client.innerApiCalls.addLocalInventories as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.addLocalInventories as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes removeLocalInventories without error using callback', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.RemoveLocalInventoriesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.RemoveLocalInventoriesRequest', ['product']); - request.product = defaultValue1; - const expectedHeaderRequestParams = `product=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.removeLocalInventories = stubLongRunningCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.removeLocalInventories( - request, - (err?: Error|null, - result?: LROperation|null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const operation = await promise as LROperation; - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.removeLocalInventories as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.removeLocalInventories as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes checkAddLocalInventoriesProgress without error', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation(), + ); + expectedResponse.name = 'test'; + expectedResponse.response = { type_url: 'url', value: Buffer.from('') }; + expectedResponse.metadata = { type_url: 'url', value: Buffer.from('') }; + + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const decodedOperation = await client.checkAddLocalInventoriesProgress( + expectedResponse.name, + ); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); - it('invokes removeLocalInventories with call error', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.RemoveLocalInventoriesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.RemoveLocalInventoriesRequest', ['product']); - request.product = defaultValue1; - const expectedHeaderRequestParams = `product=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.removeLocalInventories = stubLongRunningCall(undefined, expectedError); - await assert.rejects(client.removeLocalInventories(request), expectedError); - const actualRequest = (client.innerApiCalls.removeLocalInventories as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.removeLocalInventories as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes checkAddLocalInventoriesProgress with error', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const expectedError = new Error('expected'); + + client.operationsClient.getOperation = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.checkAddLocalInventoriesProgress(''), + expectedError, + ); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + }); + + describe('removeLocalInventories', () => { + it('invokes removeLocalInventories without error', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.RemoveLocalInventoriesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.RemoveLocalInventoriesRequest', + ['product'], + ); + request.product = defaultValue1; + const expectedHeaderRequestParams = `product=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.removeLocalInventories = + stubLongRunningCall(expectedResponse); + const [operation] = await client.removeLocalInventories(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.removeLocalInventories as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.removeLocalInventories as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes removeLocalInventories with LRO error', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.RemoveLocalInventoriesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.RemoveLocalInventoriesRequest', ['product']); - request.product = defaultValue1; - const expectedHeaderRequestParams = `product=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.removeLocalInventories = stubLongRunningCall(undefined, undefined, expectedError); - const [operation] = await client.removeLocalInventories(request); - await assert.rejects(operation.promise(), expectedError); - const actualRequest = (client.innerApiCalls.removeLocalInventories as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.removeLocalInventories as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes removeLocalInventories without error using callback', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.RemoveLocalInventoriesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.RemoveLocalInventoriesRequest', + ['product'], + ); + request.product = defaultValue1; + const expectedHeaderRequestParams = `product=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.removeLocalInventories = + stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.removeLocalInventories( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.cloud.retail.v2alpha.IRemoveLocalInventoriesResponse, + protos.google.cloud.retail.v2alpha.IRemoveLocalInventoriesMetadata + > | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const operation = (await promise) as LROperation< + protos.google.cloud.retail.v2alpha.IRemoveLocalInventoriesResponse, + protos.google.cloud.retail.v2alpha.IRemoveLocalInventoriesMetadata + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.removeLocalInventories as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.removeLocalInventories as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkRemoveLocalInventoriesProgress without error', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedResponse = generateSampleMessage( - new operationsProtos.google.longrunning.Operation() - ); - expectedResponse.name = 'test'; - expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; - expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')} - - client.operationsClient.getOperation = stubSimpleCall(expectedResponse); - const decodedOperation = await client.checkRemoveLocalInventoriesProgress(expectedResponse.name); - assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); - assert(decodedOperation.metadata); - assert((client.operationsClient.getOperation as SinonStub).getCall(0)); - }); + it('invokes removeLocalInventories with call error', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.RemoveLocalInventoriesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.RemoveLocalInventoriesRequest', + ['product'], + ); + request.product = defaultValue1; + const expectedHeaderRequestParams = `product=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.removeLocalInventories = stubLongRunningCall( + undefined, + expectedError, + ); + await assert.rejects( + client.removeLocalInventories(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.removeLocalInventories as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.removeLocalInventories as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkRemoveLocalInventoriesProgress with error', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedError = new Error('expected'); - - client.operationsClient.getOperation = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.checkRemoveLocalInventoriesProgress(''), expectedError); - assert((client.operationsClient.getOperation as SinonStub) - .getCall(0)); - }); + it('invokes removeLocalInventories with LRO error', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.RemoveLocalInventoriesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.RemoveLocalInventoriesRequest', + ['product'], + ); + request.product = defaultValue1; + const expectedHeaderRequestParams = `product=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.removeLocalInventories = stubLongRunningCall( + undefined, + undefined, + expectedError, + ); + const [operation] = await client.removeLocalInventories(request); + await assert.rejects(operation.promise(), expectedError); + const actualRequest = ( + client.innerApiCalls.removeLocalInventories as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.removeLocalInventories as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('listProducts', () => { - it('invokes listProducts without error', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ListProductsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ListProductsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.retail.v2alpha.Product()), - generateSampleMessage(new protos.google.cloud.retail.v2alpha.Product()), - generateSampleMessage(new protos.google.cloud.retail.v2alpha.Product()), - ]; - client.innerApiCalls.listProducts = stubSimpleCall(expectedResponse); - const [response] = await client.listProducts(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listProducts as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listProducts as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes checkRemoveLocalInventoriesProgress without error', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation(), + ); + expectedResponse.name = 'test'; + expectedResponse.response = { type_url: 'url', value: Buffer.from('') }; + expectedResponse.metadata = { type_url: 'url', value: Buffer.from('') }; + + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const decodedOperation = await client.checkRemoveLocalInventoriesProgress( + expectedResponse.name, + ); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); - it('invokes listProducts without error using callback', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ListProductsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ListProductsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.retail.v2alpha.Product()), - generateSampleMessage(new protos.google.cloud.retail.v2alpha.Product()), - generateSampleMessage(new protos.google.cloud.retail.v2alpha.Product()), - ]; - client.innerApiCalls.listProducts = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listProducts( - request, - (err?: Error|null, result?: protos.google.cloud.retail.v2alpha.IProduct[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listProducts as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listProducts as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes checkRemoveLocalInventoriesProgress with error', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const expectedError = new Error('expected'); + + client.operationsClient.getOperation = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.checkRemoveLocalInventoriesProgress(''), + expectedError, + ); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + }); + + describe('listProducts', () => { + it('invokes listProducts without error', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ListProductsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ListProductsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.retail.v2alpha.Product()), + generateSampleMessage(new protos.google.cloud.retail.v2alpha.Product()), + generateSampleMessage(new protos.google.cloud.retail.v2alpha.Product()), + ]; + client.innerApiCalls.listProducts = stubSimpleCall(expectedResponse); + const [response] = await client.listProducts(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listProducts as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listProducts as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listProducts with error', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ListProductsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ListProductsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listProducts = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listProducts(request), expectedError); - const actualRequest = (client.innerApiCalls.listProducts as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listProducts as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listProducts without error using callback', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ListProductsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ListProductsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.retail.v2alpha.Product()), + generateSampleMessage(new protos.google.cloud.retail.v2alpha.Product()), + generateSampleMessage(new protos.google.cloud.retail.v2alpha.Product()), + ]; + client.innerApiCalls.listProducts = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listProducts( + request, + ( + err?: Error | null, + result?: protos.google.cloud.retail.v2alpha.IProduct[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listProducts as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listProducts as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listProductsStream without error', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ListProductsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ListProductsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.retail.v2alpha.Product()), - generateSampleMessage(new protos.google.cloud.retail.v2alpha.Product()), - generateSampleMessage(new protos.google.cloud.retail.v2alpha.Product()), - ]; - client.descriptors.page.listProducts.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listProductsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.cloud.retail.v2alpha.Product[] = []; - stream.on('data', (response: protos.google.cloud.retail.v2alpha.Product) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.listProducts.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listProducts, request)); - assert( - (client.descriptors.page.listProducts.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listProducts with error', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ListProductsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ListProductsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listProducts = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listProducts(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listProducts as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listProducts as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listProductsStream with error', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ListProductsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ListProductsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listProducts.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listProductsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.cloud.retail.v2alpha.Product[] = []; - stream.on('data', (response: protos.google.cloud.retail.v2alpha.Product) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listProducts.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listProducts, request)); - assert( - (client.descriptors.page.listProducts.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listProductsStream without error', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ListProductsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ListProductsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.retail.v2alpha.Product()), + generateSampleMessage(new protos.google.cloud.retail.v2alpha.Product()), + generateSampleMessage(new protos.google.cloud.retail.v2alpha.Product()), + ]; + client.descriptors.page.listProducts.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listProductsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.cloud.retail.v2alpha.Product[] = []; + stream.on( + 'data', + (response: protos.google.cloud.retail.v2alpha.Product) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listProducts.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listProducts, request), + ); + assert( + (client.descriptors.page.listProducts.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('uses async iteration with listProducts without error', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ListProductsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ListProductsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.retail.v2alpha.Product()), - generateSampleMessage(new protos.google.cloud.retail.v2alpha.Product()), - generateSampleMessage(new protos.google.cloud.retail.v2alpha.Product()), - ]; - client.descriptors.page.listProducts.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.cloud.retail.v2alpha.IProduct[] = []; - const iterable = client.listProductsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listProducts.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listProducts.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listProductsStream with error', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ListProductsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ListProductsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listProducts.createStream = stubPageStreamingCall( + undefined, + expectedError, + ); + const stream = client.listProductsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.cloud.retail.v2alpha.Product[] = []; + stream.on( + 'data', + (response: protos.google.cloud.retail.v2alpha.Product) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listProducts.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listProducts, request), + ); + assert( + (client.descriptors.page.listProducts.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('uses async iteration with listProducts with error', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ListProductsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ListProductsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listProducts.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listProductsAsync(request); - await assert.rejects(async () => { - const responses: protos.google.cloud.retail.v2alpha.IProduct[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listProducts.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listProducts.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listProducts without error', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ListProductsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ListProductsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.retail.v2alpha.Product()), + generateSampleMessage(new protos.google.cloud.retail.v2alpha.Product()), + generateSampleMessage(new protos.google.cloud.retail.v2alpha.Product()), + ]; + client.descriptors.page.listProducts.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.cloud.retail.v2alpha.IProduct[] = []; + const iterable = client.listProductsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listProducts.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listProducts.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); }); - describe('Path templates', () => { - - describe('alertConfig', () => { - const fakePath = "/rendered/path/alertConfig"; - const expectedParameters = { - project: "projectValue", - }; - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.alertConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.alertConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('alertConfigPath', () => { - const result = client.alertConfigPath("projectValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.alertConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromAlertConfigName', () => { - const result = client.matchProjectFromAlertConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.alertConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('uses async iteration with listProducts with error', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ListProductsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ListProductsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listProducts.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listProductsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.cloud.retail.v2alpha.IProduct[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listProducts.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listProducts.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + }); + + describe('Path templates', () => { + describe('alertConfig', () => { + const fakePath = '/rendered/path/alertConfig'; + const expectedParameters = { + project: 'projectValue', + }; + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.alertConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.alertConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('alertConfigPath', () => { + const result = client.alertConfigPath('projectValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.alertConfigPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromAlertConfigName', () => { + const result = client.matchProjectFromAlertConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.alertConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('attributesConfig', () => { - const fakePath = "/rendered/path/attributesConfig"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - }; - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.attributesConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.attributesConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('attributesConfigPath', () => { - const result = client.attributesConfigPath("projectValue", "locationValue", "catalogValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.attributesConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromAttributesConfigName', () => { - const result = client.matchProjectFromAttributesConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromAttributesConfigName', () => { - const result = client.matchLocationFromAttributesConfigName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromAttributesConfigName', () => { - const result = client.matchCatalogFromAttributesConfigName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('attributesConfig', () => { + const fakePath = '/rendered/path/attributesConfig'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + }; + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.attributesConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.attributesConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('attributesConfigPath', () => { + const result = client.attributesConfigPath( + 'projectValue', + 'locationValue', + 'catalogValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.attributesConfigPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromAttributesConfigName', () => { + const result = client.matchProjectFromAttributesConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromAttributesConfigName', () => { + const result = client.matchLocationFromAttributesConfigName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromAttributesConfigName', () => { + const result = client.matchCatalogFromAttributesConfigName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('branch', () => { - const fakePath = "/rendered/path/branch"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - branch: "branchValue", - }; - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.branchPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.branchPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('branchPath', () => { - const result = client.branchPath("projectValue", "locationValue", "catalogValue", "branchValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.branchPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromBranchName', () => { - const result = client.matchProjectFromBranchName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.branchPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromBranchName', () => { - const result = client.matchLocationFromBranchName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.branchPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromBranchName', () => { - const result = client.matchCatalogFromBranchName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.branchPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBranchFromBranchName', () => { - const result = client.matchBranchFromBranchName(fakePath); - assert.strictEqual(result, "branchValue"); - assert((client.pathTemplates.branchPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('branch', () => { + const fakePath = '/rendered/path/branch'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + branch: 'branchValue', + }; + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.branchPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.branchPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('branchPath', () => { + const result = client.branchPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'branchValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.branchPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromBranchName', () => { + const result = client.matchProjectFromBranchName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.branchPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromBranchName', () => { + const result = client.matchLocationFromBranchName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.branchPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromBranchName', () => { + const result = client.matchCatalogFromBranchName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.branchPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBranchFromBranchName', () => { + const result = client.matchBranchFromBranchName(fakePath); + assert.strictEqual(result, 'branchValue'); + assert( + (client.pathTemplates.branchPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('catalog', () => { - const fakePath = "/rendered/path/catalog"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - }; - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.catalogPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.catalogPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('catalogPath', () => { - const result = client.catalogPath("projectValue", "locationValue", "catalogValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.catalogPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromCatalogName', () => { - const result = client.matchProjectFromCatalogName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.catalogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromCatalogName', () => { - const result = client.matchLocationFromCatalogName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.catalogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromCatalogName', () => { - const result = client.matchCatalogFromCatalogName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.catalogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('catalog', () => { + const fakePath = '/rendered/path/catalog'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + }; + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.catalogPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.catalogPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('catalogPath', () => { + const result = client.catalogPath( + 'projectValue', + 'locationValue', + 'catalogValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.catalogPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromCatalogName', () => { + const result = client.matchProjectFromCatalogName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.catalogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromCatalogName', () => { + const result = client.matchLocationFromCatalogName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.catalogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromCatalogName', () => { + const result = client.matchCatalogFromCatalogName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.catalogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('completionConfig', () => { - const fakePath = "/rendered/path/completionConfig"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - }; - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.completionConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.completionConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('completionConfigPath', () => { - const result = client.completionConfigPath("projectValue", "locationValue", "catalogValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.completionConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromCompletionConfigName', () => { - const result = client.matchProjectFromCompletionConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.completionConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromCompletionConfigName', () => { - const result = client.matchLocationFromCompletionConfigName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.completionConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromCompletionConfigName', () => { - const result = client.matchCatalogFromCompletionConfigName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.completionConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('completionConfig', () => { + const fakePath = '/rendered/path/completionConfig'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + }; + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.completionConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.completionConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('completionConfigPath', () => { + const result = client.completionConfigPath( + 'projectValue', + 'locationValue', + 'catalogValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.completionConfigPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromCompletionConfigName', () => { + const result = client.matchProjectFromCompletionConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.completionConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromCompletionConfigName', () => { + const result = client.matchLocationFromCompletionConfigName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.completionConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromCompletionConfigName', () => { + const result = client.matchCatalogFromCompletionConfigName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.completionConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('control', () => { - const fakePath = "/rendered/path/control"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - control: "controlValue", - }; - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.controlPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.controlPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('controlPath', () => { - const result = client.controlPath("projectValue", "locationValue", "catalogValue", "controlValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.controlPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromControlName', () => { - const result = client.matchProjectFromControlName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.controlPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromControlName', () => { - const result = client.matchLocationFromControlName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.controlPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromControlName', () => { - const result = client.matchCatalogFromControlName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.controlPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchControlFromControlName', () => { - const result = client.matchControlFromControlName(fakePath); - assert.strictEqual(result, "controlValue"); - assert((client.pathTemplates.controlPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('control', () => { + const fakePath = '/rendered/path/control'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + control: 'controlValue', + }; + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.controlPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.controlPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('controlPath', () => { + const result = client.controlPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'controlValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.controlPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromControlName', () => { + const result = client.matchProjectFromControlName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.controlPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromControlName', () => { + const result = client.matchLocationFromControlName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.controlPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromControlName', () => { + const result = client.matchCatalogFromControlName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.controlPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchControlFromControlName', () => { + const result = client.matchControlFromControlName(fakePath); + assert.strictEqual(result, 'controlValue'); + assert( + (client.pathTemplates.controlPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('loggingConfig', () => { - const fakePath = "/rendered/path/loggingConfig"; - const expectedParameters = { - project: "projectValue", - }; - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.loggingConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.loggingConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('loggingConfigPath', () => { - const result = client.loggingConfigPath("projectValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.loggingConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromLoggingConfigName', () => { - const result = client.matchProjectFromLoggingConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.loggingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('loggingConfig', () => { + const fakePath = '/rendered/path/loggingConfig'; + const expectedParameters = { + project: 'projectValue', + }; + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.loggingConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.loggingConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('loggingConfigPath', () => { + const result = client.loggingConfigPath('projectValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.loggingConfigPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromLoggingConfigName', () => { + const result = client.matchProjectFromLoggingConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.loggingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('merchantCenterAccountLink', () => { - const fakePath = "/rendered/path/merchantCenterAccountLink"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - merchant_center_account_link: "merchantCenterAccountLinkValue", - }; - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.merchantCenterAccountLinkPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.merchantCenterAccountLinkPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('merchantCenterAccountLinkPath', () => { - const result = client.merchantCenterAccountLinkPath("projectValue", "locationValue", "catalogValue", "merchantCenterAccountLinkValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromMerchantCenterAccountLinkName', () => { - const result = client.matchProjectFromMerchantCenterAccountLinkName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromMerchantCenterAccountLinkName', () => { - const result = client.matchLocationFromMerchantCenterAccountLinkName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromMerchantCenterAccountLinkName', () => { - const result = client.matchCatalogFromMerchantCenterAccountLinkName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName', () => { - const result = client.matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName(fakePath); - assert.strictEqual(result, "merchantCenterAccountLinkValue"); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('merchantCenterAccountLink', () => { + const fakePath = '/rendered/path/merchantCenterAccountLink'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + merchant_center_account_link: 'merchantCenterAccountLinkValue', + }; + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.merchantCenterAccountLinkPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.merchantCenterAccountLinkPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('merchantCenterAccountLinkPath', () => { + const result = client.merchantCenterAccountLinkPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'merchantCenterAccountLinkValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromMerchantCenterAccountLinkName', () => { + const result = + client.matchProjectFromMerchantCenterAccountLinkName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromMerchantCenterAccountLinkName', () => { + const result = + client.matchLocationFromMerchantCenterAccountLinkName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromMerchantCenterAccountLinkName', () => { + const result = + client.matchCatalogFromMerchantCenterAccountLinkName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName', () => { + const result = + client.matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName( + fakePath, + ); + assert.strictEqual(result, 'merchantCenterAccountLinkValue'); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('model', () => { - const fakePath = "/rendered/path/model"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - model: "modelValue", - }; - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.modelPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.modelPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('modelPath', () => { - const result = client.modelPath("projectValue", "locationValue", "catalogValue", "modelValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.modelPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromModelName', () => { - const result = client.matchProjectFromModelName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromModelName', () => { - const result = client.matchLocationFromModelName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromModelName', () => { - const result = client.matchCatalogFromModelName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchModelFromModelName', () => { - const result = client.matchModelFromModelName(fakePath); - assert.strictEqual(result, "modelValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('model', () => { + const fakePath = '/rendered/path/model'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + model: 'modelValue', + }; + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.modelPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.modelPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('modelPath', () => { + const result = client.modelPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'modelValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.modelPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromModelName', () => { + const result = client.matchProjectFromModelName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromModelName', () => { + const result = client.matchLocationFromModelName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromModelName', () => { + const result = client.matchCatalogFromModelName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchModelFromModelName', () => { + const result = client.matchModelFromModelName(fakePath); + assert.strictEqual(result, 'modelValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('product', () => { - const fakePath = "/rendered/path/product"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - branch: "branchValue", - product: "productValue", - }; - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.productPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.productPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('productPath', () => { - const result = client.productPath("projectValue", "locationValue", "catalogValue", "branchValue", "productValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.productPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProductName', () => { - const result = client.matchProjectFromProductName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromProductName', () => { - const result = client.matchLocationFromProductName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromProductName', () => { - const result = client.matchCatalogFromProductName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBranchFromProductName', () => { - const result = client.matchBranchFromProductName(fakePath); - assert.strictEqual(result, "branchValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchProductFromProductName', () => { - const result = client.matchProductFromProductName(fakePath); - assert.strictEqual(result, "productValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('product', () => { + const fakePath = '/rendered/path/product'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + branch: 'branchValue', + product: 'productValue', + }; + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.productPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.productPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('productPath', () => { + const result = client.productPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'branchValue', + 'productValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.productPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProductName', () => { + const result = client.matchProjectFromProductName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromProductName', () => { + const result = client.matchLocationFromProductName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromProductName', () => { + const result = client.matchCatalogFromProductName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBranchFromProductName', () => { + const result = client.matchBranchFromProductName(fakePath); + assert.strictEqual(result, 'branchValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchProductFromProductName', () => { + const result = client.matchProductFromProductName(fakePath); + assert.strictEqual(result, 'productValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('retailProject', () => { - const fakePath = "/rendered/path/retailProject"; - const expectedParameters = { - project: "projectValue", - }; - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.retailProjectPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.retailProjectPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('retailProjectPath', () => { - const result = client.retailProjectPath("projectValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.retailProjectPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromRetailProjectName', () => { - const result = client.matchProjectFromRetailProjectName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.retailProjectPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('retailProject', () => { + const fakePath = '/rendered/path/retailProject'; + const expectedParameters = { + project: 'projectValue', + }; + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.retailProjectPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.retailProjectPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('retailProjectPath', () => { + const result = client.retailProjectPath('projectValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.retailProjectPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromRetailProjectName', () => { + const result = client.matchProjectFromRetailProjectName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.retailProjectPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('servingConfig', () => { - const fakePath = "/rendered/path/servingConfig"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - serving_config: "servingConfigValue", - }; - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.servingConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.servingConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('servingConfigPath', () => { - const result = client.servingConfigPath("projectValue", "locationValue", "catalogValue", "servingConfigValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.servingConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromServingConfigName', () => { - const result = client.matchProjectFromServingConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.servingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromServingConfigName', () => { - const result = client.matchLocationFromServingConfigName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.servingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromServingConfigName', () => { - const result = client.matchCatalogFromServingConfigName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.servingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServingConfigFromServingConfigName', () => { - const result = client.matchServingConfigFromServingConfigName(fakePath); - assert.strictEqual(result, "servingConfigValue"); - assert((client.pathTemplates.servingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('servingConfig', () => { + const fakePath = '/rendered/path/servingConfig'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + serving_config: 'servingConfigValue', + }; + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.servingConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.servingConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('servingConfigPath', () => { + const result = client.servingConfigPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'servingConfigValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.servingConfigPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromServingConfigName', () => { + const result = client.matchProjectFromServingConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.servingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromServingConfigName', () => { + const result = client.matchLocationFromServingConfigName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.servingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromServingConfigName', () => { + const result = client.matchCatalogFromServingConfigName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.servingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServingConfigFromServingConfigName', () => { + const result = client.matchServingConfigFromServingConfigName(fakePath); + assert.strictEqual(result, 'servingConfigValue'); + assert( + (client.pathTemplates.servingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/test/gapic_project_service_v2alpha.ts.baseline b/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/test/gapic_project_service_v2alpha.ts.baseline index bc734d97200c..b3855b9126bc 100644 --- a/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/test/gapic_project_service_v2alpha.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/test/gapic_project_service_v2alpha.ts.baseline @@ -20,14 +20,14 @@ import * as protos from '../../protos/protos.js'; import assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as projectserviceModule from '../src/index.js'; -import {protobuf, LROperation, operationsProtos} from 'google-gax'; +import { protobuf, LROperation, operationsProtos } from 'google-gax'; import fs from 'fs'; import path from 'path'; -import {fileURLToPath} from 'url'; +import { fileURLToPath } from 'url'; // @ts-ignore const dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -35,1716 +35,2267 @@ const dirname = path.dirname(fileURLToPath(import.meta.url)); // to fill in default values for request objects const root = protobuf.Root.fromJSON( JSON.parse( - fs.readFileSync(path.join(dirname, '..', '..', 'protos/protos.json'), 'utf8') - )) + fs.readFileSync( + path.join(dirname, '..', '..', 'protos/protos.json'), + 'utf8', + ), + ), +); // eslint-disable-next-line @typescript-eslint/no-unused-vars function getTypeDefaultValue(typeName: string, fields: string[]) { - let type = root.lookupType(typeName) as protobuf.Type; - for (const field of fields.slice(0, -1)) { - type = type?.fields[field]?.resolvedType as protobuf.Type; - } - return type?.fields[fields[fields.length - 1]]?.defaultValue ?? null; + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type?.fields[field]?.resolvedType as protobuf.Type; + } + return type?.fields[fields[fields.length - 1]]?.defaultValue ?? null; } function generateSampleMessage(instance: T) { - const filledObject = (instance.constructor as typeof protobuf.Message) - .toObject(instance as protobuf.Message, {defaults: true}); - return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, { defaults: true }); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; } function stubSimpleCall(response?: ResponseType, error?: Error) { - return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); } -function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { - return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +function stubSimpleCallWithCallback( + response?: ResponseType, + error?: Error, +) { + return error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); } -function stubLongRunningCall(response?: ResponseType, callError?: Error, lroError?: Error) { - const innerStub = lroError ? sinon.stub().rejects(lroError) : sinon.stub().resolves([response]); - const mockOperation = { - promise: innerStub, - }; - return callError ? sinon.stub().rejects(callError) : sinon.stub().resolves([mockOperation]); +function stubLongRunningCall( + response?: ResponseType, + callError?: Error, + lroError?: Error, +) { + const innerStub = lroError + ? sinon.stub().rejects(lroError) + : sinon.stub().resolves([response]); + const mockOperation = { + promise: innerStub, + }; + return callError + ? sinon.stub().rejects(callError) + : sinon.stub().resolves([mockOperation]); } -function stubLongRunningCallWithCallback(response?: ResponseType, callError?: Error, lroError?: Error) { - const innerStub = lroError ? sinon.stub().rejects(lroError) : sinon.stub().resolves([response]); - const mockOperation = { - promise: innerStub, - }; - return callError ? sinon.stub().callsArgWith(2, callError) : sinon.stub().callsArgWith(2, null, mockOperation); +function stubLongRunningCallWithCallback( + response?: ResponseType, + callError?: Error, + lroError?: Error, +) { + const innerStub = lroError + ? sinon.stub().rejects(lroError) + : sinon.stub().resolves([response]); + const mockOperation = { + promise: innerStub, + }; + return callError + ? sinon.stub().callsArgWith(2, callError) + : sinon.stub().callsArgWith(2, null, mockOperation); } describe('v2alpha.ProjectServiceClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new projectserviceModule.v2alpha.ProjectServiceClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'retail.googleapis.com'); - }); - - it('has universeDomain', () => { - const client = new projectserviceModule.v2alpha.ProjectServiceClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); - - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - it('throws DeprecationWarning if static servicePath is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const servicePath = projectserviceModule.v2alpha.ProjectServiceClient.servicePath; - assert.strictEqual(servicePath, 'retail.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = projectserviceModule.v2alpha.ProjectServiceClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'retail.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new projectserviceModule.v2alpha.ProjectServiceClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'retail.example.com'); - }); - - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new projectserviceModule.v2alpha.ProjectServiceClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'retail.example.com'); - }); - - if (typeof process === 'object' && 'env' in process) { - describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { - it('sets apiEndpoint from environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new projectserviceModule.v2alpha.ProjectServiceClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'retail.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - - it('value configured in code has priority over environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new projectserviceModule.v2alpha.ProjectServiceClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'retail.configured.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { new projectserviceModule.v2alpha.ProjectServiceClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); - - it('has port', () => { - const port = projectserviceModule.v2alpha.ProjectServiceClient.port; - assert(port); - assert(typeof port === 'number'); - }); - - it('should create a client with no option', () => { - const client = new projectserviceModule.v2alpha.ProjectServiceClient(); - assert(client); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new projectserviceModule.v2alpha.ProjectServiceClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'retail.googleapis.com'); + }); - it('should create a client with gRPC fallback', () => { - const client = new projectserviceModule.v2alpha.ProjectServiceClient({ - fallback: true, - }); - assert(client); - }); + it('has universeDomain', () => { + const client = new projectserviceModule.v2alpha.ProjectServiceClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - it('has initialize method and supports deferred initialization', async () => { - const client = new projectserviceModule.v2alpha.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.projectServiceStub, undefined); - await client.initialize(); - assert(client.projectServiceStub); - }); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = + projectserviceModule.v2alpha.ProjectServiceClient.servicePath; + assert.strictEqual(servicePath, 'retail.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + projectserviceModule.v2alpha.ProjectServiceClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'retail.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = new projectserviceModule.v2alpha.ProjectServiceClient({ + universeDomain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'retail.example.com'); + }); - it('has close method for the initialized client', done => { - const client = new projectserviceModule.v2alpha.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.projectServiceStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = new projectserviceModule.v2alpha.ProjectServiceClient({ + universe_domain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'retail.example.com'); + }); - it('has close method for the non-initialized client', done => { - const client = new projectserviceModule.v2alpha.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.projectServiceStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); + if (typeof process === 'object' && 'env' in process) { + describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { + it('sets apiEndpoint from environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = + new projectserviceModule.v2alpha.ProjectServiceClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'retail.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new projectserviceModule.v2alpha.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + it('value configured in code has priority over environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new projectserviceModule.v2alpha.ProjectServiceClient({ + universeDomain: 'configured.example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'retail.configured.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new projectserviceModule.v2alpha.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId((err?: Error|null, projectId?: string|null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } - }); - }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new projectserviceModule.v2alpha.ProjectServiceClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); }); - describe('getProject', () => { - it('invokes getProject without error', async () => { - const client = new projectserviceModule.v2alpha.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.GetProjectRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.GetProjectRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.Project() - ); - client.innerApiCalls.getProject = stubSimpleCall(expectedResponse); - const [response] = await client.getProject(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getProject as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getProject as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getProject without error using callback', async () => { - const client = new projectserviceModule.v2alpha.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.GetProjectRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.GetProjectRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.Project() - ); - client.innerApiCalls.getProject = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getProject( - request, - (err?: Error|null, result?: protos.google.cloud.retail.v2alpha.IProject|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getProject as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getProject as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has port', () => { + const port = projectserviceModule.v2alpha.ProjectServiceClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('invokes getProject with error', async () => { - const client = new projectserviceModule.v2alpha.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.GetProjectRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.GetProjectRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getProject = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getProject(request), expectedError); - const actualRequest = (client.innerApiCalls.getProject as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getProject as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('should create a client with no option', () => { + const client = new projectserviceModule.v2alpha.ProjectServiceClient(); + assert(client); + }); - it('invokes getProject with closed client', async () => { - const client = new projectserviceModule.v2alpha.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.GetProjectRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.GetProjectRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getProject(request), expectedError); - }); + it('should create a client with gRPC fallback', () => { + const client = new projectserviceModule.v2alpha.ProjectServiceClient({ + fallback: true, + }); + assert(client); }); - describe('acceptTerms', () => { - it('invokes acceptTerms without error', async () => { - const client = new projectserviceModule.v2alpha.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.AcceptTermsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.AcceptTermsRequest', ['project']); - request.project = defaultValue1; - const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.Project() - ); - client.innerApiCalls.acceptTerms = stubSimpleCall(expectedResponse); - const [response] = await client.acceptTerms(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.acceptTerms as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.acceptTerms as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has initialize method and supports deferred initialization', async () => { + const client = new projectserviceModule.v2alpha.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.projectServiceStub, undefined); + await client.initialize(); + assert(client.projectServiceStub); + }); - it('invokes acceptTerms without error using callback', async () => { - const client = new projectserviceModule.v2alpha.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.AcceptTermsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.AcceptTermsRequest', ['project']); - request.project = defaultValue1; - const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.Project() - ); - client.innerApiCalls.acceptTerms = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.acceptTerms( - request, - (err?: Error|null, result?: protos.google.cloud.retail.v2alpha.IProject|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.acceptTerms as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.acceptTerms as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('has close method for the initialized client', (done) => { + const client = new projectserviceModule.v2alpha.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.projectServiceStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes acceptTerms with error', async () => { - const client = new projectserviceModule.v2alpha.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.AcceptTermsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.AcceptTermsRequest', ['project']); - request.project = defaultValue1; - const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.acceptTerms = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.acceptTerms(request), expectedError); - const actualRequest = (client.innerApiCalls.acceptTerms as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.acceptTerms as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('has close method for the non-initialized client', (done) => { + const client = new projectserviceModule.v2alpha.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.projectServiceStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes acceptTerms with closed client', async () => { - const client = new projectserviceModule.v2alpha.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.AcceptTermsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.AcceptTermsRequest', ['project']); - request.project = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.acceptTerms(request), expectedError); - }); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new projectserviceModule.v2alpha.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); }); - describe('listEnrolledSolutions', () => { - it('invokes listEnrolledSolutions without error', async () => { - const client = new projectserviceModule.v2alpha.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ListEnrolledSolutionsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ListEnrolledSolutionsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ListEnrolledSolutionsResponse() - ); - client.innerApiCalls.listEnrolledSolutions = stubSimpleCall(expectedResponse); - const [response] = await client.listEnrolledSolutions(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listEnrolledSolutions as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listEnrolledSolutions as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new projectserviceModule.v2alpha.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + }); + + describe('getProject', () => { + it('invokes getProject without error', async () => { + const client = new projectserviceModule.v2alpha.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.GetProjectRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.GetProjectRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.Project(), + ); + client.innerApiCalls.getProject = stubSimpleCall(expectedResponse); + const [response] = await client.getProject(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getProject as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getProject as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listEnrolledSolutions without error using callback', async () => { - const client = new projectserviceModule.v2alpha.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ListEnrolledSolutionsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ListEnrolledSolutionsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ListEnrolledSolutionsResponse() - ); - client.innerApiCalls.listEnrolledSolutions = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listEnrolledSolutions( - request, - (err?: Error|null, result?: protos.google.cloud.retail.v2alpha.IListEnrolledSolutionsResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listEnrolledSolutions as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listEnrolledSolutions as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getProject without error using callback', async () => { + const client = new projectserviceModule.v2alpha.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.GetProjectRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.GetProjectRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.Project(), + ); + client.innerApiCalls.getProject = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getProject( + request, + ( + err?: Error | null, + result?: protos.google.cloud.retail.v2alpha.IProject | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getProject as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getProject as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listEnrolledSolutions with error', async () => { - const client = new projectserviceModule.v2alpha.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ListEnrolledSolutionsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ListEnrolledSolutionsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listEnrolledSolutions = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listEnrolledSolutions(request), expectedError); - const actualRequest = (client.innerApiCalls.listEnrolledSolutions as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listEnrolledSolutions as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getProject with error', async () => { + const client = new projectserviceModule.v2alpha.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.GetProjectRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.GetProjectRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getProject = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getProject(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getProject as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getProject as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listEnrolledSolutions with closed client', async () => { - const client = new projectserviceModule.v2alpha.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ListEnrolledSolutionsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ListEnrolledSolutionsRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.listEnrolledSolutions(request), expectedError); - }); + it('invokes getProject with closed client', async () => { + const client = new projectserviceModule.v2alpha.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.GetProjectRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.GetProjectRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getProject(request), expectedError); + }); + }); + + describe('acceptTerms', () => { + it('invokes acceptTerms without error', async () => { + const client = new projectserviceModule.v2alpha.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.AcceptTermsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.AcceptTermsRequest', + ['project'], + ); + request.project = defaultValue1; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.Project(), + ); + client.innerApiCalls.acceptTerms = stubSimpleCall(expectedResponse); + const [response] = await client.acceptTerms(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.acceptTerms as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.acceptTerms as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('getLoggingConfig', () => { - it('invokes getLoggingConfig without error', async () => { - const client = new projectserviceModule.v2alpha.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.GetLoggingConfigRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.GetLoggingConfigRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.LoggingConfig() - ); - client.innerApiCalls.getLoggingConfig = stubSimpleCall(expectedResponse); - const [response] = await client.getLoggingConfig(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getLoggingConfig as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getLoggingConfig as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes acceptTerms without error using callback', async () => { + const client = new projectserviceModule.v2alpha.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.AcceptTermsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.AcceptTermsRequest', + ['project'], + ); + request.project = defaultValue1; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.Project(), + ); + client.innerApiCalls.acceptTerms = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.acceptTerms( + request, + ( + err?: Error | null, + result?: protos.google.cloud.retail.v2alpha.IProject | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.acceptTerms as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.acceptTerms as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getLoggingConfig without error using callback', async () => { - const client = new projectserviceModule.v2alpha.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.GetLoggingConfigRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.GetLoggingConfigRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.LoggingConfig() - ); - client.innerApiCalls.getLoggingConfig = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getLoggingConfig( - request, - (err?: Error|null, result?: protos.google.cloud.retail.v2alpha.ILoggingConfig|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getLoggingConfig as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getLoggingConfig as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes acceptTerms with error', async () => { + const client = new projectserviceModule.v2alpha.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.AcceptTermsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.AcceptTermsRequest', + ['project'], + ); + request.project = defaultValue1; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.acceptTerms = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.acceptTerms(request), expectedError); + const actualRequest = ( + client.innerApiCalls.acceptTerms as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.acceptTerms as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getLoggingConfig with error', async () => { - const client = new projectserviceModule.v2alpha.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.GetLoggingConfigRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.GetLoggingConfigRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getLoggingConfig = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getLoggingConfig(request), expectedError); - const actualRequest = (client.innerApiCalls.getLoggingConfig as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getLoggingConfig as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes acceptTerms with closed client', async () => { + const client = new projectserviceModule.v2alpha.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.AcceptTermsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.AcceptTermsRequest', + ['project'], + ); + request.project = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.acceptTerms(request), expectedError); + }); + }); + + describe('listEnrolledSolutions', () => { + it('invokes listEnrolledSolutions without error', async () => { + const client = new projectserviceModule.v2alpha.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ListEnrolledSolutionsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ListEnrolledSolutionsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ListEnrolledSolutionsResponse(), + ); + client.innerApiCalls.listEnrolledSolutions = + stubSimpleCall(expectedResponse); + const [response] = await client.listEnrolledSolutions(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listEnrolledSolutions as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listEnrolledSolutions as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getLoggingConfig with closed client', async () => { - const client = new projectserviceModule.v2alpha.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.GetLoggingConfigRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.GetLoggingConfigRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getLoggingConfig(request), expectedError); - }); + it('invokes listEnrolledSolutions without error using callback', async () => { + const client = new projectserviceModule.v2alpha.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ListEnrolledSolutionsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ListEnrolledSolutionsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ListEnrolledSolutionsResponse(), + ); + client.innerApiCalls.listEnrolledSolutions = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listEnrolledSolutions( + request, + ( + err?: Error | null, + result?: protos.google.cloud.retail.v2alpha.IListEnrolledSolutionsResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listEnrolledSolutions as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listEnrolledSolutions as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('updateLoggingConfig', () => { - it('invokes updateLoggingConfig without error', async () => { - const client = new projectserviceModule.v2alpha.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.UpdateLoggingConfigRequest() - ); - request.loggingConfig ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.UpdateLoggingConfigRequest', ['loggingConfig', 'name']); - request.loggingConfig.name = defaultValue1; - const expectedHeaderRequestParams = `logging_config.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.LoggingConfig() - ); - client.innerApiCalls.updateLoggingConfig = stubSimpleCall(expectedResponse); - const [response] = await client.updateLoggingConfig(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateLoggingConfig as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateLoggingConfig as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listEnrolledSolutions with error', async () => { + const client = new projectserviceModule.v2alpha.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ListEnrolledSolutionsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ListEnrolledSolutionsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listEnrolledSolutions = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.listEnrolledSolutions(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.listEnrolledSolutions as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listEnrolledSolutions as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateLoggingConfig without error using callback', async () => { - const client = new projectserviceModule.v2alpha.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.UpdateLoggingConfigRequest() - ); - request.loggingConfig ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.UpdateLoggingConfigRequest', ['loggingConfig', 'name']); - request.loggingConfig.name = defaultValue1; - const expectedHeaderRequestParams = `logging_config.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.LoggingConfig() - ); - client.innerApiCalls.updateLoggingConfig = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateLoggingConfig( - request, - (err?: Error|null, result?: protos.google.cloud.retail.v2alpha.ILoggingConfig|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateLoggingConfig as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateLoggingConfig as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listEnrolledSolutions with closed client', async () => { + const client = new projectserviceModule.v2alpha.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ListEnrolledSolutionsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ListEnrolledSolutionsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.listEnrolledSolutions(request), + expectedError, + ); + }); + }); + + describe('getLoggingConfig', () => { + it('invokes getLoggingConfig without error', async () => { + const client = new projectserviceModule.v2alpha.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.GetLoggingConfigRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.GetLoggingConfigRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.LoggingConfig(), + ); + client.innerApiCalls.getLoggingConfig = stubSimpleCall(expectedResponse); + const [response] = await client.getLoggingConfig(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getLoggingConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getLoggingConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateLoggingConfig with error', async () => { - const client = new projectserviceModule.v2alpha.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.UpdateLoggingConfigRequest() - ); - request.loggingConfig ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.UpdateLoggingConfigRequest', ['loggingConfig', 'name']); - request.loggingConfig.name = defaultValue1; - const expectedHeaderRequestParams = `logging_config.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateLoggingConfig = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateLoggingConfig(request), expectedError); - const actualRequest = (client.innerApiCalls.updateLoggingConfig as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateLoggingConfig as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getLoggingConfig without error using callback', async () => { + const client = new projectserviceModule.v2alpha.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.GetLoggingConfigRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.GetLoggingConfigRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.LoggingConfig(), + ); + client.innerApiCalls.getLoggingConfig = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getLoggingConfig( + request, + ( + err?: Error | null, + result?: protos.google.cloud.retail.v2alpha.ILoggingConfig | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getLoggingConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getLoggingConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateLoggingConfig with closed client', async () => { - const client = new projectserviceModule.v2alpha.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.UpdateLoggingConfigRequest() - ); - request.loggingConfig ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.UpdateLoggingConfigRequest', ['loggingConfig', 'name']); - request.loggingConfig.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateLoggingConfig(request), expectedError); - }); + it('invokes getLoggingConfig with error', async () => { + const client = new projectserviceModule.v2alpha.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.GetLoggingConfigRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.GetLoggingConfigRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getLoggingConfig = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getLoggingConfig(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getLoggingConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getLoggingConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('getAlertConfig', () => { - it('invokes getAlertConfig without error', async () => { - const client = new projectserviceModule.v2alpha.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.GetAlertConfigRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.GetAlertConfigRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.AlertConfig() - ); - client.innerApiCalls.getAlertConfig = stubSimpleCall(expectedResponse); - const [response] = await client.getAlertConfig(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getAlertConfig as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getAlertConfig as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getLoggingConfig with closed client', async () => { + const client = new projectserviceModule.v2alpha.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.GetLoggingConfigRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.GetLoggingConfigRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getLoggingConfig(request), expectedError); + }); + }); + + describe('updateLoggingConfig', () => { + it('invokes updateLoggingConfig without error', async () => { + const client = new projectserviceModule.v2alpha.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.UpdateLoggingConfigRequest(), + ); + request.loggingConfig ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.UpdateLoggingConfigRequest', + ['loggingConfig', 'name'], + ); + request.loggingConfig.name = defaultValue1; + const expectedHeaderRequestParams = `logging_config.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.LoggingConfig(), + ); + client.innerApiCalls.updateLoggingConfig = + stubSimpleCall(expectedResponse); + const [response] = await client.updateLoggingConfig(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateLoggingConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateLoggingConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getAlertConfig without error using callback', async () => { - const client = new projectserviceModule.v2alpha.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.GetAlertConfigRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.GetAlertConfigRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.AlertConfig() - ); - client.innerApiCalls.getAlertConfig = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getAlertConfig( - request, - (err?: Error|null, result?: protos.google.cloud.retail.v2alpha.IAlertConfig|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getAlertConfig as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getAlertConfig as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateLoggingConfig without error using callback', async () => { + const client = new projectserviceModule.v2alpha.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.UpdateLoggingConfigRequest(), + ); + request.loggingConfig ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.UpdateLoggingConfigRequest', + ['loggingConfig', 'name'], + ); + request.loggingConfig.name = defaultValue1; + const expectedHeaderRequestParams = `logging_config.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.LoggingConfig(), + ); + client.innerApiCalls.updateLoggingConfig = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateLoggingConfig( + request, + ( + err?: Error | null, + result?: protos.google.cloud.retail.v2alpha.ILoggingConfig | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateLoggingConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateLoggingConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getAlertConfig with error', async () => { - const client = new projectserviceModule.v2alpha.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.GetAlertConfigRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.GetAlertConfigRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getAlertConfig = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getAlertConfig(request), expectedError); - const actualRequest = (client.innerApiCalls.getAlertConfig as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getAlertConfig as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateLoggingConfig with error', async () => { + const client = new projectserviceModule.v2alpha.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.UpdateLoggingConfigRequest(), + ); + request.loggingConfig ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.UpdateLoggingConfigRequest', + ['loggingConfig', 'name'], + ); + request.loggingConfig.name = defaultValue1; + const expectedHeaderRequestParams = `logging_config.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateLoggingConfig = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.updateLoggingConfig(request), expectedError); + const actualRequest = ( + client.innerApiCalls.updateLoggingConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateLoggingConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getAlertConfig with closed client', async () => { - const client = new projectserviceModule.v2alpha.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.GetAlertConfigRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.GetAlertConfigRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getAlertConfig(request), expectedError); - }); + it('invokes updateLoggingConfig with closed client', async () => { + const client = new projectserviceModule.v2alpha.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.UpdateLoggingConfigRequest(), + ); + request.loggingConfig ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.UpdateLoggingConfigRequest', + ['loggingConfig', 'name'], + ); + request.loggingConfig.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.updateLoggingConfig(request), expectedError); + }); + }); + + describe('getAlertConfig', () => { + it('invokes getAlertConfig without error', async () => { + const client = new projectserviceModule.v2alpha.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.GetAlertConfigRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.GetAlertConfigRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.AlertConfig(), + ); + client.innerApiCalls.getAlertConfig = stubSimpleCall(expectedResponse); + const [response] = await client.getAlertConfig(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getAlertConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getAlertConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('updateAlertConfig', () => { - it('invokes updateAlertConfig without error', async () => { - const client = new projectserviceModule.v2alpha.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.UpdateAlertConfigRequest() - ); - request.alertConfig ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.UpdateAlertConfigRequest', ['alertConfig', 'name']); - request.alertConfig.name = defaultValue1; - const expectedHeaderRequestParams = `alert_config.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.AlertConfig() - ); - client.innerApiCalls.updateAlertConfig = stubSimpleCall(expectedResponse); - const [response] = await client.updateAlertConfig(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateAlertConfig as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateAlertConfig as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getAlertConfig without error using callback', async () => { + const client = new projectserviceModule.v2alpha.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.GetAlertConfigRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.GetAlertConfigRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.AlertConfig(), + ); + client.innerApiCalls.getAlertConfig = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getAlertConfig( + request, + ( + err?: Error | null, + result?: protos.google.cloud.retail.v2alpha.IAlertConfig | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getAlertConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getAlertConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateAlertConfig without error using callback', async () => { - const client = new projectserviceModule.v2alpha.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.UpdateAlertConfigRequest() - ); - request.alertConfig ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.UpdateAlertConfigRequest', ['alertConfig', 'name']); - request.alertConfig.name = defaultValue1; - const expectedHeaderRequestParams = `alert_config.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.AlertConfig() - ); - client.innerApiCalls.updateAlertConfig = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateAlertConfig( - request, - (err?: Error|null, result?: protos.google.cloud.retail.v2alpha.IAlertConfig|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateAlertConfig as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateAlertConfig as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getAlertConfig with error', async () => { + const client = new projectserviceModule.v2alpha.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.GetAlertConfigRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.GetAlertConfigRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getAlertConfig = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getAlertConfig(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getAlertConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getAlertConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateAlertConfig with error', async () => { - const client = new projectserviceModule.v2alpha.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.UpdateAlertConfigRequest() - ); - request.alertConfig ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.UpdateAlertConfigRequest', ['alertConfig', 'name']); - request.alertConfig.name = defaultValue1; - const expectedHeaderRequestParams = `alert_config.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateAlertConfig = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateAlertConfig(request), expectedError); - const actualRequest = (client.innerApiCalls.updateAlertConfig as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateAlertConfig as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getAlertConfig with closed client', async () => { + const client = new projectserviceModule.v2alpha.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.GetAlertConfigRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.GetAlertConfigRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getAlertConfig(request), expectedError); + }); + }); + + describe('updateAlertConfig', () => { + it('invokes updateAlertConfig without error', async () => { + const client = new projectserviceModule.v2alpha.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.UpdateAlertConfigRequest(), + ); + request.alertConfig ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.UpdateAlertConfigRequest', + ['alertConfig', 'name'], + ); + request.alertConfig.name = defaultValue1; + const expectedHeaderRequestParams = `alert_config.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.AlertConfig(), + ); + client.innerApiCalls.updateAlertConfig = stubSimpleCall(expectedResponse); + const [response] = await client.updateAlertConfig(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateAlertConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateAlertConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateAlertConfig with closed client', async () => { - const client = new projectserviceModule.v2alpha.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.UpdateAlertConfigRequest() - ); - request.alertConfig ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.UpdateAlertConfigRequest', ['alertConfig', 'name']); - request.alertConfig.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateAlertConfig(request), expectedError); - }); + it('invokes updateAlertConfig without error using callback', async () => { + const client = new projectserviceModule.v2alpha.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.UpdateAlertConfigRequest(), + ); + request.alertConfig ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.UpdateAlertConfigRequest', + ['alertConfig', 'name'], + ); + request.alertConfig.name = defaultValue1; + const expectedHeaderRequestParams = `alert_config.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.AlertConfig(), + ); + client.innerApiCalls.updateAlertConfig = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateAlertConfig( + request, + ( + err?: Error | null, + result?: protos.google.cloud.retail.v2alpha.IAlertConfig | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateAlertConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateAlertConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('enrollSolution', () => { - it('invokes enrollSolution without error', async () => { - const client = new projectserviceModule.v2alpha.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.EnrollSolutionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.EnrollSolutionRequest', ['project']); - request.project = defaultValue1; - const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.enrollSolution = stubLongRunningCall(expectedResponse); - const [operation] = await client.enrollSolution(request); - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.enrollSolution as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.enrollSolution as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateAlertConfig with error', async () => { + const client = new projectserviceModule.v2alpha.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.UpdateAlertConfigRequest(), + ); + request.alertConfig ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.UpdateAlertConfigRequest', + ['alertConfig', 'name'], + ); + request.alertConfig.name = defaultValue1; + const expectedHeaderRequestParams = `alert_config.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateAlertConfig = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.updateAlertConfig(request), expectedError); + const actualRequest = ( + client.innerApiCalls.updateAlertConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateAlertConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes enrollSolution without error using callback', async () => { - const client = new projectserviceModule.v2alpha.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.EnrollSolutionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.EnrollSolutionRequest', ['project']); - request.project = defaultValue1; - const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.enrollSolution = stubLongRunningCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.enrollSolution( - request, - (err?: Error|null, - result?: LROperation|null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const operation = await promise as LROperation; - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.enrollSolution as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.enrollSolution as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateAlertConfig with closed client', async () => { + const client = new projectserviceModule.v2alpha.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.UpdateAlertConfigRequest(), + ); + request.alertConfig ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.UpdateAlertConfigRequest', + ['alertConfig', 'name'], + ); + request.alertConfig.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.updateAlertConfig(request), expectedError); + }); + }); + + describe('enrollSolution', () => { + it('invokes enrollSolution without error', async () => { + const client = new projectserviceModule.v2alpha.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.EnrollSolutionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.EnrollSolutionRequest', + ['project'], + ); + request.project = defaultValue1; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.enrollSolution = + stubLongRunningCall(expectedResponse); + const [operation] = await client.enrollSolution(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.enrollSolution as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.enrollSolution as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes enrollSolution with call error', async () => { - const client = new projectserviceModule.v2alpha.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.EnrollSolutionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.EnrollSolutionRequest', ['project']); - request.project = defaultValue1; - const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.enrollSolution = stubLongRunningCall(undefined, expectedError); - await assert.rejects(client.enrollSolution(request), expectedError); - const actualRequest = (client.innerApiCalls.enrollSolution as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.enrollSolution as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes enrollSolution without error using callback', async () => { + const client = new projectserviceModule.v2alpha.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.EnrollSolutionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.EnrollSolutionRequest', + ['project'], + ); + request.project = defaultValue1; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.enrollSolution = + stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.enrollSolution( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.cloud.retail.v2alpha.IEnrollSolutionResponse, + protos.google.cloud.retail.v2alpha.IEnrollSolutionMetadata + > | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const operation = (await promise) as LROperation< + protos.google.cloud.retail.v2alpha.IEnrollSolutionResponse, + protos.google.cloud.retail.v2alpha.IEnrollSolutionMetadata + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.enrollSolution as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.enrollSolution as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes enrollSolution with LRO error', async () => { - const client = new projectserviceModule.v2alpha.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.EnrollSolutionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.EnrollSolutionRequest', ['project']); - request.project = defaultValue1; - const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.enrollSolution = stubLongRunningCall(undefined, undefined, expectedError); - const [operation] = await client.enrollSolution(request); - await assert.rejects(operation.promise(), expectedError); - const actualRequest = (client.innerApiCalls.enrollSolution as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.enrollSolution as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes enrollSolution with call error', async () => { + const client = new projectserviceModule.v2alpha.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.EnrollSolutionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.EnrollSolutionRequest', + ['project'], + ); + request.project = defaultValue1; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.enrollSolution = stubLongRunningCall( + undefined, + expectedError, + ); + await assert.rejects(client.enrollSolution(request), expectedError); + const actualRequest = ( + client.innerApiCalls.enrollSolution as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.enrollSolution as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkEnrollSolutionProgress without error', async () => { - const client = new projectserviceModule.v2alpha.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedResponse = generateSampleMessage( - new operationsProtos.google.longrunning.Operation() - ); - expectedResponse.name = 'test'; - expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; - expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')} - - client.operationsClient.getOperation = stubSimpleCall(expectedResponse); - const decodedOperation = await client.checkEnrollSolutionProgress(expectedResponse.name); - assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); - assert(decodedOperation.metadata); - assert((client.operationsClient.getOperation as SinonStub).getCall(0)); - }); + it('invokes enrollSolution with LRO error', async () => { + const client = new projectserviceModule.v2alpha.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.EnrollSolutionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.EnrollSolutionRequest', + ['project'], + ); + request.project = defaultValue1; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.enrollSolution = stubLongRunningCall( + undefined, + undefined, + expectedError, + ); + const [operation] = await client.enrollSolution(request); + await assert.rejects(operation.promise(), expectedError); + const actualRequest = ( + client.innerApiCalls.enrollSolution as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.enrollSolution as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkEnrollSolutionProgress with error', async () => { - const client = new projectserviceModule.v2alpha.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedError = new Error('expected'); - - client.operationsClient.getOperation = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.checkEnrollSolutionProgress(''), expectedError); - assert((client.operationsClient.getOperation as SinonStub) - .getCall(0)); - }); + it('invokes checkEnrollSolutionProgress without error', async () => { + const client = new projectserviceModule.v2alpha.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation(), + ); + expectedResponse.name = 'test'; + expectedResponse.response = { type_url: 'url', value: Buffer.from('') }; + expectedResponse.metadata = { type_url: 'url', value: Buffer.from('') }; + + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const decodedOperation = await client.checkEnrollSolutionProgress( + expectedResponse.name, + ); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); }); - describe('Path templates', () => { - - describe('alertConfig', () => { - const fakePath = "/rendered/path/alertConfig"; - const expectedParameters = { - project: "projectValue", - }; - const client = new projectserviceModule.v2alpha.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.alertConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.alertConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('alertConfigPath', () => { - const result = client.alertConfigPath("projectValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.alertConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromAlertConfigName', () => { - const result = client.matchProjectFromAlertConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.alertConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('invokes checkEnrollSolutionProgress with error', async () => { + const client = new projectserviceModule.v2alpha.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const expectedError = new Error('expected'); + + client.operationsClient.getOperation = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.checkEnrollSolutionProgress(''), + expectedError, + ); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + }); + + describe('Path templates', () => { + describe('alertConfig', () => { + const fakePath = '/rendered/path/alertConfig'; + const expectedParameters = { + project: 'projectValue', + }; + const client = new projectserviceModule.v2alpha.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.alertConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.alertConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('alertConfigPath', () => { + const result = client.alertConfigPath('projectValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.alertConfigPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromAlertConfigName', () => { + const result = client.matchProjectFromAlertConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.alertConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('attributesConfig', () => { - const fakePath = "/rendered/path/attributesConfig"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - }; - const client = new projectserviceModule.v2alpha.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.attributesConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.attributesConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('attributesConfigPath', () => { - const result = client.attributesConfigPath("projectValue", "locationValue", "catalogValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.attributesConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromAttributesConfigName', () => { - const result = client.matchProjectFromAttributesConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromAttributesConfigName', () => { - const result = client.matchLocationFromAttributesConfigName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromAttributesConfigName', () => { - const result = client.matchCatalogFromAttributesConfigName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('attributesConfig', () => { + const fakePath = '/rendered/path/attributesConfig'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + }; + const client = new projectserviceModule.v2alpha.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.attributesConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.attributesConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('attributesConfigPath', () => { + const result = client.attributesConfigPath( + 'projectValue', + 'locationValue', + 'catalogValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.attributesConfigPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromAttributesConfigName', () => { + const result = client.matchProjectFromAttributesConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromAttributesConfigName', () => { + const result = client.matchLocationFromAttributesConfigName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromAttributesConfigName', () => { + const result = client.matchCatalogFromAttributesConfigName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('branch', () => { - const fakePath = "/rendered/path/branch"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - branch: "branchValue", - }; - const client = new projectserviceModule.v2alpha.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.branchPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.branchPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('branchPath', () => { - const result = client.branchPath("projectValue", "locationValue", "catalogValue", "branchValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.branchPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromBranchName', () => { - const result = client.matchProjectFromBranchName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.branchPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromBranchName', () => { - const result = client.matchLocationFromBranchName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.branchPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromBranchName', () => { - const result = client.matchCatalogFromBranchName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.branchPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBranchFromBranchName', () => { - const result = client.matchBranchFromBranchName(fakePath); - assert.strictEqual(result, "branchValue"); - assert((client.pathTemplates.branchPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('branch', () => { + const fakePath = '/rendered/path/branch'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + branch: 'branchValue', + }; + const client = new projectserviceModule.v2alpha.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.branchPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.branchPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('branchPath', () => { + const result = client.branchPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'branchValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.branchPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromBranchName', () => { + const result = client.matchProjectFromBranchName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.branchPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromBranchName', () => { + const result = client.matchLocationFromBranchName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.branchPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromBranchName', () => { + const result = client.matchCatalogFromBranchName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.branchPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBranchFromBranchName', () => { + const result = client.matchBranchFromBranchName(fakePath); + assert.strictEqual(result, 'branchValue'); + assert( + (client.pathTemplates.branchPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('catalog', () => { - const fakePath = "/rendered/path/catalog"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - }; - const client = new projectserviceModule.v2alpha.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.catalogPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.catalogPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('catalogPath', () => { - const result = client.catalogPath("projectValue", "locationValue", "catalogValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.catalogPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromCatalogName', () => { - const result = client.matchProjectFromCatalogName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.catalogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromCatalogName', () => { - const result = client.matchLocationFromCatalogName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.catalogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromCatalogName', () => { - const result = client.matchCatalogFromCatalogName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.catalogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('catalog', () => { + const fakePath = '/rendered/path/catalog'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + }; + const client = new projectserviceModule.v2alpha.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.catalogPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.catalogPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('catalogPath', () => { + const result = client.catalogPath( + 'projectValue', + 'locationValue', + 'catalogValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.catalogPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromCatalogName', () => { + const result = client.matchProjectFromCatalogName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.catalogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromCatalogName', () => { + const result = client.matchLocationFromCatalogName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.catalogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromCatalogName', () => { + const result = client.matchCatalogFromCatalogName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.catalogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('completionConfig', () => { - const fakePath = "/rendered/path/completionConfig"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - }; - const client = new projectserviceModule.v2alpha.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.completionConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.completionConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('completionConfigPath', () => { - const result = client.completionConfigPath("projectValue", "locationValue", "catalogValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.completionConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromCompletionConfigName', () => { - const result = client.matchProjectFromCompletionConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.completionConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromCompletionConfigName', () => { - const result = client.matchLocationFromCompletionConfigName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.completionConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromCompletionConfigName', () => { - const result = client.matchCatalogFromCompletionConfigName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.completionConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('completionConfig', () => { + const fakePath = '/rendered/path/completionConfig'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + }; + const client = new projectserviceModule.v2alpha.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.completionConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.completionConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('completionConfigPath', () => { + const result = client.completionConfigPath( + 'projectValue', + 'locationValue', + 'catalogValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.completionConfigPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromCompletionConfigName', () => { + const result = client.matchProjectFromCompletionConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.completionConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromCompletionConfigName', () => { + const result = client.matchLocationFromCompletionConfigName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.completionConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromCompletionConfigName', () => { + const result = client.matchCatalogFromCompletionConfigName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.completionConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('control', () => { - const fakePath = "/rendered/path/control"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - control: "controlValue", - }; - const client = new projectserviceModule.v2alpha.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.controlPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.controlPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('controlPath', () => { - const result = client.controlPath("projectValue", "locationValue", "catalogValue", "controlValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.controlPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromControlName', () => { - const result = client.matchProjectFromControlName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.controlPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromControlName', () => { - const result = client.matchLocationFromControlName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.controlPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromControlName', () => { - const result = client.matchCatalogFromControlName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.controlPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchControlFromControlName', () => { - const result = client.matchControlFromControlName(fakePath); - assert.strictEqual(result, "controlValue"); - assert((client.pathTemplates.controlPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('control', () => { + const fakePath = '/rendered/path/control'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + control: 'controlValue', + }; + const client = new projectserviceModule.v2alpha.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.controlPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.controlPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('controlPath', () => { + const result = client.controlPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'controlValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.controlPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromControlName', () => { + const result = client.matchProjectFromControlName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.controlPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromControlName', () => { + const result = client.matchLocationFromControlName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.controlPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromControlName', () => { + const result = client.matchCatalogFromControlName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.controlPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchControlFromControlName', () => { + const result = client.matchControlFromControlName(fakePath); + assert.strictEqual(result, 'controlValue'); + assert( + (client.pathTemplates.controlPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('loggingConfig', () => { - const fakePath = "/rendered/path/loggingConfig"; - const expectedParameters = { - project: "projectValue", - }; - const client = new projectserviceModule.v2alpha.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.loggingConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.loggingConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('loggingConfigPath', () => { - const result = client.loggingConfigPath("projectValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.loggingConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromLoggingConfigName', () => { - const result = client.matchProjectFromLoggingConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.loggingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('loggingConfig', () => { + const fakePath = '/rendered/path/loggingConfig'; + const expectedParameters = { + project: 'projectValue', + }; + const client = new projectserviceModule.v2alpha.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.loggingConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.loggingConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('loggingConfigPath', () => { + const result = client.loggingConfigPath('projectValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.loggingConfigPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromLoggingConfigName', () => { + const result = client.matchProjectFromLoggingConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.loggingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('merchantCenterAccountLink', () => { - const fakePath = "/rendered/path/merchantCenterAccountLink"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - merchant_center_account_link: "merchantCenterAccountLinkValue", - }; - const client = new projectserviceModule.v2alpha.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.merchantCenterAccountLinkPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.merchantCenterAccountLinkPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('merchantCenterAccountLinkPath', () => { - const result = client.merchantCenterAccountLinkPath("projectValue", "locationValue", "catalogValue", "merchantCenterAccountLinkValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromMerchantCenterAccountLinkName', () => { - const result = client.matchProjectFromMerchantCenterAccountLinkName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromMerchantCenterAccountLinkName', () => { - const result = client.matchLocationFromMerchantCenterAccountLinkName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromMerchantCenterAccountLinkName', () => { - const result = client.matchCatalogFromMerchantCenterAccountLinkName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName', () => { - const result = client.matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName(fakePath); - assert.strictEqual(result, "merchantCenterAccountLinkValue"); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('merchantCenterAccountLink', () => { + const fakePath = '/rendered/path/merchantCenterAccountLink'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + merchant_center_account_link: 'merchantCenterAccountLinkValue', + }; + const client = new projectserviceModule.v2alpha.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.merchantCenterAccountLinkPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.merchantCenterAccountLinkPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('merchantCenterAccountLinkPath', () => { + const result = client.merchantCenterAccountLinkPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'merchantCenterAccountLinkValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromMerchantCenterAccountLinkName', () => { + const result = + client.matchProjectFromMerchantCenterAccountLinkName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromMerchantCenterAccountLinkName', () => { + const result = + client.matchLocationFromMerchantCenterAccountLinkName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromMerchantCenterAccountLinkName', () => { + const result = + client.matchCatalogFromMerchantCenterAccountLinkName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName', () => { + const result = + client.matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName( + fakePath, + ); + assert.strictEqual(result, 'merchantCenterAccountLinkValue'); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('model', () => { - const fakePath = "/rendered/path/model"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - model: "modelValue", - }; - const client = new projectserviceModule.v2alpha.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.modelPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.modelPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('modelPath', () => { - const result = client.modelPath("projectValue", "locationValue", "catalogValue", "modelValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.modelPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromModelName', () => { - const result = client.matchProjectFromModelName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromModelName', () => { - const result = client.matchLocationFromModelName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromModelName', () => { - const result = client.matchCatalogFromModelName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchModelFromModelName', () => { - const result = client.matchModelFromModelName(fakePath); - assert.strictEqual(result, "modelValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('model', () => { + const fakePath = '/rendered/path/model'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + model: 'modelValue', + }; + const client = new projectserviceModule.v2alpha.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.modelPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.modelPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('modelPath', () => { + const result = client.modelPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'modelValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.modelPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromModelName', () => { + const result = client.matchProjectFromModelName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromModelName', () => { + const result = client.matchLocationFromModelName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromModelName', () => { + const result = client.matchCatalogFromModelName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchModelFromModelName', () => { + const result = client.matchModelFromModelName(fakePath); + assert.strictEqual(result, 'modelValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('product', () => { - const fakePath = "/rendered/path/product"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - branch: "branchValue", - product: "productValue", - }; - const client = new projectserviceModule.v2alpha.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.productPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.productPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('productPath', () => { - const result = client.productPath("projectValue", "locationValue", "catalogValue", "branchValue", "productValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.productPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProductName', () => { - const result = client.matchProjectFromProductName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromProductName', () => { - const result = client.matchLocationFromProductName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromProductName', () => { - const result = client.matchCatalogFromProductName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBranchFromProductName', () => { - const result = client.matchBranchFromProductName(fakePath); - assert.strictEqual(result, "branchValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchProductFromProductName', () => { - const result = client.matchProductFromProductName(fakePath); - assert.strictEqual(result, "productValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('product', () => { + const fakePath = '/rendered/path/product'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + branch: 'branchValue', + product: 'productValue', + }; + const client = new projectserviceModule.v2alpha.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.productPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.productPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('productPath', () => { + const result = client.productPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'branchValue', + 'productValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.productPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProductName', () => { + const result = client.matchProjectFromProductName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromProductName', () => { + const result = client.matchLocationFromProductName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromProductName', () => { + const result = client.matchCatalogFromProductName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBranchFromProductName', () => { + const result = client.matchBranchFromProductName(fakePath); + assert.strictEqual(result, 'branchValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchProductFromProductName', () => { + const result = client.matchProductFromProductName(fakePath); + assert.strictEqual(result, 'productValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('project', () => { - const fakePath = "/rendered/path/project"; - const expectedParameters = { - project: "projectValue", - }; - const client = new projectserviceModule.v2alpha.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.projectPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectPath', () => { - const result = client.projectPath("projectValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectName', () => { - const result = client.matchProjectFromProjectName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('project', () => { + const fakePath = '/rendered/path/project'; + const expectedParameters = { + project: 'projectValue', + }; + const client = new projectserviceModule.v2alpha.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.projectPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectPath', () => { + const result = client.projectPath('projectValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.projectPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectName', () => { + const result = client.matchProjectFromProjectName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.projectPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('retailProject', () => { - const fakePath = "/rendered/path/retailProject"; - const expectedParameters = { - project: "projectValue", - }; - const client = new projectserviceModule.v2alpha.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.retailProjectPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.retailProjectPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('retailProjectPath', () => { - const result = client.retailProjectPath("projectValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.retailProjectPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromRetailProjectName', () => { - const result = client.matchProjectFromRetailProjectName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.retailProjectPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('retailProject', () => { + const fakePath = '/rendered/path/retailProject'; + const expectedParameters = { + project: 'projectValue', + }; + const client = new projectserviceModule.v2alpha.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.retailProjectPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.retailProjectPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('retailProjectPath', () => { + const result = client.retailProjectPath('projectValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.retailProjectPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromRetailProjectName', () => { + const result = client.matchProjectFromRetailProjectName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.retailProjectPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('servingConfig', () => { - const fakePath = "/rendered/path/servingConfig"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - serving_config: "servingConfigValue", - }; - const client = new projectserviceModule.v2alpha.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.servingConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.servingConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('servingConfigPath', () => { - const result = client.servingConfigPath("projectValue", "locationValue", "catalogValue", "servingConfigValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.servingConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromServingConfigName', () => { - const result = client.matchProjectFromServingConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.servingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromServingConfigName', () => { - const result = client.matchLocationFromServingConfigName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.servingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromServingConfigName', () => { - const result = client.matchCatalogFromServingConfigName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.servingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServingConfigFromServingConfigName', () => { - const result = client.matchServingConfigFromServingConfigName(fakePath); - assert.strictEqual(result, "servingConfigValue"); - assert((client.pathTemplates.servingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('servingConfig', () => { + const fakePath = '/rendered/path/servingConfig'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + serving_config: 'servingConfigValue', + }; + const client = new projectserviceModule.v2alpha.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.servingConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.servingConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('servingConfigPath', () => { + const result = client.servingConfigPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'servingConfigValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.servingConfigPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromServingConfigName', () => { + const result = client.matchProjectFromServingConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.servingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromServingConfigName', () => { + const result = client.matchLocationFromServingConfigName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.servingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromServingConfigName', () => { + const result = client.matchCatalogFromServingConfigName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.servingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServingConfigFromServingConfigName', () => { + const result = client.matchServingConfigFromServingConfigName(fakePath); + assert.strictEqual(result, 'servingConfigValue'); + assert( + (client.pathTemplates.servingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/test/gapic_search_service_v2alpha.ts.baseline b/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/test/gapic_search_service_v2alpha.ts.baseline index b3111ae687a7..a4dd92687df9 100644 --- a/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/test/gapic_search_service_v2alpha.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/test/gapic_search_service_v2alpha.ts.baseline @@ -20,16 +20,16 @@ import * as protos from '../../protos/protos.js'; import assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as searchserviceModule from '../src/index.js'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; -import {protobuf} from 'google-gax'; +import { protobuf } from 'google-gax'; import fs from 'fs'; import path from 'path'; -import {fileURLToPath} from 'url'; +import { fileURLToPath } from 'url'; // @ts-ignore const dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -37,1096 +37,1533 @@ const dirname = path.dirname(fileURLToPath(import.meta.url)); // to fill in default values for request objects const root = protobuf.Root.fromJSON( JSON.parse( - fs.readFileSync(path.join(dirname, '..', '..', 'protos/protos.json'), 'utf8') - )) + fs.readFileSync( + path.join(dirname, '..', '..', 'protos/protos.json'), + 'utf8', + ), + ), +); // eslint-disable-next-line @typescript-eslint/no-unused-vars function getTypeDefaultValue(typeName: string, fields: string[]) { - let type = root.lookupType(typeName) as protobuf.Type; - for (const field of fields.slice(0, -1)) { - type = type?.fields[field]?.resolvedType as protobuf.Type; - } - return type?.fields[fields[fields.length - 1]]?.defaultValue ?? null; + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type?.fields[field]?.resolvedType as protobuf.Type; + } + return type?.fields[fields[fields.length - 1]]?.defaultValue ?? null; } function generateSampleMessage(instance: T) { - const filledObject = (instance.constructor as typeof protobuf.Message) - .toObject(instance as protobuf.Message, {defaults: true}); - return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, { defaults: true }); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; } function stubSimpleCall(response?: ResponseType, error?: Error) { - return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); } -function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { - return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +function stubSimpleCallWithCallback( + response?: ResponseType, + error?: Error, +) { + return error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); } -function stubPageStreamingCall(responses?: ResponseType[], error?: Error) { - const pagingStub = sinon.stub(); - if (responses) { - for (let i = 0; i < responses.length; ++i) { - pagingStub.onCall(i).callsArgWith(2, null, responses[i]); - } +function stubPageStreamingCall( + responses?: ResponseType[], + error?: Error, +) { + const pagingStub = sinon.stub(); + if (responses) { + for (let i = 0; i < responses.length; ++i) { + pagingStub.onCall(i).callsArgWith(2, null, responses[i]); } - const transformStub = error ? sinon.stub().callsArgWith(2, error) : pagingStub; - const mockStream = new PassThrough({ - objectMode: true, - transform: transformStub, - }); - // trigger as many responses as needed - if (responses) { - for (let i = 0; i < responses.length; ++i) { - setImmediate(() => { mockStream.write({}); }); - } - setImmediate(() => { mockStream.end(); }); - } else { - setImmediate(() => { mockStream.write({}); }); - setImmediate(() => { mockStream.end(); }); + } + const transformStub = error + ? sinon.stub().callsArgWith(2, error) + : pagingStub; + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + // trigger as many responses as needed + if (responses) { + for (let i = 0; i < responses.length; ++i) { + setImmediate(() => { + mockStream.write({}); + }); } - return sinon.stub().returns(mockStream); + setImmediate(() => { + mockStream.end(); + }); + } else { + setImmediate(() => { + mockStream.write({}); + }); + setImmediate(() => { + mockStream.end(); + }); + } + return sinon.stub().returns(mockStream); } -function stubAsyncIterationCall(responses?: ResponseType[], error?: Error) { - let counter = 0; - const asyncIterable = { - [Symbol.asyncIterator]() { - return { - async next() { - if (error) { - return Promise.reject(error); - } - if (counter >= responses!.length) { - return Promise.resolve({done: true, value: undefined}); - } - return Promise.resolve({done: false, value: responses![counter++]}); - } - }; - } - }; - return sinon.stub().returns(asyncIterable); +function stubAsyncIterationCall( + responses?: ResponseType[], + error?: Error, +) { + let counter = 0; + const asyncIterable = { + [Symbol.asyncIterator]() { + return { + async next() { + if (error) { + return Promise.reject(error); + } + if (counter >= responses!.length) { + return Promise.resolve({ done: true, value: undefined }); + } + return Promise.resolve({ done: false, value: responses![counter++] }); + }, + }; + }, + }; + return sinon.stub().returns(asyncIterable); } describe('v2alpha.SearchServiceClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new searchserviceModule.v2alpha.SearchServiceClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'retail.googleapis.com'); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new searchserviceModule.v2alpha.SearchServiceClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'retail.googleapis.com'); + }); - it('has universeDomain', () => { - const client = new searchserviceModule.v2alpha.SearchServiceClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); + it('has universeDomain', () => { + const client = new searchserviceModule.v2alpha.SearchServiceClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - it('throws DeprecationWarning if static servicePath is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const servicePath = searchserviceModule.v2alpha.SearchServiceClient.servicePath; - assert.strictEqual(servicePath, 'retail.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = searchserviceModule.v2alpha.SearchServiceClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'retail.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new searchserviceModule.v2alpha.SearchServiceClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'retail.example.com'); - }); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = + searchserviceModule.v2alpha.SearchServiceClient.servicePath; + assert.strictEqual(servicePath, 'retail.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + searchserviceModule.v2alpha.SearchServiceClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'retail.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = new searchserviceModule.v2alpha.SearchServiceClient({ + universeDomain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'retail.example.com'); + }); - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new searchserviceModule.v2alpha.SearchServiceClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'retail.example.com'); - }); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = new searchserviceModule.v2alpha.SearchServiceClient({ + universe_domain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'retail.example.com'); + }); - if (typeof process === 'object' && 'env' in process) { - describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { - it('sets apiEndpoint from environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new searchserviceModule.v2alpha.SearchServiceClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'retail.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - - it('value configured in code has priority over environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new searchserviceModule.v2alpha.SearchServiceClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'retail.configured.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { new searchserviceModule.v2alpha.SearchServiceClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); + if (typeof process === 'object' && 'env' in process) { + describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { + it('sets apiEndpoint from environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new searchserviceModule.v2alpha.SearchServiceClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'retail.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - it('has port', () => { - const port = searchserviceModule.v2alpha.SearchServiceClient.port; - assert(port); - assert(typeof port === 'number'); + it('value configured in code has priority over environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new searchserviceModule.v2alpha.SearchServiceClient({ + universeDomain: 'configured.example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'retail.configured.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - - it('should create a client with no option', () => { - const client = new searchserviceModule.v2alpha.SearchServiceClient(); - assert(client); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new searchserviceModule.v2alpha.SearchServiceClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); + }); - it('should create a client with gRPC fallback', () => { - const client = new searchserviceModule.v2alpha.SearchServiceClient({ - fallback: true, - }); - assert(client); - }); + it('has port', () => { + const port = searchserviceModule.v2alpha.SearchServiceClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('has initialize method and supports deferred initialization', async () => { - const client = new searchserviceModule.v2alpha.SearchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.searchServiceStub, undefined); - await client.initialize(); - assert(client.searchServiceStub); - }); + it('should create a client with no option', () => { + const client = new searchserviceModule.v2alpha.SearchServiceClient(); + assert(client); + }); - it('has close method for the initialized client', done => { - const client = new searchserviceModule.v2alpha.SearchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.searchServiceStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('should create a client with gRPC fallback', () => { + const client = new searchserviceModule.v2alpha.SearchServiceClient({ + fallback: true, + }); + assert(client); + }); - it('has close method for the non-initialized client', done => { - const client = new searchserviceModule.v2alpha.SearchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.searchServiceStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('has initialize method and supports deferred initialization', async () => { + const client = new searchserviceModule.v2alpha.SearchServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.searchServiceStub, undefined); + await client.initialize(); + assert(client.searchServiceStub); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new searchserviceModule.v2alpha.SearchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + it('has close method for the initialized client', (done) => { + const client = new searchserviceModule.v2alpha.SearchServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.searchServiceStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new searchserviceModule.v2alpha.SearchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId((err?: Error|null, projectId?: string|null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } - }); - }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); + it('has close method for the non-initialized client', (done) => { + const client = new searchserviceModule.v2alpha.SearchServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.searchServiceStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); }); - describe('search', () => { - it('invokes search without error', async () => { - const client = new searchserviceModule.v2alpha.SearchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.SearchRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.SearchRequest', ['placement']); - request.placement = defaultValue1; - const expectedHeaderRequestParams = `placement=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.retail.v2alpha.SearchResponse.SearchResult()), - generateSampleMessage(new protos.google.cloud.retail.v2alpha.SearchResponse.SearchResult()), - generateSampleMessage(new protos.google.cloud.retail.v2alpha.SearchResponse.SearchResult()), - ]; - client.innerApiCalls.search = stubSimpleCall(expectedResponse); - const [response] = await client.search(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.search as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.search as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new searchserviceModule.v2alpha.SearchServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + }); - it('invokes search without error using callback', async () => { - const client = new searchserviceModule.v2alpha.SearchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.SearchRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.SearchRequest', ['placement']); - request.placement = defaultValue1; - const expectedHeaderRequestParams = `placement=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.retail.v2alpha.SearchResponse.SearchResult()), - generateSampleMessage(new protos.google.cloud.retail.v2alpha.SearchResponse.SearchResult()), - generateSampleMessage(new protos.google.cloud.retail.v2alpha.SearchResponse.SearchResult()), - ]; - client.innerApiCalls.search = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.search( - request, - (err?: Error|null, result?: protos.google.cloud.retail.v2alpha.SearchResponse.ISearchResult[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.search as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.search as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new searchserviceModule.v2alpha.SearchServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + }); + + describe('search', () => { + it('invokes search without error', async () => { + const client = new searchserviceModule.v2alpha.SearchServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.SearchRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.SearchRequest', + ['placement'], + ); + request.placement = defaultValue1; + const expectedHeaderRequestParams = `placement=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.cloud.retail.v2alpha.SearchResponse.SearchResult(), + ), + generateSampleMessage( + new protos.google.cloud.retail.v2alpha.SearchResponse.SearchResult(), + ), + generateSampleMessage( + new protos.google.cloud.retail.v2alpha.SearchResponse.SearchResult(), + ), + ]; + client.innerApiCalls.search = stubSimpleCall(expectedResponse); + const [response] = await client.search(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.search as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.search as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes search with error', async () => { - const client = new searchserviceModule.v2alpha.SearchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.SearchRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.SearchRequest', ['placement']); - request.placement = defaultValue1; - const expectedHeaderRequestParams = `placement=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.search = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.search(request), expectedError); - const actualRequest = (client.innerApiCalls.search as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.search as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes search without error using callback', async () => { + const client = new searchserviceModule.v2alpha.SearchServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.SearchRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.SearchRequest', + ['placement'], + ); + request.placement = defaultValue1; + const expectedHeaderRequestParams = `placement=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.cloud.retail.v2alpha.SearchResponse.SearchResult(), + ), + generateSampleMessage( + new protos.google.cloud.retail.v2alpha.SearchResponse.SearchResult(), + ), + generateSampleMessage( + new protos.google.cloud.retail.v2alpha.SearchResponse.SearchResult(), + ), + ]; + client.innerApiCalls.search = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.search( + request, + ( + err?: Error | null, + result?: + | protos.google.cloud.retail.v2alpha.SearchResponse.ISearchResult[] + | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.search as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.search as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes searchStream without error', async () => { - const client = new searchserviceModule.v2alpha.SearchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.SearchRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.SearchRequest', ['placement']); - request.placement = defaultValue1; - const expectedHeaderRequestParams = `placement=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.retail.v2alpha.SearchResponse.SearchResult()), - generateSampleMessage(new protos.google.cloud.retail.v2alpha.SearchResponse.SearchResult()), - generateSampleMessage(new protos.google.cloud.retail.v2alpha.SearchResponse.SearchResult()), - ]; - client.descriptors.page.search.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.searchStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.cloud.retail.v2alpha.SearchResponse.SearchResult[] = []; - stream.on('data', (response: protos.google.cloud.retail.v2alpha.SearchResponse.SearchResult) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.search.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.search, request)); - assert( - (client.descriptors.page.search.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes search with error', async () => { + const client = new searchserviceModule.v2alpha.SearchServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.SearchRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.SearchRequest', + ['placement'], + ); + request.placement = defaultValue1; + const expectedHeaderRequestParams = `placement=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.search = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.search(request), expectedError); + const actualRequest = (client.innerApiCalls.search as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.search as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes searchStream with error', async () => { - const client = new searchserviceModule.v2alpha.SearchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.SearchRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.SearchRequest', ['placement']); - request.placement = defaultValue1; - const expectedHeaderRequestParams = `placement=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.search.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.searchStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.cloud.retail.v2alpha.SearchResponse.SearchResult[] = []; - stream.on('data', (response: protos.google.cloud.retail.v2alpha.SearchResponse.SearchResult) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.search.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.search, request)); - assert( - (client.descriptors.page.search.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); + it('invokes searchStream without error', async () => { + const client = new searchserviceModule.v2alpha.SearchServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.SearchRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.SearchRequest', + ['placement'], + ); + request.placement = defaultValue1; + const expectedHeaderRequestParams = `placement=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.cloud.retail.v2alpha.SearchResponse.SearchResult(), + ), + generateSampleMessage( + new protos.google.cloud.retail.v2alpha.SearchResponse.SearchResult(), + ), + generateSampleMessage( + new protos.google.cloud.retail.v2alpha.SearchResponse.SearchResult(), + ), + ]; + client.descriptors.page.search.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.searchStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.cloud.retail.v2alpha.SearchResponse.SearchResult[] = + []; + stream.on( + 'data', + ( + response: protos.google.cloud.retail.v2alpha.SearchResponse.SearchResult, + ) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); }); - - it('uses async iteration with search without error', async () => { - const client = new searchserviceModule.v2alpha.SearchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.SearchRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.SearchRequest', ['placement']); - request.placement = defaultValue1; - const expectedHeaderRequestParams = `placement=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.retail.v2alpha.SearchResponse.SearchResult()), - generateSampleMessage(new protos.google.cloud.retail.v2alpha.SearchResponse.SearchResult()), - generateSampleMessage(new protos.google.cloud.retail.v2alpha.SearchResponse.SearchResult()), - ]; - client.descriptors.page.search.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.cloud.retail.v2alpha.SearchResponse.ISearchResult[] = []; - const iterable = client.searchAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.search.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.search.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); + stream.on('error', (err: Error) => { + reject(err); }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.search.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.search, request), + ); + assert( + (client.descriptors.page.search.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('uses async iteration with search with error', async () => { - const client = new searchserviceModule.v2alpha.SearchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.SearchRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.SearchRequest', ['placement']); - request.placement = defaultValue1; - const expectedHeaderRequestParams = `placement=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.search.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.searchAsync(request); - await assert.rejects(async () => { - const responses: protos.google.cloud.retail.v2alpha.SearchResponse.ISearchResult[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.search.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.search.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); + it('invokes searchStream with error', async () => { + const client = new searchserviceModule.v2alpha.SearchServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.SearchRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.SearchRequest', + ['placement'], + ); + request.placement = defaultValue1; + const expectedHeaderRequestParams = `placement=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.search.createStream = stubPageStreamingCall( + undefined, + expectedError, + ); + const stream = client.searchStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.cloud.retail.v2alpha.SearchResponse.SearchResult[] = + []; + stream.on( + 'data', + ( + response: protos.google.cloud.retail.v2alpha.SearchResponse.SearchResult, + ) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.search.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.search, request), + ); + assert( + (client.descriptors.page.search.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); }); - describe('Path templates', () => { - - describe('alertConfig', () => { - const fakePath = "/rendered/path/alertConfig"; - const expectedParameters = { - project: "projectValue", - }; - const client = new searchserviceModule.v2alpha.SearchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.alertConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.alertConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('alertConfigPath', () => { - const result = client.alertConfigPath("projectValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.alertConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromAlertConfigName', () => { - const result = client.matchProjectFromAlertConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.alertConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('uses async iteration with search without error', async () => { + const client = new searchserviceModule.v2alpha.SearchServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.SearchRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.SearchRequest', + ['placement'], + ); + request.placement = defaultValue1; + const expectedHeaderRequestParams = `placement=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.cloud.retail.v2alpha.SearchResponse.SearchResult(), + ), + generateSampleMessage( + new protos.google.cloud.retail.v2alpha.SearchResponse.SearchResult(), + ), + generateSampleMessage( + new protos.google.cloud.retail.v2alpha.SearchResponse.SearchResult(), + ), + ]; + client.descriptors.page.search.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.cloud.retail.v2alpha.SearchResponse.ISearchResult[] = + []; + const iterable = client.searchAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + (client.descriptors.page.search.asyncIterate as SinonStub).getCall(0) + .args[1], + request, + ); + assert( + (client.descriptors.page.search.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - describe('attributesConfig', () => { - const fakePath = "/rendered/path/attributesConfig"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - }; - const client = new searchserviceModule.v2alpha.SearchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.attributesConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.attributesConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('attributesConfigPath', () => { - const result = client.attributesConfigPath("projectValue", "locationValue", "catalogValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.attributesConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromAttributesConfigName', () => { - const result = client.matchProjectFromAttributesConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromAttributesConfigName', () => { - const result = client.matchLocationFromAttributesConfigName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromAttributesConfigName', () => { - const result = client.matchCatalogFromAttributesConfigName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('uses async iteration with search with error', async () => { + const client = new searchserviceModule.v2alpha.SearchServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.SearchRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.SearchRequest', + ['placement'], + ); + request.placement = defaultValue1; + const expectedHeaderRequestParams = `placement=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.search.asyncIterate = stubAsyncIterationCall( + undefined, + expectedError, + ); + const iterable = client.searchAsync(request); + await assert.rejects(async () => { + const responses: protos.google.cloud.retail.v2alpha.SearchResponse.ISearchResult[] = + []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + (client.descriptors.page.search.asyncIterate as SinonStub).getCall(0) + .args[1], + request, + ); + assert( + (client.descriptors.page.search.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + }); + + describe('Path templates', () => { + describe('alertConfig', () => { + const fakePath = '/rendered/path/alertConfig'; + const expectedParameters = { + project: 'projectValue', + }; + const client = new searchserviceModule.v2alpha.SearchServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.alertConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.alertConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('alertConfigPath', () => { + const result = client.alertConfigPath('projectValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.alertConfigPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromAlertConfigName', () => { + const result = client.matchProjectFromAlertConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.alertConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('branch', () => { - const fakePath = "/rendered/path/branch"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - branch: "branchValue", - }; - const client = new searchserviceModule.v2alpha.SearchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.branchPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.branchPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('branchPath', () => { - const result = client.branchPath("projectValue", "locationValue", "catalogValue", "branchValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.branchPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromBranchName', () => { - const result = client.matchProjectFromBranchName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.branchPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromBranchName', () => { - const result = client.matchLocationFromBranchName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.branchPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromBranchName', () => { - const result = client.matchCatalogFromBranchName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.branchPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBranchFromBranchName', () => { - const result = client.matchBranchFromBranchName(fakePath); - assert.strictEqual(result, "branchValue"); - assert((client.pathTemplates.branchPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('attributesConfig', () => { + const fakePath = '/rendered/path/attributesConfig'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + }; + const client = new searchserviceModule.v2alpha.SearchServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.attributesConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.attributesConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('attributesConfigPath', () => { + const result = client.attributesConfigPath( + 'projectValue', + 'locationValue', + 'catalogValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.attributesConfigPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromAttributesConfigName', () => { + const result = client.matchProjectFromAttributesConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromAttributesConfigName', () => { + const result = client.matchLocationFromAttributesConfigName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromAttributesConfigName', () => { + const result = client.matchCatalogFromAttributesConfigName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('catalog', () => { - const fakePath = "/rendered/path/catalog"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - }; - const client = new searchserviceModule.v2alpha.SearchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.catalogPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.catalogPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('catalogPath', () => { - const result = client.catalogPath("projectValue", "locationValue", "catalogValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.catalogPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromCatalogName', () => { - const result = client.matchProjectFromCatalogName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.catalogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromCatalogName', () => { - const result = client.matchLocationFromCatalogName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.catalogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromCatalogName', () => { - const result = client.matchCatalogFromCatalogName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.catalogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('branch', () => { + const fakePath = '/rendered/path/branch'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + branch: 'branchValue', + }; + const client = new searchserviceModule.v2alpha.SearchServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.branchPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.branchPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('branchPath', () => { + const result = client.branchPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'branchValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.branchPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromBranchName', () => { + const result = client.matchProjectFromBranchName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.branchPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromBranchName', () => { + const result = client.matchLocationFromBranchName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.branchPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromBranchName', () => { + const result = client.matchCatalogFromBranchName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.branchPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBranchFromBranchName', () => { + const result = client.matchBranchFromBranchName(fakePath); + assert.strictEqual(result, 'branchValue'); + assert( + (client.pathTemplates.branchPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('completionConfig', () => { - const fakePath = "/rendered/path/completionConfig"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - }; - const client = new searchserviceModule.v2alpha.SearchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.completionConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.completionConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('completionConfigPath', () => { - const result = client.completionConfigPath("projectValue", "locationValue", "catalogValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.completionConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromCompletionConfigName', () => { - const result = client.matchProjectFromCompletionConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.completionConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromCompletionConfigName', () => { - const result = client.matchLocationFromCompletionConfigName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.completionConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromCompletionConfigName', () => { - const result = client.matchCatalogFromCompletionConfigName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.completionConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('catalog', () => { + const fakePath = '/rendered/path/catalog'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + }; + const client = new searchserviceModule.v2alpha.SearchServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.catalogPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.catalogPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('catalogPath', () => { + const result = client.catalogPath( + 'projectValue', + 'locationValue', + 'catalogValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.catalogPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromCatalogName', () => { + const result = client.matchProjectFromCatalogName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.catalogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromCatalogName', () => { + const result = client.matchLocationFromCatalogName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.catalogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromCatalogName', () => { + const result = client.matchCatalogFromCatalogName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.catalogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('control', () => { - const fakePath = "/rendered/path/control"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - control: "controlValue", - }; - const client = new searchserviceModule.v2alpha.SearchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.controlPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.controlPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('controlPath', () => { - const result = client.controlPath("projectValue", "locationValue", "catalogValue", "controlValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.controlPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromControlName', () => { - const result = client.matchProjectFromControlName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.controlPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromControlName', () => { - const result = client.matchLocationFromControlName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.controlPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromControlName', () => { - const result = client.matchCatalogFromControlName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.controlPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchControlFromControlName', () => { - const result = client.matchControlFromControlName(fakePath); - assert.strictEqual(result, "controlValue"); - assert((client.pathTemplates.controlPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('completionConfig', () => { + const fakePath = '/rendered/path/completionConfig'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + }; + const client = new searchserviceModule.v2alpha.SearchServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.completionConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.completionConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('completionConfigPath', () => { + const result = client.completionConfigPath( + 'projectValue', + 'locationValue', + 'catalogValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.completionConfigPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromCompletionConfigName', () => { + const result = client.matchProjectFromCompletionConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.completionConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromCompletionConfigName', () => { + const result = client.matchLocationFromCompletionConfigName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.completionConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromCompletionConfigName', () => { + const result = client.matchCatalogFromCompletionConfigName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.completionConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('experiment', () => { - const fakePath = "/rendered/path/experiment"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - experiment: "experimentValue", - }; - const client = new searchserviceModule.v2alpha.SearchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.experimentPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.experimentPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('experimentPath', () => { - const result = client.experimentPath("projectValue", "locationValue", "catalogValue", "experimentValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.experimentPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromExperimentName', () => { - const result = client.matchProjectFromExperimentName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.experimentPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromExperimentName', () => { - const result = client.matchLocationFromExperimentName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.experimentPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromExperimentName', () => { - const result = client.matchCatalogFromExperimentName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.experimentPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchExperimentFromExperimentName', () => { - const result = client.matchExperimentFromExperimentName(fakePath); - assert.strictEqual(result, "experimentValue"); - assert((client.pathTemplates.experimentPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('control', () => { + const fakePath = '/rendered/path/control'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + control: 'controlValue', + }; + const client = new searchserviceModule.v2alpha.SearchServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.controlPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.controlPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('controlPath', () => { + const result = client.controlPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'controlValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.controlPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromControlName', () => { + const result = client.matchProjectFromControlName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.controlPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromControlName', () => { + const result = client.matchLocationFromControlName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.controlPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromControlName', () => { + const result = client.matchCatalogFromControlName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.controlPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchControlFromControlName', () => { + const result = client.matchControlFromControlName(fakePath); + assert.strictEqual(result, 'controlValue'); + assert( + (client.pathTemplates.controlPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('loggingConfig', () => { - const fakePath = "/rendered/path/loggingConfig"; - const expectedParameters = { - project: "projectValue", - }; - const client = new searchserviceModule.v2alpha.SearchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.loggingConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.loggingConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('loggingConfigPath', () => { - const result = client.loggingConfigPath("projectValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.loggingConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromLoggingConfigName', () => { - const result = client.matchProjectFromLoggingConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.loggingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('experiment', () => { + const fakePath = '/rendered/path/experiment'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + experiment: 'experimentValue', + }; + const client = new searchserviceModule.v2alpha.SearchServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.experimentPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.experimentPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('experimentPath', () => { + const result = client.experimentPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'experimentValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.experimentPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromExperimentName', () => { + const result = client.matchProjectFromExperimentName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.experimentPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromExperimentName', () => { + const result = client.matchLocationFromExperimentName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.experimentPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromExperimentName', () => { + const result = client.matchCatalogFromExperimentName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.experimentPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchExperimentFromExperimentName', () => { + const result = client.matchExperimentFromExperimentName(fakePath); + assert.strictEqual(result, 'experimentValue'); + assert( + (client.pathTemplates.experimentPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('merchantCenterAccountLink', () => { - const fakePath = "/rendered/path/merchantCenterAccountLink"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - merchant_center_account_link: "merchantCenterAccountLinkValue", - }; - const client = new searchserviceModule.v2alpha.SearchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.merchantCenterAccountLinkPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.merchantCenterAccountLinkPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('merchantCenterAccountLinkPath', () => { - const result = client.merchantCenterAccountLinkPath("projectValue", "locationValue", "catalogValue", "merchantCenterAccountLinkValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromMerchantCenterAccountLinkName', () => { - const result = client.matchProjectFromMerchantCenterAccountLinkName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromMerchantCenterAccountLinkName', () => { - const result = client.matchLocationFromMerchantCenterAccountLinkName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromMerchantCenterAccountLinkName', () => { - const result = client.matchCatalogFromMerchantCenterAccountLinkName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName', () => { - const result = client.matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName(fakePath); - assert.strictEqual(result, "merchantCenterAccountLinkValue"); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('loggingConfig', () => { + const fakePath = '/rendered/path/loggingConfig'; + const expectedParameters = { + project: 'projectValue', + }; + const client = new searchserviceModule.v2alpha.SearchServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.loggingConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.loggingConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('loggingConfigPath', () => { + const result = client.loggingConfigPath('projectValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.loggingConfigPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromLoggingConfigName', () => { + const result = client.matchProjectFromLoggingConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.loggingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('model', () => { - const fakePath = "/rendered/path/model"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - model: "modelValue", - }; - const client = new searchserviceModule.v2alpha.SearchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.modelPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.modelPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('modelPath', () => { - const result = client.modelPath("projectValue", "locationValue", "catalogValue", "modelValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.modelPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromModelName', () => { - const result = client.matchProjectFromModelName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromModelName', () => { - const result = client.matchLocationFromModelName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromModelName', () => { - const result = client.matchCatalogFromModelName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchModelFromModelName', () => { - const result = client.matchModelFromModelName(fakePath); - assert.strictEqual(result, "modelValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('merchantCenterAccountLink', () => { + const fakePath = '/rendered/path/merchantCenterAccountLink'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + merchant_center_account_link: 'merchantCenterAccountLinkValue', + }; + const client = new searchserviceModule.v2alpha.SearchServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.merchantCenterAccountLinkPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.merchantCenterAccountLinkPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('merchantCenterAccountLinkPath', () => { + const result = client.merchantCenterAccountLinkPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'merchantCenterAccountLinkValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromMerchantCenterAccountLinkName', () => { + const result = + client.matchProjectFromMerchantCenterAccountLinkName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromMerchantCenterAccountLinkName', () => { + const result = + client.matchLocationFromMerchantCenterAccountLinkName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromMerchantCenterAccountLinkName', () => { + const result = + client.matchCatalogFromMerchantCenterAccountLinkName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName', () => { + const result = + client.matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName( + fakePath, + ); + assert.strictEqual(result, 'merchantCenterAccountLinkValue'); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('product', () => { - const fakePath = "/rendered/path/product"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - branch: "branchValue", - product: "productValue", - }; - const client = new searchserviceModule.v2alpha.SearchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.productPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.productPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('productPath', () => { - const result = client.productPath("projectValue", "locationValue", "catalogValue", "branchValue", "productValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.productPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProductName', () => { - const result = client.matchProjectFromProductName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromProductName', () => { - const result = client.matchLocationFromProductName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromProductName', () => { - const result = client.matchCatalogFromProductName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBranchFromProductName', () => { - const result = client.matchBranchFromProductName(fakePath); - assert.strictEqual(result, "branchValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchProductFromProductName', () => { - const result = client.matchProductFromProductName(fakePath); - assert.strictEqual(result, "productValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('model', () => { + const fakePath = '/rendered/path/model'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + model: 'modelValue', + }; + const client = new searchserviceModule.v2alpha.SearchServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.modelPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.modelPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('modelPath', () => { + const result = client.modelPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'modelValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.modelPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromModelName', () => { + const result = client.matchProjectFromModelName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromModelName', () => { + const result = client.matchLocationFromModelName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromModelName', () => { + const result = client.matchCatalogFromModelName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchModelFromModelName', () => { + const result = client.matchModelFromModelName(fakePath); + assert.strictEqual(result, 'modelValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('retailProject', () => { - const fakePath = "/rendered/path/retailProject"; - const expectedParameters = { - project: "projectValue", - }; - const client = new searchserviceModule.v2alpha.SearchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.retailProjectPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.retailProjectPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('retailProjectPath', () => { - const result = client.retailProjectPath("projectValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.retailProjectPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromRetailProjectName', () => { - const result = client.matchProjectFromRetailProjectName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.retailProjectPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('product', () => { + const fakePath = '/rendered/path/product'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + branch: 'branchValue', + product: 'productValue', + }; + const client = new searchserviceModule.v2alpha.SearchServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.productPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.productPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('productPath', () => { + const result = client.productPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'branchValue', + 'productValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.productPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProductName', () => { + const result = client.matchProjectFromProductName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromProductName', () => { + const result = client.matchLocationFromProductName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromProductName', () => { + const result = client.matchCatalogFromProductName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBranchFromProductName', () => { + const result = client.matchBranchFromProductName(fakePath); + assert.strictEqual(result, 'branchValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchProductFromProductName', () => { + const result = client.matchProductFromProductName(fakePath); + assert.strictEqual(result, 'productValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('servingConfig', () => { - const fakePath = "/rendered/path/servingConfig"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - serving_config: "servingConfigValue", - }; - const client = new searchserviceModule.v2alpha.SearchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.servingConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.servingConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('servingConfigPath', () => { - const result = client.servingConfigPath("projectValue", "locationValue", "catalogValue", "servingConfigValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.servingConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromServingConfigName', () => { - const result = client.matchProjectFromServingConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.servingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromServingConfigName', () => { - const result = client.matchLocationFromServingConfigName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.servingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromServingConfigName', () => { - const result = client.matchCatalogFromServingConfigName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.servingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServingConfigFromServingConfigName', () => { - const result = client.matchServingConfigFromServingConfigName(fakePath); - assert.strictEqual(result, "servingConfigValue"); - assert((client.pathTemplates.servingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('retailProject', () => { + const fakePath = '/rendered/path/retailProject'; + const expectedParameters = { + project: 'projectValue', + }; + const client = new searchserviceModule.v2alpha.SearchServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.retailProjectPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.retailProjectPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('retailProjectPath', () => { + const result = client.retailProjectPath('projectValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.retailProjectPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromRetailProjectName', () => { + const result = client.matchProjectFromRetailProjectName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.retailProjectPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); + + describe('servingConfig', () => { + const fakePath = '/rendered/path/servingConfig'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + serving_config: 'servingConfigValue', + }; + const client = new searchserviceModule.v2alpha.SearchServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.servingConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.servingConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('servingConfigPath', () => { + const result = client.servingConfigPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'servingConfigValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.servingConfigPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromServingConfigName', () => { + const result = client.matchProjectFromServingConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.servingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromServingConfigName', () => { + const result = client.matchLocationFromServingConfigName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.servingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromServingConfigName', () => { + const result = client.matchCatalogFromServingConfigName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.servingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServingConfigFromServingConfigName', () => { + const result = client.matchServingConfigFromServingConfigName(fakePath); + assert.strictEqual(result, 'servingConfigValue'); + assert( + (client.pathTemplates.servingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/test/gapic_serving_config_service_v2alpha.ts.baseline b/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/test/gapic_serving_config_service_v2alpha.ts.baseline index ae2f7b6662df..72aa3d72dd20 100644 --- a/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/test/gapic_serving_config_service_v2alpha.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/test/gapic_serving_config_service_v2alpha.ts.baseline @@ -20,16 +20,16 @@ import * as protos from '../../protos/protos.js'; import assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as servingconfigserviceModule from '../src/index.js'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; -import {protobuf} from 'google-gax'; +import { protobuf } from 'google-gax'; import fs from 'fs'; import path from 'path'; -import {fileURLToPath} from 'url'; +import { fileURLToPath } from 'url'; // @ts-ignore const dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -37,1694 +37,2308 @@ const dirname = path.dirname(fileURLToPath(import.meta.url)); // to fill in default values for request objects const root = protobuf.Root.fromJSON( JSON.parse( - fs.readFileSync(path.join(dirname, '..', '..', 'protos/protos.json'), 'utf8') - )) + fs.readFileSync( + path.join(dirname, '..', '..', 'protos/protos.json'), + 'utf8', + ), + ), +); // eslint-disable-next-line @typescript-eslint/no-unused-vars function getTypeDefaultValue(typeName: string, fields: string[]) { - let type = root.lookupType(typeName) as protobuf.Type; - for (const field of fields.slice(0, -1)) { - type = type?.fields[field]?.resolvedType as protobuf.Type; - } - return type?.fields[fields[fields.length - 1]]?.defaultValue ?? null; + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type?.fields[field]?.resolvedType as protobuf.Type; + } + return type?.fields[fields[fields.length - 1]]?.defaultValue ?? null; } function generateSampleMessage(instance: T) { - const filledObject = (instance.constructor as typeof protobuf.Message) - .toObject(instance as protobuf.Message, {defaults: true}); - return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, { defaults: true }); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; } function stubSimpleCall(response?: ResponseType, error?: Error) { - return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); } -function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { - return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +function stubSimpleCallWithCallback( + response?: ResponseType, + error?: Error, +) { + return error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); } -function stubPageStreamingCall(responses?: ResponseType[], error?: Error) { - const pagingStub = sinon.stub(); - if (responses) { - for (let i = 0; i < responses.length; ++i) { - pagingStub.onCall(i).callsArgWith(2, null, responses[i]); - } +function stubPageStreamingCall( + responses?: ResponseType[], + error?: Error, +) { + const pagingStub = sinon.stub(); + if (responses) { + for (let i = 0; i < responses.length; ++i) { + pagingStub.onCall(i).callsArgWith(2, null, responses[i]); } - const transformStub = error ? sinon.stub().callsArgWith(2, error) : pagingStub; - const mockStream = new PassThrough({ - objectMode: true, - transform: transformStub, - }); - // trigger as many responses as needed - if (responses) { - for (let i = 0; i < responses.length; ++i) { - setImmediate(() => { mockStream.write({}); }); - } - setImmediate(() => { mockStream.end(); }); - } else { - setImmediate(() => { mockStream.write({}); }); - setImmediate(() => { mockStream.end(); }); + } + const transformStub = error + ? sinon.stub().callsArgWith(2, error) + : pagingStub; + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + // trigger as many responses as needed + if (responses) { + for (let i = 0; i < responses.length; ++i) { + setImmediate(() => { + mockStream.write({}); + }); } - return sinon.stub().returns(mockStream); + setImmediate(() => { + mockStream.end(); + }); + } else { + setImmediate(() => { + mockStream.write({}); + }); + setImmediate(() => { + mockStream.end(); + }); + } + return sinon.stub().returns(mockStream); } -function stubAsyncIterationCall(responses?: ResponseType[], error?: Error) { - let counter = 0; - const asyncIterable = { - [Symbol.asyncIterator]() { - return { - async next() { - if (error) { - return Promise.reject(error); - } - if (counter >= responses!.length) { - return Promise.resolve({done: true, value: undefined}); - } - return Promise.resolve({done: false, value: responses![counter++]}); - } - }; - } - }; - return sinon.stub().returns(asyncIterable); +function stubAsyncIterationCall( + responses?: ResponseType[], + error?: Error, +) { + let counter = 0; + const asyncIterable = { + [Symbol.asyncIterator]() { + return { + async next() { + if (error) { + return Promise.reject(error); + } + if (counter >= responses!.length) { + return Promise.resolve({ done: true, value: undefined }); + } + return Promise.resolve({ done: false, value: responses![counter++] }); + }, + }; + }, + }; + return sinon.stub().returns(asyncIterable); } describe('v2alpha.ServingConfigServiceClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new servingconfigserviceModule.v2alpha.ServingConfigServiceClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'retail.googleapis.com'); - }); - - it('has universeDomain', () => { - const client = new servingconfigserviceModule.v2alpha.ServingConfigServiceClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = + new servingconfigserviceModule.v2alpha.ServingConfigServiceClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'retail.googleapis.com'); + }); - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - it('throws DeprecationWarning if static servicePath is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const servicePath = servingconfigserviceModule.v2alpha.ServingConfigServiceClient.servicePath; - assert.strictEqual(servicePath, 'retail.googleapis.com'); - assert(stub.called); - stub.restore(); - }); + it('has universeDomain', () => { + const client = + new servingconfigserviceModule.v2alpha.ServingConfigServiceClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = servingconfigserviceModule.v2alpha.ServingConfigServiceClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'retail.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'retail.example.com'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = + servingconfigserviceModule.v2alpha.ServingConfigServiceClient + .servicePath; + assert.strictEqual(servicePath, 'retail.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + servingconfigserviceModule.v2alpha.ServingConfigServiceClient + .apiEndpoint; + assert.strictEqual(apiEndpoint, 'retail.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = + new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ + universeDomain: 'example.com', }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'retail.example.com'); + }); - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'retail.example.com'); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = + new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ + universe_domain: 'example.com', }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'retail.example.com'); + }); - if (typeof process === 'object' && 'env' in process) { - describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { - it('sets apiEndpoint from environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new servingconfigserviceModule.v2alpha.ServingConfigServiceClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'retail.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - - it('value configured in code has priority over environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'retail.configured.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); + if (typeof process === 'object' && 'env' in process) { + describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { + it('sets apiEndpoint from environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = + new servingconfigserviceModule.v2alpha.ServingConfigServiceClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'retail.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - it('has port', () => { - const port = servingconfigserviceModule.v2alpha.ServingConfigServiceClient.port; - assert(port); - assert(typeof port === 'number'); + it('value configured in code has priority over environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = + new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ + universeDomain: 'configured.example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'retail.configured.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - - it('should create a client with no option', () => { - const client = new servingconfigserviceModule.v2alpha.ServingConfigServiceClient(); - assert(client); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); + }); - it('should create a client with gRPC fallback', () => { - const client = new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ - fallback: true, - }); - assert(client); - }); + it('has port', () => { + const port = + servingconfigserviceModule.v2alpha.ServingConfigServiceClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('has initialize method and supports deferred initialization', async () => { - const client = new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.servingConfigServiceStub, undefined); - await client.initialize(); - assert(client.servingConfigServiceStub); - }); + it('should create a client with no option', () => { + const client = + new servingconfigserviceModule.v2alpha.ServingConfigServiceClient(); + assert(client); + }); - it('has close method for the initialized client', done => { - const client = new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.servingConfigServiceStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); + it('should create a client with gRPC fallback', () => { + const client = + new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ + fallback: true, }); + assert(client); + }); - it('has close method for the non-initialized client', done => { - const client = new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.servingConfigServiceStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); + it('has initialize method and supports deferred initialization', async () => { + const client = + new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + assert.strictEqual(client.servingConfigServiceStub, undefined); + await client.initialize(); + assert(client.servingConfigServiceStub); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + it('has close method for the initialized client', (done) => { + const client = + new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); - - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId((err?: Error|null, projectId?: string|null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } - }); - }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); + client.initialize().catch((err) => { + throw err; + }); + assert(client.servingConfigServiceStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); }); - describe('createServingConfig', () => { - it('invokes createServingConfig without error', async () => { - const client = new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.CreateServingConfigRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.CreateServingConfigRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ServingConfig() - ); - client.innerApiCalls.createServingConfig = stubSimpleCall(expectedResponse); - const [response] = await client.createServingConfig(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createServingConfig as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createServingConfig as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('has close method for the non-initialized client', (done) => { + const client = + new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); - - it('invokes createServingConfig without error using callback', async () => { - const client = new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.CreateServingConfigRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.CreateServingConfigRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ServingConfig() - ); - client.innerApiCalls.createServingConfig = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createServingConfig( - request, - (err?: Error|null, result?: protos.google.cloud.retail.v2alpha.IServingConfig|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createServingConfig as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createServingConfig as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + assert.strictEqual(client.servingConfigServiceStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes createServingConfig with error', async () => { - const client = new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.CreateServingConfigRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.CreateServingConfigRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createServingConfig = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createServingConfig(request), expectedError); - const actualRequest = (client.innerApiCalls.createServingConfig as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createServingConfig as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = + new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + }); - it('invokes createServingConfig with closed client', async () => { - const client = new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.CreateServingConfigRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.CreateServingConfigRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createServingConfig(request), expectedError); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = + new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); }); - - describe('deleteServingConfig', () => { - it('invokes deleteServingConfig without error', async () => { - const client = new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.DeleteServingConfigRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.DeleteServingConfigRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteServingConfig = stubSimpleCall(expectedResponse); - const [response] = await client.deleteServingConfig(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteServingConfig as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteServingConfig as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + describe('createServingConfig', () => { + it('invokes createServingConfig without error', async () => { + const client = + new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.CreateServingConfigRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.CreateServingConfigRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ServingConfig(), + ); + client.innerApiCalls.createServingConfig = + stubSimpleCall(expectedResponse); + const [response] = await client.createServingConfig(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createServingConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createServingConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteServingConfig without error using callback', async () => { - const client = new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.DeleteServingConfigRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.DeleteServingConfigRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteServingConfig = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteServingConfig( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteServingConfig as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteServingConfig as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes createServingConfig without error using callback', async () => { + const client = + new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.CreateServingConfigRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.CreateServingConfigRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ServingConfig(), + ); + client.innerApiCalls.createServingConfig = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createServingConfig( + request, + ( + err?: Error | null, + result?: protos.google.cloud.retail.v2alpha.IServingConfig | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createServingConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createServingConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteServingConfig with error', async () => { - const client = new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.DeleteServingConfigRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.DeleteServingConfigRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteServingConfig = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteServingConfig(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteServingConfig as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteServingConfig as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes createServingConfig with error', async () => { + const client = + new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.CreateServingConfigRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.CreateServingConfigRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createServingConfig = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.createServingConfig(request), expectedError); + const actualRequest = ( + client.innerApiCalls.createServingConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createServingConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteServingConfig with closed client', async () => { - const client = new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.DeleteServingConfigRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.DeleteServingConfigRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteServingConfig(request), expectedError); + it('invokes createServingConfig with closed client', async () => { + const client = + new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.CreateServingConfigRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.CreateServingConfigRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.createServingConfig(request), expectedError); }); - - describe('updateServingConfig', () => { - it('invokes updateServingConfig without error', async () => { - const client = new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.UpdateServingConfigRequest() - ); - request.servingConfig ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.UpdateServingConfigRequest', ['servingConfig', 'name']); - request.servingConfig.name = defaultValue1; - const expectedHeaderRequestParams = `serving_config.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ServingConfig() - ); - client.innerApiCalls.updateServingConfig = stubSimpleCall(expectedResponse); - const [response] = await client.updateServingConfig(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateServingConfig as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateServingConfig as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + describe('deleteServingConfig', () => { + it('invokes deleteServingConfig without error', async () => { + const client = + new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.DeleteServingConfigRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.DeleteServingConfigRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteServingConfig = + stubSimpleCall(expectedResponse); + const [response] = await client.deleteServingConfig(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteServingConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteServingConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateServingConfig without error using callback', async () => { - const client = new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.UpdateServingConfigRequest() - ); - request.servingConfig ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.UpdateServingConfigRequest', ['servingConfig', 'name']); - request.servingConfig.name = defaultValue1; - const expectedHeaderRequestParams = `serving_config.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ServingConfig() - ); - client.innerApiCalls.updateServingConfig = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateServingConfig( - request, - (err?: Error|null, result?: protos.google.cloud.retail.v2alpha.IServingConfig|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateServingConfig as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateServingConfig as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes deleteServingConfig without error using callback', async () => { + const client = + new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.DeleteServingConfigRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.DeleteServingConfigRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteServingConfig = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteServingConfig( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteServingConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteServingConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateServingConfig with error', async () => { - const client = new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.UpdateServingConfigRequest() - ); - request.servingConfig ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.UpdateServingConfigRequest', ['servingConfig', 'name']); - request.servingConfig.name = defaultValue1; - const expectedHeaderRequestParams = `serving_config.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateServingConfig = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateServingConfig(request), expectedError); - const actualRequest = (client.innerApiCalls.updateServingConfig as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateServingConfig as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes deleteServingConfig with error', async () => { + const client = + new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.DeleteServingConfigRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.DeleteServingConfigRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteServingConfig = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.deleteServingConfig(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteServingConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteServingConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateServingConfig with closed client', async () => { - const client = new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.UpdateServingConfigRequest() - ); - request.servingConfig ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.UpdateServingConfigRequest', ['servingConfig', 'name']); - request.servingConfig.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateServingConfig(request), expectedError); + it('invokes deleteServingConfig with closed client', async () => { + const client = + new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.DeleteServingConfigRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.DeleteServingConfigRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.deleteServingConfig(request), expectedError); }); - - describe('getServingConfig', () => { - it('invokes getServingConfig without error', async () => { - const client = new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.GetServingConfigRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.GetServingConfigRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ServingConfig() - ); - client.innerApiCalls.getServingConfig = stubSimpleCall(expectedResponse); - const [response] = await client.getServingConfig(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getServingConfig as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getServingConfig as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + describe('updateServingConfig', () => { + it('invokes updateServingConfig without error', async () => { + const client = + new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.UpdateServingConfigRequest(), + ); + request.servingConfig ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.UpdateServingConfigRequest', + ['servingConfig', 'name'], + ); + request.servingConfig.name = defaultValue1; + const expectedHeaderRequestParams = `serving_config.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ServingConfig(), + ); + client.innerApiCalls.updateServingConfig = + stubSimpleCall(expectedResponse); + const [response] = await client.updateServingConfig(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateServingConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateServingConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getServingConfig without error using callback', async () => { - const client = new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.GetServingConfigRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.GetServingConfigRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ServingConfig() - ); - client.innerApiCalls.getServingConfig = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getServingConfig( - request, - (err?: Error|null, result?: protos.google.cloud.retail.v2alpha.IServingConfig|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getServingConfig as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getServingConfig as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes updateServingConfig without error using callback', async () => { + const client = + new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.UpdateServingConfigRequest(), + ); + request.servingConfig ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.UpdateServingConfigRequest', + ['servingConfig', 'name'], + ); + request.servingConfig.name = defaultValue1; + const expectedHeaderRequestParams = `serving_config.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ServingConfig(), + ); + client.innerApiCalls.updateServingConfig = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateServingConfig( + request, + ( + err?: Error | null, + result?: protos.google.cloud.retail.v2alpha.IServingConfig | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateServingConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateServingConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getServingConfig with error', async () => { - const client = new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.GetServingConfigRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.GetServingConfigRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getServingConfig = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getServingConfig(request), expectedError); - const actualRequest = (client.innerApiCalls.getServingConfig as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getServingConfig as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes updateServingConfig with error', async () => { + const client = + new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.UpdateServingConfigRequest(), + ); + request.servingConfig ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.UpdateServingConfigRequest', + ['servingConfig', 'name'], + ); + request.servingConfig.name = defaultValue1; + const expectedHeaderRequestParams = `serving_config.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateServingConfig = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.updateServingConfig(request), expectedError); + const actualRequest = ( + client.innerApiCalls.updateServingConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateServingConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getServingConfig with closed client', async () => { - const client = new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.GetServingConfigRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.GetServingConfigRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getServingConfig(request), expectedError); + it('invokes updateServingConfig with closed client', async () => { + const client = + new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.UpdateServingConfigRequest(), + ); + request.servingConfig ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.UpdateServingConfigRequest', + ['servingConfig', 'name'], + ); + request.servingConfig.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.updateServingConfig(request), expectedError); }); - - describe('addControl', () => { - it('invokes addControl without error', async () => { - const client = new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.AddControlRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.AddControlRequest', ['servingConfig']); - request.servingConfig = defaultValue1; - const expectedHeaderRequestParams = `serving_config=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ServingConfig() - ); - client.innerApiCalls.addControl = stubSimpleCall(expectedResponse); - const [response] = await client.addControl(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.addControl as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.addControl as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + describe('getServingConfig', () => { + it('invokes getServingConfig without error', async () => { + const client = + new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.GetServingConfigRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.GetServingConfigRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ServingConfig(), + ); + client.innerApiCalls.getServingConfig = stubSimpleCall(expectedResponse); + const [response] = await client.getServingConfig(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getServingConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getServingConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes addControl without error using callback', async () => { - const client = new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.AddControlRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.AddControlRequest', ['servingConfig']); - request.servingConfig = defaultValue1; - const expectedHeaderRequestParams = `serving_config=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ServingConfig() - ); - client.innerApiCalls.addControl = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.addControl( - request, - (err?: Error|null, result?: protos.google.cloud.retail.v2alpha.IServingConfig|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.addControl as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.addControl as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes getServingConfig without error using callback', async () => { + const client = + new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.GetServingConfigRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.GetServingConfigRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ServingConfig(), + ); + client.innerApiCalls.getServingConfig = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getServingConfig( + request, + ( + err?: Error | null, + result?: protos.google.cloud.retail.v2alpha.IServingConfig | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getServingConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getServingConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes addControl with error', async () => { - const client = new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.AddControlRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.AddControlRequest', ['servingConfig']); - request.servingConfig = defaultValue1; - const expectedHeaderRequestParams = `serving_config=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.addControl = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.addControl(request), expectedError); - const actualRequest = (client.innerApiCalls.addControl as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.addControl as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes getServingConfig with error', async () => { + const client = + new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.GetServingConfigRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.GetServingConfigRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getServingConfig = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getServingConfig(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getServingConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getServingConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes addControl with closed client', async () => { - const client = new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.AddControlRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.AddControlRequest', ['servingConfig']); - request.servingConfig = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.addControl(request), expectedError); + it('invokes getServingConfig with closed client', async () => { + const client = + new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.GetServingConfigRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.GetServingConfigRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getServingConfig(request), expectedError); }); - - describe('removeControl', () => { - it('invokes removeControl without error', async () => { - const client = new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.RemoveControlRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.RemoveControlRequest', ['servingConfig']); - request.servingConfig = defaultValue1; - const expectedHeaderRequestParams = `serving_config=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ServingConfig() - ); - client.innerApiCalls.removeControl = stubSimpleCall(expectedResponse); - const [response] = await client.removeControl(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.removeControl as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.removeControl as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + describe('addControl', () => { + it('invokes addControl without error', async () => { + const client = + new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.AddControlRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.AddControlRequest', + ['servingConfig'], + ); + request.servingConfig = defaultValue1; + const expectedHeaderRequestParams = `serving_config=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ServingConfig(), + ); + client.innerApiCalls.addControl = stubSimpleCall(expectedResponse); + const [response] = await client.addControl(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.addControl as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.addControl as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes removeControl without error using callback', async () => { - const client = new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.RemoveControlRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.RemoveControlRequest', ['servingConfig']); - request.servingConfig = defaultValue1; - const expectedHeaderRequestParams = `serving_config=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ServingConfig() - ); - client.innerApiCalls.removeControl = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.removeControl( - request, - (err?: Error|null, result?: protos.google.cloud.retail.v2alpha.IServingConfig|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.removeControl as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.removeControl as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes addControl without error using callback', async () => { + const client = + new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.AddControlRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.AddControlRequest', + ['servingConfig'], + ); + request.servingConfig = defaultValue1; + const expectedHeaderRequestParams = `serving_config=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ServingConfig(), + ); + client.innerApiCalls.addControl = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.addControl( + request, + ( + err?: Error | null, + result?: protos.google.cloud.retail.v2alpha.IServingConfig | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.addControl as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.addControl as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes removeControl with error', async () => { - const client = new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.RemoveControlRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.RemoveControlRequest', ['servingConfig']); - request.servingConfig = defaultValue1; - const expectedHeaderRequestParams = `serving_config=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.removeControl = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.removeControl(request), expectedError); - const actualRequest = (client.innerApiCalls.removeControl as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.removeControl as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes addControl with error', async () => { + const client = + new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.AddControlRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.AddControlRequest', + ['servingConfig'], + ); + request.servingConfig = defaultValue1; + const expectedHeaderRequestParams = `serving_config=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.addControl = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.addControl(request), expectedError); + const actualRequest = ( + client.innerApiCalls.addControl as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.addControl as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes removeControl with closed client', async () => { - const client = new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.RemoveControlRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.RemoveControlRequest', ['servingConfig']); - request.servingConfig = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.removeControl(request), expectedError); + it('invokes addControl with closed client', async () => { + const client = + new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.AddControlRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.AddControlRequest', + ['servingConfig'], + ); + request.servingConfig = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.addControl(request), expectedError); }); - - describe('listServingConfigs', () => { - it('invokes listServingConfigs without error', async () => { - const client = new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ListServingConfigsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ListServingConfigsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.retail.v2alpha.ServingConfig()), - generateSampleMessage(new protos.google.cloud.retail.v2alpha.ServingConfig()), - generateSampleMessage(new protos.google.cloud.retail.v2alpha.ServingConfig()), - ]; - client.innerApiCalls.listServingConfigs = stubSimpleCall(expectedResponse); - const [response] = await client.listServingConfigs(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listServingConfigs as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listServingConfigs as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + describe('removeControl', () => { + it('invokes removeControl without error', async () => { + const client = + new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.RemoveControlRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.RemoveControlRequest', + ['servingConfig'], + ); + request.servingConfig = defaultValue1; + const expectedHeaderRequestParams = `serving_config=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ServingConfig(), + ); + client.innerApiCalls.removeControl = stubSimpleCall(expectedResponse); + const [response] = await client.removeControl(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.removeControl as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.removeControl as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listServingConfigs without error using callback', async () => { - const client = new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ListServingConfigsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ListServingConfigsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.retail.v2alpha.ServingConfig()), - generateSampleMessage(new protos.google.cloud.retail.v2alpha.ServingConfig()), - generateSampleMessage(new protos.google.cloud.retail.v2alpha.ServingConfig()), - ]; - client.innerApiCalls.listServingConfigs = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listServingConfigs( - request, - (err?: Error|null, result?: protos.google.cloud.retail.v2alpha.IServingConfig[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listServingConfigs as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listServingConfigs as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes removeControl without error using callback', async () => { + const client = + new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.RemoveControlRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.RemoveControlRequest', + ['servingConfig'], + ); + request.servingConfig = defaultValue1; + const expectedHeaderRequestParams = `serving_config=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ServingConfig(), + ); + client.innerApiCalls.removeControl = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.removeControl( + request, + ( + err?: Error | null, + result?: protos.google.cloud.retail.v2alpha.IServingConfig | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.removeControl as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.removeControl as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listServingConfigs with error', async () => { - const client = new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ListServingConfigsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ListServingConfigsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listServingConfigs = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listServingConfigs(request), expectedError); - const actualRequest = (client.innerApiCalls.listServingConfigs as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listServingConfigs as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes removeControl with error', async () => { + const client = + new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.RemoveControlRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.RemoveControlRequest', + ['servingConfig'], + ); + request.servingConfig = defaultValue1; + const expectedHeaderRequestParams = `serving_config=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.removeControl = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.removeControl(request), expectedError); + const actualRequest = ( + client.innerApiCalls.removeControl as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.removeControl as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listServingConfigsStream without error', async () => { - const client = new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ListServingConfigsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ListServingConfigsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.retail.v2alpha.ServingConfig()), - generateSampleMessage(new protos.google.cloud.retail.v2alpha.ServingConfig()), - generateSampleMessage(new protos.google.cloud.retail.v2alpha.ServingConfig()), - ]; - client.descriptors.page.listServingConfigs.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listServingConfigsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.cloud.retail.v2alpha.ServingConfig[] = []; - stream.on('data', (response: protos.google.cloud.retail.v2alpha.ServingConfig) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.listServingConfigs.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listServingConfigs, request)); - assert( - (client.descriptors.page.listServingConfigs.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); + it('invokes removeControl with closed client', async () => { + const client = + new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); - - it('invokes listServingConfigsStream with error', async () => { - const client = new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ListServingConfigsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ListServingConfigsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listServingConfigs.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listServingConfigsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.cloud.retail.v2alpha.ServingConfig[] = []; - stream.on('data', (response: protos.google.cloud.retail.v2alpha.ServingConfig) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listServingConfigs.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listServingConfigs, request)); - assert( - (client.descriptors.page.listServingConfigs.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.RemoveControlRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.RemoveControlRequest', + ['servingConfig'], + ); + request.servingConfig = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.removeControl(request), expectedError); + }); + }); + + describe('listServingConfigs', () => { + it('invokes listServingConfigs without error', async () => { + const client = + new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ListServingConfigsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ListServingConfigsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ServingConfig(), + ), + generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ServingConfig(), + ), + generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ServingConfig(), + ), + ]; + client.innerApiCalls.listServingConfigs = + stubSimpleCall(expectedResponse); + const [response] = await client.listServingConfigs(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listServingConfigs as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listServingConfigs as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('uses async iteration with listServingConfigs without error', async () => { - const client = new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ListServingConfigsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ListServingConfigsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.retail.v2alpha.ServingConfig()), - generateSampleMessage(new protos.google.cloud.retail.v2alpha.ServingConfig()), - generateSampleMessage(new protos.google.cloud.retail.v2alpha.ServingConfig()), - ]; - client.descriptors.page.listServingConfigs.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.cloud.retail.v2alpha.IServingConfig[] = []; - const iterable = client.listServingConfigsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listServingConfigs.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listServingConfigs.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); + it('invokes listServingConfigs without error using callback', async () => { + const client = + new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ListServingConfigsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ListServingConfigsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ServingConfig(), + ), + generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ServingConfig(), + ), + generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ServingConfig(), + ), + ]; + client.innerApiCalls.listServingConfigs = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listServingConfigs( + request, + ( + err?: Error | null, + result?: protos.google.cloud.retail.v2alpha.IServingConfig[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listServingConfigs as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listServingConfigs as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('uses async iteration with listServingConfigs with error', async () => { - const client = new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ListServingConfigsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ListServingConfigsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listServingConfigs.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listServingConfigsAsync(request); - await assert.rejects(async () => { - const responses: protos.google.cloud.retail.v2alpha.IServingConfig[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listServingConfigs.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listServingConfigs.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); + it('invokes listServingConfigs with error', async () => { + const client = + new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ListServingConfigsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ListServingConfigsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listServingConfigs = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listServingConfigs(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listServingConfigs as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listServingConfigs as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('Path templates', () => { - - describe('alertConfig', () => { - const fakePath = "/rendered/path/alertConfig"; - const expectedParameters = { - project: "projectValue", - }; - const client = new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.alertConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.alertConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('alertConfigPath', () => { - const result = client.alertConfigPath("projectValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.alertConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromAlertConfigName', () => { - const result = client.matchProjectFromAlertConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.alertConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('invokes listServingConfigsStream without error', async () => { + const client = + new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); - - describe('attributesConfig', () => { - const fakePath = "/rendered/path/attributesConfig"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - }; - const client = new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.attributesConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.attributesConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('attributesConfigPath', () => { - const result = client.attributesConfigPath("projectValue", "locationValue", "catalogValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.attributesConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromAttributesConfigName', () => { - const result = client.matchProjectFromAttributesConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromAttributesConfigName', () => { - const result = client.matchLocationFromAttributesConfigName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromAttributesConfigName', () => { - const result = client.matchCatalogFromAttributesConfigName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ListServingConfigsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ListServingConfigsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ServingConfig(), + ), + generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ServingConfig(), + ), + generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ServingConfig(), + ), + ]; + client.descriptors.page.listServingConfigs.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listServingConfigsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.cloud.retail.v2alpha.ServingConfig[] = + []; + stream.on( + 'data', + (response: protos.google.cloud.retail.v2alpha.ServingConfig) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); }); - - describe('branch', () => { - const fakePath = "/rendered/path/branch"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - branch: "branchValue", - }; - const client = new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.branchPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.branchPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('branchPath', () => { - const result = client.branchPath("projectValue", "locationValue", "catalogValue", "branchValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.branchPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromBranchName', () => { - const result = client.matchProjectFromBranchName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.branchPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromBranchName', () => { - const result = client.matchLocationFromBranchName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.branchPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromBranchName', () => { - const result = client.matchCatalogFromBranchName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.branchPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBranchFromBranchName', () => { - const result = client.matchBranchFromBranchName(fakePath); - assert.strictEqual(result, "branchValue"); - assert((client.pathTemplates.branchPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + stream.on('error', (err: Error) => { + reject(err); }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listServingConfigs.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listServingConfigs, request), + ); + assert( + (client.descriptors.page.listServingConfigs.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - describe('catalog', () => { - const fakePath = "/rendered/path/catalog"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - }; - const client = new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.catalogPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.catalogPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('catalogPath', () => { - const result = client.catalogPath("projectValue", "locationValue", "catalogValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.catalogPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromCatalogName', () => { - const result = client.matchProjectFromCatalogName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.catalogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromCatalogName', () => { - const result = client.matchLocationFromCatalogName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.catalogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromCatalogName', () => { - const result = client.matchCatalogFromCatalogName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.catalogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('invokes listServingConfigsStream with error', async () => { + const client = + new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); - - describe('completionConfig', () => { - const fakePath = "/rendered/path/completionConfig"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - }; - const client = new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.completionConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.completionConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('completionConfigPath', () => { - const result = client.completionConfigPath("projectValue", "locationValue", "catalogValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.completionConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromCompletionConfigName', () => { - const result = client.matchProjectFromCompletionConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.completionConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromCompletionConfigName', () => { - const result = client.matchLocationFromCompletionConfigName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.completionConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromCompletionConfigName', () => { - const result = client.matchCatalogFromCompletionConfigName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.completionConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ListServingConfigsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ListServingConfigsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listServingConfigs.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listServingConfigsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.cloud.retail.v2alpha.ServingConfig[] = + []; + stream.on( + 'data', + (response: protos.google.cloud.retail.v2alpha.ServingConfig) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); }); - - describe('control', () => { - const fakePath = "/rendered/path/control"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - control: "controlValue", - }; - const client = new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.controlPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.controlPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('controlPath', () => { - const result = client.controlPath("projectValue", "locationValue", "catalogValue", "controlValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.controlPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromControlName', () => { - const result = client.matchProjectFromControlName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.controlPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromControlName', () => { - const result = client.matchLocationFromControlName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.controlPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromControlName', () => { - const result = client.matchCatalogFromControlName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.controlPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchControlFromControlName', () => { - const result = client.matchControlFromControlName(fakePath); - assert.strictEqual(result, "controlValue"); - assert((client.pathTemplates.controlPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + stream.on('error', (err: Error) => { + reject(err); }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listServingConfigs.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listServingConfigs, request), + ); + assert( + (client.descriptors.page.listServingConfigs.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - describe('loggingConfig', () => { - const fakePath = "/rendered/path/loggingConfig"; - const expectedParameters = { - project: "projectValue", - }; - const client = new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.loggingConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.loggingConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('loggingConfigPath', () => { - const result = client.loggingConfigPath("projectValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.loggingConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromLoggingConfigName', () => { - const result = client.matchProjectFromLoggingConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.loggingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('uses async iteration with listServingConfigs without error', async () => { + const client = + new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ListServingConfigsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ListServingConfigsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ServingConfig(), + ), + generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ServingConfig(), + ), + generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ServingConfig(), + ), + ]; + client.descriptors.page.listServingConfigs.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.cloud.retail.v2alpha.IServingConfig[] = []; + const iterable = client.listServingConfigsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listServingConfigs.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listServingConfigs.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - describe('merchantCenterAccountLink', () => { - const fakePath = "/rendered/path/merchantCenterAccountLink"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - merchant_center_account_link: "merchantCenterAccountLinkValue", - }; - const client = new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.merchantCenterAccountLinkPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.merchantCenterAccountLinkPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('merchantCenterAccountLinkPath', () => { - const result = client.merchantCenterAccountLinkPath("projectValue", "locationValue", "catalogValue", "merchantCenterAccountLinkValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromMerchantCenterAccountLinkName', () => { - const result = client.matchProjectFromMerchantCenterAccountLinkName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromMerchantCenterAccountLinkName', () => { - const result = client.matchLocationFromMerchantCenterAccountLinkName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromMerchantCenterAccountLinkName', () => { - const result = client.matchCatalogFromMerchantCenterAccountLinkName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName', () => { - const result = client.matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName(fakePath); - assert.strictEqual(result, "merchantCenterAccountLinkValue"); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('uses async iteration with listServingConfigs with error', async () => { + const client = + new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); - - describe('model', () => { - const fakePath = "/rendered/path/model"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - model: "modelValue", - }; - const client = new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.modelPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.modelPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('modelPath', () => { - const result = client.modelPath("projectValue", "locationValue", "catalogValue", "modelValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.modelPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromModelName', () => { - const result = client.matchProjectFromModelName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromModelName', () => { - const result = client.matchLocationFromModelName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromModelName', () => { - const result = client.matchCatalogFromModelName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchModelFromModelName', () => { - const result = client.matchModelFromModelName(fakePath); - assert.strictEqual(result, "modelValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ListServingConfigsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ListServingConfigsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listServingConfigs.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listServingConfigsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.cloud.retail.v2alpha.IServingConfig[] = + []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listServingConfigs.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listServingConfigs.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + }); + + describe('Path templates', () => { + describe('alertConfig', () => { + const fakePath = '/rendered/path/alertConfig'; + const expectedParameters = { + project: 'projectValue', + }; + const client = + new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.alertConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.alertConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('alertConfigPath', () => { + const result = client.alertConfigPath('projectValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.alertConfigPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromAlertConfigName', () => { + const result = client.matchProjectFromAlertConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.alertConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('product', () => { - const fakePath = "/rendered/path/product"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - branch: "branchValue", - product: "productValue", - }; - const client = new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.productPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.productPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('productPath', () => { - const result = client.productPath("projectValue", "locationValue", "catalogValue", "branchValue", "productValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.productPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProductName', () => { - const result = client.matchProjectFromProductName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromProductName', () => { - const result = client.matchLocationFromProductName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('attributesConfig', () => { + const fakePath = '/rendered/path/attributesConfig'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + }; + const client = + new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.attributesConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.attributesConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('attributesConfigPath', () => { + const result = client.attributesConfigPath( + 'projectValue', + 'locationValue', + 'catalogValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.attributesConfigPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromAttributesConfigName', () => { + const result = client.matchProjectFromAttributesConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromAttributesConfigName', () => { + const result = client.matchLocationFromAttributesConfigName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromAttributesConfigName', () => { + const result = client.matchCatalogFromAttributesConfigName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchCatalogFromProductName', () => { - const result = client.matchCatalogFromProductName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('branch', () => { + const fakePath = '/rendered/path/branch'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + branch: 'branchValue', + }; + const client = + new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.branchPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.branchPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('branchPath', () => { + const result = client.branchPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'branchValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.branchPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromBranchName', () => { + const result = client.matchProjectFromBranchName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.branchPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromBranchName', () => { + const result = client.matchLocationFromBranchName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.branchPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromBranchName', () => { + const result = client.matchCatalogFromBranchName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.branchPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBranchFromBranchName', () => { + const result = client.matchBranchFromBranchName(fakePath); + assert.strictEqual(result, 'branchValue'); + assert( + (client.pathTemplates.branchPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchBranchFromProductName', () => { - const result = client.matchBranchFromProductName(fakePath); - assert.strictEqual(result, "branchValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('catalog', () => { + const fakePath = '/rendered/path/catalog'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + }; + const client = + new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.catalogPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.catalogPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('catalogPath', () => { + const result = client.catalogPath( + 'projectValue', + 'locationValue', + 'catalogValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.catalogPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromCatalogName', () => { + const result = client.matchProjectFromCatalogName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.catalogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromCatalogName', () => { + const result = client.matchLocationFromCatalogName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.catalogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromCatalogName', () => { + const result = client.matchCatalogFromCatalogName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.catalogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchProductFromProductName', () => { - const result = client.matchProductFromProductName(fakePath); - assert.strictEqual(result, "productValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('completionConfig', () => { + const fakePath = '/rendered/path/completionConfig'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + }; + const client = + new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.completionConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.completionConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('completionConfigPath', () => { + const result = client.completionConfigPath( + 'projectValue', + 'locationValue', + 'catalogValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.completionConfigPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromCompletionConfigName', () => { + const result = client.matchProjectFromCompletionConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.completionConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromCompletionConfigName', () => { + const result = client.matchLocationFromCompletionConfigName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.completionConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromCompletionConfigName', () => { + const result = client.matchCatalogFromCompletionConfigName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.completionConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('retailProject', () => { - const fakePath = "/rendered/path/retailProject"; - const expectedParameters = { - project: "projectValue", - }; - const client = new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.retailProjectPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.retailProjectPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('retailProjectPath', () => { - const result = client.retailProjectPath("projectValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.retailProjectPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + describe('control', () => { + const fakePath = '/rendered/path/control'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + control: 'controlValue', + }; + const client = + new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.controlPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.controlPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('controlPath', () => { + const result = client.controlPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'controlValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.controlPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromControlName', () => { + const result = client.matchProjectFromControlName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.controlPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromControlName', () => { + const result = client.matchLocationFromControlName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.controlPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromControlName', () => { + const result = client.matchCatalogFromControlName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.controlPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchControlFromControlName', () => { + const result = client.matchControlFromControlName(fakePath); + assert.strictEqual(result, 'controlValue'); + assert( + (client.pathTemplates.controlPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchProjectFromRetailProjectName', () => { - const result = client.matchProjectFromRetailProjectName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.retailProjectPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('loggingConfig', () => { + const fakePath = '/rendered/path/loggingConfig'; + const expectedParameters = { + project: 'projectValue', + }; + const client = + new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.loggingConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.loggingConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('loggingConfigPath', () => { + const result = client.loggingConfigPath('projectValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.loggingConfigPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromLoggingConfigName', () => { + const result = client.matchProjectFromLoggingConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.loggingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('servingConfig', () => { - const fakePath = "/rendered/path/servingConfig"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - serving_config: "servingConfigValue", - }; - const client = new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.servingConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.servingConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('servingConfigPath', () => { - const result = client.servingConfigPath("projectValue", "locationValue", "catalogValue", "servingConfigValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.servingConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + describe('merchantCenterAccountLink', () => { + const fakePath = '/rendered/path/merchantCenterAccountLink'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + merchant_center_account_link: 'merchantCenterAccountLinkValue', + }; + const client = + new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.merchantCenterAccountLinkPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.merchantCenterAccountLinkPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('merchantCenterAccountLinkPath', () => { + const result = client.merchantCenterAccountLinkPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'merchantCenterAccountLinkValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromMerchantCenterAccountLinkName', () => { + const result = + client.matchProjectFromMerchantCenterAccountLinkName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromMerchantCenterAccountLinkName', () => { + const result = + client.matchLocationFromMerchantCenterAccountLinkName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromMerchantCenterAccountLinkName', () => { + const result = + client.matchCatalogFromMerchantCenterAccountLinkName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName', () => { + const result = + client.matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName( + fakePath, + ); + assert.strictEqual(result, 'merchantCenterAccountLinkValue'); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchProjectFromServingConfigName', () => { - const result = client.matchProjectFromServingConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.servingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('model', () => { + const fakePath = '/rendered/path/model'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + model: 'modelValue', + }; + const client = + new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.modelPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.modelPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('modelPath', () => { + const result = client.modelPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'modelValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.modelPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromModelName', () => { + const result = client.matchProjectFromModelName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromModelName', () => { + const result = client.matchLocationFromModelName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromModelName', () => { + const result = client.matchCatalogFromModelName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchModelFromModelName', () => { + const result = client.matchModelFromModelName(fakePath); + assert.strictEqual(result, 'modelValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchLocationFromServingConfigName', () => { - const result = client.matchLocationFromServingConfigName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.servingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('product', () => { + const fakePath = '/rendered/path/product'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + branch: 'branchValue', + product: 'productValue', + }; + const client = + new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.productPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.productPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('productPath', () => { + const result = client.productPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'branchValue', + 'productValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.productPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProductName', () => { + const result = client.matchProjectFromProductName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromProductName', () => { + const result = client.matchLocationFromProductName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromProductName', () => { + const result = client.matchCatalogFromProductName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBranchFromProductName', () => { + const result = client.matchBranchFromProductName(fakePath); + assert.strictEqual(result, 'branchValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchProductFromProductName', () => { + const result = client.matchProductFromProductName(fakePath); + assert.strictEqual(result, 'productValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchCatalogFromServingConfigName', () => { - const result = client.matchCatalogFromServingConfigName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.servingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('retailProject', () => { + const fakePath = '/rendered/path/retailProject'; + const expectedParameters = { + project: 'projectValue', + }; + const client = + new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.retailProjectPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.retailProjectPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('retailProjectPath', () => { + const result = client.retailProjectPath('projectValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.retailProjectPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromRetailProjectName', () => { + const result = client.matchProjectFromRetailProjectName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.retailProjectPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchServingConfigFromServingConfigName', () => { - const result = client.matchServingConfigFromServingConfigName(fakePath); - assert.strictEqual(result, "servingConfigValue"); - assert((client.pathTemplates.servingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('servingConfig', () => { + const fakePath = '/rendered/path/servingConfig'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + serving_config: 'servingConfigValue', + }; + const client = + new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.servingConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.servingConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('servingConfigPath', () => { + const result = client.servingConfigPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'servingConfigValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.servingConfigPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromServingConfigName', () => { + const result = client.matchProjectFromServingConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.servingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromServingConfigName', () => { + const result = client.matchLocationFromServingConfigName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.servingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromServingConfigName', () => { + const result = client.matchCatalogFromServingConfigName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.servingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServingConfigFromServingConfigName', () => { + const result = client.matchServingConfigFromServingConfigName(fakePath); + assert.strictEqual(result, 'servingConfigValue'); + assert( + (client.pathTemplates.servingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/test/gapic_user_event_service_v2alpha.ts.baseline b/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/test/gapic_user_event_service_v2alpha.ts.baseline index 07bb9d1fbf1a..2e6e086b6b9b 100644 --- a/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/test/gapic_user_event_service_v2alpha.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/retail-esm/esm/test/gapic_user_event_service_v2alpha.ts.baseline @@ -20,14 +20,14 @@ import * as protos from '../../protos/protos.js'; import assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as usereventserviceModule from '../src/index.js'; -import {protobuf, LROperation, operationsProtos} from 'google-gax'; +import { protobuf, LROperation, operationsProtos } from 'google-gax'; import fs from 'fs'; import path from 'path'; -import {fileURLToPath} from 'url'; +import { fileURLToPath } from 'url'; // @ts-ignore const dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -35,1600 +35,2134 @@ const dirname = path.dirname(fileURLToPath(import.meta.url)); // to fill in default values for request objects const root = protobuf.Root.fromJSON( JSON.parse( - fs.readFileSync(path.join(dirname, '..', '..', 'protos/protos.json'), 'utf8') - )) + fs.readFileSync( + path.join(dirname, '..', '..', 'protos/protos.json'), + 'utf8', + ), + ), +); // eslint-disable-next-line @typescript-eslint/no-unused-vars function getTypeDefaultValue(typeName: string, fields: string[]) { - let type = root.lookupType(typeName) as protobuf.Type; - for (const field of fields.slice(0, -1)) { - type = type?.fields[field]?.resolvedType as protobuf.Type; - } - return type?.fields[fields[fields.length - 1]]?.defaultValue ?? null; + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type?.fields[field]?.resolvedType as protobuf.Type; + } + return type?.fields[fields[fields.length - 1]]?.defaultValue ?? null; } function generateSampleMessage(instance: T) { - const filledObject = (instance.constructor as typeof protobuf.Message) - .toObject(instance as protobuf.Message, {defaults: true}); - return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, { defaults: true }); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; } function stubSimpleCall(response?: ResponseType, error?: Error) { - return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); } -function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { - return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +function stubSimpleCallWithCallback( + response?: ResponseType, + error?: Error, +) { + return error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); } -function stubLongRunningCall(response?: ResponseType, callError?: Error, lroError?: Error) { - const innerStub = lroError ? sinon.stub().rejects(lroError) : sinon.stub().resolves([response]); - const mockOperation = { - promise: innerStub, - }; - return callError ? sinon.stub().rejects(callError) : sinon.stub().resolves([mockOperation]); +function stubLongRunningCall( + response?: ResponseType, + callError?: Error, + lroError?: Error, +) { + const innerStub = lroError + ? sinon.stub().rejects(lroError) + : sinon.stub().resolves([response]); + const mockOperation = { + promise: innerStub, + }; + return callError + ? sinon.stub().rejects(callError) + : sinon.stub().resolves([mockOperation]); } -function stubLongRunningCallWithCallback(response?: ResponseType, callError?: Error, lroError?: Error) { - const innerStub = lroError ? sinon.stub().rejects(lroError) : sinon.stub().resolves([response]); - const mockOperation = { - promise: innerStub, - }; - return callError ? sinon.stub().callsArgWith(2, callError) : sinon.stub().callsArgWith(2, null, mockOperation); +function stubLongRunningCallWithCallback( + response?: ResponseType, + callError?: Error, + lroError?: Error, +) { + const innerStub = lroError + ? sinon.stub().rejects(lroError) + : sinon.stub().resolves([response]); + const mockOperation = { + promise: innerStub, + }; + return callError + ? sinon.stub().callsArgWith(2, callError) + : sinon.stub().callsArgWith(2, null, mockOperation); } describe('v2alpha.UserEventServiceClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new usereventserviceModule.v2alpha.UserEventServiceClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'retail.googleapis.com'); - }); - - it('has universeDomain', () => { - const client = new usereventserviceModule.v2alpha.UserEventServiceClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); - - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - it('throws DeprecationWarning if static servicePath is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const servicePath = usereventserviceModule.v2alpha.UserEventServiceClient.servicePath; - assert.strictEqual(servicePath, 'retail.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = usereventserviceModule.v2alpha.UserEventServiceClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'retail.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new usereventserviceModule.v2alpha.UserEventServiceClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'retail.example.com'); - }); - - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new usereventserviceModule.v2alpha.UserEventServiceClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'retail.example.com'); - }); - - if (typeof process === 'object' && 'env' in process) { - describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { - it('sets apiEndpoint from environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new usereventserviceModule.v2alpha.UserEventServiceClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'retail.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - - it('value configured in code has priority over environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new usereventserviceModule.v2alpha.UserEventServiceClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'retail.configured.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { new usereventserviceModule.v2alpha.UserEventServiceClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); - - it('has port', () => { - const port = usereventserviceModule.v2alpha.UserEventServiceClient.port; - assert(port); - assert(typeof port === 'number'); - }); - - it('should create a client with no option', () => { - const client = new usereventserviceModule.v2alpha.UserEventServiceClient(); - assert(client); - }); - - it('should create a client with gRPC fallback', () => { - const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ - fallback: true, - }); - assert(client); - }); - - it('has initialize method and supports deferred initialization', async () => { - const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.userEventServiceStub, undefined); - await client.initialize(); - assert(client.userEventServiceStub); - }); - - it('has close method for the initialized client', done => { - const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.userEventServiceStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); - - it('has close method for the non-initialized client', done => { - const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.userEventServiceStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); - - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); - }); - - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId((err?: Error|null, projectId?: string|null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } - }); - }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = + new usereventserviceModule.v2alpha.UserEventServiceClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'retail.googleapis.com'); }); - describe('writeUserEvent', () => { - it('invokes writeUserEvent without error', async () => { - const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.WriteUserEventRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.WriteUserEventRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.UserEvent() - ); - client.innerApiCalls.writeUserEvent = stubSimpleCall(expectedResponse); - const [response] = await client.writeUserEvent(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.writeUserEvent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.writeUserEvent as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes writeUserEvent without error using callback', async () => { - const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.WriteUserEventRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.WriteUserEventRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.UserEvent() - ); - client.innerApiCalls.writeUserEvent = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.writeUserEvent( - request, - (err?: Error|null, result?: protos.google.cloud.retail.v2alpha.IUserEvent|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.writeUserEvent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.writeUserEvent as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes writeUserEvent with error', async () => { - const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.WriteUserEventRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.WriteUserEventRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.writeUserEvent = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.writeUserEvent(request), expectedError); - const actualRequest = (client.innerApiCalls.writeUserEvent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.writeUserEvent as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes writeUserEvent with closed client', async () => { - const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.WriteUserEventRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.WriteUserEventRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.writeUserEvent(request), expectedError); - }); + it('has universeDomain', () => { + const client = + new usereventserviceModule.v2alpha.UserEventServiceClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); }); - describe('collectUserEvent', () => { - it('invokes collectUserEvent without error', async () => { - const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.CollectUserEventRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.CollectUserEventRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.api.HttpBody() - ); - client.innerApiCalls.collectUserEvent = stubSimpleCall(expectedResponse); - const [response] = await client.collectUserEvent(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.collectUserEvent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.collectUserEvent as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes collectUserEvent without error using callback', async () => { - const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.CollectUserEventRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.CollectUserEventRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.api.HttpBody() - ); - client.innerApiCalls.collectUserEvent = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.collectUserEvent( - request, - (err?: Error|null, result?: protos.google.api.IHttpBody|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.collectUserEvent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.collectUserEvent as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes collectUserEvent with error', async () => { - const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.CollectUserEventRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.CollectUserEventRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.collectUserEvent = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.collectUserEvent(request), expectedError); - const actualRequest = (client.innerApiCalls.collectUserEvent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.collectUserEvent as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes collectUserEvent with closed client', async () => { - const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.CollectUserEventRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.CollectUserEventRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.collectUserEvent(request), expectedError); - }); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = + usereventserviceModule.v2alpha.UserEventServiceClient.servicePath; + assert.strictEqual(servicePath, 'retail.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + usereventserviceModule.v2alpha.UserEventServiceClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'retail.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ + universeDomain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'retail.example.com'); }); - describe('purgeUserEvents', () => { - it('invokes purgeUserEvents without error', async () => { - const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.PurgeUserEventsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.PurgeUserEventsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.purgeUserEvents = stubLongRunningCall(expectedResponse); - const [operation] = await client.purgeUserEvents(request); - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.purgeUserEvents as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.purgeUserEvents as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes purgeUserEvents without error using callback', async () => { - const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.PurgeUserEventsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.PurgeUserEventsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.purgeUserEvents = stubLongRunningCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.purgeUserEvents( - request, - (err?: Error|null, - result?: LROperation|null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const operation = await promise as LROperation; - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.purgeUserEvents as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.purgeUserEvents as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes purgeUserEvents with call error', async () => { - const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.PurgeUserEventsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.PurgeUserEventsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.purgeUserEvents = stubLongRunningCall(undefined, expectedError); - await assert.rejects(client.purgeUserEvents(request), expectedError); - const actualRequest = (client.innerApiCalls.purgeUserEvents as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.purgeUserEvents as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes purgeUserEvents with LRO error', async () => { - const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.PurgeUserEventsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.PurgeUserEventsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.purgeUserEvents = stubLongRunningCall(undefined, undefined, expectedError); - const [operation] = await client.purgeUserEvents(request); - await assert.rejects(operation.promise(), expectedError); - const actualRequest = (client.innerApiCalls.purgeUserEvents as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.purgeUserEvents as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes checkPurgeUserEventsProgress without error', async () => { - const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedResponse = generateSampleMessage( - new operationsProtos.google.longrunning.Operation() - ); - expectedResponse.name = 'test'; - expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; - expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')} - - client.operationsClient.getOperation = stubSimpleCall(expectedResponse); - const decodedOperation = await client.checkPurgeUserEventsProgress(expectedResponse.name); - assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); - assert(decodedOperation.metadata); - assert((client.operationsClient.getOperation as SinonStub).getCall(0)); - }); - - it('invokes checkPurgeUserEventsProgress with error', async () => { - const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedError = new Error('expected'); - - client.operationsClient.getOperation = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.checkPurgeUserEventsProgress(''), expectedError); - assert((client.operationsClient.getOperation as SinonStub) - .getCall(0)); - }); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ + universe_domain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'retail.example.com'); }); - describe('importUserEvents', () => { - it('invokes importUserEvents without error', async () => { - const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ImportUserEventsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ImportUserEventsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.importUserEvents = stubLongRunningCall(expectedResponse); - const [operation] = await client.importUserEvents(request); - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.importUserEvents as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.importUserEvents as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + if (typeof process === 'object' && 'env' in process) { + describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { + it('sets apiEndpoint from environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = + new usereventserviceModule.v2alpha.UserEventServiceClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'retail.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - it('invokes importUserEvents without error using callback', async () => { - const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ImportUserEventsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ImportUserEventsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.importUserEvents = stubLongRunningCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.importUserEvents( - request, - (err?: Error|null, - result?: LROperation|null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const operation = await promise as LROperation; - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.importUserEvents as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.importUserEvents as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes importUserEvents with call error', async () => { - const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ImportUserEventsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ImportUserEventsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.importUserEvents = stubLongRunningCall(undefined, expectedError); - await assert.rejects(client.importUserEvents(request), expectedError); - const actualRequest = (client.innerApiCalls.importUserEvents as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.importUserEvents as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes importUserEvents with LRO error', async () => { - const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ImportUserEventsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ImportUserEventsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.importUserEvents = stubLongRunningCall(undefined, undefined, expectedError); - const [operation] = await client.importUserEvents(request); - await assert.rejects(operation.promise(), expectedError); - const actualRequest = (client.innerApiCalls.importUserEvents as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.importUserEvents as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes checkImportUserEventsProgress without error', async () => { - const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedResponse = generateSampleMessage( - new operationsProtos.google.longrunning.Operation() - ); - expectedResponse.name = 'test'; - expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; - expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')} - - client.operationsClient.getOperation = stubSimpleCall(expectedResponse); - const decodedOperation = await client.checkImportUserEventsProgress(expectedResponse.name); - assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); - assert(decodedOperation.metadata); - assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + it('value configured in code has priority over environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = + new usereventserviceModule.v2alpha.UserEventServiceClient({ + universeDomain: 'configured.example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'retail.configured.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - - it('invokes checkImportUserEventsProgress with error', async () => { - const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedError = new Error('expected'); - - client.operationsClient.getOperation = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.checkImportUserEventsProgress(''), expectedError); - assert((client.operationsClient.getOperation as SinonStub) - .getCall(0)); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new usereventserviceModule.v2alpha.UserEventServiceClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); }); - describe('exportUserEvents', () => { - it('invokes exportUserEvents without error', async () => { - const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ExportUserEventsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ExportUserEventsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.exportUserEvents = stubLongRunningCall(expectedResponse); - const [operation] = await client.exportUserEvents(request); - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.exportUserEvents as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.exportUserEvents as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes exportUserEvents without error using callback', async () => { - const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ExportUserEventsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ExportUserEventsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.exportUserEvents = stubLongRunningCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.exportUserEvents( - request, - (err?: Error|null, - result?: LROperation|null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const operation = await promise as LROperation; - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.exportUserEvents as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.exportUserEvents as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes exportUserEvents with call error', async () => { - const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ExportUserEventsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ExportUserEventsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.exportUserEvents = stubLongRunningCall(undefined, expectedError); - await assert.rejects(client.exportUserEvents(request), expectedError); - const actualRequest = (client.innerApiCalls.exportUserEvents as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.exportUserEvents as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes exportUserEvents with LRO error', async () => { - const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ExportUserEventsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ExportUserEventsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.exportUserEvents = stubLongRunningCall(undefined, undefined, expectedError); - const [operation] = await client.exportUserEvents(request); - await assert.rejects(operation.promise(), expectedError); - const actualRequest = (client.innerApiCalls.exportUserEvents as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.exportUserEvents as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes checkExportUserEventsProgress without error', async () => { - const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedResponse = generateSampleMessage( - new operationsProtos.google.longrunning.Operation() - ); - expectedResponse.name = 'test'; - expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; - expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')} - - client.operationsClient.getOperation = stubSimpleCall(expectedResponse); - const decodedOperation = await client.checkExportUserEventsProgress(expectedResponse.name); - assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); - assert(decodedOperation.metadata); - assert((client.operationsClient.getOperation as SinonStub).getCall(0)); - }); - - it('invokes checkExportUserEventsProgress with error', async () => { - const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedError = new Error('expected'); - - client.operationsClient.getOperation = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.checkExportUserEventsProgress(''), expectedError); - assert((client.operationsClient.getOperation as SinonStub) - .getCall(0)); - }); + it('has port', () => { + const port = usereventserviceModule.v2alpha.UserEventServiceClient.port; + assert(port); + assert(typeof port === 'number'); }); - describe('rejoinUserEvents', () => { - it('invokes rejoinUserEvents without error', async () => { - const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.RejoinUserEventsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.RejoinUserEventsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.rejoinUserEvents = stubLongRunningCall(expectedResponse); - const [operation] = await client.rejoinUserEvents(request); - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.rejoinUserEvents as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.rejoinUserEvents as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes rejoinUserEvents without error using callback', async () => { - const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.RejoinUserEventsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.RejoinUserEventsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.rejoinUserEvents = stubLongRunningCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.rejoinUserEvents( - request, - (err?: Error|null, - result?: LROperation|null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const operation = await promise as LROperation; - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.rejoinUserEvents as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.rejoinUserEvents as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes rejoinUserEvents with call error', async () => { - const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.RejoinUserEventsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.RejoinUserEventsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.rejoinUserEvents = stubLongRunningCall(undefined, expectedError); - await assert.rejects(client.rejoinUserEvents(request), expectedError); - const actualRequest = (client.innerApiCalls.rejoinUserEvents as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.rejoinUserEvents as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes rejoinUserEvents with LRO error', async () => { - const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.RejoinUserEventsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.RejoinUserEventsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.rejoinUserEvents = stubLongRunningCall(undefined, undefined, expectedError); - const [operation] = await client.rejoinUserEvents(request); - await assert.rejects(operation.promise(), expectedError); - const actualRequest = (client.innerApiCalls.rejoinUserEvents as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.rejoinUserEvents as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes checkRejoinUserEventsProgress without error', async () => { - const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedResponse = generateSampleMessage( - new operationsProtos.google.longrunning.Operation() - ); - expectedResponse.name = 'test'; - expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; - expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')} - - client.operationsClient.getOperation = stubSimpleCall(expectedResponse); - const decodedOperation = await client.checkRejoinUserEventsProgress(expectedResponse.name); - assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); - assert(decodedOperation.metadata); - assert((client.operationsClient.getOperation as SinonStub).getCall(0)); - }); - - it('invokes checkRejoinUserEventsProgress with error', async () => { - const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedError = new Error('expected'); - - client.operationsClient.getOperation = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.checkRejoinUserEventsProgress(''), expectedError); - assert((client.operationsClient.getOperation as SinonStub) - .getCall(0)); - }); + it('should create a client with no option', () => { + const client = + new usereventserviceModule.v2alpha.UserEventServiceClient(); + assert(client); }); - describe('Path templates', () => { + it('should create a client with gRPC fallback', () => { + const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ + fallback: true, + }); + assert(client); + }); - describe('alertConfig', () => { - const fakePath = "/rendered/path/alertConfig"; - const expectedParameters = { - project: "projectValue", - }; - const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.alertConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.alertConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('alertConfigPath', () => { - const result = client.alertConfigPath("projectValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.alertConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + it('has initialize method and supports deferred initialization', async () => { + const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.userEventServiceStub, undefined); + await client.initialize(); + assert(client.userEventServiceStub); + }); - it('matchProjectFromAlertConfigName', () => { - const result = client.matchProjectFromAlertConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.alertConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('has close method for the initialized client', (done) => { + const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.userEventServiceStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - describe('attributesConfig', () => { - const fakePath = "/rendered/path/attributesConfig"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - }; - const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.attributesConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.attributesConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('attributesConfigPath', () => { - const result = client.attributesConfigPath("projectValue", "locationValue", "catalogValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.attributesConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromAttributesConfigName', () => { - const result = client.matchProjectFromAttributesConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromAttributesConfigName', () => { - const result = client.matchLocationFromAttributesConfigName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromAttributesConfigName', () => { - const result = client.matchCatalogFromAttributesConfigName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('has close method for the non-initialized client', (done) => { + const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.userEventServiceStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - describe('branch', () => { - const fakePath = "/rendered/path/branch"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - branch: "branchValue", - }; - const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.branchPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.branchPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('branchPath', () => { - const result = client.branchPath("projectValue", "locationValue", "catalogValue", "branchValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.branchPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromBranchName', () => { - const result = client.matchProjectFromBranchName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.branchPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromBranchName', () => { - const result = client.matchLocationFromBranchName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.branchPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromBranchName', () => { - const result = client.matchCatalogFromBranchName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.branchPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + }); - it('matchBranchFromBranchName', () => { - const result = client.matchBranchFromBranchName(fakePath); - assert.strictEqual(result, "branchValue"); - assert((client.pathTemplates.branchPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + }); + + describe('writeUserEvent', () => { + it('invokes writeUserEvent without error', async () => { + const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.WriteUserEventRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.WriteUserEventRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.UserEvent(), + ); + client.innerApiCalls.writeUserEvent = stubSimpleCall(expectedResponse); + const [response] = await client.writeUserEvent(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.writeUserEvent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.writeUserEvent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - describe('catalog', () => { - const fakePath = "/rendered/path/catalog"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - }; - const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.catalogPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.catalogPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('catalogPath', () => { - const result = client.catalogPath("projectValue", "locationValue", "catalogValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.catalogPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromCatalogName', () => { - const result = client.matchProjectFromCatalogName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.catalogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('invokes writeUserEvent without error using callback', async () => { + const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.WriteUserEventRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.WriteUserEventRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.UserEvent(), + ); + client.innerApiCalls.writeUserEvent = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.writeUserEvent( + request, + ( + err?: Error | null, + result?: protos.google.cloud.retail.v2alpha.IUserEvent | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.writeUserEvent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.writeUserEvent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('matchLocationFromCatalogName', () => { - const result = client.matchLocationFromCatalogName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.catalogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('invokes writeUserEvent with error', async () => { + const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.WriteUserEventRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.WriteUserEventRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.writeUserEvent = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.writeUserEvent(request), expectedError); + const actualRequest = ( + client.innerApiCalls.writeUserEvent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.writeUserEvent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('matchCatalogFromCatalogName', () => { - const result = client.matchCatalogFromCatalogName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.catalogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('invokes writeUserEvent with closed client', async () => { + const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.WriteUserEventRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.WriteUserEventRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.writeUserEvent(request), expectedError); + }); + }); + + describe('collectUserEvent', () => { + it('invokes collectUserEvent without error', async () => { + const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.CollectUserEventRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.CollectUserEventRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.api.HttpBody(), + ); + client.innerApiCalls.collectUserEvent = stubSimpleCall(expectedResponse); + const [response] = await client.collectUserEvent(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.collectUserEvent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.collectUserEvent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - describe('completionConfig', () => { - const fakePath = "/rendered/path/completionConfig"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - }; - const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.completionConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.completionConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('completionConfigPath', () => { - const result = client.completionConfigPath("projectValue", "locationValue", "catalogValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.completionConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + it('invokes collectUserEvent without error using callback', async () => { + const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.CollectUserEventRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.CollectUserEventRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.api.HttpBody(), + ); + client.innerApiCalls.collectUserEvent = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.collectUserEvent( + request, + (err?: Error | null, result?: protos.google.api.IHttpBody | null) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.collectUserEvent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.collectUserEvent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('matchProjectFromCompletionConfigName', () => { - const result = client.matchProjectFromCompletionConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.completionConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('invokes collectUserEvent with error', async () => { + const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.CollectUserEventRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.CollectUserEventRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.collectUserEvent = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.collectUserEvent(request), expectedError); + const actualRequest = ( + client.innerApiCalls.collectUserEvent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.collectUserEvent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('matchLocationFromCompletionConfigName', () => { - const result = client.matchLocationFromCompletionConfigName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.completionConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('invokes collectUserEvent with closed client', async () => { + const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.CollectUserEventRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.CollectUserEventRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.collectUserEvent(request), expectedError); + }); + }); + + describe('purgeUserEvents', () => { + it('invokes purgeUserEvents without error', async () => { + const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.PurgeUserEventsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.PurgeUserEventsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.purgeUserEvents = + stubLongRunningCall(expectedResponse); + const [operation] = await client.purgeUserEvents(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.purgeUserEvents as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.purgeUserEvents as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('matchCatalogFromCompletionConfigName', () => { - const result = client.matchCatalogFromCompletionConfigName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.completionConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('invokes purgeUserEvents without error using callback', async () => { + const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.PurgeUserEventsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.PurgeUserEventsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.purgeUserEvents = + stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.purgeUserEvents( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.cloud.retail.v2alpha.IPurgeUserEventsResponse, + protos.google.cloud.retail.v2alpha.IPurgeMetadata + > | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const operation = (await promise) as LROperation< + protos.google.cloud.retail.v2alpha.IPurgeUserEventsResponse, + protos.google.cloud.retail.v2alpha.IPurgeMetadata + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.purgeUserEvents as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.purgeUserEvents as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - describe('control', () => { - const fakePath = "/rendered/path/control"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - control: "controlValue", - }; - const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.controlPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.controlPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('controlPath', () => { - const result = client.controlPath("projectValue", "locationValue", "catalogValue", "controlValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.controlPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + it('invokes purgeUserEvents with call error', async () => { + const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.PurgeUserEventsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.PurgeUserEventsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.purgeUserEvents = stubLongRunningCall( + undefined, + expectedError, + ); + await assert.rejects(client.purgeUserEvents(request), expectedError); + const actualRequest = ( + client.innerApiCalls.purgeUserEvents as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.purgeUserEvents as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('matchProjectFromControlName', () => { - const result = client.matchProjectFromControlName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.controlPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('invokes purgeUserEvents with LRO error', async () => { + const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.PurgeUserEventsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.PurgeUserEventsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.purgeUserEvents = stubLongRunningCall( + undefined, + undefined, + expectedError, + ); + const [operation] = await client.purgeUserEvents(request); + await assert.rejects(operation.promise(), expectedError); + const actualRequest = ( + client.innerApiCalls.purgeUserEvents as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.purgeUserEvents as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('matchLocationFromControlName', () => { - const result = client.matchLocationFromControlName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.controlPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('invokes checkPurgeUserEventsProgress without error', async () => { + const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation(), + ); + expectedResponse.name = 'test'; + expectedResponse.response = { type_url: 'url', value: Buffer.from('') }; + expectedResponse.metadata = { type_url: 'url', value: Buffer.from('') }; + + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const decodedOperation = await client.checkPurgeUserEventsProgress( + expectedResponse.name, + ); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); - it('matchCatalogFromControlName', () => { - const result = client.matchCatalogFromControlName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.controlPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('invokes checkPurgeUserEventsProgress with error', async () => { + const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const expectedError = new Error('expected'); + + client.operationsClient.getOperation = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.checkPurgeUserEventsProgress(''), + expectedError, + ); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + }); + + describe('importUserEvents', () => { + it('invokes importUserEvents without error', async () => { + const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ImportUserEventsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ImportUserEventsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.importUserEvents = + stubLongRunningCall(expectedResponse); + const [operation] = await client.importUserEvents(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.importUserEvents as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.importUserEvents as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('matchControlFromControlName', () => { - const result = client.matchControlFromControlName(fakePath); - assert.strictEqual(result, "controlValue"); - assert((client.pathTemplates.controlPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('invokes importUserEvents without error using callback', async () => { + const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ImportUserEventsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ImportUserEventsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.importUserEvents = + stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.importUserEvents( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.cloud.retail.v2alpha.IImportUserEventsResponse, + protos.google.cloud.retail.v2alpha.IImportMetadata + > | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const operation = (await promise) as LROperation< + protos.google.cloud.retail.v2alpha.IImportUserEventsResponse, + protos.google.cloud.retail.v2alpha.IImportMetadata + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.importUserEvents as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.importUserEvents as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - describe('loggingConfig', () => { - const fakePath = "/rendered/path/loggingConfig"; - const expectedParameters = { - project: "projectValue", - }; - const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.loggingConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.loggingConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('loggingConfigPath', () => { - const result = client.loggingConfigPath("projectValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.loggingConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + it('invokes importUserEvents with call error', async () => { + const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ImportUserEventsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ImportUserEventsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.importUserEvents = stubLongRunningCall( + undefined, + expectedError, + ); + await assert.rejects(client.importUserEvents(request), expectedError); + const actualRequest = ( + client.innerApiCalls.importUserEvents as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.importUserEvents as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('matchProjectFromLoggingConfigName', () => { - const result = client.matchProjectFromLoggingConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.loggingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('invokes importUserEvents with LRO error', async () => { + const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ImportUserEventsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ImportUserEventsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.importUserEvents = stubLongRunningCall( + undefined, + undefined, + expectedError, + ); + const [operation] = await client.importUserEvents(request); + await assert.rejects(operation.promise(), expectedError); + const actualRequest = ( + client.innerApiCalls.importUserEvents as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.importUserEvents as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - describe('merchantCenterAccountLink', () => { - const fakePath = "/rendered/path/merchantCenterAccountLink"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - merchant_center_account_link: "merchantCenterAccountLinkValue", - }; - const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.merchantCenterAccountLinkPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.merchantCenterAccountLinkPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('merchantCenterAccountLinkPath', () => { - const result = client.merchantCenterAccountLinkPath("projectValue", "locationValue", "catalogValue", "merchantCenterAccountLinkValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + it('invokes checkImportUserEventsProgress without error', async () => { + const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation(), + ); + expectedResponse.name = 'test'; + expectedResponse.response = { type_url: 'url', value: Buffer.from('') }; + expectedResponse.metadata = { type_url: 'url', value: Buffer.from('') }; + + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const decodedOperation = await client.checkImportUserEventsProgress( + expectedResponse.name, + ); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); - it('matchProjectFromMerchantCenterAccountLinkName', () => { - const result = client.matchProjectFromMerchantCenterAccountLinkName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('invokes checkImportUserEventsProgress with error', async () => { + const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const expectedError = new Error('expected'); + + client.operationsClient.getOperation = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.checkImportUserEventsProgress(''), + expectedError, + ); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + }); + + describe('exportUserEvents', () => { + it('invokes exportUserEvents without error', async () => { + const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ExportUserEventsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ExportUserEventsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.exportUserEvents = + stubLongRunningCall(expectedResponse); + const [operation] = await client.exportUserEvents(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.exportUserEvents as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.exportUserEvents as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('matchLocationFromMerchantCenterAccountLinkName', () => { - const result = client.matchLocationFromMerchantCenterAccountLinkName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('invokes exportUserEvents without error using callback', async () => { + const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ExportUserEventsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ExportUserEventsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.exportUserEvents = + stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.exportUserEvents( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.cloud.retail.v2alpha.IExportUserEventsResponse, + protos.google.cloud.retail.v2alpha.IExportMetadata + > | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const operation = (await promise) as LROperation< + protos.google.cloud.retail.v2alpha.IExportUserEventsResponse, + protos.google.cloud.retail.v2alpha.IExportMetadata + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.exportUserEvents as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.exportUserEvents as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('matchCatalogFromMerchantCenterAccountLinkName', () => { - const result = client.matchCatalogFromMerchantCenterAccountLinkName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('invokes exportUserEvents with call error', async () => { + const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ExportUserEventsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ExportUserEventsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.exportUserEvents = stubLongRunningCall( + undefined, + expectedError, + ); + await assert.rejects(client.exportUserEvents(request), expectedError); + const actualRequest = ( + client.innerApiCalls.exportUserEvents as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.exportUserEvents as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName', () => { - const result = client.matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName(fakePath); - assert.strictEqual(result, "merchantCenterAccountLinkValue"); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('invokes exportUserEvents with LRO error', async () => { + const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ExportUserEventsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ExportUserEventsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.exportUserEvents = stubLongRunningCall( + undefined, + undefined, + expectedError, + ); + const [operation] = await client.exportUserEvents(request); + await assert.rejects(operation.promise(), expectedError); + const actualRequest = ( + client.innerApiCalls.exportUserEvents as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.exportUserEvents as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - describe('model', () => { - const fakePath = "/rendered/path/model"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - model: "modelValue", - }; - const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.modelPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.modelPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('modelPath', () => { - const result = client.modelPath("projectValue", "locationValue", "catalogValue", "modelValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.modelPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + it('invokes checkExportUserEventsProgress without error', async () => { + const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation(), + ); + expectedResponse.name = 'test'; + expectedResponse.response = { type_url: 'url', value: Buffer.from('') }; + expectedResponse.metadata = { type_url: 'url', value: Buffer.from('') }; + + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const decodedOperation = await client.checkExportUserEventsProgress( + expectedResponse.name, + ); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); - it('matchProjectFromModelName', () => { - const result = client.matchProjectFromModelName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('invokes checkExportUserEventsProgress with error', async () => { + const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const expectedError = new Error('expected'); + + client.operationsClient.getOperation = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.checkExportUserEventsProgress(''), + expectedError, + ); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + }); + + describe('rejoinUserEvents', () => { + it('invokes rejoinUserEvents without error', async () => { + const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.RejoinUserEventsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.RejoinUserEventsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.rejoinUserEvents = + stubLongRunningCall(expectedResponse); + const [operation] = await client.rejoinUserEvents(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.rejoinUserEvents as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.rejoinUserEvents as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('matchLocationFromModelName', () => { - const result = client.matchLocationFromModelName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('invokes rejoinUserEvents without error using callback', async () => { + const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.RejoinUserEventsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.RejoinUserEventsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.rejoinUserEvents = + stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.rejoinUserEvents( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.cloud.retail.v2alpha.IRejoinUserEventsResponse, + protos.google.cloud.retail.v2alpha.IRejoinUserEventsMetadata + > | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const operation = (await promise) as LROperation< + protos.google.cloud.retail.v2alpha.IRejoinUserEventsResponse, + protos.google.cloud.retail.v2alpha.IRejoinUserEventsMetadata + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.rejoinUserEvents as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.rejoinUserEvents as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('matchCatalogFromModelName', () => { - const result = client.matchCatalogFromModelName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('invokes rejoinUserEvents with call error', async () => { + const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.RejoinUserEventsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.RejoinUserEventsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.rejoinUserEvents = stubLongRunningCall( + undefined, + expectedError, + ); + await assert.rejects(client.rejoinUserEvents(request), expectedError); + const actualRequest = ( + client.innerApiCalls.rejoinUserEvents as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.rejoinUserEvents as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('matchModelFromModelName', () => { - const result = client.matchModelFromModelName(fakePath); - assert.strictEqual(result, "modelValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('invokes rejoinUserEvents with LRO error', async () => { + const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.RejoinUserEventsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.RejoinUserEventsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.rejoinUserEvents = stubLongRunningCall( + undefined, + undefined, + expectedError, + ); + const [operation] = await client.rejoinUserEvents(request); + await assert.rejects(operation.promise(), expectedError); + const actualRequest = ( + client.innerApiCalls.rejoinUserEvents as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.rejoinUserEvents as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - describe('product', () => { - const fakePath = "/rendered/path/product"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - branch: "branchValue", - product: "productValue", - }; - const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.productPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.productPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('productPath', () => { - const result = client.productPath("projectValue", "locationValue", "catalogValue", "branchValue", "productValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.productPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + it('invokes checkRejoinUserEventsProgress without error', async () => { + const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation(), + ); + expectedResponse.name = 'test'; + expectedResponse.response = { type_url: 'url', value: Buffer.from('') }; + expectedResponse.metadata = { type_url: 'url', value: Buffer.from('') }; + + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const decodedOperation = await client.checkRejoinUserEventsProgress( + expectedResponse.name, + ); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); - it('matchProjectFromProductName', () => { - const result = client.matchProjectFromProductName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('invokes checkRejoinUserEventsProgress with error', async () => { + const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const expectedError = new Error('expected'); + + client.operationsClient.getOperation = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.checkRejoinUserEventsProgress(''), + expectedError, + ); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + }); + + describe('Path templates', () => { + describe('alertConfig', () => { + const fakePath = '/rendered/path/alertConfig'; + const expectedParameters = { + project: 'projectValue', + }; + const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.alertConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.alertConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('alertConfigPath', () => { + const result = client.alertConfigPath('projectValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.alertConfigPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromAlertConfigName', () => { + const result = client.matchProjectFromAlertConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.alertConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchLocationFromProductName', () => { - const result = client.matchLocationFromProductName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('attributesConfig', () => { + const fakePath = '/rendered/path/attributesConfig'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + }; + const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.attributesConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.attributesConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('attributesConfigPath', () => { + const result = client.attributesConfigPath( + 'projectValue', + 'locationValue', + 'catalogValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.attributesConfigPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromAttributesConfigName', () => { + const result = client.matchProjectFromAttributesConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromAttributesConfigName', () => { + const result = client.matchLocationFromAttributesConfigName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromAttributesConfigName', () => { + const result = client.matchCatalogFromAttributesConfigName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchCatalogFromProductName', () => { - const result = client.matchCatalogFromProductName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('branch', () => { + const fakePath = '/rendered/path/branch'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + branch: 'branchValue', + }; + const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.branchPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.branchPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('branchPath', () => { + const result = client.branchPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'branchValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.branchPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromBranchName', () => { + const result = client.matchProjectFromBranchName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.branchPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromBranchName', () => { + const result = client.matchLocationFromBranchName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.branchPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromBranchName', () => { + const result = client.matchCatalogFromBranchName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.branchPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBranchFromBranchName', () => { + const result = client.matchBranchFromBranchName(fakePath); + assert.strictEqual(result, 'branchValue'); + assert( + (client.pathTemplates.branchPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchBranchFromProductName', () => { - const result = client.matchBranchFromProductName(fakePath); - assert.strictEqual(result, "branchValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('catalog', () => { + const fakePath = '/rendered/path/catalog'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + }; + const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.catalogPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.catalogPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('catalogPath', () => { + const result = client.catalogPath( + 'projectValue', + 'locationValue', + 'catalogValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.catalogPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromCatalogName', () => { + const result = client.matchProjectFromCatalogName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.catalogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromCatalogName', () => { + const result = client.matchLocationFromCatalogName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.catalogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromCatalogName', () => { + const result = client.matchCatalogFromCatalogName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.catalogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchProductFromProductName', () => { - const result = client.matchProductFromProductName(fakePath); - assert.strictEqual(result, "productValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('completionConfig', () => { + const fakePath = '/rendered/path/completionConfig'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + }; + const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.completionConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.completionConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('completionConfigPath', () => { + const result = client.completionConfigPath( + 'projectValue', + 'locationValue', + 'catalogValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.completionConfigPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromCompletionConfigName', () => { + const result = client.matchProjectFromCompletionConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.completionConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromCompletionConfigName', () => { + const result = client.matchLocationFromCompletionConfigName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.completionConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromCompletionConfigName', () => { + const result = client.matchCatalogFromCompletionConfigName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.completionConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('retailProject', () => { - const fakePath = "/rendered/path/retailProject"; - const expectedParameters = { - project: "projectValue", - }; - const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.retailProjectPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.retailProjectPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('retailProjectPath', () => { - const result = client.retailProjectPath("projectValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.retailProjectPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + describe('control', () => { + const fakePath = '/rendered/path/control'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + control: 'controlValue', + }; + const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.controlPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.controlPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('controlPath', () => { + const result = client.controlPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'controlValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.controlPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromControlName', () => { + const result = client.matchProjectFromControlName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.controlPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromControlName', () => { + const result = client.matchLocationFromControlName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.controlPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromControlName', () => { + const result = client.matchCatalogFromControlName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.controlPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchControlFromControlName', () => { + const result = client.matchControlFromControlName(fakePath); + assert.strictEqual(result, 'controlValue'); + assert( + (client.pathTemplates.controlPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchProjectFromRetailProjectName', () => { - const result = client.matchProjectFromRetailProjectName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.retailProjectPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('loggingConfig', () => { + const fakePath = '/rendered/path/loggingConfig'; + const expectedParameters = { + project: 'projectValue', + }; + const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.loggingConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.loggingConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('loggingConfigPath', () => { + const result = client.loggingConfigPath('projectValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.loggingConfigPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromLoggingConfigName', () => { + const result = client.matchProjectFromLoggingConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.loggingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('servingConfig', () => { - const fakePath = "/rendered/path/servingConfig"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - serving_config: "servingConfigValue", - }; - const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.servingConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.servingConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('servingConfigPath', () => { - const result = client.servingConfigPath("projectValue", "locationValue", "catalogValue", "servingConfigValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.servingConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + describe('merchantCenterAccountLink', () => { + const fakePath = '/rendered/path/merchantCenterAccountLink'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + merchant_center_account_link: 'merchantCenterAccountLinkValue', + }; + const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.merchantCenterAccountLinkPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.merchantCenterAccountLinkPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('merchantCenterAccountLinkPath', () => { + const result = client.merchantCenterAccountLinkPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'merchantCenterAccountLinkValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromMerchantCenterAccountLinkName', () => { + const result = + client.matchProjectFromMerchantCenterAccountLinkName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromMerchantCenterAccountLinkName', () => { + const result = + client.matchLocationFromMerchantCenterAccountLinkName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromMerchantCenterAccountLinkName', () => { + const result = + client.matchCatalogFromMerchantCenterAccountLinkName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName', () => { + const result = + client.matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName( + fakePath, + ); + assert.strictEqual(result, 'merchantCenterAccountLinkValue'); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchProjectFromServingConfigName', () => { - const result = client.matchProjectFromServingConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.servingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('model', () => { + const fakePath = '/rendered/path/model'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + model: 'modelValue', + }; + const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.modelPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.modelPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('modelPath', () => { + const result = client.modelPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'modelValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.modelPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromModelName', () => { + const result = client.matchProjectFromModelName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromModelName', () => { + const result = client.matchLocationFromModelName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromModelName', () => { + const result = client.matchCatalogFromModelName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchModelFromModelName', () => { + const result = client.matchModelFromModelName(fakePath); + assert.strictEqual(result, 'modelValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchLocationFromServingConfigName', () => { - const result = client.matchLocationFromServingConfigName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.servingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('product', () => { + const fakePath = '/rendered/path/product'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + branch: 'branchValue', + product: 'productValue', + }; + const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.productPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.productPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('productPath', () => { + const result = client.productPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'branchValue', + 'productValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.productPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProductName', () => { + const result = client.matchProjectFromProductName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromProductName', () => { + const result = client.matchLocationFromProductName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromProductName', () => { + const result = client.matchCatalogFromProductName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBranchFromProductName', () => { + const result = client.matchBranchFromProductName(fakePath); + assert.strictEqual(result, 'branchValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchProductFromProductName', () => { + const result = client.matchProductFromProductName(fakePath); + assert.strictEqual(result, 'productValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchCatalogFromServingConfigName', () => { - const result = client.matchCatalogFromServingConfigName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.servingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('retailProject', () => { + const fakePath = '/rendered/path/retailProject'; + const expectedParameters = { + project: 'projectValue', + }; + const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.retailProjectPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.retailProjectPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('retailProjectPath', () => { + const result = client.retailProjectPath('projectValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.retailProjectPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromRetailProjectName', () => { + const result = client.matchProjectFromRetailProjectName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.retailProjectPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchServingConfigFromServingConfigName', () => { - const result = client.matchServingConfigFromServingConfigName(fakePath); - assert.strictEqual(result, "servingConfigValue"); - assert((client.pathTemplates.servingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('servingConfig', () => { + const fakePath = '/rendered/path/servingConfig'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + serving_config: 'servingConfigValue', + }; + const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.servingConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.servingConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('servingConfigPath', () => { + const result = client.servingConfigPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'servingConfigValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.servingConfigPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromServingConfigName', () => { + const result = client.matchProjectFromServingConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.servingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromServingConfigName', () => { + const result = client.matchLocationFromServingConfigName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.servingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromServingConfigName', () => { + const result = client.matchCatalogFromServingConfigName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.servingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServingConfigFromServingConfigName', () => { + const result = client.matchServingConfigFromServingConfigName(fakePath); + assert.strictEqual(result, 'servingConfigValue'); + assert( + (client.pathTemplates.servingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/core/generator/gapic-generator-typescript/baselines/retail/src/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/retail/src/index.ts.baseline index 781726dc39b8..72c358116a2f 100644 --- a/core/generator/gapic-generator-typescript/baselines/retail/src/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/retail/src/index.ts.baseline @@ -27,12 +27,16 @@ const CompletionServiceClient = v2alpha.CompletionServiceClient; type CompletionServiceClient = v2alpha.CompletionServiceClient; const ControlServiceClient = v2alpha.ControlServiceClient; type ControlServiceClient = v2alpha.ControlServiceClient; -const ConversationalSearchServiceClient = v2alpha.ConversationalSearchServiceClient; -type ConversationalSearchServiceClient = v2alpha.ConversationalSearchServiceClient; +const ConversationalSearchServiceClient = + v2alpha.ConversationalSearchServiceClient; +type ConversationalSearchServiceClient = + v2alpha.ConversationalSearchServiceClient; const GenerativeQuestionServiceClient = v2alpha.GenerativeQuestionServiceClient; type GenerativeQuestionServiceClient = v2alpha.GenerativeQuestionServiceClient; -const MerchantCenterAccountLinkServiceClient = v2alpha.MerchantCenterAccountLinkServiceClient; -type MerchantCenterAccountLinkServiceClient = v2alpha.MerchantCenterAccountLinkServiceClient; +const MerchantCenterAccountLinkServiceClient = + v2alpha.MerchantCenterAccountLinkServiceClient; +type MerchantCenterAccountLinkServiceClient = + v2alpha.MerchantCenterAccountLinkServiceClient; const ModelServiceClient = v2alpha.ModelServiceClient; type ModelServiceClient = v2alpha.ModelServiceClient; const PredictionServiceClient = v2alpha.PredictionServiceClient; @@ -47,7 +51,41 @@ const ServingConfigServiceClient = v2alpha.ServingConfigServiceClient; type ServingConfigServiceClient = v2alpha.ServingConfigServiceClient; const UserEventServiceClient = v2alpha.UserEventServiceClient; type UserEventServiceClient = v2alpha.UserEventServiceClient; -export {v2alpha, AnalyticsServiceClient, BranchServiceClient, CatalogServiceClient, CompletionServiceClient, ControlServiceClient, ConversationalSearchServiceClient, GenerativeQuestionServiceClient, MerchantCenterAccountLinkServiceClient, ModelServiceClient, PredictionServiceClient, ProductServiceClient, ProjectServiceClient, SearchServiceClient, ServingConfigServiceClient, UserEventServiceClient}; -export default {v2alpha, AnalyticsServiceClient, BranchServiceClient, CatalogServiceClient, CompletionServiceClient, ControlServiceClient, ConversationalSearchServiceClient, GenerativeQuestionServiceClient, MerchantCenterAccountLinkServiceClient, ModelServiceClient, PredictionServiceClient, ProductServiceClient, ProjectServiceClient, SearchServiceClient, ServingConfigServiceClient, UserEventServiceClient}; +export { + v2alpha, + AnalyticsServiceClient, + BranchServiceClient, + CatalogServiceClient, + CompletionServiceClient, + ControlServiceClient, + ConversationalSearchServiceClient, + GenerativeQuestionServiceClient, + MerchantCenterAccountLinkServiceClient, + ModelServiceClient, + PredictionServiceClient, + ProductServiceClient, + ProjectServiceClient, + SearchServiceClient, + ServingConfigServiceClient, + UserEventServiceClient, +}; +export default { + v2alpha, + AnalyticsServiceClient, + BranchServiceClient, + CatalogServiceClient, + CompletionServiceClient, + ControlServiceClient, + ConversationalSearchServiceClient, + GenerativeQuestionServiceClient, + MerchantCenterAccountLinkServiceClient, + ModelServiceClient, + PredictionServiceClient, + ProductServiceClient, + ProjectServiceClient, + SearchServiceClient, + ServingConfigServiceClient, + UserEventServiceClient, +}; import * as protos from '../protos/protos'; -export {protos} +export { protos }; diff --git a/core/generator/gapic-generator-typescript/baselines/retail/src/v2alpha/analytics_service_client.ts.baseline b/core/generator/gapic-generator-typescript/baselines/retail/src/v2alpha/analytics_service_client.ts.baseline index 15a667095bee..7b50b42bd797 100644 --- a/core/generator/gapic-generator-typescript/baselines/retail/src/v2alpha/analytics_service_client.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/retail/src/v2alpha/analytics_service_client.ts.baseline @@ -18,11 +18,18 @@ /* global window */ import type * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions, GrpcClientOptions, LROperation} from 'google-gax'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + GrpcClientOptions, + LROperation, +} from 'google-gax'; import * as protos from '../../protos/protos'; import jsonProtos = require('../../protos/protos.json'); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; /** * Client JSON configuration object, loaded from @@ -45,7 +52,7 @@ export class AnalyticsServiceClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('retail'); @@ -58,10 +65,10 @@ export class AnalyticsServiceClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; operationsClient: gax.OperationsClient; - analyticsServiceStub?: Promise<{[name: string]: Function}>; + analyticsServiceStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of AnalyticsServiceClient. @@ -102,21 +109,42 @@ export class AnalyticsServiceClient { * const client = new AnalyticsServiceClient({fallback: true}, gax); * ``` */ - constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { // Ensure that options include all the required fields. const staticMembers = this.constructor as typeof AnalyticsServiceClient; - if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { - throw new Error('Please set either universe_domain or universeDomain, but not both.'); + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); } - const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; - this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; this._servicePath = 'retail.' + this._universeDomain; - const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; - const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. if (servicePath !== this._servicePath && !('scopes' in opts)) { @@ -138,7 +166,7 @@ export class AnalyticsServiceClient { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; @@ -152,10 +180,7 @@ export class AnalyticsServiceClient { } // Determine the client header string. - const clientHeader = [ - `gax/${this._gaxModule.version}`, - `gapic/${version}`, - ]; + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/${process.versions.node}`); } else { @@ -177,40 +202,40 @@ export class AnalyticsServiceClient { // Create useful helper objects for these. this.pathTemplates = { alertConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/alertConfig' + 'projects/{project}/alertConfig', ), attributesConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/attributesConfig' + 'projects/{project}/locations/{location}/catalogs/{catalog}/attributesConfig', ), branchPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}', ), catalogPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}' + 'projects/{project}/locations/{location}/catalogs/{catalog}', ), completionConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/completionConfig' + 'projects/{project}/locations/{location}/catalogs/{catalog}/completionConfig', ), controlPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/controls/{control}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/controls/{control}', ), loggingConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/loggingConfig' + 'projects/{project}/loggingConfig', ), merchantCenterAccountLinkPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/merchantCenterAccountLinks/{merchant_center_account_link}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/merchantCenterAccountLinks/{merchant_center_account_link}', ), modelPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/models/{model}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/models/{model}', ), productPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}', ), retailProjectPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/retailProject' + 'projects/{project}/retailProject', ), servingConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/servingConfigs/{serving_config}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/servingConfigs/{serving_config}', ), }; @@ -220,31 +245,64 @@ export class AnalyticsServiceClient { // rather than holding a request open. const lroOptions: GrpcClientOptions = { auth: this.auth, - grpc: 'grpc' in this._gaxGrpc ? this._gaxGrpc.grpc : undefined + grpc: 'grpc' in this._gaxGrpc ? this._gaxGrpc.grpc : undefined, }; if (opts.fallback) { lroOptions.protoJson = protoFilesRoot; - lroOptions.httpRules = [{selector: 'google.longrunning.Operations.GetOperation',get: '/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*/operations/*}',additional_bindings: [{get: '/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*/places/*/operations/*}',},{get: '/v2alpha/{name=projects/*/locations/*/catalogs/*/operations/*}',},{get: '/v2alpha/{name=projects/*/locations/*/operations/*}',},{get: '/v2alpha/{name=projects/*/operations/*}',}], - },{selector: 'google.longrunning.Operations.ListOperations',get: '/v2alpha/{name=projects/*/locations/*/catalogs/*}/operations',additional_bindings: [{get: '/v2alpha/{name=projects/*/locations/*}/operations',},{get: '/v2alpha/{name=projects/*}/operations',}], - }]; + lroOptions.httpRules = [ + { + selector: 'google.longrunning.Operations.GetOperation', + get: '/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*/operations/*}', + additional_bindings: [ + { + get: '/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*/places/*/operations/*}', + }, + { + get: '/v2alpha/{name=projects/*/locations/*/catalogs/*/operations/*}', + }, + { get: '/v2alpha/{name=projects/*/locations/*/operations/*}' }, + { get: '/v2alpha/{name=projects/*/operations/*}' }, + ], + }, + { + selector: 'google.longrunning.Operations.ListOperations', + get: '/v2alpha/{name=projects/*/locations/*/catalogs/*}/operations', + additional_bindings: [ + { get: '/v2alpha/{name=projects/*/locations/*}/operations' }, + { get: '/v2alpha/{name=projects/*}/operations' }, + ], + }, + ]; } - this.operationsClient = this._gaxModule.lro(lroOptions).operationsClient(opts); + this.operationsClient = this._gaxModule + .lro(lroOptions) + .operationsClient(opts); const exportAnalyticsMetricsResponse = protoFilesRoot.lookup( - '.google.cloud.retail.v2alpha.ExportAnalyticsMetricsResponse') as gax.protobuf.Type; + '.google.cloud.retail.v2alpha.ExportAnalyticsMetricsResponse', + ) as gax.protobuf.Type; const exportAnalyticsMetricsMetadata = protoFilesRoot.lookup( - '.google.cloud.retail.v2alpha.ExportMetadata') as gax.protobuf.Type; + '.google.cloud.retail.v2alpha.ExportMetadata', + ) as gax.protobuf.Type; this.descriptors.longrunning = { exportAnalyticsMetrics: new this._gaxModule.LongrunningDescriptor( this.operationsClient, - exportAnalyticsMetricsResponse.decode.bind(exportAnalyticsMetricsResponse), - exportAnalyticsMetricsMetadata.decode.bind(exportAnalyticsMetricsMetadata)) + exportAnalyticsMetricsResponse.decode.bind( + exportAnalyticsMetricsResponse, + ), + exportAnalyticsMetricsMetadata.decode.bind( + exportAnalyticsMetricsMetadata, + ), + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.cloud.retail.v2alpha.AnalyticsService', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.cloud.retail.v2alpha.AnalyticsService', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + { 'x-goog-api-client': clientHeader.join(' ') }, + ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -275,37 +333,40 @@ export class AnalyticsServiceClient { // Put together the "service stub" for // google.cloud.retail.v2alpha.AnalyticsService. this.analyticsServiceStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.cloud.retail.v2alpha.AnalyticsService') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.cloud.retail.v2alpha.AnalyticsService', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.cloud.retail.v2alpha.AnalyticsService, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts, + this._providedCustomServicePath, + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const analyticsServiceStubMethods = - ['exportAnalyticsMetrics']; + const analyticsServiceStubMethods = ['exportAnalyticsMetrics']; for (const methodName of analyticsServiceStubMethods) { const callPromise = this.analyticsServiceStub.then( - stub => (...args: Array<{}>) => { - if (this._terminated) { - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error|null|undefined) => () => { + (stub) => + (...args: Array<{}>) => { + if (this._terminated) { + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { throw err; - }); + }, + ); - const descriptor = - this.descriptors.longrunning[methodName] || - undefined; + const descriptor = this.descriptors.longrunning[methodName] || undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -320,8 +381,14 @@ export class AnalyticsServiceClient { * @returns {string} The DNS address for this service. */ static get servicePath() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'retail.googleapis.com'; } @@ -332,8 +399,14 @@ export class AnalyticsServiceClient { * @returns {string} The DNS address for this service. */ static get apiEndpoint() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'retail.googleapis.com'; } @@ -364,9 +437,7 @@ export class AnalyticsServiceClient { * @returns {string[]} List of default scopes. */ static get scopes() { - return [ - 'https://www.googleapis.com/auth/cloud-platform' - ]; + return ['https://www.googleapis.com/auth/cloud-platform']; } getProjectId(): Promise; @@ -375,8 +446,9 @@ export class AnalyticsServiceClient { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId(callback?: Callback): - Promise|void { + getProjectId( + callback?: Callback, + ): Promise | void { if (callback) { this.auth.getProjectId(callback); return; @@ -388,136 +460,198 @@ export class AnalyticsServiceClient { // -- Service calls -- // ------------------- -/** - * Exports analytics metrics. - * - * `Operation.response` is of type `ExportAnalyticsMetricsResponse`. - * `Operation.metadata` is of type `ExportMetadata`. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.catalog - * Required. Full resource name of the parent catalog. - * Expected format: `projects/* /locations/* /catalogs/*` - * @param {google.cloud.retail.v2alpha.OutputConfig} request.outputConfig - * Required. The output location of the data. - * @param {string} request.filter - * A filtering expression to specify restrictions on returned metrics. - * The expression is a sequence of terms. Each term applies a restriction to - * the returned metrics. Use this expression to restrict results to a - * specific time range. - * - * Currently we expect only one types of fields: - * - * * `timestamp`: This can be specified twice, once with a - * less than operator and once with a greater than operator. The - * `timestamp` restriction should result in one, contiguous, valid, - * `timestamp` range. - * - * Some examples of valid filters expressions: - * - * * Example 1: `timestamp > "2012-04-23T18:25:43.511Z" - * timestamp < "2012-04-23T18:30:43.511Z"` - * * Example 2: `timestamp > "2012-04-23T18:25:43.511Z"` - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing - * a long running operation. Its `promise()` method returns a promise - * you can `await` for. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/analytics_service.export_analytics_metrics.js - * region_tag:retail_v2alpha_generated_AnalyticsService_ExportAnalyticsMetrics_async - */ + /** + * Exports analytics metrics. + * + * `Operation.response` is of type `ExportAnalyticsMetricsResponse`. + * `Operation.metadata` is of type `ExportMetadata`. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.catalog + * Required. Full resource name of the parent catalog. + * Expected format: `projects/* /locations/* /catalogs/*` + * @param {google.cloud.retail.v2alpha.OutputConfig} request.outputConfig + * Required. The output location of the data. + * @param {string} request.filter + * A filtering expression to specify restrictions on returned metrics. + * The expression is a sequence of terms. Each term applies a restriction to + * the returned metrics. Use this expression to restrict results to a + * specific time range. + * + * Currently we expect only one types of fields: + * + * * `timestamp`: This can be specified twice, once with a + * less than operator and once with a greater than operator. The + * `timestamp` restriction should result in one, contiguous, valid, + * `timestamp` range. + * + * Some examples of valid filters expressions: + * + * * Example 1: `timestamp > "2012-04-23T18:25:43.511Z" + * timestamp < "2012-04-23T18:30:43.511Z"` + * * Example 2: `timestamp > "2012-04-23T18:25:43.511Z"` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/analytics_service.export_analytics_metrics.js + * region_tag:retail_v2alpha_generated_AnalyticsService_ExportAnalyticsMetrics_async + */ exportAnalyticsMetrics( - request?: protos.google.cloud.retail.v2alpha.IExportAnalyticsMetricsRequest, - options?: CallOptions): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.IExportAnalyticsMetricsRequest, + options?: CallOptions, + ): Promise< + [ + LROperation< + protos.google.cloud.retail.v2alpha.IExportAnalyticsMetricsResponse, + protos.google.cloud.retail.v2alpha.IExportMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; exportAnalyticsMetrics( - request: protos.google.cloud.retail.v2alpha.IExportAnalyticsMetricsRequest, - options: CallOptions, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IExportAnalyticsMetricsRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IExportAnalyticsMetricsResponse, + protos.google.cloud.retail.v2alpha.IExportMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; exportAnalyticsMetrics( - request: protos.google.cloud.retail.v2alpha.IExportAnalyticsMetricsRequest, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IExportAnalyticsMetricsRequest, + callback: Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IExportAnalyticsMetricsResponse, + protos.google.cloud.retail.v2alpha.IExportMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; exportAnalyticsMetrics( - request?: protos.google.cloud.retail.v2alpha.IExportAnalyticsMetricsRequest, - optionsOrCallback?: CallOptions|Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>, - callback?: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>|void { + request?: protos.google.cloud.retail.v2alpha.IExportAnalyticsMetricsRequest, + optionsOrCallback?: + | CallOptions + | Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IExportAnalyticsMetricsResponse, + protos.google.cloud.retail.v2alpha.IExportMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + callback?: Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IExportAnalyticsMetricsResponse, + protos.google.cloud.retail.v2alpha.IExportMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + LROperation< + protos.google.cloud.retail.v2alpha.IExportAnalyticsMetricsResponse, + protos.google.cloud.retail.v2alpha.IExportMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'catalog': request.catalog ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + catalog: request.catalog ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IExportAnalyticsMetricsResponse, + protos.google.cloud.retail.v2alpha.IExportMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, rawResponse, _) => { this._log.info('exportAnalyticsMetrics response %j', rawResponse); callback!(error, response, rawResponse, _); // We verified callback above. } : undefined; this._log.info('exportAnalyticsMetrics request %j', request); - return this.innerApiCalls.exportAnalyticsMetrics(request, options, wrappedCallback) - ?.then(([response, rawResponse, _]: [ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]) => { - this._log.info('exportAnalyticsMetrics response %j', rawResponse); - return [response, rawResponse, _]; - }); + return this.innerApiCalls + .exportAnalyticsMetrics(request, options, wrappedCallback) + ?.then( + ([response, rawResponse, _]: [ + LROperation< + protos.google.cloud.retail.v2alpha.IExportAnalyticsMetricsResponse, + protos.google.cloud.retail.v2alpha.IExportMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ]) => { + this._log.info('exportAnalyticsMetrics response %j', rawResponse); + return [response, rawResponse, _]; + }, + ); } -/** - * Check the status of the long running operation returned by `exportAnalyticsMetrics()`. - * @param {String} name - * The operation name that will be passed. - * @returns {Promise} - The promise which resolves to an object. - * The decoded operation object has result and metadata field to get information from. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/analytics_service.export_analytics_metrics.js - * region_tag:retail_v2alpha_generated_AnalyticsService_ExportAnalyticsMetrics_async - */ - async checkExportAnalyticsMetricsProgress(name: string): Promise>{ + /** + * Check the status of the long running operation returned by `exportAnalyticsMetrics()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/analytics_service.export_analytics_metrics.js + * region_tag:retail_v2alpha_generated_AnalyticsService_ExportAnalyticsMetrics_async + */ + async checkExportAnalyticsMetricsProgress( + name: string, + ): Promise< + LROperation< + protos.google.cloud.retail.v2alpha.ExportAnalyticsMetricsResponse, + protos.google.cloud.retail.v2alpha.ExportMetadata + > + > { this._log.info('exportAnalyticsMetrics long-running'); - const request = new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest({name}); + const request = + new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( + { name }, + ); const [operation] = await this.operationsClient.getOperation(request); - const decodeOperation = new this._gaxModule.Operation(operation, this.descriptors.longrunning.exportAnalyticsMetrics, this._gaxModule.createDefaultBackoffSettings()); - return decodeOperation as LROperation; + const decodeOperation = new this._gaxModule.Operation( + operation, + this.descriptors.longrunning.exportAnalyticsMetrics, + this._gaxModule.createDefaultBackoffSettings(), + ); + return decodeOperation as LROperation< + protos.google.cloud.retail.v2alpha.ExportAnalyticsMetricsResponse, + protos.google.cloud.retail.v2alpha.ExportMetadata + >; } // -------------------- // -- Path templates -- @@ -529,7 +663,7 @@ export class AnalyticsServiceClient { * @param {string} project * @returns {string} Resource name string. */ - alertConfigPath(project:string) { + alertConfigPath(project: string) { return this.pathTemplates.alertConfigPathTemplate.render({ project: project, }); @@ -543,7 +677,8 @@ export class AnalyticsServiceClient { * @returns {string} A string representing the project. */ matchProjectFromAlertConfigName(alertConfigName: string) { - return this.pathTemplates.alertConfigPathTemplate.match(alertConfigName).project; + return this.pathTemplates.alertConfigPathTemplate.match(alertConfigName) + .project; } /** @@ -554,7 +689,7 @@ export class AnalyticsServiceClient { * @param {string} catalog * @returns {string} Resource name string. */ - attributesConfigPath(project:string,location:string,catalog:string) { + attributesConfigPath(project: string, location: string, catalog: string) { return this.pathTemplates.attributesConfigPathTemplate.render({ project: project, location: location, @@ -570,7 +705,9 @@ export class AnalyticsServiceClient { * @returns {string} A string representing the project. */ matchProjectFromAttributesConfigName(attributesConfigName: string) { - return this.pathTemplates.attributesConfigPathTemplate.match(attributesConfigName).project; + return this.pathTemplates.attributesConfigPathTemplate.match( + attributesConfigName, + ).project; } /** @@ -581,7 +718,9 @@ export class AnalyticsServiceClient { * @returns {string} A string representing the location. */ matchLocationFromAttributesConfigName(attributesConfigName: string) { - return this.pathTemplates.attributesConfigPathTemplate.match(attributesConfigName).location; + return this.pathTemplates.attributesConfigPathTemplate.match( + attributesConfigName, + ).location; } /** @@ -592,7 +731,9 @@ export class AnalyticsServiceClient { * @returns {string} A string representing the catalog. */ matchCatalogFromAttributesConfigName(attributesConfigName: string) { - return this.pathTemplates.attributesConfigPathTemplate.match(attributesConfigName).catalog; + return this.pathTemplates.attributesConfigPathTemplate.match( + attributesConfigName, + ).catalog; } /** @@ -604,7 +745,12 @@ export class AnalyticsServiceClient { * @param {string} branch * @returns {string} Resource name string. */ - branchPath(project:string,location:string,catalog:string,branch:string) { + branchPath( + project: string, + location: string, + catalog: string, + branch: string, + ) { return this.pathTemplates.branchPathTemplate.render({ project: project, location: location, @@ -665,7 +811,7 @@ export class AnalyticsServiceClient { * @param {string} catalog * @returns {string} Resource name string. */ - catalogPath(project:string,location:string,catalog:string) { + catalogPath(project: string, location: string, catalog: string) { return this.pathTemplates.catalogPathTemplate.render({ project: project, location: location, @@ -714,7 +860,7 @@ export class AnalyticsServiceClient { * @param {string} catalog * @returns {string} Resource name string. */ - completionConfigPath(project:string,location:string,catalog:string) { + completionConfigPath(project: string, location: string, catalog: string) { return this.pathTemplates.completionConfigPathTemplate.render({ project: project, location: location, @@ -730,7 +876,9 @@ export class AnalyticsServiceClient { * @returns {string} A string representing the project. */ matchProjectFromCompletionConfigName(completionConfigName: string) { - return this.pathTemplates.completionConfigPathTemplate.match(completionConfigName).project; + return this.pathTemplates.completionConfigPathTemplate.match( + completionConfigName, + ).project; } /** @@ -741,7 +889,9 @@ export class AnalyticsServiceClient { * @returns {string} A string representing the location. */ matchLocationFromCompletionConfigName(completionConfigName: string) { - return this.pathTemplates.completionConfigPathTemplate.match(completionConfigName).location; + return this.pathTemplates.completionConfigPathTemplate.match( + completionConfigName, + ).location; } /** @@ -752,7 +902,9 @@ export class AnalyticsServiceClient { * @returns {string} A string representing the catalog. */ matchCatalogFromCompletionConfigName(completionConfigName: string) { - return this.pathTemplates.completionConfigPathTemplate.match(completionConfigName).catalog; + return this.pathTemplates.completionConfigPathTemplate.match( + completionConfigName, + ).catalog; } /** @@ -764,7 +916,12 @@ export class AnalyticsServiceClient { * @param {string} control * @returns {string} Resource name string. */ - controlPath(project:string,location:string,catalog:string,control:string) { + controlPath( + project: string, + location: string, + catalog: string, + control: string, + ) { return this.pathTemplates.controlPathTemplate.render({ project: project, location: location, @@ -823,7 +980,7 @@ export class AnalyticsServiceClient { * @param {string} project * @returns {string} Resource name string. */ - loggingConfigPath(project:string) { + loggingConfigPath(project: string) { return this.pathTemplates.loggingConfigPathTemplate.render({ project: project, }); @@ -837,7 +994,8 @@ export class AnalyticsServiceClient { * @returns {string} A string representing the project. */ matchProjectFromLoggingConfigName(loggingConfigName: string) { - return this.pathTemplates.loggingConfigPathTemplate.match(loggingConfigName).project; + return this.pathTemplates.loggingConfigPathTemplate.match(loggingConfigName) + .project; } /** @@ -849,7 +1007,12 @@ export class AnalyticsServiceClient { * @param {string} merchant_center_account_link * @returns {string} Resource name string. */ - merchantCenterAccountLinkPath(project:string,location:string,catalog:string,merchantCenterAccountLink:string) { + merchantCenterAccountLinkPath( + project: string, + location: string, + catalog: string, + merchantCenterAccountLink: string, + ) { return this.pathTemplates.merchantCenterAccountLinkPathTemplate.render({ project: project, location: location, @@ -865,8 +1028,12 @@ export class AnalyticsServiceClient { * A fully-qualified path representing MerchantCenterAccountLink resource. * @returns {string} A string representing the project. */ - matchProjectFromMerchantCenterAccountLinkName(merchantCenterAccountLinkName: string) { - return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match(merchantCenterAccountLinkName).project; + matchProjectFromMerchantCenterAccountLinkName( + merchantCenterAccountLinkName: string, + ) { + return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match( + merchantCenterAccountLinkName, + ).project; } /** @@ -876,8 +1043,12 @@ export class AnalyticsServiceClient { * A fully-qualified path representing MerchantCenterAccountLink resource. * @returns {string} A string representing the location. */ - matchLocationFromMerchantCenterAccountLinkName(merchantCenterAccountLinkName: string) { - return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match(merchantCenterAccountLinkName).location; + matchLocationFromMerchantCenterAccountLinkName( + merchantCenterAccountLinkName: string, + ) { + return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match( + merchantCenterAccountLinkName, + ).location; } /** @@ -887,8 +1058,12 @@ export class AnalyticsServiceClient { * A fully-qualified path representing MerchantCenterAccountLink resource. * @returns {string} A string representing the catalog. */ - matchCatalogFromMerchantCenterAccountLinkName(merchantCenterAccountLinkName: string) { - return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match(merchantCenterAccountLinkName).catalog; + matchCatalogFromMerchantCenterAccountLinkName( + merchantCenterAccountLinkName: string, + ) { + return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match( + merchantCenterAccountLinkName, + ).catalog; } /** @@ -898,8 +1073,12 @@ export class AnalyticsServiceClient { * A fully-qualified path representing MerchantCenterAccountLink resource. * @returns {string} A string representing the merchant_center_account_link. */ - matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName(merchantCenterAccountLinkName: string) { - return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match(merchantCenterAccountLinkName).merchant_center_account_link; + matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName( + merchantCenterAccountLinkName: string, + ) { + return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match( + merchantCenterAccountLinkName, + ).merchant_center_account_link; } /** @@ -911,7 +1090,7 @@ export class AnalyticsServiceClient { * @param {string} model * @returns {string} Resource name string. */ - modelPath(project:string,location:string,catalog:string,model:string) { + modelPath(project: string, location: string, catalog: string, model: string) { return this.pathTemplates.modelPathTemplate.render({ project: project, location: location, @@ -974,7 +1153,13 @@ export class AnalyticsServiceClient { * @param {string} product * @returns {string} Resource name string. */ - productPath(project:string,location:string,catalog:string,branch:string,product:string) { + productPath( + project: string, + location: string, + catalog: string, + branch: string, + product: string, + ) { return this.pathTemplates.productPathTemplate.render({ project: project, location: location, @@ -1045,7 +1230,7 @@ export class AnalyticsServiceClient { * @param {string} project * @returns {string} Resource name string. */ - retailProjectPath(project:string) { + retailProjectPath(project: string) { return this.pathTemplates.retailProjectPathTemplate.render({ project: project, }); @@ -1059,7 +1244,8 @@ export class AnalyticsServiceClient { * @returns {string} A string representing the project. */ matchProjectFromRetailProjectName(retailProjectName: string) { - return this.pathTemplates.retailProjectPathTemplate.match(retailProjectName).project; + return this.pathTemplates.retailProjectPathTemplate.match(retailProjectName) + .project; } /** @@ -1071,7 +1257,12 @@ export class AnalyticsServiceClient { * @param {string} serving_config * @returns {string} Resource name string. */ - servingConfigPath(project:string,location:string,catalog:string,servingConfig:string) { + servingConfigPath( + project: string, + location: string, + catalog: string, + servingConfig: string, + ) { return this.pathTemplates.servingConfigPathTemplate.render({ project: project, location: location, @@ -1088,7 +1279,8 @@ export class AnalyticsServiceClient { * @returns {string} A string representing the project. */ matchProjectFromServingConfigName(servingConfigName: string) { - return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName).project; + return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName) + .project; } /** @@ -1099,7 +1291,8 @@ export class AnalyticsServiceClient { * @returns {string} A string representing the location. */ matchLocationFromServingConfigName(servingConfigName: string) { - return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName).location; + return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName) + .location; } /** @@ -1110,7 +1303,8 @@ export class AnalyticsServiceClient { * @returns {string} A string representing the catalog. */ matchCatalogFromServingConfigName(servingConfigName: string) { - return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName).catalog; + return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName) + .catalog; } /** @@ -1121,7 +1315,8 @@ export class AnalyticsServiceClient { * @returns {string} A string representing the serving_config. */ matchServingConfigFromServingConfigName(servingConfigName: string) { - return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName).serving_config; + return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName) + .serving_config; } /** @@ -1132,7 +1327,7 @@ export class AnalyticsServiceClient { */ close(): Promise { if (this.analyticsServiceStub && !this._terminated) { - return this.analyticsServiceStub.then(stub => { + return this.analyticsServiceStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -1141,4 +1336,4 @@ export class AnalyticsServiceClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/core/generator/gapic-generator-typescript/baselines/retail/src/v2alpha/branch_service_client.ts.baseline b/core/generator/gapic-generator-typescript/baselines/retail/src/v2alpha/branch_service_client.ts.baseline index 82511e0f7474..6020696f147f 100644 --- a/core/generator/gapic-generator-typescript/baselines/retail/src/v2alpha/branch_service_client.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/retail/src/v2alpha/branch_service_client.ts.baseline @@ -18,11 +18,16 @@ /* global window */ import type * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions} from 'google-gax'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, +} from 'google-gax'; import * as protos from '../../protos/protos'; import jsonProtos = require('../../protos/protos.json'); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; /** * Client JSON configuration object, loaded from @@ -50,7 +55,7 @@ export class BranchServiceClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('retail'); @@ -63,9 +68,9 @@ export class BranchServiceClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; - branchServiceStub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; + branchServiceStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of BranchServiceClient. @@ -106,21 +111,42 @@ export class BranchServiceClient { * const client = new BranchServiceClient({fallback: true}, gax); * ``` */ - constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { // Ensure that options include all the required fields. const staticMembers = this.constructor as typeof BranchServiceClient; - if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { - throw new Error('Please set either universe_domain or universeDomain, but not both.'); + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); } - const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; - this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; this._servicePath = 'retail.' + this._universeDomain; - const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; - const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. if (servicePath !== this._servicePath && !('scopes' in opts)) { @@ -142,7 +168,7 @@ export class BranchServiceClient { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; @@ -156,10 +182,7 @@ export class BranchServiceClient { } // Determine the client header string. - const clientHeader = [ - `gax/${this._gaxModule.version}`, - `gapic/${version}`, - ]; + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/${process.versions.node}`); } else { @@ -181,47 +204,50 @@ export class BranchServiceClient { // Create useful helper objects for these. this.pathTemplates = { alertConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/alertConfig' + 'projects/{project}/alertConfig', ), attributesConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/attributesConfig' + 'projects/{project}/locations/{location}/catalogs/{catalog}/attributesConfig', ), branchPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}', ), catalogPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}' + 'projects/{project}/locations/{location}/catalogs/{catalog}', ), completionConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/completionConfig' + 'projects/{project}/locations/{location}/catalogs/{catalog}/completionConfig', ), controlPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/controls/{control}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/controls/{control}', ), loggingConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/loggingConfig' + 'projects/{project}/loggingConfig', ), merchantCenterAccountLinkPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/merchantCenterAccountLinks/{merchant_center_account_link}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/merchantCenterAccountLinks/{merchant_center_account_link}', ), modelPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/models/{model}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/models/{model}', ), productPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}', ), retailProjectPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/retailProject' + 'projects/{project}/retailProject', ), servingConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/servingConfigs/{serving_config}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/servingConfigs/{serving_config}', ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.cloud.retail.v2alpha.BranchService', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.cloud.retail.v2alpha.BranchService', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + { 'x-goog-api-client': clientHeader.join(' ') }, + ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -252,36 +278,40 @@ export class BranchServiceClient { // Put together the "service stub" for // google.cloud.retail.v2alpha.BranchService. this.branchServiceStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.cloud.retail.v2alpha.BranchService') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.cloud.retail.v2alpha.BranchService', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.cloud.retail.v2alpha.BranchService, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts, + this._providedCustomServicePath, + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const branchServiceStubMethods = - ['listBranches', 'getBranch']; + const branchServiceStubMethods = ['listBranches', 'getBranch']; for (const methodName of branchServiceStubMethods) { const callPromise = this.branchServiceStub.then( - stub => (...args: Array<{}>) => { - if (this._terminated) { - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error|null|undefined) => () => { + (stub) => + (...args: Array<{}>) => { + if (this._terminated) { + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { throw err; - }); + }, + ); - const descriptor = - undefined; + const descriptor = undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -296,8 +326,14 @@ export class BranchServiceClient { * @returns {string} The DNS address for this service. */ static get servicePath() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'retail.googleapis.com'; } @@ -308,8 +344,14 @@ export class BranchServiceClient { * @returns {string} The DNS address for this service. */ static get apiEndpoint() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'retail.googleapis.com'; } @@ -340,9 +382,7 @@ export class BranchServiceClient { * @returns {string[]} List of default scopes. */ static get scopes() { - return [ - 'https://www.googleapis.com/auth/cloud-platform' - ]; + return ['https://www.googleapis.com/auth/cloud-platform']; } getProjectId(): Promise; @@ -351,8 +391,9 @@ export class BranchServiceClient { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId(callback?: Callback): - Promise|void { + getProjectId( + callback?: Callback, + ): Promise | void { if (callback) { this.auth.getProjectId(callback); return; @@ -363,208 +404,282 @@ export class BranchServiceClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Lists all instances of {@link protos.google.cloud.retail.v2alpha.Branch|Branch} under - * the specified parent {@link protos.google.cloud.retail.v2alpha.Catalog|Catalog}. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent catalog resource name. - * @param {google.cloud.retail.v2alpha.BranchView} request.view - * The view to apply to the returned - * {@link protos.google.cloud.retail.v2alpha.Branch|Branch}. Defaults to - * [Branch.BranchView.BASIC] if unspecified. - * See documentation of fields of {@link protos.google.cloud.retail.v2alpha.Branch|Branch} - * to find what fields are excluded from BASIC view. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.ListBranchesResponse|ListBranchesResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/branch_service.list_branches.js - * region_tag:retail_v2alpha_generated_BranchService_ListBranches_async - */ + /** + * Lists all instances of {@link protos.google.cloud.retail.v2alpha.Branch|Branch} under + * the specified parent {@link protos.google.cloud.retail.v2alpha.Catalog|Catalog}. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent catalog resource name. + * @param {google.cloud.retail.v2alpha.BranchView} request.view + * The view to apply to the returned + * {@link protos.google.cloud.retail.v2alpha.Branch|Branch}. Defaults to + * [Branch.BranchView.BASIC] if unspecified. + * See documentation of fields of {@link protos.google.cloud.retail.v2alpha.Branch|Branch} + * to find what fields are excluded from BASIC view. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.ListBranchesResponse|ListBranchesResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/branch_service.list_branches.js + * region_tag:retail_v2alpha_generated_BranchService_ListBranches_async + */ listBranches( - request?: protos.google.cloud.retail.v2alpha.IListBranchesRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.retail.v2alpha.IListBranchesResponse, - protos.google.cloud.retail.v2alpha.IListBranchesRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.IListBranchesRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IListBranchesResponse, + protos.google.cloud.retail.v2alpha.IListBranchesRequest | undefined, + {} | undefined, + ] + >; listBranches( - request: protos.google.cloud.retail.v2alpha.IListBranchesRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.retail.v2alpha.IListBranchesResponse, - protos.google.cloud.retail.v2alpha.IListBranchesRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IListBranchesRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.retail.v2alpha.IListBranchesResponse, + | protos.google.cloud.retail.v2alpha.IListBranchesRequest + | null + | undefined, + {} | null | undefined + >, + ): void; listBranches( - request: protos.google.cloud.retail.v2alpha.IListBranchesRequest, - callback: Callback< - protos.google.cloud.retail.v2alpha.IListBranchesResponse, - protos.google.cloud.retail.v2alpha.IListBranchesRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IListBranchesRequest, + callback: Callback< + protos.google.cloud.retail.v2alpha.IListBranchesResponse, + | protos.google.cloud.retail.v2alpha.IListBranchesRequest + | null + | undefined, + {} | null | undefined + >, + ): void; listBranches( - request?: protos.google.cloud.retail.v2alpha.IListBranchesRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.retail.v2alpha.IListBranchesResponse, - protos.google.cloud.retail.v2alpha.IListBranchesRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.retail.v2alpha.IListBranchesRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.retail.v2alpha.IListBranchesResponse, - protos.google.cloud.retail.v2alpha.IListBranchesRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.retail.v2alpha.IListBranchesResponse, - protos.google.cloud.retail.v2alpha.IListBranchesRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.retail.v2alpha.IListBranchesRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.retail.v2alpha.IListBranchesResponse, + | protos.google.cloud.retail.v2alpha.IListBranchesRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IListBranchesResponse, + protos.google.cloud.retail.v2alpha.IListBranchesRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('listBranches request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.retail.v2alpha.IListBranchesResponse, - protos.google.cloud.retail.v2alpha.IListBranchesRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.retail.v2alpha.IListBranchesResponse, + | protos.google.cloud.retail.v2alpha.IListBranchesRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('listBranches response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.listBranches(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.retail.v2alpha.IListBranchesResponse, - protos.google.cloud.retail.v2alpha.IListBranchesRequest|undefined, - {}|undefined - ]) => { - this._log.info('listBranches response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .listBranches(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.retail.v2alpha.IListBranchesResponse, + protos.google.cloud.retail.v2alpha.IListBranchesRequest | undefined, + {} | undefined, + ]) => { + this._log.info('listBranches response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Retrieves a {@link protos.google.cloud.retail.v2alpha.Branch|Branch}. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The name of the branch to retrieve. - * Format: - * `projects/* /locations/global/catalogs/default_catalog/branches/some_branch_id`. - * - * "default_branch" can be used as a special branch_id, it returns the - * default branch that has been set for the catalog. - * @param {google.cloud.retail.v2alpha.BranchView} request.view - * The view to apply to the returned - * {@link protos.google.cloud.retail.v2alpha.Branch|Branch}. Defaults to - * [Branch.BranchView.BASIC] if unspecified. - * See documentation of fields of {@link protos.google.cloud.retail.v2alpha.Branch|Branch} - * to find what fields are excluded from BASIC view. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.Branch|Branch}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/branch_service.get_branch.js - * region_tag:retail_v2alpha_generated_BranchService_GetBranch_async - */ + /** + * Retrieves a {@link protos.google.cloud.retail.v2alpha.Branch|Branch}. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The name of the branch to retrieve. + * Format: + * `projects/* /locations/global/catalogs/default_catalog/branches/some_branch_id`. + * + * "default_branch" can be used as a special branch_id, it returns the + * default branch that has been set for the catalog. + * @param {google.cloud.retail.v2alpha.BranchView} request.view + * The view to apply to the returned + * {@link protos.google.cloud.retail.v2alpha.Branch|Branch}. Defaults to + * [Branch.BranchView.BASIC] if unspecified. + * See documentation of fields of {@link protos.google.cloud.retail.v2alpha.Branch|Branch} + * to find what fields are excluded from BASIC view. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.Branch|Branch}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/branch_service.get_branch.js + * region_tag:retail_v2alpha_generated_BranchService_GetBranch_async + */ getBranch( - request?: protos.google.cloud.retail.v2alpha.IGetBranchRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.retail.v2alpha.IBranch, - protos.google.cloud.retail.v2alpha.IGetBranchRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.IGetBranchRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IBranch, + protos.google.cloud.retail.v2alpha.IGetBranchRequest | undefined, + {} | undefined, + ] + >; getBranch( - request: protos.google.cloud.retail.v2alpha.IGetBranchRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.retail.v2alpha.IBranch, - protos.google.cloud.retail.v2alpha.IGetBranchRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IGetBranchRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.retail.v2alpha.IBranch, + protos.google.cloud.retail.v2alpha.IGetBranchRequest | null | undefined, + {} | null | undefined + >, + ): void; getBranch( - request: protos.google.cloud.retail.v2alpha.IGetBranchRequest, - callback: Callback< - protos.google.cloud.retail.v2alpha.IBranch, - protos.google.cloud.retail.v2alpha.IGetBranchRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IGetBranchRequest, + callback: Callback< + protos.google.cloud.retail.v2alpha.IBranch, + protos.google.cloud.retail.v2alpha.IGetBranchRequest | null | undefined, + {} | null | undefined + >, + ): void; getBranch( - request?: protos.google.cloud.retail.v2alpha.IGetBranchRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.retail.v2alpha.IBranch, - protos.google.cloud.retail.v2alpha.IGetBranchRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.retail.v2alpha.IGetBranchRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.retail.v2alpha.IBranch, - protos.google.cloud.retail.v2alpha.IGetBranchRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.retail.v2alpha.IBranch, - protos.google.cloud.retail.v2alpha.IGetBranchRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.retail.v2alpha.IGetBranchRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.retail.v2alpha.IBranch, + protos.google.cloud.retail.v2alpha.IGetBranchRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IBranch, + protos.google.cloud.retail.v2alpha.IGetBranchRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getBranch request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.retail.v2alpha.IBranch, - protos.google.cloud.retail.v2alpha.IGetBranchRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.retail.v2alpha.IBranch, + | protos.google.cloud.retail.v2alpha.IGetBranchRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getBranch response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getBranch(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.retail.v2alpha.IBranch, - protos.google.cloud.retail.v2alpha.IGetBranchRequest|undefined, - {}|undefined - ]) => { - this._log.info('getBranch response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getBranch(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.retail.v2alpha.IBranch, + protos.google.cloud.retail.v2alpha.IGetBranchRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getBranch response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); @@ -580,7 +695,7 @@ export class BranchServiceClient { * @param {string} project * @returns {string} Resource name string. */ - alertConfigPath(project:string) { + alertConfigPath(project: string) { return this.pathTemplates.alertConfigPathTemplate.render({ project: project, }); @@ -594,7 +709,8 @@ export class BranchServiceClient { * @returns {string} A string representing the project. */ matchProjectFromAlertConfigName(alertConfigName: string) { - return this.pathTemplates.alertConfigPathTemplate.match(alertConfigName).project; + return this.pathTemplates.alertConfigPathTemplate.match(alertConfigName) + .project; } /** @@ -605,7 +721,7 @@ export class BranchServiceClient { * @param {string} catalog * @returns {string} Resource name string. */ - attributesConfigPath(project:string,location:string,catalog:string) { + attributesConfigPath(project: string, location: string, catalog: string) { return this.pathTemplates.attributesConfigPathTemplate.render({ project: project, location: location, @@ -621,7 +737,9 @@ export class BranchServiceClient { * @returns {string} A string representing the project. */ matchProjectFromAttributesConfigName(attributesConfigName: string) { - return this.pathTemplates.attributesConfigPathTemplate.match(attributesConfigName).project; + return this.pathTemplates.attributesConfigPathTemplate.match( + attributesConfigName, + ).project; } /** @@ -632,7 +750,9 @@ export class BranchServiceClient { * @returns {string} A string representing the location. */ matchLocationFromAttributesConfigName(attributesConfigName: string) { - return this.pathTemplates.attributesConfigPathTemplate.match(attributesConfigName).location; + return this.pathTemplates.attributesConfigPathTemplate.match( + attributesConfigName, + ).location; } /** @@ -643,7 +763,9 @@ export class BranchServiceClient { * @returns {string} A string representing the catalog. */ matchCatalogFromAttributesConfigName(attributesConfigName: string) { - return this.pathTemplates.attributesConfigPathTemplate.match(attributesConfigName).catalog; + return this.pathTemplates.attributesConfigPathTemplate.match( + attributesConfigName, + ).catalog; } /** @@ -655,7 +777,12 @@ export class BranchServiceClient { * @param {string} branch * @returns {string} Resource name string. */ - branchPath(project:string,location:string,catalog:string,branch:string) { + branchPath( + project: string, + location: string, + catalog: string, + branch: string, + ) { return this.pathTemplates.branchPathTemplate.render({ project: project, location: location, @@ -716,7 +843,7 @@ export class BranchServiceClient { * @param {string} catalog * @returns {string} Resource name string. */ - catalogPath(project:string,location:string,catalog:string) { + catalogPath(project: string, location: string, catalog: string) { return this.pathTemplates.catalogPathTemplate.render({ project: project, location: location, @@ -765,7 +892,7 @@ export class BranchServiceClient { * @param {string} catalog * @returns {string} Resource name string. */ - completionConfigPath(project:string,location:string,catalog:string) { + completionConfigPath(project: string, location: string, catalog: string) { return this.pathTemplates.completionConfigPathTemplate.render({ project: project, location: location, @@ -781,7 +908,9 @@ export class BranchServiceClient { * @returns {string} A string representing the project. */ matchProjectFromCompletionConfigName(completionConfigName: string) { - return this.pathTemplates.completionConfigPathTemplate.match(completionConfigName).project; + return this.pathTemplates.completionConfigPathTemplate.match( + completionConfigName, + ).project; } /** @@ -792,7 +921,9 @@ export class BranchServiceClient { * @returns {string} A string representing the location. */ matchLocationFromCompletionConfigName(completionConfigName: string) { - return this.pathTemplates.completionConfigPathTemplate.match(completionConfigName).location; + return this.pathTemplates.completionConfigPathTemplate.match( + completionConfigName, + ).location; } /** @@ -803,7 +934,9 @@ export class BranchServiceClient { * @returns {string} A string representing the catalog. */ matchCatalogFromCompletionConfigName(completionConfigName: string) { - return this.pathTemplates.completionConfigPathTemplate.match(completionConfigName).catalog; + return this.pathTemplates.completionConfigPathTemplate.match( + completionConfigName, + ).catalog; } /** @@ -815,7 +948,12 @@ export class BranchServiceClient { * @param {string} control * @returns {string} Resource name string. */ - controlPath(project:string,location:string,catalog:string,control:string) { + controlPath( + project: string, + location: string, + catalog: string, + control: string, + ) { return this.pathTemplates.controlPathTemplate.render({ project: project, location: location, @@ -874,7 +1012,7 @@ export class BranchServiceClient { * @param {string} project * @returns {string} Resource name string. */ - loggingConfigPath(project:string) { + loggingConfigPath(project: string) { return this.pathTemplates.loggingConfigPathTemplate.render({ project: project, }); @@ -888,7 +1026,8 @@ export class BranchServiceClient { * @returns {string} A string representing the project. */ matchProjectFromLoggingConfigName(loggingConfigName: string) { - return this.pathTemplates.loggingConfigPathTemplate.match(loggingConfigName).project; + return this.pathTemplates.loggingConfigPathTemplate.match(loggingConfigName) + .project; } /** @@ -900,7 +1039,12 @@ export class BranchServiceClient { * @param {string} merchant_center_account_link * @returns {string} Resource name string. */ - merchantCenterAccountLinkPath(project:string,location:string,catalog:string,merchantCenterAccountLink:string) { + merchantCenterAccountLinkPath( + project: string, + location: string, + catalog: string, + merchantCenterAccountLink: string, + ) { return this.pathTemplates.merchantCenterAccountLinkPathTemplate.render({ project: project, location: location, @@ -916,8 +1060,12 @@ export class BranchServiceClient { * A fully-qualified path representing MerchantCenterAccountLink resource. * @returns {string} A string representing the project. */ - matchProjectFromMerchantCenterAccountLinkName(merchantCenterAccountLinkName: string) { - return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match(merchantCenterAccountLinkName).project; + matchProjectFromMerchantCenterAccountLinkName( + merchantCenterAccountLinkName: string, + ) { + return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match( + merchantCenterAccountLinkName, + ).project; } /** @@ -927,8 +1075,12 @@ export class BranchServiceClient { * A fully-qualified path representing MerchantCenterAccountLink resource. * @returns {string} A string representing the location. */ - matchLocationFromMerchantCenterAccountLinkName(merchantCenterAccountLinkName: string) { - return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match(merchantCenterAccountLinkName).location; + matchLocationFromMerchantCenterAccountLinkName( + merchantCenterAccountLinkName: string, + ) { + return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match( + merchantCenterAccountLinkName, + ).location; } /** @@ -938,8 +1090,12 @@ export class BranchServiceClient { * A fully-qualified path representing MerchantCenterAccountLink resource. * @returns {string} A string representing the catalog. */ - matchCatalogFromMerchantCenterAccountLinkName(merchantCenterAccountLinkName: string) { - return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match(merchantCenterAccountLinkName).catalog; + matchCatalogFromMerchantCenterAccountLinkName( + merchantCenterAccountLinkName: string, + ) { + return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match( + merchantCenterAccountLinkName, + ).catalog; } /** @@ -949,8 +1105,12 @@ export class BranchServiceClient { * A fully-qualified path representing MerchantCenterAccountLink resource. * @returns {string} A string representing the merchant_center_account_link. */ - matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName(merchantCenterAccountLinkName: string) { - return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match(merchantCenterAccountLinkName).merchant_center_account_link; + matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName( + merchantCenterAccountLinkName: string, + ) { + return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match( + merchantCenterAccountLinkName, + ).merchant_center_account_link; } /** @@ -962,7 +1122,7 @@ export class BranchServiceClient { * @param {string} model * @returns {string} Resource name string. */ - modelPath(project:string,location:string,catalog:string,model:string) { + modelPath(project: string, location: string, catalog: string, model: string) { return this.pathTemplates.modelPathTemplate.render({ project: project, location: location, @@ -1025,7 +1185,13 @@ export class BranchServiceClient { * @param {string} product * @returns {string} Resource name string. */ - productPath(project:string,location:string,catalog:string,branch:string,product:string) { + productPath( + project: string, + location: string, + catalog: string, + branch: string, + product: string, + ) { return this.pathTemplates.productPathTemplate.render({ project: project, location: location, @@ -1096,7 +1262,7 @@ export class BranchServiceClient { * @param {string} project * @returns {string} Resource name string. */ - retailProjectPath(project:string) { + retailProjectPath(project: string) { return this.pathTemplates.retailProjectPathTemplate.render({ project: project, }); @@ -1110,7 +1276,8 @@ export class BranchServiceClient { * @returns {string} A string representing the project. */ matchProjectFromRetailProjectName(retailProjectName: string) { - return this.pathTemplates.retailProjectPathTemplate.match(retailProjectName).project; + return this.pathTemplates.retailProjectPathTemplate.match(retailProjectName) + .project; } /** @@ -1122,7 +1289,12 @@ export class BranchServiceClient { * @param {string} serving_config * @returns {string} Resource name string. */ - servingConfigPath(project:string,location:string,catalog:string,servingConfig:string) { + servingConfigPath( + project: string, + location: string, + catalog: string, + servingConfig: string, + ) { return this.pathTemplates.servingConfigPathTemplate.render({ project: project, location: location, @@ -1139,7 +1311,8 @@ export class BranchServiceClient { * @returns {string} A string representing the project. */ matchProjectFromServingConfigName(servingConfigName: string) { - return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName).project; + return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName) + .project; } /** @@ -1150,7 +1323,8 @@ export class BranchServiceClient { * @returns {string} A string representing the location. */ matchLocationFromServingConfigName(servingConfigName: string) { - return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName).location; + return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName) + .location; } /** @@ -1161,7 +1335,8 @@ export class BranchServiceClient { * @returns {string} A string representing the catalog. */ matchCatalogFromServingConfigName(servingConfigName: string) { - return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName).catalog; + return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName) + .catalog; } /** @@ -1172,7 +1347,8 @@ export class BranchServiceClient { * @returns {string} A string representing the serving_config. */ matchServingConfigFromServingConfigName(servingConfigName: string) { - return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName).serving_config; + return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName) + .serving_config; } /** @@ -1183,7 +1359,7 @@ export class BranchServiceClient { */ close(): Promise { if (this.branchServiceStub && !this._terminated) { - return this.branchServiceStub.then(stub => { + return this.branchServiceStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -1191,4 +1367,4 @@ export class BranchServiceClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/core/generator/gapic-generator-typescript/baselines/retail/src/v2alpha/catalog_service_client.ts.baseline b/core/generator/gapic-generator-typescript/baselines/retail/src/v2alpha/catalog_service_client.ts.baseline index e9df6a9d3547..4fd1bdb8509d 100644 --- a/core/generator/gapic-generator-typescript/baselines/retail/src/v2alpha/catalog_service_client.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/retail/src/v2alpha/catalog_service_client.ts.baseline @@ -18,11 +18,18 @@ /* global window */ import type * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions, PaginationCallback, GaxCall} from 'google-gax'; -import {Transform} from 'stream'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + PaginationCallback, + GaxCall, +} from 'google-gax'; +import { Transform } from 'stream'; import * as protos from '../../protos/protos'; import jsonProtos = require('../../protos/protos.json'); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; /** * Client JSON configuration object, loaded from @@ -44,7 +51,7 @@ export class CatalogServiceClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('retail'); @@ -57,9 +64,9 @@ export class CatalogServiceClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; - catalogServiceStub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; + catalogServiceStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of CatalogServiceClient. @@ -100,21 +107,42 @@ export class CatalogServiceClient { * const client = new CatalogServiceClient({fallback: true}, gax); * ``` */ - constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { // Ensure that options include all the required fields. const staticMembers = this.constructor as typeof CatalogServiceClient; - if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { - throw new Error('Please set either universe_domain or universeDomain, but not both.'); + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); } - const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; - this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; this._servicePath = 'retail.' + this._universeDomain; - const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; - const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. if (servicePath !== this._servicePath && !('scopes' in opts)) { @@ -136,7 +164,7 @@ export class CatalogServiceClient { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; @@ -150,10 +178,7 @@ export class CatalogServiceClient { } // Determine the client header string. - const clientHeader = [ - `gax/${this._gaxModule.version}`, - `gapic/${version}`, - ]; + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/${process.versions.node}`); } else { @@ -175,43 +200,43 @@ export class CatalogServiceClient { // Create useful helper objects for these. this.pathTemplates = { alertConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/alertConfig' + 'projects/{project}/alertConfig', ), attributesConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/attributesConfig' + 'projects/{project}/locations/{location}/catalogs/{catalog}/attributesConfig', ), branchPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}', ), catalogPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}' + 'projects/{project}/locations/{location}/catalogs/{catalog}', ), completionConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/completionConfig' + 'projects/{project}/locations/{location}/catalogs/{catalog}/completionConfig', ), controlPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/controls/{control}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/controls/{control}', ), locationPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}' + 'projects/{project}/locations/{location}', ), loggingConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/loggingConfig' + 'projects/{project}/loggingConfig', ), merchantCenterAccountLinkPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/merchantCenterAccountLinks/{merchant_center_account_link}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/merchantCenterAccountLinks/{merchant_center_account_link}', ), modelPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/models/{model}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/models/{model}', ), productPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}', ), retailProjectPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/retailProject' + 'projects/{project}/retailProject', ), servingConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/servingConfigs/{serving_config}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/servingConfigs/{serving_config}', ), }; @@ -219,14 +244,20 @@ export class CatalogServiceClient { // (e.g. 50 results at a time, with tokens to get subsequent // pages). Denote the keys used for pagination and results. this.descriptors.page = { - listCatalogs: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'catalogs') + listCatalogs: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'catalogs', + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.cloud.retail.v2alpha.CatalogService', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.cloud.retail.v2alpha.CatalogService', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + { 'x-goog-api-client': clientHeader.join(' ') }, + ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -257,37 +288,53 @@ export class CatalogServiceClient { // Put together the "service stub" for // google.cloud.retail.v2alpha.CatalogService. this.catalogServiceStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.cloud.retail.v2alpha.CatalogService') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.cloud.retail.v2alpha.CatalogService', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.cloud.retail.v2alpha.CatalogService, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts, + this._providedCustomServicePath, + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const catalogServiceStubMethods = - ['listCatalogs', 'updateCatalog', 'setDefaultBranch', 'getDefaultBranch', 'getCompletionConfig', 'updateCompletionConfig', 'getAttributesConfig', 'updateAttributesConfig', 'addCatalogAttribute', 'removeCatalogAttribute', 'batchRemoveCatalogAttributes', 'replaceCatalogAttribute']; + const catalogServiceStubMethods = [ + 'listCatalogs', + 'updateCatalog', + 'setDefaultBranch', + 'getDefaultBranch', + 'getCompletionConfig', + 'updateCompletionConfig', + 'getAttributesConfig', + 'updateAttributesConfig', + 'addCatalogAttribute', + 'removeCatalogAttribute', + 'batchRemoveCatalogAttributes', + 'replaceCatalogAttribute', + ]; for (const methodName of catalogServiceStubMethods) { const callPromise = this.catalogServiceStub.then( - stub => (...args: Array<{}>) => { - if (this._terminated) { - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error|null|undefined) => () => { + (stub) => + (...args: Array<{}>) => { + if (this._terminated) { + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { throw err; - }); + }, + ); - const descriptor = - this.descriptors.page[methodName] || - undefined; + const descriptor = this.descriptors.page[methodName] || undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -302,8 +349,14 @@ export class CatalogServiceClient { * @returns {string} The DNS address for this service. */ static get servicePath() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'retail.googleapis.com'; } @@ -314,8 +367,14 @@ export class CatalogServiceClient { * @returns {string} The DNS address for this service. */ static get apiEndpoint() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'retail.googleapis.com'; } @@ -346,9 +405,7 @@ export class CatalogServiceClient { * @returns {string[]} List of default scopes. */ static get scopes() { - return [ - 'https://www.googleapis.com/auth/cloud-platform' - ]; + return ['https://www.googleapis.com/auth/cloud-platform']; } getProjectId(): Promise; @@ -357,8 +414,9 @@ export class CatalogServiceClient { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId(callback?: Callback): - Promise|void { + getProjectId( + callback?: Callback, + ): Promise | void { if (callback) { this.auth.getProjectId(callback); return; @@ -369,1295 +427,1838 @@ export class CatalogServiceClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Updates the {@link protos.google.cloud.retail.v2alpha.Catalog|Catalog}s. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.cloud.retail.v2alpha.Catalog} request.catalog - * Required. The {@link protos.google.cloud.retail.v2alpha.Catalog|Catalog} to update. - * - * If the caller does not have permission to update the - * {@link protos.google.cloud.retail.v2alpha.Catalog|Catalog}, regardless of whether or - * not it exists, a PERMISSION_DENIED error is returned. - * - * If the {@link protos.google.cloud.retail.v2alpha.Catalog|Catalog} to update does not - * exist, a NOT_FOUND error is returned. - * @param {google.protobuf.FieldMask} request.updateMask - * Indicates which fields in the provided - * {@link protos.google.cloud.retail.v2alpha.Catalog|Catalog} to update. - * - * If an unsupported or unknown field is provided, an INVALID_ARGUMENT error - * is returned. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.Catalog|Catalog}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/catalog_service.update_catalog.js - * region_tag:retail_v2alpha_generated_CatalogService_UpdateCatalog_async - */ + /** + * Updates the {@link protos.google.cloud.retail.v2alpha.Catalog|Catalog}s. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.cloud.retail.v2alpha.Catalog} request.catalog + * Required. The {@link protos.google.cloud.retail.v2alpha.Catalog|Catalog} to update. + * + * If the caller does not have permission to update the + * {@link protos.google.cloud.retail.v2alpha.Catalog|Catalog}, regardless of whether or + * not it exists, a PERMISSION_DENIED error is returned. + * + * If the {@link protos.google.cloud.retail.v2alpha.Catalog|Catalog} to update does not + * exist, a NOT_FOUND error is returned. + * @param {google.protobuf.FieldMask} request.updateMask + * Indicates which fields in the provided + * {@link protos.google.cloud.retail.v2alpha.Catalog|Catalog} to update. + * + * If an unsupported or unknown field is provided, an INVALID_ARGUMENT error + * is returned. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.Catalog|Catalog}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/catalog_service.update_catalog.js + * region_tag:retail_v2alpha_generated_CatalogService_UpdateCatalog_async + */ updateCatalog( - request?: protos.google.cloud.retail.v2alpha.IUpdateCatalogRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.retail.v2alpha.ICatalog, - protos.google.cloud.retail.v2alpha.IUpdateCatalogRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.IUpdateCatalogRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.ICatalog, + protos.google.cloud.retail.v2alpha.IUpdateCatalogRequest | undefined, + {} | undefined, + ] + >; updateCatalog( - request: protos.google.cloud.retail.v2alpha.IUpdateCatalogRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.retail.v2alpha.ICatalog, - protos.google.cloud.retail.v2alpha.IUpdateCatalogRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IUpdateCatalogRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.retail.v2alpha.ICatalog, + | protos.google.cloud.retail.v2alpha.IUpdateCatalogRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateCatalog( - request: protos.google.cloud.retail.v2alpha.IUpdateCatalogRequest, - callback: Callback< - protos.google.cloud.retail.v2alpha.ICatalog, - protos.google.cloud.retail.v2alpha.IUpdateCatalogRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IUpdateCatalogRequest, + callback: Callback< + protos.google.cloud.retail.v2alpha.ICatalog, + | protos.google.cloud.retail.v2alpha.IUpdateCatalogRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateCatalog( - request?: protos.google.cloud.retail.v2alpha.IUpdateCatalogRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.cloud.retail.v2alpha.IUpdateCatalogRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.retail.v2alpha.ICatalog, - protos.google.cloud.retail.v2alpha.IUpdateCatalogRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.cloud.retail.v2alpha.ICatalog, - protos.google.cloud.retail.v2alpha.IUpdateCatalogRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.retail.v2alpha.ICatalog, - protos.google.cloud.retail.v2alpha.IUpdateCatalogRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.retail.v2alpha.IUpdateCatalogRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.retail.v2alpha.ICatalog, + | protos.google.cloud.retail.v2alpha.IUpdateCatalogRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.ICatalog, + protos.google.cloud.retail.v2alpha.IUpdateCatalogRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'catalog.name': request.catalog!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'catalog.name': request.catalog!.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateCatalog request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.retail.v2alpha.ICatalog, - protos.google.cloud.retail.v2alpha.IUpdateCatalogRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.retail.v2alpha.ICatalog, + | protos.google.cloud.retail.v2alpha.IUpdateCatalogRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateCatalog response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.updateCatalog(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.retail.v2alpha.ICatalog, - protos.google.cloud.retail.v2alpha.IUpdateCatalogRequest|undefined, - {}|undefined - ]) => { - this._log.info('updateCatalog response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateCatalog(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.retail.v2alpha.ICatalog, + protos.google.cloud.retail.v2alpha.IUpdateCatalogRequest | undefined, + {} | undefined, + ]) => { + this._log.info('updateCatalog response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Set a specified branch id as default branch. API methods such as - * {@link protos.google.cloud.retail.v2alpha.SearchService.Search|SearchService.Search}, - * {@link protos.google.cloud.retail.v2alpha.ProductService.GetProduct|ProductService.GetProduct}, - * {@link protos.google.cloud.retail.v2alpha.ProductService.ListProducts|ProductService.ListProducts} - * will treat requests using "default_branch" to the actual branch id set as - * default. - * - * For example, if `projects/* /locations/* /catalogs/* /branches/1` is set as - * default, setting - * {@link protos.google.cloud.retail.v2alpha.SearchRequest.branch|SearchRequest.branch} to - * `projects/* /locations/* /catalogs/* /branches/default_branch` is equivalent - * to setting - * {@link protos.google.cloud.retail.v2alpha.SearchRequest.branch|SearchRequest.branch} to - * `projects/* /locations/* /catalogs/* /branches/1`. - * - * Using multiple branches can be useful when developers would like - * to have a staging branch to test and verify for future usage. When it - * becomes ready, developers switch on the staging branch using this API - * while keeping using - * `projects/* /locations/* /catalogs/* /branches/default_branch` as - * {@link protos.google.cloud.retail.v2alpha.SearchRequest.branch|SearchRequest.branch} to - * route the traffic to this staging branch. - * - * CAUTION: If you have live predict/search traffic, switching the default - * branch could potentially cause outages if the ID space of the new branch - * is very different from the old one. - * - * More specifically: - * - * * PredictionService will only return product IDs from branch {newBranch}. - * * SearchService will only return product IDs from branch {newBranch} - * (if branch is not explicitly set). - * * UserEventService will only join events with products from branch - * {newBranch}. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.catalog - * Full resource name of the catalog, such as - * `projects/* /locations/global/catalogs/default_catalog`. - * @param {string} request.branchId - * The final component of the resource name of a branch. - * - * This field must be one of "0", "1" or "2". Otherwise, an INVALID_ARGUMENT - * error is returned. - * - * If there are no sufficient active products in the targeted branch and - * {@link protos.google.cloud.retail.v2alpha.SetDefaultBranchRequest.force|force} is not - * set, a FAILED_PRECONDITION error is returned. - * @param {string} request.note - * Some note on this request, this can be retrieved by - * {@link protos.google.cloud.retail.v2alpha.CatalogService.GetDefaultBranch|CatalogService.GetDefaultBranch} - * before next valid default branch set occurs. - * - * This field must be a UTF-8 encoded string with a length limit of 1,000 - * characters. Otherwise, an INVALID_ARGUMENT error is returned. - * @param {boolean} request.force - * If set to true, it permits switching to a branch with - * {@link protos.google.cloud.retail.v2alpha.SetDefaultBranchRequest.branch_id|branch_id} - * even if it has no sufficient active products. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/catalog_service.set_default_branch.js - * region_tag:retail_v2alpha_generated_CatalogService_SetDefaultBranch_async - */ + /** + * Set a specified branch id as default branch. API methods such as + * {@link protos.google.cloud.retail.v2alpha.SearchService.Search|SearchService.Search}, + * {@link protos.google.cloud.retail.v2alpha.ProductService.GetProduct|ProductService.GetProduct}, + * {@link protos.google.cloud.retail.v2alpha.ProductService.ListProducts|ProductService.ListProducts} + * will treat requests using "default_branch" to the actual branch id set as + * default. + * + * For example, if `projects/* /locations/* /catalogs/* /branches/1` is set as + * default, setting + * {@link protos.google.cloud.retail.v2alpha.SearchRequest.branch|SearchRequest.branch} to + * `projects/* /locations/* /catalogs/* /branches/default_branch` is equivalent + * to setting + * {@link protos.google.cloud.retail.v2alpha.SearchRequest.branch|SearchRequest.branch} to + * `projects/* /locations/* /catalogs/* /branches/1`. + * + * Using multiple branches can be useful when developers would like + * to have a staging branch to test and verify for future usage. When it + * becomes ready, developers switch on the staging branch using this API + * while keeping using + * `projects/* /locations/* /catalogs/* /branches/default_branch` as + * {@link protos.google.cloud.retail.v2alpha.SearchRequest.branch|SearchRequest.branch} to + * route the traffic to this staging branch. + * + * CAUTION: If you have live predict/search traffic, switching the default + * branch could potentially cause outages if the ID space of the new branch + * is very different from the old one. + * + * More specifically: + * + * * PredictionService will only return product IDs from branch {newBranch}. + * * SearchService will only return product IDs from branch {newBranch} + * (if branch is not explicitly set). + * * UserEventService will only join events with products from branch + * {newBranch}. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.catalog + * Full resource name of the catalog, such as + * `projects/* /locations/global/catalogs/default_catalog`. + * @param {string} request.branchId + * The final component of the resource name of a branch. + * + * This field must be one of "0", "1" or "2". Otherwise, an INVALID_ARGUMENT + * error is returned. + * + * If there are no sufficient active products in the targeted branch and + * {@link protos.google.cloud.retail.v2alpha.SetDefaultBranchRequest.force|force} is not + * set, a FAILED_PRECONDITION error is returned. + * @param {string} request.note + * Some note on this request, this can be retrieved by + * {@link protos.google.cloud.retail.v2alpha.CatalogService.GetDefaultBranch|CatalogService.GetDefaultBranch} + * before next valid default branch set occurs. + * + * This field must be a UTF-8 encoded string with a length limit of 1,000 + * characters. Otherwise, an INVALID_ARGUMENT error is returned. + * @param {boolean} request.force + * If set to true, it permits switching to a branch with + * {@link protos.google.cloud.retail.v2alpha.SetDefaultBranchRequest.branch_id|branch_id} + * even if it has no sufficient active products. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/catalog_service.set_default_branch.js + * region_tag:retail_v2alpha_generated_CatalogService_SetDefaultBranch_async + */ setDefaultBranch( - request?: protos.google.cloud.retail.v2alpha.ISetDefaultBranchRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.cloud.retail.v2alpha.ISetDefaultBranchRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.ISetDefaultBranchRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.cloud.retail.v2alpha.ISetDefaultBranchRequest | undefined, + {} | undefined, + ] + >; setDefaultBranch( - request: protos.google.cloud.retail.v2alpha.ISetDefaultBranchRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.cloud.retail.v2alpha.ISetDefaultBranchRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.ISetDefaultBranchRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.cloud.retail.v2alpha.ISetDefaultBranchRequest + | null + | undefined, + {} | null | undefined + >, + ): void; setDefaultBranch( - request: protos.google.cloud.retail.v2alpha.ISetDefaultBranchRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.cloud.retail.v2alpha.ISetDefaultBranchRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.ISetDefaultBranchRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.cloud.retail.v2alpha.ISetDefaultBranchRequest + | null + | undefined, + {} | null | undefined + >, + ): void; setDefaultBranch( - request?: protos.google.cloud.retail.v2alpha.ISetDefaultBranchRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.protobuf.IEmpty, - protos.google.cloud.retail.v2alpha.ISetDefaultBranchRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.retail.v2alpha.ISetDefaultBranchRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.cloud.retail.v2alpha.ISetDefaultBranchRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.cloud.retail.v2alpha.ISetDefaultBranchRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.retail.v2alpha.ISetDefaultBranchRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + | protos.google.cloud.retail.v2alpha.ISetDefaultBranchRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.cloud.retail.v2alpha.ISetDefaultBranchRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'catalog': request.catalog ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + catalog: request.catalog ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('setDefaultBranch request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.cloud.retail.v2alpha.ISetDefaultBranchRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.cloud.retail.v2alpha.ISetDefaultBranchRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('setDefaultBranch response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.setDefaultBranch(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.cloud.retail.v2alpha.ISetDefaultBranchRequest|undefined, - {}|undefined - ]) => { - this._log.info('setDefaultBranch response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .setDefaultBranch(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + ( + | protos.google.cloud.retail.v2alpha.ISetDefaultBranchRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('setDefaultBranch response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Get which branch is currently default branch set by - * {@link protos.google.cloud.retail.v2alpha.CatalogService.SetDefaultBranch|CatalogService.SetDefaultBranch} - * method under a specified parent catalog. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.catalog - * The parent catalog resource name, such as - * `projects/* /locations/global/catalogs/default_catalog`. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.GetDefaultBranchResponse|GetDefaultBranchResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/catalog_service.get_default_branch.js - * region_tag:retail_v2alpha_generated_CatalogService_GetDefaultBranch_async - */ + /** + * Get which branch is currently default branch set by + * {@link protos.google.cloud.retail.v2alpha.CatalogService.SetDefaultBranch|CatalogService.SetDefaultBranch} + * method under a specified parent catalog. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.catalog + * The parent catalog resource name, such as + * `projects/* /locations/global/catalogs/default_catalog`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.GetDefaultBranchResponse|GetDefaultBranchResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/catalog_service.get_default_branch.js + * region_tag:retail_v2alpha_generated_CatalogService_GetDefaultBranch_async + */ getDefaultBranch( - request?: protos.google.cloud.retail.v2alpha.IGetDefaultBranchRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.retail.v2alpha.IGetDefaultBranchResponse, - protos.google.cloud.retail.v2alpha.IGetDefaultBranchRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.IGetDefaultBranchRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IGetDefaultBranchResponse, + protos.google.cloud.retail.v2alpha.IGetDefaultBranchRequest | undefined, + {} | undefined, + ] + >; getDefaultBranch( - request: protos.google.cloud.retail.v2alpha.IGetDefaultBranchRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.retail.v2alpha.IGetDefaultBranchResponse, - protos.google.cloud.retail.v2alpha.IGetDefaultBranchRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IGetDefaultBranchRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.retail.v2alpha.IGetDefaultBranchResponse, + | protos.google.cloud.retail.v2alpha.IGetDefaultBranchRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getDefaultBranch( - request: protos.google.cloud.retail.v2alpha.IGetDefaultBranchRequest, - callback: Callback< - protos.google.cloud.retail.v2alpha.IGetDefaultBranchResponse, - protos.google.cloud.retail.v2alpha.IGetDefaultBranchRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IGetDefaultBranchRequest, + callback: Callback< + protos.google.cloud.retail.v2alpha.IGetDefaultBranchResponse, + | protos.google.cloud.retail.v2alpha.IGetDefaultBranchRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getDefaultBranch( - request?: protos.google.cloud.retail.v2alpha.IGetDefaultBranchRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.cloud.retail.v2alpha.IGetDefaultBranchRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.retail.v2alpha.IGetDefaultBranchResponse, - protos.google.cloud.retail.v2alpha.IGetDefaultBranchRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.cloud.retail.v2alpha.IGetDefaultBranchResponse, - protos.google.cloud.retail.v2alpha.IGetDefaultBranchRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.retail.v2alpha.IGetDefaultBranchResponse, - protos.google.cloud.retail.v2alpha.IGetDefaultBranchRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.retail.v2alpha.IGetDefaultBranchRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.retail.v2alpha.IGetDefaultBranchResponse, + | protos.google.cloud.retail.v2alpha.IGetDefaultBranchRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IGetDefaultBranchResponse, + protos.google.cloud.retail.v2alpha.IGetDefaultBranchRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'catalog': request.catalog ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + catalog: request.catalog ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getDefaultBranch request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.retail.v2alpha.IGetDefaultBranchResponse, - protos.google.cloud.retail.v2alpha.IGetDefaultBranchRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.retail.v2alpha.IGetDefaultBranchResponse, + | protos.google.cloud.retail.v2alpha.IGetDefaultBranchRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getDefaultBranch response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getDefaultBranch(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.retail.v2alpha.IGetDefaultBranchResponse, - protos.google.cloud.retail.v2alpha.IGetDefaultBranchRequest|undefined, - {}|undefined - ]) => { - this._log.info('getDefaultBranch response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getDefaultBranch(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.retail.v2alpha.IGetDefaultBranchResponse, + ( + | protos.google.cloud.retail.v2alpha.IGetDefaultBranchRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('getDefaultBranch response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Gets a {@link protos.google.cloud.retail.v2alpha.CompletionConfig|CompletionConfig}. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. Full CompletionConfig resource name. Format: - * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/completionConfig` - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.CompletionConfig|CompletionConfig}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/catalog_service.get_completion_config.js - * region_tag:retail_v2alpha_generated_CatalogService_GetCompletionConfig_async - */ + /** + * Gets a {@link protos.google.cloud.retail.v2alpha.CompletionConfig|CompletionConfig}. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Full CompletionConfig resource name. Format: + * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/completionConfig` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.CompletionConfig|CompletionConfig}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/catalog_service.get_completion_config.js + * region_tag:retail_v2alpha_generated_CatalogService_GetCompletionConfig_async + */ getCompletionConfig( - request?: protos.google.cloud.retail.v2alpha.IGetCompletionConfigRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.retail.v2alpha.ICompletionConfig, - protos.google.cloud.retail.v2alpha.IGetCompletionConfigRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.IGetCompletionConfigRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.ICompletionConfig, + ( + | protos.google.cloud.retail.v2alpha.IGetCompletionConfigRequest + | undefined + ), + {} | undefined, + ] + >; getCompletionConfig( - request: protos.google.cloud.retail.v2alpha.IGetCompletionConfigRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.retail.v2alpha.ICompletionConfig, - protos.google.cloud.retail.v2alpha.IGetCompletionConfigRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IGetCompletionConfigRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.retail.v2alpha.ICompletionConfig, + | protos.google.cloud.retail.v2alpha.IGetCompletionConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getCompletionConfig( - request: protos.google.cloud.retail.v2alpha.IGetCompletionConfigRequest, - callback: Callback< - protos.google.cloud.retail.v2alpha.ICompletionConfig, - protos.google.cloud.retail.v2alpha.IGetCompletionConfigRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IGetCompletionConfigRequest, + callback: Callback< + protos.google.cloud.retail.v2alpha.ICompletionConfig, + | protos.google.cloud.retail.v2alpha.IGetCompletionConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getCompletionConfig( - request?: protos.google.cloud.retail.v2alpha.IGetCompletionConfigRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.cloud.retail.v2alpha.IGetCompletionConfigRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.retail.v2alpha.ICompletionConfig, - protos.google.cloud.retail.v2alpha.IGetCompletionConfigRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.cloud.retail.v2alpha.ICompletionConfig, - protos.google.cloud.retail.v2alpha.IGetCompletionConfigRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.retail.v2alpha.ICompletionConfig, - protos.google.cloud.retail.v2alpha.IGetCompletionConfigRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.retail.v2alpha.IGetCompletionConfigRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.retail.v2alpha.ICompletionConfig, + | protos.google.cloud.retail.v2alpha.IGetCompletionConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.ICompletionConfig, + ( + | protos.google.cloud.retail.v2alpha.IGetCompletionConfigRequest + | undefined + ), + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getCompletionConfig request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.retail.v2alpha.ICompletionConfig, - protos.google.cloud.retail.v2alpha.IGetCompletionConfigRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.retail.v2alpha.ICompletionConfig, + | protos.google.cloud.retail.v2alpha.IGetCompletionConfigRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getCompletionConfig response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getCompletionConfig(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.retail.v2alpha.ICompletionConfig, - protos.google.cloud.retail.v2alpha.IGetCompletionConfigRequest|undefined, - {}|undefined - ]) => { - this._log.info('getCompletionConfig response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getCompletionConfig(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.retail.v2alpha.ICompletionConfig, + ( + | protos.google.cloud.retail.v2alpha.IGetCompletionConfigRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('getCompletionConfig response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Updates the - * {@link protos.google.cloud.retail.v2alpha.CompletionConfig|CompletionConfig}s. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.cloud.retail.v2alpha.CompletionConfig} request.completionConfig - * Required. The - * {@link protos.google.cloud.retail.v2alpha.CompletionConfig|CompletionConfig} to update. - * - * If the caller does not have permission to update the - * {@link protos.google.cloud.retail.v2alpha.CompletionConfig|CompletionConfig}, then a - * PERMISSION_DENIED error is returned. - * - * If the {@link protos.google.cloud.retail.v2alpha.CompletionConfig|CompletionConfig} to - * update does not exist, a NOT_FOUND error is returned. - * @param {google.protobuf.FieldMask} request.updateMask - * Indicates which fields in the provided - * {@link protos.google.cloud.retail.v2alpha.CompletionConfig|CompletionConfig} to update. - * The following are the only supported fields: - * - * * {@link protos.google.cloud.retail.v2alpha.CompletionConfig.matching_order|CompletionConfig.matching_order} - * * {@link protos.google.cloud.retail.v2alpha.CompletionConfig.max_suggestions|CompletionConfig.max_suggestions} - * * {@link protos.google.cloud.retail.v2alpha.CompletionConfig.min_prefix_length|CompletionConfig.min_prefix_length} - * * {@link protos.google.cloud.retail.v2alpha.CompletionConfig.auto_learning|CompletionConfig.auto_learning} - * - * If not set, all supported fields are updated. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.CompletionConfig|CompletionConfig}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/catalog_service.update_completion_config.js - * region_tag:retail_v2alpha_generated_CatalogService_UpdateCompletionConfig_async - */ + /** + * Updates the + * {@link protos.google.cloud.retail.v2alpha.CompletionConfig|CompletionConfig}s. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.cloud.retail.v2alpha.CompletionConfig} request.completionConfig + * Required. The + * {@link protos.google.cloud.retail.v2alpha.CompletionConfig|CompletionConfig} to update. + * + * If the caller does not have permission to update the + * {@link protos.google.cloud.retail.v2alpha.CompletionConfig|CompletionConfig}, then a + * PERMISSION_DENIED error is returned. + * + * If the {@link protos.google.cloud.retail.v2alpha.CompletionConfig|CompletionConfig} to + * update does not exist, a NOT_FOUND error is returned. + * @param {google.protobuf.FieldMask} request.updateMask + * Indicates which fields in the provided + * {@link protos.google.cloud.retail.v2alpha.CompletionConfig|CompletionConfig} to update. + * The following are the only supported fields: + * + * * {@link protos.google.cloud.retail.v2alpha.CompletionConfig.matching_order|CompletionConfig.matching_order} + * * {@link protos.google.cloud.retail.v2alpha.CompletionConfig.max_suggestions|CompletionConfig.max_suggestions} + * * {@link protos.google.cloud.retail.v2alpha.CompletionConfig.min_prefix_length|CompletionConfig.min_prefix_length} + * * {@link protos.google.cloud.retail.v2alpha.CompletionConfig.auto_learning|CompletionConfig.auto_learning} + * + * If not set, all supported fields are updated. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.CompletionConfig|CompletionConfig}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/catalog_service.update_completion_config.js + * region_tag:retail_v2alpha_generated_CatalogService_UpdateCompletionConfig_async + */ updateCompletionConfig( - request?: protos.google.cloud.retail.v2alpha.IUpdateCompletionConfigRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.retail.v2alpha.ICompletionConfig, - protos.google.cloud.retail.v2alpha.IUpdateCompletionConfigRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.IUpdateCompletionConfigRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.ICompletionConfig, + ( + | protos.google.cloud.retail.v2alpha.IUpdateCompletionConfigRequest + | undefined + ), + {} | undefined, + ] + >; updateCompletionConfig( - request: protos.google.cloud.retail.v2alpha.IUpdateCompletionConfigRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.retail.v2alpha.ICompletionConfig, - protos.google.cloud.retail.v2alpha.IUpdateCompletionConfigRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IUpdateCompletionConfigRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.retail.v2alpha.ICompletionConfig, + | protos.google.cloud.retail.v2alpha.IUpdateCompletionConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateCompletionConfig( - request: protos.google.cloud.retail.v2alpha.IUpdateCompletionConfigRequest, - callback: Callback< - protos.google.cloud.retail.v2alpha.ICompletionConfig, - protos.google.cloud.retail.v2alpha.IUpdateCompletionConfigRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IUpdateCompletionConfigRequest, + callback: Callback< + protos.google.cloud.retail.v2alpha.ICompletionConfig, + | protos.google.cloud.retail.v2alpha.IUpdateCompletionConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateCompletionConfig( - request?: protos.google.cloud.retail.v2alpha.IUpdateCompletionConfigRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.retail.v2alpha.ICompletionConfig, - protos.google.cloud.retail.v2alpha.IUpdateCompletionConfigRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.retail.v2alpha.IUpdateCompletionConfigRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.retail.v2alpha.ICompletionConfig, - protos.google.cloud.retail.v2alpha.IUpdateCompletionConfigRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.retail.v2alpha.ICompletionConfig, - protos.google.cloud.retail.v2alpha.IUpdateCompletionConfigRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.retail.v2alpha.IUpdateCompletionConfigRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.retail.v2alpha.ICompletionConfig, + | protos.google.cloud.retail.v2alpha.IUpdateCompletionConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.ICompletionConfig, + ( + | protos.google.cloud.retail.v2alpha.IUpdateCompletionConfigRequest + | undefined + ), + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'completion_config.name': request.completionConfig!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'completion_config.name': request.completionConfig!.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateCompletionConfig request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.retail.v2alpha.ICompletionConfig, - protos.google.cloud.retail.v2alpha.IUpdateCompletionConfigRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.retail.v2alpha.ICompletionConfig, + | protos.google.cloud.retail.v2alpha.IUpdateCompletionConfigRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateCompletionConfig response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.updateCompletionConfig(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.retail.v2alpha.ICompletionConfig, - protos.google.cloud.retail.v2alpha.IUpdateCompletionConfigRequest|undefined, - {}|undefined - ]) => { - this._log.info('updateCompletionConfig response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateCompletionConfig(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.retail.v2alpha.ICompletionConfig, + ( + | protos.google.cloud.retail.v2alpha.IUpdateCompletionConfigRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('updateCompletionConfig response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Gets an {@link protos.google.cloud.retail.v2alpha.AttributesConfig|AttributesConfig}. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. Full AttributesConfig resource name. Format: - * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/attributesConfig` - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.AttributesConfig|AttributesConfig}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/catalog_service.get_attributes_config.js - * region_tag:retail_v2alpha_generated_CatalogService_GetAttributesConfig_async - */ + /** + * Gets an {@link protos.google.cloud.retail.v2alpha.AttributesConfig|AttributesConfig}. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Full AttributesConfig resource name. Format: + * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/attributesConfig` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.AttributesConfig|AttributesConfig}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/catalog_service.get_attributes_config.js + * region_tag:retail_v2alpha_generated_CatalogService_GetAttributesConfig_async + */ getAttributesConfig( - request?: protos.google.cloud.retail.v2alpha.IGetAttributesConfigRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.retail.v2alpha.IAttributesConfig, - protos.google.cloud.retail.v2alpha.IGetAttributesConfigRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.IGetAttributesConfigRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IAttributesConfig, + ( + | protos.google.cloud.retail.v2alpha.IGetAttributesConfigRequest + | undefined + ), + {} | undefined, + ] + >; getAttributesConfig( - request: protos.google.cloud.retail.v2alpha.IGetAttributesConfigRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.retail.v2alpha.IAttributesConfig, - protos.google.cloud.retail.v2alpha.IGetAttributesConfigRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IGetAttributesConfigRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.retail.v2alpha.IAttributesConfig, + | protos.google.cloud.retail.v2alpha.IGetAttributesConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getAttributesConfig( - request: protos.google.cloud.retail.v2alpha.IGetAttributesConfigRequest, - callback: Callback< - protos.google.cloud.retail.v2alpha.IAttributesConfig, - protos.google.cloud.retail.v2alpha.IGetAttributesConfigRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IGetAttributesConfigRequest, + callback: Callback< + protos.google.cloud.retail.v2alpha.IAttributesConfig, + | protos.google.cloud.retail.v2alpha.IGetAttributesConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getAttributesConfig( - request?: protos.google.cloud.retail.v2alpha.IGetAttributesConfigRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.cloud.retail.v2alpha.IGetAttributesConfigRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.retail.v2alpha.IAttributesConfig, - protos.google.cloud.retail.v2alpha.IGetAttributesConfigRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.cloud.retail.v2alpha.IAttributesConfig, - protos.google.cloud.retail.v2alpha.IGetAttributesConfigRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.retail.v2alpha.IAttributesConfig, - protos.google.cloud.retail.v2alpha.IGetAttributesConfigRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.retail.v2alpha.IGetAttributesConfigRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.retail.v2alpha.IAttributesConfig, + | protos.google.cloud.retail.v2alpha.IGetAttributesConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IAttributesConfig, + ( + | protos.google.cloud.retail.v2alpha.IGetAttributesConfigRequest + | undefined + ), + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getAttributesConfig request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.retail.v2alpha.IAttributesConfig, - protos.google.cloud.retail.v2alpha.IGetAttributesConfigRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.retail.v2alpha.IAttributesConfig, + | protos.google.cloud.retail.v2alpha.IGetAttributesConfigRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getAttributesConfig response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getAttributesConfig(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.retail.v2alpha.IAttributesConfig, - protos.google.cloud.retail.v2alpha.IGetAttributesConfigRequest|undefined, - {}|undefined - ]) => { - this._log.info('getAttributesConfig response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getAttributesConfig(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.retail.v2alpha.IAttributesConfig, + ( + | protos.google.cloud.retail.v2alpha.IGetAttributesConfigRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('getAttributesConfig response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Updates the - * {@link protos.google.cloud.retail.v2alpha.AttributesConfig|AttributesConfig}. - * - * The catalog attributes in the request will be updated in the catalog, or - * inserted if they do not exist. Existing catalog attributes not included in - * the request will remain unchanged. Attributes that are assigned to - * products, but do not exist at the catalog level, are always included in the - * response. The product attribute is assigned default values for missing - * catalog attribute fields, e.g., searchable and dynamic facetable options. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.cloud.retail.v2alpha.AttributesConfig} request.attributesConfig - * Required. The - * {@link protos.google.cloud.retail.v2alpha.AttributesConfig|AttributesConfig} to update. - * @param {google.protobuf.FieldMask} request.updateMask - * Indicates which fields in the provided - * {@link protos.google.cloud.retail.v2alpha.AttributesConfig|AttributesConfig} to update. - * The following is the only supported field: - * - * * {@link protos.google.cloud.retail.v2alpha.AttributesConfig.catalog_attributes|AttributesConfig.catalog_attributes} - * - * If not set, all supported fields are updated. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.AttributesConfig|AttributesConfig}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/catalog_service.update_attributes_config.js - * region_tag:retail_v2alpha_generated_CatalogService_UpdateAttributesConfig_async - */ + /** + * Updates the + * {@link protos.google.cloud.retail.v2alpha.AttributesConfig|AttributesConfig}. + * + * The catalog attributes in the request will be updated in the catalog, or + * inserted if they do not exist. Existing catalog attributes not included in + * the request will remain unchanged. Attributes that are assigned to + * products, but do not exist at the catalog level, are always included in the + * response. The product attribute is assigned default values for missing + * catalog attribute fields, e.g., searchable and dynamic facetable options. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.cloud.retail.v2alpha.AttributesConfig} request.attributesConfig + * Required. The + * {@link protos.google.cloud.retail.v2alpha.AttributesConfig|AttributesConfig} to update. + * @param {google.protobuf.FieldMask} request.updateMask + * Indicates which fields in the provided + * {@link protos.google.cloud.retail.v2alpha.AttributesConfig|AttributesConfig} to update. + * The following is the only supported field: + * + * * {@link protos.google.cloud.retail.v2alpha.AttributesConfig.catalog_attributes|AttributesConfig.catalog_attributes} + * + * If not set, all supported fields are updated. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.AttributesConfig|AttributesConfig}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/catalog_service.update_attributes_config.js + * region_tag:retail_v2alpha_generated_CatalogService_UpdateAttributesConfig_async + */ updateAttributesConfig( - request?: protos.google.cloud.retail.v2alpha.IUpdateAttributesConfigRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.retail.v2alpha.IAttributesConfig, - protos.google.cloud.retail.v2alpha.IUpdateAttributesConfigRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.IUpdateAttributesConfigRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IAttributesConfig, + ( + | protos.google.cloud.retail.v2alpha.IUpdateAttributesConfigRequest + | undefined + ), + {} | undefined, + ] + >; updateAttributesConfig( - request: protos.google.cloud.retail.v2alpha.IUpdateAttributesConfigRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.retail.v2alpha.IAttributesConfig, - protos.google.cloud.retail.v2alpha.IUpdateAttributesConfigRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IUpdateAttributesConfigRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.retail.v2alpha.IAttributesConfig, + | protos.google.cloud.retail.v2alpha.IUpdateAttributesConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateAttributesConfig( - request: protos.google.cloud.retail.v2alpha.IUpdateAttributesConfigRequest, - callback: Callback< - protos.google.cloud.retail.v2alpha.IAttributesConfig, - protos.google.cloud.retail.v2alpha.IUpdateAttributesConfigRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IUpdateAttributesConfigRequest, + callback: Callback< + protos.google.cloud.retail.v2alpha.IAttributesConfig, + | protos.google.cloud.retail.v2alpha.IUpdateAttributesConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateAttributesConfig( - request?: protos.google.cloud.retail.v2alpha.IUpdateAttributesConfigRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.cloud.retail.v2alpha.IUpdateAttributesConfigRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.retail.v2alpha.IAttributesConfig, - protos.google.cloud.retail.v2alpha.IUpdateAttributesConfigRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.cloud.retail.v2alpha.IAttributesConfig, - protos.google.cloud.retail.v2alpha.IUpdateAttributesConfigRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.retail.v2alpha.IAttributesConfig, - protos.google.cloud.retail.v2alpha.IUpdateAttributesConfigRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.retail.v2alpha.IUpdateAttributesConfigRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.retail.v2alpha.IAttributesConfig, + | protos.google.cloud.retail.v2alpha.IUpdateAttributesConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IAttributesConfig, + ( + | protos.google.cloud.retail.v2alpha.IUpdateAttributesConfigRequest + | undefined + ), + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'attributes_config.name': request.attributesConfig!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'attributes_config.name': request.attributesConfig!.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateAttributesConfig request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.retail.v2alpha.IAttributesConfig, - protos.google.cloud.retail.v2alpha.IUpdateAttributesConfigRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.retail.v2alpha.IAttributesConfig, + | protos.google.cloud.retail.v2alpha.IUpdateAttributesConfigRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateAttributesConfig response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.updateAttributesConfig(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.retail.v2alpha.IAttributesConfig, - protos.google.cloud.retail.v2alpha.IUpdateAttributesConfigRequest|undefined, - {}|undefined - ]) => { - this._log.info('updateAttributesConfig response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateAttributesConfig(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.retail.v2alpha.IAttributesConfig, + ( + | protos.google.cloud.retail.v2alpha.IUpdateAttributesConfigRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('updateAttributesConfig response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Adds the specified - * {@link protos.google.cloud.retail.v2alpha.CatalogAttribute|CatalogAttribute} to the - * {@link protos.google.cloud.retail.v2alpha.AttributesConfig|AttributesConfig}. - * - * If the {@link protos.google.cloud.retail.v2alpha.CatalogAttribute|CatalogAttribute} to - * add already exists, an ALREADY_EXISTS error is returned. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.attributesConfig - * Required. Full AttributesConfig resource name. Format: - * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/attributesConfig` - * @param {google.cloud.retail.v2alpha.CatalogAttribute} request.catalogAttribute - * Required. The - * {@link protos.google.cloud.retail.v2alpha.CatalogAttribute|CatalogAttribute} to add. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.AttributesConfig|AttributesConfig}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/catalog_service.add_catalog_attribute.js - * region_tag:retail_v2alpha_generated_CatalogService_AddCatalogAttribute_async - */ + /** + * Adds the specified + * {@link protos.google.cloud.retail.v2alpha.CatalogAttribute|CatalogAttribute} to the + * {@link protos.google.cloud.retail.v2alpha.AttributesConfig|AttributesConfig}. + * + * If the {@link protos.google.cloud.retail.v2alpha.CatalogAttribute|CatalogAttribute} to + * add already exists, an ALREADY_EXISTS error is returned. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.attributesConfig + * Required. Full AttributesConfig resource name. Format: + * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/attributesConfig` + * @param {google.cloud.retail.v2alpha.CatalogAttribute} request.catalogAttribute + * Required. The + * {@link protos.google.cloud.retail.v2alpha.CatalogAttribute|CatalogAttribute} to add. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.AttributesConfig|AttributesConfig}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/catalog_service.add_catalog_attribute.js + * region_tag:retail_v2alpha_generated_CatalogService_AddCatalogAttribute_async + */ addCatalogAttribute( - request?: protos.google.cloud.retail.v2alpha.IAddCatalogAttributeRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.retail.v2alpha.IAttributesConfig, - protos.google.cloud.retail.v2alpha.IAddCatalogAttributeRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.IAddCatalogAttributeRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IAttributesConfig, + ( + | protos.google.cloud.retail.v2alpha.IAddCatalogAttributeRequest + | undefined + ), + {} | undefined, + ] + >; addCatalogAttribute( - request: protos.google.cloud.retail.v2alpha.IAddCatalogAttributeRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.retail.v2alpha.IAttributesConfig, - protos.google.cloud.retail.v2alpha.IAddCatalogAttributeRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IAddCatalogAttributeRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.retail.v2alpha.IAttributesConfig, + | protos.google.cloud.retail.v2alpha.IAddCatalogAttributeRequest + | null + | undefined, + {} | null | undefined + >, + ): void; addCatalogAttribute( - request: protos.google.cloud.retail.v2alpha.IAddCatalogAttributeRequest, - callback: Callback< - protos.google.cloud.retail.v2alpha.IAttributesConfig, - protos.google.cloud.retail.v2alpha.IAddCatalogAttributeRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IAddCatalogAttributeRequest, + callback: Callback< + protos.google.cloud.retail.v2alpha.IAttributesConfig, + | protos.google.cloud.retail.v2alpha.IAddCatalogAttributeRequest + | null + | undefined, + {} | null | undefined + >, + ): void; addCatalogAttribute( - request?: protos.google.cloud.retail.v2alpha.IAddCatalogAttributeRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.cloud.retail.v2alpha.IAddCatalogAttributeRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.retail.v2alpha.IAttributesConfig, - protos.google.cloud.retail.v2alpha.IAddCatalogAttributeRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.cloud.retail.v2alpha.IAttributesConfig, - protos.google.cloud.retail.v2alpha.IAddCatalogAttributeRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.retail.v2alpha.IAttributesConfig, - protos.google.cloud.retail.v2alpha.IAddCatalogAttributeRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.retail.v2alpha.IAddCatalogAttributeRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.retail.v2alpha.IAttributesConfig, + | protos.google.cloud.retail.v2alpha.IAddCatalogAttributeRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IAttributesConfig, + ( + | protos.google.cloud.retail.v2alpha.IAddCatalogAttributeRequest + | undefined + ), + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'attributes_config': request.attributesConfig ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + attributes_config: request.attributesConfig ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('addCatalogAttribute request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.retail.v2alpha.IAttributesConfig, - protos.google.cloud.retail.v2alpha.IAddCatalogAttributeRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.retail.v2alpha.IAttributesConfig, + | protos.google.cloud.retail.v2alpha.IAddCatalogAttributeRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('addCatalogAttribute response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.addCatalogAttribute(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.retail.v2alpha.IAttributesConfig, - protos.google.cloud.retail.v2alpha.IAddCatalogAttributeRequest|undefined, - {}|undefined - ]) => { - this._log.info('addCatalogAttribute response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .addCatalogAttribute(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.retail.v2alpha.IAttributesConfig, + ( + | protos.google.cloud.retail.v2alpha.IAddCatalogAttributeRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('addCatalogAttribute response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Removes the specified - * {@link protos.google.cloud.retail.v2alpha.CatalogAttribute|CatalogAttribute} from the - * {@link protos.google.cloud.retail.v2alpha.AttributesConfig|AttributesConfig}. - * - * If the {@link protos.google.cloud.retail.v2alpha.CatalogAttribute|CatalogAttribute} to - * remove does not exist, a NOT_FOUND error is returned. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.attributesConfig - * Required. Full AttributesConfig resource name. Format: - * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/attributesConfig` - * @param {string} request.key - * Required. The attribute name key of the - * {@link protos.google.cloud.retail.v2alpha.CatalogAttribute|CatalogAttribute} to remove. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.AttributesConfig|AttributesConfig}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/catalog_service.remove_catalog_attribute.js - * region_tag:retail_v2alpha_generated_CatalogService_RemoveCatalogAttribute_async - */ + /** + * Removes the specified + * {@link protos.google.cloud.retail.v2alpha.CatalogAttribute|CatalogAttribute} from the + * {@link protos.google.cloud.retail.v2alpha.AttributesConfig|AttributesConfig}. + * + * If the {@link protos.google.cloud.retail.v2alpha.CatalogAttribute|CatalogAttribute} to + * remove does not exist, a NOT_FOUND error is returned. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.attributesConfig + * Required. Full AttributesConfig resource name. Format: + * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/attributesConfig` + * @param {string} request.key + * Required. The attribute name key of the + * {@link protos.google.cloud.retail.v2alpha.CatalogAttribute|CatalogAttribute} to remove. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.AttributesConfig|AttributesConfig}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/catalog_service.remove_catalog_attribute.js + * region_tag:retail_v2alpha_generated_CatalogService_RemoveCatalogAttribute_async + */ removeCatalogAttribute( - request?: protos.google.cloud.retail.v2alpha.IRemoveCatalogAttributeRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.retail.v2alpha.IAttributesConfig, - protos.google.cloud.retail.v2alpha.IRemoveCatalogAttributeRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.IRemoveCatalogAttributeRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IAttributesConfig, + ( + | protos.google.cloud.retail.v2alpha.IRemoveCatalogAttributeRequest + | undefined + ), + {} | undefined, + ] + >; removeCatalogAttribute( - request: protos.google.cloud.retail.v2alpha.IRemoveCatalogAttributeRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.retail.v2alpha.IAttributesConfig, - protos.google.cloud.retail.v2alpha.IRemoveCatalogAttributeRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IRemoveCatalogAttributeRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.retail.v2alpha.IAttributesConfig, + | protos.google.cloud.retail.v2alpha.IRemoveCatalogAttributeRequest + | null + | undefined, + {} | null | undefined + >, + ): void; removeCatalogAttribute( - request: protos.google.cloud.retail.v2alpha.IRemoveCatalogAttributeRequest, - callback: Callback< - protos.google.cloud.retail.v2alpha.IAttributesConfig, - protos.google.cloud.retail.v2alpha.IRemoveCatalogAttributeRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IRemoveCatalogAttributeRequest, + callback: Callback< + protos.google.cloud.retail.v2alpha.IAttributesConfig, + | protos.google.cloud.retail.v2alpha.IRemoveCatalogAttributeRequest + | null + | undefined, + {} | null | undefined + >, + ): void; removeCatalogAttribute( - request?: protos.google.cloud.retail.v2alpha.IRemoveCatalogAttributeRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.cloud.retail.v2alpha.IRemoveCatalogAttributeRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.retail.v2alpha.IAttributesConfig, - protos.google.cloud.retail.v2alpha.IRemoveCatalogAttributeRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.cloud.retail.v2alpha.IAttributesConfig, - protos.google.cloud.retail.v2alpha.IRemoveCatalogAttributeRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.retail.v2alpha.IAttributesConfig, - protos.google.cloud.retail.v2alpha.IRemoveCatalogAttributeRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.retail.v2alpha.IRemoveCatalogAttributeRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.retail.v2alpha.IAttributesConfig, + | protos.google.cloud.retail.v2alpha.IRemoveCatalogAttributeRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IAttributesConfig, + ( + | protos.google.cloud.retail.v2alpha.IRemoveCatalogAttributeRequest + | undefined + ), + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'attributes_config': request.attributesConfig ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + attributes_config: request.attributesConfig ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('removeCatalogAttribute request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.retail.v2alpha.IAttributesConfig, - protos.google.cloud.retail.v2alpha.IRemoveCatalogAttributeRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.retail.v2alpha.IAttributesConfig, + | protos.google.cloud.retail.v2alpha.IRemoveCatalogAttributeRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('removeCatalogAttribute response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.removeCatalogAttribute(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.retail.v2alpha.IAttributesConfig, - protos.google.cloud.retail.v2alpha.IRemoveCatalogAttributeRequest|undefined, - {}|undefined - ]) => { - this._log.info('removeCatalogAttribute response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .removeCatalogAttribute(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.retail.v2alpha.IAttributesConfig, + ( + | protos.google.cloud.retail.v2alpha.IRemoveCatalogAttributeRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('removeCatalogAttribute response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Removes all specified - * {@link protos.google.cloud.retail.v2alpha.CatalogAttribute|CatalogAttribute}s from the - * {@link protos.google.cloud.retail.v2alpha.AttributesConfig|AttributesConfig}. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.attributesConfig - * Required. The attributes config resource shared by all catalog attributes - * being deleted. Format: - * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/attributesConfig` - * @param {string[]} request.attributeKeys - * Required. The attribute name keys of the - * {@link protos.google.cloud.retail.v2alpha.CatalogAttribute|CatalogAttribute}s to - * delete. A maximum of 1000 catalog attributes can be deleted in a batch. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.BatchRemoveCatalogAttributesResponse|BatchRemoveCatalogAttributesResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/catalog_service.batch_remove_catalog_attributes.js - * region_tag:retail_v2alpha_generated_CatalogService_BatchRemoveCatalogAttributes_async - */ + /** + * Removes all specified + * {@link protos.google.cloud.retail.v2alpha.CatalogAttribute|CatalogAttribute}s from the + * {@link protos.google.cloud.retail.v2alpha.AttributesConfig|AttributesConfig}. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.attributesConfig + * Required. The attributes config resource shared by all catalog attributes + * being deleted. Format: + * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/attributesConfig` + * @param {string[]} request.attributeKeys + * Required. The attribute name keys of the + * {@link protos.google.cloud.retail.v2alpha.CatalogAttribute|CatalogAttribute}s to + * delete. A maximum of 1000 catalog attributes can be deleted in a batch. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.BatchRemoveCatalogAttributesResponse|BatchRemoveCatalogAttributesResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/catalog_service.batch_remove_catalog_attributes.js + * region_tag:retail_v2alpha_generated_CatalogService_BatchRemoveCatalogAttributes_async + */ batchRemoveCatalogAttributes( - request?: protos.google.cloud.retail.v2alpha.IBatchRemoveCatalogAttributesRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.retail.v2alpha.IBatchRemoveCatalogAttributesResponse, - protos.google.cloud.retail.v2alpha.IBatchRemoveCatalogAttributesRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.IBatchRemoveCatalogAttributesRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IBatchRemoveCatalogAttributesResponse, + ( + | protos.google.cloud.retail.v2alpha.IBatchRemoveCatalogAttributesRequest + | undefined + ), + {} | undefined, + ] + >; batchRemoveCatalogAttributes( - request: protos.google.cloud.retail.v2alpha.IBatchRemoveCatalogAttributesRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.retail.v2alpha.IBatchRemoveCatalogAttributesResponse, - protos.google.cloud.retail.v2alpha.IBatchRemoveCatalogAttributesRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IBatchRemoveCatalogAttributesRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.retail.v2alpha.IBatchRemoveCatalogAttributesResponse, + | protos.google.cloud.retail.v2alpha.IBatchRemoveCatalogAttributesRequest + | null + | undefined, + {} | null | undefined + >, + ): void; batchRemoveCatalogAttributes( - request: protos.google.cloud.retail.v2alpha.IBatchRemoveCatalogAttributesRequest, - callback: Callback< - protos.google.cloud.retail.v2alpha.IBatchRemoveCatalogAttributesResponse, - protos.google.cloud.retail.v2alpha.IBatchRemoveCatalogAttributesRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IBatchRemoveCatalogAttributesRequest, + callback: Callback< + protos.google.cloud.retail.v2alpha.IBatchRemoveCatalogAttributesResponse, + | protos.google.cloud.retail.v2alpha.IBatchRemoveCatalogAttributesRequest + | null + | undefined, + {} | null | undefined + >, + ): void; batchRemoveCatalogAttributes( - request?: protos.google.cloud.retail.v2alpha.IBatchRemoveCatalogAttributesRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.cloud.retail.v2alpha.IBatchRemoveCatalogAttributesRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.retail.v2alpha.IBatchRemoveCatalogAttributesResponse, - protos.google.cloud.retail.v2alpha.IBatchRemoveCatalogAttributesRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.cloud.retail.v2alpha.IBatchRemoveCatalogAttributesResponse, - protos.google.cloud.retail.v2alpha.IBatchRemoveCatalogAttributesRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.retail.v2alpha.IBatchRemoveCatalogAttributesResponse, - protos.google.cloud.retail.v2alpha.IBatchRemoveCatalogAttributesRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.retail.v2alpha.IBatchRemoveCatalogAttributesRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.retail.v2alpha.IBatchRemoveCatalogAttributesResponse, + | protos.google.cloud.retail.v2alpha.IBatchRemoveCatalogAttributesRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IBatchRemoveCatalogAttributesResponse, + ( + | protos.google.cloud.retail.v2alpha.IBatchRemoveCatalogAttributesRequest + | undefined + ), + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'attributes_config': request.attributesConfig ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + attributes_config: request.attributesConfig ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('batchRemoveCatalogAttributes request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.retail.v2alpha.IBatchRemoveCatalogAttributesResponse, - protos.google.cloud.retail.v2alpha.IBatchRemoveCatalogAttributesRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.retail.v2alpha.IBatchRemoveCatalogAttributesResponse, + | protos.google.cloud.retail.v2alpha.IBatchRemoveCatalogAttributesRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('batchRemoveCatalogAttributes response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.batchRemoveCatalogAttributes(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.retail.v2alpha.IBatchRemoveCatalogAttributesResponse, - protos.google.cloud.retail.v2alpha.IBatchRemoveCatalogAttributesRequest|undefined, - {}|undefined - ]) => { - this._log.info('batchRemoveCatalogAttributes response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .batchRemoveCatalogAttributes(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.retail.v2alpha.IBatchRemoveCatalogAttributesResponse, + ( + | protos.google.cloud.retail.v2alpha.IBatchRemoveCatalogAttributesRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('batchRemoveCatalogAttributes response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Replaces the specified - * {@link protos.google.cloud.retail.v2alpha.CatalogAttribute|CatalogAttribute} in the - * {@link protos.google.cloud.retail.v2alpha.AttributesConfig|AttributesConfig} by - * updating the catalog attribute with the same - * {@link protos.google.cloud.retail.v2alpha.CatalogAttribute.key|CatalogAttribute.key}. - * - * If the {@link protos.google.cloud.retail.v2alpha.CatalogAttribute|CatalogAttribute} to - * replace does not exist, a NOT_FOUND error is returned. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.attributesConfig - * Required. Full AttributesConfig resource name. Format: - * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/attributesConfig` - * @param {google.cloud.retail.v2alpha.CatalogAttribute} request.catalogAttribute - * Required. The updated - * {@link protos.google.cloud.retail.v2alpha.CatalogAttribute|CatalogAttribute}. - * @param {google.protobuf.FieldMask} request.updateMask - * Indicates which fields in the provided - * {@link protos.google.cloud.retail.v2alpha.CatalogAttribute|CatalogAttribute} to update. - * The following are NOT supported: - * - * * {@link protos.google.cloud.retail.v2alpha.CatalogAttribute.key|CatalogAttribute.key} - * - * If not set, all supported fields are updated. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.AttributesConfig|AttributesConfig}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/catalog_service.replace_catalog_attribute.js - * region_tag:retail_v2alpha_generated_CatalogService_ReplaceCatalogAttribute_async - */ + /** + * Replaces the specified + * {@link protos.google.cloud.retail.v2alpha.CatalogAttribute|CatalogAttribute} in the + * {@link protos.google.cloud.retail.v2alpha.AttributesConfig|AttributesConfig} by + * updating the catalog attribute with the same + * {@link protos.google.cloud.retail.v2alpha.CatalogAttribute.key|CatalogAttribute.key}. + * + * If the {@link protos.google.cloud.retail.v2alpha.CatalogAttribute|CatalogAttribute} to + * replace does not exist, a NOT_FOUND error is returned. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.attributesConfig + * Required. Full AttributesConfig resource name. Format: + * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/attributesConfig` + * @param {google.cloud.retail.v2alpha.CatalogAttribute} request.catalogAttribute + * Required. The updated + * {@link protos.google.cloud.retail.v2alpha.CatalogAttribute|CatalogAttribute}. + * @param {google.protobuf.FieldMask} request.updateMask + * Indicates which fields in the provided + * {@link protos.google.cloud.retail.v2alpha.CatalogAttribute|CatalogAttribute} to update. + * The following are NOT supported: + * + * * {@link protos.google.cloud.retail.v2alpha.CatalogAttribute.key|CatalogAttribute.key} + * + * If not set, all supported fields are updated. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.AttributesConfig|AttributesConfig}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/catalog_service.replace_catalog_attribute.js + * region_tag:retail_v2alpha_generated_CatalogService_ReplaceCatalogAttribute_async + */ replaceCatalogAttribute( - request?: protos.google.cloud.retail.v2alpha.IReplaceCatalogAttributeRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.retail.v2alpha.IAttributesConfig, - protos.google.cloud.retail.v2alpha.IReplaceCatalogAttributeRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.IReplaceCatalogAttributeRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IAttributesConfig, + ( + | protos.google.cloud.retail.v2alpha.IReplaceCatalogAttributeRequest + | undefined + ), + {} | undefined, + ] + >; replaceCatalogAttribute( - request: protos.google.cloud.retail.v2alpha.IReplaceCatalogAttributeRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.retail.v2alpha.IAttributesConfig, - protos.google.cloud.retail.v2alpha.IReplaceCatalogAttributeRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IReplaceCatalogAttributeRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.retail.v2alpha.IAttributesConfig, + | protos.google.cloud.retail.v2alpha.IReplaceCatalogAttributeRequest + | null + | undefined, + {} | null | undefined + >, + ): void; replaceCatalogAttribute( - request: protos.google.cloud.retail.v2alpha.IReplaceCatalogAttributeRequest, - callback: Callback< - protos.google.cloud.retail.v2alpha.IAttributesConfig, - protos.google.cloud.retail.v2alpha.IReplaceCatalogAttributeRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IReplaceCatalogAttributeRequest, + callback: Callback< + protos.google.cloud.retail.v2alpha.IAttributesConfig, + | protos.google.cloud.retail.v2alpha.IReplaceCatalogAttributeRequest + | null + | undefined, + {} | null | undefined + >, + ): void; replaceCatalogAttribute( - request?: protos.google.cloud.retail.v2alpha.IReplaceCatalogAttributeRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.cloud.retail.v2alpha.IReplaceCatalogAttributeRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.retail.v2alpha.IAttributesConfig, - protos.google.cloud.retail.v2alpha.IReplaceCatalogAttributeRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.cloud.retail.v2alpha.IAttributesConfig, - protos.google.cloud.retail.v2alpha.IReplaceCatalogAttributeRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.retail.v2alpha.IAttributesConfig, - protos.google.cloud.retail.v2alpha.IReplaceCatalogAttributeRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.retail.v2alpha.IReplaceCatalogAttributeRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.retail.v2alpha.IAttributesConfig, + | protos.google.cloud.retail.v2alpha.IReplaceCatalogAttributeRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IAttributesConfig, + ( + | protos.google.cloud.retail.v2alpha.IReplaceCatalogAttributeRequest + | undefined + ), + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'attributes_config': request.attributesConfig ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + attributes_config: request.attributesConfig ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('replaceCatalogAttribute request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.retail.v2alpha.IAttributesConfig, - protos.google.cloud.retail.v2alpha.IReplaceCatalogAttributeRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.retail.v2alpha.IAttributesConfig, + | protos.google.cloud.retail.v2alpha.IReplaceCatalogAttributeRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('replaceCatalogAttribute response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.replaceCatalogAttribute(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.retail.v2alpha.IAttributesConfig, - protos.google.cloud.retail.v2alpha.IReplaceCatalogAttributeRequest|undefined, - {}|undefined - ]) => { - this._log.info('replaceCatalogAttribute response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .replaceCatalogAttribute(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.retail.v2alpha.IAttributesConfig, + ( + | protos.google.cloud.retail.v2alpha.IReplaceCatalogAttributeRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('replaceCatalogAttribute response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } - /** - * Lists all the {@link protos.google.cloud.retail.v2alpha.Catalog|Catalog}s associated - * with the project. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The account resource name with an associated location. - * - * If the caller does not have permission to list - * {@link protos.google.cloud.retail.v2alpha.Catalog|Catalog}s under this location, - * regardless of whether or not this location exists, a PERMISSION_DENIED - * error is returned. - * @param {number} request.pageSize - * Maximum number of {@link protos.google.cloud.retail.v2alpha.Catalog|Catalog}s to - * return. If unspecified, defaults to 50. The maximum allowed value is 1000. - * Values above 1000 will be coerced to 1000. - * - * If this field is negative, an INVALID_ARGUMENT is returned. - * @param {string} request.pageToken - * A page token - * {@link protos.google.cloud.retail.v2alpha.ListCatalogsResponse.next_page_token|ListCatalogsResponse.next_page_token}, - * received from a previous - * {@link protos.google.cloud.retail.v2alpha.CatalogService.ListCatalogs|CatalogService.ListCatalogs} - * call. Provide this to retrieve the subsequent page. - * - * When paginating, all other parameters provided to - * {@link protos.google.cloud.retail.v2alpha.CatalogService.ListCatalogs|CatalogService.ListCatalogs} - * must match the call that provided the page token. Otherwise, an - * INVALID_ARGUMENT error is returned. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.cloud.retail.v2alpha.Catalog|Catalog}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `listCatalogsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Lists all the {@link protos.google.cloud.retail.v2alpha.Catalog|Catalog}s associated + * with the project. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The account resource name with an associated location. + * + * If the caller does not have permission to list + * {@link protos.google.cloud.retail.v2alpha.Catalog|Catalog}s under this location, + * regardless of whether or not this location exists, a PERMISSION_DENIED + * error is returned. + * @param {number} request.pageSize + * Maximum number of {@link protos.google.cloud.retail.v2alpha.Catalog|Catalog}s to + * return. If unspecified, defaults to 50. The maximum allowed value is 1000. + * Values above 1000 will be coerced to 1000. + * + * If this field is negative, an INVALID_ARGUMENT is returned. + * @param {string} request.pageToken + * A page token + * {@link protos.google.cloud.retail.v2alpha.ListCatalogsResponse.next_page_token|ListCatalogsResponse.next_page_token}, + * received from a previous + * {@link protos.google.cloud.retail.v2alpha.CatalogService.ListCatalogs|CatalogService.ListCatalogs} + * call. Provide this to retrieve the subsequent page. + * + * When paginating, all other parameters provided to + * {@link protos.google.cloud.retail.v2alpha.CatalogService.ListCatalogs|CatalogService.ListCatalogs} + * must match the call that provided the page token. Otherwise, an + * INVALID_ARGUMENT error is returned. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.cloud.retail.v2alpha.Catalog|Catalog}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listCatalogsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listCatalogs( - request?: protos.google.cloud.retail.v2alpha.IListCatalogsRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.retail.v2alpha.ICatalog[], - protos.google.cloud.retail.v2alpha.IListCatalogsRequest|null, - protos.google.cloud.retail.v2alpha.IListCatalogsResponse - ]>; + request?: protos.google.cloud.retail.v2alpha.IListCatalogsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.ICatalog[], + protos.google.cloud.retail.v2alpha.IListCatalogsRequest | null, + protos.google.cloud.retail.v2alpha.IListCatalogsResponse, + ] + >; listCatalogs( - request: protos.google.cloud.retail.v2alpha.IListCatalogsRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.cloud.retail.v2alpha.IListCatalogsRequest, - protos.google.cloud.retail.v2alpha.IListCatalogsResponse|null|undefined, - protos.google.cloud.retail.v2alpha.ICatalog>): void; + request: protos.google.cloud.retail.v2alpha.IListCatalogsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.cloud.retail.v2alpha.IListCatalogsRequest, + | protos.google.cloud.retail.v2alpha.IListCatalogsResponse + | null + | undefined, + protos.google.cloud.retail.v2alpha.ICatalog + >, + ): void; listCatalogs( - request: protos.google.cloud.retail.v2alpha.IListCatalogsRequest, - callback: PaginationCallback< - protos.google.cloud.retail.v2alpha.IListCatalogsRequest, - protos.google.cloud.retail.v2alpha.IListCatalogsResponse|null|undefined, - protos.google.cloud.retail.v2alpha.ICatalog>): void; + request: protos.google.cloud.retail.v2alpha.IListCatalogsRequest, + callback: PaginationCallback< + protos.google.cloud.retail.v2alpha.IListCatalogsRequest, + | protos.google.cloud.retail.v2alpha.IListCatalogsResponse + | null + | undefined, + protos.google.cloud.retail.v2alpha.ICatalog + >, + ): void; listCatalogs( - request?: protos.google.cloud.retail.v2alpha.IListCatalogsRequest, - optionsOrCallback?: CallOptions|PaginationCallback< - protos.google.cloud.retail.v2alpha.IListCatalogsRequest, - protos.google.cloud.retail.v2alpha.IListCatalogsResponse|null|undefined, - protos.google.cloud.retail.v2alpha.ICatalog>, - callback?: PaginationCallback< + request?: protos.google.cloud.retail.v2alpha.IListCatalogsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.cloud.retail.v2alpha.IListCatalogsRequest, - protos.google.cloud.retail.v2alpha.IListCatalogsResponse|null|undefined, - protos.google.cloud.retail.v2alpha.ICatalog>): - Promise<[ - protos.google.cloud.retail.v2alpha.ICatalog[], - protos.google.cloud.retail.v2alpha.IListCatalogsRequest|null, - protos.google.cloud.retail.v2alpha.IListCatalogsResponse - ]>|void { + | protos.google.cloud.retail.v2alpha.IListCatalogsResponse + | null + | undefined, + protos.google.cloud.retail.v2alpha.ICatalog + >, + callback?: PaginationCallback< + protos.google.cloud.retail.v2alpha.IListCatalogsRequest, + | protos.google.cloud.retail.v2alpha.IListCatalogsResponse + | null + | undefined, + protos.google.cloud.retail.v2alpha.ICatalog + >, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.ICatalog[], + protos.google.cloud.retail.v2alpha.IListCatalogsRequest | null, + protos.google.cloud.retail.v2alpha.IListCatalogsResponse, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.cloud.retail.v2alpha.IListCatalogsRequest, - protos.google.cloud.retail.v2alpha.IListCatalogsResponse|null|undefined, - protos.google.cloud.retail.v2alpha.ICatalog>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.cloud.retail.v2alpha.IListCatalogsRequest, + | protos.google.cloud.retail.v2alpha.IListCatalogsResponse + | null + | undefined, + protos.google.cloud.retail.v2alpha.ICatalog + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listCatalogs values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -1666,142 +2267,146 @@ export class CatalogServiceClient { this._log.info('listCatalogs request %j', request); return this.innerApiCalls .listCatalogs(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.cloud.retail.v2alpha.ICatalog[], - protos.google.cloud.retail.v2alpha.IListCatalogsRequest|null, - protos.google.cloud.retail.v2alpha.IListCatalogsResponse - ]) => { - this._log.info('listCatalogs values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.cloud.retail.v2alpha.ICatalog[], + protos.google.cloud.retail.v2alpha.IListCatalogsRequest | null, + protos.google.cloud.retail.v2alpha.IListCatalogsResponse, + ]) => { + this._log.info('listCatalogs values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listCatalogs`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The account resource name with an associated location. - * - * If the caller does not have permission to list - * {@link protos.google.cloud.retail.v2alpha.Catalog|Catalog}s under this location, - * regardless of whether or not this location exists, a PERMISSION_DENIED - * error is returned. - * @param {number} request.pageSize - * Maximum number of {@link protos.google.cloud.retail.v2alpha.Catalog|Catalog}s to - * return. If unspecified, defaults to 50. The maximum allowed value is 1000. - * Values above 1000 will be coerced to 1000. - * - * If this field is negative, an INVALID_ARGUMENT is returned. - * @param {string} request.pageToken - * A page token - * {@link protos.google.cloud.retail.v2alpha.ListCatalogsResponse.next_page_token|ListCatalogsResponse.next_page_token}, - * received from a previous - * {@link protos.google.cloud.retail.v2alpha.CatalogService.ListCatalogs|CatalogService.ListCatalogs} - * call. Provide this to retrieve the subsequent page. - * - * When paginating, all other parameters provided to - * {@link protos.google.cloud.retail.v2alpha.CatalogService.ListCatalogs|CatalogService.ListCatalogs} - * must match the call that provided the page token. Otherwise, an - * INVALID_ARGUMENT error is returned. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.cloud.retail.v2alpha.Catalog|Catalog} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `listCatalogsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `listCatalogs`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The account resource name with an associated location. + * + * If the caller does not have permission to list + * {@link protos.google.cloud.retail.v2alpha.Catalog|Catalog}s under this location, + * regardless of whether or not this location exists, a PERMISSION_DENIED + * error is returned. + * @param {number} request.pageSize + * Maximum number of {@link protos.google.cloud.retail.v2alpha.Catalog|Catalog}s to + * return. If unspecified, defaults to 50. The maximum allowed value is 1000. + * Values above 1000 will be coerced to 1000. + * + * If this field is negative, an INVALID_ARGUMENT is returned. + * @param {string} request.pageToken + * A page token + * {@link protos.google.cloud.retail.v2alpha.ListCatalogsResponse.next_page_token|ListCatalogsResponse.next_page_token}, + * received from a previous + * {@link protos.google.cloud.retail.v2alpha.CatalogService.ListCatalogs|CatalogService.ListCatalogs} + * call. Provide this to retrieve the subsequent page. + * + * When paginating, all other parameters provided to + * {@link protos.google.cloud.retail.v2alpha.CatalogService.ListCatalogs|CatalogService.ListCatalogs} + * must match the call that provided the page token. Otherwise, an + * INVALID_ARGUMENT error is returned. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.cloud.retail.v2alpha.Catalog|Catalog} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listCatalogsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listCatalogsStream( - request?: protos.google.cloud.retail.v2alpha.IListCatalogsRequest, - options?: CallOptions): - Transform{ + request?: protos.google.cloud.retail.v2alpha.IListCatalogsRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); const defaultCallSettings = this._defaults['listCatalogs']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listCatalogs stream %j', request); return this.descriptors.page.listCatalogs.createStream( this.innerApiCalls.listCatalogs as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listCatalogs`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The account resource name with an associated location. - * - * If the caller does not have permission to list - * {@link protos.google.cloud.retail.v2alpha.Catalog|Catalog}s under this location, - * regardless of whether or not this location exists, a PERMISSION_DENIED - * error is returned. - * @param {number} request.pageSize - * Maximum number of {@link protos.google.cloud.retail.v2alpha.Catalog|Catalog}s to - * return. If unspecified, defaults to 50. The maximum allowed value is 1000. - * Values above 1000 will be coerced to 1000. - * - * If this field is negative, an INVALID_ARGUMENT is returned. - * @param {string} request.pageToken - * A page token - * {@link protos.google.cloud.retail.v2alpha.ListCatalogsResponse.next_page_token|ListCatalogsResponse.next_page_token}, - * received from a previous - * {@link protos.google.cloud.retail.v2alpha.CatalogService.ListCatalogs|CatalogService.ListCatalogs} - * call. Provide this to retrieve the subsequent page. - * - * When paginating, all other parameters provided to - * {@link protos.google.cloud.retail.v2alpha.CatalogService.ListCatalogs|CatalogService.ListCatalogs} - * must match the call that provided the page token. Otherwise, an - * INVALID_ARGUMENT error is returned. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.cloud.retail.v2alpha.Catalog|Catalog}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/catalog_service.list_catalogs.js - * region_tag:retail_v2alpha_generated_CatalogService_ListCatalogs_async - */ + /** + * Equivalent to `listCatalogs`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The account resource name with an associated location. + * + * If the caller does not have permission to list + * {@link protos.google.cloud.retail.v2alpha.Catalog|Catalog}s under this location, + * regardless of whether or not this location exists, a PERMISSION_DENIED + * error is returned. + * @param {number} request.pageSize + * Maximum number of {@link protos.google.cloud.retail.v2alpha.Catalog|Catalog}s to + * return. If unspecified, defaults to 50. The maximum allowed value is 1000. + * Values above 1000 will be coerced to 1000. + * + * If this field is negative, an INVALID_ARGUMENT is returned. + * @param {string} request.pageToken + * A page token + * {@link protos.google.cloud.retail.v2alpha.ListCatalogsResponse.next_page_token|ListCatalogsResponse.next_page_token}, + * received from a previous + * {@link protos.google.cloud.retail.v2alpha.CatalogService.ListCatalogs|CatalogService.ListCatalogs} + * call. Provide this to retrieve the subsequent page. + * + * When paginating, all other parameters provided to + * {@link protos.google.cloud.retail.v2alpha.CatalogService.ListCatalogs|CatalogService.ListCatalogs} + * must match the call that provided the page token. Otherwise, an + * INVALID_ARGUMENT error is returned. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.cloud.retail.v2alpha.Catalog|Catalog}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/catalog_service.list_catalogs.js + * region_tag:retail_v2alpha_generated_CatalogService_ListCatalogs_async + */ listCatalogsAsync( - request?: protos.google.cloud.retail.v2alpha.IListCatalogsRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.cloud.retail.v2alpha.IListCatalogsRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); const defaultCallSettings = this._defaults['listCatalogs']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listCatalogs iterate %j', request); return this.descriptors.page.listCatalogs.asyncIterate( this.innerApiCalls['listCatalogs'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } // -------------------- @@ -1814,7 +2419,7 @@ export class CatalogServiceClient { * @param {string} project * @returns {string} Resource name string. */ - alertConfigPath(project:string) { + alertConfigPath(project: string) { return this.pathTemplates.alertConfigPathTemplate.render({ project: project, }); @@ -1828,7 +2433,8 @@ export class CatalogServiceClient { * @returns {string} A string representing the project. */ matchProjectFromAlertConfigName(alertConfigName: string) { - return this.pathTemplates.alertConfigPathTemplate.match(alertConfigName).project; + return this.pathTemplates.alertConfigPathTemplate.match(alertConfigName) + .project; } /** @@ -1839,7 +2445,7 @@ export class CatalogServiceClient { * @param {string} catalog * @returns {string} Resource name string. */ - attributesConfigPath(project:string,location:string,catalog:string) { + attributesConfigPath(project: string, location: string, catalog: string) { return this.pathTemplates.attributesConfigPathTemplate.render({ project: project, location: location, @@ -1855,7 +2461,9 @@ export class CatalogServiceClient { * @returns {string} A string representing the project. */ matchProjectFromAttributesConfigName(attributesConfigName: string) { - return this.pathTemplates.attributesConfigPathTemplate.match(attributesConfigName).project; + return this.pathTemplates.attributesConfigPathTemplate.match( + attributesConfigName, + ).project; } /** @@ -1866,7 +2474,9 @@ export class CatalogServiceClient { * @returns {string} A string representing the location. */ matchLocationFromAttributesConfigName(attributesConfigName: string) { - return this.pathTemplates.attributesConfigPathTemplate.match(attributesConfigName).location; + return this.pathTemplates.attributesConfigPathTemplate.match( + attributesConfigName, + ).location; } /** @@ -1877,7 +2487,9 @@ export class CatalogServiceClient { * @returns {string} A string representing the catalog. */ matchCatalogFromAttributesConfigName(attributesConfigName: string) { - return this.pathTemplates.attributesConfigPathTemplate.match(attributesConfigName).catalog; + return this.pathTemplates.attributesConfigPathTemplate.match( + attributesConfigName, + ).catalog; } /** @@ -1889,7 +2501,12 @@ export class CatalogServiceClient { * @param {string} branch * @returns {string} Resource name string. */ - branchPath(project:string,location:string,catalog:string,branch:string) { + branchPath( + project: string, + location: string, + catalog: string, + branch: string, + ) { return this.pathTemplates.branchPathTemplate.render({ project: project, location: location, @@ -1950,7 +2567,7 @@ export class CatalogServiceClient { * @param {string} catalog * @returns {string} Resource name string. */ - catalogPath(project:string,location:string,catalog:string) { + catalogPath(project: string, location: string, catalog: string) { return this.pathTemplates.catalogPathTemplate.render({ project: project, location: location, @@ -1999,7 +2616,7 @@ export class CatalogServiceClient { * @param {string} catalog * @returns {string} Resource name string. */ - completionConfigPath(project:string,location:string,catalog:string) { + completionConfigPath(project: string, location: string, catalog: string) { return this.pathTemplates.completionConfigPathTemplate.render({ project: project, location: location, @@ -2015,7 +2632,9 @@ export class CatalogServiceClient { * @returns {string} A string representing the project. */ matchProjectFromCompletionConfigName(completionConfigName: string) { - return this.pathTemplates.completionConfigPathTemplate.match(completionConfigName).project; + return this.pathTemplates.completionConfigPathTemplate.match( + completionConfigName, + ).project; } /** @@ -2026,7 +2645,9 @@ export class CatalogServiceClient { * @returns {string} A string representing the location. */ matchLocationFromCompletionConfigName(completionConfigName: string) { - return this.pathTemplates.completionConfigPathTemplate.match(completionConfigName).location; + return this.pathTemplates.completionConfigPathTemplate.match( + completionConfigName, + ).location; } /** @@ -2037,7 +2658,9 @@ export class CatalogServiceClient { * @returns {string} A string representing the catalog. */ matchCatalogFromCompletionConfigName(completionConfigName: string) { - return this.pathTemplates.completionConfigPathTemplate.match(completionConfigName).catalog; + return this.pathTemplates.completionConfigPathTemplate.match( + completionConfigName, + ).catalog; } /** @@ -2049,7 +2672,12 @@ export class CatalogServiceClient { * @param {string} control * @returns {string} Resource name string. */ - controlPath(project:string,location:string,catalog:string,control:string) { + controlPath( + project: string, + location: string, + catalog: string, + control: string, + ) { return this.pathTemplates.controlPathTemplate.render({ project: project, location: location, @@ -2109,7 +2737,7 @@ export class CatalogServiceClient { * @param {string} location * @returns {string} Resource name string. */ - locationPath(project:string,location:string) { + locationPath(project: string, location: string) { return this.pathTemplates.locationPathTemplate.render({ project: project, location: location, @@ -2144,7 +2772,7 @@ export class CatalogServiceClient { * @param {string} project * @returns {string} Resource name string. */ - loggingConfigPath(project:string) { + loggingConfigPath(project: string) { return this.pathTemplates.loggingConfigPathTemplate.render({ project: project, }); @@ -2158,7 +2786,8 @@ export class CatalogServiceClient { * @returns {string} A string representing the project. */ matchProjectFromLoggingConfigName(loggingConfigName: string) { - return this.pathTemplates.loggingConfigPathTemplate.match(loggingConfigName).project; + return this.pathTemplates.loggingConfigPathTemplate.match(loggingConfigName) + .project; } /** @@ -2170,7 +2799,12 @@ export class CatalogServiceClient { * @param {string} merchant_center_account_link * @returns {string} Resource name string. */ - merchantCenterAccountLinkPath(project:string,location:string,catalog:string,merchantCenterAccountLink:string) { + merchantCenterAccountLinkPath( + project: string, + location: string, + catalog: string, + merchantCenterAccountLink: string, + ) { return this.pathTemplates.merchantCenterAccountLinkPathTemplate.render({ project: project, location: location, @@ -2186,8 +2820,12 @@ export class CatalogServiceClient { * A fully-qualified path representing MerchantCenterAccountLink resource. * @returns {string} A string representing the project. */ - matchProjectFromMerchantCenterAccountLinkName(merchantCenterAccountLinkName: string) { - return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match(merchantCenterAccountLinkName).project; + matchProjectFromMerchantCenterAccountLinkName( + merchantCenterAccountLinkName: string, + ) { + return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match( + merchantCenterAccountLinkName, + ).project; } /** @@ -2197,8 +2835,12 @@ export class CatalogServiceClient { * A fully-qualified path representing MerchantCenterAccountLink resource. * @returns {string} A string representing the location. */ - matchLocationFromMerchantCenterAccountLinkName(merchantCenterAccountLinkName: string) { - return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match(merchantCenterAccountLinkName).location; + matchLocationFromMerchantCenterAccountLinkName( + merchantCenterAccountLinkName: string, + ) { + return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match( + merchantCenterAccountLinkName, + ).location; } /** @@ -2208,8 +2850,12 @@ export class CatalogServiceClient { * A fully-qualified path representing MerchantCenterAccountLink resource. * @returns {string} A string representing the catalog. */ - matchCatalogFromMerchantCenterAccountLinkName(merchantCenterAccountLinkName: string) { - return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match(merchantCenterAccountLinkName).catalog; + matchCatalogFromMerchantCenterAccountLinkName( + merchantCenterAccountLinkName: string, + ) { + return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match( + merchantCenterAccountLinkName, + ).catalog; } /** @@ -2219,8 +2865,12 @@ export class CatalogServiceClient { * A fully-qualified path representing MerchantCenterAccountLink resource. * @returns {string} A string representing the merchant_center_account_link. */ - matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName(merchantCenterAccountLinkName: string) { - return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match(merchantCenterAccountLinkName).merchant_center_account_link; + matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName( + merchantCenterAccountLinkName: string, + ) { + return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match( + merchantCenterAccountLinkName, + ).merchant_center_account_link; } /** @@ -2232,7 +2882,7 @@ export class CatalogServiceClient { * @param {string} model * @returns {string} Resource name string. */ - modelPath(project:string,location:string,catalog:string,model:string) { + modelPath(project: string, location: string, catalog: string, model: string) { return this.pathTemplates.modelPathTemplate.render({ project: project, location: location, @@ -2295,7 +2945,13 @@ export class CatalogServiceClient { * @param {string} product * @returns {string} Resource name string. */ - productPath(project:string,location:string,catalog:string,branch:string,product:string) { + productPath( + project: string, + location: string, + catalog: string, + branch: string, + product: string, + ) { return this.pathTemplates.productPathTemplate.render({ project: project, location: location, @@ -2366,7 +3022,7 @@ export class CatalogServiceClient { * @param {string} project * @returns {string} Resource name string. */ - retailProjectPath(project:string) { + retailProjectPath(project: string) { return this.pathTemplates.retailProjectPathTemplate.render({ project: project, }); @@ -2380,7 +3036,8 @@ export class CatalogServiceClient { * @returns {string} A string representing the project. */ matchProjectFromRetailProjectName(retailProjectName: string) { - return this.pathTemplates.retailProjectPathTemplate.match(retailProjectName).project; + return this.pathTemplates.retailProjectPathTemplate.match(retailProjectName) + .project; } /** @@ -2392,7 +3049,12 @@ export class CatalogServiceClient { * @param {string} serving_config * @returns {string} Resource name string. */ - servingConfigPath(project:string,location:string,catalog:string,servingConfig:string) { + servingConfigPath( + project: string, + location: string, + catalog: string, + servingConfig: string, + ) { return this.pathTemplates.servingConfigPathTemplate.render({ project: project, location: location, @@ -2409,7 +3071,8 @@ export class CatalogServiceClient { * @returns {string} A string representing the project. */ matchProjectFromServingConfigName(servingConfigName: string) { - return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName).project; + return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName) + .project; } /** @@ -2420,7 +3083,8 @@ export class CatalogServiceClient { * @returns {string} A string representing the location. */ matchLocationFromServingConfigName(servingConfigName: string) { - return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName).location; + return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName) + .location; } /** @@ -2431,7 +3095,8 @@ export class CatalogServiceClient { * @returns {string} A string representing the catalog. */ matchCatalogFromServingConfigName(servingConfigName: string) { - return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName).catalog; + return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName) + .catalog; } /** @@ -2442,7 +3107,8 @@ export class CatalogServiceClient { * @returns {string} A string representing the serving_config. */ matchServingConfigFromServingConfigName(servingConfigName: string) { - return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName).serving_config; + return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName) + .serving_config; } /** @@ -2453,7 +3119,7 @@ export class CatalogServiceClient { */ close(): Promise { if (this.catalogServiceStub && !this._terminated) { - return this.catalogServiceStub.then(stub => { + return this.catalogServiceStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -2461,4 +3127,4 @@ export class CatalogServiceClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/core/generator/gapic-generator-typescript/baselines/retail/src/v2alpha/completion_service_client.ts.baseline b/core/generator/gapic-generator-typescript/baselines/retail/src/v2alpha/completion_service_client.ts.baseline index f7a11c51a79b..e7dd2cd69ab4 100644 --- a/core/generator/gapic-generator-typescript/baselines/retail/src/v2alpha/completion_service_client.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/retail/src/v2alpha/completion_service_client.ts.baseline @@ -18,11 +18,18 @@ /* global window */ import type * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions, GrpcClientOptions, LROperation} from 'google-gax'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + GrpcClientOptions, + LROperation, +} from 'google-gax'; import * as protos from '../../protos/protos'; import jsonProtos = require('../../protos/protos.json'); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; /** * Client JSON configuration object, loaded from @@ -47,7 +54,7 @@ export class CompletionServiceClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('retail'); @@ -60,10 +67,10 @@ export class CompletionServiceClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; operationsClient: gax.OperationsClient; - completionServiceStub?: Promise<{[name: string]: Function}>; + completionServiceStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of CompletionServiceClient. @@ -104,21 +111,42 @@ export class CompletionServiceClient { * const client = new CompletionServiceClient({fallback: true}, gax); * ``` */ - constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { // Ensure that options include all the required fields. const staticMembers = this.constructor as typeof CompletionServiceClient; - if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { - throw new Error('Please set either universe_domain or universeDomain, but not both.'); + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); } - const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; - this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; this._servicePath = 'retail.' + this._universeDomain; - const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; - const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. if (servicePath !== this._servicePath && !('scopes' in opts)) { @@ -140,7 +168,7 @@ export class CompletionServiceClient { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; @@ -154,10 +182,7 @@ export class CompletionServiceClient { } // Determine the client header string. - const clientHeader = [ - `gax/${this._gaxModule.version}`, - `gapic/${version}`, - ]; + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/${process.versions.node}`); } else { @@ -179,40 +204,40 @@ export class CompletionServiceClient { // Create useful helper objects for these. this.pathTemplates = { alertConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/alertConfig' + 'projects/{project}/alertConfig', ), attributesConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/attributesConfig' + 'projects/{project}/locations/{location}/catalogs/{catalog}/attributesConfig', ), branchPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}', ), catalogPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}' + 'projects/{project}/locations/{location}/catalogs/{catalog}', ), completionConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/completionConfig' + 'projects/{project}/locations/{location}/catalogs/{catalog}/completionConfig', ), controlPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/controls/{control}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/controls/{control}', ), loggingConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/loggingConfig' + 'projects/{project}/loggingConfig', ), merchantCenterAccountLinkPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/merchantCenterAccountLinks/{merchant_center_account_link}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/merchantCenterAccountLinks/{merchant_center_account_link}', ), modelPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/models/{model}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/models/{model}', ), productPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}', ), retailProjectPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/retailProject' + 'projects/{project}/retailProject', ), servingConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/servingConfigs/{serving_config}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/servingConfigs/{serving_config}', ), }; @@ -222,31 +247,60 @@ export class CompletionServiceClient { // rather than holding a request open. const lroOptions: GrpcClientOptions = { auth: this.auth, - grpc: 'grpc' in this._gaxGrpc ? this._gaxGrpc.grpc : undefined + grpc: 'grpc' in this._gaxGrpc ? this._gaxGrpc.grpc : undefined, }; if (opts.fallback) { lroOptions.protoJson = protoFilesRoot; - lroOptions.httpRules = [{selector: 'google.longrunning.Operations.GetOperation',get: '/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*/operations/*}',additional_bindings: [{get: '/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*/places/*/operations/*}',},{get: '/v2alpha/{name=projects/*/locations/*/catalogs/*/operations/*}',},{get: '/v2alpha/{name=projects/*/locations/*/operations/*}',},{get: '/v2alpha/{name=projects/*/operations/*}',}], - },{selector: 'google.longrunning.Operations.ListOperations',get: '/v2alpha/{name=projects/*/locations/*/catalogs/*}/operations',additional_bindings: [{get: '/v2alpha/{name=projects/*/locations/*}/operations',},{get: '/v2alpha/{name=projects/*}/operations',}], - }]; + lroOptions.httpRules = [ + { + selector: 'google.longrunning.Operations.GetOperation', + get: '/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*/operations/*}', + additional_bindings: [ + { + get: '/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*/places/*/operations/*}', + }, + { + get: '/v2alpha/{name=projects/*/locations/*/catalogs/*/operations/*}', + }, + { get: '/v2alpha/{name=projects/*/locations/*/operations/*}' }, + { get: '/v2alpha/{name=projects/*/operations/*}' }, + ], + }, + { + selector: 'google.longrunning.Operations.ListOperations', + get: '/v2alpha/{name=projects/*/locations/*/catalogs/*}/operations', + additional_bindings: [ + { get: '/v2alpha/{name=projects/*/locations/*}/operations' }, + { get: '/v2alpha/{name=projects/*}/operations' }, + ], + }, + ]; } - this.operationsClient = this._gaxModule.lro(lroOptions).operationsClient(opts); + this.operationsClient = this._gaxModule + .lro(lroOptions) + .operationsClient(opts); const importCompletionDataResponse = protoFilesRoot.lookup( - '.google.cloud.retail.v2alpha.ImportCompletionDataResponse') as gax.protobuf.Type; + '.google.cloud.retail.v2alpha.ImportCompletionDataResponse', + ) as gax.protobuf.Type; const importCompletionDataMetadata = protoFilesRoot.lookup( - '.google.cloud.retail.v2alpha.ImportMetadata') as gax.protobuf.Type; + '.google.cloud.retail.v2alpha.ImportMetadata', + ) as gax.protobuf.Type; this.descriptors.longrunning = { importCompletionData: new this._gaxModule.LongrunningDescriptor( this.operationsClient, importCompletionDataResponse.decode.bind(importCompletionDataResponse), - importCompletionDataMetadata.decode.bind(importCompletionDataMetadata)) + importCompletionDataMetadata.decode.bind(importCompletionDataMetadata), + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.cloud.retail.v2alpha.CompletionService', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.cloud.retail.v2alpha.CompletionService', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + { 'x-goog-api-client': clientHeader.join(' ') }, + ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -277,37 +331,43 @@ export class CompletionServiceClient { // Put together the "service stub" for // google.cloud.retail.v2alpha.CompletionService. this.completionServiceStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.cloud.retail.v2alpha.CompletionService') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.cloud.retail.v2alpha.CompletionService', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.cloud.retail.v2alpha.CompletionService, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts, + this._providedCustomServicePath, + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const completionServiceStubMethods = - ['completeQuery', 'importCompletionData']; + const completionServiceStubMethods = [ + 'completeQuery', + 'importCompletionData', + ]; for (const methodName of completionServiceStubMethods) { const callPromise = this.completionServiceStub.then( - stub => (...args: Array<{}>) => { - if (this._terminated) { - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error|null|undefined) => () => { + (stub) => + (...args: Array<{}>) => { + if (this._terminated) { + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { throw err; - }); + }, + ); - const descriptor = - this.descriptors.longrunning[methodName] || - undefined; + const descriptor = this.descriptors.longrunning[methodName] || undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -322,8 +382,14 @@ export class CompletionServiceClient { * @returns {string} The DNS address for this service. */ static get servicePath() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'retail.googleapis.com'; } @@ -334,8 +400,14 @@ export class CompletionServiceClient { * @returns {string} The DNS address for this service. */ static get apiEndpoint() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'retail.googleapis.com'; } @@ -366,9 +438,7 @@ export class CompletionServiceClient { * @returns {string[]} List of default scopes. */ static get scopes() { - return [ - 'https://www.googleapis.com/auth/cloud-platform' - ]; + return ['https://www.googleapis.com/auth/cloud-platform']; } getProjectId(): Promise; @@ -377,8 +447,9 @@ export class CompletionServiceClient { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId(callback?: Callback): - Promise|void { + getProjectId( + callback?: Callback, + ): Promise | void { if (callback) { this.auth.getProjectId(callback); return; @@ -389,308 +460,410 @@ export class CompletionServiceClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Completes the specified prefix with keyword suggestions. - * - * This feature is only available for users who have Retail Search enabled. - * Enable Retail Search on Cloud Console before using this feature. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.catalog - * Required. Catalog for which the completion is performed. - * - * Full resource name of catalog, such as - * `projects/* /locations/global/catalogs/default_catalog`. - * @param {string} request.query - * Required. The query used to generate suggestions. - * - * The maximum number of allowed characters is 255. - * @param {string} request.visitorId - * Recommended field. A unique identifier for tracking visitors. For example, - * this could be implemented with an HTTP cookie, which should be able to - * uniquely identify a visitor on a single device. This unique identifier - * should not change if the visitor logs in or out of the website. - * - * The field must be a UTF-8 encoded string with a length limit of 128 - * characters. Otherwise, an INVALID_ARGUMENT error is returned. - * @param {string[]} request.languageCodes - * Note that this field applies for `user-data` dataset only. For requests - * with `cloud-retail` dataset, setting this field has no effect. - * - * The language filters applied to the output suggestions. If set, it should - * contain the language of the query. If not set, suggestions are returned - * without considering language restrictions. This is the BCP-47 language - * code, such as "en-US" or "sr-Latn". For more information, see [Tags for - * Identifying Languages](https://tools.ietf.org/html/bcp47). The maximum - * number of language codes is 3. - * @param {string} request.deviceType - * The device type context for completion suggestions. We recommend that you - * leave this field empty. - * - * It can apply different suggestions on different device types, e.g. - * `DESKTOP`, `MOBILE`. If it is empty, the suggestions are across all device - * types. - * - * Supported formats: - * - * * `UNKNOWN_DEVICE_TYPE` - * - * * `DESKTOP` - * - * * `MOBILE` - * - * * A customized string starts with `OTHER_`, e.g. `OTHER_IPHONE`. - * @param {string} request.dataset - * Determines which dataset to use for fetching completion. "user-data" will - * use the dataset imported through - * {@link protos.google.cloud.retail.v2alpha.CompletionService.ImportCompletionData|CompletionService.ImportCompletionData}. - * `cloud-retail` will use the dataset generated by Cloud Retail based on user - * events. If left empty, completions will be fetched from the `user-data` - * dataset. - * - * Current supported values: - * - * * user-data - * - * * cloud-retail: - * This option requires enabling auto-learning function first. See - * [guidelines](https://cloud.google.com/retail/docs/completion-overview#generated-completion-dataset). - * @param {number} request.maxSuggestions - * Completion max suggestions. If left unset or set to 0, then will fallback - * to the configured value - * {@link protos.google.cloud.retail.v2alpha.CompletionConfig.max_suggestions|CompletionConfig.max_suggestions}. - * - * The maximum allowed max suggestions is 20. If it is set higher, it will be - * capped by 20. - * @param {boolean} request.enableAttributeSuggestions - * If true, attribute suggestions are enabled and provided in the response. - * - * This field is only available for the `cloud-retail` dataset. - * @param {string} request.entity - * The entity for customers who run multiple entities, domains, sites, or - * regions, for example, `Google US`, `Google Ads`, `Waymo`, - * `google.com`, `youtube.com`, etc. - * If this is set, it must be an exact match with - * {@link protos.google.cloud.retail.v2alpha.UserEvent.entity|UserEvent.entity} to get - * per-entity autocomplete results. This field will be applied to - * `completion_results` only. It has no effect on the `attribute_results`. - * Also, this entity should be limited to 256 characters, if too long, it will - * be truncated to 256 characters in both generation and serving time, and may - * lead to mis-match. To ensure it works, please set the entity with string - * within 256 characters. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.CompleteQueryResponse|CompleteQueryResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/completion_service.complete_query.js - * region_tag:retail_v2alpha_generated_CompletionService_CompleteQuery_async - */ + /** + * Completes the specified prefix with keyword suggestions. + * + * This feature is only available for users who have Retail Search enabled. + * Enable Retail Search on Cloud Console before using this feature. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.catalog + * Required. Catalog for which the completion is performed. + * + * Full resource name of catalog, such as + * `projects/* /locations/global/catalogs/default_catalog`. + * @param {string} request.query + * Required. The query used to generate suggestions. + * + * The maximum number of allowed characters is 255. + * @param {string} request.visitorId + * Recommended field. A unique identifier for tracking visitors. For example, + * this could be implemented with an HTTP cookie, which should be able to + * uniquely identify a visitor on a single device. This unique identifier + * should not change if the visitor logs in or out of the website. + * + * The field must be a UTF-8 encoded string with a length limit of 128 + * characters. Otherwise, an INVALID_ARGUMENT error is returned. + * @param {string[]} request.languageCodes + * Note that this field applies for `user-data` dataset only. For requests + * with `cloud-retail` dataset, setting this field has no effect. + * + * The language filters applied to the output suggestions. If set, it should + * contain the language of the query. If not set, suggestions are returned + * without considering language restrictions. This is the BCP-47 language + * code, such as "en-US" or "sr-Latn". For more information, see [Tags for + * Identifying Languages](https://tools.ietf.org/html/bcp47). The maximum + * number of language codes is 3. + * @param {string} request.deviceType + * The device type context for completion suggestions. We recommend that you + * leave this field empty. + * + * It can apply different suggestions on different device types, e.g. + * `DESKTOP`, `MOBILE`. If it is empty, the suggestions are across all device + * types. + * + * Supported formats: + * + * * `UNKNOWN_DEVICE_TYPE` + * + * * `DESKTOP` + * + * * `MOBILE` + * + * * A customized string starts with `OTHER_`, e.g. `OTHER_IPHONE`. + * @param {string} request.dataset + * Determines which dataset to use for fetching completion. "user-data" will + * use the dataset imported through + * {@link protos.google.cloud.retail.v2alpha.CompletionService.ImportCompletionData|CompletionService.ImportCompletionData}. + * `cloud-retail` will use the dataset generated by Cloud Retail based on user + * events. If left empty, completions will be fetched from the `user-data` + * dataset. + * + * Current supported values: + * + * * user-data + * + * * cloud-retail: + * This option requires enabling auto-learning function first. See + * [guidelines](https://cloud.google.com/retail/docs/completion-overview#generated-completion-dataset). + * @param {number} request.maxSuggestions + * Completion max suggestions. If left unset or set to 0, then will fallback + * to the configured value + * {@link protos.google.cloud.retail.v2alpha.CompletionConfig.max_suggestions|CompletionConfig.max_suggestions}. + * + * The maximum allowed max suggestions is 20. If it is set higher, it will be + * capped by 20. + * @param {boolean} request.enableAttributeSuggestions + * If true, attribute suggestions are enabled and provided in the response. + * + * This field is only available for the `cloud-retail` dataset. + * @param {string} request.entity + * The entity for customers who run multiple entities, domains, sites, or + * regions, for example, `Google US`, `Google Ads`, `Waymo`, + * `google.com`, `youtube.com`, etc. + * If this is set, it must be an exact match with + * {@link protos.google.cloud.retail.v2alpha.UserEvent.entity|UserEvent.entity} to get + * per-entity autocomplete results. This field will be applied to + * `completion_results` only. It has no effect on the `attribute_results`. + * Also, this entity should be limited to 256 characters, if too long, it will + * be truncated to 256 characters in both generation and serving time, and may + * lead to mis-match. To ensure it works, please set the entity with string + * within 256 characters. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.CompleteQueryResponse|CompleteQueryResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/completion_service.complete_query.js + * region_tag:retail_v2alpha_generated_CompletionService_CompleteQuery_async + */ completeQuery( - request?: protos.google.cloud.retail.v2alpha.ICompleteQueryRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.retail.v2alpha.ICompleteQueryResponse, - protos.google.cloud.retail.v2alpha.ICompleteQueryRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.ICompleteQueryRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.ICompleteQueryResponse, + protos.google.cloud.retail.v2alpha.ICompleteQueryRequest | undefined, + {} | undefined, + ] + >; completeQuery( - request: protos.google.cloud.retail.v2alpha.ICompleteQueryRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.retail.v2alpha.ICompleteQueryResponse, - protos.google.cloud.retail.v2alpha.ICompleteQueryRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.ICompleteQueryRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.retail.v2alpha.ICompleteQueryResponse, + | protos.google.cloud.retail.v2alpha.ICompleteQueryRequest + | null + | undefined, + {} | null | undefined + >, + ): void; completeQuery( - request: protos.google.cloud.retail.v2alpha.ICompleteQueryRequest, - callback: Callback< - protos.google.cloud.retail.v2alpha.ICompleteQueryResponse, - protos.google.cloud.retail.v2alpha.ICompleteQueryRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.ICompleteQueryRequest, + callback: Callback< + protos.google.cloud.retail.v2alpha.ICompleteQueryResponse, + | protos.google.cloud.retail.v2alpha.ICompleteQueryRequest + | null + | undefined, + {} | null | undefined + >, + ): void; completeQuery( - request?: protos.google.cloud.retail.v2alpha.ICompleteQueryRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.cloud.retail.v2alpha.ICompleteQueryRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.retail.v2alpha.ICompleteQueryResponse, - protos.google.cloud.retail.v2alpha.ICompleteQueryRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.cloud.retail.v2alpha.ICompleteQueryResponse, - protos.google.cloud.retail.v2alpha.ICompleteQueryRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.retail.v2alpha.ICompleteQueryResponse, - protos.google.cloud.retail.v2alpha.ICompleteQueryRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.retail.v2alpha.ICompleteQueryRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.retail.v2alpha.ICompleteQueryResponse, + | protos.google.cloud.retail.v2alpha.ICompleteQueryRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.ICompleteQueryResponse, + protos.google.cloud.retail.v2alpha.ICompleteQueryRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'catalog': request.catalog ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + catalog: request.catalog ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('completeQuery request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.retail.v2alpha.ICompleteQueryResponse, - protos.google.cloud.retail.v2alpha.ICompleteQueryRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.retail.v2alpha.ICompleteQueryResponse, + | protos.google.cloud.retail.v2alpha.ICompleteQueryRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('completeQuery response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.completeQuery(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.retail.v2alpha.ICompleteQueryResponse, - protos.google.cloud.retail.v2alpha.ICompleteQueryRequest|undefined, - {}|undefined - ]) => { - this._log.info('completeQuery response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .completeQuery(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.retail.v2alpha.ICompleteQueryResponse, + protos.google.cloud.retail.v2alpha.ICompleteQueryRequest | undefined, + {} | undefined, + ]) => { + this._log.info('completeQuery response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Bulk import of processed completion dataset. - * - * Request processing is asynchronous. Partial updating is not supported. - * - * The operation is successfully finished only after the imported suggestions - * are indexed successfully and ready for serving. The process takes hours. - * - * This feature is only available for users who have Retail Search enabled. - * Enable Retail Search on Cloud Console before using this feature. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The catalog which the suggestions dataset belongs to. - * - * Format: `projects/1234/locations/global/catalogs/default_catalog`. - * @param {google.cloud.retail.v2alpha.CompletionDataInputConfig} request.inputConfig - * Required. The desired input location of the data. - * @param {string} request.notificationPubsubTopic - * Pub/Sub topic for receiving notification. If this field is set, - * when the import is finished, a notification is sent to - * specified Pub/Sub topic. The message data is JSON string of a - * {@link protos.google.longrunning.Operation|Operation}. - * Format of the Pub/Sub topic is `projects/{project}/topics/{topic}`. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing - * a long running operation. Its `promise()` method returns a promise - * you can `await` for. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/completion_service.import_completion_data.js - * region_tag:retail_v2alpha_generated_CompletionService_ImportCompletionData_async - */ + /** + * Bulk import of processed completion dataset. + * + * Request processing is asynchronous. Partial updating is not supported. + * + * The operation is successfully finished only after the imported suggestions + * are indexed successfully and ready for serving. The process takes hours. + * + * This feature is only available for users who have Retail Search enabled. + * Enable Retail Search on Cloud Console before using this feature. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The catalog which the suggestions dataset belongs to. + * + * Format: `projects/1234/locations/global/catalogs/default_catalog`. + * @param {google.cloud.retail.v2alpha.CompletionDataInputConfig} request.inputConfig + * Required. The desired input location of the data. + * @param {string} request.notificationPubsubTopic + * Pub/Sub topic for receiving notification. If this field is set, + * when the import is finished, a notification is sent to + * specified Pub/Sub topic. The message data is JSON string of a + * {@link protos.google.longrunning.Operation|Operation}. + * Format of the Pub/Sub topic is `projects/{project}/topics/{topic}`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/completion_service.import_completion_data.js + * region_tag:retail_v2alpha_generated_CompletionService_ImportCompletionData_async + */ importCompletionData( - request?: protos.google.cloud.retail.v2alpha.IImportCompletionDataRequest, - options?: CallOptions): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.IImportCompletionDataRequest, + options?: CallOptions, + ): Promise< + [ + LROperation< + protos.google.cloud.retail.v2alpha.IImportCompletionDataResponse, + protos.google.cloud.retail.v2alpha.IImportMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; importCompletionData( - request: protos.google.cloud.retail.v2alpha.IImportCompletionDataRequest, - options: CallOptions, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IImportCompletionDataRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IImportCompletionDataResponse, + protos.google.cloud.retail.v2alpha.IImportMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; importCompletionData( - request: protos.google.cloud.retail.v2alpha.IImportCompletionDataRequest, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IImportCompletionDataRequest, + callback: Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IImportCompletionDataResponse, + protos.google.cloud.retail.v2alpha.IImportMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; importCompletionData( - request?: protos.google.cloud.retail.v2alpha.IImportCompletionDataRequest, - optionsOrCallback?: CallOptions|Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>, - callback?: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>|void { + request?: protos.google.cloud.retail.v2alpha.IImportCompletionDataRequest, + optionsOrCallback?: + | CallOptions + | Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IImportCompletionDataResponse, + protos.google.cloud.retail.v2alpha.IImportMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + callback?: Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IImportCompletionDataResponse, + protos.google.cloud.retail.v2alpha.IImportMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + LROperation< + protos.google.cloud.retail.v2alpha.IImportCompletionDataResponse, + protos.google.cloud.retail.v2alpha.IImportMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IImportCompletionDataResponse, + protos.google.cloud.retail.v2alpha.IImportMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, rawResponse, _) => { this._log.info('importCompletionData response %j', rawResponse); callback!(error, response, rawResponse, _); // We verified callback above. } : undefined; this._log.info('importCompletionData request %j', request); - return this.innerApiCalls.importCompletionData(request, options, wrappedCallback) - ?.then(([response, rawResponse, _]: [ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]) => { - this._log.info('importCompletionData response %j', rawResponse); - return [response, rawResponse, _]; - }); + return this.innerApiCalls + .importCompletionData(request, options, wrappedCallback) + ?.then( + ([response, rawResponse, _]: [ + LROperation< + protos.google.cloud.retail.v2alpha.IImportCompletionDataResponse, + protos.google.cloud.retail.v2alpha.IImportMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ]) => { + this._log.info('importCompletionData response %j', rawResponse); + return [response, rawResponse, _]; + }, + ); } -/** - * Check the status of the long running operation returned by `importCompletionData()`. - * @param {String} name - * The operation name that will be passed. - * @returns {Promise} - The promise which resolves to an object. - * The decoded operation object has result and metadata field to get information from. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/completion_service.import_completion_data.js - * region_tag:retail_v2alpha_generated_CompletionService_ImportCompletionData_async - */ - async checkImportCompletionDataProgress(name: string): Promise>{ + /** + * Check the status of the long running operation returned by `importCompletionData()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/completion_service.import_completion_data.js + * region_tag:retail_v2alpha_generated_CompletionService_ImportCompletionData_async + */ + async checkImportCompletionDataProgress( + name: string, + ): Promise< + LROperation< + protos.google.cloud.retail.v2alpha.ImportCompletionDataResponse, + protos.google.cloud.retail.v2alpha.ImportMetadata + > + > { this._log.info('importCompletionData long-running'); - const request = new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest({name}); + const request = + new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( + { name }, + ); const [operation] = await this.operationsClient.getOperation(request); - const decodeOperation = new this._gaxModule.Operation(operation, this.descriptors.longrunning.importCompletionData, this._gaxModule.createDefaultBackoffSettings()); - return decodeOperation as LROperation; + const decodeOperation = new this._gaxModule.Operation( + operation, + this.descriptors.longrunning.importCompletionData, + this._gaxModule.createDefaultBackoffSettings(), + ); + return decodeOperation as LROperation< + protos.google.cloud.retail.v2alpha.ImportCompletionDataResponse, + protos.google.cloud.retail.v2alpha.ImportMetadata + >; } // -------------------- // -- Path templates -- @@ -702,7 +875,7 @@ export class CompletionServiceClient { * @param {string} project * @returns {string} Resource name string. */ - alertConfigPath(project:string) { + alertConfigPath(project: string) { return this.pathTemplates.alertConfigPathTemplate.render({ project: project, }); @@ -716,7 +889,8 @@ export class CompletionServiceClient { * @returns {string} A string representing the project. */ matchProjectFromAlertConfigName(alertConfigName: string) { - return this.pathTemplates.alertConfigPathTemplate.match(alertConfigName).project; + return this.pathTemplates.alertConfigPathTemplate.match(alertConfigName) + .project; } /** @@ -727,7 +901,7 @@ export class CompletionServiceClient { * @param {string} catalog * @returns {string} Resource name string. */ - attributesConfigPath(project:string,location:string,catalog:string) { + attributesConfigPath(project: string, location: string, catalog: string) { return this.pathTemplates.attributesConfigPathTemplate.render({ project: project, location: location, @@ -743,7 +917,9 @@ export class CompletionServiceClient { * @returns {string} A string representing the project. */ matchProjectFromAttributesConfigName(attributesConfigName: string) { - return this.pathTemplates.attributesConfigPathTemplate.match(attributesConfigName).project; + return this.pathTemplates.attributesConfigPathTemplate.match( + attributesConfigName, + ).project; } /** @@ -754,7 +930,9 @@ export class CompletionServiceClient { * @returns {string} A string representing the location. */ matchLocationFromAttributesConfigName(attributesConfigName: string) { - return this.pathTemplates.attributesConfigPathTemplate.match(attributesConfigName).location; + return this.pathTemplates.attributesConfigPathTemplate.match( + attributesConfigName, + ).location; } /** @@ -765,7 +943,9 @@ export class CompletionServiceClient { * @returns {string} A string representing the catalog. */ matchCatalogFromAttributesConfigName(attributesConfigName: string) { - return this.pathTemplates.attributesConfigPathTemplate.match(attributesConfigName).catalog; + return this.pathTemplates.attributesConfigPathTemplate.match( + attributesConfigName, + ).catalog; } /** @@ -777,7 +957,12 @@ export class CompletionServiceClient { * @param {string} branch * @returns {string} Resource name string. */ - branchPath(project:string,location:string,catalog:string,branch:string) { + branchPath( + project: string, + location: string, + catalog: string, + branch: string, + ) { return this.pathTemplates.branchPathTemplate.render({ project: project, location: location, @@ -838,7 +1023,7 @@ export class CompletionServiceClient { * @param {string} catalog * @returns {string} Resource name string. */ - catalogPath(project:string,location:string,catalog:string) { + catalogPath(project: string, location: string, catalog: string) { return this.pathTemplates.catalogPathTemplate.render({ project: project, location: location, @@ -887,7 +1072,7 @@ export class CompletionServiceClient { * @param {string} catalog * @returns {string} Resource name string. */ - completionConfigPath(project:string,location:string,catalog:string) { + completionConfigPath(project: string, location: string, catalog: string) { return this.pathTemplates.completionConfigPathTemplate.render({ project: project, location: location, @@ -903,7 +1088,9 @@ export class CompletionServiceClient { * @returns {string} A string representing the project. */ matchProjectFromCompletionConfigName(completionConfigName: string) { - return this.pathTemplates.completionConfigPathTemplate.match(completionConfigName).project; + return this.pathTemplates.completionConfigPathTemplate.match( + completionConfigName, + ).project; } /** @@ -914,7 +1101,9 @@ export class CompletionServiceClient { * @returns {string} A string representing the location. */ matchLocationFromCompletionConfigName(completionConfigName: string) { - return this.pathTemplates.completionConfigPathTemplate.match(completionConfigName).location; + return this.pathTemplates.completionConfigPathTemplate.match( + completionConfigName, + ).location; } /** @@ -925,7 +1114,9 @@ export class CompletionServiceClient { * @returns {string} A string representing the catalog. */ matchCatalogFromCompletionConfigName(completionConfigName: string) { - return this.pathTemplates.completionConfigPathTemplate.match(completionConfigName).catalog; + return this.pathTemplates.completionConfigPathTemplate.match( + completionConfigName, + ).catalog; } /** @@ -937,7 +1128,12 @@ export class CompletionServiceClient { * @param {string} control * @returns {string} Resource name string. */ - controlPath(project:string,location:string,catalog:string,control:string) { + controlPath( + project: string, + location: string, + catalog: string, + control: string, + ) { return this.pathTemplates.controlPathTemplate.render({ project: project, location: location, @@ -996,7 +1192,7 @@ export class CompletionServiceClient { * @param {string} project * @returns {string} Resource name string. */ - loggingConfigPath(project:string) { + loggingConfigPath(project: string) { return this.pathTemplates.loggingConfigPathTemplate.render({ project: project, }); @@ -1010,7 +1206,8 @@ export class CompletionServiceClient { * @returns {string} A string representing the project. */ matchProjectFromLoggingConfigName(loggingConfigName: string) { - return this.pathTemplates.loggingConfigPathTemplate.match(loggingConfigName).project; + return this.pathTemplates.loggingConfigPathTemplate.match(loggingConfigName) + .project; } /** @@ -1022,7 +1219,12 @@ export class CompletionServiceClient { * @param {string} merchant_center_account_link * @returns {string} Resource name string. */ - merchantCenterAccountLinkPath(project:string,location:string,catalog:string,merchantCenterAccountLink:string) { + merchantCenterAccountLinkPath( + project: string, + location: string, + catalog: string, + merchantCenterAccountLink: string, + ) { return this.pathTemplates.merchantCenterAccountLinkPathTemplate.render({ project: project, location: location, @@ -1038,8 +1240,12 @@ export class CompletionServiceClient { * A fully-qualified path representing MerchantCenterAccountLink resource. * @returns {string} A string representing the project. */ - matchProjectFromMerchantCenterAccountLinkName(merchantCenterAccountLinkName: string) { - return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match(merchantCenterAccountLinkName).project; + matchProjectFromMerchantCenterAccountLinkName( + merchantCenterAccountLinkName: string, + ) { + return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match( + merchantCenterAccountLinkName, + ).project; } /** @@ -1049,8 +1255,12 @@ export class CompletionServiceClient { * A fully-qualified path representing MerchantCenterAccountLink resource. * @returns {string} A string representing the location. */ - matchLocationFromMerchantCenterAccountLinkName(merchantCenterAccountLinkName: string) { - return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match(merchantCenterAccountLinkName).location; + matchLocationFromMerchantCenterAccountLinkName( + merchantCenterAccountLinkName: string, + ) { + return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match( + merchantCenterAccountLinkName, + ).location; } /** @@ -1060,8 +1270,12 @@ export class CompletionServiceClient { * A fully-qualified path representing MerchantCenterAccountLink resource. * @returns {string} A string representing the catalog. */ - matchCatalogFromMerchantCenterAccountLinkName(merchantCenterAccountLinkName: string) { - return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match(merchantCenterAccountLinkName).catalog; + matchCatalogFromMerchantCenterAccountLinkName( + merchantCenterAccountLinkName: string, + ) { + return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match( + merchantCenterAccountLinkName, + ).catalog; } /** @@ -1071,8 +1285,12 @@ export class CompletionServiceClient { * A fully-qualified path representing MerchantCenterAccountLink resource. * @returns {string} A string representing the merchant_center_account_link. */ - matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName(merchantCenterAccountLinkName: string) { - return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match(merchantCenterAccountLinkName).merchant_center_account_link; + matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName( + merchantCenterAccountLinkName: string, + ) { + return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match( + merchantCenterAccountLinkName, + ).merchant_center_account_link; } /** @@ -1084,7 +1302,7 @@ export class CompletionServiceClient { * @param {string} model * @returns {string} Resource name string. */ - modelPath(project:string,location:string,catalog:string,model:string) { + modelPath(project: string, location: string, catalog: string, model: string) { return this.pathTemplates.modelPathTemplate.render({ project: project, location: location, @@ -1147,7 +1365,13 @@ export class CompletionServiceClient { * @param {string} product * @returns {string} Resource name string. */ - productPath(project:string,location:string,catalog:string,branch:string,product:string) { + productPath( + project: string, + location: string, + catalog: string, + branch: string, + product: string, + ) { return this.pathTemplates.productPathTemplate.render({ project: project, location: location, @@ -1218,7 +1442,7 @@ export class CompletionServiceClient { * @param {string} project * @returns {string} Resource name string. */ - retailProjectPath(project:string) { + retailProjectPath(project: string) { return this.pathTemplates.retailProjectPathTemplate.render({ project: project, }); @@ -1232,7 +1456,8 @@ export class CompletionServiceClient { * @returns {string} A string representing the project. */ matchProjectFromRetailProjectName(retailProjectName: string) { - return this.pathTemplates.retailProjectPathTemplate.match(retailProjectName).project; + return this.pathTemplates.retailProjectPathTemplate.match(retailProjectName) + .project; } /** @@ -1244,7 +1469,12 @@ export class CompletionServiceClient { * @param {string} serving_config * @returns {string} Resource name string. */ - servingConfigPath(project:string,location:string,catalog:string,servingConfig:string) { + servingConfigPath( + project: string, + location: string, + catalog: string, + servingConfig: string, + ) { return this.pathTemplates.servingConfigPathTemplate.render({ project: project, location: location, @@ -1261,7 +1491,8 @@ export class CompletionServiceClient { * @returns {string} A string representing the project. */ matchProjectFromServingConfigName(servingConfigName: string) { - return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName).project; + return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName) + .project; } /** @@ -1272,7 +1503,8 @@ export class CompletionServiceClient { * @returns {string} A string representing the location. */ matchLocationFromServingConfigName(servingConfigName: string) { - return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName).location; + return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName) + .location; } /** @@ -1283,7 +1515,8 @@ export class CompletionServiceClient { * @returns {string} A string representing the catalog. */ matchCatalogFromServingConfigName(servingConfigName: string) { - return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName).catalog; + return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName) + .catalog; } /** @@ -1294,7 +1527,8 @@ export class CompletionServiceClient { * @returns {string} A string representing the serving_config. */ matchServingConfigFromServingConfigName(servingConfigName: string) { - return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName).serving_config; + return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName) + .serving_config; } /** @@ -1305,7 +1539,7 @@ export class CompletionServiceClient { */ close(): Promise { if (this.completionServiceStub && !this._terminated) { - return this.completionServiceStub.then(stub => { + return this.completionServiceStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -1314,4 +1548,4 @@ export class CompletionServiceClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/core/generator/gapic-generator-typescript/baselines/retail/src/v2alpha/control_service_client.ts.baseline b/core/generator/gapic-generator-typescript/baselines/retail/src/v2alpha/control_service_client.ts.baseline index 1c2779ad8eba..5726bc0add92 100644 --- a/core/generator/gapic-generator-typescript/baselines/retail/src/v2alpha/control_service_client.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/retail/src/v2alpha/control_service_client.ts.baseline @@ -18,11 +18,18 @@ /* global window */ import type * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions, PaginationCallback, GaxCall} from 'google-gax'; -import {Transform} from 'stream'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + PaginationCallback, + GaxCall, +} from 'google-gax'; +import { Transform } from 'stream'; import * as protos from '../../protos/protos'; import jsonProtos = require('../../protos/protos.json'); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; /** * Client JSON configuration object, loaded from @@ -44,7 +51,7 @@ export class ControlServiceClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('retail'); @@ -57,9 +64,9 @@ export class ControlServiceClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; - controlServiceStub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; + controlServiceStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of ControlServiceClient. @@ -100,21 +107,42 @@ export class ControlServiceClient { * const client = new ControlServiceClient({fallback: true}, gax); * ``` */ - constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { // Ensure that options include all the required fields. const staticMembers = this.constructor as typeof ControlServiceClient; - if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { - throw new Error('Please set either universe_domain or universeDomain, but not both.'); + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); } - const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; - this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; this._servicePath = 'retail.' + this._universeDomain; - const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; - const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. if (servicePath !== this._servicePath && !('scopes' in opts)) { @@ -136,7 +164,7 @@ export class ControlServiceClient { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; @@ -150,10 +178,7 @@ export class ControlServiceClient { } // Determine the client header string. - const clientHeader = [ - `gax/${this._gaxModule.version}`, - `gapic/${version}`, - ]; + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/${process.versions.node}`); } else { @@ -175,40 +200,40 @@ export class ControlServiceClient { // Create useful helper objects for these. this.pathTemplates = { alertConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/alertConfig' + 'projects/{project}/alertConfig', ), attributesConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/attributesConfig' + 'projects/{project}/locations/{location}/catalogs/{catalog}/attributesConfig', ), branchPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}', ), catalogPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}' + 'projects/{project}/locations/{location}/catalogs/{catalog}', ), completionConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/completionConfig' + 'projects/{project}/locations/{location}/catalogs/{catalog}/completionConfig', ), controlPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/controls/{control}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/controls/{control}', ), loggingConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/loggingConfig' + 'projects/{project}/loggingConfig', ), merchantCenterAccountLinkPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/merchantCenterAccountLinks/{merchant_center_account_link}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/merchantCenterAccountLinks/{merchant_center_account_link}', ), modelPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/models/{model}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/models/{model}', ), productPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}', ), retailProjectPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/retailProject' + 'projects/{project}/retailProject', ), servingConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/servingConfigs/{serving_config}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/servingConfigs/{serving_config}', ), }; @@ -216,14 +241,20 @@ export class ControlServiceClient { // (e.g. 50 results at a time, with tokens to get subsequent // pages). Denote the keys used for pagination and results. this.descriptors.page = { - listControls: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'controls') + listControls: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'controls', + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.cloud.retail.v2alpha.ControlService', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.cloud.retail.v2alpha.ControlService', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + { 'x-goog-api-client': clientHeader.join(' ') }, + ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -254,37 +285,46 @@ export class ControlServiceClient { // Put together the "service stub" for // google.cloud.retail.v2alpha.ControlService. this.controlServiceStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.cloud.retail.v2alpha.ControlService') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.cloud.retail.v2alpha.ControlService', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.cloud.retail.v2alpha.ControlService, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts, + this._providedCustomServicePath, + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const controlServiceStubMethods = - ['createControl', 'deleteControl', 'updateControl', 'getControl', 'listControls']; + const controlServiceStubMethods = [ + 'createControl', + 'deleteControl', + 'updateControl', + 'getControl', + 'listControls', + ]; for (const methodName of controlServiceStubMethods) { const callPromise = this.controlServiceStub.then( - stub => (...args: Array<{}>) => { - if (this._terminated) { - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error|null|undefined) => () => { + (stub) => + (...args: Array<{}>) => { + if (this._terminated) { + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { throw err; - }); + }, + ); - const descriptor = - this.descriptors.page[methodName] || - undefined; + const descriptor = this.descriptors.page[methodName] || undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -299,8 +339,14 @@ export class ControlServiceClient { * @returns {string} The DNS address for this service. */ static get servicePath() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'retail.googleapis.com'; } @@ -311,8 +357,14 @@ export class ControlServiceClient { * @returns {string} The DNS address for this service. */ static get apiEndpoint() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'retail.googleapis.com'; } @@ -343,9 +395,7 @@ export class ControlServiceClient { * @returns {string[]} List of default scopes. */ static get scopes() { - return [ - 'https://www.googleapis.com/auth/cloud-platform' - ]; + return ['https://www.googleapis.com/auth/cloud-platform']; } getProjectId(): Promise; @@ -354,8 +404,9 @@ export class ControlServiceClient { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId(callback?: Callback): - Promise|void { + getProjectId( + callback?: Callback, + ): Promise | void { if (callback) { this.auth.getProjectId(callback); return; @@ -366,505 +417,684 @@ export class ControlServiceClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Creates a Control. - * - * If the {@link protos.google.cloud.retail.v2alpha.Control|Control} to create already - * exists, an ALREADY_EXISTS error is returned. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. Full resource name of parent catalog. Format: - * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}` - * @param {google.cloud.retail.v2alpha.Control} request.control - * Required. The Control to create. - * @param {string} request.controlId - * Required. The ID to use for the Control, which will become the final - * component of the Control's resource name. - * - * This value should be 4-63 characters, and valid characters - * are /{@link protos.0-9|a-z}-_/. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.Control|Control}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/control_service.create_control.js - * region_tag:retail_v2alpha_generated_ControlService_CreateControl_async - */ + /** + * Creates a Control. + * + * If the {@link protos.google.cloud.retail.v2alpha.Control|Control} to create already + * exists, an ALREADY_EXISTS error is returned. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Full resource name of parent catalog. Format: + * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}` + * @param {google.cloud.retail.v2alpha.Control} request.control + * Required. The Control to create. + * @param {string} request.controlId + * Required. The ID to use for the Control, which will become the final + * component of the Control's resource name. + * + * This value should be 4-63 characters, and valid characters + * are /{@link protos.0-9|a-z}-_/. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.Control|Control}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/control_service.create_control.js + * region_tag:retail_v2alpha_generated_ControlService_CreateControl_async + */ createControl( - request?: protos.google.cloud.retail.v2alpha.ICreateControlRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.retail.v2alpha.IControl, - protos.google.cloud.retail.v2alpha.ICreateControlRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.ICreateControlRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IControl, + protos.google.cloud.retail.v2alpha.ICreateControlRequest | undefined, + {} | undefined, + ] + >; createControl( - request: protos.google.cloud.retail.v2alpha.ICreateControlRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.retail.v2alpha.IControl, - protos.google.cloud.retail.v2alpha.ICreateControlRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.ICreateControlRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.retail.v2alpha.IControl, + | protos.google.cloud.retail.v2alpha.ICreateControlRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createControl( - request: protos.google.cloud.retail.v2alpha.ICreateControlRequest, - callback: Callback< - protos.google.cloud.retail.v2alpha.IControl, - protos.google.cloud.retail.v2alpha.ICreateControlRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.ICreateControlRequest, + callback: Callback< + protos.google.cloud.retail.v2alpha.IControl, + | protos.google.cloud.retail.v2alpha.ICreateControlRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createControl( - request?: protos.google.cloud.retail.v2alpha.ICreateControlRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.cloud.retail.v2alpha.ICreateControlRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.retail.v2alpha.IControl, - protos.google.cloud.retail.v2alpha.ICreateControlRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.cloud.retail.v2alpha.IControl, - protos.google.cloud.retail.v2alpha.ICreateControlRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.retail.v2alpha.IControl, - protos.google.cloud.retail.v2alpha.ICreateControlRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.retail.v2alpha.ICreateControlRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.retail.v2alpha.IControl, + | protos.google.cloud.retail.v2alpha.ICreateControlRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IControl, + protos.google.cloud.retail.v2alpha.ICreateControlRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('createControl request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.retail.v2alpha.IControl, - protos.google.cloud.retail.v2alpha.ICreateControlRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.retail.v2alpha.IControl, + | protos.google.cloud.retail.v2alpha.ICreateControlRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createControl response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.createControl(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.retail.v2alpha.IControl, - protos.google.cloud.retail.v2alpha.ICreateControlRequest|undefined, - {}|undefined - ]) => { - this._log.info('createControl response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createControl(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.retail.v2alpha.IControl, + protos.google.cloud.retail.v2alpha.ICreateControlRequest | undefined, + {} | undefined, + ]) => { + this._log.info('createControl response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Deletes a Control. - * - * If the {@link protos.google.cloud.retail.v2alpha.Control|Control} to delete does not - * exist, a NOT_FOUND error is returned. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The resource name of the Control to delete. Format: - * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/controls/{control_id}` - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/control_service.delete_control.js - * region_tag:retail_v2alpha_generated_ControlService_DeleteControl_async - */ + /** + * Deletes a Control. + * + * If the {@link protos.google.cloud.retail.v2alpha.Control|Control} to delete does not + * exist, a NOT_FOUND error is returned. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The resource name of the Control to delete. Format: + * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/controls/{control_id}` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/control_service.delete_control.js + * region_tag:retail_v2alpha_generated_ControlService_DeleteControl_async + */ deleteControl( - request?: protos.google.cloud.retail.v2alpha.IDeleteControlRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.cloud.retail.v2alpha.IDeleteControlRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.IDeleteControlRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.cloud.retail.v2alpha.IDeleteControlRequest | undefined, + {} | undefined, + ] + >; deleteControl( - request: protos.google.cloud.retail.v2alpha.IDeleteControlRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.cloud.retail.v2alpha.IDeleteControlRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IDeleteControlRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.cloud.retail.v2alpha.IDeleteControlRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteControl( - request: protos.google.cloud.retail.v2alpha.IDeleteControlRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.cloud.retail.v2alpha.IDeleteControlRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IDeleteControlRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.cloud.retail.v2alpha.IDeleteControlRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteControl( - request?: protos.google.cloud.retail.v2alpha.IDeleteControlRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.cloud.retail.v2alpha.IDeleteControlRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.cloud.retail.v2alpha.IDeleteControlRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.protobuf.IEmpty, - protos.google.cloud.retail.v2alpha.IDeleteControlRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.cloud.retail.v2alpha.IDeleteControlRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.retail.v2alpha.IDeleteControlRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + | protos.google.cloud.retail.v2alpha.IDeleteControlRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.cloud.retail.v2alpha.IDeleteControlRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('deleteControl request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.cloud.retail.v2alpha.IDeleteControlRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.cloud.retail.v2alpha.IDeleteControlRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteControl response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.deleteControl(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.cloud.retail.v2alpha.IDeleteControlRequest|undefined, - {}|undefined - ]) => { - this._log.info('deleteControl response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteControl(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.cloud.retail.v2alpha.IDeleteControlRequest | undefined, + {} | undefined, + ]) => { + this._log.info('deleteControl response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Updates a Control. - * - * {@link protos.google.cloud.retail.v2alpha.Control|Control} cannot be set to a different - * oneof field, if so an INVALID_ARGUMENT is returned. If the - * {@link protos.google.cloud.retail.v2alpha.Control|Control} to update does not exist, a - * NOT_FOUND error is returned. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.cloud.retail.v2alpha.Control} request.control - * Required. The Control to update. - * @param {google.protobuf.FieldMask} request.updateMask - * Indicates which fields in the provided - * {@link protos.google.cloud.retail.v2alpha.Control|Control} to update. The following are - * NOT supported: - * - * * {@link protos.google.cloud.retail.v2alpha.Control.name|Control.name} - * - * If not set or empty, all supported fields are updated. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.Control|Control}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/control_service.update_control.js - * region_tag:retail_v2alpha_generated_ControlService_UpdateControl_async - */ + /** + * Updates a Control. + * + * {@link protos.google.cloud.retail.v2alpha.Control|Control} cannot be set to a different + * oneof field, if so an INVALID_ARGUMENT is returned. If the + * {@link protos.google.cloud.retail.v2alpha.Control|Control} to update does not exist, a + * NOT_FOUND error is returned. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.cloud.retail.v2alpha.Control} request.control + * Required. The Control to update. + * @param {google.protobuf.FieldMask} request.updateMask + * Indicates which fields in the provided + * {@link protos.google.cloud.retail.v2alpha.Control|Control} to update. The following are + * NOT supported: + * + * * {@link protos.google.cloud.retail.v2alpha.Control.name|Control.name} + * + * If not set or empty, all supported fields are updated. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.Control|Control}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/control_service.update_control.js + * region_tag:retail_v2alpha_generated_ControlService_UpdateControl_async + */ updateControl( - request?: protos.google.cloud.retail.v2alpha.IUpdateControlRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.retail.v2alpha.IControl, - protos.google.cloud.retail.v2alpha.IUpdateControlRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.IUpdateControlRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IControl, + protos.google.cloud.retail.v2alpha.IUpdateControlRequest | undefined, + {} | undefined, + ] + >; updateControl( - request: protos.google.cloud.retail.v2alpha.IUpdateControlRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.retail.v2alpha.IControl, - protos.google.cloud.retail.v2alpha.IUpdateControlRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IUpdateControlRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.retail.v2alpha.IControl, + | protos.google.cloud.retail.v2alpha.IUpdateControlRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateControl( - request: protos.google.cloud.retail.v2alpha.IUpdateControlRequest, - callback: Callback< - protos.google.cloud.retail.v2alpha.IControl, - protos.google.cloud.retail.v2alpha.IUpdateControlRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IUpdateControlRequest, + callback: Callback< + protos.google.cloud.retail.v2alpha.IControl, + | protos.google.cloud.retail.v2alpha.IUpdateControlRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateControl( - request?: protos.google.cloud.retail.v2alpha.IUpdateControlRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.retail.v2alpha.IControl, - protos.google.cloud.retail.v2alpha.IUpdateControlRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.retail.v2alpha.IUpdateControlRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.retail.v2alpha.IControl, - protos.google.cloud.retail.v2alpha.IUpdateControlRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.retail.v2alpha.IControl, - protos.google.cloud.retail.v2alpha.IUpdateControlRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.retail.v2alpha.IUpdateControlRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.retail.v2alpha.IControl, + | protos.google.cloud.retail.v2alpha.IUpdateControlRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IControl, + protos.google.cloud.retail.v2alpha.IUpdateControlRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'control.name': request.control!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'control.name': request.control!.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateControl request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.retail.v2alpha.IControl, - protos.google.cloud.retail.v2alpha.IUpdateControlRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.retail.v2alpha.IControl, + | protos.google.cloud.retail.v2alpha.IUpdateControlRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateControl response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.updateControl(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.retail.v2alpha.IControl, - protos.google.cloud.retail.v2alpha.IUpdateControlRequest|undefined, - {}|undefined - ]) => { - this._log.info('updateControl response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateControl(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.retail.v2alpha.IControl, + protos.google.cloud.retail.v2alpha.IUpdateControlRequest | undefined, + {} | undefined, + ]) => { + this._log.info('updateControl response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Gets a Control. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The resource name of the Control to get. Format: - * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/controls/{control_id}` - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.Control|Control}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/control_service.get_control.js - * region_tag:retail_v2alpha_generated_ControlService_GetControl_async - */ + /** + * Gets a Control. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The resource name of the Control to get. Format: + * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/controls/{control_id}` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.Control|Control}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/control_service.get_control.js + * region_tag:retail_v2alpha_generated_ControlService_GetControl_async + */ getControl( - request?: protos.google.cloud.retail.v2alpha.IGetControlRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.retail.v2alpha.IControl, - protos.google.cloud.retail.v2alpha.IGetControlRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.IGetControlRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IControl, + protos.google.cloud.retail.v2alpha.IGetControlRequest | undefined, + {} | undefined, + ] + >; getControl( - request: protos.google.cloud.retail.v2alpha.IGetControlRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.retail.v2alpha.IControl, - protos.google.cloud.retail.v2alpha.IGetControlRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IGetControlRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.retail.v2alpha.IControl, + protos.google.cloud.retail.v2alpha.IGetControlRequest | null | undefined, + {} | null | undefined + >, + ): void; getControl( - request: protos.google.cloud.retail.v2alpha.IGetControlRequest, - callback: Callback< - protos.google.cloud.retail.v2alpha.IControl, - protos.google.cloud.retail.v2alpha.IGetControlRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IGetControlRequest, + callback: Callback< + protos.google.cloud.retail.v2alpha.IControl, + protos.google.cloud.retail.v2alpha.IGetControlRequest | null | undefined, + {} | null | undefined + >, + ): void; getControl( - request?: protos.google.cloud.retail.v2alpha.IGetControlRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.retail.v2alpha.IControl, - protos.google.cloud.retail.v2alpha.IGetControlRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.retail.v2alpha.IGetControlRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.retail.v2alpha.IControl, - protos.google.cloud.retail.v2alpha.IGetControlRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.retail.v2alpha.IControl, - protos.google.cloud.retail.v2alpha.IGetControlRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.retail.v2alpha.IGetControlRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.retail.v2alpha.IControl, + protos.google.cloud.retail.v2alpha.IGetControlRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IControl, + protos.google.cloud.retail.v2alpha.IGetControlRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getControl request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.retail.v2alpha.IControl, - protos.google.cloud.retail.v2alpha.IGetControlRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.retail.v2alpha.IControl, + | protos.google.cloud.retail.v2alpha.IGetControlRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getControl response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getControl(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.retail.v2alpha.IControl, - protos.google.cloud.retail.v2alpha.IGetControlRequest|undefined, - {}|undefined - ]) => { - this._log.info('getControl response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getControl(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.retail.v2alpha.IControl, + protos.google.cloud.retail.v2alpha.IGetControlRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getControl response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } - /** - * Lists all Controls by their parent - * {@link protos.google.cloud.retail.v2alpha.Catalog|Catalog}. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The catalog resource name. Format: - * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}` - * @param {number} [request.pageSize] - * Optional. Maximum number of results to return. If unspecified, defaults - * to 50. Max allowed value is 1000. - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous `ListControls` call. - * Provide this to retrieve the subsequent page. - * @param {string} [request.filter] - * Optional. A filter to apply on the list results. Supported features: - * - * * List all the products under the parent branch if - * {@link protos.google.cloud.retail.v2alpha.ListControlsRequest.filter|filter} is unset. - * * List controls that are used in a single ServingConfig: - * 'serving_config = "boosted_home_page_cvr"' - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.cloud.retail.v2alpha.Control|Control}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `listControlsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Lists all Controls by their parent + * {@link protos.google.cloud.retail.v2alpha.Catalog|Catalog}. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The catalog resource name. Format: + * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}` + * @param {number} [request.pageSize] + * Optional. Maximum number of results to return. If unspecified, defaults + * to 50. Max allowed value is 1000. + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListControls` call. + * Provide this to retrieve the subsequent page. + * @param {string} [request.filter] + * Optional. A filter to apply on the list results. Supported features: + * + * * List all the products under the parent branch if + * {@link protos.google.cloud.retail.v2alpha.ListControlsRequest.filter|filter} is unset. + * * List controls that are used in a single ServingConfig: + * 'serving_config = "boosted_home_page_cvr"' + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.cloud.retail.v2alpha.Control|Control}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listControlsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listControls( - request?: protos.google.cloud.retail.v2alpha.IListControlsRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.retail.v2alpha.IControl[], - protos.google.cloud.retail.v2alpha.IListControlsRequest|null, - protos.google.cloud.retail.v2alpha.IListControlsResponse - ]>; + request?: protos.google.cloud.retail.v2alpha.IListControlsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IControl[], + protos.google.cloud.retail.v2alpha.IListControlsRequest | null, + protos.google.cloud.retail.v2alpha.IListControlsResponse, + ] + >; listControls( - request: protos.google.cloud.retail.v2alpha.IListControlsRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.cloud.retail.v2alpha.IListControlsRequest, - protos.google.cloud.retail.v2alpha.IListControlsResponse|null|undefined, - protos.google.cloud.retail.v2alpha.IControl>): void; + request: protos.google.cloud.retail.v2alpha.IListControlsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.cloud.retail.v2alpha.IListControlsRequest, + | protos.google.cloud.retail.v2alpha.IListControlsResponse + | null + | undefined, + protos.google.cloud.retail.v2alpha.IControl + >, + ): void; listControls( - request: protos.google.cloud.retail.v2alpha.IListControlsRequest, - callback: PaginationCallback< - protos.google.cloud.retail.v2alpha.IListControlsRequest, - protos.google.cloud.retail.v2alpha.IListControlsResponse|null|undefined, - protos.google.cloud.retail.v2alpha.IControl>): void; + request: protos.google.cloud.retail.v2alpha.IListControlsRequest, + callback: PaginationCallback< + protos.google.cloud.retail.v2alpha.IListControlsRequest, + | protos.google.cloud.retail.v2alpha.IListControlsResponse + | null + | undefined, + protos.google.cloud.retail.v2alpha.IControl + >, + ): void; listControls( - request?: protos.google.cloud.retail.v2alpha.IListControlsRequest, - optionsOrCallback?: CallOptions|PaginationCallback< + request?: protos.google.cloud.retail.v2alpha.IListControlsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.cloud.retail.v2alpha.IListControlsRequest, - protos.google.cloud.retail.v2alpha.IListControlsResponse|null|undefined, - protos.google.cloud.retail.v2alpha.IControl>, - callback?: PaginationCallback< - protos.google.cloud.retail.v2alpha.IListControlsRequest, - protos.google.cloud.retail.v2alpha.IListControlsResponse|null|undefined, - protos.google.cloud.retail.v2alpha.IControl>): - Promise<[ - protos.google.cloud.retail.v2alpha.IControl[], - protos.google.cloud.retail.v2alpha.IListControlsRequest|null, - protos.google.cloud.retail.v2alpha.IListControlsResponse - ]>|void { + | protos.google.cloud.retail.v2alpha.IListControlsResponse + | null + | undefined, + protos.google.cloud.retail.v2alpha.IControl + >, + callback?: PaginationCallback< + protos.google.cloud.retail.v2alpha.IListControlsRequest, + | protos.google.cloud.retail.v2alpha.IListControlsResponse + | null + | undefined, + protos.google.cloud.retail.v2alpha.IControl + >, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IControl[], + protos.google.cloud.retail.v2alpha.IListControlsRequest | null, + protos.google.cloud.retail.v2alpha.IListControlsResponse, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.cloud.retail.v2alpha.IListControlsRequest, - protos.google.cloud.retail.v2alpha.IListControlsResponse|null|undefined, - protos.google.cloud.retail.v2alpha.IControl>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.cloud.retail.v2alpha.IListControlsRequest, + | protos.google.cloud.retail.v2alpha.IListControlsResponse + | null + | undefined, + protos.google.cloud.retail.v2alpha.IControl + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listControls values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -873,126 +1103,130 @@ export class ControlServiceClient { this._log.info('listControls request %j', request); return this.innerApiCalls .listControls(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.cloud.retail.v2alpha.IControl[], - protos.google.cloud.retail.v2alpha.IListControlsRequest|null, - protos.google.cloud.retail.v2alpha.IListControlsResponse - ]) => { - this._log.info('listControls values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.cloud.retail.v2alpha.IControl[], + protos.google.cloud.retail.v2alpha.IListControlsRequest | null, + protos.google.cloud.retail.v2alpha.IListControlsResponse, + ]) => { + this._log.info('listControls values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listControls`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The catalog resource name. Format: - * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}` - * @param {number} [request.pageSize] - * Optional. Maximum number of results to return. If unspecified, defaults - * to 50. Max allowed value is 1000. - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous `ListControls` call. - * Provide this to retrieve the subsequent page. - * @param {string} [request.filter] - * Optional. A filter to apply on the list results. Supported features: - * - * * List all the products under the parent branch if - * {@link protos.google.cloud.retail.v2alpha.ListControlsRequest.filter|filter} is unset. - * * List controls that are used in a single ServingConfig: - * 'serving_config = "boosted_home_page_cvr"' - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.cloud.retail.v2alpha.Control|Control} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `listControlsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `listControls`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The catalog resource name. Format: + * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}` + * @param {number} [request.pageSize] + * Optional. Maximum number of results to return. If unspecified, defaults + * to 50. Max allowed value is 1000. + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListControls` call. + * Provide this to retrieve the subsequent page. + * @param {string} [request.filter] + * Optional. A filter to apply on the list results. Supported features: + * + * * List all the products under the parent branch if + * {@link protos.google.cloud.retail.v2alpha.ListControlsRequest.filter|filter} is unset. + * * List controls that are used in a single ServingConfig: + * 'serving_config = "boosted_home_page_cvr"' + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.cloud.retail.v2alpha.Control|Control} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listControlsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listControlsStream( - request?: protos.google.cloud.retail.v2alpha.IListControlsRequest, - options?: CallOptions): - Transform{ + request?: protos.google.cloud.retail.v2alpha.IListControlsRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); const defaultCallSettings = this._defaults['listControls']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listControls stream %j', request); return this.descriptors.page.listControls.createStream( this.innerApiCalls.listControls as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listControls`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The catalog resource name. Format: - * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}` - * @param {number} [request.pageSize] - * Optional. Maximum number of results to return. If unspecified, defaults - * to 50. Max allowed value is 1000. - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous `ListControls` call. - * Provide this to retrieve the subsequent page. - * @param {string} [request.filter] - * Optional. A filter to apply on the list results. Supported features: - * - * * List all the products under the parent branch if - * {@link protos.google.cloud.retail.v2alpha.ListControlsRequest.filter|filter} is unset. - * * List controls that are used in a single ServingConfig: - * 'serving_config = "boosted_home_page_cvr"' - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.cloud.retail.v2alpha.Control|Control}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/control_service.list_controls.js - * region_tag:retail_v2alpha_generated_ControlService_ListControls_async - */ + /** + * Equivalent to `listControls`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The catalog resource name. Format: + * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}` + * @param {number} [request.pageSize] + * Optional. Maximum number of results to return. If unspecified, defaults + * to 50. Max allowed value is 1000. + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListControls` call. + * Provide this to retrieve the subsequent page. + * @param {string} [request.filter] + * Optional. A filter to apply on the list results. Supported features: + * + * * List all the products under the parent branch if + * {@link protos.google.cloud.retail.v2alpha.ListControlsRequest.filter|filter} is unset. + * * List controls that are used in a single ServingConfig: + * 'serving_config = "boosted_home_page_cvr"' + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.cloud.retail.v2alpha.Control|Control}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/control_service.list_controls.js + * region_tag:retail_v2alpha_generated_ControlService_ListControls_async + */ listControlsAsync( - request?: protos.google.cloud.retail.v2alpha.IListControlsRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.cloud.retail.v2alpha.IListControlsRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); const defaultCallSettings = this._defaults['listControls']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listControls iterate %j', request); return this.descriptors.page.listControls.asyncIterate( this.innerApiCalls['listControls'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } // -------------------- @@ -1005,7 +1239,7 @@ export class ControlServiceClient { * @param {string} project * @returns {string} Resource name string. */ - alertConfigPath(project:string) { + alertConfigPath(project: string) { return this.pathTemplates.alertConfigPathTemplate.render({ project: project, }); @@ -1019,7 +1253,8 @@ export class ControlServiceClient { * @returns {string} A string representing the project. */ matchProjectFromAlertConfigName(alertConfigName: string) { - return this.pathTemplates.alertConfigPathTemplate.match(alertConfigName).project; + return this.pathTemplates.alertConfigPathTemplate.match(alertConfigName) + .project; } /** @@ -1030,7 +1265,7 @@ export class ControlServiceClient { * @param {string} catalog * @returns {string} Resource name string. */ - attributesConfigPath(project:string,location:string,catalog:string) { + attributesConfigPath(project: string, location: string, catalog: string) { return this.pathTemplates.attributesConfigPathTemplate.render({ project: project, location: location, @@ -1046,7 +1281,9 @@ export class ControlServiceClient { * @returns {string} A string representing the project. */ matchProjectFromAttributesConfigName(attributesConfigName: string) { - return this.pathTemplates.attributesConfigPathTemplate.match(attributesConfigName).project; + return this.pathTemplates.attributesConfigPathTemplate.match( + attributesConfigName, + ).project; } /** @@ -1057,7 +1294,9 @@ export class ControlServiceClient { * @returns {string} A string representing the location. */ matchLocationFromAttributesConfigName(attributesConfigName: string) { - return this.pathTemplates.attributesConfigPathTemplate.match(attributesConfigName).location; + return this.pathTemplates.attributesConfigPathTemplate.match( + attributesConfigName, + ).location; } /** @@ -1068,7 +1307,9 @@ export class ControlServiceClient { * @returns {string} A string representing the catalog. */ matchCatalogFromAttributesConfigName(attributesConfigName: string) { - return this.pathTemplates.attributesConfigPathTemplate.match(attributesConfigName).catalog; + return this.pathTemplates.attributesConfigPathTemplate.match( + attributesConfigName, + ).catalog; } /** @@ -1080,7 +1321,12 @@ export class ControlServiceClient { * @param {string} branch * @returns {string} Resource name string. */ - branchPath(project:string,location:string,catalog:string,branch:string) { + branchPath( + project: string, + location: string, + catalog: string, + branch: string, + ) { return this.pathTemplates.branchPathTemplate.render({ project: project, location: location, @@ -1141,7 +1387,7 @@ export class ControlServiceClient { * @param {string} catalog * @returns {string} Resource name string. */ - catalogPath(project:string,location:string,catalog:string) { + catalogPath(project: string, location: string, catalog: string) { return this.pathTemplates.catalogPathTemplate.render({ project: project, location: location, @@ -1190,7 +1436,7 @@ export class ControlServiceClient { * @param {string} catalog * @returns {string} Resource name string. */ - completionConfigPath(project:string,location:string,catalog:string) { + completionConfigPath(project: string, location: string, catalog: string) { return this.pathTemplates.completionConfigPathTemplate.render({ project: project, location: location, @@ -1206,7 +1452,9 @@ export class ControlServiceClient { * @returns {string} A string representing the project. */ matchProjectFromCompletionConfigName(completionConfigName: string) { - return this.pathTemplates.completionConfigPathTemplate.match(completionConfigName).project; + return this.pathTemplates.completionConfigPathTemplate.match( + completionConfigName, + ).project; } /** @@ -1217,7 +1465,9 @@ export class ControlServiceClient { * @returns {string} A string representing the location. */ matchLocationFromCompletionConfigName(completionConfigName: string) { - return this.pathTemplates.completionConfigPathTemplate.match(completionConfigName).location; + return this.pathTemplates.completionConfigPathTemplate.match( + completionConfigName, + ).location; } /** @@ -1228,7 +1478,9 @@ export class ControlServiceClient { * @returns {string} A string representing the catalog. */ matchCatalogFromCompletionConfigName(completionConfigName: string) { - return this.pathTemplates.completionConfigPathTemplate.match(completionConfigName).catalog; + return this.pathTemplates.completionConfigPathTemplate.match( + completionConfigName, + ).catalog; } /** @@ -1240,7 +1492,12 @@ export class ControlServiceClient { * @param {string} control * @returns {string} Resource name string. */ - controlPath(project:string,location:string,catalog:string,control:string) { + controlPath( + project: string, + location: string, + catalog: string, + control: string, + ) { return this.pathTemplates.controlPathTemplate.render({ project: project, location: location, @@ -1299,7 +1556,7 @@ export class ControlServiceClient { * @param {string} project * @returns {string} Resource name string. */ - loggingConfigPath(project:string) { + loggingConfigPath(project: string) { return this.pathTemplates.loggingConfigPathTemplate.render({ project: project, }); @@ -1313,7 +1570,8 @@ export class ControlServiceClient { * @returns {string} A string representing the project. */ matchProjectFromLoggingConfigName(loggingConfigName: string) { - return this.pathTemplates.loggingConfigPathTemplate.match(loggingConfigName).project; + return this.pathTemplates.loggingConfigPathTemplate.match(loggingConfigName) + .project; } /** @@ -1325,7 +1583,12 @@ export class ControlServiceClient { * @param {string} merchant_center_account_link * @returns {string} Resource name string. */ - merchantCenterAccountLinkPath(project:string,location:string,catalog:string,merchantCenterAccountLink:string) { + merchantCenterAccountLinkPath( + project: string, + location: string, + catalog: string, + merchantCenterAccountLink: string, + ) { return this.pathTemplates.merchantCenterAccountLinkPathTemplate.render({ project: project, location: location, @@ -1341,8 +1604,12 @@ export class ControlServiceClient { * A fully-qualified path representing MerchantCenterAccountLink resource. * @returns {string} A string representing the project. */ - matchProjectFromMerchantCenterAccountLinkName(merchantCenterAccountLinkName: string) { - return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match(merchantCenterAccountLinkName).project; + matchProjectFromMerchantCenterAccountLinkName( + merchantCenterAccountLinkName: string, + ) { + return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match( + merchantCenterAccountLinkName, + ).project; } /** @@ -1352,8 +1619,12 @@ export class ControlServiceClient { * A fully-qualified path representing MerchantCenterAccountLink resource. * @returns {string} A string representing the location. */ - matchLocationFromMerchantCenterAccountLinkName(merchantCenterAccountLinkName: string) { - return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match(merchantCenterAccountLinkName).location; + matchLocationFromMerchantCenterAccountLinkName( + merchantCenterAccountLinkName: string, + ) { + return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match( + merchantCenterAccountLinkName, + ).location; } /** @@ -1363,8 +1634,12 @@ export class ControlServiceClient { * A fully-qualified path representing MerchantCenterAccountLink resource. * @returns {string} A string representing the catalog. */ - matchCatalogFromMerchantCenterAccountLinkName(merchantCenterAccountLinkName: string) { - return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match(merchantCenterAccountLinkName).catalog; + matchCatalogFromMerchantCenterAccountLinkName( + merchantCenterAccountLinkName: string, + ) { + return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match( + merchantCenterAccountLinkName, + ).catalog; } /** @@ -1374,8 +1649,12 @@ export class ControlServiceClient { * A fully-qualified path representing MerchantCenterAccountLink resource. * @returns {string} A string representing the merchant_center_account_link. */ - matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName(merchantCenterAccountLinkName: string) { - return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match(merchantCenterAccountLinkName).merchant_center_account_link; + matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName( + merchantCenterAccountLinkName: string, + ) { + return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match( + merchantCenterAccountLinkName, + ).merchant_center_account_link; } /** @@ -1387,7 +1666,7 @@ export class ControlServiceClient { * @param {string} model * @returns {string} Resource name string. */ - modelPath(project:string,location:string,catalog:string,model:string) { + modelPath(project: string, location: string, catalog: string, model: string) { return this.pathTemplates.modelPathTemplate.render({ project: project, location: location, @@ -1450,7 +1729,13 @@ export class ControlServiceClient { * @param {string} product * @returns {string} Resource name string. */ - productPath(project:string,location:string,catalog:string,branch:string,product:string) { + productPath( + project: string, + location: string, + catalog: string, + branch: string, + product: string, + ) { return this.pathTemplates.productPathTemplate.render({ project: project, location: location, @@ -1521,7 +1806,7 @@ export class ControlServiceClient { * @param {string} project * @returns {string} Resource name string. */ - retailProjectPath(project:string) { + retailProjectPath(project: string) { return this.pathTemplates.retailProjectPathTemplate.render({ project: project, }); @@ -1535,7 +1820,8 @@ export class ControlServiceClient { * @returns {string} A string representing the project. */ matchProjectFromRetailProjectName(retailProjectName: string) { - return this.pathTemplates.retailProjectPathTemplate.match(retailProjectName).project; + return this.pathTemplates.retailProjectPathTemplate.match(retailProjectName) + .project; } /** @@ -1547,7 +1833,12 @@ export class ControlServiceClient { * @param {string} serving_config * @returns {string} Resource name string. */ - servingConfigPath(project:string,location:string,catalog:string,servingConfig:string) { + servingConfigPath( + project: string, + location: string, + catalog: string, + servingConfig: string, + ) { return this.pathTemplates.servingConfigPathTemplate.render({ project: project, location: location, @@ -1564,7 +1855,8 @@ export class ControlServiceClient { * @returns {string} A string representing the project. */ matchProjectFromServingConfigName(servingConfigName: string) { - return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName).project; + return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName) + .project; } /** @@ -1575,7 +1867,8 @@ export class ControlServiceClient { * @returns {string} A string representing the location. */ matchLocationFromServingConfigName(servingConfigName: string) { - return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName).location; + return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName) + .location; } /** @@ -1586,7 +1879,8 @@ export class ControlServiceClient { * @returns {string} A string representing the catalog. */ matchCatalogFromServingConfigName(servingConfigName: string) { - return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName).catalog; + return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName) + .catalog; } /** @@ -1597,7 +1891,8 @@ export class ControlServiceClient { * @returns {string} A string representing the serving_config. */ matchServingConfigFromServingConfigName(servingConfigName: string) { - return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName).serving_config; + return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName) + .serving_config; } /** @@ -1608,7 +1903,7 @@ export class ControlServiceClient { */ close(): Promise { if (this.controlServiceStub && !this._terminated) { - return this.controlServiceStub.then(stub => { + return this.controlServiceStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -1616,4 +1911,4 @@ export class ControlServiceClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/core/generator/gapic-generator-typescript/baselines/retail/src/v2alpha/conversational_search_service_client.ts.baseline b/core/generator/gapic-generator-typescript/baselines/retail/src/v2alpha/conversational_search_service_client.ts.baseline index 8f3f06d2f6c3..5f611881f465 100644 --- a/core/generator/gapic-generator-typescript/baselines/retail/src/v2alpha/conversational_search_service_client.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/retail/src/v2alpha/conversational_search_service_client.ts.baseline @@ -18,11 +18,16 @@ /* global window */ import type * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions} from 'google-gax'; -import {PassThrough} from 'stream'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, +} from 'google-gax'; +import { PassThrough } from 'stream'; import * as protos from '../../protos/protos'; import jsonProtos = require('../../protos/protos.json'); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; /** * Client JSON configuration object, loaded from @@ -48,7 +53,7 @@ export class ConversationalSearchServiceClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('retail'); @@ -61,9 +66,9 @@ export class ConversationalSearchServiceClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; - conversationalSearchServiceStub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; + conversationalSearchServiceStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of ConversationalSearchServiceClient. @@ -104,21 +109,43 @@ export class ConversationalSearchServiceClient { * const client = new ConversationalSearchServiceClient({fallback: true}, gax); * ``` */ - constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { // Ensure that options include all the required fields. - const staticMembers = this.constructor as typeof ConversationalSearchServiceClient; - if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { - throw new Error('Please set either universe_domain or universeDomain, but not both.'); + const staticMembers = this + .constructor as typeof ConversationalSearchServiceClient; + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); } - const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; - this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; this._servicePath = 'retail.' + this._universeDomain; - const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; - const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. if (servicePath !== this._servicePath && !('scopes' in opts)) { @@ -140,7 +167,7 @@ export class ConversationalSearchServiceClient { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; @@ -154,10 +181,7 @@ export class ConversationalSearchServiceClient { } // Determine the client header string. - const clientHeader = [ - `gax/${this._gaxModule.version}`, - `gapic/${version}`, - ]; + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/${process.versions.node}`); } else { @@ -179,53 +203,60 @@ export class ConversationalSearchServiceClient { // Create useful helper objects for these. this.pathTemplates = { alertConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/alertConfig' + 'projects/{project}/alertConfig', ), attributesConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/attributesConfig' + 'projects/{project}/locations/{location}/catalogs/{catalog}/attributesConfig', ), branchPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}', ), catalogPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}' + 'projects/{project}/locations/{location}/catalogs/{catalog}', ), completionConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/completionConfig' + 'projects/{project}/locations/{location}/catalogs/{catalog}/completionConfig', ), controlPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/controls/{control}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/controls/{control}', ), loggingConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/loggingConfig' + 'projects/{project}/loggingConfig', ), merchantCenterAccountLinkPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/merchantCenterAccountLinks/{merchant_center_account_link}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/merchantCenterAccountLinks/{merchant_center_account_link}', ), modelPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/models/{model}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/models/{model}', ), productPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}', ), retailProjectPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/retailProject' + 'projects/{project}/retailProject', ), servingConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/servingConfigs/{serving_config}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/servingConfigs/{serving_config}', ), }; // Some of the methods on this service provide streaming responses. // Provide descriptors for these. this.descriptors.stream = { - conversationalSearch: new this._gaxModule.StreamDescriptor(this._gaxModule.StreamType.SERVER_STREAMING, !!opts.fallback, !!opts.gaxServerStreamingRetries) + conversationalSearch: new this._gaxModule.StreamDescriptor( + this._gaxModule.StreamType.SERVER_STREAMING, + !!opts.fallback, + !!opts.gaxServerStreamingRetries, + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.cloud.retail.v2alpha.ConversationalSearchService', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.cloud.retail.v2alpha.ConversationalSearchService', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + { 'x-goog-api-client': clientHeader.join(' ') }, + ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -256,44 +287,53 @@ export class ConversationalSearchServiceClient { // Put together the "service stub" for // google.cloud.retail.v2alpha.ConversationalSearchService. this.conversationalSearchServiceStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.cloud.retail.v2alpha.ConversationalSearchService') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any - (this._protos as any).google.cloud.retail.v2alpha.ConversationalSearchService, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.cloud.retail.v2alpha.ConversationalSearchService', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any + (this._protos as any).google.cloud.retail.v2alpha + .ConversationalSearchService, + this._opts, + this._providedCustomServicePath, + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const conversationalSearchServiceStubMethods = - ['conversationalSearch']; + const conversationalSearchServiceStubMethods = ['conversationalSearch']; for (const methodName of conversationalSearchServiceStubMethods) { const callPromise = this.conversationalSearchServiceStub.then( - stub => (...args: Array<{}>) => { - if (this._terminated) { - if (methodName in this.descriptors.stream) { - const stream = new PassThrough({objectMode: true}); - setImmediate(() => { - stream.emit('error', new this._gaxModule.GoogleError('The client has already been closed.')); - }); - return stream; + (stub) => + (...args: Array<{}>) => { + if (this._terminated) { + if (methodName in this.descriptors.stream) { + const stream = new PassThrough({ objectMode: true }); + setImmediate(() => { + stream.emit( + 'error', + new this._gaxModule.GoogleError( + 'The client has already been closed.', + ), + ); + }); + return stream; + } + return Promise.reject('The client has already been closed.'); } - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error|null|undefined) => () => { + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { throw err; - }); + }, + ); - const descriptor = - this.descriptors.stream[methodName] || - undefined; + const descriptor = this.descriptors.stream[methodName] || undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -308,8 +348,14 @@ export class ConversationalSearchServiceClient { * @returns {string} The DNS address for this service. */ static get servicePath() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'retail.googleapis.com'; } @@ -320,8 +366,14 @@ export class ConversationalSearchServiceClient { * @returns {string} The DNS address for this service. */ static get apiEndpoint() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'retail.googleapis.com'; } @@ -352,9 +404,7 @@ export class ConversationalSearchServiceClient { * @returns {string[]} List of default scopes. */ static get scopes() { - return [ - 'https://www.googleapis.com/auth/cloud-platform' - ]; + return ['https://www.googleapis.com/auth/cloud-platform']; } getProjectId(): Promise; @@ -363,8 +413,9 @@ export class ConversationalSearchServiceClient { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId(callback?: Callback): - Promise|void { + getProjectId( + callback?: Callback, + ): Promise | void { if (callback) { this.auth.getProjectId(callback); return; @@ -376,92 +427,93 @@ export class ConversationalSearchServiceClient { // -- Service calls -- // ------------------- -/** - * Performs a conversational search. - * - * This feature is only available for users who have Conversational Search - * enabled. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.placement - * Required. The resource name of the search engine placement, such as - * `projects/* /locations/global/catalogs/default_catalog/placements/default_search` - * or - * `projects/* /locations/global/catalogs/default_catalog/servingConfigs/default_serving_config` - * This field is used to identify the serving config name and the set - * of models that will be used to make the search. - * @param {string} request.branch - * Required. The branch resource name, such as - * `projects/* /locations/global/catalogs/default_catalog/branches/0`. - * - * Use "default_branch" as the branch ID or leave this field empty, to search - * products under the default branch. - * @param {string} [request.query] - * Optional. Raw search query to be searched for. - * - * If this field is empty, the request is considered a category browsing - * request. - * @param {string[]} [request.pageCategories] - * Optional. The categories associated with a category page. Must be set for - * category navigation queries to achieve good search quality. The format - * should be the same as - * {@link protos.google.cloud.retail.v2alpha.UserEvent.page_categories|UserEvent.page_categories}; - * - * To represent full path of category, use '>' sign to separate different - * hierarchies. If '>' is part of the category name, replace it with - * other character(s). - * - * Category pages include special pages such as sales or promotions. For - * instance, a special sale page may have the category hierarchy: - * "pageCategories" : ["Sales > 2017 Black Friday Deals"]. - * @param {string} [request.conversationId] - * Optional. This field specifies the conversation id, which maintains the - * state of the conversation between client side and server side. Use the - * value from the previous - * {@link protos.google.cloud.retail.v2alpha.ConversationalSearchResponse.conversation_id|ConversationalSearchResponse.conversation_id}. - * For the initial request, this should be empty. - * @param {google.cloud.retail.v2alpha.ConversationalSearchRequest.SearchParams} [request.searchParams] - * Optional. Search parameters. - * @param {string} request.visitorId - * Required. A unique identifier for tracking visitors. For example, this - * could be implemented with an HTTP cookie, which should be able to uniquely - * identify a visitor on a single device. This unique identifier should not - * change if the visitor logs in or out of the website. - * - * This should be the same identifier as - * {@link protos.google.cloud.retail.v2alpha.UserEvent.visitor_id|UserEvent.visitor_id}. - * - * The field must be a UTF-8 encoded string with a length limit of 128 - * characters. Otherwise, an INVALID_ARGUMENT error is returned. - * @param {google.cloud.retail.v2alpha.UserInfo} [request.userInfo] - * Optional. User information. - * @param {google.cloud.retail.v2alpha.ConversationalSearchRequest.ConversationalFilteringSpec} [request.conversationalFilteringSpec] - * Optional. This field specifies all conversational filtering related - * parameters. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits {@link protos.google.cloud.retail.v2alpha.ConversationalSearchResponse|ConversationalSearchResponse} on 'data' event. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#server-streaming | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/conversational_search_service.conversational_search.js - * region_tag:retail_v2alpha_generated_ConversationalSearchService_ConversationalSearch_async - */ + /** + * Performs a conversational search. + * + * This feature is only available for users who have Conversational Search + * enabled. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.placement + * Required. The resource name of the search engine placement, such as + * `projects/* /locations/global/catalogs/default_catalog/placements/default_search` + * or + * `projects/* /locations/global/catalogs/default_catalog/servingConfigs/default_serving_config` + * This field is used to identify the serving config name and the set + * of models that will be used to make the search. + * @param {string} request.branch + * Required. The branch resource name, such as + * `projects/* /locations/global/catalogs/default_catalog/branches/0`. + * + * Use "default_branch" as the branch ID or leave this field empty, to search + * products under the default branch. + * @param {string} [request.query] + * Optional. Raw search query to be searched for. + * + * If this field is empty, the request is considered a category browsing + * request. + * @param {string[]} [request.pageCategories] + * Optional. The categories associated with a category page. Must be set for + * category navigation queries to achieve good search quality. The format + * should be the same as + * {@link protos.google.cloud.retail.v2alpha.UserEvent.page_categories|UserEvent.page_categories}; + * + * To represent full path of category, use '>' sign to separate different + * hierarchies. If '>' is part of the category name, replace it with + * other character(s). + * + * Category pages include special pages such as sales or promotions. For + * instance, a special sale page may have the category hierarchy: + * "pageCategories" : ["Sales > 2017 Black Friday Deals"]. + * @param {string} [request.conversationId] + * Optional. This field specifies the conversation id, which maintains the + * state of the conversation between client side and server side. Use the + * value from the previous + * {@link protos.google.cloud.retail.v2alpha.ConversationalSearchResponse.conversation_id|ConversationalSearchResponse.conversation_id}. + * For the initial request, this should be empty. + * @param {google.cloud.retail.v2alpha.ConversationalSearchRequest.SearchParams} [request.searchParams] + * Optional. Search parameters. + * @param {string} request.visitorId + * Required. A unique identifier for tracking visitors. For example, this + * could be implemented with an HTTP cookie, which should be able to uniquely + * identify a visitor on a single device. This unique identifier should not + * change if the visitor logs in or out of the website. + * + * This should be the same identifier as + * {@link protos.google.cloud.retail.v2alpha.UserEvent.visitor_id|UserEvent.visitor_id}. + * + * The field must be a UTF-8 encoded string with a length limit of 128 + * characters. Otherwise, an INVALID_ARGUMENT error is returned. + * @param {google.cloud.retail.v2alpha.UserInfo} [request.userInfo] + * Optional. User information. + * @param {google.cloud.retail.v2alpha.ConversationalSearchRequest.ConversationalFilteringSpec} [request.conversationalFilteringSpec] + * Optional. This field specifies all conversational filtering related + * parameters. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits {@link protos.google.cloud.retail.v2alpha.ConversationalSearchResponse|ConversationalSearchResponse} on 'data' event. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#server-streaming | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/conversational_search_service.conversational_search.js + * region_tag:retail_v2alpha_generated_ConversationalSearchService_ConversationalSearch_async + */ conversationalSearch( - request?: protos.google.cloud.retail.v2alpha.IConversationalSearchRequest, - options?: CallOptions): - gax.CancellableStream{ + request?: protos.google.cloud.retail.v2alpha.IConversationalSearchRequest, + options?: CallOptions, + ): gax.CancellableStream { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'placement': request.placement ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + placement: request.placement ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('conversationalSearch stream %j', options); return this.innerApiCalls.conversationalSearch(request, options); } @@ -476,7 +528,7 @@ export class ConversationalSearchServiceClient { * @param {string} project * @returns {string} Resource name string. */ - alertConfigPath(project:string) { + alertConfigPath(project: string) { return this.pathTemplates.alertConfigPathTemplate.render({ project: project, }); @@ -490,7 +542,8 @@ export class ConversationalSearchServiceClient { * @returns {string} A string representing the project. */ matchProjectFromAlertConfigName(alertConfigName: string) { - return this.pathTemplates.alertConfigPathTemplate.match(alertConfigName).project; + return this.pathTemplates.alertConfigPathTemplate.match(alertConfigName) + .project; } /** @@ -501,7 +554,7 @@ export class ConversationalSearchServiceClient { * @param {string} catalog * @returns {string} Resource name string. */ - attributesConfigPath(project:string,location:string,catalog:string) { + attributesConfigPath(project: string, location: string, catalog: string) { return this.pathTemplates.attributesConfigPathTemplate.render({ project: project, location: location, @@ -517,7 +570,9 @@ export class ConversationalSearchServiceClient { * @returns {string} A string representing the project. */ matchProjectFromAttributesConfigName(attributesConfigName: string) { - return this.pathTemplates.attributesConfigPathTemplate.match(attributesConfigName).project; + return this.pathTemplates.attributesConfigPathTemplate.match( + attributesConfigName, + ).project; } /** @@ -528,7 +583,9 @@ export class ConversationalSearchServiceClient { * @returns {string} A string representing the location. */ matchLocationFromAttributesConfigName(attributesConfigName: string) { - return this.pathTemplates.attributesConfigPathTemplate.match(attributesConfigName).location; + return this.pathTemplates.attributesConfigPathTemplate.match( + attributesConfigName, + ).location; } /** @@ -539,7 +596,9 @@ export class ConversationalSearchServiceClient { * @returns {string} A string representing the catalog. */ matchCatalogFromAttributesConfigName(attributesConfigName: string) { - return this.pathTemplates.attributesConfigPathTemplate.match(attributesConfigName).catalog; + return this.pathTemplates.attributesConfigPathTemplate.match( + attributesConfigName, + ).catalog; } /** @@ -551,7 +610,12 @@ export class ConversationalSearchServiceClient { * @param {string} branch * @returns {string} Resource name string. */ - branchPath(project:string,location:string,catalog:string,branch:string) { + branchPath( + project: string, + location: string, + catalog: string, + branch: string, + ) { return this.pathTemplates.branchPathTemplate.render({ project: project, location: location, @@ -612,7 +676,7 @@ export class ConversationalSearchServiceClient { * @param {string} catalog * @returns {string} Resource name string. */ - catalogPath(project:string,location:string,catalog:string) { + catalogPath(project: string, location: string, catalog: string) { return this.pathTemplates.catalogPathTemplate.render({ project: project, location: location, @@ -661,7 +725,7 @@ export class ConversationalSearchServiceClient { * @param {string} catalog * @returns {string} Resource name string. */ - completionConfigPath(project:string,location:string,catalog:string) { + completionConfigPath(project: string, location: string, catalog: string) { return this.pathTemplates.completionConfigPathTemplate.render({ project: project, location: location, @@ -677,7 +741,9 @@ export class ConversationalSearchServiceClient { * @returns {string} A string representing the project. */ matchProjectFromCompletionConfigName(completionConfigName: string) { - return this.pathTemplates.completionConfigPathTemplate.match(completionConfigName).project; + return this.pathTemplates.completionConfigPathTemplate.match( + completionConfigName, + ).project; } /** @@ -688,7 +754,9 @@ export class ConversationalSearchServiceClient { * @returns {string} A string representing the location. */ matchLocationFromCompletionConfigName(completionConfigName: string) { - return this.pathTemplates.completionConfigPathTemplate.match(completionConfigName).location; + return this.pathTemplates.completionConfigPathTemplate.match( + completionConfigName, + ).location; } /** @@ -699,7 +767,9 @@ export class ConversationalSearchServiceClient { * @returns {string} A string representing the catalog. */ matchCatalogFromCompletionConfigName(completionConfigName: string) { - return this.pathTemplates.completionConfigPathTemplate.match(completionConfigName).catalog; + return this.pathTemplates.completionConfigPathTemplate.match( + completionConfigName, + ).catalog; } /** @@ -711,7 +781,12 @@ export class ConversationalSearchServiceClient { * @param {string} control * @returns {string} Resource name string. */ - controlPath(project:string,location:string,catalog:string,control:string) { + controlPath( + project: string, + location: string, + catalog: string, + control: string, + ) { return this.pathTemplates.controlPathTemplate.render({ project: project, location: location, @@ -770,7 +845,7 @@ export class ConversationalSearchServiceClient { * @param {string} project * @returns {string} Resource name string. */ - loggingConfigPath(project:string) { + loggingConfigPath(project: string) { return this.pathTemplates.loggingConfigPathTemplate.render({ project: project, }); @@ -784,7 +859,8 @@ export class ConversationalSearchServiceClient { * @returns {string} A string representing the project. */ matchProjectFromLoggingConfigName(loggingConfigName: string) { - return this.pathTemplates.loggingConfigPathTemplate.match(loggingConfigName).project; + return this.pathTemplates.loggingConfigPathTemplate.match(loggingConfigName) + .project; } /** @@ -796,7 +872,12 @@ export class ConversationalSearchServiceClient { * @param {string} merchant_center_account_link * @returns {string} Resource name string. */ - merchantCenterAccountLinkPath(project:string,location:string,catalog:string,merchantCenterAccountLink:string) { + merchantCenterAccountLinkPath( + project: string, + location: string, + catalog: string, + merchantCenterAccountLink: string, + ) { return this.pathTemplates.merchantCenterAccountLinkPathTemplate.render({ project: project, location: location, @@ -812,8 +893,12 @@ export class ConversationalSearchServiceClient { * A fully-qualified path representing MerchantCenterAccountLink resource. * @returns {string} A string representing the project. */ - matchProjectFromMerchantCenterAccountLinkName(merchantCenterAccountLinkName: string) { - return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match(merchantCenterAccountLinkName).project; + matchProjectFromMerchantCenterAccountLinkName( + merchantCenterAccountLinkName: string, + ) { + return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match( + merchantCenterAccountLinkName, + ).project; } /** @@ -823,8 +908,12 @@ export class ConversationalSearchServiceClient { * A fully-qualified path representing MerchantCenterAccountLink resource. * @returns {string} A string representing the location. */ - matchLocationFromMerchantCenterAccountLinkName(merchantCenterAccountLinkName: string) { - return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match(merchantCenterAccountLinkName).location; + matchLocationFromMerchantCenterAccountLinkName( + merchantCenterAccountLinkName: string, + ) { + return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match( + merchantCenterAccountLinkName, + ).location; } /** @@ -834,8 +923,12 @@ export class ConversationalSearchServiceClient { * A fully-qualified path representing MerchantCenterAccountLink resource. * @returns {string} A string representing the catalog. */ - matchCatalogFromMerchantCenterAccountLinkName(merchantCenterAccountLinkName: string) { - return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match(merchantCenterAccountLinkName).catalog; + matchCatalogFromMerchantCenterAccountLinkName( + merchantCenterAccountLinkName: string, + ) { + return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match( + merchantCenterAccountLinkName, + ).catalog; } /** @@ -845,8 +938,12 @@ export class ConversationalSearchServiceClient { * A fully-qualified path representing MerchantCenterAccountLink resource. * @returns {string} A string representing the merchant_center_account_link. */ - matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName(merchantCenterAccountLinkName: string) { - return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match(merchantCenterAccountLinkName).merchant_center_account_link; + matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName( + merchantCenterAccountLinkName: string, + ) { + return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match( + merchantCenterAccountLinkName, + ).merchant_center_account_link; } /** @@ -858,7 +955,7 @@ export class ConversationalSearchServiceClient { * @param {string} model * @returns {string} Resource name string. */ - modelPath(project:string,location:string,catalog:string,model:string) { + modelPath(project: string, location: string, catalog: string, model: string) { return this.pathTemplates.modelPathTemplate.render({ project: project, location: location, @@ -921,7 +1018,13 @@ export class ConversationalSearchServiceClient { * @param {string} product * @returns {string} Resource name string. */ - productPath(project:string,location:string,catalog:string,branch:string,product:string) { + productPath( + project: string, + location: string, + catalog: string, + branch: string, + product: string, + ) { return this.pathTemplates.productPathTemplate.render({ project: project, location: location, @@ -992,7 +1095,7 @@ export class ConversationalSearchServiceClient { * @param {string} project * @returns {string} Resource name string. */ - retailProjectPath(project:string) { + retailProjectPath(project: string) { return this.pathTemplates.retailProjectPathTemplate.render({ project: project, }); @@ -1006,7 +1109,8 @@ export class ConversationalSearchServiceClient { * @returns {string} A string representing the project. */ matchProjectFromRetailProjectName(retailProjectName: string) { - return this.pathTemplates.retailProjectPathTemplate.match(retailProjectName).project; + return this.pathTemplates.retailProjectPathTemplate.match(retailProjectName) + .project; } /** @@ -1018,7 +1122,12 @@ export class ConversationalSearchServiceClient { * @param {string} serving_config * @returns {string} Resource name string. */ - servingConfigPath(project:string,location:string,catalog:string,servingConfig:string) { + servingConfigPath( + project: string, + location: string, + catalog: string, + servingConfig: string, + ) { return this.pathTemplates.servingConfigPathTemplate.render({ project: project, location: location, @@ -1035,7 +1144,8 @@ export class ConversationalSearchServiceClient { * @returns {string} A string representing the project. */ matchProjectFromServingConfigName(servingConfigName: string) { - return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName).project; + return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName) + .project; } /** @@ -1046,7 +1156,8 @@ export class ConversationalSearchServiceClient { * @returns {string} A string representing the location. */ matchLocationFromServingConfigName(servingConfigName: string) { - return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName).location; + return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName) + .location; } /** @@ -1057,7 +1168,8 @@ export class ConversationalSearchServiceClient { * @returns {string} A string representing the catalog. */ matchCatalogFromServingConfigName(servingConfigName: string) { - return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName).catalog; + return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName) + .catalog; } /** @@ -1068,7 +1180,8 @@ export class ConversationalSearchServiceClient { * @returns {string} A string representing the serving_config. */ matchServingConfigFromServingConfigName(servingConfigName: string) { - return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName).serving_config; + return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName) + .serving_config; } /** @@ -1079,7 +1192,7 @@ export class ConversationalSearchServiceClient { */ close(): Promise { if (this.conversationalSearchServiceStub && !this._terminated) { - return this.conversationalSearchServiceStub.then(stub => { + return this.conversationalSearchServiceStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -1087,4 +1200,4 @@ export class ConversationalSearchServiceClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/core/generator/gapic-generator-typescript/baselines/retail/src/v2alpha/generative_question_service_client.ts.baseline b/core/generator/gapic-generator-typescript/baselines/retail/src/v2alpha/generative_question_service_client.ts.baseline index 90b5eaee4ce1..fa8dc7033b9d 100644 --- a/core/generator/gapic-generator-typescript/baselines/retail/src/v2alpha/generative_question_service_client.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/retail/src/v2alpha/generative_question_service_client.ts.baseline @@ -18,11 +18,16 @@ /* global window */ import type * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions} from 'google-gax'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, +} from 'google-gax'; import * as protos from '../../protos/protos'; import jsonProtos = require('../../protos/protos.json'); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; /** * Client JSON configuration object, loaded from @@ -44,7 +49,7 @@ export class GenerativeQuestionServiceClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('retail'); @@ -57,9 +62,9 @@ export class GenerativeQuestionServiceClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; - generativeQuestionServiceStub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; + generativeQuestionServiceStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of GenerativeQuestionServiceClient. @@ -100,21 +105,43 @@ export class GenerativeQuestionServiceClient { * const client = new GenerativeQuestionServiceClient({fallback: true}, gax); * ``` */ - constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { // Ensure that options include all the required fields. - const staticMembers = this.constructor as typeof GenerativeQuestionServiceClient; - if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { - throw new Error('Please set either universe_domain or universeDomain, but not both.'); + const staticMembers = this + .constructor as typeof GenerativeQuestionServiceClient; + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); } - const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; - this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; this._servicePath = 'retail.' + this._universeDomain; - const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; - const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. if (servicePath !== this._servicePath && !('scopes' in opts)) { @@ -136,7 +163,7 @@ export class GenerativeQuestionServiceClient { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; @@ -150,10 +177,7 @@ export class GenerativeQuestionServiceClient { } // Determine the client header string. - const clientHeader = [ - `gax/${this._gaxModule.version}`, - `gapic/${version}`, - ]; + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/${process.versions.node}`); } else { @@ -175,47 +199,50 @@ export class GenerativeQuestionServiceClient { // Create useful helper objects for these. this.pathTemplates = { alertConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/alertConfig' + 'projects/{project}/alertConfig', ), attributesConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/attributesConfig' + 'projects/{project}/locations/{location}/catalogs/{catalog}/attributesConfig', ), branchPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}', ), catalogPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}' + 'projects/{project}/locations/{location}/catalogs/{catalog}', ), completionConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/completionConfig' + 'projects/{project}/locations/{location}/catalogs/{catalog}/completionConfig', ), controlPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/controls/{control}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/controls/{control}', ), loggingConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/loggingConfig' + 'projects/{project}/loggingConfig', ), merchantCenterAccountLinkPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/merchantCenterAccountLinks/{merchant_center_account_link}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/merchantCenterAccountLinks/{merchant_center_account_link}', ), modelPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/models/{model}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/models/{model}', ), productPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}', ), retailProjectPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/retailProject' + 'projects/{project}/retailProject', ), servingConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/servingConfigs/{serving_config}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/servingConfigs/{serving_config}', ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.cloud.retail.v2alpha.GenerativeQuestionService', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.cloud.retail.v2alpha.GenerativeQuestionService', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + { 'x-goog-api-client': clientHeader.join(' ') }, + ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -246,36 +273,47 @@ export class GenerativeQuestionServiceClient { // Put together the "service stub" for // google.cloud.retail.v2alpha.GenerativeQuestionService. this.generativeQuestionServiceStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.cloud.retail.v2alpha.GenerativeQuestionService') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any - (this._protos as any).google.cloud.retail.v2alpha.GenerativeQuestionService, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.cloud.retail.v2alpha.GenerativeQuestionService', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any + (this._protos as any).google.cloud.retail.v2alpha + .GenerativeQuestionService, + this._opts, + this._providedCustomServicePath, + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const generativeQuestionServiceStubMethods = - ['updateGenerativeQuestionsFeatureConfig', 'getGenerativeQuestionsFeatureConfig', 'listGenerativeQuestionConfigs', 'updateGenerativeQuestionConfig', 'batchUpdateGenerativeQuestionConfigs']; + const generativeQuestionServiceStubMethods = [ + 'updateGenerativeQuestionsFeatureConfig', + 'getGenerativeQuestionsFeatureConfig', + 'listGenerativeQuestionConfigs', + 'updateGenerativeQuestionConfig', + 'batchUpdateGenerativeQuestionConfigs', + ]; for (const methodName of generativeQuestionServiceStubMethods) { const callPromise = this.generativeQuestionServiceStub.then( - stub => (...args: Array<{}>) => { - if (this._terminated) { - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error|null|undefined) => () => { + (stub) => + (...args: Array<{}>) => { + if (this._terminated) { + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { throw err; - }); + }, + ); - const descriptor = - undefined; + const descriptor = undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -290,8 +328,14 @@ export class GenerativeQuestionServiceClient { * @returns {string} The DNS address for this service. */ static get servicePath() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'retail.googleapis.com'; } @@ -302,8 +346,14 @@ export class GenerativeQuestionServiceClient { * @returns {string} The DNS address for this service. */ static get apiEndpoint() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'retail.googleapis.com'; } @@ -334,9 +384,7 @@ export class GenerativeQuestionServiceClient { * @returns {string[]} List of default scopes. */ static get scopes() { - return [ - 'https://www.googleapis.com/auth/cloud-platform' - ]; + return ['https://www.googleapis.com/auth/cloud-platform']; } getProjectId(): Promise; @@ -345,8 +393,9 @@ export class GenerativeQuestionServiceClient { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId(callback?: Callback): - Promise|void { + getProjectId( + callback?: Callback, + ): Promise | void { if (callback) { this.auth.getProjectId(callback); return; @@ -357,491 +406,765 @@ export class GenerativeQuestionServiceClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Manages overal generative question feature state -- enables toggling - * feature on and off. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.cloud.retail.v2alpha.GenerativeQuestionsFeatureConfig} request.generativeQuestionsFeatureConfig - * Required. The configuration managing the feature state. - * @param {google.protobuf.FieldMask} [request.updateMask] - * Optional. Indicates which fields in the provided - * {@link protos.google.cloud.retail.v2alpha.GenerativeQuestionsFeatureConfig|GenerativeQuestionsFeatureConfig} - * to update. If not set or empty, all supported fields are updated. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.GenerativeQuestionsFeatureConfig|GenerativeQuestionsFeatureConfig}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/generative_question_service.update_generative_questions_feature_config.js - * region_tag:retail_v2alpha_generated_GenerativeQuestionService_UpdateGenerativeQuestionsFeatureConfig_async - */ + /** + * Manages overal generative question feature state -- enables toggling + * feature on and off. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.cloud.retail.v2alpha.GenerativeQuestionsFeatureConfig} request.generativeQuestionsFeatureConfig + * Required. The configuration managing the feature state. + * @param {google.protobuf.FieldMask} [request.updateMask] + * Optional. Indicates which fields in the provided + * {@link protos.google.cloud.retail.v2alpha.GenerativeQuestionsFeatureConfig|GenerativeQuestionsFeatureConfig} + * to update. If not set or empty, all supported fields are updated. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.GenerativeQuestionsFeatureConfig|GenerativeQuestionsFeatureConfig}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/generative_question_service.update_generative_questions_feature_config.js + * region_tag:retail_v2alpha_generated_GenerativeQuestionService_UpdateGenerativeQuestionsFeatureConfig_async + */ updateGenerativeQuestionsFeatureConfig( - request?: protos.google.cloud.retail.v2alpha.IUpdateGenerativeQuestionsFeatureConfigRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.retail.v2alpha.IGenerativeQuestionsFeatureConfig, - protos.google.cloud.retail.v2alpha.IUpdateGenerativeQuestionsFeatureConfigRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.IUpdateGenerativeQuestionsFeatureConfigRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IGenerativeQuestionsFeatureConfig, + ( + | protos.google.cloud.retail.v2alpha.IUpdateGenerativeQuestionsFeatureConfigRequest + | undefined + ), + {} | undefined, + ] + >; updateGenerativeQuestionsFeatureConfig( - request: protos.google.cloud.retail.v2alpha.IUpdateGenerativeQuestionsFeatureConfigRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.retail.v2alpha.IGenerativeQuestionsFeatureConfig, - protos.google.cloud.retail.v2alpha.IUpdateGenerativeQuestionsFeatureConfigRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IUpdateGenerativeQuestionsFeatureConfigRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.retail.v2alpha.IGenerativeQuestionsFeatureConfig, + | protos.google.cloud.retail.v2alpha.IUpdateGenerativeQuestionsFeatureConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateGenerativeQuestionsFeatureConfig( - request: protos.google.cloud.retail.v2alpha.IUpdateGenerativeQuestionsFeatureConfigRequest, - callback: Callback< - protos.google.cloud.retail.v2alpha.IGenerativeQuestionsFeatureConfig, - protos.google.cloud.retail.v2alpha.IUpdateGenerativeQuestionsFeatureConfigRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IUpdateGenerativeQuestionsFeatureConfigRequest, + callback: Callback< + protos.google.cloud.retail.v2alpha.IGenerativeQuestionsFeatureConfig, + | protos.google.cloud.retail.v2alpha.IUpdateGenerativeQuestionsFeatureConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateGenerativeQuestionsFeatureConfig( - request?: protos.google.cloud.retail.v2alpha.IUpdateGenerativeQuestionsFeatureConfigRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.retail.v2alpha.IGenerativeQuestionsFeatureConfig, - protos.google.cloud.retail.v2alpha.IUpdateGenerativeQuestionsFeatureConfigRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.retail.v2alpha.IUpdateGenerativeQuestionsFeatureConfigRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.retail.v2alpha.IGenerativeQuestionsFeatureConfig, - protos.google.cloud.retail.v2alpha.IUpdateGenerativeQuestionsFeatureConfigRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.retail.v2alpha.IGenerativeQuestionsFeatureConfig, - protos.google.cloud.retail.v2alpha.IUpdateGenerativeQuestionsFeatureConfigRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.retail.v2alpha.IUpdateGenerativeQuestionsFeatureConfigRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.retail.v2alpha.IGenerativeQuestionsFeatureConfig, + | protos.google.cloud.retail.v2alpha.IUpdateGenerativeQuestionsFeatureConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IGenerativeQuestionsFeatureConfig, + ( + | protos.google.cloud.retail.v2alpha.IUpdateGenerativeQuestionsFeatureConfigRequest + | undefined + ), + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'generative_questions_feature_config.catalog': request.generativeQuestionsFeatureConfig!.catalog ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'generative_questions_feature_config.catalog': + request.generativeQuestionsFeatureConfig!.catalog ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - this._log.info('updateGenerativeQuestionsFeatureConfig request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.retail.v2alpha.IGenerativeQuestionsFeatureConfig, - protos.google.cloud.retail.v2alpha.IUpdateGenerativeQuestionsFeatureConfigRequest|null|undefined, - {}|null|undefined>|undefined = callback + this._log.info( + 'updateGenerativeQuestionsFeatureConfig request %j', + request, + ); + const wrappedCallback: + | Callback< + protos.google.cloud.retail.v2alpha.IGenerativeQuestionsFeatureConfig, + | protos.google.cloud.retail.v2alpha.IUpdateGenerativeQuestionsFeatureConfigRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { - this._log.info('updateGenerativeQuestionsFeatureConfig response %j', response); + this._log.info( + 'updateGenerativeQuestionsFeatureConfig response %j', + response, + ); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.updateGenerativeQuestionsFeatureConfig(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.retail.v2alpha.IGenerativeQuestionsFeatureConfig, - protos.google.cloud.retail.v2alpha.IUpdateGenerativeQuestionsFeatureConfigRequest|undefined, - {}|undefined - ]) => { - this._log.info('updateGenerativeQuestionsFeatureConfig response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateGenerativeQuestionsFeatureConfig(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.retail.v2alpha.IGenerativeQuestionsFeatureConfig, + ( + | protos.google.cloud.retail.v2alpha.IUpdateGenerativeQuestionsFeatureConfigRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info( + 'updateGenerativeQuestionsFeatureConfig response %j', + response, + ); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Manages overal generative question feature state -- enables toggling - * feature on and off. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.catalog - * Required. Resource name of the parent catalog. - * Format: projects/{project}/locations/{location}/catalogs/{catalog} - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.GenerativeQuestionsFeatureConfig|GenerativeQuestionsFeatureConfig}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/generative_question_service.get_generative_questions_feature_config.js - * region_tag:retail_v2alpha_generated_GenerativeQuestionService_GetGenerativeQuestionsFeatureConfig_async - */ + /** + * Manages overal generative question feature state -- enables toggling + * feature on and off. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.catalog + * Required. Resource name of the parent catalog. + * Format: projects/{project}/locations/{location}/catalogs/{catalog} + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.GenerativeQuestionsFeatureConfig|GenerativeQuestionsFeatureConfig}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/generative_question_service.get_generative_questions_feature_config.js + * region_tag:retail_v2alpha_generated_GenerativeQuestionService_GetGenerativeQuestionsFeatureConfig_async + */ getGenerativeQuestionsFeatureConfig( - request?: protos.google.cloud.retail.v2alpha.IGetGenerativeQuestionsFeatureConfigRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.retail.v2alpha.IGenerativeQuestionsFeatureConfig, - protos.google.cloud.retail.v2alpha.IGetGenerativeQuestionsFeatureConfigRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.IGetGenerativeQuestionsFeatureConfigRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IGenerativeQuestionsFeatureConfig, + ( + | protos.google.cloud.retail.v2alpha.IGetGenerativeQuestionsFeatureConfigRequest + | undefined + ), + {} | undefined, + ] + >; getGenerativeQuestionsFeatureConfig( - request: protos.google.cloud.retail.v2alpha.IGetGenerativeQuestionsFeatureConfigRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.retail.v2alpha.IGenerativeQuestionsFeatureConfig, - protos.google.cloud.retail.v2alpha.IGetGenerativeQuestionsFeatureConfigRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IGetGenerativeQuestionsFeatureConfigRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.retail.v2alpha.IGenerativeQuestionsFeatureConfig, + | protos.google.cloud.retail.v2alpha.IGetGenerativeQuestionsFeatureConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getGenerativeQuestionsFeatureConfig( - request: protos.google.cloud.retail.v2alpha.IGetGenerativeQuestionsFeatureConfigRequest, - callback: Callback< - protos.google.cloud.retail.v2alpha.IGenerativeQuestionsFeatureConfig, - protos.google.cloud.retail.v2alpha.IGetGenerativeQuestionsFeatureConfigRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IGetGenerativeQuestionsFeatureConfigRequest, + callback: Callback< + protos.google.cloud.retail.v2alpha.IGenerativeQuestionsFeatureConfig, + | protos.google.cloud.retail.v2alpha.IGetGenerativeQuestionsFeatureConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getGenerativeQuestionsFeatureConfig( - request?: protos.google.cloud.retail.v2alpha.IGetGenerativeQuestionsFeatureConfigRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.retail.v2alpha.IGenerativeQuestionsFeatureConfig, - protos.google.cloud.retail.v2alpha.IGetGenerativeQuestionsFeatureConfigRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.retail.v2alpha.IGetGenerativeQuestionsFeatureConfigRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.retail.v2alpha.IGenerativeQuestionsFeatureConfig, - protos.google.cloud.retail.v2alpha.IGetGenerativeQuestionsFeatureConfigRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.retail.v2alpha.IGenerativeQuestionsFeatureConfig, - protos.google.cloud.retail.v2alpha.IGetGenerativeQuestionsFeatureConfigRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.retail.v2alpha.IGetGenerativeQuestionsFeatureConfigRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.retail.v2alpha.IGenerativeQuestionsFeatureConfig, + | protos.google.cloud.retail.v2alpha.IGetGenerativeQuestionsFeatureConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IGenerativeQuestionsFeatureConfig, + ( + | protos.google.cloud.retail.v2alpha.IGetGenerativeQuestionsFeatureConfigRequest + | undefined + ), + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'catalog': request.catalog ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + catalog: request.catalog ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getGenerativeQuestionsFeatureConfig request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.retail.v2alpha.IGenerativeQuestionsFeatureConfig, - protos.google.cloud.retail.v2alpha.IGetGenerativeQuestionsFeatureConfigRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.retail.v2alpha.IGenerativeQuestionsFeatureConfig, + | protos.google.cloud.retail.v2alpha.IGetGenerativeQuestionsFeatureConfigRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { - this._log.info('getGenerativeQuestionsFeatureConfig response %j', response); + this._log.info( + 'getGenerativeQuestionsFeatureConfig response %j', + response, + ); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getGenerativeQuestionsFeatureConfig(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.retail.v2alpha.IGenerativeQuestionsFeatureConfig, - protos.google.cloud.retail.v2alpha.IGetGenerativeQuestionsFeatureConfigRequest|undefined, - {}|undefined - ]) => { - this._log.info('getGenerativeQuestionsFeatureConfig response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getGenerativeQuestionsFeatureConfig(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.retail.v2alpha.IGenerativeQuestionsFeatureConfig, + ( + | protos.google.cloud.retail.v2alpha.IGetGenerativeQuestionsFeatureConfigRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info( + 'getGenerativeQuestionsFeatureConfig response %j', + response, + ); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Returns all questions for a given catalog. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. Resource name of the parent catalog. - * Format: projects/{project}/locations/{location}/catalogs/{catalog} - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.ListGenerativeQuestionConfigsResponse|ListGenerativeQuestionConfigsResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/generative_question_service.list_generative_question_configs.js - * region_tag:retail_v2alpha_generated_GenerativeQuestionService_ListGenerativeQuestionConfigs_async - */ + /** + * Returns all questions for a given catalog. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Resource name of the parent catalog. + * Format: projects/{project}/locations/{location}/catalogs/{catalog} + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.ListGenerativeQuestionConfigsResponse|ListGenerativeQuestionConfigsResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/generative_question_service.list_generative_question_configs.js + * region_tag:retail_v2alpha_generated_GenerativeQuestionService_ListGenerativeQuestionConfigs_async + */ listGenerativeQuestionConfigs( - request?: protos.google.cloud.retail.v2alpha.IListGenerativeQuestionConfigsRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.retail.v2alpha.IListGenerativeQuestionConfigsResponse, - protos.google.cloud.retail.v2alpha.IListGenerativeQuestionConfigsRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.IListGenerativeQuestionConfigsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IListGenerativeQuestionConfigsResponse, + ( + | protos.google.cloud.retail.v2alpha.IListGenerativeQuestionConfigsRequest + | undefined + ), + {} | undefined, + ] + >; listGenerativeQuestionConfigs( - request: protos.google.cloud.retail.v2alpha.IListGenerativeQuestionConfigsRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.retail.v2alpha.IListGenerativeQuestionConfigsResponse, - protos.google.cloud.retail.v2alpha.IListGenerativeQuestionConfigsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IListGenerativeQuestionConfigsRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.retail.v2alpha.IListGenerativeQuestionConfigsResponse, + | protos.google.cloud.retail.v2alpha.IListGenerativeQuestionConfigsRequest + | null + | undefined, + {} | null | undefined + >, + ): void; listGenerativeQuestionConfigs( - request: protos.google.cloud.retail.v2alpha.IListGenerativeQuestionConfigsRequest, - callback: Callback< - protos.google.cloud.retail.v2alpha.IListGenerativeQuestionConfigsResponse, - protos.google.cloud.retail.v2alpha.IListGenerativeQuestionConfigsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IListGenerativeQuestionConfigsRequest, + callback: Callback< + protos.google.cloud.retail.v2alpha.IListGenerativeQuestionConfigsResponse, + | protos.google.cloud.retail.v2alpha.IListGenerativeQuestionConfigsRequest + | null + | undefined, + {} | null | undefined + >, + ): void; listGenerativeQuestionConfigs( - request?: protos.google.cloud.retail.v2alpha.IListGenerativeQuestionConfigsRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.cloud.retail.v2alpha.IListGenerativeQuestionConfigsRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.retail.v2alpha.IListGenerativeQuestionConfigsResponse, - protos.google.cloud.retail.v2alpha.IListGenerativeQuestionConfigsRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.cloud.retail.v2alpha.IListGenerativeQuestionConfigsResponse, - protos.google.cloud.retail.v2alpha.IListGenerativeQuestionConfigsRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.retail.v2alpha.IListGenerativeQuestionConfigsResponse, - protos.google.cloud.retail.v2alpha.IListGenerativeQuestionConfigsRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.retail.v2alpha.IListGenerativeQuestionConfigsRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.retail.v2alpha.IListGenerativeQuestionConfigsResponse, + | protos.google.cloud.retail.v2alpha.IListGenerativeQuestionConfigsRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IListGenerativeQuestionConfigsResponse, + ( + | protos.google.cloud.retail.v2alpha.IListGenerativeQuestionConfigsRequest + | undefined + ), + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('listGenerativeQuestionConfigs request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.retail.v2alpha.IListGenerativeQuestionConfigsResponse, - protos.google.cloud.retail.v2alpha.IListGenerativeQuestionConfigsRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.retail.v2alpha.IListGenerativeQuestionConfigsResponse, + | protos.google.cloud.retail.v2alpha.IListGenerativeQuestionConfigsRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('listGenerativeQuestionConfigs response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.listGenerativeQuestionConfigs(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.retail.v2alpha.IListGenerativeQuestionConfigsResponse, - protos.google.cloud.retail.v2alpha.IListGenerativeQuestionConfigsRequest|undefined, - {}|undefined - ]) => { - this._log.info('listGenerativeQuestionConfigs response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .listGenerativeQuestionConfigs(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.retail.v2alpha.IListGenerativeQuestionConfigsResponse, + ( + | protos.google.cloud.retail.v2alpha.IListGenerativeQuestionConfigsRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('listGenerativeQuestionConfigs response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Allows management of individual questions. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.cloud.retail.v2alpha.GenerativeQuestionConfig} request.generativeQuestionConfig - * Required. The question to update. - * @param {google.protobuf.FieldMask} [request.updateMask] - * Optional. Indicates which fields in the provided - * {@link protos.google.cloud.retail.v2alpha.GenerativeQuestionConfig|GenerativeQuestionConfig} - * to update. The following are NOT supported: - * - * * {@link protos.google.cloud.retail.v2alpha.GenerativeQuestionConfig.frequency|GenerativeQuestionConfig.frequency} - * - * If not set or empty, all supported fields are updated. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.GenerativeQuestionConfig|GenerativeQuestionConfig}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/generative_question_service.update_generative_question_config.js - * region_tag:retail_v2alpha_generated_GenerativeQuestionService_UpdateGenerativeQuestionConfig_async - */ + /** + * Allows management of individual questions. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.cloud.retail.v2alpha.GenerativeQuestionConfig} request.generativeQuestionConfig + * Required. The question to update. + * @param {google.protobuf.FieldMask} [request.updateMask] + * Optional. Indicates which fields in the provided + * {@link protos.google.cloud.retail.v2alpha.GenerativeQuestionConfig|GenerativeQuestionConfig} + * to update. The following are NOT supported: + * + * * {@link protos.google.cloud.retail.v2alpha.GenerativeQuestionConfig.frequency|GenerativeQuestionConfig.frequency} + * + * If not set or empty, all supported fields are updated. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.GenerativeQuestionConfig|GenerativeQuestionConfig}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/generative_question_service.update_generative_question_config.js + * region_tag:retail_v2alpha_generated_GenerativeQuestionService_UpdateGenerativeQuestionConfig_async + */ updateGenerativeQuestionConfig( - request?: protos.google.cloud.retail.v2alpha.IUpdateGenerativeQuestionConfigRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.retail.v2alpha.IGenerativeQuestionConfig, - protos.google.cloud.retail.v2alpha.IUpdateGenerativeQuestionConfigRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.IUpdateGenerativeQuestionConfigRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IGenerativeQuestionConfig, + ( + | protos.google.cloud.retail.v2alpha.IUpdateGenerativeQuestionConfigRequest + | undefined + ), + {} | undefined, + ] + >; updateGenerativeQuestionConfig( - request: protos.google.cloud.retail.v2alpha.IUpdateGenerativeQuestionConfigRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.retail.v2alpha.IGenerativeQuestionConfig, - protos.google.cloud.retail.v2alpha.IUpdateGenerativeQuestionConfigRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IUpdateGenerativeQuestionConfigRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.retail.v2alpha.IGenerativeQuestionConfig, + | protos.google.cloud.retail.v2alpha.IUpdateGenerativeQuestionConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateGenerativeQuestionConfig( - request: protos.google.cloud.retail.v2alpha.IUpdateGenerativeQuestionConfigRequest, - callback: Callback< - protos.google.cloud.retail.v2alpha.IGenerativeQuestionConfig, - protos.google.cloud.retail.v2alpha.IUpdateGenerativeQuestionConfigRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IUpdateGenerativeQuestionConfigRequest, + callback: Callback< + protos.google.cloud.retail.v2alpha.IGenerativeQuestionConfig, + | protos.google.cloud.retail.v2alpha.IUpdateGenerativeQuestionConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateGenerativeQuestionConfig( - request?: protos.google.cloud.retail.v2alpha.IUpdateGenerativeQuestionConfigRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.retail.v2alpha.IGenerativeQuestionConfig, - protos.google.cloud.retail.v2alpha.IUpdateGenerativeQuestionConfigRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.retail.v2alpha.IUpdateGenerativeQuestionConfigRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.retail.v2alpha.IGenerativeQuestionConfig, - protos.google.cloud.retail.v2alpha.IUpdateGenerativeQuestionConfigRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.retail.v2alpha.IGenerativeQuestionConfig, - protos.google.cloud.retail.v2alpha.IUpdateGenerativeQuestionConfigRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.retail.v2alpha.IUpdateGenerativeQuestionConfigRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.retail.v2alpha.IGenerativeQuestionConfig, + | protos.google.cloud.retail.v2alpha.IUpdateGenerativeQuestionConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IGenerativeQuestionConfig, + ( + | protos.google.cloud.retail.v2alpha.IUpdateGenerativeQuestionConfigRequest + | undefined + ), + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'generative_question_config.catalog': request.generativeQuestionConfig!.catalog ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'generative_question_config.catalog': + request.generativeQuestionConfig!.catalog ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateGenerativeQuestionConfig request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.retail.v2alpha.IGenerativeQuestionConfig, - protos.google.cloud.retail.v2alpha.IUpdateGenerativeQuestionConfigRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.retail.v2alpha.IGenerativeQuestionConfig, + | protos.google.cloud.retail.v2alpha.IUpdateGenerativeQuestionConfigRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { - this._log.info('updateGenerativeQuestionConfig response %j', response); + this._log.info( + 'updateGenerativeQuestionConfig response %j', + response, + ); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.updateGenerativeQuestionConfig(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.retail.v2alpha.IGenerativeQuestionConfig, - protos.google.cloud.retail.v2alpha.IUpdateGenerativeQuestionConfigRequest|undefined, - {}|undefined - ]) => { - this._log.info('updateGenerativeQuestionConfig response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateGenerativeQuestionConfig(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.retail.v2alpha.IGenerativeQuestionConfig, + ( + | protos.google.cloud.retail.v2alpha.IUpdateGenerativeQuestionConfigRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info( + 'updateGenerativeQuestionConfig response %j', + response, + ); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Allows management of multiple questions. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} [request.parent] - * Optional. Resource name of the parent catalog. - * Format: projects/{project}/locations/{location}/catalogs/{catalog} - * @param {number[]} request.requests - * Required. The updates question configs. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.BatchUpdateGenerativeQuestionConfigsResponse|BatchUpdateGenerativeQuestionConfigsResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/generative_question_service.batch_update_generative_question_configs.js - * region_tag:retail_v2alpha_generated_GenerativeQuestionService_BatchUpdateGenerativeQuestionConfigs_async - */ + /** + * Allows management of multiple questions. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} [request.parent] + * Optional. Resource name of the parent catalog. + * Format: projects/{project}/locations/{location}/catalogs/{catalog} + * @param {number[]} request.requests + * Required. The updates question configs. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.BatchUpdateGenerativeQuestionConfigsResponse|BatchUpdateGenerativeQuestionConfigsResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/generative_question_service.batch_update_generative_question_configs.js + * region_tag:retail_v2alpha_generated_GenerativeQuestionService_BatchUpdateGenerativeQuestionConfigs_async + */ batchUpdateGenerativeQuestionConfigs( - request?: protos.google.cloud.retail.v2alpha.IBatchUpdateGenerativeQuestionConfigsRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.retail.v2alpha.IBatchUpdateGenerativeQuestionConfigsResponse, - protos.google.cloud.retail.v2alpha.IBatchUpdateGenerativeQuestionConfigsRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.IBatchUpdateGenerativeQuestionConfigsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IBatchUpdateGenerativeQuestionConfigsResponse, + ( + | protos.google.cloud.retail.v2alpha.IBatchUpdateGenerativeQuestionConfigsRequest + | undefined + ), + {} | undefined, + ] + >; batchUpdateGenerativeQuestionConfigs( - request: protos.google.cloud.retail.v2alpha.IBatchUpdateGenerativeQuestionConfigsRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.retail.v2alpha.IBatchUpdateGenerativeQuestionConfigsResponse, - protos.google.cloud.retail.v2alpha.IBatchUpdateGenerativeQuestionConfigsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IBatchUpdateGenerativeQuestionConfigsRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.retail.v2alpha.IBatchUpdateGenerativeQuestionConfigsResponse, + | protos.google.cloud.retail.v2alpha.IBatchUpdateGenerativeQuestionConfigsRequest + | null + | undefined, + {} | null | undefined + >, + ): void; batchUpdateGenerativeQuestionConfigs( - request: protos.google.cloud.retail.v2alpha.IBatchUpdateGenerativeQuestionConfigsRequest, - callback: Callback< - protos.google.cloud.retail.v2alpha.IBatchUpdateGenerativeQuestionConfigsResponse, - protos.google.cloud.retail.v2alpha.IBatchUpdateGenerativeQuestionConfigsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IBatchUpdateGenerativeQuestionConfigsRequest, + callback: Callback< + protos.google.cloud.retail.v2alpha.IBatchUpdateGenerativeQuestionConfigsResponse, + | protos.google.cloud.retail.v2alpha.IBatchUpdateGenerativeQuestionConfigsRequest + | null + | undefined, + {} | null | undefined + >, + ): void; batchUpdateGenerativeQuestionConfigs( - request?: protos.google.cloud.retail.v2alpha.IBatchUpdateGenerativeQuestionConfigsRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.cloud.retail.v2alpha.IBatchUpdateGenerativeQuestionConfigsRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.retail.v2alpha.IBatchUpdateGenerativeQuestionConfigsResponse, - protos.google.cloud.retail.v2alpha.IBatchUpdateGenerativeQuestionConfigsRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.cloud.retail.v2alpha.IBatchUpdateGenerativeQuestionConfigsResponse, - protos.google.cloud.retail.v2alpha.IBatchUpdateGenerativeQuestionConfigsRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.retail.v2alpha.IBatchUpdateGenerativeQuestionConfigsResponse, - protos.google.cloud.retail.v2alpha.IBatchUpdateGenerativeQuestionConfigsRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.retail.v2alpha.IBatchUpdateGenerativeQuestionConfigsRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.retail.v2alpha.IBatchUpdateGenerativeQuestionConfigsResponse, + | protos.google.cloud.retail.v2alpha.IBatchUpdateGenerativeQuestionConfigsRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IBatchUpdateGenerativeQuestionConfigsResponse, + ( + | protos.google.cloud.retail.v2alpha.IBatchUpdateGenerativeQuestionConfigsRequest + | undefined + ), + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('batchUpdateGenerativeQuestionConfigs request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.retail.v2alpha.IBatchUpdateGenerativeQuestionConfigsResponse, - protos.google.cloud.retail.v2alpha.IBatchUpdateGenerativeQuestionConfigsRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.retail.v2alpha.IBatchUpdateGenerativeQuestionConfigsResponse, + | protos.google.cloud.retail.v2alpha.IBatchUpdateGenerativeQuestionConfigsRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { - this._log.info('batchUpdateGenerativeQuestionConfigs response %j', response); + this._log.info( + 'batchUpdateGenerativeQuestionConfigs response %j', + response, + ); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.batchUpdateGenerativeQuestionConfigs(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.retail.v2alpha.IBatchUpdateGenerativeQuestionConfigsResponse, - protos.google.cloud.retail.v2alpha.IBatchUpdateGenerativeQuestionConfigsRequest|undefined, - {}|undefined - ]) => { - this._log.info('batchUpdateGenerativeQuestionConfigs response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .batchUpdateGenerativeQuestionConfigs(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.retail.v2alpha.IBatchUpdateGenerativeQuestionConfigsResponse, + ( + | protos.google.cloud.retail.v2alpha.IBatchUpdateGenerativeQuestionConfigsRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info( + 'batchUpdateGenerativeQuestionConfigs response %j', + response, + ); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); @@ -857,7 +1180,7 @@ export class GenerativeQuestionServiceClient { * @param {string} project * @returns {string} Resource name string. */ - alertConfigPath(project:string) { + alertConfigPath(project: string) { return this.pathTemplates.alertConfigPathTemplate.render({ project: project, }); @@ -871,7 +1194,8 @@ export class GenerativeQuestionServiceClient { * @returns {string} A string representing the project. */ matchProjectFromAlertConfigName(alertConfigName: string) { - return this.pathTemplates.alertConfigPathTemplate.match(alertConfigName).project; + return this.pathTemplates.alertConfigPathTemplate.match(alertConfigName) + .project; } /** @@ -882,7 +1206,7 @@ export class GenerativeQuestionServiceClient { * @param {string} catalog * @returns {string} Resource name string. */ - attributesConfigPath(project:string,location:string,catalog:string) { + attributesConfigPath(project: string, location: string, catalog: string) { return this.pathTemplates.attributesConfigPathTemplate.render({ project: project, location: location, @@ -898,7 +1222,9 @@ export class GenerativeQuestionServiceClient { * @returns {string} A string representing the project. */ matchProjectFromAttributesConfigName(attributesConfigName: string) { - return this.pathTemplates.attributesConfigPathTemplate.match(attributesConfigName).project; + return this.pathTemplates.attributesConfigPathTemplate.match( + attributesConfigName, + ).project; } /** @@ -909,7 +1235,9 @@ export class GenerativeQuestionServiceClient { * @returns {string} A string representing the location. */ matchLocationFromAttributesConfigName(attributesConfigName: string) { - return this.pathTemplates.attributesConfigPathTemplate.match(attributesConfigName).location; + return this.pathTemplates.attributesConfigPathTemplate.match( + attributesConfigName, + ).location; } /** @@ -920,7 +1248,9 @@ export class GenerativeQuestionServiceClient { * @returns {string} A string representing the catalog. */ matchCatalogFromAttributesConfigName(attributesConfigName: string) { - return this.pathTemplates.attributesConfigPathTemplate.match(attributesConfigName).catalog; + return this.pathTemplates.attributesConfigPathTemplate.match( + attributesConfigName, + ).catalog; } /** @@ -932,7 +1262,12 @@ export class GenerativeQuestionServiceClient { * @param {string} branch * @returns {string} Resource name string. */ - branchPath(project:string,location:string,catalog:string,branch:string) { + branchPath( + project: string, + location: string, + catalog: string, + branch: string, + ) { return this.pathTemplates.branchPathTemplate.render({ project: project, location: location, @@ -993,7 +1328,7 @@ export class GenerativeQuestionServiceClient { * @param {string} catalog * @returns {string} Resource name string. */ - catalogPath(project:string,location:string,catalog:string) { + catalogPath(project: string, location: string, catalog: string) { return this.pathTemplates.catalogPathTemplate.render({ project: project, location: location, @@ -1042,7 +1377,7 @@ export class GenerativeQuestionServiceClient { * @param {string} catalog * @returns {string} Resource name string. */ - completionConfigPath(project:string,location:string,catalog:string) { + completionConfigPath(project: string, location: string, catalog: string) { return this.pathTemplates.completionConfigPathTemplate.render({ project: project, location: location, @@ -1058,7 +1393,9 @@ export class GenerativeQuestionServiceClient { * @returns {string} A string representing the project. */ matchProjectFromCompletionConfigName(completionConfigName: string) { - return this.pathTemplates.completionConfigPathTemplate.match(completionConfigName).project; + return this.pathTemplates.completionConfigPathTemplate.match( + completionConfigName, + ).project; } /** @@ -1069,7 +1406,9 @@ export class GenerativeQuestionServiceClient { * @returns {string} A string representing the location. */ matchLocationFromCompletionConfigName(completionConfigName: string) { - return this.pathTemplates.completionConfigPathTemplate.match(completionConfigName).location; + return this.pathTemplates.completionConfigPathTemplate.match( + completionConfigName, + ).location; } /** @@ -1080,7 +1419,9 @@ export class GenerativeQuestionServiceClient { * @returns {string} A string representing the catalog. */ matchCatalogFromCompletionConfigName(completionConfigName: string) { - return this.pathTemplates.completionConfigPathTemplate.match(completionConfigName).catalog; + return this.pathTemplates.completionConfigPathTemplate.match( + completionConfigName, + ).catalog; } /** @@ -1092,7 +1433,12 @@ export class GenerativeQuestionServiceClient { * @param {string} control * @returns {string} Resource name string. */ - controlPath(project:string,location:string,catalog:string,control:string) { + controlPath( + project: string, + location: string, + catalog: string, + control: string, + ) { return this.pathTemplates.controlPathTemplate.render({ project: project, location: location, @@ -1151,7 +1497,7 @@ export class GenerativeQuestionServiceClient { * @param {string} project * @returns {string} Resource name string. */ - loggingConfigPath(project:string) { + loggingConfigPath(project: string) { return this.pathTemplates.loggingConfigPathTemplate.render({ project: project, }); @@ -1165,7 +1511,8 @@ export class GenerativeQuestionServiceClient { * @returns {string} A string representing the project. */ matchProjectFromLoggingConfigName(loggingConfigName: string) { - return this.pathTemplates.loggingConfigPathTemplate.match(loggingConfigName).project; + return this.pathTemplates.loggingConfigPathTemplate.match(loggingConfigName) + .project; } /** @@ -1177,7 +1524,12 @@ export class GenerativeQuestionServiceClient { * @param {string} merchant_center_account_link * @returns {string} Resource name string. */ - merchantCenterAccountLinkPath(project:string,location:string,catalog:string,merchantCenterAccountLink:string) { + merchantCenterAccountLinkPath( + project: string, + location: string, + catalog: string, + merchantCenterAccountLink: string, + ) { return this.pathTemplates.merchantCenterAccountLinkPathTemplate.render({ project: project, location: location, @@ -1193,8 +1545,12 @@ export class GenerativeQuestionServiceClient { * A fully-qualified path representing MerchantCenterAccountLink resource. * @returns {string} A string representing the project. */ - matchProjectFromMerchantCenterAccountLinkName(merchantCenterAccountLinkName: string) { - return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match(merchantCenterAccountLinkName).project; + matchProjectFromMerchantCenterAccountLinkName( + merchantCenterAccountLinkName: string, + ) { + return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match( + merchantCenterAccountLinkName, + ).project; } /** @@ -1204,8 +1560,12 @@ export class GenerativeQuestionServiceClient { * A fully-qualified path representing MerchantCenterAccountLink resource. * @returns {string} A string representing the location. */ - matchLocationFromMerchantCenterAccountLinkName(merchantCenterAccountLinkName: string) { - return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match(merchantCenterAccountLinkName).location; + matchLocationFromMerchantCenterAccountLinkName( + merchantCenterAccountLinkName: string, + ) { + return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match( + merchantCenterAccountLinkName, + ).location; } /** @@ -1215,8 +1575,12 @@ export class GenerativeQuestionServiceClient { * A fully-qualified path representing MerchantCenterAccountLink resource. * @returns {string} A string representing the catalog. */ - matchCatalogFromMerchantCenterAccountLinkName(merchantCenterAccountLinkName: string) { - return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match(merchantCenterAccountLinkName).catalog; + matchCatalogFromMerchantCenterAccountLinkName( + merchantCenterAccountLinkName: string, + ) { + return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match( + merchantCenterAccountLinkName, + ).catalog; } /** @@ -1226,8 +1590,12 @@ export class GenerativeQuestionServiceClient { * A fully-qualified path representing MerchantCenterAccountLink resource. * @returns {string} A string representing the merchant_center_account_link. */ - matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName(merchantCenterAccountLinkName: string) { - return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match(merchantCenterAccountLinkName).merchant_center_account_link; + matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName( + merchantCenterAccountLinkName: string, + ) { + return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match( + merchantCenterAccountLinkName, + ).merchant_center_account_link; } /** @@ -1239,7 +1607,7 @@ export class GenerativeQuestionServiceClient { * @param {string} model * @returns {string} Resource name string. */ - modelPath(project:string,location:string,catalog:string,model:string) { + modelPath(project: string, location: string, catalog: string, model: string) { return this.pathTemplates.modelPathTemplate.render({ project: project, location: location, @@ -1302,7 +1670,13 @@ export class GenerativeQuestionServiceClient { * @param {string} product * @returns {string} Resource name string. */ - productPath(project:string,location:string,catalog:string,branch:string,product:string) { + productPath( + project: string, + location: string, + catalog: string, + branch: string, + product: string, + ) { return this.pathTemplates.productPathTemplate.render({ project: project, location: location, @@ -1373,7 +1747,7 @@ export class GenerativeQuestionServiceClient { * @param {string} project * @returns {string} Resource name string. */ - retailProjectPath(project:string) { + retailProjectPath(project: string) { return this.pathTemplates.retailProjectPathTemplate.render({ project: project, }); @@ -1387,7 +1761,8 @@ export class GenerativeQuestionServiceClient { * @returns {string} A string representing the project. */ matchProjectFromRetailProjectName(retailProjectName: string) { - return this.pathTemplates.retailProjectPathTemplate.match(retailProjectName).project; + return this.pathTemplates.retailProjectPathTemplate.match(retailProjectName) + .project; } /** @@ -1399,7 +1774,12 @@ export class GenerativeQuestionServiceClient { * @param {string} serving_config * @returns {string} Resource name string. */ - servingConfigPath(project:string,location:string,catalog:string,servingConfig:string) { + servingConfigPath( + project: string, + location: string, + catalog: string, + servingConfig: string, + ) { return this.pathTemplates.servingConfigPathTemplate.render({ project: project, location: location, @@ -1416,7 +1796,8 @@ export class GenerativeQuestionServiceClient { * @returns {string} A string representing the project. */ matchProjectFromServingConfigName(servingConfigName: string) { - return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName).project; + return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName) + .project; } /** @@ -1427,7 +1808,8 @@ export class GenerativeQuestionServiceClient { * @returns {string} A string representing the location. */ matchLocationFromServingConfigName(servingConfigName: string) { - return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName).location; + return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName) + .location; } /** @@ -1438,7 +1820,8 @@ export class GenerativeQuestionServiceClient { * @returns {string} A string representing the catalog. */ matchCatalogFromServingConfigName(servingConfigName: string) { - return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName).catalog; + return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName) + .catalog; } /** @@ -1449,7 +1832,8 @@ export class GenerativeQuestionServiceClient { * @returns {string} A string representing the serving_config. */ matchServingConfigFromServingConfigName(servingConfigName: string) { - return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName).serving_config; + return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName) + .serving_config; } /** @@ -1460,7 +1844,7 @@ export class GenerativeQuestionServiceClient { */ close(): Promise { if (this.generativeQuestionServiceStub && !this._terminated) { - return this.generativeQuestionServiceStub.then(stub => { + return this.generativeQuestionServiceStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -1468,4 +1852,4 @@ export class GenerativeQuestionServiceClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/core/generator/gapic-generator-typescript/baselines/retail/src/v2alpha/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/retail/src/v2alpha/index.ts.baseline index 24776f3d0790..c9d477ad404b 100644 --- a/core/generator/gapic-generator-typescript/baselines/retail/src/v2alpha/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/retail/src/v2alpha/index.ts.baseline @@ -16,18 +16,18 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -export {AnalyticsServiceClient} from './analytics_service_client'; -export {BranchServiceClient} from './branch_service_client'; -export {CatalogServiceClient} from './catalog_service_client'; -export {CompletionServiceClient} from './completion_service_client'; -export {ControlServiceClient} from './control_service_client'; -export {ConversationalSearchServiceClient} from './conversational_search_service_client'; -export {GenerativeQuestionServiceClient} from './generative_question_service_client'; -export {MerchantCenterAccountLinkServiceClient} from './merchant_center_account_link_service_client'; -export {ModelServiceClient} from './model_service_client'; -export {PredictionServiceClient} from './prediction_service_client'; -export {ProductServiceClient} from './product_service_client'; -export {ProjectServiceClient} from './project_service_client'; -export {SearchServiceClient} from './search_service_client'; -export {ServingConfigServiceClient} from './serving_config_service_client'; -export {UserEventServiceClient} from './user_event_service_client'; +export { AnalyticsServiceClient } from './analytics_service_client'; +export { BranchServiceClient } from './branch_service_client'; +export { CatalogServiceClient } from './catalog_service_client'; +export { CompletionServiceClient } from './completion_service_client'; +export { ControlServiceClient } from './control_service_client'; +export { ConversationalSearchServiceClient } from './conversational_search_service_client'; +export { GenerativeQuestionServiceClient } from './generative_question_service_client'; +export { MerchantCenterAccountLinkServiceClient } from './merchant_center_account_link_service_client'; +export { ModelServiceClient } from './model_service_client'; +export { PredictionServiceClient } from './prediction_service_client'; +export { ProductServiceClient } from './product_service_client'; +export { ProjectServiceClient } from './project_service_client'; +export { SearchServiceClient } from './search_service_client'; +export { ServingConfigServiceClient } from './serving_config_service_client'; +export { UserEventServiceClient } from './user_event_service_client'; diff --git a/core/generator/gapic-generator-typescript/baselines/retail/src/v2alpha/merchant_center_account_link_service_client.ts.baseline b/core/generator/gapic-generator-typescript/baselines/retail/src/v2alpha/merchant_center_account_link_service_client.ts.baseline index be13d9272727..0defa4c3b54d 100644 --- a/core/generator/gapic-generator-typescript/baselines/retail/src/v2alpha/merchant_center_account_link_service_client.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/retail/src/v2alpha/merchant_center_account_link_service_client.ts.baseline @@ -18,11 +18,18 @@ /* global window */ import type * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions, GrpcClientOptions, LROperation} from 'google-gax'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + GrpcClientOptions, + LROperation, +} from 'google-gax'; import * as protos from '../../protos/protos'; import jsonProtos = require('../../protos/protos.json'); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; /** * Client JSON configuration object, loaded from @@ -44,7 +51,7 @@ export class MerchantCenterAccountLinkServiceClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('retail'); @@ -57,10 +64,10 @@ export class MerchantCenterAccountLinkServiceClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; operationsClient: gax.OperationsClient; - merchantCenterAccountLinkServiceStub?: Promise<{[name: string]: Function}>; + merchantCenterAccountLinkServiceStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of MerchantCenterAccountLinkServiceClient. @@ -101,21 +108,43 @@ export class MerchantCenterAccountLinkServiceClient { * const client = new MerchantCenterAccountLinkServiceClient({fallback: true}, gax); * ``` */ - constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { // Ensure that options include all the required fields. - const staticMembers = this.constructor as typeof MerchantCenterAccountLinkServiceClient; - if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { - throw new Error('Please set either universe_domain or universeDomain, but not both.'); + const staticMembers = this + .constructor as typeof MerchantCenterAccountLinkServiceClient; + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); } - const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; - this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; this._servicePath = 'retail.' + this._universeDomain; - const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; - const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. if (servicePath !== this._servicePath && !('scopes' in opts)) { @@ -137,7 +166,7 @@ export class MerchantCenterAccountLinkServiceClient { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; @@ -151,10 +180,7 @@ export class MerchantCenterAccountLinkServiceClient { } // Determine the client header string. - const clientHeader = [ - `gax/${this._gaxModule.version}`, - `gapic/${version}`, - ]; + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/${process.versions.node}`); } else { @@ -176,40 +202,40 @@ export class MerchantCenterAccountLinkServiceClient { // Create useful helper objects for these. this.pathTemplates = { alertConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/alertConfig' + 'projects/{project}/alertConfig', ), attributesConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/attributesConfig' + 'projects/{project}/locations/{location}/catalogs/{catalog}/attributesConfig', ), branchPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}', ), catalogPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}' + 'projects/{project}/locations/{location}/catalogs/{catalog}', ), completionConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/completionConfig' + 'projects/{project}/locations/{location}/catalogs/{catalog}/completionConfig', ), controlPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/controls/{control}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/controls/{control}', ), loggingConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/loggingConfig' + 'projects/{project}/loggingConfig', ), merchantCenterAccountLinkPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/merchantCenterAccountLinks/{merchant_center_account_link}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/merchantCenterAccountLinks/{merchant_center_account_link}', ), modelPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/models/{model}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/models/{model}', ), productPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}', ), retailProjectPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/retailProject' + 'projects/{project}/retailProject', ), servingConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/servingConfigs/{serving_config}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/servingConfigs/{serving_config}', ), }; @@ -219,31 +245,65 @@ export class MerchantCenterAccountLinkServiceClient { // rather than holding a request open. const lroOptions: GrpcClientOptions = { auth: this.auth, - grpc: 'grpc' in this._gaxGrpc ? this._gaxGrpc.grpc : undefined + grpc: 'grpc' in this._gaxGrpc ? this._gaxGrpc.grpc : undefined, }; if (opts.fallback) { lroOptions.protoJson = protoFilesRoot; - lroOptions.httpRules = [{selector: 'google.longrunning.Operations.GetOperation',get: '/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*/operations/*}',additional_bindings: [{get: '/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*/places/*/operations/*}',},{get: '/v2alpha/{name=projects/*/locations/*/catalogs/*/operations/*}',},{get: '/v2alpha/{name=projects/*/locations/*/operations/*}',},{get: '/v2alpha/{name=projects/*/operations/*}',}], - },{selector: 'google.longrunning.Operations.ListOperations',get: '/v2alpha/{name=projects/*/locations/*/catalogs/*}/operations',additional_bindings: [{get: '/v2alpha/{name=projects/*/locations/*}/operations',},{get: '/v2alpha/{name=projects/*}/operations',}], - }]; + lroOptions.httpRules = [ + { + selector: 'google.longrunning.Operations.GetOperation', + get: '/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*/operations/*}', + additional_bindings: [ + { + get: '/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*/places/*/operations/*}', + }, + { + get: '/v2alpha/{name=projects/*/locations/*/catalogs/*/operations/*}', + }, + { get: '/v2alpha/{name=projects/*/locations/*/operations/*}' }, + { get: '/v2alpha/{name=projects/*/operations/*}' }, + ], + }, + { + selector: 'google.longrunning.Operations.ListOperations', + get: '/v2alpha/{name=projects/*/locations/*/catalogs/*}/operations', + additional_bindings: [ + { get: '/v2alpha/{name=projects/*/locations/*}/operations' }, + { get: '/v2alpha/{name=projects/*}/operations' }, + ], + }, + ]; } - this.operationsClient = this._gaxModule.lro(lroOptions).operationsClient(opts); + this.operationsClient = this._gaxModule + .lro(lroOptions) + .operationsClient(opts); const createMerchantCenterAccountLinkResponse = protoFilesRoot.lookup( - '.google.cloud.retail.v2alpha.MerchantCenterAccountLink') as gax.protobuf.Type; + '.google.cloud.retail.v2alpha.MerchantCenterAccountLink', + ) as gax.protobuf.Type; const createMerchantCenterAccountLinkMetadata = protoFilesRoot.lookup( - '.google.cloud.retail.v2alpha.CreateMerchantCenterAccountLinkMetadata') as gax.protobuf.Type; + '.google.cloud.retail.v2alpha.CreateMerchantCenterAccountLinkMetadata', + ) as gax.protobuf.Type; this.descriptors.longrunning = { - createMerchantCenterAccountLink: new this._gaxModule.LongrunningDescriptor( - this.operationsClient, - createMerchantCenterAccountLinkResponse.decode.bind(createMerchantCenterAccountLinkResponse), - createMerchantCenterAccountLinkMetadata.decode.bind(createMerchantCenterAccountLinkMetadata)) + createMerchantCenterAccountLink: + new this._gaxModule.LongrunningDescriptor( + this.operationsClient, + createMerchantCenterAccountLinkResponse.decode.bind( + createMerchantCenterAccountLinkResponse, + ), + createMerchantCenterAccountLinkMetadata.decode.bind( + createMerchantCenterAccountLinkMetadata, + ), + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.cloud.retail.v2alpha.MerchantCenterAccountLinkService', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.cloud.retail.v2alpha.MerchantCenterAccountLinkService', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + { 'x-goog-api-client': clientHeader.join(' ') }, + ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -274,37 +334,45 @@ export class MerchantCenterAccountLinkServiceClient { // Put together the "service stub" for // google.cloud.retail.v2alpha.MerchantCenterAccountLinkService. this.merchantCenterAccountLinkServiceStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.cloud.retail.v2alpha.MerchantCenterAccountLinkService') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any - (this._protos as any).google.cloud.retail.v2alpha.MerchantCenterAccountLinkService, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.cloud.retail.v2alpha.MerchantCenterAccountLinkService', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any + (this._protos as any).google.cloud.retail.v2alpha + .MerchantCenterAccountLinkService, + this._opts, + this._providedCustomServicePath, + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const merchantCenterAccountLinkServiceStubMethods = - ['listMerchantCenterAccountLinks', 'createMerchantCenterAccountLink', 'deleteMerchantCenterAccountLink']; + const merchantCenterAccountLinkServiceStubMethods = [ + 'listMerchantCenterAccountLinks', + 'createMerchantCenterAccountLink', + 'deleteMerchantCenterAccountLink', + ]; for (const methodName of merchantCenterAccountLinkServiceStubMethods) { const callPromise = this.merchantCenterAccountLinkServiceStub.then( - stub => (...args: Array<{}>) => { - if (this._terminated) { - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error|null|undefined) => () => { + (stub) => + (...args: Array<{}>) => { + if (this._terminated) { + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { throw err; - }); + }, + ); - const descriptor = - this.descriptors.longrunning[methodName] || - undefined; + const descriptor = this.descriptors.longrunning[methodName] || undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -319,8 +387,14 @@ export class MerchantCenterAccountLinkServiceClient { * @returns {string} The DNS address for this service. */ static get servicePath() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'retail.googleapis.com'; } @@ -331,8 +405,14 @@ export class MerchantCenterAccountLinkServiceClient { * @returns {string} The DNS address for this service. */ static get apiEndpoint() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'retail.googleapis.com'; } @@ -363,9 +443,7 @@ export class MerchantCenterAccountLinkServiceClient { * @returns {string[]} List of default scopes. */ static get scopes() { - return [ - 'https://www.googleapis.com/auth/cloud-platform' - ]; + return ['https://www.googleapis.com/auth/cloud-platform']; } getProjectId(): Promise; @@ -374,8 +452,9 @@ export class MerchantCenterAccountLinkServiceClient { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId(callback?: Callback): - Promise|void { + getProjectId( + callback?: Callback, + ): Promise | void { if (callback) { this.auth.getProjectId(callback); return; @@ -386,322 +465,500 @@ export class MerchantCenterAccountLinkServiceClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Lists all - * {@link protos.google.cloud.retail.v2alpha.MerchantCenterAccountLink|MerchantCenterAccountLink}s - * under the specified parent {@link protos.google.cloud.retail.v2alpha.Catalog|Catalog}. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent Catalog of the resource. - * It must match this format: - * `projects/{PROJECT_NUMBER}/locations/global/catalogs/{CATALOG_ID}` - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.ListMerchantCenterAccountLinksResponse|ListMerchantCenterAccountLinksResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/merchant_center_account_link_service.list_merchant_center_account_links.js - * region_tag:retail_v2alpha_generated_MerchantCenterAccountLinkService_ListMerchantCenterAccountLinks_async - */ + /** + * Lists all + * {@link protos.google.cloud.retail.v2alpha.MerchantCenterAccountLink|MerchantCenterAccountLink}s + * under the specified parent {@link protos.google.cloud.retail.v2alpha.Catalog|Catalog}. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent Catalog of the resource. + * It must match this format: + * `projects/{PROJECT_NUMBER}/locations/global/catalogs/{CATALOG_ID}` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.ListMerchantCenterAccountLinksResponse|ListMerchantCenterAccountLinksResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/merchant_center_account_link_service.list_merchant_center_account_links.js + * region_tag:retail_v2alpha_generated_MerchantCenterAccountLinkService_ListMerchantCenterAccountLinks_async + */ listMerchantCenterAccountLinks( - request?: protos.google.cloud.retail.v2alpha.IListMerchantCenterAccountLinksRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.retail.v2alpha.IListMerchantCenterAccountLinksResponse, - protos.google.cloud.retail.v2alpha.IListMerchantCenterAccountLinksRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.IListMerchantCenterAccountLinksRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IListMerchantCenterAccountLinksResponse, + ( + | protos.google.cloud.retail.v2alpha.IListMerchantCenterAccountLinksRequest + | undefined + ), + {} | undefined, + ] + >; listMerchantCenterAccountLinks( - request: protos.google.cloud.retail.v2alpha.IListMerchantCenterAccountLinksRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.retail.v2alpha.IListMerchantCenterAccountLinksResponse, - protos.google.cloud.retail.v2alpha.IListMerchantCenterAccountLinksRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IListMerchantCenterAccountLinksRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.retail.v2alpha.IListMerchantCenterAccountLinksResponse, + | protos.google.cloud.retail.v2alpha.IListMerchantCenterAccountLinksRequest + | null + | undefined, + {} | null | undefined + >, + ): void; listMerchantCenterAccountLinks( - request: protos.google.cloud.retail.v2alpha.IListMerchantCenterAccountLinksRequest, - callback: Callback< - protos.google.cloud.retail.v2alpha.IListMerchantCenterAccountLinksResponse, - protos.google.cloud.retail.v2alpha.IListMerchantCenterAccountLinksRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IListMerchantCenterAccountLinksRequest, + callback: Callback< + protos.google.cloud.retail.v2alpha.IListMerchantCenterAccountLinksResponse, + | protos.google.cloud.retail.v2alpha.IListMerchantCenterAccountLinksRequest + | null + | undefined, + {} | null | undefined + >, + ): void; listMerchantCenterAccountLinks( - request?: protos.google.cloud.retail.v2alpha.IListMerchantCenterAccountLinksRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.cloud.retail.v2alpha.IListMerchantCenterAccountLinksRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.retail.v2alpha.IListMerchantCenterAccountLinksResponse, - protos.google.cloud.retail.v2alpha.IListMerchantCenterAccountLinksRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.cloud.retail.v2alpha.IListMerchantCenterAccountLinksResponse, - protos.google.cloud.retail.v2alpha.IListMerchantCenterAccountLinksRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.retail.v2alpha.IListMerchantCenterAccountLinksResponse, - protos.google.cloud.retail.v2alpha.IListMerchantCenterAccountLinksRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.retail.v2alpha.IListMerchantCenterAccountLinksRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.retail.v2alpha.IListMerchantCenterAccountLinksResponse, + | protos.google.cloud.retail.v2alpha.IListMerchantCenterAccountLinksRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IListMerchantCenterAccountLinksResponse, + ( + | protos.google.cloud.retail.v2alpha.IListMerchantCenterAccountLinksRequest + | undefined + ), + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('listMerchantCenterAccountLinks request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.retail.v2alpha.IListMerchantCenterAccountLinksResponse, - protos.google.cloud.retail.v2alpha.IListMerchantCenterAccountLinksRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.retail.v2alpha.IListMerchantCenterAccountLinksResponse, + | protos.google.cloud.retail.v2alpha.IListMerchantCenterAccountLinksRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { - this._log.info('listMerchantCenterAccountLinks response %j', response); + this._log.info( + 'listMerchantCenterAccountLinks response %j', + response, + ); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.listMerchantCenterAccountLinks(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.retail.v2alpha.IListMerchantCenterAccountLinksResponse, - protos.google.cloud.retail.v2alpha.IListMerchantCenterAccountLinksRequest|undefined, - {}|undefined - ]) => { - this._log.info('listMerchantCenterAccountLinks response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .listMerchantCenterAccountLinks(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.retail.v2alpha.IListMerchantCenterAccountLinksResponse, + ( + | protos.google.cloud.retail.v2alpha.IListMerchantCenterAccountLinksRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info( + 'listMerchantCenterAccountLinks response %j', + response, + ); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Deletes a - * {@link protos.google.cloud.retail.v2alpha.MerchantCenterAccountLink|MerchantCenterAccountLink}. - * If the - * {@link protos.google.cloud.retail.v2alpha.MerchantCenterAccountLink|MerchantCenterAccountLink} - * to delete does not exist, a NOT_FOUND error is returned. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. Full resource name. Format: - * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/merchantCenterAccountLinks/{merchant_center_account_link_id}` - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/merchant_center_account_link_service.delete_merchant_center_account_link.js - * region_tag:retail_v2alpha_generated_MerchantCenterAccountLinkService_DeleteMerchantCenterAccountLink_async - */ + /** + * Deletes a + * {@link protos.google.cloud.retail.v2alpha.MerchantCenterAccountLink|MerchantCenterAccountLink}. + * If the + * {@link protos.google.cloud.retail.v2alpha.MerchantCenterAccountLink|MerchantCenterAccountLink} + * to delete does not exist, a NOT_FOUND error is returned. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Full resource name. Format: + * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/merchantCenterAccountLinks/{merchant_center_account_link_id}` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/merchant_center_account_link_service.delete_merchant_center_account_link.js + * region_tag:retail_v2alpha_generated_MerchantCenterAccountLinkService_DeleteMerchantCenterAccountLink_async + */ deleteMerchantCenterAccountLink( - request?: protos.google.cloud.retail.v2alpha.IDeleteMerchantCenterAccountLinkRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.cloud.retail.v2alpha.IDeleteMerchantCenterAccountLinkRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.IDeleteMerchantCenterAccountLinkRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.cloud.retail.v2alpha.IDeleteMerchantCenterAccountLinkRequest + | undefined + ), + {} | undefined, + ] + >; deleteMerchantCenterAccountLink( - request: protos.google.cloud.retail.v2alpha.IDeleteMerchantCenterAccountLinkRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.cloud.retail.v2alpha.IDeleteMerchantCenterAccountLinkRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IDeleteMerchantCenterAccountLinkRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.cloud.retail.v2alpha.IDeleteMerchantCenterAccountLinkRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteMerchantCenterAccountLink( - request: protos.google.cloud.retail.v2alpha.IDeleteMerchantCenterAccountLinkRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.cloud.retail.v2alpha.IDeleteMerchantCenterAccountLinkRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IDeleteMerchantCenterAccountLinkRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.cloud.retail.v2alpha.IDeleteMerchantCenterAccountLinkRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteMerchantCenterAccountLink( - request?: protos.google.cloud.retail.v2alpha.IDeleteMerchantCenterAccountLinkRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.protobuf.IEmpty, - protos.google.cloud.retail.v2alpha.IDeleteMerchantCenterAccountLinkRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.retail.v2alpha.IDeleteMerchantCenterAccountLinkRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.cloud.retail.v2alpha.IDeleteMerchantCenterAccountLinkRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.cloud.retail.v2alpha.IDeleteMerchantCenterAccountLinkRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.retail.v2alpha.IDeleteMerchantCenterAccountLinkRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + | protos.google.cloud.retail.v2alpha.IDeleteMerchantCenterAccountLinkRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.cloud.retail.v2alpha.IDeleteMerchantCenterAccountLinkRequest + | undefined + ), + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('deleteMerchantCenterAccountLink request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.cloud.retail.v2alpha.IDeleteMerchantCenterAccountLinkRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.cloud.retail.v2alpha.IDeleteMerchantCenterAccountLinkRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { - this._log.info('deleteMerchantCenterAccountLink response %j', response); + this._log.info( + 'deleteMerchantCenterAccountLink response %j', + response, + ); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.deleteMerchantCenterAccountLink(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.cloud.retail.v2alpha.IDeleteMerchantCenterAccountLinkRequest|undefined, - {}|undefined - ]) => { - this._log.info('deleteMerchantCenterAccountLink response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteMerchantCenterAccountLink(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + ( + | protos.google.cloud.retail.v2alpha.IDeleteMerchantCenterAccountLinkRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info( + 'deleteMerchantCenterAccountLink response %j', + response, + ); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Creates a - * {@link protos.google.cloud.retail.v2alpha.MerchantCenterAccountLink|MerchantCenterAccountLink}. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The branch resource where this MerchantCenterAccountLink will be - * created. Format: - * `projects/{PROJECT_NUMBER}/locations/global/catalogs/{CATALOG_ID}` - * @param {google.cloud.retail.v2alpha.MerchantCenterAccountLink} request.merchantCenterAccountLink - * Required. The - * {@link protos.google.cloud.retail.v2alpha.MerchantCenterAccountLink|MerchantCenterAccountLink} - * to create. - * - * If the caller does not have permission to create the - * {@link protos.google.cloud.retail.v2alpha.MerchantCenterAccountLink|MerchantCenterAccountLink}, - * regardless of whether or not it exists, a PERMISSION_DENIED error is - * returned. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing - * a long running operation. Its `promise()` method returns a promise - * you can `await` for. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/merchant_center_account_link_service.create_merchant_center_account_link.js - * region_tag:retail_v2alpha_generated_MerchantCenterAccountLinkService_CreateMerchantCenterAccountLink_async - */ + /** + * Creates a + * {@link protos.google.cloud.retail.v2alpha.MerchantCenterAccountLink|MerchantCenterAccountLink}. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The branch resource where this MerchantCenterAccountLink will be + * created. Format: + * `projects/{PROJECT_NUMBER}/locations/global/catalogs/{CATALOG_ID}` + * @param {google.cloud.retail.v2alpha.MerchantCenterAccountLink} request.merchantCenterAccountLink + * Required. The + * {@link protos.google.cloud.retail.v2alpha.MerchantCenterAccountLink|MerchantCenterAccountLink} + * to create. + * + * If the caller does not have permission to create the + * {@link protos.google.cloud.retail.v2alpha.MerchantCenterAccountLink|MerchantCenterAccountLink}, + * regardless of whether or not it exists, a PERMISSION_DENIED error is + * returned. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/merchant_center_account_link_service.create_merchant_center_account_link.js + * region_tag:retail_v2alpha_generated_MerchantCenterAccountLinkService_CreateMerchantCenterAccountLink_async + */ createMerchantCenterAccountLink( - request?: protos.google.cloud.retail.v2alpha.ICreateMerchantCenterAccountLinkRequest, - options?: CallOptions): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.ICreateMerchantCenterAccountLinkRequest, + options?: CallOptions, + ): Promise< + [ + LROperation< + protos.google.cloud.retail.v2alpha.IMerchantCenterAccountLink, + protos.google.cloud.retail.v2alpha.ICreateMerchantCenterAccountLinkMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; createMerchantCenterAccountLink( - request: protos.google.cloud.retail.v2alpha.ICreateMerchantCenterAccountLinkRequest, - options: CallOptions, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.ICreateMerchantCenterAccountLinkRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IMerchantCenterAccountLink, + protos.google.cloud.retail.v2alpha.ICreateMerchantCenterAccountLinkMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; createMerchantCenterAccountLink( - request: protos.google.cloud.retail.v2alpha.ICreateMerchantCenterAccountLinkRequest, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.ICreateMerchantCenterAccountLinkRequest, + callback: Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IMerchantCenterAccountLink, + protos.google.cloud.retail.v2alpha.ICreateMerchantCenterAccountLinkMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; createMerchantCenterAccountLink( - request?: protos.google.cloud.retail.v2alpha.ICreateMerchantCenterAccountLinkRequest, - optionsOrCallback?: CallOptions|Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>, - callback?: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>|void { + request?: protos.google.cloud.retail.v2alpha.ICreateMerchantCenterAccountLinkRequest, + optionsOrCallback?: + | CallOptions + | Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IMerchantCenterAccountLink, + protos.google.cloud.retail.v2alpha.ICreateMerchantCenterAccountLinkMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + callback?: Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IMerchantCenterAccountLink, + protos.google.cloud.retail.v2alpha.ICreateMerchantCenterAccountLinkMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + LROperation< + protos.google.cloud.retail.v2alpha.IMerchantCenterAccountLink, + protos.google.cloud.retail.v2alpha.ICreateMerchantCenterAccountLinkMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IMerchantCenterAccountLink, + protos.google.cloud.retail.v2alpha.ICreateMerchantCenterAccountLinkMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, rawResponse, _) => { - this._log.info('createMerchantCenterAccountLink response %j', rawResponse); + this._log.info( + 'createMerchantCenterAccountLink response %j', + rawResponse, + ); callback!(error, response, rawResponse, _); // We verified callback above. } : undefined; this._log.info('createMerchantCenterAccountLink request %j', request); - return this.innerApiCalls.createMerchantCenterAccountLink(request, options, wrappedCallback) - ?.then(([response, rawResponse, _]: [ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]) => { - this._log.info('createMerchantCenterAccountLink response %j', rawResponse); - return [response, rawResponse, _]; - }); + return this.innerApiCalls + .createMerchantCenterAccountLink(request, options, wrappedCallback) + ?.then( + ([response, rawResponse, _]: [ + LROperation< + protos.google.cloud.retail.v2alpha.IMerchantCenterAccountLink, + protos.google.cloud.retail.v2alpha.ICreateMerchantCenterAccountLinkMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ]) => { + this._log.info( + 'createMerchantCenterAccountLink response %j', + rawResponse, + ); + return [response, rawResponse, _]; + }, + ); } -/** - * Check the status of the long running operation returned by `createMerchantCenterAccountLink()`. - * @param {String} name - * The operation name that will be passed. - * @returns {Promise} - The promise which resolves to an object. - * The decoded operation object has result and metadata field to get information from. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/merchant_center_account_link_service.create_merchant_center_account_link.js - * region_tag:retail_v2alpha_generated_MerchantCenterAccountLinkService_CreateMerchantCenterAccountLink_async - */ - async checkCreateMerchantCenterAccountLinkProgress(name: string): Promise>{ + /** + * Check the status of the long running operation returned by `createMerchantCenterAccountLink()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/merchant_center_account_link_service.create_merchant_center_account_link.js + * region_tag:retail_v2alpha_generated_MerchantCenterAccountLinkService_CreateMerchantCenterAccountLink_async + */ + async checkCreateMerchantCenterAccountLinkProgress( + name: string, + ): Promise< + LROperation< + protos.google.cloud.retail.v2alpha.MerchantCenterAccountLink, + protos.google.cloud.retail.v2alpha.CreateMerchantCenterAccountLinkMetadata + > + > { this._log.info('createMerchantCenterAccountLink long-running'); - const request = new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest({name}); + const request = + new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( + { name }, + ); const [operation] = await this.operationsClient.getOperation(request); - const decodeOperation = new this._gaxModule.Operation(operation, this.descriptors.longrunning.createMerchantCenterAccountLink, this._gaxModule.createDefaultBackoffSettings()); - return decodeOperation as LROperation; + const decodeOperation = new this._gaxModule.Operation( + operation, + this.descriptors.longrunning.createMerchantCenterAccountLink, + this._gaxModule.createDefaultBackoffSettings(), + ); + return decodeOperation as LROperation< + protos.google.cloud.retail.v2alpha.MerchantCenterAccountLink, + protos.google.cloud.retail.v2alpha.CreateMerchantCenterAccountLinkMetadata + >; } // -------------------- // -- Path templates -- @@ -713,7 +970,7 @@ export class MerchantCenterAccountLinkServiceClient { * @param {string} project * @returns {string} Resource name string. */ - alertConfigPath(project:string) { + alertConfigPath(project: string) { return this.pathTemplates.alertConfigPathTemplate.render({ project: project, }); @@ -727,7 +984,8 @@ export class MerchantCenterAccountLinkServiceClient { * @returns {string} A string representing the project. */ matchProjectFromAlertConfigName(alertConfigName: string) { - return this.pathTemplates.alertConfigPathTemplate.match(alertConfigName).project; + return this.pathTemplates.alertConfigPathTemplate.match(alertConfigName) + .project; } /** @@ -738,7 +996,7 @@ export class MerchantCenterAccountLinkServiceClient { * @param {string} catalog * @returns {string} Resource name string. */ - attributesConfigPath(project:string,location:string,catalog:string) { + attributesConfigPath(project: string, location: string, catalog: string) { return this.pathTemplates.attributesConfigPathTemplate.render({ project: project, location: location, @@ -754,7 +1012,9 @@ export class MerchantCenterAccountLinkServiceClient { * @returns {string} A string representing the project. */ matchProjectFromAttributesConfigName(attributesConfigName: string) { - return this.pathTemplates.attributesConfigPathTemplate.match(attributesConfigName).project; + return this.pathTemplates.attributesConfigPathTemplate.match( + attributesConfigName, + ).project; } /** @@ -765,7 +1025,9 @@ export class MerchantCenterAccountLinkServiceClient { * @returns {string} A string representing the location. */ matchLocationFromAttributesConfigName(attributesConfigName: string) { - return this.pathTemplates.attributesConfigPathTemplate.match(attributesConfigName).location; + return this.pathTemplates.attributesConfigPathTemplate.match( + attributesConfigName, + ).location; } /** @@ -776,7 +1038,9 @@ export class MerchantCenterAccountLinkServiceClient { * @returns {string} A string representing the catalog. */ matchCatalogFromAttributesConfigName(attributesConfigName: string) { - return this.pathTemplates.attributesConfigPathTemplate.match(attributesConfigName).catalog; + return this.pathTemplates.attributesConfigPathTemplate.match( + attributesConfigName, + ).catalog; } /** @@ -788,7 +1052,12 @@ export class MerchantCenterAccountLinkServiceClient { * @param {string} branch * @returns {string} Resource name string. */ - branchPath(project:string,location:string,catalog:string,branch:string) { + branchPath( + project: string, + location: string, + catalog: string, + branch: string, + ) { return this.pathTemplates.branchPathTemplate.render({ project: project, location: location, @@ -849,7 +1118,7 @@ export class MerchantCenterAccountLinkServiceClient { * @param {string} catalog * @returns {string} Resource name string. */ - catalogPath(project:string,location:string,catalog:string) { + catalogPath(project: string, location: string, catalog: string) { return this.pathTemplates.catalogPathTemplate.render({ project: project, location: location, @@ -898,7 +1167,7 @@ export class MerchantCenterAccountLinkServiceClient { * @param {string} catalog * @returns {string} Resource name string. */ - completionConfigPath(project:string,location:string,catalog:string) { + completionConfigPath(project: string, location: string, catalog: string) { return this.pathTemplates.completionConfigPathTemplate.render({ project: project, location: location, @@ -914,7 +1183,9 @@ export class MerchantCenterAccountLinkServiceClient { * @returns {string} A string representing the project. */ matchProjectFromCompletionConfigName(completionConfigName: string) { - return this.pathTemplates.completionConfigPathTemplate.match(completionConfigName).project; + return this.pathTemplates.completionConfigPathTemplate.match( + completionConfigName, + ).project; } /** @@ -925,7 +1196,9 @@ export class MerchantCenterAccountLinkServiceClient { * @returns {string} A string representing the location. */ matchLocationFromCompletionConfigName(completionConfigName: string) { - return this.pathTemplates.completionConfigPathTemplate.match(completionConfigName).location; + return this.pathTemplates.completionConfigPathTemplate.match( + completionConfigName, + ).location; } /** @@ -936,7 +1209,9 @@ export class MerchantCenterAccountLinkServiceClient { * @returns {string} A string representing the catalog. */ matchCatalogFromCompletionConfigName(completionConfigName: string) { - return this.pathTemplates.completionConfigPathTemplate.match(completionConfigName).catalog; + return this.pathTemplates.completionConfigPathTemplate.match( + completionConfigName, + ).catalog; } /** @@ -948,7 +1223,12 @@ export class MerchantCenterAccountLinkServiceClient { * @param {string} control * @returns {string} Resource name string. */ - controlPath(project:string,location:string,catalog:string,control:string) { + controlPath( + project: string, + location: string, + catalog: string, + control: string, + ) { return this.pathTemplates.controlPathTemplate.render({ project: project, location: location, @@ -1007,7 +1287,7 @@ export class MerchantCenterAccountLinkServiceClient { * @param {string} project * @returns {string} Resource name string. */ - loggingConfigPath(project:string) { + loggingConfigPath(project: string) { return this.pathTemplates.loggingConfigPathTemplate.render({ project: project, }); @@ -1021,7 +1301,8 @@ export class MerchantCenterAccountLinkServiceClient { * @returns {string} A string representing the project. */ matchProjectFromLoggingConfigName(loggingConfigName: string) { - return this.pathTemplates.loggingConfigPathTemplate.match(loggingConfigName).project; + return this.pathTemplates.loggingConfigPathTemplate.match(loggingConfigName) + .project; } /** @@ -1033,7 +1314,12 @@ export class MerchantCenterAccountLinkServiceClient { * @param {string} merchant_center_account_link * @returns {string} Resource name string. */ - merchantCenterAccountLinkPath(project:string,location:string,catalog:string,merchantCenterAccountLink:string) { + merchantCenterAccountLinkPath( + project: string, + location: string, + catalog: string, + merchantCenterAccountLink: string, + ) { return this.pathTemplates.merchantCenterAccountLinkPathTemplate.render({ project: project, location: location, @@ -1049,8 +1335,12 @@ export class MerchantCenterAccountLinkServiceClient { * A fully-qualified path representing MerchantCenterAccountLink resource. * @returns {string} A string representing the project. */ - matchProjectFromMerchantCenterAccountLinkName(merchantCenterAccountLinkName: string) { - return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match(merchantCenterAccountLinkName).project; + matchProjectFromMerchantCenterAccountLinkName( + merchantCenterAccountLinkName: string, + ) { + return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match( + merchantCenterAccountLinkName, + ).project; } /** @@ -1060,8 +1350,12 @@ export class MerchantCenterAccountLinkServiceClient { * A fully-qualified path representing MerchantCenterAccountLink resource. * @returns {string} A string representing the location. */ - matchLocationFromMerchantCenterAccountLinkName(merchantCenterAccountLinkName: string) { - return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match(merchantCenterAccountLinkName).location; + matchLocationFromMerchantCenterAccountLinkName( + merchantCenterAccountLinkName: string, + ) { + return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match( + merchantCenterAccountLinkName, + ).location; } /** @@ -1071,8 +1365,12 @@ export class MerchantCenterAccountLinkServiceClient { * A fully-qualified path representing MerchantCenterAccountLink resource. * @returns {string} A string representing the catalog. */ - matchCatalogFromMerchantCenterAccountLinkName(merchantCenterAccountLinkName: string) { - return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match(merchantCenterAccountLinkName).catalog; + matchCatalogFromMerchantCenterAccountLinkName( + merchantCenterAccountLinkName: string, + ) { + return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match( + merchantCenterAccountLinkName, + ).catalog; } /** @@ -1082,8 +1380,12 @@ export class MerchantCenterAccountLinkServiceClient { * A fully-qualified path representing MerchantCenterAccountLink resource. * @returns {string} A string representing the merchant_center_account_link. */ - matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName(merchantCenterAccountLinkName: string) { - return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match(merchantCenterAccountLinkName).merchant_center_account_link; + matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName( + merchantCenterAccountLinkName: string, + ) { + return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match( + merchantCenterAccountLinkName, + ).merchant_center_account_link; } /** @@ -1095,7 +1397,7 @@ export class MerchantCenterAccountLinkServiceClient { * @param {string} model * @returns {string} Resource name string. */ - modelPath(project:string,location:string,catalog:string,model:string) { + modelPath(project: string, location: string, catalog: string, model: string) { return this.pathTemplates.modelPathTemplate.render({ project: project, location: location, @@ -1158,7 +1460,13 @@ export class MerchantCenterAccountLinkServiceClient { * @param {string} product * @returns {string} Resource name string. */ - productPath(project:string,location:string,catalog:string,branch:string,product:string) { + productPath( + project: string, + location: string, + catalog: string, + branch: string, + product: string, + ) { return this.pathTemplates.productPathTemplate.render({ project: project, location: location, @@ -1229,7 +1537,7 @@ export class MerchantCenterAccountLinkServiceClient { * @param {string} project * @returns {string} Resource name string. */ - retailProjectPath(project:string) { + retailProjectPath(project: string) { return this.pathTemplates.retailProjectPathTemplate.render({ project: project, }); @@ -1243,7 +1551,8 @@ export class MerchantCenterAccountLinkServiceClient { * @returns {string} A string representing the project. */ matchProjectFromRetailProjectName(retailProjectName: string) { - return this.pathTemplates.retailProjectPathTemplate.match(retailProjectName).project; + return this.pathTemplates.retailProjectPathTemplate.match(retailProjectName) + .project; } /** @@ -1255,7 +1564,12 @@ export class MerchantCenterAccountLinkServiceClient { * @param {string} serving_config * @returns {string} Resource name string. */ - servingConfigPath(project:string,location:string,catalog:string,servingConfig:string) { + servingConfigPath( + project: string, + location: string, + catalog: string, + servingConfig: string, + ) { return this.pathTemplates.servingConfigPathTemplate.render({ project: project, location: location, @@ -1272,7 +1586,8 @@ export class MerchantCenterAccountLinkServiceClient { * @returns {string} A string representing the project. */ matchProjectFromServingConfigName(servingConfigName: string) { - return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName).project; + return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName) + .project; } /** @@ -1283,7 +1598,8 @@ export class MerchantCenterAccountLinkServiceClient { * @returns {string} A string representing the location. */ matchLocationFromServingConfigName(servingConfigName: string) { - return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName).location; + return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName) + .location; } /** @@ -1294,7 +1610,8 @@ export class MerchantCenterAccountLinkServiceClient { * @returns {string} A string representing the catalog. */ matchCatalogFromServingConfigName(servingConfigName: string) { - return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName).catalog; + return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName) + .catalog; } /** @@ -1305,7 +1622,8 @@ export class MerchantCenterAccountLinkServiceClient { * @returns {string} A string representing the serving_config. */ matchServingConfigFromServingConfigName(servingConfigName: string) { - return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName).serving_config; + return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName) + .serving_config; } /** @@ -1316,7 +1634,7 @@ export class MerchantCenterAccountLinkServiceClient { */ close(): Promise { if (this.merchantCenterAccountLinkServiceStub && !this._terminated) { - return this.merchantCenterAccountLinkServiceStub.then(stub => { + return this.merchantCenterAccountLinkServiceStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -1325,4 +1643,4 @@ export class MerchantCenterAccountLinkServiceClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/core/generator/gapic-generator-typescript/baselines/retail/src/v2alpha/model_service_client.ts.baseline b/core/generator/gapic-generator-typescript/baselines/retail/src/v2alpha/model_service_client.ts.baseline index f0b115cd6681..eaa6df8ce9ff 100644 --- a/core/generator/gapic-generator-typescript/baselines/retail/src/v2alpha/model_service_client.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/retail/src/v2alpha/model_service_client.ts.baseline @@ -18,11 +18,20 @@ /* global window */ import type * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions, GrpcClientOptions, LROperation, PaginationCallback, GaxCall} from 'google-gax'; -import {Transform} from 'stream'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + GrpcClientOptions, + LROperation, + PaginationCallback, + GaxCall, +} from 'google-gax'; +import { Transform } from 'stream'; import * as protos from '../../protos/protos'; import jsonProtos = require('../../protos/protos.json'); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; /** * Client JSON configuration object, loaded from @@ -55,7 +64,7 @@ export class ModelServiceClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('retail'); @@ -68,10 +77,10 @@ export class ModelServiceClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; operationsClient: gax.OperationsClient; - modelServiceStub?: Promise<{[name: string]: Function}>; + modelServiceStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of ModelServiceClient. @@ -112,21 +121,42 @@ export class ModelServiceClient { * const client = new ModelServiceClient({fallback: true}, gax); * ``` */ - constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { // Ensure that options include all the required fields. const staticMembers = this.constructor as typeof ModelServiceClient; - if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { - throw new Error('Please set either universe_domain or universeDomain, but not both.'); + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); } - const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; - this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; this._servicePath = 'retail.' + this._universeDomain; - const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; - const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. if (servicePath !== this._servicePath && !('scopes' in opts)) { @@ -148,7 +178,7 @@ export class ModelServiceClient { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; @@ -162,10 +192,7 @@ export class ModelServiceClient { } // Determine the client header string. - const clientHeader = [ - `gax/${this._gaxModule.version}`, - `gapic/${version}`, - ]; + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/${process.versions.node}`); } else { @@ -187,40 +214,40 @@ export class ModelServiceClient { // Create useful helper objects for these. this.pathTemplates = { alertConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/alertConfig' + 'projects/{project}/alertConfig', ), attributesConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/attributesConfig' + 'projects/{project}/locations/{location}/catalogs/{catalog}/attributesConfig', ), branchPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}', ), catalogPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}' + 'projects/{project}/locations/{location}/catalogs/{catalog}', ), completionConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/completionConfig' + 'projects/{project}/locations/{location}/catalogs/{catalog}/completionConfig', ), controlPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/controls/{control}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/controls/{control}', ), loggingConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/loggingConfig' + 'projects/{project}/loggingConfig', ), merchantCenterAccountLinkPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/merchantCenterAccountLinks/{merchant_center_account_link}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/merchantCenterAccountLinks/{merchant_center_account_link}', ), modelPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/models/{model}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/models/{model}', ), productPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}', ), retailProjectPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/retailProject' + 'projects/{project}/retailProject', ), servingConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/servingConfigs/{serving_config}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/servingConfigs/{serving_config}', ), }; @@ -228,8 +255,11 @@ export class ModelServiceClient { // (e.g. 50 results at a time, with tokens to get subsequent // pages). Denote the keys used for pagination and results. this.descriptors.page = { - listModels: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'models') + listModels: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'models', + ), }; const protoFilesRoot = this._gaxModule.protobufFromJSON(jsonProtos); @@ -238,39 +268,71 @@ export class ModelServiceClient { // rather than holding a request open. const lroOptions: GrpcClientOptions = { auth: this.auth, - grpc: 'grpc' in this._gaxGrpc ? this._gaxGrpc.grpc : undefined + grpc: 'grpc' in this._gaxGrpc ? this._gaxGrpc.grpc : undefined, }; if (opts.fallback) { lroOptions.protoJson = protoFilesRoot; - lroOptions.httpRules = [{selector: 'google.longrunning.Operations.GetOperation',get: '/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*/operations/*}',additional_bindings: [{get: '/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*/places/*/operations/*}',},{get: '/v2alpha/{name=projects/*/locations/*/catalogs/*/operations/*}',},{get: '/v2alpha/{name=projects/*/locations/*/operations/*}',},{get: '/v2alpha/{name=projects/*/operations/*}',}], - },{selector: 'google.longrunning.Operations.ListOperations',get: '/v2alpha/{name=projects/*/locations/*/catalogs/*}/operations',additional_bindings: [{get: '/v2alpha/{name=projects/*/locations/*}/operations',},{get: '/v2alpha/{name=projects/*}/operations',}], - }]; + lroOptions.httpRules = [ + { + selector: 'google.longrunning.Operations.GetOperation', + get: '/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*/operations/*}', + additional_bindings: [ + { + get: '/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*/places/*/operations/*}', + }, + { + get: '/v2alpha/{name=projects/*/locations/*/catalogs/*/operations/*}', + }, + { get: '/v2alpha/{name=projects/*/locations/*/operations/*}' }, + { get: '/v2alpha/{name=projects/*/operations/*}' }, + ], + }, + { + selector: 'google.longrunning.Operations.ListOperations', + get: '/v2alpha/{name=projects/*/locations/*/catalogs/*}/operations', + additional_bindings: [ + { get: '/v2alpha/{name=projects/*/locations/*}/operations' }, + { get: '/v2alpha/{name=projects/*}/operations' }, + ], + }, + ]; } - this.operationsClient = this._gaxModule.lro(lroOptions).operationsClient(opts); + this.operationsClient = this._gaxModule + .lro(lroOptions) + .operationsClient(opts); const createModelResponse = protoFilesRoot.lookup( - '.google.cloud.retail.v2alpha.Model') as gax.protobuf.Type; + '.google.cloud.retail.v2alpha.Model', + ) as gax.protobuf.Type; const createModelMetadata = protoFilesRoot.lookup( - '.google.cloud.retail.v2alpha.CreateModelMetadata') as gax.protobuf.Type; + '.google.cloud.retail.v2alpha.CreateModelMetadata', + ) as gax.protobuf.Type; const tuneModelResponse = protoFilesRoot.lookup( - '.google.cloud.retail.v2alpha.TuneModelResponse') as gax.protobuf.Type; + '.google.cloud.retail.v2alpha.TuneModelResponse', + ) as gax.protobuf.Type; const tuneModelMetadata = protoFilesRoot.lookup( - '.google.cloud.retail.v2alpha.TuneModelMetadata') as gax.protobuf.Type; + '.google.cloud.retail.v2alpha.TuneModelMetadata', + ) as gax.protobuf.Type; this.descriptors.longrunning = { createModel: new this._gaxModule.LongrunningDescriptor( this.operationsClient, createModelResponse.decode.bind(createModelResponse), - createModelMetadata.decode.bind(createModelMetadata)), + createModelMetadata.decode.bind(createModelMetadata), + ), tuneModel: new this._gaxModule.LongrunningDescriptor( this.operationsClient, tuneModelResponse.decode.bind(tuneModelResponse), - tuneModelMetadata.decode.bind(tuneModelMetadata)) + tuneModelMetadata.decode.bind(tuneModelMetadata), + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.cloud.retail.v2alpha.ModelService', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.cloud.retail.v2alpha.ModelService', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + { 'x-goog-api-client': clientHeader.join(' ') }, + ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -301,28 +363,42 @@ export class ModelServiceClient { // Put together the "service stub" for // google.cloud.retail.v2alpha.ModelService. this.modelServiceStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.cloud.retail.v2alpha.ModelService') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.cloud.retail.v2alpha.ModelService', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.cloud.retail.v2alpha.ModelService, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts, + this._providedCustomServicePath, + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const modelServiceStubMethods = - ['createModel', 'getModel', 'pauseModel', 'resumeModel', 'deleteModel', 'listModels', 'updateModel', 'tuneModel']; + const modelServiceStubMethods = [ + 'createModel', + 'getModel', + 'pauseModel', + 'resumeModel', + 'deleteModel', + 'listModels', + 'updateModel', + 'tuneModel', + ]; for (const methodName of modelServiceStubMethods) { const callPromise = this.modelServiceStub.then( - stub => (...args: Array<{}>) => { - if (this._terminated) { - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error|null|undefined) => () => { + (stub) => + (...args: Array<{}>) => { + if (this._terminated) { + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { throw err; - }); + }, + ); const descriptor = this.descriptors.page[methodName] || @@ -332,7 +408,7 @@ export class ModelServiceClient { callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -347,8 +423,14 @@ export class ModelServiceClient { * @returns {string} The DNS address for this service. */ static get servicePath() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'retail.googleapis.com'; } @@ -359,8 +441,14 @@ export class ModelServiceClient { * @returns {string} The DNS address for this service. */ static get apiEndpoint() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'retail.googleapis.com'; } @@ -391,9 +479,7 @@ export class ModelServiceClient { * @returns {string[]} List of default scopes. */ static get scopes() { - return [ - 'https://www.googleapis.com/auth/cloud-platform' - ]; + return ['https://www.googleapis.com/auth/cloud-platform']; } getProjectId(): Promise; @@ -402,8 +488,9 @@ export class ModelServiceClient { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId(callback?: Callback): - Promise|void { + getProjectId( + callback?: Callback, + ): Promise | void { if (callback) { this.auth.getProjectId(callback); return; @@ -414,800 +501,1113 @@ export class ModelServiceClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Gets a model. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The resource name of the - * {@link protos.google.cloud.retail.v2alpha.Model|Model} to get. Format: - * `projects/{project_number}/locations/{location_id}/catalogs/{catalog}/models/{model_id}` - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.Model|Model}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/model_service.get_model.js - * region_tag:retail_v2alpha_generated_ModelService_GetModel_async - */ + /** + * Gets a model. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The resource name of the + * {@link protos.google.cloud.retail.v2alpha.Model|Model} to get. Format: + * `projects/{project_number}/locations/{location_id}/catalogs/{catalog}/models/{model_id}` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.Model|Model}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/model_service.get_model.js + * region_tag:retail_v2alpha_generated_ModelService_GetModel_async + */ getModel( - request?: protos.google.cloud.retail.v2alpha.IGetModelRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.retail.v2alpha.IModel, - protos.google.cloud.retail.v2alpha.IGetModelRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.IGetModelRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IModel, + protos.google.cloud.retail.v2alpha.IGetModelRequest | undefined, + {} | undefined, + ] + >; getModel( - request: protos.google.cloud.retail.v2alpha.IGetModelRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.retail.v2alpha.IModel, - protos.google.cloud.retail.v2alpha.IGetModelRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IGetModelRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.retail.v2alpha.IModel, + protos.google.cloud.retail.v2alpha.IGetModelRequest | null | undefined, + {} | null | undefined + >, + ): void; getModel( - request: protos.google.cloud.retail.v2alpha.IGetModelRequest, - callback: Callback< - protos.google.cloud.retail.v2alpha.IModel, - protos.google.cloud.retail.v2alpha.IGetModelRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IGetModelRequest, + callback: Callback< + protos.google.cloud.retail.v2alpha.IModel, + protos.google.cloud.retail.v2alpha.IGetModelRequest | null | undefined, + {} | null | undefined + >, + ): void; getModel( - request?: protos.google.cloud.retail.v2alpha.IGetModelRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.cloud.retail.v2alpha.IGetModelRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.retail.v2alpha.IModel, - protos.google.cloud.retail.v2alpha.IGetModelRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.cloud.retail.v2alpha.IModel, - protos.google.cloud.retail.v2alpha.IGetModelRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.retail.v2alpha.IModel, - protos.google.cloud.retail.v2alpha.IGetModelRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.retail.v2alpha.IGetModelRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.retail.v2alpha.IModel, + protos.google.cloud.retail.v2alpha.IGetModelRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IModel, + protos.google.cloud.retail.v2alpha.IGetModelRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getModel request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.retail.v2alpha.IModel, - protos.google.cloud.retail.v2alpha.IGetModelRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.retail.v2alpha.IModel, + | protos.google.cloud.retail.v2alpha.IGetModelRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getModel response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getModel(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.retail.v2alpha.IModel, - protos.google.cloud.retail.v2alpha.IGetModelRequest|undefined, - {}|undefined - ]) => { - this._log.info('getModel response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getModel(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.retail.v2alpha.IModel, + protos.google.cloud.retail.v2alpha.IGetModelRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getModel response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Pauses the training of an existing model. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The name of the model to pause. - * Format: - * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/models/{model_id}` - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.Model|Model}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/model_service.pause_model.js - * region_tag:retail_v2alpha_generated_ModelService_PauseModel_async - */ + /** + * Pauses the training of an existing model. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The name of the model to pause. + * Format: + * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/models/{model_id}` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.Model|Model}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/model_service.pause_model.js + * region_tag:retail_v2alpha_generated_ModelService_PauseModel_async + */ pauseModel( - request?: protos.google.cloud.retail.v2alpha.IPauseModelRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.retail.v2alpha.IModel, - protos.google.cloud.retail.v2alpha.IPauseModelRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.IPauseModelRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IModel, + protos.google.cloud.retail.v2alpha.IPauseModelRequest | undefined, + {} | undefined, + ] + >; pauseModel( - request: protos.google.cloud.retail.v2alpha.IPauseModelRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.retail.v2alpha.IModel, - protos.google.cloud.retail.v2alpha.IPauseModelRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IPauseModelRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.retail.v2alpha.IModel, + protos.google.cloud.retail.v2alpha.IPauseModelRequest | null | undefined, + {} | null | undefined + >, + ): void; pauseModel( - request: protos.google.cloud.retail.v2alpha.IPauseModelRequest, - callback: Callback< - protos.google.cloud.retail.v2alpha.IModel, - protos.google.cloud.retail.v2alpha.IPauseModelRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IPauseModelRequest, + callback: Callback< + protos.google.cloud.retail.v2alpha.IModel, + protos.google.cloud.retail.v2alpha.IPauseModelRequest | null | undefined, + {} | null | undefined + >, + ): void; pauseModel( - request?: protos.google.cloud.retail.v2alpha.IPauseModelRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.retail.v2alpha.IModel, - protos.google.cloud.retail.v2alpha.IPauseModelRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.retail.v2alpha.IPauseModelRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.retail.v2alpha.IModel, - protos.google.cloud.retail.v2alpha.IPauseModelRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.retail.v2alpha.IModel, - protos.google.cloud.retail.v2alpha.IPauseModelRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.retail.v2alpha.IPauseModelRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.retail.v2alpha.IModel, + protos.google.cloud.retail.v2alpha.IPauseModelRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IModel, + protos.google.cloud.retail.v2alpha.IPauseModelRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('pauseModel request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.retail.v2alpha.IModel, - protos.google.cloud.retail.v2alpha.IPauseModelRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.retail.v2alpha.IModel, + | protos.google.cloud.retail.v2alpha.IPauseModelRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('pauseModel response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.pauseModel(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.retail.v2alpha.IModel, - protos.google.cloud.retail.v2alpha.IPauseModelRequest|undefined, - {}|undefined - ]) => { - this._log.info('pauseModel response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .pauseModel(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.retail.v2alpha.IModel, + protos.google.cloud.retail.v2alpha.IPauseModelRequest | undefined, + {} | undefined, + ]) => { + this._log.info('pauseModel response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Resumes the training of an existing model. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The name of the model to resume. - * Format: - * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/models/{model_id}` - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.Model|Model}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/model_service.resume_model.js - * region_tag:retail_v2alpha_generated_ModelService_ResumeModel_async - */ + /** + * Resumes the training of an existing model. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The name of the model to resume. + * Format: + * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/models/{model_id}` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.Model|Model}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/model_service.resume_model.js + * region_tag:retail_v2alpha_generated_ModelService_ResumeModel_async + */ resumeModel( - request?: protos.google.cloud.retail.v2alpha.IResumeModelRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.retail.v2alpha.IModel, - protos.google.cloud.retail.v2alpha.IResumeModelRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.IResumeModelRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IModel, + protos.google.cloud.retail.v2alpha.IResumeModelRequest | undefined, + {} | undefined, + ] + >; resumeModel( - request: protos.google.cloud.retail.v2alpha.IResumeModelRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.retail.v2alpha.IModel, - protos.google.cloud.retail.v2alpha.IResumeModelRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IResumeModelRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.retail.v2alpha.IModel, + protos.google.cloud.retail.v2alpha.IResumeModelRequest | null | undefined, + {} | null | undefined + >, + ): void; resumeModel( - request: protos.google.cloud.retail.v2alpha.IResumeModelRequest, - callback: Callback< - protos.google.cloud.retail.v2alpha.IModel, - protos.google.cloud.retail.v2alpha.IResumeModelRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IResumeModelRequest, + callback: Callback< + protos.google.cloud.retail.v2alpha.IModel, + protos.google.cloud.retail.v2alpha.IResumeModelRequest | null | undefined, + {} | null | undefined + >, + ): void; resumeModel( - request?: protos.google.cloud.retail.v2alpha.IResumeModelRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.retail.v2alpha.IModel, - protos.google.cloud.retail.v2alpha.IResumeModelRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.retail.v2alpha.IResumeModelRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.retail.v2alpha.IModel, - protos.google.cloud.retail.v2alpha.IResumeModelRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.retail.v2alpha.IModel, - protos.google.cloud.retail.v2alpha.IResumeModelRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.retail.v2alpha.IResumeModelRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.retail.v2alpha.IModel, + protos.google.cloud.retail.v2alpha.IResumeModelRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IModel, + protos.google.cloud.retail.v2alpha.IResumeModelRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('resumeModel request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.retail.v2alpha.IModel, - protos.google.cloud.retail.v2alpha.IResumeModelRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.retail.v2alpha.IModel, + | protos.google.cloud.retail.v2alpha.IResumeModelRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('resumeModel response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.resumeModel(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.retail.v2alpha.IModel, - protos.google.cloud.retail.v2alpha.IResumeModelRequest|undefined, - {}|undefined - ]) => { - this._log.info('resumeModel response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .resumeModel(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.retail.v2alpha.IModel, + protos.google.cloud.retail.v2alpha.IResumeModelRequest | undefined, + {} | undefined, + ]) => { + this._log.info('resumeModel response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Deletes an existing model. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The resource name of the - * {@link protos.google.cloud.retail.v2alpha.Model|Model} to delete. Format: - * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/models/{model_id}` - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/model_service.delete_model.js - * region_tag:retail_v2alpha_generated_ModelService_DeleteModel_async - */ + /** + * Deletes an existing model. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The resource name of the + * {@link protos.google.cloud.retail.v2alpha.Model|Model} to delete. Format: + * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/models/{model_id}` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/model_service.delete_model.js + * region_tag:retail_v2alpha_generated_ModelService_DeleteModel_async + */ deleteModel( - request?: protos.google.cloud.retail.v2alpha.IDeleteModelRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.cloud.retail.v2alpha.IDeleteModelRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.IDeleteModelRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.cloud.retail.v2alpha.IDeleteModelRequest | undefined, + {} | undefined, + ] + >; deleteModel( - request: protos.google.cloud.retail.v2alpha.IDeleteModelRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.cloud.retail.v2alpha.IDeleteModelRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IDeleteModelRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.cloud.retail.v2alpha.IDeleteModelRequest | null | undefined, + {} | null | undefined + >, + ): void; deleteModel( - request: protos.google.cloud.retail.v2alpha.IDeleteModelRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.cloud.retail.v2alpha.IDeleteModelRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IDeleteModelRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.cloud.retail.v2alpha.IDeleteModelRequest | null | undefined, + {} | null | undefined + >, + ): void; deleteModel( - request?: protos.google.cloud.retail.v2alpha.IDeleteModelRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.cloud.retail.v2alpha.IDeleteModelRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.cloud.retail.v2alpha.IDeleteModelRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.protobuf.IEmpty, - protos.google.cloud.retail.v2alpha.IDeleteModelRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.cloud.retail.v2alpha.IDeleteModelRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.retail.v2alpha.IDeleteModelRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + protos.google.cloud.retail.v2alpha.IDeleteModelRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.cloud.retail.v2alpha.IDeleteModelRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('deleteModel request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.cloud.retail.v2alpha.IDeleteModelRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.cloud.retail.v2alpha.IDeleteModelRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteModel response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.deleteModel(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.cloud.retail.v2alpha.IDeleteModelRequest|undefined, - {}|undefined - ]) => { - this._log.info('deleteModel response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteModel(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.cloud.retail.v2alpha.IDeleteModelRequest | undefined, + {} | undefined, + ]) => { + this._log.info('deleteModel response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Update of model metadata. Only fields that - * currently can be updated are: `filtering_option` and - * `periodic_tuning_state`. - * If other values are provided, this API method ignores them. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.cloud.retail.v2alpha.Model} request.model - * Required. The body of the updated - * {@link protos.google.cloud.retail.v2alpha.Model|Model}. - * @param {google.protobuf.FieldMask} [request.updateMask] - * Optional. Indicates which fields in the provided 'model' to - * update. If not set, by default updates all fields. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.Model|Model}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/model_service.update_model.js - * region_tag:retail_v2alpha_generated_ModelService_UpdateModel_async - */ + /** + * Update of model metadata. Only fields that + * currently can be updated are: `filtering_option` and + * `periodic_tuning_state`. + * If other values are provided, this API method ignores them. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.cloud.retail.v2alpha.Model} request.model + * Required. The body of the updated + * {@link protos.google.cloud.retail.v2alpha.Model|Model}. + * @param {google.protobuf.FieldMask} [request.updateMask] + * Optional. Indicates which fields in the provided 'model' to + * update. If not set, by default updates all fields. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.Model|Model}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/model_service.update_model.js + * region_tag:retail_v2alpha_generated_ModelService_UpdateModel_async + */ updateModel( - request?: protos.google.cloud.retail.v2alpha.IUpdateModelRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.retail.v2alpha.IModel, - protos.google.cloud.retail.v2alpha.IUpdateModelRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.IUpdateModelRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IModel, + protos.google.cloud.retail.v2alpha.IUpdateModelRequest | undefined, + {} | undefined, + ] + >; updateModel( - request: protos.google.cloud.retail.v2alpha.IUpdateModelRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.retail.v2alpha.IModel, - protos.google.cloud.retail.v2alpha.IUpdateModelRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IUpdateModelRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.retail.v2alpha.IModel, + protos.google.cloud.retail.v2alpha.IUpdateModelRequest | null | undefined, + {} | null | undefined + >, + ): void; updateModel( - request: protos.google.cloud.retail.v2alpha.IUpdateModelRequest, - callback: Callback< - protos.google.cloud.retail.v2alpha.IModel, - protos.google.cloud.retail.v2alpha.IUpdateModelRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IUpdateModelRequest, + callback: Callback< + protos.google.cloud.retail.v2alpha.IModel, + protos.google.cloud.retail.v2alpha.IUpdateModelRequest | null | undefined, + {} | null | undefined + >, + ): void; updateModel( - request?: protos.google.cloud.retail.v2alpha.IUpdateModelRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.retail.v2alpha.IModel, - protos.google.cloud.retail.v2alpha.IUpdateModelRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.retail.v2alpha.IUpdateModelRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.retail.v2alpha.IModel, - protos.google.cloud.retail.v2alpha.IUpdateModelRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.retail.v2alpha.IModel, - protos.google.cloud.retail.v2alpha.IUpdateModelRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.retail.v2alpha.IUpdateModelRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.retail.v2alpha.IModel, + protos.google.cloud.retail.v2alpha.IUpdateModelRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IModel, + protos.google.cloud.retail.v2alpha.IUpdateModelRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'model.name': request.model!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'model.name': request.model!.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateModel request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.retail.v2alpha.IModel, - protos.google.cloud.retail.v2alpha.IUpdateModelRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.retail.v2alpha.IModel, + | protos.google.cloud.retail.v2alpha.IUpdateModelRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateModel response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.updateModel(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.retail.v2alpha.IModel, - protos.google.cloud.retail.v2alpha.IUpdateModelRequest|undefined, - {}|undefined - ]) => { - this._log.info('updateModel response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateModel(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.retail.v2alpha.IModel, + protos.google.cloud.retail.v2alpha.IUpdateModelRequest | undefined, + {} | undefined, + ]) => { + this._log.info('updateModel response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Creates a new model. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent resource under which to create the model. Format: - * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}` - * @param {google.cloud.retail.v2alpha.Model} request.model - * Required. The payload of the {@link protos.google.cloud.retail.v2alpha.Model|Model} to - * create. - * @param {boolean} [request.dryRun] - * Optional. Whether to run a dry run to validate the request (without - * actually creating the model). - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing - * a long running operation. Its `promise()` method returns a promise - * you can `await` for. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/model_service.create_model.js - * region_tag:retail_v2alpha_generated_ModelService_CreateModel_async - */ + /** + * Creates a new model. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource under which to create the model. Format: + * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}` + * @param {google.cloud.retail.v2alpha.Model} request.model + * Required. The payload of the {@link protos.google.cloud.retail.v2alpha.Model|Model} to + * create. + * @param {boolean} [request.dryRun] + * Optional. Whether to run a dry run to validate the request (without + * actually creating the model). + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/model_service.create_model.js + * region_tag:retail_v2alpha_generated_ModelService_CreateModel_async + */ createModel( - request?: protos.google.cloud.retail.v2alpha.ICreateModelRequest, - options?: CallOptions): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.ICreateModelRequest, + options?: CallOptions, + ): Promise< + [ + LROperation< + protos.google.cloud.retail.v2alpha.IModel, + protos.google.cloud.retail.v2alpha.ICreateModelMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; createModel( - request: protos.google.cloud.retail.v2alpha.ICreateModelRequest, - options: CallOptions, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.ICreateModelRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IModel, + protos.google.cloud.retail.v2alpha.ICreateModelMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; createModel( - request: protos.google.cloud.retail.v2alpha.ICreateModelRequest, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.ICreateModelRequest, + callback: Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IModel, + protos.google.cloud.retail.v2alpha.ICreateModelMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; createModel( - request?: protos.google.cloud.retail.v2alpha.ICreateModelRequest, - optionsOrCallback?: CallOptions|Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>, - callback?: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>|void { + request?: protos.google.cloud.retail.v2alpha.ICreateModelRequest, + optionsOrCallback?: + | CallOptions + | Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IModel, + protos.google.cloud.retail.v2alpha.ICreateModelMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + callback?: Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IModel, + protos.google.cloud.retail.v2alpha.ICreateModelMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + LROperation< + protos.google.cloud.retail.v2alpha.IModel, + protos.google.cloud.retail.v2alpha.ICreateModelMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IModel, + protos.google.cloud.retail.v2alpha.ICreateModelMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, rawResponse, _) => { this._log.info('createModel response %j', rawResponse); callback!(error, response, rawResponse, _); // We verified callback above. } : undefined; this._log.info('createModel request %j', request); - return this.innerApiCalls.createModel(request, options, wrappedCallback) - ?.then(([response, rawResponse, _]: [ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]) => { - this._log.info('createModel response %j', rawResponse); - return [response, rawResponse, _]; - }); + return this.innerApiCalls + .createModel(request, options, wrappedCallback) + ?.then( + ([response, rawResponse, _]: [ + LROperation< + protos.google.cloud.retail.v2alpha.IModel, + protos.google.cloud.retail.v2alpha.ICreateModelMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ]) => { + this._log.info('createModel response %j', rawResponse); + return [response, rawResponse, _]; + }, + ); } -/** - * Check the status of the long running operation returned by `createModel()`. - * @param {String} name - * The operation name that will be passed. - * @returns {Promise} - The promise which resolves to an object. - * The decoded operation object has result and metadata field to get information from. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/model_service.create_model.js - * region_tag:retail_v2alpha_generated_ModelService_CreateModel_async - */ - async checkCreateModelProgress(name: string): Promise>{ + /** + * Check the status of the long running operation returned by `createModel()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/model_service.create_model.js + * region_tag:retail_v2alpha_generated_ModelService_CreateModel_async + */ + async checkCreateModelProgress( + name: string, + ): Promise< + LROperation< + protos.google.cloud.retail.v2alpha.Model, + protos.google.cloud.retail.v2alpha.CreateModelMetadata + > + > { this._log.info('createModel long-running'); - const request = new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest({name}); + const request = + new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( + { name }, + ); const [operation] = await this.operationsClient.getOperation(request); - const decodeOperation = new this._gaxModule.Operation(operation, this.descriptors.longrunning.createModel, this._gaxModule.createDefaultBackoffSettings()); - return decodeOperation as LROperation; + const decodeOperation = new this._gaxModule.Operation( + operation, + this.descriptors.longrunning.createModel, + this._gaxModule.createDefaultBackoffSettings(), + ); + return decodeOperation as LROperation< + protos.google.cloud.retail.v2alpha.Model, + protos.google.cloud.retail.v2alpha.CreateModelMetadata + >; } -/** - * Tunes an existing model. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The resource name of the model to tune. - * Format: - * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/models/{model_id}` - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing - * a long running operation. Its `promise()` method returns a promise - * you can `await` for. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/model_service.tune_model.js - * region_tag:retail_v2alpha_generated_ModelService_TuneModel_async - */ + /** + * Tunes an existing model. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The resource name of the model to tune. + * Format: + * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/models/{model_id}` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/model_service.tune_model.js + * region_tag:retail_v2alpha_generated_ModelService_TuneModel_async + */ tuneModel( - request?: protos.google.cloud.retail.v2alpha.ITuneModelRequest, - options?: CallOptions): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.ITuneModelRequest, + options?: CallOptions, + ): Promise< + [ + LROperation< + protos.google.cloud.retail.v2alpha.ITuneModelResponse, + protos.google.cloud.retail.v2alpha.ITuneModelMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; tuneModel( - request: protos.google.cloud.retail.v2alpha.ITuneModelRequest, - options: CallOptions, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.ITuneModelRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.cloud.retail.v2alpha.ITuneModelResponse, + protos.google.cloud.retail.v2alpha.ITuneModelMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; tuneModel( - request: protos.google.cloud.retail.v2alpha.ITuneModelRequest, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.ITuneModelRequest, + callback: Callback< + LROperation< + protos.google.cloud.retail.v2alpha.ITuneModelResponse, + protos.google.cloud.retail.v2alpha.ITuneModelMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; tuneModel( - request?: protos.google.cloud.retail.v2alpha.ITuneModelRequest, - optionsOrCallback?: CallOptions|Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>, - callback?: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>|void { + request?: protos.google.cloud.retail.v2alpha.ITuneModelRequest, + optionsOrCallback?: + | CallOptions + | Callback< + LROperation< + protos.google.cloud.retail.v2alpha.ITuneModelResponse, + protos.google.cloud.retail.v2alpha.ITuneModelMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + callback?: Callback< + LROperation< + protos.google.cloud.retail.v2alpha.ITuneModelResponse, + protos.google.cloud.retail.v2alpha.ITuneModelMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + LROperation< + protos.google.cloud.retail.v2alpha.ITuneModelResponse, + protos.google.cloud.retail.v2alpha.ITuneModelMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + LROperation< + protos.google.cloud.retail.v2alpha.ITuneModelResponse, + protos.google.cloud.retail.v2alpha.ITuneModelMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, rawResponse, _) => { this._log.info('tuneModel response %j', rawResponse); callback!(error, response, rawResponse, _); // We verified callback above. } : undefined; this._log.info('tuneModel request %j', request); - return this.innerApiCalls.tuneModel(request, options, wrappedCallback) - ?.then(([response, rawResponse, _]: [ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]) => { - this._log.info('tuneModel response %j', rawResponse); - return [response, rawResponse, _]; - }); + return this.innerApiCalls + .tuneModel(request, options, wrappedCallback) + ?.then( + ([response, rawResponse, _]: [ + LROperation< + protos.google.cloud.retail.v2alpha.ITuneModelResponse, + protos.google.cloud.retail.v2alpha.ITuneModelMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ]) => { + this._log.info('tuneModel response %j', rawResponse); + return [response, rawResponse, _]; + }, + ); } -/** - * Check the status of the long running operation returned by `tuneModel()`. - * @param {String} name - * The operation name that will be passed. - * @returns {Promise} - The promise which resolves to an object. - * The decoded operation object has result and metadata field to get information from. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/model_service.tune_model.js - * region_tag:retail_v2alpha_generated_ModelService_TuneModel_async - */ - async checkTuneModelProgress(name: string): Promise>{ + /** + * Check the status of the long running operation returned by `tuneModel()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/model_service.tune_model.js + * region_tag:retail_v2alpha_generated_ModelService_TuneModel_async + */ + async checkTuneModelProgress( + name: string, + ): Promise< + LROperation< + protos.google.cloud.retail.v2alpha.TuneModelResponse, + protos.google.cloud.retail.v2alpha.TuneModelMetadata + > + > { this._log.info('tuneModel long-running'); - const request = new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest({name}); + const request = + new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( + { name }, + ); const [operation] = await this.operationsClient.getOperation(request); - const decodeOperation = new this._gaxModule.Operation(operation, this.descriptors.longrunning.tuneModel, this._gaxModule.createDefaultBackoffSettings()); - return decodeOperation as LROperation; + const decodeOperation = new this._gaxModule.Operation( + operation, + this.descriptors.longrunning.tuneModel, + this._gaxModule.createDefaultBackoffSettings(), + ); + return decodeOperation as LROperation< + protos.google.cloud.retail.v2alpha.TuneModelResponse, + protos.google.cloud.retail.v2alpha.TuneModelMetadata + >; } - /** - * Lists all the models linked to this event store. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent for which to list models. - * Format: - * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}` - * @param {number} [request.pageSize] - * Optional. Maximum number of results to return. If unspecified, defaults - * to 50. Max allowed value is 1000. - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous `ListModels` - * call. Provide this to retrieve the subsequent page. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.cloud.retail.v2alpha.Model|Model}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `listModelsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Lists all the models linked to this event store. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent for which to list models. + * Format: + * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}` + * @param {number} [request.pageSize] + * Optional. Maximum number of results to return. If unspecified, defaults + * to 50. Max allowed value is 1000. + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListModels` + * call. Provide this to retrieve the subsequent page. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.cloud.retail.v2alpha.Model|Model}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listModelsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listModels( - request?: protos.google.cloud.retail.v2alpha.IListModelsRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.retail.v2alpha.IModel[], - protos.google.cloud.retail.v2alpha.IListModelsRequest|null, - protos.google.cloud.retail.v2alpha.IListModelsResponse - ]>; + request?: protos.google.cloud.retail.v2alpha.IListModelsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IModel[], + protos.google.cloud.retail.v2alpha.IListModelsRequest | null, + protos.google.cloud.retail.v2alpha.IListModelsResponse, + ] + >; listModels( - request: protos.google.cloud.retail.v2alpha.IListModelsRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.cloud.retail.v2alpha.IListModelsRequest, - protos.google.cloud.retail.v2alpha.IListModelsResponse|null|undefined, - protos.google.cloud.retail.v2alpha.IModel>): void; + request: protos.google.cloud.retail.v2alpha.IListModelsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.cloud.retail.v2alpha.IListModelsRequest, + protos.google.cloud.retail.v2alpha.IListModelsResponse | null | undefined, + protos.google.cloud.retail.v2alpha.IModel + >, + ): void; listModels( - request: protos.google.cloud.retail.v2alpha.IListModelsRequest, - callback: PaginationCallback< - protos.google.cloud.retail.v2alpha.IListModelsRequest, - protos.google.cloud.retail.v2alpha.IListModelsResponse|null|undefined, - protos.google.cloud.retail.v2alpha.IModel>): void; + request: protos.google.cloud.retail.v2alpha.IListModelsRequest, + callback: PaginationCallback< + protos.google.cloud.retail.v2alpha.IListModelsRequest, + protos.google.cloud.retail.v2alpha.IListModelsResponse | null | undefined, + protos.google.cloud.retail.v2alpha.IModel + >, + ): void; listModels( - request?: protos.google.cloud.retail.v2alpha.IListModelsRequest, - optionsOrCallback?: CallOptions|PaginationCallback< - protos.google.cloud.retail.v2alpha.IListModelsRequest, - protos.google.cloud.retail.v2alpha.IListModelsResponse|null|undefined, - protos.google.cloud.retail.v2alpha.IModel>, - callback?: PaginationCallback< + request?: protos.google.cloud.retail.v2alpha.IListModelsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.cloud.retail.v2alpha.IListModelsRequest, - protos.google.cloud.retail.v2alpha.IListModelsResponse|null|undefined, - protos.google.cloud.retail.v2alpha.IModel>): - Promise<[ - protos.google.cloud.retail.v2alpha.IModel[], - protos.google.cloud.retail.v2alpha.IListModelsRequest|null, - protos.google.cloud.retail.v2alpha.IListModelsResponse - ]>|void { + | protos.google.cloud.retail.v2alpha.IListModelsResponse + | null + | undefined, + protos.google.cloud.retail.v2alpha.IModel + >, + callback?: PaginationCallback< + protos.google.cloud.retail.v2alpha.IListModelsRequest, + protos.google.cloud.retail.v2alpha.IListModelsResponse | null | undefined, + protos.google.cloud.retail.v2alpha.IModel + >, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IModel[], + protos.google.cloud.retail.v2alpha.IListModelsRequest | null, + protos.google.cloud.retail.v2alpha.IListModelsResponse, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.cloud.retail.v2alpha.IListModelsRequest, - protos.google.cloud.retail.v2alpha.IListModelsResponse|null|undefined, - protos.google.cloud.retail.v2alpha.IModel>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.cloud.retail.v2alpha.IListModelsRequest, + | protos.google.cloud.retail.v2alpha.IListModelsResponse + | null + | undefined, + protos.google.cloud.retail.v2alpha.IModel + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listModels values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -1216,114 +1616,118 @@ export class ModelServiceClient { this._log.info('listModels request %j', request); return this.innerApiCalls .listModels(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.cloud.retail.v2alpha.IModel[], - protos.google.cloud.retail.v2alpha.IListModelsRequest|null, - protos.google.cloud.retail.v2alpha.IListModelsResponse - ]) => { - this._log.info('listModels values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.cloud.retail.v2alpha.IModel[], + protos.google.cloud.retail.v2alpha.IListModelsRequest | null, + protos.google.cloud.retail.v2alpha.IListModelsResponse, + ]) => { + this._log.info('listModels values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listModels`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent for which to list models. - * Format: - * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}` - * @param {number} [request.pageSize] - * Optional. Maximum number of results to return. If unspecified, defaults - * to 50. Max allowed value is 1000. - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous `ListModels` - * call. Provide this to retrieve the subsequent page. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.cloud.retail.v2alpha.Model|Model} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `listModelsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `listModels`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent for which to list models. + * Format: + * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}` + * @param {number} [request.pageSize] + * Optional. Maximum number of results to return. If unspecified, defaults + * to 50. Max allowed value is 1000. + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListModels` + * call. Provide this to retrieve the subsequent page. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.cloud.retail.v2alpha.Model|Model} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listModelsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listModelsStream( - request?: protos.google.cloud.retail.v2alpha.IListModelsRequest, - options?: CallOptions): - Transform{ + request?: protos.google.cloud.retail.v2alpha.IListModelsRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); const defaultCallSettings = this._defaults['listModels']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listModels stream %j', request); return this.descriptors.page.listModels.createStream( this.innerApiCalls.listModels as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listModels`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent for which to list models. - * Format: - * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}` - * @param {number} [request.pageSize] - * Optional. Maximum number of results to return. If unspecified, defaults - * to 50. Max allowed value is 1000. - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous `ListModels` - * call. Provide this to retrieve the subsequent page. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.cloud.retail.v2alpha.Model|Model}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/model_service.list_models.js - * region_tag:retail_v2alpha_generated_ModelService_ListModels_async - */ + /** + * Equivalent to `listModels`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent for which to list models. + * Format: + * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}` + * @param {number} [request.pageSize] + * Optional. Maximum number of results to return. If unspecified, defaults + * to 50. Max allowed value is 1000. + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListModels` + * call. Provide this to retrieve the subsequent page. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.cloud.retail.v2alpha.Model|Model}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/model_service.list_models.js + * region_tag:retail_v2alpha_generated_ModelService_ListModels_async + */ listModelsAsync( - request?: protos.google.cloud.retail.v2alpha.IListModelsRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.cloud.retail.v2alpha.IListModelsRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); const defaultCallSettings = this._defaults['listModels']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listModels iterate %j', request); return this.descriptors.page.listModels.asyncIterate( this.innerApiCalls['listModels'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } // -------------------- @@ -1336,7 +1740,7 @@ export class ModelServiceClient { * @param {string} project * @returns {string} Resource name string. */ - alertConfigPath(project:string) { + alertConfigPath(project: string) { return this.pathTemplates.alertConfigPathTemplate.render({ project: project, }); @@ -1350,7 +1754,8 @@ export class ModelServiceClient { * @returns {string} A string representing the project. */ matchProjectFromAlertConfigName(alertConfigName: string) { - return this.pathTemplates.alertConfigPathTemplate.match(alertConfigName).project; + return this.pathTemplates.alertConfigPathTemplate.match(alertConfigName) + .project; } /** @@ -1361,7 +1766,7 @@ export class ModelServiceClient { * @param {string} catalog * @returns {string} Resource name string. */ - attributesConfigPath(project:string,location:string,catalog:string) { + attributesConfigPath(project: string, location: string, catalog: string) { return this.pathTemplates.attributesConfigPathTemplate.render({ project: project, location: location, @@ -1377,7 +1782,9 @@ export class ModelServiceClient { * @returns {string} A string representing the project. */ matchProjectFromAttributesConfigName(attributesConfigName: string) { - return this.pathTemplates.attributesConfigPathTemplate.match(attributesConfigName).project; + return this.pathTemplates.attributesConfigPathTemplate.match( + attributesConfigName, + ).project; } /** @@ -1388,7 +1795,9 @@ export class ModelServiceClient { * @returns {string} A string representing the location. */ matchLocationFromAttributesConfigName(attributesConfigName: string) { - return this.pathTemplates.attributesConfigPathTemplate.match(attributesConfigName).location; + return this.pathTemplates.attributesConfigPathTemplate.match( + attributesConfigName, + ).location; } /** @@ -1399,7 +1808,9 @@ export class ModelServiceClient { * @returns {string} A string representing the catalog. */ matchCatalogFromAttributesConfigName(attributesConfigName: string) { - return this.pathTemplates.attributesConfigPathTemplate.match(attributesConfigName).catalog; + return this.pathTemplates.attributesConfigPathTemplate.match( + attributesConfigName, + ).catalog; } /** @@ -1411,7 +1822,12 @@ export class ModelServiceClient { * @param {string} branch * @returns {string} Resource name string. */ - branchPath(project:string,location:string,catalog:string,branch:string) { + branchPath( + project: string, + location: string, + catalog: string, + branch: string, + ) { return this.pathTemplates.branchPathTemplate.render({ project: project, location: location, @@ -1472,7 +1888,7 @@ export class ModelServiceClient { * @param {string} catalog * @returns {string} Resource name string. */ - catalogPath(project:string,location:string,catalog:string) { + catalogPath(project: string, location: string, catalog: string) { return this.pathTemplates.catalogPathTemplate.render({ project: project, location: location, @@ -1521,7 +1937,7 @@ export class ModelServiceClient { * @param {string} catalog * @returns {string} Resource name string. */ - completionConfigPath(project:string,location:string,catalog:string) { + completionConfigPath(project: string, location: string, catalog: string) { return this.pathTemplates.completionConfigPathTemplate.render({ project: project, location: location, @@ -1537,7 +1953,9 @@ export class ModelServiceClient { * @returns {string} A string representing the project. */ matchProjectFromCompletionConfigName(completionConfigName: string) { - return this.pathTemplates.completionConfigPathTemplate.match(completionConfigName).project; + return this.pathTemplates.completionConfigPathTemplate.match( + completionConfigName, + ).project; } /** @@ -1548,7 +1966,9 @@ export class ModelServiceClient { * @returns {string} A string representing the location. */ matchLocationFromCompletionConfigName(completionConfigName: string) { - return this.pathTemplates.completionConfigPathTemplate.match(completionConfigName).location; + return this.pathTemplates.completionConfigPathTemplate.match( + completionConfigName, + ).location; } /** @@ -1559,7 +1979,9 @@ export class ModelServiceClient { * @returns {string} A string representing the catalog. */ matchCatalogFromCompletionConfigName(completionConfigName: string) { - return this.pathTemplates.completionConfigPathTemplate.match(completionConfigName).catalog; + return this.pathTemplates.completionConfigPathTemplate.match( + completionConfigName, + ).catalog; } /** @@ -1571,7 +1993,12 @@ export class ModelServiceClient { * @param {string} control * @returns {string} Resource name string. */ - controlPath(project:string,location:string,catalog:string,control:string) { + controlPath( + project: string, + location: string, + catalog: string, + control: string, + ) { return this.pathTemplates.controlPathTemplate.render({ project: project, location: location, @@ -1630,7 +2057,7 @@ export class ModelServiceClient { * @param {string} project * @returns {string} Resource name string. */ - loggingConfigPath(project:string) { + loggingConfigPath(project: string) { return this.pathTemplates.loggingConfigPathTemplate.render({ project: project, }); @@ -1644,7 +2071,8 @@ export class ModelServiceClient { * @returns {string} A string representing the project. */ matchProjectFromLoggingConfigName(loggingConfigName: string) { - return this.pathTemplates.loggingConfigPathTemplate.match(loggingConfigName).project; + return this.pathTemplates.loggingConfigPathTemplate.match(loggingConfigName) + .project; } /** @@ -1656,7 +2084,12 @@ export class ModelServiceClient { * @param {string} merchant_center_account_link * @returns {string} Resource name string. */ - merchantCenterAccountLinkPath(project:string,location:string,catalog:string,merchantCenterAccountLink:string) { + merchantCenterAccountLinkPath( + project: string, + location: string, + catalog: string, + merchantCenterAccountLink: string, + ) { return this.pathTemplates.merchantCenterAccountLinkPathTemplate.render({ project: project, location: location, @@ -1672,8 +2105,12 @@ export class ModelServiceClient { * A fully-qualified path representing MerchantCenterAccountLink resource. * @returns {string} A string representing the project. */ - matchProjectFromMerchantCenterAccountLinkName(merchantCenterAccountLinkName: string) { - return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match(merchantCenterAccountLinkName).project; + matchProjectFromMerchantCenterAccountLinkName( + merchantCenterAccountLinkName: string, + ) { + return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match( + merchantCenterAccountLinkName, + ).project; } /** @@ -1683,8 +2120,12 @@ export class ModelServiceClient { * A fully-qualified path representing MerchantCenterAccountLink resource. * @returns {string} A string representing the location. */ - matchLocationFromMerchantCenterAccountLinkName(merchantCenterAccountLinkName: string) { - return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match(merchantCenterAccountLinkName).location; + matchLocationFromMerchantCenterAccountLinkName( + merchantCenterAccountLinkName: string, + ) { + return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match( + merchantCenterAccountLinkName, + ).location; } /** @@ -1694,8 +2135,12 @@ export class ModelServiceClient { * A fully-qualified path representing MerchantCenterAccountLink resource. * @returns {string} A string representing the catalog. */ - matchCatalogFromMerchantCenterAccountLinkName(merchantCenterAccountLinkName: string) { - return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match(merchantCenterAccountLinkName).catalog; + matchCatalogFromMerchantCenterAccountLinkName( + merchantCenterAccountLinkName: string, + ) { + return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match( + merchantCenterAccountLinkName, + ).catalog; } /** @@ -1705,8 +2150,12 @@ export class ModelServiceClient { * A fully-qualified path representing MerchantCenterAccountLink resource. * @returns {string} A string representing the merchant_center_account_link. */ - matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName(merchantCenterAccountLinkName: string) { - return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match(merchantCenterAccountLinkName).merchant_center_account_link; + matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName( + merchantCenterAccountLinkName: string, + ) { + return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match( + merchantCenterAccountLinkName, + ).merchant_center_account_link; } /** @@ -1718,7 +2167,7 @@ export class ModelServiceClient { * @param {string} model * @returns {string} Resource name string. */ - modelPath(project:string,location:string,catalog:string,model:string) { + modelPath(project: string, location: string, catalog: string, model: string) { return this.pathTemplates.modelPathTemplate.render({ project: project, location: location, @@ -1781,7 +2230,13 @@ export class ModelServiceClient { * @param {string} product * @returns {string} Resource name string. */ - productPath(project:string,location:string,catalog:string,branch:string,product:string) { + productPath( + project: string, + location: string, + catalog: string, + branch: string, + product: string, + ) { return this.pathTemplates.productPathTemplate.render({ project: project, location: location, @@ -1852,7 +2307,7 @@ export class ModelServiceClient { * @param {string} project * @returns {string} Resource name string. */ - retailProjectPath(project:string) { + retailProjectPath(project: string) { return this.pathTemplates.retailProjectPathTemplate.render({ project: project, }); @@ -1866,7 +2321,8 @@ export class ModelServiceClient { * @returns {string} A string representing the project. */ matchProjectFromRetailProjectName(retailProjectName: string) { - return this.pathTemplates.retailProjectPathTemplate.match(retailProjectName).project; + return this.pathTemplates.retailProjectPathTemplate.match(retailProjectName) + .project; } /** @@ -1878,7 +2334,12 @@ export class ModelServiceClient { * @param {string} serving_config * @returns {string} Resource name string. */ - servingConfigPath(project:string,location:string,catalog:string,servingConfig:string) { + servingConfigPath( + project: string, + location: string, + catalog: string, + servingConfig: string, + ) { return this.pathTemplates.servingConfigPathTemplate.render({ project: project, location: location, @@ -1895,7 +2356,8 @@ export class ModelServiceClient { * @returns {string} A string representing the project. */ matchProjectFromServingConfigName(servingConfigName: string) { - return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName).project; + return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName) + .project; } /** @@ -1906,7 +2368,8 @@ export class ModelServiceClient { * @returns {string} A string representing the location. */ matchLocationFromServingConfigName(servingConfigName: string) { - return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName).location; + return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName) + .location; } /** @@ -1917,7 +2380,8 @@ export class ModelServiceClient { * @returns {string} A string representing the catalog. */ matchCatalogFromServingConfigName(servingConfigName: string) { - return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName).catalog; + return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName) + .catalog; } /** @@ -1928,7 +2392,8 @@ export class ModelServiceClient { * @returns {string} A string representing the serving_config. */ matchServingConfigFromServingConfigName(servingConfigName: string) { - return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName).serving_config; + return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName) + .serving_config; } /** @@ -1939,7 +2404,7 @@ export class ModelServiceClient { */ close(): Promise { if (this.modelServiceStub && !this._terminated) { - return this.modelServiceStub.then(stub => { + return this.modelServiceStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -1948,4 +2413,4 @@ export class ModelServiceClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/core/generator/gapic-generator-typescript/baselines/retail/src/v2alpha/prediction_service_client.ts.baseline b/core/generator/gapic-generator-typescript/baselines/retail/src/v2alpha/prediction_service_client.ts.baseline index 0d314b78eb15..a8ed7f716f19 100644 --- a/core/generator/gapic-generator-typescript/baselines/retail/src/v2alpha/prediction_service_client.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/retail/src/v2alpha/prediction_service_client.ts.baseline @@ -18,11 +18,16 @@ /* global window */ import type * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions} from 'google-gax'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, +} from 'google-gax'; import * as protos from '../../protos/protos'; import jsonProtos = require('../../protos/protos.json'); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; /** * Client JSON configuration object, loaded from @@ -44,7 +49,7 @@ export class PredictionServiceClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('retail'); @@ -57,9 +62,9 @@ export class PredictionServiceClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; - predictionServiceStub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; + predictionServiceStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of PredictionServiceClient. @@ -100,21 +105,42 @@ export class PredictionServiceClient { * const client = new PredictionServiceClient({fallback: true}, gax); * ``` */ - constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { // Ensure that options include all the required fields. const staticMembers = this.constructor as typeof PredictionServiceClient; - if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { - throw new Error('Please set either universe_domain or universeDomain, but not both.'); + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); } - const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; - this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; this._servicePath = 'retail.' + this._universeDomain; - const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; - const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. if (servicePath !== this._servicePath && !('scopes' in opts)) { @@ -136,7 +162,7 @@ export class PredictionServiceClient { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; @@ -150,10 +176,7 @@ export class PredictionServiceClient { } // Determine the client header string. - const clientHeader = [ - `gax/${this._gaxModule.version}`, - `gapic/${version}`, - ]; + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/${process.versions.node}`); } else { @@ -175,47 +198,50 @@ export class PredictionServiceClient { // Create useful helper objects for these. this.pathTemplates = { alertConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/alertConfig' + 'projects/{project}/alertConfig', ), attributesConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/attributesConfig' + 'projects/{project}/locations/{location}/catalogs/{catalog}/attributesConfig', ), branchPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}', ), catalogPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}' + 'projects/{project}/locations/{location}/catalogs/{catalog}', ), completionConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/completionConfig' + 'projects/{project}/locations/{location}/catalogs/{catalog}/completionConfig', ), controlPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/controls/{control}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/controls/{control}', ), loggingConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/loggingConfig' + 'projects/{project}/loggingConfig', ), merchantCenterAccountLinkPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/merchantCenterAccountLinks/{merchant_center_account_link}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/merchantCenterAccountLinks/{merchant_center_account_link}', ), modelPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/models/{model}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/models/{model}', ), productPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}', ), retailProjectPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/retailProject' + 'projects/{project}/retailProject', ), servingConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/servingConfigs/{serving_config}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/servingConfigs/{serving_config}', ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.cloud.retail.v2alpha.PredictionService', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.cloud.retail.v2alpha.PredictionService', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + { 'x-goog-api-client': clientHeader.join(' ') }, + ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -246,36 +272,40 @@ export class PredictionServiceClient { // Put together the "service stub" for // google.cloud.retail.v2alpha.PredictionService. this.predictionServiceStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.cloud.retail.v2alpha.PredictionService') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.cloud.retail.v2alpha.PredictionService', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.cloud.retail.v2alpha.PredictionService, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts, + this._providedCustomServicePath, + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const predictionServiceStubMethods = - ['predict']; + const predictionServiceStubMethods = ['predict']; for (const methodName of predictionServiceStubMethods) { const callPromise = this.predictionServiceStub.then( - stub => (...args: Array<{}>) => { - if (this._terminated) { - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error|null|undefined) => () => { + (stub) => + (...args: Array<{}>) => { + if (this._terminated) { + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { throw err; - }); + }, + ); - const descriptor = - undefined; + const descriptor = undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -290,8 +320,14 @@ export class PredictionServiceClient { * @returns {string} The DNS address for this service. */ static get servicePath() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'retail.googleapis.com'; } @@ -302,8 +338,14 @@ export class PredictionServiceClient { * @returns {string} The DNS address for this service. */ static get apiEndpoint() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'retail.googleapis.com'; } @@ -334,9 +376,7 @@ export class PredictionServiceClient { * @returns {string[]} List of default scopes. */ static get scopes() { - return [ - 'https://www.googleapis.com/auth/cloud-platform' - ]; + return ['https://www.googleapis.com/auth/cloud-platform']; } getProjectId(): Promise; @@ -345,8 +385,9 @@ export class PredictionServiceClient { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId(callback?: Callback): - Promise|void { + getProjectId( + callback?: Callback, + ): Promise | void { if (callback) { this.auth.getProjectId(callback); return; @@ -357,222 +398,252 @@ export class PredictionServiceClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Makes a recommendation prediction. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.placement - * Required. Full resource name of the format: - * `{placement=projects/* /locations/global/catalogs/default_catalog/servingConfigs/*}` - * or - * `{placement=projects/* /locations/global/catalogs/default_catalog/placements/*}`. - * We recommend using the `servingConfigs` resource. `placements` is a legacy - * resource. - * The ID of the Recommendations AI serving config or placement. - * Before you can request predictions from your model, you must create at - * least one serving config or placement for it. For more information, see - * [Manage serving configs] - * (https://cloud.google.com/retail/docs/manage-configs). - * - * The full list of available serving configs can be seen at - * https://console.cloud.google.com/ai/retail/catalogs/default_catalog/configs - * @param {google.cloud.retail.v2alpha.UserEvent} request.userEvent - * Required. Context about the user, what they are looking at and what action - * they took to trigger the predict request. Note that this user event detail - * won't be ingested to userEvent logs. Thus, a separate userEvent write - * request is required for event logging. - * - * Don't set - * {@link protos.google.cloud.retail.v2alpha.UserEvent.visitor_id|UserEvent.visitor_id} or - * {@link protos.google.cloud.retail.v2alpha.UserInfo.user_id|UserInfo.user_id} to the - * same fixed ID for different users. If you are trying to receive - * non-personalized recommendations (not recommended; this can negatively - * impact model performance), instead set - * {@link protos.google.cloud.retail.v2alpha.UserEvent.visitor_id|UserEvent.visitor_id} to - * a random unique ID and leave - * {@link protos.google.cloud.retail.v2alpha.UserInfo.user_id|UserInfo.user_id} unset. - * @param {number} request.pageSize - * Maximum number of results to return. Set this property to the number of - * prediction results needed. If zero, the service will choose a reasonable - * default. The maximum allowed value is 100. Values above 100 will be coerced - * to 100. - * @param {string} request.pageToken - * This field is not used; leave it unset. - * @param {string} request.filter - * Filter for restricting prediction results with a length limit of 5,000 - * characters. Accepts values for tags and the `filterOutOfStockItems` flag. - * - * * Tag expressions. Restricts predictions to products that match all of the - * specified tags. Boolean operators `OR` and `NOT` are supported if the - * expression is enclosed in parentheses, and must be separated from the - * tag values by a space. `-"tagA"` is also supported and is equivalent to - * `NOT "tagA"`. Tag values must be double quoted UTF-8 encoded strings - * with a size limit of 1,000 characters. - * - * Note: "Recently viewed" models don't support tag filtering at the - * moment. - * - * * filterOutOfStockItems. Restricts predictions to products that do not - * have a - * stockState value of OUT_OF_STOCK. - * - * Examples: - * - * * tag=("Red" OR "Blue") tag="New-Arrival" tag=(NOT "promotional") - * * filterOutOfStockItems tag=(-"promotional") - * * filterOutOfStockItems - * - * If your filter blocks all prediction results, the API will return *no* - * results. If instead you want empty result sets to return generic - * (unfiltered) popular products, set `strictFiltering` to False in - * `PredictRequest.params`. Note that the API will never return items with - * storageStatus of "EXPIRED" or "DELETED" regardless of filter choices. - * - * If `filterSyntaxV2` is set to true under the `params` field, then - * attribute-based expressions are expected instead of the above described - * tag-based syntax. Examples: - * - * * (colors: ANY("Red", "Blue")) AND NOT (categories: ANY("Phones")) - * * (availability: ANY("IN_STOCK")) AND - * (colors: ANY("Red") OR categories: ANY("Phones")) - * - * For more information, see - * [Filter recommendations](https://cloud.google.com/retail/docs/filter-recs). - * @param {boolean} request.validateOnly - * Use validate only mode for this prediction query. If set to true, a - * dummy model will be used that returns arbitrary products. - * Note that the validate only mode should only be used for testing the API, - * or if the model is not ready. - * @param {number[]} request.params - * Additional domain specific parameters for the predictions. - * - * Allowed values: - * - * * `returnProduct`: Boolean. If set to true, the associated product - * object will be returned in the `results.metadata` field in the - * prediction response. - * * `returnScore`: Boolean. If set to true, the prediction 'score' - * corresponding to each returned product will be set in the - * `results.metadata` field in the prediction response. The given - * 'score' indicates the probability of a product being clicked/purchased - * given the user's context and history. - * * `strictFiltering`: Boolean. True by default. If set to false, the service - * will return generic (unfiltered) popular products instead of empty if - * your filter blocks all prediction results. - * * `priceRerankLevel`: String. Default empty. If set to be non-empty, then - * it needs to be one of {'no-price-reranking', 'low-price-reranking', - * 'medium-price-reranking', 'high-price-reranking'}. This gives - * request-level control and adjusts prediction results based on product - * price. - * * `diversityLevel`: String. Default empty. If set to be non-empty, then - * it needs to be one of {'no-diversity', 'low-diversity', - * 'medium-diversity', 'high-diversity', 'auto-diversity'}. This gives - * request-level control and adjusts prediction results based on product - * category. - * * `filterSyntaxV2`: Boolean. False by default. If set to true, the `filter` - * field is interpreteted according to the new, attribute-based syntax. - * @param {number[]} request.labels - * The labels applied to a resource must meet the following requirements: - * - * * Each resource can have multiple labels, up to a maximum of 64. - * * Each label must be a key-value pair. - * * Keys have a minimum length of 1 character and a maximum length of 63 - * characters and cannot be empty. Values can be empty and have a maximum - * length of 63 characters. - * * Keys and values can contain only lowercase letters, numeric characters, - * underscores, and dashes. All characters must use UTF-8 encoding, and - * international characters are allowed. - * * The key portion of a label must be unique. However, you can use the same - * key with multiple resources. - * * Keys must start with a lowercase letter or international character. - * - * See [Google Cloud - * Document](https://cloud.google.com/resource-manager/docs/creating-managing-labels#requirements) - * for more details. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.PredictResponse|PredictResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/prediction_service.predict.js - * region_tag:retail_v2alpha_generated_PredictionService_Predict_async - */ + /** + * Makes a recommendation prediction. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.placement + * Required. Full resource name of the format: + * `{placement=projects/* /locations/global/catalogs/default_catalog/servingConfigs/*}` + * or + * `{placement=projects/* /locations/global/catalogs/default_catalog/placements/*}`. + * We recommend using the `servingConfigs` resource. `placements` is a legacy + * resource. + * The ID of the Recommendations AI serving config or placement. + * Before you can request predictions from your model, you must create at + * least one serving config or placement for it. For more information, see + * [Manage serving configs] + * (https://cloud.google.com/retail/docs/manage-configs). + * + * The full list of available serving configs can be seen at + * https://console.cloud.google.com/ai/retail/catalogs/default_catalog/configs + * @param {google.cloud.retail.v2alpha.UserEvent} request.userEvent + * Required. Context about the user, what they are looking at and what action + * they took to trigger the predict request. Note that this user event detail + * won't be ingested to userEvent logs. Thus, a separate userEvent write + * request is required for event logging. + * + * Don't set + * {@link protos.google.cloud.retail.v2alpha.UserEvent.visitor_id|UserEvent.visitor_id} or + * {@link protos.google.cloud.retail.v2alpha.UserInfo.user_id|UserInfo.user_id} to the + * same fixed ID for different users. If you are trying to receive + * non-personalized recommendations (not recommended; this can negatively + * impact model performance), instead set + * {@link protos.google.cloud.retail.v2alpha.UserEvent.visitor_id|UserEvent.visitor_id} to + * a random unique ID and leave + * {@link protos.google.cloud.retail.v2alpha.UserInfo.user_id|UserInfo.user_id} unset. + * @param {number} request.pageSize + * Maximum number of results to return. Set this property to the number of + * prediction results needed. If zero, the service will choose a reasonable + * default. The maximum allowed value is 100. Values above 100 will be coerced + * to 100. + * @param {string} request.pageToken + * This field is not used; leave it unset. + * @param {string} request.filter + * Filter for restricting prediction results with a length limit of 5,000 + * characters. Accepts values for tags and the `filterOutOfStockItems` flag. + * + * * Tag expressions. Restricts predictions to products that match all of the + * specified tags. Boolean operators `OR` and `NOT` are supported if the + * expression is enclosed in parentheses, and must be separated from the + * tag values by a space. `-"tagA"` is also supported and is equivalent to + * `NOT "tagA"`. Tag values must be double quoted UTF-8 encoded strings + * with a size limit of 1,000 characters. + * + * Note: "Recently viewed" models don't support tag filtering at the + * moment. + * + * * filterOutOfStockItems. Restricts predictions to products that do not + * have a + * stockState value of OUT_OF_STOCK. + * + * Examples: + * + * * tag=("Red" OR "Blue") tag="New-Arrival" tag=(NOT "promotional") + * * filterOutOfStockItems tag=(-"promotional") + * * filterOutOfStockItems + * + * If your filter blocks all prediction results, the API will return *no* + * results. If instead you want empty result sets to return generic + * (unfiltered) popular products, set `strictFiltering` to False in + * `PredictRequest.params`. Note that the API will never return items with + * storageStatus of "EXPIRED" or "DELETED" regardless of filter choices. + * + * If `filterSyntaxV2` is set to true under the `params` field, then + * attribute-based expressions are expected instead of the above described + * tag-based syntax. Examples: + * + * * (colors: ANY("Red", "Blue")) AND NOT (categories: ANY("Phones")) + * * (availability: ANY("IN_STOCK")) AND + * (colors: ANY("Red") OR categories: ANY("Phones")) + * + * For more information, see + * [Filter recommendations](https://cloud.google.com/retail/docs/filter-recs). + * @param {boolean} request.validateOnly + * Use validate only mode for this prediction query. If set to true, a + * dummy model will be used that returns arbitrary products. + * Note that the validate only mode should only be used for testing the API, + * or if the model is not ready. + * @param {number[]} request.params + * Additional domain specific parameters for the predictions. + * + * Allowed values: + * + * * `returnProduct`: Boolean. If set to true, the associated product + * object will be returned in the `results.metadata` field in the + * prediction response. + * * `returnScore`: Boolean. If set to true, the prediction 'score' + * corresponding to each returned product will be set in the + * `results.metadata` field in the prediction response. The given + * 'score' indicates the probability of a product being clicked/purchased + * given the user's context and history. + * * `strictFiltering`: Boolean. True by default. If set to false, the service + * will return generic (unfiltered) popular products instead of empty if + * your filter blocks all prediction results. + * * `priceRerankLevel`: String. Default empty. If set to be non-empty, then + * it needs to be one of {'no-price-reranking', 'low-price-reranking', + * 'medium-price-reranking', 'high-price-reranking'}. This gives + * request-level control and adjusts prediction results based on product + * price. + * * `diversityLevel`: String. Default empty. If set to be non-empty, then + * it needs to be one of {'no-diversity', 'low-diversity', + * 'medium-diversity', 'high-diversity', 'auto-diversity'}. This gives + * request-level control and adjusts prediction results based on product + * category. + * * `filterSyntaxV2`: Boolean. False by default. If set to true, the `filter` + * field is interpreteted according to the new, attribute-based syntax. + * @param {number[]} request.labels + * The labels applied to a resource must meet the following requirements: + * + * * Each resource can have multiple labels, up to a maximum of 64. + * * Each label must be a key-value pair. + * * Keys have a minimum length of 1 character and a maximum length of 63 + * characters and cannot be empty. Values can be empty and have a maximum + * length of 63 characters. + * * Keys and values can contain only lowercase letters, numeric characters, + * underscores, and dashes. All characters must use UTF-8 encoding, and + * international characters are allowed. + * * The key portion of a label must be unique. However, you can use the same + * key with multiple resources. + * * Keys must start with a lowercase letter or international character. + * + * See [Google Cloud + * Document](https://cloud.google.com/resource-manager/docs/creating-managing-labels#requirements) + * for more details. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.PredictResponse|PredictResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/prediction_service.predict.js + * region_tag:retail_v2alpha_generated_PredictionService_Predict_async + */ predict( - request?: protos.google.cloud.retail.v2alpha.IPredictRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.retail.v2alpha.IPredictResponse, - protos.google.cloud.retail.v2alpha.IPredictRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.IPredictRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IPredictResponse, + protos.google.cloud.retail.v2alpha.IPredictRequest | undefined, + {} | undefined, + ] + >; predict( - request: protos.google.cloud.retail.v2alpha.IPredictRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.retail.v2alpha.IPredictResponse, - protos.google.cloud.retail.v2alpha.IPredictRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IPredictRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.retail.v2alpha.IPredictResponse, + protos.google.cloud.retail.v2alpha.IPredictRequest | null | undefined, + {} | null | undefined + >, + ): void; predict( - request: protos.google.cloud.retail.v2alpha.IPredictRequest, - callback: Callback< - protos.google.cloud.retail.v2alpha.IPredictResponse, - protos.google.cloud.retail.v2alpha.IPredictRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IPredictRequest, + callback: Callback< + protos.google.cloud.retail.v2alpha.IPredictResponse, + protos.google.cloud.retail.v2alpha.IPredictRequest | null | undefined, + {} | null | undefined + >, + ): void; predict( - request?: protos.google.cloud.retail.v2alpha.IPredictRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.retail.v2alpha.IPredictResponse, - protos.google.cloud.retail.v2alpha.IPredictRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.retail.v2alpha.IPredictRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.retail.v2alpha.IPredictResponse, - protos.google.cloud.retail.v2alpha.IPredictRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.retail.v2alpha.IPredictResponse, - protos.google.cloud.retail.v2alpha.IPredictRequest|undefined, {}|undefined - ]>|void { + protos.google.cloud.retail.v2alpha.IPredictRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.retail.v2alpha.IPredictResponse, + protos.google.cloud.retail.v2alpha.IPredictRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IPredictResponse, + protos.google.cloud.retail.v2alpha.IPredictRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'placement': request.placement ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + placement: request.placement ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('predict request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.retail.v2alpha.IPredictResponse, - protos.google.cloud.retail.v2alpha.IPredictRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.retail.v2alpha.IPredictResponse, + protos.google.cloud.retail.v2alpha.IPredictRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('predict response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.predict(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.retail.v2alpha.IPredictResponse, - protos.google.cloud.retail.v2alpha.IPredictRequest|undefined, - {}|undefined - ]) => { - this._log.info('predict response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .predict(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.retail.v2alpha.IPredictResponse, + protos.google.cloud.retail.v2alpha.IPredictRequest | undefined, + {} | undefined, + ]) => { + this._log.info('predict response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); @@ -588,7 +659,7 @@ export class PredictionServiceClient { * @param {string} project * @returns {string} Resource name string. */ - alertConfigPath(project:string) { + alertConfigPath(project: string) { return this.pathTemplates.alertConfigPathTemplate.render({ project: project, }); @@ -602,7 +673,8 @@ export class PredictionServiceClient { * @returns {string} A string representing the project. */ matchProjectFromAlertConfigName(alertConfigName: string) { - return this.pathTemplates.alertConfigPathTemplate.match(alertConfigName).project; + return this.pathTemplates.alertConfigPathTemplate.match(alertConfigName) + .project; } /** @@ -613,7 +685,7 @@ export class PredictionServiceClient { * @param {string} catalog * @returns {string} Resource name string. */ - attributesConfigPath(project:string,location:string,catalog:string) { + attributesConfigPath(project: string, location: string, catalog: string) { return this.pathTemplates.attributesConfigPathTemplate.render({ project: project, location: location, @@ -629,7 +701,9 @@ export class PredictionServiceClient { * @returns {string} A string representing the project. */ matchProjectFromAttributesConfigName(attributesConfigName: string) { - return this.pathTemplates.attributesConfigPathTemplate.match(attributesConfigName).project; + return this.pathTemplates.attributesConfigPathTemplate.match( + attributesConfigName, + ).project; } /** @@ -640,7 +714,9 @@ export class PredictionServiceClient { * @returns {string} A string representing the location. */ matchLocationFromAttributesConfigName(attributesConfigName: string) { - return this.pathTemplates.attributesConfigPathTemplate.match(attributesConfigName).location; + return this.pathTemplates.attributesConfigPathTemplate.match( + attributesConfigName, + ).location; } /** @@ -651,7 +727,9 @@ export class PredictionServiceClient { * @returns {string} A string representing the catalog. */ matchCatalogFromAttributesConfigName(attributesConfigName: string) { - return this.pathTemplates.attributesConfigPathTemplate.match(attributesConfigName).catalog; + return this.pathTemplates.attributesConfigPathTemplate.match( + attributesConfigName, + ).catalog; } /** @@ -663,7 +741,12 @@ export class PredictionServiceClient { * @param {string} branch * @returns {string} Resource name string. */ - branchPath(project:string,location:string,catalog:string,branch:string) { + branchPath( + project: string, + location: string, + catalog: string, + branch: string, + ) { return this.pathTemplates.branchPathTemplate.render({ project: project, location: location, @@ -724,7 +807,7 @@ export class PredictionServiceClient { * @param {string} catalog * @returns {string} Resource name string. */ - catalogPath(project:string,location:string,catalog:string) { + catalogPath(project: string, location: string, catalog: string) { return this.pathTemplates.catalogPathTemplate.render({ project: project, location: location, @@ -773,7 +856,7 @@ export class PredictionServiceClient { * @param {string} catalog * @returns {string} Resource name string. */ - completionConfigPath(project:string,location:string,catalog:string) { + completionConfigPath(project: string, location: string, catalog: string) { return this.pathTemplates.completionConfigPathTemplate.render({ project: project, location: location, @@ -789,7 +872,9 @@ export class PredictionServiceClient { * @returns {string} A string representing the project. */ matchProjectFromCompletionConfigName(completionConfigName: string) { - return this.pathTemplates.completionConfigPathTemplate.match(completionConfigName).project; + return this.pathTemplates.completionConfigPathTemplate.match( + completionConfigName, + ).project; } /** @@ -800,7 +885,9 @@ export class PredictionServiceClient { * @returns {string} A string representing the location. */ matchLocationFromCompletionConfigName(completionConfigName: string) { - return this.pathTemplates.completionConfigPathTemplate.match(completionConfigName).location; + return this.pathTemplates.completionConfigPathTemplate.match( + completionConfigName, + ).location; } /** @@ -811,7 +898,9 @@ export class PredictionServiceClient { * @returns {string} A string representing the catalog. */ matchCatalogFromCompletionConfigName(completionConfigName: string) { - return this.pathTemplates.completionConfigPathTemplate.match(completionConfigName).catalog; + return this.pathTemplates.completionConfigPathTemplate.match( + completionConfigName, + ).catalog; } /** @@ -823,7 +912,12 @@ export class PredictionServiceClient { * @param {string} control * @returns {string} Resource name string. */ - controlPath(project:string,location:string,catalog:string,control:string) { + controlPath( + project: string, + location: string, + catalog: string, + control: string, + ) { return this.pathTemplates.controlPathTemplate.render({ project: project, location: location, @@ -882,7 +976,7 @@ export class PredictionServiceClient { * @param {string} project * @returns {string} Resource name string. */ - loggingConfigPath(project:string) { + loggingConfigPath(project: string) { return this.pathTemplates.loggingConfigPathTemplate.render({ project: project, }); @@ -896,7 +990,8 @@ export class PredictionServiceClient { * @returns {string} A string representing the project. */ matchProjectFromLoggingConfigName(loggingConfigName: string) { - return this.pathTemplates.loggingConfigPathTemplate.match(loggingConfigName).project; + return this.pathTemplates.loggingConfigPathTemplate.match(loggingConfigName) + .project; } /** @@ -908,7 +1003,12 @@ export class PredictionServiceClient { * @param {string} merchant_center_account_link * @returns {string} Resource name string. */ - merchantCenterAccountLinkPath(project:string,location:string,catalog:string,merchantCenterAccountLink:string) { + merchantCenterAccountLinkPath( + project: string, + location: string, + catalog: string, + merchantCenterAccountLink: string, + ) { return this.pathTemplates.merchantCenterAccountLinkPathTemplate.render({ project: project, location: location, @@ -924,8 +1024,12 @@ export class PredictionServiceClient { * A fully-qualified path representing MerchantCenterAccountLink resource. * @returns {string} A string representing the project. */ - matchProjectFromMerchantCenterAccountLinkName(merchantCenterAccountLinkName: string) { - return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match(merchantCenterAccountLinkName).project; + matchProjectFromMerchantCenterAccountLinkName( + merchantCenterAccountLinkName: string, + ) { + return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match( + merchantCenterAccountLinkName, + ).project; } /** @@ -935,8 +1039,12 @@ export class PredictionServiceClient { * A fully-qualified path representing MerchantCenterAccountLink resource. * @returns {string} A string representing the location. */ - matchLocationFromMerchantCenterAccountLinkName(merchantCenterAccountLinkName: string) { - return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match(merchantCenterAccountLinkName).location; + matchLocationFromMerchantCenterAccountLinkName( + merchantCenterAccountLinkName: string, + ) { + return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match( + merchantCenterAccountLinkName, + ).location; } /** @@ -946,8 +1054,12 @@ export class PredictionServiceClient { * A fully-qualified path representing MerchantCenterAccountLink resource. * @returns {string} A string representing the catalog. */ - matchCatalogFromMerchantCenterAccountLinkName(merchantCenterAccountLinkName: string) { - return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match(merchantCenterAccountLinkName).catalog; + matchCatalogFromMerchantCenterAccountLinkName( + merchantCenterAccountLinkName: string, + ) { + return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match( + merchantCenterAccountLinkName, + ).catalog; } /** @@ -957,8 +1069,12 @@ export class PredictionServiceClient { * A fully-qualified path representing MerchantCenterAccountLink resource. * @returns {string} A string representing the merchant_center_account_link. */ - matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName(merchantCenterAccountLinkName: string) { - return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match(merchantCenterAccountLinkName).merchant_center_account_link; + matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName( + merchantCenterAccountLinkName: string, + ) { + return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match( + merchantCenterAccountLinkName, + ).merchant_center_account_link; } /** @@ -970,7 +1086,7 @@ export class PredictionServiceClient { * @param {string} model * @returns {string} Resource name string. */ - modelPath(project:string,location:string,catalog:string,model:string) { + modelPath(project: string, location: string, catalog: string, model: string) { return this.pathTemplates.modelPathTemplate.render({ project: project, location: location, @@ -1033,7 +1149,13 @@ export class PredictionServiceClient { * @param {string} product * @returns {string} Resource name string. */ - productPath(project:string,location:string,catalog:string,branch:string,product:string) { + productPath( + project: string, + location: string, + catalog: string, + branch: string, + product: string, + ) { return this.pathTemplates.productPathTemplate.render({ project: project, location: location, @@ -1104,7 +1226,7 @@ export class PredictionServiceClient { * @param {string} project * @returns {string} Resource name string. */ - retailProjectPath(project:string) { + retailProjectPath(project: string) { return this.pathTemplates.retailProjectPathTemplate.render({ project: project, }); @@ -1118,7 +1240,8 @@ export class PredictionServiceClient { * @returns {string} A string representing the project. */ matchProjectFromRetailProjectName(retailProjectName: string) { - return this.pathTemplates.retailProjectPathTemplate.match(retailProjectName).project; + return this.pathTemplates.retailProjectPathTemplate.match(retailProjectName) + .project; } /** @@ -1130,7 +1253,12 @@ export class PredictionServiceClient { * @param {string} serving_config * @returns {string} Resource name string. */ - servingConfigPath(project:string,location:string,catalog:string,servingConfig:string) { + servingConfigPath( + project: string, + location: string, + catalog: string, + servingConfig: string, + ) { return this.pathTemplates.servingConfigPathTemplate.render({ project: project, location: location, @@ -1147,7 +1275,8 @@ export class PredictionServiceClient { * @returns {string} A string representing the project. */ matchProjectFromServingConfigName(servingConfigName: string) { - return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName).project; + return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName) + .project; } /** @@ -1158,7 +1287,8 @@ export class PredictionServiceClient { * @returns {string} A string representing the location. */ matchLocationFromServingConfigName(servingConfigName: string) { - return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName).location; + return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName) + .location; } /** @@ -1169,7 +1299,8 @@ export class PredictionServiceClient { * @returns {string} A string representing the catalog. */ matchCatalogFromServingConfigName(servingConfigName: string) { - return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName).catalog; + return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName) + .catalog; } /** @@ -1180,7 +1311,8 @@ export class PredictionServiceClient { * @returns {string} A string representing the serving_config. */ matchServingConfigFromServingConfigName(servingConfigName: string) { - return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName).serving_config; + return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName) + .serving_config; } /** @@ -1191,7 +1323,7 @@ export class PredictionServiceClient { */ close(): Promise { if (this.predictionServiceStub && !this._terminated) { - return this.predictionServiceStub.then(stub => { + return this.predictionServiceStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -1199,4 +1331,4 @@ export class PredictionServiceClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/core/generator/gapic-generator-typescript/baselines/retail/src/v2alpha/product_service_client.ts.baseline b/core/generator/gapic-generator-typescript/baselines/retail/src/v2alpha/product_service_client.ts.baseline index f18f971f405e..2bd42971d735 100644 --- a/core/generator/gapic-generator-typescript/baselines/retail/src/v2alpha/product_service_client.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/retail/src/v2alpha/product_service_client.ts.baseline @@ -18,11 +18,20 @@ /* global window */ import type * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions, GrpcClientOptions, LROperation, PaginationCallback, GaxCall} from 'google-gax'; -import {Transform} from 'stream'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + GrpcClientOptions, + LROperation, + PaginationCallback, + GaxCall, +} from 'google-gax'; +import { Transform } from 'stream'; import * as protos from '../../protos/protos'; import jsonProtos = require('../../protos/protos.json'); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; /** * Client JSON configuration object, loaded from @@ -45,7 +54,7 @@ export class ProductServiceClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('retail'); @@ -58,10 +67,10 @@ export class ProductServiceClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; operationsClient: gax.OperationsClient; - productServiceStub?: Promise<{[name: string]: Function}>; + productServiceStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of ProductServiceClient. @@ -102,21 +111,42 @@ export class ProductServiceClient { * const client = new ProductServiceClient({fallback: true}, gax); * ``` */ - constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { // Ensure that options include all the required fields. const staticMembers = this.constructor as typeof ProductServiceClient; - if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { - throw new Error('Please set either universe_domain or universeDomain, but not both.'); + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); } - const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; - this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; this._servicePath = 'retail.' + this._universeDomain; - const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; - const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. if (servicePath !== this._servicePath && !('scopes' in opts)) { @@ -138,7 +168,7 @@ export class ProductServiceClient { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; @@ -152,10 +182,7 @@ export class ProductServiceClient { } // Determine the client header string. - const clientHeader = [ - `gax/${this._gaxModule.version}`, - `gapic/${version}`, - ]; + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/${process.versions.node}`); } else { @@ -177,40 +204,40 @@ export class ProductServiceClient { // Create useful helper objects for these. this.pathTemplates = { alertConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/alertConfig' + 'projects/{project}/alertConfig', ), attributesConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/attributesConfig' + 'projects/{project}/locations/{location}/catalogs/{catalog}/attributesConfig', ), branchPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}', ), catalogPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}' + 'projects/{project}/locations/{location}/catalogs/{catalog}', ), completionConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/completionConfig' + 'projects/{project}/locations/{location}/catalogs/{catalog}/completionConfig', ), controlPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/controls/{control}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/controls/{control}', ), loggingConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/loggingConfig' + 'projects/{project}/loggingConfig', ), merchantCenterAccountLinkPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/merchantCenterAccountLinks/{merchant_center_account_link}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/merchantCenterAccountLinks/{merchant_center_account_link}', ), modelPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/models/{model}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/models/{model}', ), productPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}', ), retailProjectPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/retailProject' + 'projects/{project}/retailProject', ), servingConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/servingConfigs/{serving_config}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/servingConfigs/{serving_config}', ), }; @@ -218,8 +245,11 @@ export class ProductServiceClient { // (e.g. 50 results at a time, with tokens to get subsequent // pages). Denote the keys used for pagination and results. this.descriptors.page = { - listProducts: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'products') + listProducts: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'products', + ), }; const protoFilesRoot = this._gaxModule.protobufFromJSON(jsonProtos); @@ -228,87 +258,145 @@ export class ProductServiceClient { // rather than holding a request open. const lroOptions: GrpcClientOptions = { auth: this.auth, - grpc: 'grpc' in this._gaxGrpc ? this._gaxGrpc.grpc : undefined + grpc: 'grpc' in this._gaxGrpc ? this._gaxGrpc.grpc : undefined, }; if (opts.fallback) { lroOptions.protoJson = protoFilesRoot; - lroOptions.httpRules = [{selector: 'google.longrunning.Operations.GetOperation',get: '/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*/operations/*}',additional_bindings: [{get: '/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*/places/*/operations/*}',},{get: '/v2alpha/{name=projects/*/locations/*/catalogs/*/operations/*}',},{get: '/v2alpha/{name=projects/*/locations/*/operations/*}',},{get: '/v2alpha/{name=projects/*/operations/*}',}], - },{selector: 'google.longrunning.Operations.ListOperations',get: '/v2alpha/{name=projects/*/locations/*/catalogs/*}/operations',additional_bindings: [{get: '/v2alpha/{name=projects/*/locations/*}/operations',},{get: '/v2alpha/{name=projects/*}/operations',}], - }]; + lroOptions.httpRules = [ + { + selector: 'google.longrunning.Operations.GetOperation', + get: '/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*/operations/*}', + additional_bindings: [ + { + get: '/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*/places/*/operations/*}', + }, + { + get: '/v2alpha/{name=projects/*/locations/*/catalogs/*/operations/*}', + }, + { get: '/v2alpha/{name=projects/*/locations/*/operations/*}' }, + { get: '/v2alpha/{name=projects/*/operations/*}' }, + ], + }, + { + selector: 'google.longrunning.Operations.ListOperations', + get: '/v2alpha/{name=projects/*/locations/*/catalogs/*}/operations', + additional_bindings: [ + { get: '/v2alpha/{name=projects/*/locations/*}/operations' }, + { get: '/v2alpha/{name=projects/*}/operations' }, + ], + }, + ]; } - this.operationsClient = this._gaxModule.lro(lroOptions).operationsClient(opts); + this.operationsClient = this._gaxModule + .lro(lroOptions) + .operationsClient(opts); const purgeProductsResponse = protoFilesRoot.lookup( - '.google.cloud.retail.v2alpha.PurgeProductsResponse') as gax.protobuf.Type; + '.google.cloud.retail.v2alpha.PurgeProductsResponse', + ) as gax.protobuf.Type; const purgeProductsMetadata = protoFilesRoot.lookup( - '.google.cloud.retail.v2alpha.PurgeProductsMetadata') as gax.protobuf.Type; + '.google.cloud.retail.v2alpha.PurgeProductsMetadata', + ) as gax.protobuf.Type; const importProductsResponse = protoFilesRoot.lookup( - '.google.cloud.retail.v2alpha.ImportProductsResponse') as gax.protobuf.Type; + '.google.cloud.retail.v2alpha.ImportProductsResponse', + ) as gax.protobuf.Type; const importProductsMetadata = protoFilesRoot.lookup( - '.google.cloud.retail.v2alpha.ImportMetadata') as gax.protobuf.Type; + '.google.cloud.retail.v2alpha.ImportMetadata', + ) as gax.protobuf.Type; const exportProductsResponse = protoFilesRoot.lookup( - '.google.cloud.retail.v2alpha.ExportProductsResponse') as gax.protobuf.Type; + '.google.cloud.retail.v2alpha.ExportProductsResponse', + ) as gax.protobuf.Type; const exportProductsMetadata = protoFilesRoot.lookup( - '.google.cloud.retail.v2alpha.ExportMetadata') as gax.protobuf.Type; + '.google.cloud.retail.v2alpha.ExportMetadata', + ) as gax.protobuf.Type; const setInventoryResponse = protoFilesRoot.lookup( - '.google.cloud.retail.v2alpha.SetInventoryResponse') as gax.protobuf.Type; + '.google.cloud.retail.v2alpha.SetInventoryResponse', + ) as gax.protobuf.Type; const setInventoryMetadata = protoFilesRoot.lookup( - '.google.cloud.retail.v2alpha.SetInventoryMetadata') as gax.protobuf.Type; + '.google.cloud.retail.v2alpha.SetInventoryMetadata', + ) as gax.protobuf.Type; const addFulfillmentPlacesResponse = protoFilesRoot.lookup( - '.google.cloud.retail.v2alpha.AddFulfillmentPlacesResponse') as gax.protobuf.Type; + '.google.cloud.retail.v2alpha.AddFulfillmentPlacesResponse', + ) as gax.protobuf.Type; const addFulfillmentPlacesMetadata = protoFilesRoot.lookup( - '.google.cloud.retail.v2alpha.AddFulfillmentPlacesMetadata') as gax.protobuf.Type; + '.google.cloud.retail.v2alpha.AddFulfillmentPlacesMetadata', + ) as gax.protobuf.Type; const removeFulfillmentPlacesResponse = protoFilesRoot.lookup( - '.google.cloud.retail.v2alpha.RemoveFulfillmentPlacesResponse') as gax.protobuf.Type; + '.google.cloud.retail.v2alpha.RemoveFulfillmentPlacesResponse', + ) as gax.protobuf.Type; const removeFulfillmentPlacesMetadata = protoFilesRoot.lookup( - '.google.cloud.retail.v2alpha.RemoveFulfillmentPlacesMetadata') as gax.protobuf.Type; + '.google.cloud.retail.v2alpha.RemoveFulfillmentPlacesMetadata', + ) as gax.protobuf.Type; const addLocalInventoriesResponse = protoFilesRoot.lookup( - '.google.cloud.retail.v2alpha.AddLocalInventoriesResponse') as gax.protobuf.Type; + '.google.cloud.retail.v2alpha.AddLocalInventoriesResponse', + ) as gax.protobuf.Type; const addLocalInventoriesMetadata = protoFilesRoot.lookup( - '.google.cloud.retail.v2alpha.AddLocalInventoriesMetadata') as gax.protobuf.Type; + '.google.cloud.retail.v2alpha.AddLocalInventoriesMetadata', + ) as gax.protobuf.Type; const removeLocalInventoriesResponse = protoFilesRoot.lookup( - '.google.cloud.retail.v2alpha.RemoveLocalInventoriesResponse') as gax.protobuf.Type; + '.google.cloud.retail.v2alpha.RemoveLocalInventoriesResponse', + ) as gax.protobuf.Type; const removeLocalInventoriesMetadata = protoFilesRoot.lookup( - '.google.cloud.retail.v2alpha.RemoveLocalInventoriesMetadata') as gax.protobuf.Type; + '.google.cloud.retail.v2alpha.RemoveLocalInventoriesMetadata', + ) as gax.protobuf.Type; this.descriptors.longrunning = { purgeProducts: new this._gaxModule.LongrunningDescriptor( this.operationsClient, purgeProductsResponse.decode.bind(purgeProductsResponse), - purgeProductsMetadata.decode.bind(purgeProductsMetadata)), + purgeProductsMetadata.decode.bind(purgeProductsMetadata), + ), importProducts: new this._gaxModule.LongrunningDescriptor( this.operationsClient, importProductsResponse.decode.bind(importProductsResponse), - importProductsMetadata.decode.bind(importProductsMetadata)), + importProductsMetadata.decode.bind(importProductsMetadata), + ), exportProducts: new this._gaxModule.LongrunningDescriptor( this.operationsClient, exportProductsResponse.decode.bind(exportProductsResponse), - exportProductsMetadata.decode.bind(exportProductsMetadata)), + exportProductsMetadata.decode.bind(exportProductsMetadata), + ), setInventory: new this._gaxModule.LongrunningDescriptor( this.operationsClient, setInventoryResponse.decode.bind(setInventoryResponse), - setInventoryMetadata.decode.bind(setInventoryMetadata)), + setInventoryMetadata.decode.bind(setInventoryMetadata), + ), addFulfillmentPlaces: new this._gaxModule.LongrunningDescriptor( this.operationsClient, addFulfillmentPlacesResponse.decode.bind(addFulfillmentPlacesResponse), - addFulfillmentPlacesMetadata.decode.bind(addFulfillmentPlacesMetadata)), + addFulfillmentPlacesMetadata.decode.bind(addFulfillmentPlacesMetadata), + ), removeFulfillmentPlaces: new this._gaxModule.LongrunningDescriptor( this.operationsClient, - removeFulfillmentPlacesResponse.decode.bind(removeFulfillmentPlacesResponse), - removeFulfillmentPlacesMetadata.decode.bind(removeFulfillmentPlacesMetadata)), + removeFulfillmentPlacesResponse.decode.bind( + removeFulfillmentPlacesResponse, + ), + removeFulfillmentPlacesMetadata.decode.bind( + removeFulfillmentPlacesMetadata, + ), + ), addLocalInventories: new this._gaxModule.LongrunningDescriptor( this.operationsClient, addLocalInventoriesResponse.decode.bind(addLocalInventoriesResponse), - addLocalInventoriesMetadata.decode.bind(addLocalInventoriesMetadata)), + addLocalInventoriesMetadata.decode.bind(addLocalInventoriesMetadata), + ), removeLocalInventories: new this._gaxModule.LongrunningDescriptor( this.operationsClient, - removeLocalInventoriesResponse.decode.bind(removeLocalInventoriesResponse), - removeLocalInventoriesMetadata.decode.bind(removeLocalInventoriesMetadata)) + removeLocalInventoriesResponse.decode.bind( + removeLocalInventoriesResponse, + ), + removeLocalInventoriesMetadata.decode.bind( + removeLocalInventoriesMetadata, + ), + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.cloud.retail.v2alpha.ProductService', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.cloud.retail.v2alpha.ProductService', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + { 'x-goog-api-client': clientHeader.join(' ') }, + ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -339,28 +427,47 @@ export class ProductServiceClient { // Put together the "service stub" for // google.cloud.retail.v2alpha.ProductService. this.productServiceStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.cloud.retail.v2alpha.ProductService') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.cloud.retail.v2alpha.ProductService', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.cloud.retail.v2alpha.ProductService, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts, + this._providedCustomServicePath, + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const productServiceStubMethods = - ['createProduct', 'getProduct', 'listProducts', 'updateProduct', 'deleteProduct', 'purgeProducts', 'importProducts', 'exportProducts', 'setInventory', 'addFulfillmentPlaces', 'removeFulfillmentPlaces', 'addLocalInventories', 'removeLocalInventories']; + const productServiceStubMethods = [ + 'createProduct', + 'getProduct', + 'listProducts', + 'updateProduct', + 'deleteProduct', + 'purgeProducts', + 'importProducts', + 'exportProducts', + 'setInventory', + 'addFulfillmentPlaces', + 'removeFulfillmentPlaces', + 'addLocalInventories', + 'removeLocalInventories', + ]; for (const methodName of productServiceStubMethods) { const callPromise = this.productServiceStub.then( - stub => (...args: Array<{}>) => { - if (this._terminated) { - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error|null|undefined) => () => { + (stub) => + (...args: Array<{}>) => { + if (this._terminated) { + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { throw err; - }); + }, + ); const descriptor = this.descriptors.page[methodName] || @@ -370,7 +477,7 @@ export class ProductServiceClient { callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -385,8 +492,14 @@ export class ProductServiceClient { * @returns {string} The DNS address for this service. */ static get servicePath() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'retail.googleapis.com'; } @@ -397,8 +510,14 @@ export class ProductServiceClient { * @returns {string} The DNS address for this service. */ static get apiEndpoint() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'retail.googleapis.com'; } @@ -429,9 +548,7 @@ export class ProductServiceClient { * @returns {string[]} List of default scopes. */ static get scopes() { - return [ - 'https://www.googleapis.com/auth/cloud-platform' - ]; + return ['https://www.googleapis.com/auth/cloud-platform']; } getProjectId(): Promise; @@ -440,8 +557,9 @@ export class ProductServiceClient { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId(callback?: Callback): - Promise|void { + getProjectId( + callback?: Callback, + ): Promise | void { if (callback) { this.auth.getProjectId(callback); return; @@ -452,2036 +570,2711 @@ export class ProductServiceClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Creates a {@link protos.google.cloud.retail.v2alpha.Product|Product}. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent catalog resource name, such as - * `projects/* /locations/global/catalogs/default_catalog/branches/default_branch`. - * @param {google.cloud.retail.v2alpha.Product} request.product - * Required. The {@link protos.google.cloud.retail.v2alpha.Product|Product} to create. - * @param {string} request.productId - * Required. The ID to use for the - * {@link protos.google.cloud.retail.v2alpha.Product|Product}, which will become the final - * component of the {@link protos.google.cloud.retail.v2alpha.Product.name|Product.name}. - * - * If the caller does not have permission to create the - * {@link protos.google.cloud.retail.v2alpha.Product|Product}, regardless of whether or - * not it exists, a PERMISSION_DENIED error is returned. - * - * This field must be unique among all - * {@link protos.google.cloud.retail.v2alpha.Product|Product}s with the same - * {@link protos.google.cloud.retail.v2alpha.CreateProductRequest.parent|parent}. - * Otherwise, an ALREADY_EXISTS error is returned. - * - * This field must be a UTF-8 encoded string with a length limit of 128 - * characters. Otherwise, an INVALID_ARGUMENT error is returned. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.Product|Product}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/product_service.create_product.js - * region_tag:retail_v2alpha_generated_ProductService_CreateProduct_async - */ + /** + * Creates a {@link protos.google.cloud.retail.v2alpha.Product|Product}. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent catalog resource name, such as + * `projects/* /locations/global/catalogs/default_catalog/branches/default_branch`. + * @param {google.cloud.retail.v2alpha.Product} request.product + * Required. The {@link protos.google.cloud.retail.v2alpha.Product|Product} to create. + * @param {string} request.productId + * Required. The ID to use for the + * {@link protos.google.cloud.retail.v2alpha.Product|Product}, which will become the final + * component of the {@link protos.google.cloud.retail.v2alpha.Product.name|Product.name}. + * + * If the caller does not have permission to create the + * {@link protos.google.cloud.retail.v2alpha.Product|Product}, regardless of whether or + * not it exists, a PERMISSION_DENIED error is returned. + * + * This field must be unique among all + * {@link protos.google.cloud.retail.v2alpha.Product|Product}s with the same + * {@link protos.google.cloud.retail.v2alpha.CreateProductRequest.parent|parent}. + * Otherwise, an ALREADY_EXISTS error is returned. + * + * This field must be a UTF-8 encoded string with a length limit of 128 + * characters. Otherwise, an INVALID_ARGUMENT error is returned. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.Product|Product}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/product_service.create_product.js + * region_tag:retail_v2alpha_generated_ProductService_CreateProduct_async + */ createProduct( - request?: protos.google.cloud.retail.v2alpha.ICreateProductRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.retail.v2alpha.IProduct, - protos.google.cloud.retail.v2alpha.ICreateProductRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.ICreateProductRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IProduct, + protos.google.cloud.retail.v2alpha.ICreateProductRequest | undefined, + {} | undefined, + ] + >; createProduct( - request: protos.google.cloud.retail.v2alpha.ICreateProductRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.retail.v2alpha.IProduct, - protos.google.cloud.retail.v2alpha.ICreateProductRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.ICreateProductRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.retail.v2alpha.IProduct, + | protos.google.cloud.retail.v2alpha.ICreateProductRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createProduct( - request: protos.google.cloud.retail.v2alpha.ICreateProductRequest, - callback: Callback< - protos.google.cloud.retail.v2alpha.IProduct, - protos.google.cloud.retail.v2alpha.ICreateProductRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.ICreateProductRequest, + callback: Callback< + protos.google.cloud.retail.v2alpha.IProduct, + | protos.google.cloud.retail.v2alpha.ICreateProductRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createProduct( - request?: protos.google.cloud.retail.v2alpha.ICreateProductRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.cloud.retail.v2alpha.ICreateProductRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.retail.v2alpha.IProduct, - protos.google.cloud.retail.v2alpha.ICreateProductRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.cloud.retail.v2alpha.IProduct, - protos.google.cloud.retail.v2alpha.ICreateProductRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.retail.v2alpha.IProduct, - protos.google.cloud.retail.v2alpha.ICreateProductRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.retail.v2alpha.ICreateProductRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.retail.v2alpha.IProduct, + | protos.google.cloud.retail.v2alpha.ICreateProductRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IProduct, + protos.google.cloud.retail.v2alpha.ICreateProductRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('createProduct request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.retail.v2alpha.IProduct, - protos.google.cloud.retail.v2alpha.ICreateProductRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.retail.v2alpha.IProduct, + | protos.google.cloud.retail.v2alpha.ICreateProductRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createProduct response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.createProduct(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.retail.v2alpha.IProduct, - protos.google.cloud.retail.v2alpha.ICreateProductRequest|undefined, - {}|undefined - ]) => { - this._log.info('createProduct response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createProduct(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.retail.v2alpha.IProduct, + protos.google.cloud.retail.v2alpha.ICreateProductRequest | undefined, + {} | undefined, + ]) => { + this._log.info('createProduct response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Gets a {@link protos.google.cloud.retail.v2alpha.Product|Product}. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. Full resource name of - * {@link protos.google.cloud.retail.v2alpha.Product|Product}, such as - * `projects/* /locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id`. - * - * If the caller does not have permission to access the - * {@link protos.google.cloud.retail.v2alpha.Product|Product}, regardless of whether or - * not it exists, a PERMISSION_DENIED error is returned. - * - * If the requested {@link protos.google.cloud.retail.v2alpha.Product|Product} does not - * exist, a NOT_FOUND error is returned. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.Product|Product}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/product_service.get_product.js - * region_tag:retail_v2alpha_generated_ProductService_GetProduct_async - */ + /** + * Gets a {@link protos.google.cloud.retail.v2alpha.Product|Product}. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Full resource name of + * {@link protos.google.cloud.retail.v2alpha.Product|Product}, such as + * `projects/* /locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id`. + * + * If the caller does not have permission to access the + * {@link protos.google.cloud.retail.v2alpha.Product|Product}, regardless of whether or + * not it exists, a PERMISSION_DENIED error is returned. + * + * If the requested {@link protos.google.cloud.retail.v2alpha.Product|Product} does not + * exist, a NOT_FOUND error is returned. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.Product|Product}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/product_service.get_product.js + * region_tag:retail_v2alpha_generated_ProductService_GetProduct_async + */ getProduct( - request?: protos.google.cloud.retail.v2alpha.IGetProductRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.retail.v2alpha.IProduct, - protos.google.cloud.retail.v2alpha.IGetProductRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.IGetProductRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IProduct, + protos.google.cloud.retail.v2alpha.IGetProductRequest | undefined, + {} | undefined, + ] + >; getProduct( - request: protos.google.cloud.retail.v2alpha.IGetProductRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.retail.v2alpha.IProduct, - protos.google.cloud.retail.v2alpha.IGetProductRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IGetProductRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.retail.v2alpha.IProduct, + protos.google.cloud.retail.v2alpha.IGetProductRequest | null | undefined, + {} | null | undefined + >, + ): void; getProduct( - request: protos.google.cloud.retail.v2alpha.IGetProductRequest, - callback: Callback< - protos.google.cloud.retail.v2alpha.IProduct, - protos.google.cloud.retail.v2alpha.IGetProductRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IGetProductRequest, + callback: Callback< + protos.google.cloud.retail.v2alpha.IProduct, + protos.google.cloud.retail.v2alpha.IGetProductRequest | null | undefined, + {} | null | undefined + >, + ): void; getProduct( - request?: protos.google.cloud.retail.v2alpha.IGetProductRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.cloud.retail.v2alpha.IGetProductRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.retail.v2alpha.IProduct, - protos.google.cloud.retail.v2alpha.IGetProductRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.cloud.retail.v2alpha.IProduct, - protos.google.cloud.retail.v2alpha.IGetProductRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.retail.v2alpha.IProduct, - protos.google.cloud.retail.v2alpha.IGetProductRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.retail.v2alpha.IGetProductRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.retail.v2alpha.IProduct, + protos.google.cloud.retail.v2alpha.IGetProductRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IProduct, + protos.google.cloud.retail.v2alpha.IGetProductRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getProduct request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.retail.v2alpha.IProduct, - protos.google.cloud.retail.v2alpha.IGetProductRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.retail.v2alpha.IProduct, + | protos.google.cloud.retail.v2alpha.IGetProductRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getProduct response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getProduct(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.retail.v2alpha.IProduct, - protos.google.cloud.retail.v2alpha.IGetProductRequest|undefined, - {}|undefined - ]) => { - this._log.info('getProduct response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getProduct(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.retail.v2alpha.IProduct, + protos.google.cloud.retail.v2alpha.IGetProductRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getProduct response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Updates a {@link protos.google.cloud.retail.v2alpha.Product|Product}. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.cloud.retail.v2alpha.Product} request.product - * Required. The product to update/create. - * - * If the caller does not have permission to update the - * {@link protos.google.cloud.retail.v2alpha.Product|Product}, regardless of whether or - * not it exists, a PERMISSION_DENIED error is returned. - * - * If the {@link protos.google.cloud.retail.v2alpha.Product|Product} to update does not - * exist and - * {@link protos.google.cloud.retail.v2alpha.UpdateProductRequest.allow_missing|allow_missing} - * is not set, a NOT_FOUND error is returned. - * @param {google.protobuf.FieldMask} request.updateMask - * Indicates which fields in the provided - * {@link protos.google.cloud.retail.v2alpha.Product|Product} to update. The immutable and - * output only fields are NOT supported. If not set, all supported fields (the - * fields that are neither immutable nor output only) are updated. - * - * If an unsupported or unknown field is provided, an INVALID_ARGUMENT error - * is returned. - * - * The attribute key can be updated by setting the mask path as - * "attributes.${key_name}". If a key name is present in the mask but not in - * the patching product from the request, this key will be deleted after the - * update. - * @param {boolean} request.allowMissing - * If set to true, and the {@link protos.google.cloud.retail.v2alpha.Product|Product} is - * not found, a new {@link protos.google.cloud.retail.v2alpha.Product|Product} will be - * created. In this situation, `update_mask` is ignored. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.Product|Product}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/product_service.update_product.js - * region_tag:retail_v2alpha_generated_ProductService_UpdateProduct_async - */ + /** + * Updates a {@link protos.google.cloud.retail.v2alpha.Product|Product}. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.cloud.retail.v2alpha.Product} request.product + * Required. The product to update/create. + * + * If the caller does not have permission to update the + * {@link protos.google.cloud.retail.v2alpha.Product|Product}, regardless of whether or + * not it exists, a PERMISSION_DENIED error is returned. + * + * If the {@link protos.google.cloud.retail.v2alpha.Product|Product} to update does not + * exist and + * {@link protos.google.cloud.retail.v2alpha.UpdateProductRequest.allow_missing|allow_missing} + * is not set, a NOT_FOUND error is returned. + * @param {google.protobuf.FieldMask} request.updateMask + * Indicates which fields in the provided + * {@link protos.google.cloud.retail.v2alpha.Product|Product} to update. The immutable and + * output only fields are NOT supported. If not set, all supported fields (the + * fields that are neither immutable nor output only) are updated. + * + * If an unsupported or unknown field is provided, an INVALID_ARGUMENT error + * is returned. + * + * The attribute key can be updated by setting the mask path as + * "attributes.${key_name}". If a key name is present in the mask but not in + * the patching product from the request, this key will be deleted after the + * update. + * @param {boolean} request.allowMissing + * If set to true, and the {@link protos.google.cloud.retail.v2alpha.Product|Product} is + * not found, a new {@link protos.google.cloud.retail.v2alpha.Product|Product} will be + * created. In this situation, `update_mask` is ignored. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.Product|Product}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/product_service.update_product.js + * region_tag:retail_v2alpha_generated_ProductService_UpdateProduct_async + */ updateProduct( - request?: protos.google.cloud.retail.v2alpha.IUpdateProductRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.retail.v2alpha.IProduct, - protos.google.cloud.retail.v2alpha.IUpdateProductRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.IUpdateProductRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IProduct, + protos.google.cloud.retail.v2alpha.IUpdateProductRequest | undefined, + {} | undefined, + ] + >; updateProduct( - request: protos.google.cloud.retail.v2alpha.IUpdateProductRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.retail.v2alpha.IProduct, - protos.google.cloud.retail.v2alpha.IUpdateProductRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IUpdateProductRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.retail.v2alpha.IProduct, + | protos.google.cloud.retail.v2alpha.IUpdateProductRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateProduct( - request: protos.google.cloud.retail.v2alpha.IUpdateProductRequest, - callback: Callback< - protos.google.cloud.retail.v2alpha.IProduct, - protos.google.cloud.retail.v2alpha.IUpdateProductRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IUpdateProductRequest, + callback: Callback< + protos.google.cloud.retail.v2alpha.IProduct, + | protos.google.cloud.retail.v2alpha.IUpdateProductRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateProduct( - request?: protos.google.cloud.retail.v2alpha.IUpdateProductRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.retail.v2alpha.IProduct, - protos.google.cloud.retail.v2alpha.IUpdateProductRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.retail.v2alpha.IUpdateProductRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.retail.v2alpha.IProduct, - protos.google.cloud.retail.v2alpha.IUpdateProductRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.retail.v2alpha.IProduct, - protos.google.cloud.retail.v2alpha.IUpdateProductRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.retail.v2alpha.IUpdateProductRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.retail.v2alpha.IProduct, + | protos.google.cloud.retail.v2alpha.IUpdateProductRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IProduct, + protos.google.cloud.retail.v2alpha.IUpdateProductRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'product.name': request.product!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'product.name': request.product!.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateProduct request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.retail.v2alpha.IProduct, - protos.google.cloud.retail.v2alpha.IUpdateProductRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.retail.v2alpha.IProduct, + | protos.google.cloud.retail.v2alpha.IUpdateProductRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateProduct response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.updateProduct(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.retail.v2alpha.IProduct, - protos.google.cloud.retail.v2alpha.IUpdateProductRequest|undefined, - {}|undefined - ]) => { - this._log.info('updateProduct response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateProduct(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.retail.v2alpha.IProduct, + protos.google.cloud.retail.v2alpha.IUpdateProductRequest | undefined, + {} | undefined, + ]) => { + this._log.info('updateProduct response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Deletes a {@link protos.google.cloud.retail.v2alpha.Product|Product}. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. Full resource name of - * {@link protos.google.cloud.retail.v2alpha.Product|Product}, such as - * `projects/* /locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id`. - * - * If the caller does not have permission to delete the - * {@link protos.google.cloud.retail.v2alpha.Product|Product}, regardless of whether or - * not it exists, a PERMISSION_DENIED error is returned. - * - * If the {@link protos.google.cloud.retail.v2alpha.Product|Product} to delete does not - * exist, a NOT_FOUND error is returned. - * - * The {@link protos.google.cloud.retail.v2alpha.Product|Product} to delete can neither be - * a - * {@link protos.google.cloud.retail.v2alpha.Product.Type.COLLECTION|Product.Type.COLLECTION} - * {@link protos.google.cloud.retail.v2alpha.Product|Product} member nor a - * {@link protos.google.cloud.retail.v2alpha.Product.Type.PRIMARY|Product.Type.PRIMARY} - * {@link protos.google.cloud.retail.v2alpha.Product|Product} with more than one - * {@link protos.google.cloud.retail.v2alpha.Product.Type.VARIANT|variants}. Otherwise, an - * INVALID_ARGUMENT error is returned. - * - * All inventory information for the named - * {@link protos.google.cloud.retail.v2alpha.Product|Product} will be deleted. - * @param {boolean} request.force - * This value only applies to the case when the target product is of type - * PRIMARY. - * When deleting a product of VARIANT/COLLECTION type, this value - * will be ignored. - * When set to true, the subsequent variant products will be - * deleted. - * When set to false, if the primary product has active variant products, an - * error will be returned. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/product_service.delete_product.js - * region_tag:retail_v2alpha_generated_ProductService_DeleteProduct_async - */ + /** + * Deletes a {@link protos.google.cloud.retail.v2alpha.Product|Product}. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Full resource name of + * {@link protos.google.cloud.retail.v2alpha.Product|Product}, such as + * `projects/* /locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id`. + * + * If the caller does not have permission to delete the + * {@link protos.google.cloud.retail.v2alpha.Product|Product}, regardless of whether or + * not it exists, a PERMISSION_DENIED error is returned. + * + * If the {@link protos.google.cloud.retail.v2alpha.Product|Product} to delete does not + * exist, a NOT_FOUND error is returned. + * + * The {@link protos.google.cloud.retail.v2alpha.Product|Product} to delete can neither be + * a + * {@link protos.google.cloud.retail.v2alpha.Product.Type.COLLECTION|Product.Type.COLLECTION} + * {@link protos.google.cloud.retail.v2alpha.Product|Product} member nor a + * {@link protos.google.cloud.retail.v2alpha.Product.Type.PRIMARY|Product.Type.PRIMARY} + * {@link protos.google.cloud.retail.v2alpha.Product|Product} with more than one + * {@link protos.google.cloud.retail.v2alpha.Product.Type.VARIANT|variants}. Otherwise, an + * INVALID_ARGUMENT error is returned. + * + * All inventory information for the named + * {@link protos.google.cloud.retail.v2alpha.Product|Product} will be deleted. + * @param {boolean} request.force + * This value only applies to the case when the target product is of type + * PRIMARY. + * When deleting a product of VARIANT/COLLECTION type, this value + * will be ignored. + * When set to true, the subsequent variant products will be + * deleted. + * When set to false, if the primary product has active variant products, an + * error will be returned. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/product_service.delete_product.js + * region_tag:retail_v2alpha_generated_ProductService_DeleteProduct_async + */ deleteProduct( - request?: protos.google.cloud.retail.v2alpha.IDeleteProductRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.cloud.retail.v2alpha.IDeleteProductRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.IDeleteProductRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.cloud.retail.v2alpha.IDeleteProductRequest | undefined, + {} | undefined, + ] + >; deleteProduct( - request: protos.google.cloud.retail.v2alpha.IDeleteProductRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.cloud.retail.v2alpha.IDeleteProductRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IDeleteProductRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.cloud.retail.v2alpha.IDeleteProductRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteProduct( - request: protos.google.cloud.retail.v2alpha.IDeleteProductRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.cloud.retail.v2alpha.IDeleteProductRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IDeleteProductRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.cloud.retail.v2alpha.IDeleteProductRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteProduct( - request?: protos.google.cloud.retail.v2alpha.IDeleteProductRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.cloud.retail.v2alpha.IDeleteProductRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.cloud.retail.v2alpha.IDeleteProductRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.protobuf.IEmpty, - protos.google.cloud.retail.v2alpha.IDeleteProductRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.cloud.retail.v2alpha.IDeleteProductRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.retail.v2alpha.IDeleteProductRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + | protos.google.cloud.retail.v2alpha.IDeleteProductRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.cloud.retail.v2alpha.IDeleteProductRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('deleteProduct request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.cloud.retail.v2alpha.IDeleteProductRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.cloud.retail.v2alpha.IDeleteProductRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteProduct response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.deleteProduct(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.cloud.retail.v2alpha.IDeleteProductRequest|undefined, - {}|undefined - ]) => { - this._log.info('deleteProduct response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteProduct(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.cloud.retail.v2alpha.IDeleteProductRequest | undefined, + {} | undefined, + ]) => { + this._log.info('deleteProduct response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Permanently deletes all selected - * {@link protos.google.cloud.retail.v2alpha.Product|Product}s under a branch. - * - * This process is asynchronous. If the request is valid, the removal will be - * enqueued and processed offline. Depending on the number of - * {@link protos.google.cloud.retail.v2alpha.Product|Product}s, this operation could take - * hours to complete. Before the operation completes, some - * {@link protos.google.cloud.retail.v2alpha.Product|Product}s may still be returned by - * {@link protos.google.cloud.retail.v2alpha.ProductService.GetProduct|ProductService.GetProduct} - * or - * {@link protos.google.cloud.retail.v2alpha.ProductService.ListProducts|ProductService.ListProducts}. - * - * Depending on the number of {@link protos.google.cloud.retail.v2alpha.Product|Product}s, - * this operation could take hours to complete. To get a sample of - * {@link protos.google.cloud.retail.v2alpha.Product|Product}s that would be deleted, set - * {@link protos.google.cloud.retail.v2alpha.PurgeProductsRequest.force|PurgeProductsRequest.force} - * to false. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The resource name of the branch under which the products are - * created. The format is - * `projects/${projectId}/locations/global/catalogs/${catalogId}/branches/${branchId}` - * @param {string} request.filter - * Required. The filter string to specify the products to be deleted with a - * length limit of 5,000 characters. - * - * Empty string filter is not allowed. "*" implies delete all items in a - * branch. - * - * The eligible fields for filtering are: - * - * * `availability`: Double quoted - * {@link protos.google.cloud.retail.v2alpha.Product.availability|Product.availability} - * string. - * * `create_time` : in ISO 8601 "zulu" format. - * - * Supported syntax: - * - * * Comparators (">", "<", ">=", "<=", "="). - * Examples: - * * create_time <= "2015-02-13T17:05:46Z" - * * availability = "IN_STOCK" - * - * * Conjunctions ("AND") - * Examples: - * * create_time <= "2015-02-13T17:05:46Z" AND availability = "PREORDER" - * - * * Disjunctions ("OR") - * Examples: - * * create_time <= "2015-02-13T17:05:46Z" OR availability = "IN_STOCK" - * - * * Can support nested queries. - * Examples: - * * (create_time <= "2015-02-13T17:05:46Z" AND availability = "PREORDER") - * OR (create_time >= "2015-02-14T13:03:32Z" AND availability = "IN_STOCK") - * - * * Filter Limits: - * * Filter should not contain more than 6 conditions. - * * Max nesting depth should not exceed 2 levels. - * - * Examples queries: - * * Delete back order products created before a timestamp. - * create_time <= "2015-02-13T17:05:46Z" OR availability = "BACKORDER" - * @param {boolean} request.force - * Actually perform the purge. - * If `force` is set to false, the method will return the expected purge count - * without deleting any products. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing - * a long running operation. Its `promise()` method returns a promise - * you can `await` for. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/product_service.purge_products.js - * region_tag:retail_v2alpha_generated_ProductService_PurgeProducts_async - */ + /** + * Permanently deletes all selected + * {@link protos.google.cloud.retail.v2alpha.Product|Product}s under a branch. + * + * This process is asynchronous. If the request is valid, the removal will be + * enqueued and processed offline. Depending on the number of + * {@link protos.google.cloud.retail.v2alpha.Product|Product}s, this operation could take + * hours to complete. Before the operation completes, some + * {@link protos.google.cloud.retail.v2alpha.Product|Product}s may still be returned by + * {@link protos.google.cloud.retail.v2alpha.ProductService.GetProduct|ProductService.GetProduct} + * or + * {@link protos.google.cloud.retail.v2alpha.ProductService.ListProducts|ProductService.ListProducts}. + * + * Depending on the number of {@link protos.google.cloud.retail.v2alpha.Product|Product}s, + * this operation could take hours to complete. To get a sample of + * {@link protos.google.cloud.retail.v2alpha.Product|Product}s that would be deleted, set + * {@link protos.google.cloud.retail.v2alpha.PurgeProductsRequest.force|PurgeProductsRequest.force} + * to false. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The resource name of the branch under which the products are + * created. The format is + * `projects/${projectId}/locations/global/catalogs/${catalogId}/branches/${branchId}` + * @param {string} request.filter + * Required. The filter string to specify the products to be deleted with a + * length limit of 5,000 characters. + * + * Empty string filter is not allowed. "*" implies delete all items in a + * branch. + * + * The eligible fields for filtering are: + * + * * `availability`: Double quoted + * {@link protos.google.cloud.retail.v2alpha.Product.availability|Product.availability} + * string. + * * `create_time` : in ISO 8601 "zulu" format. + * + * Supported syntax: + * + * * Comparators (">", "<", ">=", "<=", "="). + * Examples: + * * create_time <= "2015-02-13T17:05:46Z" + * * availability = "IN_STOCK" + * + * * Conjunctions ("AND") + * Examples: + * * create_time <= "2015-02-13T17:05:46Z" AND availability = "PREORDER" + * + * * Disjunctions ("OR") + * Examples: + * * create_time <= "2015-02-13T17:05:46Z" OR availability = "IN_STOCK" + * + * * Can support nested queries. + * Examples: + * * (create_time <= "2015-02-13T17:05:46Z" AND availability = "PREORDER") + * OR (create_time >= "2015-02-14T13:03:32Z" AND availability = "IN_STOCK") + * + * * Filter Limits: + * * Filter should not contain more than 6 conditions. + * * Max nesting depth should not exceed 2 levels. + * + * Examples queries: + * * Delete back order products created before a timestamp. + * create_time <= "2015-02-13T17:05:46Z" OR availability = "BACKORDER" + * @param {boolean} request.force + * Actually perform the purge. + * If `force` is set to false, the method will return the expected purge count + * without deleting any products. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/product_service.purge_products.js + * region_tag:retail_v2alpha_generated_ProductService_PurgeProducts_async + */ purgeProducts( - request?: protos.google.cloud.retail.v2alpha.IPurgeProductsRequest, - options?: CallOptions): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.IPurgeProductsRequest, + options?: CallOptions, + ): Promise< + [ + LROperation< + protos.google.cloud.retail.v2alpha.IPurgeProductsResponse, + protos.google.cloud.retail.v2alpha.IPurgeProductsMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; purgeProducts( - request: protos.google.cloud.retail.v2alpha.IPurgeProductsRequest, - options: CallOptions, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IPurgeProductsRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IPurgeProductsResponse, + protos.google.cloud.retail.v2alpha.IPurgeProductsMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; purgeProducts( - request: protos.google.cloud.retail.v2alpha.IPurgeProductsRequest, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IPurgeProductsRequest, + callback: Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IPurgeProductsResponse, + protos.google.cloud.retail.v2alpha.IPurgeProductsMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; purgeProducts( - request?: protos.google.cloud.retail.v2alpha.IPurgeProductsRequest, - optionsOrCallback?: CallOptions|Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>, - callback?: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>|void { + request?: protos.google.cloud.retail.v2alpha.IPurgeProductsRequest, + optionsOrCallback?: + | CallOptions + | Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IPurgeProductsResponse, + protos.google.cloud.retail.v2alpha.IPurgeProductsMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + callback?: Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IPurgeProductsResponse, + protos.google.cloud.retail.v2alpha.IPurgeProductsMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + LROperation< + protos.google.cloud.retail.v2alpha.IPurgeProductsResponse, + protos.google.cloud.retail.v2alpha.IPurgeProductsMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IPurgeProductsResponse, + protos.google.cloud.retail.v2alpha.IPurgeProductsMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, rawResponse, _) => { this._log.info('purgeProducts response %j', rawResponse); callback!(error, response, rawResponse, _); // We verified callback above. } : undefined; this._log.info('purgeProducts request %j', request); - return this.innerApiCalls.purgeProducts(request, options, wrappedCallback) - ?.then(([response, rawResponse, _]: [ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]) => { - this._log.info('purgeProducts response %j', rawResponse); - return [response, rawResponse, _]; - }); + return this.innerApiCalls + .purgeProducts(request, options, wrappedCallback) + ?.then( + ([response, rawResponse, _]: [ + LROperation< + protos.google.cloud.retail.v2alpha.IPurgeProductsResponse, + protos.google.cloud.retail.v2alpha.IPurgeProductsMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ]) => { + this._log.info('purgeProducts response %j', rawResponse); + return [response, rawResponse, _]; + }, + ); } -/** - * Check the status of the long running operation returned by `purgeProducts()`. - * @param {String} name - * The operation name that will be passed. - * @returns {Promise} - The promise which resolves to an object. - * The decoded operation object has result and metadata field to get information from. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/product_service.purge_products.js - * region_tag:retail_v2alpha_generated_ProductService_PurgeProducts_async - */ - async checkPurgeProductsProgress(name: string): Promise>{ + /** + * Check the status of the long running operation returned by `purgeProducts()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/product_service.purge_products.js + * region_tag:retail_v2alpha_generated_ProductService_PurgeProducts_async + */ + async checkPurgeProductsProgress( + name: string, + ): Promise< + LROperation< + protos.google.cloud.retail.v2alpha.PurgeProductsResponse, + protos.google.cloud.retail.v2alpha.PurgeProductsMetadata + > + > { this._log.info('purgeProducts long-running'); - const request = new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest({name}); + const request = + new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( + { name }, + ); const [operation] = await this.operationsClient.getOperation(request); - const decodeOperation = new this._gaxModule.Operation(operation, this.descriptors.longrunning.purgeProducts, this._gaxModule.createDefaultBackoffSettings()); - return decodeOperation as LROperation; + const decodeOperation = new this._gaxModule.Operation( + operation, + this.descriptors.longrunning.purgeProducts, + this._gaxModule.createDefaultBackoffSettings(), + ); + return decodeOperation as LROperation< + protos.google.cloud.retail.v2alpha.PurgeProductsResponse, + protos.google.cloud.retail.v2alpha.PurgeProductsMetadata + >; } -/** - * Bulk import of multiple {@link protos.google.cloud.retail.v2alpha.Product|Product}s. - * - * Request processing may be synchronous. - * Non-existing items are created. - * - * Note that it is possible for a subset of the - * {@link protos.google.cloud.retail.v2alpha.Product|Product}s to be successfully updated. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. - * `projects/1234/locations/global/catalogs/default_catalog/branches/default_branch` - * - * If no updateMask is specified, requires products.create permission. - * If updateMask is specified, requires products.update permission. - * @param {string} request.requestId - * Deprecated. This field has no effect. - * @param {google.cloud.retail.v2alpha.ProductInputConfig} request.inputConfig - * Required. The desired input location of the data. - * @param {google.cloud.retail.v2alpha.ImportErrorsConfig} request.errorsConfig - * The desired location of errors incurred during the Import. - * @param {google.protobuf.FieldMask} request.updateMask - * Indicates which fields in the provided imported `products` to update. If - * not set, all fields are updated. If provided, only the existing product - * fields are updated. Missing products will not be created. - * @param {google.cloud.retail.v2alpha.ImportProductsRequest.ReconciliationMode} request.reconciliationMode - * The mode of reconciliation between existing products and the products to be - * imported. Defaults to - * {@link protos.google.cloud.retail.v2alpha.ImportProductsRequest.ReconciliationMode.INCREMENTAL|ReconciliationMode.INCREMENTAL}. - * @param {string} request.notificationPubsubTopic - * Full Pub/Sub topic name for receiving notification. If this field is set, - * when the import is finished, a notification is sent to - * specified Pub/Sub topic. The message data is JSON string of a - * {@link protos.google.longrunning.Operation|Operation}. - * - * Format of the Pub/Sub topic is `projects/{project}/topics/{topic}`. It has - * to be within the same project as - * {@link protos.google.cloud.retail.v2alpha.ImportProductsRequest.parent|ImportProductsRequest.parent}. - * Make sure that both - * `cloud-retail-customer-data-access@system.gserviceaccount.com` and - * `service-@gcp-sa-retail.iam.gserviceaccount.com` - * have the `pubsub.topics.publish` IAM permission on the topic. - * - * Only supported when - * {@link protos.google.cloud.retail.v2alpha.ImportProductsRequest.reconciliation_mode|ImportProductsRequest.reconciliation_mode} - * is set to `FULL`. - * @param {boolean} request.skipDefaultBranchProtection - * If true, this performs the FULL import even if it would delete a large - * proportion of the products in the default branch, which could potentially - * cause outages if you have live predict/search traffic. - * - * Only supported when - * {@link protos.google.cloud.retail.v2alpha.ImportProductsRequest.reconciliation_mode|ImportProductsRequest.reconciliation_mode} - * is set to `FULL`. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing - * a long running operation. Its `promise()` method returns a promise - * you can `await` for. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/product_service.import_products.js - * region_tag:retail_v2alpha_generated_ProductService_ImportProducts_async - */ + /** + * Bulk import of multiple {@link protos.google.cloud.retail.v2alpha.Product|Product}s. + * + * Request processing may be synchronous. + * Non-existing items are created. + * + * Note that it is possible for a subset of the + * {@link protos.google.cloud.retail.v2alpha.Product|Product}s to be successfully updated. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. + * `projects/1234/locations/global/catalogs/default_catalog/branches/default_branch` + * + * If no updateMask is specified, requires products.create permission. + * If updateMask is specified, requires products.update permission. + * @param {string} request.requestId + * Deprecated. This field has no effect. + * @param {google.cloud.retail.v2alpha.ProductInputConfig} request.inputConfig + * Required. The desired input location of the data. + * @param {google.cloud.retail.v2alpha.ImportErrorsConfig} request.errorsConfig + * The desired location of errors incurred during the Import. + * @param {google.protobuf.FieldMask} request.updateMask + * Indicates which fields in the provided imported `products` to update. If + * not set, all fields are updated. If provided, only the existing product + * fields are updated. Missing products will not be created. + * @param {google.cloud.retail.v2alpha.ImportProductsRequest.ReconciliationMode} request.reconciliationMode + * The mode of reconciliation between existing products and the products to be + * imported. Defaults to + * {@link protos.google.cloud.retail.v2alpha.ImportProductsRequest.ReconciliationMode.INCREMENTAL|ReconciliationMode.INCREMENTAL}. + * @param {string} request.notificationPubsubTopic + * Full Pub/Sub topic name for receiving notification. If this field is set, + * when the import is finished, a notification is sent to + * specified Pub/Sub topic. The message data is JSON string of a + * {@link protos.google.longrunning.Operation|Operation}. + * + * Format of the Pub/Sub topic is `projects/{project}/topics/{topic}`. It has + * to be within the same project as + * {@link protos.google.cloud.retail.v2alpha.ImportProductsRequest.parent|ImportProductsRequest.parent}. + * Make sure that both + * `cloud-retail-customer-data-access@system.gserviceaccount.com` and + * `service-@gcp-sa-retail.iam.gserviceaccount.com` + * have the `pubsub.topics.publish` IAM permission on the topic. + * + * Only supported when + * {@link protos.google.cloud.retail.v2alpha.ImportProductsRequest.reconciliation_mode|ImportProductsRequest.reconciliation_mode} + * is set to `FULL`. + * @param {boolean} request.skipDefaultBranchProtection + * If true, this performs the FULL import even if it would delete a large + * proportion of the products in the default branch, which could potentially + * cause outages if you have live predict/search traffic. + * + * Only supported when + * {@link protos.google.cloud.retail.v2alpha.ImportProductsRequest.reconciliation_mode|ImportProductsRequest.reconciliation_mode} + * is set to `FULL`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/product_service.import_products.js + * region_tag:retail_v2alpha_generated_ProductService_ImportProducts_async + */ importProducts( - request?: protos.google.cloud.retail.v2alpha.IImportProductsRequest, - options?: CallOptions): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.IImportProductsRequest, + options?: CallOptions, + ): Promise< + [ + LROperation< + protos.google.cloud.retail.v2alpha.IImportProductsResponse, + protos.google.cloud.retail.v2alpha.IImportMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; importProducts( - request: protos.google.cloud.retail.v2alpha.IImportProductsRequest, - options: CallOptions, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IImportProductsRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IImportProductsResponse, + protos.google.cloud.retail.v2alpha.IImportMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; importProducts( - request: protos.google.cloud.retail.v2alpha.IImportProductsRequest, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IImportProductsRequest, + callback: Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IImportProductsResponse, + protos.google.cloud.retail.v2alpha.IImportMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; importProducts( - request?: protos.google.cloud.retail.v2alpha.IImportProductsRequest, - optionsOrCallback?: CallOptions|Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>, - callback?: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>|void { + request?: protos.google.cloud.retail.v2alpha.IImportProductsRequest, + optionsOrCallback?: + | CallOptions + | Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IImportProductsResponse, + protos.google.cloud.retail.v2alpha.IImportMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + callback?: Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IImportProductsResponse, + protos.google.cloud.retail.v2alpha.IImportMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + LROperation< + protos.google.cloud.retail.v2alpha.IImportProductsResponse, + protos.google.cloud.retail.v2alpha.IImportMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IImportProductsResponse, + protos.google.cloud.retail.v2alpha.IImportMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, rawResponse, _) => { this._log.info('importProducts response %j', rawResponse); callback!(error, response, rawResponse, _); // We verified callback above. } : undefined; this._log.info('importProducts request %j', request); - return this.innerApiCalls.importProducts(request, options, wrappedCallback) - ?.then(([response, rawResponse, _]: [ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]) => { - this._log.info('importProducts response %j', rawResponse); - return [response, rawResponse, _]; - }); + return this.innerApiCalls + .importProducts(request, options, wrappedCallback) + ?.then( + ([response, rawResponse, _]: [ + LROperation< + protos.google.cloud.retail.v2alpha.IImportProductsResponse, + protos.google.cloud.retail.v2alpha.IImportMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ]) => { + this._log.info('importProducts response %j', rawResponse); + return [response, rawResponse, _]; + }, + ); } -/** - * Check the status of the long running operation returned by `importProducts()`. - * @param {String} name - * The operation name that will be passed. - * @returns {Promise} - The promise which resolves to an object. - * The decoded operation object has result and metadata field to get information from. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/product_service.import_products.js - * region_tag:retail_v2alpha_generated_ProductService_ImportProducts_async - */ - async checkImportProductsProgress(name: string): Promise>{ + /** + * Check the status of the long running operation returned by `importProducts()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/product_service.import_products.js + * region_tag:retail_v2alpha_generated_ProductService_ImportProducts_async + */ + async checkImportProductsProgress( + name: string, + ): Promise< + LROperation< + protos.google.cloud.retail.v2alpha.ImportProductsResponse, + protos.google.cloud.retail.v2alpha.ImportMetadata + > + > { this._log.info('importProducts long-running'); - const request = new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest({name}); + const request = + new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( + { name }, + ); const [operation] = await this.operationsClient.getOperation(request); - const decodeOperation = new this._gaxModule.Operation(operation, this.descriptors.longrunning.importProducts, this._gaxModule.createDefaultBackoffSettings()); - return decodeOperation as LROperation; + const decodeOperation = new this._gaxModule.Operation( + operation, + this.descriptors.longrunning.importProducts, + this._gaxModule.createDefaultBackoffSettings(), + ); + return decodeOperation as LROperation< + protos.google.cloud.retail.v2alpha.ImportProductsResponse, + protos.google.cloud.retail.v2alpha.ImportMetadata + >; } -/** - * Exports multiple {@link protos.google.cloud.retail.v2alpha.Product|Product}s. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. Resource name of a {@link protos.google.cloud.retail.v2alpha.Branch|Branch}, - * and `default_branch` for branch_id component is supported. For example - * `projects/1234/locations/global/catalogs/default_catalog/branches/default_branch` - * @param {google.cloud.retail.v2alpha.OutputConfig} request.outputConfig - * Required. The output location of the data. - * @param {string} request.filter - * A filtering expression to specify restrictions on returned events. - * The expression is a sequence of terms. Each term applies a restriction to - * the returned products. Use this expression to restrict results to a - * specific time range, tag, or stock state or to filter products by product - * type. - * For example, `lastModifiedTime > "2012-04-23T18:25:43.511Z" - * lastModifiedTime<"2012-04-23T18:25:43.511Z" productType=primary` - * - * We expect only four types of fields: - * - * * `lastModifiedTime`: This can be specified twice, once with a - * less than operator and once with a greater than operator. The - * `lastModifiedTime` restriction should result in one, contiguous, - * valid, last-modified, time range. - * - * * `productType`: Supported values are `primary` and `variant`. The - * Boolean operators `OR` and `NOT` are supported if the expression is - * enclosed in parentheses and must be separated from the - * `productType` values by a space. - * - * * `availability`: Supported values are `IN_STOCK`, `OUT_OF_STOCK`, - * `PREORDER`, and `BACKORDER`. Boolean operators `OR` and `NOT` are - * supported if the expression is enclosed in parentheses and must be - * separated from the `availability` values by a space. - * - * * `Tag expressions`: Restricts output to products that match all of the - * specified tags. Boolean operators `OR` and `NOT` are supported if the - * expression is enclosed in parentheses and the operators are separated - * from the tag values by a space. Also supported is '`-"tagA"`', which - * is equivalent to '`NOT "tagA"`'. Tag values must be double-quoted, - * UTF-8 encoded strings and have a size limit of 1,000 characters. - * - * Some examples of valid filters expressions: - * - * * Example 1: `lastModifiedTime > "2012-04-23T18:25:43.511Z" - * lastModifiedTime < "2012-04-23T18:30:43.511Z"` - * * Example 2: `lastModifiedTime > "2012-04-23T18:25:43.511Z" - * productType = "variant"` - * * Example 3: `tag=("Red" OR "Blue") tag="New-Arrival" - * tag=(NOT "promotional") - * productType = "primary" lastModifiedTime < - * "2018-04-23T18:30:43.511Z"` - * * Example 4: `lastModifiedTime > "2012-04-23T18:25:43.511Z"` - * * Example 5: `availability = (IN_STOCK OR BACKORDER)` - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing - * a long running operation. Its `promise()` method returns a promise - * you can `await` for. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/product_service.export_products.js - * region_tag:retail_v2alpha_generated_ProductService_ExportProducts_async - */ + /** + * Exports multiple {@link protos.google.cloud.retail.v2alpha.Product|Product}s. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Resource name of a {@link protos.google.cloud.retail.v2alpha.Branch|Branch}, + * and `default_branch` for branch_id component is supported. For example + * `projects/1234/locations/global/catalogs/default_catalog/branches/default_branch` + * @param {google.cloud.retail.v2alpha.OutputConfig} request.outputConfig + * Required. The output location of the data. + * @param {string} request.filter + * A filtering expression to specify restrictions on returned events. + * The expression is a sequence of terms. Each term applies a restriction to + * the returned products. Use this expression to restrict results to a + * specific time range, tag, or stock state or to filter products by product + * type. + * For example, `lastModifiedTime > "2012-04-23T18:25:43.511Z" + * lastModifiedTime<"2012-04-23T18:25:43.511Z" productType=primary` + * + * We expect only four types of fields: + * + * * `lastModifiedTime`: This can be specified twice, once with a + * less than operator and once with a greater than operator. The + * `lastModifiedTime` restriction should result in one, contiguous, + * valid, last-modified, time range. + * + * * `productType`: Supported values are `primary` and `variant`. The + * Boolean operators `OR` and `NOT` are supported if the expression is + * enclosed in parentheses and must be separated from the + * `productType` values by a space. + * + * * `availability`: Supported values are `IN_STOCK`, `OUT_OF_STOCK`, + * `PREORDER`, and `BACKORDER`. Boolean operators `OR` and `NOT` are + * supported if the expression is enclosed in parentheses and must be + * separated from the `availability` values by a space. + * + * * `Tag expressions`: Restricts output to products that match all of the + * specified tags. Boolean operators `OR` and `NOT` are supported if the + * expression is enclosed in parentheses and the operators are separated + * from the tag values by a space. Also supported is '`-"tagA"`', which + * is equivalent to '`NOT "tagA"`'. Tag values must be double-quoted, + * UTF-8 encoded strings and have a size limit of 1,000 characters. + * + * Some examples of valid filters expressions: + * + * * Example 1: `lastModifiedTime > "2012-04-23T18:25:43.511Z" + * lastModifiedTime < "2012-04-23T18:30:43.511Z"` + * * Example 2: `lastModifiedTime > "2012-04-23T18:25:43.511Z" + * productType = "variant"` + * * Example 3: `tag=("Red" OR "Blue") tag="New-Arrival" + * tag=(NOT "promotional") + * productType = "primary" lastModifiedTime < + * "2018-04-23T18:30:43.511Z"` + * * Example 4: `lastModifiedTime > "2012-04-23T18:25:43.511Z"` + * * Example 5: `availability = (IN_STOCK OR BACKORDER)` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/product_service.export_products.js + * region_tag:retail_v2alpha_generated_ProductService_ExportProducts_async + */ exportProducts( - request?: protos.google.cloud.retail.v2alpha.IExportProductsRequest, - options?: CallOptions): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.IExportProductsRequest, + options?: CallOptions, + ): Promise< + [ + LROperation< + protos.google.cloud.retail.v2alpha.IExportProductsResponse, + protos.google.cloud.retail.v2alpha.IExportMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; exportProducts( - request: protos.google.cloud.retail.v2alpha.IExportProductsRequest, - options: CallOptions, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IExportProductsRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IExportProductsResponse, + protos.google.cloud.retail.v2alpha.IExportMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; exportProducts( - request: protos.google.cloud.retail.v2alpha.IExportProductsRequest, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IExportProductsRequest, + callback: Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IExportProductsResponse, + protos.google.cloud.retail.v2alpha.IExportMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; exportProducts( - request?: protos.google.cloud.retail.v2alpha.IExportProductsRequest, - optionsOrCallback?: CallOptions|Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>, - callback?: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>|void { + request?: protos.google.cloud.retail.v2alpha.IExportProductsRequest, + optionsOrCallback?: + | CallOptions + | Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IExportProductsResponse, + protos.google.cloud.retail.v2alpha.IExportMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + callback?: Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IExportProductsResponse, + protos.google.cloud.retail.v2alpha.IExportMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + LROperation< + protos.google.cloud.retail.v2alpha.IExportProductsResponse, + protos.google.cloud.retail.v2alpha.IExportMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IExportProductsResponse, + protos.google.cloud.retail.v2alpha.IExportMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, rawResponse, _) => { this._log.info('exportProducts response %j', rawResponse); callback!(error, response, rawResponse, _); // We verified callback above. } : undefined; this._log.info('exportProducts request %j', request); - return this.innerApiCalls.exportProducts(request, options, wrappedCallback) - ?.then(([response, rawResponse, _]: [ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]) => { - this._log.info('exportProducts response %j', rawResponse); - return [response, rawResponse, _]; - }); + return this.innerApiCalls + .exportProducts(request, options, wrappedCallback) + ?.then( + ([response, rawResponse, _]: [ + LROperation< + protos.google.cloud.retail.v2alpha.IExportProductsResponse, + protos.google.cloud.retail.v2alpha.IExportMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ]) => { + this._log.info('exportProducts response %j', rawResponse); + return [response, rawResponse, _]; + }, + ); } -/** - * Check the status of the long running operation returned by `exportProducts()`. - * @param {String} name - * The operation name that will be passed. - * @returns {Promise} - The promise which resolves to an object. - * The decoded operation object has result and metadata field to get information from. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/product_service.export_products.js - * region_tag:retail_v2alpha_generated_ProductService_ExportProducts_async - */ - async checkExportProductsProgress(name: string): Promise>{ + /** + * Check the status of the long running operation returned by `exportProducts()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/product_service.export_products.js + * region_tag:retail_v2alpha_generated_ProductService_ExportProducts_async + */ + async checkExportProductsProgress( + name: string, + ): Promise< + LROperation< + protos.google.cloud.retail.v2alpha.ExportProductsResponse, + protos.google.cloud.retail.v2alpha.ExportMetadata + > + > { this._log.info('exportProducts long-running'); - const request = new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest({name}); + const request = + new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( + { name }, + ); const [operation] = await this.operationsClient.getOperation(request); - const decodeOperation = new this._gaxModule.Operation(operation, this.descriptors.longrunning.exportProducts, this._gaxModule.createDefaultBackoffSettings()); - return decodeOperation as LROperation; + const decodeOperation = new this._gaxModule.Operation( + operation, + this.descriptors.longrunning.exportProducts, + this._gaxModule.createDefaultBackoffSettings(), + ); + return decodeOperation as LROperation< + protos.google.cloud.retail.v2alpha.ExportProductsResponse, + protos.google.cloud.retail.v2alpha.ExportMetadata + >; } -/** - * Updates inventory information for a - * {@link protos.google.cloud.retail.v2alpha.Product|Product} while respecting the last - * update timestamps of each inventory field. - * - * This process is asynchronous and does not require the - * {@link protos.google.cloud.retail.v2alpha.Product|Product} to exist before updating - * fulfillment information. If the request is valid, the update is enqueued - * and processed downstream. As a consequence, when a response is returned, - * updates are not immediately manifested in the - * {@link protos.google.cloud.retail.v2alpha.Product|Product} queried by - * {@link protos.google.cloud.retail.v2alpha.ProductService.GetProduct|ProductService.GetProduct} - * or - * {@link protos.google.cloud.retail.v2alpha.ProductService.ListProducts|ProductService.ListProducts}. - * - * When inventory is updated with - * {@link protos.google.cloud.retail.v2alpha.ProductService.CreateProduct|ProductService.CreateProduct} - * and - * {@link protos.google.cloud.retail.v2alpha.ProductService.UpdateProduct|ProductService.UpdateProduct}, - * the specified inventory field value(s) overwrite any existing value(s) - * while ignoring the last update time for this field. Furthermore, the last - * update times for the specified inventory fields are overwritten by the - * times of the - * {@link protos.google.cloud.retail.v2alpha.ProductService.CreateProduct|ProductService.CreateProduct} - * or - * {@link protos.google.cloud.retail.v2alpha.ProductService.UpdateProduct|ProductService.UpdateProduct} - * request. - * - * If no inventory fields are set in - * {@link protos.google.cloud.retail.v2alpha.CreateProductRequest.product|CreateProductRequest.product}, - * then any pre-existing inventory information for this product is used. - * - * If no inventory fields are set in - * {@link protos.google.cloud.retail.v2alpha.SetInventoryRequest.set_mask|SetInventoryRequest.set_mask}, - * then any existing inventory information is preserved. - * - * Pre-existing inventory information can only be updated with - * {@link protos.google.cloud.retail.v2alpha.ProductService.SetInventory|ProductService.SetInventory}, - * {@link protos.google.cloud.retail.v2alpha.ProductService.AddFulfillmentPlaces|ProductService.AddFulfillmentPlaces}, - * and - * {@link protos.google.cloud.retail.v2alpha.ProductService.RemoveFulfillmentPlaces|ProductService.RemoveFulfillmentPlaces}. - * - * The returned {@link protos.google.longrunning.Operation|Operation}s is obsolete after - * one day, and the {@link protos.google.longrunning.Operations.GetOperation|GetOperation} - * API returns `NOT_FOUND` afterwards. - * - * If conflicting updates are issued, the - * {@link protos.google.longrunning.Operation|Operation}s associated with the stale - * updates are not marked as {@link protos.google.longrunning.Operation.done|done} until - * they are obsolete. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.cloud.retail.v2alpha.Product} request.inventory - * Required. The inventory information to update. The allowable fields to - * update are: - * - * * {@link protos.google.cloud.retail.v2alpha.Product.price_info|Product.price_info} - * * {@link protos.google.cloud.retail.v2alpha.Product.availability|Product.availability} - * * {@link protos.google.cloud.retail.v2alpha.Product.available_quantity|Product.available_quantity} - * * {@link protos.google.cloud.retail.v2alpha.Product.fulfillment_info|Product.fulfillment_info} - * The updated inventory fields must be specified in - * {@link protos.google.cloud.retail.v2alpha.SetInventoryRequest.set_mask|SetInventoryRequest.set_mask}. - * - * If - * {@link protos.google.cloud.retail.v2alpha.Product.name|SetInventoryRequest.inventory.name} - * is empty or invalid, an INVALID_ARGUMENT error is returned. - * - * If the caller does not have permission to update the - * {@link protos.google.cloud.retail.v2alpha.Product|Product} named in - * {@link protos.google.cloud.retail.v2alpha.Product.name|Product.name}, regardless of - * whether or not it exists, a PERMISSION_DENIED error is returned. - * - * If the {@link protos.google.cloud.retail.v2alpha.Product|Product} to update does not - * have existing inventory information, the provided inventory information - * will be inserted. - * - * If the {@link protos.google.cloud.retail.v2alpha.Product|Product} to update has - * existing inventory information, the provided inventory information will be - * merged while respecting the last update time for each inventory field, - * using the provided or default value for - * {@link protos.google.cloud.retail.v2alpha.SetInventoryRequest.set_time|SetInventoryRequest.set_time}. - * - * The caller can replace place IDs for a subset of fulfillment types in the - * following ways: - * - * * Adds "fulfillment_info" in - * {@link protos.google.cloud.retail.v2alpha.SetInventoryRequest.set_mask|SetInventoryRequest.set_mask} - * * Specifies only the desired fulfillment types and corresponding place IDs - * to update in - * {@link protos.google.cloud.retail.v2alpha.Product.fulfillment_info|SetInventoryRequest.inventory.fulfillment_info} - * - * The caller can clear all place IDs from a subset of fulfillment types in - * the following ways: - * - * * Adds "fulfillment_info" in - * {@link protos.google.cloud.retail.v2alpha.SetInventoryRequest.set_mask|SetInventoryRequest.set_mask} - * * Specifies only the desired fulfillment types to clear in - * {@link protos.google.cloud.retail.v2alpha.Product.fulfillment_info|SetInventoryRequest.inventory.fulfillment_info} - * * Checks that only the desired fulfillment info types have empty - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.place_ids|SetInventoryRequest.inventory.fulfillment_info.place_ids} - * - * The last update time is recorded for the following inventory fields: - * * {@link protos.google.cloud.retail.v2alpha.Product.price_info|Product.price_info} - * * {@link protos.google.cloud.retail.v2alpha.Product.availability|Product.availability} - * * {@link protos.google.cloud.retail.v2alpha.Product.available_quantity|Product.available_quantity} - * * {@link protos.google.cloud.retail.v2alpha.Product.fulfillment_info|Product.fulfillment_info} - * - * If a full overwrite of inventory information while ignoring timestamps is - * needed, - * {@link protos.google.cloud.retail.v2alpha.ProductService.UpdateProduct|ProductService.UpdateProduct} - * should be invoked instead. - * @param {google.protobuf.FieldMask} request.setMask - * Indicates which inventory fields in the provided - * {@link protos.google.cloud.retail.v2alpha.Product|Product} to update. - * - * At least one field must be provided. - * - * If an unsupported or unknown field is provided, an INVALID_ARGUMENT error - * is returned and the entire update will be ignored. - * @param {google.protobuf.Timestamp} request.setTime - * The time when the request is issued, used to prevent - * out-of-order updates on inventory fields with the last update time - * recorded. If not provided, the internal system time will be used. - * @param {boolean} request.allowMissing - * If set to true, and the {@link protos.google.cloud.retail.v2alpha.Product|Product} with - * name {@link protos.google.cloud.retail.v2alpha.Product.name|Product.name} is not found, - * the inventory update will still be processed and retained for at most 1 day - * until the {@link protos.google.cloud.retail.v2alpha.Product|Product} is created. If set - * to false, a NOT_FOUND error is returned if the - * {@link protos.google.cloud.retail.v2alpha.Product|Product} is not found. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing - * a long running operation. Its `promise()` method returns a promise - * you can `await` for. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/product_service.set_inventory.js - * region_tag:retail_v2alpha_generated_ProductService_SetInventory_async - */ + /** + * Updates inventory information for a + * {@link protos.google.cloud.retail.v2alpha.Product|Product} while respecting the last + * update timestamps of each inventory field. + * + * This process is asynchronous and does not require the + * {@link protos.google.cloud.retail.v2alpha.Product|Product} to exist before updating + * fulfillment information. If the request is valid, the update is enqueued + * and processed downstream. As a consequence, when a response is returned, + * updates are not immediately manifested in the + * {@link protos.google.cloud.retail.v2alpha.Product|Product} queried by + * {@link protos.google.cloud.retail.v2alpha.ProductService.GetProduct|ProductService.GetProduct} + * or + * {@link protos.google.cloud.retail.v2alpha.ProductService.ListProducts|ProductService.ListProducts}. + * + * When inventory is updated with + * {@link protos.google.cloud.retail.v2alpha.ProductService.CreateProduct|ProductService.CreateProduct} + * and + * {@link protos.google.cloud.retail.v2alpha.ProductService.UpdateProduct|ProductService.UpdateProduct}, + * the specified inventory field value(s) overwrite any existing value(s) + * while ignoring the last update time for this field. Furthermore, the last + * update times for the specified inventory fields are overwritten by the + * times of the + * {@link protos.google.cloud.retail.v2alpha.ProductService.CreateProduct|ProductService.CreateProduct} + * or + * {@link protos.google.cloud.retail.v2alpha.ProductService.UpdateProduct|ProductService.UpdateProduct} + * request. + * + * If no inventory fields are set in + * {@link protos.google.cloud.retail.v2alpha.CreateProductRequest.product|CreateProductRequest.product}, + * then any pre-existing inventory information for this product is used. + * + * If no inventory fields are set in + * {@link protos.google.cloud.retail.v2alpha.SetInventoryRequest.set_mask|SetInventoryRequest.set_mask}, + * then any existing inventory information is preserved. + * + * Pre-existing inventory information can only be updated with + * {@link protos.google.cloud.retail.v2alpha.ProductService.SetInventory|ProductService.SetInventory}, + * {@link protos.google.cloud.retail.v2alpha.ProductService.AddFulfillmentPlaces|ProductService.AddFulfillmentPlaces}, + * and + * {@link protos.google.cloud.retail.v2alpha.ProductService.RemoveFulfillmentPlaces|ProductService.RemoveFulfillmentPlaces}. + * + * The returned {@link protos.google.longrunning.Operation|Operation}s is obsolete after + * one day, and the {@link protos.google.longrunning.Operations.GetOperation|GetOperation} + * API returns `NOT_FOUND` afterwards. + * + * If conflicting updates are issued, the + * {@link protos.google.longrunning.Operation|Operation}s associated with the stale + * updates are not marked as {@link protos.google.longrunning.Operation.done|done} until + * they are obsolete. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.cloud.retail.v2alpha.Product} request.inventory + * Required. The inventory information to update. The allowable fields to + * update are: + * + * * {@link protos.google.cloud.retail.v2alpha.Product.price_info|Product.price_info} + * * {@link protos.google.cloud.retail.v2alpha.Product.availability|Product.availability} + * * {@link protos.google.cloud.retail.v2alpha.Product.available_quantity|Product.available_quantity} + * * {@link protos.google.cloud.retail.v2alpha.Product.fulfillment_info|Product.fulfillment_info} + * The updated inventory fields must be specified in + * {@link protos.google.cloud.retail.v2alpha.SetInventoryRequest.set_mask|SetInventoryRequest.set_mask}. + * + * If + * {@link protos.google.cloud.retail.v2alpha.Product.name|SetInventoryRequest.inventory.name} + * is empty or invalid, an INVALID_ARGUMENT error is returned. + * + * If the caller does not have permission to update the + * {@link protos.google.cloud.retail.v2alpha.Product|Product} named in + * {@link protos.google.cloud.retail.v2alpha.Product.name|Product.name}, regardless of + * whether or not it exists, a PERMISSION_DENIED error is returned. + * + * If the {@link protos.google.cloud.retail.v2alpha.Product|Product} to update does not + * have existing inventory information, the provided inventory information + * will be inserted. + * + * If the {@link protos.google.cloud.retail.v2alpha.Product|Product} to update has + * existing inventory information, the provided inventory information will be + * merged while respecting the last update time for each inventory field, + * using the provided or default value for + * {@link protos.google.cloud.retail.v2alpha.SetInventoryRequest.set_time|SetInventoryRequest.set_time}. + * + * The caller can replace place IDs for a subset of fulfillment types in the + * following ways: + * + * * Adds "fulfillment_info" in + * {@link protos.google.cloud.retail.v2alpha.SetInventoryRequest.set_mask|SetInventoryRequest.set_mask} + * * Specifies only the desired fulfillment types and corresponding place IDs + * to update in + * {@link protos.google.cloud.retail.v2alpha.Product.fulfillment_info|SetInventoryRequest.inventory.fulfillment_info} + * + * The caller can clear all place IDs from a subset of fulfillment types in + * the following ways: + * + * * Adds "fulfillment_info" in + * {@link protos.google.cloud.retail.v2alpha.SetInventoryRequest.set_mask|SetInventoryRequest.set_mask} + * * Specifies only the desired fulfillment types to clear in + * {@link protos.google.cloud.retail.v2alpha.Product.fulfillment_info|SetInventoryRequest.inventory.fulfillment_info} + * * Checks that only the desired fulfillment info types have empty + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.place_ids|SetInventoryRequest.inventory.fulfillment_info.place_ids} + * + * The last update time is recorded for the following inventory fields: + * * {@link protos.google.cloud.retail.v2alpha.Product.price_info|Product.price_info} + * * {@link protos.google.cloud.retail.v2alpha.Product.availability|Product.availability} + * * {@link protos.google.cloud.retail.v2alpha.Product.available_quantity|Product.available_quantity} + * * {@link protos.google.cloud.retail.v2alpha.Product.fulfillment_info|Product.fulfillment_info} + * + * If a full overwrite of inventory information while ignoring timestamps is + * needed, + * {@link protos.google.cloud.retail.v2alpha.ProductService.UpdateProduct|ProductService.UpdateProduct} + * should be invoked instead. + * @param {google.protobuf.FieldMask} request.setMask + * Indicates which inventory fields in the provided + * {@link protos.google.cloud.retail.v2alpha.Product|Product} to update. + * + * At least one field must be provided. + * + * If an unsupported or unknown field is provided, an INVALID_ARGUMENT error + * is returned and the entire update will be ignored. + * @param {google.protobuf.Timestamp} request.setTime + * The time when the request is issued, used to prevent + * out-of-order updates on inventory fields with the last update time + * recorded. If not provided, the internal system time will be used. + * @param {boolean} request.allowMissing + * If set to true, and the {@link protos.google.cloud.retail.v2alpha.Product|Product} with + * name {@link protos.google.cloud.retail.v2alpha.Product.name|Product.name} is not found, + * the inventory update will still be processed and retained for at most 1 day + * until the {@link protos.google.cloud.retail.v2alpha.Product|Product} is created. If set + * to false, a NOT_FOUND error is returned if the + * {@link protos.google.cloud.retail.v2alpha.Product|Product} is not found. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/product_service.set_inventory.js + * region_tag:retail_v2alpha_generated_ProductService_SetInventory_async + */ setInventory( - request?: protos.google.cloud.retail.v2alpha.ISetInventoryRequest, - options?: CallOptions): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.ISetInventoryRequest, + options?: CallOptions, + ): Promise< + [ + LROperation< + protos.google.cloud.retail.v2alpha.ISetInventoryResponse, + protos.google.cloud.retail.v2alpha.ISetInventoryMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; setInventory( - request: protos.google.cloud.retail.v2alpha.ISetInventoryRequest, - options: CallOptions, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.ISetInventoryRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.cloud.retail.v2alpha.ISetInventoryResponse, + protos.google.cloud.retail.v2alpha.ISetInventoryMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; setInventory( - request: protos.google.cloud.retail.v2alpha.ISetInventoryRequest, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.ISetInventoryRequest, + callback: Callback< + LROperation< + protos.google.cloud.retail.v2alpha.ISetInventoryResponse, + protos.google.cloud.retail.v2alpha.ISetInventoryMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; setInventory( - request?: protos.google.cloud.retail.v2alpha.ISetInventoryRequest, - optionsOrCallback?: CallOptions|Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>, - callback?: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>|void { + request?: protos.google.cloud.retail.v2alpha.ISetInventoryRequest, + optionsOrCallback?: + | CallOptions + | Callback< + LROperation< + protos.google.cloud.retail.v2alpha.ISetInventoryResponse, + protos.google.cloud.retail.v2alpha.ISetInventoryMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + callback?: Callback< + LROperation< + protos.google.cloud.retail.v2alpha.ISetInventoryResponse, + protos.google.cloud.retail.v2alpha.ISetInventoryMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + LROperation< + protos.google.cloud.retail.v2alpha.ISetInventoryResponse, + protos.google.cloud.retail.v2alpha.ISetInventoryMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'inventory.name': request.inventory!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'inventory.name': request.inventory!.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + LROperation< + protos.google.cloud.retail.v2alpha.ISetInventoryResponse, + protos.google.cloud.retail.v2alpha.ISetInventoryMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, rawResponse, _) => { this._log.info('setInventory response %j', rawResponse); callback!(error, response, rawResponse, _); // We verified callback above. } : undefined; this._log.info('setInventory request %j', request); - return this.innerApiCalls.setInventory(request, options, wrappedCallback) - ?.then(([response, rawResponse, _]: [ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]) => { - this._log.info('setInventory response %j', rawResponse); - return [response, rawResponse, _]; - }); + return this.innerApiCalls + .setInventory(request, options, wrappedCallback) + ?.then( + ([response, rawResponse, _]: [ + LROperation< + protos.google.cloud.retail.v2alpha.ISetInventoryResponse, + protos.google.cloud.retail.v2alpha.ISetInventoryMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ]) => { + this._log.info('setInventory response %j', rawResponse); + return [response, rawResponse, _]; + }, + ); } -/** - * Check the status of the long running operation returned by `setInventory()`. - * @param {String} name - * The operation name that will be passed. - * @returns {Promise} - The promise which resolves to an object. - * The decoded operation object has result and metadata field to get information from. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/product_service.set_inventory.js - * region_tag:retail_v2alpha_generated_ProductService_SetInventory_async - */ - async checkSetInventoryProgress(name: string): Promise>{ + /** + * Check the status of the long running operation returned by `setInventory()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/product_service.set_inventory.js + * region_tag:retail_v2alpha_generated_ProductService_SetInventory_async + */ + async checkSetInventoryProgress( + name: string, + ): Promise< + LROperation< + protos.google.cloud.retail.v2alpha.SetInventoryResponse, + protos.google.cloud.retail.v2alpha.SetInventoryMetadata + > + > { this._log.info('setInventory long-running'); - const request = new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest({name}); + const request = + new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( + { name }, + ); const [operation] = await this.operationsClient.getOperation(request); - const decodeOperation = new this._gaxModule.Operation(operation, this.descriptors.longrunning.setInventory, this._gaxModule.createDefaultBackoffSettings()); - return decodeOperation as LROperation; + const decodeOperation = new this._gaxModule.Operation( + operation, + this.descriptors.longrunning.setInventory, + this._gaxModule.createDefaultBackoffSettings(), + ); + return decodeOperation as LROperation< + protos.google.cloud.retail.v2alpha.SetInventoryResponse, + protos.google.cloud.retail.v2alpha.SetInventoryMetadata + >; } -/** - * We recommend that you use the - * {@link protos.google.cloud.retail.v2alpha.ProductService.AddLocalInventories|ProductService.AddLocalInventories} - * method instead of the - * {@link protos.google.cloud.retail.v2alpha.ProductService.AddFulfillmentPlaces|ProductService.AddFulfillmentPlaces} - * method. - * {@link protos.google.cloud.retail.v2alpha.ProductService.AddLocalInventories|ProductService.AddLocalInventories} - * achieves the same results but provides more fine-grained control over - * ingesting local inventory data. - * - * Incrementally adds place IDs to - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.place_ids|Product.fulfillment_info.place_ids}. - * - * This process is asynchronous and does not require the - * {@link protos.google.cloud.retail.v2alpha.Product|Product} to exist before updating - * fulfillment information. If the request is valid, the update will be - * enqueued and processed downstream. As a consequence, when a response is - * returned, the added place IDs are not immediately manifested in the - * {@link protos.google.cloud.retail.v2alpha.Product|Product} queried by - * {@link protos.google.cloud.retail.v2alpha.ProductService.GetProduct|ProductService.GetProduct} - * or - * {@link protos.google.cloud.retail.v2alpha.ProductService.ListProducts|ProductService.ListProducts}. - * - * The returned {@link protos.google.longrunning.Operation|Operation}s will be obsolete - * after 1 day, and {@link protos.google.longrunning.Operations.GetOperation|GetOperation} - * API will return NOT_FOUND afterwards. - * - * If conflicting updates are issued, the - * {@link protos.google.longrunning.Operation|Operation}s associated with the stale - * updates will not be marked as {@link protos.google.longrunning.Operation.done|done} - * until being obsolete. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.product - * Required. Full resource name of - * {@link protos.google.cloud.retail.v2alpha.Product|Product}, such as - * `projects/* /locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id`. - * - * If the caller does not have permission to access the - * {@link protos.google.cloud.retail.v2alpha.Product|Product}, regardless of whether or - * not it exists, a PERMISSION_DENIED error is returned. - * @param {string} request.type - * Required. The fulfillment type, including commonly used types (such as - * pickup in store and same day delivery), and custom types. - * - * Supported values: - * - * * "pickup-in-store" - * * "ship-to-store" - * * "same-day-delivery" - * * "next-day-delivery" - * * "custom-type-1" - * * "custom-type-2" - * * "custom-type-3" - * * "custom-type-4" - * * "custom-type-5" - * - * If this field is set to an invalid value other than these, an - * INVALID_ARGUMENT error is returned. - * - * This field directly corresponds to - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.type|Product.fulfillment_info.type}. - * @param {string[]} request.placeIds - * Required. The IDs for this - * {@link protos.google.cloud.retail.v2alpha.AddFulfillmentPlacesRequest.type|type}, such - * as the store IDs for "pickup-in-store" or the region IDs for - * "same-day-delivery" to be added for this - * {@link protos.google.cloud.retail.v2alpha.AddFulfillmentPlacesRequest.type|type}. - * Duplicate IDs will be automatically ignored. - * - * At least 1 value is required, and a maximum of 2000 values are allowed. - * Each value must be a string with a length limit of 10 characters, matching - * the pattern `[a-zA-Z0-9_-]+`, such as "store1" or "REGION-2". Otherwise, an - * INVALID_ARGUMENT error is returned. - * - * If the total number of place IDs exceeds 2000 for this - * {@link protos.google.cloud.retail.v2alpha.AddFulfillmentPlacesRequest.type|type} after - * adding, then the update will be rejected. - * @param {google.protobuf.Timestamp} request.addTime - * The time when the fulfillment updates are issued, used to prevent - * out-of-order updates on fulfillment information. If not provided, the - * internal system time will be used. - * @param {boolean} request.allowMissing - * If set to true, and the {@link protos.google.cloud.retail.v2alpha.Product|Product} is - * not found, the fulfillment information will still be processed and retained - * for at most 1 day and processed once the - * {@link protos.google.cloud.retail.v2alpha.Product|Product} is created. If set to false, - * a NOT_FOUND error is returned if the - * {@link protos.google.cloud.retail.v2alpha.Product|Product} is not found. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing - * a long running operation. Its `promise()` method returns a promise - * you can `await` for. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/product_service.add_fulfillment_places.js - * region_tag:retail_v2alpha_generated_ProductService_AddFulfillmentPlaces_async - */ + /** + * We recommend that you use the + * {@link protos.google.cloud.retail.v2alpha.ProductService.AddLocalInventories|ProductService.AddLocalInventories} + * method instead of the + * {@link protos.google.cloud.retail.v2alpha.ProductService.AddFulfillmentPlaces|ProductService.AddFulfillmentPlaces} + * method. + * {@link protos.google.cloud.retail.v2alpha.ProductService.AddLocalInventories|ProductService.AddLocalInventories} + * achieves the same results but provides more fine-grained control over + * ingesting local inventory data. + * + * Incrementally adds place IDs to + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.place_ids|Product.fulfillment_info.place_ids}. + * + * This process is asynchronous and does not require the + * {@link protos.google.cloud.retail.v2alpha.Product|Product} to exist before updating + * fulfillment information. If the request is valid, the update will be + * enqueued and processed downstream. As a consequence, when a response is + * returned, the added place IDs are not immediately manifested in the + * {@link protos.google.cloud.retail.v2alpha.Product|Product} queried by + * {@link protos.google.cloud.retail.v2alpha.ProductService.GetProduct|ProductService.GetProduct} + * or + * {@link protos.google.cloud.retail.v2alpha.ProductService.ListProducts|ProductService.ListProducts}. + * + * The returned {@link protos.google.longrunning.Operation|Operation}s will be obsolete + * after 1 day, and {@link protos.google.longrunning.Operations.GetOperation|GetOperation} + * API will return NOT_FOUND afterwards. + * + * If conflicting updates are issued, the + * {@link protos.google.longrunning.Operation|Operation}s associated with the stale + * updates will not be marked as {@link protos.google.longrunning.Operation.done|done} + * until being obsolete. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.product + * Required. Full resource name of + * {@link protos.google.cloud.retail.v2alpha.Product|Product}, such as + * `projects/* /locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id`. + * + * If the caller does not have permission to access the + * {@link protos.google.cloud.retail.v2alpha.Product|Product}, regardless of whether or + * not it exists, a PERMISSION_DENIED error is returned. + * @param {string} request.type + * Required. The fulfillment type, including commonly used types (such as + * pickup in store and same day delivery), and custom types. + * + * Supported values: + * + * * "pickup-in-store" + * * "ship-to-store" + * * "same-day-delivery" + * * "next-day-delivery" + * * "custom-type-1" + * * "custom-type-2" + * * "custom-type-3" + * * "custom-type-4" + * * "custom-type-5" + * + * If this field is set to an invalid value other than these, an + * INVALID_ARGUMENT error is returned. + * + * This field directly corresponds to + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.type|Product.fulfillment_info.type}. + * @param {string[]} request.placeIds + * Required. The IDs for this + * {@link protos.google.cloud.retail.v2alpha.AddFulfillmentPlacesRequest.type|type}, such + * as the store IDs for "pickup-in-store" or the region IDs for + * "same-day-delivery" to be added for this + * {@link protos.google.cloud.retail.v2alpha.AddFulfillmentPlacesRequest.type|type}. + * Duplicate IDs will be automatically ignored. + * + * At least 1 value is required, and a maximum of 2000 values are allowed. + * Each value must be a string with a length limit of 10 characters, matching + * the pattern `[a-zA-Z0-9_-]+`, such as "store1" or "REGION-2". Otherwise, an + * INVALID_ARGUMENT error is returned. + * + * If the total number of place IDs exceeds 2000 for this + * {@link protos.google.cloud.retail.v2alpha.AddFulfillmentPlacesRequest.type|type} after + * adding, then the update will be rejected. + * @param {google.protobuf.Timestamp} request.addTime + * The time when the fulfillment updates are issued, used to prevent + * out-of-order updates on fulfillment information. If not provided, the + * internal system time will be used. + * @param {boolean} request.allowMissing + * If set to true, and the {@link protos.google.cloud.retail.v2alpha.Product|Product} is + * not found, the fulfillment information will still be processed and retained + * for at most 1 day and processed once the + * {@link protos.google.cloud.retail.v2alpha.Product|Product} is created. If set to false, + * a NOT_FOUND error is returned if the + * {@link protos.google.cloud.retail.v2alpha.Product|Product} is not found. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/product_service.add_fulfillment_places.js + * region_tag:retail_v2alpha_generated_ProductService_AddFulfillmentPlaces_async + */ addFulfillmentPlaces( - request?: protos.google.cloud.retail.v2alpha.IAddFulfillmentPlacesRequest, - options?: CallOptions): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.IAddFulfillmentPlacesRequest, + options?: CallOptions, + ): Promise< + [ + LROperation< + protos.google.cloud.retail.v2alpha.IAddFulfillmentPlacesResponse, + protos.google.cloud.retail.v2alpha.IAddFulfillmentPlacesMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; addFulfillmentPlaces( - request: protos.google.cloud.retail.v2alpha.IAddFulfillmentPlacesRequest, - options: CallOptions, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IAddFulfillmentPlacesRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IAddFulfillmentPlacesResponse, + protos.google.cloud.retail.v2alpha.IAddFulfillmentPlacesMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; addFulfillmentPlaces( - request: protos.google.cloud.retail.v2alpha.IAddFulfillmentPlacesRequest, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IAddFulfillmentPlacesRequest, + callback: Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IAddFulfillmentPlacesResponse, + protos.google.cloud.retail.v2alpha.IAddFulfillmentPlacesMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; addFulfillmentPlaces( - request?: protos.google.cloud.retail.v2alpha.IAddFulfillmentPlacesRequest, - optionsOrCallback?: CallOptions|Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>, - callback?: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>|void { + request?: protos.google.cloud.retail.v2alpha.IAddFulfillmentPlacesRequest, + optionsOrCallback?: + | CallOptions + | Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IAddFulfillmentPlacesResponse, + protos.google.cloud.retail.v2alpha.IAddFulfillmentPlacesMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + callback?: Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IAddFulfillmentPlacesResponse, + protos.google.cloud.retail.v2alpha.IAddFulfillmentPlacesMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + LROperation< + protos.google.cloud.retail.v2alpha.IAddFulfillmentPlacesResponse, + protos.google.cloud.retail.v2alpha.IAddFulfillmentPlacesMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'product': request.product ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + product: request.product ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IAddFulfillmentPlacesResponse, + protos.google.cloud.retail.v2alpha.IAddFulfillmentPlacesMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, rawResponse, _) => { this._log.info('addFulfillmentPlaces response %j', rawResponse); callback!(error, response, rawResponse, _); // We verified callback above. } : undefined; this._log.info('addFulfillmentPlaces request %j', request); - return this.innerApiCalls.addFulfillmentPlaces(request, options, wrappedCallback) - ?.then(([response, rawResponse, _]: [ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]) => { - this._log.info('addFulfillmentPlaces response %j', rawResponse); - return [response, rawResponse, _]; - }); + return this.innerApiCalls + .addFulfillmentPlaces(request, options, wrappedCallback) + ?.then( + ([response, rawResponse, _]: [ + LROperation< + protos.google.cloud.retail.v2alpha.IAddFulfillmentPlacesResponse, + protos.google.cloud.retail.v2alpha.IAddFulfillmentPlacesMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ]) => { + this._log.info('addFulfillmentPlaces response %j', rawResponse); + return [response, rawResponse, _]; + }, + ); } -/** - * Check the status of the long running operation returned by `addFulfillmentPlaces()`. - * @param {String} name - * The operation name that will be passed. - * @returns {Promise} - The promise which resolves to an object. - * The decoded operation object has result and metadata field to get information from. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/product_service.add_fulfillment_places.js - * region_tag:retail_v2alpha_generated_ProductService_AddFulfillmentPlaces_async - */ - async checkAddFulfillmentPlacesProgress(name: string): Promise>{ + /** + * Check the status of the long running operation returned by `addFulfillmentPlaces()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/product_service.add_fulfillment_places.js + * region_tag:retail_v2alpha_generated_ProductService_AddFulfillmentPlaces_async + */ + async checkAddFulfillmentPlacesProgress( + name: string, + ): Promise< + LROperation< + protos.google.cloud.retail.v2alpha.AddFulfillmentPlacesResponse, + protos.google.cloud.retail.v2alpha.AddFulfillmentPlacesMetadata + > + > { this._log.info('addFulfillmentPlaces long-running'); - const request = new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest({name}); + const request = + new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( + { name }, + ); const [operation] = await this.operationsClient.getOperation(request); - const decodeOperation = new this._gaxModule.Operation(operation, this.descriptors.longrunning.addFulfillmentPlaces, this._gaxModule.createDefaultBackoffSettings()); - return decodeOperation as LROperation; + const decodeOperation = new this._gaxModule.Operation( + operation, + this.descriptors.longrunning.addFulfillmentPlaces, + this._gaxModule.createDefaultBackoffSettings(), + ); + return decodeOperation as LROperation< + protos.google.cloud.retail.v2alpha.AddFulfillmentPlacesResponse, + protos.google.cloud.retail.v2alpha.AddFulfillmentPlacesMetadata + >; } -/** - * We recommend that you use the - * {@link protos.google.cloud.retail.v2alpha.ProductService.RemoveLocalInventories|ProductService.RemoveLocalInventories} - * method instead of the - * {@link protos.google.cloud.retail.v2alpha.ProductService.RemoveFulfillmentPlaces|ProductService.RemoveFulfillmentPlaces} - * method. - * {@link protos.google.cloud.retail.v2alpha.ProductService.RemoveLocalInventories|ProductService.RemoveLocalInventories} - * achieves the same results but provides more fine-grained control over - * ingesting local inventory data. - * - * Incrementally removes place IDs from a - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.place_ids|Product.fulfillment_info.place_ids}. - * - * This process is asynchronous and does not require the - * {@link protos.google.cloud.retail.v2alpha.Product|Product} to exist before updating - * fulfillment information. If the request is valid, the update will be - * enqueued and processed downstream. As a consequence, when a response is - * returned, the removed place IDs are not immediately manifested in the - * {@link protos.google.cloud.retail.v2alpha.Product|Product} queried by - * {@link protos.google.cloud.retail.v2alpha.ProductService.GetProduct|ProductService.GetProduct} - * or - * {@link protos.google.cloud.retail.v2alpha.ProductService.ListProducts|ProductService.ListProducts}. - * - * The returned {@link protos.google.longrunning.Operation|Operation}s will be obsolete - * after 1 day, and {@link protos.google.longrunning.Operations.GetOperation|GetOperation} - * API will return NOT_FOUND afterwards. - * - * If conflicting updates are issued, the - * {@link protos.google.longrunning.Operation|Operation}s associated with the stale - * updates will not be marked as {@link protos.google.longrunning.Operation.done|done} - * until being obsolete. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.product - * Required. Full resource name of - * {@link protos.google.cloud.retail.v2alpha.Product|Product}, such as - * `projects/* /locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id`. - * - * If the caller does not have permission to access the - * {@link protos.google.cloud.retail.v2alpha.Product|Product}, regardless of whether or - * not it exists, a PERMISSION_DENIED error is returned. - * @param {string} request.type - * Required. The fulfillment type, including commonly used types (such as - * pickup in store and same day delivery), and custom types. - * - * Supported values: - * - * * "pickup-in-store" - * * "ship-to-store" - * * "same-day-delivery" - * * "next-day-delivery" - * * "custom-type-1" - * * "custom-type-2" - * * "custom-type-3" - * * "custom-type-4" - * * "custom-type-5" - * - * If this field is set to an invalid value other than these, an - * INVALID_ARGUMENT error is returned. - * - * This field directly corresponds to - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.type|Product.fulfillment_info.type}. - * @param {string[]} request.placeIds - * Required. The IDs for this - * {@link protos.google.cloud.retail.v2alpha.RemoveFulfillmentPlacesRequest.type|type}, - * such as the store IDs for "pickup-in-store" or the region IDs for - * "same-day-delivery", to be removed for this - * {@link protos.google.cloud.retail.v2alpha.RemoveFulfillmentPlacesRequest.type|type}. - * - * At least 1 value is required, and a maximum of 2000 values are allowed. - * Each value must be a string with a length limit of 10 characters, matching - * the pattern `[a-zA-Z0-9_-]+`, such as "store1" or "REGION-2". Otherwise, an - * INVALID_ARGUMENT error is returned. - * @param {google.protobuf.Timestamp} request.removeTime - * The time when the fulfillment updates are issued, used to prevent - * out-of-order updates on fulfillment information. If not provided, the - * internal system time will be used. - * @param {boolean} request.allowMissing - * If set to true, and the {@link protos.google.cloud.retail.v2alpha.Product|Product} is - * not found, the fulfillment information will still be processed and retained - * for at most 1 day and processed once the - * {@link protos.google.cloud.retail.v2alpha.Product|Product} is created. If set to false, - * a NOT_FOUND error is returned if the - * {@link protos.google.cloud.retail.v2alpha.Product|Product} is not found. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing - * a long running operation. Its `promise()` method returns a promise - * you can `await` for. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/product_service.remove_fulfillment_places.js - * region_tag:retail_v2alpha_generated_ProductService_RemoveFulfillmentPlaces_async - */ + /** + * We recommend that you use the + * {@link protos.google.cloud.retail.v2alpha.ProductService.RemoveLocalInventories|ProductService.RemoveLocalInventories} + * method instead of the + * {@link protos.google.cloud.retail.v2alpha.ProductService.RemoveFulfillmentPlaces|ProductService.RemoveFulfillmentPlaces} + * method. + * {@link protos.google.cloud.retail.v2alpha.ProductService.RemoveLocalInventories|ProductService.RemoveLocalInventories} + * achieves the same results but provides more fine-grained control over + * ingesting local inventory data. + * + * Incrementally removes place IDs from a + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.place_ids|Product.fulfillment_info.place_ids}. + * + * This process is asynchronous and does not require the + * {@link protos.google.cloud.retail.v2alpha.Product|Product} to exist before updating + * fulfillment information. If the request is valid, the update will be + * enqueued and processed downstream. As a consequence, when a response is + * returned, the removed place IDs are not immediately manifested in the + * {@link protos.google.cloud.retail.v2alpha.Product|Product} queried by + * {@link protos.google.cloud.retail.v2alpha.ProductService.GetProduct|ProductService.GetProduct} + * or + * {@link protos.google.cloud.retail.v2alpha.ProductService.ListProducts|ProductService.ListProducts}. + * + * The returned {@link protos.google.longrunning.Operation|Operation}s will be obsolete + * after 1 day, and {@link protos.google.longrunning.Operations.GetOperation|GetOperation} + * API will return NOT_FOUND afterwards. + * + * If conflicting updates are issued, the + * {@link protos.google.longrunning.Operation|Operation}s associated with the stale + * updates will not be marked as {@link protos.google.longrunning.Operation.done|done} + * until being obsolete. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.product + * Required. Full resource name of + * {@link protos.google.cloud.retail.v2alpha.Product|Product}, such as + * `projects/* /locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id`. + * + * If the caller does not have permission to access the + * {@link protos.google.cloud.retail.v2alpha.Product|Product}, regardless of whether or + * not it exists, a PERMISSION_DENIED error is returned. + * @param {string} request.type + * Required. The fulfillment type, including commonly used types (such as + * pickup in store and same day delivery), and custom types. + * + * Supported values: + * + * * "pickup-in-store" + * * "ship-to-store" + * * "same-day-delivery" + * * "next-day-delivery" + * * "custom-type-1" + * * "custom-type-2" + * * "custom-type-3" + * * "custom-type-4" + * * "custom-type-5" + * + * If this field is set to an invalid value other than these, an + * INVALID_ARGUMENT error is returned. + * + * This field directly corresponds to + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.type|Product.fulfillment_info.type}. + * @param {string[]} request.placeIds + * Required. The IDs for this + * {@link protos.google.cloud.retail.v2alpha.RemoveFulfillmentPlacesRequest.type|type}, + * such as the store IDs for "pickup-in-store" or the region IDs for + * "same-day-delivery", to be removed for this + * {@link protos.google.cloud.retail.v2alpha.RemoveFulfillmentPlacesRequest.type|type}. + * + * At least 1 value is required, and a maximum of 2000 values are allowed. + * Each value must be a string with a length limit of 10 characters, matching + * the pattern `[a-zA-Z0-9_-]+`, such as "store1" or "REGION-2". Otherwise, an + * INVALID_ARGUMENT error is returned. + * @param {google.protobuf.Timestamp} request.removeTime + * The time when the fulfillment updates are issued, used to prevent + * out-of-order updates on fulfillment information. If not provided, the + * internal system time will be used. + * @param {boolean} request.allowMissing + * If set to true, and the {@link protos.google.cloud.retail.v2alpha.Product|Product} is + * not found, the fulfillment information will still be processed and retained + * for at most 1 day and processed once the + * {@link protos.google.cloud.retail.v2alpha.Product|Product} is created. If set to false, + * a NOT_FOUND error is returned if the + * {@link protos.google.cloud.retail.v2alpha.Product|Product} is not found. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/product_service.remove_fulfillment_places.js + * region_tag:retail_v2alpha_generated_ProductService_RemoveFulfillmentPlaces_async + */ removeFulfillmentPlaces( - request?: protos.google.cloud.retail.v2alpha.IRemoveFulfillmentPlacesRequest, - options?: CallOptions): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.IRemoveFulfillmentPlacesRequest, + options?: CallOptions, + ): Promise< + [ + LROperation< + protos.google.cloud.retail.v2alpha.IRemoveFulfillmentPlacesResponse, + protos.google.cloud.retail.v2alpha.IRemoveFulfillmentPlacesMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; removeFulfillmentPlaces( - request: protos.google.cloud.retail.v2alpha.IRemoveFulfillmentPlacesRequest, - options: CallOptions, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IRemoveFulfillmentPlacesRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IRemoveFulfillmentPlacesResponse, + protos.google.cloud.retail.v2alpha.IRemoveFulfillmentPlacesMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; removeFulfillmentPlaces( - request: protos.google.cloud.retail.v2alpha.IRemoveFulfillmentPlacesRequest, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IRemoveFulfillmentPlacesRequest, + callback: Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IRemoveFulfillmentPlacesResponse, + protos.google.cloud.retail.v2alpha.IRemoveFulfillmentPlacesMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; removeFulfillmentPlaces( - request?: protos.google.cloud.retail.v2alpha.IRemoveFulfillmentPlacesRequest, - optionsOrCallback?: CallOptions|Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>, - callback?: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>|void { + request?: protos.google.cloud.retail.v2alpha.IRemoveFulfillmentPlacesRequest, + optionsOrCallback?: + | CallOptions + | Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IRemoveFulfillmentPlacesResponse, + protos.google.cloud.retail.v2alpha.IRemoveFulfillmentPlacesMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + callback?: Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IRemoveFulfillmentPlacesResponse, + protos.google.cloud.retail.v2alpha.IRemoveFulfillmentPlacesMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + LROperation< + protos.google.cloud.retail.v2alpha.IRemoveFulfillmentPlacesResponse, + protos.google.cloud.retail.v2alpha.IRemoveFulfillmentPlacesMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'product': request.product ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + product: request.product ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IRemoveFulfillmentPlacesResponse, + protos.google.cloud.retail.v2alpha.IRemoveFulfillmentPlacesMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, rawResponse, _) => { this._log.info('removeFulfillmentPlaces response %j', rawResponse); callback!(error, response, rawResponse, _); // We verified callback above. } : undefined; this._log.info('removeFulfillmentPlaces request %j', request); - return this.innerApiCalls.removeFulfillmentPlaces(request, options, wrappedCallback) - ?.then(([response, rawResponse, _]: [ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]) => { - this._log.info('removeFulfillmentPlaces response %j', rawResponse); - return [response, rawResponse, _]; - }); + return this.innerApiCalls + .removeFulfillmentPlaces(request, options, wrappedCallback) + ?.then( + ([response, rawResponse, _]: [ + LROperation< + protos.google.cloud.retail.v2alpha.IRemoveFulfillmentPlacesResponse, + protos.google.cloud.retail.v2alpha.IRemoveFulfillmentPlacesMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ]) => { + this._log.info('removeFulfillmentPlaces response %j', rawResponse); + return [response, rawResponse, _]; + }, + ); } -/** - * Check the status of the long running operation returned by `removeFulfillmentPlaces()`. - * @param {String} name - * The operation name that will be passed. - * @returns {Promise} - The promise which resolves to an object. - * The decoded operation object has result and metadata field to get information from. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/product_service.remove_fulfillment_places.js - * region_tag:retail_v2alpha_generated_ProductService_RemoveFulfillmentPlaces_async - */ - async checkRemoveFulfillmentPlacesProgress(name: string): Promise>{ + /** + * Check the status of the long running operation returned by `removeFulfillmentPlaces()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/product_service.remove_fulfillment_places.js + * region_tag:retail_v2alpha_generated_ProductService_RemoveFulfillmentPlaces_async + */ + async checkRemoveFulfillmentPlacesProgress( + name: string, + ): Promise< + LROperation< + protos.google.cloud.retail.v2alpha.RemoveFulfillmentPlacesResponse, + protos.google.cloud.retail.v2alpha.RemoveFulfillmentPlacesMetadata + > + > { this._log.info('removeFulfillmentPlaces long-running'); - const request = new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest({name}); + const request = + new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( + { name }, + ); const [operation] = await this.operationsClient.getOperation(request); - const decodeOperation = new this._gaxModule.Operation(operation, this.descriptors.longrunning.removeFulfillmentPlaces, this._gaxModule.createDefaultBackoffSettings()); - return decodeOperation as LROperation; + const decodeOperation = new this._gaxModule.Operation( + operation, + this.descriptors.longrunning.removeFulfillmentPlaces, + this._gaxModule.createDefaultBackoffSettings(), + ); + return decodeOperation as LROperation< + protos.google.cloud.retail.v2alpha.RemoveFulfillmentPlacesResponse, + protos.google.cloud.retail.v2alpha.RemoveFulfillmentPlacesMetadata + >; } -/** - * Updates local inventory information for a - * {@link protos.google.cloud.retail.v2alpha.Product|Product} at a list of places, while - * respecting the last update timestamps of each inventory field. - * - * This process is asynchronous and does not require the - * {@link protos.google.cloud.retail.v2alpha.Product|Product} to exist before updating - * inventory information. If the request is valid, the update will be enqueued - * and processed downstream. As a consequence, when a response is returned, - * updates are not immediately manifested in the - * {@link protos.google.cloud.retail.v2alpha.Product|Product} queried by - * {@link protos.google.cloud.retail.v2alpha.ProductService.GetProduct|ProductService.GetProduct} - * or - * {@link protos.google.cloud.retail.v2alpha.ProductService.ListProducts|ProductService.ListProducts}. - * - * Local inventory information can only be modified using this method. - * {@link protos.google.cloud.retail.v2alpha.ProductService.CreateProduct|ProductService.CreateProduct} - * and - * {@link protos.google.cloud.retail.v2alpha.ProductService.UpdateProduct|ProductService.UpdateProduct} - * has no effect on local inventories. - * - * The returned {@link protos.google.longrunning.Operation|Operation}s will be obsolete - * after 1 day, and {@link protos.google.longrunning.Operations.GetOperation|GetOperation} - * API will return NOT_FOUND afterwards. - * - * If conflicting updates are issued, the - * {@link protos.google.longrunning.Operation|Operation}s associated with the stale - * updates will not be marked as {@link protos.google.longrunning.Operation.done|done} - * until being obsolete. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.product - * Required. Full resource name of - * {@link protos.google.cloud.retail.v2alpha.Product|Product}, such as - * `projects/* /locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id`. - * - * If the caller does not have permission to access the - * {@link protos.google.cloud.retail.v2alpha.Product|Product}, regardless of whether or - * not it exists, a PERMISSION_DENIED error is returned. - * @param {number[]} request.localInventories - * Required. A list of inventory information at difference places. Each place - * is identified by its place ID. At most 3000 inventories are allowed per - * request. - * @param {google.protobuf.FieldMask} request.addMask - * Indicates which inventory fields in the provided list of - * {@link protos.google.cloud.retail.v2alpha.LocalInventory|LocalInventory} to update. The - * field is updated to the provided value. - * - * If a field is set while the place does not have a previous local inventory, - * the local inventory at that store is created. - * - * If a field is set while the value of that field is not provided, the - * original field value, if it exists, is deleted. - * - * If the mask is not set or set with empty paths, all inventory fields will - * be updated. - * - * If an unsupported or unknown field is provided, an INVALID_ARGUMENT error - * is returned and the entire update will be ignored. - * @param {google.protobuf.Timestamp} request.addTime - * The time when the inventory updates are issued. Used to prevent - * out-of-order updates on local inventory fields. If not provided, the - * internal system time will be used. - * @param {boolean} request.allowMissing - * If set to true, and the {@link protos.google.cloud.retail.v2alpha.Product|Product} is - * not found, the local inventory will still be processed and retained for at - * most 1 day and processed once the - * {@link protos.google.cloud.retail.v2alpha.Product|Product} is created. If set to false, - * a NOT_FOUND error is returned if the - * {@link protos.google.cloud.retail.v2alpha.Product|Product} is not found. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing - * a long running operation. Its `promise()` method returns a promise - * you can `await` for. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/product_service.add_local_inventories.js - * region_tag:retail_v2alpha_generated_ProductService_AddLocalInventories_async - */ + /** + * Updates local inventory information for a + * {@link protos.google.cloud.retail.v2alpha.Product|Product} at a list of places, while + * respecting the last update timestamps of each inventory field. + * + * This process is asynchronous and does not require the + * {@link protos.google.cloud.retail.v2alpha.Product|Product} to exist before updating + * inventory information. If the request is valid, the update will be enqueued + * and processed downstream. As a consequence, when a response is returned, + * updates are not immediately manifested in the + * {@link protos.google.cloud.retail.v2alpha.Product|Product} queried by + * {@link protos.google.cloud.retail.v2alpha.ProductService.GetProduct|ProductService.GetProduct} + * or + * {@link protos.google.cloud.retail.v2alpha.ProductService.ListProducts|ProductService.ListProducts}. + * + * Local inventory information can only be modified using this method. + * {@link protos.google.cloud.retail.v2alpha.ProductService.CreateProduct|ProductService.CreateProduct} + * and + * {@link protos.google.cloud.retail.v2alpha.ProductService.UpdateProduct|ProductService.UpdateProduct} + * has no effect on local inventories. + * + * The returned {@link protos.google.longrunning.Operation|Operation}s will be obsolete + * after 1 day, and {@link protos.google.longrunning.Operations.GetOperation|GetOperation} + * API will return NOT_FOUND afterwards. + * + * If conflicting updates are issued, the + * {@link protos.google.longrunning.Operation|Operation}s associated with the stale + * updates will not be marked as {@link protos.google.longrunning.Operation.done|done} + * until being obsolete. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.product + * Required. Full resource name of + * {@link protos.google.cloud.retail.v2alpha.Product|Product}, such as + * `projects/* /locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id`. + * + * If the caller does not have permission to access the + * {@link protos.google.cloud.retail.v2alpha.Product|Product}, regardless of whether or + * not it exists, a PERMISSION_DENIED error is returned. + * @param {number[]} request.localInventories + * Required. A list of inventory information at difference places. Each place + * is identified by its place ID. At most 3000 inventories are allowed per + * request. + * @param {google.protobuf.FieldMask} request.addMask + * Indicates which inventory fields in the provided list of + * {@link protos.google.cloud.retail.v2alpha.LocalInventory|LocalInventory} to update. The + * field is updated to the provided value. + * + * If a field is set while the place does not have a previous local inventory, + * the local inventory at that store is created. + * + * If a field is set while the value of that field is not provided, the + * original field value, if it exists, is deleted. + * + * If the mask is not set or set with empty paths, all inventory fields will + * be updated. + * + * If an unsupported or unknown field is provided, an INVALID_ARGUMENT error + * is returned and the entire update will be ignored. + * @param {google.protobuf.Timestamp} request.addTime + * The time when the inventory updates are issued. Used to prevent + * out-of-order updates on local inventory fields. If not provided, the + * internal system time will be used. + * @param {boolean} request.allowMissing + * If set to true, and the {@link protos.google.cloud.retail.v2alpha.Product|Product} is + * not found, the local inventory will still be processed and retained for at + * most 1 day and processed once the + * {@link protos.google.cloud.retail.v2alpha.Product|Product} is created. If set to false, + * a NOT_FOUND error is returned if the + * {@link protos.google.cloud.retail.v2alpha.Product|Product} is not found. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/product_service.add_local_inventories.js + * region_tag:retail_v2alpha_generated_ProductService_AddLocalInventories_async + */ addLocalInventories( - request?: protos.google.cloud.retail.v2alpha.IAddLocalInventoriesRequest, - options?: CallOptions): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.IAddLocalInventoriesRequest, + options?: CallOptions, + ): Promise< + [ + LROperation< + protos.google.cloud.retail.v2alpha.IAddLocalInventoriesResponse, + protos.google.cloud.retail.v2alpha.IAddLocalInventoriesMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; addLocalInventories( - request: protos.google.cloud.retail.v2alpha.IAddLocalInventoriesRequest, - options: CallOptions, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IAddLocalInventoriesRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IAddLocalInventoriesResponse, + protos.google.cloud.retail.v2alpha.IAddLocalInventoriesMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; addLocalInventories( - request: protos.google.cloud.retail.v2alpha.IAddLocalInventoriesRequest, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IAddLocalInventoriesRequest, + callback: Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IAddLocalInventoriesResponse, + protos.google.cloud.retail.v2alpha.IAddLocalInventoriesMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; addLocalInventories( - request?: protos.google.cloud.retail.v2alpha.IAddLocalInventoriesRequest, - optionsOrCallback?: CallOptions|Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>, - callback?: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>|void { + request?: protos.google.cloud.retail.v2alpha.IAddLocalInventoriesRequest, + optionsOrCallback?: + | CallOptions + | Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IAddLocalInventoriesResponse, + protos.google.cloud.retail.v2alpha.IAddLocalInventoriesMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + callback?: Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IAddLocalInventoriesResponse, + protos.google.cloud.retail.v2alpha.IAddLocalInventoriesMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + LROperation< + protos.google.cloud.retail.v2alpha.IAddLocalInventoriesResponse, + protos.google.cloud.retail.v2alpha.IAddLocalInventoriesMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'product': request.product ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + product: request.product ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IAddLocalInventoriesResponse, + protos.google.cloud.retail.v2alpha.IAddLocalInventoriesMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, rawResponse, _) => { this._log.info('addLocalInventories response %j', rawResponse); callback!(error, response, rawResponse, _); // We verified callback above. } : undefined; this._log.info('addLocalInventories request %j', request); - return this.innerApiCalls.addLocalInventories(request, options, wrappedCallback) - ?.then(([response, rawResponse, _]: [ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]) => { - this._log.info('addLocalInventories response %j', rawResponse); - return [response, rawResponse, _]; - }); + return this.innerApiCalls + .addLocalInventories(request, options, wrappedCallback) + ?.then( + ([response, rawResponse, _]: [ + LROperation< + protos.google.cloud.retail.v2alpha.IAddLocalInventoriesResponse, + protos.google.cloud.retail.v2alpha.IAddLocalInventoriesMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ]) => { + this._log.info('addLocalInventories response %j', rawResponse); + return [response, rawResponse, _]; + }, + ); } -/** - * Check the status of the long running operation returned by `addLocalInventories()`. - * @param {String} name - * The operation name that will be passed. - * @returns {Promise} - The promise which resolves to an object. - * The decoded operation object has result and metadata field to get information from. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/product_service.add_local_inventories.js - * region_tag:retail_v2alpha_generated_ProductService_AddLocalInventories_async - */ - async checkAddLocalInventoriesProgress(name: string): Promise>{ + /** + * Check the status of the long running operation returned by `addLocalInventories()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/product_service.add_local_inventories.js + * region_tag:retail_v2alpha_generated_ProductService_AddLocalInventories_async + */ + async checkAddLocalInventoriesProgress( + name: string, + ): Promise< + LROperation< + protos.google.cloud.retail.v2alpha.AddLocalInventoriesResponse, + protos.google.cloud.retail.v2alpha.AddLocalInventoriesMetadata + > + > { this._log.info('addLocalInventories long-running'); - const request = new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest({name}); + const request = + new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( + { name }, + ); const [operation] = await this.operationsClient.getOperation(request); - const decodeOperation = new this._gaxModule.Operation(operation, this.descriptors.longrunning.addLocalInventories, this._gaxModule.createDefaultBackoffSettings()); - return decodeOperation as LROperation; + const decodeOperation = new this._gaxModule.Operation( + operation, + this.descriptors.longrunning.addLocalInventories, + this._gaxModule.createDefaultBackoffSettings(), + ); + return decodeOperation as LROperation< + protos.google.cloud.retail.v2alpha.AddLocalInventoriesResponse, + protos.google.cloud.retail.v2alpha.AddLocalInventoriesMetadata + >; } -/** - * Remove local inventory information for a - * {@link protos.google.cloud.retail.v2alpha.Product|Product} at a list of places at a - * removal timestamp. - * - * This process is asynchronous. If the request is valid, the removal will be - * enqueued and processed downstream. As a consequence, when a response is - * returned, removals are not immediately manifested in the - * {@link protos.google.cloud.retail.v2alpha.Product|Product} queried by - * {@link protos.google.cloud.retail.v2alpha.ProductService.GetProduct|ProductService.GetProduct} - * or - * {@link protos.google.cloud.retail.v2alpha.ProductService.ListProducts|ProductService.ListProducts}. - * - * Local inventory information can only be removed using this method. - * {@link protos.google.cloud.retail.v2alpha.ProductService.CreateProduct|ProductService.CreateProduct} - * and - * {@link protos.google.cloud.retail.v2alpha.ProductService.UpdateProduct|ProductService.UpdateProduct} - * has no effect on local inventories. - * - * The returned {@link protos.google.longrunning.Operation|Operation}s will be obsolete - * after 1 day, and {@link protos.google.longrunning.Operations.GetOperation|GetOperation} - * API will return NOT_FOUND afterwards. - * - * If conflicting updates are issued, the - * {@link protos.google.longrunning.Operation|Operation}s associated with the stale - * updates will not be marked as {@link protos.google.longrunning.Operation.done|done} - * until being obsolete. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.product - * Required. Full resource name of - * {@link protos.google.cloud.retail.v2alpha.Product|Product}, such as - * `projects/* /locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id`. - * - * If the caller does not have permission to access the - * {@link protos.google.cloud.retail.v2alpha.Product|Product}, regardless of whether or - * not it exists, a PERMISSION_DENIED error is returned. - * @param {string[]} request.placeIds - * Required. A list of place IDs to have their inventory deleted. - * At most 3000 place IDs are allowed per request. - * @param {google.protobuf.Timestamp} request.removeTime - * The time when the inventory deletions are issued. Used to prevent - * out-of-order updates and deletions on local inventory fields. If not - * provided, the internal system time will be used. - * @param {boolean} request.allowMissing - * If set to true, and the {@link protos.google.cloud.retail.v2alpha.Product|Product} is - * not found, the local inventory removal request will still be processed and - * retained for at most 1 day and processed once the - * {@link protos.google.cloud.retail.v2alpha.Product|Product} is created. If set to false, - * a NOT_FOUND error is returned if the - * {@link protos.google.cloud.retail.v2alpha.Product|Product} is not found. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing - * a long running operation. Its `promise()` method returns a promise - * you can `await` for. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/product_service.remove_local_inventories.js - * region_tag:retail_v2alpha_generated_ProductService_RemoveLocalInventories_async - */ + /** + * Remove local inventory information for a + * {@link protos.google.cloud.retail.v2alpha.Product|Product} at a list of places at a + * removal timestamp. + * + * This process is asynchronous. If the request is valid, the removal will be + * enqueued and processed downstream. As a consequence, when a response is + * returned, removals are not immediately manifested in the + * {@link protos.google.cloud.retail.v2alpha.Product|Product} queried by + * {@link protos.google.cloud.retail.v2alpha.ProductService.GetProduct|ProductService.GetProduct} + * or + * {@link protos.google.cloud.retail.v2alpha.ProductService.ListProducts|ProductService.ListProducts}. + * + * Local inventory information can only be removed using this method. + * {@link protos.google.cloud.retail.v2alpha.ProductService.CreateProduct|ProductService.CreateProduct} + * and + * {@link protos.google.cloud.retail.v2alpha.ProductService.UpdateProduct|ProductService.UpdateProduct} + * has no effect on local inventories. + * + * The returned {@link protos.google.longrunning.Operation|Operation}s will be obsolete + * after 1 day, and {@link protos.google.longrunning.Operations.GetOperation|GetOperation} + * API will return NOT_FOUND afterwards. + * + * If conflicting updates are issued, the + * {@link protos.google.longrunning.Operation|Operation}s associated with the stale + * updates will not be marked as {@link protos.google.longrunning.Operation.done|done} + * until being obsolete. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.product + * Required. Full resource name of + * {@link protos.google.cloud.retail.v2alpha.Product|Product}, such as + * `projects/* /locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id`. + * + * If the caller does not have permission to access the + * {@link protos.google.cloud.retail.v2alpha.Product|Product}, regardless of whether or + * not it exists, a PERMISSION_DENIED error is returned. + * @param {string[]} request.placeIds + * Required. A list of place IDs to have their inventory deleted. + * At most 3000 place IDs are allowed per request. + * @param {google.protobuf.Timestamp} request.removeTime + * The time when the inventory deletions are issued. Used to prevent + * out-of-order updates and deletions on local inventory fields. If not + * provided, the internal system time will be used. + * @param {boolean} request.allowMissing + * If set to true, and the {@link protos.google.cloud.retail.v2alpha.Product|Product} is + * not found, the local inventory removal request will still be processed and + * retained for at most 1 day and processed once the + * {@link protos.google.cloud.retail.v2alpha.Product|Product} is created. If set to false, + * a NOT_FOUND error is returned if the + * {@link protos.google.cloud.retail.v2alpha.Product|Product} is not found. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/product_service.remove_local_inventories.js + * region_tag:retail_v2alpha_generated_ProductService_RemoveLocalInventories_async + */ removeLocalInventories( - request?: protos.google.cloud.retail.v2alpha.IRemoveLocalInventoriesRequest, - options?: CallOptions): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.IRemoveLocalInventoriesRequest, + options?: CallOptions, + ): Promise< + [ + LROperation< + protos.google.cloud.retail.v2alpha.IRemoveLocalInventoriesResponse, + protos.google.cloud.retail.v2alpha.IRemoveLocalInventoriesMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; removeLocalInventories( - request: protos.google.cloud.retail.v2alpha.IRemoveLocalInventoriesRequest, - options: CallOptions, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IRemoveLocalInventoriesRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IRemoveLocalInventoriesResponse, + protos.google.cloud.retail.v2alpha.IRemoveLocalInventoriesMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; removeLocalInventories( - request: protos.google.cloud.retail.v2alpha.IRemoveLocalInventoriesRequest, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IRemoveLocalInventoriesRequest, + callback: Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IRemoveLocalInventoriesResponse, + protos.google.cloud.retail.v2alpha.IRemoveLocalInventoriesMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; removeLocalInventories( - request?: protos.google.cloud.retail.v2alpha.IRemoveLocalInventoriesRequest, - optionsOrCallback?: CallOptions|Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>, - callback?: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>|void { + request?: protos.google.cloud.retail.v2alpha.IRemoveLocalInventoriesRequest, + optionsOrCallback?: + | CallOptions + | Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IRemoveLocalInventoriesResponse, + protos.google.cloud.retail.v2alpha.IRemoveLocalInventoriesMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + callback?: Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IRemoveLocalInventoriesResponse, + protos.google.cloud.retail.v2alpha.IRemoveLocalInventoriesMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + LROperation< + protos.google.cloud.retail.v2alpha.IRemoveLocalInventoriesResponse, + protos.google.cloud.retail.v2alpha.IRemoveLocalInventoriesMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'product': request.product ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + product: request.product ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IRemoveLocalInventoriesResponse, + protos.google.cloud.retail.v2alpha.IRemoveLocalInventoriesMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, rawResponse, _) => { this._log.info('removeLocalInventories response %j', rawResponse); callback!(error, response, rawResponse, _); // We verified callback above. } : undefined; this._log.info('removeLocalInventories request %j', request); - return this.innerApiCalls.removeLocalInventories(request, options, wrappedCallback) - ?.then(([response, rawResponse, _]: [ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]) => { - this._log.info('removeLocalInventories response %j', rawResponse); - return [response, rawResponse, _]; - }); + return this.innerApiCalls + .removeLocalInventories(request, options, wrappedCallback) + ?.then( + ([response, rawResponse, _]: [ + LROperation< + protos.google.cloud.retail.v2alpha.IRemoveLocalInventoriesResponse, + protos.google.cloud.retail.v2alpha.IRemoveLocalInventoriesMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ]) => { + this._log.info('removeLocalInventories response %j', rawResponse); + return [response, rawResponse, _]; + }, + ); } -/** - * Check the status of the long running operation returned by `removeLocalInventories()`. - * @param {String} name - * The operation name that will be passed. - * @returns {Promise} - The promise which resolves to an object. - * The decoded operation object has result and metadata field to get information from. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/product_service.remove_local_inventories.js - * region_tag:retail_v2alpha_generated_ProductService_RemoveLocalInventories_async - */ - async checkRemoveLocalInventoriesProgress(name: string): Promise>{ + /** + * Check the status of the long running operation returned by `removeLocalInventories()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/product_service.remove_local_inventories.js + * region_tag:retail_v2alpha_generated_ProductService_RemoveLocalInventories_async + */ + async checkRemoveLocalInventoriesProgress( + name: string, + ): Promise< + LROperation< + protos.google.cloud.retail.v2alpha.RemoveLocalInventoriesResponse, + protos.google.cloud.retail.v2alpha.RemoveLocalInventoriesMetadata + > + > { this._log.info('removeLocalInventories long-running'); - const request = new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest({name}); + const request = + new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( + { name }, + ); const [operation] = await this.operationsClient.getOperation(request); - const decodeOperation = new this._gaxModule.Operation(operation, this.descriptors.longrunning.removeLocalInventories, this._gaxModule.createDefaultBackoffSettings()); - return decodeOperation as LROperation; - } - /** - * Gets a list of {@link protos.google.cloud.retail.v2alpha.Product|Product}s. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent branch resource name, such as - * `projects/* /locations/global/catalogs/default_catalog/branches/0`. Use - * `default_branch` as the branch ID, to list products under the default - * branch. - * - * If the caller does not have permission to list - * {@link protos.google.cloud.retail.v2alpha.Product|Product}s under this branch, - * regardless of whether or not this branch exists, a PERMISSION_DENIED error - * is returned. - * @param {number} request.pageSize - * Maximum number of {@link protos.google.cloud.retail.v2alpha.Product|Product}s to - * return. If unspecified, defaults to 100. The maximum allowed value is 1000. - * Values above 1000 will be coerced to 1000. - * - * If this field is negative, an INVALID_ARGUMENT error is returned. - * @param {string} request.pageToken - * A page token - * {@link protos.google.cloud.retail.v2alpha.ListProductsResponse.next_page_token|ListProductsResponse.next_page_token}, - * received from a previous - * {@link protos.google.cloud.retail.v2alpha.ProductService.ListProducts|ProductService.ListProducts} - * call. Provide this to retrieve the subsequent page. - * - * When paginating, all other parameters provided to - * {@link protos.google.cloud.retail.v2alpha.ProductService.ListProducts|ProductService.ListProducts} - * must match the call that provided the page token. Otherwise, an - * INVALID_ARGUMENT error is returned. - * @param {string} request.filter - * A filter to apply on the list results. Supported features: - * - * * List all the products under the parent branch if - * {@link protos.google.cloud.retail.v2alpha.ListProductsRequest.filter|filter} is unset. - * * List - * {@link protos.google.cloud.retail.v2alpha.Product.Type.VARIANT|Product.Type.VARIANT} - * {@link protos.google.cloud.retail.v2alpha.Product|Product}s sharing the same - * {@link protos.google.cloud.retail.v2alpha.Product.Type.PRIMARY|Product.Type.PRIMARY} - * {@link protos.google.cloud.retail.v2alpha.Product|Product}. For example: - * `primary_product_id = "some_product_id"` - * * List {@link protos.google.cloud.retail.v2alpha.Product|Product}s bundled in a - * {@link protos.google.cloud.retail.v2alpha.Product.Type.COLLECTION|Product.Type.COLLECTION} - * {@link protos.google.cloud.retail.v2alpha.Product|Product}. - * For example: - * `collection_product_id = "some_product_id"` - * * List {@link protos.google.cloud.retail.v2alpha.Product|Product}s with a partibular - * type. For example: - * `type = "PRIMARY"` - * `type = "VARIANT"` - * `type = "COLLECTION"` - * - * If the field is unrecognizable, an INVALID_ARGUMENT error is returned. - * - * If the specified - * {@link protos.google.cloud.retail.v2alpha.Product.Type.PRIMARY|Product.Type.PRIMARY} - * {@link protos.google.cloud.retail.v2alpha.Product|Product} or - * {@link protos.google.cloud.retail.v2alpha.Product.Type.COLLECTION|Product.Type.COLLECTION} - * {@link protos.google.cloud.retail.v2alpha.Product|Product} does not exist, a NOT_FOUND - * error is returned. - * @param {google.protobuf.FieldMask} request.readMask - * The fields of {@link protos.google.cloud.retail.v2alpha.Product|Product} to return in - * the responses. If not set or empty, the following fields are returned: - * - * * {@link protos.google.cloud.retail.v2alpha.Product.name|Product.name} - * * {@link protos.google.cloud.retail.v2alpha.Product.id|Product.id} - * * {@link protos.google.cloud.retail.v2alpha.Product.title|Product.title} - * * {@link protos.google.cloud.retail.v2alpha.Product.uri|Product.uri} - * * {@link protos.google.cloud.retail.v2alpha.Product.images|Product.images} - * * {@link protos.google.cloud.retail.v2alpha.Product.price_info|Product.price_info} - * * {@link protos.google.cloud.retail.v2alpha.Product.brands|Product.brands} - * - * If "*" is provided, all fields are returned. - * {@link protos.google.cloud.retail.v2alpha.Product.name|Product.name} is always returned - * no matter what mask is set. - * - * If an unsupported or unknown field is provided, an INVALID_ARGUMENT error - * is returned. - * @param {boolean} request.requireTotalSize - * If true and - * {@link protos.google.cloud.retail.v2alpha.ListProductsRequest.page_token|page_token} is - * empty, - * {@link protos.google.cloud.retail.v2alpha.ListProductsResponse.total_size|ListProductsResponse.total_size} - * is set to the total count of matched items irrespective of pagination. - * - * Notice that setting this field to true affects the performance. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.cloud.retail.v2alpha.Product|Product}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `listProductsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + const decodeOperation = new this._gaxModule.Operation( + operation, + this.descriptors.longrunning.removeLocalInventories, + this._gaxModule.createDefaultBackoffSettings(), + ); + return decodeOperation as LROperation< + protos.google.cloud.retail.v2alpha.RemoveLocalInventoriesResponse, + protos.google.cloud.retail.v2alpha.RemoveLocalInventoriesMetadata + >; + } + /** + * Gets a list of {@link protos.google.cloud.retail.v2alpha.Product|Product}s. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent branch resource name, such as + * `projects/* /locations/global/catalogs/default_catalog/branches/0`. Use + * `default_branch` as the branch ID, to list products under the default + * branch. + * + * If the caller does not have permission to list + * {@link protos.google.cloud.retail.v2alpha.Product|Product}s under this branch, + * regardless of whether or not this branch exists, a PERMISSION_DENIED error + * is returned. + * @param {number} request.pageSize + * Maximum number of {@link protos.google.cloud.retail.v2alpha.Product|Product}s to + * return. If unspecified, defaults to 100. The maximum allowed value is 1000. + * Values above 1000 will be coerced to 1000. + * + * If this field is negative, an INVALID_ARGUMENT error is returned. + * @param {string} request.pageToken + * A page token + * {@link protos.google.cloud.retail.v2alpha.ListProductsResponse.next_page_token|ListProductsResponse.next_page_token}, + * received from a previous + * {@link protos.google.cloud.retail.v2alpha.ProductService.ListProducts|ProductService.ListProducts} + * call. Provide this to retrieve the subsequent page. + * + * When paginating, all other parameters provided to + * {@link protos.google.cloud.retail.v2alpha.ProductService.ListProducts|ProductService.ListProducts} + * must match the call that provided the page token. Otherwise, an + * INVALID_ARGUMENT error is returned. + * @param {string} request.filter + * A filter to apply on the list results. Supported features: + * + * * List all the products under the parent branch if + * {@link protos.google.cloud.retail.v2alpha.ListProductsRequest.filter|filter} is unset. + * * List + * {@link protos.google.cloud.retail.v2alpha.Product.Type.VARIANT|Product.Type.VARIANT} + * {@link protos.google.cloud.retail.v2alpha.Product|Product}s sharing the same + * {@link protos.google.cloud.retail.v2alpha.Product.Type.PRIMARY|Product.Type.PRIMARY} + * {@link protos.google.cloud.retail.v2alpha.Product|Product}. For example: + * `primary_product_id = "some_product_id"` + * * List {@link protos.google.cloud.retail.v2alpha.Product|Product}s bundled in a + * {@link protos.google.cloud.retail.v2alpha.Product.Type.COLLECTION|Product.Type.COLLECTION} + * {@link protos.google.cloud.retail.v2alpha.Product|Product}. + * For example: + * `collection_product_id = "some_product_id"` + * * List {@link protos.google.cloud.retail.v2alpha.Product|Product}s with a partibular + * type. For example: + * `type = "PRIMARY"` + * `type = "VARIANT"` + * `type = "COLLECTION"` + * + * If the field is unrecognizable, an INVALID_ARGUMENT error is returned. + * + * If the specified + * {@link protos.google.cloud.retail.v2alpha.Product.Type.PRIMARY|Product.Type.PRIMARY} + * {@link protos.google.cloud.retail.v2alpha.Product|Product} or + * {@link protos.google.cloud.retail.v2alpha.Product.Type.COLLECTION|Product.Type.COLLECTION} + * {@link protos.google.cloud.retail.v2alpha.Product|Product} does not exist, a NOT_FOUND + * error is returned. + * @param {google.protobuf.FieldMask} request.readMask + * The fields of {@link protos.google.cloud.retail.v2alpha.Product|Product} to return in + * the responses. If not set or empty, the following fields are returned: + * + * * {@link protos.google.cloud.retail.v2alpha.Product.name|Product.name} + * * {@link protos.google.cloud.retail.v2alpha.Product.id|Product.id} + * * {@link protos.google.cloud.retail.v2alpha.Product.title|Product.title} + * * {@link protos.google.cloud.retail.v2alpha.Product.uri|Product.uri} + * * {@link protos.google.cloud.retail.v2alpha.Product.images|Product.images} + * * {@link protos.google.cloud.retail.v2alpha.Product.price_info|Product.price_info} + * * {@link protos.google.cloud.retail.v2alpha.Product.brands|Product.brands} + * + * If "*" is provided, all fields are returned. + * {@link protos.google.cloud.retail.v2alpha.Product.name|Product.name} is always returned + * no matter what mask is set. + * + * If an unsupported or unknown field is provided, an INVALID_ARGUMENT error + * is returned. + * @param {boolean} request.requireTotalSize + * If true and + * {@link protos.google.cloud.retail.v2alpha.ListProductsRequest.page_token|page_token} is + * empty, + * {@link protos.google.cloud.retail.v2alpha.ListProductsResponse.total_size|ListProductsResponse.total_size} + * is set to the total count of matched items irrespective of pagination. + * + * Notice that setting this field to true affects the performance. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.cloud.retail.v2alpha.Product|Product}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listProductsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listProducts( - request?: protos.google.cloud.retail.v2alpha.IListProductsRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.retail.v2alpha.IProduct[], - protos.google.cloud.retail.v2alpha.IListProductsRequest|null, - protos.google.cloud.retail.v2alpha.IListProductsResponse - ]>; + request?: protos.google.cloud.retail.v2alpha.IListProductsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IProduct[], + protos.google.cloud.retail.v2alpha.IListProductsRequest | null, + protos.google.cloud.retail.v2alpha.IListProductsResponse, + ] + >; listProducts( - request: protos.google.cloud.retail.v2alpha.IListProductsRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.cloud.retail.v2alpha.IListProductsRequest, - protos.google.cloud.retail.v2alpha.IListProductsResponse|null|undefined, - protos.google.cloud.retail.v2alpha.IProduct>): void; + request: protos.google.cloud.retail.v2alpha.IListProductsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.cloud.retail.v2alpha.IListProductsRequest, + | protos.google.cloud.retail.v2alpha.IListProductsResponse + | null + | undefined, + protos.google.cloud.retail.v2alpha.IProduct + >, + ): void; listProducts( - request: protos.google.cloud.retail.v2alpha.IListProductsRequest, - callback: PaginationCallback< - protos.google.cloud.retail.v2alpha.IListProductsRequest, - protos.google.cloud.retail.v2alpha.IListProductsResponse|null|undefined, - protos.google.cloud.retail.v2alpha.IProduct>): void; + request: protos.google.cloud.retail.v2alpha.IListProductsRequest, + callback: PaginationCallback< + protos.google.cloud.retail.v2alpha.IListProductsRequest, + | protos.google.cloud.retail.v2alpha.IListProductsResponse + | null + | undefined, + protos.google.cloud.retail.v2alpha.IProduct + >, + ): void; listProducts( - request?: protos.google.cloud.retail.v2alpha.IListProductsRequest, - optionsOrCallback?: CallOptions|PaginationCallback< + request?: protos.google.cloud.retail.v2alpha.IListProductsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.cloud.retail.v2alpha.IListProductsRequest, - protos.google.cloud.retail.v2alpha.IListProductsResponse|null|undefined, - protos.google.cloud.retail.v2alpha.IProduct>, - callback?: PaginationCallback< - protos.google.cloud.retail.v2alpha.IListProductsRequest, - protos.google.cloud.retail.v2alpha.IListProductsResponse|null|undefined, - protos.google.cloud.retail.v2alpha.IProduct>): - Promise<[ - protos.google.cloud.retail.v2alpha.IProduct[], - protos.google.cloud.retail.v2alpha.IListProductsRequest|null, - protos.google.cloud.retail.v2alpha.IListProductsResponse - ]>|void { + | protos.google.cloud.retail.v2alpha.IListProductsResponse + | null + | undefined, + protos.google.cloud.retail.v2alpha.IProduct + >, + callback?: PaginationCallback< + protos.google.cloud.retail.v2alpha.IListProductsRequest, + | protos.google.cloud.retail.v2alpha.IListProductsResponse + | null + | undefined, + protos.google.cloud.retail.v2alpha.IProduct + >, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IProduct[], + protos.google.cloud.retail.v2alpha.IListProductsRequest | null, + protos.google.cloud.retail.v2alpha.IListProductsResponse, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.cloud.retail.v2alpha.IListProductsRequest, - protos.google.cloud.retail.v2alpha.IListProductsResponse|null|undefined, - protos.google.cloud.retail.v2alpha.IProduct>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.cloud.retail.v2alpha.IListProductsRequest, + | protos.google.cloud.retail.v2alpha.IListProductsResponse + | null + | undefined, + protos.google.cloud.retail.v2alpha.IProduct + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listProducts values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -2490,260 +3283,264 @@ export class ProductServiceClient { this._log.info('listProducts request %j', request); return this.innerApiCalls .listProducts(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.cloud.retail.v2alpha.IProduct[], - protos.google.cloud.retail.v2alpha.IListProductsRequest|null, - protos.google.cloud.retail.v2alpha.IListProductsResponse - ]) => { - this._log.info('listProducts values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.cloud.retail.v2alpha.IProduct[], + protos.google.cloud.retail.v2alpha.IListProductsRequest | null, + protos.google.cloud.retail.v2alpha.IListProductsResponse, + ]) => { + this._log.info('listProducts values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listProducts`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent branch resource name, such as - * `projects/* /locations/global/catalogs/default_catalog/branches/0`. Use - * `default_branch` as the branch ID, to list products under the default - * branch. - * - * If the caller does not have permission to list - * {@link protos.google.cloud.retail.v2alpha.Product|Product}s under this branch, - * regardless of whether or not this branch exists, a PERMISSION_DENIED error - * is returned. - * @param {number} request.pageSize - * Maximum number of {@link protos.google.cloud.retail.v2alpha.Product|Product}s to - * return. If unspecified, defaults to 100. The maximum allowed value is 1000. - * Values above 1000 will be coerced to 1000. - * - * If this field is negative, an INVALID_ARGUMENT error is returned. - * @param {string} request.pageToken - * A page token - * {@link protos.google.cloud.retail.v2alpha.ListProductsResponse.next_page_token|ListProductsResponse.next_page_token}, - * received from a previous - * {@link protos.google.cloud.retail.v2alpha.ProductService.ListProducts|ProductService.ListProducts} - * call. Provide this to retrieve the subsequent page. - * - * When paginating, all other parameters provided to - * {@link protos.google.cloud.retail.v2alpha.ProductService.ListProducts|ProductService.ListProducts} - * must match the call that provided the page token. Otherwise, an - * INVALID_ARGUMENT error is returned. - * @param {string} request.filter - * A filter to apply on the list results. Supported features: - * - * * List all the products under the parent branch if - * {@link protos.google.cloud.retail.v2alpha.ListProductsRequest.filter|filter} is unset. - * * List - * {@link protos.google.cloud.retail.v2alpha.Product.Type.VARIANT|Product.Type.VARIANT} - * {@link protos.google.cloud.retail.v2alpha.Product|Product}s sharing the same - * {@link protos.google.cloud.retail.v2alpha.Product.Type.PRIMARY|Product.Type.PRIMARY} - * {@link protos.google.cloud.retail.v2alpha.Product|Product}. For example: - * `primary_product_id = "some_product_id"` - * * List {@link protos.google.cloud.retail.v2alpha.Product|Product}s bundled in a - * {@link protos.google.cloud.retail.v2alpha.Product.Type.COLLECTION|Product.Type.COLLECTION} - * {@link protos.google.cloud.retail.v2alpha.Product|Product}. - * For example: - * `collection_product_id = "some_product_id"` - * * List {@link protos.google.cloud.retail.v2alpha.Product|Product}s with a partibular - * type. For example: - * `type = "PRIMARY"` - * `type = "VARIANT"` - * `type = "COLLECTION"` - * - * If the field is unrecognizable, an INVALID_ARGUMENT error is returned. - * - * If the specified - * {@link protos.google.cloud.retail.v2alpha.Product.Type.PRIMARY|Product.Type.PRIMARY} - * {@link protos.google.cloud.retail.v2alpha.Product|Product} or - * {@link protos.google.cloud.retail.v2alpha.Product.Type.COLLECTION|Product.Type.COLLECTION} - * {@link protos.google.cloud.retail.v2alpha.Product|Product} does not exist, a NOT_FOUND - * error is returned. - * @param {google.protobuf.FieldMask} request.readMask - * The fields of {@link protos.google.cloud.retail.v2alpha.Product|Product} to return in - * the responses. If not set or empty, the following fields are returned: - * - * * {@link protos.google.cloud.retail.v2alpha.Product.name|Product.name} - * * {@link protos.google.cloud.retail.v2alpha.Product.id|Product.id} - * * {@link protos.google.cloud.retail.v2alpha.Product.title|Product.title} - * * {@link protos.google.cloud.retail.v2alpha.Product.uri|Product.uri} - * * {@link protos.google.cloud.retail.v2alpha.Product.images|Product.images} - * * {@link protos.google.cloud.retail.v2alpha.Product.price_info|Product.price_info} - * * {@link protos.google.cloud.retail.v2alpha.Product.brands|Product.brands} - * - * If "*" is provided, all fields are returned. - * {@link protos.google.cloud.retail.v2alpha.Product.name|Product.name} is always returned - * no matter what mask is set. - * - * If an unsupported or unknown field is provided, an INVALID_ARGUMENT error - * is returned. - * @param {boolean} request.requireTotalSize - * If true and - * {@link protos.google.cloud.retail.v2alpha.ListProductsRequest.page_token|page_token} is - * empty, - * {@link protos.google.cloud.retail.v2alpha.ListProductsResponse.total_size|ListProductsResponse.total_size} - * is set to the total count of matched items irrespective of pagination. - * - * Notice that setting this field to true affects the performance. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.cloud.retail.v2alpha.Product|Product} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `listProductsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `listProducts`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent branch resource name, such as + * `projects/* /locations/global/catalogs/default_catalog/branches/0`. Use + * `default_branch` as the branch ID, to list products under the default + * branch. + * + * If the caller does not have permission to list + * {@link protos.google.cloud.retail.v2alpha.Product|Product}s under this branch, + * regardless of whether or not this branch exists, a PERMISSION_DENIED error + * is returned. + * @param {number} request.pageSize + * Maximum number of {@link protos.google.cloud.retail.v2alpha.Product|Product}s to + * return. If unspecified, defaults to 100. The maximum allowed value is 1000. + * Values above 1000 will be coerced to 1000. + * + * If this field is negative, an INVALID_ARGUMENT error is returned. + * @param {string} request.pageToken + * A page token + * {@link protos.google.cloud.retail.v2alpha.ListProductsResponse.next_page_token|ListProductsResponse.next_page_token}, + * received from a previous + * {@link protos.google.cloud.retail.v2alpha.ProductService.ListProducts|ProductService.ListProducts} + * call. Provide this to retrieve the subsequent page. + * + * When paginating, all other parameters provided to + * {@link protos.google.cloud.retail.v2alpha.ProductService.ListProducts|ProductService.ListProducts} + * must match the call that provided the page token. Otherwise, an + * INVALID_ARGUMENT error is returned. + * @param {string} request.filter + * A filter to apply on the list results. Supported features: + * + * * List all the products under the parent branch if + * {@link protos.google.cloud.retail.v2alpha.ListProductsRequest.filter|filter} is unset. + * * List + * {@link protos.google.cloud.retail.v2alpha.Product.Type.VARIANT|Product.Type.VARIANT} + * {@link protos.google.cloud.retail.v2alpha.Product|Product}s sharing the same + * {@link protos.google.cloud.retail.v2alpha.Product.Type.PRIMARY|Product.Type.PRIMARY} + * {@link protos.google.cloud.retail.v2alpha.Product|Product}. For example: + * `primary_product_id = "some_product_id"` + * * List {@link protos.google.cloud.retail.v2alpha.Product|Product}s bundled in a + * {@link protos.google.cloud.retail.v2alpha.Product.Type.COLLECTION|Product.Type.COLLECTION} + * {@link protos.google.cloud.retail.v2alpha.Product|Product}. + * For example: + * `collection_product_id = "some_product_id"` + * * List {@link protos.google.cloud.retail.v2alpha.Product|Product}s with a partibular + * type. For example: + * `type = "PRIMARY"` + * `type = "VARIANT"` + * `type = "COLLECTION"` + * + * If the field is unrecognizable, an INVALID_ARGUMENT error is returned. + * + * If the specified + * {@link protos.google.cloud.retail.v2alpha.Product.Type.PRIMARY|Product.Type.PRIMARY} + * {@link protos.google.cloud.retail.v2alpha.Product|Product} or + * {@link protos.google.cloud.retail.v2alpha.Product.Type.COLLECTION|Product.Type.COLLECTION} + * {@link protos.google.cloud.retail.v2alpha.Product|Product} does not exist, a NOT_FOUND + * error is returned. + * @param {google.protobuf.FieldMask} request.readMask + * The fields of {@link protos.google.cloud.retail.v2alpha.Product|Product} to return in + * the responses. If not set or empty, the following fields are returned: + * + * * {@link protos.google.cloud.retail.v2alpha.Product.name|Product.name} + * * {@link protos.google.cloud.retail.v2alpha.Product.id|Product.id} + * * {@link protos.google.cloud.retail.v2alpha.Product.title|Product.title} + * * {@link protos.google.cloud.retail.v2alpha.Product.uri|Product.uri} + * * {@link protos.google.cloud.retail.v2alpha.Product.images|Product.images} + * * {@link protos.google.cloud.retail.v2alpha.Product.price_info|Product.price_info} + * * {@link protos.google.cloud.retail.v2alpha.Product.brands|Product.brands} + * + * If "*" is provided, all fields are returned. + * {@link protos.google.cloud.retail.v2alpha.Product.name|Product.name} is always returned + * no matter what mask is set. + * + * If an unsupported or unknown field is provided, an INVALID_ARGUMENT error + * is returned. + * @param {boolean} request.requireTotalSize + * If true and + * {@link protos.google.cloud.retail.v2alpha.ListProductsRequest.page_token|page_token} is + * empty, + * {@link protos.google.cloud.retail.v2alpha.ListProductsResponse.total_size|ListProductsResponse.total_size} + * is set to the total count of matched items irrespective of pagination. + * + * Notice that setting this field to true affects the performance. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.cloud.retail.v2alpha.Product|Product} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listProductsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listProductsStream( - request?: protos.google.cloud.retail.v2alpha.IListProductsRequest, - options?: CallOptions): - Transform{ + request?: protos.google.cloud.retail.v2alpha.IListProductsRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); const defaultCallSettings = this._defaults['listProducts']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listProducts stream %j', request); return this.descriptors.page.listProducts.createStream( this.innerApiCalls.listProducts as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listProducts`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent branch resource name, such as - * `projects/* /locations/global/catalogs/default_catalog/branches/0`. Use - * `default_branch` as the branch ID, to list products under the default - * branch. - * - * If the caller does not have permission to list - * {@link protos.google.cloud.retail.v2alpha.Product|Product}s under this branch, - * regardless of whether or not this branch exists, a PERMISSION_DENIED error - * is returned. - * @param {number} request.pageSize - * Maximum number of {@link protos.google.cloud.retail.v2alpha.Product|Product}s to - * return. If unspecified, defaults to 100. The maximum allowed value is 1000. - * Values above 1000 will be coerced to 1000. - * - * If this field is negative, an INVALID_ARGUMENT error is returned. - * @param {string} request.pageToken - * A page token - * {@link protos.google.cloud.retail.v2alpha.ListProductsResponse.next_page_token|ListProductsResponse.next_page_token}, - * received from a previous - * {@link protos.google.cloud.retail.v2alpha.ProductService.ListProducts|ProductService.ListProducts} - * call. Provide this to retrieve the subsequent page. - * - * When paginating, all other parameters provided to - * {@link protos.google.cloud.retail.v2alpha.ProductService.ListProducts|ProductService.ListProducts} - * must match the call that provided the page token. Otherwise, an - * INVALID_ARGUMENT error is returned. - * @param {string} request.filter - * A filter to apply on the list results. Supported features: - * - * * List all the products under the parent branch if - * {@link protos.google.cloud.retail.v2alpha.ListProductsRequest.filter|filter} is unset. - * * List - * {@link protos.google.cloud.retail.v2alpha.Product.Type.VARIANT|Product.Type.VARIANT} - * {@link protos.google.cloud.retail.v2alpha.Product|Product}s sharing the same - * {@link protos.google.cloud.retail.v2alpha.Product.Type.PRIMARY|Product.Type.PRIMARY} - * {@link protos.google.cloud.retail.v2alpha.Product|Product}. For example: - * `primary_product_id = "some_product_id"` - * * List {@link protos.google.cloud.retail.v2alpha.Product|Product}s bundled in a - * {@link protos.google.cloud.retail.v2alpha.Product.Type.COLLECTION|Product.Type.COLLECTION} - * {@link protos.google.cloud.retail.v2alpha.Product|Product}. - * For example: - * `collection_product_id = "some_product_id"` - * * List {@link protos.google.cloud.retail.v2alpha.Product|Product}s with a partibular - * type. For example: - * `type = "PRIMARY"` - * `type = "VARIANT"` - * `type = "COLLECTION"` - * - * If the field is unrecognizable, an INVALID_ARGUMENT error is returned. - * - * If the specified - * {@link protos.google.cloud.retail.v2alpha.Product.Type.PRIMARY|Product.Type.PRIMARY} - * {@link protos.google.cloud.retail.v2alpha.Product|Product} or - * {@link protos.google.cloud.retail.v2alpha.Product.Type.COLLECTION|Product.Type.COLLECTION} - * {@link protos.google.cloud.retail.v2alpha.Product|Product} does not exist, a NOT_FOUND - * error is returned. - * @param {google.protobuf.FieldMask} request.readMask - * The fields of {@link protos.google.cloud.retail.v2alpha.Product|Product} to return in - * the responses. If not set or empty, the following fields are returned: - * - * * {@link protos.google.cloud.retail.v2alpha.Product.name|Product.name} - * * {@link protos.google.cloud.retail.v2alpha.Product.id|Product.id} - * * {@link protos.google.cloud.retail.v2alpha.Product.title|Product.title} - * * {@link protos.google.cloud.retail.v2alpha.Product.uri|Product.uri} - * * {@link protos.google.cloud.retail.v2alpha.Product.images|Product.images} - * * {@link protos.google.cloud.retail.v2alpha.Product.price_info|Product.price_info} - * * {@link protos.google.cloud.retail.v2alpha.Product.brands|Product.brands} - * - * If "*" is provided, all fields are returned. - * {@link protos.google.cloud.retail.v2alpha.Product.name|Product.name} is always returned - * no matter what mask is set. - * - * If an unsupported or unknown field is provided, an INVALID_ARGUMENT error - * is returned. - * @param {boolean} request.requireTotalSize - * If true and - * {@link protos.google.cloud.retail.v2alpha.ListProductsRequest.page_token|page_token} is - * empty, - * {@link protos.google.cloud.retail.v2alpha.ListProductsResponse.total_size|ListProductsResponse.total_size} - * is set to the total count of matched items irrespective of pagination. - * - * Notice that setting this field to true affects the performance. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.cloud.retail.v2alpha.Product|Product}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/product_service.list_products.js - * region_tag:retail_v2alpha_generated_ProductService_ListProducts_async - */ + /** + * Equivalent to `listProducts`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent branch resource name, such as + * `projects/* /locations/global/catalogs/default_catalog/branches/0`. Use + * `default_branch` as the branch ID, to list products under the default + * branch. + * + * If the caller does not have permission to list + * {@link protos.google.cloud.retail.v2alpha.Product|Product}s under this branch, + * regardless of whether or not this branch exists, a PERMISSION_DENIED error + * is returned. + * @param {number} request.pageSize + * Maximum number of {@link protos.google.cloud.retail.v2alpha.Product|Product}s to + * return. If unspecified, defaults to 100. The maximum allowed value is 1000. + * Values above 1000 will be coerced to 1000. + * + * If this field is negative, an INVALID_ARGUMENT error is returned. + * @param {string} request.pageToken + * A page token + * {@link protos.google.cloud.retail.v2alpha.ListProductsResponse.next_page_token|ListProductsResponse.next_page_token}, + * received from a previous + * {@link protos.google.cloud.retail.v2alpha.ProductService.ListProducts|ProductService.ListProducts} + * call. Provide this to retrieve the subsequent page. + * + * When paginating, all other parameters provided to + * {@link protos.google.cloud.retail.v2alpha.ProductService.ListProducts|ProductService.ListProducts} + * must match the call that provided the page token. Otherwise, an + * INVALID_ARGUMENT error is returned. + * @param {string} request.filter + * A filter to apply on the list results. Supported features: + * + * * List all the products under the parent branch if + * {@link protos.google.cloud.retail.v2alpha.ListProductsRequest.filter|filter} is unset. + * * List + * {@link protos.google.cloud.retail.v2alpha.Product.Type.VARIANT|Product.Type.VARIANT} + * {@link protos.google.cloud.retail.v2alpha.Product|Product}s sharing the same + * {@link protos.google.cloud.retail.v2alpha.Product.Type.PRIMARY|Product.Type.PRIMARY} + * {@link protos.google.cloud.retail.v2alpha.Product|Product}. For example: + * `primary_product_id = "some_product_id"` + * * List {@link protos.google.cloud.retail.v2alpha.Product|Product}s bundled in a + * {@link protos.google.cloud.retail.v2alpha.Product.Type.COLLECTION|Product.Type.COLLECTION} + * {@link protos.google.cloud.retail.v2alpha.Product|Product}. + * For example: + * `collection_product_id = "some_product_id"` + * * List {@link protos.google.cloud.retail.v2alpha.Product|Product}s with a partibular + * type. For example: + * `type = "PRIMARY"` + * `type = "VARIANT"` + * `type = "COLLECTION"` + * + * If the field is unrecognizable, an INVALID_ARGUMENT error is returned. + * + * If the specified + * {@link protos.google.cloud.retail.v2alpha.Product.Type.PRIMARY|Product.Type.PRIMARY} + * {@link protos.google.cloud.retail.v2alpha.Product|Product} or + * {@link protos.google.cloud.retail.v2alpha.Product.Type.COLLECTION|Product.Type.COLLECTION} + * {@link protos.google.cloud.retail.v2alpha.Product|Product} does not exist, a NOT_FOUND + * error is returned. + * @param {google.protobuf.FieldMask} request.readMask + * The fields of {@link protos.google.cloud.retail.v2alpha.Product|Product} to return in + * the responses. If not set or empty, the following fields are returned: + * + * * {@link protos.google.cloud.retail.v2alpha.Product.name|Product.name} + * * {@link protos.google.cloud.retail.v2alpha.Product.id|Product.id} + * * {@link protos.google.cloud.retail.v2alpha.Product.title|Product.title} + * * {@link protos.google.cloud.retail.v2alpha.Product.uri|Product.uri} + * * {@link protos.google.cloud.retail.v2alpha.Product.images|Product.images} + * * {@link protos.google.cloud.retail.v2alpha.Product.price_info|Product.price_info} + * * {@link protos.google.cloud.retail.v2alpha.Product.brands|Product.brands} + * + * If "*" is provided, all fields are returned. + * {@link protos.google.cloud.retail.v2alpha.Product.name|Product.name} is always returned + * no matter what mask is set. + * + * If an unsupported or unknown field is provided, an INVALID_ARGUMENT error + * is returned. + * @param {boolean} request.requireTotalSize + * If true and + * {@link protos.google.cloud.retail.v2alpha.ListProductsRequest.page_token|page_token} is + * empty, + * {@link protos.google.cloud.retail.v2alpha.ListProductsResponse.total_size|ListProductsResponse.total_size} + * is set to the total count of matched items irrespective of pagination. + * + * Notice that setting this field to true affects the performance. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.cloud.retail.v2alpha.Product|Product}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/product_service.list_products.js + * region_tag:retail_v2alpha_generated_ProductService_ListProducts_async + */ listProductsAsync( - request?: protos.google.cloud.retail.v2alpha.IListProductsRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.cloud.retail.v2alpha.IListProductsRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); const defaultCallSettings = this._defaults['listProducts']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listProducts iterate %j', request); return this.descriptors.page.listProducts.asyncIterate( this.innerApiCalls['listProducts'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } // -------------------- @@ -2756,7 +3553,7 @@ export class ProductServiceClient { * @param {string} project * @returns {string} Resource name string. */ - alertConfigPath(project:string) { + alertConfigPath(project: string) { return this.pathTemplates.alertConfigPathTemplate.render({ project: project, }); @@ -2770,7 +3567,8 @@ export class ProductServiceClient { * @returns {string} A string representing the project. */ matchProjectFromAlertConfigName(alertConfigName: string) { - return this.pathTemplates.alertConfigPathTemplate.match(alertConfigName).project; + return this.pathTemplates.alertConfigPathTemplate.match(alertConfigName) + .project; } /** @@ -2781,7 +3579,7 @@ export class ProductServiceClient { * @param {string} catalog * @returns {string} Resource name string. */ - attributesConfigPath(project:string,location:string,catalog:string) { + attributesConfigPath(project: string, location: string, catalog: string) { return this.pathTemplates.attributesConfigPathTemplate.render({ project: project, location: location, @@ -2797,7 +3595,9 @@ export class ProductServiceClient { * @returns {string} A string representing the project. */ matchProjectFromAttributesConfigName(attributesConfigName: string) { - return this.pathTemplates.attributesConfigPathTemplate.match(attributesConfigName).project; + return this.pathTemplates.attributesConfigPathTemplate.match( + attributesConfigName, + ).project; } /** @@ -2808,7 +3608,9 @@ export class ProductServiceClient { * @returns {string} A string representing the location. */ matchLocationFromAttributesConfigName(attributesConfigName: string) { - return this.pathTemplates.attributesConfigPathTemplate.match(attributesConfigName).location; + return this.pathTemplates.attributesConfigPathTemplate.match( + attributesConfigName, + ).location; } /** @@ -2819,7 +3621,9 @@ export class ProductServiceClient { * @returns {string} A string representing the catalog. */ matchCatalogFromAttributesConfigName(attributesConfigName: string) { - return this.pathTemplates.attributesConfigPathTemplate.match(attributesConfigName).catalog; + return this.pathTemplates.attributesConfigPathTemplate.match( + attributesConfigName, + ).catalog; } /** @@ -2831,7 +3635,12 @@ export class ProductServiceClient { * @param {string} branch * @returns {string} Resource name string. */ - branchPath(project:string,location:string,catalog:string,branch:string) { + branchPath( + project: string, + location: string, + catalog: string, + branch: string, + ) { return this.pathTemplates.branchPathTemplate.render({ project: project, location: location, @@ -2892,7 +3701,7 @@ export class ProductServiceClient { * @param {string} catalog * @returns {string} Resource name string. */ - catalogPath(project:string,location:string,catalog:string) { + catalogPath(project: string, location: string, catalog: string) { return this.pathTemplates.catalogPathTemplate.render({ project: project, location: location, @@ -2941,7 +3750,7 @@ export class ProductServiceClient { * @param {string} catalog * @returns {string} Resource name string. */ - completionConfigPath(project:string,location:string,catalog:string) { + completionConfigPath(project: string, location: string, catalog: string) { return this.pathTemplates.completionConfigPathTemplate.render({ project: project, location: location, @@ -2957,7 +3766,9 @@ export class ProductServiceClient { * @returns {string} A string representing the project. */ matchProjectFromCompletionConfigName(completionConfigName: string) { - return this.pathTemplates.completionConfigPathTemplate.match(completionConfigName).project; + return this.pathTemplates.completionConfigPathTemplate.match( + completionConfigName, + ).project; } /** @@ -2968,7 +3779,9 @@ export class ProductServiceClient { * @returns {string} A string representing the location. */ matchLocationFromCompletionConfigName(completionConfigName: string) { - return this.pathTemplates.completionConfigPathTemplate.match(completionConfigName).location; + return this.pathTemplates.completionConfigPathTemplate.match( + completionConfigName, + ).location; } /** @@ -2979,7 +3792,9 @@ export class ProductServiceClient { * @returns {string} A string representing the catalog. */ matchCatalogFromCompletionConfigName(completionConfigName: string) { - return this.pathTemplates.completionConfigPathTemplate.match(completionConfigName).catalog; + return this.pathTemplates.completionConfigPathTemplate.match( + completionConfigName, + ).catalog; } /** @@ -2991,7 +3806,12 @@ export class ProductServiceClient { * @param {string} control * @returns {string} Resource name string. */ - controlPath(project:string,location:string,catalog:string,control:string) { + controlPath( + project: string, + location: string, + catalog: string, + control: string, + ) { return this.pathTemplates.controlPathTemplate.render({ project: project, location: location, @@ -3050,7 +3870,7 @@ export class ProductServiceClient { * @param {string} project * @returns {string} Resource name string. */ - loggingConfigPath(project:string) { + loggingConfigPath(project: string) { return this.pathTemplates.loggingConfigPathTemplate.render({ project: project, }); @@ -3064,7 +3884,8 @@ export class ProductServiceClient { * @returns {string} A string representing the project. */ matchProjectFromLoggingConfigName(loggingConfigName: string) { - return this.pathTemplates.loggingConfigPathTemplate.match(loggingConfigName).project; + return this.pathTemplates.loggingConfigPathTemplate.match(loggingConfigName) + .project; } /** @@ -3076,7 +3897,12 @@ export class ProductServiceClient { * @param {string} merchant_center_account_link * @returns {string} Resource name string. */ - merchantCenterAccountLinkPath(project:string,location:string,catalog:string,merchantCenterAccountLink:string) { + merchantCenterAccountLinkPath( + project: string, + location: string, + catalog: string, + merchantCenterAccountLink: string, + ) { return this.pathTemplates.merchantCenterAccountLinkPathTemplate.render({ project: project, location: location, @@ -3092,8 +3918,12 @@ export class ProductServiceClient { * A fully-qualified path representing MerchantCenterAccountLink resource. * @returns {string} A string representing the project. */ - matchProjectFromMerchantCenterAccountLinkName(merchantCenterAccountLinkName: string) { - return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match(merchantCenterAccountLinkName).project; + matchProjectFromMerchantCenterAccountLinkName( + merchantCenterAccountLinkName: string, + ) { + return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match( + merchantCenterAccountLinkName, + ).project; } /** @@ -3103,8 +3933,12 @@ export class ProductServiceClient { * A fully-qualified path representing MerchantCenterAccountLink resource. * @returns {string} A string representing the location. */ - matchLocationFromMerchantCenterAccountLinkName(merchantCenterAccountLinkName: string) { - return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match(merchantCenterAccountLinkName).location; + matchLocationFromMerchantCenterAccountLinkName( + merchantCenterAccountLinkName: string, + ) { + return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match( + merchantCenterAccountLinkName, + ).location; } /** @@ -3114,8 +3948,12 @@ export class ProductServiceClient { * A fully-qualified path representing MerchantCenterAccountLink resource. * @returns {string} A string representing the catalog. */ - matchCatalogFromMerchantCenterAccountLinkName(merchantCenterAccountLinkName: string) { - return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match(merchantCenterAccountLinkName).catalog; + matchCatalogFromMerchantCenterAccountLinkName( + merchantCenterAccountLinkName: string, + ) { + return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match( + merchantCenterAccountLinkName, + ).catalog; } /** @@ -3125,8 +3963,12 @@ export class ProductServiceClient { * A fully-qualified path representing MerchantCenterAccountLink resource. * @returns {string} A string representing the merchant_center_account_link. */ - matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName(merchantCenterAccountLinkName: string) { - return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match(merchantCenterAccountLinkName).merchant_center_account_link; + matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName( + merchantCenterAccountLinkName: string, + ) { + return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match( + merchantCenterAccountLinkName, + ).merchant_center_account_link; } /** @@ -3138,7 +3980,7 @@ export class ProductServiceClient { * @param {string} model * @returns {string} Resource name string. */ - modelPath(project:string,location:string,catalog:string,model:string) { + modelPath(project: string, location: string, catalog: string, model: string) { return this.pathTemplates.modelPathTemplate.render({ project: project, location: location, @@ -3201,7 +4043,13 @@ export class ProductServiceClient { * @param {string} product * @returns {string} Resource name string. */ - productPath(project:string,location:string,catalog:string,branch:string,product:string) { + productPath( + project: string, + location: string, + catalog: string, + branch: string, + product: string, + ) { return this.pathTemplates.productPathTemplate.render({ project: project, location: location, @@ -3272,7 +4120,7 @@ export class ProductServiceClient { * @param {string} project * @returns {string} Resource name string. */ - retailProjectPath(project:string) { + retailProjectPath(project: string) { return this.pathTemplates.retailProjectPathTemplate.render({ project: project, }); @@ -3286,7 +4134,8 @@ export class ProductServiceClient { * @returns {string} A string representing the project. */ matchProjectFromRetailProjectName(retailProjectName: string) { - return this.pathTemplates.retailProjectPathTemplate.match(retailProjectName).project; + return this.pathTemplates.retailProjectPathTemplate.match(retailProjectName) + .project; } /** @@ -3298,7 +4147,12 @@ export class ProductServiceClient { * @param {string} serving_config * @returns {string} Resource name string. */ - servingConfigPath(project:string,location:string,catalog:string,servingConfig:string) { + servingConfigPath( + project: string, + location: string, + catalog: string, + servingConfig: string, + ) { return this.pathTemplates.servingConfigPathTemplate.render({ project: project, location: location, @@ -3315,7 +4169,8 @@ export class ProductServiceClient { * @returns {string} A string representing the project. */ matchProjectFromServingConfigName(servingConfigName: string) { - return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName).project; + return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName) + .project; } /** @@ -3326,7 +4181,8 @@ export class ProductServiceClient { * @returns {string} A string representing the location. */ matchLocationFromServingConfigName(servingConfigName: string) { - return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName).location; + return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName) + .location; } /** @@ -3337,7 +4193,8 @@ export class ProductServiceClient { * @returns {string} A string representing the catalog. */ matchCatalogFromServingConfigName(servingConfigName: string) { - return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName).catalog; + return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName) + .catalog; } /** @@ -3348,7 +4205,8 @@ export class ProductServiceClient { * @returns {string} A string representing the serving_config. */ matchServingConfigFromServingConfigName(servingConfigName: string) { - return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName).serving_config; + return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName) + .serving_config; } /** @@ -3359,7 +4217,7 @@ export class ProductServiceClient { */ close(): Promise { if (this.productServiceStub && !this._terminated) { - return this.productServiceStub.then(stub => { + return this.productServiceStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -3368,4 +4226,4 @@ export class ProductServiceClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/core/generator/gapic-generator-typescript/baselines/retail/src/v2alpha/project_service_client.ts.baseline b/core/generator/gapic-generator-typescript/baselines/retail/src/v2alpha/project_service_client.ts.baseline index f79335bc3e1b..76cf8f1da2a1 100644 --- a/core/generator/gapic-generator-typescript/baselines/retail/src/v2alpha/project_service_client.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/retail/src/v2alpha/project_service_client.ts.baseline @@ -18,11 +18,18 @@ /* global window */ import type * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions, GrpcClientOptions, LROperation} from 'google-gax'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + GrpcClientOptions, + LROperation, +} from 'google-gax'; import * as protos from '../../protos/protos'; import jsonProtos = require('../../protos/protos.json'); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; /** * Client JSON configuration object, loaded from @@ -44,7 +51,7 @@ export class ProjectServiceClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('retail'); @@ -57,10 +64,10 @@ export class ProjectServiceClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; operationsClient: gax.OperationsClient; - projectServiceStub?: Promise<{[name: string]: Function}>; + projectServiceStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of ProjectServiceClient. @@ -101,21 +108,42 @@ export class ProjectServiceClient { * const client = new ProjectServiceClient({fallback: true}, gax); * ``` */ - constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { // Ensure that options include all the required fields. const staticMembers = this.constructor as typeof ProjectServiceClient; - if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { - throw new Error('Please set either universe_domain or universeDomain, but not both.'); + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); } - const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; - this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; this._servicePath = 'retail.' + this._universeDomain; - const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; - const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. if (servicePath !== this._servicePath && !('scopes' in opts)) { @@ -137,7 +165,7 @@ export class ProjectServiceClient { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; @@ -151,10 +179,7 @@ export class ProjectServiceClient { } // Determine the client header string. - const clientHeader = [ - `gax/${this._gaxModule.version}`, - `gapic/${version}`, - ]; + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/${process.versions.node}`); } else { @@ -176,43 +201,43 @@ export class ProjectServiceClient { // Create useful helper objects for these. this.pathTemplates = { alertConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/alertConfig' + 'projects/{project}/alertConfig', ), attributesConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/attributesConfig' + 'projects/{project}/locations/{location}/catalogs/{catalog}/attributesConfig', ), branchPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}', ), catalogPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}' + 'projects/{project}/locations/{location}/catalogs/{catalog}', ), completionConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/completionConfig' + 'projects/{project}/locations/{location}/catalogs/{catalog}/completionConfig', ), controlPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/controls/{control}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/controls/{control}', ), loggingConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/loggingConfig' + 'projects/{project}/loggingConfig', ), merchantCenterAccountLinkPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/merchantCenterAccountLinks/{merchant_center_account_link}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/merchantCenterAccountLinks/{merchant_center_account_link}', ), modelPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/models/{model}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/models/{model}', ), productPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}', ), projectPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}' + 'projects/{project}', ), retailProjectPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/retailProject' + 'projects/{project}/retailProject', ), servingConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/servingConfigs/{serving_config}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/servingConfigs/{serving_config}', ), }; @@ -222,31 +247,60 @@ export class ProjectServiceClient { // rather than holding a request open. const lroOptions: GrpcClientOptions = { auth: this.auth, - grpc: 'grpc' in this._gaxGrpc ? this._gaxGrpc.grpc : undefined + grpc: 'grpc' in this._gaxGrpc ? this._gaxGrpc.grpc : undefined, }; if (opts.fallback) { lroOptions.protoJson = protoFilesRoot; - lroOptions.httpRules = [{selector: 'google.longrunning.Operations.GetOperation',get: '/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*/operations/*}',additional_bindings: [{get: '/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*/places/*/operations/*}',},{get: '/v2alpha/{name=projects/*/locations/*/catalogs/*/operations/*}',},{get: '/v2alpha/{name=projects/*/locations/*/operations/*}',},{get: '/v2alpha/{name=projects/*/operations/*}',}], - },{selector: 'google.longrunning.Operations.ListOperations',get: '/v2alpha/{name=projects/*/locations/*/catalogs/*}/operations',additional_bindings: [{get: '/v2alpha/{name=projects/*/locations/*}/operations',},{get: '/v2alpha/{name=projects/*}/operations',}], - }]; + lroOptions.httpRules = [ + { + selector: 'google.longrunning.Operations.GetOperation', + get: '/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*/operations/*}', + additional_bindings: [ + { + get: '/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*/places/*/operations/*}', + }, + { + get: '/v2alpha/{name=projects/*/locations/*/catalogs/*/operations/*}', + }, + { get: '/v2alpha/{name=projects/*/locations/*/operations/*}' }, + { get: '/v2alpha/{name=projects/*/operations/*}' }, + ], + }, + { + selector: 'google.longrunning.Operations.ListOperations', + get: '/v2alpha/{name=projects/*/locations/*/catalogs/*}/operations', + additional_bindings: [ + { get: '/v2alpha/{name=projects/*/locations/*}/operations' }, + { get: '/v2alpha/{name=projects/*}/operations' }, + ], + }, + ]; } - this.operationsClient = this._gaxModule.lro(lroOptions).operationsClient(opts); + this.operationsClient = this._gaxModule + .lro(lroOptions) + .operationsClient(opts); const enrollSolutionResponse = protoFilesRoot.lookup( - '.google.cloud.retail.v2alpha.EnrollSolutionResponse') as gax.protobuf.Type; + '.google.cloud.retail.v2alpha.EnrollSolutionResponse', + ) as gax.protobuf.Type; const enrollSolutionMetadata = protoFilesRoot.lookup( - '.google.cloud.retail.v2alpha.EnrollSolutionMetadata') as gax.protobuf.Type; + '.google.cloud.retail.v2alpha.EnrollSolutionMetadata', + ) as gax.protobuf.Type; this.descriptors.longrunning = { enrollSolution: new this._gaxModule.LongrunningDescriptor( this.operationsClient, enrollSolutionResponse.decode.bind(enrollSolutionResponse), - enrollSolutionMetadata.decode.bind(enrollSolutionMetadata)) + enrollSolutionMetadata.decode.bind(enrollSolutionMetadata), + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.cloud.retail.v2alpha.ProjectService', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.cloud.retail.v2alpha.ProjectService', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + { 'x-goog-api-client': clientHeader.join(' ') }, + ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -277,37 +331,49 @@ export class ProjectServiceClient { // Put together the "service stub" for // google.cloud.retail.v2alpha.ProjectService. this.projectServiceStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.cloud.retail.v2alpha.ProjectService') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.cloud.retail.v2alpha.ProjectService', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.cloud.retail.v2alpha.ProjectService, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts, + this._providedCustomServicePath, + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const projectServiceStubMethods = - ['getProject', 'acceptTerms', 'enrollSolution', 'listEnrolledSolutions', 'getLoggingConfig', 'updateLoggingConfig', 'getAlertConfig', 'updateAlertConfig']; + const projectServiceStubMethods = [ + 'getProject', + 'acceptTerms', + 'enrollSolution', + 'listEnrolledSolutions', + 'getLoggingConfig', + 'updateLoggingConfig', + 'getAlertConfig', + 'updateAlertConfig', + ]; for (const methodName of projectServiceStubMethods) { const callPromise = this.projectServiceStub.then( - stub => (...args: Array<{}>) => { - if (this._terminated) { - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error|null|undefined) => () => { + (stub) => + (...args: Array<{}>) => { + if (this._terminated) { + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { throw err; - }); + }, + ); - const descriptor = - this.descriptors.longrunning[methodName] || - undefined; + const descriptor = this.descriptors.longrunning[methodName] || undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -322,8 +388,14 @@ export class ProjectServiceClient { * @returns {string} The DNS address for this service. */ static get servicePath() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'retail.googleapis.com'; } @@ -334,8 +406,14 @@ export class ProjectServiceClient { * @returns {string} The DNS address for this service. */ static get apiEndpoint() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'retail.googleapis.com'; } @@ -366,9 +444,7 @@ export class ProjectServiceClient { * @returns {string[]} List of default scopes. */ static get scopes() { - return [ - 'https://www.googleapis.com/auth/cloud-platform' - ]; + return ['https://www.googleapis.com/auth/cloud-platform']; } getProjectId(): Promise; @@ -377,8 +453,9 @@ export class ProjectServiceClient { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId(callback?: Callback): - Promise|void { + getProjectId( + callback?: Callback, + ): Promise | void { if (callback) { this.auth.getProjectId(callback); return; @@ -389,824 +466,1178 @@ export class ProjectServiceClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Gets the project. - * - * Throws `NOT_FOUND` if the project wasn't initialized for the Retail API - * service. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. Full resource name of the project. Format: - * `projects/{project_number_or_id}/retailProject` - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.Project|Project}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/project_service.get_project.js - * region_tag:retail_v2alpha_generated_ProjectService_GetProject_async - */ + /** + * Gets the project. + * + * Throws `NOT_FOUND` if the project wasn't initialized for the Retail API + * service. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Full resource name of the project. Format: + * `projects/{project_number_or_id}/retailProject` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.Project|Project}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/project_service.get_project.js + * region_tag:retail_v2alpha_generated_ProjectService_GetProject_async + */ getProject( - request?: protos.google.cloud.retail.v2alpha.IGetProjectRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.retail.v2alpha.IProject, - protos.google.cloud.retail.v2alpha.IGetProjectRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.IGetProjectRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IProject, + protos.google.cloud.retail.v2alpha.IGetProjectRequest | undefined, + {} | undefined, + ] + >; getProject( - request: protos.google.cloud.retail.v2alpha.IGetProjectRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.retail.v2alpha.IProject, - protos.google.cloud.retail.v2alpha.IGetProjectRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IGetProjectRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.retail.v2alpha.IProject, + protos.google.cloud.retail.v2alpha.IGetProjectRequest | null | undefined, + {} | null | undefined + >, + ): void; getProject( - request: protos.google.cloud.retail.v2alpha.IGetProjectRequest, - callback: Callback< - protos.google.cloud.retail.v2alpha.IProject, - protos.google.cloud.retail.v2alpha.IGetProjectRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IGetProjectRequest, + callback: Callback< + protos.google.cloud.retail.v2alpha.IProject, + protos.google.cloud.retail.v2alpha.IGetProjectRequest | null | undefined, + {} | null | undefined + >, + ): void; getProject( - request?: protos.google.cloud.retail.v2alpha.IGetProjectRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.retail.v2alpha.IProject, - protos.google.cloud.retail.v2alpha.IGetProjectRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.retail.v2alpha.IGetProjectRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.retail.v2alpha.IProject, - protos.google.cloud.retail.v2alpha.IGetProjectRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.retail.v2alpha.IProject, - protos.google.cloud.retail.v2alpha.IGetProjectRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.retail.v2alpha.IGetProjectRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.retail.v2alpha.IProject, + protos.google.cloud.retail.v2alpha.IGetProjectRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IProject, + protos.google.cloud.retail.v2alpha.IGetProjectRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getProject request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.retail.v2alpha.IProject, - protos.google.cloud.retail.v2alpha.IGetProjectRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.retail.v2alpha.IProject, + | protos.google.cloud.retail.v2alpha.IGetProjectRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getProject response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getProject(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.retail.v2alpha.IProject, - protos.google.cloud.retail.v2alpha.IGetProjectRequest|undefined, - {}|undefined - ]) => { - this._log.info('getProject response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getProject(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.retail.v2alpha.IProject, + protos.google.cloud.retail.v2alpha.IGetProjectRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getProject response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Accepts service terms for this project. - * By making requests to this API, you agree to the terms of service linked - * below. - * https://cloud.google.com/retail/data-use-terms - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.project - * Required. Full resource name of the project. Format: - * `projects/{project_number_or_id}/retailProject` - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.Project|Project}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/project_service.accept_terms.js - * region_tag:retail_v2alpha_generated_ProjectService_AcceptTerms_async - */ + /** + * Accepts service terms for this project. + * By making requests to this API, you agree to the terms of service linked + * below. + * https://cloud.google.com/retail/data-use-terms + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.project + * Required. Full resource name of the project. Format: + * `projects/{project_number_or_id}/retailProject` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.Project|Project}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/project_service.accept_terms.js + * region_tag:retail_v2alpha_generated_ProjectService_AcceptTerms_async + */ acceptTerms( - request?: protos.google.cloud.retail.v2alpha.IAcceptTermsRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.retail.v2alpha.IProject, - protos.google.cloud.retail.v2alpha.IAcceptTermsRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.IAcceptTermsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IProject, + protos.google.cloud.retail.v2alpha.IAcceptTermsRequest | undefined, + {} | undefined, + ] + >; acceptTerms( - request: protos.google.cloud.retail.v2alpha.IAcceptTermsRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.retail.v2alpha.IProject, - protos.google.cloud.retail.v2alpha.IAcceptTermsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IAcceptTermsRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.retail.v2alpha.IProject, + protos.google.cloud.retail.v2alpha.IAcceptTermsRequest | null | undefined, + {} | null | undefined + >, + ): void; acceptTerms( - request: protos.google.cloud.retail.v2alpha.IAcceptTermsRequest, - callback: Callback< - protos.google.cloud.retail.v2alpha.IProject, - protos.google.cloud.retail.v2alpha.IAcceptTermsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IAcceptTermsRequest, + callback: Callback< + protos.google.cloud.retail.v2alpha.IProject, + protos.google.cloud.retail.v2alpha.IAcceptTermsRequest | null | undefined, + {} | null | undefined + >, + ): void; acceptTerms( - request?: protos.google.cloud.retail.v2alpha.IAcceptTermsRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.cloud.retail.v2alpha.IAcceptTermsRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.retail.v2alpha.IProject, - protos.google.cloud.retail.v2alpha.IAcceptTermsRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.cloud.retail.v2alpha.IProject, - protos.google.cloud.retail.v2alpha.IAcceptTermsRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.retail.v2alpha.IProject, - protos.google.cloud.retail.v2alpha.IAcceptTermsRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.retail.v2alpha.IAcceptTermsRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.retail.v2alpha.IProject, + protos.google.cloud.retail.v2alpha.IAcceptTermsRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IProject, + protos.google.cloud.retail.v2alpha.IAcceptTermsRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'project': request.project ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + project: request.project ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('acceptTerms request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.retail.v2alpha.IProject, - protos.google.cloud.retail.v2alpha.IAcceptTermsRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.retail.v2alpha.IProject, + | protos.google.cloud.retail.v2alpha.IAcceptTermsRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('acceptTerms response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.acceptTerms(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.retail.v2alpha.IProject, - protos.google.cloud.retail.v2alpha.IAcceptTermsRequest|undefined, - {}|undefined - ]) => { - this._log.info('acceptTerms response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .acceptTerms(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.retail.v2alpha.IProject, + protos.google.cloud.retail.v2alpha.IAcceptTermsRequest | undefined, + {} | undefined, + ]) => { + this._log.info('acceptTerms response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Lists all the retail API solutions the project has enrolled. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. Full resource name of parent. Format: - * `projects/{project_number_or_id}` - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.ListEnrolledSolutionsResponse|ListEnrolledSolutionsResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/project_service.list_enrolled_solutions.js - * region_tag:retail_v2alpha_generated_ProjectService_ListEnrolledSolutions_async - */ + /** + * Lists all the retail API solutions the project has enrolled. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Full resource name of parent. Format: + * `projects/{project_number_or_id}` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.ListEnrolledSolutionsResponse|ListEnrolledSolutionsResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/project_service.list_enrolled_solutions.js + * region_tag:retail_v2alpha_generated_ProjectService_ListEnrolledSolutions_async + */ listEnrolledSolutions( - request?: protos.google.cloud.retail.v2alpha.IListEnrolledSolutionsRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.retail.v2alpha.IListEnrolledSolutionsResponse, - protos.google.cloud.retail.v2alpha.IListEnrolledSolutionsRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.IListEnrolledSolutionsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IListEnrolledSolutionsResponse, + ( + | protos.google.cloud.retail.v2alpha.IListEnrolledSolutionsRequest + | undefined + ), + {} | undefined, + ] + >; listEnrolledSolutions( - request: protos.google.cloud.retail.v2alpha.IListEnrolledSolutionsRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.retail.v2alpha.IListEnrolledSolutionsResponse, - protos.google.cloud.retail.v2alpha.IListEnrolledSolutionsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IListEnrolledSolutionsRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.retail.v2alpha.IListEnrolledSolutionsResponse, + | protos.google.cloud.retail.v2alpha.IListEnrolledSolutionsRequest + | null + | undefined, + {} | null | undefined + >, + ): void; listEnrolledSolutions( - request: protos.google.cloud.retail.v2alpha.IListEnrolledSolutionsRequest, - callback: Callback< - protos.google.cloud.retail.v2alpha.IListEnrolledSolutionsResponse, - protos.google.cloud.retail.v2alpha.IListEnrolledSolutionsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IListEnrolledSolutionsRequest, + callback: Callback< + protos.google.cloud.retail.v2alpha.IListEnrolledSolutionsResponse, + | protos.google.cloud.retail.v2alpha.IListEnrolledSolutionsRequest + | null + | undefined, + {} | null | undefined + >, + ): void; listEnrolledSolutions( - request?: protos.google.cloud.retail.v2alpha.IListEnrolledSolutionsRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.cloud.retail.v2alpha.IListEnrolledSolutionsRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.retail.v2alpha.IListEnrolledSolutionsResponse, - protos.google.cloud.retail.v2alpha.IListEnrolledSolutionsRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.cloud.retail.v2alpha.IListEnrolledSolutionsResponse, - protos.google.cloud.retail.v2alpha.IListEnrolledSolutionsRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.retail.v2alpha.IListEnrolledSolutionsResponse, - protos.google.cloud.retail.v2alpha.IListEnrolledSolutionsRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.retail.v2alpha.IListEnrolledSolutionsRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.retail.v2alpha.IListEnrolledSolutionsResponse, + | protos.google.cloud.retail.v2alpha.IListEnrolledSolutionsRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IListEnrolledSolutionsResponse, + ( + | protos.google.cloud.retail.v2alpha.IListEnrolledSolutionsRequest + | undefined + ), + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('listEnrolledSolutions request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.retail.v2alpha.IListEnrolledSolutionsResponse, - protos.google.cloud.retail.v2alpha.IListEnrolledSolutionsRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.retail.v2alpha.IListEnrolledSolutionsResponse, + | protos.google.cloud.retail.v2alpha.IListEnrolledSolutionsRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('listEnrolledSolutions response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.listEnrolledSolutions(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.retail.v2alpha.IListEnrolledSolutionsResponse, - protos.google.cloud.retail.v2alpha.IListEnrolledSolutionsRequest|undefined, - {}|undefined - ]) => { - this._log.info('listEnrolledSolutions response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .listEnrolledSolutions(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.retail.v2alpha.IListEnrolledSolutionsResponse, + ( + | protos.google.cloud.retail.v2alpha.IListEnrolledSolutionsRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('listEnrolledSolutions response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Gets the {@link protos.google.cloud.retail.v2alpha.LoggingConfig|LoggingConfig} of the - * requested project. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. Full LoggingConfig resource name. Format: - * projects/{project_number}/loggingConfig - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.LoggingConfig|LoggingConfig}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/project_service.get_logging_config.js - * region_tag:retail_v2alpha_generated_ProjectService_GetLoggingConfig_async - */ + /** + * Gets the {@link protos.google.cloud.retail.v2alpha.LoggingConfig|LoggingConfig} of the + * requested project. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Full LoggingConfig resource name. Format: + * projects/{project_number}/loggingConfig + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.LoggingConfig|LoggingConfig}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/project_service.get_logging_config.js + * region_tag:retail_v2alpha_generated_ProjectService_GetLoggingConfig_async + */ getLoggingConfig( - request?: protos.google.cloud.retail.v2alpha.IGetLoggingConfigRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.retail.v2alpha.ILoggingConfig, - protos.google.cloud.retail.v2alpha.IGetLoggingConfigRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.IGetLoggingConfigRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.ILoggingConfig, + protos.google.cloud.retail.v2alpha.IGetLoggingConfigRequest | undefined, + {} | undefined, + ] + >; getLoggingConfig( - request: protos.google.cloud.retail.v2alpha.IGetLoggingConfigRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.retail.v2alpha.ILoggingConfig, - protos.google.cloud.retail.v2alpha.IGetLoggingConfigRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IGetLoggingConfigRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.retail.v2alpha.ILoggingConfig, + | protos.google.cloud.retail.v2alpha.IGetLoggingConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getLoggingConfig( - request: protos.google.cloud.retail.v2alpha.IGetLoggingConfigRequest, - callback: Callback< - protos.google.cloud.retail.v2alpha.ILoggingConfig, - protos.google.cloud.retail.v2alpha.IGetLoggingConfigRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IGetLoggingConfigRequest, + callback: Callback< + protos.google.cloud.retail.v2alpha.ILoggingConfig, + | protos.google.cloud.retail.v2alpha.IGetLoggingConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getLoggingConfig( - request?: protos.google.cloud.retail.v2alpha.IGetLoggingConfigRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.cloud.retail.v2alpha.IGetLoggingConfigRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.retail.v2alpha.ILoggingConfig, - protos.google.cloud.retail.v2alpha.IGetLoggingConfigRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.cloud.retail.v2alpha.ILoggingConfig, - protos.google.cloud.retail.v2alpha.IGetLoggingConfigRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.retail.v2alpha.ILoggingConfig, - protos.google.cloud.retail.v2alpha.IGetLoggingConfigRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.retail.v2alpha.IGetLoggingConfigRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.retail.v2alpha.ILoggingConfig, + | protos.google.cloud.retail.v2alpha.IGetLoggingConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.ILoggingConfig, + protos.google.cloud.retail.v2alpha.IGetLoggingConfigRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getLoggingConfig request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.retail.v2alpha.ILoggingConfig, - protos.google.cloud.retail.v2alpha.IGetLoggingConfigRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.retail.v2alpha.ILoggingConfig, + | protos.google.cloud.retail.v2alpha.IGetLoggingConfigRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getLoggingConfig response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getLoggingConfig(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.retail.v2alpha.ILoggingConfig, - protos.google.cloud.retail.v2alpha.IGetLoggingConfigRequest|undefined, - {}|undefined - ]) => { - this._log.info('getLoggingConfig response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getLoggingConfig(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.retail.v2alpha.ILoggingConfig, + ( + | protos.google.cloud.retail.v2alpha.IGetLoggingConfigRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('getLoggingConfig response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Updates the {@link protos.google.cloud.retail.v2alpha.LoggingConfig|LoggingConfig} of - * the requested project. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.cloud.retail.v2alpha.LoggingConfig} request.loggingConfig - * Required. The {@link protos.google.cloud.retail.v2alpha.LoggingConfig|LoggingConfig} to - * update. - * - * If the caller does not have permission to update the - * {@link protos.google.cloud.retail.v2alpha.LoggingConfig|LoggingConfig}, then a - * PERMISSION_DENIED error is returned. - * - * If the {@link protos.google.cloud.retail.v2alpha.LoggingConfig|LoggingConfig} to update - * does not exist, a NOT_FOUND error is returned. - * @param {google.protobuf.FieldMask} request.updateMask - * Indicates which fields in the provided - * {@link protos.google.cloud.retail.v2alpha.LoggingConfig|LoggingConfig} to update. The - * following are the only supported fields: - * - * * {@link protos.google.cloud.retail.v2alpha.LoggingConfig.default_log_generation_rule|LoggingConfig.default_log_generation_rule} - * * {@link protos.google.cloud.retail.v2alpha.LoggingConfig.service_log_generation_rules|LoggingConfig.service_log_generation_rules} - * - * If not set, all supported fields are updated. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.LoggingConfig|LoggingConfig}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/project_service.update_logging_config.js - * region_tag:retail_v2alpha_generated_ProjectService_UpdateLoggingConfig_async - */ + /** + * Updates the {@link protos.google.cloud.retail.v2alpha.LoggingConfig|LoggingConfig} of + * the requested project. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.cloud.retail.v2alpha.LoggingConfig} request.loggingConfig + * Required. The {@link protos.google.cloud.retail.v2alpha.LoggingConfig|LoggingConfig} to + * update. + * + * If the caller does not have permission to update the + * {@link protos.google.cloud.retail.v2alpha.LoggingConfig|LoggingConfig}, then a + * PERMISSION_DENIED error is returned. + * + * If the {@link protos.google.cloud.retail.v2alpha.LoggingConfig|LoggingConfig} to update + * does not exist, a NOT_FOUND error is returned. + * @param {google.protobuf.FieldMask} request.updateMask + * Indicates which fields in the provided + * {@link protos.google.cloud.retail.v2alpha.LoggingConfig|LoggingConfig} to update. The + * following are the only supported fields: + * + * * {@link protos.google.cloud.retail.v2alpha.LoggingConfig.default_log_generation_rule|LoggingConfig.default_log_generation_rule} + * * {@link protos.google.cloud.retail.v2alpha.LoggingConfig.service_log_generation_rules|LoggingConfig.service_log_generation_rules} + * + * If not set, all supported fields are updated. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.LoggingConfig|LoggingConfig}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/project_service.update_logging_config.js + * region_tag:retail_v2alpha_generated_ProjectService_UpdateLoggingConfig_async + */ updateLoggingConfig( - request?: protos.google.cloud.retail.v2alpha.IUpdateLoggingConfigRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.retail.v2alpha.ILoggingConfig, - protos.google.cloud.retail.v2alpha.IUpdateLoggingConfigRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.IUpdateLoggingConfigRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.ILoggingConfig, + ( + | protos.google.cloud.retail.v2alpha.IUpdateLoggingConfigRequest + | undefined + ), + {} | undefined, + ] + >; updateLoggingConfig( - request: protos.google.cloud.retail.v2alpha.IUpdateLoggingConfigRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.retail.v2alpha.ILoggingConfig, - protos.google.cloud.retail.v2alpha.IUpdateLoggingConfigRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IUpdateLoggingConfigRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.retail.v2alpha.ILoggingConfig, + | protos.google.cloud.retail.v2alpha.IUpdateLoggingConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateLoggingConfig( - request: protos.google.cloud.retail.v2alpha.IUpdateLoggingConfigRequest, - callback: Callback< - protos.google.cloud.retail.v2alpha.ILoggingConfig, - protos.google.cloud.retail.v2alpha.IUpdateLoggingConfigRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IUpdateLoggingConfigRequest, + callback: Callback< + protos.google.cloud.retail.v2alpha.ILoggingConfig, + | protos.google.cloud.retail.v2alpha.IUpdateLoggingConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateLoggingConfig( - request?: protos.google.cloud.retail.v2alpha.IUpdateLoggingConfigRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.retail.v2alpha.ILoggingConfig, - protos.google.cloud.retail.v2alpha.IUpdateLoggingConfigRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.retail.v2alpha.IUpdateLoggingConfigRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.retail.v2alpha.ILoggingConfig, - protos.google.cloud.retail.v2alpha.IUpdateLoggingConfigRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.retail.v2alpha.ILoggingConfig, - protos.google.cloud.retail.v2alpha.IUpdateLoggingConfigRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.retail.v2alpha.IUpdateLoggingConfigRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.retail.v2alpha.ILoggingConfig, + | protos.google.cloud.retail.v2alpha.IUpdateLoggingConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.ILoggingConfig, + ( + | protos.google.cloud.retail.v2alpha.IUpdateLoggingConfigRequest + | undefined + ), + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'logging_config.name': request.loggingConfig!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'logging_config.name': request.loggingConfig!.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateLoggingConfig request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.retail.v2alpha.ILoggingConfig, - protos.google.cloud.retail.v2alpha.IUpdateLoggingConfigRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.retail.v2alpha.ILoggingConfig, + | protos.google.cloud.retail.v2alpha.IUpdateLoggingConfigRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateLoggingConfig response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.updateLoggingConfig(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.retail.v2alpha.ILoggingConfig, - protos.google.cloud.retail.v2alpha.IUpdateLoggingConfigRequest|undefined, - {}|undefined - ]) => { - this._log.info('updateLoggingConfig response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateLoggingConfig(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.retail.v2alpha.ILoggingConfig, + ( + | protos.google.cloud.retail.v2alpha.IUpdateLoggingConfigRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('updateLoggingConfig response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Get the {@link protos.google.cloud.retail.v2alpha.AlertConfig|AlertConfig} of the - * requested project. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. Full AlertConfig resource name. Format: - * projects/{project_number}/alertConfig - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.AlertConfig|AlertConfig}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/project_service.get_alert_config.js - * region_tag:retail_v2alpha_generated_ProjectService_GetAlertConfig_async - */ + /** + * Get the {@link protos.google.cloud.retail.v2alpha.AlertConfig|AlertConfig} of the + * requested project. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Full AlertConfig resource name. Format: + * projects/{project_number}/alertConfig + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.AlertConfig|AlertConfig}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/project_service.get_alert_config.js + * region_tag:retail_v2alpha_generated_ProjectService_GetAlertConfig_async + */ getAlertConfig( - request?: protos.google.cloud.retail.v2alpha.IGetAlertConfigRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.retail.v2alpha.IAlertConfig, - protos.google.cloud.retail.v2alpha.IGetAlertConfigRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.IGetAlertConfigRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IAlertConfig, + protos.google.cloud.retail.v2alpha.IGetAlertConfigRequest | undefined, + {} | undefined, + ] + >; getAlertConfig( - request: protos.google.cloud.retail.v2alpha.IGetAlertConfigRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.retail.v2alpha.IAlertConfig, - protos.google.cloud.retail.v2alpha.IGetAlertConfigRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IGetAlertConfigRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.retail.v2alpha.IAlertConfig, + | protos.google.cloud.retail.v2alpha.IGetAlertConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getAlertConfig( - request: protos.google.cloud.retail.v2alpha.IGetAlertConfigRequest, - callback: Callback< - protos.google.cloud.retail.v2alpha.IAlertConfig, - protos.google.cloud.retail.v2alpha.IGetAlertConfigRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IGetAlertConfigRequest, + callback: Callback< + protos.google.cloud.retail.v2alpha.IAlertConfig, + | protos.google.cloud.retail.v2alpha.IGetAlertConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getAlertConfig( - request?: protos.google.cloud.retail.v2alpha.IGetAlertConfigRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.retail.v2alpha.IAlertConfig, - protos.google.cloud.retail.v2alpha.IGetAlertConfigRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.retail.v2alpha.IGetAlertConfigRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.retail.v2alpha.IAlertConfig, - protos.google.cloud.retail.v2alpha.IGetAlertConfigRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.retail.v2alpha.IAlertConfig, - protos.google.cloud.retail.v2alpha.IGetAlertConfigRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.retail.v2alpha.IGetAlertConfigRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.retail.v2alpha.IAlertConfig, + | protos.google.cloud.retail.v2alpha.IGetAlertConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IAlertConfig, + protos.google.cloud.retail.v2alpha.IGetAlertConfigRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getAlertConfig request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.retail.v2alpha.IAlertConfig, - protos.google.cloud.retail.v2alpha.IGetAlertConfigRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.retail.v2alpha.IAlertConfig, + | protos.google.cloud.retail.v2alpha.IGetAlertConfigRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getAlertConfig response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getAlertConfig(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.retail.v2alpha.IAlertConfig, - protos.google.cloud.retail.v2alpha.IGetAlertConfigRequest|undefined, - {}|undefined - ]) => { - this._log.info('getAlertConfig response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getAlertConfig(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.retail.v2alpha.IAlertConfig, + protos.google.cloud.retail.v2alpha.IGetAlertConfigRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getAlertConfig response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Update the alert config of the requested project. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.cloud.retail.v2alpha.AlertConfig} request.alertConfig - * Required. The {@link protos.google.cloud.retail.v2alpha.AlertConfig|AlertConfig} to - * update. - * - * If the caller does not have permission to update the - * {@link protos.google.cloud.retail.v2alpha.AlertConfig|AlertConfig}, then a - * PERMISSION_DENIED error is returned. - * - * If the {@link protos.google.cloud.retail.v2alpha.AlertConfig|AlertConfig} to update - * does not exist, a NOT_FOUND error is returned. - * @param {google.protobuf.FieldMask} request.updateMask - * Indicates which fields in the provided - * {@link protos.google.cloud.retail.v2alpha.AlertConfig|AlertConfig} to update. If not - * set, all supported fields are updated. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.AlertConfig|AlertConfig}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/project_service.update_alert_config.js - * region_tag:retail_v2alpha_generated_ProjectService_UpdateAlertConfig_async - */ + /** + * Update the alert config of the requested project. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.cloud.retail.v2alpha.AlertConfig} request.alertConfig + * Required. The {@link protos.google.cloud.retail.v2alpha.AlertConfig|AlertConfig} to + * update. + * + * If the caller does not have permission to update the + * {@link protos.google.cloud.retail.v2alpha.AlertConfig|AlertConfig}, then a + * PERMISSION_DENIED error is returned. + * + * If the {@link protos.google.cloud.retail.v2alpha.AlertConfig|AlertConfig} to update + * does not exist, a NOT_FOUND error is returned. + * @param {google.protobuf.FieldMask} request.updateMask + * Indicates which fields in the provided + * {@link protos.google.cloud.retail.v2alpha.AlertConfig|AlertConfig} to update. If not + * set, all supported fields are updated. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.AlertConfig|AlertConfig}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/project_service.update_alert_config.js + * region_tag:retail_v2alpha_generated_ProjectService_UpdateAlertConfig_async + */ updateAlertConfig( - request?: protos.google.cloud.retail.v2alpha.IUpdateAlertConfigRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.retail.v2alpha.IAlertConfig, - protos.google.cloud.retail.v2alpha.IUpdateAlertConfigRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.IUpdateAlertConfigRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IAlertConfig, + protos.google.cloud.retail.v2alpha.IUpdateAlertConfigRequest | undefined, + {} | undefined, + ] + >; updateAlertConfig( - request: protos.google.cloud.retail.v2alpha.IUpdateAlertConfigRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.retail.v2alpha.IAlertConfig, - protos.google.cloud.retail.v2alpha.IUpdateAlertConfigRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IUpdateAlertConfigRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.retail.v2alpha.IAlertConfig, + | protos.google.cloud.retail.v2alpha.IUpdateAlertConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateAlertConfig( - request: protos.google.cloud.retail.v2alpha.IUpdateAlertConfigRequest, - callback: Callback< - protos.google.cloud.retail.v2alpha.IAlertConfig, - protos.google.cloud.retail.v2alpha.IUpdateAlertConfigRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IUpdateAlertConfigRequest, + callback: Callback< + protos.google.cloud.retail.v2alpha.IAlertConfig, + | protos.google.cloud.retail.v2alpha.IUpdateAlertConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateAlertConfig( - request?: protos.google.cloud.retail.v2alpha.IUpdateAlertConfigRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.retail.v2alpha.IAlertConfig, - protos.google.cloud.retail.v2alpha.IUpdateAlertConfigRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.retail.v2alpha.IUpdateAlertConfigRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.retail.v2alpha.IAlertConfig, - protos.google.cloud.retail.v2alpha.IUpdateAlertConfigRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.retail.v2alpha.IAlertConfig, - protos.google.cloud.retail.v2alpha.IUpdateAlertConfigRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.retail.v2alpha.IUpdateAlertConfigRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.retail.v2alpha.IAlertConfig, + | protos.google.cloud.retail.v2alpha.IUpdateAlertConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IAlertConfig, + protos.google.cloud.retail.v2alpha.IUpdateAlertConfigRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'alert_config.name': request.alertConfig!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'alert_config.name': request.alertConfig!.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateAlertConfig request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.retail.v2alpha.IAlertConfig, - protos.google.cloud.retail.v2alpha.IUpdateAlertConfigRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.retail.v2alpha.IAlertConfig, + | protos.google.cloud.retail.v2alpha.IUpdateAlertConfigRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateAlertConfig response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.updateAlertConfig(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.retail.v2alpha.IAlertConfig, - protos.google.cloud.retail.v2alpha.IUpdateAlertConfigRequest|undefined, - {}|undefined - ]) => { - this._log.info('updateAlertConfig response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateAlertConfig(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.retail.v2alpha.IAlertConfig, + ( + | protos.google.cloud.retail.v2alpha.IUpdateAlertConfigRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('updateAlertConfig response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * The method enrolls a solution of type [Retail - * Search][google.cloud.retail.v2alpha.SolutionType.SOLUTION_TYPE_SEARCH] - * into a project. - * - * The [Recommendations AI solution - * type][google.cloud.retail.v2alpha.SolutionType.SOLUTION_TYPE_RECOMMENDATION] - * is enrolled by default when your project enables Retail API, so you don't - * need to call the enrollSolution method for recommendations. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.project - * Required. Full resource name of parent. Format: - * `projects/{project_number_or_id}` - * @param {google.cloud.retail.v2alpha.SolutionType} request.solution - * Required. Solution to enroll. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing - * a long running operation. Its `promise()` method returns a promise - * you can `await` for. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/project_service.enroll_solution.js - * region_tag:retail_v2alpha_generated_ProjectService_EnrollSolution_async - */ + /** + * The method enrolls a solution of type [Retail + * Search][google.cloud.retail.v2alpha.SolutionType.SOLUTION_TYPE_SEARCH] + * into a project. + * + * The [Recommendations AI solution + * type][google.cloud.retail.v2alpha.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + * is enrolled by default when your project enables Retail API, so you don't + * need to call the enrollSolution method for recommendations. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.project + * Required. Full resource name of parent. Format: + * `projects/{project_number_or_id}` + * @param {google.cloud.retail.v2alpha.SolutionType} request.solution + * Required. Solution to enroll. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/project_service.enroll_solution.js + * region_tag:retail_v2alpha_generated_ProjectService_EnrollSolution_async + */ enrollSolution( - request?: protos.google.cloud.retail.v2alpha.IEnrollSolutionRequest, - options?: CallOptions): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.IEnrollSolutionRequest, + options?: CallOptions, + ): Promise< + [ + LROperation< + protos.google.cloud.retail.v2alpha.IEnrollSolutionResponse, + protos.google.cloud.retail.v2alpha.IEnrollSolutionMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; enrollSolution( - request: protos.google.cloud.retail.v2alpha.IEnrollSolutionRequest, - options: CallOptions, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IEnrollSolutionRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IEnrollSolutionResponse, + protos.google.cloud.retail.v2alpha.IEnrollSolutionMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; enrollSolution( - request: protos.google.cloud.retail.v2alpha.IEnrollSolutionRequest, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IEnrollSolutionRequest, + callback: Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IEnrollSolutionResponse, + protos.google.cloud.retail.v2alpha.IEnrollSolutionMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; enrollSolution( - request?: protos.google.cloud.retail.v2alpha.IEnrollSolutionRequest, - optionsOrCallback?: CallOptions|Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>, - callback?: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>|void { + request?: protos.google.cloud.retail.v2alpha.IEnrollSolutionRequest, + optionsOrCallback?: + | CallOptions + | Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IEnrollSolutionResponse, + protos.google.cloud.retail.v2alpha.IEnrollSolutionMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + callback?: Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IEnrollSolutionResponse, + protos.google.cloud.retail.v2alpha.IEnrollSolutionMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + LROperation< + protos.google.cloud.retail.v2alpha.IEnrollSolutionResponse, + protos.google.cloud.retail.v2alpha.IEnrollSolutionMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'project': request.project ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + project: request.project ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IEnrollSolutionResponse, + protos.google.cloud.retail.v2alpha.IEnrollSolutionMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, rawResponse, _) => { this._log.info('enrollSolution response %j', rawResponse); callback!(error, response, rawResponse, _); // We verified callback above. } : undefined; this._log.info('enrollSolution request %j', request); - return this.innerApiCalls.enrollSolution(request, options, wrappedCallback) - ?.then(([response, rawResponse, _]: [ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]) => { - this._log.info('enrollSolution response %j', rawResponse); - return [response, rawResponse, _]; - }); + return this.innerApiCalls + .enrollSolution(request, options, wrappedCallback) + ?.then( + ([response, rawResponse, _]: [ + LROperation< + protos.google.cloud.retail.v2alpha.IEnrollSolutionResponse, + protos.google.cloud.retail.v2alpha.IEnrollSolutionMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ]) => { + this._log.info('enrollSolution response %j', rawResponse); + return [response, rawResponse, _]; + }, + ); } -/** - * Check the status of the long running operation returned by `enrollSolution()`. - * @param {String} name - * The operation name that will be passed. - * @returns {Promise} - The promise which resolves to an object. - * The decoded operation object has result and metadata field to get information from. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/project_service.enroll_solution.js - * region_tag:retail_v2alpha_generated_ProjectService_EnrollSolution_async - */ - async checkEnrollSolutionProgress(name: string): Promise>{ + /** + * Check the status of the long running operation returned by `enrollSolution()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/project_service.enroll_solution.js + * region_tag:retail_v2alpha_generated_ProjectService_EnrollSolution_async + */ + async checkEnrollSolutionProgress( + name: string, + ): Promise< + LROperation< + protos.google.cloud.retail.v2alpha.EnrollSolutionResponse, + protos.google.cloud.retail.v2alpha.EnrollSolutionMetadata + > + > { this._log.info('enrollSolution long-running'); - const request = new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest({name}); + const request = + new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( + { name }, + ); const [operation] = await this.operationsClient.getOperation(request); - const decodeOperation = new this._gaxModule.Operation(operation, this.descriptors.longrunning.enrollSolution, this._gaxModule.createDefaultBackoffSettings()); - return decodeOperation as LROperation; + const decodeOperation = new this._gaxModule.Operation( + operation, + this.descriptors.longrunning.enrollSolution, + this._gaxModule.createDefaultBackoffSettings(), + ); + return decodeOperation as LROperation< + protos.google.cloud.retail.v2alpha.EnrollSolutionResponse, + protos.google.cloud.retail.v2alpha.EnrollSolutionMetadata + >; } // -------------------- // -- Path templates -- @@ -1218,7 +1649,7 @@ export class ProjectServiceClient { * @param {string} project * @returns {string} Resource name string. */ - alertConfigPath(project:string) { + alertConfigPath(project: string) { return this.pathTemplates.alertConfigPathTemplate.render({ project: project, }); @@ -1232,7 +1663,8 @@ export class ProjectServiceClient { * @returns {string} A string representing the project. */ matchProjectFromAlertConfigName(alertConfigName: string) { - return this.pathTemplates.alertConfigPathTemplate.match(alertConfigName).project; + return this.pathTemplates.alertConfigPathTemplate.match(alertConfigName) + .project; } /** @@ -1243,7 +1675,7 @@ export class ProjectServiceClient { * @param {string} catalog * @returns {string} Resource name string. */ - attributesConfigPath(project:string,location:string,catalog:string) { + attributesConfigPath(project: string, location: string, catalog: string) { return this.pathTemplates.attributesConfigPathTemplate.render({ project: project, location: location, @@ -1259,7 +1691,9 @@ export class ProjectServiceClient { * @returns {string} A string representing the project. */ matchProjectFromAttributesConfigName(attributesConfigName: string) { - return this.pathTemplates.attributesConfigPathTemplate.match(attributesConfigName).project; + return this.pathTemplates.attributesConfigPathTemplate.match( + attributesConfigName, + ).project; } /** @@ -1270,7 +1704,9 @@ export class ProjectServiceClient { * @returns {string} A string representing the location. */ matchLocationFromAttributesConfigName(attributesConfigName: string) { - return this.pathTemplates.attributesConfigPathTemplate.match(attributesConfigName).location; + return this.pathTemplates.attributesConfigPathTemplate.match( + attributesConfigName, + ).location; } /** @@ -1281,7 +1717,9 @@ export class ProjectServiceClient { * @returns {string} A string representing the catalog. */ matchCatalogFromAttributesConfigName(attributesConfigName: string) { - return this.pathTemplates.attributesConfigPathTemplate.match(attributesConfigName).catalog; + return this.pathTemplates.attributesConfigPathTemplate.match( + attributesConfigName, + ).catalog; } /** @@ -1293,7 +1731,12 @@ export class ProjectServiceClient { * @param {string} branch * @returns {string} Resource name string. */ - branchPath(project:string,location:string,catalog:string,branch:string) { + branchPath( + project: string, + location: string, + catalog: string, + branch: string, + ) { return this.pathTemplates.branchPathTemplate.render({ project: project, location: location, @@ -1354,7 +1797,7 @@ export class ProjectServiceClient { * @param {string} catalog * @returns {string} Resource name string. */ - catalogPath(project:string,location:string,catalog:string) { + catalogPath(project: string, location: string, catalog: string) { return this.pathTemplates.catalogPathTemplate.render({ project: project, location: location, @@ -1403,7 +1846,7 @@ export class ProjectServiceClient { * @param {string} catalog * @returns {string} Resource name string. */ - completionConfigPath(project:string,location:string,catalog:string) { + completionConfigPath(project: string, location: string, catalog: string) { return this.pathTemplates.completionConfigPathTemplate.render({ project: project, location: location, @@ -1419,7 +1862,9 @@ export class ProjectServiceClient { * @returns {string} A string representing the project. */ matchProjectFromCompletionConfigName(completionConfigName: string) { - return this.pathTemplates.completionConfigPathTemplate.match(completionConfigName).project; + return this.pathTemplates.completionConfigPathTemplate.match( + completionConfigName, + ).project; } /** @@ -1430,7 +1875,9 @@ export class ProjectServiceClient { * @returns {string} A string representing the location. */ matchLocationFromCompletionConfigName(completionConfigName: string) { - return this.pathTemplates.completionConfigPathTemplate.match(completionConfigName).location; + return this.pathTemplates.completionConfigPathTemplate.match( + completionConfigName, + ).location; } /** @@ -1441,7 +1888,9 @@ export class ProjectServiceClient { * @returns {string} A string representing the catalog. */ matchCatalogFromCompletionConfigName(completionConfigName: string) { - return this.pathTemplates.completionConfigPathTemplate.match(completionConfigName).catalog; + return this.pathTemplates.completionConfigPathTemplate.match( + completionConfigName, + ).catalog; } /** @@ -1453,7 +1902,12 @@ export class ProjectServiceClient { * @param {string} control * @returns {string} Resource name string. */ - controlPath(project:string,location:string,catalog:string,control:string) { + controlPath( + project: string, + location: string, + catalog: string, + control: string, + ) { return this.pathTemplates.controlPathTemplate.render({ project: project, location: location, @@ -1512,7 +1966,7 @@ export class ProjectServiceClient { * @param {string} project * @returns {string} Resource name string. */ - loggingConfigPath(project:string) { + loggingConfigPath(project: string) { return this.pathTemplates.loggingConfigPathTemplate.render({ project: project, }); @@ -1526,7 +1980,8 @@ export class ProjectServiceClient { * @returns {string} A string representing the project. */ matchProjectFromLoggingConfigName(loggingConfigName: string) { - return this.pathTemplates.loggingConfigPathTemplate.match(loggingConfigName).project; + return this.pathTemplates.loggingConfigPathTemplate.match(loggingConfigName) + .project; } /** @@ -1538,7 +1993,12 @@ export class ProjectServiceClient { * @param {string} merchant_center_account_link * @returns {string} Resource name string. */ - merchantCenterAccountLinkPath(project:string,location:string,catalog:string,merchantCenterAccountLink:string) { + merchantCenterAccountLinkPath( + project: string, + location: string, + catalog: string, + merchantCenterAccountLink: string, + ) { return this.pathTemplates.merchantCenterAccountLinkPathTemplate.render({ project: project, location: location, @@ -1554,8 +2014,12 @@ export class ProjectServiceClient { * A fully-qualified path representing MerchantCenterAccountLink resource. * @returns {string} A string representing the project. */ - matchProjectFromMerchantCenterAccountLinkName(merchantCenterAccountLinkName: string) { - return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match(merchantCenterAccountLinkName).project; + matchProjectFromMerchantCenterAccountLinkName( + merchantCenterAccountLinkName: string, + ) { + return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match( + merchantCenterAccountLinkName, + ).project; } /** @@ -1565,8 +2029,12 @@ export class ProjectServiceClient { * A fully-qualified path representing MerchantCenterAccountLink resource. * @returns {string} A string representing the location. */ - matchLocationFromMerchantCenterAccountLinkName(merchantCenterAccountLinkName: string) { - return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match(merchantCenterAccountLinkName).location; + matchLocationFromMerchantCenterAccountLinkName( + merchantCenterAccountLinkName: string, + ) { + return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match( + merchantCenterAccountLinkName, + ).location; } /** @@ -1576,8 +2044,12 @@ export class ProjectServiceClient { * A fully-qualified path representing MerchantCenterAccountLink resource. * @returns {string} A string representing the catalog. */ - matchCatalogFromMerchantCenterAccountLinkName(merchantCenterAccountLinkName: string) { - return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match(merchantCenterAccountLinkName).catalog; + matchCatalogFromMerchantCenterAccountLinkName( + merchantCenterAccountLinkName: string, + ) { + return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match( + merchantCenterAccountLinkName, + ).catalog; } /** @@ -1587,8 +2059,12 @@ export class ProjectServiceClient { * A fully-qualified path representing MerchantCenterAccountLink resource. * @returns {string} A string representing the merchant_center_account_link. */ - matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName(merchantCenterAccountLinkName: string) { - return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match(merchantCenterAccountLinkName).merchant_center_account_link; + matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName( + merchantCenterAccountLinkName: string, + ) { + return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match( + merchantCenterAccountLinkName, + ).merchant_center_account_link; } /** @@ -1600,7 +2076,7 @@ export class ProjectServiceClient { * @param {string} model * @returns {string} Resource name string. */ - modelPath(project:string,location:string,catalog:string,model:string) { + modelPath(project: string, location: string, catalog: string, model: string) { return this.pathTemplates.modelPathTemplate.render({ project: project, location: location, @@ -1663,7 +2139,13 @@ export class ProjectServiceClient { * @param {string} product * @returns {string} Resource name string. */ - productPath(project:string,location:string,catalog:string,branch:string,product:string) { + productPath( + project: string, + location: string, + catalog: string, + branch: string, + product: string, + ) { return this.pathTemplates.productPathTemplate.render({ project: project, location: location, @@ -1734,7 +2216,7 @@ export class ProjectServiceClient { * @param {string} project * @returns {string} Resource name string. */ - projectPath(project:string) { + projectPath(project: string) { return this.pathTemplates.projectPathTemplate.render({ project: project, }); @@ -1757,7 +2239,7 @@ export class ProjectServiceClient { * @param {string} project * @returns {string} Resource name string. */ - retailProjectPath(project:string) { + retailProjectPath(project: string) { return this.pathTemplates.retailProjectPathTemplate.render({ project: project, }); @@ -1771,7 +2253,8 @@ export class ProjectServiceClient { * @returns {string} A string representing the project. */ matchProjectFromRetailProjectName(retailProjectName: string) { - return this.pathTemplates.retailProjectPathTemplate.match(retailProjectName).project; + return this.pathTemplates.retailProjectPathTemplate.match(retailProjectName) + .project; } /** @@ -1783,7 +2266,12 @@ export class ProjectServiceClient { * @param {string} serving_config * @returns {string} Resource name string. */ - servingConfigPath(project:string,location:string,catalog:string,servingConfig:string) { + servingConfigPath( + project: string, + location: string, + catalog: string, + servingConfig: string, + ) { return this.pathTemplates.servingConfigPathTemplate.render({ project: project, location: location, @@ -1800,7 +2288,8 @@ export class ProjectServiceClient { * @returns {string} A string representing the project. */ matchProjectFromServingConfigName(servingConfigName: string) { - return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName).project; + return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName) + .project; } /** @@ -1811,7 +2300,8 @@ export class ProjectServiceClient { * @returns {string} A string representing the location. */ matchLocationFromServingConfigName(servingConfigName: string) { - return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName).location; + return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName) + .location; } /** @@ -1822,7 +2312,8 @@ export class ProjectServiceClient { * @returns {string} A string representing the catalog. */ matchCatalogFromServingConfigName(servingConfigName: string) { - return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName).catalog; + return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName) + .catalog; } /** @@ -1833,7 +2324,8 @@ export class ProjectServiceClient { * @returns {string} A string representing the serving_config. */ matchServingConfigFromServingConfigName(servingConfigName: string) { - return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName).serving_config; + return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName) + .serving_config; } /** @@ -1844,7 +2336,7 @@ export class ProjectServiceClient { */ close(): Promise { if (this.projectServiceStub && !this._terminated) { - return this.projectServiceStub.then(stub => { + return this.projectServiceStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -1853,4 +2345,4 @@ export class ProjectServiceClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/core/generator/gapic-generator-typescript/baselines/retail/src/v2alpha/search_service_client.ts.baseline b/core/generator/gapic-generator-typescript/baselines/retail/src/v2alpha/search_service_client.ts.baseline index ac948b7514ba..ac613eef9724 100644 --- a/core/generator/gapic-generator-typescript/baselines/retail/src/v2alpha/search_service_client.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/retail/src/v2alpha/search_service_client.ts.baseline @@ -18,11 +18,18 @@ /* global window */ import type * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions, PaginationCallback, GaxCall} from 'google-gax'; -import {Transform} from 'stream'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + PaginationCallback, + GaxCall, +} from 'google-gax'; +import { Transform } from 'stream'; import * as protos from '../../protos/protos'; import jsonProtos = require('../../protos/protos.json'); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; /** * Client JSON configuration object, loaded from @@ -47,7 +54,7 @@ export class SearchServiceClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('retail'); @@ -60,9 +67,9 @@ export class SearchServiceClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; - searchServiceStub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; + searchServiceStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of SearchServiceClient. @@ -103,21 +110,42 @@ export class SearchServiceClient { * const client = new SearchServiceClient({fallback: true}, gax); * ``` */ - constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { // Ensure that options include all the required fields. const staticMembers = this.constructor as typeof SearchServiceClient; - if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { - throw new Error('Please set either universe_domain or universeDomain, but not both.'); + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); } - const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; - this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; this._servicePath = 'retail.' + this._universeDomain; - const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; - const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. if (servicePath !== this._servicePath && !('scopes' in opts)) { @@ -139,7 +167,7 @@ export class SearchServiceClient { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; @@ -153,10 +181,7 @@ export class SearchServiceClient { } // Determine the client header string. - const clientHeader = [ - `gax/${this._gaxModule.version}`, - `gapic/${version}`, - ]; + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/${process.versions.node}`); } else { @@ -178,43 +203,43 @@ export class SearchServiceClient { // Create useful helper objects for these. this.pathTemplates = { alertConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/alertConfig' + 'projects/{project}/alertConfig', ), attributesConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/attributesConfig' + 'projects/{project}/locations/{location}/catalogs/{catalog}/attributesConfig', ), branchPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}', ), catalogPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}' + 'projects/{project}/locations/{location}/catalogs/{catalog}', ), completionConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/completionConfig' + 'projects/{project}/locations/{location}/catalogs/{catalog}/completionConfig', ), controlPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/controls/{control}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/controls/{control}', ), experimentPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/experiments/{experiment}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/experiments/{experiment}', ), loggingConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/loggingConfig' + 'projects/{project}/loggingConfig', ), merchantCenterAccountLinkPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/merchantCenterAccountLinks/{merchant_center_account_link}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/merchantCenterAccountLinks/{merchant_center_account_link}', ), modelPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/models/{model}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/models/{model}', ), productPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}', ), retailProjectPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/retailProject' + 'projects/{project}/retailProject', ), servingConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/servingConfigs/{serving_config}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/servingConfigs/{serving_config}', ), }; @@ -222,14 +247,20 @@ export class SearchServiceClient { // (e.g. 50 results at a time, with tokens to get subsequent // pages). Denote the keys used for pagination and results. this.descriptors.page = { - search: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'results') + search: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'results', + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.cloud.retail.v2alpha.SearchService', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.cloud.retail.v2alpha.SearchService', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + { 'x-goog-api-client': clientHeader.join(' ') }, + ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -260,37 +291,40 @@ export class SearchServiceClient { // Put together the "service stub" for // google.cloud.retail.v2alpha.SearchService. this.searchServiceStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.cloud.retail.v2alpha.SearchService') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.cloud.retail.v2alpha.SearchService', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.cloud.retail.v2alpha.SearchService, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts, + this._providedCustomServicePath, + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const searchServiceStubMethods = - ['search']; + const searchServiceStubMethods = ['search']; for (const methodName of searchServiceStubMethods) { const callPromise = this.searchServiceStub.then( - stub => (...args: Array<{}>) => { - if (this._terminated) { - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error|null|undefined) => () => { + (stub) => + (...args: Array<{}>) => { + if (this._terminated) { + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { throw err; - }); + }, + ); - const descriptor = - this.descriptors.page[methodName] || - undefined; + const descriptor = this.descriptors.page[methodName] || undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -305,8 +339,14 @@ export class SearchServiceClient { * @returns {string} The DNS address for this service. */ static get servicePath() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'retail.googleapis.com'; } @@ -317,8 +357,14 @@ export class SearchServiceClient { * @returns {string} The DNS address for this service. */ static get apiEndpoint() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'retail.googleapis.com'; } @@ -349,9 +395,7 @@ export class SearchServiceClient { * @returns {string[]} List of default scopes. */ static get scopes() { - return [ - 'https://www.googleapis.com/auth/cloud-platform' - ]; + return ['https://www.googleapis.com/auth/cloud-platform']; } getProjectId(): Promise; @@ -360,8 +404,9 @@ export class SearchServiceClient { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId(callback?: Callback): - Promise|void { + getProjectId( + callback?: Callback, + ): Promise | void { if (callback) { this.auth.getProjectId(callback); return; @@ -373,384 +418,399 @@ export class SearchServiceClient { // -- Service calls -- // ------------------- - /** - * Performs a search. - * - * This feature is only available for users who have Retail Search enabled. - * Enable Retail Search on Cloud Console before using this feature. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.placement - * Required. The resource name of the Retail Search serving config, such as - * `projects/* /locations/global/catalogs/default_catalog/servingConfigs/default_serving_config` - * or the name of the legacy placement resource, such as - * `projects/* /locations/global/catalogs/default_catalog/placements/default_search`. - * This field is used to identify the serving config name and the set - * of models that are used to make the search. - * @param {string} request.branch - * The branch resource name, such as - * `projects/* /locations/global/catalogs/default_catalog/branches/0`. - * - * Use "default_branch" as the branch ID or leave this field empty, to search - * products under the default branch. - * @param {string} request.query - * Raw search query. - * - * If this field is empty, the request is considered a category browsing - * request and returned results are based on - * {@link protos.google.cloud.retail.v2alpha.SearchRequest.filter|filter} and - * {@link protos.google.cloud.retail.v2alpha.SearchRequest.page_categories|page_categories}. - * @param {string} request.visitorId - * Required. A unique identifier for tracking visitors. For example, this - * could be implemented with an HTTP cookie, which should be able to uniquely - * identify a visitor on a single device. This unique identifier should not - * change if the visitor logs in or out of the website. - * - * This should be the same identifier as - * {@link protos.google.cloud.retail.v2alpha.UserEvent.visitor_id|UserEvent.visitor_id}. - * - * The field must be a UTF-8 encoded string with a length limit of 128 - * characters. Otherwise, an INVALID_ARGUMENT error is returned. - * @param {google.cloud.retail.v2alpha.UserInfo} request.userInfo - * User information. - * @param {number} request.pageSize - * Maximum number of {@link protos.google.cloud.retail.v2alpha.Product|Product}s to - * return. If unspecified, defaults to a reasonable value. The maximum allowed - * value is 120. Values above 120 will be coerced to 120. - * - * If this field is negative, an INVALID_ARGUMENT is returned. - * @param {string} request.pageToken - * A page token - * {@link protos.google.cloud.retail.v2alpha.SearchResponse.next_page_token|SearchResponse.next_page_token}, - * received from a previous - * {@link protos.google.cloud.retail.v2alpha.SearchService.Search|SearchService.Search} - * call. Provide this to retrieve the subsequent page. - * - * When paginating, all other parameters provided to - * {@link protos.google.cloud.retail.v2alpha.SearchService.Search|SearchService.Search} - * must match the call that provided the page token. Otherwise, an - * INVALID_ARGUMENT error is returned. - * @param {number} request.offset - * A 0-indexed integer that specifies the current offset (that is, starting - * result location, amongst the - * {@link protos.google.cloud.retail.v2alpha.Product|Product}s deemed by the API as - * relevant) in search results. This field is only considered if - * {@link protos.google.cloud.retail.v2alpha.SearchRequest.page_token|page_token} is - * unset. - * - * If this field is negative, an INVALID_ARGUMENT is returned. - * @param {string} request.filter - * The filter syntax consists of an expression language for constructing a - * predicate from one or more fields of the products being filtered. Filter - * expression is case-sensitive. For more information, see - * [Filter](https://cloud.google.com/retail/docs/filter-and-order#filter). - * - * If this field is unrecognizable, an INVALID_ARGUMENT is returned. - * @param {string} request.canonicalFilter - * The default filter that is applied when a user performs a search without - * checking any filters on the search page. - * - * The filter applied to every search request when quality improvement such as - * query expansion is needed. In the case a query does not have a sufficient - * amount of results this filter will be used to determine whether or not to - * enable the query expansion flow. The original filter will still be used for - * the query expanded search. - * This field is strongly recommended to achieve high search quality. - * - * For more information about filter syntax, see - * {@link protos.google.cloud.retail.v2alpha.SearchRequest.filter|SearchRequest.filter}. - * @param {string} request.orderBy - * The order in which products are returned. Products can be ordered by - * a field in an {@link protos.google.cloud.retail.v2alpha.Product|Product} object. Leave - * it unset if ordered by relevance. OrderBy expression is case-sensitive. For - * more information, see - * [Order](https://cloud.google.com/retail/docs/filter-and-order#order). - * - * If this field is unrecognizable, an INVALID_ARGUMENT is returned. - * @param {number[]} request.facetSpecs - * Facet specifications for faceted search. If empty, no facets are returned. - * - * A maximum of 200 values are allowed. Otherwise, an INVALID_ARGUMENT error - * is returned. - * @param {google.cloud.retail.v2alpha.SearchRequest.DynamicFacetSpec} request.dynamicFacetSpec - * Deprecated. Refer to https://cloud.google.com/retail/docs/configs#dynamic - * to enable dynamic facets. Do not set this field. - * - * The specification for dynamically generated facets. Notice that only - * textual facets can be dynamically generated. - * @param {google.cloud.retail.v2alpha.SearchRequest.BoostSpec} request.boostSpec - * Boost specification to boost certain products. For more information, see - * [Boost results](https://cloud.google.com/retail/docs/boosting). - * - * Notice that if both - * {@link protos.google.cloud.retail.v2alpha.ServingConfig.boost_control_ids|ServingConfig.boost_control_ids} - * and - * {@link protos.google.cloud.retail.v2alpha.SearchRequest.boost_spec|SearchRequest.boost_spec} - * are set, the boost conditions from both places are evaluated. If a search - * request matches multiple boost conditions, the final boost score is equal - * to the sum of the boost scores from all matched boost conditions. - * @param {google.cloud.retail.v2alpha.SearchRequest.QueryExpansionSpec} request.queryExpansionSpec - * The query expansion specification that specifies the conditions under which - * query expansion occurs. For more information, see [Query - * expansion](https://cloud.google.com/retail/docs/result-size#query_expansion). - * @param {google.cloud.retail.v2alpha.SearchRequest.RelevanceThreshold} request.relevanceThreshold - * The relevance threshold of the search results. - * - * Defaults to - * {@link protos.google.cloud.retail.v2alpha.SearchRequest.RelevanceThreshold.HIGH|RelevanceThreshold.HIGH}, - * which means only the most relevant results are shown, and the least number - * of results are returned. For more information, see [Adjust result - * size](https://cloud.google.com/retail/docs/result-size#relevance_thresholding). - * @param {string[]} request.variantRollupKeys - * The keys to fetch and rollup the matching - * {@link protos.google.cloud.retail.v2alpha.Product.Type.VARIANT|variant} - * {@link protos.google.cloud.retail.v2alpha.Product|Product}s attributes, - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo|FulfillmentInfo} or - * {@link protos.google.cloud.retail.v2alpha.LocalInventory|LocalInventory}s attributes. - * The attributes from all the matching - * {@link protos.google.cloud.retail.v2alpha.Product.Type.VARIANT|variant} - * {@link protos.google.cloud.retail.v2alpha.Product|Product}s or - * {@link protos.google.cloud.retail.v2alpha.LocalInventory|LocalInventory}s are merged - * and de-duplicated. Notice that rollup attributes will lead to extra query - * latency. Maximum number of keys is 30. - * - * For {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo|FulfillmentInfo}, a - * fulfillment type and a fulfillment ID must be provided in the format of - * "fulfillmentType.fulfillmentId". E.g., in "pickupInStore.store123", - * "pickupInStore" is fulfillment type and "store123" is the store ID. - * - * Supported keys are: - * - * * colorFamilies - * * price - * * originalPrice - * * discount - * * variantId - * * inventory(place_id,price) - * * inventory(place_id,original_price) - * * inventory(place_id,attributes.key), where key is any key in the - * {@link protos.google.cloud.retail.v2alpha.LocalInventory.attributes|Product.local_inventories.attributes} - * map. - * * attributes.key, where key is any key in the - * {@link protos.google.cloud.retail.v2alpha.Product.attributes|Product.attributes} map. - * * pickupInStore.id, where id is any - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.place_ids|FulfillmentInfo.place_ids} - * for - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.type|FulfillmentInfo.type} - * "pickup-in-store". - * * shipToStore.id, where id is any - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.place_ids|FulfillmentInfo.place_ids} - * for - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.type|FulfillmentInfo.type} - * "ship-to-store". - * * sameDayDelivery.id, where id is any - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.place_ids|FulfillmentInfo.place_ids} - * for - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.type|FulfillmentInfo.type} - * "same-day-delivery". - * * nextDayDelivery.id, where id is any - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.place_ids|FulfillmentInfo.place_ids} - * for - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.type|FulfillmentInfo.type} - * "next-day-delivery". - * * customFulfillment1.id, where id is any - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.place_ids|FulfillmentInfo.place_ids} - * for - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.type|FulfillmentInfo.type} - * "custom-type-1". - * * customFulfillment2.id, where id is any - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.place_ids|FulfillmentInfo.place_ids} - * for - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.type|FulfillmentInfo.type} - * "custom-type-2". - * * customFulfillment3.id, where id is any - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.place_ids|FulfillmentInfo.place_ids} - * for - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.type|FulfillmentInfo.type} - * "custom-type-3". - * * customFulfillment4.id, where id is any - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.place_ids|FulfillmentInfo.place_ids} - * for - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.type|FulfillmentInfo.type} - * "custom-type-4". - * * customFulfillment5.id, where id is any - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.place_ids|FulfillmentInfo.place_ids} - * for - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.type|FulfillmentInfo.type} - * "custom-type-5". - * - * If this field is set to an invalid value other than these, an - * INVALID_ARGUMENT error is returned. - * @param {string[]} request.pageCategories - * The categories associated with a category page. Must be set for category - * navigation queries to achieve good search quality. The format should be - * the same as - * {@link protos.google.cloud.retail.v2alpha.UserEvent.page_categories|UserEvent.page_categories}; - * - * To represent full path of category, use '>' sign to separate different - * hierarchies. If '>' is part of the category name, replace it with - * other character(s). - * - * Category pages include special pages such as sales or promotions. For - * instance, a special sale page may have the category hierarchy: - * "pageCategories" : ["Sales > 2017 Black Friday Deals"]. - * @param {google.cloud.retail.v2alpha.SearchRequest.SearchMode} request.searchMode - * The search mode of the search request. If not specified, a single search - * request triggers both product search and faceted search. - * @param {google.cloud.retail.v2alpha.SearchRequest.PersonalizationSpec} request.personalizationSpec - * The specification for personalization. - * - * Notice that if both - * {@link protos.google.cloud.retail.v2alpha.ServingConfig.personalization_spec|ServingConfig.personalization_spec} - * and - * {@link protos.google.cloud.retail.v2alpha.SearchRequest.personalization_spec|SearchRequest.personalization_spec} - * are set. - * {@link protos.google.cloud.retail.v2alpha.SearchRequest.personalization_spec|SearchRequest.personalization_spec} - * will override - * {@link protos.google.cloud.retail.v2alpha.ServingConfig.personalization_spec|ServingConfig.personalization_spec}. - * @param {number[]} request.labels - * The labels applied to a resource must meet the following requirements: - * - * * Each resource can have multiple labels, up to a maximum of 64. - * * Each label must be a key-value pair. - * * Keys have a minimum length of 1 character and a maximum length of 63 - * characters and cannot be empty. Values can be empty and have a maximum - * length of 63 characters. - * * Keys and values can contain only lowercase letters, numeric characters, - * underscores, and dashes. All characters must use UTF-8 encoding, and - * international characters are allowed. - * * The key portion of a label must be unique. However, you can use the same - * key with multiple resources. - * * Keys must start with a lowercase letter or international character. - * - * For more information, see [Requirements for - * labels](https://cloud.google.com/resource-manager/docs/creating-managing-labels#requirements) - * in the Resource Manager documentation. - * @param {google.cloud.retail.v2alpha.SearchRequest.SpellCorrectionSpec} request.spellCorrectionSpec - * The spell correction specification that specifies the mode under - * which spell correction will take effect. - * @param {string} request.entity - * The entity for customers that may run multiple different entities, domains, - * sites or regions, for example, `Google US`, `Google Ads`, `Waymo`, - * `google.com`, `youtube.com`, etc. - * If this is set, it should be exactly matched with - * {@link protos.google.cloud.retail.v2alpha.UserEvent.entity|UserEvent.entity} to get - * search results boosted by entity. - * @param {google.cloud.retail.v2alpha.SearchRequest.ConversationalSearchSpec} [request.conversationalSearchSpec] - * Optional. This field specifies all conversational related parameters - * addition to traditional retail search. - * @param {google.cloud.retail.v2alpha.SearchRequest.TileNavigationSpec} [request.tileNavigationSpec] - * Optional. This field specifies tile navigation related parameters. - * @param {string} [request.languageCode] - * Optional. The BCP-47 language code, such as "en-US" or "sr-Latn" - * [list](https://www.unicode.org/cldr/charts/46/summary/root.html). For more - * information, see [Standardized codes](https://google.aip.dev/143). This - * field helps to better interpret the query. If a value isn't specified, the - * query language code is automatically detected, which may not be accurate. - * @param {string} [request.regionCode] - * Optional. The Unicode country/region code (CLDR) of a location, such as - * "US" and "419" - * [list](https://www.unicode.org/cldr/charts/46/supplemental/territory_information.html). - * For more information, see [Standardized codes](https://google.aip.dev/143). - * If set, then results will be boosted based on the region_code provided. - * @param {string} [request.placeId] - * Optional. An id corresponding to a place, such as a store id or region id. - * When specified, we use the price from the local inventory with the matching - * product's - * {@link protos.google.cloud.retail.v2alpha.LocalInventory.place_id|LocalInventory.place_id} - * for revenue optimization. - * @param {number[]} [request.userAttributes] - * Optional. The user attributes that could be used for personalization of - * search results. - * * Populate at most 100 key-value pairs per query. - * * Only supports string keys and repeated string values. - * * Duplcate keys are not allowed within a single query. - * - * Example: - * user_attributes: [ - * { key: "pets" - * value { - * values: "dog" - * values: "cat" - * } - * }, - * { key: "state" - * value { - * values: "CA" - * } - * } - * ] - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.cloud.retail.v2alpha.SearchResponse.SearchResult|SearchResult}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `searchAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Performs a search. + * + * This feature is only available for users who have Retail Search enabled. + * Enable Retail Search on Cloud Console before using this feature. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.placement + * Required. The resource name of the Retail Search serving config, such as + * `projects/* /locations/global/catalogs/default_catalog/servingConfigs/default_serving_config` + * or the name of the legacy placement resource, such as + * `projects/* /locations/global/catalogs/default_catalog/placements/default_search`. + * This field is used to identify the serving config name and the set + * of models that are used to make the search. + * @param {string} request.branch + * The branch resource name, such as + * `projects/* /locations/global/catalogs/default_catalog/branches/0`. + * + * Use "default_branch" as the branch ID or leave this field empty, to search + * products under the default branch. + * @param {string} request.query + * Raw search query. + * + * If this field is empty, the request is considered a category browsing + * request and returned results are based on + * {@link protos.google.cloud.retail.v2alpha.SearchRequest.filter|filter} and + * {@link protos.google.cloud.retail.v2alpha.SearchRequest.page_categories|page_categories}. + * @param {string} request.visitorId + * Required. A unique identifier for tracking visitors. For example, this + * could be implemented with an HTTP cookie, which should be able to uniquely + * identify a visitor on a single device. This unique identifier should not + * change if the visitor logs in or out of the website. + * + * This should be the same identifier as + * {@link protos.google.cloud.retail.v2alpha.UserEvent.visitor_id|UserEvent.visitor_id}. + * + * The field must be a UTF-8 encoded string with a length limit of 128 + * characters. Otherwise, an INVALID_ARGUMENT error is returned. + * @param {google.cloud.retail.v2alpha.UserInfo} request.userInfo + * User information. + * @param {number} request.pageSize + * Maximum number of {@link protos.google.cloud.retail.v2alpha.Product|Product}s to + * return. If unspecified, defaults to a reasonable value. The maximum allowed + * value is 120. Values above 120 will be coerced to 120. + * + * If this field is negative, an INVALID_ARGUMENT is returned. + * @param {string} request.pageToken + * A page token + * {@link protos.google.cloud.retail.v2alpha.SearchResponse.next_page_token|SearchResponse.next_page_token}, + * received from a previous + * {@link protos.google.cloud.retail.v2alpha.SearchService.Search|SearchService.Search} + * call. Provide this to retrieve the subsequent page. + * + * When paginating, all other parameters provided to + * {@link protos.google.cloud.retail.v2alpha.SearchService.Search|SearchService.Search} + * must match the call that provided the page token. Otherwise, an + * INVALID_ARGUMENT error is returned. + * @param {number} request.offset + * A 0-indexed integer that specifies the current offset (that is, starting + * result location, amongst the + * {@link protos.google.cloud.retail.v2alpha.Product|Product}s deemed by the API as + * relevant) in search results. This field is only considered if + * {@link protos.google.cloud.retail.v2alpha.SearchRequest.page_token|page_token} is + * unset. + * + * If this field is negative, an INVALID_ARGUMENT is returned. + * @param {string} request.filter + * The filter syntax consists of an expression language for constructing a + * predicate from one or more fields of the products being filtered. Filter + * expression is case-sensitive. For more information, see + * [Filter](https://cloud.google.com/retail/docs/filter-and-order#filter). + * + * If this field is unrecognizable, an INVALID_ARGUMENT is returned. + * @param {string} request.canonicalFilter + * The default filter that is applied when a user performs a search without + * checking any filters on the search page. + * + * The filter applied to every search request when quality improvement such as + * query expansion is needed. In the case a query does not have a sufficient + * amount of results this filter will be used to determine whether or not to + * enable the query expansion flow. The original filter will still be used for + * the query expanded search. + * This field is strongly recommended to achieve high search quality. + * + * For more information about filter syntax, see + * {@link protos.google.cloud.retail.v2alpha.SearchRequest.filter|SearchRequest.filter}. + * @param {string} request.orderBy + * The order in which products are returned. Products can be ordered by + * a field in an {@link protos.google.cloud.retail.v2alpha.Product|Product} object. Leave + * it unset if ordered by relevance. OrderBy expression is case-sensitive. For + * more information, see + * [Order](https://cloud.google.com/retail/docs/filter-and-order#order). + * + * If this field is unrecognizable, an INVALID_ARGUMENT is returned. + * @param {number[]} request.facetSpecs + * Facet specifications for faceted search. If empty, no facets are returned. + * + * A maximum of 200 values are allowed. Otherwise, an INVALID_ARGUMENT error + * is returned. + * @param {google.cloud.retail.v2alpha.SearchRequest.DynamicFacetSpec} request.dynamicFacetSpec + * Deprecated. Refer to https://cloud.google.com/retail/docs/configs#dynamic + * to enable dynamic facets. Do not set this field. + * + * The specification for dynamically generated facets. Notice that only + * textual facets can be dynamically generated. + * @param {google.cloud.retail.v2alpha.SearchRequest.BoostSpec} request.boostSpec + * Boost specification to boost certain products. For more information, see + * [Boost results](https://cloud.google.com/retail/docs/boosting). + * + * Notice that if both + * {@link protos.google.cloud.retail.v2alpha.ServingConfig.boost_control_ids|ServingConfig.boost_control_ids} + * and + * {@link protos.google.cloud.retail.v2alpha.SearchRequest.boost_spec|SearchRequest.boost_spec} + * are set, the boost conditions from both places are evaluated. If a search + * request matches multiple boost conditions, the final boost score is equal + * to the sum of the boost scores from all matched boost conditions. + * @param {google.cloud.retail.v2alpha.SearchRequest.QueryExpansionSpec} request.queryExpansionSpec + * The query expansion specification that specifies the conditions under which + * query expansion occurs. For more information, see [Query + * expansion](https://cloud.google.com/retail/docs/result-size#query_expansion). + * @param {google.cloud.retail.v2alpha.SearchRequest.RelevanceThreshold} request.relevanceThreshold + * The relevance threshold of the search results. + * + * Defaults to + * {@link protos.google.cloud.retail.v2alpha.SearchRequest.RelevanceThreshold.HIGH|RelevanceThreshold.HIGH}, + * which means only the most relevant results are shown, and the least number + * of results are returned. For more information, see [Adjust result + * size](https://cloud.google.com/retail/docs/result-size#relevance_thresholding). + * @param {string[]} request.variantRollupKeys + * The keys to fetch and rollup the matching + * {@link protos.google.cloud.retail.v2alpha.Product.Type.VARIANT|variant} + * {@link protos.google.cloud.retail.v2alpha.Product|Product}s attributes, + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo|FulfillmentInfo} or + * {@link protos.google.cloud.retail.v2alpha.LocalInventory|LocalInventory}s attributes. + * The attributes from all the matching + * {@link protos.google.cloud.retail.v2alpha.Product.Type.VARIANT|variant} + * {@link protos.google.cloud.retail.v2alpha.Product|Product}s or + * {@link protos.google.cloud.retail.v2alpha.LocalInventory|LocalInventory}s are merged + * and de-duplicated. Notice that rollup attributes will lead to extra query + * latency. Maximum number of keys is 30. + * + * For {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo|FulfillmentInfo}, a + * fulfillment type and a fulfillment ID must be provided in the format of + * "fulfillmentType.fulfillmentId". E.g., in "pickupInStore.store123", + * "pickupInStore" is fulfillment type and "store123" is the store ID. + * + * Supported keys are: + * + * * colorFamilies + * * price + * * originalPrice + * * discount + * * variantId + * * inventory(place_id,price) + * * inventory(place_id,original_price) + * * inventory(place_id,attributes.key), where key is any key in the + * {@link protos.google.cloud.retail.v2alpha.LocalInventory.attributes|Product.local_inventories.attributes} + * map. + * * attributes.key, where key is any key in the + * {@link protos.google.cloud.retail.v2alpha.Product.attributes|Product.attributes} map. + * * pickupInStore.id, where id is any + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.place_ids|FulfillmentInfo.place_ids} + * for + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.type|FulfillmentInfo.type} + * "pickup-in-store". + * * shipToStore.id, where id is any + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.place_ids|FulfillmentInfo.place_ids} + * for + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.type|FulfillmentInfo.type} + * "ship-to-store". + * * sameDayDelivery.id, where id is any + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.place_ids|FulfillmentInfo.place_ids} + * for + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.type|FulfillmentInfo.type} + * "same-day-delivery". + * * nextDayDelivery.id, where id is any + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.place_ids|FulfillmentInfo.place_ids} + * for + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.type|FulfillmentInfo.type} + * "next-day-delivery". + * * customFulfillment1.id, where id is any + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.place_ids|FulfillmentInfo.place_ids} + * for + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.type|FulfillmentInfo.type} + * "custom-type-1". + * * customFulfillment2.id, where id is any + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.place_ids|FulfillmentInfo.place_ids} + * for + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.type|FulfillmentInfo.type} + * "custom-type-2". + * * customFulfillment3.id, where id is any + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.place_ids|FulfillmentInfo.place_ids} + * for + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.type|FulfillmentInfo.type} + * "custom-type-3". + * * customFulfillment4.id, where id is any + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.place_ids|FulfillmentInfo.place_ids} + * for + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.type|FulfillmentInfo.type} + * "custom-type-4". + * * customFulfillment5.id, where id is any + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.place_ids|FulfillmentInfo.place_ids} + * for + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.type|FulfillmentInfo.type} + * "custom-type-5". + * + * If this field is set to an invalid value other than these, an + * INVALID_ARGUMENT error is returned. + * @param {string[]} request.pageCategories + * The categories associated with a category page. Must be set for category + * navigation queries to achieve good search quality. The format should be + * the same as + * {@link protos.google.cloud.retail.v2alpha.UserEvent.page_categories|UserEvent.page_categories}; + * + * To represent full path of category, use '>' sign to separate different + * hierarchies. If '>' is part of the category name, replace it with + * other character(s). + * + * Category pages include special pages such as sales or promotions. For + * instance, a special sale page may have the category hierarchy: + * "pageCategories" : ["Sales > 2017 Black Friday Deals"]. + * @param {google.cloud.retail.v2alpha.SearchRequest.SearchMode} request.searchMode + * The search mode of the search request. If not specified, a single search + * request triggers both product search and faceted search. + * @param {google.cloud.retail.v2alpha.SearchRequest.PersonalizationSpec} request.personalizationSpec + * The specification for personalization. + * + * Notice that if both + * {@link protos.google.cloud.retail.v2alpha.ServingConfig.personalization_spec|ServingConfig.personalization_spec} + * and + * {@link protos.google.cloud.retail.v2alpha.SearchRequest.personalization_spec|SearchRequest.personalization_spec} + * are set. + * {@link protos.google.cloud.retail.v2alpha.SearchRequest.personalization_spec|SearchRequest.personalization_spec} + * will override + * {@link protos.google.cloud.retail.v2alpha.ServingConfig.personalization_spec|ServingConfig.personalization_spec}. + * @param {number[]} request.labels + * The labels applied to a resource must meet the following requirements: + * + * * Each resource can have multiple labels, up to a maximum of 64. + * * Each label must be a key-value pair. + * * Keys have a minimum length of 1 character and a maximum length of 63 + * characters and cannot be empty. Values can be empty and have a maximum + * length of 63 characters. + * * Keys and values can contain only lowercase letters, numeric characters, + * underscores, and dashes. All characters must use UTF-8 encoding, and + * international characters are allowed. + * * The key portion of a label must be unique. However, you can use the same + * key with multiple resources. + * * Keys must start with a lowercase letter or international character. + * + * For more information, see [Requirements for + * labels](https://cloud.google.com/resource-manager/docs/creating-managing-labels#requirements) + * in the Resource Manager documentation. + * @param {google.cloud.retail.v2alpha.SearchRequest.SpellCorrectionSpec} request.spellCorrectionSpec + * The spell correction specification that specifies the mode under + * which spell correction will take effect. + * @param {string} request.entity + * The entity for customers that may run multiple different entities, domains, + * sites or regions, for example, `Google US`, `Google Ads`, `Waymo`, + * `google.com`, `youtube.com`, etc. + * If this is set, it should be exactly matched with + * {@link protos.google.cloud.retail.v2alpha.UserEvent.entity|UserEvent.entity} to get + * search results boosted by entity. + * @param {google.cloud.retail.v2alpha.SearchRequest.ConversationalSearchSpec} [request.conversationalSearchSpec] + * Optional. This field specifies all conversational related parameters + * addition to traditional retail search. + * @param {google.cloud.retail.v2alpha.SearchRequest.TileNavigationSpec} [request.tileNavigationSpec] + * Optional. This field specifies tile navigation related parameters. + * @param {string} [request.languageCode] + * Optional. The BCP-47 language code, such as "en-US" or "sr-Latn" + * [list](https://www.unicode.org/cldr/charts/46/summary/root.html). For more + * information, see [Standardized codes](https://google.aip.dev/143). This + * field helps to better interpret the query. If a value isn't specified, the + * query language code is automatically detected, which may not be accurate. + * @param {string} [request.regionCode] + * Optional. The Unicode country/region code (CLDR) of a location, such as + * "US" and "419" + * [list](https://www.unicode.org/cldr/charts/46/supplemental/territory_information.html). + * For more information, see [Standardized codes](https://google.aip.dev/143). + * If set, then results will be boosted based on the region_code provided. + * @param {string} [request.placeId] + * Optional. An id corresponding to a place, such as a store id or region id. + * When specified, we use the price from the local inventory with the matching + * product's + * {@link protos.google.cloud.retail.v2alpha.LocalInventory.place_id|LocalInventory.place_id} + * for revenue optimization. + * @param {number[]} [request.userAttributes] + * Optional. The user attributes that could be used for personalization of + * search results. + * * Populate at most 100 key-value pairs per query. + * * Only supports string keys and repeated string values. + * * Duplcate keys are not allowed within a single query. + * + * Example: + * user_attributes: [ + * { key: "pets" + * value { + * values: "dog" + * values: "cat" + * } + * }, + * { key: "state" + * value { + * values: "CA" + * } + * } + * ] + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.cloud.retail.v2alpha.SearchResponse.SearchResult|SearchResult}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `searchAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ search( - request?: protos.google.cloud.retail.v2alpha.ISearchRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.retail.v2alpha.SearchResponse.ISearchResult[], - protos.google.cloud.retail.v2alpha.ISearchRequest|null, - protos.google.cloud.retail.v2alpha.ISearchResponse - ]>; + request?: protos.google.cloud.retail.v2alpha.ISearchRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.SearchResponse.ISearchResult[], + protos.google.cloud.retail.v2alpha.ISearchRequest | null, + protos.google.cloud.retail.v2alpha.ISearchResponse, + ] + >; search( - request: protos.google.cloud.retail.v2alpha.ISearchRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.cloud.retail.v2alpha.ISearchRequest, - protos.google.cloud.retail.v2alpha.ISearchResponse|null|undefined, - protos.google.cloud.retail.v2alpha.SearchResponse.ISearchResult>): void; + request: protos.google.cloud.retail.v2alpha.ISearchRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.cloud.retail.v2alpha.ISearchRequest, + protos.google.cloud.retail.v2alpha.ISearchResponse | null | undefined, + protos.google.cloud.retail.v2alpha.SearchResponse.ISearchResult + >, + ): void; search( - request: protos.google.cloud.retail.v2alpha.ISearchRequest, - callback: PaginationCallback< - protos.google.cloud.retail.v2alpha.ISearchRequest, - protos.google.cloud.retail.v2alpha.ISearchResponse|null|undefined, - protos.google.cloud.retail.v2alpha.SearchResponse.ISearchResult>): void; + request: protos.google.cloud.retail.v2alpha.ISearchRequest, + callback: PaginationCallback< + protos.google.cloud.retail.v2alpha.ISearchRequest, + protos.google.cloud.retail.v2alpha.ISearchResponse | null | undefined, + protos.google.cloud.retail.v2alpha.SearchResponse.ISearchResult + >, + ): void; search( - request?: protos.google.cloud.retail.v2alpha.ISearchRequest, - optionsOrCallback?: CallOptions|PaginationCallback< - protos.google.cloud.retail.v2alpha.ISearchRequest, - protos.google.cloud.retail.v2alpha.ISearchResponse|null|undefined, - protos.google.cloud.retail.v2alpha.SearchResponse.ISearchResult>, - callback?: PaginationCallback< + request?: protos.google.cloud.retail.v2alpha.ISearchRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.cloud.retail.v2alpha.ISearchRequest, - protos.google.cloud.retail.v2alpha.ISearchResponse|null|undefined, - protos.google.cloud.retail.v2alpha.SearchResponse.ISearchResult>): - Promise<[ - protos.google.cloud.retail.v2alpha.SearchResponse.ISearchResult[], - protos.google.cloud.retail.v2alpha.ISearchRequest|null, - protos.google.cloud.retail.v2alpha.ISearchResponse - ]>|void { + protos.google.cloud.retail.v2alpha.ISearchResponse | null | undefined, + protos.google.cloud.retail.v2alpha.SearchResponse.ISearchResult + >, + callback?: PaginationCallback< + protos.google.cloud.retail.v2alpha.ISearchRequest, + protos.google.cloud.retail.v2alpha.ISearchResponse | null | undefined, + protos.google.cloud.retail.v2alpha.SearchResponse.ISearchResult + >, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.SearchResponse.ISearchResult[], + protos.google.cloud.retail.v2alpha.ISearchRequest | null, + protos.google.cloud.retail.v2alpha.ISearchResponse, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'placement': request.placement ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + placement: request.placement ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.cloud.retail.v2alpha.ISearchRequest, - protos.google.cloud.retail.v2alpha.ISearchResponse|null|undefined, - protos.google.cloud.retail.v2alpha.SearchResponse.ISearchResult>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.cloud.retail.v2alpha.ISearchRequest, + protos.google.cloud.retail.v2alpha.ISearchResponse | null | undefined, + protos.google.cloud.retail.v2alpha.SearchResponse.ISearchResult + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('search values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -759,694 +819,698 @@ export class SearchServiceClient { this._log.info('search request %j', request); return this.innerApiCalls .search(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.cloud.retail.v2alpha.SearchResponse.ISearchResult[], - protos.google.cloud.retail.v2alpha.ISearchRequest|null, - protos.google.cloud.retail.v2alpha.ISearchResponse - ]) => { - this._log.info('search values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.cloud.retail.v2alpha.SearchResponse.ISearchResult[], + protos.google.cloud.retail.v2alpha.ISearchRequest | null, + protos.google.cloud.retail.v2alpha.ISearchResponse, + ]) => { + this._log.info('search values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `search`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.placement - * Required. The resource name of the Retail Search serving config, such as - * `projects/* /locations/global/catalogs/default_catalog/servingConfigs/default_serving_config` - * or the name of the legacy placement resource, such as - * `projects/* /locations/global/catalogs/default_catalog/placements/default_search`. - * This field is used to identify the serving config name and the set - * of models that are used to make the search. - * @param {string} request.branch - * The branch resource name, such as - * `projects/* /locations/global/catalogs/default_catalog/branches/0`. - * - * Use "default_branch" as the branch ID or leave this field empty, to search - * products under the default branch. - * @param {string} request.query - * Raw search query. - * - * If this field is empty, the request is considered a category browsing - * request and returned results are based on - * {@link protos.google.cloud.retail.v2alpha.SearchRequest.filter|filter} and - * {@link protos.google.cloud.retail.v2alpha.SearchRequest.page_categories|page_categories}. - * @param {string} request.visitorId - * Required. A unique identifier for tracking visitors. For example, this - * could be implemented with an HTTP cookie, which should be able to uniquely - * identify a visitor on a single device. This unique identifier should not - * change if the visitor logs in or out of the website. - * - * This should be the same identifier as - * {@link protos.google.cloud.retail.v2alpha.UserEvent.visitor_id|UserEvent.visitor_id}. - * - * The field must be a UTF-8 encoded string with a length limit of 128 - * characters. Otherwise, an INVALID_ARGUMENT error is returned. - * @param {google.cloud.retail.v2alpha.UserInfo} request.userInfo - * User information. - * @param {number} request.pageSize - * Maximum number of {@link protos.google.cloud.retail.v2alpha.Product|Product}s to - * return. If unspecified, defaults to a reasonable value. The maximum allowed - * value is 120. Values above 120 will be coerced to 120. - * - * If this field is negative, an INVALID_ARGUMENT is returned. - * @param {string} request.pageToken - * A page token - * {@link protos.google.cloud.retail.v2alpha.SearchResponse.next_page_token|SearchResponse.next_page_token}, - * received from a previous - * {@link protos.google.cloud.retail.v2alpha.SearchService.Search|SearchService.Search} - * call. Provide this to retrieve the subsequent page. - * - * When paginating, all other parameters provided to - * {@link protos.google.cloud.retail.v2alpha.SearchService.Search|SearchService.Search} - * must match the call that provided the page token. Otherwise, an - * INVALID_ARGUMENT error is returned. - * @param {number} request.offset - * A 0-indexed integer that specifies the current offset (that is, starting - * result location, amongst the - * {@link protos.google.cloud.retail.v2alpha.Product|Product}s deemed by the API as - * relevant) in search results. This field is only considered if - * {@link protos.google.cloud.retail.v2alpha.SearchRequest.page_token|page_token} is - * unset. - * - * If this field is negative, an INVALID_ARGUMENT is returned. - * @param {string} request.filter - * The filter syntax consists of an expression language for constructing a - * predicate from one or more fields of the products being filtered. Filter - * expression is case-sensitive. For more information, see - * [Filter](https://cloud.google.com/retail/docs/filter-and-order#filter). - * - * If this field is unrecognizable, an INVALID_ARGUMENT is returned. - * @param {string} request.canonicalFilter - * The default filter that is applied when a user performs a search without - * checking any filters on the search page. - * - * The filter applied to every search request when quality improvement such as - * query expansion is needed. In the case a query does not have a sufficient - * amount of results this filter will be used to determine whether or not to - * enable the query expansion flow. The original filter will still be used for - * the query expanded search. - * This field is strongly recommended to achieve high search quality. - * - * For more information about filter syntax, see - * {@link protos.google.cloud.retail.v2alpha.SearchRequest.filter|SearchRequest.filter}. - * @param {string} request.orderBy - * The order in which products are returned. Products can be ordered by - * a field in an {@link protos.google.cloud.retail.v2alpha.Product|Product} object. Leave - * it unset if ordered by relevance. OrderBy expression is case-sensitive. For - * more information, see - * [Order](https://cloud.google.com/retail/docs/filter-and-order#order). - * - * If this field is unrecognizable, an INVALID_ARGUMENT is returned. - * @param {number[]} request.facetSpecs - * Facet specifications for faceted search. If empty, no facets are returned. - * - * A maximum of 200 values are allowed. Otherwise, an INVALID_ARGUMENT error - * is returned. - * @param {google.cloud.retail.v2alpha.SearchRequest.DynamicFacetSpec} request.dynamicFacetSpec - * Deprecated. Refer to https://cloud.google.com/retail/docs/configs#dynamic - * to enable dynamic facets. Do not set this field. - * - * The specification for dynamically generated facets. Notice that only - * textual facets can be dynamically generated. - * @param {google.cloud.retail.v2alpha.SearchRequest.BoostSpec} request.boostSpec - * Boost specification to boost certain products. For more information, see - * [Boost results](https://cloud.google.com/retail/docs/boosting). - * - * Notice that if both - * {@link protos.google.cloud.retail.v2alpha.ServingConfig.boost_control_ids|ServingConfig.boost_control_ids} - * and - * {@link protos.google.cloud.retail.v2alpha.SearchRequest.boost_spec|SearchRequest.boost_spec} - * are set, the boost conditions from both places are evaluated. If a search - * request matches multiple boost conditions, the final boost score is equal - * to the sum of the boost scores from all matched boost conditions. - * @param {google.cloud.retail.v2alpha.SearchRequest.QueryExpansionSpec} request.queryExpansionSpec - * The query expansion specification that specifies the conditions under which - * query expansion occurs. For more information, see [Query - * expansion](https://cloud.google.com/retail/docs/result-size#query_expansion). - * @param {google.cloud.retail.v2alpha.SearchRequest.RelevanceThreshold} request.relevanceThreshold - * The relevance threshold of the search results. - * - * Defaults to - * {@link protos.google.cloud.retail.v2alpha.SearchRequest.RelevanceThreshold.HIGH|RelevanceThreshold.HIGH}, - * which means only the most relevant results are shown, and the least number - * of results are returned. For more information, see [Adjust result - * size](https://cloud.google.com/retail/docs/result-size#relevance_thresholding). - * @param {string[]} request.variantRollupKeys - * The keys to fetch and rollup the matching - * {@link protos.google.cloud.retail.v2alpha.Product.Type.VARIANT|variant} - * {@link protos.google.cloud.retail.v2alpha.Product|Product}s attributes, - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo|FulfillmentInfo} or - * {@link protos.google.cloud.retail.v2alpha.LocalInventory|LocalInventory}s attributes. - * The attributes from all the matching - * {@link protos.google.cloud.retail.v2alpha.Product.Type.VARIANT|variant} - * {@link protos.google.cloud.retail.v2alpha.Product|Product}s or - * {@link protos.google.cloud.retail.v2alpha.LocalInventory|LocalInventory}s are merged - * and de-duplicated. Notice that rollup attributes will lead to extra query - * latency. Maximum number of keys is 30. - * - * For {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo|FulfillmentInfo}, a - * fulfillment type and a fulfillment ID must be provided in the format of - * "fulfillmentType.fulfillmentId". E.g., in "pickupInStore.store123", - * "pickupInStore" is fulfillment type and "store123" is the store ID. - * - * Supported keys are: - * - * * colorFamilies - * * price - * * originalPrice - * * discount - * * variantId - * * inventory(place_id,price) - * * inventory(place_id,original_price) - * * inventory(place_id,attributes.key), where key is any key in the - * {@link protos.google.cloud.retail.v2alpha.LocalInventory.attributes|Product.local_inventories.attributes} - * map. - * * attributes.key, where key is any key in the - * {@link protos.google.cloud.retail.v2alpha.Product.attributes|Product.attributes} map. - * * pickupInStore.id, where id is any - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.place_ids|FulfillmentInfo.place_ids} - * for - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.type|FulfillmentInfo.type} - * "pickup-in-store". - * * shipToStore.id, where id is any - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.place_ids|FulfillmentInfo.place_ids} - * for - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.type|FulfillmentInfo.type} - * "ship-to-store". - * * sameDayDelivery.id, where id is any - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.place_ids|FulfillmentInfo.place_ids} - * for - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.type|FulfillmentInfo.type} - * "same-day-delivery". - * * nextDayDelivery.id, where id is any - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.place_ids|FulfillmentInfo.place_ids} - * for - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.type|FulfillmentInfo.type} - * "next-day-delivery". - * * customFulfillment1.id, where id is any - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.place_ids|FulfillmentInfo.place_ids} - * for - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.type|FulfillmentInfo.type} - * "custom-type-1". - * * customFulfillment2.id, where id is any - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.place_ids|FulfillmentInfo.place_ids} - * for - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.type|FulfillmentInfo.type} - * "custom-type-2". - * * customFulfillment3.id, where id is any - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.place_ids|FulfillmentInfo.place_ids} - * for - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.type|FulfillmentInfo.type} - * "custom-type-3". - * * customFulfillment4.id, where id is any - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.place_ids|FulfillmentInfo.place_ids} - * for - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.type|FulfillmentInfo.type} - * "custom-type-4". - * * customFulfillment5.id, where id is any - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.place_ids|FulfillmentInfo.place_ids} - * for - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.type|FulfillmentInfo.type} - * "custom-type-5". - * - * If this field is set to an invalid value other than these, an - * INVALID_ARGUMENT error is returned. - * @param {string[]} request.pageCategories - * The categories associated with a category page. Must be set for category - * navigation queries to achieve good search quality. The format should be - * the same as - * {@link protos.google.cloud.retail.v2alpha.UserEvent.page_categories|UserEvent.page_categories}; - * - * To represent full path of category, use '>' sign to separate different - * hierarchies. If '>' is part of the category name, replace it with - * other character(s). - * - * Category pages include special pages such as sales or promotions. For - * instance, a special sale page may have the category hierarchy: - * "pageCategories" : ["Sales > 2017 Black Friday Deals"]. - * @param {google.cloud.retail.v2alpha.SearchRequest.SearchMode} request.searchMode - * The search mode of the search request. If not specified, a single search - * request triggers both product search and faceted search. - * @param {google.cloud.retail.v2alpha.SearchRequest.PersonalizationSpec} request.personalizationSpec - * The specification for personalization. - * - * Notice that if both - * {@link protos.google.cloud.retail.v2alpha.ServingConfig.personalization_spec|ServingConfig.personalization_spec} - * and - * {@link protos.google.cloud.retail.v2alpha.SearchRequest.personalization_spec|SearchRequest.personalization_spec} - * are set. - * {@link protos.google.cloud.retail.v2alpha.SearchRequest.personalization_spec|SearchRequest.personalization_spec} - * will override - * {@link protos.google.cloud.retail.v2alpha.ServingConfig.personalization_spec|ServingConfig.personalization_spec}. - * @param {number[]} request.labels - * The labels applied to a resource must meet the following requirements: - * - * * Each resource can have multiple labels, up to a maximum of 64. - * * Each label must be a key-value pair. - * * Keys have a minimum length of 1 character and a maximum length of 63 - * characters and cannot be empty. Values can be empty and have a maximum - * length of 63 characters. - * * Keys and values can contain only lowercase letters, numeric characters, - * underscores, and dashes. All characters must use UTF-8 encoding, and - * international characters are allowed. - * * The key portion of a label must be unique. However, you can use the same - * key with multiple resources. - * * Keys must start with a lowercase letter or international character. - * - * For more information, see [Requirements for - * labels](https://cloud.google.com/resource-manager/docs/creating-managing-labels#requirements) - * in the Resource Manager documentation. - * @param {google.cloud.retail.v2alpha.SearchRequest.SpellCorrectionSpec} request.spellCorrectionSpec - * The spell correction specification that specifies the mode under - * which spell correction will take effect. - * @param {string} request.entity - * The entity for customers that may run multiple different entities, domains, - * sites or regions, for example, `Google US`, `Google Ads`, `Waymo`, - * `google.com`, `youtube.com`, etc. - * If this is set, it should be exactly matched with - * {@link protos.google.cloud.retail.v2alpha.UserEvent.entity|UserEvent.entity} to get - * search results boosted by entity. - * @param {google.cloud.retail.v2alpha.SearchRequest.ConversationalSearchSpec} [request.conversationalSearchSpec] - * Optional. This field specifies all conversational related parameters - * addition to traditional retail search. - * @param {google.cloud.retail.v2alpha.SearchRequest.TileNavigationSpec} [request.tileNavigationSpec] - * Optional. This field specifies tile navigation related parameters. - * @param {string} [request.languageCode] - * Optional. The BCP-47 language code, such as "en-US" or "sr-Latn" - * [list](https://www.unicode.org/cldr/charts/46/summary/root.html). For more - * information, see [Standardized codes](https://google.aip.dev/143). This - * field helps to better interpret the query. If a value isn't specified, the - * query language code is automatically detected, which may not be accurate. - * @param {string} [request.regionCode] - * Optional. The Unicode country/region code (CLDR) of a location, such as - * "US" and "419" - * [list](https://www.unicode.org/cldr/charts/46/supplemental/territory_information.html). - * For more information, see [Standardized codes](https://google.aip.dev/143). - * If set, then results will be boosted based on the region_code provided. - * @param {string} [request.placeId] - * Optional. An id corresponding to a place, such as a store id or region id. - * When specified, we use the price from the local inventory with the matching - * product's - * {@link protos.google.cloud.retail.v2alpha.LocalInventory.place_id|LocalInventory.place_id} - * for revenue optimization. - * @param {number[]} [request.userAttributes] - * Optional. The user attributes that could be used for personalization of - * search results. - * * Populate at most 100 key-value pairs per query. - * * Only supports string keys and repeated string values. - * * Duplcate keys are not allowed within a single query. - * - * Example: - * user_attributes: [ - * { key: "pets" - * value { - * values: "dog" - * values: "cat" - * } - * }, - * { key: "state" - * value { - * values: "CA" - * } - * } - * ] - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.cloud.retail.v2alpha.SearchResponse.SearchResult|SearchResult} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `searchAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `search`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.placement + * Required. The resource name of the Retail Search serving config, such as + * `projects/* /locations/global/catalogs/default_catalog/servingConfigs/default_serving_config` + * or the name of the legacy placement resource, such as + * `projects/* /locations/global/catalogs/default_catalog/placements/default_search`. + * This field is used to identify the serving config name and the set + * of models that are used to make the search. + * @param {string} request.branch + * The branch resource name, such as + * `projects/* /locations/global/catalogs/default_catalog/branches/0`. + * + * Use "default_branch" as the branch ID or leave this field empty, to search + * products under the default branch. + * @param {string} request.query + * Raw search query. + * + * If this field is empty, the request is considered a category browsing + * request and returned results are based on + * {@link protos.google.cloud.retail.v2alpha.SearchRequest.filter|filter} and + * {@link protos.google.cloud.retail.v2alpha.SearchRequest.page_categories|page_categories}. + * @param {string} request.visitorId + * Required. A unique identifier for tracking visitors. For example, this + * could be implemented with an HTTP cookie, which should be able to uniquely + * identify a visitor on a single device. This unique identifier should not + * change if the visitor logs in or out of the website. + * + * This should be the same identifier as + * {@link protos.google.cloud.retail.v2alpha.UserEvent.visitor_id|UserEvent.visitor_id}. + * + * The field must be a UTF-8 encoded string with a length limit of 128 + * characters. Otherwise, an INVALID_ARGUMENT error is returned. + * @param {google.cloud.retail.v2alpha.UserInfo} request.userInfo + * User information. + * @param {number} request.pageSize + * Maximum number of {@link protos.google.cloud.retail.v2alpha.Product|Product}s to + * return. If unspecified, defaults to a reasonable value. The maximum allowed + * value is 120. Values above 120 will be coerced to 120. + * + * If this field is negative, an INVALID_ARGUMENT is returned. + * @param {string} request.pageToken + * A page token + * {@link protos.google.cloud.retail.v2alpha.SearchResponse.next_page_token|SearchResponse.next_page_token}, + * received from a previous + * {@link protos.google.cloud.retail.v2alpha.SearchService.Search|SearchService.Search} + * call. Provide this to retrieve the subsequent page. + * + * When paginating, all other parameters provided to + * {@link protos.google.cloud.retail.v2alpha.SearchService.Search|SearchService.Search} + * must match the call that provided the page token. Otherwise, an + * INVALID_ARGUMENT error is returned. + * @param {number} request.offset + * A 0-indexed integer that specifies the current offset (that is, starting + * result location, amongst the + * {@link protos.google.cloud.retail.v2alpha.Product|Product}s deemed by the API as + * relevant) in search results. This field is only considered if + * {@link protos.google.cloud.retail.v2alpha.SearchRequest.page_token|page_token} is + * unset. + * + * If this field is negative, an INVALID_ARGUMENT is returned. + * @param {string} request.filter + * The filter syntax consists of an expression language for constructing a + * predicate from one or more fields of the products being filtered. Filter + * expression is case-sensitive. For more information, see + * [Filter](https://cloud.google.com/retail/docs/filter-and-order#filter). + * + * If this field is unrecognizable, an INVALID_ARGUMENT is returned. + * @param {string} request.canonicalFilter + * The default filter that is applied when a user performs a search without + * checking any filters on the search page. + * + * The filter applied to every search request when quality improvement such as + * query expansion is needed. In the case a query does not have a sufficient + * amount of results this filter will be used to determine whether or not to + * enable the query expansion flow. The original filter will still be used for + * the query expanded search. + * This field is strongly recommended to achieve high search quality. + * + * For more information about filter syntax, see + * {@link protos.google.cloud.retail.v2alpha.SearchRequest.filter|SearchRequest.filter}. + * @param {string} request.orderBy + * The order in which products are returned. Products can be ordered by + * a field in an {@link protos.google.cloud.retail.v2alpha.Product|Product} object. Leave + * it unset if ordered by relevance. OrderBy expression is case-sensitive. For + * more information, see + * [Order](https://cloud.google.com/retail/docs/filter-and-order#order). + * + * If this field is unrecognizable, an INVALID_ARGUMENT is returned. + * @param {number[]} request.facetSpecs + * Facet specifications for faceted search. If empty, no facets are returned. + * + * A maximum of 200 values are allowed. Otherwise, an INVALID_ARGUMENT error + * is returned. + * @param {google.cloud.retail.v2alpha.SearchRequest.DynamicFacetSpec} request.dynamicFacetSpec + * Deprecated. Refer to https://cloud.google.com/retail/docs/configs#dynamic + * to enable dynamic facets. Do not set this field. + * + * The specification for dynamically generated facets. Notice that only + * textual facets can be dynamically generated. + * @param {google.cloud.retail.v2alpha.SearchRequest.BoostSpec} request.boostSpec + * Boost specification to boost certain products. For more information, see + * [Boost results](https://cloud.google.com/retail/docs/boosting). + * + * Notice that if both + * {@link protos.google.cloud.retail.v2alpha.ServingConfig.boost_control_ids|ServingConfig.boost_control_ids} + * and + * {@link protos.google.cloud.retail.v2alpha.SearchRequest.boost_spec|SearchRequest.boost_spec} + * are set, the boost conditions from both places are evaluated. If a search + * request matches multiple boost conditions, the final boost score is equal + * to the sum of the boost scores from all matched boost conditions. + * @param {google.cloud.retail.v2alpha.SearchRequest.QueryExpansionSpec} request.queryExpansionSpec + * The query expansion specification that specifies the conditions under which + * query expansion occurs. For more information, see [Query + * expansion](https://cloud.google.com/retail/docs/result-size#query_expansion). + * @param {google.cloud.retail.v2alpha.SearchRequest.RelevanceThreshold} request.relevanceThreshold + * The relevance threshold of the search results. + * + * Defaults to + * {@link protos.google.cloud.retail.v2alpha.SearchRequest.RelevanceThreshold.HIGH|RelevanceThreshold.HIGH}, + * which means only the most relevant results are shown, and the least number + * of results are returned. For more information, see [Adjust result + * size](https://cloud.google.com/retail/docs/result-size#relevance_thresholding). + * @param {string[]} request.variantRollupKeys + * The keys to fetch and rollup the matching + * {@link protos.google.cloud.retail.v2alpha.Product.Type.VARIANT|variant} + * {@link protos.google.cloud.retail.v2alpha.Product|Product}s attributes, + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo|FulfillmentInfo} or + * {@link protos.google.cloud.retail.v2alpha.LocalInventory|LocalInventory}s attributes. + * The attributes from all the matching + * {@link protos.google.cloud.retail.v2alpha.Product.Type.VARIANT|variant} + * {@link protos.google.cloud.retail.v2alpha.Product|Product}s or + * {@link protos.google.cloud.retail.v2alpha.LocalInventory|LocalInventory}s are merged + * and de-duplicated. Notice that rollup attributes will lead to extra query + * latency. Maximum number of keys is 30. + * + * For {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo|FulfillmentInfo}, a + * fulfillment type and a fulfillment ID must be provided in the format of + * "fulfillmentType.fulfillmentId". E.g., in "pickupInStore.store123", + * "pickupInStore" is fulfillment type and "store123" is the store ID. + * + * Supported keys are: + * + * * colorFamilies + * * price + * * originalPrice + * * discount + * * variantId + * * inventory(place_id,price) + * * inventory(place_id,original_price) + * * inventory(place_id,attributes.key), where key is any key in the + * {@link protos.google.cloud.retail.v2alpha.LocalInventory.attributes|Product.local_inventories.attributes} + * map. + * * attributes.key, where key is any key in the + * {@link protos.google.cloud.retail.v2alpha.Product.attributes|Product.attributes} map. + * * pickupInStore.id, where id is any + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.place_ids|FulfillmentInfo.place_ids} + * for + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.type|FulfillmentInfo.type} + * "pickup-in-store". + * * shipToStore.id, where id is any + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.place_ids|FulfillmentInfo.place_ids} + * for + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.type|FulfillmentInfo.type} + * "ship-to-store". + * * sameDayDelivery.id, where id is any + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.place_ids|FulfillmentInfo.place_ids} + * for + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.type|FulfillmentInfo.type} + * "same-day-delivery". + * * nextDayDelivery.id, where id is any + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.place_ids|FulfillmentInfo.place_ids} + * for + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.type|FulfillmentInfo.type} + * "next-day-delivery". + * * customFulfillment1.id, where id is any + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.place_ids|FulfillmentInfo.place_ids} + * for + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.type|FulfillmentInfo.type} + * "custom-type-1". + * * customFulfillment2.id, where id is any + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.place_ids|FulfillmentInfo.place_ids} + * for + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.type|FulfillmentInfo.type} + * "custom-type-2". + * * customFulfillment3.id, where id is any + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.place_ids|FulfillmentInfo.place_ids} + * for + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.type|FulfillmentInfo.type} + * "custom-type-3". + * * customFulfillment4.id, where id is any + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.place_ids|FulfillmentInfo.place_ids} + * for + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.type|FulfillmentInfo.type} + * "custom-type-4". + * * customFulfillment5.id, where id is any + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.place_ids|FulfillmentInfo.place_ids} + * for + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.type|FulfillmentInfo.type} + * "custom-type-5". + * + * If this field is set to an invalid value other than these, an + * INVALID_ARGUMENT error is returned. + * @param {string[]} request.pageCategories + * The categories associated with a category page. Must be set for category + * navigation queries to achieve good search quality. The format should be + * the same as + * {@link protos.google.cloud.retail.v2alpha.UserEvent.page_categories|UserEvent.page_categories}; + * + * To represent full path of category, use '>' sign to separate different + * hierarchies. If '>' is part of the category name, replace it with + * other character(s). + * + * Category pages include special pages such as sales or promotions. For + * instance, a special sale page may have the category hierarchy: + * "pageCategories" : ["Sales > 2017 Black Friday Deals"]. + * @param {google.cloud.retail.v2alpha.SearchRequest.SearchMode} request.searchMode + * The search mode of the search request. If not specified, a single search + * request triggers both product search and faceted search. + * @param {google.cloud.retail.v2alpha.SearchRequest.PersonalizationSpec} request.personalizationSpec + * The specification for personalization. + * + * Notice that if both + * {@link protos.google.cloud.retail.v2alpha.ServingConfig.personalization_spec|ServingConfig.personalization_spec} + * and + * {@link protos.google.cloud.retail.v2alpha.SearchRequest.personalization_spec|SearchRequest.personalization_spec} + * are set. + * {@link protos.google.cloud.retail.v2alpha.SearchRequest.personalization_spec|SearchRequest.personalization_spec} + * will override + * {@link protos.google.cloud.retail.v2alpha.ServingConfig.personalization_spec|ServingConfig.personalization_spec}. + * @param {number[]} request.labels + * The labels applied to a resource must meet the following requirements: + * + * * Each resource can have multiple labels, up to a maximum of 64. + * * Each label must be a key-value pair. + * * Keys have a minimum length of 1 character and a maximum length of 63 + * characters and cannot be empty. Values can be empty and have a maximum + * length of 63 characters. + * * Keys and values can contain only lowercase letters, numeric characters, + * underscores, and dashes. All characters must use UTF-8 encoding, and + * international characters are allowed. + * * The key portion of a label must be unique. However, you can use the same + * key with multiple resources. + * * Keys must start with a lowercase letter or international character. + * + * For more information, see [Requirements for + * labels](https://cloud.google.com/resource-manager/docs/creating-managing-labels#requirements) + * in the Resource Manager documentation. + * @param {google.cloud.retail.v2alpha.SearchRequest.SpellCorrectionSpec} request.spellCorrectionSpec + * The spell correction specification that specifies the mode under + * which spell correction will take effect. + * @param {string} request.entity + * The entity for customers that may run multiple different entities, domains, + * sites or regions, for example, `Google US`, `Google Ads`, `Waymo`, + * `google.com`, `youtube.com`, etc. + * If this is set, it should be exactly matched with + * {@link protos.google.cloud.retail.v2alpha.UserEvent.entity|UserEvent.entity} to get + * search results boosted by entity. + * @param {google.cloud.retail.v2alpha.SearchRequest.ConversationalSearchSpec} [request.conversationalSearchSpec] + * Optional. This field specifies all conversational related parameters + * addition to traditional retail search. + * @param {google.cloud.retail.v2alpha.SearchRequest.TileNavigationSpec} [request.tileNavigationSpec] + * Optional. This field specifies tile navigation related parameters. + * @param {string} [request.languageCode] + * Optional. The BCP-47 language code, such as "en-US" or "sr-Latn" + * [list](https://www.unicode.org/cldr/charts/46/summary/root.html). For more + * information, see [Standardized codes](https://google.aip.dev/143). This + * field helps to better interpret the query. If a value isn't specified, the + * query language code is automatically detected, which may not be accurate. + * @param {string} [request.regionCode] + * Optional. The Unicode country/region code (CLDR) of a location, such as + * "US" and "419" + * [list](https://www.unicode.org/cldr/charts/46/supplemental/territory_information.html). + * For more information, see [Standardized codes](https://google.aip.dev/143). + * If set, then results will be boosted based on the region_code provided. + * @param {string} [request.placeId] + * Optional. An id corresponding to a place, such as a store id or region id. + * When specified, we use the price from the local inventory with the matching + * product's + * {@link protos.google.cloud.retail.v2alpha.LocalInventory.place_id|LocalInventory.place_id} + * for revenue optimization. + * @param {number[]} [request.userAttributes] + * Optional. The user attributes that could be used for personalization of + * search results. + * * Populate at most 100 key-value pairs per query. + * * Only supports string keys and repeated string values. + * * Duplcate keys are not allowed within a single query. + * + * Example: + * user_attributes: [ + * { key: "pets" + * value { + * values: "dog" + * values: "cat" + * } + * }, + * { key: "state" + * value { + * values: "CA" + * } + * } + * ] + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.cloud.retail.v2alpha.SearchResponse.SearchResult|SearchResult} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `searchAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ searchStream( - request?: protos.google.cloud.retail.v2alpha.ISearchRequest, - options?: CallOptions): - Transform{ + request?: protos.google.cloud.retail.v2alpha.ISearchRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'placement': request.placement ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + placement: request.placement ?? '', + }); const defaultCallSettings = this._defaults['search']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('search stream %j', request); return this.descriptors.page.search.createStream( this.innerApiCalls.search as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `search`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.placement - * Required. The resource name of the Retail Search serving config, such as - * `projects/* /locations/global/catalogs/default_catalog/servingConfigs/default_serving_config` - * or the name of the legacy placement resource, such as - * `projects/* /locations/global/catalogs/default_catalog/placements/default_search`. - * This field is used to identify the serving config name and the set - * of models that are used to make the search. - * @param {string} request.branch - * The branch resource name, such as - * `projects/* /locations/global/catalogs/default_catalog/branches/0`. - * - * Use "default_branch" as the branch ID or leave this field empty, to search - * products under the default branch. - * @param {string} request.query - * Raw search query. - * - * If this field is empty, the request is considered a category browsing - * request and returned results are based on - * {@link protos.google.cloud.retail.v2alpha.SearchRequest.filter|filter} and - * {@link protos.google.cloud.retail.v2alpha.SearchRequest.page_categories|page_categories}. - * @param {string} request.visitorId - * Required. A unique identifier for tracking visitors. For example, this - * could be implemented with an HTTP cookie, which should be able to uniquely - * identify a visitor on a single device. This unique identifier should not - * change if the visitor logs in or out of the website. - * - * This should be the same identifier as - * {@link protos.google.cloud.retail.v2alpha.UserEvent.visitor_id|UserEvent.visitor_id}. - * - * The field must be a UTF-8 encoded string with a length limit of 128 - * characters. Otherwise, an INVALID_ARGUMENT error is returned. - * @param {google.cloud.retail.v2alpha.UserInfo} request.userInfo - * User information. - * @param {number} request.pageSize - * Maximum number of {@link protos.google.cloud.retail.v2alpha.Product|Product}s to - * return. If unspecified, defaults to a reasonable value. The maximum allowed - * value is 120. Values above 120 will be coerced to 120. - * - * If this field is negative, an INVALID_ARGUMENT is returned. - * @param {string} request.pageToken - * A page token - * {@link protos.google.cloud.retail.v2alpha.SearchResponse.next_page_token|SearchResponse.next_page_token}, - * received from a previous - * {@link protos.google.cloud.retail.v2alpha.SearchService.Search|SearchService.Search} - * call. Provide this to retrieve the subsequent page. - * - * When paginating, all other parameters provided to - * {@link protos.google.cloud.retail.v2alpha.SearchService.Search|SearchService.Search} - * must match the call that provided the page token. Otherwise, an - * INVALID_ARGUMENT error is returned. - * @param {number} request.offset - * A 0-indexed integer that specifies the current offset (that is, starting - * result location, amongst the - * {@link protos.google.cloud.retail.v2alpha.Product|Product}s deemed by the API as - * relevant) in search results. This field is only considered if - * {@link protos.google.cloud.retail.v2alpha.SearchRequest.page_token|page_token} is - * unset. - * - * If this field is negative, an INVALID_ARGUMENT is returned. - * @param {string} request.filter - * The filter syntax consists of an expression language for constructing a - * predicate from one or more fields of the products being filtered. Filter - * expression is case-sensitive. For more information, see - * [Filter](https://cloud.google.com/retail/docs/filter-and-order#filter). - * - * If this field is unrecognizable, an INVALID_ARGUMENT is returned. - * @param {string} request.canonicalFilter - * The default filter that is applied when a user performs a search without - * checking any filters on the search page. - * - * The filter applied to every search request when quality improvement such as - * query expansion is needed. In the case a query does not have a sufficient - * amount of results this filter will be used to determine whether or not to - * enable the query expansion flow. The original filter will still be used for - * the query expanded search. - * This field is strongly recommended to achieve high search quality. - * - * For more information about filter syntax, see - * {@link protos.google.cloud.retail.v2alpha.SearchRequest.filter|SearchRequest.filter}. - * @param {string} request.orderBy - * The order in which products are returned. Products can be ordered by - * a field in an {@link protos.google.cloud.retail.v2alpha.Product|Product} object. Leave - * it unset if ordered by relevance. OrderBy expression is case-sensitive. For - * more information, see - * [Order](https://cloud.google.com/retail/docs/filter-and-order#order). - * - * If this field is unrecognizable, an INVALID_ARGUMENT is returned. - * @param {number[]} request.facetSpecs - * Facet specifications for faceted search. If empty, no facets are returned. - * - * A maximum of 200 values are allowed. Otherwise, an INVALID_ARGUMENT error - * is returned. - * @param {google.cloud.retail.v2alpha.SearchRequest.DynamicFacetSpec} request.dynamicFacetSpec - * Deprecated. Refer to https://cloud.google.com/retail/docs/configs#dynamic - * to enable dynamic facets. Do not set this field. - * - * The specification for dynamically generated facets. Notice that only - * textual facets can be dynamically generated. - * @param {google.cloud.retail.v2alpha.SearchRequest.BoostSpec} request.boostSpec - * Boost specification to boost certain products. For more information, see - * [Boost results](https://cloud.google.com/retail/docs/boosting). - * - * Notice that if both - * {@link protos.google.cloud.retail.v2alpha.ServingConfig.boost_control_ids|ServingConfig.boost_control_ids} - * and - * {@link protos.google.cloud.retail.v2alpha.SearchRequest.boost_spec|SearchRequest.boost_spec} - * are set, the boost conditions from both places are evaluated. If a search - * request matches multiple boost conditions, the final boost score is equal - * to the sum of the boost scores from all matched boost conditions. - * @param {google.cloud.retail.v2alpha.SearchRequest.QueryExpansionSpec} request.queryExpansionSpec - * The query expansion specification that specifies the conditions under which - * query expansion occurs. For more information, see [Query - * expansion](https://cloud.google.com/retail/docs/result-size#query_expansion). - * @param {google.cloud.retail.v2alpha.SearchRequest.RelevanceThreshold} request.relevanceThreshold - * The relevance threshold of the search results. - * - * Defaults to - * {@link protos.google.cloud.retail.v2alpha.SearchRequest.RelevanceThreshold.HIGH|RelevanceThreshold.HIGH}, - * which means only the most relevant results are shown, and the least number - * of results are returned. For more information, see [Adjust result - * size](https://cloud.google.com/retail/docs/result-size#relevance_thresholding). - * @param {string[]} request.variantRollupKeys - * The keys to fetch and rollup the matching - * {@link protos.google.cloud.retail.v2alpha.Product.Type.VARIANT|variant} - * {@link protos.google.cloud.retail.v2alpha.Product|Product}s attributes, - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo|FulfillmentInfo} or - * {@link protos.google.cloud.retail.v2alpha.LocalInventory|LocalInventory}s attributes. - * The attributes from all the matching - * {@link protos.google.cloud.retail.v2alpha.Product.Type.VARIANT|variant} - * {@link protos.google.cloud.retail.v2alpha.Product|Product}s or - * {@link protos.google.cloud.retail.v2alpha.LocalInventory|LocalInventory}s are merged - * and de-duplicated. Notice that rollup attributes will lead to extra query - * latency. Maximum number of keys is 30. - * - * For {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo|FulfillmentInfo}, a - * fulfillment type and a fulfillment ID must be provided in the format of - * "fulfillmentType.fulfillmentId". E.g., in "pickupInStore.store123", - * "pickupInStore" is fulfillment type and "store123" is the store ID. - * - * Supported keys are: - * - * * colorFamilies - * * price - * * originalPrice - * * discount - * * variantId - * * inventory(place_id,price) - * * inventory(place_id,original_price) - * * inventory(place_id,attributes.key), where key is any key in the - * {@link protos.google.cloud.retail.v2alpha.LocalInventory.attributes|Product.local_inventories.attributes} - * map. - * * attributes.key, where key is any key in the - * {@link protos.google.cloud.retail.v2alpha.Product.attributes|Product.attributes} map. - * * pickupInStore.id, where id is any - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.place_ids|FulfillmentInfo.place_ids} - * for - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.type|FulfillmentInfo.type} - * "pickup-in-store". - * * shipToStore.id, where id is any - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.place_ids|FulfillmentInfo.place_ids} - * for - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.type|FulfillmentInfo.type} - * "ship-to-store". - * * sameDayDelivery.id, where id is any - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.place_ids|FulfillmentInfo.place_ids} - * for - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.type|FulfillmentInfo.type} - * "same-day-delivery". - * * nextDayDelivery.id, where id is any - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.place_ids|FulfillmentInfo.place_ids} - * for - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.type|FulfillmentInfo.type} - * "next-day-delivery". - * * customFulfillment1.id, where id is any - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.place_ids|FulfillmentInfo.place_ids} - * for - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.type|FulfillmentInfo.type} - * "custom-type-1". - * * customFulfillment2.id, where id is any - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.place_ids|FulfillmentInfo.place_ids} - * for - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.type|FulfillmentInfo.type} - * "custom-type-2". - * * customFulfillment3.id, where id is any - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.place_ids|FulfillmentInfo.place_ids} - * for - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.type|FulfillmentInfo.type} - * "custom-type-3". - * * customFulfillment4.id, where id is any - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.place_ids|FulfillmentInfo.place_ids} - * for - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.type|FulfillmentInfo.type} - * "custom-type-4". - * * customFulfillment5.id, where id is any - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.place_ids|FulfillmentInfo.place_ids} - * for - * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.type|FulfillmentInfo.type} - * "custom-type-5". - * - * If this field is set to an invalid value other than these, an - * INVALID_ARGUMENT error is returned. - * @param {string[]} request.pageCategories - * The categories associated with a category page. Must be set for category - * navigation queries to achieve good search quality. The format should be - * the same as - * {@link protos.google.cloud.retail.v2alpha.UserEvent.page_categories|UserEvent.page_categories}; - * - * To represent full path of category, use '>' sign to separate different - * hierarchies. If '>' is part of the category name, replace it with - * other character(s). - * - * Category pages include special pages such as sales or promotions. For - * instance, a special sale page may have the category hierarchy: - * "pageCategories" : ["Sales > 2017 Black Friday Deals"]. - * @param {google.cloud.retail.v2alpha.SearchRequest.SearchMode} request.searchMode - * The search mode of the search request. If not specified, a single search - * request triggers both product search and faceted search. - * @param {google.cloud.retail.v2alpha.SearchRequest.PersonalizationSpec} request.personalizationSpec - * The specification for personalization. - * - * Notice that if both - * {@link protos.google.cloud.retail.v2alpha.ServingConfig.personalization_spec|ServingConfig.personalization_spec} - * and - * {@link protos.google.cloud.retail.v2alpha.SearchRequest.personalization_spec|SearchRequest.personalization_spec} - * are set. - * {@link protos.google.cloud.retail.v2alpha.SearchRequest.personalization_spec|SearchRequest.personalization_spec} - * will override - * {@link protos.google.cloud.retail.v2alpha.ServingConfig.personalization_spec|ServingConfig.personalization_spec}. - * @param {number[]} request.labels - * The labels applied to a resource must meet the following requirements: - * - * * Each resource can have multiple labels, up to a maximum of 64. - * * Each label must be a key-value pair. - * * Keys have a minimum length of 1 character and a maximum length of 63 - * characters and cannot be empty. Values can be empty and have a maximum - * length of 63 characters. - * * Keys and values can contain only lowercase letters, numeric characters, - * underscores, and dashes. All characters must use UTF-8 encoding, and - * international characters are allowed. - * * The key portion of a label must be unique. However, you can use the same - * key with multiple resources. - * * Keys must start with a lowercase letter or international character. - * - * For more information, see [Requirements for - * labels](https://cloud.google.com/resource-manager/docs/creating-managing-labels#requirements) - * in the Resource Manager documentation. - * @param {google.cloud.retail.v2alpha.SearchRequest.SpellCorrectionSpec} request.spellCorrectionSpec - * The spell correction specification that specifies the mode under - * which spell correction will take effect. - * @param {string} request.entity - * The entity for customers that may run multiple different entities, domains, - * sites or regions, for example, `Google US`, `Google Ads`, `Waymo`, - * `google.com`, `youtube.com`, etc. - * If this is set, it should be exactly matched with - * {@link protos.google.cloud.retail.v2alpha.UserEvent.entity|UserEvent.entity} to get - * search results boosted by entity. - * @param {google.cloud.retail.v2alpha.SearchRequest.ConversationalSearchSpec} [request.conversationalSearchSpec] - * Optional. This field specifies all conversational related parameters - * addition to traditional retail search. - * @param {google.cloud.retail.v2alpha.SearchRequest.TileNavigationSpec} [request.tileNavigationSpec] - * Optional. This field specifies tile navigation related parameters. - * @param {string} [request.languageCode] - * Optional. The BCP-47 language code, such as "en-US" or "sr-Latn" - * [list](https://www.unicode.org/cldr/charts/46/summary/root.html). For more - * information, see [Standardized codes](https://google.aip.dev/143). This - * field helps to better interpret the query. If a value isn't specified, the - * query language code is automatically detected, which may not be accurate. - * @param {string} [request.regionCode] - * Optional. The Unicode country/region code (CLDR) of a location, such as - * "US" and "419" - * [list](https://www.unicode.org/cldr/charts/46/supplemental/territory_information.html). - * For more information, see [Standardized codes](https://google.aip.dev/143). - * If set, then results will be boosted based on the region_code provided. - * @param {string} [request.placeId] - * Optional. An id corresponding to a place, such as a store id or region id. - * When specified, we use the price from the local inventory with the matching - * product's - * {@link protos.google.cloud.retail.v2alpha.LocalInventory.place_id|LocalInventory.place_id} - * for revenue optimization. - * @param {number[]} [request.userAttributes] - * Optional. The user attributes that could be used for personalization of - * search results. - * * Populate at most 100 key-value pairs per query. - * * Only supports string keys and repeated string values. - * * Duplcate keys are not allowed within a single query. - * - * Example: - * user_attributes: [ - * { key: "pets" - * value { - * values: "dog" - * values: "cat" - * } - * }, - * { key: "state" - * value { - * values: "CA" - * } - * } - * ] - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.cloud.retail.v2alpha.SearchResponse.SearchResult|SearchResult}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/search_service.search.js - * region_tag:retail_v2alpha_generated_SearchService_Search_async - */ + /** + * Equivalent to `search`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.placement + * Required. The resource name of the Retail Search serving config, such as + * `projects/* /locations/global/catalogs/default_catalog/servingConfigs/default_serving_config` + * or the name of the legacy placement resource, such as + * `projects/* /locations/global/catalogs/default_catalog/placements/default_search`. + * This field is used to identify the serving config name and the set + * of models that are used to make the search. + * @param {string} request.branch + * The branch resource name, such as + * `projects/* /locations/global/catalogs/default_catalog/branches/0`. + * + * Use "default_branch" as the branch ID or leave this field empty, to search + * products under the default branch. + * @param {string} request.query + * Raw search query. + * + * If this field is empty, the request is considered a category browsing + * request and returned results are based on + * {@link protos.google.cloud.retail.v2alpha.SearchRequest.filter|filter} and + * {@link protos.google.cloud.retail.v2alpha.SearchRequest.page_categories|page_categories}. + * @param {string} request.visitorId + * Required. A unique identifier for tracking visitors. For example, this + * could be implemented with an HTTP cookie, which should be able to uniquely + * identify a visitor on a single device. This unique identifier should not + * change if the visitor logs in or out of the website. + * + * This should be the same identifier as + * {@link protos.google.cloud.retail.v2alpha.UserEvent.visitor_id|UserEvent.visitor_id}. + * + * The field must be a UTF-8 encoded string with a length limit of 128 + * characters. Otherwise, an INVALID_ARGUMENT error is returned. + * @param {google.cloud.retail.v2alpha.UserInfo} request.userInfo + * User information. + * @param {number} request.pageSize + * Maximum number of {@link protos.google.cloud.retail.v2alpha.Product|Product}s to + * return. If unspecified, defaults to a reasonable value. The maximum allowed + * value is 120. Values above 120 will be coerced to 120. + * + * If this field is negative, an INVALID_ARGUMENT is returned. + * @param {string} request.pageToken + * A page token + * {@link protos.google.cloud.retail.v2alpha.SearchResponse.next_page_token|SearchResponse.next_page_token}, + * received from a previous + * {@link protos.google.cloud.retail.v2alpha.SearchService.Search|SearchService.Search} + * call. Provide this to retrieve the subsequent page. + * + * When paginating, all other parameters provided to + * {@link protos.google.cloud.retail.v2alpha.SearchService.Search|SearchService.Search} + * must match the call that provided the page token. Otherwise, an + * INVALID_ARGUMENT error is returned. + * @param {number} request.offset + * A 0-indexed integer that specifies the current offset (that is, starting + * result location, amongst the + * {@link protos.google.cloud.retail.v2alpha.Product|Product}s deemed by the API as + * relevant) in search results. This field is only considered if + * {@link protos.google.cloud.retail.v2alpha.SearchRequest.page_token|page_token} is + * unset. + * + * If this field is negative, an INVALID_ARGUMENT is returned. + * @param {string} request.filter + * The filter syntax consists of an expression language for constructing a + * predicate from one or more fields of the products being filtered. Filter + * expression is case-sensitive. For more information, see + * [Filter](https://cloud.google.com/retail/docs/filter-and-order#filter). + * + * If this field is unrecognizable, an INVALID_ARGUMENT is returned. + * @param {string} request.canonicalFilter + * The default filter that is applied when a user performs a search without + * checking any filters on the search page. + * + * The filter applied to every search request when quality improvement such as + * query expansion is needed. In the case a query does not have a sufficient + * amount of results this filter will be used to determine whether or not to + * enable the query expansion flow. The original filter will still be used for + * the query expanded search. + * This field is strongly recommended to achieve high search quality. + * + * For more information about filter syntax, see + * {@link protos.google.cloud.retail.v2alpha.SearchRequest.filter|SearchRequest.filter}. + * @param {string} request.orderBy + * The order in which products are returned. Products can be ordered by + * a field in an {@link protos.google.cloud.retail.v2alpha.Product|Product} object. Leave + * it unset if ordered by relevance. OrderBy expression is case-sensitive. For + * more information, see + * [Order](https://cloud.google.com/retail/docs/filter-and-order#order). + * + * If this field is unrecognizable, an INVALID_ARGUMENT is returned. + * @param {number[]} request.facetSpecs + * Facet specifications for faceted search. If empty, no facets are returned. + * + * A maximum of 200 values are allowed. Otherwise, an INVALID_ARGUMENT error + * is returned. + * @param {google.cloud.retail.v2alpha.SearchRequest.DynamicFacetSpec} request.dynamicFacetSpec + * Deprecated. Refer to https://cloud.google.com/retail/docs/configs#dynamic + * to enable dynamic facets. Do not set this field. + * + * The specification for dynamically generated facets. Notice that only + * textual facets can be dynamically generated. + * @param {google.cloud.retail.v2alpha.SearchRequest.BoostSpec} request.boostSpec + * Boost specification to boost certain products. For more information, see + * [Boost results](https://cloud.google.com/retail/docs/boosting). + * + * Notice that if both + * {@link protos.google.cloud.retail.v2alpha.ServingConfig.boost_control_ids|ServingConfig.boost_control_ids} + * and + * {@link protos.google.cloud.retail.v2alpha.SearchRequest.boost_spec|SearchRequest.boost_spec} + * are set, the boost conditions from both places are evaluated. If a search + * request matches multiple boost conditions, the final boost score is equal + * to the sum of the boost scores from all matched boost conditions. + * @param {google.cloud.retail.v2alpha.SearchRequest.QueryExpansionSpec} request.queryExpansionSpec + * The query expansion specification that specifies the conditions under which + * query expansion occurs. For more information, see [Query + * expansion](https://cloud.google.com/retail/docs/result-size#query_expansion). + * @param {google.cloud.retail.v2alpha.SearchRequest.RelevanceThreshold} request.relevanceThreshold + * The relevance threshold of the search results. + * + * Defaults to + * {@link protos.google.cloud.retail.v2alpha.SearchRequest.RelevanceThreshold.HIGH|RelevanceThreshold.HIGH}, + * which means only the most relevant results are shown, and the least number + * of results are returned. For more information, see [Adjust result + * size](https://cloud.google.com/retail/docs/result-size#relevance_thresholding). + * @param {string[]} request.variantRollupKeys + * The keys to fetch and rollup the matching + * {@link protos.google.cloud.retail.v2alpha.Product.Type.VARIANT|variant} + * {@link protos.google.cloud.retail.v2alpha.Product|Product}s attributes, + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo|FulfillmentInfo} or + * {@link protos.google.cloud.retail.v2alpha.LocalInventory|LocalInventory}s attributes. + * The attributes from all the matching + * {@link protos.google.cloud.retail.v2alpha.Product.Type.VARIANT|variant} + * {@link protos.google.cloud.retail.v2alpha.Product|Product}s or + * {@link protos.google.cloud.retail.v2alpha.LocalInventory|LocalInventory}s are merged + * and de-duplicated. Notice that rollup attributes will lead to extra query + * latency. Maximum number of keys is 30. + * + * For {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo|FulfillmentInfo}, a + * fulfillment type and a fulfillment ID must be provided in the format of + * "fulfillmentType.fulfillmentId". E.g., in "pickupInStore.store123", + * "pickupInStore" is fulfillment type and "store123" is the store ID. + * + * Supported keys are: + * + * * colorFamilies + * * price + * * originalPrice + * * discount + * * variantId + * * inventory(place_id,price) + * * inventory(place_id,original_price) + * * inventory(place_id,attributes.key), where key is any key in the + * {@link protos.google.cloud.retail.v2alpha.LocalInventory.attributes|Product.local_inventories.attributes} + * map. + * * attributes.key, where key is any key in the + * {@link protos.google.cloud.retail.v2alpha.Product.attributes|Product.attributes} map. + * * pickupInStore.id, where id is any + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.place_ids|FulfillmentInfo.place_ids} + * for + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.type|FulfillmentInfo.type} + * "pickup-in-store". + * * shipToStore.id, where id is any + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.place_ids|FulfillmentInfo.place_ids} + * for + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.type|FulfillmentInfo.type} + * "ship-to-store". + * * sameDayDelivery.id, where id is any + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.place_ids|FulfillmentInfo.place_ids} + * for + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.type|FulfillmentInfo.type} + * "same-day-delivery". + * * nextDayDelivery.id, where id is any + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.place_ids|FulfillmentInfo.place_ids} + * for + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.type|FulfillmentInfo.type} + * "next-day-delivery". + * * customFulfillment1.id, where id is any + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.place_ids|FulfillmentInfo.place_ids} + * for + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.type|FulfillmentInfo.type} + * "custom-type-1". + * * customFulfillment2.id, where id is any + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.place_ids|FulfillmentInfo.place_ids} + * for + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.type|FulfillmentInfo.type} + * "custom-type-2". + * * customFulfillment3.id, where id is any + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.place_ids|FulfillmentInfo.place_ids} + * for + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.type|FulfillmentInfo.type} + * "custom-type-3". + * * customFulfillment4.id, where id is any + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.place_ids|FulfillmentInfo.place_ids} + * for + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.type|FulfillmentInfo.type} + * "custom-type-4". + * * customFulfillment5.id, where id is any + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.place_ids|FulfillmentInfo.place_ids} + * for + * {@link protos.google.cloud.retail.v2alpha.FulfillmentInfo.type|FulfillmentInfo.type} + * "custom-type-5". + * + * If this field is set to an invalid value other than these, an + * INVALID_ARGUMENT error is returned. + * @param {string[]} request.pageCategories + * The categories associated with a category page. Must be set for category + * navigation queries to achieve good search quality. The format should be + * the same as + * {@link protos.google.cloud.retail.v2alpha.UserEvent.page_categories|UserEvent.page_categories}; + * + * To represent full path of category, use '>' sign to separate different + * hierarchies. If '>' is part of the category name, replace it with + * other character(s). + * + * Category pages include special pages such as sales or promotions. For + * instance, a special sale page may have the category hierarchy: + * "pageCategories" : ["Sales > 2017 Black Friday Deals"]. + * @param {google.cloud.retail.v2alpha.SearchRequest.SearchMode} request.searchMode + * The search mode of the search request. If not specified, a single search + * request triggers both product search and faceted search. + * @param {google.cloud.retail.v2alpha.SearchRequest.PersonalizationSpec} request.personalizationSpec + * The specification for personalization. + * + * Notice that if both + * {@link protos.google.cloud.retail.v2alpha.ServingConfig.personalization_spec|ServingConfig.personalization_spec} + * and + * {@link protos.google.cloud.retail.v2alpha.SearchRequest.personalization_spec|SearchRequest.personalization_spec} + * are set. + * {@link protos.google.cloud.retail.v2alpha.SearchRequest.personalization_spec|SearchRequest.personalization_spec} + * will override + * {@link protos.google.cloud.retail.v2alpha.ServingConfig.personalization_spec|ServingConfig.personalization_spec}. + * @param {number[]} request.labels + * The labels applied to a resource must meet the following requirements: + * + * * Each resource can have multiple labels, up to a maximum of 64. + * * Each label must be a key-value pair. + * * Keys have a minimum length of 1 character and a maximum length of 63 + * characters and cannot be empty. Values can be empty and have a maximum + * length of 63 characters. + * * Keys and values can contain only lowercase letters, numeric characters, + * underscores, and dashes. All characters must use UTF-8 encoding, and + * international characters are allowed. + * * The key portion of a label must be unique. However, you can use the same + * key with multiple resources. + * * Keys must start with a lowercase letter or international character. + * + * For more information, see [Requirements for + * labels](https://cloud.google.com/resource-manager/docs/creating-managing-labels#requirements) + * in the Resource Manager documentation. + * @param {google.cloud.retail.v2alpha.SearchRequest.SpellCorrectionSpec} request.spellCorrectionSpec + * The spell correction specification that specifies the mode under + * which spell correction will take effect. + * @param {string} request.entity + * The entity for customers that may run multiple different entities, domains, + * sites or regions, for example, `Google US`, `Google Ads`, `Waymo`, + * `google.com`, `youtube.com`, etc. + * If this is set, it should be exactly matched with + * {@link protos.google.cloud.retail.v2alpha.UserEvent.entity|UserEvent.entity} to get + * search results boosted by entity. + * @param {google.cloud.retail.v2alpha.SearchRequest.ConversationalSearchSpec} [request.conversationalSearchSpec] + * Optional. This field specifies all conversational related parameters + * addition to traditional retail search. + * @param {google.cloud.retail.v2alpha.SearchRequest.TileNavigationSpec} [request.tileNavigationSpec] + * Optional. This field specifies tile navigation related parameters. + * @param {string} [request.languageCode] + * Optional. The BCP-47 language code, such as "en-US" or "sr-Latn" + * [list](https://www.unicode.org/cldr/charts/46/summary/root.html). For more + * information, see [Standardized codes](https://google.aip.dev/143). This + * field helps to better interpret the query. If a value isn't specified, the + * query language code is automatically detected, which may not be accurate. + * @param {string} [request.regionCode] + * Optional. The Unicode country/region code (CLDR) of a location, such as + * "US" and "419" + * [list](https://www.unicode.org/cldr/charts/46/supplemental/territory_information.html). + * For more information, see [Standardized codes](https://google.aip.dev/143). + * If set, then results will be boosted based on the region_code provided. + * @param {string} [request.placeId] + * Optional. An id corresponding to a place, such as a store id or region id. + * When specified, we use the price from the local inventory with the matching + * product's + * {@link protos.google.cloud.retail.v2alpha.LocalInventory.place_id|LocalInventory.place_id} + * for revenue optimization. + * @param {number[]} [request.userAttributes] + * Optional. The user attributes that could be used for personalization of + * search results. + * * Populate at most 100 key-value pairs per query. + * * Only supports string keys and repeated string values. + * * Duplcate keys are not allowed within a single query. + * + * Example: + * user_attributes: [ + * { key: "pets" + * value { + * values: "dog" + * values: "cat" + * } + * }, + * { key: "state" + * value { + * values: "CA" + * } + * } + * ] + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.cloud.retail.v2alpha.SearchResponse.SearchResult|SearchResult}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/search_service.search.js + * region_tag:retail_v2alpha_generated_SearchService_Search_async + */ searchAsync( - request?: protos.google.cloud.retail.v2alpha.ISearchRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.cloud.retail.v2alpha.ISearchRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'placement': request.placement ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + placement: request.placement ?? '', + }); const defaultCallSettings = this._defaults['search']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('search iterate %j', request); return this.descriptors.page.search.asyncIterate( this.innerApiCalls['search'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } // -------------------- @@ -1459,7 +1523,7 @@ export class SearchServiceClient { * @param {string} project * @returns {string} Resource name string. */ - alertConfigPath(project:string) { + alertConfigPath(project: string) { return this.pathTemplates.alertConfigPathTemplate.render({ project: project, }); @@ -1473,7 +1537,8 @@ export class SearchServiceClient { * @returns {string} A string representing the project. */ matchProjectFromAlertConfigName(alertConfigName: string) { - return this.pathTemplates.alertConfigPathTemplate.match(alertConfigName).project; + return this.pathTemplates.alertConfigPathTemplate.match(alertConfigName) + .project; } /** @@ -1484,7 +1549,7 @@ export class SearchServiceClient { * @param {string} catalog * @returns {string} Resource name string. */ - attributesConfigPath(project:string,location:string,catalog:string) { + attributesConfigPath(project: string, location: string, catalog: string) { return this.pathTemplates.attributesConfigPathTemplate.render({ project: project, location: location, @@ -1500,7 +1565,9 @@ export class SearchServiceClient { * @returns {string} A string representing the project. */ matchProjectFromAttributesConfigName(attributesConfigName: string) { - return this.pathTemplates.attributesConfigPathTemplate.match(attributesConfigName).project; + return this.pathTemplates.attributesConfigPathTemplate.match( + attributesConfigName, + ).project; } /** @@ -1511,7 +1578,9 @@ export class SearchServiceClient { * @returns {string} A string representing the location. */ matchLocationFromAttributesConfigName(attributesConfigName: string) { - return this.pathTemplates.attributesConfigPathTemplate.match(attributesConfigName).location; + return this.pathTemplates.attributesConfigPathTemplate.match( + attributesConfigName, + ).location; } /** @@ -1522,7 +1591,9 @@ export class SearchServiceClient { * @returns {string} A string representing the catalog. */ matchCatalogFromAttributesConfigName(attributesConfigName: string) { - return this.pathTemplates.attributesConfigPathTemplate.match(attributesConfigName).catalog; + return this.pathTemplates.attributesConfigPathTemplate.match( + attributesConfigName, + ).catalog; } /** @@ -1534,7 +1605,12 @@ export class SearchServiceClient { * @param {string} branch * @returns {string} Resource name string. */ - branchPath(project:string,location:string,catalog:string,branch:string) { + branchPath( + project: string, + location: string, + catalog: string, + branch: string, + ) { return this.pathTemplates.branchPathTemplate.render({ project: project, location: location, @@ -1595,7 +1671,7 @@ export class SearchServiceClient { * @param {string} catalog * @returns {string} Resource name string. */ - catalogPath(project:string,location:string,catalog:string) { + catalogPath(project: string, location: string, catalog: string) { return this.pathTemplates.catalogPathTemplate.render({ project: project, location: location, @@ -1644,7 +1720,7 @@ export class SearchServiceClient { * @param {string} catalog * @returns {string} Resource name string. */ - completionConfigPath(project:string,location:string,catalog:string) { + completionConfigPath(project: string, location: string, catalog: string) { return this.pathTemplates.completionConfigPathTemplate.render({ project: project, location: location, @@ -1660,7 +1736,9 @@ export class SearchServiceClient { * @returns {string} A string representing the project. */ matchProjectFromCompletionConfigName(completionConfigName: string) { - return this.pathTemplates.completionConfigPathTemplate.match(completionConfigName).project; + return this.pathTemplates.completionConfigPathTemplate.match( + completionConfigName, + ).project; } /** @@ -1671,7 +1749,9 @@ export class SearchServiceClient { * @returns {string} A string representing the location. */ matchLocationFromCompletionConfigName(completionConfigName: string) { - return this.pathTemplates.completionConfigPathTemplate.match(completionConfigName).location; + return this.pathTemplates.completionConfigPathTemplate.match( + completionConfigName, + ).location; } /** @@ -1682,7 +1762,9 @@ export class SearchServiceClient { * @returns {string} A string representing the catalog. */ matchCatalogFromCompletionConfigName(completionConfigName: string) { - return this.pathTemplates.completionConfigPathTemplate.match(completionConfigName).catalog; + return this.pathTemplates.completionConfigPathTemplate.match( + completionConfigName, + ).catalog; } /** @@ -1694,7 +1776,12 @@ export class SearchServiceClient { * @param {string} control * @returns {string} Resource name string. */ - controlPath(project:string,location:string,catalog:string,control:string) { + controlPath( + project: string, + location: string, + catalog: string, + control: string, + ) { return this.pathTemplates.controlPathTemplate.render({ project: project, location: location, @@ -1756,7 +1843,12 @@ export class SearchServiceClient { * @param {string} experiment * @returns {string} Resource name string. */ - experimentPath(project:string,location:string,catalog:string,experiment:string) { + experimentPath( + project: string, + location: string, + catalog: string, + experiment: string, + ) { return this.pathTemplates.experimentPathTemplate.render({ project: project, location: location, @@ -1773,7 +1865,8 @@ export class SearchServiceClient { * @returns {string} A string representing the project. */ matchProjectFromExperimentName(experimentName: string) { - return this.pathTemplates.experimentPathTemplate.match(experimentName).project; + return this.pathTemplates.experimentPathTemplate.match(experimentName) + .project; } /** @@ -1784,7 +1877,8 @@ export class SearchServiceClient { * @returns {string} A string representing the location. */ matchLocationFromExperimentName(experimentName: string) { - return this.pathTemplates.experimentPathTemplate.match(experimentName).location; + return this.pathTemplates.experimentPathTemplate.match(experimentName) + .location; } /** @@ -1795,7 +1889,8 @@ export class SearchServiceClient { * @returns {string} A string representing the catalog. */ matchCatalogFromExperimentName(experimentName: string) { - return this.pathTemplates.experimentPathTemplate.match(experimentName).catalog; + return this.pathTemplates.experimentPathTemplate.match(experimentName) + .catalog; } /** @@ -1806,7 +1901,8 @@ export class SearchServiceClient { * @returns {string} A string representing the experiment. */ matchExperimentFromExperimentName(experimentName: string) { - return this.pathTemplates.experimentPathTemplate.match(experimentName).experiment; + return this.pathTemplates.experimentPathTemplate.match(experimentName) + .experiment; } /** @@ -1815,7 +1911,7 @@ export class SearchServiceClient { * @param {string} project * @returns {string} Resource name string. */ - loggingConfigPath(project:string) { + loggingConfigPath(project: string) { return this.pathTemplates.loggingConfigPathTemplate.render({ project: project, }); @@ -1829,7 +1925,8 @@ export class SearchServiceClient { * @returns {string} A string representing the project. */ matchProjectFromLoggingConfigName(loggingConfigName: string) { - return this.pathTemplates.loggingConfigPathTemplate.match(loggingConfigName).project; + return this.pathTemplates.loggingConfigPathTemplate.match(loggingConfigName) + .project; } /** @@ -1841,7 +1938,12 @@ export class SearchServiceClient { * @param {string} merchant_center_account_link * @returns {string} Resource name string. */ - merchantCenterAccountLinkPath(project:string,location:string,catalog:string,merchantCenterAccountLink:string) { + merchantCenterAccountLinkPath( + project: string, + location: string, + catalog: string, + merchantCenterAccountLink: string, + ) { return this.pathTemplates.merchantCenterAccountLinkPathTemplate.render({ project: project, location: location, @@ -1857,8 +1959,12 @@ export class SearchServiceClient { * A fully-qualified path representing MerchantCenterAccountLink resource. * @returns {string} A string representing the project. */ - matchProjectFromMerchantCenterAccountLinkName(merchantCenterAccountLinkName: string) { - return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match(merchantCenterAccountLinkName).project; + matchProjectFromMerchantCenterAccountLinkName( + merchantCenterAccountLinkName: string, + ) { + return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match( + merchantCenterAccountLinkName, + ).project; } /** @@ -1868,8 +1974,12 @@ export class SearchServiceClient { * A fully-qualified path representing MerchantCenterAccountLink resource. * @returns {string} A string representing the location. */ - matchLocationFromMerchantCenterAccountLinkName(merchantCenterAccountLinkName: string) { - return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match(merchantCenterAccountLinkName).location; + matchLocationFromMerchantCenterAccountLinkName( + merchantCenterAccountLinkName: string, + ) { + return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match( + merchantCenterAccountLinkName, + ).location; } /** @@ -1879,8 +1989,12 @@ export class SearchServiceClient { * A fully-qualified path representing MerchantCenterAccountLink resource. * @returns {string} A string representing the catalog. */ - matchCatalogFromMerchantCenterAccountLinkName(merchantCenterAccountLinkName: string) { - return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match(merchantCenterAccountLinkName).catalog; + matchCatalogFromMerchantCenterAccountLinkName( + merchantCenterAccountLinkName: string, + ) { + return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match( + merchantCenterAccountLinkName, + ).catalog; } /** @@ -1890,8 +2004,12 @@ export class SearchServiceClient { * A fully-qualified path representing MerchantCenterAccountLink resource. * @returns {string} A string representing the merchant_center_account_link. */ - matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName(merchantCenterAccountLinkName: string) { - return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match(merchantCenterAccountLinkName).merchant_center_account_link; + matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName( + merchantCenterAccountLinkName: string, + ) { + return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match( + merchantCenterAccountLinkName, + ).merchant_center_account_link; } /** @@ -1903,7 +2021,7 @@ export class SearchServiceClient { * @param {string} model * @returns {string} Resource name string. */ - modelPath(project:string,location:string,catalog:string,model:string) { + modelPath(project: string, location: string, catalog: string, model: string) { return this.pathTemplates.modelPathTemplate.render({ project: project, location: location, @@ -1966,7 +2084,13 @@ export class SearchServiceClient { * @param {string} product * @returns {string} Resource name string. */ - productPath(project:string,location:string,catalog:string,branch:string,product:string) { + productPath( + project: string, + location: string, + catalog: string, + branch: string, + product: string, + ) { return this.pathTemplates.productPathTemplate.render({ project: project, location: location, @@ -2037,7 +2161,7 @@ export class SearchServiceClient { * @param {string} project * @returns {string} Resource name string. */ - retailProjectPath(project:string) { + retailProjectPath(project: string) { return this.pathTemplates.retailProjectPathTemplate.render({ project: project, }); @@ -2051,7 +2175,8 @@ export class SearchServiceClient { * @returns {string} A string representing the project. */ matchProjectFromRetailProjectName(retailProjectName: string) { - return this.pathTemplates.retailProjectPathTemplate.match(retailProjectName).project; + return this.pathTemplates.retailProjectPathTemplate.match(retailProjectName) + .project; } /** @@ -2063,7 +2188,12 @@ export class SearchServiceClient { * @param {string} serving_config * @returns {string} Resource name string. */ - servingConfigPath(project:string,location:string,catalog:string,servingConfig:string) { + servingConfigPath( + project: string, + location: string, + catalog: string, + servingConfig: string, + ) { return this.pathTemplates.servingConfigPathTemplate.render({ project: project, location: location, @@ -2080,7 +2210,8 @@ export class SearchServiceClient { * @returns {string} A string representing the project. */ matchProjectFromServingConfigName(servingConfigName: string) { - return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName).project; + return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName) + .project; } /** @@ -2091,7 +2222,8 @@ export class SearchServiceClient { * @returns {string} A string representing the location. */ matchLocationFromServingConfigName(servingConfigName: string) { - return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName).location; + return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName) + .location; } /** @@ -2102,7 +2234,8 @@ export class SearchServiceClient { * @returns {string} A string representing the catalog. */ matchCatalogFromServingConfigName(servingConfigName: string) { - return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName).catalog; + return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName) + .catalog; } /** @@ -2113,7 +2246,8 @@ export class SearchServiceClient { * @returns {string} A string representing the serving_config. */ matchServingConfigFromServingConfigName(servingConfigName: string) { - return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName).serving_config; + return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName) + .serving_config; } /** @@ -2124,7 +2258,7 @@ export class SearchServiceClient { */ close(): Promise { if (this.searchServiceStub && !this._terminated) { - return this.searchServiceStub.then(stub => { + return this.searchServiceStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -2132,4 +2266,4 @@ export class SearchServiceClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/core/generator/gapic-generator-typescript/baselines/retail/src/v2alpha/serving_config_service_client.ts.baseline b/core/generator/gapic-generator-typescript/baselines/retail/src/v2alpha/serving_config_service_client.ts.baseline index e14660714811..8b87c6a592ec 100644 --- a/core/generator/gapic-generator-typescript/baselines/retail/src/v2alpha/serving_config_service_client.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/retail/src/v2alpha/serving_config_service_client.ts.baseline @@ -18,11 +18,18 @@ /* global window */ import type * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions, PaginationCallback, GaxCall} from 'google-gax'; -import {Transform} from 'stream'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + PaginationCallback, + GaxCall, +} from 'google-gax'; +import { Transform } from 'stream'; import * as protos from '../../protos/protos'; import jsonProtos = require('../../protos/protos.json'); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; /** * Client JSON configuration object, loaded from @@ -44,7 +51,7 @@ export class ServingConfigServiceClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('retail'); @@ -57,9 +64,9 @@ export class ServingConfigServiceClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; - servingConfigServiceStub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; + servingConfigServiceStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of ServingConfigServiceClient. @@ -100,21 +107,42 @@ export class ServingConfigServiceClient { * const client = new ServingConfigServiceClient({fallback: true}, gax); * ``` */ - constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { // Ensure that options include all the required fields. const staticMembers = this.constructor as typeof ServingConfigServiceClient; - if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { - throw new Error('Please set either universe_domain or universeDomain, but not both.'); + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); } - const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; - this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; this._servicePath = 'retail.' + this._universeDomain; - const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; - const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. if (servicePath !== this._servicePath && !('scopes' in opts)) { @@ -136,7 +164,7 @@ export class ServingConfigServiceClient { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; @@ -150,10 +178,7 @@ export class ServingConfigServiceClient { } // Determine the client header string. - const clientHeader = [ - `gax/${this._gaxModule.version}`, - `gapic/${version}`, - ]; + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/${process.versions.node}`); } else { @@ -175,40 +200,40 @@ export class ServingConfigServiceClient { // Create useful helper objects for these. this.pathTemplates = { alertConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/alertConfig' + 'projects/{project}/alertConfig', ), attributesConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/attributesConfig' + 'projects/{project}/locations/{location}/catalogs/{catalog}/attributesConfig', ), branchPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}', ), catalogPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}' + 'projects/{project}/locations/{location}/catalogs/{catalog}', ), completionConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/completionConfig' + 'projects/{project}/locations/{location}/catalogs/{catalog}/completionConfig', ), controlPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/controls/{control}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/controls/{control}', ), loggingConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/loggingConfig' + 'projects/{project}/loggingConfig', ), merchantCenterAccountLinkPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/merchantCenterAccountLinks/{merchant_center_account_link}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/merchantCenterAccountLinks/{merchant_center_account_link}', ), modelPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/models/{model}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/models/{model}', ), productPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}', ), retailProjectPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/retailProject' + 'projects/{project}/retailProject', ), servingConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/servingConfigs/{serving_config}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/servingConfigs/{serving_config}', ), }; @@ -216,14 +241,20 @@ export class ServingConfigServiceClient { // (e.g. 50 results at a time, with tokens to get subsequent // pages). Denote the keys used for pagination and results. this.descriptors.page = { - listServingConfigs: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'servingConfigs') + listServingConfigs: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'servingConfigs', + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.cloud.retail.v2alpha.ServingConfigService', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.cloud.retail.v2alpha.ServingConfigService', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + { 'x-goog-api-client': clientHeader.join(' ') }, + ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -254,37 +285,49 @@ export class ServingConfigServiceClient { // Put together the "service stub" for // google.cloud.retail.v2alpha.ServingConfigService. this.servingConfigServiceStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.cloud.retail.v2alpha.ServingConfigService') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any - (this._protos as any).google.cloud.retail.v2alpha.ServingConfigService, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.cloud.retail.v2alpha.ServingConfigService', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any + (this._protos as any).google.cloud.retail.v2alpha + .ServingConfigService, + this._opts, + this._providedCustomServicePath, + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const servingConfigServiceStubMethods = - ['createServingConfig', 'deleteServingConfig', 'updateServingConfig', 'getServingConfig', 'listServingConfigs', 'addControl', 'removeControl']; + const servingConfigServiceStubMethods = [ + 'createServingConfig', + 'deleteServingConfig', + 'updateServingConfig', + 'getServingConfig', + 'listServingConfigs', + 'addControl', + 'removeControl', + ]; for (const methodName of servingConfigServiceStubMethods) { const callPromise = this.servingConfigServiceStub.then( - stub => (...args: Array<{}>) => { - if (this._terminated) { - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error|null|undefined) => () => { + (stub) => + (...args: Array<{}>) => { + if (this._terminated) { + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { throw err; - }); + }, + ); - const descriptor = - this.descriptors.page[methodName] || - undefined; + const descriptor = this.descriptors.page[methodName] || undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -299,8 +342,14 @@ export class ServingConfigServiceClient { * @returns {string} The DNS address for this service. */ static get servicePath() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'retail.googleapis.com'; } @@ -311,8 +360,14 @@ export class ServingConfigServiceClient { * @returns {string} The DNS address for this service. */ static get apiEndpoint() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'retail.googleapis.com'; } @@ -343,9 +398,7 @@ export class ServingConfigServiceClient { * @returns {string[]} List of default scopes. */ static get scopes() { - return [ - 'https://www.googleapis.com/auth/cloud-platform' - ]; + return ['https://www.googleapis.com/auth/cloud-platform']; } getProjectId(): Promise; @@ -354,8 +407,9 @@ export class ServingConfigServiceClient { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId(callback?: Callback): - Promise|void { + getProjectId( + callback?: Callback, + ): Promise | void { if (callback) { this.auth.getProjectId(callback); return; @@ -366,701 +420,990 @@ export class ServingConfigServiceClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Creates a ServingConfig. - * - * A maximum of 100 - * {@link protos.google.cloud.retail.v2alpha.ServingConfig|ServingConfig}s are allowed in - * a {@link protos.google.cloud.retail.v2alpha.Catalog|Catalog}, otherwise a - * FAILED_PRECONDITION error is returned. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. Full resource name of parent. Format: - * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}` - * @param {google.cloud.retail.v2alpha.ServingConfig} request.servingConfig - * Required. The ServingConfig to create. - * @param {string} request.servingConfigId - * Required. The ID to use for the ServingConfig, which will become the final - * component of the ServingConfig's resource name. - * - * This value should be 4-63 characters, and valid characters - * are /{@link protos.0-9|a-z}-_/. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.ServingConfig|ServingConfig}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/serving_config_service.create_serving_config.js - * region_tag:retail_v2alpha_generated_ServingConfigService_CreateServingConfig_async - */ + /** + * Creates a ServingConfig. + * + * A maximum of 100 + * {@link protos.google.cloud.retail.v2alpha.ServingConfig|ServingConfig}s are allowed in + * a {@link protos.google.cloud.retail.v2alpha.Catalog|Catalog}, otherwise a + * FAILED_PRECONDITION error is returned. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Full resource name of parent. Format: + * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}` + * @param {google.cloud.retail.v2alpha.ServingConfig} request.servingConfig + * Required. The ServingConfig to create. + * @param {string} request.servingConfigId + * Required. The ID to use for the ServingConfig, which will become the final + * component of the ServingConfig's resource name. + * + * This value should be 4-63 characters, and valid characters + * are /{@link protos.0-9|a-z}-_/. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.ServingConfig|ServingConfig}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/serving_config_service.create_serving_config.js + * region_tag:retail_v2alpha_generated_ServingConfigService_CreateServingConfig_async + */ createServingConfig( - request?: protos.google.cloud.retail.v2alpha.ICreateServingConfigRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.retail.v2alpha.IServingConfig, - protos.google.cloud.retail.v2alpha.ICreateServingConfigRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.ICreateServingConfigRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IServingConfig, + ( + | protos.google.cloud.retail.v2alpha.ICreateServingConfigRequest + | undefined + ), + {} | undefined, + ] + >; createServingConfig( - request: protos.google.cloud.retail.v2alpha.ICreateServingConfigRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.retail.v2alpha.IServingConfig, - protos.google.cloud.retail.v2alpha.ICreateServingConfigRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.ICreateServingConfigRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.retail.v2alpha.IServingConfig, + | protos.google.cloud.retail.v2alpha.ICreateServingConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createServingConfig( - request: protos.google.cloud.retail.v2alpha.ICreateServingConfigRequest, - callback: Callback< - protos.google.cloud.retail.v2alpha.IServingConfig, - protos.google.cloud.retail.v2alpha.ICreateServingConfigRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.ICreateServingConfigRequest, + callback: Callback< + protos.google.cloud.retail.v2alpha.IServingConfig, + | protos.google.cloud.retail.v2alpha.ICreateServingConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createServingConfig( - request?: protos.google.cloud.retail.v2alpha.ICreateServingConfigRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.retail.v2alpha.IServingConfig, - protos.google.cloud.retail.v2alpha.ICreateServingConfigRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.retail.v2alpha.ICreateServingConfigRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.retail.v2alpha.IServingConfig, - protos.google.cloud.retail.v2alpha.ICreateServingConfigRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.retail.v2alpha.IServingConfig, - protos.google.cloud.retail.v2alpha.ICreateServingConfigRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.retail.v2alpha.ICreateServingConfigRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.retail.v2alpha.IServingConfig, + | protos.google.cloud.retail.v2alpha.ICreateServingConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IServingConfig, + ( + | protos.google.cloud.retail.v2alpha.ICreateServingConfigRequest + | undefined + ), + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('createServingConfig request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.retail.v2alpha.IServingConfig, - protos.google.cloud.retail.v2alpha.ICreateServingConfigRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.retail.v2alpha.IServingConfig, + | protos.google.cloud.retail.v2alpha.ICreateServingConfigRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createServingConfig response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.createServingConfig(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.retail.v2alpha.IServingConfig, - protos.google.cloud.retail.v2alpha.ICreateServingConfigRequest|undefined, - {}|undefined - ]) => { - this._log.info('createServingConfig response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createServingConfig(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.retail.v2alpha.IServingConfig, + ( + | protos.google.cloud.retail.v2alpha.ICreateServingConfigRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('createServingConfig response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Deletes a ServingConfig. - * - * Returns a NotFound error if the ServingConfig does not exist. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The resource name of the ServingConfig to delete. Format: - * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id}` - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/serving_config_service.delete_serving_config.js - * region_tag:retail_v2alpha_generated_ServingConfigService_DeleteServingConfig_async - */ + /** + * Deletes a ServingConfig. + * + * Returns a NotFound error if the ServingConfig does not exist. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The resource name of the ServingConfig to delete. Format: + * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id}` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/serving_config_service.delete_serving_config.js + * region_tag:retail_v2alpha_generated_ServingConfigService_DeleteServingConfig_async + */ deleteServingConfig( - request?: protos.google.cloud.retail.v2alpha.IDeleteServingConfigRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.cloud.retail.v2alpha.IDeleteServingConfigRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.IDeleteServingConfigRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.cloud.retail.v2alpha.IDeleteServingConfigRequest + | undefined + ), + {} | undefined, + ] + >; deleteServingConfig( - request: protos.google.cloud.retail.v2alpha.IDeleteServingConfigRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.cloud.retail.v2alpha.IDeleteServingConfigRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IDeleteServingConfigRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.cloud.retail.v2alpha.IDeleteServingConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteServingConfig( - request: protos.google.cloud.retail.v2alpha.IDeleteServingConfigRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.cloud.retail.v2alpha.IDeleteServingConfigRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IDeleteServingConfigRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.cloud.retail.v2alpha.IDeleteServingConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteServingConfig( - request?: protos.google.cloud.retail.v2alpha.IDeleteServingConfigRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.protobuf.IEmpty, - protos.google.cloud.retail.v2alpha.IDeleteServingConfigRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.retail.v2alpha.IDeleteServingConfigRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.cloud.retail.v2alpha.IDeleteServingConfigRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.cloud.retail.v2alpha.IDeleteServingConfigRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.retail.v2alpha.IDeleteServingConfigRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + | protos.google.cloud.retail.v2alpha.IDeleteServingConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.cloud.retail.v2alpha.IDeleteServingConfigRequest + | undefined + ), + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('deleteServingConfig request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.cloud.retail.v2alpha.IDeleteServingConfigRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.cloud.retail.v2alpha.IDeleteServingConfigRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteServingConfig response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.deleteServingConfig(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.cloud.retail.v2alpha.IDeleteServingConfigRequest|undefined, - {}|undefined - ]) => { - this._log.info('deleteServingConfig response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteServingConfig(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + ( + | protos.google.cloud.retail.v2alpha.IDeleteServingConfigRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('deleteServingConfig response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Updates a ServingConfig. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.cloud.retail.v2alpha.ServingConfig} request.servingConfig - * Required. The ServingConfig to update. - * @param {google.protobuf.FieldMask} request.updateMask - * Indicates which fields in the provided - * {@link protos.google.cloud.retail.v2alpha.ServingConfig|ServingConfig} to update. The - * following are NOT supported: - * - * * {@link protos.google.cloud.retail.v2alpha.ServingConfig.name|ServingConfig.name} - * - * If not set, all supported fields are updated. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.ServingConfig|ServingConfig}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/serving_config_service.update_serving_config.js - * region_tag:retail_v2alpha_generated_ServingConfigService_UpdateServingConfig_async - */ + /** + * Updates a ServingConfig. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.cloud.retail.v2alpha.ServingConfig} request.servingConfig + * Required. The ServingConfig to update. + * @param {google.protobuf.FieldMask} request.updateMask + * Indicates which fields in the provided + * {@link protos.google.cloud.retail.v2alpha.ServingConfig|ServingConfig} to update. The + * following are NOT supported: + * + * * {@link protos.google.cloud.retail.v2alpha.ServingConfig.name|ServingConfig.name} + * + * If not set, all supported fields are updated. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.ServingConfig|ServingConfig}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/serving_config_service.update_serving_config.js + * region_tag:retail_v2alpha_generated_ServingConfigService_UpdateServingConfig_async + */ updateServingConfig( - request?: protos.google.cloud.retail.v2alpha.IUpdateServingConfigRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.retail.v2alpha.IServingConfig, - protos.google.cloud.retail.v2alpha.IUpdateServingConfigRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.IUpdateServingConfigRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IServingConfig, + ( + | protos.google.cloud.retail.v2alpha.IUpdateServingConfigRequest + | undefined + ), + {} | undefined, + ] + >; updateServingConfig( - request: protos.google.cloud.retail.v2alpha.IUpdateServingConfigRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.retail.v2alpha.IServingConfig, - protos.google.cloud.retail.v2alpha.IUpdateServingConfigRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IUpdateServingConfigRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.retail.v2alpha.IServingConfig, + | protos.google.cloud.retail.v2alpha.IUpdateServingConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateServingConfig( - request: protos.google.cloud.retail.v2alpha.IUpdateServingConfigRequest, - callback: Callback< - protos.google.cloud.retail.v2alpha.IServingConfig, - protos.google.cloud.retail.v2alpha.IUpdateServingConfigRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IUpdateServingConfigRequest, + callback: Callback< + protos.google.cloud.retail.v2alpha.IServingConfig, + | protos.google.cloud.retail.v2alpha.IUpdateServingConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateServingConfig( - request?: protos.google.cloud.retail.v2alpha.IUpdateServingConfigRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.cloud.retail.v2alpha.IUpdateServingConfigRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.retail.v2alpha.IServingConfig, - protos.google.cloud.retail.v2alpha.IUpdateServingConfigRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.cloud.retail.v2alpha.IServingConfig, - protos.google.cloud.retail.v2alpha.IUpdateServingConfigRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.retail.v2alpha.IServingConfig, - protos.google.cloud.retail.v2alpha.IUpdateServingConfigRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.retail.v2alpha.IUpdateServingConfigRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.retail.v2alpha.IServingConfig, + | protos.google.cloud.retail.v2alpha.IUpdateServingConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IServingConfig, + ( + | protos.google.cloud.retail.v2alpha.IUpdateServingConfigRequest + | undefined + ), + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'serving_config.name': request.servingConfig!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'serving_config.name': request.servingConfig!.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateServingConfig request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.retail.v2alpha.IServingConfig, - protos.google.cloud.retail.v2alpha.IUpdateServingConfigRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.retail.v2alpha.IServingConfig, + | protos.google.cloud.retail.v2alpha.IUpdateServingConfigRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateServingConfig response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.updateServingConfig(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.retail.v2alpha.IServingConfig, - protos.google.cloud.retail.v2alpha.IUpdateServingConfigRequest|undefined, - {}|undefined - ]) => { - this._log.info('updateServingConfig response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateServingConfig(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.retail.v2alpha.IServingConfig, + ( + | protos.google.cloud.retail.v2alpha.IUpdateServingConfigRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('updateServingConfig response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Gets a ServingConfig. - * - * Returns a NotFound error if the ServingConfig does not exist. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The resource name of the ServingConfig to get. Format: - * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id}` - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.ServingConfig|ServingConfig}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/serving_config_service.get_serving_config.js - * region_tag:retail_v2alpha_generated_ServingConfigService_GetServingConfig_async - */ + /** + * Gets a ServingConfig. + * + * Returns a NotFound error if the ServingConfig does not exist. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The resource name of the ServingConfig to get. Format: + * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id}` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.ServingConfig|ServingConfig}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/serving_config_service.get_serving_config.js + * region_tag:retail_v2alpha_generated_ServingConfigService_GetServingConfig_async + */ getServingConfig( - request?: protos.google.cloud.retail.v2alpha.IGetServingConfigRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.retail.v2alpha.IServingConfig, - protos.google.cloud.retail.v2alpha.IGetServingConfigRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.IGetServingConfigRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IServingConfig, + protos.google.cloud.retail.v2alpha.IGetServingConfigRequest | undefined, + {} | undefined, + ] + >; getServingConfig( - request: protos.google.cloud.retail.v2alpha.IGetServingConfigRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.retail.v2alpha.IServingConfig, - protos.google.cloud.retail.v2alpha.IGetServingConfigRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IGetServingConfigRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.retail.v2alpha.IServingConfig, + | protos.google.cloud.retail.v2alpha.IGetServingConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getServingConfig( - request: protos.google.cloud.retail.v2alpha.IGetServingConfigRequest, - callback: Callback< - protos.google.cloud.retail.v2alpha.IServingConfig, - protos.google.cloud.retail.v2alpha.IGetServingConfigRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IGetServingConfigRequest, + callback: Callback< + protos.google.cloud.retail.v2alpha.IServingConfig, + | protos.google.cloud.retail.v2alpha.IGetServingConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getServingConfig( - request?: protos.google.cloud.retail.v2alpha.IGetServingConfigRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.retail.v2alpha.IServingConfig, - protos.google.cloud.retail.v2alpha.IGetServingConfigRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.retail.v2alpha.IGetServingConfigRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.retail.v2alpha.IServingConfig, - protos.google.cloud.retail.v2alpha.IGetServingConfigRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.retail.v2alpha.IServingConfig, - protos.google.cloud.retail.v2alpha.IGetServingConfigRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.retail.v2alpha.IGetServingConfigRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.retail.v2alpha.IServingConfig, + | protos.google.cloud.retail.v2alpha.IGetServingConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IServingConfig, + protos.google.cloud.retail.v2alpha.IGetServingConfigRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getServingConfig request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.retail.v2alpha.IServingConfig, - protos.google.cloud.retail.v2alpha.IGetServingConfigRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.retail.v2alpha.IServingConfig, + | protos.google.cloud.retail.v2alpha.IGetServingConfigRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getServingConfig response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getServingConfig(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.retail.v2alpha.IServingConfig, - protos.google.cloud.retail.v2alpha.IGetServingConfigRequest|undefined, - {}|undefined - ]) => { - this._log.info('getServingConfig response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getServingConfig(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.retail.v2alpha.IServingConfig, + ( + | protos.google.cloud.retail.v2alpha.IGetServingConfigRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('getServingConfig response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Enables a Control on the specified ServingConfig. - * The control is added in the last position of the list of controls - * it belongs to (e.g. if it's a facet spec control it will be applied - * in the last position of servingConfig.facetSpecIds) - * Returns a ALREADY_EXISTS error if the control has already been applied. - * Returns a FAILED_PRECONDITION error if the addition could exceed maximum - * number of control allowed for that type of control. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.servingConfig - * Required. The source ServingConfig resource name . Format: - * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id}` - * @param {string} request.controlId - * Required. The id of the control to apply. Assumed to be in the same catalog - * as the serving config - if id is not found a NOT_FOUND error is returned. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.ServingConfig|ServingConfig}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/serving_config_service.add_control.js - * region_tag:retail_v2alpha_generated_ServingConfigService_AddControl_async - */ + /** + * Enables a Control on the specified ServingConfig. + * The control is added in the last position of the list of controls + * it belongs to (e.g. if it's a facet spec control it will be applied + * in the last position of servingConfig.facetSpecIds) + * Returns a ALREADY_EXISTS error if the control has already been applied. + * Returns a FAILED_PRECONDITION error if the addition could exceed maximum + * number of control allowed for that type of control. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.servingConfig + * Required. The source ServingConfig resource name . Format: + * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id}` + * @param {string} request.controlId + * Required. The id of the control to apply. Assumed to be in the same catalog + * as the serving config - if id is not found a NOT_FOUND error is returned. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.ServingConfig|ServingConfig}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/serving_config_service.add_control.js + * region_tag:retail_v2alpha_generated_ServingConfigService_AddControl_async + */ addControl( - request?: protos.google.cloud.retail.v2alpha.IAddControlRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.retail.v2alpha.IServingConfig, - protos.google.cloud.retail.v2alpha.IAddControlRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.IAddControlRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IServingConfig, + protos.google.cloud.retail.v2alpha.IAddControlRequest | undefined, + {} | undefined, + ] + >; addControl( - request: protos.google.cloud.retail.v2alpha.IAddControlRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.retail.v2alpha.IServingConfig, - protos.google.cloud.retail.v2alpha.IAddControlRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IAddControlRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.retail.v2alpha.IServingConfig, + protos.google.cloud.retail.v2alpha.IAddControlRequest | null | undefined, + {} | null | undefined + >, + ): void; addControl( - request: protos.google.cloud.retail.v2alpha.IAddControlRequest, - callback: Callback< - protos.google.cloud.retail.v2alpha.IServingConfig, - protos.google.cloud.retail.v2alpha.IAddControlRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IAddControlRequest, + callback: Callback< + protos.google.cloud.retail.v2alpha.IServingConfig, + protos.google.cloud.retail.v2alpha.IAddControlRequest | null | undefined, + {} | null | undefined + >, + ): void; addControl( - request?: protos.google.cloud.retail.v2alpha.IAddControlRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.retail.v2alpha.IServingConfig, - protos.google.cloud.retail.v2alpha.IAddControlRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.retail.v2alpha.IAddControlRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.retail.v2alpha.IServingConfig, - protos.google.cloud.retail.v2alpha.IAddControlRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.retail.v2alpha.IServingConfig, - protos.google.cloud.retail.v2alpha.IAddControlRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.retail.v2alpha.IAddControlRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.retail.v2alpha.IServingConfig, + protos.google.cloud.retail.v2alpha.IAddControlRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IServingConfig, + protos.google.cloud.retail.v2alpha.IAddControlRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'serving_config': request.servingConfig ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + serving_config: request.servingConfig ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('addControl request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.retail.v2alpha.IServingConfig, - protos.google.cloud.retail.v2alpha.IAddControlRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.retail.v2alpha.IServingConfig, + | protos.google.cloud.retail.v2alpha.IAddControlRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('addControl response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.addControl(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.retail.v2alpha.IServingConfig, - protos.google.cloud.retail.v2alpha.IAddControlRequest|undefined, - {}|undefined - ]) => { - this._log.info('addControl response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .addControl(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.retail.v2alpha.IServingConfig, + protos.google.cloud.retail.v2alpha.IAddControlRequest | undefined, + {} | undefined, + ]) => { + this._log.info('addControl response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Disables a Control on the specified ServingConfig. - * The control is removed from the ServingConfig. - * Returns a NOT_FOUND error if the Control is not enabled for the - * ServingConfig. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.servingConfig - * Required. The source ServingConfig resource name . Format: - * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id}` - * @param {string} request.controlId - * Required. The id of the control to apply. Assumed to be in the same catalog - * as the serving config. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.ServingConfig|ServingConfig}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/serving_config_service.remove_control.js - * region_tag:retail_v2alpha_generated_ServingConfigService_RemoveControl_async - */ + /** + * Disables a Control on the specified ServingConfig. + * The control is removed from the ServingConfig. + * Returns a NOT_FOUND error if the Control is not enabled for the + * ServingConfig. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.servingConfig + * Required. The source ServingConfig resource name . Format: + * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}/servingConfigs/{serving_config_id}` + * @param {string} request.controlId + * Required. The id of the control to apply. Assumed to be in the same catalog + * as the serving config. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.ServingConfig|ServingConfig}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/serving_config_service.remove_control.js + * region_tag:retail_v2alpha_generated_ServingConfigService_RemoveControl_async + */ removeControl( - request?: protos.google.cloud.retail.v2alpha.IRemoveControlRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.retail.v2alpha.IServingConfig, - protos.google.cloud.retail.v2alpha.IRemoveControlRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.IRemoveControlRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IServingConfig, + protos.google.cloud.retail.v2alpha.IRemoveControlRequest | undefined, + {} | undefined, + ] + >; removeControl( - request: protos.google.cloud.retail.v2alpha.IRemoveControlRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.retail.v2alpha.IServingConfig, - protos.google.cloud.retail.v2alpha.IRemoveControlRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IRemoveControlRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.retail.v2alpha.IServingConfig, + | protos.google.cloud.retail.v2alpha.IRemoveControlRequest + | null + | undefined, + {} | null | undefined + >, + ): void; removeControl( - request: protos.google.cloud.retail.v2alpha.IRemoveControlRequest, - callback: Callback< - protos.google.cloud.retail.v2alpha.IServingConfig, - protos.google.cloud.retail.v2alpha.IRemoveControlRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IRemoveControlRequest, + callback: Callback< + protos.google.cloud.retail.v2alpha.IServingConfig, + | protos.google.cloud.retail.v2alpha.IRemoveControlRequest + | null + | undefined, + {} | null | undefined + >, + ): void; removeControl( - request?: protos.google.cloud.retail.v2alpha.IRemoveControlRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.cloud.retail.v2alpha.IRemoveControlRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.retail.v2alpha.IServingConfig, - protos.google.cloud.retail.v2alpha.IRemoveControlRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.cloud.retail.v2alpha.IServingConfig, - protos.google.cloud.retail.v2alpha.IRemoveControlRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.retail.v2alpha.IServingConfig, - protos.google.cloud.retail.v2alpha.IRemoveControlRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.retail.v2alpha.IRemoveControlRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.retail.v2alpha.IServingConfig, + | protos.google.cloud.retail.v2alpha.IRemoveControlRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IServingConfig, + protos.google.cloud.retail.v2alpha.IRemoveControlRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'serving_config': request.servingConfig ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + serving_config: request.servingConfig ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('removeControl request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.retail.v2alpha.IServingConfig, - protos.google.cloud.retail.v2alpha.IRemoveControlRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.retail.v2alpha.IServingConfig, + | protos.google.cloud.retail.v2alpha.IRemoveControlRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('removeControl response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.removeControl(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.retail.v2alpha.IServingConfig, - protos.google.cloud.retail.v2alpha.IRemoveControlRequest|undefined, - {}|undefined - ]) => { - this._log.info('removeControl response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .removeControl(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.retail.v2alpha.IServingConfig, + protos.google.cloud.retail.v2alpha.IRemoveControlRequest | undefined, + {} | undefined, + ]) => { + this._log.info('removeControl response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } - /** - * Lists all ServingConfigs linked to this catalog. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The catalog resource name. Format: - * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}` - * @param {number} [request.pageSize] - * Optional. Maximum number of results to return. If unspecified, defaults - * to 100. If a value greater than 100 is provided, at most 100 results are - * returned. - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous `ListServingConfigs` call. - * Provide this to retrieve the subsequent page. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.cloud.retail.v2alpha.ServingConfig|ServingConfig}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `listServingConfigsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Lists all ServingConfigs linked to this catalog. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The catalog resource name. Format: + * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}` + * @param {number} [request.pageSize] + * Optional. Maximum number of results to return. If unspecified, defaults + * to 100. If a value greater than 100 is provided, at most 100 results are + * returned. + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListServingConfigs` call. + * Provide this to retrieve the subsequent page. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.cloud.retail.v2alpha.ServingConfig|ServingConfig}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listServingConfigsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listServingConfigs( - request?: protos.google.cloud.retail.v2alpha.IListServingConfigsRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.retail.v2alpha.IServingConfig[], - protos.google.cloud.retail.v2alpha.IListServingConfigsRequest|null, - protos.google.cloud.retail.v2alpha.IListServingConfigsResponse - ]>; + request?: protos.google.cloud.retail.v2alpha.IListServingConfigsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IServingConfig[], + protos.google.cloud.retail.v2alpha.IListServingConfigsRequest | null, + protos.google.cloud.retail.v2alpha.IListServingConfigsResponse, + ] + >; listServingConfigs( - request: protos.google.cloud.retail.v2alpha.IListServingConfigsRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.cloud.retail.v2alpha.IListServingConfigsRequest, - protos.google.cloud.retail.v2alpha.IListServingConfigsResponse|null|undefined, - protos.google.cloud.retail.v2alpha.IServingConfig>): void; + request: protos.google.cloud.retail.v2alpha.IListServingConfigsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.cloud.retail.v2alpha.IListServingConfigsRequest, + | protos.google.cloud.retail.v2alpha.IListServingConfigsResponse + | null + | undefined, + protos.google.cloud.retail.v2alpha.IServingConfig + >, + ): void; listServingConfigs( - request: protos.google.cloud.retail.v2alpha.IListServingConfigsRequest, - callback: PaginationCallback< - protos.google.cloud.retail.v2alpha.IListServingConfigsRequest, - protos.google.cloud.retail.v2alpha.IListServingConfigsResponse|null|undefined, - protos.google.cloud.retail.v2alpha.IServingConfig>): void; + request: protos.google.cloud.retail.v2alpha.IListServingConfigsRequest, + callback: PaginationCallback< + protos.google.cloud.retail.v2alpha.IListServingConfigsRequest, + | protos.google.cloud.retail.v2alpha.IListServingConfigsResponse + | null + | undefined, + protos.google.cloud.retail.v2alpha.IServingConfig + >, + ): void; listServingConfigs( - request?: protos.google.cloud.retail.v2alpha.IListServingConfigsRequest, - optionsOrCallback?: CallOptions|PaginationCallback< + request?: protos.google.cloud.retail.v2alpha.IListServingConfigsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.cloud.retail.v2alpha.IListServingConfigsRequest, - protos.google.cloud.retail.v2alpha.IListServingConfigsResponse|null|undefined, - protos.google.cloud.retail.v2alpha.IServingConfig>, - callback?: PaginationCallback< - protos.google.cloud.retail.v2alpha.IListServingConfigsRequest, - protos.google.cloud.retail.v2alpha.IListServingConfigsResponse|null|undefined, - protos.google.cloud.retail.v2alpha.IServingConfig>): - Promise<[ - protos.google.cloud.retail.v2alpha.IServingConfig[], - protos.google.cloud.retail.v2alpha.IListServingConfigsRequest|null, - protos.google.cloud.retail.v2alpha.IListServingConfigsResponse - ]>|void { + | protos.google.cloud.retail.v2alpha.IListServingConfigsResponse + | null + | undefined, + protos.google.cloud.retail.v2alpha.IServingConfig + >, + callback?: PaginationCallback< + protos.google.cloud.retail.v2alpha.IListServingConfigsRequest, + | protos.google.cloud.retail.v2alpha.IListServingConfigsResponse + | null + | undefined, + protos.google.cloud.retail.v2alpha.IServingConfig + >, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IServingConfig[], + protos.google.cloud.retail.v2alpha.IListServingConfigsRequest | null, + protos.google.cloud.retail.v2alpha.IListServingConfigsResponse, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.cloud.retail.v2alpha.IListServingConfigsRequest, - protos.google.cloud.retail.v2alpha.IListServingConfigsResponse|null|undefined, - protos.google.cloud.retail.v2alpha.IServingConfig>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.cloud.retail.v2alpha.IListServingConfigsRequest, + | protos.google.cloud.retail.v2alpha.IListServingConfigsResponse + | null + | undefined, + protos.google.cloud.retail.v2alpha.IServingConfig + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listServingConfigs values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -1069,114 +1412,118 @@ export class ServingConfigServiceClient { this._log.info('listServingConfigs request %j', request); return this.innerApiCalls .listServingConfigs(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.cloud.retail.v2alpha.IServingConfig[], - protos.google.cloud.retail.v2alpha.IListServingConfigsRequest|null, - protos.google.cloud.retail.v2alpha.IListServingConfigsResponse - ]) => { - this._log.info('listServingConfigs values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.cloud.retail.v2alpha.IServingConfig[], + protos.google.cloud.retail.v2alpha.IListServingConfigsRequest | null, + protos.google.cloud.retail.v2alpha.IListServingConfigsResponse, + ]) => { + this._log.info('listServingConfigs values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listServingConfigs`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The catalog resource name. Format: - * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}` - * @param {number} [request.pageSize] - * Optional. Maximum number of results to return. If unspecified, defaults - * to 100. If a value greater than 100 is provided, at most 100 results are - * returned. - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous `ListServingConfigs` call. - * Provide this to retrieve the subsequent page. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.cloud.retail.v2alpha.ServingConfig|ServingConfig} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `listServingConfigsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `listServingConfigs`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The catalog resource name. Format: + * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}` + * @param {number} [request.pageSize] + * Optional. Maximum number of results to return. If unspecified, defaults + * to 100. If a value greater than 100 is provided, at most 100 results are + * returned. + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListServingConfigs` call. + * Provide this to retrieve the subsequent page. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.cloud.retail.v2alpha.ServingConfig|ServingConfig} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listServingConfigsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listServingConfigsStream( - request?: protos.google.cloud.retail.v2alpha.IListServingConfigsRequest, - options?: CallOptions): - Transform{ + request?: protos.google.cloud.retail.v2alpha.IListServingConfigsRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); const defaultCallSettings = this._defaults['listServingConfigs']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listServingConfigs stream %j', request); return this.descriptors.page.listServingConfigs.createStream( this.innerApiCalls.listServingConfigs as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listServingConfigs`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The catalog resource name. Format: - * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}` - * @param {number} [request.pageSize] - * Optional. Maximum number of results to return. If unspecified, defaults - * to 100. If a value greater than 100 is provided, at most 100 results are - * returned. - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous `ListServingConfigs` call. - * Provide this to retrieve the subsequent page. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.cloud.retail.v2alpha.ServingConfig|ServingConfig}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/serving_config_service.list_serving_configs.js - * region_tag:retail_v2alpha_generated_ServingConfigService_ListServingConfigs_async - */ + /** + * Equivalent to `listServingConfigs`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The catalog resource name. Format: + * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}` + * @param {number} [request.pageSize] + * Optional. Maximum number of results to return. If unspecified, defaults + * to 100. If a value greater than 100 is provided, at most 100 results are + * returned. + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListServingConfigs` call. + * Provide this to retrieve the subsequent page. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.cloud.retail.v2alpha.ServingConfig|ServingConfig}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/serving_config_service.list_serving_configs.js + * region_tag:retail_v2alpha_generated_ServingConfigService_ListServingConfigs_async + */ listServingConfigsAsync( - request?: protos.google.cloud.retail.v2alpha.IListServingConfigsRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.cloud.retail.v2alpha.IListServingConfigsRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); const defaultCallSettings = this._defaults['listServingConfigs']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listServingConfigs iterate %j', request); return this.descriptors.page.listServingConfigs.asyncIterate( this.innerApiCalls['listServingConfigs'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } // -------------------- @@ -1189,7 +1536,7 @@ export class ServingConfigServiceClient { * @param {string} project * @returns {string} Resource name string. */ - alertConfigPath(project:string) { + alertConfigPath(project: string) { return this.pathTemplates.alertConfigPathTemplate.render({ project: project, }); @@ -1203,7 +1550,8 @@ export class ServingConfigServiceClient { * @returns {string} A string representing the project. */ matchProjectFromAlertConfigName(alertConfigName: string) { - return this.pathTemplates.alertConfigPathTemplate.match(alertConfigName).project; + return this.pathTemplates.alertConfigPathTemplate.match(alertConfigName) + .project; } /** @@ -1214,7 +1562,7 @@ export class ServingConfigServiceClient { * @param {string} catalog * @returns {string} Resource name string. */ - attributesConfigPath(project:string,location:string,catalog:string) { + attributesConfigPath(project: string, location: string, catalog: string) { return this.pathTemplates.attributesConfigPathTemplate.render({ project: project, location: location, @@ -1230,7 +1578,9 @@ export class ServingConfigServiceClient { * @returns {string} A string representing the project. */ matchProjectFromAttributesConfigName(attributesConfigName: string) { - return this.pathTemplates.attributesConfigPathTemplate.match(attributesConfigName).project; + return this.pathTemplates.attributesConfigPathTemplate.match( + attributesConfigName, + ).project; } /** @@ -1241,7 +1591,9 @@ export class ServingConfigServiceClient { * @returns {string} A string representing the location. */ matchLocationFromAttributesConfigName(attributesConfigName: string) { - return this.pathTemplates.attributesConfigPathTemplate.match(attributesConfigName).location; + return this.pathTemplates.attributesConfigPathTemplate.match( + attributesConfigName, + ).location; } /** @@ -1252,7 +1604,9 @@ export class ServingConfigServiceClient { * @returns {string} A string representing the catalog. */ matchCatalogFromAttributesConfigName(attributesConfigName: string) { - return this.pathTemplates.attributesConfigPathTemplate.match(attributesConfigName).catalog; + return this.pathTemplates.attributesConfigPathTemplate.match( + attributesConfigName, + ).catalog; } /** @@ -1264,7 +1618,12 @@ export class ServingConfigServiceClient { * @param {string} branch * @returns {string} Resource name string. */ - branchPath(project:string,location:string,catalog:string,branch:string) { + branchPath( + project: string, + location: string, + catalog: string, + branch: string, + ) { return this.pathTemplates.branchPathTemplate.render({ project: project, location: location, @@ -1325,7 +1684,7 @@ export class ServingConfigServiceClient { * @param {string} catalog * @returns {string} Resource name string. */ - catalogPath(project:string,location:string,catalog:string) { + catalogPath(project: string, location: string, catalog: string) { return this.pathTemplates.catalogPathTemplate.render({ project: project, location: location, @@ -1374,7 +1733,7 @@ export class ServingConfigServiceClient { * @param {string} catalog * @returns {string} Resource name string. */ - completionConfigPath(project:string,location:string,catalog:string) { + completionConfigPath(project: string, location: string, catalog: string) { return this.pathTemplates.completionConfigPathTemplate.render({ project: project, location: location, @@ -1390,7 +1749,9 @@ export class ServingConfigServiceClient { * @returns {string} A string representing the project. */ matchProjectFromCompletionConfigName(completionConfigName: string) { - return this.pathTemplates.completionConfigPathTemplate.match(completionConfigName).project; + return this.pathTemplates.completionConfigPathTemplate.match( + completionConfigName, + ).project; } /** @@ -1401,7 +1762,9 @@ export class ServingConfigServiceClient { * @returns {string} A string representing the location. */ matchLocationFromCompletionConfigName(completionConfigName: string) { - return this.pathTemplates.completionConfigPathTemplate.match(completionConfigName).location; + return this.pathTemplates.completionConfigPathTemplate.match( + completionConfigName, + ).location; } /** @@ -1412,7 +1775,9 @@ export class ServingConfigServiceClient { * @returns {string} A string representing the catalog. */ matchCatalogFromCompletionConfigName(completionConfigName: string) { - return this.pathTemplates.completionConfigPathTemplate.match(completionConfigName).catalog; + return this.pathTemplates.completionConfigPathTemplate.match( + completionConfigName, + ).catalog; } /** @@ -1424,7 +1789,12 @@ export class ServingConfigServiceClient { * @param {string} control * @returns {string} Resource name string. */ - controlPath(project:string,location:string,catalog:string,control:string) { + controlPath( + project: string, + location: string, + catalog: string, + control: string, + ) { return this.pathTemplates.controlPathTemplate.render({ project: project, location: location, @@ -1483,7 +1853,7 @@ export class ServingConfigServiceClient { * @param {string} project * @returns {string} Resource name string. */ - loggingConfigPath(project:string) { + loggingConfigPath(project: string) { return this.pathTemplates.loggingConfigPathTemplate.render({ project: project, }); @@ -1497,7 +1867,8 @@ export class ServingConfigServiceClient { * @returns {string} A string representing the project. */ matchProjectFromLoggingConfigName(loggingConfigName: string) { - return this.pathTemplates.loggingConfigPathTemplate.match(loggingConfigName).project; + return this.pathTemplates.loggingConfigPathTemplate.match(loggingConfigName) + .project; } /** @@ -1509,7 +1880,12 @@ export class ServingConfigServiceClient { * @param {string} merchant_center_account_link * @returns {string} Resource name string. */ - merchantCenterAccountLinkPath(project:string,location:string,catalog:string,merchantCenterAccountLink:string) { + merchantCenterAccountLinkPath( + project: string, + location: string, + catalog: string, + merchantCenterAccountLink: string, + ) { return this.pathTemplates.merchantCenterAccountLinkPathTemplate.render({ project: project, location: location, @@ -1525,8 +1901,12 @@ export class ServingConfigServiceClient { * A fully-qualified path representing MerchantCenterAccountLink resource. * @returns {string} A string representing the project. */ - matchProjectFromMerchantCenterAccountLinkName(merchantCenterAccountLinkName: string) { - return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match(merchantCenterAccountLinkName).project; + matchProjectFromMerchantCenterAccountLinkName( + merchantCenterAccountLinkName: string, + ) { + return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match( + merchantCenterAccountLinkName, + ).project; } /** @@ -1536,8 +1916,12 @@ export class ServingConfigServiceClient { * A fully-qualified path representing MerchantCenterAccountLink resource. * @returns {string} A string representing the location. */ - matchLocationFromMerchantCenterAccountLinkName(merchantCenterAccountLinkName: string) { - return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match(merchantCenterAccountLinkName).location; + matchLocationFromMerchantCenterAccountLinkName( + merchantCenterAccountLinkName: string, + ) { + return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match( + merchantCenterAccountLinkName, + ).location; } /** @@ -1547,8 +1931,12 @@ export class ServingConfigServiceClient { * A fully-qualified path representing MerchantCenterAccountLink resource. * @returns {string} A string representing the catalog. */ - matchCatalogFromMerchantCenterAccountLinkName(merchantCenterAccountLinkName: string) { - return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match(merchantCenterAccountLinkName).catalog; + matchCatalogFromMerchantCenterAccountLinkName( + merchantCenterAccountLinkName: string, + ) { + return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match( + merchantCenterAccountLinkName, + ).catalog; } /** @@ -1558,8 +1946,12 @@ export class ServingConfigServiceClient { * A fully-qualified path representing MerchantCenterAccountLink resource. * @returns {string} A string representing the merchant_center_account_link. */ - matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName(merchantCenterAccountLinkName: string) { - return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match(merchantCenterAccountLinkName).merchant_center_account_link; + matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName( + merchantCenterAccountLinkName: string, + ) { + return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match( + merchantCenterAccountLinkName, + ).merchant_center_account_link; } /** @@ -1571,7 +1963,7 @@ export class ServingConfigServiceClient { * @param {string} model * @returns {string} Resource name string. */ - modelPath(project:string,location:string,catalog:string,model:string) { + modelPath(project: string, location: string, catalog: string, model: string) { return this.pathTemplates.modelPathTemplate.render({ project: project, location: location, @@ -1634,7 +2026,13 @@ export class ServingConfigServiceClient { * @param {string} product * @returns {string} Resource name string. */ - productPath(project:string,location:string,catalog:string,branch:string,product:string) { + productPath( + project: string, + location: string, + catalog: string, + branch: string, + product: string, + ) { return this.pathTemplates.productPathTemplate.render({ project: project, location: location, @@ -1705,7 +2103,7 @@ export class ServingConfigServiceClient { * @param {string} project * @returns {string} Resource name string. */ - retailProjectPath(project:string) { + retailProjectPath(project: string) { return this.pathTemplates.retailProjectPathTemplate.render({ project: project, }); @@ -1719,7 +2117,8 @@ export class ServingConfigServiceClient { * @returns {string} A string representing the project. */ matchProjectFromRetailProjectName(retailProjectName: string) { - return this.pathTemplates.retailProjectPathTemplate.match(retailProjectName).project; + return this.pathTemplates.retailProjectPathTemplate.match(retailProjectName) + .project; } /** @@ -1731,7 +2130,12 @@ export class ServingConfigServiceClient { * @param {string} serving_config * @returns {string} Resource name string. */ - servingConfigPath(project:string,location:string,catalog:string,servingConfig:string) { + servingConfigPath( + project: string, + location: string, + catalog: string, + servingConfig: string, + ) { return this.pathTemplates.servingConfigPathTemplate.render({ project: project, location: location, @@ -1748,7 +2152,8 @@ export class ServingConfigServiceClient { * @returns {string} A string representing the project. */ matchProjectFromServingConfigName(servingConfigName: string) { - return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName).project; + return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName) + .project; } /** @@ -1759,7 +2164,8 @@ export class ServingConfigServiceClient { * @returns {string} A string representing the location. */ matchLocationFromServingConfigName(servingConfigName: string) { - return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName).location; + return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName) + .location; } /** @@ -1770,7 +2176,8 @@ export class ServingConfigServiceClient { * @returns {string} A string representing the catalog. */ matchCatalogFromServingConfigName(servingConfigName: string) { - return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName).catalog; + return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName) + .catalog; } /** @@ -1781,7 +2188,8 @@ export class ServingConfigServiceClient { * @returns {string} A string representing the serving_config. */ matchServingConfigFromServingConfigName(servingConfigName: string) { - return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName).serving_config; + return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName) + .serving_config; } /** @@ -1792,7 +2200,7 @@ export class ServingConfigServiceClient { */ close(): Promise { if (this.servingConfigServiceStub && !this._terminated) { - return this.servingConfigServiceStub.then(stub => { + return this.servingConfigServiceStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -1800,4 +2208,4 @@ export class ServingConfigServiceClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/core/generator/gapic-generator-typescript/baselines/retail/src/v2alpha/user_event_service_client.ts.baseline b/core/generator/gapic-generator-typescript/baselines/retail/src/v2alpha/user_event_service_client.ts.baseline index c1af7bda9466..e0bb604c20d8 100644 --- a/core/generator/gapic-generator-typescript/baselines/retail/src/v2alpha/user_event_service_client.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/retail/src/v2alpha/user_event_service_client.ts.baseline @@ -18,11 +18,18 @@ /* global window */ import type * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions, GrpcClientOptions, LROperation} from 'google-gax'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + GrpcClientOptions, + LROperation, +} from 'google-gax'; import * as protos from '../../protos/protos'; import jsonProtos = require('../../protos/protos.json'); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; /** * Client JSON configuration object, loaded from @@ -44,7 +51,7 @@ export class UserEventServiceClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('retail'); @@ -57,10 +64,10 @@ export class UserEventServiceClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; operationsClient: gax.OperationsClient; - userEventServiceStub?: Promise<{[name: string]: Function}>; + userEventServiceStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of UserEventServiceClient. @@ -101,21 +108,42 @@ export class UserEventServiceClient { * const client = new UserEventServiceClient({fallback: true}, gax); * ``` */ - constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { // Ensure that options include all the required fields. const staticMembers = this.constructor as typeof UserEventServiceClient; - if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { - throw new Error('Please set either universe_domain or universeDomain, but not both.'); + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); } - const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; - this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; this._servicePath = 'retail.' + this._universeDomain; - const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; - const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. if (servicePath !== this._servicePath && !('scopes' in opts)) { @@ -137,7 +165,7 @@ export class UserEventServiceClient { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; @@ -151,10 +179,7 @@ export class UserEventServiceClient { } // Determine the client header string. - const clientHeader = [ - `gax/${this._gaxModule.version}`, - `gapic/${version}`, - ]; + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/${process.versions.node}`); } else { @@ -176,40 +201,40 @@ export class UserEventServiceClient { // Create useful helper objects for these. this.pathTemplates = { alertConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/alertConfig' + 'projects/{project}/alertConfig', ), attributesConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/attributesConfig' + 'projects/{project}/locations/{location}/catalogs/{catalog}/attributesConfig', ), branchPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}', ), catalogPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}' + 'projects/{project}/locations/{location}/catalogs/{catalog}', ), completionConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/completionConfig' + 'projects/{project}/locations/{location}/catalogs/{catalog}/completionConfig', ), controlPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/controls/{control}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/controls/{control}', ), loggingConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/loggingConfig' + 'projects/{project}/loggingConfig', ), merchantCenterAccountLinkPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/merchantCenterAccountLinks/{merchant_center_account_link}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/merchantCenterAccountLinks/{merchant_center_account_link}', ), modelPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/models/{model}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/models/{model}', ), productPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}', ), retailProjectPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/retailProject' + 'projects/{project}/retailProject', ), servingConfigPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/catalogs/{catalog}/servingConfigs/{serving_config}' + 'projects/{project}/locations/{location}/catalogs/{catalog}/servingConfigs/{serving_config}', ), }; @@ -219,55 +244,93 @@ export class UserEventServiceClient { // rather than holding a request open. const lroOptions: GrpcClientOptions = { auth: this.auth, - grpc: 'grpc' in this._gaxGrpc ? this._gaxGrpc.grpc : undefined + grpc: 'grpc' in this._gaxGrpc ? this._gaxGrpc.grpc : undefined, }; if (opts.fallback) { lroOptions.protoJson = protoFilesRoot; - lroOptions.httpRules = [{selector: 'google.longrunning.Operations.GetOperation',get: '/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*/operations/*}',additional_bindings: [{get: '/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*/places/*/operations/*}',},{get: '/v2alpha/{name=projects/*/locations/*/catalogs/*/operations/*}',},{get: '/v2alpha/{name=projects/*/locations/*/operations/*}',},{get: '/v2alpha/{name=projects/*/operations/*}',}], - },{selector: 'google.longrunning.Operations.ListOperations',get: '/v2alpha/{name=projects/*/locations/*/catalogs/*}/operations',additional_bindings: [{get: '/v2alpha/{name=projects/*/locations/*}/operations',},{get: '/v2alpha/{name=projects/*}/operations',}], - }]; + lroOptions.httpRules = [ + { + selector: 'google.longrunning.Operations.GetOperation', + get: '/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*/operations/*}', + additional_bindings: [ + { + get: '/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*/places/*/operations/*}', + }, + { + get: '/v2alpha/{name=projects/*/locations/*/catalogs/*/operations/*}', + }, + { get: '/v2alpha/{name=projects/*/locations/*/operations/*}' }, + { get: '/v2alpha/{name=projects/*/operations/*}' }, + ], + }, + { + selector: 'google.longrunning.Operations.ListOperations', + get: '/v2alpha/{name=projects/*/locations/*/catalogs/*}/operations', + additional_bindings: [ + { get: '/v2alpha/{name=projects/*/locations/*}/operations' }, + { get: '/v2alpha/{name=projects/*}/operations' }, + ], + }, + ]; } - this.operationsClient = this._gaxModule.lro(lroOptions).operationsClient(opts); + this.operationsClient = this._gaxModule + .lro(lroOptions) + .operationsClient(opts); const purgeUserEventsResponse = protoFilesRoot.lookup( - '.google.cloud.retail.v2alpha.PurgeUserEventsResponse') as gax.protobuf.Type; + '.google.cloud.retail.v2alpha.PurgeUserEventsResponse', + ) as gax.protobuf.Type; const purgeUserEventsMetadata = protoFilesRoot.lookup( - '.google.cloud.retail.v2alpha.PurgeMetadata') as gax.protobuf.Type; + '.google.cloud.retail.v2alpha.PurgeMetadata', + ) as gax.protobuf.Type; const importUserEventsResponse = protoFilesRoot.lookup( - '.google.cloud.retail.v2alpha.ImportUserEventsResponse') as gax.protobuf.Type; + '.google.cloud.retail.v2alpha.ImportUserEventsResponse', + ) as gax.protobuf.Type; const importUserEventsMetadata = protoFilesRoot.lookup( - '.google.cloud.retail.v2alpha.ImportMetadata') as gax.protobuf.Type; + '.google.cloud.retail.v2alpha.ImportMetadata', + ) as gax.protobuf.Type; const exportUserEventsResponse = protoFilesRoot.lookup( - '.google.cloud.retail.v2alpha.ExportUserEventsResponse') as gax.protobuf.Type; + '.google.cloud.retail.v2alpha.ExportUserEventsResponse', + ) as gax.protobuf.Type; const exportUserEventsMetadata = protoFilesRoot.lookup( - '.google.cloud.retail.v2alpha.ExportMetadata') as gax.protobuf.Type; + '.google.cloud.retail.v2alpha.ExportMetadata', + ) as gax.protobuf.Type; const rejoinUserEventsResponse = protoFilesRoot.lookup( - '.google.cloud.retail.v2alpha.RejoinUserEventsResponse') as gax.protobuf.Type; + '.google.cloud.retail.v2alpha.RejoinUserEventsResponse', + ) as gax.protobuf.Type; const rejoinUserEventsMetadata = protoFilesRoot.lookup( - '.google.cloud.retail.v2alpha.RejoinUserEventsMetadata') as gax.protobuf.Type; + '.google.cloud.retail.v2alpha.RejoinUserEventsMetadata', + ) as gax.protobuf.Type; this.descriptors.longrunning = { purgeUserEvents: new this._gaxModule.LongrunningDescriptor( this.operationsClient, purgeUserEventsResponse.decode.bind(purgeUserEventsResponse), - purgeUserEventsMetadata.decode.bind(purgeUserEventsMetadata)), + purgeUserEventsMetadata.decode.bind(purgeUserEventsMetadata), + ), importUserEvents: new this._gaxModule.LongrunningDescriptor( this.operationsClient, importUserEventsResponse.decode.bind(importUserEventsResponse), - importUserEventsMetadata.decode.bind(importUserEventsMetadata)), + importUserEventsMetadata.decode.bind(importUserEventsMetadata), + ), exportUserEvents: new this._gaxModule.LongrunningDescriptor( this.operationsClient, exportUserEventsResponse.decode.bind(exportUserEventsResponse), - exportUserEventsMetadata.decode.bind(exportUserEventsMetadata)), + exportUserEventsMetadata.decode.bind(exportUserEventsMetadata), + ), rejoinUserEvents: new this._gaxModule.LongrunningDescriptor( this.operationsClient, rejoinUserEventsResponse.decode.bind(rejoinUserEventsResponse), - rejoinUserEventsMetadata.decode.bind(rejoinUserEventsMetadata)) + rejoinUserEventsMetadata.decode.bind(rejoinUserEventsMetadata), + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.cloud.retail.v2alpha.UserEventService', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.cloud.retail.v2alpha.UserEventService', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + { 'x-goog-api-client': clientHeader.join(' ') }, + ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -298,37 +361,47 @@ export class UserEventServiceClient { // Put together the "service stub" for // google.cloud.retail.v2alpha.UserEventService. this.userEventServiceStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.cloud.retail.v2alpha.UserEventService') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.cloud.retail.v2alpha.UserEventService', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.cloud.retail.v2alpha.UserEventService, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts, + this._providedCustomServicePath, + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const userEventServiceStubMethods = - ['writeUserEvent', 'collectUserEvent', 'purgeUserEvents', 'importUserEvents', 'exportUserEvents', 'rejoinUserEvents']; + const userEventServiceStubMethods = [ + 'writeUserEvent', + 'collectUserEvent', + 'purgeUserEvents', + 'importUserEvents', + 'exportUserEvents', + 'rejoinUserEvents', + ]; for (const methodName of userEventServiceStubMethods) { const callPromise = this.userEventServiceStub.then( - stub => (...args: Array<{}>) => { - if (this._terminated) { - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error|null|undefined) => () => { + (stub) => + (...args: Array<{}>) => { + if (this._terminated) { + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { throw err; - }); + }, + ); - const descriptor = - this.descriptors.longrunning[methodName] || - undefined; + const descriptor = this.descriptors.longrunning[methodName] || undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -343,8 +416,14 @@ export class UserEventServiceClient { * @returns {string} The DNS address for this service. */ static get servicePath() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'retail.googleapis.com'; } @@ -355,8 +434,14 @@ export class UserEventServiceClient { * @returns {string} The DNS address for this service. */ static get apiEndpoint() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'retail.googleapis.com'; } @@ -387,9 +472,7 @@ export class UserEventServiceClient { * @returns {string[]} List of default scopes. */ static get scopes() { - return [ - 'https://www.googleapis.com/auth/cloud-platform' - ]; + return ['https://www.googleapis.com/auth/cloud-platform']; } getProjectId(): Promise; @@ -398,8 +481,9 @@ export class UserEventServiceClient { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId(callback?: Callback): - Promise|void { + getProjectId( + callback?: Callback, + ): Promise | void { if (callback) { this.auth.getProjectId(callback); return; @@ -410,759 +494,1090 @@ export class UserEventServiceClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Writes a single user event. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent catalog resource name, such as - * `projects/1234/locations/global/catalogs/default_catalog`. - * @param {google.cloud.retail.v2alpha.UserEvent} request.userEvent - * Required. User event to write. - * @param {boolean} request.writeAsync - * If set to true, the user event will be written asynchronously after - * validation, and the API will respond without waiting for the write. - * Therefore, silent failures can occur even if the API returns success. In - * case of silent failures, error messages can be found in Stackdriver logs. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.UserEvent|UserEvent}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/user_event_service.write_user_event.js - * region_tag:retail_v2alpha_generated_UserEventService_WriteUserEvent_async - */ + /** + * Writes a single user event. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent catalog resource name, such as + * `projects/1234/locations/global/catalogs/default_catalog`. + * @param {google.cloud.retail.v2alpha.UserEvent} request.userEvent + * Required. User event to write. + * @param {boolean} request.writeAsync + * If set to true, the user event will be written asynchronously after + * validation, and the API will respond without waiting for the write. + * Therefore, silent failures can occur even if the API returns success. In + * case of silent failures, error messages can be found in Stackdriver logs. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.retail.v2alpha.UserEvent|UserEvent}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/user_event_service.write_user_event.js + * region_tag:retail_v2alpha_generated_UserEventService_WriteUserEvent_async + */ writeUserEvent( - request?: protos.google.cloud.retail.v2alpha.IWriteUserEventRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.retail.v2alpha.IUserEvent, - protos.google.cloud.retail.v2alpha.IWriteUserEventRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.IWriteUserEventRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IUserEvent, + protos.google.cloud.retail.v2alpha.IWriteUserEventRequest | undefined, + {} | undefined, + ] + >; writeUserEvent( - request: protos.google.cloud.retail.v2alpha.IWriteUserEventRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.retail.v2alpha.IUserEvent, - protos.google.cloud.retail.v2alpha.IWriteUserEventRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IWriteUserEventRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.retail.v2alpha.IUserEvent, + | protos.google.cloud.retail.v2alpha.IWriteUserEventRequest + | null + | undefined, + {} | null | undefined + >, + ): void; writeUserEvent( - request: protos.google.cloud.retail.v2alpha.IWriteUserEventRequest, - callback: Callback< - protos.google.cloud.retail.v2alpha.IUserEvent, - protos.google.cloud.retail.v2alpha.IWriteUserEventRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IWriteUserEventRequest, + callback: Callback< + protos.google.cloud.retail.v2alpha.IUserEvent, + | protos.google.cloud.retail.v2alpha.IWriteUserEventRequest + | null + | undefined, + {} | null | undefined + >, + ): void; writeUserEvent( - request?: protos.google.cloud.retail.v2alpha.IWriteUserEventRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.cloud.retail.v2alpha.IWriteUserEventRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.retail.v2alpha.IUserEvent, - protos.google.cloud.retail.v2alpha.IWriteUserEventRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.cloud.retail.v2alpha.IUserEvent, - protos.google.cloud.retail.v2alpha.IWriteUserEventRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.retail.v2alpha.IUserEvent, - protos.google.cloud.retail.v2alpha.IWriteUserEventRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.retail.v2alpha.IWriteUserEventRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.retail.v2alpha.IUserEvent, + | protos.google.cloud.retail.v2alpha.IWriteUserEventRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.retail.v2alpha.IUserEvent, + protos.google.cloud.retail.v2alpha.IWriteUserEventRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('writeUserEvent request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.retail.v2alpha.IUserEvent, - protos.google.cloud.retail.v2alpha.IWriteUserEventRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.retail.v2alpha.IUserEvent, + | protos.google.cloud.retail.v2alpha.IWriteUserEventRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('writeUserEvent response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.writeUserEvent(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.retail.v2alpha.IUserEvent, - protos.google.cloud.retail.v2alpha.IWriteUserEventRequest|undefined, - {}|undefined - ]) => { - this._log.info('writeUserEvent response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .writeUserEvent(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.retail.v2alpha.IUserEvent, + protos.google.cloud.retail.v2alpha.IWriteUserEventRequest | undefined, + {} | undefined, + ]) => { + this._log.info('writeUserEvent response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Writes a single user event from the browser. - * - * For larger user event payload over 16 KB, the POST method should be used - * instead, otherwise a 400 Bad Request error is returned. - * - * This method is used only by the Retail API JavaScript pixel and Google Tag - * Manager. Users should not call this method directly. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.prebuiltRule - * The prebuilt rule name that can convert a specific type of raw_json. - * For example: "ga4_bq" rule for the GA4 user event schema. - * @param {string} request.parent - * Required. The parent catalog name, such as - * `projects/1234/locations/global/catalogs/default_catalog`. - * @param {string} request.userEvent - * Required. URL encoded UserEvent proto with a length limit of 2,000,000 - * characters. - * @param {string} request.uri - * The URL including cgi-parameters but excluding the hash fragment with a - * length limit of 5,000 characters. This is often more useful than the - * referer URL, because many browsers only send the domain for 3rd party - * requests. - * @param {number} request.ets - * The event timestamp in milliseconds. This prevents browser caching of - * otherwise identical get requests. The name is abbreviated to reduce the - * payload bytes. - * @param {string} request.rawJson - * An arbitrary serialized JSON string that contains necessary information - * that can comprise a user event. When this field is specified, the - * user_event field will be ignored. Note: line-delimited JSON is not - * supported, a single JSON only. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.api.HttpBody|HttpBody}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/user_event_service.collect_user_event.js - * region_tag:retail_v2alpha_generated_UserEventService_CollectUserEvent_async - */ + /** + * Writes a single user event from the browser. + * + * For larger user event payload over 16 KB, the POST method should be used + * instead, otherwise a 400 Bad Request error is returned. + * + * This method is used only by the Retail API JavaScript pixel and Google Tag + * Manager. Users should not call this method directly. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.prebuiltRule + * The prebuilt rule name that can convert a specific type of raw_json. + * For example: "ga4_bq" rule for the GA4 user event schema. + * @param {string} request.parent + * Required. The parent catalog name, such as + * `projects/1234/locations/global/catalogs/default_catalog`. + * @param {string} request.userEvent + * Required. URL encoded UserEvent proto with a length limit of 2,000,000 + * characters. + * @param {string} request.uri + * The URL including cgi-parameters but excluding the hash fragment with a + * length limit of 5,000 characters. This is often more useful than the + * referer URL, because many browsers only send the domain for 3rd party + * requests. + * @param {number} request.ets + * The event timestamp in milliseconds. This prevents browser caching of + * otherwise identical get requests. The name is abbreviated to reduce the + * payload bytes. + * @param {string} request.rawJson + * An arbitrary serialized JSON string that contains necessary information + * that can comprise a user event. When this field is specified, the + * user_event field will be ignored. Note: line-delimited JSON is not + * supported, a single JSON only. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.api.HttpBody|HttpBody}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/user_event_service.collect_user_event.js + * region_tag:retail_v2alpha_generated_UserEventService_CollectUserEvent_async + */ collectUserEvent( - request?: protos.google.cloud.retail.v2alpha.ICollectUserEventRequest, - options?: CallOptions): - Promise<[ - protos.google.api.IHttpBody, - protos.google.cloud.retail.v2alpha.ICollectUserEventRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.ICollectUserEventRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.api.IHttpBody, + protos.google.cloud.retail.v2alpha.ICollectUserEventRequest | undefined, + {} | undefined, + ] + >; collectUserEvent( - request: protos.google.cloud.retail.v2alpha.ICollectUserEventRequest, - options: CallOptions, - callback: Callback< - protos.google.api.IHttpBody, - protos.google.cloud.retail.v2alpha.ICollectUserEventRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.ICollectUserEventRequest, + options: CallOptions, + callback: Callback< + protos.google.api.IHttpBody, + | protos.google.cloud.retail.v2alpha.ICollectUserEventRequest + | null + | undefined, + {} | null | undefined + >, + ): void; collectUserEvent( - request: protos.google.cloud.retail.v2alpha.ICollectUserEventRequest, - callback: Callback< - protos.google.api.IHttpBody, - protos.google.cloud.retail.v2alpha.ICollectUserEventRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.ICollectUserEventRequest, + callback: Callback< + protos.google.api.IHttpBody, + | protos.google.cloud.retail.v2alpha.ICollectUserEventRequest + | null + | undefined, + {} | null | undefined + >, + ): void; collectUserEvent( - request?: protos.google.cloud.retail.v2alpha.ICollectUserEventRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.api.IHttpBody, - protos.google.cloud.retail.v2alpha.ICollectUserEventRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.retail.v2alpha.ICollectUserEventRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.api.IHttpBody, - protos.google.cloud.retail.v2alpha.ICollectUserEventRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.api.IHttpBody, - protos.google.cloud.retail.v2alpha.ICollectUserEventRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.retail.v2alpha.ICollectUserEventRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.api.IHttpBody, + | protos.google.cloud.retail.v2alpha.ICollectUserEventRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.api.IHttpBody, + protos.google.cloud.retail.v2alpha.ICollectUserEventRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('collectUserEvent request %j', request); - const wrappedCallback: Callback< - protos.google.api.IHttpBody, - protos.google.cloud.retail.v2alpha.ICollectUserEventRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.api.IHttpBody, + | protos.google.cloud.retail.v2alpha.ICollectUserEventRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('collectUserEvent response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.collectUserEvent(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.api.IHttpBody, - protos.google.cloud.retail.v2alpha.ICollectUserEventRequest|undefined, - {}|undefined - ]) => { - this._log.info('collectUserEvent response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .collectUserEvent(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.api.IHttpBody, + ( + | protos.google.cloud.retail.v2alpha.ICollectUserEventRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('collectUserEvent response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Deletes permanently all user events specified by the filter provided. - * Depending on the number of events specified by the filter, this operation - * could take hours or days to complete. To test a filter, use the list - * command first. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The resource name of the catalog under which the events are - * created. The format is - * `projects/${projectId}/locations/global/catalogs/${catalogId}` - * @param {string} request.filter - * Required. The filter string to specify the events to be deleted with a - * length limit of 5,000 characters. Empty string filter is not allowed. The - * eligible fields for filtering are: - * - * * `eventType`: Double quoted - * {@link protos.google.cloud.retail.v2alpha.UserEvent.event_type|UserEvent.event_type} - * string. - * * `eventTime`: in ISO 8601 "zulu" format. - * * `visitorId`: Double quoted string. Specifying this will delete all - * events associated with a visitor. - * * `userId`: Double quoted string. Specifying this will delete all events - * associated with a user. - * - * Examples: - * - * * Deleting all events in a time range: - * `eventTime > "2012-04-23T18:25:43.511Z" - * eventTime < "2012-04-23T18:30:43.511Z"` - * * Deleting specific eventType in time range: - * `eventTime > "2012-04-23T18:25:43.511Z" eventType = "detail-page-view"` - * * Deleting all events for a specific visitor: - * `visitorId = "visitor1024"` - * - * The filtering fields are assumed to have an implicit AND. - * @param {boolean} request.force - * Actually perform the purge. - * If `force` is set to false, the method will return the expected purge count - * without deleting any user events. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing - * a long running operation. Its `promise()` method returns a promise - * you can `await` for. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/user_event_service.purge_user_events.js - * region_tag:retail_v2alpha_generated_UserEventService_PurgeUserEvents_async - */ + /** + * Deletes permanently all user events specified by the filter provided. + * Depending on the number of events specified by the filter, this operation + * could take hours or days to complete. To test a filter, use the list + * command first. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The resource name of the catalog under which the events are + * created. The format is + * `projects/${projectId}/locations/global/catalogs/${catalogId}` + * @param {string} request.filter + * Required. The filter string to specify the events to be deleted with a + * length limit of 5,000 characters. Empty string filter is not allowed. The + * eligible fields for filtering are: + * + * * `eventType`: Double quoted + * {@link protos.google.cloud.retail.v2alpha.UserEvent.event_type|UserEvent.event_type} + * string. + * * `eventTime`: in ISO 8601 "zulu" format. + * * `visitorId`: Double quoted string. Specifying this will delete all + * events associated with a visitor. + * * `userId`: Double quoted string. Specifying this will delete all events + * associated with a user. + * + * Examples: + * + * * Deleting all events in a time range: + * `eventTime > "2012-04-23T18:25:43.511Z" + * eventTime < "2012-04-23T18:30:43.511Z"` + * * Deleting specific eventType in time range: + * `eventTime > "2012-04-23T18:25:43.511Z" eventType = "detail-page-view"` + * * Deleting all events for a specific visitor: + * `visitorId = "visitor1024"` + * + * The filtering fields are assumed to have an implicit AND. + * @param {boolean} request.force + * Actually perform the purge. + * If `force` is set to false, the method will return the expected purge count + * without deleting any user events. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/user_event_service.purge_user_events.js + * region_tag:retail_v2alpha_generated_UserEventService_PurgeUserEvents_async + */ purgeUserEvents( - request?: protos.google.cloud.retail.v2alpha.IPurgeUserEventsRequest, - options?: CallOptions): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.IPurgeUserEventsRequest, + options?: CallOptions, + ): Promise< + [ + LROperation< + protos.google.cloud.retail.v2alpha.IPurgeUserEventsResponse, + protos.google.cloud.retail.v2alpha.IPurgeMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; purgeUserEvents( - request: protos.google.cloud.retail.v2alpha.IPurgeUserEventsRequest, - options: CallOptions, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IPurgeUserEventsRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IPurgeUserEventsResponse, + protos.google.cloud.retail.v2alpha.IPurgeMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; purgeUserEvents( - request: protos.google.cloud.retail.v2alpha.IPurgeUserEventsRequest, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IPurgeUserEventsRequest, + callback: Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IPurgeUserEventsResponse, + protos.google.cloud.retail.v2alpha.IPurgeMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; purgeUserEvents( - request?: protos.google.cloud.retail.v2alpha.IPurgeUserEventsRequest, - optionsOrCallback?: CallOptions|Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>, - callback?: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>|void { + request?: protos.google.cloud.retail.v2alpha.IPurgeUserEventsRequest, + optionsOrCallback?: + | CallOptions + | Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IPurgeUserEventsResponse, + protos.google.cloud.retail.v2alpha.IPurgeMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + callback?: Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IPurgeUserEventsResponse, + protos.google.cloud.retail.v2alpha.IPurgeMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + LROperation< + protos.google.cloud.retail.v2alpha.IPurgeUserEventsResponse, + protos.google.cloud.retail.v2alpha.IPurgeMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IPurgeUserEventsResponse, + protos.google.cloud.retail.v2alpha.IPurgeMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, rawResponse, _) => { this._log.info('purgeUserEvents response %j', rawResponse); callback!(error, response, rawResponse, _); // We verified callback above. } : undefined; this._log.info('purgeUserEvents request %j', request); - return this.innerApiCalls.purgeUserEvents(request, options, wrappedCallback) - ?.then(([response, rawResponse, _]: [ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]) => { - this._log.info('purgeUserEvents response %j', rawResponse); - return [response, rawResponse, _]; - }); + return this.innerApiCalls + .purgeUserEvents(request, options, wrappedCallback) + ?.then( + ([response, rawResponse, _]: [ + LROperation< + protos.google.cloud.retail.v2alpha.IPurgeUserEventsResponse, + protos.google.cloud.retail.v2alpha.IPurgeMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ]) => { + this._log.info('purgeUserEvents response %j', rawResponse); + return [response, rawResponse, _]; + }, + ); } -/** - * Check the status of the long running operation returned by `purgeUserEvents()`. - * @param {String} name - * The operation name that will be passed. - * @returns {Promise} - The promise which resolves to an object. - * The decoded operation object has result and metadata field to get information from. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/user_event_service.purge_user_events.js - * region_tag:retail_v2alpha_generated_UserEventService_PurgeUserEvents_async - */ - async checkPurgeUserEventsProgress(name: string): Promise>{ + /** + * Check the status of the long running operation returned by `purgeUserEvents()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/user_event_service.purge_user_events.js + * region_tag:retail_v2alpha_generated_UserEventService_PurgeUserEvents_async + */ + async checkPurgeUserEventsProgress( + name: string, + ): Promise< + LROperation< + protos.google.cloud.retail.v2alpha.PurgeUserEventsResponse, + protos.google.cloud.retail.v2alpha.PurgeMetadata + > + > { this._log.info('purgeUserEvents long-running'); - const request = new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest({name}); + const request = + new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( + { name }, + ); const [operation] = await this.operationsClient.getOperation(request); - const decodeOperation = new this._gaxModule.Operation(operation, this.descriptors.longrunning.purgeUserEvents, this._gaxModule.createDefaultBackoffSettings()); - return decodeOperation as LROperation; + const decodeOperation = new this._gaxModule.Operation( + operation, + this.descriptors.longrunning.purgeUserEvents, + this._gaxModule.createDefaultBackoffSettings(), + ); + return decodeOperation as LROperation< + protos.google.cloud.retail.v2alpha.PurgeUserEventsResponse, + protos.google.cloud.retail.v2alpha.PurgeMetadata + >; } -/** - * Bulk import of User events. Request processing might be - * synchronous. Events that already exist are skipped. - * Use this method for backfilling historical user events. - * - * `Operation.response` is of type `ImportResponse`. Note that it is - * possible for a subset of the items to be successfully inserted. - * `Operation.metadata` is of type `ImportMetadata`. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. `projects/1234/locations/global/catalogs/default_catalog` - * @param {google.cloud.retail.v2alpha.UserEventInputConfig} request.inputConfig - * Required. The desired input location of the data. - * @param {google.cloud.retail.v2alpha.ImportErrorsConfig} request.errorsConfig - * The desired location of errors incurred during the Import. Cannot be set - * for inline user event imports. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing - * a long running operation. Its `promise()` method returns a promise - * you can `await` for. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/user_event_service.import_user_events.js - * region_tag:retail_v2alpha_generated_UserEventService_ImportUserEvents_async - */ + /** + * Bulk import of User events. Request processing might be + * synchronous. Events that already exist are skipped. + * Use this method for backfilling historical user events. + * + * `Operation.response` is of type `ImportResponse`. Note that it is + * possible for a subset of the items to be successfully inserted. + * `Operation.metadata` is of type `ImportMetadata`. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. `projects/1234/locations/global/catalogs/default_catalog` + * @param {google.cloud.retail.v2alpha.UserEventInputConfig} request.inputConfig + * Required. The desired input location of the data. + * @param {google.cloud.retail.v2alpha.ImportErrorsConfig} request.errorsConfig + * The desired location of errors incurred during the Import. Cannot be set + * for inline user event imports. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/user_event_service.import_user_events.js + * region_tag:retail_v2alpha_generated_UserEventService_ImportUserEvents_async + */ importUserEvents( - request?: protos.google.cloud.retail.v2alpha.IImportUserEventsRequest, - options?: CallOptions): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.IImportUserEventsRequest, + options?: CallOptions, + ): Promise< + [ + LROperation< + protos.google.cloud.retail.v2alpha.IImportUserEventsResponse, + protos.google.cloud.retail.v2alpha.IImportMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; importUserEvents( - request: protos.google.cloud.retail.v2alpha.IImportUserEventsRequest, - options: CallOptions, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IImportUserEventsRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IImportUserEventsResponse, + protos.google.cloud.retail.v2alpha.IImportMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; importUserEvents( - request: protos.google.cloud.retail.v2alpha.IImportUserEventsRequest, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IImportUserEventsRequest, + callback: Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IImportUserEventsResponse, + protos.google.cloud.retail.v2alpha.IImportMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; importUserEvents( - request?: protos.google.cloud.retail.v2alpha.IImportUserEventsRequest, - optionsOrCallback?: CallOptions|Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>, - callback?: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>|void { + request?: protos.google.cloud.retail.v2alpha.IImportUserEventsRequest, + optionsOrCallback?: + | CallOptions + | Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IImportUserEventsResponse, + protos.google.cloud.retail.v2alpha.IImportMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + callback?: Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IImportUserEventsResponse, + protos.google.cloud.retail.v2alpha.IImportMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + LROperation< + protos.google.cloud.retail.v2alpha.IImportUserEventsResponse, + protos.google.cloud.retail.v2alpha.IImportMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IImportUserEventsResponse, + protos.google.cloud.retail.v2alpha.IImportMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, rawResponse, _) => { this._log.info('importUserEvents response %j', rawResponse); callback!(error, response, rawResponse, _); // We verified callback above. } : undefined; this._log.info('importUserEvents request %j', request); - return this.innerApiCalls.importUserEvents(request, options, wrappedCallback) - ?.then(([response, rawResponse, _]: [ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]) => { - this._log.info('importUserEvents response %j', rawResponse); - return [response, rawResponse, _]; - }); + return this.innerApiCalls + .importUserEvents(request, options, wrappedCallback) + ?.then( + ([response, rawResponse, _]: [ + LROperation< + protos.google.cloud.retail.v2alpha.IImportUserEventsResponse, + protos.google.cloud.retail.v2alpha.IImportMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ]) => { + this._log.info('importUserEvents response %j', rawResponse); + return [response, rawResponse, _]; + }, + ); } -/** - * Check the status of the long running operation returned by `importUserEvents()`. - * @param {String} name - * The operation name that will be passed. - * @returns {Promise} - The promise which resolves to an object. - * The decoded operation object has result and metadata field to get information from. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/user_event_service.import_user_events.js - * region_tag:retail_v2alpha_generated_UserEventService_ImportUserEvents_async - */ - async checkImportUserEventsProgress(name: string): Promise>{ + /** + * Check the status of the long running operation returned by `importUserEvents()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/user_event_service.import_user_events.js + * region_tag:retail_v2alpha_generated_UserEventService_ImportUserEvents_async + */ + async checkImportUserEventsProgress( + name: string, + ): Promise< + LROperation< + protos.google.cloud.retail.v2alpha.ImportUserEventsResponse, + protos.google.cloud.retail.v2alpha.ImportMetadata + > + > { this._log.info('importUserEvents long-running'); - const request = new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest({name}); + const request = + new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( + { name }, + ); const [operation] = await this.operationsClient.getOperation(request); - const decodeOperation = new this._gaxModule.Operation(operation, this.descriptors.longrunning.importUserEvents, this._gaxModule.createDefaultBackoffSettings()); - return decodeOperation as LROperation; + const decodeOperation = new this._gaxModule.Operation( + operation, + this.descriptors.longrunning.importUserEvents, + this._gaxModule.createDefaultBackoffSettings(), + ); + return decodeOperation as LROperation< + protos.google.cloud.retail.v2alpha.ImportUserEventsResponse, + protos.google.cloud.retail.v2alpha.ImportMetadata + >; } -/** - * Exports user events. - * - * `Operation.response` is of type `ExportResponse`. - * `Operation.metadata` is of type `ExportMetadata`. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. Resource name of a - * {@link protos.google.cloud.retail.v2alpha.Catalog|Catalog}. For example - * `projects/1234/locations/global/catalogs/default_catalog` - * @param {google.cloud.retail.v2alpha.OutputConfig} request.outputConfig - * Required. The output location of the data. - * @param {string} request.filter - * A filtering expression to specify restrictions on returned events. - * The expression is a sequence of terms. Each term applies a restriction to - * the returned user events. Use this expression to restrict results to a - * specific time range or to filter events by eventType. - * For example, `eventTime > "2012-04-23T18:25:43.511Z" - * eventsMissingCatalogItems eventTime<"2012-04-23T18:25:43.511Z" - * eventType=search` - * - * We expect only three types of fields: - * - * * `eventTime`: This can be specified twice, once with a - * less than operator and once with a greater than operator. The - * `eventTime` restriction should result in one, contiguous, valid, - * `eventTime` range. - * - * * `eventType`: Boolean operators `OR` and `NOT` are supported if the - * expression is enclosed in parentheses and the operators are separated - * from the tag values by a space. - * - * * `eventsMissingCatalogItems`: This restricts results - * to events for which catalog items were not found in the catalog. The - * default behavior is to return only those events for which catalog - * items were found. - * - * Some examples of valid filters expressions: - * - * * Example 1: `eventTime > "2012-04-23T18:25:43.511Z" - * eventTime < "2012-04-23T18:30:43.511Z"` - * * Example 2: `eventTime > "2012-04-23T18:25:43.511Z" - * eventType = detail-page-view` - * * Example 3: `eventsMissingCatalogItems - * eventType = (NOT search) eventTime < - * "2018-04-23T18:30:43.511Z"` - * * Example 4: `eventTime > "2012-04-23T18:25:43.511Z"` - * * Example 5: `eventType = (detail-page-view OR search)` - * * Example 6: `eventsMissingCatalogItems` - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing - * a long running operation. Its `promise()` method returns a promise - * you can `await` for. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/user_event_service.export_user_events.js - * region_tag:retail_v2alpha_generated_UserEventService_ExportUserEvents_async - */ + /** + * Exports user events. + * + * `Operation.response` is of type `ExportResponse`. + * `Operation.metadata` is of type `ExportMetadata`. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Resource name of a + * {@link protos.google.cloud.retail.v2alpha.Catalog|Catalog}. For example + * `projects/1234/locations/global/catalogs/default_catalog` + * @param {google.cloud.retail.v2alpha.OutputConfig} request.outputConfig + * Required. The output location of the data. + * @param {string} request.filter + * A filtering expression to specify restrictions on returned events. + * The expression is a sequence of terms. Each term applies a restriction to + * the returned user events. Use this expression to restrict results to a + * specific time range or to filter events by eventType. + * For example, `eventTime > "2012-04-23T18:25:43.511Z" + * eventsMissingCatalogItems eventTime<"2012-04-23T18:25:43.511Z" + * eventType=search` + * + * We expect only three types of fields: + * + * * `eventTime`: This can be specified twice, once with a + * less than operator and once with a greater than operator. The + * `eventTime` restriction should result in one, contiguous, valid, + * `eventTime` range. + * + * * `eventType`: Boolean operators `OR` and `NOT` are supported if the + * expression is enclosed in parentheses and the operators are separated + * from the tag values by a space. + * + * * `eventsMissingCatalogItems`: This restricts results + * to events for which catalog items were not found in the catalog. The + * default behavior is to return only those events for which catalog + * items were found. + * + * Some examples of valid filters expressions: + * + * * Example 1: `eventTime > "2012-04-23T18:25:43.511Z" + * eventTime < "2012-04-23T18:30:43.511Z"` + * * Example 2: `eventTime > "2012-04-23T18:25:43.511Z" + * eventType = detail-page-view` + * * Example 3: `eventsMissingCatalogItems + * eventType = (NOT search) eventTime < + * "2018-04-23T18:30:43.511Z"` + * * Example 4: `eventTime > "2012-04-23T18:25:43.511Z"` + * * Example 5: `eventType = (detail-page-view OR search)` + * * Example 6: `eventsMissingCatalogItems` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/user_event_service.export_user_events.js + * region_tag:retail_v2alpha_generated_UserEventService_ExportUserEvents_async + */ exportUserEvents( - request?: protos.google.cloud.retail.v2alpha.IExportUserEventsRequest, - options?: CallOptions): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.IExportUserEventsRequest, + options?: CallOptions, + ): Promise< + [ + LROperation< + protos.google.cloud.retail.v2alpha.IExportUserEventsResponse, + protos.google.cloud.retail.v2alpha.IExportMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; exportUserEvents( - request: protos.google.cloud.retail.v2alpha.IExportUserEventsRequest, - options: CallOptions, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IExportUserEventsRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IExportUserEventsResponse, + protos.google.cloud.retail.v2alpha.IExportMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; exportUserEvents( - request: protos.google.cloud.retail.v2alpha.IExportUserEventsRequest, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IExportUserEventsRequest, + callback: Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IExportUserEventsResponse, + protos.google.cloud.retail.v2alpha.IExportMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; exportUserEvents( - request?: protos.google.cloud.retail.v2alpha.IExportUserEventsRequest, - optionsOrCallback?: CallOptions|Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>, - callback?: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>|void { + request?: protos.google.cloud.retail.v2alpha.IExportUserEventsRequest, + optionsOrCallback?: + | CallOptions + | Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IExportUserEventsResponse, + protos.google.cloud.retail.v2alpha.IExportMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + callback?: Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IExportUserEventsResponse, + protos.google.cloud.retail.v2alpha.IExportMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + LROperation< + protos.google.cloud.retail.v2alpha.IExportUserEventsResponse, + protos.google.cloud.retail.v2alpha.IExportMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IExportUserEventsResponse, + protos.google.cloud.retail.v2alpha.IExportMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, rawResponse, _) => { this._log.info('exportUserEvents response %j', rawResponse); callback!(error, response, rawResponse, _); // We verified callback above. } : undefined; this._log.info('exportUserEvents request %j', request); - return this.innerApiCalls.exportUserEvents(request, options, wrappedCallback) - ?.then(([response, rawResponse, _]: [ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]) => { - this._log.info('exportUserEvents response %j', rawResponse); - return [response, rawResponse, _]; - }); + return this.innerApiCalls + .exportUserEvents(request, options, wrappedCallback) + ?.then( + ([response, rawResponse, _]: [ + LROperation< + protos.google.cloud.retail.v2alpha.IExportUserEventsResponse, + protos.google.cloud.retail.v2alpha.IExportMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ]) => { + this._log.info('exportUserEvents response %j', rawResponse); + return [response, rawResponse, _]; + }, + ); } -/** - * Check the status of the long running operation returned by `exportUserEvents()`. - * @param {String} name - * The operation name that will be passed. - * @returns {Promise} - The promise which resolves to an object. - * The decoded operation object has result and metadata field to get information from. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/user_event_service.export_user_events.js - * region_tag:retail_v2alpha_generated_UserEventService_ExportUserEvents_async - */ - async checkExportUserEventsProgress(name: string): Promise>{ + /** + * Check the status of the long running operation returned by `exportUserEvents()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/user_event_service.export_user_events.js + * region_tag:retail_v2alpha_generated_UserEventService_ExportUserEvents_async + */ + async checkExportUserEventsProgress( + name: string, + ): Promise< + LROperation< + protos.google.cloud.retail.v2alpha.ExportUserEventsResponse, + protos.google.cloud.retail.v2alpha.ExportMetadata + > + > { this._log.info('exportUserEvents long-running'); - const request = new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest({name}); + const request = + new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( + { name }, + ); const [operation] = await this.operationsClient.getOperation(request); - const decodeOperation = new this._gaxModule.Operation(operation, this.descriptors.longrunning.exportUserEvents, this._gaxModule.createDefaultBackoffSettings()); - return decodeOperation as LROperation; + const decodeOperation = new this._gaxModule.Operation( + operation, + this.descriptors.longrunning.exportUserEvents, + this._gaxModule.createDefaultBackoffSettings(), + ); + return decodeOperation as LROperation< + protos.google.cloud.retail.v2alpha.ExportUserEventsResponse, + protos.google.cloud.retail.v2alpha.ExportMetadata + >; } -/** - * Starts a user-event rejoin operation with latest product catalog. Events - * are not annotated with detailed product information for products that are - * missing from the catalog when the user event is ingested. These - * events are stored as unjoined events with limited usage on training and - * serving. You can use this method to start a join operation on specified - * events with the latest version of product catalog. You can also use this - * method to correct events joined with the wrong product catalog. A rejoin - * operation can take hours or days to complete. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent catalog resource name, such as - * `projects/1234/locations/global/catalogs/default_catalog`. - * @param {google.cloud.retail.v2alpha.RejoinUserEventsRequest.UserEventRejoinScope} request.userEventRejoinScope - * The type of the user event rejoin to define the scope and range of the user - * events to be rejoined with the latest product catalog. Defaults to - * `USER_EVENT_REJOIN_SCOPE_UNSPECIFIED` if this field is not set, or set to - * an invalid integer value. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing - * a long running operation. Its `promise()` method returns a promise - * you can `await` for. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/user_event_service.rejoin_user_events.js - * region_tag:retail_v2alpha_generated_UserEventService_RejoinUserEvents_async - */ + /** + * Starts a user-event rejoin operation with latest product catalog. Events + * are not annotated with detailed product information for products that are + * missing from the catalog when the user event is ingested. These + * events are stored as unjoined events with limited usage on training and + * serving. You can use this method to start a join operation on specified + * events with the latest version of product catalog. You can also use this + * method to correct events joined with the wrong product catalog. A rejoin + * operation can take hours or days to complete. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent catalog resource name, such as + * `projects/1234/locations/global/catalogs/default_catalog`. + * @param {google.cloud.retail.v2alpha.RejoinUserEventsRequest.UserEventRejoinScope} request.userEventRejoinScope + * The type of the user event rejoin to define the scope and range of the user + * events to be rejoined with the latest product catalog. Defaults to + * `USER_EVENT_REJOIN_SCOPE_UNSPECIFIED` if this field is not set, or set to + * an invalid integer value. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/user_event_service.rejoin_user_events.js + * region_tag:retail_v2alpha_generated_UserEventService_RejoinUserEvents_async + */ rejoinUserEvents( - request?: protos.google.cloud.retail.v2alpha.IRejoinUserEventsRequest, - options?: CallOptions): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>; + request?: protos.google.cloud.retail.v2alpha.IRejoinUserEventsRequest, + options?: CallOptions, + ): Promise< + [ + LROperation< + protos.google.cloud.retail.v2alpha.IRejoinUserEventsResponse, + protos.google.cloud.retail.v2alpha.IRejoinUserEventsMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; rejoinUserEvents( - request: protos.google.cloud.retail.v2alpha.IRejoinUserEventsRequest, - options: CallOptions, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IRejoinUserEventsRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IRejoinUserEventsResponse, + protos.google.cloud.retail.v2alpha.IRejoinUserEventsMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; rejoinUserEvents( - request: protos.google.cloud.retail.v2alpha.IRejoinUserEventsRequest, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.retail.v2alpha.IRejoinUserEventsRequest, + callback: Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IRejoinUserEventsResponse, + protos.google.cloud.retail.v2alpha.IRejoinUserEventsMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; rejoinUserEvents( - request?: protos.google.cloud.retail.v2alpha.IRejoinUserEventsRequest, - optionsOrCallback?: CallOptions|Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>, - callback?: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>|void { + request?: protos.google.cloud.retail.v2alpha.IRejoinUserEventsRequest, + optionsOrCallback?: + | CallOptions + | Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IRejoinUserEventsResponse, + protos.google.cloud.retail.v2alpha.IRejoinUserEventsMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + callback?: Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IRejoinUserEventsResponse, + protos.google.cloud.retail.v2alpha.IRejoinUserEventsMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + LROperation< + protos.google.cloud.retail.v2alpha.IRejoinUserEventsResponse, + protos.google.cloud.retail.v2alpha.IRejoinUserEventsMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + LROperation< + protos.google.cloud.retail.v2alpha.IRejoinUserEventsResponse, + protos.google.cloud.retail.v2alpha.IRejoinUserEventsMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, rawResponse, _) => { this._log.info('rejoinUserEvents response %j', rawResponse); callback!(error, response, rawResponse, _); // We verified callback above. } : undefined; this._log.info('rejoinUserEvents request %j', request); - return this.innerApiCalls.rejoinUserEvents(request, options, wrappedCallback) - ?.then(([response, rawResponse, _]: [ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]) => { - this._log.info('rejoinUserEvents response %j', rawResponse); - return [response, rawResponse, _]; - }); + return this.innerApiCalls + .rejoinUserEvents(request, options, wrappedCallback) + ?.then( + ([response, rawResponse, _]: [ + LROperation< + protos.google.cloud.retail.v2alpha.IRejoinUserEventsResponse, + protos.google.cloud.retail.v2alpha.IRejoinUserEventsMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ]) => { + this._log.info('rejoinUserEvents response %j', rawResponse); + return [response, rawResponse, _]; + }, + ); } -/** - * Check the status of the long running operation returned by `rejoinUserEvents()`. - * @param {String} name - * The operation name that will be passed. - * @returns {Promise} - The promise which resolves to an object. - * The decoded operation object has result and metadata field to get information from. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v2alpha/user_event_service.rejoin_user_events.js - * region_tag:retail_v2alpha_generated_UserEventService_RejoinUserEvents_async - */ - async checkRejoinUserEventsProgress(name: string): Promise>{ + /** + * Check the status of the long running operation returned by `rejoinUserEvents()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v2alpha/user_event_service.rejoin_user_events.js + * region_tag:retail_v2alpha_generated_UserEventService_RejoinUserEvents_async + */ + async checkRejoinUserEventsProgress( + name: string, + ): Promise< + LROperation< + protos.google.cloud.retail.v2alpha.RejoinUserEventsResponse, + protos.google.cloud.retail.v2alpha.RejoinUserEventsMetadata + > + > { this._log.info('rejoinUserEvents long-running'); - const request = new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest({name}); + const request = + new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( + { name }, + ); const [operation] = await this.operationsClient.getOperation(request); - const decodeOperation = new this._gaxModule.Operation(operation, this.descriptors.longrunning.rejoinUserEvents, this._gaxModule.createDefaultBackoffSettings()); - return decodeOperation as LROperation; + const decodeOperation = new this._gaxModule.Operation( + operation, + this.descriptors.longrunning.rejoinUserEvents, + this._gaxModule.createDefaultBackoffSettings(), + ); + return decodeOperation as LROperation< + protos.google.cloud.retail.v2alpha.RejoinUserEventsResponse, + protos.google.cloud.retail.v2alpha.RejoinUserEventsMetadata + >; } // -------------------- // -- Path templates -- @@ -1174,7 +1589,7 @@ export class UserEventServiceClient { * @param {string} project * @returns {string} Resource name string. */ - alertConfigPath(project:string) { + alertConfigPath(project: string) { return this.pathTemplates.alertConfigPathTemplate.render({ project: project, }); @@ -1188,7 +1603,8 @@ export class UserEventServiceClient { * @returns {string} A string representing the project. */ matchProjectFromAlertConfigName(alertConfigName: string) { - return this.pathTemplates.alertConfigPathTemplate.match(alertConfigName).project; + return this.pathTemplates.alertConfigPathTemplate.match(alertConfigName) + .project; } /** @@ -1199,7 +1615,7 @@ export class UserEventServiceClient { * @param {string} catalog * @returns {string} Resource name string. */ - attributesConfigPath(project:string,location:string,catalog:string) { + attributesConfigPath(project: string, location: string, catalog: string) { return this.pathTemplates.attributesConfigPathTemplate.render({ project: project, location: location, @@ -1215,7 +1631,9 @@ export class UserEventServiceClient { * @returns {string} A string representing the project. */ matchProjectFromAttributesConfigName(attributesConfigName: string) { - return this.pathTemplates.attributesConfigPathTemplate.match(attributesConfigName).project; + return this.pathTemplates.attributesConfigPathTemplate.match( + attributesConfigName, + ).project; } /** @@ -1226,7 +1644,9 @@ export class UserEventServiceClient { * @returns {string} A string representing the location. */ matchLocationFromAttributesConfigName(attributesConfigName: string) { - return this.pathTemplates.attributesConfigPathTemplate.match(attributesConfigName).location; + return this.pathTemplates.attributesConfigPathTemplate.match( + attributesConfigName, + ).location; } /** @@ -1237,7 +1657,9 @@ export class UserEventServiceClient { * @returns {string} A string representing the catalog. */ matchCatalogFromAttributesConfigName(attributesConfigName: string) { - return this.pathTemplates.attributesConfigPathTemplate.match(attributesConfigName).catalog; + return this.pathTemplates.attributesConfigPathTemplate.match( + attributesConfigName, + ).catalog; } /** @@ -1249,7 +1671,12 @@ export class UserEventServiceClient { * @param {string} branch * @returns {string} Resource name string. */ - branchPath(project:string,location:string,catalog:string,branch:string) { + branchPath( + project: string, + location: string, + catalog: string, + branch: string, + ) { return this.pathTemplates.branchPathTemplate.render({ project: project, location: location, @@ -1310,7 +1737,7 @@ export class UserEventServiceClient { * @param {string} catalog * @returns {string} Resource name string. */ - catalogPath(project:string,location:string,catalog:string) { + catalogPath(project: string, location: string, catalog: string) { return this.pathTemplates.catalogPathTemplate.render({ project: project, location: location, @@ -1359,7 +1786,7 @@ export class UserEventServiceClient { * @param {string} catalog * @returns {string} Resource name string. */ - completionConfigPath(project:string,location:string,catalog:string) { + completionConfigPath(project: string, location: string, catalog: string) { return this.pathTemplates.completionConfigPathTemplate.render({ project: project, location: location, @@ -1375,7 +1802,9 @@ export class UserEventServiceClient { * @returns {string} A string representing the project. */ matchProjectFromCompletionConfigName(completionConfigName: string) { - return this.pathTemplates.completionConfigPathTemplate.match(completionConfigName).project; + return this.pathTemplates.completionConfigPathTemplate.match( + completionConfigName, + ).project; } /** @@ -1386,7 +1815,9 @@ export class UserEventServiceClient { * @returns {string} A string representing the location. */ matchLocationFromCompletionConfigName(completionConfigName: string) { - return this.pathTemplates.completionConfigPathTemplate.match(completionConfigName).location; + return this.pathTemplates.completionConfigPathTemplate.match( + completionConfigName, + ).location; } /** @@ -1397,7 +1828,9 @@ export class UserEventServiceClient { * @returns {string} A string representing the catalog. */ matchCatalogFromCompletionConfigName(completionConfigName: string) { - return this.pathTemplates.completionConfigPathTemplate.match(completionConfigName).catalog; + return this.pathTemplates.completionConfigPathTemplate.match( + completionConfigName, + ).catalog; } /** @@ -1409,7 +1842,12 @@ export class UserEventServiceClient { * @param {string} control * @returns {string} Resource name string. */ - controlPath(project:string,location:string,catalog:string,control:string) { + controlPath( + project: string, + location: string, + catalog: string, + control: string, + ) { return this.pathTemplates.controlPathTemplate.render({ project: project, location: location, @@ -1468,7 +1906,7 @@ export class UserEventServiceClient { * @param {string} project * @returns {string} Resource name string. */ - loggingConfigPath(project:string) { + loggingConfigPath(project: string) { return this.pathTemplates.loggingConfigPathTemplate.render({ project: project, }); @@ -1482,7 +1920,8 @@ export class UserEventServiceClient { * @returns {string} A string representing the project. */ matchProjectFromLoggingConfigName(loggingConfigName: string) { - return this.pathTemplates.loggingConfigPathTemplate.match(loggingConfigName).project; + return this.pathTemplates.loggingConfigPathTemplate.match(loggingConfigName) + .project; } /** @@ -1494,7 +1933,12 @@ export class UserEventServiceClient { * @param {string} merchant_center_account_link * @returns {string} Resource name string. */ - merchantCenterAccountLinkPath(project:string,location:string,catalog:string,merchantCenterAccountLink:string) { + merchantCenterAccountLinkPath( + project: string, + location: string, + catalog: string, + merchantCenterAccountLink: string, + ) { return this.pathTemplates.merchantCenterAccountLinkPathTemplate.render({ project: project, location: location, @@ -1510,8 +1954,12 @@ export class UserEventServiceClient { * A fully-qualified path representing MerchantCenterAccountLink resource. * @returns {string} A string representing the project. */ - matchProjectFromMerchantCenterAccountLinkName(merchantCenterAccountLinkName: string) { - return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match(merchantCenterAccountLinkName).project; + matchProjectFromMerchantCenterAccountLinkName( + merchantCenterAccountLinkName: string, + ) { + return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match( + merchantCenterAccountLinkName, + ).project; } /** @@ -1521,8 +1969,12 @@ export class UserEventServiceClient { * A fully-qualified path representing MerchantCenterAccountLink resource. * @returns {string} A string representing the location. */ - matchLocationFromMerchantCenterAccountLinkName(merchantCenterAccountLinkName: string) { - return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match(merchantCenterAccountLinkName).location; + matchLocationFromMerchantCenterAccountLinkName( + merchantCenterAccountLinkName: string, + ) { + return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match( + merchantCenterAccountLinkName, + ).location; } /** @@ -1532,8 +1984,12 @@ export class UserEventServiceClient { * A fully-qualified path representing MerchantCenterAccountLink resource. * @returns {string} A string representing the catalog. */ - matchCatalogFromMerchantCenterAccountLinkName(merchantCenterAccountLinkName: string) { - return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match(merchantCenterAccountLinkName).catalog; + matchCatalogFromMerchantCenterAccountLinkName( + merchantCenterAccountLinkName: string, + ) { + return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match( + merchantCenterAccountLinkName, + ).catalog; } /** @@ -1543,8 +1999,12 @@ export class UserEventServiceClient { * A fully-qualified path representing MerchantCenterAccountLink resource. * @returns {string} A string representing the merchant_center_account_link. */ - matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName(merchantCenterAccountLinkName: string) { - return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match(merchantCenterAccountLinkName).merchant_center_account_link; + matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName( + merchantCenterAccountLinkName: string, + ) { + return this.pathTemplates.merchantCenterAccountLinkPathTemplate.match( + merchantCenterAccountLinkName, + ).merchant_center_account_link; } /** @@ -1556,7 +2016,7 @@ export class UserEventServiceClient { * @param {string} model * @returns {string} Resource name string. */ - modelPath(project:string,location:string,catalog:string,model:string) { + modelPath(project: string, location: string, catalog: string, model: string) { return this.pathTemplates.modelPathTemplate.render({ project: project, location: location, @@ -1619,7 +2079,13 @@ export class UserEventServiceClient { * @param {string} product * @returns {string} Resource name string. */ - productPath(project:string,location:string,catalog:string,branch:string,product:string) { + productPath( + project: string, + location: string, + catalog: string, + branch: string, + product: string, + ) { return this.pathTemplates.productPathTemplate.render({ project: project, location: location, @@ -1690,7 +2156,7 @@ export class UserEventServiceClient { * @param {string} project * @returns {string} Resource name string. */ - retailProjectPath(project:string) { + retailProjectPath(project: string) { return this.pathTemplates.retailProjectPathTemplate.render({ project: project, }); @@ -1704,7 +2170,8 @@ export class UserEventServiceClient { * @returns {string} A string representing the project. */ matchProjectFromRetailProjectName(retailProjectName: string) { - return this.pathTemplates.retailProjectPathTemplate.match(retailProjectName).project; + return this.pathTemplates.retailProjectPathTemplate.match(retailProjectName) + .project; } /** @@ -1716,7 +2183,12 @@ export class UserEventServiceClient { * @param {string} serving_config * @returns {string} Resource name string. */ - servingConfigPath(project:string,location:string,catalog:string,servingConfig:string) { + servingConfigPath( + project: string, + location: string, + catalog: string, + servingConfig: string, + ) { return this.pathTemplates.servingConfigPathTemplate.render({ project: project, location: location, @@ -1733,7 +2205,8 @@ export class UserEventServiceClient { * @returns {string} A string representing the project. */ matchProjectFromServingConfigName(servingConfigName: string) { - return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName).project; + return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName) + .project; } /** @@ -1744,7 +2217,8 @@ export class UserEventServiceClient { * @returns {string} A string representing the location. */ matchLocationFromServingConfigName(servingConfigName: string) { - return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName).location; + return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName) + .location; } /** @@ -1755,7 +2229,8 @@ export class UserEventServiceClient { * @returns {string} A string representing the catalog. */ matchCatalogFromServingConfigName(servingConfigName: string) { - return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName).catalog; + return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName) + .catalog; } /** @@ -1766,7 +2241,8 @@ export class UserEventServiceClient { * @returns {string} A string representing the serving_config. */ matchServingConfigFromServingConfigName(servingConfigName: string) { - return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName).serving_config; + return this.pathTemplates.servingConfigPathTemplate.match(servingConfigName) + .serving_config; } /** @@ -1777,7 +2253,7 @@ export class UserEventServiceClient { */ close(): Promise { if (this.userEventServiceStub && !this._terminated) { - return this.userEventServiceStub.then(stub => { + return this.userEventServiceStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -1786,4 +2262,4 @@ export class UserEventServiceClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/core/generator/gapic-generator-typescript/baselines/retail/system-test/fixtures/sample/src/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/retail/system-test/fixtures/sample/src/index.ts.baseline index 060b8503bc11..970f32087ad0 100644 --- a/core/generator/gapic-generator-typescript/baselines/retail/system-test/fixtures/sample/src/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/retail/system-test/fixtures/sample/src/index.ts.baseline @@ -16,7 +16,23 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -import {AnalyticsServiceClient, BranchServiceClient, CatalogServiceClient, CompletionServiceClient, ControlServiceClient, ConversationalSearchServiceClient, GenerativeQuestionServiceClient, MerchantCenterAccountLinkServiceClient, ModelServiceClient, PredictionServiceClient, ProductServiceClient, ProjectServiceClient, SearchServiceClient, ServingConfigServiceClient, UserEventServiceClient} from 'retail'; +import { + AnalyticsServiceClient, + BranchServiceClient, + CatalogServiceClient, + CompletionServiceClient, + ControlServiceClient, + ConversationalSearchServiceClient, + GenerativeQuestionServiceClient, + MerchantCenterAccountLinkServiceClient, + ModelServiceClient, + PredictionServiceClient, + ProductServiceClient, + ProjectServiceClient, + SearchServiceClient, + ServingConfigServiceClient, + UserEventServiceClient, +} from 'retail'; // check that the client class type name can be used function doStuffWithAnalyticsServiceClient(client: AnalyticsServiceClient) { @@ -34,13 +50,19 @@ function doStuffWithCompletionServiceClient(client: CompletionServiceClient) { function doStuffWithControlServiceClient(client: ControlServiceClient) { client.close(); } -function doStuffWithConversationalSearchServiceClient(client: ConversationalSearchServiceClient) { +function doStuffWithConversationalSearchServiceClient( + client: ConversationalSearchServiceClient, +) { client.close(); } -function doStuffWithGenerativeQuestionServiceClient(client: GenerativeQuestionServiceClient) { +function doStuffWithGenerativeQuestionServiceClient( + client: GenerativeQuestionServiceClient, +) { client.close(); } -function doStuffWithMerchantCenterAccountLinkServiceClient(client: MerchantCenterAccountLinkServiceClient) { +function doStuffWithMerchantCenterAccountLinkServiceClient( + client: MerchantCenterAccountLinkServiceClient, +) { client.close(); } function doStuffWithModelServiceClient(client: ModelServiceClient) { @@ -58,7 +80,9 @@ function doStuffWithProjectServiceClient(client: ProjectServiceClient) { function doStuffWithSearchServiceClient(client: SearchServiceClient) { client.close(); } -function doStuffWithServingConfigServiceClient(client: ServingConfigServiceClient) { +function doStuffWithServingConfigServiceClient( + client: ServingConfigServiceClient, +) { client.close(); } function doStuffWithUserEventServiceClient(client: UserEventServiceClient) { @@ -82,14 +106,20 @@ function main() { const controlServiceClient = new ControlServiceClient(); doStuffWithControlServiceClient(controlServiceClient); // check that the client instance can be created - const conversationalSearchServiceClient = new ConversationalSearchServiceClient(); - doStuffWithConversationalSearchServiceClient(conversationalSearchServiceClient); + const conversationalSearchServiceClient = + new ConversationalSearchServiceClient(); + doStuffWithConversationalSearchServiceClient( + conversationalSearchServiceClient, + ); // check that the client instance can be created const generativeQuestionServiceClient = new GenerativeQuestionServiceClient(); doStuffWithGenerativeQuestionServiceClient(generativeQuestionServiceClient); // check that the client instance can be created - const merchantCenterAccountLinkServiceClient = new MerchantCenterAccountLinkServiceClient(); - doStuffWithMerchantCenterAccountLinkServiceClient(merchantCenterAccountLinkServiceClient); + const merchantCenterAccountLinkServiceClient = + new MerchantCenterAccountLinkServiceClient(); + doStuffWithMerchantCenterAccountLinkServiceClient( + merchantCenterAccountLinkServiceClient, + ); // check that the client instance can be created const modelServiceClient = new ModelServiceClient(); doStuffWithModelServiceClient(modelServiceClient); diff --git a/core/generator/gapic-generator-typescript/baselines/retail/system-test/install.ts.baseline b/core/generator/gapic-generator-typescript/baselines/retail/system-test/install.ts.baseline index f66069aa3940..ccf167042d2e 100644 --- a/core/generator/gapic-generator-typescript/baselines/retail/system-test/install.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/retail/system-test/install.ts.baseline @@ -16,34 +16,36 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -import {packNTest} from 'pack-n-play'; -import {readFileSync} from 'fs'; -import {describe, it} from 'mocha'; +import { packNTest } from 'pack-n-play'; +import { readFileSync } from 'fs'; +import { describe, it } from 'mocha'; describe('📦 pack-n-play test', () => { - - it('TypeScript code', async function() { + it('TypeScript code', async function () { this.timeout(300000); const options = { packageDir: process.cwd(), sample: { description: 'TypeScript user can use the type definitions', - ts: readFileSync('./system-test/fixtures/sample/src/index.ts').toString() - } + ts: readFileSync( + './system-test/fixtures/sample/src/index.ts', + ).toString(), + }, }; await packNTest(options); }); - it('JavaScript code', async function() { + it('JavaScript code', async function () { this.timeout(300000); const options = { packageDir: process.cwd(), sample: { description: 'JavaScript user can use the library', - cjs: readFileSync('./system-test/fixtures/sample/src/index.js').toString() - } + cjs: readFileSync( + './system-test/fixtures/sample/src/index.js', + ).toString(), + }, }; await packNTest(options); }); - }); diff --git a/core/generator/gapic-generator-typescript/baselines/retail/test/gapic_analytics_service_v2alpha.ts.baseline b/core/generator/gapic-generator-typescript/baselines/retail/test/gapic_analytics_service_v2alpha.ts.baseline index 4e4320fcc73d..b53209aeb7d3 100644 --- a/core/generator/gapic-generator-typescript/baselines/retail/test/gapic_analytics_service_v2alpha.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/retail/test/gapic_analytics_service_v2alpha.ts.baseline @@ -19,925 +19,1266 @@ import * as protos from '../protos/protos'; import * as assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as analyticsserviceModule from '../src'; -import {protobuf, LROperation, operationsProtos} from 'google-gax'; +import { protobuf, LROperation, operationsProtos } from 'google-gax'; // Dynamically loaded proto JSON is needed to get the type information // to fill in default values for request objects -const root = protobuf.Root.fromJSON(require('../protos/protos.json')).resolveAll(); +const root = protobuf.Root.fromJSON( + require('../protos/protos.json'), +).resolveAll(); // eslint-disable-next-line @typescript-eslint/no-unused-vars function getTypeDefaultValue(typeName: string, fields: string[]) { - let type = root.lookupType(typeName) as protobuf.Type; - for (const field of fields.slice(0, -1)) { - type = type.fields[field]?.resolvedType as protobuf.Type; - } - return type.fields[fields[fields.length - 1]]?.defaultValue; + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type.fields[field]?.resolvedType as protobuf.Type; + } + return type.fields[fields[fields.length - 1]]?.defaultValue; } function generateSampleMessage(instance: T) { - const filledObject = (instance.constructor as typeof protobuf.Message) - .toObject(instance as protobuf.Message, {defaults: true}); - return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, { defaults: true }); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; } function stubSimpleCall(response?: ResponseType, error?: Error) { - return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); } -function stubLongRunningCall(response?: ResponseType, callError?: Error, lroError?: Error) { - const innerStub = lroError ? sinon.stub().rejects(lroError) : sinon.stub().resolves([response]); - const mockOperation = { - promise: innerStub, - }; - return callError ? sinon.stub().rejects(callError) : sinon.stub().resolves([mockOperation]); +function stubLongRunningCall( + response?: ResponseType, + callError?: Error, + lroError?: Error, +) { + const innerStub = lroError + ? sinon.stub().rejects(lroError) + : sinon.stub().resolves([response]); + const mockOperation = { + promise: innerStub, + }; + return callError + ? sinon.stub().rejects(callError) + : sinon.stub().resolves([mockOperation]); } -function stubLongRunningCallWithCallback(response?: ResponseType, callError?: Error, lroError?: Error) { - const innerStub = lroError ? sinon.stub().rejects(lroError) : sinon.stub().resolves([response]); - const mockOperation = { - promise: innerStub, - }; - return callError ? sinon.stub().callsArgWith(2, callError) : sinon.stub().callsArgWith(2, null, mockOperation); +function stubLongRunningCallWithCallback( + response?: ResponseType, + callError?: Error, + lroError?: Error, +) { + const innerStub = lroError + ? sinon.stub().rejects(lroError) + : sinon.stub().resolves([response]); + const mockOperation = { + promise: innerStub, + }; + return callError + ? sinon.stub().callsArgWith(2, callError) + : sinon.stub().callsArgWith(2, null, mockOperation); } describe('v2alpha.AnalyticsServiceClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new analyticsserviceModule.v2alpha.AnalyticsServiceClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'retail.googleapis.com'); - }); - - it('has universeDomain', () => { - const client = new analyticsserviceModule.v2alpha.AnalyticsServiceClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); - - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - it('throws DeprecationWarning if static servicePath is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const servicePath = analyticsserviceModule.v2alpha.AnalyticsServiceClient.servicePath; - assert.strictEqual(servicePath, 'retail.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = analyticsserviceModule.v2alpha.AnalyticsServiceClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'retail.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new analyticsserviceModule.v2alpha.AnalyticsServiceClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'retail.example.com'); - }); - - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new analyticsserviceModule.v2alpha.AnalyticsServiceClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'retail.example.com'); - }); - - if (typeof process === 'object' && 'env' in process) { - describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { - it('sets apiEndpoint from environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new analyticsserviceModule.v2alpha.AnalyticsServiceClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'retail.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - - it('value configured in code has priority over environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new analyticsserviceModule.v2alpha.AnalyticsServiceClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'retail.configured.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { new analyticsserviceModule.v2alpha.AnalyticsServiceClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); - - it('has port', () => { - const port = analyticsserviceModule.v2alpha.AnalyticsServiceClient.port; - assert(port); - assert(typeof port === 'number'); - }); - - it('should create a client with no option', () => { - const client = new analyticsserviceModule.v2alpha.AnalyticsServiceClient(); - assert(client); - }); - - it('should create a client with gRPC fallback', () => { - const client = new analyticsserviceModule.v2alpha.AnalyticsServiceClient({ - fallback: true, - }); - assert(client); - }); - - it('has initialize method and supports deferred initialization', async () => { - const client = new analyticsserviceModule.v2alpha.AnalyticsServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.analyticsServiceStub, undefined); - await client.initialize(); - assert(client.analyticsServiceStub); - }); - - it('has close method for the initialized client', done => { - const client = new analyticsserviceModule.v2alpha.AnalyticsServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.analyticsServiceStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); - - it('has close method for the non-initialized client', done => { - const client = new analyticsserviceModule.v2alpha.AnalyticsServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.analyticsServiceStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); - - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new analyticsserviceModule.v2alpha.AnalyticsServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); - }); - - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new analyticsserviceModule.v2alpha.AnalyticsServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId((err?: Error|null, projectId?: string|null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } - }); - }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = + new analyticsserviceModule.v2alpha.AnalyticsServiceClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'retail.googleapis.com'); }); - describe('exportAnalyticsMetrics', () => { - it('invokes exportAnalyticsMetrics without error', async () => { - const client = new analyticsserviceModule.v2alpha.AnalyticsServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ExportAnalyticsMetricsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ExportAnalyticsMetricsRequest', ['catalog']); - request.catalog = defaultValue1; - const expectedHeaderRequestParams = `catalog=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.exportAnalyticsMetrics = stubLongRunningCall(expectedResponse); - const [operation] = await client.exportAnalyticsMetrics(request); - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.exportAnalyticsMetrics as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.exportAnalyticsMetrics as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes exportAnalyticsMetrics without error using callback', async () => { - const client = new analyticsserviceModule.v2alpha.AnalyticsServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ExportAnalyticsMetricsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ExportAnalyticsMetricsRequest', ['catalog']); - request.catalog = defaultValue1; - const expectedHeaderRequestParams = `catalog=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.exportAnalyticsMetrics = stubLongRunningCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.exportAnalyticsMetrics( - request, - (err?: Error|null, - result?: LROperation|null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const operation = await promise as LROperation; - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.exportAnalyticsMetrics as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.exportAnalyticsMetrics as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes exportAnalyticsMetrics with call error', async () => { - const client = new analyticsserviceModule.v2alpha.AnalyticsServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ExportAnalyticsMetricsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ExportAnalyticsMetricsRequest', ['catalog']); - request.catalog = defaultValue1; - const expectedHeaderRequestParams = `catalog=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.exportAnalyticsMetrics = stubLongRunningCall(undefined, expectedError); - await assert.rejects(client.exportAnalyticsMetrics(request), expectedError); - const actualRequest = (client.innerApiCalls.exportAnalyticsMetrics as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.exportAnalyticsMetrics as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes exportAnalyticsMetrics with LRO error', async () => { - const client = new analyticsserviceModule.v2alpha.AnalyticsServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ExportAnalyticsMetricsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ExportAnalyticsMetricsRequest', ['catalog']); - request.catalog = defaultValue1; - const expectedHeaderRequestParams = `catalog=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.exportAnalyticsMetrics = stubLongRunningCall(undefined, undefined, expectedError); - const [operation] = await client.exportAnalyticsMetrics(request); - await assert.rejects(operation.promise(), expectedError); - const actualRequest = (client.innerApiCalls.exportAnalyticsMetrics as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.exportAnalyticsMetrics as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes checkExportAnalyticsMetricsProgress without error', async () => { - const client = new analyticsserviceModule.v2alpha.AnalyticsServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedResponse = generateSampleMessage( - new operationsProtos.google.longrunning.Operation() - ); - expectedResponse.name = 'test'; - expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; - expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')} - - client.operationsClient.getOperation = stubSimpleCall(expectedResponse); - const decodedOperation = await client.checkExportAnalyticsMetricsProgress(expectedResponse.name); - assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); - assert(decodedOperation.metadata); - assert((client.operationsClient.getOperation as SinonStub).getCall(0)); - }); - - it('invokes checkExportAnalyticsMetricsProgress with error', async () => { - const client = new analyticsserviceModule.v2alpha.AnalyticsServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedError = new Error('expected'); - - client.operationsClient.getOperation = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.checkExportAnalyticsMetricsProgress(''), expectedError); - assert((client.operationsClient.getOperation as SinonStub) - .getCall(0)); - }); + it('has universeDomain', () => { + const client = + new analyticsserviceModule.v2alpha.AnalyticsServiceClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); }); - describe('Path templates', () => { - - describe('alertConfig', async () => { - const fakePath = "/rendered/path/alertConfig"; - const expectedParameters = { - project: "projectValue", - }; - const client = new analyticsserviceModule.v2alpha.AnalyticsServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.alertConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.alertConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('alertConfigPath', () => { - const result = client.alertConfigPath("projectValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.alertConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromAlertConfigName', () => { - const result = client.matchProjectFromAlertConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.alertConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('attributesConfig', async () => { - const fakePath = "/rendered/path/attributesConfig"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - }; - const client = new analyticsserviceModule.v2alpha.AnalyticsServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.attributesConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.attributesConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('attributesConfigPath', () => { - const result = client.attributesConfigPath("projectValue", "locationValue", "catalogValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.attributesConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromAttributesConfigName', () => { - const result = client.matchProjectFromAttributesConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = + analyticsserviceModule.v2alpha.AnalyticsServiceClient.servicePath; + assert.strictEqual(servicePath, 'retail.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + analyticsserviceModule.v2alpha.AnalyticsServiceClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'retail.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = new analyticsserviceModule.v2alpha.AnalyticsServiceClient({ + universeDomain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'retail.example.com'); + }); - it('matchLocationFromAttributesConfigName', () => { - const result = client.matchLocationFromAttributesConfigName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = new analyticsserviceModule.v2alpha.AnalyticsServiceClient({ + universe_domain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'retail.example.com'); + }); - it('matchCatalogFromAttributesConfigName', () => { - const result = client.matchCatalogFromAttributesConfigName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + if (typeof process === 'object' && 'env' in process) { + describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { + it('sets apiEndpoint from environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = + new analyticsserviceModule.v2alpha.AnalyticsServiceClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'retail.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - describe('branch', async () => { - const fakePath = "/rendered/path/branch"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - branch: "branchValue", - }; - const client = new analyticsserviceModule.v2alpha.AnalyticsServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.branchPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.branchPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('branchPath', () => { - const result = client.branchPath("projectValue", "locationValue", "catalogValue", "branchValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.branchPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromBranchName', () => { - const result = client.matchProjectFromBranchName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.branchPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromBranchName', () => { - const result = client.matchLocationFromBranchName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.branchPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromBranchName', () => { - const result = client.matchCatalogFromBranchName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.branchPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBranchFromBranchName', () => { - const result = client.matchBranchFromBranchName(fakePath); - assert.strictEqual(result, "branchValue"); - assert((client.pathTemplates.branchPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('value configured in code has priority over environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = + new analyticsserviceModule.v2alpha.AnalyticsServiceClient({ + universeDomain: 'configured.example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'retail.configured.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - - describe('catalog', async () => { - const fakePath = "/rendered/path/catalog"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - }; - const client = new analyticsserviceModule.v2alpha.AnalyticsServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.catalogPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.catalogPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('catalogPath', () => { - const result = client.catalogPath("projectValue", "locationValue", "catalogValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.catalogPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromCatalogName', () => { - const result = client.matchProjectFromCatalogName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.catalogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromCatalogName', () => { - const result = client.matchLocationFromCatalogName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.catalogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromCatalogName', () => { - const result = client.matchCatalogFromCatalogName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.catalogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('completionConfig', async () => { - const fakePath = "/rendered/path/completionConfig"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - }; - const client = new analyticsserviceModule.v2alpha.AnalyticsServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.completionConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.completionConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('completionConfigPath', () => { - const result = client.completionConfigPath("projectValue", "locationValue", "catalogValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.completionConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromCompletionConfigName', () => { - const result = client.matchProjectFromCompletionConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.completionConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromCompletionConfigName', () => { - const result = client.matchLocationFromCompletionConfigName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.completionConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromCompletionConfigName', () => { - const result = client.matchCatalogFromCompletionConfigName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.completionConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new analyticsserviceModule.v2alpha.AnalyticsServiceClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); + }); - describe('control', async () => { - const fakePath = "/rendered/path/control"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - control: "controlValue", - }; - const client = new analyticsserviceModule.v2alpha.AnalyticsServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.controlPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.controlPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('controlPath', () => { - const result = client.controlPath("projectValue", "locationValue", "catalogValue", "controlValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.controlPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + it('has port', () => { + const port = analyticsserviceModule.v2alpha.AnalyticsServiceClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('matchProjectFromControlName', () => { - const result = client.matchProjectFromControlName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.controlPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('should create a client with no option', () => { + const client = + new analyticsserviceModule.v2alpha.AnalyticsServiceClient(); + assert(client); + }); - it('matchLocationFromControlName', () => { - const result = client.matchLocationFromControlName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.controlPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('should create a client with gRPC fallback', () => { + const client = new analyticsserviceModule.v2alpha.AnalyticsServiceClient({ + fallback: true, + }); + assert(client); + }); - it('matchCatalogFromControlName', () => { - const result = client.matchCatalogFromControlName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.controlPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('has initialize method and supports deferred initialization', async () => { + const client = new analyticsserviceModule.v2alpha.AnalyticsServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.analyticsServiceStub, undefined); + await client.initialize(); + assert(client.analyticsServiceStub); + }); - it('matchControlFromControlName', () => { - const result = client.matchControlFromControlName(fakePath); - assert.strictEqual(result, "controlValue"); - assert((client.pathTemplates.controlPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('has close method for the initialized client', (done) => { + const client = new analyticsserviceModule.v2alpha.AnalyticsServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.analyticsServiceStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - describe('loggingConfig', async () => { - const fakePath = "/rendered/path/loggingConfig"; - const expectedParameters = { - project: "projectValue", - }; - const client = new analyticsserviceModule.v2alpha.AnalyticsServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.loggingConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.loggingConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('loggingConfigPath', () => { - const result = client.loggingConfigPath("projectValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.loggingConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromLoggingConfigName', () => { - const result = client.matchProjectFromLoggingConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.loggingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('has close method for the non-initialized client', (done) => { + const client = new analyticsserviceModule.v2alpha.AnalyticsServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.analyticsServiceStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - describe('merchantCenterAccountLink', async () => { - const fakePath = "/rendered/path/merchantCenterAccountLink"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - merchant_center_account_link: "merchantCenterAccountLinkValue", - }; - const client = new analyticsserviceModule.v2alpha.AnalyticsServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.merchantCenterAccountLinkPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.merchantCenterAccountLinkPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('merchantCenterAccountLinkPath', () => { - const result = client.merchantCenterAccountLinkPath("projectValue", "locationValue", "catalogValue", "merchantCenterAccountLinkValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromMerchantCenterAccountLinkName', () => { - const result = client.matchProjectFromMerchantCenterAccountLinkName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromMerchantCenterAccountLinkName', () => { - const result = client.matchLocationFromMerchantCenterAccountLinkName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromMerchantCenterAccountLinkName', () => { - const result = client.matchCatalogFromMerchantCenterAccountLinkName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new analyticsserviceModule.v2alpha.AnalyticsServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + }); - it('matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName', () => { - const result = client.matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName(fakePath); - assert.strictEqual(result, "merchantCenterAccountLinkValue"); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new analyticsserviceModule.v2alpha.AnalyticsServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + }); + + describe('exportAnalyticsMetrics', () => { + it('invokes exportAnalyticsMetrics without error', async () => { + const client = new analyticsserviceModule.v2alpha.AnalyticsServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ExportAnalyticsMetricsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ExportAnalyticsMetricsRequest', + ['catalog'], + ); + request.catalog = defaultValue1; + const expectedHeaderRequestParams = `catalog=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.exportAnalyticsMetrics = + stubLongRunningCall(expectedResponse); + const [operation] = await client.exportAnalyticsMetrics(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.exportAnalyticsMetrics as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.exportAnalyticsMetrics as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - describe('model', async () => { - const fakePath = "/rendered/path/model"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - model: "modelValue", - }; - const client = new analyticsserviceModule.v2alpha.AnalyticsServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.modelPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.modelPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('modelPath', () => { - const result = client.modelPath("projectValue", "locationValue", "catalogValue", "modelValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.modelPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromModelName', () => { - const result = client.matchProjectFromModelName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromModelName', () => { - const result = client.matchLocationFromModelName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('invokes exportAnalyticsMetrics without error using callback', async () => { + const client = new analyticsserviceModule.v2alpha.AnalyticsServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ExportAnalyticsMetricsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ExportAnalyticsMetricsRequest', + ['catalog'], + ); + request.catalog = defaultValue1; + const expectedHeaderRequestParams = `catalog=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.exportAnalyticsMetrics = + stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.exportAnalyticsMetrics( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.cloud.retail.v2alpha.IExportAnalyticsMetricsResponse, + protos.google.cloud.retail.v2alpha.IExportMetadata + > | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const operation = (await promise) as LROperation< + protos.google.cloud.retail.v2alpha.IExportAnalyticsMetricsResponse, + protos.google.cloud.retail.v2alpha.IExportMetadata + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.exportAnalyticsMetrics as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.exportAnalyticsMetrics as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('matchCatalogFromModelName', () => { - const result = client.matchCatalogFromModelName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('invokes exportAnalyticsMetrics with call error', async () => { + const client = new analyticsserviceModule.v2alpha.AnalyticsServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ExportAnalyticsMetricsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ExportAnalyticsMetricsRequest', + ['catalog'], + ); + request.catalog = defaultValue1; + const expectedHeaderRequestParams = `catalog=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.exportAnalyticsMetrics = stubLongRunningCall( + undefined, + expectedError, + ); + await assert.rejects( + client.exportAnalyticsMetrics(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.exportAnalyticsMetrics as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.exportAnalyticsMetrics as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('matchModelFromModelName', () => { - const result = client.matchModelFromModelName(fakePath); - assert.strictEqual(result, "modelValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('invokes exportAnalyticsMetrics with LRO error', async () => { + const client = new analyticsserviceModule.v2alpha.AnalyticsServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ExportAnalyticsMetricsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ExportAnalyticsMetricsRequest', + ['catalog'], + ); + request.catalog = defaultValue1; + const expectedHeaderRequestParams = `catalog=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.exportAnalyticsMetrics = stubLongRunningCall( + undefined, + undefined, + expectedError, + ); + const [operation] = await client.exportAnalyticsMetrics(request); + await assert.rejects(operation.promise(), expectedError); + const actualRequest = ( + client.innerApiCalls.exportAnalyticsMetrics as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.exportAnalyticsMetrics as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - describe('product', async () => { - const fakePath = "/rendered/path/product"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - branch: "branchValue", - product: "productValue", - }; - const client = new analyticsserviceModule.v2alpha.AnalyticsServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.productPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.productPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('productPath', () => { - const result = client.productPath("projectValue", "locationValue", "catalogValue", "branchValue", "productValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.productPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + it('invokes checkExportAnalyticsMetricsProgress without error', async () => { + const client = new analyticsserviceModule.v2alpha.AnalyticsServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation(), + ); + expectedResponse.name = 'test'; + expectedResponse.response = { type_url: 'url', value: Buffer.from('') }; + expectedResponse.metadata = { type_url: 'url', value: Buffer.from('') }; + + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const decodedOperation = await client.checkExportAnalyticsMetricsProgress( + expectedResponse.name, + ); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); - it('matchProjectFromProductName', () => { - const result = client.matchProjectFromProductName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('invokes checkExportAnalyticsMetricsProgress with error', async () => { + const client = new analyticsserviceModule.v2alpha.AnalyticsServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const expectedError = new Error('expected'); + + client.operationsClient.getOperation = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.checkExportAnalyticsMetricsProgress(''), + expectedError, + ); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + }); + + describe('Path templates', () => { + describe('alertConfig', async () => { + const fakePath = '/rendered/path/alertConfig'; + const expectedParameters = { + project: 'projectValue', + }; + const client = new analyticsserviceModule.v2alpha.AnalyticsServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.alertConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.alertConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('alertConfigPath', () => { + const result = client.alertConfigPath('projectValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.alertConfigPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromAlertConfigName', () => { + const result = client.matchProjectFromAlertConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.alertConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchLocationFromProductName', () => { - const result = client.matchLocationFromProductName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('attributesConfig', async () => { + const fakePath = '/rendered/path/attributesConfig'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + }; + const client = new analyticsserviceModule.v2alpha.AnalyticsServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.attributesConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.attributesConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('attributesConfigPath', () => { + const result = client.attributesConfigPath( + 'projectValue', + 'locationValue', + 'catalogValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.attributesConfigPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromAttributesConfigName', () => { + const result = client.matchProjectFromAttributesConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromAttributesConfigName', () => { + const result = client.matchLocationFromAttributesConfigName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromAttributesConfigName', () => { + const result = client.matchCatalogFromAttributesConfigName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchCatalogFromProductName', () => { - const result = client.matchCatalogFromProductName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('branch', async () => { + const fakePath = '/rendered/path/branch'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + branch: 'branchValue', + }; + const client = new analyticsserviceModule.v2alpha.AnalyticsServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.branchPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.branchPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('branchPath', () => { + const result = client.branchPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'branchValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.branchPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromBranchName', () => { + const result = client.matchProjectFromBranchName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.branchPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromBranchName', () => { + const result = client.matchLocationFromBranchName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.branchPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromBranchName', () => { + const result = client.matchCatalogFromBranchName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.branchPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBranchFromBranchName', () => { + const result = client.matchBranchFromBranchName(fakePath); + assert.strictEqual(result, 'branchValue'); + assert( + (client.pathTemplates.branchPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchBranchFromProductName', () => { - const result = client.matchBranchFromProductName(fakePath); - assert.strictEqual(result, "branchValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('catalog', async () => { + const fakePath = '/rendered/path/catalog'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + }; + const client = new analyticsserviceModule.v2alpha.AnalyticsServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.catalogPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.catalogPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('catalogPath', () => { + const result = client.catalogPath( + 'projectValue', + 'locationValue', + 'catalogValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.catalogPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromCatalogName', () => { + const result = client.matchProjectFromCatalogName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.catalogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromCatalogName', () => { + const result = client.matchLocationFromCatalogName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.catalogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromCatalogName', () => { + const result = client.matchCatalogFromCatalogName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.catalogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchProductFromProductName', () => { - const result = client.matchProductFromProductName(fakePath); - assert.strictEqual(result, "productValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('completionConfig', async () => { + const fakePath = '/rendered/path/completionConfig'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + }; + const client = new analyticsserviceModule.v2alpha.AnalyticsServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.completionConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.completionConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('completionConfigPath', () => { + const result = client.completionConfigPath( + 'projectValue', + 'locationValue', + 'catalogValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.completionConfigPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromCompletionConfigName', () => { + const result = client.matchProjectFromCompletionConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.completionConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromCompletionConfigName', () => { + const result = client.matchLocationFromCompletionConfigName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.completionConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromCompletionConfigName', () => { + const result = client.matchCatalogFromCompletionConfigName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.completionConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('retailProject', async () => { - const fakePath = "/rendered/path/retailProject"; - const expectedParameters = { - project: "projectValue", - }; - const client = new analyticsserviceModule.v2alpha.AnalyticsServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.retailProjectPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.retailProjectPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('retailProjectPath', () => { - const result = client.retailProjectPath("projectValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.retailProjectPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + describe('control', async () => { + const fakePath = '/rendered/path/control'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + control: 'controlValue', + }; + const client = new analyticsserviceModule.v2alpha.AnalyticsServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.controlPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.controlPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('controlPath', () => { + const result = client.controlPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'controlValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.controlPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromControlName', () => { + const result = client.matchProjectFromControlName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.controlPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromControlName', () => { + const result = client.matchLocationFromControlName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.controlPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromControlName', () => { + const result = client.matchCatalogFromControlName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.controlPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchControlFromControlName', () => { + const result = client.matchControlFromControlName(fakePath); + assert.strictEqual(result, 'controlValue'); + assert( + (client.pathTemplates.controlPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchProjectFromRetailProjectName', () => { - const result = client.matchProjectFromRetailProjectName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.retailProjectPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('loggingConfig', async () => { + const fakePath = '/rendered/path/loggingConfig'; + const expectedParameters = { + project: 'projectValue', + }; + const client = new analyticsserviceModule.v2alpha.AnalyticsServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.loggingConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.loggingConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('loggingConfigPath', () => { + const result = client.loggingConfigPath('projectValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.loggingConfigPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromLoggingConfigName', () => { + const result = client.matchProjectFromLoggingConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.loggingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('servingConfig', async () => { - const fakePath = "/rendered/path/servingConfig"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - serving_config: "servingConfigValue", - }; - const client = new analyticsserviceModule.v2alpha.AnalyticsServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.servingConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.servingConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('servingConfigPath', () => { - const result = client.servingConfigPath("projectValue", "locationValue", "catalogValue", "servingConfigValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.servingConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + describe('merchantCenterAccountLink', async () => { + const fakePath = '/rendered/path/merchantCenterAccountLink'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + merchant_center_account_link: 'merchantCenterAccountLinkValue', + }; + const client = new analyticsserviceModule.v2alpha.AnalyticsServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.merchantCenterAccountLinkPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.merchantCenterAccountLinkPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('merchantCenterAccountLinkPath', () => { + const result = client.merchantCenterAccountLinkPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'merchantCenterAccountLinkValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromMerchantCenterAccountLinkName', () => { + const result = + client.matchProjectFromMerchantCenterAccountLinkName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromMerchantCenterAccountLinkName', () => { + const result = + client.matchLocationFromMerchantCenterAccountLinkName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromMerchantCenterAccountLinkName', () => { + const result = + client.matchCatalogFromMerchantCenterAccountLinkName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName', () => { + const result = + client.matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName( + fakePath, + ); + assert.strictEqual(result, 'merchantCenterAccountLinkValue'); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchProjectFromServingConfigName', () => { - const result = client.matchProjectFromServingConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.servingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('model', async () => { + const fakePath = '/rendered/path/model'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + model: 'modelValue', + }; + const client = new analyticsserviceModule.v2alpha.AnalyticsServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.modelPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.modelPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('modelPath', () => { + const result = client.modelPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'modelValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.modelPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromModelName', () => { + const result = client.matchProjectFromModelName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromModelName', () => { + const result = client.matchLocationFromModelName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromModelName', () => { + const result = client.matchCatalogFromModelName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchModelFromModelName', () => { + const result = client.matchModelFromModelName(fakePath); + assert.strictEqual(result, 'modelValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchLocationFromServingConfigName', () => { - const result = client.matchLocationFromServingConfigName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.servingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('product', async () => { + const fakePath = '/rendered/path/product'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + branch: 'branchValue', + product: 'productValue', + }; + const client = new analyticsserviceModule.v2alpha.AnalyticsServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.productPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.productPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('productPath', () => { + const result = client.productPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'branchValue', + 'productValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.productPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProductName', () => { + const result = client.matchProjectFromProductName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromProductName', () => { + const result = client.matchLocationFromProductName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromProductName', () => { + const result = client.matchCatalogFromProductName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBranchFromProductName', () => { + const result = client.matchBranchFromProductName(fakePath); + assert.strictEqual(result, 'branchValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchProductFromProductName', () => { + const result = client.matchProductFromProductName(fakePath); + assert.strictEqual(result, 'productValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchCatalogFromServingConfigName', () => { - const result = client.matchCatalogFromServingConfigName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.servingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('retailProject', async () => { + const fakePath = '/rendered/path/retailProject'; + const expectedParameters = { + project: 'projectValue', + }; + const client = new analyticsserviceModule.v2alpha.AnalyticsServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.retailProjectPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.retailProjectPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('retailProjectPath', () => { + const result = client.retailProjectPath('projectValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.retailProjectPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromRetailProjectName', () => { + const result = client.matchProjectFromRetailProjectName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.retailProjectPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchServingConfigFromServingConfigName', () => { - const result = client.matchServingConfigFromServingConfigName(fakePath); - assert.strictEqual(result, "servingConfigValue"); - assert((client.pathTemplates.servingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('servingConfig', async () => { + const fakePath = '/rendered/path/servingConfig'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + serving_config: 'servingConfigValue', + }; + const client = new analyticsserviceModule.v2alpha.AnalyticsServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.servingConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.servingConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('servingConfigPath', () => { + const result = client.servingConfigPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'servingConfigValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.servingConfigPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromServingConfigName', () => { + const result = client.matchProjectFromServingConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.servingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromServingConfigName', () => { + const result = client.matchLocationFromServingConfigName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.servingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromServingConfigName', () => { + const result = client.matchCatalogFromServingConfigName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.servingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServingConfigFromServingConfigName', () => { + const result = client.matchServingConfigFromServingConfigName(fakePath); + assert.strictEqual(result, 'servingConfigValue'); + assert( + (client.pathTemplates.servingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/core/generator/gapic-generator-typescript/baselines/retail/test/gapic_branch_service_v2alpha.ts.baseline b/core/generator/gapic-generator-typescript/baselines/retail/test/gapic_branch_service_v2alpha.ts.baseline index b2bbf1dd160a..331b34e7000e 100644 --- a/core/generator/gapic-generator-typescript/baselines/retail/test/gapic_branch_service_v2alpha.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/retail/test/gapic_branch_service_v2alpha.ts.baseline @@ -19,975 +19,1302 @@ import * as protos from '../protos/protos'; import * as assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as branchserviceModule from '../src'; -import {protobuf} from 'google-gax'; +import { protobuf } from 'google-gax'; // Dynamically loaded proto JSON is needed to get the type information // to fill in default values for request objects -const root = protobuf.Root.fromJSON(require('../protos/protos.json')).resolveAll(); +const root = protobuf.Root.fromJSON( + require('../protos/protos.json'), +).resolveAll(); // eslint-disable-next-line @typescript-eslint/no-unused-vars function getTypeDefaultValue(typeName: string, fields: string[]) { - let type = root.lookupType(typeName) as protobuf.Type; - for (const field of fields.slice(0, -1)) { - type = type.fields[field]?.resolvedType as protobuf.Type; - } - return type.fields[fields[fields.length - 1]]?.defaultValue; + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type.fields[field]?.resolvedType as protobuf.Type; + } + return type.fields[fields[fields.length - 1]]?.defaultValue; } function generateSampleMessage(instance: T) { - const filledObject = (instance.constructor as typeof protobuf.Message) - .toObject(instance as protobuf.Message, {defaults: true}); - return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, { defaults: true }); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; } function stubSimpleCall(response?: ResponseType, error?: Error) { - return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); } -function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { - return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +function stubSimpleCallWithCallback( + response?: ResponseType, + error?: Error, +) { + return error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); } describe('v2alpha.BranchServiceClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new branchserviceModule.v2alpha.BranchServiceClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'retail.googleapis.com'); - }); - - it('has universeDomain', () => { - const client = new branchserviceModule.v2alpha.BranchServiceClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new branchserviceModule.v2alpha.BranchServiceClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'retail.googleapis.com'); + }); - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - it('throws DeprecationWarning if static servicePath is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const servicePath = branchserviceModule.v2alpha.BranchServiceClient.servicePath; - assert.strictEqual(servicePath, 'retail.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = branchserviceModule.v2alpha.BranchServiceClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'retail.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new branchserviceModule.v2alpha.BranchServiceClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'retail.example.com'); - }); + it('has universeDomain', () => { + const client = new branchserviceModule.v2alpha.BranchServiceClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new branchserviceModule.v2alpha.BranchServiceClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'retail.example.com'); - }); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = + branchserviceModule.v2alpha.BranchServiceClient.servicePath; + assert.strictEqual(servicePath, 'retail.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + branchserviceModule.v2alpha.BranchServiceClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'retail.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = new branchserviceModule.v2alpha.BranchServiceClient({ + universeDomain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'retail.example.com'); + }); - if (typeof process === 'object' && 'env' in process) { - describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { - it('sets apiEndpoint from environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new branchserviceModule.v2alpha.BranchServiceClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'retail.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - - it('value configured in code has priority over environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new branchserviceModule.v2alpha.BranchServiceClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'retail.configured.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { new branchserviceModule.v2alpha.BranchServiceClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = new branchserviceModule.v2alpha.BranchServiceClient({ + universe_domain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'retail.example.com'); + }); - it('has port', () => { - const port = branchserviceModule.v2alpha.BranchServiceClient.port; - assert(port); - assert(typeof port === 'number'); + if (typeof process === 'object' && 'env' in process) { + describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { + it('sets apiEndpoint from environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new branchserviceModule.v2alpha.BranchServiceClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'retail.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - it('should create a client with no option', () => { - const client = new branchserviceModule.v2alpha.BranchServiceClient(); - assert(client); + it('value configured in code has priority over environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new branchserviceModule.v2alpha.BranchServiceClient({ + universeDomain: 'configured.example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'retail.configured.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - - it('should create a client with gRPC fallback', () => { - const client = new branchserviceModule.v2alpha.BranchServiceClient({ - fallback: true, - }); - assert(client); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new branchserviceModule.v2alpha.BranchServiceClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); + }); - it('has initialize method and supports deferred initialization', async () => { - const client = new branchserviceModule.v2alpha.BranchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.branchServiceStub, undefined); - await client.initialize(); - assert(client.branchServiceStub); - }); + it('has port', () => { + const port = branchserviceModule.v2alpha.BranchServiceClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('has close method for the initialized client', done => { - const client = new branchserviceModule.v2alpha.BranchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.branchServiceStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('should create a client with no option', () => { + const client = new branchserviceModule.v2alpha.BranchServiceClient(); + assert(client); + }); - it('has close method for the non-initialized client', done => { - const client = new branchserviceModule.v2alpha.BranchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.branchServiceStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('should create a client with gRPC fallback', () => { + const client = new branchserviceModule.v2alpha.BranchServiceClient({ + fallback: true, + }); + assert(client); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new branchserviceModule.v2alpha.BranchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); - }); + it('has initialize method and supports deferred initialization', async () => { + const client = new branchserviceModule.v2alpha.BranchServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.branchServiceStub, undefined); + await client.initialize(); + assert(client.branchServiceStub); + }); - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new branchserviceModule.v2alpha.BranchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId((err?: Error|null, projectId?: string|null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } - }); - }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); + it('has close method for the initialized client', (done) => { + const client = new branchserviceModule.v2alpha.BranchServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.branchServiceStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); }); - describe('listBranches', () => { - it('invokes listBranches without error', async () => { - const client = new branchserviceModule.v2alpha.BranchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ListBranchesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ListBranchesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ListBranchesResponse() - ); - client.innerApiCalls.listBranches = stubSimpleCall(expectedResponse); - const [response] = await client.listBranches(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listBranches as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listBranches as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('has close method for the non-initialized client', (done) => { + const client = new branchserviceModule.v2alpha.BranchServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.branchServiceStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes listBranches without error using callback', async () => { - const client = new branchserviceModule.v2alpha.BranchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ListBranchesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ListBranchesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ListBranchesResponse() - ); - client.innerApiCalls.listBranches = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listBranches( - request, - (err?: Error|null, result?: protos.google.cloud.retail.v2alpha.IListBranchesResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listBranches as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listBranches as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new branchserviceModule.v2alpha.BranchServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + }); - it('invokes listBranches with error', async () => { - const client = new branchserviceModule.v2alpha.BranchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ListBranchesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ListBranchesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listBranches = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listBranches(request), expectedError); - const actualRequest = (client.innerApiCalls.listBranches as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listBranches as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new branchserviceModule.v2alpha.BranchServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + }); + + describe('listBranches', () => { + it('invokes listBranches without error', async () => { + const client = new branchserviceModule.v2alpha.BranchServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ListBranchesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ListBranchesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ListBranchesResponse(), + ); + client.innerApiCalls.listBranches = stubSimpleCall(expectedResponse); + const [response] = await client.listBranches(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listBranches as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listBranches as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listBranches with closed client', async () => { - const client = new branchserviceModule.v2alpha.BranchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ListBranchesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ListBranchesRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.listBranches(request), expectedError); - }); + it('invokes listBranches without error using callback', async () => { + const client = new branchserviceModule.v2alpha.BranchServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ListBranchesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ListBranchesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ListBranchesResponse(), + ); + client.innerApiCalls.listBranches = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listBranches( + request, + ( + err?: Error | null, + result?: protos.google.cloud.retail.v2alpha.IListBranchesResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listBranches as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listBranches as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('getBranch', () => { - it('invokes getBranch without error', async () => { - const client = new branchserviceModule.v2alpha.BranchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.GetBranchRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.GetBranchRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.Branch() - ); - client.innerApiCalls.getBranch = stubSimpleCall(expectedResponse); - const [response] = await client.getBranch(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getBranch as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getBranch as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listBranches with error', async () => { + const client = new branchserviceModule.v2alpha.BranchServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ListBranchesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ListBranchesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listBranches = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listBranches(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listBranches as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listBranches as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getBranch without error using callback', async () => { - const client = new branchserviceModule.v2alpha.BranchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.GetBranchRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.GetBranchRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.Branch() - ); - client.innerApiCalls.getBranch = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getBranch( - request, - (err?: Error|null, result?: protos.google.cloud.retail.v2alpha.IBranch|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getBranch as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getBranch as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listBranches with closed client', async () => { + const client = new branchserviceModule.v2alpha.BranchServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ListBranchesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ListBranchesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.listBranches(request), expectedError); + }); + }); + + describe('getBranch', () => { + it('invokes getBranch without error', async () => { + const client = new branchserviceModule.v2alpha.BranchServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.GetBranchRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.GetBranchRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.Branch(), + ); + client.innerApiCalls.getBranch = stubSimpleCall(expectedResponse); + const [response] = await client.getBranch(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getBranch as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getBranch as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getBranch with error', async () => { - const client = new branchserviceModule.v2alpha.BranchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.GetBranchRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.GetBranchRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getBranch = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getBranch(request), expectedError); - const actualRequest = (client.innerApiCalls.getBranch as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getBranch as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getBranch without error using callback', async () => { + const client = new branchserviceModule.v2alpha.BranchServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.GetBranchRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.GetBranchRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.Branch(), + ); + client.innerApiCalls.getBranch = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getBranch( + request, + ( + err?: Error | null, + result?: protos.google.cloud.retail.v2alpha.IBranch | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getBranch as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getBranch as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getBranch with closed client', async () => { - const client = new branchserviceModule.v2alpha.BranchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.GetBranchRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.GetBranchRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getBranch(request), expectedError); - }); + it('invokes getBranch with error', async () => { + const client = new branchserviceModule.v2alpha.BranchServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.GetBranchRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.GetBranchRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getBranch = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.getBranch(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getBranch as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getBranch as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('Path templates', () => { - - describe('alertConfig', async () => { - const fakePath = "/rendered/path/alertConfig"; - const expectedParameters = { - project: "projectValue", - }; - const client = new branchserviceModule.v2alpha.BranchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.alertConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.alertConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('alertConfigPath', () => { - const result = client.alertConfigPath("projectValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.alertConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromAlertConfigName', () => { - const result = client.matchProjectFromAlertConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.alertConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('invokes getBranch with closed client', async () => { + const client = new branchserviceModule.v2alpha.BranchServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.GetBranchRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.GetBranchRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getBranch(request), expectedError); + }); + }); + + describe('Path templates', () => { + describe('alertConfig', async () => { + const fakePath = '/rendered/path/alertConfig'; + const expectedParameters = { + project: 'projectValue', + }; + const client = new branchserviceModule.v2alpha.BranchServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.alertConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.alertConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('alertConfigPath', () => { + const result = client.alertConfigPath('projectValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.alertConfigPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromAlertConfigName', () => { + const result = client.matchProjectFromAlertConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.alertConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('attributesConfig', async () => { - const fakePath = "/rendered/path/attributesConfig"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - }; - const client = new branchserviceModule.v2alpha.BranchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.attributesConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.attributesConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('attributesConfigPath', () => { - const result = client.attributesConfigPath("projectValue", "locationValue", "catalogValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.attributesConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromAttributesConfigName', () => { - const result = client.matchProjectFromAttributesConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromAttributesConfigName', () => { - const result = client.matchLocationFromAttributesConfigName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromAttributesConfigName', () => { - const result = client.matchCatalogFromAttributesConfigName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('attributesConfig', async () => { + const fakePath = '/rendered/path/attributesConfig'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + }; + const client = new branchserviceModule.v2alpha.BranchServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.attributesConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.attributesConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('attributesConfigPath', () => { + const result = client.attributesConfigPath( + 'projectValue', + 'locationValue', + 'catalogValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.attributesConfigPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromAttributesConfigName', () => { + const result = client.matchProjectFromAttributesConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromAttributesConfigName', () => { + const result = client.matchLocationFromAttributesConfigName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromAttributesConfigName', () => { + const result = client.matchCatalogFromAttributesConfigName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('branch', async () => { - const fakePath = "/rendered/path/branch"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - branch: "branchValue", - }; - const client = new branchserviceModule.v2alpha.BranchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.branchPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.branchPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('branchPath', () => { - const result = client.branchPath("projectValue", "locationValue", "catalogValue", "branchValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.branchPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromBranchName', () => { - const result = client.matchProjectFromBranchName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.branchPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromBranchName', () => { - const result = client.matchLocationFromBranchName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.branchPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromBranchName', () => { - const result = client.matchCatalogFromBranchName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.branchPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBranchFromBranchName', () => { - const result = client.matchBranchFromBranchName(fakePath); - assert.strictEqual(result, "branchValue"); - assert((client.pathTemplates.branchPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('branch', async () => { + const fakePath = '/rendered/path/branch'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + branch: 'branchValue', + }; + const client = new branchserviceModule.v2alpha.BranchServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.branchPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.branchPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('branchPath', () => { + const result = client.branchPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'branchValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.branchPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromBranchName', () => { + const result = client.matchProjectFromBranchName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.branchPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromBranchName', () => { + const result = client.matchLocationFromBranchName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.branchPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromBranchName', () => { + const result = client.matchCatalogFromBranchName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.branchPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBranchFromBranchName', () => { + const result = client.matchBranchFromBranchName(fakePath); + assert.strictEqual(result, 'branchValue'); + assert( + (client.pathTemplates.branchPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('catalog', async () => { - const fakePath = "/rendered/path/catalog"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - }; - const client = new branchserviceModule.v2alpha.BranchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.catalogPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.catalogPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('catalogPath', () => { - const result = client.catalogPath("projectValue", "locationValue", "catalogValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.catalogPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromCatalogName', () => { - const result = client.matchProjectFromCatalogName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.catalogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromCatalogName', () => { - const result = client.matchLocationFromCatalogName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.catalogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromCatalogName', () => { - const result = client.matchCatalogFromCatalogName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.catalogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('catalog', async () => { + const fakePath = '/rendered/path/catalog'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + }; + const client = new branchserviceModule.v2alpha.BranchServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.catalogPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.catalogPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('catalogPath', () => { + const result = client.catalogPath( + 'projectValue', + 'locationValue', + 'catalogValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.catalogPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromCatalogName', () => { + const result = client.matchProjectFromCatalogName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.catalogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromCatalogName', () => { + const result = client.matchLocationFromCatalogName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.catalogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromCatalogName', () => { + const result = client.matchCatalogFromCatalogName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.catalogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('completionConfig', async () => { - const fakePath = "/rendered/path/completionConfig"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - }; - const client = new branchserviceModule.v2alpha.BranchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.completionConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.completionConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('completionConfigPath', () => { - const result = client.completionConfigPath("projectValue", "locationValue", "catalogValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.completionConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromCompletionConfigName', () => { - const result = client.matchProjectFromCompletionConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.completionConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromCompletionConfigName', () => { - const result = client.matchLocationFromCompletionConfigName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.completionConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromCompletionConfigName', () => { - const result = client.matchCatalogFromCompletionConfigName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.completionConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('completionConfig', async () => { + const fakePath = '/rendered/path/completionConfig'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + }; + const client = new branchserviceModule.v2alpha.BranchServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.completionConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.completionConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('completionConfigPath', () => { + const result = client.completionConfigPath( + 'projectValue', + 'locationValue', + 'catalogValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.completionConfigPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromCompletionConfigName', () => { + const result = client.matchProjectFromCompletionConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.completionConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromCompletionConfigName', () => { + const result = client.matchLocationFromCompletionConfigName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.completionConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromCompletionConfigName', () => { + const result = client.matchCatalogFromCompletionConfigName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.completionConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('control', async () => { - const fakePath = "/rendered/path/control"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - control: "controlValue", - }; - const client = new branchserviceModule.v2alpha.BranchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.controlPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.controlPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('controlPath', () => { - const result = client.controlPath("projectValue", "locationValue", "catalogValue", "controlValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.controlPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromControlName', () => { - const result = client.matchProjectFromControlName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.controlPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromControlName', () => { - const result = client.matchLocationFromControlName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.controlPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromControlName', () => { - const result = client.matchCatalogFromControlName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.controlPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchControlFromControlName', () => { - const result = client.matchControlFromControlName(fakePath); - assert.strictEqual(result, "controlValue"); - assert((client.pathTemplates.controlPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('control', async () => { + const fakePath = '/rendered/path/control'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + control: 'controlValue', + }; + const client = new branchserviceModule.v2alpha.BranchServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.controlPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.controlPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('controlPath', () => { + const result = client.controlPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'controlValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.controlPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromControlName', () => { + const result = client.matchProjectFromControlName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.controlPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromControlName', () => { + const result = client.matchLocationFromControlName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.controlPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromControlName', () => { + const result = client.matchCatalogFromControlName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.controlPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchControlFromControlName', () => { + const result = client.matchControlFromControlName(fakePath); + assert.strictEqual(result, 'controlValue'); + assert( + (client.pathTemplates.controlPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('loggingConfig', async () => { - const fakePath = "/rendered/path/loggingConfig"; - const expectedParameters = { - project: "projectValue", - }; - const client = new branchserviceModule.v2alpha.BranchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.loggingConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.loggingConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('loggingConfigPath', () => { - const result = client.loggingConfigPath("projectValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.loggingConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromLoggingConfigName', () => { - const result = client.matchProjectFromLoggingConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.loggingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('loggingConfig', async () => { + const fakePath = '/rendered/path/loggingConfig'; + const expectedParameters = { + project: 'projectValue', + }; + const client = new branchserviceModule.v2alpha.BranchServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.loggingConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.loggingConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('loggingConfigPath', () => { + const result = client.loggingConfigPath('projectValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.loggingConfigPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromLoggingConfigName', () => { + const result = client.matchProjectFromLoggingConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.loggingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('merchantCenterAccountLink', async () => { - const fakePath = "/rendered/path/merchantCenterAccountLink"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - merchant_center_account_link: "merchantCenterAccountLinkValue", - }; - const client = new branchserviceModule.v2alpha.BranchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.merchantCenterAccountLinkPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.merchantCenterAccountLinkPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('merchantCenterAccountLinkPath', () => { - const result = client.merchantCenterAccountLinkPath("projectValue", "locationValue", "catalogValue", "merchantCenterAccountLinkValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromMerchantCenterAccountLinkName', () => { - const result = client.matchProjectFromMerchantCenterAccountLinkName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromMerchantCenterAccountLinkName', () => { - const result = client.matchLocationFromMerchantCenterAccountLinkName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromMerchantCenterAccountLinkName', () => { - const result = client.matchCatalogFromMerchantCenterAccountLinkName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName', () => { - const result = client.matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName(fakePath); - assert.strictEqual(result, "merchantCenterAccountLinkValue"); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('merchantCenterAccountLink', async () => { + const fakePath = '/rendered/path/merchantCenterAccountLink'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + merchant_center_account_link: 'merchantCenterAccountLinkValue', + }; + const client = new branchserviceModule.v2alpha.BranchServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.merchantCenterAccountLinkPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.merchantCenterAccountLinkPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('merchantCenterAccountLinkPath', () => { + const result = client.merchantCenterAccountLinkPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'merchantCenterAccountLinkValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromMerchantCenterAccountLinkName', () => { + const result = + client.matchProjectFromMerchantCenterAccountLinkName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromMerchantCenterAccountLinkName', () => { + const result = + client.matchLocationFromMerchantCenterAccountLinkName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromMerchantCenterAccountLinkName', () => { + const result = + client.matchCatalogFromMerchantCenterAccountLinkName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName', () => { + const result = + client.matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName( + fakePath, + ); + assert.strictEqual(result, 'merchantCenterAccountLinkValue'); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('model', async () => { - const fakePath = "/rendered/path/model"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - model: "modelValue", - }; - const client = new branchserviceModule.v2alpha.BranchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.modelPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.modelPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('modelPath', () => { - const result = client.modelPath("projectValue", "locationValue", "catalogValue", "modelValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.modelPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromModelName', () => { - const result = client.matchProjectFromModelName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromModelName', () => { - const result = client.matchLocationFromModelName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromModelName', () => { - const result = client.matchCatalogFromModelName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchModelFromModelName', () => { - const result = client.matchModelFromModelName(fakePath); - assert.strictEqual(result, "modelValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('model', async () => { + const fakePath = '/rendered/path/model'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + model: 'modelValue', + }; + const client = new branchserviceModule.v2alpha.BranchServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.modelPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.modelPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('modelPath', () => { + const result = client.modelPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'modelValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.modelPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromModelName', () => { + const result = client.matchProjectFromModelName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromModelName', () => { + const result = client.matchLocationFromModelName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromModelName', () => { + const result = client.matchCatalogFromModelName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchModelFromModelName', () => { + const result = client.matchModelFromModelName(fakePath); + assert.strictEqual(result, 'modelValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('product', async () => { - const fakePath = "/rendered/path/product"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - branch: "branchValue", - product: "productValue", - }; - const client = new branchserviceModule.v2alpha.BranchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.productPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.productPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('productPath', () => { - const result = client.productPath("projectValue", "locationValue", "catalogValue", "branchValue", "productValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.productPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProductName', () => { - const result = client.matchProjectFromProductName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromProductName', () => { - const result = client.matchLocationFromProductName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromProductName', () => { - const result = client.matchCatalogFromProductName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBranchFromProductName', () => { - const result = client.matchBranchFromProductName(fakePath); - assert.strictEqual(result, "branchValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchProductFromProductName', () => { - const result = client.matchProductFromProductName(fakePath); - assert.strictEqual(result, "productValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('product', async () => { + const fakePath = '/rendered/path/product'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + branch: 'branchValue', + product: 'productValue', + }; + const client = new branchserviceModule.v2alpha.BranchServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.productPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.productPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('productPath', () => { + const result = client.productPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'branchValue', + 'productValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.productPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProductName', () => { + const result = client.matchProjectFromProductName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromProductName', () => { + const result = client.matchLocationFromProductName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromProductName', () => { + const result = client.matchCatalogFromProductName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBranchFromProductName', () => { + const result = client.matchBranchFromProductName(fakePath); + assert.strictEqual(result, 'branchValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchProductFromProductName', () => { + const result = client.matchProductFromProductName(fakePath); + assert.strictEqual(result, 'productValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('retailProject', async () => { - const fakePath = "/rendered/path/retailProject"; - const expectedParameters = { - project: "projectValue", - }; - const client = new branchserviceModule.v2alpha.BranchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.retailProjectPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.retailProjectPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('retailProjectPath', () => { - const result = client.retailProjectPath("projectValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.retailProjectPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromRetailProjectName', () => { - const result = client.matchProjectFromRetailProjectName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.retailProjectPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('retailProject', async () => { + const fakePath = '/rendered/path/retailProject'; + const expectedParameters = { + project: 'projectValue', + }; + const client = new branchserviceModule.v2alpha.BranchServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.retailProjectPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.retailProjectPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('retailProjectPath', () => { + const result = client.retailProjectPath('projectValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.retailProjectPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromRetailProjectName', () => { + const result = client.matchProjectFromRetailProjectName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.retailProjectPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('servingConfig', async () => { - const fakePath = "/rendered/path/servingConfig"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - serving_config: "servingConfigValue", - }; - const client = new branchserviceModule.v2alpha.BranchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.servingConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.servingConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('servingConfigPath', () => { - const result = client.servingConfigPath("projectValue", "locationValue", "catalogValue", "servingConfigValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.servingConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromServingConfigName', () => { - const result = client.matchProjectFromServingConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.servingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromServingConfigName', () => { - const result = client.matchLocationFromServingConfigName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.servingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromServingConfigName', () => { - const result = client.matchCatalogFromServingConfigName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.servingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServingConfigFromServingConfigName', () => { - const result = client.matchServingConfigFromServingConfigName(fakePath); - assert.strictEqual(result, "servingConfigValue"); - assert((client.pathTemplates.servingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('servingConfig', async () => { + const fakePath = '/rendered/path/servingConfig'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + serving_config: 'servingConfigValue', + }; + const client = new branchserviceModule.v2alpha.BranchServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.servingConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.servingConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('servingConfigPath', () => { + const result = client.servingConfigPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'servingConfigValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.servingConfigPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromServingConfigName', () => { + const result = client.matchProjectFromServingConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.servingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromServingConfigName', () => { + const result = client.matchLocationFromServingConfigName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.servingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromServingConfigName', () => { + const result = client.matchCatalogFromServingConfigName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.servingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServingConfigFromServingConfigName', () => { + const result = client.matchServingConfigFromServingConfigName(fakePath); + assert.strictEqual(result, 'servingConfigValue'); + assert( + (client.pathTemplates.servingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/core/generator/gapic-generator-typescript/baselines/retail/test/gapic_catalog_service_v2alpha.ts.baseline b/core/generator/gapic-generator-typescript/baselines/retail/test/gapic_catalog_service_v2alpha.ts.baseline index c042b00f66e1..edb398349e55 100644 --- a/core/generator/gapic-generator-typescript/baselines/retail/test/gapic_catalog_service_v2alpha.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/retail/test/gapic_catalog_service_v2alpha.ts.baseline @@ -19,2289 +19,2959 @@ import * as protos from '../protos/protos'; import * as assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as catalogserviceModule from '../src'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; -import {protobuf} from 'google-gax'; +import { protobuf } from 'google-gax'; // Dynamically loaded proto JSON is needed to get the type information // to fill in default values for request objects -const root = protobuf.Root.fromJSON(require('../protos/protos.json')).resolveAll(); +const root = protobuf.Root.fromJSON( + require('../protos/protos.json'), +).resolveAll(); // eslint-disable-next-line @typescript-eslint/no-unused-vars function getTypeDefaultValue(typeName: string, fields: string[]) { - let type = root.lookupType(typeName) as protobuf.Type; - for (const field of fields.slice(0, -1)) { - type = type.fields[field]?.resolvedType as protobuf.Type; - } - return type.fields[fields[fields.length - 1]]?.defaultValue; + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type.fields[field]?.resolvedType as protobuf.Type; + } + return type.fields[fields[fields.length - 1]]?.defaultValue; } function generateSampleMessage(instance: T) { - const filledObject = (instance.constructor as typeof protobuf.Message) - .toObject(instance as protobuf.Message, {defaults: true}); - return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, { defaults: true }); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; } function stubSimpleCall(response?: ResponseType, error?: Error) { - return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); } -function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { - return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +function stubSimpleCallWithCallback( + response?: ResponseType, + error?: Error, +) { + return error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); } -function stubPageStreamingCall(responses?: ResponseType[], error?: Error) { - const pagingStub = sinon.stub(); - if (responses) { - for (let i = 0; i < responses.length; ++i) { - pagingStub.onCall(i).callsArgWith(2, null, responses[i]); - } +function stubPageStreamingCall( + responses?: ResponseType[], + error?: Error, +) { + const pagingStub = sinon.stub(); + if (responses) { + for (let i = 0; i < responses.length; ++i) { + pagingStub.onCall(i).callsArgWith(2, null, responses[i]); } - const transformStub = error ? sinon.stub().callsArgWith(2, error) : pagingStub; - const mockStream = new PassThrough({ - objectMode: true, - transform: transformStub, - }); - // trigger as many responses as needed - if (responses) { - for (let i = 0; i < responses.length; ++i) { - setImmediate(() => { mockStream.write({}); }); - } - setImmediate(() => { mockStream.end(); }); - } else { - setImmediate(() => { mockStream.write({}); }); - setImmediate(() => { mockStream.end(); }); + } + const transformStub = error + ? sinon.stub().callsArgWith(2, error) + : pagingStub; + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + // trigger as many responses as needed + if (responses) { + for (let i = 0; i < responses.length; ++i) { + setImmediate(() => { + mockStream.write({}); + }); } - return sinon.stub().returns(mockStream); + setImmediate(() => { + mockStream.end(); + }); + } else { + setImmediate(() => { + mockStream.write({}); + }); + setImmediate(() => { + mockStream.end(); + }); + } + return sinon.stub().returns(mockStream); } -function stubAsyncIterationCall(responses?: ResponseType[], error?: Error) { - let counter = 0; - const asyncIterable = { - [Symbol.asyncIterator]() { - return { - async next() { - if (error) { - return Promise.reject(error); - } - if (counter >= responses!.length) { - return Promise.resolve({done: true, value: undefined}); - } - return Promise.resolve({done: false, value: responses![counter++]}); - } - }; - } - }; - return sinon.stub().returns(asyncIterable); +function stubAsyncIterationCall( + responses?: ResponseType[], + error?: Error, +) { + let counter = 0; + const asyncIterable = { + [Symbol.asyncIterator]() { + return { + async next() { + if (error) { + return Promise.reject(error); + } + if (counter >= responses!.length) { + return Promise.resolve({ done: true, value: undefined }); + } + return Promise.resolve({ done: false, value: responses![counter++] }); + }, + }; + }, + }; + return sinon.stub().returns(asyncIterable); } describe('v2alpha.CatalogServiceClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new catalogserviceModule.v2alpha.CatalogServiceClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'retail.googleapis.com'); - }); - - it('has universeDomain', () => { - const client = new catalogserviceModule.v2alpha.CatalogServiceClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); - - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - it('throws DeprecationWarning if static servicePath is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const servicePath = catalogserviceModule.v2alpha.CatalogServiceClient.servicePath; - assert.strictEqual(servicePath, 'retail.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = catalogserviceModule.v2alpha.CatalogServiceClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'retail.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'retail.example.com'); - }); - - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'retail.example.com'); - }); - - if (typeof process === 'object' && 'env' in process) { - describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { - it('sets apiEndpoint from environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new catalogserviceModule.v2alpha.CatalogServiceClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'retail.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - - it('value configured in code has priority over environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'retail.configured.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { new catalogserviceModule.v2alpha.CatalogServiceClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); - - it('has port', () => { - const port = catalogserviceModule.v2alpha.CatalogServiceClient.port; - assert(port); - assert(typeof port === 'number'); - }); - - it('should create a client with no option', () => { - const client = new catalogserviceModule.v2alpha.CatalogServiceClient(); - assert(client); - }); - - it('should create a client with gRPC fallback', () => { - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - fallback: true, - }); - assert(client); - }); - - it('has initialize method and supports deferred initialization', async () => { - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.catalogServiceStub, undefined); - await client.initialize(); - assert(client.catalogServiceStub); - }); - - it('has close method for the initialized client', done => { - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.catalogServiceStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); - - it('has close method for the non-initialized client', done => { - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.catalogServiceStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); - - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); - }); - - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId((err?: Error|null, projectId?: string|null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } - }); - }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new catalogserviceModule.v2alpha.CatalogServiceClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'retail.googleapis.com'); }); - describe('updateCatalog', () => { - it('invokes updateCatalog without error', async () => { - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.UpdateCatalogRequest() - ); - request.catalog ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.UpdateCatalogRequest', ['catalog', 'name']); - request.catalog.name = defaultValue1; - const expectedHeaderRequestParams = `catalog.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.Catalog() - ); - client.innerApiCalls.updateCatalog = stubSimpleCall(expectedResponse); - const [response] = await client.updateCatalog(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateCatalog as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateCatalog as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateCatalog without error using callback', async () => { - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.UpdateCatalogRequest() - ); - request.catalog ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.UpdateCatalogRequest', ['catalog', 'name']); - request.catalog.name = defaultValue1; - const expectedHeaderRequestParams = `catalog.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.Catalog() - ); - client.innerApiCalls.updateCatalog = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateCatalog( - request, - (err?: Error|null, result?: protos.google.cloud.retail.v2alpha.ICatalog|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateCatalog as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateCatalog as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has universeDomain', () => { + const client = new catalogserviceModule.v2alpha.CatalogServiceClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - it('invokes updateCatalog with error', async () => { - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.UpdateCatalogRequest() - ); - request.catalog ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.UpdateCatalogRequest', ['catalog', 'name']); - request.catalog.name = defaultValue1; - const expectedHeaderRequestParams = `catalog.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateCatalog = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateCatalog(request), expectedError); - const actualRequest = (client.innerApiCalls.updateCatalog as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateCatalog as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = + catalogserviceModule.v2alpha.CatalogServiceClient.servicePath; + assert.strictEqual(servicePath, 'retail.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + catalogserviceModule.v2alpha.CatalogServiceClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'retail.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + universeDomain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'retail.example.com'); + }); - it('invokes updateCatalog with closed client', async () => { - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.UpdateCatalogRequest() - ); - request.catalog ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.UpdateCatalogRequest', ['catalog', 'name']); - request.catalog.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateCatalog(request), expectedError); - }); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + universe_domain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'retail.example.com'); }); - describe('setDefaultBranch', () => { - it('invokes setDefaultBranch without error', async () => { - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.SetDefaultBranchRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.SetDefaultBranchRequest', ['catalog']); - request.catalog = defaultValue1; - const expectedHeaderRequestParams = `catalog=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.setDefaultBranch = stubSimpleCall(expectedResponse); - const [response] = await client.setDefaultBranch(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.setDefaultBranch as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.setDefaultBranch as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + if (typeof process === 'object' && 'env' in process) { + describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { + it('sets apiEndpoint from environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = + new catalogserviceModule.v2alpha.CatalogServiceClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'retail.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } + }); + + it('value configured in code has priority over environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + universeDomain: 'configured.example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'retail.configured.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } + }); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new catalogserviceModule.v2alpha.CatalogServiceClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); + }); - it('invokes setDefaultBranch without error using callback', async () => { - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.SetDefaultBranchRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.SetDefaultBranchRequest', ['catalog']); - request.catalog = defaultValue1; - const expectedHeaderRequestParams = `catalog=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.setDefaultBranch = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.setDefaultBranch( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.setDefaultBranch as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.setDefaultBranch as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has port', () => { + const port = catalogserviceModule.v2alpha.CatalogServiceClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('invokes setDefaultBranch with error', async () => { - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.SetDefaultBranchRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.SetDefaultBranchRequest', ['catalog']); - request.catalog = defaultValue1; - const expectedHeaderRequestParams = `catalog=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.setDefaultBranch = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.setDefaultBranch(request), expectedError); - const actualRequest = (client.innerApiCalls.setDefaultBranch as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.setDefaultBranch as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('should create a client with no option', () => { + const client = new catalogserviceModule.v2alpha.CatalogServiceClient(); + assert(client); + }); - it('invokes setDefaultBranch with closed client', async () => { - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.SetDefaultBranchRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.SetDefaultBranchRequest', ['catalog']); - request.catalog = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.setDefaultBranch(request), expectedError); - }); + it('should create a client with gRPC fallback', () => { + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + fallback: true, + }); + assert(client); }); - describe('getDefaultBranch', () => { - it('invokes getDefaultBranch without error', async () => { - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.GetDefaultBranchRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.GetDefaultBranchRequest', ['catalog']); - request.catalog = defaultValue1; - const expectedHeaderRequestParams = `catalog=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.GetDefaultBranchResponse() - ); - client.innerApiCalls.getDefaultBranch = stubSimpleCall(expectedResponse); - const [response] = await client.getDefaultBranch(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getDefaultBranch as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getDefaultBranch as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has initialize method and supports deferred initialization', async () => { + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.catalogServiceStub, undefined); + await client.initialize(); + assert(client.catalogServiceStub); + }); - it('invokes getDefaultBranch without error using callback', async () => { - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.GetDefaultBranchRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.GetDefaultBranchRequest', ['catalog']); - request.catalog = defaultValue1; - const expectedHeaderRequestParams = `catalog=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.GetDefaultBranchResponse() - ); - client.innerApiCalls.getDefaultBranch = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getDefaultBranch( - request, - (err?: Error|null, result?: protos.google.cloud.retail.v2alpha.IGetDefaultBranchResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getDefaultBranch as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getDefaultBranch as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('has close method for the initialized client', (done) => { + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.catalogServiceStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes getDefaultBranch with error', async () => { - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.GetDefaultBranchRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.GetDefaultBranchRequest', ['catalog']); - request.catalog = defaultValue1; - const expectedHeaderRequestParams = `catalog=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getDefaultBranch = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getDefaultBranch(request), expectedError); - const actualRequest = (client.innerApiCalls.getDefaultBranch as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getDefaultBranch as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('has close method for the non-initialized client', (done) => { + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.catalogServiceStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes getDefaultBranch with closed client', async () => { - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.GetDefaultBranchRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.GetDefaultBranchRequest', ['catalog']); - request.catalog = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getDefaultBranch(request), expectedError); - }); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); }); - describe('getCompletionConfig', () => { - it('invokes getCompletionConfig without error', async () => { - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.GetCompletionConfigRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.GetCompletionConfigRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.CompletionConfig() - ); - client.innerApiCalls.getCompletionConfig = stubSimpleCall(expectedResponse); - const [response] = await client.getCompletionConfig(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getCompletionConfig as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getCompletionConfig as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } + }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + }); + + describe('updateCatalog', () => { + it('invokes updateCatalog without error', async () => { + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.UpdateCatalogRequest(), + ); + request.catalog ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.UpdateCatalogRequest', + ['catalog', 'name'], + ); + request.catalog.name = defaultValue1; + const expectedHeaderRequestParams = `catalog.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.Catalog(), + ); + client.innerApiCalls.updateCatalog = stubSimpleCall(expectedResponse); + const [response] = await client.updateCatalog(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateCatalog as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateCatalog as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getCompletionConfig without error using callback', async () => { - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.GetCompletionConfigRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.GetCompletionConfigRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.CompletionConfig() - ); - client.innerApiCalls.getCompletionConfig = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getCompletionConfig( - request, - (err?: Error|null, result?: protos.google.cloud.retail.v2alpha.ICompletionConfig|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getCompletionConfig as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getCompletionConfig as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateCatalog without error using callback', async () => { + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.UpdateCatalogRequest(), + ); + request.catalog ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.UpdateCatalogRequest', + ['catalog', 'name'], + ); + request.catalog.name = defaultValue1; + const expectedHeaderRequestParams = `catalog.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.Catalog(), + ); + client.innerApiCalls.updateCatalog = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateCatalog( + request, + ( + err?: Error | null, + result?: protos.google.cloud.retail.v2alpha.ICatalog | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateCatalog as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateCatalog as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getCompletionConfig with error', async () => { - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.GetCompletionConfigRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.GetCompletionConfigRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getCompletionConfig = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getCompletionConfig(request), expectedError); - const actualRequest = (client.innerApiCalls.getCompletionConfig as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getCompletionConfig as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateCatalog with error', async () => { + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.UpdateCatalogRequest(), + ); + request.catalog ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.UpdateCatalogRequest', + ['catalog', 'name'], + ); + request.catalog.name = defaultValue1; + const expectedHeaderRequestParams = `catalog.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateCatalog = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.updateCatalog(request), expectedError); + const actualRequest = ( + client.innerApiCalls.updateCatalog as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateCatalog as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getCompletionConfig with closed client', async () => { - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.GetCompletionConfigRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.GetCompletionConfigRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getCompletionConfig(request), expectedError); - }); + it('invokes updateCatalog with closed client', async () => { + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.UpdateCatalogRequest(), + ); + request.catalog ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.UpdateCatalogRequest', + ['catalog', 'name'], + ); + request.catalog.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.updateCatalog(request), expectedError); + }); + }); + + describe('setDefaultBranch', () => { + it('invokes setDefaultBranch without error', async () => { + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.SetDefaultBranchRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.SetDefaultBranchRequest', + ['catalog'], + ); + request.catalog = defaultValue1; + const expectedHeaderRequestParams = `catalog=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.setDefaultBranch = stubSimpleCall(expectedResponse); + const [response] = await client.setDefaultBranch(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.setDefaultBranch as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.setDefaultBranch as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('updateCompletionConfig', () => { - it('invokes updateCompletionConfig without error', async () => { - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.UpdateCompletionConfigRequest() - ); - request.completionConfig ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.UpdateCompletionConfigRequest', ['completionConfig', 'name']); - request.completionConfig.name = defaultValue1; - const expectedHeaderRequestParams = `completion_config.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.CompletionConfig() - ); - client.innerApiCalls.updateCompletionConfig = stubSimpleCall(expectedResponse); - const [response] = await client.updateCompletionConfig(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateCompletionConfig as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateCompletionConfig as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes setDefaultBranch without error using callback', async () => { + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.SetDefaultBranchRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.SetDefaultBranchRequest', + ['catalog'], + ); + request.catalog = defaultValue1; + const expectedHeaderRequestParams = `catalog=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.setDefaultBranch = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.setDefaultBranch( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.setDefaultBranch as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.setDefaultBranch as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateCompletionConfig without error using callback', async () => { - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.UpdateCompletionConfigRequest() - ); - request.completionConfig ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.UpdateCompletionConfigRequest', ['completionConfig', 'name']); - request.completionConfig.name = defaultValue1; - const expectedHeaderRequestParams = `completion_config.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.CompletionConfig() - ); - client.innerApiCalls.updateCompletionConfig = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateCompletionConfig( - request, - (err?: Error|null, result?: protos.google.cloud.retail.v2alpha.ICompletionConfig|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateCompletionConfig as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateCompletionConfig as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes setDefaultBranch with error', async () => { + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.SetDefaultBranchRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.SetDefaultBranchRequest', + ['catalog'], + ); + request.catalog = defaultValue1; + const expectedHeaderRequestParams = `catalog=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.setDefaultBranch = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.setDefaultBranch(request), expectedError); + const actualRequest = ( + client.innerApiCalls.setDefaultBranch as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.setDefaultBranch as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateCompletionConfig with error', async () => { - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.UpdateCompletionConfigRequest() - ); - request.completionConfig ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.UpdateCompletionConfigRequest', ['completionConfig', 'name']); - request.completionConfig.name = defaultValue1; - const expectedHeaderRequestParams = `completion_config.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateCompletionConfig = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateCompletionConfig(request), expectedError); - const actualRequest = (client.innerApiCalls.updateCompletionConfig as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateCompletionConfig as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes setDefaultBranch with closed client', async () => { + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.SetDefaultBranchRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.SetDefaultBranchRequest', + ['catalog'], + ); + request.catalog = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.setDefaultBranch(request), expectedError); + }); + }); + + describe('getDefaultBranch', () => { + it('invokes getDefaultBranch without error', async () => { + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.GetDefaultBranchRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.GetDefaultBranchRequest', + ['catalog'], + ); + request.catalog = defaultValue1; + const expectedHeaderRequestParams = `catalog=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.GetDefaultBranchResponse(), + ); + client.innerApiCalls.getDefaultBranch = stubSimpleCall(expectedResponse); + const [response] = await client.getDefaultBranch(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getDefaultBranch as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getDefaultBranch as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateCompletionConfig with closed client', async () => { - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.UpdateCompletionConfigRequest() - ); - request.completionConfig ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.UpdateCompletionConfigRequest', ['completionConfig', 'name']); - request.completionConfig.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateCompletionConfig(request), expectedError); - }); + it('invokes getDefaultBranch without error using callback', async () => { + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.GetDefaultBranchRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.GetDefaultBranchRequest', + ['catalog'], + ); + request.catalog = defaultValue1; + const expectedHeaderRequestParams = `catalog=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.GetDefaultBranchResponse(), + ); + client.innerApiCalls.getDefaultBranch = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getDefaultBranch( + request, + ( + err?: Error | null, + result?: protos.google.cloud.retail.v2alpha.IGetDefaultBranchResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getDefaultBranch as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getDefaultBranch as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('getAttributesConfig', () => { - it('invokes getAttributesConfig without error', async () => { - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.GetAttributesConfigRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.GetAttributesConfigRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.AttributesConfig() - ); - client.innerApiCalls.getAttributesConfig = stubSimpleCall(expectedResponse); - const [response] = await client.getAttributesConfig(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getAttributesConfig as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getAttributesConfig as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getDefaultBranch with error', async () => { + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.GetDefaultBranchRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.GetDefaultBranchRequest', + ['catalog'], + ); + request.catalog = defaultValue1; + const expectedHeaderRequestParams = `catalog=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getDefaultBranch = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getDefaultBranch(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getDefaultBranch as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getDefaultBranch as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getAttributesConfig without error using callback', async () => { - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.GetAttributesConfigRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.GetAttributesConfigRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.AttributesConfig() - ); - client.innerApiCalls.getAttributesConfig = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getAttributesConfig( - request, - (err?: Error|null, result?: protos.google.cloud.retail.v2alpha.IAttributesConfig|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getAttributesConfig as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getAttributesConfig as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getDefaultBranch with closed client', async () => { + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.GetDefaultBranchRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.GetDefaultBranchRequest', + ['catalog'], + ); + request.catalog = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getDefaultBranch(request), expectedError); + }); + }); + + describe('getCompletionConfig', () => { + it('invokes getCompletionConfig without error', async () => { + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.GetCompletionConfigRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.GetCompletionConfigRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.CompletionConfig(), + ); + client.innerApiCalls.getCompletionConfig = + stubSimpleCall(expectedResponse); + const [response] = await client.getCompletionConfig(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getCompletionConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getCompletionConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getAttributesConfig with error', async () => { - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.GetAttributesConfigRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.GetAttributesConfigRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getAttributesConfig = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getAttributesConfig(request), expectedError); - const actualRequest = (client.innerApiCalls.getAttributesConfig as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getAttributesConfig as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getCompletionConfig without error using callback', async () => { + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.GetCompletionConfigRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.GetCompletionConfigRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.CompletionConfig(), + ); + client.innerApiCalls.getCompletionConfig = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getCompletionConfig( + request, + ( + err?: Error | null, + result?: protos.google.cloud.retail.v2alpha.ICompletionConfig | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getCompletionConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getCompletionConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getAttributesConfig with closed client', async () => { - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.GetAttributesConfigRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.GetAttributesConfigRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getAttributesConfig(request), expectedError); - }); + it('invokes getCompletionConfig with error', async () => { + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.GetCompletionConfigRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.GetCompletionConfigRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getCompletionConfig = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getCompletionConfig(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getCompletionConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getCompletionConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('updateAttributesConfig', () => { - it('invokes updateAttributesConfig without error', async () => { - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.UpdateAttributesConfigRequest() - ); - request.attributesConfig ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.UpdateAttributesConfigRequest', ['attributesConfig', 'name']); - request.attributesConfig.name = defaultValue1; - const expectedHeaderRequestParams = `attributes_config.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.AttributesConfig() - ); - client.innerApiCalls.updateAttributesConfig = stubSimpleCall(expectedResponse); - const [response] = await client.updateAttributesConfig(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateAttributesConfig as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateAttributesConfig as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getCompletionConfig with closed client', async () => { + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.GetCompletionConfigRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.GetCompletionConfigRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getCompletionConfig(request), expectedError); + }); + }); + + describe('updateCompletionConfig', () => { + it('invokes updateCompletionConfig without error', async () => { + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.UpdateCompletionConfigRequest(), + ); + request.completionConfig ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.UpdateCompletionConfigRequest', + ['completionConfig', 'name'], + ); + request.completionConfig.name = defaultValue1; + const expectedHeaderRequestParams = `completion_config.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.CompletionConfig(), + ); + client.innerApiCalls.updateCompletionConfig = + stubSimpleCall(expectedResponse); + const [response] = await client.updateCompletionConfig(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateCompletionConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateCompletionConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateAttributesConfig without error using callback', async () => { - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.UpdateAttributesConfigRequest() - ); - request.attributesConfig ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.UpdateAttributesConfigRequest', ['attributesConfig', 'name']); - request.attributesConfig.name = defaultValue1; - const expectedHeaderRequestParams = `attributes_config.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.AttributesConfig() - ); - client.innerApiCalls.updateAttributesConfig = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateAttributesConfig( - request, - (err?: Error|null, result?: protos.google.cloud.retail.v2alpha.IAttributesConfig|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateAttributesConfig as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateAttributesConfig as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateCompletionConfig without error using callback', async () => { + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.UpdateCompletionConfigRequest(), + ); + request.completionConfig ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.UpdateCompletionConfigRequest', + ['completionConfig', 'name'], + ); + request.completionConfig.name = defaultValue1; + const expectedHeaderRequestParams = `completion_config.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.CompletionConfig(), + ); + client.innerApiCalls.updateCompletionConfig = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateCompletionConfig( + request, + ( + err?: Error | null, + result?: protos.google.cloud.retail.v2alpha.ICompletionConfig | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateCompletionConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateCompletionConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateAttributesConfig with error', async () => { - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.UpdateAttributesConfigRequest() - ); - request.attributesConfig ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.UpdateAttributesConfigRequest', ['attributesConfig', 'name']); - request.attributesConfig.name = defaultValue1; - const expectedHeaderRequestParams = `attributes_config.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateAttributesConfig = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateAttributesConfig(request), expectedError); - const actualRequest = (client.innerApiCalls.updateAttributesConfig as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateAttributesConfig as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateCompletionConfig with error', async () => { + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.UpdateCompletionConfigRequest(), + ); + request.completionConfig ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.UpdateCompletionConfigRequest', + ['completionConfig', 'name'], + ); + request.completionConfig.name = defaultValue1; + const expectedHeaderRequestParams = `completion_config.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateCompletionConfig = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.updateCompletionConfig(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.updateCompletionConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateCompletionConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateAttributesConfig with closed client', async () => { - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.UpdateAttributesConfigRequest() - ); - request.attributesConfig ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.UpdateAttributesConfigRequest', ['attributesConfig', 'name']); - request.attributesConfig.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateAttributesConfig(request), expectedError); - }); + it('invokes updateCompletionConfig with closed client', async () => { + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.UpdateCompletionConfigRequest(), + ); + request.completionConfig ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.UpdateCompletionConfigRequest', + ['completionConfig', 'name'], + ); + request.completionConfig.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.updateCompletionConfig(request), + expectedError, + ); + }); + }); + + describe('getAttributesConfig', () => { + it('invokes getAttributesConfig without error', async () => { + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.GetAttributesConfigRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.GetAttributesConfigRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.AttributesConfig(), + ); + client.innerApiCalls.getAttributesConfig = + stubSimpleCall(expectedResponse); + const [response] = await client.getAttributesConfig(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getAttributesConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getAttributesConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('addCatalogAttribute', () => { - it('invokes addCatalogAttribute without error', async () => { - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.AddCatalogAttributeRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.AddCatalogAttributeRequest', ['attributesConfig']); - request.attributesConfig = defaultValue1; - const expectedHeaderRequestParams = `attributes_config=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.AttributesConfig() - ); - client.innerApiCalls.addCatalogAttribute = stubSimpleCall(expectedResponse); - const [response] = await client.addCatalogAttribute(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.addCatalogAttribute as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.addCatalogAttribute as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getAttributesConfig without error using callback', async () => { + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.GetAttributesConfigRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.GetAttributesConfigRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.AttributesConfig(), + ); + client.innerApiCalls.getAttributesConfig = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getAttributesConfig( + request, + ( + err?: Error | null, + result?: protos.google.cloud.retail.v2alpha.IAttributesConfig | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getAttributesConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getAttributesConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes addCatalogAttribute without error using callback', async () => { - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.AddCatalogAttributeRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.AddCatalogAttributeRequest', ['attributesConfig']); - request.attributesConfig = defaultValue1; - const expectedHeaderRequestParams = `attributes_config=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.AttributesConfig() - ); - client.innerApiCalls.addCatalogAttribute = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.addCatalogAttribute( - request, - (err?: Error|null, result?: protos.google.cloud.retail.v2alpha.IAttributesConfig|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.addCatalogAttribute as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.addCatalogAttribute as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getAttributesConfig with error', async () => { + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.GetAttributesConfigRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.GetAttributesConfigRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getAttributesConfig = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getAttributesConfig(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getAttributesConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getAttributesConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes addCatalogAttribute with error', async () => { - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.AddCatalogAttributeRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.AddCatalogAttributeRequest', ['attributesConfig']); - request.attributesConfig = defaultValue1; - const expectedHeaderRequestParams = `attributes_config=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.addCatalogAttribute = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.addCatalogAttribute(request), expectedError); - const actualRequest = (client.innerApiCalls.addCatalogAttribute as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.addCatalogAttribute as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getAttributesConfig with closed client', async () => { + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.GetAttributesConfigRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.GetAttributesConfigRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getAttributesConfig(request), expectedError); + }); + }); + + describe('updateAttributesConfig', () => { + it('invokes updateAttributesConfig without error', async () => { + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.UpdateAttributesConfigRequest(), + ); + request.attributesConfig ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.UpdateAttributesConfigRequest', + ['attributesConfig', 'name'], + ); + request.attributesConfig.name = defaultValue1; + const expectedHeaderRequestParams = `attributes_config.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.AttributesConfig(), + ); + client.innerApiCalls.updateAttributesConfig = + stubSimpleCall(expectedResponse); + const [response] = await client.updateAttributesConfig(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateAttributesConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateAttributesConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes addCatalogAttribute with closed client', async () => { - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.AddCatalogAttributeRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.AddCatalogAttributeRequest', ['attributesConfig']); - request.attributesConfig = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.addCatalogAttribute(request), expectedError); - }); + it('invokes updateAttributesConfig without error using callback', async () => { + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.UpdateAttributesConfigRequest(), + ); + request.attributesConfig ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.UpdateAttributesConfigRequest', + ['attributesConfig', 'name'], + ); + request.attributesConfig.name = defaultValue1; + const expectedHeaderRequestParams = `attributes_config.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.AttributesConfig(), + ); + client.innerApiCalls.updateAttributesConfig = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateAttributesConfig( + request, + ( + err?: Error | null, + result?: protos.google.cloud.retail.v2alpha.IAttributesConfig | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateAttributesConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateAttributesConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('removeCatalogAttribute', () => { - it('invokes removeCatalogAttribute without error', async () => { - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.RemoveCatalogAttributeRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.RemoveCatalogAttributeRequest', ['attributesConfig']); - request.attributesConfig = defaultValue1; - const expectedHeaderRequestParams = `attributes_config=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.AttributesConfig() - ); - client.innerApiCalls.removeCatalogAttribute = stubSimpleCall(expectedResponse); - const [response] = await client.removeCatalogAttribute(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.removeCatalogAttribute as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.removeCatalogAttribute as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateAttributesConfig with error', async () => { + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.UpdateAttributesConfigRequest(), + ); + request.attributesConfig ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.UpdateAttributesConfigRequest', + ['attributesConfig', 'name'], + ); + request.attributesConfig.name = defaultValue1; + const expectedHeaderRequestParams = `attributes_config.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateAttributesConfig = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.updateAttributesConfig(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.updateAttributesConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateAttributesConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes removeCatalogAttribute without error using callback', async () => { - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.RemoveCatalogAttributeRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.RemoveCatalogAttributeRequest', ['attributesConfig']); - request.attributesConfig = defaultValue1; - const expectedHeaderRequestParams = `attributes_config=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.AttributesConfig() - ); - client.innerApiCalls.removeCatalogAttribute = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.removeCatalogAttribute( - request, - (err?: Error|null, result?: protos.google.cloud.retail.v2alpha.IAttributesConfig|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.removeCatalogAttribute as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.removeCatalogAttribute as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateAttributesConfig with closed client', async () => { + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.UpdateAttributesConfigRequest(), + ); + request.attributesConfig ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.UpdateAttributesConfigRequest', + ['attributesConfig', 'name'], + ); + request.attributesConfig.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.updateAttributesConfig(request), + expectedError, + ); + }); + }); + + describe('addCatalogAttribute', () => { + it('invokes addCatalogAttribute without error', async () => { + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.AddCatalogAttributeRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.AddCatalogAttributeRequest', + ['attributesConfig'], + ); + request.attributesConfig = defaultValue1; + const expectedHeaderRequestParams = `attributes_config=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.AttributesConfig(), + ); + client.innerApiCalls.addCatalogAttribute = + stubSimpleCall(expectedResponse); + const [response] = await client.addCatalogAttribute(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.addCatalogAttribute as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.addCatalogAttribute as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes removeCatalogAttribute with error', async () => { - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.RemoveCatalogAttributeRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.RemoveCatalogAttributeRequest', ['attributesConfig']); - request.attributesConfig = defaultValue1; - const expectedHeaderRequestParams = `attributes_config=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.removeCatalogAttribute = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.removeCatalogAttribute(request), expectedError); - const actualRequest = (client.innerApiCalls.removeCatalogAttribute as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.removeCatalogAttribute as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes addCatalogAttribute without error using callback', async () => { + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.AddCatalogAttributeRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.AddCatalogAttributeRequest', + ['attributesConfig'], + ); + request.attributesConfig = defaultValue1; + const expectedHeaderRequestParams = `attributes_config=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.AttributesConfig(), + ); + client.innerApiCalls.addCatalogAttribute = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.addCatalogAttribute( + request, + ( + err?: Error | null, + result?: protos.google.cloud.retail.v2alpha.IAttributesConfig | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.addCatalogAttribute as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.addCatalogAttribute as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes removeCatalogAttribute with closed client', async () => { - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.RemoveCatalogAttributeRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.RemoveCatalogAttributeRequest', ['attributesConfig']); - request.attributesConfig = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.removeCatalogAttribute(request), expectedError); - }); + it('invokes addCatalogAttribute with error', async () => { + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.AddCatalogAttributeRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.AddCatalogAttributeRequest', + ['attributesConfig'], + ); + request.attributesConfig = defaultValue1; + const expectedHeaderRequestParams = `attributes_config=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.addCatalogAttribute = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.addCatalogAttribute(request), expectedError); + const actualRequest = ( + client.innerApiCalls.addCatalogAttribute as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.addCatalogAttribute as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('batchRemoveCatalogAttributes', () => { - it('invokes batchRemoveCatalogAttributes without error', async () => { - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.BatchRemoveCatalogAttributesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.BatchRemoveCatalogAttributesRequest', ['attributesConfig']); - request.attributesConfig = defaultValue1; - const expectedHeaderRequestParams = `attributes_config=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.BatchRemoveCatalogAttributesResponse() - ); - client.innerApiCalls.batchRemoveCatalogAttributes = stubSimpleCall(expectedResponse); - const [response] = await client.batchRemoveCatalogAttributes(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.batchRemoveCatalogAttributes as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.batchRemoveCatalogAttributes as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes addCatalogAttribute with closed client', async () => { + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.AddCatalogAttributeRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.AddCatalogAttributeRequest', + ['attributesConfig'], + ); + request.attributesConfig = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.addCatalogAttribute(request), expectedError); + }); + }); + + describe('removeCatalogAttribute', () => { + it('invokes removeCatalogAttribute without error', async () => { + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.RemoveCatalogAttributeRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.RemoveCatalogAttributeRequest', + ['attributesConfig'], + ); + request.attributesConfig = defaultValue1; + const expectedHeaderRequestParams = `attributes_config=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.AttributesConfig(), + ); + client.innerApiCalls.removeCatalogAttribute = + stubSimpleCall(expectedResponse); + const [response] = await client.removeCatalogAttribute(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.removeCatalogAttribute as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.removeCatalogAttribute as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes batchRemoveCatalogAttributes without error using callback', async () => { - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.BatchRemoveCatalogAttributesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.BatchRemoveCatalogAttributesRequest', ['attributesConfig']); - request.attributesConfig = defaultValue1; - const expectedHeaderRequestParams = `attributes_config=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.BatchRemoveCatalogAttributesResponse() - ); - client.innerApiCalls.batchRemoveCatalogAttributes = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.batchRemoveCatalogAttributes( - request, - (err?: Error|null, result?: protos.google.cloud.retail.v2alpha.IBatchRemoveCatalogAttributesResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.batchRemoveCatalogAttributes as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.batchRemoveCatalogAttributes as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes removeCatalogAttribute without error using callback', async () => { + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.RemoveCatalogAttributeRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.RemoveCatalogAttributeRequest', + ['attributesConfig'], + ); + request.attributesConfig = defaultValue1; + const expectedHeaderRequestParams = `attributes_config=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.AttributesConfig(), + ); + client.innerApiCalls.removeCatalogAttribute = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.removeCatalogAttribute( + request, + ( + err?: Error | null, + result?: protos.google.cloud.retail.v2alpha.IAttributesConfig | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.removeCatalogAttribute as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.removeCatalogAttribute as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes batchRemoveCatalogAttributes with error', async () => { - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.BatchRemoveCatalogAttributesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.BatchRemoveCatalogAttributesRequest', ['attributesConfig']); - request.attributesConfig = defaultValue1; - const expectedHeaderRequestParams = `attributes_config=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.batchRemoveCatalogAttributes = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.batchRemoveCatalogAttributes(request), expectedError); - const actualRequest = (client.innerApiCalls.batchRemoveCatalogAttributes as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.batchRemoveCatalogAttributes as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes removeCatalogAttribute with error', async () => { + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.RemoveCatalogAttributeRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.RemoveCatalogAttributeRequest', + ['attributesConfig'], + ); + request.attributesConfig = defaultValue1; + const expectedHeaderRequestParams = `attributes_config=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.removeCatalogAttribute = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.removeCatalogAttribute(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.removeCatalogAttribute as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.removeCatalogAttribute as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes batchRemoveCatalogAttributes with closed client', async () => { - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.BatchRemoveCatalogAttributesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.BatchRemoveCatalogAttributesRequest', ['attributesConfig']); - request.attributesConfig = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.batchRemoveCatalogAttributes(request), expectedError); - }); + it('invokes removeCatalogAttribute with closed client', async () => { + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.RemoveCatalogAttributeRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.RemoveCatalogAttributeRequest', + ['attributesConfig'], + ); + request.attributesConfig = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.removeCatalogAttribute(request), + expectedError, + ); + }); + }); + + describe('batchRemoveCatalogAttributes', () => { + it('invokes batchRemoveCatalogAttributes without error', async () => { + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.BatchRemoveCatalogAttributesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.BatchRemoveCatalogAttributesRequest', + ['attributesConfig'], + ); + request.attributesConfig = defaultValue1; + const expectedHeaderRequestParams = `attributes_config=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.BatchRemoveCatalogAttributesResponse(), + ); + client.innerApiCalls.batchRemoveCatalogAttributes = + stubSimpleCall(expectedResponse); + const [response] = await client.batchRemoveCatalogAttributes(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.batchRemoveCatalogAttributes as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.batchRemoveCatalogAttributes as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('replaceCatalogAttribute', () => { - it('invokes replaceCatalogAttribute without error', async () => { - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ReplaceCatalogAttributeRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ReplaceCatalogAttributeRequest', ['attributesConfig']); - request.attributesConfig = defaultValue1; - const expectedHeaderRequestParams = `attributes_config=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.AttributesConfig() - ); - client.innerApiCalls.replaceCatalogAttribute = stubSimpleCall(expectedResponse); - const [response] = await client.replaceCatalogAttribute(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.replaceCatalogAttribute as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.replaceCatalogAttribute as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes batchRemoveCatalogAttributes without error using callback', async () => { + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.BatchRemoveCatalogAttributesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.BatchRemoveCatalogAttributesRequest', + ['attributesConfig'], + ); + request.attributesConfig = defaultValue1; + const expectedHeaderRequestParams = `attributes_config=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.BatchRemoveCatalogAttributesResponse(), + ); + client.innerApiCalls.batchRemoveCatalogAttributes = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.batchRemoveCatalogAttributes( + request, + ( + err?: Error | null, + result?: protos.google.cloud.retail.v2alpha.IBatchRemoveCatalogAttributesResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.batchRemoveCatalogAttributes as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.batchRemoveCatalogAttributes as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes replaceCatalogAttribute without error using callback', async () => { - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ReplaceCatalogAttributeRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ReplaceCatalogAttributeRequest', ['attributesConfig']); - request.attributesConfig = defaultValue1; - const expectedHeaderRequestParams = `attributes_config=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.AttributesConfig() - ); - client.innerApiCalls.replaceCatalogAttribute = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.replaceCatalogAttribute( - request, - (err?: Error|null, result?: protos.google.cloud.retail.v2alpha.IAttributesConfig|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.replaceCatalogAttribute as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.replaceCatalogAttribute as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes batchRemoveCatalogAttributes with error', async () => { + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.BatchRemoveCatalogAttributesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.BatchRemoveCatalogAttributesRequest', + ['attributesConfig'], + ); + request.attributesConfig = defaultValue1; + const expectedHeaderRequestParams = `attributes_config=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.batchRemoveCatalogAttributes = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.batchRemoveCatalogAttributes(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.batchRemoveCatalogAttributes as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.batchRemoveCatalogAttributes as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes replaceCatalogAttribute with error', async () => { - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ReplaceCatalogAttributeRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ReplaceCatalogAttributeRequest', ['attributesConfig']); - request.attributesConfig = defaultValue1; - const expectedHeaderRequestParams = `attributes_config=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.replaceCatalogAttribute = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.replaceCatalogAttribute(request), expectedError); - const actualRequest = (client.innerApiCalls.replaceCatalogAttribute as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.replaceCatalogAttribute as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes batchRemoveCatalogAttributes with closed client', async () => { + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.BatchRemoveCatalogAttributesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.BatchRemoveCatalogAttributesRequest', + ['attributesConfig'], + ); + request.attributesConfig = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.batchRemoveCatalogAttributes(request), + expectedError, + ); + }); + }); + + describe('replaceCatalogAttribute', () => { + it('invokes replaceCatalogAttribute without error', async () => { + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ReplaceCatalogAttributeRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ReplaceCatalogAttributeRequest', + ['attributesConfig'], + ); + request.attributesConfig = defaultValue1; + const expectedHeaderRequestParams = `attributes_config=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.AttributesConfig(), + ); + client.innerApiCalls.replaceCatalogAttribute = + stubSimpleCall(expectedResponse); + const [response] = await client.replaceCatalogAttribute(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.replaceCatalogAttribute as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.replaceCatalogAttribute as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes replaceCatalogAttribute with closed client', async () => { - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ReplaceCatalogAttributeRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ReplaceCatalogAttributeRequest', ['attributesConfig']); - request.attributesConfig = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.replaceCatalogAttribute(request), expectedError); - }); + it('invokes replaceCatalogAttribute without error using callback', async () => { + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ReplaceCatalogAttributeRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ReplaceCatalogAttributeRequest', + ['attributesConfig'], + ); + request.attributesConfig = defaultValue1; + const expectedHeaderRequestParams = `attributes_config=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.AttributesConfig(), + ); + client.innerApiCalls.replaceCatalogAttribute = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.replaceCatalogAttribute( + request, + ( + err?: Error | null, + result?: protos.google.cloud.retail.v2alpha.IAttributesConfig | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.replaceCatalogAttribute as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.replaceCatalogAttribute as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('listCatalogs', () => { - it('invokes listCatalogs without error', async () => { - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ListCatalogsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ListCatalogsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.retail.v2alpha.Catalog()), - generateSampleMessage(new protos.google.cloud.retail.v2alpha.Catalog()), - generateSampleMessage(new protos.google.cloud.retail.v2alpha.Catalog()), - ]; - client.innerApiCalls.listCatalogs = stubSimpleCall(expectedResponse); - const [response] = await client.listCatalogs(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listCatalogs as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listCatalogs as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes replaceCatalogAttribute with error', async () => { + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ReplaceCatalogAttributeRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ReplaceCatalogAttributeRequest', + ['attributesConfig'], + ); + request.attributesConfig = defaultValue1; + const expectedHeaderRequestParams = `attributes_config=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.replaceCatalogAttribute = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.replaceCatalogAttribute(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.replaceCatalogAttribute as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.replaceCatalogAttribute as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listCatalogs without error using callback', async () => { - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ListCatalogsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ListCatalogsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.retail.v2alpha.Catalog()), - generateSampleMessage(new protos.google.cloud.retail.v2alpha.Catalog()), - generateSampleMessage(new protos.google.cloud.retail.v2alpha.Catalog()), - ]; - client.innerApiCalls.listCatalogs = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listCatalogs( - request, - (err?: Error|null, result?: protos.google.cloud.retail.v2alpha.ICatalog[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listCatalogs as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listCatalogs as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes replaceCatalogAttribute with closed client', async () => { + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ReplaceCatalogAttributeRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ReplaceCatalogAttributeRequest', + ['attributesConfig'], + ); + request.attributesConfig = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.replaceCatalogAttribute(request), + expectedError, + ); + }); + }); + + describe('listCatalogs', () => { + it('invokes listCatalogs without error', async () => { + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ListCatalogsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ListCatalogsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.retail.v2alpha.Catalog()), + generateSampleMessage(new protos.google.cloud.retail.v2alpha.Catalog()), + generateSampleMessage(new protos.google.cloud.retail.v2alpha.Catalog()), + ]; + client.innerApiCalls.listCatalogs = stubSimpleCall(expectedResponse); + const [response] = await client.listCatalogs(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listCatalogs as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listCatalogs as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listCatalogs with error', async () => { - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ListCatalogsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ListCatalogsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listCatalogs = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listCatalogs(request), expectedError); - const actualRequest = (client.innerApiCalls.listCatalogs as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listCatalogs as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listCatalogs without error using callback', async () => { + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ListCatalogsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ListCatalogsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.retail.v2alpha.Catalog()), + generateSampleMessage(new protos.google.cloud.retail.v2alpha.Catalog()), + generateSampleMessage(new protos.google.cloud.retail.v2alpha.Catalog()), + ]; + client.innerApiCalls.listCatalogs = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listCatalogs( + request, + ( + err?: Error | null, + result?: protos.google.cloud.retail.v2alpha.ICatalog[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listCatalogs as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listCatalogs as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listCatalogsStream without error', async () => { - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ListCatalogsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ListCatalogsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.retail.v2alpha.Catalog()), - generateSampleMessage(new protos.google.cloud.retail.v2alpha.Catalog()), - generateSampleMessage(new protos.google.cloud.retail.v2alpha.Catalog()), - ]; - client.descriptors.page.listCatalogs.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listCatalogsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.cloud.retail.v2alpha.Catalog[] = []; - stream.on('data', (response: protos.google.cloud.retail.v2alpha.Catalog) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.listCatalogs.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listCatalogs, request)); - assert( - (client.descriptors.page.listCatalogs.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listCatalogs with error', async () => { + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ListCatalogsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ListCatalogsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listCatalogs = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listCatalogs(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listCatalogs as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listCatalogs as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listCatalogsStream with error', async () => { - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ListCatalogsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ListCatalogsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listCatalogs.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listCatalogsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.cloud.retail.v2alpha.Catalog[] = []; - stream.on('data', (response: protos.google.cloud.retail.v2alpha.Catalog) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listCatalogs.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listCatalogs, request)); - assert( - (client.descriptors.page.listCatalogs.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listCatalogsStream without error', async () => { + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ListCatalogsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ListCatalogsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.retail.v2alpha.Catalog()), + generateSampleMessage(new protos.google.cloud.retail.v2alpha.Catalog()), + generateSampleMessage(new protos.google.cloud.retail.v2alpha.Catalog()), + ]; + client.descriptors.page.listCatalogs.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listCatalogsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.cloud.retail.v2alpha.Catalog[] = []; + stream.on( + 'data', + (response: protos.google.cloud.retail.v2alpha.Catalog) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listCatalogs.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listCatalogs, request), + ); + assert( + (client.descriptors.page.listCatalogs.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('uses async iteration with listCatalogs without error', async () => { - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ListCatalogsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ListCatalogsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.retail.v2alpha.Catalog()), - generateSampleMessage(new protos.google.cloud.retail.v2alpha.Catalog()), - generateSampleMessage(new protos.google.cloud.retail.v2alpha.Catalog()), - ]; - client.descriptors.page.listCatalogs.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.cloud.retail.v2alpha.ICatalog[] = []; - const iterable = client.listCatalogsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listCatalogs.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listCatalogs.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listCatalogsStream with error', async () => { + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ListCatalogsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ListCatalogsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listCatalogs.createStream = stubPageStreamingCall( + undefined, + expectedError, + ); + const stream = client.listCatalogsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.cloud.retail.v2alpha.Catalog[] = []; + stream.on( + 'data', + (response: protos.google.cloud.retail.v2alpha.Catalog) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listCatalogs.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listCatalogs, request), + ); + assert( + (client.descriptors.page.listCatalogs.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('uses async iteration with listCatalogs with error', async () => { - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ListCatalogsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ListCatalogsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listCatalogs.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listCatalogsAsync(request); - await assert.rejects(async () => { - const responses: protos.google.cloud.retail.v2alpha.ICatalog[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listCatalogs.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listCatalogs.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listCatalogs without error', async () => { + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ListCatalogsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ListCatalogsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.retail.v2alpha.Catalog()), + generateSampleMessage(new protos.google.cloud.retail.v2alpha.Catalog()), + generateSampleMessage(new protos.google.cloud.retail.v2alpha.Catalog()), + ]; + client.descriptors.page.listCatalogs.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.cloud.retail.v2alpha.ICatalog[] = []; + const iterable = client.listCatalogsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listCatalogs.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listCatalogs.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); }); - describe('Path templates', () => { - - describe('alertConfig', async () => { - const fakePath = "/rendered/path/alertConfig"; - const expectedParameters = { - project: "projectValue", - }; - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.alertConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.alertConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('alertConfigPath', () => { - const result = client.alertConfigPath("projectValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.alertConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromAlertConfigName', () => { - const result = client.matchProjectFromAlertConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.alertConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('uses async iteration with listCatalogs with error', async () => { + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ListCatalogsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ListCatalogsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listCatalogs.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listCatalogsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.cloud.retail.v2alpha.ICatalog[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listCatalogs.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listCatalogs.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + }); + + describe('Path templates', () => { + describe('alertConfig', async () => { + const fakePath = '/rendered/path/alertConfig'; + const expectedParameters = { + project: 'projectValue', + }; + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.alertConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.alertConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('alertConfigPath', () => { + const result = client.alertConfigPath('projectValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.alertConfigPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromAlertConfigName', () => { + const result = client.matchProjectFromAlertConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.alertConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('attributesConfig', async () => { - const fakePath = "/rendered/path/attributesConfig"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - }; - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.attributesConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.attributesConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('attributesConfigPath', () => { - const result = client.attributesConfigPath("projectValue", "locationValue", "catalogValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.attributesConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromAttributesConfigName', () => { - const result = client.matchProjectFromAttributesConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromAttributesConfigName', () => { - const result = client.matchLocationFromAttributesConfigName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromAttributesConfigName', () => { - const result = client.matchCatalogFromAttributesConfigName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('attributesConfig', async () => { + const fakePath = '/rendered/path/attributesConfig'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + }; + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.attributesConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.attributesConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('attributesConfigPath', () => { + const result = client.attributesConfigPath( + 'projectValue', + 'locationValue', + 'catalogValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.attributesConfigPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromAttributesConfigName', () => { + const result = client.matchProjectFromAttributesConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromAttributesConfigName', () => { + const result = client.matchLocationFromAttributesConfigName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromAttributesConfigName', () => { + const result = client.matchCatalogFromAttributesConfigName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('branch', async () => { - const fakePath = "/rendered/path/branch"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - branch: "branchValue", - }; - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.branchPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.branchPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('branchPath', () => { - const result = client.branchPath("projectValue", "locationValue", "catalogValue", "branchValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.branchPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromBranchName', () => { - const result = client.matchProjectFromBranchName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.branchPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromBranchName', () => { - const result = client.matchLocationFromBranchName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.branchPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromBranchName', () => { - const result = client.matchCatalogFromBranchName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.branchPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBranchFromBranchName', () => { - const result = client.matchBranchFromBranchName(fakePath); - assert.strictEqual(result, "branchValue"); - assert((client.pathTemplates.branchPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('branch', async () => { + const fakePath = '/rendered/path/branch'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + branch: 'branchValue', + }; + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.branchPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.branchPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('branchPath', () => { + const result = client.branchPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'branchValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.branchPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromBranchName', () => { + const result = client.matchProjectFromBranchName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.branchPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromBranchName', () => { + const result = client.matchLocationFromBranchName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.branchPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromBranchName', () => { + const result = client.matchCatalogFromBranchName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.branchPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBranchFromBranchName', () => { + const result = client.matchBranchFromBranchName(fakePath); + assert.strictEqual(result, 'branchValue'); + assert( + (client.pathTemplates.branchPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('catalog', async () => { - const fakePath = "/rendered/path/catalog"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - }; - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.catalogPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.catalogPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('catalogPath', () => { - const result = client.catalogPath("projectValue", "locationValue", "catalogValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.catalogPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromCatalogName', () => { - const result = client.matchProjectFromCatalogName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.catalogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromCatalogName', () => { - const result = client.matchLocationFromCatalogName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.catalogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromCatalogName', () => { - const result = client.matchCatalogFromCatalogName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.catalogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('catalog', async () => { + const fakePath = '/rendered/path/catalog'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + }; + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.catalogPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.catalogPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('catalogPath', () => { + const result = client.catalogPath( + 'projectValue', + 'locationValue', + 'catalogValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.catalogPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromCatalogName', () => { + const result = client.matchProjectFromCatalogName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.catalogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromCatalogName', () => { + const result = client.matchLocationFromCatalogName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.catalogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromCatalogName', () => { + const result = client.matchCatalogFromCatalogName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.catalogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('completionConfig', async () => { - const fakePath = "/rendered/path/completionConfig"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - }; - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.completionConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.completionConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('completionConfigPath', () => { - const result = client.completionConfigPath("projectValue", "locationValue", "catalogValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.completionConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromCompletionConfigName', () => { - const result = client.matchProjectFromCompletionConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.completionConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromCompletionConfigName', () => { - const result = client.matchLocationFromCompletionConfigName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.completionConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromCompletionConfigName', () => { - const result = client.matchCatalogFromCompletionConfigName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.completionConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('completionConfig', async () => { + const fakePath = '/rendered/path/completionConfig'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + }; + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.completionConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.completionConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('completionConfigPath', () => { + const result = client.completionConfigPath( + 'projectValue', + 'locationValue', + 'catalogValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.completionConfigPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromCompletionConfigName', () => { + const result = client.matchProjectFromCompletionConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.completionConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromCompletionConfigName', () => { + const result = client.matchLocationFromCompletionConfigName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.completionConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromCompletionConfigName', () => { + const result = client.matchCatalogFromCompletionConfigName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.completionConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('control', async () => { - const fakePath = "/rendered/path/control"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - control: "controlValue", - }; - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.controlPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.controlPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('controlPath', () => { - const result = client.controlPath("projectValue", "locationValue", "catalogValue", "controlValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.controlPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromControlName', () => { - const result = client.matchProjectFromControlName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.controlPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromControlName', () => { - const result = client.matchLocationFromControlName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.controlPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromControlName', () => { - const result = client.matchCatalogFromControlName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.controlPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchControlFromControlName', () => { - const result = client.matchControlFromControlName(fakePath); - assert.strictEqual(result, "controlValue"); - assert((client.pathTemplates.controlPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('control', async () => { + const fakePath = '/rendered/path/control'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + control: 'controlValue', + }; + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.controlPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.controlPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('controlPath', () => { + const result = client.controlPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'controlValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.controlPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromControlName', () => { + const result = client.matchProjectFromControlName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.controlPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromControlName', () => { + const result = client.matchLocationFromControlName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.controlPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromControlName', () => { + const result = client.matchCatalogFromControlName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.controlPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchControlFromControlName', () => { + const result = client.matchControlFromControlName(fakePath); + assert.strictEqual(result, 'controlValue'); + assert( + (client.pathTemplates.controlPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('location', async () => { - const fakePath = "/rendered/path/location"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - }; - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.locationPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.locationPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('locationPath', () => { - const result = client.locationPath("projectValue", "locationValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.locationPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromLocationName', () => { - const result = client.matchProjectFromLocationName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.locationPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromLocationName', () => { - const result = client.matchLocationFromLocationName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.locationPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('location', async () => { + const fakePath = '/rendered/path/location'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + }; + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.locationPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.locationPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('locationPath', () => { + const result = client.locationPath('projectValue', 'locationValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.locationPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromLocationName', () => { + const result = client.matchProjectFromLocationName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.locationPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromLocationName', () => { + const result = client.matchLocationFromLocationName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.locationPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('loggingConfig', async () => { - const fakePath = "/rendered/path/loggingConfig"; - const expectedParameters = { - project: "projectValue", - }; - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.loggingConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.loggingConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('loggingConfigPath', () => { - const result = client.loggingConfigPath("projectValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.loggingConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromLoggingConfigName', () => { - const result = client.matchProjectFromLoggingConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.loggingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('loggingConfig', async () => { + const fakePath = '/rendered/path/loggingConfig'; + const expectedParameters = { + project: 'projectValue', + }; + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.loggingConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.loggingConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('loggingConfigPath', () => { + const result = client.loggingConfigPath('projectValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.loggingConfigPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromLoggingConfigName', () => { + const result = client.matchProjectFromLoggingConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.loggingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('merchantCenterAccountLink', async () => { - const fakePath = "/rendered/path/merchantCenterAccountLink"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - merchant_center_account_link: "merchantCenterAccountLinkValue", - }; - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.merchantCenterAccountLinkPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.merchantCenterAccountLinkPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('merchantCenterAccountLinkPath', () => { - const result = client.merchantCenterAccountLinkPath("projectValue", "locationValue", "catalogValue", "merchantCenterAccountLinkValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromMerchantCenterAccountLinkName', () => { - const result = client.matchProjectFromMerchantCenterAccountLinkName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromMerchantCenterAccountLinkName', () => { - const result = client.matchLocationFromMerchantCenterAccountLinkName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromMerchantCenterAccountLinkName', () => { - const result = client.matchCatalogFromMerchantCenterAccountLinkName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName', () => { - const result = client.matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName(fakePath); - assert.strictEqual(result, "merchantCenterAccountLinkValue"); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('merchantCenterAccountLink', async () => { + const fakePath = '/rendered/path/merchantCenterAccountLink'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + merchant_center_account_link: 'merchantCenterAccountLinkValue', + }; + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.merchantCenterAccountLinkPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.merchantCenterAccountLinkPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('merchantCenterAccountLinkPath', () => { + const result = client.merchantCenterAccountLinkPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'merchantCenterAccountLinkValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromMerchantCenterAccountLinkName', () => { + const result = + client.matchProjectFromMerchantCenterAccountLinkName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromMerchantCenterAccountLinkName', () => { + const result = + client.matchLocationFromMerchantCenterAccountLinkName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromMerchantCenterAccountLinkName', () => { + const result = + client.matchCatalogFromMerchantCenterAccountLinkName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName', () => { + const result = + client.matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName( + fakePath, + ); + assert.strictEqual(result, 'merchantCenterAccountLinkValue'); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('model', async () => { - const fakePath = "/rendered/path/model"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - model: "modelValue", - }; - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.modelPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.modelPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('modelPath', () => { - const result = client.modelPath("projectValue", "locationValue", "catalogValue", "modelValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.modelPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromModelName', () => { - const result = client.matchProjectFromModelName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromModelName', () => { - const result = client.matchLocationFromModelName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromModelName', () => { - const result = client.matchCatalogFromModelName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchModelFromModelName', () => { - const result = client.matchModelFromModelName(fakePath); - assert.strictEqual(result, "modelValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('model', async () => { + const fakePath = '/rendered/path/model'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + model: 'modelValue', + }; + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.modelPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.modelPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('modelPath', () => { + const result = client.modelPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'modelValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.modelPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromModelName', () => { + const result = client.matchProjectFromModelName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromModelName', () => { + const result = client.matchLocationFromModelName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromModelName', () => { + const result = client.matchCatalogFromModelName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchModelFromModelName', () => { + const result = client.matchModelFromModelName(fakePath); + assert.strictEqual(result, 'modelValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('product', async () => { - const fakePath = "/rendered/path/product"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - branch: "branchValue", - product: "productValue", - }; - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.productPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.productPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('productPath', () => { - const result = client.productPath("projectValue", "locationValue", "catalogValue", "branchValue", "productValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.productPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProductName', () => { - const result = client.matchProjectFromProductName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromProductName', () => { - const result = client.matchLocationFromProductName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromProductName', () => { - const result = client.matchCatalogFromProductName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBranchFromProductName', () => { - const result = client.matchBranchFromProductName(fakePath); - assert.strictEqual(result, "branchValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchProductFromProductName', () => { - const result = client.matchProductFromProductName(fakePath); - assert.strictEqual(result, "productValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('product', async () => { + const fakePath = '/rendered/path/product'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + branch: 'branchValue', + product: 'productValue', + }; + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.productPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.productPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('productPath', () => { + const result = client.productPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'branchValue', + 'productValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.productPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProductName', () => { + const result = client.matchProjectFromProductName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromProductName', () => { + const result = client.matchLocationFromProductName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromProductName', () => { + const result = client.matchCatalogFromProductName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBranchFromProductName', () => { + const result = client.matchBranchFromProductName(fakePath); + assert.strictEqual(result, 'branchValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchProductFromProductName', () => { + const result = client.matchProductFromProductName(fakePath); + assert.strictEqual(result, 'productValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('retailProject', async () => { - const fakePath = "/rendered/path/retailProject"; - const expectedParameters = { - project: "projectValue", - }; - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.retailProjectPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.retailProjectPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('retailProjectPath', () => { - const result = client.retailProjectPath("projectValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.retailProjectPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromRetailProjectName', () => { - const result = client.matchProjectFromRetailProjectName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.retailProjectPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('retailProject', async () => { + const fakePath = '/rendered/path/retailProject'; + const expectedParameters = { + project: 'projectValue', + }; + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.retailProjectPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.retailProjectPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('retailProjectPath', () => { + const result = client.retailProjectPath('projectValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.retailProjectPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromRetailProjectName', () => { + const result = client.matchProjectFromRetailProjectName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.retailProjectPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('servingConfig', async () => { - const fakePath = "/rendered/path/servingConfig"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - serving_config: "servingConfigValue", - }; - const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.servingConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.servingConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('servingConfigPath', () => { - const result = client.servingConfigPath("projectValue", "locationValue", "catalogValue", "servingConfigValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.servingConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromServingConfigName', () => { - const result = client.matchProjectFromServingConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.servingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromServingConfigName', () => { - const result = client.matchLocationFromServingConfigName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.servingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromServingConfigName', () => { - const result = client.matchCatalogFromServingConfigName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.servingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServingConfigFromServingConfigName', () => { - const result = client.matchServingConfigFromServingConfigName(fakePath); - assert.strictEqual(result, "servingConfigValue"); - assert((client.pathTemplates.servingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('servingConfig', async () => { + const fakePath = '/rendered/path/servingConfig'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + serving_config: 'servingConfigValue', + }; + const client = new catalogserviceModule.v2alpha.CatalogServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.servingConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.servingConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('servingConfigPath', () => { + const result = client.servingConfigPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'servingConfigValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.servingConfigPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromServingConfigName', () => { + const result = client.matchProjectFromServingConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.servingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromServingConfigName', () => { + const result = client.matchLocationFromServingConfigName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.servingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromServingConfigName', () => { + const result = client.matchCatalogFromServingConfigName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.servingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServingConfigFromServingConfigName', () => { + const result = client.matchServingConfigFromServingConfigName(fakePath); + assert.strictEqual(result, 'servingConfigValue'); + assert( + (client.pathTemplates.servingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/core/generator/gapic-generator-typescript/baselines/retail/test/gapic_completion_service_v2alpha.ts.baseline b/core/generator/gapic-generator-typescript/baselines/retail/test/gapic_completion_service_v2alpha.ts.baseline index edb151f19161..770babc4b34e 100644 --- a/core/generator/gapic-generator-typescript/baselines/retail/test/gapic_completion_service_v2alpha.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/retail/test/gapic_completion_service_v2alpha.ts.baseline @@ -19,1037 +19,1434 @@ import * as protos from '../protos/protos'; import * as assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as completionserviceModule from '../src'; -import {protobuf, LROperation, operationsProtos} from 'google-gax'; +import { protobuf, LROperation, operationsProtos } from 'google-gax'; // Dynamically loaded proto JSON is needed to get the type information // to fill in default values for request objects -const root = protobuf.Root.fromJSON(require('../protos/protos.json')).resolveAll(); +const root = protobuf.Root.fromJSON( + require('../protos/protos.json'), +).resolveAll(); // eslint-disable-next-line @typescript-eslint/no-unused-vars function getTypeDefaultValue(typeName: string, fields: string[]) { - let type = root.lookupType(typeName) as protobuf.Type; - for (const field of fields.slice(0, -1)) { - type = type.fields[field]?.resolvedType as protobuf.Type; - } - return type.fields[fields[fields.length - 1]]?.defaultValue; + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type.fields[field]?.resolvedType as protobuf.Type; + } + return type.fields[fields[fields.length - 1]]?.defaultValue; } function generateSampleMessage(instance: T) { - const filledObject = (instance.constructor as typeof protobuf.Message) - .toObject(instance as protobuf.Message, {defaults: true}); - return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, { defaults: true }); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; } function stubSimpleCall(response?: ResponseType, error?: Error) { - return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); } -function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { - return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +function stubSimpleCallWithCallback( + response?: ResponseType, + error?: Error, +) { + return error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); } -function stubLongRunningCall(response?: ResponseType, callError?: Error, lroError?: Error) { - const innerStub = lroError ? sinon.stub().rejects(lroError) : sinon.stub().resolves([response]); - const mockOperation = { - promise: innerStub, - }; - return callError ? sinon.stub().rejects(callError) : sinon.stub().resolves([mockOperation]); +function stubLongRunningCall( + response?: ResponseType, + callError?: Error, + lroError?: Error, +) { + const innerStub = lroError + ? sinon.stub().rejects(lroError) + : sinon.stub().resolves([response]); + const mockOperation = { + promise: innerStub, + }; + return callError + ? sinon.stub().rejects(callError) + : sinon.stub().resolves([mockOperation]); } -function stubLongRunningCallWithCallback(response?: ResponseType, callError?: Error, lroError?: Error) { - const innerStub = lroError ? sinon.stub().rejects(lroError) : sinon.stub().resolves([response]); - const mockOperation = { - promise: innerStub, - }; - return callError ? sinon.stub().callsArgWith(2, callError) : sinon.stub().callsArgWith(2, null, mockOperation); +function stubLongRunningCallWithCallback( + response?: ResponseType, + callError?: Error, + lroError?: Error, +) { + const innerStub = lroError + ? sinon.stub().rejects(lroError) + : sinon.stub().resolves([response]); + const mockOperation = { + promise: innerStub, + }; + return callError + ? sinon.stub().callsArgWith(2, callError) + : sinon.stub().callsArgWith(2, null, mockOperation); } describe('v2alpha.CompletionServiceClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new completionserviceModule.v2alpha.CompletionServiceClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'retail.googleapis.com'); - }); - - it('has universeDomain', () => { - const client = new completionserviceModule.v2alpha.CompletionServiceClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = + new completionserviceModule.v2alpha.CompletionServiceClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'retail.googleapis.com'); + }); - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - it('throws DeprecationWarning if static servicePath is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const servicePath = completionserviceModule.v2alpha.CompletionServiceClient.servicePath; - assert.strictEqual(servicePath, 'retail.googleapis.com'); - assert(stub.called); - stub.restore(); - }); + it('has universeDomain', () => { + const client = + new completionserviceModule.v2alpha.CompletionServiceClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = completionserviceModule.v2alpha.CompletionServiceClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'retail.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new completionserviceModule.v2alpha.CompletionServiceClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'retail.example.com'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = + completionserviceModule.v2alpha.CompletionServiceClient.servicePath; + assert.strictEqual(servicePath, 'retail.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + completionserviceModule.v2alpha.CompletionServiceClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'retail.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = + new completionserviceModule.v2alpha.CompletionServiceClient({ + universeDomain: 'example.com', }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'retail.example.com'); + }); - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new completionserviceModule.v2alpha.CompletionServiceClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'retail.example.com'); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = + new completionserviceModule.v2alpha.CompletionServiceClient({ + universe_domain: 'example.com', }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'retail.example.com'); + }); - if (typeof process === 'object' && 'env' in process) { - describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { - it('sets apiEndpoint from environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new completionserviceModule.v2alpha.CompletionServiceClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'retail.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - - it('value configured in code has priority over environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new completionserviceModule.v2alpha.CompletionServiceClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'retail.configured.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { new completionserviceModule.v2alpha.CompletionServiceClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); + if (typeof process === 'object' && 'env' in process) { + describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { + it('sets apiEndpoint from environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = + new completionserviceModule.v2alpha.CompletionServiceClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'retail.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - it('has port', () => { - const port = completionserviceModule.v2alpha.CompletionServiceClient.port; - assert(port); - assert(typeof port === 'number'); + it('value configured in code has priority over environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = + new completionserviceModule.v2alpha.CompletionServiceClient({ + universeDomain: 'configured.example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'retail.configured.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - - it('should create a client with no option', () => { - const client = new completionserviceModule.v2alpha.CompletionServiceClient(); - assert(client); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new completionserviceModule.v2alpha.CompletionServiceClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); + }); - it('should create a client with gRPC fallback', () => { - const client = new completionserviceModule.v2alpha.CompletionServiceClient({ - fallback: true, - }); - assert(client); - }); + it('has port', () => { + const port = completionserviceModule.v2alpha.CompletionServiceClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('has initialize method and supports deferred initialization', async () => { - const client = new completionserviceModule.v2alpha.CompletionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.completionServiceStub, undefined); - await client.initialize(); - assert(client.completionServiceStub); - }); + it('should create a client with no option', () => { + const client = + new completionserviceModule.v2alpha.CompletionServiceClient(); + assert(client); + }); - it('has close method for the initialized client', done => { - const client = new completionserviceModule.v2alpha.CompletionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.completionServiceStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); + it('should create a client with gRPC fallback', () => { + const client = + new completionserviceModule.v2alpha.CompletionServiceClient({ + fallback: true, }); + assert(client); + }); - it('has close method for the non-initialized client', done => { - const client = new completionserviceModule.v2alpha.CompletionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.completionServiceStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); + it('has initialize method and supports deferred initialization', async () => { + const client = + new completionserviceModule.v2alpha.CompletionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + assert.strictEqual(client.completionServiceStub, undefined); + await client.initialize(); + assert(client.completionServiceStub); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new completionserviceModule.v2alpha.CompletionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + it('has close method for the initialized client', (done) => { + const client = + new completionserviceModule.v2alpha.CompletionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); - - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new completionserviceModule.v2alpha.CompletionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId((err?: Error|null, projectId?: string|null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } - }); - }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); + client.initialize().catch((err) => { + throw err; + }); + assert(client.completionServiceStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); }); - describe('completeQuery', () => { - it('invokes completeQuery without error', async () => { - const client = new completionserviceModule.v2alpha.CompletionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.CompleteQueryRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.CompleteQueryRequest', ['catalog']); - request.catalog = defaultValue1; - const expectedHeaderRequestParams = `catalog=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.CompleteQueryResponse() - ); - client.innerApiCalls.completeQuery = stubSimpleCall(expectedResponse); - const [response] = await client.completeQuery(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.completeQuery as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.completeQuery as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('has close method for the non-initialized client', (done) => { + const client = + new completionserviceModule.v2alpha.CompletionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); - - it('invokes completeQuery without error using callback', async () => { - const client = new completionserviceModule.v2alpha.CompletionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.CompleteQueryRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.CompleteQueryRequest', ['catalog']); - request.catalog = defaultValue1; - const expectedHeaderRequestParams = `catalog=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.CompleteQueryResponse() - ); - client.innerApiCalls.completeQuery = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.completeQuery( - request, - (err?: Error|null, result?: protos.google.cloud.retail.v2alpha.ICompleteQueryResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.completeQuery as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.completeQuery as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + assert.strictEqual(client.completionServiceStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes completeQuery with error', async () => { - const client = new completionserviceModule.v2alpha.CompletionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.CompleteQueryRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.CompleteQueryRequest', ['catalog']); - request.catalog = defaultValue1; - const expectedHeaderRequestParams = `catalog=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.completeQuery = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.completeQuery(request), expectedError); - const actualRequest = (client.innerApiCalls.completeQuery as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.completeQuery as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = + new completionserviceModule.v2alpha.CompletionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + }); - it('invokes completeQuery with closed client', async () => { - const client = new completionserviceModule.v2alpha.CompletionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.CompleteQueryRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.CompleteQueryRequest', ['catalog']); - request.catalog = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.completeQuery(request), expectedError); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = + new completionserviceModule.v2alpha.CompletionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } + }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); }); - - describe('importCompletionData', () => { - it('invokes importCompletionData without error', async () => { - const client = new completionserviceModule.v2alpha.CompletionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ImportCompletionDataRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ImportCompletionDataRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.importCompletionData = stubLongRunningCall(expectedResponse); - const [operation] = await client.importCompletionData(request); - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.importCompletionData as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.importCompletionData as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + describe('completeQuery', () => { + it('invokes completeQuery without error', async () => { + const client = + new completionserviceModule.v2alpha.CompletionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.CompleteQueryRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.CompleteQueryRequest', + ['catalog'], + ); + request.catalog = defaultValue1; + const expectedHeaderRequestParams = `catalog=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.CompleteQueryResponse(), + ); + client.innerApiCalls.completeQuery = stubSimpleCall(expectedResponse); + const [response] = await client.completeQuery(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.completeQuery as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.completeQuery as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes importCompletionData without error using callback', async () => { - const client = new completionserviceModule.v2alpha.CompletionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ImportCompletionDataRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ImportCompletionDataRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.importCompletionData = stubLongRunningCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.importCompletionData( - request, - (err?: Error|null, - result?: LROperation|null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const operation = await promise as LROperation; - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.importCompletionData as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.importCompletionData as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes completeQuery without error using callback', async () => { + const client = + new completionserviceModule.v2alpha.CompletionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.CompleteQueryRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.CompleteQueryRequest', + ['catalog'], + ); + request.catalog = defaultValue1; + const expectedHeaderRequestParams = `catalog=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.CompleteQueryResponse(), + ); + client.innerApiCalls.completeQuery = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.completeQuery( + request, + ( + err?: Error | null, + result?: protos.google.cloud.retail.v2alpha.ICompleteQueryResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.completeQuery as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.completeQuery as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes importCompletionData with call error', async () => { - const client = new completionserviceModule.v2alpha.CompletionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ImportCompletionDataRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ImportCompletionDataRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.importCompletionData = stubLongRunningCall(undefined, expectedError); - await assert.rejects(client.importCompletionData(request), expectedError); - const actualRequest = (client.innerApiCalls.importCompletionData as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.importCompletionData as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes completeQuery with error', async () => { + const client = + new completionserviceModule.v2alpha.CompletionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.CompleteQueryRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.CompleteQueryRequest', + ['catalog'], + ); + request.catalog = defaultValue1; + const expectedHeaderRequestParams = `catalog=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.completeQuery = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.completeQuery(request), expectedError); + const actualRequest = ( + client.innerApiCalls.completeQuery as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.completeQuery as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes importCompletionData with LRO error', async () => { - const client = new completionserviceModule.v2alpha.CompletionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ImportCompletionDataRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ImportCompletionDataRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.importCompletionData = stubLongRunningCall(undefined, undefined, expectedError); - const [operation] = await client.importCompletionData(request); - await assert.rejects(operation.promise(), expectedError); - const actualRequest = (client.innerApiCalls.importCompletionData as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.importCompletionData as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes completeQuery with closed client', async () => { + const client = + new completionserviceModule.v2alpha.CompletionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); - - it('invokes checkImportCompletionDataProgress without error', async () => { - const client = new completionserviceModule.v2alpha.CompletionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedResponse = generateSampleMessage( - new operationsProtos.google.longrunning.Operation() - ); - expectedResponse.name = 'test'; - expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; - expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')} - - client.operationsClient.getOperation = stubSimpleCall(expectedResponse); - const decodedOperation = await client.checkImportCompletionDataProgress(expectedResponse.name); - assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); - assert(decodedOperation.metadata); - assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.CompleteQueryRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.CompleteQueryRequest', + ['catalog'], + ); + request.catalog = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.completeQuery(request), expectedError); + }); + }); + + describe('importCompletionData', () => { + it('invokes importCompletionData without error', async () => { + const client = + new completionserviceModule.v2alpha.CompletionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ImportCompletionDataRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ImportCompletionDataRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.importCompletionData = + stubLongRunningCall(expectedResponse); + const [operation] = await client.importCompletionData(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.importCompletionData as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.importCompletionData as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkImportCompletionDataProgress with error', async () => { - const client = new completionserviceModule.v2alpha.CompletionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedError = new Error('expected'); - - client.operationsClient.getOperation = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.checkImportCompletionDataProgress(''), expectedError); - assert((client.operationsClient.getOperation as SinonStub) - .getCall(0)); + it('invokes importCompletionData without error using callback', async () => { + const client = + new completionserviceModule.v2alpha.CompletionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ImportCompletionDataRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ImportCompletionDataRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.importCompletionData = + stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.importCompletionData( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.cloud.retail.v2alpha.IImportCompletionDataResponse, + protos.google.cloud.retail.v2alpha.IImportMetadata + > | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const operation = (await promise) as LROperation< + protos.google.cloud.retail.v2alpha.IImportCompletionDataResponse, + protos.google.cloud.retail.v2alpha.IImportMetadata + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.importCompletionData as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.importCompletionData as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('Path templates', () => { - - describe('alertConfig', async () => { - const fakePath = "/rendered/path/alertConfig"; - const expectedParameters = { - project: "projectValue", - }; - const client = new completionserviceModule.v2alpha.CompletionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.alertConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.alertConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('alertConfigPath', () => { - const result = client.alertConfigPath("projectValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.alertConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromAlertConfigName', () => { - const result = client.matchProjectFromAlertConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.alertConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('invokes importCompletionData with call error', async () => { + const client = + new completionserviceModule.v2alpha.CompletionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ImportCompletionDataRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ImportCompletionDataRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.importCompletionData = stubLongRunningCall( + undefined, + expectedError, + ); + await assert.rejects(client.importCompletionData(request), expectedError); + const actualRequest = ( + client.innerApiCalls.importCompletionData as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.importCompletionData as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - describe('attributesConfig', async () => { - const fakePath = "/rendered/path/attributesConfig"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - }; - const client = new completionserviceModule.v2alpha.CompletionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.attributesConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.attributesConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('attributesConfigPath', () => { - const result = client.attributesConfigPath("projectValue", "locationValue", "catalogValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.attributesConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromAttributesConfigName', () => { - const result = client.matchProjectFromAttributesConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromAttributesConfigName', () => { - const result = client.matchLocationFromAttributesConfigName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromAttributesConfigName', () => { - const result = client.matchCatalogFromAttributesConfigName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('invokes importCompletionData with LRO error', async () => { + const client = + new completionserviceModule.v2alpha.CompletionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ImportCompletionDataRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ImportCompletionDataRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.importCompletionData = stubLongRunningCall( + undefined, + undefined, + expectedError, + ); + const [operation] = await client.importCompletionData(request); + await assert.rejects(operation.promise(), expectedError); + const actualRequest = ( + client.innerApiCalls.importCompletionData as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.importCompletionData as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - describe('branch', async () => { - const fakePath = "/rendered/path/branch"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - branch: "branchValue", - }; - const client = new completionserviceModule.v2alpha.CompletionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.branchPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.branchPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('branchPath', () => { - const result = client.branchPath("projectValue", "locationValue", "catalogValue", "branchValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.branchPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromBranchName', () => { - const result = client.matchProjectFromBranchName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.branchPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromBranchName', () => { - const result = client.matchLocationFromBranchName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.branchPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromBranchName', () => { - const result = client.matchCatalogFromBranchName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.branchPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBranchFromBranchName', () => { - const result = client.matchBranchFromBranchName(fakePath); - assert.strictEqual(result, "branchValue"); - assert((client.pathTemplates.branchPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('invokes checkImportCompletionDataProgress without error', async () => { + const client = + new completionserviceModule.v2alpha.CompletionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation(), + ); + expectedResponse.name = 'test'; + expectedResponse.response = { type_url: 'url', value: Buffer.from('') }; + expectedResponse.metadata = { type_url: 'url', value: Buffer.from('') }; + + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const decodedOperation = await client.checkImportCompletionDataProgress( + expectedResponse.name, + ); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); - describe('catalog', async () => { - const fakePath = "/rendered/path/catalog"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - }; - const client = new completionserviceModule.v2alpha.CompletionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.catalogPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.catalogPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('catalogPath', () => { - const result = client.catalogPath("projectValue", "locationValue", "catalogValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.catalogPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromCatalogName', () => { - const result = client.matchProjectFromCatalogName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.catalogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromCatalogName', () => { - const result = client.matchLocationFromCatalogName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.catalogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromCatalogName', () => { - const result = client.matchCatalogFromCatalogName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.catalogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('invokes checkImportCompletionDataProgress with error', async () => { + const client = + new completionserviceModule.v2alpha.CompletionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); - - describe('completionConfig', async () => { - const fakePath = "/rendered/path/completionConfig"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - }; - const client = new completionserviceModule.v2alpha.CompletionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.completionConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.completionConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('completionConfigPath', () => { - const result = client.completionConfigPath("projectValue", "locationValue", "catalogValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.completionConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromCompletionConfigName', () => { - const result = client.matchProjectFromCompletionConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.completionConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromCompletionConfigName', () => { - const result = client.matchLocationFromCompletionConfigName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.completionConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromCompletionConfigName', () => { - const result = client.matchCatalogFromCompletionConfigName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.completionConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + await client.initialize(); + const expectedError = new Error('expected'); + + client.operationsClient.getOperation = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.checkImportCompletionDataProgress(''), + expectedError, + ); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + }); + + describe('Path templates', () => { + describe('alertConfig', async () => { + const fakePath = '/rendered/path/alertConfig'; + const expectedParameters = { + project: 'projectValue', + }; + const client = + new completionserviceModule.v2alpha.CompletionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + client.pathTemplates.alertConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.alertConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('alertConfigPath', () => { + const result = client.alertConfigPath('projectValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.alertConfigPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromAlertConfigName', () => { + const result = client.matchProjectFromAlertConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.alertConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('control', async () => { - const fakePath = "/rendered/path/control"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - control: "controlValue", - }; - const client = new completionserviceModule.v2alpha.CompletionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.controlPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.controlPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('controlPath', () => { - const result = client.controlPath("projectValue", "locationValue", "catalogValue", "controlValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.controlPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromControlName', () => { - const result = client.matchProjectFromControlName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.controlPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromControlName', () => { - const result = client.matchLocationFromControlName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.controlPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromControlName', () => { - const result = client.matchCatalogFromControlName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.controlPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchControlFromControlName', () => { - const result = client.matchControlFromControlName(fakePath); - assert.strictEqual(result, "controlValue"); - assert((client.pathTemplates.controlPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('attributesConfig', async () => { + const fakePath = '/rendered/path/attributesConfig'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + }; + const client = + new completionserviceModule.v2alpha.CompletionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + client.pathTemplates.attributesConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.attributesConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('attributesConfigPath', () => { + const result = client.attributesConfigPath( + 'projectValue', + 'locationValue', + 'catalogValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.attributesConfigPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromAttributesConfigName', () => { + const result = client.matchProjectFromAttributesConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromAttributesConfigName', () => { + const result = client.matchLocationFromAttributesConfigName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromAttributesConfigName', () => { + const result = client.matchCatalogFromAttributesConfigName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('loggingConfig', async () => { - const fakePath = "/rendered/path/loggingConfig"; - const expectedParameters = { - project: "projectValue", - }; - const client = new completionserviceModule.v2alpha.CompletionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.loggingConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.loggingConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('loggingConfigPath', () => { - const result = client.loggingConfigPath("projectValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.loggingConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromLoggingConfigName', () => { - const result = client.matchProjectFromLoggingConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.loggingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('branch', async () => { + const fakePath = '/rendered/path/branch'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + branch: 'branchValue', + }; + const client = + new completionserviceModule.v2alpha.CompletionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + client.pathTemplates.branchPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.branchPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('branchPath', () => { + const result = client.branchPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'branchValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.branchPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromBranchName', () => { + const result = client.matchProjectFromBranchName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.branchPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromBranchName', () => { + const result = client.matchLocationFromBranchName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.branchPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromBranchName', () => { + const result = client.matchCatalogFromBranchName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.branchPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBranchFromBranchName', () => { + const result = client.matchBranchFromBranchName(fakePath); + assert.strictEqual(result, 'branchValue'); + assert( + (client.pathTemplates.branchPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('merchantCenterAccountLink', async () => { - const fakePath = "/rendered/path/merchantCenterAccountLink"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - merchant_center_account_link: "merchantCenterAccountLinkValue", - }; - const client = new completionserviceModule.v2alpha.CompletionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.merchantCenterAccountLinkPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.merchantCenterAccountLinkPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('merchantCenterAccountLinkPath', () => { - const result = client.merchantCenterAccountLinkPath("projectValue", "locationValue", "catalogValue", "merchantCenterAccountLinkValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromMerchantCenterAccountLinkName', () => { - const result = client.matchProjectFromMerchantCenterAccountLinkName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromMerchantCenterAccountLinkName', () => { - const result = client.matchLocationFromMerchantCenterAccountLinkName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromMerchantCenterAccountLinkName', () => { - const result = client.matchCatalogFromMerchantCenterAccountLinkName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName', () => { - const result = client.matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName(fakePath); - assert.strictEqual(result, "merchantCenterAccountLinkValue"); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('catalog', async () => { + const fakePath = '/rendered/path/catalog'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + }; + const client = + new completionserviceModule.v2alpha.CompletionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + client.pathTemplates.catalogPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.catalogPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('catalogPath', () => { + const result = client.catalogPath( + 'projectValue', + 'locationValue', + 'catalogValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.catalogPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromCatalogName', () => { + const result = client.matchProjectFromCatalogName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.catalogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromCatalogName', () => { + const result = client.matchLocationFromCatalogName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.catalogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromCatalogName', () => { + const result = client.matchCatalogFromCatalogName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.catalogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('model', async () => { - const fakePath = "/rendered/path/model"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - model: "modelValue", - }; - const client = new completionserviceModule.v2alpha.CompletionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.modelPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.modelPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('modelPath', () => { - const result = client.modelPath("projectValue", "locationValue", "catalogValue", "modelValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.modelPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromModelName', () => { - const result = client.matchProjectFromModelName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromModelName', () => { - const result = client.matchLocationFromModelName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromModelName', () => { - const result = client.matchCatalogFromModelName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchModelFromModelName', () => { - const result = client.matchModelFromModelName(fakePath); - assert.strictEqual(result, "modelValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('completionConfig', async () => { + const fakePath = '/rendered/path/completionConfig'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + }; + const client = + new completionserviceModule.v2alpha.CompletionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + client.pathTemplates.completionConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.completionConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('completionConfigPath', () => { + const result = client.completionConfigPath( + 'projectValue', + 'locationValue', + 'catalogValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.completionConfigPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromCompletionConfigName', () => { + const result = client.matchProjectFromCompletionConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.completionConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromCompletionConfigName', () => { + const result = client.matchLocationFromCompletionConfigName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.completionConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromCompletionConfigName', () => { + const result = client.matchCatalogFromCompletionConfigName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.completionConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('product', async () => { - const fakePath = "/rendered/path/product"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - branch: "branchValue", - product: "productValue", - }; - const client = new completionserviceModule.v2alpha.CompletionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.productPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.productPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('productPath', () => { - const result = client.productPath("projectValue", "locationValue", "catalogValue", "branchValue", "productValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.productPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProductName', () => { - const result = client.matchProjectFromProductName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromProductName', () => { - const result = client.matchLocationFromProductName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromProductName', () => { - const result = client.matchCatalogFromProductName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBranchFromProductName', () => { - const result = client.matchBranchFromProductName(fakePath); - assert.strictEqual(result, "branchValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchProductFromProductName', () => { - const result = client.matchProductFromProductName(fakePath); - assert.strictEqual(result, "productValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('control', async () => { + const fakePath = '/rendered/path/control'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + control: 'controlValue', + }; + const client = + new completionserviceModule.v2alpha.CompletionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + client.pathTemplates.controlPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.controlPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('controlPath', () => { + const result = client.controlPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'controlValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.controlPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromControlName', () => { + const result = client.matchProjectFromControlName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.controlPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromControlName', () => { + const result = client.matchLocationFromControlName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.controlPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromControlName', () => { + const result = client.matchCatalogFromControlName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.controlPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchControlFromControlName', () => { + const result = client.matchControlFromControlName(fakePath); + assert.strictEqual(result, 'controlValue'); + assert( + (client.pathTemplates.controlPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('retailProject', async () => { - const fakePath = "/rendered/path/retailProject"; - const expectedParameters = { - project: "projectValue", - }; - const client = new completionserviceModule.v2alpha.CompletionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.retailProjectPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.retailProjectPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('retailProjectPath', () => { - const result = client.retailProjectPath("projectValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.retailProjectPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromRetailProjectName', () => { - const result = client.matchProjectFromRetailProjectName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.retailProjectPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('loggingConfig', async () => { + const fakePath = '/rendered/path/loggingConfig'; + const expectedParameters = { + project: 'projectValue', + }; + const client = + new completionserviceModule.v2alpha.CompletionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + client.pathTemplates.loggingConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.loggingConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('loggingConfigPath', () => { + const result = client.loggingConfigPath('projectValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.loggingConfigPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromLoggingConfigName', () => { + const result = client.matchProjectFromLoggingConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.loggingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('servingConfig', async () => { - const fakePath = "/rendered/path/servingConfig"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - serving_config: "servingConfigValue", - }; - const client = new completionserviceModule.v2alpha.CompletionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.servingConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.servingConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('servingConfigPath', () => { - const result = client.servingConfigPath("projectValue", "locationValue", "catalogValue", "servingConfigValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.servingConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + describe('merchantCenterAccountLink', async () => { + const fakePath = '/rendered/path/merchantCenterAccountLink'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + merchant_center_account_link: 'merchantCenterAccountLinkValue', + }; + const client = + new completionserviceModule.v2alpha.CompletionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.merchantCenterAccountLinkPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.merchantCenterAccountLinkPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('merchantCenterAccountLinkPath', () => { + const result = client.merchantCenterAccountLinkPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'merchantCenterAccountLinkValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromMerchantCenterAccountLinkName', () => { + const result = + client.matchProjectFromMerchantCenterAccountLinkName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromMerchantCenterAccountLinkName', () => { + const result = + client.matchLocationFromMerchantCenterAccountLinkName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromMerchantCenterAccountLinkName', () => { + const result = + client.matchCatalogFromMerchantCenterAccountLinkName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName', () => { + const result = + client.matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName( + fakePath, + ); + assert.strictEqual(result, 'merchantCenterAccountLinkValue'); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchProjectFromServingConfigName', () => { - const result = client.matchProjectFromServingConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.servingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('model', async () => { + const fakePath = '/rendered/path/model'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + model: 'modelValue', + }; + const client = + new completionserviceModule.v2alpha.CompletionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.modelPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.modelPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('modelPath', () => { + const result = client.modelPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'modelValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.modelPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromModelName', () => { + const result = client.matchProjectFromModelName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromModelName', () => { + const result = client.matchLocationFromModelName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromModelName', () => { + const result = client.matchCatalogFromModelName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchModelFromModelName', () => { + const result = client.matchModelFromModelName(fakePath); + assert.strictEqual(result, 'modelValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchLocationFromServingConfigName', () => { - const result = client.matchLocationFromServingConfigName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.servingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('product', async () => { + const fakePath = '/rendered/path/product'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + branch: 'branchValue', + product: 'productValue', + }; + const client = + new completionserviceModule.v2alpha.CompletionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.productPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.productPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('productPath', () => { + const result = client.productPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'branchValue', + 'productValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.productPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProductName', () => { + const result = client.matchProjectFromProductName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromProductName', () => { + const result = client.matchLocationFromProductName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromProductName', () => { + const result = client.matchCatalogFromProductName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBranchFromProductName', () => { + const result = client.matchBranchFromProductName(fakePath); + assert.strictEqual(result, 'branchValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchProductFromProductName', () => { + const result = client.matchProductFromProductName(fakePath); + assert.strictEqual(result, 'productValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchCatalogFromServingConfigName', () => { - const result = client.matchCatalogFromServingConfigName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.servingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('retailProject', async () => { + const fakePath = '/rendered/path/retailProject'; + const expectedParameters = { + project: 'projectValue', + }; + const client = + new completionserviceModule.v2alpha.CompletionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.retailProjectPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.retailProjectPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('retailProjectPath', () => { + const result = client.retailProjectPath('projectValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.retailProjectPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromRetailProjectName', () => { + const result = client.matchProjectFromRetailProjectName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.retailProjectPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchServingConfigFromServingConfigName', () => { - const result = client.matchServingConfigFromServingConfigName(fakePath); - assert.strictEqual(result, "servingConfigValue"); - assert((client.pathTemplates.servingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('servingConfig', async () => { + const fakePath = '/rendered/path/servingConfig'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + serving_config: 'servingConfigValue', + }; + const client = + new completionserviceModule.v2alpha.CompletionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + client.pathTemplates.servingConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.servingConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('servingConfigPath', () => { + const result = client.servingConfigPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'servingConfigValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.servingConfigPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromServingConfigName', () => { + const result = client.matchProjectFromServingConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.servingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromServingConfigName', () => { + const result = client.matchLocationFromServingConfigName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.servingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromServingConfigName', () => { + const result = client.matchCatalogFromServingConfigName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.servingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServingConfigFromServingConfigName', () => { + const result = client.matchServingConfigFromServingConfigName(fakePath); + assert.strictEqual(result, 'servingConfigValue'); + assert( + (client.pathTemplates.servingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/core/generator/gapic-generator-typescript/baselines/retail/test/gapic_control_service_v2alpha.ts.baseline b/core/generator/gapic-generator-typescript/baselines/retail/test/gapic_control_service_v2alpha.ts.baseline index 6a4bf6b4b0ca..405749fcc72f 100644 --- a/core/generator/gapic-generator-typescript/baselines/retail/test/gapic_control_service_v2alpha.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/retail/test/gapic_control_service_v2alpha.ts.baseline @@ -19,1487 +19,1940 @@ import * as protos from '../protos/protos'; import * as assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as controlserviceModule from '../src'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; -import {protobuf} from 'google-gax'; +import { protobuf } from 'google-gax'; // Dynamically loaded proto JSON is needed to get the type information // to fill in default values for request objects -const root = protobuf.Root.fromJSON(require('../protos/protos.json')).resolveAll(); +const root = protobuf.Root.fromJSON( + require('../protos/protos.json'), +).resolveAll(); // eslint-disable-next-line @typescript-eslint/no-unused-vars function getTypeDefaultValue(typeName: string, fields: string[]) { - let type = root.lookupType(typeName) as protobuf.Type; - for (const field of fields.slice(0, -1)) { - type = type.fields[field]?.resolvedType as protobuf.Type; - } - return type.fields[fields[fields.length - 1]]?.defaultValue; + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type.fields[field]?.resolvedType as protobuf.Type; + } + return type.fields[fields[fields.length - 1]]?.defaultValue; } function generateSampleMessage(instance: T) { - const filledObject = (instance.constructor as typeof protobuf.Message) - .toObject(instance as protobuf.Message, {defaults: true}); - return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, { defaults: true }); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; } function stubSimpleCall(response?: ResponseType, error?: Error) { - return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); } -function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { - return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +function stubSimpleCallWithCallback( + response?: ResponseType, + error?: Error, +) { + return error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); } -function stubPageStreamingCall(responses?: ResponseType[], error?: Error) { - const pagingStub = sinon.stub(); - if (responses) { - for (let i = 0; i < responses.length; ++i) { - pagingStub.onCall(i).callsArgWith(2, null, responses[i]); - } +function stubPageStreamingCall( + responses?: ResponseType[], + error?: Error, +) { + const pagingStub = sinon.stub(); + if (responses) { + for (let i = 0; i < responses.length; ++i) { + pagingStub.onCall(i).callsArgWith(2, null, responses[i]); } - const transformStub = error ? sinon.stub().callsArgWith(2, error) : pagingStub; - const mockStream = new PassThrough({ - objectMode: true, - transform: transformStub, - }); - // trigger as many responses as needed - if (responses) { - for (let i = 0; i < responses.length; ++i) { - setImmediate(() => { mockStream.write({}); }); - } - setImmediate(() => { mockStream.end(); }); - } else { - setImmediate(() => { mockStream.write({}); }); - setImmediate(() => { mockStream.end(); }); + } + const transformStub = error + ? sinon.stub().callsArgWith(2, error) + : pagingStub; + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + // trigger as many responses as needed + if (responses) { + for (let i = 0; i < responses.length; ++i) { + setImmediate(() => { + mockStream.write({}); + }); } - return sinon.stub().returns(mockStream); + setImmediate(() => { + mockStream.end(); + }); + } else { + setImmediate(() => { + mockStream.write({}); + }); + setImmediate(() => { + mockStream.end(); + }); + } + return sinon.stub().returns(mockStream); } -function stubAsyncIterationCall(responses?: ResponseType[], error?: Error) { - let counter = 0; - const asyncIterable = { - [Symbol.asyncIterator]() { - return { - async next() { - if (error) { - return Promise.reject(error); - } - if (counter >= responses!.length) { - return Promise.resolve({done: true, value: undefined}); - } - return Promise.resolve({done: false, value: responses![counter++]}); - } - }; - } - }; - return sinon.stub().returns(asyncIterable); +function stubAsyncIterationCall( + responses?: ResponseType[], + error?: Error, +) { + let counter = 0; + const asyncIterable = { + [Symbol.asyncIterator]() { + return { + async next() { + if (error) { + return Promise.reject(error); + } + if (counter >= responses!.length) { + return Promise.resolve({ done: true, value: undefined }); + } + return Promise.resolve({ done: false, value: responses![counter++] }); + }, + }; + }, + }; + return sinon.stub().returns(asyncIterable); } describe('v2alpha.ControlServiceClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new controlserviceModule.v2alpha.ControlServiceClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'retail.googleapis.com'); - }); - - it('has universeDomain', () => { - const client = new controlserviceModule.v2alpha.ControlServiceClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); - - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - it('throws DeprecationWarning if static servicePath is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const servicePath = controlserviceModule.v2alpha.ControlServiceClient.servicePath; - assert.strictEqual(servicePath, 'retail.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = controlserviceModule.v2alpha.ControlServiceClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'retail.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new controlserviceModule.v2alpha.ControlServiceClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'retail.example.com'); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new controlserviceModule.v2alpha.ControlServiceClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'retail.googleapis.com'); + }); - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new controlserviceModule.v2alpha.ControlServiceClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'retail.example.com'); - }); + it('has universeDomain', () => { + const client = new controlserviceModule.v2alpha.ControlServiceClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - if (typeof process === 'object' && 'env' in process) { - describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { - it('sets apiEndpoint from environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new controlserviceModule.v2alpha.ControlServiceClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'retail.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - - it('value configured in code has priority over environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new controlserviceModule.v2alpha.ControlServiceClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'retail.configured.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { new controlserviceModule.v2alpha.ControlServiceClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = + controlserviceModule.v2alpha.ControlServiceClient.servicePath; + assert.strictEqual(servicePath, 'retail.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + controlserviceModule.v2alpha.ControlServiceClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'retail.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = new controlserviceModule.v2alpha.ControlServiceClient({ + universeDomain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'retail.example.com'); + }); - it('has port', () => { - const port = controlserviceModule.v2alpha.ControlServiceClient.port; - assert(port); - assert(typeof port === 'number'); - }); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = new controlserviceModule.v2alpha.ControlServiceClient({ + universe_domain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'retail.example.com'); + }); - it('should create a client with no option', () => { - const client = new controlserviceModule.v2alpha.ControlServiceClient(); - assert(client); + if (typeof process === 'object' && 'env' in process) { + describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { + it('sets apiEndpoint from environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = + new controlserviceModule.v2alpha.ControlServiceClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'retail.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - it('should create a client with gRPC fallback', () => { - const client = new controlserviceModule.v2alpha.ControlServiceClient({ - fallback: true, - }); - assert(client); + it('value configured in code has priority over environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new controlserviceModule.v2alpha.ControlServiceClient({ + universeDomain: 'configured.example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'retail.configured.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - - it('has initialize method and supports deferred initialization', async () => { - const client = new controlserviceModule.v2alpha.ControlServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.controlServiceStub, undefined); - await client.initialize(); - assert(client.controlServiceStub); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new controlserviceModule.v2alpha.ControlServiceClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); + }); - it('has close method for the initialized client', done => { - const client = new controlserviceModule.v2alpha.ControlServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.controlServiceStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('has port', () => { + const port = controlserviceModule.v2alpha.ControlServiceClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('has close method for the non-initialized client', done => { - const client = new controlserviceModule.v2alpha.ControlServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.controlServiceStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('should create a client with no option', () => { + const client = new controlserviceModule.v2alpha.ControlServiceClient(); + assert(client); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new controlserviceModule.v2alpha.ControlServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); - }); + it('should create a client with gRPC fallback', () => { + const client = new controlserviceModule.v2alpha.ControlServiceClient({ + fallback: true, + }); + assert(client); + }); - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new controlserviceModule.v2alpha.ControlServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId((err?: Error|null, projectId?: string|null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } - }); - }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); - }); + it('has initialize method and supports deferred initialization', async () => { + const client = new controlserviceModule.v2alpha.ControlServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.controlServiceStub, undefined); + await client.initialize(); + assert(client.controlServiceStub); }); - describe('createControl', () => { - it('invokes createControl without error', async () => { - const client = new controlserviceModule.v2alpha.ControlServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.CreateControlRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.CreateControlRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.Control() - ); - client.innerApiCalls.createControl = stubSimpleCall(expectedResponse); - const [response] = await client.createControl(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createControl as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createControl as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('has close method for the initialized client', (done) => { + const client = new controlserviceModule.v2alpha.ControlServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.controlServiceStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes createControl without error using callback', async () => { - const client = new controlserviceModule.v2alpha.ControlServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.CreateControlRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.CreateControlRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.Control() - ); - client.innerApiCalls.createControl = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createControl( - request, - (err?: Error|null, result?: protos.google.cloud.retail.v2alpha.IControl|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createControl as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createControl as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('has close method for the non-initialized client', (done) => { + const client = new controlserviceModule.v2alpha.ControlServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.controlServiceStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes createControl with error', async () => { - const client = new controlserviceModule.v2alpha.ControlServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.CreateControlRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.CreateControlRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createControl = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createControl(request), expectedError); - const actualRequest = (client.innerApiCalls.createControl as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createControl as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new controlserviceModule.v2alpha.ControlServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + }); - it('invokes createControl with closed client', async () => { - const client = new controlserviceModule.v2alpha.ControlServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.CreateControlRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.CreateControlRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createControl(request), expectedError); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new controlserviceModule.v2alpha.ControlServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + }); + + describe('createControl', () => { + it('invokes createControl without error', async () => { + const client = new controlserviceModule.v2alpha.ControlServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.CreateControlRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.CreateControlRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.Control(), + ); + client.innerApiCalls.createControl = stubSimpleCall(expectedResponse); + const [response] = await client.createControl(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createControl as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createControl as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('deleteControl', () => { - it('invokes deleteControl without error', async () => { - const client = new controlserviceModule.v2alpha.ControlServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.DeleteControlRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.DeleteControlRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteControl = stubSimpleCall(expectedResponse); - const [response] = await client.deleteControl(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteControl as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteControl as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createControl without error using callback', async () => { + const client = new controlserviceModule.v2alpha.ControlServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.CreateControlRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.CreateControlRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.Control(), + ); + client.innerApiCalls.createControl = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createControl( + request, + ( + err?: Error | null, + result?: protos.google.cloud.retail.v2alpha.IControl | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createControl as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createControl as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteControl without error using callback', async () => { - const client = new controlserviceModule.v2alpha.ControlServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.DeleteControlRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.DeleteControlRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteControl = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteControl( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteControl as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteControl as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createControl with error', async () => { + const client = new controlserviceModule.v2alpha.ControlServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.CreateControlRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.CreateControlRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createControl = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.createControl(request), expectedError); + const actualRequest = ( + client.innerApiCalls.createControl as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createControl as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteControl with error', async () => { - const client = new controlserviceModule.v2alpha.ControlServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.DeleteControlRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.DeleteControlRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteControl = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteControl(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteControl as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteControl as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createControl with closed client', async () => { + const client = new controlserviceModule.v2alpha.ControlServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.CreateControlRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.CreateControlRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.createControl(request), expectedError); + }); + }); + + describe('deleteControl', () => { + it('invokes deleteControl without error', async () => { + const client = new controlserviceModule.v2alpha.ControlServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.DeleteControlRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.DeleteControlRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteControl = stubSimpleCall(expectedResponse); + const [response] = await client.deleteControl(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteControl as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteControl as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteControl with closed client', async () => { - const client = new controlserviceModule.v2alpha.ControlServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.DeleteControlRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.DeleteControlRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteControl(request), expectedError); - }); + it('invokes deleteControl without error using callback', async () => { + const client = new controlserviceModule.v2alpha.ControlServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.DeleteControlRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.DeleteControlRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteControl = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteControl( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteControl as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteControl as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('updateControl', () => { - it('invokes updateControl without error', async () => { - const client = new controlserviceModule.v2alpha.ControlServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.UpdateControlRequest() - ); - request.control ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.UpdateControlRequest', ['control', 'name']); - request.control.name = defaultValue1; - const expectedHeaderRequestParams = `control.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.Control() - ); - client.innerApiCalls.updateControl = stubSimpleCall(expectedResponse); - const [response] = await client.updateControl(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateControl as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateControl as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteControl with error', async () => { + const client = new controlserviceModule.v2alpha.ControlServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.DeleteControlRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.DeleteControlRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteControl = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.deleteControl(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteControl as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteControl as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateControl without error using callback', async () => { - const client = new controlserviceModule.v2alpha.ControlServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.UpdateControlRequest() - ); - request.control ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.UpdateControlRequest', ['control', 'name']); - request.control.name = defaultValue1; - const expectedHeaderRequestParams = `control.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.Control() - ); - client.innerApiCalls.updateControl = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateControl( - request, - (err?: Error|null, result?: protos.google.cloud.retail.v2alpha.IControl|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateControl as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateControl as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteControl with closed client', async () => { + const client = new controlserviceModule.v2alpha.ControlServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.DeleteControlRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.DeleteControlRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.deleteControl(request), expectedError); + }); + }); + + describe('updateControl', () => { + it('invokes updateControl without error', async () => { + const client = new controlserviceModule.v2alpha.ControlServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.UpdateControlRequest(), + ); + request.control ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.UpdateControlRequest', + ['control', 'name'], + ); + request.control.name = defaultValue1; + const expectedHeaderRequestParams = `control.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.Control(), + ); + client.innerApiCalls.updateControl = stubSimpleCall(expectedResponse); + const [response] = await client.updateControl(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateControl as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateControl as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateControl with error', async () => { - const client = new controlserviceModule.v2alpha.ControlServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.UpdateControlRequest() - ); - request.control ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.UpdateControlRequest', ['control', 'name']); - request.control.name = defaultValue1; - const expectedHeaderRequestParams = `control.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateControl = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateControl(request), expectedError); - const actualRequest = (client.innerApiCalls.updateControl as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateControl as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateControl without error using callback', async () => { + const client = new controlserviceModule.v2alpha.ControlServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.UpdateControlRequest(), + ); + request.control ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.UpdateControlRequest', + ['control', 'name'], + ); + request.control.name = defaultValue1; + const expectedHeaderRequestParams = `control.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.Control(), + ); + client.innerApiCalls.updateControl = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateControl( + request, + ( + err?: Error | null, + result?: protos.google.cloud.retail.v2alpha.IControl | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateControl as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateControl as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateControl with closed client', async () => { - const client = new controlserviceModule.v2alpha.ControlServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.UpdateControlRequest() - ); - request.control ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.UpdateControlRequest', ['control', 'name']); - request.control.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateControl(request), expectedError); - }); + it('invokes updateControl with error', async () => { + const client = new controlserviceModule.v2alpha.ControlServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.UpdateControlRequest(), + ); + request.control ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.UpdateControlRequest', + ['control', 'name'], + ); + request.control.name = defaultValue1; + const expectedHeaderRequestParams = `control.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateControl = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.updateControl(request), expectedError); + const actualRequest = ( + client.innerApiCalls.updateControl as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateControl as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('getControl', () => { - it('invokes getControl without error', async () => { - const client = new controlserviceModule.v2alpha.ControlServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.GetControlRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.GetControlRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.Control() - ); - client.innerApiCalls.getControl = stubSimpleCall(expectedResponse); - const [response] = await client.getControl(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getControl as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getControl as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateControl with closed client', async () => { + const client = new controlserviceModule.v2alpha.ControlServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.UpdateControlRequest(), + ); + request.control ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.UpdateControlRequest', + ['control', 'name'], + ); + request.control.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.updateControl(request), expectedError); + }); + }); + + describe('getControl', () => { + it('invokes getControl without error', async () => { + const client = new controlserviceModule.v2alpha.ControlServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.GetControlRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.GetControlRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.Control(), + ); + client.innerApiCalls.getControl = stubSimpleCall(expectedResponse); + const [response] = await client.getControl(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getControl as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getControl as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getControl without error using callback', async () => { - const client = new controlserviceModule.v2alpha.ControlServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.GetControlRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.GetControlRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.Control() - ); - client.innerApiCalls.getControl = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getControl( - request, - (err?: Error|null, result?: protos.google.cloud.retail.v2alpha.IControl|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getControl as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getControl as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getControl without error using callback', async () => { + const client = new controlserviceModule.v2alpha.ControlServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.GetControlRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.GetControlRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.Control(), + ); + client.innerApiCalls.getControl = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getControl( + request, + ( + err?: Error | null, + result?: protos.google.cloud.retail.v2alpha.IControl | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getControl as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getControl as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getControl with error', async () => { - const client = new controlserviceModule.v2alpha.ControlServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.GetControlRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.GetControlRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getControl = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getControl(request), expectedError); - const actualRequest = (client.innerApiCalls.getControl as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getControl as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getControl with error', async () => { + const client = new controlserviceModule.v2alpha.ControlServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.GetControlRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.GetControlRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getControl = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getControl(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getControl as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getControl as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getControl with closed client', async () => { - const client = new controlserviceModule.v2alpha.ControlServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.GetControlRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.GetControlRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getControl(request), expectedError); - }); + it('invokes getControl with closed client', async () => { + const client = new controlserviceModule.v2alpha.ControlServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.GetControlRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.GetControlRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getControl(request), expectedError); + }); + }); + + describe('listControls', () => { + it('invokes listControls without error', async () => { + const client = new controlserviceModule.v2alpha.ControlServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ListControlsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ListControlsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.retail.v2alpha.Control()), + generateSampleMessage(new protos.google.cloud.retail.v2alpha.Control()), + generateSampleMessage(new protos.google.cloud.retail.v2alpha.Control()), + ]; + client.innerApiCalls.listControls = stubSimpleCall(expectedResponse); + const [response] = await client.listControls(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listControls as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listControls as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('listControls', () => { - it('invokes listControls without error', async () => { - const client = new controlserviceModule.v2alpha.ControlServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ListControlsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ListControlsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.retail.v2alpha.Control()), - generateSampleMessage(new protos.google.cloud.retail.v2alpha.Control()), - generateSampleMessage(new protos.google.cloud.retail.v2alpha.Control()), - ]; - client.innerApiCalls.listControls = stubSimpleCall(expectedResponse); - const [response] = await client.listControls(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listControls as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listControls as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listControls without error using callback', async () => { + const client = new controlserviceModule.v2alpha.ControlServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ListControlsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ListControlsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.retail.v2alpha.Control()), + generateSampleMessage(new protos.google.cloud.retail.v2alpha.Control()), + generateSampleMessage(new protos.google.cloud.retail.v2alpha.Control()), + ]; + client.innerApiCalls.listControls = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listControls( + request, + ( + err?: Error | null, + result?: protos.google.cloud.retail.v2alpha.IControl[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listControls as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listControls as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listControls without error using callback', async () => { - const client = new controlserviceModule.v2alpha.ControlServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ListControlsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ListControlsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.retail.v2alpha.Control()), - generateSampleMessage(new protos.google.cloud.retail.v2alpha.Control()), - generateSampleMessage(new protos.google.cloud.retail.v2alpha.Control()), - ]; - client.innerApiCalls.listControls = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listControls( - request, - (err?: Error|null, result?: protos.google.cloud.retail.v2alpha.IControl[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listControls as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listControls as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listControls with error', async () => { + const client = new controlserviceModule.v2alpha.ControlServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ListControlsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ListControlsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listControls = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listControls(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listControls as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listControls as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listControls with error', async () => { - const client = new controlserviceModule.v2alpha.ControlServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ListControlsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ListControlsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listControls = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listControls(request), expectedError); - const actualRequest = (client.innerApiCalls.listControls as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listControls as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes listControlsStream without error', async () => { + const client = new controlserviceModule.v2alpha.ControlServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ListControlsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ListControlsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.retail.v2alpha.Control()), + generateSampleMessage(new protos.google.cloud.retail.v2alpha.Control()), + generateSampleMessage(new protos.google.cloud.retail.v2alpha.Control()), + ]; + client.descriptors.page.listControls.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listControlsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.cloud.retail.v2alpha.Control[] = []; + stream.on( + 'data', + (response: protos.google.cloud.retail.v2alpha.Control) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); }); - - it('invokes listControlsStream without error', async () => { - const client = new controlserviceModule.v2alpha.ControlServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ListControlsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ListControlsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.retail.v2alpha.Control()), - generateSampleMessage(new protos.google.cloud.retail.v2alpha.Control()), - generateSampleMessage(new protos.google.cloud.retail.v2alpha.Control()), - ]; - client.descriptors.page.listControls.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listControlsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.cloud.retail.v2alpha.Control[] = []; - stream.on('data', (response: protos.google.cloud.retail.v2alpha.Control) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.listControls.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listControls, request)); - assert( - (client.descriptors.page.listControls.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); + stream.on('error', (err: Error) => { + reject(err); }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listControls.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listControls, request), + ); + assert( + (client.descriptors.page.listControls.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('invokes listControlsStream with error', async () => { - const client = new controlserviceModule.v2alpha.ControlServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ListControlsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ListControlsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listControls.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listControlsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.cloud.retail.v2alpha.Control[] = []; - stream.on('data', (response: protos.google.cloud.retail.v2alpha.Control) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listControls.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listControls, request)); - assert( - (client.descriptors.page.listControls.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); + it('invokes listControlsStream with error', async () => { + const client = new controlserviceModule.v2alpha.ControlServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ListControlsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ListControlsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listControls.createStream = stubPageStreamingCall( + undefined, + expectedError, + ); + const stream = client.listControlsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.cloud.retail.v2alpha.Control[] = []; + stream.on( + 'data', + (response: protos.google.cloud.retail.v2alpha.Control) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); }); - - it('uses async iteration with listControls without error', async () => { - const client = new controlserviceModule.v2alpha.ControlServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ListControlsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ListControlsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.retail.v2alpha.Control()), - generateSampleMessage(new protos.google.cloud.retail.v2alpha.Control()), - generateSampleMessage(new protos.google.cloud.retail.v2alpha.Control()), - ]; - client.descriptors.page.listControls.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.cloud.retail.v2alpha.IControl[] = []; - const iterable = client.listControlsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listControls.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listControls.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); + stream.on('error', (err: Error) => { + reject(err); }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listControls.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listControls, request), + ); + assert( + (client.descriptors.page.listControls.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('uses async iteration with listControls with error', async () => { - const client = new controlserviceModule.v2alpha.ControlServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ListControlsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ListControlsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listControls.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listControlsAsync(request); - await assert.rejects(async () => { - const responses: protos.google.cloud.retail.v2alpha.IControl[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listControls.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listControls.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listControls without error', async () => { + const client = new controlserviceModule.v2alpha.ControlServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ListControlsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ListControlsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.retail.v2alpha.Control()), + generateSampleMessage(new protos.google.cloud.retail.v2alpha.Control()), + generateSampleMessage(new protos.google.cloud.retail.v2alpha.Control()), + ]; + client.descriptors.page.listControls.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.cloud.retail.v2alpha.IControl[] = []; + const iterable = client.listControlsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listControls.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listControls.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); }); - describe('Path templates', () => { - - describe('alertConfig', async () => { - const fakePath = "/rendered/path/alertConfig"; - const expectedParameters = { - project: "projectValue", - }; - const client = new controlserviceModule.v2alpha.ControlServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.alertConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.alertConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('alertConfigPath', () => { - const result = client.alertConfigPath("projectValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.alertConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromAlertConfigName', () => { - const result = client.matchProjectFromAlertConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.alertConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('uses async iteration with listControls with error', async () => { + const client = new controlserviceModule.v2alpha.ControlServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ListControlsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ListControlsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listControls.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listControlsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.cloud.retail.v2alpha.IControl[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listControls.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listControls.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + }); + + describe('Path templates', () => { + describe('alertConfig', async () => { + const fakePath = '/rendered/path/alertConfig'; + const expectedParameters = { + project: 'projectValue', + }; + const client = new controlserviceModule.v2alpha.ControlServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.alertConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.alertConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('alertConfigPath', () => { + const result = client.alertConfigPath('projectValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.alertConfigPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromAlertConfigName', () => { + const result = client.matchProjectFromAlertConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.alertConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('attributesConfig', async () => { - const fakePath = "/rendered/path/attributesConfig"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - }; - const client = new controlserviceModule.v2alpha.ControlServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.attributesConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.attributesConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('attributesConfigPath', () => { - const result = client.attributesConfigPath("projectValue", "locationValue", "catalogValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.attributesConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromAttributesConfigName', () => { - const result = client.matchProjectFromAttributesConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromAttributesConfigName', () => { - const result = client.matchLocationFromAttributesConfigName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromAttributesConfigName', () => { - const result = client.matchCatalogFromAttributesConfigName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('attributesConfig', async () => { + const fakePath = '/rendered/path/attributesConfig'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + }; + const client = new controlserviceModule.v2alpha.ControlServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.attributesConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.attributesConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('attributesConfigPath', () => { + const result = client.attributesConfigPath( + 'projectValue', + 'locationValue', + 'catalogValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.attributesConfigPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromAttributesConfigName', () => { + const result = client.matchProjectFromAttributesConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromAttributesConfigName', () => { + const result = client.matchLocationFromAttributesConfigName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromAttributesConfigName', () => { + const result = client.matchCatalogFromAttributesConfigName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('branch', async () => { - const fakePath = "/rendered/path/branch"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - branch: "branchValue", - }; - const client = new controlserviceModule.v2alpha.ControlServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.branchPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.branchPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('branchPath', () => { - const result = client.branchPath("projectValue", "locationValue", "catalogValue", "branchValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.branchPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromBranchName', () => { - const result = client.matchProjectFromBranchName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.branchPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromBranchName', () => { - const result = client.matchLocationFromBranchName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.branchPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromBranchName', () => { - const result = client.matchCatalogFromBranchName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.branchPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBranchFromBranchName', () => { - const result = client.matchBranchFromBranchName(fakePath); - assert.strictEqual(result, "branchValue"); - assert((client.pathTemplates.branchPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('branch', async () => { + const fakePath = '/rendered/path/branch'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + branch: 'branchValue', + }; + const client = new controlserviceModule.v2alpha.ControlServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.branchPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.branchPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('branchPath', () => { + const result = client.branchPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'branchValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.branchPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromBranchName', () => { + const result = client.matchProjectFromBranchName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.branchPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromBranchName', () => { + const result = client.matchLocationFromBranchName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.branchPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromBranchName', () => { + const result = client.matchCatalogFromBranchName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.branchPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBranchFromBranchName', () => { + const result = client.matchBranchFromBranchName(fakePath); + assert.strictEqual(result, 'branchValue'); + assert( + (client.pathTemplates.branchPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('catalog', async () => { - const fakePath = "/rendered/path/catalog"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - }; - const client = new controlserviceModule.v2alpha.ControlServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.catalogPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.catalogPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('catalogPath', () => { - const result = client.catalogPath("projectValue", "locationValue", "catalogValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.catalogPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromCatalogName', () => { - const result = client.matchProjectFromCatalogName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.catalogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromCatalogName', () => { - const result = client.matchLocationFromCatalogName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.catalogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromCatalogName', () => { - const result = client.matchCatalogFromCatalogName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.catalogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('catalog', async () => { + const fakePath = '/rendered/path/catalog'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + }; + const client = new controlserviceModule.v2alpha.ControlServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.catalogPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.catalogPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('catalogPath', () => { + const result = client.catalogPath( + 'projectValue', + 'locationValue', + 'catalogValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.catalogPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromCatalogName', () => { + const result = client.matchProjectFromCatalogName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.catalogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromCatalogName', () => { + const result = client.matchLocationFromCatalogName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.catalogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromCatalogName', () => { + const result = client.matchCatalogFromCatalogName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.catalogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('completionConfig', async () => { - const fakePath = "/rendered/path/completionConfig"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - }; - const client = new controlserviceModule.v2alpha.ControlServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.completionConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.completionConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('completionConfigPath', () => { - const result = client.completionConfigPath("projectValue", "locationValue", "catalogValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.completionConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromCompletionConfigName', () => { - const result = client.matchProjectFromCompletionConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.completionConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromCompletionConfigName', () => { - const result = client.matchLocationFromCompletionConfigName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.completionConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromCompletionConfigName', () => { - const result = client.matchCatalogFromCompletionConfigName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.completionConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('completionConfig', async () => { + const fakePath = '/rendered/path/completionConfig'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + }; + const client = new controlserviceModule.v2alpha.ControlServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.completionConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.completionConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('completionConfigPath', () => { + const result = client.completionConfigPath( + 'projectValue', + 'locationValue', + 'catalogValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.completionConfigPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromCompletionConfigName', () => { + const result = client.matchProjectFromCompletionConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.completionConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromCompletionConfigName', () => { + const result = client.matchLocationFromCompletionConfigName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.completionConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromCompletionConfigName', () => { + const result = client.matchCatalogFromCompletionConfigName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.completionConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('control', async () => { - const fakePath = "/rendered/path/control"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - control: "controlValue", - }; - const client = new controlserviceModule.v2alpha.ControlServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.controlPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.controlPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('controlPath', () => { - const result = client.controlPath("projectValue", "locationValue", "catalogValue", "controlValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.controlPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromControlName', () => { - const result = client.matchProjectFromControlName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.controlPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromControlName', () => { - const result = client.matchLocationFromControlName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.controlPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromControlName', () => { - const result = client.matchCatalogFromControlName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.controlPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchControlFromControlName', () => { - const result = client.matchControlFromControlName(fakePath); - assert.strictEqual(result, "controlValue"); - assert((client.pathTemplates.controlPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('control', async () => { + const fakePath = '/rendered/path/control'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + control: 'controlValue', + }; + const client = new controlserviceModule.v2alpha.ControlServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.controlPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.controlPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('controlPath', () => { + const result = client.controlPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'controlValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.controlPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromControlName', () => { + const result = client.matchProjectFromControlName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.controlPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromControlName', () => { + const result = client.matchLocationFromControlName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.controlPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromControlName', () => { + const result = client.matchCatalogFromControlName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.controlPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchControlFromControlName', () => { + const result = client.matchControlFromControlName(fakePath); + assert.strictEqual(result, 'controlValue'); + assert( + (client.pathTemplates.controlPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('loggingConfig', async () => { - const fakePath = "/rendered/path/loggingConfig"; - const expectedParameters = { - project: "projectValue", - }; - const client = new controlserviceModule.v2alpha.ControlServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.loggingConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.loggingConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('loggingConfigPath', () => { - const result = client.loggingConfigPath("projectValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.loggingConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromLoggingConfigName', () => { - const result = client.matchProjectFromLoggingConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.loggingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('loggingConfig', async () => { + const fakePath = '/rendered/path/loggingConfig'; + const expectedParameters = { + project: 'projectValue', + }; + const client = new controlserviceModule.v2alpha.ControlServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.loggingConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.loggingConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('loggingConfigPath', () => { + const result = client.loggingConfigPath('projectValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.loggingConfigPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromLoggingConfigName', () => { + const result = client.matchProjectFromLoggingConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.loggingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('merchantCenterAccountLink', async () => { - const fakePath = "/rendered/path/merchantCenterAccountLink"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - merchant_center_account_link: "merchantCenterAccountLinkValue", - }; - const client = new controlserviceModule.v2alpha.ControlServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.merchantCenterAccountLinkPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.merchantCenterAccountLinkPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('merchantCenterAccountLinkPath', () => { - const result = client.merchantCenterAccountLinkPath("projectValue", "locationValue", "catalogValue", "merchantCenterAccountLinkValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromMerchantCenterAccountLinkName', () => { - const result = client.matchProjectFromMerchantCenterAccountLinkName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromMerchantCenterAccountLinkName', () => { - const result = client.matchLocationFromMerchantCenterAccountLinkName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromMerchantCenterAccountLinkName', () => { - const result = client.matchCatalogFromMerchantCenterAccountLinkName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName', () => { - const result = client.matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName(fakePath); - assert.strictEqual(result, "merchantCenterAccountLinkValue"); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('merchantCenterAccountLink', async () => { + const fakePath = '/rendered/path/merchantCenterAccountLink'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + merchant_center_account_link: 'merchantCenterAccountLinkValue', + }; + const client = new controlserviceModule.v2alpha.ControlServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.merchantCenterAccountLinkPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.merchantCenterAccountLinkPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('merchantCenterAccountLinkPath', () => { + const result = client.merchantCenterAccountLinkPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'merchantCenterAccountLinkValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromMerchantCenterAccountLinkName', () => { + const result = + client.matchProjectFromMerchantCenterAccountLinkName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromMerchantCenterAccountLinkName', () => { + const result = + client.matchLocationFromMerchantCenterAccountLinkName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromMerchantCenterAccountLinkName', () => { + const result = + client.matchCatalogFromMerchantCenterAccountLinkName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName', () => { + const result = + client.matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName( + fakePath, + ); + assert.strictEqual(result, 'merchantCenterAccountLinkValue'); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('model', async () => { - const fakePath = "/rendered/path/model"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - model: "modelValue", - }; - const client = new controlserviceModule.v2alpha.ControlServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.modelPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.modelPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('modelPath', () => { - const result = client.modelPath("projectValue", "locationValue", "catalogValue", "modelValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.modelPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromModelName', () => { - const result = client.matchProjectFromModelName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromModelName', () => { - const result = client.matchLocationFromModelName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromModelName', () => { - const result = client.matchCatalogFromModelName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchModelFromModelName', () => { - const result = client.matchModelFromModelName(fakePath); - assert.strictEqual(result, "modelValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('model', async () => { + const fakePath = '/rendered/path/model'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + model: 'modelValue', + }; + const client = new controlserviceModule.v2alpha.ControlServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.modelPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.modelPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('modelPath', () => { + const result = client.modelPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'modelValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.modelPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromModelName', () => { + const result = client.matchProjectFromModelName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromModelName', () => { + const result = client.matchLocationFromModelName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromModelName', () => { + const result = client.matchCatalogFromModelName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchModelFromModelName', () => { + const result = client.matchModelFromModelName(fakePath); + assert.strictEqual(result, 'modelValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('product', async () => { - const fakePath = "/rendered/path/product"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - branch: "branchValue", - product: "productValue", - }; - const client = new controlserviceModule.v2alpha.ControlServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.productPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.productPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('productPath', () => { - const result = client.productPath("projectValue", "locationValue", "catalogValue", "branchValue", "productValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.productPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProductName', () => { - const result = client.matchProjectFromProductName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromProductName', () => { - const result = client.matchLocationFromProductName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromProductName', () => { - const result = client.matchCatalogFromProductName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBranchFromProductName', () => { - const result = client.matchBranchFromProductName(fakePath); - assert.strictEqual(result, "branchValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchProductFromProductName', () => { - const result = client.matchProductFromProductName(fakePath); - assert.strictEqual(result, "productValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('product', async () => { + const fakePath = '/rendered/path/product'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + branch: 'branchValue', + product: 'productValue', + }; + const client = new controlserviceModule.v2alpha.ControlServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.productPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.productPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('productPath', () => { + const result = client.productPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'branchValue', + 'productValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.productPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProductName', () => { + const result = client.matchProjectFromProductName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromProductName', () => { + const result = client.matchLocationFromProductName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromProductName', () => { + const result = client.matchCatalogFromProductName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBranchFromProductName', () => { + const result = client.matchBranchFromProductName(fakePath); + assert.strictEqual(result, 'branchValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchProductFromProductName', () => { + const result = client.matchProductFromProductName(fakePath); + assert.strictEqual(result, 'productValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('retailProject', async () => { - const fakePath = "/rendered/path/retailProject"; - const expectedParameters = { - project: "projectValue", - }; - const client = new controlserviceModule.v2alpha.ControlServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.retailProjectPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.retailProjectPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('retailProjectPath', () => { - const result = client.retailProjectPath("projectValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.retailProjectPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromRetailProjectName', () => { - const result = client.matchProjectFromRetailProjectName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.retailProjectPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('retailProject', async () => { + const fakePath = '/rendered/path/retailProject'; + const expectedParameters = { + project: 'projectValue', + }; + const client = new controlserviceModule.v2alpha.ControlServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.retailProjectPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.retailProjectPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('retailProjectPath', () => { + const result = client.retailProjectPath('projectValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.retailProjectPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromRetailProjectName', () => { + const result = client.matchProjectFromRetailProjectName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.retailProjectPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('servingConfig', async () => { - const fakePath = "/rendered/path/servingConfig"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - serving_config: "servingConfigValue", - }; - const client = new controlserviceModule.v2alpha.ControlServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.servingConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.servingConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('servingConfigPath', () => { - const result = client.servingConfigPath("projectValue", "locationValue", "catalogValue", "servingConfigValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.servingConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromServingConfigName', () => { - const result = client.matchProjectFromServingConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.servingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromServingConfigName', () => { - const result = client.matchLocationFromServingConfigName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.servingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromServingConfigName', () => { - const result = client.matchCatalogFromServingConfigName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.servingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServingConfigFromServingConfigName', () => { - const result = client.matchServingConfigFromServingConfigName(fakePath); - assert.strictEqual(result, "servingConfigValue"); - assert((client.pathTemplates.servingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('servingConfig', async () => { + const fakePath = '/rendered/path/servingConfig'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + serving_config: 'servingConfigValue', + }; + const client = new controlserviceModule.v2alpha.ControlServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.servingConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.servingConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('servingConfigPath', () => { + const result = client.servingConfigPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'servingConfigValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.servingConfigPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromServingConfigName', () => { + const result = client.matchProjectFromServingConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.servingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromServingConfigName', () => { + const result = client.matchLocationFromServingConfigName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.servingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromServingConfigName', () => { + const result = client.matchCatalogFromServingConfigName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.servingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServingConfigFromServingConfigName', () => { + const result = client.matchServingConfigFromServingConfigName(fakePath); + assert.strictEqual(result, 'servingConfigValue'); + assert( + (client.pathTemplates.servingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/core/generator/gapic-generator-typescript/baselines/retail/test/gapic_conversational_search_service_v2alpha.ts.baseline b/core/generator/gapic-generator-typescript/baselines/retail/test/gapic_conversational_search_service_v2alpha.ts.baseline index 3723e2c2fbb0..056b679ed340 100644 --- a/core/generator/gapic-generator-typescript/baselines/retail/test/gapic_conversational_search_service_v2alpha.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/retail/test/gapic_conversational_search_service_v2alpha.ts.baseline @@ -19,905 +19,1311 @@ import * as protos from '../protos/protos'; import * as assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as conversationalsearchserviceModule from '../src'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; -import {protobuf} from 'google-gax'; +import { protobuf } from 'google-gax'; // Dynamically loaded proto JSON is needed to get the type information // to fill in default values for request objects -const root = protobuf.Root.fromJSON(require('../protos/protos.json')).resolveAll(); +const root = protobuf.Root.fromJSON( + require('../protos/protos.json'), +).resolveAll(); // eslint-disable-next-line @typescript-eslint/no-unused-vars function getTypeDefaultValue(typeName: string, fields: string[]) { - let type = root.lookupType(typeName) as protobuf.Type; - for (const field of fields.slice(0, -1)) { - type = type.fields[field]?.resolvedType as protobuf.Type; - } - return type.fields[fields[fields.length - 1]]?.defaultValue; + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type.fields[field]?.resolvedType as protobuf.Type; + } + return type.fields[fields[fields.length - 1]]?.defaultValue; } function generateSampleMessage(instance: T) { - const filledObject = (instance.constructor as typeof protobuf.Message) - .toObject(instance as protobuf.Message, {defaults: true}); - return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, { defaults: true }); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; } -function stubServerStreamingCall(response?: ResponseType, error?: Error) { - const transformStub = error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); - const mockStream = new PassThrough({ - objectMode: true, - transform: transformStub, - }); - // write something to the stream to trigger transformStub and send the response back to the client - setImmediate(() => { mockStream.write({}); }); - setImmediate(() => { mockStream.end(); }); - return sinon.stub().returns(mockStream); +function stubServerStreamingCall( + response?: ResponseType, + error?: Error, +) { + const transformStub = error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + // write something to the stream to trigger transformStub and send the response back to the client + setImmediate(() => { + mockStream.write({}); + }); + setImmediate(() => { + mockStream.end(); + }); + return sinon.stub().returns(mockStream); } describe('v2alpha.ConversationalSearchServiceClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'retail.googleapis.com'); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = + new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'retail.googleapis.com'); + }); - it('has universeDomain', () => { - const client = new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); + it('has universeDomain', () => { + const client = + new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - it('throws DeprecationWarning if static servicePath is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const servicePath = conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient.servicePath; - assert.strictEqual(servicePath, 'retail.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'retail.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'retail.example.com'); - }); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = + conversationalsearchserviceModule.v2alpha + .ConversationalSearchServiceClient.servicePath; + assert.strictEqual(servicePath, 'retail.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + conversationalsearchserviceModule.v2alpha + .ConversationalSearchServiceClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'retail.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = + new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient( + { universeDomain: 'example.com' }, + ); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'retail.example.com'); + }); - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'retail.example.com'); - }); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = + new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient( + { universe_domain: 'example.com' }, + ); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'retail.example.com'); + }); - if (typeof process === 'object' && 'env' in process) { - describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { - it('sets apiEndpoint from environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'retail.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - - it('value configured in code has priority over environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'retail.configured.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); + if (typeof process === 'object' && 'env' in process) { + describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { + it('sets apiEndpoint from environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = + new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'retail.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - it('has port', () => { - const port = conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient.port; - assert(port); - assert(typeof port === 'number'); + it('value configured in code has priority over environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = + new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient( + { universeDomain: 'configured.example.com' }, + ); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'retail.configured.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient( + { universe_domain: 'example.com', universeDomain: 'example.net' }, + ); + }); + }); - it('should create a client with no option', () => { - const client = new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient(); - assert(client); - }); + it('has port', () => { + const port = + conversationalsearchserviceModule.v2alpha + .ConversationalSearchServiceClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('should create a client with gRPC fallback', () => { - const client = new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient({ - fallback: true, - }); - assert(client); - }); + it('should create a client with no option', () => { + const client = + new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient(); + assert(client); + }); - it('has initialize method and supports deferred initialization', async () => { - const client = new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.conversationalSearchServiceStub, undefined); - await client.initialize(); - assert(client.conversationalSearchServiceStub); - }); + it('should create a client with gRPC fallback', () => { + const client = + new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient( + { + fallback: true, + }, + ); + assert(client); + }); - it('has close method for the initialized client', done => { - const client = new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.conversationalSearchServiceStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('has initialize method and supports deferred initialization', async () => { + const client = + new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + assert.strictEqual(client.conversationalSearchServiceStub, undefined); + await client.initialize(); + assert(client.conversationalSearchServiceStub); + }); - it('has close method for the non-initialized client', done => { - const client = new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.conversationalSearchServiceStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); + it('has close method for the initialized client', (done) => { + const client = + new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + client.initialize().catch((err) => { + throw err; + }); + assert(client.conversationalSearchServiceStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + it('has close method for the non-initialized client', (done) => { + const client = + new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + assert.strictEqual(client.conversationalSearchServiceStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId((err?: Error|null, projectId?: string|null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } - }); - }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); - }); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = + new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); }); - describe('conversationalSearch', () => { - it('invokes conversationalSearch without error', async () => { - const client = new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ConversationalSearchRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ConversationalSearchRequest', ['placement']); - request.placement = defaultValue1; - const expectedHeaderRequestParams = `placement=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ConversationalSearchResponse() - ); - client.innerApiCalls.conversationalSearch = stubServerStreamingCall(expectedResponse); - const stream = client.conversationalSearch(request); - const promise = new Promise((resolve, reject) => { - stream.on('data', (response: protos.google.cloud.retail.v2alpha.ConversationalSearchResponse) => { - resolve(response); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.conversationalSearch as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.conversationalSearch as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = + new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } }); - - it('invokes conversationalSearch without error and gaxServerStreamingRetries enabled', async () => { - const client = new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - gaxServerStreamingRetries: true - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ConversationalSearchRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ConversationalSearchRequest', ['placement']); - request.placement = defaultValue1; - const expectedHeaderRequestParams = `placement=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ConversationalSearchResponse() - ); - client.innerApiCalls.conversationalSearch = stubServerStreamingCall(expectedResponse); - const stream = client.conversationalSearch(request); - const promise = new Promise((resolve, reject) => { - stream.on('data', (response: protos.google.cloud.retail.v2alpha.ConversationalSearchResponse) => { - resolve(response); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.conversationalSearch as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.conversationalSearch as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + }); + + describe('conversationalSearch', () => { + it('invokes conversationalSearch without error', async () => { + const client = + new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ConversationalSearchRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ConversationalSearchRequest', + ['placement'], + ); + request.placement = defaultValue1; + const expectedHeaderRequestParams = `placement=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ConversationalSearchResponse(), + ); + client.innerApiCalls.conversationalSearch = + stubServerStreamingCall(expectedResponse); + const stream = client.conversationalSearch(request); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + ( + response: protos.google.cloud.retail.v2alpha.ConversationalSearchResponse, + ) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.conversationalSearch as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.conversationalSearch as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes conversationalSearch with error', async () => { - const client = new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ConversationalSearchRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ConversationalSearchRequest', ['placement']); - request.placement = defaultValue1; - const expectedHeaderRequestParams = `placement=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.conversationalSearch = stubServerStreamingCall(undefined, expectedError); - const stream = client.conversationalSearch(request); - const promise = new Promise((resolve, reject) => { - stream.on('data', (response: protos.google.cloud.retail.v2alpha.ConversationalSearchResponse) => { - resolve(response); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - const actualRequest = (client.innerApiCalls.conversationalSearch as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.conversationalSearch as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes conversationalSearch without error and gaxServerStreamingRetries enabled', async () => { + const client = + new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + gaxServerStreamingRetries: true, + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ConversationalSearchRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ConversationalSearchRequest', + ['placement'], + ); + request.placement = defaultValue1; + const expectedHeaderRequestParams = `placement=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ConversationalSearchResponse(), + ); + client.innerApiCalls.conversationalSearch = + stubServerStreamingCall(expectedResponse); + const stream = client.conversationalSearch(request); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + ( + response: protos.google.cloud.retail.v2alpha.ConversationalSearchResponse, + ) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.conversationalSearch as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.conversationalSearch as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes conversationalSearch with closed client', async () => { - const client = new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ConversationalSearchRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ConversationalSearchRequest', ['placement']); - request.placement = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - const stream = client.conversationalSearch(request, {retryRequestOptions: {noResponseRetries: 0}}); - const promise = new Promise((resolve, reject) => { - stream.on('data', (response: protos.google.cloud.retail.v2alpha.ConversationalSearchResponse) => { - resolve(response); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - }); - it('should create a client with gaxServerStreamingRetries enabled', () => { - const client = new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient({ - gaxServerStreamingRetries: true, - }); - assert(client); + it('invokes conversationalSearch with error', async () => { + const client = + new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ConversationalSearchRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ConversationalSearchRequest', + ['placement'], + ); + request.placement = defaultValue1; + const expectedHeaderRequestParams = `placement=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.conversationalSearch = stubServerStreamingCall( + undefined, + expectedError, + ); + const stream = client.conversationalSearch(request); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + ( + response: protos.google.cloud.retail.v2alpha.ConversationalSearchResponse, + ) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); }); + }); + await assert.rejects(promise, expectedError); + const actualRequest = ( + client.innerApiCalls.conversationalSearch as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.conversationalSearch as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('Path templates', () => { - - describe('alertConfig', async () => { - const fakePath = "/rendered/path/alertConfig"; - const expectedParameters = { - project: "projectValue", - }; - const client = new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.alertConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.alertConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('alertConfigPath', () => { - const result = client.alertConfigPath("projectValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.alertConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromAlertConfigName', () => { - const result = client.matchProjectFromAlertConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.alertConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('invokes conversationalSearch with closed client', async () => { + const client = + new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ConversationalSearchRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ConversationalSearchRequest', + ['placement'], + ); + request.placement = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + const stream = client.conversationalSearch(request, { + retryRequestOptions: { noResponseRetries: 0 }, + }); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + ( + response: protos.google.cloud.retail.v2alpha.ConversationalSearchResponse, + ) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); }); + }); + await assert.rejects(promise, expectedError); + }); + it('should create a client with gaxServerStreamingRetries enabled', () => { + const client = + new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient( + { + gaxServerStreamingRetries: true, + }, + ); + assert(client); + }); + }); + + describe('Path templates', () => { + describe('alertConfig', async () => { + const fakePath = '/rendered/path/alertConfig'; + const expectedParameters = { + project: 'projectValue', + }; + const client = + new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + client.pathTemplates.alertConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.alertConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('alertConfigPath', () => { + const result = client.alertConfigPath('projectValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.alertConfigPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromAlertConfigName', () => { + const result = client.matchProjectFromAlertConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.alertConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('attributesConfig', async () => { - const fakePath = "/rendered/path/attributesConfig"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - }; - const client = new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.attributesConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.attributesConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('attributesConfigPath', () => { - const result = client.attributesConfigPath("projectValue", "locationValue", "catalogValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.attributesConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromAttributesConfigName', () => { - const result = client.matchProjectFromAttributesConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromAttributesConfigName', () => { - const result = client.matchLocationFromAttributesConfigName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromAttributesConfigName', () => { - const result = client.matchCatalogFromAttributesConfigName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('attributesConfig', async () => { + const fakePath = '/rendered/path/attributesConfig'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + }; + const client = + new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + client.pathTemplates.attributesConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.attributesConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('attributesConfigPath', () => { + const result = client.attributesConfigPath( + 'projectValue', + 'locationValue', + 'catalogValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.attributesConfigPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromAttributesConfigName', () => { + const result = client.matchProjectFromAttributesConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromAttributesConfigName', () => { + const result = client.matchLocationFromAttributesConfigName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromAttributesConfigName', () => { + const result = client.matchCatalogFromAttributesConfigName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('branch', async () => { - const fakePath = "/rendered/path/branch"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - branch: "branchValue", - }; - const client = new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.branchPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.branchPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('branchPath', () => { - const result = client.branchPath("projectValue", "locationValue", "catalogValue", "branchValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.branchPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromBranchName', () => { - const result = client.matchProjectFromBranchName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.branchPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromBranchName', () => { - const result = client.matchLocationFromBranchName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.branchPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromBranchName', () => { - const result = client.matchCatalogFromBranchName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.branchPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBranchFromBranchName', () => { - const result = client.matchBranchFromBranchName(fakePath); - assert.strictEqual(result, "branchValue"); - assert((client.pathTemplates.branchPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('branch', async () => { + const fakePath = '/rendered/path/branch'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + branch: 'branchValue', + }; + const client = + new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + client.pathTemplates.branchPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.branchPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('branchPath', () => { + const result = client.branchPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'branchValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.branchPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromBranchName', () => { + const result = client.matchProjectFromBranchName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.branchPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromBranchName', () => { + const result = client.matchLocationFromBranchName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.branchPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromBranchName', () => { + const result = client.matchCatalogFromBranchName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.branchPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBranchFromBranchName', () => { + const result = client.matchBranchFromBranchName(fakePath); + assert.strictEqual(result, 'branchValue'); + assert( + (client.pathTemplates.branchPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('catalog', async () => { - const fakePath = "/rendered/path/catalog"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - }; - const client = new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.catalogPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.catalogPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('catalogPath', () => { - const result = client.catalogPath("projectValue", "locationValue", "catalogValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.catalogPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromCatalogName', () => { - const result = client.matchProjectFromCatalogName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.catalogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromCatalogName', () => { - const result = client.matchLocationFromCatalogName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.catalogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromCatalogName', () => { - const result = client.matchCatalogFromCatalogName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.catalogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('catalog', async () => { + const fakePath = '/rendered/path/catalog'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + }; + const client = + new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + client.pathTemplates.catalogPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.catalogPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('catalogPath', () => { + const result = client.catalogPath( + 'projectValue', + 'locationValue', + 'catalogValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.catalogPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromCatalogName', () => { + const result = client.matchProjectFromCatalogName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.catalogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromCatalogName', () => { + const result = client.matchLocationFromCatalogName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.catalogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromCatalogName', () => { + const result = client.matchCatalogFromCatalogName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.catalogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('completionConfig', async () => { - const fakePath = "/rendered/path/completionConfig"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - }; - const client = new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.completionConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.completionConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('completionConfigPath', () => { - const result = client.completionConfigPath("projectValue", "locationValue", "catalogValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.completionConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromCompletionConfigName', () => { - const result = client.matchProjectFromCompletionConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.completionConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromCompletionConfigName', () => { - const result = client.matchLocationFromCompletionConfigName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.completionConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromCompletionConfigName', () => { - const result = client.matchCatalogFromCompletionConfigName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.completionConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('completionConfig', async () => { + const fakePath = '/rendered/path/completionConfig'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + }; + const client = + new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + client.pathTemplates.completionConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.completionConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('completionConfigPath', () => { + const result = client.completionConfigPath( + 'projectValue', + 'locationValue', + 'catalogValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.completionConfigPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromCompletionConfigName', () => { + const result = client.matchProjectFromCompletionConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.completionConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromCompletionConfigName', () => { + const result = client.matchLocationFromCompletionConfigName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.completionConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromCompletionConfigName', () => { + const result = client.matchCatalogFromCompletionConfigName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.completionConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('control', async () => { - const fakePath = "/rendered/path/control"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - control: "controlValue", - }; - const client = new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.controlPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.controlPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('controlPath', () => { - const result = client.controlPath("projectValue", "locationValue", "catalogValue", "controlValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.controlPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromControlName', () => { - const result = client.matchProjectFromControlName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.controlPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromControlName', () => { - const result = client.matchLocationFromControlName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.controlPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromControlName', () => { - const result = client.matchCatalogFromControlName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.controlPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchControlFromControlName', () => { - const result = client.matchControlFromControlName(fakePath); - assert.strictEqual(result, "controlValue"); - assert((client.pathTemplates.controlPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('control', async () => { + const fakePath = '/rendered/path/control'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + control: 'controlValue', + }; + const client = + new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + client.pathTemplates.controlPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.controlPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('controlPath', () => { + const result = client.controlPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'controlValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.controlPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromControlName', () => { + const result = client.matchProjectFromControlName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.controlPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromControlName', () => { + const result = client.matchLocationFromControlName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.controlPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromControlName', () => { + const result = client.matchCatalogFromControlName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.controlPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchControlFromControlName', () => { + const result = client.matchControlFromControlName(fakePath); + assert.strictEqual(result, 'controlValue'); + assert( + (client.pathTemplates.controlPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('loggingConfig', async () => { - const fakePath = "/rendered/path/loggingConfig"; - const expectedParameters = { - project: "projectValue", - }; - const client = new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.loggingConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.loggingConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('loggingConfigPath', () => { - const result = client.loggingConfigPath("projectValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.loggingConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromLoggingConfigName', () => { - const result = client.matchProjectFromLoggingConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.loggingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('loggingConfig', async () => { + const fakePath = '/rendered/path/loggingConfig'; + const expectedParameters = { + project: 'projectValue', + }; + const client = + new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + client.pathTemplates.loggingConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.loggingConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('loggingConfigPath', () => { + const result = client.loggingConfigPath('projectValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.loggingConfigPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromLoggingConfigName', () => { + const result = client.matchProjectFromLoggingConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.loggingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('merchantCenterAccountLink', async () => { - const fakePath = "/rendered/path/merchantCenterAccountLink"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - merchant_center_account_link: "merchantCenterAccountLinkValue", - }; - const client = new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.merchantCenterAccountLinkPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.merchantCenterAccountLinkPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('merchantCenterAccountLinkPath', () => { - const result = client.merchantCenterAccountLinkPath("projectValue", "locationValue", "catalogValue", "merchantCenterAccountLinkValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromMerchantCenterAccountLinkName', () => { - const result = client.matchProjectFromMerchantCenterAccountLinkName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromMerchantCenterAccountLinkName', () => { - const result = client.matchLocationFromMerchantCenterAccountLinkName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromMerchantCenterAccountLinkName', () => { - const result = client.matchCatalogFromMerchantCenterAccountLinkName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName', () => { - const result = client.matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName(fakePath); - assert.strictEqual(result, "merchantCenterAccountLinkValue"); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('merchantCenterAccountLink', async () => { + const fakePath = '/rendered/path/merchantCenterAccountLink'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + merchant_center_account_link: 'merchantCenterAccountLinkValue', + }; + const client = + new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + client.pathTemplates.merchantCenterAccountLinkPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.merchantCenterAccountLinkPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('merchantCenterAccountLinkPath', () => { + const result = client.merchantCenterAccountLinkPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'merchantCenterAccountLinkValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromMerchantCenterAccountLinkName', () => { + const result = + client.matchProjectFromMerchantCenterAccountLinkName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromMerchantCenterAccountLinkName', () => { + const result = + client.matchLocationFromMerchantCenterAccountLinkName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromMerchantCenterAccountLinkName', () => { + const result = + client.matchCatalogFromMerchantCenterAccountLinkName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName', () => { + const result = + client.matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName( + fakePath, + ); + assert.strictEqual(result, 'merchantCenterAccountLinkValue'); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('model', async () => { - const fakePath = "/rendered/path/model"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - model: "modelValue", - }; - const client = new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.modelPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.modelPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('modelPath', () => { - const result = client.modelPath("projectValue", "locationValue", "catalogValue", "modelValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.modelPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromModelName', () => { - const result = client.matchProjectFromModelName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromModelName', () => { - const result = client.matchLocationFromModelName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromModelName', () => { - const result = client.matchCatalogFromModelName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchModelFromModelName', () => { - const result = client.matchModelFromModelName(fakePath); - assert.strictEqual(result, "modelValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('model', async () => { + const fakePath = '/rendered/path/model'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + model: 'modelValue', + }; + const client = + new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + client.pathTemplates.modelPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.modelPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('modelPath', () => { + const result = client.modelPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'modelValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.modelPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromModelName', () => { + const result = client.matchProjectFromModelName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromModelName', () => { + const result = client.matchLocationFromModelName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromModelName', () => { + const result = client.matchCatalogFromModelName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchModelFromModelName', () => { + const result = client.matchModelFromModelName(fakePath); + assert.strictEqual(result, 'modelValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('product', async () => { - const fakePath = "/rendered/path/product"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - branch: "branchValue", - product: "productValue", - }; - const client = new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.productPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.productPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('productPath', () => { - const result = client.productPath("projectValue", "locationValue", "catalogValue", "branchValue", "productValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.productPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProductName', () => { - const result = client.matchProjectFromProductName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromProductName', () => { - const result = client.matchLocationFromProductName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromProductName', () => { - const result = client.matchCatalogFromProductName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBranchFromProductName', () => { - const result = client.matchBranchFromProductName(fakePath); - assert.strictEqual(result, "branchValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchProductFromProductName', () => { - const result = client.matchProductFromProductName(fakePath); - assert.strictEqual(result, "productValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('product', async () => { + const fakePath = '/rendered/path/product'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + branch: 'branchValue', + product: 'productValue', + }; + const client = + new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + client.pathTemplates.productPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.productPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('productPath', () => { + const result = client.productPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'branchValue', + 'productValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.productPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProductName', () => { + const result = client.matchProjectFromProductName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromProductName', () => { + const result = client.matchLocationFromProductName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromProductName', () => { + const result = client.matchCatalogFromProductName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBranchFromProductName', () => { + const result = client.matchBranchFromProductName(fakePath); + assert.strictEqual(result, 'branchValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchProductFromProductName', () => { + const result = client.matchProductFromProductName(fakePath); + assert.strictEqual(result, 'productValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('retailProject', async () => { - const fakePath = "/rendered/path/retailProject"; - const expectedParameters = { - project: "projectValue", - }; - const client = new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.retailProjectPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.retailProjectPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('retailProjectPath', () => { - const result = client.retailProjectPath("projectValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.retailProjectPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromRetailProjectName', () => { - const result = client.matchProjectFromRetailProjectName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.retailProjectPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('retailProject', async () => { + const fakePath = '/rendered/path/retailProject'; + const expectedParameters = { + project: 'projectValue', + }; + const client = + new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + client.pathTemplates.retailProjectPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.retailProjectPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('retailProjectPath', () => { + const result = client.retailProjectPath('projectValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.retailProjectPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromRetailProjectName', () => { + const result = client.matchProjectFromRetailProjectName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.retailProjectPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('servingConfig', async () => { - const fakePath = "/rendered/path/servingConfig"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - serving_config: "servingConfigValue", - }; - const client = new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.servingConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.servingConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('servingConfigPath', () => { - const result = client.servingConfigPath("projectValue", "locationValue", "catalogValue", "servingConfigValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.servingConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromServingConfigName', () => { - const result = client.matchProjectFromServingConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.servingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromServingConfigName', () => { - const result = client.matchLocationFromServingConfigName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.servingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromServingConfigName', () => { - const result = client.matchCatalogFromServingConfigName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.servingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServingConfigFromServingConfigName', () => { - const result = client.matchServingConfigFromServingConfigName(fakePath); - assert.strictEqual(result, "servingConfigValue"); - assert((client.pathTemplates.servingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('servingConfig', async () => { + const fakePath = '/rendered/path/servingConfig'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + serving_config: 'servingConfigValue', + }; + const client = + new conversationalsearchserviceModule.v2alpha.ConversationalSearchServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + client.pathTemplates.servingConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.servingConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('servingConfigPath', () => { + const result = client.servingConfigPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'servingConfigValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.servingConfigPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromServingConfigName', () => { + const result = client.matchProjectFromServingConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.servingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromServingConfigName', () => { + const result = client.matchLocationFromServingConfigName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.servingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromServingConfigName', () => { + const result = client.matchCatalogFromServingConfigName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.servingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServingConfigFromServingConfigName', () => { + const result = client.matchServingConfigFromServingConfigName(fakePath); + assert.strictEqual(result, 'servingConfigValue'); + assert( + (client.pathTemplates.servingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/core/generator/gapic-generator-typescript/baselines/retail/test/gapic_generative_question_service_v2alpha.ts.baseline b/core/generator/gapic-generator-typescript/baselines/retail/test/gapic_generative_question_service_v2alpha.ts.baseline index c3531333f6d6..754591f11e4f 100644 --- a/core/generator/gapic-generator-typescript/baselines/retail/test/gapic_generative_question_service_v2alpha.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/retail/test/gapic_generative_question_service_v2alpha.ts.baseline @@ -19,1307 +19,1867 @@ import * as protos from '../protos/protos'; import * as assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as generativequestionserviceModule from '../src'; -import {protobuf} from 'google-gax'; +import { protobuf } from 'google-gax'; // Dynamically loaded proto JSON is needed to get the type information // to fill in default values for request objects -const root = protobuf.Root.fromJSON(require('../protos/protos.json')).resolveAll(); +const root = protobuf.Root.fromJSON( + require('../protos/protos.json'), +).resolveAll(); // eslint-disable-next-line @typescript-eslint/no-unused-vars function getTypeDefaultValue(typeName: string, fields: string[]) { - let type = root.lookupType(typeName) as protobuf.Type; - for (const field of fields.slice(0, -1)) { - type = type.fields[field]?.resolvedType as protobuf.Type; - } - return type.fields[fields[fields.length - 1]]?.defaultValue; + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type.fields[field]?.resolvedType as protobuf.Type; + } + return type.fields[fields[fields.length - 1]]?.defaultValue; } function generateSampleMessage(instance: T) { - const filledObject = (instance.constructor as typeof protobuf.Message) - .toObject(instance as protobuf.Message, {defaults: true}); - return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, { defaults: true }); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; } function stubSimpleCall(response?: ResponseType, error?: Error) { - return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); } -function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { - return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +function stubSimpleCallWithCallback( + response?: ResponseType, + error?: Error, +) { + return error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); } describe('v2alpha.GenerativeQuestionServiceClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'retail.googleapis.com'); - }); - - it('has universeDomain', () => { - const client = new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); - - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - it('throws DeprecationWarning if static servicePath is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const servicePath = generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient.servicePath; - assert.strictEqual(servicePath, 'retail.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'retail.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'retail.example.com'); - }); - - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'retail.example.com'); - }); - - if (typeof process === 'object' && 'env' in process) { - describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { - it('sets apiEndpoint from environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'retail.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - - it('value configured in code has priority over environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'retail.configured.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); - - it('has port', () => { - const port = generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient.port; - assert(port); - assert(typeof port === 'number'); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = + new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'retail.googleapis.com'); + }); - it('should create a client with no option', () => { - const client = new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient(); - assert(client); - }); + it('has universeDomain', () => { + const client = + new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - it('should create a client with gRPC fallback', () => { - const client = new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient({ - fallback: true, - }); - assert(client); - }); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = + generativequestionserviceModule.v2alpha + .GenerativeQuestionServiceClient.servicePath; + assert.strictEqual(servicePath, 'retail.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + generativequestionserviceModule.v2alpha + .GenerativeQuestionServiceClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'retail.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = + new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient( + { universeDomain: 'example.com' }, + ); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'retail.example.com'); + }); - it('has initialize method and supports deferred initialization', async () => { - const client = new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.generativeQuestionServiceStub, undefined); - await client.initialize(); - assert(client.generativeQuestionServiceStub); - }); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = + new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient( + { universe_domain: 'example.com' }, + ); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'retail.example.com'); + }); - it('has close method for the initialized client', done => { - const client = new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.generativeQuestionServiceStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); + if (typeof process === 'object' && 'env' in process) { + describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { + it('sets apiEndpoint from environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = + new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'retail.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - it('has close method for the non-initialized client', done => { - const client = new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.generativeQuestionServiceStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); + it('value configured in code has priority over environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = + new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient( + { universeDomain: 'configured.example.com' }, + ); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'retail.configured.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient( + { universe_domain: 'example.com', universeDomain: 'example.net' }, + ); + }); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); - }); + it('has port', () => { + const port = + generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient + .port; + assert(port); + assert(typeof port === 'number'); + }); - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId((err?: Error|null, projectId?: string|null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } - }); - }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); - }); + it('should create a client with no option', () => { + const client = + new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient(); + assert(client); }); - describe('updateGenerativeQuestionsFeatureConfig', () => { - it('invokes updateGenerativeQuestionsFeatureConfig without error', async () => { - const client = new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.UpdateGenerativeQuestionsFeatureConfigRequest() - ); - request.generativeQuestionsFeatureConfig ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.UpdateGenerativeQuestionsFeatureConfigRequest', ['generativeQuestionsFeatureConfig', 'catalog']); - request.generativeQuestionsFeatureConfig.catalog = defaultValue1; - const expectedHeaderRequestParams = `generative_questions_feature_config.catalog=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.GenerativeQuestionsFeatureConfig() - ); - client.innerApiCalls.updateGenerativeQuestionsFeatureConfig = stubSimpleCall(expectedResponse); - const [response] = await client.updateGenerativeQuestionsFeatureConfig(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateGenerativeQuestionsFeatureConfig as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateGenerativeQuestionsFeatureConfig as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('should create a client with gRPC fallback', () => { + const client = + new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient( + { + fallback: true, + }, + ); + assert(client); + }); - it('invokes updateGenerativeQuestionsFeatureConfig without error using callback', async () => { - const client = new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.UpdateGenerativeQuestionsFeatureConfigRequest() - ); - request.generativeQuestionsFeatureConfig ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.UpdateGenerativeQuestionsFeatureConfigRequest', ['generativeQuestionsFeatureConfig', 'catalog']); - request.generativeQuestionsFeatureConfig.catalog = defaultValue1; - const expectedHeaderRequestParams = `generative_questions_feature_config.catalog=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.GenerativeQuestionsFeatureConfig() - ); - client.innerApiCalls.updateGenerativeQuestionsFeatureConfig = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateGenerativeQuestionsFeatureConfig( - request, - (err?: Error|null, result?: protos.google.cloud.retail.v2alpha.IGenerativeQuestionsFeatureConfig|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateGenerativeQuestionsFeatureConfig as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateGenerativeQuestionsFeatureConfig as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has initialize method and supports deferred initialization', async () => { + const client = + new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + assert.strictEqual(client.generativeQuestionServiceStub, undefined); + await client.initialize(); + assert(client.generativeQuestionServiceStub); + }); - it('invokes updateGenerativeQuestionsFeatureConfig with error', async () => { - const client = new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.UpdateGenerativeQuestionsFeatureConfigRequest() - ); - request.generativeQuestionsFeatureConfig ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.UpdateGenerativeQuestionsFeatureConfigRequest', ['generativeQuestionsFeatureConfig', 'catalog']); - request.generativeQuestionsFeatureConfig.catalog = defaultValue1; - const expectedHeaderRequestParams = `generative_questions_feature_config.catalog=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateGenerativeQuestionsFeatureConfig = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateGenerativeQuestionsFeatureConfig(request), expectedError); - const actualRequest = (client.innerApiCalls.updateGenerativeQuestionsFeatureConfig as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateGenerativeQuestionsFeatureConfig as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('has close method for the initialized client', (done) => { + const client = + new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + client.initialize().catch((err) => { + throw err; + }); + assert(client.generativeQuestionServiceStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes updateGenerativeQuestionsFeatureConfig with closed client', async () => { - const client = new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.UpdateGenerativeQuestionsFeatureConfigRequest() - ); - request.generativeQuestionsFeatureConfig ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.UpdateGenerativeQuestionsFeatureConfigRequest', ['generativeQuestionsFeatureConfig', 'catalog']); - request.generativeQuestionsFeatureConfig.catalog = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateGenerativeQuestionsFeatureConfig(request), expectedError); + it('has close method for the non-initialized client', (done) => { + const client = + new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + assert.strictEqual(client.generativeQuestionServiceStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); }); - describe('getGenerativeQuestionsFeatureConfig', () => { - it('invokes getGenerativeQuestionsFeatureConfig without error', async () => { - const client = new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.GetGenerativeQuestionsFeatureConfigRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.GetGenerativeQuestionsFeatureConfigRequest', ['catalog']); - request.catalog = defaultValue1; - const expectedHeaderRequestParams = `catalog=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.GenerativeQuestionsFeatureConfig() - ); - client.innerApiCalls.getGenerativeQuestionsFeatureConfig = stubSimpleCall(expectedResponse); - const [response] = await client.getGenerativeQuestionsFeatureConfig(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getGenerativeQuestionsFeatureConfig as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getGenerativeQuestionsFeatureConfig as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = + new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + }); - it('invokes getGenerativeQuestionsFeatureConfig without error using callback', async () => { - const client = new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.GetGenerativeQuestionsFeatureConfigRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.GetGenerativeQuestionsFeatureConfigRequest', ['catalog']); - request.catalog = defaultValue1; - const expectedHeaderRequestParams = `catalog=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.GenerativeQuestionsFeatureConfig() - ); - client.innerApiCalls.getGenerativeQuestionsFeatureConfig = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getGenerativeQuestionsFeatureConfig( - request, - (err?: Error|null, result?: protos.google.cloud.retail.v2alpha.IGenerativeQuestionsFeatureConfig|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getGenerativeQuestionsFeatureConfig as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getGenerativeQuestionsFeatureConfig as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = + new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + }); + + describe('updateGenerativeQuestionsFeatureConfig', () => { + it('invokes updateGenerativeQuestionsFeatureConfig without error', async () => { + const client = + new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.UpdateGenerativeQuestionsFeatureConfigRequest(), + ); + request.generativeQuestionsFeatureConfig ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.UpdateGenerativeQuestionsFeatureConfigRequest', + ['generativeQuestionsFeatureConfig', 'catalog'], + ); + request.generativeQuestionsFeatureConfig.catalog = defaultValue1; + const expectedHeaderRequestParams = `generative_questions_feature_config.catalog=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.GenerativeQuestionsFeatureConfig(), + ); + client.innerApiCalls.updateGenerativeQuestionsFeatureConfig = + stubSimpleCall(expectedResponse); + const [response] = + await client.updateGenerativeQuestionsFeatureConfig(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateGenerativeQuestionsFeatureConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateGenerativeQuestionsFeatureConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getGenerativeQuestionsFeatureConfig with error', async () => { - const client = new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.GetGenerativeQuestionsFeatureConfigRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.GetGenerativeQuestionsFeatureConfigRequest', ['catalog']); - request.catalog = defaultValue1; - const expectedHeaderRequestParams = `catalog=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getGenerativeQuestionsFeatureConfig = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getGenerativeQuestionsFeatureConfig(request), expectedError); - const actualRequest = (client.innerApiCalls.getGenerativeQuestionsFeatureConfig as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getGenerativeQuestionsFeatureConfig as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateGenerativeQuestionsFeatureConfig without error using callback', async () => { + const client = + new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.UpdateGenerativeQuestionsFeatureConfigRequest(), + ); + request.generativeQuestionsFeatureConfig ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.UpdateGenerativeQuestionsFeatureConfigRequest', + ['generativeQuestionsFeatureConfig', 'catalog'], + ); + request.generativeQuestionsFeatureConfig.catalog = defaultValue1; + const expectedHeaderRequestParams = `generative_questions_feature_config.catalog=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.GenerativeQuestionsFeatureConfig(), + ); + client.innerApiCalls.updateGenerativeQuestionsFeatureConfig = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateGenerativeQuestionsFeatureConfig( + request, + ( + err?: Error | null, + result?: protos.google.cloud.retail.v2alpha.IGenerativeQuestionsFeatureConfig | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateGenerativeQuestionsFeatureConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateGenerativeQuestionsFeatureConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getGenerativeQuestionsFeatureConfig with closed client', async () => { - const client = new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.GetGenerativeQuestionsFeatureConfigRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.GetGenerativeQuestionsFeatureConfigRequest', ['catalog']); - request.catalog = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getGenerativeQuestionsFeatureConfig(request), expectedError); - }); + it('invokes updateGenerativeQuestionsFeatureConfig with error', async () => { + const client = + new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.UpdateGenerativeQuestionsFeatureConfigRequest(), + ); + request.generativeQuestionsFeatureConfig ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.UpdateGenerativeQuestionsFeatureConfigRequest', + ['generativeQuestionsFeatureConfig', 'catalog'], + ); + request.generativeQuestionsFeatureConfig.catalog = defaultValue1; + const expectedHeaderRequestParams = `generative_questions_feature_config.catalog=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateGenerativeQuestionsFeatureConfig = + stubSimpleCall(undefined, expectedError); + await assert.rejects( + client.updateGenerativeQuestionsFeatureConfig(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.updateGenerativeQuestionsFeatureConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateGenerativeQuestionsFeatureConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('listGenerativeQuestionConfigs', () => { - it('invokes listGenerativeQuestionConfigs without error', async () => { - const client = new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ListGenerativeQuestionConfigsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ListGenerativeQuestionConfigsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ListGenerativeQuestionConfigsResponse() - ); - client.innerApiCalls.listGenerativeQuestionConfigs = stubSimpleCall(expectedResponse); - const [response] = await client.listGenerativeQuestionConfigs(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listGenerativeQuestionConfigs as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listGenerativeQuestionConfigs as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateGenerativeQuestionsFeatureConfig with closed client', async () => { + const client = + new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.UpdateGenerativeQuestionsFeatureConfigRequest(), + ); + request.generativeQuestionsFeatureConfig ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.UpdateGenerativeQuestionsFeatureConfigRequest', + ['generativeQuestionsFeatureConfig', 'catalog'], + ); + request.generativeQuestionsFeatureConfig.catalog = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.updateGenerativeQuestionsFeatureConfig(request), + expectedError, + ); + }); + }); + + describe('getGenerativeQuestionsFeatureConfig', () => { + it('invokes getGenerativeQuestionsFeatureConfig without error', async () => { + const client = + new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.GetGenerativeQuestionsFeatureConfigRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.GetGenerativeQuestionsFeatureConfigRequest', + ['catalog'], + ); + request.catalog = defaultValue1; + const expectedHeaderRequestParams = `catalog=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.GenerativeQuestionsFeatureConfig(), + ); + client.innerApiCalls.getGenerativeQuestionsFeatureConfig = + stubSimpleCall(expectedResponse); + const [response] = + await client.getGenerativeQuestionsFeatureConfig(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getGenerativeQuestionsFeatureConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getGenerativeQuestionsFeatureConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listGenerativeQuestionConfigs without error using callback', async () => { - const client = new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ListGenerativeQuestionConfigsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ListGenerativeQuestionConfigsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ListGenerativeQuestionConfigsResponse() - ); - client.innerApiCalls.listGenerativeQuestionConfigs = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listGenerativeQuestionConfigs( - request, - (err?: Error|null, result?: protos.google.cloud.retail.v2alpha.IListGenerativeQuestionConfigsResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listGenerativeQuestionConfigs as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listGenerativeQuestionConfigs as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getGenerativeQuestionsFeatureConfig without error using callback', async () => { + const client = + new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.GetGenerativeQuestionsFeatureConfigRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.GetGenerativeQuestionsFeatureConfigRequest', + ['catalog'], + ); + request.catalog = defaultValue1; + const expectedHeaderRequestParams = `catalog=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.GenerativeQuestionsFeatureConfig(), + ); + client.innerApiCalls.getGenerativeQuestionsFeatureConfig = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getGenerativeQuestionsFeatureConfig( + request, + ( + err?: Error | null, + result?: protos.google.cloud.retail.v2alpha.IGenerativeQuestionsFeatureConfig | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getGenerativeQuestionsFeatureConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getGenerativeQuestionsFeatureConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listGenerativeQuestionConfigs with error', async () => { - const client = new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ListGenerativeQuestionConfigsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ListGenerativeQuestionConfigsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listGenerativeQuestionConfigs = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listGenerativeQuestionConfigs(request), expectedError); - const actualRequest = (client.innerApiCalls.listGenerativeQuestionConfigs as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listGenerativeQuestionConfigs as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getGenerativeQuestionsFeatureConfig with error', async () => { + const client = + new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.GetGenerativeQuestionsFeatureConfigRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.GetGenerativeQuestionsFeatureConfigRequest', + ['catalog'], + ); + request.catalog = defaultValue1; + const expectedHeaderRequestParams = `catalog=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getGenerativeQuestionsFeatureConfig = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.getGenerativeQuestionsFeatureConfig(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.getGenerativeQuestionsFeatureConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getGenerativeQuestionsFeatureConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listGenerativeQuestionConfigs with closed client', async () => { - const client = new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ListGenerativeQuestionConfigsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ListGenerativeQuestionConfigsRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.listGenerativeQuestionConfigs(request), expectedError); - }); + it('invokes getGenerativeQuestionsFeatureConfig with closed client', async () => { + const client = + new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.GetGenerativeQuestionsFeatureConfigRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.GetGenerativeQuestionsFeatureConfigRequest', + ['catalog'], + ); + request.catalog = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.getGenerativeQuestionsFeatureConfig(request), + expectedError, + ); + }); + }); + + describe('listGenerativeQuestionConfigs', () => { + it('invokes listGenerativeQuestionConfigs without error', async () => { + const client = + new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ListGenerativeQuestionConfigsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ListGenerativeQuestionConfigsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ListGenerativeQuestionConfigsResponse(), + ); + client.innerApiCalls.listGenerativeQuestionConfigs = + stubSimpleCall(expectedResponse); + const [response] = await client.listGenerativeQuestionConfigs(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listGenerativeQuestionConfigs as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listGenerativeQuestionConfigs as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('updateGenerativeQuestionConfig', () => { - it('invokes updateGenerativeQuestionConfig without error', async () => { - const client = new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.UpdateGenerativeQuestionConfigRequest() - ); - request.generativeQuestionConfig ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.UpdateGenerativeQuestionConfigRequest', ['generativeQuestionConfig', 'catalog']); - request.generativeQuestionConfig.catalog = defaultValue1; - const expectedHeaderRequestParams = `generative_question_config.catalog=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.GenerativeQuestionConfig() - ); - client.innerApiCalls.updateGenerativeQuestionConfig = stubSimpleCall(expectedResponse); - const [response] = await client.updateGenerativeQuestionConfig(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateGenerativeQuestionConfig as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateGenerativeQuestionConfig as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listGenerativeQuestionConfigs without error using callback', async () => { + const client = + new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ListGenerativeQuestionConfigsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ListGenerativeQuestionConfigsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ListGenerativeQuestionConfigsResponse(), + ); + client.innerApiCalls.listGenerativeQuestionConfigs = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listGenerativeQuestionConfigs( + request, + ( + err?: Error | null, + result?: protos.google.cloud.retail.v2alpha.IListGenerativeQuestionConfigsResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listGenerativeQuestionConfigs as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listGenerativeQuestionConfigs as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateGenerativeQuestionConfig without error using callback', async () => { - const client = new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.UpdateGenerativeQuestionConfigRequest() - ); - request.generativeQuestionConfig ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.UpdateGenerativeQuestionConfigRequest', ['generativeQuestionConfig', 'catalog']); - request.generativeQuestionConfig.catalog = defaultValue1; - const expectedHeaderRequestParams = `generative_question_config.catalog=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.GenerativeQuestionConfig() - ); - client.innerApiCalls.updateGenerativeQuestionConfig = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateGenerativeQuestionConfig( - request, - (err?: Error|null, result?: protos.google.cloud.retail.v2alpha.IGenerativeQuestionConfig|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateGenerativeQuestionConfig as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateGenerativeQuestionConfig as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listGenerativeQuestionConfigs with error', async () => { + const client = + new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ListGenerativeQuestionConfigsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ListGenerativeQuestionConfigsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listGenerativeQuestionConfigs = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.listGenerativeQuestionConfigs(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.listGenerativeQuestionConfigs as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listGenerativeQuestionConfigs as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateGenerativeQuestionConfig with error', async () => { - const client = new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.UpdateGenerativeQuestionConfigRequest() - ); - request.generativeQuestionConfig ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.UpdateGenerativeQuestionConfigRequest', ['generativeQuestionConfig', 'catalog']); - request.generativeQuestionConfig.catalog = defaultValue1; - const expectedHeaderRequestParams = `generative_question_config.catalog=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateGenerativeQuestionConfig = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateGenerativeQuestionConfig(request), expectedError); - const actualRequest = (client.innerApiCalls.updateGenerativeQuestionConfig as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateGenerativeQuestionConfig as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listGenerativeQuestionConfigs with closed client', async () => { + const client = + new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ListGenerativeQuestionConfigsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ListGenerativeQuestionConfigsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.listGenerativeQuestionConfigs(request), + expectedError, + ); + }); + }); + + describe('updateGenerativeQuestionConfig', () => { + it('invokes updateGenerativeQuestionConfig without error', async () => { + const client = + new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.UpdateGenerativeQuestionConfigRequest(), + ); + request.generativeQuestionConfig ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.UpdateGenerativeQuestionConfigRequest', + ['generativeQuestionConfig', 'catalog'], + ); + request.generativeQuestionConfig.catalog = defaultValue1; + const expectedHeaderRequestParams = `generative_question_config.catalog=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.GenerativeQuestionConfig(), + ); + client.innerApiCalls.updateGenerativeQuestionConfig = + stubSimpleCall(expectedResponse); + const [response] = await client.updateGenerativeQuestionConfig(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateGenerativeQuestionConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateGenerativeQuestionConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateGenerativeQuestionConfig with closed client', async () => { - const client = new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.UpdateGenerativeQuestionConfigRequest() - ); - request.generativeQuestionConfig ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.UpdateGenerativeQuestionConfigRequest', ['generativeQuestionConfig', 'catalog']); - request.generativeQuestionConfig.catalog = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateGenerativeQuestionConfig(request), expectedError); - }); + it('invokes updateGenerativeQuestionConfig without error using callback', async () => { + const client = + new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.UpdateGenerativeQuestionConfigRequest(), + ); + request.generativeQuestionConfig ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.UpdateGenerativeQuestionConfigRequest', + ['generativeQuestionConfig', 'catalog'], + ); + request.generativeQuestionConfig.catalog = defaultValue1; + const expectedHeaderRequestParams = `generative_question_config.catalog=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.GenerativeQuestionConfig(), + ); + client.innerApiCalls.updateGenerativeQuestionConfig = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateGenerativeQuestionConfig( + request, + ( + err?: Error | null, + result?: protos.google.cloud.retail.v2alpha.IGenerativeQuestionConfig | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateGenerativeQuestionConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateGenerativeQuestionConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('batchUpdateGenerativeQuestionConfigs', () => { - it('invokes batchUpdateGenerativeQuestionConfigs without error', async () => { - const client = new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.BatchUpdateGenerativeQuestionConfigsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.BatchUpdateGenerativeQuestionConfigsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.BatchUpdateGenerativeQuestionConfigsResponse() - ); - client.innerApiCalls.batchUpdateGenerativeQuestionConfigs = stubSimpleCall(expectedResponse); - const [response] = await client.batchUpdateGenerativeQuestionConfigs(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.batchUpdateGenerativeQuestionConfigs as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.batchUpdateGenerativeQuestionConfigs as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateGenerativeQuestionConfig with error', async () => { + const client = + new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.UpdateGenerativeQuestionConfigRequest(), + ); + request.generativeQuestionConfig ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.UpdateGenerativeQuestionConfigRequest', + ['generativeQuestionConfig', 'catalog'], + ); + request.generativeQuestionConfig.catalog = defaultValue1; + const expectedHeaderRequestParams = `generative_question_config.catalog=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateGenerativeQuestionConfig = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.updateGenerativeQuestionConfig(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.updateGenerativeQuestionConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateGenerativeQuestionConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes batchUpdateGenerativeQuestionConfigs without error using callback', async () => { - const client = new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.BatchUpdateGenerativeQuestionConfigsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.BatchUpdateGenerativeQuestionConfigsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.BatchUpdateGenerativeQuestionConfigsResponse() - ); - client.innerApiCalls.batchUpdateGenerativeQuestionConfigs = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.batchUpdateGenerativeQuestionConfigs( - request, - (err?: Error|null, result?: protos.google.cloud.retail.v2alpha.IBatchUpdateGenerativeQuestionConfigsResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.batchUpdateGenerativeQuestionConfigs as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.batchUpdateGenerativeQuestionConfigs as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateGenerativeQuestionConfig with closed client', async () => { + const client = + new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.UpdateGenerativeQuestionConfigRequest(), + ); + request.generativeQuestionConfig ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.UpdateGenerativeQuestionConfigRequest', + ['generativeQuestionConfig', 'catalog'], + ); + request.generativeQuestionConfig.catalog = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.updateGenerativeQuestionConfig(request), + expectedError, + ); + }); + }); + + describe('batchUpdateGenerativeQuestionConfigs', () => { + it('invokes batchUpdateGenerativeQuestionConfigs without error', async () => { + const client = + new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.BatchUpdateGenerativeQuestionConfigsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.BatchUpdateGenerativeQuestionConfigsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.BatchUpdateGenerativeQuestionConfigsResponse(), + ); + client.innerApiCalls.batchUpdateGenerativeQuestionConfigs = + stubSimpleCall(expectedResponse); + const [response] = + await client.batchUpdateGenerativeQuestionConfigs(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.batchUpdateGenerativeQuestionConfigs as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.batchUpdateGenerativeQuestionConfigs as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes batchUpdateGenerativeQuestionConfigs with error', async () => { - const client = new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.BatchUpdateGenerativeQuestionConfigsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.BatchUpdateGenerativeQuestionConfigsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.batchUpdateGenerativeQuestionConfigs = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.batchUpdateGenerativeQuestionConfigs(request), expectedError); - const actualRequest = (client.innerApiCalls.batchUpdateGenerativeQuestionConfigs as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.batchUpdateGenerativeQuestionConfigs as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes batchUpdateGenerativeQuestionConfigs without error using callback', async () => { + const client = + new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.BatchUpdateGenerativeQuestionConfigsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.BatchUpdateGenerativeQuestionConfigsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.BatchUpdateGenerativeQuestionConfigsResponse(), + ); + client.innerApiCalls.batchUpdateGenerativeQuestionConfigs = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.batchUpdateGenerativeQuestionConfigs( + request, + ( + err?: Error | null, + result?: protos.google.cloud.retail.v2alpha.IBatchUpdateGenerativeQuestionConfigsResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.batchUpdateGenerativeQuestionConfigs as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.batchUpdateGenerativeQuestionConfigs as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes batchUpdateGenerativeQuestionConfigs with closed client', async () => { - const client = new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.BatchUpdateGenerativeQuestionConfigsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.BatchUpdateGenerativeQuestionConfigsRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.batchUpdateGenerativeQuestionConfigs(request), expectedError); - }); + it('invokes batchUpdateGenerativeQuestionConfigs with error', async () => { + const client = + new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.BatchUpdateGenerativeQuestionConfigsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.BatchUpdateGenerativeQuestionConfigsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.batchUpdateGenerativeQuestionConfigs = + stubSimpleCall(undefined, expectedError); + await assert.rejects( + client.batchUpdateGenerativeQuestionConfigs(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.batchUpdateGenerativeQuestionConfigs as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.batchUpdateGenerativeQuestionConfigs as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('Path templates', () => { - - describe('alertConfig', async () => { - const fakePath = "/rendered/path/alertConfig"; - const expectedParameters = { - project: "projectValue", - }; - const client = new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.alertConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.alertConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('alertConfigPath', () => { - const result = client.alertConfigPath("projectValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.alertConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromAlertConfigName', () => { - const result = client.matchProjectFromAlertConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.alertConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('invokes batchUpdateGenerativeQuestionConfigs with closed client', async () => { + const client = + new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.BatchUpdateGenerativeQuestionConfigsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.BatchUpdateGenerativeQuestionConfigsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.batchUpdateGenerativeQuestionConfigs(request), + expectedError, + ); + }); + }); + + describe('Path templates', () => { + describe('alertConfig', async () => { + const fakePath = '/rendered/path/alertConfig'; + const expectedParameters = { + project: 'projectValue', + }; + const client = + new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + client.pathTemplates.alertConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.alertConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('alertConfigPath', () => { + const result = client.alertConfigPath('projectValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.alertConfigPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromAlertConfigName', () => { + const result = client.matchProjectFromAlertConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.alertConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('attributesConfig', async () => { - const fakePath = "/rendered/path/attributesConfig"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - }; - const client = new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.attributesConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.attributesConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('attributesConfigPath', () => { - const result = client.attributesConfigPath("projectValue", "locationValue", "catalogValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.attributesConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromAttributesConfigName', () => { - const result = client.matchProjectFromAttributesConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromAttributesConfigName', () => { - const result = client.matchLocationFromAttributesConfigName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromAttributesConfigName', () => { - const result = client.matchCatalogFromAttributesConfigName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('attributesConfig', async () => { + const fakePath = '/rendered/path/attributesConfig'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + }; + const client = + new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + client.pathTemplates.attributesConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.attributesConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('attributesConfigPath', () => { + const result = client.attributesConfigPath( + 'projectValue', + 'locationValue', + 'catalogValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.attributesConfigPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromAttributesConfigName', () => { + const result = client.matchProjectFromAttributesConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromAttributesConfigName', () => { + const result = client.matchLocationFromAttributesConfigName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromAttributesConfigName', () => { + const result = client.matchCatalogFromAttributesConfigName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('branch', async () => { - const fakePath = "/rendered/path/branch"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - branch: "branchValue", - }; - const client = new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.branchPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.branchPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('branchPath', () => { - const result = client.branchPath("projectValue", "locationValue", "catalogValue", "branchValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.branchPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromBranchName', () => { - const result = client.matchProjectFromBranchName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.branchPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromBranchName', () => { - const result = client.matchLocationFromBranchName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.branchPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromBranchName', () => { - const result = client.matchCatalogFromBranchName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.branchPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBranchFromBranchName', () => { - const result = client.matchBranchFromBranchName(fakePath); - assert.strictEqual(result, "branchValue"); - assert((client.pathTemplates.branchPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('branch', async () => { + const fakePath = '/rendered/path/branch'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + branch: 'branchValue', + }; + const client = + new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + client.pathTemplates.branchPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.branchPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('branchPath', () => { + const result = client.branchPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'branchValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.branchPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromBranchName', () => { + const result = client.matchProjectFromBranchName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.branchPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromBranchName', () => { + const result = client.matchLocationFromBranchName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.branchPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromBranchName', () => { + const result = client.matchCatalogFromBranchName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.branchPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBranchFromBranchName', () => { + const result = client.matchBranchFromBranchName(fakePath); + assert.strictEqual(result, 'branchValue'); + assert( + (client.pathTemplates.branchPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('catalog', async () => { - const fakePath = "/rendered/path/catalog"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - }; - const client = new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.catalogPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.catalogPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('catalogPath', () => { - const result = client.catalogPath("projectValue", "locationValue", "catalogValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.catalogPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromCatalogName', () => { - const result = client.matchProjectFromCatalogName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.catalogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromCatalogName', () => { - const result = client.matchLocationFromCatalogName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.catalogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromCatalogName', () => { - const result = client.matchCatalogFromCatalogName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.catalogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('catalog', async () => { + const fakePath = '/rendered/path/catalog'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + }; + const client = + new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + client.pathTemplates.catalogPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.catalogPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('catalogPath', () => { + const result = client.catalogPath( + 'projectValue', + 'locationValue', + 'catalogValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.catalogPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromCatalogName', () => { + const result = client.matchProjectFromCatalogName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.catalogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromCatalogName', () => { + const result = client.matchLocationFromCatalogName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.catalogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromCatalogName', () => { + const result = client.matchCatalogFromCatalogName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.catalogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('completionConfig', async () => { - const fakePath = "/rendered/path/completionConfig"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - }; - const client = new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.completionConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.completionConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('completionConfigPath', () => { - const result = client.completionConfigPath("projectValue", "locationValue", "catalogValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.completionConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromCompletionConfigName', () => { - const result = client.matchProjectFromCompletionConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.completionConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromCompletionConfigName', () => { - const result = client.matchLocationFromCompletionConfigName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.completionConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromCompletionConfigName', () => { - const result = client.matchCatalogFromCompletionConfigName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.completionConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('completionConfig', async () => { + const fakePath = '/rendered/path/completionConfig'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + }; + const client = + new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + client.pathTemplates.completionConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.completionConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('completionConfigPath', () => { + const result = client.completionConfigPath( + 'projectValue', + 'locationValue', + 'catalogValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.completionConfigPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromCompletionConfigName', () => { + const result = client.matchProjectFromCompletionConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.completionConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromCompletionConfigName', () => { + const result = client.matchLocationFromCompletionConfigName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.completionConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromCompletionConfigName', () => { + const result = client.matchCatalogFromCompletionConfigName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.completionConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('control', async () => { - const fakePath = "/rendered/path/control"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - control: "controlValue", - }; - const client = new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.controlPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.controlPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('controlPath', () => { - const result = client.controlPath("projectValue", "locationValue", "catalogValue", "controlValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.controlPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromControlName', () => { - const result = client.matchProjectFromControlName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.controlPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromControlName', () => { - const result = client.matchLocationFromControlName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.controlPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromControlName', () => { - const result = client.matchCatalogFromControlName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.controlPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchControlFromControlName', () => { - const result = client.matchControlFromControlName(fakePath); - assert.strictEqual(result, "controlValue"); - assert((client.pathTemplates.controlPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('control', async () => { + const fakePath = '/rendered/path/control'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + control: 'controlValue', + }; + const client = + new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + client.pathTemplates.controlPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.controlPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('controlPath', () => { + const result = client.controlPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'controlValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.controlPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromControlName', () => { + const result = client.matchProjectFromControlName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.controlPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromControlName', () => { + const result = client.matchLocationFromControlName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.controlPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromControlName', () => { + const result = client.matchCatalogFromControlName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.controlPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchControlFromControlName', () => { + const result = client.matchControlFromControlName(fakePath); + assert.strictEqual(result, 'controlValue'); + assert( + (client.pathTemplates.controlPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('loggingConfig', async () => { - const fakePath = "/rendered/path/loggingConfig"; - const expectedParameters = { - project: "projectValue", - }; - const client = new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.loggingConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.loggingConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('loggingConfigPath', () => { - const result = client.loggingConfigPath("projectValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.loggingConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromLoggingConfigName', () => { - const result = client.matchProjectFromLoggingConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.loggingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('loggingConfig', async () => { + const fakePath = '/rendered/path/loggingConfig'; + const expectedParameters = { + project: 'projectValue', + }; + const client = + new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + client.pathTemplates.loggingConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.loggingConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('loggingConfigPath', () => { + const result = client.loggingConfigPath('projectValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.loggingConfigPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromLoggingConfigName', () => { + const result = client.matchProjectFromLoggingConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.loggingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('merchantCenterAccountLink', async () => { - const fakePath = "/rendered/path/merchantCenterAccountLink"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - merchant_center_account_link: "merchantCenterAccountLinkValue", - }; - const client = new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.merchantCenterAccountLinkPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.merchantCenterAccountLinkPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('merchantCenterAccountLinkPath', () => { - const result = client.merchantCenterAccountLinkPath("projectValue", "locationValue", "catalogValue", "merchantCenterAccountLinkValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromMerchantCenterAccountLinkName', () => { - const result = client.matchProjectFromMerchantCenterAccountLinkName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromMerchantCenterAccountLinkName', () => { - const result = client.matchLocationFromMerchantCenterAccountLinkName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromMerchantCenterAccountLinkName', () => { - const result = client.matchCatalogFromMerchantCenterAccountLinkName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName', () => { - const result = client.matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName(fakePath); - assert.strictEqual(result, "merchantCenterAccountLinkValue"); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('merchantCenterAccountLink', async () => { + const fakePath = '/rendered/path/merchantCenterAccountLink'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + merchant_center_account_link: 'merchantCenterAccountLinkValue', + }; + const client = + new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + client.pathTemplates.merchantCenterAccountLinkPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.merchantCenterAccountLinkPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('merchantCenterAccountLinkPath', () => { + const result = client.merchantCenterAccountLinkPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'merchantCenterAccountLinkValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromMerchantCenterAccountLinkName', () => { + const result = + client.matchProjectFromMerchantCenterAccountLinkName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromMerchantCenterAccountLinkName', () => { + const result = + client.matchLocationFromMerchantCenterAccountLinkName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromMerchantCenterAccountLinkName', () => { + const result = + client.matchCatalogFromMerchantCenterAccountLinkName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName', () => { + const result = + client.matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName( + fakePath, + ); + assert.strictEqual(result, 'merchantCenterAccountLinkValue'); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('model', async () => { - const fakePath = "/rendered/path/model"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - model: "modelValue", - }; - const client = new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.modelPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.modelPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('modelPath', () => { - const result = client.modelPath("projectValue", "locationValue", "catalogValue", "modelValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.modelPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromModelName', () => { - const result = client.matchProjectFromModelName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromModelName', () => { - const result = client.matchLocationFromModelName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromModelName', () => { - const result = client.matchCatalogFromModelName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchModelFromModelName', () => { - const result = client.matchModelFromModelName(fakePath); - assert.strictEqual(result, "modelValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('model', async () => { + const fakePath = '/rendered/path/model'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + model: 'modelValue', + }; + const client = + new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + client.pathTemplates.modelPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.modelPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('modelPath', () => { + const result = client.modelPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'modelValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.modelPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromModelName', () => { + const result = client.matchProjectFromModelName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromModelName', () => { + const result = client.matchLocationFromModelName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromModelName', () => { + const result = client.matchCatalogFromModelName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchModelFromModelName', () => { + const result = client.matchModelFromModelName(fakePath); + assert.strictEqual(result, 'modelValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('product', async () => { - const fakePath = "/rendered/path/product"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - branch: "branchValue", - product: "productValue", - }; - const client = new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.productPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.productPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('productPath', () => { - const result = client.productPath("projectValue", "locationValue", "catalogValue", "branchValue", "productValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.productPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProductName', () => { - const result = client.matchProjectFromProductName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromProductName', () => { - const result = client.matchLocationFromProductName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromProductName', () => { - const result = client.matchCatalogFromProductName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBranchFromProductName', () => { - const result = client.matchBranchFromProductName(fakePath); - assert.strictEqual(result, "branchValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchProductFromProductName', () => { - const result = client.matchProductFromProductName(fakePath); - assert.strictEqual(result, "productValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('product', async () => { + const fakePath = '/rendered/path/product'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + branch: 'branchValue', + product: 'productValue', + }; + const client = + new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + client.pathTemplates.productPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.productPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('productPath', () => { + const result = client.productPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'branchValue', + 'productValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.productPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProductName', () => { + const result = client.matchProjectFromProductName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromProductName', () => { + const result = client.matchLocationFromProductName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromProductName', () => { + const result = client.matchCatalogFromProductName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBranchFromProductName', () => { + const result = client.matchBranchFromProductName(fakePath); + assert.strictEqual(result, 'branchValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchProductFromProductName', () => { + const result = client.matchProductFromProductName(fakePath); + assert.strictEqual(result, 'productValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('retailProject', async () => { - const fakePath = "/rendered/path/retailProject"; - const expectedParameters = { - project: "projectValue", - }; - const client = new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.retailProjectPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.retailProjectPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('retailProjectPath', () => { - const result = client.retailProjectPath("projectValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.retailProjectPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromRetailProjectName', () => { - const result = client.matchProjectFromRetailProjectName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.retailProjectPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('retailProject', async () => { + const fakePath = '/rendered/path/retailProject'; + const expectedParameters = { + project: 'projectValue', + }; + const client = + new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + client.pathTemplates.retailProjectPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.retailProjectPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('retailProjectPath', () => { + const result = client.retailProjectPath('projectValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.retailProjectPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromRetailProjectName', () => { + const result = client.matchProjectFromRetailProjectName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.retailProjectPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('servingConfig', async () => { - const fakePath = "/rendered/path/servingConfig"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - serving_config: "servingConfigValue", - }; - const client = new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.servingConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.servingConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('servingConfigPath', () => { - const result = client.servingConfigPath("projectValue", "locationValue", "catalogValue", "servingConfigValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.servingConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromServingConfigName', () => { - const result = client.matchProjectFromServingConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.servingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromServingConfigName', () => { - const result = client.matchLocationFromServingConfigName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.servingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromServingConfigName', () => { - const result = client.matchCatalogFromServingConfigName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.servingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServingConfigFromServingConfigName', () => { - const result = client.matchServingConfigFromServingConfigName(fakePath); - assert.strictEqual(result, "servingConfigValue"); - assert((client.pathTemplates.servingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('servingConfig', async () => { + const fakePath = '/rendered/path/servingConfig'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + serving_config: 'servingConfigValue', + }; + const client = + new generativequestionserviceModule.v2alpha.GenerativeQuestionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + client.pathTemplates.servingConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.servingConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('servingConfigPath', () => { + const result = client.servingConfigPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'servingConfigValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.servingConfigPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromServingConfigName', () => { + const result = client.matchProjectFromServingConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.servingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromServingConfigName', () => { + const result = client.matchLocationFromServingConfigName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.servingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromServingConfigName', () => { + const result = client.matchCatalogFromServingConfigName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.servingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServingConfigFromServingConfigName', () => { + const result = client.matchServingConfigFromServingConfigName(fakePath); + assert.strictEqual(result, 'servingConfigValue'); + assert( + (client.pathTemplates.servingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/core/generator/gapic-generator-typescript/baselines/retail/test/gapic_merchant_center_account_link_service_v2alpha.ts.baseline b/core/generator/gapic-generator-typescript/baselines/retail/test/gapic_merchant_center_account_link_service_v2alpha.ts.baseline index b8166ae516d3..c56d551695a5 100644 --- a/core/generator/gapic-generator-typescript/baselines/retail/test/gapic_merchant_center_account_link_service_v2alpha.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/retail/test/gapic_merchant_center_account_link_service_v2alpha.ts.baseline @@ -19,1145 +19,1656 @@ import * as protos from '../protos/protos'; import * as assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as merchantcenteraccountlinkserviceModule from '../src'; -import {protobuf, LROperation, operationsProtos} from 'google-gax'; +import { protobuf, LROperation, operationsProtos } from 'google-gax'; // Dynamically loaded proto JSON is needed to get the type information // to fill in default values for request objects -const root = protobuf.Root.fromJSON(require('../protos/protos.json')).resolveAll(); +const root = protobuf.Root.fromJSON( + require('../protos/protos.json'), +).resolveAll(); // eslint-disable-next-line @typescript-eslint/no-unused-vars function getTypeDefaultValue(typeName: string, fields: string[]) { - let type = root.lookupType(typeName) as protobuf.Type; - for (const field of fields.slice(0, -1)) { - type = type.fields[field]?.resolvedType as protobuf.Type; - } - return type.fields[fields[fields.length - 1]]?.defaultValue; + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type.fields[field]?.resolvedType as protobuf.Type; + } + return type.fields[fields[fields.length - 1]]?.defaultValue; } function generateSampleMessage(instance: T) { - const filledObject = (instance.constructor as typeof protobuf.Message) - .toObject(instance as protobuf.Message, {defaults: true}); - return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, { defaults: true }); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; } function stubSimpleCall(response?: ResponseType, error?: Error) { - return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); } -function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { - return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +function stubSimpleCallWithCallback( + response?: ResponseType, + error?: Error, +) { + return error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); } -function stubLongRunningCall(response?: ResponseType, callError?: Error, lroError?: Error) { - const innerStub = lroError ? sinon.stub().rejects(lroError) : sinon.stub().resolves([response]); - const mockOperation = { - promise: innerStub, - }; - return callError ? sinon.stub().rejects(callError) : sinon.stub().resolves([mockOperation]); +function stubLongRunningCall( + response?: ResponseType, + callError?: Error, + lroError?: Error, +) { + const innerStub = lroError + ? sinon.stub().rejects(lroError) + : sinon.stub().resolves([response]); + const mockOperation = { + promise: innerStub, + }; + return callError + ? sinon.stub().rejects(callError) + : sinon.stub().resolves([mockOperation]); } -function stubLongRunningCallWithCallback(response?: ResponseType, callError?: Error, lroError?: Error) { - const innerStub = lroError ? sinon.stub().rejects(lroError) : sinon.stub().resolves([response]); - const mockOperation = { - promise: innerStub, - }; - return callError ? sinon.stub().callsArgWith(2, callError) : sinon.stub().callsArgWith(2, null, mockOperation); +function stubLongRunningCallWithCallback( + response?: ResponseType, + callError?: Error, + lroError?: Error, +) { + const innerStub = lroError + ? sinon.stub().rejects(lroError) + : sinon.stub().resolves([response]); + const mockOperation = { + promise: innerStub, + }; + return callError + ? sinon.stub().callsArgWith(2, callError) + : sinon.stub().callsArgWith(2, null, mockOperation); } describe('v2alpha.MerchantCenterAccountLinkServiceClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'retail.googleapis.com'); - }); - - it('has universeDomain', () => { - const client = new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); - - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - it('throws DeprecationWarning if static servicePath is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const servicePath = merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient.servicePath; - assert.strictEqual(servicePath, 'retail.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'retail.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'retail.example.com'); - }); - - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'retail.example.com'); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = + new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'retail.googleapis.com'); + }); - if (typeof process === 'object' && 'env' in process) { - describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { - it('sets apiEndpoint from environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'retail.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - - it('value configured in code has priority over environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'retail.configured.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); + it('has universeDomain', () => { + const client = + new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - it('has port', () => { - const port = merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient.port; - assert(port); - assert(typeof port === 'number'); - }); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = + merchantcenteraccountlinkserviceModule.v2alpha + .MerchantCenterAccountLinkServiceClient.servicePath; + assert.strictEqual(servicePath, 'retail.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + merchantcenteraccountlinkserviceModule.v2alpha + .MerchantCenterAccountLinkServiceClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'retail.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = + new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient( + { universeDomain: 'example.com' }, + ); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'retail.example.com'); + }); - it('should create a client with no option', () => { - const client = new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient(); - assert(client); - }); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = + new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient( + { universe_domain: 'example.com' }, + ); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'retail.example.com'); + }); - it('should create a client with gRPC fallback', () => { - const client = new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient({ - fallback: true, - }); - assert(client); + if (typeof process === 'object' && 'env' in process) { + describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { + it('sets apiEndpoint from environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = + new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'retail.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - it('has initialize method and supports deferred initialization', async () => { - const client = new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.merchantCenterAccountLinkServiceStub, undefined); - await client.initialize(); - assert(client.merchantCenterAccountLinkServiceStub); + it('value configured in code has priority over environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = + new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient( + { universeDomain: 'configured.example.com' }, + ); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'retail.configured.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient( + { universe_domain: 'example.com', universeDomain: 'example.net' }, + ); + }); + }); - it('has close method for the initialized client', done => { - const client = new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.merchantCenterAccountLinkServiceStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('has port', () => { + const port = + merchantcenteraccountlinkserviceModule.v2alpha + .MerchantCenterAccountLinkServiceClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('has close method for the non-initialized client', done => { - const client = new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.merchantCenterAccountLinkServiceStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('should create a client with no option', () => { + const client = + new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient(); + assert(client); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); - }); + it('should create a client with gRPC fallback', () => { + const client = + new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient( + { + fallback: true, + }, + ); + assert(client); + }); - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId((err?: Error|null, projectId?: string|null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } - }); - }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); - }); + it('has initialize method and supports deferred initialization', async () => { + const client = + new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + assert.strictEqual( + client.merchantCenterAccountLinkServiceStub, + undefined, + ); + await client.initialize(); + assert(client.merchantCenterAccountLinkServiceStub); }); - describe('listMerchantCenterAccountLinks', () => { - it('invokes listMerchantCenterAccountLinks without error', async () => { - const client = new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ListMerchantCenterAccountLinksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ListMerchantCenterAccountLinksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ListMerchantCenterAccountLinksResponse() - ); - client.innerApiCalls.listMerchantCenterAccountLinks = stubSimpleCall(expectedResponse); - const [response] = await client.listMerchantCenterAccountLinks(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listMerchantCenterAccountLinks as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listMerchantCenterAccountLinks as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('has close method for the initialized client', (done) => { + const client = + new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + client.initialize().catch((err) => { + throw err; + }); + assert(client.merchantCenterAccountLinkServiceStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes listMerchantCenterAccountLinks without error using callback', async () => { - const client = new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ListMerchantCenterAccountLinksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ListMerchantCenterAccountLinksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ListMerchantCenterAccountLinksResponse() - ); - client.innerApiCalls.listMerchantCenterAccountLinks = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listMerchantCenterAccountLinks( - request, - (err?: Error|null, result?: protos.google.cloud.retail.v2alpha.IListMerchantCenterAccountLinksResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listMerchantCenterAccountLinks as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listMerchantCenterAccountLinks as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('has close method for the non-initialized client', (done) => { + const client = + new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + assert.strictEqual( + client.merchantCenterAccountLinkServiceStub, + undefined, + ); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes listMerchantCenterAccountLinks with error', async () => { - const client = new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ListMerchantCenterAccountLinksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ListMerchantCenterAccountLinksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listMerchantCenterAccountLinks = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listMerchantCenterAccountLinks(request), expectedError); - const actualRequest = (client.innerApiCalls.listMerchantCenterAccountLinks as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listMerchantCenterAccountLinks as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = + new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + }); - it('invokes listMerchantCenterAccountLinks with closed client', async () => { - const client = new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ListMerchantCenterAccountLinksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ListMerchantCenterAccountLinksRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.listMerchantCenterAccountLinks(request), expectedError); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = + new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + }); + + describe('listMerchantCenterAccountLinks', () => { + it('invokes listMerchantCenterAccountLinks without error', async () => { + const client = + new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ListMerchantCenterAccountLinksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ListMerchantCenterAccountLinksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ListMerchantCenterAccountLinksResponse(), + ); + client.innerApiCalls.listMerchantCenterAccountLinks = + stubSimpleCall(expectedResponse); + const [response] = await client.listMerchantCenterAccountLinks(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listMerchantCenterAccountLinks as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listMerchantCenterAccountLinks as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('deleteMerchantCenterAccountLink', () => { - it('invokes deleteMerchantCenterAccountLink without error', async () => { - const client = new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.DeleteMerchantCenterAccountLinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.DeleteMerchantCenterAccountLinkRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteMerchantCenterAccountLink = stubSimpleCall(expectedResponse); - const [response] = await client.deleteMerchantCenterAccountLink(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteMerchantCenterAccountLink as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteMerchantCenterAccountLink as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listMerchantCenterAccountLinks without error using callback', async () => { + const client = + new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ListMerchantCenterAccountLinksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ListMerchantCenterAccountLinksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ListMerchantCenterAccountLinksResponse(), + ); + client.innerApiCalls.listMerchantCenterAccountLinks = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listMerchantCenterAccountLinks( + request, + ( + err?: Error | null, + result?: protos.google.cloud.retail.v2alpha.IListMerchantCenterAccountLinksResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listMerchantCenterAccountLinks as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listMerchantCenterAccountLinks as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteMerchantCenterAccountLink without error using callback', async () => { - const client = new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.DeleteMerchantCenterAccountLinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.DeleteMerchantCenterAccountLinkRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteMerchantCenterAccountLink = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteMerchantCenterAccountLink( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteMerchantCenterAccountLink as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteMerchantCenterAccountLink as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listMerchantCenterAccountLinks with error', async () => { + const client = + new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ListMerchantCenterAccountLinksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ListMerchantCenterAccountLinksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listMerchantCenterAccountLinks = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.listMerchantCenterAccountLinks(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.listMerchantCenterAccountLinks as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listMerchantCenterAccountLinks as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteMerchantCenterAccountLink with error', async () => { - const client = new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.DeleteMerchantCenterAccountLinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.DeleteMerchantCenterAccountLinkRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteMerchantCenterAccountLink = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteMerchantCenterAccountLink(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteMerchantCenterAccountLink as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteMerchantCenterAccountLink as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listMerchantCenterAccountLinks with closed client', async () => { + const client = + new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ListMerchantCenterAccountLinksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ListMerchantCenterAccountLinksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.listMerchantCenterAccountLinks(request), + expectedError, + ); + }); + }); + + describe('deleteMerchantCenterAccountLink', () => { + it('invokes deleteMerchantCenterAccountLink without error', async () => { + const client = + new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.DeleteMerchantCenterAccountLinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.DeleteMerchantCenterAccountLinkRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteMerchantCenterAccountLink = + stubSimpleCall(expectedResponse); + const [response] = await client.deleteMerchantCenterAccountLink(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteMerchantCenterAccountLink as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteMerchantCenterAccountLink as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteMerchantCenterAccountLink with closed client', async () => { - const client = new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.DeleteMerchantCenterAccountLinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.DeleteMerchantCenterAccountLinkRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteMerchantCenterAccountLink(request), expectedError); - }); + it('invokes deleteMerchantCenterAccountLink without error using callback', async () => { + const client = + new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.DeleteMerchantCenterAccountLinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.DeleteMerchantCenterAccountLinkRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteMerchantCenterAccountLink = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteMerchantCenterAccountLink( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteMerchantCenterAccountLink as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteMerchantCenterAccountLink as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('createMerchantCenterAccountLink', () => { - it('invokes createMerchantCenterAccountLink without error', async () => { - const client = new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.CreateMerchantCenterAccountLinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.CreateMerchantCenterAccountLinkRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.createMerchantCenterAccountLink = stubLongRunningCall(expectedResponse); - const [operation] = await client.createMerchantCenterAccountLink(request); - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createMerchantCenterAccountLink as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createMerchantCenterAccountLink as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteMerchantCenterAccountLink with error', async () => { + const client = + new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.DeleteMerchantCenterAccountLinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.DeleteMerchantCenterAccountLinkRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteMerchantCenterAccountLink = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.deleteMerchantCenterAccountLink(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.deleteMerchantCenterAccountLink as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteMerchantCenterAccountLink as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createMerchantCenterAccountLink without error using callback', async () => { - const client = new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.CreateMerchantCenterAccountLinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.CreateMerchantCenterAccountLinkRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.createMerchantCenterAccountLink = stubLongRunningCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createMerchantCenterAccountLink( - request, - (err?: Error|null, - result?: LROperation|null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const operation = await promise as LROperation; - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createMerchantCenterAccountLink as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createMerchantCenterAccountLink as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteMerchantCenterAccountLink with closed client', async () => { + const client = + new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.DeleteMerchantCenterAccountLinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.DeleteMerchantCenterAccountLinkRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.deleteMerchantCenterAccountLink(request), + expectedError, + ); + }); + }); + + describe('createMerchantCenterAccountLink', () => { + it('invokes createMerchantCenterAccountLink without error', async () => { + const client = + new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.CreateMerchantCenterAccountLinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.CreateMerchantCenterAccountLinkRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.createMerchantCenterAccountLink = + stubLongRunningCall(expectedResponse); + const [operation] = await client.createMerchantCenterAccountLink(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createMerchantCenterAccountLink as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createMerchantCenterAccountLink as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createMerchantCenterAccountLink with call error', async () => { - const client = new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.CreateMerchantCenterAccountLinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.CreateMerchantCenterAccountLinkRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createMerchantCenterAccountLink = stubLongRunningCall(undefined, expectedError); - await assert.rejects(client.createMerchantCenterAccountLink(request), expectedError); - const actualRequest = (client.innerApiCalls.createMerchantCenterAccountLink as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createMerchantCenterAccountLink as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createMerchantCenterAccountLink without error using callback', async () => { + const client = + new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.CreateMerchantCenterAccountLinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.CreateMerchantCenterAccountLinkRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.createMerchantCenterAccountLink = + stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createMerchantCenterAccountLink( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.cloud.retail.v2alpha.IMerchantCenterAccountLink, + protos.google.cloud.retail.v2alpha.ICreateMerchantCenterAccountLinkMetadata + > | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const operation = (await promise) as LROperation< + protos.google.cloud.retail.v2alpha.IMerchantCenterAccountLink, + protos.google.cloud.retail.v2alpha.ICreateMerchantCenterAccountLinkMetadata + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createMerchantCenterAccountLink as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createMerchantCenterAccountLink as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createMerchantCenterAccountLink with LRO error', async () => { - const client = new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.CreateMerchantCenterAccountLinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.CreateMerchantCenterAccountLinkRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createMerchantCenterAccountLink = stubLongRunningCall(undefined, undefined, expectedError); - const [operation] = await client.createMerchantCenterAccountLink(request); - await assert.rejects(operation.promise(), expectedError); - const actualRequest = (client.innerApiCalls.createMerchantCenterAccountLink as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createMerchantCenterAccountLink as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createMerchantCenterAccountLink with call error', async () => { + const client = + new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.CreateMerchantCenterAccountLinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.CreateMerchantCenterAccountLinkRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createMerchantCenterAccountLink = + stubLongRunningCall(undefined, expectedError); + await assert.rejects( + client.createMerchantCenterAccountLink(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.createMerchantCenterAccountLink as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createMerchantCenterAccountLink as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkCreateMerchantCenterAccountLinkProgress without error', async () => { - const client = new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedResponse = generateSampleMessage( - new operationsProtos.google.longrunning.Operation() - ); - expectedResponse.name = 'test'; - expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; - expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')} - - client.operationsClient.getOperation = stubSimpleCall(expectedResponse); - const decodedOperation = await client.checkCreateMerchantCenterAccountLinkProgress(expectedResponse.name); - assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); - assert(decodedOperation.metadata); - assert((client.operationsClient.getOperation as SinonStub).getCall(0)); - }); + it('invokes createMerchantCenterAccountLink with LRO error', async () => { + const client = + new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.CreateMerchantCenterAccountLinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.CreateMerchantCenterAccountLinkRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createMerchantCenterAccountLink = + stubLongRunningCall(undefined, undefined, expectedError); + const [operation] = await client.createMerchantCenterAccountLink(request); + await assert.rejects(operation.promise(), expectedError); + const actualRequest = ( + client.innerApiCalls.createMerchantCenterAccountLink as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createMerchantCenterAccountLink as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkCreateMerchantCenterAccountLinkProgress with error', async () => { - const client = new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedError = new Error('expected'); - - client.operationsClient.getOperation = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.checkCreateMerchantCenterAccountLinkProgress(''), expectedError); - assert((client.operationsClient.getOperation as SinonStub) - .getCall(0)); - }); + it('invokes checkCreateMerchantCenterAccountLinkProgress without error', async () => { + const client = + new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation(), + ); + expectedResponse.name = 'test'; + expectedResponse.response = { type_url: 'url', value: Buffer.from('') }; + expectedResponse.metadata = { type_url: 'url', value: Buffer.from('') }; + + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const decodedOperation = + await client.checkCreateMerchantCenterAccountLinkProgress( + expectedResponse.name, + ); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); }); - describe('Path templates', () => { - - describe('alertConfig', async () => { - const fakePath = "/rendered/path/alertConfig"; - const expectedParameters = { - project: "projectValue", - }; - const client = new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.alertConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.alertConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('alertConfigPath', () => { - const result = client.alertConfigPath("projectValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.alertConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromAlertConfigName', () => { - const result = client.matchProjectFromAlertConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.alertConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('invokes checkCreateMerchantCenterAccountLinkProgress with error', async () => { + const client = + new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const expectedError = new Error('expected'); + + client.operationsClient.getOperation = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.checkCreateMerchantCenterAccountLinkProgress(''), + expectedError, + ); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + }); + + describe('Path templates', () => { + describe('alertConfig', async () => { + const fakePath = '/rendered/path/alertConfig'; + const expectedParameters = { + project: 'projectValue', + }; + const client = + new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + client.pathTemplates.alertConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.alertConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('alertConfigPath', () => { + const result = client.alertConfigPath('projectValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.alertConfigPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromAlertConfigName', () => { + const result = client.matchProjectFromAlertConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.alertConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('attributesConfig', async () => { - const fakePath = "/rendered/path/attributesConfig"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - }; - const client = new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.attributesConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.attributesConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('attributesConfigPath', () => { - const result = client.attributesConfigPath("projectValue", "locationValue", "catalogValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.attributesConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromAttributesConfigName', () => { - const result = client.matchProjectFromAttributesConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromAttributesConfigName', () => { - const result = client.matchLocationFromAttributesConfigName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromAttributesConfigName', () => { - const result = client.matchCatalogFromAttributesConfigName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('attributesConfig', async () => { + const fakePath = '/rendered/path/attributesConfig'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + }; + const client = + new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + client.pathTemplates.attributesConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.attributesConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('attributesConfigPath', () => { + const result = client.attributesConfigPath( + 'projectValue', + 'locationValue', + 'catalogValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.attributesConfigPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromAttributesConfigName', () => { + const result = client.matchProjectFromAttributesConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromAttributesConfigName', () => { + const result = client.matchLocationFromAttributesConfigName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromAttributesConfigName', () => { + const result = client.matchCatalogFromAttributesConfigName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('branch', async () => { - const fakePath = "/rendered/path/branch"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - branch: "branchValue", - }; - const client = new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.branchPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.branchPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('branchPath', () => { - const result = client.branchPath("projectValue", "locationValue", "catalogValue", "branchValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.branchPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromBranchName', () => { - const result = client.matchProjectFromBranchName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.branchPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromBranchName', () => { - const result = client.matchLocationFromBranchName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.branchPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromBranchName', () => { - const result = client.matchCatalogFromBranchName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.branchPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBranchFromBranchName', () => { - const result = client.matchBranchFromBranchName(fakePath); - assert.strictEqual(result, "branchValue"); - assert((client.pathTemplates.branchPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('branch', async () => { + const fakePath = '/rendered/path/branch'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + branch: 'branchValue', + }; + const client = + new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + client.pathTemplates.branchPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.branchPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('branchPath', () => { + const result = client.branchPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'branchValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.branchPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromBranchName', () => { + const result = client.matchProjectFromBranchName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.branchPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromBranchName', () => { + const result = client.matchLocationFromBranchName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.branchPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromBranchName', () => { + const result = client.matchCatalogFromBranchName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.branchPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBranchFromBranchName', () => { + const result = client.matchBranchFromBranchName(fakePath); + assert.strictEqual(result, 'branchValue'); + assert( + (client.pathTemplates.branchPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('catalog', async () => { - const fakePath = "/rendered/path/catalog"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - }; - const client = new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.catalogPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.catalogPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('catalogPath', () => { - const result = client.catalogPath("projectValue", "locationValue", "catalogValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.catalogPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromCatalogName', () => { - const result = client.matchProjectFromCatalogName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.catalogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromCatalogName', () => { - const result = client.matchLocationFromCatalogName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.catalogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromCatalogName', () => { - const result = client.matchCatalogFromCatalogName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.catalogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('catalog', async () => { + const fakePath = '/rendered/path/catalog'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + }; + const client = + new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + client.pathTemplates.catalogPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.catalogPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('catalogPath', () => { + const result = client.catalogPath( + 'projectValue', + 'locationValue', + 'catalogValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.catalogPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromCatalogName', () => { + const result = client.matchProjectFromCatalogName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.catalogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromCatalogName', () => { + const result = client.matchLocationFromCatalogName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.catalogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromCatalogName', () => { + const result = client.matchCatalogFromCatalogName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.catalogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('completionConfig', async () => { - const fakePath = "/rendered/path/completionConfig"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - }; - const client = new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.completionConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.completionConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('completionConfigPath', () => { - const result = client.completionConfigPath("projectValue", "locationValue", "catalogValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.completionConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromCompletionConfigName', () => { - const result = client.matchProjectFromCompletionConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.completionConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromCompletionConfigName', () => { - const result = client.matchLocationFromCompletionConfigName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.completionConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromCompletionConfigName', () => { - const result = client.matchCatalogFromCompletionConfigName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.completionConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('completionConfig', async () => { + const fakePath = '/rendered/path/completionConfig'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + }; + const client = + new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + client.pathTemplates.completionConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.completionConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('completionConfigPath', () => { + const result = client.completionConfigPath( + 'projectValue', + 'locationValue', + 'catalogValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.completionConfigPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromCompletionConfigName', () => { + const result = client.matchProjectFromCompletionConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.completionConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromCompletionConfigName', () => { + const result = client.matchLocationFromCompletionConfigName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.completionConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromCompletionConfigName', () => { + const result = client.matchCatalogFromCompletionConfigName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.completionConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('control', async () => { - const fakePath = "/rendered/path/control"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - control: "controlValue", - }; - const client = new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.controlPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.controlPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('controlPath', () => { - const result = client.controlPath("projectValue", "locationValue", "catalogValue", "controlValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.controlPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromControlName', () => { - const result = client.matchProjectFromControlName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.controlPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromControlName', () => { - const result = client.matchLocationFromControlName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.controlPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromControlName', () => { - const result = client.matchCatalogFromControlName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.controlPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchControlFromControlName', () => { - const result = client.matchControlFromControlName(fakePath); - assert.strictEqual(result, "controlValue"); - assert((client.pathTemplates.controlPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('control', async () => { + const fakePath = '/rendered/path/control'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + control: 'controlValue', + }; + const client = + new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + client.pathTemplates.controlPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.controlPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('controlPath', () => { + const result = client.controlPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'controlValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.controlPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromControlName', () => { + const result = client.matchProjectFromControlName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.controlPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromControlName', () => { + const result = client.matchLocationFromControlName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.controlPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromControlName', () => { + const result = client.matchCatalogFromControlName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.controlPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchControlFromControlName', () => { + const result = client.matchControlFromControlName(fakePath); + assert.strictEqual(result, 'controlValue'); + assert( + (client.pathTemplates.controlPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('loggingConfig', async () => { - const fakePath = "/rendered/path/loggingConfig"; - const expectedParameters = { - project: "projectValue", - }; - const client = new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.loggingConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.loggingConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('loggingConfigPath', () => { - const result = client.loggingConfigPath("projectValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.loggingConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromLoggingConfigName', () => { - const result = client.matchProjectFromLoggingConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.loggingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('loggingConfig', async () => { + const fakePath = '/rendered/path/loggingConfig'; + const expectedParameters = { + project: 'projectValue', + }; + const client = + new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + client.pathTemplates.loggingConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.loggingConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('loggingConfigPath', () => { + const result = client.loggingConfigPath('projectValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.loggingConfigPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromLoggingConfigName', () => { + const result = client.matchProjectFromLoggingConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.loggingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('merchantCenterAccountLink', async () => { - const fakePath = "/rendered/path/merchantCenterAccountLink"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - merchant_center_account_link: "merchantCenterAccountLinkValue", - }; - const client = new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.merchantCenterAccountLinkPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.merchantCenterAccountLinkPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('merchantCenterAccountLinkPath', () => { - const result = client.merchantCenterAccountLinkPath("projectValue", "locationValue", "catalogValue", "merchantCenterAccountLinkValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromMerchantCenterAccountLinkName', () => { - const result = client.matchProjectFromMerchantCenterAccountLinkName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromMerchantCenterAccountLinkName', () => { - const result = client.matchLocationFromMerchantCenterAccountLinkName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromMerchantCenterAccountLinkName', () => { - const result = client.matchCatalogFromMerchantCenterAccountLinkName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName', () => { - const result = client.matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName(fakePath); - assert.strictEqual(result, "merchantCenterAccountLinkValue"); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('merchantCenterAccountLink', async () => { + const fakePath = '/rendered/path/merchantCenterAccountLink'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + merchant_center_account_link: 'merchantCenterAccountLinkValue', + }; + const client = + new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + client.pathTemplates.merchantCenterAccountLinkPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.merchantCenterAccountLinkPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('merchantCenterAccountLinkPath', () => { + const result = client.merchantCenterAccountLinkPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'merchantCenterAccountLinkValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromMerchantCenterAccountLinkName', () => { + const result = + client.matchProjectFromMerchantCenterAccountLinkName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromMerchantCenterAccountLinkName', () => { + const result = + client.matchLocationFromMerchantCenterAccountLinkName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromMerchantCenterAccountLinkName', () => { + const result = + client.matchCatalogFromMerchantCenterAccountLinkName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName', () => { + const result = + client.matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName( + fakePath, + ); + assert.strictEqual(result, 'merchantCenterAccountLinkValue'); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('model', async () => { - const fakePath = "/rendered/path/model"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - model: "modelValue", - }; - const client = new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.modelPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.modelPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('modelPath', () => { - const result = client.modelPath("projectValue", "locationValue", "catalogValue", "modelValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.modelPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromModelName', () => { - const result = client.matchProjectFromModelName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromModelName', () => { - const result = client.matchLocationFromModelName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromModelName', () => { - const result = client.matchCatalogFromModelName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchModelFromModelName', () => { - const result = client.matchModelFromModelName(fakePath); - assert.strictEqual(result, "modelValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('model', async () => { + const fakePath = '/rendered/path/model'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + model: 'modelValue', + }; + const client = + new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + client.pathTemplates.modelPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.modelPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('modelPath', () => { + const result = client.modelPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'modelValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.modelPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromModelName', () => { + const result = client.matchProjectFromModelName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromModelName', () => { + const result = client.matchLocationFromModelName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromModelName', () => { + const result = client.matchCatalogFromModelName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchModelFromModelName', () => { + const result = client.matchModelFromModelName(fakePath); + assert.strictEqual(result, 'modelValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('product', async () => { - const fakePath = "/rendered/path/product"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - branch: "branchValue", - product: "productValue", - }; - const client = new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.productPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.productPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('productPath', () => { - const result = client.productPath("projectValue", "locationValue", "catalogValue", "branchValue", "productValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.productPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProductName', () => { - const result = client.matchProjectFromProductName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromProductName', () => { - const result = client.matchLocationFromProductName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromProductName', () => { - const result = client.matchCatalogFromProductName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBranchFromProductName', () => { - const result = client.matchBranchFromProductName(fakePath); - assert.strictEqual(result, "branchValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchProductFromProductName', () => { - const result = client.matchProductFromProductName(fakePath); - assert.strictEqual(result, "productValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('product', async () => { + const fakePath = '/rendered/path/product'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + branch: 'branchValue', + product: 'productValue', + }; + const client = + new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + client.pathTemplates.productPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.productPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('productPath', () => { + const result = client.productPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'branchValue', + 'productValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.productPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProductName', () => { + const result = client.matchProjectFromProductName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromProductName', () => { + const result = client.matchLocationFromProductName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromProductName', () => { + const result = client.matchCatalogFromProductName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBranchFromProductName', () => { + const result = client.matchBranchFromProductName(fakePath); + assert.strictEqual(result, 'branchValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchProductFromProductName', () => { + const result = client.matchProductFromProductName(fakePath); + assert.strictEqual(result, 'productValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('retailProject', async () => { - const fakePath = "/rendered/path/retailProject"; - const expectedParameters = { - project: "projectValue", - }; - const client = new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.retailProjectPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.retailProjectPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('retailProjectPath', () => { - const result = client.retailProjectPath("projectValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.retailProjectPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromRetailProjectName', () => { - const result = client.matchProjectFromRetailProjectName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.retailProjectPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('retailProject', async () => { + const fakePath = '/rendered/path/retailProject'; + const expectedParameters = { + project: 'projectValue', + }; + const client = + new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + client.pathTemplates.retailProjectPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.retailProjectPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('retailProjectPath', () => { + const result = client.retailProjectPath('projectValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.retailProjectPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromRetailProjectName', () => { + const result = client.matchProjectFromRetailProjectName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.retailProjectPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('servingConfig', async () => { - const fakePath = "/rendered/path/servingConfig"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - serving_config: "servingConfigValue", - }; - const client = new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.servingConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.servingConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('servingConfigPath', () => { - const result = client.servingConfigPath("projectValue", "locationValue", "catalogValue", "servingConfigValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.servingConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromServingConfigName', () => { - const result = client.matchProjectFromServingConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.servingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromServingConfigName', () => { - const result = client.matchLocationFromServingConfigName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.servingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromServingConfigName', () => { - const result = client.matchCatalogFromServingConfigName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.servingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServingConfigFromServingConfigName', () => { - const result = client.matchServingConfigFromServingConfigName(fakePath); - assert.strictEqual(result, "servingConfigValue"); - assert((client.pathTemplates.servingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('servingConfig', async () => { + const fakePath = '/rendered/path/servingConfig'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + serving_config: 'servingConfigValue', + }; + const client = + new merchantcenteraccountlinkserviceModule.v2alpha.MerchantCenterAccountLinkServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + client.pathTemplates.servingConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.servingConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('servingConfigPath', () => { + const result = client.servingConfigPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'servingConfigValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.servingConfigPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromServingConfigName', () => { + const result = client.matchProjectFromServingConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.servingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromServingConfigName', () => { + const result = client.matchLocationFromServingConfigName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.servingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromServingConfigName', () => { + const result = client.matchCatalogFromServingConfigName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.servingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServingConfigFromServingConfigName', () => { + const result = client.matchServingConfigFromServingConfigName(fakePath); + assert.strictEqual(result, 'servingConfigValue'); + assert( + (client.pathTemplates.servingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/core/generator/gapic-generator-typescript/baselines/retail/test/gapic_model_service_v2alpha.ts.baseline b/core/generator/gapic-generator-typescript/baselines/retail/test/gapic_model_service_v2alpha.ts.baseline index 36022a799068..41577d7f8c47 100644 --- a/core/generator/gapic-generator-typescript/baselines/retail/test/gapic_model_service_v2alpha.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/retail/test/gapic_model_service_v2alpha.ts.baseline @@ -19,1919 +19,2482 @@ import * as protos from '../protos/protos'; import * as assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as modelserviceModule from '../src'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; -import {protobuf, LROperation, operationsProtos} from 'google-gax'; +import { protobuf, LROperation, operationsProtos } from 'google-gax'; // Dynamically loaded proto JSON is needed to get the type information // to fill in default values for request objects -const root = protobuf.Root.fromJSON(require('../protos/protos.json')).resolveAll(); +const root = protobuf.Root.fromJSON( + require('../protos/protos.json'), +).resolveAll(); // eslint-disable-next-line @typescript-eslint/no-unused-vars function getTypeDefaultValue(typeName: string, fields: string[]) { - let type = root.lookupType(typeName) as protobuf.Type; - for (const field of fields.slice(0, -1)) { - type = type.fields[field]?.resolvedType as protobuf.Type; - } - return type.fields[fields[fields.length - 1]]?.defaultValue; + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type.fields[field]?.resolvedType as protobuf.Type; + } + return type.fields[fields[fields.length - 1]]?.defaultValue; } function generateSampleMessage(instance: T) { - const filledObject = (instance.constructor as typeof protobuf.Message) - .toObject(instance as protobuf.Message, {defaults: true}); - return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, { defaults: true }); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; } function stubSimpleCall(response?: ResponseType, error?: Error) { - return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); } -function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { - return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +function stubSimpleCallWithCallback( + response?: ResponseType, + error?: Error, +) { + return error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); } -function stubLongRunningCall(response?: ResponseType, callError?: Error, lroError?: Error) { - const innerStub = lroError ? sinon.stub().rejects(lroError) : sinon.stub().resolves([response]); - const mockOperation = { - promise: innerStub, - }; - return callError ? sinon.stub().rejects(callError) : sinon.stub().resolves([mockOperation]); +function stubLongRunningCall( + response?: ResponseType, + callError?: Error, + lroError?: Error, +) { + const innerStub = lroError + ? sinon.stub().rejects(lroError) + : sinon.stub().resolves([response]); + const mockOperation = { + promise: innerStub, + }; + return callError + ? sinon.stub().rejects(callError) + : sinon.stub().resolves([mockOperation]); } -function stubLongRunningCallWithCallback(response?: ResponseType, callError?: Error, lroError?: Error) { - const innerStub = lroError ? sinon.stub().rejects(lroError) : sinon.stub().resolves([response]); - const mockOperation = { - promise: innerStub, - }; - return callError ? sinon.stub().callsArgWith(2, callError) : sinon.stub().callsArgWith(2, null, mockOperation); +function stubLongRunningCallWithCallback( + response?: ResponseType, + callError?: Error, + lroError?: Error, +) { + const innerStub = lroError + ? sinon.stub().rejects(lroError) + : sinon.stub().resolves([response]); + const mockOperation = { + promise: innerStub, + }; + return callError + ? sinon.stub().callsArgWith(2, callError) + : sinon.stub().callsArgWith(2, null, mockOperation); } -function stubPageStreamingCall(responses?: ResponseType[], error?: Error) { - const pagingStub = sinon.stub(); - if (responses) { - for (let i = 0; i < responses.length; ++i) { - pagingStub.onCall(i).callsArgWith(2, null, responses[i]); - } +function stubPageStreamingCall( + responses?: ResponseType[], + error?: Error, +) { + const pagingStub = sinon.stub(); + if (responses) { + for (let i = 0; i < responses.length; ++i) { + pagingStub.onCall(i).callsArgWith(2, null, responses[i]); } - const transformStub = error ? sinon.stub().callsArgWith(2, error) : pagingStub; - const mockStream = new PassThrough({ - objectMode: true, - transform: transformStub, - }); - // trigger as many responses as needed - if (responses) { - for (let i = 0; i < responses.length; ++i) { - setImmediate(() => { mockStream.write({}); }); - } - setImmediate(() => { mockStream.end(); }); - } else { - setImmediate(() => { mockStream.write({}); }); - setImmediate(() => { mockStream.end(); }); + } + const transformStub = error + ? sinon.stub().callsArgWith(2, error) + : pagingStub; + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + // trigger as many responses as needed + if (responses) { + for (let i = 0; i < responses.length; ++i) { + setImmediate(() => { + mockStream.write({}); + }); } - return sinon.stub().returns(mockStream); + setImmediate(() => { + mockStream.end(); + }); + } else { + setImmediate(() => { + mockStream.write({}); + }); + setImmediate(() => { + mockStream.end(); + }); + } + return sinon.stub().returns(mockStream); } -function stubAsyncIterationCall(responses?: ResponseType[], error?: Error) { - let counter = 0; - const asyncIterable = { - [Symbol.asyncIterator]() { - return { - async next() { - if (error) { - return Promise.reject(error); - } - if (counter >= responses!.length) { - return Promise.resolve({done: true, value: undefined}); - } - return Promise.resolve({done: false, value: responses![counter++]}); - } - }; - } - }; - return sinon.stub().returns(asyncIterable); +function stubAsyncIterationCall( + responses?: ResponseType[], + error?: Error, +) { + let counter = 0; + const asyncIterable = { + [Symbol.asyncIterator]() { + return { + async next() { + if (error) { + return Promise.reject(error); + } + if (counter >= responses!.length) { + return Promise.resolve({ done: true, value: undefined }); + } + return Promise.resolve({ done: false, value: responses![counter++] }); + }, + }; + }, + }; + return sinon.stub().returns(asyncIterable); } describe('v2alpha.ModelServiceClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new modelserviceModule.v2alpha.ModelServiceClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'retail.googleapis.com'); - }); - - it('has universeDomain', () => { - const client = new modelserviceModule.v2alpha.ModelServiceClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); - - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - it('throws DeprecationWarning if static servicePath is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const servicePath = modelserviceModule.v2alpha.ModelServiceClient.servicePath; - assert.strictEqual(servicePath, 'retail.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = modelserviceModule.v2alpha.ModelServiceClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'retail.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new modelserviceModule.v2alpha.ModelServiceClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'retail.example.com'); - }); - - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new modelserviceModule.v2alpha.ModelServiceClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'retail.example.com'); - }); - - if (typeof process === 'object' && 'env' in process) { - describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { - it('sets apiEndpoint from environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new modelserviceModule.v2alpha.ModelServiceClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'retail.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - - it('value configured in code has priority over environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new modelserviceModule.v2alpha.ModelServiceClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'retail.configured.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { new modelserviceModule.v2alpha.ModelServiceClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); - - it('has port', () => { - const port = modelserviceModule.v2alpha.ModelServiceClient.port; - assert(port); - assert(typeof port === 'number'); - }); - - it('should create a client with no option', () => { - const client = new modelserviceModule.v2alpha.ModelServiceClient(); - assert(client); - }); - - it('should create a client with gRPC fallback', () => { - const client = new modelserviceModule.v2alpha.ModelServiceClient({ - fallback: true, - }); - assert(client); - }); - - it('has initialize method and supports deferred initialization', async () => { - const client = new modelserviceModule.v2alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.modelServiceStub, undefined); - await client.initialize(); - assert(client.modelServiceStub); - }); - - it('has close method for the initialized client', done => { - const client = new modelserviceModule.v2alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.modelServiceStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new modelserviceModule.v2alpha.ModelServiceClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'retail.googleapis.com'); + }); - it('has close method for the non-initialized client', done => { - const client = new modelserviceModule.v2alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.modelServiceStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('has universeDomain', () => { + const client = new modelserviceModule.v2alpha.ModelServiceClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new modelserviceModule.v2alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); - }); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = + modelserviceModule.v2alpha.ModelServiceClient.servicePath; + assert.strictEqual(servicePath, 'retail.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + modelserviceModule.v2alpha.ModelServiceClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'retail.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = new modelserviceModule.v2alpha.ModelServiceClient({ + universeDomain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'retail.example.com'); + }); - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new modelserviceModule.v2alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId((err?: Error|null, projectId?: string|null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } - }); - }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); - }); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = new modelserviceModule.v2alpha.ModelServiceClient({ + universe_domain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'retail.example.com'); }); - describe('getModel', () => { - it('invokes getModel without error', async () => { - const client = new modelserviceModule.v2alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.GetModelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.GetModelRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.Model() - ); - client.innerApiCalls.getModel = stubSimpleCall(expectedResponse); - const [response] = await client.getModel(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getModel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getModel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + if (typeof process === 'object' && 'env' in process) { + describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { + it('sets apiEndpoint from environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new modelserviceModule.v2alpha.ModelServiceClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'retail.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } + }); + + it('value configured in code has priority over environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new modelserviceModule.v2alpha.ModelServiceClient({ + universeDomain: 'configured.example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'retail.configured.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } + }); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new modelserviceModule.v2alpha.ModelServiceClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); + }); - it('invokes getModel without error using callback', async () => { - const client = new modelserviceModule.v2alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.GetModelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.GetModelRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.Model() - ); - client.innerApiCalls.getModel = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getModel( - request, - (err?: Error|null, result?: protos.google.cloud.retail.v2alpha.IModel|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getModel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getModel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has port', () => { + const port = modelserviceModule.v2alpha.ModelServiceClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('invokes getModel with error', async () => { - const client = new modelserviceModule.v2alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.GetModelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.GetModelRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getModel = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getModel(request), expectedError); - const actualRequest = (client.innerApiCalls.getModel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getModel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('should create a client with no option', () => { + const client = new modelserviceModule.v2alpha.ModelServiceClient(); + assert(client); + }); - it('invokes getModel with closed client', async () => { - const client = new modelserviceModule.v2alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.GetModelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.GetModelRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getModel(request), expectedError); - }); + it('should create a client with gRPC fallback', () => { + const client = new modelserviceModule.v2alpha.ModelServiceClient({ + fallback: true, + }); + assert(client); }); - describe('pauseModel', () => { - it('invokes pauseModel without error', async () => { - const client = new modelserviceModule.v2alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.PauseModelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.PauseModelRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.Model() - ); - client.innerApiCalls.pauseModel = stubSimpleCall(expectedResponse); - const [response] = await client.pauseModel(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.pauseModel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.pauseModel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has initialize method and supports deferred initialization', async () => { + const client = new modelserviceModule.v2alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.modelServiceStub, undefined); + await client.initialize(); + assert(client.modelServiceStub); + }); - it('invokes pauseModel without error using callback', async () => { - const client = new modelserviceModule.v2alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.PauseModelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.PauseModelRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.Model() - ); - client.innerApiCalls.pauseModel = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.pauseModel( - request, - (err?: Error|null, result?: protos.google.cloud.retail.v2alpha.IModel|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.pauseModel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.pauseModel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('has close method for the initialized client', (done) => { + const client = new modelserviceModule.v2alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.modelServiceStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes pauseModel with error', async () => { - const client = new modelserviceModule.v2alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.PauseModelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.PauseModelRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.pauseModel = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.pauseModel(request), expectedError); - const actualRequest = (client.innerApiCalls.pauseModel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.pauseModel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('has close method for the non-initialized client', (done) => { + const client = new modelserviceModule.v2alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.modelServiceStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes pauseModel with closed client', async () => { - const client = new modelserviceModule.v2alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.PauseModelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.PauseModelRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.pauseModel(request), expectedError); - }); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new modelserviceModule.v2alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); }); - describe('resumeModel', () => { - it('invokes resumeModel without error', async () => { - const client = new modelserviceModule.v2alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ResumeModelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ResumeModelRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.Model() - ); - client.innerApiCalls.resumeModel = stubSimpleCall(expectedResponse); - const [response] = await client.resumeModel(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.resumeModel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.resumeModel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new modelserviceModule.v2alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } + }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + }); + + describe('getModel', () => { + it('invokes getModel without error', async () => { + const client = new modelserviceModule.v2alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.GetModelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.GetModelRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.Model(), + ); + client.innerApiCalls.getModel = stubSimpleCall(expectedResponse); + const [response] = await client.getModel(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getModel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getModel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes resumeModel without error using callback', async () => { - const client = new modelserviceModule.v2alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ResumeModelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ResumeModelRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.Model() - ); - client.innerApiCalls.resumeModel = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.resumeModel( - request, - (err?: Error|null, result?: protos.google.cloud.retail.v2alpha.IModel|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.resumeModel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.resumeModel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getModel without error using callback', async () => { + const client = new modelserviceModule.v2alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.GetModelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.GetModelRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.Model(), + ); + client.innerApiCalls.getModel = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getModel( + request, + ( + err?: Error | null, + result?: protos.google.cloud.retail.v2alpha.IModel | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getModel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getModel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes resumeModel with error', async () => { - const client = new modelserviceModule.v2alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ResumeModelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ResumeModelRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.resumeModel = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.resumeModel(request), expectedError); - const actualRequest = (client.innerApiCalls.resumeModel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.resumeModel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getModel with error', async () => { + const client = new modelserviceModule.v2alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.GetModelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.GetModelRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getModel = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.getModel(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getModel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getModel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes resumeModel with closed client', async () => { - const client = new modelserviceModule.v2alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ResumeModelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ResumeModelRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.resumeModel(request), expectedError); - }); + it('invokes getModel with closed client', async () => { + const client = new modelserviceModule.v2alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.GetModelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.GetModelRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getModel(request), expectedError); + }); + }); + + describe('pauseModel', () => { + it('invokes pauseModel without error', async () => { + const client = new modelserviceModule.v2alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.PauseModelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.PauseModelRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.Model(), + ); + client.innerApiCalls.pauseModel = stubSimpleCall(expectedResponse); + const [response] = await client.pauseModel(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.pauseModel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.pauseModel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('deleteModel', () => { - it('invokes deleteModel without error', async () => { - const client = new modelserviceModule.v2alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.DeleteModelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.DeleteModelRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteModel = stubSimpleCall(expectedResponse); - const [response] = await client.deleteModel(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteModel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteModel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes pauseModel without error using callback', async () => { + const client = new modelserviceModule.v2alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.PauseModelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.PauseModelRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.Model(), + ); + client.innerApiCalls.pauseModel = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.pauseModel( + request, + ( + err?: Error | null, + result?: protos.google.cloud.retail.v2alpha.IModel | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.pauseModel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.pauseModel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteModel without error using callback', async () => { - const client = new modelserviceModule.v2alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.DeleteModelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.DeleteModelRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteModel = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteModel( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteModel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteModel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes pauseModel with error', async () => { + const client = new modelserviceModule.v2alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.PauseModelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.PauseModelRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.pauseModel = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.pauseModel(request), expectedError); + const actualRequest = ( + client.innerApiCalls.pauseModel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.pauseModel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteModel with error', async () => { - const client = new modelserviceModule.v2alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.DeleteModelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.DeleteModelRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteModel = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteModel(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteModel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteModel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes pauseModel with closed client', async () => { + const client = new modelserviceModule.v2alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.PauseModelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.PauseModelRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.pauseModel(request), expectedError); + }); + }); + + describe('resumeModel', () => { + it('invokes resumeModel without error', async () => { + const client = new modelserviceModule.v2alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ResumeModelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ResumeModelRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.Model(), + ); + client.innerApiCalls.resumeModel = stubSimpleCall(expectedResponse); + const [response] = await client.resumeModel(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.resumeModel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.resumeModel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteModel with closed client', async () => { - const client = new modelserviceModule.v2alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.DeleteModelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.DeleteModelRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteModel(request), expectedError); - }); + it('invokes resumeModel without error using callback', async () => { + const client = new modelserviceModule.v2alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ResumeModelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ResumeModelRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.Model(), + ); + client.innerApiCalls.resumeModel = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.resumeModel( + request, + ( + err?: Error | null, + result?: protos.google.cloud.retail.v2alpha.IModel | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.resumeModel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.resumeModel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('updateModel', () => { - it('invokes updateModel without error', async () => { - const client = new modelserviceModule.v2alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.UpdateModelRequest() - ); - request.model ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.UpdateModelRequest', ['model', 'name']); - request.model.name = defaultValue1; - const expectedHeaderRequestParams = `model.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.Model() - ); - client.innerApiCalls.updateModel = stubSimpleCall(expectedResponse); - const [response] = await client.updateModel(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateModel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateModel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes resumeModel with error', async () => { + const client = new modelserviceModule.v2alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ResumeModelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ResumeModelRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.resumeModel = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.resumeModel(request), expectedError); + const actualRequest = ( + client.innerApiCalls.resumeModel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.resumeModel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateModel without error using callback', async () => { - const client = new modelserviceModule.v2alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.UpdateModelRequest() - ); - request.model ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.UpdateModelRequest', ['model', 'name']); - request.model.name = defaultValue1; - const expectedHeaderRequestParams = `model.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.Model() - ); - client.innerApiCalls.updateModel = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateModel( - request, - (err?: Error|null, result?: protos.google.cloud.retail.v2alpha.IModel|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateModel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateModel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes resumeModel with closed client', async () => { + const client = new modelserviceModule.v2alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ResumeModelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ResumeModelRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.resumeModel(request), expectedError); + }); + }); + + describe('deleteModel', () => { + it('invokes deleteModel without error', async () => { + const client = new modelserviceModule.v2alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.DeleteModelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.DeleteModelRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteModel = stubSimpleCall(expectedResponse); + const [response] = await client.deleteModel(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteModel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteModel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateModel with error', async () => { - const client = new modelserviceModule.v2alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.UpdateModelRequest() - ); - request.model ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.UpdateModelRequest', ['model', 'name']); - request.model.name = defaultValue1; - const expectedHeaderRequestParams = `model.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateModel = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateModel(request), expectedError); - const actualRequest = (client.innerApiCalls.updateModel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateModel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteModel without error using callback', async () => { + const client = new modelserviceModule.v2alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.DeleteModelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.DeleteModelRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteModel = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteModel( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteModel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteModel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateModel with closed client', async () => { - const client = new modelserviceModule.v2alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.UpdateModelRequest() - ); - request.model ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.UpdateModelRequest', ['model', 'name']); - request.model.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateModel(request), expectedError); - }); + it('invokes deleteModel with error', async () => { + const client = new modelserviceModule.v2alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.DeleteModelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.DeleteModelRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteModel = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.deleteModel(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteModel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteModel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('createModel', () => { - it('invokes createModel without error', async () => { - const client = new modelserviceModule.v2alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.CreateModelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.CreateModelRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.createModel = stubLongRunningCall(expectedResponse); - const [operation] = await client.createModel(request); - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createModel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createModel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteModel with closed client', async () => { + const client = new modelserviceModule.v2alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.DeleteModelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.DeleteModelRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.deleteModel(request), expectedError); + }); + }); + + describe('updateModel', () => { + it('invokes updateModel without error', async () => { + const client = new modelserviceModule.v2alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.UpdateModelRequest(), + ); + request.model ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.UpdateModelRequest', + ['model', 'name'], + ); + request.model.name = defaultValue1; + const expectedHeaderRequestParams = `model.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.Model(), + ); + client.innerApiCalls.updateModel = stubSimpleCall(expectedResponse); + const [response] = await client.updateModel(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateModel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateModel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createModel without error using callback', async () => { - const client = new modelserviceModule.v2alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.CreateModelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.CreateModelRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.createModel = stubLongRunningCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createModel( - request, - (err?: Error|null, - result?: LROperation|null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const operation = await promise as LROperation; - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createModel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createModel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateModel without error using callback', async () => { + const client = new modelserviceModule.v2alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.UpdateModelRequest(), + ); + request.model ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.UpdateModelRequest', + ['model', 'name'], + ); + request.model.name = defaultValue1; + const expectedHeaderRequestParams = `model.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.Model(), + ); + client.innerApiCalls.updateModel = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateModel( + request, + ( + err?: Error | null, + result?: protos.google.cloud.retail.v2alpha.IModel | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateModel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateModel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createModel with call error', async () => { - const client = new modelserviceModule.v2alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.CreateModelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.CreateModelRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createModel = stubLongRunningCall(undefined, expectedError); - await assert.rejects(client.createModel(request), expectedError); - const actualRequest = (client.innerApiCalls.createModel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createModel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateModel with error', async () => { + const client = new modelserviceModule.v2alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.UpdateModelRequest(), + ); + request.model ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.UpdateModelRequest', + ['model', 'name'], + ); + request.model.name = defaultValue1; + const expectedHeaderRequestParams = `model.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateModel = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.updateModel(request), expectedError); + const actualRequest = ( + client.innerApiCalls.updateModel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateModel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createModel with LRO error', async () => { - const client = new modelserviceModule.v2alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.CreateModelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.CreateModelRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createModel = stubLongRunningCall(undefined, undefined, expectedError); - const [operation] = await client.createModel(request); - await assert.rejects(operation.promise(), expectedError); - const actualRequest = (client.innerApiCalls.createModel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createModel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateModel with closed client', async () => { + const client = new modelserviceModule.v2alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.UpdateModelRequest(), + ); + request.model ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.UpdateModelRequest', + ['model', 'name'], + ); + request.model.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.updateModel(request), expectedError); + }); + }); + + describe('createModel', () => { + it('invokes createModel without error', async () => { + const client = new modelserviceModule.v2alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.CreateModelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.CreateModelRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.createModel = stubLongRunningCall(expectedResponse); + const [operation] = await client.createModel(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createModel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createModel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkCreateModelProgress without error', async () => { - const client = new modelserviceModule.v2alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedResponse = generateSampleMessage( - new operationsProtos.google.longrunning.Operation() - ); - expectedResponse.name = 'test'; - expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; - expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')} - - client.operationsClient.getOperation = stubSimpleCall(expectedResponse); - const decodedOperation = await client.checkCreateModelProgress(expectedResponse.name); - assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); - assert(decodedOperation.metadata); - assert((client.operationsClient.getOperation as SinonStub).getCall(0)); - }); + it('invokes createModel without error using callback', async () => { + const client = new modelserviceModule.v2alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.CreateModelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.CreateModelRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.createModel = + stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createModel( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.cloud.retail.v2alpha.IModel, + protos.google.cloud.retail.v2alpha.ICreateModelMetadata + > | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const operation = (await promise) as LROperation< + protos.google.cloud.retail.v2alpha.IModel, + protos.google.cloud.retail.v2alpha.ICreateModelMetadata + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createModel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createModel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkCreateModelProgress with error', async () => { - const client = new modelserviceModule.v2alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedError = new Error('expected'); - - client.operationsClient.getOperation = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.checkCreateModelProgress(''), expectedError); - assert((client.operationsClient.getOperation as SinonStub) - .getCall(0)); - }); + it('invokes createModel with call error', async () => { + const client = new modelserviceModule.v2alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.CreateModelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.CreateModelRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createModel = stubLongRunningCall( + undefined, + expectedError, + ); + await assert.rejects(client.createModel(request), expectedError); + const actualRequest = ( + client.innerApiCalls.createModel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createModel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('tuneModel', () => { - it('invokes tuneModel without error', async () => { - const client = new modelserviceModule.v2alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.TuneModelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.TuneModelRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.tuneModel = stubLongRunningCall(expectedResponse); - const [operation] = await client.tuneModel(request); - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.tuneModel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.tuneModel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createModel with LRO error', async () => { + const client = new modelserviceModule.v2alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.CreateModelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.CreateModelRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createModel = stubLongRunningCall( + undefined, + undefined, + expectedError, + ); + const [operation] = await client.createModel(request); + await assert.rejects(operation.promise(), expectedError); + const actualRequest = ( + client.innerApiCalls.createModel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createModel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes tuneModel without error using callback', async () => { - const client = new modelserviceModule.v2alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.TuneModelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.TuneModelRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.tuneModel = stubLongRunningCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.tuneModel( - request, - (err?: Error|null, - result?: LROperation|null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const operation = await promise as LROperation; - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.tuneModel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.tuneModel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes checkCreateModelProgress without error', async () => { + const client = new modelserviceModule.v2alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation(), + ); + expectedResponse.name = 'test'; + expectedResponse.response = { type_url: 'url', value: Buffer.from('') }; + expectedResponse.metadata = { type_url: 'url', value: Buffer.from('') }; + + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const decodedOperation = await client.checkCreateModelProgress( + expectedResponse.name, + ); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); - it('invokes tuneModel with call error', async () => { - const client = new modelserviceModule.v2alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.TuneModelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.TuneModelRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.tuneModel = stubLongRunningCall(undefined, expectedError); - await assert.rejects(client.tuneModel(request), expectedError); - const actualRequest = (client.innerApiCalls.tuneModel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.tuneModel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes checkCreateModelProgress with error', async () => { + const client = new modelserviceModule.v2alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const expectedError = new Error('expected'); + + client.operationsClient.getOperation = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.checkCreateModelProgress(''), expectedError); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + }); + + describe('tuneModel', () => { + it('invokes tuneModel without error', async () => { + const client = new modelserviceModule.v2alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.TuneModelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.TuneModelRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.tuneModel = stubLongRunningCall(expectedResponse); + const [operation] = await client.tuneModel(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.tuneModel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.tuneModel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes tuneModel with LRO error', async () => { - const client = new modelserviceModule.v2alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.TuneModelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.TuneModelRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.tuneModel = stubLongRunningCall(undefined, undefined, expectedError); - const [operation] = await client.tuneModel(request); - await assert.rejects(operation.promise(), expectedError); - const actualRequest = (client.innerApiCalls.tuneModel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.tuneModel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes tuneModel without error using callback', async () => { + const client = new modelserviceModule.v2alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.TuneModelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.TuneModelRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.tuneModel = + stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.tuneModel( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.cloud.retail.v2alpha.ITuneModelResponse, + protos.google.cloud.retail.v2alpha.ITuneModelMetadata + > | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const operation = (await promise) as LROperation< + protos.google.cloud.retail.v2alpha.ITuneModelResponse, + protos.google.cloud.retail.v2alpha.ITuneModelMetadata + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.tuneModel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.tuneModel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkTuneModelProgress without error', async () => { - const client = new modelserviceModule.v2alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedResponse = generateSampleMessage( - new operationsProtos.google.longrunning.Operation() - ); - expectedResponse.name = 'test'; - expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; - expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')} - - client.operationsClient.getOperation = stubSimpleCall(expectedResponse); - const decodedOperation = await client.checkTuneModelProgress(expectedResponse.name); - assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); - assert(decodedOperation.metadata); - assert((client.operationsClient.getOperation as SinonStub).getCall(0)); - }); + it('invokes tuneModel with call error', async () => { + const client = new modelserviceModule.v2alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.TuneModelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.TuneModelRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.tuneModel = stubLongRunningCall( + undefined, + expectedError, + ); + await assert.rejects(client.tuneModel(request), expectedError); + const actualRequest = ( + client.innerApiCalls.tuneModel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.tuneModel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkTuneModelProgress with error', async () => { - const client = new modelserviceModule.v2alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedError = new Error('expected'); - - client.operationsClient.getOperation = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.checkTuneModelProgress(''), expectedError); - assert((client.operationsClient.getOperation as SinonStub) - .getCall(0)); - }); + it('invokes tuneModel with LRO error', async () => { + const client = new modelserviceModule.v2alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.TuneModelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.TuneModelRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.tuneModel = stubLongRunningCall( + undefined, + undefined, + expectedError, + ); + const [operation] = await client.tuneModel(request); + await assert.rejects(operation.promise(), expectedError); + const actualRequest = ( + client.innerApiCalls.tuneModel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.tuneModel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('listModels', () => { - it('invokes listModels without error', async () => { - const client = new modelserviceModule.v2alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ListModelsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ListModelsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.retail.v2alpha.Model()), - generateSampleMessage(new protos.google.cloud.retail.v2alpha.Model()), - generateSampleMessage(new protos.google.cloud.retail.v2alpha.Model()), - ]; - client.innerApiCalls.listModels = stubSimpleCall(expectedResponse); - const [response] = await client.listModels(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listModels as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listModels as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes checkTuneModelProgress without error', async () => { + const client = new modelserviceModule.v2alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation(), + ); + expectedResponse.name = 'test'; + expectedResponse.response = { type_url: 'url', value: Buffer.from('') }; + expectedResponse.metadata = { type_url: 'url', value: Buffer.from('') }; + + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const decodedOperation = await client.checkTuneModelProgress( + expectedResponse.name, + ); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); - it('invokes listModels without error using callback', async () => { - const client = new modelserviceModule.v2alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ListModelsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ListModelsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.retail.v2alpha.Model()), - generateSampleMessage(new protos.google.cloud.retail.v2alpha.Model()), - generateSampleMessage(new protos.google.cloud.retail.v2alpha.Model()), - ]; - client.innerApiCalls.listModels = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listModels( - request, - (err?: Error|null, result?: protos.google.cloud.retail.v2alpha.IModel[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listModels as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listModels as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes checkTuneModelProgress with error', async () => { + const client = new modelserviceModule.v2alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const expectedError = new Error('expected'); + + client.operationsClient.getOperation = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.checkTuneModelProgress(''), expectedError); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + }); + + describe('listModels', () => { + it('invokes listModels without error', async () => { + const client = new modelserviceModule.v2alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ListModelsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ListModelsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.retail.v2alpha.Model()), + generateSampleMessage(new protos.google.cloud.retail.v2alpha.Model()), + generateSampleMessage(new protos.google.cloud.retail.v2alpha.Model()), + ]; + client.innerApiCalls.listModels = stubSimpleCall(expectedResponse); + const [response] = await client.listModels(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listModels as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listModels as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listModels with error', async () => { - const client = new modelserviceModule.v2alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ListModelsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ListModelsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listModels = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listModels(request), expectedError); - const actualRequest = (client.innerApiCalls.listModels as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listModels as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listModels without error using callback', async () => { + const client = new modelserviceModule.v2alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ListModelsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ListModelsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.retail.v2alpha.Model()), + generateSampleMessage(new protos.google.cloud.retail.v2alpha.Model()), + generateSampleMessage(new protos.google.cloud.retail.v2alpha.Model()), + ]; + client.innerApiCalls.listModels = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listModels( + request, + ( + err?: Error | null, + result?: protos.google.cloud.retail.v2alpha.IModel[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listModels as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listModels as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listModelsStream without error', async () => { - const client = new modelserviceModule.v2alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ListModelsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ListModelsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.retail.v2alpha.Model()), - generateSampleMessage(new protos.google.cloud.retail.v2alpha.Model()), - generateSampleMessage(new protos.google.cloud.retail.v2alpha.Model()), - ]; - client.descriptors.page.listModels.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listModelsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.cloud.retail.v2alpha.Model[] = []; - stream.on('data', (response: protos.google.cloud.retail.v2alpha.Model) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.listModels.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listModels, request)); - assert( - (client.descriptors.page.listModels.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listModels with error', async () => { + const client = new modelserviceModule.v2alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ListModelsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ListModelsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listModels = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listModels(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listModels as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listModels as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listModelsStream with error', async () => { - const client = new modelserviceModule.v2alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ListModelsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ListModelsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listModels.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listModelsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.cloud.retail.v2alpha.Model[] = []; - stream.on('data', (response: protos.google.cloud.retail.v2alpha.Model) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listModels.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listModels, request)); - assert( - (client.descriptors.page.listModels.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listModelsStream without error', async () => { + const client = new modelserviceModule.v2alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ListModelsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ListModelsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.retail.v2alpha.Model()), + generateSampleMessage(new protos.google.cloud.retail.v2alpha.Model()), + generateSampleMessage(new protos.google.cloud.retail.v2alpha.Model()), + ]; + client.descriptors.page.listModels.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listModelsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.cloud.retail.v2alpha.Model[] = []; + stream.on( + 'data', + (response: protos.google.cloud.retail.v2alpha.Model) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listModels.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listModels, request), + ); + assert( + (client.descriptors.page.listModels.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('uses async iteration with listModels without error', async () => { - const client = new modelserviceModule.v2alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ListModelsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ListModelsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.retail.v2alpha.Model()), - generateSampleMessage(new protos.google.cloud.retail.v2alpha.Model()), - generateSampleMessage(new protos.google.cloud.retail.v2alpha.Model()), - ]; - client.descriptors.page.listModels.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.cloud.retail.v2alpha.IModel[] = []; - const iterable = client.listModelsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listModels.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listModels.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listModelsStream with error', async () => { + const client = new modelserviceModule.v2alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ListModelsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ListModelsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listModels.createStream = stubPageStreamingCall( + undefined, + expectedError, + ); + const stream = client.listModelsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.cloud.retail.v2alpha.Model[] = []; + stream.on( + 'data', + (response: protos.google.cloud.retail.v2alpha.Model) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listModels.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listModels, request), + ); + assert( + (client.descriptors.page.listModels.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('uses async iteration with listModels with error', async () => { - const client = new modelserviceModule.v2alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ListModelsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ListModelsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listModels.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listModelsAsync(request); - await assert.rejects(async () => { - const responses: protos.google.cloud.retail.v2alpha.IModel[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listModels.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listModels.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listModels without error', async () => { + const client = new modelserviceModule.v2alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ListModelsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ListModelsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.retail.v2alpha.Model()), + generateSampleMessage(new protos.google.cloud.retail.v2alpha.Model()), + generateSampleMessage(new protos.google.cloud.retail.v2alpha.Model()), + ]; + client.descriptors.page.listModels.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.cloud.retail.v2alpha.IModel[] = []; + const iterable = client.listModelsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + (client.descriptors.page.listModels.asyncIterate as SinonStub).getCall( + 0, + ).args[1], + request, + ); + assert( + (client.descriptors.page.listModels.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); }); - describe('Path templates', () => { - - describe('alertConfig', async () => { - const fakePath = "/rendered/path/alertConfig"; - const expectedParameters = { - project: "projectValue", - }; - const client = new modelserviceModule.v2alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.alertConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.alertConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('alertConfigPath', () => { - const result = client.alertConfigPath("projectValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.alertConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromAlertConfigName', () => { - const result = client.matchProjectFromAlertConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.alertConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('uses async iteration with listModels with error', async () => { + const client = new modelserviceModule.v2alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ListModelsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ListModelsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listModels.asyncIterate = stubAsyncIterationCall( + undefined, + expectedError, + ); + const iterable = client.listModelsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.cloud.retail.v2alpha.IModel[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + (client.descriptors.page.listModels.asyncIterate as SinonStub).getCall( + 0, + ).args[1], + request, + ); + assert( + (client.descriptors.page.listModels.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + }); + + describe('Path templates', () => { + describe('alertConfig', async () => { + const fakePath = '/rendered/path/alertConfig'; + const expectedParameters = { + project: 'projectValue', + }; + const client = new modelserviceModule.v2alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.alertConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.alertConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('alertConfigPath', () => { + const result = client.alertConfigPath('projectValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.alertConfigPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromAlertConfigName', () => { + const result = client.matchProjectFromAlertConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.alertConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('attributesConfig', async () => { - const fakePath = "/rendered/path/attributesConfig"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - }; - const client = new modelserviceModule.v2alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.attributesConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.attributesConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('attributesConfigPath', () => { - const result = client.attributesConfigPath("projectValue", "locationValue", "catalogValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.attributesConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromAttributesConfigName', () => { - const result = client.matchProjectFromAttributesConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromAttributesConfigName', () => { - const result = client.matchLocationFromAttributesConfigName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromAttributesConfigName', () => { - const result = client.matchCatalogFromAttributesConfigName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('attributesConfig', async () => { + const fakePath = '/rendered/path/attributesConfig'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + }; + const client = new modelserviceModule.v2alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.attributesConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.attributesConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('attributesConfigPath', () => { + const result = client.attributesConfigPath( + 'projectValue', + 'locationValue', + 'catalogValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.attributesConfigPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromAttributesConfigName', () => { + const result = client.matchProjectFromAttributesConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromAttributesConfigName', () => { + const result = client.matchLocationFromAttributesConfigName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromAttributesConfigName', () => { + const result = client.matchCatalogFromAttributesConfigName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('branch', async () => { - const fakePath = "/rendered/path/branch"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - branch: "branchValue", - }; - const client = new modelserviceModule.v2alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.branchPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.branchPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('branchPath', () => { - const result = client.branchPath("projectValue", "locationValue", "catalogValue", "branchValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.branchPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromBranchName', () => { - const result = client.matchProjectFromBranchName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.branchPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromBranchName', () => { - const result = client.matchLocationFromBranchName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.branchPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromBranchName', () => { - const result = client.matchCatalogFromBranchName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.branchPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBranchFromBranchName', () => { - const result = client.matchBranchFromBranchName(fakePath); - assert.strictEqual(result, "branchValue"); - assert((client.pathTemplates.branchPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('branch', async () => { + const fakePath = '/rendered/path/branch'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + branch: 'branchValue', + }; + const client = new modelserviceModule.v2alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.branchPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.branchPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('branchPath', () => { + const result = client.branchPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'branchValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.branchPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromBranchName', () => { + const result = client.matchProjectFromBranchName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.branchPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromBranchName', () => { + const result = client.matchLocationFromBranchName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.branchPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromBranchName', () => { + const result = client.matchCatalogFromBranchName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.branchPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBranchFromBranchName', () => { + const result = client.matchBranchFromBranchName(fakePath); + assert.strictEqual(result, 'branchValue'); + assert( + (client.pathTemplates.branchPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('catalog', async () => { - const fakePath = "/rendered/path/catalog"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - }; - const client = new modelserviceModule.v2alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.catalogPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.catalogPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('catalogPath', () => { - const result = client.catalogPath("projectValue", "locationValue", "catalogValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.catalogPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromCatalogName', () => { - const result = client.matchProjectFromCatalogName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.catalogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromCatalogName', () => { - const result = client.matchLocationFromCatalogName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.catalogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromCatalogName', () => { - const result = client.matchCatalogFromCatalogName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.catalogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('catalog', async () => { + const fakePath = '/rendered/path/catalog'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + }; + const client = new modelserviceModule.v2alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.catalogPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.catalogPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('catalogPath', () => { + const result = client.catalogPath( + 'projectValue', + 'locationValue', + 'catalogValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.catalogPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromCatalogName', () => { + const result = client.matchProjectFromCatalogName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.catalogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromCatalogName', () => { + const result = client.matchLocationFromCatalogName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.catalogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromCatalogName', () => { + const result = client.matchCatalogFromCatalogName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.catalogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('completionConfig', async () => { - const fakePath = "/rendered/path/completionConfig"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - }; - const client = new modelserviceModule.v2alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.completionConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.completionConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('completionConfigPath', () => { - const result = client.completionConfigPath("projectValue", "locationValue", "catalogValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.completionConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromCompletionConfigName', () => { - const result = client.matchProjectFromCompletionConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.completionConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromCompletionConfigName', () => { - const result = client.matchLocationFromCompletionConfigName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.completionConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromCompletionConfigName', () => { - const result = client.matchCatalogFromCompletionConfigName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.completionConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('completionConfig', async () => { + const fakePath = '/rendered/path/completionConfig'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + }; + const client = new modelserviceModule.v2alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.completionConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.completionConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('completionConfigPath', () => { + const result = client.completionConfigPath( + 'projectValue', + 'locationValue', + 'catalogValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.completionConfigPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromCompletionConfigName', () => { + const result = client.matchProjectFromCompletionConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.completionConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromCompletionConfigName', () => { + const result = client.matchLocationFromCompletionConfigName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.completionConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromCompletionConfigName', () => { + const result = client.matchCatalogFromCompletionConfigName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.completionConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('control', async () => { - const fakePath = "/rendered/path/control"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - control: "controlValue", - }; - const client = new modelserviceModule.v2alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.controlPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.controlPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('controlPath', () => { - const result = client.controlPath("projectValue", "locationValue", "catalogValue", "controlValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.controlPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromControlName', () => { - const result = client.matchProjectFromControlName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.controlPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromControlName', () => { - const result = client.matchLocationFromControlName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.controlPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromControlName', () => { - const result = client.matchCatalogFromControlName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.controlPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchControlFromControlName', () => { - const result = client.matchControlFromControlName(fakePath); - assert.strictEqual(result, "controlValue"); - assert((client.pathTemplates.controlPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('control', async () => { + const fakePath = '/rendered/path/control'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + control: 'controlValue', + }; + const client = new modelserviceModule.v2alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.controlPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.controlPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('controlPath', () => { + const result = client.controlPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'controlValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.controlPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromControlName', () => { + const result = client.matchProjectFromControlName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.controlPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromControlName', () => { + const result = client.matchLocationFromControlName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.controlPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromControlName', () => { + const result = client.matchCatalogFromControlName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.controlPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchControlFromControlName', () => { + const result = client.matchControlFromControlName(fakePath); + assert.strictEqual(result, 'controlValue'); + assert( + (client.pathTemplates.controlPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('loggingConfig', async () => { - const fakePath = "/rendered/path/loggingConfig"; - const expectedParameters = { - project: "projectValue", - }; - const client = new modelserviceModule.v2alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.loggingConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.loggingConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('loggingConfigPath', () => { - const result = client.loggingConfigPath("projectValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.loggingConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromLoggingConfigName', () => { - const result = client.matchProjectFromLoggingConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.loggingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('loggingConfig', async () => { + const fakePath = '/rendered/path/loggingConfig'; + const expectedParameters = { + project: 'projectValue', + }; + const client = new modelserviceModule.v2alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.loggingConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.loggingConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('loggingConfigPath', () => { + const result = client.loggingConfigPath('projectValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.loggingConfigPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromLoggingConfigName', () => { + const result = client.matchProjectFromLoggingConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.loggingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('merchantCenterAccountLink', async () => { - const fakePath = "/rendered/path/merchantCenterAccountLink"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - merchant_center_account_link: "merchantCenterAccountLinkValue", - }; - const client = new modelserviceModule.v2alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.merchantCenterAccountLinkPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.merchantCenterAccountLinkPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('merchantCenterAccountLinkPath', () => { - const result = client.merchantCenterAccountLinkPath("projectValue", "locationValue", "catalogValue", "merchantCenterAccountLinkValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromMerchantCenterAccountLinkName', () => { - const result = client.matchProjectFromMerchantCenterAccountLinkName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromMerchantCenterAccountLinkName', () => { - const result = client.matchLocationFromMerchantCenterAccountLinkName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromMerchantCenterAccountLinkName', () => { - const result = client.matchCatalogFromMerchantCenterAccountLinkName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName', () => { - const result = client.matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName(fakePath); - assert.strictEqual(result, "merchantCenterAccountLinkValue"); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('merchantCenterAccountLink', async () => { + const fakePath = '/rendered/path/merchantCenterAccountLink'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + merchant_center_account_link: 'merchantCenterAccountLinkValue', + }; + const client = new modelserviceModule.v2alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.merchantCenterAccountLinkPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.merchantCenterAccountLinkPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('merchantCenterAccountLinkPath', () => { + const result = client.merchantCenterAccountLinkPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'merchantCenterAccountLinkValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromMerchantCenterAccountLinkName', () => { + const result = + client.matchProjectFromMerchantCenterAccountLinkName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromMerchantCenterAccountLinkName', () => { + const result = + client.matchLocationFromMerchantCenterAccountLinkName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromMerchantCenterAccountLinkName', () => { + const result = + client.matchCatalogFromMerchantCenterAccountLinkName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName', () => { + const result = + client.matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName( + fakePath, + ); + assert.strictEqual(result, 'merchantCenterAccountLinkValue'); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('model', async () => { - const fakePath = "/rendered/path/model"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - model: "modelValue", - }; - const client = new modelserviceModule.v2alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.modelPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.modelPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('modelPath', () => { - const result = client.modelPath("projectValue", "locationValue", "catalogValue", "modelValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.modelPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromModelName', () => { - const result = client.matchProjectFromModelName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromModelName', () => { - const result = client.matchLocationFromModelName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromModelName', () => { - const result = client.matchCatalogFromModelName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchModelFromModelName', () => { - const result = client.matchModelFromModelName(fakePath); - assert.strictEqual(result, "modelValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('model', async () => { + const fakePath = '/rendered/path/model'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + model: 'modelValue', + }; + const client = new modelserviceModule.v2alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.modelPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.modelPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('modelPath', () => { + const result = client.modelPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'modelValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.modelPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromModelName', () => { + const result = client.matchProjectFromModelName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromModelName', () => { + const result = client.matchLocationFromModelName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromModelName', () => { + const result = client.matchCatalogFromModelName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchModelFromModelName', () => { + const result = client.matchModelFromModelName(fakePath); + assert.strictEqual(result, 'modelValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('product', async () => { - const fakePath = "/rendered/path/product"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - branch: "branchValue", - product: "productValue", - }; - const client = new modelserviceModule.v2alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.productPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.productPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('productPath', () => { - const result = client.productPath("projectValue", "locationValue", "catalogValue", "branchValue", "productValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.productPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProductName', () => { - const result = client.matchProjectFromProductName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromProductName', () => { - const result = client.matchLocationFromProductName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromProductName', () => { - const result = client.matchCatalogFromProductName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBranchFromProductName', () => { - const result = client.matchBranchFromProductName(fakePath); - assert.strictEqual(result, "branchValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchProductFromProductName', () => { - const result = client.matchProductFromProductName(fakePath); - assert.strictEqual(result, "productValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('product', async () => { + const fakePath = '/rendered/path/product'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + branch: 'branchValue', + product: 'productValue', + }; + const client = new modelserviceModule.v2alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.productPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.productPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('productPath', () => { + const result = client.productPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'branchValue', + 'productValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.productPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProductName', () => { + const result = client.matchProjectFromProductName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromProductName', () => { + const result = client.matchLocationFromProductName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromProductName', () => { + const result = client.matchCatalogFromProductName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBranchFromProductName', () => { + const result = client.matchBranchFromProductName(fakePath); + assert.strictEqual(result, 'branchValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchProductFromProductName', () => { + const result = client.matchProductFromProductName(fakePath); + assert.strictEqual(result, 'productValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('retailProject', async () => { - const fakePath = "/rendered/path/retailProject"; - const expectedParameters = { - project: "projectValue", - }; - const client = new modelserviceModule.v2alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.retailProjectPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.retailProjectPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('retailProjectPath', () => { - const result = client.retailProjectPath("projectValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.retailProjectPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromRetailProjectName', () => { - const result = client.matchProjectFromRetailProjectName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.retailProjectPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('retailProject', async () => { + const fakePath = '/rendered/path/retailProject'; + const expectedParameters = { + project: 'projectValue', + }; + const client = new modelserviceModule.v2alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.retailProjectPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.retailProjectPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('retailProjectPath', () => { + const result = client.retailProjectPath('projectValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.retailProjectPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromRetailProjectName', () => { + const result = client.matchProjectFromRetailProjectName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.retailProjectPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('servingConfig', async () => { - const fakePath = "/rendered/path/servingConfig"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - serving_config: "servingConfigValue", - }; - const client = new modelserviceModule.v2alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.servingConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.servingConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('servingConfigPath', () => { - const result = client.servingConfigPath("projectValue", "locationValue", "catalogValue", "servingConfigValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.servingConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromServingConfigName', () => { - const result = client.matchProjectFromServingConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.servingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromServingConfigName', () => { - const result = client.matchLocationFromServingConfigName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.servingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromServingConfigName', () => { - const result = client.matchCatalogFromServingConfigName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.servingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServingConfigFromServingConfigName', () => { - const result = client.matchServingConfigFromServingConfigName(fakePath); - assert.strictEqual(result, "servingConfigValue"); - assert((client.pathTemplates.servingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('servingConfig', async () => { + const fakePath = '/rendered/path/servingConfig'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + serving_config: 'servingConfigValue', + }; + const client = new modelserviceModule.v2alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.servingConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.servingConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('servingConfigPath', () => { + const result = client.servingConfigPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'servingConfigValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.servingConfigPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromServingConfigName', () => { + const result = client.matchProjectFromServingConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.servingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromServingConfigName', () => { + const result = client.matchLocationFromServingConfigName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.servingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromServingConfigName', () => { + const result = client.matchCatalogFromServingConfigName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.servingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServingConfigFromServingConfigName', () => { + const result = client.matchServingConfigFromServingConfigName(fakePath); + assert.strictEqual(result, 'servingConfigValue'); + assert( + (client.pathTemplates.servingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/core/generator/gapic-generator-typescript/baselines/retail/test/gapic_prediction_service_v2alpha.ts.baseline b/core/generator/gapic-generator-typescript/baselines/retail/test/gapic_prediction_service_v2alpha.ts.baseline index 35230e3a276a..33ee0ef9b0ec 100644 --- a/core/generator/gapic-generator-typescript/baselines/retail/test/gapic_prediction_service_v2alpha.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/retail/test/gapic_prediction_service_v2alpha.ts.baseline @@ -19,867 +19,1199 @@ import * as protos from '../protos/protos'; import * as assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as predictionserviceModule from '../src'; -import {protobuf} from 'google-gax'; +import { protobuf } from 'google-gax'; // Dynamically loaded proto JSON is needed to get the type information // to fill in default values for request objects -const root = protobuf.Root.fromJSON(require('../protos/protos.json')).resolveAll(); +const root = protobuf.Root.fromJSON( + require('../protos/protos.json'), +).resolveAll(); // eslint-disable-next-line @typescript-eslint/no-unused-vars function getTypeDefaultValue(typeName: string, fields: string[]) { - let type = root.lookupType(typeName) as protobuf.Type; - for (const field of fields.slice(0, -1)) { - type = type.fields[field]?.resolvedType as protobuf.Type; - } - return type.fields[fields[fields.length - 1]]?.defaultValue; + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type.fields[field]?.resolvedType as protobuf.Type; + } + return type.fields[fields[fields.length - 1]]?.defaultValue; } function generateSampleMessage(instance: T) { - const filledObject = (instance.constructor as typeof protobuf.Message) - .toObject(instance as protobuf.Message, {defaults: true}); - return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, { defaults: true }); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; } function stubSimpleCall(response?: ResponseType, error?: Error) { - return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); } -function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { - return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +function stubSimpleCallWithCallback( + response?: ResponseType, + error?: Error, +) { + return error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); } describe('v2alpha.PredictionServiceClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new predictionserviceModule.v2alpha.PredictionServiceClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'retail.googleapis.com'); - }); - - it('has universeDomain', () => { - const client = new predictionserviceModule.v2alpha.PredictionServiceClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = + new predictionserviceModule.v2alpha.PredictionServiceClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'retail.googleapis.com'); + }); - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - it('throws DeprecationWarning if static servicePath is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const servicePath = predictionserviceModule.v2alpha.PredictionServiceClient.servicePath; - assert.strictEqual(servicePath, 'retail.googleapis.com'); - assert(stub.called); - stub.restore(); - }); + it('has universeDomain', () => { + const client = + new predictionserviceModule.v2alpha.PredictionServiceClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = predictionserviceModule.v2alpha.PredictionServiceClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'retail.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new predictionserviceModule.v2alpha.PredictionServiceClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'retail.example.com'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = + predictionserviceModule.v2alpha.PredictionServiceClient.servicePath; + assert.strictEqual(servicePath, 'retail.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + predictionserviceModule.v2alpha.PredictionServiceClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'retail.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = + new predictionserviceModule.v2alpha.PredictionServiceClient({ + universeDomain: 'example.com', }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'retail.example.com'); + }); - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new predictionserviceModule.v2alpha.PredictionServiceClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'retail.example.com'); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = + new predictionserviceModule.v2alpha.PredictionServiceClient({ + universe_domain: 'example.com', }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'retail.example.com'); + }); - if (typeof process === 'object' && 'env' in process) { - describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { - it('sets apiEndpoint from environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new predictionserviceModule.v2alpha.PredictionServiceClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'retail.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - - it('value configured in code has priority over environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new predictionserviceModule.v2alpha.PredictionServiceClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'retail.configured.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { new predictionserviceModule.v2alpha.PredictionServiceClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); + if (typeof process === 'object' && 'env' in process) { + describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { + it('sets apiEndpoint from environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = + new predictionserviceModule.v2alpha.PredictionServiceClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'retail.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - it('has port', () => { - const port = predictionserviceModule.v2alpha.PredictionServiceClient.port; - assert(port); - assert(typeof port === 'number'); + it('value configured in code has priority over environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = + new predictionserviceModule.v2alpha.PredictionServiceClient({ + universeDomain: 'configured.example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'retail.configured.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - - it('should create a client with no option', () => { - const client = new predictionserviceModule.v2alpha.PredictionServiceClient(); - assert(client); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new predictionserviceModule.v2alpha.PredictionServiceClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); + }); - it('should create a client with gRPC fallback', () => { - const client = new predictionserviceModule.v2alpha.PredictionServiceClient({ - fallback: true, - }); - assert(client); - }); + it('has port', () => { + const port = predictionserviceModule.v2alpha.PredictionServiceClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('has initialize method and supports deferred initialization', async () => { - const client = new predictionserviceModule.v2alpha.PredictionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.predictionServiceStub, undefined); - await client.initialize(); - assert(client.predictionServiceStub); - }); + it('should create a client with no option', () => { + const client = + new predictionserviceModule.v2alpha.PredictionServiceClient(); + assert(client); + }); - it('has close method for the initialized client', done => { - const client = new predictionserviceModule.v2alpha.PredictionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.predictionServiceStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); + it('should create a client with gRPC fallback', () => { + const client = + new predictionserviceModule.v2alpha.PredictionServiceClient({ + fallback: true, }); + assert(client); + }); - it('has close method for the non-initialized client', done => { - const client = new predictionserviceModule.v2alpha.PredictionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.predictionServiceStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); + it('has initialize method and supports deferred initialization', async () => { + const client = + new predictionserviceModule.v2alpha.PredictionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + assert.strictEqual(client.predictionServiceStub, undefined); + await client.initialize(); + assert(client.predictionServiceStub); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new predictionserviceModule.v2alpha.PredictionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + it('has close method for the initialized client', (done) => { + const client = + new predictionserviceModule.v2alpha.PredictionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); - - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new predictionserviceModule.v2alpha.PredictionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId((err?: Error|null, projectId?: string|null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } - }); - }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); + client.initialize().catch((err) => { + throw err; + }); + assert(client.predictionServiceStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); }); - describe('predict', () => { - it('invokes predict without error', async () => { - const client = new predictionserviceModule.v2alpha.PredictionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.PredictRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.PredictRequest', ['placement']); - request.placement = defaultValue1; - const expectedHeaderRequestParams = `placement=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.PredictResponse() - ); - client.innerApiCalls.predict = stubSimpleCall(expectedResponse); - const [response] = await client.predict(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.predict as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.predict as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('has close method for the non-initialized client', (done) => { + const client = + new predictionserviceModule.v2alpha.PredictionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); - - it('invokes predict without error using callback', async () => { - const client = new predictionserviceModule.v2alpha.PredictionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.PredictRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.PredictRequest', ['placement']); - request.placement = defaultValue1; - const expectedHeaderRequestParams = `placement=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.PredictResponse() - ); - client.innerApiCalls.predict = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.predict( - request, - (err?: Error|null, result?: protos.google.cloud.retail.v2alpha.IPredictResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.predict as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.predict as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + assert.strictEqual(client.predictionServiceStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes predict with error', async () => { - const client = new predictionserviceModule.v2alpha.PredictionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.PredictRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.PredictRequest', ['placement']); - request.placement = defaultValue1; - const expectedHeaderRequestParams = `placement=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.predict = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.predict(request), expectedError); - const actualRequest = (client.innerApiCalls.predict as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.predict as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = + new predictionserviceModule.v2alpha.PredictionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + }); - it('invokes predict with closed client', async () => { - const client = new predictionserviceModule.v2alpha.PredictionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.PredictRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.PredictRequest', ['placement']); - request.placement = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.predict(request), expectedError); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = + new predictionserviceModule.v2alpha.PredictionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } + }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); }); - - describe('Path templates', () => { - - describe('alertConfig', async () => { - const fakePath = "/rendered/path/alertConfig"; - const expectedParameters = { - project: "projectValue", - }; - const client = new predictionserviceModule.v2alpha.PredictionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.alertConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.alertConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('alertConfigPath', () => { - const result = client.alertConfigPath("projectValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.alertConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromAlertConfigName', () => { - const result = client.matchProjectFromAlertConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.alertConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + }); + + describe('predict', () => { + it('invokes predict without error', async () => { + const client = + new predictionserviceModule.v2alpha.PredictionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.PredictRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.PredictRequest', + ['placement'], + ); + request.placement = defaultValue1; + const expectedHeaderRequestParams = `placement=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.PredictResponse(), + ); + client.innerApiCalls.predict = stubSimpleCall(expectedResponse); + const [response] = await client.predict(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.predict as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.predict as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - describe('attributesConfig', async () => { - const fakePath = "/rendered/path/attributesConfig"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - }; - const client = new predictionserviceModule.v2alpha.PredictionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.attributesConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.attributesConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('attributesConfigPath', () => { - const result = client.attributesConfigPath("projectValue", "locationValue", "catalogValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.attributesConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromAttributesConfigName', () => { - const result = client.matchProjectFromAttributesConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromAttributesConfigName', () => { - const result = client.matchLocationFromAttributesConfigName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromAttributesConfigName', () => { - const result = client.matchCatalogFromAttributesConfigName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('invokes predict without error using callback', async () => { + const client = + new predictionserviceModule.v2alpha.PredictionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.PredictRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.PredictRequest', + ['placement'], + ); + request.placement = defaultValue1; + const expectedHeaderRequestParams = `placement=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.PredictResponse(), + ); + client.innerApiCalls.predict = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.predict( + request, + ( + err?: Error | null, + result?: protos.google.cloud.retail.v2alpha.IPredictResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.predict as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.predict as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - describe('branch', async () => { - const fakePath = "/rendered/path/branch"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - branch: "branchValue", - }; - const client = new predictionserviceModule.v2alpha.PredictionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.branchPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.branchPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('branchPath', () => { - const result = client.branchPath("projectValue", "locationValue", "catalogValue", "branchValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.branchPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromBranchName', () => { - const result = client.matchProjectFromBranchName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.branchPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromBranchName', () => { - const result = client.matchLocationFromBranchName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.branchPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromBranchName', () => { - const result = client.matchCatalogFromBranchName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.branchPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBranchFromBranchName', () => { - const result = client.matchBranchFromBranchName(fakePath); - assert.strictEqual(result, "branchValue"); - assert((client.pathTemplates.branchPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('invokes predict with error', async () => { + const client = + new predictionserviceModule.v2alpha.PredictionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.PredictRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.PredictRequest', + ['placement'], + ); + request.placement = defaultValue1; + const expectedHeaderRequestParams = `placement=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.predict = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.predict(request), expectedError); + const actualRequest = (client.innerApiCalls.predict as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.predict as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - describe('catalog', async () => { - const fakePath = "/rendered/path/catalog"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - }; - const client = new predictionserviceModule.v2alpha.PredictionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.catalogPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.catalogPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('catalogPath', () => { - const result = client.catalogPath("projectValue", "locationValue", "catalogValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.catalogPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromCatalogName', () => { - const result = client.matchProjectFromCatalogName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.catalogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromCatalogName', () => { - const result = client.matchLocationFromCatalogName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.catalogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromCatalogName', () => { - const result = client.matchCatalogFromCatalogName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.catalogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('invokes predict with closed client', async () => { + const client = + new predictionserviceModule.v2alpha.PredictionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); - - describe('completionConfig', async () => { - const fakePath = "/rendered/path/completionConfig"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - }; - const client = new predictionserviceModule.v2alpha.PredictionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.completionConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.completionConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('completionConfigPath', () => { - const result = client.completionConfigPath("projectValue", "locationValue", "catalogValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.completionConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromCompletionConfigName', () => { - const result = client.matchProjectFromCompletionConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.completionConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromCompletionConfigName', () => { - const result = client.matchLocationFromCompletionConfigName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.completionConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromCompletionConfigName', () => { - const result = client.matchCatalogFromCompletionConfigName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.completionConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.PredictRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.PredictRequest', + ['placement'], + ); + request.placement = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.predict(request), expectedError); + }); + }); + + describe('Path templates', () => { + describe('alertConfig', async () => { + const fakePath = '/rendered/path/alertConfig'; + const expectedParameters = { + project: 'projectValue', + }; + const client = + new predictionserviceModule.v2alpha.PredictionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + client.pathTemplates.alertConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.alertConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('alertConfigPath', () => { + const result = client.alertConfigPath('projectValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.alertConfigPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromAlertConfigName', () => { + const result = client.matchProjectFromAlertConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.alertConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('control', async () => { - const fakePath = "/rendered/path/control"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - control: "controlValue", - }; - const client = new predictionserviceModule.v2alpha.PredictionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.controlPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.controlPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('controlPath', () => { - const result = client.controlPath("projectValue", "locationValue", "catalogValue", "controlValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.controlPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromControlName', () => { - const result = client.matchProjectFromControlName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.controlPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromControlName', () => { - const result = client.matchLocationFromControlName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.controlPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromControlName', () => { - const result = client.matchCatalogFromControlName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.controlPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchControlFromControlName', () => { - const result = client.matchControlFromControlName(fakePath); - assert.strictEqual(result, "controlValue"); - assert((client.pathTemplates.controlPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('attributesConfig', async () => { + const fakePath = '/rendered/path/attributesConfig'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + }; + const client = + new predictionserviceModule.v2alpha.PredictionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + client.pathTemplates.attributesConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.attributesConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('attributesConfigPath', () => { + const result = client.attributesConfigPath( + 'projectValue', + 'locationValue', + 'catalogValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.attributesConfigPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromAttributesConfigName', () => { + const result = client.matchProjectFromAttributesConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromAttributesConfigName', () => { + const result = client.matchLocationFromAttributesConfigName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromAttributesConfigName', () => { + const result = client.matchCatalogFromAttributesConfigName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('loggingConfig', async () => { - const fakePath = "/rendered/path/loggingConfig"; - const expectedParameters = { - project: "projectValue", - }; - const client = new predictionserviceModule.v2alpha.PredictionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.loggingConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.loggingConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('loggingConfigPath', () => { - const result = client.loggingConfigPath("projectValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.loggingConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromLoggingConfigName', () => { - const result = client.matchProjectFromLoggingConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.loggingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('branch', async () => { + const fakePath = '/rendered/path/branch'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + branch: 'branchValue', + }; + const client = + new predictionserviceModule.v2alpha.PredictionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + client.pathTemplates.branchPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.branchPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('branchPath', () => { + const result = client.branchPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'branchValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.branchPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromBranchName', () => { + const result = client.matchProjectFromBranchName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.branchPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromBranchName', () => { + const result = client.matchLocationFromBranchName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.branchPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromBranchName', () => { + const result = client.matchCatalogFromBranchName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.branchPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBranchFromBranchName', () => { + const result = client.matchBranchFromBranchName(fakePath); + assert.strictEqual(result, 'branchValue'); + assert( + (client.pathTemplates.branchPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('merchantCenterAccountLink', async () => { - const fakePath = "/rendered/path/merchantCenterAccountLink"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - merchant_center_account_link: "merchantCenterAccountLinkValue", - }; - const client = new predictionserviceModule.v2alpha.PredictionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.merchantCenterAccountLinkPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.merchantCenterAccountLinkPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('merchantCenterAccountLinkPath', () => { - const result = client.merchantCenterAccountLinkPath("projectValue", "locationValue", "catalogValue", "merchantCenterAccountLinkValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromMerchantCenterAccountLinkName', () => { - const result = client.matchProjectFromMerchantCenterAccountLinkName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromMerchantCenterAccountLinkName', () => { - const result = client.matchLocationFromMerchantCenterAccountLinkName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromMerchantCenterAccountLinkName', () => { - const result = client.matchCatalogFromMerchantCenterAccountLinkName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName', () => { - const result = client.matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName(fakePath); - assert.strictEqual(result, "merchantCenterAccountLinkValue"); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('catalog', async () => { + const fakePath = '/rendered/path/catalog'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + }; + const client = + new predictionserviceModule.v2alpha.PredictionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + client.pathTemplates.catalogPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.catalogPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('catalogPath', () => { + const result = client.catalogPath( + 'projectValue', + 'locationValue', + 'catalogValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.catalogPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromCatalogName', () => { + const result = client.matchProjectFromCatalogName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.catalogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromCatalogName', () => { + const result = client.matchLocationFromCatalogName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.catalogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromCatalogName', () => { + const result = client.matchCatalogFromCatalogName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.catalogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('model', async () => { - const fakePath = "/rendered/path/model"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - model: "modelValue", - }; - const client = new predictionserviceModule.v2alpha.PredictionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.modelPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.modelPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('modelPath', () => { - const result = client.modelPath("projectValue", "locationValue", "catalogValue", "modelValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.modelPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromModelName', () => { - const result = client.matchProjectFromModelName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromModelName', () => { - const result = client.matchLocationFromModelName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromModelName', () => { - const result = client.matchCatalogFromModelName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchModelFromModelName', () => { - const result = client.matchModelFromModelName(fakePath); - assert.strictEqual(result, "modelValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('completionConfig', async () => { + const fakePath = '/rendered/path/completionConfig'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + }; + const client = + new predictionserviceModule.v2alpha.PredictionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + client.pathTemplates.completionConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.completionConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('completionConfigPath', () => { + const result = client.completionConfigPath( + 'projectValue', + 'locationValue', + 'catalogValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.completionConfigPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromCompletionConfigName', () => { + const result = client.matchProjectFromCompletionConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.completionConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromCompletionConfigName', () => { + const result = client.matchLocationFromCompletionConfigName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.completionConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromCompletionConfigName', () => { + const result = client.matchCatalogFromCompletionConfigName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.completionConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('product', async () => { - const fakePath = "/rendered/path/product"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - branch: "branchValue", - product: "productValue", - }; - const client = new predictionserviceModule.v2alpha.PredictionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.productPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.productPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('productPath', () => { - const result = client.productPath("projectValue", "locationValue", "catalogValue", "branchValue", "productValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.productPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProductName', () => { - const result = client.matchProjectFromProductName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromProductName', () => { - const result = client.matchLocationFromProductName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromProductName', () => { - const result = client.matchCatalogFromProductName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBranchFromProductName', () => { - const result = client.matchBranchFromProductName(fakePath); - assert.strictEqual(result, "branchValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchProductFromProductName', () => { - const result = client.matchProductFromProductName(fakePath); - assert.strictEqual(result, "productValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('control', async () => { + const fakePath = '/rendered/path/control'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + control: 'controlValue', + }; + const client = + new predictionserviceModule.v2alpha.PredictionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + client.pathTemplates.controlPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.controlPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('controlPath', () => { + const result = client.controlPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'controlValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.controlPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromControlName', () => { + const result = client.matchProjectFromControlName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.controlPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromControlName', () => { + const result = client.matchLocationFromControlName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.controlPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromControlName', () => { + const result = client.matchCatalogFromControlName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.controlPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchControlFromControlName', () => { + const result = client.matchControlFromControlName(fakePath); + assert.strictEqual(result, 'controlValue'); + assert( + (client.pathTemplates.controlPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('retailProject', async () => { - const fakePath = "/rendered/path/retailProject"; - const expectedParameters = { - project: "projectValue", - }; - const client = new predictionserviceModule.v2alpha.PredictionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.retailProjectPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.retailProjectPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('retailProjectPath', () => { - const result = client.retailProjectPath("projectValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.retailProjectPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromRetailProjectName', () => { - const result = client.matchProjectFromRetailProjectName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.retailProjectPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('loggingConfig', async () => { + const fakePath = '/rendered/path/loggingConfig'; + const expectedParameters = { + project: 'projectValue', + }; + const client = + new predictionserviceModule.v2alpha.PredictionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + client.pathTemplates.loggingConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.loggingConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('loggingConfigPath', () => { + const result = client.loggingConfigPath('projectValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.loggingConfigPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromLoggingConfigName', () => { + const result = client.matchProjectFromLoggingConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.loggingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('servingConfig', async () => { - const fakePath = "/rendered/path/servingConfig"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - serving_config: "servingConfigValue", - }; - const client = new predictionserviceModule.v2alpha.PredictionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.servingConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.servingConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('servingConfigPath', () => { - const result = client.servingConfigPath("projectValue", "locationValue", "catalogValue", "servingConfigValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.servingConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + describe('merchantCenterAccountLink', async () => { + const fakePath = '/rendered/path/merchantCenterAccountLink'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + merchant_center_account_link: 'merchantCenterAccountLinkValue', + }; + const client = + new predictionserviceModule.v2alpha.PredictionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.merchantCenterAccountLinkPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.merchantCenterAccountLinkPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('merchantCenterAccountLinkPath', () => { + const result = client.merchantCenterAccountLinkPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'merchantCenterAccountLinkValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromMerchantCenterAccountLinkName', () => { + const result = + client.matchProjectFromMerchantCenterAccountLinkName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromMerchantCenterAccountLinkName', () => { + const result = + client.matchLocationFromMerchantCenterAccountLinkName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromMerchantCenterAccountLinkName', () => { + const result = + client.matchCatalogFromMerchantCenterAccountLinkName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName', () => { + const result = + client.matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName( + fakePath, + ); + assert.strictEqual(result, 'merchantCenterAccountLinkValue'); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchProjectFromServingConfigName', () => { - const result = client.matchProjectFromServingConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.servingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('model', async () => { + const fakePath = '/rendered/path/model'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + model: 'modelValue', + }; + const client = + new predictionserviceModule.v2alpha.PredictionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.modelPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.modelPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('modelPath', () => { + const result = client.modelPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'modelValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.modelPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromModelName', () => { + const result = client.matchProjectFromModelName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromModelName', () => { + const result = client.matchLocationFromModelName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromModelName', () => { + const result = client.matchCatalogFromModelName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchModelFromModelName', () => { + const result = client.matchModelFromModelName(fakePath); + assert.strictEqual(result, 'modelValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchLocationFromServingConfigName', () => { - const result = client.matchLocationFromServingConfigName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.servingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('product', async () => { + const fakePath = '/rendered/path/product'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + branch: 'branchValue', + product: 'productValue', + }; + const client = + new predictionserviceModule.v2alpha.PredictionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.productPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.productPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('productPath', () => { + const result = client.productPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'branchValue', + 'productValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.productPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProductName', () => { + const result = client.matchProjectFromProductName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromProductName', () => { + const result = client.matchLocationFromProductName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromProductName', () => { + const result = client.matchCatalogFromProductName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBranchFromProductName', () => { + const result = client.matchBranchFromProductName(fakePath); + assert.strictEqual(result, 'branchValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchProductFromProductName', () => { + const result = client.matchProductFromProductName(fakePath); + assert.strictEqual(result, 'productValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchCatalogFromServingConfigName', () => { - const result = client.matchCatalogFromServingConfigName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.servingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('retailProject', async () => { + const fakePath = '/rendered/path/retailProject'; + const expectedParameters = { + project: 'projectValue', + }; + const client = + new predictionserviceModule.v2alpha.PredictionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.retailProjectPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.retailProjectPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('retailProjectPath', () => { + const result = client.retailProjectPath('projectValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.retailProjectPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromRetailProjectName', () => { + const result = client.matchProjectFromRetailProjectName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.retailProjectPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchServingConfigFromServingConfigName', () => { - const result = client.matchServingConfigFromServingConfigName(fakePath); - assert.strictEqual(result, "servingConfigValue"); - assert((client.pathTemplates.servingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('servingConfig', async () => { + const fakePath = '/rendered/path/servingConfig'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + serving_config: 'servingConfigValue', + }; + const client = + new predictionserviceModule.v2alpha.PredictionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + client.pathTemplates.servingConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.servingConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('servingConfigPath', () => { + const result = client.servingConfigPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'servingConfigValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.servingConfigPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromServingConfigName', () => { + const result = client.matchProjectFromServingConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.servingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromServingConfigName', () => { + const result = client.matchLocationFromServingConfigName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.servingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromServingConfigName', () => { + const result = client.matchCatalogFromServingConfigName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.servingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServingConfigFromServingConfigName', () => { + const result = client.matchServingConfigFromServingConfigName(fakePath); + assert.strictEqual(result, 'servingConfigValue'); + assert( + (client.pathTemplates.servingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/core/generator/gapic-generator-typescript/baselines/retail/test/gapic_product_service_v2alpha.ts.baseline b/core/generator/gapic-generator-typescript/baselines/retail/test/gapic_product_service_v2alpha.ts.baseline index d806c5a092c6..1e8e7f8bdaba 100644 --- a/core/generator/gapic-generator-typescript/baselines/retail/test/gapic_product_service_v2alpha.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/retail/test/gapic_product_service_v2alpha.ts.baseline @@ -19,2739 +19,3531 @@ import * as protos from '../protos/protos'; import * as assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as productserviceModule from '../src'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; -import {protobuf, LROperation, operationsProtos} from 'google-gax'; +import { protobuf, LROperation, operationsProtos } from 'google-gax'; // Dynamically loaded proto JSON is needed to get the type information // to fill in default values for request objects -const root = protobuf.Root.fromJSON(require('../protos/protos.json')).resolveAll(); +const root = protobuf.Root.fromJSON( + require('../protos/protos.json'), +).resolveAll(); // eslint-disable-next-line @typescript-eslint/no-unused-vars function getTypeDefaultValue(typeName: string, fields: string[]) { - let type = root.lookupType(typeName) as protobuf.Type; - for (const field of fields.slice(0, -1)) { - type = type.fields[field]?.resolvedType as protobuf.Type; - } - return type.fields[fields[fields.length - 1]]?.defaultValue; + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type.fields[field]?.resolvedType as protobuf.Type; + } + return type.fields[fields[fields.length - 1]]?.defaultValue; } function generateSampleMessage(instance: T) { - const filledObject = (instance.constructor as typeof protobuf.Message) - .toObject(instance as protobuf.Message, {defaults: true}); - return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, { defaults: true }); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; } function stubSimpleCall(response?: ResponseType, error?: Error) { - return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); } -function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { - return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +function stubSimpleCallWithCallback( + response?: ResponseType, + error?: Error, +) { + return error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); } -function stubLongRunningCall(response?: ResponseType, callError?: Error, lroError?: Error) { - const innerStub = lroError ? sinon.stub().rejects(lroError) : sinon.stub().resolves([response]); - const mockOperation = { - promise: innerStub, - }; - return callError ? sinon.stub().rejects(callError) : sinon.stub().resolves([mockOperation]); +function stubLongRunningCall( + response?: ResponseType, + callError?: Error, + lroError?: Error, +) { + const innerStub = lroError + ? sinon.stub().rejects(lroError) + : sinon.stub().resolves([response]); + const mockOperation = { + promise: innerStub, + }; + return callError + ? sinon.stub().rejects(callError) + : sinon.stub().resolves([mockOperation]); } -function stubLongRunningCallWithCallback(response?: ResponseType, callError?: Error, lroError?: Error) { - const innerStub = lroError ? sinon.stub().rejects(lroError) : sinon.stub().resolves([response]); - const mockOperation = { - promise: innerStub, - }; - return callError ? sinon.stub().callsArgWith(2, callError) : sinon.stub().callsArgWith(2, null, mockOperation); +function stubLongRunningCallWithCallback( + response?: ResponseType, + callError?: Error, + lroError?: Error, +) { + const innerStub = lroError + ? sinon.stub().rejects(lroError) + : sinon.stub().resolves([response]); + const mockOperation = { + promise: innerStub, + }; + return callError + ? sinon.stub().callsArgWith(2, callError) + : sinon.stub().callsArgWith(2, null, mockOperation); } -function stubPageStreamingCall(responses?: ResponseType[], error?: Error) { - const pagingStub = sinon.stub(); - if (responses) { - for (let i = 0; i < responses.length; ++i) { - pagingStub.onCall(i).callsArgWith(2, null, responses[i]); - } +function stubPageStreamingCall( + responses?: ResponseType[], + error?: Error, +) { + const pagingStub = sinon.stub(); + if (responses) { + for (let i = 0; i < responses.length; ++i) { + pagingStub.onCall(i).callsArgWith(2, null, responses[i]); } - const transformStub = error ? sinon.stub().callsArgWith(2, error) : pagingStub; - const mockStream = new PassThrough({ - objectMode: true, - transform: transformStub, - }); - // trigger as many responses as needed - if (responses) { - for (let i = 0; i < responses.length; ++i) { - setImmediate(() => { mockStream.write({}); }); - } - setImmediate(() => { mockStream.end(); }); - } else { - setImmediate(() => { mockStream.write({}); }); - setImmediate(() => { mockStream.end(); }); + } + const transformStub = error + ? sinon.stub().callsArgWith(2, error) + : pagingStub; + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + // trigger as many responses as needed + if (responses) { + for (let i = 0; i < responses.length; ++i) { + setImmediate(() => { + mockStream.write({}); + }); } - return sinon.stub().returns(mockStream); + setImmediate(() => { + mockStream.end(); + }); + } else { + setImmediate(() => { + mockStream.write({}); + }); + setImmediate(() => { + mockStream.end(); + }); + } + return sinon.stub().returns(mockStream); } -function stubAsyncIterationCall(responses?: ResponseType[], error?: Error) { - let counter = 0; - const asyncIterable = { - [Symbol.asyncIterator]() { - return { - async next() { - if (error) { - return Promise.reject(error); - } - if (counter >= responses!.length) { - return Promise.resolve({done: true, value: undefined}); - } - return Promise.resolve({done: false, value: responses![counter++]}); - } - }; - } - }; - return sinon.stub().returns(asyncIterable); +function stubAsyncIterationCall( + responses?: ResponseType[], + error?: Error, +) { + let counter = 0; + const asyncIterable = { + [Symbol.asyncIterator]() { + return { + async next() { + if (error) { + return Promise.reject(error); + } + if (counter >= responses!.length) { + return Promise.resolve({ done: true, value: undefined }); + } + return Promise.resolve({ done: false, value: responses![counter++] }); + }, + }; + }, + }; + return sinon.stub().returns(asyncIterable); } describe('v2alpha.ProductServiceClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new productserviceModule.v2alpha.ProductServiceClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'retail.googleapis.com'); - }); - - it('has universeDomain', () => { - const client = new productserviceModule.v2alpha.ProductServiceClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); - - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - it('throws DeprecationWarning if static servicePath is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const servicePath = productserviceModule.v2alpha.ProductServiceClient.servicePath; - assert.strictEqual(servicePath, 'retail.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = productserviceModule.v2alpha.ProductServiceClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'retail.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'retail.example.com'); - }); - - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'retail.example.com'); - }); - - if (typeof process === 'object' && 'env' in process) { - describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { - it('sets apiEndpoint from environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new productserviceModule.v2alpha.ProductServiceClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'retail.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - - it('value configured in code has priority over environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new productserviceModule.v2alpha.ProductServiceClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'retail.configured.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { new productserviceModule.v2alpha.ProductServiceClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); - - it('has port', () => { - const port = productserviceModule.v2alpha.ProductServiceClient.port; - assert(port); - assert(typeof port === 'number'); - }); - - it('should create a client with no option', () => { - const client = new productserviceModule.v2alpha.ProductServiceClient(); - assert(client); - }); - - it('should create a client with gRPC fallback', () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - fallback: true, - }); - assert(client); - }); - - it('has initialize method and supports deferred initialization', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.productServiceStub, undefined); - await client.initialize(); - assert(client.productServiceStub); - }); - - it('has close method for the initialized client', done => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.productServiceStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); - - it('has close method for the non-initialized client', done => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.productServiceStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); - - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); - }); - - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId((err?: Error|null, projectId?: string|null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } - }); - }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new productserviceModule.v2alpha.ProductServiceClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'retail.googleapis.com'); }); - describe('createProduct', () => { - it('invokes createProduct without error', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.CreateProductRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.CreateProductRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.Product() - ); - client.innerApiCalls.createProduct = stubSimpleCall(expectedResponse); - const [response] = await client.createProduct(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createProduct as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createProduct as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createProduct without error using callback', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.CreateProductRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.CreateProductRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.Product() - ); - client.innerApiCalls.createProduct = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createProduct( - request, - (err?: Error|null, result?: protos.google.cloud.retail.v2alpha.IProduct|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createProduct as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createProduct as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createProduct with error', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.CreateProductRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.CreateProductRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createProduct = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createProduct(request), expectedError); - const actualRequest = (client.innerApiCalls.createProduct as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createProduct as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has universeDomain', () => { + const client = new productserviceModule.v2alpha.ProductServiceClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - it('invokes createProduct with closed client', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.CreateProductRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.CreateProductRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createProduct(request), expectedError); - }); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = + productserviceModule.v2alpha.ProductServiceClient.servicePath; + assert.strictEqual(servicePath, 'retail.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + productserviceModule.v2alpha.ProductServiceClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'retail.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + universeDomain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'retail.example.com'); }); - describe('getProduct', () => { - it('invokes getProduct without error', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.GetProductRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.GetProductRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.Product() - ); - client.innerApiCalls.getProduct = stubSimpleCall(expectedResponse); - const [response] = await client.getProduct(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getProduct as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getProduct as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + universe_domain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'retail.example.com'); + }); - it('invokes getProduct without error using callback', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.GetProductRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.GetProductRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.Product() - ); - client.innerApiCalls.getProduct = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getProduct( - request, - (err?: Error|null, result?: protos.google.cloud.retail.v2alpha.IProduct|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getProduct as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getProduct as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + if (typeof process === 'object' && 'env' in process) { + describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { + it('sets apiEndpoint from environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = + new productserviceModule.v2alpha.ProductServiceClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'retail.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } + }); + + it('value configured in code has priority over environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new productserviceModule.v2alpha.ProductServiceClient({ + universeDomain: 'configured.example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'retail.configured.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } + }); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new productserviceModule.v2alpha.ProductServiceClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); + }); - it('invokes getProduct with error', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.GetProductRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.GetProductRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getProduct = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getProduct(request), expectedError); - const actualRequest = (client.innerApiCalls.getProduct as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getProduct as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has port', () => { + const port = productserviceModule.v2alpha.ProductServiceClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('invokes getProduct with closed client', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.GetProductRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.GetProductRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getProduct(request), expectedError); - }); + it('should create a client with no option', () => { + const client = new productserviceModule.v2alpha.ProductServiceClient(); + assert(client); }); - describe('updateProduct', () => { - it('invokes updateProduct without error', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.UpdateProductRequest() - ); - request.product ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.UpdateProductRequest', ['product', 'name']); - request.product.name = defaultValue1; - const expectedHeaderRequestParams = `product.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.Product() - ); - client.innerApiCalls.updateProduct = stubSimpleCall(expectedResponse); - const [response] = await client.updateProduct(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateProduct as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateProduct as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('should create a client with gRPC fallback', () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + fallback: true, + }); + assert(client); + }); - it('invokes updateProduct without error using callback', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.UpdateProductRequest() - ); - request.product ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.UpdateProductRequest', ['product', 'name']); - request.product.name = defaultValue1; - const expectedHeaderRequestParams = `product.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.Product() - ); - client.innerApiCalls.updateProduct = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateProduct( - request, - (err?: Error|null, result?: protos.google.cloud.retail.v2alpha.IProduct|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateProduct as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateProduct as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has initialize method and supports deferred initialization', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.productServiceStub, undefined); + await client.initialize(); + assert(client.productServiceStub); + }); - it('invokes updateProduct with error', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.UpdateProductRequest() - ); - request.product ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.UpdateProductRequest', ['product', 'name']); - request.product.name = defaultValue1; - const expectedHeaderRequestParams = `product.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateProduct = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateProduct(request), expectedError); - const actualRequest = (client.innerApiCalls.updateProduct as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateProduct as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('has close method for the initialized client', (done) => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.productServiceStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes updateProduct with closed client', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.UpdateProductRequest() - ); - request.product ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.UpdateProductRequest', ['product', 'name']); - request.product.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateProduct(request), expectedError); + it('has close method for the non-initialized client', (done) => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.productServiceStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); }); - describe('deleteProduct', () => { - it('invokes deleteProduct without error', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.DeleteProductRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.DeleteProductRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteProduct = stubSimpleCall(expectedResponse); - const [response] = await client.deleteProduct(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteProduct as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteProduct as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + }); - it('invokes deleteProduct without error using callback', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.DeleteProductRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.DeleteProductRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteProduct = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteProduct( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteProduct as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteProduct as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } + }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + }); + + describe('createProduct', () => { + it('invokes createProduct without error', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.CreateProductRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.CreateProductRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.Product(), + ); + client.innerApiCalls.createProduct = stubSimpleCall(expectedResponse); + const [response] = await client.createProduct(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createProduct as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createProduct as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteProduct with error', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.DeleteProductRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.DeleteProductRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteProduct = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteProduct(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteProduct as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteProduct as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createProduct without error using callback', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.CreateProductRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.CreateProductRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.Product(), + ); + client.innerApiCalls.createProduct = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createProduct( + request, + ( + err?: Error | null, + result?: protos.google.cloud.retail.v2alpha.IProduct | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createProduct as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createProduct as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteProduct with closed client', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.DeleteProductRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.DeleteProductRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteProduct(request), expectedError); - }); + it('invokes createProduct with error', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.CreateProductRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.CreateProductRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createProduct = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.createProduct(request), expectedError); + const actualRequest = ( + client.innerApiCalls.createProduct as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createProduct as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('purgeProducts', () => { - it('invokes purgeProducts without error', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.PurgeProductsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.PurgeProductsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.purgeProducts = stubLongRunningCall(expectedResponse); - const [operation] = await client.purgeProducts(request); - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.purgeProducts as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.purgeProducts as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createProduct with closed client', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.CreateProductRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.CreateProductRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.createProduct(request), expectedError); + }); + }); + + describe('getProduct', () => { + it('invokes getProduct without error', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.GetProductRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.GetProductRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.Product(), + ); + client.innerApiCalls.getProduct = stubSimpleCall(expectedResponse); + const [response] = await client.getProduct(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getProduct as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getProduct as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes purgeProducts without error using callback', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.PurgeProductsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.PurgeProductsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.purgeProducts = stubLongRunningCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.purgeProducts( - request, - (err?: Error|null, - result?: LROperation|null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const operation = await promise as LROperation; - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.purgeProducts as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.purgeProducts as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getProduct without error using callback', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.GetProductRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.GetProductRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.Product(), + ); + client.innerApiCalls.getProduct = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getProduct( + request, + ( + err?: Error | null, + result?: protos.google.cloud.retail.v2alpha.IProduct | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getProduct as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getProduct as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes purgeProducts with call error', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.PurgeProductsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.PurgeProductsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.purgeProducts = stubLongRunningCall(undefined, expectedError); - await assert.rejects(client.purgeProducts(request), expectedError); - const actualRequest = (client.innerApiCalls.purgeProducts as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.purgeProducts as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getProduct with error', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.GetProductRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.GetProductRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getProduct = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getProduct(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getProduct as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getProduct as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes purgeProducts with LRO error', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.PurgeProductsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.PurgeProductsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.purgeProducts = stubLongRunningCall(undefined, undefined, expectedError); - const [operation] = await client.purgeProducts(request); - await assert.rejects(operation.promise(), expectedError); - const actualRequest = (client.innerApiCalls.purgeProducts as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.purgeProducts as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getProduct with closed client', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.GetProductRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.GetProductRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getProduct(request), expectedError); + }); + }); + + describe('updateProduct', () => { + it('invokes updateProduct without error', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.UpdateProductRequest(), + ); + request.product ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.UpdateProductRequest', + ['product', 'name'], + ); + request.product.name = defaultValue1; + const expectedHeaderRequestParams = `product.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.Product(), + ); + client.innerApiCalls.updateProduct = stubSimpleCall(expectedResponse); + const [response] = await client.updateProduct(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateProduct as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateProduct as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkPurgeProductsProgress without error', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedResponse = generateSampleMessage( - new operationsProtos.google.longrunning.Operation() - ); - expectedResponse.name = 'test'; - expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; - expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')} - - client.operationsClient.getOperation = stubSimpleCall(expectedResponse); - const decodedOperation = await client.checkPurgeProductsProgress(expectedResponse.name); - assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); - assert(decodedOperation.metadata); - assert((client.operationsClient.getOperation as SinonStub).getCall(0)); - }); + it('invokes updateProduct without error using callback', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.UpdateProductRequest(), + ); + request.product ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.UpdateProductRequest', + ['product', 'name'], + ); + request.product.name = defaultValue1; + const expectedHeaderRequestParams = `product.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.Product(), + ); + client.innerApiCalls.updateProduct = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateProduct( + request, + ( + err?: Error | null, + result?: protos.google.cloud.retail.v2alpha.IProduct | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateProduct as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateProduct as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkPurgeProductsProgress with error', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedError = new Error('expected'); - - client.operationsClient.getOperation = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.checkPurgeProductsProgress(''), expectedError); - assert((client.operationsClient.getOperation as SinonStub) - .getCall(0)); - }); + it('invokes updateProduct with error', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.UpdateProductRequest(), + ); + request.product ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.UpdateProductRequest', + ['product', 'name'], + ); + request.product.name = defaultValue1; + const expectedHeaderRequestParams = `product.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateProduct = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.updateProduct(request), expectedError); + const actualRequest = ( + client.innerApiCalls.updateProduct as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateProduct as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('importProducts', () => { - it('invokes importProducts without error', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ImportProductsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ImportProductsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.importProducts = stubLongRunningCall(expectedResponse); - const [operation] = await client.importProducts(request); - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.importProducts as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.importProducts as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateProduct with closed client', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.UpdateProductRequest(), + ); + request.product ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.UpdateProductRequest', + ['product', 'name'], + ); + request.product.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.updateProduct(request), expectedError); + }); + }); + + describe('deleteProduct', () => { + it('invokes deleteProduct without error', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.DeleteProductRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.DeleteProductRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteProduct = stubSimpleCall(expectedResponse); + const [response] = await client.deleteProduct(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteProduct as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteProduct as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes importProducts without error using callback', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ImportProductsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ImportProductsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.importProducts = stubLongRunningCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.importProducts( - request, - (err?: Error|null, - result?: LROperation|null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const operation = await promise as LROperation; - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.importProducts as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.importProducts as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteProduct without error using callback', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.DeleteProductRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.DeleteProductRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteProduct = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteProduct( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteProduct as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteProduct as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes importProducts with call error', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ImportProductsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ImportProductsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.importProducts = stubLongRunningCall(undefined, expectedError); - await assert.rejects(client.importProducts(request), expectedError); - const actualRequest = (client.innerApiCalls.importProducts as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.importProducts as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteProduct with error', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.DeleteProductRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.DeleteProductRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteProduct = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.deleteProduct(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteProduct as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteProduct as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes importProducts with LRO error', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ImportProductsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ImportProductsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.importProducts = stubLongRunningCall(undefined, undefined, expectedError); - const [operation] = await client.importProducts(request); - await assert.rejects(operation.promise(), expectedError); - const actualRequest = (client.innerApiCalls.importProducts as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.importProducts as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteProduct with closed client', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.DeleteProductRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.DeleteProductRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.deleteProduct(request), expectedError); + }); + }); + + describe('purgeProducts', () => { + it('invokes purgeProducts without error', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.PurgeProductsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.PurgeProductsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.purgeProducts = + stubLongRunningCall(expectedResponse); + const [operation] = await client.purgeProducts(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.purgeProducts as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.purgeProducts as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkImportProductsProgress without error', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedResponse = generateSampleMessage( - new operationsProtos.google.longrunning.Operation() - ); - expectedResponse.name = 'test'; - expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; - expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')} - - client.operationsClient.getOperation = stubSimpleCall(expectedResponse); - const decodedOperation = await client.checkImportProductsProgress(expectedResponse.name); - assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); - assert(decodedOperation.metadata); - assert((client.operationsClient.getOperation as SinonStub).getCall(0)); - }); + it('invokes purgeProducts without error using callback', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.PurgeProductsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.PurgeProductsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.purgeProducts = + stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.purgeProducts( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.cloud.retail.v2alpha.IPurgeProductsResponse, + protos.google.cloud.retail.v2alpha.IPurgeProductsMetadata + > | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const operation = (await promise) as LROperation< + protos.google.cloud.retail.v2alpha.IPurgeProductsResponse, + protos.google.cloud.retail.v2alpha.IPurgeProductsMetadata + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.purgeProducts as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.purgeProducts as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkImportProductsProgress with error', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedError = new Error('expected'); - - client.operationsClient.getOperation = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.checkImportProductsProgress(''), expectedError); - assert((client.operationsClient.getOperation as SinonStub) - .getCall(0)); - }); + it('invokes purgeProducts with call error', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.PurgeProductsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.PurgeProductsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.purgeProducts = stubLongRunningCall( + undefined, + expectedError, + ); + await assert.rejects(client.purgeProducts(request), expectedError); + const actualRequest = ( + client.innerApiCalls.purgeProducts as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.purgeProducts as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('exportProducts', () => { - it('invokes exportProducts without error', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ExportProductsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ExportProductsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.exportProducts = stubLongRunningCall(expectedResponse); - const [operation] = await client.exportProducts(request); - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.exportProducts as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.exportProducts as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes purgeProducts with LRO error', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.PurgeProductsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.PurgeProductsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.purgeProducts = stubLongRunningCall( + undefined, + undefined, + expectedError, + ); + const [operation] = await client.purgeProducts(request); + await assert.rejects(operation.promise(), expectedError); + const actualRequest = ( + client.innerApiCalls.purgeProducts as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.purgeProducts as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes exportProducts without error using callback', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ExportProductsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ExportProductsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.exportProducts = stubLongRunningCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.exportProducts( - request, - (err?: Error|null, - result?: LROperation|null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const operation = await promise as LROperation; - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.exportProducts as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.exportProducts as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes checkPurgeProductsProgress without error', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation(), + ); + expectedResponse.name = 'test'; + expectedResponse.response = { type_url: 'url', value: Buffer.from('') }; + expectedResponse.metadata = { type_url: 'url', value: Buffer.from('') }; + + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const decodedOperation = await client.checkPurgeProductsProgress( + expectedResponse.name, + ); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); - it('invokes exportProducts with call error', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ExportProductsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ExportProductsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.exportProducts = stubLongRunningCall(undefined, expectedError); - await assert.rejects(client.exportProducts(request), expectedError); - const actualRequest = (client.innerApiCalls.exportProducts as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.exportProducts as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes checkPurgeProductsProgress with error', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const expectedError = new Error('expected'); + + client.operationsClient.getOperation = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.checkPurgeProductsProgress(''), + expectedError, + ); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + }); + + describe('importProducts', () => { + it('invokes importProducts without error', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ImportProductsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ImportProductsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.importProducts = + stubLongRunningCall(expectedResponse); + const [operation] = await client.importProducts(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.importProducts as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.importProducts as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes exportProducts with LRO error', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ExportProductsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ExportProductsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.exportProducts = stubLongRunningCall(undefined, undefined, expectedError); - const [operation] = await client.exportProducts(request); - await assert.rejects(operation.promise(), expectedError); - const actualRequest = (client.innerApiCalls.exportProducts as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.exportProducts as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes importProducts without error using callback', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ImportProductsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ImportProductsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.importProducts = + stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.importProducts( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.cloud.retail.v2alpha.IImportProductsResponse, + protos.google.cloud.retail.v2alpha.IImportMetadata + > | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const operation = (await promise) as LROperation< + protos.google.cloud.retail.v2alpha.IImportProductsResponse, + protos.google.cloud.retail.v2alpha.IImportMetadata + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.importProducts as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.importProducts as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkExportProductsProgress without error', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedResponse = generateSampleMessage( - new operationsProtos.google.longrunning.Operation() - ); - expectedResponse.name = 'test'; - expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; - expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')} - - client.operationsClient.getOperation = stubSimpleCall(expectedResponse); - const decodedOperation = await client.checkExportProductsProgress(expectedResponse.name); - assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); - assert(decodedOperation.metadata); - assert((client.operationsClient.getOperation as SinonStub).getCall(0)); - }); + it('invokes importProducts with call error', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ImportProductsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ImportProductsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.importProducts = stubLongRunningCall( + undefined, + expectedError, + ); + await assert.rejects(client.importProducts(request), expectedError); + const actualRequest = ( + client.innerApiCalls.importProducts as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.importProducts as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkExportProductsProgress with error', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedError = new Error('expected'); - - client.operationsClient.getOperation = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.checkExportProductsProgress(''), expectedError); - assert((client.operationsClient.getOperation as SinonStub) - .getCall(0)); - }); + it('invokes importProducts with LRO error', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ImportProductsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ImportProductsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.importProducts = stubLongRunningCall( + undefined, + undefined, + expectedError, + ); + const [operation] = await client.importProducts(request); + await assert.rejects(operation.promise(), expectedError); + const actualRequest = ( + client.innerApiCalls.importProducts as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.importProducts as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('setInventory', () => { - it('invokes setInventory without error', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.SetInventoryRequest() - ); - request.inventory ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.SetInventoryRequest', ['inventory', 'name']); - request.inventory.name = defaultValue1; - const expectedHeaderRequestParams = `inventory.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.setInventory = stubLongRunningCall(expectedResponse); - const [operation] = await client.setInventory(request); - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.setInventory as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.setInventory as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes checkImportProductsProgress without error', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation(), + ); + expectedResponse.name = 'test'; + expectedResponse.response = { type_url: 'url', value: Buffer.from('') }; + expectedResponse.metadata = { type_url: 'url', value: Buffer.from('') }; + + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const decodedOperation = await client.checkImportProductsProgress( + expectedResponse.name, + ); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); - it('invokes setInventory without error using callback', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.SetInventoryRequest() - ); - request.inventory ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.SetInventoryRequest', ['inventory', 'name']); - request.inventory.name = defaultValue1; - const expectedHeaderRequestParams = `inventory.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.setInventory = stubLongRunningCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.setInventory( - request, - (err?: Error|null, - result?: LROperation|null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const operation = await promise as LROperation; - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.setInventory as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.setInventory as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes checkImportProductsProgress with error', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const expectedError = new Error('expected'); + + client.operationsClient.getOperation = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.checkImportProductsProgress(''), + expectedError, + ); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + }); + + describe('exportProducts', () => { + it('invokes exportProducts without error', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ExportProductsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ExportProductsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.exportProducts = + stubLongRunningCall(expectedResponse); + const [operation] = await client.exportProducts(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.exportProducts as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.exportProducts as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes setInventory with call error', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.SetInventoryRequest() - ); - request.inventory ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.SetInventoryRequest', ['inventory', 'name']); - request.inventory.name = defaultValue1; - const expectedHeaderRequestParams = `inventory.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.setInventory = stubLongRunningCall(undefined, expectedError); - await assert.rejects(client.setInventory(request), expectedError); - const actualRequest = (client.innerApiCalls.setInventory as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.setInventory as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes exportProducts without error using callback', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ExportProductsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ExportProductsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.exportProducts = + stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.exportProducts( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.cloud.retail.v2alpha.IExportProductsResponse, + protos.google.cloud.retail.v2alpha.IExportMetadata + > | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const operation = (await promise) as LROperation< + protos.google.cloud.retail.v2alpha.IExportProductsResponse, + protos.google.cloud.retail.v2alpha.IExportMetadata + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.exportProducts as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.exportProducts as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes setInventory with LRO error', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.SetInventoryRequest() - ); - request.inventory ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.SetInventoryRequest', ['inventory', 'name']); - request.inventory.name = defaultValue1; - const expectedHeaderRequestParams = `inventory.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.setInventory = stubLongRunningCall(undefined, undefined, expectedError); - const [operation] = await client.setInventory(request); - await assert.rejects(operation.promise(), expectedError); - const actualRequest = (client.innerApiCalls.setInventory as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.setInventory as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes exportProducts with call error', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ExportProductsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ExportProductsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.exportProducts = stubLongRunningCall( + undefined, + expectedError, + ); + await assert.rejects(client.exportProducts(request), expectedError); + const actualRequest = ( + client.innerApiCalls.exportProducts as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.exportProducts as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkSetInventoryProgress without error', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedResponse = generateSampleMessage( - new operationsProtos.google.longrunning.Operation() - ); - expectedResponse.name = 'test'; - expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; - expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')} - - client.operationsClient.getOperation = stubSimpleCall(expectedResponse); - const decodedOperation = await client.checkSetInventoryProgress(expectedResponse.name); - assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); - assert(decodedOperation.metadata); - assert((client.operationsClient.getOperation as SinonStub).getCall(0)); - }); + it('invokes exportProducts with LRO error', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ExportProductsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ExportProductsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.exportProducts = stubLongRunningCall( + undefined, + undefined, + expectedError, + ); + const [operation] = await client.exportProducts(request); + await assert.rejects(operation.promise(), expectedError); + const actualRequest = ( + client.innerApiCalls.exportProducts as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.exportProducts as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkSetInventoryProgress with error', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedError = new Error('expected'); - - client.operationsClient.getOperation = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.checkSetInventoryProgress(''), expectedError); - assert((client.operationsClient.getOperation as SinonStub) - .getCall(0)); - }); + it('invokes checkExportProductsProgress without error', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation(), + ); + expectedResponse.name = 'test'; + expectedResponse.response = { type_url: 'url', value: Buffer.from('') }; + expectedResponse.metadata = { type_url: 'url', value: Buffer.from('') }; + + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const decodedOperation = await client.checkExportProductsProgress( + expectedResponse.name, + ); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); }); - describe('addFulfillmentPlaces', () => { - it('invokes addFulfillmentPlaces without error', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.AddFulfillmentPlacesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.AddFulfillmentPlacesRequest', ['product']); - request.product = defaultValue1; - const expectedHeaderRequestParams = `product=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.addFulfillmentPlaces = stubLongRunningCall(expectedResponse); - const [operation] = await client.addFulfillmentPlaces(request); - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.addFulfillmentPlaces as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.addFulfillmentPlaces as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes checkExportProductsProgress with error', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const expectedError = new Error('expected'); + + client.operationsClient.getOperation = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.checkExportProductsProgress(''), + expectedError, + ); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + }); + + describe('setInventory', () => { + it('invokes setInventory without error', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.SetInventoryRequest(), + ); + request.inventory ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.SetInventoryRequest', + ['inventory', 'name'], + ); + request.inventory.name = defaultValue1; + const expectedHeaderRequestParams = `inventory.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.setInventory = stubLongRunningCall(expectedResponse); + const [operation] = await client.setInventory(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.setInventory as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.setInventory as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes addFulfillmentPlaces without error using callback', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.AddFulfillmentPlacesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.AddFulfillmentPlacesRequest', ['product']); - request.product = defaultValue1; - const expectedHeaderRequestParams = `product=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.addFulfillmentPlaces = stubLongRunningCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.addFulfillmentPlaces( - request, - (err?: Error|null, - result?: LROperation|null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const operation = await promise as LROperation; - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.addFulfillmentPlaces as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.addFulfillmentPlaces as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes setInventory without error using callback', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.SetInventoryRequest(), + ); + request.inventory ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.SetInventoryRequest', + ['inventory', 'name'], + ); + request.inventory.name = defaultValue1; + const expectedHeaderRequestParams = `inventory.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.setInventory = + stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.setInventory( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.cloud.retail.v2alpha.ISetInventoryResponse, + protos.google.cloud.retail.v2alpha.ISetInventoryMetadata + > | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const operation = (await promise) as LROperation< + protos.google.cloud.retail.v2alpha.ISetInventoryResponse, + protos.google.cloud.retail.v2alpha.ISetInventoryMetadata + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.setInventory as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.setInventory as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes addFulfillmentPlaces with call error', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.AddFulfillmentPlacesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.AddFulfillmentPlacesRequest', ['product']); - request.product = defaultValue1; - const expectedHeaderRequestParams = `product=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.addFulfillmentPlaces = stubLongRunningCall(undefined, expectedError); - await assert.rejects(client.addFulfillmentPlaces(request), expectedError); - const actualRequest = (client.innerApiCalls.addFulfillmentPlaces as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.addFulfillmentPlaces as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes setInventory with call error', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.SetInventoryRequest(), + ); + request.inventory ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.SetInventoryRequest', + ['inventory', 'name'], + ); + request.inventory.name = defaultValue1; + const expectedHeaderRequestParams = `inventory.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.setInventory = stubLongRunningCall( + undefined, + expectedError, + ); + await assert.rejects(client.setInventory(request), expectedError); + const actualRequest = ( + client.innerApiCalls.setInventory as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.setInventory as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes addFulfillmentPlaces with LRO error', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.AddFulfillmentPlacesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.AddFulfillmentPlacesRequest', ['product']); - request.product = defaultValue1; - const expectedHeaderRequestParams = `product=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.addFulfillmentPlaces = stubLongRunningCall(undefined, undefined, expectedError); - const [operation] = await client.addFulfillmentPlaces(request); - await assert.rejects(operation.promise(), expectedError); - const actualRequest = (client.innerApiCalls.addFulfillmentPlaces as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.addFulfillmentPlaces as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes setInventory with LRO error', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.SetInventoryRequest(), + ); + request.inventory ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.SetInventoryRequest', + ['inventory', 'name'], + ); + request.inventory.name = defaultValue1; + const expectedHeaderRequestParams = `inventory.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.setInventory = stubLongRunningCall( + undefined, + undefined, + expectedError, + ); + const [operation] = await client.setInventory(request); + await assert.rejects(operation.promise(), expectedError); + const actualRequest = ( + client.innerApiCalls.setInventory as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.setInventory as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkAddFulfillmentPlacesProgress without error', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedResponse = generateSampleMessage( - new operationsProtos.google.longrunning.Operation() - ); - expectedResponse.name = 'test'; - expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; - expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')} - - client.operationsClient.getOperation = stubSimpleCall(expectedResponse); - const decodedOperation = await client.checkAddFulfillmentPlacesProgress(expectedResponse.name); - assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); - assert(decodedOperation.metadata); - assert((client.operationsClient.getOperation as SinonStub).getCall(0)); - }); + it('invokes checkSetInventoryProgress without error', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation(), + ); + expectedResponse.name = 'test'; + expectedResponse.response = { type_url: 'url', value: Buffer.from('') }; + expectedResponse.metadata = { type_url: 'url', value: Buffer.from('') }; + + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const decodedOperation = await client.checkSetInventoryProgress( + expectedResponse.name, + ); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); - it('invokes checkAddFulfillmentPlacesProgress with error', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedError = new Error('expected'); - - client.operationsClient.getOperation = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.checkAddFulfillmentPlacesProgress(''), expectedError); - assert((client.operationsClient.getOperation as SinonStub) - .getCall(0)); - }); + it('invokes checkSetInventoryProgress with error', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const expectedError = new Error('expected'); + + client.operationsClient.getOperation = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.checkSetInventoryProgress(''), expectedError); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + }); + + describe('addFulfillmentPlaces', () => { + it('invokes addFulfillmentPlaces without error', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.AddFulfillmentPlacesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.AddFulfillmentPlacesRequest', + ['product'], + ); + request.product = defaultValue1; + const expectedHeaderRequestParams = `product=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.addFulfillmentPlaces = + stubLongRunningCall(expectedResponse); + const [operation] = await client.addFulfillmentPlaces(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.addFulfillmentPlaces as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.addFulfillmentPlaces as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('removeFulfillmentPlaces', () => { - it('invokes removeFulfillmentPlaces without error', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.RemoveFulfillmentPlacesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.RemoveFulfillmentPlacesRequest', ['product']); - request.product = defaultValue1; - const expectedHeaderRequestParams = `product=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.removeFulfillmentPlaces = stubLongRunningCall(expectedResponse); - const [operation] = await client.removeFulfillmentPlaces(request); - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.removeFulfillmentPlaces as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.removeFulfillmentPlaces as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes addFulfillmentPlaces without error using callback', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.AddFulfillmentPlacesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.AddFulfillmentPlacesRequest', + ['product'], + ); + request.product = defaultValue1; + const expectedHeaderRequestParams = `product=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.addFulfillmentPlaces = + stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.addFulfillmentPlaces( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.cloud.retail.v2alpha.IAddFulfillmentPlacesResponse, + protos.google.cloud.retail.v2alpha.IAddFulfillmentPlacesMetadata + > | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const operation = (await promise) as LROperation< + protos.google.cloud.retail.v2alpha.IAddFulfillmentPlacesResponse, + protos.google.cloud.retail.v2alpha.IAddFulfillmentPlacesMetadata + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.addFulfillmentPlaces as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.addFulfillmentPlaces as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes removeFulfillmentPlaces without error using callback', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.RemoveFulfillmentPlacesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.RemoveFulfillmentPlacesRequest', ['product']); - request.product = defaultValue1; - const expectedHeaderRequestParams = `product=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.removeFulfillmentPlaces = stubLongRunningCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.removeFulfillmentPlaces( - request, - (err?: Error|null, - result?: LROperation|null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const operation = await promise as LROperation; - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.removeFulfillmentPlaces as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.removeFulfillmentPlaces as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes addFulfillmentPlaces with call error', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.AddFulfillmentPlacesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.AddFulfillmentPlacesRequest', + ['product'], + ); + request.product = defaultValue1; + const expectedHeaderRequestParams = `product=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.addFulfillmentPlaces = stubLongRunningCall( + undefined, + expectedError, + ); + await assert.rejects(client.addFulfillmentPlaces(request), expectedError); + const actualRequest = ( + client.innerApiCalls.addFulfillmentPlaces as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.addFulfillmentPlaces as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes removeFulfillmentPlaces with call error', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.RemoveFulfillmentPlacesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.RemoveFulfillmentPlacesRequest', ['product']); - request.product = defaultValue1; - const expectedHeaderRequestParams = `product=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.removeFulfillmentPlaces = stubLongRunningCall(undefined, expectedError); - await assert.rejects(client.removeFulfillmentPlaces(request), expectedError); - const actualRequest = (client.innerApiCalls.removeFulfillmentPlaces as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.removeFulfillmentPlaces as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes addFulfillmentPlaces with LRO error', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.AddFulfillmentPlacesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.AddFulfillmentPlacesRequest', + ['product'], + ); + request.product = defaultValue1; + const expectedHeaderRequestParams = `product=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.addFulfillmentPlaces = stubLongRunningCall( + undefined, + undefined, + expectedError, + ); + const [operation] = await client.addFulfillmentPlaces(request); + await assert.rejects(operation.promise(), expectedError); + const actualRequest = ( + client.innerApiCalls.addFulfillmentPlaces as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.addFulfillmentPlaces as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes removeFulfillmentPlaces with LRO error', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.RemoveFulfillmentPlacesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.RemoveFulfillmentPlacesRequest', ['product']); - request.product = defaultValue1; - const expectedHeaderRequestParams = `product=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.removeFulfillmentPlaces = stubLongRunningCall(undefined, undefined, expectedError); - const [operation] = await client.removeFulfillmentPlaces(request); - await assert.rejects(operation.promise(), expectedError); - const actualRequest = (client.innerApiCalls.removeFulfillmentPlaces as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.removeFulfillmentPlaces as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes checkAddFulfillmentPlacesProgress without error', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation(), + ); + expectedResponse.name = 'test'; + expectedResponse.response = { type_url: 'url', value: Buffer.from('') }; + expectedResponse.metadata = { type_url: 'url', value: Buffer.from('') }; + + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const decodedOperation = await client.checkAddFulfillmentPlacesProgress( + expectedResponse.name, + ); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); - it('invokes checkRemoveFulfillmentPlacesProgress without error', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedResponse = generateSampleMessage( - new operationsProtos.google.longrunning.Operation() - ); - expectedResponse.name = 'test'; - expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; - expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')} - - client.operationsClient.getOperation = stubSimpleCall(expectedResponse); - const decodedOperation = await client.checkRemoveFulfillmentPlacesProgress(expectedResponse.name); - assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); - assert(decodedOperation.metadata); - assert((client.operationsClient.getOperation as SinonStub).getCall(0)); - }); + it('invokes checkAddFulfillmentPlacesProgress with error', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const expectedError = new Error('expected'); + + client.operationsClient.getOperation = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.checkAddFulfillmentPlacesProgress(''), + expectedError, + ); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + }); + + describe('removeFulfillmentPlaces', () => { + it('invokes removeFulfillmentPlaces without error', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.RemoveFulfillmentPlacesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.RemoveFulfillmentPlacesRequest', + ['product'], + ); + request.product = defaultValue1; + const expectedHeaderRequestParams = `product=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.removeFulfillmentPlaces = + stubLongRunningCall(expectedResponse); + const [operation] = await client.removeFulfillmentPlaces(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.removeFulfillmentPlaces as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.removeFulfillmentPlaces as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkRemoveFulfillmentPlacesProgress with error', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedError = new Error('expected'); - - client.operationsClient.getOperation = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.checkRemoveFulfillmentPlacesProgress(''), expectedError); - assert((client.operationsClient.getOperation as SinonStub) - .getCall(0)); - }); + it('invokes removeFulfillmentPlaces without error using callback', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.RemoveFulfillmentPlacesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.RemoveFulfillmentPlacesRequest', + ['product'], + ); + request.product = defaultValue1; + const expectedHeaderRequestParams = `product=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.removeFulfillmentPlaces = + stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.removeFulfillmentPlaces( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.cloud.retail.v2alpha.IRemoveFulfillmentPlacesResponse, + protos.google.cloud.retail.v2alpha.IRemoveFulfillmentPlacesMetadata + > | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const operation = (await promise) as LROperation< + protos.google.cloud.retail.v2alpha.IRemoveFulfillmentPlacesResponse, + protos.google.cloud.retail.v2alpha.IRemoveFulfillmentPlacesMetadata + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.removeFulfillmentPlaces as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.removeFulfillmentPlaces as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('addLocalInventories', () => { - it('invokes addLocalInventories without error', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.AddLocalInventoriesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.AddLocalInventoriesRequest', ['product']); - request.product = defaultValue1; - const expectedHeaderRequestParams = `product=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.addLocalInventories = stubLongRunningCall(expectedResponse); - const [operation] = await client.addLocalInventories(request); - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.addLocalInventories as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.addLocalInventories as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes removeFulfillmentPlaces with call error', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.RemoveFulfillmentPlacesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.RemoveFulfillmentPlacesRequest', + ['product'], + ); + request.product = defaultValue1; + const expectedHeaderRequestParams = `product=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.removeFulfillmentPlaces = stubLongRunningCall( + undefined, + expectedError, + ); + await assert.rejects( + client.removeFulfillmentPlaces(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.removeFulfillmentPlaces as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.removeFulfillmentPlaces as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes addLocalInventories without error using callback', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.AddLocalInventoriesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.AddLocalInventoriesRequest', ['product']); - request.product = defaultValue1; - const expectedHeaderRequestParams = `product=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.addLocalInventories = stubLongRunningCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.addLocalInventories( - request, - (err?: Error|null, - result?: LROperation|null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const operation = await promise as LROperation; - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.addLocalInventories as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.addLocalInventories as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes removeFulfillmentPlaces with LRO error', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.RemoveFulfillmentPlacesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.RemoveFulfillmentPlacesRequest', + ['product'], + ); + request.product = defaultValue1; + const expectedHeaderRequestParams = `product=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.removeFulfillmentPlaces = stubLongRunningCall( + undefined, + undefined, + expectedError, + ); + const [operation] = await client.removeFulfillmentPlaces(request); + await assert.rejects(operation.promise(), expectedError); + const actualRequest = ( + client.innerApiCalls.removeFulfillmentPlaces as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.removeFulfillmentPlaces as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes addLocalInventories with call error', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.AddLocalInventoriesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.AddLocalInventoriesRequest', ['product']); - request.product = defaultValue1; - const expectedHeaderRequestParams = `product=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.addLocalInventories = stubLongRunningCall(undefined, expectedError); - await assert.rejects(client.addLocalInventories(request), expectedError); - const actualRequest = (client.innerApiCalls.addLocalInventories as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.addLocalInventories as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes checkRemoveFulfillmentPlacesProgress without error', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation(), + ); + expectedResponse.name = 'test'; + expectedResponse.response = { type_url: 'url', value: Buffer.from('') }; + expectedResponse.metadata = { type_url: 'url', value: Buffer.from('') }; + + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const decodedOperation = + await client.checkRemoveFulfillmentPlacesProgress( + expectedResponse.name, + ); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); - it('invokes addLocalInventories with LRO error', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.AddLocalInventoriesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.AddLocalInventoriesRequest', ['product']); - request.product = defaultValue1; - const expectedHeaderRequestParams = `product=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.addLocalInventories = stubLongRunningCall(undefined, undefined, expectedError); - const [operation] = await client.addLocalInventories(request); - await assert.rejects(operation.promise(), expectedError); - const actualRequest = (client.innerApiCalls.addLocalInventories as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.addLocalInventories as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes checkRemoveFulfillmentPlacesProgress with error', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const expectedError = new Error('expected'); + + client.operationsClient.getOperation = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.checkRemoveFulfillmentPlacesProgress(''), + expectedError, + ); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + }); + + describe('addLocalInventories', () => { + it('invokes addLocalInventories without error', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.AddLocalInventoriesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.AddLocalInventoriesRequest', + ['product'], + ); + request.product = defaultValue1; + const expectedHeaderRequestParams = `product=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.addLocalInventories = + stubLongRunningCall(expectedResponse); + const [operation] = await client.addLocalInventories(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.addLocalInventories as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.addLocalInventories as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkAddLocalInventoriesProgress without error', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedResponse = generateSampleMessage( - new operationsProtos.google.longrunning.Operation() - ); - expectedResponse.name = 'test'; - expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; - expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')} - - client.operationsClient.getOperation = stubSimpleCall(expectedResponse); - const decodedOperation = await client.checkAddLocalInventoriesProgress(expectedResponse.name); - assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); - assert(decodedOperation.metadata); - assert((client.operationsClient.getOperation as SinonStub).getCall(0)); - }); + it('invokes addLocalInventories without error using callback', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.AddLocalInventoriesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.AddLocalInventoriesRequest', + ['product'], + ); + request.product = defaultValue1; + const expectedHeaderRequestParams = `product=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.addLocalInventories = + stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.addLocalInventories( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.cloud.retail.v2alpha.IAddLocalInventoriesResponse, + protos.google.cloud.retail.v2alpha.IAddLocalInventoriesMetadata + > | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const operation = (await promise) as LROperation< + protos.google.cloud.retail.v2alpha.IAddLocalInventoriesResponse, + protos.google.cloud.retail.v2alpha.IAddLocalInventoriesMetadata + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.addLocalInventories as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.addLocalInventories as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkAddLocalInventoriesProgress with error', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedError = new Error('expected'); - - client.operationsClient.getOperation = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.checkAddLocalInventoriesProgress(''), expectedError); - assert((client.operationsClient.getOperation as SinonStub) - .getCall(0)); - }); + it('invokes addLocalInventories with call error', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.AddLocalInventoriesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.AddLocalInventoriesRequest', + ['product'], + ); + request.product = defaultValue1; + const expectedHeaderRequestParams = `product=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.addLocalInventories = stubLongRunningCall( + undefined, + expectedError, + ); + await assert.rejects(client.addLocalInventories(request), expectedError); + const actualRequest = ( + client.innerApiCalls.addLocalInventories as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.addLocalInventories as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('removeLocalInventories', () => { - it('invokes removeLocalInventories without error', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.RemoveLocalInventoriesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.RemoveLocalInventoriesRequest', ['product']); - request.product = defaultValue1; - const expectedHeaderRequestParams = `product=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.removeLocalInventories = stubLongRunningCall(expectedResponse); - const [operation] = await client.removeLocalInventories(request); - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.removeLocalInventories as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.removeLocalInventories as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes addLocalInventories with LRO error', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.AddLocalInventoriesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.AddLocalInventoriesRequest', + ['product'], + ); + request.product = defaultValue1; + const expectedHeaderRequestParams = `product=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.addLocalInventories = stubLongRunningCall( + undefined, + undefined, + expectedError, + ); + const [operation] = await client.addLocalInventories(request); + await assert.rejects(operation.promise(), expectedError); + const actualRequest = ( + client.innerApiCalls.addLocalInventories as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.addLocalInventories as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes removeLocalInventories without error using callback', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.RemoveLocalInventoriesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.RemoveLocalInventoriesRequest', ['product']); - request.product = defaultValue1; - const expectedHeaderRequestParams = `product=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.removeLocalInventories = stubLongRunningCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.removeLocalInventories( - request, - (err?: Error|null, - result?: LROperation|null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const operation = await promise as LROperation; - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.removeLocalInventories as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.removeLocalInventories as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes checkAddLocalInventoriesProgress without error', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation(), + ); + expectedResponse.name = 'test'; + expectedResponse.response = { type_url: 'url', value: Buffer.from('') }; + expectedResponse.metadata = { type_url: 'url', value: Buffer.from('') }; + + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const decodedOperation = await client.checkAddLocalInventoriesProgress( + expectedResponse.name, + ); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); - it('invokes removeLocalInventories with call error', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.RemoveLocalInventoriesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.RemoveLocalInventoriesRequest', ['product']); - request.product = defaultValue1; - const expectedHeaderRequestParams = `product=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.removeLocalInventories = stubLongRunningCall(undefined, expectedError); - await assert.rejects(client.removeLocalInventories(request), expectedError); - const actualRequest = (client.innerApiCalls.removeLocalInventories as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.removeLocalInventories as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes checkAddLocalInventoriesProgress with error', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const expectedError = new Error('expected'); + + client.operationsClient.getOperation = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.checkAddLocalInventoriesProgress(''), + expectedError, + ); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + }); + + describe('removeLocalInventories', () => { + it('invokes removeLocalInventories without error', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.RemoveLocalInventoriesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.RemoveLocalInventoriesRequest', + ['product'], + ); + request.product = defaultValue1; + const expectedHeaderRequestParams = `product=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.removeLocalInventories = + stubLongRunningCall(expectedResponse); + const [operation] = await client.removeLocalInventories(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.removeLocalInventories as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.removeLocalInventories as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes removeLocalInventories with LRO error', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.RemoveLocalInventoriesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.RemoveLocalInventoriesRequest', ['product']); - request.product = defaultValue1; - const expectedHeaderRequestParams = `product=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.removeLocalInventories = stubLongRunningCall(undefined, undefined, expectedError); - const [operation] = await client.removeLocalInventories(request); - await assert.rejects(operation.promise(), expectedError); - const actualRequest = (client.innerApiCalls.removeLocalInventories as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.removeLocalInventories as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes removeLocalInventories without error using callback', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.RemoveLocalInventoriesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.RemoveLocalInventoriesRequest', + ['product'], + ); + request.product = defaultValue1; + const expectedHeaderRequestParams = `product=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.removeLocalInventories = + stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.removeLocalInventories( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.cloud.retail.v2alpha.IRemoveLocalInventoriesResponse, + protos.google.cloud.retail.v2alpha.IRemoveLocalInventoriesMetadata + > | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const operation = (await promise) as LROperation< + protos.google.cloud.retail.v2alpha.IRemoveLocalInventoriesResponse, + protos.google.cloud.retail.v2alpha.IRemoveLocalInventoriesMetadata + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.removeLocalInventories as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.removeLocalInventories as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkRemoveLocalInventoriesProgress without error', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedResponse = generateSampleMessage( - new operationsProtos.google.longrunning.Operation() - ); - expectedResponse.name = 'test'; - expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; - expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')} - - client.operationsClient.getOperation = stubSimpleCall(expectedResponse); - const decodedOperation = await client.checkRemoveLocalInventoriesProgress(expectedResponse.name); - assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); - assert(decodedOperation.metadata); - assert((client.operationsClient.getOperation as SinonStub).getCall(0)); - }); + it('invokes removeLocalInventories with call error', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.RemoveLocalInventoriesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.RemoveLocalInventoriesRequest', + ['product'], + ); + request.product = defaultValue1; + const expectedHeaderRequestParams = `product=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.removeLocalInventories = stubLongRunningCall( + undefined, + expectedError, + ); + await assert.rejects( + client.removeLocalInventories(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.removeLocalInventories as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.removeLocalInventories as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkRemoveLocalInventoriesProgress with error', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedError = new Error('expected'); - - client.operationsClient.getOperation = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.checkRemoveLocalInventoriesProgress(''), expectedError); - assert((client.operationsClient.getOperation as SinonStub) - .getCall(0)); - }); + it('invokes removeLocalInventories with LRO error', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.RemoveLocalInventoriesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.RemoveLocalInventoriesRequest', + ['product'], + ); + request.product = defaultValue1; + const expectedHeaderRequestParams = `product=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.removeLocalInventories = stubLongRunningCall( + undefined, + undefined, + expectedError, + ); + const [operation] = await client.removeLocalInventories(request); + await assert.rejects(operation.promise(), expectedError); + const actualRequest = ( + client.innerApiCalls.removeLocalInventories as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.removeLocalInventories as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('listProducts', () => { - it('invokes listProducts without error', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ListProductsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ListProductsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.retail.v2alpha.Product()), - generateSampleMessage(new protos.google.cloud.retail.v2alpha.Product()), - generateSampleMessage(new protos.google.cloud.retail.v2alpha.Product()), - ]; - client.innerApiCalls.listProducts = stubSimpleCall(expectedResponse); - const [response] = await client.listProducts(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listProducts as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listProducts as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes checkRemoveLocalInventoriesProgress without error', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation(), + ); + expectedResponse.name = 'test'; + expectedResponse.response = { type_url: 'url', value: Buffer.from('') }; + expectedResponse.metadata = { type_url: 'url', value: Buffer.from('') }; + + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const decodedOperation = await client.checkRemoveLocalInventoriesProgress( + expectedResponse.name, + ); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); - it('invokes listProducts without error using callback', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ListProductsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ListProductsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.retail.v2alpha.Product()), - generateSampleMessage(new protos.google.cloud.retail.v2alpha.Product()), - generateSampleMessage(new protos.google.cloud.retail.v2alpha.Product()), - ]; - client.innerApiCalls.listProducts = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listProducts( - request, - (err?: Error|null, result?: protos.google.cloud.retail.v2alpha.IProduct[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listProducts as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listProducts as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes checkRemoveLocalInventoriesProgress with error', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const expectedError = new Error('expected'); + + client.operationsClient.getOperation = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.checkRemoveLocalInventoriesProgress(''), + expectedError, + ); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + }); + + describe('listProducts', () => { + it('invokes listProducts without error', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ListProductsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ListProductsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.retail.v2alpha.Product()), + generateSampleMessage(new protos.google.cloud.retail.v2alpha.Product()), + generateSampleMessage(new protos.google.cloud.retail.v2alpha.Product()), + ]; + client.innerApiCalls.listProducts = stubSimpleCall(expectedResponse); + const [response] = await client.listProducts(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listProducts as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listProducts as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listProducts with error', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ListProductsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ListProductsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listProducts = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listProducts(request), expectedError); - const actualRequest = (client.innerApiCalls.listProducts as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listProducts as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listProducts without error using callback', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ListProductsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ListProductsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.retail.v2alpha.Product()), + generateSampleMessage(new protos.google.cloud.retail.v2alpha.Product()), + generateSampleMessage(new protos.google.cloud.retail.v2alpha.Product()), + ]; + client.innerApiCalls.listProducts = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listProducts( + request, + ( + err?: Error | null, + result?: protos.google.cloud.retail.v2alpha.IProduct[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listProducts as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listProducts as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listProductsStream without error', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ListProductsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ListProductsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.retail.v2alpha.Product()), - generateSampleMessage(new protos.google.cloud.retail.v2alpha.Product()), - generateSampleMessage(new protos.google.cloud.retail.v2alpha.Product()), - ]; - client.descriptors.page.listProducts.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listProductsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.cloud.retail.v2alpha.Product[] = []; - stream.on('data', (response: protos.google.cloud.retail.v2alpha.Product) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.listProducts.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listProducts, request)); - assert( - (client.descriptors.page.listProducts.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listProducts with error', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ListProductsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ListProductsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listProducts = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listProducts(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listProducts as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listProducts as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listProductsStream with error', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ListProductsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ListProductsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listProducts.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listProductsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.cloud.retail.v2alpha.Product[] = []; - stream.on('data', (response: protos.google.cloud.retail.v2alpha.Product) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listProducts.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listProducts, request)); - assert( - (client.descriptors.page.listProducts.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listProductsStream without error', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ListProductsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ListProductsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.retail.v2alpha.Product()), + generateSampleMessage(new protos.google.cloud.retail.v2alpha.Product()), + generateSampleMessage(new protos.google.cloud.retail.v2alpha.Product()), + ]; + client.descriptors.page.listProducts.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listProductsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.cloud.retail.v2alpha.Product[] = []; + stream.on( + 'data', + (response: protos.google.cloud.retail.v2alpha.Product) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listProducts.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listProducts, request), + ); + assert( + (client.descriptors.page.listProducts.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('uses async iteration with listProducts without error', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ListProductsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ListProductsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.retail.v2alpha.Product()), - generateSampleMessage(new protos.google.cloud.retail.v2alpha.Product()), - generateSampleMessage(new protos.google.cloud.retail.v2alpha.Product()), - ]; - client.descriptors.page.listProducts.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.cloud.retail.v2alpha.IProduct[] = []; - const iterable = client.listProductsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listProducts.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listProducts.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listProductsStream with error', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ListProductsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ListProductsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listProducts.createStream = stubPageStreamingCall( + undefined, + expectedError, + ); + const stream = client.listProductsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.cloud.retail.v2alpha.Product[] = []; + stream.on( + 'data', + (response: protos.google.cloud.retail.v2alpha.Product) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listProducts.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listProducts, request), + ); + assert( + (client.descriptors.page.listProducts.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('uses async iteration with listProducts with error', async () => { - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ListProductsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ListProductsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listProducts.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listProductsAsync(request); - await assert.rejects(async () => { - const responses: protos.google.cloud.retail.v2alpha.IProduct[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listProducts.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listProducts.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listProducts without error', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ListProductsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ListProductsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.retail.v2alpha.Product()), + generateSampleMessage(new protos.google.cloud.retail.v2alpha.Product()), + generateSampleMessage(new protos.google.cloud.retail.v2alpha.Product()), + ]; + client.descriptors.page.listProducts.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.cloud.retail.v2alpha.IProduct[] = []; + const iterable = client.listProductsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listProducts.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listProducts.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); }); - describe('Path templates', () => { - - describe('alertConfig', async () => { - const fakePath = "/rendered/path/alertConfig"; - const expectedParameters = { - project: "projectValue", - }; - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.alertConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.alertConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('alertConfigPath', () => { - const result = client.alertConfigPath("projectValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.alertConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromAlertConfigName', () => { - const result = client.matchProjectFromAlertConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.alertConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('uses async iteration with listProducts with error', async () => { + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ListProductsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ListProductsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listProducts.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listProductsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.cloud.retail.v2alpha.IProduct[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listProducts.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listProducts.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + }); + + describe('Path templates', () => { + describe('alertConfig', async () => { + const fakePath = '/rendered/path/alertConfig'; + const expectedParameters = { + project: 'projectValue', + }; + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.alertConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.alertConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('alertConfigPath', () => { + const result = client.alertConfigPath('projectValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.alertConfigPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromAlertConfigName', () => { + const result = client.matchProjectFromAlertConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.alertConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('attributesConfig', async () => { - const fakePath = "/rendered/path/attributesConfig"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - }; - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.attributesConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.attributesConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('attributesConfigPath', () => { - const result = client.attributesConfigPath("projectValue", "locationValue", "catalogValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.attributesConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromAttributesConfigName', () => { - const result = client.matchProjectFromAttributesConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromAttributesConfigName', () => { - const result = client.matchLocationFromAttributesConfigName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromAttributesConfigName', () => { - const result = client.matchCatalogFromAttributesConfigName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('attributesConfig', async () => { + const fakePath = '/rendered/path/attributesConfig'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + }; + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.attributesConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.attributesConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('attributesConfigPath', () => { + const result = client.attributesConfigPath( + 'projectValue', + 'locationValue', + 'catalogValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.attributesConfigPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromAttributesConfigName', () => { + const result = client.matchProjectFromAttributesConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromAttributesConfigName', () => { + const result = client.matchLocationFromAttributesConfigName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromAttributesConfigName', () => { + const result = client.matchCatalogFromAttributesConfigName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('branch', async () => { - const fakePath = "/rendered/path/branch"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - branch: "branchValue", - }; - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.branchPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.branchPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('branchPath', () => { - const result = client.branchPath("projectValue", "locationValue", "catalogValue", "branchValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.branchPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromBranchName', () => { - const result = client.matchProjectFromBranchName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.branchPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromBranchName', () => { - const result = client.matchLocationFromBranchName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.branchPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromBranchName', () => { - const result = client.matchCatalogFromBranchName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.branchPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBranchFromBranchName', () => { - const result = client.matchBranchFromBranchName(fakePath); - assert.strictEqual(result, "branchValue"); - assert((client.pathTemplates.branchPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('branch', async () => { + const fakePath = '/rendered/path/branch'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + branch: 'branchValue', + }; + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.branchPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.branchPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('branchPath', () => { + const result = client.branchPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'branchValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.branchPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromBranchName', () => { + const result = client.matchProjectFromBranchName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.branchPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromBranchName', () => { + const result = client.matchLocationFromBranchName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.branchPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromBranchName', () => { + const result = client.matchCatalogFromBranchName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.branchPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBranchFromBranchName', () => { + const result = client.matchBranchFromBranchName(fakePath); + assert.strictEqual(result, 'branchValue'); + assert( + (client.pathTemplates.branchPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('catalog', async () => { - const fakePath = "/rendered/path/catalog"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - }; - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.catalogPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.catalogPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('catalogPath', () => { - const result = client.catalogPath("projectValue", "locationValue", "catalogValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.catalogPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromCatalogName', () => { - const result = client.matchProjectFromCatalogName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.catalogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromCatalogName', () => { - const result = client.matchLocationFromCatalogName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.catalogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromCatalogName', () => { - const result = client.matchCatalogFromCatalogName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.catalogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('catalog', async () => { + const fakePath = '/rendered/path/catalog'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + }; + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.catalogPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.catalogPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('catalogPath', () => { + const result = client.catalogPath( + 'projectValue', + 'locationValue', + 'catalogValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.catalogPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromCatalogName', () => { + const result = client.matchProjectFromCatalogName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.catalogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromCatalogName', () => { + const result = client.matchLocationFromCatalogName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.catalogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromCatalogName', () => { + const result = client.matchCatalogFromCatalogName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.catalogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('completionConfig', async () => { - const fakePath = "/rendered/path/completionConfig"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - }; - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.completionConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.completionConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('completionConfigPath', () => { - const result = client.completionConfigPath("projectValue", "locationValue", "catalogValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.completionConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromCompletionConfigName', () => { - const result = client.matchProjectFromCompletionConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.completionConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromCompletionConfigName', () => { - const result = client.matchLocationFromCompletionConfigName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.completionConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromCompletionConfigName', () => { - const result = client.matchCatalogFromCompletionConfigName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.completionConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('completionConfig', async () => { + const fakePath = '/rendered/path/completionConfig'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + }; + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.completionConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.completionConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('completionConfigPath', () => { + const result = client.completionConfigPath( + 'projectValue', + 'locationValue', + 'catalogValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.completionConfigPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromCompletionConfigName', () => { + const result = client.matchProjectFromCompletionConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.completionConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromCompletionConfigName', () => { + const result = client.matchLocationFromCompletionConfigName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.completionConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromCompletionConfigName', () => { + const result = client.matchCatalogFromCompletionConfigName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.completionConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('control', async () => { - const fakePath = "/rendered/path/control"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - control: "controlValue", - }; - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.controlPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.controlPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('controlPath', () => { - const result = client.controlPath("projectValue", "locationValue", "catalogValue", "controlValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.controlPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromControlName', () => { - const result = client.matchProjectFromControlName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.controlPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromControlName', () => { - const result = client.matchLocationFromControlName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.controlPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromControlName', () => { - const result = client.matchCatalogFromControlName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.controlPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchControlFromControlName', () => { - const result = client.matchControlFromControlName(fakePath); - assert.strictEqual(result, "controlValue"); - assert((client.pathTemplates.controlPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('control', async () => { + const fakePath = '/rendered/path/control'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + control: 'controlValue', + }; + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.controlPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.controlPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('controlPath', () => { + const result = client.controlPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'controlValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.controlPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromControlName', () => { + const result = client.matchProjectFromControlName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.controlPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromControlName', () => { + const result = client.matchLocationFromControlName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.controlPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromControlName', () => { + const result = client.matchCatalogFromControlName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.controlPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchControlFromControlName', () => { + const result = client.matchControlFromControlName(fakePath); + assert.strictEqual(result, 'controlValue'); + assert( + (client.pathTemplates.controlPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('loggingConfig', async () => { - const fakePath = "/rendered/path/loggingConfig"; - const expectedParameters = { - project: "projectValue", - }; - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.loggingConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.loggingConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('loggingConfigPath', () => { - const result = client.loggingConfigPath("projectValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.loggingConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromLoggingConfigName', () => { - const result = client.matchProjectFromLoggingConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.loggingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('loggingConfig', async () => { + const fakePath = '/rendered/path/loggingConfig'; + const expectedParameters = { + project: 'projectValue', + }; + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.loggingConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.loggingConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('loggingConfigPath', () => { + const result = client.loggingConfigPath('projectValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.loggingConfigPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromLoggingConfigName', () => { + const result = client.matchProjectFromLoggingConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.loggingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('merchantCenterAccountLink', async () => { - const fakePath = "/rendered/path/merchantCenterAccountLink"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - merchant_center_account_link: "merchantCenterAccountLinkValue", - }; - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.merchantCenterAccountLinkPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.merchantCenterAccountLinkPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('merchantCenterAccountLinkPath', () => { - const result = client.merchantCenterAccountLinkPath("projectValue", "locationValue", "catalogValue", "merchantCenterAccountLinkValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromMerchantCenterAccountLinkName', () => { - const result = client.matchProjectFromMerchantCenterAccountLinkName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromMerchantCenterAccountLinkName', () => { - const result = client.matchLocationFromMerchantCenterAccountLinkName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromMerchantCenterAccountLinkName', () => { - const result = client.matchCatalogFromMerchantCenterAccountLinkName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName', () => { - const result = client.matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName(fakePath); - assert.strictEqual(result, "merchantCenterAccountLinkValue"); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('merchantCenterAccountLink', async () => { + const fakePath = '/rendered/path/merchantCenterAccountLink'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + merchant_center_account_link: 'merchantCenterAccountLinkValue', + }; + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.merchantCenterAccountLinkPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.merchantCenterAccountLinkPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('merchantCenterAccountLinkPath', () => { + const result = client.merchantCenterAccountLinkPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'merchantCenterAccountLinkValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromMerchantCenterAccountLinkName', () => { + const result = + client.matchProjectFromMerchantCenterAccountLinkName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromMerchantCenterAccountLinkName', () => { + const result = + client.matchLocationFromMerchantCenterAccountLinkName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromMerchantCenterAccountLinkName', () => { + const result = + client.matchCatalogFromMerchantCenterAccountLinkName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName', () => { + const result = + client.matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName( + fakePath, + ); + assert.strictEqual(result, 'merchantCenterAccountLinkValue'); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('model', async () => { - const fakePath = "/rendered/path/model"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - model: "modelValue", - }; - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.modelPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.modelPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('modelPath', () => { - const result = client.modelPath("projectValue", "locationValue", "catalogValue", "modelValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.modelPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromModelName', () => { - const result = client.matchProjectFromModelName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromModelName', () => { - const result = client.matchLocationFromModelName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromModelName', () => { - const result = client.matchCatalogFromModelName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchModelFromModelName', () => { - const result = client.matchModelFromModelName(fakePath); - assert.strictEqual(result, "modelValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('model', async () => { + const fakePath = '/rendered/path/model'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + model: 'modelValue', + }; + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.modelPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.modelPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('modelPath', () => { + const result = client.modelPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'modelValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.modelPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromModelName', () => { + const result = client.matchProjectFromModelName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromModelName', () => { + const result = client.matchLocationFromModelName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromModelName', () => { + const result = client.matchCatalogFromModelName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchModelFromModelName', () => { + const result = client.matchModelFromModelName(fakePath); + assert.strictEqual(result, 'modelValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('product', async () => { - const fakePath = "/rendered/path/product"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - branch: "branchValue", - product: "productValue", - }; - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.productPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.productPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('productPath', () => { - const result = client.productPath("projectValue", "locationValue", "catalogValue", "branchValue", "productValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.productPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProductName', () => { - const result = client.matchProjectFromProductName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromProductName', () => { - const result = client.matchLocationFromProductName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromProductName', () => { - const result = client.matchCatalogFromProductName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBranchFromProductName', () => { - const result = client.matchBranchFromProductName(fakePath); - assert.strictEqual(result, "branchValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchProductFromProductName', () => { - const result = client.matchProductFromProductName(fakePath); - assert.strictEqual(result, "productValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('product', async () => { + const fakePath = '/rendered/path/product'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + branch: 'branchValue', + product: 'productValue', + }; + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.productPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.productPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('productPath', () => { + const result = client.productPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'branchValue', + 'productValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.productPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProductName', () => { + const result = client.matchProjectFromProductName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromProductName', () => { + const result = client.matchLocationFromProductName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromProductName', () => { + const result = client.matchCatalogFromProductName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBranchFromProductName', () => { + const result = client.matchBranchFromProductName(fakePath); + assert.strictEqual(result, 'branchValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchProductFromProductName', () => { + const result = client.matchProductFromProductName(fakePath); + assert.strictEqual(result, 'productValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('retailProject', async () => { - const fakePath = "/rendered/path/retailProject"; - const expectedParameters = { - project: "projectValue", - }; - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.retailProjectPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.retailProjectPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('retailProjectPath', () => { - const result = client.retailProjectPath("projectValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.retailProjectPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromRetailProjectName', () => { - const result = client.matchProjectFromRetailProjectName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.retailProjectPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('retailProject', async () => { + const fakePath = '/rendered/path/retailProject'; + const expectedParameters = { + project: 'projectValue', + }; + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.retailProjectPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.retailProjectPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('retailProjectPath', () => { + const result = client.retailProjectPath('projectValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.retailProjectPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromRetailProjectName', () => { + const result = client.matchProjectFromRetailProjectName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.retailProjectPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('servingConfig', async () => { - const fakePath = "/rendered/path/servingConfig"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - serving_config: "servingConfigValue", - }; - const client = new productserviceModule.v2alpha.ProductServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.servingConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.servingConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('servingConfigPath', () => { - const result = client.servingConfigPath("projectValue", "locationValue", "catalogValue", "servingConfigValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.servingConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromServingConfigName', () => { - const result = client.matchProjectFromServingConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.servingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromServingConfigName', () => { - const result = client.matchLocationFromServingConfigName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.servingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromServingConfigName', () => { - const result = client.matchCatalogFromServingConfigName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.servingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServingConfigFromServingConfigName', () => { - const result = client.matchServingConfigFromServingConfigName(fakePath); - assert.strictEqual(result, "servingConfigValue"); - assert((client.pathTemplates.servingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('servingConfig', async () => { + const fakePath = '/rendered/path/servingConfig'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + serving_config: 'servingConfigValue', + }; + const client = new productserviceModule.v2alpha.ProductServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.servingConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.servingConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('servingConfigPath', () => { + const result = client.servingConfigPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'servingConfigValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.servingConfigPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromServingConfigName', () => { + const result = client.matchProjectFromServingConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.servingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromServingConfigName', () => { + const result = client.matchLocationFromServingConfigName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.servingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromServingConfigName', () => { + const result = client.matchCatalogFromServingConfigName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.servingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServingConfigFromServingConfigName', () => { + const result = client.matchServingConfigFromServingConfigName(fakePath); + assert.strictEqual(result, 'servingConfigValue'); + assert( + (client.pathTemplates.servingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/core/generator/gapic-generator-typescript/baselines/retail/test/gapic_project_service_v2alpha.ts.baseline b/core/generator/gapic-generator-typescript/baselines/retail/test/gapic_project_service_v2alpha.ts.baseline index a0d3cc3643ef..a47b9867dbd4 100644 --- a/core/generator/gapic-generator-typescript/baselines/retail/test/gapic_project_service_v2alpha.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/retail/test/gapic_project_service_v2alpha.ts.baseline @@ -19,1723 +19,2246 @@ import * as protos from '../protos/protos'; import * as assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as projectserviceModule from '../src'; -import {protobuf, LROperation, operationsProtos} from 'google-gax'; +import { protobuf, LROperation, operationsProtos } from 'google-gax'; // Dynamically loaded proto JSON is needed to get the type information // to fill in default values for request objects -const root = protobuf.Root.fromJSON(require('../protos/protos.json')).resolveAll(); +const root = protobuf.Root.fromJSON( + require('../protos/protos.json'), +).resolveAll(); // eslint-disable-next-line @typescript-eslint/no-unused-vars function getTypeDefaultValue(typeName: string, fields: string[]) { - let type = root.lookupType(typeName) as protobuf.Type; - for (const field of fields.slice(0, -1)) { - type = type.fields[field]?.resolvedType as protobuf.Type; - } - return type.fields[fields[fields.length - 1]]?.defaultValue; + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type.fields[field]?.resolvedType as protobuf.Type; + } + return type.fields[fields[fields.length - 1]]?.defaultValue; } function generateSampleMessage(instance: T) { - const filledObject = (instance.constructor as typeof protobuf.Message) - .toObject(instance as protobuf.Message, {defaults: true}); - return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, { defaults: true }); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; } function stubSimpleCall(response?: ResponseType, error?: Error) { - return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); } -function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { - return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +function stubSimpleCallWithCallback( + response?: ResponseType, + error?: Error, +) { + return error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); } -function stubLongRunningCall(response?: ResponseType, callError?: Error, lroError?: Error) { - const innerStub = lroError ? sinon.stub().rejects(lroError) : sinon.stub().resolves([response]); - const mockOperation = { - promise: innerStub, - }; - return callError ? sinon.stub().rejects(callError) : sinon.stub().resolves([mockOperation]); +function stubLongRunningCall( + response?: ResponseType, + callError?: Error, + lroError?: Error, +) { + const innerStub = lroError + ? sinon.stub().rejects(lroError) + : sinon.stub().resolves([response]); + const mockOperation = { + promise: innerStub, + }; + return callError + ? sinon.stub().rejects(callError) + : sinon.stub().resolves([mockOperation]); } -function stubLongRunningCallWithCallback(response?: ResponseType, callError?: Error, lroError?: Error) { - const innerStub = lroError ? sinon.stub().rejects(lroError) : sinon.stub().resolves([response]); - const mockOperation = { - promise: innerStub, - }; - return callError ? sinon.stub().callsArgWith(2, callError) : sinon.stub().callsArgWith(2, null, mockOperation); +function stubLongRunningCallWithCallback( + response?: ResponseType, + callError?: Error, + lroError?: Error, +) { + const innerStub = lroError + ? sinon.stub().rejects(lroError) + : sinon.stub().resolves([response]); + const mockOperation = { + promise: innerStub, + }; + return callError + ? sinon.stub().callsArgWith(2, callError) + : sinon.stub().callsArgWith(2, null, mockOperation); } describe('v2alpha.ProjectServiceClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new projectserviceModule.v2alpha.ProjectServiceClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'retail.googleapis.com'); - }); - - it('has universeDomain', () => { - const client = new projectserviceModule.v2alpha.ProjectServiceClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); - - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - it('throws DeprecationWarning if static servicePath is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const servicePath = projectserviceModule.v2alpha.ProjectServiceClient.servicePath; - assert.strictEqual(servicePath, 'retail.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = projectserviceModule.v2alpha.ProjectServiceClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'retail.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new projectserviceModule.v2alpha.ProjectServiceClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'retail.example.com'); - }); - - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new projectserviceModule.v2alpha.ProjectServiceClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'retail.example.com'); - }); - - if (typeof process === 'object' && 'env' in process) { - describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { - it('sets apiEndpoint from environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new projectserviceModule.v2alpha.ProjectServiceClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'retail.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - - it('value configured in code has priority over environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new projectserviceModule.v2alpha.ProjectServiceClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'retail.configured.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { new projectserviceModule.v2alpha.ProjectServiceClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); - - it('has port', () => { - const port = projectserviceModule.v2alpha.ProjectServiceClient.port; - assert(port); - assert(typeof port === 'number'); - }); - - it('should create a client with no option', () => { - const client = new projectserviceModule.v2alpha.ProjectServiceClient(); - assert(client); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new projectserviceModule.v2alpha.ProjectServiceClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'retail.googleapis.com'); + }); - it('should create a client with gRPC fallback', () => { - const client = new projectserviceModule.v2alpha.ProjectServiceClient({ - fallback: true, - }); - assert(client); - }); + it('has universeDomain', () => { + const client = new projectserviceModule.v2alpha.ProjectServiceClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - it('has initialize method and supports deferred initialization', async () => { - const client = new projectserviceModule.v2alpha.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.projectServiceStub, undefined); - await client.initialize(); - assert(client.projectServiceStub); - }); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = + projectserviceModule.v2alpha.ProjectServiceClient.servicePath; + assert.strictEqual(servicePath, 'retail.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + projectserviceModule.v2alpha.ProjectServiceClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'retail.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = new projectserviceModule.v2alpha.ProjectServiceClient({ + universeDomain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'retail.example.com'); + }); - it('has close method for the initialized client', done => { - const client = new projectserviceModule.v2alpha.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.projectServiceStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = new projectserviceModule.v2alpha.ProjectServiceClient({ + universe_domain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'retail.example.com'); + }); - it('has close method for the non-initialized client', done => { - const client = new projectserviceModule.v2alpha.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.projectServiceStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); + if (typeof process === 'object' && 'env' in process) { + describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { + it('sets apiEndpoint from environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = + new projectserviceModule.v2alpha.ProjectServiceClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'retail.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new projectserviceModule.v2alpha.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + it('value configured in code has priority over environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new projectserviceModule.v2alpha.ProjectServiceClient({ + universeDomain: 'configured.example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'retail.configured.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new projectserviceModule.v2alpha.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId((err?: Error|null, projectId?: string|null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } - }); - }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new projectserviceModule.v2alpha.ProjectServiceClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); }); - describe('getProject', () => { - it('invokes getProject without error', async () => { - const client = new projectserviceModule.v2alpha.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.GetProjectRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.GetProjectRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.Project() - ); - client.innerApiCalls.getProject = stubSimpleCall(expectedResponse); - const [response] = await client.getProject(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getProject as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getProject as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getProject without error using callback', async () => { - const client = new projectserviceModule.v2alpha.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.GetProjectRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.GetProjectRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.Project() - ); - client.innerApiCalls.getProject = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getProject( - request, - (err?: Error|null, result?: protos.google.cloud.retail.v2alpha.IProject|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getProject as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getProject as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has port', () => { + const port = projectserviceModule.v2alpha.ProjectServiceClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('invokes getProject with error', async () => { - const client = new projectserviceModule.v2alpha.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.GetProjectRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.GetProjectRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getProject = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getProject(request), expectedError); - const actualRequest = (client.innerApiCalls.getProject as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getProject as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('should create a client with no option', () => { + const client = new projectserviceModule.v2alpha.ProjectServiceClient(); + assert(client); + }); - it('invokes getProject with closed client', async () => { - const client = new projectserviceModule.v2alpha.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.GetProjectRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.GetProjectRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getProject(request), expectedError); - }); + it('should create a client with gRPC fallback', () => { + const client = new projectserviceModule.v2alpha.ProjectServiceClient({ + fallback: true, + }); + assert(client); }); - describe('acceptTerms', () => { - it('invokes acceptTerms without error', async () => { - const client = new projectserviceModule.v2alpha.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.AcceptTermsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.AcceptTermsRequest', ['project']); - request.project = defaultValue1; - const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.Project() - ); - client.innerApiCalls.acceptTerms = stubSimpleCall(expectedResponse); - const [response] = await client.acceptTerms(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.acceptTerms as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.acceptTerms as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has initialize method and supports deferred initialization', async () => { + const client = new projectserviceModule.v2alpha.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.projectServiceStub, undefined); + await client.initialize(); + assert(client.projectServiceStub); + }); - it('invokes acceptTerms without error using callback', async () => { - const client = new projectserviceModule.v2alpha.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.AcceptTermsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.AcceptTermsRequest', ['project']); - request.project = defaultValue1; - const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.Project() - ); - client.innerApiCalls.acceptTerms = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.acceptTerms( - request, - (err?: Error|null, result?: protos.google.cloud.retail.v2alpha.IProject|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.acceptTerms as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.acceptTerms as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('has close method for the initialized client', (done) => { + const client = new projectserviceModule.v2alpha.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.projectServiceStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes acceptTerms with error', async () => { - const client = new projectserviceModule.v2alpha.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.AcceptTermsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.AcceptTermsRequest', ['project']); - request.project = defaultValue1; - const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.acceptTerms = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.acceptTerms(request), expectedError); - const actualRequest = (client.innerApiCalls.acceptTerms as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.acceptTerms as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('has close method for the non-initialized client', (done) => { + const client = new projectserviceModule.v2alpha.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.projectServiceStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes acceptTerms with closed client', async () => { - const client = new projectserviceModule.v2alpha.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.AcceptTermsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.AcceptTermsRequest', ['project']); - request.project = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.acceptTerms(request), expectedError); - }); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new projectserviceModule.v2alpha.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); }); - describe('listEnrolledSolutions', () => { - it('invokes listEnrolledSolutions without error', async () => { - const client = new projectserviceModule.v2alpha.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ListEnrolledSolutionsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ListEnrolledSolutionsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ListEnrolledSolutionsResponse() - ); - client.innerApiCalls.listEnrolledSolutions = stubSimpleCall(expectedResponse); - const [response] = await client.listEnrolledSolutions(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listEnrolledSolutions as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listEnrolledSolutions as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new projectserviceModule.v2alpha.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + }); + + describe('getProject', () => { + it('invokes getProject without error', async () => { + const client = new projectserviceModule.v2alpha.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.GetProjectRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.GetProjectRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.Project(), + ); + client.innerApiCalls.getProject = stubSimpleCall(expectedResponse); + const [response] = await client.getProject(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getProject as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getProject as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listEnrolledSolutions without error using callback', async () => { - const client = new projectserviceModule.v2alpha.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ListEnrolledSolutionsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ListEnrolledSolutionsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ListEnrolledSolutionsResponse() - ); - client.innerApiCalls.listEnrolledSolutions = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listEnrolledSolutions( - request, - (err?: Error|null, result?: protos.google.cloud.retail.v2alpha.IListEnrolledSolutionsResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listEnrolledSolutions as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listEnrolledSolutions as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getProject without error using callback', async () => { + const client = new projectserviceModule.v2alpha.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.GetProjectRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.GetProjectRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.Project(), + ); + client.innerApiCalls.getProject = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getProject( + request, + ( + err?: Error | null, + result?: protos.google.cloud.retail.v2alpha.IProject | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getProject as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getProject as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listEnrolledSolutions with error', async () => { - const client = new projectserviceModule.v2alpha.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ListEnrolledSolutionsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ListEnrolledSolutionsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listEnrolledSolutions = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listEnrolledSolutions(request), expectedError); - const actualRequest = (client.innerApiCalls.listEnrolledSolutions as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listEnrolledSolutions as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getProject with error', async () => { + const client = new projectserviceModule.v2alpha.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.GetProjectRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.GetProjectRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getProject = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getProject(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getProject as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getProject as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listEnrolledSolutions with closed client', async () => { - const client = new projectserviceModule.v2alpha.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ListEnrolledSolutionsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ListEnrolledSolutionsRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.listEnrolledSolutions(request), expectedError); - }); + it('invokes getProject with closed client', async () => { + const client = new projectserviceModule.v2alpha.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.GetProjectRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.GetProjectRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getProject(request), expectedError); + }); + }); + + describe('acceptTerms', () => { + it('invokes acceptTerms without error', async () => { + const client = new projectserviceModule.v2alpha.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.AcceptTermsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.AcceptTermsRequest', + ['project'], + ); + request.project = defaultValue1; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.Project(), + ); + client.innerApiCalls.acceptTerms = stubSimpleCall(expectedResponse); + const [response] = await client.acceptTerms(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.acceptTerms as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.acceptTerms as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('getLoggingConfig', () => { - it('invokes getLoggingConfig without error', async () => { - const client = new projectserviceModule.v2alpha.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.GetLoggingConfigRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.GetLoggingConfigRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.LoggingConfig() - ); - client.innerApiCalls.getLoggingConfig = stubSimpleCall(expectedResponse); - const [response] = await client.getLoggingConfig(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getLoggingConfig as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getLoggingConfig as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes acceptTerms without error using callback', async () => { + const client = new projectserviceModule.v2alpha.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.AcceptTermsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.AcceptTermsRequest', + ['project'], + ); + request.project = defaultValue1; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.Project(), + ); + client.innerApiCalls.acceptTerms = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.acceptTerms( + request, + ( + err?: Error | null, + result?: protos.google.cloud.retail.v2alpha.IProject | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.acceptTerms as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.acceptTerms as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getLoggingConfig without error using callback', async () => { - const client = new projectserviceModule.v2alpha.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.GetLoggingConfigRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.GetLoggingConfigRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.LoggingConfig() - ); - client.innerApiCalls.getLoggingConfig = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getLoggingConfig( - request, - (err?: Error|null, result?: protos.google.cloud.retail.v2alpha.ILoggingConfig|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getLoggingConfig as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getLoggingConfig as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes acceptTerms with error', async () => { + const client = new projectserviceModule.v2alpha.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.AcceptTermsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.AcceptTermsRequest', + ['project'], + ); + request.project = defaultValue1; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.acceptTerms = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.acceptTerms(request), expectedError); + const actualRequest = ( + client.innerApiCalls.acceptTerms as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.acceptTerms as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getLoggingConfig with error', async () => { - const client = new projectserviceModule.v2alpha.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.GetLoggingConfigRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.GetLoggingConfigRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getLoggingConfig = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getLoggingConfig(request), expectedError); - const actualRequest = (client.innerApiCalls.getLoggingConfig as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getLoggingConfig as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes acceptTerms with closed client', async () => { + const client = new projectserviceModule.v2alpha.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.AcceptTermsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.AcceptTermsRequest', + ['project'], + ); + request.project = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.acceptTerms(request), expectedError); + }); + }); + + describe('listEnrolledSolutions', () => { + it('invokes listEnrolledSolutions without error', async () => { + const client = new projectserviceModule.v2alpha.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ListEnrolledSolutionsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ListEnrolledSolutionsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ListEnrolledSolutionsResponse(), + ); + client.innerApiCalls.listEnrolledSolutions = + stubSimpleCall(expectedResponse); + const [response] = await client.listEnrolledSolutions(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listEnrolledSolutions as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listEnrolledSolutions as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getLoggingConfig with closed client', async () => { - const client = new projectserviceModule.v2alpha.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.GetLoggingConfigRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.GetLoggingConfigRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getLoggingConfig(request), expectedError); - }); + it('invokes listEnrolledSolutions without error using callback', async () => { + const client = new projectserviceModule.v2alpha.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ListEnrolledSolutionsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ListEnrolledSolutionsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ListEnrolledSolutionsResponse(), + ); + client.innerApiCalls.listEnrolledSolutions = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listEnrolledSolutions( + request, + ( + err?: Error | null, + result?: protos.google.cloud.retail.v2alpha.IListEnrolledSolutionsResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listEnrolledSolutions as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listEnrolledSolutions as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('updateLoggingConfig', () => { - it('invokes updateLoggingConfig without error', async () => { - const client = new projectserviceModule.v2alpha.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.UpdateLoggingConfigRequest() - ); - request.loggingConfig ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.UpdateLoggingConfigRequest', ['loggingConfig', 'name']); - request.loggingConfig.name = defaultValue1; - const expectedHeaderRequestParams = `logging_config.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.LoggingConfig() - ); - client.innerApiCalls.updateLoggingConfig = stubSimpleCall(expectedResponse); - const [response] = await client.updateLoggingConfig(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateLoggingConfig as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateLoggingConfig as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listEnrolledSolutions with error', async () => { + const client = new projectserviceModule.v2alpha.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ListEnrolledSolutionsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ListEnrolledSolutionsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listEnrolledSolutions = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.listEnrolledSolutions(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.listEnrolledSolutions as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listEnrolledSolutions as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateLoggingConfig without error using callback', async () => { - const client = new projectserviceModule.v2alpha.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.UpdateLoggingConfigRequest() - ); - request.loggingConfig ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.UpdateLoggingConfigRequest', ['loggingConfig', 'name']); - request.loggingConfig.name = defaultValue1; - const expectedHeaderRequestParams = `logging_config.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.LoggingConfig() - ); - client.innerApiCalls.updateLoggingConfig = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateLoggingConfig( - request, - (err?: Error|null, result?: protos.google.cloud.retail.v2alpha.ILoggingConfig|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateLoggingConfig as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateLoggingConfig as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listEnrolledSolutions with closed client', async () => { + const client = new projectserviceModule.v2alpha.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ListEnrolledSolutionsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ListEnrolledSolutionsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.listEnrolledSolutions(request), + expectedError, + ); + }); + }); + + describe('getLoggingConfig', () => { + it('invokes getLoggingConfig without error', async () => { + const client = new projectserviceModule.v2alpha.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.GetLoggingConfigRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.GetLoggingConfigRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.LoggingConfig(), + ); + client.innerApiCalls.getLoggingConfig = stubSimpleCall(expectedResponse); + const [response] = await client.getLoggingConfig(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getLoggingConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getLoggingConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateLoggingConfig with error', async () => { - const client = new projectserviceModule.v2alpha.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.UpdateLoggingConfigRequest() - ); - request.loggingConfig ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.UpdateLoggingConfigRequest', ['loggingConfig', 'name']); - request.loggingConfig.name = defaultValue1; - const expectedHeaderRequestParams = `logging_config.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateLoggingConfig = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateLoggingConfig(request), expectedError); - const actualRequest = (client.innerApiCalls.updateLoggingConfig as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateLoggingConfig as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getLoggingConfig without error using callback', async () => { + const client = new projectserviceModule.v2alpha.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.GetLoggingConfigRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.GetLoggingConfigRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.LoggingConfig(), + ); + client.innerApiCalls.getLoggingConfig = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getLoggingConfig( + request, + ( + err?: Error | null, + result?: protos.google.cloud.retail.v2alpha.ILoggingConfig | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getLoggingConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getLoggingConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateLoggingConfig with closed client', async () => { - const client = new projectserviceModule.v2alpha.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.UpdateLoggingConfigRequest() - ); - request.loggingConfig ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.UpdateLoggingConfigRequest', ['loggingConfig', 'name']); - request.loggingConfig.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateLoggingConfig(request), expectedError); - }); + it('invokes getLoggingConfig with error', async () => { + const client = new projectserviceModule.v2alpha.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.GetLoggingConfigRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.GetLoggingConfigRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getLoggingConfig = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getLoggingConfig(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getLoggingConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getLoggingConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('getAlertConfig', () => { - it('invokes getAlertConfig without error', async () => { - const client = new projectserviceModule.v2alpha.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.GetAlertConfigRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.GetAlertConfigRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.AlertConfig() - ); - client.innerApiCalls.getAlertConfig = stubSimpleCall(expectedResponse); - const [response] = await client.getAlertConfig(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getAlertConfig as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getAlertConfig as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getLoggingConfig with closed client', async () => { + const client = new projectserviceModule.v2alpha.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.GetLoggingConfigRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.GetLoggingConfigRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getLoggingConfig(request), expectedError); + }); + }); + + describe('updateLoggingConfig', () => { + it('invokes updateLoggingConfig without error', async () => { + const client = new projectserviceModule.v2alpha.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.UpdateLoggingConfigRequest(), + ); + request.loggingConfig ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.UpdateLoggingConfigRequest', + ['loggingConfig', 'name'], + ); + request.loggingConfig.name = defaultValue1; + const expectedHeaderRequestParams = `logging_config.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.LoggingConfig(), + ); + client.innerApiCalls.updateLoggingConfig = + stubSimpleCall(expectedResponse); + const [response] = await client.updateLoggingConfig(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateLoggingConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateLoggingConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getAlertConfig without error using callback', async () => { - const client = new projectserviceModule.v2alpha.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.GetAlertConfigRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.GetAlertConfigRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.AlertConfig() - ); - client.innerApiCalls.getAlertConfig = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getAlertConfig( - request, - (err?: Error|null, result?: protos.google.cloud.retail.v2alpha.IAlertConfig|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getAlertConfig as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getAlertConfig as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateLoggingConfig without error using callback', async () => { + const client = new projectserviceModule.v2alpha.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.UpdateLoggingConfigRequest(), + ); + request.loggingConfig ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.UpdateLoggingConfigRequest', + ['loggingConfig', 'name'], + ); + request.loggingConfig.name = defaultValue1; + const expectedHeaderRequestParams = `logging_config.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.LoggingConfig(), + ); + client.innerApiCalls.updateLoggingConfig = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateLoggingConfig( + request, + ( + err?: Error | null, + result?: protos.google.cloud.retail.v2alpha.ILoggingConfig | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateLoggingConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateLoggingConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getAlertConfig with error', async () => { - const client = new projectserviceModule.v2alpha.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.GetAlertConfigRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.GetAlertConfigRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getAlertConfig = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getAlertConfig(request), expectedError); - const actualRequest = (client.innerApiCalls.getAlertConfig as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getAlertConfig as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateLoggingConfig with error', async () => { + const client = new projectserviceModule.v2alpha.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.UpdateLoggingConfigRequest(), + ); + request.loggingConfig ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.UpdateLoggingConfigRequest', + ['loggingConfig', 'name'], + ); + request.loggingConfig.name = defaultValue1; + const expectedHeaderRequestParams = `logging_config.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateLoggingConfig = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.updateLoggingConfig(request), expectedError); + const actualRequest = ( + client.innerApiCalls.updateLoggingConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateLoggingConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getAlertConfig with closed client', async () => { - const client = new projectserviceModule.v2alpha.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.GetAlertConfigRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.GetAlertConfigRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getAlertConfig(request), expectedError); - }); + it('invokes updateLoggingConfig with closed client', async () => { + const client = new projectserviceModule.v2alpha.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.UpdateLoggingConfigRequest(), + ); + request.loggingConfig ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.UpdateLoggingConfigRequest', + ['loggingConfig', 'name'], + ); + request.loggingConfig.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.updateLoggingConfig(request), expectedError); + }); + }); + + describe('getAlertConfig', () => { + it('invokes getAlertConfig without error', async () => { + const client = new projectserviceModule.v2alpha.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.GetAlertConfigRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.GetAlertConfigRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.AlertConfig(), + ); + client.innerApiCalls.getAlertConfig = stubSimpleCall(expectedResponse); + const [response] = await client.getAlertConfig(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getAlertConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getAlertConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('updateAlertConfig', () => { - it('invokes updateAlertConfig without error', async () => { - const client = new projectserviceModule.v2alpha.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.UpdateAlertConfigRequest() - ); - request.alertConfig ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.UpdateAlertConfigRequest', ['alertConfig', 'name']); - request.alertConfig.name = defaultValue1; - const expectedHeaderRequestParams = `alert_config.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.AlertConfig() - ); - client.innerApiCalls.updateAlertConfig = stubSimpleCall(expectedResponse); - const [response] = await client.updateAlertConfig(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateAlertConfig as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateAlertConfig as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getAlertConfig without error using callback', async () => { + const client = new projectserviceModule.v2alpha.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.GetAlertConfigRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.GetAlertConfigRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.AlertConfig(), + ); + client.innerApiCalls.getAlertConfig = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getAlertConfig( + request, + ( + err?: Error | null, + result?: protos.google.cloud.retail.v2alpha.IAlertConfig | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getAlertConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getAlertConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateAlertConfig without error using callback', async () => { - const client = new projectserviceModule.v2alpha.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.UpdateAlertConfigRequest() - ); - request.alertConfig ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.UpdateAlertConfigRequest', ['alertConfig', 'name']); - request.alertConfig.name = defaultValue1; - const expectedHeaderRequestParams = `alert_config.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.AlertConfig() - ); - client.innerApiCalls.updateAlertConfig = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateAlertConfig( - request, - (err?: Error|null, result?: protos.google.cloud.retail.v2alpha.IAlertConfig|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateAlertConfig as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateAlertConfig as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getAlertConfig with error', async () => { + const client = new projectserviceModule.v2alpha.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.GetAlertConfigRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.GetAlertConfigRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getAlertConfig = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getAlertConfig(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getAlertConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getAlertConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateAlertConfig with error', async () => { - const client = new projectserviceModule.v2alpha.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.UpdateAlertConfigRequest() - ); - request.alertConfig ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.UpdateAlertConfigRequest', ['alertConfig', 'name']); - request.alertConfig.name = defaultValue1; - const expectedHeaderRequestParams = `alert_config.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateAlertConfig = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateAlertConfig(request), expectedError); - const actualRequest = (client.innerApiCalls.updateAlertConfig as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateAlertConfig as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getAlertConfig with closed client', async () => { + const client = new projectserviceModule.v2alpha.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.GetAlertConfigRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.GetAlertConfigRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getAlertConfig(request), expectedError); + }); + }); + + describe('updateAlertConfig', () => { + it('invokes updateAlertConfig without error', async () => { + const client = new projectserviceModule.v2alpha.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.UpdateAlertConfigRequest(), + ); + request.alertConfig ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.UpdateAlertConfigRequest', + ['alertConfig', 'name'], + ); + request.alertConfig.name = defaultValue1; + const expectedHeaderRequestParams = `alert_config.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.AlertConfig(), + ); + client.innerApiCalls.updateAlertConfig = stubSimpleCall(expectedResponse); + const [response] = await client.updateAlertConfig(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateAlertConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateAlertConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateAlertConfig with closed client', async () => { - const client = new projectserviceModule.v2alpha.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.UpdateAlertConfigRequest() - ); - request.alertConfig ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.UpdateAlertConfigRequest', ['alertConfig', 'name']); - request.alertConfig.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateAlertConfig(request), expectedError); - }); + it('invokes updateAlertConfig without error using callback', async () => { + const client = new projectserviceModule.v2alpha.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.UpdateAlertConfigRequest(), + ); + request.alertConfig ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.UpdateAlertConfigRequest', + ['alertConfig', 'name'], + ); + request.alertConfig.name = defaultValue1; + const expectedHeaderRequestParams = `alert_config.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.AlertConfig(), + ); + client.innerApiCalls.updateAlertConfig = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateAlertConfig( + request, + ( + err?: Error | null, + result?: protos.google.cloud.retail.v2alpha.IAlertConfig | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateAlertConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateAlertConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('enrollSolution', () => { - it('invokes enrollSolution without error', async () => { - const client = new projectserviceModule.v2alpha.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.EnrollSolutionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.EnrollSolutionRequest', ['project']); - request.project = defaultValue1; - const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.enrollSolution = stubLongRunningCall(expectedResponse); - const [operation] = await client.enrollSolution(request); - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.enrollSolution as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.enrollSolution as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateAlertConfig with error', async () => { + const client = new projectserviceModule.v2alpha.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.UpdateAlertConfigRequest(), + ); + request.alertConfig ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.UpdateAlertConfigRequest', + ['alertConfig', 'name'], + ); + request.alertConfig.name = defaultValue1; + const expectedHeaderRequestParams = `alert_config.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateAlertConfig = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.updateAlertConfig(request), expectedError); + const actualRequest = ( + client.innerApiCalls.updateAlertConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateAlertConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes enrollSolution without error using callback', async () => { - const client = new projectserviceModule.v2alpha.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.EnrollSolutionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.EnrollSolutionRequest', ['project']); - request.project = defaultValue1; - const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.enrollSolution = stubLongRunningCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.enrollSolution( - request, - (err?: Error|null, - result?: LROperation|null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const operation = await promise as LROperation; - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.enrollSolution as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.enrollSolution as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateAlertConfig with closed client', async () => { + const client = new projectserviceModule.v2alpha.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.UpdateAlertConfigRequest(), + ); + request.alertConfig ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.UpdateAlertConfigRequest', + ['alertConfig', 'name'], + ); + request.alertConfig.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.updateAlertConfig(request), expectedError); + }); + }); + + describe('enrollSolution', () => { + it('invokes enrollSolution without error', async () => { + const client = new projectserviceModule.v2alpha.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.EnrollSolutionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.EnrollSolutionRequest', + ['project'], + ); + request.project = defaultValue1; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.enrollSolution = + stubLongRunningCall(expectedResponse); + const [operation] = await client.enrollSolution(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.enrollSolution as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.enrollSolution as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes enrollSolution with call error', async () => { - const client = new projectserviceModule.v2alpha.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.EnrollSolutionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.EnrollSolutionRequest', ['project']); - request.project = defaultValue1; - const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.enrollSolution = stubLongRunningCall(undefined, expectedError); - await assert.rejects(client.enrollSolution(request), expectedError); - const actualRequest = (client.innerApiCalls.enrollSolution as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.enrollSolution as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes enrollSolution without error using callback', async () => { + const client = new projectserviceModule.v2alpha.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.EnrollSolutionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.EnrollSolutionRequest', + ['project'], + ); + request.project = defaultValue1; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.enrollSolution = + stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.enrollSolution( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.cloud.retail.v2alpha.IEnrollSolutionResponse, + protos.google.cloud.retail.v2alpha.IEnrollSolutionMetadata + > | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const operation = (await promise) as LROperation< + protos.google.cloud.retail.v2alpha.IEnrollSolutionResponse, + protos.google.cloud.retail.v2alpha.IEnrollSolutionMetadata + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.enrollSolution as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.enrollSolution as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes enrollSolution with LRO error', async () => { - const client = new projectserviceModule.v2alpha.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.EnrollSolutionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.EnrollSolutionRequest', ['project']); - request.project = defaultValue1; - const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.enrollSolution = stubLongRunningCall(undefined, undefined, expectedError); - const [operation] = await client.enrollSolution(request); - await assert.rejects(operation.promise(), expectedError); - const actualRequest = (client.innerApiCalls.enrollSolution as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.enrollSolution as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes enrollSolution with call error', async () => { + const client = new projectserviceModule.v2alpha.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.EnrollSolutionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.EnrollSolutionRequest', + ['project'], + ); + request.project = defaultValue1; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.enrollSolution = stubLongRunningCall( + undefined, + expectedError, + ); + await assert.rejects(client.enrollSolution(request), expectedError); + const actualRequest = ( + client.innerApiCalls.enrollSolution as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.enrollSolution as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkEnrollSolutionProgress without error', async () => { - const client = new projectserviceModule.v2alpha.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedResponse = generateSampleMessage( - new operationsProtos.google.longrunning.Operation() - ); - expectedResponse.name = 'test'; - expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; - expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')} - - client.operationsClient.getOperation = stubSimpleCall(expectedResponse); - const decodedOperation = await client.checkEnrollSolutionProgress(expectedResponse.name); - assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); - assert(decodedOperation.metadata); - assert((client.operationsClient.getOperation as SinonStub).getCall(0)); - }); + it('invokes enrollSolution with LRO error', async () => { + const client = new projectserviceModule.v2alpha.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.EnrollSolutionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.EnrollSolutionRequest', + ['project'], + ); + request.project = defaultValue1; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.enrollSolution = stubLongRunningCall( + undefined, + undefined, + expectedError, + ); + const [operation] = await client.enrollSolution(request); + await assert.rejects(operation.promise(), expectedError); + const actualRequest = ( + client.innerApiCalls.enrollSolution as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.enrollSolution as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkEnrollSolutionProgress with error', async () => { - const client = new projectserviceModule.v2alpha.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedError = new Error('expected'); - - client.operationsClient.getOperation = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.checkEnrollSolutionProgress(''), expectedError); - assert((client.operationsClient.getOperation as SinonStub) - .getCall(0)); - }); + it('invokes checkEnrollSolutionProgress without error', async () => { + const client = new projectserviceModule.v2alpha.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation(), + ); + expectedResponse.name = 'test'; + expectedResponse.response = { type_url: 'url', value: Buffer.from('') }; + expectedResponse.metadata = { type_url: 'url', value: Buffer.from('') }; + + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const decodedOperation = await client.checkEnrollSolutionProgress( + expectedResponse.name, + ); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); }); - describe('Path templates', () => { - - describe('alertConfig', async () => { - const fakePath = "/rendered/path/alertConfig"; - const expectedParameters = { - project: "projectValue", - }; - const client = new projectserviceModule.v2alpha.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.alertConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.alertConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('alertConfigPath', () => { - const result = client.alertConfigPath("projectValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.alertConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromAlertConfigName', () => { - const result = client.matchProjectFromAlertConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.alertConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('invokes checkEnrollSolutionProgress with error', async () => { + const client = new projectserviceModule.v2alpha.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const expectedError = new Error('expected'); + + client.operationsClient.getOperation = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.checkEnrollSolutionProgress(''), + expectedError, + ); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + }); + + describe('Path templates', () => { + describe('alertConfig', async () => { + const fakePath = '/rendered/path/alertConfig'; + const expectedParameters = { + project: 'projectValue', + }; + const client = new projectserviceModule.v2alpha.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.alertConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.alertConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('alertConfigPath', () => { + const result = client.alertConfigPath('projectValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.alertConfigPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromAlertConfigName', () => { + const result = client.matchProjectFromAlertConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.alertConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('attributesConfig', async () => { - const fakePath = "/rendered/path/attributesConfig"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - }; - const client = new projectserviceModule.v2alpha.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.attributesConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.attributesConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('attributesConfigPath', () => { - const result = client.attributesConfigPath("projectValue", "locationValue", "catalogValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.attributesConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromAttributesConfigName', () => { - const result = client.matchProjectFromAttributesConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromAttributesConfigName', () => { - const result = client.matchLocationFromAttributesConfigName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromAttributesConfigName', () => { - const result = client.matchCatalogFromAttributesConfigName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('attributesConfig', async () => { + const fakePath = '/rendered/path/attributesConfig'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + }; + const client = new projectserviceModule.v2alpha.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.attributesConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.attributesConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('attributesConfigPath', () => { + const result = client.attributesConfigPath( + 'projectValue', + 'locationValue', + 'catalogValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.attributesConfigPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromAttributesConfigName', () => { + const result = client.matchProjectFromAttributesConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromAttributesConfigName', () => { + const result = client.matchLocationFromAttributesConfigName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromAttributesConfigName', () => { + const result = client.matchCatalogFromAttributesConfigName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('branch', async () => { - const fakePath = "/rendered/path/branch"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - branch: "branchValue", - }; - const client = new projectserviceModule.v2alpha.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.branchPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.branchPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('branchPath', () => { - const result = client.branchPath("projectValue", "locationValue", "catalogValue", "branchValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.branchPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromBranchName', () => { - const result = client.matchProjectFromBranchName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.branchPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromBranchName', () => { - const result = client.matchLocationFromBranchName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.branchPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromBranchName', () => { - const result = client.matchCatalogFromBranchName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.branchPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBranchFromBranchName', () => { - const result = client.matchBranchFromBranchName(fakePath); - assert.strictEqual(result, "branchValue"); - assert((client.pathTemplates.branchPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('branch', async () => { + const fakePath = '/rendered/path/branch'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + branch: 'branchValue', + }; + const client = new projectserviceModule.v2alpha.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.branchPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.branchPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('branchPath', () => { + const result = client.branchPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'branchValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.branchPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromBranchName', () => { + const result = client.matchProjectFromBranchName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.branchPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromBranchName', () => { + const result = client.matchLocationFromBranchName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.branchPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromBranchName', () => { + const result = client.matchCatalogFromBranchName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.branchPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBranchFromBranchName', () => { + const result = client.matchBranchFromBranchName(fakePath); + assert.strictEqual(result, 'branchValue'); + assert( + (client.pathTemplates.branchPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('catalog', async () => { - const fakePath = "/rendered/path/catalog"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - }; - const client = new projectserviceModule.v2alpha.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.catalogPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.catalogPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('catalogPath', () => { - const result = client.catalogPath("projectValue", "locationValue", "catalogValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.catalogPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromCatalogName', () => { - const result = client.matchProjectFromCatalogName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.catalogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromCatalogName', () => { - const result = client.matchLocationFromCatalogName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.catalogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromCatalogName', () => { - const result = client.matchCatalogFromCatalogName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.catalogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('catalog', async () => { + const fakePath = '/rendered/path/catalog'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + }; + const client = new projectserviceModule.v2alpha.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.catalogPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.catalogPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('catalogPath', () => { + const result = client.catalogPath( + 'projectValue', + 'locationValue', + 'catalogValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.catalogPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromCatalogName', () => { + const result = client.matchProjectFromCatalogName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.catalogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromCatalogName', () => { + const result = client.matchLocationFromCatalogName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.catalogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromCatalogName', () => { + const result = client.matchCatalogFromCatalogName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.catalogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('completionConfig', async () => { - const fakePath = "/rendered/path/completionConfig"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - }; - const client = new projectserviceModule.v2alpha.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.completionConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.completionConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('completionConfigPath', () => { - const result = client.completionConfigPath("projectValue", "locationValue", "catalogValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.completionConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromCompletionConfigName', () => { - const result = client.matchProjectFromCompletionConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.completionConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromCompletionConfigName', () => { - const result = client.matchLocationFromCompletionConfigName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.completionConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromCompletionConfigName', () => { - const result = client.matchCatalogFromCompletionConfigName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.completionConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('completionConfig', async () => { + const fakePath = '/rendered/path/completionConfig'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + }; + const client = new projectserviceModule.v2alpha.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.completionConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.completionConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('completionConfigPath', () => { + const result = client.completionConfigPath( + 'projectValue', + 'locationValue', + 'catalogValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.completionConfigPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromCompletionConfigName', () => { + const result = client.matchProjectFromCompletionConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.completionConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromCompletionConfigName', () => { + const result = client.matchLocationFromCompletionConfigName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.completionConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromCompletionConfigName', () => { + const result = client.matchCatalogFromCompletionConfigName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.completionConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('control', async () => { - const fakePath = "/rendered/path/control"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - control: "controlValue", - }; - const client = new projectserviceModule.v2alpha.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.controlPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.controlPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('controlPath', () => { - const result = client.controlPath("projectValue", "locationValue", "catalogValue", "controlValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.controlPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromControlName', () => { - const result = client.matchProjectFromControlName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.controlPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromControlName', () => { - const result = client.matchLocationFromControlName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.controlPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromControlName', () => { - const result = client.matchCatalogFromControlName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.controlPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchControlFromControlName', () => { - const result = client.matchControlFromControlName(fakePath); - assert.strictEqual(result, "controlValue"); - assert((client.pathTemplates.controlPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('control', async () => { + const fakePath = '/rendered/path/control'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + control: 'controlValue', + }; + const client = new projectserviceModule.v2alpha.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.controlPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.controlPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('controlPath', () => { + const result = client.controlPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'controlValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.controlPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromControlName', () => { + const result = client.matchProjectFromControlName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.controlPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromControlName', () => { + const result = client.matchLocationFromControlName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.controlPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromControlName', () => { + const result = client.matchCatalogFromControlName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.controlPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchControlFromControlName', () => { + const result = client.matchControlFromControlName(fakePath); + assert.strictEqual(result, 'controlValue'); + assert( + (client.pathTemplates.controlPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('loggingConfig', async () => { - const fakePath = "/rendered/path/loggingConfig"; - const expectedParameters = { - project: "projectValue", - }; - const client = new projectserviceModule.v2alpha.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.loggingConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.loggingConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('loggingConfigPath', () => { - const result = client.loggingConfigPath("projectValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.loggingConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromLoggingConfigName', () => { - const result = client.matchProjectFromLoggingConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.loggingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('loggingConfig', async () => { + const fakePath = '/rendered/path/loggingConfig'; + const expectedParameters = { + project: 'projectValue', + }; + const client = new projectserviceModule.v2alpha.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.loggingConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.loggingConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('loggingConfigPath', () => { + const result = client.loggingConfigPath('projectValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.loggingConfigPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromLoggingConfigName', () => { + const result = client.matchProjectFromLoggingConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.loggingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('merchantCenterAccountLink', async () => { - const fakePath = "/rendered/path/merchantCenterAccountLink"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - merchant_center_account_link: "merchantCenterAccountLinkValue", - }; - const client = new projectserviceModule.v2alpha.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.merchantCenterAccountLinkPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.merchantCenterAccountLinkPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('merchantCenterAccountLinkPath', () => { - const result = client.merchantCenterAccountLinkPath("projectValue", "locationValue", "catalogValue", "merchantCenterAccountLinkValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromMerchantCenterAccountLinkName', () => { - const result = client.matchProjectFromMerchantCenterAccountLinkName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromMerchantCenterAccountLinkName', () => { - const result = client.matchLocationFromMerchantCenterAccountLinkName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromMerchantCenterAccountLinkName', () => { - const result = client.matchCatalogFromMerchantCenterAccountLinkName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName', () => { - const result = client.matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName(fakePath); - assert.strictEqual(result, "merchantCenterAccountLinkValue"); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('merchantCenterAccountLink', async () => { + const fakePath = '/rendered/path/merchantCenterAccountLink'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + merchant_center_account_link: 'merchantCenterAccountLinkValue', + }; + const client = new projectserviceModule.v2alpha.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.merchantCenterAccountLinkPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.merchantCenterAccountLinkPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('merchantCenterAccountLinkPath', () => { + const result = client.merchantCenterAccountLinkPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'merchantCenterAccountLinkValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromMerchantCenterAccountLinkName', () => { + const result = + client.matchProjectFromMerchantCenterAccountLinkName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromMerchantCenterAccountLinkName', () => { + const result = + client.matchLocationFromMerchantCenterAccountLinkName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromMerchantCenterAccountLinkName', () => { + const result = + client.matchCatalogFromMerchantCenterAccountLinkName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName', () => { + const result = + client.matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName( + fakePath, + ); + assert.strictEqual(result, 'merchantCenterAccountLinkValue'); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('model', async () => { - const fakePath = "/rendered/path/model"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - model: "modelValue", - }; - const client = new projectserviceModule.v2alpha.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.modelPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.modelPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('modelPath', () => { - const result = client.modelPath("projectValue", "locationValue", "catalogValue", "modelValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.modelPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromModelName', () => { - const result = client.matchProjectFromModelName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromModelName', () => { - const result = client.matchLocationFromModelName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromModelName', () => { - const result = client.matchCatalogFromModelName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchModelFromModelName', () => { - const result = client.matchModelFromModelName(fakePath); - assert.strictEqual(result, "modelValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('model', async () => { + const fakePath = '/rendered/path/model'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + model: 'modelValue', + }; + const client = new projectserviceModule.v2alpha.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.modelPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.modelPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('modelPath', () => { + const result = client.modelPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'modelValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.modelPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromModelName', () => { + const result = client.matchProjectFromModelName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromModelName', () => { + const result = client.matchLocationFromModelName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromModelName', () => { + const result = client.matchCatalogFromModelName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchModelFromModelName', () => { + const result = client.matchModelFromModelName(fakePath); + assert.strictEqual(result, 'modelValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('product', async () => { - const fakePath = "/rendered/path/product"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - branch: "branchValue", - product: "productValue", - }; - const client = new projectserviceModule.v2alpha.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.productPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.productPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('productPath', () => { - const result = client.productPath("projectValue", "locationValue", "catalogValue", "branchValue", "productValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.productPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProductName', () => { - const result = client.matchProjectFromProductName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromProductName', () => { - const result = client.matchLocationFromProductName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromProductName', () => { - const result = client.matchCatalogFromProductName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBranchFromProductName', () => { - const result = client.matchBranchFromProductName(fakePath); - assert.strictEqual(result, "branchValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchProductFromProductName', () => { - const result = client.matchProductFromProductName(fakePath); - assert.strictEqual(result, "productValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('product', async () => { + const fakePath = '/rendered/path/product'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + branch: 'branchValue', + product: 'productValue', + }; + const client = new projectserviceModule.v2alpha.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.productPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.productPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('productPath', () => { + const result = client.productPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'branchValue', + 'productValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.productPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProductName', () => { + const result = client.matchProjectFromProductName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromProductName', () => { + const result = client.matchLocationFromProductName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromProductName', () => { + const result = client.matchCatalogFromProductName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBranchFromProductName', () => { + const result = client.matchBranchFromProductName(fakePath); + assert.strictEqual(result, 'branchValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchProductFromProductName', () => { + const result = client.matchProductFromProductName(fakePath); + assert.strictEqual(result, 'productValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('project', async () => { - const fakePath = "/rendered/path/project"; - const expectedParameters = { - project: "projectValue", - }; - const client = new projectserviceModule.v2alpha.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.projectPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectPath', () => { - const result = client.projectPath("projectValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectName', () => { - const result = client.matchProjectFromProjectName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('project', async () => { + const fakePath = '/rendered/path/project'; + const expectedParameters = { + project: 'projectValue', + }; + const client = new projectserviceModule.v2alpha.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.projectPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectPath', () => { + const result = client.projectPath('projectValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.projectPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectName', () => { + const result = client.matchProjectFromProjectName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.projectPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('retailProject', async () => { - const fakePath = "/rendered/path/retailProject"; - const expectedParameters = { - project: "projectValue", - }; - const client = new projectserviceModule.v2alpha.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.retailProjectPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.retailProjectPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('retailProjectPath', () => { - const result = client.retailProjectPath("projectValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.retailProjectPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromRetailProjectName', () => { - const result = client.matchProjectFromRetailProjectName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.retailProjectPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('retailProject', async () => { + const fakePath = '/rendered/path/retailProject'; + const expectedParameters = { + project: 'projectValue', + }; + const client = new projectserviceModule.v2alpha.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.retailProjectPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.retailProjectPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('retailProjectPath', () => { + const result = client.retailProjectPath('projectValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.retailProjectPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromRetailProjectName', () => { + const result = client.matchProjectFromRetailProjectName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.retailProjectPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('servingConfig', async () => { - const fakePath = "/rendered/path/servingConfig"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - serving_config: "servingConfigValue", - }; - const client = new projectserviceModule.v2alpha.ProjectServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.servingConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.servingConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('servingConfigPath', () => { - const result = client.servingConfigPath("projectValue", "locationValue", "catalogValue", "servingConfigValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.servingConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromServingConfigName', () => { - const result = client.matchProjectFromServingConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.servingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromServingConfigName', () => { - const result = client.matchLocationFromServingConfigName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.servingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromServingConfigName', () => { - const result = client.matchCatalogFromServingConfigName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.servingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServingConfigFromServingConfigName', () => { - const result = client.matchServingConfigFromServingConfigName(fakePath); - assert.strictEqual(result, "servingConfigValue"); - assert((client.pathTemplates.servingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('servingConfig', async () => { + const fakePath = '/rendered/path/servingConfig'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + serving_config: 'servingConfigValue', + }; + const client = new projectserviceModule.v2alpha.ProjectServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.servingConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.servingConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('servingConfigPath', () => { + const result = client.servingConfigPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'servingConfigValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.servingConfigPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromServingConfigName', () => { + const result = client.matchProjectFromServingConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.servingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromServingConfigName', () => { + const result = client.matchLocationFromServingConfigName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.servingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromServingConfigName', () => { + const result = client.matchCatalogFromServingConfigName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.servingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServingConfigFromServingConfigName', () => { + const result = client.matchServingConfigFromServingConfigName(fakePath); + assert.strictEqual(result, 'servingConfigValue'); + assert( + (client.pathTemplates.servingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/core/generator/gapic-generator-typescript/baselines/retail/test/gapic_search_service_v2alpha.ts.baseline b/core/generator/gapic-generator-typescript/baselines/retail/test/gapic_search_service_v2alpha.ts.baseline index 66e39d3fa6ca..e1b088c07d4f 100644 --- a/core/generator/gapic-generator-typescript/baselines/retail/test/gapic_search_service_v2alpha.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/retail/test/gapic_search_service_v2alpha.ts.baseline @@ -19,1105 +19,1514 @@ import * as protos from '../protos/protos'; import * as assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as searchserviceModule from '../src'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; -import {protobuf} from 'google-gax'; +import { protobuf } from 'google-gax'; // Dynamically loaded proto JSON is needed to get the type information // to fill in default values for request objects -const root = protobuf.Root.fromJSON(require('../protos/protos.json')).resolveAll(); +const root = protobuf.Root.fromJSON( + require('../protos/protos.json'), +).resolveAll(); // eslint-disable-next-line @typescript-eslint/no-unused-vars function getTypeDefaultValue(typeName: string, fields: string[]) { - let type = root.lookupType(typeName) as protobuf.Type; - for (const field of fields.slice(0, -1)) { - type = type.fields[field]?.resolvedType as protobuf.Type; - } - return type.fields[fields[fields.length - 1]]?.defaultValue; + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type.fields[field]?.resolvedType as protobuf.Type; + } + return type.fields[fields[fields.length - 1]]?.defaultValue; } function generateSampleMessage(instance: T) { - const filledObject = (instance.constructor as typeof protobuf.Message) - .toObject(instance as protobuf.Message, {defaults: true}); - return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, { defaults: true }); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; } function stubSimpleCall(response?: ResponseType, error?: Error) { - return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); } -function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { - return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +function stubSimpleCallWithCallback( + response?: ResponseType, + error?: Error, +) { + return error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); } -function stubPageStreamingCall(responses?: ResponseType[], error?: Error) { - const pagingStub = sinon.stub(); - if (responses) { - for (let i = 0; i < responses.length; ++i) { - pagingStub.onCall(i).callsArgWith(2, null, responses[i]); - } +function stubPageStreamingCall( + responses?: ResponseType[], + error?: Error, +) { + const pagingStub = sinon.stub(); + if (responses) { + for (let i = 0; i < responses.length; ++i) { + pagingStub.onCall(i).callsArgWith(2, null, responses[i]); } - const transformStub = error ? sinon.stub().callsArgWith(2, error) : pagingStub; - const mockStream = new PassThrough({ - objectMode: true, - transform: transformStub, - }); - // trigger as many responses as needed - if (responses) { - for (let i = 0; i < responses.length; ++i) { - setImmediate(() => { mockStream.write({}); }); - } - setImmediate(() => { mockStream.end(); }); - } else { - setImmediate(() => { mockStream.write({}); }); - setImmediate(() => { mockStream.end(); }); + } + const transformStub = error + ? sinon.stub().callsArgWith(2, error) + : pagingStub; + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + // trigger as many responses as needed + if (responses) { + for (let i = 0; i < responses.length; ++i) { + setImmediate(() => { + mockStream.write({}); + }); } - return sinon.stub().returns(mockStream); + setImmediate(() => { + mockStream.end(); + }); + } else { + setImmediate(() => { + mockStream.write({}); + }); + setImmediate(() => { + mockStream.end(); + }); + } + return sinon.stub().returns(mockStream); } -function stubAsyncIterationCall(responses?: ResponseType[], error?: Error) { - let counter = 0; - const asyncIterable = { - [Symbol.asyncIterator]() { - return { - async next() { - if (error) { - return Promise.reject(error); - } - if (counter >= responses!.length) { - return Promise.resolve({done: true, value: undefined}); - } - return Promise.resolve({done: false, value: responses![counter++]}); - } - }; - } - }; - return sinon.stub().returns(asyncIterable); +function stubAsyncIterationCall( + responses?: ResponseType[], + error?: Error, +) { + let counter = 0; + const asyncIterable = { + [Symbol.asyncIterator]() { + return { + async next() { + if (error) { + return Promise.reject(error); + } + if (counter >= responses!.length) { + return Promise.resolve({ done: true, value: undefined }); + } + return Promise.resolve({ done: false, value: responses![counter++] }); + }, + }; + }, + }; + return sinon.stub().returns(asyncIterable); } describe('v2alpha.SearchServiceClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new searchserviceModule.v2alpha.SearchServiceClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'retail.googleapis.com'); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new searchserviceModule.v2alpha.SearchServiceClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'retail.googleapis.com'); + }); - it('has universeDomain', () => { - const client = new searchserviceModule.v2alpha.SearchServiceClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); + it('has universeDomain', () => { + const client = new searchserviceModule.v2alpha.SearchServiceClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - it('throws DeprecationWarning if static servicePath is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const servicePath = searchserviceModule.v2alpha.SearchServiceClient.servicePath; - assert.strictEqual(servicePath, 'retail.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = searchserviceModule.v2alpha.SearchServiceClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'retail.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new searchserviceModule.v2alpha.SearchServiceClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'retail.example.com'); - }); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = + searchserviceModule.v2alpha.SearchServiceClient.servicePath; + assert.strictEqual(servicePath, 'retail.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + searchserviceModule.v2alpha.SearchServiceClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'retail.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = new searchserviceModule.v2alpha.SearchServiceClient({ + universeDomain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'retail.example.com'); + }); - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new searchserviceModule.v2alpha.SearchServiceClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'retail.example.com'); - }); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = new searchserviceModule.v2alpha.SearchServiceClient({ + universe_domain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'retail.example.com'); + }); - if (typeof process === 'object' && 'env' in process) { - describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { - it('sets apiEndpoint from environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new searchserviceModule.v2alpha.SearchServiceClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'retail.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - - it('value configured in code has priority over environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new searchserviceModule.v2alpha.SearchServiceClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'retail.configured.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { new searchserviceModule.v2alpha.SearchServiceClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); + if (typeof process === 'object' && 'env' in process) { + describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { + it('sets apiEndpoint from environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new searchserviceModule.v2alpha.SearchServiceClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'retail.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - it('has port', () => { - const port = searchserviceModule.v2alpha.SearchServiceClient.port; - assert(port); - assert(typeof port === 'number'); + it('value configured in code has priority over environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new searchserviceModule.v2alpha.SearchServiceClient({ + universeDomain: 'configured.example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'retail.configured.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - - it('should create a client with no option', () => { - const client = new searchserviceModule.v2alpha.SearchServiceClient(); - assert(client); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new searchserviceModule.v2alpha.SearchServiceClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); + }); - it('should create a client with gRPC fallback', () => { - const client = new searchserviceModule.v2alpha.SearchServiceClient({ - fallback: true, - }); - assert(client); - }); + it('has port', () => { + const port = searchserviceModule.v2alpha.SearchServiceClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('has initialize method and supports deferred initialization', async () => { - const client = new searchserviceModule.v2alpha.SearchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.searchServiceStub, undefined); - await client.initialize(); - assert(client.searchServiceStub); - }); + it('should create a client with no option', () => { + const client = new searchserviceModule.v2alpha.SearchServiceClient(); + assert(client); + }); - it('has close method for the initialized client', done => { - const client = new searchserviceModule.v2alpha.SearchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.searchServiceStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('should create a client with gRPC fallback', () => { + const client = new searchserviceModule.v2alpha.SearchServiceClient({ + fallback: true, + }); + assert(client); + }); - it('has close method for the non-initialized client', done => { - const client = new searchserviceModule.v2alpha.SearchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.searchServiceStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('has initialize method and supports deferred initialization', async () => { + const client = new searchserviceModule.v2alpha.SearchServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.searchServiceStub, undefined); + await client.initialize(); + assert(client.searchServiceStub); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new searchserviceModule.v2alpha.SearchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + it('has close method for the initialized client', (done) => { + const client = new searchserviceModule.v2alpha.SearchServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.searchServiceStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new searchserviceModule.v2alpha.SearchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId((err?: Error|null, projectId?: string|null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } - }); - }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); + it('has close method for the non-initialized client', (done) => { + const client = new searchserviceModule.v2alpha.SearchServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.searchServiceStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); }); - describe('search', () => { - it('invokes search without error', async () => { - const client = new searchserviceModule.v2alpha.SearchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.SearchRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.SearchRequest', ['placement']); - request.placement = defaultValue1; - const expectedHeaderRequestParams = `placement=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.retail.v2alpha.SearchResponse.SearchResult()), - generateSampleMessage(new protos.google.cloud.retail.v2alpha.SearchResponse.SearchResult()), - generateSampleMessage(new protos.google.cloud.retail.v2alpha.SearchResponse.SearchResult()), - ]; - client.innerApiCalls.search = stubSimpleCall(expectedResponse); - const [response] = await client.search(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.search as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.search as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new searchserviceModule.v2alpha.SearchServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + }); - it('invokes search without error using callback', async () => { - const client = new searchserviceModule.v2alpha.SearchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.SearchRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.SearchRequest', ['placement']); - request.placement = defaultValue1; - const expectedHeaderRequestParams = `placement=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.retail.v2alpha.SearchResponse.SearchResult()), - generateSampleMessage(new protos.google.cloud.retail.v2alpha.SearchResponse.SearchResult()), - generateSampleMessage(new protos.google.cloud.retail.v2alpha.SearchResponse.SearchResult()), - ]; - client.innerApiCalls.search = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.search( - request, - (err?: Error|null, result?: protos.google.cloud.retail.v2alpha.SearchResponse.ISearchResult[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.search as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.search as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new searchserviceModule.v2alpha.SearchServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + }); + + describe('search', () => { + it('invokes search without error', async () => { + const client = new searchserviceModule.v2alpha.SearchServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.SearchRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.SearchRequest', + ['placement'], + ); + request.placement = defaultValue1; + const expectedHeaderRequestParams = `placement=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.cloud.retail.v2alpha.SearchResponse.SearchResult(), + ), + generateSampleMessage( + new protos.google.cloud.retail.v2alpha.SearchResponse.SearchResult(), + ), + generateSampleMessage( + new protos.google.cloud.retail.v2alpha.SearchResponse.SearchResult(), + ), + ]; + client.innerApiCalls.search = stubSimpleCall(expectedResponse); + const [response] = await client.search(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.search as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.search as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes search with error', async () => { - const client = new searchserviceModule.v2alpha.SearchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.SearchRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.SearchRequest', ['placement']); - request.placement = defaultValue1; - const expectedHeaderRequestParams = `placement=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.search = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.search(request), expectedError); - const actualRequest = (client.innerApiCalls.search as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.search as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes search without error using callback', async () => { + const client = new searchserviceModule.v2alpha.SearchServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.SearchRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.SearchRequest', + ['placement'], + ); + request.placement = defaultValue1; + const expectedHeaderRequestParams = `placement=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.cloud.retail.v2alpha.SearchResponse.SearchResult(), + ), + generateSampleMessage( + new protos.google.cloud.retail.v2alpha.SearchResponse.SearchResult(), + ), + generateSampleMessage( + new protos.google.cloud.retail.v2alpha.SearchResponse.SearchResult(), + ), + ]; + client.innerApiCalls.search = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.search( + request, + ( + err?: Error | null, + result?: + | protos.google.cloud.retail.v2alpha.SearchResponse.ISearchResult[] + | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.search as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.search as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes searchStream without error', async () => { - const client = new searchserviceModule.v2alpha.SearchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.SearchRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.SearchRequest', ['placement']); - request.placement = defaultValue1; - const expectedHeaderRequestParams = `placement=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.retail.v2alpha.SearchResponse.SearchResult()), - generateSampleMessage(new protos.google.cloud.retail.v2alpha.SearchResponse.SearchResult()), - generateSampleMessage(new protos.google.cloud.retail.v2alpha.SearchResponse.SearchResult()), - ]; - client.descriptors.page.search.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.searchStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.cloud.retail.v2alpha.SearchResponse.SearchResult[] = []; - stream.on('data', (response: protos.google.cloud.retail.v2alpha.SearchResponse.SearchResult) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.search.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.search, request)); - assert( - (client.descriptors.page.search.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes search with error', async () => { + const client = new searchserviceModule.v2alpha.SearchServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.SearchRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.SearchRequest', + ['placement'], + ); + request.placement = defaultValue1; + const expectedHeaderRequestParams = `placement=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.search = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.search(request), expectedError); + const actualRequest = (client.innerApiCalls.search as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.search as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes searchStream with error', async () => { - const client = new searchserviceModule.v2alpha.SearchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.SearchRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.SearchRequest', ['placement']); - request.placement = defaultValue1; - const expectedHeaderRequestParams = `placement=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.search.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.searchStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.cloud.retail.v2alpha.SearchResponse.SearchResult[] = []; - stream.on('data', (response: protos.google.cloud.retail.v2alpha.SearchResponse.SearchResult) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.search.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.search, request)); - assert( - (client.descriptors.page.search.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); + it('invokes searchStream without error', async () => { + const client = new searchserviceModule.v2alpha.SearchServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.SearchRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.SearchRequest', + ['placement'], + ); + request.placement = defaultValue1; + const expectedHeaderRequestParams = `placement=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.cloud.retail.v2alpha.SearchResponse.SearchResult(), + ), + generateSampleMessage( + new protos.google.cloud.retail.v2alpha.SearchResponse.SearchResult(), + ), + generateSampleMessage( + new protos.google.cloud.retail.v2alpha.SearchResponse.SearchResult(), + ), + ]; + client.descriptors.page.search.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.searchStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.cloud.retail.v2alpha.SearchResponse.SearchResult[] = + []; + stream.on( + 'data', + ( + response: protos.google.cloud.retail.v2alpha.SearchResponse.SearchResult, + ) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); }); - - it('uses async iteration with search without error', async () => { - const client = new searchserviceModule.v2alpha.SearchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.SearchRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.SearchRequest', ['placement']); - request.placement = defaultValue1; - const expectedHeaderRequestParams = `placement=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.retail.v2alpha.SearchResponse.SearchResult()), - generateSampleMessage(new protos.google.cloud.retail.v2alpha.SearchResponse.SearchResult()), - generateSampleMessage(new protos.google.cloud.retail.v2alpha.SearchResponse.SearchResult()), - ]; - client.descriptors.page.search.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.cloud.retail.v2alpha.SearchResponse.ISearchResult[] = []; - const iterable = client.searchAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.search.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.search.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); + stream.on('error', (err: Error) => { + reject(err); }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.search.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.search, request), + ); + assert( + (client.descriptors.page.search.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('uses async iteration with search with error', async () => { - const client = new searchserviceModule.v2alpha.SearchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.SearchRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.SearchRequest', ['placement']); - request.placement = defaultValue1; - const expectedHeaderRequestParams = `placement=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.search.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.searchAsync(request); - await assert.rejects(async () => { - const responses: protos.google.cloud.retail.v2alpha.SearchResponse.ISearchResult[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.search.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.search.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); + it('invokes searchStream with error', async () => { + const client = new searchserviceModule.v2alpha.SearchServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.SearchRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.SearchRequest', + ['placement'], + ); + request.placement = defaultValue1; + const expectedHeaderRequestParams = `placement=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.search.createStream = stubPageStreamingCall( + undefined, + expectedError, + ); + const stream = client.searchStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.cloud.retail.v2alpha.SearchResponse.SearchResult[] = + []; + stream.on( + 'data', + ( + response: protos.google.cloud.retail.v2alpha.SearchResponse.SearchResult, + ) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.search.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.search, request), + ); + assert( + (client.descriptors.page.search.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); }); - describe('Path templates', () => { - - describe('alertConfig', async () => { - const fakePath = "/rendered/path/alertConfig"; - const expectedParameters = { - project: "projectValue", - }; - const client = new searchserviceModule.v2alpha.SearchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.alertConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.alertConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('alertConfigPath', () => { - const result = client.alertConfigPath("projectValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.alertConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromAlertConfigName', () => { - const result = client.matchProjectFromAlertConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.alertConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('uses async iteration with search without error', async () => { + const client = new searchserviceModule.v2alpha.SearchServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.SearchRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.SearchRequest', + ['placement'], + ); + request.placement = defaultValue1; + const expectedHeaderRequestParams = `placement=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.cloud.retail.v2alpha.SearchResponse.SearchResult(), + ), + generateSampleMessage( + new protos.google.cloud.retail.v2alpha.SearchResponse.SearchResult(), + ), + generateSampleMessage( + new protos.google.cloud.retail.v2alpha.SearchResponse.SearchResult(), + ), + ]; + client.descriptors.page.search.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.cloud.retail.v2alpha.SearchResponse.ISearchResult[] = + []; + const iterable = client.searchAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + (client.descriptors.page.search.asyncIterate as SinonStub).getCall(0) + .args[1], + request, + ); + assert( + (client.descriptors.page.search.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - describe('attributesConfig', async () => { - const fakePath = "/rendered/path/attributesConfig"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - }; - const client = new searchserviceModule.v2alpha.SearchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.attributesConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.attributesConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('attributesConfigPath', () => { - const result = client.attributesConfigPath("projectValue", "locationValue", "catalogValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.attributesConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromAttributesConfigName', () => { - const result = client.matchProjectFromAttributesConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromAttributesConfigName', () => { - const result = client.matchLocationFromAttributesConfigName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromAttributesConfigName', () => { - const result = client.matchCatalogFromAttributesConfigName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('uses async iteration with search with error', async () => { + const client = new searchserviceModule.v2alpha.SearchServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.SearchRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.SearchRequest', + ['placement'], + ); + request.placement = defaultValue1; + const expectedHeaderRequestParams = `placement=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.search.asyncIterate = stubAsyncIterationCall( + undefined, + expectedError, + ); + const iterable = client.searchAsync(request); + await assert.rejects(async () => { + const responses: protos.google.cloud.retail.v2alpha.SearchResponse.ISearchResult[] = + []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + (client.descriptors.page.search.asyncIterate as SinonStub).getCall(0) + .args[1], + request, + ); + assert( + (client.descriptors.page.search.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + }); + + describe('Path templates', () => { + describe('alertConfig', async () => { + const fakePath = '/rendered/path/alertConfig'; + const expectedParameters = { + project: 'projectValue', + }; + const client = new searchserviceModule.v2alpha.SearchServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.alertConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.alertConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('alertConfigPath', () => { + const result = client.alertConfigPath('projectValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.alertConfigPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromAlertConfigName', () => { + const result = client.matchProjectFromAlertConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.alertConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('branch', async () => { - const fakePath = "/rendered/path/branch"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - branch: "branchValue", - }; - const client = new searchserviceModule.v2alpha.SearchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.branchPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.branchPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('branchPath', () => { - const result = client.branchPath("projectValue", "locationValue", "catalogValue", "branchValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.branchPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromBranchName', () => { - const result = client.matchProjectFromBranchName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.branchPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromBranchName', () => { - const result = client.matchLocationFromBranchName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.branchPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromBranchName', () => { - const result = client.matchCatalogFromBranchName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.branchPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBranchFromBranchName', () => { - const result = client.matchBranchFromBranchName(fakePath); - assert.strictEqual(result, "branchValue"); - assert((client.pathTemplates.branchPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('attributesConfig', async () => { + const fakePath = '/rendered/path/attributesConfig'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + }; + const client = new searchserviceModule.v2alpha.SearchServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.attributesConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.attributesConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('attributesConfigPath', () => { + const result = client.attributesConfigPath( + 'projectValue', + 'locationValue', + 'catalogValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.attributesConfigPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromAttributesConfigName', () => { + const result = client.matchProjectFromAttributesConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromAttributesConfigName', () => { + const result = client.matchLocationFromAttributesConfigName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromAttributesConfigName', () => { + const result = client.matchCatalogFromAttributesConfigName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('catalog', async () => { - const fakePath = "/rendered/path/catalog"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - }; - const client = new searchserviceModule.v2alpha.SearchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.catalogPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.catalogPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('catalogPath', () => { - const result = client.catalogPath("projectValue", "locationValue", "catalogValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.catalogPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromCatalogName', () => { - const result = client.matchProjectFromCatalogName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.catalogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromCatalogName', () => { - const result = client.matchLocationFromCatalogName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.catalogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromCatalogName', () => { - const result = client.matchCatalogFromCatalogName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.catalogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('branch', async () => { + const fakePath = '/rendered/path/branch'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + branch: 'branchValue', + }; + const client = new searchserviceModule.v2alpha.SearchServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.branchPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.branchPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('branchPath', () => { + const result = client.branchPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'branchValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.branchPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromBranchName', () => { + const result = client.matchProjectFromBranchName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.branchPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromBranchName', () => { + const result = client.matchLocationFromBranchName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.branchPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromBranchName', () => { + const result = client.matchCatalogFromBranchName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.branchPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBranchFromBranchName', () => { + const result = client.matchBranchFromBranchName(fakePath); + assert.strictEqual(result, 'branchValue'); + assert( + (client.pathTemplates.branchPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('completionConfig', async () => { - const fakePath = "/rendered/path/completionConfig"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - }; - const client = new searchserviceModule.v2alpha.SearchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.completionConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.completionConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('completionConfigPath', () => { - const result = client.completionConfigPath("projectValue", "locationValue", "catalogValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.completionConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromCompletionConfigName', () => { - const result = client.matchProjectFromCompletionConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.completionConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromCompletionConfigName', () => { - const result = client.matchLocationFromCompletionConfigName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.completionConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromCompletionConfigName', () => { - const result = client.matchCatalogFromCompletionConfigName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.completionConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('catalog', async () => { + const fakePath = '/rendered/path/catalog'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + }; + const client = new searchserviceModule.v2alpha.SearchServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.catalogPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.catalogPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('catalogPath', () => { + const result = client.catalogPath( + 'projectValue', + 'locationValue', + 'catalogValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.catalogPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromCatalogName', () => { + const result = client.matchProjectFromCatalogName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.catalogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromCatalogName', () => { + const result = client.matchLocationFromCatalogName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.catalogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromCatalogName', () => { + const result = client.matchCatalogFromCatalogName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.catalogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('control', async () => { - const fakePath = "/rendered/path/control"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - control: "controlValue", - }; - const client = new searchserviceModule.v2alpha.SearchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.controlPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.controlPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('controlPath', () => { - const result = client.controlPath("projectValue", "locationValue", "catalogValue", "controlValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.controlPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromControlName', () => { - const result = client.matchProjectFromControlName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.controlPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromControlName', () => { - const result = client.matchLocationFromControlName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.controlPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromControlName', () => { - const result = client.matchCatalogFromControlName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.controlPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchControlFromControlName', () => { - const result = client.matchControlFromControlName(fakePath); - assert.strictEqual(result, "controlValue"); - assert((client.pathTemplates.controlPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('completionConfig', async () => { + const fakePath = '/rendered/path/completionConfig'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + }; + const client = new searchserviceModule.v2alpha.SearchServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.completionConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.completionConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('completionConfigPath', () => { + const result = client.completionConfigPath( + 'projectValue', + 'locationValue', + 'catalogValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.completionConfigPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromCompletionConfigName', () => { + const result = client.matchProjectFromCompletionConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.completionConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromCompletionConfigName', () => { + const result = client.matchLocationFromCompletionConfigName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.completionConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromCompletionConfigName', () => { + const result = client.matchCatalogFromCompletionConfigName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.completionConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('experiment', async () => { - const fakePath = "/rendered/path/experiment"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - experiment: "experimentValue", - }; - const client = new searchserviceModule.v2alpha.SearchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.experimentPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.experimentPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('experimentPath', () => { - const result = client.experimentPath("projectValue", "locationValue", "catalogValue", "experimentValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.experimentPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromExperimentName', () => { - const result = client.matchProjectFromExperimentName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.experimentPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromExperimentName', () => { - const result = client.matchLocationFromExperimentName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.experimentPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromExperimentName', () => { - const result = client.matchCatalogFromExperimentName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.experimentPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchExperimentFromExperimentName', () => { - const result = client.matchExperimentFromExperimentName(fakePath); - assert.strictEqual(result, "experimentValue"); - assert((client.pathTemplates.experimentPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('control', async () => { + const fakePath = '/rendered/path/control'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + control: 'controlValue', + }; + const client = new searchserviceModule.v2alpha.SearchServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.controlPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.controlPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('controlPath', () => { + const result = client.controlPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'controlValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.controlPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromControlName', () => { + const result = client.matchProjectFromControlName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.controlPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromControlName', () => { + const result = client.matchLocationFromControlName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.controlPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromControlName', () => { + const result = client.matchCatalogFromControlName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.controlPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchControlFromControlName', () => { + const result = client.matchControlFromControlName(fakePath); + assert.strictEqual(result, 'controlValue'); + assert( + (client.pathTemplates.controlPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('loggingConfig', async () => { - const fakePath = "/rendered/path/loggingConfig"; - const expectedParameters = { - project: "projectValue", - }; - const client = new searchserviceModule.v2alpha.SearchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.loggingConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.loggingConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('loggingConfigPath', () => { - const result = client.loggingConfigPath("projectValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.loggingConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromLoggingConfigName', () => { - const result = client.matchProjectFromLoggingConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.loggingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('experiment', async () => { + const fakePath = '/rendered/path/experiment'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + experiment: 'experimentValue', + }; + const client = new searchserviceModule.v2alpha.SearchServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.experimentPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.experimentPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('experimentPath', () => { + const result = client.experimentPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'experimentValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.experimentPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromExperimentName', () => { + const result = client.matchProjectFromExperimentName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.experimentPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromExperimentName', () => { + const result = client.matchLocationFromExperimentName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.experimentPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromExperimentName', () => { + const result = client.matchCatalogFromExperimentName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.experimentPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchExperimentFromExperimentName', () => { + const result = client.matchExperimentFromExperimentName(fakePath); + assert.strictEqual(result, 'experimentValue'); + assert( + (client.pathTemplates.experimentPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('merchantCenterAccountLink', async () => { - const fakePath = "/rendered/path/merchantCenterAccountLink"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - merchant_center_account_link: "merchantCenterAccountLinkValue", - }; - const client = new searchserviceModule.v2alpha.SearchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.merchantCenterAccountLinkPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.merchantCenterAccountLinkPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('merchantCenterAccountLinkPath', () => { - const result = client.merchantCenterAccountLinkPath("projectValue", "locationValue", "catalogValue", "merchantCenterAccountLinkValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromMerchantCenterAccountLinkName', () => { - const result = client.matchProjectFromMerchantCenterAccountLinkName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromMerchantCenterAccountLinkName', () => { - const result = client.matchLocationFromMerchantCenterAccountLinkName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromMerchantCenterAccountLinkName', () => { - const result = client.matchCatalogFromMerchantCenterAccountLinkName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName', () => { - const result = client.matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName(fakePath); - assert.strictEqual(result, "merchantCenterAccountLinkValue"); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('loggingConfig', async () => { + const fakePath = '/rendered/path/loggingConfig'; + const expectedParameters = { + project: 'projectValue', + }; + const client = new searchserviceModule.v2alpha.SearchServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.loggingConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.loggingConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('loggingConfigPath', () => { + const result = client.loggingConfigPath('projectValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.loggingConfigPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromLoggingConfigName', () => { + const result = client.matchProjectFromLoggingConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.loggingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('model', async () => { - const fakePath = "/rendered/path/model"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - model: "modelValue", - }; - const client = new searchserviceModule.v2alpha.SearchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.modelPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.modelPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('modelPath', () => { - const result = client.modelPath("projectValue", "locationValue", "catalogValue", "modelValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.modelPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromModelName', () => { - const result = client.matchProjectFromModelName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromModelName', () => { - const result = client.matchLocationFromModelName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromModelName', () => { - const result = client.matchCatalogFromModelName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchModelFromModelName', () => { - const result = client.matchModelFromModelName(fakePath); - assert.strictEqual(result, "modelValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('merchantCenterAccountLink', async () => { + const fakePath = '/rendered/path/merchantCenterAccountLink'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + merchant_center_account_link: 'merchantCenterAccountLinkValue', + }; + const client = new searchserviceModule.v2alpha.SearchServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.merchantCenterAccountLinkPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.merchantCenterAccountLinkPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('merchantCenterAccountLinkPath', () => { + const result = client.merchantCenterAccountLinkPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'merchantCenterAccountLinkValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromMerchantCenterAccountLinkName', () => { + const result = + client.matchProjectFromMerchantCenterAccountLinkName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromMerchantCenterAccountLinkName', () => { + const result = + client.matchLocationFromMerchantCenterAccountLinkName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromMerchantCenterAccountLinkName', () => { + const result = + client.matchCatalogFromMerchantCenterAccountLinkName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName', () => { + const result = + client.matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName( + fakePath, + ); + assert.strictEqual(result, 'merchantCenterAccountLinkValue'); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('product', async () => { - const fakePath = "/rendered/path/product"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - branch: "branchValue", - product: "productValue", - }; - const client = new searchserviceModule.v2alpha.SearchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.productPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.productPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('productPath', () => { - const result = client.productPath("projectValue", "locationValue", "catalogValue", "branchValue", "productValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.productPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProductName', () => { - const result = client.matchProjectFromProductName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromProductName', () => { - const result = client.matchLocationFromProductName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromProductName', () => { - const result = client.matchCatalogFromProductName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBranchFromProductName', () => { - const result = client.matchBranchFromProductName(fakePath); - assert.strictEqual(result, "branchValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchProductFromProductName', () => { - const result = client.matchProductFromProductName(fakePath); - assert.strictEqual(result, "productValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('model', async () => { + const fakePath = '/rendered/path/model'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + model: 'modelValue', + }; + const client = new searchserviceModule.v2alpha.SearchServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.modelPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.modelPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('modelPath', () => { + const result = client.modelPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'modelValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.modelPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromModelName', () => { + const result = client.matchProjectFromModelName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromModelName', () => { + const result = client.matchLocationFromModelName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromModelName', () => { + const result = client.matchCatalogFromModelName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchModelFromModelName', () => { + const result = client.matchModelFromModelName(fakePath); + assert.strictEqual(result, 'modelValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('retailProject', async () => { - const fakePath = "/rendered/path/retailProject"; - const expectedParameters = { - project: "projectValue", - }; - const client = new searchserviceModule.v2alpha.SearchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.retailProjectPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.retailProjectPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('retailProjectPath', () => { - const result = client.retailProjectPath("projectValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.retailProjectPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromRetailProjectName', () => { - const result = client.matchProjectFromRetailProjectName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.retailProjectPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('product', async () => { + const fakePath = '/rendered/path/product'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + branch: 'branchValue', + product: 'productValue', + }; + const client = new searchserviceModule.v2alpha.SearchServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.productPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.productPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('productPath', () => { + const result = client.productPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'branchValue', + 'productValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.productPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProductName', () => { + const result = client.matchProjectFromProductName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromProductName', () => { + const result = client.matchLocationFromProductName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromProductName', () => { + const result = client.matchCatalogFromProductName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBranchFromProductName', () => { + const result = client.matchBranchFromProductName(fakePath); + assert.strictEqual(result, 'branchValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchProductFromProductName', () => { + const result = client.matchProductFromProductName(fakePath); + assert.strictEqual(result, 'productValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('servingConfig', async () => { - const fakePath = "/rendered/path/servingConfig"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - serving_config: "servingConfigValue", - }; - const client = new searchserviceModule.v2alpha.SearchServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.servingConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.servingConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('servingConfigPath', () => { - const result = client.servingConfigPath("projectValue", "locationValue", "catalogValue", "servingConfigValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.servingConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromServingConfigName', () => { - const result = client.matchProjectFromServingConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.servingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromServingConfigName', () => { - const result = client.matchLocationFromServingConfigName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.servingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromServingConfigName', () => { - const result = client.matchCatalogFromServingConfigName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.servingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServingConfigFromServingConfigName', () => { - const result = client.matchServingConfigFromServingConfigName(fakePath); - assert.strictEqual(result, "servingConfigValue"); - assert((client.pathTemplates.servingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('retailProject', async () => { + const fakePath = '/rendered/path/retailProject'; + const expectedParameters = { + project: 'projectValue', + }; + const client = new searchserviceModule.v2alpha.SearchServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.retailProjectPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.retailProjectPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('retailProjectPath', () => { + const result = client.retailProjectPath('projectValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.retailProjectPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromRetailProjectName', () => { + const result = client.matchProjectFromRetailProjectName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.retailProjectPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); + + describe('servingConfig', async () => { + const fakePath = '/rendered/path/servingConfig'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + serving_config: 'servingConfigValue', + }; + const client = new searchserviceModule.v2alpha.SearchServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.servingConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.servingConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('servingConfigPath', () => { + const result = client.servingConfigPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'servingConfigValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.servingConfigPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromServingConfigName', () => { + const result = client.matchProjectFromServingConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.servingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromServingConfigName', () => { + const result = client.matchLocationFromServingConfigName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.servingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromServingConfigName', () => { + const result = client.matchCatalogFromServingConfigName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.servingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServingConfigFromServingConfigName', () => { + const result = client.matchServingConfigFromServingConfigName(fakePath); + assert.strictEqual(result, 'servingConfigValue'); + assert( + (client.pathTemplates.servingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/core/generator/gapic-generator-typescript/baselines/retail/test/gapic_serving_config_service_v2alpha.ts.baseline b/core/generator/gapic-generator-typescript/baselines/retail/test/gapic_serving_config_service_v2alpha.ts.baseline index 1638a554681a..09b227083ccf 100644 --- a/core/generator/gapic-generator-typescript/baselines/retail/test/gapic_serving_config_service_v2alpha.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/retail/test/gapic_serving_config_service_v2alpha.ts.baseline @@ -19,1703 +19,2291 @@ import * as protos from '../protos/protos'; import * as assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as servingconfigserviceModule from '../src'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; -import {protobuf} from 'google-gax'; +import { protobuf } from 'google-gax'; // Dynamically loaded proto JSON is needed to get the type information // to fill in default values for request objects -const root = protobuf.Root.fromJSON(require('../protos/protos.json')).resolveAll(); +const root = protobuf.Root.fromJSON( + require('../protos/protos.json'), +).resolveAll(); // eslint-disable-next-line @typescript-eslint/no-unused-vars function getTypeDefaultValue(typeName: string, fields: string[]) { - let type = root.lookupType(typeName) as protobuf.Type; - for (const field of fields.slice(0, -1)) { - type = type.fields[field]?.resolvedType as protobuf.Type; - } - return type.fields[fields[fields.length - 1]]?.defaultValue; + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type.fields[field]?.resolvedType as protobuf.Type; + } + return type.fields[fields[fields.length - 1]]?.defaultValue; } function generateSampleMessage(instance: T) { - const filledObject = (instance.constructor as typeof protobuf.Message) - .toObject(instance as protobuf.Message, {defaults: true}); - return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, { defaults: true }); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; } function stubSimpleCall(response?: ResponseType, error?: Error) { - return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); } -function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { - return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +function stubSimpleCallWithCallback( + response?: ResponseType, + error?: Error, +) { + return error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); } -function stubPageStreamingCall(responses?: ResponseType[], error?: Error) { - const pagingStub = sinon.stub(); - if (responses) { - for (let i = 0; i < responses.length; ++i) { - pagingStub.onCall(i).callsArgWith(2, null, responses[i]); - } +function stubPageStreamingCall( + responses?: ResponseType[], + error?: Error, +) { + const pagingStub = sinon.stub(); + if (responses) { + for (let i = 0; i < responses.length; ++i) { + pagingStub.onCall(i).callsArgWith(2, null, responses[i]); } - const transformStub = error ? sinon.stub().callsArgWith(2, error) : pagingStub; - const mockStream = new PassThrough({ - objectMode: true, - transform: transformStub, - }); - // trigger as many responses as needed - if (responses) { - for (let i = 0; i < responses.length; ++i) { - setImmediate(() => { mockStream.write({}); }); - } - setImmediate(() => { mockStream.end(); }); - } else { - setImmediate(() => { mockStream.write({}); }); - setImmediate(() => { mockStream.end(); }); + } + const transformStub = error + ? sinon.stub().callsArgWith(2, error) + : pagingStub; + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + // trigger as many responses as needed + if (responses) { + for (let i = 0; i < responses.length; ++i) { + setImmediate(() => { + mockStream.write({}); + }); } - return sinon.stub().returns(mockStream); + setImmediate(() => { + mockStream.end(); + }); + } else { + setImmediate(() => { + mockStream.write({}); + }); + setImmediate(() => { + mockStream.end(); + }); + } + return sinon.stub().returns(mockStream); } -function stubAsyncIterationCall(responses?: ResponseType[], error?: Error) { - let counter = 0; - const asyncIterable = { - [Symbol.asyncIterator]() { - return { - async next() { - if (error) { - return Promise.reject(error); - } - if (counter >= responses!.length) { - return Promise.resolve({done: true, value: undefined}); - } - return Promise.resolve({done: false, value: responses![counter++]}); - } - }; - } - }; - return sinon.stub().returns(asyncIterable); +function stubAsyncIterationCall( + responses?: ResponseType[], + error?: Error, +) { + let counter = 0; + const asyncIterable = { + [Symbol.asyncIterator]() { + return { + async next() { + if (error) { + return Promise.reject(error); + } + if (counter >= responses!.length) { + return Promise.resolve({ done: true, value: undefined }); + } + return Promise.resolve({ done: false, value: responses![counter++] }); + }, + }; + }, + }; + return sinon.stub().returns(asyncIterable); } describe('v2alpha.ServingConfigServiceClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new servingconfigserviceModule.v2alpha.ServingConfigServiceClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'retail.googleapis.com'); - }); - - it('has universeDomain', () => { - const client = new servingconfigserviceModule.v2alpha.ServingConfigServiceClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = + new servingconfigserviceModule.v2alpha.ServingConfigServiceClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'retail.googleapis.com'); + }); - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - it('throws DeprecationWarning if static servicePath is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const servicePath = servingconfigserviceModule.v2alpha.ServingConfigServiceClient.servicePath; - assert.strictEqual(servicePath, 'retail.googleapis.com'); - assert(stub.called); - stub.restore(); - }); + it('has universeDomain', () => { + const client = + new servingconfigserviceModule.v2alpha.ServingConfigServiceClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = servingconfigserviceModule.v2alpha.ServingConfigServiceClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'retail.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'retail.example.com'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = + servingconfigserviceModule.v2alpha.ServingConfigServiceClient + .servicePath; + assert.strictEqual(servicePath, 'retail.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + servingconfigserviceModule.v2alpha.ServingConfigServiceClient + .apiEndpoint; + assert.strictEqual(apiEndpoint, 'retail.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = + new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ + universeDomain: 'example.com', }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'retail.example.com'); + }); - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'retail.example.com'); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = + new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ + universe_domain: 'example.com', }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'retail.example.com'); + }); - if (typeof process === 'object' && 'env' in process) { - describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { - it('sets apiEndpoint from environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new servingconfigserviceModule.v2alpha.ServingConfigServiceClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'retail.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - - it('value configured in code has priority over environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'retail.configured.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); + if (typeof process === 'object' && 'env' in process) { + describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { + it('sets apiEndpoint from environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = + new servingconfigserviceModule.v2alpha.ServingConfigServiceClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'retail.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - it('has port', () => { - const port = servingconfigserviceModule.v2alpha.ServingConfigServiceClient.port; - assert(port); - assert(typeof port === 'number'); + it('value configured in code has priority over environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = + new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ + universeDomain: 'configured.example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'retail.configured.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - - it('should create a client with no option', () => { - const client = new servingconfigserviceModule.v2alpha.ServingConfigServiceClient(); - assert(client); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); + }); - it('should create a client with gRPC fallback', () => { - const client = new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ - fallback: true, - }); - assert(client); - }); + it('has port', () => { + const port = + servingconfigserviceModule.v2alpha.ServingConfigServiceClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('has initialize method and supports deferred initialization', async () => { - const client = new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.servingConfigServiceStub, undefined); - await client.initialize(); - assert(client.servingConfigServiceStub); - }); + it('should create a client with no option', () => { + const client = + new servingconfigserviceModule.v2alpha.ServingConfigServiceClient(); + assert(client); + }); - it('has close method for the initialized client', done => { - const client = new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.servingConfigServiceStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); + it('should create a client with gRPC fallback', () => { + const client = + new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ + fallback: true, }); + assert(client); + }); - it('has close method for the non-initialized client', done => { - const client = new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.servingConfigServiceStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); + it('has initialize method and supports deferred initialization', async () => { + const client = + new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + assert.strictEqual(client.servingConfigServiceStub, undefined); + await client.initialize(); + assert(client.servingConfigServiceStub); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + it('has close method for the initialized client', (done) => { + const client = + new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); - - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId((err?: Error|null, projectId?: string|null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } - }); - }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); + client.initialize().catch((err) => { + throw err; + }); + assert(client.servingConfigServiceStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); }); - describe('createServingConfig', () => { - it('invokes createServingConfig without error', async () => { - const client = new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.CreateServingConfigRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.CreateServingConfigRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ServingConfig() - ); - client.innerApiCalls.createServingConfig = stubSimpleCall(expectedResponse); - const [response] = await client.createServingConfig(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createServingConfig as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createServingConfig as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('has close method for the non-initialized client', (done) => { + const client = + new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); - - it('invokes createServingConfig without error using callback', async () => { - const client = new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.CreateServingConfigRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.CreateServingConfigRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ServingConfig() - ); - client.innerApiCalls.createServingConfig = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createServingConfig( - request, - (err?: Error|null, result?: protos.google.cloud.retail.v2alpha.IServingConfig|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createServingConfig as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createServingConfig as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + assert.strictEqual(client.servingConfigServiceStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes createServingConfig with error', async () => { - const client = new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.CreateServingConfigRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.CreateServingConfigRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createServingConfig = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createServingConfig(request), expectedError); - const actualRequest = (client.innerApiCalls.createServingConfig as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createServingConfig as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = + new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + }); - it('invokes createServingConfig with closed client', async () => { - const client = new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.CreateServingConfigRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.CreateServingConfigRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createServingConfig(request), expectedError); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = + new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); }); - - describe('deleteServingConfig', () => { - it('invokes deleteServingConfig without error', async () => { - const client = new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.DeleteServingConfigRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.DeleteServingConfigRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteServingConfig = stubSimpleCall(expectedResponse); - const [response] = await client.deleteServingConfig(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteServingConfig as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteServingConfig as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + describe('createServingConfig', () => { + it('invokes createServingConfig without error', async () => { + const client = + new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.CreateServingConfigRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.CreateServingConfigRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ServingConfig(), + ); + client.innerApiCalls.createServingConfig = + stubSimpleCall(expectedResponse); + const [response] = await client.createServingConfig(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createServingConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createServingConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteServingConfig without error using callback', async () => { - const client = new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.DeleteServingConfigRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.DeleteServingConfigRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteServingConfig = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteServingConfig( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteServingConfig as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteServingConfig as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes createServingConfig without error using callback', async () => { + const client = + new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.CreateServingConfigRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.CreateServingConfigRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ServingConfig(), + ); + client.innerApiCalls.createServingConfig = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createServingConfig( + request, + ( + err?: Error | null, + result?: protos.google.cloud.retail.v2alpha.IServingConfig | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createServingConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createServingConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteServingConfig with error', async () => { - const client = new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.DeleteServingConfigRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.DeleteServingConfigRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteServingConfig = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteServingConfig(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteServingConfig as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteServingConfig as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes createServingConfig with error', async () => { + const client = + new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.CreateServingConfigRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.CreateServingConfigRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createServingConfig = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.createServingConfig(request), expectedError); + const actualRequest = ( + client.innerApiCalls.createServingConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createServingConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteServingConfig with closed client', async () => { - const client = new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.DeleteServingConfigRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.DeleteServingConfigRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteServingConfig(request), expectedError); + it('invokes createServingConfig with closed client', async () => { + const client = + new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.CreateServingConfigRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.CreateServingConfigRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.createServingConfig(request), expectedError); }); - - describe('updateServingConfig', () => { - it('invokes updateServingConfig without error', async () => { - const client = new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.UpdateServingConfigRequest() - ); - request.servingConfig ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.UpdateServingConfigRequest', ['servingConfig', 'name']); - request.servingConfig.name = defaultValue1; - const expectedHeaderRequestParams = `serving_config.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ServingConfig() - ); - client.innerApiCalls.updateServingConfig = stubSimpleCall(expectedResponse); - const [response] = await client.updateServingConfig(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateServingConfig as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateServingConfig as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + describe('deleteServingConfig', () => { + it('invokes deleteServingConfig without error', async () => { + const client = + new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.DeleteServingConfigRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.DeleteServingConfigRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteServingConfig = + stubSimpleCall(expectedResponse); + const [response] = await client.deleteServingConfig(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteServingConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteServingConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateServingConfig without error using callback', async () => { - const client = new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.UpdateServingConfigRequest() - ); - request.servingConfig ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.UpdateServingConfigRequest', ['servingConfig', 'name']); - request.servingConfig.name = defaultValue1; - const expectedHeaderRequestParams = `serving_config.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ServingConfig() - ); - client.innerApiCalls.updateServingConfig = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateServingConfig( - request, - (err?: Error|null, result?: protos.google.cloud.retail.v2alpha.IServingConfig|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateServingConfig as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateServingConfig as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes deleteServingConfig without error using callback', async () => { + const client = + new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.DeleteServingConfigRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.DeleteServingConfigRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteServingConfig = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteServingConfig( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteServingConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteServingConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateServingConfig with error', async () => { - const client = new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.UpdateServingConfigRequest() - ); - request.servingConfig ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.UpdateServingConfigRequest', ['servingConfig', 'name']); - request.servingConfig.name = defaultValue1; - const expectedHeaderRequestParams = `serving_config.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateServingConfig = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateServingConfig(request), expectedError); - const actualRequest = (client.innerApiCalls.updateServingConfig as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateServingConfig as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes deleteServingConfig with error', async () => { + const client = + new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.DeleteServingConfigRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.DeleteServingConfigRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteServingConfig = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.deleteServingConfig(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteServingConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteServingConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateServingConfig with closed client', async () => { - const client = new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.UpdateServingConfigRequest() - ); - request.servingConfig ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.UpdateServingConfigRequest', ['servingConfig', 'name']); - request.servingConfig.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateServingConfig(request), expectedError); + it('invokes deleteServingConfig with closed client', async () => { + const client = + new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.DeleteServingConfigRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.DeleteServingConfigRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.deleteServingConfig(request), expectedError); }); - - describe('getServingConfig', () => { - it('invokes getServingConfig without error', async () => { - const client = new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.GetServingConfigRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.GetServingConfigRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ServingConfig() - ); - client.innerApiCalls.getServingConfig = stubSimpleCall(expectedResponse); - const [response] = await client.getServingConfig(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getServingConfig as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getServingConfig as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + describe('updateServingConfig', () => { + it('invokes updateServingConfig without error', async () => { + const client = + new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.UpdateServingConfigRequest(), + ); + request.servingConfig ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.UpdateServingConfigRequest', + ['servingConfig', 'name'], + ); + request.servingConfig.name = defaultValue1; + const expectedHeaderRequestParams = `serving_config.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ServingConfig(), + ); + client.innerApiCalls.updateServingConfig = + stubSimpleCall(expectedResponse); + const [response] = await client.updateServingConfig(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateServingConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateServingConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getServingConfig without error using callback', async () => { - const client = new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.GetServingConfigRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.GetServingConfigRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ServingConfig() - ); - client.innerApiCalls.getServingConfig = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getServingConfig( - request, - (err?: Error|null, result?: protos.google.cloud.retail.v2alpha.IServingConfig|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getServingConfig as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getServingConfig as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes updateServingConfig without error using callback', async () => { + const client = + new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.UpdateServingConfigRequest(), + ); + request.servingConfig ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.UpdateServingConfigRequest', + ['servingConfig', 'name'], + ); + request.servingConfig.name = defaultValue1; + const expectedHeaderRequestParams = `serving_config.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ServingConfig(), + ); + client.innerApiCalls.updateServingConfig = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateServingConfig( + request, + ( + err?: Error | null, + result?: protos.google.cloud.retail.v2alpha.IServingConfig | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateServingConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateServingConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getServingConfig with error', async () => { - const client = new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.GetServingConfigRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.GetServingConfigRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getServingConfig = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getServingConfig(request), expectedError); - const actualRequest = (client.innerApiCalls.getServingConfig as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getServingConfig as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes updateServingConfig with error', async () => { + const client = + new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.UpdateServingConfigRequest(), + ); + request.servingConfig ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.UpdateServingConfigRequest', + ['servingConfig', 'name'], + ); + request.servingConfig.name = defaultValue1; + const expectedHeaderRequestParams = `serving_config.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateServingConfig = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.updateServingConfig(request), expectedError); + const actualRequest = ( + client.innerApiCalls.updateServingConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateServingConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getServingConfig with closed client', async () => { - const client = new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.GetServingConfigRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.GetServingConfigRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getServingConfig(request), expectedError); + it('invokes updateServingConfig with closed client', async () => { + const client = + new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.UpdateServingConfigRequest(), + ); + request.servingConfig ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.UpdateServingConfigRequest', + ['servingConfig', 'name'], + ); + request.servingConfig.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.updateServingConfig(request), expectedError); }); - - describe('addControl', () => { - it('invokes addControl without error', async () => { - const client = new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.AddControlRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.AddControlRequest', ['servingConfig']); - request.servingConfig = defaultValue1; - const expectedHeaderRequestParams = `serving_config=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ServingConfig() - ); - client.innerApiCalls.addControl = stubSimpleCall(expectedResponse); - const [response] = await client.addControl(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.addControl as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.addControl as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + describe('getServingConfig', () => { + it('invokes getServingConfig without error', async () => { + const client = + new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.GetServingConfigRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.GetServingConfigRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ServingConfig(), + ); + client.innerApiCalls.getServingConfig = stubSimpleCall(expectedResponse); + const [response] = await client.getServingConfig(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getServingConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getServingConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes addControl without error using callback', async () => { - const client = new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.AddControlRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.AddControlRequest', ['servingConfig']); - request.servingConfig = defaultValue1; - const expectedHeaderRequestParams = `serving_config=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ServingConfig() - ); - client.innerApiCalls.addControl = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.addControl( - request, - (err?: Error|null, result?: protos.google.cloud.retail.v2alpha.IServingConfig|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.addControl as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.addControl as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes getServingConfig without error using callback', async () => { + const client = + new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.GetServingConfigRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.GetServingConfigRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ServingConfig(), + ); + client.innerApiCalls.getServingConfig = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getServingConfig( + request, + ( + err?: Error | null, + result?: protos.google.cloud.retail.v2alpha.IServingConfig | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getServingConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getServingConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes addControl with error', async () => { - const client = new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.AddControlRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.AddControlRequest', ['servingConfig']); - request.servingConfig = defaultValue1; - const expectedHeaderRequestParams = `serving_config=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.addControl = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.addControl(request), expectedError); - const actualRequest = (client.innerApiCalls.addControl as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.addControl as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes getServingConfig with error', async () => { + const client = + new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.GetServingConfigRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.GetServingConfigRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getServingConfig = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getServingConfig(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getServingConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getServingConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes addControl with closed client', async () => { - const client = new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.AddControlRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.AddControlRequest', ['servingConfig']); - request.servingConfig = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.addControl(request), expectedError); + it('invokes getServingConfig with closed client', async () => { + const client = + new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.GetServingConfigRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.GetServingConfigRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getServingConfig(request), expectedError); }); - - describe('removeControl', () => { - it('invokes removeControl without error', async () => { - const client = new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.RemoveControlRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.RemoveControlRequest', ['servingConfig']); - request.servingConfig = defaultValue1; - const expectedHeaderRequestParams = `serving_config=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ServingConfig() - ); - client.innerApiCalls.removeControl = stubSimpleCall(expectedResponse); - const [response] = await client.removeControl(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.removeControl as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.removeControl as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + describe('addControl', () => { + it('invokes addControl without error', async () => { + const client = + new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.AddControlRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.AddControlRequest', + ['servingConfig'], + ); + request.servingConfig = defaultValue1; + const expectedHeaderRequestParams = `serving_config=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ServingConfig(), + ); + client.innerApiCalls.addControl = stubSimpleCall(expectedResponse); + const [response] = await client.addControl(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.addControl as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.addControl as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes removeControl without error using callback', async () => { - const client = new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.RemoveControlRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.RemoveControlRequest', ['servingConfig']); - request.servingConfig = defaultValue1; - const expectedHeaderRequestParams = `serving_config=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ServingConfig() - ); - client.innerApiCalls.removeControl = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.removeControl( - request, - (err?: Error|null, result?: protos.google.cloud.retail.v2alpha.IServingConfig|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.removeControl as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.removeControl as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes addControl without error using callback', async () => { + const client = + new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.AddControlRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.AddControlRequest', + ['servingConfig'], + ); + request.servingConfig = defaultValue1; + const expectedHeaderRequestParams = `serving_config=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ServingConfig(), + ); + client.innerApiCalls.addControl = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.addControl( + request, + ( + err?: Error | null, + result?: protos.google.cloud.retail.v2alpha.IServingConfig | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.addControl as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.addControl as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes removeControl with error', async () => { - const client = new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.RemoveControlRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.RemoveControlRequest', ['servingConfig']); - request.servingConfig = defaultValue1; - const expectedHeaderRequestParams = `serving_config=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.removeControl = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.removeControl(request), expectedError); - const actualRequest = (client.innerApiCalls.removeControl as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.removeControl as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes addControl with error', async () => { + const client = + new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.AddControlRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.AddControlRequest', + ['servingConfig'], + ); + request.servingConfig = defaultValue1; + const expectedHeaderRequestParams = `serving_config=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.addControl = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.addControl(request), expectedError); + const actualRequest = ( + client.innerApiCalls.addControl as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.addControl as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes removeControl with closed client', async () => { - const client = new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.RemoveControlRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.RemoveControlRequest', ['servingConfig']); - request.servingConfig = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.removeControl(request), expectedError); + it('invokes addControl with closed client', async () => { + const client = + new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.AddControlRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.AddControlRequest', + ['servingConfig'], + ); + request.servingConfig = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.addControl(request), expectedError); }); - - describe('listServingConfigs', () => { - it('invokes listServingConfigs without error', async () => { - const client = new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ListServingConfigsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ListServingConfigsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.retail.v2alpha.ServingConfig()), - generateSampleMessage(new protos.google.cloud.retail.v2alpha.ServingConfig()), - generateSampleMessage(new protos.google.cloud.retail.v2alpha.ServingConfig()), - ]; - client.innerApiCalls.listServingConfigs = stubSimpleCall(expectedResponse); - const [response] = await client.listServingConfigs(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listServingConfigs as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listServingConfigs as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + describe('removeControl', () => { + it('invokes removeControl without error', async () => { + const client = + new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.RemoveControlRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.RemoveControlRequest', + ['servingConfig'], + ); + request.servingConfig = defaultValue1; + const expectedHeaderRequestParams = `serving_config=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ServingConfig(), + ); + client.innerApiCalls.removeControl = stubSimpleCall(expectedResponse); + const [response] = await client.removeControl(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.removeControl as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.removeControl as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listServingConfigs without error using callback', async () => { - const client = new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ListServingConfigsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ListServingConfigsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.retail.v2alpha.ServingConfig()), - generateSampleMessage(new protos.google.cloud.retail.v2alpha.ServingConfig()), - generateSampleMessage(new protos.google.cloud.retail.v2alpha.ServingConfig()), - ]; - client.innerApiCalls.listServingConfigs = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listServingConfigs( - request, - (err?: Error|null, result?: protos.google.cloud.retail.v2alpha.IServingConfig[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listServingConfigs as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listServingConfigs as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes removeControl without error using callback', async () => { + const client = + new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.RemoveControlRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.RemoveControlRequest', + ['servingConfig'], + ); + request.servingConfig = defaultValue1; + const expectedHeaderRequestParams = `serving_config=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ServingConfig(), + ); + client.innerApiCalls.removeControl = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.removeControl( + request, + ( + err?: Error | null, + result?: protos.google.cloud.retail.v2alpha.IServingConfig | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.removeControl as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.removeControl as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listServingConfigs with error', async () => { - const client = new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ListServingConfigsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ListServingConfigsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listServingConfigs = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listServingConfigs(request), expectedError); - const actualRequest = (client.innerApiCalls.listServingConfigs as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listServingConfigs as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes removeControl with error', async () => { + const client = + new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.RemoveControlRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.RemoveControlRequest', + ['servingConfig'], + ); + request.servingConfig = defaultValue1; + const expectedHeaderRequestParams = `serving_config=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.removeControl = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.removeControl(request), expectedError); + const actualRequest = ( + client.innerApiCalls.removeControl as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.removeControl as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listServingConfigsStream without error', async () => { - const client = new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ListServingConfigsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ListServingConfigsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.retail.v2alpha.ServingConfig()), - generateSampleMessage(new protos.google.cloud.retail.v2alpha.ServingConfig()), - generateSampleMessage(new protos.google.cloud.retail.v2alpha.ServingConfig()), - ]; - client.descriptors.page.listServingConfigs.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listServingConfigsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.cloud.retail.v2alpha.ServingConfig[] = []; - stream.on('data', (response: protos.google.cloud.retail.v2alpha.ServingConfig) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.listServingConfigs.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listServingConfigs, request)); - assert( - (client.descriptors.page.listServingConfigs.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); + it('invokes removeControl with closed client', async () => { + const client = + new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); - - it('invokes listServingConfigsStream with error', async () => { - const client = new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ListServingConfigsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ListServingConfigsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listServingConfigs.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listServingConfigsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.cloud.retail.v2alpha.ServingConfig[] = []; - stream.on('data', (response: protos.google.cloud.retail.v2alpha.ServingConfig) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listServingConfigs.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listServingConfigs, request)); - assert( - (client.descriptors.page.listServingConfigs.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.RemoveControlRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.RemoveControlRequest', + ['servingConfig'], + ); + request.servingConfig = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.removeControl(request), expectedError); + }); + }); + + describe('listServingConfigs', () => { + it('invokes listServingConfigs without error', async () => { + const client = + new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ListServingConfigsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ListServingConfigsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ServingConfig(), + ), + generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ServingConfig(), + ), + generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ServingConfig(), + ), + ]; + client.innerApiCalls.listServingConfigs = + stubSimpleCall(expectedResponse); + const [response] = await client.listServingConfigs(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listServingConfigs as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listServingConfigs as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('uses async iteration with listServingConfigs without error', async () => { - const client = new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ListServingConfigsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ListServingConfigsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.retail.v2alpha.ServingConfig()), - generateSampleMessage(new protos.google.cloud.retail.v2alpha.ServingConfig()), - generateSampleMessage(new protos.google.cloud.retail.v2alpha.ServingConfig()), - ]; - client.descriptors.page.listServingConfigs.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.cloud.retail.v2alpha.IServingConfig[] = []; - const iterable = client.listServingConfigsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listServingConfigs.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listServingConfigs.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); + it('invokes listServingConfigs without error using callback', async () => { + const client = + new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ListServingConfigsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ListServingConfigsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ServingConfig(), + ), + generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ServingConfig(), + ), + generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ServingConfig(), + ), + ]; + client.innerApiCalls.listServingConfigs = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listServingConfigs( + request, + ( + err?: Error | null, + result?: protos.google.cloud.retail.v2alpha.IServingConfig[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listServingConfigs as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listServingConfigs as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('uses async iteration with listServingConfigs with error', async () => { - const client = new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ListServingConfigsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ListServingConfigsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listServingConfigs.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listServingConfigsAsync(request); - await assert.rejects(async () => { - const responses: protos.google.cloud.retail.v2alpha.IServingConfig[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listServingConfigs.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listServingConfigs.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); + it('invokes listServingConfigs with error', async () => { + const client = + new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ListServingConfigsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ListServingConfigsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listServingConfigs = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listServingConfigs(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listServingConfigs as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listServingConfigs as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('Path templates', () => { - - describe('alertConfig', async () => { - const fakePath = "/rendered/path/alertConfig"; - const expectedParameters = { - project: "projectValue", - }; - const client = new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.alertConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.alertConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('alertConfigPath', () => { - const result = client.alertConfigPath("projectValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.alertConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromAlertConfigName', () => { - const result = client.matchProjectFromAlertConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.alertConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('invokes listServingConfigsStream without error', async () => { + const client = + new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); - - describe('attributesConfig', async () => { - const fakePath = "/rendered/path/attributesConfig"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - }; - const client = new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.attributesConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.attributesConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('attributesConfigPath', () => { - const result = client.attributesConfigPath("projectValue", "locationValue", "catalogValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.attributesConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromAttributesConfigName', () => { - const result = client.matchProjectFromAttributesConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromAttributesConfigName', () => { - const result = client.matchLocationFromAttributesConfigName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromAttributesConfigName', () => { - const result = client.matchCatalogFromAttributesConfigName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ListServingConfigsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ListServingConfigsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ServingConfig(), + ), + generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ServingConfig(), + ), + generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ServingConfig(), + ), + ]; + client.descriptors.page.listServingConfigs.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listServingConfigsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.cloud.retail.v2alpha.ServingConfig[] = + []; + stream.on( + 'data', + (response: protos.google.cloud.retail.v2alpha.ServingConfig) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); }); - - describe('branch', async () => { - const fakePath = "/rendered/path/branch"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - branch: "branchValue", - }; - const client = new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.branchPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.branchPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('branchPath', () => { - const result = client.branchPath("projectValue", "locationValue", "catalogValue", "branchValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.branchPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromBranchName', () => { - const result = client.matchProjectFromBranchName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.branchPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromBranchName', () => { - const result = client.matchLocationFromBranchName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.branchPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromBranchName', () => { - const result = client.matchCatalogFromBranchName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.branchPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBranchFromBranchName', () => { - const result = client.matchBranchFromBranchName(fakePath); - assert.strictEqual(result, "branchValue"); - assert((client.pathTemplates.branchPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + stream.on('error', (err: Error) => { + reject(err); }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listServingConfigs.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listServingConfigs, request), + ); + assert( + (client.descriptors.page.listServingConfigs.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - describe('catalog', async () => { - const fakePath = "/rendered/path/catalog"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - }; - const client = new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.catalogPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.catalogPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('catalogPath', () => { - const result = client.catalogPath("projectValue", "locationValue", "catalogValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.catalogPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromCatalogName', () => { - const result = client.matchProjectFromCatalogName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.catalogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromCatalogName', () => { - const result = client.matchLocationFromCatalogName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.catalogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromCatalogName', () => { - const result = client.matchCatalogFromCatalogName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.catalogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('invokes listServingConfigsStream with error', async () => { + const client = + new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); - - describe('completionConfig', async () => { - const fakePath = "/rendered/path/completionConfig"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - }; - const client = new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.completionConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.completionConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('completionConfigPath', () => { - const result = client.completionConfigPath("projectValue", "locationValue", "catalogValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.completionConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromCompletionConfigName', () => { - const result = client.matchProjectFromCompletionConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.completionConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromCompletionConfigName', () => { - const result = client.matchLocationFromCompletionConfigName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.completionConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromCompletionConfigName', () => { - const result = client.matchCatalogFromCompletionConfigName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.completionConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ListServingConfigsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ListServingConfigsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listServingConfigs.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listServingConfigsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.cloud.retail.v2alpha.ServingConfig[] = + []; + stream.on( + 'data', + (response: protos.google.cloud.retail.v2alpha.ServingConfig) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); }); - - describe('control', async () => { - const fakePath = "/rendered/path/control"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - control: "controlValue", - }; - const client = new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.controlPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.controlPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('controlPath', () => { - const result = client.controlPath("projectValue", "locationValue", "catalogValue", "controlValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.controlPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromControlName', () => { - const result = client.matchProjectFromControlName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.controlPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromControlName', () => { - const result = client.matchLocationFromControlName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.controlPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromControlName', () => { - const result = client.matchCatalogFromControlName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.controlPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchControlFromControlName', () => { - const result = client.matchControlFromControlName(fakePath); - assert.strictEqual(result, "controlValue"); - assert((client.pathTemplates.controlPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + stream.on('error', (err: Error) => { + reject(err); }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listServingConfigs.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listServingConfigs, request), + ); + assert( + (client.descriptors.page.listServingConfigs.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - describe('loggingConfig', async () => { - const fakePath = "/rendered/path/loggingConfig"; - const expectedParameters = { - project: "projectValue", - }; - const client = new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.loggingConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.loggingConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('loggingConfigPath', () => { - const result = client.loggingConfigPath("projectValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.loggingConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromLoggingConfigName', () => { - const result = client.matchProjectFromLoggingConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.loggingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('uses async iteration with listServingConfigs without error', async () => { + const client = + new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ListServingConfigsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ListServingConfigsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ServingConfig(), + ), + generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ServingConfig(), + ), + generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ServingConfig(), + ), + ]; + client.descriptors.page.listServingConfigs.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.cloud.retail.v2alpha.IServingConfig[] = []; + const iterable = client.listServingConfigsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listServingConfigs.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listServingConfigs.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - describe('merchantCenterAccountLink', async () => { - const fakePath = "/rendered/path/merchantCenterAccountLink"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - merchant_center_account_link: "merchantCenterAccountLinkValue", - }; - const client = new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.merchantCenterAccountLinkPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.merchantCenterAccountLinkPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('merchantCenterAccountLinkPath', () => { - const result = client.merchantCenterAccountLinkPath("projectValue", "locationValue", "catalogValue", "merchantCenterAccountLinkValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromMerchantCenterAccountLinkName', () => { - const result = client.matchProjectFromMerchantCenterAccountLinkName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromMerchantCenterAccountLinkName', () => { - const result = client.matchLocationFromMerchantCenterAccountLinkName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromMerchantCenterAccountLinkName', () => { - const result = client.matchCatalogFromMerchantCenterAccountLinkName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName', () => { - const result = client.matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName(fakePath); - assert.strictEqual(result, "merchantCenterAccountLinkValue"); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('uses async iteration with listServingConfigs with error', async () => { + const client = + new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); - - describe('model', async () => { - const fakePath = "/rendered/path/model"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - model: "modelValue", - }; - const client = new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.modelPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.modelPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('modelPath', () => { - const result = client.modelPath("projectValue", "locationValue", "catalogValue", "modelValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.modelPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromModelName', () => { - const result = client.matchProjectFromModelName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromModelName', () => { - const result = client.matchLocationFromModelName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromModelName', () => { - const result = client.matchCatalogFromModelName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchModelFromModelName', () => { - const result = client.matchModelFromModelName(fakePath); - assert.strictEqual(result, "modelValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ListServingConfigsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ListServingConfigsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listServingConfigs.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listServingConfigsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.cloud.retail.v2alpha.IServingConfig[] = + []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listServingConfigs.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listServingConfigs.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + }); + + describe('Path templates', () => { + describe('alertConfig', async () => { + const fakePath = '/rendered/path/alertConfig'; + const expectedParameters = { + project: 'projectValue', + }; + const client = + new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + client.pathTemplates.alertConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.alertConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('alertConfigPath', () => { + const result = client.alertConfigPath('projectValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.alertConfigPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromAlertConfigName', () => { + const result = client.matchProjectFromAlertConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.alertConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('product', async () => { - const fakePath = "/rendered/path/product"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - branch: "branchValue", - product: "productValue", - }; - const client = new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.productPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.productPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('productPath', () => { - const result = client.productPath("projectValue", "locationValue", "catalogValue", "branchValue", "productValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.productPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProductName', () => { - const result = client.matchProjectFromProductName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromProductName', () => { - const result = client.matchLocationFromProductName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('attributesConfig', async () => { + const fakePath = '/rendered/path/attributesConfig'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + }; + const client = + new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.attributesConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.attributesConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('attributesConfigPath', () => { + const result = client.attributesConfigPath( + 'projectValue', + 'locationValue', + 'catalogValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.attributesConfigPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromAttributesConfigName', () => { + const result = client.matchProjectFromAttributesConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromAttributesConfigName', () => { + const result = client.matchLocationFromAttributesConfigName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromAttributesConfigName', () => { + const result = client.matchCatalogFromAttributesConfigName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchCatalogFromProductName', () => { - const result = client.matchCatalogFromProductName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('branch', async () => { + const fakePath = '/rendered/path/branch'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + branch: 'branchValue', + }; + const client = + new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.branchPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.branchPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('branchPath', () => { + const result = client.branchPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'branchValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.branchPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromBranchName', () => { + const result = client.matchProjectFromBranchName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.branchPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromBranchName', () => { + const result = client.matchLocationFromBranchName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.branchPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromBranchName', () => { + const result = client.matchCatalogFromBranchName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.branchPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBranchFromBranchName', () => { + const result = client.matchBranchFromBranchName(fakePath); + assert.strictEqual(result, 'branchValue'); + assert( + (client.pathTemplates.branchPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchBranchFromProductName', () => { - const result = client.matchBranchFromProductName(fakePath); - assert.strictEqual(result, "branchValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('catalog', async () => { + const fakePath = '/rendered/path/catalog'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + }; + const client = + new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.catalogPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.catalogPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('catalogPath', () => { + const result = client.catalogPath( + 'projectValue', + 'locationValue', + 'catalogValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.catalogPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromCatalogName', () => { + const result = client.matchProjectFromCatalogName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.catalogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromCatalogName', () => { + const result = client.matchLocationFromCatalogName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.catalogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromCatalogName', () => { + const result = client.matchCatalogFromCatalogName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.catalogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchProductFromProductName', () => { - const result = client.matchProductFromProductName(fakePath); - assert.strictEqual(result, "productValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('completionConfig', async () => { + const fakePath = '/rendered/path/completionConfig'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + }; + const client = + new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + client.pathTemplates.completionConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.completionConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('completionConfigPath', () => { + const result = client.completionConfigPath( + 'projectValue', + 'locationValue', + 'catalogValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.completionConfigPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromCompletionConfigName', () => { + const result = client.matchProjectFromCompletionConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.completionConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromCompletionConfigName', () => { + const result = client.matchLocationFromCompletionConfigName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.completionConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromCompletionConfigName', () => { + const result = client.matchCatalogFromCompletionConfigName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.completionConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('retailProject', async () => { - const fakePath = "/rendered/path/retailProject"; - const expectedParameters = { - project: "projectValue", - }; - const client = new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.retailProjectPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.retailProjectPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('retailProjectPath', () => { - const result = client.retailProjectPath("projectValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.retailProjectPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + describe('control', async () => { + const fakePath = '/rendered/path/control'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + control: 'controlValue', + }; + const client = + new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.controlPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.controlPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('controlPath', () => { + const result = client.controlPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'controlValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.controlPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromControlName', () => { + const result = client.matchProjectFromControlName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.controlPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromControlName', () => { + const result = client.matchLocationFromControlName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.controlPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromControlName', () => { + const result = client.matchCatalogFromControlName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.controlPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchControlFromControlName', () => { + const result = client.matchControlFromControlName(fakePath); + assert.strictEqual(result, 'controlValue'); + assert( + (client.pathTemplates.controlPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchProjectFromRetailProjectName', () => { - const result = client.matchProjectFromRetailProjectName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.retailProjectPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('loggingConfig', async () => { + const fakePath = '/rendered/path/loggingConfig'; + const expectedParameters = { + project: 'projectValue', + }; + const client = + new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + client.pathTemplates.loggingConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.loggingConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('loggingConfigPath', () => { + const result = client.loggingConfigPath('projectValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.loggingConfigPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromLoggingConfigName', () => { + const result = client.matchProjectFromLoggingConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.loggingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('servingConfig', async () => { - const fakePath = "/rendered/path/servingConfig"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - serving_config: "servingConfigValue", - }; - const client = new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.servingConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.servingConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('servingConfigPath', () => { - const result = client.servingConfigPath("projectValue", "locationValue", "catalogValue", "servingConfigValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.servingConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + describe('merchantCenterAccountLink', async () => { + const fakePath = '/rendered/path/merchantCenterAccountLink'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + merchant_center_account_link: 'merchantCenterAccountLinkValue', + }; + const client = + new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.merchantCenterAccountLinkPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.merchantCenterAccountLinkPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('merchantCenterAccountLinkPath', () => { + const result = client.merchantCenterAccountLinkPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'merchantCenterAccountLinkValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromMerchantCenterAccountLinkName', () => { + const result = + client.matchProjectFromMerchantCenterAccountLinkName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromMerchantCenterAccountLinkName', () => { + const result = + client.matchLocationFromMerchantCenterAccountLinkName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromMerchantCenterAccountLinkName', () => { + const result = + client.matchCatalogFromMerchantCenterAccountLinkName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName', () => { + const result = + client.matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName( + fakePath, + ); + assert.strictEqual(result, 'merchantCenterAccountLinkValue'); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchProjectFromServingConfigName', () => { - const result = client.matchProjectFromServingConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.servingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('model', async () => { + const fakePath = '/rendered/path/model'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + model: 'modelValue', + }; + const client = + new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.modelPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.modelPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('modelPath', () => { + const result = client.modelPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'modelValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.modelPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromModelName', () => { + const result = client.matchProjectFromModelName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromModelName', () => { + const result = client.matchLocationFromModelName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromModelName', () => { + const result = client.matchCatalogFromModelName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchModelFromModelName', () => { + const result = client.matchModelFromModelName(fakePath); + assert.strictEqual(result, 'modelValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchLocationFromServingConfigName', () => { - const result = client.matchLocationFromServingConfigName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.servingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('product', async () => { + const fakePath = '/rendered/path/product'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + branch: 'branchValue', + product: 'productValue', + }; + const client = + new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.productPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.productPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('productPath', () => { + const result = client.productPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'branchValue', + 'productValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.productPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProductName', () => { + const result = client.matchProjectFromProductName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromProductName', () => { + const result = client.matchLocationFromProductName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromProductName', () => { + const result = client.matchCatalogFromProductName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBranchFromProductName', () => { + const result = client.matchBranchFromProductName(fakePath); + assert.strictEqual(result, 'branchValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchProductFromProductName', () => { + const result = client.matchProductFromProductName(fakePath); + assert.strictEqual(result, 'productValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchCatalogFromServingConfigName', () => { - const result = client.matchCatalogFromServingConfigName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.servingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('retailProject', async () => { + const fakePath = '/rendered/path/retailProject'; + const expectedParameters = { + project: 'projectValue', + }; + const client = + new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.retailProjectPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.retailProjectPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('retailProjectPath', () => { + const result = client.retailProjectPath('projectValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.retailProjectPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromRetailProjectName', () => { + const result = client.matchProjectFromRetailProjectName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.retailProjectPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchServingConfigFromServingConfigName', () => { - const result = client.matchServingConfigFromServingConfigName(fakePath); - assert.strictEqual(result, "servingConfigValue"); - assert((client.pathTemplates.servingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('servingConfig', async () => { + const fakePath = '/rendered/path/servingConfig'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + serving_config: 'servingConfigValue', + }; + const client = + new servingconfigserviceModule.v2alpha.ServingConfigServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + client.pathTemplates.servingConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.servingConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('servingConfigPath', () => { + const result = client.servingConfigPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'servingConfigValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.servingConfigPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromServingConfigName', () => { + const result = client.matchProjectFromServingConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.servingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromServingConfigName', () => { + const result = client.matchLocationFromServingConfigName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.servingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromServingConfigName', () => { + const result = client.matchCatalogFromServingConfigName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.servingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServingConfigFromServingConfigName', () => { + const result = client.matchServingConfigFromServingConfigName(fakePath); + assert.strictEqual(result, 'servingConfigValue'); + assert( + (client.pathTemplates.servingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/core/generator/gapic-generator-typescript/baselines/retail/test/gapic_user_event_service_v2alpha.ts.baseline b/core/generator/gapic-generator-typescript/baselines/retail/test/gapic_user_event_service_v2alpha.ts.baseline index 3ea4a094fcd0..2ac74d374170 100644 --- a/core/generator/gapic-generator-typescript/baselines/retail/test/gapic_user_event_service_v2alpha.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/retail/test/gapic_user_event_service_v2alpha.ts.baseline @@ -19,1607 +19,2115 @@ import * as protos from '../protos/protos'; import * as assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as usereventserviceModule from '../src'; -import {protobuf, LROperation, operationsProtos} from 'google-gax'; +import { protobuf, LROperation, operationsProtos } from 'google-gax'; // Dynamically loaded proto JSON is needed to get the type information // to fill in default values for request objects -const root = protobuf.Root.fromJSON(require('../protos/protos.json')).resolveAll(); +const root = protobuf.Root.fromJSON( + require('../protos/protos.json'), +).resolveAll(); // eslint-disable-next-line @typescript-eslint/no-unused-vars function getTypeDefaultValue(typeName: string, fields: string[]) { - let type = root.lookupType(typeName) as protobuf.Type; - for (const field of fields.slice(0, -1)) { - type = type.fields[field]?.resolvedType as protobuf.Type; - } - return type.fields[fields[fields.length - 1]]?.defaultValue; + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type.fields[field]?.resolvedType as protobuf.Type; + } + return type.fields[fields[fields.length - 1]]?.defaultValue; } function generateSampleMessage(instance: T) { - const filledObject = (instance.constructor as typeof protobuf.Message) - .toObject(instance as protobuf.Message, {defaults: true}); - return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, { defaults: true }); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; } function stubSimpleCall(response?: ResponseType, error?: Error) { - return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); } -function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { - return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +function stubSimpleCallWithCallback( + response?: ResponseType, + error?: Error, +) { + return error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); } -function stubLongRunningCall(response?: ResponseType, callError?: Error, lroError?: Error) { - const innerStub = lroError ? sinon.stub().rejects(lroError) : sinon.stub().resolves([response]); - const mockOperation = { - promise: innerStub, - }; - return callError ? sinon.stub().rejects(callError) : sinon.stub().resolves([mockOperation]); +function stubLongRunningCall( + response?: ResponseType, + callError?: Error, + lroError?: Error, +) { + const innerStub = lroError + ? sinon.stub().rejects(lroError) + : sinon.stub().resolves([response]); + const mockOperation = { + promise: innerStub, + }; + return callError + ? sinon.stub().rejects(callError) + : sinon.stub().resolves([mockOperation]); } -function stubLongRunningCallWithCallback(response?: ResponseType, callError?: Error, lroError?: Error) { - const innerStub = lroError ? sinon.stub().rejects(lroError) : sinon.stub().resolves([response]); - const mockOperation = { - promise: innerStub, - }; - return callError ? sinon.stub().callsArgWith(2, callError) : sinon.stub().callsArgWith(2, null, mockOperation); +function stubLongRunningCallWithCallback( + response?: ResponseType, + callError?: Error, + lroError?: Error, +) { + const innerStub = lroError + ? sinon.stub().rejects(lroError) + : sinon.stub().resolves([response]); + const mockOperation = { + promise: innerStub, + }; + return callError + ? sinon.stub().callsArgWith(2, callError) + : sinon.stub().callsArgWith(2, null, mockOperation); } describe('v2alpha.UserEventServiceClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new usereventserviceModule.v2alpha.UserEventServiceClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'retail.googleapis.com'); - }); - - it('has universeDomain', () => { - const client = new usereventserviceModule.v2alpha.UserEventServiceClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); - - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - it('throws DeprecationWarning if static servicePath is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const servicePath = usereventserviceModule.v2alpha.UserEventServiceClient.servicePath; - assert.strictEqual(servicePath, 'retail.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = usereventserviceModule.v2alpha.UserEventServiceClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'retail.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new usereventserviceModule.v2alpha.UserEventServiceClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'retail.example.com'); - }); - - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new usereventserviceModule.v2alpha.UserEventServiceClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'retail.example.com'); - }); - - if (typeof process === 'object' && 'env' in process) { - describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { - it('sets apiEndpoint from environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new usereventserviceModule.v2alpha.UserEventServiceClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'retail.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - - it('value configured in code has priority over environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new usereventserviceModule.v2alpha.UserEventServiceClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'retail.configured.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { new usereventserviceModule.v2alpha.UserEventServiceClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); - - it('has port', () => { - const port = usereventserviceModule.v2alpha.UserEventServiceClient.port; - assert(port); - assert(typeof port === 'number'); - }); - - it('should create a client with no option', () => { - const client = new usereventserviceModule.v2alpha.UserEventServiceClient(); - assert(client); - }); - - it('should create a client with gRPC fallback', () => { - const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ - fallback: true, - }); - assert(client); - }); - - it('has initialize method and supports deferred initialization', async () => { - const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.userEventServiceStub, undefined); - await client.initialize(); - assert(client.userEventServiceStub); - }); - - it('has close method for the initialized client', done => { - const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.userEventServiceStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); - - it('has close method for the non-initialized client', done => { - const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.userEventServiceStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); - - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); - }); - - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId((err?: Error|null, projectId?: string|null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } - }); - }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = + new usereventserviceModule.v2alpha.UserEventServiceClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'retail.googleapis.com'); }); - describe('writeUserEvent', () => { - it('invokes writeUserEvent without error', async () => { - const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.WriteUserEventRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.WriteUserEventRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.UserEvent() - ); - client.innerApiCalls.writeUserEvent = stubSimpleCall(expectedResponse); - const [response] = await client.writeUserEvent(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.writeUserEvent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.writeUserEvent as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes writeUserEvent without error using callback', async () => { - const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.WriteUserEventRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.WriteUserEventRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.UserEvent() - ); - client.innerApiCalls.writeUserEvent = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.writeUserEvent( - request, - (err?: Error|null, result?: protos.google.cloud.retail.v2alpha.IUserEvent|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.writeUserEvent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.writeUserEvent as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes writeUserEvent with error', async () => { - const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.WriteUserEventRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.WriteUserEventRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.writeUserEvent = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.writeUserEvent(request), expectedError); - const actualRequest = (client.innerApiCalls.writeUserEvent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.writeUserEvent as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes writeUserEvent with closed client', async () => { - const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.WriteUserEventRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.WriteUserEventRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.writeUserEvent(request), expectedError); - }); + it('has universeDomain', () => { + const client = + new usereventserviceModule.v2alpha.UserEventServiceClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); }); - describe('collectUserEvent', () => { - it('invokes collectUserEvent without error', async () => { - const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.CollectUserEventRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.CollectUserEventRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.api.HttpBody() - ); - client.innerApiCalls.collectUserEvent = stubSimpleCall(expectedResponse); - const [response] = await client.collectUserEvent(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.collectUserEvent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.collectUserEvent as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes collectUserEvent without error using callback', async () => { - const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.CollectUserEventRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.CollectUserEventRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.api.HttpBody() - ); - client.innerApiCalls.collectUserEvent = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.collectUserEvent( - request, - (err?: Error|null, result?: protos.google.api.IHttpBody|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.collectUserEvent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.collectUserEvent as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes collectUserEvent with error', async () => { - const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.CollectUserEventRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.CollectUserEventRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.collectUserEvent = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.collectUserEvent(request), expectedError); - const actualRequest = (client.innerApiCalls.collectUserEvent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.collectUserEvent as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes collectUserEvent with closed client', async () => { - const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.CollectUserEventRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.CollectUserEventRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.collectUserEvent(request), expectedError); - }); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = + usereventserviceModule.v2alpha.UserEventServiceClient.servicePath; + assert.strictEqual(servicePath, 'retail.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + usereventserviceModule.v2alpha.UserEventServiceClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'retail.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ + universeDomain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'retail.example.com'); }); - describe('purgeUserEvents', () => { - it('invokes purgeUserEvents without error', async () => { - const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.PurgeUserEventsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.PurgeUserEventsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.purgeUserEvents = stubLongRunningCall(expectedResponse); - const [operation] = await client.purgeUserEvents(request); - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.purgeUserEvents as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.purgeUserEvents as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes purgeUserEvents without error using callback', async () => { - const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.PurgeUserEventsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.PurgeUserEventsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.purgeUserEvents = stubLongRunningCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.purgeUserEvents( - request, - (err?: Error|null, - result?: LROperation|null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const operation = await promise as LROperation; - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.purgeUserEvents as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.purgeUserEvents as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes purgeUserEvents with call error', async () => { - const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.PurgeUserEventsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.PurgeUserEventsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.purgeUserEvents = stubLongRunningCall(undefined, expectedError); - await assert.rejects(client.purgeUserEvents(request), expectedError); - const actualRequest = (client.innerApiCalls.purgeUserEvents as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.purgeUserEvents as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes purgeUserEvents with LRO error', async () => { - const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.PurgeUserEventsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.PurgeUserEventsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.purgeUserEvents = stubLongRunningCall(undefined, undefined, expectedError); - const [operation] = await client.purgeUserEvents(request); - await assert.rejects(operation.promise(), expectedError); - const actualRequest = (client.innerApiCalls.purgeUserEvents as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.purgeUserEvents as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes checkPurgeUserEventsProgress without error', async () => { - const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedResponse = generateSampleMessage( - new operationsProtos.google.longrunning.Operation() - ); - expectedResponse.name = 'test'; - expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; - expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')} - - client.operationsClient.getOperation = stubSimpleCall(expectedResponse); - const decodedOperation = await client.checkPurgeUserEventsProgress(expectedResponse.name); - assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); - assert(decodedOperation.metadata); - assert((client.operationsClient.getOperation as SinonStub).getCall(0)); - }); - - it('invokes checkPurgeUserEventsProgress with error', async () => { - const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedError = new Error('expected'); - - client.operationsClient.getOperation = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.checkPurgeUserEventsProgress(''), expectedError); - assert((client.operationsClient.getOperation as SinonStub) - .getCall(0)); - }); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ + universe_domain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'retail.example.com'); }); - describe('importUserEvents', () => { - it('invokes importUserEvents without error', async () => { - const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ImportUserEventsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ImportUserEventsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.importUserEvents = stubLongRunningCall(expectedResponse); - const [operation] = await client.importUserEvents(request); - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.importUserEvents as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.importUserEvents as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + if (typeof process === 'object' && 'env' in process) { + describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { + it('sets apiEndpoint from environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = + new usereventserviceModule.v2alpha.UserEventServiceClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'retail.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - it('invokes importUserEvents without error using callback', async () => { - const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ImportUserEventsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ImportUserEventsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.importUserEvents = stubLongRunningCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.importUserEvents( - request, - (err?: Error|null, - result?: LROperation|null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const operation = await promise as LROperation; - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.importUserEvents as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.importUserEvents as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes importUserEvents with call error', async () => { - const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ImportUserEventsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ImportUserEventsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.importUserEvents = stubLongRunningCall(undefined, expectedError); - await assert.rejects(client.importUserEvents(request), expectedError); - const actualRequest = (client.innerApiCalls.importUserEvents as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.importUserEvents as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes importUserEvents with LRO error', async () => { - const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ImportUserEventsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ImportUserEventsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.importUserEvents = stubLongRunningCall(undefined, undefined, expectedError); - const [operation] = await client.importUserEvents(request); - await assert.rejects(operation.promise(), expectedError); - const actualRequest = (client.innerApiCalls.importUserEvents as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.importUserEvents as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes checkImportUserEventsProgress without error', async () => { - const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedResponse = generateSampleMessage( - new operationsProtos.google.longrunning.Operation() - ); - expectedResponse.name = 'test'; - expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; - expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')} - - client.operationsClient.getOperation = stubSimpleCall(expectedResponse); - const decodedOperation = await client.checkImportUserEventsProgress(expectedResponse.name); - assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); - assert(decodedOperation.metadata); - assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + it('value configured in code has priority over environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = + new usereventserviceModule.v2alpha.UserEventServiceClient({ + universeDomain: 'configured.example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'retail.configured.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - - it('invokes checkImportUserEventsProgress with error', async () => { - const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedError = new Error('expected'); - - client.operationsClient.getOperation = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.checkImportUserEventsProgress(''), expectedError); - assert((client.operationsClient.getOperation as SinonStub) - .getCall(0)); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new usereventserviceModule.v2alpha.UserEventServiceClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); }); - describe('exportUserEvents', () => { - it('invokes exportUserEvents without error', async () => { - const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ExportUserEventsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ExportUserEventsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.exportUserEvents = stubLongRunningCall(expectedResponse); - const [operation] = await client.exportUserEvents(request); - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.exportUserEvents as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.exportUserEvents as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes exportUserEvents without error using callback', async () => { - const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ExportUserEventsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ExportUserEventsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.exportUserEvents = stubLongRunningCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.exportUserEvents( - request, - (err?: Error|null, - result?: LROperation|null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const operation = await promise as LROperation; - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.exportUserEvents as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.exportUserEvents as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes exportUserEvents with call error', async () => { - const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ExportUserEventsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ExportUserEventsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.exportUserEvents = stubLongRunningCall(undefined, expectedError); - await assert.rejects(client.exportUserEvents(request), expectedError); - const actualRequest = (client.innerApiCalls.exportUserEvents as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.exportUserEvents as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes exportUserEvents with LRO error', async () => { - const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.ExportUserEventsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.ExportUserEventsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.exportUserEvents = stubLongRunningCall(undefined, undefined, expectedError); - const [operation] = await client.exportUserEvents(request); - await assert.rejects(operation.promise(), expectedError); - const actualRequest = (client.innerApiCalls.exportUserEvents as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.exportUserEvents as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes checkExportUserEventsProgress without error', async () => { - const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedResponse = generateSampleMessage( - new operationsProtos.google.longrunning.Operation() - ); - expectedResponse.name = 'test'; - expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; - expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')} - - client.operationsClient.getOperation = stubSimpleCall(expectedResponse); - const decodedOperation = await client.checkExportUserEventsProgress(expectedResponse.name); - assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); - assert(decodedOperation.metadata); - assert((client.operationsClient.getOperation as SinonStub).getCall(0)); - }); - - it('invokes checkExportUserEventsProgress with error', async () => { - const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedError = new Error('expected'); - - client.operationsClient.getOperation = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.checkExportUserEventsProgress(''), expectedError); - assert((client.operationsClient.getOperation as SinonStub) - .getCall(0)); - }); + it('has port', () => { + const port = usereventserviceModule.v2alpha.UserEventServiceClient.port; + assert(port); + assert(typeof port === 'number'); }); - describe('rejoinUserEvents', () => { - it('invokes rejoinUserEvents without error', async () => { - const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.RejoinUserEventsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.RejoinUserEventsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.rejoinUserEvents = stubLongRunningCall(expectedResponse); - const [operation] = await client.rejoinUserEvents(request); - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.rejoinUserEvents as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.rejoinUserEvents as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes rejoinUserEvents without error using callback', async () => { - const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.RejoinUserEventsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.RejoinUserEventsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.rejoinUserEvents = stubLongRunningCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.rejoinUserEvents( - request, - (err?: Error|null, - result?: LROperation|null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const operation = await promise as LROperation; - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.rejoinUserEvents as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.rejoinUserEvents as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes rejoinUserEvents with call error', async () => { - const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.RejoinUserEventsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.RejoinUserEventsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.rejoinUserEvents = stubLongRunningCall(undefined, expectedError); - await assert.rejects(client.rejoinUserEvents(request), expectedError); - const actualRequest = (client.innerApiCalls.rejoinUserEvents as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.rejoinUserEvents as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes rejoinUserEvents with LRO error', async () => { - const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.retail.v2alpha.RejoinUserEventsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.retail.v2alpha.RejoinUserEventsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.rejoinUserEvents = stubLongRunningCall(undefined, undefined, expectedError); - const [operation] = await client.rejoinUserEvents(request); - await assert.rejects(operation.promise(), expectedError); - const actualRequest = (client.innerApiCalls.rejoinUserEvents as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.rejoinUserEvents as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes checkRejoinUserEventsProgress without error', async () => { - const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedResponse = generateSampleMessage( - new operationsProtos.google.longrunning.Operation() - ); - expectedResponse.name = 'test'; - expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; - expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')} - - client.operationsClient.getOperation = stubSimpleCall(expectedResponse); - const decodedOperation = await client.checkRejoinUserEventsProgress(expectedResponse.name); - assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); - assert(decodedOperation.metadata); - assert((client.operationsClient.getOperation as SinonStub).getCall(0)); - }); - - it('invokes checkRejoinUserEventsProgress with error', async () => { - const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedError = new Error('expected'); - - client.operationsClient.getOperation = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.checkRejoinUserEventsProgress(''), expectedError); - assert((client.operationsClient.getOperation as SinonStub) - .getCall(0)); - }); + it('should create a client with no option', () => { + const client = + new usereventserviceModule.v2alpha.UserEventServiceClient(); + assert(client); }); - describe('Path templates', () => { + it('should create a client with gRPC fallback', () => { + const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ + fallback: true, + }); + assert(client); + }); - describe('alertConfig', async () => { - const fakePath = "/rendered/path/alertConfig"; - const expectedParameters = { - project: "projectValue", - }; - const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.alertConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.alertConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('alertConfigPath', () => { - const result = client.alertConfigPath("projectValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.alertConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + it('has initialize method and supports deferred initialization', async () => { + const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.userEventServiceStub, undefined); + await client.initialize(); + assert(client.userEventServiceStub); + }); - it('matchProjectFromAlertConfigName', () => { - const result = client.matchProjectFromAlertConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.alertConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('has close method for the initialized client', (done) => { + const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.userEventServiceStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - describe('attributesConfig', async () => { - const fakePath = "/rendered/path/attributesConfig"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - }; - const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.attributesConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.attributesConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('attributesConfigPath', () => { - const result = client.attributesConfigPath("projectValue", "locationValue", "catalogValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.attributesConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromAttributesConfigName', () => { - const result = client.matchProjectFromAttributesConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromAttributesConfigName', () => { - const result = client.matchLocationFromAttributesConfigName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromAttributesConfigName', () => { - const result = client.matchCatalogFromAttributesConfigName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('has close method for the non-initialized client', (done) => { + const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.userEventServiceStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - describe('branch', async () => { - const fakePath = "/rendered/path/branch"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - branch: "branchValue", - }; - const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.branchPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.branchPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('branchPath', () => { - const result = client.branchPath("projectValue", "locationValue", "catalogValue", "branchValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.branchPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromBranchName', () => { - const result = client.matchProjectFromBranchName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.branchPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromBranchName', () => { - const result = client.matchLocationFromBranchName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.branchPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCatalogFromBranchName', () => { - const result = client.matchCatalogFromBranchName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.branchPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + }); - it('matchBranchFromBranchName', () => { - const result = client.matchBranchFromBranchName(fakePath); - assert.strictEqual(result, "branchValue"); - assert((client.pathTemplates.branchPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + }); + + describe('writeUserEvent', () => { + it('invokes writeUserEvent without error', async () => { + const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.WriteUserEventRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.WriteUserEventRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.UserEvent(), + ); + client.innerApiCalls.writeUserEvent = stubSimpleCall(expectedResponse); + const [response] = await client.writeUserEvent(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.writeUserEvent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.writeUserEvent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - describe('catalog', async () => { - const fakePath = "/rendered/path/catalog"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - }; - const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.catalogPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.catalogPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('catalogPath', () => { - const result = client.catalogPath("projectValue", "locationValue", "catalogValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.catalogPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromCatalogName', () => { - const result = client.matchProjectFromCatalogName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.catalogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('invokes writeUserEvent without error using callback', async () => { + const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.WriteUserEventRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.WriteUserEventRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.UserEvent(), + ); + client.innerApiCalls.writeUserEvent = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.writeUserEvent( + request, + ( + err?: Error | null, + result?: protos.google.cloud.retail.v2alpha.IUserEvent | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.writeUserEvent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.writeUserEvent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('matchLocationFromCatalogName', () => { - const result = client.matchLocationFromCatalogName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.catalogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('invokes writeUserEvent with error', async () => { + const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.WriteUserEventRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.WriteUserEventRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.writeUserEvent = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.writeUserEvent(request), expectedError); + const actualRequest = ( + client.innerApiCalls.writeUserEvent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.writeUserEvent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('matchCatalogFromCatalogName', () => { - const result = client.matchCatalogFromCatalogName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.catalogPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('invokes writeUserEvent with closed client', async () => { + const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.WriteUserEventRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.WriteUserEventRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.writeUserEvent(request), expectedError); + }); + }); + + describe('collectUserEvent', () => { + it('invokes collectUserEvent without error', async () => { + const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.CollectUserEventRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.CollectUserEventRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.api.HttpBody(), + ); + client.innerApiCalls.collectUserEvent = stubSimpleCall(expectedResponse); + const [response] = await client.collectUserEvent(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.collectUserEvent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.collectUserEvent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - describe('completionConfig', async () => { - const fakePath = "/rendered/path/completionConfig"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - }; - const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.completionConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.completionConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('completionConfigPath', () => { - const result = client.completionConfigPath("projectValue", "locationValue", "catalogValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.completionConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + it('invokes collectUserEvent without error using callback', async () => { + const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.CollectUserEventRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.CollectUserEventRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.api.HttpBody(), + ); + client.innerApiCalls.collectUserEvent = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.collectUserEvent( + request, + (err?: Error | null, result?: protos.google.api.IHttpBody | null) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.collectUserEvent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.collectUserEvent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('matchProjectFromCompletionConfigName', () => { - const result = client.matchProjectFromCompletionConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.completionConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('invokes collectUserEvent with error', async () => { + const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.CollectUserEventRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.CollectUserEventRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.collectUserEvent = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.collectUserEvent(request), expectedError); + const actualRequest = ( + client.innerApiCalls.collectUserEvent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.collectUserEvent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('matchLocationFromCompletionConfigName', () => { - const result = client.matchLocationFromCompletionConfigName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.completionConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('invokes collectUserEvent with closed client', async () => { + const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.CollectUserEventRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.CollectUserEventRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.collectUserEvent(request), expectedError); + }); + }); + + describe('purgeUserEvents', () => { + it('invokes purgeUserEvents without error', async () => { + const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.PurgeUserEventsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.PurgeUserEventsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.purgeUserEvents = + stubLongRunningCall(expectedResponse); + const [operation] = await client.purgeUserEvents(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.purgeUserEvents as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.purgeUserEvents as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('matchCatalogFromCompletionConfigName', () => { - const result = client.matchCatalogFromCompletionConfigName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.completionConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('invokes purgeUserEvents without error using callback', async () => { + const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.PurgeUserEventsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.PurgeUserEventsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.purgeUserEvents = + stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.purgeUserEvents( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.cloud.retail.v2alpha.IPurgeUserEventsResponse, + protos.google.cloud.retail.v2alpha.IPurgeMetadata + > | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const operation = (await promise) as LROperation< + protos.google.cloud.retail.v2alpha.IPurgeUserEventsResponse, + protos.google.cloud.retail.v2alpha.IPurgeMetadata + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.purgeUserEvents as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.purgeUserEvents as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - describe('control', async () => { - const fakePath = "/rendered/path/control"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - control: "controlValue", - }; - const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.controlPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.controlPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('controlPath', () => { - const result = client.controlPath("projectValue", "locationValue", "catalogValue", "controlValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.controlPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + it('invokes purgeUserEvents with call error', async () => { + const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.PurgeUserEventsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.PurgeUserEventsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.purgeUserEvents = stubLongRunningCall( + undefined, + expectedError, + ); + await assert.rejects(client.purgeUserEvents(request), expectedError); + const actualRequest = ( + client.innerApiCalls.purgeUserEvents as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.purgeUserEvents as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('matchProjectFromControlName', () => { - const result = client.matchProjectFromControlName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.controlPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('invokes purgeUserEvents with LRO error', async () => { + const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.PurgeUserEventsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.PurgeUserEventsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.purgeUserEvents = stubLongRunningCall( + undefined, + undefined, + expectedError, + ); + const [operation] = await client.purgeUserEvents(request); + await assert.rejects(operation.promise(), expectedError); + const actualRequest = ( + client.innerApiCalls.purgeUserEvents as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.purgeUserEvents as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('matchLocationFromControlName', () => { - const result = client.matchLocationFromControlName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.controlPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('invokes checkPurgeUserEventsProgress without error', async () => { + const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation(), + ); + expectedResponse.name = 'test'; + expectedResponse.response = { type_url: 'url', value: Buffer.from('') }; + expectedResponse.metadata = { type_url: 'url', value: Buffer.from('') }; + + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const decodedOperation = await client.checkPurgeUserEventsProgress( + expectedResponse.name, + ); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); - it('matchCatalogFromControlName', () => { - const result = client.matchCatalogFromControlName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.controlPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('invokes checkPurgeUserEventsProgress with error', async () => { + const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const expectedError = new Error('expected'); + + client.operationsClient.getOperation = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.checkPurgeUserEventsProgress(''), + expectedError, + ); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + }); + + describe('importUserEvents', () => { + it('invokes importUserEvents without error', async () => { + const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ImportUserEventsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ImportUserEventsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.importUserEvents = + stubLongRunningCall(expectedResponse); + const [operation] = await client.importUserEvents(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.importUserEvents as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.importUserEvents as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('matchControlFromControlName', () => { - const result = client.matchControlFromControlName(fakePath); - assert.strictEqual(result, "controlValue"); - assert((client.pathTemplates.controlPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('invokes importUserEvents without error using callback', async () => { + const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ImportUserEventsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ImportUserEventsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.importUserEvents = + stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.importUserEvents( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.cloud.retail.v2alpha.IImportUserEventsResponse, + protos.google.cloud.retail.v2alpha.IImportMetadata + > | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const operation = (await promise) as LROperation< + protos.google.cloud.retail.v2alpha.IImportUserEventsResponse, + protos.google.cloud.retail.v2alpha.IImportMetadata + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.importUserEvents as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.importUserEvents as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - describe('loggingConfig', async () => { - const fakePath = "/rendered/path/loggingConfig"; - const expectedParameters = { - project: "projectValue", - }; - const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.loggingConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.loggingConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('loggingConfigPath', () => { - const result = client.loggingConfigPath("projectValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.loggingConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + it('invokes importUserEvents with call error', async () => { + const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ImportUserEventsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ImportUserEventsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.importUserEvents = stubLongRunningCall( + undefined, + expectedError, + ); + await assert.rejects(client.importUserEvents(request), expectedError); + const actualRequest = ( + client.innerApiCalls.importUserEvents as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.importUserEvents as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('matchProjectFromLoggingConfigName', () => { - const result = client.matchProjectFromLoggingConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.loggingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('invokes importUserEvents with LRO error', async () => { + const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ImportUserEventsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ImportUserEventsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.importUserEvents = stubLongRunningCall( + undefined, + undefined, + expectedError, + ); + const [operation] = await client.importUserEvents(request); + await assert.rejects(operation.promise(), expectedError); + const actualRequest = ( + client.innerApiCalls.importUserEvents as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.importUserEvents as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - describe('merchantCenterAccountLink', async () => { - const fakePath = "/rendered/path/merchantCenterAccountLink"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - merchant_center_account_link: "merchantCenterAccountLinkValue", - }; - const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.merchantCenterAccountLinkPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.merchantCenterAccountLinkPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('merchantCenterAccountLinkPath', () => { - const result = client.merchantCenterAccountLinkPath("projectValue", "locationValue", "catalogValue", "merchantCenterAccountLinkValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + it('invokes checkImportUserEventsProgress without error', async () => { + const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation(), + ); + expectedResponse.name = 'test'; + expectedResponse.response = { type_url: 'url', value: Buffer.from('') }; + expectedResponse.metadata = { type_url: 'url', value: Buffer.from('') }; + + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const decodedOperation = await client.checkImportUserEventsProgress( + expectedResponse.name, + ); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); - it('matchProjectFromMerchantCenterAccountLinkName', () => { - const result = client.matchProjectFromMerchantCenterAccountLinkName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('invokes checkImportUserEventsProgress with error', async () => { + const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const expectedError = new Error('expected'); + + client.operationsClient.getOperation = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.checkImportUserEventsProgress(''), + expectedError, + ); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + }); + + describe('exportUserEvents', () => { + it('invokes exportUserEvents without error', async () => { + const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ExportUserEventsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ExportUserEventsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.exportUserEvents = + stubLongRunningCall(expectedResponse); + const [operation] = await client.exportUserEvents(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.exportUserEvents as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.exportUserEvents as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('matchLocationFromMerchantCenterAccountLinkName', () => { - const result = client.matchLocationFromMerchantCenterAccountLinkName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('invokes exportUserEvents without error using callback', async () => { + const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ExportUserEventsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ExportUserEventsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.exportUserEvents = + stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.exportUserEvents( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.cloud.retail.v2alpha.IExportUserEventsResponse, + protos.google.cloud.retail.v2alpha.IExportMetadata + > | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const operation = (await promise) as LROperation< + protos.google.cloud.retail.v2alpha.IExportUserEventsResponse, + protos.google.cloud.retail.v2alpha.IExportMetadata + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.exportUserEvents as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.exportUserEvents as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('matchCatalogFromMerchantCenterAccountLinkName', () => { - const result = client.matchCatalogFromMerchantCenterAccountLinkName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('invokes exportUserEvents with call error', async () => { + const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ExportUserEventsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ExportUserEventsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.exportUserEvents = stubLongRunningCall( + undefined, + expectedError, + ); + await assert.rejects(client.exportUserEvents(request), expectedError); + const actualRequest = ( + client.innerApiCalls.exportUserEvents as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.exportUserEvents as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName', () => { - const result = client.matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName(fakePath); - assert.strictEqual(result, "merchantCenterAccountLinkValue"); - assert((client.pathTemplates.merchantCenterAccountLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('invokes exportUserEvents with LRO error', async () => { + const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.ExportUserEventsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.ExportUserEventsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.exportUserEvents = stubLongRunningCall( + undefined, + undefined, + expectedError, + ); + const [operation] = await client.exportUserEvents(request); + await assert.rejects(operation.promise(), expectedError); + const actualRequest = ( + client.innerApiCalls.exportUserEvents as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.exportUserEvents as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - describe('model', async () => { - const fakePath = "/rendered/path/model"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - model: "modelValue", - }; - const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.modelPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.modelPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('modelPath', () => { - const result = client.modelPath("projectValue", "locationValue", "catalogValue", "modelValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.modelPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + it('invokes checkExportUserEventsProgress without error', async () => { + const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation(), + ); + expectedResponse.name = 'test'; + expectedResponse.response = { type_url: 'url', value: Buffer.from('') }; + expectedResponse.metadata = { type_url: 'url', value: Buffer.from('') }; + + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const decodedOperation = await client.checkExportUserEventsProgress( + expectedResponse.name, + ); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); - it('matchProjectFromModelName', () => { - const result = client.matchProjectFromModelName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('invokes checkExportUserEventsProgress with error', async () => { + const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const expectedError = new Error('expected'); + + client.operationsClient.getOperation = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.checkExportUserEventsProgress(''), + expectedError, + ); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + }); + + describe('rejoinUserEvents', () => { + it('invokes rejoinUserEvents without error', async () => { + const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.RejoinUserEventsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.RejoinUserEventsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.rejoinUserEvents = + stubLongRunningCall(expectedResponse); + const [operation] = await client.rejoinUserEvents(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.rejoinUserEvents as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.rejoinUserEvents as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('matchLocationFromModelName', () => { - const result = client.matchLocationFromModelName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('invokes rejoinUserEvents without error using callback', async () => { + const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.RejoinUserEventsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.RejoinUserEventsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.rejoinUserEvents = + stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.rejoinUserEvents( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.cloud.retail.v2alpha.IRejoinUserEventsResponse, + protos.google.cloud.retail.v2alpha.IRejoinUserEventsMetadata + > | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const operation = (await promise) as LROperation< + protos.google.cloud.retail.v2alpha.IRejoinUserEventsResponse, + protos.google.cloud.retail.v2alpha.IRejoinUserEventsMetadata + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.rejoinUserEvents as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.rejoinUserEvents as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('matchCatalogFromModelName', () => { - const result = client.matchCatalogFromModelName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('invokes rejoinUserEvents with call error', async () => { + const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.RejoinUserEventsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.RejoinUserEventsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.rejoinUserEvents = stubLongRunningCall( + undefined, + expectedError, + ); + await assert.rejects(client.rejoinUserEvents(request), expectedError); + const actualRequest = ( + client.innerApiCalls.rejoinUserEvents as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.rejoinUserEvents as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('matchModelFromModelName', () => { - const result = client.matchModelFromModelName(fakePath); - assert.strictEqual(result, "modelValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('invokes rejoinUserEvents with LRO error', async () => { + const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.retail.v2alpha.RejoinUserEventsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.retail.v2alpha.RejoinUserEventsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.rejoinUserEvents = stubLongRunningCall( + undefined, + undefined, + expectedError, + ); + const [operation] = await client.rejoinUserEvents(request); + await assert.rejects(operation.promise(), expectedError); + const actualRequest = ( + client.innerApiCalls.rejoinUserEvents as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.rejoinUserEvents as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - describe('product', async () => { - const fakePath = "/rendered/path/product"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - branch: "branchValue", - product: "productValue", - }; - const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.productPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.productPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('productPath', () => { - const result = client.productPath("projectValue", "locationValue", "catalogValue", "branchValue", "productValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.productPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + it('invokes checkRejoinUserEventsProgress without error', async () => { + const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation(), + ); + expectedResponse.name = 'test'; + expectedResponse.response = { type_url: 'url', value: Buffer.from('') }; + expectedResponse.metadata = { type_url: 'url', value: Buffer.from('') }; + + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const decodedOperation = await client.checkRejoinUserEventsProgress( + expectedResponse.name, + ); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); - it('matchProjectFromProductName', () => { - const result = client.matchProjectFromProductName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('invokes checkRejoinUserEventsProgress with error', async () => { + const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const expectedError = new Error('expected'); + + client.operationsClient.getOperation = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.checkRejoinUserEventsProgress(''), + expectedError, + ); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + }); + + describe('Path templates', () => { + describe('alertConfig', async () => { + const fakePath = '/rendered/path/alertConfig'; + const expectedParameters = { + project: 'projectValue', + }; + const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.alertConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.alertConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('alertConfigPath', () => { + const result = client.alertConfigPath('projectValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.alertConfigPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromAlertConfigName', () => { + const result = client.matchProjectFromAlertConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.alertConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchLocationFromProductName', () => { - const result = client.matchLocationFromProductName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('attributesConfig', async () => { + const fakePath = '/rendered/path/attributesConfig'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + }; + const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.attributesConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.attributesConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('attributesConfigPath', () => { + const result = client.attributesConfigPath( + 'projectValue', + 'locationValue', + 'catalogValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.attributesConfigPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromAttributesConfigName', () => { + const result = client.matchProjectFromAttributesConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromAttributesConfigName', () => { + const result = client.matchLocationFromAttributesConfigName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromAttributesConfigName', () => { + const result = client.matchCatalogFromAttributesConfigName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.attributesConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchCatalogFromProductName', () => { - const result = client.matchCatalogFromProductName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('branch', async () => { + const fakePath = '/rendered/path/branch'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + branch: 'branchValue', + }; + const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.branchPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.branchPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('branchPath', () => { + const result = client.branchPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'branchValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.branchPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromBranchName', () => { + const result = client.matchProjectFromBranchName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.branchPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromBranchName', () => { + const result = client.matchLocationFromBranchName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.branchPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromBranchName', () => { + const result = client.matchCatalogFromBranchName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.branchPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBranchFromBranchName', () => { + const result = client.matchBranchFromBranchName(fakePath); + assert.strictEqual(result, 'branchValue'); + assert( + (client.pathTemplates.branchPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchBranchFromProductName', () => { - const result = client.matchBranchFromProductName(fakePath); - assert.strictEqual(result, "branchValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('catalog', async () => { + const fakePath = '/rendered/path/catalog'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + }; + const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.catalogPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.catalogPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('catalogPath', () => { + const result = client.catalogPath( + 'projectValue', + 'locationValue', + 'catalogValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.catalogPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromCatalogName', () => { + const result = client.matchProjectFromCatalogName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.catalogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromCatalogName', () => { + const result = client.matchLocationFromCatalogName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.catalogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromCatalogName', () => { + const result = client.matchCatalogFromCatalogName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.catalogPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchProductFromProductName', () => { - const result = client.matchProductFromProductName(fakePath); - assert.strictEqual(result, "productValue"); - assert((client.pathTemplates.productPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('completionConfig', async () => { + const fakePath = '/rendered/path/completionConfig'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + }; + const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.completionConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.completionConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('completionConfigPath', () => { + const result = client.completionConfigPath( + 'projectValue', + 'locationValue', + 'catalogValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.completionConfigPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromCompletionConfigName', () => { + const result = client.matchProjectFromCompletionConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.completionConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromCompletionConfigName', () => { + const result = client.matchLocationFromCompletionConfigName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.completionConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromCompletionConfigName', () => { + const result = client.matchCatalogFromCompletionConfigName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.completionConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('retailProject', async () => { - const fakePath = "/rendered/path/retailProject"; - const expectedParameters = { - project: "projectValue", - }; - const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.retailProjectPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.retailProjectPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('retailProjectPath', () => { - const result = client.retailProjectPath("projectValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.retailProjectPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + describe('control', async () => { + const fakePath = '/rendered/path/control'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + control: 'controlValue', + }; + const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.controlPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.controlPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('controlPath', () => { + const result = client.controlPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'controlValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.controlPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromControlName', () => { + const result = client.matchProjectFromControlName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.controlPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromControlName', () => { + const result = client.matchLocationFromControlName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.controlPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromControlName', () => { + const result = client.matchCatalogFromControlName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.controlPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchControlFromControlName', () => { + const result = client.matchControlFromControlName(fakePath); + assert.strictEqual(result, 'controlValue'); + assert( + (client.pathTemplates.controlPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchProjectFromRetailProjectName', () => { - const result = client.matchProjectFromRetailProjectName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.retailProjectPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('loggingConfig', async () => { + const fakePath = '/rendered/path/loggingConfig'; + const expectedParameters = { + project: 'projectValue', + }; + const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.loggingConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.loggingConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('loggingConfigPath', () => { + const result = client.loggingConfigPath('projectValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.loggingConfigPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromLoggingConfigName', () => { + const result = client.matchProjectFromLoggingConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.loggingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('servingConfig', async () => { - const fakePath = "/rendered/path/servingConfig"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - catalog: "catalogValue", - serving_config: "servingConfigValue", - }; - const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.servingConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.servingConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('servingConfigPath', () => { - const result = client.servingConfigPath("projectValue", "locationValue", "catalogValue", "servingConfigValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.servingConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + describe('merchantCenterAccountLink', async () => { + const fakePath = '/rendered/path/merchantCenterAccountLink'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + merchant_center_account_link: 'merchantCenterAccountLinkValue', + }; + const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.merchantCenterAccountLinkPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.merchantCenterAccountLinkPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('merchantCenterAccountLinkPath', () => { + const result = client.merchantCenterAccountLinkPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'merchantCenterAccountLinkValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromMerchantCenterAccountLinkName', () => { + const result = + client.matchProjectFromMerchantCenterAccountLinkName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromMerchantCenterAccountLinkName', () => { + const result = + client.matchLocationFromMerchantCenterAccountLinkName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromMerchantCenterAccountLinkName', () => { + const result = + client.matchCatalogFromMerchantCenterAccountLinkName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName', () => { + const result = + client.matchMerchantCenterAccountLinkFromMerchantCenterAccountLinkName( + fakePath, + ); + assert.strictEqual(result, 'merchantCenterAccountLinkValue'); + assert( + ( + client.pathTemplates.merchantCenterAccountLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchProjectFromServingConfigName', () => { - const result = client.matchProjectFromServingConfigName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.servingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('model', async () => { + const fakePath = '/rendered/path/model'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + model: 'modelValue', + }; + const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.modelPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.modelPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('modelPath', () => { + const result = client.modelPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'modelValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.modelPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromModelName', () => { + const result = client.matchProjectFromModelName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromModelName', () => { + const result = client.matchLocationFromModelName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromModelName', () => { + const result = client.matchCatalogFromModelName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchModelFromModelName', () => { + const result = client.matchModelFromModelName(fakePath); + assert.strictEqual(result, 'modelValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchLocationFromServingConfigName', () => { - const result = client.matchLocationFromServingConfigName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.servingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('product', async () => { + const fakePath = '/rendered/path/product'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + branch: 'branchValue', + product: 'productValue', + }; + const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.productPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.productPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('productPath', () => { + const result = client.productPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'branchValue', + 'productValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.productPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProductName', () => { + const result = client.matchProjectFromProductName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromProductName', () => { + const result = client.matchLocationFromProductName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromProductName', () => { + const result = client.matchCatalogFromProductName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBranchFromProductName', () => { + const result = client.matchBranchFromProductName(fakePath); + assert.strictEqual(result, 'branchValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchProductFromProductName', () => { + const result = client.matchProductFromProductName(fakePath); + assert.strictEqual(result, 'productValue'); + assert( + (client.pathTemplates.productPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchCatalogFromServingConfigName', () => { - const result = client.matchCatalogFromServingConfigName(fakePath); - assert.strictEqual(result, "catalogValue"); - assert((client.pathTemplates.servingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('retailProject', async () => { + const fakePath = '/rendered/path/retailProject'; + const expectedParameters = { + project: 'projectValue', + }; + const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.retailProjectPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.retailProjectPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('retailProjectPath', () => { + const result = client.retailProjectPath('projectValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.retailProjectPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromRetailProjectName', () => { + const result = client.matchProjectFromRetailProjectName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.retailProjectPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchServingConfigFromServingConfigName', () => { - const result = client.matchServingConfigFromServingConfigName(fakePath); - assert.strictEqual(result, "servingConfigValue"); - assert((client.pathTemplates.servingConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('servingConfig', async () => { + const fakePath = '/rendered/path/servingConfig'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + catalog: 'catalogValue', + serving_config: 'servingConfigValue', + }; + const client = new usereventserviceModule.v2alpha.UserEventServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.servingConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.servingConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('servingConfigPath', () => { + const result = client.servingConfigPath( + 'projectValue', + 'locationValue', + 'catalogValue', + 'servingConfigValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.servingConfigPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromServingConfigName', () => { + const result = client.matchProjectFromServingConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.servingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromServingConfigName', () => { + const result = client.matchLocationFromServingConfigName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.servingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCatalogFromServingConfigName', () => { + const result = client.matchCatalogFromServingConfigName(fakePath); + assert.strictEqual(result, 'catalogValue'); + assert( + (client.pathTemplates.servingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServingConfigFromServingConfigName', () => { + const result = client.matchServingConfigFromServingConfigName(fakePath); + assert.strictEqual(result, 'servingConfigValue'); + assert( + (client.pathTemplates.servingConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/core/generator/gapic-generator-typescript/baselines/routingtest-esm/esm/src/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/routingtest-esm/esm/src/index.ts.baseline index e0b9fe7c0ad7..372ad98bd593 100644 --- a/core/generator/gapic-generator-typescript/baselines/routingtest-esm/esm/src/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/routingtest-esm/esm/src/index.ts.baseline @@ -19,8 +19,8 @@ import * as v1 from './v1/index.js'; const TestServiceClient = v1.TestServiceClient; type TestServiceClient = v1.TestServiceClient; -export {v1, TestServiceClient}; -export default {v1, TestServiceClient}; +export { v1, TestServiceClient }; +export default { v1, TestServiceClient }; // @ts-ignore import * as protos from '../../protos/protos.js'; -export {protos} +export { protos }; diff --git a/core/generator/gapic-generator-typescript/baselines/routingtest-esm/esm/src/v1/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/routingtest-esm/esm/src/v1/index.ts.baseline index d023b4366ab3..14836d947225 100644 --- a/core/generator/gapic-generator-typescript/baselines/routingtest-esm/esm/src/v1/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/routingtest-esm/esm/src/v1/index.ts.baseline @@ -16,4 +16,4 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -export {TestServiceClient} from './test_service_client.js'; +export { TestServiceClient } from './test_service_client.js'; diff --git a/core/generator/gapic-generator-typescript/baselines/routingtest-esm/esm/src/v1/test_service_client.ts.baseline b/core/generator/gapic-generator-typescript/baselines/routingtest-esm/esm/src/v1/test_service_client.ts.baseline index ba7217a0b2cf..134597becf1e 100644 --- a/core/generator/gapic-generator-typescript/baselines/routingtest-esm/esm/src/v1/test_service_client.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/routingtest-esm/esm/src/v1/test_service_client.ts.baseline @@ -18,15 +18,20 @@ /* global window */ import * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions} from 'google-gax'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, +} from 'google-gax'; // @ts-ignore import type * as protos from '../../../protos/protos.js'; import * as test_service_client_config from './test_service_client_config.json'; import fs from 'fs'; import path from 'path'; -import {fileURLToPath} from 'url'; -import {getJSON} from '../json-helper.cjs'; +import { fileURLToPath } from 'url'; +import { getJSON } from '../json-helper.cjs'; // @ts-ignore const dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -36,15 +41,15 @@ const dirname = path.dirname(fileURLToPath(import.meta.url)); * This file defines retry strategy and timeouts for all API methods in this library. */ const gapicConfig = getJSON( - path.join(dirname, 'test_service_client_config.json') + path.join(dirname, 'test_service_client_config.json'), ); const jsonProtos = getJSON( - path.join(dirname, '..', '..', '..', 'protos/protos.json') + path.join(dirname, '..', '..', '..', 'protos/protos.json'), ); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; const version = getJSON( - path.join(dirname, '..', '..', '..', '..', 'package.json') + path.join(dirname, '..', '..', '..', '..', 'package.json'), ).version; /** @@ -60,7 +65,7 @@ export class TestServiceClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('routingtest'); @@ -72,8 +77,8 @@ export class TestServiceClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - testServiceStub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + testServiceStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of TestServiceClient. @@ -115,21 +120,42 @@ export class TestServiceClient { * const client = new TestServiceClient({fallback: 'rest'}, gax); * ``` */ - constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { // Ensure that options include all the required fields. const staticMembers = this.constructor as typeof TestServiceClient; - if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { - throw new Error('Please set either universe_domain or universeDomain, but not both.'); + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); } - const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; - this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; this._servicePath = 'localhost'; - const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; - const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. if (servicePath !== this._servicePath && !('scopes' in opts)) { @@ -151,7 +177,7 @@ export class TestServiceClient { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; @@ -168,10 +194,7 @@ export class TestServiceClient { const isEsm = true; const isEsmString = isEsm ? '-esm' : '-cjs'; // Determine the client header string. - const clientHeader = [ - `gax/${this._gaxModule.version}`, - `gapic/${version}`, - ]; + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/{process.versions.node}${isEsmString}`); } else { @@ -179,7 +202,7 @@ export class TestServiceClient { } if (!opts.fallback) { clientHeader.push(`grpc/${this._gaxGrpc.grpcVersion}`); - } else if (opts.fallback === 'rest' ) { + } else if (opts.fallback === 'rest') { clientHeader.push(`rest/${this._gaxGrpc.grpcVersion}`); } if (opts.libName && opts.libVersion) { @@ -187,12 +210,17 @@ export class TestServiceClient { } // Load the applicable protos. - this._protos = this._gaxGrpc.loadProtoJSON(jsonProtos as gax.protobuf.INamespace); + this._protos = this._gaxGrpc.loadProtoJSON( + jsonProtos as gax.protobuf.INamespace, + ); // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.routingtest.v1.TestService', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.routingtest.v1.TestService', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + { 'x-goog-api-client': clientHeader.join(' ') }, + ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -223,36 +251,44 @@ export class TestServiceClient { // Put together the "service stub" for // google.routingtest.v1.TestService. this.testServiceStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.routingtest.v1.TestService') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.routingtest.v1.TestService', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.routingtest.v1.TestService, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts, + this._providedCustomServicePath, + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const testServiceStubMethods = - ['fastFibonacci', 'randomFibonacci', 'slowFibonacci']; + const testServiceStubMethods = [ + 'fastFibonacci', + 'randomFibonacci', + 'slowFibonacci', + ]; for (const methodName of testServiceStubMethods) { const callPromise = this.testServiceStub.then( - stub => (...args: Array<{}>) => { - if (this._terminated) { - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error|null|undefined) => () => { + (stub) => + (...args: Array<{}>) => { + if (this._terminated) { + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { throw err; - }); + }, + ); - const descriptor = - undefined; + const descriptor = undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -267,8 +303,14 @@ export class TestServiceClient { * @returns {string} The DNS address for this service. */ static get servicePath() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'localhost'; } @@ -280,8 +322,14 @@ export class TestServiceClient { * @returns {string} The DNS address for this service. */ static get apiEndpoint() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'localhost'; } @@ -312,9 +360,7 @@ export class TestServiceClient { * @returns {string[]} List of default scopes. */ static get scopes() { - return [ - 'https://www.googleapis.com/auth/cloud-platform' - ]; + return ['https://www.googleapis.com/auth/cloud-platform']; } getProjectId(): Promise; @@ -323,8 +369,9 @@ export class TestServiceClient { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId(callback?: Callback): - Promise|void { + getProjectId( + callback?: Callback, + ): Promise | void { if (callback) { this.auth.getProjectId(callback); return; @@ -335,69 +382,82 @@ export class TestServiceClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Calculates Fibonacci on the provided value, quickly. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.routingtest.v1.FibonacciRequest.Inner1} request.nest1 - * @param {number} request.value - * The nth term to retrieve in the Fibonacci sequence. - * @param {string} request.name - * This is for testing the routing annotation. - * @param {string} request.parentId - * This is for testing the routing annotation. - * @param {string} request.anotherParentId - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1/test_service.fast_fibonacci.js - * region_tag:localhost_v1_generated_TestService_FastFibonacci_async - */ + /** + * Calculates Fibonacci on the provided value, quickly. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.routingtest.v1.FibonacciRequest.Inner1} request.nest1 + * @param {number} request.value + * The nth term to retrieve in the Fibonacci sequence. + * @param {string} request.name + * This is for testing the routing annotation. + * @param {string} request.parentId + * This is for testing the routing annotation. + * @param {string} request.anotherParentId + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/test_service.fast_fibonacci.js + * region_tag:localhost_v1_generated_TestService_FastFibonacci_async + */ fastFibonacci( - request?: protos.google.routingtest.v1.IFibonacciRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.routingtest.v1.IFibonacciRequest|undefined, {}|undefined - ]>; + request?: protos.google.routingtest.v1.IFibonacciRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.routingtest.v1.IFibonacciRequest | undefined, + {} | undefined, + ] + >; fastFibonacci( - request: protos.google.routingtest.v1.IFibonacciRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.routingtest.v1.IFibonacciRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.routingtest.v1.IFibonacciRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.routingtest.v1.IFibonacciRequest | null | undefined, + {} | null | undefined + >, + ): void; fastFibonacci( - request: protos.google.routingtest.v1.IFibonacciRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.routingtest.v1.IFibonacciRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.routingtest.v1.IFibonacciRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.routingtest.v1.IFibonacciRequest | null | undefined, + {} | null | undefined + >, + ): void; fastFibonacci( - request?: protos.google.routingtest.v1.IFibonacciRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.routingtest.v1.IFibonacciRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.routingtest.v1.IFibonacciRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.protobuf.IEmpty, - protos.google.routingtest.v1.IFibonacciRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.routingtest.v1.IFibonacciRequest|undefined, {}|undefined - ]>|void { + protos.google.routingtest.v1.IFibonacciRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + protos.google.routingtest.v1.IFibonacciRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.routingtest.v1.IFibonacciRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; @@ -407,107 +467,140 @@ export class TestServiceClient { { const fieldValue = request.name; if (fieldValue !== undefined && fieldValue !== null) { - const match = fieldValue.toString().match(RegExp('(?projects/[^/]+/databases/[^/]+)/documents')); + const match = fieldValue + .toString() + .match( + RegExp('(?projects/[^/]+/databases/[^/]+)/documents'), + ); if (match) { const parameterValue = match.groups?.['database'] ?? fieldValue; Object.assign(routingParameter, { database: parameterValue }); } } } - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams( - routingParameter - ); - this.initialize().catch(err => {throw err}); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams(routingParameter); + this.initialize().catch((err) => { + throw err; + }); this._log.info('fastFibonacci request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.routingtest.v1.IFibonacciRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + protos.google.routingtest.v1.IFibonacciRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('fastFibonacci response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.fastFibonacci(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.routingtest.v1.IFibonacciRequest|undefined, {}|undefined - ]) => { - this._log.info('fastFibonacci response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .fastFibonacci(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.routingtest.v1.IFibonacciRequest | undefined, + {} | undefined, + ]) => { + this._log.info('fastFibonacci response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Calculates Fibonacci on the provided value, randomly. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.routingtest.v1.FibonacciRequest.Inner1} request.nest1 - * @param {number} request.value - * The nth term to retrieve in the Fibonacci sequence. - * @param {string} request.name - * This is for testing the routing annotation. - * @param {string} request.parentId - * This is for testing the routing annotation. - * @param {string} request.anotherParentId - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1/test_service.random_fibonacci.js - * region_tag:localhost_v1_generated_TestService_RandomFibonacci_async - */ + /** + * Calculates Fibonacci on the provided value, randomly. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.routingtest.v1.FibonacciRequest.Inner1} request.nest1 + * @param {number} request.value + * The nth term to retrieve in the Fibonacci sequence. + * @param {string} request.name + * This is for testing the routing annotation. + * @param {string} request.parentId + * This is for testing the routing annotation. + * @param {string} request.anotherParentId + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/test_service.random_fibonacci.js + * region_tag:localhost_v1_generated_TestService_RandomFibonacci_async + */ randomFibonacci( - request?: protos.google.routingtest.v1.IFibonacciRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.routingtest.v1.IFibonacciRequest|undefined, {}|undefined - ]>; + request?: protos.google.routingtest.v1.IFibonacciRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.routingtest.v1.IFibonacciRequest | undefined, + {} | undefined, + ] + >; randomFibonacci( - request: protos.google.routingtest.v1.IFibonacciRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.routingtest.v1.IFibonacciRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.routingtest.v1.IFibonacciRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.routingtest.v1.IFibonacciRequest | null | undefined, + {} | null | undefined + >, + ): void; randomFibonacci( - request: protos.google.routingtest.v1.IFibonacciRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.routingtest.v1.IFibonacciRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.routingtest.v1.IFibonacciRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.routingtest.v1.IFibonacciRequest | null | undefined, + {} | null | undefined + >, + ): void; randomFibonacci( - request?: protos.google.routingtest.v1.IFibonacciRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.protobuf.IEmpty, - protos.google.routingtest.v1.IFibonacciRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.routingtest.v1.IFibonacciRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.routingtest.v1.IFibonacciRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.routingtest.v1.IFibonacciRequest|undefined, {}|undefined - ]>|void { + protos.google.routingtest.v1.IFibonacciRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + protos.google.routingtest.v1.IFibonacciRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.routingtest.v1.IFibonacciRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; @@ -527,107 +620,138 @@ export class TestServiceClient { { const fieldValue = request.name; if (fieldValue !== undefined && fieldValue !== null) { - const match = fieldValue.toString().match(RegExp('(?(?:.*)?)')); + const match = fieldValue + .toString() + .match(RegExp('(?(?:.*)?)')); if (match) { const parameterValue = match.groups?.['routing_id'] ?? fieldValue; Object.assign(routingParameter, { routing_id: parameterValue }); } } } - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams( - routingParameter - ); - this.initialize().catch(err => {throw err}); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams(routingParameter); + this.initialize().catch((err) => { + throw err; + }); this._log.info('randomFibonacci request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.routingtest.v1.IFibonacciRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + protos.google.routingtest.v1.IFibonacciRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('randomFibonacci response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.randomFibonacci(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.routingtest.v1.IFibonacciRequest|undefined, {}|undefined - ]) => { - this._log.info('randomFibonacci response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .randomFibonacci(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.routingtest.v1.IFibonacciRequest | undefined, + {} | undefined, + ]) => { + this._log.info('randomFibonacci response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Calculates Fibonacci on the provided value, slowly. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.routingtest.v1.FibonacciRequest.Inner1} request.nest1 - * @param {number} request.value - * The nth term to retrieve in the Fibonacci sequence. - * @param {string} request.name - * This is for testing the routing annotation. - * @param {string} request.parentId - * This is for testing the routing annotation. - * @param {string} request.anotherParentId - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1/test_service.slow_fibonacci.js - * region_tag:localhost_v1_generated_TestService_SlowFibonacci_async - */ + /** + * Calculates Fibonacci on the provided value, slowly. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.routingtest.v1.FibonacciRequest.Inner1} request.nest1 + * @param {number} request.value + * The nth term to retrieve in the Fibonacci sequence. + * @param {string} request.name + * This is for testing the routing annotation. + * @param {string} request.parentId + * This is for testing the routing annotation. + * @param {string} request.anotherParentId + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/test_service.slow_fibonacci.js + * region_tag:localhost_v1_generated_TestService_SlowFibonacci_async + */ slowFibonacci( - request?: protos.google.routingtest.v1.IFibonacciRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.routingtest.v1.IFibonacciRequest|undefined, {}|undefined - ]>; + request?: protos.google.routingtest.v1.IFibonacciRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.routingtest.v1.IFibonacciRequest | undefined, + {} | undefined, + ] + >; slowFibonacci( - request: protos.google.routingtest.v1.IFibonacciRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.routingtest.v1.IFibonacciRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.routingtest.v1.IFibonacciRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.routingtest.v1.IFibonacciRequest | null | undefined, + {} | null | undefined + >, + ): void; slowFibonacci( - request: protos.google.routingtest.v1.IFibonacciRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.routingtest.v1.IFibonacciRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.routingtest.v1.IFibonacciRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.routingtest.v1.IFibonacciRequest | null | undefined, + {} | null | undefined + >, + ): void; slowFibonacci( - request?: protos.google.routingtest.v1.IFibonacciRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.protobuf.IEmpty, - protos.google.routingtest.v1.IFibonacciRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.routingtest.v1.IFibonacciRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.routingtest.v1.IFibonacciRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.routingtest.v1.IFibonacciRequest|undefined, {}|undefined - ]>|void { + protos.google.routingtest.v1.IFibonacciRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + protos.google.routingtest.v1.IFibonacciRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.routingtest.v1.IFibonacciRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; @@ -637,7 +761,9 @@ export class TestServiceClient { { const fieldValue = request.parentId; if (fieldValue !== undefined && fieldValue !== null) { - const match = fieldValue.toString().match(RegExp('(?projects/[^/]+)')); + const match = fieldValue + .toString() + .match(RegExp('(?projects/[^/]+)')); if (match) { const parameterValue = match.groups?.['database'] ?? fieldValue; Object.assign(routingParameter, { database: parameterValue }); @@ -647,7 +773,11 @@ export class TestServiceClient { { const fieldValue = request.nest1?.nest2?.nameId; if (fieldValue !== undefined && fieldValue !== null) { - const match = fieldValue.toString().match(RegExp('(?projects/[^/]+/databases/[^/]+)/documents')); + const match = fieldValue + .toString() + .match( + RegExp('(?projects/[^/]+/databases/[^/]+)/documents'), + ); if (match) { const parameterValue = match.groups?.['database'] ?? fieldValue; Object.assign(routingParameter, { database: parameterValue }); @@ -657,46 +787,65 @@ export class TestServiceClient { { const fieldValue = request.anotherParentId; if (fieldValue !== undefined && fieldValue !== null) { - const match = fieldValue.toString().match(RegExp('(?projects/[^/]+)/databases/[^/]+/documents')); + const match = fieldValue + .toString() + .match( + RegExp('(?projects/[^/]+)/databases/[^/]+/documents'), + ); if (match) { const parameterValue = match.groups?.['routing_id'] ?? fieldValue; Object.assign(routingParameter, { routing_id: parameterValue }); } } } - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams( - routingParameter - ); - this.initialize().catch(err => {throw err}); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams(routingParameter); + this.initialize().catch((err) => { + throw err; + }); this._log.info('slowFibonacci request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.routingtest.v1.IFibonacciRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + protos.google.routingtest.v1.IFibonacciRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('slowFibonacci response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.slowFibonacci(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.routingtest.v1.IFibonacciRequest|undefined, {}|undefined - ]) => { - this._log.info('slowFibonacci response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .slowFibonacci(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.routingtest.v1.IFibonacciRequest | undefined, + {} | undefined, + ]) => { + this._log.info('slowFibonacci response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } - /** * Terminate the gRPC channel and close the client. * @@ -705,7 +854,7 @@ export class TestServiceClient { */ close(): Promise { if (this.testServiceStub && !this._terminated) { - return this.testServiceStub.then(stub => { + return this.testServiceStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -713,4 +862,4 @@ export class TestServiceClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/core/generator/gapic-generator-typescript/baselines/routingtest-esm/esm/system-test/fixtures/sample/src/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/routingtest-esm/esm/system-test/fixtures/sample/src/index.ts.baseline index a07bf100be47..e78f3939d820 100644 --- a/core/generator/gapic-generator-typescript/baselines/routingtest-esm/esm/system-test/fixtures/sample/src/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/routingtest-esm/esm/system-test/fixtures/sample/src/index.ts.baseline @@ -17,7 +17,7 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -import {TestServiceClient} from 'routingtest'; +import { TestServiceClient } from 'routingtest'; // check that the client class type name can be used function doStuffWithTestServiceClient(client: TestServiceClient) { diff --git a/core/generator/gapic-generator-typescript/baselines/routingtest-esm/esm/system-test/install.ts.baseline b/core/generator/gapic-generator-typescript/baselines/routingtest-esm/esm/system-test/install.ts.baseline index e079c4fa1101..d109fdd8c97f 100644 --- a/core/generator/gapic-generator-typescript/baselines/routingtest-esm/esm/system-test/install.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/routingtest-esm/esm/system-test/install.ts.baseline @@ -16,40 +16,45 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -import {packNTest} from 'pack-n-play'; -import {readFileSync} from 'fs'; -import {describe, it} from 'mocha'; +import { packNTest } from 'pack-n-play'; +import { readFileSync } from 'fs'; +import { describe, it } from 'mocha'; describe('📦 pack-n-play test', () => { - it('TypeScript', async function() { + it('TypeScript', async function () { this.timeout(300000); await packNTest({ packageDir: process.cwd(), sample: { description: 'TypeScript user can use the type definitions', - ts: readFileSync('./esm/system-test/fixtures/sample/src/index.ts').toString() - } + ts: readFileSync( + './esm/system-test/fixtures/sample/src/index.ts', + ).toString(), + }, }); }); - it('ESM module', async function() { + it('ESM module', async function () { this.timeout(300000); await packNTest({ sample: { description: 'Should be able to import using ESM', - esm: readFileSync('./esm/system-test/fixtures/sample/src/index.js').toString(), + esm: readFileSync( + './esm/system-test/fixtures/sample/src/index.js', + ).toString(), }, }); }); - it('CJS module', async function() { + it('CJS module', async function () { this.timeout(300000); await packNTest({ sample: { description: 'Should be able to import using CJS', - cjs: readFileSync('./esm/system-test/fixtures/sample/src/index.cjs').toString(), + cjs: readFileSync( + './esm/system-test/fixtures/sample/src/index.cjs', + ).toString(), }, }); }); - }); diff --git a/core/generator/gapic-generator-typescript/baselines/routingtest-esm/esm/test/gapic_test_service_v1.ts.baseline b/core/generator/gapic-generator-typescript/baselines/routingtest-esm/esm/test/gapic_test_service_v1.ts.baseline index 274ac5a2f027..9c805d838af3 100644 --- a/core/generator/gapic-generator-typescript/baselines/routingtest-esm/esm/test/gapic_test_service_v1.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/routingtest-esm/esm/test/gapic_test_service_v1.ts.baseline @@ -20,14 +20,14 @@ import * as protos from '../../protos/protos.js'; import assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as testserviceModule from '../src/index.js'; -import {protobuf} from 'google-gax'; +import { protobuf } from 'google-gax'; import fs from 'fs'; import path from 'path'; -import {fileURLToPath} from 'url'; +import { fileURLToPath } from 'url'; // @ts-ignore const dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -35,460 +35,547 @@ const dirname = path.dirname(fileURLToPath(import.meta.url)); // to fill in default values for request objects const root = protobuf.Root.fromJSON( JSON.parse( - fs.readFileSync(path.join(dirname, '..', '..', 'protos/protos.json'), 'utf8') - )) + fs.readFileSync( + path.join(dirname, '..', '..', 'protos/protos.json'), + 'utf8', + ), + ), +); // eslint-disable-next-line @typescript-eslint/no-unused-vars function getTypeDefaultValue(typeName: string, fields: string[]) { - let type = root.lookupType(typeName) as protobuf.Type; - for (const field of fields.slice(0, -1)) { - type = type?.fields[field]?.resolvedType as protobuf.Type; - } - return type?.fields[fields[fields.length - 1]]?.defaultValue ?? null; + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type?.fields[field]?.resolvedType as protobuf.Type; + } + return type?.fields[fields[fields.length - 1]]?.defaultValue ?? null; } function generateSampleMessage(instance: T) { - const filledObject = (instance.constructor as typeof protobuf.Message) - .toObject(instance as protobuf.Message, {defaults: true}); - return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, { defaults: true }); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; } function stubSimpleCall(response?: ResponseType, error?: Error) { - return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); } -function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { - return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +function stubSimpleCallWithCallback( + response?: ResponseType, + error?: Error, +) { + return error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); } describe('v1.TestServiceClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new testserviceModule.v1.TestServiceClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'localhost'); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new testserviceModule.v1.TestServiceClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'localhost'); + }); - it('has universeDomain', () => { - const client = new testserviceModule.v1.TestServiceClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); + it('has universeDomain', () => { + const client = new testserviceModule.v1.TestServiceClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - it('throws DeprecationWarning if static servicePath is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const servicePath = testserviceModule.v1.TestServiceClient.servicePath; - assert.strictEqual(servicePath, 'localhost'); - assert(stub.called); - stub.restore(); - }); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = testserviceModule.v1.TestServiceClient.servicePath; + assert.strictEqual(servicePath, 'localhost'); + assert(stub.called); + stub.restore(); + }); - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = testserviceModule.v1.TestServiceClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'localhost'); - assert(stub.called); - stub.restore(); - }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { new testserviceModule.v1.TestServiceClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = testserviceModule.v1.TestServiceClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'localhost'); + assert(stub.called); + stub.restore(); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new testserviceModule.v1.TestServiceClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); + }); - it('has port', () => { - const port = testserviceModule.v1.TestServiceClient.port; - assert(port); - assert(typeof port === 'number'); - }); + it('has port', () => { + const port = testserviceModule.v1.TestServiceClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('should create a client with no option', () => { - const client = new testserviceModule.v1.TestServiceClient(); - assert(client); - }); + it('should create a client with no option', () => { + const client = new testserviceModule.v1.TestServiceClient(); + assert(client); + }); - it('should create a client with gRPC fallback', () => { - const client = new testserviceModule.v1.TestServiceClient({ - fallback: true, - }); - assert(client); - }); + it('should create a client with gRPC fallback', () => { + const client = new testserviceModule.v1.TestServiceClient({ + fallback: true, + }); + assert(client); + }); - it('has initialize method and supports deferred initialization', async () => { - const client = new testserviceModule.v1.TestServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.testServiceStub, undefined); - await client.initialize(); - assert(client.testServiceStub); - }); + it('has initialize method and supports deferred initialization', async () => { + const client = new testserviceModule.v1.TestServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.testServiceStub, undefined); + await client.initialize(); + assert(client.testServiceStub); + }); - it('has close method for the initialized client', done => { - const client = new testserviceModule.v1.TestServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.testServiceStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); + it('has close method for the initialized client', (done) => { + const client = new testserviceModule.v1.TestServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.testServiceStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('has close method for the non-initialized client', done => { - const client = new testserviceModule.v1.TestServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.testServiceStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); + it('has close method for the non-initialized client', (done) => { + const client = new testserviceModule.v1.TestServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.testServiceStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new testserviceModule.v1.TestServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); - }); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new testserviceModule.v1.TestServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + }); - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new testserviceModule.v1.TestServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId((err?: Error|null, projectId?: string|null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } - }); - }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new testserviceModule.v1.TestServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); }); + }); - describe('fastFibonacci', () => { - it('invokes fastFibonacci without error', async () => { - const client = new testserviceModule.v1.TestServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.routingtest.v1.FibonacciRequest() - ); - // path template: {database=projects/*/databases/*}/documents - request.name = 'projects/value/databases/value/documents'; - const expectedHeaderRequestParams = 'database=projects%2Fvalue%2Fdatabases%2Fvalue'; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.fastFibonacci = stubSimpleCall(expectedResponse); - const [response] = await client.fastFibonacci(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.fastFibonacci as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.fastFibonacci as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + describe('fastFibonacci', () => { + it('invokes fastFibonacci without error', async () => { + const client = new testserviceModule.v1.TestServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.routingtest.v1.FibonacciRequest(), + ); + // path template: {database=projects/*/databases/*}/documents + request.name = 'projects/value/databases/value/documents'; + const expectedHeaderRequestParams = + 'database=projects%2Fvalue%2Fdatabases%2Fvalue'; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.fastFibonacci = stubSimpleCall(expectedResponse); + const [response] = await client.fastFibonacci(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.fastFibonacci as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.fastFibonacci as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes fastFibonacci without error using callback', async () => { - const client = new testserviceModule.v1.TestServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.routingtest.v1.FibonacciRequest() - ); - // path template: {database=projects/*/databases/*}/documents - request.name = 'projects/value/databases/value/documents'; - const expectedHeaderRequestParams = 'database=projects%2Fvalue%2Fdatabases%2Fvalue'; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.fastFibonacci = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.fastFibonacci( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.fastFibonacci as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.fastFibonacci as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes fastFibonacci without error using callback', async () => { + const client = new testserviceModule.v1.TestServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.routingtest.v1.FibonacciRequest(), + ); + // path template: {database=projects/*/databases/*}/documents + request.name = 'projects/value/databases/value/documents'; + const expectedHeaderRequestParams = + 'database=projects%2Fvalue%2Fdatabases%2Fvalue'; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.fastFibonacci = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.fastFibonacci( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.fastFibonacci as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.fastFibonacci as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes fastFibonacci with error', async () => { - const client = new testserviceModule.v1.TestServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.routingtest.v1.FibonacciRequest() - ); - // path template: {database=projects/*/databases/*}/documents - request.name = 'projects/value/databases/value/documents'; - const expectedHeaderRequestParams = 'database=projects%2Fvalue%2Fdatabases%2Fvalue'; - const expectedError = new Error('expected'); - client.innerApiCalls.fastFibonacci = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.fastFibonacci(request), expectedError); - const actualRequest = (client.innerApiCalls.fastFibonacci as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.fastFibonacci as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes fastFibonacci with error', async () => { + const client = new testserviceModule.v1.TestServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.routingtest.v1.FibonacciRequest(), + ); + // path template: {database=projects/*/databases/*}/documents + request.name = 'projects/value/databases/value/documents'; + const expectedHeaderRequestParams = + 'database=projects%2Fvalue%2Fdatabases%2Fvalue'; + const expectedError = new Error('expected'); + client.innerApiCalls.fastFibonacci = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.fastFibonacci(request), expectedError); + const actualRequest = ( + client.innerApiCalls.fastFibonacci as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.fastFibonacci as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes fastFibonacci with closed client', async () => { - const client = new testserviceModule.v1.TestServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.routingtest.v1.FibonacciRequest() - ); - // path template: {database=projects/*/databases/*}/documents - request.name = 'projects/value/databases/value/documents'; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.fastFibonacci(request), expectedError); - }); + it('invokes fastFibonacci with closed client', async () => { + const client = new testserviceModule.v1.TestServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.routingtest.v1.FibonacciRequest(), + ); + // path template: {database=projects/*/databases/*}/documents + request.name = 'projects/value/databases/value/documents'; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.fastFibonacci(request), expectedError); }); + }); - describe('randomFibonacci', () => { - it('invokes randomFibonacci without error', async () => { - const client = new testserviceModule.v1.TestServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.routingtest.v1.FibonacciRequest() - ); - // path template: {routing_id=**} - request.name = 'value'; - const expectedHeaderRequestParams = 'routing_id=value'; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.randomFibonacci = stubSimpleCall(expectedResponse); - const [response] = await client.randomFibonacci(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.randomFibonacci as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.randomFibonacci as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + describe('randomFibonacci', () => { + it('invokes randomFibonacci without error', async () => { + const client = new testserviceModule.v1.TestServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.routingtest.v1.FibonacciRequest(), + ); + // path template: {routing_id=**} + request.name = 'value'; + const expectedHeaderRequestParams = 'routing_id=value'; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.randomFibonacci = stubSimpleCall(expectedResponse); + const [response] = await client.randomFibonacci(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.randomFibonacci as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.randomFibonacci as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes randomFibonacci without error using callback', async () => { - const client = new testserviceModule.v1.TestServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.routingtest.v1.FibonacciRequest() - ); - // path template: {routing_id=**} - request.name = 'value'; - const expectedHeaderRequestParams = 'routing_id=value'; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.randomFibonacci = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.randomFibonacci( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.randomFibonacci as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.randomFibonacci as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes randomFibonacci without error using callback', async () => { + const client = new testserviceModule.v1.TestServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.routingtest.v1.FibonacciRequest(), + ); + // path template: {routing_id=**} + request.name = 'value'; + const expectedHeaderRequestParams = 'routing_id=value'; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.randomFibonacci = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.randomFibonacci( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.randomFibonacci as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.randomFibonacci as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes randomFibonacci with error', async () => { - const client = new testserviceModule.v1.TestServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.routingtest.v1.FibonacciRequest() - ); - // path template: {routing_id=**} - request.name = 'value'; - const expectedHeaderRequestParams = 'routing_id=value'; - const expectedError = new Error('expected'); - client.innerApiCalls.randomFibonacci = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.randomFibonacci(request), expectedError); - const actualRequest = (client.innerApiCalls.randomFibonacci as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.randomFibonacci as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes randomFibonacci with error', async () => { + const client = new testserviceModule.v1.TestServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.routingtest.v1.FibonacciRequest(), + ); + // path template: {routing_id=**} + request.name = 'value'; + const expectedHeaderRequestParams = 'routing_id=value'; + const expectedError = new Error('expected'); + client.innerApiCalls.randomFibonacci = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.randomFibonacci(request), expectedError); + const actualRequest = ( + client.innerApiCalls.randomFibonacci as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.randomFibonacci as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes randomFibonacci with closed client', async () => { - const client = new testserviceModule.v1.TestServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.routingtest.v1.FibonacciRequest() - ); - // path template: {routing_id=**} - request.name = 'value'; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.randomFibonacci(request), expectedError); - }); + it('invokes randomFibonacci with closed client', async () => { + const client = new testserviceModule.v1.TestServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.routingtest.v1.FibonacciRequest(), + ); + // path template: {routing_id=**} + request.name = 'value'; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.randomFibonacci(request), expectedError); }); + }); - describe('slowFibonacci', () => { - it('invokes slowFibonacci without error', async () => { - const client = new testserviceModule.v1.TestServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.routingtest.v1.FibonacciRequest() - ); - // path template: {routing_id=projects/*}/databases/*/documents - request.anotherParentId = 'projects/value/databases/value/documents'; - const expectedHeaderRequestParams = 'routing_id=projects%2Fvalue'; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.slowFibonacci = stubSimpleCall(expectedResponse); - const [response] = await client.slowFibonacci(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.slowFibonacci as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.slowFibonacci as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + describe('slowFibonacci', () => { + it('invokes slowFibonacci without error', async () => { + const client = new testserviceModule.v1.TestServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.routingtest.v1.FibonacciRequest(), + ); + // path template: {routing_id=projects/*}/databases/*/documents + request.anotherParentId = 'projects/value/databases/value/documents'; + const expectedHeaderRequestParams = 'routing_id=projects%2Fvalue'; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.slowFibonacci = stubSimpleCall(expectedResponse); + const [response] = await client.slowFibonacci(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.slowFibonacci as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.slowFibonacci as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes slowFibonacci without error using callback', async () => { - const client = new testserviceModule.v1.TestServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.routingtest.v1.FibonacciRequest() - ); - // path template: {routing_id=projects/*}/databases/*/documents - request.anotherParentId = 'projects/value/databases/value/documents'; - const expectedHeaderRequestParams = 'routing_id=projects%2Fvalue'; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.slowFibonacci = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.slowFibonacci( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.slowFibonacci as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.slowFibonacci as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes slowFibonacci without error using callback', async () => { + const client = new testserviceModule.v1.TestServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.routingtest.v1.FibonacciRequest(), + ); + // path template: {routing_id=projects/*}/databases/*/documents + request.anotherParentId = 'projects/value/databases/value/documents'; + const expectedHeaderRequestParams = 'routing_id=projects%2Fvalue'; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.slowFibonacci = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.slowFibonacci( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.slowFibonacci as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.slowFibonacci as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes slowFibonacci with error', async () => { - const client = new testserviceModule.v1.TestServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.routingtest.v1.FibonacciRequest() - ); - // path template: {routing_id=projects/*}/databases/*/documents - request.anotherParentId = 'projects/value/databases/value/documents'; - const expectedHeaderRequestParams = 'routing_id=projects%2Fvalue'; - const expectedError = new Error('expected'); - client.innerApiCalls.slowFibonacci = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.slowFibonacci(request), expectedError); - const actualRequest = (client.innerApiCalls.slowFibonacci as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.slowFibonacci as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes slowFibonacci with error', async () => { + const client = new testserviceModule.v1.TestServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.routingtest.v1.FibonacciRequest(), + ); + // path template: {routing_id=projects/*}/databases/*/documents + request.anotherParentId = 'projects/value/databases/value/documents'; + const expectedHeaderRequestParams = 'routing_id=projects%2Fvalue'; + const expectedError = new Error('expected'); + client.innerApiCalls.slowFibonacci = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.slowFibonacci(request), expectedError); + const actualRequest = ( + client.innerApiCalls.slowFibonacci as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.slowFibonacci as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes slowFibonacci with closed client', async () => { - const client = new testserviceModule.v1.TestServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.routingtest.v1.FibonacciRequest() - ); - // path template: {routing_id=projects/*}/databases/*/documents - request.anotherParentId = 'projects/value/databases/value/documents'; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.slowFibonacci(request), expectedError); - }); + it('invokes slowFibonacci with closed client', async () => { + const client = new testserviceModule.v1.TestServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.routingtest.v1.FibonacciRequest(), + ); + // path template: {routing_id=projects/*}/databases/*/documents + request.anotherParentId = 'projects/value/databases/value/documents'; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.slowFibonacci(request), expectedError); }); + }); }); diff --git a/core/generator/gapic-generator-typescript/baselines/routingtest/src/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/routingtest/src/index.ts.baseline index 3ab98078f086..47a8bd88f355 100644 --- a/core/generator/gapic-generator-typescript/baselines/routingtest/src/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/routingtest/src/index.ts.baseline @@ -19,7 +19,7 @@ import * as v1 from './v1'; const TestServiceClient = v1.TestServiceClient; type TestServiceClient = v1.TestServiceClient; -export {v1, TestServiceClient}; -export default {v1, TestServiceClient}; +export { v1, TestServiceClient }; +export default { v1, TestServiceClient }; import * as protos from '../protos/protos'; -export {protos} +export { protos }; diff --git a/core/generator/gapic-generator-typescript/baselines/routingtest/src/v1/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/routingtest/src/v1/index.ts.baseline index ae9662f6819c..766b0ac7d4fc 100644 --- a/core/generator/gapic-generator-typescript/baselines/routingtest/src/v1/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/routingtest/src/v1/index.ts.baseline @@ -16,4 +16,4 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -export {TestServiceClient} from './test_service_client'; +export { TestServiceClient } from './test_service_client'; diff --git a/core/generator/gapic-generator-typescript/baselines/routingtest/src/v1/test_service_client.ts.baseline b/core/generator/gapic-generator-typescript/baselines/routingtest/src/v1/test_service_client.ts.baseline index 1d459e685a19..b45af1a1196d 100644 --- a/core/generator/gapic-generator-typescript/baselines/routingtest/src/v1/test_service_client.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/routingtest/src/v1/test_service_client.ts.baseline @@ -18,11 +18,16 @@ /* global window */ import type * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions} from 'google-gax'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, +} from 'google-gax'; import * as protos from '../../protos/protos'; import jsonProtos = require('../../protos/protos.json'); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; /** * Client JSON configuration object, loaded from @@ -45,7 +50,7 @@ export class TestServiceClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('routingtest'); @@ -58,8 +63,8 @@ export class TestServiceClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - testServiceStub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + testServiceStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of TestServiceClient. @@ -100,21 +105,42 @@ export class TestServiceClient { * const client = new TestServiceClient({fallback: true}, gax); * ``` */ - constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { // Ensure that options include all the required fields. const staticMembers = this.constructor as typeof TestServiceClient; - if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { - throw new Error('Please set either universe_domain or universeDomain, but not both.'); + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); } - const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; - this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; this._servicePath = 'localhost'; - const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; - const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. if (servicePath !== this._servicePath && !('scopes' in opts)) { @@ -136,7 +162,7 @@ export class TestServiceClient { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; @@ -150,10 +176,7 @@ export class TestServiceClient { } // Determine the client header string. - const clientHeader = [ - `gax/${this._gaxModule.version}`, - `gapic/${version}`, - ]; + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/${process.versions.node}`); } else { @@ -172,8 +195,11 @@ export class TestServiceClient { // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.routingtest.v1.TestService', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.routingtest.v1.TestService', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + { 'x-goog-api-client': clientHeader.join(' ') }, + ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -204,36 +230,44 @@ export class TestServiceClient { // Put together the "service stub" for // google.routingtest.v1.TestService. this.testServiceStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.routingtest.v1.TestService') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.routingtest.v1.TestService', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.routingtest.v1.TestService, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts, + this._providedCustomServicePath, + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const testServiceStubMethods = - ['fastFibonacci', 'randomFibonacci', 'slowFibonacci']; + const testServiceStubMethods = [ + 'fastFibonacci', + 'randomFibonacci', + 'slowFibonacci', + ]; for (const methodName of testServiceStubMethods) { const callPromise = this.testServiceStub.then( - stub => (...args: Array<{}>) => { - if (this._terminated) { - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error|null|undefined) => () => { + (stub) => + (...args: Array<{}>) => { + if (this._terminated) { + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { throw err; - }); + }, + ); - const descriptor = - undefined; + const descriptor = undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -248,8 +282,14 @@ export class TestServiceClient { * @returns {string} The DNS address for this service. */ static get servicePath() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'localhost'; } @@ -260,8 +300,14 @@ export class TestServiceClient { * @returns {string} The DNS address for this service. */ static get apiEndpoint() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'localhost'; } @@ -292,9 +338,7 @@ export class TestServiceClient { * @returns {string[]} List of default scopes. */ static get scopes() { - return [ - 'https://www.googleapis.com/auth/cloud-platform' - ]; + return ['https://www.googleapis.com/auth/cloud-platform']; } getProjectId(): Promise; @@ -303,8 +347,9 @@ export class TestServiceClient { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId(callback?: Callback): - Promise|void { + getProjectId( + callback?: Callback, + ): Promise | void { if (callback) { this.auth.getProjectId(callback); return; @@ -315,69 +360,82 @@ export class TestServiceClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Calculates Fibonacci on the provided value, quickly. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.routingtest.v1.FibonacciRequest.Inner1} request.nest1 - * @param {number} request.value - * The nth term to retrieve in the Fibonacci sequence. - * @param {string} request.name - * This is for testing the routing annotation. - * @param {string} request.parentId - * This is for testing the routing annotation. - * @param {string} request.anotherParentId - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1/test_service.fast_fibonacci.js - * region_tag:localhost_v1_generated_TestService_FastFibonacci_async - */ + /** + * Calculates Fibonacci on the provided value, quickly. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.routingtest.v1.FibonacciRequest.Inner1} request.nest1 + * @param {number} request.value + * The nth term to retrieve in the Fibonacci sequence. + * @param {string} request.name + * This is for testing the routing annotation. + * @param {string} request.parentId + * This is for testing the routing annotation. + * @param {string} request.anotherParentId + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/test_service.fast_fibonacci.js + * region_tag:localhost_v1_generated_TestService_FastFibonacci_async + */ fastFibonacci( - request?: protos.google.routingtest.v1.IFibonacciRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.routingtest.v1.IFibonacciRequest|undefined, {}|undefined - ]>; + request?: protos.google.routingtest.v1.IFibonacciRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.routingtest.v1.IFibonacciRequest | undefined, + {} | undefined, + ] + >; fastFibonacci( - request: protos.google.routingtest.v1.IFibonacciRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.routingtest.v1.IFibonacciRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.routingtest.v1.IFibonacciRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.routingtest.v1.IFibonacciRequest | null | undefined, + {} | null | undefined + >, + ): void; fastFibonacci( - request: protos.google.routingtest.v1.IFibonacciRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.routingtest.v1.IFibonacciRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.routingtest.v1.IFibonacciRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.routingtest.v1.IFibonacciRequest | null | undefined, + {} | null | undefined + >, + ): void; fastFibonacci( - request?: protos.google.routingtest.v1.IFibonacciRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.protobuf.IEmpty, - protos.google.routingtest.v1.IFibonacciRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.routingtest.v1.IFibonacciRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.routingtest.v1.IFibonacciRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.routingtest.v1.IFibonacciRequest|undefined, {}|undefined - ]>|void { + protos.google.routingtest.v1.IFibonacciRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + protos.google.routingtest.v1.IFibonacciRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.routingtest.v1.IFibonacciRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; @@ -387,108 +445,140 @@ export class TestServiceClient { { const fieldValue = request.name; if (fieldValue !== undefined && fieldValue !== null) { - const match = fieldValue.toString().match(RegExp('(?projects/[^/]+/databases/[^/]+)/documents')); + const match = fieldValue + .toString() + .match( + RegExp('(?projects/[^/]+/databases/[^/]+)/documents'), + ); if (match) { const parameterValue = match.groups?.['database'] ?? fieldValue; Object.assign(routingParameter, { database: parameterValue }); } } } - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams( - routingParameter - ); - this.initialize().catch(err => {throw err}); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams(routingParameter); + this.initialize().catch((err) => { + throw err; + }); this._log.info('fastFibonacci request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.routingtest.v1.IFibonacciRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + protos.google.routingtest.v1.IFibonacciRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('fastFibonacci response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.fastFibonacci(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.routingtest.v1.IFibonacciRequest|undefined, - {}|undefined - ]) => { - this._log.info('fastFibonacci response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .fastFibonacci(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.routingtest.v1.IFibonacciRequest | undefined, + {} | undefined, + ]) => { + this._log.info('fastFibonacci response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Calculates Fibonacci on the provided value, randomly. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.routingtest.v1.FibonacciRequest.Inner1} request.nest1 - * @param {number} request.value - * The nth term to retrieve in the Fibonacci sequence. - * @param {string} request.name - * This is for testing the routing annotation. - * @param {string} request.parentId - * This is for testing the routing annotation. - * @param {string} request.anotherParentId - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1/test_service.random_fibonacci.js - * region_tag:localhost_v1_generated_TestService_RandomFibonacci_async - */ + /** + * Calculates Fibonacci on the provided value, randomly. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.routingtest.v1.FibonacciRequest.Inner1} request.nest1 + * @param {number} request.value + * The nth term to retrieve in the Fibonacci sequence. + * @param {string} request.name + * This is for testing the routing annotation. + * @param {string} request.parentId + * This is for testing the routing annotation. + * @param {string} request.anotherParentId + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/test_service.random_fibonacci.js + * region_tag:localhost_v1_generated_TestService_RandomFibonacci_async + */ randomFibonacci( - request?: protos.google.routingtest.v1.IFibonacciRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.routingtest.v1.IFibonacciRequest|undefined, {}|undefined - ]>; + request?: protos.google.routingtest.v1.IFibonacciRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.routingtest.v1.IFibonacciRequest | undefined, + {} | undefined, + ] + >; randomFibonacci( - request: protos.google.routingtest.v1.IFibonacciRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.routingtest.v1.IFibonacciRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.routingtest.v1.IFibonacciRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.routingtest.v1.IFibonacciRequest | null | undefined, + {} | null | undefined + >, + ): void; randomFibonacci( - request: protos.google.routingtest.v1.IFibonacciRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.routingtest.v1.IFibonacciRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.routingtest.v1.IFibonacciRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.routingtest.v1.IFibonacciRequest | null | undefined, + {} | null | undefined + >, + ): void; randomFibonacci( - request?: protos.google.routingtest.v1.IFibonacciRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.routingtest.v1.IFibonacciRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.routingtest.v1.IFibonacciRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.protobuf.IEmpty, - protos.google.routingtest.v1.IFibonacciRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.routingtest.v1.IFibonacciRequest|undefined, {}|undefined - ]>|void { + protos.google.routingtest.v1.IFibonacciRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + protos.google.routingtest.v1.IFibonacciRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.routingtest.v1.IFibonacciRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; @@ -508,108 +598,138 @@ export class TestServiceClient { { const fieldValue = request.name; if (fieldValue !== undefined && fieldValue !== null) { - const match = fieldValue.toString().match(RegExp('(?(?:.*)?)')); + const match = fieldValue + .toString() + .match(RegExp('(?(?:.*)?)')); if (match) { const parameterValue = match.groups?.['routing_id'] ?? fieldValue; Object.assign(routingParameter, { routing_id: parameterValue }); } } } - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams( - routingParameter - ); - this.initialize().catch(err => {throw err}); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams(routingParameter); + this.initialize().catch((err) => { + throw err; + }); this._log.info('randomFibonacci request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.routingtest.v1.IFibonacciRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + protos.google.routingtest.v1.IFibonacciRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('randomFibonacci response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.randomFibonacci(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.routingtest.v1.IFibonacciRequest|undefined, - {}|undefined - ]) => { - this._log.info('randomFibonacci response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .randomFibonacci(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.routingtest.v1.IFibonacciRequest | undefined, + {} | undefined, + ]) => { + this._log.info('randomFibonacci response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Calculates Fibonacci on the provided value, slowly. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.routingtest.v1.FibonacciRequest.Inner1} request.nest1 - * @param {number} request.value - * The nth term to retrieve in the Fibonacci sequence. - * @param {string} request.name - * This is for testing the routing annotation. - * @param {string} request.parentId - * This is for testing the routing annotation. - * @param {string} request.anotherParentId - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1/test_service.slow_fibonacci.js - * region_tag:localhost_v1_generated_TestService_SlowFibonacci_async - */ + /** + * Calculates Fibonacci on the provided value, slowly. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.routingtest.v1.FibonacciRequest.Inner1} request.nest1 + * @param {number} request.value + * The nth term to retrieve in the Fibonacci sequence. + * @param {string} request.name + * This is for testing the routing annotation. + * @param {string} request.parentId + * This is for testing the routing annotation. + * @param {string} request.anotherParentId + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/test_service.slow_fibonacci.js + * region_tag:localhost_v1_generated_TestService_SlowFibonacci_async + */ slowFibonacci( - request?: protos.google.routingtest.v1.IFibonacciRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.routingtest.v1.IFibonacciRequest|undefined, {}|undefined - ]>; + request?: protos.google.routingtest.v1.IFibonacciRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.routingtest.v1.IFibonacciRequest | undefined, + {} | undefined, + ] + >; slowFibonacci( - request: protos.google.routingtest.v1.IFibonacciRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.routingtest.v1.IFibonacciRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.routingtest.v1.IFibonacciRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.routingtest.v1.IFibonacciRequest | null | undefined, + {} | null | undefined + >, + ): void; slowFibonacci( - request: protos.google.routingtest.v1.IFibonacciRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.routingtest.v1.IFibonacciRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.routingtest.v1.IFibonacciRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.routingtest.v1.IFibonacciRequest | null | undefined, + {} | null | undefined + >, + ): void; slowFibonacci( - request?: protos.google.routingtest.v1.IFibonacciRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.protobuf.IEmpty, - protos.google.routingtest.v1.IFibonacciRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.routingtest.v1.IFibonacciRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.routingtest.v1.IFibonacciRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.routingtest.v1.IFibonacciRequest|undefined, {}|undefined - ]>|void { + protos.google.routingtest.v1.IFibonacciRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + protos.google.routingtest.v1.IFibonacciRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.routingtest.v1.IFibonacciRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; @@ -619,7 +739,9 @@ export class TestServiceClient { { const fieldValue = request.parentId; if (fieldValue !== undefined && fieldValue !== null) { - const match = fieldValue.toString().match(RegExp('(?projects/[^/]+)')); + const match = fieldValue + .toString() + .match(RegExp('(?projects/[^/]+)')); if (match) { const parameterValue = match.groups?.['database'] ?? fieldValue; Object.assign(routingParameter, { database: parameterValue }); @@ -629,7 +751,11 @@ export class TestServiceClient { { const fieldValue = request.nest1?.nest2?.nameId; if (fieldValue !== undefined && fieldValue !== null) { - const match = fieldValue.toString().match(RegExp('(?projects/[^/]+/databases/[^/]+)/documents')); + const match = fieldValue + .toString() + .match( + RegExp('(?projects/[^/]+/databases/[^/]+)/documents'), + ); if (match) { const parameterValue = match.groups?.['database'] ?? fieldValue; Object.assign(routingParameter, { database: parameterValue }); @@ -639,47 +765,65 @@ export class TestServiceClient { { const fieldValue = request.anotherParentId; if (fieldValue !== undefined && fieldValue !== null) { - const match = fieldValue.toString().match(RegExp('(?projects/[^/]+)/databases/[^/]+/documents')); + const match = fieldValue + .toString() + .match( + RegExp('(?projects/[^/]+)/databases/[^/]+/documents'), + ); if (match) { const parameterValue = match.groups?.['routing_id'] ?? fieldValue; Object.assign(routingParameter, { routing_id: parameterValue }); } } } - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams( - routingParameter - ); - this.initialize().catch(err => {throw err}); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams(routingParameter); + this.initialize().catch((err) => { + throw err; + }); this._log.info('slowFibonacci request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.routingtest.v1.IFibonacciRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + protos.google.routingtest.v1.IFibonacciRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('slowFibonacci response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.slowFibonacci(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.routingtest.v1.IFibonacciRequest|undefined, - {}|undefined - ]) => { - this._log.info('slowFibonacci response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .slowFibonacci(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.routingtest.v1.IFibonacciRequest | undefined, + {} | undefined, + ]) => { + this._log.info('slowFibonacci response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } - /** * Terminate the gRPC channel and close the client. * @@ -688,7 +832,7 @@ export class TestServiceClient { */ close(): Promise { if (this.testServiceStub && !this._terminated) { - return this.testServiceStub.then(stub => { + return this.testServiceStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -696,4 +840,4 @@ export class TestServiceClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/core/generator/gapic-generator-typescript/baselines/routingtest/system-test/fixtures/sample/src/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/routingtest/system-test/fixtures/sample/src/index.ts.baseline index 2064c65d4c0c..8219f574c4b0 100644 --- a/core/generator/gapic-generator-typescript/baselines/routingtest/system-test/fixtures/sample/src/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/routingtest/system-test/fixtures/sample/src/index.ts.baseline @@ -16,7 +16,7 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -import {TestServiceClient} from 'routingtest'; +import { TestServiceClient } from 'routingtest'; // check that the client class type name can be used function doStuffWithTestServiceClient(client: TestServiceClient) { diff --git a/core/generator/gapic-generator-typescript/baselines/routingtest/system-test/install.ts.baseline b/core/generator/gapic-generator-typescript/baselines/routingtest/system-test/install.ts.baseline index f66069aa3940..ccf167042d2e 100644 --- a/core/generator/gapic-generator-typescript/baselines/routingtest/system-test/install.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/routingtest/system-test/install.ts.baseline @@ -16,34 +16,36 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -import {packNTest} from 'pack-n-play'; -import {readFileSync} from 'fs'; -import {describe, it} from 'mocha'; +import { packNTest } from 'pack-n-play'; +import { readFileSync } from 'fs'; +import { describe, it } from 'mocha'; describe('📦 pack-n-play test', () => { - - it('TypeScript code', async function() { + it('TypeScript code', async function () { this.timeout(300000); const options = { packageDir: process.cwd(), sample: { description: 'TypeScript user can use the type definitions', - ts: readFileSync('./system-test/fixtures/sample/src/index.ts').toString() - } + ts: readFileSync( + './system-test/fixtures/sample/src/index.ts', + ).toString(), + }, }; await packNTest(options); }); - it('JavaScript code', async function() { + it('JavaScript code', async function () { this.timeout(300000); const options = { packageDir: process.cwd(), sample: { description: 'JavaScript user can use the library', - cjs: readFileSync('./system-test/fixtures/sample/src/index.js').toString() - } + cjs: readFileSync( + './system-test/fixtures/sample/src/index.js', + ).toString(), + }, }; await packNTest(options); }); - }); diff --git a/core/generator/gapic-generator-typescript/baselines/routingtest/test/gapic_test_service_v1.ts.baseline b/core/generator/gapic-generator-typescript/baselines/routingtest/test/gapic_test_service_v1.ts.baseline index 8a360496e13f..53f8cf29debf 100644 --- a/core/generator/gapic-generator-typescript/baselines/routingtest/test/gapic_test_service_v1.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/routingtest/test/gapic_test_service_v1.ts.baseline @@ -19,467 +19,552 @@ import * as protos from '../protos/protos'; import * as assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as testserviceModule from '../src'; -import {protobuf} from 'google-gax'; +import { protobuf } from 'google-gax'; // Dynamically loaded proto JSON is needed to get the type information // to fill in default values for request objects -const root = protobuf.Root.fromJSON(require('../protos/protos.json')).resolveAll(); +const root = protobuf.Root.fromJSON( + require('../protos/protos.json'), +).resolveAll(); // eslint-disable-next-line @typescript-eslint/no-unused-vars function getTypeDefaultValue(typeName: string, fields: string[]) { - let type = root.lookupType(typeName) as protobuf.Type; - for (const field of fields.slice(0, -1)) { - type = type.fields[field]?.resolvedType as protobuf.Type; - } - return type.fields[fields[fields.length - 1]]?.defaultValue; + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type.fields[field]?.resolvedType as protobuf.Type; + } + return type.fields[fields[fields.length - 1]]?.defaultValue; } function generateSampleMessage(instance: T) { - const filledObject = (instance.constructor as typeof protobuf.Message) - .toObject(instance as protobuf.Message, {defaults: true}); - return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, { defaults: true }); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; } function stubSimpleCall(response?: ResponseType, error?: Error) { - return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); } -function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { - return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +function stubSimpleCallWithCallback( + response?: ResponseType, + error?: Error, +) { + return error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); } describe('v1.TestServiceClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new testserviceModule.v1.TestServiceClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'localhost'); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new testserviceModule.v1.TestServiceClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'localhost'); + }); - it('has universeDomain', () => { - const client = new testserviceModule.v1.TestServiceClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); + it('has universeDomain', () => { + const client = new testserviceModule.v1.TestServiceClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - it('throws DeprecationWarning if static servicePath is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const servicePath = testserviceModule.v1.TestServiceClient.servicePath; - assert.strictEqual(servicePath, 'localhost'); - assert(stub.called); - stub.restore(); - }); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = testserviceModule.v1.TestServiceClient.servicePath; + assert.strictEqual(servicePath, 'localhost'); + assert(stub.called); + stub.restore(); + }); - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = testserviceModule.v1.TestServiceClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'localhost'); - assert(stub.called); - stub.restore(); - }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { new testserviceModule.v1.TestServiceClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = testserviceModule.v1.TestServiceClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'localhost'); + assert(stub.called); + stub.restore(); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new testserviceModule.v1.TestServiceClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); + }); - it('has port', () => { - const port = testserviceModule.v1.TestServiceClient.port; - assert(port); - assert(typeof port === 'number'); - }); + it('has port', () => { + const port = testserviceModule.v1.TestServiceClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('should create a client with no option', () => { - const client = new testserviceModule.v1.TestServiceClient(); - assert(client); - }); + it('should create a client with no option', () => { + const client = new testserviceModule.v1.TestServiceClient(); + assert(client); + }); - it('should create a client with gRPC fallback', () => { - const client = new testserviceModule.v1.TestServiceClient({ - fallback: true, - }); - assert(client); - }); + it('should create a client with gRPC fallback', () => { + const client = new testserviceModule.v1.TestServiceClient({ + fallback: true, + }); + assert(client); + }); - it('has initialize method and supports deferred initialization', async () => { - const client = new testserviceModule.v1.TestServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.testServiceStub, undefined); - await client.initialize(); - assert(client.testServiceStub); - }); + it('has initialize method and supports deferred initialization', async () => { + const client = new testserviceModule.v1.TestServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.testServiceStub, undefined); + await client.initialize(); + assert(client.testServiceStub); + }); - it('has close method for the initialized client', done => { - const client = new testserviceModule.v1.TestServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.testServiceStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); + it('has close method for the initialized client', (done) => { + const client = new testserviceModule.v1.TestServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.testServiceStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('has close method for the non-initialized client', done => { - const client = new testserviceModule.v1.TestServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.testServiceStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); + it('has close method for the non-initialized client', (done) => { + const client = new testserviceModule.v1.TestServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.testServiceStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new testserviceModule.v1.TestServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); - }); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new testserviceModule.v1.TestServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + }); - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new testserviceModule.v1.TestServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId((err?: Error|null, projectId?: string|null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } - }); - }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new testserviceModule.v1.TestServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); }); + }); - describe('fastFibonacci', () => { - it('invokes fastFibonacci without error', async () => { - const client = new testserviceModule.v1.TestServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.routingtest.v1.FibonacciRequest() - ); - // path template: {database=projects/*/databases/*}/documents - request.name = 'projects/value/databases/value/documents'; - const expectedHeaderRequestParams = 'database=projects%2Fvalue%2Fdatabases%2Fvalue'; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.fastFibonacci = stubSimpleCall(expectedResponse); - const [response] = await client.fastFibonacci(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.fastFibonacci as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.fastFibonacci as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + describe('fastFibonacci', () => { + it('invokes fastFibonacci without error', async () => { + const client = new testserviceModule.v1.TestServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.routingtest.v1.FibonacciRequest(), + ); + // path template: {database=projects/*/databases/*}/documents + request.name = 'projects/value/databases/value/documents'; + const expectedHeaderRequestParams = + 'database=projects%2Fvalue%2Fdatabases%2Fvalue'; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.fastFibonacci = stubSimpleCall(expectedResponse); + const [response] = await client.fastFibonacci(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.fastFibonacci as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.fastFibonacci as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes fastFibonacci without error using callback', async () => { - const client = new testserviceModule.v1.TestServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.routingtest.v1.FibonacciRequest() - ); - // path template: {database=projects/*/databases/*}/documents - request.name = 'projects/value/databases/value/documents'; - const expectedHeaderRequestParams = 'database=projects%2Fvalue%2Fdatabases%2Fvalue'; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.fastFibonacci = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.fastFibonacci( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.fastFibonacci as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.fastFibonacci as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes fastFibonacci without error using callback', async () => { + const client = new testserviceModule.v1.TestServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.routingtest.v1.FibonacciRequest(), + ); + // path template: {database=projects/*/databases/*}/documents + request.name = 'projects/value/databases/value/documents'; + const expectedHeaderRequestParams = + 'database=projects%2Fvalue%2Fdatabases%2Fvalue'; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.fastFibonacci = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.fastFibonacci( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.fastFibonacci as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.fastFibonacci as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes fastFibonacci with error', async () => { - const client = new testserviceModule.v1.TestServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.routingtest.v1.FibonacciRequest() - ); - // path template: {database=projects/*/databases/*}/documents - request.name = 'projects/value/databases/value/documents'; - const expectedHeaderRequestParams = 'database=projects%2Fvalue%2Fdatabases%2Fvalue'; - const expectedError = new Error('expected'); - client.innerApiCalls.fastFibonacci = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.fastFibonacci(request), expectedError); - const actualRequest = (client.innerApiCalls.fastFibonacci as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.fastFibonacci as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes fastFibonacci with error', async () => { + const client = new testserviceModule.v1.TestServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.routingtest.v1.FibonacciRequest(), + ); + // path template: {database=projects/*/databases/*}/documents + request.name = 'projects/value/databases/value/documents'; + const expectedHeaderRequestParams = + 'database=projects%2Fvalue%2Fdatabases%2Fvalue'; + const expectedError = new Error('expected'); + client.innerApiCalls.fastFibonacci = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.fastFibonacci(request), expectedError); + const actualRequest = ( + client.innerApiCalls.fastFibonacci as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.fastFibonacci as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes fastFibonacci with closed client', async () => { - const client = new testserviceModule.v1.TestServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.routingtest.v1.FibonacciRequest() - ); - // path template: {database=projects/*/databases/*}/documents - request.name = 'projects/value/databases/value/documents'; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.fastFibonacci(request), expectedError); - }); + it('invokes fastFibonacci with closed client', async () => { + const client = new testserviceModule.v1.TestServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.routingtest.v1.FibonacciRequest(), + ); + // path template: {database=projects/*/databases/*}/documents + request.name = 'projects/value/databases/value/documents'; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.fastFibonacci(request), expectedError); }); + }); - describe('randomFibonacci', () => { - it('invokes randomFibonacci without error', async () => { - const client = new testserviceModule.v1.TestServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.routingtest.v1.FibonacciRequest() - ); - // path template: {routing_id=**} - request.name = 'value'; - const expectedHeaderRequestParams = 'routing_id=value'; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.randomFibonacci = stubSimpleCall(expectedResponse); - const [response] = await client.randomFibonacci(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.randomFibonacci as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.randomFibonacci as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + describe('randomFibonacci', () => { + it('invokes randomFibonacci without error', async () => { + const client = new testserviceModule.v1.TestServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.routingtest.v1.FibonacciRequest(), + ); + // path template: {routing_id=**} + request.name = 'value'; + const expectedHeaderRequestParams = 'routing_id=value'; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.randomFibonacci = stubSimpleCall(expectedResponse); + const [response] = await client.randomFibonacci(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.randomFibonacci as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.randomFibonacci as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes randomFibonacci without error using callback', async () => { - const client = new testserviceModule.v1.TestServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.routingtest.v1.FibonacciRequest() - ); - // path template: {routing_id=**} - request.name = 'value'; - const expectedHeaderRequestParams = 'routing_id=value'; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.randomFibonacci = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.randomFibonacci( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.randomFibonacci as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.randomFibonacci as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes randomFibonacci without error using callback', async () => { + const client = new testserviceModule.v1.TestServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.routingtest.v1.FibonacciRequest(), + ); + // path template: {routing_id=**} + request.name = 'value'; + const expectedHeaderRequestParams = 'routing_id=value'; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.randomFibonacci = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.randomFibonacci( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.randomFibonacci as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.randomFibonacci as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes randomFibonacci with error', async () => { - const client = new testserviceModule.v1.TestServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.routingtest.v1.FibonacciRequest() - ); - // path template: {routing_id=**} - request.name = 'value'; - const expectedHeaderRequestParams = 'routing_id=value'; - const expectedError = new Error('expected'); - client.innerApiCalls.randomFibonacci = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.randomFibonacci(request), expectedError); - const actualRequest = (client.innerApiCalls.randomFibonacci as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.randomFibonacci as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes randomFibonacci with error', async () => { + const client = new testserviceModule.v1.TestServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.routingtest.v1.FibonacciRequest(), + ); + // path template: {routing_id=**} + request.name = 'value'; + const expectedHeaderRequestParams = 'routing_id=value'; + const expectedError = new Error('expected'); + client.innerApiCalls.randomFibonacci = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.randomFibonacci(request), expectedError); + const actualRequest = ( + client.innerApiCalls.randomFibonacci as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.randomFibonacci as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes randomFibonacci with closed client', async () => { - const client = new testserviceModule.v1.TestServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.routingtest.v1.FibonacciRequest() - ); - // path template: {routing_id=**} - request.name = 'value'; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.randomFibonacci(request), expectedError); - }); + it('invokes randomFibonacci with closed client', async () => { + const client = new testserviceModule.v1.TestServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.routingtest.v1.FibonacciRequest(), + ); + // path template: {routing_id=**} + request.name = 'value'; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.randomFibonacci(request), expectedError); }); + }); - describe('slowFibonacci', () => { - it('invokes slowFibonacci without error', async () => { - const client = new testserviceModule.v1.TestServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.routingtest.v1.FibonacciRequest() - ); - // path template: {routing_id=projects/*}/databases/*/documents - request.anotherParentId = 'projects/value/databases/value/documents'; - const expectedHeaderRequestParams = 'routing_id=projects%2Fvalue'; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.slowFibonacci = stubSimpleCall(expectedResponse); - const [response] = await client.slowFibonacci(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.slowFibonacci as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.slowFibonacci as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + describe('slowFibonacci', () => { + it('invokes slowFibonacci without error', async () => { + const client = new testserviceModule.v1.TestServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.routingtest.v1.FibonacciRequest(), + ); + // path template: {routing_id=projects/*}/databases/*/documents + request.anotherParentId = 'projects/value/databases/value/documents'; + const expectedHeaderRequestParams = 'routing_id=projects%2Fvalue'; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.slowFibonacci = stubSimpleCall(expectedResponse); + const [response] = await client.slowFibonacci(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.slowFibonacci as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.slowFibonacci as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes slowFibonacci without error using callback', async () => { - const client = new testserviceModule.v1.TestServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.routingtest.v1.FibonacciRequest() - ); - // path template: {routing_id=projects/*}/databases/*/documents - request.anotherParentId = 'projects/value/databases/value/documents'; - const expectedHeaderRequestParams = 'routing_id=projects%2Fvalue'; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.slowFibonacci = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.slowFibonacci( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.slowFibonacci as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.slowFibonacci as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes slowFibonacci without error using callback', async () => { + const client = new testserviceModule.v1.TestServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.routingtest.v1.FibonacciRequest(), + ); + // path template: {routing_id=projects/*}/databases/*/documents + request.anotherParentId = 'projects/value/databases/value/documents'; + const expectedHeaderRequestParams = 'routing_id=projects%2Fvalue'; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.slowFibonacci = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.slowFibonacci( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.slowFibonacci as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.slowFibonacci as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes slowFibonacci with error', async () => { - const client = new testserviceModule.v1.TestServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.routingtest.v1.FibonacciRequest() - ); - // path template: {routing_id=projects/*}/databases/*/documents - request.anotherParentId = 'projects/value/databases/value/documents'; - const expectedHeaderRequestParams = 'routing_id=projects%2Fvalue'; - const expectedError = new Error('expected'); - client.innerApiCalls.slowFibonacci = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.slowFibonacci(request), expectedError); - const actualRequest = (client.innerApiCalls.slowFibonacci as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.slowFibonacci as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes slowFibonacci with error', async () => { + const client = new testserviceModule.v1.TestServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.routingtest.v1.FibonacciRequest(), + ); + // path template: {routing_id=projects/*}/databases/*/documents + request.anotherParentId = 'projects/value/databases/value/documents'; + const expectedHeaderRequestParams = 'routing_id=projects%2Fvalue'; + const expectedError = new Error('expected'); + client.innerApiCalls.slowFibonacci = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.slowFibonacci(request), expectedError); + const actualRequest = ( + client.innerApiCalls.slowFibonacci as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.slowFibonacci as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes slowFibonacci with closed client', async () => { - const client = new testserviceModule.v1.TestServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.routingtest.v1.FibonacciRequest() - ); - // path template: {routing_id=projects/*}/databases/*/documents - request.anotherParentId = 'projects/value/databases/value/documents'; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.slowFibonacci(request), expectedError); - }); + it('invokes slowFibonacci with closed client', async () => { + const client = new testserviceModule.v1.TestServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.routingtest.v1.FibonacciRequest(), + ); + // path template: {routing_id=projects/*}/databases/*/documents + request.anotherParentId = 'projects/value/databases/value/documents'; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.slowFibonacci(request), expectedError); }); + }); }); diff --git a/core/generator/gapic-generator-typescript/baselines/showcase-esm/esm/src/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/showcase-esm/esm/src/index.ts.baseline index 485391ab99b2..8858d09869b8 100644 --- a/core/generator/gapic-generator-typescript/baselines/showcase-esm/esm/src/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/showcase-esm/esm/src/index.ts.baseline @@ -29,8 +29,24 @@ const SequenceServiceClient = v1beta1.SequenceServiceClient; type SequenceServiceClient = v1beta1.SequenceServiceClient; const TestingClient = v1beta1.TestingClient; type TestingClient = v1beta1.TestingClient; -export {v1beta1, ComplianceClient, EchoClient, IdentityClient, MessagingClient, SequenceServiceClient, TestingClient}; -export default {v1beta1, ComplianceClient, EchoClient, IdentityClient, MessagingClient, SequenceServiceClient, TestingClient}; +export { + v1beta1, + ComplianceClient, + EchoClient, + IdentityClient, + MessagingClient, + SequenceServiceClient, + TestingClient, +}; +export default { + v1beta1, + ComplianceClient, + EchoClient, + IdentityClient, + MessagingClient, + SequenceServiceClient, + TestingClient, +}; // @ts-ignore import * as protos from '../../protos/protos.js'; -export {protos} +export { protos }; diff --git a/core/generator/gapic-generator-typescript/baselines/showcase-esm/esm/src/v1beta1/compliance_client.ts.baseline b/core/generator/gapic-generator-typescript/baselines/showcase-esm/esm/src/v1beta1/compliance_client.ts.baseline index af5997018d20..62b26d1f1bb8 100644 --- a/core/generator/gapic-generator-typescript/baselines/showcase-esm/esm/src/v1beta1/compliance_client.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/showcase-esm/esm/src/v1beta1/compliance_client.ts.baseline @@ -18,15 +18,20 @@ /* global window */ import * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions} from 'google-gax'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, +} from 'google-gax'; // @ts-ignore import type * as protos from '../../../protos/protos.js'; import * as compliance_client_config from './compliance_client_config.json'; import fs from 'fs'; import path from 'path'; -import {fileURLToPath} from 'url'; -import {getJSON} from '../json-helper.cjs'; +import { fileURLToPath } from 'url'; +import { getJSON } from '../json-helper.cjs'; // @ts-ignore const dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -36,15 +41,15 @@ const dirname = path.dirname(fileURLToPath(import.meta.url)); * This file defines retry strategy and timeouts for all API methods in this library. */ const gapicConfig = getJSON( - path.join(dirname, 'compliance_client_config.json') + path.join(dirname, 'compliance_client_config.json'), ); const jsonProtos = getJSON( - path.join(dirname, '..', '..', '..', 'protos/protos.json') + path.join(dirname, '..', '..', '..', 'protos/protos.json'), ); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; const version = getJSON( - path.join(dirname, '..', '..', '..', '..', 'package.json') + path.join(dirname, '..', '..', '..', '..', 'package.json'), ).version; /** @@ -61,7 +66,7 @@ export class ComplianceClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('showcase'); @@ -73,9 +78,9 @@ export class ComplianceClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; - complianceStub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; + complianceStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of ComplianceClient. @@ -117,21 +122,42 @@ export class ComplianceClient { * const client = new ComplianceClient({fallback: 'rest'}, gax); * ``` */ - constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { // Ensure that options include all the required fields. const staticMembers = this.constructor as typeof ComplianceClient; - if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { - throw new Error('Please set either universe_domain or universeDomain, but not both.'); + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); } - const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; - this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; this._servicePath = 'localhost'; - const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; - const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // Request numeric enum values if REST transport is used. opts.numericEnums = true; @@ -156,7 +182,7 @@ export class ComplianceClient { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; @@ -173,10 +199,7 @@ export class ComplianceClient { const isEsm = true; const isEsmString = isEsm ? '-esm' : '-cjs'; // Determine the client header string. - const clientHeader = [ - `gax/${this._gaxModule.version}`, - `gapic/${version}`, - ]; + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/{process.versions.node}${isEsmString}`); } else { @@ -184,7 +207,7 @@ export class ComplianceClient { } if (!opts.fallback) { clientHeader.push(`grpc/${this._gaxGrpc.grpcVersion}`); - } else if (opts.fallback === 'rest' ) { + } else if (opts.fallback === 'rest') { clientHeader.push(`rest/${this._gaxGrpc.grpcVersion}`); } if (opts.libName && opts.libVersion) { @@ -192,51 +215,53 @@ export class ComplianceClient { } // Load the applicable protos. - this._protos = this._gaxGrpc.loadProtoJSON(jsonProtos as gax.protobuf.INamespace); + this._protos = this._gaxGrpc.loadProtoJSON( + jsonProtos as gax.protobuf.INamespace, + ); // This API contains "path templates"; forward-slash-separated // identifiers to uniquely identify resources within the API. // Create useful helper objects for these. this.pathTemplates = { blueprintPathTemplate: new this._gaxModule.PathTemplate( - 'sessions/{session}/tests/{test}/blueprints/{blueprint}' - ), - roomPathTemplate: new this._gaxModule.PathTemplate( - 'rooms/{room}' + 'sessions/{session}/tests/{test}/blueprints/{blueprint}', ), + roomPathTemplate: new this._gaxModule.PathTemplate('rooms/{room}'), roomBlurbPathTemplate: new this._gaxModule.PathTemplate( - 'rooms/{room}/blurbs/{blurb}' + 'rooms/{room}/blurbs/{blurb}', ), roomBlurbsLegacyRoomBlurbPathTemplate: new this._gaxModule.PathTemplate( - 'rooms/{room}/blurbs/legacy/{legacy_room}.{blurb}' + 'rooms/{room}/blurbs/legacy/{legacy_room}.{blurb}', ), sequencePathTemplate: new this._gaxModule.PathTemplate( - 'sequences/{sequence}' + 'sequences/{sequence}', ), sequenceReportPathTemplate: new this._gaxModule.PathTemplate( - 'sequences/{sequence}/sequenceReport' + 'sequences/{sequence}/sequenceReport', ), sessionPathTemplate: new this._gaxModule.PathTemplate( - 'sessions/{session}' + 'sessions/{session}', ), testPathTemplate: new this._gaxModule.PathTemplate( - 'sessions/{session}/tests/{test}' - ), - userPathTemplate: new this._gaxModule.PathTemplate( - 'users/{user}' + 'sessions/{session}/tests/{test}', ), + userPathTemplate: new this._gaxModule.PathTemplate('users/{user}'), userProfileBlurbPathTemplate: new this._gaxModule.PathTemplate( - 'users/{user}/profile/blurbs/{blurb}' - ), - userProfileBlurbsLegacyUserBlurbPathTemplate: new this._gaxModule.PathTemplate( - 'users/{user}/profile/blurbs/legacy/{legacy_user}~{blurb}' + 'users/{user}/profile/blurbs/{blurb}', ), + userProfileBlurbsLegacyUserBlurbPathTemplate: + new this._gaxModule.PathTemplate( + 'users/{user}/profile/blurbs/legacy/{legacy_user}~{blurb}', + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.showcase.v1beta1.Compliance', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.showcase.v1beta1.Compliance', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + { 'x-goog-api-client': clientHeader.join(' ') }, + ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -267,36 +292,51 @@ export class ComplianceClient { // Put together the "service stub" for // google.showcase.v1beta1.Compliance. this.complianceStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.showcase.v1beta1.Compliance') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.showcase.v1beta1.Compliance', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.showcase.v1beta1.Compliance, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts, + this._providedCustomServicePath, + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const complianceStubMethods = - ['repeatDataBody', 'repeatDataBodyInfo', 'repeatDataQuery', 'repeatDataSimplePath', 'repeatDataPathResource', 'repeatDataPathTrailingResource', 'repeatDataBodyPut', 'repeatDataBodyPatch', 'getEnum', 'verifyEnum']; + const complianceStubMethods = [ + 'repeatDataBody', + 'repeatDataBodyInfo', + 'repeatDataQuery', + 'repeatDataSimplePath', + 'repeatDataPathResource', + 'repeatDataPathTrailingResource', + 'repeatDataBodyPut', + 'repeatDataBodyPatch', + 'getEnum', + 'verifyEnum', + ]; for (const methodName of complianceStubMethods) { const callPromise = this.complianceStub.then( - stub => (...args: Array<{}>) => { - if (this._terminated) { - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error|null|undefined) => () => { + (stub) => + (...args: Array<{}>) => { + if (this._terminated) { + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { throw err; - }); + }, + ); - const descriptor = - undefined; + const descriptor = undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -311,8 +351,14 @@ export class ComplianceClient { * @returns {string} The DNS address for this service. */ static get servicePath() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'localhost'; } @@ -324,8 +370,14 @@ export class ComplianceClient { * @returns {string} The DNS address for this service. */ static get apiEndpoint() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'localhost'; } @@ -365,8 +417,9 @@ export class ComplianceClient { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId(callback?: Callback): - Promise|void { + getProjectId( + callback?: Callback, + ): Promise | void { if (callback) { this.auth.getProjectId(callback); return; @@ -377,1026 +430,1349 @@ export class ComplianceClient { // ------------------- // -- Service calls -- // ------------------- -/** - * This method echoes the ComplianceData request. This method exercises - * sending the entire request object in the REST body. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * @param {google.showcase.v1beta1.ComplianceData} request.info - * @param {boolean} request.serverVerify - * If true, the server will verify that the received request matches - * the request with the same name in the compliance test suite. - * @param {string} request.intendedBindingUri - * The URI template this request is expected to be bound to server-side. - * @param {number} request.fInt32 - * Some top level fields, to test that these are encoded correctly - * in query params. - * @param {number} request.fInt64 - * @param {number} request.fDouble - * @param {number} request.pInt32 - * @param {number} request.pInt64 - * @param {number} request.pDouble - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.RepeatResponse|RepeatResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/compliance.repeat_data_body.js - * region_tag:localhost_v1beta1_generated_Compliance_RepeatDataBody_async - */ + /** + * This method echoes the ComplianceData request. This method exercises + * sending the entire request object in the REST body. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * @param {google.showcase.v1beta1.ComplianceData} request.info + * @param {boolean} request.serverVerify + * If true, the server will verify that the received request matches + * the request with the same name in the compliance test suite. + * @param {string} request.intendedBindingUri + * The URI template this request is expected to be bound to server-side. + * @param {number} request.fInt32 + * Some top level fields, to test that these are encoded correctly + * in query params. + * @param {number} request.fInt64 + * @param {number} request.fDouble + * @param {number} request.pInt32 + * @param {number} request.pInt64 + * @param {number} request.pDouble + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.RepeatResponse|RepeatResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/compliance.repeat_data_body.js + * region_tag:localhost_v1beta1_generated_Compliance_RepeatDataBody_async + */ repeatDataBody( - request?: protos.google.showcase.v1beta1.IRepeatRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IRepeatRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | undefined, + {} | undefined, + ] + >; repeatDataBody( - request: protos.google.showcase.v1beta1.IRepeatRequest, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IRepeatRequest, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + ): void; repeatDataBody( - request: protos.google.showcase.v1beta1.IRepeatRequest, - callback: Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IRepeatRequest, + callback: Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + ): void; repeatDataBody( - request?: protos.google.showcase.v1beta1.IRepeatRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.showcase.v1beta1.IRepeatRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|undefined, {}|undefined - ]>|void { + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('repeatDataBody request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('repeatDataBody response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.repeatDataBody(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|undefined, {}|undefined - ]) => { - this._log.info('repeatDataBody response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .repeatDataBody(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | undefined, + {} | undefined, + ]) => { + this._log.info('repeatDataBody response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * This method echoes the ComplianceData request. This method exercises - * sending the a message-type field in the REST body. Per AIP-127, only - * top-level, non-repeated fields can be sent this way. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * @param {google.showcase.v1beta1.ComplianceData} request.info - * @param {boolean} request.serverVerify - * If true, the server will verify that the received request matches - * the request with the same name in the compliance test suite. - * @param {string} request.intendedBindingUri - * The URI template this request is expected to be bound to server-side. - * @param {number} request.fInt32 - * Some top level fields, to test that these are encoded correctly - * in query params. - * @param {number} request.fInt64 - * @param {number} request.fDouble - * @param {number} request.pInt32 - * @param {number} request.pInt64 - * @param {number} request.pDouble - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.RepeatResponse|RepeatResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/compliance.repeat_data_body_info.js - * region_tag:localhost_v1beta1_generated_Compliance_RepeatDataBodyInfo_async - */ + /** + * This method echoes the ComplianceData request. This method exercises + * sending the a message-type field in the REST body. Per AIP-127, only + * top-level, non-repeated fields can be sent this way. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * @param {google.showcase.v1beta1.ComplianceData} request.info + * @param {boolean} request.serverVerify + * If true, the server will verify that the received request matches + * the request with the same name in the compliance test suite. + * @param {string} request.intendedBindingUri + * The URI template this request is expected to be bound to server-side. + * @param {number} request.fInt32 + * Some top level fields, to test that these are encoded correctly + * in query params. + * @param {number} request.fInt64 + * @param {number} request.fDouble + * @param {number} request.pInt32 + * @param {number} request.pInt64 + * @param {number} request.pDouble + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.RepeatResponse|RepeatResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/compliance.repeat_data_body_info.js + * region_tag:localhost_v1beta1_generated_Compliance_RepeatDataBodyInfo_async + */ repeatDataBodyInfo( - request?: protos.google.showcase.v1beta1.IRepeatRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IRepeatRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | undefined, + {} | undefined, + ] + >; repeatDataBodyInfo( - request: protos.google.showcase.v1beta1.IRepeatRequest, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IRepeatRequest, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + ): void; repeatDataBodyInfo( - request: protos.google.showcase.v1beta1.IRepeatRequest, - callback: Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IRepeatRequest, + callback: Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + ): void; repeatDataBodyInfo( - request?: protos.google.showcase.v1beta1.IRepeatRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.showcase.v1beta1.IRepeatRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|undefined, {}|undefined - ]>|void { + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('repeatDataBodyInfo request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('repeatDataBodyInfo response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.repeatDataBodyInfo(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|undefined, {}|undefined - ]) => { - this._log.info('repeatDataBodyInfo response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .repeatDataBodyInfo(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | undefined, + {} | undefined, + ]) => { + this._log.info('repeatDataBodyInfo response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * This method echoes the ComplianceData request. This method exercises - * sending all request fields as query parameters. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * @param {google.showcase.v1beta1.ComplianceData} request.info - * @param {boolean} request.serverVerify - * If true, the server will verify that the received request matches - * the request with the same name in the compliance test suite. - * @param {string} request.intendedBindingUri - * The URI template this request is expected to be bound to server-side. - * @param {number} request.fInt32 - * Some top level fields, to test that these are encoded correctly - * in query params. - * @param {number} request.fInt64 - * @param {number} request.fDouble - * @param {number} request.pInt32 - * @param {number} request.pInt64 - * @param {number} request.pDouble - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.RepeatResponse|RepeatResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/compliance.repeat_data_query.js - * region_tag:localhost_v1beta1_generated_Compliance_RepeatDataQuery_async - */ + /** + * This method echoes the ComplianceData request. This method exercises + * sending all request fields as query parameters. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * @param {google.showcase.v1beta1.ComplianceData} request.info + * @param {boolean} request.serverVerify + * If true, the server will verify that the received request matches + * the request with the same name in the compliance test suite. + * @param {string} request.intendedBindingUri + * The URI template this request is expected to be bound to server-side. + * @param {number} request.fInt32 + * Some top level fields, to test that these are encoded correctly + * in query params. + * @param {number} request.fInt64 + * @param {number} request.fDouble + * @param {number} request.pInt32 + * @param {number} request.pInt64 + * @param {number} request.pDouble + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.RepeatResponse|RepeatResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/compliance.repeat_data_query.js + * region_tag:localhost_v1beta1_generated_Compliance_RepeatDataQuery_async + */ repeatDataQuery( - request?: protos.google.showcase.v1beta1.IRepeatRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IRepeatRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | undefined, + {} | undefined, + ] + >; repeatDataQuery( - request: protos.google.showcase.v1beta1.IRepeatRequest, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IRepeatRequest, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + ): void; repeatDataQuery( - request: protos.google.showcase.v1beta1.IRepeatRequest, - callback: Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IRepeatRequest, + callback: Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + ): void; repeatDataQuery( - request?: protos.google.showcase.v1beta1.IRepeatRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.showcase.v1beta1.IRepeatRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|undefined, {}|undefined - ]>|void { + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('repeatDataQuery request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('repeatDataQuery response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.repeatDataQuery(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|undefined, {}|undefined - ]) => { - this._log.info('repeatDataQuery response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .repeatDataQuery(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | undefined, + {} | undefined, + ]) => { + this._log.info('repeatDataQuery response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * This method echoes the ComplianceData request. This method exercises - * sending some parameters as "simple" path variables (i.e., of the form - * "/bar/{foo}" rather than "/{foo=bar/*}"), and the rest as query parameters. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * @param {google.showcase.v1beta1.ComplianceData} request.info - * @param {boolean} request.serverVerify - * If true, the server will verify that the received request matches - * the request with the same name in the compliance test suite. - * @param {string} request.intendedBindingUri - * The URI template this request is expected to be bound to server-side. - * @param {number} request.fInt32 - * Some top level fields, to test that these are encoded correctly - * in query params. - * @param {number} request.fInt64 - * @param {number} request.fDouble - * @param {number} request.pInt32 - * @param {number} request.pInt64 - * @param {number} request.pDouble - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.RepeatResponse|RepeatResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/compliance.repeat_data_simple_path.js - * region_tag:localhost_v1beta1_generated_Compliance_RepeatDataSimplePath_async - */ + /** + * This method echoes the ComplianceData request. This method exercises + * sending some parameters as "simple" path variables (i.e., of the form + * "/bar/{foo}" rather than "/{foo=bar/*}"), and the rest as query parameters. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * @param {google.showcase.v1beta1.ComplianceData} request.info + * @param {boolean} request.serverVerify + * If true, the server will verify that the received request matches + * the request with the same name in the compliance test suite. + * @param {string} request.intendedBindingUri + * The URI template this request is expected to be bound to server-side. + * @param {number} request.fInt32 + * Some top level fields, to test that these are encoded correctly + * in query params. + * @param {number} request.fInt64 + * @param {number} request.fDouble + * @param {number} request.pInt32 + * @param {number} request.pInt64 + * @param {number} request.pDouble + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.RepeatResponse|RepeatResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/compliance.repeat_data_simple_path.js + * region_tag:localhost_v1beta1_generated_Compliance_RepeatDataSimplePath_async + */ repeatDataSimplePath( - request?: protos.google.showcase.v1beta1.IRepeatRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IRepeatRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | undefined, + {} | undefined, + ] + >; repeatDataSimplePath( - request: protos.google.showcase.v1beta1.IRepeatRequest, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IRepeatRequest, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + ): void; repeatDataSimplePath( - request: protos.google.showcase.v1beta1.IRepeatRequest, - callback: Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IRepeatRequest, + callback: Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + ): void; repeatDataSimplePath( - request?: protos.google.showcase.v1beta1.IRepeatRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.showcase.v1beta1.IRepeatRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|undefined, {}|undefined - ]>|void { + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'info.f_string': request.info!.fString ?? '', - 'info.f_int32': request.info!.fInt32 ?? '', - 'info.f_double': request.info!.fDouble ?? '', - 'info.f_bool': request.info!.fBool ?? '', - 'info.f_kingdom': request.info!.fKingdom ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'info.f_string': request.info!.fString ?? '', + 'info.f_int32': request.info!.fInt32 ?? '', + 'info.f_double': request.info!.fDouble ?? '', + 'info.f_bool': request.info!.fBool ?? '', + 'info.f_kingdom': request.info!.fKingdom ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('repeatDataSimplePath request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('repeatDataSimplePath response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.repeatDataSimplePath(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|undefined, {}|undefined - ]) => { - this._log.info('repeatDataSimplePath response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .repeatDataSimplePath(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | undefined, + {} | undefined, + ]) => { + this._log.info('repeatDataSimplePath response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Same as RepeatDataSimplePath, but with a path resource. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * @param {google.showcase.v1beta1.ComplianceData} request.info - * @param {boolean} request.serverVerify - * If true, the server will verify that the received request matches - * the request with the same name in the compliance test suite. - * @param {string} request.intendedBindingUri - * The URI template this request is expected to be bound to server-side. - * @param {number} request.fInt32 - * Some top level fields, to test that these are encoded correctly - * in query params. - * @param {number} request.fInt64 - * @param {number} request.fDouble - * @param {number} request.pInt32 - * @param {number} request.pInt64 - * @param {number} request.pDouble - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.RepeatResponse|RepeatResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/compliance.repeat_data_path_resource.js - * region_tag:localhost_v1beta1_generated_Compliance_RepeatDataPathResource_async - */ + /** + * Same as RepeatDataSimplePath, but with a path resource. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * @param {google.showcase.v1beta1.ComplianceData} request.info + * @param {boolean} request.serverVerify + * If true, the server will verify that the received request matches + * the request with the same name in the compliance test suite. + * @param {string} request.intendedBindingUri + * The URI template this request is expected to be bound to server-side. + * @param {number} request.fInt32 + * Some top level fields, to test that these are encoded correctly + * in query params. + * @param {number} request.fInt64 + * @param {number} request.fDouble + * @param {number} request.pInt32 + * @param {number} request.pInt64 + * @param {number} request.pDouble + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.RepeatResponse|RepeatResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/compliance.repeat_data_path_resource.js + * region_tag:localhost_v1beta1_generated_Compliance_RepeatDataPathResource_async + */ repeatDataPathResource( - request?: protos.google.showcase.v1beta1.IRepeatRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IRepeatRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | undefined, + {} | undefined, + ] + >; repeatDataPathResource( - request: protos.google.showcase.v1beta1.IRepeatRequest, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IRepeatRequest, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + ): void; repeatDataPathResource( - request: protos.google.showcase.v1beta1.IRepeatRequest, - callback: Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IRepeatRequest, + callback: Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + ): void; repeatDataPathResource( - request?: protos.google.showcase.v1beta1.IRepeatRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.showcase.v1beta1.IRepeatRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|undefined, {}|undefined - ]>|void { + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'info.f_string': request.info!.fString ?? '', - 'info.f_child.f_string': request.info!.fChild!.fString ?? '', - 'info.f_bool': request.info!.fBool ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'info.f_string': request.info!.fString ?? '', + 'info.f_child.f_string': request.info!.fChild!.fString ?? '', + 'info.f_bool': request.info!.fBool ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('repeatDataPathResource request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('repeatDataPathResource response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.repeatDataPathResource(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|undefined, {}|undefined - ]) => { - this._log.info('repeatDataPathResource response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .repeatDataPathResource(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | undefined, + {} | undefined, + ]) => { + this._log.info('repeatDataPathResource response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Same as RepeatDataSimplePath, but with a trailing resource. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * @param {google.showcase.v1beta1.ComplianceData} request.info - * @param {boolean} request.serverVerify - * If true, the server will verify that the received request matches - * the request with the same name in the compliance test suite. - * @param {string} request.intendedBindingUri - * The URI template this request is expected to be bound to server-side. - * @param {number} request.fInt32 - * Some top level fields, to test that these are encoded correctly - * in query params. - * @param {number} request.fInt64 - * @param {number} request.fDouble - * @param {number} request.pInt32 - * @param {number} request.pInt64 - * @param {number} request.pDouble - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.RepeatResponse|RepeatResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/compliance.repeat_data_path_trailing_resource.js - * region_tag:localhost_v1beta1_generated_Compliance_RepeatDataPathTrailingResource_async - */ + /** + * Same as RepeatDataSimplePath, but with a trailing resource. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * @param {google.showcase.v1beta1.ComplianceData} request.info + * @param {boolean} request.serverVerify + * If true, the server will verify that the received request matches + * the request with the same name in the compliance test suite. + * @param {string} request.intendedBindingUri + * The URI template this request is expected to be bound to server-side. + * @param {number} request.fInt32 + * Some top level fields, to test that these are encoded correctly + * in query params. + * @param {number} request.fInt64 + * @param {number} request.fDouble + * @param {number} request.pInt32 + * @param {number} request.pInt64 + * @param {number} request.pDouble + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.RepeatResponse|RepeatResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/compliance.repeat_data_path_trailing_resource.js + * region_tag:localhost_v1beta1_generated_Compliance_RepeatDataPathTrailingResource_async + */ repeatDataPathTrailingResource( - request?: protos.google.showcase.v1beta1.IRepeatRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IRepeatRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | undefined, + {} | undefined, + ] + >; repeatDataPathTrailingResource( - request: protos.google.showcase.v1beta1.IRepeatRequest, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IRepeatRequest, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + ): void; repeatDataPathTrailingResource( - request: protos.google.showcase.v1beta1.IRepeatRequest, - callback: Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IRepeatRequest, + callback: Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + ): void; repeatDataPathTrailingResource( - request?: protos.google.showcase.v1beta1.IRepeatRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.showcase.v1beta1.IRepeatRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|undefined, {}|undefined - ]>|void { + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'info.f_string': request.info!.fString ?? '', - 'info.f_child.f_string': request.info!.fChild!.fString ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'info.f_string': request.info!.fString ?? '', + 'info.f_child.f_string': request.info!.fChild!.fString ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('repeatDataPathTrailingResource request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { - this._log.info('repeatDataPathTrailingResource response %j', response); + this._log.info( + 'repeatDataPathTrailingResource response %j', + response, + ); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.repeatDataPathTrailingResource(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|undefined, {}|undefined - ]) => { - this._log.info('repeatDataPathTrailingResource response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .repeatDataPathTrailingResource(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | undefined, + {} | undefined, + ]) => { + this._log.info( + 'repeatDataPathTrailingResource response %j', + response, + ); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * This method echoes the ComplianceData request, using the HTTP PUT method. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * @param {google.showcase.v1beta1.ComplianceData} request.info - * @param {boolean} request.serverVerify - * If true, the server will verify that the received request matches - * the request with the same name in the compliance test suite. - * @param {string} request.intendedBindingUri - * The URI template this request is expected to be bound to server-side. - * @param {number} request.fInt32 - * Some top level fields, to test that these are encoded correctly - * in query params. - * @param {number} request.fInt64 - * @param {number} request.fDouble - * @param {number} request.pInt32 - * @param {number} request.pInt64 - * @param {number} request.pDouble - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.RepeatResponse|RepeatResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/compliance.repeat_data_body_put.js - * region_tag:localhost_v1beta1_generated_Compliance_RepeatDataBodyPut_async - */ + /** + * This method echoes the ComplianceData request, using the HTTP PUT method. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * @param {google.showcase.v1beta1.ComplianceData} request.info + * @param {boolean} request.serverVerify + * If true, the server will verify that the received request matches + * the request with the same name in the compliance test suite. + * @param {string} request.intendedBindingUri + * The URI template this request is expected to be bound to server-side. + * @param {number} request.fInt32 + * Some top level fields, to test that these are encoded correctly + * in query params. + * @param {number} request.fInt64 + * @param {number} request.fDouble + * @param {number} request.pInt32 + * @param {number} request.pInt64 + * @param {number} request.pDouble + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.RepeatResponse|RepeatResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/compliance.repeat_data_body_put.js + * region_tag:localhost_v1beta1_generated_Compliance_RepeatDataBodyPut_async + */ repeatDataBodyPut( - request?: protos.google.showcase.v1beta1.IRepeatRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IRepeatRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | undefined, + {} | undefined, + ] + >; repeatDataBodyPut( - request: protos.google.showcase.v1beta1.IRepeatRequest, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IRepeatRequest, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + ): void; repeatDataBodyPut( - request: protos.google.showcase.v1beta1.IRepeatRequest, - callback: Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IRepeatRequest, + callback: Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + ): void; repeatDataBodyPut( - request?: protos.google.showcase.v1beta1.IRepeatRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.showcase.v1beta1.IRepeatRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|undefined, {}|undefined - ]>|void { + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('repeatDataBodyPut request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('repeatDataBodyPut response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.repeatDataBodyPut(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|undefined, {}|undefined - ]) => { - this._log.info('repeatDataBodyPut response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .repeatDataBodyPut(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | undefined, + {} | undefined, + ]) => { + this._log.info('repeatDataBodyPut response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * This method echoes the ComplianceData request, using the HTTP PATCH method. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * @param {google.showcase.v1beta1.ComplianceData} request.info - * @param {boolean} request.serverVerify - * If true, the server will verify that the received request matches - * the request with the same name in the compliance test suite. - * @param {string} request.intendedBindingUri - * The URI template this request is expected to be bound to server-side. - * @param {number} request.fInt32 - * Some top level fields, to test that these are encoded correctly - * in query params. - * @param {number} request.fInt64 - * @param {number} request.fDouble - * @param {number} request.pInt32 - * @param {number} request.pInt64 - * @param {number} request.pDouble - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.RepeatResponse|RepeatResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/compliance.repeat_data_body_patch.js - * region_tag:localhost_v1beta1_generated_Compliance_RepeatDataBodyPatch_async - */ + /** + * This method echoes the ComplianceData request, using the HTTP PATCH method. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * @param {google.showcase.v1beta1.ComplianceData} request.info + * @param {boolean} request.serverVerify + * If true, the server will verify that the received request matches + * the request with the same name in the compliance test suite. + * @param {string} request.intendedBindingUri + * The URI template this request is expected to be bound to server-side. + * @param {number} request.fInt32 + * Some top level fields, to test that these are encoded correctly + * in query params. + * @param {number} request.fInt64 + * @param {number} request.fDouble + * @param {number} request.pInt32 + * @param {number} request.pInt64 + * @param {number} request.pDouble + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.RepeatResponse|RepeatResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/compliance.repeat_data_body_patch.js + * region_tag:localhost_v1beta1_generated_Compliance_RepeatDataBodyPatch_async + */ repeatDataBodyPatch( - request?: protos.google.showcase.v1beta1.IRepeatRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IRepeatRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | undefined, + {} | undefined, + ] + >; repeatDataBodyPatch( - request: protos.google.showcase.v1beta1.IRepeatRequest, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IRepeatRequest, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + ): void; repeatDataBodyPatch( - request: protos.google.showcase.v1beta1.IRepeatRequest, - callback: Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IRepeatRequest, + callback: Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + ): void; repeatDataBodyPatch( - request?: protos.google.showcase.v1beta1.IRepeatRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.showcase.v1beta1.IRepeatRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|undefined, {}|undefined - ]>|void { + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('repeatDataBodyPatch request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('repeatDataBodyPatch response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.repeatDataBodyPatch(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|undefined, {}|undefined - ]) => { - this._log.info('repeatDataBodyPatch response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .repeatDataBodyPatch(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | undefined, + {} | undefined, + ]) => { + this._log.info('repeatDataBodyPatch response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * This method requests an enum value from the server. Depending on the contents of EnumRequest, the enum value returned will be a known enum declared in the - * .proto file, or a made-up enum value the is unknown to the client. To verify that clients can round-trip unknown enum vaues they receive, use the - * response from this RPC as the request to VerifyEnum() - * - * The values of enums sent by the server when a known or unknown value is requested will be the same within a single Showcase server run (this is needed for - * VerifyEnum() to work) but are not guaranteed to be the same across separate Showcase server runs. - * - * @param {Object} request - * The request object that will be sent. - * @param {boolean} request.unknownEnum - * Whether the client is requesting a new, unknown enum value or a known enum value already declard in this proto file. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.EnumResponse|EnumResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/compliance.get_enum.js - * region_tag:localhost_v1beta1_generated_Compliance_GetEnum_async - */ + /** + * This method requests an enum value from the server. Depending on the contents of EnumRequest, the enum value returned will be a known enum declared in the + * .proto file, or a made-up enum value the is unknown to the client. To verify that clients can round-trip unknown enum vaues they receive, use the + * response from this RPC as the request to VerifyEnum() + * + * The values of enums sent by the server when a known or unknown value is requested will be the same within a single Showcase server run (this is needed for + * VerifyEnum() to work) but are not guaranteed to be the same across separate Showcase server runs. + * + * @param {Object} request + * The request object that will be sent. + * @param {boolean} request.unknownEnum + * Whether the client is requesting a new, unknown enum value or a known enum value already declard in this proto file. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.EnumResponse|EnumResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/compliance.get_enum.js + * region_tag:localhost_v1beta1_generated_Compliance_GetEnum_async + */ getEnum( - request?: protos.google.showcase.v1beta1.IEnumRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IEnumResponse, - protos.google.showcase.v1beta1.IEnumRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IEnumRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IEnumResponse, + protos.google.showcase.v1beta1.IEnumRequest | undefined, + {} | undefined, + ] + >; getEnum( - request: protos.google.showcase.v1beta1.IEnumRequest, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.IEnumResponse, - protos.google.showcase.v1beta1.IEnumRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IEnumRequest, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.IEnumResponse, + protos.google.showcase.v1beta1.IEnumRequest | null | undefined, + {} | null | undefined + >, + ): void; getEnum( - request: protos.google.showcase.v1beta1.IEnumRequest, - callback: Callback< - protos.google.showcase.v1beta1.IEnumResponse, - protos.google.showcase.v1beta1.IEnumRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IEnumRequest, + callback: Callback< + protos.google.showcase.v1beta1.IEnumResponse, + protos.google.showcase.v1beta1.IEnumRequest | null | undefined, + {} | null | undefined + >, + ): void; getEnum( - request?: protos.google.showcase.v1beta1.IEnumRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.showcase.v1beta1.IEnumRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.IEnumResponse, - protos.google.showcase.v1beta1.IEnumRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.showcase.v1beta1.IEnumResponse, - protos.google.showcase.v1beta1.IEnumRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.IEnumResponse, - protos.google.showcase.v1beta1.IEnumRequest|undefined, {}|undefined - ]>|void { + protos.google.showcase.v1beta1.IEnumRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.IEnumResponse, + protos.google.showcase.v1beta1.IEnumRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IEnumResponse, + protos.google.showcase.v1beta1.IEnumRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('getEnum request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.IEnumResponse, - protos.google.showcase.v1beta1.IEnumRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.IEnumResponse, + protos.google.showcase.v1beta1.IEnumRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getEnum response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.getEnum(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.IEnumResponse, - protos.google.showcase.v1beta1.IEnumRequest|undefined, {}|undefined - ]) => { - this._log.info('getEnum response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getEnum(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.IEnumResponse, + protos.google.showcase.v1beta1.IEnumRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getEnum response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * This method is used to verify that clients can round-trip enum values, which is particularly important for unknown enum values over REST. VerifyEnum() - * verifies that its request, which is presumably the response that the client previously got to a GetEnum(), contains the correct data. If so, it responds - * with the same EnumResponse; otherwise, the RPC errors. - * - * This works because the values of enums sent by the server when a known or unknown value is requested will be the same within a single Showcase server run, - * although they are not guaranteed to be the same across separate Showcase server runs. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.showcase.v1beta1.EnumRequest} request.request - * The original request for a known or unknown enum from the server. - * @param {google.showcase.v1beta1.Continent} request.continent - * The actual enum the server provided. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.EnumResponse|EnumResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/compliance.verify_enum.js - * region_tag:localhost_v1beta1_generated_Compliance_VerifyEnum_async - */ + /** + * This method is used to verify that clients can round-trip enum values, which is particularly important for unknown enum values over REST. VerifyEnum() + * verifies that its request, which is presumably the response that the client previously got to a GetEnum(), contains the correct data. If so, it responds + * with the same EnumResponse; otherwise, the RPC errors. + * + * This works because the values of enums sent by the server when a known or unknown value is requested will be the same within a single Showcase server run, + * although they are not guaranteed to be the same across separate Showcase server runs. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.showcase.v1beta1.EnumRequest} request.request + * The original request for a known or unknown enum from the server. + * @param {google.showcase.v1beta1.Continent} request.continent + * The actual enum the server provided. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.EnumResponse|EnumResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/compliance.verify_enum.js + * region_tag:localhost_v1beta1_generated_Compliance_VerifyEnum_async + */ verifyEnum( - request?: protos.google.showcase.v1beta1.IEnumResponse, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IEnumResponse, - protos.google.showcase.v1beta1.IEnumResponse|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IEnumResponse, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IEnumResponse, + protos.google.showcase.v1beta1.IEnumResponse | undefined, + {} | undefined, + ] + >; verifyEnum( - request: protos.google.showcase.v1beta1.IEnumResponse, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.IEnumResponse, - protos.google.showcase.v1beta1.IEnumResponse|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IEnumResponse, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.IEnumResponse, + protos.google.showcase.v1beta1.IEnumResponse | null | undefined, + {} | null | undefined + >, + ): void; verifyEnum( - request: protos.google.showcase.v1beta1.IEnumResponse, - callback: Callback< - protos.google.showcase.v1beta1.IEnumResponse, - protos.google.showcase.v1beta1.IEnumResponse|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IEnumResponse, + callback: Callback< + protos.google.showcase.v1beta1.IEnumResponse, + protos.google.showcase.v1beta1.IEnumResponse | null | undefined, + {} | null | undefined + >, + ): void; verifyEnum( - request?: protos.google.showcase.v1beta1.IEnumResponse, - optionsOrCallback?: CallOptions|Callback< - protos.google.showcase.v1beta1.IEnumResponse, - protos.google.showcase.v1beta1.IEnumResponse|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.showcase.v1beta1.IEnumResponse, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.IEnumResponse, - protos.google.showcase.v1beta1.IEnumResponse|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.IEnumResponse, - protos.google.showcase.v1beta1.IEnumResponse|undefined, {}|undefined - ]>|void { + protos.google.showcase.v1beta1.IEnumResponse | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.IEnumResponse, + protos.google.showcase.v1beta1.IEnumResponse | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IEnumResponse, + protos.google.showcase.v1beta1.IEnumResponse | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('verifyEnum request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.IEnumResponse, - protos.google.showcase.v1beta1.IEnumResponse|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.IEnumResponse, + protos.google.showcase.v1beta1.IEnumResponse | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('verifyEnum response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.verifyEnum(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.IEnumResponse, - protos.google.showcase.v1beta1.IEnumResponse|undefined, {}|undefined - ]) => { - this._log.info('verifyEnum response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .verifyEnum(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.IEnumResponse, + protos.google.showcase.v1beta1.IEnumResponse | undefined, + {} | undefined, + ]) => { + this._log.info('verifyEnum response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); @@ -1414,7 +1790,7 @@ export class ComplianceClient { * @param {string} blueprint * @returns {string} Resource name string. */ - blueprintPath(session:string,test:string,blueprint:string) { + blueprintPath(session: string, test: string, blueprint: string) { return this.pathTemplates.blueprintPathTemplate.render({ session: session, test: test, @@ -1430,7 +1806,8 @@ export class ComplianceClient { * @returns {string} A string representing the session. */ matchSessionFromBlueprintName(blueprintName: string) { - return this.pathTemplates.blueprintPathTemplate.match(blueprintName).session; + return this.pathTemplates.blueprintPathTemplate.match(blueprintName) + .session; } /** @@ -1452,7 +1829,8 @@ export class ComplianceClient { * @returns {string} A string representing the blueprint. */ matchBlueprintFromBlueprintName(blueprintName: string) { - return this.pathTemplates.blueprintPathTemplate.match(blueprintName).blueprint; + return this.pathTemplates.blueprintPathTemplate.match(blueprintName) + .blueprint; } /** @@ -1461,7 +1839,7 @@ export class ComplianceClient { * @param {string} room * @returns {string} Resource name string. */ - roomPath(room:string) { + roomPath(room: string) { return this.pathTemplates.roomPathTemplate.render({ room: room, }); @@ -1485,7 +1863,7 @@ export class ComplianceClient { * @param {string} blurb * @returns {string} Resource name string. */ - roomBlurbPath(room:string,blurb:string) { + roomBlurbPath(room: string, blurb: string) { return this.pathTemplates.roomBlurbPathTemplate.render({ room: room, blurb: blurb, @@ -1522,7 +1900,11 @@ export class ComplianceClient { * @param {string} blurb * @returns {string} Resource name string. */ - roomBlurbsLegacyRoomBlurbPath(room:string,legacyRoom:string,blurb:string) { + roomBlurbsLegacyRoomBlurbPath( + room: string, + legacyRoom: string, + blurb: string, + ) { return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.render({ room: room, legacy_room: legacyRoom, @@ -1537,8 +1919,12 @@ export class ComplianceClient { * A fully-qualified path representing room_blurbs_legacy_room_blurb resource. * @returns {string} A string representing the room. */ - matchRoomFromRoomBlurbsLegacyRoomBlurbName(roomBlurbsLegacyRoomBlurbName: string) { - return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match(roomBlurbsLegacyRoomBlurbName).room; + matchRoomFromRoomBlurbsLegacyRoomBlurbName( + roomBlurbsLegacyRoomBlurbName: string, + ) { + return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match( + roomBlurbsLegacyRoomBlurbName, + ).room; } /** @@ -1548,8 +1934,12 @@ export class ComplianceClient { * A fully-qualified path representing room_blurbs_legacy_room_blurb resource. * @returns {string} A string representing the legacy_room. */ - matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName(roomBlurbsLegacyRoomBlurbName: string) { - return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match(roomBlurbsLegacyRoomBlurbName).legacy_room; + matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName( + roomBlurbsLegacyRoomBlurbName: string, + ) { + return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match( + roomBlurbsLegacyRoomBlurbName, + ).legacy_room; } /** @@ -1559,8 +1949,12 @@ export class ComplianceClient { * A fully-qualified path representing room_blurbs_legacy_room_blurb resource. * @returns {string} A string representing the blurb. */ - matchBlurbFromRoomBlurbsLegacyRoomBlurbName(roomBlurbsLegacyRoomBlurbName: string) { - return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match(roomBlurbsLegacyRoomBlurbName).blurb; + matchBlurbFromRoomBlurbsLegacyRoomBlurbName( + roomBlurbsLegacyRoomBlurbName: string, + ) { + return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match( + roomBlurbsLegacyRoomBlurbName, + ).blurb; } /** @@ -1569,7 +1963,7 @@ export class ComplianceClient { * @param {string} sequence * @returns {string} Resource name string. */ - sequencePath(sequence:string) { + sequencePath(sequence: string) { return this.pathTemplates.sequencePathTemplate.render({ sequence: sequence, }); @@ -1592,7 +1986,7 @@ export class ComplianceClient { * @param {string} sequence * @returns {string} Resource name string. */ - sequenceReportPath(sequence:string) { + sequenceReportPath(sequence: string) { return this.pathTemplates.sequenceReportPathTemplate.render({ sequence: sequence, }); @@ -1606,7 +2000,9 @@ export class ComplianceClient { * @returns {string} A string representing the sequence. */ matchSequenceFromSequenceReportName(sequenceReportName: string) { - return this.pathTemplates.sequenceReportPathTemplate.match(sequenceReportName).sequence; + return this.pathTemplates.sequenceReportPathTemplate.match( + sequenceReportName, + ).sequence; } /** @@ -1615,7 +2011,7 @@ export class ComplianceClient { * @param {string} session * @returns {string} Resource name string. */ - sessionPath(session:string) { + sessionPath(session: string) { return this.pathTemplates.sessionPathTemplate.render({ session: session, }); @@ -1639,7 +2035,7 @@ export class ComplianceClient { * @param {string} test * @returns {string} Resource name string. */ - testPath(session:string,test:string) { + testPath(session: string, test: string) { return this.pathTemplates.testPathTemplate.render({ session: session, test: test, @@ -1674,7 +2070,7 @@ export class ComplianceClient { * @param {string} user * @returns {string} Resource name string. */ - userPath(user:string) { + userPath(user: string) { return this.pathTemplates.userPathTemplate.render({ user: user, }); @@ -1698,7 +2094,7 @@ export class ComplianceClient { * @param {string} blurb * @returns {string} Resource name string. */ - userProfileBlurbPath(user:string,blurb:string) { + userProfileBlurbPath(user: string, blurb: string) { return this.pathTemplates.userProfileBlurbPathTemplate.render({ user: user, blurb: blurb, @@ -1713,7 +2109,9 @@ export class ComplianceClient { * @returns {string} A string representing the user. */ matchUserFromUserProfileBlurbName(userProfileBlurbName: string) { - return this.pathTemplates.userProfileBlurbPathTemplate.match(userProfileBlurbName).user; + return this.pathTemplates.userProfileBlurbPathTemplate.match( + userProfileBlurbName, + ).user; } /** @@ -1724,7 +2122,9 @@ export class ComplianceClient { * @returns {string} A string representing the blurb. */ matchBlurbFromUserProfileBlurbName(userProfileBlurbName: string) { - return this.pathTemplates.userProfileBlurbPathTemplate.match(userProfileBlurbName).blurb; + return this.pathTemplates.userProfileBlurbPathTemplate.match( + userProfileBlurbName, + ).blurb; } /** @@ -1735,12 +2135,18 @@ export class ComplianceClient { * @param {string} blurb * @returns {string} Resource name string. */ - userProfileBlurbsLegacyUserBlurbPath(user:string,legacyUser:string,blurb:string) { - return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.render({ - user: user, - legacy_user: legacyUser, - blurb: blurb, - }); + userProfileBlurbsLegacyUserBlurbPath( + user: string, + legacyUser: string, + blurb: string, + ) { + return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.render( + { + user: user, + legacy_user: legacyUser, + blurb: blurb, + }, + ); } /** @@ -1750,8 +2156,12 @@ export class ComplianceClient { * A fully-qualified path representing user_profile_blurbs_legacy_user_blurb resource. * @returns {string} A string representing the user. */ - matchUserFromUserProfileBlurbsLegacyUserBlurbName(userProfileBlurbsLegacyUserBlurbName: string) { - return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match(userProfileBlurbsLegacyUserBlurbName).user; + matchUserFromUserProfileBlurbsLegacyUserBlurbName( + userProfileBlurbsLegacyUserBlurbName: string, + ) { + return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match( + userProfileBlurbsLegacyUserBlurbName, + ).user; } /** @@ -1761,8 +2171,12 @@ export class ComplianceClient { * A fully-qualified path representing user_profile_blurbs_legacy_user_blurb resource. * @returns {string} A string representing the legacy_user. */ - matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName(userProfileBlurbsLegacyUserBlurbName: string) { - return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match(userProfileBlurbsLegacyUserBlurbName).legacy_user; + matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName( + userProfileBlurbsLegacyUserBlurbName: string, + ) { + return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match( + userProfileBlurbsLegacyUserBlurbName, + ).legacy_user; } /** @@ -1772,8 +2186,12 @@ export class ComplianceClient { * A fully-qualified path representing user_profile_blurbs_legacy_user_blurb resource. * @returns {string} A string representing the blurb. */ - matchBlurbFromUserProfileBlurbsLegacyUserBlurbName(userProfileBlurbsLegacyUserBlurbName: string) { - return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match(userProfileBlurbsLegacyUserBlurbName).blurb; + matchBlurbFromUserProfileBlurbsLegacyUserBlurbName( + userProfileBlurbsLegacyUserBlurbName: string, + ) { + return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match( + userProfileBlurbsLegacyUserBlurbName, + ).blurb; } /** @@ -1784,7 +2202,7 @@ export class ComplianceClient { */ close(): Promise { if (this.complianceStub && !this._terminated) { - return this.complianceStub.then(stub => { + return this.complianceStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -1792,4 +2210,4 @@ export class ComplianceClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/core/generator/gapic-generator-typescript/baselines/showcase-esm/esm/src/v1beta1/echo_client.ts.baseline b/core/generator/gapic-generator-typescript/baselines/showcase-esm/esm/src/v1beta1/echo_client.ts.baseline index c4105b158a90..7365c1bb583a 100644 --- a/core/generator/gapic-generator-typescript/baselines/showcase-esm/esm/src/v1beta1/echo_client.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/showcase-esm/esm/src/v1beta1/echo_client.ts.baseline @@ -18,15 +18,24 @@ /* global window */ import * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions, GrpcClientOptions, LROperation, PaginationCallback, GaxCall} from 'google-gax'; -import {Transform, PassThrough} from 'stream'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + GrpcClientOptions, + LROperation, + PaginationCallback, + GaxCall, +} from 'google-gax'; +import { Transform, PassThrough } from 'stream'; // @ts-ignore import type * as protos from '../../../protos/protos.js'; import * as echo_client_config from './echo_client_config.json'; import fs from 'fs'; import path from 'path'; -import {fileURLToPath} from 'url'; -import {getJSON} from '../json-helper.cjs'; +import { fileURLToPath } from 'url'; +import { getJSON } from '../json-helper.cjs'; // @ts-ignore const dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -35,16 +44,14 @@ const dirname = path.dirname(fileURLToPath(import.meta.url)); * `src/v1beta1/echo_client_config.json`. * This file defines retry strategy and timeouts for all API methods in this library. */ -const gapicConfig = getJSON( - path.join(dirname, 'echo_client_config.json') -); +const gapicConfig = getJSON(path.join(dirname, 'echo_client_config.json')); const jsonProtos = getJSON( - path.join(dirname, '..', '..', '..', 'protos/protos.json') + path.join(dirname, '..', '..', '..', 'protos/protos.json'), ); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; const version = getJSON( - path.join(dirname, '..', '..', '..', '..', 'package.json') + path.join(dirname, '..', '..', '..', '..', 'package.json'), ).version; /** @@ -67,7 +74,7 @@ export class EchoClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('showcase'); @@ -79,10 +86,10 @@ export class EchoClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; operationsClient: gax.OperationsClient; - echoStub?: Promise<{[name: string]: Function}>; + echoStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of EchoClient. @@ -124,21 +131,42 @@ export class EchoClient { * const client = new EchoClient({fallback: 'rest'}, gax); * ``` */ - constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { // Ensure that options include all the required fields. const staticMembers = this.constructor as typeof EchoClient; - if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { - throw new Error('Please set either universe_domain or universeDomain, but not both.'); + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); } - const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; - this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; this._servicePath = 'localhost'; - const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; - const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // Request numeric enum values if REST transport is used. opts.numericEnums = true; @@ -163,7 +191,7 @@ export class EchoClient { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; @@ -180,10 +208,7 @@ export class EchoClient { const isEsm = true; const isEsmString = isEsm ? '-esm' : '-cjs'; // Determine the client header string. - const clientHeader = [ - `gax/${this._gaxModule.version}`, - `gapic/${version}`, - ]; + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/{process.versions.node}${isEsmString}`); } else { @@ -191,7 +216,7 @@ export class EchoClient { } if (!opts.fallback) { clientHeader.push(`grpc/${this._gaxGrpc.grpcVersion}`); - } else if (opts.fallback === 'rest' ) { + } else if (opts.fallback === 'rest') { clientHeader.push(`rest/${this._gaxGrpc.grpcVersion}`); } if (opts.libName && opts.libVersion) { @@ -199,61 +224,74 @@ export class EchoClient { } // Load the applicable protos. - this._protos = this._gaxGrpc.loadProtoJSON(jsonProtos as gax.protobuf.INamespace); + this._protos = this._gaxGrpc.loadProtoJSON( + jsonProtos as gax.protobuf.INamespace, + ); // This API contains "path templates"; forward-slash-separated // identifiers to uniquely identify resources within the API. // Create useful helper objects for these. this.pathTemplates = { blueprintPathTemplate: new this._gaxModule.PathTemplate( - 'sessions/{session}/tests/{test}/blueprints/{blueprint}' - ), - roomPathTemplate: new this._gaxModule.PathTemplate( - 'rooms/{room}' + 'sessions/{session}/tests/{test}/blueprints/{blueprint}', ), + roomPathTemplate: new this._gaxModule.PathTemplate('rooms/{room}'), roomBlurbPathTemplate: new this._gaxModule.PathTemplate( - 'rooms/{room}/blurbs/{blurb}' + 'rooms/{room}/blurbs/{blurb}', ), roomBlurbsLegacyRoomBlurbPathTemplate: new this._gaxModule.PathTemplate( - 'rooms/{room}/blurbs/legacy/{legacy_room}.{blurb}' + 'rooms/{room}/blurbs/legacy/{legacy_room}.{blurb}', ), sequencePathTemplate: new this._gaxModule.PathTemplate( - 'sequences/{sequence}' + 'sequences/{sequence}', ), sequenceReportPathTemplate: new this._gaxModule.PathTemplate( - 'sequences/{sequence}/sequenceReport' + 'sequences/{sequence}/sequenceReport', ), sessionPathTemplate: new this._gaxModule.PathTemplate( - 'sessions/{session}' + 'sessions/{session}', ), testPathTemplate: new this._gaxModule.PathTemplate( - 'sessions/{session}/tests/{test}' - ), - userPathTemplate: new this._gaxModule.PathTemplate( - 'users/{user}' + 'sessions/{session}/tests/{test}', ), + userPathTemplate: new this._gaxModule.PathTemplate('users/{user}'), userProfileBlurbPathTemplate: new this._gaxModule.PathTemplate( - 'users/{user}/profile/blurbs/{blurb}' - ), - userProfileBlurbsLegacyUserBlurbPathTemplate: new this._gaxModule.PathTemplate( - 'users/{user}/profile/blurbs/legacy/{legacy_user}~{blurb}' + 'users/{user}/profile/blurbs/{blurb}', ), + userProfileBlurbsLegacyUserBlurbPathTemplate: + new this._gaxModule.PathTemplate( + 'users/{user}/profile/blurbs/legacy/{legacy_user}~{blurb}', + ), }; // Some of the methods on this service return "paged" results, // (e.g. 50 results at a time, with tokens to get subsequent // pages). Denote the keys used for pagination and results. this.descriptors.page = { - pagedExpand: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'responses') + pagedExpand: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'responses', + ), }; // Some of the methods on this service provide streaming responses. // Provide descriptors for these. this.descriptors.stream = { - expand: new this._gaxModule.StreamDescriptor(this._gaxModule.StreamType.SERVER_STREAMING, !!opts.fallback, !!opts.gaxServerStreamingRetries), - collect: new this._gaxModule.StreamDescriptor(this._gaxModule.StreamType.CLIENT_STREAMING, !!opts.fallback), - chat: new this._gaxModule.StreamDescriptor(this._gaxModule.StreamType.BIDI_STREAMING, !!opts.fallback, !!opts.gaxServerStreamingRetries) + expand: new this._gaxModule.StreamDescriptor( + this._gaxModule.StreamType.SERVER_STREAMING, + !!opts.fallback, + !!opts.gaxServerStreamingRetries, + ), + collect: new this._gaxModule.StreamDescriptor( + this._gaxModule.StreamType.CLIENT_STREAMING, + !!opts.fallback, + ), + chat: new this._gaxModule.StreamDescriptor( + this._gaxModule.StreamType.BIDI_STREAMING, + !!opts.fallback, + !!opts.gaxServerStreamingRetries, + ), }; const protoFilesRoot = this._gaxModule.protobufFromJSON(jsonProtos); @@ -262,32 +300,106 @@ export class EchoClient { // rather than holding a request open. const lroOptions: GrpcClientOptions = { auth: this.auth, - grpc: 'grpc' in this._gaxGrpc ? this._gaxGrpc.grpc : undefined + grpc: 'grpc' in this._gaxGrpc ? this._gaxGrpc.grpc : undefined, }; if (opts.fallback === 'rest') { lroOptions.protoJson = protoFilesRoot; - lroOptions.httpRules = [{selector: 'google.cloud.location.Locations.ListLocations',get: '/v1beta1/{name=projects/*}/locations',},{selector: 'google.cloud.location.Locations.GetLocation',get: '/v1beta1/{name=projects/*/locations/*}',},{selector: 'google.iam.v1.IAMPolicy.SetIamPolicy',post: '/v1beta1/{resource=users/*}:setIamPolicy',body: '*',additional_bindings: [{post: '/v1beta1/{resource=rooms/*}:setIamPolicy',body: '*',},{post: '/v1beta1/{resource=rooms/*/blurbs/*}:setIamPolicy',body: '*',},{post: '/v1beta1/{resource=sequences/*}:setIamPolicy',body: '*',}], - },{selector: 'google.iam.v1.IAMPolicy.GetIamPolicy',get: '/v1beta1/{resource=users/*}:getIamPolicy',additional_bindings: [{get: '/v1beta1/{resource=rooms/*}:getIamPolicy',},{get: '/v1beta1/{resource=rooms/*/blurbs/*}:getIamPolicy',},{get: '/v1beta1/{resource=sequences/*}:getIamPolicy',}], - },{selector: 'google.iam.v1.IAMPolicy.TestIamPermissions',post: '/v1beta1/{resource=users/*}:testIamPermissions',body: '*',additional_bindings: [{post: '/v1beta1/{resource=rooms/*}:testIamPermissions',body: '*',},{post: '/v1beta1/{resource=rooms/*/blurbs/*}:testIamPermissions',body: '*',},{post: '/v1beta1/{resource=sequences/*}:testIamPermissions',body: '*',}], - },{selector: 'google.longrunning.Operations.ListOperations',get: '/v1beta1/operations',},{selector: 'google.longrunning.Operations.GetOperation',get: '/v1beta1/{name=operations/**}',},{selector: 'google.longrunning.Operations.DeleteOperation',delete: '/v1beta1/{name=operations/**}',},{selector: 'google.longrunning.Operations.CancelOperation',post: '/v1beta1/{name=operations/**}:cancel',}]; + lroOptions.httpRules = [ + { + selector: 'google.cloud.location.Locations.ListLocations', + get: '/v1beta1/{name=projects/*}/locations', + }, + { + selector: 'google.cloud.location.Locations.GetLocation', + get: '/v1beta1/{name=projects/*/locations/*}', + }, + { + selector: 'google.iam.v1.IAMPolicy.SetIamPolicy', + post: '/v1beta1/{resource=users/*}:setIamPolicy', + body: '*', + additional_bindings: [ + { post: '/v1beta1/{resource=rooms/*}:setIamPolicy', body: '*' }, + { + post: '/v1beta1/{resource=rooms/*/blurbs/*}:setIamPolicy', + body: '*', + }, + { post: '/v1beta1/{resource=sequences/*}:setIamPolicy', body: '*' }, + ], + }, + { + selector: 'google.iam.v1.IAMPolicy.GetIamPolicy', + get: '/v1beta1/{resource=users/*}:getIamPolicy', + additional_bindings: [ + { get: '/v1beta1/{resource=rooms/*}:getIamPolicy' }, + { get: '/v1beta1/{resource=rooms/*/blurbs/*}:getIamPolicy' }, + { get: '/v1beta1/{resource=sequences/*}:getIamPolicy' }, + ], + }, + { + selector: 'google.iam.v1.IAMPolicy.TestIamPermissions', + post: '/v1beta1/{resource=users/*}:testIamPermissions', + body: '*', + additional_bindings: [ + { + post: '/v1beta1/{resource=rooms/*}:testIamPermissions', + body: '*', + }, + { + post: '/v1beta1/{resource=rooms/*/blurbs/*}:testIamPermissions', + body: '*', + }, + { + post: '/v1beta1/{resource=sequences/*}:testIamPermissions', + body: '*', + }, + ], + }, + { + selector: 'google.longrunning.Operations.ListOperations', + get: '/v1beta1/operations', + }, + { + selector: 'google.longrunning.Operations.GetOperation', + get: '/v1beta1/{name=operations/**}', + }, + { + selector: 'google.longrunning.Operations.DeleteOperation', + delete: '/v1beta1/{name=operations/**}', + }, + { + selector: 'google.longrunning.Operations.CancelOperation', + post: '/v1beta1/{name=operations/**}:cancel', + }, + ]; } - this.operationsClient = this._gaxModule.lro(lroOptions).operationsClient(opts); + this.operationsClient = this._gaxModule + .lro(lroOptions) + .operationsClient(opts); const waitResponse = protoFilesRoot.lookup( - '.google.showcase.v1beta1.WaitResponse') as gax.protobuf.Type; + '.google.showcase.v1beta1.WaitResponse', + ) as gax.protobuf.Type; const waitMetadata = protoFilesRoot.lookup( - '.google.showcase.v1beta1.WaitMetadata') as gax.protobuf.Type; + '.google.showcase.v1beta1.WaitMetadata', + ) as gax.protobuf.Type; this.descriptors.longrunning = { wait: new this._gaxModule.LongrunningDescriptor( this.operationsClient, waitResponse.decode.bind(waitResponse), - waitMetadata.decode.bind(waitMetadata)) + waitMetadata.decode.bind(waitMetadata), + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.showcase.v1beta1.Echo', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' '), 'x-goog-api-version': 'v1_20240408'}); + 'google.showcase.v1beta1.Echo', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + { + 'x-goog-api-client': clientHeader.join(' '), + 'x-goog-api-version': 'v1_20240408', + }, + ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -318,35 +430,55 @@ export class EchoClient { // Put together the "service stub" for // google.showcase.v1beta1.Echo. this.echoStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.showcase.v1beta1.Echo') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.showcase.v1beta1.Echo', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.showcase.v1beta1.Echo, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts, + this._providedCustomServicePath, + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const echoStubMethods = - ['echo', 'echoErrorDetails', 'expand', 'collect', 'chat', 'pagedExpand', 'pagedExpandLegacy', 'wait', 'block']; + const echoStubMethods = [ + 'echo', + 'echoErrorDetails', + 'expand', + 'collect', + 'chat', + 'pagedExpand', + 'pagedExpandLegacy', + 'wait', + 'block', + ]; for (const methodName of echoStubMethods) { const callPromise = this.echoStub.then( - stub => (...args: Array<{}>) => { - if (this._terminated) { - if (methodName in this.descriptors.stream) { - const stream = new PassThrough({objectMode: true}); - setImmediate(() => { - stream.emit('error', new this._gaxModule.GoogleError('The client has already been closed.')); - }); - return stream; + (stub) => + (...args: Array<{}>) => { + if (this._terminated) { + if (methodName in this.descriptors.stream) { + const stream = new PassThrough({ objectMode: true }); + setImmediate(() => { + stream.emit( + 'error', + new this._gaxModule.GoogleError( + 'The client has already been closed.', + ), + ); + }); + return stream; + } + return Promise.reject('The client has already been closed.'); } - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error|null|undefined) => () => { + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { throw err; - }); + }, + ); const descriptor = this.descriptors.page[methodName] || @@ -357,7 +489,7 @@ export class EchoClient { callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -372,8 +504,14 @@ export class EchoClient { * @returns {string} The DNS address for this service. */ static get servicePath() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'localhost'; } @@ -385,8 +523,14 @@ export class EchoClient { * @returns {string} The DNS address for this service. */ static get apiEndpoint() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'localhost'; } @@ -426,8 +570,9 @@ export class EchoClient { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId(callback?: Callback): - Promise|void { + getProjectId( + callback?: Callback, + ): Promise | void { if (callback) { this.auth.getProjectId(callback); return; @@ -438,66 +583,80 @@ export class EchoClient { // ------------------- // -- Service calls -- // ------------------- -/** - * @param {Object} request - * The request object that will be sent. - * @param {string} request.content - * The content to be echoed by the server. - * @param {google.rpc.Status} request.error - * The error to be thrown by the server. - * @param {google.showcase.v1beta1.Severity} request.severity - * The severity to be echoed by the server. - * @param {string} request.header - * Optional. This field can be set to test the routing annotation on the Echo method. - * @param {string} request.otherHeader - * Optional. This field can be set to test the routing annotation on the Echo method. - * @param {string} request.requestId - * To facilitate testing of https://google.aip.dev/client-libraries/4235 - * @param {string} request.otherRequestId - * To facilitate testing of https://google.aip.dev/client-libraries/4235 - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.EchoResponse|EchoResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/echo.echo.js - * region_tag:localhost_v1beta1_generated_Echo_Echo_async - */ + /** + * @param {Object} request + * The request object that will be sent. + * @param {string} request.content + * The content to be echoed by the server. + * @param {google.rpc.Status} request.error + * The error to be thrown by the server. + * @param {google.showcase.v1beta1.Severity} request.severity + * The severity to be echoed by the server. + * @param {string} request.header + * Optional. This field can be set to test the routing annotation on the Echo method. + * @param {string} request.otherHeader + * Optional. This field can be set to test the routing annotation on the Echo method. + * @param {string} request.requestId + * To facilitate testing of https://google.aip.dev/client-libraries/4235 + * @param {string} request.otherRequestId + * To facilitate testing of https://google.aip.dev/client-libraries/4235 + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.EchoResponse|EchoResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/echo.echo.js + * region_tag:localhost_v1beta1_generated_Echo_Echo_async + */ echo( - request?: protos.google.showcase.v1beta1.IEchoRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IEchoResponse, - protos.google.showcase.v1beta1.IEchoRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IEchoRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IEchoResponse, + protos.google.showcase.v1beta1.IEchoRequest | undefined, + {} | undefined, + ] + >; echo( - request: protos.google.showcase.v1beta1.IEchoRequest, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.IEchoResponse, - protos.google.showcase.v1beta1.IEchoRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IEchoRequest, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.IEchoResponse, + protos.google.showcase.v1beta1.IEchoRequest | null | undefined, + {} | null | undefined + >, + ): void; echo( - request: protos.google.showcase.v1beta1.IEchoRequest, - callback: Callback< - protos.google.showcase.v1beta1.IEchoResponse, - protos.google.showcase.v1beta1.IEchoRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IEchoRequest, + callback: Callback< + protos.google.showcase.v1beta1.IEchoResponse, + protos.google.showcase.v1beta1.IEchoRequest | null | undefined, + {} | null | undefined + >, + ): void; echo( - request?: protos.google.showcase.v1beta1.IEchoRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.showcase.v1beta1.IEchoResponse, - protos.google.showcase.v1beta1.IEchoRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.showcase.v1beta1.IEchoRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.IEchoResponse, - protos.google.showcase.v1beta1.IEchoRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.IEchoResponse, - protos.google.showcase.v1beta1.IEchoRequest|undefined, {}|undefined - ]>|void { + protos.google.showcase.v1beta1.IEchoRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.IEchoResponse, + protos.google.showcase.v1beta1.IEchoRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IEchoResponse, + protos.google.showcase.v1beta1.IEchoRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; if (!request.requestId) { request.requestId = gax.makeUUID(); @@ -506,8 +665,7 @@ export class EchoClient { if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; @@ -527,7 +685,9 @@ export class EchoClient { { const fieldValue = request.header; if (fieldValue !== undefined && fieldValue !== null) { - const match = fieldValue.toString().match(RegExp('(?(?:.*)?)')); + const match = fieldValue + .toString() + .match(RegExp('(?(?:.*)?)')); if (match) { const parameterValue = match.groups?.['routing_id'] ?? fieldValue; Object.assign(routingParameter, { routing_id: parameterValue }); @@ -537,7 +697,9 @@ export class EchoClient { { const fieldValue = request.header; if (fieldValue !== undefined && fieldValue !== null) { - const match = fieldValue.toString().match(RegExp('(?regions/[^/]+/zones/[^/]+(?:/.*)?)')); + const match = fieldValue + .toString() + .match(RegExp('(?regions/[^/]+/zones/[^/]+(?:/.*)?)')); if (match) { const parameterValue = match.groups?.['table_name'] ?? fieldValue; Object.assign(routingParameter, { table_name: parameterValue }); @@ -547,7 +709,9 @@ export class EchoClient { { const fieldValue = request.header; if (fieldValue !== undefined && fieldValue !== null) { - const match = fieldValue.toString().match(RegExp('(?projects/[^/]+)(?:/.*)?')); + const match = fieldValue + .toString() + .match(RegExp('(?projects/[^/]+)(?:/.*)?')); if (match) { const parameterValue = match.groups?.['super_id'] ?? fieldValue; Object.assign(routingParameter, { super_id: parameterValue }); @@ -557,7 +721,11 @@ export class EchoClient { { const fieldValue = request.header; if (fieldValue !== undefined && fieldValue !== null) { - const match = fieldValue.toString().match(RegExp('(?projects/[^/]+/instances/[^/]+(?:/.*)?)')); + const match = fieldValue + .toString() + .match( + RegExp('(?projects/[^/]+/instances/[^/]+(?:/.*)?)'), + ); if (match) { const parameterValue = match.groups?.['table_name'] ?? fieldValue; Object.assign(routingParameter, { table_name: parameterValue }); @@ -567,7 +735,11 @@ export class EchoClient { { const fieldValue = request.header; if (fieldValue !== undefined && fieldValue !== null) { - const match = fieldValue.toString().match(RegExp('projects/[^/]+/(?instances/[^/]+)(?:/.*)?')); + const match = fieldValue + .toString() + .match( + RegExp('projects/[^/]+/(?instances/[^/]+)(?:/.*)?'), + ); if (match) { const parameterValue = match.groups?.['instance_id'] ?? fieldValue; Object.assign(routingParameter, { instance_id: parameterValue }); @@ -587,625 +759,852 @@ export class EchoClient { { const fieldValue = request.otherHeader; if (fieldValue !== undefined && fieldValue !== null) { - const match = fieldValue.toString().match(RegExp('(?projects/[^/]+)(?:/.*)?')); + const match = fieldValue + .toString() + .match(RegExp('(?projects/[^/]+)(?:/.*)?')); if (match) { const parameterValue = match.groups?.['qux'] ?? fieldValue; Object.assign(routingParameter, { qux: parameterValue }); } } } - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams( - routingParameter - ); - this.initialize().catch(err => {throw err}); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams(routingParameter); + this.initialize().catch((err) => { + throw err; + }); this._log.info('echo request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.IEchoResponse, - protos.google.showcase.v1beta1.IEchoRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.IEchoResponse, + protos.google.showcase.v1beta1.IEchoRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('echo response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.echo(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.IEchoResponse, - protos.google.showcase.v1beta1.IEchoRequest|undefined, {}|undefined - ]) => { - this._log.info('echo response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .echo(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.IEchoResponse, + protos.google.showcase.v1beta1.IEchoRequest | undefined, + {} | undefined, + ]) => { + this._log.info('echo response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * This method returns error details in a repeated "google.protobuf.Any" - * field. This method showcases handling errors thus encoded, particularly - * over REST transport. Note that GAPICs only allow the type - * "google.protobuf.Any" for field paths ending in "error.details", and, at - * run-time, the actual types for these fields must be one of the types in - * google/rpc/error_details.proto. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.singleDetailText - * Content to return in a singular `*.error.details` field of type - * `google.protobuf.Any` - * @param {string[]} request.multiDetailText - * Content to return in a repeated `*.error.details` field of type - * `google.protobuf.Any` - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.EchoErrorDetailsResponse|EchoErrorDetailsResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/echo.echo_error_details.js - * region_tag:localhost_v1beta1_generated_Echo_EchoErrorDetails_async - */ + /** + * This method returns error details in a repeated "google.protobuf.Any" + * field. This method showcases handling errors thus encoded, particularly + * over REST transport. Note that GAPICs only allow the type + * "google.protobuf.Any" for field paths ending in "error.details", and, at + * run-time, the actual types for these fields must be one of the types in + * google/rpc/error_details.proto. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.singleDetailText + * Content to return in a singular `*.error.details` field of type + * `google.protobuf.Any` + * @param {string[]} request.multiDetailText + * Content to return in a repeated `*.error.details` field of type + * `google.protobuf.Any` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.EchoErrorDetailsResponse|EchoErrorDetailsResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/echo.echo_error_details.js + * region_tag:localhost_v1beta1_generated_Echo_EchoErrorDetails_async + */ echoErrorDetails( - request?: protos.google.showcase.v1beta1.IEchoErrorDetailsRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IEchoErrorDetailsResponse, - protos.google.showcase.v1beta1.IEchoErrorDetailsRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IEchoErrorDetailsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IEchoErrorDetailsResponse, + protos.google.showcase.v1beta1.IEchoErrorDetailsRequest | undefined, + {} | undefined, + ] + >; echoErrorDetails( - request: protos.google.showcase.v1beta1.IEchoErrorDetailsRequest, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.IEchoErrorDetailsResponse, - protos.google.showcase.v1beta1.IEchoErrorDetailsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IEchoErrorDetailsRequest, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.IEchoErrorDetailsResponse, + | protos.google.showcase.v1beta1.IEchoErrorDetailsRequest + | null + | undefined, + {} | null | undefined + >, + ): void; echoErrorDetails( - request: protos.google.showcase.v1beta1.IEchoErrorDetailsRequest, - callback: Callback< - protos.google.showcase.v1beta1.IEchoErrorDetailsResponse, - protos.google.showcase.v1beta1.IEchoErrorDetailsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IEchoErrorDetailsRequest, + callback: Callback< + protos.google.showcase.v1beta1.IEchoErrorDetailsResponse, + | protos.google.showcase.v1beta1.IEchoErrorDetailsRequest + | null + | undefined, + {} | null | undefined + >, + ): void; echoErrorDetails( - request?: protos.google.showcase.v1beta1.IEchoErrorDetailsRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.showcase.v1beta1.IEchoErrorDetailsRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.IEchoErrorDetailsResponse, - protos.google.showcase.v1beta1.IEchoErrorDetailsRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.showcase.v1beta1.IEchoErrorDetailsResponse, - protos.google.showcase.v1beta1.IEchoErrorDetailsRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.IEchoErrorDetailsResponse, - protos.google.showcase.v1beta1.IEchoErrorDetailsRequest|undefined, {}|undefined - ]>|void { + | protos.google.showcase.v1beta1.IEchoErrorDetailsRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.IEchoErrorDetailsResponse, + | protos.google.showcase.v1beta1.IEchoErrorDetailsRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IEchoErrorDetailsResponse, + protos.google.showcase.v1beta1.IEchoErrorDetailsRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('echoErrorDetails request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.IEchoErrorDetailsResponse, - protos.google.showcase.v1beta1.IEchoErrorDetailsRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.IEchoErrorDetailsResponse, + | protos.google.showcase.v1beta1.IEchoErrorDetailsRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('echoErrorDetails response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.echoErrorDetails(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.IEchoErrorDetailsResponse, - protos.google.showcase.v1beta1.IEchoErrorDetailsRequest|undefined, {}|undefined - ]) => { - this._log.info('echoErrorDetails response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .echoErrorDetails(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.IEchoErrorDetailsResponse, + protos.google.showcase.v1beta1.IEchoErrorDetailsRequest | undefined, + {} | undefined, + ]) => { + this._log.info('echoErrorDetails response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * This is similar to the PagedExpand except that it uses - * max_results instead of page_size, as some legacy APIs still - * do. New APIs should NOT use this pattern. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.content - * The string to expand. - * @param {number} request.maxResults - * The number of words to returned in each page. - * (-- aip.dev/not-precedent: This is a legacy, non-standard pattern that - * violates aip.dev/158. Ordinarily, this should be page_size. --) - * @param {string} request.pageToken - * The position of the page to be returned. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.PagedExpandResponse|PagedExpandResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/echo.paged_expand_legacy.js - * region_tag:localhost_v1beta1_generated_Echo_PagedExpandLegacy_async - */ + /** + * This is similar to the PagedExpand except that it uses + * max_results instead of page_size, as some legacy APIs still + * do. New APIs should NOT use this pattern. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.content + * The string to expand. + * @param {number} request.maxResults + * The number of words to returned in each page. + * (-- aip.dev/not-precedent: This is a legacy, non-standard pattern that + * violates aip.dev/158. Ordinarily, this should be page_size. --) + * @param {string} request.pageToken + * The position of the page to be returned. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.PagedExpandResponse|PagedExpandResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/echo.paged_expand_legacy.js + * region_tag:localhost_v1beta1_generated_Echo_PagedExpandLegacy_async + */ pagedExpandLegacy( - request?: protos.google.showcase.v1beta1.IPagedExpandLegacyRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IPagedExpandResponse, - protos.google.showcase.v1beta1.IPagedExpandLegacyRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IPagedExpandLegacyRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IPagedExpandResponse, + protos.google.showcase.v1beta1.IPagedExpandLegacyRequest | undefined, + {} | undefined, + ] + >; pagedExpandLegacy( - request: protos.google.showcase.v1beta1.IPagedExpandLegacyRequest, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.IPagedExpandResponse, - protos.google.showcase.v1beta1.IPagedExpandLegacyRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IPagedExpandLegacyRequest, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.IPagedExpandResponse, + | protos.google.showcase.v1beta1.IPagedExpandLegacyRequest + | null + | undefined, + {} | null | undefined + >, + ): void; pagedExpandLegacy( - request: protos.google.showcase.v1beta1.IPagedExpandLegacyRequest, - callback: Callback< - protos.google.showcase.v1beta1.IPagedExpandResponse, - protos.google.showcase.v1beta1.IPagedExpandLegacyRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IPagedExpandLegacyRequest, + callback: Callback< + protos.google.showcase.v1beta1.IPagedExpandResponse, + | protos.google.showcase.v1beta1.IPagedExpandLegacyRequest + | null + | undefined, + {} | null | undefined + >, + ): void; pagedExpandLegacy( - request?: protos.google.showcase.v1beta1.IPagedExpandLegacyRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.showcase.v1beta1.IPagedExpandResponse, - protos.google.showcase.v1beta1.IPagedExpandLegacyRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.showcase.v1beta1.IPagedExpandLegacyRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.IPagedExpandResponse, - protos.google.showcase.v1beta1.IPagedExpandLegacyRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.IPagedExpandResponse, - protos.google.showcase.v1beta1.IPagedExpandLegacyRequest|undefined, {}|undefined - ]>|void { + | protos.google.showcase.v1beta1.IPagedExpandLegacyRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.IPagedExpandResponse, + | protos.google.showcase.v1beta1.IPagedExpandLegacyRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IPagedExpandResponse, + protos.google.showcase.v1beta1.IPagedExpandLegacyRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('pagedExpandLegacy request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.IPagedExpandResponse, - protos.google.showcase.v1beta1.IPagedExpandLegacyRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.IPagedExpandResponse, + | protos.google.showcase.v1beta1.IPagedExpandLegacyRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('pagedExpandLegacy response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.pagedExpandLegacy(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.IPagedExpandResponse, - protos.google.showcase.v1beta1.IPagedExpandLegacyRequest|undefined, {}|undefined - ]) => { - this._log.info('pagedExpandLegacy response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .pagedExpandLegacy(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.IPagedExpandResponse, + protos.google.showcase.v1beta1.IPagedExpandLegacyRequest | undefined, + {} | undefined, + ]) => { + this._log.info('pagedExpandLegacy response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * This method will block (wait) for the requested amount of time - * and then return the response or error. - * This method showcases how a client handles delays or retries. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.protobuf.Duration} request.responseDelay - * The amount of time to block before returning a response. - * @param {google.rpc.Status} request.error - * The error that will be returned by the server. If this code is specified - * to be the OK rpc code, an empty response will be returned. - * @param {google.showcase.v1beta1.BlockResponse} request.success - * The response to be returned that will signify successful method call. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.BlockResponse|BlockResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/echo.block.js - * region_tag:localhost_v1beta1_generated_Echo_Block_async - */ + /** + * This method will block (wait) for the requested amount of time + * and then return the response or error. + * This method showcases how a client handles delays or retries. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.protobuf.Duration} request.responseDelay + * The amount of time to block before returning a response. + * @param {google.rpc.Status} request.error + * The error that will be returned by the server. If this code is specified + * to be the OK rpc code, an empty response will be returned. + * @param {google.showcase.v1beta1.BlockResponse} request.success + * The response to be returned that will signify successful method call. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.BlockResponse|BlockResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/echo.block.js + * region_tag:localhost_v1beta1_generated_Echo_Block_async + */ block( - request?: protos.google.showcase.v1beta1.IBlockRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IBlockResponse, - protos.google.showcase.v1beta1.IBlockRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IBlockRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IBlockResponse, + protos.google.showcase.v1beta1.IBlockRequest | undefined, + {} | undefined, + ] + >; block( - request: protos.google.showcase.v1beta1.IBlockRequest, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.IBlockResponse, - protos.google.showcase.v1beta1.IBlockRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IBlockRequest, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.IBlockResponse, + protos.google.showcase.v1beta1.IBlockRequest | null | undefined, + {} | null | undefined + >, + ): void; block( - request: protos.google.showcase.v1beta1.IBlockRequest, - callback: Callback< - protos.google.showcase.v1beta1.IBlockResponse, - protos.google.showcase.v1beta1.IBlockRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IBlockRequest, + callback: Callback< + protos.google.showcase.v1beta1.IBlockResponse, + protos.google.showcase.v1beta1.IBlockRequest | null | undefined, + {} | null | undefined + >, + ): void; block( - request?: protos.google.showcase.v1beta1.IBlockRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.showcase.v1beta1.IBlockResponse, - protos.google.showcase.v1beta1.IBlockRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.showcase.v1beta1.IBlockRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.IBlockResponse, - protos.google.showcase.v1beta1.IBlockRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.IBlockResponse, - protos.google.showcase.v1beta1.IBlockRequest|undefined, {}|undefined - ]>|void { + protos.google.showcase.v1beta1.IBlockRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.IBlockResponse, + protos.google.showcase.v1beta1.IBlockRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IBlockResponse, + protos.google.showcase.v1beta1.IBlockRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('block request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.IBlockResponse, - protos.google.showcase.v1beta1.IBlockRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.IBlockResponse, + protos.google.showcase.v1beta1.IBlockRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('block response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.block(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.IBlockResponse, - protos.google.showcase.v1beta1.IBlockRequest|undefined, {}|undefined - ]) => { - this._log.info('block response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .block(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.IBlockResponse, + protos.google.showcase.v1beta1.IBlockRequest | undefined, + {} | undefined, + ]) => { + this._log.info('block response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * This method splits the given content into words and will pass each word back - * through the stream. This method showcases server-side streaming RPCs. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.content - * The content that will be split into words and returned on the stream. - * @param {google.rpc.Status} request.error - * The error that is thrown after all words are sent on the stream. - * @param {google.protobuf.Duration} request.streamWaitTime - * The wait time between each server streaming messages - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits {@link protos.google.showcase.v1beta1.EchoResponse|EchoResponse} on 'data' event. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#server-streaming | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/echo.expand.js - * region_tag:localhost_v1beta1_generated_Echo_Expand_async - */ + /** + * This method splits the given content into words and will pass each word back + * through the stream. This method showcases server-side streaming RPCs. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.content + * The content that will be split into words and returned on the stream. + * @param {google.rpc.Status} request.error + * The error that is thrown after all words are sent on the stream. + * @param {google.protobuf.Duration} request.streamWaitTime + * The wait time between each server streaming messages + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits {@link protos.google.showcase.v1beta1.EchoResponse|EchoResponse} on 'data' event. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#server-streaming | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/echo.expand.js + * region_tag:localhost_v1beta1_generated_Echo_Expand_async + */ expand( - request?: protos.google.showcase.v1beta1.IExpandRequest, - options?: CallOptions): - gax.CancellableStream{ + request?: protos.google.showcase.v1beta1.IExpandRequest, + options?: CallOptions, + ): gax.CancellableStream { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('expand stream %j', options); return this.innerApiCalls.expand(request, options); } -/** - * This method will collect the words given to it. When the stream is closed - * by the client, this method will return the a concatenation of the strings - * passed to it. This method showcases client-side streaming RPCs. - * - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - A writable stream which accepts objects representing - * {@link protos.google.showcase.v1beta1.EchoRequest|EchoRequest}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#client-streaming | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/echo.collect.js - * region_tag:localhost_v1beta1_generated_Echo_Collect_async - */ + /** + * This method will collect the words given to it. When the stream is closed + * by the client, this method will return the a concatenation of the strings + * passed to it. This method showcases client-side streaming RPCs. + * + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} - A writable stream which accepts objects representing + * {@link protos.google.showcase.v1beta1.EchoRequest|EchoRequest}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#client-streaming | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/echo.collect.js + * region_tag:localhost_v1beta1_generated_Echo_Collect_async + */ collect( - options?: CallOptions, - callback?: Callback< - protos.google.showcase.v1beta1.IEchoResponse, - protos.google.showcase.v1beta1.IEchoRequest|null|undefined, - {}|null|undefined>): - gax.CancellableStream; + options?: CallOptions, + callback?: Callback< + protos.google.showcase.v1beta1.IEchoResponse, + protos.google.showcase.v1beta1.IEchoRequest | null | undefined, + {} | null | undefined + >, + ): gax.CancellableStream; collect( - callback?: Callback< - protos.google.showcase.v1beta1.IEchoResponse, - protos.google.showcase.v1beta1.IEchoRequest|null|undefined, - {}|null|undefined>): - gax.CancellableStream; + callback?: Callback< + protos.google.showcase.v1beta1.IEchoResponse, + protos.google.showcase.v1beta1.IEchoRequest | null | undefined, + {} | null | undefined + >, + ): gax.CancellableStream; collect( - optionsOrCallback?: CallOptions|Callback< - protos.google.showcase.v1beta1.IEchoResponse, - protos.google.showcase.v1beta1.IEchoRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.showcase.v1beta1.IEchoResponse, - protos.google.showcase.v1beta1.IEchoRequest|null|undefined, - {}|null|undefined>): - gax.CancellableStream { + optionsOrCallback?: + | CallOptions + | Callback< + protos.google.showcase.v1beta1.IEchoResponse, + protos.google.showcase.v1beta1.IEchoRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.IEchoResponse, + protos.google.showcase.v1beta1.IEchoRequest | null | undefined, + {} | null | undefined + >, + ): gax.CancellableStream { if (optionsOrCallback instanceof Function && callback === undefined) { - callback = optionsOrCallback; - optionsOrCallback = {}; + callback = optionsOrCallback; + optionsOrCallback = {}; } const options = optionsOrCallback as CallOptions; - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('collect stream %j', options); return this.innerApiCalls.collect(null, options, callback); } -/** - * This method, upon receiving a request on the stream, will pass the same - * content back on the stream. This method showcases bidirectional - * streaming RPCs. - * - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which is both readable and writable. It accepts objects - * representing {@link protos.google.showcase.v1beta1.EchoRequest|EchoRequest} for write() method, and - * will emit objects representing {@link protos.google.showcase.v1beta1.EchoResponse|EchoResponse} on 'data' event asynchronously. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#bi-directional-streaming | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/echo.chat.js - * region_tag:localhost_v1beta1_generated_Echo_Chat_async - */ - chat( - options?: CallOptions): - gax.CancellableStream { - this.initialize().catch(err => {throw err}); + /** + * This method, upon receiving a request on the stream, will pass the same + * content back on the stream. This method showcases bidirectional + * streaming RPCs. + * + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which is both readable and writable. It accepts objects + * representing {@link protos.google.showcase.v1beta1.EchoRequest|EchoRequest} for write() method, and + * will emit objects representing {@link protos.google.showcase.v1beta1.EchoResponse|EchoResponse} on 'data' event asynchronously. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#bi-directional-streaming | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/echo.chat.js + * region_tag:localhost_v1beta1_generated_Echo_Chat_async + */ + chat(options?: CallOptions): gax.CancellableStream { + this.initialize().catch((err) => { + throw err; + }); this._log.info('chat stream %j', options); return this.innerApiCalls.chat(null, options); } -/** - * This method will wait for the requested amount of time and then return. - * This method showcases how a client handles a request timeout. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.protobuf.Timestamp} request.endTime - * The time that this operation will complete. - * @param {google.protobuf.Duration} request.ttl - * The duration of this operation. - * @param {google.rpc.Status} request.error - * The error that will be returned by the server. If this code is specified - * to be the OK rpc code, an empty response will be returned. - * @param {google.showcase.v1beta1.WaitResponse} request.success - * The response to be returned on operation completion. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing - * a long running operation. Its `promise()` method returns a promise - * you can `await` for. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/echo.wait.js - * region_tag:localhost_v1beta1_generated_Echo_Wait_async - */ + /** + * This method will wait for the requested amount of time and then return. + * This method showcases how a client handles a request timeout. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.protobuf.Timestamp} request.endTime + * The time that this operation will complete. + * @param {google.protobuf.Duration} request.ttl + * The duration of this operation. + * @param {google.rpc.Status} request.error + * The error that will be returned by the server. If this code is specified + * to be the OK rpc code, an empty response will be returned. + * @param {google.showcase.v1beta1.WaitResponse} request.success + * The response to be returned on operation completion. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/echo.wait.js + * region_tag:localhost_v1beta1_generated_Echo_Wait_async + */ wait( - request?: protos.google.showcase.v1beta1.IWaitRequest, - options?: CallOptions): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IWaitRequest, + options?: CallOptions, + ): Promise< + [ + LROperation< + protos.google.showcase.v1beta1.IWaitResponse, + protos.google.showcase.v1beta1.IWaitMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; wait( - request: protos.google.showcase.v1beta1.IWaitRequest, - options: CallOptions, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IWaitRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.showcase.v1beta1.IWaitResponse, + protos.google.showcase.v1beta1.IWaitMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; wait( - request: protos.google.showcase.v1beta1.IWaitRequest, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IWaitRequest, + callback: Callback< + LROperation< + protos.google.showcase.v1beta1.IWaitResponse, + protos.google.showcase.v1beta1.IWaitMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; wait( - request?: protos.google.showcase.v1beta1.IWaitRequest, - optionsOrCallback?: CallOptions|Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>, - callback?: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>|void { + request?: protos.google.showcase.v1beta1.IWaitRequest, + optionsOrCallback?: + | CallOptions + | Callback< + LROperation< + protos.google.showcase.v1beta1.IWaitResponse, + protos.google.showcase.v1beta1.IWaitMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + callback?: Callback< + LROperation< + protos.google.showcase.v1beta1.IWaitResponse, + protos.google.showcase.v1beta1.IWaitMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + LROperation< + protos.google.showcase.v1beta1.IWaitResponse, + protos.google.showcase.v1beta1.IWaitMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize().catch(err => {throw err}); - const wrappedCallback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>|undefined = callback + this.initialize().catch((err) => { + throw err; + }); + const wrappedCallback: + | Callback< + LROperation< + protos.google.showcase.v1beta1.IWaitResponse, + protos.google.showcase.v1beta1.IWaitMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, rawResponse, _) => { this._log.info('wait response %j', rawResponse); callback!(error, response, rawResponse, _); // We verified `callback` above. } : undefined; this._log.info('wait request %j', request); - return this.innerApiCalls.wait(request, options, wrappedCallback) - ?.then(([response, rawResponse, _]: [ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]) => { - this._log.info('wait response %j', rawResponse); - return [response, rawResponse, _]; - }); + return this.innerApiCalls + .wait(request, options, wrappedCallback) + ?.then( + ([response, rawResponse, _]: [ + LROperation< + protos.google.showcase.v1beta1.IWaitResponse, + protos.google.showcase.v1beta1.IWaitMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ]) => { + this._log.info('wait response %j', rawResponse); + return [response, rawResponse, _]; + }, + ); } -/** - * Check the status of the long running operation returned by `wait()`. - * @param {String} name - * The operation name that will be passed. - * @returns {Promise} - The promise which resolves to an object. - * The decoded operation object has result and metadata field to get information from. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/echo.wait.js - * region_tag:localhost_v1beta1_generated_Echo_Wait_async - */ - async checkWaitProgress(name: string): Promise>{ + /** + * Check the status of the long running operation returned by `wait()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/echo.wait.js + * region_tag:localhost_v1beta1_generated_Echo_Wait_async + */ + async checkWaitProgress( + name: string, + ): Promise< + LROperation< + protos.google.showcase.v1beta1.WaitResponse, + protos.google.showcase.v1beta1.WaitMetadata + > + > { this._log.info('wait long-running'); - const request = new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest({name}); + const request = + new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( + { name }, + ); const [operation] = await this.operationsClient.getOperation(request); - const decodeOperation = new this._gaxModule.Operation(operation, this.descriptors.longrunning.wait, this._gaxModule.createDefaultBackoffSettings()); - return decodeOperation as LROperation; + const decodeOperation = new this._gaxModule.Operation( + operation, + this.descriptors.longrunning.wait, + this._gaxModule.createDefaultBackoffSettings(), + ); + return decodeOperation as LROperation< + protos.google.showcase.v1beta1.WaitResponse, + protos.google.showcase.v1beta1.WaitMetadata + >; } - /** - * This is similar to the Expand method but instead of returning a stream of - * expanded words, this method returns a paged list of expanded words. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.content - * The string to expand. - * @param {number} request.pageSize - * The number of words to returned in each page. - * @param {string} request.pageToken - * The position of the page to be returned. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.showcase.v1beta1.EchoResponse|EchoResponse}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `pagedExpandAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * This is similar to the Expand method but instead of returning a stream of + * expanded words, this method returns a paged list of expanded words. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.content + * The string to expand. + * @param {number} request.pageSize + * The number of words to returned in each page. + * @param {string} request.pageToken + * The position of the page to be returned. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.showcase.v1beta1.EchoResponse|EchoResponse}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `pagedExpandAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ pagedExpand( - request?: protos.google.showcase.v1beta1.IPagedExpandRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IEchoResponse[], - protos.google.showcase.v1beta1.IPagedExpandRequest|null, - protos.google.showcase.v1beta1.IPagedExpandResponse - ]>; + request?: protos.google.showcase.v1beta1.IPagedExpandRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IEchoResponse[], + protos.google.showcase.v1beta1.IPagedExpandRequest | null, + protos.google.showcase.v1beta1.IPagedExpandResponse, + ] + >; pagedExpand( - request: protos.google.showcase.v1beta1.IPagedExpandRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.showcase.v1beta1.IPagedExpandRequest, - protos.google.showcase.v1beta1.IPagedExpandResponse|null|undefined, - protos.google.showcase.v1beta1.IEchoResponse>): void; + request: protos.google.showcase.v1beta1.IPagedExpandRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.showcase.v1beta1.IPagedExpandRequest, + protos.google.showcase.v1beta1.IPagedExpandResponse | null | undefined, + protos.google.showcase.v1beta1.IEchoResponse + >, + ): void; pagedExpand( - request: protos.google.showcase.v1beta1.IPagedExpandRequest, - callback: PaginationCallback< - protos.google.showcase.v1beta1.IPagedExpandRequest, - protos.google.showcase.v1beta1.IPagedExpandResponse|null|undefined, - protos.google.showcase.v1beta1.IEchoResponse>): void; + request: protos.google.showcase.v1beta1.IPagedExpandRequest, + callback: PaginationCallback< + protos.google.showcase.v1beta1.IPagedExpandRequest, + protos.google.showcase.v1beta1.IPagedExpandResponse | null | undefined, + protos.google.showcase.v1beta1.IEchoResponse + >, + ): void; pagedExpand( - request?: protos.google.showcase.v1beta1.IPagedExpandRequest, - optionsOrCallback?: CallOptions|PaginationCallback< - protos.google.showcase.v1beta1.IPagedExpandRequest, - protos.google.showcase.v1beta1.IPagedExpandResponse|null|undefined, - protos.google.showcase.v1beta1.IEchoResponse>, - callback?: PaginationCallback< + request?: protos.google.showcase.v1beta1.IPagedExpandRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.showcase.v1beta1.IPagedExpandRequest, - protos.google.showcase.v1beta1.IPagedExpandResponse|null|undefined, - protos.google.showcase.v1beta1.IEchoResponse>): - Promise<[ - protos.google.showcase.v1beta1.IEchoResponse[], - protos.google.showcase.v1beta1.IPagedExpandRequest|null, - protos.google.showcase.v1beta1.IPagedExpandResponse - ]>|void { + | protos.google.showcase.v1beta1.IPagedExpandResponse + | null + | undefined, + protos.google.showcase.v1beta1.IEchoResponse + >, + callback?: PaginationCallback< + protos.google.showcase.v1beta1.IPagedExpandRequest, + protos.google.showcase.v1beta1.IPagedExpandResponse | null | undefined, + protos.google.showcase.v1beta1.IEchoResponse + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IEchoResponse[], + protos.google.showcase.v1beta1.IPagedExpandRequest | null, + protos.google.showcase.v1beta1.IPagedExpandResponse, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.showcase.v1beta1.IPagedExpandRequest, - protos.google.showcase.v1beta1.IPagedExpandResponse|null|undefined, - protos.google.showcase.v1beta1.IEchoResponse>|undefined = callback + this.initialize().catch((err) => { + throw err; + }); + const wrappedCallback: + | PaginationCallback< + protos.google.showcase.v1beta1.IPagedExpandRequest, + | protos.google.showcase.v1beta1.IPagedExpandResponse + | null + | undefined, + protos.google.showcase.v1beta1.IEchoResponse + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('pagedExpand values %j', values); callback!(error, values, nextPageRequest, rawResponse); @@ -1214,96 +1613,102 @@ export class EchoClient { this._log.info('pagedExpand request %j', request); return this.innerApiCalls .pagedExpand(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.showcase.v1beta1.IEchoResponse[], - protos.google.showcase.v1beta1.IPagedExpandRequest|null, - protos.google.showcase.v1beta1.IPagedExpandResponse - ]) => { - this._log.info('pagedExpand values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.showcase.v1beta1.IEchoResponse[], + protos.google.showcase.v1beta1.IPagedExpandRequest | null, + protos.google.showcase.v1beta1.IPagedExpandResponse, + ]) => { + this._log.info('pagedExpand values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `pagedExpand`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.content - * The string to expand. - * @param {number} request.pageSize - * The number of words to returned in each page. - * @param {string} request.pageToken - * The position of the page to be returned. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.showcase.v1beta1.EchoResponse|EchoResponse} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `pagedExpandAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `pagedExpand`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.content + * The string to expand. + * @param {number} request.pageSize + * The number of words to returned in each page. + * @param {string} request.pageToken + * The position of the page to be returned. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.showcase.v1beta1.EchoResponse|EchoResponse} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `pagedExpandAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ pagedExpandStream( - request?: protos.google.showcase.v1beta1.IPagedExpandRequest, - options?: CallOptions): - Transform{ + request?: protos.google.showcase.v1beta1.IPagedExpandRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; const defaultCallSettings = this._defaults['pagedExpand']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('pagedExpand stream %j', request); return this.descriptors.page.pagedExpand.createStream( this.innerApiCalls.pagedExpand as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `pagedExpand`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.content - * The string to expand. - * @param {number} request.pageSize - * The number of words to returned in each page. - * @param {string} request.pageToken - * The position of the page to be returned. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.showcase.v1beta1.EchoResponse|EchoResponse}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/echo.paged_expand.js - * region_tag:localhost_v1beta1_generated_Echo_PagedExpand_async - */ + /** + * Equivalent to `pagedExpand`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.content + * The string to expand. + * @param {number} request.pageSize + * The number of words to returned in each page. + * @param {string} request.pageToken + * The position of the page to be returned. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.showcase.v1beta1.EchoResponse|EchoResponse}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/echo.paged_expand.js + * region_tag:localhost_v1beta1_generated_Echo_PagedExpand_async + */ pagedExpandAsync( - request?: protos.google.showcase.v1beta1.IPagedExpandRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.showcase.v1beta1.IPagedExpandRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; const defaultCallSettings = this._defaults['pagedExpand']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('pagedExpand iterate %j', request); return this.descriptors.page.pagedExpand.asyncIterate( this.innerApiCalls['pagedExpand'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } // -------------------- @@ -1318,7 +1723,7 @@ export class EchoClient { * @param {string} blueprint * @returns {string} Resource name string. */ - blueprintPath(session:string,test:string,blueprint:string) { + blueprintPath(session: string, test: string, blueprint: string) { return this.pathTemplates.blueprintPathTemplate.render({ session: session, test: test, @@ -1334,7 +1739,8 @@ export class EchoClient { * @returns {string} A string representing the session. */ matchSessionFromBlueprintName(blueprintName: string) { - return this.pathTemplates.blueprintPathTemplate.match(blueprintName).session; + return this.pathTemplates.blueprintPathTemplate.match(blueprintName) + .session; } /** @@ -1356,7 +1762,8 @@ export class EchoClient { * @returns {string} A string representing the blueprint. */ matchBlueprintFromBlueprintName(blueprintName: string) { - return this.pathTemplates.blueprintPathTemplate.match(blueprintName).blueprint; + return this.pathTemplates.blueprintPathTemplate.match(blueprintName) + .blueprint; } /** @@ -1365,7 +1772,7 @@ export class EchoClient { * @param {string} room * @returns {string} Resource name string. */ - roomPath(room:string) { + roomPath(room: string) { return this.pathTemplates.roomPathTemplate.render({ room: room, }); @@ -1389,7 +1796,7 @@ export class EchoClient { * @param {string} blurb * @returns {string} Resource name string. */ - roomBlurbPath(room:string,blurb:string) { + roomBlurbPath(room: string, blurb: string) { return this.pathTemplates.roomBlurbPathTemplate.render({ room: room, blurb: blurb, @@ -1426,7 +1833,11 @@ export class EchoClient { * @param {string} blurb * @returns {string} Resource name string. */ - roomBlurbsLegacyRoomBlurbPath(room:string,legacyRoom:string,blurb:string) { + roomBlurbsLegacyRoomBlurbPath( + room: string, + legacyRoom: string, + blurb: string, + ) { return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.render({ room: room, legacy_room: legacyRoom, @@ -1441,8 +1852,12 @@ export class EchoClient { * A fully-qualified path representing room_blurbs_legacy_room_blurb resource. * @returns {string} A string representing the room. */ - matchRoomFromRoomBlurbsLegacyRoomBlurbName(roomBlurbsLegacyRoomBlurbName: string) { - return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match(roomBlurbsLegacyRoomBlurbName).room; + matchRoomFromRoomBlurbsLegacyRoomBlurbName( + roomBlurbsLegacyRoomBlurbName: string, + ) { + return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match( + roomBlurbsLegacyRoomBlurbName, + ).room; } /** @@ -1452,8 +1867,12 @@ export class EchoClient { * A fully-qualified path representing room_blurbs_legacy_room_blurb resource. * @returns {string} A string representing the legacy_room. */ - matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName(roomBlurbsLegacyRoomBlurbName: string) { - return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match(roomBlurbsLegacyRoomBlurbName).legacy_room; + matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName( + roomBlurbsLegacyRoomBlurbName: string, + ) { + return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match( + roomBlurbsLegacyRoomBlurbName, + ).legacy_room; } /** @@ -1463,8 +1882,12 @@ export class EchoClient { * A fully-qualified path representing room_blurbs_legacy_room_blurb resource. * @returns {string} A string representing the blurb. */ - matchBlurbFromRoomBlurbsLegacyRoomBlurbName(roomBlurbsLegacyRoomBlurbName: string) { - return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match(roomBlurbsLegacyRoomBlurbName).blurb; + matchBlurbFromRoomBlurbsLegacyRoomBlurbName( + roomBlurbsLegacyRoomBlurbName: string, + ) { + return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match( + roomBlurbsLegacyRoomBlurbName, + ).blurb; } /** @@ -1473,7 +1896,7 @@ export class EchoClient { * @param {string} sequence * @returns {string} Resource name string. */ - sequencePath(sequence:string) { + sequencePath(sequence: string) { return this.pathTemplates.sequencePathTemplate.render({ sequence: sequence, }); @@ -1496,7 +1919,7 @@ export class EchoClient { * @param {string} sequence * @returns {string} Resource name string. */ - sequenceReportPath(sequence:string) { + sequenceReportPath(sequence: string) { return this.pathTemplates.sequenceReportPathTemplate.render({ sequence: sequence, }); @@ -1510,7 +1933,9 @@ export class EchoClient { * @returns {string} A string representing the sequence. */ matchSequenceFromSequenceReportName(sequenceReportName: string) { - return this.pathTemplates.sequenceReportPathTemplate.match(sequenceReportName).sequence; + return this.pathTemplates.sequenceReportPathTemplate.match( + sequenceReportName, + ).sequence; } /** @@ -1519,7 +1944,7 @@ export class EchoClient { * @param {string} session * @returns {string} Resource name string. */ - sessionPath(session:string) { + sessionPath(session: string) { return this.pathTemplates.sessionPathTemplate.render({ session: session, }); @@ -1543,7 +1968,7 @@ export class EchoClient { * @param {string} test * @returns {string} Resource name string. */ - testPath(session:string,test:string) { + testPath(session: string, test: string) { return this.pathTemplates.testPathTemplate.render({ session: session, test: test, @@ -1578,7 +2003,7 @@ export class EchoClient { * @param {string} user * @returns {string} Resource name string. */ - userPath(user:string) { + userPath(user: string) { return this.pathTemplates.userPathTemplate.render({ user: user, }); @@ -1602,7 +2027,7 @@ export class EchoClient { * @param {string} blurb * @returns {string} Resource name string. */ - userProfileBlurbPath(user:string,blurb:string) { + userProfileBlurbPath(user: string, blurb: string) { return this.pathTemplates.userProfileBlurbPathTemplate.render({ user: user, blurb: blurb, @@ -1617,7 +2042,9 @@ export class EchoClient { * @returns {string} A string representing the user. */ matchUserFromUserProfileBlurbName(userProfileBlurbName: string) { - return this.pathTemplates.userProfileBlurbPathTemplate.match(userProfileBlurbName).user; + return this.pathTemplates.userProfileBlurbPathTemplate.match( + userProfileBlurbName, + ).user; } /** @@ -1628,7 +2055,9 @@ export class EchoClient { * @returns {string} A string representing the blurb. */ matchBlurbFromUserProfileBlurbName(userProfileBlurbName: string) { - return this.pathTemplates.userProfileBlurbPathTemplate.match(userProfileBlurbName).blurb; + return this.pathTemplates.userProfileBlurbPathTemplate.match( + userProfileBlurbName, + ).blurb; } /** @@ -1639,12 +2068,18 @@ export class EchoClient { * @param {string} blurb * @returns {string} Resource name string. */ - userProfileBlurbsLegacyUserBlurbPath(user:string,legacyUser:string,blurb:string) { - return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.render({ - user: user, - legacy_user: legacyUser, - blurb: blurb, - }); + userProfileBlurbsLegacyUserBlurbPath( + user: string, + legacyUser: string, + blurb: string, + ) { + return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.render( + { + user: user, + legacy_user: legacyUser, + blurb: blurb, + }, + ); } /** @@ -1654,8 +2089,12 @@ export class EchoClient { * A fully-qualified path representing user_profile_blurbs_legacy_user_blurb resource. * @returns {string} A string representing the user. */ - matchUserFromUserProfileBlurbsLegacyUserBlurbName(userProfileBlurbsLegacyUserBlurbName: string) { - return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match(userProfileBlurbsLegacyUserBlurbName).user; + matchUserFromUserProfileBlurbsLegacyUserBlurbName( + userProfileBlurbsLegacyUserBlurbName: string, + ) { + return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match( + userProfileBlurbsLegacyUserBlurbName, + ).user; } /** @@ -1665,8 +2104,12 @@ export class EchoClient { * A fully-qualified path representing user_profile_blurbs_legacy_user_blurb resource. * @returns {string} A string representing the legacy_user. */ - matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName(userProfileBlurbsLegacyUserBlurbName: string) { - return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match(userProfileBlurbsLegacyUserBlurbName).legacy_user; + matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName( + userProfileBlurbsLegacyUserBlurbName: string, + ) { + return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match( + userProfileBlurbsLegacyUserBlurbName, + ).legacy_user; } /** @@ -1676,8 +2119,12 @@ export class EchoClient { * A fully-qualified path representing user_profile_blurbs_legacy_user_blurb resource. * @returns {string} A string representing the blurb. */ - matchBlurbFromUserProfileBlurbsLegacyUserBlurbName(userProfileBlurbsLegacyUserBlurbName: string) { - return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match(userProfileBlurbsLegacyUserBlurbName).blurb; + matchBlurbFromUserProfileBlurbsLegacyUserBlurbName( + userProfileBlurbsLegacyUserBlurbName: string, + ) { + return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match( + userProfileBlurbsLegacyUserBlurbName, + ).blurb; } /** @@ -1688,7 +2135,7 @@ export class EchoClient { */ close(): Promise { if (this.echoStub && !this._terminated) { - return this.echoStub.then(stub => { + return this.echoStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -1697,4 +2144,4 @@ export class EchoClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/core/generator/gapic-generator-typescript/baselines/showcase-esm/esm/src/v1beta1/identity_client.ts.baseline b/core/generator/gapic-generator-typescript/baselines/showcase-esm/esm/src/v1beta1/identity_client.ts.baseline index 8dfc40a7ac0d..40f3d1b5fb30 100644 --- a/core/generator/gapic-generator-typescript/baselines/showcase-esm/esm/src/v1beta1/identity_client.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/showcase-esm/esm/src/v1beta1/identity_client.ts.baseline @@ -18,15 +18,22 @@ /* global window */ import * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions, PaginationCallback, GaxCall} from 'google-gax'; -import {Transform} from 'stream'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + PaginationCallback, + GaxCall, +} from 'google-gax'; +import { Transform } from 'stream'; // @ts-ignore import type * as protos from '../../../protos/protos.js'; import * as identity_client_config from './identity_client_config.json'; import fs from 'fs'; import path from 'path'; -import {fileURLToPath} from 'url'; -import {getJSON} from '../json-helper.cjs'; +import { fileURLToPath } from 'url'; +import { getJSON } from '../json-helper.cjs'; // @ts-ignore const dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -35,16 +42,14 @@ const dirname = path.dirname(fileURLToPath(import.meta.url)); * `src/v1beta1/identity_client_config.json`. * This file defines retry strategy and timeouts for all API methods in this library. */ -const gapicConfig = getJSON( - path.join(dirname, 'identity_client_config.json') -); +const gapicConfig = getJSON(path.join(dirname, 'identity_client_config.json')); const jsonProtos = getJSON( - path.join(dirname, '..', '..', '..', 'protos/protos.json') + path.join(dirname, '..', '..', '..', 'protos/protos.json'), ); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; const version = getJSON( - path.join(dirname, '..', '..', '..', '..', 'package.json') + path.join(dirname, '..', '..', '..', '..', 'package.json'), ).version; /** @@ -59,7 +64,7 @@ export class IdentityClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('showcase'); @@ -71,9 +76,9 @@ export class IdentityClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; - identityStub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; + identityStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of IdentityClient. @@ -115,21 +120,42 @@ export class IdentityClient { * const client = new IdentityClient({fallback: 'rest'}, gax); * ``` */ - constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { // Ensure that options include all the required fields. const staticMembers = this.constructor as typeof IdentityClient; - if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { - throw new Error('Please set either universe_domain or universeDomain, but not both.'); + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); } - const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; - this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; this._servicePath = 'localhost'; - const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; - const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // Request numeric enum values if REST transport is used. opts.numericEnums = true; @@ -154,7 +180,7 @@ export class IdentityClient { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; @@ -171,10 +197,7 @@ export class IdentityClient { const isEsm = true; const isEsmString = isEsm ? '-esm' : '-cjs'; // Determine the client header string. - const clientHeader = [ - `gax/${this._gaxModule.version}`, - `gapic/${version}`, - ]; + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/{process.versions.node}${isEsmString}`); } else { @@ -182,7 +205,7 @@ export class IdentityClient { } if (!opts.fallback) { clientHeader.push(`grpc/${this._gaxGrpc.grpcVersion}`); - } else if (opts.fallback === 'rest' ) { + } else if (opts.fallback === 'rest') { clientHeader.push(`rest/${this._gaxGrpc.grpcVersion}`); } if (opts.libName && opts.libVersion) { @@ -190,59 +213,64 @@ export class IdentityClient { } // Load the applicable protos. - this._protos = this._gaxGrpc.loadProtoJSON(jsonProtos as gax.protobuf.INamespace); + this._protos = this._gaxGrpc.loadProtoJSON( + jsonProtos as gax.protobuf.INamespace, + ); // This API contains "path templates"; forward-slash-separated // identifiers to uniquely identify resources within the API. // Create useful helper objects for these. this.pathTemplates = { blueprintPathTemplate: new this._gaxModule.PathTemplate( - 'sessions/{session}/tests/{test}/blueprints/{blueprint}' - ), - roomPathTemplate: new this._gaxModule.PathTemplate( - 'rooms/{room}' + 'sessions/{session}/tests/{test}/blueprints/{blueprint}', ), + roomPathTemplate: new this._gaxModule.PathTemplate('rooms/{room}'), roomBlurbPathTemplate: new this._gaxModule.PathTemplate( - 'rooms/{room}/blurbs/{blurb}' + 'rooms/{room}/blurbs/{blurb}', ), roomBlurbsLegacyRoomBlurbPathTemplate: new this._gaxModule.PathTemplate( - 'rooms/{room}/blurbs/legacy/{legacy_room}.{blurb}' + 'rooms/{room}/blurbs/legacy/{legacy_room}.{blurb}', ), sequencePathTemplate: new this._gaxModule.PathTemplate( - 'sequences/{sequence}' + 'sequences/{sequence}', ), sequenceReportPathTemplate: new this._gaxModule.PathTemplate( - 'sequences/{sequence}/sequenceReport' + 'sequences/{sequence}/sequenceReport', ), sessionPathTemplate: new this._gaxModule.PathTemplate( - 'sessions/{session}' + 'sessions/{session}', ), testPathTemplate: new this._gaxModule.PathTemplate( - 'sessions/{session}/tests/{test}' - ), - userPathTemplate: new this._gaxModule.PathTemplate( - 'users/{user}' + 'sessions/{session}/tests/{test}', ), + userPathTemplate: new this._gaxModule.PathTemplate('users/{user}'), userProfileBlurbPathTemplate: new this._gaxModule.PathTemplate( - 'users/{user}/profile/blurbs/{blurb}' - ), - userProfileBlurbsLegacyUserBlurbPathTemplate: new this._gaxModule.PathTemplate( - 'users/{user}/profile/blurbs/legacy/{legacy_user}~{blurb}' + 'users/{user}/profile/blurbs/{blurb}', ), + userProfileBlurbsLegacyUserBlurbPathTemplate: + new this._gaxModule.PathTemplate( + 'users/{user}/profile/blurbs/legacy/{legacy_user}~{blurb}', + ), }; // Some of the methods on this service return "paged" results, // (e.g. 50 results at a time, with tokens to get subsequent // pages). Denote the keys used for pagination and results. this.descriptors.page = { - listUsers: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'users') + listUsers: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'users', + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.showcase.v1beta1.Identity', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.showcase.v1beta1.Identity', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + { 'x-goog-api-client': clientHeader.join(' ') }, + ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -273,37 +301,46 @@ export class IdentityClient { // Put together the "service stub" for // google.showcase.v1beta1.Identity. this.identityStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.showcase.v1beta1.Identity') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.showcase.v1beta1.Identity', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.showcase.v1beta1.Identity, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts, + this._providedCustomServicePath, + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const identityStubMethods = - ['createUser', 'getUser', 'updateUser', 'deleteUser', 'listUsers']; + const identityStubMethods = [ + 'createUser', + 'getUser', + 'updateUser', + 'deleteUser', + 'listUsers', + ]; for (const methodName of identityStubMethods) { const callPromise = this.identityStub.then( - stub => (...args: Array<{}>) => { - if (this._terminated) { - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error|null|undefined) => () => { + (stub) => + (...args: Array<{}>) => { + if (this._terminated) { + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { throw err; - }); + }, + ); - const descriptor = - this.descriptors.page[methodName] || - undefined; + const descriptor = this.descriptors.page[methodName] || undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -318,8 +355,14 @@ export class IdentityClient { * @returns {string} The DNS address for this service. */ static get servicePath() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'localhost'; } @@ -331,8 +374,14 @@ export class IdentityClient { * @returns {string} The DNS address for this service. */ static get apiEndpoint() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'localhost'; } @@ -372,8 +421,9 @@ export class IdentityClient { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId(callback?: Callback): - Promise|void { + getProjectId( + callback?: Callback, + ): Promise | void { if (callback) { this.auth.getProjectId(callback); return; @@ -384,454 +434,595 @@ export class IdentityClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Creates a user. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.showcase.v1beta1.User} request.user - * The user to create. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.User|User}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/identity.create_user.js - * region_tag:localhost_v1beta1_generated_Identity_CreateUser_async - */ + /** + * Creates a user. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.showcase.v1beta1.User} request.user + * The user to create. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.User|User}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/identity.create_user.js + * region_tag:localhost_v1beta1_generated_Identity_CreateUser_async + */ createUser( - request?: protos.google.showcase.v1beta1.ICreateUserRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IUser, - protos.google.showcase.v1beta1.ICreateUserRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.ICreateUserRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IUser, + protos.google.showcase.v1beta1.ICreateUserRequest | undefined, + {} | undefined, + ] + >; createUser( - request: protos.google.showcase.v1beta1.ICreateUserRequest, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.IUser, - protos.google.showcase.v1beta1.ICreateUserRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.ICreateUserRequest, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.IUser, + protos.google.showcase.v1beta1.ICreateUserRequest | null | undefined, + {} | null | undefined + >, + ): void; createUser( - request: protos.google.showcase.v1beta1.ICreateUserRequest, - callback: Callback< - protos.google.showcase.v1beta1.IUser, - protos.google.showcase.v1beta1.ICreateUserRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.ICreateUserRequest, + callback: Callback< + protos.google.showcase.v1beta1.IUser, + protos.google.showcase.v1beta1.ICreateUserRequest | null | undefined, + {} | null | undefined + >, + ): void; createUser( - request?: protos.google.showcase.v1beta1.ICreateUserRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.showcase.v1beta1.IUser, - protos.google.showcase.v1beta1.ICreateUserRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.showcase.v1beta1.ICreateUserRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.IUser, - protos.google.showcase.v1beta1.ICreateUserRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.IUser, - protos.google.showcase.v1beta1.ICreateUserRequest|undefined, {}|undefined - ]>|void { + protos.google.showcase.v1beta1.ICreateUserRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.IUser, + protos.google.showcase.v1beta1.ICreateUserRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IUser, + protos.google.showcase.v1beta1.ICreateUserRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('createUser request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.IUser, - protos.google.showcase.v1beta1.ICreateUserRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.IUser, + protos.google.showcase.v1beta1.ICreateUserRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createUser response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.createUser(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.IUser, - protos.google.showcase.v1beta1.ICreateUserRequest|undefined, {}|undefined - ]) => { - this._log.info('createUser response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createUser(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.IUser, + protos.google.showcase.v1beta1.ICreateUserRequest | undefined, + {} | undefined, + ]) => { + this._log.info('createUser response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Retrieves the User with the given uri. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * The resource name of the requested user. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.User|User}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/identity.get_user.js - * region_tag:localhost_v1beta1_generated_Identity_GetUser_async - */ + /** + * Retrieves the User with the given uri. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * The resource name of the requested user. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.User|User}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/identity.get_user.js + * region_tag:localhost_v1beta1_generated_Identity_GetUser_async + */ getUser( - request?: protos.google.showcase.v1beta1.IGetUserRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IUser, - protos.google.showcase.v1beta1.IGetUserRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IGetUserRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IUser, + protos.google.showcase.v1beta1.IGetUserRequest | undefined, + {} | undefined, + ] + >; getUser( - request: protos.google.showcase.v1beta1.IGetUserRequest, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.IUser, - protos.google.showcase.v1beta1.IGetUserRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IGetUserRequest, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.IUser, + protos.google.showcase.v1beta1.IGetUserRequest | null | undefined, + {} | null | undefined + >, + ): void; getUser( - request: protos.google.showcase.v1beta1.IGetUserRequest, - callback: Callback< - protos.google.showcase.v1beta1.IUser, - protos.google.showcase.v1beta1.IGetUserRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IGetUserRequest, + callback: Callback< + protos.google.showcase.v1beta1.IUser, + protos.google.showcase.v1beta1.IGetUserRequest | null | undefined, + {} | null | undefined + >, + ): void; getUser( - request?: protos.google.showcase.v1beta1.IGetUserRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.showcase.v1beta1.IUser, - protos.google.showcase.v1beta1.IGetUserRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.showcase.v1beta1.IGetUserRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.IUser, - protos.google.showcase.v1beta1.IGetUserRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.IUser, - protos.google.showcase.v1beta1.IGetUserRequest|undefined, {}|undefined - ]>|void { + protos.google.showcase.v1beta1.IGetUserRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.IUser, + protos.google.showcase.v1beta1.IGetUserRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IUser, + protos.google.showcase.v1beta1.IGetUserRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getUser request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.IUser, - protos.google.showcase.v1beta1.IGetUserRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.IUser, + protos.google.showcase.v1beta1.IGetUserRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getUser response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.getUser(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.IUser, - protos.google.showcase.v1beta1.IGetUserRequest|undefined, {}|undefined - ]) => { - this._log.info('getUser response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getUser(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.IUser, + protos.google.showcase.v1beta1.IGetUserRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getUser response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Updates a user. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.showcase.v1beta1.User} request.user - * The user to update. - * @param {google.protobuf.FieldMask} request.updateMask - * The field mask to determine which fields are to be updated. If empty, the - * server will assume all fields are to be updated. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.User|User}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/identity.update_user.js - * region_tag:localhost_v1beta1_generated_Identity_UpdateUser_async - */ + /** + * Updates a user. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.showcase.v1beta1.User} request.user + * The user to update. + * @param {google.protobuf.FieldMask} request.updateMask + * The field mask to determine which fields are to be updated. If empty, the + * server will assume all fields are to be updated. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.User|User}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/identity.update_user.js + * region_tag:localhost_v1beta1_generated_Identity_UpdateUser_async + */ updateUser( - request?: protos.google.showcase.v1beta1.IUpdateUserRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IUser, - protos.google.showcase.v1beta1.IUpdateUserRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IUpdateUserRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IUser, + protos.google.showcase.v1beta1.IUpdateUserRequest | undefined, + {} | undefined, + ] + >; updateUser( - request: protos.google.showcase.v1beta1.IUpdateUserRequest, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.IUser, - protos.google.showcase.v1beta1.IUpdateUserRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IUpdateUserRequest, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.IUser, + protos.google.showcase.v1beta1.IUpdateUserRequest | null | undefined, + {} | null | undefined + >, + ): void; updateUser( - request: protos.google.showcase.v1beta1.IUpdateUserRequest, - callback: Callback< - protos.google.showcase.v1beta1.IUser, - protos.google.showcase.v1beta1.IUpdateUserRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IUpdateUserRequest, + callback: Callback< + protos.google.showcase.v1beta1.IUser, + protos.google.showcase.v1beta1.IUpdateUserRequest | null | undefined, + {} | null | undefined + >, + ): void; updateUser( - request?: protos.google.showcase.v1beta1.IUpdateUserRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.showcase.v1beta1.IUser, - protos.google.showcase.v1beta1.IUpdateUserRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.showcase.v1beta1.IUpdateUserRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.IUser, - protos.google.showcase.v1beta1.IUpdateUserRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.IUser, - protos.google.showcase.v1beta1.IUpdateUserRequest|undefined, {}|undefined - ]>|void { + protos.google.showcase.v1beta1.IUpdateUserRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.IUser, + protos.google.showcase.v1beta1.IUpdateUserRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IUser, + protos.google.showcase.v1beta1.IUpdateUserRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'user.name': request.user!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'user.name': request.user!.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateUser request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.IUser, - protos.google.showcase.v1beta1.IUpdateUserRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.IUser, + protos.google.showcase.v1beta1.IUpdateUserRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateUser response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.updateUser(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.IUser, - protos.google.showcase.v1beta1.IUpdateUserRequest|undefined, {}|undefined - ]) => { - this._log.info('updateUser response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateUser(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.IUser, + protos.google.showcase.v1beta1.IUpdateUserRequest | undefined, + {} | undefined, + ]) => { + this._log.info('updateUser response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Deletes a user, their profile, and all of their authored messages. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * The resource name of the user to delete. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/identity.delete_user.js - * region_tag:localhost_v1beta1_generated_Identity_DeleteUser_async - */ + /** + * Deletes a user, their profile, and all of their authored messages. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * The resource name of the user to delete. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/identity.delete_user.js + * region_tag:localhost_v1beta1_generated_Identity_DeleteUser_async + */ deleteUser( - request?: protos.google.showcase.v1beta1.IDeleteUserRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteUserRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IDeleteUserRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteUserRequest | undefined, + {} | undefined, + ] + >; deleteUser( - request: protos.google.showcase.v1beta1.IDeleteUserRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteUserRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IDeleteUserRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteUserRequest | null | undefined, + {} | null | undefined + >, + ): void; deleteUser( - request: protos.google.showcase.v1beta1.IDeleteUserRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteUserRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IDeleteUserRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteUserRequest | null | undefined, + {} | null | undefined + >, + ): void; deleteUser( - request?: protos.google.showcase.v1beta1.IDeleteUserRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.showcase.v1beta1.IDeleteUserRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteUserRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteUserRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteUserRequest|undefined, {}|undefined - ]>|void { + protos.google.showcase.v1beta1.IDeleteUserRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteUserRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteUserRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('deleteUser request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteUserRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteUserRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteUser response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.deleteUser(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteUserRequest|undefined, {}|undefined - ]) => { - this._log.info('deleteUser response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteUser(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteUserRequest | undefined, + {} | undefined, + ]) => { + this._log.info('deleteUser response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } - /** - * Lists all users. - * - * @param {Object} request - * The request object that will be sent. - * @param {number} request.pageSize - * The maximum number of users to return. Server may return fewer users - * than requested. If unspecified, server will pick an appropriate default. - * @param {string} request.pageToken - * The value of google.showcase.v1beta1.ListUsersResponse.next_page_token - * returned from the previous call to - * `google.showcase.v1beta1.Identity\ListUsers` method. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.showcase.v1beta1.User|User}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `listUsersAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Lists all users. + * + * @param {Object} request + * The request object that will be sent. + * @param {number} request.pageSize + * The maximum number of users to return. Server may return fewer users + * than requested. If unspecified, server will pick an appropriate default. + * @param {string} request.pageToken + * The value of google.showcase.v1beta1.ListUsersResponse.next_page_token + * returned from the previous call to + * `google.showcase.v1beta1.Identity\ListUsers` method. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.showcase.v1beta1.User|User}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listUsersAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listUsers( - request?: protos.google.showcase.v1beta1.IListUsersRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IUser[], - protos.google.showcase.v1beta1.IListUsersRequest|null, - protos.google.showcase.v1beta1.IListUsersResponse - ]>; + request?: protos.google.showcase.v1beta1.IListUsersRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IUser[], + protos.google.showcase.v1beta1.IListUsersRequest | null, + protos.google.showcase.v1beta1.IListUsersResponse, + ] + >; listUsers( - request: protos.google.showcase.v1beta1.IListUsersRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.showcase.v1beta1.IListUsersRequest, - protos.google.showcase.v1beta1.IListUsersResponse|null|undefined, - protos.google.showcase.v1beta1.IUser>): void; + request: protos.google.showcase.v1beta1.IListUsersRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.showcase.v1beta1.IListUsersRequest, + protos.google.showcase.v1beta1.IListUsersResponse | null | undefined, + protos.google.showcase.v1beta1.IUser + >, + ): void; listUsers( - request: protos.google.showcase.v1beta1.IListUsersRequest, - callback: PaginationCallback< - protos.google.showcase.v1beta1.IListUsersRequest, - protos.google.showcase.v1beta1.IListUsersResponse|null|undefined, - protos.google.showcase.v1beta1.IUser>): void; + request: protos.google.showcase.v1beta1.IListUsersRequest, + callback: PaginationCallback< + protos.google.showcase.v1beta1.IListUsersRequest, + protos.google.showcase.v1beta1.IListUsersResponse | null | undefined, + protos.google.showcase.v1beta1.IUser + >, + ): void; listUsers( - request?: protos.google.showcase.v1beta1.IListUsersRequest, - optionsOrCallback?: CallOptions|PaginationCallback< - protos.google.showcase.v1beta1.IListUsersRequest, - protos.google.showcase.v1beta1.IListUsersResponse|null|undefined, - protos.google.showcase.v1beta1.IUser>, - callback?: PaginationCallback< + request?: protos.google.showcase.v1beta1.IListUsersRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.showcase.v1beta1.IListUsersRequest, - protos.google.showcase.v1beta1.IListUsersResponse|null|undefined, - protos.google.showcase.v1beta1.IUser>): - Promise<[ - protos.google.showcase.v1beta1.IUser[], - protos.google.showcase.v1beta1.IListUsersRequest|null, - protos.google.showcase.v1beta1.IListUsersResponse - ]>|void { + protos.google.showcase.v1beta1.IListUsersResponse | null | undefined, + protos.google.showcase.v1beta1.IUser + >, + callback?: PaginationCallback< + protos.google.showcase.v1beta1.IListUsersRequest, + protos.google.showcase.v1beta1.IListUsersResponse | null | undefined, + protos.google.showcase.v1beta1.IUser + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IUser[], + protos.google.showcase.v1beta1.IListUsersRequest | null, + protos.google.showcase.v1beta1.IListUsersResponse, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.showcase.v1beta1.IListUsersRequest, - protos.google.showcase.v1beta1.IListUsersResponse|null|undefined, - protos.google.showcase.v1beta1.IUser>|undefined = callback + this.initialize().catch((err) => { + throw err; + }); + const wrappedCallback: + | PaginationCallback< + protos.google.showcase.v1beta1.IListUsersRequest, + protos.google.showcase.v1beta1.IListUsersResponse | null | undefined, + protos.google.showcase.v1beta1.IUser + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listUsers values %j', values); callback!(error, values, nextPageRequest, rawResponse); @@ -840,98 +1031,104 @@ export class IdentityClient { this._log.info('listUsers request %j', request); return this.innerApiCalls .listUsers(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.showcase.v1beta1.IUser[], - protos.google.showcase.v1beta1.IListUsersRequest|null, - protos.google.showcase.v1beta1.IListUsersResponse - ]) => { - this._log.info('listUsers values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.showcase.v1beta1.IUser[], + protos.google.showcase.v1beta1.IListUsersRequest | null, + protos.google.showcase.v1beta1.IListUsersResponse, + ]) => { + this._log.info('listUsers values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listUsers`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {number} request.pageSize - * The maximum number of users to return. Server may return fewer users - * than requested. If unspecified, server will pick an appropriate default. - * @param {string} request.pageToken - * The value of google.showcase.v1beta1.ListUsersResponse.next_page_token - * returned from the previous call to - * `google.showcase.v1beta1.Identity\ListUsers` method. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.showcase.v1beta1.User|User} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `listUsersAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `listUsers`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {number} request.pageSize + * The maximum number of users to return. Server may return fewer users + * than requested. If unspecified, server will pick an appropriate default. + * @param {string} request.pageToken + * The value of google.showcase.v1beta1.ListUsersResponse.next_page_token + * returned from the previous call to + * `google.showcase.v1beta1.Identity\ListUsers` method. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.showcase.v1beta1.User|User} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listUsersAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listUsersStream( - request?: protos.google.showcase.v1beta1.IListUsersRequest, - options?: CallOptions): - Transform{ + request?: protos.google.showcase.v1beta1.IListUsersRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; const defaultCallSettings = this._defaults['listUsers']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listUsers stream %j', request); return this.descriptors.page.listUsers.createStream( this.innerApiCalls.listUsers as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listUsers`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {number} request.pageSize - * The maximum number of users to return. Server may return fewer users - * than requested. If unspecified, server will pick an appropriate default. - * @param {string} request.pageToken - * The value of google.showcase.v1beta1.ListUsersResponse.next_page_token - * returned from the previous call to - * `google.showcase.v1beta1.Identity\ListUsers` method. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.showcase.v1beta1.User|User}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/identity.list_users.js - * region_tag:localhost_v1beta1_generated_Identity_ListUsers_async - */ + /** + * Equivalent to `listUsers`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {number} request.pageSize + * The maximum number of users to return. Server may return fewer users + * than requested. If unspecified, server will pick an appropriate default. + * @param {string} request.pageToken + * The value of google.showcase.v1beta1.ListUsersResponse.next_page_token + * returned from the previous call to + * `google.showcase.v1beta1.Identity\ListUsers` method. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.showcase.v1beta1.User|User}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/identity.list_users.js + * region_tag:localhost_v1beta1_generated_Identity_ListUsers_async + */ listUsersAsync( - request?: protos.google.showcase.v1beta1.IListUsersRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.showcase.v1beta1.IListUsersRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; const defaultCallSettings = this._defaults['listUsers']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listUsers iterate %j', request); return this.descriptors.page.listUsers.asyncIterate( this.innerApiCalls['listUsers'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } // -------------------- @@ -946,7 +1143,7 @@ export class IdentityClient { * @param {string} blueprint * @returns {string} Resource name string. */ - blueprintPath(session:string,test:string,blueprint:string) { + blueprintPath(session: string, test: string, blueprint: string) { return this.pathTemplates.blueprintPathTemplate.render({ session: session, test: test, @@ -962,7 +1159,8 @@ export class IdentityClient { * @returns {string} A string representing the session. */ matchSessionFromBlueprintName(blueprintName: string) { - return this.pathTemplates.blueprintPathTemplate.match(blueprintName).session; + return this.pathTemplates.blueprintPathTemplate.match(blueprintName) + .session; } /** @@ -984,7 +1182,8 @@ export class IdentityClient { * @returns {string} A string representing the blueprint. */ matchBlueprintFromBlueprintName(blueprintName: string) { - return this.pathTemplates.blueprintPathTemplate.match(blueprintName).blueprint; + return this.pathTemplates.blueprintPathTemplate.match(blueprintName) + .blueprint; } /** @@ -993,7 +1192,7 @@ export class IdentityClient { * @param {string} room * @returns {string} Resource name string. */ - roomPath(room:string) { + roomPath(room: string) { return this.pathTemplates.roomPathTemplate.render({ room: room, }); @@ -1017,7 +1216,7 @@ export class IdentityClient { * @param {string} blurb * @returns {string} Resource name string. */ - roomBlurbPath(room:string,blurb:string) { + roomBlurbPath(room: string, blurb: string) { return this.pathTemplates.roomBlurbPathTemplate.render({ room: room, blurb: blurb, @@ -1054,7 +1253,11 @@ export class IdentityClient { * @param {string} blurb * @returns {string} Resource name string. */ - roomBlurbsLegacyRoomBlurbPath(room:string,legacyRoom:string,blurb:string) { + roomBlurbsLegacyRoomBlurbPath( + room: string, + legacyRoom: string, + blurb: string, + ) { return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.render({ room: room, legacy_room: legacyRoom, @@ -1069,8 +1272,12 @@ export class IdentityClient { * A fully-qualified path representing room_blurbs_legacy_room_blurb resource. * @returns {string} A string representing the room. */ - matchRoomFromRoomBlurbsLegacyRoomBlurbName(roomBlurbsLegacyRoomBlurbName: string) { - return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match(roomBlurbsLegacyRoomBlurbName).room; + matchRoomFromRoomBlurbsLegacyRoomBlurbName( + roomBlurbsLegacyRoomBlurbName: string, + ) { + return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match( + roomBlurbsLegacyRoomBlurbName, + ).room; } /** @@ -1080,8 +1287,12 @@ export class IdentityClient { * A fully-qualified path representing room_blurbs_legacy_room_blurb resource. * @returns {string} A string representing the legacy_room. */ - matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName(roomBlurbsLegacyRoomBlurbName: string) { - return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match(roomBlurbsLegacyRoomBlurbName).legacy_room; + matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName( + roomBlurbsLegacyRoomBlurbName: string, + ) { + return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match( + roomBlurbsLegacyRoomBlurbName, + ).legacy_room; } /** @@ -1091,8 +1302,12 @@ export class IdentityClient { * A fully-qualified path representing room_blurbs_legacy_room_blurb resource. * @returns {string} A string representing the blurb. */ - matchBlurbFromRoomBlurbsLegacyRoomBlurbName(roomBlurbsLegacyRoomBlurbName: string) { - return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match(roomBlurbsLegacyRoomBlurbName).blurb; + matchBlurbFromRoomBlurbsLegacyRoomBlurbName( + roomBlurbsLegacyRoomBlurbName: string, + ) { + return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match( + roomBlurbsLegacyRoomBlurbName, + ).blurb; } /** @@ -1101,7 +1316,7 @@ export class IdentityClient { * @param {string} sequence * @returns {string} Resource name string. */ - sequencePath(sequence:string) { + sequencePath(sequence: string) { return this.pathTemplates.sequencePathTemplate.render({ sequence: sequence, }); @@ -1124,7 +1339,7 @@ export class IdentityClient { * @param {string} sequence * @returns {string} Resource name string. */ - sequenceReportPath(sequence:string) { + sequenceReportPath(sequence: string) { return this.pathTemplates.sequenceReportPathTemplate.render({ sequence: sequence, }); @@ -1138,7 +1353,9 @@ export class IdentityClient { * @returns {string} A string representing the sequence. */ matchSequenceFromSequenceReportName(sequenceReportName: string) { - return this.pathTemplates.sequenceReportPathTemplate.match(sequenceReportName).sequence; + return this.pathTemplates.sequenceReportPathTemplate.match( + sequenceReportName, + ).sequence; } /** @@ -1147,7 +1364,7 @@ export class IdentityClient { * @param {string} session * @returns {string} Resource name string. */ - sessionPath(session:string) { + sessionPath(session: string) { return this.pathTemplates.sessionPathTemplate.render({ session: session, }); @@ -1171,7 +1388,7 @@ export class IdentityClient { * @param {string} test * @returns {string} Resource name string. */ - testPath(session:string,test:string) { + testPath(session: string, test: string) { return this.pathTemplates.testPathTemplate.render({ session: session, test: test, @@ -1206,7 +1423,7 @@ export class IdentityClient { * @param {string} user * @returns {string} Resource name string. */ - userPath(user:string) { + userPath(user: string) { return this.pathTemplates.userPathTemplate.render({ user: user, }); @@ -1230,7 +1447,7 @@ export class IdentityClient { * @param {string} blurb * @returns {string} Resource name string. */ - userProfileBlurbPath(user:string,blurb:string) { + userProfileBlurbPath(user: string, blurb: string) { return this.pathTemplates.userProfileBlurbPathTemplate.render({ user: user, blurb: blurb, @@ -1245,7 +1462,9 @@ export class IdentityClient { * @returns {string} A string representing the user. */ matchUserFromUserProfileBlurbName(userProfileBlurbName: string) { - return this.pathTemplates.userProfileBlurbPathTemplate.match(userProfileBlurbName).user; + return this.pathTemplates.userProfileBlurbPathTemplate.match( + userProfileBlurbName, + ).user; } /** @@ -1256,7 +1475,9 @@ export class IdentityClient { * @returns {string} A string representing the blurb. */ matchBlurbFromUserProfileBlurbName(userProfileBlurbName: string) { - return this.pathTemplates.userProfileBlurbPathTemplate.match(userProfileBlurbName).blurb; + return this.pathTemplates.userProfileBlurbPathTemplate.match( + userProfileBlurbName, + ).blurb; } /** @@ -1267,12 +1488,18 @@ export class IdentityClient { * @param {string} blurb * @returns {string} Resource name string. */ - userProfileBlurbsLegacyUserBlurbPath(user:string,legacyUser:string,blurb:string) { - return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.render({ - user: user, - legacy_user: legacyUser, - blurb: blurb, - }); + userProfileBlurbsLegacyUserBlurbPath( + user: string, + legacyUser: string, + blurb: string, + ) { + return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.render( + { + user: user, + legacy_user: legacyUser, + blurb: blurb, + }, + ); } /** @@ -1282,8 +1509,12 @@ export class IdentityClient { * A fully-qualified path representing user_profile_blurbs_legacy_user_blurb resource. * @returns {string} A string representing the user. */ - matchUserFromUserProfileBlurbsLegacyUserBlurbName(userProfileBlurbsLegacyUserBlurbName: string) { - return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match(userProfileBlurbsLegacyUserBlurbName).user; + matchUserFromUserProfileBlurbsLegacyUserBlurbName( + userProfileBlurbsLegacyUserBlurbName: string, + ) { + return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match( + userProfileBlurbsLegacyUserBlurbName, + ).user; } /** @@ -1293,8 +1524,12 @@ export class IdentityClient { * A fully-qualified path representing user_profile_blurbs_legacy_user_blurb resource. * @returns {string} A string representing the legacy_user. */ - matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName(userProfileBlurbsLegacyUserBlurbName: string) { - return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match(userProfileBlurbsLegacyUserBlurbName).legacy_user; + matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName( + userProfileBlurbsLegacyUserBlurbName: string, + ) { + return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match( + userProfileBlurbsLegacyUserBlurbName, + ).legacy_user; } /** @@ -1304,8 +1539,12 @@ export class IdentityClient { * A fully-qualified path representing user_profile_blurbs_legacy_user_blurb resource. * @returns {string} A string representing the blurb. */ - matchBlurbFromUserProfileBlurbsLegacyUserBlurbName(userProfileBlurbsLegacyUserBlurbName: string) { - return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match(userProfileBlurbsLegacyUserBlurbName).blurb; + matchBlurbFromUserProfileBlurbsLegacyUserBlurbName( + userProfileBlurbsLegacyUserBlurbName: string, + ) { + return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match( + userProfileBlurbsLegacyUserBlurbName, + ).blurb; } /** @@ -1316,7 +1555,7 @@ export class IdentityClient { */ close(): Promise { if (this.identityStub && !this._terminated) { - return this.identityStub.then(stub => { + return this.identityStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -1324,4 +1563,4 @@ export class IdentityClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/core/generator/gapic-generator-typescript/baselines/showcase-esm/esm/src/v1beta1/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/showcase-esm/esm/src/v1beta1/index.ts.baseline index 3a94be5d9834..4470211c9331 100644 --- a/core/generator/gapic-generator-typescript/baselines/showcase-esm/esm/src/v1beta1/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/showcase-esm/esm/src/v1beta1/index.ts.baseline @@ -16,9 +16,9 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -export {ComplianceClient} from './compliance_client.js'; -export {EchoClient} from './echo_client.js'; -export {IdentityClient} from './identity_client.js'; -export {MessagingClient} from './messaging_client.js'; -export {SequenceServiceClient} from './sequence_service_client.js'; -export {TestingClient} from './testing_client.js'; +export { ComplianceClient } from './compliance_client.js'; +export { EchoClient } from './echo_client.js'; +export { IdentityClient } from './identity_client.js'; +export { MessagingClient } from './messaging_client.js'; +export { SequenceServiceClient } from './sequence_service_client.js'; +export { TestingClient } from './testing_client.js'; diff --git a/core/generator/gapic-generator-typescript/baselines/showcase-esm/esm/src/v1beta1/messaging_client.ts.baseline b/core/generator/gapic-generator-typescript/baselines/showcase-esm/esm/src/v1beta1/messaging_client.ts.baseline index 23e4c9dce498..e7376462302b 100644 --- a/core/generator/gapic-generator-typescript/baselines/showcase-esm/esm/src/v1beta1/messaging_client.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/showcase-esm/esm/src/v1beta1/messaging_client.ts.baseline @@ -18,15 +18,24 @@ /* global window */ import * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions, GrpcClientOptions, LROperation, PaginationCallback, GaxCall} from 'google-gax'; -import {Transform, PassThrough} from 'stream'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + GrpcClientOptions, + LROperation, + PaginationCallback, + GaxCall, +} from 'google-gax'; +import { Transform, PassThrough } from 'stream'; // @ts-ignore import type * as protos from '../../../protos/protos.js'; import * as messaging_client_config from './messaging_client_config.json'; import fs from 'fs'; import path from 'path'; -import {fileURLToPath} from 'url'; -import {getJSON} from '../json-helper.cjs'; +import { fileURLToPath } from 'url'; +import { getJSON } from '../json-helper.cjs'; // @ts-ignore const dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -35,16 +44,14 @@ const dirname = path.dirname(fileURLToPath(import.meta.url)); * `src/v1beta1/messaging_client_config.json`. * This file defines retry strategy and timeouts for all API methods in this library. */ -const gapicConfig = getJSON( - path.join(dirname, 'messaging_client_config.json') -); +const gapicConfig = getJSON(path.join(dirname, 'messaging_client_config.json')); const jsonProtos = getJSON( - path.join(dirname, '..', '..', '..', 'protos/protos.json') + path.join(dirname, '..', '..', '..', 'protos/protos.json'), ); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; const version = getJSON( - path.join(dirname, '..', '..', '..', '..', 'package.json') + path.join(dirname, '..', '..', '..', '..', 'package.json'), ).version; /** @@ -62,7 +69,7 @@ export class MessagingClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('showcase'); @@ -74,10 +81,10 @@ export class MessagingClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; operationsClient: gax.OperationsClient; - messagingStub?: Promise<{[name: string]: Function}>; + messagingStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of MessagingClient. @@ -119,21 +126,42 @@ export class MessagingClient { * const client = new MessagingClient({fallback: 'rest'}, gax); * ``` */ - constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { // Ensure that options include all the required fields. const staticMembers = this.constructor as typeof MessagingClient; - if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { - throw new Error('Please set either universe_domain or universeDomain, but not both.'); + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); } - const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; - this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; this._servicePath = 'localhost'; - const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; - const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // Request numeric enum values if REST transport is used. opts.numericEnums = true; @@ -158,7 +186,7 @@ export class MessagingClient { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; @@ -175,10 +203,7 @@ export class MessagingClient { const isEsm = true; const isEsmString = isEsm ? '-esm' : '-cjs'; // Determine the client header string. - const clientHeader = [ - `gax/${this._gaxModule.version}`, - `gapic/${version}`, - ]; + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/{process.versions.node}${isEsmString}`); } else { @@ -186,7 +211,7 @@ export class MessagingClient { } if (!opts.fallback) { clientHeader.push(`grpc/${this._gaxGrpc.grpcVersion}`); - } else if (opts.fallback === 'rest' ) { + } else if (opts.fallback === 'rest') { clientHeader.push(`rest/${this._gaxGrpc.grpcVersion}`); } if (opts.libName && opts.libVersion) { @@ -194,63 +219,79 @@ export class MessagingClient { } // Load the applicable protos. - this._protos = this._gaxGrpc.loadProtoJSON(jsonProtos as gax.protobuf.INamespace); + this._protos = this._gaxGrpc.loadProtoJSON( + jsonProtos as gax.protobuf.INamespace, + ); // This API contains "path templates"; forward-slash-separated // identifiers to uniquely identify resources within the API. // Create useful helper objects for these. this.pathTemplates = { blueprintPathTemplate: new this._gaxModule.PathTemplate( - 'sessions/{session}/tests/{test}/blueprints/{blueprint}' - ), - roomPathTemplate: new this._gaxModule.PathTemplate( - 'rooms/{room}' + 'sessions/{session}/tests/{test}/blueprints/{blueprint}', ), + roomPathTemplate: new this._gaxModule.PathTemplate('rooms/{room}'), roomBlurbPathTemplate: new this._gaxModule.PathTemplate( - 'rooms/{room}/blurbs/{blurb}' + 'rooms/{room}/blurbs/{blurb}', ), roomBlurbsLegacyRoomBlurbPathTemplate: new this._gaxModule.PathTemplate( - 'rooms/{room}/blurbs/legacy/{legacy_room}.{blurb}' + 'rooms/{room}/blurbs/legacy/{legacy_room}.{blurb}', ), sequencePathTemplate: new this._gaxModule.PathTemplate( - 'sequences/{sequence}' + 'sequences/{sequence}', ), sequenceReportPathTemplate: new this._gaxModule.PathTemplate( - 'sequences/{sequence}/sequenceReport' + 'sequences/{sequence}/sequenceReport', ), sessionPathTemplate: new this._gaxModule.PathTemplate( - 'sessions/{session}' + 'sessions/{session}', ), testPathTemplate: new this._gaxModule.PathTemplate( - 'sessions/{session}/tests/{test}' - ), - userPathTemplate: new this._gaxModule.PathTemplate( - 'users/{user}' + 'sessions/{session}/tests/{test}', ), + userPathTemplate: new this._gaxModule.PathTemplate('users/{user}'), userProfileBlurbPathTemplate: new this._gaxModule.PathTemplate( - 'users/{user}/profile/blurbs/{blurb}' - ), - userProfileBlurbsLegacyUserBlurbPathTemplate: new this._gaxModule.PathTemplate( - 'users/{user}/profile/blurbs/legacy/{legacy_user}~{blurb}' + 'users/{user}/profile/blurbs/{blurb}', ), + userProfileBlurbsLegacyUserBlurbPathTemplate: + new this._gaxModule.PathTemplate( + 'users/{user}/profile/blurbs/legacy/{legacy_user}~{blurb}', + ), }; // Some of the methods on this service return "paged" results, // (e.g. 50 results at a time, with tokens to get subsequent // pages). Denote the keys used for pagination and results. this.descriptors.page = { - listRooms: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'rooms'), - listBlurbs: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'blurbs') + listRooms: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'rooms', + ), + listBlurbs: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'blurbs', + ), }; // Some of the methods on this service provide streaming responses. // Provide descriptors for these. this.descriptors.stream = { - streamBlurbs: new this._gaxModule.StreamDescriptor(this._gaxModule.StreamType.SERVER_STREAMING, !!opts.fallback, !!opts.gaxServerStreamingRetries), - sendBlurbs: new this._gaxModule.StreamDescriptor(this._gaxModule.StreamType.CLIENT_STREAMING, !!opts.fallback), - connect: new this._gaxModule.StreamDescriptor(this._gaxModule.StreamType.BIDI_STREAMING, !!opts.fallback, !!opts.gaxServerStreamingRetries) + streamBlurbs: new this._gaxModule.StreamDescriptor( + this._gaxModule.StreamType.SERVER_STREAMING, + !!opts.fallback, + !!opts.gaxServerStreamingRetries, + ), + sendBlurbs: new this._gaxModule.StreamDescriptor( + this._gaxModule.StreamType.CLIENT_STREAMING, + !!opts.fallback, + ), + connect: new this._gaxModule.StreamDescriptor( + this._gaxModule.StreamType.BIDI_STREAMING, + !!opts.fallback, + !!opts.gaxServerStreamingRetries, + ), }; const protoFilesRoot = this._gaxModule.protobufFromJSON(jsonProtos); @@ -259,32 +300,103 @@ export class MessagingClient { // rather than holding a request open. const lroOptions: GrpcClientOptions = { auth: this.auth, - grpc: 'grpc' in this._gaxGrpc ? this._gaxGrpc.grpc : undefined + grpc: 'grpc' in this._gaxGrpc ? this._gaxGrpc.grpc : undefined, }; if (opts.fallback === 'rest') { lroOptions.protoJson = protoFilesRoot; - lroOptions.httpRules = [{selector: 'google.cloud.location.Locations.ListLocations',get: '/v1beta1/{name=projects/*}/locations',},{selector: 'google.cloud.location.Locations.GetLocation',get: '/v1beta1/{name=projects/*/locations/*}',},{selector: 'google.iam.v1.IAMPolicy.SetIamPolicy',post: '/v1beta1/{resource=users/*}:setIamPolicy',body: '*',additional_bindings: [{post: '/v1beta1/{resource=rooms/*}:setIamPolicy',body: '*',},{post: '/v1beta1/{resource=rooms/*/blurbs/*}:setIamPolicy',body: '*',},{post: '/v1beta1/{resource=sequences/*}:setIamPolicy',body: '*',}], - },{selector: 'google.iam.v1.IAMPolicy.GetIamPolicy',get: '/v1beta1/{resource=users/*}:getIamPolicy',additional_bindings: [{get: '/v1beta1/{resource=rooms/*}:getIamPolicy',},{get: '/v1beta1/{resource=rooms/*/blurbs/*}:getIamPolicy',},{get: '/v1beta1/{resource=sequences/*}:getIamPolicy',}], - },{selector: 'google.iam.v1.IAMPolicy.TestIamPermissions',post: '/v1beta1/{resource=users/*}:testIamPermissions',body: '*',additional_bindings: [{post: '/v1beta1/{resource=rooms/*}:testIamPermissions',body: '*',},{post: '/v1beta1/{resource=rooms/*/blurbs/*}:testIamPermissions',body: '*',},{post: '/v1beta1/{resource=sequences/*}:testIamPermissions',body: '*',}], - },{selector: 'google.longrunning.Operations.ListOperations',get: '/v1beta1/operations',},{selector: 'google.longrunning.Operations.GetOperation',get: '/v1beta1/{name=operations/**}',},{selector: 'google.longrunning.Operations.DeleteOperation',delete: '/v1beta1/{name=operations/**}',},{selector: 'google.longrunning.Operations.CancelOperation',post: '/v1beta1/{name=operations/**}:cancel',}]; + lroOptions.httpRules = [ + { + selector: 'google.cloud.location.Locations.ListLocations', + get: '/v1beta1/{name=projects/*}/locations', + }, + { + selector: 'google.cloud.location.Locations.GetLocation', + get: '/v1beta1/{name=projects/*/locations/*}', + }, + { + selector: 'google.iam.v1.IAMPolicy.SetIamPolicy', + post: '/v1beta1/{resource=users/*}:setIamPolicy', + body: '*', + additional_bindings: [ + { post: '/v1beta1/{resource=rooms/*}:setIamPolicy', body: '*' }, + { + post: '/v1beta1/{resource=rooms/*/blurbs/*}:setIamPolicy', + body: '*', + }, + { post: '/v1beta1/{resource=sequences/*}:setIamPolicy', body: '*' }, + ], + }, + { + selector: 'google.iam.v1.IAMPolicy.GetIamPolicy', + get: '/v1beta1/{resource=users/*}:getIamPolicy', + additional_bindings: [ + { get: '/v1beta1/{resource=rooms/*}:getIamPolicy' }, + { get: '/v1beta1/{resource=rooms/*/blurbs/*}:getIamPolicy' }, + { get: '/v1beta1/{resource=sequences/*}:getIamPolicy' }, + ], + }, + { + selector: 'google.iam.v1.IAMPolicy.TestIamPermissions', + post: '/v1beta1/{resource=users/*}:testIamPermissions', + body: '*', + additional_bindings: [ + { + post: '/v1beta1/{resource=rooms/*}:testIamPermissions', + body: '*', + }, + { + post: '/v1beta1/{resource=rooms/*/blurbs/*}:testIamPermissions', + body: '*', + }, + { + post: '/v1beta1/{resource=sequences/*}:testIamPermissions', + body: '*', + }, + ], + }, + { + selector: 'google.longrunning.Operations.ListOperations', + get: '/v1beta1/operations', + }, + { + selector: 'google.longrunning.Operations.GetOperation', + get: '/v1beta1/{name=operations/**}', + }, + { + selector: 'google.longrunning.Operations.DeleteOperation', + delete: '/v1beta1/{name=operations/**}', + }, + { + selector: 'google.longrunning.Operations.CancelOperation', + post: '/v1beta1/{name=operations/**}:cancel', + }, + ]; } - this.operationsClient = this._gaxModule.lro(lroOptions).operationsClient(opts); + this.operationsClient = this._gaxModule + .lro(lroOptions) + .operationsClient(opts); const searchBlurbsResponse = protoFilesRoot.lookup( - '.google.showcase.v1beta1.SearchBlurbsResponse') as gax.protobuf.Type; + '.google.showcase.v1beta1.SearchBlurbsResponse', + ) as gax.protobuf.Type; const searchBlurbsMetadata = protoFilesRoot.lookup( - '.google.showcase.v1beta1.SearchBlurbsMetadata') as gax.protobuf.Type; + '.google.showcase.v1beta1.SearchBlurbsMetadata', + ) as gax.protobuf.Type; this.descriptors.longrunning = { searchBlurbs: new this._gaxModule.LongrunningDescriptor( this.operationsClient, searchBlurbsResponse.decode.bind(searchBlurbsResponse), - searchBlurbsMetadata.decode.bind(searchBlurbsMetadata)) + searchBlurbsMetadata.decode.bind(searchBlurbsMetadata), + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.showcase.v1beta1.Messaging', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.showcase.v1beta1.Messaging', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + { 'x-goog-api-client': clientHeader.join(' ') }, + ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -315,35 +427,60 @@ export class MessagingClient { // Put together the "service stub" for // google.showcase.v1beta1.Messaging. this.messagingStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.showcase.v1beta1.Messaging') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.showcase.v1beta1.Messaging', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.showcase.v1beta1.Messaging, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts, + this._providedCustomServicePath, + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const messagingStubMethods = - ['createRoom', 'getRoom', 'updateRoom', 'deleteRoom', 'listRooms', 'createBlurb', 'getBlurb', 'updateBlurb', 'deleteBlurb', 'listBlurbs', 'searchBlurbs', 'streamBlurbs', 'sendBlurbs', 'connect']; + const messagingStubMethods = [ + 'createRoom', + 'getRoom', + 'updateRoom', + 'deleteRoom', + 'listRooms', + 'createBlurb', + 'getBlurb', + 'updateBlurb', + 'deleteBlurb', + 'listBlurbs', + 'searchBlurbs', + 'streamBlurbs', + 'sendBlurbs', + 'connect', + ]; for (const methodName of messagingStubMethods) { const callPromise = this.messagingStub.then( - stub => (...args: Array<{}>) => { - if (this._terminated) { - if (methodName in this.descriptors.stream) { - const stream = new PassThrough({objectMode: true}); - setImmediate(() => { - stream.emit('error', new this._gaxModule.GoogleError('The client has already been closed.')); - }); - return stream; + (stub) => + (...args: Array<{}>) => { + if (this._terminated) { + if (methodName in this.descriptors.stream) { + const stream = new PassThrough({ objectMode: true }); + setImmediate(() => { + stream.emit( + 'error', + new this._gaxModule.GoogleError( + 'The client has already been closed.', + ), + ); + }); + return stream; + } + return Promise.reject('The client has already been closed.'); } - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error|null|undefined) => () => { + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { throw err; - }); + }, + ); const descriptor = this.descriptors.page[methodName] || @@ -354,7 +491,7 @@ export class MessagingClient { callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -369,8 +506,14 @@ export class MessagingClient { * @returns {string} The DNS address for this service. */ static get servicePath() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'localhost'; } @@ -382,8 +525,14 @@ export class MessagingClient { * @returns {string} The DNS address for this service. */ static get apiEndpoint() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'localhost'; } @@ -423,8 +572,9 @@ export class MessagingClient { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId(callback?: Callback): - Promise|void { + getProjectId( + callback?: Callback, + ): Promise | void { if (callback) { this.auth.getProjectId(callback); return; @@ -435,1064 +585,1400 @@ export class MessagingClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Creates a room. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.showcase.v1beta1.Room} request.room - * The room to create. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.Room|Room}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/messaging.create_room.js - * region_tag:localhost_v1beta1_generated_Messaging_CreateRoom_async - */ + /** + * Creates a room. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.showcase.v1beta1.Room} request.room + * The room to create. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.Room|Room}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/messaging.create_room.js + * region_tag:localhost_v1beta1_generated_Messaging_CreateRoom_async + */ createRoom( - request?: protos.google.showcase.v1beta1.ICreateRoomRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IRoom, - protos.google.showcase.v1beta1.ICreateRoomRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.ICreateRoomRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IRoom, + protos.google.showcase.v1beta1.ICreateRoomRequest | undefined, + {} | undefined, + ] + >; createRoom( - request: protos.google.showcase.v1beta1.ICreateRoomRequest, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.IRoom, - protos.google.showcase.v1beta1.ICreateRoomRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.ICreateRoomRequest, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.IRoom, + protos.google.showcase.v1beta1.ICreateRoomRequest | null | undefined, + {} | null | undefined + >, + ): void; createRoom( - request: protos.google.showcase.v1beta1.ICreateRoomRequest, - callback: Callback< - protos.google.showcase.v1beta1.IRoom, - protos.google.showcase.v1beta1.ICreateRoomRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.ICreateRoomRequest, + callback: Callback< + protos.google.showcase.v1beta1.IRoom, + protos.google.showcase.v1beta1.ICreateRoomRequest | null | undefined, + {} | null | undefined + >, + ): void; createRoom( - request?: protos.google.showcase.v1beta1.ICreateRoomRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.showcase.v1beta1.ICreateRoomRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.IRoom, - protos.google.showcase.v1beta1.ICreateRoomRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.showcase.v1beta1.IRoom, - protos.google.showcase.v1beta1.ICreateRoomRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.IRoom, - protos.google.showcase.v1beta1.ICreateRoomRequest|undefined, {}|undefined - ]>|void { + protos.google.showcase.v1beta1.ICreateRoomRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.IRoom, + protos.google.showcase.v1beta1.ICreateRoomRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IRoom, + protos.google.showcase.v1beta1.ICreateRoomRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('createRoom request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.IRoom, - protos.google.showcase.v1beta1.ICreateRoomRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.IRoom, + protos.google.showcase.v1beta1.ICreateRoomRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createRoom response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.createRoom(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.IRoom, - protos.google.showcase.v1beta1.ICreateRoomRequest|undefined, {}|undefined - ]) => { - this._log.info('createRoom response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createRoom(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.IRoom, + protos.google.showcase.v1beta1.ICreateRoomRequest | undefined, + {} | undefined, + ]) => { + this._log.info('createRoom response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Retrieves the Room with the given resource name. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * The resource name of the requested room. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.Room|Room}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/messaging.get_room.js - * region_tag:localhost_v1beta1_generated_Messaging_GetRoom_async - */ + /** + * Retrieves the Room with the given resource name. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * The resource name of the requested room. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.Room|Room}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/messaging.get_room.js + * region_tag:localhost_v1beta1_generated_Messaging_GetRoom_async + */ getRoom( - request?: protos.google.showcase.v1beta1.IGetRoomRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IRoom, - protos.google.showcase.v1beta1.IGetRoomRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IGetRoomRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IRoom, + protos.google.showcase.v1beta1.IGetRoomRequest | undefined, + {} | undefined, + ] + >; getRoom( - request: protos.google.showcase.v1beta1.IGetRoomRequest, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.IRoom, - protos.google.showcase.v1beta1.IGetRoomRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IGetRoomRequest, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.IRoom, + protos.google.showcase.v1beta1.IGetRoomRequest | null | undefined, + {} | null | undefined + >, + ): void; getRoom( - request: protos.google.showcase.v1beta1.IGetRoomRequest, - callback: Callback< - protos.google.showcase.v1beta1.IRoom, - protos.google.showcase.v1beta1.IGetRoomRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IGetRoomRequest, + callback: Callback< + protos.google.showcase.v1beta1.IRoom, + protos.google.showcase.v1beta1.IGetRoomRequest | null | undefined, + {} | null | undefined + >, + ): void; getRoom( - request?: protos.google.showcase.v1beta1.IGetRoomRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.showcase.v1beta1.IRoom, - protos.google.showcase.v1beta1.IGetRoomRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.showcase.v1beta1.IGetRoomRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.IRoom, - protos.google.showcase.v1beta1.IGetRoomRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.IRoom, - protos.google.showcase.v1beta1.IGetRoomRequest|undefined, {}|undefined - ]>|void { + protos.google.showcase.v1beta1.IGetRoomRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.IRoom, + protos.google.showcase.v1beta1.IGetRoomRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IRoom, + protos.google.showcase.v1beta1.IGetRoomRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getRoom request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.IRoom, - protos.google.showcase.v1beta1.IGetRoomRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.IRoom, + protos.google.showcase.v1beta1.IGetRoomRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getRoom response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.getRoom(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.IRoom, - protos.google.showcase.v1beta1.IGetRoomRequest|undefined, {}|undefined - ]) => { - this._log.info('getRoom response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getRoom(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.IRoom, + protos.google.showcase.v1beta1.IGetRoomRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getRoom response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Updates a room. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.showcase.v1beta1.Room} request.room - * The room to update. - * @param {google.protobuf.FieldMask} request.updateMask - * The field mask to determine which fields are to be updated. If empty, the - * server will assume all fields are to be updated. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.Room|Room}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/messaging.update_room.js - * region_tag:localhost_v1beta1_generated_Messaging_UpdateRoom_async - */ + /** + * Updates a room. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.showcase.v1beta1.Room} request.room + * The room to update. + * @param {google.protobuf.FieldMask} request.updateMask + * The field mask to determine which fields are to be updated. If empty, the + * server will assume all fields are to be updated. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.Room|Room}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/messaging.update_room.js + * region_tag:localhost_v1beta1_generated_Messaging_UpdateRoom_async + */ updateRoom( - request?: protos.google.showcase.v1beta1.IUpdateRoomRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IRoom, - protos.google.showcase.v1beta1.IUpdateRoomRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IUpdateRoomRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IRoom, + protos.google.showcase.v1beta1.IUpdateRoomRequest | undefined, + {} | undefined, + ] + >; updateRoom( - request: protos.google.showcase.v1beta1.IUpdateRoomRequest, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.IRoom, - protos.google.showcase.v1beta1.IUpdateRoomRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IUpdateRoomRequest, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.IRoom, + protos.google.showcase.v1beta1.IUpdateRoomRequest | null | undefined, + {} | null | undefined + >, + ): void; updateRoom( - request: protos.google.showcase.v1beta1.IUpdateRoomRequest, - callback: Callback< - protos.google.showcase.v1beta1.IRoom, - protos.google.showcase.v1beta1.IUpdateRoomRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IUpdateRoomRequest, + callback: Callback< + protos.google.showcase.v1beta1.IRoom, + protos.google.showcase.v1beta1.IUpdateRoomRequest | null | undefined, + {} | null | undefined + >, + ): void; updateRoom( - request?: protos.google.showcase.v1beta1.IUpdateRoomRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.showcase.v1beta1.IRoom, - protos.google.showcase.v1beta1.IUpdateRoomRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.showcase.v1beta1.IUpdateRoomRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.IRoom, - protos.google.showcase.v1beta1.IUpdateRoomRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.IRoom, - protos.google.showcase.v1beta1.IUpdateRoomRequest|undefined, {}|undefined - ]>|void { + protos.google.showcase.v1beta1.IUpdateRoomRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.IRoom, + protos.google.showcase.v1beta1.IUpdateRoomRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IRoom, + protos.google.showcase.v1beta1.IUpdateRoomRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'room.name': request.room!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'room.name': request.room!.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateRoom request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.IRoom, - protos.google.showcase.v1beta1.IUpdateRoomRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.IRoom, + protos.google.showcase.v1beta1.IUpdateRoomRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateRoom response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.updateRoom(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.IRoom, - protos.google.showcase.v1beta1.IUpdateRoomRequest|undefined, {}|undefined - ]) => { - this._log.info('updateRoom response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateRoom(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.IRoom, + protos.google.showcase.v1beta1.IUpdateRoomRequest | undefined, + {} | undefined, + ]) => { + this._log.info('updateRoom response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Deletes a room and all of its blurbs. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * The resource name of the requested room. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/messaging.delete_room.js - * region_tag:localhost_v1beta1_generated_Messaging_DeleteRoom_async - */ + /** + * Deletes a room and all of its blurbs. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * The resource name of the requested room. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/messaging.delete_room.js + * region_tag:localhost_v1beta1_generated_Messaging_DeleteRoom_async + */ deleteRoom( - request?: protos.google.showcase.v1beta1.IDeleteRoomRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteRoomRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IDeleteRoomRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteRoomRequest | undefined, + {} | undefined, + ] + >; deleteRoom( - request: protos.google.showcase.v1beta1.IDeleteRoomRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteRoomRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IDeleteRoomRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteRoomRequest | null | undefined, + {} | null | undefined + >, + ): void; deleteRoom( - request: protos.google.showcase.v1beta1.IDeleteRoomRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteRoomRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IDeleteRoomRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteRoomRequest | null | undefined, + {} | null | undefined + >, + ): void; deleteRoom( - request?: protos.google.showcase.v1beta1.IDeleteRoomRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteRoomRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.showcase.v1beta1.IDeleteRoomRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteRoomRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteRoomRequest|undefined, {}|undefined - ]>|void { + protos.google.showcase.v1beta1.IDeleteRoomRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteRoomRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteRoomRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('deleteRoom request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteRoomRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteRoomRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteRoom response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.deleteRoom(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteRoomRequest|undefined, {}|undefined - ]) => { - this._log.info('deleteRoom response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteRoom(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteRoomRequest | undefined, + {} | undefined, + ]) => { + this._log.info('deleteRoom response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Creates a blurb. If the parent is a room, the blurb is understood to be a - * message in that room. If the parent is a profile, the blurb is understood - * to be a post on the profile. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * The resource name of the chat room or user profile that this blurb will - * be tied to. - * @param {google.showcase.v1beta1.Blurb} request.blurb - * The blurb to create. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.Blurb|Blurb}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/messaging.create_blurb.js - * region_tag:localhost_v1beta1_generated_Messaging_CreateBlurb_async - */ + /** + * Creates a blurb. If the parent is a room, the blurb is understood to be a + * message in that room. If the parent is a profile, the blurb is understood + * to be a post on the profile. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * The resource name of the chat room or user profile that this blurb will + * be tied to. + * @param {google.showcase.v1beta1.Blurb} request.blurb + * The blurb to create. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.Blurb|Blurb}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/messaging.create_blurb.js + * region_tag:localhost_v1beta1_generated_Messaging_CreateBlurb_async + */ createBlurb( - request?: protos.google.showcase.v1beta1.ICreateBlurbRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IBlurb, - protos.google.showcase.v1beta1.ICreateBlurbRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.ICreateBlurbRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IBlurb, + protos.google.showcase.v1beta1.ICreateBlurbRequest | undefined, + {} | undefined, + ] + >; createBlurb( - request: protos.google.showcase.v1beta1.ICreateBlurbRequest, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.IBlurb, - protos.google.showcase.v1beta1.ICreateBlurbRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.ICreateBlurbRequest, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.IBlurb, + protos.google.showcase.v1beta1.ICreateBlurbRequest | null | undefined, + {} | null | undefined + >, + ): void; createBlurb( - request: protos.google.showcase.v1beta1.ICreateBlurbRequest, - callback: Callback< - protos.google.showcase.v1beta1.IBlurb, - protos.google.showcase.v1beta1.ICreateBlurbRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.ICreateBlurbRequest, + callback: Callback< + protos.google.showcase.v1beta1.IBlurb, + protos.google.showcase.v1beta1.ICreateBlurbRequest | null | undefined, + {} | null | undefined + >, + ): void; createBlurb( - request?: protos.google.showcase.v1beta1.ICreateBlurbRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.showcase.v1beta1.IBlurb, - protos.google.showcase.v1beta1.ICreateBlurbRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.showcase.v1beta1.ICreateBlurbRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.IBlurb, - protos.google.showcase.v1beta1.ICreateBlurbRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.IBlurb, - protos.google.showcase.v1beta1.ICreateBlurbRequest|undefined, {}|undefined - ]>|void { + protos.google.showcase.v1beta1.ICreateBlurbRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.IBlurb, + protos.google.showcase.v1beta1.ICreateBlurbRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IBlurb, + protos.google.showcase.v1beta1.ICreateBlurbRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('createBlurb request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.IBlurb, - protos.google.showcase.v1beta1.ICreateBlurbRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.IBlurb, + protos.google.showcase.v1beta1.ICreateBlurbRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createBlurb response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.createBlurb(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.IBlurb, - protos.google.showcase.v1beta1.ICreateBlurbRequest|undefined, {}|undefined - ]) => { - this._log.info('createBlurb response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createBlurb(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.IBlurb, + protos.google.showcase.v1beta1.ICreateBlurbRequest | undefined, + {} | undefined, + ]) => { + this._log.info('createBlurb response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Retrieves the Blurb with the given resource name. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * The resource name of the requested blurb. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.Blurb|Blurb}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/messaging.get_blurb.js - * region_tag:localhost_v1beta1_generated_Messaging_GetBlurb_async - */ + /** + * Retrieves the Blurb with the given resource name. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * The resource name of the requested blurb. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.Blurb|Blurb}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/messaging.get_blurb.js + * region_tag:localhost_v1beta1_generated_Messaging_GetBlurb_async + */ getBlurb( - request?: protos.google.showcase.v1beta1.IGetBlurbRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IBlurb, - protos.google.showcase.v1beta1.IGetBlurbRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IGetBlurbRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IBlurb, + protos.google.showcase.v1beta1.IGetBlurbRequest | undefined, + {} | undefined, + ] + >; getBlurb( - request: protos.google.showcase.v1beta1.IGetBlurbRequest, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.IBlurb, - protos.google.showcase.v1beta1.IGetBlurbRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IGetBlurbRequest, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.IBlurb, + protos.google.showcase.v1beta1.IGetBlurbRequest | null | undefined, + {} | null | undefined + >, + ): void; getBlurb( - request: protos.google.showcase.v1beta1.IGetBlurbRequest, - callback: Callback< - protos.google.showcase.v1beta1.IBlurb, - protos.google.showcase.v1beta1.IGetBlurbRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IGetBlurbRequest, + callback: Callback< + protos.google.showcase.v1beta1.IBlurb, + protos.google.showcase.v1beta1.IGetBlurbRequest | null | undefined, + {} | null | undefined + >, + ): void; getBlurb( - request?: protos.google.showcase.v1beta1.IGetBlurbRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.showcase.v1beta1.IBlurb, - protos.google.showcase.v1beta1.IGetBlurbRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.showcase.v1beta1.IGetBlurbRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.IBlurb, - protos.google.showcase.v1beta1.IGetBlurbRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.IBlurb, - protos.google.showcase.v1beta1.IGetBlurbRequest|undefined, {}|undefined - ]>|void { + protos.google.showcase.v1beta1.IGetBlurbRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.IBlurb, + protos.google.showcase.v1beta1.IGetBlurbRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IBlurb, + protos.google.showcase.v1beta1.IGetBlurbRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getBlurb request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.IBlurb, - protos.google.showcase.v1beta1.IGetBlurbRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.IBlurb, + protos.google.showcase.v1beta1.IGetBlurbRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getBlurb response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.getBlurb(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.IBlurb, - protos.google.showcase.v1beta1.IGetBlurbRequest|undefined, {}|undefined - ]) => { - this._log.info('getBlurb response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getBlurb(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.IBlurb, + protos.google.showcase.v1beta1.IGetBlurbRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getBlurb response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Updates a blurb. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.showcase.v1beta1.Blurb} request.blurb - * The blurb to update. - * @param {google.protobuf.FieldMask} request.updateMask - * The field mask to determine wich fields are to be updated. If empty, the - * server will assume all fields are to be updated. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.Blurb|Blurb}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/messaging.update_blurb.js - * region_tag:localhost_v1beta1_generated_Messaging_UpdateBlurb_async - */ + /** + * Updates a blurb. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.showcase.v1beta1.Blurb} request.blurb + * The blurb to update. + * @param {google.protobuf.FieldMask} request.updateMask + * The field mask to determine wich fields are to be updated. If empty, the + * server will assume all fields are to be updated. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.Blurb|Blurb}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/messaging.update_blurb.js + * region_tag:localhost_v1beta1_generated_Messaging_UpdateBlurb_async + */ updateBlurb( - request?: protos.google.showcase.v1beta1.IUpdateBlurbRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IBlurb, - protos.google.showcase.v1beta1.IUpdateBlurbRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IUpdateBlurbRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IBlurb, + protos.google.showcase.v1beta1.IUpdateBlurbRequest | undefined, + {} | undefined, + ] + >; updateBlurb( - request: protos.google.showcase.v1beta1.IUpdateBlurbRequest, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.IBlurb, - protos.google.showcase.v1beta1.IUpdateBlurbRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IUpdateBlurbRequest, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.IBlurb, + protos.google.showcase.v1beta1.IUpdateBlurbRequest | null | undefined, + {} | null | undefined + >, + ): void; updateBlurb( - request: protos.google.showcase.v1beta1.IUpdateBlurbRequest, - callback: Callback< - protos.google.showcase.v1beta1.IBlurb, - protos.google.showcase.v1beta1.IUpdateBlurbRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IUpdateBlurbRequest, + callback: Callback< + protos.google.showcase.v1beta1.IBlurb, + protos.google.showcase.v1beta1.IUpdateBlurbRequest | null | undefined, + {} | null | undefined + >, + ): void; updateBlurb( - request?: protos.google.showcase.v1beta1.IUpdateBlurbRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.showcase.v1beta1.IBlurb, - protos.google.showcase.v1beta1.IUpdateBlurbRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.showcase.v1beta1.IUpdateBlurbRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.IBlurb, - protos.google.showcase.v1beta1.IUpdateBlurbRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.IBlurb, - protos.google.showcase.v1beta1.IUpdateBlurbRequest|undefined, {}|undefined - ]>|void { + protos.google.showcase.v1beta1.IUpdateBlurbRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.IBlurb, + protos.google.showcase.v1beta1.IUpdateBlurbRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IBlurb, + protos.google.showcase.v1beta1.IUpdateBlurbRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'blurb.name': request.blurb!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'blurb.name': request.blurb!.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateBlurb request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.IBlurb, - protos.google.showcase.v1beta1.IUpdateBlurbRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.IBlurb, + protos.google.showcase.v1beta1.IUpdateBlurbRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateBlurb response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.updateBlurb(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.IBlurb, - protos.google.showcase.v1beta1.IUpdateBlurbRequest|undefined, {}|undefined - ]) => { - this._log.info('updateBlurb response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateBlurb(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.IBlurb, + protos.google.showcase.v1beta1.IUpdateBlurbRequest | undefined, + {} | undefined, + ]) => { + this._log.info('updateBlurb response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Deletes a blurb. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * The resource name of the requested blurb. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/messaging.delete_blurb.js - * region_tag:localhost_v1beta1_generated_Messaging_DeleteBlurb_async - */ + /** + * Deletes a blurb. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * The resource name of the requested blurb. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/messaging.delete_blurb.js + * region_tag:localhost_v1beta1_generated_Messaging_DeleteBlurb_async + */ deleteBlurb( - request?: protos.google.showcase.v1beta1.IDeleteBlurbRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteBlurbRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IDeleteBlurbRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteBlurbRequest | undefined, + {} | undefined, + ] + >; deleteBlurb( - request: protos.google.showcase.v1beta1.IDeleteBlurbRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteBlurbRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IDeleteBlurbRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteBlurbRequest | null | undefined, + {} | null | undefined + >, + ): void; deleteBlurb( - request: protos.google.showcase.v1beta1.IDeleteBlurbRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteBlurbRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IDeleteBlurbRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteBlurbRequest | null | undefined, + {} | null | undefined + >, + ): void; deleteBlurb( - request?: protos.google.showcase.v1beta1.IDeleteBlurbRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.showcase.v1beta1.IDeleteBlurbRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteBlurbRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteBlurbRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteBlurbRequest|undefined, {}|undefined - ]>|void { + protos.google.showcase.v1beta1.IDeleteBlurbRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteBlurbRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteBlurbRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('deleteBlurb request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteBlurbRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteBlurbRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteBlurb response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.deleteBlurb(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteBlurbRequest|undefined, {}|undefined - ]) => { - this._log.info('deleteBlurb response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteBlurb(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteBlurbRequest | undefined, + {} | undefined, + ]) => { + this._log.info('deleteBlurb response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * This returns a stream that emits the blurbs that are created for a - * particular chat room or user profile. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * The resource name of a chat room or user profile whose blurbs to stream. - * @param {google.protobuf.Timestamp} request.expireTime - * The time at which this stream will close. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits {@link protos.google.showcase.v1beta1.StreamBlurbsResponse|StreamBlurbsResponse} on 'data' event. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#server-streaming | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/messaging.stream_blurbs.js - * region_tag:localhost_v1beta1_generated_Messaging_StreamBlurbs_async - */ + /** + * This returns a stream that emits the blurbs that are created for a + * particular chat room or user profile. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * The resource name of a chat room or user profile whose blurbs to stream. + * @param {google.protobuf.Timestamp} request.expireTime + * The time at which this stream will close. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits {@link protos.google.showcase.v1beta1.StreamBlurbsResponse|StreamBlurbsResponse} on 'data' event. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#server-streaming | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/messaging.stream_blurbs.js + * region_tag:localhost_v1beta1_generated_Messaging_StreamBlurbs_async + */ streamBlurbs( - request?: protos.google.showcase.v1beta1.IStreamBlurbsRequest, - options?: CallOptions): - gax.CancellableStream{ + request?: protos.google.showcase.v1beta1.IStreamBlurbsRequest, + options?: CallOptions, + ): gax.CancellableStream { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('streamBlurbs stream %j', options); return this.innerApiCalls.streamBlurbs(request, options); } -/** - * This is a stream to create multiple blurbs. If an invalid blurb is - * requested to be created, the stream will close with an error. - * - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - A writable stream which accepts objects representing - * {@link protos.google.showcase.v1beta1.CreateBlurbRequest|CreateBlurbRequest}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#client-streaming | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/messaging.send_blurbs.js - * region_tag:localhost_v1beta1_generated_Messaging_SendBlurbs_async - */ + /** + * This is a stream to create multiple blurbs. If an invalid blurb is + * requested to be created, the stream will close with an error. + * + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} - A writable stream which accepts objects representing + * {@link protos.google.showcase.v1beta1.CreateBlurbRequest|CreateBlurbRequest}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#client-streaming | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/messaging.send_blurbs.js + * region_tag:localhost_v1beta1_generated_Messaging_SendBlurbs_async + */ sendBlurbs( - options?: CallOptions, - callback?: Callback< - protos.google.showcase.v1beta1.ISendBlurbsResponse, - protos.google.showcase.v1beta1.ICreateBlurbRequest|null|undefined, - {}|null|undefined>): - gax.CancellableStream; + options?: CallOptions, + callback?: Callback< + protos.google.showcase.v1beta1.ISendBlurbsResponse, + protos.google.showcase.v1beta1.ICreateBlurbRequest | null | undefined, + {} | null | undefined + >, + ): gax.CancellableStream; sendBlurbs( - callback?: Callback< - protos.google.showcase.v1beta1.ISendBlurbsResponse, - protos.google.showcase.v1beta1.ICreateBlurbRequest|null|undefined, - {}|null|undefined>): - gax.CancellableStream; + callback?: Callback< + protos.google.showcase.v1beta1.ISendBlurbsResponse, + protos.google.showcase.v1beta1.ICreateBlurbRequest | null | undefined, + {} | null | undefined + >, + ): gax.CancellableStream; sendBlurbs( - optionsOrCallback?: CallOptions|Callback< - protos.google.showcase.v1beta1.ISendBlurbsResponse, - protos.google.showcase.v1beta1.ICreateBlurbRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.showcase.v1beta1.ISendBlurbsResponse, - protos.google.showcase.v1beta1.ICreateBlurbRequest|null|undefined, - {}|null|undefined>): - gax.CancellableStream { + optionsOrCallback?: + | CallOptions + | Callback< + protos.google.showcase.v1beta1.ISendBlurbsResponse, + protos.google.showcase.v1beta1.ICreateBlurbRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.ISendBlurbsResponse, + protos.google.showcase.v1beta1.ICreateBlurbRequest | null | undefined, + {} | null | undefined + >, + ): gax.CancellableStream { if (optionsOrCallback instanceof Function && callback === undefined) { - callback = optionsOrCallback; - optionsOrCallback = {}; + callback = optionsOrCallback; + optionsOrCallback = {}; } const options = optionsOrCallback as CallOptions; - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('sendBlurbs stream %j', options); return this.innerApiCalls.sendBlurbs(null, options, callback); } -/** - * This method starts a bidirectional stream that receives all blurbs that - * are being created after the stream has started and sends requests to create - * blurbs. If an invalid blurb is requested to be created, the stream will - * close with an error. - * - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which is both readable and writable. It accepts objects - * representing {@link protos.google.showcase.v1beta1.ConnectRequest|ConnectRequest} for write() method, and - * will emit objects representing {@link protos.google.showcase.v1beta1.StreamBlurbsResponse|StreamBlurbsResponse} on 'data' event asynchronously. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#bi-directional-streaming | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/messaging.connect.js - * region_tag:localhost_v1beta1_generated_Messaging_Connect_async - */ - connect( - options?: CallOptions): - gax.CancellableStream { - this.initialize().catch(err => {throw err}); + /** + * This method starts a bidirectional stream that receives all blurbs that + * are being created after the stream has started and sends requests to create + * blurbs. If an invalid blurb is requested to be created, the stream will + * close with an error. + * + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which is both readable and writable. It accepts objects + * representing {@link protos.google.showcase.v1beta1.ConnectRequest|ConnectRequest} for write() method, and + * will emit objects representing {@link protos.google.showcase.v1beta1.StreamBlurbsResponse|StreamBlurbsResponse} on 'data' event asynchronously. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#bi-directional-streaming | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/messaging.connect.js + * region_tag:localhost_v1beta1_generated_Messaging_Connect_async + */ + connect(options?: CallOptions): gax.CancellableStream { + this.initialize().catch((err) => { + throw err; + }); this._log.info('connect stream %j', options); return this.innerApiCalls.connect(null, options); } -/** - * This method searches through all blurbs across all rooms and profiles - * for blurbs containing to words found in the query. Only posts that - * contain an exact match of a queried word will be returned. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.query - * The query used to search for blurbs containing to words of this string. - * Only posts that contain an exact match of a queried word will be returned. - * @param {string} request.parent - * The rooms or profiles to search. If unset, `SearchBlurbs` will search all - * rooms and all profiles. - * @param {number} request.pageSize - * The maximum number of blurbs return. Server may return fewer - * blurbs than requested. If unspecified, server will pick an appropriate - * default. - * @param {string} request.pageToken - * The value of - * google.showcase.v1beta1.SearchBlurbsResponse.next_page_token - * returned from the previous call to - * `google.showcase.v1beta1.Messaging\SearchBlurbs` method. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing - * a long running operation. Its `promise()` method returns a promise - * you can `await` for. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/messaging.search_blurbs.js - * region_tag:localhost_v1beta1_generated_Messaging_SearchBlurbs_async - */ + /** + * This method searches through all blurbs across all rooms and profiles + * for blurbs containing to words found in the query. Only posts that + * contain an exact match of a queried word will be returned. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.query + * The query used to search for blurbs containing to words of this string. + * Only posts that contain an exact match of a queried word will be returned. + * @param {string} request.parent + * The rooms or profiles to search. If unset, `SearchBlurbs` will search all + * rooms and all profiles. + * @param {number} request.pageSize + * The maximum number of blurbs return. Server may return fewer + * blurbs than requested. If unspecified, server will pick an appropriate + * default. + * @param {string} request.pageToken + * The value of + * google.showcase.v1beta1.SearchBlurbsResponse.next_page_token + * returned from the previous call to + * `google.showcase.v1beta1.Messaging\SearchBlurbs` method. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/messaging.search_blurbs.js + * region_tag:localhost_v1beta1_generated_Messaging_SearchBlurbs_async + */ searchBlurbs( - request?: protos.google.showcase.v1beta1.ISearchBlurbsRequest, - options?: CallOptions): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.ISearchBlurbsRequest, + options?: CallOptions, + ): Promise< + [ + LROperation< + protos.google.showcase.v1beta1.ISearchBlurbsResponse, + protos.google.showcase.v1beta1.ISearchBlurbsMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; searchBlurbs( - request: protos.google.showcase.v1beta1.ISearchBlurbsRequest, - options: CallOptions, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.ISearchBlurbsRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.showcase.v1beta1.ISearchBlurbsResponse, + protos.google.showcase.v1beta1.ISearchBlurbsMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; searchBlurbs( - request: protos.google.showcase.v1beta1.ISearchBlurbsRequest, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.ISearchBlurbsRequest, + callback: Callback< + LROperation< + protos.google.showcase.v1beta1.ISearchBlurbsResponse, + protos.google.showcase.v1beta1.ISearchBlurbsMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; searchBlurbs( - request?: protos.google.showcase.v1beta1.ISearchBlurbsRequest, - optionsOrCallback?: CallOptions|Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>, - callback?: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>|void { + request?: protos.google.showcase.v1beta1.ISearchBlurbsRequest, + optionsOrCallback?: + | CallOptions + | Callback< + LROperation< + protos.google.showcase.v1beta1.ISearchBlurbsResponse, + protos.google.showcase.v1beta1.ISearchBlurbsMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + callback?: Callback< + LROperation< + protos.google.showcase.v1beta1.ISearchBlurbsResponse, + protos.google.showcase.v1beta1.ISearchBlurbsMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + LROperation< + protos.google.showcase.v1beta1.ISearchBlurbsResponse, + protos.google.showcase.v1beta1.ISearchBlurbsMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + LROperation< + protos.google.showcase.v1beta1.ISearchBlurbsResponse, + protos.google.showcase.v1beta1.ISearchBlurbsMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, rawResponse, _) => { this._log.info('searchBlurbs response %j', rawResponse); callback!(error, response, rawResponse, _); // We verified `callback` above. } : undefined; this._log.info('searchBlurbs request %j', request); - return this.innerApiCalls.searchBlurbs(request, options, wrappedCallback) - ?.then(([response, rawResponse, _]: [ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]) => { - this._log.info('searchBlurbs response %j', rawResponse); - return [response, rawResponse, _]; - }); + return this.innerApiCalls + .searchBlurbs(request, options, wrappedCallback) + ?.then( + ([response, rawResponse, _]: [ + LROperation< + protos.google.showcase.v1beta1.ISearchBlurbsResponse, + protos.google.showcase.v1beta1.ISearchBlurbsMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ]) => { + this._log.info('searchBlurbs response %j', rawResponse); + return [response, rawResponse, _]; + }, + ); } -/** - * Check the status of the long running operation returned by `searchBlurbs()`. - * @param {String} name - * The operation name that will be passed. - * @returns {Promise} - The promise which resolves to an object. - * The decoded operation object has result and metadata field to get information from. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/messaging.search_blurbs.js - * region_tag:localhost_v1beta1_generated_Messaging_SearchBlurbs_async - */ - async checkSearchBlurbsProgress(name: string): Promise>{ + /** + * Check the status of the long running operation returned by `searchBlurbs()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/messaging.search_blurbs.js + * region_tag:localhost_v1beta1_generated_Messaging_SearchBlurbs_async + */ + async checkSearchBlurbsProgress( + name: string, + ): Promise< + LROperation< + protos.google.showcase.v1beta1.SearchBlurbsResponse, + protos.google.showcase.v1beta1.SearchBlurbsMetadata + > + > { this._log.info('searchBlurbs long-running'); - const request = new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest({name}); + const request = + new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( + { name }, + ); const [operation] = await this.operationsClient.getOperation(request); - const decodeOperation = new this._gaxModule.Operation(operation, this.descriptors.longrunning.searchBlurbs, this._gaxModule.createDefaultBackoffSettings()); - return decodeOperation as LROperation; + const decodeOperation = new this._gaxModule.Operation( + operation, + this.descriptors.longrunning.searchBlurbs, + this._gaxModule.createDefaultBackoffSettings(), + ); + return decodeOperation as LROperation< + protos.google.showcase.v1beta1.SearchBlurbsResponse, + protos.google.showcase.v1beta1.SearchBlurbsMetadata + >; } - /** - * Lists all chat rooms. - * - * @param {Object} request - * The request object that will be sent. - * @param {number} request.pageSize - * The maximum number of rooms return. Server may return fewer rooms - * than requested. If unspecified, server will pick an appropriate default. - * @param {string} request.pageToken - * The value of google.showcase.v1beta1.ListRoomsResponse.next_page_token - * returned from the previous call to - * `google.showcase.v1beta1.Messaging\ListRooms` method. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.showcase.v1beta1.Room|Room}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `listRoomsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Lists all chat rooms. + * + * @param {Object} request + * The request object that will be sent. + * @param {number} request.pageSize + * The maximum number of rooms return. Server may return fewer rooms + * than requested. If unspecified, server will pick an appropriate default. + * @param {string} request.pageToken + * The value of google.showcase.v1beta1.ListRoomsResponse.next_page_token + * returned from the previous call to + * `google.showcase.v1beta1.Messaging\ListRooms` method. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.showcase.v1beta1.Room|Room}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listRoomsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listRooms( - request?: protos.google.showcase.v1beta1.IListRoomsRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IRoom[], - protos.google.showcase.v1beta1.IListRoomsRequest|null, - protos.google.showcase.v1beta1.IListRoomsResponse - ]>; + request?: protos.google.showcase.v1beta1.IListRoomsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IRoom[], + protos.google.showcase.v1beta1.IListRoomsRequest | null, + protos.google.showcase.v1beta1.IListRoomsResponse, + ] + >; listRooms( - request: protos.google.showcase.v1beta1.IListRoomsRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.showcase.v1beta1.IListRoomsRequest, - protos.google.showcase.v1beta1.IListRoomsResponse|null|undefined, - protos.google.showcase.v1beta1.IRoom>): void; + request: protos.google.showcase.v1beta1.IListRoomsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.showcase.v1beta1.IListRoomsRequest, + protos.google.showcase.v1beta1.IListRoomsResponse | null | undefined, + protos.google.showcase.v1beta1.IRoom + >, + ): void; listRooms( - request: protos.google.showcase.v1beta1.IListRoomsRequest, - callback: PaginationCallback< - protos.google.showcase.v1beta1.IListRoomsRequest, - protos.google.showcase.v1beta1.IListRoomsResponse|null|undefined, - protos.google.showcase.v1beta1.IRoom>): void; + request: protos.google.showcase.v1beta1.IListRoomsRequest, + callback: PaginationCallback< + protos.google.showcase.v1beta1.IListRoomsRequest, + protos.google.showcase.v1beta1.IListRoomsResponse | null | undefined, + protos.google.showcase.v1beta1.IRoom + >, + ): void; listRooms( - request?: protos.google.showcase.v1beta1.IListRoomsRequest, - optionsOrCallback?: CallOptions|PaginationCallback< - protos.google.showcase.v1beta1.IListRoomsRequest, - protos.google.showcase.v1beta1.IListRoomsResponse|null|undefined, - protos.google.showcase.v1beta1.IRoom>, - callback?: PaginationCallback< + request?: protos.google.showcase.v1beta1.IListRoomsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.showcase.v1beta1.IListRoomsRequest, - protos.google.showcase.v1beta1.IListRoomsResponse|null|undefined, - protos.google.showcase.v1beta1.IRoom>): - Promise<[ - protos.google.showcase.v1beta1.IRoom[], - protos.google.showcase.v1beta1.IListRoomsRequest|null, - protos.google.showcase.v1beta1.IListRoomsResponse - ]>|void { + protos.google.showcase.v1beta1.IListRoomsResponse | null | undefined, + protos.google.showcase.v1beta1.IRoom + >, + callback?: PaginationCallback< + protos.google.showcase.v1beta1.IListRoomsRequest, + protos.google.showcase.v1beta1.IListRoomsResponse | null | undefined, + protos.google.showcase.v1beta1.IRoom + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IRoom[], + protos.google.showcase.v1beta1.IListRoomsRequest | null, + protos.google.showcase.v1beta1.IListRoomsResponse, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.showcase.v1beta1.IListRoomsRequest, - protos.google.showcase.v1beta1.IListRoomsResponse|null|undefined, - protos.google.showcase.v1beta1.IRoom>|undefined = callback + this.initialize().catch((err) => { + throw err; + }); + const wrappedCallback: + | PaginationCallback< + protos.google.showcase.v1beta1.IListRoomsRequest, + protos.google.showcase.v1beta1.IListRoomsResponse | null | undefined, + protos.google.showcase.v1beta1.IRoom + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listRooms values %j', values); callback!(error, values, nextPageRequest, rawResponse); @@ -1501,186 +1987,207 @@ export class MessagingClient { this._log.info('listRooms request %j', request); return this.innerApiCalls .listRooms(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.showcase.v1beta1.IRoom[], - protos.google.showcase.v1beta1.IListRoomsRequest|null, - protos.google.showcase.v1beta1.IListRoomsResponse - ]) => { - this._log.info('listRooms values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.showcase.v1beta1.IRoom[], + protos.google.showcase.v1beta1.IListRoomsRequest | null, + protos.google.showcase.v1beta1.IListRoomsResponse, + ]) => { + this._log.info('listRooms values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listRooms`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {number} request.pageSize - * The maximum number of rooms return. Server may return fewer rooms - * than requested. If unspecified, server will pick an appropriate default. - * @param {string} request.pageToken - * The value of google.showcase.v1beta1.ListRoomsResponse.next_page_token - * returned from the previous call to - * `google.showcase.v1beta1.Messaging\ListRooms` method. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.showcase.v1beta1.Room|Room} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `listRoomsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `listRooms`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {number} request.pageSize + * The maximum number of rooms return. Server may return fewer rooms + * than requested. If unspecified, server will pick an appropriate default. + * @param {string} request.pageToken + * The value of google.showcase.v1beta1.ListRoomsResponse.next_page_token + * returned from the previous call to + * `google.showcase.v1beta1.Messaging\ListRooms` method. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.showcase.v1beta1.Room|Room} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listRoomsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listRoomsStream( - request?: protos.google.showcase.v1beta1.IListRoomsRequest, - options?: CallOptions): - Transform{ + request?: protos.google.showcase.v1beta1.IListRoomsRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; const defaultCallSettings = this._defaults['listRooms']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listRooms stream %j', request); return this.descriptors.page.listRooms.createStream( this.innerApiCalls.listRooms as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listRooms`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {number} request.pageSize - * The maximum number of rooms return. Server may return fewer rooms - * than requested. If unspecified, server will pick an appropriate default. - * @param {string} request.pageToken - * The value of google.showcase.v1beta1.ListRoomsResponse.next_page_token - * returned from the previous call to - * `google.showcase.v1beta1.Messaging\ListRooms` method. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.showcase.v1beta1.Room|Room}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/messaging.list_rooms.js - * region_tag:localhost_v1beta1_generated_Messaging_ListRooms_async - */ + /** + * Equivalent to `listRooms`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {number} request.pageSize + * The maximum number of rooms return. Server may return fewer rooms + * than requested. If unspecified, server will pick an appropriate default. + * @param {string} request.pageToken + * The value of google.showcase.v1beta1.ListRoomsResponse.next_page_token + * returned from the previous call to + * `google.showcase.v1beta1.Messaging\ListRooms` method. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.showcase.v1beta1.Room|Room}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/messaging.list_rooms.js + * region_tag:localhost_v1beta1_generated_Messaging_ListRooms_async + */ listRoomsAsync( - request?: protos.google.showcase.v1beta1.IListRoomsRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.showcase.v1beta1.IListRoomsRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; const defaultCallSettings = this._defaults['listRooms']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listRooms iterate %j', request); return this.descriptors.page.listRooms.asyncIterate( this.innerApiCalls['listRooms'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } - /** - * Lists blurbs for a specific chat room or user profile depending on the - * parent resource name. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * The resource name of the requested room or profile whos blurbs to list. - * @param {number} request.pageSize - * The maximum number of blurbs to return. Server may return fewer - * blurbs than requested. If unspecified, server will pick an appropriate - * default. - * @param {string} request.pageToken - * The value of google.showcase.v1beta1.ListBlurbsResponse.next_page_token - * returned from the previous call to - * `google.showcase.v1beta1.Messaging\ListBlurbs` method. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.showcase.v1beta1.Blurb|Blurb}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `listBlurbsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Lists blurbs for a specific chat room or user profile depending on the + * parent resource name. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * The resource name of the requested room or profile whos blurbs to list. + * @param {number} request.pageSize + * The maximum number of blurbs to return. Server may return fewer + * blurbs than requested. If unspecified, server will pick an appropriate + * default. + * @param {string} request.pageToken + * The value of google.showcase.v1beta1.ListBlurbsResponse.next_page_token + * returned from the previous call to + * `google.showcase.v1beta1.Messaging\ListBlurbs` method. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.showcase.v1beta1.Blurb|Blurb}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listBlurbsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listBlurbs( - request?: protos.google.showcase.v1beta1.IListBlurbsRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IBlurb[], - protos.google.showcase.v1beta1.IListBlurbsRequest|null, - protos.google.showcase.v1beta1.IListBlurbsResponse - ]>; + request?: protos.google.showcase.v1beta1.IListBlurbsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IBlurb[], + protos.google.showcase.v1beta1.IListBlurbsRequest | null, + protos.google.showcase.v1beta1.IListBlurbsResponse, + ] + >; listBlurbs( - request: protos.google.showcase.v1beta1.IListBlurbsRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.showcase.v1beta1.IListBlurbsRequest, - protos.google.showcase.v1beta1.IListBlurbsResponse|null|undefined, - protos.google.showcase.v1beta1.IBlurb>): void; + request: protos.google.showcase.v1beta1.IListBlurbsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.showcase.v1beta1.IListBlurbsRequest, + protos.google.showcase.v1beta1.IListBlurbsResponse | null | undefined, + protos.google.showcase.v1beta1.IBlurb + >, + ): void; listBlurbs( - request: protos.google.showcase.v1beta1.IListBlurbsRequest, - callback: PaginationCallback< - protos.google.showcase.v1beta1.IListBlurbsRequest, - protos.google.showcase.v1beta1.IListBlurbsResponse|null|undefined, - protos.google.showcase.v1beta1.IBlurb>): void; + request: protos.google.showcase.v1beta1.IListBlurbsRequest, + callback: PaginationCallback< + protos.google.showcase.v1beta1.IListBlurbsRequest, + protos.google.showcase.v1beta1.IListBlurbsResponse | null | undefined, + protos.google.showcase.v1beta1.IBlurb + >, + ): void; listBlurbs( - request?: protos.google.showcase.v1beta1.IListBlurbsRequest, - optionsOrCallback?: CallOptions|PaginationCallback< - protos.google.showcase.v1beta1.IListBlurbsRequest, - protos.google.showcase.v1beta1.IListBlurbsResponse|null|undefined, - protos.google.showcase.v1beta1.IBlurb>, - callback?: PaginationCallback< + request?: protos.google.showcase.v1beta1.IListBlurbsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.showcase.v1beta1.IListBlurbsRequest, - protos.google.showcase.v1beta1.IListBlurbsResponse|null|undefined, - protos.google.showcase.v1beta1.IBlurb>): - Promise<[ - protos.google.showcase.v1beta1.IBlurb[], - protos.google.showcase.v1beta1.IListBlurbsRequest|null, - protos.google.showcase.v1beta1.IListBlurbsResponse - ]>|void { + protos.google.showcase.v1beta1.IListBlurbsResponse | null | undefined, + protos.google.showcase.v1beta1.IBlurb + >, + callback?: PaginationCallback< + protos.google.showcase.v1beta1.IListBlurbsRequest, + protos.google.showcase.v1beta1.IListBlurbsResponse | null | undefined, + protos.google.showcase.v1beta1.IBlurb + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IBlurb[], + protos.google.showcase.v1beta1.IListBlurbsRequest | null, + protos.google.showcase.v1beta1.IListBlurbsResponse, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.showcase.v1beta1.IListBlurbsRequest, - protos.google.showcase.v1beta1.IListBlurbsResponse|null|undefined, - protos.google.showcase.v1beta1.IBlurb>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.showcase.v1beta1.IListBlurbsRequest, + protos.google.showcase.v1beta1.IListBlurbsResponse | null | undefined, + protos.google.showcase.v1beta1.IBlurb + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listBlurbs values %j', values); callback!(error, values, nextPageRequest, rawResponse); @@ -1689,114 +2196,118 @@ export class MessagingClient { this._log.info('listBlurbs request %j', request); return this.innerApiCalls .listBlurbs(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.showcase.v1beta1.IBlurb[], - protos.google.showcase.v1beta1.IListBlurbsRequest|null, - protos.google.showcase.v1beta1.IListBlurbsResponse - ]) => { - this._log.info('listBlurbs values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.showcase.v1beta1.IBlurb[], + protos.google.showcase.v1beta1.IListBlurbsRequest | null, + protos.google.showcase.v1beta1.IListBlurbsResponse, + ]) => { + this._log.info('listBlurbs values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listBlurbs`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * The resource name of the requested room or profile whos blurbs to list. - * @param {number} request.pageSize - * The maximum number of blurbs to return. Server may return fewer - * blurbs than requested. If unspecified, server will pick an appropriate - * default. - * @param {string} request.pageToken - * The value of google.showcase.v1beta1.ListBlurbsResponse.next_page_token - * returned from the previous call to - * `google.showcase.v1beta1.Messaging\ListBlurbs` method. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.showcase.v1beta1.Blurb|Blurb} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `listBlurbsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `listBlurbs`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * The resource name of the requested room or profile whos blurbs to list. + * @param {number} request.pageSize + * The maximum number of blurbs to return. Server may return fewer + * blurbs than requested. If unspecified, server will pick an appropriate + * default. + * @param {string} request.pageToken + * The value of google.showcase.v1beta1.ListBlurbsResponse.next_page_token + * returned from the previous call to + * `google.showcase.v1beta1.Messaging\ListBlurbs` method. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.showcase.v1beta1.Blurb|Blurb} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listBlurbsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listBlurbsStream( - request?: protos.google.showcase.v1beta1.IListBlurbsRequest, - options?: CallOptions): - Transform{ + request?: protos.google.showcase.v1beta1.IListBlurbsRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); const defaultCallSettings = this._defaults['listBlurbs']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listBlurbs stream %j', request); return this.descriptors.page.listBlurbs.createStream( this.innerApiCalls.listBlurbs as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listBlurbs`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * The resource name of the requested room or profile whos blurbs to list. - * @param {number} request.pageSize - * The maximum number of blurbs to return. Server may return fewer - * blurbs than requested. If unspecified, server will pick an appropriate - * default. - * @param {string} request.pageToken - * The value of google.showcase.v1beta1.ListBlurbsResponse.next_page_token - * returned from the previous call to - * `google.showcase.v1beta1.Messaging\ListBlurbs` method. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.showcase.v1beta1.Blurb|Blurb}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/messaging.list_blurbs.js - * region_tag:localhost_v1beta1_generated_Messaging_ListBlurbs_async - */ + /** + * Equivalent to `listBlurbs`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * The resource name of the requested room or profile whos blurbs to list. + * @param {number} request.pageSize + * The maximum number of blurbs to return. Server may return fewer + * blurbs than requested. If unspecified, server will pick an appropriate + * default. + * @param {string} request.pageToken + * The value of google.showcase.v1beta1.ListBlurbsResponse.next_page_token + * returned from the previous call to + * `google.showcase.v1beta1.Messaging\ListBlurbs` method. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.showcase.v1beta1.Blurb|Blurb}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/messaging.list_blurbs.js + * region_tag:localhost_v1beta1_generated_Messaging_ListBlurbs_async + */ listBlurbsAsync( - request?: protos.google.showcase.v1beta1.IListBlurbsRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.showcase.v1beta1.IListBlurbsRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); const defaultCallSettings = this._defaults['listBlurbs']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listBlurbs iterate %j', request); return this.descriptors.page.listBlurbs.asyncIterate( this.innerApiCalls['listBlurbs'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } // -------------------- @@ -1811,7 +2322,7 @@ export class MessagingClient { * @param {string} blueprint * @returns {string} Resource name string. */ - blueprintPath(session:string,test:string,blueprint:string) { + blueprintPath(session: string, test: string, blueprint: string) { return this.pathTemplates.blueprintPathTemplate.render({ session: session, test: test, @@ -1827,7 +2338,8 @@ export class MessagingClient { * @returns {string} A string representing the session. */ matchSessionFromBlueprintName(blueprintName: string) { - return this.pathTemplates.blueprintPathTemplate.match(blueprintName).session; + return this.pathTemplates.blueprintPathTemplate.match(blueprintName) + .session; } /** @@ -1849,7 +2361,8 @@ export class MessagingClient { * @returns {string} A string representing the blueprint. */ matchBlueprintFromBlueprintName(blueprintName: string) { - return this.pathTemplates.blueprintPathTemplate.match(blueprintName).blueprint; + return this.pathTemplates.blueprintPathTemplate.match(blueprintName) + .blueprint; } /** @@ -1858,7 +2371,7 @@ export class MessagingClient { * @param {string} room * @returns {string} Resource name string. */ - roomPath(room:string) { + roomPath(room: string) { return this.pathTemplates.roomPathTemplate.render({ room: room, }); @@ -1882,7 +2395,7 @@ export class MessagingClient { * @param {string} blurb * @returns {string} Resource name string. */ - roomBlurbPath(room:string,blurb:string) { + roomBlurbPath(room: string, blurb: string) { return this.pathTemplates.roomBlurbPathTemplate.render({ room: room, blurb: blurb, @@ -1919,7 +2432,11 @@ export class MessagingClient { * @param {string} blurb * @returns {string} Resource name string. */ - roomBlurbsLegacyRoomBlurbPath(room:string,legacyRoom:string,blurb:string) { + roomBlurbsLegacyRoomBlurbPath( + room: string, + legacyRoom: string, + blurb: string, + ) { return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.render({ room: room, legacy_room: legacyRoom, @@ -1934,8 +2451,12 @@ export class MessagingClient { * A fully-qualified path representing room_blurbs_legacy_room_blurb resource. * @returns {string} A string representing the room. */ - matchRoomFromRoomBlurbsLegacyRoomBlurbName(roomBlurbsLegacyRoomBlurbName: string) { - return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match(roomBlurbsLegacyRoomBlurbName).room; + matchRoomFromRoomBlurbsLegacyRoomBlurbName( + roomBlurbsLegacyRoomBlurbName: string, + ) { + return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match( + roomBlurbsLegacyRoomBlurbName, + ).room; } /** @@ -1945,8 +2466,12 @@ export class MessagingClient { * A fully-qualified path representing room_blurbs_legacy_room_blurb resource. * @returns {string} A string representing the legacy_room. */ - matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName(roomBlurbsLegacyRoomBlurbName: string) { - return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match(roomBlurbsLegacyRoomBlurbName).legacy_room; + matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName( + roomBlurbsLegacyRoomBlurbName: string, + ) { + return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match( + roomBlurbsLegacyRoomBlurbName, + ).legacy_room; } /** @@ -1956,8 +2481,12 @@ export class MessagingClient { * A fully-qualified path representing room_blurbs_legacy_room_blurb resource. * @returns {string} A string representing the blurb. */ - matchBlurbFromRoomBlurbsLegacyRoomBlurbName(roomBlurbsLegacyRoomBlurbName: string) { - return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match(roomBlurbsLegacyRoomBlurbName).blurb; + matchBlurbFromRoomBlurbsLegacyRoomBlurbName( + roomBlurbsLegacyRoomBlurbName: string, + ) { + return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match( + roomBlurbsLegacyRoomBlurbName, + ).blurb; } /** @@ -1966,7 +2495,7 @@ export class MessagingClient { * @param {string} sequence * @returns {string} Resource name string. */ - sequencePath(sequence:string) { + sequencePath(sequence: string) { return this.pathTemplates.sequencePathTemplate.render({ sequence: sequence, }); @@ -1989,7 +2518,7 @@ export class MessagingClient { * @param {string} sequence * @returns {string} Resource name string. */ - sequenceReportPath(sequence:string) { + sequenceReportPath(sequence: string) { return this.pathTemplates.sequenceReportPathTemplate.render({ sequence: sequence, }); @@ -2003,7 +2532,9 @@ export class MessagingClient { * @returns {string} A string representing the sequence. */ matchSequenceFromSequenceReportName(sequenceReportName: string) { - return this.pathTemplates.sequenceReportPathTemplate.match(sequenceReportName).sequence; + return this.pathTemplates.sequenceReportPathTemplate.match( + sequenceReportName, + ).sequence; } /** @@ -2012,7 +2543,7 @@ export class MessagingClient { * @param {string} session * @returns {string} Resource name string. */ - sessionPath(session:string) { + sessionPath(session: string) { return this.pathTemplates.sessionPathTemplate.render({ session: session, }); @@ -2036,7 +2567,7 @@ export class MessagingClient { * @param {string} test * @returns {string} Resource name string. */ - testPath(session:string,test:string) { + testPath(session: string, test: string) { return this.pathTemplates.testPathTemplate.render({ session: session, test: test, @@ -2071,7 +2602,7 @@ export class MessagingClient { * @param {string} user * @returns {string} Resource name string. */ - userPath(user:string) { + userPath(user: string) { return this.pathTemplates.userPathTemplate.render({ user: user, }); @@ -2095,7 +2626,7 @@ export class MessagingClient { * @param {string} blurb * @returns {string} Resource name string. */ - userProfileBlurbPath(user:string,blurb:string) { + userProfileBlurbPath(user: string, blurb: string) { return this.pathTemplates.userProfileBlurbPathTemplate.render({ user: user, blurb: blurb, @@ -2110,7 +2641,9 @@ export class MessagingClient { * @returns {string} A string representing the user. */ matchUserFromUserProfileBlurbName(userProfileBlurbName: string) { - return this.pathTemplates.userProfileBlurbPathTemplate.match(userProfileBlurbName).user; + return this.pathTemplates.userProfileBlurbPathTemplate.match( + userProfileBlurbName, + ).user; } /** @@ -2121,7 +2654,9 @@ export class MessagingClient { * @returns {string} A string representing the blurb. */ matchBlurbFromUserProfileBlurbName(userProfileBlurbName: string) { - return this.pathTemplates.userProfileBlurbPathTemplate.match(userProfileBlurbName).blurb; + return this.pathTemplates.userProfileBlurbPathTemplate.match( + userProfileBlurbName, + ).blurb; } /** @@ -2132,12 +2667,18 @@ export class MessagingClient { * @param {string} blurb * @returns {string} Resource name string. */ - userProfileBlurbsLegacyUserBlurbPath(user:string,legacyUser:string,blurb:string) { - return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.render({ - user: user, - legacy_user: legacyUser, - blurb: blurb, - }); + userProfileBlurbsLegacyUserBlurbPath( + user: string, + legacyUser: string, + blurb: string, + ) { + return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.render( + { + user: user, + legacy_user: legacyUser, + blurb: blurb, + }, + ); } /** @@ -2147,8 +2688,12 @@ export class MessagingClient { * A fully-qualified path representing user_profile_blurbs_legacy_user_blurb resource. * @returns {string} A string representing the user. */ - matchUserFromUserProfileBlurbsLegacyUserBlurbName(userProfileBlurbsLegacyUserBlurbName: string) { - return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match(userProfileBlurbsLegacyUserBlurbName).user; + matchUserFromUserProfileBlurbsLegacyUserBlurbName( + userProfileBlurbsLegacyUserBlurbName: string, + ) { + return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match( + userProfileBlurbsLegacyUserBlurbName, + ).user; } /** @@ -2158,8 +2703,12 @@ export class MessagingClient { * A fully-qualified path representing user_profile_blurbs_legacy_user_blurb resource. * @returns {string} A string representing the legacy_user. */ - matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName(userProfileBlurbsLegacyUserBlurbName: string) { - return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match(userProfileBlurbsLegacyUserBlurbName).legacy_user; + matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName( + userProfileBlurbsLegacyUserBlurbName: string, + ) { + return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match( + userProfileBlurbsLegacyUserBlurbName, + ).legacy_user; } /** @@ -2169,8 +2718,12 @@ export class MessagingClient { * A fully-qualified path representing user_profile_blurbs_legacy_user_blurb resource. * @returns {string} A string representing the blurb. */ - matchBlurbFromUserProfileBlurbsLegacyUserBlurbName(userProfileBlurbsLegacyUserBlurbName: string) { - return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match(userProfileBlurbsLegacyUserBlurbName).blurb; + matchBlurbFromUserProfileBlurbsLegacyUserBlurbName( + userProfileBlurbsLegacyUserBlurbName: string, + ) { + return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match( + userProfileBlurbsLegacyUserBlurbName, + ).blurb; } /** @@ -2181,7 +2734,7 @@ export class MessagingClient { */ close(): Promise { if (this.messagingStub && !this._terminated) { - return this.messagingStub.then(stub => { + return this.messagingStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -2190,4 +2743,4 @@ export class MessagingClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/core/generator/gapic-generator-typescript/baselines/showcase-esm/esm/src/v1beta1/sequence_service_client.ts.baseline b/core/generator/gapic-generator-typescript/baselines/showcase-esm/esm/src/v1beta1/sequence_service_client.ts.baseline index d4751443cbb4..c808fa6c1401 100644 --- a/core/generator/gapic-generator-typescript/baselines/showcase-esm/esm/src/v1beta1/sequence_service_client.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/showcase-esm/esm/src/v1beta1/sequence_service_client.ts.baseline @@ -18,15 +18,20 @@ /* global window */ import * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions} from 'google-gax'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, +} from 'google-gax'; // @ts-ignore import type * as protos from '../../../protos/protos.js'; import * as sequence_service_client_config from './sequence_service_client_config.json'; import fs from 'fs'; import path from 'path'; -import {fileURLToPath} from 'url'; -import {getJSON} from '../json-helper.cjs'; +import { fileURLToPath } from 'url'; +import { getJSON } from '../json-helper.cjs'; // @ts-ignore const dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -36,15 +41,15 @@ const dirname = path.dirname(fileURLToPath(import.meta.url)); * This file defines retry strategy and timeouts for all API methods in this library. */ const gapicConfig = getJSON( - path.join(dirname, 'sequence_service_client_config.json') + path.join(dirname, 'sequence_service_client_config.json'), ); const jsonProtos = getJSON( - path.join(dirname, '..', '..', '..', 'protos/protos.json') + path.join(dirname, '..', '..', '..', 'protos/protos.json'), ); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; const version = getJSON( - path.join(dirname, '..', '..', '..', '..', 'package.json') + path.join(dirname, '..', '..', '..', '..', 'package.json'), ).version; /** @@ -58,7 +63,7 @@ export class SequenceServiceClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('showcase'); @@ -70,9 +75,9 @@ export class SequenceServiceClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; - sequenceServiceStub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; + sequenceServiceStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of SequenceServiceClient. @@ -114,21 +119,42 @@ export class SequenceServiceClient { * const client = new SequenceServiceClient({fallback: 'rest'}, gax); * ``` */ - constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { // Ensure that options include all the required fields. const staticMembers = this.constructor as typeof SequenceServiceClient; - if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { - throw new Error('Please set either universe_domain or universeDomain, but not both.'); + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); } - const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; - this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; this._servicePath = 'localhost'; - const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; - const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // Request numeric enum values if REST transport is used. opts.numericEnums = true; @@ -153,7 +179,7 @@ export class SequenceServiceClient { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; @@ -170,10 +196,7 @@ export class SequenceServiceClient { const isEsm = true; const isEsmString = isEsm ? '-esm' : '-cjs'; // Determine the client header string. - const clientHeader = [ - `gax/${this._gaxModule.version}`, - `gapic/${version}`, - ]; + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/{process.versions.node}${isEsmString}`); } else { @@ -181,7 +204,7 @@ export class SequenceServiceClient { } if (!opts.fallback) { clientHeader.push(`grpc/${this._gaxGrpc.grpcVersion}`); - } else if (opts.fallback === 'rest' ) { + } else if (opts.fallback === 'rest') { clientHeader.push(`rest/${this._gaxGrpc.grpcVersion}`); } if (opts.libName && opts.libVersion) { @@ -189,51 +212,53 @@ export class SequenceServiceClient { } // Load the applicable protos. - this._protos = this._gaxGrpc.loadProtoJSON(jsonProtos as gax.protobuf.INamespace); + this._protos = this._gaxGrpc.loadProtoJSON( + jsonProtos as gax.protobuf.INamespace, + ); // This API contains "path templates"; forward-slash-separated // identifiers to uniquely identify resources within the API. // Create useful helper objects for these. this.pathTemplates = { blueprintPathTemplate: new this._gaxModule.PathTemplate( - 'sessions/{session}/tests/{test}/blueprints/{blueprint}' - ), - roomPathTemplate: new this._gaxModule.PathTemplate( - 'rooms/{room}' + 'sessions/{session}/tests/{test}/blueprints/{blueprint}', ), + roomPathTemplate: new this._gaxModule.PathTemplate('rooms/{room}'), roomBlurbPathTemplate: new this._gaxModule.PathTemplate( - 'rooms/{room}/blurbs/{blurb}' + 'rooms/{room}/blurbs/{blurb}', ), roomBlurbsLegacyRoomBlurbPathTemplate: new this._gaxModule.PathTemplate( - 'rooms/{room}/blurbs/legacy/{legacy_room}.{blurb}' + 'rooms/{room}/blurbs/legacy/{legacy_room}.{blurb}', ), sequencePathTemplate: new this._gaxModule.PathTemplate( - 'sequences/{sequence}' + 'sequences/{sequence}', ), sequenceReportPathTemplate: new this._gaxModule.PathTemplate( - 'sequences/{sequence}/sequenceReport' + 'sequences/{sequence}/sequenceReport', ), sessionPathTemplate: new this._gaxModule.PathTemplate( - 'sessions/{session}' + 'sessions/{session}', ), testPathTemplate: new this._gaxModule.PathTemplate( - 'sessions/{session}/tests/{test}' - ), - userPathTemplate: new this._gaxModule.PathTemplate( - 'users/{user}' + 'sessions/{session}/tests/{test}', ), + userPathTemplate: new this._gaxModule.PathTemplate('users/{user}'), userProfileBlurbPathTemplate: new this._gaxModule.PathTemplate( - 'users/{user}/profile/blurbs/{blurb}' - ), - userProfileBlurbsLegacyUserBlurbPathTemplate: new this._gaxModule.PathTemplate( - 'users/{user}/profile/blurbs/legacy/{legacy_user}~{blurb}' + 'users/{user}/profile/blurbs/{blurb}', ), + userProfileBlurbsLegacyUserBlurbPathTemplate: + new this._gaxModule.PathTemplate( + 'users/{user}/profile/blurbs/legacy/{legacy_user}~{blurb}', + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.showcase.v1beta1.SequenceService', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.showcase.v1beta1.SequenceService', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + { 'x-goog-api-client': clientHeader.join(' ') }, + ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -264,36 +289,44 @@ export class SequenceServiceClient { // Put together the "service stub" for // google.showcase.v1beta1.SequenceService. this.sequenceServiceStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.showcase.v1beta1.SequenceService') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.showcase.v1beta1.SequenceService', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.showcase.v1beta1.SequenceService, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts, + this._providedCustomServicePath, + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const sequenceServiceStubMethods = - ['createSequence', 'getSequenceReport', 'attemptSequence']; + const sequenceServiceStubMethods = [ + 'createSequence', + 'getSequenceReport', + 'attemptSequence', + ]; for (const methodName of sequenceServiceStubMethods) { const callPromise = this.sequenceServiceStub.then( - stub => (...args: Array<{}>) => { - if (this._terminated) { - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error|null|undefined) => () => { + (stub) => + (...args: Array<{}>) => { + if (this._terminated) { + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { throw err; - }); + }, + ); - const descriptor = - undefined; + const descriptor = undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -308,8 +341,14 @@ export class SequenceServiceClient { * @returns {string} The DNS address for this service. */ static get servicePath() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'localhost'; } @@ -321,8 +360,14 @@ export class SequenceServiceClient { * @returns {string} The DNS address for this service. */ static get apiEndpoint() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'localhost'; } @@ -362,8 +407,9 @@ export class SequenceServiceClient { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId(callback?: Callback): - Promise|void { + getProjectId( + callback?: Callback, + ): Promise | void { if (callback) { this.auth.getProjectId(callback); return; @@ -374,273 +420,385 @@ export class SequenceServiceClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Creates a sequence. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.showcase.v1beta1.Sequence} request.sequence - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.Sequence|Sequence}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/sequence_service.create_sequence.js - * region_tag:localhost_v1beta1_generated_SequenceService_CreateSequence_async - */ + /** + * Creates a sequence. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.showcase.v1beta1.Sequence} request.sequence + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.Sequence|Sequence}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/sequence_service.create_sequence.js + * region_tag:localhost_v1beta1_generated_SequenceService_CreateSequence_async + */ createSequence( - request?: protos.google.showcase.v1beta1.ICreateSequenceRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.ISequence, - protos.google.showcase.v1beta1.ICreateSequenceRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.ICreateSequenceRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.ISequence, + protos.google.showcase.v1beta1.ICreateSequenceRequest | undefined, + {} | undefined, + ] + >; createSequence( - request: protos.google.showcase.v1beta1.ICreateSequenceRequest, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.ISequence, - protos.google.showcase.v1beta1.ICreateSequenceRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.ICreateSequenceRequest, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.ISequence, + protos.google.showcase.v1beta1.ICreateSequenceRequest | null | undefined, + {} | null | undefined + >, + ): void; createSequence( - request: protos.google.showcase.v1beta1.ICreateSequenceRequest, - callback: Callback< - protos.google.showcase.v1beta1.ISequence, - protos.google.showcase.v1beta1.ICreateSequenceRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.ICreateSequenceRequest, + callback: Callback< + protos.google.showcase.v1beta1.ISequence, + protos.google.showcase.v1beta1.ICreateSequenceRequest | null | undefined, + {} | null | undefined + >, + ): void; createSequence( - request?: protos.google.showcase.v1beta1.ICreateSequenceRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.showcase.v1beta1.ISequence, - protos.google.showcase.v1beta1.ICreateSequenceRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.showcase.v1beta1.ICreateSequenceRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.ISequence, - protos.google.showcase.v1beta1.ICreateSequenceRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.ISequence, - protos.google.showcase.v1beta1.ICreateSequenceRequest|undefined, {}|undefined - ]>|void { + | protos.google.showcase.v1beta1.ICreateSequenceRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.ISequence, + protos.google.showcase.v1beta1.ICreateSequenceRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.ISequence, + protos.google.showcase.v1beta1.ICreateSequenceRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('createSequence request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.ISequence, - protos.google.showcase.v1beta1.ICreateSequenceRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.ISequence, + | protos.google.showcase.v1beta1.ICreateSequenceRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createSequence response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.createSequence(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.ISequence, - protos.google.showcase.v1beta1.ICreateSequenceRequest|undefined, {}|undefined - ]) => { - this._log.info('createSequence response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createSequence(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.ISequence, + protos.google.showcase.v1beta1.ICreateSequenceRequest | undefined, + {} | undefined, + ]) => { + this._log.info('createSequence response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Retrieves a sequence. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.SequenceReport|SequenceReport}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/sequence_service.get_sequence_report.js - * region_tag:localhost_v1beta1_generated_SequenceService_GetSequenceReport_async - */ + /** + * Retrieves a sequence. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.SequenceReport|SequenceReport}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/sequence_service.get_sequence_report.js + * region_tag:localhost_v1beta1_generated_SequenceService_GetSequenceReport_async + */ getSequenceReport( - request?: protos.google.showcase.v1beta1.IGetSequenceReportRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.ISequenceReport, - protos.google.showcase.v1beta1.IGetSequenceReportRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IGetSequenceReportRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.ISequenceReport, + protos.google.showcase.v1beta1.IGetSequenceReportRequest | undefined, + {} | undefined, + ] + >; getSequenceReport( - request: protos.google.showcase.v1beta1.IGetSequenceReportRequest, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.ISequenceReport, - protos.google.showcase.v1beta1.IGetSequenceReportRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IGetSequenceReportRequest, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.ISequenceReport, + | protos.google.showcase.v1beta1.IGetSequenceReportRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getSequenceReport( - request: protos.google.showcase.v1beta1.IGetSequenceReportRequest, - callback: Callback< - protos.google.showcase.v1beta1.ISequenceReport, - protos.google.showcase.v1beta1.IGetSequenceReportRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IGetSequenceReportRequest, + callback: Callback< + protos.google.showcase.v1beta1.ISequenceReport, + | protos.google.showcase.v1beta1.IGetSequenceReportRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getSequenceReport( - request?: protos.google.showcase.v1beta1.IGetSequenceReportRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.showcase.v1beta1.ISequenceReport, - protos.google.showcase.v1beta1.IGetSequenceReportRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.showcase.v1beta1.IGetSequenceReportRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.ISequenceReport, - protos.google.showcase.v1beta1.IGetSequenceReportRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.ISequenceReport, - protos.google.showcase.v1beta1.IGetSequenceReportRequest|undefined, {}|undefined - ]>|void { + | protos.google.showcase.v1beta1.IGetSequenceReportRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.ISequenceReport, + | protos.google.showcase.v1beta1.IGetSequenceReportRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.ISequenceReport, + protos.google.showcase.v1beta1.IGetSequenceReportRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getSequenceReport request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.ISequenceReport, - protos.google.showcase.v1beta1.IGetSequenceReportRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.ISequenceReport, + | protos.google.showcase.v1beta1.IGetSequenceReportRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getSequenceReport response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.getSequenceReport(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.ISequenceReport, - protos.google.showcase.v1beta1.IGetSequenceReportRequest|undefined, {}|undefined - ]) => { - this._log.info('getSequenceReport response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getSequenceReport(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.ISequenceReport, + protos.google.showcase.v1beta1.IGetSequenceReportRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getSequenceReport response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Attempts a sequence. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/sequence_service.attempt_sequence.js - * region_tag:localhost_v1beta1_generated_SequenceService_AttemptSequence_async - */ + /** + * Attempts a sequence. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/sequence_service.attempt_sequence.js + * region_tag:localhost_v1beta1_generated_SequenceService_AttemptSequence_async + */ attemptSequence( - request?: protos.google.showcase.v1beta1.IAttemptSequenceRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IAttemptSequenceRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IAttemptSequenceRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IAttemptSequenceRequest | undefined, + {} | undefined, + ] + >; attemptSequence( - request: protos.google.showcase.v1beta1.IAttemptSequenceRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IAttemptSequenceRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IAttemptSequenceRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IAttemptSequenceRequest | null | undefined, + {} | null | undefined + >, + ): void; attemptSequence( - request: protos.google.showcase.v1beta1.IAttemptSequenceRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IAttemptSequenceRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IAttemptSequenceRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IAttemptSequenceRequest | null | undefined, + {} | null | undefined + >, + ): void; attemptSequence( - request?: protos.google.showcase.v1beta1.IAttemptSequenceRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IAttemptSequenceRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.showcase.v1beta1.IAttemptSequenceRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IAttemptSequenceRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IAttemptSequenceRequest|undefined, {}|undefined - ]>|void { + | protos.google.showcase.v1beta1.IAttemptSequenceRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IAttemptSequenceRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IAttemptSequenceRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('attemptSequence request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IAttemptSequenceRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.showcase.v1beta1.IAttemptSequenceRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('attemptSequence response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.attemptSequence(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IAttemptSequenceRequest|undefined, {}|undefined - ]) => { - this._log.info('attemptSequence response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .attemptSequence(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IAttemptSequenceRequest | undefined, + {} | undefined, + ]) => { + this._log.info('attemptSequence response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); @@ -658,7 +816,7 @@ export class SequenceServiceClient { * @param {string} blueprint * @returns {string} Resource name string. */ - blueprintPath(session:string,test:string,blueprint:string) { + blueprintPath(session: string, test: string, blueprint: string) { return this.pathTemplates.blueprintPathTemplate.render({ session: session, test: test, @@ -674,7 +832,8 @@ export class SequenceServiceClient { * @returns {string} A string representing the session. */ matchSessionFromBlueprintName(blueprintName: string) { - return this.pathTemplates.blueprintPathTemplate.match(blueprintName).session; + return this.pathTemplates.blueprintPathTemplate.match(blueprintName) + .session; } /** @@ -696,7 +855,8 @@ export class SequenceServiceClient { * @returns {string} A string representing the blueprint. */ matchBlueprintFromBlueprintName(blueprintName: string) { - return this.pathTemplates.blueprintPathTemplate.match(blueprintName).blueprint; + return this.pathTemplates.blueprintPathTemplate.match(blueprintName) + .blueprint; } /** @@ -705,7 +865,7 @@ export class SequenceServiceClient { * @param {string} room * @returns {string} Resource name string. */ - roomPath(room:string) { + roomPath(room: string) { return this.pathTemplates.roomPathTemplate.render({ room: room, }); @@ -729,7 +889,7 @@ export class SequenceServiceClient { * @param {string} blurb * @returns {string} Resource name string. */ - roomBlurbPath(room:string,blurb:string) { + roomBlurbPath(room: string, blurb: string) { return this.pathTemplates.roomBlurbPathTemplate.render({ room: room, blurb: blurb, @@ -766,7 +926,11 @@ export class SequenceServiceClient { * @param {string} blurb * @returns {string} Resource name string. */ - roomBlurbsLegacyRoomBlurbPath(room:string,legacyRoom:string,blurb:string) { + roomBlurbsLegacyRoomBlurbPath( + room: string, + legacyRoom: string, + blurb: string, + ) { return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.render({ room: room, legacy_room: legacyRoom, @@ -781,8 +945,12 @@ export class SequenceServiceClient { * A fully-qualified path representing room_blurbs_legacy_room_blurb resource. * @returns {string} A string representing the room. */ - matchRoomFromRoomBlurbsLegacyRoomBlurbName(roomBlurbsLegacyRoomBlurbName: string) { - return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match(roomBlurbsLegacyRoomBlurbName).room; + matchRoomFromRoomBlurbsLegacyRoomBlurbName( + roomBlurbsLegacyRoomBlurbName: string, + ) { + return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match( + roomBlurbsLegacyRoomBlurbName, + ).room; } /** @@ -792,8 +960,12 @@ export class SequenceServiceClient { * A fully-qualified path representing room_blurbs_legacy_room_blurb resource. * @returns {string} A string representing the legacy_room. */ - matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName(roomBlurbsLegacyRoomBlurbName: string) { - return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match(roomBlurbsLegacyRoomBlurbName).legacy_room; + matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName( + roomBlurbsLegacyRoomBlurbName: string, + ) { + return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match( + roomBlurbsLegacyRoomBlurbName, + ).legacy_room; } /** @@ -803,8 +975,12 @@ export class SequenceServiceClient { * A fully-qualified path representing room_blurbs_legacy_room_blurb resource. * @returns {string} A string representing the blurb. */ - matchBlurbFromRoomBlurbsLegacyRoomBlurbName(roomBlurbsLegacyRoomBlurbName: string) { - return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match(roomBlurbsLegacyRoomBlurbName).blurb; + matchBlurbFromRoomBlurbsLegacyRoomBlurbName( + roomBlurbsLegacyRoomBlurbName: string, + ) { + return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match( + roomBlurbsLegacyRoomBlurbName, + ).blurb; } /** @@ -813,7 +989,7 @@ export class SequenceServiceClient { * @param {string} sequence * @returns {string} Resource name string. */ - sequencePath(sequence:string) { + sequencePath(sequence: string) { return this.pathTemplates.sequencePathTemplate.render({ sequence: sequence, }); @@ -836,7 +1012,7 @@ export class SequenceServiceClient { * @param {string} sequence * @returns {string} Resource name string. */ - sequenceReportPath(sequence:string) { + sequenceReportPath(sequence: string) { return this.pathTemplates.sequenceReportPathTemplate.render({ sequence: sequence, }); @@ -850,7 +1026,9 @@ export class SequenceServiceClient { * @returns {string} A string representing the sequence. */ matchSequenceFromSequenceReportName(sequenceReportName: string) { - return this.pathTemplates.sequenceReportPathTemplate.match(sequenceReportName).sequence; + return this.pathTemplates.sequenceReportPathTemplate.match( + sequenceReportName, + ).sequence; } /** @@ -859,7 +1037,7 @@ export class SequenceServiceClient { * @param {string} session * @returns {string} Resource name string. */ - sessionPath(session:string) { + sessionPath(session: string) { return this.pathTemplates.sessionPathTemplate.render({ session: session, }); @@ -883,7 +1061,7 @@ export class SequenceServiceClient { * @param {string} test * @returns {string} Resource name string. */ - testPath(session:string,test:string) { + testPath(session: string, test: string) { return this.pathTemplates.testPathTemplate.render({ session: session, test: test, @@ -918,7 +1096,7 @@ export class SequenceServiceClient { * @param {string} user * @returns {string} Resource name string. */ - userPath(user:string) { + userPath(user: string) { return this.pathTemplates.userPathTemplate.render({ user: user, }); @@ -942,7 +1120,7 @@ export class SequenceServiceClient { * @param {string} blurb * @returns {string} Resource name string. */ - userProfileBlurbPath(user:string,blurb:string) { + userProfileBlurbPath(user: string, blurb: string) { return this.pathTemplates.userProfileBlurbPathTemplate.render({ user: user, blurb: blurb, @@ -957,7 +1135,9 @@ export class SequenceServiceClient { * @returns {string} A string representing the user. */ matchUserFromUserProfileBlurbName(userProfileBlurbName: string) { - return this.pathTemplates.userProfileBlurbPathTemplate.match(userProfileBlurbName).user; + return this.pathTemplates.userProfileBlurbPathTemplate.match( + userProfileBlurbName, + ).user; } /** @@ -968,7 +1148,9 @@ export class SequenceServiceClient { * @returns {string} A string representing the blurb. */ matchBlurbFromUserProfileBlurbName(userProfileBlurbName: string) { - return this.pathTemplates.userProfileBlurbPathTemplate.match(userProfileBlurbName).blurb; + return this.pathTemplates.userProfileBlurbPathTemplate.match( + userProfileBlurbName, + ).blurb; } /** @@ -979,12 +1161,18 @@ export class SequenceServiceClient { * @param {string} blurb * @returns {string} Resource name string. */ - userProfileBlurbsLegacyUserBlurbPath(user:string,legacyUser:string,blurb:string) { - return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.render({ - user: user, - legacy_user: legacyUser, - blurb: blurb, - }); + userProfileBlurbsLegacyUserBlurbPath( + user: string, + legacyUser: string, + blurb: string, + ) { + return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.render( + { + user: user, + legacy_user: legacyUser, + blurb: blurb, + }, + ); } /** @@ -994,8 +1182,12 @@ export class SequenceServiceClient { * A fully-qualified path representing user_profile_blurbs_legacy_user_blurb resource. * @returns {string} A string representing the user. */ - matchUserFromUserProfileBlurbsLegacyUserBlurbName(userProfileBlurbsLegacyUserBlurbName: string) { - return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match(userProfileBlurbsLegacyUserBlurbName).user; + matchUserFromUserProfileBlurbsLegacyUserBlurbName( + userProfileBlurbsLegacyUserBlurbName: string, + ) { + return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match( + userProfileBlurbsLegacyUserBlurbName, + ).user; } /** @@ -1005,8 +1197,12 @@ export class SequenceServiceClient { * A fully-qualified path representing user_profile_blurbs_legacy_user_blurb resource. * @returns {string} A string representing the legacy_user. */ - matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName(userProfileBlurbsLegacyUserBlurbName: string) { - return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match(userProfileBlurbsLegacyUserBlurbName).legacy_user; + matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName( + userProfileBlurbsLegacyUserBlurbName: string, + ) { + return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match( + userProfileBlurbsLegacyUserBlurbName, + ).legacy_user; } /** @@ -1016,8 +1212,12 @@ export class SequenceServiceClient { * A fully-qualified path representing user_profile_blurbs_legacy_user_blurb resource. * @returns {string} A string representing the blurb. */ - matchBlurbFromUserProfileBlurbsLegacyUserBlurbName(userProfileBlurbsLegacyUserBlurbName: string) { - return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match(userProfileBlurbsLegacyUserBlurbName).blurb; + matchBlurbFromUserProfileBlurbsLegacyUserBlurbName( + userProfileBlurbsLegacyUserBlurbName: string, + ) { + return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match( + userProfileBlurbsLegacyUserBlurbName, + ).blurb; } /** @@ -1028,7 +1228,7 @@ export class SequenceServiceClient { */ close(): Promise { if (this.sequenceServiceStub && !this._terminated) { - return this.sequenceServiceStub.then(stub => { + return this.sequenceServiceStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -1036,4 +1236,4 @@ export class SequenceServiceClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/core/generator/gapic-generator-typescript/baselines/showcase-esm/esm/src/v1beta1/testing_client.ts.baseline b/core/generator/gapic-generator-typescript/baselines/showcase-esm/esm/src/v1beta1/testing_client.ts.baseline index d176ece1e950..5be603092902 100644 --- a/core/generator/gapic-generator-typescript/baselines/showcase-esm/esm/src/v1beta1/testing_client.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/showcase-esm/esm/src/v1beta1/testing_client.ts.baseline @@ -18,15 +18,22 @@ /* global window */ import * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions, PaginationCallback, GaxCall} from 'google-gax'; -import {Transform} from 'stream'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + PaginationCallback, + GaxCall, +} from 'google-gax'; +import { Transform } from 'stream'; // @ts-ignore import type * as protos from '../../../protos/protos.js'; import * as testing_client_config from './testing_client_config.json'; import fs from 'fs'; import path from 'path'; -import {fileURLToPath} from 'url'; -import {getJSON} from '../json-helper.cjs'; +import { fileURLToPath } from 'url'; +import { getJSON } from '../json-helper.cjs'; // @ts-ignore const dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -35,16 +42,14 @@ const dirname = path.dirname(fileURLToPath(import.meta.url)); * `src/v1beta1/testing_client_config.json`. * This file defines retry strategy and timeouts for all API methods in this library. */ -const gapicConfig = getJSON( - path.join(dirname, 'testing_client_config.json') -); +const gapicConfig = getJSON(path.join(dirname, 'testing_client_config.json')); const jsonProtos = getJSON( - path.join(dirname, '..', '..', '..', 'protos/protos.json') + path.join(dirname, '..', '..', '..', 'protos/protos.json'), ); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; const version = getJSON( - path.join(dirname, '..', '..', '..', '..', 'package.json') + path.join(dirname, '..', '..', '..', '..', 'package.json'), ).version; /** @@ -60,7 +65,7 @@ export class TestingClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('showcase'); @@ -72,9 +77,9 @@ export class TestingClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; - testingStub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; + testingStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of TestingClient. @@ -116,21 +121,42 @@ export class TestingClient { * const client = new TestingClient({fallback: 'rest'}, gax); * ``` */ - constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { // Ensure that options include all the required fields. const staticMembers = this.constructor as typeof TestingClient; - if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { - throw new Error('Please set either universe_domain or universeDomain, but not both.'); + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); } - const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; - this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; this._servicePath = 'localhost'; - const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; - const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // Request numeric enum values if REST transport is used. opts.numericEnums = true; @@ -155,7 +181,7 @@ export class TestingClient { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; @@ -172,10 +198,7 @@ export class TestingClient { const isEsm = true; const isEsmString = isEsm ? '-esm' : '-cjs'; // Determine the client header string. - const clientHeader = [ - `gax/${this._gaxModule.version}`, - `gapic/${version}`, - ]; + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/{process.versions.node}${isEsmString}`); } else { @@ -183,7 +206,7 @@ export class TestingClient { } if (!opts.fallback) { clientHeader.push(`grpc/${this._gaxGrpc.grpcVersion}`); - } else if (opts.fallback === 'rest' ) { + } else if (opts.fallback === 'rest') { clientHeader.push(`rest/${this._gaxGrpc.grpcVersion}`); } if (opts.libName && opts.libVersion) { @@ -191,61 +214,69 @@ export class TestingClient { } // Load the applicable protos. - this._protos = this._gaxGrpc.loadProtoJSON(jsonProtos as gax.protobuf.INamespace); + this._protos = this._gaxGrpc.loadProtoJSON( + jsonProtos as gax.protobuf.INamespace, + ); // This API contains "path templates"; forward-slash-separated // identifiers to uniquely identify resources within the API. // Create useful helper objects for these. this.pathTemplates = { blueprintPathTemplate: new this._gaxModule.PathTemplate( - 'sessions/{session}/tests/{test}/blueprints/{blueprint}' - ), - roomPathTemplate: new this._gaxModule.PathTemplate( - 'rooms/{room}' + 'sessions/{session}/tests/{test}/blueprints/{blueprint}', ), + roomPathTemplate: new this._gaxModule.PathTemplate('rooms/{room}'), roomBlurbPathTemplate: new this._gaxModule.PathTemplate( - 'rooms/{room}/blurbs/{blurb}' + 'rooms/{room}/blurbs/{blurb}', ), roomBlurbsLegacyRoomBlurbPathTemplate: new this._gaxModule.PathTemplate( - 'rooms/{room}/blurbs/legacy/{legacy_room}.{blurb}' + 'rooms/{room}/blurbs/legacy/{legacy_room}.{blurb}', ), sequencePathTemplate: new this._gaxModule.PathTemplate( - 'sequences/{sequence}' + 'sequences/{sequence}', ), sequenceReportPathTemplate: new this._gaxModule.PathTemplate( - 'sequences/{sequence}/sequenceReport' + 'sequences/{sequence}/sequenceReport', ), sessionPathTemplate: new this._gaxModule.PathTemplate( - 'sessions/{session}' + 'sessions/{session}', ), testPathTemplate: new this._gaxModule.PathTemplate( - 'sessions/{session}/tests/{test}' - ), - userPathTemplate: new this._gaxModule.PathTemplate( - 'users/{user}' + 'sessions/{session}/tests/{test}', ), + userPathTemplate: new this._gaxModule.PathTemplate('users/{user}'), userProfileBlurbPathTemplate: new this._gaxModule.PathTemplate( - 'users/{user}/profile/blurbs/{blurb}' - ), - userProfileBlurbsLegacyUserBlurbPathTemplate: new this._gaxModule.PathTemplate( - 'users/{user}/profile/blurbs/legacy/{legacy_user}~{blurb}' + 'users/{user}/profile/blurbs/{blurb}', ), + userProfileBlurbsLegacyUserBlurbPathTemplate: + new this._gaxModule.PathTemplate( + 'users/{user}/profile/blurbs/legacy/{legacy_user}~{blurb}', + ), }; // Some of the methods on this service return "paged" results, // (e.g. 50 results at a time, with tokens to get subsequent // pages). Denote the keys used for pagination and results. this.descriptors.page = { - listSessions: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'sessions'), - listTests: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'tests') + listSessions: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'sessions', + ), + listTests: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'tests', + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.showcase.v1beta1.Testing', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.showcase.v1beta1.Testing', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + { 'x-goog-api-client': clientHeader.join(' ') }, + ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -276,37 +307,49 @@ export class TestingClient { // Put together the "service stub" for // google.showcase.v1beta1.Testing. this.testingStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.showcase.v1beta1.Testing') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.showcase.v1beta1.Testing', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.showcase.v1beta1.Testing, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts, + this._providedCustomServicePath, + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const testingStubMethods = - ['createSession', 'getSession', 'listSessions', 'deleteSession', 'reportSession', 'listTests', 'deleteTest', 'verifyTest']; + const testingStubMethods = [ + 'createSession', + 'getSession', + 'listSessions', + 'deleteSession', + 'reportSession', + 'listTests', + 'deleteTest', + 'verifyTest', + ]; for (const methodName of testingStubMethods) { const callPromise = this.testingStub.then( - stub => (...args: Array<{}>) => { - if (this._terminated) { - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error|null|undefined) => () => { + (stub) => + (...args: Array<{}>) => { + if (this._terminated) { + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { throw err; - }); + }, + ); - const descriptor = - this.descriptors.page[methodName] || - undefined; + const descriptor = this.descriptors.page[methodName] || undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -321,8 +364,14 @@ export class TestingClient { * @returns {string} The DNS address for this service. */ static get servicePath() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'localhost'; } @@ -334,8 +383,14 @@ export class TestingClient { * @returns {string} The DNS address for this service. */ static get apiEndpoint() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'localhost'; } @@ -375,8 +430,9 @@ export class TestingClient { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId(callback?: Callback): - Promise|void { + getProjectId( + callback?: Callback, + ): Promise | void { if (callback) { this.auth.getProjectId(callback); return; @@ -387,650 +443,869 @@ export class TestingClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Creates a new testing session. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.showcase.v1beta1.Session} request.session - * The session to be created. - * Sessions are immutable once they are created (although they can - * be deleted). - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.Session|Session}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/testing.create_session.js - * region_tag:localhost_v1beta1_generated_Testing_CreateSession_async - */ + /** + * Creates a new testing session. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.showcase.v1beta1.Session} request.session + * The session to be created. + * Sessions are immutable once they are created (although they can + * be deleted). + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.Session|Session}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/testing.create_session.js + * region_tag:localhost_v1beta1_generated_Testing_CreateSession_async + */ createSession( - request?: protos.google.showcase.v1beta1.ICreateSessionRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.ISession, - protos.google.showcase.v1beta1.ICreateSessionRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.ICreateSessionRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.ISession, + protos.google.showcase.v1beta1.ICreateSessionRequest | undefined, + {} | undefined, + ] + >; createSession( - request: protos.google.showcase.v1beta1.ICreateSessionRequest, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.ISession, - protos.google.showcase.v1beta1.ICreateSessionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.ICreateSessionRequest, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.ISession, + protos.google.showcase.v1beta1.ICreateSessionRequest | null | undefined, + {} | null | undefined + >, + ): void; createSession( - request: protos.google.showcase.v1beta1.ICreateSessionRequest, - callback: Callback< - protos.google.showcase.v1beta1.ISession, - protos.google.showcase.v1beta1.ICreateSessionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.ICreateSessionRequest, + callback: Callback< + protos.google.showcase.v1beta1.ISession, + protos.google.showcase.v1beta1.ICreateSessionRequest | null | undefined, + {} | null | undefined + >, + ): void; createSession( - request?: protos.google.showcase.v1beta1.ICreateSessionRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.showcase.v1beta1.ISession, - protos.google.showcase.v1beta1.ICreateSessionRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.showcase.v1beta1.ICreateSessionRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.ISession, - protos.google.showcase.v1beta1.ICreateSessionRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.ISession, - protos.google.showcase.v1beta1.ICreateSessionRequest|undefined, {}|undefined - ]>|void { + | protos.google.showcase.v1beta1.ICreateSessionRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.ISession, + protos.google.showcase.v1beta1.ICreateSessionRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.ISession, + protos.google.showcase.v1beta1.ICreateSessionRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('createSession request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.ISession, - protos.google.showcase.v1beta1.ICreateSessionRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.ISession, + | protos.google.showcase.v1beta1.ICreateSessionRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createSession response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.createSession(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.ISession, - protos.google.showcase.v1beta1.ICreateSessionRequest|undefined, {}|undefined - ]) => { - this._log.info('createSession response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createSession(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.ISession, + protos.google.showcase.v1beta1.ICreateSessionRequest | undefined, + {} | undefined, + ]) => { + this._log.info('createSession response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Gets a testing session. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * The session to be retrieved. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.Session|Session}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/testing.get_session.js - * region_tag:localhost_v1beta1_generated_Testing_GetSession_async - */ + /** + * Gets a testing session. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * The session to be retrieved. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.Session|Session}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/testing.get_session.js + * region_tag:localhost_v1beta1_generated_Testing_GetSession_async + */ getSession( - request?: protos.google.showcase.v1beta1.IGetSessionRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.ISession, - protos.google.showcase.v1beta1.IGetSessionRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IGetSessionRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.ISession, + protos.google.showcase.v1beta1.IGetSessionRequest | undefined, + {} | undefined, + ] + >; getSession( - request: protos.google.showcase.v1beta1.IGetSessionRequest, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.ISession, - protos.google.showcase.v1beta1.IGetSessionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IGetSessionRequest, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.ISession, + protos.google.showcase.v1beta1.IGetSessionRequest | null | undefined, + {} | null | undefined + >, + ): void; getSession( - request: protos.google.showcase.v1beta1.IGetSessionRequest, - callback: Callback< - protos.google.showcase.v1beta1.ISession, - protos.google.showcase.v1beta1.IGetSessionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IGetSessionRequest, + callback: Callback< + protos.google.showcase.v1beta1.ISession, + protos.google.showcase.v1beta1.IGetSessionRequest | null | undefined, + {} | null | undefined + >, + ): void; getSession( - request?: protos.google.showcase.v1beta1.IGetSessionRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.showcase.v1beta1.ISession, - protos.google.showcase.v1beta1.IGetSessionRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.showcase.v1beta1.IGetSessionRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.ISession, - protos.google.showcase.v1beta1.IGetSessionRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.ISession, - protos.google.showcase.v1beta1.IGetSessionRequest|undefined, {}|undefined - ]>|void { + protos.google.showcase.v1beta1.IGetSessionRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.ISession, + protos.google.showcase.v1beta1.IGetSessionRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.ISession, + protos.google.showcase.v1beta1.IGetSessionRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getSession request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.ISession, - protos.google.showcase.v1beta1.IGetSessionRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.ISession, + protos.google.showcase.v1beta1.IGetSessionRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getSession response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.getSession(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.ISession, - protos.google.showcase.v1beta1.IGetSessionRequest|undefined, {}|undefined - ]) => { - this._log.info('getSession response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getSession(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.ISession, + protos.google.showcase.v1beta1.IGetSessionRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getSession response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Delete a test session. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * The session to be deleted. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/testing.delete_session.js - * region_tag:localhost_v1beta1_generated_Testing_DeleteSession_async - */ + /** + * Delete a test session. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * The session to be deleted. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/testing.delete_session.js + * region_tag:localhost_v1beta1_generated_Testing_DeleteSession_async + */ deleteSession( - request?: protos.google.showcase.v1beta1.IDeleteSessionRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteSessionRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IDeleteSessionRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteSessionRequest | undefined, + {} | undefined, + ] + >; deleteSession( - request: protos.google.showcase.v1beta1.IDeleteSessionRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteSessionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IDeleteSessionRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteSessionRequest | null | undefined, + {} | null | undefined + >, + ): void; deleteSession( - request: protos.google.showcase.v1beta1.IDeleteSessionRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteSessionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IDeleteSessionRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteSessionRequest | null | undefined, + {} | null | undefined + >, + ): void; deleteSession( - request?: protos.google.showcase.v1beta1.IDeleteSessionRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteSessionRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.showcase.v1beta1.IDeleteSessionRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteSessionRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteSessionRequest|undefined, {}|undefined - ]>|void { + | protos.google.showcase.v1beta1.IDeleteSessionRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteSessionRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteSessionRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('deleteSession request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteSessionRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.showcase.v1beta1.IDeleteSessionRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteSession response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.deleteSession(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteSessionRequest|undefined, {}|undefined - ]) => { - this._log.info('deleteSession response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteSession(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteSessionRequest | undefined, + {} | undefined, + ]) => { + this._log.info('deleteSession response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Report on the status of a session. - * This generates a report detailing which tests have been completed, - * and an overall rollup. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * The session to be reported on. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.ReportSessionResponse|ReportSessionResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/testing.report_session.js - * region_tag:localhost_v1beta1_generated_Testing_ReportSession_async - */ + /** + * Report on the status of a session. + * This generates a report detailing which tests have been completed, + * and an overall rollup. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * The session to be reported on. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.ReportSessionResponse|ReportSessionResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/testing.report_session.js + * region_tag:localhost_v1beta1_generated_Testing_ReportSession_async + */ reportSession( - request?: protos.google.showcase.v1beta1.IReportSessionRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IReportSessionResponse, - protos.google.showcase.v1beta1.IReportSessionRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IReportSessionRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IReportSessionResponse, + protos.google.showcase.v1beta1.IReportSessionRequest | undefined, + {} | undefined, + ] + >; reportSession( - request: protos.google.showcase.v1beta1.IReportSessionRequest, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.IReportSessionResponse, - protos.google.showcase.v1beta1.IReportSessionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IReportSessionRequest, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.IReportSessionResponse, + protos.google.showcase.v1beta1.IReportSessionRequest | null | undefined, + {} | null | undefined + >, + ): void; reportSession( - request: protos.google.showcase.v1beta1.IReportSessionRequest, - callback: Callback< - protos.google.showcase.v1beta1.IReportSessionResponse, - protos.google.showcase.v1beta1.IReportSessionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IReportSessionRequest, + callback: Callback< + protos.google.showcase.v1beta1.IReportSessionResponse, + protos.google.showcase.v1beta1.IReportSessionRequest | null | undefined, + {} | null | undefined + >, + ): void; reportSession( - request?: protos.google.showcase.v1beta1.IReportSessionRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.showcase.v1beta1.IReportSessionRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.IReportSessionResponse, - protos.google.showcase.v1beta1.IReportSessionRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.showcase.v1beta1.IReportSessionResponse, - protos.google.showcase.v1beta1.IReportSessionRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.IReportSessionResponse, - protos.google.showcase.v1beta1.IReportSessionRequest|undefined, {}|undefined - ]>|void { + | protos.google.showcase.v1beta1.IReportSessionRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.IReportSessionResponse, + protos.google.showcase.v1beta1.IReportSessionRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IReportSessionResponse, + protos.google.showcase.v1beta1.IReportSessionRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('reportSession request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.IReportSessionResponse, - protos.google.showcase.v1beta1.IReportSessionRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.IReportSessionResponse, + | protos.google.showcase.v1beta1.IReportSessionRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('reportSession response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.reportSession(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.IReportSessionResponse, - protos.google.showcase.v1beta1.IReportSessionRequest|undefined, {}|undefined - ]) => { - this._log.info('reportSession response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .reportSession(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.IReportSessionResponse, + protos.google.showcase.v1beta1.IReportSessionRequest | undefined, + {} | undefined, + ]) => { + this._log.info('reportSession response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Explicitly decline to implement a test. - * - * This removes the test from subsequent `ListTests` calls, and - * attempting to do the test will error. - * - * This method will error if attempting to delete a required test. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * The test to be deleted. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/testing.delete_test.js - * region_tag:localhost_v1beta1_generated_Testing_DeleteTest_async - */ + /** + * Explicitly decline to implement a test. + * + * This removes the test from subsequent `ListTests` calls, and + * attempting to do the test will error. + * + * This method will error if attempting to delete a required test. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * The test to be deleted. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/testing.delete_test.js + * region_tag:localhost_v1beta1_generated_Testing_DeleteTest_async + */ deleteTest( - request?: protos.google.showcase.v1beta1.IDeleteTestRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteTestRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IDeleteTestRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteTestRequest | undefined, + {} | undefined, + ] + >; deleteTest( - request: protos.google.showcase.v1beta1.IDeleteTestRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteTestRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IDeleteTestRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteTestRequest | null | undefined, + {} | null | undefined + >, + ): void; deleteTest( - request: protos.google.showcase.v1beta1.IDeleteTestRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteTestRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IDeleteTestRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteTestRequest | null | undefined, + {} | null | undefined + >, + ): void; deleteTest( - request?: protos.google.showcase.v1beta1.IDeleteTestRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteTestRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.showcase.v1beta1.IDeleteTestRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteTestRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteTestRequest|undefined, {}|undefined - ]>|void { + protos.google.showcase.v1beta1.IDeleteTestRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteTestRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteTestRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('deleteTest request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteTestRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteTestRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteTest response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.deleteTest(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteTestRequest|undefined, {}|undefined - ]) => { - this._log.info('deleteTest response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteTest(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteTestRequest | undefined, + {} | undefined, + ]) => { + this._log.info('deleteTest response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Register a response to a test. - * - * In cases where a test involves registering a final answer at the - * end of the test, this method provides the means to do so. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * The test to have an answer registered to it. - * @param {Buffer} request.answer - * The answer from the test. - * @param {Buffer[]} request.answers - * The answers from the test if multiple are to be checked - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.VerifyTestResponse|VerifyTestResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/testing.verify_test.js - * region_tag:localhost_v1beta1_generated_Testing_VerifyTest_async - */ + /** + * Register a response to a test. + * + * In cases where a test involves registering a final answer at the + * end of the test, this method provides the means to do so. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * The test to have an answer registered to it. + * @param {Buffer} request.answer + * The answer from the test. + * @param {Buffer[]} request.answers + * The answers from the test if multiple are to be checked + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.VerifyTestResponse|VerifyTestResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/testing.verify_test.js + * region_tag:localhost_v1beta1_generated_Testing_VerifyTest_async + */ verifyTest( - request?: protos.google.showcase.v1beta1.IVerifyTestRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IVerifyTestResponse, - protos.google.showcase.v1beta1.IVerifyTestRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IVerifyTestRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IVerifyTestResponse, + protos.google.showcase.v1beta1.IVerifyTestRequest | undefined, + {} | undefined, + ] + >; verifyTest( - request: protos.google.showcase.v1beta1.IVerifyTestRequest, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.IVerifyTestResponse, - protos.google.showcase.v1beta1.IVerifyTestRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IVerifyTestRequest, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.IVerifyTestResponse, + protos.google.showcase.v1beta1.IVerifyTestRequest | null | undefined, + {} | null | undefined + >, + ): void; verifyTest( - request: protos.google.showcase.v1beta1.IVerifyTestRequest, - callback: Callback< - protos.google.showcase.v1beta1.IVerifyTestResponse, - protos.google.showcase.v1beta1.IVerifyTestRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IVerifyTestRequest, + callback: Callback< + protos.google.showcase.v1beta1.IVerifyTestResponse, + protos.google.showcase.v1beta1.IVerifyTestRequest | null | undefined, + {} | null | undefined + >, + ): void; verifyTest( - request?: protos.google.showcase.v1beta1.IVerifyTestRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.showcase.v1beta1.IVerifyTestResponse, - protos.google.showcase.v1beta1.IVerifyTestRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.showcase.v1beta1.IVerifyTestRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.IVerifyTestResponse, - protos.google.showcase.v1beta1.IVerifyTestRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.IVerifyTestResponse, - protos.google.showcase.v1beta1.IVerifyTestRequest|undefined, {}|undefined - ]>|void { + protos.google.showcase.v1beta1.IVerifyTestRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.IVerifyTestResponse, + protos.google.showcase.v1beta1.IVerifyTestRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IVerifyTestResponse, + protos.google.showcase.v1beta1.IVerifyTestRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('verifyTest request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.IVerifyTestResponse, - protos.google.showcase.v1beta1.IVerifyTestRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.IVerifyTestResponse, + protos.google.showcase.v1beta1.IVerifyTestRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('verifyTest response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.verifyTest(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.IVerifyTestResponse, - protos.google.showcase.v1beta1.IVerifyTestRequest|undefined, {}|undefined - ]) => { - this._log.info('verifyTest response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .verifyTest(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.IVerifyTestResponse, + protos.google.showcase.v1beta1.IVerifyTestRequest | undefined, + {} | undefined, + ]) => { + this._log.info('verifyTest response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } - /** - * Lists the current test sessions. - * - * @param {Object} request - * The request object that will be sent. - * @param {number} request.pageSize - * The maximum number of sessions to return per page. - * @param {string} request.pageToken - * The page token, for retrieving subsequent pages. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.showcase.v1beta1.Session|Session}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `listSessionsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Lists the current test sessions. + * + * @param {Object} request + * The request object that will be sent. + * @param {number} request.pageSize + * The maximum number of sessions to return per page. + * @param {string} request.pageToken + * The page token, for retrieving subsequent pages. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.showcase.v1beta1.Session|Session}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listSessionsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listSessions( - request?: protos.google.showcase.v1beta1.IListSessionsRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.ISession[], - protos.google.showcase.v1beta1.IListSessionsRequest|null, - protos.google.showcase.v1beta1.IListSessionsResponse - ]>; + request?: protos.google.showcase.v1beta1.IListSessionsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.ISession[], + protos.google.showcase.v1beta1.IListSessionsRequest | null, + protos.google.showcase.v1beta1.IListSessionsResponse, + ] + >; listSessions( - request: protos.google.showcase.v1beta1.IListSessionsRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.showcase.v1beta1.IListSessionsRequest, - protos.google.showcase.v1beta1.IListSessionsResponse|null|undefined, - protos.google.showcase.v1beta1.ISession>): void; + request: protos.google.showcase.v1beta1.IListSessionsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.showcase.v1beta1.IListSessionsRequest, + protos.google.showcase.v1beta1.IListSessionsResponse | null | undefined, + protos.google.showcase.v1beta1.ISession + >, + ): void; listSessions( - request: protos.google.showcase.v1beta1.IListSessionsRequest, - callback: PaginationCallback< - protos.google.showcase.v1beta1.IListSessionsRequest, - protos.google.showcase.v1beta1.IListSessionsResponse|null|undefined, - protos.google.showcase.v1beta1.ISession>): void; + request: protos.google.showcase.v1beta1.IListSessionsRequest, + callback: PaginationCallback< + protos.google.showcase.v1beta1.IListSessionsRequest, + protos.google.showcase.v1beta1.IListSessionsResponse | null | undefined, + protos.google.showcase.v1beta1.ISession + >, + ): void; listSessions( - request?: protos.google.showcase.v1beta1.IListSessionsRequest, - optionsOrCallback?: CallOptions|PaginationCallback< - protos.google.showcase.v1beta1.IListSessionsRequest, - protos.google.showcase.v1beta1.IListSessionsResponse|null|undefined, - protos.google.showcase.v1beta1.ISession>, - callback?: PaginationCallback< + request?: protos.google.showcase.v1beta1.IListSessionsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.showcase.v1beta1.IListSessionsRequest, - protos.google.showcase.v1beta1.IListSessionsResponse|null|undefined, - protos.google.showcase.v1beta1.ISession>): - Promise<[ - protos.google.showcase.v1beta1.ISession[], - protos.google.showcase.v1beta1.IListSessionsRequest|null, - protos.google.showcase.v1beta1.IListSessionsResponse - ]>|void { + | protos.google.showcase.v1beta1.IListSessionsResponse + | null + | undefined, + protos.google.showcase.v1beta1.ISession + >, + callback?: PaginationCallback< + protos.google.showcase.v1beta1.IListSessionsRequest, + protos.google.showcase.v1beta1.IListSessionsResponse | null | undefined, + protos.google.showcase.v1beta1.ISession + >, + ): Promise< + [ + protos.google.showcase.v1beta1.ISession[], + protos.google.showcase.v1beta1.IListSessionsRequest | null, + protos.google.showcase.v1beta1.IListSessionsResponse, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.showcase.v1beta1.IListSessionsRequest, - protos.google.showcase.v1beta1.IListSessionsResponse|null|undefined, - protos.google.showcase.v1beta1.ISession>|undefined = callback + this.initialize().catch((err) => { + throw err; + }); + const wrappedCallback: + | PaginationCallback< + protos.google.showcase.v1beta1.IListSessionsRequest, + | protos.google.showcase.v1beta1.IListSessionsResponse + | null + | undefined, + protos.google.showcase.v1beta1.ISession + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listSessions values %j', values); callback!(error, values, nextPageRequest, rawResponse); @@ -1039,175 +1314,196 @@ export class TestingClient { this._log.info('listSessions request %j', request); return this.innerApiCalls .listSessions(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.showcase.v1beta1.ISession[], - protos.google.showcase.v1beta1.IListSessionsRequest|null, - protos.google.showcase.v1beta1.IListSessionsResponse - ]) => { - this._log.info('listSessions values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.showcase.v1beta1.ISession[], + protos.google.showcase.v1beta1.IListSessionsRequest | null, + protos.google.showcase.v1beta1.IListSessionsResponse, + ]) => { + this._log.info('listSessions values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listSessions`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {number} request.pageSize - * The maximum number of sessions to return per page. - * @param {string} request.pageToken - * The page token, for retrieving subsequent pages. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.showcase.v1beta1.Session|Session} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `listSessionsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `listSessions`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {number} request.pageSize + * The maximum number of sessions to return per page. + * @param {string} request.pageToken + * The page token, for retrieving subsequent pages. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.showcase.v1beta1.Session|Session} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listSessionsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listSessionsStream( - request?: protos.google.showcase.v1beta1.IListSessionsRequest, - options?: CallOptions): - Transform{ + request?: protos.google.showcase.v1beta1.IListSessionsRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; const defaultCallSettings = this._defaults['listSessions']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listSessions stream %j', request); return this.descriptors.page.listSessions.createStream( this.innerApiCalls.listSessions as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listSessions`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {number} request.pageSize - * The maximum number of sessions to return per page. - * @param {string} request.pageToken - * The page token, for retrieving subsequent pages. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.showcase.v1beta1.Session|Session}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/testing.list_sessions.js - * region_tag:localhost_v1beta1_generated_Testing_ListSessions_async - */ + /** + * Equivalent to `listSessions`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {number} request.pageSize + * The maximum number of sessions to return per page. + * @param {string} request.pageToken + * The page token, for retrieving subsequent pages. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.showcase.v1beta1.Session|Session}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/testing.list_sessions.js + * region_tag:localhost_v1beta1_generated_Testing_ListSessions_async + */ listSessionsAsync( - request?: protos.google.showcase.v1beta1.IListSessionsRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.showcase.v1beta1.IListSessionsRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; const defaultCallSettings = this._defaults['listSessions']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listSessions iterate %j', request); return this.descriptors.page.listSessions.asyncIterate( this.innerApiCalls['listSessions'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } - /** - * List the tests of a sessesion. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * The session. - * @param {number} request.pageSize - * The maximum number of tests to return per page. - * @param {string} request.pageToken - * The page token, for retrieving subsequent pages. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.showcase.v1beta1.Test|Test}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `listTestsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * List the tests of a sessesion. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * The session. + * @param {number} request.pageSize + * The maximum number of tests to return per page. + * @param {string} request.pageToken + * The page token, for retrieving subsequent pages. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.showcase.v1beta1.Test|Test}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listTestsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listTests( - request?: protos.google.showcase.v1beta1.IListTestsRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.ITest[], - protos.google.showcase.v1beta1.IListTestsRequest|null, - protos.google.showcase.v1beta1.IListTestsResponse - ]>; + request?: protos.google.showcase.v1beta1.IListTestsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.ITest[], + protos.google.showcase.v1beta1.IListTestsRequest | null, + protos.google.showcase.v1beta1.IListTestsResponse, + ] + >; listTests( - request: protos.google.showcase.v1beta1.IListTestsRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.showcase.v1beta1.IListTestsRequest, - protos.google.showcase.v1beta1.IListTestsResponse|null|undefined, - protos.google.showcase.v1beta1.ITest>): void; + request: protos.google.showcase.v1beta1.IListTestsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.showcase.v1beta1.IListTestsRequest, + protos.google.showcase.v1beta1.IListTestsResponse | null | undefined, + protos.google.showcase.v1beta1.ITest + >, + ): void; listTests( - request: protos.google.showcase.v1beta1.IListTestsRequest, - callback: PaginationCallback< - protos.google.showcase.v1beta1.IListTestsRequest, - protos.google.showcase.v1beta1.IListTestsResponse|null|undefined, - protos.google.showcase.v1beta1.ITest>): void; + request: protos.google.showcase.v1beta1.IListTestsRequest, + callback: PaginationCallback< + protos.google.showcase.v1beta1.IListTestsRequest, + protos.google.showcase.v1beta1.IListTestsResponse | null | undefined, + protos.google.showcase.v1beta1.ITest + >, + ): void; listTests( - request?: protos.google.showcase.v1beta1.IListTestsRequest, - optionsOrCallback?: CallOptions|PaginationCallback< - protos.google.showcase.v1beta1.IListTestsRequest, - protos.google.showcase.v1beta1.IListTestsResponse|null|undefined, - protos.google.showcase.v1beta1.ITest>, - callback?: PaginationCallback< + request?: protos.google.showcase.v1beta1.IListTestsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.showcase.v1beta1.IListTestsRequest, - protos.google.showcase.v1beta1.IListTestsResponse|null|undefined, - protos.google.showcase.v1beta1.ITest>): - Promise<[ - protos.google.showcase.v1beta1.ITest[], - protos.google.showcase.v1beta1.IListTestsRequest|null, - protos.google.showcase.v1beta1.IListTestsResponse - ]>|void { + protos.google.showcase.v1beta1.IListTestsResponse | null | undefined, + protos.google.showcase.v1beta1.ITest + >, + callback?: PaginationCallback< + protos.google.showcase.v1beta1.IListTestsRequest, + protos.google.showcase.v1beta1.IListTestsResponse | null | undefined, + protos.google.showcase.v1beta1.ITest + >, + ): Promise< + [ + protos.google.showcase.v1beta1.ITest[], + protos.google.showcase.v1beta1.IListTestsRequest | null, + protos.google.showcase.v1beta1.IListTestsResponse, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.showcase.v1beta1.IListTestsRequest, - protos.google.showcase.v1beta1.IListTestsResponse|null|undefined, - protos.google.showcase.v1beta1.ITest>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.showcase.v1beta1.IListTestsRequest, + protos.google.showcase.v1beta1.IListTestsResponse | null | undefined, + protos.google.showcase.v1beta1.ITest + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listTests values %j', values); callback!(error, values, nextPageRequest, rawResponse); @@ -1216,106 +1512,110 @@ export class TestingClient { this._log.info('listTests request %j', request); return this.innerApiCalls .listTests(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.showcase.v1beta1.ITest[], - protos.google.showcase.v1beta1.IListTestsRequest|null, - protos.google.showcase.v1beta1.IListTestsResponse - ]) => { - this._log.info('listTests values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.showcase.v1beta1.ITest[], + protos.google.showcase.v1beta1.IListTestsRequest | null, + protos.google.showcase.v1beta1.IListTestsResponse, + ]) => { + this._log.info('listTests values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listTests`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * The session. - * @param {number} request.pageSize - * The maximum number of tests to return per page. - * @param {string} request.pageToken - * The page token, for retrieving subsequent pages. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.showcase.v1beta1.Test|Test} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `listTestsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `listTests`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * The session. + * @param {number} request.pageSize + * The maximum number of tests to return per page. + * @param {string} request.pageToken + * The page token, for retrieving subsequent pages. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.showcase.v1beta1.Test|Test} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listTestsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listTestsStream( - request?: protos.google.showcase.v1beta1.IListTestsRequest, - options?: CallOptions): - Transform{ + request?: protos.google.showcase.v1beta1.IListTestsRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); const defaultCallSettings = this._defaults['listTests']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listTests stream %j', request); return this.descriptors.page.listTests.createStream( this.innerApiCalls.listTests as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listTests`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * The session. - * @param {number} request.pageSize - * The maximum number of tests to return per page. - * @param {string} request.pageToken - * The page token, for retrieving subsequent pages. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.showcase.v1beta1.Test|Test}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/testing.list_tests.js - * region_tag:localhost_v1beta1_generated_Testing_ListTests_async - */ + /** + * Equivalent to `listTests`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * The session. + * @param {number} request.pageSize + * The maximum number of tests to return per page. + * @param {string} request.pageToken + * The page token, for retrieving subsequent pages. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.showcase.v1beta1.Test|Test}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/testing.list_tests.js + * region_tag:localhost_v1beta1_generated_Testing_ListTests_async + */ listTestsAsync( - request?: protos.google.showcase.v1beta1.IListTestsRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.showcase.v1beta1.IListTestsRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); const defaultCallSettings = this._defaults['listTests']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listTests iterate %j', request); return this.descriptors.page.listTests.asyncIterate( this.innerApiCalls['listTests'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } // -------------------- @@ -1330,7 +1630,7 @@ export class TestingClient { * @param {string} blueprint * @returns {string} Resource name string. */ - blueprintPath(session:string,test:string,blueprint:string) { + blueprintPath(session: string, test: string, blueprint: string) { return this.pathTemplates.blueprintPathTemplate.render({ session: session, test: test, @@ -1346,7 +1646,8 @@ export class TestingClient { * @returns {string} A string representing the session. */ matchSessionFromBlueprintName(blueprintName: string) { - return this.pathTemplates.blueprintPathTemplate.match(blueprintName).session; + return this.pathTemplates.blueprintPathTemplate.match(blueprintName) + .session; } /** @@ -1368,7 +1669,8 @@ export class TestingClient { * @returns {string} A string representing the blueprint. */ matchBlueprintFromBlueprintName(blueprintName: string) { - return this.pathTemplates.blueprintPathTemplate.match(blueprintName).blueprint; + return this.pathTemplates.blueprintPathTemplate.match(blueprintName) + .blueprint; } /** @@ -1377,7 +1679,7 @@ export class TestingClient { * @param {string} room * @returns {string} Resource name string. */ - roomPath(room:string) { + roomPath(room: string) { return this.pathTemplates.roomPathTemplate.render({ room: room, }); @@ -1401,7 +1703,7 @@ export class TestingClient { * @param {string} blurb * @returns {string} Resource name string. */ - roomBlurbPath(room:string,blurb:string) { + roomBlurbPath(room: string, blurb: string) { return this.pathTemplates.roomBlurbPathTemplate.render({ room: room, blurb: blurb, @@ -1438,7 +1740,11 @@ export class TestingClient { * @param {string} blurb * @returns {string} Resource name string. */ - roomBlurbsLegacyRoomBlurbPath(room:string,legacyRoom:string,blurb:string) { + roomBlurbsLegacyRoomBlurbPath( + room: string, + legacyRoom: string, + blurb: string, + ) { return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.render({ room: room, legacy_room: legacyRoom, @@ -1453,8 +1759,12 @@ export class TestingClient { * A fully-qualified path representing room_blurbs_legacy_room_blurb resource. * @returns {string} A string representing the room. */ - matchRoomFromRoomBlurbsLegacyRoomBlurbName(roomBlurbsLegacyRoomBlurbName: string) { - return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match(roomBlurbsLegacyRoomBlurbName).room; + matchRoomFromRoomBlurbsLegacyRoomBlurbName( + roomBlurbsLegacyRoomBlurbName: string, + ) { + return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match( + roomBlurbsLegacyRoomBlurbName, + ).room; } /** @@ -1464,8 +1774,12 @@ export class TestingClient { * A fully-qualified path representing room_blurbs_legacy_room_blurb resource. * @returns {string} A string representing the legacy_room. */ - matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName(roomBlurbsLegacyRoomBlurbName: string) { - return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match(roomBlurbsLegacyRoomBlurbName).legacy_room; + matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName( + roomBlurbsLegacyRoomBlurbName: string, + ) { + return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match( + roomBlurbsLegacyRoomBlurbName, + ).legacy_room; } /** @@ -1475,8 +1789,12 @@ export class TestingClient { * A fully-qualified path representing room_blurbs_legacy_room_blurb resource. * @returns {string} A string representing the blurb. */ - matchBlurbFromRoomBlurbsLegacyRoomBlurbName(roomBlurbsLegacyRoomBlurbName: string) { - return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match(roomBlurbsLegacyRoomBlurbName).blurb; + matchBlurbFromRoomBlurbsLegacyRoomBlurbName( + roomBlurbsLegacyRoomBlurbName: string, + ) { + return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match( + roomBlurbsLegacyRoomBlurbName, + ).blurb; } /** @@ -1485,7 +1803,7 @@ export class TestingClient { * @param {string} sequence * @returns {string} Resource name string. */ - sequencePath(sequence:string) { + sequencePath(sequence: string) { return this.pathTemplates.sequencePathTemplate.render({ sequence: sequence, }); @@ -1508,7 +1826,7 @@ export class TestingClient { * @param {string} sequence * @returns {string} Resource name string. */ - sequenceReportPath(sequence:string) { + sequenceReportPath(sequence: string) { return this.pathTemplates.sequenceReportPathTemplate.render({ sequence: sequence, }); @@ -1522,7 +1840,9 @@ export class TestingClient { * @returns {string} A string representing the sequence. */ matchSequenceFromSequenceReportName(sequenceReportName: string) { - return this.pathTemplates.sequenceReportPathTemplate.match(sequenceReportName).sequence; + return this.pathTemplates.sequenceReportPathTemplate.match( + sequenceReportName, + ).sequence; } /** @@ -1531,7 +1851,7 @@ export class TestingClient { * @param {string} session * @returns {string} Resource name string. */ - sessionPath(session:string) { + sessionPath(session: string) { return this.pathTemplates.sessionPathTemplate.render({ session: session, }); @@ -1555,7 +1875,7 @@ export class TestingClient { * @param {string} test * @returns {string} Resource name string. */ - testPath(session:string,test:string) { + testPath(session: string, test: string) { return this.pathTemplates.testPathTemplate.render({ session: session, test: test, @@ -1590,7 +1910,7 @@ export class TestingClient { * @param {string} user * @returns {string} Resource name string. */ - userPath(user:string) { + userPath(user: string) { return this.pathTemplates.userPathTemplate.render({ user: user, }); @@ -1614,7 +1934,7 @@ export class TestingClient { * @param {string} blurb * @returns {string} Resource name string. */ - userProfileBlurbPath(user:string,blurb:string) { + userProfileBlurbPath(user: string, blurb: string) { return this.pathTemplates.userProfileBlurbPathTemplate.render({ user: user, blurb: blurb, @@ -1629,7 +1949,9 @@ export class TestingClient { * @returns {string} A string representing the user. */ matchUserFromUserProfileBlurbName(userProfileBlurbName: string) { - return this.pathTemplates.userProfileBlurbPathTemplate.match(userProfileBlurbName).user; + return this.pathTemplates.userProfileBlurbPathTemplate.match( + userProfileBlurbName, + ).user; } /** @@ -1640,7 +1962,9 @@ export class TestingClient { * @returns {string} A string representing the blurb. */ matchBlurbFromUserProfileBlurbName(userProfileBlurbName: string) { - return this.pathTemplates.userProfileBlurbPathTemplate.match(userProfileBlurbName).blurb; + return this.pathTemplates.userProfileBlurbPathTemplate.match( + userProfileBlurbName, + ).blurb; } /** @@ -1651,12 +1975,18 @@ export class TestingClient { * @param {string} blurb * @returns {string} Resource name string. */ - userProfileBlurbsLegacyUserBlurbPath(user:string,legacyUser:string,blurb:string) { - return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.render({ - user: user, - legacy_user: legacyUser, - blurb: blurb, - }); + userProfileBlurbsLegacyUserBlurbPath( + user: string, + legacyUser: string, + blurb: string, + ) { + return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.render( + { + user: user, + legacy_user: legacyUser, + blurb: blurb, + }, + ); } /** @@ -1666,8 +1996,12 @@ export class TestingClient { * A fully-qualified path representing user_profile_blurbs_legacy_user_blurb resource. * @returns {string} A string representing the user. */ - matchUserFromUserProfileBlurbsLegacyUserBlurbName(userProfileBlurbsLegacyUserBlurbName: string) { - return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match(userProfileBlurbsLegacyUserBlurbName).user; + matchUserFromUserProfileBlurbsLegacyUserBlurbName( + userProfileBlurbsLegacyUserBlurbName: string, + ) { + return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match( + userProfileBlurbsLegacyUserBlurbName, + ).user; } /** @@ -1677,8 +2011,12 @@ export class TestingClient { * A fully-qualified path representing user_profile_blurbs_legacy_user_blurb resource. * @returns {string} A string representing the legacy_user. */ - matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName(userProfileBlurbsLegacyUserBlurbName: string) { - return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match(userProfileBlurbsLegacyUserBlurbName).legacy_user; + matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName( + userProfileBlurbsLegacyUserBlurbName: string, + ) { + return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match( + userProfileBlurbsLegacyUserBlurbName, + ).legacy_user; } /** @@ -1688,8 +2026,12 @@ export class TestingClient { * A fully-qualified path representing user_profile_blurbs_legacy_user_blurb resource. * @returns {string} A string representing the blurb. */ - matchBlurbFromUserProfileBlurbsLegacyUserBlurbName(userProfileBlurbsLegacyUserBlurbName: string) { - return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match(userProfileBlurbsLegacyUserBlurbName).blurb; + matchBlurbFromUserProfileBlurbsLegacyUserBlurbName( + userProfileBlurbsLegacyUserBlurbName: string, + ) { + return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match( + userProfileBlurbsLegacyUserBlurbName, + ).blurb; } /** @@ -1700,7 +2042,7 @@ export class TestingClient { */ close(): Promise { if (this.testingStub && !this._terminated) { - return this.testingStub.then(stub => { + return this.testingStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -1708,4 +2050,4 @@ export class TestingClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/core/generator/gapic-generator-typescript/baselines/showcase-esm/esm/system-test/fixtures/sample/src/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/showcase-esm/esm/system-test/fixtures/sample/src/index.ts.baseline index 54230b252a83..b715977934e6 100644 --- a/core/generator/gapic-generator-typescript/baselines/showcase-esm/esm/system-test/fixtures/sample/src/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/showcase-esm/esm/system-test/fixtures/sample/src/index.ts.baseline @@ -17,7 +17,14 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -import {ComplianceClient, EchoClient, IdentityClient, MessagingClient, SequenceServiceClient, TestingClient} from 'showcase'; +import { + ComplianceClient, + EchoClient, + IdentityClient, + MessagingClient, + SequenceServiceClient, + TestingClient, +} from 'showcase'; // check that the client class type name can be used function doStuffWithComplianceClient(client: ComplianceClient) { diff --git a/core/generator/gapic-generator-typescript/baselines/showcase-esm/esm/system-test/install.ts.baseline b/core/generator/gapic-generator-typescript/baselines/showcase-esm/esm/system-test/install.ts.baseline index e079c4fa1101..d109fdd8c97f 100644 --- a/core/generator/gapic-generator-typescript/baselines/showcase-esm/esm/system-test/install.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/showcase-esm/esm/system-test/install.ts.baseline @@ -16,40 +16,45 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -import {packNTest} from 'pack-n-play'; -import {readFileSync} from 'fs'; -import {describe, it} from 'mocha'; +import { packNTest } from 'pack-n-play'; +import { readFileSync } from 'fs'; +import { describe, it } from 'mocha'; describe('📦 pack-n-play test', () => { - it('TypeScript', async function() { + it('TypeScript', async function () { this.timeout(300000); await packNTest({ packageDir: process.cwd(), sample: { description: 'TypeScript user can use the type definitions', - ts: readFileSync('./esm/system-test/fixtures/sample/src/index.ts').toString() - } + ts: readFileSync( + './esm/system-test/fixtures/sample/src/index.ts', + ).toString(), + }, }); }); - it('ESM module', async function() { + it('ESM module', async function () { this.timeout(300000); await packNTest({ sample: { description: 'Should be able to import using ESM', - esm: readFileSync('./esm/system-test/fixtures/sample/src/index.js').toString(), + esm: readFileSync( + './esm/system-test/fixtures/sample/src/index.js', + ).toString(), }, }); }); - it('CJS module', async function() { + it('CJS module', async function () { this.timeout(300000); await packNTest({ sample: { description: 'Should be able to import using CJS', - cjs: readFileSync('./esm/system-test/fixtures/sample/src/index.cjs').toString(), + cjs: readFileSync( + './esm/system-test/fixtures/sample/src/index.cjs', + ).toString(), }, }); }); - }); diff --git a/core/generator/gapic-generator-typescript/baselines/showcase-esm/esm/test/gapic_compliance_v1beta1.ts.baseline b/core/generator/gapic-generator-typescript/baselines/showcase-esm/esm/test/gapic_compliance_v1beta1.ts.baseline index 7403c5712d59..2ce0a2340ee2 100644 --- a/core/generator/gapic-generator-typescript/baselines/showcase-esm/esm/test/gapic_compliance_v1beta1.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/showcase-esm/esm/test/gapic_compliance_v1beta1.ts.baseline @@ -20,14 +20,14 @@ import * as protos from '../../protos/protos.js'; import assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as complianceModule from '../src/index.js'; -import {protobuf} from 'google-gax'; +import { protobuf } from 'google-gax'; import fs from 'fs'; import path from 'path'; -import {fileURLToPath} from 'url'; +import { fileURLToPath } from 'url'; // @ts-ignore const dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -35,1534 +35,1965 @@ const dirname = path.dirname(fileURLToPath(import.meta.url)); // to fill in default values for request objects const root = protobuf.Root.fromJSON( JSON.parse( - fs.readFileSync(path.join(dirname, '..', '..', 'protos/protos.json'), 'utf8') - )) + fs.readFileSync( + path.join(dirname, '..', '..', 'protos/protos.json'), + 'utf8', + ), + ), +); // eslint-disable-next-line @typescript-eslint/no-unused-vars function getTypeDefaultValue(typeName: string, fields: string[]) { - let type = root.lookupType(typeName) as protobuf.Type; - for (const field of fields.slice(0, -1)) { - type = type?.fields[field]?.resolvedType as protobuf.Type; - } - return type?.fields[fields[fields.length - 1]]?.defaultValue ?? null; + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type?.fields[field]?.resolvedType as protobuf.Type; + } + return type?.fields[fields[fields.length - 1]]?.defaultValue ?? null; } function generateSampleMessage(instance: T) { - const filledObject = (instance.constructor as typeof protobuf.Message) - .toObject(instance as protobuf.Message, {defaults: true}); - return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, { defaults: true }); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; } function stubSimpleCall(response?: ResponseType, error?: Error) { - return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); } -function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { - return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +function stubSimpleCallWithCallback( + response?: ResponseType, + error?: Error, +) { + return error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); } describe('v1beta1.ComplianceClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new complianceModule.v1beta1.ComplianceClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'localhost'); - }); - - it('has universeDomain', () => { - const client = new complianceModule.v1beta1.ComplianceClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); - - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - it('throws DeprecationWarning if static servicePath is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const servicePath = complianceModule.v1beta1.ComplianceClient.servicePath; - assert.strictEqual(servicePath, 'localhost'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = complianceModule.v1beta1.ComplianceClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'localhost'); - assert(stub.called); - stub.restore(); - }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { new complianceModule.v1beta1.ComplianceClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); - - it('has port', () => { - const port = complianceModule.v1beta1.ComplianceClient.port; - assert(port); - assert(typeof port === 'number'); - }); - - it('should create a client with no option', () => { - const client = new complianceModule.v1beta1.ComplianceClient(); - assert(client); - }); - - it('should create a client with gRPC fallback', () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - fallback: true, - }); - assert(client); - }); - - it('has initialize method and supports deferred initialization', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.complianceStub, undefined); - await client.initialize(); - assert(client.complianceStub); - }); - - it('has close method for the initialized client', done => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.complianceStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); - - it('has close method for the non-initialized client', done => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.complianceStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); - - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); - }); - - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId((err?: Error|null, projectId?: string|null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } - }); - }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new complianceModule.v1beta1.ComplianceClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'localhost'); }); - describe('repeatDataBody', () => { - it('invokes repeatDataBody without error', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatResponse() - ); - client.innerApiCalls.repeatDataBody = stubSimpleCall(expectedResponse); - const [response] = await client.repeatDataBody(request); - assert.deepStrictEqual(response, expectedResponse); - }); - - it('invokes repeatDataBody without error using callback', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatResponse() - ); - client.innerApiCalls.repeatDataBody = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.repeatDataBody( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IRepeatResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); + it('has universeDomain', () => { + const client = new complianceModule.v1beta1.ComplianceClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - it('invokes repeatDataBody with error', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.repeatDataBody = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.repeatDataBody(request), expectedError); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = + complianceModule.v1beta1.ComplianceClient.servicePath; + assert.strictEqual(servicePath, 'localhost'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + complianceModule.v1beta1.ComplianceClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'localhost'); + assert(stub.called); + stub.restore(); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new complianceModule.v1beta1.ComplianceClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); + }); - it('invokes repeatDataBody with closed client', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.repeatDataBody(request), expectedError); - }); + it('has port', () => { + const port = complianceModule.v1beta1.ComplianceClient.port; + assert(port); + assert(typeof port === 'number'); }); - describe('repeatDataBodyInfo', () => { - it('invokes repeatDataBodyInfo without error', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatResponse() - ); - client.innerApiCalls.repeatDataBodyInfo = stubSimpleCall(expectedResponse); - const [response] = await client.repeatDataBodyInfo(request); - assert.deepStrictEqual(response, expectedResponse); - }); + it('should create a client with no option', () => { + const client = new complianceModule.v1beta1.ComplianceClient(); + assert(client); + }); - it('invokes repeatDataBodyInfo without error using callback', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatResponse() - ); - client.innerApiCalls.repeatDataBodyInfo = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.repeatDataBodyInfo( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IRepeatResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); + it('should create a client with gRPC fallback', () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + fallback: true, + }); + assert(client); + }); - it('invokes repeatDataBodyInfo with error', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.repeatDataBodyInfo = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.repeatDataBodyInfo(request), expectedError); - }); + it('has initialize method and supports deferred initialization', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.complianceStub, undefined); + await client.initialize(); + assert(client.complianceStub); + }); - it('invokes repeatDataBodyInfo with closed client', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.repeatDataBodyInfo(request), expectedError); + it('has close method for the initialized client', (done) => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.complianceStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); }); - describe('repeatDataQuery', () => { - it('invokes repeatDataQuery without error', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatResponse() - ); - client.innerApiCalls.repeatDataQuery = stubSimpleCall(expectedResponse); - const [response] = await client.repeatDataQuery(request); - assert.deepStrictEqual(response, expectedResponse); + it('has close method for the non-initialized client', (done) => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.complianceStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes repeatDataQuery without error using callback', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatResponse() - ); - client.innerApiCalls.repeatDataQuery = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.repeatDataQuery( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IRepeatResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + }); - it('invokes repeatDataQuery with error', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.repeatDataQuery = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.repeatDataQuery(request), expectedError); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + }); + + describe('repeatDataBody', () => { + it('invokes repeatDataBody without error', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatResponse(), + ); + client.innerApiCalls.repeatDataBody = stubSimpleCall(expectedResponse); + const [response] = await client.repeatDataBody(request); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes repeatDataQuery with closed client', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.repeatDataQuery(request), expectedError); - }); + it('invokes repeatDataBody without error using callback', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatResponse(), + ); + client.innerApiCalls.repeatDataBody = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.repeatDataBody( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IRepeatResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); }); - describe('repeatDataSimplePath', () => { - it('invokes repeatDataSimplePath without error', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - request.info ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fString']); - request.info.fString = defaultValue1; - request.info ??= {}; - const defaultValue2 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fInt32']); - request.info.fInt32 = defaultValue2; - request.info ??= {}; - const defaultValue3 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fDouble']); - request.info.fDouble = defaultValue3; - request.info ??= {}; - const defaultValue4 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fBool']); - request.info.fBool = defaultValue4; - request.info ??= {}; - const defaultValue5 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fKingdom']); - request.info.fKingdom = defaultValue5; - const expectedHeaderRequestParams = `info.f_string=${defaultValue1 ?? '' }&info.f_int32=${defaultValue2 ?? '' }&info.f_double=${defaultValue3 ?? '' }&info.f_bool=${defaultValue4 ?? '' }&info.f_kingdom=${defaultValue5 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatResponse() - ); - client.innerApiCalls.repeatDataSimplePath = stubSimpleCall(expectedResponse); - const [response] = await client.repeatDataSimplePath(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.repeatDataSimplePath as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.repeatDataSimplePath as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes repeatDataBody with error', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.repeatDataBody = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.repeatDataBody(request), expectedError); + }); - it('invokes repeatDataSimplePath without error using callback', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - request.info ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fString']); - request.info.fString = defaultValue1; - request.info ??= {}; - const defaultValue2 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fInt32']); - request.info.fInt32 = defaultValue2; - request.info ??= {}; - const defaultValue3 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fDouble']); - request.info.fDouble = defaultValue3; - request.info ??= {}; - const defaultValue4 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fBool']); - request.info.fBool = defaultValue4; - request.info ??= {}; - const defaultValue5 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fKingdom']); - request.info.fKingdom = defaultValue5; - const expectedHeaderRequestParams = `info.f_string=${defaultValue1 ?? '' }&info.f_int32=${defaultValue2 ?? '' }&info.f_double=${defaultValue3 ?? '' }&info.f_bool=${defaultValue4 ?? '' }&info.f_kingdom=${defaultValue5 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatResponse() - ); - client.innerApiCalls.repeatDataSimplePath = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.repeatDataSimplePath( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IRepeatResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.repeatDataSimplePath as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.repeatDataSimplePath as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes repeatDataBody with closed client', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.repeatDataBody(request), expectedError); + }); + }); + + describe('repeatDataBodyInfo', () => { + it('invokes repeatDataBodyInfo without error', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatResponse(), + ); + client.innerApiCalls.repeatDataBodyInfo = + stubSimpleCall(expectedResponse); + const [response] = await client.repeatDataBodyInfo(request); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes repeatDataSimplePath with error', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - request.info ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fString']); - request.info.fString = defaultValue1; - request.info ??= {}; - const defaultValue2 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fInt32']); - request.info.fInt32 = defaultValue2; - request.info ??= {}; - const defaultValue3 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fDouble']); - request.info.fDouble = defaultValue3; - request.info ??= {}; - const defaultValue4 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fBool']); - request.info.fBool = defaultValue4; - request.info ??= {}; - const defaultValue5 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fKingdom']); - request.info.fKingdom = defaultValue5; - const expectedHeaderRequestParams = `info.f_string=${defaultValue1 ?? '' }&info.f_int32=${defaultValue2 ?? '' }&info.f_double=${defaultValue3 ?? '' }&info.f_bool=${defaultValue4 ?? '' }&info.f_kingdom=${defaultValue5 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.repeatDataSimplePath = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.repeatDataSimplePath(request), expectedError); - const actualRequest = (client.innerApiCalls.repeatDataSimplePath as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.repeatDataSimplePath as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes repeatDataBodyInfo without error using callback', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatResponse(), + ); + client.innerApiCalls.repeatDataBodyInfo = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.repeatDataBodyInfo( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IRepeatResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes repeatDataSimplePath with closed client', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - request.info ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fString']); - request.info.fString = defaultValue1; - request.info ??= {}; - const defaultValue2 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fInt32']); - request.info.fInt32 = defaultValue2; - request.info ??= {}; - const defaultValue3 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fDouble']); - request.info.fDouble = defaultValue3; - request.info ??= {}; - const defaultValue4 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fBool']); - request.info.fBool = defaultValue4; - request.info ??= {}; - const defaultValue5 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fKingdom']); - request.info.fKingdom = defaultValue5; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.repeatDataSimplePath(request), expectedError); - }); + it('invokes repeatDataBodyInfo with error', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.repeatDataBodyInfo = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.repeatDataBodyInfo(request), expectedError); }); - describe('repeatDataPathResource', () => { - it('invokes repeatDataPathResource without error', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - request.info ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fString']); - request.info.fString = defaultValue1; - request.info ??= {}; - request.info.fChild ??= {}; - const defaultValue2 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fChild', 'fString']); - request.info.fChild.fString = defaultValue2; - request.info ??= {}; - const defaultValue3 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fBool']); - request.info.fBool = defaultValue3; - const expectedHeaderRequestParams = `info.f_string=${defaultValue1 ?? '' }&info.f_child.f_string=${defaultValue2 ?? '' }&info.f_bool=${defaultValue3 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatResponse() - ); - client.innerApiCalls.repeatDataPathResource = stubSimpleCall(expectedResponse); - const [response] = await client.repeatDataPathResource(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.repeatDataPathResource as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.repeatDataPathResource as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes repeatDataBodyInfo with closed client', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.repeatDataBodyInfo(request), expectedError); + }); + }); + + describe('repeatDataQuery', () => { + it('invokes repeatDataQuery without error', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatResponse(), + ); + client.innerApiCalls.repeatDataQuery = stubSimpleCall(expectedResponse); + const [response] = await client.repeatDataQuery(request); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes repeatDataPathResource without error using callback', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - request.info ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fString']); - request.info.fString = defaultValue1; - request.info ??= {}; - request.info.fChild ??= {}; - const defaultValue2 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fChild', 'fString']); - request.info.fChild.fString = defaultValue2; - request.info ??= {}; - const defaultValue3 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fBool']); - request.info.fBool = defaultValue3; - const expectedHeaderRequestParams = `info.f_string=${defaultValue1 ?? '' }&info.f_child.f_string=${defaultValue2 ?? '' }&info.f_bool=${defaultValue3 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatResponse() - ); - client.innerApiCalls.repeatDataPathResource = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.repeatDataPathResource( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IRepeatResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.repeatDataPathResource as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.repeatDataPathResource as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes repeatDataQuery without error using callback', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatResponse(), + ); + client.innerApiCalls.repeatDataQuery = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.repeatDataQuery( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IRepeatResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes repeatDataPathResource with error', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - request.info ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fString']); - request.info.fString = defaultValue1; - request.info ??= {}; - request.info.fChild ??= {}; - const defaultValue2 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fChild', 'fString']); - request.info.fChild.fString = defaultValue2; - request.info ??= {}; - const defaultValue3 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fBool']); - request.info.fBool = defaultValue3; - const expectedHeaderRequestParams = `info.f_string=${defaultValue1 ?? '' }&info.f_child.f_string=${defaultValue2 ?? '' }&info.f_bool=${defaultValue3 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.repeatDataPathResource = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.repeatDataPathResource(request), expectedError); - const actualRequest = (client.innerApiCalls.repeatDataPathResource as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.repeatDataPathResource as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes repeatDataQuery with error', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.repeatDataQuery = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.repeatDataQuery(request), expectedError); + }); - it('invokes repeatDataPathResource with closed client', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - request.info ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fString']); - request.info.fString = defaultValue1; - request.info ??= {}; - request.info.fChild ??= {}; - const defaultValue2 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fChild', 'fString']); - request.info.fChild.fString = defaultValue2; - request.info ??= {}; - const defaultValue3 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fBool']); - request.info.fBool = defaultValue3; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.repeatDataPathResource(request), expectedError); - }); + it('invokes repeatDataQuery with closed client', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.repeatDataQuery(request), expectedError); + }); + }); + + describe('repeatDataSimplePath', () => { + it('invokes repeatDataSimplePath without error', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + request.info ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fString'], + ); + request.info.fString = defaultValue1; + request.info ??= {}; + const defaultValue2 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fInt32'], + ); + request.info.fInt32 = defaultValue2; + request.info ??= {}; + const defaultValue3 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fDouble'], + ); + request.info.fDouble = defaultValue3; + request.info ??= {}; + const defaultValue4 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fBool'], + ); + request.info.fBool = defaultValue4; + request.info ??= {}; + const defaultValue5 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fKingdom'], + ); + request.info.fKingdom = defaultValue5; + const expectedHeaderRequestParams = `info.f_string=${defaultValue1 ?? ''}&info.f_int32=${defaultValue2 ?? ''}&info.f_double=${defaultValue3 ?? ''}&info.f_bool=${defaultValue4 ?? ''}&info.f_kingdom=${defaultValue5 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatResponse(), + ); + client.innerApiCalls.repeatDataSimplePath = + stubSimpleCall(expectedResponse); + const [response] = await client.repeatDataSimplePath(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.repeatDataSimplePath as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.repeatDataSimplePath as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('repeatDataPathTrailingResource', () => { - it('invokes repeatDataPathTrailingResource without error', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - request.info ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fString']); - request.info.fString = defaultValue1; - request.info ??= {}; - request.info.fChild ??= {}; - const defaultValue2 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fChild', 'fString']); - request.info.fChild.fString = defaultValue2; - const expectedHeaderRequestParams = `info.f_string=${defaultValue1 ?? '' }&info.f_child.f_string=${defaultValue2 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatResponse() - ); - client.innerApiCalls.repeatDataPathTrailingResource = stubSimpleCall(expectedResponse); - const [response] = await client.repeatDataPathTrailingResource(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.repeatDataPathTrailingResource as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.repeatDataPathTrailingResource as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes repeatDataSimplePath without error using callback', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + request.info ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fString'], + ); + request.info.fString = defaultValue1; + request.info ??= {}; + const defaultValue2 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fInt32'], + ); + request.info.fInt32 = defaultValue2; + request.info ??= {}; + const defaultValue3 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fDouble'], + ); + request.info.fDouble = defaultValue3; + request.info ??= {}; + const defaultValue4 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fBool'], + ); + request.info.fBool = defaultValue4; + request.info ??= {}; + const defaultValue5 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fKingdom'], + ); + request.info.fKingdom = defaultValue5; + const expectedHeaderRequestParams = `info.f_string=${defaultValue1 ?? ''}&info.f_int32=${defaultValue2 ?? ''}&info.f_double=${defaultValue3 ?? ''}&info.f_bool=${defaultValue4 ?? ''}&info.f_kingdom=${defaultValue5 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatResponse(), + ); + client.innerApiCalls.repeatDataSimplePath = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.repeatDataSimplePath( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IRepeatResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.repeatDataSimplePath as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.repeatDataSimplePath as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes repeatDataPathTrailingResource without error using callback', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - request.info ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fString']); - request.info.fString = defaultValue1; - request.info ??= {}; - request.info.fChild ??= {}; - const defaultValue2 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fChild', 'fString']); - request.info.fChild.fString = defaultValue2; - const expectedHeaderRequestParams = `info.f_string=${defaultValue1 ?? '' }&info.f_child.f_string=${defaultValue2 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatResponse() - ); - client.innerApiCalls.repeatDataPathTrailingResource = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.repeatDataPathTrailingResource( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IRepeatResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.repeatDataPathTrailingResource as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.repeatDataPathTrailingResource as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes repeatDataSimplePath with error', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + request.info ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fString'], + ); + request.info.fString = defaultValue1; + request.info ??= {}; + const defaultValue2 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fInt32'], + ); + request.info.fInt32 = defaultValue2; + request.info ??= {}; + const defaultValue3 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fDouble'], + ); + request.info.fDouble = defaultValue3; + request.info ??= {}; + const defaultValue4 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fBool'], + ); + request.info.fBool = defaultValue4; + request.info ??= {}; + const defaultValue5 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fKingdom'], + ); + request.info.fKingdom = defaultValue5; + const expectedHeaderRequestParams = `info.f_string=${defaultValue1 ?? ''}&info.f_int32=${defaultValue2 ?? ''}&info.f_double=${defaultValue3 ?? ''}&info.f_bool=${defaultValue4 ?? ''}&info.f_kingdom=${defaultValue5 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.repeatDataSimplePath = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.repeatDataSimplePath(request), expectedError); + const actualRequest = ( + client.innerApiCalls.repeatDataSimplePath as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.repeatDataSimplePath as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes repeatDataPathTrailingResource with error', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - request.info ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fString']); - request.info.fString = defaultValue1; - request.info ??= {}; - request.info.fChild ??= {}; - const defaultValue2 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fChild', 'fString']); - request.info.fChild.fString = defaultValue2; - const expectedHeaderRequestParams = `info.f_string=${defaultValue1 ?? '' }&info.f_child.f_string=${defaultValue2 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.repeatDataPathTrailingResource = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.repeatDataPathTrailingResource(request), expectedError); - const actualRequest = (client.innerApiCalls.repeatDataPathTrailingResource as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.repeatDataPathTrailingResource as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes repeatDataSimplePath with closed client', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + request.info ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fString'], + ); + request.info.fString = defaultValue1; + request.info ??= {}; + const defaultValue2 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fInt32'], + ); + request.info.fInt32 = defaultValue2; + request.info ??= {}; + const defaultValue3 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fDouble'], + ); + request.info.fDouble = defaultValue3; + request.info ??= {}; + const defaultValue4 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fBool'], + ); + request.info.fBool = defaultValue4; + request.info ??= {}; + const defaultValue5 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fKingdom'], + ); + request.info.fKingdom = defaultValue5; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.repeatDataSimplePath(request), expectedError); + }); + }); + + describe('repeatDataPathResource', () => { + it('invokes repeatDataPathResource without error', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + request.info ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fString'], + ); + request.info.fString = defaultValue1; + request.info ??= {}; + request.info.fChild ??= {}; + const defaultValue2 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fChild', 'fString'], + ); + request.info.fChild.fString = defaultValue2; + request.info ??= {}; + const defaultValue3 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fBool'], + ); + request.info.fBool = defaultValue3; + const expectedHeaderRequestParams = `info.f_string=${defaultValue1 ?? ''}&info.f_child.f_string=${defaultValue2 ?? ''}&info.f_bool=${defaultValue3 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatResponse(), + ); + client.innerApiCalls.repeatDataPathResource = + stubSimpleCall(expectedResponse); + const [response] = await client.repeatDataPathResource(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.repeatDataPathResource as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.repeatDataPathResource as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes repeatDataPathTrailingResource with closed client', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - request.info ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fString']); - request.info.fString = defaultValue1; - request.info ??= {}; - request.info.fChild ??= {}; - const defaultValue2 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fChild', 'fString']); - request.info.fChild.fString = defaultValue2; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.repeatDataPathTrailingResource(request), expectedError); - }); + it('invokes repeatDataPathResource without error using callback', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + request.info ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fString'], + ); + request.info.fString = defaultValue1; + request.info ??= {}; + request.info.fChild ??= {}; + const defaultValue2 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fChild', 'fString'], + ); + request.info.fChild.fString = defaultValue2; + request.info ??= {}; + const defaultValue3 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fBool'], + ); + request.info.fBool = defaultValue3; + const expectedHeaderRequestParams = `info.f_string=${defaultValue1 ?? ''}&info.f_child.f_string=${defaultValue2 ?? ''}&info.f_bool=${defaultValue3 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatResponse(), + ); + client.innerApiCalls.repeatDataPathResource = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.repeatDataPathResource( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IRepeatResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.repeatDataPathResource as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.repeatDataPathResource as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('repeatDataBodyPut', () => { - it('invokes repeatDataBodyPut without error', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatResponse() - ); - client.innerApiCalls.repeatDataBodyPut = stubSimpleCall(expectedResponse); - const [response] = await client.repeatDataBodyPut(request); - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes repeatDataPathResource with error', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + request.info ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fString'], + ); + request.info.fString = defaultValue1; + request.info ??= {}; + request.info.fChild ??= {}; + const defaultValue2 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fChild', 'fString'], + ); + request.info.fChild.fString = defaultValue2; + request.info ??= {}; + const defaultValue3 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fBool'], + ); + request.info.fBool = defaultValue3; + const expectedHeaderRequestParams = `info.f_string=${defaultValue1 ?? ''}&info.f_child.f_string=${defaultValue2 ?? ''}&info.f_bool=${defaultValue3 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.repeatDataPathResource = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.repeatDataPathResource(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.repeatDataPathResource as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.repeatDataPathResource as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes repeatDataBodyPut without error using callback', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatResponse() - ); - client.innerApiCalls.repeatDataBodyPut = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.repeatDataBodyPut( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IRepeatResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes repeatDataPathResource with closed client', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + request.info ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fString'], + ); + request.info.fString = defaultValue1; + request.info ??= {}; + request.info.fChild ??= {}; + const defaultValue2 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fChild', 'fString'], + ); + request.info.fChild.fString = defaultValue2; + request.info ??= {}; + const defaultValue3 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fBool'], + ); + request.info.fBool = defaultValue3; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.repeatDataPathResource(request), + expectedError, + ); + }); + }); + + describe('repeatDataPathTrailingResource', () => { + it('invokes repeatDataPathTrailingResource without error', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + request.info ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fString'], + ); + request.info.fString = defaultValue1; + request.info ??= {}; + request.info.fChild ??= {}; + const defaultValue2 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fChild', 'fString'], + ); + request.info.fChild.fString = defaultValue2; + const expectedHeaderRequestParams = `info.f_string=${defaultValue1 ?? ''}&info.f_child.f_string=${defaultValue2 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatResponse(), + ); + client.innerApiCalls.repeatDataPathTrailingResource = + stubSimpleCall(expectedResponse); + const [response] = await client.repeatDataPathTrailingResource(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.repeatDataPathTrailingResource as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.repeatDataPathTrailingResource as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes repeatDataBodyPut with error', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.repeatDataBodyPut = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.repeatDataBodyPut(request), expectedError); - }); + it('invokes repeatDataPathTrailingResource without error using callback', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + request.info ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fString'], + ); + request.info.fString = defaultValue1; + request.info ??= {}; + request.info.fChild ??= {}; + const defaultValue2 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fChild', 'fString'], + ); + request.info.fChild.fString = defaultValue2; + const expectedHeaderRequestParams = `info.f_string=${defaultValue1 ?? ''}&info.f_child.f_string=${defaultValue2 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatResponse(), + ); + client.innerApiCalls.repeatDataPathTrailingResource = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.repeatDataPathTrailingResource( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IRepeatResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.repeatDataPathTrailingResource as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.repeatDataPathTrailingResource as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes repeatDataBodyPut with closed client', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.repeatDataBodyPut(request), expectedError); - }); + it('invokes repeatDataPathTrailingResource with error', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + request.info ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fString'], + ); + request.info.fString = defaultValue1; + request.info ??= {}; + request.info.fChild ??= {}; + const defaultValue2 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fChild', 'fString'], + ); + request.info.fChild.fString = defaultValue2; + const expectedHeaderRequestParams = `info.f_string=${defaultValue1 ?? ''}&info.f_child.f_string=${defaultValue2 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.repeatDataPathTrailingResource = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.repeatDataPathTrailingResource(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.repeatDataPathTrailingResource as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.repeatDataPathTrailingResource as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('repeatDataBodyPatch', () => { - it('invokes repeatDataBodyPatch without error', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatResponse() - ); - client.innerApiCalls.repeatDataBodyPatch = stubSimpleCall(expectedResponse); - const [response] = await client.repeatDataBodyPatch(request); - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes repeatDataPathTrailingResource with closed client', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + request.info ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fString'], + ); + request.info.fString = defaultValue1; + request.info ??= {}; + request.info.fChild ??= {}; + const defaultValue2 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fChild', 'fString'], + ); + request.info.fChild.fString = defaultValue2; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.repeatDataPathTrailingResource(request), + expectedError, + ); + }); + }); + + describe('repeatDataBodyPut', () => { + it('invokes repeatDataBodyPut without error', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatResponse(), + ); + client.innerApiCalls.repeatDataBodyPut = stubSimpleCall(expectedResponse); + const [response] = await client.repeatDataBodyPut(request); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes repeatDataBodyPatch without error using callback', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatResponse() - ); - client.innerApiCalls.repeatDataBodyPatch = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.repeatDataBodyPatch( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IRepeatResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes repeatDataBodyPut without error using callback', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatResponse(), + ); + client.innerApiCalls.repeatDataBodyPut = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.repeatDataBodyPut( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IRepeatResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes repeatDataBodyPatch with error', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.repeatDataBodyPatch = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.repeatDataBodyPatch(request), expectedError); - }); + it('invokes repeatDataBodyPut with error', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.repeatDataBodyPut = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.repeatDataBodyPut(request), expectedError); + }); - it('invokes repeatDataBodyPatch with closed client', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.repeatDataBodyPatch(request), expectedError); - }); + it('invokes repeatDataBodyPut with closed client', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.repeatDataBodyPut(request), expectedError); + }); + }); + + describe('repeatDataBodyPatch', () => { + it('invokes repeatDataBodyPatch without error', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatResponse(), + ); + client.innerApiCalls.repeatDataBodyPatch = + stubSimpleCall(expectedResponse); + const [response] = await client.repeatDataBodyPatch(request); + assert.deepStrictEqual(response, expectedResponse); }); - describe('getEnum', () => { - it('invokes getEnum without error', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.EnumRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.EnumResponse() - ); - client.innerApiCalls.getEnum = stubSimpleCall(expectedResponse); - const [response] = await client.getEnum(request); - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes repeatDataBodyPatch without error using callback', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatResponse(), + ); + client.innerApiCalls.repeatDataBodyPatch = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.repeatDataBodyPatch( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IRepeatResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes getEnum without error using callback', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.EnumRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.EnumResponse() - ); - client.innerApiCalls.getEnum = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getEnum( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IEnumResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes repeatDataBodyPatch with error', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.repeatDataBodyPatch = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.repeatDataBodyPatch(request), expectedError); + }); - it('invokes getEnum with error', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.EnumRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.getEnum = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getEnum(request), expectedError); - }); + it('invokes repeatDataBodyPatch with closed client', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.repeatDataBodyPatch(request), expectedError); + }); + }); + + describe('getEnum', () => { + it('invokes getEnum without error', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.EnumRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.EnumResponse(), + ); + client.innerApiCalls.getEnum = stubSimpleCall(expectedResponse); + const [response] = await client.getEnum(request); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes getEnum with closed client', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.EnumRequest() - ); - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getEnum(request), expectedError); - }); + it('invokes getEnum without error using callback', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.EnumRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.EnumResponse(), + ); + client.innerApiCalls.getEnum = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getEnum( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IEnumResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); }); - describe('verifyEnum', () => { - it('invokes verifyEnum without error', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.EnumResponse() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.EnumResponse() - ); - client.innerApiCalls.verifyEnum = stubSimpleCall(expectedResponse); - const [response] = await client.verifyEnum(request); - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes getEnum with error', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.EnumRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.getEnum = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.getEnum(request), expectedError); + }); - it('invokes verifyEnum without error using callback', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.EnumResponse() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.EnumResponse() - ); - client.innerApiCalls.verifyEnum = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.verifyEnum( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IEnumResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes getEnum with closed client', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.EnumRequest(), + ); + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getEnum(request), expectedError); + }); + }); + + describe('verifyEnum', () => { + it('invokes verifyEnum without error', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.EnumResponse(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.EnumResponse(), + ); + client.innerApiCalls.verifyEnum = stubSimpleCall(expectedResponse); + const [response] = await client.verifyEnum(request); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes verifyEnum with error', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.EnumResponse() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.verifyEnum = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.verifyEnum(request), expectedError); - }); + it('invokes verifyEnum without error using callback', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.EnumResponse(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.EnumResponse(), + ); + client.innerApiCalls.verifyEnum = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.verifyEnum( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IEnumResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes verifyEnum with closed client', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.EnumResponse() - ); - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.verifyEnum(request), expectedError); - }); + it('invokes verifyEnum with error', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.EnumResponse(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.verifyEnum = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.verifyEnum(request), expectedError); }); - describe('Path templates', () => { - - describe('blueprint', () => { - const fakePath = "/rendered/path/blueprint"; - const expectedParameters = { - session: "sessionValue", - test: "testValue", - blueprint: "blueprintValue", - }; - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.blueprintPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.blueprintPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('blueprintPath', () => { - const result = client.blueprintPath("sessionValue", "testValue", "blueprintValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.blueprintPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchSessionFromBlueprintName', () => { - const result = client.matchSessionFromBlueprintName(fakePath); - assert.strictEqual(result, "sessionValue"); - assert((client.pathTemplates.blueprintPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchTestFromBlueprintName', () => { - const result = client.matchTestFromBlueprintName(fakePath); - assert.strictEqual(result, "testValue"); - assert((client.pathTemplates.blueprintPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBlueprintFromBlueprintName', () => { - const result = client.matchBlueprintFromBlueprintName(fakePath); - assert.strictEqual(result, "blueprintValue"); - assert((client.pathTemplates.blueprintPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('invokes verifyEnum with closed client', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.EnumResponse(), + ); + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.verifyEnum(request), expectedError); + }); + }); + + describe('Path templates', () => { + describe('blueprint', () => { + const fakePath = '/rendered/path/blueprint'; + const expectedParameters = { + session: 'sessionValue', + test: 'testValue', + blueprint: 'blueprintValue', + }; + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.blueprintPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.blueprintPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('blueprintPath', () => { + const result = client.blueprintPath( + 'sessionValue', + 'testValue', + 'blueprintValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.blueprintPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchSessionFromBlueprintName', () => { + const result = client.matchSessionFromBlueprintName(fakePath); + assert.strictEqual(result, 'sessionValue'); + assert( + (client.pathTemplates.blueprintPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchTestFromBlueprintName', () => { + const result = client.matchTestFromBlueprintName(fakePath); + assert.strictEqual(result, 'testValue'); + assert( + (client.pathTemplates.blueprintPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBlueprintFromBlueprintName', () => { + const result = client.matchBlueprintFromBlueprintName(fakePath); + assert.strictEqual(result, 'blueprintValue'); + assert( + (client.pathTemplates.blueprintPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('room', () => { - const fakePath = "/rendered/path/room"; - const expectedParameters = { - room: "roomValue", - }; - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.roomPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.roomPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('roomPath', () => { - const result = client.roomPath("roomValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.roomPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchRoomFromRoomName', () => { - const result = client.matchRoomFromRoomName(fakePath); - assert.strictEqual(result, "roomValue"); - assert((client.pathTemplates.roomPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('room', () => { + const fakePath = '/rendered/path/room'; + const expectedParameters = { + room: 'roomValue', + }; + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.roomPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.roomPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('roomPath', () => { + const result = client.roomPath('roomValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.roomPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchRoomFromRoomName', () => { + const result = client.matchRoomFromRoomName(fakePath); + assert.strictEqual(result, 'roomValue'); + assert( + (client.pathTemplates.roomPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('roomBlurb', () => { - const fakePath = "/rendered/path/roomBlurb"; - const expectedParameters = { - room: "roomValue", - blurb: "blurbValue", - }; - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.roomBlurbPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.roomBlurbPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('roomBlurbPath', () => { - const result = client.roomBlurbPath("roomValue", "blurbValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.roomBlurbPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchRoomFromRoomBlurbName', () => { - const result = client.matchRoomFromRoomBlurbName(fakePath); - assert.strictEqual(result, "roomValue"); - assert((client.pathTemplates.roomBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBlurbFromRoomBlurbName', () => { - const result = client.matchBlurbFromRoomBlurbName(fakePath); - assert.strictEqual(result, "blurbValue"); - assert((client.pathTemplates.roomBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('roomBlurb', () => { + const fakePath = '/rendered/path/roomBlurb'; + const expectedParameters = { + room: 'roomValue', + blurb: 'blurbValue', + }; + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.roomBlurbPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.roomBlurbPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('roomBlurbPath', () => { + const result = client.roomBlurbPath('roomValue', 'blurbValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.roomBlurbPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchRoomFromRoomBlurbName', () => { + const result = client.matchRoomFromRoomBlurbName(fakePath); + assert.strictEqual(result, 'roomValue'); + assert( + (client.pathTemplates.roomBlurbPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBlurbFromRoomBlurbName', () => { + const result = client.matchBlurbFromRoomBlurbName(fakePath); + assert.strictEqual(result, 'blurbValue'); + assert( + (client.pathTemplates.roomBlurbPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('roomBlurbsLegacyRoomBlurb', () => { - const fakePath = "/rendered/path/roomBlurbsLegacyRoomBlurb"; - const expectedParameters = { - room: "roomValue", - legacy_room: "legacyRoomValue", - blurb: "blurbValue", - }; - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('roomBlurbsLegacyRoomBlurbPath', () => { - const result = client.roomBlurbsLegacyRoomBlurbPath("roomValue", "legacyRoomValue", "blurbValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchRoomFromRoomBlurbsLegacyRoomBlurbName', () => { - const result = client.matchRoomFromRoomBlurbsLegacyRoomBlurbName(fakePath); - assert.strictEqual(result, "roomValue"); - assert((client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName', () => { - const result = client.matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName(fakePath); - assert.strictEqual(result, "legacyRoomValue"); - assert((client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBlurbFromRoomBlurbsLegacyRoomBlurbName', () => { - const result = client.matchBlurbFromRoomBlurbsLegacyRoomBlurbName(fakePath); - assert.strictEqual(result, "blurbValue"); - assert((client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('roomBlurbsLegacyRoomBlurb', () => { + const fakePath = '/rendered/path/roomBlurbsLegacyRoomBlurb'; + const expectedParameters = { + room: 'roomValue', + legacy_room: 'legacyRoomValue', + blurb: 'blurbValue', + }; + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('roomBlurbsLegacyRoomBlurbPath', () => { + const result = client.roomBlurbsLegacyRoomBlurbPath( + 'roomValue', + 'legacyRoomValue', + 'blurbValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchRoomFromRoomBlurbsLegacyRoomBlurbName', () => { + const result = + client.matchRoomFromRoomBlurbsLegacyRoomBlurbName(fakePath); + assert.strictEqual(result, 'roomValue'); + assert( + ( + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName', () => { + const result = + client.matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName(fakePath); + assert.strictEqual(result, 'legacyRoomValue'); + assert( + ( + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBlurbFromRoomBlurbsLegacyRoomBlurbName', () => { + const result = + client.matchBlurbFromRoomBlurbsLegacyRoomBlurbName(fakePath); + assert.strictEqual(result, 'blurbValue'); + assert( + ( + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('sequence', () => { - const fakePath = "/rendered/path/sequence"; - const expectedParameters = { - sequence: "sequenceValue", - }; - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.sequencePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.sequencePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('sequencePath', () => { - const result = client.sequencePath("sequenceValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.sequencePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchSequenceFromSequenceName', () => { - const result = client.matchSequenceFromSequenceName(fakePath); - assert.strictEqual(result, "sequenceValue"); - assert((client.pathTemplates.sequencePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('sequence', () => { + const fakePath = '/rendered/path/sequence'; + const expectedParameters = { + sequence: 'sequenceValue', + }; + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.sequencePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.sequencePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('sequencePath', () => { + const result = client.sequencePath('sequenceValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.sequencePathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchSequenceFromSequenceName', () => { + const result = client.matchSequenceFromSequenceName(fakePath); + assert.strictEqual(result, 'sequenceValue'); + assert( + (client.pathTemplates.sequencePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('sequenceReport', () => { - const fakePath = "/rendered/path/sequenceReport"; - const expectedParameters = { - sequence: "sequenceValue", - }; - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.sequenceReportPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.sequenceReportPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('sequenceReportPath', () => { - const result = client.sequenceReportPath("sequenceValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.sequenceReportPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchSequenceFromSequenceReportName', () => { - const result = client.matchSequenceFromSequenceReportName(fakePath); - assert.strictEqual(result, "sequenceValue"); - assert((client.pathTemplates.sequenceReportPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('sequenceReport', () => { + const fakePath = '/rendered/path/sequenceReport'; + const expectedParameters = { + sequence: 'sequenceValue', + }; + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.sequenceReportPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.sequenceReportPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('sequenceReportPath', () => { + const result = client.sequenceReportPath('sequenceValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.sequenceReportPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchSequenceFromSequenceReportName', () => { + const result = client.matchSequenceFromSequenceReportName(fakePath); + assert.strictEqual(result, 'sequenceValue'); + assert( + (client.pathTemplates.sequenceReportPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('session', () => { - const fakePath = "/rendered/path/session"; - const expectedParameters = { - session: "sessionValue", - }; - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.sessionPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.sessionPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('sessionPath', () => { - const result = client.sessionPath("sessionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.sessionPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchSessionFromSessionName', () => { - const result = client.matchSessionFromSessionName(fakePath); - assert.strictEqual(result, "sessionValue"); - assert((client.pathTemplates.sessionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('session', () => { + const fakePath = '/rendered/path/session'; + const expectedParameters = { + session: 'sessionValue', + }; + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.sessionPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.sessionPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('sessionPath', () => { + const result = client.sessionPath('sessionValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.sessionPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchSessionFromSessionName', () => { + const result = client.matchSessionFromSessionName(fakePath); + assert.strictEqual(result, 'sessionValue'); + assert( + (client.pathTemplates.sessionPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('test', () => { - const fakePath = "/rendered/path/test"; - const expectedParameters = { - session: "sessionValue", - test: "testValue", - }; - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.testPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.testPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('testPath', () => { - const result = client.testPath("sessionValue", "testValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.testPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchSessionFromTestName', () => { - const result = client.matchSessionFromTestName(fakePath); - assert.strictEqual(result, "sessionValue"); - assert((client.pathTemplates.testPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchTestFromTestName', () => { - const result = client.matchTestFromTestName(fakePath); - assert.strictEqual(result, "testValue"); - assert((client.pathTemplates.testPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('test', () => { + const fakePath = '/rendered/path/test'; + const expectedParameters = { + session: 'sessionValue', + test: 'testValue', + }; + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.testPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.testPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('testPath', () => { + const result = client.testPath('sessionValue', 'testValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.testPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchSessionFromTestName', () => { + const result = client.matchSessionFromTestName(fakePath); + assert.strictEqual(result, 'sessionValue'); + assert( + (client.pathTemplates.testPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchTestFromTestName', () => { + const result = client.matchTestFromTestName(fakePath); + assert.strictEqual(result, 'testValue'); + assert( + (client.pathTemplates.testPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('user', () => { - const fakePath = "/rendered/path/user"; - const expectedParameters = { - user: "userValue", - }; - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.userPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.userPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('userPath', () => { - const result = client.userPath("userValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.userPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchUserFromUserName', () => { - const result = client.matchUserFromUserName(fakePath); - assert.strictEqual(result, "userValue"); - assert((client.pathTemplates.userPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('user', () => { + const fakePath = '/rendered/path/user'; + const expectedParameters = { + user: 'userValue', + }; + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.userPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.userPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('userPath', () => { + const result = client.userPath('userValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.userPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchUserFromUserName', () => { + const result = client.matchUserFromUserName(fakePath); + assert.strictEqual(result, 'userValue'); + assert( + (client.pathTemplates.userPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('userProfileBlurb', () => { - const fakePath = "/rendered/path/userProfileBlurb"; - const expectedParameters = { - user: "userValue", - blurb: "blurbValue", - }; - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.userProfileBlurbPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.userProfileBlurbPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('userProfileBlurbPath', () => { - const result = client.userProfileBlurbPath("userValue", "blurbValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.userProfileBlurbPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchUserFromUserProfileBlurbName', () => { - const result = client.matchUserFromUserProfileBlurbName(fakePath); - assert.strictEqual(result, "userValue"); - assert((client.pathTemplates.userProfileBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBlurbFromUserProfileBlurbName', () => { - const result = client.matchBlurbFromUserProfileBlurbName(fakePath); - assert.strictEqual(result, "blurbValue"); - assert((client.pathTemplates.userProfileBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('userProfileBlurb', () => { + const fakePath = '/rendered/path/userProfileBlurb'; + const expectedParameters = { + user: 'userValue', + blurb: 'blurbValue', + }; + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.userProfileBlurbPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.userProfileBlurbPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('userProfileBlurbPath', () => { + const result = client.userProfileBlurbPath('userValue', 'blurbValue'); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.userProfileBlurbPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchUserFromUserProfileBlurbName', () => { + const result = client.matchUserFromUserProfileBlurbName(fakePath); + assert.strictEqual(result, 'userValue'); + assert( + (client.pathTemplates.userProfileBlurbPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBlurbFromUserProfileBlurbName', () => { + const result = client.matchBlurbFromUserProfileBlurbName(fakePath); + assert.strictEqual(result, 'blurbValue'); + assert( + (client.pathTemplates.userProfileBlurbPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('userProfileBlurbsLegacyUserBlurb', () => { - const fakePath = "/rendered/path/userProfileBlurbsLegacyUserBlurb"; - const expectedParameters = { - user: "userValue", - legacy_user: "legacyUserValue", - blurb: "blurbValue", - }; - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('userProfileBlurbsLegacyUserBlurbPath', () => { - const result = client.userProfileBlurbsLegacyUserBlurbPath("userValue", "legacyUserValue", "blurbValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchUserFromUserProfileBlurbsLegacyUserBlurbName', () => { - const result = client.matchUserFromUserProfileBlurbsLegacyUserBlurbName(fakePath); - assert.strictEqual(result, "userValue"); - assert((client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName', () => { - const result = client.matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName(fakePath); - assert.strictEqual(result, "legacyUserValue"); - assert((client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBlurbFromUserProfileBlurbsLegacyUserBlurbName', () => { - const result = client.matchBlurbFromUserProfileBlurbsLegacyUserBlurbName(fakePath); - assert.strictEqual(result, "blurbValue"); - assert((client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('userProfileBlurbsLegacyUserBlurb', () => { + const fakePath = '/rendered/path/userProfileBlurbsLegacyUserBlurb'; + const expectedParameters = { + user: 'userValue', + legacy_user: 'legacyUserValue', + blurb: 'blurbValue', + }; + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('userProfileBlurbsLegacyUserBlurbPath', () => { + const result = client.userProfileBlurbsLegacyUserBlurbPath( + 'userValue', + 'legacyUserValue', + 'blurbValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchUserFromUserProfileBlurbsLegacyUserBlurbName', () => { + const result = + client.matchUserFromUserProfileBlurbsLegacyUserBlurbName(fakePath); + assert.strictEqual(result, 'userValue'); + assert( + ( + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName', () => { + const result = + client.matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName( + fakePath, + ); + assert.strictEqual(result, 'legacyUserValue'); + assert( + ( + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBlurbFromUserProfileBlurbsLegacyUserBlurbName', () => { + const result = + client.matchBlurbFromUserProfileBlurbsLegacyUserBlurbName(fakePath); + assert.strictEqual(result, 'blurbValue'); + assert( + ( + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/core/generator/gapic-generator-typescript/baselines/showcase-esm/esm/test/gapic_echo_v1beta1.ts.baseline b/core/generator/gapic-generator-typescript/baselines/showcase-esm/esm/test/gapic_echo_v1beta1.ts.baseline index dbae7ddd07fc..889c6f672f35 100644 --- a/core/generator/gapic-generator-typescript/baselines/showcase-esm/esm/test/gapic_echo_v1beta1.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/showcase-esm/esm/test/gapic_echo_v1beta1.ts.baseline @@ -20,16 +20,16 @@ import * as protos from '../../protos/protos.js'; import assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as echoModule from '../src/index.js'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; -import {protobuf, LROperation, operationsProtos} from 'google-gax'; +import { protobuf, LROperation, operationsProtos } from 'google-gax'; import fs from 'fs'; import path from 'path'; -import {fileURLToPath} from 'url'; +import { fileURLToPath } from 'url'; // @ts-ignore const dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -37,1507 +37,1946 @@ const dirname = path.dirname(fileURLToPath(import.meta.url)); // to fill in default values for request objects const root = protobuf.Root.fromJSON( JSON.parse( - fs.readFileSync(path.join(dirname, '..', '..', 'protos/protos.json'), 'utf8') - )) + fs.readFileSync( + path.join(dirname, '..', '..', 'protos/protos.json'), + 'utf8', + ), + ), +); // eslint-disable-next-line @typescript-eslint/no-unused-vars function getTypeDefaultValue(typeName: string, fields: string[]) { - let type = root.lookupType(typeName) as protobuf.Type; - for (const field of fields.slice(0, -1)) { - type = type?.fields[field]?.resolvedType as protobuf.Type; - } - return type?.fields[fields[fields.length - 1]]?.defaultValue ?? null; + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type?.fields[field]?.resolvedType as protobuf.Type; + } + return type?.fields[fields[fields.length - 1]]?.defaultValue ?? null; } function generateSampleMessage(instance: T) { - const filledObject = (instance.constructor as typeof protobuf.Message) - .toObject(instance as protobuf.Message, {defaults: true}); - return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, { defaults: true }); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; } function stubSimpleCall(response?: ResponseType, error?: Error) { - return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); } -function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { - return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +function stubSimpleCallWithCallback( + response?: ResponseType, + error?: Error, +) { + return error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); } -function stubServerStreamingCall(response?: ResponseType, error?: Error) { - const transformStub = error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); - const mockStream = new PassThrough({ - objectMode: true, - transform: transformStub, - }); - // write something to the stream to trigger transformStub and send the response back to the client - setImmediate(() => { mockStream.write({}); }); - setImmediate(() => { mockStream.end(); }); - return sinon.stub().returns(mockStream); +function stubServerStreamingCall( + response?: ResponseType, + error?: Error, +) { + const transformStub = error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + // write something to the stream to trigger transformStub and send the response back to the client + setImmediate(() => { + mockStream.write({}); + }); + setImmediate(() => { + mockStream.end(); + }); + return sinon.stub().returns(mockStream); } -function stubBidiStreamingCall(response?: ResponseType, error?: Error) { - const transformStub = error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); - const mockStream = new PassThrough({ - objectMode: true, - transform: transformStub, - }); - return sinon.stub().returns(mockStream); +function stubBidiStreamingCall( + response?: ResponseType, + error?: Error, +) { + const transformStub = error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + return sinon.stub().returns(mockStream); } -function stubClientStreamingCall(response?: ResponseType, error?: Error) { - if (error) { - return sinon.stub().callsArgWith(2, error); - } - const transformStub = sinon.stub(); - const mockStream = new PassThrough({ - objectMode: true, - transform: transformStub, - }); - return sinon.stub().returns(mockStream).callsArgWith(2, null, response); +function stubClientStreamingCall( + response?: ResponseType, + error?: Error, +) { + if (error) { + return sinon.stub().callsArgWith(2, error); + } + const transformStub = sinon.stub(); + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + return sinon.stub().returns(mockStream).callsArgWith(2, null, response); } -function stubLongRunningCall(response?: ResponseType, callError?: Error, lroError?: Error) { - const innerStub = lroError ? sinon.stub().rejects(lroError) : sinon.stub().resolves([response]); - const mockOperation = { - promise: innerStub, - }; - return callError ? sinon.stub().rejects(callError) : sinon.stub().resolves([mockOperation]); +function stubLongRunningCall( + response?: ResponseType, + callError?: Error, + lroError?: Error, +) { + const innerStub = lroError + ? sinon.stub().rejects(lroError) + : sinon.stub().resolves([response]); + const mockOperation = { + promise: innerStub, + }; + return callError + ? sinon.stub().rejects(callError) + : sinon.stub().resolves([mockOperation]); } -function stubLongRunningCallWithCallback(response?: ResponseType, callError?: Error, lroError?: Error) { - const innerStub = lroError ? sinon.stub().rejects(lroError) : sinon.stub().resolves([response]); - const mockOperation = { - promise: innerStub, - }; - return callError ? sinon.stub().callsArgWith(2, callError) : sinon.stub().callsArgWith(2, null, mockOperation); +function stubLongRunningCallWithCallback( + response?: ResponseType, + callError?: Error, + lroError?: Error, +) { + const innerStub = lroError + ? sinon.stub().rejects(lroError) + : sinon.stub().resolves([response]); + const mockOperation = { + promise: innerStub, + }; + return callError + ? sinon.stub().callsArgWith(2, callError) + : sinon.stub().callsArgWith(2, null, mockOperation); } -function stubPageStreamingCall(responses?: ResponseType[], error?: Error) { - const pagingStub = sinon.stub(); - if (responses) { - for (let i = 0; i < responses.length; ++i) { - pagingStub.onCall(i).callsArgWith(2, null, responses[i]); - } +function stubPageStreamingCall( + responses?: ResponseType[], + error?: Error, +) { + const pagingStub = sinon.stub(); + if (responses) { + for (let i = 0; i < responses.length; ++i) { + pagingStub.onCall(i).callsArgWith(2, null, responses[i]); } - const transformStub = error ? sinon.stub().callsArgWith(2, error) : pagingStub; - const mockStream = new PassThrough({ - objectMode: true, - transform: transformStub, - }); - // trigger as many responses as needed - if (responses) { - for (let i = 0; i < responses.length; ++i) { - setImmediate(() => { mockStream.write({}); }); - } - setImmediate(() => { mockStream.end(); }); - } else { - setImmediate(() => { mockStream.write({}); }); - setImmediate(() => { mockStream.end(); }); + } + const transformStub = error + ? sinon.stub().callsArgWith(2, error) + : pagingStub; + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + // trigger as many responses as needed + if (responses) { + for (let i = 0; i < responses.length; ++i) { + setImmediate(() => { + mockStream.write({}); + }); } - return sinon.stub().returns(mockStream); + setImmediate(() => { + mockStream.end(); + }); + } else { + setImmediate(() => { + mockStream.write({}); + }); + setImmediate(() => { + mockStream.end(); + }); + } + return sinon.stub().returns(mockStream); } -function stubAsyncIterationCall(responses?: ResponseType[], error?: Error) { - let counter = 0; - const asyncIterable = { - [Symbol.asyncIterator]() { - return { - async next() { - if (error) { - return Promise.reject(error); - } - if (counter >= responses!.length) { - return Promise.resolve({done: true, value: undefined}); - } - return Promise.resolve({done: false, value: responses![counter++]}); - } - }; - } - }; - return sinon.stub().returns(asyncIterable); +function stubAsyncIterationCall( + responses?: ResponseType[], + error?: Error, +) { + let counter = 0; + const asyncIterable = { + [Symbol.asyncIterator]() { + return { + async next() { + if (error) { + return Promise.reject(error); + } + if (counter >= responses!.length) { + return Promise.resolve({ done: true, value: undefined }); + } + return Promise.resolve({ done: false, value: responses![counter++] }); + }, + }; + }, + }; + return sinon.stub().returns(asyncIterable); } describe('v1beta1.EchoClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new echoModule.v1beta1.EchoClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'localhost'); - }); - - it('has universeDomain', () => { - const client = new echoModule.v1beta1.EchoClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); - - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - it('throws DeprecationWarning if static servicePath is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const servicePath = echoModule.v1beta1.EchoClient.servicePath; - assert.strictEqual(servicePath, 'localhost'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = echoModule.v1beta1.EchoClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'localhost'); - assert(stub.called); - stub.restore(); - }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { new echoModule.v1beta1.EchoClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); - - it('has port', () => { - const port = echoModule.v1beta1.EchoClient.port; - assert(port); - assert(typeof port === 'number'); - }); - - it('should create a client with no option', () => { - const client = new echoModule.v1beta1.EchoClient(); - assert(client); - }); - - it('should create a client with gRPC fallback', () => { - const client = new echoModule.v1beta1.EchoClient({ - fallback: true, - }); - assert(client); - }); - - it('has initialize method and supports deferred initialization', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.echoStub, undefined); - await client.initialize(); - assert(client.echoStub); - }); - - it('has close method for the initialized client', done => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.echoStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); - - it('has close method for the non-initialized client', done => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.echoStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new echoModule.v1beta1.EchoClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'localhost'); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); - }); + it('has universeDomain', () => { + const client = new echoModule.v1beta1.EchoClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId((err?: Error|null, projectId?: string|null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } - }); - }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = echoModule.v1beta1.EchoClient.servicePath; + assert.strictEqual(servicePath, 'localhost'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = echoModule.v1beta1.EchoClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'localhost'); + assert(stub.called); + stub.restore(); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new echoModule.v1beta1.EchoClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); }); - describe('echo', () => { - it('invokes echo without error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.EchoRequest() - ); - // path template: {qux=projects/*}/** - request.otherHeader = 'projects/value/value'; - const expectedHeaderRequestParams = 'qux=projects%2Fvalue'; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.EchoResponse() - ); - client.innerApiCalls.echo = stubSimpleCall(expectedResponse); - const [response] = await client.echo(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.echo as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.echo as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - assert.match((client.innerApiCalls.echo as SinonStub) - .getCall(0).args[0].requestId, /[a-z0-9-]{36}/) - }); + it('has port', () => { + const port = echoModule.v1beta1.EchoClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('invokes echo without error using callback', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.EchoRequest() - ); - // path template: {qux=projects/*}/** - request.otherHeader = 'projects/value/value'; - const expectedHeaderRequestParams = 'qux=projects%2Fvalue'; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.EchoResponse() - ); - client.innerApiCalls.echo = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.echo( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IEchoResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.echo as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.echo as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - assert.match((client.innerApiCalls.echo as SinonStub) - .getCall(0).args[0].requestId, /[a-z0-9-]{36}/) - }); + it('should create a client with no option', () => { + const client = new echoModule.v1beta1.EchoClient(); + assert(client); + }); - it('invokes echo with error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.EchoRequest() - ); - // path template: {qux=projects/*}/** - request.otherHeader = 'projects/value/value'; - const expectedHeaderRequestParams = 'qux=projects%2Fvalue'; - const expectedError = new Error('expected'); - client.innerApiCalls.echo = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.echo(request), expectedError); - const actualRequest = (client.innerApiCalls.echo as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.echo as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - assert.match((client.innerApiCalls.echo as SinonStub) - .getCall(0).args[0].requestId, /[a-z0-9-]{36}/) - }); + it('should create a client with gRPC fallback', () => { + const client = new echoModule.v1beta1.EchoClient({ + fallback: true, + }); + assert(client); + }); - it('invokes echo with closed client', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.EchoRequest() - ); - // path template: {qux=projects/*}/** - request.otherHeader = 'projects/value/value'; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.echo(request), expectedError); - }); + it('has initialize method and supports deferred initialization', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.echoStub, undefined); + await client.initialize(); + assert(client.echoStub); }); - describe('echoErrorDetails', () => { - it('invokes echoErrorDetails without error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.EchoErrorDetailsRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.EchoErrorDetailsResponse() - ); - client.innerApiCalls.echoErrorDetails = stubSimpleCall(expectedResponse); - const [response] = await client.echoErrorDetails(request); - assert.deepStrictEqual(response, expectedResponse); + it('has close method for the initialized client', (done) => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.echoStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes echoErrorDetails without error using callback', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.EchoErrorDetailsRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.EchoErrorDetailsResponse() - ); - client.innerApiCalls.echoErrorDetails = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.echoErrorDetails( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IEchoErrorDetailsResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); + it('has close method for the non-initialized client', (done) => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.echoStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes echoErrorDetails with error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.EchoErrorDetailsRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.echoErrorDetails = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.echoErrorDetails(request), expectedError); - }); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + }); - it('invokes echoErrorDetails with closed client', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.EchoErrorDetailsRequest() - ); - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.echoErrorDetails(request), expectedError); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + }); + + describe('echo', () => { + it('invokes echo without error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.EchoRequest(), + ); + // path template: {qux=projects/*}/** + request.otherHeader = 'projects/value/value'; + const expectedHeaderRequestParams = 'qux=projects%2Fvalue'; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.EchoResponse(), + ); + client.innerApiCalls.echo = stubSimpleCall(expectedResponse); + const [response] = await client.echo(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.echo as SinonStub).getCall(0) + .args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.echo as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + assert.match( + (client.innerApiCalls.echo as SinonStub).getCall(0).args[0].requestId, + /[a-z0-9-]{36}/, + ); }); - describe('pagedExpandLegacy', () => { - it('invokes pagedExpandLegacy without error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.PagedExpandLegacyRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.PagedExpandResponse() - ); - client.innerApiCalls.pagedExpandLegacy = stubSimpleCall(expectedResponse); - const [response] = await client.pagedExpandLegacy(request); - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes echo without error using callback', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.EchoRequest(), + ); + // path template: {qux=projects/*}/** + request.otherHeader = 'projects/value/value'; + const expectedHeaderRequestParams = 'qux=projects%2Fvalue'; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.EchoResponse(), + ); + client.innerApiCalls.echo = stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.echo( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IEchoResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.echo as SinonStub).getCall(0) + .args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.echo as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + assert.match( + (client.innerApiCalls.echo as SinonStub).getCall(0).args[0].requestId, + /[a-z0-9-]{36}/, + ); + }); - it('invokes pagedExpandLegacy without error using callback', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.PagedExpandLegacyRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.PagedExpandResponse() - ); - client.innerApiCalls.pagedExpandLegacy = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.pagedExpandLegacy( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IPagedExpandResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes echo with error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.EchoRequest(), + ); + // path template: {qux=projects/*}/** + request.otherHeader = 'projects/value/value'; + const expectedHeaderRequestParams = 'qux=projects%2Fvalue'; + const expectedError = new Error('expected'); + client.innerApiCalls.echo = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.echo(request), expectedError); + const actualRequest = (client.innerApiCalls.echo as SinonStub).getCall(0) + .args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.echo as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + assert.match( + (client.innerApiCalls.echo as SinonStub).getCall(0).args[0].requestId, + /[a-z0-9-]{36}/, + ); + }); - it('invokes pagedExpandLegacy with error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.PagedExpandLegacyRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.pagedExpandLegacy = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.pagedExpandLegacy(request), expectedError); - }); + it('invokes echo with closed client', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.EchoRequest(), + ); + // path template: {qux=projects/*}/** + request.otherHeader = 'projects/value/value'; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.echo(request), expectedError); + }); + }); + + describe('echoErrorDetails', () => { + it('invokes echoErrorDetails without error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.EchoErrorDetailsRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.EchoErrorDetailsResponse(), + ); + client.innerApiCalls.echoErrorDetails = stubSimpleCall(expectedResponse); + const [response] = await client.echoErrorDetails(request); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes pagedExpandLegacy with closed client', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.PagedExpandLegacyRequest() - ); - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.pagedExpandLegacy(request), expectedError); - }); + it('invokes echoErrorDetails without error using callback', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.EchoErrorDetailsRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.EchoErrorDetailsResponse(), + ); + client.innerApiCalls.echoErrorDetails = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.echoErrorDetails( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IEchoErrorDetailsResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); }); - describe('block', () => { - it('invokes block without error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.BlockRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.BlockResponse() - ); - client.innerApiCalls.block = stubSimpleCall(expectedResponse); - const [response] = await client.block(request); - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes echoErrorDetails with error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.EchoErrorDetailsRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.echoErrorDetails = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.echoErrorDetails(request), expectedError); + }); - it('invokes block without error using callback', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.BlockRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.BlockResponse() - ); - client.innerApiCalls.block = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.block( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IBlockResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes echoErrorDetails with closed client', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.EchoErrorDetailsRequest(), + ); + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.echoErrorDetails(request), expectedError); + }); + }); + + describe('pagedExpandLegacy', () => { + it('invokes pagedExpandLegacy without error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.PagedExpandLegacyRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.PagedExpandResponse(), + ); + client.innerApiCalls.pagedExpandLegacy = stubSimpleCall(expectedResponse); + const [response] = await client.pagedExpandLegacy(request); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes block with error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.BlockRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.block = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.block(request), expectedError); - }); + it('invokes pagedExpandLegacy without error using callback', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.PagedExpandLegacyRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.PagedExpandResponse(), + ); + client.innerApiCalls.pagedExpandLegacy = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.pagedExpandLegacy( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IPagedExpandResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes block with closed client', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.BlockRequest() - ); - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.block(request), expectedError); - }); + it('invokes pagedExpandLegacy with error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.PagedExpandLegacyRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.pagedExpandLegacy = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.pagedExpandLegacy(request), expectedError); }); - describe('wait', () => { - it('invokes wait without error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.WaitRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.wait = stubLongRunningCall(expectedResponse); - const [operation] = await client.wait(request); - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes pagedExpandLegacy with closed client', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.PagedExpandLegacyRequest(), + ); + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.pagedExpandLegacy(request), expectedError); + }); + }); + + describe('block', () => { + it('invokes block without error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.BlockRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.BlockResponse(), + ); + client.innerApiCalls.block = stubSimpleCall(expectedResponse); + const [response] = await client.block(request); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes wait without error using callback', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.WaitRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.wait = stubLongRunningCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.wait( - request, - (err?: Error|null, - result?: LROperation|null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const operation = await promise as LROperation; - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes block without error using callback', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.BlockRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.BlockResponse(), + ); + client.innerApiCalls.block = stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.block( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IBlockResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes wait with call error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.WaitRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.wait = stubLongRunningCall(undefined, expectedError); - await assert.rejects(client.wait(request), expectedError); - }); + it('invokes block with error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.BlockRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.block = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.block(request), expectedError); + }); - it('invokes wait with LRO error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.WaitRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.wait = stubLongRunningCall(undefined, undefined, expectedError); - const [operation] = await client.wait(request); - await assert.rejects(operation.promise(), expectedError); - }); + it('invokes block with closed client', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.BlockRequest(), + ); + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.block(request), expectedError); + }); + }); + + describe('wait', () => { + it('invokes wait without error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.WaitRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.wait = stubLongRunningCall(expectedResponse); + const [operation] = await client.wait(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes checkWaitProgress without error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedResponse = generateSampleMessage( - new operationsProtos.google.longrunning.Operation() - ); - expectedResponse.name = 'test'; - expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; - expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')} - - client.operationsClient.getOperation = stubSimpleCall(expectedResponse); - const decodedOperation = await client.checkWaitProgress(expectedResponse.name); - assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); - assert(decodedOperation.metadata); - assert((client.operationsClient.getOperation as SinonStub).getCall(0)); - }); + it('invokes wait without error using callback', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.WaitRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.wait = + stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.wait( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.showcase.v1beta1.IWaitResponse, + protos.google.showcase.v1beta1.IWaitMetadata + > | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const operation = (await promise) as LROperation< + protos.google.showcase.v1beta1.IWaitResponse, + protos.google.showcase.v1beta1.IWaitMetadata + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes checkWaitProgress with error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedError = new Error('expected'); - - client.operationsClient.getOperation = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.checkWaitProgress(''), expectedError); - assert((client.operationsClient.getOperation as SinonStub) - .getCall(0)); - }); + it('invokes wait with call error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.WaitRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.wait = stubLongRunningCall(undefined, expectedError); + await assert.rejects(client.wait(request), expectedError); }); - describe('expand', () => { - it('invokes expand without error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ExpandRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.EchoResponse() - ); - client.innerApiCalls.expand = stubServerStreamingCall(expectedResponse); - const stream = client.expand(request); - const promise = new Promise((resolve, reject) => { - stream.on('data', (response: protos.google.showcase.v1beta1.EchoResponse) => { - resolve(response); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes wait with LRO error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.WaitRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.wait = stubLongRunningCall( + undefined, + undefined, + expectedError, + ); + const [operation] = await client.wait(request); + await assert.rejects(operation.promise(), expectedError); + }); - it('invokes expand without error and gaxServerStreamingRetries enabled', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ExpandRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.EchoResponse() - ); - client.innerApiCalls.expand = stubServerStreamingCall(expectedResponse); - const stream = client.expand(request); - const promise = new Promise((resolve, reject) => { - stream.on('data', (response: protos.google.showcase.v1beta1.EchoResponse) => { - resolve(response); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes checkWaitProgress without error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation(), + ); + expectedResponse.name = 'test'; + expectedResponse.response = { type_url: 'url', value: Buffer.from('') }; + expectedResponse.metadata = { type_url: 'url', value: Buffer.from('') }; + + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const decodedOperation = await client.checkWaitProgress( + expectedResponse.name, + ); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); - it('invokes expand with error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ExpandRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.expand = stubServerStreamingCall(undefined, expectedError); - const stream = client.expand(request); - const promise = new Promise((resolve, reject) => { - stream.on('data', (response: protos.google.showcase.v1beta1.EchoResponse) => { - resolve(response); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); + it('invokes checkWaitProgress with error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const expectedError = new Error('expected'); + + client.operationsClient.getOperation = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.checkWaitProgress(''), expectedError); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + }); + + describe('expand', () => { + it('invokes expand without error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ExpandRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.EchoResponse(), + ); + client.innerApiCalls.expand = stubServerStreamingCall(expectedResponse); + const stream = client.expand(request); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + (response: protos.google.showcase.v1beta1.EchoResponse) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes expand with closed client', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ExpandRequest() - ); - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - const stream = client.expand(request, {retryRequestOptions: {noResponseRetries: 0}}); - const promise = new Promise((resolve, reject) => { - stream.on('data', (response: protos.google.showcase.v1beta1.EchoResponse) => { - resolve(response); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - }); - it('should create a client with gaxServerStreamingRetries enabled', () => { - const client = new echoModule.v1beta1.EchoClient({ - gaxServerStreamingRetries: true, - }); - assert(client); + it('invokes expand without error and gaxServerStreamingRetries enabled', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ExpandRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.EchoResponse(), + ); + client.innerApiCalls.expand = stubServerStreamingCall(expectedResponse); + const stream = client.expand(request); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + (response: protos.google.showcase.v1beta1.EchoResponse) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); }); - describe('chat', () => { - it('invokes chat without error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.EchoRequest() - ); - - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.EchoResponse() - ); - client.innerApiCalls.chat = stubBidiStreamingCall(expectedResponse); - const stream = client.chat(); - const promise = new Promise((resolve, reject) => { - stream.on('data', (response: protos.google.showcase.v1beta1.EchoResponse) => { - resolve(response); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - stream.write(request); - stream.end(); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - assert((client.innerApiCalls.chat as SinonStub) - .getCall(0).calledWith(null)); - assert.deepStrictEqual(((stream as unknown as PassThrough) - ._transform as SinonStub).getCall(0).args[0], request); + it('invokes expand with error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ExpandRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.expand = stubServerStreamingCall( + undefined, + expectedError, + ); + const stream = client.expand(request); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + (response: protos.google.showcase.v1beta1.EchoResponse) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); }); + }); + await assert.rejects(promise, expectedError); + }); - it('invokes chat with error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.EchoRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.chat = stubBidiStreamingCall(undefined, expectedError); - const stream = client.chat(); - const promise = new Promise((resolve, reject) => { - stream.on('data', (response: protos.google.showcase.v1beta1.EchoResponse) => { - resolve(response); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - stream.write(request); - stream.end(); - }); - await assert.rejects(promise, expectedError); - assert((client.innerApiCalls.chat as SinonStub) - .getCall(0).calledWith(null)); - assert.deepStrictEqual(((stream as unknown as PassThrough) - ._transform as SinonStub).getCall(0).args[0], request); + it('invokes expand with closed client', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ExpandRequest(), + ); + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + const stream = client.expand(request, { + retryRequestOptions: { noResponseRetries: 0 }, + }); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + (response: protos.google.showcase.v1beta1.EchoResponse) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); }); + }); + await assert.rejects(promise, expectedError); }); - - describe('collect', () => { - it('invokes collect without error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.EchoRequest() - ); - - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.EchoResponse() - ); - client.innerApiCalls.collect = stubClientStreamingCall(expectedResponse); - let stream: PassThrough; - const promise = new Promise((resolve, reject) => { - stream = client.collect( - (err?: Error|null, result?: protos.google.showcase.v1beta1.IEchoResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }) as unknown as PassThrough; - stream.write(request); - stream.end(); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - assert((client.innerApiCalls.collect as SinonStub) - .getCall(0).calledWith(null, {} /*, callback defined above */)); - assert.deepStrictEqual((stream!._transform as SinonStub).getCall(0).args[0], request); + it('should create a client with gaxServerStreamingRetries enabled', () => { + const client = new echoModule.v1beta1.EchoClient({ + gaxServerStreamingRetries: true, + }); + assert(client); + }); + }); + + describe('chat', () => { + it('invokes chat without error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.EchoRequest(), + ); + + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.EchoResponse(), + ); + client.innerApiCalls.chat = stubBidiStreamingCall(expectedResponse); + const stream = client.chat(); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + (response: protos.google.showcase.v1beta1.EchoResponse) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); }); + stream.write(request); + stream.end(); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + assert( + (client.innerApiCalls.chat as SinonStub).getCall(0).calledWith(null), + ); + assert.deepStrictEqual( + ((stream as unknown as PassThrough)._transform as SinonStub).getCall(0) + .args[0], + request, + ); + }); - it('invokes collect with error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.EchoRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.collect = stubClientStreamingCall(undefined, expectedError); - let stream: PassThrough; - const promise = new Promise((resolve, reject) => { - stream = client.collect( - (err?: Error|null, result?: protos.google.showcase.v1beta1.IEchoResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }) as unknown as PassThrough; - stream.write(request); - stream.end(); - }); - await assert.rejects(promise, expectedError); - assert((client.innerApiCalls.collect as SinonStub) - .getCall(0).calledWith(null, {} /*, callback defined above */)); + it('invokes chat with error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.EchoRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.chat = stubBidiStreamingCall( + undefined, + expectedError, + ); + const stream = client.chat(); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + (response: protos.google.showcase.v1beta1.EchoResponse) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); }); + stream.write(request); + stream.end(); + }); + await assert.rejects(promise, expectedError); + assert( + (client.innerApiCalls.chat as SinonStub).getCall(0).calledWith(null), + ); + assert.deepStrictEqual( + ((stream as unknown as PassThrough)._transform as SinonStub).getCall(0) + .args[0], + request, + ); + }); + }); + + describe('collect', () => { + it('invokes collect without error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.EchoRequest(), + ); + + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.EchoResponse(), + ); + client.innerApiCalls.collect = stubClientStreamingCall(expectedResponse); + let stream: PassThrough; + const promise = new Promise((resolve, reject) => { + stream = client.collect( + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IEchoResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ) as unknown as PassThrough; + stream.write(request); + stream.end(); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + assert( + (client.innerApiCalls.collect as SinonStub) + .getCall(0) + .calledWith(null, {} /*, callback defined above */), + ); + assert.deepStrictEqual( + (stream!._transform as SinonStub).getCall(0).args[0], + request, + ); }); - describe('pagedExpand', () => { - it('invokes pagedExpand without error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.PagedExpandRequest() - );const expectedResponse = [ - generateSampleMessage(new protos.google.showcase.v1beta1.EchoResponse()), - generateSampleMessage(new protos.google.showcase.v1beta1.EchoResponse()), - generateSampleMessage(new protos.google.showcase.v1beta1.EchoResponse()), - ]; - client.innerApiCalls.pagedExpand = stubSimpleCall(expectedResponse); - const [response] = await client.pagedExpand(request); - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes collect with error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.EchoRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.collect = stubClientStreamingCall( + undefined, + expectedError, + ); + let stream: PassThrough; + const promise = new Promise((resolve, reject) => { + stream = client.collect( + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IEchoResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ) as unknown as PassThrough; + stream.write(request); + stream.end(); + }); + await assert.rejects(promise, expectedError); + assert( + (client.innerApiCalls.collect as SinonStub) + .getCall(0) + .calledWith(null, {} /*, callback defined above */), + ); + }); + }); + + describe('pagedExpand', () => { + it('invokes pagedExpand without error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.PagedExpandRequest(), + ); + const expectedResponse = [ + generateSampleMessage( + new protos.google.showcase.v1beta1.EchoResponse(), + ), + generateSampleMessage( + new protos.google.showcase.v1beta1.EchoResponse(), + ), + generateSampleMessage( + new protos.google.showcase.v1beta1.EchoResponse(), + ), + ]; + client.innerApiCalls.pagedExpand = stubSimpleCall(expectedResponse); + const [response] = await client.pagedExpand(request); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes pagedExpand without error using callback', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.PagedExpandRequest() - );const expectedResponse = [ - generateSampleMessage(new protos.google.showcase.v1beta1.EchoResponse()), - generateSampleMessage(new protos.google.showcase.v1beta1.EchoResponse()), - generateSampleMessage(new protos.google.showcase.v1beta1.EchoResponse()), - ]; - client.innerApiCalls.pagedExpand = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.pagedExpand( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IEchoResponse[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes pagedExpand without error using callback', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.PagedExpandRequest(), + ); + const expectedResponse = [ + generateSampleMessage( + new protos.google.showcase.v1beta1.EchoResponse(), + ), + generateSampleMessage( + new protos.google.showcase.v1beta1.EchoResponse(), + ), + generateSampleMessage( + new protos.google.showcase.v1beta1.EchoResponse(), + ), + ]; + client.innerApiCalls.pagedExpand = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.pagedExpand( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IEchoResponse[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes pagedExpand with error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.PagedExpandRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.pagedExpand = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.pagedExpand(request), expectedError); - }); + it('invokes pagedExpand with error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.PagedExpandRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.pagedExpand = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.pagedExpand(request), expectedError); + }); - it('invokes pagedExpandStream without error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.PagedExpandRequest() - ); - const expectedResponse = [ - generateSampleMessage(new protos.google.showcase.v1beta1.EchoResponse()), - generateSampleMessage(new protos.google.showcase.v1beta1.EchoResponse()), - generateSampleMessage(new protos.google.showcase.v1beta1.EchoResponse()), - ]; - client.descriptors.page.pagedExpand.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.pagedExpandStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.showcase.v1beta1.EchoResponse[] = []; - stream.on('data', (response: protos.google.showcase.v1beta1.EchoResponse) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.pagedExpand.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.pagedExpand, request)); + it('invokes pagedExpandStream without error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.PagedExpandRequest(), + ); + const expectedResponse = [ + generateSampleMessage( + new protos.google.showcase.v1beta1.EchoResponse(), + ), + generateSampleMessage( + new protos.google.showcase.v1beta1.EchoResponse(), + ), + generateSampleMessage( + new protos.google.showcase.v1beta1.EchoResponse(), + ), + ]; + client.descriptors.page.pagedExpand.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.pagedExpandStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.showcase.v1beta1.EchoResponse[] = []; + stream.on( + 'data', + (response: protos.google.showcase.v1beta1.EchoResponse) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); }); - - it('invokes pagedExpandStream with error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.PagedExpandRequest() - ); - const expectedError = new Error('expected'); - client.descriptors.page.pagedExpand.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.pagedExpandStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.showcase.v1beta1.EchoResponse[] = []; - stream.on('data', (response: protos.google.showcase.v1beta1.EchoResponse) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.pagedExpand.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.pagedExpand, request)); + stream.on('error', (err: Error) => { + reject(err); }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.pagedExpand.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.pagedExpand, request), + ); + }); - it('uses async iteration with pagedExpand without error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.PagedExpandRequest() - ); - const expectedResponse = [ - generateSampleMessage(new protos.google.showcase.v1beta1.EchoResponse()), - generateSampleMessage(new protos.google.showcase.v1beta1.EchoResponse()), - generateSampleMessage(new protos.google.showcase.v1beta1.EchoResponse()), - ]; - client.descriptors.page.pagedExpand.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.showcase.v1beta1.IEchoResponse[] = []; - const iterable = client.pagedExpandAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.pagedExpand.asyncIterate as SinonStub) - .getCall(0).args[1], request); + it('invokes pagedExpandStream with error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.PagedExpandRequest(), + ); + const expectedError = new Error('expected'); + client.descriptors.page.pagedExpand.createStream = stubPageStreamingCall( + undefined, + expectedError, + ); + const stream = client.pagedExpandStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.showcase.v1beta1.EchoResponse[] = []; + stream.on( + 'data', + (response: protos.google.showcase.v1beta1.EchoResponse) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); }); - - it('uses async iteration with pagedExpand with error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.PagedExpandRequest() - ); - const expectedError = new Error('expected'); - client.descriptors.page.pagedExpand.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.pagedExpandAsync(request); - await assert.rejects(async () => { - const responses: protos.google.showcase.v1beta1.IEchoResponse[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.pagedExpand.asyncIterate as SinonStub) - .getCall(0).args[1], request); + stream.on('error', (err: Error) => { + reject(err); }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.pagedExpand.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.pagedExpand, request), + ); }); + it('uses async iteration with pagedExpand without error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.PagedExpandRequest(), + ); + const expectedResponse = [ + generateSampleMessage( + new protos.google.showcase.v1beta1.EchoResponse(), + ), + generateSampleMessage( + new protos.google.showcase.v1beta1.EchoResponse(), + ), + generateSampleMessage( + new protos.google.showcase.v1beta1.EchoResponse(), + ), + ]; + client.descriptors.page.pagedExpand.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.showcase.v1beta1.IEchoResponse[] = []; + const iterable = client.pagedExpandAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + (client.descriptors.page.pagedExpand.asyncIterate as SinonStub).getCall( + 0, + ).args[1], + request, + ); + }); - describe('Path templates', () => { - - describe('blueprint', () => { - const fakePath = "/rendered/path/blueprint"; - const expectedParameters = { - session: "sessionValue", - test: "testValue", - blueprint: "blueprintValue", - }; - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.blueprintPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.blueprintPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('blueprintPath', () => { - const result = client.blueprintPath("sessionValue", "testValue", "blueprintValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.blueprintPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchSessionFromBlueprintName', () => { - const result = client.matchSessionFromBlueprintName(fakePath); - assert.strictEqual(result, "sessionValue"); - assert((client.pathTemplates.blueprintPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchTestFromBlueprintName', () => { - const result = client.matchTestFromBlueprintName(fakePath); - assert.strictEqual(result, "testValue"); - assert((client.pathTemplates.blueprintPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBlueprintFromBlueprintName', () => { - const result = client.matchBlueprintFromBlueprintName(fakePath); - assert.strictEqual(result, "blueprintValue"); - assert((client.pathTemplates.blueprintPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('uses async iteration with pagedExpand with error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.PagedExpandRequest(), + ); + const expectedError = new Error('expected'); + client.descriptors.page.pagedExpand.asyncIterate = stubAsyncIterationCall( + undefined, + expectedError, + ); + const iterable = client.pagedExpandAsync(request); + await assert.rejects(async () => { + const responses: protos.google.showcase.v1beta1.IEchoResponse[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + (client.descriptors.page.pagedExpand.asyncIterate as SinonStub).getCall( + 0, + ).args[1], + request, + ); + }); + }); + + describe('Path templates', () => { + describe('blueprint', () => { + const fakePath = '/rendered/path/blueprint'; + const expectedParameters = { + session: 'sessionValue', + test: 'testValue', + blueprint: 'blueprintValue', + }; + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.blueprintPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.blueprintPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('blueprintPath', () => { + const result = client.blueprintPath( + 'sessionValue', + 'testValue', + 'blueprintValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.blueprintPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchSessionFromBlueprintName', () => { + const result = client.matchSessionFromBlueprintName(fakePath); + assert.strictEqual(result, 'sessionValue'); + assert( + (client.pathTemplates.blueprintPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchTestFromBlueprintName', () => { + const result = client.matchTestFromBlueprintName(fakePath); + assert.strictEqual(result, 'testValue'); + assert( + (client.pathTemplates.blueprintPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBlueprintFromBlueprintName', () => { + const result = client.matchBlueprintFromBlueprintName(fakePath); + assert.strictEqual(result, 'blueprintValue'); + assert( + (client.pathTemplates.blueprintPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('room', () => { - const fakePath = "/rendered/path/room"; - const expectedParameters = { - room: "roomValue", - }; - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.roomPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.roomPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('roomPath', () => { - const result = client.roomPath("roomValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.roomPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchRoomFromRoomName', () => { - const result = client.matchRoomFromRoomName(fakePath); - assert.strictEqual(result, "roomValue"); - assert((client.pathTemplates.roomPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('room', () => { + const fakePath = '/rendered/path/room'; + const expectedParameters = { + room: 'roomValue', + }; + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.roomPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.roomPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('roomPath', () => { + const result = client.roomPath('roomValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.roomPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchRoomFromRoomName', () => { + const result = client.matchRoomFromRoomName(fakePath); + assert.strictEqual(result, 'roomValue'); + assert( + (client.pathTemplates.roomPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('roomBlurb', () => { - const fakePath = "/rendered/path/roomBlurb"; - const expectedParameters = { - room: "roomValue", - blurb: "blurbValue", - }; - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.roomBlurbPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.roomBlurbPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('roomBlurbPath', () => { - const result = client.roomBlurbPath("roomValue", "blurbValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.roomBlurbPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchRoomFromRoomBlurbName', () => { - const result = client.matchRoomFromRoomBlurbName(fakePath); - assert.strictEqual(result, "roomValue"); - assert((client.pathTemplates.roomBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBlurbFromRoomBlurbName', () => { - const result = client.matchBlurbFromRoomBlurbName(fakePath); - assert.strictEqual(result, "blurbValue"); - assert((client.pathTemplates.roomBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('roomBlurb', () => { + const fakePath = '/rendered/path/roomBlurb'; + const expectedParameters = { + room: 'roomValue', + blurb: 'blurbValue', + }; + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.roomBlurbPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.roomBlurbPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('roomBlurbPath', () => { + const result = client.roomBlurbPath('roomValue', 'blurbValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.roomBlurbPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchRoomFromRoomBlurbName', () => { + const result = client.matchRoomFromRoomBlurbName(fakePath); + assert.strictEqual(result, 'roomValue'); + assert( + (client.pathTemplates.roomBlurbPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBlurbFromRoomBlurbName', () => { + const result = client.matchBlurbFromRoomBlurbName(fakePath); + assert.strictEqual(result, 'blurbValue'); + assert( + (client.pathTemplates.roomBlurbPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('roomBlurbsLegacyRoomBlurb', () => { - const fakePath = "/rendered/path/roomBlurbsLegacyRoomBlurb"; - const expectedParameters = { - room: "roomValue", - legacy_room: "legacyRoomValue", - blurb: "blurbValue", - }; - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('roomBlurbsLegacyRoomBlurbPath', () => { - const result = client.roomBlurbsLegacyRoomBlurbPath("roomValue", "legacyRoomValue", "blurbValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchRoomFromRoomBlurbsLegacyRoomBlurbName', () => { - const result = client.matchRoomFromRoomBlurbsLegacyRoomBlurbName(fakePath); - assert.strictEqual(result, "roomValue"); - assert((client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName', () => { - const result = client.matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName(fakePath); - assert.strictEqual(result, "legacyRoomValue"); - assert((client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBlurbFromRoomBlurbsLegacyRoomBlurbName', () => { - const result = client.matchBlurbFromRoomBlurbsLegacyRoomBlurbName(fakePath); - assert.strictEqual(result, "blurbValue"); - assert((client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('roomBlurbsLegacyRoomBlurb', () => { + const fakePath = '/rendered/path/roomBlurbsLegacyRoomBlurb'; + const expectedParameters = { + room: 'roomValue', + legacy_room: 'legacyRoomValue', + blurb: 'blurbValue', + }; + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('roomBlurbsLegacyRoomBlurbPath', () => { + const result = client.roomBlurbsLegacyRoomBlurbPath( + 'roomValue', + 'legacyRoomValue', + 'blurbValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchRoomFromRoomBlurbsLegacyRoomBlurbName', () => { + const result = + client.matchRoomFromRoomBlurbsLegacyRoomBlurbName(fakePath); + assert.strictEqual(result, 'roomValue'); + assert( + ( + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName', () => { + const result = + client.matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName(fakePath); + assert.strictEqual(result, 'legacyRoomValue'); + assert( + ( + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBlurbFromRoomBlurbsLegacyRoomBlurbName', () => { + const result = + client.matchBlurbFromRoomBlurbsLegacyRoomBlurbName(fakePath); + assert.strictEqual(result, 'blurbValue'); + assert( + ( + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('sequence', () => { - const fakePath = "/rendered/path/sequence"; - const expectedParameters = { - sequence: "sequenceValue", - }; - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.sequencePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.sequencePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('sequencePath', () => { - const result = client.sequencePath("sequenceValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.sequencePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchSequenceFromSequenceName', () => { - const result = client.matchSequenceFromSequenceName(fakePath); - assert.strictEqual(result, "sequenceValue"); - assert((client.pathTemplates.sequencePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('sequence', () => { + const fakePath = '/rendered/path/sequence'; + const expectedParameters = { + sequence: 'sequenceValue', + }; + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.sequencePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.sequencePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('sequencePath', () => { + const result = client.sequencePath('sequenceValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.sequencePathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchSequenceFromSequenceName', () => { + const result = client.matchSequenceFromSequenceName(fakePath); + assert.strictEqual(result, 'sequenceValue'); + assert( + (client.pathTemplates.sequencePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('sequenceReport', () => { - const fakePath = "/rendered/path/sequenceReport"; - const expectedParameters = { - sequence: "sequenceValue", - }; - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.sequenceReportPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.sequenceReportPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('sequenceReportPath', () => { - const result = client.sequenceReportPath("sequenceValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.sequenceReportPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchSequenceFromSequenceReportName', () => { - const result = client.matchSequenceFromSequenceReportName(fakePath); - assert.strictEqual(result, "sequenceValue"); - assert((client.pathTemplates.sequenceReportPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('sequenceReport', () => { + const fakePath = '/rendered/path/sequenceReport'; + const expectedParameters = { + sequence: 'sequenceValue', + }; + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.sequenceReportPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.sequenceReportPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('sequenceReportPath', () => { + const result = client.sequenceReportPath('sequenceValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.sequenceReportPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchSequenceFromSequenceReportName', () => { + const result = client.matchSequenceFromSequenceReportName(fakePath); + assert.strictEqual(result, 'sequenceValue'); + assert( + (client.pathTemplates.sequenceReportPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('session', () => { - const fakePath = "/rendered/path/session"; - const expectedParameters = { - session: "sessionValue", - }; - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.sessionPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.sessionPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('sessionPath', () => { - const result = client.sessionPath("sessionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.sessionPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchSessionFromSessionName', () => { - const result = client.matchSessionFromSessionName(fakePath); - assert.strictEqual(result, "sessionValue"); - assert((client.pathTemplates.sessionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('session', () => { + const fakePath = '/rendered/path/session'; + const expectedParameters = { + session: 'sessionValue', + }; + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.sessionPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.sessionPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('sessionPath', () => { + const result = client.sessionPath('sessionValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.sessionPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchSessionFromSessionName', () => { + const result = client.matchSessionFromSessionName(fakePath); + assert.strictEqual(result, 'sessionValue'); + assert( + (client.pathTemplates.sessionPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('test', () => { - const fakePath = "/rendered/path/test"; - const expectedParameters = { - session: "sessionValue", - test: "testValue", - }; - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.testPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.testPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('testPath', () => { - const result = client.testPath("sessionValue", "testValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.testPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchSessionFromTestName', () => { - const result = client.matchSessionFromTestName(fakePath); - assert.strictEqual(result, "sessionValue"); - assert((client.pathTemplates.testPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchTestFromTestName', () => { - const result = client.matchTestFromTestName(fakePath); - assert.strictEqual(result, "testValue"); - assert((client.pathTemplates.testPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('test', () => { + const fakePath = '/rendered/path/test'; + const expectedParameters = { + session: 'sessionValue', + test: 'testValue', + }; + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.testPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.testPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('testPath', () => { + const result = client.testPath('sessionValue', 'testValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.testPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchSessionFromTestName', () => { + const result = client.matchSessionFromTestName(fakePath); + assert.strictEqual(result, 'sessionValue'); + assert( + (client.pathTemplates.testPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchTestFromTestName', () => { + const result = client.matchTestFromTestName(fakePath); + assert.strictEqual(result, 'testValue'); + assert( + (client.pathTemplates.testPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('user', () => { - const fakePath = "/rendered/path/user"; - const expectedParameters = { - user: "userValue", - }; - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.userPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.userPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('userPath', () => { - const result = client.userPath("userValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.userPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchUserFromUserName', () => { - const result = client.matchUserFromUserName(fakePath); - assert.strictEqual(result, "userValue"); - assert((client.pathTemplates.userPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('user', () => { + const fakePath = '/rendered/path/user'; + const expectedParameters = { + user: 'userValue', + }; + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.userPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.userPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('userPath', () => { + const result = client.userPath('userValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.userPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchUserFromUserName', () => { + const result = client.matchUserFromUserName(fakePath); + assert.strictEqual(result, 'userValue'); + assert( + (client.pathTemplates.userPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('userProfileBlurb', () => { - const fakePath = "/rendered/path/userProfileBlurb"; - const expectedParameters = { - user: "userValue", - blurb: "blurbValue", - }; - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.userProfileBlurbPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.userProfileBlurbPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('userProfileBlurbPath', () => { - const result = client.userProfileBlurbPath("userValue", "blurbValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.userProfileBlurbPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchUserFromUserProfileBlurbName', () => { - const result = client.matchUserFromUserProfileBlurbName(fakePath); - assert.strictEqual(result, "userValue"); - assert((client.pathTemplates.userProfileBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBlurbFromUserProfileBlurbName', () => { - const result = client.matchBlurbFromUserProfileBlurbName(fakePath); - assert.strictEqual(result, "blurbValue"); - assert((client.pathTemplates.userProfileBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('userProfileBlurb', () => { + const fakePath = '/rendered/path/userProfileBlurb'; + const expectedParameters = { + user: 'userValue', + blurb: 'blurbValue', + }; + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.userProfileBlurbPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.userProfileBlurbPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('userProfileBlurbPath', () => { + const result = client.userProfileBlurbPath('userValue', 'blurbValue'); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.userProfileBlurbPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchUserFromUserProfileBlurbName', () => { + const result = client.matchUserFromUserProfileBlurbName(fakePath); + assert.strictEqual(result, 'userValue'); + assert( + (client.pathTemplates.userProfileBlurbPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBlurbFromUserProfileBlurbName', () => { + const result = client.matchBlurbFromUserProfileBlurbName(fakePath); + assert.strictEqual(result, 'blurbValue'); + assert( + (client.pathTemplates.userProfileBlurbPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('userProfileBlurbsLegacyUserBlurb', () => { - const fakePath = "/rendered/path/userProfileBlurbsLegacyUserBlurb"; - const expectedParameters = { - user: "userValue", - legacy_user: "legacyUserValue", - blurb: "blurbValue", - }; - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('userProfileBlurbsLegacyUserBlurbPath', () => { - const result = client.userProfileBlurbsLegacyUserBlurbPath("userValue", "legacyUserValue", "blurbValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchUserFromUserProfileBlurbsLegacyUserBlurbName', () => { - const result = client.matchUserFromUserProfileBlurbsLegacyUserBlurbName(fakePath); - assert.strictEqual(result, "userValue"); - assert((client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName', () => { - const result = client.matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName(fakePath); - assert.strictEqual(result, "legacyUserValue"); - assert((client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBlurbFromUserProfileBlurbsLegacyUserBlurbName', () => { - const result = client.matchBlurbFromUserProfileBlurbsLegacyUserBlurbName(fakePath); - assert.strictEqual(result, "blurbValue"); - assert((client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('userProfileBlurbsLegacyUserBlurb', () => { + const fakePath = '/rendered/path/userProfileBlurbsLegacyUserBlurb'; + const expectedParameters = { + user: 'userValue', + legacy_user: 'legacyUserValue', + blurb: 'blurbValue', + }; + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('userProfileBlurbsLegacyUserBlurbPath', () => { + const result = client.userProfileBlurbsLegacyUserBlurbPath( + 'userValue', + 'legacyUserValue', + 'blurbValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchUserFromUserProfileBlurbsLegacyUserBlurbName', () => { + const result = + client.matchUserFromUserProfileBlurbsLegacyUserBlurbName(fakePath); + assert.strictEqual(result, 'userValue'); + assert( + ( + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName', () => { + const result = + client.matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName( + fakePath, + ); + assert.strictEqual(result, 'legacyUserValue'); + assert( + ( + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBlurbFromUserProfileBlurbsLegacyUserBlurbName', () => { + const result = + client.matchBlurbFromUserProfileBlurbsLegacyUserBlurbName(fakePath); + assert.strictEqual(result, 'blurbValue'); + assert( + ( + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/core/generator/gapic-generator-typescript/baselines/showcase-esm/esm/test/gapic_identity_v1beta1.ts.baseline b/core/generator/gapic-generator-typescript/baselines/showcase-esm/esm/test/gapic_identity_v1beta1.ts.baseline index 2da43f67b837..a23a82809616 100644 --- a/core/generator/gapic-generator-typescript/baselines/showcase-esm/esm/test/gapic_identity_v1beta1.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/showcase-esm/esm/test/gapic_identity_v1beta1.ts.baseline @@ -20,16 +20,16 @@ import * as protos from '../../protos/protos.js'; import assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as identityModule from '../src/index.js'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; -import {protobuf} from 'google-gax'; +import { protobuf } from 'google-gax'; import fs from 'fs'; import path from 'path'; -import {fileURLToPath} from 'url'; +import { fileURLToPath } from 'url'; // @ts-ignore const dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -37,1176 +37,1513 @@ const dirname = path.dirname(fileURLToPath(import.meta.url)); // to fill in default values for request objects const root = protobuf.Root.fromJSON( JSON.parse( - fs.readFileSync(path.join(dirname, '..', '..', 'protos/protos.json'), 'utf8') - )) + fs.readFileSync( + path.join(dirname, '..', '..', 'protos/protos.json'), + 'utf8', + ), + ), +); // eslint-disable-next-line @typescript-eslint/no-unused-vars function getTypeDefaultValue(typeName: string, fields: string[]) { - let type = root.lookupType(typeName) as protobuf.Type; - for (const field of fields.slice(0, -1)) { - type = type?.fields[field]?.resolvedType as protobuf.Type; - } - return type?.fields[fields[fields.length - 1]]?.defaultValue ?? null; + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type?.fields[field]?.resolvedType as protobuf.Type; + } + return type?.fields[fields[fields.length - 1]]?.defaultValue ?? null; } function generateSampleMessage(instance: T) { - const filledObject = (instance.constructor as typeof protobuf.Message) - .toObject(instance as protobuf.Message, {defaults: true}); - return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, { defaults: true }); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; } function stubSimpleCall(response?: ResponseType, error?: Error) { - return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); } -function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { - return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +function stubSimpleCallWithCallback( + response?: ResponseType, + error?: Error, +) { + return error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); } -function stubPageStreamingCall(responses?: ResponseType[], error?: Error) { - const pagingStub = sinon.stub(); - if (responses) { - for (let i = 0; i < responses.length; ++i) { - pagingStub.onCall(i).callsArgWith(2, null, responses[i]); - } +function stubPageStreamingCall( + responses?: ResponseType[], + error?: Error, +) { + const pagingStub = sinon.stub(); + if (responses) { + for (let i = 0; i < responses.length; ++i) { + pagingStub.onCall(i).callsArgWith(2, null, responses[i]); } - const transformStub = error ? sinon.stub().callsArgWith(2, error) : pagingStub; - const mockStream = new PassThrough({ - objectMode: true, - transform: transformStub, - }); - // trigger as many responses as needed - if (responses) { - for (let i = 0; i < responses.length; ++i) { - setImmediate(() => { mockStream.write({}); }); - } - setImmediate(() => { mockStream.end(); }); - } else { - setImmediate(() => { mockStream.write({}); }); - setImmediate(() => { mockStream.end(); }); + } + const transformStub = error + ? sinon.stub().callsArgWith(2, error) + : pagingStub; + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + // trigger as many responses as needed + if (responses) { + for (let i = 0; i < responses.length; ++i) { + setImmediate(() => { + mockStream.write({}); + }); } - return sinon.stub().returns(mockStream); + setImmediate(() => { + mockStream.end(); + }); + } else { + setImmediate(() => { + mockStream.write({}); + }); + setImmediate(() => { + mockStream.end(); + }); + } + return sinon.stub().returns(mockStream); } -function stubAsyncIterationCall(responses?: ResponseType[], error?: Error) { - let counter = 0; - const asyncIterable = { - [Symbol.asyncIterator]() { - return { - async next() { - if (error) { - return Promise.reject(error); - } - if (counter >= responses!.length) { - return Promise.resolve({done: true, value: undefined}); - } - return Promise.resolve({done: false, value: responses![counter++]}); - } - }; - } - }; - return sinon.stub().returns(asyncIterable); +function stubAsyncIterationCall( + responses?: ResponseType[], + error?: Error, +) { + let counter = 0; + const asyncIterable = { + [Symbol.asyncIterator]() { + return { + async next() { + if (error) { + return Promise.reject(error); + } + if (counter >= responses!.length) { + return Promise.resolve({ done: true, value: undefined }); + } + return Promise.resolve({ done: false, value: responses![counter++] }); + }, + }; + }, + }; + return sinon.stub().returns(asyncIterable); } describe('v1beta1.IdentityClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new identityModule.v1beta1.IdentityClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'localhost'); - }); - - it('has universeDomain', () => { - const client = new identityModule.v1beta1.IdentityClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); - - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - it('throws DeprecationWarning if static servicePath is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const servicePath = identityModule.v1beta1.IdentityClient.servicePath; - assert.strictEqual(servicePath, 'localhost'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = identityModule.v1beta1.IdentityClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'localhost'); - assert(stub.called); - stub.restore(); - }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { new identityModule.v1beta1.IdentityClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new identityModule.v1beta1.IdentityClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'localhost'); + }); - it('has port', () => { - const port = identityModule.v1beta1.IdentityClient.port; - assert(port); - assert(typeof port === 'number'); - }); + it('has universeDomain', () => { + const client = new identityModule.v1beta1.IdentityClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - it('should create a client with no option', () => { - const client = new identityModule.v1beta1.IdentityClient(); - assert(client); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = identityModule.v1beta1.IdentityClient.servicePath; + assert.strictEqual(servicePath, 'localhost'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = identityModule.v1beta1.IdentityClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'localhost'); + assert(stub.called); + stub.restore(); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new identityModule.v1beta1.IdentityClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); + }); - it('should create a client with gRPC fallback', () => { - const client = new identityModule.v1beta1.IdentityClient({ - fallback: true, - }); - assert(client); - }); + it('has port', () => { + const port = identityModule.v1beta1.IdentityClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('has initialize method and supports deferred initialization', async () => { - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.identityStub, undefined); - await client.initialize(); - assert(client.identityStub); - }); + it('should create a client with no option', () => { + const client = new identityModule.v1beta1.IdentityClient(); + assert(client); + }); - it('has close method for the initialized client', done => { - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.identityStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('should create a client with gRPC fallback', () => { + const client = new identityModule.v1beta1.IdentityClient({ + fallback: true, + }); + assert(client); + }); - it('has close method for the non-initialized client', done => { - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.identityStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('has initialize method and supports deferred initialization', async () => { + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.identityStub, undefined); + await client.initialize(); + assert(client.identityStub); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + it('has close method for the initialized client', (done) => { + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.identityStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId((err?: Error|null, projectId?: string|null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } - }); - }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); + it('has close method for the non-initialized client', (done) => { + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.identityStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); }); - describe('createUser', () => { - it('invokes createUser without error', async () => { - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.CreateUserRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.User() - ); - client.innerApiCalls.createUser = stubSimpleCall(expectedResponse); - const [response] = await client.createUser(request); - assert.deepStrictEqual(response, expectedResponse); - }); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + }); - it('invokes createUser without error using callback', async () => { - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.CreateUserRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.User() - ); - client.innerApiCalls.createUser = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createUser( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IUser|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + }); + + describe('createUser', () => { + it('invokes createUser without error', async () => { + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.CreateUserRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.User(), + ); + client.innerApiCalls.createUser = stubSimpleCall(expectedResponse); + const [response] = await client.createUser(request); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes createUser with error', async () => { - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.CreateUserRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.createUser = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createUser(request), expectedError); - }); + it('invokes createUser without error using callback', async () => { + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.CreateUserRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.User(), + ); + client.innerApiCalls.createUser = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createUser( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IUser | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes createUser with closed client', async () => { - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.CreateUserRequest() - ); - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createUser(request), expectedError); - }); + it('invokes createUser with error', async () => { + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.CreateUserRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.createUser = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.createUser(request), expectedError); }); - describe('getUser', () => { - it('invokes getUser without error', async () => { - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.GetUserRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.GetUserRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.User() - ); - client.innerApiCalls.getUser = stubSimpleCall(expectedResponse); - const [response] = await client.getUser(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getUser as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getUser as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createUser with closed client', async () => { + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.CreateUserRequest(), + ); + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.createUser(request), expectedError); + }); + }); + + describe('getUser', () => { + it('invokes getUser without error', async () => { + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.GetUserRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.GetUserRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.User(), + ); + client.innerApiCalls.getUser = stubSimpleCall(expectedResponse); + const [response] = await client.getUser(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.getUser as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getUser as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getUser without error using callback', async () => { - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.GetUserRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.GetUserRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.User() - ); - client.innerApiCalls.getUser = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getUser( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IUser|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getUser as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getUser as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getUser without error using callback', async () => { + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.GetUserRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.GetUserRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.User(), + ); + client.innerApiCalls.getUser = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getUser( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IUser | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.getUser as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getUser as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getUser with error', async () => { - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.GetUserRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.GetUserRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getUser = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getUser(request), expectedError); - const actualRequest = (client.innerApiCalls.getUser as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getUser as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getUser with error', async () => { + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.GetUserRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.GetUserRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getUser = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.getUser(request), expectedError); + const actualRequest = (client.innerApiCalls.getUser as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getUser as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getUser with closed client', async () => { - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.GetUserRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.GetUserRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getUser(request), expectedError); - }); + it('invokes getUser with closed client', async () => { + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.GetUserRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.GetUserRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getUser(request), expectedError); + }); + }); + + describe('updateUser', () => { + it('invokes updateUser without error', async () => { + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.UpdateUserRequest(), + ); + request.user ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.UpdateUserRequest', + ['user', 'name'], + ); + request.user.name = defaultValue1; + const expectedHeaderRequestParams = `user.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.User(), + ); + client.innerApiCalls.updateUser = stubSimpleCall(expectedResponse); + const [response] = await client.updateUser(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateUser as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateUser as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('updateUser', () => { - it('invokes updateUser without error', async () => { - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.UpdateUserRequest() - ); - request.user ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.UpdateUserRequest', ['user', 'name']); - request.user.name = defaultValue1; - const expectedHeaderRequestParams = `user.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.User() - ); - client.innerApiCalls.updateUser = stubSimpleCall(expectedResponse); - const [response] = await client.updateUser(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateUser as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateUser as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateUser without error using callback', async () => { + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.UpdateUserRequest(), + ); + request.user ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.UpdateUserRequest', + ['user', 'name'], + ); + request.user.name = defaultValue1; + const expectedHeaderRequestParams = `user.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.User(), + ); + client.innerApiCalls.updateUser = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateUser( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IUser | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateUser as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateUser as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateUser without error using callback', async () => { - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.UpdateUserRequest() - ); - request.user ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.UpdateUserRequest', ['user', 'name']); - request.user.name = defaultValue1; - const expectedHeaderRequestParams = `user.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.User() - ); - client.innerApiCalls.updateUser = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateUser( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IUser|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateUser as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateUser as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateUser with error', async () => { + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.UpdateUserRequest(), + ); + request.user ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.UpdateUserRequest', + ['user', 'name'], + ); + request.user.name = defaultValue1; + const expectedHeaderRequestParams = `user.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateUser = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.updateUser(request), expectedError); + const actualRequest = ( + client.innerApiCalls.updateUser as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateUser as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateUser with error', async () => { - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.UpdateUserRequest() - ); - request.user ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.UpdateUserRequest', ['user', 'name']); - request.user.name = defaultValue1; - const expectedHeaderRequestParams = `user.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateUser = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateUser(request), expectedError); - const actualRequest = (client.innerApiCalls.updateUser as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateUser as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateUser with closed client', async () => { + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.UpdateUserRequest(), + ); + request.user ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.UpdateUserRequest', + ['user', 'name'], + ); + request.user.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.updateUser(request), expectedError); + }); + }); + + describe('deleteUser', () => { + it('invokes deleteUser without error', async () => { + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.DeleteUserRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.DeleteUserRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteUser = stubSimpleCall(expectedResponse); + const [response] = await client.deleteUser(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteUser as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteUser as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateUser with closed client', async () => { - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.UpdateUserRequest() - ); - request.user ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.UpdateUserRequest', ['user', 'name']); - request.user.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateUser(request), expectedError); - }); + it('invokes deleteUser without error using callback', async () => { + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.DeleteUserRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.DeleteUserRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteUser = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteUser( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteUser as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteUser as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('deleteUser', () => { - it('invokes deleteUser without error', async () => { - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.DeleteUserRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.DeleteUserRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteUser = stubSimpleCall(expectedResponse); - const [response] = await client.deleteUser(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteUser as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteUser as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteUser with error', async () => { + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.DeleteUserRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.DeleteUserRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteUser = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.deleteUser(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteUser as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteUser as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteUser without error using callback', async () => { - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.DeleteUserRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.DeleteUserRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteUser = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteUser( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteUser as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteUser as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteUser with closed client', async () => { + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.DeleteUserRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.DeleteUserRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.deleteUser(request), expectedError); + }); + }); + + describe('listUsers', () => { + it('invokes listUsers without error', async () => { + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListUsersRequest(), + ); + const expectedResponse = [ + generateSampleMessage(new protos.google.showcase.v1beta1.User()), + generateSampleMessage(new protos.google.showcase.v1beta1.User()), + generateSampleMessage(new protos.google.showcase.v1beta1.User()), + ]; + client.innerApiCalls.listUsers = stubSimpleCall(expectedResponse); + const [response] = await client.listUsers(request); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes deleteUser with error', async () => { - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.DeleteUserRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.DeleteUserRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteUser = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteUser(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteUser as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteUser as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listUsers without error using callback', async () => { + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListUsersRequest(), + ); + const expectedResponse = [ + generateSampleMessage(new protos.google.showcase.v1beta1.User()), + generateSampleMessage(new protos.google.showcase.v1beta1.User()), + generateSampleMessage(new protos.google.showcase.v1beta1.User()), + ]; + client.innerApiCalls.listUsers = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listUsers( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IUser[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes deleteUser with closed client', async () => { - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.DeleteUserRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.DeleteUserRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteUser(request), expectedError); - }); + it('invokes listUsers with error', async () => { + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListUsersRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.listUsers = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.listUsers(request), expectedError); }); - describe('listUsers', () => { - it('invokes listUsers without error', async () => { - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListUsersRequest() - );const expectedResponse = [ - generateSampleMessage(new protos.google.showcase.v1beta1.User()), - generateSampleMessage(new protos.google.showcase.v1beta1.User()), - generateSampleMessage(new protos.google.showcase.v1beta1.User()), - ]; - client.innerApiCalls.listUsers = stubSimpleCall(expectedResponse); - const [response] = await client.listUsers(request); - assert.deepStrictEqual(response, expectedResponse); + it('invokes listUsersStream without error', async () => { + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListUsersRequest(), + ); + const expectedResponse = [ + generateSampleMessage(new protos.google.showcase.v1beta1.User()), + generateSampleMessage(new protos.google.showcase.v1beta1.User()), + generateSampleMessage(new protos.google.showcase.v1beta1.User()), + ]; + client.descriptors.page.listUsers.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listUsersStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.showcase.v1beta1.User[] = []; + stream.on('data', (response: protos.google.showcase.v1beta1.User) => { + responses.push(response); }); - - it('invokes listUsers without error using callback', async () => { - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListUsersRequest() - );const expectedResponse = [ - generateSampleMessage(new protos.google.showcase.v1beta1.User()), - generateSampleMessage(new protos.google.showcase.v1beta1.User()), - generateSampleMessage(new protos.google.showcase.v1beta1.User()), - ]; - client.innerApiCalls.listUsers = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listUsers( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IUser[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); + stream.on('end', () => { + resolve(responses); }); - - it('invokes listUsers with error', async () => { - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListUsersRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.listUsers = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listUsers(request), expectedError); + stream.on('error', (err: Error) => { + reject(err); }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listUsers.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listUsers, request), + ); + }); - it('invokes listUsersStream without error', async () => { - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListUsersRequest() - ); - const expectedResponse = [ - generateSampleMessage(new protos.google.showcase.v1beta1.User()), - generateSampleMessage(new protos.google.showcase.v1beta1.User()), - generateSampleMessage(new protos.google.showcase.v1beta1.User()), - ]; - client.descriptors.page.listUsers.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listUsersStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.showcase.v1beta1.User[] = []; - stream.on('data', (response: protos.google.showcase.v1beta1.User) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.listUsers.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listUsers, request)); + it('invokes listUsersStream with error', async () => { + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListUsersRequest(), + ); + const expectedError = new Error('expected'); + client.descriptors.page.listUsers.createStream = stubPageStreamingCall( + undefined, + expectedError, + ); + const stream = client.listUsersStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.showcase.v1beta1.User[] = []; + stream.on('data', (response: protos.google.showcase.v1beta1.User) => { + responses.push(response); }); - - it('invokes listUsersStream with error', async () => { - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListUsersRequest() - ); - const expectedError = new Error('expected'); - client.descriptors.page.listUsers.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listUsersStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.showcase.v1beta1.User[] = []; - stream.on('data', (response: protos.google.showcase.v1beta1.User) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listUsers.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listUsers, request)); + stream.on('end', () => { + resolve(responses); }); - - it('uses async iteration with listUsers without error', async () => { - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListUsersRequest() - ); - const expectedResponse = [ - generateSampleMessage(new protos.google.showcase.v1beta1.User()), - generateSampleMessage(new protos.google.showcase.v1beta1.User()), - generateSampleMessage(new protos.google.showcase.v1beta1.User()), - ]; - client.descriptors.page.listUsers.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.showcase.v1beta1.IUser[] = []; - const iterable = client.listUsersAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listUsers.asyncIterate as SinonStub) - .getCall(0).args[1], request); + stream.on('error', (err: Error) => { + reject(err); }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listUsers.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listUsers, request), + ); + }); - it('uses async iteration with listUsers with error', async () => { - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListUsersRequest() - ); - const expectedError = new Error('expected'); - client.descriptors.page.listUsers.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listUsersAsync(request); - await assert.rejects(async () => { - const responses: protos.google.showcase.v1beta1.IUser[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listUsers.asyncIterate as SinonStub) - .getCall(0).args[1], request); - }); + it('uses async iteration with listUsers without error', async () => { + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListUsersRequest(), + ); + const expectedResponse = [ + generateSampleMessage(new protos.google.showcase.v1beta1.User()), + generateSampleMessage(new protos.google.showcase.v1beta1.User()), + generateSampleMessage(new protos.google.showcase.v1beta1.User()), + ]; + client.descriptors.page.listUsers.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.showcase.v1beta1.IUser[] = []; + const iterable = client.listUsersAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + (client.descriptors.page.listUsers.asyncIterate as SinonStub).getCall(0) + .args[1], + request, + ); }); - describe('Path templates', () => { - - describe('blueprint', () => { - const fakePath = "/rendered/path/blueprint"; - const expectedParameters = { - session: "sessionValue", - test: "testValue", - blueprint: "blueprintValue", - }; - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.blueprintPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.blueprintPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('blueprintPath', () => { - const result = client.blueprintPath("sessionValue", "testValue", "blueprintValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.blueprintPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchSessionFromBlueprintName', () => { - const result = client.matchSessionFromBlueprintName(fakePath); - assert.strictEqual(result, "sessionValue"); - assert((client.pathTemplates.blueprintPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchTestFromBlueprintName', () => { - const result = client.matchTestFromBlueprintName(fakePath); - assert.strictEqual(result, "testValue"); - assert((client.pathTemplates.blueprintPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBlueprintFromBlueprintName', () => { - const result = client.matchBlueprintFromBlueprintName(fakePath); - assert.strictEqual(result, "blueprintValue"); - assert((client.pathTemplates.blueprintPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('uses async iteration with listUsers with error', async () => { + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListUsersRequest(), + ); + const expectedError = new Error('expected'); + client.descriptors.page.listUsers.asyncIterate = stubAsyncIterationCall( + undefined, + expectedError, + ); + const iterable = client.listUsersAsync(request); + await assert.rejects(async () => { + const responses: protos.google.showcase.v1beta1.IUser[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + (client.descriptors.page.listUsers.asyncIterate as SinonStub).getCall(0) + .args[1], + request, + ); + }); + }); + + describe('Path templates', () => { + describe('blueprint', () => { + const fakePath = '/rendered/path/blueprint'; + const expectedParameters = { + session: 'sessionValue', + test: 'testValue', + blueprint: 'blueprintValue', + }; + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.blueprintPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.blueprintPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('blueprintPath', () => { + const result = client.blueprintPath( + 'sessionValue', + 'testValue', + 'blueprintValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.blueprintPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchSessionFromBlueprintName', () => { + const result = client.matchSessionFromBlueprintName(fakePath); + assert.strictEqual(result, 'sessionValue'); + assert( + (client.pathTemplates.blueprintPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchTestFromBlueprintName', () => { + const result = client.matchTestFromBlueprintName(fakePath); + assert.strictEqual(result, 'testValue'); + assert( + (client.pathTemplates.blueprintPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBlueprintFromBlueprintName', () => { + const result = client.matchBlueprintFromBlueprintName(fakePath); + assert.strictEqual(result, 'blueprintValue'); + assert( + (client.pathTemplates.blueprintPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('room', () => { - const fakePath = "/rendered/path/room"; - const expectedParameters = { - room: "roomValue", - }; - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.roomPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.roomPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('roomPath', () => { - const result = client.roomPath("roomValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.roomPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchRoomFromRoomName', () => { - const result = client.matchRoomFromRoomName(fakePath); - assert.strictEqual(result, "roomValue"); - assert((client.pathTemplates.roomPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('room', () => { + const fakePath = '/rendered/path/room'; + const expectedParameters = { + room: 'roomValue', + }; + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.roomPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.roomPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('roomPath', () => { + const result = client.roomPath('roomValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.roomPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchRoomFromRoomName', () => { + const result = client.matchRoomFromRoomName(fakePath); + assert.strictEqual(result, 'roomValue'); + assert( + (client.pathTemplates.roomPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('roomBlurb', () => { - const fakePath = "/rendered/path/roomBlurb"; - const expectedParameters = { - room: "roomValue", - blurb: "blurbValue", - }; - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.roomBlurbPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.roomBlurbPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('roomBlurbPath', () => { - const result = client.roomBlurbPath("roomValue", "blurbValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.roomBlurbPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchRoomFromRoomBlurbName', () => { - const result = client.matchRoomFromRoomBlurbName(fakePath); - assert.strictEqual(result, "roomValue"); - assert((client.pathTemplates.roomBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBlurbFromRoomBlurbName', () => { - const result = client.matchBlurbFromRoomBlurbName(fakePath); - assert.strictEqual(result, "blurbValue"); - assert((client.pathTemplates.roomBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('roomBlurb', () => { + const fakePath = '/rendered/path/roomBlurb'; + const expectedParameters = { + room: 'roomValue', + blurb: 'blurbValue', + }; + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.roomBlurbPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.roomBlurbPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('roomBlurbPath', () => { + const result = client.roomBlurbPath('roomValue', 'blurbValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.roomBlurbPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchRoomFromRoomBlurbName', () => { + const result = client.matchRoomFromRoomBlurbName(fakePath); + assert.strictEqual(result, 'roomValue'); + assert( + (client.pathTemplates.roomBlurbPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBlurbFromRoomBlurbName', () => { + const result = client.matchBlurbFromRoomBlurbName(fakePath); + assert.strictEqual(result, 'blurbValue'); + assert( + (client.pathTemplates.roomBlurbPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('roomBlurbsLegacyRoomBlurb', () => { - const fakePath = "/rendered/path/roomBlurbsLegacyRoomBlurb"; - const expectedParameters = { - room: "roomValue", - legacy_room: "legacyRoomValue", - blurb: "blurbValue", - }; - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('roomBlurbsLegacyRoomBlurbPath', () => { - const result = client.roomBlurbsLegacyRoomBlurbPath("roomValue", "legacyRoomValue", "blurbValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchRoomFromRoomBlurbsLegacyRoomBlurbName', () => { - const result = client.matchRoomFromRoomBlurbsLegacyRoomBlurbName(fakePath); - assert.strictEqual(result, "roomValue"); - assert((client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName', () => { - const result = client.matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName(fakePath); - assert.strictEqual(result, "legacyRoomValue"); - assert((client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBlurbFromRoomBlurbsLegacyRoomBlurbName', () => { - const result = client.matchBlurbFromRoomBlurbsLegacyRoomBlurbName(fakePath); - assert.strictEqual(result, "blurbValue"); - assert((client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('roomBlurbsLegacyRoomBlurb', () => { + const fakePath = '/rendered/path/roomBlurbsLegacyRoomBlurb'; + const expectedParameters = { + room: 'roomValue', + legacy_room: 'legacyRoomValue', + blurb: 'blurbValue', + }; + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('roomBlurbsLegacyRoomBlurbPath', () => { + const result = client.roomBlurbsLegacyRoomBlurbPath( + 'roomValue', + 'legacyRoomValue', + 'blurbValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchRoomFromRoomBlurbsLegacyRoomBlurbName', () => { + const result = + client.matchRoomFromRoomBlurbsLegacyRoomBlurbName(fakePath); + assert.strictEqual(result, 'roomValue'); + assert( + ( + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName', () => { + const result = + client.matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName(fakePath); + assert.strictEqual(result, 'legacyRoomValue'); + assert( + ( + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBlurbFromRoomBlurbsLegacyRoomBlurbName', () => { + const result = + client.matchBlurbFromRoomBlurbsLegacyRoomBlurbName(fakePath); + assert.strictEqual(result, 'blurbValue'); + assert( + ( + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('sequence', () => { - const fakePath = "/rendered/path/sequence"; - const expectedParameters = { - sequence: "sequenceValue", - }; - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.sequencePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.sequencePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('sequencePath', () => { - const result = client.sequencePath("sequenceValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.sequencePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchSequenceFromSequenceName', () => { - const result = client.matchSequenceFromSequenceName(fakePath); - assert.strictEqual(result, "sequenceValue"); - assert((client.pathTemplates.sequencePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('sequence', () => { + const fakePath = '/rendered/path/sequence'; + const expectedParameters = { + sequence: 'sequenceValue', + }; + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.sequencePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.sequencePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('sequencePath', () => { + const result = client.sequencePath('sequenceValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.sequencePathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchSequenceFromSequenceName', () => { + const result = client.matchSequenceFromSequenceName(fakePath); + assert.strictEqual(result, 'sequenceValue'); + assert( + (client.pathTemplates.sequencePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('sequenceReport', () => { - const fakePath = "/rendered/path/sequenceReport"; - const expectedParameters = { - sequence: "sequenceValue", - }; - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.sequenceReportPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.sequenceReportPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('sequenceReportPath', () => { - const result = client.sequenceReportPath("sequenceValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.sequenceReportPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchSequenceFromSequenceReportName', () => { - const result = client.matchSequenceFromSequenceReportName(fakePath); - assert.strictEqual(result, "sequenceValue"); - assert((client.pathTemplates.sequenceReportPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('sequenceReport', () => { + const fakePath = '/rendered/path/sequenceReport'; + const expectedParameters = { + sequence: 'sequenceValue', + }; + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.sequenceReportPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.sequenceReportPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('sequenceReportPath', () => { + const result = client.sequenceReportPath('sequenceValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.sequenceReportPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchSequenceFromSequenceReportName', () => { + const result = client.matchSequenceFromSequenceReportName(fakePath); + assert.strictEqual(result, 'sequenceValue'); + assert( + (client.pathTemplates.sequenceReportPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('session', () => { - const fakePath = "/rendered/path/session"; - const expectedParameters = { - session: "sessionValue", - }; - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.sessionPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.sessionPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('sessionPath', () => { - const result = client.sessionPath("sessionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.sessionPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchSessionFromSessionName', () => { - const result = client.matchSessionFromSessionName(fakePath); - assert.strictEqual(result, "sessionValue"); - assert((client.pathTemplates.sessionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('session', () => { + const fakePath = '/rendered/path/session'; + const expectedParameters = { + session: 'sessionValue', + }; + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.sessionPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.sessionPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('sessionPath', () => { + const result = client.sessionPath('sessionValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.sessionPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchSessionFromSessionName', () => { + const result = client.matchSessionFromSessionName(fakePath); + assert.strictEqual(result, 'sessionValue'); + assert( + (client.pathTemplates.sessionPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('test', () => { - const fakePath = "/rendered/path/test"; - const expectedParameters = { - session: "sessionValue", - test: "testValue", - }; - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.testPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.testPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('testPath', () => { - const result = client.testPath("sessionValue", "testValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.testPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchSessionFromTestName', () => { - const result = client.matchSessionFromTestName(fakePath); - assert.strictEqual(result, "sessionValue"); - assert((client.pathTemplates.testPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchTestFromTestName', () => { - const result = client.matchTestFromTestName(fakePath); - assert.strictEqual(result, "testValue"); - assert((client.pathTemplates.testPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('test', () => { + const fakePath = '/rendered/path/test'; + const expectedParameters = { + session: 'sessionValue', + test: 'testValue', + }; + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.testPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.testPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('testPath', () => { + const result = client.testPath('sessionValue', 'testValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.testPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchSessionFromTestName', () => { + const result = client.matchSessionFromTestName(fakePath); + assert.strictEqual(result, 'sessionValue'); + assert( + (client.pathTemplates.testPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchTestFromTestName', () => { + const result = client.matchTestFromTestName(fakePath); + assert.strictEqual(result, 'testValue'); + assert( + (client.pathTemplates.testPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('user', () => { - const fakePath = "/rendered/path/user"; - const expectedParameters = { - user: "userValue", - }; - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.userPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.userPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('userPath', () => { - const result = client.userPath("userValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.userPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchUserFromUserName', () => { - const result = client.matchUserFromUserName(fakePath); - assert.strictEqual(result, "userValue"); - assert((client.pathTemplates.userPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('user', () => { + const fakePath = '/rendered/path/user'; + const expectedParameters = { + user: 'userValue', + }; + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.userPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.userPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('userPath', () => { + const result = client.userPath('userValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.userPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchUserFromUserName', () => { + const result = client.matchUserFromUserName(fakePath); + assert.strictEqual(result, 'userValue'); + assert( + (client.pathTemplates.userPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('userProfileBlurb', () => { - const fakePath = "/rendered/path/userProfileBlurb"; - const expectedParameters = { - user: "userValue", - blurb: "blurbValue", - }; - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.userProfileBlurbPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.userProfileBlurbPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('userProfileBlurbPath', () => { - const result = client.userProfileBlurbPath("userValue", "blurbValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.userProfileBlurbPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchUserFromUserProfileBlurbName', () => { - const result = client.matchUserFromUserProfileBlurbName(fakePath); - assert.strictEqual(result, "userValue"); - assert((client.pathTemplates.userProfileBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBlurbFromUserProfileBlurbName', () => { - const result = client.matchBlurbFromUserProfileBlurbName(fakePath); - assert.strictEqual(result, "blurbValue"); - assert((client.pathTemplates.userProfileBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('userProfileBlurb', () => { + const fakePath = '/rendered/path/userProfileBlurb'; + const expectedParameters = { + user: 'userValue', + blurb: 'blurbValue', + }; + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.userProfileBlurbPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.userProfileBlurbPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('userProfileBlurbPath', () => { + const result = client.userProfileBlurbPath('userValue', 'blurbValue'); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.userProfileBlurbPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchUserFromUserProfileBlurbName', () => { + const result = client.matchUserFromUserProfileBlurbName(fakePath); + assert.strictEqual(result, 'userValue'); + assert( + (client.pathTemplates.userProfileBlurbPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBlurbFromUserProfileBlurbName', () => { + const result = client.matchBlurbFromUserProfileBlurbName(fakePath); + assert.strictEqual(result, 'blurbValue'); + assert( + (client.pathTemplates.userProfileBlurbPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('userProfileBlurbsLegacyUserBlurb', () => { - const fakePath = "/rendered/path/userProfileBlurbsLegacyUserBlurb"; - const expectedParameters = { - user: "userValue", - legacy_user: "legacyUserValue", - blurb: "blurbValue", - }; - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('userProfileBlurbsLegacyUserBlurbPath', () => { - const result = client.userProfileBlurbsLegacyUserBlurbPath("userValue", "legacyUserValue", "blurbValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchUserFromUserProfileBlurbsLegacyUserBlurbName', () => { - const result = client.matchUserFromUserProfileBlurbsLegacyUserBlurbName(fakePath); - assert.strictEqual(result, "userValue"); - assert((client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName', () => { - const result = client.matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName(fakePath); - assert.strictEqual(result, "legacyUserValue"); - assert((client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBlurbFromUserProfileBlurbsLegacyUserBlurbName', () => { - const result = client.matchBlurbFromUserProfileBlurbsLegacyUserBlurbName(fakePath); - assert.strictEqual(result, "blurbValue"); - assert((client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('userProfileBlurbsLegacyUserBlurb', () => { + const fakePath = '/rendered/path/userProfileBlurbsLegacyUserBlurb'; + const expectedParameters = { + user: 'userValue', + legacy_user: 'legacyUserValue', + blurb: 'blurbValue', + }; + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('userProfileBlurbsLegacyUserBlurbPath', () => { + const result = client.userProfileBlurbsLegacyUserBlurbPath( + 'userValue', + 'legacyUserValue', + 'blurbValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchUserFromUserProfileBlurbsLegacyUserBlurbName', () => { + const result = + client.matchUserFromUserProfileBlurbsLegacyUserBlurbName(fakePath); + assert.strictEqual(result, 'userValue'); + assert( + ( + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName', () => { + const result = + client.matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName( + fakePath, + ); + assert.strictEqual(result, 'legacyUserValue'); + assert( + ( + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBlurbFromUserProfileBlurbsLegacyUserBlurbName', () => { + const result = + client.matchBlurbFromUserProfileBlurbsLegacyUserBlurbName(fakePath); + assert.strictEqual(result, 'blurbValue'); + assert( + ( + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/core/generator/gapic-generator-typescript/baselines/showcase-esm/esm/test/gapic_messaging_v1beta1.ts.baseline b/core/generator/gapic-generator-typescript/baselines/showcase-esm/esm/test/gapic_messaging_v1beta1.ts.baseline index e65f87dfaf42..9c254f7eedbd 100644 --- a/core/generator/gapic-generator-typescript/baselines/showcase-esm/esm/test/gapic_messaging_v1beta1.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/showcase-esm/esm/test/gapic_messaging_v1beta1.ts.baseline @@ -20,16 +20,16 @@ import * as protos from '../../protos/protos.js'; import assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as messagingModule from '../src/index.js'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; -import {protobuf, LROperation, operationsProtos} from 'google-gax'; +import { protobuf, LROperation, operationsProtos } from 'google-gax'; import fs from 'fs'; import path from 'path'; -import {fileURLToPath} from 'url'; +import { fileURLToPath } from 'url'; // @ts-ignore const dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -37,2328 +37,2954 @@ const dirname = path.dirname(fileURLToPath(import.meta.url)); // to fill in default values for request objects const root = protobuf.Root.fromJSON( JSON.parse( - fs.readFileSync(path.join(dirname, '..', '..', 'protos/protos.json'), 'utf8') - )) + fs.readFileSync( + path.join(dirname, '..', '..', 'protos/protos.json'), + 'utf8', + ), + ), +); // eslint-disable-next-line @typescript-eslint/no-unused-vars function getTypeDefaultValue(typeName: string, fields: string[]) { - let type = root.lookupType(typeName) as protobuf.Type; - for (const field of fields.slice(0, -1)) { - type = type?.fields[field]?.resolvedType as protobuf.Type; - } - return type?.fields[fields[fields.length - 1]]?.defaultValue ?? null; + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type?.fields[field]?.resolvedType as protobuf.Type; + } + return type?.fields[fields[fields.length - 1]]?.defaultValue ?? null; } function generateSampleMessage(instance: T) { - const filledObject = (instance.constructor as typeof protobuf.Message) - .toObject(instance as protobuf.Message, {defaults: true}); - return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, { defaults: true }); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; } function stubSimpleCall(response?: ResponseType, error?: Error) { - return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); } -function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { - return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +function stubSimpleCallWithCallback( + response?: ResponseType, + error?: Error, +) { + return error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); } -function stubServerStreamingCall(response?: ResponseType, error?: Error) { - const transformStub = error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); - const mockStream = new PassThrough({ - objectMode: true, - transform: transformStub, - }); - // write something to the stream to trigger transformStub and send the response back to the client - setImmediate(() => { mockStream.write({}); }); - setImmediate(() => { mockStream.end(); }); - return sinon.stub().returns(mockStream); +function stubServerStreamingCall( + response?: ResponseType, + error?: Error, +) { + const transformStub = error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + // write something to the stream to trigger transformStub and send the response back to the client + setImmediate(() => { + mockStream.write({}); + }); + setImmediate(() => { + mockStream.end(); + }); + return sinon.stub().returns(mockStream); } -function stubBidiStreamingCall(response?: ResponseType, error?: Error) { - const transformStub = error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); - const mockStream = new PassThrough({ - objectMode: true, - transform: transformStub, - }); - return sinon.stub().returns(mockStream); +function stubBidiStreamingCall( + response?: ResponseType, + error?: Error, +) { + const transformStub = error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + return sinon.stub().returns(mockStream); } -function stubClientStreamingCall(response?: ResponseType, error?: Error) { - if (error) { - return sinon.stub().callsArgWith(2, error); - } - const transformStub = sinon.stub(); - const mockStream = new PassThrough({ - objectMode: true, - transform: transformStub, - }); - return sinon.stub().returns(mockStream).callsArgWith(2, null, response); +function stubClientStreamingCall( + response?: ResponseType, + error?: Error, +) { + if (error) { + return sinon.stub().callsArgWith(2, error); + } + const transformStub = sinon.stub(); + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + return sinon.stub().returns(mockStream).callsArgWith(2, null, response); } -function stubLongRunningCall(response?: ResponseType, callError?: Error, lroError?: Error) { - const innerStub = lroError ? sinon.stub().rejects(lroError) : sinon.stub().resolves([response]); - const mockOperation = { - promise: innerStub, - }; - return callError ? sinon.stub().rejects(callError) : sinon.stub().resolves([mockOperation]); +function stubLongRunningCall( + response?: ResponseType, + callError?: Error, + lroError?: Error, +) { + const innerStub = lroError + ? sinon.stub().rejects(lroError) + : sinon.stub().resolves([response]); + const mockOperation = { + promise: innerStub, + }; + return callError + ? sinon.stub().rejects(callError) + : sinon.stub().resolves([mockOperation]); } -function stubLongRunningCallWithCallback(response?: ResponseType, callError?: Error, lroError?: Error) { - const innerStub = lroError ? sinon.stub().rejects(lroError) : sinon.stub().resolves([response]); - const mockOperation = { - promise: innerStub, - }; - return callError ? sinon.stub().callsArgWith(2, callError) : sinon.stub().callsArgWith(2, null, mockOperation); +function stubLongRunningCallWithCallback( + response?: ResponseType, + callError?: Error, + lroError?: Error, +) { + const innerStub = lroError + ? sinon.stub().rejects(lroError) + : sinon.stub().resolves([response]); + const mockOperation = { + promise: innerStub, + }; + return callError + ? sinon.stub().callsArgWith(2, callError) + : sinon.stub().callsArgWith(2, null, mockOperation); } -function stubPageStreamingCall(responses?: ResponseType[], error?: Error) { - const pagingStub = sinon.stub(); - if (responses) { - for (let i = 0; i < responses.length; ++i) { - pagingStub.onCall(i).callsArgWith(2, null, responses[i]); - } +function stubPageStreamingCall( + responses?: ResponseType[], + error?: Error, +) { + const pagingStub = sinon.stub(); + if (responses) { + for (let i = 0; i < responses.length; ++i) { + pagingStub.onCall(i).callsArgWith(2, null, responses[i]); } - const transformStub = error ? sinon.stub().callsArgWith(2, error) : pagingStub; - const mockStream = new PassThrough({ - objectMode: true, - transform: transformStub, - }); - // trigger as many responses as needed - if (responses) { - for (let i = 0; i < responses.length; ++i) { - setImmediate(() => { mockStream.write({}); }); - } - setImmediate(() => { mockStream.end(); }); - } else { - setImmediate(() => { mockStream.write({}); }); - setImmediate(() => { mockStream.end(); }); + } + const transformStub = error + ? sinon.stub().callsArgWith(2, error) + : pagingStub; + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + // trigger as many responses as needed + if (responses) { + for (let i = 0; i < responses.length; ++i) { + setImmediate(() => { + mockStream.write({}); + }); } - return sinon.stub().returns(mockStream); + setImmediate(() => { + mockStream.end(); + }); + } else { + setImmediate(() => { + mockStream.write({}); + }); + setImmediate(() => { + mockStream.end(); + }); + } + return sinon.stub().returns(mockStream); } -function stubAsyncIterationCall(responses?: ResponseType[], error?: Error) { - let counter = 0; - const asyncIterable = { - [Symbol.asyncIterator]() { - return { - async next() { - if (error) { - return Promise.reject(error); - } - if (counter >= responses!.length) { - return Promise.resolve({done: true, value: undefined}); - } - return Promise.resolve({done: false, value: responses![counter++]}); - } - }; - } - }; - return sinon.stub().returns(asyncIterable); +function stubAsyncIterationCall( + responses?: ResponseType[], + error?: Error, +) { + let counter = 0; + const asyncIterable = { + [Symbol.asyncIterator]() { + return { + async next() { + if (error) { + return Promise.reject(error); + } + if (counter >= responses!.length) { + return Promise.resolve({ done: true, value: undefined }); + } + return Promise.resolve({ done: false, value: responses![counter++] }); + }, + }; + }, + }; + return sinon.stub().returns(asyncIterable); } describe('v1beta1.MessagingClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new messagingModule.v1beta1.MessagingClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'localhost'); - }); - - it('has universeDomain', () => { - const client = new messagingModule.v1beta1.MessagingClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); - - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - it('throws DeprecationWarning if static servicePath is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const servicePath = messagingModule.v1beta1.MessagingClient.servicePath; - assert.strictEqual(servicePath, 'localhost'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = messagingModule.v1beta1.MessagingClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'localhost'); - assert(stub.called); - stub.restore(); - }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { new messagingModule.v1beta1.MessagingClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); - - it('has port', () => { - const port = messagingModule.v1beta1.MessagingClient.port; - assert(port); - assert(typeof port === 'number'); - }); - - it('should create a client with no option', () => { - const client = new messagingModule.v1beta1.MessagingClient(); - assert(client); - }); - - it('should create a client with gRPC fallback', () => { - const client = new messagingModule.v1beta1.MessagingClient({ - fallback: true, - }); - assert(client); - }); - - it('has initialize method and supports deferred initialization', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.messagingStub, undefined); - await client.initialize(); - assert(client.messagingStub); - }); - - it('has close method for the initialized client', done => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.messagingStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); - - it('has close method for the non-initialized client', done => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.messagingStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); - - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); - }); - - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId((err?: Error|null, projectId?: string|null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } - }); - }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new messagingModule.v1beta1.MessagingClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'localhost'); }); - describe('createRoom', () => { - it('invokes createRoom without error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.CreateRoomRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.Room() - ); - client.innerApiCalls.createRoom = stubSimpleCall(expectedResponse); - const [response] = await client.createRoom(request); - assert.deepStrictEqual(response, expectedResponse); - }); - - it('invokes createRoom without error using callback', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.CreateRoomRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.Room() - ); - client.innerApiCalls.createRoom = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createRoom( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IRoom|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); + it('has universeDomain', () => { + const client = new messagingModule.v1beta1.MessagingClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - it('invokes createRoom with error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.CreateRoomRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.createRoom = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createRoom(request), expectedError); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = messagingModule.v1beta1.MessagingClient.servicePath; + assert.strictEqual(servicePath, 'localhost'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = messagingModule.v1beta1.MessagingClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'localhost'); + assert(stub.called); + stub.restore(); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new messagingModule.v1beta1.MessagingClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); + }); - it('invokes createRoom with closed client', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.CreateRoomRequest() - ); - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createRoom(request), expectedError); - }); + it('has port', () => { + const port = messagingModule.v1beta1.MessagingClient.port; + assert(port); + assert(typeof port === 'number'); }); - describe('getRoom', () => { - it('invokes getRoom without error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.GetRoomRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.GetRoomRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.Room() - ); - client.innerApiCalls.getRoom = stubSimpleCall(expectedResponse); - const [response] = await client.getRoom(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getRoom as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getRoom as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('should create a client with no option', () => { + const client = new messagingModule.v1beta1.MessagingClient(); + assert(client); + }); - it('invokes getRoom without error using callback', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.GetRoomRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.GetRoomRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.Room() - ); - client.innerApiCalls.getRoom = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getRoom( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IRoom|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getRoom as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getRoom as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('should create a client with gRPC fallback', () => { + const client = new messagingModule.v1beta1.MessagingClient({ + fallback: true, + }); + assert(client); + }); - it('invokes getRoom with error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.GetRoomRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.GetRoomRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getRoom = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getRoom(request), expectedError); - const actualRequest = (client.innerApiCalls.getRoom as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getRoom as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has initialize method and supports deferred initialization', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.messagingStub, undefined); + await client.initialize(); + assert(client.messagingStub); + }); - it('invokes getRoom with closed client', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.GetRoomRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.GetRoomRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getRoom(request), expectedError); + it('has close method for the initialized client', (done) => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.messagingStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); }); - describe('updateRoom', () => { - it('invokes updateRoom without error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.UpdateRoomRequest() - ); - request.room ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.UpdateRoomRequest', ['room', 'name']); - request.room.name = defaultValue1; - const expectedHeaderRequestParams = `room.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.Room() - ); - client.innerApiCalls.updateRoom = stubSimpleCall(expectedResponse); - const [response] = await client.updateRoom(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateRoom as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateRoom as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('has close method for the non-initialized client', (done) => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.messagingStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes updateRoom without error using callback', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.UpdateRoomRequest() - ); - request.room ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.UpdateRoomRequest', ['room', 'name']); - request.room.name = defaultValue1; - const expectedHeaderRequestParams = `room.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.Room() - ); - client.innerApiCalls.updateRoom = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateRoom( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IRoom|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateRoom as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateRoom as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + }); - it('invokes updateRoom with error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.UpdateRoomRequest() - ); - request.room ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.UpdateRoomRequest', ['room', 'name']); - request.room.name = defaultValue1; - const expectedHeaderRequestParams = `room.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateRoom = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateRoom(request), expectedError); - const actualRequest = (client.innerApiCalls.updateRoom as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateRoom as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } + }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + }); + + describe('createRoom', () => { + it('invokes createRoom without error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.CreateRoomRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.Room(), + ); + client.innerApiCalls.createRoom = stubSimpleCall(expectedResponse); + const [response] = await client.createRoom(request); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes updateRoom with closed client', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.UpdateRoomRequest() - ); - request.room ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.UpdateRoomRequest', ['room', 'name']); - request.room.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateRoom(request), expectedError); - }); + it('invokes createRoom without error using callback', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.CreateRoomRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.Room(), + ); + client.innerApiCalls.createRoom = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createRoom( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IRoom | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); }); - describe('deleteRoom', () => { - it('invokes deleteRoom without error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.DeleteRoomRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.DeleteRoomRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteRoom = stubSimpleCall(expectedResponse); - const [response] = await client.deleteRoom(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteRoom as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteRoom as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createRoom with error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.CreateRoomRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.createRoom = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.createRoom(request), expectedError); + }); - it('invokes deleteRoom without error using callback', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.DeleteRoomRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.DeleteRoomRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteRoom = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteRoom( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteRoom as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteRoom as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createRoom with closed client', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.CreateRoomRequest(), + ); + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.createRoom(request), expectedError); + }); + }); + + describe('getRoom', () => { + it('invokes getRoom without error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.GetRoomRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.GetRoomRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.Room(), + ); + client.innerApiCalls.getRoom = stubSimpleCall(expectedResponse); + const [response] = await client.getRoom(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.getRoom as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getRoom as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteRoom with error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.DeleteRoomRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.DeleteRoomRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteRoom = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteRoom(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteRoom as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteRoom as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getRoom without error using callback', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.GetRoomRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.GetRoomRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.Room(), + ); + client.innerApiCalls.getRoom = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getRoom( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IRoom | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.getRoom as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getRoom as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteRoom with closed client', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.DeleteRoomRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.DeleteRoomRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteRoom(request), expectedError); - }); + it('invokes getRoom with error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.GetRoomRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.GetRoomRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getRoom = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.getRoom(request), expectedError); + const actualRequest = (client.innerApiCalls.getRoom as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getRoom as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('createBlurb', () => { - it('invokes createBlurb without error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.CreateBlurbRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.CreateBlurbRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.Blurb() - ); - client.innerApiCalls.createBlurb = stubSimpleCall(expectedResponse); - const [response] = await client.createBlurb(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createBlurb as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createBlurb as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getRoom with closed client', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.GetRoomRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.GetRoomRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getRoom(request), expectedError); + }); + }); + + describe('updateRoom', () => { + it('invokes updateRoom without error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.UpdateRoomRequest(), + ); + request.room ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.UpdateRoomRequest', + ['room', 'name'], + ); + request.room.name = defaultValue1; + const expectedHeaderRequestParams = `room.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.Room(), + ); + client.innerApiCalls.updateRoom = stubSimpleCall(expectedResponse); + const [response] = await client.updateRoom(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateRoom as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateRoom as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createBlurb without error using callback', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.CreateBlurbRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.CreateBlurbRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.Blurb() - ); - client.innerApiCalls.createBlurb = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createBlurb( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IBlurb|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createBlurb as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createBlurb as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateRoom without error using callback', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.UpdateRoomRequest(), + ); + request.room ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.UpdateRoomRequest', + ['room', 'name'], + ); + request.room.name = defaultValue1; + const expectedHeaderRequestParams = `room.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.Room(), + ); + client.innerApiCalls.updateRoom = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateRoom( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IRoom | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateRoom as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateRoom as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createBlurb with error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.CreateBlurbRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.CreateBlurbRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createBlurb = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createBlurb(request), expectedError); - const actualRequest = (client.innerApiCalls.createBlurb as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createBlurb as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateRoom with error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.UpdateRoomRequest(), + ); + request.room ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.UpdateRoomRequest', + ['room', 'name'], + ); + request.room.name = defaultValue1; + const expectedHeaderRequestParams = `room.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateRoom = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.updateRoom(request), expectedError); + const actualRequest = ( + client.innerApiCalls.updateRoom as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateRoom as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createBlurb with closed client', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.CreateBlurbRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.CreateBlurbRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createBlurb(request), expectedError); - }); + it('invokes updateRoom with closed client', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.UpdateRoomRequest(), + ); + request.room ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.UpdateRoomRequest', + ['room', 'name'], + ); + request.room.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.updateRoom(request), expectedError); + }); + }); + + describe('deleteRoom', () => { + it('invokes deleteRoom without error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.DeleteRoomRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.DeleteRoomRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteRoom = stubSimpleCall(expectedResponse); + const [response] = await client.deleteRoom(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteRoom as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteRoom as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('getBlurb', () => { - it('invokes getBlurb without error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.GetBlurbRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.GetBlurbRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.Blurb() - ); - client.innerApiCalls.getBlurb = stubSimpleCall(expectedResponse); - const [response] = await client.getBlurb(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getBlurb as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getBlurb as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteRoom without error using callback', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.DeleteRoomRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.DeleteRoomRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteRoom = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteRoom( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteRoom as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteRoom as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getBlurb without error using callback', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.GetBlurbRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.GetBlurbRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.Blurb() - ); - client.innerApiCalls.getBlurb = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getBlurb( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IBlurb|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getBlurb as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getBlurb as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteRoom with error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.DeleteRoomRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.DeleteRoomRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteRoom = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.deleteRoom(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteRoom as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteRoom as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getBlurb with error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.GetBlurbRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.GetBlurbRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getBlurb = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getBlurb(request), expectedError); - const actualRequest = (client.innerApiCalls.getBlurb as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getBlurb as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteRoom with closed client', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.DeleteRoomRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.DeleteRoomRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.deleteRoom(request), expectedError); + }); + }); + + describe('createBlurb', () => { + it('invokes createBlurb without error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.CreateBlurbRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.CreateBlurbRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.Blurb(), + ); + client.innerApiCalls.createBlurb = stubSimpleCall(expectedResponse); + const [response] = await client.createBlurb(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createBlurb as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createBlurb as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getBlurb with closed client', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.GetBlurbRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.GetBlurbRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getBlurb(request), expectedError); - }); + it('invokes createBlurb without error using callback', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.CreateBlurbRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.CreateBlurbRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.Blurb(), + ); + client.innerApiCalls.createBlurb = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createBlurb( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IBlurb | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createBlurb as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createBlurb as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('updateBlurb', () => { - it('invokes updateBlurb without error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.UpdateBlurbRequest() - ); - request.blurb ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.UpdateBlurbRequest', ['blurb', 'name']); - request.blurb.name = defaultValue1; - const expectedHeaderRequestParams = `blurb.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.Blurb() - ); - client.innerApiCalls.updateBlurb = stubSimpleCall(expectedResponse); - const [response] = await client.updateBlurb(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateBlurb as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateBlurb as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createBlurb with error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.CreateBlurbRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.CreateBlurbRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createBlurb = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.createBlurb(request), expectedError); + const actualRequest = ( + client.innerApiCalls.createBlurb as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createBlurb as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateBlurb without error using callback', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.UpdateBlurbRequest() - ); - request.blurb ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.UpdateBlurbRequest', ['blurb', 'name']); - request.blurb.name = defaultValue1; - const expectedHeaderRequestParams = `blurb.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.Blurb() - ); - client.innerApiCalls.updateBlurb = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateBlurb( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IBlurb|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateBlurb as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateBlurb as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createBlurb with closed client', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.CreateBlurbRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.CreateBlurbRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.createBlurb(request), expectedError); + }); + }); + + describe('getBlurb', () => { + it('invokes getBlurb without error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.GetBlurbRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.GetBlurbRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.Blurb(), + ); + client.innerApiCalls.getBlurb = stubSimpleCall(expectedResponse); + const [response] = await client.getBlurb(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getBlurb as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getBlurb as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateBlurb with error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.UpdateBlurbRequest() - ); - request.blurb ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.UpdateBlurbRequest', ['blurb', 'name']); - request.blurb.name = defaultValue1; - const expectedHeaderRequestParams = `blurb.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateBlurb = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateBlurb(request), expectedError); - const actualRequest = (client.innerApiCalls.updateBlurb as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateBlurb as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getBlurb without error using callback', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.GetBlurbRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.GetBlurbRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.Blurb(), + ); + client.innerApiCalls.getBlurb = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getBlurb( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IBlurb | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getBlurb as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getBlurb as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateBlurb with closed client', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.UpdateBlurbRequest() - ); - request.blurb ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.UpdateBlurbRequest', ['blurb', 'name']); - request.blurb.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateBlurb(request), expectedError); - }); + it('invokes getBlurb with error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.GetBlurbRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.GetBlurbRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getBlurb = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.getBlurb(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getBlurb as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getBlurb as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('deleteBlurb', () => { - it('invokes deleteBlurb without error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.DeleteBlurbRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.DeleteBlurbRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteBlurb = stubSimpleCall(expectedResponse); - const [response] = await client.deleteBlurb(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteBlurb as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteBlurb as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getBlurb with closed client', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.GetBlurbRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.GetBlurbRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getBlurb(request), expectedError); + }); + }); + + describe('updateBlurb', () => { + it('invokes updateBlurb without error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.UpdateBlurbRequest(), + ); + request.blurb ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.UpdateBlurbRequest', + ['blurb', 'name'], + ); + request.blurb.name = defaultValue1; + const expectedHeaderRequestParams = `blurb.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.Blurb(), + ); + client.innerApiCalls.updateBlurb = stubSimpleCall(expectedResponse); + const [response] = await client.updateBlurb(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateBlurb as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateBlurb as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteBlurb without error using callback', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.DeleteBlurbRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.DeleteBlurbRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteBlurb = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteBlurb( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteBlurb as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteBlurb as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateBlurb without error using callback', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.UpdateBlurbRequest(), + ); + request.blurb ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.UpdateBlurbRequest', + ['blurb', 'name'], + ); + request.blurb.name = defaultValue1; + const expectedHeaderRequestParams = `blurb.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.Blurb(), + ); + client.innerApiCalls.updateBlurb = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateBlurb( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IBlurb | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateBlurb as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateBlurb as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteBlurb with error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.DeleteBlurbRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.DeleteBlurbRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteBlurb = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteBlurb(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteBlurb as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteBlurb as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateBlurb with error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.UpdateBlurbRequest(), + ); + request.blurb ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.UpdateBlurbRequest', + ['blurb', 'name'], + ); + request.blurb.name = defaultValue1; + const expectedHeaderRequestParams = `blurb.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateBlurb = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.updateBlurb(request), expectedError); + const actualRequest = ( + client.innerApiCalls.updateBlurb as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateBlurb as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteBlurb with closed client', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.DeleteBlurbRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.DeleteBlurbRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteBlurb(request), expectedError); - }); + it('invokes updateBlurb with closed client', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.UpdateBlurbRequest(), + ); + request.blurb ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.UpdateBlurbRequest', + ['blurb', 'name'], + ); + request.blurb.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.updateBlurb(request), expectedError); + }); + }); + + describe('deleteBlurb', () => { + it('invokes deleteBlurb without error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.DeleteBlurbRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.DeleteBlurbRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteBlurb = stubSimpleCall(expectedResponse); + const [response] = await client.deleteBlurb(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteBlurb as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteBlurb as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('searchBlurbs', () => { - it('invokes searchBlurbs without error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.SearchBlurbsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.SearchBlurbsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.searchBlurbs = stubLongRunningCall(expectedResponse); - const [operation] = await client.searchBlurbs(request); - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.searchBlurbs as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.searchBlurbs as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteBlurb without error using callback', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.DeleteBlurbRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.DeleteBlurbRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteBlurb = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteBlurb( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteBlurb as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteBlurb as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes searchBlurbs without error using callback', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.SearchBlurbsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.SearchBlurbsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.searchBlurbs = stubLongRunningCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.searchBlurbs( - request, - (err?: Error|null, - result?: LROperation|null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const operation = await promise as LROperation; - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.searchBlurbs as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.searchBlurbs as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteBlurb with error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.DeleteBlurbRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.DeleteBlurbRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteBlurb = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.deleteBlurb(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteBlurb as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteBlurb as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes searchBlurbs with call error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.SearchBlurbsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.SearchBlurbsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.searchBlurbs = stubLongRunningCall(undefined, expectedError); - await assert.rejects(client.searchBlurbs(request), expectedError); - const actualRequest = (client.innerApiCalls.searchBlurbs as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.searchBlurbs as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteBlurb with closed client', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.DeleteBlurbRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.DeleteBlurbRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.deleteBlurb(request), expectedError); + }); + }); + + describe('searchBlurbs', () => { + it('invokes searchBlurbs without error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.SearchBlurbsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.SearchBlurbsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.searchBlurbs = stubLongRunningCall(expectedResponse); + const [operation] = await client.searchBlurbs(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.searchBlurbs as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.searchBlurbs as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes searchBlurbs with LRO error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.SearchBlurbsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.SearchBlurbsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.searchBlurbs = stubLongRunningCall(undefined, undefined, expectedError); - const [operation] = await client.searchBlurbs(request); - await assert.rejects(operation.promise(), expectedError); - const actualRequest = (client.innerApiCalls.searchBlurbs as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.searchBlurbs as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes searchBlurbs without error using callback', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.SearchBlurbsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.SearchBlurbsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.searchBlurbs = + stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.searchBlurbs( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.showcase.v1beta1.ISearchBlurbsResponse, + protos.google.showcase.v1beta1.ISearchBlurbsMetadata + > | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const operation = (await promise) as LROperation< + protos.google.showcase.v1beta1.ISearchBlurbsResponse, + protos.google.showcase.v1beta1.ISearchBlurbsMetadata + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.searchBlurbs as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.searchBlurbs as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkSearchBlurbsProgress without error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedResponse = generateSampleMessage( - new operationsProtos.google.longrunning.Operation() - ); - expectedResponse.name = 'test'; - expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; - expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')} - - client.operationsClient.getOperation = stubSimpleCall(expectedResponse); - const decodedOperation = await client.checkSearchBlurbsProgress(expectedResponse.name); - assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); - assert(decodedOperation.metadata); - assert((client.operationsClient.getOperation as SinonStub).getCall(0)); - }); + it('invokes searchBlurbs with call error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.SearchBlurbsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.SearchBlurbsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.searchBlurbs = stubLongRunningCall( + undefined, + expectedError, + ); + await assert.rejects(client.searchBlurbs(request), expectedError); + const actualRequest = ( + client.innerApiCalls.searchBlurbs as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.searchBlurbs as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkSearchBlurbsProgress with error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedError = new Error('expected'); - - client.operationsClient.getOperation = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.checkSearchBlurbsProgress(''), expectedError); - assert((client.operationsClient.getOperation as SinonStub) - .getCall(0)); - }); + it('invokes searchBlurbs with LRO error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.SearchBlurbsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.SearchBlurbsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.searchBlurbs = stubLongRunningCall( + undefined, + undefined, + expectedError, + ); + const [operation] = await client.searchBlurbs(request); + await assert.rejects(operation.promise(), expectedError); + const actualRequest = ( + client.innerApiCalls.searchBlurbs as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.searchBlurbs as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('streamBlurbs', () => { - it('invokes streamBlurbs without error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.StreamBlurbsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.StreamBlurbsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.StreamBlurbsResponse() - ); - client.innerApiCalls.streamBlurbs = stubServerStreamingCall(expectedResponse); - const stream = client.streamBlurbs(request); - const promise = new Promise((resolve, reject) => { - stream.on('data', (response: protos.google.showcase.v1beta1.StreamBlurbsResponse) => { - resolve(response); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.streamBlurbs as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.streamBlurbs as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes checkSearchBlurbsProgress without error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation(), + ); + expectedResponse.name = 'test'; + expectedResponse.response = { type_url: 'url', value: Buffer.from('') }; + expectedResponse.metadata = { type_url: 'url', value: Buffer.from('') }; + + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const decodedOperation = await client.checkSearchBlurbsProgress( + expectedResponse.name, + ); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); - it('invokes streamBlurbs without error and gaxServerStreamingRetries enabled', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.StreamBlurbsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.StreamBlurbsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.StreamBlurbsResponse() - ); - client.innerApiCalls.streamBlurbs = stubServerStreamingCall(expectedResponse); - const stream = client.streamBlurbs(request); - const promise = new Promise((resolve, reject) => { - stream.on('data', (response: protos.google.showcase.v1beta1.StreamBlurbsResponse) => { - resolve(response); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.streamBlurbs as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.streamBlurbs as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes checkSearchBlurbsProgress with error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const expectedError = new Error('expected'); + + client.operationsClient.getOperation = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.checkSearchBlurbsProgress(''), expectedError); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + }); + + describe('streamBlurbs', () => { + it('invokes streamBlurbs without error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.StreamBlurbsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.StreamBlurbsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.StreamBlurbsResponse(), + ); + client.innerApiCalls.streamBlurbs = + stubServerStreamingCall(expectedResponse); + const stream = client.streamBlurbs(request); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + (response: protos.google.showcase.v1beta1.StreamBlurbsResponse) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.streamBlurbs as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.streamBlurbs as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes streamBlurbs with error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.StreamBlurbsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.StreamBlurbsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.streamBlurbs = stubServerStreamingCall(undefined, expectedError); - const stream = client.streamBlurbs(request); - const promise = new Promise((resolve, reject) => { - stream.on('data', (response: protos.google.showcase.v1beta1.StreamBlurbsResponse) => { - resolve(response); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - const actualRequest = (client.innerApiCalls.streamBlurbs as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.streamBlurbs as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes streamBlurbs without error and gaxServerStreamingRetries enabled', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.StreamBlurbsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.StreamBlurbsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.StreamBlurbsResponse(), + ); + client.innerApiCalls.streamBlurbs = + stubServerStreamingCall(expectedResponse); + const stream = client.streamBlurbs(request); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + (response: protos.google.showcase.v1beta1.StreamBlurbsResponse) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.streamBlurbs as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.streamBlurbs as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes streamBlurbs with closed client', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.StreamBlurbsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.StreamBlurbsRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - const stream = client.streamBlurbs(request, {retryRequestOptions: {noResponseRetries: 0}}); - const promise = new Promise((resolve, reject) => { - stream.on('data', (response: protos.google.showcase.v1beta1.StreamBlurbsResponse) => { - resolve(response); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - }); - it('should create a client with gaxServerStreamingRetries enabled', () => { - const client = new messagingModule.v1beta1.MessagingClient({ - gaxServerStreamingRetries: true, - }); - assert(client); - }); + it('invokes streamBlurbs with error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.StreamBlurbsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.StreamBlurbsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.streamBlurbs = stubServerStreamingCall( + undefined, + expectedError, + ); + const stream = client.streamBlurbs(request); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + (response: protos.google.showcase.v1beta1.StreamBlurbsResponse) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + const actualRequest = ( + client.innerApiCalls.streamBlurbs as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.streamBlurbs as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('connect', () => { - it('invokes connect without error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ConnectRequest() - ); - - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.StreamBlurbsResponse() - ); - client.innerApiCalls.connect = stubBidiStreamingCall(expectedResponse); - const stream = client.connect(); - const promise = new Promise((resolve, reject) => { - stream.on('data', (response: protos.google.showcase.v1beta1.StreamBlurbsResponse) => { - resolve(response); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - stream.write(request); - stream.end(); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - assert((client.innerApiCalls.connect as SinonStub) - .getCall(0).calledWith(null)); - assert.deepStrictEqual(((stream as unknown as PassThrough) - ._transform as SinonStub).getCall(0).args[0], request); - }); + it('invokes streamBlurbs with closed client', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.StreamBlurbsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.StreamBlurbsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + const stream = client.streamBlurbs(request, { + retryRequestOptions: { noResponseRetries: 0 }, + }); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + (response: protos.google.showcase.v1beta1.StreamBlurbsResponse) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + }); + it('should create a client with gaxServerStreamingRetries enabled', () => { + const client = new messagingModule.v1beta1.MessagingClient({ + gaxServerStreamingRetries: true, + }); + assert(client); + }); + }); + + describe('connect', () => { + it('invokes connect without error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ConnectRequest(), + ); + + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.StreamBlurbsResponse(), + ); + client.innerApiCalls.connect = stubBidiStreamingCall(expectedResponse); + const stream = client.connect(); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + (response: protos.google.showcase.v1beta1.StreamBlurbsResponse) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); + }); + stream.write(request); + stream.end(); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + assert( + (client.innerApiCalls.connect as SinonStub).getCall(0).calledWith(null), + ); + assert.deepStrictEqual( + ((stream as unknown as PassThrough)._transform as SinonStub).getCall(0) + .args[0], + request, + ); + }); - it('invokes connect with error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ConnectRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.connect = stubBidiStreamingCall(undefined, expectedError); - const stream = client.connect(); - const promise = new Promise((resolve, reject) => { - stream.on('data', (response: protos.google.showcase.v1beta1.StreamBlurbsResponse) => { - resolve(response); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - stream.write(request); - stream.end(); - }); - await assert.rejects(promise, expectedError); - assert((client.innerApiCalls.connect as SinonStub) - .getCall(0).calledWith(null)); - assert.deepStrictEqual(((stream as unknown as PassThrough) - ._transform as SinonStub).getCall(0).args[0], request); - }); + it('invokes connect with error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ConnectRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.connect = stubBidiStreamingCall( + undefined, + expectedError, + ); + const stream = client.connect(); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + (response: protos.google.showcase.v1beta1.StreamBlurbsResponse) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); + }); + stream.write(request); + stream.end(); + }); + await assert.rejects(promise, expectedError); + assert( + (client.innerApiCalls.connect as SinonStub).getCall(0).calledWith(null), + ); + assert.deepStrictEqual( + ((stream as unknown as PassThrough)._transform as SinonStub).getCall(0) + .args[0], + request, + ); + }); + }); + + describe('sendBlurbs', () => { + it('invokes sendBlurbs without error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.CreateBlurbRequest(), + ); + + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.SendBlurbsResponse(), + ); + client.innerApiCalls.sendBlurbs = + stubClientStreamingCall(expectedResponse); + let stream: PassThrough; + const promise = new Promise((resolve, reject) => { + stream = client.sendBlurbs( + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.ISendBlurbsResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ) as unknown as PassThrough; + stream.write(request); + stream.end(); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + assert( + (client.innerApiCalls.sendBlurbs as SinonStub) + .getCall(0) + .calledWith(null, {} /*, callback defined above */), + ); + assert.deepStrictEqual( + (stream!._transform as SinonStub).getCall(0).args[0], + request, + ); }); - describe('sendBlurbs', () => { - it('invokes sendBlurbs without error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.CreateBlurbRequest() - ); - - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.SendBlurbsResponse() - ); - client.innerApiCalls.sendBlurbs = stubClientStreamingCall(expectedResponse); - let stream: PassThrough; - const promise = new Promise((resolve, reject) => { - stream = client.sendBlurbs( - (err?: Error|null, result?: protos.google.showcase.v1beta1.ISendBlurbsResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }) as unknown as PassThrough; - stream.write(request); - stream.end(); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - assert((client.innerApiCalls.sendBlurbs as SinonStub) - .getCall(0).calledWith(null, {} /*, callback defined above */)); - assert.deepStrictEqual((stream!._transform as SinonStub).getCall(0).args[0], request); - }); + it('invokes sendBlurbs with error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.CreateBlurbRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.sendBlurbs = stubClientStreamingCall( + undefined, + expectedError, + ); + let stream: PassThrough; + const promise = new Promise((resolve, reject) => { + stream = client.sendBlurbs( + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.ISendBlurbsResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ) as unknown as PassThrough; + stream.write(request); + stream.end(); + }); + await assert.rejects(promise, expectedError); + assert( + (client.innerApiCalls.sendBlurbs as SinonStub) + .getCall(0) + .calledWith(null, {} /*, callback defined above */), + ); + }); + }); + + describe('listRooms', () => { + it('invokes listRooms without error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListRoomsRequest(), + ); + const expectedResponse = [ + generateSampleMessage(new protos.google.showcase.v1beta1.Room()), + generateSampleMessage(new protos.google.showcase.v1beta1.Room()), + generateSampleMessage(new protos.google.showcase.v1beta1.Room()), + ]; + client.innerApiCalls.listRooms = stubSimpleCall(expectedResponse); + const [response] = await client.listRooms(request); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes sendBlurbs with error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.CreateBlurbRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.sendBlurbs = stubClientStreamingCall(undefined, expectedError); - let stream: PassThrough; - const promise = new Promise((resolve, reject) => { - stream = client.sendBlurbs( - (err?: Error|null, result?: protos.google.showcase.v1beta1.ISendBlurbsResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }) as unknown as PassThrough; - stream.write(request); - stream.end(); - }); - await assert.rejects(promise, expectedError); - assert((client.innerApiCalls.sendBlurbs as SinonStub) - .getCall(0).calledWith(null, {} /*, callback defined above */)); - }); + it('invokes listRooms without error using callback', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListRoomsRequest(), + ); + const expectedResponse = [ + generateSampleMessage(new protos.google.showcase.v1beta1.Room()), + generateSampleMessage(new protos.google.showcase.v1beta1.Room()), + generateSampleMessage(new protos.google.showcase.v1beta1.Room()), + ]; + client.innerApiCalls.listRooms = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listRooms( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IRoom[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); }); - describe('listRooms', () => { - it('invokes listRooms without error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListRoomsRequest() - );const expectedResponse = [ - generateSampleMessage(new protos.google.showcase.v1beta1.Room()), - generateSampleMessage(new protos.google.showcase.v1beta1.Room()), - generateSampleMessage(new protos.google.showcase.v1beta1.Room()), - ]; - client.innerApiCalls.listRooms = stubSimpleCall(expectedResponse); - const [response] = await client.listRooms(request); - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes listRooms with error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListRoomsRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.listRooms = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.listRooms(request), expectedError); + }); - it('invokes listRooms without error using callback', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListRoomsRequest() - );const expectedResponse = [ - generateSampleMessage(new protos.google.showcase.v1beta1.Room()), - generateSampleMessage(new protos.google.showcase.v1beta1.Room()), - generateSampleMessage(new protos.google.showcase.v1beta1.Room()), - ]; - client.innerApiCalls.listRooms = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listRooms( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IRoom[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes listRoomsStream without error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListRoomsRequest(), + ); + const expectedResponse = [ + generateSampleMessage(new protos.google.showcase.v1beta1.Room()), + generateSampleMessage(new protos.google.showcase.v1beta1.Room()), + generateSampleMessage(new protos.google.showcase.v1beta1.Room()), + ]; + client.descriptors.page.listRooms.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listRoomsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.showcase.v1beta1.Room[] = []; + stream.on('data', (response: protos.google.showcase.v1beta1.Room) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listRooms.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listRooms, request), + ); + }); - it('invokes listRooms with error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListRoomsRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.listRooms = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listRooms(request), expectedError); - }); + it('invokes listRoomsStream with error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListRoomsRequest(), + ); + const expectedError = new Error('expected'); + client.descriptors.page.listRooms.createStream = stubPageStreamingCall( + undefined, + expectedError, + ); + const stream = client.listRoomsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.showcase.v1beta1.Room[] = []; + stream.on('data', (response: protos.google.showcase.v1beta1.Room) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listRooms.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listRooms, request), + ); + }); - it('invokes listRoomsStream without error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListRoomsRequest() - ); - const expectedResponse = [ - generateSampleMessage(new protos.google.showcase.v1beta1.Room()), - generateSampleMessage(new protos.google.showcase.v1beta1.Room()), - generateSampleMessage(new protos.google.showcase.v1beta1.Room()), - ]; - client.descriptors.page.listRooms.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listRoomsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.showcase.v1beta1.Room[] = []; - stream.on('data', (response: protos.google.showcase.v1beta1.Room) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.listRooms.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listRooms, request)); - }); + it('uses async iteration with listRooms without error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListRoomsRequest(), + ); + const expectedResponse = [ + generateSampleMessage(new protos.google.showcase.v1beta1.Room()), + generateSampleMessage(new protos.google.showcase.v1beta1.Room()), + generateSampleMessage(new protos.google.showcase.v1beta1.Room()), + ]; + client.descriptors.page.listRooms.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.showcase.v1beta1.IRoom[] = []; + const iterable = client.listRoomsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + (client.descriptors.page.listRooms.asyncIterate as SinonStub).getCall(0) + .args[1], + request, + ); + }); - it('invokes listRoomsStream with error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListRoomsRequest() - ); - const expectedError = new Error('expected'); - client.descriptors.page.listRooms.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listRoomsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.showcase.v1beta1.Room[] = []; - stream.on('data', (response: protos.google.showcase.v1beta1.Room) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listRooms.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listRooms, request)); - }); + it('uses async iteration with listRooms with error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListRoomsRequest(), + ); + const expectedError = new Error('expected'); + client.descriptors.page.listRooms.asyncIterate = stubAsyncIterationCall( + undefined, + expectedError, + ); + const iterable = client.listRoomsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.showcase.v1beta1.IRoom[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + (client.descriptors.page.listRooms.asyncIterate as SinonStub).getCall(0) + .args[1], + request, + ); + }); + }); + + describe('listBlurbs', () => { + it('invokes listBlurbs without error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListBlurbsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.ListBlurbsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.showcase.v1beta1.Blurb()), + generateSampleMessage(new protos.google.showcase.v1beta1.Blurb()), + generateSampleMessage(new protos.google.showcase.v1beta1.Blurb()), + ]; + client.innerApiCalls.listBlurbs = stubSimpleCall(expectedResponse); + const [response] = await client.listBlurbs(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listBlurbs as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listBlurbs as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('uses async iteration with listRooms without error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListRoomsRequest() - ); - const expectedResponse = [ - generateSampleMessage(new protos.google.showcase.v1beta1.Room()), - generateSampleMessage(new protos.google.showcase.v1beta1.Room()), - generateSampleMessage(new protos.google.showcase.v1beta1.Room()), - ]; - client.descriptors.page.listRooms.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.showcase.v1beta1.IRoom[] = []; - const iterable = client.listRoomsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); + it('invokes listBlurbs without error using callback', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListBlurbsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.ListBlurbsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.showcase.v1beta1.Blurb()), + generateSampleMessage(new protos.google.showcase.v1beta1.Blurb()), + generateSampleMessage(new protos.google.showcase.v1beta1.Blurb()), + ]; + client.innerApiCalls.listBlurbs = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listBlurbs( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IBlurb[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listRooms.asyncIterate as SinonStub) - .getCall(0).args[1], request); - }); - - it('uses async iteration with listRooms with error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListRoomsRequest() - ); - const expectedError = new Error('expected'); - client.descriptors.page.listRooms.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listRoomsAsync(request); - await assert.rejects(async () => { - const responses: protos.google.showcase.v1beta1.IRoom[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listRooms.asyncIterate as SinonStub) - .getCall(0).args[1], request); - }); + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listBlurbs as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listBlurbs as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('listBlurbs', () => { - it('invokes listBlurbs without error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListBlurbsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.ListBlurbsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.showcase.v1beta1.Blurb()), - generateSampleMessage(new protos.google.showcase.v1beta1.Blurb()), - generateSampleMessage(new protos.google.showcase.v1beta1.Blurb()), - ]; - client.innerApiCalls.listBlurbs = stubSimpleCall(expectedResponse); - const [response] = await client.listBlurbs(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listBlurbs as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listBlurbs as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listBlurbs without error using callback', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListBlurbsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.ListBlurbsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.showcase.v1beta1.Blurb()), - generateSampleMessage(new protos.google.showcase.v1beta1.Blurb()), - generateSampleMessage(new protos.google.showcase.v1beta1.Blurb()), - ]; - client.innerApiCalls.listBlurbs = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listBlurbs( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IBlurb[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listBlurbs as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listBlurbs as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listBlurbs with error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListBlurbsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.ListBlurbsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listBlurbs = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listBlurbs(request), expectedError); - const actualRequest = (client.innerApiCalls.listBlurbs as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listBlurbs as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listBlurbsStream without error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListBlurbsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.ListBlurbsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.showcase.v1beta1.Blurb()), - generateSampleMessage(new protos.google.showcase.v1beta1.Blurb()), - generateSampleMessage(new protos.google.showcase.v1beta1.Blurb()), - ]; - client.descriptors.page.listBlurbs.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listBlurbsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.showcase.v1beta1.Blurb[] = []; - stream.on('data', (response: protos.google.showcase.v1beta1.Blurb) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.listBlurbs.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listBlurbs, request)); - assert( - (client.descriptors.page.listBlurbs.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listBlurbs with error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListBlurbsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.ListBlurbsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listBlurbs = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listBlurbs(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listBlurbs as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listBlurbs as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listBlurbsStream with error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListBlurbsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.ListBlurbsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listBlurbs.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listBlurbsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.showcase.v1beta1.Blurb[] = []; - stream.on('data', (response: protos.google.showcase.v1beta1.Blurb) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listBlurbs.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listBlurbs, request)); - assert( - (client.descriptors.page.listBlurbs.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listBlurbsStream without error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListBlurbsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.ListBlurbsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.showcase.v1beta1.Blurb()), + generateSampleMessage(new protos.google.showcase.v1beta1.Blurb()), + generateSampleMessage(new protos.google.showcase.v1beta1.Blurb()), + ]; + client.descriptors.page.listBlurbs.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listBlurbsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.showcase.v1beta1.Blurb[] = []; + stream.on('data', (response: protos.google.showcase.v1beta1.Blurb) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listBlurbs.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listBlurbs, request), + ); + assert( + (client.descriptors.page.listBlurbs.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('uses async iteration with listBlurbs without error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListBlurbsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.ListBlurbsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.showcase.v1beta1.Blurb()), - generateSampleMessage(new protos.google.showcase.v1beta1.Blurb()), - generateSampleMessage(new protos.google.showcase.v1beta1.Blurb()), - ]; - client.descriptors.page.listBlurbs.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.showcase.v1beta1.IBlurb[] = []; - const iterable = client.listBlurbsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listBlurbs.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listBlurbs.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listBlurbsStream with error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListBlurbsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.ListBlurbsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listBlurbs.createStream = stubPageStreamingCall( + undefined, + expectedError, + ); + const stream = client.listBlurbsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.showcase.v1beta1.Blurb[] = []; + stream.on('data', (response: protos.google.showcase.v1beta1.Blurb) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listBlurbs.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listBlurbs, request), + ); + assert( + (client.descriptors.page.listBlurbs.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('uses async iteration with listBlurbs with error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListBlurbsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.ListBlurbsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listBlurbs.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listBlurbsAsync(request); - await assert.rejects(async () => { - const responses: protos.google.showcase.v1beta1.IBlurb[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listBlurbs.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listBlurbs.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listBlurbs without error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListBlurbsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.ListBlurbsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.showcase.v1beta1.Blurb()), + generateSampleMessage(new protos.google.showcase.v1beta1.Blurb()), + generateSampleMessage(new protos.google.showcase.v1beta1.Blurb()), + ]; + client.descriptors.page.listBlurbs.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.showcase.v1beta1.IBlurb[] = []; + const iterable = client.listBlurbsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + (client.descriptors.page.listBlurbs.asyncIterate as SinonStub).getCall( + 0, + ).args[1], + request, + ); + assert( + (client.descriptors.page.listBlurbs.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); }); - describe('Path templates', () => { - - describe('blueprint', () => { - const fakePath = "/rendered/path/blueprint"; - const expectedParameters = { - session: "sessionValue", - test: "testValue", - blueprint: "blueprintValue", - }; - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.blueprintPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.blueprintPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('blueprintPath', () => { - const result = client.blueprintPath("sessionValue", "testValue", "blueprintValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.blueprintPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchSessionFromBlueprintName', () => { - const result = client.matchSessionFromBlueprintName(fakePath); - assert.strictEqual(result, "sessionValue"); - assert((client.pathTemplates.blueprintPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchTestFromBlueprintName', () => { - const result = client.matchTestFromBlueprintName(fakePath); - assert.strictEqual(result, "testValue"); - assert((client.pathTemplates.blueprintPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBlueprintFromBlueprintName', () => { - const result = client.matchBlueprintFromBlueprintName(fakePath); - assert.strictEqual(result, "blueprintValue"); - assert((client.pathTemplates.blueprintPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('uses async iteration with listBlurbs with error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListBlurbsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.ListBlurbsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listBlurbs.asyncIterate = stubAsyncIterationCall( + undefined, + expectedError, + ); + const iterable = client.listBlurbsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.showcase.v1beta1.IBlurb[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + (client.descriptors.page.listBlurbs.asyncIterate as SinonStub).getCall( + 0, + ).args[1], + request, + ); + assert( + (client.descriptors.page.listBlurbs.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + }); + + describe('Path templates', () => { + describe('blueprint', () => { + const fakePath = '/rendered/path/blueprint'; + const expectedParameters = { + session: 'sessionValue', + test: 'testValue', + blueprint: 'blueprintValue', + }; + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.blueprintPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.blueprintPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('blueprintPath', () => { + const result = client.blueprintPath( + 'sessionValue', + 'testValue', + 'blueprintValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.blueprintPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchSessionFromBlueprintName', () => { + const result = client.matchSessionFromBlueprintName(fakePath); + assert.strictEqual(result, 'sessionValue'); + assert( + (client.pathTemplates.blueprintPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchTestFromBlueprintName', () => { + const result = client.matchTestFromBlueprintName(fakePath); + assert.strictEqual(result, 'testValue'); + assert( + (client.pathTemplates.blueprintPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBlueprintFromBlueprintName', () => { + const result = client.matchBlueprintFromBlueprintName(fakePath); + assert.strictEqual(result, 'blueprintValue'); + assert( + (client.pathTemplates.blueprintPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('room', () => { - const fakePath = "/rendered/path/room"; - const expectedParameters = { - room: "roomValue", - }; - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.roomPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.roomPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('roomPath', () => { - const result = client.roomPath("roomValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.roomPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchRoomFromRoomName', () => { - const result = client.matchRoomFromRoomName(fakePath); - assert.strictEqual(result, "roomValue"); - assert((client.pathTemplates.roomPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('room', () => { + const fakePath = '/rendered/path/room'; + const expectedParameters = { + room: 'roomValue', + }; + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.roomPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.roomPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('roomPath', () => { + const result = client.roomPath('roomValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.roomPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchRoomFromRoomName', () => { + const result = client.matchRoomFromRoomName(fakePath); + assert.strictEqual(result, 'roomValue'); + assert( + (client.pathTemplates.roomPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('roomBlurb', () => { - const fakePath = "/rendered/path/roomBlurb"; - const expectedParameters = { - room: "roomValue", - blurb: "blurbValue", - }; - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.roomBlurbPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.roomBlurbPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('roomBlurbPath', () => { - const result = client.roomBlurbPath("roomValue", "blurbValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.roomBlurbPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchRoomFromRoomBlurbName', () => { - const result = client.matchRoomFromRoomBlurbName(fakePath); - assert.strictEqual(result, "roomValue"); - assert((client.pathTemplates.roomBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBlurbFromRoomBlurbName', () => { - const result = client.matchBlurbFromRoomBlurbName(fakePath); - assert.strictEqual(result, "blurbValue"); - assert((client.pathTemplates.roomBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('roomBlurb', () => { + const fakePath = '/rendered/path/roomBlurb'; + const expectedParameters = { + room: 'roomValue', + blurb: 'blurbValue', + }; + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.roomBlurbPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.roomBlurbPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('roomBlurbPath', () => { + const result = client.roomBlurbPath('roomValue', 'blurbValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.roomBlurbPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchRoomFromRoomBlurbName', () => { + const result = client.matchRoomFromRoomBlurbName(fakePath); + assert.strictEqual(result, 'roomValue'); + assert( + (client.pathTemplates.roomBlurbPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBlurbFromRoomBlurbName', () => { + const result = client.matchBlurbFromRoomBlurbName(fakePath); + assert.strictEqual(result, 'blurbValue'); + assert( + (client.pathTemplates.roomBlurbPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('roomBlurbsLegacyRoomBlurb', () => { - const fakePath = "/rendered/path/roomBlurbsLegacyRoomBlurb"; - const expectedParameters = { - room: "roomValue", - legacy_room: "legacyRoomValue", - blurb: "blurbValue", - }; - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('roomBlurbsLegacyRoomBlurbPath', () => { - const result = client.roomBlurbsLegacyRoomBlurbPath("roomValue", "legacyRoomValue", "blurbValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchRoomFromRoomBlurbsLegacyRoomBlurbName', () => { - const result = client.matchRoomFromRoomBlurbsLegacyRoomBlurbName(fakePath); - assert.strictEqual(result, "roomValue"); - assert((client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName', () => { - const result = client.matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName(fakePath); - assert.strictEqual(result, "legacyRoomValue"); - assert((client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBlurbFromRoomBlurbsLegacyRoomBlurbName', () => { - const result = client.matchBlurbFromRoomBlurbsLegacyRoomBlurbName(fakePath); - assert.strictEqual(result, "blurbValue"); - assert((client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('roomBlurbsLegacyRoomBlurb', () => { + const fakePath = '/rendered/path/roomBlurbsLegacyRoomBlurb'; + const expectedParameters = { + room: 'roomValue', + legacy_room: 'legacyRoomValue', + blurb: 'blurbValue', + }; + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('roomBlurbsLegacyRoomBlurbPath', () => { + const result = client.roomBlurbsLegacyRoomBlurbPath( + 'roomValue', + 'legacyRoomValue', + 'blurbValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchRoomFromRoomBlurbsLegacyRoomBlurbName', () => { + const result = + client.matchRoomFromRoomBlurbsLegacyRoomBlurbName(fakePath); + assert.strictEqual(result, 'roomValue'); + assert( + ( + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName', () => { + const result = + client.matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName(fakePath); + assert.strictEqual(result, 'legacyRoomValue'); + assert( + ( + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBlurbFromRoomBlurbsLegacyRoomBlurbName', () => { + const result = + client.matchBlurbFromRoomBlurbsLegacyRoomBlurbName(fakePath); + assert.strictEqual(result, 'blurbValue'); + assert( + ( + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('sequence', () => { - const fakePath = "/rendered/path/sequence"; - const expectedParameters = { - sequence: "sequenceValue", - }; - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.sequencePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.sequencePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('sequencePath', () => { - const result = client.sequencePath("sequenceValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.sequencePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchSequenceFromSequenceName', () => { - const result = client.matchSequenceFromSequenceName(fakePath); - assert.strictEqual(result, "sequenceValue"); - assert((client.pathTemplates.sequencePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('sequence', () => { + const fakePath = '/rendered/path/sequence'; + const expectedParameters = { + sequence: 'sequenceValue', + }; + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.sequencePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.sequencePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('sequencePath', () => { + const result = client.sequencePath('sequenceValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.sequencePathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchSequenceFromSequenceName', () => { + const result = client.matchSequenceFromSequenceName(fakePath); + assert.strictEqual(result, 'sequenceValue'); + assert( + (client.pathTemplates.sequencePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('sequenceReport', () => { - const fakePath = "/rendered/path/sequenceReport"; - const expectedParameters = { - sequence: "sequenceValue", - }; - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.sequenceReportPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.sequenceReportPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('sequenceReportPath', () => { - const result = client.sequenceReportPath("sequenceValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.sequenceReportPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchSequenceFromSequenceReportName', () => { - const result = client.matchSequenceFromSequenceReportName(fakePath); - assert.strictEqual(result, "sequenceValue"); - assert((client.pathTemplates.sequenceReportPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('sequenceReport', () => { + const fakePath = '/rendered/path/sequenceReport'; + const expectedParameters = { + sequence: 'sequenceValue', + }; + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.sequenceReportPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.sequenceReportPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('sequenceReportPath', () => { + const result = client.sequenceReportPath('sequenceValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.sequenceReportPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchSequenceFromSequenceReportName', () => { + const result = client.matchSequenceFromSequenceReportName(fakePath); + assert.strictEqual(result, 'sequenceValue'); + assert( + (client.pathTemplates.sequenceReportPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('session', () => { - const fakePath = "/rendered/path/session"; - const expectedParameters = { - session: "sessionValue", - }; - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.sessionPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.sessionPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('sessionPath', () => { - const result = client.sessionPath("sessionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.sessionPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchSessionFromSessionName', () => { - const result = client.matchSessionFromSessionName(fakePath); - assert.strictEqual(result, "sessionValue"); - assert((client.pathTemplates.sessionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('session', () => { + const fakePath = '/rendered/path/session'; + const expectedParameters = { + session: 'sessionValue', + }; + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.sessionPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.sessionPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('sessionPath', () => { + const result = client.sessionPath('sessionValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.sessionPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchSessionFromSessionName', () => { + const result = client.matchSessionFromSessionName(fakePath); + assert.strictEqual(result, 'sessionValue'); + assert( + (client.pathTemplates.sessionPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('test', () => { - const fakePath = "/rendered/path/test"; - const expectedParameters = { - session: "sessionValue", - test: "testValue", - }; - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.testPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.testPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('testPath', () => { - const result = client.testPath("sessionValue", "testValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.testPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchSessionFromTestName', () => { - const result = client.matchSessionFromTestName(fakePath); - assert.strictEqual(result, "sessionValue"); - assert((client.pathTemplates.testPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchTestFromTestName', () => { - const result = client.matchTestFromTestName(fakePath); - assert.strictEqual(result, "testValue"); - assert((client.pathTemplates.testPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('test', () => { + const fakePath = '/rendered/path/test'; + const expectedParameters = { + session: 'sessionValue', + test: 'testValue', + }; + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.testPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.testPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('testPath', () => { + const result = client.testPath('sessionValue', 'testValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.testPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchSessionFromTestName', () => { + const result = client.matchSessionFromTestName(fakePath); + assert.strictEqual(result, 'sessionValue'); + assert( + (client.pathTemplates.testPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchTestFromTestName', () => { + const result = client.matchTestFromTestName(fakePath); + assert.strictEqual(result, 'testValue'); + assert( + (client.pathTemplates.testPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('user', () => { - const fakePath = "/rendered/path/user"; - const expectedParameters = { - user: "userValue", - }; - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.userPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.userPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('userPath', () => { - const result = client.userPath("userValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.userPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchUserFromUserName', () => { - const result = client.matchUserFromUserName(fakePath); - assert.strictEqual(result, "userValue"); - assert((client.pathTemplates.userPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('user', () => { + const fakePath = '/rendered/path/user'; + const expectedParameters = { + user: 'userValue', + }; + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.userPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.userPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('userPath', () => { + const result = client.userPath('userValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.userPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchUserFromUserName', () => { + const result = client.matchUserFromUserName(fakePath); + assert.strictEqual(result, 'userValue'); + assert( + (client.pathTemplates.userPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('userProfileBlurb', () => { - const fakePath = "/rendered/path/userProfileBlurb"; - const expectedParameters = { - user: "userValue", - blurb: "blurbValue", - }; - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.userProfileBlurbPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.userProfileBlurbPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('userProfileBlurbPath', () => { - const result = client.userProfileBlurbPath("userValue", "blurbValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.userProfileBlurbPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchUserFromUserProfileBlurbName', () => { - const result = client.matchUserFromUserProfileBlurbName(fakePath); - assert.strictEqual(result, "userValue"); - assert((client.pathTemplates.userProfileBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBlurbFromUserProfileBlurbName', () => { - const result = client.matchBlurbFromUserProfileBlurbName(fakePath); - assert.strictEqual(result, "blurbValue"); - assert((client.pathTemplates.userProfileBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('userProfileBlurb', () => { + const fakePath = '/rendered/path/userProfileBlurb'; + const expectedParameters = { + user: 'userValue', + blurb: 'blurbValue', + }; + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.userProfileBlurbPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.userProfileBlurbPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('userProfileBlurbPath', () => { + const result = client.userProfileBlurbPath('userValue', 'blurbValue'); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.userProfileBlurbPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchUserFromUserProfileBlurbName', () => { + const result = client.matchUserFromUserProfileBlurbName(fakePath); + assert.strictEqual(result, 'userValue'); + assert( + (client.pathTemplates.userProfileBlurbPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBlurbFromUserProfileBlurbName', () => { + const result = client.matchBlurbFromUserProfileBlurbName(fakePath); + assert.strictEqual(result, 'blurbValue'); + assert( + (client.pathTemplates.userProfileBlurbPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('userProfileBlurbsLegacyUserBlurb', () => { - const fakePath = "/rendered/path/userProfileBlurbsLegacyUserBlurb"; - const expectedParameters = { - user: "userValue", - legacy_user: "legacyUserValue", - blurb: "blurbValue", - }; - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('userProfileBlurbsLegacyUserBlurbPath', () => { - const result = client.userProfileBlurbsLegacyUserBlurbPath("userValue", "legacyUserValue", "blurbValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchUserFromUserProfileBlurbsLegacyUserBlurbName', () => { - const result = client.matchUserFromUserProfileBlurbsLegacyUserBlurbName(fakePath); - assert.strictEqual(result, "userValue"); - assert((client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName', () => { - const result = client.matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName(fakePath); - assert.strictEqual(result, "legacyUserValue"); - assert((client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBlurbFromUserProfileBlurbsLegacyUserBlurbName', () => { - const result = client.matchBlurbFromUserProfileBlurbsLegacyUserBlurbName(fakePath); - assert.strictEqual(result, "blurbValue"); - assert((client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('userProfileBlurbsLegacyUserBlurb', () => { + const fakePath = '/rendered/path/userProfileBlurbsLegacyUserBlurb'; + const expectedParameters = { + user: 'userValue', + legacy_user: 'legacyUserValue', + blurb: 'blurbValue', + }; + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('userProfileBlurbsLegacyUserBlurbPath', () => { + const result = client.userProfileBlurbsLegacyUserBlurbPath( + 'userValue', + 'legacyUserValue', + 'blurbValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchUserFromUserProfileBlurbsLegacyUserBlurbName', () => { + const result = + client.matchUserFromUserProfileBlurbsLegacyUserBlurbName(fakePath); + assert.strictEqual(result, 'userValue'); + assert( + ( + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName', () => { + const result = + client.matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName( + fakePath, + ); + assert.strictEqual(result, 'legacyUserValue'); + assert( + ( + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBlurbFromUserProfileBlurbsLegacyUserBlurbName', () => { + const result = + client.matchBlurbFromUserProfileBlurbsLegacyUserBlurbName(fakePath); + assert.strictEqual(result, 'blurbValue'); + assert( + ( + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/core/generator/gapic-generator-typescript/baselines/showcase-esm/esm/test/gapic_sequence_service_v1beta1.ts.baseline b/core/generator/gapic-generator-typescript/baselines/showcase-esm/esm/test/gapic_sequence_service_v1beta1.ts.baseline index 6ad653d66ad9..5546d302702c 100644 --- a/core/generator/gapic-generator-typescript/baselines/showcase-esm/esm/test/gapic_sequence_service_v1beta1.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/showcase-esm/esm/test/gapic_sequence_service_v1beta1.ts.baseline @@ -20,14 +20,14 @@ import * as protos from '../../protos/protos.js'; import assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as sequenceserviceModule from '../src/index.js'; -import {protobuf} from 'google-gax'; +import { protobuf } from 'google-gax'; import fs from 'fs'; import path from 'path'; -import {fileURLToPath} from 'url'; +import { fileURLToPath } from 'url'; // @ts-ignore const dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -35,844 +35,1121 @@ const dirname = path.dirname(fileURLToPath(import.meta.url)); // to fill in default values for request objects const root = protobuf.Root.fromJSON( JSON.parse( - fs.readFileSync(path.join(dirname, '..', '..', 'protos/protos.json'), 'utf8') - )) + fs.readFileSync( + path.join(dirname, '..', '..', 'protos/protos.json'), + 'utf8', + ), + ), +); // eslint-disable-next-line @typescript-eslint/no-unused-vars function getTypeDefaultValue(typeName: string, fields: string[]) { - let type = root.lookupType(typeName) as protobuf.Type; - for (const field of fields.slice(0, -1)) { - type = type?.fields[field]?.resolvedType as protobuf.Type; - } - return type?.fields[fields[fields.length - 1]]?.defaultValue ?? null; + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type?.fields[field]?.resolvedType as protobuf.Type; + } + return type?.fields[fields[fields.length - 1]]?.defaultValue ?? null; } function generateSampleMessage(instance: T) { - const filledObject = (instance.constructor as typeof protobuf.Message) - .toObject(instance as protobuf.Message, {defaults: true}); - return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, { defaults: true }); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; } function stubSimpleCall(response?: ResponseType, error?: Error) { - return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); } -function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { - return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +function stubSimpleCallWithCallback( + response?: ResponseType, + error?: Error, +) { + return error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); } describe('v1beta1.SequenceServiceClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'localhost'); - }); - - it('has universeDomain', () => { - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); - - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - it('throws DeprecationWarning if static servicePath is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const servicePath = sequenceserviceModule.v1beta1.SequenceServiceClient.servicePath; - assert.strictEqual(servicePath, 'localhost'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = sequenceserviceModule.v1beta1.SequenceServiceClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'localhost'); - assert(stub.called); - stub.restore(); - }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { new sequenceserviceModule.v1beta1.SequenceServiceClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); - - it('has port', () => { - const port = sequenceserviceModule.v1beta1.SequenceServiceClient.port; - assert(port); - assert(typeof port === 'number'); - }); - - it('should create a client with no option', () => { - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient(); - assert(client); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'localhost'); + }); - it('should create a client with gRPC fallback', () => { - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ - fallback: true, - }); - assert(client); - }); + it('has universeDomain', () => { + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - it('has initialize method and supports deferred initialization', async () => { - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.sequenceServiceStub, undefined); - await client.initialize(); - assert(client.sequenceServiceStub); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = + sequenceserviceModule.v1beta1.SequenceServiceClient.servicePath; + assert.strictEqual(servicePath, 'localhost'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + sequenceserviceModule.v1beta1.SequenceServiceClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'localhost'); + assert(stub.called); + stub.restore(); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new sequenceserviceModule.v1beta1.SequenceServiceClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); + }); - it('has close method for the initialized client', done => { - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.sequenceServiceStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('has port', () => { + const port = sequenceserviceModule.v1beta1.SequenceServiceClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('has close method for the non-initialized client', done => { - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.sequenceServiceStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('should create a client with no option', () => { + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient(); + assert(client); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); - }); + it('should create a client with gRPC fallback', () => { + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ + fallback: true, + }); + assert(client); + }); - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId((err?: Error|null, projectId?: string|null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } - }); - }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); - }); + it('has initialize method and supports deferred initialization', async () => { + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.sequenceServiceStub, undefined); + await client.initialize(); + assert(client.sequenceServiceStub); }); - describe('createSequence', () => { - it('invokes createSequence without error', async () => { - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.CreateSequenceRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.Sequence() - ); - client.innerApiCalls.createSequence = stubSimpleCall(expectedResponse); - const [response] = await client.createSequence(request); - assert.deepStrictEqual(response, expectedResponse); + it('has close method for the initialized client', (done) => { + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.sequenceServiceStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes createSequence without error using callback', async () => { - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.CreateSequenceRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.Sequence() - ); - client.innerApiCalls.createSequence = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createSequence( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.ISequence|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); + it('has close method for the non-initialized client', (done) => { + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.sequenceServiceStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes createSequence with error', async () => { - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.CreateSequenceRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.createSequence = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createSequence(request), expectedError); - }); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + }); - it('invokes createSequence with closed client', async () => { - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.CreateSequenceRequest() - ); - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createSequence(request), expectedError); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + }); + + describe('createSequence', () => { + it('invokes createSequence without error', async () => { + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.CreateSequenceRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.Sequence(), + ); + client.innerApiCalls.createSequence = stubSimpleCall(expectedResponse); + const [response] = await client.createSequence(request); + assert.deepStrictEqual(response, expectedResponse); }); - describe('getSequenceReport', () => { - it('invokes getSequenceReport without error', async () => { - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.GetSequenceReportRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.GetSequenceReportRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.SequenceReport() - ); - client.innerApiCalls.getSequenceReport = stubSimpleCall(expectedResponse); - const [response] = await client.getSequenceReport(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getSequenceReport as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getSequenceReport as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createSequence without error using callback', async () => { + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.CreateSequenceRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.Sequence(), + ); + client.innerApiCalls.createSequence = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createSequence( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.ISequence | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes getSequenceReport without error using callback', async () => { - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.GetSequenceReportRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.GetSequenceReportRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.SequenceReport() - ); - client.innerApiCalls.getSequenceReport = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getSequenceReport( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.ISequenceReport|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getSequenceReport as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getSequenceReport as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createSequence with error', async () => { + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.CreateSequenceRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.createSequence = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.createSequence(request), expectedError); + }); - it('invokes getSequenceReport with error', async () => { - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.GetSequenceReportRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.GetSequenceReportRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getSequenceReport = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getSequenceReport(request), expectedError); - const actualRequest = (client.innerApiCalls.getSequenceReport as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getSequenceReport as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createSequence with closed client', async () => { + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.CreateSequenceRequest(), + ); + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.createSequence(request), expectedError); + }); + }); + + describe('getSequenceReport', () => { + it('invokes getSequenceReport without error', async () => { + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.GetSequenceReportRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.GetSequenceReportRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.SequenceReport(), + ); + client.innerApiCalls.getSequenceReport = stubSimpleCall(expectedResponse); + const [response] = await client.getSequenceReport(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getSequenceReport as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getSequenceReport as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getSequenceReport with closed client', async () => { - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.GetSequenceReportRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.GetSequenceReportRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getSequenceReport(request), expectedError); - }); + it('invokes getSequenceReport without error using callback', async () => { + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.GetSequenceReportRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.GetSequenceReportRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.SequenceReport(), + ); + client.innerApiCalls.getSequenceReport = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getSequenceReport( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.ISequenceReport | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getSequenceReport as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getSequenceReport as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('attemptSequence', () => { - it('invokes attemptSequence without error', async () => { - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.AttemptSequenceRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.AttemptSequenceRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.attemptSequence = stubSimpleCall(expectedResponse); - const [response] = await client.attemptSequence(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.attemptSequence as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.attemptSequence as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getSequenceReport with error', async () => { + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.GetSequenceReportRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.GetSequenceReportRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getSequenceReport = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getSequenceReport(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getSequenceReport as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getSequenceReport as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes attemptSequence without error using callback', async () => { - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.AttemptSequenceRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.AttemptSequenceRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.attemptSequence = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.attemptSequence( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.attemptSequence as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.attemptSequence as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getSequenceReport with closed client', async () => { + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.GetSequenceReportRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.GetSequenceReportRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getSequenceReport(request), expectedError); + }); + }); + + describe('attemptSequence', () => { + it('invokes attemptSequence without error', async () => { + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.AttemptSequenceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.AttemptSequenceRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.attemptSequence = stubSimpleCall(expectedResponse); + const [response] = await client.attemptSequence(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.attemptSequence as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.attemptSequence as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes attemptSequence with error', async () => { - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.AttemptSequenceRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.AttemptSequenceRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.attemptSequence = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.attemptSequence(request), expectedError); - const actualRequest = (client.innerApiCalls.attemptSequence as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.attemptSequence as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes attemptSequence without error using callback', async () => { + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.AttemptSequenceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.AttemptSequenceRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.attemptSequence = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.attemptSequence( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.attemptSequence as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.attemptSequence as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes attemptSequence with closed client', async () => { - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.AttemptSequenceRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.AttemptSequenceRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.attemptSequence(request), expectedError); - }); + it('invokes attemptSequence with error', async () => { + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.AttemptSequenceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.AttemptSequenceRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.attemptSequence = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.attemptSequence(request), expectedError); + const actualRequest = ( + client.innerApiCalls.attemptSequence as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.attemptSequence as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('Path templates', () => { - - describe('blueprint', () => { - const fakePath = "/rendered/path/blueprint"; - const expectedParameters = { - session: "sessionValue", - test: "testValue", - blueprint: "blueprintValue", - }; - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.blueprintPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.blueprintPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('blueprintPath', () => { - const result = client.blueprintPath("sessionValue", "testValue", "blueprintValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.blueprintPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchSessionFromBlueprintName', () => { - const result = client.matchSessionFromBlueprintName(fakePath); - assert.strictEqual(result, "sessionValue"); - assert((client.pathTemplates.blueprintPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchTestFromBlueprintName', () => { - const result = client.matchTestFromBlueprintName(fakePath); - assert.strictEqual(result, "testValue"); - assert((client.pathTemplates.blueprintPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBlueprintFromBlueprintName', () => { - const result = client.matchBlueprintFromBlueprintName(fakePath); - assert.strictEqual(result, "blueprintValue"); - assert((client.pathTemplates.blueprintPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('invokes attemptSequence with closed client', async () => { + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.AttemptSequenceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.AttemptSequenceRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.attemptSequence(request), expectedError); + }); + }); + + describe('Path templates', () => { + describe('blueprint', () => { + const fakePath = '/rendered/path/blueprint'; + const expectedParameters = { + session: 'sessionValue', + test: 'testValue', + blueprint: 'blueprintValue', + }; + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.blueprintPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.blueprintPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('blueprintPath', () => { + const result = client.blueprintPath( + 'sessionValue', + 'testValue', + 'blueprintValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.blueprintPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchSessionFromBlueprintName', () => { + const result = client.matchSessionFromBlueprintName(fakePath); + assert.strictEqual(result, 'sessionValue'); + assert( + (client.pathTemplates.blueprintPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchTestFromBlueprintName', () => { + const result = client.matchTestFromBlueprintName(fakePath); + assert.strictEqual(result, 'testValue'); + assert( + (client.pathTemplates.blueprintPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBlueprintFromBlueprintName', () => { + const result = client.matchBlueprintFromBlueprintName(fakePath); + assert.strictEqual(result, 'blueprintValue'); + assert( + (client.pathTemplates.blueprintPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('room', () => { - const fakePath = "/rendered/path/room"; - const expectedParameters = { - room: "roomValue", - }; - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.roomPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.roomPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('roomPath', () => { - const result = client.roomPath("roomValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.roomPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchRoomFromRoomName', () => { - const result = client.matchRoomFromRoomName(fakePath); - assert.strictEqual(result, "roomValue"); - assert((client.pathTemplates.roomPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('room', () => { + const fakePath = '/rendered/path/room'; + const expectedParameters = { + room: 'roomValue', + }; + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.roomPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.roomPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('roomPath', () => { + const result = client.roomPath('roomValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.roomPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchRoomFromRoomName', () => { + const result = client.matchRoomFromRoomName(fakePath); + assert.strictEqual(result, 'roomValue'); + assert( + (client.pathTemplates.roomPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('roomBlurb', () => { - const fakePath = "/rendered/path/roomBlurb"; - const expectedParameters = { - room: "roomValue", - blurb: "blurbValue", - }; - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.roomBlurbPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.roomBlurbPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('roomBlurbPath', () => { - const result = client.roomBlurbPath("roomValue", "blurbValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.roomBlurbPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchRoomFromRoomBlurbName', () => { - const result = client.matchRoomFromRoomBlurbName(fakePath); - assert.strictEqual(result, "roomValue"); - assert((client.pathTemplates.roomBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBlurbFromRoomBlurbName', () => { - const result = client.matchBlurbFromRoomBlurbName(fakePath); - assert.strictEqual(result, "blurbValue"); - assert((client.pathTemplates.roomBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('roomBlurb', () => { + const fakePath = '/rendered/path/roomBlurb'; + const expectedParameters = { + room: 'roomValue', + blurb: 'blurbValue', + }; + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.roomBlurbPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.roomBlurbPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('roomBlurbPath', () => { + const result = client.roomBlurbPath('roomValue', 'blurbValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.roomBlurbPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchRoomFromRoomBlurbName', () => { + const result = client.matchRoomFromRoomBlurbName(fakePath); + assert.strictEqual(result, 'roomValue'); + assert( + (client.pathTemplates.roomBlurbPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBlurbFromRoomBlurbName', () => { + const result = client.matchBlurbFromRoomBlurbName(fakePath); + assert.strictEqual(result, 'blurbValue'); + assert( + (client.pathTemplates.roomBlurbPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('roomBlurbsLegacyRoomBlurb', () => { - const fakePath = "/rendered/path/roomBlurbsLegacyRoomBlurb"; - const expectedParameters = { - room: "roomValue", - legacy_room: "legacyRoomValue", - blurb: "blurbValue", - }; - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('roomBlurbsLegacyRoomBlurbPath', () => { - const result = client.roomBlurbsLegacyRoomBlurbPath("roomValue", "legacyRoomValue", "blurbValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchRoomFromRoomBlurbsLegacyRoomBlurbName', () => { - const result = client.matchRoomFromRoomBlurbsLegacyRoomBlurbName(fakePath); - assert.strictEqual(result, "roomValue"); - assert((client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName', () => { - const result = client.matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName(fakePath); - assert.strictEqual(result, "legacyRoomValue"); - assert((client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBlurbFromRoomBlurbsLegacyRoomBlurbName', () => { - const result = client.matchBlurbFromRoomBlurbsLegacyRoomBlurbName(fakePath); - assert.strictEqual(result, "blurbValue"); - assert((client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('roomBlurbsLegacyRoomBlurb', () => { + const fakePath = '/rendered/path/roomBlurbsLegacyRoomBlurb'; + const expectedParameters = { + room: 'roomValue', + legacy_room: 'legacyRoomValue', + blurb: 'blurbValue', + }; + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('roomBlurbsLegacyRoomBlurbPath', () => { + const result = client.roomBlurbsLegacyRoomBlurbPath( + 'roomValue', + 'legacyRoomValue', + 'blurbValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchRoomFromRoomBlurbsLegacyRoomBlurbName', () => { + const result = + client.matchRoomFromRoomBlurbsLegacyRoomBlurbName(fakePath); + assert.strictEqual(result, 'roomValue'); + assert( + ( + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName', () => { + const result = + client.matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName(fakePath); + assert.strictEqual(result, 'legacyRoomValue'); + assert( + ( + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBlurbFromRoomBlurbsLegacyRoomBlurbName', () => { + const result = + client.matchBlurbFromRoomBlurbsLegacyRoomBlurbName(fakePath); + assert.strictEqual(result, 'blurbValue'); + assert( + ( + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('sequence', () => { - const fakePath = "/rendered/path/sequence"; - const expectedParameters = { - sequence: "sequenceValue", - }; - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.sequencePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.sequencePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('sequencePath', () => { - const result = client.sequencePath("sequenceValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.sequencePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchSequenceFromSequenceName', () => { - const result = client.matchSequenceFromSequenceName(fakePath); - assert.strictEqual(result, "sequenceValue"); - assert((client.pathTemplates.sequencePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('sequence', () => { + const fakePath = '/rendered/path/sequence'; + const expectedParameters = { + sequence: 'sequenceValue', + }; + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.sequencePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.sequencePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('sequencePath', () => { + const result = client.sequencePath('sequenceValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.sequencePathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchSequenceFromSequenceName', () => { + const result = client.matchSequenceFromSequenceName(fakePath); + assert.strictEqual(result, 'sequenceValue'); + assert( + (client.pathTemplates.sequencePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('sequenceReport', () => { - const fakePath = "/rendered/path/sequenceReport"; - const expectedParameters = { - sequence: "sequenceValue", - }; - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.sequenceReportPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.sequenceReportPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('sequenceReportPath', () => { - const result = client.sequenceReportPath("sequenceValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.sequenceReportPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchSequenceFromSequenceReportName', () => { - const result = client.matchSequenceFromSequenceReportName(fakePath); - assert.strictEqual(result, "sequenceValue"); - assert((client.pathTemplates.sequenceReportPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('sequenceReport', () => { + const fakePath = '/rendered/path/sequenceReport'; + const expectedParameters = { + sequence: 'sequenceValue', + }; + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.sequenceReportPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.sequenceReportPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('sequenceReportPath', () => { + const result = client.sequenceReportPath('sequenceValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.sequenceReportPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchSequenceFromSequenceReportName', () => { + const result = client.matchSequenceFromSequenceReportName(fakePath); + assert.strictEqual(result, 'sequenceValue'); + assert( + (client.pathTemplates.sequenceReportPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('session', () => { - const fakePath = "/rendered/path/session"; - const expectedParameters = { - session: "sessionValue", - }; - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.sessionPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.sessionPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('sessionPath', () => { - const result = client.sessionPath("sessionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.sessionPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchSessionFromSessionName', () => { - const result = client.matchSessionFromSessionName(fakePath); - assert.strictEqual(result, "sessionValue"); - assert((client.pathTemplates.sessionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('session', () => { + const fakePath = '/rendered/path/session'; + const expectedParameters = { + session: 'sessionValue', + }; + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.sessionPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.sessionPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('sessionPath', () => { + const result = client.sessionPath('sessionValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.sessionPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchSessionFromSessionName', () => { + const result = client.matchSessionFromSessionName(fakePath); + assert.strictEqual(result, 'sessionValue'); + assert( + (client.pathTemplates.sessionPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('test', () => { - const fakePath = "/rendered/path/test"; - const expectedParameters = { - session: "sessionValue", - test: "testValue", - }; - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.testPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.testPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('testPath', () => { - const result = client.testPath("sessionValue", "testValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.testPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchSessionFromTestName', () => { - const result = client.matchSessionFromTestName(fakePath); - assert.strictEqual(result, "sessionValue"); - assert((client.pathTemplates.testPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchTestFromTestName', () => { - const result = client.matchTestFromTestName(fakePath); - assert.strictEqual(result, "testValue"); - assert((client.pathTemplates.testPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('test', () => { + const fakePath = '/rendered/path/test'; + const expectedParameters = { + session: 'sessionValue', + test: 'testValue', + }; + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.testPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.testPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('testPath', () => { + const result = client.testPath('sessionValue', 'testValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.testPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchSessionFromTestName', () => { + const result = client.matchSessionFromTestName(fakePath); + assert.strictEqual(result, 'sessionValue'); + assert( + (client.pathTemplates.testPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchTestFromTestName', () => { + const result = client.matchTestFromTestName(fakePath); + assert.strictEqual(result, 'testValue'); + assert( + (client.pathTemplates.testPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('user', () => { - const fakePath = "/rendered/path/user"; - const expectedParameters = { - user: "userValue", - }; - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.userPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.userPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('userPath', () => { - const result = client.userPath("userValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.userPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchUserFromUserName', () => { - const result = client.matchUserFromUserName(fakePath); - assert.strictEqual(result, "userValue"); - assert((client.pathTemplates.userPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('user', () => { + const fakePath = '/rendered/path/user'; + const expectedParameters = { + user: 'userValue', + }; + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.userPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.userPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('userPath', () => { + const result = client.userPath('userValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.userPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchUserFromUserName', () => { + const result = client.matchUserFromUserName(fakePath); + assert.strictEqual(result, 'userValue'); + assert( + (client.pathTemplates.userPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('userProfileBlurb', () => { - const fakePath = "/rendered/path/userProfileBlurb"; - const expectedParameters = { - user: "userValue", - blurb: "blurbValue", - }; - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.userProfileBlurbPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.userProfileBlurbPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('userProfileBlurbPath', () => { - const result = client.userProfileBlurbPath("userValue", "blurbValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.userProfileBlurbPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchUserFromUserProfileBlurbName', () => { - const result = client.matchUserFromUserProfileBlurbName(fakePath); - assert.strictEqual(result, "userValue"); - assert((client.pathTemplates.userProfileBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBlurbFromUserProfileBlurbName', () => { - const result = client.matchBlurbFromUserProfileBlurbName(fakePath); - assert.strictEqual(result, "blurbValue"); - assert((client.pathTemplates.userProfileBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('userProfileBlurb', () => { + const fakePath = '/rendered/path/userProfileBlurb'; + const expectedParameters = { + user: 'userValue', + blurb: 'blurbValue', + }; + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.userProfileBlurbPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.userProfileBlurbPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('userProfileBlurbPath', () => { + const result = client.userProfileBlurbPath('userValue', 'blurbValue'); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.userProfileBlurbPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchUserFromUserProfileBlurbName', () => { + const result = client.matchUserFromUserProfileBlurbName(fakePath); + assert.strictEqual(result, 'userValue'); + assert( + (client.pathTemplates.userProfileBlurbPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBlurbFromUserProfileBlurbName', () => { + const result = client.matchBlurbFromUserProfileBlurbName(fakePath); + assert.strictEqual(result, 'blurbValue'); + assert( + (client.pathTemplates.userProfileBlurbPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('userProfileBlurbsLegacyUserBlurb', () => { - const fakePath = "/rendered/path/userProfileBlurbsLegacyUserBlurb"; - const expectedParameters = { - user: "userValue", - legacy_user: "legacyUserValue", - blurb: "blurbValue", - }; - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('userProfileBlurbsLegacyUserBlurbPath', () => { - const result = client.userProfileBlurbsLegacyUserBlurbPath("userValue", "legacyUserValue", "blurbValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchUserFromUserProfileBlurbsLegacyUserBlurbName', () => { - const result = client.matchUserFromUserProfileBlurbsLegacyUserBlurbName(fakePath); - assert.strictEqual(result, "userValue"); - assert((client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName', () => { - const result = client.matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName(fakePath); - assert.strictEqual(result, "legacyUserValue"); - assert((client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBlurbFromUserProfileBlurbsLegacyUserBlurbName', () => { - const result = client.matchBlurbFromUserProfileBlurbsLegacyUserBlurbName(fakePath); - assert.strictEqual(result, "blurbValue"); - assert((client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('userProfileBlurbsLegacyUserBlurb', () => { + const fakePath = '/rendered/path/userProfileBlurbsLegacyUserBlurb'; + const expectedParameters = { + user: 'userValue', + legacy_user: 'legacyUserValue', + blurb: 'blurbValue', + }; + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('userProfileBlurbsLegacyUserBlurbPath', () => { + const result = client.userProfileBlurbsLegacyUserBlurbPath( + 'userValue', + 'legacyUserValue', + 'blurbValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchUserFromUserProfileBlurbsLegacyUserBlurbName', () => { + const result = + client.matchUserFromUserProfileBlurbsLegacyUserBlurbName(fakePath); + assert.strictEqual(result, 'userValue'); + assert( + ( + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName', () => { + const result = + client.matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName( + fakePath, + ); + assert.strictEqual(result, 'legacyUserValue'); + assert( + ( + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBlurbFromUserProfileBlurbsLegacyUserBlurbName', () => { + const result = + client.matchBlurbFromUserProfileBlurbsLegacyUserBlurbName(fakePath); + assert.strictEqual(result, 'blurbValue'); + assert( + ( + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/core/generator/gapic-generator-typescript/baselines/showcase-esm/esm/test/gapic_testing_v1beta1.ts.baseline b/core/generator/gapic-generator-typescript/baselines/showcase-esm/esm/test/gapic_testing_v1beta1.ts.baseline index f19fcdb3cbb3..f0662335f974 100644 --- a/core/generator/gapic-generator-typescript/baselines/showcase-esm/esm/test/gapic_testing_v1beta1.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/showcase-esm/esm/test/gapic_testing_v1beta1.ts.baseline @@ -20,16 +20,16 @@ import * as protos from '../../protos/protos.js'; import assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as testingModule from '../src/index.js'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; -import {protobuf} from 'google-gax'; +import { protobuf } from 'google-gax'; import fs from 'fs'; import path from 'path'; -import {fileURLToPath} from 'url'; +import { fileURLToPath } from 'url'; // @ts-ignore const dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -37,1633 +37,2079 @@ const dirname = path.dirname(fileURLToPath(import.meta.url)); // to fill in default values for request objects const root = protobuf.Root.fromJSON( JSON.parse( - fs.readFileSync(path.join(dirname, '..', '..', 'protos/protos.json'), 'utf8') - )) + fs.readFileSync( + path.join(dirname, '..', '..', 'protos/protos.json'), + 'utf8', + ), + ), +); // eslint-disable-next-line @typescript-eslint/no-unused-vars function getTypeDefaultValue(typeName: string, fields: string[]) { - let type = root.lookupType(typeName) as protobuf.Type; - for (const field of fields.slice(0, -1)) { - type = type?.fields[field]?.resolvedType as protobuf.Type; - } - return type?.fields[fields[fields.length - 1]]?.defaultValue ?? null; + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type?.fields[field]?.resolvedType as protobuf.Type; + } + return type?.fields[fields[fields.length - 1]]?.defaultValue ?? null; } function generateSampleMessage(instance: T) { - const filledObject = (instance.constructor as typeof protobuf.Message) - .toObject(instance as protobuf.Message, {defaults: true}); - return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, { defaults: true }); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; } function stubSimpleCall(response?: ResponseType, error?: Error) { - return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); } -function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { - return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +function stubSimpleCallWithCallback( + response?: ResponseType, + error?: Error, +) { + return error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); } -function stubPageStreamingCall(responses?: ResponseType[], error?: Error) { - const pagingStub = sinon.stub(); - if (responses) { - for (let i = 0; i < responses.length; ++i) { - pagingStub.onCall(i).callsArgWith(2, null, responses[i]); - } +function stubPageStreamingCall( + responses?: ResponseType[], + error?: Error, +) { + const pagingStub = sinon.stub(); + if (responses) { + for (let i = 0; i < responses.length; ++i) { + pagingStub.onCall(i).callsArgWith(2, null, responses[i]); } - const transformStub = error ? sinon.stub().callsArgWith(2, error) : pagingStub; - const mockStream = new PassThrough({ - objectMode: true, - transform: transformStub, - }); - // trigger as many responses as needed - if (responses) { - for (let i = 0; i < responses.length; ++i) { - setImmediate(() => { mockStream.write({}); }); - } - setImmediate(() => { mockStream.end(); }); - } else { - setImmediate(() => { mockStream.write({}); }); - setImmediate(() => { mockStream.end(); }); + } + const transformStub = error + ? sinon.stub().callsArgWith(2, error) + : pagingStub; + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + // trigger as many responses as needed + if (responses) { + for (let i = 0; i < responses.length; ++i) { + setImmediate(() => { + mockStream.write({}); + }); } - return sinon.stub().returns(mockStream); + setImmediate(() => { + mockStream.end(); + }); + } else { + setImmediate(() => { + mockStream.write({}); + }); + setImmediate(() => { + mockStream.end(); + }); + } + return sinon.stub().returns(mockStream); } -function stubAsyncIterationCall(responses?: ResponseType[], error?: Error) { - let counter = 0; - const asyncIterable = { - [Symbol.asyncIterator]() { - return { - async next() { - if (error) { - return Promise.reject(error); - } - if (counter >= responses!.length) { - return Promise.resolve({done: true, value: undefined}); - } - return Promise.resolve({done: false, value: responses![counter++]}); - } - }; - } - }; - return sinon.stub().returns(asyncIterable); +function stubAsyncIterationCall( + responses?: ResponseType[], + error?: Error, +) { + let counter = 0; + const asyncIterable = { + [Symbol.asyncIterator]() { + return { + async next() { + if (error) { + return Promise.reject(error); + } + if (counter >= responses!.length) { + return Promise.resolve({ done: true, value: undefined }); + } + return Promise.resolve({ done: false, value: responses![counter++] }); + }, + }; + }, + }; + return sinon.stub().returns(asyncIterable); } describe('v1beta1.TestingClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new testingModule.v1beta1.TestingClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'localhost'); - }); - - it('has universeDomain', () => { - const client = new testingModule.v1beta1.TestingClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); - - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - it('throws DeprecationWarning if static servicePath is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const servicePath = testingModule.v1beta1.TestingClient.servicePath; - assert.strictEqual(servicePath, 'localhost'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = testingModule.v1beta1.TestingClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'localhost'); - assert(stub.called); - stub.restore(); - }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { new testingModule.v1beta1.TestingClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new testingModule.v1beta1.TestingClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'localhost'); + }); - it('has port', () => { - const port = testingModule.v1beta1.TestingClient.port; - assert(port); - assert(typeof port === 'number'); - }); + it('has universeDomain', () => { + const client = new testingModule.v1beta1.TestingClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - it('should create a client with no option', () => { - const client = new testingModule.v1beta1.TestingClient(); - assert(client); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = testingModule.v1beta1.TestingClient.servicePath; + assert.strictEqual(servicePath, 'localhost'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = testingModule.v1beta1.TestingClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'localhost'); + assert(stub.called); + stub.restore(); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new testingModule.v1beta1.TestingClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); + }); - it('should create a client with gRPC fallback', () => { - const client = new testingModule.v1beta1.TestingClient({ - fallback: true, - }); - assert(client); - }); + it('has port', () => { + const port = testingModule.v1beta1.TestingClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('has initialize method and supports deferred initialization', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.testingStub, undefined); - await client.initialize(); - assert(client.testingStub); - }); + it('should create a client with no option', () => { + const client = new testingModule.v1beta1.TestingClient(); + assert(client); + }); - it('has close method for the initialized client', done => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.testingStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('should create a client with gRPC fallback', () => { + const client = new testingModule.v1beta1.TestingClient({ + fallback: true, + }); + assert(client); + }); - it('has close method for the non-initialized client', done => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.testingStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('has initialize method and supports deferred initialization', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.testingStub, undefined); + await client.initialize(); + assert(client.testingStub); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + it('has close method for the initialized client', (done) => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.testingStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId((err?: Error|null, projectId?: string|null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } - }); - }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); + it('has close method for the non-initialized client', (done) => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.testingStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); }); - describe('createSession', () => { - it('invokes createSession without error', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.CreateSessionRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.Session() - ); - client.innerApiCalls.createSession = stubSimpleCall(expectedResponse); - const [response] = await client.createSession(request); - assert.deepStrictEqual(response, expectedResponse); - }); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + }); - it('invokes createSession without error using callback', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.CreateSessionRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.Session() - ); - client.innerApiCalls.createSession = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createSession( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.ISession|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + }); + + describe('createSession', () => { + it('invokes createSession without error', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.CreateSessionRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.Session(), + ); + client.innerApiCalls.createSession = stubSimpleCall(expectedResponse); + const [response] = await client.createSession(request); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes createSession with error', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.CreateSessionRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.createSession = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createSession(request), expectedError); - }); + it('invokes createSession without error using callback', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.CreateSessionRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.Session(), + ); + client.innerApiCalls.createSession = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createSession( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.ISession | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes createSession with closed client', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.CreateSessionRequest() - ); - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createSession(request), expectedError); - }); + it('invokes createSession with error', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.CreateSessionRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.createSession = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.createSession(request), expectedError); }); - describe('getSession', () => { - it('invokes getSession without error', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.GetSessionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.GetSessionRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.Session() - ); - client.innerApiCalls.getSession = stubSimpleCall(expectedResponse); - const [response] = await client.getSession(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getSession as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getSession as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createSession with closed client', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.CreateSessionRequest(), + ); + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.createSession(request), expectedError); + }); + }); + + describe('getSession', () => { + it('invokes getSession without error', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.GetSessionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.GetSessionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.Session(), + ); + client.innerApiCalls.getSession = stubSimpleCall(expectedResponse); + const [response] = await client.getSession(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getSession as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getSession as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getSession without error using callback', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.GetSessionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.GetSessionRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.Session() - ); - client.innerApiCalls.getSession = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getSession( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.ISession|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getSession as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getSession as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getSession without error using callback', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.GetSessionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.GetSessionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.Session(), + ); + client.innerApiCalls.getSession = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getSession( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.ISession | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getSession as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getSession as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getSession with error', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.GetSessionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.GetSessionRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getSession = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getSession(request), expectedError); - const actualRequest = (client.innerApiCalls.getSession as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getSession as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getSession with error', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.GetSessionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.GetSessionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getSession = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getSession(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getSession as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getSession as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getSession with closed client', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.GetSessionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.GetSessionRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getSession(request), expectedError); - }); + it('invokes getSession with closed client', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.GetSessionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.GetSessionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getSession(request), expectedError); + }); + }); + + describe('deleteSession', () => { + it('invokes deleteSession without error', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.DeleteSessionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.DeleteSessionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteSession = stubSimpleCall(expectedResponse); + const [response] = await client.deleteSession(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteSession as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteSession as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('deleteSession', () => { - it('invokes deleteSession without error', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.DeleteSessionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.DeleteSessionRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteSession = stubSimpleCall(expectedResponse); - const [response] = await client.deleteSession(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteSession as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteSession as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteSession without error using callback', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.DeleteSessionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.DeleteSessionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteSession = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteSession( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteSession as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteSession as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteSession without error using callback', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.DeleteSessionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.DeleteSessionRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteSession = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteSession( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteSession as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteSession as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteSession with error', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.DeleteSessionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.DeleteSessionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteSession = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.deleteSession(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteSession as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteSession as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteSession with error', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.DeleteSessionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.DeleteSessionRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteSession = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteSession(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteSession as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteSession as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteSession with closed client', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.DeleteSessionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.DeleteSessionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.deleteSession(request), expectedError); + }); + }); + + describe('reportSession', () => { + it('invokes reportSession without error', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ReportSessionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.ReportSessionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.ReportSessionResponse(), + ); + client.innerApiCalls.reportSession = stubSimpleCall(expectedResponse); + const [response] = await client.reportSession(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.reportSession as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.reportSession as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteSession with closed client', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.DeleteSessionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.DeleteSessionRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteSession(request), expectedError); - }); + it('invokes reportSession without error using callback', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ReportSessionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.ReportSessionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.ReportSessionResponse(), + ); + client.innerApiCalls.reportSession = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.reportSession( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IReportSessionResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.reportSession as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.reportSession as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('reportSession', () => { - it('invokes reportSession without error', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ReportSessionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.ReportSessionRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.ReportSessionResponse() - ); - client.innerApiCalls.reportSession = stubSimpleCall(expectedResponse); - const [response] = await client.reportSession(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.reportSession as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.reportSession as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes reportSession with error', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ReportSessionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.ReportSessionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.reportSession = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.reportSession(request), expectedError); + const actualRequest = ( + client.innerApiCalls.reportSession as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.reportSession as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes reportSession without error using callback', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ReportSessionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.ReportSessionRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.ReportSessionResponse() - ); - client.innerApiCalls.reportSession = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.reportSession( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IReportSessionResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.reportSession as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.reportSession as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes reportSession with closed client', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ReportSessionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.ReportSessionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.reportSession(request), expectedError); + }); + }); + + describe('deleteTest', () => { + it('invokes deleteTest without error', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.DeleteTestRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.DeleteTestRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteTest = stubSimpleCall(expectedResponse); + const [response] = await client.deleteTest(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteTest as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteTest as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes reportSession with error', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ReportSessionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.ReportSessionRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.reportSession = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.reportSession(request), expectedError); - const actualRequest = (client.innerApiCalls.reportSession as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.reportSession as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteTest without error using callback', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.DeleteTestRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.DeleteTestRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteTest = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteTest( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteTest as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteTest as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes reportSession with closed client', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ReportSessionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.ReportSessionRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.reportSession(request), expectedError); - }); + it('invokes deleteTest with error', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.DeleteTestRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.DeleteTestRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteTest = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.deleteTest(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteTest as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteTest as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('deleteTest', () => { - it('invokes deleteTest without error', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.DeleteTestRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.DeleteTestRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteTest = stubSimpleCall(expectedResponse); - const [response] = await client.deleteTest(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteTest as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteTest as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteTest with closed client', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.DeleteTestRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.DeleteTestRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.deleteTest(request), expectedError); + }); + }); + + describe('verifyTest', () => { + it('invokes verifyTest without error', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.VerifyTestRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.VerifyTestRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.VerifyTestResponse(), + ); + client.innerApiCalls.verifyTest = stubSimpleCall(expectedResponse); + const [response] = await client.verifyTest(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.verifyTest as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.verifyTest as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteTest without error using callback', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.DeleteTestRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.DeleteTestRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteTest = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteTest( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteTest as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteTest as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes verifyTest without error using callback', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.VerifyTestRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.VerifyTestRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.VerifyTestResponse(), + ); + client.innerApiCalls.verifyTest = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.verifyTest( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IVerifyTestResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.verifyTest as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.verifyTest as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteTest with error', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.DeleteTestRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.DeleteTestRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteTest = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteTest(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteTest as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteTest as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes verifyTest with error', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.VerifyTestRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.VerifyTestRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.verifyTest = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.verifyTest(request), expectedError); + const actualRequest = ( + client.innerApiCalls.verifyTest as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.verifyTest as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteTest with closed client', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.DeleteTestRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.DeleteTestRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteTest(request), expectedError); - }); + it('invokes verifyTest with closed client', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.VerifyTestRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.VerifyTestRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.verifyTest(request), expectedError); + }); + }); + + describe('listSessions', () => { + it('invokes listSessions without error', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListSessionsRequest(), + ); + const expectedResponse = [ + generateSampleMessage(new protos.google.showcase.v1beta1.Session()), + generateSampleMessage(new protos.google.showcase.v1beta1.Session()), + generateSampleMessage(new protos.google.showcase.v1beta1.Session()), + ]; + client.innerApiCalls.listSessions = stubSimpleCall(expectedResponse); + const [response] = await client.listSessions(request); + assert.deepStrictEqual(response, expectedResponse); }); - describe('verifyTest', () => { - it('invokes verifyTest without error', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.VerifyTestRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.VerifyTestRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.VerifyTestResponse() - ); - client.innerApiCalls.verifyTest = stubSimpleCall(expectedResponse); - const [response] = await client.verifyTest(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.verifyTest as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.verifyTest as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listSessions without error using callback', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListSessionsRequest(), + ); + const expectedResponse = [ + generateSampleMessage(new protos.google.showcase.v1beta1.Session()), + generateSampleMessage(new protos.google.showcase.v1beta1.Session()), + generateSampleMessage(new protos.google.showcase.v1beta1.Session()), + ]; + client.innerApiCalls.listSessions = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listSessions( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.ISession[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes verifyTest without error using callback', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.VerifyTestRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.VerifyTestRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.VerifyTestResponse() - ); - client.innerApiCalls.verifyTest = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.verifyTest( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IVerifyTestResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.verifyTest as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.verifyTest as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listSessions with error', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListSessionsRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.listSessions = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listSessions(request), expectedError); + }); - it('invokes verifyTest with error', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.VerifyTestRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.VerifyTestRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.verifyTest = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.verifyTest(request), expectedError); - const actualRequest = (client.innerApiCalls.verifyTest as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.verifyTest as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes listSessionsStream without error', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListSessionsRequest(), + ); + const expectedResponse = [ + generateSampleMessage(new protos.google.showcase.v1beta1.Session()), + generateSampleMessage(new protos.google.showcase.v1beta1.Session()), + generateSampleMessage(new protos.google.showcase.v1beta1.Session()), + ]; + client.descriptors.page.listSessions.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listSessionsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.showcase.v1beta1.Session[] = []; + stream.on( + 'data', + (response: protos.google.showcase.v1beta1.Session) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); }); - - it('invokes verifyTest with closed client', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.VerifyTestRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.VerifyTestRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.verifyTest(request), expectedError); + stream.on('error', (err: Error) => { + reject(err); }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listSessions.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listSessions, request), + ); }); - describe('listSessions', () => { - it('invokes listSessions without error', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListSessionsRequest() - );const expectedResponse = [ - generateSampleMessage(new protos.google.showcase.v1beta1.Session()), - generateSampleMessage(new protos.google.showcase.v1beta1.Session()), - generateSampleMessage(new protos.google.showcase.v1beta1.Session()), - ]; - client.innerApiCalls.listSessions = stubSimpleCall(expectedResponse); - const [response] = await client.listSessions(request); - assert.deepStrictEqual(response, expectedResponse); - }); - - it('invokes listSessions without error using callback', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListSessionsRequest() - );const expectedResponse = [ - generateSampleMessage(new protos.google.showcase.v1beta1.Session()), - generateSampleMessage(new protos.google.showcase.v1beta1.Session()), - generateSampleMessage(new protos.google.showcase.v1beta1.Session()), - ]; - client.innerApiCalls.listSessions = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listSessions( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.ISession[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); + it('invokes listSessionsStream with error', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListSessionsRequest(), + ); + const expectedError = new Error('expected'); + client.descriptors.page.listSessions.createStream = stubPageStreamingCall( + undefined, + expectedError, + ); + const stream = client.listSessionsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.showcase.v1beta1.Session[] = []; + stream.on( + 'data', + (response: protos.google.showcase.v1beta1.Session) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); }); - - it('invokes listSessions with error', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListSessionsRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.listSessions = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listSessions(request), expectedError); + stream.on('error', (err: Error) => { + reject(err); }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listSessions.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listSessions, request), + ); + }); - it('invokes listSessionsStream without error', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListSessionsRequest() - ); - const expectedResponse = [ - generateSampleMessage(new protos.google.showcase.v1beta1.Session()), - generateSampleMessage(new protos.google.showcase.v1beta1.Session()), - generateSampleMessage(new protos.google.showcase.v1beta1.Session()), - ]; - client.descriptors.page.listSessions.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listSessionsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.showcase.v1beta1.Session[] = []; - stream.on('data', (response: protos.google.showcase.v1beta1.Session) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.listSessions.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listSessions, request)); - }); + it('uses async iteration with listSessions without error', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListSessionsRequest(), + ); + const expectedResponse = [ + generateSampleMessage(new protos.google.showcase.v1beta1.Session()), + generateSampleMessage(new protos.google.showcase.v1beta1.Session()), + generateSampleMessage(new protos.google.showcase.v1beta1.Session()), + ]; + client.descriptors.page.listSessions.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.showcase.v1beta1.ISession[] = []; + const iterable = client.listSessionsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listSessions.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + }); - it('invokes listSessionsStream with error', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListSessionsRequest() - ); - const expectedError = new Error('expected'); - client.descriptors.page.listSessions.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listSessionsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.showcase.v1beta1.Session[] = []; - stream.on('data', (response: protos.google.showcase.v1beta1.Session) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listSessions.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listSessions, request)); - }); + it('uses async iteration with listSessions with error', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListSessionsRequest(), + ); + const expectedError = new Error('expected'); + client.descriptors.page.listSessions.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listSessionsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.showcase.v1beta1.ISession[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listSessions.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + }); + }); + + describe('listTests', () => { + it('invokes listTests without error', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListTestsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.ListTestsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.showcase.v1beta1.Test()), + generateSampleMessage(new protos.google.showcase.v1beta1.Test()), + generateSampleMessage(new protos.google.showcase.v1beta1.Test()), + ]; + client.innerApiCalls.listTests = stubSimpleCall(expectedResponse); + const [response] = await client.listTests(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listTests as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listTests as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('uses async iteration with listSessions without error', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListSessionsRequest() - ); - const expectedResponse = [ - generateSampleMessage(new protos.google.showcase.v1beta1.Session()), - generateSampleMessage(new protos.google.showcase.v1beta1.Session()), - generateSampleMessage(new protos.google.showcase.v1beta1.Session()), - ]; - client.descriptors.page.listSessions.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.showcase.v1beta1.ISession[] = []; - const iterable = client.listSessionsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); + it('invokes listTests without error using callback', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListTestsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.ListTestsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.showcase.v1beta1.Test()), + generateSampleMessage(new protos.google.showcase.v1beta1.Test()), + generateSampleMessage(new protos.google.showcase.v1beta1.Test()), + ]; + client.innerApiCalls.listTests = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listTests( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.ITest[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listSessions.asyncIterate as SinonStub) - .getCall(0).args[1], request); - }); + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listTests as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listTests as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('uses async iteration with listSessions with error', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListSessionsRequest() - ); - const expectedError = new Error('expected'); - client.descriptors.page.listSessions.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listSessionsAsync(request); - await assert.rejects(async () => { - const responses: protos.google.showcase.v1beta1.ISession[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listSessions.asyncIterate as SinonStub) - .getCall(0).args[1], request); - }); + it('invokes listTests with error', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListTestsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.ListTestsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listTests = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.listTests(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listTests as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listTests as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('listTests', () => { - it('invokes listTests without error', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListTestsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.ListTestsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.showcase.v1beta1.Test()), - generateSampleMessage(new protos.google.showcase.v1beta1.Test()), - generateSampleMessage(new protos.google.showcase.v1beta1.Test()), - ]; - client.innerApiCalls.listTests = stubSimpleCall(expectedResponse); - const [response] = await client.listTests(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listTests as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listTests as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes listTestsStream without error', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListTestsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.ListTestsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.showcase.v1beta1.Test()), + generateSampleMessage(new protos.google.showcase.v1beta1.Test()), + generateSampleMessage(new protos.google.showcase.v1beta1.Test()), + ]; + client.descriptors.page.listTests.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listTestsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.showcase.v1beta1.Test[] = []; + stream.on('data', (response: protos.google.showcase.v1beta1.Test) => { + responses.push(response); }); - - it('invokes listTests without error using callback', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListTestsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.ListTestsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.showcase.v1beta1.Test()), - generateSampleMessage(new protos.google.showcase.v1beta1.Test()), - generateSampleMessage(new protos.google.showcase.v1beta1.Test()), - ]; - client.innerApiCalls.listTests = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listTests( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.ITest[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listTests as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listTests as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + stream.on('end', () => { + resolve(responses); }); - - it('invokes listTests with error', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListTestsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.ListTestsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listTests = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listTests(request), expectedError); - const actualRequest = (client.innerApiCalls.listTests as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listTests as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + stream.on('error', (err: Error) => { + reject(err); }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listTests.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listTests, request), + ); + assert( + (client.descriptors.page.listTests.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('invokes listTestsStream without error', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListTestsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.ListTestsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.showcase.v1beta1.Test()), - generateSampleMessage(new protos.google.showcase.v1beta1.Test()), - generateSampleMessage(new protos.google.showcase.v1beta1.Test()), - ]; - client.descriptors.page.listTests.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listTestsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.showcase.v1beta1.Test[] = []; - stream.on('data', (response: protos.google.showcase.v1beta1.Test) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.listTests.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listTests, request)); - assert( - (client.descriptors.page.listTests.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); + it('invokes listTestsStream with error', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListTestsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.ListTestsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listTests.createStream = stubPageStreamingCall( + undefined, + expectedError, + ); + const stream = client.listTestsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.showcase.v1beta1.Test[] = []; + stream.on('data', (response: protos.google.showcase.v1beta1.Test) => { + responses.push(response); }); - - it('invokes listTestsStream with error', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListTestsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.ListTestsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listTests.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listTestsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.showcase.v1beta1.Test[] = []; - stream.on('data', (response: protos.google.showcase.v1beta1.Test) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listTests.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listTests, request)); - assert( - (client.descriptors.page.listTests.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); + stream.on('end', () => { + resolve(responses); }); - - it('uses async iteration with listTests without error', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListTestsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.ListTestsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.showcase.v1beta1.Test()), - generateSampleMessage(new protos.google.showcase.v1beta1.Test()), - generateSampleMessage(new protos.google.showcase.v1beta1.Test()), - ]; - client.descriptors.page.listTests.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.showcase.v1beta1.ITest[] = []; - const iterable = client.listTestsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listTests.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listTests.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); + stream.on('error', (err: Error) => { + reject(err); }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listTests.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listTests, request), + ); + assert( + (client.descriptors.page.listTests.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('uses async iteration with listTests with error', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListTestsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.ListTestsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listTests.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listTestsAsync(request); - await assert.rejects(async () => { - const responses: protos.google.showcase.v1beta1.ITest[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listTests.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listTests.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listTests without error', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListTestsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.ListTestsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.showcase.v1beta1.Test()), + generateSampleMessage(new protos.google.showcase.v1beta1.Test()), + generateSampleMessage(new protos.google.showcase.v1beta1.Test()), + ]; + client.descriptors.page.listTests.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.showcase.v1beta1.ITest[] = []; + const iterable = client.listTestsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + (client.descriptors.page.listTests.asyncIterate as SinonStub).getCall(0) + .args[1], + request, + ); + assert( + (client.descriptors.page.listTests.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); }); - describe('Path templates', () => { - - describe('blueprint', () => { - const fakePath = "/rendered/path/blueprint"; - const expectedParameters = { - session: "sessionValue", - test: "testValue", - blueprint: "blueprintValue", - }; - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.blueprintPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.blueprintPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('blueprintPath', () => { - const result = client.blueprintPath("sessionValue", "testValue", "blueprintValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.blueprintPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchSessionFromBlueprintName', () => { - const result = client.matchSessionFromBlueprintName(fakePath); - assert.strictEqual(result, "sessionValue"); - assert((client.pathTemplates.blueprintPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchTestFromBlueprintName', () => { - const result = client.matchTestFromBlueprintName(fakePath); - assert.strictEqual(result, "testValue"); - assert((client.pathTemplates.blueprintPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBlueprintFromBlueprintName', () => { - const result = client.matchBlueprintFromBlueprintName(fakePath); - assert.strictEqual(result, "blueprintValue"); - assert((client.pathTemplates.blueprintPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('uses async iteration with listTests with error', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListTestsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.ListTestsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listTests.asyncIterate = stubAsyncIterationCall( + undefined, + expectedError, + ); + const iterable = client.listTestsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.showcase.v1beta1.ITest[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + (client.descriptors.page.listTests.asyncIterate as SinonStub).getCall(0) + .args[1], + request, + ); + assert( + (client.descriptors.page.listTests.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + }); + + describe('Path templates', () => { + describe('blueprint', () => { + const fakePath = '/rendered/path/blueprint'; + const expectedParameters = { + session: 'sessionValue', + test: 'testValue', + blueprint: 'blueprintValue', + }; + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.blueprintPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.blueprintPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('blueprintPath', () => { + const result = client.blueprintPath( + 'sessionValue', + 'testValue', + 'blueprintValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.blueprintPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchSessionFromBlueprintName', () => { + const result = client.matchSessionFromBlueprintName(fakePath); + assert.strictEqual(result, 'sessionValue'); + assert( + (client.pathTemplates.blueprintPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchTestFromBlueprintName', () => { + const result = client.matchTestFromBlueprintName(fakePath); + assert.strictEqual(result, 'testValue'); + assert( + (client.pathTemplates.blueprintPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBlueprintFromBlueprintName', () => { + const result = client.matchBlueprintFromBlueprintName(fakePath); + assert.strictEqual(result, 'blueprintValue'); + assert( + (client.pathTemplates.blueprintPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('room', () => { - const fakePath = "/rendered/path/room"; - const expectedParameters = { - room: "roomValue", - }; - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.roomPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.roomPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('roomPath', () => { - const result = client.roomPath("roomValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.roomPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchRoomFromRoomName', () => { - const result = client.matchRoomFromRoomName(fakePath); - assert.strictEqual(result, "roomValue"); - assert((client.pathTemplates.roomPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('room', () => { + const fakePath = '/rendered/path/room'; + const expectedParameters = { + room: 'roomValue', + }; + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.roomPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.roomPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('roomPath', () => { + const result = client.roomPath('roomValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.roomPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchRoomFromRoomName', () => { + const result = client.matchRoomFromRoomName(fakePath); + assert.strictEqual(result, 'roomValue'); + assert( + (client.pathTemplates.roomPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('roomBlurb', () => { - const fakePath = "/rendered/path/roomBlurb"; - const expectedParameters = { - room: "roomValue", - blurb: "blurbValue", - }; - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.roomBlurbPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.roomBlurbPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('roomBlurbPath', () => { - const result = client.roomBlurbPath("roomValue", "blurbValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.roomBlurbPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchRoomFromRoomBlurbName', () => { - const result = client.matchRoomFromRoomBlurbName(fakePath); - assert.strictEqual(result, "roomValue"); - assert((client.pathTemplates.roomBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBlurbFromRoomBlurbName', () => { - const result = client.matchBlurbFromRoomBlurbName(fakePath); - assert.strictEqual(result, "blurbValue"); - assert((client.pathTemplates.roomBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('roomBlurb', () => { + const fakePath = '/rendered/path/roomBlurb'; + const expectedParameters = { + room: 'roomValue', + blurb: 'blurbValue', + }; + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.roomBlurbPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.roomBlurbPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('roomBlurbPath', () => { + const result = client.roomBlurbPath('roomValue', 'blurbValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.roomBlurbPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchRoomFromRoomBlurbName', () => { + const result = client.matchRoomFromRoomBlurbName(fakePath); + assert.strictEqual(result, 'roomValue'); + assert( + (client.pathTemplates.roomBlurbPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBlurbFromRoomBlurbName', () => { + const result = client.matchBlurbFromRoomBlurbName(fakePath); + assert.strictEqual(result, 'blurbValue'); + assert( + (client.pathTemplates.roomBlurbPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('roomBlurbsLegacyRoomBlurb', () => { - const fakePath = "/rendered/path/roomBlurbsLegacyRoomBlurb"; - const expectedParameters = { - room: "roomValue", - legacy_room: "legacyRoomValue", - blurb: "blurbValue", - }; - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('roomBlurbsLegacyRoomBlurbPath', () => { - const result = client.roomBlurbsLegacyRoomBlurbPath("roomValue", "legacyRoomValue", "blurbValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchRoomFromRoomBlurbsLegacyRoomBlurbName', () => { - const result = client.matchRoomFromRoomBlurbsLegacyRoomBlurbName(fakePath); - assert.strictEqual(result, "roomValue"); - assert((client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName', () => { - const result = client.matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName(fakePath); - assert.strictEqual(result, "legacyRoomValue"); - assert((client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBlurbFromRoomBlurbsLegacyRoomBlurbName', () => { - const result = client.matchBlurbFromRoomBlurbsLegacyRoomBlurbName(fakePath); - assert.strictEqual(result, "blurbValue"); - assert((client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('roomBlurbsLegacyRoomBlurb', () => { + const fakePath = '/rendered/path/roomBlurbsLegacyRoomBlurb'; + const expectedParameters = { + room: 'roomValue', + legacy_room: 'legacyRoomValue', + blurb: 'blurbValue', + }; + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('roomBlurbsLegacyRoomBlurbPath', () => { + const result = client.roomBlurbsLegacyRoomBlurbPath( + 'roomValue', + 'legacyRoomValue', + 'blurbValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchRoomFromRoomBlurbsLegacyRoomBlurbName', () => { + const result = + client.matchRoomFromRoomBlurbsLegacyRoomBlurbName(fakePath); + assert.strictEqual(result, 'roomValue'); + assert( + ( + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName', () => { + const result = + client.matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName(fakePath); + assert.strictEqual(result, 'legacyRoomValue'); + assert( + ( + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBlurbFromRoomBlurbsLegacyRoomBlurbName', () => { + const result = + client.matchBlurbFromRoomBlurbsLegacyRoomBlurbName(fakePath); + assert.strictEqual(result, 'blurbValue'); + assert( + ( + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('sequence', () => { - const fakePath = "/rendered/path/sequence"; - const expectedParameters = { - sequence: "sequenceValue", - }; - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.sequencePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.sequencePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('sequencePath', () => { - const result = client.sequencePath("sequenceValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.sequencePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchSequenceFromSequenceName', () => { - const result = client.matchSequenceFromSequenceName(fakePath); - assert.strictEqual(result, "sequenceValue"); - assert((client.pathTemplates.sequencePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('sequence', () => { + const fakePath = '/rendered/path/sequence'; + const expectedParameters = { + sequence: 'sequenceValue', + }; + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.sequencePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.sequencePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('sequencePath', () => { + const result = client.sequencePath('sequenceValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.sequencePathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchSequenceFromSequenceName', () => { + const result = client.matchSequenceFromSequenceName(fakePath); + assert.strictEqual(result, 'sequenceValue'); + assert( + (client.pathTemplates.sequencePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('sequenceReport', () => { - const fakePath = "/rendered/path/sequenceReport"; - const expectedParameters = { - sequence: "sequenceValue", - }; - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.sequenceReportPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.sequenceReportPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('sequenceReportPath', () => { - const result = client.sequenceReportPath("sequenceValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.sequenceReportPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchSequenceFromSequenceReportName', () => { - const result = client.matchSequenceFromSequenceReportName(fakePath); - assert.strictEqual(result, "sequenceValue"); - assert((client.pathTemplates.sequenceReportPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('sequenceReport', () => { + const fakePath = '/rendered/path/sequenceReport'; + const expectedParameters = { + sequence: 'sequenceValue', + }; + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.sequenceReportPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.sequenceReportPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('sequenceReportPath', () => { + const result = client.sequenceReportPath('sequenceValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.sequenceReportPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchSequenceFromSequenceReportName', () => { + const result = client.matchSequenceFromSequenceReportName(fakePath); + assert.strictEqual(result, 'sequenceValue'); + assert( + (client.pathTemplates.sequenceReportPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('session', () => { - const fakePath = "/rendered/path/session"; - const expectedParameters = { - session: "sessionValue", - }; - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.sessionPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.sessionPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('sessionPath', () => { - const result = client.sessionPath("sessionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.sessionPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchSessionFromSessionName', () => { - const result = client.matchSessionFromSessionName(fakePath); - assert.strictEqual(result, "sessionValue"); - assert((client.pathTemplates.sessionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('session', () => { + const fakePath = '/rendered/path/session'; + const expectedParameters = { + session: 'sessionValue', + }; + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.sessionPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.sessionPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('sessionPath', () => { + const result = client.sessionPath('sessionValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.sessionPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchSessionFromSessionName', () => { + const result = client.matchSessionFromSessionName(fakePath); + assert.strictEqual(result, 'sessionValue'); + assert( + (client.pathTemplates.sessionPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('test', () => { - const fakePath = "/rendered/path/test"; - const expectedParameters = { - session: "sessionValue", - test: "testValue", - }; - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.testPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.testPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('testPath', () => { - const result = client.testPath("sessionValue", "testValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.testPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchSessionFromTestName', () => { - const result = client.matchSessionFromTestName(fakePath); - assert.strictEqual(result, "sessionValue"); - assert((client.pathTemplates.testPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchTestFromTestName', () => { - const result = client.matchTestFromTestName(fakePath); - assert.strictEqual(result, "testValue"); - assert((client.pathTemplates.testPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('test', () => { + const fakePath = '/rendered/path/test'; + const expectedParameters = { + session: 'sessionValue', + test: 'testValue', + }; + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.testPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.testPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('testPath', () => { + const result = client.testPath('sessionValue', 'testValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.testPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchSessionFromTestName', () => { + const result = client.matchSessionFromTestName(fakePath); + assert.strictEqual(result, 'sessionValue'); + assert( + (client.pathTemplates.testPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchTestFromTestName', () => { + const result = client.matchTestFromTestName(fakePath); + assert.strictEqual(result, 'testValue'); + assert( + (client.pathTemplates.testPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('user', () => { - const fakePath = "/rendered/path/user"; - const expectedParameters = { - user: "userValue", - }; - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.userPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.userPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('userPath', () => { - const result = client.userPath("userValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.userPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchUserFromUserName', () => { - const result = client.matchUserFromUserName(fakePath); - assert.strictEqual(result, "userValue"); - assert((client.pathTemplates.userPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('user', () => { + const fakePath = '/rendered/path/user'; + const expectedParameters = { + user: 'userValue', + }; + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.userPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.userPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('userPath', () => { + const result = client.userPath('userValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.userPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchUserFromUserName', () => { + const result = client.matchUserFromUserName(fakePath); + assert.strictEqual(result, 'userValue'); + assert( + (client.pathTemplates.userPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('userProfileBlurb', () => { - const fakePath = "/rendered/path/userProfileBlurb"; - const expectedParameters = { - user: "userValue", - blurb: "blurbValue", - }; - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.userProfileBlurbPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.userProfileBlurbPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('userProfileBlurbPath', () => { - const result = client.userProfileBlurbPath("userValue", "blurbValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.userProfileBlurbPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchUserFromUserProfileBlurbName', () => { - const result = client.matchUserFromUserProfileBlurbName(fakePath); - assert.strictEqual(result, "userValue"); - assert((client.pathTemplates.userProfileBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBlurbFromUserProfileBlurbName', () => { - const result = client.matchBlurbFromUserProfileBlurbName(fakePath); - assert.strictEqual(result, "blurbValue"); - assert((client.pathTemplates.userProfileBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('userProfileBlurb', () => { + const fakePath = '/rendered/path/userProfileBlurb'; + const expectedParameters = { + user: 'userValue', + blurb: 'blurbValue', + }; + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.userProfileBlurbPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.userProfileBlurbPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('userProfileBlurbPath', () => { + const result = client.userProfileBlurbPath('userValue', 'blurbValue'); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.userProfileBlurbPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchUserFromUserProfileBlurbName', () => { + const result = client.matchUserFromUserProfileBlurbName(fakePath); + assert.strictEqual(result, 'userValue'); + assert( + (client.pathTemplates.userProfileBlurbPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBlurbFromUserProfileBlurbName', () => { + const result = client.matchBlurbFromUserProfileBlurbName(fakePath); + assert.strictEqual(result, 'blurbValue'); + assert( + (client.pathTemplates.userProfileBlurbPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('userProfileBlurbsLegacyUserBlurb', () => { - const fakePath = "/rendered/path/userProfileBlurbsLegacyUserBlurb"; - const expectedParameters = { - user: "userValue", - legacy_user: "legacyUserValue", - blurb: "blurbValue", - }; - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('userProfileBlurbsLegacyUserBlurbPath', () => { - const result = client.userProfileBlurbsLegacyUserBlurbPath("userValue", "legacyUserValue", "blurbValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchUserFromUserProfileBlurbsLegacyUserBlurbName', () => { - const result = client.matchUserFromUserProfileBlurbsLegacyUserBlurbName(fakePath); - assert.strictEqual(result, "userValue"); - assert((client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName', () => { - const result = client.matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName(fakePath); - assert.strictEqual(result, "legacyUserValue"); - assert((client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBlurbFromUserProfileBlurbsLegacyUserBlurbName', () => { - const result = client.matchBlurbFromUserProfileBlurbsLegacyUserBlurbName(fakePath); - assert.strictEqual(result, "blurbValue"); - assert((client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('userProfileBlurbsLegacyUserBlurb', () => { + const fakePath = '/rendered/path/userProfileBlurbsLegacyUserBlurb'; + const expectedParameters = { + user: 'userValue', + legacy_user: 'legacyUserValue', + blurb: 'blurbValue', + }; + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('userProfileBlurbsLegacyUserBlurbPath', () => { + const result = client.userProfileBlurbsLegacyUserBlurbPath( + 'userValue', + 'legacyUserValue', + 'blurbValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchUserFromUserProfileBlurbsLegacyUserBlurbName', () => { + const result = + client.matchUserFromUserProfileBlurbsLegacyUserBlurbName(fakePath); + assert.strictEqual(result, 'userValue'); + assert( + ( + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName', () => { + const result = + client.matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName( + fakePath, + ); + assert.strictEqual(result, 'legacyUserValue'); + assert( + ( + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBlurbFromUserProfileBlurbsLegacyUserBlurbName', () => { + const result = + client.matchBlurbFromUserProfileBlurbsLegacyUserBlurbName(fakePath); + assert.strictEqual(result, 'blurbValue'); + assert( + ( + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/core/generator/gapic-generator-typescript/baselines/showcase-legacy-esm/esm/src/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/showcase-legacy-esm/esm/src/index.ts.baseline index 6499b5483840..3b8a3c4f334f 100644 --- a/core/generator/gapic-generator-typescript/baselines/showcase-legacy-esm/esm/src/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/showcase-legacy-esm/esm/src/index.ts.baseline @@ -19,8 +19,8 @@ import * as v1beta1 from './v1beta1/index.js'; const EchoClient = v1beta1.EchoClient; type EchoClient = v1beta1.EchoClient; -export {v1beta1, EchoClient}; -export default {v1beta1, EchoClient}; +export { v1beta1, EchoClient }; +export default { v1beta1, EchoClient }; // @ts-ignore import * as protos from '../../protos/protos.js'; -export {protos} +export { protos }; diff --git a/core/generator/gapic-generator-typescript/baselines/showcase-legacy-esm/esm/src/v1beta1/echo_client.ts.baseline b/core/generator/gapic-generator-typescript/baselines/showcase-legacy-esm/esm/src/v1beta1/echo_client.ts.baseline index 8b80d7a015d2..6f3f70a0cf76 100644 --- a/core/generator/gapic-generator-typescript/baselines/showcase-legacy-esm/esm/src/v1beta1/echo_client.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/showcase-legacy-esm/esm/src/v1beta1/echo_client.ts.baseline @@ -17,15 +17,24 @@ // ** All changes to this file may be overwritten. ** import * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions, GrpcClientOptions, LROperation, PaginationCallback, GaxCall} from 'google-gax'; -import {Transform, PassThrough} from 'stream'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + GrpcClientOptions, + LROperation, + PaginationCallback, + GaxCall, +} from 'google-gax'; +import { Transform, PassThrough } from 'stream'; // @ts-ignore import type * as protos from '../../../protos/protos.js'; import * as echo_client_config from './echo_client_config.json'; import fs from 'fs'; import path from 'path'; -import {fileURLToPath} from 'url'; -import {getJSON} from '../json-helper.cjs'; +import { fileURLToPath } from 'url'; +import { getJSON } from '../json-helper.cjs'; // @ts-ignore const dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -34,14 +43,12 @@ const dirname = path.dirname(fileURLToPath(import.meta.url)); * `src/v1beta1/echo_client_config.json`. * This file defines retry strategy and timeouts for all API methods in this library. */ -const gapicConfig = getJSON( - path.join(dirname, 'echo_client_config.json') -); +const gapicConfig = getJSON(path.join(dirname, 'echo_client_config.json')); -import {loggingUtils as logging} from 'google-gax'; +import { loggingUtils as logging } from 'google-gax'; const version = getJSON( - path.join(dirname, '..', '..', '..', '..', 'package.json') + path.join(dirname, '..', '..', '..', '..', 'package.json'), ).version; /** @@ -64,7 +71,7 @@ export class EchoClient { private _gaxModule: typeof gax; private _gaxGrpc: gax.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('showcase'); @@ -76,9 +83,9 @@ export class EchoClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; + innerApiCalls: { [name: string]: Function }; operationsClient: gax.OperationsClient; - echoStub?: Promise<{[name: string]: Function}>; + echoStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of EchoClient. @@ -112,17 +119,33 @@ export class EchoClient { constructor(opts?: ClientOptions) { // Ensure that options include all the required fields. const staticMembers = this.constructor as typeof EchoClient; - if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { - throw new Error('Please set either universe_domain or universeDomain, but not both.'); + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); } - const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; - this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; this._servicePath = 'localhost'; - const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; - opts = Object.assign({servicePath, port, clientConfig}, opts); + opts = Object.assign({ servicePath, port, clientConfig }, opts); // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. if (servicePath !== this._servicePath && !('scopes' in opts)) { @@ -139,7 +162,7 @@ export class EchoClient { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; @@ -156,10 +179,7 @@ export class EchoClient { const isEsm = true; const isEsmString = isEsm ? '-esm' : '-cjs'; // Determine the client header string. - const clientHeader = [ - `gax/${this._gaxModule.version}`, - `gapic/${version}`, - ]; + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/{process.versions.node}${isEsmString}`); } else { @@ -173,53 +193,86 @@ export class EchoClient { // Load the applicable protos. this._protos = this._gaxGrpc.loadProto( path.join(dirname, '..', '..', '..', 'protos'), - 'google/showcase/v1beta1/echo.proto' + 'google/showcase/v1beta1/echo.proto', ); // Some of the methods on this service return "paged" results, // (e.g. 50 results at a time, with tokens to get subsequent // pages). Denote the keys used for pagination and results. this.descriptors.page = { - pagedExpand: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'responses') + pagedExpand: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'responses', + ), }; // Some of the methods on this service provide streaming responses. // Provide descriptors for these. this.descriptors.stream = { - expand: new this._gaxModule.StreamDescriptor(this._gaxModule.StreamType.SERVER_STREAMING, !!opts.fallback, !!opts.gaxServerStreamingRetries), - collect: new this._gaxModule.StreamDescriptor(this._gaxModule.StreamType.CLIENT_STREAMING, !!opts.fallback), - chat: new this._gaxModule.StreamDescriptor(this._gaxModule.StreamType.BIDI_STREAMING, !!opts.fallback, !!opts.gaxServerStreamingRetries) + expand: new this._gaxModule.StreamDescriptor( + this._gaxModule.StreamType.SERVER_STREAMING, + !!opts.fallback, + !!opts.gaxServerStreamingRetries, + ), + collect: new this._gaxModule.StreamDescriptor( + this._gaxModule.StreamType.CLIENT_STREAMING, + !!opts.fallback, + ), + chat: new this._gaxModule.StreamDescriptor( + this._gaxModule.StreamType.BIDI_STREAMING, + !!opts.fallback, + !!opts.gaxServerStreamingRetries, + ), }; let protoFilesRoot = new this._gaxModule.GoogleProtoFilesRoot(); protoFilesRoot = this._gaxModule.protobuf.loadSync( - path.join(dirname, '..', '..', '..', 'protos', 'google/showcase/v1beta1/echo.proto'), - protoFilesRoot) as (typeof protoFilesRoot); + path.join( + dirname, + '..', + '..', + '..', + 'protos', + 'google/showcase/v1beta1/echo.proto', + ), + protoFilesRoot, + ) as typeof protoFilesRoot; // This API contains "long-running operations", which return a // an Operation object that allows for tracking of the operation, // rather than holding a request open. const lroOptions: GrpcClientOptions = { auth: this.auth, - grpc: 'grpc' in this._gaxGrpc ? this._gaxGrpc.grpc : undefined + grpc: 'grpc' in this._gaxGrpc ? this._gaxGrpc.grpc : undefined, }; - this.operationsClient = this._gaxModule.lro(lroOptions).operationsClient(opts); + this.operationsClient = this._gaxModule + .lro(lroOptions) + .operationsClient(opts); const waitResponse = protoFilesRoot.lookup( - '.google.showcase.v1beta1.WaitResponse') as gax.protobuf.Type; + '.google.showcase.v1beta1.WaitResponse', + ) as gax.protobuf.Type; const waitMetadata = protoFilesRoot.lookup( - '.google.showcase.v1beta1.WaitMetadata') as gax.protobuf.Type; + '.google.showcase.v1beta1.WaitMetadata', + ) as gax.protobuf.Type; this.descriptors.longrunning = { wait: new this._gaxModule.LongrunningDescriptor( this.operationsClient, waitResponse.decode.bind(waitResponse), - waitMetadata.decode.bind(waitMetadata)) + waitMetadata.decode.bind(waitMetadata), + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.showcase.v1beta1.Echo', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' '), 'x-goog-api-version': 'v1_20240408'}); + 'google.showcase.v1beta1.Echo', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + { + 'x-goog-api-client': clientHeader.join(' '), + 'x-goog-api-version': 'v1_20240408', + }, + ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -250,33 +303,51 @@ export class EchoClient { // Put together the "service stub" for // google.showcase.v1beta1.Echo. this.echoStub = this._gaxGrpc.createStub( - // eslint-disable-next-line @typescript-eslint/no-explicit-any - (this._protos as any).google.showcase.v1beta1.Echo, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + (this._protos as any).google.showcase.v1beta1.Echo, + this._opts, + this._providedCustomServicePath, + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const echoStubMethods = - ['echo', 'echoErrorDetails', 'expand', 'collect', 'chat', 'pagedExpand', 'pagedExpandLegacy', 'wait', 'block']; + const echoStubMethods = [ + 'echo', + 'echoErrorDetails', + 'expand', + 'collect', + 'chat', + 'pagedExpand', + 'pagedExpandLegacy', + 'wait', + 'block', + ]; for (const methodName of echoStubMethods) { const callPromise = this.echoStub.then( - stub => (...args: Array<{}>) => { - if (this._terminated) { - if (methodName in this.descriptors.stream) { - const stream = new PassThrough({objectMode: true}); - setImmediate(() => { - stream.emit('error', new this._gaxModule.GoogleError('The client has already been closed.')); - }); - return stream; + (stub) => + (...args: Array<{}>) => { + if (this._terminated) { + if (methodName in this.descriptors.stream) { + const stream = new PassThrough({ objectMode: true }); + setImmediate(() => { + stream.emit( + 'error', + new this._gaxModule.GoogleError( + 'The client has already been closed.', + ), + ); + }); + return stream; + } + return Promise.reject('The client has already been closed.'); } - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error|null|undefined) => () => { + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { throw err; - }); + }, + ); const descriptor = this.descriptors.page[methodName] || @@ -287,7 +358,7 @@ export class EchoClient { callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -302,8 +373,14 @@ export class EchoClient { * @returns {string} The DNS address for this service. */ static get servicePath() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'localhost'; } @@ -315,8 +392,14 @@ export class EchoClient { * @returns {string} The DNS address for this service. */ static get apiEndpoint() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'localhost'; } @@ -356,8 +439,9 @@ export class EchoClient { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId(callback?: Callback): - Promise|void { + getProjectId( + callback?: Callback, + ): Promise | void { if (callback) { this.auth.getProjectId(callback); return; @@ -368,73 +452,86 @@ export class EchoClient { // ------------------- // -- Service calls -- // ------------------- -/** - * @param {Object} request - * The request object that will be sent. - * @param {string} request.content - * The content to be echoed by the server. - * @param {google.rpc.Status} request.error - * The error to be thrown by the server. - * @param {google.showcase.v1beta1.Severity} request.severity - * The severity to be echoed by the server. - * @param {string} request.header - * Optional. This field can be set to test the routing annotation on the Echo method. - * @param {string} request.otherHeader - * Optional. This field can be set to test the routing annotation on the Echo method. - * @param {string} request.requestId - * To facilitate testing of https://google.aip.dev/client-libraries/4235 - * @param {string} request.otherRequestId - * To facilitate testing of https://google.aip.dev/client-libraries/4235 - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.EchoResponse|EchoResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/echo.echo.js - * region_tag:localhost_v1beta1_generated_Echo_Echo_async - */ + /** + * @param {Object} request + * The request object that will be sent. + * @param {string} request.content + * The content to be echoed by the server. + * @param {google.rpc.Status} request.error + * The error to be thrown by the server. + * @param {google.showcase.v1beta1.Severity} request.severity + * The severity to be echoed by the server. + * @param {string} request.header + * Optional. This field can be set to test the routing annotation on the Echo method. + * @param {string} request.otherHeader + * Optional. This field can be set to test the routing annotation on the Echo method. + * @param {string} request.requestId + * To facilitate testing of https://google.aip.dev/client-libraries/4235 + * @param {string} request.otherRequestId + * To facilitate testing of https://google.aip.dev/client-libraries/4235 + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.EchoResponse|EchoResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/echo.echo.js + * region_tag:localhost_v1beta1_generated_Echo_Echo_async + */ echo( - request?: protos.google.showcase.v1beta1.IEchoRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IEchoResponse, - protos.google.showcase.v1beta1.IEchoRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IEchoRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IEchoResponse, + protos.google.showcase.v1beta1.IEchoRequest | undefined, + {} | undefined, + ] + >; echo( - request: protos.google.showcase.v1beta1.IEchoRequest, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.IEchoResponse, - protos.google.showcase.v1beta1.IEchoRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IEchoRequest, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.IEchoResponse, + protos.google.showcase.v1beta1.IEchoRequest | null | undefined, + {} | null | undefined + >, + ): void; echo( - request: protos.google.showcase.v1beta1.IEchoRequest, - callback: Callback< - protos.google.showcase.v1beta1.IEchoResponse, - protos.google.showcase.v1beta1.IEchoRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IEchoRequest, + callback: Callback< + protos.google.showcase.v1beta1.IEchoResponse, + protos.google.showcase.v1beta1.IEchoRequest | null | undefined, + {} | null | undefined + >, + ): void; echo( - request?: protos.google.showcase.v1beta1.IEchoRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.showcase.v1beta1.IEchoResponse, - protos.google.showcase.v1beta1.IEchoRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.showcase.v1beta1.IEchoRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.IEchoResponse, - protos.google.showcase.v1beta1.IEchoRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.IEchoResponse, - protos.google.showcase.v1beta1.IEchoRequest|undefined, {}|undefined - ]>|void { + protos.google.showcase.v1beta1.IEchoRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.IEchoResponse, + protos.google.showcase.v1beta1.IEchoRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IEchoResponse, + protos.google.showcase.v1beta1.IEchoRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; @@ -454,7 +551,9 @@ export class EchoClient { { const fieldValue = request.header; if (fieldValue !== undefined && fieldValue !== null) { - const match = fieldValue.toString().match(RegExp('(?(?:.*)?)')); + const match = fieldValue + .toString() + .match(RegExp('(?(?:.*)?)')); if (match) { const parameterValue = match.groups?.['routing_id'] ?? fieldValue; Object.assign(routingParameter, { routing_id: parameterValue }); @@ -464,7 +563,9 @@ export class EchoClient { { const fieldValue = request.header; if (fieldValue !== undefined && fieldValue !== null) { - const match = fieldValue.toString().match(RegExp('(?regions/[^/]+/zones/[^/]+(?:/.*)?)')); + const match = fieldValue + .toString() + .match(RegExp('(?regions/[^/]+/zones/[^/]+(?:/.*)?)')); if (match) { const parameterValue = match.groups?.['table_name'] ?? fieldValue; Object.assign(routingParameter, { table_name: parameterValue }); @@ -474,7 +575,9 @@ export class EchoClient { { const fieldValue = request.header; if (fieldValue !== undefined && fieldValue !== null) { - const match = fieldValue.toString().match(RegExp('(?projects/[^/]+)(?:/.*)?')); + const match = fieldValue + .toString() + .match(RegExp('(?projects/[^/]+)(?:/.*)?')); if (match) { const parameterValue = match.groups?.['super_id'] ?? fieldValue; Object.assign(routingParameter, { super_id: parameterValue }); @@ -484,7 +587,11 @@ export class EchoClient { { const fieldValue = request.header; if (fieldValue !== undefined && fieldValue !== null) { - const match = fieldValue.toString().match(RegExp('(?projects/[^/]+/instances/[^/]+(?:/.*)?)')); + const match = fieldValue + .toString() + .match( + RegExp('(?projects/[^/]+/instances/[^/]+(?:/.*)?)'), + ); if (match) { const parameterValue = match.groups?.['table_name'] ?? fieldValue; Object.assign(routingParameter, { table_name: parameterValue }); @@ -494,7 +601,11 @@ export class EchoClient { { const fieldValue = request.header; if (fieldValue !== undefined && fieldValue !== null) { - const match = fieldValue.toString().match(RegExp('projects/[^/]+/(?instances/[^/]+)(?:/.*)?')); + const match = fieldValue + .toString() + .match( + RegExp('projects/[^/]+/(?instances/[^/]+)(?:/.*)?'), + ); if (match) { const parameterValue = match.groups?.['instance_id'] ?? fieldValue; Object.assign(routingParameter, { instance_id: parameterValue }); @@ -514,609 +625,800 @@ export class EchoClient { { const fieldValue = request.otherHeader; if (fieldValue !== undefined && fieldValue !== null) { - const match = fieldValue.toString().match(RegExp('(?projects/[^/]+)(?:/.*)?')); + const match = fieldValue + .toString() + .match(RegExp('(?projects/[^/]+)(?:/.*)?')); if (match) { const parameterValue = match.groups?.['qux'] ?? fieldValue; Object.assign(routingParameter, { qux: parameterValue }); } } } - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams( - routingParameter - ); - this.initialize().catch(err => {throw err}); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams(routingParameter); + this.initialize().catch((err) => { + throw err; + }); this._log.info('echo request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.IEchoResponse, - protos.google.showcase.v1beta1.IEchoRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.IEchoResponse, + protos.google.showcase.v1beta1.IEchoRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('echo response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.echo(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.IEchoResponse, - protos.google.showcase.v1beta1.IEchoRequest|undefined, {}|undefined - ]) => { - this._log.info('echo response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { + return this.innerApiCalls + .echo(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.IEchoResponse, + protos.google.showcase.v1beta1.IEchoRequest | undefined, + {} | undefined, + ]) => { + this._log.info('echo response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { throw error; }); } -/** - * This method returns error details in a repeated "google.protobuf.Any" - * field. This method showcases handling errors thus encoded, particularly - * over REST transport. Note that GAPICs only allow the type - * "google.protobuf.Any" for field paths ending in "error.details", and, at - * run-time, the actual types for these fields must be one of the types in - * google/rpc/error_details.proto. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.singleDetailText - * Content to return in a singular `*.error.details` field of type - * `google.protobuf.Any` - * @param {string[]} request.multiDetailText - * Content to return in a repeated `*.error.details` field of type - * `google.protobuf.Any` - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.EchoErrorDetailsResponse|EchoErrorDetailsResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/echo.echo_error_details.js - * region_tag:localhost_v1beta1_generated_Echo_EchoErrorDetails_async - */ + /** + * This method returns error details in a repeated "google.protobuf.Any" + * field. This method showcases handling errors thus encoded, particularly + * over REST transport. Note that GAPICs only allow the type + * "google.protobuf.Any" for field paths ending in "error.details", and, at + * run-time, the actual types for these fields must be one of the types in + * google/rpc/error_details.proto. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.singleDetailText + * Content to return in a singular `*.error.details` field of type + * `google.protobuf.Any` + * @param {string[]} request.multiDetailText + * Content to return in a repeated `*.error.details` field of type + * `google.protobuf.Any` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.EchoErrorDetailsResponse|EchoErrorDetailsResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/echo.echo_error_details.js + * region_tag:localhost_v1beta1_generated_Echo_EchoErrorDetails_async + */ echoErrorDetails( - request?: protos.google.showcase.v1beta1.IEchoErrorDetailsRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IEchoErrorDetailsResponse, - protos.google.showcase.v1beta1.IEchoErrorDetailsRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IEchoErrorDetailsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IEchoErrorDetailsResponse, + protos.google.showcase.v1beta1.IEchoErrorDetailsRequest | undefined, + {} | undefined, + ] + >; echoErrorDetails( - request: protos.google.showcase.v1beta1.IEchoErrorDetailsRequest, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.IEchoErrorDetailsResponse, - protos.google.showcase.v1beta1.IEchoErrorDetailsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IEchoErrorDetailsRequest, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.IEchoErrorDetailsResponse, + | protos.google.showcase.v1beta1.IEchoErrorDetailsRequest + | null + | undefined, + {} | null | undefined + >, + ): void; echoErrorDetails( - request: protos.google.showcase.v1beta1.IEchoErrorDetailsRequest, - callback: Callback< - protos.google.showcase.v1beta1.IEchoErrorDetailsResponse, - protos.google.showcase.v1beta1.IEchoErrorDetailsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IEchoErrorDetailsRequest, + callback: Callback< + protos.google.showcase.v1beta1.IEchoErrorDetailsResponse, + | protos.google.showcase.v1beta1.IEchoErrorDetailsRequest + | null + | undefined, + {} | null | undefined + >, + ): void; echoErrorDetails( - request?: protos.google.showcase.v1beta1.IEchoErrorDetailsRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.showcase.v1beta1.IEchoErrorDetailsRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.IEchoErrorDetailsResponse, - protos.google.showcase.v1beta1.IEchoErrorDetailsRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.showcase.v1beta1.IEchoErrorDetailsResponse, - protos.google.showcase.v1beta1.IEchoErrorDetailsRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.IEchoErrorDetailsResponse, - protos.google.showcase.v1beta1.IEchoErrorDetailsRequest|undefined, {}|undefined - ]>|void { + | protos.google.showcase.v1beta1.IEchoErrorDetailsRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.IEchoErrorDetailsResponse, + | protos.google.showcase.v1beta1.IEchoErrorDetailsRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IEchoErrorDetailsResponse, + protos.google.showcase.v1beta1.IEchoErrorDetailsRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('echoErrorDetails request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.IEchoErrorDetailsResponse, - protos.google.showcase.v1beta1.IEchoErrorDetailsRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.IEchoErrorDetailsResponse, + | protos.google.showcase.v1beta1.IEchoErrorDetailsRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('echoErrorDetails response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.echoErrorDetails(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.IEchoErrorDetailsResponse, - protos.google.showcase.v1beta1.IEchoErrorDetailsRequest|undefined, {}|undefined - ]) => { - this._log.info('echoErrorDetails response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { + return this.innerApiCalls + .echoErrorDetails(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.IEchoErrorDetailsResponse, + protos.google.showcase.v1beta1.IEchoErrorDetailsRequest | undefined, + {} | undefined, + ]) => { + this._log.info('echoErrorDetails response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { throw error; }); } -/** - * This is similar to the PagedExpand except that it uses - * max_results instead of page_size, as some legacy APIs still - * do. New APIs should NOT use this pattern. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.content - * The string to expand. - * @param {number} request.maxResults - * The number of words to returned in each page. - * (-- aip.dev/not-precedent: This is a legacy, non-standard pattern that - * violates aip.dev/158. Ordinarily, this should be page_size. --) - * @param {string} request.pageToken - * The position of the page to be returned. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.PagedExpandResponse|PagedExpandResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/echo.paged_expand_legacy.js - * region_tag:localhost_v1beta1_generated_Echo_PagedExpandLegacy_async - */ + /** + * This is similar to the PagedExpand except that it uses + * max_results instead of page_size, as some legacy APIs still + * do. New APIs should NOT use this pattern. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.content + * The string to expand. + * @param {number} request.maxResults + * The number of words to returned in each page. + * (-- aip.dev/not-precedent: This is a legacy, non-standard pattern that + * violates aip.dev/158. Ordinarily, this should be page_size. --) + * @param {string} request.pageToken + * The position of the page to be returned. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.PagedExpandResponse|PagedExpandResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/echo.paged_expand_legacy.js + * region_tag:localhost_v1beta1_generated_Echo_PagedExpandLegacy_async + */ pagedExpandLegacy( - request?: protos.google.showcase.v1beta1.IPagedExpandLegacyRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IPagedExpandResponse, - protos.google.showcase.v1beta1.IPagedExpandLegacyRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IPagedExpandLegacyRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IPagedExpandResponse, + protos.google.showcase.v1beta1.IPagedExpandLegacyRequest | undefined, + {} | undefined, + ] + >; pagedExpandLegacy( - request: protos.google.showcase.v1beta1.IPagedExpandLegacyRequest, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.IPagedExpandResponse, - protos.google.showcase.v1beta1.IPagedExpandLegacyRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IPagedExpandLegacyRequest, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.IPagedExpandResponse, + | protos.google.showcase.v1beta1.IPagedExpandLegacyRequest + | null + | undefined, + {} | null | undefined + >, + ): void; pagedExpandLegacy( - request: protos.google.showcase.v1beta1.IPagedExpandLegacyRequest, - callback: Callback< - protos.google.showcase.v1beta1.IPagedExpandResponse, - protos.google.showcase.v1beta1.IPagedExpandLegacyRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IPagedExpandLegacyRequest, + callback: Callback< + protos.google.showcase.v1beta1.IPagedExpandResponse, + | protos.google.showcase.v1beta1.IPagedExpandLegacyRequest + | null + | undefined, + {} | null | undefined + >, + ): void; pagedExpandLegacy( - request?: protos.google.showcase.v1beta1.IPagedExpandLegacyRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.showcase.v1beta1.IPagedExpandLegacyRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.IPagedExpandResponse, - protos.google.showcase.v1beta1.IPagedExpandLegacyRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.showcase.v1beta1.IPagedExpandResponse, - protos.google.showcase.v1beta1.IPagedExpandLegacyRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.IPagedExpandResponse, - protos.google.showcase.v1beta1.IPagedExpandLegacyRequest|undefined, {}|undefined - ]>|void { + | protos.google.showcase.v1beta1.IPagedExpandLegacyRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.IPagedExpandResponse, + | protos.google.showcase.v1beta1.IPagedExpandLegacyRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IPagedExpandResponse, + protos.google.showcase.v1beta1.IPagedExpandLegacyRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('pagedExpandLegacy request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.IPagedExpandResponse, - protos.google.showcase.v1beta1.IPagedExpandLegacyRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.IPagedExpandResponse, + | protos.google.showcase.v1beta1.IPagedExpandLegacyRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('pagedExpandLegacy response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.pagedExpandLegacy(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.IPagedExpandResponse, - protos.google.showcase.v1beta1.IPagedExpandLegacyRequest|undefined, {}|undefined - ]) => { - this._log.info('pagedExpandLegacy response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { + return this.innerApiCalls + .pagedExpandLegacy(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.IPagedExpandResponse, + protos.google.showcase.v1beta1.IPagedExpandLegacyRequest | undefined, + {} | undefined, + ]) => { + this._log.info('pagedExpandLegacy response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { throw error; }); } -/** - * This method will block (wait) for the requested amount of time - * and then return the response or error. - * This method showcases how a client handles delays or retries. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.protobuf.Duration} request.responseDelay - * The amount of time to block before returning a response. - * @param {google.rpc.Status} request.error - * The error that will be returned by the server. If this code is specified - * to be the OK rpc code, an empty response will be returned. - * @param {google.showcase.v1beta1.BlockResponse} request.success - * The response to be returned that will signify successful method call. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.BlockResponse|BlockResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/echo.block.js - * region_tag:localhost_v1beta1_generated_Echo_Block_async - */ + /** + * This method will block (wait) for the requested amount of time + * and then return the response or error. + * This method showcases how a client handles delays or retries. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.protobuf.Duration} request.responseDelay + * The amount of time to block before returning a response. + * @param {google.rpc.Status} request.error + * The error that will be returned by the server. If this code is specified + * to be the OK rpc code, an empty response will be returned. + * @param {google.showcase.v1beta1.BlockResponse} request.success + * The response to be returned that will signify successful method call. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.BlockResponse|BlockResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/echo.block.js + * region_tag:localhost_v1beta1_generated_Echo_Block_async + */ block( - request?: protos.google.showcase.v1beta1.IBlockRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IBlockResponse, - protos.google.showcase.v1beta1.IBlockRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IBlockRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IBlockResponse, + protos.google.showcase.v1beta1.IBlockRequest | undefined, + {} | undefined, + ] + >; block( - request: protos.google.showcase.v1beta1.IBlockRequest, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.IBlockResponse, - protos.google.showcase.v1beta1.IBlockRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IBlockRequest, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.IBlockResponse, + protos.google.showcase.v1beta1.IBlockRequest | null | undefined, + {} | null | undefined + >, + ): void; block( - request: protos.google.showcase.v1beta1.IBlockRequest, - callback: Callback< - protos.google.showcase.v1beta1.IBlockResponse, - protos.google.showcase.v1beta1.IBlockRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IBlockRequest, + callback: Callback< + protos.google.showcase.v1beta1.IBlockResponse, + protos.google.showcase.v1beta1.IBlockRequest | null | undefined, + {} | null | undefined + >, + ): void; block( - request?: protos.google.showcase.v1beta1.IBlockRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.showcase.v1beta1.IBlockResponse, - protos.google.showcase.v1beta1.IBlockRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.showcase.v1beta1.IBlockRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.IBlockResponse, - protos.google.showcase.v1beta1.IBlockRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.IBlockResponse, - protos.google.showcase.v1beta1.IBlockRequest|undefined, {}|undefined - ]>|void { + protos.google.showcase.v1beta1.IBlockRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.IBlockResponse, + protos.google.showcase.v1beta1.IBlockRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IBlockResponse, + protos.google.showcase.v1beta1.IBlockRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('block request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.IBlockResponse, - protos.google.showcase.v1beta1.IBlockRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.IBlockResponse, + protos.google.showcase.v1beta1.IBlockRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('block response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.block(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.IBlockResponse, - protos.google.showcase.v1beta1.IBlockRequest|undefined, {}|undefined - ]) => { - this._log.info('block response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { + return this.innerApiCalls + .block(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.IBlockResponse, + protos.google.showcase.v1beta1.IBlockRequest | undefined, + {} | undefined, + ]) => { + this._log.info('block response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { throw error; }); } -/** - * This method splits the given content into words and will pass each word back - * through the stream. This method showcases server-side streaming RPCs. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.content - * The content that will be split into words and returned on the stream. - * @param {google.rpc.Status} request.error - * The error that is thrown after all words are sent on the stream. - * @param {google.protobuf.Duration} request.streamWaitTime - * The wait time between each server streaming messages - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits {@link protos.google.showcase.v1beta1.EchoResponse|EchoResponse} on 'data' event. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#server-streaming | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/echo.expand.js - * region_tag:localhost_v1beta1_generated_Echo_Expand_async - */ + /** + * This method splits the given content into words and will pass each word back + * through the stream. This method showcases server-side streaming RPCs. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.content + * The content that will be split into words and returned on the stream. + * @param {google.rpc.Status} request.error + * The error that is thrown after all words are sent on the stream. + * @param {google.protobuf.Duration} request.streamWaitTime + * The wait time between each server streaming messages + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits {@link protos.google.showcase.v1beta1.EchoResponse|EchoResponse} on 'data' event. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#server-streaming | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/echo.expand.js + * region_tag:localhost_v1beta1_generated_Echo_Expand_async + */ expand( - request?: protos.google.showcase.v1beta1.IExpandRequest, - options?: CallOptions): - gax.CancellableStream{ + request?: protos.google.showcase.v1beta1.IExpandRequest, + options?: CallOptions, + ): gax.CancellableStream { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('expand stream %j', options); return this.innerApiCalls.expand(request, options); } -/** - * This method will collect the words given to it. When the stream is closed - * by the client, this method will return the a concatenation of the strings - * passed to it. This method showcases client-side streaming RPCs. - * - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - A writable stream which accepts objects representing - * {@link protos.google.showcase.v1beta1.EchoRequest|EchoRequest}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#client-streaming | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/echo.collect.js - * region_tag:localhost_v1beta1_generated_Echo_Collect_async - */ + /** + * This method will collect the words given to it. When the stream is closed + * by the client, this method will return the a concatenation of the strings + * passed to it. This method showcases client-side streaming RPCs. + * + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} - A writable stream which accepts objects representing + * {@link protos.google.showcase.v1beta1.EchoRequest|EchoRequest}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#client-streaming | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/echo.collect.js + * region_tag:localhost_v1beta1_generated_Echo_Collect_async + */ collect( - options?: CallOptions, - callback?: Callback< - protos.google.showcase.v1beta1.IEchoResponse, - protos.google.showcase.v1beta1.IEchoRequest|null|undefined, - {}|null|undefined>): - gax.CancellableStream; + options?: CallOptions, + callback?: Callback< + protos.google.showcase.v1beta1.IEchoResponse, + protos.google.showcase.v1beta1.IEchoRequest | null | undefined, + {} | null | undefined + >, + ): gax.CancellableStream; collect( - callback?: Callback< - protos.google.showcase.v1beta1.IEchoResponse, - protos.google.showcase.v1beta1.IEchoRequest|null|undefined, - {}|null|undefined>): - gax.CancellableStream; + callback?: Callback< + protos.google.showcase.v1beta1.IEchoResponse, + protos.google.showcase.v1beta1.IEchoRequest | null | undefined, + {} | null | undefined + >, + ): gax.CancellableStream; collect( - optionsOrCallback?: CallOptions|Callback< - protos.google.showcase.v1beta1.IEchoResponse, - protos.google.showcase.v1beta1.IEchoRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.showcase.v1beta1.IEchoResponse, - protos.google.showcase.v1beta1.IEchoRequest|null|undefined, - {}|null|undefined>): - gax.CancellableStream { + optionsOrCallback?: + | CallOptions + | Callback< + protos.google.showcase.v1beta1.IEchoResponse, + protos.google.showcase.v1beta1.IEchoRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.IEchoResponse, + protos.google.showcase.v1beta1.IEchoRequest | null | undefined, + {} | null | undefined + >, + ): gax.CancellableStream { if (optionsOrCallback instanceof Function && callback === undefined) { - callback = optionsOrCallback; - optionsOrCallback = {}; + callback = optionsOrCallback; + optionsOrCallback = {}; } const options = optionsOrCallback as CallOptions; - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('collect stream %j', options); return this.innerApiCalls.collect(null, options, callback); } -/** - * This method, upon receiving a request on the stream, will pass the same - * content back on the stream. This method showcases bidirectional - * streaming RPCs. - * - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which is both readable and writable. It accepts objects - * representing {@link protos.google.showcase.v1beta1.EchoRequest|EchoRequest} for write() method, and - * will emit objects representing {@link protos.google.showcase.v1beta1.EchoResponse|EchoResponse} on 'data' event asynchronously. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#bi-directional-streaming | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/echo.chat.js - * region_tag:localhost_v1beta1_generated_Echo_Chat_async - */ - chat( - options?: CallOptions): - gax.CancellableStream { - this.initialize().catch(err => {throw err}); + /** + * This method, upon receiving a request on the stream, will pass the same + * content back on the stream. This method showcases bidirectional + * streaming RPCs. + * + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which is both readable and writable. It accepts objects + * representing {@link protos.google.showcase.v1beta1.EchoRequest|EchoRequest} for write() method, and + * will emit objects representing {@link protos.google.showcase.v1beta1.EchoResponse|EchoResponse} on 'data' event asynchronously. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#bi-directional-streaming | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/echo.chat.js + * region_tag:localhost_v1beta1_generated_Echo_Chat_async + */ + chat(options?: CallOptions): gax.CancellableStream { + this.initialize().catch((err) => { + throw err; + }); this._log.info('chat stream %j', options); return this.innerApiCalls.chat(null, options); } -/** - * This method will wait for the requested amount of time and then return. - * This method showcases how a client handles a request timeout. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.protobuf.Timestamp} request.endTime - * The time that this operation will complete. - * @param {google.protobuf.Duration} request.ttl - * The duration of this operation. - * @param {google.rpc.Status} request.error - * The error that will be returned by the server. If this code is specified - * to be the OK rpc code, an empty response will be returned. - * @param {google.showcase.v1beta1.WaitResponse} request.success - * The response to be returned on operation completion. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing - * a long running operation. Its `promise()` method returns a promise - * you can `await` for. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/echo.wait.js - * region_tag:localhost_v1beta1_generated_Echo_Wait_async - */ + /** + * This method will wait for the requested amount of time and then return. + * This method showcases how a client handles a request timeout. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.protobuf.Timestamp} request.endTime + * The time that this operation will complete. + * @param {google.protobuf.Duration} request.ttl + * The duration of this operation. + * @param {google.rpc.Status} request.error + * The error that will be returned by the server. If this code is specified + * to be the OK rpc code, an empty response will be returned. + * @param {google.showcase.v1beta1.WaitResponse} request.success + * The response to be returned on operation completion. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/echo.wait.js + * region_tag:localhost_v1beta1_generated_Echo_Wait_async + */ wait( - request?: protos.google.showcase.v1beta1.IWaitRequest, - options?: CallOptions): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IWaitRequest, + options?: CallOptions, + ): Promise< + [ + LROperation< + protos.google.showcase.v1beta1.IWaitResponse, + protos.google.showcase.v1beta1.IWaitMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; wait( - request: protos.google.showcase.v1beta1.IWaitRequest, - options: CallOptions, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IWaitRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.showcase.v1beta1.IWaitResponse, + protos.google.showcase.v1beta1.IWaitMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; wait( - request: protos.google.showcase.v1beta1.IWaitRequest, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IWaitRequest, + callback: Callback< + LROperation< + protos.google.showcase.v1beta1.IWaitResponse, + protos.google.showcase.v1beta1.IWaitMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; wait( - request?: protos.google.showcase.v1beta1.IWaitRequest, - optionsOrCallback?: CallOptions|Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>, - callback?: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>|void { + request?: protos.google.showcase.v1beta1.IWaitRequest, + optionsOrCallback?: + | CallOptions + | Callback< + LROperation< + protos.google.showcase.v1beta1.IWaitResponse, + protos.google.showcase.v1beta1.IWaitMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + callback?: Callback< + LROperation< + protos.google.showcase.v1beta1.IWaitResponse, + protos.google.showcase.v1beta1.IWaitMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + LROperation< + protos.google.showcase.v1beta1.IWaitResponse, + protos.google.showcase.v1beta1.IWaitMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize().catch(err => {throw err}); - const wrappedCallback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>|undefined = callback + this.initialize().catch((err) => { + throw err; + }); + const wrappedCallback: + | Callback< + LROperation< + protos.google.showcase.v1beta1.IWaitResponse, + protos.google.showcase.v1beta1.IWaitMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, rawResponse, _) => { this._log.info('wait response %j', rawResponse); callback!(error, response, rawResponse, _); // We verified `callback` above. } : undefined; this._log.info('wait request %j', request); - return this.innerApiCalls.wait(request, options, wrappedCallback) - ?.then(([response, rawResponse, _]: [ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]) => { - this._log.info('wait response %j', rawResponse); - return [response, rawResponse, _]; - }); + return this.innerApiCalls + .wait(request, options, wrappedCallback) + ?.then( + ([response, rawResponse, _]: [ + LROperation< + protos.google.showcase.v1beta1.IWaitResponse, + protos.google.showcase.v1beta1.IWaitMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ]) => { + this._log.info('wait response %j', rawResponse); + return [response, rawResponse, _]; + }, + ); } -/** - * Check the status of the long running operation returned by `wait()`. - * @param {String} name - * The operation name that will be passed. - * @returns {Promise} - The promise which resolves to an object. - * The decoded operation object has result and metadata field to get information from. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/echo.wait.js - * region_tag:localhost_v1beta1_generated_Echo_Wait_async - */ - async checkWaitProgress(name: string): Promise>{ + /** + * Check the status of the long running operation returned by `wait()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/echo.wait.js + * region_tag:localhost_v1beta1_generated_Echo_Wait_async + */ + async checkWaitProgress( + name: string, + ): Promise< + LROperation< + protos.google.showcase.v1beta1.WaitResponse, + protos.google.showcase.v1beta1.WaitMetadata + > + > { this._log.info('wait long-running'); - const request = new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest({name}); + const request = + new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( + { name }, + ); const [operation] = await this.operationsClient.getOperation(request); - const decodeOperation = new this._gaxModule.Operation(operation, this.descriptors.longrunning.wait, this._gaxModule.createDefaultBackoffSettings()); - return decodeOperation as LROperation; + const decodeOperation = new this._gaxModule.Operation( + operation, + this.descriptors.longrunning.wait, + this._gaxModule.createDefaultBackoffSettings(), + ); + return decodeOperation as LROperation< + protos.google.showcase.v1beta1.WaitResponse, + protos.google.showcase.v1beta1.WaitMetadata + >; } - /** - * This is similar to the Expand method but instead of returning a stream of - * expanded words, this method returns a paged list of expanded words. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.content - * The string to expand. - * @param {number} request.pageSize - * The number of words to returned in each page. - * @param {string} request.pageToken - * The position of the page to be returned. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.showcase.v1beta1.EchoResponse|EchoResponse}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `pagedExpandAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * This is similar to the Expand method but instead of returning a stream of + * expanded words, this method returns a paged list of expanded words. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.content + * The string to expand. + * @param {number} request.pageSize + * The number of words to returned in each page. + * @param {string} request.pageToken + * The position of the page to be returned. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.showcase.v1beta1.EchoResponse|EchoResponse}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `pagedExpandAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ pagedExpand( - request?: protos.google.showcase.v1beta1.IPagedExpandRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IEchoResponse[], - protos.google.showcase.v1beta1.IPagedExpandRequest|null, - protos.google.showcase.v1beta1.IPagedExpandResponse - ]>; + request?: protos.google.showcase.v1beta1.IPagedExpandRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IEchoResponse[], + protos.google.showcase.v1beta1.IPagedExpandRequest | null, + protos.google.showcase.v1beta1.IPagedExpandResponse, + ] + >; pagedExpand( - request: protos.google.showcase.v1beta1.IPagedExpandRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.showcase.v1beta1.IPagedExpandRequest, - protos.google.showcase.v1beta1.IPagedExpandResponse|null|undefined, - protos.google.showcase.v1beta1.IEchoResponse>): void; + request: protos.google.showcase.v1beta1.IPagedExpandRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.showcase.v1beta1.IPagedExpandRequest, + protos.google.showcase.v1beta1.IPagedExpandResponse | null | undefined, + protos.google.showcase.v1beta1.IEchoResponse + >, + ): void; pagedExpand( - request: protos.google.showcase.v1beta1.IPagedExpandRequest, - callback: PaginationCallback< - protos.google.showcase.v1beta1.IPagedExpandRequest, - protos.google.showcase.v1beta1.IPagedExpandResponse|null|undefined, - protos.google.showcase.v1beta1.IEchoResponse>): void; + request: protos.google.showcase.v1beta1.IPagedExpandRequest, + callback: PaginationCallback< + protos.google.showcase.v1beta1.IPagedExpandRequest, + protos.google.showcase.v1beta1.IPagedExpandResponse | null | undefined, + protos.google.showcase.v1beta1.IEchoResponse + >, + ): void; pagedExpand( - request?: protos.google.showcase.v1beta1.IPagedExpandRequest, - optionsOrCallback?: CallOptions|PaginationCallback< + request?: protos.google.showcase.v1beta1.IPagedExpandRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.showcase.v1beta1.IPagedExpandRequest, - protos.google.showcase.v1beta1.IPagedExpandResponse|null|undefined, - protos.google.showcase.v1beta1.IEchoResponse>, - callback?: PaginationCallback< - protos.google.showcase.v1beta1.IPagedExpandRequest, - protos.google.showcase.v1beta1.IPagedExpandResponse|null|undefined, - protos.google.showcase.v1beta1.IEchoResponse>): - Promise<[ - protos.google.showcase.v1beta1.IEchoResponse[], - protos.google.showcase.v1beta1.IPagedExpandRequest|null, - protos.google.showcase.v1beta1.IPagedExpandResponse - ]>|void { + | protos.google.showcase.v1beta1.IPagedExpandResponse + | null + | undefined, + protos.google.showcase.v1beta1.IEchoResponse + >, + callback?: PaginationCallback< + protos.google.showcase.v1beta1.IPagedExpandRequest, + protos.google.showcase.v1beta1.IPagedExpandResponse | null | undefined, + protos.google.showcase.v1beta1.IEchoResponse + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IEchoResponse[], + protos.google.showcase.v1beta1.IPagedExpandRequest | null, + protos.google.showcase.v1beta1.IPagedExpandResponse, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.showcase.v1beta1.IPagedExpandRequest, - protos.google.showcase.v1beta1.IPagedExpandResponse|null|undefined, - protos.google.showcase.v1beta1.IEchoResponse>|undefined = callback + this.initialize().catch((err) => { + throw err; + }); + const wrappedCallback: + | PaginationCallback< + protos.google.showcase.v1beta1.IPagedExpandRequest, + | protos.google.showcase.v1beta1.IPagedExpandResponse + | null + | undefined, + protos.google.showcase.v1beta1.IEchoResponse + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('pagedExpand values %j', values); callback!(error, values, nextPageRequest, rawResponse); @@ -1125,96 +1427,102 @@ export class EchoClient { this._log.info('pagedExpand request %j', request); return this.innerApiCalls .pagedExpand(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.showcase.v1beta1.IEchoResponse[], - protos.google.showcase.v1beta1.IPagedExpandRequest|null, - protos.google.showcase.v1beta1.IPagedExpandResponse - ]) => { - this._log.info('pagedExpand values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.showcase.v1beta1.IEchoResponse[], + protos.google.showcase.v1beta1.IPagedExpandRequest | null, + protos.google.showcase.v1beta1.IPagedExpandResponse, + ]) => { + this._log.info('pagedExpand values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `pagedExpand`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.content - * The string to expand. - * @param {number} request.pageSize - * The number of words to returned in each page. - * @param {string} request.pageToken - * The position of the page to be returned. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.showcase.v1beta1.EchoResponse|EchoResponse} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `pagedExpandAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `pagedExpand`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.content + * The string to expand. + * @param {number} request.pageSize + * The number of words to returned in each page. + * @param {string} request.pageToken + * The position of the page to be returned. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.showcase.v1beta1.EchoResponse|EchoResponse} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `pagedExpandAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ pagedExpandStream( - request?: protos.google.showcase.v1beta1.IPagedExpandRequest, - options?: CallOptions): - Transform{ + request?: protos.google.showcase.v1beta1.IPagedExpandRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; const defaultCallSettings = this._defaults['pagedExpand']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('pagedExpand stream %j', request); return this.descriptors.page.pagedExpand.createStream( this.innerApiCalls.pagedExpand as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `pagedExpand`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.content - * The string to expand. - * @param {number} request.pageSize - * The number of words to returned in each page. - * @param {string} request.pageToken - * The position of the page to be returned. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.showcase.v1beta1.EchoResponse|EchoResponse}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/echo.paged_expand.js - * region_tag:localhost_v1beta1_generated_Echo_PagedExpand_async - */ + /** + * Equivalent to `pagedExpand`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.content + * The string to expand. + * @param {number} request.pageSize + * The number of words to returned in each page. + * @param {string} request.pageToken + * The position of the page to be returned. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.showcase.v1beta1.EchoResponse|EchoResponse}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/echo.paged_expand.js + * region_tag:localhost_v1beta1_generated_Echo_PagedExpand_async + */ pagedExpandAsync( - request?: protos.google.showcase.v1beta1.IPagedExpandRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.showcase.v1beta1.IPagedExpandRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; const defaultCallSettings = this._defaults['pagedExpand']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('pagedExpand iterate %j', request); return this.descriptors.page.pagedExpand.asyncIterate( this.innerApiCalls['pagedExpand'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } @@ -1226,7 +1534,7 @@ export class EchoClient { */ close(): Promise { if (this.echoStub && !this._terminated) { - return this.echoStub.then(stub => { + return this.echoStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -1235,4 +1543,4 @@ export class EchoClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/core/generator/gapic-generator-typescript/baselines/showcase-legacy-esm/esm/src/v1beta1/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/showcase-legacy-esm/esm/src/v1beta1/index.ts.baseline index 54412c29f55d..77bbfee7c61f 100644 --- a/core/generator/gapic-generator-typescript/baselines/showcase-legacy-esm/esm/src/v1beta1/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/showcase-legacy-esm/esm/src/v1beta1/index.ts.baseline @@ -16,4 +16,4 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -export {EchoClient} from './echo_client.js'; +export { EchoClient } from './echo_client.js'; diff --git a/core/generator/gapic-generator-typescript/baselines/showcase-legacy-esm/esm/system-test/fixtures/sample/src/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/showcase-legacy-esm/esm/system-test/fixtures/sample/src/index.ts.baseline index 1e660d0737f9..6db36b5f887a 100644 --- a/core/generator/gapic-generator-typescript/baselines/showcase-legacy-esm/esm/system-test/fixtures/sample/src/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/showcase-legacy-esm/esm/system-test/fixtures/sample/src/index.ts.baseline @@ -17,7 +17,7 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -import {EchoClient} from 'showcase'; +import { EchoClient } from 'showcase'; // check that the client class type name can be used function doStuffWithEchoClient(client: EchoClient) { diff --git a/core/generator/gapic-generator-typescript/baselines/showcase-legacy-esm/esm/system-test/install.ts.baseline b/core/generator/gapic-generator-typescript/baselines/showcase-legacy-esm/esm/system-test/install.ts.baseline index e079c4fa1101..d109fdd8c97f 100644 --- a/core/generator/gapic-generator-typescript/baselines/showcase-legacy-esm/esm/system-test/install.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/showcase-legacy-esm/esm/system-test/install.ts.baseline @@ -16,40 +16,45 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -import {packNTest} from 'pack-n-play'; -import {readFileSync} from 'fs'; -import {describe, it} from 'mocha'; +import { packNTest } from 'pack-n-play'; +import { readFileSync } from 'fs'; +import { describe, it } from 'mocha'; describe('📦 pack-n-play test', () => { - it('TypeScript', async function() { + it('TypeScript', async function () { this.timeout(300000); await packNTest({ packageDir: process.cwd(), sample: { description: 'TypeScript user can use the type definitions', - ts: readFileSync('./esm/system-test/fixtures/sample/src/index.ts').toString() - } + ts: readFileSync( + './esm/system-test/fixtures/sample/src/index.ts', + ).toString(), + }, }); }); - it('ESM module', async function() { + it('ESM module', async function () { this.timeout(300000); await packNTest({ sample: { description: 'Should be able to import using ESM', - esm: readFileSync('./esm/system-test/fixtures/sample/src/index.js').toString(), + esm: readFileSync( + './esm/system-test/fixtures/sample/src/index.js', + ).toString(), }, }); }); - it('CJS module', async function() { + it('CJS module', async function () { this.timeout(300000); await packNTest({ sample: { description: 'Should be able to import using CJS', - cjs: readFileSync('./esm/system-test/fixtures/sample/src/index.cjs').toString(), + cjs: readFileSync( + './esm/system-test/fixtures/sample/src/index.cjs', + ).toString(), }, }); }); - }); diff --git a/core/generator/gapic-generator-typescript/baselines/showcase-legacy-esm/esm/test/gapic_echo_v1beta1.ts.baseline b/core/generator/gapic-generator-typescript/baselines/showcase-legacy-esm/esm/test/gapic_echo_v1beta1.ts.baseline index 047db4ae9dda..0b14994fe785 100644 --- a/core/generator/gapic-generator-typescript/baselines/showcase-legacy-esm/esm/test/gapic_echo_v1beta1.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/showcase-legacy-esm/esm/test/gapic_echo_v1beta1.ts.baseline @@ -20,1092 +20,1340 @@ import * as protos from '../../protos/protos.js'; import assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as echoModule from '../src/index.js'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; -import {protobuf, LROperation, operationsProtos} from 'google-gax'; +import { protobuf, LROperation, operationsProtos } from 'google-gax'; // eslint-disable-next-line @typescript-eslint/no-unused-vars function getTypeDefaultValue(typeName: string, fields: string[]) { - // non-string x-goog-request-param values are not supported; - // we always assume that it's a string. - return ''; + // non-string x-goog-request-param values are not supported; + // we always assume that it's a string. + return ''; } function generateSampleMessage(instance: T) { - const filledObject = (instance.constructor as typeof protobuf.Message) - .toObject(instance as protobuf.Message, {defaults: true}); - return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, { defaults: true }); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; } function stubSimpleCall(response?: ResponseType, error?: Error) { - return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); } -function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { - return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +function stubSimpleCallWithCallback( + response?: ResponseType, + error?: Error, +) { + return error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); } -function stubServerStreamingCall(response?: ResponseType, error?: Error) { - const transformStub = error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); - const mockStream = new PassThrough({ - objectMode: true, - transform: transformStub, - }); - // write something to the stream to trigger transformStub and send the response back to the client - setImmediate(() => { mockStream.write({}); }); - setImmediate(() => { mockStream.end(); }); - return sinon.stub().returns(mockStream); +function stubServerStreamingCall( + response?: ResponseType, + error?: Error, +) { + const transformStub = error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + // write something to the stream to trigger transformStub and send the response back to the client + setImmediate(() => { + mockStream.write({}); + }); + setImmediate(() => { + mockStream.end(); + }); + return sinon.stub().returns(mockStream); } -function stubBidiStreamingCall(response?: ResponseType, error?: Error) { - const transformStub = error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); - const mockStream = new PassThrough({ - objectMode: true, - transform: transformStub, - }); - return sinon.stub().returns(mockStream); +function stubBidiStreamingCall( + response?: ResponseType, + error?: Error, +) { + const transformStub = error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + return sinon.stub().returns(mockStream); } -function stubClientStreamingCall(response?: ResponseType, error?: Error) { - if (error) { - return sinon.stub().callsArgWith(2, error); - } - const transformStub = sinon.stub(); - const mockStream = new PassThrough({ - objectMode: true, - transform: transformStub, - }); - return sinon.stub().returns(mockStream).callsArgWith(2, null, response); +function stubClientStreamingCall( + response?: ResponseType, + error?: Error, +) { + if (error) { + return sinon.stub().callsArgWith(2, error); + } + const transformStub = sinon.stub(); + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + return sinon.stub().returns(mockStream).callsArgWith(2, null, response); } -function stubLongRunningCall(response?: ResponseType, callError?: Error, lroError?: Error) { - const innerStub = lroError ? sinon.stub().rejects(lroError) : sinon.stub().resolves([response]); - const mockOperation = { - promise: innerStub, - }; - return callError ? sinon.stub().rejects(callError) : sinon.stub().resolves([mockOperation]); +function stubLongRunningCall( + response?: ResponseType, + callError?: Error, + lroError?: Error, +) { + const innerStub = lroError + ? sinon.stub().rejects(lroError) + : sinon.stub().resolves([response]); + const mockOperation = { + promise: innerStub, + }; + return callError + ? sinon.stub().rejects(callError) + : sinon.stub().resolves([mockOperation]); } -function stubLongRunningCallWithCallback(response?: ResponseType, callError?: Error, lroError?: Error) { - const innerStub = lroError ? sinon.stub().rejects(lroError) : sinon.stub().resolves([response]); - const mockOperation = { - promise: innerStub, - }; - return callError ? sinon.stub().callsArgWith(2, callError) : sinon.stub().callsArgWith(2, null, mockOperation); +function stubLongRunningCallWithCallback( + response?: ResponseType, + callError?: Error, + lroError?: Error, +) { + const innerStub = lroError + ? sinon.stub().rejects(lroError) + : sinon.stub().resolves([response]); + const mockOperation = { + promise: innerStub, + }; + return callError + ? sinon.stub().callsArgWith(2, callError) + : sinon.stub().callsArgWith(2, null, mockOperation); } -function stubPageStreamingCall(responses?: ResponseType[], error?: Error) { - const pagingStub = sinon.stub(); - if (responses) { - for (let i = 0; i < responses.length; ++i) { - pagingStub.onCall(i).callsArgWith(2, null, responses[i]); - } +function stubPageStreamingCall( + responses?: ResponseType[], + error?: Error, +) { + const pagingStub = sinon.stub(); + if (responses) { + for (let i = 0; i < responses.length; ++i) { + pagingStub.onCall(i).callsArgWith(2, null, responses[i]); } - const transformStub = error ? sinon.stub().callsArgWith(2, error) : pagingStub; - const mockStream = new PassThrough({ - objectMode: true, - transform: transformStub, - }); - // trigger as many responses as needed - if (responses) { - for (let i = 0; i < responses.length; ++i) { - setImmediate(() => { mockStream.write({}); }); - } - setImmediate(() => { mockStream.end(); }); - } else { - setImmediate(() => { mockStream.write({}); }); - setImmediate(() => { mockStream.end(); }); + } + const transformStub = error + ? sinon.stub().callsArgWith(2, error) + : pagingStub; + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + // trigger as many responses as needed + if (responses) { + for (let i = 0; i < responses.length; ++i) { + setImmediate(() => { + mockStream.write({}); + }); } - return sinon.stub().returns(mockStream); + setImmediate(() => { + mockStream.end(); + }); + } else { + setImmediate(() => { + mockStream.write({}); + }); + setImmediate(() => { + mockStream.end(); + }); + } + return sinon.stub().returns(mockStream); } -function stubAsyncIterationCall(responses?: ResponseType[], error?: Error) { - let counter = 0; - const asyncIterable = { - [Symbol.asyncIterator]() { - return { - async next() { - if (error) { - return Promise.reject(error); - } - if (counter >= responses!.length) { - return Promise.resolve({done: true, value: undefined}); - } - return Promise.resolve({done: false, value: responses![counter++]}); - } - }; - } - }; - return sinon.stub().returns(asyncIterable); +function stubAsyncIterationCall( + responses?: ResponseType[], + error?: Error, +) { + let counter = 0; + const asyncIterable = { + [Symbol.asyncIterator]() { + return { + async next() { + if (error) { + return Promise.reject(error); + } + if (counter >= responses!.length) { + return Promise.resolve({ done: true, value: undefined }); + } + return Promise.resolve({ done: false, value: responses![counter++] }); + }, + }; + }, + }; + return sinon.stub().returns(asyncIterable); } describe('v1beta1.EchoClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new echoModule.v1beta1.EchoClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'localhost'); - }); - - it('has universeDomain', () => { - const client = new echoModule.v1beta1.EchoClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); - - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - it('throws DeprecationWarning if static servicePath is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const servicePath = echoModule.v1beta1.EchoClient.servicePath; - assert.strictEqual(servicePath, 'localhost'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = echoModule.v1beta1.EchoClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'localhost'); - assert(stub.called); - stub.restore(); - }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { new echoModule.v1beta1.EchoClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); - - it('has port', () => { - const port = echoModule.v1beta1.EchoClient.port; - assert(port); - assert(typeof port === 'number'); - }); - - it('should create a client with no option', () => { - const client = new echoModule.v1beta1.EchoClient(); - assert(client); - }); - - it('has initialize method and supports deferred initialization', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.echoStub, undefined); - await client.initialize(); - assert(client.echoStub); - }); - - it('has close method for the initialized client', done => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.echoStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); - - it('has close method for the non-initialized client', done => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.echoStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new echoModule.v1beta1.EchoClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'localhost'); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); - }); + it('has universeDomain', () => { + const client = new echoModule.v1beta1.EchoClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId((err?: Error|null, projectId?: string|null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } - }); - }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = echoModule.v1beta1.EchoClient.servicePath; + assert.strictEqual(servicePath, 'localhost'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = echoModule.v1beta1.EchoClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'localhost'); + assert(stub.called); + stub.restore(); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new echoModule.v1beta1.EchoClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); }); - describe('echo', () => { - it('invokes echo without error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.EchoRequest() - ); - // path template: {qux=projects/*}/** - request.otherHeader = 'projects/value/value'; - const expectedHeaderRequestParams = 'qux=projects%2Fvalue'; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.EchoResponse() - ); - client.innerApiCalls.echo = stubSimpleCall(expectedResponse); - const [response] = await client.echo(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.echo as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.echo as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has port', () => { + const port = echoModule.v1beta1.EchoClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('invokes echo without error using callback', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.EchoRequest() - ); - // path template: {qux=projects/*}/** - request.otherHeader = 'projects/value/value'; - const expectedHeaderRequestParams = 'qux=projects%2Fvalue'; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.EchoResponse() - ); - client.innerApiCalls.echo = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.echo( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IEchoResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.echo as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.echo as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('should create a client with no option', () => { + const client = new echoModule.v1beta1.EchoClient(); + assert(client); + }); - it('invokes echo with error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.EchoRequest() - ); - // path template: {qux=projects/*}/** - request.otherHeader = 'projects/value/value'; - const expectedHeaderRequestParams = 'qux=projects%2Fvalue'; - const expectedError = new Error('expected'); - client.innerApiCalls.echo = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.echo(request), expectedError); - const actualRequest = (client.innerApiCalls.echo as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.echo as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has initialize method and supports deferred initialization', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.echoStub, undefined); + await client.initialize(); + assert(client.echoStub); + }); - it('invokes echo with closed client', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.EchoRequest() - ); - // path template: {qux=projects/*}/** - request.otherHeader = 'projects/value/value'; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.echo(request), expectedError); + it('has close method for the initialized client', (done) => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.echoStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); }); - describe('echoErrorDetails', () => { - it('invokes echoErrorDetails without error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.EchoErrorDetailsRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.EchoErrorDetailsResponse() - ); - client.innerApiCalls.echoErrorDetails = stubSimpleCall(expectedResponse); - const [response] = await client.echoErrorDetails(request); - assert.deepStrictEqual(response, expectedResponse); + it('has close method for the non-initialized client', (done) => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.echoStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes echoErrorDetails without error using callback', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.EchoErrorDetailsRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.EchoErrorDetailsResponse() - ); - client.innerApiCalls.echoErrorDetails = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.echoErrorDetails( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IEchoErrorDetailsResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + }); - it('invokes echoErrorDetails with error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.EchoErrorDetailsRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.echoErrorDetails = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.echoErrorDetails(request), expectedError); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + }); + + describe('echo', () => { + it('invokes echo without error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.EchoRequest(), + ); + // path template: {qux=projects/*}/** + request.otherHeader = 'projects/value/value'; + const expectedHeaderRequestParams = 'qux=projects%2Fvalue'; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.EchoResponse(), + ); + client.innerApiCalls.echo = stubSimpleCall(expectedResponse); + const [response] = await client.echo(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.echo as SinonStub).getCall(0) + .args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.echo as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes echoErrorDetails with closed client', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.EchoErrorDetailsRequest() - ); - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.echoErrorDetails(request), expectedError); - }); + it('invokes echo without error using callback', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.EchoRequest(), + ); + // path template: {qux=projects/*}/** + request.otherHeader = 'projects/value/value'; + const expectedHeaderRequestParams = 'qux=projects%2Fvalue'; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.EchoResponse(), + ); + client.innerApiCalls.echo = stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.echo( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IEchoResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.echo as SinonStub).getCall(0) + .args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.echo as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('pagedExpandLegacy', () => { - it('invokes pagedExpandLegacy without error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.PagedExpandLegacyRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.PagedExpandResponse() - ); - client.innerApiCalls.pagedExpandLegacy = stubSimpleCall(expectedResponse); - const [response] = await client.pagedExpandLegacy(request); - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes echo with error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.EchoRequest(), + ); + // path template: {qux=projects/*}/** + request.otherHeader = 'projects/value/value'; + const expectedHeaderRequestParams = 'qux=projects%2Fvalue'; + const expectedError = new Error('expected'); + client.innerApiCalls.echo = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.echo(request), expectedError); + const actualRequest = (client.innerApiCalls.echo as SinonStub).getCall(0) + .args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.echo as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes pagedExpandLegacy without error using callback', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.PagedExpandLegacyRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.PagedExpandResponse() - ); - client.innerApiCalls.pagedExpandLegacy = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.pagedExpandLegacy( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IPagedExpandResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes echo with closed client', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.EchoRequest(), + ); + // path template: {qux=projects/*}/** + request.otherHeader = 'projects/value/value'; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.echo(request), expectedError); + }); + }); + + describe('echoErrorDetails', () => { + it('invokes echoErrorDetails without error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.EchoErrorDetailsRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.EchoErrorDetailsResponse(), + ); + client.innerApiCalls.echoErrorDetails = stubSimpleCall(expectedResponse); + const [response] = await client.echoErrorDetails(request); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes pagedExpandLegacy with error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.PagedExpandLegacyRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.pagedExpandLegacy = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.pagedExpandLegacy(request), expectedError); - }); + it('invokes echoErrorDetails without error using callback', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.EchoErrorDetailsRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.EchoErrorDetailsResponse(), + ); + client.innerApiCalls.echoErrorDetails = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.echoErrorDetails( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IEchoErrorDetailsResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes pagedExpandLegacy with closed client', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.PagedExpandLegacyRequest() - ); - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.pagedExpandLegacy(request), expectedError); - }); + it('invokes echoErrorDetails with error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.EchoErrorDetailsRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.echoErrorDetails = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.echoErrorDetails(request), expectedError); }); - describe('block', () => { - it('invokes block without error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.BlockRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.BlockResponse() - ); - client.innerApiCalls.block = stubSimpleCall(expectedResponse); - const [response] = await client.block(request); - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes echoErrorDetails with closed client', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.EchoErrorDetailsRequest(), + ); + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.echoErrorDetails(request), expectedError); + }); + }); + + describe('pagedExpandLegacy', () => { + it('invokes pagedExpandLegacy without error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.PagedExpandLegacyRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.PagedExpandResponse(), + ); + client.innerApiCalls.pagedExpandLegacy = stubSimpleCall(expectedResponse); + const [response] = await client.pagedExpandLegacy(request); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes block without error using callback', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.BlockRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.BlockResponse() - ); - client.innerApiCalls.block = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.block( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IBlockResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes pagedExpandLegacy without error using callback', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.PagedExpandLegacyRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.PagedExpandResponse(), + ); + client.innerApiCalls.pagedExpandLegacy = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.pagedExpandLegacy( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IPagedExpandResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes block with error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.BlockRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.block = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.block(request), expectedError); - }); + it('invokes pagedExpandLegacy with error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.PagedExpandLegacyRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.pagedExpandLegacy = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.pagedExpandLegacy(request), expectedError); + }); - it('invokes block with closed client', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.BlockRequest() - ); - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.block(request), expectedError); - }); + it('invokes pagedExpandLegacy with closed client', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.PagedExpandLegacyRequest(), + ); + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.pagedExpandLegacy(request), expectedError); + }); + }); + + describe('block', () => { + it('invokes block without error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.BlockRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.BlockResponse(), + ); + client.innerApiCalls.block = stubSimpleCall(expectedResponse); + const [response] = await client.block(request); + assert.deepStrictEqual(response, expectedResponse); }); - describe('wait', () => { - it('invokes wait without error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.WaitRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.wait = stubLongRunningCall(expectedResponse); - const [operation] = await client.wait(request); - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes block without error using callback', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.BlockRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.BlockResponse(), + ); + client.innerApiCalls.block = stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.block( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IBlockResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes wait without error using callback', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.WaitRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.wait = stubLongRunningCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.wait( - request, - (err?: Error|null, - result?: LROperation|null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const operation = await promise as LROperation; - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes block with error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.BlockRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.block = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.block(request), expectedError); + }); - it('invokes wait with call error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.WaitRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.wait = stubLongRunningCall(undefined, expectedError); - await assert.rejects(client.wait(request), expectedError); - }); + it('invokes block with closed client', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.BlockRequest(), + ); + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.block(request), expectedError); + }); + }); + + describe('wait', () => { + it('invokes wait without error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.WaitRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.wait = stubLongRunningCall(expectedResponse); + const [operation] = await client.wait(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes wait with LRO error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.WaitRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.wait = stubLongRunningCall(undefined, undefined, expectedError); - const [operation] = await client.wait(request); - await assert.rejects(operation.promise(), expectedError); - }); + it('invokes wait without error using callback', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.WaitRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.wait = + stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.wait( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.showcase.v1beta1.IWaitResponse, + protos.google.showcase.v1beta1.IWaitMetadata + > | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const operation = (await promise) as LROperation< + protos.google.showcase.v1beta1.IWaitResponse, + protos.google.showcase.v1beta1.IWaitMetadata + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes checkWaitProgress without error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedResponse = generateSampleMessage( - new operationsProtos.google.longrunning.Operation() - ); - expectedResponse.name = 'test'; - expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; - expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')} - - client.operationsClient.getOperation = stubSimpleCall(expectedResponse); - const decodedOperation = await client.checkWaitProgress(expectedResponse.name); - assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); - assert(decodedOperation.metadata); - assert((client.operationsClient.getOperation as SinonStub).getCall(0)); - }); + it('invokes wait with call error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.WaitRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.wait = stubLongRunningCall(undefined, expectedError); + await assert.rejects(client.wait(request), expectedError); + }); - it('invokes checkWaitProgress with error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedError = new Error('expected'); - - client.operationsClient.getOperation = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.checkWaitProgress(''), expectedError); - assert((client.operationsClient.getOperation as SinonStub) - .getCall(0)); - }); + it('invokes wait with LRO error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.WaitRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.wait = stubLongRunningCall( + undefined, + undefined, + expectedError, + ); + const [operation] = await client.wait(request); + await assert.rejects(operation.promise(), expectedError); }); - describe('expand', () => { - it('invokes expand without error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ExpandRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.EchoResponse() - ); - client.innerApiCalls.expand = stubServerStreamingCall(expectedResponse); - const stream = client.expand(request); - const promise = new Promise((resolve, reject) => { - stream.on('data', (response: protos.google.showcase.v1beta1.EchoResponse) => { - resolve(response); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes checkWaitProgress without error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation(), + ); + expectedResponse.name = 'test'; + expectedResponse.response = { type_url: 'url', value: Buffer.from('') }; + expectedResponse.metadata = { type_url: 'url', value: Buffer.from('') }; + + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const decodedOperation = await client.checkWaitProgress( + expectedResponse.name, + ); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); - it('invokes expand without error and gaxServerStreamingRetries enabled', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ExpandRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.EchoResponse() - ); - client.innerApiCalls.expand = stubServerStreamingCall(expectedResponse); - const stream = client.expand(request); - const promise = new Promise((resolve, reject) => { - stream.on('data', (response: protos.google.showcase.v1beta1.EchoResponse) => { - resolve(response); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); + it('invokes checkWaitProgress with error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const expectedError = new Error('expected'); + + client.operationsClient.getOperation = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.checkWaitProgress(''), expectedError); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + }); + + describe('expand', () => { + it('invokes expand without error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ExpandRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.EchoResponse(), + ); + client.innerApiCalls.expand = stubServerStreamingCall(expectedResponse); + const stream = client.expand(request); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + (response: protos.google.showcase.v1beta1.EchoResponse) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes expand with error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ExpandRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.expand = stubServerStreamingCall(undefined, expectedError); - const stream = client.expand(request); - const promise = new Promise((resolve, reject) => { - stream.on('data', (response: protos.google.showcase.v1beta1.EchoResponse) => { - resolve(response); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); + it('invokes expand without error and gaxServerStreamingRetries enabled', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ExpandRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.EchoResponse(), + ); + client.innerApiCalls.expand = stubServerStreamingCall(expectedResponse); + const stream = client.expand(request); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + (response: protos.google.showcase.v1beta1.EchoResponse) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes expand with closed client', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ExpandRequest() - ); - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - const stream = client.expand(request, {retryRequestOptions: {noResponseRetries: 0}}); - const promise = new Promise((resolve, reject) => { - stream.on('data', (response: protos.google.showcase.v1beta1.EchoResponse) => { - resolve(response); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - }); - it('should create a client with gaxServerStreamingRetries enabled', () => { - const client = new echoModule.v1beta1.EchoClient({ - gaxServerStreamingRetries: true, - }); - assert(client); + it('invokes expand with error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ExpandRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.expand = stubServerStreamingCall( + undefined, + expectedError, + ); + const stream = client.expand(request); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + (response: protos.google.showcase.v1beta1.EchoResponse) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); }); + }); + await assert.rejects(promise, expectedError); }); - describe('chat', () => { - it('invokes chat without error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.EchoRequest() - ); - - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.EchoResponse() - ); - client.innerApiCalls.chat = stubBidiStreamingCall(expectedResponse); - const stream = client.chat(); - const promise = new Promise((resolve, reject) => { - stream.on('data', (response: protos.google.showcase.v1beta1.EchoResponse) => { - resolve(response); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - stream.write(request); - stream.end(); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - assert((client.innerApiCalls.chat as SinonStub) - .getCall(0).calledWith(null)); - assert.deepStrictEqual(((stream as unknown as PassThrough) - ._transform as SinonStub).getCall(0).args[0], request); + it('invokes expand with closed client', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ExpandRequest(), + ); + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + const stream = client.expand(request, { + retryRequestOptions: { noResponseRetries: 0 }, + }); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + (response: protos.google.showcase.v1beta1.EchoResponse) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); }); - - it('invokes chat with error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.EchoRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.chat = stubBidiStreamingCall(undefined, expectedError); - const stream = client.chat(); - const promise = new Promise((resolve, reject) => { - stream.on('data', (response: protos.google.showcase.v1beta1.EchoResponse) => { - resolve(response); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - stream.write(request); - stream.end(); - }); - await assert.rejects(promise, expectedError); - assert((client.innerApiCalls.chat as SinonStub) - .getCall(0).calledWith(null)); - assert.deepStrictEqual(((stream as unknown as PassThrough) - ._transform as SinonStub).getCall(0).args[0], request); + }); + await assert.rejects(promise, expectedError); + }); + it('should create a client with gaxServerStreamingRetries enabled', () => { + const client = new echoModule.v1beta1.EchoClient({ + gaxServerStreamingRetries: true, + }); + assert(client); + }); + }); + + describe('chat', () => { + it('invokes chat without error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.EchoRequest(), + ); + + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.EchoResponse(), + ); + client.innerApiCalls.chat = stubBidiStreamingCall(expectedResponse); + const stream = client.chat(); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + (response: protos.google.showcase.v1beta1.EchoResponse) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); }); + stream.write(request); + stream.end(); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + assert( + (client.innerApiCalls.chat as SinonStub).getCall(0).calledWith(null), + ); + assert.deepStrictEqual( + ((stream as unknown as PassThrough)._transform as SinonStub).getCall(0) + .args[0], + request, + ); }); - describe('collect', () => { - it('invokes collect without error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.EchoRequest() - ); - - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.EchoResponse() - ); - client.innerApiCalls.collect = stubClientStreamingCall(expectedResponse); - let stream: PassThrough; - const promise = new Promise((resolve, reject) => { - stream = client.collect( - (err?: Error|null, result?: protos.google.showcase.v1beta1.IEchoResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }) as unknown as PassThrough; - stream.write(request); - stream.end(); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - assert((client.innerApiCalls.collect as SinonStub) - .getCall(0).calledWith(null, {} /*, callback defined above */)); - assert.deepStrictEqual((stream!._transform as SinonStub).getCall(0).args[0], request); + it('invokes chat with error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.EchoRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.chat = stubBidiStreamingCall( + undefined, + expectedError, + ); + const stream = client.chat(); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + (response: protos.google.showcase.v1beta1.EchoResponse) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); }); + stream.write(request); + stream.end(); + }); + await assert.rejects(promise, expectedError); + assert( + (client.innerApiCalls.chat as SinonStub).getCall(0).calledWith(null), + ); + assert.deepStrictEqual( + ((stream as unknown as PassThrough)._transform as SinonStub).getCall(0) + .args[0], + request, + ); + }); + }); + + describe('collect', () => { + it('invokes collect without error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.EchoRequest(), + ); + + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.EchoResponse(), + ); + client.innerApiCalls.collect = stubClientStreamingCall(expectedResponse); + let stream: PassThrough; + const promise = new Promise((resolve, reject) => { + stream = client.collect( + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IEchoResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ) as unknown as PassThrough; + stream.write(request); + stream.end(); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + assert( + (client.innerApiCalls.collect as SinonStub) + .getCall(0) + .calledWith(null, {} /*, callback defined above */), + ); + assert.deepStrictEqual( + (stream!._transform as SinonStub).getCall(0).args[0], + request, + ); + }); - it('invokes collect with error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.EchoRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.collect = stubClientStreamingCall(undefined, expectedError); - let stream: PassThrough; - const promise = new Promise((resolve, reject) => { - stream = client.collect( - (err?: Error|null, result?: protos.google.showcase.v1beta1.IEchoResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }) as unknown as PassThrough; - stream.write(request); - stream.end(); - }); - await assert.rejects(promise, expectedError); - assert((client.innerApiCalls.collect as SinonStub) - .getCall(0).calledWith(null, {} /*, callback defined above */)); - }); + it('invokes collect with error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.EchoRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.collect = stubClientStreamingCall( + undefined, + expectedError, + ); + let stream: PassThrough; + const promise = new Promise((resolve, reject) => { + stream = client.collect( + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IEchoResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ) as unknown as PassThrough; + stream.write(request); + stream.end(); + }); + await assert.rejects(promise, expectedError); + assert( + (client.innerApiCalls.collect as SinonStub) + .getCall(0) + .calledWith(null, {} /*, callback defined above */), + ); + }); + }); + + describe('pagedExpand', () => { + it('invokes pagedExpand without error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.PagedExpandRequest(), + ); + const expectedResponse = [ + generateSampleMessage( + new protos.google.showcase.v1beta1.EchoResponse(), + ), + generateSampleMessage( + new protos.google.showcase.v1beta1.EchoResponse(), + ), + generateSampleMessage( + new protos.google.showcase.v1beta1.EchoResponse(), + ), + ]; + client.innerApiCalls.pagedExpand = stubSimpleCall(expectedResponse); + const [response] = await client.pagedExpand(request); + assert.deepStrictEqual(response, expectedResponse); }); - describe('pagedExpand', () => { - it('invokes pagedExpand without error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.PagedExpandRequest() - );const expectedResponse = [ - generateSampleMessage(new protos.google.showcase.v1beta1.EchoResponse()), - generateSampleMessage(new protos.google.showcase.v1beta1.EchoResponse()), - generateSampleMessage(new protos.google.showcase.v1beta1.EchoResponse()), - ]; - client.innerApiCalls.pagedExpand = stubSimpleCall(expectedResponse); - const [response] = await client.pagedExpand(request); - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes pagedExpand without error using callback', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.PagedExpandRequest(), + ); + const expectedResponse = [ + generateSampleMessage( + new protos.google.showcase.v1beta1.EchoResponse(), + ), + generateSampleMessage( + new protos.google.showcase.v1beta1.EchoResponse(), + ), + generateSampleMessage( + new protos.google.showcase.v1beta1.EchoResponse(), + ), + ]; + client.innerApiCalls.pagedExpand = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.pagedExpand( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IEchoResponse[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes pagedExpand without error using callback', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.PagedExpandRequest() - );const expectedResponse = [ - generateSampleMessage(new protos.google.showcase.v1beta1.EchoResponse()), - generateSampleMessage(new protos.google.showcase.v1beta1.EchoResponse()), - generateSampleMessage(new protos.google.showcase.v1beta1.EchoResponse()), - ]; - client.innerApiCalls.pagedExpand = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.pagedExpand( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IEchoResponse[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes pagedExpand with error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.PagedExpandRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.pagedExpand = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.pagedExpand(request), expectedError); + }); - it('invokes pagedExpand with error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.PagedExpandRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.pagedExpand = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.pagedExpand(request), expectedError); + it('invokes pagedExpandStream without error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.PagedExpandRequest(), + ); + const expectedResponse = [ + generateSampleMessage( + new protos.google.showcase.v1beta1.EchoResponse(), + ), + generateSampleMessage( + new protos.google.showcase.v1beta1.EchoResponse(), + ), + generateSampleMessage( + new protos.google.showcase.v1beta1.EchoResponse(), + ), + ]; + client.descriptors.page.pagedExpand.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.pagedExpandStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.showcase.v1beta1.EchoResponse[] = []; + stream.on( + 'data', + (response: protos.google.showcase.v1beta1.EchoResponse) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); }); - - it('invokes pagedExpandStream without error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.PagedExpandRequest() - ); - const expectedResponse = [ - generateSampleMessage(new protos.google.showcase.v1beta1.EchoResponse()), - generateSampleMessage(new protos.google.showcase.v1beta1.EchoResponse()), - generateSampleMessage(new protos.google.showcase.v1beta1.EchoResponse()), - ]; - client.descriptors.page.pagedExpand.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.pagedExpandStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.showcase.v1beta1.EchoResponse[] = []; - stream.on('data', (response: protos.google.showcase.v1beta1.EchoResponse) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.pagedExpand.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.pagedExpand, request)); + stream.on('error', (err: Error) => { + reject(err); }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.pagedExpand.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.pagedExpand, request), + ); + }); - it('invokes pagedExpandStream with error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.PagedExpandRequest() - ); - const expectedError = new Error('expected'); - client.descriptors.page.pagedExpand.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.pagedExpandStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.showcase.v1beta1.EchoResponse[] = []; - stream.on('data', (response: protos.google.showcase.v1beta1.EchoResponse) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.pagedExpand.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.pagedExpand, request)); + it('invokes pagedExpandStream with error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.PagedExpandRequest(), + ); + const expectedError = new Error('expected'); + client.descriptors.page.pagedExpand.createStream = stubPageStreamingCall( + undefined, + expectedError, + ); + const stream = client.pagedExpandStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.showcase.v1beta1.EchoResponse[] = []; + stream.on( + 'data', + (response: protos.google.showcase.v1beta1.EchoResponse) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); }); - - it('uses async iteration with pagedExpand without error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.PagedExpandRequest() - ); - const expectedResponse = [ - generateSampleMessage(new protos.google.showcase.v1beta1.EchoResponse()), - generateSampleMessage(new protos.google.showcase.v1beta1.EchoResponse()), - generateSampleMessage(new protos.google.showcase.v1beta1.EchoResponse()), - ]; - client.descriptors.page.pagedExpand.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.showcase.v1beta1.IEchoResponse[] = []; - const iterable = client.pagedExpandAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.pagedExpand.asyncIterate as SinonStub) - .getCall(0).args[1], request); + stream.on('error', (err: Error) => { + reject(err); }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.pagedExpand.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.pagedExpand, request), + ); + }); - it('uses async iteration with pagedExpand with error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.PagedExpandRequest() - ); - const expectedError = new Error('expected'); - client.descriptors.page.pagedExpand.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.pagedExpandAsync(request); - await assert.rejects(async () => { - const responses: protos.google.showcase.v1beta1.IEchoResponse[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.pagedExpand.asyncIterate as SinonStub) - .getCall(0).args[1], request); - }); + it('uses async iteration with pagedExpand without error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.PagedExpandRequest(), + ); + const expectedResponse = [ + generateSampleMessage( + new protos.google.showcase.v1beta1.EchoResponse(), + ), + generateSampleMessage( + new protos.google.showcase.v1beta1.EchoResponse(), + ), + generateSampleMessage( + new protos.google.showcase.v1beta1.EchoResponse(), + ), + ]; + client.descriptors.page.pagedExpand.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.showcase.v1beta1.IEchoResponse[] = []; + const iterable = client.pagedExpandAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + (client.descriptors.page.pagedExpand.asyncIterate as SinonStub).getCall( + 0, + ).args[1], + request, + ); }); + it('uses async iteration with pagedExpand with error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.PagedExpandRequest(), + ); + const expectedError = new Error('expected'); + client.descriptors.page.pagedExpand.asyncIterate = stubAsyncIterationCall( + undefined, + expectedError, + ); + const iterable = client.pagedExpandAsync(request); + await assert.rejects(async () => { + const responses: protos.google.showcase.v1beta1.IEchoResponse[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + (client.descriptors.page.pagedExpand.asyncIterate as SinonStub).getCall( + 0, + ).args[1], + request, + ); + }); + }); }); diff --git a/core/generator/gapic-generator-typescript/baselines/showcase-legacy/src/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/showcase-legacy/src/index.ts.baseline index cc71fdcb10f1..b7757ba69fde 100644 --- a/core/generator/gapic-generator-typescript/baselines/showcase-legacy/src/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/showcase-legacy/src/index.ts.baseline @@ -19,7 +19,7 @@ import * as v1beta1 from './v1beta1'; const EchoClient = v1beta1.EchoClient; type EchoClient = v1beta1.EchoClient; -export {v1beta1, EchoClient}; -export default {v1beta1, EchoClient}; +export { v1beta1, EchoClient }; +export default { v1beta1, EchoClient }; import * as protos from '../protos/protos'; -export {protos} +export { protos }; diff --git a/core/generator/gapic-generator-typescript/baselines/showcase-legacy/src/v1beta1/echo_client.ts.baseline b/core/generator/gapic-generator-typescript/baselines/showcase-legacy/src/v1beta1/echo_client.ts.baseline index 8f57a2c0fa0b..6c06b34da12e 100644 --- a/core/generator/gapic-generator-typescript/baselines/showcase-legacy/src/v1beta1/echo_client.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/showcase-legacy/src/v1beta1/echo_client.ts.baseline @@ -17,11 +17,20 @@ // ** All changes to this file may be overwritten. ** import * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions, GrpcClientOptions, LROperation, PaginationCallback, GaxCall} from 'google-gax'; -import {Transform, PassThrough} from 'stream'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + GrpcClientOptions, + LROperation, + PaginationCallback, + GaxCall, +} from 'google-gax'; +import { Transform, PassThrough } from 'stream'; import * as protos from '../../protos/protos'; import * as path from 'path'; -import {loggingUtils as logging} from 'google-gax'; +import { loggingUtils as logging } from 'google-gax'; /** * Client JSON configuration object, loaded from @@ -51,7 +60,7 @@ export class EchoClient { private _gaxModule: typeof gax; private _gaxGrpc: gax.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('showcase'); @@ -64,9 +73,9 @@ export class EchoClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; + innerApiCalls: { [name: string]: Function }; operationsClient: gax.OperationsClient; - echoStub?: Promise<{[name: string]: Function}>; + echoStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of EchoClient. @@ -100,17 +109,33 @@ export class EchoClient { constructor(opts?: ClientOptions) { // Ensure that options include all the required fields. const staticMembers = this.constructor as typeof EchoClient; - if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { - throw new Error('Please set either universe_domain or universeDomain, but not both.'); + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); } - const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; - this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; this._servicePath = 'localhost'; - const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; - opts = Object.assign({servicePath, port, clientConfig}, opts); + opts = Object.assign({ servicePath, port, clientConfig }, opts); // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. if (servicePath !== this._servicePath && !('scopes' in opts)) { @@ -127,7 +152,7 @@ export class EchoClient { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; @@ -141,10 +166,7 @@ export class EchoClient { } // Determine the client header string. - const clientHeader = [ - `gax/${this._gaxModule.version}`, - `gapic/${version}`, - ]; + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/${process.versions.node}`); } else { @@ -157,53 +179,85 @@ export class EchoClient { // Load the applicable protos. this._protos = this._gaxGrpc.loadProto( path.join(__dirname, '..', '..', 'protos'), - 'google/showcase/v1beta1/echo.proto' + 'google/showcase/v1beta1/echo.proto', ); // Some of the methods on this service return "paged" results, // (e.g. 50 results at a time, with tokens to get subsequent // pages). Denote the keys used for pagination and results. this.descriptors.page = { - pagedExpand: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'responses') + pagedExpand: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'responses', + ), }; // Some of the methods on this service provide streaming responses. // Provide descriptors for these. this.descriptors.stream = { - expand: new this._gaxModule.StreamDescriptor(this._gaxModule.StreamType.SERVER_STREAMING, !!opts.fallback, !!opts.gaxServerStreamingRetries), - collect: new this._gaxModule.StreamDescriptor(this._gaxModule.StreamType.CLIENT_STREAMING, !!opts.fallback), - chat: new this._gaxModule.StreamDescriptor(this._gaxModule.StreamType.BIDI_STREAMING, !!opts.fallback, !!opts.gaxServerStreamingRetries) + expand: new this._gaxModule.StreamDescriptor( + this._gaxModule.StreamType.SERVER_STREAMING, + !!opts.fallback, + !!opts.gaxServerStreamingRetries, + ), + collect: new this._gaxModule.StreamDescriptor( + this._gaxModule.StreamType.CLIENT_STREAMING, + !!opts.fallback, + ), + chat: new this._gaxModule.StreamDescriptor( + this._gaxModule.StreamType.BIDI_STREAMING, + !!opts.fallback, + !!opts.gaxServerStreamingRetries, + ), }; let protoFilesRoot = new this._gaxModule.GoogleProtoFilesRoot(); protoFilesRoot = this._gaxModule.protobuf.loadSync( - path.join(__dirname, '..', '..', 'protos', 'google/showcase/v1beta1/echo.proto'), - protoFilesRoot) as (typeof protoFilesRoot); + path.join( + __dirname, + '..', + '..', + 'protos', + 'google/showcase/v1beta1/echo.proto', + ), + protoFilesRoot, + ) as typeof protoFilesRoot; // This API contains "long-running operations", which return a // an Operation object that allows for tracking of the operation, // rather than holding a request open. const lroOptions: GrpcClientOptions = { auth: this.auth, - grpc: 'grpc' in this._gaxGrpc ? this._gaxGrpc.grpc : undefined + grpc: 'grpc' in this._gaxGrpc ? this._gaxGrpc.grpc : undefined, }; - this.operationsClient = this._gaxModule.lro(lroOptions).operationsClient(opts); + this.operationsClient = this._gaxModule + .lro(lroOptions) + .operationsClient(opts); const waitResponse = protoFilesRoot.lookup( - '.google.showcase.v1beta1.WaitResponse') as gax.protobuf.Type; + '.google.showcase.v1beta1.WaitResponse', + ) as gax.protobuf.Type; const waitMetadata = protoFilesRoot.lookup( - '.google.showcase.v1beta1.WaitMetadata') as gax.protobuf.Type; + '.google.showcase.v1beta1.WaitMetadata', + ) as gax.protobuf.Type; this.descriptors.longrunning = { wait: new this._gaxModule.LongrunningDescriptor( this.operationsClient, waitResponse.decode.bind(waitResponse), - waitMetadata.decode.bind(waitMetadata)) + waitMetadata.decode.bind(waitMetadata), + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.showcase.v1beta1.Echo', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' '), 'x-goog-api-version': 'v1_20240408'}); + 'google.showcase.v1beta1.Echo', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + { + 'x-goog-api-client': clientHeader.join(' '), + 'x-goog-api-version': 'v1_20240408', + }, + ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -234,33 +288,51 @@ export class EchoClient { // Put together the "service stub" for // google.showcase.v1beta1.Echo. this.echoStub = this._gaxGrpc.createStub( - // eslint-disable-next-line @typescript-eslint/no-explicit-any - (this._protos as any).google.showcase.v1beta1.Echo, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + (this._protos as any).google.showcase.v1beta1.Echo, + this._opts, + this._providedCustomServicePath, + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const echoStubMethods = - ['echo', 'echoErrorDetails', 'expand', 'collect', 'chat', 'pagedExpand', 'pagedExpandLegacy', 'wait', 'block']; + const echoStubMethods = [ + 'echo', + 'echoErrorDetails', + 'expand', + 'collect', + 'chat', + 'pagedExpand', + 'pagedExpandLegacy', + 'wait', + 'block', + ]; for (const methodName of echoStubMethods) { const callPromise = this.echoStub.then( - stub => (...args: Array<{}>) => { - if (this._terminated) { - if (methodName in this.descriptors.stream) { - const stream = new PassThrough({objectMode: true}); - setImmediate(() => { - stream.emit('error', new this._gaxModule.GoogleError('The client has already been closed.')); - }); - return stream; + (stub) => + (...args: Array<{}>) => { + if (this._terminated) { + if (methodName in this.descriptors.stream) { + const stream = new PassThrough({ objectMode: true }); + setImmediate(() => { + stream.emit( + 'error', + new this._gaxModule.GoogleError( + 'The client has already been closed.', + ), + ); + }); + return stream; + } + return Promise.reject('The client has already been closed.'); } - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error|null|undefined) => () => { + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { throw err; - }); + }, + ); const descriptor = this.descriptors.page[methodName] || @@ -271,7 +343,7 @@ export class EchoClient { callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -286,8 +358,14 @@ export class EchoClient { * @returns {string} The DNS address for this service. */ static get servicePath() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'localhost'; } @@ -298,8 +376,14 @@ export class EchoClient { * @returns {string} The DNS address for this service. */ static get apiEndpoint() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'localhost'; } @@ -339,8 +423,9 @@ export class EchoClient { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId(callback?: Callback): - Promise|void { + getProjectId( + callback?: Callback, + ): Promise | void { if (callback) { this.auth.getProjectId(callback); return; @@ -351,73 +436,86 @@ export class EchoClient { // ------------------- // -- Service calls -- // ------------------- -/** - * @param {Object} request - * The request object that will be sent. - * @param {string} request.content - * The content to be echoed by the server. - * @param {google.rpc.Status} request.error - * The error to be thrown by the server. - * @param {google.showcase.v1beta1.Severity} request.severity - * The severity to be echoed by the server. - * @param {string} request.header - * Optional. This field can be set to test the routing annotation on the Echo method. - * @param {string} request.otherHeader - * Optional. This field can be set to test the routing annotation on the Echo method. - * @param {string} request.requestId - * To facilitate testing of https://google.aip.dev/client-libraries/4235 - * @param {string} request.otherRequestId - * To facilitate testing of https://google.aip.dev/client-libraries/4235 - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.EchoResponse|EchoResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/echo.echo.js - * region_tag:localhost_v1beta1_generated_Echo_Echo_async - */ + /** + * @param {Object} request + * The request object that will be sent. + * @param {string} request.content + * The content to be echoed by the server. + * @param {google.rpc.Status} request.error + * The error to be thrown by the server. + * @param {google.showcase.v1beta1.Severity} request.severity + * The severity to be echoed by the server. + * @param {string} request.header + * Optional. This field can be set to test the routing annotation on the Echo method. + * @param {string} request.otherHeader + * Optional. This field can be set to test the routing annotation on the Echo method. + * @param {string} request.requestId + * To facilitate testing of https://google.aip.dev/client-libraries/4235 + * @param {string} request.otherRequestId + * To facilitate testing of https://google.aip.dev/client-libraries/4235 + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.EchoResponse|EchoResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/echo.echo.js + * region_tag:localhost_v1beta1_generated_Echo_Echo_async + */ echo( - request?: protos.google.showcase.v1beta1.IEchoRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IEchoResponse, - protos.google.showcase.v1beta1.IEchoRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IEchoRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IEchoResponse, + protos.google.showcase.v1beta1.IEchoRequest | undefined, + {} | undefined, + ] + >; echo( - request: protos.google.showcase.v1beta1.IEchoRequest, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.IEchoResponse, - protos.google.showcase.v1beta1.IEchoRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IEchoRequest, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.IEchoResponse, + protos.google.showcase.v1beta1.IEchoRequest | null | undefined, + {} | null | undefined + >, + ): void; echo( - request: protos.google.showcase.v1beta1.IEchoRequest, - callback: Callback< - protos.google.showcase.v1beta1.IEchoResponse, - protos.google.showcase.v1beta1.IEchoRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IEchoRequest, + callback: Callback< + protos.google.showcase.v1beta1.IEchoResponse, + protos.google.showcase.v1beta1.IEchoRequest | null | undefined, + {} | null | undefined + >, + ): void; echo( - request?: protos.google.showcase.v1beta1.IEchoRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.showcase.v1beta1.IEchoResponse, - protos.google.showcase.v1beta1.IEchoRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.showcase.v1beta1.IEchoRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.IEchoResponse, - protos.google.showcase.v1beta1.IEchoRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.IEchoResponse, - protos.google.showcase.v1beta1.IEchoRequest|undefined, {}|undefined - ]>|void { + protos.google.showcase.v1beta1.IEchoRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.IEchoResponse, + protos.google.showcase.v1beta1.IEchoRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IEchoResponse, + protos.google.showcase.v1beta1.IEchoRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; @@ -437,7 +535,9 @@ export class EchoClient { { const fieldValue = request.header; if (fieldValue !== undefined && fieldValue !== null) { - const match = fieldValue.toString().match(RegExp('(?(?:.*)?)')); + const match = fieldValue + .toString() + .match(RegExp('(?(?:.*)?)')); if (match) { const parameterValue = match.groups?.['routing_id'] ?? fieldValue; Object.assign(routingParameter, { routing_id: parameterValue }); @@ -447,7 +547,9 @@ export class EchoClient { { const fieldValue = request.header; if (fieldValue !== undefined && fieldValue !== null) { - const match = fieldValue.toString().match(RegExp('(?regions/[^/]+/zones/[^/]+(?:/.*)?)')); + const match = fieldValue + .toString() + .match(RegExp('(?regions/[^/]+/zones/[^/]+(?:/.*)?)')); if (match) { const parameterValue = match.groups?.['table_name'] ?? fieldValue; Object.assign(routingParameter, { table_name: parameterValue }); @@ -457,7 +559,9 @@ export class EchoClient { { const fieldValue = request.header; if (fieldValue !== undefined && fieldValue !== null) { - const match = fieldValue.toString().match(RegExp('(?projects/[^/]+)(?:/.*)?')); + const match = fieldValue + .toString() + .match(RegExp('(?projects/[^/]+)(?:/.*)?')); if (match) { const parameterValue = match.groups?.['super_id'] ?? fieldValue; Object.assign(routingParameter, { super_id: parameterValue }); @@ -467,7 +571,11 @@ export class EchoClient { { const fieldValue = request.header; if (fieldValue !== undefined && fieldValue !== null) { - const match = fieldValue.toString().match(RegExp('(?projects/[^/]+/instances/[^/]+(?:/.*)?)')); + const match = fieldValue + .toString() + .match( + RegExp('(?projects/[^/]+/instances/[^/]+(?:/.*)?)'), + ); if (match) { const parameterValue = match.groups?.['table_name'] ?? fieldValue; Object.assign(routingParameter, { table_name: parameterValue }); @@ -477,7 +585,11 @@ export class EchoClient { { const fieldValue = request.header; if (fieldValue !== undefined && fieldValue !== null) { - const match = fieldValue.toString().match(RegExp('projects/[^/]+/(?instances/[^/]+)(?:/.*)?')); + const match = fieldValue + .toString() + .match( + RegExp('projects/[^/]+/(?instances/[^/]+)(?:/.*)?'), + ); if (match) { const parameterValue = match.groups?.['instance_id'] ?? fieldValue; Object.assign(routingParameter, { instance_id: parameterValue }); @@ -497,613 +609,800 @@ export class EchoClient { { const fieldValue = request.otherHeader; if (fieldValue !== undefined && fieldValue !== null) { - const match = fieldValue.toString().match(RegExp('(?projects/[^/]+)(?:/.*)?')); + const match = fieldValue + .toString() + .match(RegExp('(?projects/[^/]+)(?:/.*)?')); if (match) { const parameterValue = match.groups?.['qux'] ?? fieldValue; Object.assign(routingParameter, { qux: parameterValue }); } } } - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams( - routingParameter - ); - this.initialize().catch(err => {throw err}); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams(routingParameter); + this.initialize().catch((err) => { + throw err; + }); this._log.info('echo request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.IEchoResponse, - protos.google.showcase.v1beta1.IEchoRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.IEchoResponse, + protos.google.showcase.v1beta1.IEchoRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('echo response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.echo(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.IEchoResponse, - protos.google.showcase.v1beta1.IEchoRequest|undefined, - {}|undefined - ]) => { - this._log.info('echo response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { + return this.innerApiCalls + .echo(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.IEchoResponse, + protos.google.showcase.v1beta1.IEchoRequest | undefined, + {} | undefined, + ]) => { + this._log.info('echo response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { throw error; }); } -/** - * This method returns error details in a repeated "google.protobuf.Any" - * field. This method showcases handling errors thus encoded, particularly - * over REST transport. Note that GAPICs only allow the type - * "google.protobuf.Any" for field paths ending in "error.details", and, at - * run-time, the actual types for these fields must be one of the types in - * google/rpc/error_details.proto. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.singleDetailText - * Content to return in a singular `*.error.details` field of type - * `google.protobuf.Any` - * @param {string[]} request.multiDetailText - * Content to return in a repeated `*.error.details` field of type - * `google.protobuf.Any` - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.EchoErrorDetailsResponse|EchoErrorDetailsResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/echo.echo_error_details.js - * region_tag:localhost_v1beta1_generated_Echo_EchoErrorDetails_async - */ + /** + * This method returns error details in a repeated "google.protobuf.Any" + * field. This method showcases handling errors thus encoded, particularly + * over REST transport. Note that GAPICs only allow the type + * "google.protobuf.Any" for field paths ending in "error.details", and, at + * run-time, the actual types for these fields must be one of the types in + * google/rpc/error_details.proto. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.singleDetailText + * Content to return in a singular `*.error.details` field of type + * `google.protobuf.Any` + * @param {string[]} request.multiDetailText + * Content to return in a repeated `*.error.details` field of type + * `google.protobuf.Any` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.EchoErrorDetailsResponse|EchoErrorDetailsResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/echo.echo_error_details.js + * region_tag:localhost_v1beta1_generated_Echo_EchoErrorDetails_async + */ echoErrorDetails( - request?: protos.google.showcase.v1beta1.IEchoErrorDetailsRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IEchoErrorDetailsResponse, - protos.google.showcase.v1beta1.IEchoErrorDetailsRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IEchoErrorDetailsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IEchoErrorDetailsResponse, + protos.google.showcase.v1beta1.IEchoErrorDetailsRequest | undefined, + {} | undefined, + ] + >; echoErrorDetails( - request: protos.google.showcase.v1beta1.IEchoErrorDetailsRequest, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.IEchoErrorDetailsResponse, - protos.google.showcase.v1beta1.IEchoErrorDetailsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IEchoErrorDetailsRequest, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.IEchoErrorDetailsResponse, + | protos.google.showcase.v1beta1.IEchoErrorDetailsRequest + | null + | undefined, + {} | null | undefined + >, + ): void; echoErrorDetails( - request: protos.google.showcase.v1beta1.IEchoErrorDetailsRequest, - callback: Callback< - protos.google.showcase.v1beta1.IEchoErrorDetailsResponse, - protos.google.showcase.v1beta1.IEchoErrorDetailsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IEchoErrorDetailsRequest, + callback: Callback< + protos.google.showcase.v1beta1.IEchoErrorDetailsResponse, + | protos.google.showcase.v1beta1.IEchoErrorDetailsRequest + | null + | undefined, + {} | null | undefined + >, + ): void; echoErrorDetails( - request?: protos.google.showcase.v1beta1.IEchoErrorDetailsRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.showcase.v1beta1.IEchoErrorDetailsRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.IEchoErrorDetailsResponse, - protos.google.showcase.v1beta1.IEchoErrorDetailsRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.showcase.v1beta1.IEchoErrorDetailsResponse, - protos.google.showcase.v1beta1.IEchoErrorDetailsRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.IEchoErrorDetailsResponse, - protos.google.showcase.v1beta1.IEchoErrorDetailsRequest|undefined, {}|undefined - ]>|void { + | protos.google.showcase.v1beta1.IEchoErrorDetailsRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.IEchoErrorDetailsResponse, + | protos.google.showcase.v1beta1.IEchoErrorDetailsRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IEchoErrorDetailsResponse, + protos.google.showcase.v1beta1.IEchoErrorDetailsRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('echoErrorDetails request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.IEchoErrorDetailsResponse, - protos.google.showcase.v1beta1.IEchoErrorDetailsRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.IEchoErrorDetailsResponse, + | protos.google.showcase.v1beta1.IEchoErrorDetailsRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('echoErrorDetails response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.echoErrorDetails(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.IEchoErrorDetailsResponse, - protos.google.showcase.v1beta1.IEchoErrorDetailsRequest|undefined, - {}|undefined - ]) => { - this._log.info('echoErrorDetails response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { + return this.innerApiCalls + .echoErrorDetails(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.IEchoErrorDetailsResponse, + protos.google.showcase.v1beta1.IEchoErrorDetailsRequest | undefined, + {} | undefined, + ]) => { + this._log.info('echoErrorDetails response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { throw error; }); } -/** - * This is similar to the PagedExpand except that it uses - * max_results instead of page_size, as some legacy APIs still - * do. New APIs should NOT use this pattern. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.content - * The string to expand. - * @param {number} request.maxResults - * The number of words to returned in each page. - * (-- aip.dev/not-precedent: This is a legacy, non-standard pattern that - * violates aip.dev/158. Ordinarily, this should be page_size. --) - * @param {string} request.pageToken - * The position of the page to be returned. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.PagedExpandResponse|PagedExpandResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/echo.paged_expand_legacy.js - * region_tag:localhost_v1beta1_generated_Echo_PagedExpandLegacy_async - */ + /** + * This is similar to the PagedExpand except that it uses + * max_results instead of page_size, as some legacy APIs still + * do. New APIs should NOT use this pattern. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.content + * The string to expand. + * @param {number} request.maxResults + * The number of words to returned in each page. + * (-- aip.dev/not-precedent: This is a legacy, non-standard pattern that + * violates aip.dev/158. Ordinarily, this should be page_size. --) + * @param {string} request.pageToken + * The position of the page to be returned. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.PagedExpandResponse|PagedExpandResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/echo.paged_expand_legacy.js + * region_tag:localhost_v1beta1_generated_Echo_PagedExpandLegacy_async + */ pagedExpandLegacy( - request?: protos.google.showcase.v1beta1.IPagedExpandLegacyRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IPagedExpandResponse, - protos.google.showcase.v1beta1.IPagedExpandLegacyRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IPagedExpandLegacyRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IPagedExpandResponse, + protos.google.showcase.v1beta1.IPagedExpandLegacyRequest | undefined, + {} | undefined, + ] + >; pagedExpandLegacy( - request: protos.google.showcase.v1beta1.IPagedExpandLegacyRequest, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.IPagedExpandResponse, - protos.google.showcase.v1beta1.IPagedExpandLegacyRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IPagedExpandLegacyRequest, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.IPagedExpandResponse, + | protos.google.showcase.v1beta1.IPagedExpandLegacyRequest + | null + | undefined, + {} | null | undefined + >, + ): void; pagedExpandLegacy( - request: protos.google.showcase.v1beta1.IPagedExpandLegacyRequest, - callback: Callback< - protos.google.showcase.v1beta1.IPagedExpandResponse, - protos.google.showcase.v1beta1.IPagedExpandLegacyRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IPagedExpandLegacyRequest, + callback: Callback< + protos.google.showcase.v1beta1.IPagedExpandResponse, + | protos.google.showcase.v1beta1.IPagedExpandLegacyRequest + | null + | undefined, + {} | null | undefined + >, + ): void; pagedExpandLegacy( - request?: protos.google.showcase.v1beta1.IPagedExpandLegacyRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.showcase.v1beta1.IPagedExpandLegacyRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.IPagedExpandResponse, - protos.google.showcase.v1beta1.IPagedExpandLegacyRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.showcase.v1beta1.IPagedExpandResponse, - protos.google.showcase.v1beta1.IPagedExpandLegacyRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.IPagedExpandResponse, - protos.google.showcase.v1beta1.IPagedExpandLegacyRequest|undefined, {}|undefined - ]>|void { + | protos.google.showcase.v1beta1.IPagedExpandLegacyRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.IPagedExpandResponse, + | protos.google.showcase.v1beta1.IPagedExpandLegacyRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IPagedExpandResponse, + protos.google.showcase.v1beta1.IPagedExpandLegacyRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('pagedExpandLegacy request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.IPagedExpandResponse, - protos.google.showcase.v1beta1.IPagedExpandLegacyRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.IPagedExpandResponse, + | protos.google.showcase.v1beta1.IPagedExpandLegacyRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('pagedExpandLegacy response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.pagedExpandLegacy(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.IPagedExpandResponse, - protos.google.showcase.v1beta1.IPagedExpandLegacyRequest|undefined, - {}|undefined - ]) => { - this._log.info('pagedExpandLegacy response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { + return this.innerApiCalls + .pagedExpandLegacy(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.IPagedExpandResponse, + protos.google.showcase.v1beta1.IPagedExpandLegacyRequest | undefined, + {} | undefined, + ]) => { + this._log.info('pagedExpandLegacy response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { throw error; }); } -/** - * This method will block (wait) for the requested amount of time - * and then return the response or error. - * This method showcases how a client handles delays or retries. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.protobuf.Duration} request.responseDelay - * The amount of time to block before returning a response. - * @param {google.rpc.Status} request.error - * The error that will be returned by the server. If this code is specified - * to be the OK rpc code, an empty response will be returned. - * @param {google.showcase.v1beta1.BlockResponse} request.success - * The response to be returned that will signify successful method call. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.BlockResponse|BlockResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/echo.block.js - * region_tag:localhost_v1beta1_generated_Echo_Block_async - */ + /** + * This method will block (wait) for the requested amount of time + * and then return the response or error. + * This method showcases how a client handles delays or retries. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.protobuf.Duration} request.responseDelay + * The amount of time to block before returning a response. + * @param {google.rpc.Status} request.error + * The error that will be returned by the server. If this code is specified + * to be the OK rpc code, an empty response will be returned. + * @param {google.showcase.v1beta1.BlockResponse} request.success + * The response to be returned that will signify successful method call. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.BlockResponse|BlockResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/echo.block.js + * region_tag:localhost_v1beta1_generated_Echo_Block_async + */ block( - request?: protos.google.showcase.v1beta1.IBlockRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IBlockResponse, - protos.google.showcase.v1beta1.IBlockRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IBlockRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IBlockResponse, + protos.google.showcase.v1beta1.IBlockRequest | undefined, + {} | undefined, + ] + >; block( - request: protos.google.showcase.v1beta1.IBlockRequest, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.IBlockResponse, - protos.google.showcase.v1beta1.IBlockRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IBlockRequest, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.IBlockResponse, + protos.google.showcase.v1beta1.IBlockRequest | null | undefined, + {} | null | undefined + >, + ): void; block( - request: protos.google.showcase.v1beta1.IBlockRequest, - callback: Callback< - protos.google.showcase.v1beta1.IBlockResponse, - protos.google.showcase.v1beta1.IBlockRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IBlockRequest, + callback: Callback< + protos.google.showcase.v1beta1.IBlockResponse, + protos.google.showcase.v1beta1.IBlockRequest | null | undefined, + {} | null | undefined + >, + ): void; block( - request?: protos.google.showcase.v1beta1.IBlockRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.showcase.v1beta1.IBlockResponse, - protos.google.showcase.v1beta1.IBlockRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.showcase.v1beta1.IBlockRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.IBlockResponse, - protos.google.showcase.v1beta1.IBlockRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.IBlockResponse, - protos.google.showcase.v1beta1.IBlockRequest|undefined, {}|undefined - ]>|void { + protos.google.showcase.v1beta1.IBlockRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.IBlockResponse, + protos.google.showcase.v1beta1.IBlockRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IBlockResponse, + protos.google.showcase.v1beta1.IBlockRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('block request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.IBlockResponse, - protos.google.showcase.v1beta1.IBlockRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.IBlockResponse, + protos.google.showcase.v1beta1.IBlockRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('block response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.block(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.IBlockResponse, - protos.google.showcase.v1beta1.IBlockRequest|undefined, - {}|undefined - ]) => { - this._log.info('block response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { + return this.innerApiCalls + .block(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.IBlockResponse, + protos.google.showcase.v1beta1.IBlockRequest | undefined, + {} | undefined, + ]) => { + this._log.info('block response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { throw error; }); } -/** - * This method splits the given content into words and will pass each word back - * through the stream. This method showcases server-side streaming RPCs. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.content - * The content that will be split into words and returned on the stream. - * @param {google.rpc.Status} request.error - * The error that is thrown after all words are sent on the stream. - * @param {google.protobuf.Duration} request.streamWaitTime - * The wait time between each server streaming messages - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits {@link protos.google.showcase.v1beta1.EchoResponse|EchoResponse} on 'data' event. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#server-streaming | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/echo.expand.js - * region_tag:localhost_v1beta1_generated_Echo_Expand_async - */ + /** + * This method splits the given content into words and will pass each word back + * through the stream. This method showcases server-side streaming RPCs. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.content + * The content that will be split into words and returned on the stream. + * @param {google.rpc.Status} request.error + * The error that is thrown after all words are sent on the stream. + * @param {google.protobuf.Duration} request.streamWaitTime + * The wait time between each server streaming messages + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits {@link protos.google.showcase.v1beta1.EchoResponse|EchoResponse} on 'data' event. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#server-streaming | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/echo.expand.js + * region_tag:localhost_v1beta1_generated_Echo_Expand_async + */ expand( - request?: protos.google.showcase.v1beta1.IExpandRequest, - options?: CallOptions): - gax.CancellableStream{ + request?: protos.google.showcase.v1beta1.IExpandRequest, + options?: CallOptions, + ): gax.CancellableStream { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('expand stream %j', options); return this.innerApiCalls.expand(request, options); } -/** - * This method will collect the words given to it. When the stream is closed - * by the client, this method will return the a concatenation of the strings - * passed to it. This method showcases client-side streaming RPCs. - * - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - A writable stream which accepts objects representing - * {@link protos.google.showcase.v1beta1.EchoRequest|EchoRequest}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#client-streaming | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/echo.collect.js - * region_tag:localhost_v1beta1_generated_Echo_Collect_async - */ + /** + * This method will collect the words given to it. When the stream is closed + * by the client, this method will return the a concatenation of the strings + * passed to it. This method showcases client-side streaming RPCs. + * + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} - A writable stream which accepts objects representing + * {@link protos.google.showcase.v1beta1.EchoRequest|EchoRequest}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#client-streaming | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/echo.collect.js + * region_tag:localhost_v1beta1_generated_Echo_Collect_async + */ collect( - options?: CallOptions, - callback?: Callback< - protos.google.showcase.v1beta1.IEchoResponse, - protos.google.showcase.v1beta1.IEchoRequest|null|undefined, - {}|null|undefined>): - gax.CancellableStream; + options?: CallOptions, + callback?: Callback< + protos.google.showcase.v1beta1.IEchoResponse, + protos.google.showcase.v1beta1.IEchoRequest | null | undefined, + {} | null | undefined + >, + ): gax.CancellableStream; collect( - callback?: Callback< - protos.google.showcase.v1beta1.IEchoResponse, - protos.google.showcase.v1beta1.IEchoRequest|null|undefined, - {}|null|undefined>): - gax.CancellableStream; + callback?: Callback< + protos.google.showcase.v1beta1.IEchoResponse, + protos.google.showcase.v1beta1.IEchoRequest | null | undefined, + {} | null | undefined + >, + ): gax.CancellableStream; collect( - optionsOrCallback?: CallOptions|Callback< - protos.google.showcase.v1beta1.IEchoResponse, - protos.google.showcase.v1beta1.IEchoRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.showcase.v1beta1.IEchoResponse, - protos.google.showcase.v1beta1.IEchoRequest|null|undefined, - {}|null|undefined>): - gax.CancellableStream { + optionsOrCallback?: + | CallOptions + | Callback< + protos.google.showcase.v1beta1.IEchoResponse, + protos.google.showcase.v1beta1.IEchoRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.IEchoResponse, + protos.google.showcase.v1beta1.IEchoRequest | null | undefined, + {} | null | undefined + >, + ): gax.CancellableStream { if (optionsOrCallback instanceof Function && callback === undefined) { - callback = optionsOrCallback; - optionsOrCallback = {}; + callback = optionsOrCallback; + optionsOrCallback = {}; } const options = optionsOrCallback as CallOptions; - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('collect stream %j', options); return this.innerApiCalls.collect(null, options, callback); } -/** - * This method, upon receiving a request on the stream, will pass the same - * content back on the stream. This method showcases bidirectional - * streaming RPCs. - * - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which is both readable and writable. It accepts objects - * representing {@link protos.google.showcase.v1beta1.EchoRequest|EchoRequest} for write() method, and - * will emit objects representing {@link protos.google.showcase.v1beta1.EchoResponse|EchoResponse} on 'data' event asynchronously. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#bi-directional-streaming | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/echo.chat.js - * region_tag:localhost_v1beta1_generated_Echo_Chat_async - */ - chat( - options?: CallOptions): - gax.CancellableStream { - this.initialize().catch(err => {throw err}); + /** + * This method, upon receiving a request on the stream, will pass the same + * content back on the stream. This method showcases bidirectional + * streaming RPCs. + * + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which is both readable and writable. It accepts objects + * representing {@link protos.google.showcase.v1beta1.EchoRequest|EchoRequest} for write() method, and + * will emit objects representing {@link protos.google.showcase.v1beta1.EchoResponse|EchoResponse} on 'data' event asynchronously. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#bi-directional-streaming | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/echo.chat.js + * region_tag:localhost_v1beta1_generated_Echo_Chat_async + */ + chat(options?: CallOptions): gax.CancellableStream { + this.initialize().catch((err) => { + throw err; + }); this._log.info('chat stream %j', options); return this.innerApiCalls.chat(null, options); } -/** - * This method will wait for the requested amount of time and then return. - * This method showcases how a client handles a request timeout. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.protobuf.Timestamp} request.endTime - * The time that this operation will complete. - * @param {google.protobuf.Duration} request.ttl - * The duration of this operation. - * @param {google.rpc.Status} request.error - * The error that will be returned by the server. If this code is specified - * to be the OK rpc code, an empty response will be returned. - * @param {google.showcase.v1beta1.WaitResponse} request.success - * The response to be returned on operation completion. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing - * a long running operation. Its `promise()` method returns a promise - * you can `await` for. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/echo.wait.js - * region_tag:localhost_v1beta1_generated_Echo_Wait_async - */ + /** + * This method will wait for the requested amount of time and then return. + * This method showcases how a client handles a request timeout. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.protobuf.Timestamp} request.endTime + * The time that this operation will complete. + * @param {google.protobuf.Duration} request.ttl + * The duration of this operation. + * @param {google.rpc.Status} request.error + * The error that will be returned by the server. If this code is specified + * to be the OK rpc code, an empty response will be returned. + * @param {google.showcase.v1beta1.WaitResponse} request.success + * The response to be returned on operation completion. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/echo.wait.js + * region_tag:localhost_v1beta1_generated_Echo_Wait_async + */ wait( - request?: protos.google.showcase.v1beta1.IWaitRequest, - options?: CallOptions): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IWaitRequest, + options?: CallOptions, + ): Promise< + [ + LROperation< + protos.google.showcase.v1beta1.IWaitResponse, + protos.google.showcase.v1beta1.IWaitMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; wait( - request: protos.google.showcase.v1beta1.IWaitRequest, - options: CallOptions, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IWaitRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.showcase.v1beta1.IWaitResponse, + protos.google.showcase.v1beta1.IWaitMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; wait( - request: protos.google.showcase.v1beta1.IWaitRequest, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IWaitRequest, + callback: Callback< + LROperation< + protos.google.showcase.v1beta1.IWaitResponse, + protos.google.showcase.v1beta1.IWaitMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; wait( - request?: protos.google.showcase.v1beta1.IWaitRequest, - optionsOrCallback?: CallOptions|Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>, - callback?: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>|void { + request?: protos.google.showcase.v1beta1.IWaitRequest, + optionsOrCallback?: + | CallOptions + | Callback< + LROperation< + protos.google.showcase.v1beta1.IWaitResponse, + protos.google.showcase.v1beta1.IWaitMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + callback?: Callback< + LROperation< + protos.google.showcase.v1beta1.IWaitResponse, + protos.google.showcase.v1beta1.IWaitMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + LROperation< + protos.google.showcase.v1beta1.IWaitResponse, + protos.google.showcase.v1beta1.IWaitMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize().catch(err => {throw err}); - const wrappedCallback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>|undefined = callback + this.initialize().catch((err) => { + throw err; + }); + const wrappedCallback: + | Callback< + LROperation< + protos.google.showcase.v1beta1.IWaitResponse, + protos.google.showcase.v1beta1.IWaitMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, rawResponse, _) => { this._log.info('wait response %j', rawResponse); callback!(error, response, rawResponse, _); // We verified callback above. } : undefined; this._log.info('wait request %j', request); - return this.innerApiCalls.wait(request, options, wrappedCallback) - ?.then(([response, rawResponse, _]: [ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]) => { - this._log.info('wait response %j', rawResponse); - return [response, rawResponse, _]; - }); + return this.innerApiCalls + .wait(request, options, wrappedCallback) + ?.then( + ([response, rawResponse, _]: [ + LROperation< + protos.google.showcase.v1beta1.IWaitResponse, + protos.google.showcase.v1beta1.IWaitMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ]) => { + this._log.info('wait response %j', rawResponse); + return [response, rawResponse, _]; + }, + ); } -/** - * Check the status of the long running operation returned by `wait()`. - * @param {String} name - * The operation name that will be passed. - * @returns {Promise} - The promise which resolves to an object. - * The decoded operation object has result and metadata field to get information from. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/echo.wait.js - * region_tag:localhost_v1beta1_generated_Echo_Wait_async - */ - async checkWaitProgress(name: string): Promise>{ + /** + * Check the status of the long running operation returned by `wait()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/echo.wait.js + * region_tag:localhost_v1beta1_generated_Echo_Wait_async + */ + async checkWaitProgress( + name: string, + ): Promise< + LROperation< + protos.google.showcase.v1beta1.WaitResponse, + protos.google.showcase.v1beta1.WaitMetadata + > + > { this._log.info('wait long-running'); - const request = new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest({name}); + const request = + new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( + { name }, + ); const [operation] = await this.operationsClient.getOperation(request); - const decodeOperation = new this._gaxModule.Operation(operation, this.descriptors.longrunning.wait, this._gaxModule.createDefaultBackoffSettings()); - return decodeOperation as LROperation; + const decodeOperation = new this._gaxModule.Operation( + operation, + this.descriptors.longrunning.wait, + this._gaxModule.createDefaultBackoffSettings(), + ); + return decodeOperation as LROperation< + protos.google.showcase.v1beta1.WaitResponse, + protos.google.showcase.v1beta1.WaitMetadata + >; } - /** - * This is similar to the Expand method but instead of returning a stream of - * expanded words, this method returns a paged list of expanded words. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.content - * The string to expand. - * @param {number} request.pageSize - * The number of words to returned in each page. - * @param {string} request.pageToken - * The position of the page to be returned. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.showcase.v1beta1.EchoResponse|EchoResponse}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `pagedExpandAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * This is similar to the Expand method but instead of returning a stream of + * expanded words, this method returns a paged list of expanded words. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.content + * The string to expand. + * @param {number} request.pageSize + * The number of words to returned in each page. + * @param {string} request.pageToken + * The position of the page to be returned. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.showcase.v1beta1.EchoResponse|EchoResponse}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `pagedExpandAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ pagedExpand( - request?: protos.google.showcase.v1beta1.IPagedExpandRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IEchoResponse[], - protos.google.showcase.v1beta1.IPagedExpandRequest|null, - protos.google.showcase.v1beta1.IPagedExpandResponse - ]>; + request?: protos.google.showcase.v1beta1.IPagedExpandRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IEchoResponse[], + protos.google.showcase.v1beta1.IPagedExpandRequest | null, + protos.google.showcase.v1beta1.IPagedExpandResponse, + ] + >; pagedExpand( - request: protos.google.showcase.v1beta1.IPagedExpandRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.showcase.v1beta1.IPagedExpandRequest, - protos.google.showcase.v1beta1.IPagedExpandResponse|null|undefined, - protos.google.showcase.v1beta1.IEchoResponse>): void; + request: protos.google.showcase.v1beta1.IPagedExpandRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.showcase.v1beta1.IPagedExpandRequest, + protos.google.showcase.v1beta1.IPagedExpandResponse | null | undefined, + protos.google.showcase.v1beta1.IEchoResponse + >, + ): void; pagedExpand( - request: protos.google.showcase.v1beta1.IPagedExpandRequest, - callback: PaginationCallback< - protos.google.showcase.v1beta1.IPagedExpandRequest, - protos.google.showcase.v1beta1.IPagedExpandResponse|null|undefined, - protos.google.showcase.v1beta1.IEchoResponse>): void; + request: protos.google.showcase.v1beta1.IPagedExpandRequest, + callback: PaginationCallback< + protos.google.showcase.v1beta1.IPagedExpandRequest, + protos.google.showcase.v1beta1.IPagedExpandResponse | null | undefined, + protos.google.showcase.v1beta1.IEchoResponse + >, + ): void; pagedExpand( - request?: protos.google.showcase.v1beta1.IPagedExpandRequest, - optionsOrCallback?: CallOptions|PaginationCallback< + request?: protos.google.showcase.v1beta1.IPagedExpandRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.showcase.v1beta1.IPagedExpandRequest, - protos.google.showcase.v1beta1.IPagedExpandResponse|null|undefined, - protos.google.showcase.v1beta1.IEchoResponse>, - callback?: PaginationCallback< - protos.google.showcase.v1beta1.IPagedExpandRequest, - protos.google.showcase.v1beta1.IPagedExpandResponse|null|undefined, - protos.google.showcase.v1beta1.IEchoResponse>): - Promise<[ - protos.google.showcase.v1beta1.IEchoResponse[], - protos.google.showcase.v1beta1.IPagedExpandRequest|null, - protos.google.showcase.v1beta1.IPagedExpandResponse - ]>|void { + | protos.google.showcase.v1beta1.IPagedExpandResponse + | null + | undefined, + protos.google.showcase.v1beta1.IEchoResponse + >, + callback?: PaginationCallback< + protos.google.showcase.v1beta1.IPagedExpandRequest, + protos.google.showcase.v1beta1.IPagedExpandResponse | null | undefined, + protos.google.showcase.v1beta1.IEchoResponse + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IEchoResponse[], + protos.google.showcase.v1beta1.IPagedExpandRequest | null, + protos.google.showcase.v1beta1.IPagedExpandResponse, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.showcase.v1beta1.IPagedExpandRequest, - protos.google.showcase.v1beta1.IPagedExpandResponse|null|undefined, - protos.google.showcase.v1beta1.IEchoResponse>|undefined = callback + this.initialize().catch((err) => { + throw err; + }); + const wrappedCallback: + | PaginationCallback< + protos.google.showcase.v1beta1.IPagedExpandRequest, + | protos.google.showcase.v1beta1.IPagedExpandResponse + | null + | undefined, + protos.google.showcase.v1beta1.IEchoResponse + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('pagedExpand values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -1112,96 +1411,102 @@ export class EchoClient { this._log.info('pagedExpand request %j', request); return this.innerApiCalls .pagedExpand(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.showcase.v1beta1.IEchoResponse[], - protos.google.showcase.v1beta1.IPagedExpandRequest|null, - protos.google.showcase.v1beta1.IPagedExpandResponse - ]) => { - this._log.info('pagedExpand values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.showcase.v1beta1.IEchoResponse[], + protos.google.showcase.v1beta1.IPagedExpandRequest | null, + protos.google.showcase.v1beta1.IPagedExpandResponse, + ]) => { + this._log.info('pagedExpand values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `pagedExpand`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.content - * The string to expand. - * @param {number} request.pageSize - * The number of words to returned in each page. - * @param {string} request.pageToken - * The position of the page to be returned. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.showcase.v1beta1.EchoResponse|EchoResponse} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `pagedExpandAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `pagedExpand`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.content + * The string to expand. + * @param {number} request.pageSize + * The number of words to returned in each page. + * @param {string} request.pageToken + * The position of the page to be returned. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.showcase.v1beta1.EchoResponse|EchoResponse} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `pagedExpandAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ pagedExpandStream( - request?: protos.google.showcase.v1beta1.IPagedExpandRequest, - options?: CallOptions): - Transform{ + request?: protos.google.showcase.v1beta1.IPagedExpandRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; const defaultCallSettings = this._defaults['pagedExpand']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('pagedExpand stream %j', request); return this.descriptors.page.pagedExpand.createStream( this.innerApiCalls.pagedExpand as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `pagedExpand`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.content - * The string to expand. - * @param {number} request.pageSize - * The number of words to returned in each page. - * @param {string} request.pageToken - * The position of the page to be returned. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.showcase.v1beta1.EchoResponse|EchoResponse}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/echo.paged_expand.js - * region_tag:localhost_v1beta1_generated_Echo_PagedExpand_async - */ + /** + * Equivalent to `pagedExpand`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.content + * The string to expand. + * @param {number} request.pageSize + * The number of words to returned in each page. + * @param {string} request.pageToken + * The position of the page to be returned. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.showcase.v1beta1.EchoResponse|EchoResponse}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/echo.paged_expand.js + * region_tag:localhost_v1beta1_generated_Echo_PagedExpand_async + */ pagedExpandAsync( - request?: protos.google.showcase.v1beta1.IPagedExpandRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.showcase.v1beta1.IPagedExpandRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; const defaultCallSettings = this._defaults['pagedExpand']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('pagedExpand iterate %j', request); return this.descriptors.page.pagedExpand.asyncIterate( this.innerApiCalls['pagedExpand'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } @@ -1213,7 +1518,7 @@ export class EchoClient { */ close(): Promise { if (this.echoStub && !this._terminated) { - return this.echoStub.then(stub => { + return this.echoStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -1222,4 +1527,4 @@ export class EchoClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/core/generator/gapic-generator-typescript/baselines/showcase-legacy/src/v1beta1/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/showcase-legacy/src/v1beta1/index.ts.baseline index 3eb609f3454f..b2946db2e7cb 100644 --- a/core/generator/gapic-generator-typescript/baselines/showcase-legacy/src/v1beta1/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/showcase-legacy/src/v1beta1/index.ts.baseline @@ -16,4 +16,4 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -export {EchoClient} from './echo_client'; +export { EchoClient } from './echo_client'; diff --git a/core/generator/gapic-generator-typescript/baselines/showcase-legacy/system-test/fixtures/sample/src/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/showcase-legacy/system-test/fixtures/sample/src/index.ts.baseline index 8a0366728d76..a7b3a4c4e15b 100644 --- a/core/generator/gapic-generator-typescript/baselines/showcase-legacy/system-test/fixtures/sample/src/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/showcase-legacy/system-test/fixtures/sample/src/index.ts.baseline @@ -16,7 +16,7 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -import {EchoClient} from 'showcase'; +import { EchoClient } from 'showcase'; // check that the client class type name can be used function doStuffWithEchoClient(client: EchoClient) { diff --git a/core/generator/gapic-generator-typescript/baselines/showcase-legacy/system-test/install.ts.baseline b/core/generator/gapic-generator-typescript/baselines/showcase-legacy/system-test/install.ts.baseline index f66069aa3940..ccf167042d2e 100644 --- a/core/generator/gapic-generator-typescript/baselines/showcase-legacy/system-test/install.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/showcase-legacy/system-test/install.ts.baseline @@ -16,34 +16,36 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -import {packNTest} from 'pack-n-play'; -import {readFileSync} from 'fs'; -import {describe, it} from 'mocha'; +import { packNTest } from 'pack-n-play'; +import { readFileSync } from 'fs'; +import { describe, it } from 'mocha'; describe('📦 pack-n-play test', () => { - - it('TypeScript code', async function() { + it('TypeScript code', async function () { this.timeout(300000); const options = { packageDir: process.cwd(), sample: { description: 'TypeScript user can use the type definitions', - ts: readFileSync('./system-test/fixtures/sample/src/index.ts').toString() - } + ts: readFileSync( + './system-test/fixtures/sample/src/index.ts', + ).toString(), + }, }; await packNTest(options); }); - it('JavaScript code', async function() { + it('JavaScript code', async function () { this.timeout(300000); const options = { packageDir: process.cwd(), sample: { description: 'JavaScript user can use the library', - cjs: readFileSync('./system-test/fixtures/sample/src/index.js').toString() - } + cjs: readFileSync( + './system-test/fixtures/sample/src/index.js', + ).toString(), + }, }; await packNTest(options); }); - }); diff --git a/core/generator/gapic-generator-typescript/baselines/showcase-legacy/test/gapic_echo_v1beta1.ts.baseline b/core/generator/gapic-generator-typescript/baselines/showcase-legacy/test/gapic_echo_v1beta1.ts.baseline index 338049d52e79..182062e13572 100644 --- a/core/generator/gapic-generator-typescript/baselines/showcase-legacy/test/gapic_echo_v1beta1.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/showcase-legacy/test/gapic_echo_v1beta1.ts.baseline @@ -19,1093 +19,1341 @@ import * as protos from '../protos/protos'; import * as assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as echoModule from '../src'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; -import {protobuf, LROperation, operationsProtos} from 'google-gax'; +import { protobuf, LROperation, operationsProtos } from 'google-gax'; // eslint-disable-next-line @typescript-eslint/no-unused-vars function getTypeDefaultValue(typeName: string, fields: string[]) { - // non-string x-goog-request-param values are not supported; - // we always assume that it's a string. - return ''; + // non-string x-goog-request-param values are not supported; + // we always assume that it's a string. + return ''; } function generateSampleMessage(instance: T) { - const filledObject = (instance.constructor as typeof protobuf.Message) - .toObject(instance as protobuf.Message, {defaults: true}); - return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, { defaults: true }); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; } function stubSimpleCall(response?: ResponseType, error?: Error) { - return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); } -function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { - return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +function stubSimpleCallWithCallback( + response?: ResponseType, + error?: Error, +) { + return error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); } -function stubServerStreamingCall(response?: ResponseType, error?: Error) { - const transformStub = error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); - const mockStream = new PassThrough({ - objectMode: true, - transform: transformStub, - }); - // write something to the stream to trigger transformStub and send the response back to the client - setImmediate(() => { mockStream.write({}); }); - setImmediate(() => { mockStream.end(); }); - return sinon.stub().returns(mockStream); +function stubServerStreamingCall( + response?: ResponseType, + error?: Error, +) { + const transformStub = error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + // write something to the stream to trigger transformStub and send the response back to the client + setImmediate(() => { + mockStream.write({}); + }); + setImmediate(() => { + mockStream.end(); + }); + return sinon.stub().returns(mockStream); } -function stubBidiStreamingCall(response?: ResponseType, error?: Error) { - const transformStub = error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); - const mockStream = new PassThrough({ - objectMode: true, - transform: transformStub, - }); - return sinon.stub().returns(mockStream); +function stubBidiStreamingCall( + response?: ResponseType, + error?: Error, +) { + const transformStub = error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + return sinon.stub().returns(mockStream); } -function stubClientStreamingCall(response?: ResponseType, error?: Error) { - if (error) { - return sinon.stub().callsArgWith(2, error); - } - const transformStub = sinon.stub(); - const mockStream = new PassThrough({ - objectMode: true, - transform: transformStub, - }); - return sinon.stub().returns(mockStream).callsArgWith(2, null, response); +function stubClientStreamingCall( + response?: ResponseType, + error?: Error, +) { + if (error) { + return sinon.stub().callsArgWith(2, error); + } + const transformStub = sinon.stub(); + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + return sinon.stub().returns(mockStream).callsArgWith(2, null, response); } -function stubLongRunningCall(response?: ResponseType, callError?: Error, lroError?: Error) { - const innerStub = lroError ? sinon.stub().rejects(lroError) : sinon.stub().resolves([response]); - const mockOperation = { - promise: innerStub, - }; - return callError ? sinon.stub().rejects(callError) : sinon.stub().resolves([mockOperation]); +function stubLongRunningCall( + response?: ResponseType, + callError?: Error, + lroError?: Error, +) { + const innerStub = lroError + ? sinon.stub().rejects(lroError) + : sinon.stub().resolves([response]); + const mockOperation = { + promise: innerStub, + }; + return callError + ? sinon.stub().rejects(callError) + : sinon.stub().resolves([mockOperation]); } -function stubLongRunningCallWithCallback(response?: ResponseType, callError?: Error, lroError?: Error) { - const innerStub = lroError ? sinon.stub().rejects(lroError) : sinon.stub().resolves([response]); - const mockOperation = { - promise: innerStub, - }; - return callError ? sinon.stub().callsArgWith(2, callError) : sinon.stub().callsArgWith(2, null, mockOperation); +function stubLongRunningCallWithCallback( + response?: ResponseType, + callError?: Error, + lroError?: Error, +) { + const innerStub = lroError + ? sinon.stub().rejects(lroError) + : sinon.stub().resolves([response]); + const mockOperation = { + promise: innerStub, + }; + return callError + ? sinon.stub().callsArgWith(2, callError) + : sinon.stub().callsArgWith(2, null, mockOperation); } -function stubPageStreamingCall(responses?: ResponseType[], error?: Error) { - const pagingStub = sinon.stub(); - if (responses) { - for (let i = 0; i < responses.length; ++i) { - pagingStub.onCall(i).callsArgWith(2, null, responses[i]); - } +function stubPageStreamingCall( + responses?: ResponseType[], + error?: Error, +) { + const pagingStub = sinon.stub(); + if (responses) { + for (let i = 0; i < responses.length; ++i) { + pagingStub.onCall(i).callsArgWith(2, null, responses[i]); } - const transformStub = error ? sinon.stub().callsArgWith(2, error) : pagingStub; - const mockStream = new PassThrough({ - objectMode: true, - transform: transformStub, - }); - // trigger as many responses as needed - if (responses) { - for (let i = 0; i < responses.length; ++i) { - setImmediate(() => { mockStream.write({}); }); - } - setImmediate(() => { mockStream.end(); }); - } else { - setImmediate(() => { mockStream.write({}); }); - setImmediate(() => { mockStream.end(); }); + } + const transformStub = error + ? sinon.stub().callsArgWith(2, error) + : pagingStub; + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + // trigger as many responses as needed + if (responses) { + for (let i = 0; i < responses.length; ++i) { + setImmediate(() => { + mockStream.write({}); + }); } - return sinon.stub().returns(mockStream); + setImmediate(() => { + mockStream.end(); + }); + } else { + setImmediate(() => { + mockStream.write({}); + }); + setImmediate(() => { + mockStream.end(); + }); + } + return sinon.stub().returns(mockStream); } -function stubAsyncIterationCall(responses?: ResponseType[], error?: Error) { - let counter = 0; - const asyncIterable = { - [Symbol.asyncIterator]() { - return { - async next() { - if (error) { - return Promise.reject(error); - } - if (counter >= responses!.length) { - return Promise.resolve({done: true, value: undefined}); - } - return Promise.resolve({done: false, value: responses![counter++]}); - } - }; - } - }; - return sinon.stub().returns(asyncIterable); +function stubAsyncIterationCall( + responses?: ResponseType[], + error?: Error, +) { + let counter = 0; + const asyncIterable = { + [Symbol.asyncIterator]() { + return { + async next() { + if (error) { + return Promise.reject(error); + } + if (counter >= responses!.length) { + return Promise.resolve({ done: true, value: undefined }); + } + return Promise.resolve({ done: false, value: responses![counter++] }); + }, + }; + }, + }; + return sinon.stub().returns(asyncIterable); } describe('v1beta1.EchoClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new echoModule.v1beta1.EchoClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'localhost'); - }); - - it('has universeDomain', () => { - const client = new echoModule.v1beta1.EchoClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); - - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - it('throws DeprecationWarning if static servicePath is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const servicePath = echoModule.v1beta1.EchoClient.servicePath; - assert.strictEqual(servicePath, 'localhost'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = echoModule.v1beta1.EchoClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'localhost'); - assert(stub.called); - stub.restore(); - }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { new echoModule.v1beta1.EchoClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); - - it('has port', () => { - const port = echoModule.v1beta1.EchoClient.port; - assert(port); - assert(typeof port === 'number'); - }); - - it('should create a client with no option', () => { - const client = new echoModule.v1beta1.EchoClient(); - assert(client); - }); - - it('has initialize method and supports deferred initialization', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.echoStub, undefined); - await client.initialize(); - assert(client.echoStub); - }); - - it('has close method for the initialized client', done => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.echoStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); - - it('has close method for the non-initialized client', done => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.echoStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new echoModule.v1beta1.EchoClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'localhost'); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); - }); + it('has universeDomain', () => { + const client = new echoModule.v1beta1.EchoClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId((err?: Error|null, projectId?: string|null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } - }); - }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = echoModule.v1beta1.EchoClient.servicePath; + assert.strictEqual(servicePath, 'localhost'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = echoModule.v1beta1.EchoClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'localhost'); + assert(stub.called); + stub.restore(); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new echoModule.v1beta1.EchoClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); }); - describe('echo', () => { - it('invokes echo without error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.EchoRequest() - ); - // path template: {qux=projects/*}/** - request.otherHeader = 'projects/value/value'; - const expectedHeaderRequestParams = 'qux=projects%2Fvalue'; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.EchoResponse() - ); - client.innerApiCalls.echo = stubSimpleCall(expectedResponse); - const [response] = await client.echo(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.echo as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.echo as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has port', () => { + const port = echoModule.v1beta1.EchoClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('invokes echo without error using callback', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.EchoRequest() - ); - // path template: {qux=projects/*}/** - request.otherHeader = 'projects/value/value'; - const expectedHeaderRequestParams = 'qux=projects%2Fvalue'; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.EchoResponse() - ); - client.innerApiCalls.echo = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.echo( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IEchoResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.echo as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.echo as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('should create a client with no option', () => { + const client = new echoModule.v1beta1.EchoClient(); + assert(client); + }); - it('invokes echo with error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.EchoRequest() - ); - // path template: {qux=projects/*}/** - request.otherHeader = 'projects/value/value'; - const expectedHeaderRequestParams = 'qux=projects%2Fvalue'; - const expectedError = new Error('expected'); - client.innerApiCalls.echo = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.echo(request), expectedError); - const actualRequest = (client.innerApiCalls.echo as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.echo as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has initialize method and supports deferred initialization', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.echoStub, undefined); + await client.initialize(); + assert(client.echoStub); + }); - it('invokes echo with closed client', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.EchoRequest() - ); - // path template: {qux=projects/*}/** - request.otherHeader = 'projects/value/value'; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.echo(request), expectedError); + it('has close method for the initialized client', (done) => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.echoStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); }); - describe('echoErrorDetails', () => { - it('invokes echoErrorDetails without error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.EchoErrorDetailsRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.EchoErrorDetailsResponse() - ); - client.innerApiCalls.echoErrorDetails = stubSimpleCall(expectedResponse); - const [response] = await client.echoErrorDetails(request); - assert.deepStrictEqual(response, expectedResponse); + it('has close method for the non-initialized client', (done) => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.echoStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes echoErrorDetails without error using callback', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.EchoErrorDetailsRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.EchoErrorDetailsResponse() - ); - client.innerApiCalls.echoErrorDetails = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.echoErrorDetails( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IEchoErrorDetailsResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + }); - it('invokes echoErrorDetails with error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.EchoErrorDetailsRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.echoErrorDetails = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.echoErrorDetails(request), expectedError); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + }); + + describe('echo', () => { + it('invokes echo without error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.EchoRequest(), + ); + // path template: {qux=projects/*}/** + request.otherHeader = 'projects/value/value'; + const expectedHeaderRequestParams = 'qux=projects%2Fvalue'; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.EchoResponse(), + ); + client.innerApiCalls.echo = stubSimpleCall(expectedResponse); + const [response] = await client.echo(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.echo as SinonStub).getCall(0) + .args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.echo as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes echoErrorDetails with closed client', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.EchoErrorDetailsRequest() - ); - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.echoErrorDetails(request), expectedError); - }); + it('invokes echo without error using callback', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.EchoRequest(), + ); + // path template: {qux=projects/*}/** + request.otherHeader = 'projects/value/value'; + const expectedHeaderRequestParams = 'qux=projects%2Fvalue'; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.EchoResponse(), + ); + client.innerApiCalls.echo = stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.echo( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IEchoResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.echo as SinonStub).getCall(0) + .args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.echo as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('pagedExpandLegacy', () => { - it('invokes pagedExpandLegacy without error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.PagedExpandLegacyRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.PagedExpandResponse() - ); - client.innerApiCalls.pagedExpandLegacy = stubSimpleCall(expectedResponse); - const [response] = await client.pagedExpandLegacy(request); - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes echo with error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.EchoRequest(), + ); + // path template: {qux=projects/*}/** + request.otherHeader = 'projects/value/value'; + const expectedHeaderRequestParams = 'qux=projects%2Fvalue'; + const expectedError = new Error('expected'); + client.innerApiCalls.echo = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.echo(request), expectedError); + const actualRequest = (client.innerApiCalls.echo as SinonStub).getCall(0) + .args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.echo as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes pagedExpandLegacy without error using callback', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.PagedExpandLegacyRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.PagedExpandResponse() - ); - client.innerApiCalls.pagedExpandLegacy = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.pagedExpandLegacy( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IPagedExpandResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes echo with closed client', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.EchoRequest(), + ); + // path template: {qux=projects/*}/** + request.otherHeader = 'projects/value/value'; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.echo(request), expectedError); + }); + }); + + describe('echoErrorDetails', () => { + it('invokes echoErrorDetails without error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.EchoErrorDetailsRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.EchoErrorDetailsResponse(), + ); + client.innerApiCalls.echoErrorDetails = stubSimpleCall(expectedResponse); + const [response] = await client.echoErrorDetails(request); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes pagedExpandLegacy with error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.PagedExpandLegacyRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.pagedExpandLegacy = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.pagedExpandLegacy(request), expectedError); - }); + it('invokes echoErrorDetails without error using callback', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.EchoErrorDetailsRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.EchoErrorDetailsResponse(), + ); + client.innerApiCalls.echoErrorDetails = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.echoErrorDetails( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IEchoErrorDetailsResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes pagedExpandLegacy with closed client', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.PagedExpandLegacyRequest() - ); - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.pagedExpandLegacy(request), expectedError); - }); + it('invokes echoErrorDetails with error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.EchoErrorDetailsRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.echoErrorDetails = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.echoErrorDetails(request), expectedError); }); - describe('block', () => { - it('invokes block without error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.BlockRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.BlockResponse() - ); - client.innerApiCalls.block = stubSimpleCall(expectedResponse); - const [response] = await client.block(request); - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes echoErrorDetails with closed client', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.EchoErrorDetailsRequest(), + ); + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.echoErrorDetails(request), expectedError); + }); + }); + + describe('pagedExpandLegacy', () => { + it('invokes pagedExpandLegacy without error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.PagedExpandLegacyRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.PagedExpandResponse(), + ); + client.innerApiCalls.pagedExpandLegacy = stubSimpleCall(expectedResponse); + const [response] = await client.pagedExpandLegacy(request); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes block without error using callback', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.BlockRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.BlockResponse() - ); - client.innerApiCalls.block = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.block( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IBlockResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes pagedExpandLegacy without error using callback', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.PagedExpandLegacyRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.PagedExpandResponse(), + ); + client.innerApiCalls.pagedExpandLegacy = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.pagedExpandLegacy( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IPagedExpandResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes block with error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.BlockRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.block = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.block(request), expectedError); - }); + it('invokes pagedExpandLegacy with error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.PagedExpandLegacyRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.pagedExpandLegacy = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.pagedExpandLegacy(request), expectedError); + }); - it('invokes block with closed client', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.BlockRequest() - ); - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.block(request), expectedError); - }); + it('invokes pagedExpandLegacy with closed client', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.PagedExpandLegacyRequest(), + ); + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.pagedExpandLegacy(request), expectedError); + }); + }); + + describe('block', () => { + it('invokes block without error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.BlockRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.BlockResponse(), + ); + client.innerApiCalls.block = stubSimpleCall(expectedResponse); + const [response] = await client.block(request); + assert.deepStrictEqual(response, expectedResponse); }); - describe('wait', () => { - it('invokes wait without error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.WaitRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.wait = stubLongRunningCall(expectedResponse); - const [operation] = await client.wait(request); - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes block without error using callback', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.BlockRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.BlockResponse(), + ); + client.innerApiCalls.block = stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.block( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IBlockResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes wait without error using callback', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.WaitRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.wait = stubLongRunningCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.wait( - request, - (err?: Error|null, - result?: LROperation|null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const operation = await promise as LROperation; - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes block with error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.BlockRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.block = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.block(request), expectedError); + }); - it('invokes wait with call error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.WaitRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.wait = stubLongRunningCall(undefined, expectedError); - await assert.rejects(client.wait(request), expectedError); - }); + it('invokes block with closed client', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.BlockRequest(), + ); + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.block(request), expectedError); + }); + }); + + describe('wait', () => { + it('invokes wait without error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.WaitRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.wait = stubLongRunningCall(expectedResponse); + const [operation] = await client.wait(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes wait with LRO error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.WaitRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.wait = stubLongRunningCall(undefined, undefined, expectedError); - const [operation] = await client.wait(request); - await assert.rejects(operation.promise(), expectedError); - }); + it('invokes wait without error using callback', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.WaitRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.wait = + stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.wait( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.showcase.v1beta1.IWaitResponse, + protos.google.showcase.v1beta1.IWaitMetadata + > | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const operation = (await promise) as LROperation< + protos.google.showcase.v1beta1.IWaitResponse, + protos.google.showcase.v1beta1.IWaitMetadata + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes checkWaitProgress without error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedResponse = generateSampleMessage( - new operationsProtos.google.longrunning.Operation() - ); - expectedResponse.name = 'test'; - expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; - expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')} - - client.operationsClient.getOperation = stubSimpleCall(expectedResponse); - const decodedOperation = await client.checkWaitProgress(expectedResponse.name); - assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); - assert(decodedOperation.metadata); - assert((client.operationsClient.getOperation as SinonStub).getCall(0)); - }); + it('invokes wait with call error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.WaitRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.wait = stubLongRunningCall(undefined, expectedError); + await assert.rejects(client.wait(request), expectedError); + }); - it('invokes checkWaitProgress with error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedError = new Error('expected'); - - client.operationsClient.getOperation = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.checkWaitProgress(''), expectedError); - assert((client.operationsClient.getOperation as SinonStub) - .getCall(0)); - }); + it('invokes wait with LRO error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.WaitRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.wait = stubLongRunningCall( + undefined, + undefined, + expectedError, + ); + const [operation] = await client.wait(request); + await assert.rejects(operation.promise(), expectedError); }); - describe('expand', () => { - it('invokes expand without error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ExpandRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.EchoResponse() - ); - client.innerApiCalls.expand = stubServerStreamingCall(expectedResponse); - const stream = client.expand(request); - const promise = new Promise((resolve, reject) => { - stream.on('data', (response: protos.google.showcase.v1beta1.EchoResponse) => { - resolve(response); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes checkWaitProgress without error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation(), + ); + expectedResponse.name = 'test'; + expectedResponse.response = { type_url: 'url', value: Buffer.from('') }; + expectedResponse.metadata = { type_url: 'url', value: Buffer.from('') }; + + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const decodedOperation = await client.checkWaitProgress( + expectedResponse.name, + ); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); - it('invokes expand without error and gaxServerStreamingRetries enabled', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - gaxServerStreamingRetries: true - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ExpandRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.EchoResponse() - ); - client.innerApiCalls.expand = stubServerStreamingCall(expectedResponse); - const stream = client.expand(request); - const promise = new Promise((resolve, reject) => { - stream.on('data', (response: protos.google.showcase.v1beta1.EchoResponse) => { - resolve(response); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); + it('invokes checkWaitProgress with error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const expectedError = new Error('expected'); + + client.operationsClient.getOperation = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.checkWaitProgress(''), expectedError); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + }); + + describe('expand', () => { + it('invokes expand without error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ExpandRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.EchoResponse(), + ); + client.innerApiCalls.expand = stubServerStreamingCall(expectedResponse); + const stream = client.expand(request); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + (response: protos.google.showcase.v1beta1.EchoResponse) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes expand with error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ExpandRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.expand = stubServerStreamingCall(undefined, expectedError); - const stream = client.expand(request); - const promise = new Promise((resolve, reject) => { - stream.on('data', (response: protos.google.showcase.v1beta1.EchoResponse) => { - resolve(response); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); + it('invokes expand without error and gaxServerStreamingRetries enabled', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + gaxServerStreamingRetries: true, + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ExpandRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.EchoResponse(), + ); + client.innerApiCalls.expand = stubServerStreamingCall(expectedResponse); + const stream = client.expand(request); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + (response: protos.google.showcase.v1beta1.EchoResponse) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes expand with closed client', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ExpandRequest() - ); - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - const stream = client.expand(request, {retryRequestOptions: {noResponseRetries: 0}}); - const promise = new Promise((resolve, reject) => { - stream.on('data', (response: protos.google.showcase.v1beta1.EchoResponse) => { - resolve(response); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - }); - it('should create a client with gaxServerStreamingRetries enabled', () => { - const client = new echoModule.v1beta1.EchoClient({ - gaxServerStreamingRetries: true, - }); - assert(client); + it('invokes expand with error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ExpandRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.expand = stubServerStreamingCall( + undefined, + expectedError, + ); + const stream = client.expand(request); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + (response: protos.google.showcase.v1beta1.EchoResponse) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); }); + }); + await assert.rejects(promise, expectedError); }); - describe('chat', () => { - it('invokes chat without error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.EchoRequest() - ); - - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.EchoResponse() - ); - client.innerApiCalls.chat = stubBidiStreamingCall(expectedResponse); - const stream = client.chat(); - const promise = new Promise((resolve, reject) => { - stream.on('data', (response: protos.google.showcase.v1beta1.EchoResponse) => { - resolve(response); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - stream.write(request); - stream.end(); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - assert((client.innerApiCalls.chat as SinonStub) - .getCall(0).calledWith(null)); - assert.deepStrictEqual(((stream as unknown as PassThrough) - ._transform as SinonStub).getCall(0).args[0], request); + it('invokes expand with closed client', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ExpandRequest(), + ); + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + const stream = client.expand(request, { + retryRequestOptions: { noResponseRetries: 0 }, + }); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + (response: protos.google.showcase.v1beta1.EchoResponse) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); }); - - it('invokes chat with error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.EchoRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.chat = stubBidiStreamingCall(undefined, expectedError); - const stream = client.chat(); - const promise = new Promise((resolve, reject) => { - stream.on('data', (response: protos.google.showcase.v1beta1.EchoResponse) => { - resolve(response); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - stream.write(request); - stream.end(); - }); - await assert.rejects(promise, expectedError); - assert((client.innerApiCalls.chat as SinonStub) - .getCall(0).calledWith(null)); - assert.deepStrictEqual(((stream as unknown as PassThrough) - ._transform as SinonStub).getCall(0).args[0], request); + }); + await assert.rejects(promise, expectedError); + }); + it('should create a client with gaxServerStreamingRetries enabled', () => { + const client = new echoModule.v1beta1.EchoClient({ + gaxServerStreamingRetries: true, + }); + assert(client); + }); + }); + + describe('chat', () => { + it('invokes chat without error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.EchoRequest(), + ); + + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.EchoResponse(), + ); + client.innerApiCalls.chat = stubBidiStreamingCall(expectedResponse); + const stream = client.chat(); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + (response: protos.google.showcase.v1beta1.EchoResponse) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); }); + stream.write(request); + stream.end(); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + assert( + (client.innerApiCalls.chat as SinonStub).getCall(0).calledWith(null), + ); + assert.deepStrictEqual( + ((stream as unknown as PassThrough)._transform as SinonStub).getCall(0) + .args[0], + request, + ); }); - describe('collect', () => { - it('invokes collect without error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.EchoRequest() - ); - - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.EchoResponse() - ); - client.innerApiCalls.collect = stubClientStreamingCall(expectedResponse); - let stream: PassThrough; - const promise = new Promise((resolve, reject) => { - stream = client.collect( - (err?: Error|null, result?: protos.google.showcase.v1beta1.IEchoResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }) as unknown as PassThrough; - stream.write(request); - stream.end(); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - assert((client.innerApiCalls.collect as SinonStub) - .getCall(0).calledWith(null, {} /*, callback defined above */)); - assert.deepStrictEqual((stream!._transform as SinonStub).getCall(0).args[0], request); + it('invokes chat with error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.EchoRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.chat = stubBidiStreamingCall( + undefined, + expectedError, + ); + const stream = client.chat(); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + (response: protos.google.showcase.v1beta1.EchoResponse) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); }); + stream.write(request); + stream.end(); + }); + await assert.rejects(promise, expectedError); + assert( + (client.innerApiCalls.chat as SinonStub).getCall(0).calledWith(null), + ); + assert.deepStrictEqual( + ((stream as unknown as PassThrough)._transform as SinonStub).getCall(0) + .args[0], + request, + ); + }); + }); + + describe('collect', () => { + it('invokes collect without error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.EchoRequest(), + ); + + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.EchoResponse(), + ); + client.innerApiCalls.collect = stubClientStreamingCall(expectedResponse); + let stream: PassThrough; + const promise = new Promise((resolve, reject) => { + stream = client.collect( + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IEchoResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ) as unknown as PassThrough; + stream.write(request); + stream.end(); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + assert( + (client.innerApiCalls.collect as SinonStub) + .getCall(0) + .calledWith(null, {} /*, callback defined above */), + ); + assert.deepStrictEqual( + (stream!._transform as SinonStub).getCall(0).args[0], + request, + ); + }); - it('invokes collect with error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.EchoRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.collect = stubClientStreamingCall(undefined, expectedError); - let stream: PassThrough; - const promise = new Promise((resolve, reject) => { - stream = client.collect( - (err?: Error|null, result?: protos.google.showcase.v1beta1.IEchoResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }) as unknown as PassThrough; - stream.write(request); - stream.end(); - }); - await assert.rejects(promise, expectedError); - assert((client.innerApiCalls.collect as SinonStub) - .getCall(0).calledWith(null, {} /*, callback defined above */)); - }); + it('invokes collect with error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.EchoRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.collect = stubClientStreamingCall( + undefined, + expectedError, + ); + let stream: PassThrough; + const promise = new Promise((resolve, reject) => { + stream = client.collect( + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IEchoResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ) as unknown as PassThrough; + stream.write(request); + stream.end(); + }); + await assert.rejects(promise, expectedError); + assert( + (client.innerApiCalls.collect as SinonStub) + .getCall(0) + .calledWith(null, {} /*, callback defined above */), + ); + }); + }); + + describe('pagedExpand', () => { + it('invokes pagedExpand without error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.PagedExpandRequest(), + ); + const expectedResponse = [ + generateSampleMessage( + new protos.google.showcase.v1beta1.EchoResponse(), + ), + generateSampleMessage( + new protos.google.showcase.v1beta1.EchoResponse(), + ), + generateSampleMessage( + new protos.google.showcase.v1beta1.EchoResponse(), + ), + ]; + client.innerApiCalls.pagedExpand = stubSimpleCall(expectedResponse); + const [response] = await client.pagedExpand(request); + assert.deepStrictEqual(response, expectedResponse); }); - describe('pagedExpand', () => { - it('invokes pagedExpand without error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.PagedExpandRequest() - );const expectedResponse = [ - generateSampleMessage(new protos.google.showcase.v1beta1.EchoResponse()), - generateSampleMessage(new protos.google.showcase.v1beta1.EchoResponse()), - generateSampleMessage(new protos.google.showcase.v1beta1.EchoResponse()), - ]; - client.innerApiCalls.pagedExpand = stubSimpleCall(expectedResponse); - const [response] = await client.pagedExpand(request); - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes pagedExpand without error using callback', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.PagedExpandRequest(), + ); + const expectedResponse = [ + generateSampleMessage( + new protos.google.showcase.v1beta1.EchoResponse(), + ), + generateSampleMessage( + new protos.google.showcase.v1beta1.EchoResponse(), + ), + generateSampleMessage( + new protos.google.showcase.v1beta1.EchoResponse(), + ), + ]; + client.innerApiCalls.pagedExpand = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.pagedExpand( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IEchoResponse[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes pagedExpand without error using callback', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.PagedExpandRequest() - );const expectedResponse = [ - generateSampleMessage(new protos.google.showcase.v1beta1.EchoResponse()), - generateSampleMessage(new protos.google.showcase.v1beta1.EchoResponse()), - generateSampleMessage(new protos.google.showcase.v1beta1.EchoResponse()), - ]; - client.innerApiCalls.pagedExpand = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.pagedExpand( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IEchoResponse[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes pagedExpand with error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.PagedExpandRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.pagedExpand = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.pagedExpand(request), expectedError); + }); - it('invokes pagedExpand with error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.PagedExpandRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.pagedExpand = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.pagedExpand(request), expectedError); + it('invokes pagedExpandStream without error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.PagedExpandRequest(), + ); + const expectedResponse = [ + generateSampleMessage( + new protos.google.showcase.v1beta1.EchoResponse(), + ), + generateSampleMessage( + new protos.google.showcase.v1beta1.EchoResponse(), + ), + generateSampleMessage( + new protos.google.showcase.v1beta1.EchoResponse(), + ), + ]; + client.descriptors.page.pagedExpand.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.pagedExpandStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.showcase.v1beta1.EchoResponse[] = []; + stream.on( + 'data', + (response: protos.google.showcase.v1beta1.EchoResponse) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); }); - - it('invokes pagedExpandStream without error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.PagedExpandRequest() - ); - const expectedResponse = [ - generateSampleMessage(new protos.google.showcase.v1beta1.EchoResponse()), - generateSampleMessage(new protos.google.showcase.v1beta1.EchoResponse()), - generateSampleMessage(new protos.google.showcase.v1beta1.EchoResponse()), - ]; - client.descriptors.page.pagedExpand.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.pagedExpandStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.showcase.v1beta1.EchoResponse[] = []; - stream.on('data', (response: protos.google.showcase.v1beta1.EchoResponse) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.pagedExpand.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.pagedExpand, request)); + stream.on('error', (err: Error) => { + reject(err); }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.pagedExpand.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.pagedExpand, request), + ); + }); - it('invokes pagedExpandStream with error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.PagedExpandRequest() - ); - const expectedError = new Error('expected'); - client.descriptors.page.pagedExpand.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.pagedExpandStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.showcase.v1beta1.EchoResponse[] = []; - stream.on('data', (response: protos.google.showcase.v1beta1.EchoResponse) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.pagedExpand.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.pagedExpand, request)); + it('invokes pagedExpandStream with error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.PagedExpandRequest(), + ); + const expectedError = new Error('expected'); + client.descriptors.page.pagedExpand.createStream = stubPageStreamingCall( + undefined, + expectedError, + ); + const stream = client.pagedExpandStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.showcase.v1beta1.EchoResponse[] = []; + stream.on( + 'data', + (response: protos.google.showcase.v1beta1.EchoResponse) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); }); - - it('uses async iteration with pagedExpand without error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.PagedExpandRequest() - ); - const expectedResponse = [ - generateSampleMessage(new protos.google.showcase.v1beta1.EchoResponse()), - generateSampleMessage(new protos.google.showcase.v1beta1.EchoResponse()), - generateSampleMessage(new protos.google.showcase.v1beta1.EchoResponse()), - ]; - client.descriptors.page.pagedExpand.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.showcase.v1beta1.IEchoResponse[] = []; - const iterable = client.pagedExpandAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.pagedExpand.asyncIterate as SinonStub) - .getCall(0).args[1], request); + stream.on('error', (err: Error) => { + reject(err); }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.pagedExpand.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.pagedExpand, request), + ); + }); - it('uses async iteration with pagedExpand with error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.PagedExpandRequest() - ); - const expectedError = new Error('expected'); - client.descriptors.page.pagedExpand.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.pagedExpandAsync(request); - await assert.rejects(async () => { - const responses: protos.google.showcase.v1beta1.IEchoResponse[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.pagedExpand.asyncIterate as SinonStub) - .getCall(0).args[1], request); - }); + it('uses async iteration with pagedExpand without error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.PagedExpandRequest(), + ); + const expectedResponse = [ + generateSampleMessage( + new protos.google.showcase.v1beta1.EchoResponse(), + ), + generateSampleMessage( + new protos.google.showcase.v1beta1.EchoResponse(), + ), + generateSampleMessage( + new protos.google.showcase.v1beta1.EchoResponse(), + ), + ]; + client.descriptors.page.pagedExpand.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.showcase.v1beta1.IEchoResponse[] = []; + const iterable = client.pagedExpandAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + (client.descriptors.page.pagedExpand.asyncIterate as SinonStub).getCall( + 0, + ).args[1], + request, + ); }); + it('uses async iteration with pagedExpand with error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.PagedExpandRequest(), + ); + const expectedError = new Error('expected'); + client.descriptors.page.pagedExpand.asyncIterate = stubAsyncIterationCall( + undefined, + expectedError, + ); + const iterable = client.pagedExpandAsync(request); + await assert.rejects(async () => { + const responses: protos.google.showcase.v1beta1.IEchoResponse[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + (client.descriptors.page.pagedExpand.asyncIterate as SinonStub).getCall( + 0, + ).args[1], + request, + ); + }); + }); }); diff --git a/core/generator/gapic-generator-typescript/baselines/showcase/src/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/showcase/src/index.ts.baseline index 55fd8ef14d16..9d0e7c754471 100644 --- a/core/generator/gapic-generator-typescript/baselines/showcase/src/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/showcase/src/index.ts.baseline @@ -29,7 +29,23 @@ const SequenceServiceClient = v1beta1.SequenceServiceClient; type SequenceServiceClient = v1beta1.SequenceServiceClient; const TestingClient = v1beta1.TestingClient; type TestingClient = v1beta1.TestingClient; -export {v1beta1, ComplianceClient, EchoClient, IdentityClient, MessagingClient, SequenceServiceClient, TestingClient}; -export default {v1beta1, ComplianceClient, EchoClient, IdentityClient, MessagingClient, SequenceServiceClient, TestingClient}; +export { + v1beta1, + ComplianceClient, + EchoClient, + IdentityClient, + MessagingClient, + SequenceServiceClient, + TestingClient, +}; +export default { + v1beta1, + ComplianceClient, + EchoClient, + IdentityClient, + MessagingClient, + SequenceServiceClient, + TestingClient, +}; import * as protos from '../protos/protos'; -export {protos} +export { protos }; diff --git a/core/generator/gapic-generator-typescript/baselines/showcase/src/v1beta1/compliance_client.ts.baseline b/core/generator/gapic-generator-typescript/baselines/showcase/src/v1beta1/compliance_client.ts.baseline index c46fdb04a76c..f29e0423713d 100644 --- a/core/generator/gapic-generator-typescript/baselines/showcase/src/v1beta1/compliance_client.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/showcase/src/v1beta1/compliance_client.ts.baseline @@ -18,11 +18,16 @@ /* global window */ import type * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions} from 'google-gax'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, +} from 'google-gax'; import * as protos from '../../protos/protos'; import jsonProtos = require('../../protos/protos.json'); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; /** * Client JSON configuration object, loaded from @@ -46,7 +51,7 @@ export class ComplianceClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('showcase'); @@ -59,9 +64,9 @@ export class ComplianceClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; - complianceStub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; + complianceStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of ComplianceClient. @@ -102,21 +107,42 @@ export class ComplianceClient { * const client = new ComplianceClient({fallback: true}, gax); * ``` */ - constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { // Ensure that options include all the required fields. const staticMembers = this.constructor as typeof ComplianceClient; - if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { - throw new Error('Please set either universe_domain or universeDomain, but not both.'); + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); } - const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; - this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; this._servicePath = 'localhost'; - const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; - const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // Request numeric enum values if REST transport is used. opts.numericEnums = true; @@ -141,7 +167,7 @@ export class ComplianceClient { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; @@ -155,10 +181,7 @@ export class ComplianceClient { } // Determine the client header string. - const clientHeader = [ - `gax/${this._gaxModule.version}`, - `gapic/${version}`, - ]; + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/${process.versions.node}`); } else { @@ -180,44 +203,44 @@ export class ComplianceClient { // Create useful helper objects for these. this.pathTemplates = { blueprintPathTemplate: new this._gaxModule.PathTemplate( - 'sessions/{session}/tests/{test}/blueprints/{blueprint}' - ), - roomPathTemplate: new this._gaxModule.PathTemplate( - 'rooms/{room}' + 'sessions/{session}/tests/{test}/blueprints/{blueprint}', ), + roomPathTemplate: new this._gaxModule.PathTemplate('rooms/{room}'), roomBlurbPathTemplate: new this._gaxModule.PathTemplate( - 'rooms/{room}/blurbs/{blurb}' + 'rooms/{room}/blurbs/{blurb}', ), roomBlurbsLegacyRoomBlurbPathTemplate: new this._gaxModule.PathTemplate( - 'rooms/{room}/blurbs/legacy/{legacy_room}.{blurb}' + 'rooms/{room}/blurbs/legacy/{legacy_room}.{blurb}', ), sequencePathTemplate: new this._gaxModule.PathTemplate( - 'sequences/{sequence}' + 'sequences/{sequence}', ), sequenceReportPathTemplate: new this._gaxModule.PathTemplate( - 'sequences/{sequence}/sequenceReport' + 'sequences/{sequence}/sequenceReport', ), sessionPathTemplate: new this._gaxModule.PathTemplate( - 'sessions/{session}' + 'sessions/{session}', ), testPathTemplate: new this._gaxModule.PathTemplate( - 'sessions/{session}/tests/{test}' - ), - userPathTemplate: new this._gaxModule.PathTemplate( - 'users/{user}' + 'sessions/{session}/tests/{test}', ), + userPathTemplate: new this._gaxModule.PathTemplate('users/{user}'), userProfileBlurbPathTemplate: new this._gaxModule.PathTemplate( - 'users/{user}/profile/blurbs/{blurb}' - ), - userProfileBlurbsLegacyUserBlurbPathTemplate: new this._gaxModule.PathTemplate( - 'users/{user}/profile/blurbs/legacy/{legacy_user}~{blurb}' + 'users/{user}/profile/blurbs/{blurb}', ), + userProfileBlurbsLegacyUserBlurbPathTemplate: + new this._gaxModule.PathTemplate( + 'users/{user}/profile/blurbs/legacy/{legacy_user}~{blurb}', + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.showcase.v1beta1.Compliance', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.showcase.v1beta1.Compliance', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + { 'x-goog-api-client': clientHeader.join(' ') }, + ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -248,36 +271,51 @@ export class ComplianceClient { // Put together the "service stub" for // google.showcase.v1beta1.Compliance. this.complianceStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.showcase.v1beta1.Compliance') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.showcase.v1beta1.Compliance', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.showcase.v1beta1.Compliance, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts, + this._providedCustomServicePath, + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const complianceStubMethods = - ['repeatDataBody', 'repeatDataBodyInfo', 'repeatDataQuery', 'repeatDataSimplePath', 'repeatDataPathResource', 'repeatDataPathTrailingResource', 'repeatDataBodyPut', 'repeatDataBodyPatch', 'getEnum', 'verifyEnum']; + const complianceStubMethods = [ + 'repeatDataBody', + 'repeatDataBodyInfo', + 'repeatDataQuery', + 'repeatDataSimplePath', + 'repeatDataPathResource', + 'repeatDataPathTrailingResource', + 'repeatDataBodyPut', + 'repeatDataBodyPatch', + 'getEnum', + 'verifyEnum', + ]; for (const methodName of complianceStubMethods) { const callPromise = this.complianceStub.then( - stub => (...args: Array<{}>) => { - if (this._terminated) { - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error|null|undefined) => () => { + (stub) => + (...args: Array<{}>) => { + if (this._terminated) { + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { throw err; - }); + }, + ); - const descriptor = - undefined; + const descriptor = undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -292,8 +330,14 @@ export class ComplianceClient { * @returns {string} The DNS address for this service. */ static get servicePath() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'localhost'; } @@ -304,8 +348,14 @@ export class ComplianceClient { * @returns {string} The DNS address for this service. */ static get apiEndpoint() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'localhost'; } @@ -345,8 +395,9 @@ export class ComplianceClient { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId(callback?: Callback): - Promise|void { + getProjectId( + callback?: Callback, + ): Promise | void { if (callback) { this.auth.getProjectId(callback); return; @@ -357,1036 +408,1349 @@ export class ComplianceClient { // ------------------- // -- Service calls -- // ------------------- -/** - * This method echoes the ComplianceData request. This method exercises - * sending the entire request object in the REST body. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * @param {google.showcase.v1beta1.ComplianceData} request.info - * @param {boolean} request.serverVerify - * If true, the server will verify that the received request matches - * the request with the same name in the compliance test suite. - * @param {string} request.intendedBindingUri - * The URI template this request is expected to be bound to server-side. - * @param {number} request.fInt32 - * Some top level fields, to test that these are encoded correctly - * in query params. - * @param {number} request.fInt64 - * @param {number} request.fDouble - * @param {number} request.pInt32 - * @param {number} request.pInt64 - * @param {number} request.pDouble - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.RepeatResponse|RepeatResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/compliance.repeat_data_body.js - * region_tag:localhost_v1beta1_generated_Compliance_RepeatDataBody_async - */ + /** + * This method echoes the ComplianceData request. This method exercises + * sending the entire request object in the REST body. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * @param {google.showcase.v1beta1.ComplianceData} request.info + * @param {boolean} request.serverVerify + * If true, the server will verify that the received request matches + * the request with the same name in the compliance test suite. + * @param {string} request.intendedBindingUri + * The URI template this request is expected to be bound to server-side. + * @param {number} request.fInt32 + * Some top level fields, to test that these are encoded correctly + * in query params. + * @param {number} request.fInt64 + * @param {number} request.fDouble + * @param {number} request.pInt32 + * @param {number} request.pInt64 + * @param {number} request.pDouble + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.RepeatResponse|RepeatResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/compliance.repeat_data_body.js + * region_tag:localhost_v1beta1_generated_Compliance_RepeatDataBody_async + */ repeatDataBody( - request?: protos.google.showcase.v1beta1.IRepeatRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IRepeatRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | undefined, + {} | undefined, + ] + >; repeatDataBody( - request: protos.google.showcase.v1beta1.IRepeatRequest, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IRepeatRequest, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + ): void; repeatDataBody( - request: protos.google.showcase.v1beta1.IRepeatRequest, - callback: Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IRepeatRequest, + callback: Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + ): void; repeatDataBody( - request?: protos.google.showcase.v1beta1.IRepeatRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.showcase.v1beta1.IRepeatRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|undefined, {}|undefined - ]>|void { + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('repeatDataBody request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('repeatDataBody response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.repeatDataBody(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|undefined, - {}|undefined - ]) => { - this._log.info('repeatDataBody response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .repeatDataBody(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | undefined, + {} | undefined, + ]) => { + this._log.info('repeatDataBody response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * This method echoes the ComplianceData request. This method exercises - * sending the a message-type field in the REST body. Per AIP-127, only - * top-level, non-repeated fields can be sent this way. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * @param {google.showcase.v1beta1.ComplianceData} request.info - * @param {boolean} request.serverVerify - * If true, the server will verify that the received request matches - * the request with the same name in the compliance test suite. - * @param {string} request.intendedBindingUri - * The URI template this request is expected to be bound to server-side. - * @param {number} request.fInt32 - * Some top level fields, to test that these are encoded correctly - * in query params. - * @param {number} request.fInt64 - * @param {number} request.fDouble - * @param {number} request.pInt32 - * @param {number} request.pInt64 - * @param {number} request.pDouble - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.RepeatResponse|RepeatResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/compliance.repeat_data_body_info.js - * region_tag:localhost_v1beta1_generated_Compliance_RepeatDataBodyInfo_async - */ + /** + * This method echoes the ComplianceData request. This method exercises + * sending the a message-type field in the REST body. Per AIP-127, only + * top-level, non-repeated fields can be sent this way. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * @param {google.showcase.v1beta1.ComplianceData} request.info + * @param {boolean} request.serverVerify + * If true, the server will verify that the received request matches + * the request with the same name in the compliance test suite. + * @param {string} request.intendedBindingUri + * The URI template this request is expected to be bound to server-side. + * @param {number} request.fInt32 + * Some top level fields, to test that these are encoded correctly + * in query params. + * @param {number} request.fInt64 + * @param {number} request.fDouble + * @param {number} request.pInt32 + * @param {number} request.pInt64 + * @param {number} request.pDouble + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.RepeatResponse|RepeatResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/compliance.repeat_data_body_info.js + * region_tag:localhost_v1beta1_generated_Compliance_RepeatDataBodyInfo_async + */ repeatDataBodyInfo( - request?: protos.google.showcase.v1beta1.IRepeatRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IRepeatRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | undefined, + {} | undefined, + ] + >; repeatDataBodyInfo( - request: protos.google.showcase.v1beta1.IRepeatRequest, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IRepeatRequest, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + ): void; repeatDataBodyInfo( - request: protos.google.showcase.v1beta1.IRepeatRequest, - callback: Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IRepeatRequest, + callback: Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + ): void; repeatDataBodyInfo( - request?: protos.google.showcase.v1beta1.IRepeatRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.showcase.v1beta1.IRepeatRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|undefined, {}|undefined - ]>|void { + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('repeatDataBodyInfo request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('repeatDataBodyInfo response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.repeatDataBodyInfo(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|undefined, - {}|undefined - ]) => { - this._log.info('repeatDataBodyInfo response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .repeatDataBodyInfo(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | undefined, + {} | undefined, + ]) => { + this._log.info('repeatDataBodyInfo response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * This method echoes the ComplianceData request. This method exercises - * sending all request fields as query parameters. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * @param {google.showcase.v1beta1.ComplianceData} request.info - * @param {boolean} request.serverVerify - * If true, the server will verify that the received request matches - * the request with the same name in the compliance test suite. - * @param {string} request.intendedBindingUri - * The URI template this request is expected to be bound to server-side. - * @param {number} request.fInt32 - * Some top level fields, to test that these are encoded correctly - * in query params. - * @param {number} request.fInt64 - * @param {number} request.fDouble - * @param {number} request.pInt32 - * @param {number} request.pInt64 - * @param {number} request.pDouble - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.RepeatResponse|RepeatResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/compliance.repeat_data_query.js - * region_tag:localhost_v1beta1_generated_Compliance_RepeatDataQuery_async - */ + /** + * This method echoes the ComplianceData request. This method exercises + * sending all request fields as query parameters. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * @param {google.showcase.v1beta1.ComplianceData} request.info + * @param {boolean} request.serverVerify + * If true, the server will verify that the received request matches + * the request with the same name in the compliance test suite. + * @param {string} request.intendedBindingUri + * The URI template this request is expected to be bound to server-side. + * @param {number} request.fInt32 + * Some top level fields, to test that these are encoded correctly + * in query params. + * @param {number} request.fInt64 + * @param {number} request.fDouble + * @param {number} request.pInt32 + * @param {number} request.pInt64 + * @param {number} request.pDouble + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.RepeatResponse|RepeatResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/compliance.repeat_data_query.js + * region_tag:localhost_v1beta1_generated_Compliance_RepeatDataQuery_async + */ repeatDataQuery( - request?: protos.google.showcase.v1beta1.IRepeatRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IRepeatRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | undefined, + {} | undefined, + ] + >; repeatDataQuery( - request: protos.google.showcase.v1beta1.IRepeatRequest, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IRepeatRequest, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + ): void; repeatDataQuery( - request: protos.google.showcase.v1beta1.IRepeatRequest, - callback: Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IRepeatRequest, + callback: Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + ): void; repeatDataQuery( - request?: protos.google.showcase.v1beta1.IRepeatRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.showcase.v1beta1.IRepeatRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|undefined, {}|undefined - ]>|void { + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('repeatDataQuery request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('repeatDataQuery response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.repeatDataQuery(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|undefined, - {}|undefined - ]) => { - this._log.info('repeatDataQuery response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .repeatDataQuery(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | undefined, + {} | undefined, + ]) => { + this._log.info('repeatDataQuery response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * This method echoes the ComplianceData request. This method exercises - * sending some parameters as "simple" path variables (i.e., of the form - * "/bar/{foo}" rather than "/{foo=bar/*}"), and the rest as query parameters. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * @param {google.showcase.v1beta1.ComplianceData} request.info - * @param {boolean} request.serverVerify - * If true, the server will verify that the received request matches - * the request with the same name in the compliance test suite. - * @param {string} request.intendedBindingUri - * The URI template this request is expected to be bound to server-side. - * @param {number} request.fInt32 - * Some top level fields, to test that these are encoded correctly - * in query params. - * @param {number} request.fInt64 - * @param {number} request.fDouble - * @param {number} request.pInt32 - * @param {number} request.pInt64 - * @param {number} request.pDouble - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.RepeatResponse|RepeatResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/compliance.repeat_data_simple_path.js - * region_tag:localhost_v1beta1_generated_Compliance_RepeatDataSimplePath_async - */ + /** + * This method echoes the ComplianceData request. This method exercises + * sending some parameters as "simple" path variables (i.e., of the form + * "/bar/{foo}" rather than "/{foo=bar/*}"), and the rest as query parameters. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * @param {google.showcase.v1beta1.ComplianceData} request.info + * @param {boolean} request.serverVerify + * If true, the server will verify that the received request matches + * the request with the same name in the compliance test suite. + * @param {string} request.intendedBindingUri + * The URI template this request is expected to be bound to server-side. + * @param {number} request.fInt32 + * Some top level fields, to test that these are encoded correctly + * in query params. + * @param {number} request.fInt64 + * @param {number} request.fDouble + * @param {number} request.pInt32 + * @param {number} request.pInt64 + * @param {number} request.pDouble + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.RepeatResponse|RepeatResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/compliance.repeat_data_simple_path.js + * region_tag:localhost_v1beta1_generated_Compliance_RepeatDataSimplePath_async + */ repeatDataSimplePath( - request?: protos.google.showcase.v1beta1.IRepeatRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IRepeatRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | undefined, + {} | undefined, + ] + >; repeatDataSimplePath( - request: protos.google.showcase.v1beta1.IRepeatRequest, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IRepeatRequest, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + ): void; repeatDataSimplePath( - request: protos.google.showcase.v1beta1.IRepeatRequest, - callback: Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IRepeatRequest, + callback: Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + ): void; repeatDataSimplePath( - request?: protos.google.showcase.v1beta1.IRepeatRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.showcase.v1beta1.IRepeatRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|undefined, {}|undefined - ]>|void { + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'info.f_string': request.info!.fString ?? '', - 'info.f_int32': request.info!.fInt32 ?? '', - 'info.f_double': request.info!.fDouble ?? '', - 'info.f_bool': request.info!.fBool ?? '', - 'info.f_kingdom': request.info!.fKingdom ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'info.f_string': request.info!.fString ?? '', + 'info.f_int32': request.info!.fInt32 ?? '', + 'info.f_double': request.info!.fDouble ?? '', + 'info.f_bool': request.info!.fBool ?? '', + 'info.f_kingdom': request.info!.fKingdom ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('repeatDataSimplePath request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('repeatDataSimplePath response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.repeatDataSimplePath(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|undefined, - {}|undefined - ]) => { - this._log.info('repeatDataSimplePath response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .repeatDataSimplePath(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | undefined, + {} | undefined, + ]) => { + this._log.info('repeatDataSimplePath response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Same as RepeatDataSimplePath, but with a path resource. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * @param {google.showcase.v1beta1.ComplianceData} request.info - * @param {boolean} request.serverVerify - * If true, the server will verify that the received request matches - * the request with the same name in the compliance test suite. - * @param {string} request.intendedBindingUri - * The URI template this request is expected to be bound to server-side. - * @param {number} request.fInt32 - * Some top level fields, to test that these are encoded correctly - * in query params. - * @param {number} request.fInt64 - * @param {number} request.fDouble - * @param {number} request.pInt32 - * @param {number} request.pInt64 - * @param {number} request.pDouble - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.RepeatResponse|RepeatResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/compliance.repeat_data_path_resource.js - * region_tag:localhost_v1beta1_generated_Compliance_RepeatDataPathResource_async - */ + /** + * Same as RepeatDataSimplePath, but with a path resource. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * @param {google.showcase.v1beta1.ComplianceData} request.info + * @param {boolean} request.serverVerify + * If true, the server will verify that the received request matches + * the request with the same name in the compliance test suite. + * @param {string} request.intendedBindingUri + * The URI template this request is expected to be bound to server-side. + * @param {number} request.fInt32 + * Some top level fields, to test that these are encoded correctly + * in query params. + * @param {number} request.fInt64 + * @param {number} request.fDouble + * @param {number} request.pInt32 + * @param {number} request.pInt64 + * @param {number} request.pDouble + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.RepeatResponse|RepeatResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/compliance.repeat_data_path_resource.js + * region_tag:localhost_v1beta1_generated_Compliance_RepeatDataPathResource_async + */ repeatDataPathResource( - request?: protos.google.showcase.v1beta1.IRepeatRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IRepeatRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | undefined, + {} | undefined, + ] + >; repeatDataPathResource( - request: protos.google.showcase.v1beta1.IRepeatRequest, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IRepeatRequest, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + ): void; repeatDataPathResource( - request: protos.google.showcase.v1beta1.IRepeatRequest, - callback: Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IRepeatRequest, + callback: Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + ): void; repeatDataPathResource( - request?: protos.google.showcase.v1beta1.IRepeatRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.showcase.v1beta1.IRepeatRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|undefined, {}|undefined - ]>|void { + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'info.f_string': request.info!.fString ?? '', - 'info.f_child.f_string': request.info!.fChild!.fString ?? '', - 'info.f_bool': request.info!.fBool ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'info.f_string': request.info!.fString ?? '', + 'info.f_child.f_string': request.info!.fChild!.fString ?? '', + 'info.f_bool': request.info!.fBool ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('repeatDataPathResource request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('repeatDataPathResource response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.repeatDataPathResource(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|undefined, - {}|undefined - ]) => { - this._log.info('repeatDataPathResource response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .repeatDataPathResource(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | undefined, + {} | undefined, + ]) => { + this._log.info('repeatDataPathResource response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Same as RepeatDataSimplePath, but with a trailing resource. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * @param {google.showcase.v1beta1.ComplianceData} request.info - * @param {boolean} request.serverVerify - * If true, the server will verify that the received request matches - * the request with the same name in the compliance test suite. - * @param {string} request.intendedBindingUri - * The URI template this request is expected to be bound to server-side. - * @param {number} request.fInt32 - * Some top level fields, to test that these are encoded correctly - * in query params. - * @param {number} request.fInt64 - * @param {number} request.fDouble - * @param {number} request.pInt32 - * @param {number} request.pInt64 - * @param {number} request.pDouble - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.RepeatResponse|RepeatResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/compliance.repeat_data_path_trailing_resource.js - * region_tag:localhost_v1beta1_generated_Compliance_RepeatDataPathTrailingResource_async - */ + /** + * Same as RepeatDataSimplePath, but with a trailing resource. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * @param {google.showcase.v1beta1.ComplianceData} request.info + * @param {boolean} request.serverVerify + * If true, the server will verify that the received request matches + * the request with the same name in the compliance test suite. + * @param {string} request.intendedBindingUri + * The URI template this request is expected to be bound to server-side. + * @param {number} request.fInt32 + * Some top level fields, to test that these are encoded correctly + * in query params. + * @param {number} request.fInt64 + * @param {number} request.fDouble + * @param {number} request.pInt32 + * @param {number} request.pInt64 + * @param {number} request.pDouble + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.RepeatResponse|RepeatResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/compliance.repeat_data_path_trailing_resource.js + * region_tag:localhost_v1beta1_generated_Compliance_RepeatDataPathTrailingResource_async + */ repeatDataPathTrailingResource( - request?: protos.google.showcase.v1beta1.IRepeatRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IRepeatRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | undefined, + {} | undefined, + ] + >; repeatDataPathTrailingResource( - request: protos.google.showcase.v1beta1.IRepeatRequest, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IRepeatRequest, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + ): void; repeatDataPathTrailingResource( - request: protos.google.showcase.v1beta1.IRepeatRequest, - callback: Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IRepeatRequest, + callback: Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + ): void; repeatDataPathTrailingResource( - request?: protos.google.showcase.v1beta1.IRepeatRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.showcase.v1beta1.IRepeatRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|undefined, {}|undefined - ]>|void { + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'info.f_string': request.info!.fString ?? '', - 'info.f_child.f_string': request.info!.fChild!.fString ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'info.f_string': request.info!.fString ?? '', + 'info.f_child.f_string': request.info!.fChild!.fString ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('repeatDataPathTrailingResource request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { - this._log.info('repeatDataPathTrailingResource response %j', response); + this._log.info( + 'repeatDataPathTrailingResource response %j', + response, + ); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.repeatDataPathTrailingResource(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|undefined, - {}|undefined - ]) => { - this._log.info('repeatDataPathTrailingResource response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .repeatDataPathTrailingResource(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | undefined, + {} | undefined, + ]) => { + this._log.info( + 'repeatDataPathTrailingResource response %j', + response, + ); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * This method echoes the ComplianceData request, using the HTTP PUT method. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * @param {google.showcase.v1beta1.ComplianceData} request.info - * @param {boolean} request.serverVerify - * If true, the server will verify that the received request matches - * the request with the same name in the compliance test suite. - * @param {string} request.intendedBindingUri - * The URI template this request is expected to be bound to server-side. - * @param {number} request.fInt32 - * Some top level fields, to test that these are encoded correctly - * in query params. - * @param {number} request.fInt64 - * @param {number} request.fDouble - * @param {number} request.pInt32 - * @param {number} request.pInt64 - * @param {number} request.pDouble - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.RepeatResponse|RepeatResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/compliance.repeat_data_body_put.js - * region_tag:localhost_v1beta1_generated_Compliance_RepeatDataBodyPut_async - */ + /** + * This method echoes the ComplianceData request, using the HTTP PUT method. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * @param {google.showcase.v1beta1.ComplianceData} request.info + * @param {boolean} request.serverVerify + * If true, the server will verify that the received request matches + * the request with the same name in the compliance test suite. + * @param {string} request.intendedBindingUri + * The URI template this request is expected to be bound to server-side. + * @param {number} request.fInt32 + * Some top level fields, to test that these are encoded correctly + * in query params. + * @param {number} request.fInt64 + * @param {number} request.fDouble + * @param {number} request.pInt32 + * @param {number} request.pInt64 + * @param {number} request.pDouble + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.RepeatResponse|RepeatResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/compliance.repeat_data_body_put.js + * region_tag:localhost_v1beta1_generated_Compliance_RepeatDataBodyPut_async + */ repeatDataBodyPut( - request?: protos.google.showcase.v1beta1.IRepeatRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IRepeatRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | undefined, + {} | undefined, + ] + >; repeatDataBodyPut( - request: protos.google.showcase.v1beta1.IRepeatRequest, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IRepeatRequest, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + ): void; repeatDataBodyPut( - request: protos.google.showcase.v1beta1.IRepeatRequest, - callback: Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IRepeatRequest, + callback: Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + ): void; repeatDataBodyPut( - request?: protos.google.showcase.v1beta1.IRepeatRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.showcase.v1beta1.IRepeatRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|undefined, {}|undefined - ]>|void { + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('repeatDataBodyPut request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('repeatDataBodyPut response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.repeatDataBodyPut(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|undefined, - {}|undefined - ]) => { - this._log.info('repeatDataBodyPut response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .repeatDataBodyPut(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | undefined, + {} | undefined, + ]) => { + this._log.info('repeatDataBodyPut response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * This method echoes the ComplianceData request, using the HTTP PATCH method. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * @param {google.showcase.v1beta1.ComplianceData} request.info - * @param {boolean} request.serverVerify - * If true, the server will verify that the received request matches - * the request with the same name in the compliance test suite. - * @param {string} request.intendedBindingUri - * The URI template this request is expected to be bound to server-side. - * @param {number} request.fInt32 - * Some top level fields, to test that these are encoded correctly - * in query params. - * @param {number} request.fInt64 - * @param {number} request.fDouble - * @param {number} request.pInt32 - * @param {number} request.pInt64 - * @param {number} request.pDouble - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.RepeatResponse|RepeatResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/compliance.repeat_data_body_patch.js - * region_tag:localhost_v1beta1_generated_Compliance_RepeatDataBodyPatch_async - */ + /** + * This method echoes the ComplianceData request, using the HTTP PATCH method. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * @param {google.showcase.v1beta1.ComplianceData} request.info + * @param {boolean} request.serverVerify + * If true, the server will verify that the received request matches + * the request with the same name in the compliance test suite. + * @param {string} request.intendedBindingUri + * The URI template this request is expected to be bound to server-side. + * @param {number} request.fInt32 + * Some top level fields, to test that these are encoded correctly + * in query params. + * @param {number} request.fInt64 + * @param {number} request.fDouble + * @param {number} request.pInt32 + * @param {number} request.pInt64 + * @param {number} request.pDouble + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.RepeatResponse|RepeatResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/compliance.repeat_data_body_patch.js + * region_tag:localhost_v1beta1_generated_Compliance_RepeatDataBodyPatch_async + */ repeatDataBodyPatch( - request?: protos.google.showcase.v1beta1.IRepeatRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IRepeatRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | undefined, + {} | undefined, + ] + >; repeatDataBodyPatch( - request: protos.google.showcase.v1beta1.IRepeatRequest, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IRepeatRequest, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + ): void; repeatDataBodyPatch( - request: protos.google.showcase.v1beta1.IRepeatRequest, - callback: Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IRepeatRequest, + callback: Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + ): void; repeatDataBodyPatch( - request?: protos.google.showcase.v1beta1.IRepeatRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.showcase.v1beta1.IRepeatRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|undefined, {}|undefined - ]>|void { + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('repeatDataBodyPatch request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('repeatDataBodyPatch response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.repeatDataBodyPatch(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.IRepeatResponse, - protos.google.showcase.v1beta1.IRepeatRequest|undefined, - {}|undefined - ]) => { - this._log.info('repeatDataBodyPatch response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .repeatDataBodyPatch(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.IRepeatResponse, + protos.google.showcase.v1beta1.IRepeatRequest | undefined, + {} | undefined, + ]) => { + this._log.info('repeatDataBodyPatch response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * This method requests an enum value from the server. Depending on the contents of EnumRequest, the enum value returned will be a known enum declared in the - * .proto file, or a made-up enum value the is unknown to the client. To verify that clients can round-trip unknown enum vaues they receive, use the - * response from this RPC as the request to VerifyEnum() - * - * The values of enums sent by the server when a known or unknown value is requested will be the same within a single Showcase server run (this is needed for - * VerifyEnum() to work) but are not guaranteed to be the same across separate Showcase server runs. - * - * @param {Object} request - * The request object that will be sent. - * @param {boolean} request.unknownEnum - * Whether the client is requesting a new, unknown enum value or a known enum value already declard in this proto file. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.EnumResponse|EnumResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/compliance.get_enum.js - * region_tag:localhost_v1beta1_generated_Compliance_GetEnum_async - */ + /** + * This method requests an enum value from the server. Depending on the contents of EnumRequest, the enum value returned will be a known enum declared in the + * .proto file, or a made-up enum value the is unknown to the client. To verify that clients can round-trip unknown enum vaues they receive, use the + * response from this RPC as the request to VerifyEnum() + * + * The values of enums sent by the server when a known or unknown value is requested will be the same within a single Showcase server run (this is needed for + * VerifyEnum() to work) but are not guaranteed to be the same across separate Showcase server runs. + * + * @param {Object} request + * The request object that will be sent. + * @param {boolean} request.unknownEnum + * Whether the client is requesting a new, unknown enum value or a known enum value already declard in this proto file. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.EnumResponse|EnumResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/compliance.get_enum.js + * region_tag:localhost_v1beta1_generated_Compliance_GetEnum_async + */ getEnum( - request?: protos.google.showcase.v1beta1.IEnumRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IEnumResponse, - protos.google.showcase.v1beta1.IEnumRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IEnumRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IEnumResponse, + protos.google.showcase.v1beta1.IEnumRequest | undefined, + {} | undefined, + ] + >; getEnum( - request: protos.google.showcase.v1beta1.IEnumRequest, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.IEnumResponse, - protos.google.showcase.v1beta1.IEnumRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IEnumRequest, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.IEnumResponse, + protos.google.showcase.v1beta1.IEnumRequest | null | undefined, + {} | null | undefined + >, + ): void; getEnum( - request: protos.google.showcase.v1beta1.IEnumRequest, - callback: Callback< - protos.google.showcase.v1beta1.IEnumResponse, - protos.google.showcase.v1beta1.IEnumRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IEnumRequest, + callback: Callback< + protos.google.showcase.v1beta1.IEnumResponse, + protos.google.showcase.v1beta1.IEnumRequest | null | undefined, + {} | null | undefined + >, + ): void; getEnum( - request?: protos.google.showcase.v1beta1.IEnumRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.showcase.v1beta1.IEnumRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.IEnumResponse, - protos.google.showcase.v1beta1.IEnumRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.showcase.v1beta1.IEnumResponse, - protos.google.showcase.v1beta1.IEnumRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.IEnumResponse, - protos.google.showcase.v1beta1.IEnumRequest|undefined, {}|undefined - ]>|void { + protos.google.showcase.v1beta1.IEnumRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.IEnumResponse, + protos.google.showcase.v1beta1.IEnumRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IEnumResponse, + protos.google.showcase.v1beta1.IEnumRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('getEnum request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.IEnumResponse, - protos.google.showcase.v1beta1.IEnumRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.IEnumResponse, + protos.google.showcase.v1beta1.IEnumRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getEnum response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getEnum(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.IEnumResponse, - protos.google.showcase.v1beta1.IEnumRequest|undefined, - {}|undefined - ]) => { - this._log.info('getEnum response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getEnum(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.IEnumResponse, + protos.google.showcase.v1beta1.IEnumRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getEnum response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * This method is used to verify that clients can round-trip enum values, which is particularly important for unknown enum values over REST. VerifyEnum() - * verifies that its request, which is presumably the response that the client previously got to a GetEnum(), contains the correct data. If so, it responds - * with the same EnumResponse; otherwise, the RPC errors. - * - * This works because the values of enums sent by the server when a known or unknown value is requested will be the same within a single Showcase server run, - * although they are not guaranteed to be the same across separate Showcase server runs. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.showcase.v1beta1.EnumRequest} request.request - * The original request for a known or unknown enum from the server. - * @param {google.showcase.v1beta1.Continent} request.continent - * The actual enum the server provided. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.EnumResponse|EnumResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/compliance.verify_enum.js - * region_tag:localhost_v1beta1_generated_Compliance_VerifyEnum_async - */ + /** + * This method is used to verify that clients can round-trip enum values, which is particularly important for unknown enum values over REST. VerifyEnum() + * verifies that its request, which is presumably the response that the client previously got to a GetEnum(), contains the correct data. If so, it responds + * with the same EnumResponse; otherwise, the RPC errors. + * + * This works because the values of enums sent by the server when a known or unknown value is requested will be the same within a single Showcase server run, + * although they are not guaranteed to be the same across separate Showcase server runs. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.showcase.v1beta1.EnumRequest} request.request + * The original request for a known or unknown enum from the server. + * @param {google.showcase.v1beta1.Continent} request.continent + * The actual enum the server provided. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.EnumResponse|EnumResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/compliance.verify_enum.js + * region_tag:localhost_v1beta1_generated_Compliance_VerifyEnum_async + */ verifyEnum( - request?: protos.google.showcase.v1beta1.IEnumResponse, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IEnumResponse, - protos.google.showcase.v1beta1.IEnumResponse|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IEnumResponse, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IEnumResponse, + protos.google.showcase.v1beta1.IEnumResponse | undefined, + {} | undefined, + ] + >; verifyEnum( - request: protos.google.showcase.v1beta1.IEnumResponse, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.IEnumResponse, - protos.google.showcase.v1beta1.IEnumResponse|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IEnumResponse, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.IEnumResponse, + protos.google.showcase.v1beta1.IEnumResponse | null | undefined, + {} | null | undefined + >, + ): void; verifyEnum( - request: protos.google.showcase.v1beta1.IEnumResponse, - callback: Callback< - protos.google.showcase.v1beta1.IEnumResponse, - protos.google.showcase.v1beta1.IEnumResponse|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IEnumResponse, + callback: Callback< + protos.google.showcase.v1beta1.IEnumResponse, + protos.google.showcase.v1beta1.IEnumResponse | null | undefined, + {} | null | undefined + >, + ): void; verifyEnum( - request?: protos.google.showcase.v1beta1.IEnumResponse, - optionsOrCallback?: CallOptions|Callback< - protos.google.showcase.v1beta1.IEnumResponse, - protos.google.showcase.v1beta1.IEnumResponse|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.showcase.v1beta1.IEnumResponse, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.IEnumResponse, - protos.google.showcase.v1beta1.IEnumResponse|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.IEnumResponse, - protos.google.showcase.v1beta1.IEnumResponse|undefined, {}|undefined - ]>|void { + protos.google.showcase.v1beta1.IEnumResponse | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.IEnumResponse, + protos.google.showcase.v1beta1.IEnumResponse | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IEnumResponse, + protos.google.showcase.v1beta1.IEnumResponse | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('verifyEnum request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.IEnumResponse, - protos.google.showcase.v1beta1.IEnumResponse|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.IEnumResponse, + protos.google.showcase.v1beta1.IEnumResponse | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('verifyEnum response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.verifyEnum(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.IEnumResponse, - protos.google.showcase.v1beta1.IEnumResponse|undefined, - {}|undefined - ]) => { - this._log.info('verifyEnum response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .verifyEnum(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.IEnumResponse, + protos.google.showcase.v1beta1.IEnumResponse | undefined, + {} | undefined, + ]) => { + this._log.info('verifyEnum response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); @@ -1404,7 +1768,7 @@ export class ComplianceClient { * @param {string} blueprint * @returns {string} Resource name string. */ - blueprintPath(session:string,test:string,blueprint:string) { + blueprintPath(session: string, test: string, blueprint: string) { return this.pathTemplates.blueprintPathTemplate.render({ session: session, test: test, @@ -1420,7 +1784,8 @@ export class ComplianceClient { * @returns {string} A string representing the session. */ matchSessionFromBlueprintName(blueprintName: string) { - return this.pathTemplates.blueprintPathTemplate.match(blueprintName).session; + return this.pathTemplates.blueprintPathTemplate.match(blueprintName) + .session; } /** @@ -1442,7 +1807,8 @@ export class ComplianceClient { * @returns {string} A string representing the blueprint. */ matchBlueprintFromBlueprintName(blueprintName: string) { - return this.pathTemplates.blueprintPathTemplate.match(blueprintName).blueprint; + return this.pathTemplates.blueprintPathTemplate.match(blueprintName) + .blueprint; } /** @@ -1451,7 +1817,7 @@ export class ComplianceClient { * @param {string} room * @returns {string} Resource name string. */ - roomPath(room:string) { + roomPath(room: string) { return this.pathTemplates.roomPathTemplate.render({ room: room, }); @@ -1475,7 +1841,7 @@ export class ComplianceClient { * @param {string} blurb * @returns {string} Resource name string. */ - roomBlurbPath(room:string,blurb:string) { + roomBlurbPath(room: string, blurb: string) { return this.pathTemplates.roomBlurbPathTemplate.render({ room: room, blurb: blurb, @@ -1512,7 +1878,11 @@ export class ComplianceClient { * @param {string} blurb * @returns {string} Resource name string. */ - roomBlurbsLegacyRoomBlurbPath(room:string,legacyRoom:string,blurb:string) { + roomBlurbsLegacyRoomBlurbPath( + room: string, + legacyRoom: string, + blurb: string, + ) { return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.render({ room: room, legacy_room: legacyRoom, @@ -1527,8 +1897,12 @@ export class ComplianceClient { * A fully-qualified path representing room_blurbs_legacy_room_blurb resource. * @returns {string} A string representing the room. */ - matchRoomFromRoomBlurbsLegacyRoomBlurbName(roomBlurbsLegacyRoomBlurbName: string) { - return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match(roomBlurbsLegacyRoomBlurbName).room; + matchRoomFromRoomBlurbsLegacyRoomBlurbName( + roomBlurbsLegacyRoomBlurbName: string, + ) { + return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match( + roomBlurbsLegacyRoomBlurbName, + ).room; } /** @@ -1538,8 +1912,12 @@ export class ComplianceClient { * A fully-qualified path representing room_blurbs_legacy_room_blurb resource. * @returns {string} A string representing the legacy_room. */ - matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName(roomBlurbsLegacyRoomBlurbName: string) { - return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match(roomBlurbsLegacyRoomBlurbName).legacy_room; + matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName( + roomBlurbsLegacyRoomBlurbName: string, + ) { + return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match( + roomBlurbsLegacyRoomBlurbName, + ).legacy_room; } /** @@ -1549,8 +1927,12 @@ export class ComplianceClient { * A fully-qualified path representing room_blurbs_legacy_room_blurb resource. * @returns {string} A string representing the blurb. */ - matchBlurbFromRoomBlurbsLegacyRoomBlurbName(roomBlurbsLegacyRoomBlurbName: string) { - return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match(roomBlurbsLegacyRoomBlurbName).blurb; + matchBlurbFromRoomBlurbsLegacyRoomBlurbName( + roomBlurbsLegacyRoomBlurbName: string, + ) { + return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match( + roomBlurbsLegacyRoomBlurbName, + ).blurb; } /** @@ -1559,7 +1941,7 @@ export class ComplianceClient { * @param {string} sequence * @returns {string} Resource name string. */ - sequencePath(sequence:string) { + sequencePath(sequence: string) { return this.pathTemplates.sequencePathTemplate.render({ sequence: sequence, }); @@ -1582,7 +1964,7 @@ export class ComplianceClient { * @param {string} sequence * @returns {string} Resource name string. */ - sequenceReportPath(sequence:string) { + sequenceReportPath(sequence: string) { return this.pathTemplates.sequenceReportPathTemplate.render({ sequence: sequence, }); @@ -1596,7 +1978,9 @@ export class ComplianceClient { * @returns {string} A string representing the sequence. */ matchSequenceFromSequenceReportName(sequenceReportName: string) { - return this.pathTemplates.sequenceReportPathTemplate.match(sequenceReportName).sequence; + return this.pathTemplates.sequenceReportPathTemplate.match( + sequenceReportName, + ).sequence; } /** @@ -1605,7 +1989,7 @@ export class ComplianceClient { * @param {string} session * @returns {string} Resource name string. */ - sessionPath(session:string) { + sessionPath(session: string) { return this.pathTemplates.sessionPathTemplate.render({ session: session, }); @@ -1629,7 +2013,7 @@ export class ComplianceClient { * @param {string} test * @returns {string} Resource name string. */ - testPath(session:string,test:string) { + testPath(session: string, test: string) { return this.pathTemplates.testPathTemplate.render({ session: session, test: test, @@ -1664,7 +2048,7 @@ export class ComplianceClient { * @param {string} user * @returns {string} Resource name string. */ - userPath(user:string) { + userPath(user: string) { return this.pathTemplates.userPathTemplate.render({ user: user, }); @@ -1688,7 +2072,7 @@ export class ComplianceClient { * @param {string} blurb * @returns {string} Resource name string. */ - userProfileBlurbPath(user:string,blurb:string) { + userProfileBlurbPath(user: string, blurb: string) { return this.pathTemplates.userProfileBlurbPathTemplate.render({ user: user, blurb: blurb, @@ -1703,7 +2087,9 @@ export class ComplianceClient { * @returns {string} A string representing the user. */ matchUserFromUserProfileBlurbName(userProfileBlurbName: string) { - return this.pathTemplates.userProfileBlurbPathTemplate.match(userProfileBlurbName).user; + return this.pathTemplates.userProfileBlurbPathTemplate.match( + userProfileBlurbName, + ).user; } /** @@ -1714,7 +2100,9 @@ export class ComplianceClient { * @returns {string} A string representing the blurb. */ matchBlurbFromUserProfileBlurbName(userProfileBlurbName: string) { - return this.pathTemplates.userProfileBlurbPathTemplate.match(userProfileBlurbName).blurb; + return this.pathTemplates.userProfileBlurbPathTemplate.match( + userProfileBlurbName, + ).blurb; } /** @@ -1725,12 +2113,18 @@ export class ComplianceClient { * @param {string} blurb * @returns {string} Resource name string. */ - userProfileBlurbsLegacyUserBlurbPath(user:string,legacyUser:string,blurb:string) { - return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.render({ - user: user, - legacy_user: legacyUser, - blurb: blurb, - }); + userProfileBlurbsLegacyUserBlurbPath( + user: string, + legacyUser: string, + blurb: string, + ) { + return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.render( + { + user: user, + legacy_user: legacyUser, + blurb: blurb, + }, + ); } /** @@ -1740,8 +2134,12 @@ export class ComplianceClient { * A fully-qualified path representing user_profile_blurbs_legacy_user_blurb resource. * @returns {string} A string representing the user. */ - matchUserFromUserProfileBlurbsLegacyUserBlurbName(userProfileBlurbsLegacyUserBlurbName: string) { - return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match(userProfileBlurbsLegacyUserBlurbName).user; + matchUserFromUserProfileBlurbsLegacyUserBlurbName( + userProfileBlurbsLegacyUserBlurbName: string, + ) { + return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match( + userProfileBlurbsLegacyUserBlurbName, + ).user; } /** @@ -1751,8 +2149,12 @@ export class ComplianceClient { * A fully-qualified path representing user_profile_blurbs_legacy_user_blurb resource. * @returns {string} A string representing the legacy_user. */ - matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName(userProfileBlurbsLegacyUserBlurbName: string) { - return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match(userProfileBlurbsLegacyUserBlurbName).legacy_user; + matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName( + userProfileBlurbsLegacyUserBlurbName: string, + ) { + return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match( + userProfileBlurbsLegacyUserBlurbName, + ).legacy_user; } /** @@ -1762,8 +2164,12 @@ export class ComplianceClient { * A fully-qualified path representing user_profile_blurbs_legacy_user_blurb resource. * @returns {string} A string representing the blurb. */ - matchBlurbFromUserProfileBlurbsLegacyUserBlurbName(userProfileBlurbsLegacyUserBlurbName: string) { - return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match(userProfileBlurbsLegacyUserBlurbName).blurb; + matchBlurbFromUserProfileBlurbsLegacyUserBlurbName( + userProfileBlurbsLegacyUserBlurbName: string, + ) { + return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match( + userProfileBlurbsLegacyUserBlurbName, + ).blurb; } /** @@ -1774,7 +2180,7 @@ export class ComplianceClient { */ close(): Promise { if (this.complianceStub && !this._terminated) { - return this.complianceStub.then(stub => { + return this.complianceStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -1782,4 +2188,4 @@ export class ComplianceClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/core/generator/gapic-generator-typescript/baselines/showcase/src/v1beta1/echo_client.ts.baseline b/core/generator/gapic-generator-typescript/baselines/showcase/src/v1beta1/echo_client.ts.baseline index 85ac6a74ccdd..f693323fb6c9 100644 --- a/core/generator/gapic-generator-typescript/baselines/showcase/src/v1beta1/echo_client.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/showcase/src/v1beta1/echo_client.ts.baseline @@ -18,11 +18,20 @@ /* global window */ import * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions, GrpcClientOptions, LROperation, PaginationCallback, GaxCall} from 'google-gax'; -import {Transform, PassThrough} from 'stream'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + GrpcClientOptions, + LROperation, + PaginationCallback, + GaxCall, +} from 'google-gax'; +import { Transform, PassThrough } from 'stream'; import * as protos from '../../protos/protos'; import jsonProtos = require('../../protos/protos.json'); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; /** * Client JSON configuration object, loaded from @@ -52,7 +61,7 @@ export class EchoClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('showcase'); @@ -65,10 +74,10 @@ export class EchoClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; operationsClient: gax.OperationsClient; - echoStub?: Promise<{[name: string]: Function}>; + echoStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of EchoClient. @@ -109,21 +118,42 @@ export class EchoClient { * const client = new EchoClient({fallback: true}, gax); * ``` */ - constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { // Ensure that options include all the required fields. const staticMembers = this.constructor as typeof EchoClient; - if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { - throw new Error('Please set either universe_domain or universeDomain, but not both.'); + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); } - const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; - this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; this._servicePath = 'localhost'; - const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; - const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // Request numeric enum values if REST transport is used. opts.numericEnums = true; @@ -148,7 +178,7 @@ export class EchoClient { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; @@ -162,10 +192,7 @@ export class EchoClient { } // Determine the client header string. - const clientHeader = [ - `gax/${this._gaxModule.version}`, - `gapic/${version}`, - ]; + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/${process.versions.node}`); } else { @@ -187,54 +214,65 @@ export class EchoClient { // Create useful helper objects for these. this.pathTemplates = { blueprintPathTemplate: new this._gaxModule.PathTemplate( - 'sessions/{session}/tests/{test}/blueprints/{blueprint}' - ), - roomPathTemplate: new this._gaxModule.PathTemplate( - 'rooms/{room}' + 'sessions/{session}/tests/{test}/blueprints/{blueprint}', ), + roomPathTemplate: new this._gaxModule.PathTemplate('rooms/{room}'), roomBlurbPathTemplate: new this._gaxModule.PathTemplate( - 'rooms/{room}/blurbs/{blurb}' + 'rooms/{room}/blurbs/{blurb}', ), roomBlurbsLegacyRoomBlurbPathTemplate: new this._gaxModule.PathTemplate( - 'rooms/{room}/blurbs/legacy/{legacy_room}.{blurb}' + 'rooms/{room}/blurbs/legacy/{legacy_room}.{blurb}', ), sequencePathTemplate: new this._gaxModule.PathTemplate( - 'sequences/{sequence}' + 'sequences/{sequence}', ), sequenceReportPathTemplate: new this._gaxModule.PathTemplate( - 'sequences/{sequence}/sequenceReport' + 'sequences/{sequence}/sequenceReport', ), sessionPathTemplate: new this._gaxModule.PathTemplate( - 'sessions/{session}' + 'sessions/{session}', ), testPathTemplate: new this._gaxModule.PathTemplate( - 'sessions/{session}/tests/{test}' - ), - userPathTemplate: new this._gaxModule.PathTemplate( - 'users/{user}' + 'sessions/{session}/tests/{test}', ), + userPathTemplate: new this._gaxModule.PathTemplate('users/{user}'), userProfileBlurbPathTemplate: new this._gaxModule.PathTemplate( - 'users/{user}/profile/blurbs/{blurb}' - ), - userProfileBlurbsLegacyUserBlurbPathTemplate: new this._gaxModule.PathTemplate( - 'users/{user}/profile/blurbs/legacy/{legacy_user}~{blurb}' + 'users/{user}/profile/blurbs/{blurb}', ), + userProfileBlurbsLegacyUserBlurbPathTemplate: + new this._gaxModule.PathTemplate( + 'users/{user}/profile/blurbs/legacy/{legacy_user}~{blurb}', + ), }; // Some of the methods on this service return "paged" results, // (e.g. 50 results at a time, with tokens to get subsequent // pages). Denote the keys used for pagination and results. this.descriptors.page = { - pagedExpand: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'responses') + pagedExpand: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'responses', + ), }; // Some of the methods on this service provide streaming responses. // Provide descriptors for these. this.descriptors.stream = { - expand: new this._gaxModule.StreamDescriptor(this._gaxModule.StreamType.SERVER_STREAMING, !!opts.fallback, !!opts.gaxServerStreamingRetries), - collect: new this._gaxModule.StreamDescriptor(this._gaxModule.StreamType.CLIENT_STREAMING, !!opts.fallback), - chat: new this._gaxModule.StreamDescriptor(this._gaxModule.StreamType.BIDI_STREAMING, !!opts.fallback, !!opts.gaxServerStreamingRetries) + expand: new this._gaxModule.StreamDescriptor( + this._gaxModule.StreamType.SERVER_STREAMING, + !!opts.fallback, + !!opts.gaxServerStreamingRetries, + ), + collect: new this._gaxModule.StreamDescriptor( + this._gaxModule.StreamType.CLIENT_STREAMING, + !!opts.fallback, + ), + chat: new this._gaxModule.StreamDescriptor( + this._gaxModule.StreamType.BIDI_STREAMING, + !!opts.fallback, + !!opts.gaxServerStreamingRetries, + ), }; const protoFilesRoot = this._gaxModule.protobufFromJSON(jsonProtos); @@ -243,32 +281,106 @@ export class EchoClient { // rather than holding a request open. const lroOptions: GrpcClientOptions = { auth: this.auth, - grpc: 'grpc' in this._gaxGrpc ? this._gaxGrpc.grpc : undefined + grpc: 'grpc' in this._gaxGrpc ? this._gaxGrpc.grpc : undefined, }; if (opts.fallback) { lroOptions.protoJson = protoFilesRoot; - lroOptions.httpRules = [{selector: 'google.cloud.location.Locations.ListLocations',get: '/v1beta1/{name=projects/*}/locations',},{selector: 'google.cloud.location.Locations.GetLocation',get: '/v1beta1/{name=projects/*/locations/*}',},{selector: 'google.iam.v1.IAMPolicy.SetIamPolicy',post: '/v1beta1/{resource=users/*}:setIamPolicy',body: '*',additional_bindings: [{post: '/v1beta1/{resource=rooms/*}:setIamPolicy',body: '*',},{post: '/v1beta1/{resource=rooms/*/blurbs/*}:setIamPolicy',body: '*',},{post: '/v1beta1/{resource=sequences/*}:setIamPolicy',body: '*',}], - },{selector: 'google.iam.v1.IAMPolicy.GetIamPolicy',get: '/v1beta1/{resource=users/*}:getIamPolicy',additional_bindings: [{get: '/v1beta1/{resource=rooms/*}:getIamPolicy',},{get: '/v1beta1/{resource=rooms/*/blurbs/*}:getIamPolicy',},{get: '/v1beta1/{resource=sequences/*}:getIamPolicy',}], - },{selector: 'google.iam.v1.IAMPolicy.TestIamPermissions',post: '/v1beta1/{resource=users/*}:testIamPermissions',body: '*',additional_bindings: [{post: '/v1beta1/{resource=rooms/*}:testIamPermissions',body: '*',},{post: '/v1beta1/{resource=rooms/*/blurbs/*}:testIamPermissions',body: '*',},{post: '/v1beta1/{resource=sequences/*}:testIamPermissions',body: '*',}], - },{selector: 'google.longrunning.Operations.ListOperations',get: '/v1beta1/operations',},{selector: 'google.longrunning.Operations.GetOperation',get: '/v1beta1/{name=operations/**}',},{selector: 'google.longrunning.Operations.DeleteOperation',delete: '/v1beta1/{name=operations/**}',},{selector: 'google.longrunning.Operations.CancelOperation',post: '/v1beta1/{name=operations/**}:cancel',}]; + lroOptions.httpRules = [ + { + selector: 'google.cloud.location.Locations.ListLocations', + get: '/v1beta1/{name=projects/*}/locations', + }, + { + selector: 'google.cloud.location.Locations.GetLocation', + get: '/v1beta1/{name=projects/*/locations/*}', + }, + { + selector: 'google.iam.v1.IAMPolicy.SetIamPolicy', + post: '/v1beta1/{resource=users/*}:setIamPolicy', + body: '*', + additional_bindings: [ + { post: '/v1beta1/{resource=rooms/*}:setIamPolicy', body: '*' }, + { + post: '/v1beta1/{resource=rooms/*/blurbs/*}:setIamPolicy', + body: '*', + }, + { post: '/v1beta1/{resource=sequences/*}:setIamPolicy', body: '*' }, + ], + }, + { + selector: 'google.iam.v1.IAMPolicy.GetIamPolicy', + get: '/v1beta1/{resource=users/*}:getIamPolicy', + additional_bindings: [ + { get: '/v1beta1/{resource=rooms/*}:getIamPolicy' }, + { get: '/v1beta1/{resource=rooms/*/blurbs/*}:getIamPolicy' }, + { get: '/v1beta1/{resource=sequences/*}:getIamPolicy' }, + ], + }, + { + selector: 'google.iam.v1.IAMPolicy.TestIamPermissions', + post: '/v1beta1/{resource=users/*}:testIamPermissions', + body: '*', + additional_bindings: [ + { + post: '/v1beta1/{resource=rooms/*}:testIamPermissions', + body: '*', + }, + { + post: '/v1beta1/{resource=rooms/*/blurbs/*}:testIamPermissions', + body: '*', + }, + { + post: '/v1beta1/{resource=sequences/*}:testIamPermissions', + body: '*', + }, + ], + }, + { + selector: 'google.longrunning.Operations.ListOperations', + get: '/v1beta1/operations', + }, + { + selector: 'google.longrunning.Operations.GetOperation', + get: '/v1beta1/{name=operations/**}', + }, + { + selector: 'google.longrunning.Operations.DeleteOperation', + delete: '/v1beta1/{name=operations/**}', + }, + { + selector: 'google.longrunning.Operations.CancelOperation', + post: '/v1beta1/{name=operations/**}:cancel', + }, + ]; } - this.operationsClient = this._gaxModule.lro(lroOptions).operationsClient(opts); + this.operationsClient = this._gaxModule + .lro(lroOptions) + .operationsClient(opts); const waitResponse = protoFilesRoot.lookup( - '.google.showcase.v1beta1.WaitResponse') as gax.protobuf.Type; + '.google.showcase.v1beta1.WaitResponse', + ) as gax.protobuf.Type; const waitMetadata = protoFilesRoot.lookup( - '.google.showcase.v1beta1.WaitMetadata') as gax.protobuf.Type; + '.google.showcase.v1beta1.WaitMetadata', + ) as gax.protobuf.Type; this.descriptors.longrunning = { wait: new this._gaxModule.LongrunningDescriptor( this.operationsClient, waitResponse.decode.bind(waitResponse), - waitMetadata.decode.bind(waitMetadata)) + waitMetadata.decode.bind(waitMetadata), + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.showcase.v1beta1.Echo', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' '), 'x-goog-api-version': 'v1_20240408'}); + 'google.showcase.v1beta1.Echo', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + { + 'x-goog-api-client': clientHeader.join(' '), + 'x-goog-api-version': 'v1_20240408', + }, + ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -299,35 +411,55 @@ export class EchoClient { // Put together the "service stub" for // google.showcase.v1beta1.Echo. this.echoStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.showcase.v1beta1.Echo') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.showcase.v1beta1.Echo', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.showcase.v1beta1.Echo, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts, + this._providedCustomServicePath, + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const echoStubMethods = - ['echo', 'echoErrorDetails', 'expand', 'collect', 'chat', 'pagedExpand', 'pagedExpandLegacy', 'wait', 'block']; + const echoStubMethods = [ + 'echo', + 'echoErrorDetails', + 'expand', + 'collect', + 'chat', + 'pagedExpand', + 'pagedExpandLegacy', + 'wait', + 'block', + ]; for (const methodName of echoStubMethods) { const callPromise = this.echoStub.then( - stub => (...args: Array<{}>) => { - if (this._terminated) { - if (methodName in this.descriptors.stream) { - const stream = new PassThrough({objectMode: true}); - setImmediate(() => { - stream.emit('error', new this._gaxModule.GoogleError('The client has already been closed.')); - }); - return stream; + (stub) => + (...args: Array<{}>) => { + if (this._terminated) { + if (methodName in this.descriptors.stream) { + const stream = new PassThrough({ objectMode: true }); + setImmediate(() => { + stream.emit( + 'error', + new this._gaxModule.GoogleError( + 'The client has already been closed.', + ), + ); + }); + return stream; + } + return Promise.reject('The client has already been closed.'); } - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error|null|undefined) => () => { + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { throw err; - }); + }, + ); const descriptor = this.descriptors.page[methodName] || @@ -338,7 +470,7 @@ export class EchoClient { callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -353,8 +485,14 @@ export class EchoClient { * @returns {string} The DNS address for this service. */ static get servicePath() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'localhost'; } @@ -365,8 +503,14 @@ export class EchoClient { * @returns {string} The DNS address for this service. */ static get apiEndpoint() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'localhost'; } @@ -406,8 +550,9 @@ export class EchoClient { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId(callback?: Callback): - Promise|void { + getProjectId( + callback?: Callback, + ): Promise | void { if (callback) { this.auth.getProjectId(callback); return; @@ -418,67 +563,81 @@ export class EchoClient { // ------------------- // -- Service calls -- // ------------------- -/** - * @param {Object} request - * The request object that will be sent. - * @param {string} request.content - * The content to be echoed by the server. - * @param {google.rpc.Status} request.error - * The error to be thrown by the server. - * @param {google.showcase.v1beta1.Severity} request.severity - * The severity to be echoed by the server. - * @param {string} request.header - * Optional. This field can be set to test the routing annotation on the Echo method. - * @param {string} request.otherHeader - * Optional. This field can be set to test the routing annotation on the Echo method. - * @param {string} request.requestId - * To facilitate testing of https://google.aip.dev/client-libraries/4235 - * @param {string} request.otherRequestId - * To facilitate testing of https://google.aip.dev/client-libraries/4235 - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.EchoResponse|EchoResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/echo.echo.js - * region_tag:localhost_v1beta1_generated_Echo_Echo_async - */ + /** + * @param {Object} request + * The request object that will be sent. + * @param {string} request.content + * The content to be echoed by the server. + * @param {google.rpc.Status} request.error + * The error to be thrown by the server. + * @param {google.showcase.v1beta1.Severity} request.severity + * The severity to be echoed by the server. + * @param {string} request.header + * Optional. This field can be set to test the routing annotation on the Echo method. + * @param {string} request.otherHeader + * Optional. This field can be set to test the routing annotation on the Echo method. + * @param {string} request.requestId + * To facilitate testing of https://google.aip.dev/client-libraries/4235 + * @param {string} request.otherRequestId + * To facilitate testing of https://google.aip.dev/client-libraries/4235 + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.EchoResponse|EchoResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/echo.echo.js + * region_tag:localhost_v1beta1_generated_Echo_Echo_async + */ echo( - request?: protos.google.showcase.v1beta1.IEchoRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IEchoResponse, - protos.google.showcase.v1beta1.IEchoRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IEchoRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IEchoResponse, + protos.google.showcase.v1beta1.IEchoRequest | undefined, + {} | undefined, + ] + >; echo( - request: protos.google.showcase.v1beta1.IEchoRequest, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.IEchoResponse, - protos.google.showcase.v1beta1.IEchoRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IEchoRequest, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.IEchoResponse, + protos.google.showcase.v1beta1.IEchoRequest | null | undefined, + {} | null | undefined + >, + ): void; echo( - request: protos.google.showcase.v1beta1.IEchoRequest, - callback: Callback< - protos.google.showcase.v1beta1.IEchoResponse, - protos.google.showcase.v1beta1.IEchoRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IEchoRequest, + callback: Callback< + protos.google.showcase.v1beta1.IEchoResponse, + protos.google.showcase.v1beta1.IEchoRequest | null | undefined, + {} | null | undefined + >, + ): void; echo( - request?: protos.google.showcase.v1beta1.IEchoRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.showcase.v1beta1.IEchoRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.IEchoResponse, - protos.google.showcase.v1beta1.IEchoRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.showcase.v1beta1.IEchoResponse, - protos.google.showcase.v1beta1.IEchoRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.IEchoResponse, - protos.google.showcase.v1beta1.IEchoRequest|undefined, {}|undefined - ]>|void { - request = request || {}; + protos.google.showcase.v1beta1.IEchoRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.IEchoResponse, + protos.google.showcase.v1beta1.IEchoRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IEchoResponse, + protos.google.showcase.v1beta1.IEchoRequest | undefined, + {} | undefined, + ] + > | void { + request = request || {}; if (!request.requestId) { request.requestId = gax.makeUUID(); } @@ -486,8 +645,7 @@ export class EchoClient { if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; @@ -507,7 +665,9 @@ export class EchoClient { { const fieldValue = request.header; if (fieldValue !== undefined && fieldValue !== null) { - const match = fieldValue.toString().match(RegExp('(?(?:.*)?)')); + const match = fieldValue + .toString() + .match(RegExp('(?(?:.*)?)')); if (match) { const parameterValue = match.groups?.['routing_id'] ?? fieldValue; Object.assign(routingParameter, { routing_id: parameterValue }); @@ -517,7 +677,9 @@ export class EchoClient { { const fieldValue = request.header; if (fieldValue !== undefined && fieldValue !== null) { - const match = fieldValue.toString().match(RegExp('(?regions/[^/]+/zones/[^/]+(?:/.*)?)')); + const match = fieldValue + .toString() + .match(RegExp('(?regions/[^/]+/zones/[^/]+(?:/.*)?)')); if (match) { const parameterValue = match.groups?.['table_name'] ?? fieldValue; Object.assign(routingParameter, { table_name: parameterValue }); @@ -527,7 +689,9 @@ export class EchoClient { { const fieldValue = request.header; if (fieldValue !== undefined && fieldValue !== null) { - const match = fieldValue.toString().match(RegExp('(?projects/[^/]+)(?:/.*)?')); + const match = fieldValue + .toString() + .match(RegExp('(?projects/[^/]+)(?:/.*)?')); if (match) { const parameterValue = match.groups?.['super_id'] ?? fieldValue; Object.assign(routingParameter, { super_id: parameterValue }); @@ -537,7 +701,11 @@ export class EchoClient { { const fieldValue = request.header; if (fieldValue !== undefined && fieldValue !== null) { - const match = fieldValue.toString().match(RegExp('(?projects/[^/]+/instances/[^/]+(?:/.*)?)')); + const match = fieldValue + .toString() + .match( + RegExp('(?projects/[^/]+/instances/[^/]+(?:/.*)?)'), + ); if (match) { const parameterValue = match.groups?.['table_name'] ?? fieldValue; Object.assign(routingParameter, { table_name: parameterValue }); @@ -547,7 +715,11 @@ export class EchoClient { { const fieldValue = request.header; if (fieldValue !== undefined && fieldValue !== null) { - const match = fieldValue.toString().match(RegExp('projects/[^/]+/(?instances/[^/]+)(?:/.*)?')); + const match = fieldValue + .toString() + .match( + RegExp('projects/[^/]+/(?instances/[^/]+)(?:/.*)?'), + ); if (match) { const parameterValue = match.groups?.['instance_id'] ?? fieldValue; Object.assign(routingParameter, { instance_id: parameterValue }); @@ -567,629 +739,852 @@ export class EchoClient { { const fieldValue = request.otherHeader; if (fieldValue !== undefined && fieldValue !== null) { - const match = fieldValue.toString().match(RegExp('(?projects/[^/]+)(?:/.*)?')); + const match = fieldValue + .toString() + .match(RegExp('(?projects/[^/]+)(?:/.*)?')); if (match) { const parameterValue = match.groups?.['qux'] ?? fieldValue; Object.assign(routingParameter, { qux: parameterValue }); } } } - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams( - routingParameter - ); - this.initialize().catch(err => {throw err}); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams(routingParameter); + this.initialize().catch((err) => { + throw err; + }); this._log.info('echo request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.IEchoResponse, - protos.google.showcase.v1beta1.IEchoRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.IEchoResponse, + protos.google.showcase.v1beta1.IEchoRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('echo response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.echo(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.IEchoResponse, - protos.google.showcase.v1beta1.IEchoRequest|undefined, - {}|undefined - ]) => { - this._log.info('echo response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .echo(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.IEchoResponse, + protos.google.showcase.v1beta1.IEchoRequest | undefined, + {} | undefined, + ]) => { + this._log.info('echo response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * This method returns error details in a repeated "google.protobuf.Any" - * field. This method showcases handling errors thus encoded, particularly - * over REST transport. Note that GAPICs only allow the type - * "google.protobuf.Any" for field paths ending in "error.details", and, at - * run-time, the actual types for these fields must be one of the types in - * google/rpc/error_details.proto. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.singleDetailText - * Content to return in a singular `*.error.details` field of type - * `google.protobuf.Any` - * @param {string[]} request.multiDetailText - * Content to return in a repeated `*.error.details` field of type - * `google.protobuf.Any` - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.EchoErrorDetailsResponse|EchoErrorDetailsResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/echo.echo_error_details.js - * region_tag:localhost_v1beta1_generated_Echo_EchoErrorDetails_async - */ + /** + * This method returns error details in a repeated "google.protobuf.Any" + * field. This method showcases handling errors thus encoded, particularly + * over REST transport. Note that GAPICs only allow the type + * "google.protobuf.Any" for field paths ending in "error.details", and, at + * run-time, the actual types for these fields must be one of the types in + * google/rpc/error_details.proto. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.singleDetailText + * Content to return in a singular `*.error.details` field of type + * `google.protobuf.Any` + * @param {string[]} request.multiDetailText + * Content to return in a repeated `*.error.details` field of type + * `google.protobuf.Any` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.EchoErrorDetailsResponse|EchoErrorDetailsResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/echo.echo_error_details.js + * region_tag:localhost_v1beta1_generated_Echo_EchoErrorDetails_async + */ echoErrorDetails( - request?: protos.google.showcase.v1beta1.IEchoErrorDetailsRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IEchoErrorDetailsResponse, - protos.google.showcase.v1beta1.IEchoErrorDetailsRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IEchoErrorDetailsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IEchoErrorDetailsResponse, + protos.google.showcase.v1beta1.IEchoErrorDetailsRequest | undefined, + {} | undefined, + ] + >; echoErrorDetails( - request: protos.google.showcase.v1beta1.IEchoErrorDetailsRequest, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.IEchoErrorDetailsResponse, - protos.google.showcase.v1beta1.IEchoErrorDetailsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IEchoErrorDetailsRequest, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.IEchoErrorDetailsResponse, + | protos.google.showcase.v1beta1.IEchoErrorDetailsRequest + | null + | undefined, + {} | null | undefined + >, + ): void; echoErrorDetails( - request: protos.google.showcase.v1beta1.IEchoErrorDetailsRequest, - callback: Callback< - protos.google.showcase.v1beta1.IEchoErrorDetailsResponse, - protos.google.showcase.v1beta1.IEchoErrorDetailsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IEchoErrorDetailsRequest, + callback: Callback< + protos.google.showcase.v1beta1.IEchoErrorDetailsResponse, + | protos.google.showcase.v1beta1.IEchoErrorDetailsRequest + | null + | undefined, + {} | null | undefined + >, + ): void; echoErrorDetails( - request?: protos.google.showcase.v1beta1.IEchoErrorDetailsRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.showcase.v1beta1.IEchoErrorDetailsResponse, - protos.google.showcase.v1beta1.IEchoErrorDetailsRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.showcase.v1beta1.IEchoErrorDetailsRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.IEchoErrorDetailsResponse, - protos.google.showcase.v1beta1.IEchoErrorDetailsRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.IEchoErrorDetailsResponse, - protos.google.showcase.v1beta1.IEchoErrorDetailsRequest|undefined, {}|undefined - ]>|void { + | protos.google.showcase.v1beta1.IEchoErrorDetailsRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.IEchoErrorDetailsResponse, + | protos.google.showcase.v1beta1.IEchoErrorDetailsRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IEchoErrorDetailsResponse, + protos.google.showcase.v1beta1.IEchoErrorDetailsRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('echoErrorDetails request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.IEchoErrorDetailsResponse, - protos.google.showcase.v1beta1.IEchoErrorDetailsRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.IEchoErrorDetailsResponse, + | protos.google.showcase.v1beta1.IEchoErrorDetailsRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('echoErrorDetails response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.echoErrorDetails(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.IEchoErrorDetailsResponse, - protos.google.showcase.v1beta1.IEchoErrorDetailsRequest|undefined, - {}|undefined - ]) => { - this._log.info('echoErrorDetails response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .echoErrorDetails(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.IEchoErrorDetailsResponse, + protos.google.showcase.v1beta1.IEchoErrorDetailsRequest | undefined, + {} | undefined, + ]) => { + this._log.info('echoErrorDetails response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * This is similar to the PagedExpand except that it uses - * max_results instead of page_size, as some legacy APIs still - * do. New APIs should NOT use this pattern. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.content - * The string to expand. - * @param {number} request.maxResults - * The number of words to returned in each page. - * (-- aip.dev/not-precedent: This is a legacy, non-standard pattern that - * violates aip.dev/158. Ordinarily, this should be page_size. --) - * @param {string} request.pageToken - * The position of the page to be returned. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.PagedExpandResponse|PagedExpandResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/echo.paged_expand_legacy.js - * region_tag:localhost_v1beta1_generated_Echo_PagedExpandLegacy_async - */ + /** + * This is similar to the PagedExpand except that it uses + * max_results instead of page_size, as some legacy APIs still + * do. New APIs should NOT use this pattern. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.content + * The string to expand. + * @param {number} request.maxResults + * The number of words to returned in each page. + * (-- aip.dev/not-precedent: This is a legacy, non-standard pattern that + * violates aip.dev/158. Ordinarily, this should be page_size. --) + * @param {string} request.pageToken + * The position of the page to be returned. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.PagedExpandResponse|PagedExpandResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/echo.paged_expand_legacy.js + * region_tag:localhost_v1beta1_generated_Echo_PagedExpandLegacy_async + */ pagedExpandLegacy( - request?: protos.google.showcase.v1beta1.IPagedExpandLegacyRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IPagedExpandResponse, - protos.google.showcase.v1beta1.IPagedExpandLegacyRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IPagedExpandLegacyRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IPagedExpandResponse, + protos.google.showcase.v1beta1.IPagedExpandLegacyRequest | undefined, + {} | undefined, + ] + >; pagedExpandLegacy( - request: protos.google.showcase.v1beta1.IPagedExpandLegacyRequest, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.IPagedExpandResponse, - protos.google.showcase.v1beta1.IPagedExpandLegacyRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IPagedExpandLegacyRequest, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.IPagedExpandResponse, + | protos.google.showcase.v1beta1.IPagedExpandLegacyRequest + | null + | undefined, + {} | null | undefined + >, + ): void; pagedExpandLegacy( - request: protos.google.showcase.v1beta1.IPagedExpandLegacyRequest, - callback: Callback< - protos.google.showcase.v1beta1.IPagedExpandResponse, - protos.google.showcase.v1beta1.IPagedExpandLegacyRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IPagedExpandLegacyRequest, + callback: Callback< + protos.google.showcase.v1beta1.IPagedExpandResponse, + | protos.google.showcase.v1beta1.IPagedExpandLegacyRequest + | null + | undefined, + {} | null | undefined + >, + ): void; pagedExpandLegacy( - request?: protos.google.showcase.v1beta1.IPagedExpandLegacyRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.showcase.v1beta1.IPagedExpandLegacyRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.IPagedExpandResponse, - protos.google.showcase.v1beta1.IPagedExpandLegacyRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.showcase.v1beta1.IPagedExpandResponse, - protos.google.showcase.v1beta1.IPagedExpandLegacyRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.IPagedExpandResponse, - protos.google.showcase.v1beta1.IPagedExpandLegacyRequest|undefined, {}|undefined - ]>|void { + | protos.google.showcase.v1beta1.IPagedExpandLegacyRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.IPagedExpandResponse, + | protos.google.showcase.v1beta1.IPagedExpandLegacyRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IPagedExpandResponse, + protos.google.showcase.v1beta1.IPagedExpandLegacyRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('pagedExpandLegacy request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.IPagedExpandResponse, - protos.google.showcase.v1beta1.IPagedExpandLegacyRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.IPagedExpandResponse, + | protos.google.showcase.v1beta1.IPagedExpandLegacyRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('pagedExpandLegacy response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.pagedExpandLegacy(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.IPagedExpandResponse, - protos.google.showcase.v1beta1.IPagedExpandLegacyRequest|undefined, - {}|undefined - ]) => { - this._log.info('pagedExpandLegacy response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .pagedExpandLegacy(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.IPagedExpandResponse, + protos.google.showcase.v1beta1.IPagedExpandLegacyRequest | undefined, + {} | undefined, + ]) => { + this._log.info('pagedExpandLegacy response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * This method will block (wait) for the requested amount of time - * and then return the response or error. - * This method showcases how a client handles delays or retries. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.protobuf.Duration} request.responseDelay - * The amount of time to block before returning a response. - * @param {google.rpc.Status} request.error - * The error that will be returned by the server. If this code is specified - * to be the OK rpc code, an empty response will be returned. - * @param {google.showcase.v1beta1.BlockResponse} request.success - * The response to be returned that will signify successful method call. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.BlockResponse|BlockResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/echo.block.js - * region_tag:localhost_v1beta1_generated_Echo_Block_async - */ + /** + * This method will block (wait) for the requested amount of time + * and then return the response or error. + * This method showcases how a client handles delays or retries. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.protobuf.Duration} request.responseDelay + * The amount of time to block before returning a response. + * @param {google.rpc.Status} request.error + * The error that will be returned by the server. If this code is specified + * to be the OK rpc code, an empty response will be returned. + * @param {google.showcase.v1beta1.BlockResponse} request.success + * The response to be returned that will signify successful method call. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.BlockResponse|BlockResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/echo.block.js + * region_tag:localhost_v1beta1_generated_Echo_Block_async + */ block( - request?: protos.google.showcase.v1beta1.IBlockRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IBlockResponse, - protos.google.showcase.v1beta1.IBlockRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IBlockRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IBlockResponse, + protos.google.showcase.v1beta1.IBlockRequest | undefined, + {} | undefined, + ] + >; block( - request: protos.google.showcase.v1beta1.IBlockRequest, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.IBlockResponse, - protos.google.showcase.v1beta1.IBlockRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IBlockRequest, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.IBlockResponse, + protos.google.showcase.v1beta1.IBlockRequest | null | undefined, + {} | null | undefined + >, + ): void; block( - request: protos.google.showcase.v1beta1.IBlockRequest, - callback: Callback< - protos.google.showcase.v1beta1.IBlockResponse, - protos.google.showcase.v1beta1.IBlockRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IBlockRequest, + callback: Callback< + protos.google.showcase.v1beta1.IBlockResponse, + protos.google.showcase.v1beta1.IBlockRequest | null | undefined, + {} | null | undefined + >, + ): void; block( - request?: protos.google.showcase.v1beta1.IBlockRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.showcase.v1beta1.IBlockResponse, - protos.google.showcase.v1beta1.IBlockRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.showcase.v1beta1.IBlockRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.IBlockResponse, - protos.google.showcase.v1beta1.IBlockRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.IBlockResponse, - protos.google.showcase.v1beta1.IBlockRequest|undefined, {}|undefined - ]>|void { + protos.google.showcase.v1beta1.IBlockRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.IBlockResponse, + protos.google.showcase.v1beta1.IBlockRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IBlockResponse, + protos.google.showcase.v1beta1.IBlockRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('block request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.IBlockResponse, - protos.google.showcase.v1beta1.IBlockRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.IBlockResponse, + protos.google.showcase.v1beta1.IBlockRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('block response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.block(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.IBlockResponse, - protos.google.showcase.v1beta1.IBlockRequest|undefined, - {}|undefined - ]) => { - this._log.info('block response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .block(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.IBlockResponse, + protos.google.showcase.v1beta1.IBlockRequest | undefined, + {} | undefined, + ]) => { + this._log.info('block response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * This method splits the given content into words and will pass each word back - * through the stream. This method showcases server-side streaming RPCs. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.content - * The content that will be split into words and returned on the stream. - * @param {google.rpc.Status} request.error - * The error that is thrown after all words are sent on the stream. - * @param {google.protobuf.Duration} request.streamWaitTime - * The wait time between each server streaming messages - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits {@link protos.google.showcase.v1beta1.EchoResponse|EchoResponse} on 'data' event. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#server-streaming | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/echo.expand.js - * region_tag:localhost_v1beta1_generated_Echo_Expand_async - */ + /** + * This method splits the given content into words and will pass each word back + * through the stream. This method showcases server-side streaming RPCs. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.content + * The content that will be split into words and returned on the stream. + * @param {google.rpc.Status} request.error + * The error that is thrown after all words are sent on the stream. + * @param {google.protobuf.Duration} request.streamWaitTime + * The wait time between each server streaming messages + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits {@link protos.google.showcase.v1beta1.EchoResponse|EchoResponse} on 'data' event. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#server-streaming | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/echo.expand.js + * region_tag:localhost_v1beta1_generated_Echo_Expand_async + */ expand( - request?: protos.google.showcase.v1beta1.IExpandRequest, - options?: CallOptions): - gax.CancellableStream{ + request?: protos.google.showcase.v1beta1.IExpandRequest, + options?: CallOptions, + ): gax.CancellableStream { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('expand stream %j', options); return this.innerApiCalls.expand(request, options); } -/** - * This method will collect the words given to it. When the stream is closed - * by the client, this method will return the a concatenation of the strings - * passed to it. This method showcases client-side streaming RPCs. - * - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - A writable stream which accepts objects representing - * {@link protos.google.showcase.v1beta1.EchoRequest|EchoRequest}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#client-streaming | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/echo.collect.js - * region_tag:localhost_v1beta1_generated_Echo_Collect_async - */ + /** + * This method will collect the words given to it. When the stream is closed + * by the client, this method will return the a concatenation of the strings + * passed to it. This method showcases client-side streaming RPCs. + * + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} - A writable stream which accepts objects representing + * {@link protos.google.showcase.v1beta1.EchoRequest|EchoRequest}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#client-streaming | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/echo.collect.js + * region_tag:localhost_v1beta1_generated_Echo_Collect_async + */ collect( - options?: CallOptions, - callback?: Callback< - protos.google.showcase.v1beta1.IEchoResponse, - protos.google.showcase.v1beta1.IEchoRequest|null|undefined, - {}|null|undefined>): - gax.CancellableStream; + options?: CallOptions, + callback?: Callback< + protos.google.showcase.v1beta1.IEchoResponse, + protos.google.showcase.v1beta1.IEchoRequest | null | undefined, + {} | null | undefined + >, + ): gax.CancellableStream; collect( - callback?: Callback< - protos.google.showcase.v1beta1.IEchoResponse, - protos.google.showcase.v1beta1.IEchoRequest|null|undefined, - {}|null|undefined>): - gax.CancellableStream; + callback?: Callback< + protos.google.showcase.v1beta1.IEchoResponse, + protos.google.showcase.v1beta1.IEchoRequest | null | undefined, + {} | null | undefined + >, + ): gax.CancellableStream; collect( - optionsOrCallback?: CallOptions|Callback< - protos.google.showcase.v1beta1.IEchoResponse, - protos.google.showcase.v1beta1.IEchoRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.showcase.v1beta1.IEchoResponse, - protos.google.showcase.v1beta1.IEchoRequest|null|undefined, - {}|null|undefined>): - gax.CancellableStream { + optionsOrCallback?: + | CallOptions + | Callback< + protos.google.showcase.v1beta1.IEchoResponse, + protos.google.showcase.v1beta1.IEchoRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.IEchoResponse, + protos.google.showcase.v1beta1.IEchoRequest | null | undefined, + {} | null | undefined + >, + ): gax.CancellableStream { if (optionsOrCallback instanceof Function && callback === undefined) { - callback = optionsOrCallback; - optionsOrCallback = {}; + callback = optionsOrCallback; + optionsOrCallback = {}; } const options = optionsOrCallback as CallOptions; - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('collect stream %j', options); return this.innerApiCalls.collect(null, options, callback); } -/** - * This method, upon receiving a request on the stream, will pass the same - * content back on the stream. This method showcases bidirectional - * streaming RPCs. - * - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which is both readable and writable. It accepts objects - * representing {@link protos.google.showcase.v1beta1.EchoRequest|EchoRequest} for write() method, and - * will emit objects representing {@link protos.google.showcase.v1beta1.EchoResponse|EchoResponse} on 'data' event asynchronously. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#bi-directional-streaming | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/echo.chat.js - * region_tag:localhost_v1beta1_generated_Echo_Chat_async - */ - chat( - options?: CallOptions): - gax.CancellableStream { - this.initialize().catch(err => {throw err}); + /** + * This method, upon receiving a request on the stream, will pass the same + * content back on the stream. This method showcases bidirectional + * streaming RPCs. + * + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which is both readable and writable. It accepts objects + * representing {@link protos.google.showcase.v1beta1.EchoRequest|EchoRequest} for write() method, and + * will emit objects representing {@link protos.google.showcase.v1beta1.EchoResponse|EchoResponse} on 'data' event asynchronously. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#bi-directional-streaming | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/echo.chat.js + * region_tag:localhost_v1beta1_generated_Echo_Chat_async + */ + chat(options?: CallOptions): gax.CancellableStream { + this.initialize().catch((err) => { + throw err; + }); this._log.info('chat stream %j', options); return this.innerApiCalls.chat(null, options); } -/** - * This method will wait for the requested amount of time and then return. - * This method showcases how a client handles a request timeout. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.protobuf.Timestamp} request.endTime - * The time that this operation will complete. - * @param {google.protobuf.Duration} request.ttl - * The duration of this operation. - * @param {google.rpc.Status} request.error - * The error that will be returned by the server. If this code is specified - * to be the OK rpc code, an empty response will be returned. - * @param {google.showcase.v1beta1.WaitResponse} request.success - * The response to be returned on operation completion. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing - * a long running operation. Its `promise()` method returns a promise - * you can `await` for. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/echo.wait.js - * region_tag:localhost_v1beta1_generated_Echo_Wait_async - */ + /** + * This method will wait for the requested amount of time and then return. + * This method showcases how a client handles a request timeout. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.protobuf.Timestamp} request.endTime + * The time that this operation will complete. + * @param {google.protobuf.Duration} request.ttl + * The duration of this operation. + * @param {google.rpc.Status} request.error + * The error that will be returned by the server. If this code is specified + * to be the OK rpc code, an empty response will be returned. + * @param {google.showcase.v1beta1.WaitResponse} request.success + * The response to be returned on operation completion. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/echo.wait.js + * region_tag:localhost_v1beta1_generated_Echo_Wait_async + */ wait( - request?: protos.google.showcase.v1beta1.IWaitRequest, - options?: CallOptions): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IWaitRequest, + options?: CallOptions, + ): Promise< + [ + LROperation< + protos.google.showcase.v1beta1.IWaitResponse, + protos.google.showcase.v1beta1.IWaitMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; wait( - request: protos.google.showcase.v1beta1.IWaitRequest, - options: CallOptions, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IWaitRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.showcase.v1beta1.IWaitResponse, + protos.google.showcase.v1beta1.IWaitMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; wait( - request: protos.google.showcase.v1beta1.IWaitRequest, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IWaitRequest, + callback: Callback< + LROperation< + protos.google.showcase.v1beta1.IWaitResponse, + protos.google.showcase.v1beta1.IWaitMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; wait( - request?: protos.google.showcase.v1beta1.IWaitRequest, - optionsOrCallback?: CallOptions|Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>, - callback?: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>|void { + request?: protos.google.showcase.v1beta1.IWaitRequest, + optionsOrCallback?: + | CallOptions + | Callback< + LROperation< + protos.google.showcase.v1beta1.IWaitResponse, + protos.google.showcase.v1beta1.IWaitMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + callback?: Callback< + LROperation< + protos.google.showcase.v1beta1.IWaitResponse, + protos.google.showcase.v1beta1.IWaitMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + LROperation< + protos.google.showcase.v1beta1.IWaitResponse, + protos.google.showcase.v1beta1.IWaitMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize().catch(err => {throw err}); - const wrappedCallback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>|undefined = callback + this.initialize().catch((err) => { + throw err; + }); + const wrappedCallback: + | Callback< + LROperation< + protos.google.showcase.v1beta1.IWaitResponse, + protos.google.showcase.v1beta1.IWaitMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, rawResponse, _) => { this._log.info('wait response %j', rawResponse); callback!(error, response, rawResponse, _); // We verified callback above. } : undefined; this._log.info('wait request %j', request); - return this.innerApiCalls.wait(request, options, wrappedCallback) - ?.then(([response, rawResponse, _]: [ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]) => { - this._log.info('wait response %j', rawResponse); - return [response, rawResponse, _]; - }); + return this.innerApiCalls + .wait(request, options, wrappedCallback) + ?.then( + ([response, rawResponse, _]: [ + LROperation< + protos.google.showcase.v1beta1.IWaitResponse, + protos.google.showcase.v1beta1.IWaitMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ]) => { + this._log.info('wait response %j', rawResponse); + return [response, rawResponse, _]; + }, + ); } -/** - * Check the status of the long running operation returned by `wait()`. - * @param {String} name - * The operation name that will be passed. - * @returns {Promise} - The promise which resolves to an object. - * The decoded operation object has result and metadata field to get information from. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/echo.wait.js - * region_tag:localhost_v1beta1_generated_Echo_Wait_async - */ - async checkWaitProgress(name: string): Promise>{ + /** + * Check the status of the long running operation returned by `wait()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/echo.wait.js + * region_tag:localhost_v1beta1_generated_Echo_Wait_async + */ + async checkWaitProgress( + name: string, + ): Promise< + LROperation< + protos.google.showcase.v1beta1.WaitResponse, + protos.google.showcase.v1beta1.WaitMetadata + > + > { this._log.info('wait long-running'); - const request = new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest({name}); + const request = + new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( + { name }, + ); const [operation] = await this.operationsClient.getOperation(request); - const decodeOperation = new this._gaxModule.Operation(operation, this.descriptors.longrunning.wait, this._gaxModule.createDefaultBackoffSettings()); - return decodeOperation as LROperation; + const decodeOperation = new this._gaxModule.Operation( + operation, + this.descriptors.longrunning.wait, + this._gaxModule.createDefaultBackoffSettings(), + ); + return decodeOperation as LROperation< + protos.google.showcase.v1beta1.WaitResponse, + protos.google.showcase.v1beta1.WaitMetadata + >; } - /** - * This is similar to the Expand method but instead of returning a stream of - * expanded words, this method returns a paged list of expanded words. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.content - * The string to expand. - * @param {number} request.pageSize - * The number of words to returned in each page. - * @param {string} request.pageToken - * The position of the page to be returned. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.showcase.v1beta1.EchoResponse|EchoResponse}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `pagedExpandAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * This is similar to the Expand method but instead of returning a stream of + * expanded words, this method returns a paged list of expanded words. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.content + * The string to expand. + * @param {number} request.pageSize + * The number of words to returned in each page. + * @param {string} request.pageToken + * The position of the page to be returned. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.showcase.v1beta1.EchoResponse|EchoResponse}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `pagedExpandAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ pagedExpand( - request?: protos.google.showcase.v1beta1.IPagedExpandRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IEchoResponse[], - protos.google.showcase.v1beta1.IPagedExpandRequest|null, - protos.google.showcase.v1beta1.IPagedExpandResponse - ]>; + request?: protos.google.showcase.v1beta1.IPagedExpandRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IEchoResponse[], + protos.google.showcase.v1beta1.IPagedExpandRequest | null, + protos.google.showcase.v1beta1.IPagedExpandResponse, + ] + >; pagedExpand( - request: protos.google.showcase.v1beta1.IPagedExpandRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.showcase.v1beta1.IPagedExpandRequest, - protos.google.showcase.v1beta1.IPagedExpandResponse|null|undefined, - protos.google.showcase.v1beta1.IEchoResponse>): void; + request: protos.google.showcase.v1beta1.IPagedExpandRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.showcase.v1beta1.IPagedExpandRequest, + protos.google.showcase.v1beta1.IPagedExpandResponse | null | undefined, + protos.google.showcase.v1beta1.IEchoResponse + >, + ): void; pagedExpand( - request: protos.google.showcase.v1beta1.IPagedExpandRequest, - callback: PaginationCallback< - protos.google.showcase.v1beta1.IPagedExpandRequest, - protos.google.showcase.v1beta1.IPagedExpandResponse|null|undefined, - protos.google.showcase.v1beta1.IEchoResponse>): void; + request: protos.google.showcase.v1beta1.IPagedExpandRequest, + callback: PaginationCallback< + protos.google.showcase.v1beta1.IPagedExpandRequest, + protos.google.showcase.v1beta1.IPagedExpandResponse | null | undefined, + protos.google.showcase.v1beta1.IEchoResponse + >, + ): void; pagedExpand( - request?: protos.google.showcase.v1beta1.IPagedExpandRequest, - optionsOrCallback?: CallOptions|PaginationCallback< - protos.google.showcase.v1beta1.IPagedExpandRequest, - protos.google.showcase.v1beta1.IPagedExpandResponse|null|undefined, - protos.google.showcase.v1beta1.IEchoResponse>, - callback?: PaginationCallback< + request?: protos.google.showcase.v1beta1.IPagedExpandRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.showcase.v1beta1.IPagedExpandRequest, - protos.google.showcase.v1beta1.IPagedExpandResponse|null|undefined, - protos.google.showcase.v1beta1.IEchoResponse>): - Promise<[ - protos.google.showcase.v1beta1.IEchoResponse[], - protos.google.showcase.v1beta1.IPagedExpandRequest|null, - protos.google.showcase.v1beta1.IPagedExpandResponse - ]>|void { + | protos.google.showcase.v1beta1.IPagedExpandResponse + | null + | undefined, + protos.google.showcase.v1beta1.IEchoResponse + >, + callback?: PaginationCallback< + protos.google.showcase.v1beta1.IPagedExpandRequest, + protos.google.showcase.v1beta1.IPagedExpandResponse | null | undefined, + protos.google.showcase.v1beta1.IEchoResponse + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IEchoResponse[], + protos.google.showcase.v1beta1.IPagedExpandRequest | null, + protos.google.showcase.v1beta1.IPagedExpandResponse, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.showcase.v1beta1.IPagedExpandRequest, - protos.google.showcase.v1beta1.IPagedExpandResponse|null|undefined, - protos.google.showcase.v1beta1.IEchoResponse>|undefined = callback + this.initialize().catch((err) => { + throw err; + }); + const wrappedCallback: + | PaginationCallback< + protos.google.showcase.v1beta1.IPagedExpandRequest, + | protos.google.showcase.v1beta1.IPagedExpandResponse + | null + | undefined, + protos.google.showcase.v1beta1.IEchoResponse + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('pagedExpand values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -1198,96 +1593,102 @@ export class EchoClient { this._log.info('pagedExpand request %j', request); return this.innerApiCalls .pagedExpand(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.showcase.v1beta1.IEchoResponse[], - protos.google.showcase.v1beta1.IPagedExpandRequest|null, - protos.google.showcase.v1beta1.IPagedExpandResponse - ]) => { - this._log.info('pagedExpand values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.showcase.v1beta1.IEchoResponse[], + protos.google.showcase.v1beta1.IPagedExpandRequest | null, + protos.google.showcase.v1beta1.IPagedExpandResponse, + ]) => { + this._log.info('pagedExpand values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `pagedExpand`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.content - * The string to expand. - * @param {number} request.pageSize - * The number of words to returned in each page. - * @param {string} request.pageToken - * The position of the page to be returned. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.showcase.v1beta1.EchoResponse|EchoResponse} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `pagedExpandAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `pagedExpand`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.content + * The string to expand. + * @param {number} request.pageSize + * The number of words to returned in each page. + * @param {string} request.pageToken + * The position of the page to be returned. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.showcase.v1beta1.EchoResponse|EchoResponse} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `pagedExpandAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ pagedExpandStream( - request?: protos.google.showcase.v1beta1.IPagedExpandRequest, - options?: CallOptions): - Transform{ + request?: protos.google.showcase.v1beta1.IPagedExpandRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; const defaultCallSettings = this._defaults['pagedExpand']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('pagedExpand stream %j', request); return this.descriptors.page.pagedExpand.createStream( this.innerApiCalls.pagedExpand as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `pagedExpand`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.content - * The string to expand. - * @param {number} request.pageSize - * The number of words to returned in each page. - * @param {string} request.pageToken - * The position of the page to be returned. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.showcase.v1beta1.EchoResponse|EchoResponse}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/echo.paged_expand.js - * region_tag:localhost_v1beta1_generated_Echo_PagedExpand_async - */ + /** + * Equivalent to `pagedExpand`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.content + * The string to expand. + * @param {number} request.pageSize + * The number of words to returned in each page. + * @param {string} request.pageToken + * The position of the page to be returned. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.showcase.v1beta1.EchoResponse|EchoResponse}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/echo.paged_expand.js + * region_tag:localhost_v1beta1_generated_Echo_PagedExpand_async + */ pagedExpandAsync( - request?: protos.google.showcase.v1beta1.IPagedExpandRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.showcase.v1beta1.IPagedExpandRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; const defaultCallSettings = this._defaults['pagedExpand']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('pagedExpand iterate %j', request); return this.descriptors.page.pagedExpand.asyncIterate( this.innerApiCalls['pagedExpand'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } // -------------------- @@ -1302,7 +1703,7 @@ export class EchoClient { * @param {string} blueprint * @returns {string} Resource name string. */ - blueprintPath(session:string,test:string,blueprint:string) { + blueprintPath(session: string, test: string, blueprint: string) { return this.pathTemplates.blueprintPathTemplate.render({ session: session, test: test, @@ -1318,7 +1719,8 @@ export class EchoClient { * @returns {string} A string representing the session. */ matchSessionFromBlueprintName(blueprintName: string) { - return this.pathTemplates.blueprintPathTemplate.match(blueprintName).session; + return this.pathTemplates.blueprintPathTemplate.match(blueprintName) + .session; } /** @@ -1340,7 +1742,8 @@ export class EchoClient { * @returns {string} A string representing the blueprint. */ matchBlueprintFromBlueprintName(blueprintName: string) { - return this.pathTemplates.blueprintPathTemplate.match(blueprintName).blueprint; + return this.pathTemplates.blueprintPathTemplate.match(blueprintName) + .blueprint; } /** @@ -1349,7 +1752,7 @@ export class EchoClient { * @param {string} room * @returns {string} Resource name string. */ - roomPath(room:string) { + roomPath(room: string) { return this.pathTemplates.roomPathTemplate.render({ room: room, }); @@ -1373,7 +1776,7 @@ export class EchoClient { * @param {string} blurb * @returns {string} Resource name string. */ - roomBlurbPath(room:string,blurb:string) { + roomBlurbPath(room: string, blurb: string) { return this.pathTemplates.roomBlurbPathTemplate.render({ room: room, blurb: blurb, @@ -1410,7 +1813,11 @@ export class EchoClient { * @param {string} blurb * @returns {string} Resource name string. */ - roomBlurbsLegacyRoomBlurbPath(room:string,legacyRoom:string,blurb:string) { + roomBlurbsLegacyRoomBlurbPath( + room: string, + legacyRoom: string, + blurb: string, + ) { return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.render({ room: room, legacy_room: legacyRoom, @@ -1425,8 +1832,12 @@ export class EchoClient { * A fully-qualified path representing room_blurbs_legacy_room_blurb resource. * @returns {string} A string representing the room. */ - matchRoomFromRoomBlurbsLegacyRoomBlurbName(roomBlurbsLegacyRoomBlurbName: string) { - return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match(roomBlurbsLegacyRoomBlurbName).room; + matchRoomFromRoomBlurbsLegacyRoomBlurbName( + roomBlurbsLegacyRoomBlurbName: string, + ) { + return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match( + roomBlurbsLegacyRoomBlurbName, + ).room; } /** @@ -1436,8 +1847,12 @@ export class EchoClient { * A fully-qualified path representing room_blurbs_legacy_room_blurb resource. * @returns {string} A string representing the legacy_room. */ - matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName(roomBlurbsLegacyRoomBlurbName: string) { - return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match(roomBlurbsLegacyRoomBlurbName).legacy_room; + matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName( + roomBlurbsLegacyRoomBlurbName: string, + ) { + return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match( + roomBlurbsLegacyRoomBlurbName, + ).legacy_room; } /** @@ -1447,8 +1862,12 @@ export class EchoClient { * A fully-qualified path representing room_blurbs_legacy_room_blurb resource. * @returns {string} A string representing the blurb. */ - matchBlurbFromRoomBlurbsLegacyRoomBlurbName(roomBlurbsLegacyRoomBlurbName: string) { - return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match(roomBlurbsLegacyRoomBlurbName).blurb; + matchBlurbFromRoomBlurbsLegacyRoomBlurbName( + roomBlurbsLegacyRoomBlurbName: string, + ) { + return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match( + roomBlurbsLegacyRoomBlurbName, + ).blurb; } /** @@ -1457,7 +1876,7 @@ export class EchoClient { * @param {string} sequence * @returns {string} Resource name string. */ - sequencePath(sequence:string) { + sequencePath(sequence: string) { return this.pathTemplates.sequencePathTemplate.render({ sequence: sequence, }); @@ -1480,7 +1899,7 @@ export class EchoClient { * @param {string} sequence * @returns {string} Resource name string. */ - sequenceReportPath(sequence:string) { + sequenceReportPath(sequence: string) { return this.pathTemplates.sequenceReportPathTemplate.render({ sequence: sequence, }); @@ -1494,7 +1913,9 @@ export class EchoClient { * @returns {string} A string representing the sequence. */ matchSequenceFromSequenceReportName(sequenceReportName: string) { - return this.pathTemplates.sequenceReportPathTemplate.match(sequenceReportName).sequence; + return this.pathTemplates.sequenceReportPathTemplate.match( + sequenceReportName, + ).sequence; } /** @@ -1503,7 +1924,7 @@ export class EchoClient { * @param {string} session * @returns {string} Resource name string. */ - sessionPath(session:string) { + sessionPath(session: string) { return this.pathTemplates.sessionPathTemplate.render({ session: session, }); @@ -1527,7 +1948,7 @@ export class EchoClient { * @param {string} test * @returns {string} Resource name string. */ - testPath(session:string,test:string) { + testPath(session: string, test: string) { return this.pathTemplates.testPathTemplate.render({ session: session, test: test, @@ -1562,7 +1983,7 @@ export class EchoClient { * @param {string} user * @returns {string} Resource name string. */ - userPath(user:string) { + userPath(user: string) { return this.pathTemplates.userPathTemplate.render({ user: user, }); @@ -1586,7 +2007,7 @@ export class EchoClient { * @param {string} blurb * @returns {string} Resource name string. */ - userProfileBlurbPath(user:string,blurb:string) { + userProfileBlurbPath(user: string, blurb: string) { return this.pathTemplates.userProfileBlurbPathTemplate.render({ user: user, blurb: blurb, @@ -1601,7 +2022,9 @@ export class EchoClient { * @returns {string} A string representing the user. */ matchUserFromUserProfileBlurbName(userProfileBlurbName: string) { - return this.pathTemplates.userProfileBlurbPathTemplate.match(userProfileBlurbName).user; + return this.pathTemplates.userProfileBlurbPathTemplate.match( + userProfileBlurbName, + ).user; } /** @@ -1612,7 +2035,9 @@ export class EchoClient { * @returns {string} A string representing the blurb. */ matchBlurbFromUserProfileBlurbName(userProfileBlurbName: string) { - return this.pathTemplates.userProfileBlurbPathTemplate.match(userProfileBlurbName).blurb; + return this.pathTemplates.userProfileBlurbPathTemplate.match( + userProfileBlurbName, + ).blurb; } /** @@ -1623,12 +2048,18 @@ export class EchoClient { * @param {string} blurb * @returns {string} Resource name string. */ - userProfileBlurbsLegacyUserBlurbPath(user:string,legacyUser:string,blurb:string) { - return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.render({ - user: user, - legacy_user: legacyUser, - blurb: blurb, - }); + userProfileBlurbsLegacyUserBlurbPath( + user: string, + legacyUser: string, + blurb: string, + ) { + return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.render( + { + user: user, + legacy_user: legacyUser, + blurb: blurb, + }, + ); } /** @@ -1638,8 +2069,12 @@ export class EchoClient { * A fully-qualified path representing user_profile_blurbs_legacy_user_blurb resource. * @returns {string} A string representing the user. */ - matchUserFromUserProfileBlurbsLegacyUserBlurbName(userProfileBlurbsLegacyUserBlurbName: string) { - return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match(userProfileBlurbsLegacyUserBlurbName).user; + matchUserFromUserProfileBlurbsLegacyUserBlurbName( + userProfileBlurbsLegacyUserBlurbName: string, + ) { + return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match( + userProfileBlurbsLegacyUserBlurbName, + ).user; } /** @@ -1649,8 +2084,12 @@ export class EchoClient { * A fully-qualified path representing user_profile_blurbs_legacy_user_blurb resource. * @returns {string} A string representing the legacy_user. */ - matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName(userProfileBlurbsLegacyUserBlurbName: string) { - return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match(userProfileBlurbsLegacyUserBlurbName).legacy_user; + matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName( + userProfileBlurbsLegacyUserBlurbName: string, + ) { + return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match( + userProfileBlurbsLegacyUserBlurbName, + ).legacy_user; } /** @@ -1660,8 +2099,12 @@ export class EchoClient { * A fully-qualified path representing user_profile_blurbs_legacy_user_blurb resource. * @returns {string} A string representing the blurb. */ - matchBlurbFromUserProfileBlurbsLegacyUserBlurbName(userProfileBlurbsLegacyUserBlurbName: string) { - return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match(userProfileBlurbsLegacyUserBlurbName).blurb; + matchBlurbFromUserProfileBlurbsLegacyUserBlurbName( + userProfileBlurbsLegacyUserBlurbName: string, + ) { + return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match( + userProfileBlurbsLegacyUserBlurbName, + ).blurb; } /** @@ -1672,7 +2115,7 @@ export class EchoClient { */ close(): Promise { if (this.echoStub && !this._terminated) { - return this.echoStub.then(stub => { + return this.echoStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -1681,4 +2124,4 @@ export class EchoClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/core/generator/gapic-generator-typescript/baselines/showcase/src/v1beta1/identity_client.ts.baseline b/core/generator/gapic-generator-typescript/baselines/showcase/src/v1beta1/identity_client.ts.baseline index 43eb3f62e443..2bfa1e8dab9f 100644 --- a/core/generator/gapic-generator-typescript/baselines/showcase/src/v1beta1/identity_client.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/showcase/src/v1beta1/identity_client.ts.baseline @@ -18,11 +18,18 @@ /* global window */ import type * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions, PaginationCallback, GaxCall} from 'google-gax'; -import {Transform} from 'stream'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + PaginationCallback, + GaxCall, +} from 'google-gax'; +import { Transform } from 'stream'; import * as protos from '../../protos/protos'; import jsonProtos = require('../../protos/protos.json'); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; /** * Client JSON configuration object, loaded from @@ -44,7 +51,7 @@ export class IdentityClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('showcase'); @@ -57,9 +64,9 @@ export class IdentityClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; - identityStub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; + identityStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of IdentityClient. @@ -100,21 +107,42 @@ export class IdentityClient { * const client = new IdentityClient({fallback: true}, gax); * ``` */ - constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { // Ensure that options include all the required fields. const staticMembers = this.constructor as typeof IdentityClient; - if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { - throw new Error('Please set either universe_domain or universeDomain, but not both.'); + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); } - const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; - this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; this._servicePath = 'localhost'; - const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; - const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // Request numeric enum values if REST transport is used. opts.numericEnums = true; @@ -139,7 +167,7 @@ export class IdentityClient { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; @@ -153,10 +181,7 @@ export class IdentityClient { } // Determine the client header string. - const clientHeader = [ - `gax/${this._gaxModule.version}`, - `gapic/${version}`, - ]; + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/${process.versions.node}`); } else { @@ -178,52 +203,55 @@ export class IdentityClient { // Create useful helper objects for these. this.pathTemplates = { blueprintPathTemplate: new this._gaxModule.PathTemplate( - 'sessions/{session}/tests/{test}/blueprints/{blueprint}' - ), - roomPathTemplate: new this._gaxModule.PathTemplate( - 'rooms/{room}' + 'sessions/{session}/tests/{test}/blueprints/{blueprint}', ), + roomPathTemplate: new this._gaxModule.PathTemplate('rooms/{room}'), roomBlurbPathTemplate: new this._gaxModule.PathTemplate( - 'rooms/{room}/blurbs/{blurb}' + 'rooms/{room}/blurbs/{blurb}', ), roomBlurbsLegacyRoomBlurbPathTemplate: new this._gaxModule.PathTemplate( - 'rooms/{room}/blurbs/legacy/{legacy_room}.{blurb}' + 'rooms/{room}/blurbs/legacy/{legacy_room}.{blurb}', ), sequencePathTemplate: new this._gaxModule.PathTemplate( - 'sequences/{sequence}' + 'sequences/{sequence}', ), sequenceReportPathTemplate: new this._gaxModule.PathTemplate( - 'sequences/{sequence}/sequenceReport' + 'sequences/{sequence}/sequenceReport', ), sessionPathTemplate: new this._gaxModule.PathTemplate( - 'sessions/{session}' + 'sessions/{session}', ), testPathTemplate: new this._gaxModule.PathTemplate( - 'sessions/{session}/tests/{test}' - ), - userPathTemplate: new this._gaxModule.PathTemplate( - 'users/{user}' + 'sessions/{session}/tests/{test}', ), + userPathTemplate: new this._gaxModule.PathTemplate('users/{user}'), userProfileBlurbPathTemplate: new this._gaxModule.PathTemplate( - 'users/{user}/profile/blurbs/{blurb}' - ), - userProfileBlurbsLegacyUserBlurbPathTemplate: new this._gaxModule.PathTemplate( - 'users/{user}/profile/blurbs/legacy/{legacy_user}~{blurb}' + 'users/{user}/profile/blurbs/{blurb}', ), + userProfileBlurbsLegacyUserBlurbPathTemplate: + new this._gaxModule.PathTemplate( + 'users/{user}/profile/blurbs/legacy/{legacy_user}~{blurb}', + ), }; // Some of the methods on this service return "paged" results, // (e.g. 50 results at a time, with tokens to get subsequent // pages). Denote the keys used for pagination and results. this.descriptors.page = { - listUsers: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'users') + listUsers: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'users', + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.showcase.v1beta1.Identity', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.showcase.v1beta1.Identity', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + { 'x-goog-api-client': clientHeader.join(' ') }, + ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -254,37 +282,46 @@ export class IdentityClient { // Put together the "service stub" for // google.showcase.v1beta1.Identity. this.identityStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.showcase.v1beta1.Identity') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.showcase.v1beta1.Identity', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.showcase.v1beta1.Identity, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts, + this._providedCustomServicePath, + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const identityStubMethods = - ['createUser', 'getUser', 'updateUser', 'deleteUser', 'listUsers']; + const identityStubMethods = [ + 'createUser', + 'getUser', + 'updateUser', + 'deleteUser', + 'listUsers', + ]; for (const methodName of identityStubMethods) { const callPromise = this.identityStub.then( - stub => (...args: Array<{}>) => { - if (this._terminated) { - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error|null|undefined) => () => { + (stub) => + (...args: Array<{}>) => { + if (this._terminated) { + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { throw err; - }); + }, + ); - const descriptor = - this.descriptors.page[methodName] || - undefined; + const descriptor = this.descriptors.page[methodName] || undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -299,8 +336,14 @@ export class IdentityClient { * @returns {string} The DNS address for this service. */ static get servicePath() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'localhost'; } @@ -311,8 +354,14 @@ export class IdentityClient { * @returns {string} The DNS address for this service. */ static get apiEndpoint() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'localhost'; } @@ -352,8 +401,9 @@ export class IdentityClient { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId(callback?: Callback): - Promise|void { + getProjectId( + callback?: Callback, + ): Promise | void { if (callback) { this.auth.getProjectId(callback); return; @@ -364,458 +414,595 @@ export class IdentityClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Creates a user. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.showcase.v1beta1.User} request.user - * The user to create. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.User|User}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/identity.create_user.js - * region_tag:localhost_v1beta1_generated_Identity_CreateUser_async - */ + /** + * Creates a user. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.showcase.v1beta1.User} request.user + * The user to create. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.User|User}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/identity.create_user.js + * region_tag:localhost_v1beta1_generated_Identity_CreateUser_async + */ createUser( - request?: protos.google.showcase.v1beta1.ICreateUserRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IUser, - protos.google.showcase.v1beta1.ICreateUserRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.ICreateUserRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IUser, + protos.google.showcase.v1beta1.ICreateUserRequest | undefined, + {} | undefined, + ] + >; createUser( - request: protos.google.showcase.v1beta1.ICreateUserRequest, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.IUser, - protos.google.showcase.v1beta1.ICreateUserRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.ICreateUserRequest, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.IUser, + protos.google.showcase.v1beta1.ICreateUserRequest | null | undefined, + {} | null | undefined + >, + ): void; createUser( - request: protos.google.showcase.v1beta1.ICreateUserRequest, - callback: Callback< - protos.google.showcase.v1beta1.IUser, - protos.google.showcase.v1beta1.ICreateUserRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.ICreateUserRequest, + callback: Callback< + protos.google.showcase.v1beta1.IUser, + protos.google.showcase.v1beta1.ICreateUserRequest | null | undefined, + {} | null | undefined + >, + ): void; createUser( - request?: protos.google.showcase.v1beta1.ICreateUserRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.showcase.v1beta1.ICreateUserRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.IUser, - protos.google.showcase.v1beta1.ICreateUserRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.showcase.v1beta1.IUser, - protos.google.showcase.v1beta1.ICreateUserRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.IUser, - protos.google.showcase.v1beta1.ICreateUserRequest|undefined, {}|undefined - ]>|void { + protos.google.showcase.v1beta1.ICreateUserRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.IUser, + protos.google.showcase.v1beta1.ICreateUserRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IUser, + protos.google.showcase.v1beta1.ICreateUserRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('createUser request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.IUser, - protos.google.showcase.v1beta1.ICreateUserRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.IUser, + protos.google.showcase.v1beta1.ICreateUserRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createUser response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.createUser(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.IUser, - protos.google.showcase.v1beta1.ICreateUserRequest|undefined, - {}|undefined - ]) => { - this._log.info('createUser response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createUser(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.IUser, + protos.google.showcase.v1beta1.ICreateUserRequest | undefined, + {} | undefined, + ]) => { + this._log.info('createUser response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Retrieves the User with the given uri. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * The resource name of the requested user. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.User|User}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/identity.get_user.js - * region_tag:localhost_v1beta1_generated_Identity_GetUser_async - */ + /** + * Retrieves the User with the given uri. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * The resource name of the requested user. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.User|User}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/identity.get_user.js + * region_tag:localhost_v1beta1_generated_Identity_GetUser_async + */ getUser( - request?: protos.google.showcase.v1beta1.IGetUserRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IUser, - protos.google.showcase.v1beta1.IGetUserRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IGetUserRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IUser, + protos.google.showcase.v1beta1.IGetUserRequest | undefined, + {} | undefined, + ] + >; getUser( - request: protos.google.showcase.v1beta1.IGetUserRequest, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.IUser, - protos.google.showcase.v1beta1.IGetUserRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IGetUserRequest, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.IUser, + protos.google.showcase.v1beta1.IGetUserRequest | null | undefined, + {} | null | undefined + >, + ): void; getUser( - request: protos.google.showcase.v1beta1.IGetUserRequest, - callback: Callback< - protos.google.showcase.v1beta1.IUser, - protos.google.showcase.v1beta1.IGetUserRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IGetUserRequest, + callback: Callback< + protos.google.showcase.v1beta1.IUser, + protos.google.showcase.v1beta1.IGetUserRequest | null | undefined, + {} | null | undefined + >, + ): void; getUser( - request?: protos.google.showcase.v1beta1.IGetUserRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.showcase.v1beta1.IGetUserRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.IUser, - protos.google.showcase.v1beta1.IGetUserRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.showcase.v1beta1.IUser, - protos.google.showcase.v1beta1.IGetUserRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.IUser, - protos.google.showcase.v1beta1.IGetUserRequest|undefined, {}|undefined - ]>|void { + protos.google.showcase.v1beta1.IGetUserRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.IUser, + protos.google.showcase.v1beta1.IGetUserRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IUser, + protos.google.showcase.v1beta1.IGetUserRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getUser request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.IUser, - protos.google.showcase.v1beta1.IGetUserRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.IUser, + protos.google.showcase.v1beta1.IGetUserRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getUser response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getUser(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.IUser, - protos.google.showcase.v1beta1.IGetUserRequest|undefined, - {}|undefined - ]) => { - this._log.info('getUser response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getUser(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.IUser, + protos.google.showcase.v1beta1.IGetUserRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getUser response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Updates a user. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.showcase.v1beta1.User} request.user - * The user to update. - * @param {google.protobuf.FieldMask} request.updateMask - * The field mask to determine which fields are to be updated. If empty, the - * server will assume all fields are to be updated. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.User|User}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/identity.update_user.js - * region_tag:localhost_v1beta1_generated_Identity_UpdateUser_async - */ + /** + * Updates a user. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.showcase.v1beta1.User} request.user + * The user to update. + * @param {google.protobuf.FieldMask} request.updateMask + * The field mask to determine which fields are to be updated. If empty, the + * server will assume all fields are to be updated. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.User|User}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/identity.update_user.js + * region_tag:localhost_v1beta1_generated_Identity_UpdateUser_async + */ updateUser( - request?: protos.google.showcase.v1beta1.IUpdateUserRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IUser, - protos.google.showcase.v1beta1.IUpdateUserRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IUpdateUserRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IUser, + protos.google.showcase.v1beta1.IUpdateUserRequest | undefined, + {} | undefined, + ] + >; updateUser( - request: protos.google.showcase.v1beta1.IUpdateUserRequest, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.IUser, - protos.google.showcase.v1beta1.IUpdateUserRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IUpdateUserRequest, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.IUser, + protos.google.showcase.v1beta1.IUpdateUserRequest | null | undefined, + {} | null | undefined + >, + ): void; updateUser( - request: protos.google.showcase.v1beta1.IUpdateUserRequest, - callback: Callback< - protos.google.showcase.v1beta1.IUser, - protos.google.showcase.v1beta1.IUpdateUserRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IUpdateUserRequest, + callback: Callback< + protos.google.showcase.v1beta1.IUser, + protos.google.showcase.v1beta1.IUpdateUserRequest | null | undefined, + {} | null | undefined + >, + ): void; updateUser( - request?: protos.google.showcase.v1beta1.IUpdateUserRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.showcase.v1beta1.IUpdateUserRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.IUser, - protos.google.showcase.v1beta1.IUpdateUserRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.showcase.v1beta1.IUser, - protos.google.showcase.v1beta1.IUpdateUserRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.IUser, - protos.google.showcase.v1beta1.IUpdateUserRequest|undefined, {}|undefined - ]>|void { + protos.google.showcase.v1beta1.IUpdateUserRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.IUser, + protos.google.showcase.v1beta1.IUpdateUserRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IUser, + protos.google.showcase.v1beta1.IUpdateUserRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'user.name': request.user!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'user.name': request.user!.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateUser request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.IUser, - protos.google.showcase.v1beta1.IUpdateUserRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.IUser, + protos.google.showcase.v1beta1.IUpdateUserRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateUser response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.updateUser(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.IUser, - protos.google.showcase.v1beta1.IUpdateUserRequest|undefined, - {}|undefined - ]) => { - this._log.info('updateUser response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateUser(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.IUser, + protos.google.showcase.v1beta1.IUpdateUserRequest | undefined, + {} | undefined, + ]) => { + this._log.info('updateUser response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Deletes a user, their profile, and all of their authored messages. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * The resource name of the user to delete. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/identity.delete_user.js - * region_tag:localhost_v1beta1_generated_Identity_DeleteUser_async - */ + /** + * Deletes a user, their profile, and all of their authored messages. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * The resource name of the user to delete. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/identity.delete_user.js + * region_tag:localhost_v1beta1_generated_Identity_DeleteUser_async + */ deleteUser( - request?: protos.google.showcase.v1beta1.IDeleteUserRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteUserRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IDeleteUserRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteUserRequest | undefined, + {} | undefined, + ] + >; deleteUser( - request: protos.google.showcase.v1beta1.IDeleteUserRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteUserRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IDeleteUserRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteUserRequest | null | undefined, + {} | null | undefined + >, + ): void; deleteUser( - request: protos.google.showcase.v1beta1.IDeleteUserRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteUserRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IDeleteUserRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteUserRequest | null | undefined, + {} | null | undefined + >, + ): void; deleteUser( - request?: protos.google.showcase.v1beta1.IDeleteUserRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteUserRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.showcase.v1beta1.IDeleteUserRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteUserRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteUserRequest|undefined, {}|undefined - ]>|void { + protos.google.showcase.v1beta1.IDeleteUserRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteUserRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteUserRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('deleteUser request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteUserRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteUserRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteUser response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.deleteUser(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteUserRequest|undefined, - {}|undefined - ]) => { - this._log.info('deleteUser response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteUser(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteUserRequest | undefined, + {} | undefined, + ]) => { + this._log.info('deleteUser response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } - /** - * Lists all users. - * - * @param {Object} request - * The request object that will be sent. - * @param {number} request.pageSize - * The maximum number of users to return. Server may return fewer users - * than requested. If unspecified, server will pick an appropriate default. - * @param {string} request.pageToken - * The value of google.showcase.v1beta1.ListUsersResponse.next_page_token - * returned from the previous call to - * `google.showcase.v1beta1.Identity\ListUsers` method. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.showcase.v1beta1.User|User}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `listUsersAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Lists all users. + * + * @param {Object} request + * The request object that will be sent. + * @param {number} request.pageSize + * The maximum number of users to return. Server may return fewer users + * than requested. If unspecified, server will pick an appropriate default. + * @param {string} request.pageToken + * The value of google.showcase.v1beta1.ListUsersResponse.next_page_token + * returned from the previous call to + * `google.showcase.v1beta1.Identity\ListUsers` method. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.showcase.v1beta1.User|User}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listUsersAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listUsers( - request?: protos.google.showcase.v1beta1.IListUsersRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IUser[], - protos.google.showcase.v1beta1.IListUsersRequest|null, - protos.google.showcase.v1beta1.IListUsersResponse - ]>; + request?: protos.google.showcase.v1beta1.IListUsersRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IUser[], + protos.google.showcase.v1beta1.IListUsersRequest | null, + protos.google.showcase.v1beta1.IListUsersResponse, + ] + >; listUsers( - request: protos.google.showcase.v1beta1.IListUsersRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.showcase.v1beta1.IListUsersRequest, - protos.google.showcase.v1beta1.IListUsersResponse|null|undefined, - protos.google.showcase.v1beta1.IUser>): void; + request: protos.google.showcase.v1beta1.IListUsersRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.showcase.v1beta1.IListUsersRequest, + protos.google.showcase.v1beta1.IListUsersResponse | null | undefined, + protos.google.showcase.v1beta1.IUser + >, + ): void; listUsers( - request: protos.google.showcase.v1beta1.IListUsersRequest, - callback: PaginationCallback< - protos.google.showcase.v1beta1.IListUsersRequest, - protos.google.showcase.v1beta1.IListUsersResponse|null|undefined, - protos.google.showcase.v1beta1.IUser>): void; + request: protos.google.showcase.v1beta1.IListUsersRequest, + callback: PaginationCallback< + protos.google.showcase.v1beta1.IListUsersRequest, + protos.google.showcase.v1beta1.IListUsersResponse | null | undefined, + protos.google.showcase.v1beta1.IUser + >, + ): void; listUsers( - request?: protos.google.showcase.v1beta1.IListUsersRequest, - optionsOrCallback?: CallOptions|PaginationCallback< + request?: protos.google.showcase.v1beta1.IListUsersRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.showcase.v1beta1.IListUsersRequest, - protos.google.showcase.v1beta1.IListUsersResponse|null|undefined, - protos.google.showcase.v1beta1.IUser>, - callback?: PaginationCallback< - protos.google.showcase.v1beta1.IListUsersRequest, - protos.google.showcase.v1beta1.IListUsersResponse|null|undefined, - protos.google.showcase.v1beta1.IUser>): - Promise<[ - protos.google.showcase.v1beta1.IUser[], - protos.google.showcase.v1beta1.IListUsersRequest|null, - protos.google.showcase.v1beta1.IListUsersResponse - ]>|void { + protos.google.showcase.v1beta1.IListUsersResponse | null | undefined, + protos.google.showcase.v1beta1.IUser + >, + callback?: PaginationCallback< + protos.google.showcase.v1beta1.IListUsersRequest, + protos.google.showcase.v1beta1.IListUsersResponse | null | undefined, + protos.google.showcase.v1beta1.IUser + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IUser[], + protos.google.showcase.v1beta1.IListUsersRequest | null, + protos.google.showcase.v1beta1.IListUsersResponse, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.showcase.v1beta1.IListUsersRequest, - protos.google.showcase.v1beta1.IListUsersResponse|null|undefined, - protos.google.showcase.v1beta1.IUser>|undefined = callback + this.initialize().catch((err) => { + throw err; + }); + const wrappedCallback: + | PaginationCallback< + protos.google.showcase.v1beta1.IListUsersRequest, + protos.google.showcase.v1beta1.IListUsersResponse | null | undefined, + protos.google.showcase.v1beta1.IUser + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listUsers values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -824,98 +1011,104 @@ export class IdentityClient { this._log.info('listUsers request %j', request); return this.innerApiCalls .listUsers(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.showcase.v1beta1.IUser[], - protos.google.showcase.v1beta1.IListUsersRequest|null, - protos.google.showcase.v1beta1.IListUsersResponse - ]) => { - this._log.info('listUsers values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.showcase.v1beta1.IUser[], + protos.google.showcase.v1beta1.IListUsersRequest | null, + protos.google.showcase.v1beta1.IListUsersResponse, + ]) => { + this._log.info('listUsers values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listUsers`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {number} request.pageSize - * The maximum number of users to return. Server may return fewer users - * than requested. If unspecified, server will pick an appropriate default. - * @param {string} request.pageToken - * The value of google.showcase.v1beta1.ListUsersResponse.next_page_token - * returned from the previous call to - * `google.showcase.v1beta1.Identity\ListUsers` method. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.showcase.v1beta1.User|User} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `listUsersAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `listUsers`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {number} request.pageSize + * The maximum number of users to return. Server may return fewer users + * than requested. If unspecified, server will pick an appropriate default. + * @param {string} request.pageToken + * The value of google.showcase.v1beta1.ListUsersResponse.next_page_token + * returned from the previous call to + * `google.showcase.v1beta1.Identity\ListUsers` method. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.showcase.v1beta1.User|User} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listUsersAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listUsersStream( - request?: protos.google.showcase.v1beta1.IListUsersRequest, - options?: CallOptions): - Transform{ + request?: protos.google.showcase.v1beta1.IListUsersRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; const defaultCallSettings = this._defaults['listUsers']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listUsers stream %j', request); return this.descriptors.page.listUsers.createStream( this.innerApiCalls.listUsers as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listUsers`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {number} request.pageSize - * The maximum number of users to return. Server may return fewer users - * than requested. If unspecified, server will pick an appropriate default. - * @param {string} request.pageToken - * The value of google.showcase.v1beta1.ListUsersResponse.next_page_token - * returned from the previous call to - * `google.showcase.v1beta1.Identity\ListUsers` method. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.showcase.v1beta1.User|User}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/identity.list_users.js - * region_tag:localhost_v1beta1_generated_Identity_ListUsers_async - */ + /** + * Equivalent to `listUsers`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {number} request.pageSize + * The maximum number of users to return. Server may return fewer users + * than requested. If unspecified, server will pick an appropriate default. + * @param {string} request.pageToken + * The value of google.showcase.v1beta1.ListUsersResponse.next_page_token + * returned from the previous call to + * `google.showcase.v1beta1.Identity\ListUsers` method. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.showcase.v1beta1.User|User}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/identity.list_users.js + * region_tag:localhost_v1beta1_generated_Identity_ListUsers_async + */ listUsersAsync( - request?: protos.google.showcase.v1beta1.IListUsersRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.showcase.v1beta1.IListUsersRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; const defaultCallSettings = this._defaults['listUsers']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listUsers iterate %j', request); return this.descriptors.page.listUsers.asyncIterate( this.innerApiCalls['listUsers'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } // -------------------- @@ -930,7 +1123,7 @@ export class IdentityClient { * @param {string} blueprint * @returns {string} Resource name string. */ - blueprintPath(session:string,test:string,blueprint:string) { + blueprintPath(session: string, test: string, blueprint: string) { return this.pathTemplates.blueprintPathTemplate.render({ session: session, test: test, @@ -946,7 +1139,8 @@ export class IdentityClient { * @returns {string} A string representing the session. */ matchSessionFromBlueprintName(blueprintName: string) { - return this.pathTemplates.blueprintPathTemplate.match(blueprintName).session; + return this.pathTemplates.blueprintPathTemplate.match(blueprintName) + .session; } /** @@ -968,7 +1162,8 @@ export class IdentityClient { * @returns {string} A string representing the blueprint. */ matchBlueprintFromBlueprintName(blueprintName: string) { - return this.pathTemplates.blueprintPathTemplate.match(blueprintName).blueprint; + return this.pathTemplates.blueprintPathTemplate.match(blueprintName) + .blueprint; } /** @@ -977,7 +1172,7 @@ export class IdentityClient { * @param {string} room * @returns {string} Resource name string. */ - roomPath(room:string) { + roomPath(room: string) { return this.pathTemplates.roomPathTemplate.render({ room: room, }); @@ -1001,7 +1196,7 @@ export class IdentityClient { * @param {string} blurb * @returns {string} Resource name string. */ - roomBlurbPath(room:string,blurb:string) { + roomBlurbPath(room: string, blurb: string) { return this.pathTemplates.roomBlurbPathTemplate.render({ room: room, blurb: blurb, @@ -1038,7 +1233,11 @@ export class IdentityClient { * @param {string} blurb * @returns {string} Resource name string. */ - roomBlurbsLegacyRoomBlurbPath(room:string,legacyRoom:string,blurb:string) { + roomBlurbsLegacyRoomBlurbPath( + room: string, + legacyRoom: string, + blurb: string, + ) { return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.render({ room: room, legacy_room: legacyRoom, @@ -1053,8 +1252,12 @@ export class IdentityClient { * A fully-qualified path representing room_blurbs_legacy_room_blurb resource. * @returns {string} A string representing the room. */ - matchRoomFromRoomBlurbsLegacyRoomBlurbName(roomBlurbsLegacyRoomBlurbName: string) { - return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match(roomBlurbsLegacyRoomBlurbName).room; + matchRoomFromRoomBlurbsLegacyRoomBlurbName( + roomBlurbsLegacyRoomBlurbName: string, + ) { + return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match( + roomBlurbsLegacyRoomBlurbName, + ).room; } /** @@ -1064,8 +1267,12 @@ export class IdentityClient { * A fully-qualified path representing room_blurbs_legacy_room_blurb resource. * @returns {string} A string representing the legacy_room. */ - matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName(roomBlurbsLegacyRoomBlurbName: string) { - return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match(roomBlurbsLegacyRoomBlurbName).legacy_room; + matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName( + roomBlurbsLegacyRoomBlurbName: string, + ) { + return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match( + roomBlurbsLegacyRoomBlurbName, + ).legacy_room; } /** @@ -1075,8 +1282,12 @@ export class IdentityClient { * A fully-qualified path representing room_blurbs_legacy_room_blurb resource. * @returns {string} A string representing the blurb. */ - matchBlurbFromRoomBlurbsLegacyRoomBlurbName(roomBlurbsLegacyRoomBlurbName: string) { - return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match(roomBlurbsLegacyRoomBlurbName).blurb; + matchBlurbFromRoomBlurbsLegacyRoomBlurbName( + roomBlurbsLegacyRoomBlurbName: string, + ) { + return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match( + roomBlurbsLegacyRoomBlurbName, + ).blurb; } /** @@ -1085,7 +1296,7 @@ export class IdentityClient { * @param {string} sequence * @returns {string} Resource name string. */ - sequencePath(sequence:string) { + sequencePath(sequence: string) { return this.pathTemplates.sequencePathTemplate.render({ sequence: sequence, }); @@ -1108,7 +1319,7 @@ export class IdentityClient { * @param {string} sequence * @returns {string} Resource name string. */ - sequenceReportPath(sequence:string) { + sequenceReportPath(sequence: string) { return this.pathTemplates.sequenceReportPathTemplate.render({ sequence: sequence, }); @@ -1122,7 +1333,9 @@ export class IdentityClient { * @returns {string} A string representing the sequence. */ matchSequenceFromSequenceReportName(sequenceReportName: string) { - return this.pathTemplates.sequenceReportPathTemplate.match(sequenceReportName).sequence; + return this.pathTemplates.sequenceReportPathTemplate.match( + sequenceReportName, + ).sequence; } /** @@ -1131,7 +1344,7 @@ export class IdentityClient { * @param {string} session * @returns {string} Resource name string. */ - sessionPath(session:string) { + sessionPath(session: string) { return this.pathTemplates.sessionPathTemplate.render({ session: session, }); @@ -1155,7 +1368,7 @@ export class IdentityClient { * @param {string} test * @returns {string} Resource name string. */ - testPath(session:string,test:string) { + testPath(session: string, test: string) { return this.pathTemplates.testPathTemplate.render({ session: session, test: test, @@ -1190,7 +1403,7 @@ export class IdentityClient { * @param {string} user * @returns {string} Resource name string. */ - userPath(user:string) { + userPath(user: string) { return this.pathTemplates.userPathTemplate.render({ user: user, }); @@ -1214,7 +1427,7 @@ export class IdentityClient { * @param {string} blurb * @returns {string} Resource name string. */ - userProfileBlurbPath(user:string,blurb:string) { + userProfileBlurbPath(user: string, blurb: string) { return this.pathTemplates.userProfileBlurbPathTemplate.render({ user: user, blurb: blurb, @@ -1229,7 +1442,9 @@ export class IdentityClient { * @returns {string} A string representing the user. */ matchUserFromUserProfileBlurbName(userProfileBlurbName: string) { - return this.pathTemplates.userProfileBlurbPathTemplate.match(userProfileBlurbName).user; + return this.pathTemplates.userProfileBlurbPathTemplate.match( + userProfileBlurbName, + ).user; } /** @@ -1240,7 +1455,9 @@ export class IdentityClient { * @returns {string} A string representing the blurb. */ matchBlurbFromUserProfileBlurbName(userProfileBlurbName: string) { - return this.pathTemplates.userProfileBlurbPathTemplate.match(userProfileBlurbName).blurb; + return this.pathTemplates.userProfileBlurbPathTemplate.match( + userProfileBlurbName, + ).blurb; } /** @@ -1251,12 +1468,18 @@ export class IdentityClient { * @param {string} blurb * @returns {string} Resource name string. */ - userProfileBlurbsLegacyUserBlurbPath(user:string,legacyUser:string,blurb:string) { - return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.render({ - user: user, - legacy_user: legacyUser, - blurb: blurb, - }); + userProfileBlurbsLegacyUserBlurbPath( + user: string, + legacyUser: string, + blurb: string, + ) { + return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.render( + { + user: user, + legacy_user: legacyUser, + blurb: blurb, + }, + ); } /** @@ -1266,8 +1489,12 @@ export class IdentityClient { * A fully-qualified path representing user_profile_blurbs_legacy_user_blurb resource. * @returns {string} A string representing the user. */ - matchUserFromUserProfileBlurbsLegacyUserBlurbName(userProfileBlurbsLegacyUserBlurbName: string) { - return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match(userProfileBlurbsLegacyUserBlurbName).user; + matchUserFromUserProfileBlurbsLegacyUserBlurbName( + userProfileBlurbsLegacyUserBlurbName: string, + ) { + return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match( + userProfileBlurbsLegacyUserBlurbName, + ).user; } /** @@ -1277,8 +1504,12 @@ export class IdentityClient { * A fully-qualified path representing user_profile_blurbs_legacy_user_blurb resource. * @returns {string} A string representing the legacy_user. */ - matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName(userProfileBlurbsLegacyUserBlurbName: string) { - return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match(userProfileBlurbsLegacyUserBlurbName).legacy_user; + matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName( + userProfileBlurbsLegacyUserBlurbName: string, + ) { + return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match( + userProfileBlurbsLegacyUserBlurbName, + ).legacy_user; } /** @@ -1288,8 +1519,12 @@ export class IdentityClient { * A fully-qualified path representing user_profile_blurbs_legacy_user_blurb resource. * @returns {string} A string representing the blurb. */ - matchBlurbFromUserProfileBlurbsLegacyUserBlurbName(userProfileBlurbsLegacyUserBlurbName: string) { - return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match(userProfileBlurbsLegacyUserBlurbName).blurb; + matchBlurbFromUserProfileBlurbsLegacyUserBlurbName( + userProfileBlurbsLegacyUserBlurbName: string, + ) { + return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match( + userProfileBlurbsLegacyUserBlurbName, + ).blurb; } /** @@ -1300,7 +1535,7 @@ export class IdentityClient { */ close(): Promise { if (this.identityStub && !this._terminated) { - return this.identityStub.then(stub => { + return this.identityStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -1308,4 +1543,4 @@ export class IdentityClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/core/generator/gapic-generator-typescript/baselines/showcase/src/v1beta1/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/showcase/src/v1beta1/index.ts.baseline index f3bb4c129cce..297c19fa8f9d 100644 --- a/core/generator/gapic-generator-typescript/baselines/showcase/src/v1beta1/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/showcase/src/v1beta1/index.ts.baseline @@ -16,9 +16,9 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -export {ComplianceClient} from './compliance_client'; -export {EchoClient} from './echo_client'; -export {IdentityClient} from './identity_client'; -export {MessagingClient} from './messaging_client'; -export {SequenceServiceClient} from './sequence_service_client'; -export {TestingClient} from './testing_client'; +export { ComplianceClient } from './compliance_client'; +export { EchoClient } from './echo_client'; +export { IdentityClient } from './identity_client'; +export { MessagingClient } from './messaging_client'; +export { SequenceServiceClient } from './sequence_service_client'; +export { TestingClient } from './testing_client'; diff --git a/core/generator/gapic-generator-typescript/baselines/showcase/src/v1beta1/messaging_client.ts.baseline b/core/generator/gapic-generator-typescript/baselines/showcase/src/v1beta1/messaging_client.ts.baseline index ce1319861341..14d19e02eacd 100644 --- a/core/generator/gapic-generator-typescript/baselines/showcase/src/v1beta1/messaging_client.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/showcase/src/v1beta1/messaging_client.ts.baseline @@ -18,11 +18,20 @@ /* global window */ import type * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions, GrpcClientOptions, LROperation, PaginationCallback, GaxCall} from 'google-gax'; -import {Transform, PassThrough} from 'stream'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + GrpcClientOptions, + LROperation, + PaginationCallback, + GaxCall, +} from 'google-gax'; +import { Transform, PassThrough } from 'stream'; import * as protos from '../../protos/protos'; import jsonProtos = require('../../protos/protos.json'); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; /** * Client JSON configuration object, loaded from @@ -47,7 +56,7 @@ export class MessagingClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('showcase'); @@ -60,10 +69,10 @@ export class MessagingClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; operationsClient: gax.OperationsClient; - messagingStub?: Promise<{[name: string]: Function}>; + messagingStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of MessagingClient. @@ -104,21 +113,42 @@ export class MessagingClient { * const client = new MessagingClient({fallback: true}, gax); * ``` */ - constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { // Ensure that options include all the required fields. const staticMembers = this.constructor as typeof MessagingClient; - if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { - throw new Error('Please set either universe_domain or universeDomain, but not both.'); + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); } - const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; - this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; this._servicePath = 'localhost'; - const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; - const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // Request numeric enum values if REST transport is used. opts.numericEnums = true; @@ -143,7 +173,7 @@ export class MessagingClient { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; @@ -157,10 +187,7 @@ export class MessagingClient { } // Determine the client header string. - const clientHeader = [ - `gax/${this._gaxModule.version}`, - `gapic/${version}`, - ]; + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/${process.versions.node}`); } else { @@ -182,56 +209,70 @@ export class MessagingClient { // Create useful helper objects for these. this.pathTemplates = { blueprintPathTemplate: new this._gaxModule.PathTemplate( - 'sessions/{session}/tests/{test}/blueprints/{blueprint}' - ), - roomPathTemplate: new this._gaxModule.PathTemplate( - 'rooms/{room}' + 'sessions/{session}/tests/{test}/blueprints/{blueprint}', ), + roomPathTemplate: new this._gaxModule.PathTemplate('rooms/{room}'), roomBlurbPathTemplate: new this._gaxModule.PathTemplate( - 'rooms/{room}/blurbs/{blurb}' + 'rooms/{room}/blurbs/{blurb}', ), roomBlurbsLegacyRoomBlurbPathTemplate: new this._gaxModule.PathTemplate( - 'rooms/{room}/blurbs/legacy/{legacy_room}.{blurb}' + 'rooms/{room}/blurbs/legacy/{legacy_room}.{blurb}', ), sequencePathTemplate: new this._gaxModule.PathTemplate( - 'sequences/{sequence}' + 'sequences/{sequence}', ), sequenceReportPathTemplate: new this._gaxModule.PathTemplate( - 'sequences/{sequence}/sequenceReport' + 'sequences/{sequence}/sequenceReport', ), sessionPathTemplate: new this._gaxModule.PathTemplate( - 'sessions/{session}' + 'sessions/{session}', ), testPathTemplate: new this._gaxModule.PathTemplate( - 'sessions/{session}/tests/{test}' - ), - userPathTemplate: new this._gaxModule.PathTemplate( - 'users/{user}' + 'sessions/{session}/tests/{test}', ), + userPathTemplate: new this._gaxModule.PathTemplate('users/{user}'), userProfileBlurbPathTemplate: new this._gaxModule.PathTemplate( - 'users/{user}/profile/blurbs/{blurb}' - ), - userProfileBlurbsLegacyUserBlurbPathTemplate: new this._gaxModule.PathTemplate( - 'users/{user}/profile/blurbs/legacy/{legacy_user}~{blurb}' + 'users/{user}/profile/blurbs/{blurb}', ), + userProfileBlurbsLegacyUserBlurbPathTemplate: + new this._gaxModule.PathTemplate( + 'users/{user}/profile/blurbs/legacy/{legacy_user}~{blurb}', + ), }; // Some of the methods on this service return "paged" results, // (e.g. 50 results at a time, with tokens to get subsequent // pages). Denote the keys used for pagination and results. this.descriptors.page = { - listRooms: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'rooms'), - listBlurbs: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'blurbs') + listRooms: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'rooms', + ), + listBlurbs: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'blurbs', + ), }; // Some of the methods on this service provide streaming responses. // Provide descriptors for these. this.descriptors.stream = { - streamBlurbs: new this._gaxModule.StreamDescriptor(this._gaxModule.StreamType.SERVER_STREAMING, !!opts.fallback, !!opts.gaxServerStreamingRetries), - sendBlurbs: new this._gaxModule.StreamDescriptor(this._gaxModule.StreamType.CLIENT_STREAMING, !!opts.fallback), - connect: new this._gaxModule.StreamDescriptor(this._gaxModule.StreamType.BIDI_STREAMING, !!opts.fallback, !!opts.gaxServerStreamingRetries) + streamBlurbs: new this._gaxModule.StreamDescriptor( + this._gaxModule.StreamType.SERVER_STREAMING, + !!opts.fallback, + !!opts.gaxServerStreamingRetries, + ), + sendBlurbs: new this._gaxModule.StreamDescriptor( + this._gaxModule.StreamType.CLIENT_STREAMING, + !!opts.fallback, + ), + connect: new this._gaxModule.StreamDescriptor( + this._gaxModule.StreamType.BIDI_STREAMING, + !!opts.fallback, + !!opts.gaxServerStreamingRetries, + ), }; const protoFilesRoot = this._gaxModule.protobufFromJSON(jsonProtos); @@ -240,32 +281,103 @@ export class MessagingClient { // rather than holding a request open. const lroOptions: GrpcClientOptions = { auth: this.auth, - grpc: 'grpc' in this._gaxGrpc ? this._gaxGrpc.grpc : undefined + grpc: 'grpc' in this._gaxGrpc ? this._gaxGrpc.grpc : undefined, }; if (opts.fallback) { lroOptions.protoJson = protoFilesRoot; - lroOptions.httpRules = [{selector: 'google.cloud.location.Locations.ListLocations',get: '/v1beta1/{name=projects/*}/locations',},{selector: 'google.cloud.location.Locations.GetLocation',get: '/v1beta1/{name=projects/*/locations/*}',},{selector: 'google.iam.v1.IAMPolicy.SetIamPolicy',post: '/v1beta1/{resource=users/*}:setIamPolicy',body: '*',additional_bindings: [{post: '/v1beta1/{resource=rooms/*}:setIamPolicy',body: '*',},{post: '/v1beta1/{resource=rooms/*/blurbs/*}:setIamPolicy',body: '*',},{post: '/v1beta1/{resource=sequences/*}:setIamPolicy',body: '*',}], - },{selector: 'google.iam.v1.IAMPolicy.GetIamPolicy',get: '/v1beta1/{resource=users/*}:getIamPolicy',additional_bindings: [{get: '/v1beta1/{resource=rooms/*}:getIamPolicy',},{get: '/v1beta1/{resource=rooms/*/blurbs/*}:getIamPolicy',},{get: '/v1beta1/{resource=sequences/*}:getIamPolicy',}], - },{selector: 'google.iam.v1.IAMPolicy.TestIamPermissions',post: '/v1beta1/{resource=users/*}:testIamPermissions',body: '*',additional_bindings: [{post: '/v1beta1/{resource=rooms/*}:testIamPermissions',body: '*',},{post: '/v1beta1/{resource=rooms/*/blurbs/*}:testIamPermissions',body: '*',},{post: '/v1beta1/{resource=sequences/*}:testIamPermissions',body: '*',}], - },{selector: 'google.longrunning.Operations.ListOperations',get: '/v1beta1/operations',},{selector: 'google.longrunning.Operations.GetOperation',get: '/v1beta1/{name=operations/**}',},{selector: 'google.longrunning.Operations.DeleteOperation',delete: '/v1beta1/{name=operations/**}',},{selector: 'google.longrunning.Operations.CancelOperation',post: '/v1beta1/{name=operations/**}:cancel',}]; + lroOptions.httpRules = [ + { + selector: 'google.cloud.location.Locations.ListLocations', + get: '/v1beta1/{name=projects/*}/locations', + }, + { + selector: 'google.cloud.location.Locations.GetLocation', + get: '/v1beta1/{name=projects/*/locations/*}', + }, + { + selector: 'google.iam.v1.IAMPolicy.SetIamPolicy', + post: '/v1beta1/{resource=users/*}:setIamPolicy', + body: '*', + additional_bindings: [ + { post: '/v1beta1/{resource=rooms/*}:setIamPolicy', body: '*' }, + { + post: '/v1beta1/{resource=rooms/*/blurbs/*}:setIamPolicy', + body: '*', + }, + { post: '/v1beta1/{resource=sequences/*}:setIamPolicy', body: '*' }, + ], + }, + { + selector: 'google.iam.v1.IAMPolicy.GetIamPolicy', + get: '/v1beta1/{resource=users/*}:getIamPolicy', + additional_bindings: [ + { get: '/v1beta1/{resource=rooms/*}:getIamPolicy' }, + { get: '/v1beta1/{resource=rooms/*/blurbs/*}:getIamPolicy' }, + { get: '/v1beta1/{resource=sequences/*}:getIamPolicy' }, + ], + }, + { + selector: 'google.iam.v1.IAMPolicy.TestIamPermissions', + post: '/v1beta1/{resource=users/*}:testIamPermissions', + body: '*', + additional_bindings: [ + { + post: '/v1beta1/{resource=rooms/*}:testIamPermissions', + body: '*', + }, + { + post: '/v1beta1/{resource=rooms/*/blurbs/*}:testIamPermissions', + body: '*', + }, + { + post: '/v1beta1/{resource=sequences/*}:testIamPermissions', + body: '*', + }, + ], + }, + { + selector: 'google.longrunning.Operations.ListOperations', + get: '/v1beta1/operations', + }, + { + selector: 'google.longrunning.Operations.GetOperation', + get: '/v1beta1/{name=operations/**}', + }, + { + selector: 'google.longrunning.Operations.DeleteOperation', + delete: '/v1beta1/{name=operations/**}', + }, + { + selector: 'google.longrunning.Operations.CancelOperation', + post: '/v1beta1/{name=operations/**}:cancel', + }, + ]; } - this.operationsClient = this._gaxModule.lro(lroOptions).operationsClient(opts); + this.operationsClient = this._gaxModule + .lro(lroOptions) + .operationsClient(opts); const searchBlurbsResponse = protoFilesRoot.lookup( - '.google.showcase.v1beta1.SearchBlurbsResponse') as gax.protobuf.Type; + '.google.showcase.v1beta1.SearchBlurbsResponse', + ) as gax.protobuf.Type; const searchBlurbsMetadata = protoFilesRoot.lookup( - '.google.showcase.v1beta1.SearchBlurbsMetadata') as gax.protobuf.Type; + '.google.showcase.v1beta1.SearchBlurbsMetadata', + ) as gax.protobuf.Type; this.descriptors.longrunning = { searchBlurbs: new this._gaxModule.LongrunningDescriptor( this.operationsClient, searchBlurbsResponse.decode.bind(searchBlurbsResponse), - searchBlurbsMetadata.decode.bind(searchBlurbsMetadata)) + searchBlurbsMetadata.decode.bind(searchBlurbsMetadata), + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.showcase.v1beta1.Messaging', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.showcase.v1beta1.Messaging', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + { 'x-goog-api-client': clientHeader.join(' ') }, + ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -296,35 +408,60 @@ export class MessagingClient { // Put together the "service stub" for // google.showcase.v1beta1.Messaging. this.messagingStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.showcase.v1beta1.Messaging') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.showcase.v1beta1.Messaging', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.showcase.v1beta1.Messaging, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts, + this._providedCustomServicePath, + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const messagingStubMethods = - ['createRoom', 'getRoom', 'updateRoom', 'deleteRoom', 'listRooms', 'createBlurb', 'getBlurb', 'updateBlurb', 'deleteBlurb', 'listBlurbs', 'searchBlurbs', 'streamBlurbs', 'sendBlurbs', 'connect']; + const messagingStubMethods = [ + 'createRoom', + 'getRoom', + 'updateRoom', + 'deleteRoom', + 'listRooms', + 'createBlurb', + 'getBlurb', + 'updateBlurb', + 'deleteBlurb', + 'listBlurbs', + 'searchBlurbs', + 'streamBlurbs', + 'sendBlurbs', + 'connect', + ]; for (const methodName of messagingStubMethods) { const callPromise = this.messagingStub.then( - stub => (...args: Array<{}>) => { - if (this._terminated) { - if (methodName in this.descriptors.stream) { - const stream = new PassThrough({objectMode: true}); - setImmediate(() => { - stream.emit('error', new this._gaxModule.GoogleError('The client has already been closed.')); - }); - return stream; + (stub) => + (...args: Array<{}>) => { + if (this._terminated) { + if (methodName in this.descriptors.stream) { + const stream = new PassThrough({ objectMode: true }); + setImmediate(() => { + stream.emit( + 'error', + new this._gaxModule.GoogleError( + 'The client has already been closed.', + ), + ); + }); + return stream; + } + return Promise.reject('The client has already been closed.'); } - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error|null|undefined) => () => { + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { throw err; - }); + }, + ); const descriptor = this.descriptors.page[methodName] || @@ -335,7 +472,7 @@ export class MessagingClient { callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -350,8 +487,14 @@ export class MessagingClient { * @returns {string} The DNS address for this service. */ static get servicePath() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'localhost'; } @@ -362,8 +505,14 @@ export class MessagingClient { * @returns {string} The DNS address for this service. */ static get apiEndpoint() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'localhost'; } @@ -403,8 +552,9 @@ export class MessagingClient { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId(callback?: Callback): - Promise|void { + getProjectId( + callback?: Callback, + ): Promise | void { if (callback) { this.auth.getProjectId(callback); return; @@ -415,1072 +565,1400 @@ export class MessagingClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Creates a room. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.showcase.v1beta1.Room} request.room - * The room to create. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.Room|Room}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/messaging.create_room.js - * region_tag:localhost_v1beta1_generated_Messaging_CreateRoom_async - */ + /** + * Creates a room. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.showcase.v1beta1.Room} request.room + * The room to create. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.Room|Room}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/messaging.create_room.js + * region_tag:localhost_v1beta1_generated_Messaging_CreateRoom_async + */ createRoom( - request?: protos.google.showcase.v1beta1.ICreateRoomRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IRoom, - protos.google.showcase.v1beta1.ICreateRoomRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.ICreateRoomRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IRoom, + protos.google.showcase.v1beta1.ICreateRoomRequest | undefined, + {} | undefined, + ] + >; createRoom( - request: protos.google.showcase.v1beta1.ICreateRoomRequest, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.IRoom, - protos.google.showcase.v1beta1.ICreateRoomRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.ICreateRoomRequest, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.IRoom, + protos.google.showcase.v1beta1.ICreateRoomRequest | null | undefined, + {} | null | undefined + >, + ): void; createRoom( - request: protos.google.showcase.v1beta1.ICreateRoomRequest, - callback: Callback< - protos.google.showcase.v1beta1.IRoom, - protos.google.showcase.v1beta1.ICreateRoomRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.ICreateRoomRequest, + callback: Callback< + protos.google.showcase.v1beta1.IRoom, + protos.google.showcase.v1beta1.ICreateRoomRequest | null | undefined, + {} | null | undefined + >, + ): void; createRoom( - request?: protos.google.showcase.v1beta1.ICreateRoomRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.showcase.v1beta1.IRoom, - protos.google.showcase.v1beta1.ICreateRoomRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.showcase.v1beta1.ICreateRoomRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.IRoom, - protos.google.showcase.v1beta1.ICreateRoomRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.IRoom, - protos.google.showcase.v1beta1.ICreateRoomRequest|undefined, {}|undefined - ]>|void { + protos.google.showcase.v1beta1.ICreateRoomRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.IRoom, + protos.google.showcase.v1beta1.ICreateRoomRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IRoom, + protos.google.showcase.v1beta1.ICreateRoomRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('createRoom request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.IRoom, - protos.google.showcase.v1beta1.ICreateRoomRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.IRoom, + protos.google.showcase.v1beta1.ICreateRoomRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createRoom response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.createRoom(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.IRoom, - protos.google.showcase.v1beta1.ICreateRoomRequest|undefined, - {}|undefined - ]) => { - this._log.info('createRoom response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createRoom(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.IRoom, + protos.google.showcase.v1beta1.ICreateRoomRequest | undefined, + {} | undefined, + ]) => { + this._log.info('createRoom response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Retrieves the Room with the given resource name. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * The resource name of the requested room. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.Room|Room}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/messaging.get_room.js - * region_tag:localhost_v1beta1_generated_Messaging_GetRoom_async - */ + /** + * Retrieves the Room with the given resource name. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * The resource name of the requested room. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.Room|Room}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/messaging.get_room.js + * region_tag:localhost_v1beta1_generated_Messaging_GetRoom_async + */ getRoom( - request?: protos.google.showcase.v1beta1.IGetRoomRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IRoom, - protos.google.showcase.v1beta1.IGetRoomRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IGetRoomRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IRoom, + protos.google.showcase.v1beta1.IGetRoomRequest | undefined, + {} | undefined, + ] + >; getRoom( - request: protos.google.showcase.v1beta1.IGetRoomRequest, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.IRoom, - protos.google.showcase.v1beta1.IGetRoomRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IGetRoomRequest, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.IRoom, + protos.google.showcase.v1beta1.IGetRoomRequest | null | undefined, + {} | null | undefined + >, + ): void; getRoom( - request: protos.google.showcase.v1beta1.IGetRoomRequest, - callback: Callback< - protos.google.showcase.v1beta1.IRoom, - protos.google.showcase.v1beta1.IGetRoomRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IGetRoomRequest, + callback: Callback< + protos.google.showcase.v1beta1.IRoom, + protos.google.showcase.v1beta1.IGetRoomRequest | null | undefined, + {} | null | undefined + >, + ): void; getRoom( - request?: protos.google.showcase.v1beta1.IGetRoomRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.showcase.v1beta1.IRoom, - protos.google.showcase.v1beta1.IGetRoomRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.showcase.v1beta1.IGetRoomRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.IRoom, - protos.google.showcase.v1beta1.IGetRoomRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.IRoom, - protos.google.showcase.v1beta1.IGetRoomRequest|undefined, {}|undefined - ]>|void { + protos.google.showcase.v1beta1.IGetRoomRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.IRoom, + protos.google.showcase.v1beta1.IGetRoomRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IRoom, + protos.google.showcase.v1beta1.IGetRoomRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getRoom request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.IRoom, - protos.google.showcase.v1beta1.IGetRoomRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.IRoom, + protos.google.showcase.v1beta1.IGetRoomRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getRoom response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getRoom(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.IRoom, - protos.google.showcase.v1beta1.IGetRoomRequest|undefined, - {}|undefined - ]) => { - this._log.info('getRoom response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getRoom(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.IRoom, + protos.google.showcase.v1beta1.IGetRoomRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getRoom response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Updates a room. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.showcase.v1beta1.Room} request.room - * The room to update. - * @param {google.protobuf.FieldMask} request.updateMask - * The field mask to determine which fields are to be updated. If empty, the - * server will assume all fields are to be updated. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.Room|Room}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/messaging.update_room.js - * region_tag:localhost_v1beta1_generated_Messaging_UpdateRoom_async - */ + /** + * Updates a room. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.showcase.v1beta1.Room} request.room + * The room to update. + * @param {google.protobuf.FieldMask} request.updateMask + * The field mask to determine which fields are to be updated. If empty, the + * server will assume all fields are to be updated. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.Room|Room}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/messaging.update_room.js + * region_tag:localhost_v1beta1_generated_Messaging_UpdateRoom_async + */ updateRoom( - request?: protos.google.showcase.v1beta1.IUpdateRoomRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IRoom, - protos.google.showcase.v1beta1.IUpdateRoomRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IUpdateRoomRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IRoom, + protos.google.showcase.v1beta1.IUpdateRoomRequest | undefined, + {} | undefined, + ] + >; updateRoom( - request: protos.google.showcase.v1beta1.IUpdateRoomRequest, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.IRoom, - protos.google.showcase.v1beta1.IUpdateRoomRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IUpdateRoomRequest, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.IRoom, + protos.google.showcase.v1beta1.IUpdateRoomRequest | null | undefined, + {} | null | undefined + >, + ): void; updateRoom( - request: protos.google.showcase.v1beta1.IUpdateRoomRequest, - callback: Callback< - protos.google.showcase.v1beta1.IRoom, - protos.google.showcase.v1beta1.IUpdateRoomRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IUpdateRoomRequest, + callback: Callback< + protos.google.showcase.v1beta1.IRoom, + protos.google.showcase.v1beta1.IUpdateRoomRequest | null | undefined, + {} | null | undefined + >, + ): void; updateRoom( - request?: protos.google.showcase.v1beta1.IUpdateRoomRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.showcase.v1beta1.IRoom, - protos.google.showcase.v1beta1.IUpdateRoomRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.showcase.v1beta1.IUpdateRoomRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.IRoom, - protos.google.showcase.v1beta1.IUpdateRoomRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.IRoom, - protos.google.showcase.v1beta1.IUpdateRoomRequest|undefined, {}|undefined - ]>|void { + protos.google.showcase.v1beta1.IUpdateRoomRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.IRoom, + protos.google.showcase.v1beta1.IUpdateRoomRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IRoom, + protos.google.showcase.v1beta1.IUpdateRoomRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'room.name': request.room!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'room.name': request.room!.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateRoom request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.IRoom, - protos.google.showcase.v1beta1.IUpdateRoomRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.IRoom, + protos.google.showcase.v1beta1.IUpdateRoomRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateRoom response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.updateRoom(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.IRoom, - protos.google.showcase.v1beta1.IUpdateRoomRequest|undefined, - {}|undefined - ]) => { - this._log.info('updateRoom response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateRoom(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.IRoom, + protos.google.showcase.v1beta1.IUpdateRoomRequest | undefined, + {} | undefined, + ]) => { + this._log.info('updateRoom response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Deletes a room and all of its blurbs. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * The resource name of the requested room. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/messaging.delete_room.js - * region_tag:localhost_v1beta1_generated_Messaging_DeleteRoom_async - */ + /** + * Deletes a room and all of its blurbs. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * The resource name of the requested room. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/messaging.delete_room.js + * region_tag:localhost_v1beta1_generated_Messaging_DeleteRoom_async + */ deleteRoom( - request?: protos.google.showcase.v1beta1.IDeleteRoomRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteRoomRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IDeleteRoomRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteRoomRequest | undefined, + {} | undefined, + ] + >; deleteRoom( - request: protos.google.showcase.v1beta1.IDeleteRoomRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteRoomRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IDeleteRoomRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteRoomRequest | null | undefined, + {} | null | undefined + >, + ): void; deleteRoom( - request: protos.google.showcase.v1beta1.IDeleteRoomRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteRoomRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IDeleteRoomRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteRoomRequest | null | undefined, + {} | null | undefined + >, + ): void; deleteRoom( - request?: protos.google.showcase.v1beta1.IDeleteRoomRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.showcase.v1beta1.IDeleteRoomRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteRoomRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteRoomRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteRoomRequest|undefined, {}|undefined - ]>|void { + protos.google.showcase.v1beta1.IDeleteRoomRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteRoomRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteRoomRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('deleteRoom request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteRoomRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteRoomRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteRoom response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.deleteRoom(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteRoomRequest|undefined, - {}|undefined - ]) => { - this._log.info('deleteRoom response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteRoom(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteRoomRequest | undefined, + {} | undefined, + ]) => { + this._log.info('deleteRoom response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Creates a blurb. If the parent is a room, the blurb is understood to be a - * message in that room. If the parent is a profile, the blurb is understood - * to be a post on the profile. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * The resource name of the chat room or user profile that this blurb will - * be tied to. - * @param {google.showcase.v1beta1.Blurb} request.blurb - * The blurb to create. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.Blurb|Blurb}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/messaging.create_blurb.js - * region_tag:localhost_v1beta1_generated_Messaging_CreateBlurb_async - */ + /** + * Creates a blurb. If the parent is a room, the blurb is understood to be a + * message in that room. If the parent is a profile, the blurb is understood + * to be a post on the profile. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * The resource name of the chat room or user profile that this blurb will + * be tied to. + * @param {google.showcase.v1beta1.Blurb} request.blurb + * The blurb to create. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.Blurb|Blurb}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/messaging.create_blurb.js + * region_tag:localhost_v1beta1_generated_Messaging_CreateBlurb_async + */ createBlurb( - request?: protos.google.showcase.v1beta1.ICreateBlurbRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IBlurb, - protos.google.showcase.v1beta1.ICreateBlurbRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.ICreateBlurbRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IBlurb, + protos.google.showcase.v1beta1.ICreateBlurbRequest | undefined, + {} | undefined, + ] + >; createBlurb( - request: protos.google.showcase.v1beta1.ICreateBlurbRequest, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.IBlurb, - protos.google.showcase.v1beta1.ICreateBlurbRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.ICreateBlurbRequest, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.IBlurb, + protos.google.showcase.v1beta1.ICreateBlurbRequest | null | undefined, + {} | null | undefined + >, + ): void; createBlurb( - request: protos.google.showcase.v1beta1.ICreateBlurbRequest, - callback: Callback< - protos.google.showcase.v1beta1.IBlurb, - protos.google.showcase.v1beta1.ICreateBlurbRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.ICreateBlurbRequest, + callback: Callback< + protos.google.showcase.v1beta1.IBlurb, + protos.google.showcase.v1beta1.ICreateBlurbRequest | null | undefined, + {} | null | undefined + >, + ): void; createBlurb( - request?: protos.google.showcase.v1beta1.ICreateBlurbRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.showcase.v1beta1.ICreateBlurbRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.IBlurb, - protos.google.showcase.v1beta1.ICreateBlurbRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.showcase.v1beta1.IBlurb, - protos.google.showcase.v1beta1.ICreateBlurbRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.IBlurb, - protos.google.showcase.v1beta1.ICreateBlurbRequest|undefined, {}|undefined - ]>|void { + protos.google.showcase.v1beta1.ICreateBlurbRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.IBlurb, + protos.google.showcase.v1beta1.ICreateBlurbRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IBlurb, + protos.google.showcase.v1beta1.ICreateBlurbRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('createBlurb request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.IBlurb, - protos.google.showcase.v1beta1.ICreateBlurbRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.IBlurb, + protos.google.showcase.v1beta1.ICreateBlurbRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createBlurb response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.createBlurb(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.IBlurb, - protos.google.showcase.v1beta1.ICreateBlurbRequest|undefined, - {}|undefined - ]) => { - this._log.info('createBlurb response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createBlurb(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.IBlurb, + protos.google.showcase.v1beta1.ICreateBlurbRequest | undefined, + {} | undefined, + ]) => { + this._log.info('createBlurb response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Retrieves the Blurb with the given resource name. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * The resource name of the requested blurb. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.Blurb|Blurb}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/messaging.get_blurb.js - * region_tag:localhost_v1beta1_generated_Messaging_GetBlurb_async - */ + /** + * Retrieves the Blurb with the given resource name. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * The resource name of the requested blurb. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.Blurb|Blurb}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/messaging.get_blurb.js + * region_tag:localhost_v1beta1_generated_Messaging_GetBlurb_async + */ getBlurb( - request?: protos.google.showcase.v1beta1.IGetBlurbRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IBlurb, - protos.google.showcase.v1beta1.IGetBlurbRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IGetBlurbRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IBlurb, + protos.google.showcase.v1beta1.IGetBlurbRequest | undefined, + {} | undefined, + ] + >; getBlurb( - request: protos.google.showcase.v1beta1.IGetBlurbRequest, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.IBlurb, - protos.google.showcase.v1beta1.IGetBlurbRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IGetBlurbRequest, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.IBlurb, + protos.google.showcase.v1beta1.IGetBlurbRequest | null | undefined, + {} | null | undefined + >, + ): void; getBlurb( - request: protos.google.showcase.v1beta1.IGetBlurbRequest, - callback: Callback< - protos.google.showcase.v1beta1.IBlurb, - protos.google.showcase.v1beta1.IGetBlurbRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IGetBlurbRequest, + callback: Callback< + protos.google.showcase.v1beta1.IBlurb, + protos.google.showcase.v1beta1.IGetBlurbRequest | null | undefined, + {} | null | undefined + >, + ): void; getBlurb( - request?: protos.google.showcase.v1beta1.IGetBlurbRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.showcase.v1beta1.IGetBlurbRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.IBlurb, - protos.google.showcase.v1beta1.IGetBlurbRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.showcase.v1beta1.IBlurb, - protos.google.showcase.v1beta1.IGetBlurbRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.IBlurb, - protos.google.showcase.v1beta1.IGetBlurbRequest|undefined, {}|undefined - ]>|void { + protos.google.showcase.v1beta1.IGetBlurbRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.IBlurb, + protos.google.showcase.v1beta1.IGetBlurbRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IBlurb, + protos.google.showcase.v1beta1.IGetBlurbRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getBlurb request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.IBlurb, - protos.google.showcase.v1beta1.IGetBlurbRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.IBlurb, + protos.google.showcase.v1beta1.IGetBlurbRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getBlurb response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getBlurb(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.IBlurb, - protos.google.showcase.v1beta1.IGetBlurbRequest|undefined, - {}|undefined - ]) => { - this._log.info('getBlurb response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getBlurb(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.IBlurb, + protos.google.showcase.v1beta1.IGetBlurbRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getBlurb response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Updates a blurb. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.showcase.v1beta1.Blurb} request.blurb - * The blurb to update. - * @param {google.protobuf.FieldMask} request.updateMask - * The field mask to determine wich fields are to be updated. If empty, the - * server will assume all fields are to be updated. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.Blurb|Blurb}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/messaging.update_blurb.js - * region_tag:localhost_v1beta1_generated_Messaging_UpdateBlurb_async - */ + /** + * Updates a blurb. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.showcase.v1beta1.Blurb} request.blurb + * The blurb to update. + * @param {google.protobuf.FieldMask} request.updateMask + * The field mask to determine wich fields are to be updated. If empty, the + * server will assume all fields are to be updated. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.Blurb|Blurb}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/messaging.update_blurb.js + * region_tag:localhost_v1beta1_generated_Messaging_UpdateBlurb_async + */ updateBlurb( - request?: protos.google.showcase.v1beta1.IUpdateBlurbRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IBlurb, - protos.google.showcase.v1beta1.IUpdateBlurbRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IUpdateBlurbRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IBlurb, + protos.google.showcase.v1beta1.IUpdateBlurbRequest | undefined, + {} | undefined, + ] + >; updateBlurb( - request: protos.google.showcase.v1beta1.IUpdateBlurbRequest, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.IBlurb, - protos.google.showcase.v1beta1.IUpdateBlurbRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IUpdateBlurbRequest, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.IBlurb, + protos.google.showcase.v1beta1.IUpdateBlurbRequest | null | undefined, + {} | null | undefined + >, + ): void; updateBlurb( - request: protos.google.showcase.v1beta1.IUpdateBlurbRequest, - callback: Callback< - protos.google.showcase.v1beta1.IBlurb, - protos.google.showcase.v1beta1.IUpdateBlurbRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IUpdateBlurbRequest, + callback: Callback< + protos.google.showcase.v1beta1.IBlurb, + protos.google.showcase.v1beta1.IUpdateBlurbRequest | null | undefined, + {} | null | undefined + >, + ): void; updateBlurb( - request?: protos.google.showcase.v1beta1.IUpdateBlurbRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.showcase.v1beta1.IUpdateBlurbRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.IBlurb, - protos.google.showcase.v1beta1.IUpdateBlurbRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.showcase.v1beta1.IBlurb, - protos.google.showcase.v1beta1.IUpdateBlurbRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.IBlurb, - protos.google.showcase.v1beta1.IUpdateBlurbRequest|undefined, {}|undefined - ]>|void { + protos.google.showcase.v1beta1.IUpdateBlurbRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.IBlurb, + protos.google.showcase.v1beta1.IUpdateBlurbRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IBlurb, + protos.google.showcase.v1beta1.IUpdateBlurbRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'blurb.name': request.blurb!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'blurb.name': request.blurb!.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateBlurb request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.IBlurb, - protos.google.showcase.v1beta1.IUpdateBlurbRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.IBlurb, + protos.google.showcase.v1beta1.IUpdateBlurbRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateBlurb response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.updateBlurb(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.IBlurb, - protos.google.showcase.v1beta1.IUpdateBlurbRequest|undefined, - {}|undefined - ]) => { - this._log.info('updateBlurb response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateBlurb(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.IBlurb, + protos.google.showcase.v1beta1.IUpdateBlurbRequest | undefined, + {} | undefined, + ]) => { + this._log.info('updateBlurb response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Deletes a blurb. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * The resource name of the requested blurb. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/messaging.delete_blurb.js - * region_tag:localhost_v1beta1_generated_Messaging_DeleteBlurb_async - */ + /** + * Deletes a blurb. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * The resource name of the requested blurb. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/messaging.delete_blurb.js + * region_tag:localhost_v1beta1_generated_Messaging_DeleteBlurb_async + */ deleteBlurb( - request?: protos.google.showcase.v1beta1.IDeleteBlurbRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteBlurbRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IDeleteBlurbRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteBlurbRequest | undefined, + {} | undefined, + ] + >; deleteBlurb( - request: protos.google.showcase.v1beta1.IDeleteBlurbRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteBlurbRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IDeleteBlurbRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteBlurbRequest | null | undefined, + {} | null | undefined + >, + ): void; deleteBlurb( - request: protos.google.showcase.v1beta1.IDeleteBlurbRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteBlurbRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IDeleteBlurbRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteBlurbRequest | null | undefined, + {} | null | undefined + >, + ): void; deleteBlurb( - request?: protos.google.showcase.v1beta1.IDeleteBlurbRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteBlurbRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.showcase.v1beta1.IDeleteBlurbRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteBlurbRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteBlurbRequest|undefined, {}|undefined - ]>|void { + protos.google.showcase.v1beta1.IDeleteBlurbRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteBlurbRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteBlurbRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('deleteBlurb request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteBlurbRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteBlurbRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteBlurb response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.deleteBlurb(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteBlurbRequest|undefined, - {}|undefined - ]) => { - this._log.info('deleteBlurb response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteBlurb(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteBlurbRequest | undefined, + {} | undefined, + ]) => { + this._log.info('deleteBlurb response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * This returns a stream that emits the blurbs that are created for a - * particular chat room or user profile. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * The resource name of a chat room or user profile whose blurbs to stream. - * @param {google.protobuf.Timestamp} request.expireTime - * The time at which this stream will close. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits {@link protos.google.showcase.v1beta1.StreamBlurbsResponse|StreamBlurbsResponse} on 'data' event. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#server-streaming | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/messaging.stream_blurbs.js - * region_tag:localhost_v1beta1_generated_Messaging_StreamBlurbs_async - */ + /** + * This returns a stream that emits the blurbs that are created for a + * particular chat room or user profile. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * The resource name of a chat room or user profile whose blurbs to stream. + * @param {google.protobuf.Timestamp} request.expireTime + * The time at which this stream will close. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits {@link protos.google.showcase.v1beta1.StreamBlurbsResponse|StreamBlurbsResponse} on 'data' event. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#server-streaming | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/messaging.stream_blurbs.js + * region_tag:localhost_v1beta1_generated_Messaging_StreamBlurbs_async + */ streamBlurbs( - request?: protos.google.showcase.v1beta1.IStreamBlurbsRequest, - options?: CallOptions): - gax.CancellableStream{ + request?: protos.google.showcase.v1beta1.IStreamBlurbsRequest, + options?: CallOptions, + ): gax.CancellableStream { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('streamBlurbs stream %j', options); return this.innerApiCalls.streamBlurbs(request, options); } -/** - * This is a stream to create multiple blurbs. If an invalid blurb is - * requested to be created, the stream will close with an error. - * - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - A writable stream which accepts objects representing - * {@link protos.google.showcase.v1beta1.CreateBlurbRequest|CreateBlurbRequest}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#client-streaming | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/messaging.send_blurbs.js - * region_tag:localhost_v1beta1_generated_Messaging_SendBlurbs_async - */ + /** + * This is a stream to create multiple blurbs. If an invalid blurb is + * requested to be created, the stream will close with an error. + * + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} - A writable stream which accepts objects representing + * {@link protos.google.showcase.v1beta1.CreateBlurbRequest|CreateBlurbRequest}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#client-streaming | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/messaging.send_blurbs.js + * region_tag:localhost_v1beta1_generated_Messaging_SendBlurbs_async + */ sendBlurbs( - options?: CallOptions, - callback?: Callback< - protos.google.showcase.v1beta1.ISendBlurbsResponse, - protos.google.showcase.v1beta1.ICreateBlurbRequest|null|undefined, - {}|null|undefined>): - gax.CancellableStream; + options?: CallOptions, + callback?: Callback< + protos.google.showcase.v1beta1.ISendBlurbsResponse, + protos.google.showcase.v1beta1.ICreateBlurbRequest | null | undefined, + {} | null | undefined + >, + ): gax.CancellableStream; sendBlurbs( - callback?: Callback< - protos.google.showcase.v1beta1.ISendBlurbsResponse, - protos.google.showcase.v1beta1.ICreateBlurbRequest|null|undefined, - {}|null|undefined>): - gax.CancellableStream; + callback?: Callback< + protos.google.showcase.v1beta1.ISendBlurbsResponse, + protos.google.showcase.v1beta1.ICreateBlurbRequest | null | undefined, + {} | null | undefined + >, + ): gax.CancellableStream; sendBlurbs( - optionsOrCallback?: CallOptions|Callback< - protos.google.showcase.v1beta1.ISendBlurbsResponse, - protos.google.showcase.v1beta1.ICreateBlurbRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.showcase.v1beta1.ISendBlurbsResponse, - protos.google.showcase.v1beta1.ICreateBlurbRequest|null|undefined, - {}|null|undefined>): - gax.CancellableStream { + optionsOrCallback?: + | CallOptions + | Callback< + protos.google.showcase.v1beta1.ISendBlurbsResponse, + protos.google.showcase.v1beta1.ICreateBlurbRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.ISendBlurbsResponse, + protos.google.showcase.v1beta1.ICreateBlurbRequest | null | undefined, + {} | null | undefined + >, + ): gax.CancellableStream { if (optionsOrCallback instanceof Function && callback === undefined) { - callback = optionsOrCallback; - optionsOrCallback = {}; + callback = optionsOrCallback; + optionsOrCallback = {}; } const options = optionsOrCallback as CallOptions; - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('sendBlurbs stream %j', options); return this.innerApiCalls.sendBlurbs(null, options, callback); } -/** - * This method starts a bidirectional stream that receives all blurbs that - * are being created after the stream has started and sends requests to create - * blurbs. If an invalid blurb is requested to be created, the stream will - * close with an error. - * - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which is both readable and writable. It accepts objects - * representing {@link protos.google.showcase.v1beta1.ConnectRequest|ConnectRequest} for write() method, and - * will emit objects representing {@link protos.google.showcase.v1beta1.StreamBlurbsResponse|StreamBlurbsResponse} on 'data' event asynchronously. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#bi-directional-streaming | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/messaging.connect.js - * region_tag:localhost_v1beta1_generated_Messaging_Connect_async - */ - connect( - options?: CallOptions): - gax.CancellableStream { - this.initialize().catch(err => {throw err}); + /** + * This method starts a bidirectional stream that receives all blurbs that + * are being created after the stream has started and sends requests to create + * blurbs. If an invalid blurb is requested to be created, the stream will + * close with an error. + * + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which is both readable and writable. It accepts objects + * representing {@link protos.google.showcase.v1beta1.ConnectRequest|ConnectRequest} for write() method, and + * will emit objects representing {@link protos.google.showcase.v1beta1.StreamBlurbsResponse|StreamBlurbsResponse} on 'data' event asynchronously. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#bi-directional-streaming | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/messaging.connect.js + * region_tag:localhost_v1beta1_generated_Messaging_Connect_async + */ + connect(options?: CallOptions): gax.CancellableStream { + this.initialize().catch((err) => { + throw err; + }); this._log.info('connect stream %j', options); return this.innerApiCalls.connect(null, options); } -/** - * This method searches through all blurbs across all rooms and profiles - * for blurbs containing to words found in the query. Only posts that - * contain an exact match of a queried word will be returned. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.query - * The query used to search for blurbs containing to words of this string. - * Only posts that contain an exact match of a queried word will be returned. - * @param {string} request.parent - * The rooms or profiles to search. If unset, `SearchBlurbs` will search all - * rooms and all profiles. - * @param {number} request.pageSize - * The maximum number of blurbs return. Server may return fewer - * blurbs than requested. If unspecified, server will pick an appropriate - * default. - * @param {string} request.pageToken - * The value of - * google.showcase.v1beta1.SearchBlurbsResponse.next_page_token - * returned from the previous call to - * `google.showcase.v1beta1.Messaging\SearchBlurbs` method. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing - * a long running operation. Its `promise()` method returns a promise - * you can `await` for. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/messaging.search_blurbs.js - * region_tag:localhost_v1beta1_generated_Messaging_SearchBlurbs_async - */ + /** + * This method searches through all blurbs across all rooms and profiles + * for blurbs containing to words found in the query. Only posts that + * contain an exact match of a queried word will be returned. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.query + * The query used to search for blurbs containing to words of this string. + * Only posts that contain an exact match of a queried word will be returned. + * @param {string} request.parent + * The rooms or profiles to search. If unset, `SearchBlurbs` will search all + * rooms and all profiles. + * @param {number} request.pageSize + * The maximum number of blurbs return. Server may return fewer + * blurbs than requested. If unspecified, server will pick an appropriate + * default. + * @param {string} request.pageToken + * The value of + * google.showcase.v1beta1.SearchBlurbsResponse.next_page_token + * returned from the previous call to + * `google.showcase.v1beta1.Messaging\SearchBlurbs` method. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/messaging.search_blurbs.js + * region_tag:localhost_v1beta1_generated_Messaging_SearchBlurbs_async + */ searchBlurbs( - request?: protos.google.showcase.v1beta1.ISearchBlurbsRequest, - options?: CallOptions): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.ISearchBlurbsRequest, + options?: CallOptions, + ): Promise< + [ + LROperation< + protos.google.showcase.v1beta1.ISearchBlurbsResponse, + protos.google.showcase.v1beta1.ISearchBlurbsMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; searchBlurbs( - request: protos.google.showcase.v1beta1.ISearchBlurbsRequest, - options: CallOptions, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.ISearchBlurbsRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.showcase.v1beta1.ISearchBlurbsResponse, + protos.google.showcase.v1beta1.ISearchBlurbsMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; searchBlurbs( - request: protos.google.showcase.v1beta1.ISearchBlurbsRequest, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.ISearchBlurbsRequest, + callback: Callback< + LROperation< + protos.google.showcase.v1beta1.ISearchBlurbsResponse, + protos.google.showcase.v1beta1.ISearchBlurbsMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; searchBlurbs( - request?: protos.google.showcase.v1beta1.ISearchBlurbsRequest, - optionsOrCallback?: CallOptions|Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>, - callback?: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>|void { + request?: protos.google.showcase.v1beta1.ISearchBlurbsRequest, + optionsOrCallback?: + | CallOptions + | Callback< + LROperation< + protos.google.showcase.v1beta1.ISearchBlurbsResponse, + protos.google.showcase.v1beta1.ISearchBlurbsMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + callback?: Callback< + LROperation< + protos.google.showcase.v1beta1.ISearchBlurbsResponse, + protos.google.showcase.v1beta1.ISearchBlurbsMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + LROperation< + protos.google.showcase.v1beta1.ISearchBlurbsResponse, + protos.google.showcase.v1beta1.ISearchBlurbsMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + LROperation< + protos.google.showcase.v1beta1.ISearchBlurbsResponse, + protos.google.showcase.v1beta1.ISearchBlurbsMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, rawResponse, _) => { this._log.info('searchBlurbs response %j', rawResponse); callback!(error, response, rawResponse, _); // We verified callback above. } : undefined; this._log.info('searchBlurbs request %j', request); - return this.innerApiCalls.searchBlurbs(request, options, wrappedCallback) - ?.then(([response, rawResponse, _]: [ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]) => { - this._log.info('searchBlurbs response %j', rawResponse); - return [response, rawResponse, _]; - }); + return this.innerApiCalls + .searchBlurbs(request, options, wrappedCallback) + ?.then( + ([response, rawResponse, _]: [ + LROperation< + protos.google.showcase.v1beta1.ISearchBlurbsResponse, + protos.google.showcase.v1beta1.ISearchBlurbsMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ]) => { + this._log.info('searchBlurbs response %j', rawResponse); + return [response, rawResponse, _]; + }, + ); } -/** - * Check the status of the long running operation returned by `searchBlurbs()`. - * @param {String} name - * The operation name that will be passed. - * @returns {Promise} - The promise which resolves to an object. - * The decoded operation object has result and metadata field to get information from. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/messaging.search_blurbs.js - * region_tag:localhost_v1beta1_generated_Messaging_SearchBlurbs_async - */ - async checkSearchBlurbsProgress(name: string): Promise>{ + /** + * Check the status of the long running operation returned by `searchBlurbs()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/messaging.search_blurbs.js + * region_tag:localhost_v1beta1_generated_Messaging_SearchBlurbs_async + */ + async checkSearchBlurbsProgress( + name: string, + ): Promise< + LROperation< + protos.google.showcase.v1beta1.SearchBlurbsResponse, + protos.google.showcase.v1beta1.SearchBlurbsMetadata + > + > { this._log.info('searchBlurbs long-running'); - const request = new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest({name}); + const request = + new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( + { name }, + ); const [operation] = await this.operationsClient.getOperation(request); - const decodeOperation = new this._gaxModule.Operation(operation, this.descriptors.longrunning.searchBlurbs, this._gaxModule.createDefaultBackoffSettings()); - return decodeOperation as LROperation; + const decodeOperation = new this._gaxModule.Operation( + operation, + this.descriptors.longrunning.searchBlurbs, + this._gaxModule.createDefaultBackoffSettings(), + ); + return decodeOperation as LROperation< + protos.google.showcase.v1beta1.SearchBlurbsResponse, + protos.google.showcase.v1beta1.SearchBlurbsMetadata + >; } - /** - * Lists all chat rooms. - * - * @param {Object} request - * The request object that will be sent. - * @param {number} request.pageSize - * The maximum number of rooms return. Server may return fewer rooms - * than requested. If unspecified, server will pick an appropriate default. - * @param {string} request.pageToken - * The value of google.showcase.v1beta1.ListRoomsResponse.next_page_token - * returned from the previous call to - * `google.showcase.v1beta1.Messaging\ListRooms` method. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.showcase.v1beta1.Room|Room}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `listRoomsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Lists all chat rooms. + * + * @param {Object} request + * The request object that will be sent. + * @param {number} request.pageSize + * The maximum number of rooms return. Server may return fewer rooms + * than requested. If unspecified, server will pick an appropriate default. + * @param {string} request.pageToken + * The value of google.showcase.v1beta1.ListRoomsResponse.next_page_token + * returned from the previous call to + * `google.showcase.v1beta1.Messaging\ListRooms` method. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.showcase.v1beta1.Room|Room}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listRoomsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listRooms( - request?: protos.google.showcase.v1beta1.IListRoomsRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IRoom[], - protos.google.showcase.v1beta1.IListRoomsRequest|null, - protos.google.showcase.v1beta1.IListRoomsResponse - ]>; + request?: protos.google.showcase.v1beta1.IListRoomsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IRoom[], + protos.google.showcase.v1beta1.IListRoomsRequest | null, + protos.google.showcase.v1beta1.IListRoomsResponse, + ] + >; listRooms( - request: protos.google.showcase.v1beta1.IListRoomsRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.showcase.v1beta1.IListRoomsRequest, - protos.google.showcase.v1beta1.IListRoomsResponse|null|undefined, - protos.google.showcase.v1beta1.IRoom>): void; + request: protos.google.showcase.v1beta1.IListRoomsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.showcase.v1beta1.IListRoomsRequest, + protos.google.showcase.v1beta1.IListRoomsResponse | null | undefined, + protos.google.showcase.v1beta1.IRoom + >, + ): void; listRooms( - request: protos.google.showcase.v1beta1.IListRoomsRequest, - callback: PaginationCallback< - protos.google.showcase.v1beta1.IListRoomsRequest, - protos.google.showcase.v1beta1.IListRoomsResponse|null|undefined, - protos.google.showcase.v1beta1.IRoom>): void; + request: protos.google.showcase.v1beta1.IListRoomsRequest, + callback: PaginationCallback< + protos.google.showcase.v1beta1.IListRoomsRequest, + protos.google.showcase.v1beta1.IListRoomsResponse | null | undefined, + protos.google.showcase.v1beta1.IRoom + >, + ): void; listRooms( - request?: protos.google.showcase.v1beta1.IListRoomsRequest, - optionsOrCallback?: CallOptions|PaginationCallback< - protos.google.showcase.v1beta1.IListRoomsRequest, - protos.google.showcase.v1beta1.IListRoomsResponse|null|undefined, - protos.google.showcase.v1beta1.IRoom>, - callback?: PaginationCallback< + request?: protos.google.showcase.v1beta1.IListRoomsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.showcase.v1beta1.IListRoomsRequest, - protos.google.showcase.v1beta1.IListRoomsResponse|null|undefined, - protos.google.showcase.v1beta1.IRoom>): - Promise<[ - protos.google.showcase.v1beta1.IRoom[], - protos.google.showcase.v1beta1.IListRoomsRequest|null, - protos.google.showcase.v1beta1.IListRoomsResponse - ]>|void { + protos.google.showcase.v1beta1.IListRoomsResponse | null | undefined, + protos.google.showcase.v1beta1.IRoom + >, + callback?: PaginationCallback< + protos.google.showcase.v1beta1.IListRoomsRequest, + protos.google.showcase.v1beta1.IListRoomsResponse | null | undefined, + protos.google.showcase.v1beta1.IRoom + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IRoom[], + protos.google.showcase.v1beta1.IListRoomsRequest | null, + protos.google.showcase.v1beta1.IListRoomsResponse, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.showcase.v1beta1.IListRoomsRequest, - protos.google.showcase.v1beta1.IListRoomsResponse|null|undefined, - protos.google.showcase.v1beta1.IRoom>|undefined = callback + this.initialize().catch((err) => { + throw err; + }); + const wrappedCallback: + | PaginationCallback< + protos.google.showcase.v1beta1.IListRoomsRequest, + protos.google.showcase.v1beta1.IListRoomsResponse | null | undefined, + protos.google.showcase.v1beta1.IRoom + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listRooms values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -1489,186 +1967,207 @@ export class MessagingClient { this._log.info('listRooms request %j', request); return this.innerApiCalls .listRooms(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.showcase.v1beta1.IRoom[], - protos.google.showcase.v1beta1.IListRoomsRequest|null, - protos.google.showcase.v1beta1.IListRoomsResponse - ]) => { - this._log.info('listRooms values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.showcase.v1beta1.IRoom[], + protos.google.showcase.v1beta1.IListRoomsRequest | null, + protos.google.showcase.v1beta1.IListRoomsResponse, + ]) => { + this._log.info('listRooms values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listRooms`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {number} request.pageSize - * The maximum number of rooms return. Server may return fewer rooms - * than requested. If unspecified, server will pick an appropriate default. - * @param {string} request.pageToken - * The value of google.showcase.v1beta1.ListRoomsResponse.next_page_token - * returned from the previous call to - * `google.showcase.v1beta1.Messaging\ListRooms` method. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.showcase.v1beta1.Room|Room} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `listRoomsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `listRooms`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {number} request.pageSize + * The maximum number of rooms return. Server may return fewer rooms + * than requested. If unspecified, server will pick an appropriate default. + * @param {string} request.pageToken + * The value of google.showcase.v1beta1.ListRoomsResponse.next_page_token + * returned from the previous call to + * `google.showcase.v1beta1.Messaging\ListRooms` method. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.showcase.v1beta1.Room|Room} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listRoomsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listRoomsStream( - request?: protos.google.showcase.v1beta1.IListRoomsRequest, - options?: CallOptions): - Transform{ + request?: protos.google.showcase.v1beta1.IListRoomsRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; const defaultCallSettings = this._defaults['listRooms']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listRooms stream %j', request); return this.descriptors.page.listRooms.createStream( this.innerApiCalls.listRooms as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listRooms`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {number} request.pageSize - * The maximum number of rooms return. Server may return fewer rooms - * than requested. If unspecified, server will pick an appropriate default. - * @param {string} request.pageToken - * The value of google.showcase.v1beta1.ListRoomsResponse.next_page_token - * returned from the previous call to - * `google.showcase.v1beta1.Messaging\ListRooms` method. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.showcase.v1beta1.Room|Room}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/messaging.list_rooms.js - * region_tag:localhost_v1beta1_generated_Messaging_ListRooms_async - */ + /** + * Equivalent to `listRooms`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {number} request.pageSize + * The maximum number of rooms return. Server may return fewer rooms + * than requested. If unspecified, server will pick an appropriate default. + * @param {string} request.pageToken + * The value of google.showcase.v1beta1.ListRoomsResponse.next_page_token + * returned from the previous call to + * `google.showcase.v1beta1.Messaging\ListRooms` method. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.showcase.v1beta1.Room|Room}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/messaging.list_rooms.js + * region_tag:localhost_v1beta1_generated_Messaging_ListRooms_async + */ listRoomsAsync( - request?: protos.google.showcase.v1beta1.IListRoomsRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.showcase.v1beta1.IListRoomsRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; const defaultCallSettings = this._defaults['listRooms']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listRooms iterate %j', request); return this.descriptors.page.listRooms.asyncIterate( this.innerApiCalls['listRooms'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } - /** - * Lists blurbs for a specific chat room or user profile depending on the - * parent resource name. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * The resource name of the requested room or profile whos blurbs to list. - * @param {number} request.pageSize - * The maximum number of blurbs to return. Server may return fewer - * blurbs than requested. If unspecified, server will pick an appropriate - * default. - * @param {string} request.pageToken - * The value of google.showcase.v1beta1.ListBlurbsResponse.next_page_token - * returned from the previous call to - * `google.showcase.v1beta1.Messaging\ListBlurbs` method. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.showcase.v1beta1.Blurb|Blurb}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `listBlurbsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Lists blurbs for a specific chat room or user profile depending on the + * parent resource name. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * The resource name of the requested room or profile whos blurbs to list. + * @param {number} request.pageSize + * The maximum number of blurbs to return. Server may return fewer + * blurbs than requested. If unspecified, server will pick an appropriate + * default. + * @param {string} request.pageToken + * The value of google.showcase.v1beta1.ListBlurbsResponse.next_page_token + * returned from the previous call to + * `google.showcase.v1beta1.Messaging\ListBlurbs` method. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.showcase.v1beta1.Blurb|Blurb}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listBlurbsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listBlurbs( - request?: protos.google.showcase.v1beta1.IListBlurbsRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IBlurb[], - protos.google.showcase.v1beta1.IListBlurbsRequest|null, - protos.google.showcase.v1beta1.IListBlurbsResponse - ]>; + request?: protos.google.showcase.v1beta1.IListBlurbsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IBlurb[], + protos.google.showcase.v1beta1.IListBlurbsRequest | null, + protos.google.showcase.v1beta1.IListBlurbsResponse, + ] + >; listBlurbs( - request: protos.google.showcase.v1beta1.IListBlurbsRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.showcase.v1beta1.IListBlurbsRequest, - protos.google.showcase.v1beta1.IListBlurbsResponse|null|undefined, - protos.google.showcase.v1beta1.IBlurb>): void; + request: protos.google.showcase.v1beta1.IListBlurbsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.showcase.v1beta1.IListBlurbsRequest, + protos.google.showcase.v1beta1.IListBlurbsResponse | null | undefined, + protos.google.showcase.v1beta1.IBlurb + >, + ): void; listBlurbs( - request: protos.google.showcase.v1beta1.IListBlurbsRequest, - callback: PaginationCallback< - protos.google.showcase.v1beta1.IListBlurbsRequest, - protos.google.showcase.v1beta1.IListBlurbsResponse|null|undefined, - protos.google.showcase.v1beta1.IBlurb>): void; + request: protos.google.showcase.v1beta1.IListBlurbsRequest, + callback: PaginationCallback< + protos.google.showcase.v1beta1.IListBlurbsRequest, + protos.google.showcase.v1beta1.IListBlurbsResponse | null | undefined, + protos.google.showcase.v1beta1.IBlurb + >, + ): void; listBlurbs( - request?: protos.google.showcase.v1beta1.IListBlurbsRequest, - optionsOrCallback?: CallOptions|PaginationCallback< - protos.google.showcase.v1beta1.IListBlurbsRequest, - protos.google.showcase.v1beta1.IListBlurbsResponse|null|undefined, - protos.google.showcase.v1beta1.IBlurb>, - callback?: PaginationCallback< + request?: protos.google.showcase.v1beta1.IListBlurbsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.showcase.v1beta1.IListBlurbsRequest, - protos.google.showcase.v1beta1.IListBlurbsResponse|null|undefined, - protos.google.showcase.v1beta1.IBlurb>): - Promise<[ - protos.google.showcase.v1beta1.IBlurb[], - protos.google.showcase.v1beta1.IListBlurbsRequest|null, - protos.google.showcase.v1beta1.IListBlurbsResponse - ]>|void { + protos.google.showcase.v1beta1.IListBlurbsResponse | null | undefined, + protos.google.showcase.v1beta1.IBlurb + >, + callback?: PaginationCallback< + protos.google.showcase.v1beta1.IListBlurbsRequest, + protos.google.showcase.v1beta1.IListBlurbsResponse | null | undefined, + protos.google.showcase.v1beta1.IBlurb + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IBlurb[], + protos.google.showcase.v1beta1.IListBlurbsRequest | null, + protos.google.showcase.v1beta1.IListBlurbsResponse, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.showcase.v1beta1.IListBlurbsRequest, - protos.google.showcase.v1beta1.IListBlurbsResponse|null|undefined, - protos.google.showcase.v1beta1.IBlurb>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.showcase.v1beta1.IListBlurbsRequest, + protos.google.showcase.v1beta1.IListBlurbsResponse | null | undefined, + protos.google.showcase.v1beta1.IBlurb + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listBlurbs values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -1677,114 +2176,118 @@ export class MessagingClient { this._log.info('listBlurbs request %j', request); return this.innerApiCalls .listBlurbs(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.showcase.v1beta1.IBlurb[], - protos.google.showcase.v1beta1.IListBlurbsRequest|null, - protos.google.showcase.v1beta1.IListBlurbsResponse - ]) => { - this._log.info('listBlurbs values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.showcase.v1beta1.IBlurb[], + protos.google.showcase.v1beta1.IListBlurbsRequest | null, + protos.google.showcase.v1beta1.IListBlurbsResponse, + ]) => { + this._log.info('listBlurbs values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listBlurbs`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * The resource name of the requested room or profile whos blurbs to list. - * @param {number} request.pageSize - * The maximum number of blurbs to return. Server may return fewer - * blurbs than requested. If unspecified, server will pick an appropriate - * default. - * @param {string} request.pageToken - * The value of google.showcase.v1beta1.ListBlurbsResponse.next_page_token - * returned from the previous call to - * `google.showcase.v1beta1.Messaging\ListBlurbs` method. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.showcase.v1beta1.Blurb|Blurb} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `listBlurbsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `listBlurbs`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * The resource name of the requested room or profile whos blurbs to list. + * @param {number} request.pageSize + * The maximum number of blurbs to return. Server may return fewer + * blurbs than requested. If unspecified, server will pick an appropriate + * default. + * @param {string} request.pageToken + * The value of google.showcase.v1beta1.ListBlurbsResponse.next_page_token + * returned from the previous call to + * `google.showcase.v1beta1.Messaging\ListBlurbs` method. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.showcase.v1beta1.Blurb|Blurb} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listBlurbsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listBlurbsStream( - request?: protos.google.showcase.v1beta1.IListBlurbsRequest, - options?: CallOptions): - Transform{ + request?: protos.google.showcase.v1beta1.IListBlurbsRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); const defaultCallSettings = this._defaults['listBlurbs']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listBlurbs stream %j', request); return this.descriptors.page.listBlurbs.createStream( this.innerApiCalls.listBlurbs as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listBlurbs`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * The resource name of the requested room or profile whos blurbs to list. - * @param {number} request.pageSize - * The maximum number of blurbs to return. Server may return fewer - * blurbs than requested. If unspecified, server will pick an appropriate - * default. - * @param {string} request.pageToken - * The value of google.showcase.v1beta1.ListBlurbsResponse.next_page_token - * returned from the previous call to - * `google.showcase.v1beta1.Messaging\ListBlurbs` method. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.showcase.v1beta1.Blurb|Blurb}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/messaging.list_blurbs.js - * region_tag:localhost_v1beta1_generated_Messaging_ListBlurbs_async - */ + /** + * Equivalent to `listBlurbs`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * The resource name of the requested room or profile whos blurbs to list. + * @param {number} request.pageSize + * The maximum number of blurbs to return. Server may return fewer + * blurbs than requested. If unspecified, server will pick an appropriate + * default. + * @param {string} request.pageToken + * The value of google.showcase.v1beta1.ListBlurbsResponse.next_page_token + * returned from the previous call to + * `google.showcase.v1beta1.Messaging\ListBlurbs` method. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.showcase.v1beta1.Blurb|Blurb}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/messaging.list_blurbs.js + * region_tag:localhost_v1beta1_generated_Messaging_ListBlurbs_async + */ listBlurbsAsync( - request?: protos.google.showcase.v1beta1.IListBlurbsRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.showcase.v1beta1.IListBlurbsRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); const defaultCallSettings = this._defaults['listBlurbs']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listBlurbs iterate %j', request); return this.descriptors.page.listBlurbs.asyncIterate( this.innerApiCalls['listBlurbs'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } // -------------------- @@ -1799,7 +2302,7 @@ export class MessagingClient { * @param {string} blueprint * @returns {string} Resource name string. */ - blueprintPath(session:string,test:string,blueprint:string) { + blueprintPath(session: string, test: string, blueprint: string) { return this.pathTemplates.blueprintPathTemplate.render({ session: session, test: test, @@ -1815,7 +2318,8 @@ export class MessagingClient { * @returns {string} A string representing the session. */ matchSessionFromBlueprintName(blueprintName: string) { - return this.pathTemplates.blueprintPathTemplate.match(blueprintName).session; + return this.pathTemplates.blueprintPathTemplate.match(blueprintName) + .session; } /** @@ -1837,7 +2341,8 @@ export class MessagingClient { * @returns {string} A string representing the blueprint. */ matchBlueprintFromBlueprintName(blueprintName: string) { - return this.pathTemplates.blueprintPathTemplate.match(blueprintName).blueprint; + return this.pathTemplates.blueprintPathTemplate.match(blueprintName) + .blueprint; } /** @@ -1846,7 +2351,7 @@ export class MessagingClient { * @param {string} room * @returns {string} Resource name string. */ - roomPath(room:string) { + roomPath(room: string) { return this.pathTemplates.roomPathTemplate.render({ room: room, }); @@ -1870,7 +2375,7 @@ export class MessagingClient { * @param {string} blurb * @returns {string} Resource name string. */ - roomBlurbPath(room:string,blurb:string) { + roomBlurbPath(room: string, blurb: string) { return this.pathTemplates.roomBlurbPathTemplate.render({ room: room, blurb: blurb, @@ -1907,7 +2412,11 @@ export class MessagingClient { * @param {string} blurb * @returns {string} Resource name string. */ - roomBlurbsLegacyRoomBlurbPath(room:string,legacyRoom:string,blurb:string) { + roomBlurbsLegacyRoomBlurbPath( + room: string, + legacyRoom: string, + blurb: string, + ) { return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.render({ room: room, legacy_room: legacyRoom, @@ -1922,8 +2431,12 @@ export class MessagingClient { * A fully-qualified path representing room_blurbs_legacy_room_blurb resource. * @returns {string} A string representing the room. */ - matchRoomFromRoomBlurbsLegacyRoomBlurbName(roomBlurbsLegacyRoomBlurbName: string) { - return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match(roomBlurbsLegacyRoomBlurbName).room; + matchRoomFromRoomBlurbsLegacyRoomBlurbName( + roomBlurbsLegacyRoomBlurbName: string, + ) { + return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match( + roomBlurbsLegacyRoomBlurbName, + ).room; } /** @@ -1933,8 +2446,12 @@ export class MessagingClient { * A fully-qualified path representing room_blurbs_legacy_room_blurb resource. * @returns {string} A string representing the legacy_room. */ - matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName(roomBlurbsLegacyRoomBlurbName: string) { - return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match(roomBlurbsLegacyRoomBlurbName).legacy_room; + matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName( + roomBlurbsLegacyRoomBlurbName: string, + ) { + return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match( + roomBlurbsLegacyRoomBlurbName, + ).legacy_room; } /** @@ -1944,8 +2461,12 @@ export class MessagingClient { * A fully-qualified path representing room_blurbs_legacy_room_blurb resource. * @returns {string} A string representing the blurb. */ - matchBlurbFromRoomBlurbsLegacyRoomBlurbName(roomBlurbsLegacyRoomBlurbName: string) { - return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match(roomBlurbsLegacyRoomBlurbName).blurb; + matchBlurbFromRoomBlurbsLegacyRoomBlurbName( + roomBlurbsLegacyRoomBlurbName: string, + ) { + return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match( + roomBlurbsLegacyRoomBlurbName, + ).blurb; } /** @@ -1954,7 +2475,7 @@ export class MessagingClient { * @param {string} sequence * @returns {string} Resource name string. */ - sequencePath(sequence:string) { + sequencePath(sequence: string) { return this.pathTemplates.sequencePathTemplate.render({ sequence: sequence, }); @@ -1977,7 +2498,7 @@ export class MessagingClient { * @param {string} sequence * @returns {string} Resource name string. */ - sequenceReportPath(sequence:string) { + sequenceReportPath(sequence: string) { return this.pathTemplates.sequenceReportPathTemplate.render({ sequence: sequence, }); @@ -1991,7 +2512,9 @@ export class MessagingClient { * @returns {string} A string representing the sequence. */ matchSequenceFromSequenceReportName(sequenceReportName: string) { - return this.pathTemplates.sequenceReportPathTemplate.match(sequenceReportName).sequence; + return this.pathTemplates.sequenceReportPathTemplate.match( + sequenceReportName, + ).sequence; } /** @@ -2000,7 +2523,7 @@ export class MessagingClient { * @param {string} session * @returns {string} Resource name string. */ - sessionPath(session:string) { + sessionPath(session: string) { return this.pathTemplates.sessionPathTemplate.render({ session: session, }); @@ -2024,7 +2547,7 @@ export class MessagingClient { * @param {string} test * @returns {string} Resource name string. */ - testPath(session:string,test:string) { + testPath(session: string, test: string) { return this.pathTemplates.testPathTemplate.render({ session: session, test: test, @@ -2059,7 +2582,7 @@ export class MessagingClient { * @param {string} user * @returns {string} Resource name string. */ - userPath(user:string) { + userPath(user: string) { return this.pathTemplates.userPathTemplate.render({ user: user, }); @@ -2083,7 +2606,7 @@ export class MessagingClient { * @param {string} blurb * @returns {string} Resource name string. */ - userProfileBlurbPath(user:string,blurb:string) { + userProfileBlurbPath(user: string, blurb: string) { return this.pathTemplates.userProfileBlurbPathTemplate.render({ user: user, blurb: blurb, @@ -2098,7 +2621,9 @@ export class MessagingClient { * @returns {string} A string representing the user. */ matchUserFromUserProfileBlurbName(userProfileBlurbName: string) { - return this.pathTemplates.userProfileBlurbPathTemplate.match(userProfileBlurbName).user; + return this.pathTemplates.userProfileBlurbPathTemplate.match( + userProfileBlurbName, + ).user; } /** @@ -2109,7 +2634,9 @@ export class MessagingClient { * @returns {string} A string representing the blurb. */ matchBlurbFromUserProfileBlurbName(userProfileBlurbName: string) { - return this.pathTemplates.userProfileBlurbPathTemplate.match(userProfileBlurbName).blurb; + return this.pathTemplates.userProfileBlurbPathTemplate.match( + userProfileBlurbName, + ).blurb; } /** @@ -2120,12 +2647,18 @@ export class MessagingClient { * @param {string} blurb * @returns {string} Resource name string. */ - userProfileBlurbsLegacyUserBlurbPath(user:string,legacyUser:string,blurb:string) { - return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.render({ - user: user, - legacy_user: legacyUser, - blurb: blurb, - }); + userProfileBlurbsLegacyUserBlurbPath( + user: string, + legacyUser: string, + blurb: string, + ) { + return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.render( + { + user: user, + legacy_user: legacyUser, + blurb: blurb, + }, + ); } /** @@ -2135,8 +2668,12 @@ export class MessagingClient { * A fully-qualified path representing user_profile_blurbs_legacy_user_blurb resource. * @returns {string} A string representing the user. */ - matchUserFromUserProfileBlurbsLegacyUserBlurbName(userProfileBlurbsLegacyUserBlurbName: string) { - return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match(userProfileBlurbsLegacyUserBlurbName).user; + matchUserFromUserProfileBlurbsLegacyUserBlurbName( + userProfileBlurbsLegacyUserBlurbName: string, + ) { + return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match( + userProfileBlurbsLegacyUserBlurbName, + ).user; } /** @@ -2146,8 +2683,12 @@ export class MessagingClient { * A fully-qualified path representing user_profile_blurbs_legacy_user_blurb resource. * @returns {string} A string representing the legacy_user. */ - matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName(userProfileBlurbsLegacyUserBlurbName: string) { - return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match(userProfileBlurbsLegacyUserBlurbName).legacy_user; + matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName( + userProfileBlurbsLegacyUserBlurbName: string, + ) { + return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match( + userProfileBlurbsLegacyUserBlurbName, + ).legacy_user; } /** @@ -2157,8 +2698,12 @@ export class MessagingClient { * A fully-qualified path representing user_profile_blurbs_legacy_user_blurb resource. * @returns {string} A string representing the blurb. */ - matchBlurbFromUserProfileBlurbsLegacyUserBlurbName(userProfileBlurbsLegacyUserBlurbName: string) { - return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match(userProfileBlurbsLegacyUserBlurbName).blurb; + matchBlurbFromUserProfileBlurbsLegacyUserBlurbName( + userProfileBlurbsLegacyUserBlurbName: string, + ) { + return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match( + userProfileBlurbsLegacyUserBlurbName, + ).blurb; } /** @@ -2169,7 +2714,7 @@ export class MessagingClient { */ close(): Promise { if (this.messagingStub && !this._terminated) { - return this.messagingStub.then(stub => { + return this.messagingStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -2178,4 +2723,4 @@ export class MessagingClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/core/generator/gapic-generator-typescript/baselines/showcase/src/v1beta1/sequence_service_client.ts.baseline b/core/generator/gapic-generator-typescript/baselines/showcase/src/v1beta1/sequence_service_client.ts.baseline index 6c019cf506ee..ec7b823234c8 100644 --- a/core/generator/gapic-generator-typescript/baselines/showcase/src/v1beta1/sequence_service_client.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/showcase/src/v1beta1/sequence_service_client.ts.baseline @@ -18,11 +18,16 @@ /* global window */ import type * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions} from 'google-gax'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, +} from 'google-gax'; import * as protos from '../../protos/protos'; import jsonProtos = require('../../protos/protos.json'); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; /** * Client JSON configuration object, loaded from @@ -43,7 +48,7 @@ export class SequenceServiceClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('showcase'); @@ -56,9 +61,9 @@ export class SequenceServiceClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; - sequenceServiceStub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; + sequenceServiceStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of SequenceServiceClient. @@ -99,21 +104,42 @@ export class SequenceServiceClient { * const client = new SequenceServiceClient({fallback: true}, gax); * ``` */ - constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { // Ensure that options include all the required fields. const staticMembers = this.constructor as typeof SequenceServiceClient; - if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { - throw new Error('Please set either universe_domain or universeDomain, but not both.'); + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); } - const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; - this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; this._servicePath = 'localhost'; - const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; - const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // Request numeric enum values if REST transport is used. opts.numericEnums = true; @@ -138,7 +164,7 @@ export class SequenceServiceClient { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; @@ -152,10 +178,7 @@ export class SequenceServiceClient { } // Determine the client header string. - const clientHeader = [ - `gax/${this._gaxModule.version}`, - `gapic/${version}`, - ]; + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/${process.versions.node}`); } else { @@ -177,44 +200,44 @@ export class SequenceServiceClient { // Create useful helper objects for these. this.pathTemplates = { blueprintPathTemplate: new this._gaxModule.PathTemplate( - 'sessions/{session}/tests/{test}/blueprints/{blueprint}' - ), - roomPathTemplate: new this._gaxModule.PathTemplate( - 'rooms/{room}' + 'sessions/{session}/tests/{test}/blueprints/{blueprint}', ), + roomPathTemplate: new this._gaxModule.PathTemplate('rooms/{room}'), roomBlurbPathTemplate: new this._gaxModule.PathTemplate( - 'rooms/{room}/blurbs/{blurb}' + 'rooms/{room}/blurbs/{blurb}', ), roomBlurbsLegacyRoomBlurbPathTemplate: new this._gaxModule.PathTemplate( - 'rooms/{room}/blurbs/legacy/{legacy_room}.{blurb}' + 'rooms/{room}/blurbs/legacy/{legacy_room}.{blurb}', ), sequencePathTemplate: new this._gaxModule.PathTemplate( - 'sequences/{sequence}' + 'sequences/{sequence}', ), sequenceReportPathTemplate: new this._gaxModule.PathTemplate( - 'sequences/{sequence}/sequenceReport' + 'sequences/{sequence}/sequenceReport', ), sessionPathTemplate: new this._gaxModule.PathTemplate( - 'sessions/{session}' + 'sessions/{session}', ), testPathTemplate: new this._gaxModule.PathTemplate( - 'sessions/{session}/tests/{test}' - ), - userPathTemplate: new this._gaxModule.PathTemplate( - 'users/{user}' + 'sessions/{session}/tests/{test}', ), + userPathTemplate: new this._gaxModule.PathTemplate('users/{user}'), userProfileBlurbPathTemplate: new this._gaxModule.PathTemplate( - 'users/{user}/profile/blurbs/{blurb}' - ), - userProfileBlurbsLegacyUserBlurbPathTemplate: new this._gaxModule.PathTemplate( - 'users/{user}/profile/blurbs/legacy/{legacy_user}~{blurb}' + 'users/{user}/profile/blurbs/{blurb}', ), + userProfileBlurbsLegacyUserBlurbPathTemplate: + new this._gaxModule.PathTemplate( + 'users/{user}/profile/blurbs/legacy/{legacy_user}~{blurb}', + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.showcase.v1beta1.SequenceService', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.showcase.v1beta1.SequenceService', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + { 'x-goog-api-client': clientHeader.join(' ') }, + ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -245,36 +268,44 @@ export class SequenceServiceClient { // Put together the "service stub" for // google.showcase.v1beta1.SequenceService. this.sequenceServiceStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.showcase.v1beta1.SequenceService') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.showcase.v1beta1.SequenceService', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.showcase.v1beta1.SequenceService, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts, + this._providedCustomServicePath, + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const sequenceServiceStubMethods = - ['createSequence', 'getSequenceReport', 'attemptSequence']; + const sequenceServiceStubMethods = [ + 'createSequence', + 'getSequenceReport', + 'attemptSequence', + ]; for (const methodName of sequenceServiceStubMethods) { const callPromise = this.sequenceServiceStub.then( - stub => (...args: Array<{}>) => { - if (this._terminated) { - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error|null|undefined) => () => { + (stub) => + (...args: Array<{}>) => { + if (this._terminated) { + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { throw err; - }); + }, + ); - const descriptor = - undefined; + const descriptor = undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -289,8 +320,14 @@ export class SequenceServiceClient { * @returns {string} The DNS address for this service. */ static get servicePath() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'localhost'; } @@ -301,8 +338,14 @@ export class SequenceServiceClient { * @returns {string} The DNS address for this service. */ static get apiEndpoint() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'localhost'; } @@ -342,8 +385,9 @@ export class SequenceServiceClient { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId(callback?: Callback): - Promise|void { + getProjectId( + callback?: Callback, + ): Promise | void { if (callback) { this.auth.getProjectId(callback); return; @@ -354,276 +398,385 @@ export class SequenceServiceClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Creates a sequence. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.showcase.v1beta1.Sequence} request.sequence - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.Sequence|Sequence}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/sequence_service.create_sequence.js - * region_tag:localhost_v1beta1_generated_SequenceService_CreateSequence_async - */ + /** + * Creates a sequence. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.showcase.v1beta1.Sequence} request.sequence + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.Sequence|Sequence}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/sequence_service.create_sequence.js + * region_tag:localhost_v1beta1_generated_SequenceService_CreateSequence_async + */ createSequence( - request?: protos.google.showcase.v1beta1.ICreateSequenceRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.ISequence, - protos.google.showcase.v1beta1.ICreateSequenceRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.ICreateSequenceRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.ISequence, + protos.google.showcase.v1beta1.ICreateSequenceRequest | undefined, + {} | undefined, + ] + >; createSequence( - request: protos.google.showcase.v1beta1.ICreateSequenceRequest, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.ISequence, - protos.google.showcase.v1beta1.ICreateSequenceRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.ICreateSequenceRequest, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.ISequence, + protos.google.showcase.v1beta1.ICreateSequenceRequest | null | undefined, + {} | null | undefined + >, + ): void; createSequence( - request: protos.google.showcase.v1beta1.ICreateSequenceRequest, - callback: Callback< - protos.google.showcase.v1beta1.ISequence, - protos.google.showcase.v1beta1.ICreateSequenceRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.ICreateSequenceRequest, + callback: Callback< + protos.google.showcase.v1beta1.ISequence, + protos.google.showcase.v1beta1.ICreateSequenceRequest | null | undefined, + {} | null | undefined + >, + ): void; createSequence( - request?: protos.google.showcase.v1beta1.ICreateSequenceRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.showcase.v1beta1.ISequence, - protos.google.showcase.v1beta1.ICreateSequenceRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.showcase.v1beta1.ICreateSequenceRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.ISequence, - protos.google.showcase.v1beta1.ICreateSequenceRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.ISequence, - protos.google.showcase.v1beta1.ICreateSequenceRequest|undefined, {}|undefined - ]>|void { + | protos.google.showcase.v1beta1.ICreateSequenceRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.ISequence, + protos.google.showcase.v1beta1.ICreateSequenceRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.ISequence, + protos.google.showcase.v1beta1.ICreateSequenceRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('createSequence request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.ISequence, - protos.google.showcase.v1beta1.ICreateSequenceRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.ISequence, + | protos.google.showcase.v1beta1.ICreateSequenceRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createSequence response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.createSequence(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.ISequence, - protos.google.showcase.v1beta1.ICreateSequenceRequest|undefined, - {}|undefined - ]) => { - this._log.info('createSequence response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createSequence(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.ISequence, + protos.google.showcase.v1beta1.ICreateSequenceRequest | undefined, + {} | undefined, + ]) => { + this._log.info('createSequence response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Retrieves a sequence. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.SequenceReport|SequenceReport}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/sequence_service.get_sequence_report.js - * region_tag:localhost_v1beta1_generated_SequenceService_GetSequenceReport_async - */ + /** + * Retrieves a sequence. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.SequenceReport|SequenceReport}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/sequence_service.get_sequence_report.js + * region_tag:localhost_v1beta1_generated_SequenceService_GetSequenceReport_async + */ getSequenceReport( - request?: protos.google.showcase.v1beta1.IGetSequenceReportRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.ISequenceReport, - protos.google.showcase.v1beta1.IGetSequenceReportRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IGetSequenceReportRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.ISequenceReport, + protos.google.showcase.v1beta1.IGetSequenceReportRequest | undefined, + {} | undefined, + ] + >; getSequenceReport( - request: protos.google.showcase.v1beta1.IGetSequenceReportRequest, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.ISequenceReport, - protos.google.showcase.v1beta1.IGetSequenceReportRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IGetSequenceReportRequest, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.ISequenceReport, + | protos.google.showcase.v1beta1.IGetSequenceReportRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getSequenceReport( - request: protos.google.showcase.v1beta1.IGetSequenceReportRequest, - callback: Callback< - protos.google.showcase.v1beta1.ISequenceReport, - protos.google.showcase.v1beta1.IGetSequenceReportRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IGetSequenceReportRequest, + callback: Callback< + protos.google.showcase.v1beta1.ISequenceReport, + | protos.google.showcase.v1beta1.IGetSequenceReportRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getSequenceReport( - request?: protos.google.showcase.v1beta1.IGetSequenceReportRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.showcase.v1beta1.ISequenceReport, - protos.google.showcase.v1beta1.IGetSequenceReportRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.showcase.v1beta1.IGetSequenceReportRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.ISequenceReport, - protos.google.showcase.v1beta1.IGetSequenceReportRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.ISequenceReport, - protos.google.showcase.v1beta1.IGetSequenceReportRequest|undefined, {}|undefined - ]>|void { + | protos.google.showcase.v1beta1.IGetSequenceReportRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.ISequenceReport, + | protos.google.showcase.v1beta1.IGetSequenceReportRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.ISequenceReport, + protos.google.showcase.v1beta1.IGetSequenceReportRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getSequenceReport request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.ISequenceReport, - protos.google.showcase.v1beta1.IGetSequenceReportRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.ISequenceReport, + | protos.google.showcase.v1beta1.IGetSequenceReportRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getSequenceReport response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getSequenceReport(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.ISequenceReport, - protos.google.showcase.v1beta1.IGetSequenceReportRequest|undefined, - {}|undefined - ]) => { - this._log.info('getSequenceReport response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getSequenceReport(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.ISequenceReport, + protos.google.showcase.v1beta1.IGetSequenceReportRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getSequenceReport response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Attempts a sequence. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/sequence_service.attempt_sequence.js - * region_tag:localhost_v1beta1_generated_SequenceService_AttemptSequence_async - */ + /** + * Attempts a sequence. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/sequence_service.attempt_sequence.js + * region_tag:localhost_v1beta1_generated_SequenceService_AttemptSequence_async + */ attemptSequence( - request?: protos.google.showcase.v1beta1.IAttemptSequenceRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IAttemptSequenceRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IAttemptSequenceRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IAttemptSequenceRequest | undefined, + {} | undefined, + ] + >; attemptSequence( - request: protos.google.showcase.v1beta1.IAttemptSequenceRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IAttemptSequenceRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IAttemptSequenceRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IAttemptSequenceRequest | null | undefined, + {} | null | undefined + >, + ): void; attemptSequence( - request: protos.google.showcase.v1beta1.IAttemptSequenceRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IAttemptSequenceRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IAttemptSequenceRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IAttemptSequenceRequest | null | undefined, + {} | null | undefined + >, + ): void; attemptSequence( - request?: protos.google.showcase.v1beta1.IAttemptSequenceRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IAttemptSequenceRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.showcase.v1beta1.IAttemptSequenceRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IAttemptSequenceRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IAttemptSequenceRequest|undefined, {}|undefined - ]>|void { + | protos.google.showcase.v1beta1.IAttemptSequenceRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IAttemptSequenceRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IAttemptSequenceRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('attemptSequence request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IAttemptSequenceRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.showcase.v1beta1.IAttemptSequenceRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('attemptSequence response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.attemptSequence(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IAttemptSequenceRequest|undefined, - {}|undefined - ]) => { - this._log.info('attemptSequence response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .attemptSequence(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IAttemptSequenceRequest | undefined, + {} | undefined, + ]) => { + this._log.info('attemptSequence response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); @@ -641,7 +794,7 @@ export class SequenceServiceClient { * @param {string} blueprint * @returns {string} Resource name string. */ - blueprintPath(session:string,test:string,blueprint:string) { + blueprintPath(session: string, test: string, blueprint: string) { return this.pathTemplates.blueprintPathTemplate.render({ session: session, test: test, @@ -657,7 +810,8 @@ export class SequenceServiceClient { * @returns {string} A string representing the session. */ matchSessionFromBlueprintName(blueprintName: string) { - return this.pathTemplates.blueprintPathTemplate.match(blueprintName).session; + return this.pathTemplates.blueprintPathTemplate.match(blueprintName) + .session; } /** @@ -679,7 +833,8 @@ export class SequenceServiceClient { * @returns {string} A string representing the blueprint. */ matchBlueprintFromBlueprintName(blueprintName: string) { - return this.pathTemplates.blueprintPathTemplate.match(blueprintName).blueprint; + return this.pathTemplates.blueprintPathTemplate.match(blueprintName) + .blueprint; } /** @@ -688,7 +843,7 @@ export class SequenceServiceClient { * @param {string} room * @returns {string} Resource name string. */ - roomPath(room:string) { + roomPath(room: string) { return this.pathTemplates.roomPathTemplate.render({ room: room, }); @@ -712,7 +867,7 @@ export class SequenceServiceClient { * @param {string} blurb * @returns {string} Resource name string. */ - roomBlurbPath(room:string,blurb:string) { + roomBlurbPath(room: string, blurb: string) { return this.pathTemplates.roomBlurbPathTemplate.render({ room: room, blurb: blurb, @@ -749,7 +904,11 @@ export class SequenceServiceClient { * @param {string} blurb * @returns {string} Resource name string. */ - roomBlurbsLegacyRoomBlurbPath(room:string,legacyRoom:string,blurb:string) { + roomBlurbsLegacyRoomBlurbPath( + room: string, + legacyRoom: string, + blurb: string, + ) { return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.render({ room: room, legacy_room: legacyRoom, @@ -764,8 +923,12 @@ export class SequenceServiceClient { * A fully-qualified path representing room_blurbs_legacy_room_blurb resource. * @returns {string} A string representing the room. */ - matchRoomFromRoomBlurbsLegacyRoomBlurbName(roomBlurbsLegacyRoomBlurbName: string) { - return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match(roomBlurbsLegacyRoomBlurbName).room; + matchRoomFromRoomBlurbsLegacyRoomBlurbName( + roomBlurbsLegacyRoomBlurbName: string, + ) { + return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match( + roomBlurbsLegacyRoomBlurbName, + ).room; } /** @@ -775,8 +938,12 @@ export class SequenceServiceClient { * A fully-qualified path representing room_blurbs_legacy_room_blurb resource. * @returns {string} A string representing the legacy_room. */ - matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName(roomBlurbsLegacyRoomBlurbName: string) { - return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match(roomBlurbsLegacyRoomBlurbName).legacy_room; + matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName( + roomBlurbsLegacyRoomBlurbName: string, + ) { + return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match( + roomBlurbsLegacyRoomBlurbName, + ).legacy_room; } /** @@ -786,8 +953,12 @@ export class SequenceServiceClient { * A fully-qualified path representing room_blurbs_legacy_room_blurb resource. * @returns {string} A string representing the blurb. */ - matchBlurbFromRoomBlurbsLegacyRoomBlurbName(roomBlurbsLegacyRoomBlurbName: string) { - return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match(roomBlurbsLegacyRoomBlurbName).blurb; + matchBlurbFromRoomBlurbsLegacyRoomBlurbName( + roomBlurbsLegacyRoomBlurbName: string, + ) { + return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match( + roomBlurbsLegacyRoomBlurbName, + ).blurb; } /** @@ -796,7 +967,7 @@ export class SequenceServiceClient { * @param {string} sequence * @returns {string} Resource name string. */ - sequencePath(sequence:string) { + sequencePath(sequence: string) { return this.pathTemplates.sequencePathTemplate.render({ sequence: sequence, }); @@ -819,7 +990,7 @@ export class SequenceServiceClient { * @param {string} sequence * @returns {string} Resource name string. */ - sequenceReportPath(sequence:string) { + sequenceReportPath(sequence: string) { return this.pathTemplates.sequenceReportPathTemplate.render({ sequence: sequence, }); @@ -833,7 +1004,9 @@ export class SequenceServiceClient { * @returns {string} A string representing the sequence. */ matchSequenceFromSequenceReportName(sequenceReportName: string) { - return this.pathTemplates.sequenceReportPathTemplate.match(sequenceReportName).sequence; + return this.pathTemplates.sequenceReportPathTemplate.match( + sequenceReportName, + ).sequence; } /** @@ -842,7 +1015,7 @@ export class SequenceServiceClient { * @param {string} session * @returns {string} Resource name string. */ - sessionPath(session:string) { + sessionPath(session: string) { return this.pathTemplates.sessionPathTemplate.render({ session: session, }); @@ -866,7 +1039,7 @@ export class SequenceServiceClient { * @param {string} test * @returns {string} Resource name string. */ - testPath(session:string,test:string) { + testPath(session: string, test: string) { return this.pathTemplates.testPathTemplate.render({ session: session, test: test, @@ -901,7 +1074,7 @@ export class SequenceServiceClient { * @param {string} user * @returns {string} Resource name string. */ - userPath(user:string) { + userPath(user: string) { return this.pathTemplates.userPathTemplate.render({ user: user, }); @@ -925,7 +1098,7 @@ export class SequenceServiceClient { * @param {string} blurb * @returns {string} Resource name string. */ - userProfileBlurbPath(user:string,blurb:string) { + userProfileBlurbPath(user: string, blurb: string) { return this.pathTemplates.userProfileBlurbPathTemplate.render({ user: user, blurb: blurb, @@ -940,7 +1113,9 @@ export class SequenceServiceClient { * @returns {string} A string representing the user. */ matchUserFromUserProfileBlurbName(userProfileBlurbName: string) { - return this.pathTemplates.userProfileBlurbPathTemplate.match(userProfileBlurbName).user; + return this.pathTemplates.userProfileBlurbPathTemplate.match( + userProfileBlurbName, + ).user; } /** @@ -951,7 +1126,9 @@ export class SequenceServiceClient { * @returns {string} A string representing the blurb. */ matchBlurbFromUserProfileBlurbName(userProfileBlurbName: string) { - return this.pathTemplates.userProfileBlurbPathTemplate.match(userProfileBlurbName).blurb; + return this.pathTemplates.userProfileBlurbPathTemplate.match( + userProfileBlurbName, + ).blurb; } /** @@ -962,12 +1139,18 @@ export class SequenceServiceClient { * @param {string} blurb * @returns {string} Resource name string. */ - userProfileBlurbsLegacyUserBlurbPath(user:string,legacyUser:string,blurb:string) { - return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.render({ - user: user, - legacy_user: legacyUser, - blurb: blurb, - }); + userProfileBlurbsLegacyUserBlurbPath( + user: string, + legacyUser: string, + blurb: string, + ) { + return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.render( + { + user: user, + legacy_user: legacyUser, + blurb: blurb, + }, + ); } /** @@ -977,8 +1160,12 @@ export class SequenceServiceClient { * A fully-qualified path representing user_profile_blurbs_legacy_user_blurb resource. * @returns {string} A string representing the user. */ - matchUserFromUserProfileBlurbsLegacyUserBlurbName(userProfileBlurbsLegacyUserBlurbName: string) { - return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match(userProfileBlurbsLegacyUserBlurbName).user; + matchUserFromUserProfileBlurbsLegacyUserBlurbName( + userProfileBlurbsLegacyUserBlurbName: string, + ) { + return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match( + userProfileBlurbsLegacyUserBlurbName, + ).user; } /** @@ -988,8 +1175,12 @@ export class SequenceServiceClient { * A fully-qualified path representing user_profile_blurbs_legacy_user_blurb resource. * @returns {string} A string representing the legacy_user. */ - matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName(userProfileBlurbsLegacyUserBlurbName: string) { - return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match(userProfileBlurbsLegacyUserBlurbName).legacy_user; + matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName( + userProfileBlurbsLegacyUserBlurbName: string, + ) { + return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match( + userProfileBlurbsLegacyUserBlurbName, + ).legacy_user; } /** @@ -999,8 +1190,12 @@ export class SequenceServiceClient { * A fully-qualified path representing user_profile_blurbs_legacy_user_blurb resource. * @returns {string} A string representing the blurb. */ - matchBlurbFromUserProfileBlurbsLegacyUserBlurbName(userProfileBlurbsLegacyUserBlurbName: string) { - return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match(userProfileBlurbsLegacyUserBlurbName).blurb; + matchBlurbFromUserProfileBlurbsLegacyUserBlurbName( + userProfileBlurbsLegacyUserBlurbName: string, + ) { + return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match( + userProfileBlurbsLegacyUserBlurbName, + ).blurb; } /** @@ -1011,7 +1206,7 @@ export class SequenceServiceClient { */ close(): Promise { if (this.sequenceServiceStub && !this._terminated) { - return this.sequenceServiceStub.then(stub => { + return this.sequenceServiceStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -1019,4 +1214,4 @@ export class SequenceServiceClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/core/generator/gapic-generator-typescript/baselines/showcase/src/v1beta1/testing_client.ts.baseline b/core/generator/gapic-generator-typescript/baselines/showcase/src/v1beta1/testing_client.ts.baseline index a9bdd67780df..cc858d7f0adf 100644 --- a/core/generator/gapic-generator-typescript/baselines/showcase/src/v1beta1/testing_client.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/showcase/src/v1beta1/testing_client.ts.baseline @@ -18,11 +18,18 @@ /* global window */ import type * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions, PaginationCallback, GaxCall} from 'google-gax'; -import {Transform} from 'stream'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + PaginationCallback, + GaxCall, +} from 'google-gax'; +import { Transform } from 'stream'; import * as protos from '../../protos/protos'; import jsonProtos = require('../../protos/protos.json'); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; /** * Client JSON configuration object, loaded from @@ -45,7 +52,7 @@ export class TestingClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('showcase'); @@ -58,9 +65,9 @@ export class TestingClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; - testingStub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; + testingStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of TestingClient. @@ -101,21 +108,42 @@ export class TestingClient { * const client = new TestingClient({fallback: true}, gax); * ``` */ - constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { // Ensure that options include all the required fields. const staticMembers = this.constructor as typeof TestingClient; - if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { - throw new Error('Please set either universe_domain or universeDomain, but not both.'); + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); } - const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; - this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; this._servicePath = 'localhost'; - const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; - const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // Request numeric enum values if REST transport is used. opts.numericEnums = true; @@ -140,7 +168,7 @@ export class TestingClient { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; @@ -154,10 +182,7 @@ export class TestingClient { } // Determine the client header string. - const clientHeader = [ - `gax/${this._gaxModule.version}`, - `gapic/${version}`, - ]; + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/${process.versions.node}`); } else { @@ -179,54 +204,60 @@ export class TestingClient { // Create useful helper objects for these. this.pathTemplates = { blueprintPathTemplate: new this._gaxModule.PathTemplate( - 'sessions/{session}/tests/{test}/blueprints/{blueprint}' - ), - roomPathTemplate: new this._gaxModule.PathTemplate( - 'rooms/{room}' + 'sessions/{session}/tests/{test}/blueprints/{blueprint}', ), + roomPathTemplate: new this._gaxModule.PathTemplate('rooms/{room}'), roomBlurbPathTemplate: new this._gaxModule.PathTemplate( - 'rooms/{room}/blurbs/{blurb}' + 'rooms/{room}/blurbs/{blurb}', ), roomBlurbsLegacyRoomBlurbPathTemplate: new this._gaxModule.PathTemplate( - 'rooms/{room}/blurbs/legacy/{legacy_room}.{blurb}' + 'rooms/{room}/blurbs/legacy/{legacy_room}.{blurb}', ), sequencePathTemplate: new this._gaxModule.PathTemplate( - 'sequences/{sequence}' + 'sequences/{sequence}', ), sequenceReportPathTemplate: new this._gaxModule.PathTemplate( - 'sequences/{sequence}/sequenceReport' + 'sequences/{sequence}/sequenceReport', ), sessionPathTemplate: new this._gaxModule.PathTemplate( - 'sessions/{session}' + 'sessions/{session}', ), testPathTemplate: new this._gaxModule.PathTemplate( - 'sessions/{session}/tests/{test}' - ), - userPathTemplate: new this._gaxModule.PathTemplate( - 'users/{user}' + 'sessions/{session}/tests/{test}', ), + userPathTemplate: new this._gaxModule.PathTemplate('users/{user}'), userProfileBlurbPathTemplate: new this._gaxModule.PathTemplate( - 'users/{user}/profile/blurbs/{blurb}' - ), - userProfileBlurbsLegacyUserBlurbPathTemplate: new this._gaxModule.PathTemplate( - 'users/{user}/profile/blurbs/legacy/{legacy_user}~{blurb}' + 'users/{user}/profile/blurbs/{blurb}', ), + userProfileBlurbsLegacyUserBlurbPathTemplate: + new this._gaxModule.PathTemplate( + 'users/{user}/profile/blurbs/legacy/{legacy_user}~{blurb}', + ), }; // Some of the methods on this service return "paged" results, // (e.g. 50 results at a time, with tokens to get subsequent // pages). Denote the keys used for pagination and results. this.descriptors.page = { - listSessions: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'sessions'), - listTests: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'tests') + listSessions: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'sessions', + ), + listTests: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'tests', + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.showcase.v1beta1.Testing', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.showcase.v1beta1.Testing', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + { 'x-goog-api-client': clientHeader.join(' ') }, + ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -257,37 +288,49 @@ export class TestingClient { // Put together the "service stub" for // google.showcase.v1beta1.Testing. this.testingStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.showcase.v1beta1.Testing') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.showcase.v1beta1.Testing', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.showcase.v1beta1.Testing, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts, + this._providedCustomServicePath, + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const testingStubMethods = - ['createSession', 'getSession', 'listSessions', 'deleteSession', 'reportSession', 'listTests', 'deleteTest', 'verifyTest']; + const testingStubMethods = [ + 'createSession', + 'getSession', + 'listSessions', + 'deleteSession', + 'reportSession', + 'listTests', + 'deleteTest', + 'verifyTest', + ]; for (const methodName of testingStubMethods) { const callPromise = this.testingStub.then( - stub => (...args: Array<{}>) => { - if (this._terminated) { - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error|null|undefined) => () => { + (stub) => + (...args: Array<{}>) => { + if (this._terminated) { + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { throw err; - }); + }, + ); - const descriptor = - this.descriptors.page[methodName] || - undefined; + const descriptor = this.descriptors.page[methodName] || undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -302,8 +345,14 @@ export class TestingClient { * @returns {string} The DNS address for this service. */ static get servicePath() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'localhost'; } @@ -314,8 +363,14 @@ export class TestingClient { * @returns {string} The DNS address for this service. */ static get apiEndpoint() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'localhost'; } @@ -355,8 +410,9 @@ export class TestingClient { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId(callback?: Callback): - Promise|void { + getProjectId( + callback?: Callback, + ): Promise | void { if (callback) { this.auth.getProjectId(callback); return; @@ -367,656 +423,869 @@ export class TestingClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Creates a new testing session. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.showcase.v1beta1.Session} request.session - * The session to be created. - * Sessions are immutable once they are created (although they can - * be deleted). - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.Session|Session}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/testing.create_session.js - * region_tag:localhost_v1beta1_generated_Testing_CreateSession_async - */ + /** + * Creates a new testing session. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.showcase.v1beta1.Session} request.session + * The session to be created. + * Sessions are immutable once they are created (although they can + * be deleted). + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.Session|Session}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/testing.create_session.js + * region_tag:localhost_v1beta1_generated_Testing_CreateSession_async + */ createSession( - request?: protos.google.showcase.v1beta1.ICreateSessionRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.ISession, - protos.google.showcase.v1beta1.ICreateSessionRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.ICreateSessionRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.ISession, + protos.google.showcase.v1beta1.ICreateSessionRequest | undefined, + {} | undefined, + ] + >; createSession( - request: protos.google.showcase.v1beta1.ICreateSessionRequest, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.ISession, - protos.google.showcase.v1beta1.ICreateSessionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.ICreateSessionRequest, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.ISession, + protos.google.showcase.v1beta1.ICreateSessionRequest | null | undefined, + {} | null | undefined + >, + ): void; createSession( - request: protos.google.showcase.v1beta1.ICreateSessionRequest, - callback: Callback< - protos.google.showcase.v1beta1.ISession, - protos.google.showcase.v1beta1.ICreateSessionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.ICreateSessionRequest, + callback: Callback< + protos.google.showcase.v1beta1.ISession, + protos.google.showcase.v1beta1.ICreateSessionRequest | null | undefined, + {} | null | undefined + >, + ): void; createSession( - request?: protos.google.showcase.v1beta1.ICreateSessionRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.showcase.v1beta1.ISession, - protos.google.showcase.v1beta1.ICreateSessionRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.showcase.v1beta1.ICreateSessionRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.ISession, - protos.google.showcase.v1beta1.ICreateSessionRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.ISession, - protos.google.showcase.v1beta1.ICreateSessionRequest|undefined, {}|undefined - ]>|void { + | protos.google.showcase.v1beta1.ICreateSessionRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.ISession, + protos.google.showcase.v1beta1.ICreateSessionRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.ISession, + protos.google.showcase.v1beta1.ICreateSessionRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('createSession request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.ISession, - protos.google.showcase.v1beta1.ICreateSessionRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.ISession, + | protos.google.showcase.v1beta1.ICreateSessionRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createSession response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.createSession(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.ISession, - protos.google.showcase.v1beta1.ICreateSessionRequest|undefined, - {}|undefined - ]) => { - this._log.info('createSession response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createSession(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.ISession, + protos.google.showcase.v1beta1.ICreateSessionRequest | undefined, + {} | undefined, + ]) => { + this._log.info('createSession response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Gets a testing session. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * The session to be retrieved. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.Session|Session}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/testing.get_session.js - * region_tag:localhost_v1beta1_generated_Testing_GetSession_async - */ + /** + * Gets a testing session. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * The session to be retrieved. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.Session|Session}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/testing.get_session.js + * region_tag:localhost_v1beta1_generated_Testing_GetSession_async + */ getSession( - request?: protos.google.showcase.v1beta1.IGetSessionRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.ISession, - protos.google.showcase.v1beta1.IGetSessionRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IGetSessionRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.ISession, + protos.google.showcase.v1beta1.IGetSessionRequest | undefined, + {} | undefined, + ] + >; getSession( - request: protos.google.showcase.v1beta1.IGetSessionRequest, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.ISession, - protos.google.showcase.v1beta1.IGetSessionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IGetSessionRequest, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.ISession, + protos.google.showcase.v1beta1.IGetSessionRequest | null | undefined, + {} | null | undefined + >, + ): void; getSession( - request: protos.google.showcase.v1beta1.IGetSessionRequest, - callback: Callback< - protos.google.showcase.v1beta1.ISession, - protos.google.showcase.v1beta1.IGetSessionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IGetSessionRequest, + callback: Callback< + protos.google.showcase.v1beta1.ISession, + protos.google.showcase.v1beta1.IGetSessionRequest | null | undefined, + {} | null | undefined + >, + ): void; getSession( - request?: protos.google.showcase.v1beta1.IGetSessionRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.showcase.v1beta1.ISession, - protos.google.showcase.v1beta1.IGetSessionRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.showcase.v1beta1.IGetSessionRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.ISession, - protos.google.showcase.v1beta1.IGetSessionRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.ISession, - protos.google.showcase.v1beta1.IGetSessionRequest|undefined, {}|undefined - ]>|void { + protos.google.showcase.v1beta1.IGetSessionRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.ISession, + protos.google.showcase.v1beta1.IGetSessionRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.ISession, + protos.google.showcase.v1beta1.IGetSessionRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getSession request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.ISession, - protos.google.showcase.v1beta1.IGetSessionRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.ISession, + protos.google.showcase.v1beta1.IGetSessionRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getSession response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getSession(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.ISession, - protos.google.showcase.v1beta1.IGetSessionRequest|undefined, - {}|undefined - ]) => { - this._log.info('getSession response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getSession(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.ISession, + protos.google.showcase.v1beta1.IGetSessionRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getSession response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Delete a test session. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * The session to be deleted. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/testing.delete_session.js - * region_tag:localhost_v1beta1_generated_Testing_DeleteSession_async - */ + /** + * Delete a test session. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * The session to be deleted. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/testing.delete_session.js + * region_tag:localhost_v1beta1_generated_Testing_DeleteSession_async + */ deleteSession( - request?: protos.google.showcase.v1beta1.IDeleteSessionRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteSessionRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IDeleteSessionRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteSessionRequest | undefined, + {} | undefined, + ] + >; deleteSession( - request: protos.google.showcase.v1beta1.IDeleteSessionRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteSessionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IDeleteSessionRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteSessionRequest | null | undefined, + {} | null | undefined + >, + ): void; deleteSession( - request: protos.google.showcase.v1beta1.IDeleteSessionRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteSessionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IDeleteSessionRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteSessionRequest | null | undefined, + {} | null | undefined + >, + ): void; deleteSession( - request?: protos.google.showcase.v1beta1.IDeleteSessionRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.showcase.v1beta1.IDeleteSessionRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteSessionRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteSessionRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteSessionRequest|undefined, {}|undefined - ]>|void { + | protos.google.showcase.v1beta1.IDeleteSessionRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteSessionRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteSessionRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('deleteSession request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteSessionRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.showcase.v1beta1.IDeleteSessionRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteSession response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.deleteSession(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteSessionRequest|undefined, - {}|undefined - ]) => { - this._log.info('deleteSession response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteSession(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteSessionRequest | undefined, + {} | undefined, + ]) => { + this._log.info('deleteSession response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Report on the status of a session. - * This generates a report detailing which tests have been completed, - * and an overall rollup. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * The session to be reported on. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.ReportSessionResponse|ReportSessionResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/testing.report_session.js - * region_tag:localhost_v1beta1_generated_Testing_ReportSession_async - */ + /** + * Report on the status of a session. + * This generates a report detailing which tests have been completed, + * and an overall rollup. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * The session to be reported on. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.ReportSessionResponse|ReportSessionResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/testing.report_session.js + * region_tag:localhost_v1beta1_generated_Testing_ReportSession_async + */ reportSession( - request?: protos.google.showcase.v1beta1.IReportSessionRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IReportSessionResponse, - protos.google.showcase.v1beta1.IReportSessionRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IReportSessionRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IReportSessionResponse, + protos.google.showcase.v1beta1.IReportSessionRequest | undefined, + {} | undefined, + ] + >; reportSession( - request: protos.google.showcase.v1beta1.IReportSessionRequest, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.IReportSessionResponse, - protos.google.showcase.v1beta1.IReportSessionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IReportSessionRequest, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.IReportSessionResponse, + protos.google.showcase.v1beta1.IReportSessionRequest | null | undefined, + {} | null | undefined + >, + ): void; reportSession( - request: protos.google.showcase.v1beta1.IReportSessionRequest, - callback: Callback< - protos.google.showcase.v1beta1.IReportSessionResponse, - protos.google.showcase.v1beta1.IReportSessionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IReportSessionRequest, + callback: Callback< + protos.google.showcase.v1beta1.IReportSessionResponse, + protos.google.showcase.v1beta1.IReportSessionRequest | null | undefined, + {} | null | undefined + >, + ): void; reportSession( - request?: protos.google.showcase.v1beta1.IReportSessionRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.showcase.v1beta1.IReportSessionResponse, - protos.google.showcase.v1beta1.IReportSessionRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.showcase.v1beta1.IReportSessionRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.IReportSessionResponse, - protos.google.showcase.v1beta1.IReportSessionRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.IReportSessionResponse, - protos.google.showcase.v1beta1.IReportSessionRequest|undefined, {}|undefined - ]>|void { + | protos.google.showcase.v1beta1.IReportSessionRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.IReportSessionResponse, + protos.google.showcase.v1beta1.IReportSessionRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IReportSessionResponse, + protos.google.showcase.v1beta1.IReportSessionRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('reportSession request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.IReportSessionResponse, - protos.google.showcase.v1beta1.IReportSessionRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.IReportSessionResponse, + | protos.google.showcase.v1beta1.IReportSessionRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('reportSession response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.reportSession(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.IReportSessionResponse, - protos.google.showcase.v1beta1.IReportSessionRequest|undefined, - {}|undefined - ]) => { - this._log.info('reportSession response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .reportSession(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.IReportSessionResponse, + protos.google.showcase.v1beta1.IReportSessionRequest | undefined, + {} | undefined, + ]) => { + this._log.info('reportSession response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Explicitly decline to implement a test. - * - * This removes the test from subsequent `ListTests` calls, and - * attempting to do the test will error. - * - * This method will error if attempting to delete a required test. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * The test to be deleted. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/testing.delete_test.js - * region_tag:localhost_v1beta1_generated_Testing_DeleteTest_async - */ + /** + * Explicitly decline to implement a test. + * + * This removes the test from subsequent `ListTests` calls, and + * attempting to do the test will error. + * + * This method will error if attempting to delete a required test. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * The test to be deleted. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/testing.delete_test.js + * region_tag:localhost_v1beta1_generated_Testing_DeleteTest_async + */ deleteTest( - request?: protos.google.showcase.v1beta1.IDeleteTestRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteTestRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IDeleteTestRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteTestRequest | undefined, + {} | undefined, + ] + >; deleteTest( - request: protos.google.showcase.v1beta1.IDeleteTestRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteTestRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IDeleteTestRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteTestRequest | null | undefined, + {} | null | undefined + >, + ): void; deleteTest( - request: protos.google.showcase.v1beta1.IDeleteTestRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteTestRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IDeleteTestRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteTestRequest | null | undefined, + {} | null | undefined + >, + ): void; deleteTest( - request?: protos.google.showcase.v1beta1.IDeleteTestRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.showcase.v1beta1.IDeleteTestRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteTestRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteTestRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteTestRequest|undefined, {}|undefined - ]>|void { + protos.google.showcase.v1beta1.IDeleteTestRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteTestRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteTestRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('deleteTest request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteTestRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteTestRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteTest response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.deleteTest(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.showcase.v1beta1.IDeleteTestRequest|undefined, - {}|undefined - ]) => { - this._log.info('deleteTest response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteTest(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.showcase.v1beta1.IDeleteTestRequest | undefined, + {} | undefined, + ]) => { + this._log.info('deleteTest response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Register a response to a test. - * - * In cases where a test involves registering a final answer at the - * end of the test, this method provides the means to do so. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * The test to have an answer registered to it. - * @param {Buffer} request.answer - * The answer from the test. - * @param {Buffer[]} request.answers - * The answers from the test if multiple are to be checked - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.VerifyTestResponse|VerifyTestResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/testing.verify_test.js - * region_tag:localhost_v1beta1_generated_Testing_VerifyTest_async - */ + /** + * Register a response to a test. + * + * In cases where a test involves registering a final answer at the + * end of the test, this method provides the means to do so. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * The test to have an answer registered to it. + * @param {Buffer} request.answer + * The answer from the test. + * @param {Buffer[]} request.answers + * The answers from the test if multiple are to be checked + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.showcase.v1beta1.VerifyTestResponse|VerifyTestResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/testing.verify_test.js + * region_tag:localhost_v1beta1_generated_Testing_VerifyTest_async + */ verifyTest( - request?: protos.google.showcase.v1beta1.IVerifyTestRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.IVerifyTestResponse, - protos.google.showcase.v1beta1.IVerifyTestRequest|undefined, {}|undefined - ]>; + request?: protos.google.showcase.v1beta1.IVerifyTestRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.IVerifyTestResponse, + protos.google.showcase.v1beta1.IVerifyTestRequest | undefined, + {} | undefined, + ] + >; verifyTest( - request: protos.google.showcase.v1beta1.IVerifyTestRequest, - options: CallOptions, - callback: Callback< - protos.google.showcase.v1beta1.IVerifyTestResponse, - protos.google.showcase.v1beta1.IVerifyTestRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IVerifyTestRequest, + options: CallOptions, + callback: Callback< + protos.google.showcase.v1beta1.IVerifyTestResponse, + protos.google.showcase.v1beta1.IVerifyTestRequest | null | undefined, + {} | null | undefined + >, + ): void; verifyTest( - request: protos.google.showcase.v1beta1.IVerifyTestRequest, - callback: Callback< - protos.google.showcase.v1beta1.IVerifyTestResponse, - protos.google.showcase.v1beta1.IVerifyTestRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.showcase.v1beta1.IVerifyTestRequest, + callback: Callback< + protos.google.showcase.v1beta1.IVerifyTestResponse, + protos.google.showcase.v1beta1.IVerifyTestRequest | null | undefined, + {} | null | undefined + >, + ): void; verifyTest( - request?: protos.google.showcase.v1beta1.IVerifyTestRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.showcase.v1beta1.IVerifyTestRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.showcase.v1beta1.IVerifyTestResponse, - protos.google.showcase.v1beta1.IVerifyTestRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.showcase.v1beta1.IVerifyTestResponse, - protos.google.showcase.v1beta1.IVerifyTestRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.showcase.v1beta1.IVerifyTestResponse, - protos.google.showcase.v1beta1.IVerifyTestRequest|undefined, {}|undefined - ]>|void { + protos.google.showcase.v1beta1.IVerifyTestRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.showcase.v1beta1.IVerifyTestResponse, + protos.google.showcase.v1beta1.IVerifyTestRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.showcase.v1beta1.IVerifyTestResponse, + protos.google.showcase.v1beta1.IVerifyTestRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('verifyTest request %j', request); - const wrappedCallback: Callback< - protos.google.showcase.v1beta1.IVerifyTestResponse, - protos.google.showcase.v1beta1.IVerifyTestRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.showcase.v1beta1.IVerifyTestResponse, + protos.google.showcase.v1beta1.IVerifyTestRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('verifyTest response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.verifyTest(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.showcase.v1beta1.IVerifyTestResponse, - protos.google.showcase.v1beta1.IVerifyTestRequest|undefined, - {}|undefined - ]) => { - this._log.info('verifyTest response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .verifyTest(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.showcase.v1beta1.IVerifyTestResponse, + protos.google.showcase.v1beta1.IVerifyTestRequest | undefined, + {} | undefined, + ]) => { + this._log.info('verifyTest response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } - /** - * Lists the current test sessions. - * - * @param {Object} request - * The request object that will be sent. - * @param {number} request.pageSize - * The maximum number of sessions to return per page. - * @param {string} request.pageToken - * The page token, for retrieving subsequent pages. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.showcase.v1beta1.Session|Session}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `listSessionsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Lists the current test sessions. + * + * @param {Object} request + * The request object that will be sent. + * @param {number} request.pageSize + * The maximum number of sessions to return per page. + * @param {string} request.pageToken + * The page token, for retrieving subsequent pages. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.showcase.v1beta1.Session|Session}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listSessionsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listSessions( - request?: protos.google.showcase.v1beta1.IListSessionsRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.ISession[], - protos.google.showcase.v1beta1.IListSessionsRequest|null, - protos.google.showcase.v1beta1.IListSessionsResponse - ]>; + request?: protos.google.showcase.v1beta1.IListSessionsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.ISession[], + protos.google.showcase.v1beta1.IListSessionsRequest | null, + protos.google.showcase.v1beta1.IListSessionsResponse, + ] + >; listSessions( - request: protos.google.showcase.v1beta1.IListSessionsRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.showcase.v1beta1.IListSessionsRequest, - protos.google.showcase.v1beta1.IListSessionsResponse|null|undefined, - protos.google.showcase.v1beta1.ISession>): void; + request: protos.google.showcase.v1beta1.IListSessionsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.showcase.v1beta1.IListSessionsRequest, + protos.google.showcase.v1beta1.IListSessionsResponse | null | undefined, + protos.google.showcase.v1beta1.ISession + >, + ): void; listSessions( - request: protos.google.showcase.v1beta1.IListSessionsRequest, - callback: PaginationCallback< - protos.google.showcase.v1beta1.IListSessionsRequest, - protos.google.showcase.v1beta1.IListSessionsResponse|null|undefined, - protos.google.showcase.v1beta1.ISession>): void; + request: protos.google.showcase.v1beta1.IListSessionsRequest, + callback: PaginationCallback< + protos.google.showcase.v1beta1.IListSessionsRequest, + protos.google.showcase.v1beta1.IListSessionsResponse | null | undefined, + protos.google.showcase.v1beta1.ISession + >, + ): void; listSessions( - request?: protos.google.showcase.v1beta1.IListSessionsRequest, - optionsOrCallback?: CallOptions|PaginationCallback< + request?: protos.google.showcase.v1beta1.IListSessionsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.showcase.v1beta1.IListSessionsRequest, - protos.google.showcase.v1beta1.IListSessionsResponse|null|undefined, - protos.google.showcase.v1beta1.ISession>, - callback?: PaginationCallback< - protos.google.showcase.v1beta1.IListSessionsRequest, - protos.google.showcase.v1beta1.IListSessionsResponse|null|undefined, - protos.google.showcase.v1beta1.ISession>): - Promise<[ - protos.google.showcase.v1beta1.ISession[], - protos.google.showcase.v1beta1.IListSessionsRequest|null, - protos.google.showcase.v1beta1.IListSessionsResponse - ]>|void { + | protos.google.showcase.v1beta1.IListSessionsResponse + | null + | undefined, + protos.google.showcase.v1beta1.ISession + >, + callback?: PaginationCallback< + protos.google.showcase.v1beta1.IListSessionsRequest, + protos.google.showcase.v1beta1.IListSessionsResponse | null | undefined, + protos.google.showcase.v1beta1.ISession + >, + ): Promise< + [ + protos.google.showcase.v1beta1.ISession[], + protos.google.showcase.v1beta1.IListSessionsRequest | null, + protos.google.showcase.v1beta1.IListSessionsResponse, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.showcase.v1beta1.IListSessionsRequest, - protos.google.showcase.v1beta1.IListSessionsResponse|null|undefined, - protos.google.showcase.v1beta1.ISession>|undefined = callback + this.initialize().catch((err) => { + throw err; + }); + const wrappedCallback: + | PaginationCallback< + protos.google.showcase.v1beta1.IListSessionsRequest, + | protos.google.showcase.v1beta1.IListSessionsResponse + | null + | undefined, + protos.google.showcase.v1beta1.ISession + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listSessions values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -1025,175 +1294,196 @@ export class TestingClient { this._log.info('listSessions request %j', request); return this.innerApiCalls .listSessions(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.showcase.v1beta1.ISession[], - protos.google.showcase.v1beta1.IListSessionsRequest|null, - protos.google.showcase.v1beta1.IListSessionsResponse - ]) => { - this._log.info('listSessions values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.showcase.v1beta1.ISession[], + protos.google.showcase.v1beta1.IListSessionsRequest | null, + protos.google.showcase.v1beta1.IListSessionsResponse, + ]) => { + this._log.info('listSessions values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listSessions`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {number} request.pageSize - * The maximum number of sessions to return per page. - * @param {string} request.pageToken - * The page token, for retrieving subsequent pages. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.showcase.v1beta1.Session|Session} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `listSessionsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `listSessions`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {number} request.pageSize + * The maximum number of sessions to return per page. + * @param {string} request.pageToken + * The page token, for retrieving subsequent pages. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.showcase.v1beta1.Session|Session} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listSessionsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listSessionsStream( - request?: protos.google.showcase.v1beta1.IListSessionsRequest, - options?: CallOptions): - Transform{ + request?: protos.google.showcase.v1beta1.IListSessionsRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; const defaultCallSettings = this._defaults['listSessions']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listSessions stream %j', request); return this.descriptors.page.listSessions.createStream( this.innerApiCalls.listSessions as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listSessions`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {number} request.pageSize - * The maximum number of sessions to return per page. - * @param {string} request.pageToken - * The page token, for retrieving subsequent pages. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.showcase.v1beta1.Session|Session}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/testing.list_sessions.js - * region_tag:localhost_v1beta1_generated_Testing_ListSessions_async - */ + /** + * Equivalent to `listSessions`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {number} request.pageSize + * The maximum number of sessions to return per page. + * @param {string} request.pageToken + * The page token, for retrieving subsequent pages. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.showcase.v1beta1.Session|Session}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/testing.list_sessions.js + * region_tag:localhost_v1beta1_generated_Testing_ListSessions_async + */ listSessionsAsync( - request?: protos.google.showcase.v1beta1.IListSessionsRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.showcase.v1beta1.IListSessionsRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; const defaultCallSettings = this._defaults['listSessions']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listSessions iterate %j', request); return this.descriptors.page.listSessions.asyncIterate( this.innerApiCalls['listSessions'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } - /** - * List the tests of a sessesion. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * The session. - * @param {number} request.pageSize - * The maximum number of tests to return per page. - * @param {string} request.pageToken - * The page token, for retrieving subsequent pages. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.showcase.v1beta1.Test|Test}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `listTestsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * List the tests of a sessesion. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * The session. + * @param {number} request.pageSize + * The maximum number of tests to return per page. + * @param {string} request.pageToken + * The page token, for retrieving subsequent pages. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.showcase.v1beta1.Test|Test}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listTestsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listTests( - request?: protos.google.showcase.v1beta1.IListTestsRequest, - options?: CallOptions): - Promise<[ - protos.google.showcase.v1beta1.ITest[], - protos.google.showcase.v1beta1.IListTestsRequest|null, - protos.google.showcase.v1beta1.IListTestsResponse - ]>; + request?: protos.google.showcase.v1beta1.IListTestsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.showcase.v1beta1.ITest[], + protos.google.showcase.v1beta1.IListTestsRequest | null, + protos.google.showcase.v1beta1.IListTestsResponse, + ] + >; listTests( - request: protos.google.showcase.v1beta1.IListTestsRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.showcase.v1beta1.IListTestsRequest, - protos.google.showcase.v1beta1.IListTestsResponse|null|undefined, - protos.google.showcase.v1beta1.ITest>): void; + request: protos.google.showcase.v1beta1.IListTestsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.showcase.v1beta1.IListTestsRequest, + protos.google.showcase.v1beta1.IListTestsResponse | null | undefined, + protos.google.showcase.v1beta1.ITest + >, + ): void; listTests( - request: protos.google.showcase.v1beta1.IListTestsRequest, - callback: PaginationCallback< - protos.google.showcase.v1beta1.IListTestsRequest, - protos.google.showcase.v1beta1.IListTestsResponse|null|undefined, - protos.google.showcase.v1beta1.ITest>): void; + request: protos.google.showcase.v1beta1.IListTestsRequest, + callback: PaginationCallback< + protos.google.showcase.v1beta1.IListTestsRequest, + protos.google.showcase.v1beta1.IListTestsResponse | null | undefined, + protos.google.showcase.v1beta1.ITest + >, + ): void; listTests( - request?: protos.google.showcase.v1beta1.IListTestsRequest, - optionsOrCallback?: CallOptions|PaginationCallback< - protos.google.showcase.v1beta1.IListTestsRequest, - protos.google.showcase.v1beta1.IListTestsResponse|null|undefined, - protos.google.showcase.v1beta1.ITest>, - callback?: PaginationCallback< + request?: protos.google.showcase.v1beta1.IListTestsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.showcase.v1beta1.IListTestsRequest, - protos.google.showcase.v1beta1.IListTestsResponse|null|undefined, - protos.google.showcase.v1beta1.ITest>): - Promise<[ - protos.google.showcase.v1beta1.ITest[], - protos.google.showcase.v1beta1.IListTestsRequest|null, - protos.google.showcase.v1beta1.IListTestsResponse - ]>|void { + protos.google.showcase.v1beta1.IListTestsResponse | null | undefined, + protos.google.showcase.v1beta1.ITest + >, + callback?: PaginationCallback< + protos.google.showcase.v1beta1.IListTestsRequest, + protos.google.showcase.v1beta1.IListTestsResponse | null | undefined, + protos.google.showcase.v1beta1.ITest + >, + ): Promise< + [ + protos.google.showcase.v1beta1.ITest[], + protos.google.showcase.v1beta1.IListTestsRequest | null, + protos.google.showcase.v1beta1.IListTestsResponse, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.showcase.v1beta1.IListTestsRequest, - protos.google.showcase.v1beta1.IListTestsResponse|null|undefined, - protos.google.showcase.v1beta1.ITest>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.showcase.v1beta1.IListTestsRequest, + protos.google.showcase.v1beta1.IListTestsResponse | null | undefined, + protos.google.showcase.v1beta1.ITest + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listTests values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -1202,106 +1492,110 @@ export class TestingClient { this._log.info('listTests request %j', request); return this.innerApiCalls .listTests(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.showcase.v1beta1.ITest[], - protos.google.showcase.v1beta1.IListTestsRequest|null, - protos.google.showcase.v1beta1.IListTestsResponse - ]) => { - this._log.info('listTests values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.showcase.v1beta1.ITest[], + protos.google.showcase.v1beta1.IListTestsRequest | null, + protos.google.showcase.v1beta1.IListTestsResponse, + ]) => { + this._log.info('listTests values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listTests`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * The session. - * @param {number} request.pageSize - * The maximum number of tests to return per page. - * @param {string} request.pageToken - * The page token, for retrieving subsequent pages. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.showcase.v1beta1.Test|Test} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `listTestsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `listTests`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * The session. + * @param {number} request.pageSize + * The maximum number of tests to return per page. + * @param {string} request.pageToken + * The page token, for retrieving subsequent pages. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.showcase.v1beta1.Test|Test} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listTestsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listTestsStream( - request?: protos.google.showcase.v1beta1.IListTestsRequest, - options?: CallOptions): - Transform{ + request?: protos.google.showcase.v1beta1.IListTestsRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); const defaultCallSettings = this._defaults['listTests']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listTests stream %j', request); return this.descriptors.page.listTests.createStream( this.innerApiCalls.listTests as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listTests`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * The session. - * @param {number} request.pageSize - * The maximum number of tests to return per page. - * @param {string} request.pageToken - * The page token, for retrieving subsequent pages. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.showcase.v1beta1.Test|Test}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v1beta1/testing.list_tests.js - * region_tag:localhost_v1beta1_generated_Testing_ListTests_async - */ + /** + * Equivalent to `listTests`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * The session. + * @param {number} request.pageSize + * The maximum number of tests to return per page. + * @param {string} request.pageToken + * The page token, for retrieving subsequent pages. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.showcase.v1beta1.Test|Test}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v1beta1/testing.list_tests.js + * region_tag:localhost_v1beta1_generated_Testing_ListTests_async + */ listTestsAsync( - request?: protos.google.showcase.v1beta1.IListTestsRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.showcase.v1beta1.IListTestsRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); const defaultCallSettings = this._defaults['listTests']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listTests iterate %j', request); return this.descriptors.page.listTests.asyncIterate( this.innerApiCalls['listTests'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } // -------------------- @@ -1316,7 +1610,7 @@ export class TestingClient { * @param {string} blueprint * @returns {string} Resource name string. */ - blueprintPath(session:string,test:string,blueprint:string) { + blueprintPath(session: string, test: string, blueprint: string) { return this.pathTemplates.blueprintPathTemplate.render({ session: session, test: test, @@ -1332,7 +1626,8 @@ export class TestingClient { * @returns {string} A string representing the session. */ matchSessionFromBlueprintName(blueprintName: string) { - return this.pathTemplates.blueprintPathTemplate.match(blueprintName).session; + return this.pathTemplates.blueprintPathTemplate.match(blueprintName) + .session; } /** @@ -1354,7 +1649,8 @@ export class TestingClient { * @returns {string} A string representing the blueprint. */ matchBlueprintFromBlueprintName(blueprintName: string) { - return this.pathTemplates.blueprintPathTemplate.match(blueprintName).blueprint; + return this.pathTemplates.blueprintPathTemplate.match(blueprintName) + .blueprint; } /** @@ -1363,7 +1659,7 @@ export class TestingClient { * @param {string} room * @returns {string} Resource name string. */ - roomPath(room:string) { + roomPath(room: string) { return this.pathTemplates.roomPathTemplate.render({ room: room, }); @@ -1387,7 +1683,7 @@ export class TestingClient { * @param {string} blurb * @returns {string} Resource name string. */ - roomBlurbPath(room:string,blurb:string) { + roomBlurbPath(room: string, blurb: string) { return this.pathTemplates.roomBlurbPathTemplate.render({ room: room, blurb: blurb, @@ -1424,7 +1720,11 @@ export class TestingClient { * @param {string} blurb * @returns {string} Resource name string. */ - roomBlurbsLegacyRoomBlurbPath(room:string,legacyRoom:string,blurb:string) { + roomBlurbsLegacyRoomBlurbPath( + room: string, + legacyRoom: string, + blurb: string, + ) { return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.render({ room: room, legacy_room: legacyRoom, @@ -1439,8 +1739,12 @@ export class TestingClient { * A fully-qualified path representing room_blurbs_legacy_room_blurb resource. * @returns {string} A string representing the room. */ - matchRoomFromRoomBlurbsLegacyRoomBlurbName(roomBlurbsLegacyRoomBlurbName: string) { - return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match(roomBlurbsLegacyRoomBlurbName).room; + matchRoomFromRoomBlurbsLegacyRoomBlurbName( + roomBlurbsLegacyRoomBlurbName: string, + ) { + return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match( + roomBlurbsLegacyRoomBlurbName, + ).room; } /** @@ -1450,8 +1754,12 @@ export class TestingClient { * A fully-qualified path representing room_blurbs_legacy_room_blurb resource. * @returns {string} A string representing the legacy_room. */ - matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName(roomBlurbsLegacyRoomBlurbName: string) { - return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match(roomBlurbsLegacyRoomBlurbName).legacy_room; + matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName( + roomBlurbsLegacyRoomBlurbName: string, + ) { + return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match( + roomBlurbsLegacyRoomBlurbName, + ).legacy_room; } /** @@ -1461,8 +1769,12 @@ export class TestingClient { * A fully-qualified path representing room_blurbs_legacy_room_blurb resource. * @returns {string} A string representing the blurb. */ - matchBlurbFromRoomBlurbsLegacyRoomBlurbName(roomBlurbsLegacyRoomBlurbName: string) { - return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match(roomBlurbsLegacyRoomBlurbName).blurb; + matchBlurbFromRoomBlurbsLegacyRoomBlurbName( + roomBlurbsLegacyRoomBlurbName: string, + ) { + return this.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match( + roomBlurbsLegacyRoomBlurbName, + ).blurb; } /** @@ -1471,7 +1783,7 @@ export class TestingClient { * @param {string} sequence * @returns {string} Resource name string. */ - sequencePath(sequence:string) { + sequencePath(sequence: string) { return this.pathTemplates.sequencePathTemplate.render({ sequence: sequence, }); @@ -1494,7 +1806,7 @@ export class TestingClient { * @param {string} sequence * @returns {string} Resource name string. */ - sequenceReportPath(sequence:string) { + sequenceReportPath(sequence: string) { return this.pathTemplates.sequenceReportPathTemplate.render({ sequence: sequence, }); @@ -1508,7 +1820,9 @@ export class TestingClient { * @returns {string} A string representing the sequence. */ matchSequenceFromSequenceReportName(sequenceReportName: string) { - return this.pathTemplates.sequenceReportPathTemplate.match(sequenceReportName).sequence; + return this.pathTemplates.sequenceReportPathTemplate.match( + sequenceReportName, + ).sequence; } /** @@ -1517,7 +1831,7 @@ export class TestingClient { * @param {string} session * @returns {string} Resource name string. */ - sessionPath(session:string) { + sessionPath(session: string) { return this.pathTemplates.sessionPathTemplate.render({ session: session, }); @@ -1541,7 +1855,7 @@ export class TestingClient { * @param {string} test * @returns {string} Resource name string. */ - testPath(session:string,test:string) { + testPath(session: string, test: string) { return this.pathTemplates.testPathTemplate.render({ session: session, test: test, @@ -1576,7 +1890,7 @@ export class TestingClient { * @param {string} user * @returns {string} Resource name string. */ - userPath(user:string) { + userPath(user: string) { return this.pathTemplates.userPathTemplate.render({ user: user, }); @@ -1600,7 +1914,7 @@ export class TestingClient { * @param {string} blurb * @returns {string} Resource name string. */ - userProfileBlurbPath(user:string,blurb:string) { + userProfileBlurbPath(user: string, blurb: string) { return this.pathTemplates.userProfileBlurbPathTemplate.render({ user: user, blurb: blurb, @@ -1615,7 +1929,9 @@ export class TestingClient { * @returns {string} A string representing the user. */ matchUserFromUserProfileBlurbName(userProfileBlurbName: string) { - return this.pathTemplates.userProfileBlurbPathTemplate.match(userProfileBlurbName).user; + return this.pathTemplates.userProfileBlurbPathTemplate.match( + userProfileBlurbName, + ).user; } /** @@ -1626,7 +1942,9 @@ export class TestingClient { * @returns {string} A string representing the blurb. */ matchBlurbFromUserProfileBlurbName(userProfileBlurbName: string) { - return this.pathTemplates.userProfileBlurbPathTemplate.match(userProfileBlurbName).blurb; + return this.pathTemplates.userProfileBlurbPathTemplate.match( + userProfileBlurbName, + ).blurb; } /** @@ -1637,12 +1955,18 @@ export class TestingClient { * @param {string} blurb * @returns {string} Resource name string. */ - userProfileBlurbsLegacyUserBlurbPath(user:string,legacyUser:string,blurb:string) { - return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.render({ - user: user, - legacy_user: legacyUser, - blurb: blurb, - }); + userProfileBlurbsLegacyUserBlurbPath( + user: string, + legacyUser: string, + blurb: string, + ) { + return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.render( + { + user: user, + legacy_user: legacyUser, + blurb: blurb, + }, + ); } /** @@ -1652,8 +1976,12 @@ export class TestingClient { * A fully-qualified path representing user_profile_blurbs_legacy_user_blurb resource. * @returns {string} A string representing the user. */ - matchUserFromUserProfileBlurbsLegacyUserBlurbName(userProfileBlurbsLegacyUserBlurbName: string) { - return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match(userProfileBlurbsLegacyUserBlurbName).user; + matchUserFromUserProfileBlurbsLegacyUserBlurbName( + userProfileBlurbsLegacyUserBlurbName: string, + ) { + return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match( + userProfileBlurbsLegacyUserBlurbName, + ).user; } /** @@ -1663,8 +1991,12 @@ export class TestingClient { * A fully-qualified path representing user_profile_blurbs_legacy_user_blurb resource. * @returns {string} A string representing the legacy_user. */ - matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName(userProfileBlurbsLegacyUserBlurbName: string) { - return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match(userProfileBlurbsLegacyUserBlurbName).legacy_user; + matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName( + userProfileBlurbsLegacyUserBlurbName: string, + ) { + return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match( + userProfileBlurbsLegacyUserBlurbName, + ).legacy_user; } /** @@ -1674,8 +2006,12 @@ export class TestingClient { * A fully-qualified path representing user_profile_blurbs_legacy_user_blurb resource. * @returns {string} A string representing the blurb. */ - matchBlurbFromUserProfileBlurbsLegacyUserBlurbName(userProfileBlurbsLegacyUserBlurbName: string) { - return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match(userProfileBlurbsLegacyUserBlurbName).blurb; + matchBlurbFromUserProfileBlurbsLegacyUserBlurbName( + userProfileBlurbsLegacyUserBlurbName: string, + ) { + return this.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match( + userProfileBlurbsLegacyUserBlurbName, + ).blurb; } /** @@ -1686,7 +2022,7 @@ export class TestingClient { */ close(): Promise { if (this.testingStub && !this._terminated) { - return this.testingStub.then(stub => { + return this.testingStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -1694,4 +2030,4 @@ export class TestingClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/core/generator/gapic-generator-typescript/baselines/showcase/system-test/fixtures/sample/src/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/showcase/system-test/fixtures/sample/src/index.ts.baseline index 889fe60d8ffc..6c964e873364 100644 --- a/core/generator/gapic-generator-typescript/baselines/showcase/system-test/fixtures/sample/src/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/showcase/system-test/fixtures/sample/src/index.ts.baseline @@ -16,7 +16,14 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -import {ComplianceClient, EchoClient, IdentityClient, MessagingClient, SequenceServiceClient, TestingClient} from 'showcase'; +import { + ComplianceClient, + EchoClient, + IdentityClient, + MessagingClient, + SequenceServiceClient, + TestingClient, +} from 'showcase'; // check that the client class type name can be used function doStuffWithComplianceClient(client: ComplianceClient) { diff --git a/core/generator/gapic-generator-typescript/baselines/showcase/system-test/install.ts.baseline b/core/generator/gapic-generator-typescript/baselines/showcase/system-test/install.ts.baseline index f66069aa3940..ccf167042d2e 100644 --- a/core/generator/gapic-generator-typescript/baselines/showcase/system-test/install.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/showcase/system-test/install.ts.baseline @@ -16,34 +16,36 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -import {packNTest} from 'pack-n-play'; -import {readFileSync} from 'fs'; -import {describe, it} from 'mocha'; +import { packNTest } from 'pack-n-play'; +import { readFileSync } from 'fs'; +import { describe, it } from 'mocha'; describe('📦 pack-n-play test', () => { - - it('TypeScript code', async function() { + it('TypeScript code', async function () { this.timeout(300000); const options = { packageDir: process.cwd(), sample: { description: 'TypeScript user can use the type definitions', - ts: readFileSync('./system-test/fixtures/sample/src/index.ts').toString() - } + ts: readFileSync( + './system-test/fixtures/sample/src/index.ts', + ).toString(), + }, }; await packNTest(options); }); - it('JavaScript code', async function() { + it('JavaScript code', async function () { this.timeout(300000); const options = { packageDir: process.cwd(), sample: { description: 'JavaScript user can use the library', - cjs: readFileSync('./system-test/fixtures/sample/src/index.js').toString() - } + cjs: readFileSync( + './system-test/fixtures/sample/src/index.js', + ).toString(), + }, }; await packNTest(options); }); - }); diff --git a/core/generator/gapic-generator-typescript/baselines/showcase/test/gapic_compliance_v1beta1.ts.baseline b/core/generator/gapic-generator-typescript/baselines/showcase/test/gapic_compliance_v1beta1.ts.baseline index 33c4db06519a..e70a93a0bc75 100644 --- a/core/generator/gapic-generator-typescript/baselines/showcase/test/gapic_compliance_v1beta1.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/showcase/test/gapic_compliance_v1beta1.ts.baseline @@ -19,1541 +19,1948 @@ import * as protos from '../protos/protos'; import * as assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as complianceModule from '../src'; -import {protobuf} from 'google-gax'; +import { protobuf } from 'google-gax'; // Dynamically loaded proto JSON is needed to get the type information // to fill in default values for request objects -const root = protobuf.Root.fromJSON(require('../protos/protos.json')).resolveAll(); +const root = protobuf.Root.fromJSON( + require('../protos/protos.json'), +).resolveAll(); // eslint-disable-next-line @typescript-eslint/no-unused-vars function getTypeDefaultValue(typeName: string, fields: string[]) { - let type = root.lookupType(typeName) as protobuf.Type; - for (const field of fields.slice(0, -1)) { - type = type.fields[field]?.resolvedType as protobuf.Type; - } - return type.fields[fields[fields.length - 1]]?.defaultValue; + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type.fields[field]?.resolvedType as protobuf.Type; + } + return type.fields[fields[fields.length - 1]]?.defaultValue; } function generateSampleMessage(instance: T) { - const filledObject = (instance.constructor as typeof protobuf.Message) - .toObject(instance as protobuf.Message, {defaults: true}); - return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, { defaults: true }); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; } function stubSimpleCall(response?: ResponseType, error?: Error) { - return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); } -function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { - return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +function stubSimpleCallWithCallback( + response?: ResponseType, + error?: Error, +) { + return error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); } describe('v1beta1.ComplianceClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new complianceModule.v1beta1.ComplianceClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'localhost'); - }); - - it('has universeDomain', () => { - const client = new complianceModule.v1beta1.ComplianceClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); - - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - it('throws DeprecationWarning if static servicePath is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const servicePath = complianceModule.v1beta1.ComplianceClient.servicePath; - assert.strictEqual(servicePath, 'localhost'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = complianceModule.v1beta1.ComplianceClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'localhost'); - assert(stub.called); - stub.restore(); - }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { new complianceModule.v1beta1.ComplianceClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); - - it('has port', () => { - const port = complianceModule.v1beta1.ComplianceClient.port; - assert(port); - assert(typeof port === 'number'); - }); - - it('should create a client with no option', () => { - const client = new complianceModule.v1beta1.ComplianceClient(); - assert(client); - }); - - it('should create a client with gRPC fallback', () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - fallback: true, - }); - assert(client); - }); - - it('has initialize method and supports deferred initialization', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.complianceStub, undefined); - await client.initialize(); - assert(client.complianceStub); - }); - - it('has close method for the initialized client', done => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.complianceStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); - - it('has close method for the non-initialized client', done => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.complianceStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); - - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); - }); - - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId((err?: Error|null, projectId?: string|null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } - }); - }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new complianceModule.v1beta1.ComplianceClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'localhost'); }); - describe('repeatDataBody', () => { - it('invokes repeatDataBody without error', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatResponse() - ); - client.innerApiCalls.repeatDataBody = stubSimpleCall(expectedResponse); - const [response] = await client.repeatDataBody(request); - assert.deepStrictEqual(response, expectedResponse); - }); - - it('invokes repeatDataBody without error using callback', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatResponse() - ); - client.innerApiCalls.repeatDataBody = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.repeatDataBody( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IRepeatResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); + it('has universeDomain', () => { + const client = new complianceModule.v1beta1.ComplianceClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - it('invokes repeatDataBody with error', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.repeatDataBody = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.repeatDataBody(request), expectedError); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = + complianceModule.v1beta1.ComplianceClient.servicePath; + assert.strictEqual(servicePath, 'localhost'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + complianceModule.v1beta1.ComplianceClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'localhost'); + assert(stub.called); + stub.restore(); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new complianceModule.v1beta1.ComplianceClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); + }); - it('invokes repeatDataBody with closed client', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.repeatDataBody(request), expectedError); - }); + it('has port', () => { + const port = complianceModule.v1beta1.ComplianceClient.port; + assert(port); + assert(typeof port === 'number'); }); - describe('repeatDataBodyInfo', () => { - it('invokes repeatDataBodyInfo without error', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatResponse() - ); - client.innerApiCalls.repeatDataBodyInfo = stubSimpleCall(expectedResponse); - const [response] = await client.repeatDataBodyInfo(request); - assert.deepStrictEqual(response, expectedResponse); - }); + it('should create a client with no option', () => { + const client = new complianceModule.v1beta1.ComplianceClient(); + assert(client); + }); - it('invokes repeatDataBodyInfo without error using callback', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatResponse() - ); - client.innerApiCalls.repeatDataBodyInfo = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.repeatDataBodyInfo( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IRepeatResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); + it('should create a client with gRPC fallback', () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + fallback: true, + }); + assert(client); + }); - it('invokes repeatDataBodyInfo with error', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.repeatDataBodyInfo = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.repeatDataBodyInfo(request), expectedError); - }); + it('has initialize method and supports deferred initialization', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.complianceStub, undefined); + await client.initialize(); + assert(client.complianceStub); + }); - it('invokes repeatDataBodyInfo with closed client', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.repeatDataBodyInfo(request), expectedError); + it('has close method for the initialized client', (done) => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.complianceStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); }); - describe('repeatDataQuery', () => { - it('invokes repeatDataQuery without error', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatResponse() - ); - client.innerApiCalls.repeatDataQuery = stubSimpleCall(expectedResponse); - const [response] = await client.repeatDataQuery(request); - assert.deepStrictEqual(response, expectedResponse); + it('has close method for the non-initialized client', (done) => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.complianceStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes repeatDataQuery without error using callback', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatResponse() - ); - client.innerApiCalls.repeatDataQuery = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.repeatDataQuery( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IRepeatResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + }); - it('invokes repeatDataQuery with error', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.repeatDataQuery = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.repeatDataQuery(request), expectedError); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + }); + + describe('repeatDataBody', () => { + it('invokes repeatDataBody without error', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatResponse(), + ); + client.innerApiCalls.repeatDataBody = stubSimpleCall(expectedResponse); + const [response] = await client.repeatDataBody(request); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes repeatDataQuery with closed client', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.repeatDataQuery(request), expectedError); - }); + it('invokes repeatDataBody without error using callback', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatResponse(), + ); + client.innerApiCalls.repeatDataBody = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.repeatDataBody( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IRepeatResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); }); - describe('repeatDataSimplePath', () => { - it('invokes repeatDataSimplePath without error', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - request.info ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fString']); - request.info.fString = defaultValue1; - request.info ??= {}; - const defaultValue2 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fInt32']); - request.info.fInt32 = defaultValue2; - request.info ??= {}; - const defaultValue3 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fDouble']); - request.info.fDouble = defaultValue3; - request.info ??= {}; - const defaultValue4 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fBool']); - request.info.fBool = defaultValue4; - request.info ??= {}; - const defaultValue5 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fKingdom']); - request.info.fKingdom = defaultValue5; - const expectedHeaderRequestParams = `info.f_string=${defaultValue1 ?? '' }&info.f_int32=${defaultValue2 ?? '' }&info.f_double=${defaultValue3 ?? '' }&info.f_bool=${defaultValue4 ?? '' }&info.f_kingdom=${defaultValue5 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatResponse() - ); - client.innerApiCalls.repeatDataSimplePath = stubSimpleCall(expectedResponse); - const [response] = await client.repeatDataSimplePath(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.repeatDataSimplePath as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.repeatDataSimplePath as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes repeatDataBody with error', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.repeatDataBody = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.repeatDataBody(request), expectedError); + }); - it('invokes repeatDataSimplePath without error using callback', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - request.info ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fString']); - request.info.fString = defaultValue1; - request.info ??= {}; - const defaultValue2 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fInt32']); - request.info.fInt32 = defaultValue2; - request.info ??= {}; - const defaultValue3 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fDouble']); - request.info.fDouble = defaultValue3; - request.info ??= {}; - const defaultValue4 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fBool']); - request.info.fBool = defaultValue4; - request.info ??= {}; - const defaultValue5 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fKingdom']); - request.info.fKingdom = defaultValue5; - const expectedHeaderRequestParams = `info.f_string=${defaultValue1 ?? '' }&info.f_int32=${defaultValue2 ?? '' }&info.f_double=${defaultValue3 ?? '' }&info.f_bool=${defaultValue4 ?? '' }&info.f_kingdom=${defaultValue5 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatResponse() - ); - client.innerApiCalls.repeatDataSimplePath = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.repeatDataSimplePath( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IRepeatResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.repeatDataSimplePath as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.repeatDataSimplePath as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes repeatDataBody with closed client', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.repeatDataBody(request), expectedError); + }); + }); + + describe('repeatDataBodyInfo', () => { + it('invokes repeatDataBodyInfo without error', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatResponse(), + ); + client.innerApiCalls.repeatDataBodyInfo = + stubSimpleCall(expectedResponse); + const [response] = await client.repeatDataBodyInfo(request); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes repeatDataSimplePath with error', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - request.info ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fString']); - request.info.fString = defaultValue1; - request.info ??= {}; - const defaultValue2 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fInt32']); - request.info.fInt32 = defaultValue2; - request.info ??= {}; - const defaultValue3 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fDouble']); - request.info.fDouble = defaultValue3; - request.info ??= {}; - const defaultValue4 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fBool']); - request.info.fBool = defaultValue4; - request.info ??= {}; - const defaultValue5 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fKingdom']); - request.info.fKingdom = defaultValue5; - const expectedHeaderRequestParams = `info.f_string=${defaultValue1 ?? '' }&info.f_int32=${defaultValue2 ?? '' }&info.f_double=${defaultValue3 ?? '' }&info.f_bool=${defaultValue4 ?? '' }&info.f_kingdom=${defaultValue5 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.repeatDataSimplePath = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.repeatDataSimplePath(request), expectedError); - const actualRequest = (client.innerApiCalls.repeatDataSimplePath as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.repeatDataSimplePath as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes repeatDataBodyInfo without error using callback', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatResponse(), + ); + client.innerApiCalls.repeatDataBodyInfo = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.repeatDataBodyInfo( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IRepeatResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes repeatDataSimplePath with closed client', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - request.info ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fString']); - request.info.fString = defaultValue1; - request.info ??= {}; - const defaultValue2 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fInt32']); - request.info.fInt32 = defaultValue2; - request.info ??= {}; - const defaultValue3 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fDouble']); - request.info.fDouble = defaultValue3; - request.info ??= {}; - const defaultValue4 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fBool']); - request.info.fBool = defaultValue4; - request.info ??= {}; - const defaultValue5 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fKingdom']); - request.info.fKingdom = defaultValue5; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.repeatDataSimplePath(request), expectedError); - }); + it('invokes repeatDataBodyInfo with error', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.repeatDataBodyInfo = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.repeatDataBodyInfo(request), expectedError); }); - describe('repeatDataPathResource', () => { - it('invokes repeatDataPathResource without error', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - request.info ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fString']); - request.info.fString = defaultValue1; - request.info ??= {}; - request.info.fChild ??= {}; - const defaultValue2 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fChild', 'fString']); - request.info.fChild.fString = defaultValue2; - request.info ??= {}; - const defaultValue3 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fBool']); - request.info.fBool = defaultValue3; - const expectedHeaderRequestParams = `info.f_string=${defaultValue1 ?? '' }&info.f_child.f_string=${defaultValue2 ?? '' }&info.f_bool=${defaultValue3 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatResponse() - ); - client.innerApiCalls.repeatDataPathResource = stubSimpleCall(expectedResponse); - const [response] = await client.repeatDataPathResource(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.repeatDataPathResource as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.repeatDataPathResource as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes repeatDataBodyInfo with closed client', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.repeatDataBodyInfo(request), expectedError); + }); + }); + + describe('repeatDataQuery', () => { + it('invokes repeatDataQuery without error', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatResponse(), + ); + client.innerApiCalls.repeatDataQuery = stubSimpleCall(expectedResponse); + const [response] = await client.repeatDataQuery(request); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes repeatDataPathResource without error using callback', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - request.info ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fString']); - request.info.fString = defaultValue1; - request.info ??= {}; - request.info.fChild ??= {}; - const defaultValue2 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fChild', 'fString']); - request.info.fChild.fString = defaultValue2; - request.info ??= {}; - const defaultValue3 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fBool']); - request.info.fBool = defaultValue3; - const expectedHeaderRequestParams = `info.f_string=${defaultValue1 ?? '' }&info.f_child.f_string=${defaultValue2 ?? '' }&info.f_bool=${defaultValue3 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatResponse() - ); - client.innerApiCalls.repeatDataPathResource = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.repeatDataPathResource( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IRepeatResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.repeatDataPathResource as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.repeatDataPathResource as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes repeatDataQuery without error using callback', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatResponse(), + ); + client.innerApiCalls.repeatDataQuery = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.repeatDataQuery( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IRepeatResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes repeatDataPathResource with error', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - request.info ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fString']); - request.info.fString = defaultValue1; - request.info ??= {}; - request.info.fChild ??= {}; - const defaultValue2 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fChild', 'fString']); - request.info.fChild.fString = defaultValue2; - request.info ??= {}; - const defaultValue3 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fBool']); - request.info.fBool = defaultValue3; - const expectedHeaderRequestParams = `info.f_string=${defaultValue1 ?? '' }&info.f_child.f_string=${defaultValue2 ?? '' }&info.f_bool=${defaultValue3 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.repeatDataPathResource = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.repeatDataPathResource(request), expectedError); - const actualRequest = (client.innerApiCalls.repeatDataPathResource as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.repeatDataPathResource as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes repeatDataQuery with error', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.repeatDataQuery = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.repeatDataQuery(request), expectedError); + }); - it('invokes repeatDataPathResource with closed client', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - request.info ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fString']); - request.info.fString = defaultValue1; - request.info ??= {}; - request.info.fChild ??= {}; - const defaultValue2 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fChild', 'fString']); - request.info.fChild.fString = defaultValue2; - request.info ??= {}; - const defaultValue3 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fBool']); - request.info.fBool = defaultValue3; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.repeatDataPathResource(request), expectedError); - }); + it('invokes repeatDataQuery with closed client', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.repeatDataQuery(request), expectedError); + }); + }); + + describe('repeatDataSimplePath', () => { + it('invokes repeatDataSimplePath without error', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + request.info ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fString'], + ); + request.info.fString = defaultValue1; + request.info ??= {}; + const defaultValue2 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fInt32'], + ); + request.info.fInt32 = defaultValue2; + request.info ??= {}; + const defaultValue3 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fDouble'], + ); + request.info.fDouble = defaultValue3; + request.info ??= {}; + const defaultValue4 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fBool'], + ); + request.info.fBool = defaultValue4; + request.info ??= {}; + const defaultValue5 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fKingdom'], + ); + request.info.fKingdom = defaultValue5; + const expectedHeaderRequestParams = `info.f_string=${defaultValue1 ?? ''}&info.f_int32=${defaultValue2 ?? ''}&info.f_double=${defaultValue3 ?? ''}&info.f_bool=${defaultValue4 ?? ''}&info.f_kingdom=${defaultValue5 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatResponse(), + ); + client.innerApiCalls.repeatDataSimplePath = + stubSimpleCall(expectedResponse); + const [response] = await client.repeatDataSimplePath(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.repeatDataSimplePath as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.repeatDataSimplePath as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('repeatDataPathTrailingResource', () => { - it('invokes repeatDataPathTrailingResource without error', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - request.info ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fString']); - request.info.fString = defaultValue1; - request.info ??= {}; - request.info.fChild ??= {}; - const defaultValue2 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fChild', 'fString']); - request.info.fChild.fString = defaultValue2; - const expectedHeaderRequestParams = `info.f_string=${defaultValue1 ?? '' }&info.f_child.f_string=${defaultValue2 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatResponse() - ); - client.innerApiCalls.repeatDataPathTrailingResource = stubSimpleCall(expectedResponse); - const [response] = await client.repeatDataPathTrailingResource(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.repeatDataPathTrailingResource as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.repeatDataPathTrailingResource as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes repeatDataSimplePath without error using callback', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + request.info ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fString'], + ); + request.info.fString = defaultValue1; + request.info ??= {}; + const defaultValue2 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fInt32'], + ); + request.info.fInt32 = defaultValue2; + request.info ??= {}; + const defaultValue3 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fDouble'], + ); + request.info.fDouble = defaultValue3; + request.info ??= {}; + const defaultValue4 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fBool'], + ); + request.info.fBool = defaultValue4; + request.info ??= {}; + const defaultValue5 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fKingdom'], + ); + request.info.fKingdom = defaultValue5; + const expectedHeaderRequestParams = `info.f_string=${defaultValue1 ?? ''}&info.f_int32=${defaultValue2 ?? ''}&info.f_double=${defaultValue3 ?? ''}&info.f_bool=${defaultValue4 ?? ''}&info.f_kingdom=${defaultValue5 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatResponse(), + ); + client.innerApiCalls.repeatDataSimplePath = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.repeatDataSimplePath( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IRepeatResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.repeatDataSimplePath as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.repeatDataSimplePath as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes repeatDataPathTrailingResource without error using callback', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - request.info ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fString']); - request.info.fString = defaultValue1; - request.info ??= {}; - request.info.fChild ??= {}; - const defaultValue2 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fChild', 'fString']); - request.info.fChild.fString = defaultValue2; - const expectedHeaderRequestParams = `info.f_string=${defaultValue1 ?? '' }&info.f_child.f_string=${defaultValue2 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatResponse() - ); - client.innerApiCalls.repeatDataPathTrailingResource = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.repeatDataPathTrailingResource( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IRepeatResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.repeatDataPathTrailingResource as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.repeatDataPathTrailingResource as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes repeatDataSimplePath with error', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + request.info ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fString'], + ); + request.info.fString = defaultValue1; + request.info ??= {}; + const defaultValue2 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fInt32'], + ); + request.info.fInt32 = defaultValue2; + request.info ??= {}; + const defaultValue3 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fDouble'], + ); + request.info.fDouble = defaultValue3; + request.info ??= {}; + const defaultValue4 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fBool'], + ); + request.info.fBool = defaultValue4; + request.info ??= {}; + const defaultValue5 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fKingdom'], + ); + request.info.fKingdom = defaultValue5; + const expectedHeaderRequestParams = `info.f_string=${defaultValue1 ?? ''}&info.f_int32=${defaultValue2 ?? ''}&info.f_double=${defaultValue3 ?? ''}&info.f_bool=${defaultValue4 ?? ''}&info.f_kingdom=${defaultValue5 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.repeatDataSimplePath = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.repeatDataSimplePath(request), expectedError); + const actualRequest = ( + client.innerApiCalls.repeatDataSimplePath as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.repeatDataSimplePath as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes repeatDataPathTrailingResource with error', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - request.info ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fString']); - request.info.fString = defaultValue1; - request.info ??= {}; - request.info.fChild ??= {}; - const defaultValue2 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fChild', 'fString']); - request.info.fChild.fString = defaultValue2; - const expectedHeaderRequestParams = `info.f_string=${defaultValue1 ?? '' }&info.f_child.f_string=${defaultValue2 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.repeatDataPathTrailingResource = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.repeatDataPathTrailingResource(request), expectedError); - const actualRequest = (client.innerApiCalls.repeatDataPathTrailingResource as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.repeatDataPathTrailingResource as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes repeatDataSimplePath with closed client', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + request.info ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fString'], + ); + request.info.fString = defaultValue1; + request.info ??= {}; + const defaultValue2 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fInt32'], + ); + request.info.fInt32 = defaultValue2; + request.info ??= {}; + const defaultValue3 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fDouble'], + ); + request.info.fDouble = defaultValue3; + request.info ??= {}; + const defaultValue4 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fBool'], + ); + request.info.fBool = defaultValue4; + request.info ??= {}; + const defaultValue5 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fKingdom'], + ); + request.info.fKingdom = defaultValue5; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.repeatDataSimplePath(request), expectedError); + }); + }); + + describe('repeatDataPathResource', () => { + it('invokes repeatDataPathResource without error', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + request.info ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fString'], + ); + request.info.fString = defaultValue1; + request.info ??= {}; + request.info.fChild ??= {}; + const defaultValue2 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fChild', 'fString'], + ); + request.info.fChild.fString = defaultValue2; + request.info ??= {}; + const defaultValue3 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fBool'], + ); + request.info.fBool = defaultValue3; + const expectedHeaderRequestParams = `info.f_string=${defaultValue1 ?? ''}&info.f_child.f_string=${defaultValue2 ?? ''}&info.f_bool=${defaultValue3 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatResponse(), + ); + client.innerApiCalls.repeatDataPathResource = + stubSimpleCall(expectedResponse); + const [response] = await client.repeatDataPathResource(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.repeatDataPathResource as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.repeatDataPathResource as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes repeatDataPathTrailingResource with closed client', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - request.info ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fString']); - request.info.fString = defaultValue1; - request.info ??= {}; - request.info.fChild ??= {}; - const defaultValue2 = - getTypeDefaultValue('.google.showcase.v1beta1.RepeatRequest', ['info', 'fChild', 'fString']); - request.info.fChild.fString = defaultValue2; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.repeatDataPathTrailingResource(request), expectedError); - }); + it('invokes repeatDataPathResource without error using callback', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + request.info ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fString'], + ); + request.info.fString = defaultValue1; + request.info ??= {}; + request.info.fChild ??= {}; + const defaultValue2 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fChild', 'fString'], + ); + request.info.fChild.fString = defaultValue2; + request.info ??= {}; + const defaultValue3 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fBool'], + ); + request.info.fBool = defaultValue3; + const expectedHeaderRequestParams = `info.f_string=${defaultValue1 ?? ''}&info.f_child.f_string=${defaultValue2 ?? ''}&info.f_bool=${defaultValue3 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatResponse(), + ); + client.innerApiCalls.repeatDataPathResource = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.repeatDataPathResource( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IRepeatResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.repeatDataPathResource as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.repeatDataPathResource as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('repeatDataBodyPut', () => { - it('invokes repeatDataBodyPut without error', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatResponse() - ); - client.innerApiCalls.repeatDataBodyPut = stubSimpleCall(expectedResponse); - const [response] = await client.repeatDataBodyPut(request); - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes repeatDataPathResource with error', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + request.info ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fString'], + ); + request.info.fString = defaultValue1; + request.info ??= {}; + request.info.fChild ??= {}; + const defaultValue2 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fChild', 'fString'], + ); + request.info.fChild.fString = defaultValue2; + request.info ??= {}; + const defaultValue3 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fBool'], + ); + request.info.fBool = defaultValue3; + const expectedHeaderRequestParams = `info.f_string=${defaultValue1 ?? ''}&info.f_child.f_string=${defaultValue2 ?? ''}&info.f_bool=${defaultValue3 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.repeatDataPathResource = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.repeatDataPathResource(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.repeatDataPathResource as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.repeatDataPathResource as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes repeatDataBodyPut without error using callback', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatResponse() - ); - client.innerApiCalls.repeatDataBodyPut = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.repeatDataBodyPut( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IRepeatResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes repeatDataPathResource with closed client', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + request.info ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fString'], + ); + request.info.fString = defaultValue1; + request.info ??= {}; + request.info.fChild ??= {}; + const defaultValue2 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fChild', 'fString'], + ); + request.info.fChild.fString = defaultValue2; + request.info ??= {}; + const defaultValue3 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fBool'], + ); + request.info.fBool = defaultValue3; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.repeatDataPathResource(request), + expectedError, + ); + }); + }); + + describe('repeatDataPathTrailingResource', () => { + it('invokes repeatDataPathTrailingResource without error', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + request.info ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fString'], + ); + request.info.fString = defaultValue1; + request.info ??= {}; + request.info.fChild ??= {}; + const defaultValue2 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fChild', 'fString'], + ); + request.info.fChild.fString = defaultValue2; + const expectedHeaderRequestParams = `info.f_string=${defaultValue1 ?? ''}&info.f_child.f_string=${defaultValue2 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatResponse(), + ); + client.innerApiCalls.repeatDataPathTrailingResource = + stubSimpleCall(expectedResponse); + const [response] = await client.repeatDataPathTrailingResource(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.repeatDataPathTrailingResource as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.repeatDataPathTrailingResource as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes repeatDataBodyPut with error', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.repeatDataBodyPut = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.repeatDataBodyPut(request), expectedError); - }); + it('invokes repeatDataPathTrailingResource without error using callback', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + request.info ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fString'], + ); + request.info.fString = defaultValue1; + request.info ??= {}; + request.info.fChild ??= {}; + const defaultValue2 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fChild', 'fString'], + ); + request.info.fChild.fString = defaultValue2; + const expectedHeaderRequestParams = `info.f_string=${defaultValue1 ?? ''}&info.f_child.f_string=${defaultValue2 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatResponse(), + ); + client.innerApiCalls.repeatDataPathTrailingResource = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.repeatDataPathTrailingResource( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IRepeatResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.repeatDataPathTrailingResource as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.repeatDataPathTrailingResource as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes repeatDataBodyPut with closed client', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.repeatDataBodyPut(request), expectedError); - }); + it('invokes repeatDataPathTrailingResource with error', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + request.info ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fString'], + ); + request.info.fString = defaultValue1; + request.info ??= {}; + request.info.fChild ??= {}; + const defaultValue2 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fChild', 'fString'], + ); + request.info.fChild.fString = defaultValue2; + const expectedHeaderRequestParams = `info.f_string=${defaultValue1 ?? ''}&info.f_child.f_string=${defaultValue2 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.repeatDataPathTrailingResource = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.repeatDataPathTrailingResource(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.repeatDataPathTrailingResource as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.repeatDataPathTrailingResource as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('repeatDataBodyPatch', () => { - it('invokes repeatDataBodyPatch without error', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatResponse() - ); - client.innerApiCalls.repeatDataBodyPatch = stubSimpleCall(expectedResponse); - const [response] = await client.repeatDataBodyPatch(request); - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes repeatDataPathTrailingResource with closed client', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + request.info ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fString'], + ); + request.info.fString = defaultValue1; + request.info ??= {}; + request.info.fChild ??= {}; + const defaultValue2 = getTypeDefaultValue( + '.google.showcase.v1beta1.RepeatRequest', + ['info', 'fChild', 'fString'], + ); + request.info.fChild.fString = defaultValue2; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.repeatDataPathTrailingResource(request), + expectedError, + ); + }); + }); + + describe('repeatDataBodyPut', () => { + it('invokes repeatDataBodyPut without error', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatResponse(), + ); + client.innerApiCalls.repeatDataBodyPut = stubSimpleCall(expectedResponse); + const [response] = await client.repeatDataBodyPut(request); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes repeatDataBodyPatch without error using callback', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatResponse() - ); - client.innerApiCalls.repeatDataBodyPatch = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.repeatDataBodyPatch( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IRepeatResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes repeatDataBodyPut without error using callback', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatResponse(), + ); + client.innerApiCalls.repeatDataBodyPut = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.repeatDataBodyPut( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IRepeatResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes repeatDataBodyPatch with error', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.repeatDataBodyPatch = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.repeatDataBodyPatch(request), expectedError); - }); + it('invokes repeatDataBodyPut with error', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.repeatDataBodyPut = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.repeatDataBodyPut(request), expectedError); + }); - it('invokes repeatDataBodyPatch with closed client', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.RepeatRequest() - ); - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.repeatDataBodyPatch(request), expectedError); - }); + it('invokes repeatDataBodyPut with closed client', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.repeatDataBodyPut(request), expectedError); + }); + }); + + describe('repeatDataBodyPatch', () => { + it('invokes repeatDataBodyPatch without error', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatResponse(), + ); + client.innerApiCalls.repeatDataBodyPatch = + stubSimpleCall(expectedResponse); + const [response] = await client.repeatDataBodyPatch(request); + assert.deepStrictEqual(response, expectedResponse); }); - describe('getEnum', () => { - it('invokes getEnum without error', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.EnumRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.EnumResponse() - ); - client.innerApiCalls.getEnum = stubSimpleCall(expectedResponse); - const [response] = await client.getEnum(request); - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes repeatDataBodyPatch without error using callback', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatResponse(), + ); + client.innerApiCalls.repeatDataBodyPatch = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.repeatDataBodyPatch( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IRepeatResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes getEnum without error using callback', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.EnumRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.EnumResponse() - ); - client.innerApiCalls.getEnum = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getEnum( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IEnumResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes repeatDataBodyPatch with error', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.repeatDataBodyPatch = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.repeatDataBodyPatch(request), expectedError); + }); - it('invokes getEnum with error', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.EnumRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.getEnum = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getEnum(request), expectedError); - }); + it('invokes repeatDataBodyPatch with closed client', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.RepeatRequest(), + ); + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.repeatDataBodyPatch(request), expectedError); + }); + }); + + describe('getEnum', () => { + it('invokes getEnum without error', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.EnumRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.EnumResponse(), + ); + client.innerApiCalls.getEnum = stubSimpleCall(expectedResponse); + const [response] = await client.getEnum(request); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes getEnum with closed client', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.EnumRequest() - ); - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getEnum(request), expectedError); - }); + it('invokes getEnum without error using callback', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.EnumRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.EnumResponse(), + ); + client.innerApiCalls.getEnum = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getEnum( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IEnumResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); }); - describe('verifyEnum', () => { - it('invokes verifyEnum without error', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.EnumResponse() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.EnumResponse() - ); - client.innerApiCalls.verifyEnum = stubSimpleCall(expectedResponse); - const [response] = await client.verifyEnum(request); - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes getEnum with error', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.EnumRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.getEnum = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.getEnum(request), expectedError); + }); - it('invokes verifyEnum without error using callback', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.EnumResponse() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.EnumResponse() - ); - client.innerApiCalls.verifyEnum = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.verifyEnum( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IEnumResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes getEnum with closed client', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.EnumRequest(), + ); + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getEnum(request), expectedError); + }); + }); + + describe('verifyEnum', () => { + it('invokes verifyEnum without error', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.EnumResponse(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.EnumResponse(), + ); + client.innerApiCalls.verifyEnum = stubSimpleCall(expectedResponse); + const [response] = await client.verifyEnum(request); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes verifyEnum with error', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.EnumResponse() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.verifyEnum = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.verifyEnum(request), expectedError); - }); + it('invokes verifyEnum without error using callback', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.EnumResponse(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.EnumResponse(), + ); + client.innerApiCalls.verifyEnum = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.verifyEnum( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IEnumResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes verifyEnum with closed client', async () => { - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.EnumResponse() - ); - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.verifyEnum(request), expectedError); - }); + it('invokes verifyEnum with error', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.EnumResponse(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.verifyEnum = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.verifyEnum(request), expectedError); }); - describe('Path templates', () => { - - describe('blueprint', async () => { - const fakePath = "/rendered/path/blueprint"; - const expectedParameters = { - session: "sessionValue", - test: "testValue", - blueprint: "blueprintValue", - }; - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.blueprintPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.blueprintPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('blueprintPath', () => { - const result = client.blueprintPath("sessionValue", "testValue", "blueprintValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.blueprintPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchSessionFromBlueprintName', () => { - const result = client.matchSessionFromBlueprintName(fakePath); - assert.strictEqual(result, "sessionValue"); - assert((client.pathTemplates.blueprintPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchTestFromBlueprintName', () => { - const result = client.matchTestFromBlueprintName(fakePath); - assert.strictEqual(result, "testValue"); - assert((client.pathTemplates.blueprintPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBlueprintFromBlueprintName', () => { - const result = client.matchBlueprintFromBlueprintName(fakePath); - assert.strictEqual(result, "blueprintValue"); - assert((client.pathTemplates.blueprintPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('invokes verifyEnum with closed client', async () => { + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.EnumResponse(), + ); + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.verifyEnum(request), expectedError); + }); + }); + + describe('Path templates', () => { + describe('blueprint', async () => { + const fakePath = '/rendered/path/blueprint'; + const expectedParameters = { + session: 'sessionValue', + test: 'testValue', + blueprint: 'blueprintValue', + }; + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.blueprintPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.blueprintPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('blueprintPath', () => { + const result = client.blueprintPath( + 'sessionValue', + 'testValue', + 'blueprintValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.blueprintPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchSessionFromBlueprintName', () => { + const result = client.matchSessionFromBlueprintName(fakePath); + assert.strictEqual(result, 'sessionValue'); + assert( + (client.pathTemplates.blueprintPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchTestFromBlueprintName', () => { + const result = client.matchTestFromBlueprintName(fakePath); + assert.strictEqual(result, 'testValue'); + assert( + (client.pathTemplates.blueprintPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBlueprintFromBlueprintName', () => { + const result = client.matchBlueprintFromBlueprintName(fakePath); + assert.strictEqual(result, 'blueprintValue'); + assert( + (client.pathTemplates.blueprintPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('room', async () => { - const fakePath = "/rendered/path/room"; - const expectedParameters = { - room: "roomValue", - }; - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.roomPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.roomPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('roomPath', () => { - const result = client.roomPath("roomValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.roomPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchRoomFromRoomName', () => { - const result = client.matchRoomFromRoomName(fakePath); - assert.strictEqual(result, "roomValue"); - assert((client.pathTemplates.roomPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('room', async () => { + const fakePath = '/rendered/path/room'; + const expectedParameters = { + room: 'roomValue', + }; + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.roomPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.roomPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('roomPath', () => { + const result = client.roomPath('roomValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.roomPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchRoomFromRoomName', () => { + const result = client.matchRoomFromRoomName(fakePath); + assert.strictEqual(result, 'roomValue'); + assert( + (client.pathTemplates.roomPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('roomBlurb', async () => { - const fakePath = "/rendered/path/roomBlurb"; - const expectedParameters = { - room: "roomValue", - blurb: "blurbValue", - }; - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.roomBlurbPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.roomBlurbPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('roomBlurbPath', () => { - const result = client.roomBlurbPath("roomValue", "blurbValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.roomBlurbPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchRoomFromRoomBlurbName', () => { - const result = client.matchRoomFromRoomBlurbName(fakePath); - assert.strictEqual(result, "roomValue"); - assert((client.pathTemplates.roomBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBlurbFromRoomBlurbName', () => { - const result = client.matchBlurbFromRoomBlurbName(fakePath); - assert.strictEqual(result, "blurbValue"); - assert((client.pathTemplates.roomBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('roomBlurb', async () => { + const fakePath = '/rendered/path/roomBlurb'; + const expectedParameters = { + room: 'roomValue', + blurb: 'blurbValue', + }; + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.roomBlurbPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.roomBlurbPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('roomBlurbPath', () => { + const result = client.roomBlurbPath('roomValue', 'blurbValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.roomBlurbPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchRoomFromRoomBlurbName', () => { + const result = client.matchRoomFromRoomBlurbName(fakePath); + assert.strictEqual(result, 'roomValue'); + assert( + (client.pathTemplates.roomBlurbPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBlurbFromRoomBlurbName', () => { + const result = client.matchBlurbFromRoomBlurbName(fakePath); + assert.strictEqual(result, 'blurbValue'); + assert( + (client.pathTemplates.roomBlurbPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('roomBlurbsLegacyRoomBlurb', async () => { - const fakePath = "/rendered/path/roomBlurbsLegacyRoomBlurb"; - const expectedParameters = { - room: "roomValue", - legacy_room: "legacyRoomValue", - blurb: "blurbValue", - }; - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('roomBlurbsLegacyRoomBlurbPath', () => { - const result = client.roomBlurbsLegacyRoomBlurbPath("roomValue", "legacyRoomValue", "blurbValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchRoomFromRoomBlurbsLegacyRoomBlurbName', () => { - const result = client.matchRoomFromRoomBlurbsLegacyRoomBlurbName(fakePath); - assert.strictEqual(result, "roomValue"); - assert((client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName', () => { - const result = client.matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName(fakePath); - assert.strictEqual(result, "legacyRoomValue"); - assert((client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBlurbFromRoomBlurbsLegacyRoomBlurbName', () => { - const result = client.matchBlurbFromRoomBlurbsLegacyRoomBlurbName(fakePath); - assert.strictEqual(result, "blurbValue"); - assert((client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('roomBlurbsLegacyRoomBlurb', async () => { + const fakePath = '/rendered/path/roomBlurbsLegacyRoomBlurb'; + const expectedParameters = { + room: 'roomValue', + legacy_room: 'legacyRoomValue', + blurb: 'blurbValue', + }; + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('roomBlurbsLegacyRoomBlurbPath', () => { + const result = client.roomBlurbsLegacyRoomBlurbPath( + 'roomValue', + 'legacyRoomValue', + 'blurbValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchRoomFromRoomBlurbsLegacyRoomBlurbName', () => { + const result = + client.matchRoomFromRoomBlurbsLegacyRoomBlurbName(fakePath); + assert.strictEqual(result, 'roomValue'); + assert( + ( + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName', () => { + const result = + client.matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName(fakePath); + assert.strictEqual(result, 'legacyRoomValue'); + assert( + ( + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBlurbFromRoomBlurbsLegacyRoomBlurbName', () => { + const result = + client.matchBlurbFromRoomBlurbsLegacyRoomBlurbName(fakePath); + assert.strictEqual(result, 'blurbValue'); + assert( + ( + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('sequence', async () => { - const fakePath = "/rendered/path/sequence"; - const expectedParameters = { - sequence: "sequenceValue", - }; - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.sequencePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.sequencePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('sequencePath', () => { - const result = client.sequencePath("sequenceValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.sequencePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchSequenceFromSequenceName', () => { - const result = client.matchSequenceFromSequenceName(fakePath); - assert.strictEqual(result, "sequenceValue"); - assert((client.pathTemplates.sequencePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('sequence', async () => { + const fakePath = '/rendered/path/sequence'; + const expectedParameters = { + sequence: 'sequenceValue', + }; + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.sequencePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.sequencePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('sequencePath', () => { + const result = client.sequencePath('sequenceValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.sequencePathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchSequenceFromSequenceName', () => { + const result = client.matchSequenceFromSequenceName(fakePath); + assert.strictEqual(result, 'sequenceValue'); + assert( + (client.pathTemplates.sequencePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('sequenceReport', async () => { - const fakePath = "/rendered/path/sequenceReport"; - const expectedParameters = { - sequence: "sequenceValue", - }; - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.sequenceReportPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.sequenceReportPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('sequenceReportPath', () => { - const result = client.sequenceReportPath("sequenceValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.sequenceReportPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchSequenceFromSequenceReportName', () => { - const result = client.matchSequenceFromSequenceReportName(fakePath); - assert.strictEqual(result, "sequenceValue"); - assert((client.pathTemplates.sequenceReportPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('sequenceReport', async () => { + const fakePath = '/rendered/path/sequenceReport'; + const expectedParameters = { + sequence: 'sequenceValue', + }; + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.sequenceReportPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.sequenceReportPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('sequenceReportPath', () => { + const result = client.sequenceReportPath('sequenceValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.sequenceReportPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchSequenceFromSequenceReportName', () => { + const result = client.matchSequenceFromSequenceReportName(fakePath); + assert.strictEqual(result, 'sequenceValue'); + assert( + (client.pathTemplates.sequenceReportPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('session', async () => { - const fakePath = "/rendered/path/session"; - const expectedParameters = { - session: "sessionValue", - }; - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.sessionPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.sessionPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('sessionPath', () => { - const result = client.sessionPath("sessionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.sessionPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchSessionFromSessionName', () => { - const result = client.matchSessionFromSessionName(fakePath); - assert.strictEqual(result, "sessionValue"); - assert((client.pathTemplates.sessionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('session', async () => { + const fakePath = '/rendered/path/session'; + const expectedParameters = { + session: 'sessionValue', + }; + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.sessionPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.sessionPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('sessionPath', () => { + const result = client.sessionPath('sessionValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.sessionPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchSessionFromSessionName', () => { + const result = client.matchSessionFromSessionName(fakePath); + assert.strictEqual(result, 'sessionValue'); + assert( + (client.pathTemplates.sessionPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('test', async () => { - const fakePath = "/rendered/path/test"; - const expectedParameters = { - session: "sessionValue", - test: "testValue", - }; - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.testPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.testPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('testPath', () => { - const result = client.testPath("sessionValue", "testValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.testPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchSessionFromTestName', () => { - const result = client.matchSessionFromTestName(fakePath); - assert.strictEqual(result, "sessionValue"); - assert((client.pathTemplates.testPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchTestFromTestName', () => { - const result = client.matchTestFromTestName(fakePath); - assert.strictEqual(result, "testValue"); - assert((client.pathTemplates.testPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('test', async () => { + const fakePath = '/rendered/path/test'; + const expectedParameters = { + session: 'sessionValue', + test: 'testValue', + }; + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.testPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.testPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('testPath', () => { + const result = client.testPath('sessionValue', 'testValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.testPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchSessionFromTestName', () => { + const result = client.matchSessionFromTestName(fakePath); + assert.strictEqual(result, 'sessionValue'); + assert( + (client.pathTemplates.testPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchTestFromTestName', () => { + const result = client.matchTestFromTestName(fakePath); + assert.strictEqual(result, 'testValue'); + assert( + (client.pathTemplates.testPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('user', async () => { - const fakePath = "/rendered/path/user"; - const expectedParameters = { - user: "userValue", - }; - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.userPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.userPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('userPath', () => { - const result = client.userPath("userValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.userPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchUserFromUserName', () => { - const result = client.matchUserFromUserName(fakePath); - assert.strictEqual(result, "userValue"); - assert((client.pathTemplates.userPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('user', async () => { + const fakePath = '/rendered/path/user'; + const expectedParameters = { + user: 'userValue', + }; + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.userPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.userPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('userPath', () => { + const result = client.userPath('userValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.userPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchUserFromUserName', () => { + const result = client.matchUserFromUserName(fakePath); + assert.strictEqual(result, 'userValue'); + assert( + (client.pathTemplates.userPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('userProfileBlurb', async () => { - const fakePath = "/rendered/path/userProfileBlurb"; - const expectedParameters = { - user: "userValue", - blurb: "blurbValue", - }; - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.userProfileBlurbPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.userProfileBlurbPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('userProfileBlurbPath', () => { - const result = client.userProfileBlurbPath("userValue", "blurbValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.userProfileBlurbPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchUserFromUserProfileBlurbName', () => { - const result = client.matchUserFromUserProfileBlurbName(fakePath); - assert.strictEqual(result, "userValue"); - assert((client.pathTemplates.userProfileBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBlurbFromUserProfileBlurbName', () => { - const result = client.matchBlurbFromUserProfileBlurbName(fakePath); - assert.strictEqual(result, "blurbValue"); - assert((client.pathTemplates.userProfileBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('userProfileBlurb', async () => { + const fakePath = '/rendered/path/userProfileBlurb'; + const expectedParameters = { + user: 'userValue', + blurb: 'blurbValue', + }; + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.userProfileBlurbPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.userProfileBlurbPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('userProfileBlurbPath', () => { + const result = client.userProfileBlurbPath('userValue', 'blurbValue'); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.userProfileBlurbPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchUserFromUserProfileBlurbName', () => { + const result = client.matchUserFromUserProfileBlurbName(fakePath); + assert.strictEqual(result, 'userValue'); + assert( + (client.pathTemplates.userProfileBlurbPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBlurbFromUserProfileBlurbName', () => { + const result = client.matchBlurbFromUserProfileBlurbName(fakePath); + assert.strictEqual(result, 'blurbValue'); + assert( + (client.pathTemplates.userProfileBlurbPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('userProfileBlurbsLegacyUserBlurb', async () => { - const fakePath = "/rendered/path/userProfileBlurbsLegacyUserBlurb"; - const expectedParameters = { - user: "userValue", - legacy_user: "legacyUserValue", - blurb: "blurbValue", - }; - const client = new complianceModule.v1beta1.ComplianceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('userProfileBlurbsLegacyUserBlurbPath', () => { - const result = client.userProfileBlurbsLegacyUserBlurbPath("userValue", "legacyUserValue", "blurbValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchUserFromUserProfileBlurbsLegacyUserBlurbName', () => { - const result = client.matchUserFromUserProfileBlurbsLegacyUserBlurbName(fakePath); - assert.strictEqual(result, "userValue"); - assert((client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName', () => { - const result = client.matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName(fakePath); - assert.strictEqual(result, "legacyUserValue"); - assert((client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBlurbFromUserProfileBlurbsLegacyUserBlurbName', () => { - const result = client.matchBlurbFromUserProfileBlurbsLegacyUserBlurbName(fakePath); - assert.strictEqual(result, "blurbValue"); - assert((client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('userProfileBlurbsLegacyUserBlurb', async () => { + const fakePath = '/rendered/path/userProfileBlurbsLegacyUserBlurb'; + const expectedParameters = { + user: 'userValue', + legacy_user: 'legacyUserValue', + blurb: 'blurbValue', + }; + const client = new complianceModule.v1beta1.ComplianceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('userProfileBlurbsLegacyUserBlurbPath', () => { + const result = client.userProfileBlurbsLegacyUserBlurbPath( + 'userValue', + 'legacyUserValue', + 'blurbValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchUserFromUserProfileBlurbsLegacyUserBlurbName', () => { + const result = + client.matchUserFromUserProfileBlurbsLegacyUserBlurbName(fakePath); + assert.strictEqual(result, 'userValue'); + assert( + ( + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName', () => { + const result = + client.matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName( + fakePath, + ); + assert.strictEqual(result, 'legacyUserValue'); + assert( + ( + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBlurbFromUserProfileBlurbsLegacyUserBlurbName', () => { + const result = + client.matchBlurbFromUserProfileBlurbsLegacyUserBlurbName(fakePath); + assert.strictEqual(result, 'blurbValue'); + assert( + ( + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/core/generator/gapic-generator-typescript/baselines/showcase/test/gapic_echo_v1beta1.ts.baseline b/core/generator/gapic-generator-typescript/baselines/showcase/test/gapic_echo_v1beta1.ts.baseline index 1a1ffd031a22..ebdac6159b3f 100644 --- a/core/generator/gapic-generator-typescript/baselines/showcase/test/gapic_echo_v1beta1.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/showcase/test/gapic_echo_v1beta1.ts.baseline @@ -19,1517 +19,1932 @@ import * as protos from '../protos/protos'; import * as assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as echoModule from '../src'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; -import {protobuf, LROperation, operationsProtos} from 'google-gax'; +import { protobuf, LROperation, operationsProtos } from 'google-gax'; // Dynamically loaded proto JSON is needed to get the type information // to fill in default values for request objects -const root = protobuf.Root.fromJSON(require('../protos/protos.json')).resolveAll(); +const root = protobuf.Root.fromJSON( + require('../protos/protos.json'), +).resolveAll(); // eslint-disable-next-line @typescript-eslint/no-unused-vars function getTypeDefaultValue(typeName: string, fields: string[]) { - let type = root.lookupType(typeName) as protobuf.Type; - for (const field of fields.slice(0, -1)) { - type = type.fields[field]?.resolvedType as protobuf.Type; - } - return type.fields[fields[fields.length - 1]]?.defaultValue; + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type.fields[field]?.resolvedType as protobuf.Type; + } + return type.fields[fields[fields.length - 1]]?.defaultValue; } function generateSampleMessage(instance: T) { - const filledObject = (instance.constructor as typeof protobuf.Message) - .toObject(instance as protobuf.Message, {defaults: true}); - return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, { defaults: true }); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; } function stubSimpleCall(response?: ResponseType, error?: Error) { - return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); } -function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { - return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +function stubSimpleCallWithCallback( + response?: ResponseType, + error?: Error, +) { + return error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); } -function stubServerStreamingCall(response?: ResponseType, error?: Error) { - const transformStub = error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); - const mockStream = new PassThrough({ - objectMode: true, - transform: transformStub, - }); - // write something to the stream to trigger transformStub and send the response back to the client - setImmediate(() => { mockStream.write({}); }); - setImmediate(() => { mockStream.end(); }); - return sinon.stub().returns(mockStream); +function stubServerStreamingCall( + response?: ResponseType, + error?: Error, +) { + const transformStub = error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + // write something to the stream to trigger transformStub and send the response back to the client + setImmediate(() => { + mockStream.write({}); + }); + setImmediate(() => { + mockStream.end(); + }); + return sinon.stub().returns(mockStream); } -function stubBidiStreamingCall(response?: ResponseType, error?: Error) { - const transformStub = error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); - const mockStream = new PassThrough({ - objectMode: true, - transform: transformStub, - }); - return sinon.stub().returns(mockStream); +function stubBidiStreamingCall( + response?: ResponseType, + error?: Error, +) { + const transformStub = error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + return sinon.stub().returns(mockStream); } -function stubClientStreamingCall(response?: ResponseType, error?: Error) { - if (error) { - return sinon.stub().callsArgWith(2, error); - } - const transformStub = sinon.stub(); - const mockStream = new PassThrough({ - objectMode: true, - transform: transformStub, - }); - return sinon.stub().returns(mockStream).callsArgWith(2, null, response); +function stubClientStreamingCall( + response?: ResponseType, + error?: Error, +) { + if (error) { + return sinon.stub().callsArgWith(2, error); + } + const transformStub = sinon.stub(); + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + return sinon.stub().returns(mockStream).callsArgWith(2, null, response); } -function stubLongRunningCall(response?: ResponseType, callError?: Error, lroError?: Error) { - const innerStub = lroError ? sinon.stub().rejects(lroError) : sinon.stub().resolves([response]); - const mockOperation = { - promise: innerStub, - }; - return callError ? sinon.stub().rejects(callError) : sinon.stub().resolves([mockOperation]); +function stubLongRunningCall( + response?: ResponseType, + callError?: Error, + lroError?: Error, +) { + const innerStub = lroError + ? sinon.stub().rejects(lroError) + : sinon.stub().resolves([response]); + const mockOperation = { + promise: innerStub, + }; + return callError + ? sinon.stub().rejects(callError) + : sinon.stub().resolves([mockOperation]); } -function stubLongRunningCallWithCallback(response?: ResponseType, callError?: Error, lroError?: Error) { - const innerStub = lroError ? sinon.stub().rejects(lroError) : sinon.stub().resolves([response]); - const mockOperation = { - promise: innerStub, - }; - return callError ? sinon.stub().callsArgWith(2, callError) : sinon.stub().callsArgWith(2, null, mockOperation); +function stubLongRunningCallWithCallback( + response?: ResponseType, + callError?: Error, + lroError?: Error, +) { + const innerStub = lroError + ? sinon.stub().rejects(lroError) + : sinon.stub().resolves([response]); + const mockOperation = { + promise: innerStub, + }; + return callError + ? sinon.stub().callsArgWith(2, callError) + : sinon.stub().callsArgWith(2, null, mockOperation); } -function stubPageStreamingCall(responses?: ResponseType[], error?: Error) { - const pagingStub = sinon.stub(); - if (responses) { - for (let i = 0; i < responses.length; ++i) { - pagingStub.onCall(i).callsArgWith(2, null, responses[i]); - } +function stubPageStreamingCall( + responses?: ResponseType[], + error?: Error, +) { + const pagingStub = sinon.stub(); + if (responses) { + for (let i = 0; i < responses.length; ++i) { + pagingStub.onCall(i).callsArgWith(2, null, responses[i]); } - const transformStub = error ? sinon.stub().callsArgWith(2, error) : pagingStub; - const mockStream = new PassThrough({ - objectMode: true, - transform: transformStub, - }); - // trigger as many responses as needed - if (responses) { - for (let i = 0; i < responses.length; ++i) { - setImmediate(() => { mockStream.write({}); }); - } - setImmediate(() => { mockStream.end(); }); - } else { - setImmediate(() => { mockStream.write({}); }); - setImmediate(() => { mockStream.end(); }); + } + const transformStub = error + ? sinon.stub().callsArgWith(2, error) + : pagingStub; + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + // trigger as many responses as needed + if (responses) { + for (let i = 0; i < responses.length; ++i) { + setImmediate(() => { + mockStream.write({}); + }); } - return sinon.stub().returns(mockStream); + setImmediate(() => { + mockStream.end(); + }); + } else { + setImmediate(() => { + mockStream.write({}); + }); + setImmediate(() => { + mockStream.end(); + }); + } + return sinon.stub().returns(mockStream); } -function stubAsyncIterationCall(responses?: ResponseType[], error?: Error) { - let counter = 0; - const asyncIterable = { - [Symbol.asyncIterator]() { - return { - async next() { - if (error) { - return Promise.reject(error); - } - if (counter >= responses!.length) { - return Promise.resolve({done: true, value: undefined}); - } - return Promise.resolve({done: false, value: responses![counter++]}); - } - }; - } - }; - return sinon.stub().returns(asyncIterable); +function stubAsyncIterationCall( + responses?: ResponseType[], + error?: Error, +) { + let counter = 0; + const asyncIterable = { + [Symbol.asyncIterator]() { + return { + async next() { + if (error) { + return Promise.reject(error); + } + if (counter >= responses!.length) { + return Promise.resolve({ done: true, value: undefined }); + } + return Promise.resolve({ done: false, value: responses![counter++] }); + }, + }; + }, + }; + return sinon.stub().returns(asyncIterable); } describe('v1beta1.EchoClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new echoModule.v1beta1.EchoClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'localhost'); - }); - - it('has universeDomain', () => { - const client = new echoModule.v1beta1.EchoClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); - - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - it('throws DeprecationWarning if static servicePath is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const servicePath = echoModule.v1beta1.EchoClient.servicePath; - assert.strictEqual(servicePath, 'localhost'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = echoModule.v1beta1.EchoClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'localhost'); - assert(stub.called); - stub.restore(); - }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { new echoModule.v1beta1.EchoClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); - - it('has port', () => { - const port = echoModule.v1beta1.EchoClient.port; - assert(port); - assert(typeof port === 'number'); - }); - - it('should create a client with no option', () => { - const client = new echoModule.v1beta1.EchoClient(); - assert(client); - }); - - it('should create a client with gRPC fallback', () => { - const client = new echoModule.v1beta1.EchoClient({ - fallback: true, - }); - assert(client); - }); - - it('has initialize method and supports deferred initialization', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.echoStub, undefined); - await client.initialize(); - assert(client.echoStub); - }); - - it('has close method for the initialized client', done => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.echoStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); - - it('has close method for the non-initialized client', done => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.echoStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new echoModule.v1beta1.EchoClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'localhost'); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); - }); + it('has universeDomain', () => { + const client = new echoModule.v1beta1.EchoClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId((err?: Error|null, projectId?: string|null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } - }); - }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = echoModule.v1beta1.EchoClient.servicePath; + assert.strictEqual(servicePath, 'localhost'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = echoModule.v1beta1.EchoClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'localhost'); + assert(stub.called); + stub.restore(); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new echoModule.v1beta1.EchoClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); }); - describe('echo', () => { - it('invokes echo without error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.EchoRequest() - ); - // path template: {qux=projects/*}/** - request.otherHeader = 'projects/value/value'; - const expectedHeaderRequestParams = 'qux=projects%2Fvalue'; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.EchoResponse() - ); - client.innerApiCalls.echo = stubSimpleCall(expectedResponse); - const [response] = await client.echo(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.echo as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.echo as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - assert.match((client.innerApiCalls.echo as SinonStub) - .getCall(0).args[0].requestId, /[a-z0-9-]{36}/) - }); + it('has port', () => { + const port = echoModule.v1beta1.EchoClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('invokes echo without error using callback', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.EchoRequest() - ); - // path template: {qux=projects/*}/** - request.otherHeader = 'projects/value/value'; - const expectedHeaderRequestParams = 'qux=projects%2Fvalue'; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.EchoResponse() - ); - client.innerApiCalls.echo = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.echo( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IEchoResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.echo as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.echo as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - assert.match((client.innerApiCalls.echo as SinonStub) - .getCall(0).args[0].requestId, /[a-z0-9-]{36}/) - }); + it('should create a client with no option', () => { + const client = new echoModule.v1beta1.EchoClient(); + assert(client); + }); - it('invokes echo with error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.EchoRequest() - ); - // path template: {qux=projects/*}/** - request.otherHeader = 'projects/value/value'; - const expectedHeaderRequestParams = 'qux=projects%2Fvalue'; - const expectedError = new Error('expected'); - client.innerApiCalls.echo = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.echo(request), expectedError); - const actualRequest = (client.innerApiCalls.echo as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.echo as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - assert.match((client.innerApiCalls.echo as SinonStub) - .getCall(0).args[0].requestId, /[a-z0-9-]{36}/) - }); + it('should create a client with gRPC fallback', () => { + const client = new echoModule.v1beta1.EchoClient({ + fallback: true, + }); + assert(client); + }); - it('invokes echo with closed client', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.EchoRequest() - ); - // path template: {qux=projects/*}/** - request.otherHeader = 'projects/value/value'; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.echo(request), expectedError); - }); + it('has initialize method and supports deferred initialization', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.echoStub, undefined); + await client.initialize(); + assert(client.echoStub); }); - describe('echoErrorDetails', () => { - it('invokes echoErrorDetails without error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.EchoErrorDetailsRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.EchoErrorDetailsResponse() - ); - client.innerApiCalls.echoErrorDetails = stubSimpleCall(expectedResponse); - const [response] = await client.echoErrorDetails(request); - assert.deepStrictEqual(response, expectedResponse); + it('has close method for the initialized client', (done) => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.echoStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes echoErrorDetails without error using callback', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.EchoErrorDetailsRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.EchoErrorDetailsResponse() - ); - client.innerApiCalls.echoErrorDetails = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.echoErrorDetails( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IEchoErrorDetailsResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); + it('has close method for the non-initialized client', (done) => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.echoStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes echoErrorDetails with error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.EchoErrorDetailsRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.echoErrorDetails = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.echoErrorDetails(request), expectedError); - }); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + }); - it('invokes echoErrorDetails with closed client', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.EchoErrorDetailsRequest() - ); - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.echoErrorDetails(request), expectedError); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + }); + + describe('echo', () => { + it('invokes echo without error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.EchoRequest(), + ); + // path template: {qux=projects/*}/** + request.otherHeader = 'projects/value/value'; + const expectedHeaderRequestParams = 'qux=projects%2Fvalue'; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.EchoResponse(), + ); + client.innerApiCalls.echo = stubSimpleCall(expectedResponse); + const [response] = await client.echo(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.echo as SinonStub).getCall(0) + .args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.echo as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + assert.match( + (client.innerApiCalls.echo as SinonStub).getCall(0).args[0].requestId, + /[a-z0-9-]{36}/, + ); }); - describe('pagedExpandLegacy', () => { - it('invokes pagedExpandLegacy without error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.PagedExpandLegacyRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.PagedExpandResponse() - ); - client.innerApiCalls.pagedExpandLegacy = stubSimpleCall(expectedResponse); - const [response] = await client.pagedExpandLegacy(request); - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes echo without error using callback', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.EchoRequest(), + ); + // path template: {qux=projects/*}/** + request.otherHeader = 'projects/value/value'; + const expectedHeaderRequestParams = 'qux=projects%2Fvalue'; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.EchoResponse(), + ); + client.innerApiCalls.echo = stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.echo( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IEchoResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.echo as SinonStub).getCall(0) + .args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.echo as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + assert.match( + (client.innerApiCalls.echo as SinonStub).getCall(0).args[0].requestId, + /[a-z0-9-]{36}/, + ); + }); - it('invokes pagedExpandLegacy without error using callback', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.PagedExpandLegacyRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.PagedExpandResponse() - ); - client.innerApiCalls.pagedExpandLegacy = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.pagedExpandLegacy( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IPagedExpandResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes echo with error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.EchoRequest(), + ); + // path template: {qux=projects/*}/** + request.otherHeader = 'projects/value/value'; + const expectedHeaderRequestParams = 'qux=projects%2Fvalue'; + const expectedError = new Error('expected'); + client.innerApiCalls.echo = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.echo(request), expectedError); + const actualRequest = (client.innerApiCalls.echo as SinonStub).getCall(0) + .args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.echo as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + assert.match( + (client.innerApiCalls.echo as SinonStub).getCall(0).args[0].requestId, + /[a-z0-9-]{36}/, + ); + }); - it('invokes pagedExpandLegacy with error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.PagedExpandLegacyRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.pagedExpandLegacy = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.pagedExpandLegacy(request), expectedError); - }); + it('invokes echo with closed client', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.EchoRequest(), + ); + // path template: {qux=projects/*}/** + request.otherHeader = 'projects/value/value'; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.echo(request), expectedError); + }); + }); + + describe('echoErrorDetails', () => { + it('invokes echoErrorDetails without error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.EchoErrorDetailsRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.EchoErrorDetailsResponse(), + ); + client.innerApiCalls.echoErrorDetails = stubSimpleCall(expectedResponse); + const [response] = await client.echoErrorDetails(request); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes pagedExpandLegacy with closed client', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.PagedExpandLegacyRequest() - ); - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.pagedExpandLegacy(request), expectedError); - }); + it('invokes echoErrorDetails without error using callback', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.EchoErrorDetailsRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.EchoErrorDetailsResponse(), + ); + client.innerApiCalls.echoErrorDetails = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.echoErrorDetails( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IEchoErrorDetailsResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); }); - describe('block', () => { - it('invokes block without error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.BlockRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.BlockResponse() - ); - client.innerApiCalls.block = stubSimpleCall(expectedResponse); - const [response] = await client.block(request); - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes echoErrorDetails with error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.EchoErrorDetailsRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.echoErrorDetails = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.echoErrorDetails(request), expectedError); + }); - it('invokes block without error using callback', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.BlockRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.BlockResponse() - ); - client.innerApiCalls.block = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.block( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IBlockResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes echoErrorDetails with closed client', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.EchoErrorDetailsRequest(), + ); + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.echoErrorDetails(request), expectedError); + }); + }); + + describe('pagedExpandLegacy', () => { + it('invokes pagedExpandLegacy without error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.PagedExpandLegacyRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.PagedExpandResponse(), + ); + client.innerApiCalls.pagedExpandLegacy = stubSimpleCall(expectedResponse); + const [response] = await client.pagedExpandLegacy(request); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes block with error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.BlockRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.block = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.block(request), expectedError); - }); + it('invokes pagedExpandLegacy without error using callback', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.PagedExpandLegacyRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.PagedExpandResponse(), + ); + client.innerApiCalls.pagedExpandLegacy = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.pagedExpandLegacy( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IPagedExpandResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes block with closed client', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.BlockRequest() - ); - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.block(request), expectedError); - }); + it('invokes pagedExpandLegacy with error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.PagedExpandLegacyRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.pagedExpandLegacy = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.pagedExpandLegacy(request), expectedError); }); - describe('wait', () => { - it('invokes wait without error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.WaitRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.wait = stubLongRunningCall(expectedResponse); - const [operation] = await client.wait(request); - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes pagedExpandLegacy with closed client', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.PagedExpandLegacyRequest(), + ); + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.pagedExpandLegacy(request), expectedError); + }); + }); + + describe('block', () => { + it('invokes block without error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.BlockRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.BlockResponse(), + ); + client.innerApiCalls.block = stubSimpleCall(expectedResponse); + const [response] = await client.block(request); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes wait without error using callback', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.WaitRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.wait = stubLongRunningCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.wait( - request, - (err?: Error|null, - result?: LROperation|null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const operation = await promise as LROperation; - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes block without error using callback', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.BlockRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.BlockResponse(), + ); + client.innerApiCalls.block = stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.block( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IBlockResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes wait with call error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.WaitRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.wait = stubLongRunningCall(undefined, expectedError); - await assert.rejects(client.wait(request), expectedError); - }); + it('invokes block with error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.BlockRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.block = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.block(request), expectedError); + }); - it('invokes wait with LRO error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.WaitRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.wait = stubLongRunningCall(undefined, undefined, expectedError); - const [operation] = await client.wait(request); - await assert.rejects(operation.promise(), expectedError); - }); + it('invokes block with closed client', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.BlockRequest(), + ); + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.block(request), expectedError); + }); + }); + + describe('wait', () => { + it('invokes wait without error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.WaitRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.wait = stubLongRunningCall(expectedResponse); + const [operation] = await client.wait(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes checkWaitProgress without error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedResponse = generateSampleMessage( - new operationsProtos.google.longrunning.Operation() - ); - expectedResponse.name = 'test'; - expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; - expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')} - - client.operationsClient.getOperation = stubSimpleCall(expectedResponse); - const decodedOperation = await client.checkWaitProgress(expectedResponse.name); - assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); - assert(decodedOperation.metadata); - assert((client.operationsClient.getOperation as SinonStub).getCall(0)); - }); + it('invokes wait without error using callback', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.WaitRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.wait = + stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.wait( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.showcase.v1beta1.IWaitResponse, + protos.google.showcase.v1beta1.IWaitMetadata + > | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const operation = (await promise) as LROperation< + protos.google.showcase.v1beta1.IWaitResponse, + protos.google.showcase.v1beta1.IWaitMetadata + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes checkWaitProgress with error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedError = new Error('expected'); - - client.operationsClient.getOperation = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.checkWaitProgress(''), expectedError); - assert((client.operationsClient.getOperation as SinonStub) - .getCall(0)); - }); + it('invokes wait with call error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.WaitRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.wait = stubLongRunningCall(undefined, expectedError); + await assert.rejects(client.wait(request), expectedError); }); - describe('expand', () => { - it('invokes expand without error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ExpandRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.EchoResponse() - ); - client.innerApiCalls.expand = stubServerStreamingCall(expectedResponse); - const stream = client.expand(request); - const promise = new Promise((resolve, reject) => { - stream.on('data', (response: protos.google.showcase.v1beta1.EchoResponse) => { - resolve(response); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes wait with LRO error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.WaitRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.wait = stubLongRunningCall( + undefined, + undefined, + expectedError, + ); + const [operation] = await client.wait(request); + await assert.rejects(operation.promise(), expectedError); + }); - it('invokes expand without error and gaxServerStreamingRetries enabled', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - gaxServerStreamingRetries: true - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ExpandRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.EchoResponse() - ); - client.innerApiCalls.expand = stubServerStreamingCall(expectedResponse); - const stream = client.expand(request); - const promise = new Promise((resolve, reject) => { - stream.on('data', (response: protos.google.showcase.v1beta1.EchoResponse) => { - resolve(response); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes checkWaitProgress without error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation(), + ); + expectedResponse.name = 'test'; + expectedResponse.response = { type_url: 'url', value: Buffer.from('') }; + expectedResponse.metadata = { type_url: 'url', value: Buffer.from('') }; + + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const decodedOperation = await client.checkWaitProgress( + expectedResponse.name, + ); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); - it('invokes expand with error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ExpandRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.expand = stubServerStreamingCall(undefined, expectedError); - const stream = client.expand(request); - const promise = new Promise((resolve, reject) => { - stream.on('data', (response: protos.google.showcase.v1beta1.EchoResponse) => { - resolve(response); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); + it('invokes checkWaitProgress with error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const expectedError = new Error('expected'); + + client.operationsClient.getOperation = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.checkWaitProgress(''), expectedError); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + }); + + describe('expand', () => { + it('invokes expand without error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ExpandRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.EchoResponse(), + ); + client.innerApiCalls.expand = stubServerStreamingCall(expectedResponse); + const stream = client.expand(request); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + (response: protos.google.showcase.v1beta1.EchoResponse) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes expand with closed client', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ExpandRequest() - ); - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - const stream = client.expand(request, {retryRequestOptions: {noResponseRetries: 0}}); - const promise = new Promise((resolve, reject) => { - stream.on('data', (response: protos.google.showcase.v1beta1.EchoResponse) => { - resolve(response); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - }); - it('should create a client with gaxServerStreamingRetries enabled', () => { - const client = new echoModule.v1beta1.EchoClient({ - gaxServerStreamingRetries: true, - }); - assert(client); + it('invokes expand without error and gaxServerStreamingRetries enabled', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + gaxServerStreamingRetries: true, + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ExpandRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.EchoResponse(), + ); + client.innerApiCalls.expand = stubServerStreamingCall(expectedResponse); + const stream = client.expand(request); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + (response: protos.google.showcase.v1beta1.EchoResponse) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); }); - describe('chat', () => { - it('invokes chat without error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.EchoRequest() - ); - - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.EchoResponse() - ); - client.innerApiCalls.chat = stubBidiStreamingCall(expectedResponse); - const stream = client.chat(); - const promise = new Promise((resolve, reject) => { - stream.on('data', (response: protos.google.showcase.v1beta1.EchoResponse) => { - resolve(response); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - stream.write(request); - stream.end(); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - assert((client.innerApiCalls.chat as SinonStub) - .getCall(0).calledWith(null)); - assert.deepStrictEqual(((stream as unknown as PassThrough) - ._transform as SinonStub).getCall(0).args[0], request); + it('invokes expand with error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ExpandRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.expand = stubServerStreamingCall( + undefined, + expectedError, + ); + const stream = client.expand(request); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + (response: protos.google.showcase.v1beta1.EchoResponse) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); }); + }); + await assert.rejects(promise, expectedError); + }); - it('invokes chat with error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.EchoRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.chat = stubBidiStreamingCall(undefined, expectedError); - const stream = client.chat(); - const promise = new Promise((resolve, reject) => { - stream.on('data', (response: protos.google.showcase.v1beta1.EchoResponse) => { - resolve(response); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - stream.write(request); - stream.end(); - }); - await assert.rejects(promise, expectedError); - assert((client.innerApiCalls.chat as SinonStub) - .getCall(0).calledWith(null)); - assert.deepStrictEqual(((stream as unknown as PassThrough) - ._transform as SinonStub).getCall(0).args[0], request); + it('invokes expand with closed client', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ExpandRequest(), + ); + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + const stream = client.expand(request, { + retryRequestOptions: { noResponseRetries: 0 }, + }); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + (response: protos.google.showcase.v1beta1.EchoResponse) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); }); + }); + await assert.rejects(promise, expectedError); }); - - describe('collect', () => { - it('invokes collect without error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.EchoRequest() - ); - - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.EchoResponse() - ); - client.innerApiCalls.collect = stubClientStreamingCall(expectedResponse); - let stream: PassThrough; - const promise = new Promise((resolve, reject) => { - stream = client.collect( - (err?: Error|null, result?: protos.google.showcase.v1beta1.IEchoResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }) as unknown as PassThrough; - stream.write(request); - stream.end(); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - assert((client.innerApiCalls.collect as SinonStub) - .getCall(0).calledWith(null, {} /*, callback defined above */)); - assert.deepStrictEqual((stream!._transform as SinonStub).getCall(0).args[0], request); + it('should create a client with gaxServerStreamingRetries enabled', () => { + const client = new echoModule.v1beta1.EchoClient({ + gaxServerStreamingRetries: true, + }); + assert(client); + }); + }); + + describe('chat', () => { + it('invokes chat without error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.EchoRequest(), + ); + + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.EchoResponse(), + ); + client.innerApiCalls.chat = stubBidiStreamingCall(expectedResponse); + const stream = client.chat(); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + (response: protos.google.showcase.v1beta1.EchoResponse) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); }); + stream.write(request); + stream.end(); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + assert( + (client.innerApiCalls.chat as SinonStub).getCall(0).calledWith(null), + ); + assert.deepStrictEqual( + ((stream as unknown as PassThrough)._transform as SinonStub).getCall(0) + .args[0], + request, + ); + }); - it('invokes collect with error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.EchoRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.collect = stubClientStreamingCall(undefined, expectedError); - let stream: PassThrough; - const promise = new Promise((resolve, reject) => { - stream = client.collect( - (err?: Error|null, result?: protos.google.showcase.v1beta1.IEchoResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }) as unknown as PassThrough; - stream.write(request); - stream.end(); - }); - await assert.rejects(promise, expectedError); - assert((client.innerApiCalls.collect as SinonStub) - .getCall(0).calledWith(null, {} /*, callback defined above */)); + it('invokes chat with error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.EchoRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.chat = stubBidiStreamingCall( + undefined, + expectedError, + ); + const stream = client.chat(); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + (response: protos.google.showcase.v1beta1.EchoResponse) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); }); + stream.write(request); + stream.end(); + }); + await assert.rejects(promise, expectedError); + assert( + (client.innerApiCalls.chat as SinonStub).getCall(0).calledWith(null), + ); + assert.deepStrictEqual( + ((stream as unknown as PassThrough)._transform as SinonStub).getCall(0) + .args[0], + request, + ); + }); + }); + + describe('collect', () => { + it('invokes collect without error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.EchoRequest(), + ); + + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.EchoResponse(), + ); + client.innerApiCalls.collect = stubClientStreamingCall(expectedResponse); + let stream: PassThrough; + const promise = new Promise((resolve, reject) => { + stream = client.collect( + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IEchoResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ) as unknown as PassThrough; + stream.write(request); + stream.end(); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + assert( + (client.innerApiCalls.collect as SinonStub) + .getCall(0) + .calledWith(null, {} /*, callback defined above */), + ); + assert.deepStrictEqual( + (stream!._transform as SinonStub).getCall(0).args[0], + request, + ); }); - describe('pagedExpand', () => { - it('invokes pagedExpand without error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.PagedExpandRequest() - );const expectedResponse = [ - generateSampleMessage(new protos.google.showcase.v1beta1.EchoResponse()), - generateSampleMessage(new protos.google.showcase.v1beta1.EchoResponse()), - generateSampleMessage(new protos.google.showcase.v1beta1.EchoResponse()), - ]; - client.innerApiCalls.pagedExpand = stubSimpleCall(expectedResponse); - const [response] = await client.pagedExpand(request); - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes collect with error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.EchoRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.collect = stubClientStreamingCall( + undefined, + expectedError, + ); + let stream: PassThrough; + const promise = new Promise((resolve, reject) => { + stream = client.collect( + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IEchoResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ) as unknown as PassThrough; + stream.write(request); + stream.end(); + }); + await assert.rejects(promise, expectedError); + assert( + (client.innerApiCalls.collect as SinonStub) + .getCall(0) + .calledWith(null, {} /*, callback defined above */), + ); + }); + }); + + describe('pagedExpand', () => { + it('invokes pagedExpand without error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.PagedExpandRequest(), + ); + const expectedResponse = [ + generateSampleMessage( + new protos.google.showcase.v1beta1.EchoResponse(), + ), + generateSampleMessage( + new protos.google.showcase.v1beta1.EchoResponse(), + ), + generateSampleMessage( + new protos.google.showcase.v1beta1.EchoResponse(), + ), + ]; + client.innerApiCalls.pagedExpand = stubSimpleCall(expectedResponse); + const [response] = await client.pagedExpand(request); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes pagedExpand without error using callback', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.PagedExpandRequest() - );const expectedResponse = [ - generateSampleMessage(new protos.google.showcase.v1beta1.EchoResponse()), - generateSampleMessage(new protos.google.showcase.v1beta1.EchoResponse()), - generateSampleMessage(new protos.google.showcase.v1beta1.EchoResponse()), - ]; - client.innerApiCalls.pagedExpand = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.pagedExpand( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IEchoResponse[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes pagedExpand without error using callback', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.PagedExpandRequest(), + ); + const expectedResponse = [ + generateSampleMessage( + new protos.google.showcase.v1beta1.EchoResponse(), + ), + generateSampleMessage( + new protos.google.showcase.v1beta1.EchoResponse(), + ), + generateSampleMessage( + new protos.google.showcase.v1beta1.EchoResponse(), + ), + ]; + client.innerApiCalls.pagedExpand = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.pagedExpand( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IEchoResponse[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes pagedExpand with error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.PagedExpandRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.pagedExpand = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.pagedExpand(request), expectedError); - }); + it('invokes pagedExpand with error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.PagedExpandRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.pagedExpand = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.pagedExpand(request), expectedError); + }); - it('invokes pagedExpandStream without error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.PagedExpandRequest() - ); - const expectedResponse = [ - generateSampleMessage(new protos.google.showcase.v1beta1.EchoResponse()), - generateSampleMessage(new protos.google.showcase.v1beta1.EchoResponse()), - generateSampleMessage(new protos.google.showcase.v1beta1.EchoResponse()), - ]; - client.descriptors.page.pagedExpand.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.pagedExpandStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.showcase.v1beta1.EchoResponse[] = []; - stream.on('data', (response: protos.google.showcase.v1beta1.EchoResponse) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.pagedExpand.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.pagedExpand, request)); + it('invokes pagedExpandStream without error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.PagedExpandRequest(), + ); + const expectedResponse = [ + generateSampleMessage( + new protos.google.showcase.v1beta1.EchoResponse(), + ), + generateSampleMessage( + new protos.google.showcase.v1beta1.EchoResponse(), + ), + generateSampleMessage( + new protos.google.showcase.v1beta1.EchoResponse(), + ), + ]; + client.descriptors.page.pagedExpand.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.pagedExpandStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.showcase.v1beta1.EchoResponse[] = []; + stream.on( + 'data', + (response: protos.google.showcase.v1beta1.EchoResponse) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); }); - - it('invokes pagedExpandStream with error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.PagedExpandRequest() - ); - const expectedError = new Error('expected'); - client.descriptors.page.pagedExpand.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.pagedExpandStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.showcase.v1beta1.EchoResponse[] = []; - stream.on('data', (response: protos.google.showcase.v1beta1.EchoResponse) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.pagedExpand.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.pagedExpand, request)); + stream.on('error', (err: Error) => { + reject(err); }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.pagedExpand.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.pagedExpand, request), + ); + }); - it('uses async iteration with pagedExpand without error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.PagedExpandRequest() - ); - const expectedResponse = [ - generateSampleMessage(new protos.google.showcase.v1beta1.EchoResponse()), - generateSampleMessage(new protos.google.showcase.v1beta1.EchoResponse()), - generateSampleMessage(new protos.google.showcase.v1beta1.EchoResponse()), - ]; - client.descriptors.page.pagedExpand.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.showcase.v1beta1.IEchoResponse[] = []; - const iterable = client.pagedExpandAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.pagedExpand.asyncIterate as SinonStub) - .getCall(0).args[1], request); + it('invokes pagedExpandStream with error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.PagedExpandRequest(), + ); + const expectedError = new Error('expected'); + client.descriptors.page.pagedExpand.createStream = stubPageStreamingCall( + undefined, + expectedError, + ); + const stream = client.pagedExpandStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.showcase.v1beta1.EchoResponse[] = []; + stream.on( + 'data', + (response: protos.google.showcase.v1beta1.EchoResponse) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); }); - - it('uses async iteration with pagedExpand with error', async () => { - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.PagedExpandRequest() - ); - const expectedError = new Error('expected'); - client.descriptors.page.pagedExpand.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.pagedExpandAsync(request); - await assert.rejects(async () => { - const responses: protos.google.showcase.v1beta1.IEchoResponse[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.pagedExpand.asyncIterate as SinonStub) - .getCall(0).args[1], request); + stream.on('error', (err: Error) => { + reject(err); }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.pagedExpand.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.pagedExpand, request), + ); }); + it('uses async iteration with pagedExpand without error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.PagedExpandRequest(), + ); + const expectedResponse = [ + generateSampleMessage( + new protos.google.showcase.v1beta1.EchoResponse(), + ), + generateSampleMessage( + new protos.google.showcase.v1beta1.EchoResponse(), + ), + generateSampleMessage( + new protos.google.showcase.v1beta1.EchoResponse(), + ), + ]; + client.descriptors.page.pagedExpand.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.showcase.v1beta1.IEchoResponse[] = []; + const iterable = client.pagedExpandAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + (client.descriptors.page.pagedExpand.asyncIterate as SinonStub).getCall( + 0, + ).args[1], + request, + ); + }); - describe('Path templates', () => { - - describe('blueprint', async () => { - const fakePath = "/rendered/path/blueprint"; - const expectedParameters = { - session: "sessionValue", - test: "testValue", - blueprint: "blueprintValue", - }; - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.blueprintPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.blueprintPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('blueprintPath', () => { - const result = client.blueprintPath("sessionValue", "testValue", "blueprintValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.blueprintPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchSessionFromBlueprintName', () => { - const result = client.matchSessionFromBlueprintName(fakePath); - assert.strictEqual(result, "sessionValue"); - assert((client.pathTemplates.blueprintPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchTestFromBlueprintName', () => { - const result = client.matchTestFromBlueprintName(fakePath); - assert.strictEqual(result, "testValue"); - assert((client.pathTemplates.blueprintPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBlueprintFromBlueprintName', () => { - const result = client.matchBlueprintFromBlueprintName(fakePath); - assert.strictEqual(result, "blueprintValue"); - assert((client.pathTemplates.blueprintPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('uses async iteration with pagedExpand with error', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.PagedExpandRequest(), + ); + const expectedError = new Error('expected'); + client.descriptors.page.pagedExpand.asyncIterate = stubAsyncIterationCall( + undefined, + expectedError, + ); + const iterable = client.pagedExpandAsync(request); + await assert.rejects(async () => { + const responses: protos.google.showcase.v1beta1.IEchoResponse[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + (client.descriptors.page.pagedExpand.asyncIterate as SinonStub).getCall( + 0, + ).args[1], + request, + ); + }); + }); + + describe('Path templates', () => { + describe('blueprint', async () => { + const fakePath = '/rendered/path/blueprint'; + const expectedParameters = { + session: 'sessionValue', + test: 'testValue', + blueprint: 'blueprintValue', + }; + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.blueprintPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.blueprintPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('blueprintPath', () => { + const result = client.blueprintPath( + 'sessionValue', + 'testValue', + 'blueprintValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.blueprintPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchSessionFromBlueprintName', () => { + const result = client.matchSessionFromBlueprintName(fakePath); + assert.strictEqual(result, 'sessionValue'); + assert( + (client.pathTemplates.blueprintPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchTestFromBlueprintName', () => { + const result = client.matchTestFromBlueprintName(fakePath); + assert.strictEqual(result, 'testValue'); + assert( + (client.pathTemplates.blueprintPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBlueprintFromBlueprintName', () => { + const result = client.matchBlueprintFromBlueprintName(fakePath); + assert.strictEqual(result, 'blueprintValue'); + assert( + (client.pathTemplates.blueprintPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('room', async () => { - const fakePath = "/rendered/path/room"; - const expectedParameters = { - room: "roomValue", - }; - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.roomPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.roomPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('roomPath', () => { - const result = client.roomPath("roomValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.roomPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchRoomFromRoomName', () => { - const result = client.matchRoomFromRoomName(fakePath); - assert.strictEqual(result, "roomValue"); - assert((client.pathTemplates.roomPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('room', async () => { + const fakePath = '/rendered/path/room'; + const expectedParameters = { + room: 'roomValue', + }; + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.roomPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.roomPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('roomPath', () => { + const result = client.roomPath('roomValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.roomPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchRoomFromRoomName', () => { + const result = client.matchRoomFromRoomName(fakePath); + assert.strictEqual(result, 'roomValue'); + assert( + (client.pathTemplates.roomPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('roomBlurb', async () => { - const fakePath = "/rendered/path/roomBlurb"; - const expectedParameters = { - room: "roomValue", - blurb: "blurbValue", - }; - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.roomBlurbPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.roomBlurbPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('roomBlurbPath', () => { - const result = client.roomBlurbPath("roomValue", "blurbValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.roomBlurbPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchRoomFromRoomBlurbName', () => { - const result = client.matchRoomFromRoomBlurbName(fakePath); - assert.strictEqual(result, "roomValue"); - assert((client.pathTemplates.roomBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBlurbFromRoomBlurbName', () => { - const result = client.matchBlurbFromRoomBlurbName(fakePath); - assert.strictEqual(result, "blurbValue"); - assert((client.pathTemplates.roomBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('roomBlurb', async () => { + const fakePath = '/rendered/path/roomBlurb'; + const expectedParameters = { + room: 'roomValue', + blurb: 'blurbValue', + }; + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.roomBlurbPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.roomBlurbPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('roomBlurbPath', () => { + const result = client.roomBlurbPath('roomValue', 'blurbValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.roomBlurbPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchRoomFromRoomBlurbName', () => { + const result = client.matchRoomFromRoomBlurbName(fakePath); + assert.strictEqual(result, 'roomValue'); + assert( + (client.pathTemplates.roomBlurbPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBlurbFromRoomBlurbName', () => { + const result = client.matchBlurbFromRoomBlurbName(fakePath); + assert.strictEqual(result, 'blurbValue'); + assert( + (client.pathTemplates.roomBlurbPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('roomBlurbsLegacyRoomBlurb', async () => { - const fakePath = "/rendered/path/roomBlurbsLegacyRoomBlurb"; - const expectedParameters = { - room: "roomValue", - legacy_room: "legacyRoomValue", - blurb: "blurbValue", - }; - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('roomBlurbsLegacyRoomBlurbPath', () => { - const result = client.roomBlurbsLegacyRoomBlurbPath("roomValue", "legacyRoomValue", "blurbValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchRoomFromRoomBlurbsLegacyRoomBlurbName', () => { - const result = client.matchRoomFromRoomBlurbsLegacyRoomBlurbName(fakePath); - assert.strictEqual(result, "roomValue"); - assert((client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName', () => { - const result = client.matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName(fakePath); - assert.strictEqual(result, "legacyRoomValue"); - assert((client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBlurbFromRoomBlurbsLegacyRoomBlurbName', () => { - const result = client.matchBlurbFromRoomBlurbsLegacyRoomBlurbName(fakePath); - assert.strictEqual(result, "blurbValue"); - assert((client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('roomBlurbsLegacyRoomBlurb', async () => { + const fakePath = '/rendered/path/roomBlurbsLegacyRoomBlurb'; + const expectedParameters = { + room: 'roomValue', + legacy_room: 'legacyRoomValue', + blurb: 'blurbValue', + }; + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('roomBlurbsLegacyRoomBlurbPath', () => { + const result = client.roomBlurbsLegacyRoomBlurbPath( + 'roomValue', + 'legacyRoomValue', + 'blurbValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchRoomFromRoomBlurbsLegacyRoomBlurbName', () => { + const result = + client.matchRoomFromRoomBlurbsLegacyRoomBlurbName(fakePath); + assert.strictEqual(result, 'roomValue'); + assert( + ( + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName', () => { + const result = + client.matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName(fakePath); + assert.strictEqual(result, 'legacyRoomValue'); + assert( + ( + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBlurbFromRoomBlurbsLegacyRoomBlurbName', () => { + const result = + client.matchBlurbFromRoomBlurbsLegacyRoomBlurbName(fakePath); + assert.strictEqual(result, 'blurbValue'); + assert( + ( + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('sequence', async () => { - const fakePath = "/rendered/path/sequence"; - const expectedParameters = { - sequence: "sequenceValue", - }; - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.sequencePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.sequencePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('sequencePath', () => { - const result = client.sequencePath("sequenceValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.sequencePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchSequenceFromSequenceName', () => { - const result = client.matchSequenceFromSequenceName(fakePath); - assert.strictEqual(result, "sequenceValue"); - assert((client.pathTemplates.sequencePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('sequence', async () => { + const fakePath = '/rendered/path/sequence'; + const expectedParameters = { + sequence: 'sequenceValue', + }; + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.sequencePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.sequencePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('sequencePath', () => { + const result = client.sequencePath('sequenceValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.sequencePathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchSequenceFromSequenceName', () => { + const result = client.matchSequenceFromSequenceName(fakePath); + assert.strictEqual(result, 'sequenceValue'); + assert( + (client.pathTemplates.sequencePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('sequenceReport', async () => { - const fakePath = "/rendered/path/sequenceReport"; - const expectedParameters = { - sequence: "sequenceValue", - }; - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.sequenceReportPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.sequenceReportPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('sequenceReportPath', () => { - const result = client.sequenceReportPath("sequenceValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.sequenceReportPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchSequenceFromSequenceReportName', () => { - const result = client.matchSequenceFromSequenceReportName(fakePath); - assert.strictEqual(result, "sequenceValue"); - assert((client.pathTemplates.sequenceReportPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('sequenceReport', async () => { + const fakePath = '/rendered/path/sequenceReport'; + const expectedParameters = { + sequence: 'sequenceValue', + }; + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.sequenceReportPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.sequenceReportPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('sequenceReportPath', () => { + const result = client.sequenceReportPath('sequenceValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.sequenceReportPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchSequenceFromSequenceReportName', () => { + const result = client.matchSequenceFromSequenceReportName(fakePath); + assert.strictEqual(result, 'sequenceValue'); + assert( + (client.pathTemplates.sequenceReportPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('session', async () => { - const fakePath = "/rendered/path/session"; - const expectedParameters = { - session: "sessionValue", - }; - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.sessionPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.sessionPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('sessionPath', () => { - const result = client.sessionPath("sessionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.sessionPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchSessionFromSessionName', () => { - const result = client.matchSessionFromSessionName(fakePath); - assert.strictEqual(result, "sessionValue"); - assert((client.pathTemplates.sessionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('session', async () => { + const fakePath = '/rendered/path/session'; + const expectedParameters = { + session: 'sessionValue', + }; + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.sessionPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.sessionPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('sessionPath', () => { + const result = client.sessionPath('sessionValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.sessionPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchSessionFromSessionName', () => { + const result = client.matchSessionFromSessionName(fakePath); + assert.strictEqual(result, 'sessionValue'); + assert( + (client.pathTemplates.sessionPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('test', async () => { - const fakePath = "/rendered/path/test"; - const expectedParameters = { - session: "sessionValue", - test: "testValue", - }; - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.testPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.testPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('testPath', () => { - const result = client.testPath("sessionValue", "testValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.testPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchSessionFromTestName', () => { - const result = client.matchSessionFromTestName(fakePath); - assert.strictEqual(result, "sessionValue"); - assert((client.pathTemplates.testPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchTestFromTestName', () => { - const result = client.matchTestFromTestName(fakePath); - assert.strictEqual(result, "testValue"); - assert((client.pathTemplates.testPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('test', async () => { + const fakePath = '/rendered/path/test'; + const expectedParameters = { + session: 'sessionValue', + test: 'testValue', + }; + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.testPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.testPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('testPath', () => { + const result = client.testPath('sessionValue', 'testValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.testPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchSessionFromTestName', () => { + const result = client.matchSessionFromTestName(fakePath); + assert.strictEqual(result, 'sessionValue'); + assert( + (client.pathTemplates.testPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchTestFromTestName', () => { + const result = client.matchTestFromTestName(fakePath); + assert.strictEqual(result, 'testValue'); + assert( + (client.pathTemplates.testPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('user', async () => { - const fakePath = "/rendered/path/user"; - const expectedParameters = { - user: "userValue", - }; - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.userPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.userPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('userPath', () => { - const result = client.userPath("userValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.userPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchUserFromUserName', () => { - const result = client.matchUserFromUserName(fakePath); - assert.strictEqual(result, "userValue"); - assert((client.pathTemplates.userPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('user', async () => { + const fakePath = '/rendered/path/user'; + const expectedParameters = { + user: 'userValue', + }; + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.userPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.userPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('userPath', () => { + const result = client.userPath('userValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.userPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchUserFromUserName', () => { + const result = client.matchUserFromUserName(fakePath); + assert.strictEqual(result, 'userValue'); + assert( + (client.pathTemplates.userPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('userProfileBlurb', async () => { - const fakePath = "/rendered/path/userProfileBlurb"; - const expectedParameters = { - user: "userValue", - blurb: "blurbValue", - }; - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.userProfileBlurbPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.userProfileBlurbPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('userProfileBlurbPath', () => { - const result = client.userProfileBlurbPath("userValue", "blurbValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.userProfileBlurbPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchUserFromUserProfileBlurbName', () => { - const result = client.matchUserFromUserProfileBlurbName(fakePath); - assert.strictEqual(result, "userValue"); - assert((client.pathTemplates.userProfileBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBlurbFromUserProfileBlurbName', () => { - const result = client.matchBlurbFromUserProfileBlurbName(fakePath); - assert.strictEqual(result, "blurbValue"); - assert((client.pathTemplates.userProfileBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('userProfileBlurb', async () => { + const fakePath = '/rendered/path/userProfileBlurb'; + const expectedParameters = { + user: 'userValue', + blurb: 'blurbValue', + }; + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.userProfileBlurbPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.userProfileBlurbPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('userProfileBlurbPath', () => { + const result = client.userProfileBlurbPath('userValue', 'blurbValue'); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.userProfileBlurbPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchUserFromUserProfileBlurbName', () => { + const result = client.matchUserFromUserProfileBlurbName(fakePath); + assert.strictEqual(result, 'userValue'); + assert( + (client.pathTemplates.userProfileBlurbPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBlurbFromUserProfileBlurbName', () => { + const result = client.matchBlurbFromUserProfileBlurbName(fakePath); + assert.strictEqual(result, 'blurbValue'); + assert( + (client.pathTemplates.userProfileBlurbPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('userProfileBlurbsLegacyUserBlurb', async () => { - const fakePath = "/rendered/path/userProfileBlurbsLegacyUserBlurb"; - const expectedParameters = { - user: "userValue", - legacy_user: "legacyUserValue", - blurb: "blurbValue", - }; - const client = new echoModule.v1beta1.EchoClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('userProfileBlurbsLegacyUserBlurbPath', () => { - const result = client.userProfileBlurbsLegacyUserBlurbPath("userValue", "legacyUserValue", "blurbValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchUserFromUserProfileBlurbsLegacyUserBlurbName', () => { - const result = client.matchUserFromUserProfileBlurbsLegacyUserBlurbName(fakePath); - assert.strictEqual(result, "userValue"); - assert((client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName', () => { - const result = client.matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName(fakePath); - assert.strictEqual(result, "legacyUserValue"); - assert((client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBlurbFromUserProfileBlurbsLegacyUserBlurbName', () => { - const result = client.matchBlurbFromUserProfileBlurbsLegacyUserBlurbName(fakePath); - assert.strictEqual(result, "blurbValue"); - assert((client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('userProfileBlurbsLegacyUserBlurb', async () => { + const fakePath = '/rendered/path/userProfileBlurbsLegacyUserBlurb'; + const expectedParameters = { + user: 'userValue', + legacy_user: 'legacyUserValue', + blurb: 'blurbValue', + }; + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('userProfileBlurbsLegacyUserBlurbPath', () => { + const result = client.userProfileBlurbsLegacyUserBlurbPath( + 'userValue', + 'legacyUserValue', + 'blurbValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchUserFromUserProfileBlurbsLegacyUserBlurbName', () => { + const result = + client.matchUserFromUserProfileBlurbsLegacyUserBlurbName(fakePath); + assert.strictEqual(result, 'userValue'); + assert( + ( + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName', () => { + const result = + client.matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName( + fakePath, + ); + assert.strictEqual(result, 'legacyUserValue'); + assert( + ( + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBlurbFromUserProfileBlurbsLegacyUserBlurbName', () => { + const result = + client.matchBlurbFromUserProfileBlurbsLegacyUserBlurbName(fakePath); + assert.strictEqual(result, 'blurbValue'); + assert( + ( + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/core/generator/gapic-generator-typescript/baselines/showcase/test/gapic_identity_v1beta1.ts.baseline b/core/generator/gapic-generator-typescript/baselines/showcase/test/gapic_identity_v1beta1.ts.baseline index b938f6196ed4..ca7f5f649db0 100644 --- a/core/generator/gapic-generator-typescript/baselines/showcase/test/gapic_identity_v1beta1.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/showcase/test/gapic_identity_v1beta1.ts.baseline @@ -19,1185 +19,1498 @@ import * as protos from '../protos/protos'; import * as assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as identityModule from '../src'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; -import {protobuf} from 'google-gax'; +import { protobuf } from 'google-gax'; // Dynamically loaded proto JSON is needed to get the type information // to fill in default values for request objects -const root = protobuf.Root.fromJSON(require('../protos/protos.json')).resolveAll(); +const root = protobuf.Root.fromJSON( + require('../protos/protos.json'), +).resolveAll(); // eslint-disable-next-line @typescript-eslint/no-unused-vars function getTypeDefaultValue(typeName: string, fields: string[]) { - let type = root.lookupType(typeName) as protobuf.Type; - for (const field of fields.slice(0, -1)) { - type = type.fields[field]?.resolvedType as protobuf.Type; - } - return type.fields[fields[fields.length - 1]]?.defaultValue; + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type.fields[field]?.resolvedType as protobuf.Type; + } + return type.fields[fields[fields.length - 1]]?.defaultValue; } function generateSampleMessage(instance: T) { - const filledObject = (instance.constructor as typeof protobuf.Message) - .toObject(instance as protobuf.Message, {defaults: true}); - return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, { defaults: true }); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; } function stubSimpleCall(response?: ResponseType, error?: Error) { - return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); } -function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { - return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +function stubSimpleCallWithCallback( + response?: ResponseType, + error?: Error, +) { + return error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); } -function stubPageStreamingCall(responses?: ResponseType[], error?: Error) { - const pagingStub = sinon.stub(); - if (responses) { - for (let i = 0; i < responses.length; ++i) { - pagingStub.onCall(i).callsArgWith(2, null, responses[i]); - } +function stubPageStreamingCall( + responses?: ResponseType[], + error?: Error, +) { + const pagingStub = sinon.stub(); + if (responses) { + for (let i = 0; i < responses.length; ++i) { + pagingStub.onCall(i).callsArgWith(2, null, responses[i]); } - const transformStub = error ? sinon.stub().callsArgWith(2, error) : pagingStub; - const mockStream = new PassThrough({ - objectMode: true, - transform: transformStub, - }); - // trigger as many responses as needed - if (responses) { - for (let i = 0; i < responses.length; ++i) { - setImmediate(() => { mockStream.write({}); }); - } - setImmediate(() => { mockStream.end(); }); - } else { - setImmediate(() => { mockStream.write({}); }); - setImmediate(() => { mockStream.end(); }); + } + const transformStub = error + ? sinon.stub().callsArgWith(2, error) + : pagingStub; + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + // trigger as many responses as needed + if (responses) { + for (let i = 0; i < responses.length; ++i) { + setImmediate(() => { + mockStream.write({}); + }); } - return sinon.stub().returns(mockStream); + setImmediate(() => { + mockStream.end(); + }); + } else { + setImmediate(() => { + mockStream.write({}); + }); + setImmediate(() => { + mockStream.end(); + }); + } + return sinon.stub().returns(mockStream); } -function stubAsyncIterationCall(responses?: ResponseType[], error?: Error) { - let counter = 0; - const asyncIterable = { - [Symbol.asyncIterator]() { - return { - async next() { - if (error) { - return Promise.reject(error); - } - if (counter >= responses!.length) { - return Promise.resolve({done: true, value: undefined}); - } - return Promise.resolve({done: false, value: responses![counter++]}); - } - }; - } - }; - return sinon.stub().returns(asyncIterable); +function stubAsyncIterationCall( + responses?: ResponseType[], + error?: Error, +) { + let counter = 0; + const asyncIterable = { + [Symbol.asyncIterator]() { + return { + async next() { + if (error) { + return Promise.reject(error); + } + if (counter >= responses!.length) { + return Promise.resolve({ done: true, value: undefined }); + } + return Promise.resolve({ done: false, value: responses![counter++] }); + }, + }; + }, + }; + return sinon.stub().returns(asyncIterable); } describe('v1beta1.IdentityClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new identityModule.v1beta1.IdentityClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'localhost'); - }); - - it('has universeDomain', () => { - const client = new identityModule.v1beta1.IdentityClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); - - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - it('throws DeprecationWarning if static servicePath is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const servicePath = identityModule.v1beta1.IdentityClient.servicePath; - assert.strictEqual(servicePath, 'localhost'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = identityModule.v1beta1.IdentityClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'localhost'); - assert(stub.called); - stub.restore(); - }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { new identityModule.v1beta1.IdentityClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new identityModule.v1beta1.IdentityClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'localhost'); + }); - it('has port', () => { - const port = identityModule.v1beta1.IdentityClient.port; - assert(port); - assert(typeof port === 'number'); - }); + it('has universeDomain', () => { + const client = new identityModule.v1beta1.IdentityClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - it('should create a client with no option', () => { - const client = new identityModule.v1beta1.IdentityClient(); - assert(client); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = identityModule.v1beta1.IdentityClient.servicePath; + assert.strictEqual(servicePath, 'localhost'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = identityModule.v1beta1.IdentityClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'localhost'); + assert(stub.called); + stub.restore(); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new identityModule.v1beta1.IdentityClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); + }); - it('should create a client with gRPC fallback', () => { - const client = new identityModule.v1beta1.IdentityClient({ - fallback: true, - }); - assert(client); - }); + it('has port', () => { + const port = identityModule.v1beta1.IdentityClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('has initialize method and supports deferred initialization', async () => { - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.identityStub, undefined); - await client.initialize(); - assert(client.identityStub); - }); + it('should create a client with no option', () => { + const client = new identityModule.v1beta1.IdentityClient(); + assert(client); + }); - it('has close method for the initialized client', done => { - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.identityStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('should create a client with gRPC fallback', () => { + const client = new identityModule.v1beta1.IdentityClient({ + fallback: true, + }); + assert(client); + }); - it('has close method for the non-initialized client', done => { - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.identityStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('has initialize method and supports deferred initialization', async () => { + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.identityStub, undefined); + await client.initialize(); + assert(client.identityStub); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + it('has close method for the initialized client', (done) => { + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.identityStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId((err?: Error|null, projectId?: string|null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } - }); - }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); + it('has close method for the non-initialized client', (done) => { + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.identityStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); }); - describe('createUser', () => { - it('invokes createUser without error', async () => { - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.CreateUserRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.User() - ); - client.innerApiCalls.createUser = stubSimpleCall(expectedResponse); - const [response] = await client.createUser(request); - assert.deepStrictEqual(response, expectedResponse); - }); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + }); - it('invokes createUser without error using callback', async () => { - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.CreateUserRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.User() - ); - client.innerApiCalls.createUser = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createUser( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IUser|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + }); + + describe('createUser', () => { + it('invokes createUser without error', async () => { + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.CreateUserRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.User(), + ); + client.innerApiCalls.createUser = stubSimpleCall(expectedResponse); + const [response] = await client.createUser(request); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes createUser with error', async () => { - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.CreateUserRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.createUser = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createUser(request), expectedError); - }); + it('invokes createUser without error using callback', async () => { + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.CreateUserRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.User(), + ); + client.innerApiCalls.createUser = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createUser( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IUser | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes createUser with closed client', async () => { - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.CreateUserRequest() - ); - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createUser(request), expectedError); - }); + it('invokes createUser with error', async () => { + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.CreateUserRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.createUser = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.createUser(request), expectedError); }); - describe('getUser', () => { - it('invokes getUser without error', async () => { - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.GetUserRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.GetUserRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.User() - ); - client.innerApiCalls.getUser = stubSimpleCall(expectedResponse); - const [response] = await client.getUser(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getUser as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getUser as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createUser with closed client', async () => { + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.CreateUserRequest(), + ); + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.createUser(request), expectedError); + }); + }); + + describe('getUser', () => { + it('invokes getUser without error', async () => { + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.GetUserRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.GetUserRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.User(), + ); + client.innerApiCalls.getUser = stubSimpleCall(expectedResponse); + const [response] = await client.getUser(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.getUser as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getUser as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getUser without error using callback', async () => { - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.GetUserRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.GetUserRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.User() - ); - client.innerApiCalls.getUser = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getUser( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IUser|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getUser as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getUser as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getUser without error using callback', async () => { + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.GetUserRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.GetUserRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.User(), + ); + client.innerApiCalls.getUser = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getUser( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IUser | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.getUser as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getUser as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getUser with error', async () => { - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.GetUserRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.GetUserRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getUser = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getUser(request), expectedError); - const actualRequest = (client.innerApiCalls.getUser as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getUser as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getUser with error', async () => { + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.GetUserRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.GetUserRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getUser = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.getUser(request), expectedError); + const actualRequest = (client.innerApiCalls.getUser as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getUser as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getUser with closed client', async () => { - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.GetUserRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.GetUserRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getUser(request), expectedError); - }); + it('invokes getUser with closed client', async () => { + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.GetUserRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.GetUserRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getUser(request), expectedError); + }); + }); + + describe('updateUser', () => { + it('invokes updateUser without error', async () => { + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.UpdateUserRequest(), + ); + request.user ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.UpdateUserRequest', + ['user', 'name'], + ); + request.user.name = defaultValue1; + const expectedHeaderRequestParams = `user.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.User(), + ); + client.innerApiCalls.updateUser = stubSimpleCall(expectedResponse); + const [response] = await client.updateUser(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateUser as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateUser as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('updateUser', () => { - it('invokes updateUser without error', async () => { - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.UpdateUserRequest() - ); - request.user ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.UpdateUserRequest', ['user', 'name']); - request.user.name = defaultValue1; - const expectedHeaderRequestParams = `user.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.User() - ); - client.innerApiCalls.updateUser = stubSimpleCall(expectedResponse); - const [response] = await client.updateUser(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateUser as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateUser as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateUser without error using callback', async () => { + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.UpdateUserRequest(), + ); + request.user ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.UpdateUserRequest', + ['user', 'name'], + ); + request.user.name = defaultValue1; + const expectedHeaderRequestParams = `user.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.User(), + ); + client.innerApiCalls.updateUser = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateUser( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IUser | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateUser as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateUser as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateUser without error using callback', async () => { - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.UpdateUserRequest() - ); - request.user ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.UpdateUserRequest', ['user', 'name']); - request.user.name = defaultValue1; - const expectedHeaderRequestParams = `user.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.User() - ); - client.innerApiCalls.updateUser = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateUser( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IUser|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateUser as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateUser as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateUser with error', async () => { + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.UpdateUserRequest(), + ); + request.user ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.UpdateUserRequest', + ['user', 'name'], + ); + request.user.name = defaultValue1; + const expectedHeaderRequestParams = `user.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateUser = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.updateUser(request), expectedError); + const actualRequest = ( + client.innerApiCalls.updateUser as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateUser as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateUser with error', async () => { - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.UpdateUserRequest() - ); - request.user ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.UpdateUserRequest', ['user', 'name']); - request.user.name = defaultValue1; - const expectedHeaderRequestParams = `user.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateUser = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateUser(request), expectedError); - const actualRequest = (client.innerApiCalls.updateUser as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateUser as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateUser with closed client', async () => { + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.UpdateUserRequest(), + ); + request.user ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.UpdateUserRequest', + ['user', 'name'], + ); + request.user.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.updateUser(request), expectedError); + }); + }); + + describe('deleteUser', () => { + it('invokes deleteUser without error', async () => { + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.DeleteUserRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.DeleteUserRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteUser = stubSimpleCall(expectedResponse); + const [response] = await client.deleteUser(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteUser as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteUser as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateUser with closed client', async () => { - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.UpdateUserRequest() - ); - request.user ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.UpdateUserRequest', ['user', 'name']); - request.user.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateUser(request), expectedError); - }); + it('invokes deleteUser without error using callback', async () => { + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.DeleteUserRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.DeleteUserRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteUser = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteUser( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteUser as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteUser as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('deleteUser', () => { - it('invokes deleteUser without error', async () => { - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.DeleteUserRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.DeleteUserRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteUser = stubSimpleCall(expectedResponse); - const [response] = await client.deleteUser(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteUser as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteUser as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteUser with error', async () => { + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.DeleteUserRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.DeleteUserRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteUser = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.deleteUser(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteUser as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteUser as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteUser without error using callback', async () => { - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.DeleteUserRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.DeleteUserRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteUser = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteUser( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteUser as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteUser as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteUser with closed client', async () => { + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.DeleteUserRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.DeleteUserRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.deleteUser(request), expectedError); + }); + }); + + describe('listUsers', () => { + it('invokes listUsers without error', async () => { + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListUsersRequest(), + ); + const expectedResponse = [ + generateSampleMessage(new protos.google.showcase.v1beta1.User()), + generateSampleMessage(new protos.google.showcase.v1beta1.User()), + generateSampleMessage(new protos.google.showcase.v1beta1.User()), + ]; + client.innerApiCalls.listUsers = stubSimpleCall(expectedResponse); + const [response] = await client.listUsers(request); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes deleteUser with error', async () => { - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.DeleteUserRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.DeleteUserRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteUser = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteUser(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteUser as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteUser as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listUsers without error using callback', async () => { + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListUsersRequest(), + ); + const expectedResponse = [ + generateSampleMessage(new protos.google.showcase.v1beta1.User()), + generateSampleMessage(new protos.google.showcase.v1beta1.User()), + generateSampleMessage(new protos.google.showcase.v1beta1.User()), + ]; + client.innerApiCalls.listUsers = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listUsers( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IUser[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes deleteUser with closed client', async () => { - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.DeleteUserRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.DeleteUserRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteUser(request), expectedError); - }); + it('invokes listUsers with error', async () => { + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListUsersRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.listUsers = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.listUsers(request), expectedError); }); - describe('listUsers', () => { - it('invokes listUsers without error', async () => { - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListUsersRequest() - );const expectedResponse = [ - generateSampleMessage(new protos.google.showcase.v1beta1.User()), - generateSampleMessage(new protos.google.showcase.v1beta1.User()), - generateSampleMessage(new protos.google.showcase.v1beta1.User()), - ]; - client.innerApiCalls.listUsers = stubSimpleCall(expectedResponse); - const [response] = await client.listUsers(request); - assert.deepStrictEqual(response, expectedResponse); + it('invokes listUsersStream without error', async () => { + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListUsersRequest(), + ); + const expectedResponse = [ + generateSampleMessage(new protos.google.showcase.v1beta1.User()), + generateSampleMessage(new protos.google.showcase.v1beta1.User()), + generateSampleMessage(new protos.google.showcase.v1beta1.User()), + ]; + client.descriptors.page.listUsers.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listUsersStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.showcase.v1beta1.User[] = []; + stream.on('data', (response: protos.google.showcase.v1beta1.User) => { + responses.push(response); }); - - it('invokes listUsers without error using callback', async () => { - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListUsersRequest() - );const expectedResponse = [ - generateSampleMessage(new protos.google.showcase.v1beta1.User()), - generateSampleMessage(new protos.google.showcase.v1beta1.User()), - generateSampleMessage(new protos.google.showcase.v1beta1.User()), - ]; - client.innerApiCalls.listUsers = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listUsers( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IUser[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); + stream.on('end', () => { + resolve(responses); }); - - it('invokes listUsers with error', async () => { - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListUsersRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.listUsers = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listUsers(request), expectedError); + stream.on('error', (err: Error) => { + reject(err); }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listUsers.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listUsers, request), + ); + }); - it('invokes listUsersStream without error', async () => { - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListUsersRequest() - ); - const expectedResponse = [ - generateSampleMessage(new protos.google.showcase.v1beta1.User()), - generateSampleMessage(new protos.google.showcase.v1beta1.User()), - generateSampleMessage(new protos.google.showcase.v1beta1.User()), - ]; - client.descriptors.page.listUsers.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listUsersStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.showcase.v1beta1.User[] = []; - stream.on('data', (response: protos.google.showcase.v1beta1.User) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.listUsers.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listUsers, request)); + it('invokes listUsersStream with error', async () => { + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListUsersRequest(), + ); + const expectedError = new Error('expected'); + client.descriptors.page.listUsers.createStream = stubPageStreamingCall( + undefined, + expectedError, + ); + const stream = client.listUsersStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.showcase.v1beta1.User[] = []; + stream.on('data', (response: protos.google.showcase.v1beta1.User) => { + responses.push(response); }); - - it('invokes listUsersStream with error', async () => { - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListUsersRequest() - ); - const expectedError = new Error('expected'); - client.descriptors.page.listUsers.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listUsersStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.showcase.v1beta1.User[] = []; - stream.on('data', (response: protos.google.showcase.v1beta1.User) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listUsers.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listUsers, request)); + stream.on('end', () => { + resolve(responses); }); - - it('uses async iteration with listUsers without error', async () => { - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListUsersRequest() - ); - const expectedResponse = [ - generateSampleMessage(new protos.google.showcase.v1beta1.User()), - generateSampleMessage(new protos.google.showcase.v1beta1.User()), - generateSampleMessage(new protos.google.showcase.v1beta1.User()), - ]; - client.descriptors.page.listUsers.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.showcase.v1beta1.IUser[] = []; - const iterable = client.listUsersAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listUsers.asyncIterate as SinonStub) - .getCall(0).args[1], request); + stream.on('error', (err: Error) => { + reject(err); }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listUsers.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listUsers, request), + ); + }); - it('uses async iteration with listUsers with error', async () => { - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListUsersRequest() - ); - const expectedError = new Error('expected'); - client.descriptors.page.listUsers.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listUsersAsync(request); - await assert.rejects(async () => { - const responses: protos.google.showcase.v1beta1.IUser[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listUsers.asyncIterate as SinonStub) - .getCall(0).args[1], request); - }); + it('uses async iteration with listUsers without error', async () => { + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListUsersRequest(), + ); + const expectedResponse = [ + generateSampleMessage(new protos.google.showcase.v1beta1.User()), + generateSampleMessage(new protos.google.showcase.v1beta1.User()), + generateSampleMessage(new protos.google.showcase.v1beta1.User()), + ]; + client.descriptors.page.listUsers.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.showcase.v1beta1.IUser[] = []; + const iterable = client.listUsersAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + (client.descriptors.page.listUsers.asyncIterate as SinonStub).getCall(0) + .args[1], + request, + ); }); - describe('Path templates', () => { - - describe('blueprint', async () => { - const fakePath = "/rendered/path/blueprint"; - const expectedParameters = { - session: "sessionValue", - test: "testValue", - blueprint: "blueprintValue", - }; - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.blueprintPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.blueprintPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('blueprintPath', () => { - const result = client.blueprintPath("sessionValue", "testValue", "blueprintValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.blueprintPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchSessionFromBlueprintName', () => { - const result = client.matchSessionFromBlueprintName(fakePath); - assert.strictEqual(result, "sessionValue"); - assert((client.pathTemplates.blueprintPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchTestFromBlueprintName', () => { - const result = client.matchTestFromBlueprintName(fakePath); - assert.strictEqual(result, "testValue"); - assert((client.pathTemplates.blueprintPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBlueprintFromBlueprintName', () => { - const result = client.matchBlueprintFromBlueprintName(fakePath); - assert.strictEqual(result, "blueprintValue"); - assert((client.pathTemplates.blueprintPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('uses async iteration with listUsers with error', async () => { + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListUsersRequest(), + ); + const expectedError = new Error('expected'); + client.descriptors.page.listUsers.asyncIterate = stubAsyncIterationCall( + undefined, + expectedError, + ); + const iterable = client.listUsersAsync(request); + await assert.rejects(async () => { + const responses: protos.google.showcase.v1beta1.IUser[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + (client.descriptors.page.listUsers.asyncIterate as SinonStub).getCall(0) + .args[1], + request, + ); + }); + }); + + describe('Path templates', () => { + describe('blueprint', async () => { + const fakePath = '/rendered/path/blueprint'; + const expectedParameters = { + session: 'sessionValue', + test: 'testValue', + blueprint: 'blueprintValue', + }; + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.blueprintPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.blueprintPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('blueprintPath', () => { + const result = client.blueprintPath( + 'sessionValue', + 'testValue', + 'blueprintValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.blueprintPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchSessionFromBlueprintName', () => { + const result = client.matchSessionFromBlueprintName(fakePath); + assert.strictEqual(result, 'sessionValue'); + assert( + (client.pathTemplates.blueprintPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchTestFromBlueprintName', () => { + const result = client.matchTestFromBlueprintName(fakePath); + assert.strictEqual(result, 'testValue'); + assert( + (client.pathTemplates.blueprintPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBlueprintFromBlueprintName', () => { + const result = client.matchBlueprintFromBlueprintName(fakePath); + assert.strictEqual(result, 'blueprintValue'); + assert( + (client.pathTemplates.blueprintPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('room', async () => { - const fakePath = "/rendered/path/room"; - const expectedParameters = { - room: "roomValue", - }; - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.roomPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.roomPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('roomPath', () => { - const result = client.roomPath("roomValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.roomPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchRoomFromRoomName', () => { - const result = client.matchRoomFromRoomName(fakePath); - assert.strictEqual(result, "roomValue"); - assert((client.pathTemplates.roomPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('room', async () => { + const fakePath = '/rendered/path/room'; + const expectedParameters = { + room: 'roomValue', + }; + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.roomPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.roomPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('roomPath', () => { + const result = client.roomPath('roomValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.roomPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchRoomFromRoomName', () => { + const result = client.matchRoomFromRoomName(fakePath); + assert.strictEqual(result, 'roomValue'); + assert( + (client.pathTemplates.roomPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('roomBlurb', async () => { - const fakePath = "/rendered/path/roomBlurb"; - const expectedParameters = { - room: "roomValue", - blurb: "blurbValue", - }; - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.roomBlurbPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.roomBlurbPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('roomBlurbPath', () => { - const result = client.roomBlurbPath("roomValue", "blurbValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.roomBlurbPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchRoomFromRoomBlurbName', () => { - const result = client.matchRoomFromRoomBlurbName(fakePath); - assert.strictEqual(result, "roomValue"); - assert((client.pathTemplates.roomBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBlurbFromRoomBlurbName', () => { - const result = client.matchBlurbFromRoomBlurbName(fakePath); - assert.strictEqual(result, "blurbValue"); - assert((client.pathTemplates.roomBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('roomBlurb', async () => { + const fakePath = '/rendered/path/roomBlurb'; + const expectedParameters = { + room: 'roomValue', + blurb: 'blurbValue', + }; + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.roomBlurbPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.roomBlurbPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('roomBlurbPath', () => { + const result = client.roomBlurbPath('roomValue', 'blurbValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.roomBlurbPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchRoomFromRoomBlurbName', () => { + const result = client.matchRoomFromRoomBlurbName(fakePath); + assert.strictEqual(result, 'roomValue'); + assert( + (client.pathTemplates.roomBlurbPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBlurbFromRoomBlurbName', () => { + const result = client.matchBlurbFromRoomBlurbName(fakePath); + assert.strictEqual(result, 'blurbValue'); + assert( + (client.pathTemplates.roomBlurbPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('roomBlurbsLegacyRoomBlurb', async () => { - const fakePath = "/rendered/path/roomBlurbsLegacyRoomBlurb"; - const expectedParameters = { - room: "roomValue", - legacy_room: "legacyRoomValue", - blurb: "blurbValue", - }; - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('roomBlurbsLegacyRoomBlurbPath', () => { - const result = client.roomBlurbsLegacyRoomBlurbPath("roomValue", "legacyRoomValue", "blurbValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchRoomFromRoomBlurbsLegacyRoomBlurbName', () => { - const result = client.matchRoomFromRoomBlurbsLegacyRoomBlurbName(fakePath); - assert.strictEqual(result, "roomValue"); - assert((client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName', () => { - const result = client.matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName(fakePath); - assert.strictEqual(result, "legacyRoomValue"); - assert((client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBlurbFromRoomBlurbsLegacyRoomBlurbName', () => { - const result = client.matchBlurbFromRoomBlurbsLegacyRoomBlurbName(fakePath); - assert.strictEqual(result, "blurbValue"); - assert((client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('roomBlurbsLegacyRoomBlurb', async () => { + const fakePath = '/rendered/path/roomBlurbsLegacyRoomBlurb'; + const expectedParameters = { + room: 'roomValue', + legacy_room: 'legacyRoomValue', + blurb: 'blurbValue', + }; + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('roomBlurbsLegacyRoomBlurbPath', () => { + const result = client.roomBlurbsLegacyRoomBlurbPath( + 'roomValue', + 'legacyRoomValue', + 'blurbValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchRoomFromRoomBlurbsLegacyRoomBlurbName', () => { + const result = + client.matchRoomFromRoomBlurbsLegacyRoomBlurbName(fakePath); + assert.strictEqual(result, 'roomValue'); + assert( + ( + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName', () => { + const result = + client.matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName(fakePath); + assert.strictEqual(result, 'legacyRoomValue'); + assert( + ( + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBlurbFromRoomBlurbsLegacyRoomBlurbName', () => { + const result = + client.matchBlurbFromRoomBlurbsLegacyRoomBlurbName(fakePath); + assert.strictEqual(result, 'blurbValue'); + assert( + ( + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('sequence', async () => { - const fakePath = "/rendered/path/sequence"; - const expectedParameters = { - sequence: "sequenceValue", - }; - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.sequencePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.sequencePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('sequencePath', () => { - const result = client.sequencePath("sequenceValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.sequencePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchSequenceFromSequenceName', () => { - const result = client.matchSequenceFromSequenceName(fakePath); - assert.strictEqual(result, "sequenceValue"); - assert((client.pathTemplates.sequencePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('sequence', async () => { + const fakePath = '/rendered/path/sequence'; + const expectedParameters = { + sequence: 'sequenceValue', + }; + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.sequencePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.sequencePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('sequencePath', () => { + const result = client.sequencePath('sequenceValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.sequencePathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchSequenceFromSequenceName', () => { + const result = client.matchSequenceFromSequenceName(fakePath); + assert.strictEqual(result, 'sequenceValue'); + assert( + (client.pathTemplates.sequencePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('sequenceReport', async () => { - const fakePath = "/rendered/path/sequenceReport"; - const expectedParameters = { - sequence: "sequenceValue", - }; - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.sequenceReportPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.sequenceReportPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('sequenceReportPath', () => { - const result = client.sequenceReportPath("sequenceValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.sequenceReportPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchSequenceFromSequenceReportName', () => { - const result = client.matchSequenceFromSequenceReportName(fakePath); - assert.strictEqual(result, "sequenceValue"); - assert((client.pathTemplates.sequenceReportPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('sequenceReport', async () => { + const fakePath = '/rendered/path/sequenceReport'; + const expectedParameters = { + sequence: 'sequenceValue', + }; + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.sequenceReportPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.sequenceReportPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('sequenceReportPath', () => { + const result = client.sequenceReportPath('sequenceValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.sequenceReportPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchSequenceFromSequenceReportName', () => { + const result = client.matchSequenceFromSequenceReportName(fakePath); + assert.strictEqual(result, 'sequenceValue'); + assert( + (client.pathTemplates.sequenceReportPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('session', async () => { - const fakePath = "/rendered/path/session"; - const expectedParameters = { - session: "sessionValue", - }; - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.sessionPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.sessionPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('sessionPath', () => { - const result = client.sessionPath("sessionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.sessionPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchSessionFromSessionName', () => { - const result = client.matchSessionFromSessionName(fakePath); - assert.strictEqual(result, "sessionValue"); - assert((client.pathTemplates.sessionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('session', async () => { + const fakePath = '/rendered/path/session'; + const expectedParameters = { + session: 'sessionValue', + }; + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.sessionPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.sessionPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('sessionPath', () => { + const result = client.sessionPath('sessionValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.sessionPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchSessionFromSessionName', () => { + const result = client.matchSessionFromSessionName(fakePath); + assert.strictEqual(result, 'sessionValue'); + assert( + (client.pathTemplates.sessionPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('test', async () => { - const fakePath = "/rendered/path/test"; - const expectedParameters = { - session: "sessionValue", - test: "testValue", - }; - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.testPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.testPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('testPath', () => { - const result = client.testPath("sessionValue", "testValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.testPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchSessionFromTestName', () => { - const result = client.matchSessionFromTestName(fakePath); - assert.strictEqual(result, "sessionValue"); - assert((client.pathTemplates.testPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchTestFromTestName', () => { - const result = client.matchTestFromTestName(fakePath); - assert.strictEqual(result, "testValue"); - assert((client.pathTemplates.testPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('test', async () => { + const fakePath = '/rendered/path/test'; + const expectedParameters = { + session: 'sessionValue', + test: 'testValue', + }; + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.testPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.testPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('testPath', () => { + const result = client.testPath('sessionValue', 'testValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.testPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchSessionFromTestName', () => { + const result = client.matchSessionFromTestName(fakePath); + assert.strictEqual(result, 'sessionValue'); + assert( + (client.pathTemplates.testPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchTestFromTestName', () => { + const result = client.matchTestFromTestName(fakePath); + assert.strictEqual(result, 'testValue'); + assert( + (client.pathTemplates.testPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('user', async () => { - const fakePath = "/rendered/path/user"; - const expectedParameters = { - user: "userValue", - }; - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.userPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.userPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('userPath', () => { - const result = client.userPath("userValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.userPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchUserFromUserName', () => { - const result = client.matchUserFromUserName(fakePath); - assert.strictEqual(result, "userValue"); - assert((client.pathTemplates.userPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('user', async () => { + const fakePath = '/rendered/path/user'; + const expectedParameters = { + user: 'userValue', + }; + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.userPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.userPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('userPath', () => { + const result = client.userPath('userValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.userPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchUserFromUserName', () => { + const result = client.matchUserFromUserName(fakePath); + assert.strictEqual(result, 'userValue'); + assert( + (client.pathTemplates.userPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('userProfileBlurb', async () => { - const fakePath = "/rendered/path/userProfileBlurb"; - const expectedParameters = { - user: "userValue", - blurb: "blurbValue", - }; - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.userProfileBlurbPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.userProfileBlurbPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('userProfileBlurbPath', () => { - const result = client.userProfileBlurbPath("userValue", "blurbValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.userProfileBlurbPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchUserFromUserProfileBlurbName', () => { - const result = client.matchUserFromUserProfileBlurbName(fakePath); - assert.strictEqual(result, "userValue"); - assert((client.pathTemplates.userProfileBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBlurbFromUserProfileBlurbName', () => { - const result = client.matchBlurbFromUserProfileBlurbName(fakePath); - assert.strictEqual(result, "blurbValue"); - assert((client.pathTemplates.userProfileBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('userProfileBlurb', async () => { + const fakePath = '/rendered/path/userProfileBlurb'; + const expectedParameters = { + user: 'userValue', + blurb: 'blurbValue', + }; + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.userProfileBlurbPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.userProfileBlurbPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('userProfileBlurbPath', () => { + const result = client.userProfileBlurbPath('userValue', 'blurbValue'); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.userProfileBlurbPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchUserFromUserProfileBlurbName', () => { + const result = client.matchUserFromUserProfileBlurbName(fakePath); + assert.strictEqual(result, 'userValue'); + assert( + (client.pathTemplates.userProfileBlurbPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBlurbFromUserProfileBlurbName', () => { + const result = client.matchBlurbFromUserProfileBlurbName(fakePath); + assert.strictEqual(result, 'blurbValue'); + assert( + (client.pathTemplates.userProfileBlurbPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('userProfileBlurbsLegacyUserBlurb', async () => { - const fakePath = "/rendered/path/userProfileBlurbsLegacyUserBlurb"; - const expectedParameters = { - user: "userValue", - legacy_user: "legacyUserValue", - blurb: "blurbValue", - }; - const client = new identityModule.v1beta1.IdentityClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('userProfileBlurbsLegacyUserBlurbPath', () => { - const result = client.userProfileBlurbsLegacyUserBlurbPath("userValue", "legacyUserValue", "blurbValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchUserFromUserProfileBlurbsLegacyUserBlurbName', () => { - const result = client.matchUserFromUserProfileBlurbsLegacyUserBlurbName(fakePath); - assert.strictEqual(result, "userValue"); - assert((client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName', () => { - const result = client.matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName(fakePath); - assert.strictEqual(result, "legacyUserValue"); - assert((client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBlurbFromUserProfileBlurbsLegacyUserBlurbName', () => { - const result = client.matchBlurbFromUserProfileBlurbsLegacyUserBlurbName(fakePath); - assert.strictEqual(result, "blurbValue"); - assert((client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('userProfileBlurbsLegacyUserBlurb', async () => { + const fakePath = '/rendered/path/userProfileBlurbsLegacyUserBlurb'; + const expectedParameters = { + user: 'userValue', + legacy_user: 'legacyUserValue', + blurb: 'blurbValue', + }; + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('userProfileBlurbsLegacyUserBlurbPath', () => { + const result = client.userProfileBlurbsLegacyUserBlurbPath( + 'userValue', + 'legacyUserValue', + 'blurbValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchUserFromUserProfileBlurbsLegacyUserBlurbName', () => { + const result = + client.matchUserFromUserProfileBlurbsLegacyUserBlurbName(fakePath); + assert.strictEqual(result, 'userValue'); + assert( + ( + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName', () => { + const result = + client.matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName( + fakePath, + ); + assert.strictEqual(result, 'legacyUserValue'); + assert( + ( + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBlurbFromUserProfileBlurbsLegacyUserBlurbName', () => { + const result = + client.matchBlurbFromUserProfileBlurbsLegacyUserBlurbName(fakePath); + assert.strictEqual(result, 'blurbValue'); + assert( + ( + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/core/generator/gapic-generator-typescript/baselines/showcase/test/gapic_messaging_v1beta1.ts.baseline b/core/generator/gapic-generator-typescript/baselines/showcase/test/gapic_messaging_v1beta1.ts.baseline index d7b2ff9708e6..450a955a3ddd 100644 --- a/core/generator/gapic-generator-typescript/baselines/showcase/test/gapic_messaging_v1beta1.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/showcase/test/gapic_messaging_v1beta1.ts.baseline @@ -19,2338 +19,2940 @@ import * as protos from '../protos/protos'; import * as assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as messagingModule from '../src'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; -import {protobuf, LROperation, operationsProtos} from 'google-gax'; +import { protobuf, LROperation, operationsProtos } from 'google-gax'; // Dynamically loaded proto JSON is needed to get the type information // to fill in default values for request objects -const root = protobuf.Root.fromJSON(require('../protos/protos.json')).resolveAll(); +const root = protobuf.Root.fromJSON( + require('../protos/protos.json'), +).resolveAll(); // eslint-disable-next-line @typescript-eslint/no-unused-vars function getTypeDefaultValue(typeName: string, fields: string[]) { - let type = root.lookupType(typeName) as protobuf.Type; - for (const field of fields.slice(0, -1)) { - type = type.fields[field]?.resolvedType as protobuf.Type; - } - return type.fields[fields[fields.length - 1]]?.defaultValue; + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type.fields[field]?.resolvedType as protobuf.Type; + } + return type.fields[fields[fields.length - 1]]?.defaultValue; } function generateSampleMessage(instance: T) { - const filledObject = (instance.constructor as typeof protobuf.Message) - .toObject(instance as protobuf.Message, {defaults: true}); - return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, { defaults: true }); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; } function stubSimpleCall(response?: ResponseType, error?: Error) { - return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); } -function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { - return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +function stubSimpleCallWithCallback( + response?: ResponseType, + error?: Error, +) { + return error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); } -function stubServerStreamingCall(response?: ResponseType, error?: Error) { - const transformStub = error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); - const mockStream = new PassThrough({ - objectMode: true, - transform: transformStub, - }); - // write something to the stream to trigger transformStub and send the response back to the client - setImmediate(() => { mockStream.write({}); }); - setImmediate(() => { mockStream.end(); }); - return sinon.stub().returns(mockStream); +function stubServerStreamingCall( + response?: ResponseType, + error?: Error, +) { + const transformStub = error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + // write something to the stream to trigger transformStub and send the response back to the client + setImmediate(() => { + mockStream.write({}); + }); + setImmediate(() => { + mockStream.end(); + }); + return sinon.stub().returns(mockStream); } -function stubBidiStreamingCall(response?: ResponseType, error?: Error) { - const transformStub = error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); - const mockStream = new PassThrough({ - objectMode: true, - transform: transformStub, - }); - return sinon.stub().returns(mockStream); +function stubBidiStreamingCall( + response?: ResponseType, + error?: Error, +) { + const transformStub = error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + return sinon.stub().returns(mockStream); } -function stubClientStreamingCall(response?: ResponseType, error?: Error) { - if (error) { - return sinon.stub().callsArgWith(2, error); - } - const transformStub = sinon.stub(); - const mockStream = new PassThrough({ - objectMode: true, - transform: transformStub, - }); - return sinon.stub().returns(mockStream).callsArgWith(2, null, response); +function stubClientStreamingCall( + response?: ResponseType, + error?: Error, +) { + if (error) { + return sinon.stub().callsArgWith(2, error); + } + const transformStub = sinon.stub(); + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + return sinon.stub().returns(mockStream).callsArgWith(2, null, response); } -function stubLongRunningCall(response?: ResponseType, callError?: Error, lroError?: Error) { - const innerStub = lroError ? sinon.stub().rejects(lroError) : sinon.stub().resolves([response]); - const mockOperation = { - promise: innerStub, - }; - return callError ? sinon.stub().rejects(callError) : sinon.stub().resolves([mockOperation]); +function stubLongRunningCall( + response?: ResponseType, + callError?: Error, + lroError?: Error, +) { + const innerStub = lroError + ? sinon.stub().rejects(lroError) + : sinon.stub().resolves([response]); + const mockOperation = { + promise: innerStub, + }; + return callError + ? sinon.stub().rejects(callError) + : sinon.stub().resolves([mockOperation]); } -function stubLongRunningCallWithCallback(response?: ResponseType, callError?: Error, lroError?: Error) { - const innerStub = lroError ? sinon.stub().rejects(lroError) : sinon.stub().resolves([response]); - const mockOperation = { - promise: innerStub, - }; - return callError ? sinon.stub().callsArgWith(2, callError) : sinon.stub().callsArgWith(2, null, mockOperation); +function stubLongRunningCallWithCallback( + response?: ResponseType, + callError?: Error, + lroError?: Error, +) { + const innerStub = lroError + ? sinon.stub().rejects(lroError) + : sinon.stub().resolves([response]); + const mockOperation = { + promise: innerStub, + }; + return callError + ? sinon.stub().callsArgWith(2, callError) + : sinon.stub().callsArgWith(2, null, mockOperation); } -function stubPageStreamingCall(responses?: ResponseType[], error?: Error) { - const pagingStub = sinon.stub(); - if (responses) { - for (let i = 0; i < responses.length; ++i) { - pagingStub.onCall(i).callsArgWith(2, null, responses[i]); - } +function stubPageStreamingCall( + responses?: ResponseType[], + error?: Error, +) { + const pagingStub = sinon.stub(); + if (responses) { + for (let i = 0; i < responses.length; ++i) { + pagingStub.onCall(i).callsArgWith(2, null, responses[i]); } - const transformStub = error ? sinon.stub().callsArgWith(2, error) : pagingStub; - const mockStream = new PassThrough({ - objectMode: true, - transform: transformStub, - }); - // trigger as many responses as needed - if (responses) { - for (let i = 0; i < responses.length; ++i) { - setImmediate(() => { mockStream.write({}); }); - } - setImmediate(() => { mockStream.end(); }); - } else { - setImmediate(() => { mockStream.write({}); }); - setImmediate(() => { mockStream.end(); }); + } + const transformStub = error + ? sinon.stub().callsArgWith(2, error) + : pagingStub; + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + // trigger as many responses as needed + if (responses) { + for (let i = 0; i < responses.length; ++i) { + setImmediate(() => { + mockStream.write({}); + }); } - return sinon.stub().returns(mockStream); + setImmediate(() => { + mockStream.end(); + }); + } else { + setImmediate(() => { + mockStream.write({}); + }); + setImmediate(() => { + mockStream.end(); + }); + } + return sinon.stub().returns(mockStream); } -function stubAsyncIterationCall(responses?: ResponseType[], error?: Error) { - let counter = 0; - const asyncIterable = { - [Symbol.asyncIterator]() { - return { - async next() { - if (error) { - return Promise.reject(error); - } - if (counter >= responses!.length) { - return Promise.resolve({done: true, value: undefined}); - } - return Promise.resolve({done: false, value: responses![counter++]}); - } - }; - } - }; - return sinon.stub().returns(asyncIterable); +function stubAsyncIterationCall( + responses?: ResponseType[], + error?: Error, +) { + let counter = 0; + const asyncIterable = { + [Symbol.asyncIterator]() { + return { + async next() { + if (error) { + return Promise.reject(error); + } + if (counter >= responses!.length) { + return Promise.resolve({ done: true, value: undefined }); + } + return Promise.resolve({ done: false, value: responses![counter++] }); + }, + }; + }, + }; + return sinon.stub().returns(asyncIterable); } describe('v1beta1.MessagingClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new messagingModule.v1beta1.MessagingClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'localhost'); - }); - - it('has universeDomain', () => { - const client = new messagingModule.v1beta1.MessagingClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); - - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - it('throws DeprecationWarning if static servicePath is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const servicePath = messagingModule.v1beta1.MessagingClient.servicePath; - assert.strictEqual(servicePath, 'localhost'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = messagingModule.v1beta1.MessagingClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'localhost'); - assert(stub.called); - stub.restore(); - }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { new messagingModule.v1beta1.MessagingClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); - - it('has port', () => { - const port = messagingModule.v1beta1.MessagingClient.port; - assert(port); - assert(typeof port === 'number'); - }); - - it('should create a client with no option', () => { - const client = new messagingModule.v1beta1.MessagingClient(); - assert(client); - }); - - it('should create a client with gRPC fallback', () => { - const client = new messagingModule.v1beta1.MessagingClient({ - fallback: true, - }); - assert(client); - }); - - it('has initialize method and supports deferred initialization', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.messagingStub, undefined); - await client.initialize(); - assert(client.messagingStub); - }); - - it('has close method for the initialized client', done => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.messagingStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); - - it('has close method for the non-initialized client', done => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.messagingStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); - - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); - }); - - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId((err?: Error|null, projectId?: string|null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } - }); - }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new messagingModule.v1beta1.MessagingClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'localhost'); }); - describe('createRoom', () => { - it('invokes createRoom without error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.CreateRoomRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.Room() - ); - client.innerApiCalls.createRoom = stubSimpleCall(expectedResponse); - const [response] = await client.createRoom(request); - assert.deepStrictEqual(response, expectedResponse); - }); - - it('invokes createRoom without error using callback', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.CreateRoomRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.Room() - ); - client.innerApiCalls.createRoom = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createRoom( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IRoom|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); + it('has universeDomain', () => { + const client = new messagingModule.v1beta1.MessagingClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - it('invokes createRoom with error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.CreateRoomRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.createRoom = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createRoom(request), expectedError); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = messagingModule.v1beta1.MessagingClient.servicePath; + assert.strictEqual(servicePath, 'localhost'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = messagingModule.v1beta1.MessagingClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'localhost'); + assert(stub.called); + stub.restore(); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new messagingModule.v1beta1.MessagingClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); + }); - it('invokes createRoom with closed client', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.CreateRoomRequest() - ); - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createRoom(request), expectedError); - }); + it('has port', () => { + const port = messagingModule.v1beta1.MessagingClient.port; + assert(port); + assert(typeof port === 'number'); }); - describe('getRoom', () => { - it('invokes getRoom without error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.GetRoomRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.GetRoomRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.Room() - ); - client.innerApiCalls.getRoom = stubSimpleCall(expectedResponse); - const [response] = await client.getRoom(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getRoom as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getRoom as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('should create a client with no option', () => { + const client = new messagingModule.v1beta1.MessagingClient(); + assert(client); + }); - it('invokes getRoom without error using callback', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.GetRoomRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.GetRoomRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.Room() - ); - client.innerApiCalls.getRoom = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getRoom( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IRoom|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getRoom as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getRoom as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('should create a client with gRPC fallback', () => { + const client = new messagingModule.v1beta1.MessagingClient({ + fallback: true, + }); + assert(client); + }); - it('invokes getRoom with error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.GetRoomRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.GetRoomRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getRoom = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getRoom(request), expectedError); - const actualRequest = (client.innerApiCalls.getRoom as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getRoom as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has initialize method and supports deferred initialization', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.messagingStub, undefined); + await client.initialize(); + assert(client.messagingStub); + }); - it('invokes getRoom with closed client', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.GetRoomRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.GetRoomRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getRoom(request), expectedError); + it('has close method for the initialized client', (done) => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.messagingStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); }); - describe('updateRoom', () => { - it('invokes updateRoom without error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.UpdateRoomRequest() - ); - request.room ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.UpdateRoomRequest', ['room', 'name']); - request.room.name = defaultValue1; - const expectedHeaderRequestParams = `room.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.Room() - ); - client.innerApiCalls.updateRoom = stubSimpleCall(expectedResponse); - const [response] = await client.updateRoom(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateRoom as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateRoom as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('has close method for the non-initialized client', (done) => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.messagingStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes updateRoom without error using callback', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.UpdateRoomRequest() - ); - request.room ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.UpdateRoomRequest', ['room', 'name']); - request.room.name = defaultValue1; - const expectedHeaderRequestParams = `room.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.Room() - ); - client.innerApiCalls.updateRoom = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateRoom( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IRoom|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateRoom as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateRoom as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + }); - it('invokes updateRoom with error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.UpdateRoomRequest() - ); - request.room ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.UpdateRoomRequest', ['room', 'name']); - request.room.name = defaultValue1; - const expectedHeaderRequestParams = `room.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateRoom = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateRoom(request), expectedError); - const actualRequest = (client.innerApiCalls.updateRoom as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateRoom as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } + }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + }); + + describe('createRoom', () => { + it('invokes createRoom without error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.CreateRoomRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.Room(), + ); + client.innerApiCalls.createRoom = stubSimpleCall(expectedResponse); + const [response] = await client.createRoom(request); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes updateRoom with closed client', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.UpdateRoomRequest() - ); - request.room ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.UpdateRoomRequest', ['room', 'name']); - request.room.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateRoom(request), expectedError); - }); + it('invokes createRoom without error using callback', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.CreateRoomRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.Room(), + ); + client.innerApiCalls.createRoom = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createRoom( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IRoom | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); }); - describe('deleteRoom', () => { - it('invokes deleteRoom without error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.DeleteRoomRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.DeleteRoomRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteRoom = stubSimpleCall(expectedResponse); - const [response] = await client.deleteRoom(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteRoom as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteRoom as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createRoom with error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.CreateRoomRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.createRoom = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.createRoom(request), expectedError); + }); - it('invokes deleteRoom without error using callback', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.DeleteRoomRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.DeleteRoomRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteRoom = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteRoom( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteRoom as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteRoom as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createRoom with closed client', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.CreateRoomRequest(), + ); + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.createRoom(request), expectedError); + }); + }); + + describe('getRoom', () => { + it('invokes getRoom without error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.GetRoomRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.GetRoomRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.Room(), + ); + client.innerApiCalls.getRoom = stubSimpleCall(expectedResponse); + const [response] = await client.getRoom(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.getRoom as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getRoom as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteRoom with error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.DeleteRoomRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.DeleteRoomRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteRoom = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteRoom(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteRoom as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteRoom as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getRoom without error using callback', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.GetRoomRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.GetRoomRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.Room(), + ); + client.innerApiCalls.getRoom = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getRoom( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IRoom | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.getRoom as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getRoom as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteRoom with closed client', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.DeleteRoomRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.DeleteRoomRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteRoom(request), expectedError); - }); + it('invokes getRoom with error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.GetRoomRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.GetRoomRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getRoom = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.getRoom(request), expectedError); + const actualRequest = (client.innerApiCalls.getRoom as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getRoom as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('createBlurb', () => { - it('invokes createBlurb without error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.CreateBlurbRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.CreateBlurbRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.Blurb() - ); - client.innerApiCalls.createBlurb = stubSimpleCall(expectedResponse); - const [response] = await client.createBlurb(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createBlurb as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createBlurb as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getRoom with closed client', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.GetRoomRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.GetRoomRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getRoom(request), expectedError); + }); + }); + + describe('updateRoom', () => { + it('invokes updateRoom without error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.UpdateRoomRequest(), + ); + request.room ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.UpdateRoomRequest', + ['room', 'name'], + ); + request.room.name = defaultValue1; + const expectedHeaderRequestParams = `room.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.Room(), + ); + client.innerApiCalls.updateRoom = stubSimpleCall(expectedResponse); + const [response] = await client.updateRoom(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateRoom as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateRoom as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createBlurb without error using callback', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.CreateBlurbRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.CreateBlurbRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.Blurb() - ); - client.innerApiCalls.createBlurb = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createBlurb( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IBlurb|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createBlurb as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createBlurb as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateRoom without error using callback', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.UpdateRoomRequest(), + ); + request.room ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.UpdateRoomRequest', + ['room', 'name'], + ); + request.room.name = defaultValue1; + const expectedHeaderRequestParams = `room.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.Room(), + ); + client.innerApiCalls.updateRoom = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateRoom( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IRoom | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateRoom as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateRoom as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createBlurb with error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.CreateBlurbRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.CreateBlurbRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createBlurb = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createBlurb(request), expectedError); - const actualRequest = (client.innerApiCalls.createBlurb as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createBlurb as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateRoom with error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.UpdateRoomRequest(), + ); + request.room ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.UpdateRoomRequest', + ['room', 'name'], + ); + request.room.name = defaultValue1; + const expectedHeaderRequestParams = `room.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateRoom = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.updateRoom(request), expectedError); + const actualRequest = ( + client.innerApiCalls.updateRoom as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateRoom as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createBlurb with closed client', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.CreateBlurbRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.CreateBlurbRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createBlurb(request), expectedError); - }); + it('invokes updateRoom with closed client', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.UpdateRoomRequest(), + ); + request.room ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.UpdateRoomRequest', + ['room', 'name'], + ); + request.room.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.updateRoom(request), expectedError); + }); + }); + + describe('deleteRoom', () => { + it('invokes deleteRoom without error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.DeleteRoomRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.DeleteRoomRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteRoom = stubSimpleCall(expectedResponse); + const [response] = await client.deleteRoom(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteRoom as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteRoom as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('getBlurb', () => { - it('invokes getBlurb without error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.GetBlurbRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.GetBlurbRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.Blurb() - ); - client.innerApiCalls.getBlurb = stubSimpleCall(expectedResponse); - const [response] = await client.getBlurb(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getBlurb as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getBlurb as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteRoom without error using callback', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.DeleteRoomRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.DeleteRoomRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteRoom = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteRoom( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteRoom as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteRoom as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getBlurb without error using callback', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.GetBlurbRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.GetBlurbRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.Blurb() - ); - client.innerApiCalls.getBlurb = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getBlurb( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IBlurb|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getBlurb as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getBlurb as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteRoom with error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.DeleteRoomRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.DeleteRoomRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteRoom = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.deleteRoom(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteRoom as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteRoom as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getBlurb with error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.GetBlurbRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.GetBlurbRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getBlurb = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getBlurb(request), expectedError); - const actualRequest = (client.innerApiCalls.getBlurb as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getBlurb as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteRoom with closed client', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.DeleteRoomRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.DeleteRoomRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.deleteRoom(request), expectedError); + }); + }); + + describe('createBlurb', () => { + it('invokes createBlurb without error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.CreateBlurbRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.CreateBlurbRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.Blurb(), + ); + client.innerApiCalls.createBlurb = stubSimpleCall(expectedResponse); + const [response] = await client.createBlurb(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createBlurb as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createBlurb as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getBlurb with closed client', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.GetBlurbRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.GetBlurbRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getBlurb(request), expectedError); - }); + it('invokes createBlurb without error using callback', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.CreateBlurbRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.CreateBlurbRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.Blurb(), + ); + client.innerApiCalls.createBlurb = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createBlurb( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IBlurb | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createBlurb as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createBlurb as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('updateBlurb', () => { - it('invokes updateBlurb without error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.UpdateBlurbRequest() - ); - request.blurb ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.UpdateBlurbRequest', ['blurb', 'name']); - request.blurb.name = defaultValue1; - const expectedHeaderRequestParams = `blurb.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.Blurb() - ); - client.innerApiCalls.updateBlurb = stubSimpleCall(expectedResponse); - const [response] = await client.updateBlurb(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateBlurb as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateBlurb as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createBlurb with error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.CreateBlurbRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.CreateBlurbRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createBlurb = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.createBlurb(request), expectedError); + const actualRequest = ( + client.innerApiCalls.createBlurb as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createBlurb as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateBlurb without error using callback', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.UpdateBlurbRequest() - ); - request.blurb ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.UpdateBlurbRequest', ['blurb', 'name']); - request.blurb.name = defaultValue1; - const expectedHeaderRequestParams = `blurb.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.Blurb() - ); - client.innerApiCalls.updateBlurb = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateBlurb( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IBlurb|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateBlurb as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateBlurb as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createBlurb with closed client', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.CreateBlurbRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.CreateBlurbRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.createBlurb(request), expectedError); + }); + }); + + describe('getBlurb', () => { + it('invokes getBlurb without error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.GetBlurbRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.GetBlurbRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.Blurb(), + ); + client.innerApiCalls.getBlurb = stubSimpleCall(expectedResponse); + const [response] = await client.getBlurb(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getBlurb as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getBlurb as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateBlurb with error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.UpdateBlurbRequest() - ); - request.blurb ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.UpdateBlurbRequest', ['blurb', 'name']); - request.blurb.name = defaultValue1; - const expectedHeaderRequestParams = `blurb.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateBlurb = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateBlurb(request), expectedError); - const actualRequest = (client.innerApiCalls.updateBlurb as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateBlurb as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getBlurb without error using callback', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.GetBlurbRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.GetBlurbRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.Blurb(), + ); + client.innerApiCalls.getBlurb = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getBlurb( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IBlurb | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getBlurb as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getBlurb as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateBlurb with closed client', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.UpdateBlurbRequest() - ); - request.blurb ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.UpdateBlurbRequest', ['blurb', 'name']); - request.blurb.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateBlurb(request), expectedError); - }); + it('invokes getBlurb with error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.GetBlurbRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.GetBlurbRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getBlurb = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.getBlurb(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getBlurb as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getBlurb as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('deleteBlurb', () => { - it('invokes deleteBlurb without error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.DeleteBlurbRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.DeleteBlurbRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteBlurb = stubSimpleCall(expectedResponse); - const [response] = await client.deleteBlurb(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteBlurb as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteBlurb as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getBlurb with closed client', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.GetBlurbRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.GetBlurbRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getBlurb(request), expectedError); + }); + }); + + describe('updateBlurb', () => { + it('invokes updateBlurb without error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.UpdateBlurbRequest(), + ); + request.blurb ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.UpdateBlurbRequest', + ['blurb', 'name'], + ); + request.blurb.name = defaultValue1; + const expectedHeaderRequestParams = `blurb.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.Blurb(), + ); + client.innerApiCalls.updateBlurb = stubSimpleCall(expectedResponse); + const [response] = await client.updateBlurb(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateBlurb as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateBlurb as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteBlurb without error using callback', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.DeleteBlurbRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.DeleteBlurbRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteBlurb = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteBlurb( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteBlurb as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteBlurb as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateBlurb without error using callback', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.UpdateBlurbRequest(), + ); + request.blurb ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.UpdateBlurbRequest', + ['blurb', 'name'], + ); + request.blurb.name = defaultValue1; + const expectedHeaderRequestParams = `blurb.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.Blurb(), + ); + client.innerApiCalls.updateBlurb = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateBlurb( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IBlurb | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateBlurb as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateBlurb as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteBlurb with error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.DeleteBlurbRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.DeleteBlurbRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteBlurb = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteBlurb(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteBlurb as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteBlurb as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateBlurb with error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.UpdateBlurbRequest(), + ); + request.blurb ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.UpdateBlurbRequest', + ['blurb', 'name'], + ); + request.blurb.name = defaultValue1; + const expectedHeaderRequestParams = `blurb.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateBlurb = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.updateBlurb(request), expectedError); + const actualRequest = ( + client.innerApiCalls.updateBlurb as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateBlurb as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteBlurb with closed client', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.DeleteBlurbRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.DeleteBlurbRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteBlurb(request), expectedError); - }); + it('invokes updateBlurb with closed client', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.UpdateBlurbRequest(), + ); + request.blurb ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.UpdateBlurbRequest', + ['blurb', 'name'], + ); + request.blurb.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.updateBlurb(request), expectedError); + }); + }); + + describe('deleteBlurb', () => { + it('invokes deleteBlurb without error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.DeleteBlurbRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.DeleteBlurbRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteBlurb = stubSimpleCall(expectedResponse); + const [response] = await client.deleteBlurb(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteBlurb as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteBlurb as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('searchBlurbs', () => { - it('invokes searchBlurbs without error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.SearchBlurbsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.SearchBlurbsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.searchBlurbs = stubLongRunningCall(expectedResponse); - const [operation] = await client.searchBlurbs(request); - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.searchBlurbs as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.searchBlurbs as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteBlurb without error using callback', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.DeleteBlurbRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.DeleteBlurbRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteBlurb = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteBlurb( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteBlurb as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteBlurb as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes searchBlurbs without error using callback', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.SearchBlurbsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.SearchBlurbsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.searchBlurbs = stubLongRunningCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.searchBlurbs( - request, - (err?: Error|null, - result?: LROperation|null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const operation = await promise as LROperation; - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.searchBlurbs as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.searchBlurbs as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteBlurb with error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.DeleteBlurbRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.DeleteBlurbRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteBlurb = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.deleteBlurb(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteBlurb as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteBlurb as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes searchBlurbs with call error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.SearchBlurbsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.SearchBlurbsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.searchBlurbs = stubLongRunningCall(undefined, expectedError); - await assert.rejects(client.searchBlurbs(request), expectedError); - const actualRequest = (client.innerApiCalls.searchBlurbs as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.searchBlurbs as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteBlurb with closed client', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.DeleteBlurbRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.DeleteBlurbRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.deleteBlurb(request), expectedError); + }); + }); + + describe('searchBlurbs', () => { + it('invokes searchBlurbs without error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.SearchBlurbsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.SearchBlurbsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.searchBlurbs = stubLongRunningCall(expectedResponse); + const [operation] = await client.searchBlurbs(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.searchBlurbs as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.searchBlurbs as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes searchBlurbs with LRO error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.SearchBlurbsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.SearchBlurbsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.searchBlurbs = stubLongRunningCall(undefined, undefined, expectedError); - const [operation] = await client.searchBlurbs(request); - await assert.rejects(operation.promise(), expectedError); - const actualRequest = (client.innerApiCalls.searchBlurbs as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.searchBlurbs as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes searchBlurbs without error using callback', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.SearchBlurbsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.SearchBlurbsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.searchBlurbs = + stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.searchBlurbs( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.showcase.v1beta1.ISearchBlurbsResponse, + protos.google.showcase.v1beta1.ISearchBlurbsMetadata + > | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const operation = (await promise) as LROperation< + protos.google.showcase.v1beta1.ISearchBlurbsResponse, + protos.google.showcase.v1beta1.ISearchBlurbsMetadata + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.searchBlurbs as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.searchBlurbs as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkSearchBlurbsProgress without error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedResponse = generateSampleMessage( - new operationsProtos.google.longrunning.Operation() - ); - expectedResponse.name = 'test'; - expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; - expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')} - - client.operationsClient.getOperation = stubSimpleCall(expectedResponse); - const decodedOperation = await client.checkSearchBlurbsProgress(expectedResponse.name); - assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); - assert(decodedOperation.metadata); - assert((client.operationsClient.getOperation as SinonStub).getCall(0)); - }); + it('invokes searchBlurbs with call error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.SearchBlurbsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.SearchBlurbsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.searchBlurbs = stubLongRunningCall( + undefined, + expectedError, + ); + await assert.rejects(client.searchBlurbs(request), expectedError); + const actualRequest = ( + client.innerApiCalls.searchBlurbs as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.searchBlurbs as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkSearchBlurbsProgress with error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedError = new Error('expected'); - - client.operationsClient.getOperation = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.checkSearchBlurbsProgress(''), expectedError); - assert((client.operationsClient.getOperation as SinonStub) - .getCall(0)); - }); + it('invokes searchBlurbs with LRO error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.SearchBlurbsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.SearchBlurbsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.searchBlurbs = stubLongRunningCall( + undefined, + undefined, + expectedError, + ); + const [operation] = await client.searchBlurbs(request); + await assert.rejects(operation.promise(), expectedError); + const actualRequest = ( + client.innerApiCalls.searchBlurbs as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.searchBlurbs as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('streamBlurbs', () => { - it('invokes streamBlurbs without error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.StreamBlurbsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.StreamBlurbsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.StreamBlurbsResponse() - ); - client.innerApiCalls.streamBlurbs = stubServerStreamingCall(expectedResponse); - const stream = client.streamBlurbs(request); - const promise = new Promise((resolve, reject) => { - stream.on('data', (response: protos.google.showcase.v1beta1.StreamBlurbsResponse) => { - resolve(response); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.streamBlurbs as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.streamBlurbs as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes checkSearchBlurbsProgress without error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation(), + ); + expectedResponse.name = 'test'; + expectedResponse.response = { type_url: 'url', value: Buffer.from('') }; + expectedResponse.metadata = { type_url: 'url', value: Buffer.from('') }; + + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const decodedOperation = await client.checkSearchBlurbsProgress( + expectedResponse.name, + ); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); - it('invokes streamBlurbs without error and gaxServerStreamingRetries enabled', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - gaxServerStreamingRetries: true - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.StreamBlurbsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.StreamBlurbsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.StreamBlurbsResponse() - ); - client.innerApiCalls.streamBlurbs = stubServerStreamingCall(expectedResponse); - const stream = client.streamBlurbs(request); - const promise = new Promise((resolve, reject) => { - stream.on('data', (response: protos.google.showcase.v1beta1.StreamBlurbsResponse) => { - resolve(response); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.streamBlurbs as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.streamBlurbs as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes checkSearchBlurbsProgress with error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const expectedError = new Error('expected'); + + client.operationsClient.getOperation = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.checkSearchBlurbsProgress(''), expectedError); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + }); + + describe('streamBlurbs', () => { + it('invokes streamBlurbs without error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.StreamBlurbsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.StreamBlurbsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.StreamBlurbsResponse(), + ); + client.innerApiCalls.streamBlurbs = + stubServerStreamingCall(expectedResponse); + const stream = client.streamBlurbs(request); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + (response: protos.google.showcase.v1beta1.StreamBlurbsResponse) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.streamBlurbs as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.streamBlurbs as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes streamBlurbs with error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.StreamBlurbsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.StreamBlurbsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.streamBlurbs = stubServerStreamingCall(undefined, expectedError); - const stream = client.streamBlurbs(request); - const promise = new Promise((resolve, reject) => { - stream.on('data', (response: protos.google.showcase.v1beta1.StreamBlurbsResponse) => { - resolve(response); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - const actualRequest = (client.innerApiCalls.streamBlurbs as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.streamBlurbs as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes streamBlurbs without error and gaxServerStreamingRetries enabled', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + gaxServerStreamingRetries: true, + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.StreamBlurbsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.StreamBlurbsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.StreamBlurbsResponse(), + ); + client.innerApiCalls.streamBlurbs = + stubServerStreamingCall(expectedResponse); + const stream = client.streamBlurbs(request); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + (response: protos.google.showcase.v1beta1.StreamBlurbsResponse) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.streamBlurbs as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.streamBlurbs as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes streamBlurbs with closed client', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.StreamBlurbsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.StreamBlurbsRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - const stream = client.streamBlurbs(request, {retryRequestOptions: {noResponseRetries: 0}}); - const promise = new Promise((resolve, reject) => { - stream.on('data', (response: protos.google.showcase.v1beta1.StreamBlurbsResponse) => { - resolve(response); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - }); - it('should create a client with gaxServerStreamingRetries enabled', () => { - const client = new messagingModule.v1beta1.MessagingClient({ - gaxServerStreamingRetries: true, - }); - assert(client); - }); + it('invokes streamBlurbs with error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.StreamBlurbsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.StreamBlurbsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.streamBlurbs = stubServerStreamingCall( + undefined, + expectedError, + ); + const stream = client.streamBlurbs(request); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + (response: protos.google.showcase.v1beta1.StreamBlurbsResponse) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + const actualRequest = ( + client.innerApiCalls.streamBlurbs as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.streamBlurbs as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('connect', () => { - it('invokes connect without error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ConnectRequest() - ); - - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.StreamBlurbsResponse() - ); - client.innerApiCalls.connect = stubBidiStreamingCall(expectedResponse); - const stream = client.connect(); - const promise = new Promise((resolve, reject) => { - stream.on('data', (response: protos.google.showcase.v1beta1.StreamBlurbsResponse) => { - resolve(response); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - stream.write(request); - stream.end(); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - assert((client.innerApiCalls.connect as SinonStub) - .getCall(0).calledWith(null)); - assert.deepStrictEqual(((stream as unknown as PassThrough) - ._transform as SinonStub).getCall(0).args[0], request); - }); + it('invokes streamBlurbs with closed client', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.StreamBlurbsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.StreamBlurbsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + const stream = client.streamBlurbs(request, { + retryRequestOptions: { noResponseRetries: 0 }, + }); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + (response: protos.google.showcase.v1beta1.StreamBlurbsResponse) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + }); + it('should create a client with gaxServerStreamingRetries enabled', () => { + const client = new messagingModule.v1beta1.MessagingClient({ + gaxServerStreamingRetries: true, + }); + assert(client); + }); + }); + + describe('connect', () => { + it('invokes connect without error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ConnectRequest(), + ); + + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.StreamBlurbsResponse(), + ); + client.innerApiCalls.connect = stubBidiStreamingCall(expectedResponse); + const stream = client.connect(); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + (response: protos.google.showcase.v1beta1.StreamBlurbsResponse) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); + }); + stream.write(request); + stream.end(); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + assert( + (client.innerApiCalls.connect as SinonStub).getCall(0).calledWith(null), + ); + assert.deepStrictEqual( + ((stream as unknown as PassThrough)._transform as SinonStub).getCall(0) + .args[0], + request, + ); + }); - it('invokes connect with error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ConnectRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.connect = stubBidiStreamingCall(undefined, expectedError); - const stream = client.connect(); - const promise = new Promise((resolve, reject) => { - stream.on('data', (response: protos.google.showcase.v1beta1.StreamBlurbsResponse) => { - resolve(response); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - stream.write(request); - stream.end(); - }); - await assert.rejects(promise, expectedError); - assert((client.innerApiCalls.connect as SinonStub) - .getCall(0).calledWith(null)); - assert.deepStrictEqual(((stream as unknown as PassThrough) - ._transform as SinonStub).getCall(0).args[0], request); - }); + it('invokes connect with error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ConnectRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.connect = stubBidiStreamingCall( + undefined, + expectedError, + ); + const stream = client.connect(); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + (response: protos.google.showcase.v1beta1.StreamBlurbsResponse) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); + }); + stream.write(request); + stream.end(); + }); + await assert.rejects(promise, expectedError); + assert( + (client.innerApiCalls.connect as SinonStub).getCall(0).calledWith(null), + ); + assert.deepStrictEqual( + ((stream as unknown as PassThrough)._transform as SinonStub).getCall(0) + .args[0], + request, + ); + }); + }); + + describe('sendBlurbs', () => { + it('invokes sendBlurbs without error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.CreateBlurbRequest(), + ); + + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.SendBlurbsResponse(), + ); + client.innerApiCalls.sendBlurbs = + stubClientStreamingCall(expectedResponse); + let stream: PassThrough; + const promise = new Promise((resolve, reject) => { + stream = client.sendBlurbs( + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.ISendBlurbsResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ) as unknown as PassThrough; + stream.write(request); + stream.end(); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + assert( + (client.innerApiCalls.sendBlurbs as SinonStub) + .getCall(0) + .calledWith(null, {} /*, callback defined above */), + ); + assert.deepStrictEqual( + (stream!._transform as SinonStub).getCall(0).args[0], + request, + ); }); - describe('sendBlurbs', () => { - it('invokes sendBlurbs without error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.CreateBlurbRequest() - ); - - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.SendBlurbsResponse() - ); - client.innerApiCalls.sendBlurbs = stubClientStreamingCall(expectedResponse); - let stream: PassThrough; - const promise = new Promise((resolve, reject) => { - stream = client.sendBlurbs( - (err?: Error|null, result?: protos.google.showcase.v1beta1.ISendBlurbsResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }) as unknown as PassThrough; - stream.write(request); - stream.end(); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - assert((client.innerApiCalls.sendBlurbs as SinonStub) - .getCall(0).calledWith(null, {} /*, callback defined above */)); - assert.deepStrictEqual((stream!._transform as SinonStub).getCall(0).args[0], request); - }); + it('invokes sendBlurbs with error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.CreateBlurbRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.sendBlurbs = stubClientStreamingCall( + undefined, + expectedError, + ); + let stream: PassThrough; + const promise = new Promise((resolve, reject) => { + stream = client.sendBlurbs( + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.ISendBlurbsResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ) as unknown as PassThrough; + stream.write(request); + stream.end(); + }); + await assert.rejects(promise, expectedError); + assert( + (client.innerApiCalls.sendBlurbs as SinonStub) + .getCall(0) + .calledWith(null, {} /*, callback defined above */), + ); + }); + }); + + describe('listRooms', () => { + it('invokes listRooms without error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListRoomsRequest(), + ); + const expectedResponse = [ + generateSampleMessage(new protos.google.showcase.v1beta1.Room()), + generateSampleMessage(new protos.google.showcase.v1beta1.Room()), + generateSampleMessage(new protos.google.showcase.v1beta1.Room()), + ]; + client.innerApiCalls.listRooms = stubSimpleCall(expectedResponse); + const [response] = await client.listRooms(request); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes sendBlurbs with error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.CreateBlurbRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.sendBlurbs = stubClientStreamingCall(undefined, expectedError); - let stream: PassThrough; - const promise = new Promise((resolve, reject) => { - stream = client.sendBlurbs( - (err?: Error|null, result?: protos.google.showcase.v1beta1.ISendBlurbsResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }) as unknown as PassThrough; - stream.write(request); - stream.end(); - }); - await assert.rejects(promise, expectedError); - assert((client.innerApiCalls.sendBlurbs as SinonStub) - .getCall(0).calledWith(null, {} /*, callback defined above */)); - }); + it('invokes listRooms without error using callback', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListRoomsRequest(), + ); + const expectedResponse = [ + generateSampleMessage(new protos.google.showcase.v1beta1.Room()), + generateSampleMessage(new protos.google.showcase.v1beta1.Room()), + generateSampleMessage(new protos.google.showcase.v1beta1.Room()), + ]; + client.innerApiCalls.listRooms = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listRooms( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IRoom[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); }); - describe('listRooms', () => { - it('invokes listRooms without error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListRoomsRequest() - );const expectedResponse = [ - generateSampleMessage(new protos.google.showcase.v1beta1.Room()), - generateSampleMessage(new protos.google.showcase.v1beta1.Room()), - generateSampleMessage(new protos.google.showcase.v1beta1.Room()), - ]; - client.innerApiCalls.listRooms = stubSimpleCall(expectedResponse); - const [response] = await client.listRooms(request); - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes listRooms with error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListRoomsRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.listRooms = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.listRooms(request), expectedError); + }); - it('invokes listRooms without error using callback', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListRoomsRequest() - );const expectedResponse = [ - generateSampleMessage(new protos.google.showcase.v1beta1.Room()), - generateSampleMessage(new protos.google.showcase.v1beta1.Room()), - generateSampleMessage(new protos.google.showcase.v1beta1.Room()), - ]; - client.innerApiCalls.listRooms = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listRooms( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IRoom[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes listRoomsStream without error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListRoomsRequest(), + ); + const expectedResponse = [ + generateSampleMessage(new protos.google.showcase.v1beta1.Room()), + generateSampleMessage(new protos.google.showcase.v1beta1.Room()), + generateSampleMessage(new protos.google.showcase.v1beta1.Room()), + ]; + client.descriptors.page.listRooms.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listRoomsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.showcase.v1beta1.Room[] = []; + stream.on('data', (response: protos.google.showcase.v1beta1.Room) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listRooms.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listRooms, request), + ); + }); - it('invokes listRooms with error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListRoomsRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.listRooms = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listRooms(request), expectedError); - }); + it('invokes listRoomsStream with error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListRoomsRequest(), + ); + const expectedError = new Error('expected'); + client.descriptors.page.listRooms.createStream = stubPageStreamingCall( + undefined, + expectedError, + ); + const stream = client.listRoomsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.showcase.v1beta1.Room[] = []; + stream.on('data', (response: protos.google.showcase.v1beta1.Room) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listRooms.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listRooms, request), + ); + }); - it('invokes listRoomsStream without error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListRoomsRequest() - ); - const expectedResponse = [ - generateSampleMessage(new protos.google.showcase.v1beta1.Room()), - generateSampleMessage(new protos.google.showcase.v1beta1.Room()), - generateSampleMessage(new protos.google.showcase.v1beta1.Room()), - ]; - client.descriptors.page.listRooms.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listRoomsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.showcase.v1beta1.Room[] = []; - stream.on('data', (response: protos.google.showcase.v1beta1.Room) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.listRooms.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listRooms, request)); - }); + it('uses async iteration with listRooms without error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListRoomsRequest(), + ); + const expectedResponse = [ + generateSampleMessage(new protos.google.showcase.v1beta1.Room()), + generateSampleMessage(new protos.google.showcase.v1beta1.Room()), + generateSampleMessage(new protos.google.showcase.v1beta1.Room()), + ]; + client.descriptors.page.listRooms.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.showcase.v1beta1.IRoom[] = []; + const iterable = client.listRoomsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + (client.descriptors.page.listRooms.asyncIterate as SinonStub).getCall(0) + .args[1], + request, + ); + }); - it('invokes listRoomsStream with error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListRoomsRequest() - ); - const expectedError = new Error('expected'); - client.descriptors.page.listRooms.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listRoomsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.showcase.v1beta1.Room[] = []; - stream.on('data', (response: protos.google.showcase.v1beta1.Room) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listRooms.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listRooms, request)); - }); + it('uses async iteration with listRooms with error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListRoomsRequest(), + ); + const expectedError = new Error('expected'); + client.descriptors.page.listRooms.asyncIterate = stubAsyncIterationCall( + undefined, + expectedError, + ); + const iterable = client.listRoomsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.showcase.v1beta1.IRoom[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + (client.descriptors.page.listRooms.asyncIterate as SinonStub).getCall(0) + .args[1], + request, + ); + }); + }); + + describe('listBlurbs', () => { + it('invokes listBlurbs without error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListBlurbsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.ListBlurbsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.showcase.v1beta1.Blurb()), + generateSampleMessage(new protos.google.showcase.v1beta1.Blurb()), + generateSampleMessage(new protos.google.showcase.v1beta1.Blurb()), + ]; + client.innerApiCalls.listBlurbs = stubSimpleCall(expectedResponse); + const [response] = await client.listBlurbs(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listBlurbs as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listBlurbs as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('uses async iteration with listRooms without error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListRoomsRequest() - ); - const expectedResponse = [ - generateSampleMessage(new protos.google.showcase.v1beta1.Room()), - generateSampleMessage(new protos.google.showcase.v1beta1.Room()), - generateSampleMessage(new protos.google.showcase.v1beta1.Room()), - ]; - client.descriptors.page.listRooms.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.showcase.v1beta1.IRoom[] = []; - const iterable = client.listRoomsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); + it('invokes listBlurbs without error using callback', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListBlurbsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.ListBlurbsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.showcase.v1beta1.Blurb()), + generateSampleMessage(new protos.google.showcase.v1beta1.Blurb()), + generateSampleMessage(new protos.google.showcase.v1beta1.Blurb()), + ]; + client.innerApiCalls.listBlurbs = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listBlurbs( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IBlurb[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listRooms.asyncIterate as SinonStub) - .getCall(0).args[1], request); - }); - - it('uses async iteration with listRooms with error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListRoomsRequest() - ); - const expectedError = new Error('expected'); - client.descriptors.page.listRooms.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listRoomsAsync(request); - await assert.rejects(async () => { - const responses: protos.google.showcase.v1beta1.IRoom[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listRooms.asyncIterate as SinonStub) - .getCall(0).args[1], request); - }); + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listBlurbs as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listBlurbs as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('listBlurbs', () => { - it('invokes listBlurbs without error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListBlurbsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.ListBlurbsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.showcase.v1beta1.Blurb()), - generateSampleMessage(new protos.google.showcase.v1beta1.Blurb()), - generateSampleMessage(new protos.google.showcase.v1beta1.Blurb()), - ]; - client.innerApiCalls.listBlurbs = stubSimpleCall(expectedResponse); - const [response] = await client.listBlurbs(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listBlurbs as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listBlurbs as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listBlurbs without error using callback', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListBlurbsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.ListBlurbsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.showcase.v1beta1.Blurb()), - generateSampleMessage(new protos.google.showcase.v1beta1.Blurb()), - generateSampleMessage(new protos.google.showcase.v1beta1.Blurb()), - ]; - client.innerApiCalls.listBlurbs = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listBlurbs( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IBlurb[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listBlurbs as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listBlurbs as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listBlurbs with error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListBlurbsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.ListBlurbsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listBlurbs = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listBlurbs(request), expectedError); - const actualRequest = (client.innerApiCalls.listBlurbs as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listBlurbs as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listBlurbsStream without error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListBlurbsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.ListBlurbsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.showcase.v1beta1.Blurb()), - generateSampleMessage(new protos.google.showcase.v1beta1.Blurb()), - generateSampleMessage(new protos.google.showcase.v1beta1.Blurb()), - ]; - client.descriptors.page.listBlurbs.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listBlurbsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.showcase.v1beta1.Blurb[] = []; - stream.on('data', (response: protos.google.showcase.v1beta1.Blurb) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.listBlurbs.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listBlurbs, request)); - assert( - (client.descriptors.page.listBlurbs.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listBlurbs with error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListBlurbsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.ListBlurbsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listBlurbs = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listBlurbs(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listBlurbs as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listBlurbs as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listBlurbsStream with error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListBlurbsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.ListBlurbsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listBlurbs.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listBlurbsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.showcase.v1beta1.Blurb[] = []; - stream.on('data', (response: protos.google.showcase.v1beta1.Blurb) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listBlurbs.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listBlurbs, request)); - assert( - (client.descriptors.page.listBlurbs.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listBlurbsStream without error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListBlurbsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.ListBlurbsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.showcase.v1beta1.Blurb()), + generateSampleMessage(new protos.google.showcase.v1beta1.Blurb()), + generateSampleMessage(new protos.google.showcase.v1beta1.Blurb()), + ]; + client.descriptors.page.listBlurbs.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listBlurbsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.showcase.v1beta1.Blurb[] = []; + stream.on('data', (response: protos.google.showcase.v1beta1.Blurb) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listBlurbs.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listBlurbs, request), + ); + assert( + (client.descriptors.page.listBlurbs.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('uses async iteration with listBlurbs without error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListBlurbsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.ListBlurbsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.showcase.v1beta1.Blurb()), - generateSampleMessage(new protos.google.showcase.v1beta1.Blurb()), - generateSampleMessage(new protos.google.showcase.v1beta1.Blurb()), - ]; - client.descriptors.page.listBlurbs.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.showcase.v1beta1.IBlurb[] = []; - const iterable = client.listBlurbsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listBlurbs.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listBlurbs.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listBlurbsStream with error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListBlurbsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.ListBlurbsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listBlurbs.createStream = stubPageStreamingCall( + undefined, + expectedError, + ); + const stream = client.listBlurbsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.showcase.v1beta1.Blurb[] = []; + stream.on('data', (response: protos.google.showcase.v1beta1.Blurb) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listBlurbs.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listBlurbs, request), + ); + assert( + (client.descriptors.page.listBlurbs.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('uses async iteration with listBlurbs with error', async () => { - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListBlurbsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.ListBlurbsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listBlurbs.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listBlurbsAsync(request); - await assert.rejects(async () => { - const responses: protos.google.showcase.v1beta1.IBlurb[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listBlurbs.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listBlurbs.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listBlurbs without error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListBlurbsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.ListBlurbsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.showcase.v1beta1.Blurb()), + generateSampleMessage(new protos.google.showcase.v1beta1.Blurb()), + generateSampleMessage(new protos.google.showcase.v1beta1.Blurb()), + ]; + client.descriptors.page.listBlurbs.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.showcase.v1beta1.IBlurb[] = []; + const iterable = client.listBlurbsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + (client.descriptors.page.listBlurbs.asyncIterate as SinonStub).getCall( + 0, + ).args[1], + request, + ); + assert( + (client.descriptors.page.listBlurbs.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); }); - describe('Path templates', () => { - - describe('blueprint', async () => { - const fakePath = "/rendered/path/blueprint"; - const expectedParameters = { - session: "sessionValue", - test: "testValue", - blueprint: "blueprintValue", - }; - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.blueprintPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.blueprintPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('blueprintPath', () => { - const result = client.blueprintPath("sessionValue", "testValue", "blueprintValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.blueprintPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchSessionFromBlueprintName', () => { - const result = client.matchSessionFromBlueprintName(fakePath); - assert.strictEqual(result, "sessionValue"); - assert((client.pathTemplates.blueprintPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchTestFromBlueprintName', () => { - const result = client.matchTestFromBlueprintName(fakePath); - assert.strictEqual(result, "testValue"); - assert((client.pathTemplates.blueprintPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBlueprintFromBlueprintName', () => { - const result = client.matchBlueprintFromBlueprintName(fakePath); - assert.strictEqual(result, "blueprintValue"); - assert((client.pathTemplates.blueprintPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('uses async iteration with listBlurbs with error', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListBlurbsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.ListBlurbsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listBlurbs.asyncIterate = stubAsyncIterationCall( + undefined, + expectedError, + ); + const iterable = client.listBlurbsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.showcase.v1beta1.IBlurb[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + (client.descriptors.page.listBlurbs.asyncIterate as SinonStub).getCall( + 0, + ).args[1], + request, + ); + assert( + (client.descriptors.page.listBlurbs.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + }); + + describe('Path templates', () => { + describe('blueprint', async () => { + const fakePath = '/rendered/path/blueprint'; + const expectedParameters = { + session: 'sessionValue', + test: 'testValue', + blueprint: 'blueprintValue', + }; + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.blueprintPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.blueprintPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('blueprintPath', () => { + const result = client.blueprintPath( + 'sessionValue', + 'testValue', + 'blueprintValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.blueprintPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchSessionFromBlueprintName', () => { + const result = client.matchSessionFromBlueprintName(fakePath); + assert.strictEqual(result, 'sessionValue'); + assert( + (client.pathTemplates.blueprintPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchTestFromBlueprintName', () => { + const result = client.matchTestFromBlueprintName(fakePath); + assert.strictEqual(result, 'testValue'); + assert( + (client.pathTemplates.blueprintPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBlueprintFromBlueprintName', () => { + const result = client.matchBlueprintFromBlueprintName(fakePath); + assert.strictEqual(result, 'blueprintValue'); + assert( + (client.pathTemplates.blueprintPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('room', async () => { - const fakePath = "/rendered/path/room"; - const expectedParameters = { - room: "roomValue", - }; - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.roomPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.roomPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('roomPath', () => { - const result = client.roomPath("roomValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.roomPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchRoomFromRoomName', () => { - const result = client.matchRoomFromRoomName(fakePath); - assert.strictEqual(result, "roomValue"); - assert((client.pathTemplates.roomPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('room', async () => { + const fakePath = '/rendered/path/room'; + const expectedParameters = { + room: 'roomValue', + }; + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.roomPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.roomPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('roomPath', () => { + const result = client.roomPath('roomValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.roomPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchRoomFromRoomName', () => { + const result = client.matchRoomFromRoomName(fakePath); + assert.strictEqual(result, 'roomValue'); + assert( + (client.pathTemplates.roomPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('roomBlurb', async () => { - const fakePath = "/rendered/path/roomBlurb"; - const expectedParameters = { - room: "roomValue", - blurb: "blurbValue", - }; - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.roomBlurbPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.roomBlurbPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('roomBlurbPath', () => { - const result = client.roomBlurbPath("roomValue", "blurbValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.roomBlurbPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchRoomFromRoomBlurbName', () => { - const result = client.matchRoomFromRoomBlurbName(fakePath); - assert.strictEqual(result, "roomValue"); - assert((client.pathTemplates.roomBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBlurbFromRoomBlurbName', () => { - const result = client.matchBlurbFromRoomBlurbName(fakePath); - assert.strictEqual(result, "blurbValue"); - assert((client.pathTemplates.roomBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('roomBlurb', async () => { + const fakePath = '/rendered/path/roomBlurb'; + const expectedParameters = { + room: 'roomValue', + blurb: 'blurbValue', + }; + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.roomBlurbPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.roomBlurbPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('roomBlurbPath', () => { + const result = client.roomBlurbPath('roomValue', 'blurbValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.roomBlurbPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchRoomFromRoomBlurbName', () => { + const result = client.matchRoomFromRoomBlurbName(fakePath); + assert.strictEqual(result, 'roomValue'); + assert( + (client.pathTemplates.roomBlurbPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBlurbFromRoomBlurbName', () => { + const result = client.matchBlurbFromRoomBlurbName(fakePath); + assert.strictEqual(result, 'blurbValue'); + assert( + (client.pathTemplates.roomBlurbPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('roomBlurbsLegacyRoomBlurb', async () => { - const fakePath = "/rendered/path/roomBlurbsLegacyRoomBlurb"; - const expectedParameters = { - room: "roomValue", - legacy_room: "legacyRoomValue", - blurb: "blurbValue", - }; - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('roomBlurbsLegacyRoomBlurbPath', () => { - const result = client.roomBlurbsLegacyRoomBlurbPath("roomValue", "legacyRoomValue", "blurbValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchRoomFromRoomBlurbsLegacyRoomBlurbName', () => { - const result = client.matchRoomFromRoomBlurbsLegacyRoomBlurbName(fakePath); - assert.strictEqual(result, "roomValue"); - assert((client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName', () => { - const result = client.matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName(fakePath); - assert.strictEqual(result, "legacyRoomValue"); - assert((client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBlurbFromRoomBlurbsLegacyRoomBlurbName', () => { - const result = client.matchBlurbFromRoomBlurbsLegacyRoomBlurbName(fakePath); - assert.strictEqual(result, "blurbValue"); - assert((client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('roomBlurbsLegacyRoomBlurb', async () => { + const fakePath = '/rendered/path/roomBlurbsLegacyRoomBlurb'; + const expectedParameters = { + room: 'roomValue', + legacy_room: 'legacyRoomValue', + blurb: 'blurbValue', + }; + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('roomBlurbsLegacyRoomBlurbPath', () => { + const result = client.roomBlurbsLegacyRoomBlurbPath( + 'roomValue', + 'legacyRoomValue', + 'blurbValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchRoomFromRoomBlurbsLegacyRoomBlurbName', () => { + const result = + client.matchRoomFromRoomBlurbsLegacyRoomBlurbName(fakePath); + assert.strictEqual(result, 'roomValue'); + assert( + ( + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName', () => { + const result = + client.matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName(fakePath); + assert.strictEqual(result, 'legacyRoomValue'); + assert( + ( + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBlurbFromRoomBlurbsLegacyRoomBlurbName', () => { + const result = + client.matchBlurbFromRoomBlurbsLegacyRoomBlurbName(fakePath); + assert.strictEqual(result, 'blurbValue'); + assert( + ( + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('sequence', async () => { - const fakePath = "/rendered/path/sequence"; - const expectedParameters = { - sequence: "sequenceValue", - }; - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.sequencePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.sequencePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('sequencePath', () => { - const result = client.sequencePath("sequenceValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.sequencePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchSequenceFromSequenceName', () => { - const result = client.matchSequenceFromSequenceName(fakePath); - assert.strictEqual(result, "sequenceValue"); - assert((client.pathTemplates.sequencePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('sequence', async () => { + const fakePath = '/rendered/path/sequence'; + const expectedParameters = { + sequence: 'sequenceValue', + }; + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.sequencePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.sequencePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('sequencePath', () => { + const result = client.sequencePath('sequenceValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.sequencePathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchSequenceFromSequenceName', () => { + const result = client.matchSequenceFromSequenceName(fakePath); + assert.strictEqual(result, 'sequenceValue'); + assert( + (client.pathTemplates.sequencePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('sequenceReport', async () => { - const fakePath = "/rendered/path/sequenceReport"; - const expectedParameters = { - sequence: "sequenceValue", - }; - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.sequenceReportPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.sequenceReportPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('sequenceReportPath', () => { - const result = client.sequenceReportPath("sequenceValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.sequenceReportPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchSequenceFromSequenceReportName', () => { - const result = client.matchSequenceFromSequenceReportName(fakePath); - assert.strictEqual(result, "sequenceValue"); - assert((client.pathTemplates.sequenceReportPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('sequenceReport', async () => { + const fakePath = '/rendered/path/sequenceReport'; + const expectedParameters = { + sequence: 'sequenceValue', + }; + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.sequenceReportPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.sequenceReportPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('sequenceReportPath', () => { + const result = client.sequenceReportPath('sequenceValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.sequenceReportPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchSequenceFromSequenceReportName', () => { + const result = client.matchSequenceFromSequenceReportName(fakePath); + assert.strictEqual(result, 'sequenceValue'); + assert( + (client.pathTemplates.sequenceReportPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('session', async () => { - const fakePath = "/rendered/path/session"; - const expectedParameters = { - session: "sessionValue", - }; - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.sessionPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.sessionPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('sessionPath', () => { - const result = client.sessionPath("sessionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.sessionPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchSessionFromSessionName', () => { - const result = client.matchSessionFromSessionName(fakePath); - assert.strictEqual(result, "sessionValue"); - assert((client.pathTemplates.sessionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('session', async () => { + const fakePath = '/rendered/path/session'; + const expectedParameters = { + session: 'sessionValue', + }; + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.sessionPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.sessionPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('sessionPath', () => { + const result = client.sessionPath('sessionValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.sessionPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchSessionFromSessionName', () => { + const result = client.matchSessionFromSessionName(fakePath); + assert.strictEqual(result, 'sessionValue'); + assert( + (client.pathTemplates.sessionPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('test', async () => { - const fakePath = "/rendered/path/test"; - const expectedParameters = { - session: "sessionValue", - test: "testValue", - }; - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.testPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.testPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('testPath', () => { - const result = client.testPath("sessionValue", "testValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.testPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchSessionFromTestName', () => { - const result = client.matchSessionFromTestName(fakePath); - assert.strictEqual(result, "sessionValue"); - assert((client.pathTemplates.testPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchTestFromTestName', () => { - const result = client.matchTestFromTestName(fakePath); - assert.strictEqual(result, "testValue"); - assert((client.pathTemplates.testPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('test', async () => { + const fakePath = '/rendered/path/test'; + const expectedParameters = { + session: 'sessionValue', + test: 'testValue', + }; + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.testPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.testPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('testPath', () => { + const result = client.testPath('sessionValue', 'testValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.testPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchSessionFromTestName', () => { + const result = client.matchSessionFromTestName(fakePath); + assert.strictEqual(result, 'sessionValue'); + assert( + (client.pathTemplates.testPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchTestFromTestName', () => { + const result = client.matchTestFromTestName(fakePath); + assert.strictEqual(result, 'testValue'); + assert( + (client.pathTemplates.testPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('user', async () => { - const fakePath = "/rendered/path/user"; - const expectedParameters = { - user: "userValue", - }; - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.userPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.userPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('userPath', () => { - const result = client.userPath("userValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.userPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchUserFromUserName', () => { - const result = client.matchUserFromUserName(fakePath); - assert.strictEqual(result, "userValue"); - assert((client.pathTemplates.userPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('user', async () => { + const fakePath = '/rendered/path/user'; + const expectedParameters = { + user: 'userValue', + }; + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.userPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.userPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('userPath', () => { + const result = client.userPath('userValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.userPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchUserFromUserName', () => { + const result = client.matchUserFromUserName(fakePath); + assert.strictEqual(result, 'userValue'); + assert( + (client.pathTemplates.userPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('userProfileBlurb', async () => { - const fakePath = "/rendered/path/userProfileBlurb"; - const expectedParameters = { - user: "userValue", - blurb: "blurbValue", - }; - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.userProfileBlurbPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.userProfileBlurbPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('userProfileBlurbPath', () => { - const result = client.userProfileBlurbPath("userValue", "blurbValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.userProfileBlurbPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchUserFromUserProfileBlurbName', () => { - const result = client.matchUserFromUserProfileBlurbName(fakePath); - assert.strictEqual(result, "userValue"); - assert((client.pathTemplates.userProfileBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBlurbFromUserProfileBlurbName', () => { - const result = client.matchBlurbFromUserProfileBlurbName(fakePath); - assert.strictEqual(result, "blurbValue"); - assert((client.pathTemplates.userProfileBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('userProfileBlurb', async () => { + const fakePath = '/rendered/path/userProfileBlurb'; + const expectedParameters = { + user: 'userValue', + blurb: 'blurbValue', + }; + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.userProfileBlurbPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.userProfileBlurbPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('userProfileBlurbPath', () => { + const result = client.userProfileBlurbPath('userValue', 'blurbValue'); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.userProfileBlurbPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchUserFromUserProfileBlurbName', () => { + const result = client.matchUserFromUserProfileBlurbName(fakePath); + assert.strictEqual(result, 'userValue'); + assert( + (client.pathTemplates.userProfileBlurbPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBlurbFromUserProfileBlurbName', () => { + const result = client.matchBlurbFromUserProfileBlurbName(fakePath); + assert.strictEqual(result, 'blurbValue'); + assert( + (client.pathTemplates.userProfileBlurbPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('userProfileBlurbsLegacyUserBlurb', async () => { - const fakePath = "/rendered/path/userProfileBlurbsLegacyUserBlurb"; - const expectedParameters = { - user: "userValue", - legacy_user: "legacyUserValue", - blurb: "blurbValue", - }; - const client = new messagingModule.v1beta1.MessagingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('userProfileBlurbsLegacyUserBlurbPath', () => { - const result = client.userProfileBlurbsLegacyUserBlurbPath("userValue", "legacyUserValue", "blurbValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchUserFromUserProfileBlurbsLegacyUserBlurbName', () => { - const result = client.matchUserFromUserProfileBlurbsLegacyUserBlurbName(fakePath); - assert.strictEqual(result, "userValue"); - assert((client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName', () => { - const result = client.matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName(fakePath); - assert.strictEqual(result, "legacyUserValue"); - assert((client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBlurbFromUserProfileBlurbsLegacyUserBlurbName', () => { - const result = client.matchBlurbFromUserProfileBlurbsLegacyUserBlurbName(fakePath); - assert.strictEqual(result, "blurbValue"); - assert((client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('userProfileBlurbsLegacyUserBlurb', async () => { + const fakePath = '/rendered/path/userProfileBlurbsLegacyUserBlurb'; + const expectedParameters = { + user: 'userValue', + legacy_user: 'legacyUserValue', + blurb: 'blurbValue', + }; + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('userProfileBlurbsLegacyUserBlurbPath', () => { + const result = client.userProfileBlurbsLegacyUserBlurbPath( + 'userValue', + 'legacyUserValue', + 'blurbValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchUserFromUserProfileBlurbsLegacyUserBlurbName', () => { + const result = + client.matchUserFromUserProfileBlurbsLegacyUserBlurbName(fakePath); + assert.strictEqual(result, 'userValue'); + assert( + ( + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName', () => { + const result = + client.matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName( + fakePath, + ); + assert.strictEqual(result, 'legacyUserValue'); + assert( + ( + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBlurbFromUserProfileBlurbsLegacyUserBlurbName', () => { + const result = + client.matchBlurbFromUserProfileBlurbsLegacyUserBlurbName(fakePath); + assert.strictEqual(result, 'blurbValue'); + assert( + ( + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/core/generator/gapic-generator-typescript/baselines/showcase/test/gapic_sequence_service_v1beta1.ts.baseline b/core/generator/gapic-generator-typescript/baselines/showcase/test/gapic_sequence_service_v1beta1.ts.baseline index e772cf81a761..a38f5ecf3aa4 100644 --- a/core/generator/gapic-generator-typescript/baselines/showcase/test/gapic_sequence_service_v1beta1.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/showcase/test/gapic_sequence_service_v1beta1.ts.baseline @@ -19,851 +19,1104 @@ import * as protos from '../protos/protos'; import * as assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as sequenceserviceModule from '../src'; -import {protobuf} from 'google-gax'; +import { protobuf } from 'google-gax'; // Dynamically loaded proto JSON is needed to get the type information // to fill in default values for request objects -const root = protobuf.Root.fromJSON(require('../protos/protos.json')).resolveAll(); +const root = protobuf.Root.fromJSON( + require('../protos/protos.json'), +).resolveAll(); // eslint-disable-next-line @typescript-eslint/no-unused-vars function getTypeDefaultValue(typeName: string, fields: string[]) { - let type = root.lookupType(typeName) as protobuf.Type; - for (const field of fields.slice(0, -1)) { - type = type.fields[field]?.resolvedType as protobuf.Type; - } - return type.fields[fields[fields.length - 1]]?.defaultValue; + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type.fields[field]?.resolvedType as protobuf.Type; + } + return type.fields[fields[fields.length - 1]]?.defaultValue; } function generateSampleMessage(instance: T) { - const filledObject = (instance.constructor as typeof protobuf.Message) - .toObject(instance as protobuf.Message, {defaults: true}); - return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, { defaults: true }); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; } function stubSimpleCall(response?: ResponseType, error?: Error) { - return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); } -function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { - return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +function stubSimpleCallWithCallback( + response?: ResponseType, + error?: Error, +) { + return error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); } describe('v1beta1.SequenceServiceClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'localhost'); - }); - - it('has universeDomain', () => { - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); - - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - it('throws DeprecationWarning if static servicePath is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const servicePath = sequenceserviceModule.v1beta1.SequenceServiceClient.servicePath; - assert.strictEqual(servicePath, 'localhost'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = sequenceserviceModule.v1beta1.SequenceServiceClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'localhost'); - assert(stub.called); - stub.restore(); - }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { new sequenceserviceModule.v1beta1.SequenceServiceClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); - - it('has port', () => { - const port = sequenceserviceModule.v1beta1.SequenceServiceClient.port; - assert(port); - assert(typeof port === 'number'); - }); - - it('should create a client with no option', () => { - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient(); - assert(client); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'localhost'); + }); - it('should create a client with gRPC fallback', () => { - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ - fallback: true, - }); - assert(client); - }); + it('has universeDomain', () => { + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - it('has initialize method and supports deferred initialization', async () => { - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.sequenceServiceStub, undefined); - await client.initialize(); - assert(client.sequenceServiceStub); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = + sequenceserviceModule.v1beta1.SequenceServiceClient.servicePath; + assert.strictEqual(servicePath, 'localhost'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + sequenceserviceModule.v1beta1.SequenceServiceClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'localhost'); + assert(stub.called); + stub.restore(); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new sequenceserviceModule.v1beta1.SequenceServiceClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); + }); - it('has close method for the initialized client', done => { - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.sequenceServiceStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('has port', () => { + const port = sequenceserviceModule.v1beta1.SequenceServiceClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('has close method for the non-initialized client', done => { - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.sequenceServiceStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('should create a client with no option', () => { + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient(); + assert(client); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); - }); + it('should create a client with gRPC fallback', () => { + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ + fallback: true, + }); + assert(client); + }); - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId((err?: Error|null, projectId?: string|null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } - }); - }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); - }); + it('has initialize method and supports deferred initialization', async () => { + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.sequenceServiceStub, undefined); + await client.initialize(); + assert(client.sequenceServiceStub); }); - describe('createSequence', () => { - it('invokes createSequence without error', async () => { - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.CreateSequenceRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.Sequence() - ); - client.innerApiCalls.createSequence = stubSimpleCall(expectedResponse); - const [response] = await client.createSequence(request); - assert.deepStrictEqual(response, expectedResponse); + it('has close method for the initialized client', (done) => { + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.sequenceServiceStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes createSequence without error using callback', async () => { - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.CreateSequenceRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.Sequence() - ); - client.innerApiCalls.createSequence = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createSequence( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.ISequence|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); + it('has close method for the non-initialized client', (done) => { + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.sequenceServiceStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes createSequence with error', async () => { - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.CreateSequenceRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.createSequence = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createSequence(request), expectedError); - }); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + }); - it('invokes createSequence with closed client', async () => { - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.CreateSequenceRequest() - ); - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createSequence(request), expectedError); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + }); + + describe('createSequence', () => { + it('invokes createSequence without error', async () => { + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.CreateSequenceRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.Sequence(), + ); + client.innerApiCalls.createSequence = stubSimpleCall(expectedResponse); + const [response] = await client.createSequence(request); + assert.deepStrictEqual(response, expectedResponse); }); - describe('getSequenceReport', () => { - it('invokes getSequenceReport without error', async () => { - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.GetSequenceReportRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.GetSequenceReportRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.SequenceReport() - ); - client.innerApiCalls.getSequenceReport = stubSimpleCall(expectedResponse); - const [response] = await client.getSequenceReport(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getSequenceReport as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getSequenceReport as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createSequence without error using callback', async () => { + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.CreateSequenceRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.Sequence(), + ); + client.innerApiCalls.createSequence = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createSequence( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.ISequence | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes getSequenceReport without error using callback', async () => { - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.GetSequenceReportRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.GetSequenceReportRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.SequenceReport() - ); - client.innerApiCalls.getSequenceReport = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getSequenceReport( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.ISequenceReport|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getSequenceReport as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getSequenceReport as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createSequence with error', async () => { + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.CreateSequenceRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.createSequence = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.createSequence(request), expectedError); + }); - it('invokes getSequenceReport with error', async () => { - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.GetSequenceReportRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.GetSequenceReportRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getSequenceReport = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getSequenceReport(request), expectedError); - const actualRequest = (client.innerApiCalls.getSequenceReport as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getSequenceReport as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createSequence with closed client', async () => { + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.CreateSequenceRequest(), + ); + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.createSequence(request), expectedError); + }); + }); + + describe('getSequenceReport', () => { + it('invokes getSequenceReport without error', async () => { + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.GetSequenceReportRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.GetSequenceReportRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.SequenceReport(), + ); + client.innerApiCalls.getSequenceReport = stubSimpleCall(expectedResponse); + const [response] = await client.getSequenceReport(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getSequenceReport as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getSequenceReport as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getSequenceReport with closed client', async () => { - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.GetSequenceReportRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.GetSequenceReportRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getSequenceReport(request), expectedError); - }); + it('invokes getSequenceReport without error using callback', async () => { + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.GetSequenceReportRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.GetSequenceReportRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.SequenceReport(), + ); + client.innerApiCalls.getSequenceReport = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getSequenceReport( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.ISequenceReport | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getSequenceReport as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getSequenceReport as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('attemptSequence', () => { - it('invokes attemptSequence without error', async () => { - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.AttemptSequenceRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.AttemptSequenceRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.attemptSequence = stubSimpleCall(expectedResponse); - const [response] = await client.attemptSequence(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.attemptSequence as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.attemptSequence as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getSequenceReport with error', async () => { + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.GetSequenceReportRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.GetSequenceReportRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getSequenceReport = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getSequenceReport(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getSequenceReport as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getSequenceReport as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes attemptSequence without error using callback', async () => { - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.AttemptSequenceRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.AttemptSequenceRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.attemptSequence = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.attemptSequence( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.attemptSequence as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.attemptSequence as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getSequenceReport with closed client', async () => { + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.GetSequenceReportRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.GetSequenceReportRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getSequenceReport(request), expectedError); + }); + }); + + describe('attemptSequence', () => { + it('invokes attemptSequence without error', async () => { + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.AttemptSequenceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.AttemptSequenceRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.attemptSequence = stubSimpleCall(expectedResponse); + const [response] = await client.attemptSequence(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.attemptSequence as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.attemptSequence as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes attemptSequence with error', async () => { - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.AttemptSequenceRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.AttemptSequenceRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.attemptSequence = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.attemptSequence(request), expectedError); - const actualRequest = (client.innerApiCalls.attemptSequence as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.attemptSequence as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes attemptSequence without error using callback', async () => { + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.AttemptSequenceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.AttemptSequenceRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.attemptSequence = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.attemptSequence( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.attemptSequence as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.attemptSequence as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes attemptSequence with closed client', async () => { - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.AttemptSequenceRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.AttemptSequenceRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.attemptSequence(request), expectedError); - }); + it('invokes attemptSequence with error', async () => { + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.AttemptSequenceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.AttemptSequenceRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.attemptSequence = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.attemptSequence(request), expectedError); + const actualRequest = ( + client.innerApiCalls.attemptSequence as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.attemptSequence as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('Path templates', () => { - - describe('blueprint', async () => { - const fakePath = "/rendered/path/blueprint"; - const expectedParameters = { - session: "sessionValue", - test: "testValue", - blueprint: "blueprintValue", - }; - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.blueprintPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.blueprintPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('blueprintPath', () => { - const result = client.blueprintPath("sessionValue", "testValue", "blueprintValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.blueprintPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchSessionFromBlueprintName', () => { - const result = client.matchSessionFromBlueprintName(fakePath); - assert.strictEqual(result, "sessionValue"); - assert((client.pathTemplates.blueprintPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchTestFromBlueprintName', () => { - const result = client.matchTestFromBlueprintName(fakePath); - assert.strictEqual(result, "testValue"); - assert((client.pathTemplates.blueprintPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBlueprintFromBlueprintName', () => { - const result = client.matchBlueprintFromBlueprintName(fakePath); - assert.strictEqual(result, "blueprintValue"); - assert((client.pathTemplates.blueprintPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('invokes attemptSequence with closed client', async () => { + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.AttemptSequenceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.AttemptSequenceRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.attemptSequence(request), expectedError); + }); + }); + + describe('Path templates', () => { + describe('blueprint', async () => { + const fakePath = '/rendered/path/blueprint'; + const expectedParameters = { + session: 'sessionValue', + test: 'testValue', + blueprint: 'blueprintValue', + }; + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.blueprintPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.blueprintPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('blueprintPath', () => { + const result = client.blueprintPath( + 'sessionValue', + 'testValue', + 'blueprintValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.blueprintPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchSessionFromBlueprintName', () => { + const result = client.matchSessionFromBlueprintName(fakePath); + assert.strictEqual(result, 'sessionValue'); + assert( + (client.pathTemplates.blueprintPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchTestFromBlueprintName', () => { + const result = client.matchTestFromBlueprintName(fakePath); + assert.strictEqual(result, 'testValue'); + assert( + (client.pathTemplates.blueprintPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBlueprintFromBlueprintName', () => { + const result = client.matchBlueprintFromBlueprintName(fakePath); + assert.strictEqual(result, 'blueprintValue'); + assert( + (client.pathTemplates.blueprintPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('room', async () => { - const fakePath = "/rendered/path/room"; - const expectedParameters = { - room: "roomValue", - }; - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.roomPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.roomPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('roomPath', () => { - const result = client.roomPath("roomValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.roomPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchRoomFromRoomName', () => { - const result = client.matchRoomFromRoomName(fakePath); - assert.strictEqual(result, "roomValue"); - assert((client.pathTemplates.roomPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('room', async () => { + const fakePath = '/rendered/path/room'; + const expectedParameters = { + room: 'roomValue', + }; + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.roomPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.roomPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('roomPath', () => { + const result = client.roomPath('roomValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.roomPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchRoomFromRoomName', () => { + const result = client.matchRoomFromRoomName(fakePath); + assert.strictEqual(result, 'roomValue'); + assert( + (client.pathTemplates.roomPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('roomBlurb', async () => { - const fakePath = "/rendered/path/roomBlurb"; - const expectedParameters = { - room: "roomValue", - blurb: "blurbValue", - }; - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.roomBlurbPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.roomBlurbPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('roomBlurbPath', () => { - const result = client.roomBlurbPath("roomValue", "blurbValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.roomBlurbPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchRoomFromRoomBlurbName', () => { - const result = client.matchRoomFromRoomBlurbName(fakePath); - assert.strictEqual(result, "roomValue"); - assert((client.pathTemplates.roomBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBlurbFromRoomBlurbName', () => { - const result = client.matchBlurbFromRoomBlurbName(fakePath); - assert.strictEqual(result, "blurbValue"); - assert((client.pathTemplates.roomBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('roomBlurb', async () => { + const fakePath = '/rendered/path/roomBlurb'; + const expectedParameters = { + room: 'roomValue', + blurb: 'blurbValue', + }; + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.roomBlurbPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.roomBlurbPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('roomBlurbPath', () => { + const result = client.roomBlurbPath('roomValue', 'blurbValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.roomBlurbPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchRoomFromRoomBlurbName', () => { + const result = client.matchRoomFromRoomBlurbName(fakePath); + assert.strictEqual(result, 'roomValue'); + assert( + (client.pathTemplates.roomBlurbPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBlurbFromRoomBlurbName', () => { + const result = client.matchBlurbFromRoomBlurbName(fakePath); + assert.strictEqual(result, 'blurbValue'); + assert( + (client.pathTemplates.roomBlurbPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('roomBlurbsLegacyRoomBlurb', async () => { - const fakePath = "/rendered/path/roomBlurbsLegacyRoomBlurb"; - const expectedParameters = { - room: "roomValue", - legacy_room: "legacyRoomValue", - blurb: "blurbValue", - }; - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('roomBlurbsLegacyRoomBlurbPath', () => { - const result = client.roomBlurbsLegacyRoomBlurbPath("roomValue", "legacyRoomValue", "blurbValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchRoomFromRoomBlurbsLegacyRoomBlurbName', () => { - const result = client.matchRoomFromRoomBlurbsLegacyRoomBlurbName(fakePath); - assert.strictEqual(result, "roomValue"); - assert((client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName', () => { - const result = client.matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName(fakePath); - assert.strictEqual(result, "legacyRoomValue"); - assert((client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBlurbFromRoomBlurbsLegacyRoomBlurbName', () => { - const result = client.matchBlurbFromRoomBlurbsLegacyRoomBlurbName(fakePath); - assert.strictEqual(result, "blurbValue"); - assert((client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('roomBlurbsLegacyRoomBlurb', async () => { + const fakePath = '/rendered/path/roomBlurbsLegacyRoomBlurb'; + const expectedParameters = { + room: 'roomValue', + legacy_room: 'legacyRoomValue', + blurb: 'blurbValue', + }; + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('roomBlurbsLegacyRoomBlurbPath', () => { + const result = client.roomBlurbsLegacyRoomBlurbPath( + 'roomValue', + 'legacyRoomValue', + 'blurbValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchRoomFromRoomBlurbsLegacyRoomBlurbName', () => { + const result = + client.matchRoomFromRoomBlurbsLegacyRoomBlurbName(fakePath); + assert.strictEqual(result, 'roomValue'); + assert( + ( + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName', () => { + const result = + client.matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName(fakePath); + assert.strictEqual(result, 'legacyRoomValue'); + assert( + ( + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBlurbFromRoomBlurbsLegacyRoomBlurbName', () => { + const result = + client.matchBlurbFromRoomBlurbsLegacyRoomBlurbName(fakePath); + assert.strictEqual(result, 'blurbValue'); + assert( + ( + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('sequence', async () => { - const fakePath = "/rendered/path/sequence"; - const expectedParameters = { - sequence: "sequenceValue", - }; - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.sequencePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.sequencePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('sequencePath', () => { - const result = client.sequencePath("sequenceValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.sequencePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchSequenceFromSequenceName', () => { - const result = client.matchSequenceFromSequenceName(fakePath); - assert.strictEqual(result, "sequenceValue"); - assert((client.pathTemplates.sequencePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('sequence', async () => { + const fakePath = '/rendered/path/sequence'; + const expectedParameters = { + sequence: 'sequenceValue', + }; + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.sequencePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.sequencePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('sequencePath', () => { + const result = client.sequencePath('sequenceValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.sequencePathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchSequenceFromSequenceName', () => { + const result = client.matchSequenceFromSequenceName(fakePath); + assert.strictEqual(result, 'sequenceValue'); + assert( + (client.pathTemplates.sequencePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('sequenceReport', async () => { - const fakePath = "/rendered/path/sequenceReport"; - const expectedParameters = { - sequence: "sequenceValue", - }; - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.sequenceReportPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.sequenceReportPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('sequenceReportPath', () => { - const result = client.sequenceReportPath("sequenceValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.sequenceReportPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchSequenceFromSequenceReportName', () => { - const result = client.matchSequenceFromSequenceReportName(fakePath); - assert.strictEqual(result, "sequenceValue"); - assert((client.pathTemplates.sequenceReportPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('sequenceReport', async () => { + const fakePath = '/rendered/path/sequenceReport'; + const expectedParameters = { + sequence: 'sequenceValue', + }; + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.sequenceReportPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.sequenceReportPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('sequenceReportPath', () => { + const result = client.sequenceReportPath('sequenceValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.sequenceReportPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchSequenceFromSequenceReportName', () => { + const result = client.matchSequenceFromSequenceReportName(fakePath); + assert.strictEqual(result, 'sequenceValue'); + assert( + (client.pathTemplates.sequenceReportPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('session', async () => { - const fakePath = "/rendered/path/session"; - const expectedParameters = { - session: "sessionValue", - }; - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.sessionPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.sessionPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('sessionPath', () => { - const result = client.sessionPath("sessionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.sessionPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchSessionFromSessionName', () => { - const result = client.matchSessionFromSessionName(fakePath); - assert.strictEqual(result, "sessionValue"); - assert((client.pathTemplates.sessionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('session', async () => { + const fakePath = '/rendered/path/session'; + const expectedParameters = { + session: 'sessionValue', + }; + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.sessionPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.sessionPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('sessionPath', () => { + const result = client.sessionPath('sessionValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.sessionPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchSessionFromSessionName', () => { + const result = client.matchSessionFromSessionName(fakePath); + assert.strictEqual(result, 'sessionValue'); + assert( + (client.pathTemplates.sessionPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('test', async () => { - const fakePath = "/rendered/path/test"; - const expectedParameters = { - session: "sessionValue", - test: "testValue", - }; - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.testPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.testPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('testPath', () => { - const result = client.testPath("sessionValue", "testValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.testPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchSessionFromTestName', () => { - const result = client.matchSessionFromTestName(fakePath); - assert.strictEqual(result, "sessionValue"); - assert((client.pathTemplates.testPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchTestFromTestName', () => { - const result = client.matchTestFromTestName(fakePath); - assert.strictEqual(result, "testValue"); - assert((client.pathTemplates.testPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('test', async () => { + const fakePath = '/rendered/path/test'; + const expectedParameters = { + session: 'sessionValue', + test: 'testValue', + }; + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.testPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.testPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('testPath', () => { + const result = client.testPath('sessionValue', 'testValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.testPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchSessionFromTestName', () => { + const result = client.matchSessionFromTestName(fakePath); + assert.strictEqual(result, 'sessionValue'); + assert( + (client.pathTemplates.testPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchTestFromTestName', () => { + const result = client.matchTestFromTestName(fakePath); + assert.strictEqual(result, 'testValue'); + assert( + (client.pathTemplates.testPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('user', async () => { - const fakePath = "/rendered/path/user"; - const expectedParameters = { - user: "userValue", - }; - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.userPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.userPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('userPath', () => { - const result = client.userPath("userValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.userPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchUserFromUserName', () => { - const result = client.matchUserFromUserName(fakePath); - assert.strictEqual(result, "userValue"); - assert((client.pathTemplates.userPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('user', async () => { + const fakePath = '/rendered/path/user'; + const expectedParameters = { + user: 'userValue', + }; + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.userPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.userPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('userPath', () => { + const result = client.userPath('userValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.userPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchUserFromUserName', () => { + const result = client.matchUserFromUserName(fakePath); + assert.strictEqual(result, 'userValue'); + assert( + (client.pathTemplates.userPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('userProfileBlurb', async () => { - const fakePath = "/rendered/path/userProfileBlurb"; - const expectedParameters = { - user: "userValue", - blurb: "blurbValue", - }; - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.userProfileBlurbPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.userProfileBlurbPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('userProfileBlurbPath', () => { - const result = client.userProfileBlurbPath("userValue", "blurbValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.userProfileBlurbPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchUserFromUserProfileBlurbName', () => { - const result = client.matchUserFromUserProfileBlurbName(fakePath); - assert.strictEqual(result, "userValue"); - assert((client.pathTemplates.userProfileBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBlurbFromUserProfileBlurbName', () => { - const result = client.matchBlurbFromUserProfileBlurbName(fakePath); - assert.strictEqual(result, "blurbValue"); - assert((client.pathTemplates.userProfileBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('userProfileBlurb', async () => { + const fakePath = '/rendered/path/userProfileBlurb'; + const expectedParameters = { + user: 'userValue', + blurb: 'blurbValue', + }; + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.userProfileBlurbPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.userProfileBlurbPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('userProfileBlurbPath', () => { + const result = client.userProfileBlurbPath('userValue', 'blurbValue'); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.userProfileBlurbPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchUserFromUserProfileBlurbName', () => { + const result = client.matchUserFromUserProfileBlurbName(fakePath); + assert.strictEqual(result, 'userValue'); + assert( + (client.pathTemplates.userProfileBlurbPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBlurbFromUserProfileBlurbName', () => { + const result = client.matchBlurbFromUserProfileBlurbName(fakePath); + assert.strictEqual(result, 'blurbValue'); + assert( + (client.pathTemplates.userProfileBlurbPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('userProfileBlurbsLegacyUserBlurb', async () => { - const fakePath = "/rendered/path/userProfileBlurbsLegacyUserBlurb"; - const expectedParameters = { - user: "userValue", - legacy_user: "legacyUserValue", - blurb: "blurbValue", - }; - const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('userProfileBlurbsLegacyUserBlurbPath', () => { - const result = client.userProfileBlurbsLegacyUserBlurbPath("userValue", "legacyUserValue", "blurbValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchUserFromUserProfileBlurbsLegacyUserBlurbName', () => { - const result = client.matchUserFromUserProfileBlurbsLegacyUserBlurbName(fakePath); - assert.strictEqual(result, "userValue"); - assert((client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName', () => { - const result = client.matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName(fakePath); - assert.strictEqual(result, "legacyUserValue"); - assert((client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBlurbFromUserProfileBlurbsLegacyUserBlurbName', () => { - const result = client.matchBlurbFromUserProfileBlurbsLegacyUserBlurbName(fakePath); - assert.strictEqual(result, "blurbValue"); - assert((client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('userProfileBlurbsLegacyUserBlurb', async () => { + const fakePath = '/rendered/path/userProfileBlurbsLegacyUserBlurb'; + const expectedParameters = { + user: 'userValue', + legacy_user: 'legacyUserValue', + blurb: 'blurbValue', + }; + const client = new sequenceserviceModule.v1beta1.SequenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('userProfileBlurbsLegacyUserBlurbPath', () => { + const result = client.userProfileBlurbsLegacyUserBlurbPath( + 'userValue', + 'legacyUserValue', + 'blurbValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchUserFromUserProfileBlurbsLegacyUserBlurbName', () => { + const result = + client.matchUserFromUserProfileBlurbsLegacyUserBlurbName(fakePath); + assert.strictEqual(result, 'userValue'); + assert( + ( + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName', () => { + const result = + client.matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName( + fakePath, + ); + assert.strictEqual(result, 'legacyUserValue'); + assert( + ( + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBlurbFromUserProfileBlurbsLegacyUserBlurbName', () => { + const result = + client.matchBlurbFromUserProfileBlurbsLegacyUserBlurbName(fakePath); + assert.strictEqual(result, 'blurbValue'); + assert( + ( + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/core/generator/gapic-generator-typescript/baselines/showcase/test/gapic_testing_v1beta1.ts.baseline b/core/generator/gapic-generator-typescript/baselines/showcase/test/gapic_testing_v1beta1.ts.baseline index 55e55cff9e27..2a880c521c73 100644 --- a/core/generator/gapic-generator-typescript/baselines/showcase/test/gapic_testing_v1beta1.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/showcase/test/gapic_testing_v1beta1.ts.baseline @@ -19,1642 +19,2064 @@ import * as protos from '../protos/protos'; import * as assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as testingModule from '../src'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; -import {protobuf} from 'google-gax'; +import { protobuf } from 'google-gax'; // Dynamically loaded proto JSON is needed to get the type information // to fill in default values for request objects -const root = protobuf.Root.fromJSON(require('../protos/protos.json')).resolveAll(); +const root = protobuf.Root.fromJSON( + require('../protos/protos.json'), +).resolveAll(); // eslint-disable-next-line @typescript-eslint/no-unused-vars function getTypeDefaultValue(typeName: string, fields: string[]) { - let type = root.lookupType(typeName) as protobuf.Type; - for (const field of fields.slice(0, -1)) { - type = type.fields[field]?.resolvedType as protobuf.Type; - } - return type.fields[fields[fields.length - 1]]?.defaultValue; + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type.fields[field]?.resolvedType as protobuf.Type; + } + return type.fields[fields[fields.length - 1]]?.defaultValue; } function generateSampleMessage(instance: T) { - const filledObject = (instance.constructor as typeof protobuf.Message) - .toObject(instance as protobuf.Message, {defaults: true}); - return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, { defaults: true }); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; } function stubSimpleCall(response?: ResponseType, error?: Error) { - return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); } -function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { - return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +function stubSimpleCallWithCallback( + response?: ResponseType, + error?: Error, +) { + return error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); } -function stubPageStreamingCall(responses?: ResponseType[], error?: Error) { - const pagingStub = sinon.stub(); - if (responses) { - for (let i = 0; i < responses.length; ++i) { - pagingStub.onCall(i).callsArgWith(2, null, responses[i]); - } +function stubPageStreamingCall( + responses?: ResponseType[], + error?: Error, +) { + const pagingStub = sinon.stub(); + if (responses) { + for (let i = 0; i < responses.length; ++i) { + pagingStub.onCall(i).callsArgWith(2, null, responses[i]); } - const transformStub = error ? sinon.stub().callsArgWith(2, error) : pagingStub; - const mockStream = new PassThrough({ - objectMode: true, - transform: transformStub, - }); - // trigger as many responses as needed - if (responses) { - for (let i = 0; i < responses.length; ++i) { - setImmediate(() => { mockStream.write({}); }); - } - setImmediate(() => { mockStream.end(); }); - } else { - setImmediate(() => { mockStream.write({}); }); - setImmediate(() => { mockStream.end(); }); + } + const transformStub = error + ? sinon.stub().callsArgWith(2, error) + : pagingStub; + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + // trigger as many responses as needed + if (responses) { + for (let i = 0; i < responses.length; ++i) { + setImmediate(() => { + mockStream.write({}); + }); } - return sinon.stub().returns(mockStream); + setImmediate(() => { + mockStream.end(); + }); + } else { + setImmediate(() => { + mockStream.write({}); + }); + setImmediate(() => { + mockStream.end(); + }); + } + return sinon.stub().returns(mockStream); } -function stubAsyncIterationCall(responses?: ResponseType[], error?: Error) { - let counter = 0; - const asyncIterable = { - [Symbol.asyncIterator]() { - return { - async next() { - if (error) { - return Promise.reject(error); - } - if (counter >= responses!.length) { - return Promise.resolve({done: true, value: undefined}); - } - return Promise.resolve({done: false, value: responses![counter++]}); - } - }; - } - }; - return sinon.stub().returns(asyncIterable); +function stubAsyncIterationCall( + responses?: ResponseType[], + error?: Error, +) { + let counter = 0; + const asyncIterable = { + [Symbol.asyncIterator]() { + return { + async next() { + if (error) { + return Promise.reject(error); + } + if (counter >= responses!.length) { + return Promise.resolve({ done: true, value: undefined }); + } + return Promise.resolve({ done: false, value: responses![counter++] }); + }, + }; + }, + }; + return sinon.stub().returns(asyncIterable); } describe('v1beta1.TestingClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new testingModule.v1beta1.TestingClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'localhost'); - }); - - it('has universeDomain', () => { - const client = new testingModule.v1beta1.TestingClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); - - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - it('throws DeprecationWarning if static servicePath is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const servicePath = testingModule.v1beta1.TestingClient.servicePath; - assert.strictEqual(servicePath, 'localhost'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = testingModule.v1beta1.TestingClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'localhost'); - assert(stub.called); - stub.restore(); - }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { new testingModule.v1beta1.TestingClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new testingModule.v1beta1.TestingClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'localhost'); + }); - it('has port', () => { - const port = testingModule.v1beta1.TestingClient.port; - assert(port); - assert(typeof port === 'number'); - }); + it('has universeDomain', () => { + const client = new testingModule.v1beta1.TestingClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - it('should create a client with no option', () => { - const client = new testingModule.v1beta1.TestingClient(); - assert(client); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = testingModule.v1beta1.TestingClient.servicePath; + assert.strictEqual(servicePath, 'localhost'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = testingModule.v1beta1.TestingClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'localhost'); + assert(stub.called); + stub.restore(); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new testingModule.v1beta1.TestingClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); + }); - it('should create a client with gRPC fallback', () => { - const client = new testingModule.v1beta1.TestingClient({ - fallback: true, - }); - assert(client); - }); + it('has port', () => { + const port = testingModule.v1beta1.TestingClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('has initialize method and supports deferred initialization', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.testingStub, undefined); - await client.initialize(); - assert(client.testingStub); - }); + it('should create a client with no option', () => { + const client = new testingModule.v1beta1.TestingClient(); + assert(client); + }); - it('has close method for the initialized client', done => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.testingStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('should create a client with gRPC fallback', () => { + const client = new testingModule.v1beta1.TestingClient({ + fallback: true, + }); + assert(client); + }); - it('has close method for the non-initialized client', done => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.testingStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('has initialize method and supports deferred initialization', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.testingStub, undefined); + await client.initialize(); + assert(client.testingStub); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + it('has close method for the initialized client', (done) => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.testingStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId((err?: Error|null, projectId?: string|null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } - }); - }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); + it('has close method for the non-initialized client', (done) => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.testingStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); }); - describe('createSession', () => { - it('invokes createSession without error', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.CreateSessionRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.Session() - ); - client.innerApiCalls.createSession = stubSimpleCall(expectedResponse); - const [response] = await client.createSession(request); - assert.deepStrictEqual(response, expectedResponse); - }); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + }); - it('invokes createSession without error using callback', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.CreateSessionRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.Session() - ); - client.innerApiCalls.createSession = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createSession( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.ISession|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + }); + + describe('createSession', () => { + it('invokes createSession without error', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.CreateSessionRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.Session(), + ); + client.innerApiCalls.createSession = stubSimpleCall(expectedResponse); + const [response] = await client.createSession(request); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes createSession with error', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.CreateSessionRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.createSession = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createSession(request), expectedError); - }); + it('invokes createSession without error using callback', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.CreateSessionRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.Session(), + ); + client.innerApiCalls.createSession = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createSession( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.ISession | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes createSession with closed client', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.CreateSessionRequest() - ); - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createSession(request), expectedError); - }); + it('invokes createSession with error', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.CreateSessionRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.createSession = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.createSession(request), expectedError); }); - describe('getSession', () => { - it('invokes getSession without error', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.GetSessionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.GetSessionRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.Session() - ); - client.innerApiCalls.getSession = stubSimpleCall(expectedResponse); - const [response] = await client.getSession(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getSession as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getSession as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createSession with closed client', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.CreateSessionRequest(), + ); + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.createSession(request), expectedError); + }); + }); + + describe('getSession', () => { + it('invokes getSession without error', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.GetSessionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.GetSessionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.Session(), + ); + client.innerApiCalls.getSession = stubSimpleCall(expectedResponse); + const [response] = await client.getSession(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getSession as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getSession as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getSession without error using callback', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.GetSessionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.GetSessionRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.Session() - ); - client.innerApiCalls.getSession = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getSession( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.ISession|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getSession as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getSession as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getSession without error using callback', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.GetSessionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.GetSessionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.Session(), + ); + client.innerApiCalls.getSession = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getSession( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.ISession | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getSession as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getSession as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getSession with error', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.GetSessionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.GetSessionRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getSession = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getSession(request), expectedError); - const actualRequest = (client.innerApiCalls.getSession as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getSession as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getSession with error', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.GetSessionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.GetSessionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getSession = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getSession(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getSession as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getSession as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getSession with closed client', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.GetSessionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.GetSessionRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getSession(request), expectedError); - }); + it('invokes getSession with closed client', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.GetSessionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.GetSessionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getSession(request), expectedError); + }); + }); + + describe('deleteSession', () => { + it('invokes deleteSession without error', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.DeleteSessionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.DeleteSessionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteSession = stubSimpleCall(expectedResponse); + const [response] = await client.deleteSession(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteSession as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteSession as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('deleteSession', () => { - it('invokes deleteSession without error', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.DeleteSessionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.DeleteSessionRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteSession = stubSimpleCall(expectedResponse); - const [response] = await client.deleteSession(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteSession as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteSession as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteSession without error using callback', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.DeleteSessionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.DeleteSessionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteSession = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteSession( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteSession as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteSession as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteSession without error using callback', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.DeleteSessionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.DeleteSessionRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteSession = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteSession( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteSession as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteSession as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteSession with error', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.DeleteSessionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.DeleteSessionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteSession = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.deleteSession(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteSession as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteSession as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteSession with error', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.DeleteSessionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.DeleteSessionRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteSession = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteSession(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteSession as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteSession as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteSession with closed client', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.DeleteSessionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.DeleteSessionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.deleteSession(request), expectedError); + }); + }); + + describe('reportSession', () => { + it('invokes reportSession without error', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ReportSessionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.ReportSessionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.ReportSessionResponse(), + ); + client.innerApiCalls.reportSession = stubSimpleCall(expectedResponse); + const [response] = await client.reportSession(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.reportSession as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.reportSession as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteSession with closed client', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.DeleteSessionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.DeleteSessionRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteSession(request), expectedError); - }); + it('invokes reportSession without error using callback', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ReportSessionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.ReportSessionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.ReportSessionResponse(), + ); + client.innerApiCalls.reportSession = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.reportSession( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IReportSessionResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.reportSession as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.reportSession as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('reportSession', () => { - it('invokes reportSession without error', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ReportSessionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.ReportSessionRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.ReportSessionResponse() - ); - client.innerApiCalls.reportSession = stubSimpleCall(expectedResponse); - const [response] = await client.reportSession(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.reportSession as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.reportSession as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes reportSession with error', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ReportSessionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.ReportSessionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.reportSession = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.reportSession(request), expectedError); + const actualRequest = ( + client.innerApiCalls.reportSession as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.reportSession as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes reportSession without error using callback', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ReportSessionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.ReportSessionRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.ReportSessionResponse() - ); - client.innerApiCalls.reportSession = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.reportSession( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IReportSessionResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.reportSession as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.reportSession as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes reportSession with closed client', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ReportSessionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.ReportSessionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.reportSession(request), expectedError); + }); + }); + + describe('deleteTest', () => { + it('invokes deleteTest without error', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.DeleteTestRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.DeleteTestRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteTest = stubSimpleCall(expectedResponse); + const [response] = await client.deleteTest(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteTest as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteTest as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes reportSession with error', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ReportSessionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.ReportSessionRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.reportSession = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.reportSession(request), expectedError); - const actualRequest = (client.innerApiCalls.reportSession as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.reportSession as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteTest without error using callback', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.DeleteTestRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.DeleteTestRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteTest = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteTest( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteTest as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteTest as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes reportSession with closed client', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ReportSessionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.ReportSessionRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.reportSession(request), expectedError); - }); + it('invokes deleteTest with error', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.DeleteTestRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.DeleteTestRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteTest = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.deleteTest(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteTest as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteTest as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('deleteTest', () => { - it('invokes deleteTest without error', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.DeleteTestRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.DeleteTestRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteTest = stubSimpleCall(expectedResponse); - const [response] = await client.deleteTest(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteTest as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteTest as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteTest with closed client', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.DeleteTestRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.DeleteTestRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.deleteTest(request), expectedError); + }); + }); + + describe('verifyTest', () => { + it('invokes verifyTest without error', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.VerifyTestRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.VerifyTestRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.VerifyTestResponse(), + ); + client.innerApiCalls.verifyTest = stubSimpleCall(expectedResponse); + const [response] = await client.verifyTest(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.verifyTest as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.verifyTest as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteTest without error using callback', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.DeleteTestRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.DeleteTestRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteTest = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteTest( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteTest as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteTest as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes verifyTest without error using callback', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.VerifyTestRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.VerifyTestRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.showcase.v1beta1.VerifyTestResponse(), + ); + client.innerApiCalls.verifyTest = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.verifyTest( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.IVerifyTestResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.verifyTest as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.verifyTest as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteTest with error', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.DeleteTestRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.DeleteTestRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteTest = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteTest(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteTest as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteTest as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes verifyTest with error', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.VerifyTestRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.VerifyTestRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.verifyTest = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.verifyTest(request), expectedError); + const actualRequest = ( + client.innerApiCalls.verifyTest as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.verifyTest as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteTest with closed client', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.DeleteTestRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.DeleteTestRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteTest(request), expectedError); - }); + it('invokes verifyTest with closed client', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.VerifyTestRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.VerifyTestRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.verifyTest(request), expectedError); + }); + }); + + describe('listSessions', () => { + it('invokes listSessions without error', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListSessionsRequest(), + ); + const expectedResponse = [ + generateSampleMessage(new protos.google.showcase.v1beta1.Session()), + generateSampleMessage(new protos.google.showcase.v1beta1.Session()), + generateSampleMessage(new protos.google.showcase.v1beta1.Session()), + ]; + client.innerApiCalls.listSessions = stubSimpleCall(expectedResponse); + const [response] = await client.listSessions(request); + assert.deepStrictEqual(response, expectedResponse); }); - describe('verifyTest', () => { - it('invokes verifyTest without error', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.VerifyTestRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.VerifyTestRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.VerifyTestResponse() - ); - client.innerApiCalls.verifyTest = stubSimpleCall(expectedResponse); - const [response] = await client.verifyTest(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.verifyTest as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.verifyTest as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listSessions without error using callback', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListSessionsRequest(), + ); + const expectedResponse = [ + generateSampleMessage(new protos.google.showcase.v1beta1.Session()), + generateSampleMessage(new protos.google.showcase.v1beta1.Session()), + generateSampleMessage(new protos.google.showcase.v1beta1.Session()), + ]; + client.innerApiCalls.listSessions = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listSessions( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.ISession[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes verifyTest without error using callback', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.VerifyTestRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.VerifyTestRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.showcase.v1beta1.VerifyTestResponse() - ); - client.innerApiCalls.verifyTest = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.verifyTest( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.IVerifyTestResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.verifyTest as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.verifyTest as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listSessions with error', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListSessionsRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.listSessions = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listSessions(request), expectedError); + }); - it('invokes verifyTest with error', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.VerifyTestRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.VerifyTestRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.verifyTest = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.verifyTest(request), expectedError); - const actualRequest = (client.innerApiCalls.verifyTest as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.verifyTest as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes listSessionsStream without error', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListSessionsRequest(), + ); + const expectedResponse = [ + generateSampleMessage(new protos.google.showcase.v1beta1.Session()), + generateSampleMessage(new protos.google.showcase.v1beta1.Session()), + generateSampleMessage(new protos.google.showcase.v1beta1.Session()), + ]; + client.descriptors.page.listSessions.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listSessionsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.showcase.v1beta1.Session[] = []; + stream.on( + 'data', + (response: protos.google.showcase.v1beta1.Session) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); }); - - it('invokes verifyTest with closed client', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.VerifyTestRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.VerifyTestRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.verifyTest(request), expectedError); + stream.on('error', (err: Error) => { + reject(err); }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listSessions.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listSessions, request), + ); }); - describe('listSessions', () => { - it('invokes listSessions without error', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListSessionsRequest() - );const expectedResponse = [ - generateSampleMessage(new protos.google.showcase.v1beta1.Session()), - generateSampleMessage(new protos.google.showcase.v1beta1.Session()), - generateSampleMessage(new protos.google.showcase.v1beta1.Session()), - ]; - client.innerApiCalls.listSessions = stubSimpleCall(expectedResponse); - const [response] = await client.listSessions(request); - assert.deepStrictEqual(response, expectedResponse); - }); - - it('invokes listSessions without error using callback', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListSessionsRequest() - );const expectedResponse = [ - generateSampleMessage(new protos.google.showcase.v1beta1.Session()), - generateSampleMessage(new protos.google.showcase.v1beta1.Session()), - generateSampleMessage(new protos.google.showcase.v1beta1.Session()), - ]; - client.innerApiCalls.listSessions = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listSessions( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.ISession[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); + it('invokes listSessionsStream with error', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListSessionsRequest(), + ); + const expectedError = new Error('expected'); + client.descriptors.page.listSessions.createStream = stubPageStreamingCall( + undefined, + expectedError, + ); + const stream = client.listSessionsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.showcase.v1beta1.Session[] = []; + stream.on( + 'data', + (response: protos.google.showcase.v1beta1.Session) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); }); - - it('invokes listSessions with error', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListSessionsRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.listSessions = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listSessions(request), expectedError); + stream.on('error', (err: Error) => { + reject(err); }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listSessions.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listSessions, request), + ); + }); - it('invokes listSessionsStream without error', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListSessionsRequest() - ); - const expectedResponse = [ - generateSampleMessage(new protos.google.showcase.v1beta1.Session()), - generateSampleMessage(new protos.google.showcase.v1beta1.Session()), - generateSampleMessage(new protos.google.showcase.v1beta1.Session()), - ]; - client.descriptors.page.listSessions.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listSessionsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.showcase.v1beta1.Session[] = []; - stream.on('data', (response: protos.google.showcase.v1beta1.Session) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.listSessions.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listSessions, request)); - }); + it('uses async iteration with listSessions without error', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListSessionsRequest(), + ); + const expectedResponse = [ + generateSampleMessage(new protos.google.showcase.v1beta1.Session()), + generateSampleMessage(new protos.google.showcase.v1beta1.Session()), + generateSampleMessage(new protos.google.showcase.v1beta1.Session()), + ]; + client.descriptors.page.listSessions.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.showcase.v1beta1.ISession[] = []; + const iterable = client.listSessionsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listSessions.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + }); - it('invokes listSessionsStream with error', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListSessionsRequest() - ); - const expectedError = new Error('expected'); - client.descriptors.page.listSessions.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listSessionsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.showcase.v1beta1.Session[] = []; - stream.on('data', (response: protos.google.showcase.v1beta1.Session) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listSessions.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listSessions, request)); - }); + it('uses async iteration with listSessions with error', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListSessionsRequest(), + ); + const expectedError = new Error('expected'); + client.descriptors.page.listSessions.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listSessionsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.showcase.v1beta1.ISession[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listSessions.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + }); + }); + + describe('listTests', () => { + it('invokes listTests without error', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListTestsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.ListTestsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.showcase.v1beta1.Test()), + generateSampleMessage(new protos.google.showcase.v1beta1.Test()), + generateSampleMessage(new protos.google.showcase.v1beta1.Test()), + ]; + client.innerApiCalls.listTests = stubSimpleCall(expectedResponse); + const [response] = await client.listTests(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listTests as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listTests as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('uses async iteration with listSessions without error', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListSessionsRequest() - ); - const expectedResponse = [ - generateSampleMessage(new protos.google.showcase.v1beta1.Session()), - generateSampleMessage(new protos.google.showcase.v1beta1.Session()), - generateSampleMessage(new protos.google.showcase.v1beta1.Session()), - ]; - client.descriptors.page.listSessions.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.showcase.v1beta1.ISession[] = []; - const iterable = client.listSessionsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); + it('invokes listTests without error using callback', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListTestsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.ListTestsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.showcase.v1beta1.Test()), + generateSampleMessage(new protos.google.showcase.v1beta1.Test()), + generateSampleMessage(new protos.google.showcase.v1beta1.Test()), + ]; + client.innerApiCalls.listTests = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listTests( + request, + ( + err?: Error | null, + result?: protos.google.showcase.v1beta1.ITest[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listSessions.asyncIterate as SinonStub) - .getCall(0).args[1], request); - }); + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listTests as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listTests as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('uses async iteration with listSessions with error', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListSessionsRequest() - ); - const expectedError = new Error('expected'); - client.descriptors.page.listSessions.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listSessionsAsync(request); - await assert.rejects(async () => { - const responses: protos.google.showcase.v1beta1.ISession[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listSessions.asyncIterate as SinonStub) - .getCall(0).args[1], request); - }); + it('invokes listTests with error', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListTestsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.ListTestsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listTests = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.listTests(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listTests as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listTests as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('listTests', () => { - it('invokes listTests without error', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListTestsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.ListTestsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.showcase.v1beta1.Test()), - generateSampleMessage(new protos.google.showcase.v1beta1.Test()), - generateSampleMessage(new protos.google.showcase.v1beta1.Test()), - ]; - client.innerApiCalls.listTests = stubSimpleCall(expectedResponse); - const [response] = await client.listTests(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listTests as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listTests as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes listTestsStream without error', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListTestsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.ListTestsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.showcase.v1beta1.Test()), + generateSampleMessage(new protos.google.showcase.v1beta1.Test()), + generateSampleMessage(new protos.google.showcase.v1beta1.Test()), + ]; + client.descriptors.page.listTests.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listTestsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.showcase.v1beta1.Test[] = []; + stream.on('data', (response: protos.google.showcase.v1beta1.Test) => { + responses.push(response); }); - - it('invokes listTests without error using callback', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListTestsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.ListTestsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.showcase.v1beta1.Test()), - generateSampleMessage(new protos.google.showcase.v1beta1.Test()), - generateSampleMessage(new protos.google.showcase.v1beta1.Test()), - ]; - client.innerApiCalls.listTests = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listTests( - request, - (err?: Error|null, result?: protos.google.showcase.v1beta1.ITest[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listTests as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listTests as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + stream.on('end', () => { + resolve(responses); }); - - it('invokes listTests with error', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListTestsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.ListTestsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listTests = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listTests(request), expectedError); - const actualRequest = (client.innerApiCalls.listTests as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listTests as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + stream.on('error', (err: Error) => { + reject(err); }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listTests.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listTests, request), + ); + assert( + (client.descriptors.page.listTests.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('invokes listTestsStream without error', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListTestsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.ListTestsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.showcase.v1beta1.Test()), - generateSampleMessage(new protos.google.showcase.v1beta1.Test()), - generateSampleMessage(new protos.google.showcase.v1beta1.Test()), - ]; - client.descriptors.page.listTests.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listTestsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.showcase.v1beta1.Test[] = []; - stream.on('data', (response: protos.google.showcase.v1beta1.Test) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.listTests.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listTests, request)); - assert( - (client.descriptors.page.listTests.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); + it('invokes listTestsStream with error', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListTestsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.ListTestsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listTests.createStream = stubPageStreamingCall( + undefined, + expectedError, + ); + const stream = client.listTestsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.showcase.v1beta1.Test[] = []; + stream.on('data', (response: protos.google.showcase.v1beta1.Test) => { + responses.push(response); }); - - it('invokes listTestsStream with error', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListTestsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.ListTestsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listTests.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listTestsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.showcase.v1beta1.Test[] = []; - stream.on('data', (response: protos.google.showcase.v1beta1.Test) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listTests.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listTests, request)); - assert( - (client.descriptors.page.listTests.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); + stream.on('end', () => { + resolve(responses); }); - - it('uses async iteration with listTests without error', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListTestsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.ListTestsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.showcase.v1beta1.Test()), - generateSampleMessage(new protos.google.showcase.v1beta1.Test()), - generateSampleMessage(new protos.google.showcase.v1beta1.Test()), - ]; - client.descriptors.page.listTests.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.showcase.v1beta1.ITest[] = []; - const iterable = client.listTestsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listTests.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listTests.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); + stream.on('error', (err: Error) => { + reject(err); }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listTests.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listTests, request), + ); + assert( + (client.descriptors.page.listTests.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('uses async iteration with listTests with error', async () => { - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.showcase.v1beta1.ListTestsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.showcase.v1beta1.ListTestsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listTests.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listTestsAsync(request); - await assert.rejects(async () => { - const responses: protos.google.showcase.v1beta1.ITest[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listTests.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listTests.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listTests without error', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListTestsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.ListTestsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.showcase.v1beta1.Test()), + generateSampleMessage(new protos.google.showcase.v1beta1.Test()), + generateSampleMessage(new protos.google.showcase.v1beta1.Test()), + ]; + client.descriptors.page.listTests.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.showcase.v1beta1.ITest[] = []; + const iterable = client.listTestsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + (client.descriptors.page.listTests.asyncIterate as SinonStub).getCall(0) + .args[1], + request, + ); + assert( + (client.descriptors.page.listTests.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); }); - describe('Path templates', () => { - - describe('blueprint', async () => { - const fakePath = "/rendered/path/blueprint"; - const expectedParameters = { - session: "sessionValue", - test: "testValue", - blueprint: "blueprintValue", - }; - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.blueprintPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.blueprintPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('blueprintPath', () => { - const result = client.blueprintPath("sessionValue", "testValue", "blueprintValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.blueprintPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchSessionFromBlueprintName', () => { - const result = client.matchSessionFromBlueprintName(fakePath); - assert.strictEqual(result, "sessionValue"); - assert((client.pathTemplates.blueprintPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchTestFromBlueprintName', () => { - const result = client.matchTestFromBlueprintName(fakePath); - assert.strictEqual(result, "testValue"); - assert((client.pathTemplates.blueprintPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBlueprintFromBlueprintName', () => { - const result = client.matchBlueprintFromBlueprintName(fakePath); - assert.strictEqual(result, "blueprintValue"); - assert((client.pathTemplates.blueprintPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('uses async iteration with listTests with error', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.showcase.v1beta1.ListTestsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.showcase.v1beta1.ListTestsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listTests.asyncIterate = stubAsyncIterationCall( + undefined, + expectedError, + ); + const iterable = client.listTestsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.showcase.v1beta1.ITest[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + (client.descriptors.page.listTests.asyncIterate as SinonStub).getCall(0) + .args[1], + request, + ); + assert( + (client.descriptors.page.listTests.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + }); + + describe('Path templates', () => { + describe('blueprint', async () => { + const fakePath = '/rendered/path/blueprint'; + const expectedParameters = { + session: 'sessionValue', + test: 'testValue', + blueprint: 'blueprintValue', + }; + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.blueprintPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.blueprintPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('blueprintPath', () => { + const result = client.blueprintPath( + 'sessionValue', + 'testValue', + 'blueprintValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.blueprintPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchSessionFromBlueprintName', () => { + const result = client.matchSessionFromBlueprintName(fakePath); + assert.strictEqual(result, 'sessionValue'); + assert( + (client.pathTemplates.blueprintPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchTestFromBlueprintName', () => { + const result = client.matchTestFromBlueprintName(fakePath); + assert.strictEqual(result, 'testValue'); + assert( + (client.pathTemplates.blueprintPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBlueprintFromBlueprintName', () => { + const result = client.matchBlueprintFromBlueprintName(fakePath); + assert.strictEqual(result, 'blueprintValue'); + assert( + (client.pathTemplates.blueprintPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('room', async () => { - const fakePath = "/rendered/path/room"; - const expectedParameters = { - room: "roomValue", - }; - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.roomPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.roomPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('roomPath', () => { - const result = client.roomPath("roomValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.roomPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchRoomFromRoomName', () => { - const result = client.matchRoomFromRoomName(fakePath); - assert.strictEqual(result, "roomValue"); - assert((client.pathTemplates.roomPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('room', async () => { + const fakePath = '/rendered/path/room'; + const expectedParameters = { + room: 'roomValue', + }; + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.roomPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.roomPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('roomPath', () => { + const result = client.roomPath('roomValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.roomPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchRoomFromRoomName', () => { + const result = client.matchRoomFromRoomName(fakePath); + assert.strictEqual(result, 'roomValue'); + assert( + (client.pathTemplates.roomPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('roomBlurb', async () => { - const fakePath = "/rendered/path/roomBlurb"; - const expectedParameters = { - room: "roomValue", - blurb: "blurbValue", - }; - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.roomBlurbPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.roomBlurbPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('roomBlurbPath', () => { - const result = client.roomBlurbPath("roomValue", "blurbValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.roomBlurbPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchRoomFromRoomBlurbName', () => { - const result = client.matchRoomFromRoomBlurbName(fakePath); - assert.strictEqual(result, "roomValue"); - assert((client.pathTemplates.roomBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBlurbFromRoomBlurbName', () => { - const result = client.matchBlurbFromRoomBlurbName(fakePath); - assert.strictEqual(result, "blurbValue"); - assert((client.pathTemplates.roomBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('roomBlurb', async () => { + const fakePath = '/rendered/path/roomBlurb'; + const expectedParameters = { + room: 'roomValue', + blurb: 'blurbValue', + }; + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.roomBlurbPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.roomBlurbPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('roomBlurbPath', () => { + const result = client.roomBlurbPath('roomValue', 'blurbValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.roomBlurbPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchRoomFromRoomBlurbName', () => { + const result = client.matchRoomFromRoomBlurbName(fakePath); + assert.strictEqual(result, 'roomValue'); + assert( + (client.pathTemplates.roomBlurbPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBlurbFromRoomBlurbName', () => { + const result = client.matchBlurbFromRoomBlurbName(fakePath); + assert.strictEqual(result, 'blurbValue'); + assert( + (client.pathTemplates.roomBlurbPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('roomBlurbsLegacyRoomBlurb', async () => { - const fakePath = "/rendered/path/roomBlurbsLegacyRoomBlurb"; - const expectedParameters = { - room: "roomValue", - legacy_room: "legacyRoomValue", - blurb: "blurbValue", - }; - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('roomBlurbsLegacyRoomBlurbPath', () => { - const result = client.roomBlurbsLegacyRoomBlurbPath("roomValue", "legacyRoomValue", "blurbValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchRoomFromRoomBlurbsLegacyRoomBlurbName', () => { - const result = client.matchRoomFromRoomBlurbsLegacyRoomBlurbName(fakePath); - assert.strictEqual(result, "roomValue"); - assert((client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName', () => { - const result = client.matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName(fakePath); - assert.strictEqual(result, "legacyRoomValue"); - assert((client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBlurbFromRoomBlurbsLegacyRoomBlurbName', () => { - const result = client.matchBlurbFromRoomBlurbsLegacyRoomBlurbName(fakePath); - assert.strictEqual(result, "blurbValue"); - assert((client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('roomBlurbsLegacyRoomBlurb', async () => { + const fakePath = '/rendered/path/roomBlurbsLegacyRoomBlurb'; + const expectedParameters = { + room: 'roomValue', + legacy_room: 'legacyRoomValue', + blurb: 'blurbValue', + }; + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('roomBlurbsLegacyRoomBlurbPath', () => { + const result = client.roomBlurbsLegacyRoomBlurbPath( + 'roomValue', + 'legacyRoomValue', + 'blurbValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchRoomFromRoomBlurbsLegacyRoomBlurbName', () => { + const result = + client.matchRoomFromRoomBlurbsLegacyRoomBlurbName(fakePath); + assert.strictEqual(result, 'roomValue'); + assert( + ( + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName', () => { + const result = + client.matchLegacyRoomFromRoomBlurbsLegacyRoomBlurbName(fakePath); + assert.strictEqual(result, 'legacyRoomValue'); + assert( + ( + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBlurbFromRoomBlurbsLegacyRoomBlurbName', () => { + const result = + client.matchBlurbFromRoomBlurbsLegacyRoomBlurbName(fakePath); + assert.strictEqual(result, 'blurbValue'); + assert( + ( + client.pathTemplates.roomBlurbsLegacyRoomBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('sequence', async () => { - const fakePath = "/rendered/path/sequence"; - const expectedParameters = { - sequence: "sequenceValue", - }; - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.sequencePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.sequencePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('sequencePath', () => { - const result = client.sequencePath("sequenceValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.sequencePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchSequenceFromSequenceName', () => { - const result = client.matchSequenceFromSequenceName(fakePath); - assert.strictEqual(result, "sequenceValue"); - assert((client.pathTemplates.sequencePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('sequence', async () => { + const fakePath = '/rendered/path/sequence'; + const expectedParameters = { + sequence: 'sequenceValue', + }; + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.sequencePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.sequencePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('sequencePath', () => { + const result = client.sequencePath('sequenceValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.sequencePathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchSequenceFromSequenceName', () => { + const result = client.matchSequenceFromSequenceName(fakePath); + assert.strictEqual(result, 'sequenceValue'); + assert( + (client.pathTemplates.sequencePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('sequenceReport', async () => { - const fakePath = "/rendered/path/sequenceReport"; - const expectedParameters = { - sequence: "sequenceValue", - }; - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.sequenceReportPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.sequenceReportPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('sequenceReportPath', () => { - const result = client.sequenceReportPath("sequenceValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.sequenceReportPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchSequenceFromSequenceReportName', () => { - const result = client.matchSequenceFromSequenceReportName(fakePath); - assert.strictEqual(result, "sequenceValue"); - assert((client.pathTemplates.sequenceReportPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('sequenceReport', async () => { + const fakePath = '/rendered/path/sequenceReport'; + const expectedParameters = { + sequence: 'sequenceValue', + }; + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.sequenceReportPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.sequenceReportPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('sequenceReportPath', () => { + const result = client.sequenceReportPath('sequenceValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.sequenceReportPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchSequenceFromSequenceReportName', () => { + const result = client.matchSequenceFromSequenceReportName(fakePath); + assert.strictEqual(result, 'sequenceValue'); + assert( + (client.pathTemplates.sequenceReportPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('session', async () => { - const fakePath = "/rendered/path/session"; - const expectedParameters = { - session: "sessionValue", - }; - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.sessionPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.sessionPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('sessionPath', () => { - const result = client.sessionPath("sessionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.sessionPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchSessionFromSessionName', () => { - const result = client.matchSessionFromSessionName(fakePath); - assert.strictEqual(result, "sessionValue"); - assert((client.pathTemplates.sessionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('session', async () => { + const fakePath = '/rendered/path/session'; + const expectedParameters = { + session: 'sessionValue', + }; + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.sessionPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.sessionPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('sessionPath', () => { + const result = client.sessionPath('sessionValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.sessionPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchSessionFromSessionName', () => { + const result = client.matchSessionFromSessionName(fakePath); + assert.strictEqual(result, 'sessionValue'); + assert( + (client.pathTemplates.sessionPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('test', async () => { - const fakePath = "/rendered/path/test"; - const expectedParameters = { - session: "sessionValue", - test: "testValue", - }; - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.testPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.testPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('testPath', () => { - const result = client.testPath("sessionValue", "testValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.testPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchSessionFromTestName', () => { - const result = client.matchSessionFromTestName(fakePath); - assert.strictEqual(result, "sessionValue"); - assert((client.pathTemplates.testPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchTestFromTestName', () => { - const result = client.matchTestFromTestName(fakePath); - assert.strictEqual(result, "testValue"); - assert((client.pathTemplates.testPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('test', async () => { + const fakePath = '/rendered/path/test'; + const expectedParameters = { + session: 'sessionValue', + test: 'testValue', + }; + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.testPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.testPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('testPath', () => { + const result = client.testPath('sessionValue', 'testValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.testPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchSessionFromTestName', () => { + const result = client.matchSessionFromTestName(fakePath); + assert.strictEqual(result, 'sessionValue'); + assert( + (client.pathTemplates.testPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchTestFromTestName', () => { + const result = client.matchTestFromTestName(fakePath); + assert.strictEqual(result, 'testValue'); + assert( + (client.pathTemplates.testPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('user', async () => { - const fakePath = "/rendered/path/user"; - const expectedParameters = { - user: "userValue", - }; - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.userPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.userPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('userPath', () => { - const result = client.userPath("userValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.userPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchUserFromUserName', () => { - const result = client.matchUserFromUserName(fakePath); - assert.strictEqual(result, "userValue"); - assert((client.pathTemplates.userPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('user', async () => { + const fakePath = '/rendered/path/user'; + const expectedParameters = { + user: 'userValue', + }; + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.userPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.userPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('userPath', () => { + const result = client.userPath('userValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.userPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchUserFromUserName', () => { + const result = client.matchUserFromUserName(fakePath); + assert.strictEqual(result, 'userValue'); + assert( + (client.pathTemplates.userPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('userProfileBlurb', async () => { - const fakePath = "/rendered/path/userProfileBlurb"; - const expectedParameters = { - user: "userValue", - blurb: "blurbValue", - }; - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.userProfileBlurbPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.userProfileBlurbPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('userProfileBlurbPath', () => { - const result = client.userProfileBlurbPath("userValue", "blurbValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.userProfileBlurbPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchUserFromUserProfileBlurbName', () => { - const result = client.matchUserFromUserProfileBlurbName(fakePath); - assert.strictEqual(result, "userValue"); - assert((client.pathTemplates.userProfileBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBlurbFromUserProfileBlurbName', () => { - const result = client.matchBlurbFromUserProfileBlurbName(fakePath); - assert.strictEqual(result, "blurbValue"); - assert((client.pathTemplates.userProfileBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('userProfileBlurb', async () => { + const fakePath = '/rendered/path/userProfileBlurb'; + const expectedParameters = { + user: 'userValue', + blurb: 'blurbValue', + }; + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.userProfileBlurbPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.userProfileBlurbPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('userProfileBlurbPath', () => { + const result = client.userProfileBlurbPath('userValue', 'blurbValue'); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.userProfileBlurbPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchUserFromUserProfileBlurbName', () => { + const result = client.matchUserFromUserProfileBlurbName(fakePath); + assert.strictEqual(result, 'userValue'); + assert( + (client.pathTemplates.userProfileBlurbPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBlurbFromUserProfileBlurbName', () => { + const result = client.matchBlurbFromUserProfileBlurbName(fakePath); + assert.strictEqual(result, 'blurbValue'); + assert( + (client.pathTemplates.userProfileBlurbPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('userProfileBlurbsLegacyUserBlurb', async () => { - const fakePath = "/rendered/path/userProfileBlurbsLegacyUserBlurb"; - const expectedParameters = { - user: "userValue", - legacy_user: "legacyUserValue", - blurb: "blurbValue", - }; - const client = new testingModule.v1beta1.TestingClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('userProfileBlurbsLegacyUserBlurbPath', () => { - const result = client.userProfileBlurbsLegacyUserBlurbPath("userValue", "legacyUserValue", "blurbValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchUserFromUserProfileBlurbsLegacyUserBlurbName', () => { - const result = client.matchUserFromUserProfileBlurbsLegacyUserBlurbName(fakePath); - assert.strictEqual(result, "userValue"); - assert((client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName', () => { - const result = client.matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName(fakePath); - assert.strictEqual(result, "legacyUserValue"); - assert((client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBlurbFromUserProfileBlurbsLegacyUserBlurbName', () => { - const result = client.matchBlurbFromUserProfileBlurbsLegacyUserBlurbName(fakePath); - assert.strictEqual(result, "blurbValue"); - assert((client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('userProfileBlurbsLegacyUserBlurb', async () => { + const fakePath = '/rendered/path/userProfileBlurbsLegacyUserBlurb'; + const expectedParameters = { + user: 'userValue', + legacy_user: 'legacyUserValue', + blurb: 'blurbValue', + }; + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('userProfileBlurbsLegacyUserBlurbPath', () => { + const result = client.userProfileBlurbsLegacyUserBlurbPath( + 'userValue', + 'legacyUserValue', + 'blurbValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchUserFromUserProfileBlurbsLegacyUserBlurbName', () => { + const result = + client.matchUserFromUserProfileBlurbsLegacyUserBlurbName(fakePath); + assert.strictEqual(result, 'userValue'); + assert( + ( + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName', () => { + const result = + client.matchLegacyUserFromUserProfileBlurbsLegacyUserBlurbName( + fakePath, + ); + assert.strictEqual(result, 'legacyUserValue'); + assert( + ( + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBlurbFromUserProfileBlurbsLegacyUserBlurbName', () => { + const result = + client.matchBlurbFromUserProfileBlurbsLegacyUserBlurbName(fakePath); + assert.strictEqual(result, 'blurbValue'); + assert( + ( + client.pathTemplates.userProfileBlurbsLegacyUserBlurbPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/core/generator/gapic-generator-typescript/baselines/tasks-esm/esm/src/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/tasks-esm/esm/src/index.ts.baseline index c75be9420e92..2ee09c05ac2b 100644 --- a/core/generator/gapic-generator-typescript/baselines/tasks-esm/esm/src/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/tasks-esm/esm/src/index.ts.baseline @@ -19,8 +19,8 @@ import * as v2 from './v2/index.js'; const CloudTasksClient = v2.CloudTasksClient; type CloudTasksClient = v2.CloudTasksClient; -export {v2, CloudTasksClient}; -export default {v2, CloudTasksClient}; +export { v2, CloudTasksClient }; +export default { v2, CloudTasksClient }; // @ts-ignore import * as protos from '../../protos/protos.js'; -export {protos} +export { protos }; diff --git a/core/generator/gapic-generator-typescript/baselines/tasks-esm/esm/src/v2/cloud_tasks_client.ts.baseline b/core/generator/gapic-generator-typescript/baselines/tasks-esm/esm/src/v2/cloud_tasks_client.ts.baseline index 99acceadff63..043cbcc1846b 100644 --- a/core/generator/gapic-generator-typescript/baselines/tasks-esm/esm/src/v2/cloud_tasks_client.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/tasks-esm/esm/src/v2/cloud_tasks_client.ts.baseline @@ -18,15 +18,22 @@ /* global window */ import * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions, PaginationCallback, GaxCall} from 'google-gax'; -import {Transform} from 'stream'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + PaginationCallback, + GaxCall, +} from 'google-gax'; +import { Transform } from 'stream'; // @ts-ignore import type * as protos from '../../../protos/protos.js'; import * as cloud_tasks_client_config from './cloud_tasks_client_config.json'; import fs from 'fs'; import path from 'path'; -import {fileURLToPath} from 'url'; -import {getJSON} from '../json-helper.cjs'; +import { fileURLToPath } from 'url'; +import { getJSON } from '../json-helper.cjs'; // @ts-ignore const dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -36,15 +43,15 @@ const dirname = path.dirname(fileURLToPath(import.meta.url)); * This file defines retry strategy and timeouts for all API methods in this library. */ const gapicConfig = getJSON( - path.join(dirname, 'cloud_tasks_client_config.json') + path.join(dirname, 'cloud_tasks_client_config.json'), ); const jsonProtos = getJSON( - path.join(dirname, '..', '..', '..', 'protos/protos.json') + path.join(dirname, '..', '..', '..', 'protos/protos.json'), ); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; const version = getJSON( - path.join(dirname, '..', '..', '..', '..', 'package.json') + path.join(dirname, '..', '..', '..', '..', 'package.json'), ).version; /** @@ -60,7 +67,7 @@ export class CloudTasksClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('tasks'); @@ -72,9 +79,9 @@ export class CloudTasksClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; - cloudTasksStub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; + cloudTasksStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of CloudTasksClient. @@ -116,21 +123,42 @@ export class CloudTasksClient { * const client = new CloudTasksClient({fallback: 'rest'}, gax); * ``` */ - constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { // Ensure that options include all the required fields. const staticMembers = this.constructor as typeof CloudTasksClient; - if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { - throw new Error('Please set either universe_domain or universeDomain, but not both.'); + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); } - const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; - this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; this._servicePath = 'cloudtasks.' + this._universeDomain; - const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; - const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. if (servicePath !== this._servicePath && !('scopes' in opts)) { @@ -152,7 +180,7 @@ export class CloudTasksClient { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; @@ -169,10 +197,7 @@ export class CloudTasksClient { const isEsm = true; const isEsmString = isEsm ? '-esm' : '-cjs'; // Determine the client header string. - const clientHeader = [ - `gax/${this._gaxModule.version}`, - `gapic/${version}`, - ]; + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/{process.versions.node}${isEsmString}`); } else { @@ -180,7 +205,7 @@ export class CloudTasksClient { } if (!opts.fallback) { clientHeader.push(`grpc/${this._gaxGrpc.grpcVersion}`); - } else if (opts.fallback === 'rest' ) { + } else if (opts.fallback === 'rest') { clientHeader.push(`rest/${this._gaxGrpc.grpcVersion}`); } if (opts.libName && opts.libVersion) { @@ -188,17 +213,19 @@ export class CloudTasksClient { } // Load the applicable protos. - this._protos = this._gaxGrpc.loadProtoJSON(jsonProtos as gax.protobuf.INamespace); + this._protos = this._gaxGrpc.loadProtoJSON( + jsonProtos as gax.protobuf.INamespace, + ); // This API contains "path templates"; forward-slash-separated // identifiers to uniquely identify resources within the API. // Create useful helper objects for these. this.pathTemplates = { queuePathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/queues/{queue}' + 'projects/{project}/locations/{location}/queues/{queue}', ), taskPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/queues/{queue}/tasks/{task}' + 'projects/{project}/locations/{location}/queues/{queue}/tasks/{task}', ), }; @@ -206,16 +233,25 @@ export class CloudTasksClient { // (e.g. 50 results at a time, with tokens to get subsequent // pages). Denote the keys used for pagination and results. this.descriptors.page = { - listQueues: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'queues'), - listTasks: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'tasks') + listQueues: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'queues', + ), + listTasks: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'tasks', + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.cloud.tasks.v2.CloudTasks', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.cloud.tasks.v2.CloudTasks', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + { 'x-goog-api-client': clientHeader.join(' ') }, + ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -246,37 +282,57 @@ export class CloudTasksClient { // Put together the "service stub" for // google.cloud.tasks.v2.CloudTasks. this.cloudTasksStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.cloud.tasks.v2.CloudTasks') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.cloud.tasks.v2.CloudTasks', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.cloud.tasks.v2.CloudTasks, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts, + this._providedCustomServicePath, + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const cloudTasksStubMethods = - ['listQueues', 'getQueue', 'createQueue', 'updateQueue', 'deleteQueue', 'purgeQueue', 'pauseQueue', 'resumeQueue', 'getIamPolicy', 'setIamPolicy', 'testIamPermissions', 'listTasks', 'getTask', 'createTask', 'deleteTask', 'runTask']; + const cloudTasksStubMethods = [ + 'listQueues', + 'getQueue', + 'createQueue', + 'updateQueue', + 'deleteQueue', + 'purgeQueue', + 'pauseQueue', + 'resumeQueue', + 'getIamPolicy', + 'setIamPolicy', + 'testIamPermissions', + 'listTasks', + 'getTask', + 'createTask', + 'deleteTask', + 'runTask', + ]; for (const methodName of cloudTasksStubMethods) { const callPromise = this.cloudTasksStub.then( - stub => (...args: Array<{}>) => { - if (this._terminated) { - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error|null|undefined) => () => { + (stub) => + (...args: Array<{}>) => { + if (this._terminated) { + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { throw err; - }); + }, + ); - const descriptor = - this.descriptors.page[methodName] || - undefined; + const descriptor = this.descriptors.page[methodName] || undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -291,8 +347,14 @@ export class CloudTasksClient { * @returns {string} The DNS address for this service. */ static get servicePath() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'cloudtasks.googleapis.com'; } @@ -304,8 +366,14 @@ export class CloudTasksClient { * @returns {string} The DNS address for this service. */ static get apiEndpoint() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'cloudtasks.googleapis.com'; } @@ -336,9 +404,7 @@ export class CloudTasksClient { * @returns {string[]} List of default scopes. */ static get scopes() { - return [ - 'https://www.googleapis.com/auth/cloud-platform' - ]; + return ['https://www.googleapis.com/auth/cloud-platform']; } getProjectId(): Promise; @@ -347,8 +413,9 @@ export class CloudTasksClient { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId(callback?: Callback): - Promise|void { + getProjectId( + callback?: Callback, + ): Promise | void { if (callback) { this.auth.getProjectId(callback); return; @@ -359,1652 +426,2101 @@ export class CloudTasksClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Gets a queue. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The resource name of the queue. For example: - * `projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID` - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.tasks.v2.Queue|Queue}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/cloud_tasks.get_queue.js - * region_tag:cloudtasks_v2_generated_CloudTasks_GetQueue_async - */ + /** + * Gets a queue. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The resource name of the queue. For example: + * `projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.tasks.v2.Queue|Queue}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/cloud_tasks.get_queue.js + * region_tag:cloudtasks_v2_generated_CloudTasks_GetQueue_async + */ getQueue( - request?: protos.google.cloud.tasks.v2.IGetQueueRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.tasks.v2.IQueue, - protos.google.cloud.tasks.v2.IGetQueueRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.tasks.v2.IGetQueueRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.tasks.v2.IQueue, + protos.google.cloud.tasks.v2.IGetQueueRequest | undefined, + {} | undefined, + ] + >; getQueue( - request: protos.google.cloud.tasks.v2.IGetQueueRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.tasks.v2.IQueue, - protos.google.cloud.tasks.v2.IGetQueueRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.tasks.v2.IGetQueueRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.tasks.v2.IQueue, + protos.google.cloud.tasks.v2.IGetQueueRequest | null | undefined, + {} | null | undefined + >, + ): void; getQueue( - request: protos.google.cloud.tasks.v2.IGetQueueRequest, - callback: Callback< - protos.google.cloud.tasks.v2.IQueue, - protos.google.cloud.tasks.v2.IGetQueueRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.tasks.v2.IGetQueueRequest, + callback: Callback< + protos.google.cloud.tasks.v2.IQueue, + protos.google.cloud.tasks.v2.IGetQueueRequest | null | undefined, + {} | null | undefined + >, + ): void; getQueue( - request?: protos.google.cloud.tasks.v2.IGetQueueRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.cloud.tasks.v2.IGetQueueRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.tasks.v2.IQueue, - protos.google.cloud.tasks.v2.IGetQueueRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.cloud.tasks.v2.IQueue, - protos.google.cloud.tasks.v2.IGetQueueRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.tasks.v2.IQueue, - protos.google.cloud.tasks.v2.IGetQueueRequest|undefined, {}|undefined - ]>|void { + protos.google.cloud.tasks.v2.IGetQueueRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.tasks.v2.IQueue, + protos.google.cloud.tasks.v2.IGetQueueRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.tasks.v2.IQueue, + protos.google.cloud.tasks.v2.IGetQueueRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getQueue request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.tasks.v2.IQueue, - protos.google.cloud.tasks.v2.IGetQueueRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.tasks.v2.IQueue, + protos.google.cloud.tasks.v2.IGetQueueRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getQueue response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.getQueue(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.tasks.v2.IQueue, - protos.google.cloud.tasks.v2.IGetQueueRequest|undefined, {}|undefined - ]) => { - this._log.info('getQueue response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getQueue(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.tasks.v2.IQueue, + protos.google.cloud.tasks.v2.IGetQueueRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getQueue response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Creates a queue. - * - * Queues created with this method allow tasks to live for a maximum of 31 - * days. After a task is 31 days old, the task will be deleted regardless of whether - * it was dispatched or not. - * - * WARNING: Using this method may have unintended side effects if you are - * using an App Engine `queue.yaml` or `queue.xml` file to manage your queues. - * Read - * [Overview of Queue Management and - * queue.yaml](https://cloud.google.com/tasks/docs/queue-yaml) before using - * this method. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The location name in which the queue will be created. - * For example: `projects/PROJECT_ID/locations/LOCATION_ID` - * - * The list of allowed locations can be obtained by calling Cloud - * Tasks' implementation of - * {@link protos.google.cloud.location.Locations.ListLocations|ListLocations}. - * @param {google.cloud.tasks.v2.Queue} request.queue - * Required. The queue to create. - * - * {@link protos.google.cloud.tasks.v2.Queue.name|Queue's name} cannot be the same as an existing queue. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.tasks.v2.Queue|Queue}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/cloud_tasks.create_queue.js - * region_tag:cloudtasks_v2_generated_CloudTasks_CreateQueue_async - */ + /** + * Creates a queue. + * + * Queues created with this method allow tasks to live for a maximum of 31 + * days. After a task is 31 days old, the task will be deleted regardless of whether + * it was dispatched or not. + * + * WARNING: Using this method may have unintended side effects if you are + * using an App Engine `queue.yaml` or `queue.xml` file to manage your queues. + * Read + * [Overview of Queue Management and + * queue.yaml](https://cloud.google.com/tasks/docs/queue-yaml) before using + * this method. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The location name in which the queue will be created. + * For example: `projects/PROJECT_ID/locations/LOCATION_ID` + * + * The list of allowed locations can be obtained by calling Cloud + * Tasks' implementation of + * {@link protos.google.cloud.location.Locations.ListLocations|ListLocations}. + * @param {google.cloud.tasks.v2.Queue} request.queue + * Required. The queue to create. + * + * {@link protos.google.cloud.tasks.v2.Queue.name|Queue's name} cannot be the same as an existing queue. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.tasks.v2.Queue|Queue}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/cloud_tasks.create_queue.js + * region_tag:cloudtasks_v2_generated_CloudTasks_CreateQueue_async + */ createQueue( - request?: protos.google.cloud.tasks.v2.ICreateQueueRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.tasks.v2.IQueue, - protos.google.cloud.tasks.v2.ICreateQueueRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.tasks.v2.ICreateQueueRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.tasks.v2.IQueue, + protos.google.cloud.tasks.v2.ICreateQueueRequest | undefined, + {} | undefined, + ] + >; createQueue( - request: protos.google.cloud.tasks.v2.ICreateQueueRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.tasks.v2.IQueue, - protos.google.cloud.tasks.v2.ICreateQueueRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.tasks.v2.ICreateQueueRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.tasks.v2.IQueue, + protos.google.cloud.tasks.v2.ICreateQueueRequest | null | undefined, + {} | null | undefined + >, + ): void; createQueue( - request: protos.google.cloud.tasks.v2.ICreateQueueRequest, - callback: Callback< - protos.google.cloud.tasks.v2.IQueue, - protos.google.cloud.tasks.v2.ICreateQueueRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.tasks.v2.ICreateQueueRequest, + callback: Callback< + protos.google.cloud.tasks.v2.IQueue, + protos.google.cloud.tasks.v2.ICreateQueueRequest | null | undefined, + {} | null | undefined + >, + ): void; createQueue( - request?: protos.google.cloud.tasks.v2.ICreateQueueRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.tasks.v2.IQueue, - protos.google.cloud.tasks.v2.ICreateQueueRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.tasks.v2.ICreateQueueRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.tasks.v2.IQueue, - protos.google.cloud.tasks.v2.ICreateQueueRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.tasks.v2.IQueue, - protos.google.cloud.tasks.v2.ICreateQueueRequest|undefined, {}|undefined - ]>|void { + protos.google.cloud.tasks.v2.ICreateQueueRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.tasks.v2.IQueue, + protos.google.cloud.tasks.v2.ICreateQueueRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.tasks.v2.IQueue, + protos.google.cloud.tasks.v2.ICreateQueueRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('createQueue request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.tasks.v2.IQueue, - protos.google.cloud.tasks.v2.ICreateQueueRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.tasks.v2.IQueue, + protos.google.cloud.tasks.v2.ICreateQueueRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createQueue response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.createQueue(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.tasks.v2.IQueue, - protos.google.cloud.tasks.v2.ICreateQueueRequest|undefined, {}|undefined - ]) => { - this._log.info('createQueue response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createQueue(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.tasks.v2.IQueue, + protos.google.cloud.tasks.v2.ICreateQueueRequest | undefined, + {} | undefined, + ]) => { + this._log.info('createQueue response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Updates a queue. - * - * This method creates the queue if it does not exist and updates - * the queue if it does exist. - * - * Queues created with this method allow tasks to live for a maximum of 31 - * days. After a task is 31 days old, the task will be deleted regardless of whether - * it was dispatched or not. - * - * WARNING: Using this method may have unintended side effects if you are - * using an App Engine `queue.yaml` or `queue.xml` file to manage your queues. - * Read - * [Overview of Queue Management and - * queue.yaml](https://cloud.google.com/tasks/docs/queue-yaml) before using - * this method. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.cloud.tasks.v2.Queue} request.queue - * Required. The queue to create or update. - * - * The queue's {@link protos.google.cloud.tasks.v2.Queue.name|name} must be specified. - * - * Output only fields cannot be modified using UpdateQueue. - * Any value specified for an output only field will be ignored. - * The queue's {@link protos.google.cloud.tasks.v2.Queue.name|name} cannot be changed. - * @param {google.protobuf.FieldMask} request.updateMask - * A mask used to specify which fields of the queue are being updated. - * - * If empty, then all fields will be updated. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.tasks.v2.Queue|Queue}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/cloud_tasks.update_queue.js - * region_tag:cloudtasks_v2_generated_CloudTasks_UpdateQueue_async - */ + /** + * Updates a queue. + * + * This method creates the queue if it does not exist and updates + * the queue if it does exist. + * + * Queues created with this method allow tasks to live for a maximum of 31 + * days. After a task is 31 days old, the task will be deleted regardless of whether + * it was dispatched or not. + * + * WARNING: Using this method may have unintended side effects if you are + * using an App Engine `queue.yaml` or `queue.xml` file to manage your queues. + * Read + * [Overview of Queue Management and + * queue.yaml](https://cloud.google.com/tasks/docs/queue-yaml) before using + * this method. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.cloud.tasks.v2.Queue} request.queue + * Required. The queue to create or update. + * + * The queue's {@link protos.google.cloud.tasks.v2.Queue.name|name} must be specified. + * + * Output only fields cannot be modified using UpdateQueue. + * Any value specified for an output only field will be ignored. + * The queue's {@link protos.google.cloud.tasks.v2.Queue.name|name} cannot be changed. + * @param {google.protobuf.FieldMask} request.updateMask + * A mask used to specify which fields of the queue are being updated. + * + * If empty, then all fields will be updated. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.tasks.v2.Queue|Queue}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/cloud_tasks.update_queue.js + * region_tag:cloudtasks_v2_generated_CloudTasks_UpdateQueue_async + */ updateQueue( - request?: protos.google.cloud.tasks.v2.IUpdateQueueRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.tasks.v2.IQueue, - protos.google.cloud.tasks.v2.IUpdateQueueRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.tasks.v2.IUpdateQueueRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.tasks.v2.IQueue, + protos.google.cloud.tasks.v2.IUpdateQueueRequest | undefined, + {} | undefined, + ] + >; updateQueue( - request: protos.google.cloud.tasks.v2.IUpdateQueueRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.tasks.v2.IQueue, - protos.google.cloud.tasks.v2.IUpdateQueueRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.tasks.v2.IUpdateQueueRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.tasks.v2.IQueue, + protos.google.cloud.tasks.v2.IUpdateQueueRequest | null | undefined, + {} | null | undefined + >, + ): void; updateQueue( - request: protos.google.cloud.tasks.v2.IUpdateQueueRequest, - callback: Callback< - protos.google.cloud.tasks.v2.IQueue, - protos.google.cloud.tasks.v2.IUpdateQueueRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.tasks.v2.IUpdateQueueRequest, + callback: Callback< + protos.google.cloud.tasks.v2.IQueue, + protos.google.cloud.tasks.v2.IUpdateQueueRequest | null | undefined, + {} | null | undefined + >, + ): void; updateQueue( - request?: protos.google.cloud.tasks.v2.IUpdateQueueRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.cloud.tasks.v2.IUpdateQueueRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.tasks.v2.IQueue, - protos.google.cloud.tasks.v2.IUpdateQueueRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.cloud.tasks.v2.IQueue, - protos.google.cloud.tasks.v2.IUpdateQueueRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.tasks.v2.IQueue, - protos.google.cloud.tasks.v2.IUpdateQueueRequest|undefined, {}|undefined - ]>|void { + protos.google.cloud.tasks.v2.IUpdateQueueRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.tasks.v2.IQueue, + protos.google.cloud.tasks.v2.IUpdateQueueRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.tasks.v2.IQueue, + protos.google.cloud.tasks.v2.IUpdateQueueRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'queue.name': request.queue!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'queue.name': request.queue!.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateQueue request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.tasks.v2.IQueue, - protos.google.cloud.tasks.v2.IUpdateQueueRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.tasks.v2.IQueue, + protos.google.cloud.tasks.v2.IUpdateQueueRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateQueue response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.updateQueue(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.tasks.v2.IQueue, - protos.google.cloud.tasks.v2.IUpdateQueueRequest|undefined, {}|undefined - ]) => { - this._log.info('updateQueue response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateQueue(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.tasks.v2.IQueue, + protos.google.cloud.tasks.v2.IUpdateQueueRequest | undefined, + {} | undefined, + ]) => { + this._log.info('updateQueue response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Deletes a queue. - * - * This command will delete the queue even if it has tasks in it. - * - * Note: If you delete a queue, a queue with the same name can't be created - * for 7 days. - * - * WARNING: Using this method may have unintended side effects if you are - * using an App Engine `queue.yaml` or `queue.xml` file to manage your queues. - * Read - * [Overview of Queue Management and - * queue.yaml](https://cloud.google.com/tasks/docs/queue-yaml) before using - * this method. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The queue name. For example: - * `projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID` - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/cloud_tasks.delete_queue.js - * region_tag:cloudtasks_v2_generated_CloudTasks_DeleteQueue_async - */ + /** + * Deletes a queue. + * + * This command will delete the queue even if it has tasks in it. + * + * Note: If you delete a queue, a queue with the same name can't be created + * for 7 days. + * + * WARNING: Using this method may have unintended side effects if you are + * using an App Engine `queue.yaml` or `queue.xml` file to manage your queues. + * Read + * [Overview of Queue Management and + * queue.yaml](https://cloud.google.com/tasks/docs/queue-yaml) before using + * this method. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The queue name. For example: + * `projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/cloud_tasks.delete_queue.js + * region_tag:cloudtasks_v2_generated_CloudTasks_DeleteQueue_async + */ deleteQueue( - request?: protos.google.cloud.tasks.v2.IDeleteQueueRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.cloud.tasks.v2.IDeleteQueueRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.tasks.v2.IDeleteQueueRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.cloud.tasks.v2.IDeleteQueueRequest | undefined, + {} | undefined, + ] + >; deleteQueue( - request: protos.google.cloud.tasks.v2.IDeleteQueueRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.cloud.tasks.v2.IDeleteQueueRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.tasks.v2.IDeleteQueueRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.cloud.tasks.v2.IDeleteQueueRequest | null | undefined, + {} | null | undefined + >, + ): void; deleteQueue( - request: protos.google.cloud.tasks.v2.IDeleteQueueRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.cloud.tasks.v2.IDeleteQueueRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.tasks.v2.IDeleteQueueRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.cloud.tasks.v2.IDeleteQueueRequest | null | undefined, + {} | null | undefined + >, + ): void; deleteQueue( - request?: protos.google.cloud.tasks.v2.IDeleteQueueRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.protobuf.IEmpty, - protos.google.cloud.tasks.v2.IDeleteQueueRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.tasks.v2.IDeleteQueueRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.cloud.tasks.v2.IDeleteQueueRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.cloud.tasks.v2.IDeleteQueueRequest|undefined, {}|undefined - ]>|void { + protos.google.cloud.tasks.v2.IDeleteQueueRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + protos.google.cloud.tasks.v2.IDeleteQueueRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.cloud.tasks.v2.IDeleteQueueRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('deleteQueue request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.cloud.tasks.v2.IDeleteQueueRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + protos.google.cloud.tasks.v2.IDeleteQueueRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteQueue response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.deleteQueue(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.cloud.tasks.v2.IDeleteQueueRequest|undefined, {}|undefined - ]) => { - this._log.info('deleteQueue response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteQueue(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.cloud.tasks.v2.IDeleteQueueRequest | undefined, + {} | undefined, + ]) => { + this._log.info('deleteQueue response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Purges a queue by deleting all of its tasks. - * - * All tasks created before this method is called are permanently deleted. - * - * Purge operations can take up to one minute to take effect. Tasks - * might be dispatched before the purge takes effect. A purge is irreversible. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The queue name. For example: - * `projects/PROJECT_ID/location/LOCATION_ID/queues/QUEUE_ID` - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.tasks.v2.Queue|Queue}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/cloud_tasks.purge_queue.js - * region_tag:cloudtasks_v2_generated_CloudTasks_PurgeQueue_async - */ + /** + * Purges a queue by deleting all of its tasks. + * + * All tasks created before this method is called are permanently deleted. + * + * Purge operations can take up to one minute to take effect. Tasks + * might be dispatched before the purge takes effect. A purge is irreversible. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The queue name. For example: + * `projects/PROJECT_ID/location/LOCATION_ID/queues/QUEUE_ID` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.tasks.v2.Queue|Queue}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/cloud_tasks.purge_queue.js + * region_tag:cloudtasks_v2_generated_CloudTasks_PurgeQueue_async + */ purgeQueue( - request?: protos.google.cloud.tasks.v2.IPurgeQueueRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.tasks.v2.IQueue, - protos.google.cloud.tasks.v2.IPurgeQueueRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.tasks.v2.IPurgeQueueRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.tasks.v2.IQueue, + protos.google.cloud.tasks.v2.IPurgeQueueRequest | undefined, + {} | undefined, + ] + >; purgeQueue( - request: protos.google.cloud.tasks.v2.IPurgeQueueRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.tasks.v2.IQueue, - protos.google.cloud.tasks.v2.IPurgeQueueRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.tasks.v2.IPurgeQueueRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.tasks.v2.IQueue, + protos.google.cloud.tasks.v2.IPurgeQueueRequest | null | undefined, + {} | null | undefined + >, + ): void; purgeQueue( - request: protos.google.cloud.tasks.v2.IPurgeQueueRequest, - callback: Callback< - protos.google.cloud.tasks.v2.IQueue, - protos.google.cloud.tasks.v2.IPurgeQueueRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.tasks.v2.IPurgeQueueRequest, + callback: Callback< + protos.google.cloud.tasks.v2.IQueue, + protos.google.cloud.tasks.v2.IPurgeQueueRequest | null | undefined, + {} | null | undefined + >, + ): void; purgeQueue( - request?: protos.google.cloud.tasks.v2.IPurgeQueueRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.tasks.v2.IQueue, - protos.google.cloud.tasks.v2.IPurgeQueueRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.tasks.v2.IPurgeQueueRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.tasks.v2.IQueue, - protos.google.cloud.tasks.v2.IPurgeQueueRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.tasks.v2.IQueue, - protos.google.cloud.tasks.v2.IPurgeQueueRequest|undefined, {}|undefined - ]>|void { + protos.google.cloud.tasks.v2.IPurgeQueueRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.tasks.v2.IQueue, + protos.google.cloud.tasks.v2.IPurgeQueueRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.tasks.v2.IQueue, + protos.google.cloud.tasks.v2.IPurgeQueueRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('purgeQueue request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.tasks.v2.IQueue, - protos.google.cloud.tasks.v2.IPurgeQueueRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.tasks.v2.IQueue, + protos.google.cloud.tasks.v2.IPurgeQueueRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('purgeQueue response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.purgeQueue(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.tasks.v2.IQueue, - protos.google.cloud.tasks.v2.IPurgeQueueRequest|undefined, {}|undefined - ]) => { - this._log.info('purgeQueue response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .purgeQueue(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.tasks.v2.IQueue, + protos.google.cloud.tasks.v2.IPurgeQueueRequest | undefined, + {} | undefined, + ]) => { + this._log.info('purgeQueue response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Pauses the queue. - * - * If a queue is paused then the system will stop dispatching tasks - * until the queue is resumed via - * {@link protos.google.cloud.tasks.v2.CloudTasks.ResumeQueue|ResumeQueue}. Tasks can still be added - * when the queue is paused. A queue is paused if its - * {@link protos.google.cloud.tasks.v2.Queue.state|state} is {@link protos.google.cloud.tasks.v2.Queue.State.PAUSED|PAUSED}. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The queue name. For example: - * `projects/PROJECT_ID/location/LOCATION_ID/queues/QUEUE_ID` - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.tasks.v2.Queue|Queue}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/cloud_tasks.pause_queue.js - * region_tag:cloudtasks_v2_generated_CloudTasks_PauseQueue_async - */ + /** + * Pauses the queue. + * + * If a queue is paused then the system will stop dispatching tasks + * until the queue is resumed via + * {@link protos.google.cloud.tasks.v2.CloudTasks.ResumeQueue|ResumeQueue}. Tasks can still be added + * when the queue is paused. A queue is paused if its + * {@link protos.google.cloud.tasks.v2.Queue.state|state} is {@link protos.google.cloud.tasks.v2.Queue.State.PAUSED|PAUSED}. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The queue name. For example: + * `projects/PROJECT_ID/location/LOCATION_ID/queues/QUEUE_ID` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.tasks.v2.Queue|Queue}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/cloud_tasks.pause_queue.js + * region_tag:cloudtasks_v2_generated_CloudTasks_PauseQueue_async + */ pauseQueue( - request?: protos.google.cloud.tasks.v2.IPauseQueueRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.tasks.v2.IQueue, - protos.google.cloud.tasks.v2.IPauseQueueRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.tasks.v2.IPauseQueueRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.tasks.v2.IQueue, + protos.google.cloud.tasks.v2.IPauseQueueRequest | undefined, + {} | undefined, + ] + >; pauseQueue( - request: protos.google.cloud.tasks.v2.IPauseQueueRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.tasks.v2.IQueue, - protos.google.cloud.tasks.v2.IPauseQueueRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.tasks.v2.IPauseQueueRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.tasks.v2.IQueue, + protos.google.cloud.tasks.v2.IPauseQueueRequest | null | undefined, + {} | null | undefined + >, + ): void; pauseQueue( - request: protos.google.cloud.tasks.v2.IPauseQueueRequest, - callback: Callback< - protos.google.cloud.tasks.v2.IQueue, - protos.google.cloud.tasks.v2.IPauseQueueRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.tasks.v2.IPauseQueueRequest, + callback: Callback< + protos.google.cloud.tasks.v2.IQueue, + protos.google.cloud.tasks.v2.IPauseQueueRequest | null | undefined, + {} | null | undefined + >, + ): void; pauseQueue( - request?: protos.google.cloud.tasks.v2.IPauseQueueRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.cloud.tasks.v2.IPauseQueueRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.tasks.v2.IQueue, - protos.google.cloud.tasks.v2.IPauseQueueRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.cloud.tasks.v2.IQueue, - protos.google.cloud.tasks.v2.IPauseQueueRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.tasks.v2.IQueue, - protos.google.cloud.tasks.v2.IPauseQueueRequest|undefined, {}|undefined - ]>|void { + protos.google.cloud.tasks.v2.IPauseQueueRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.tasks.v2.IQueue, + protos.google.cloud.tasks.v2.IPauseQueueRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.tasks.v2.IQueue, + protos.google.cloud.tasks.v2.IPauseQueueRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('pauseQueue request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.tasks.v2.IQueue, - protos.google.cloud.tasks.v2.IPauseQueueRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.tasks.v2.IQueue, + protos.google.cloud.tasks.v2.IPauseQueueRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('pauseQueue response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.pauseQueue(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.tasks.v2.IQueue, - protos.google.cloud.tasks.v2.IPauseQueueRequest|undefined, {}|undefined - ]) => { - this._log.info('pauseQueue response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .pauseQueue(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.tasks.v2.IQueue, + protos.google.cloud.tasks.v2.IPauseQueueRequest | undefined, + {} | undefined, + ]) => { + this._log.info('pauseQueue response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Resume a queue. - * - * This method resumes a queue after it has been - * {@link protos.google.cloud.tasks.v2.Queue.State.PAUSED|PAUSED} or - * {@link protos.google.cloud.tasks.v2.Queue.State.DISABLED|DISABLED}. The state of a queue is stored - * in the queue's {@link protos.google.cloud.tasks.v2.Queue.state|state}; after calling this method it - * will be set to {@link protos.google.cloud.tasks.v2.Queue.State.RUNNING|RUNNING}. - * - * WARNING: Resuming many high-QPS queues at the same time can - * lead to target overloading. If you are resuming high-QPS - * queues, follow the 500/50/5 pattern described in - * [Managing Cloud Tasks Scaling - * Risks](https://cloud.google.com/tasks/docs/manage-cloud-task-scaling). - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The queue name. For example: - * `projects/PROJECT_ID/location/LOCATION_ID/queues/QUEUE_ID` - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.tasks.v2.Queue|Queue}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/cloud_tasks.resume_queue.js - * region_tag:cloudtasks_v2_generated_CloudTasks_ResumeQueue_async - */ + /** + * Resume a queue. + * + * This method resumes a queue after it has been + * {@link protos.google.cloud.tasks.v2.Queue.State.PAUSED|PAUSED} or + * {@link protos.google.cloud.tasks.v2.Queue.State.DISABLED|DISABLED}. The state of a queue is stored + * in the queue's {@link protos.google.cloud.tasks.v2.Queue.state|state}; after calling this method it + * will be set to {@link protos.google.cloud.tasks.v2.Queue.State.RUNNING|RUNNING}. + * + * WARNING: Resuming many high-QPS queues at the same time can + * lead to target overloading. If you are resuming high-QPS + * queues, follow the 500/50/5 pattern described in + * [Managing Cloud Tasks Scaling + * Risks](https://cloud.google.com/tasks/docs/manage-cloud-task-scaling). + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The queue name. For example: + * `projects/PROJECT_ID/location/LOCATION_ID/queues/QUEUE_ID` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.tasks.v2.Queue|Queue}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/cloud_tasks.resume_queue.js + * region_tag:cloudtasks_v2_generated_CloudTasks_ResumeQueue_async + */ resumeQueue( - request?: protos.google.cloud.tasks.v2.IResumeQueueRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.tasks.v2.IQueue, - protos.google.cloud.tasks.v2.IResumeQueueRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.tasks.v2.IResumeQueueRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.tasks.v2.IQueue, + protos.google.cloud.tasks.v2.IResumeQueueRequest | undefined, + {} | undefined, + ] + >; resumeQueue( - request: protos.google.cloud.tasks.v2.IResumeQueueRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.tasks.v2.IQueue, - protos.google.cloud.tasks.v2.IResumeQueueRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.tasks.v2.IResumeQueueRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.tasks.v2.IQueue, + protos.google.cloud.tasks.v2.IResumeQueueRequest | null | undefined, + {} | null | undefined + >, + ): void; resumeQueue( - request: protos.google.cloud.tasks.v2.IResumeQueueRequest, - callback: Callback< - protos.google.cloud.tasks.v2.IQueue, - protos.google.cloud.tasks.v2.IResumeQueueRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.tasks.v2.IResumeQueueRequest, + callback: Callback< + protos.google.cloud.tasks.v2.IQueue, + protos.google.cloud.tasks.v2.IResumeQueueRequest | null | undefined, + {} | null | undefined + >, + ): void; resumeQueue( - request?: protos.google.cloud.tasks.v2.IResumeQueueRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.cloud.tasks.v2.IResumeQueueRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.tasks.v2.IQueue, - protos.google.cloud.tasks.v2.IResumeQueueRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.cloud.tasks.v2.IQueue, - protos.google.cloud.tasks.v2.IResumeQueueRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.tasks.v2.IQueue, - protos.google.cloud.tasks.v2.IResumeQueueRequest|undefined, {}|undefined - ]>|void { + protos.google.cloud.tasks.v2.IResumeQueueRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.tasks.v2.IQueue, + protos.google.cloud.tasks.v2.IResumeQueueRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.tasks.v2.IQueue, + protos.google.cloud.tasks.v2.IResumeQueueRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('resumeQueue request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.tasks.v2.IQueue, - protos.google.cloud.tasks.v2.IResumeQueueRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.tasks.v2.IQueue, + protos.google.cloud.tasks.v2.IResumeQueueRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('resumeQueue response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.resumeQueue(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.tasks.v2.IQueue, - protos.google.cloud.tasks.v2.IResumeQueueRequest|undefined, {}|undefined - ]) => { - this._log.info('resumeQueue response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .resumeQueue(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.tasks.v2.IQueue, + protos.google.cloud.tasks.v2.IResumeQueueRequest | undefined, + {} | undefined, + ]) => { + this._log.info('resumeQueue response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Gets the access control policy for a {@link protos.google.cloud.tasks.v2.Queue|Queue}. - * Returns an empty policy if the resource exists and does not have a policy - * set. - * - * Authorization requires the following - * [Google IAM](https://cloud.google.com/iam) permission on the specified - * resource parent: - * - * * `cloudtasks.queues.getIamPolicy` - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.resource - * REQUIRED: The resource for which the policy is being requested. - * See the operation documentation for the appropriate value for this field. - * @param {google.iam.v1.GetPolicyOptions} request.options - * OPTIONAL: A `GetPolicyOptions` object for specifying options to - * `GetIamPolicy`. This field is only used by Cloud IAM. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.iam.v1.Policy|Policy}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/cloud_tasks.get_iam_policy.js - * region_tag:cloudtasks_v2_generated_CloudTasks_GetIamPolicy_async - */ + /** + * Gets the access control policy for a {@link protos.google.cloud.tasks.v2.Queue|Queue}. + * Returns an empty policy if the resource exists and does not have a policy + * set. + * + * Authorization requires the following + * [Google IAM](https://cloud.google.com/iam) permission on the specified + * resource parent: + * + * * `cloudtasks.queues.getIamPolicy` + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.resource + * REQUIRED: The resource for which the policy is being requested. + * See the operation documentation for the appropriate value for this field. + * @param {google.iam.v1.GetPolicyOptions} request.options + * OPTIONAL: A `GetPolicyOptions` object for specifying options to + * `GetIamPolicy`. This field is only used by Cloud IAM. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.iam.v1.Policy|Policy}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/cloud_tasks.get_iam_policy.js + * region_tag:cloudtasks_v2_generated_CloudTasks_GetIamPolicy_async + */ getIamPolicy( - request?: protos.google.iam.v1.IGetIamPolicyRequest, - options?: CallOptions): - Promise<[ - protos.google.iam.v1.IPolicy, - protos.google.iam.v1.IGetIamPolicyRequest|undefined, {}|undefined - ]>; + request?: protos.google.iam.v1.IGetIamPolicyRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.iam.v1.IPolicy, + protos.google.iam.v1.IGetIamPolicyRequest | undefined, + {} | undefined, + ] + >; getIamPolicy( - request: protos.google.iam.v1.IGetIamPolicyRequest, - options: CallOptions, - callback: Callback< - protos.google.iam.v1.IPolicy, - protos.google.iam.v1.IGetIamPolicyRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.iam.v1.IGetIamPolicyRequest, + options: CallOptions, + callback: Callback< + protos.google.iam.v1.IPolicy, + protos.google.iam.v1.IGetIamPolicyRequest | null | undefined, + {} | null | undefined + >, + ): void; getIamPolicy( - request: protos.google.iam.v1.IGetIamPolicyRequest, - callback: Callback< - protos.google.iam.v1.IPolicy, - protos.google.iam.v1.IGetIamPolicyRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.iam.v1.IGetIamPolicyRequest, + callback: Callback< + protos.google.iam.v1.IPolicy, + protos.google.iam.v1.IGetIamPolicyRequest | null | undefined, + {} | null | undefined + >, + ): void; getIamPolicy( - request?: protos.google.iam.v1.IGetIamPolicyRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.iam.v1.IGetIamPolicyRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.iam.v1.IPolicy, - protos.google.iam.v1.IGetIamPolicyRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.iam.v1.IPolicy, - protos.google.iam.v1.IGetIamPolicyRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.iam.v1.IPolicy, - protos.google.iam.v1.IGetIamPolicyRequest|undefined, {}|undefined - ]>|void { + protos.google.iam.v1.IGetIamPolicyRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.iam.v1.IPolicy, + protos.google.iam.v1.IGetIamPolicyRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.iam.v1.IPolicy, + protos.google.iam.v1.IGetIamPolicyRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'resource': request.resource ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + resource: request.resource ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getIamPolicy request %j', request); - const wrappedCallback: Callback< - protos.google.iam.v1.IPolicy, - protos.google.iam.v1.IGetIamPolicyRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.iam.v1.IPolicy, + protos.google.iam.v1.IGetIamPolicyRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getIamPolicy response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.getIamPolicy(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.iam.v1.IPolicy, - protos.google.iam.v1.IGetIamPolicyRequest|undefined, {}|undefined - ]) => { - this._log.info('getIamPolicy response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getIamPolicy(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.iam.v1.IPolicy, + protos.google.iam.v1.IGetIamPolicyRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getIamPolicy response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Sets the access control policy for a {@link protos.google.cloud.tasks.v2.Queue|Queue}. Replaces any existing - * policy. - * - * Note: The Cloud Console does not check queue-level IAM permissions yet. - * Project-level permissions are required to use the Cloud Console. - * - * Authorization requires the following - * [Google IAM](https://cloud.google.com/iam) permission on the specified - * resource parent: - * - * * `cloudtasks.queues.setIamPolicy` - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.resource - * REQUIRED: The resource for which the policy is being specified. - * See the operation documentation for the appropriate value for this field. - * @param {google.iam.v1.Policy} request.policy - * REQUIRED: The complete policy to be applied to the `resource`. The size of - * the policy is limited to a few 10s of KB. An empty policy is a - * valid policy but certain Cloud Platform services (such as Projects) - * might reject them. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.iam.v1.Policy|Policy}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/cloud_tasks.set_iam_policy.js - * region_tag:cloudtasks_v2_generated_CloudTasks_SetIamPolicy_async - */ + /** + * Sets the access control policy for a {@link protos.google.cloud.tasks.v2.Queue|Queue}. Replaces any existing + * policy. + * + * Note: The Cloud Console does not check queue-level IAM permissions yet. + * Project-level permissions are required to use the Cloud Console. + * + * Authorization requires the following + * [Google IAM](https://cloud.google.com/iam) permission on the specified + * resource parent: + * + * * `cloudtasks.queues.setIamPolicy` + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.resource + * REQUIRED: The resource for which the policy is being specified. + * See the operation documentation for the appropriate value for this field. + * @param {google.iam.v1.Policy} request.policy + * REQUIRED: The complete policy to be applied to the `resource`. The size of + * the policy is limited to a few 10s of KB. An empty policy is a + * valid policy but certain Cloud Platform services (such as Projects) + * might reject them. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.iam.v1.Policy|Policy}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/cloud_tasks.set_iam_policy.js + * region_tag:cloudtasks_v2_generated_CloudTasks_SetIamPolicy_async + */ setIamPolicy( - request?: protos.google.iam.v1.ISetIamPolicyRequest, - options?: CallOptions): - Promise<[ - protos.google.iam.v1.IPolicy, - protos.google.iam.v1.ISetIamPolicyRequest|undefined, {}|undefined - ]>; + request?: protos.google.iam.v1.ISetIamPolicyRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.iam.v1.IPolicy, + protos.google.iam.v1.ISetIamPolicyRequest | undefined, + {} | undefined, + ] + >; setIamPolicy( - request: protos.google.iam.v1.ISetIamPolicyRequest, - options: CallOptions, - callback: Callback< - protos.google.iam.v1.IPolicy, - protos.google.iam.v1.ISetIamPolicyRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.iam.v1.ISetIamPolicyRequest, + options: CallOptions, + callback: Callback< + protos.google.iam.v1.IPolicy, + protos.google.iam.v1.ISetIamPolicyRequest | null | undefined, + {} | null | undefined + >, + ): void; setIamPolicy( - request: protos.google.iam.v1.ISetIamPolicyRequest, - callback: Callback< - protos.google.iam.v1.IPolicy, - protos.google.iam.v1.ISetIamPolicyRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.iam.v1.ISetIamPolicyRequest, + callback: Callback< + protos.google.iam.v1.IPolicy, + protos.google.iam.v1.ISetIamPolicyRequest | null | undefined, + {} | null | undefined + >, + ): void; setIamPolicy( - request?: protos.google.iam.v1.ISetIamPolicyRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.iam.v1.IPolicy, - protos.google.iam.v1.ISetIamPolicyRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.iam.v1.ISetIamPolicyRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.iam.v1.IPolicy, - protos.google.iam.v1.ISetIamPolicyRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.iam.v1.IPolicy, - protos.google.iam.v1.ISetIamPolicyRequest|undefined, {}|undefined - ]>|void { + protos.google.iam.v1.ISetIamPolicyRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.iam.v1.IPolicy, + protos.google.iam.v1.ISetIamPolicyRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.iam.v1.IPolicy, + protos.google.iam.v1.ISetIamPolicyRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'resource': request.resource ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + resource: request.resource ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('setIamPolicy request %j', request); - const wrappedCallback: Callback< - protos.google.iam.v1.IPolicy, - protos.google.iam.v1.ISetIamPolicyRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.iam.v1.IPolicy, + protos.google.iam.v1.ISetIamPolicyRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('setIamPolicy response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.setIamPolicy(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.iam.v1.IPolicy, - protos.google.iam.v1.ISetIamPolicyRequest|undefined, {}|undefined - ]) => { - this._log.info('setIamPolicy response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .setIamPolicy(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.iam.v1.IPolicy, + protos.google.iam.v1.ISetIamPolicyRequest | undefined, + {} | undefined, + ]) => { + this._log.info('setIamPolicy response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Returns permissions that a caller has on a {@link protos.google.cloud.tasks.v2.Queue|Queue}. - * If the resource does not exist, this will return an empty set of - * permissions, not a {@link protos.google.rpc.Code.NOT_FOUND|NOT_FOUND} error. - * - * Note: This operation is designed to be used for building permission-aware - * UIs and command-line tools, not for authorization checking. This operation - * may "fail open" without warning. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.resource - * REQUIRED: The resource for which the policy detail is being requested. - * See the operation documentation for the appropriate value for this field. - * @param {string[]} request.permissions - * The set of permissions to check for the `resource`. Permissions with - * wildcards (such as '*' or 'storage.*') are not allowed. For more - * information see - * [IAM Overview](https://cloud.google.com/iam/docs/overview#permissions). - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.iam.v1.TestIamPermissionsResponse|TestIamPermissionsResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/cloud_tasks.test_iam_permissions.js - * region_tag:cloudtasks_v2_generated_CloudTasks_TestIamPermissions_async - */ + /** + * Returns permissions that a caller has on a {@link protos.google.cloud.tasks.v2.Queue|Queue}. + * If the resource does not exist, this will return an empty set of + * permissions, not a {@link protos.google.rpc.Code.NOT_FOUND|NOT_FOUND} error. + * + * Note: This operation is designed to be used for building permission-aware + * UIs and command-line tools, not for authorization checking. This operation + * may "fail open" without warning. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.resource + * REQUIRED: The resource for which the policy detail is being requested. + * See the operation documentation for the appropriate value for this field. + * @param {string[]} request.permissions + * The set of permissions to check for the `resource`. Permissions with + * wildcards (such as '*' or 'storage.*') are not allowed. For more + * information see + * [IAM Overview](https://cloud.google.com/iam/docs/overview#permissions). + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.iam.v1.TestIamPermissionsResponse|TestIamPermissionsResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/cloud_tasks.test_iam_permissions.js + * region_tag:cloudtasks_v2_generated_CloudTasks_TestIamPermissions_async + */ testIamPermissions( - request?: protos.google.iam.v1.ITestIamPermissionsRequest, - options?: CallOptions): - Promise<[ - protos.google.iam.v1.ITestIamPermissionsResponse, - protos.google.iam.v1.ITestIamPermissionsRequest|undefined, {}|undefined - ]>; + request?: protos.google.iam.v1.ITestIamPermissionsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.iam.v1.ITestIamPermissionsResponse, + protos.google.iam.v1.ITestIamPermissionsRequest | undefined, + {} | undefined, + ] + >; testIamPermissions( - request: protos.google.iam.v1.ITestIamPermissionsRequest, - options: CallOptions, - callback: Callback< - protos.google.iam.v1.ITestIamPermissionsResponse, - protos.google.iam.v1.ITestIamPermissionsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.iam.v1.ITestIamPermissionsRequest, + options: CallOptions, + callback: Callback< + protos.google.iam.v1.ITestIamPermissionsResponse, + protos.google.iam.v1.ITestIamPermissionsRequest | null | undefined, + {} | null | undefined + >, + ): void; testIamPermissions( - request: protos.google.iam.v1.ITestIamPermissionsRequest, - callback: Callback< - protos.google.iam.v1.ITestIamPermissionsResponse, - protos.google.iam.v1.ITestIamPermissionsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.iam.v1.ITestIamPermissionsRequest, + callback: Callback< + protos.google.iam.v1.ITestIamPermissionsResponse, + protos.google.iam.v1.ITestIamPermissionsRequest | null | undefined, + {} | null | undefined + >, + ): void; testIamPermissions( - request?: protos.google.iam.v1.ITestIamPermissionsRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.iam.v1.ITestIamPermissionsRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.iam.v1.ITestIamPermissionsResponse, - protos.google.iam.v1.ITestIamPermissionsRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.iam.v1.ITestIamPermissionsResponse, - protos.google.iam.v1.ITestIamPermissionsRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.iam.v1.ITestIamPermissionsResponse, - protos.google.iam.v1.ITestIamPermissionsRequest|undefined, {}|undefined - ]>|void { + protos.google.iam.v1.ITestIamPermissionsRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.iam.v1.ITestIamPermissionsResponse, + protos.google.iam.v1.ITestIamPermissionsRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.iam.v1.ITestIamPermissionsResponse, + protos.google.iam.v1.ITestIamPermissionsRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'resource': request.resource ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + resource: request.resource ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('testIamPermissions request %j', request); - const wrappedCallback: Callback< - protos.google.iam.v1.ITestIamPermissionsResponse, - protos.google.iam.v1.ITestIamPermissionsRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.iam.v1.ITestIamPermissionsResponse, + protos.google.iam.v1.ITestIamPermissionsRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('testIamPermissions response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.testIamPermissions(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.iam.v1.ITestIamPermissionsResponse, - protos.google.iam.v1.ITestIamPermissionsRequest|undefined, {}|undefined - ]) => { - this._log.info('testIamPermissions response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .testIamPermissions(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.iam.v1.ITestIamPermissionsResponse, + protos.google.iam.v1.ITestIamPermissionsRequest | undefined, + {} | undefined, + ]) => { + this._log.info('testIamPermissions response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Gets a task. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The task name. For example: - * `projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID/tasks/TASK_ID` - * @param {google.cloud.tasks.v2.Task.View} request.responseView - * The response_view specifies which subset of the {@link protos.google.cloud.tasks.v2.Task|Task} will be - * returned. - * - * By default response_view is {@link protos.google.cloud.tasks.v2.Task.View.BASIC|BASIC}; not all - * information is retrieved by default because some data, such as - * payloads, might be desirable to return only when needed because - * of its large size or because of the sensitivity of data that it - * contains. - * - * Authorization for {@link protos.google.cloud.tasks.v2.Task.View.FULL|FULL} requires - * `cloudtasks.tasks.fullView` [Google IAM](https://cloud.google.com/iam/) - * permission on the {@link protos.google.cloud.tasks.v2.Task|Task} resource. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.tasks.v2.Task|Task}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/cloud_tasks.get_task.js - * region_tag:cloudtasks_v2_generated_CloudTasks_GetTask_async - */ + /** + * Gets a task. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The task name. For example: + * `projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID/tasks/TASK_ID` + * @param {google.cloud.tasks.v2.Task.View} request.responseView + * The response_view specifies which subset of the {@link protos.google.cloud.tasks.v2.Task|Task} will be + * returned. + * + * By default response_view is {@link protos.google.cloud.tasks.v2.Task.View.BASIC|BASIC}; not all + * information is retrieved by default because some data, such as + * payloads, might be desirable to return only when needed because + * of its large size or because of the sensitivity of data that it + * contains. + * + * Authorization for {@link protos.google.cloud.tasks.v2.Task.View.FULL|FULL} requires + * `cloudtasks.tasks.fullView` [Google IAM](https://cloud.google.com/iam/) + * permission on the {@link protos.google.cloud.tasks.v2.Task|Task} resource. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.tasks.v2.Task|Task}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/cloud_tasks.get_task.js + * region_tag:cloudtasks_v2_generated_CloudTasks_GetTask_async + */ getTask( - request?: protos.google.cloud.tasks.v2.IGetTaskRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.tasks.v2.ITask, - protos.google.cloud.tasks.v2.IGetTaskRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.tasks.v2.IGetTaskRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.tasks.v2.ITask, + protos.google.cloud.tasks.v2.IGetTaskRequest | undefined, + {} | undefined, + ] + >; getTask( - request: protos.google.cloud.tasks.v2.IGetTaskRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.tasks.v2.ITask, - protos.google.cloud.tasks.v2.IGetTaskRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.tasks.v2.IGetTaskRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.tasks.v2.ITask, + protos.google.cloud.tasks.v2.IGetTaskRequest | null | undefined, + {} | null | undefined + >, + ): void; getTask( - request: protos.google.cloud.tasks.v2.IGetTaskRequest, - callback: Callback< - protos.google.cloud.tasks.v2.ITask, - protos.google.cloud.tasks.v2.IGetTaskRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.tasks.v2.IGetTaskRequest, + callback: Callback< + protos.google.cloud.tasks.v2.ITask, + protos.google.cloud.tasks.v2.IGetTaskRequest | null | undefined, + {} | null | undefined + >, + ): void; getTask( - request?: protos.google.cloud.tasks.v2.IGetTaskRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.tasks.v2.ITask, - protos.google.cloud.tasks.v2.IGetTaskRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.tasks.v2.IGetTaskRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.tasks.v2.ITask, - protos.google.cloud.tasks.v2.IGetTaskRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.tasks.v2.ITask, - protos.google.cloud.tasks.v2.IGetTaskRequest|undefined, {}|undefined - ]>|void { + protos.google.cloud.tasks.v2.IGetTaskRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.tasks.v2.ITask, + protos.google.cloud.tasks.v2.IGetTaskRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.tasks.v2.ITask, + protos.google.cloud.tasks.v2.IGetTaskRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getTask request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.tasks.v2.ITask, - protos.google.cloud.tasks.v2.IGetTaskRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.tasks.v2.ITask, + protos.google.cloud.tasks.v2.IGetTaskRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getTask response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.getTask(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.tasks.v2.ITask, - protos.google.cloud.tasks.v2.IGetTaskRequest|undefined, {}|undefined - ]) => { - this._log.info('getTask response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getTask(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.tasks.v2.ITask, + protos.google.cloud.tasks.v2.IGetTaskRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getTask response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Creates a task and adds it to a queue. - * - * Tasks cannot be updated after creation; there is no UpdateTask command. - * - * * The maximum task size is 100KB. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The queue name. For example: - * `projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID` - * - * The queue must already exist. - * @param {google.cloud.tasks.v2.Task} request.task - * Required. The task to add. - * - * Task names have the following format: - * `projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID/tasks/TASK_ID`. - * The user can optionally specify a task {@link protos.google.cloud.tasks.v2.Task.name|name}. If a - * name is not specified then the system will generate a random - * unique task id, which will be set in the task returned in the - * {@link protos.google.cloud.tasks.v2.Task.name|response}. - * - * If {@link protos.google.cloud.tasks.v2.Task.schedule_time|schedule_time} is not set or is in the - * past then Cloud Tasks will set it to the current time. - * - * Task De-duplication: - * - * Explicitly specifying a task ID enables task de-duplication. If - * a task's ID is identical to that of an existing task or a task - * that was deleted or executed recently then the call will fail - * with {@link protos.google.rpc.Code.ALREADY_EXISTS|ALREADY_EXISTS}. - * If the task's queue was created using Cloud Tasks, then another task with - * the same name can't be created for ~1hour after the original task was - * deleted or executed. If the task's queue was created using queue.yaml or - * queue.xml, then another task with the same name can't be created - * for ~9days after the original task was deleted or executed. - * - * Because there is an extra lookup cost to identify duplicate task - * names, these {@link protos.google.cloud.tasks.v2.CloudTasks.CreateTask|CreateTask} calls have significantly - * increased latency. Using hashed strings for the task id or for - * the prefix of the task id is recommended. Choosing task ids that - * are sequential or have sequential prefixes, for example using a - * timestamp, causes an increase in latency and error rates in all - * task commands. The infrastructure relies on an approximately - * uniform distribution of task ids to store and serve tasks - * efficiently. - * @param {google.cloud.tasks.v2.Task.View} request.responseView - * The response_view specifies which subset of the {@link protos.google.cloud.tasks.v2.Task|Task} will be - * returned. - * - * By default response_view is {@link protos.google.cloud.tasks.v2.Task.View.BASIC|BASIC}; not all - * information is retrieved by default because some data, such as - * payloads, might be desirable to return only when needed because - * of its large size or because of the sensitivity of data that it - * contains. - * - * Authorization for {@link protos.google.cloud.tasks.v2.Task.View.FULL|FULL} requires - * `cloudtasks.tasks.fullView` [Google IAM](https://cloud.google.com/iam/) - * permission on the {@link protos.google.cloud.tasks.v2.Task|Task} resource. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.tasks.v2.Task|Task}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/cloud_tasks.create_task.js - * region_tag:cloudtasks_v2_generated_CloudTasks_CreateTask_async - */ + /** + * Creates a task and adds it to a queue. + * + * Tasks cannot be updated after creation; there is no UpdateTask command. + * + * * The maximum task size is 100KB. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The queue name. For example: + * `projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID` + * + * The queue must already exist. + * @param {google.cloud.tasks.v2.Task} request.task + * Required. The task to add. + * + * Task names have the following format: + * `projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID/tasks/TASK_ID`. + * The user can optionally specify a task {@link protos.google.cloud.tasks.v2.Task.name|name}. If a + * name is not specified then the system will generate a random + * unique task id, which will be set in the task returned in the + * {@link protos.google.cloud.tasks.v2.Task.name|response}. + * + * If {@link protos.google.cloud.tasks.v2.Task.schedule_time|schedule_time} is not set or is in the + * past then Cloud Tasks will set it to the current time. + * + * Task De-duplication: + * + * Explicitly specifying a task ID enables task de-duplication. If + * a task's ID is identical to that of an existing task or a task + * that was deleted or executed recently then the call will fail + * with {@link protos.google.rpc.Code.ALREADY_EXISTS|ALREADY_EXISTS}. + * If the task's queue was created using Cloud Tasks, then another task with + * the same name can't be created for ~1hour after the original task was + * deleted or executed. If the task's queue was created using queue.yaml or + * queue.xml, then another task with the same name can't be created + * for ~9days after the original task was deleted or executed. + * + * Because there is an extra lookup cost to identify duplicate task + * names, these {@link protos.google.cloud.tasks.v2.CloudTasks.CreateTask|CreateTask} calls have significantly + * increased latency. Using hashed strings for the task id or for + * the prefix of the task id is recommended. Choosing task ids that + * are sequential or have sequential prefixes, for example using a + * timestamp, causes an increase in latency and error rates in all + * task commands. The infrastructure relies on an approximately + * uniform distribution of task ids to store and serve tasks + * efficiently. + * @param {google.cloud.tasks.v2.Task.View} request.responseView + * The response_view specifies which subset of the {@link protos.google.cloud.tasks.v2.Task|Task} will be + * returned. + * + * By default response_view is {@link protos.google.cloud.tasks.v2.Task.View.BASIC|BASIC}; not all + * information is retrieved by default because some data, such as + * payloads, might be desirable to return only when needed because + * of its large size or because of the sensitivity of data that it + * contains. + * + * Authorization for {@link protos.google.cloud.tasks.v2.Task.View.FULL|FULL} requires + * `cloudtasks.tasks.fullView` [Google IAM](https://cloud.google.com/iam/) + * permission on the {@link protos.google.cloud.tasks.v2.Task|Task} resource. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.tasks.v2.Task|Task}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/cloud_tasks.create_task.js + * region_tag:cloudtasks_v2_generated_CloudTasks_CreateTask_async + */ createTask( - request?: protos.google.cloud.tasks.v2.ICreateTaskRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.tasks.v2.ITask, - protos.google.cloud.tasks.v2.ICreateTaskRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.tasks.v2.ICreateTaskRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.tasks.v2.ITask, + protos.google.cloud.tasks.v2.ICreateTaskRequest | undefined, + {} | undefined, + ] + >; createTask( - request: protos.google.cloud.tasks.v2.ICreateTaskRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.tasks.v2.ITask, - protos.google.cloud.tasks.v2.ICreateTaskRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.tasks.v2.ICreateTaskRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.tasks.v2.ITask, + protos.google.cloud.tasks.v2.ICreateTaskRequest | null | undefined, + {} | null | undefined + >, + ): void; createTask( - request: protos.google.cloud.tasks.v2.ICreateTaskRequest, - callback: Callback< - protos.google.cloud.tasks.v2.ITask, - protos.google.cloud.tasks.v2.ICreateTaskRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.tasks.v2.ICreateTaskRequest, + callback: Callback< + protos.google.cloud.tasks.v2.ITask, + protos.google.cloud.tasks.v2.ICreateTaskRequest | null | undefined, + {} | null | undefined + >, + ): void; createTask( - request?: protos.google.cloud.tasks.v2.ICreateTaskRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.cloud.tasks.v2.ICreateTaskRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.tasks.v2.ITask, - protos.google.cloud.tasks.v2.ICreateTaskRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.cloud.tasks.v2.ITask, - protos.google.cloud.tasks.v2.ICreateTaskRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.tasks.v2.ITask, - protos.google.cloud.tasks.v2.ICreateTaskRequest|undefined, {}|undefined - ]>|void { + protos.google.cloud.tasks.v2.ICreateTaskRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.tasks.v2.ITask, + protos.google.cloud.tasks.v2.ICreateTaskRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.tasks.v2.ITask, + protos.google.cloud.tasks.v2.ICreateTaskRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('createTask request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.tasks.v2.ITask, - protos.google.cloud.tasks.v2.ICreateTaskRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.tasks.v2.ITask, + protos.google.cloud.tasks.v2.ICreateTaskRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createTask response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.createTask(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.tasks.v2.ITask, - protos.google.cloud.tasks.v2.ICreateTaskRequest|undefined, {}|undefined - ]) => { - this._log.info('createTask response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createTask(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.tasks.v2.ITask, + protos.google.cloud.tasks.v2.ICreateTaskRequest | undefined, + {} | undefined, + ]) => { + this._log.info('createTask response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Deletes a task. - * - * A task can be deleted if it is scheduled or dispatched. A task - * cannot be deleted if it has executed successfully or permanently - * failed. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The task name. For example: - * `projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID/tasks/TASK_ID` - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/cloud_tasks.delete_task.js - * region_tag:cloudtasks_v2_generated_CloudTasks_DeleteTask_async - */ + /** + * Deletes a task. + * + * A task can be deleted if it is scheduled or dispatched. A task + * cannot be deleted if it has executed successfully or permanently + * failed. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The task name. For example: + * `projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID/tasks/TASK_ID` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/cloud_tasks.delete_task.js + * region_tag:cloudtasks_v2_generated_CloudTasks_DeleteTask_async + */ deleteTask( - request?: protos.google.cloud.tasks.v2.IDeleteTaskRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.cloud.tasks.v2.IDeleteTaskRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.tasks.v2.IDeleteTaskRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.cloud.tasks.v2.IDeleteTaskRequest | undefined, + {} | undefined, + ] + >; deleteTask( - request: protos.google.cloud.tasks.v2.IDeleteTaskRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.cloud.tasks.v2.IDeleteTaskRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.tasks.v2.IDeleteTaskRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.cloud.tasks.v2.IDeleteTaskRequest | null | undefined, + {} | null | undefined + >, + ): void; deleteTask( - request: protos.google.cloud.tasks.v2.IDeleteTaskRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.cloud.tasks.v2.IDeleteTaskRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.tasks.v2.IDeleteTaskRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.cloud.tasks.v2.IDeleteTaskRequest | null | undefined, + {} | null | undefined + >, + ): void; deleteTask( - request?: protos.google.cloud.tasks.v2.IDeleteTaskRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.protobuf.IEmpty, - protos.google.cloud.tasks.v2.IDeleteTaskRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.tasks.v2.IDeleteTaskRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.cloud.tasks.v2.IDeleteTaskRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.cloud.tasks.v2.IDeleteTaskRequest|undefined, {}|undefined - ]>|void { + protos.google.cloud.tasks.v2.IDeleteTaskRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + protos.google.cloud.tasks.v2.IDeleteTaskRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.cloud.tasks.v2.IDeleteTaskRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('deleteTask request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.cloud.tasks.v2.IDeleteTaskRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + protos.google.cloud.tasks.v2.IDeleteTaskRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteTask response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.deleteTask(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.cloud.tasks.v2.IDeleteTaskRequest|undefined, {}|undefined - ]) => { - this._log.info('deleteTask response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteTask(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.cloud.tasks.v2.IDeleteTaskRequest | undefined, + {} | undefined, + ]) => { + this._log.info('deleteTask response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Forces a task to run now. - * - * When this method is called, Cloud Tasks will dispatch the task, even if - * the task is already running, the queue has reached its {@link protos.google.cloud.tasks.v2.RateLimits|RateLimits} or - * is {@link protos.google.cloud.tasks.v2.Queue.State.PAUSED|PAUSED}. - * - * This command is meant to be used for manual debugging. For - * example, {@link protos.google.cloud.tasks.v2.CloudTasks.RunTask|RunTask} can be used to retry a failed - * task after a fix has been made or to manually force a task to be - * dispatched now. - * - * The dispatched task is returned. That is, the task that is returned - * contains the {@link protos.Task.status|status} after the task is dispatched but - * before the task is received by its target. - * - * If Cloud Tasks receives a successful response from the task's - * target, then the task will be deleted; otherwise the task's - * {@link protos.google.cloud.tasks.v2.Task.schedule_time|schedule_time} will be reset to the time that - * {@link protos.google.cloud.tasks.v2.CloudTasks.RunTask|RunTask} was called plus the retry delay specified - * in the queue's {@link protos.google.cloud.tasks.v2.RetryConfig|RetryConfig}. - * - * {@link protos.google.cloud.tasks.v2.CloudTasks.RunTask|RunTask} returns - * {@link protos.google.rpc.Code.NOT_FOUND|NOT_FOUND} when it is called on a - * task that has already succeeded or permanently failed. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The task name. For example: - * `projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID/tasks/TASK_ID` - * @param {google.cloud.tasks.v2.Task.View} request.responseView - * The response_view specifies which subset of the {@link protos.google.cloud.tasks.v2.Task|Task} will be - * returned. - * - * By default response_view is {@link protos.google.cloud.tasks.v2.Task.View.BASIC|BASIC}; not all - * information is retrieved by default because some data, such as - * payloads, might be desirable to return only when needed because - * of its large size or because of the sensitivity of data that it - * contains. - * - * Authorization for {@link protos.google.cloud.tasks.v2.Task.View.FULL|FULL} requires - * `cloudtasks.tasks.fullView` [Google IAM](https://cloud.google.com/iam/) - * permission on the {@link protos.google.cloud.tasks.v2.Task|Task} resource. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.tasks.v2.Task|Task}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/cloud_tasks.run_task.js - * region_tag:cloudtasks_v2_generated_CloudTasks_RunTask_async - */ + /** + * Forces a task to run now. + * + * When this method is called, Cloud Tasks will dispatch the task, even if + * the task is already running, the queue has reached its {@link protos.google.cloud.tasks.v2.RateLimits|RateLimits} or + * is {@link protos.google.cloud.tasks.v2.Queue.State.PAUSED|PAUSED}. + * + * This command is meant to be used for manual debugging. For + * example, {@link protos.google.cloud.tasks.v2.CloudTasks.RunTask|RunTask} can be used to retry a failed + * task after a fix has been made or to manually force a task to be + * dispatched now. + * + * The dispatched task is returned. That is, the task that is returned + * contains the {@link protos.Task.status|status} after the task is dispatched but + * before the task is received by its target. + * + * If Cloud Tasks receives a successful response from the task's + * target, then the task will be deleted; otherwise the task's + * {@link protos.google.cloud.tasks.v2.Task.schedule_time|schedule_time} will be reset to the time that + * {@link protos.google.cloud.tasks.v2.CloudTasks.RunTask|RunTask} was called plus the retry delay specified + * in the queue's {@link protos.google.cloud.tasks.v2.RetryConfig|RetryConfig}. + * + * {@link protos.google.cloud.tasks.v2.CloudTasks.RunTask|RunTask} returns + * {@link protos.google.rpc.Code.NOT_FOUND|NOT_FOUND} when it is called on a + * task that has already succeeded or permanently failed. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The task name. For example: + * `projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID/tasks/TASK_ID` + * @param {google.cloud.tasks.v2.Task.View} request.responseView + * The response_view specifies which subset of the {@link protos.google.cloud.tasks.v2.Task|Task} will be + * returned. + * + * By default response_view is {@link protos.google.cloud.tasks.v2.Task.View.BASIC|BASIC}; not all + * information is retrieved by default because some data, such as + * payloads, might be desirable to return only when needed because + * of its large size or because of the sensitivity of data that it + * contains. + * + * Authorization for {@link protos.google.cloud.tasks.v2.Task.View.FULL|FULL} requires + * `cloudtasks.tasks.fullView` [Google IAM](https://cloud.google.com/iam/) + * permission on the {@link protos.google.cloud.tasks.v2.Task|Task} resource. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.tasks.v2.Task|Task}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/cloud_tasks.run_task.js + * region_tag:cloudtasks_v2_generated_CloudTasks_RunTask_async + */ runTask( - request?: protos.google.cloud.tasks.v2.IRunTaskRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.tasks.v2.ITask, - protos.google.cloud.tasks.v2.IRunTaskRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.tasks.v2.IRunTaskRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.tasks.v2.ITask, + protos.google.cloud.tasks.v2.IRunTaskRequest | undefined, + {} | undefined, + ] + >; runTask( - request: protos.google.cloud.tasks.v2.IRunTaskRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.tasks.v2.ITask, - protos.google.cloud.tasks.v2.IRunTaskRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.tasks.v2.IRunTaskRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.tasks.v2.ITask, + protos.google.cloud.tasks.v2.IRunTaskRequest | null | undefined, + {} | null | undefined + >, + ): void; runTask( - request: protos.google.cloud.tasks.v2.IRunTaskRequest, - callback: Callback< - protos.google.cloud.tasks.v2.ITask, - protos.google.cloud.tasks.v2.IRunTaskRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.tasks.v2.IRunTaskRequest, + callback: Callback< + protos.google.cloud.tasks.v2.ITask, + protos.google.cloud.tasks.v2.IRunTaskRequest | null | undefined, + {} | null | undefined + >, + ): void; runTask( - request?: protos.google.cloud.tasks.v2.IRunTaskRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.tasks.v2.ITask, - protos.google.cloud.tasks.v2.IRunTaskRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.tasks.v2.IRunTaskRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.tasks.v2.ITask, - protos.google.cloud.tasks.v2.IRunTaskRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.tasks.v2.ITask, - protos.google.cloud.tasks.v2.IRunTaskRequest|undefined, {}|undefined - ]>|void { + protos.google.cloud.tasks.v2.IRunTaskRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.tasks.v2.ITask, + protos.google.cloud.tasks.v2.IRunTaskRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.tasks.v2.ITask, + protos.google.cloud.tasks.v2.IRunTaskRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('runTask request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.tasks.v2.ITask, - protos.google.cloud.tasks.v2.IRunTaskRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.tasks.v2.ITask, + protos.google.cloud.tasks.v2.IRunTaskRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('runTask response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.runTask(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.tasks.v2.ITask, - protos.google.cloud.tasks.v2.IRunTaskRequest|undefined, {}|undefined - ]) => { - this._log.info('runTask response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .runTask(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.tasks.v2.ITask, + protos.google.cloud.tasks.v2.IRunTaskRequest | undefined, + {} | undefined, + ]) => { + this._log.info('runTask response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } - /** - * Lists queues. - * - * Queues are returned in lexicographical order. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The location name. - * For example: `projects/PROJECT_ID/locations/LOCATION_ID` - * @param {string} request.filter - * `filter` can be used to specify a subset of queues. Any {@link protos.google.cloud.tasks.v2.Queue|Queue} - * field can be used as a filter and several operators as supported. - * For example: `<=, <, >=, >, !=, =, :`. The filter syntax is the same as - * described in - * [Stackdriver's Advanced Logs - * Filters](https://cloud.google.com/logging/docs/view/advanced_filters). - * - * Sample filter "state: PAUSED". - * - * Note that using filters might cause fewer queues than the - * requested page_size to be returned. - * @param {number} request.pageSize - * Requested page size. - * - * The maximum page size is 9800. If unspecified, the page size will - * be the maximum. Fewer queues than requested might be returned, - * even if more queues exist; use the - * {@link protos.google.cloud.tasks.v2.ListQueuesResponse.next_page_token|next_page_token} in the - * response to determine if more queues exist. - * @param {string} request.pageToken - * A token identifying the page of results to return. - * - * To request the first page results, page_token must be empty. To - * request the next page of results, page_token must be the value of - * {@link protos.google.cloud.tasks.v2.ListQueuesResponse.next_page_token|next_page_token} returned - * from the previous call to {@link protos.google.cloud.tasks.v2.CloudTasks.ListQueues|ListQueues} - * method. It is an error to switch the value of the - * {@link protos.google.cloud.tasks.v2.ListQueuesRequest.filter|filter} while iterating through pages. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.cloud.tasks.v2.Queue|Queue}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `listQueuesAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Lists queues. + * + * Queues are returned in lexicographical order. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The location name. + * For example: `projects/PROJECT_ID/locations/LOCATION_ID` + * @param {string} request.filter + * `filter` can be used to specify a subset of queues. Any {@link protos.google.cloud.tasks.v2.Queue|Queue} + * field can be used as a filter and several operators as supported. + * For example: `<=, <, >=, >, !=, =, :`. The filter syntax is the same as + * described in + * [Stackdriver's Advanced Logs + * Filters](https://cloud.google.com/logging/docs/view/advanced_filters). + * + * Sample filter "state: PAUSED". + * + * Note that using filters might cause fewer queues than the + * requested page_size to be returned. + * @param {number} request.pageSize + * Requested page size. + * + * The maximum page size is 9800. If unspecified, the page size will + * be the maximum. Fewer queues than requested might be returned, + * even if more queues exist; use the + * {@link protos.google.cloud.tasks.v2.ListQueuesResponse.next_page_token|next_page_token} in the + * response to determine if more queues exist. + * @param {string} request.pageToken + * A token identifying the page of results to return. + * + * To request the first page results, page_token must be empty. To + * request the next page of results, page_token must be the value of + * {@link protos.google.cloud.tasks.v2.ListQueuesResponse.next_page_token|next_page_token} returned + * from the previous call to {@link protos.google.cloud.tasks.v2.CloudTasks.ListQueues|ListQueues} + * method. It is an error to switch the value of the + * {@link protos.google.cloud.tasks.v2.ListQueuesRequest.filter|filter} while iterating through pages. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.cloud.tasks.v2.Queue|Queue}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listQueuesAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listQueues( - request?: protos.google.cloud.tasks.v2.IListQueuesRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.tasks.v2.IQueue[], - protos.google.cloud.tasks.v2.IListQueuesRequest|null, - protos.google.cloud.tasks.v2.IListQueuesResponse - ]>; + request?: protos.google.cloud.tasks.v2.IListQueuesRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.tasks.v2.IQueue[], + protos.google.cloud.tasks.v2.IListQueuesRequest | null, + protos.google.cloud.tasks.v2.IListQueuesResponse, + ] + >; listQueues( - request: protos.google.cloud.tasks.v2.IListQueuesRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.cloud.tasks.v2.IListQueuesRequest, - protos.google.cloud.tasks.v2.IListQueuesResponse|null|undefined, - protos.google.cloud.tasks.v2.IQueue>): void; + request: protos.google.cloud.tasks.v2.IListQueuesRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.cloud.tasks.v2.IListQueuesRequest, + protos.google.cloud.tasks.v2.IListQueuesResponse | null | undefined, + protos.google.cloud.tasks.v2.IQueue + >, + ): void; listQueues( - request: protos.google.cloud.tasks.v2.IListQueuesRequest, - callback: PaginationCallback< - protos.google.cloud.tasks.v2.IListQueuesRequest, - protos.google.cloud.tasks.v2.IListQueuesResponse|null|undefined, - protos.google.cloud.tasks.v2.IQueue>): void; + request: protos.google.cloud.tasks.v2.IListQueuesRequest, + callback: PaginationCallback< + protos.google.cloud.tasks.v2.IListQueuesRequest, + protos.google.cloud.tasks.v2.IListQueuesResponse | null | undefined, + protos.google.cloud.tasks.v2.IQueue + >, + ): void; listQueues( - request?: protos.google.cloud.tasks.v2.IListQueuesRequest, - optionsOrCallback?: CallOptions|PaginationCallback< + request?: protos.google.cloud.tasks.v2.IListQueuesRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.cloud.tasks.v2.IListQueuesRequest, - protos.google.cloud.tasks.v2.IListQueuesResponse|null|undefined, - protos.google.cloud.tasks.v2.IQueue>, - callback?: PaginationCallback< - protos.google.cloud.tasks.v2.IListQueuesRequest, - protos.google.cloud.tasks.v2.IListQueuesResponse|null|undefined, - protos.google.cloud.tasks.v2.IQueue>): - Promise<[ - protos.google.cloud.tasks.v2.IQueue[], - protos.google.cloud.tasks.v2.IListQueuesRequest|null, - protos.google.cloud.tasks.v2.IListQueuesResponse - ]>|void { + protos.google.cloud.tasks.v2.IListQueuesResponse | null | undefined, + protos.google.cloud.tasks.v2.IQueue + >, + callback?: PaginationCallback< + protos.google.cloud.tasks.v2.IListQueuesRequest, + protos.google.cloud.tasks.v2.IListQueuesResponse | null | undefined, + protos.google.cloud.tasks.v2.IQueue + >, + ): Promise< + [ + protos.google.cloud.tasks.v2.IQueue[], + protos.google.cloud.tasks.v2.IListQueuesRequest | null, + protos.google.cloud.tasks.v2.IListQueuesResponse, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.cloud.tasks.v2.IListQueuesRequest, - protos.google.cloud.tasks.v2.IListQueuesResponse|null|undefined, - protos.google.cloud.tasks.v2.IQueue>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.cloud.tasks.v2.IListQueuesRequest, + protos.google.cloud.tasks.v2.IListQueuesResponse | null | undefined, + protos.google.cloud.tasks.v2.IQueue + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listQueues values %j', values); callback!(error, values, nextPageRequest, rawResponse); @@ -2013,278 +2529,297 @@ export class CloudTasksClient { this._log.info('listQueues request %j', request); return this.innerApiCalls .listQueues(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.cloud.tasks.v2.IQueue[], - protos.google.cloud.tasks.v2.IListQueuesRequest|null, - protos.google.cloud.tasks.v2.IListQueuesResponse - ]) => { - this._log.info('listQueues values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.cloud.tasks.v2.IQueue[], + protos.google.cloud.tasks.v2.IListQueuesRequest | null, + protos.google.cloud.tasks.v2.IListQueuesResponse, + ]) => { + this._log.info('listQueues values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listQueues`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The location name. - * For example: `projects/PROJECT_ID/locations/LOCATION_ID` - * @param {string} request.filter - * `filter` can be used to specify a subset of queues. Any {@link protos.google.cloud.tasks.v2.Queue|Queue} - * field can be used as a filter and several operators as supported. - * For example: `<=, <, >=, >, !=, =, :`. The filter syntax is the same as - * described in - * [Stackdriver's Advanced Logs - * Filters](https://cloud.google.com/logging/docs/view/advanced_filters). - * - * Sample filter "state: PAUSED". - * - * Note that using filters might cause fewer queues than the - * requested page_size to be returned. - * @param {number} request.pageSize - * Requested page size. - * - * The maximum page size is 9800. If unspecified, the page size will - * be the maximum. Fewer queues than requested might be returned, - * even if more queues exist; use the - * {@link protos.google.cloud.tasks.v2.ListQueuesResponse.next_page_token|next_page_token} in the - * response to determine if more queues exist. - * @param {string} request.pageToken - * A token identifying the page of results to return. - * - * To request the first page results, page_token must be empty. To - * request the next page of results, page_token must be the value of - * {@link protos.google.cloud.tasks.v2.ListQueuesResponse.next_page_token|next_page_token} returned - * from the previous call to {@link protos.google.cloud.tasks.v2.CloudTasks.ListQueues|ListQueues} - * method. It is an error to switch the value of the - * {@link protos.google.cloud.tasks.v2.ListQueuesRequest.filter|filter} while iterating through pages. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.cloud.tasks.v2.Queue|Queue} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `listQueuesAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `listQueues`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The location name. + * For example: `projects/PROJECT_ID/locations/LOCATION_ID` + * @param {string} request.filter + * `filter` can be used to specify a subset of queues. Any {@link protos.google.cloud.tasks.v2.Queue|Queue} + * field can be used as a filter and several operators as supported. + * For example: `<=, <, >=, >, !=, =, :`. The filter syntax is the same as + * described in + * [Stackdriver's Advanced Logs + * Filters](https://cloud.google.com/logging/docs/view/advanced_filters). + * + * Sample filter "state: PAUSED". + * + * Note that using filters might cause fewer queues than the + * requested page_size to be returned. + * @param {number} request.pageSize + * Requested page size. + * + * The maximum page size is 9800. If unspecified, the page size will + * be the maximum. Fewer queues than requested might be returned, + * even if more queues exist; use the + * {@link protos.google.cloud.tasks.v2.ListQueuesResponse.next_page_token|next_page_token} in the + * response to determine if more queues exist. + * @param {string} request.pageToken + * A token identifying the page of results to return. + * + * To request the first page results, page_token must be empty. To + * request the next page of results, page_token must be the value of + * {@link protos.google.cloud.tasks.v2.ListQueuesResponse.next_page_token|next_page_token} returned + * from the previous call to {@link protos.google.cloud.tasks.v2.CloudTasks.ListQueues|ListQueues} + * method. It is an error to switch the value of the + * {@link protos.google.cloud.tasks.v2.ListQueuesRequest.filter|filter} while iterating through pages. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.cloud.tasks.v2.Queue|Queue} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listQueuesAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listQueuesStream( - request?: protos.google.cloud.tasks.v2.IListQueuesRequest, - options?: CallOptions): - Transform{ + request?: protos.google.cloud.tasks.v2.IListQueuesRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); const defaultCallSettings = this._defaults['listQueues']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listQueues stream %j', request); return this.descriptors.page.listQueues.createStream( this.innerApiCalls.listQueues as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listQueues`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The location name. - * For example: `projects/PROJECT_ID/locations/LOCATION_ID` - * @param {string} request.filter - * `filter` can be used to specify a subset of queues. Any {@link protos.google.cloud.tasks.v2.Queue|Queue} - * field can be used as a filter and several operators as supported. - * For example: `<=, <, >=, >, !=, =, :`. The filter syntax is the same as - * described in - * [Stackdriver's Advanced Logs - * Filters](https://cloud.google.com/logging/docs/view/advanced_filters). - * - * Sample filter "state: PAUSED". - * - * Note that using filters might cause fewer queues than the - * requested page_size to be returned. - * @param {number} request.pageSize - * Requested page size. - * - * The maximum page size is 9800. If unspecified, the page size will - * be the maximum. Fewer queues than requested might be returned, - * even if more queues exist; use the - * {@link protos.google.cloud.tasks.v2.ListQueuesResponse.next_page_token|next_page_token} in the - * response to determine if more queues exist. - * @param {string} request.pageToken - * A token identifying the page of results to return. - * - * To request the first page results, page_token must be empty. To - * request the next page of results, page_token must be the value of - * {@link protos.google.cloud.tasks.v2.ListQueuesResponse.next_page_token|next_page_token} returned - * from the previous call to {@link protos.google.cloud.tasks.v2.CloudTasks.ListQueues|ListQueues} - * method. It is an error to switch the value of the - * {@link protos.google.cloud.tasks.v2.ListQueuesRequest.filter|filter} while iterating through pages. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.cloud.tasks.v2.Queue|Queue}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v2/cloud_tasks.list_queues.js - * region_tag:cloudtasks_v2_generated_CloudTasks_ListQueues_async - */ + /** + * Equivalent to `listQueues`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The location name. + * For example: `projects/PROJECT_ID/locations/LOCATION_ID` + * @param {string} request.filter + * `filter` can be used to specify a subset of queues. Any {@link protos.google.cloud.tasks.v2.Queue|Queue} + * field can be used as a filter and several operators as supported. + * For example: `<=, <, >=, >, !=, =, :`. The filter syntax is the same as + * described in + * [Stackdriver's Advanced Logs + * Filters](https://cloud.google.com/logging/docs/view/advanced_filters). + * + * Sample filter "state: PAUSED". + * + * Note that using filters might cause fewer queues than the + * requested page_size to be returned. + * @param {number} request.pageSize + * Requested page size. + * + * The maximum page size is 9800. If unspecified, the page size will + * be the maximum. Fewer queues than requested might be returned, + * even if more queues exist; use the + * {@link protos.google.cloud.tasks.v2.ListQueuesResponse.next_page_token|next_page_token} in the + * response to determine if more queues exist. + * @param {string} request.pageToken + * A token identifying the page of results to return. + * + * To request the first page results, page_token must be empty. To + * request the next page of results, page_token must be the value of + * {@link protos.google.cloud.tasks.v2.ListQueuesResponse.next_page_token|next_page_token} returned + * from the previous call to {@link protos.google.cloud.tasks.v2.CloudTasks.ListQueues|ListQueues} + * method. It is an error to switch the value of the + * {@link protos.google.cloud.tasks.v2.ListQueuesRequest.filter|filter} while iterating through pages. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.cloud.tasks.v2.Queue|Queue}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v2/cloud_tasks.list_queues.js + * region_tag:cloudtasks_v2_generated_CloudTasks_ListQueues_async + */ listQueuesAsync( - request?: protos.google.cloud.tasks.v2.IListQueuesRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.cloud.tasks.v2.IListQueuesRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); const defaultCallSettings = this._defaults['listQueues']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listQueues iterate %j', request); return this.descriptors.page.listQueues.asyncIterate( this.innerApiCalls['listQueues'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } - /** - * Lists the tasks in a queue. - * - * By default, only the {@link protos.google.cloud.tasks.v2.Task.View.BASIC|BASIC} view is retrieved - * due to performance considerations; - * {@link protos.google.cloud.tasks.v2.ListTasksRequest.response_view|response_view} controls the - * subset of information which is returned. - * - * The tasks may be returned in any order. The ordering may change at any - * time. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The queue name. For example: - * `projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID` - * @param {google.cloud.tasks.v2.Task.View} request.responseView - * The response_view specifies which subset of the {@link protos.google.cloud.tasks.v2.Task|Task} will be - * returned. - * - * By default response_view is {@link protos.google.cloud.tasks.v2.Task.View.BASIC|BASIC}; not all - * information is retrieved by default because some data, such as - * payloads, might be desirable to return only when needed because - * of its large size or because of the sensitivity of data that it - * contains. - * - * Authorization for {@link protos.google.cloud.tasks.v2.Task.View.FULL|FULL} requires - * `cloudtasks.tasks.fullView` [Google IAM](https://cloud.google.com/iam/) - * permission on the {@link protos.google.cloud.tasks.v2.Task|Task} resource. - * @param {number} request.pageSize - * Maximum page size. - * - * Fewer tasks than requested might be returned, even if more tasks exist; use - * {@link protos.google.cloud.tasks.v2.ListTasksResponse.next_page_token|next_page_token} in the response to - * determine if more tasks exist. - * - * The maximum page size is 1000. If unspecified, the page size will be the - * maximum. - * @param {string} request.pageToken - * A token identifying the page of results to return. - * - * To request the first page results, page_token must be empty. To - * request the next page of results, page_token must be the value of - * {@link protos.google.cloud.tasks.v2.ListTasksResponse.next_page_token|next_page_token} returned - * from the previous call to {@link protos.google.cloud.tasks.v2.CloudTasks.ListTasks|ListTasks} - * method. - * - * The page token is valid for only 2 hours. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.cloud.tasks.v2.Task|Task}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `listTasksAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Lists the tasks in a queue. + * + * By default, only the {@link protos.google.cloud.tasks.v2.Task.View.BASIC|BASIC} view is retrieved + * due to performance considerations; + * {@link protos.google.cloud.tasks.v2.ListTasksRequest.response_view|response_view} controls the + * subset of information which is returned. + * + * The tasks may be returned in any order. The ordering may change at any + * time. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The queue name. For example: + * `projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID` + * @param {google.cloud.tasks.v2.Task.View} request.responseView + * The response_view specifies which subset of the {@link protos.google.cloud.tasks.v2.Task|Task} will be + * returned. + * + * By default response_view is {@link protos.google.cloud.tasks.v2.Task.View.BASIC|BASIC}; not all + * information is retrieved by default because some data, such as + * payloads, might be desirable to return only when needed because + * of its large size or because of the sensitivity of data that it + * contains. + * + * Authorization for {@link protos.google.cloud.tasks.v2.Task.View.FULL|FULL} requires + * `cloudtasks.tasks.fullView` [Google IAM](https://cloud.google.com/iam/) + * permission on the {@link protos.google.cloud.tasks.v2.Task|Task} resource. + * @param {number} request.pageSize + * Maximum page size. + * + * Fewer tasks than requested might be returned, even if more tasks exist; use + * {@link protos.google.cloud.tasks.v2.ListTasksResponse.next_page_token|next_page_token} in the response to + * determine if more tasks exist. + * + * The maximum page size is 1000. If unspecified, the page size will be the + * maximum. + * @param {string} request.pageToken + * A token identifying the page of results to return. + * + * To request the first page results, page_token must be empty. To + * request the next page of results, page_token must be the value of + * {@link protos.google.cloud.tasks.v2.ListTasksResponse.next_page_token|next_page_token} returned + * from the previous call to {@link protos.google.cloud.tasks.v2.CloudTasks.ListTasks|ListTasks} + * method. + * + * The page token is valid for only 2 hours. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.cloud.tasks.v2.Task|Task}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listTasksAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listTasks( - request?: protos.google.cloud.tasks.v2.IListTasksRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.tasks.v2.ITask[], - protos.google.cloud.tasks.v2.IListTasksRequest|null, - protos.google.cloud.tasks.v2.IListTasksResponse - ]>; + request?: protos.google.cloud.tasks.v2.IListTasksRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.tasks.v2.ITask[], + protos.google.cloud.tasks.v2.IListTasksRequest | null, + protos.google.cloud.tasks.v2.IListTasksResponse, + ] + >; listTasks( - request: protos.google.cloud.tasks.v2.IListTasksRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.cloud.tasks.v2.IListTasksRequest, - protos.google.cloud.tasks.v2.IListTasksResponse|null|undefined, - protos.google.cloud.tasks.v2.ITask>): void; + request: protos.google.cloud.tasks.v2.IListTasksRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.cloud.tasks.v2.IListTasksRequest, + protos.google.cloud.tasks.v2.IListTasksResponse | null | undefined, + protos.google.cloud.tasks.v2.ITask + >, + ): void; listTasks( - request: protos.google.cloud.tasks.v2.IListTasksRequest, - callback: PaginationCallback< - protos.google.cloud.tasks.v2.IListTasksRequest, - protos.google.cloud.tasks.v2.IListTasksResponse|null|undefined, - protos.google.cloud.tasks.v2.ITask>): void; + request: protos.google.cloud.tasks.v2.IListTasksRequest, + callback: PaginationCallback< + protos.google.cloud.tasks.v2.IListTasksRequest, + protos.google.cloud.tasks.v2.IListTasksResponse | null | undefined, + protos.google.cloud.tasks.v2.ITask + >, + ): void; listTasks( - request?: protos.google.cloud.tasks.v2.IListTasksRequest, - optionsOrCallback?: CallOptions|PaginationCallback< - protos.google.cloud.tasks.v2.IListTasksRequest, - protos.google.cloud.tasks.v2.IListTasksResponse|null|undefined, - protos.google.cloud.tasks.v2.ITask>, - callback?: PaginationCallback< + request?: protos.google.cloud.tasks.v2.IListTasksRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.cloud.tasks.v2.IListTasksRequest, - protos.google.cloud.tasks.v2.IListTasksResponse|null|undefined, - protos.google.cloud.tasks.v2.ITask>): - Promise<[ - protos.google.cloud.tasks.v2.ITask[], - protos.google.cloud.tasks.v2.IListTasksRequest|null, - protos.google.cloud.tasks.v2.IListTasksResponse - ]>|void { + protos.google.cloud.tasks.v2.IListTasksResponse | null | undefined, + protos.google.cloud.tasks.v2.ITask + >, + callback?: PaginationCallback< + protos.google.cloud.tasks.v2.IListTasksRequest, + protos.google.cloud.tasks.v2.IListTasksResponse | null | undefined, + protos.google.cloud.tasks.v2.ITask + >, + ): Promise< + [ + protos.google.cloud.tasks.v2.ITask[], + protos.google.cloud.tasks.v2.IListTasksRequest | null, + protos.google.cloud.tasks.v2.IListTasksResponse, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.cloud.tasks.v2.IListTasksRequest, - protos.google.cloud.tasks.v2.IListTasksResponse|null|undefined, - protos.google.cloud.tasks.v2.ITask>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.cloud.tasks.v2.IListTasksRequest, + protos.google.cloud.tasks.v2.IListTasksResponse | null | undefined, + protos.google.cloud.tasks.v2.ITask + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listTasks values %j', values); callback!(error, values, nextPageRequest, rawResponse); @@ -2293,164 +2828,168 @@ export class CloudTasksClient { this._log.info('listTasks request %j', request); return this.innerApiCalls .listTasks(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.cloud.tasks.v2.ITask[], - protos.google.cloud.tasks.v2.IListTasksRequest|null, - protos.google.cloud.tasks.v2.IListTasksResponse - ]) => { - this._log.info('listTasks values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.cloud.tasks.v2.ITask[], + protos.google.cloud.tasks.v2.IListTasksRequest | null, + protos.google.cloud.tasks.v2.IListTasksResponse, + ]) => { + this._log.info('listTasks values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listTasks`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The queue name. For example: - * `projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID` - * @param {google.cloud.tasks.v2.Task.View} request.responseView - * The response_view specifies which subset of the {@link protos.google.cloud.tasks.v2.Task|Task} will be - * returned. - * - * By default response_view is {@link protos.google.cloud.tasks.v2.Task.View.BASIC|BASIC}; not all - * information is retrieved by default because some data, such as - * payloads, might be desirable to return only when needed because - * of its large size or because of the sensitivity of data that it - * contains. - * - * Authorization for {@link protos.google.cloud.tasks.v2.Task.View.FULL|FULL} requires - * `cloudtasks.tasks.fullView` [Google IAM](https://cloud.google.com/iam/) - * permission on the {@link protos.google.cloud.tasks.v2.Task|Task} resource. - * @param {number} request.pageSize - * Maximum page size. - * - * Fewer tasks than requested might be returned, even if more tasks exist; use - * {@link protos.google.cloud.tasks.v2.ListTasksResponse.next_page_token|next_page_token} in the response to - * determine if more tasks exist. - * - * The maximum page size is 1000. If unspecified, the page size will be the - * maximum. - * @param {string} request.pageToken - * A token identifying the page of results to return. - * - * To request the first page results, page_token must be empty. To - * request the next page of results, page_token must be the value of - * {@link protos.google.cloud.tasks.v2.ListTasksResponse.next_page_token|next_page_token} returned - * from the previous call to {@link protos.google.cloud.tasks.v2.CloudTasks.ListTasks|ListTasks} - * method. - * - * The page token is valid for only 2 hours. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.cloud.tasks.v2.Task|Task} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `listTasksAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `listTasks`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The queue name. For example: + * `projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID` + * @param {google.cloud.tasks.v2.Task.View} request.responseView + * The response_view specifies which subset of the {@link protos.google.cloud.tasks.v2.Task|Task} will be + * returned. + * + * By default response_view is {@link protos.google.cloud.tasks.v2.Task.View.BASIC|BASIC}; not all + * information is retrieved by default because some data, such as + * payloads, might be desirable to return only when needed because + * of its large size or because of the sensitivity of data that it + * contains. + * + * Authorization for {@link protos.google.cloud.tasks.v2.Task.View.FULL|FULL} requires + * `cloudtasks.tasks.fullView` [Google IAM](https://cloud.google.com/iam/) + * permission on the {@link protos.google.cloud.tasks.v2.Task|Task} resource. + * @param {number} request.pageSize + * Maximum page size. + * + * Fewer tasks than requested might be returned, even if more tasks exist; use + * {@link protos.google.cloud.tasks.v2.ListTasksResponse.next_page_token|next_page_token} in the response to + * determine if more tasks exist. + * + * The maximum page size is 1000. If unspecified, the page size will be the + * maximum. + * @param {string} request.pageToken + * A token identifying the page of results to return. + * + * To request the first page results, page_token must be empty. To + * request the next page of results, page_token must be the value of + * {@link protos.google.cloud.tasks.v2.ListTasksResponse.next_page_token|next_page_token} returned + * from the previous call to {@link protos.google.cloud.tasks.v2.CloudTasks.ListTasks|ListTasks} + * method. + * + * The page token is valid for only 2 hours. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.cloud.tasks.v2.Task|Task} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listTasksAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listTasksStream( - request?: protos.google.cloud.tasks.v2.IListTasksRequest, - options?: CallOptions): - Transform{ + request?: protos.google.cloud.tasks.v2.IListTasksRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); const defaultCallSettings = this._defaults['listTasks']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listTasks stream %j', request); return this.descriptors.page.listTasks.createStream( this.innerApiCalls.listTasks as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listTasks`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The queue name. For example: - * `projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID` - * @param {google.cloud.tasks.v2.Task.View} request.responseView - * The response_view specifies which subset of the {@link protos.google.cloud.tasks.v2.Task|Task} will be - * returned. - * - * By default response_view is {@link protos.google.cloud.tasks.v2.Task.View.BASIC|BASIC}; not all - * information is retrieved by default because some data, such as - * payloads, might be desirable to return only when needed because - * of its large size or because of the sensitivity of data that it - * contains. - * - * Authorization for {@link protos.google.cloud.tasks.v2.Task.View.FULL|FULL} requires - * `cloudtasks.tasks.fullView` [Google IAM](https://cloud.google.com/iam/) - * permission on the {@link protos.google.cloud.tasks.v2.Task|Task} resource. - * @param {number} request.pageSize - * Maximum page size. - * - * Fewer tasks than requested might be returned, even if more tasks exist; use - * {@link protos.google.cloud.tasks.v2.ListTasksResponse.next_page_token|next_page_token} in the response to - * determine if more tasks exist. - * - * The maximum page size is 1000. If unspecified, the page size will be the - * maximum. - * @param {string} request.pageToken - * A token identifying the page of results to return. - * - * To request the first page results, page_token must be empty. To - * request the next page of results, page_token must be the value of - * {@link protos.google.cloud.tasks.v2.ListTasksResponse.next_page_token|next_page_token} returned - * from the previous call to {@link protos.google.cloud.tasks.v2.CloudTasks.ListTasks|ListTasks} - * method. - * - * The page token is valid for only 2 hours. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.cloud.tasks.v2.Task|Task}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v2/cloud_tasks.list_tasks.js - * region_tag:cloudtasks_v2_generated_CloudTasks_ListTasks_async - */ + /** + * Equivalent to `listTasks`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The queue name. For example: + * `projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID` + * @param {google.cloud.tasks.v2.Task.View} request.responseView + * The response_view specifies which subset of the {@link protos.google.cloud.tasks.v2.Task|Task} will be + * returned. + * + * By default response_view is {@link protos.google.cloud.tasks.v2.Task.View.BASIC|BASIC}; not all + * information is retrieved by default because some data, such as + * payloads, might be desirable to return only when needed because + * of its large size or because of the sensitivity of data that it + * contains. + * + * Authorization for {@link protos.google.cloud.tasks.v2.Task.View.FULL|FULL} requires + * `cloudtasks.tasks.fullView` [Google IAM](https://cloud.google.com/iam/) + * permission on the {@link protos.google.cloud.tasks.v2.Task|Task} resource. + * @param {number} request.pageSize + * Maximum page size. + * + * Fewer tasks than requested might be returned, even if more tasks exist; use + * {@link protos.google.cloud.tasks.v2.ListTasksResponse.next_page_token|next_page_token} in the response to + * determine if more tasks exist. + * + * The maximum page size is 1000. If unspecified, the page size will be the + * maximum. + * @param {string} request.pageToken + * A token identifying the page of results to return. + * + * To request the first page results, page_token must be empty. To + * request the next page of results, page_token must be the value of + * {@link protos.google.cloud.tasks.v2.ListTasksResponse.next_page_token|next_page_token} returned + * from the previous call to {@link protos.google.cloud.tasks.v2.CloudTasks.ListTasks|ListTasks} + * method. + * + * The page token is valid for only 2 hours. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.cloud.tasks.v2.Task|Task}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v2/cloud_tasks.list_tasks.js + * region_tag:cloudtasks_v2_generated_CloudTasks_ListTasks_async + */ listTasksAsync( - request?: protos.google.cloud.tasks.v2.IListTasksRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.cloud.tasks.v2.IListTasksRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); const defaultCallSettings = this._defaults['listTasks']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listTasks iterate %j', request); return this.descriptors.page.listTasks.asyncIterate( this.innerApiCalls['listTasks'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } // -------------------- @@ -2465,7 +3004,7 @@ export class CloudTasksClient { * @param {string} queue * @returns {string} Resource name string. */ - queuePath(project:string,location:string,queue:string) { + queuePath(project: string, location: string, queue: string) { return this.pathTemplates.queuePathTemplate.render({ project: project, location: location, @@ -2515,7 +3054,7 @@ export class CloudTasksClient { * @param {string} task * @returns {string} Resource name string. */ - taskPath(project:string,location:string,queue:string,task:string) { + taskPath(project: string, location: string, queue: string, task: string) { return this.pathTemplates.taskPathTemplate.render({ project: project, location: location, @@ -2576,7 +3115,7 @@ export class CloudTasksClient { */ close(): Promise { if (this.cloudTasksStub && !this._terminated) { - return this.cloudTasksStub.then(stub => { + return this.cloudTasksStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -2584,4 +3123,4 @@ export class CloudTasksClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/core/generator/gapic-generator-typescript/baselines/tasks-esm/esm/src/v2/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/tasks-esm/esm/src/v2/index.ts.baseline index 9500073e7175..90d3c82528c5 100644 --- a/core/generator/gapic-generator-typescript/baselines/tasks-esm/esm/src/v2/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/tasks-esm/esm/src/v2/index.ts.baseline @@ -16,4 +16,4 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -export {CloudTasksClient} from './cloud_tasks_client.js'; +export { CloudTasksClient } from './cloud_tasks_client.js'; diff --git a/core/generator/gapic-generator-typescript/baselines/tasks-esm/esm/system-test/fixtures/sample/src/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/tasks-esm/esm/system-test/fixtures/sample/src/index.ts.baseline index ec89e07d98c8..5c9760035511 100644 --- a/core/generator/gapic-generator-typescript/baselines/tasks-esm/esm/system-test/fixtures/sample/src/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/tasks-esm/esm/system-test/fixtures/sample/src/index.ts.baseline @@ -17,7 +17,7 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -import {CloudTasksClient} from 'tasks'; +import { CloudTasksClient } from 'tasks'; // check that the client class type name can be used function doStuffWithCloudTasksClient(client: CloudTasksClient) { diff --git a/core/generator/gapic-generator-typescript/baselines/tasks-esm/esm/system-test/install.ts.baseline b/core/generator/gapic-generator-typescript/baselines/tasks-esm/esm/system-test/install.ts.baseline index e079c4fa1101..d109fdd8c97f 100644 --- a/core/generator/gapic-generator-typescript/baselines/tasks-esm/esm/system-test/install.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/tasks-esm/esm/system-test/install.ts.baseline @@ -16,40 +16,45 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -import {packNTest} from 'pack-n-play'; -import {readFileSync} from 'fs'; -import {describe, it} from 'mocha'; +import { packNTest } from 'pack-n-play'; +import { readFileSync } from 'fs'; +import { describe, it } from 'mocha'; describe('📦 pack-n-play test', () => { - it('TypeScript', async function() { + it('TypeScript', async function () { this.timeout(300000); await packNTest({ packageDir: process.cwd(), sample: { description: 'TypeScript user can use the type definitions', - ts: readFileSync('./esm/system-test/fixtures/sample/src/index.ts').toString() - } + ts: readFileSync( + './esm/system-test/fixtures/sample/src/index.ts', + ).toString(), + }, }); }); - it('ESM module', async function() { + it('ESM module', async function () { this.timeout(300000); await packNTest({ sample: { description: 'Should be able to import using ESM', - esm: readFileSync('./esm/system-test/fixtures/sample/src/index.js').toString(), + esm: readFileSync( + './esm/system-test/fixtures/sample/src/index.js', + ).toString(), }, }); }); - it('CJS module', async function() { + it('CJS module', async function () { this.timeout(300000); await packNTest({ sample: { description: 'Should be able to import using CJS', - cjs: readFileSync('./esm/system-test/fixtures/sample/src/index.cjs').toString(), + cjs: readFileSync( + './esm/system-test/fixtures/sample/src/index.cjs', + ).toString(), }, }); }); - }); diff --git a/core/generator/gapic-generator-typescript/baselines/tasks-esm/esm/test/gapic_cloud_tasks_v2.ts.baseline b/core/generator/gapic-generator-typescript/baselines/tasks-esm/esm/test/gapic_cloud_tasks_v2.ts.baseline index c5117b2279a0..2bf5545702ed 100644 --- a/core/generator/gapic-generator-typescript/baselines/tasks-esm/esm/test/gapic_cloud_tasks_v2.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/tasks-esm/esm/test/gapic_cloud_tasks_v2.ts.baseline @@ -20,16 +20,16 @@ import * as protos from '../../protos/protos.js'; import assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as cloudtasksModule from '../src/index.js'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; -import {protobuf} from 'google-gax'; +import { protobuf } from 'google-gax'; import fs from 'fs'; import path from 'path'; -import {fileURLToPath} from 'url'; +import { fileURLToPath } from 'url'; // @ts-ignore const dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -37,2343 +37,2875 @@ const dirname = path.dirname(fileURLToPath(import.meta.url)); // to fill in default values for request objects const root = protobuf.Root.fromJSON( JSON.parse( - fs.readFileSync(path.join(dirname, '..', '..', 'protos/protos.json'), 'utf8') - )) + fs.readFileSync( + path.join(dirname, '..', '..', 'protos/protos.json'), + 'utf8', + ), + ), +); // eslint-disable-next-line @typescript-eslint/no-unused-vars function getTypeDefaultValue(typeName: string, fields: string[]) { - let type = root.lookupType(typeName) as protobuf.Type; - for (const field of fields.slice(0, -1)) { - type = type?.fields[field]?.resolvedType as protobuf.Type; - } - return type?.fields[fields[fields.length - 1]]?.defaultValue ?? null; + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type?.fields[field]?.resolvedType as protobuf.Type; + } + return type?.fields[fields[fields.length - 1]]?.defaultValue ?? null; } function generateSampleMessage(instance: T) { - const filledObject = (instance.constructor as typeof protobuf.Message) - .toObject(instance as protobuf.Message, {defaults: true}); - return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, { defaults: true }); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; } function stubSimpleCall(response?: ResponseType, error?: Error) { - return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); } -function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { - return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +function stubSimpleCallWithCallback( + response?: ResponseType, + error?: Error, +) { + return error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); } -function stubPageStreamingCall(responses?: ResponseType[], error?: Error) { - const pagingStub = sinon.stub(); - if (responses) { - for (let i = 0; i < responses.length; ++i) { - pagingStub.onCall(i).callsArgWith(2, null, responses[i]); - } +function stubPageStreamingCall( + responses?: ResponseType[], + error?: Error, +) { + const pagingStub = sinon.stub(); + if (responses) { + for (let i = 0; i < responses.length; ++i) { + pagingStub.onCall(i).callsArgWith(2, null, responses[i]); } - const transformStub = error ? sinon.stub().callsArgWith(2, error) : pagingStub; - const mockStream = new PassThrough({ - objectMode: true, - transform: transformStub, - }); - // trigger as many responses as needed - if (responses) { - for (let i = 0; i < responses.length; ++i) { - setImmediate(() => { mockStream.write({}); }); - } - setImmediate(() => { mockStream.end(); }); - } else { - setImmediate(() => { mockStream.write({}); }); - setImmediate(() => { mockStream.end(); }); + } + const transformStub = error + ? sinon.stub().callsArgWith(2, error) + : pagingStub; + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + // trigger as many responses as needed + if (responses) { + for (let i = 0; i < responses.length; ++i) { + setImmediate(() => { + mockStream.write({}); + }); } - return sinon.stub().returns(mockStream); + setImmediate(() => { + mockStream.end(); + }); + } else { + setImmediate(() => { + mockStream.write({}); + }); + setImmediate(() => { + mockStream.end(); + }); + } + return sinon.stub().returns(mockStream); } -function stubAsyncIterationCall(responses?: ResponseType[], error?: Error) { - let counter = 0; - const asyncIterable = { - [Symbol.asyncIterator]() { - return { - async next() { - if (error) { - return Promise.reject(error); - } - if (counter >= responses!.length) { - return Promise.resolve({done: true, value: undefined}); - } - return Promise.resolve({done: false, value: responses![counter++]}); - } - }; - } - }; - return sinon.stub().returns(asyncIterable); +function stubAsyncIterationCall( + responses?: ResponseType[], + error?: Error, +) { + let counter = 0; + const asyncIterable = { + [Symbol.asyncIterator]() { + return { + async next() { + if (error) { + return Promise.reject(error); + } + if (counter >= responses!.length) { + return Promise.resolve({ done: true, value: undefined }); + } + return Promise.resolve({ done: false, value: responses![counter++] }); + }, + }; + }, + }; + return sinon.stub().returns(asyncIterable); } describe('v2.CloudTasksClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new cloudtasksModule.v2.CloudTasksClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'cloudtasks.googleapis.com'); - }); - - it('has universeDomain', () => { - const client = new cloudtasksModule.v2.CloudTasksClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); - - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - it('throws DeprecationWarning if static servicePath is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const servicePath = cloudtasksModule.v2.CloudTasksClient.servicePath; - assert.strictEqual(servicePath, 'cloudtasks.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = cloudtasksModule.v2.CloudTasksClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'cloudtasks.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new cloudtasksModule.v2.CloudTasksClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'cloudtasks.example.com'); - }); - - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new cloudtasksModule.v2.CloudTasksClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'cloudtasks.example.com'); - }); - - if (typeof process === 'object' && 'env' in process) { - describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { - it('sets apiEndpoint from environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new cloudtasksModule.v2.CloudTasksClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'cloudtasks.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - - it('value configured in code has priority over environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new cloudtasksModule.v2.CloudTasksClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'cloudtasks.configured.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { new cloudtasksModule.v2.CloudTasksClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); - - it('has port', () => { - const port = cloudtasksModule.v2.CloudTasksClient.port; - assert(port); - assert(typeof port === 'number'); - }); - - it('should create a client with no option', () => { - const client = new cloudtasksModule.v2.CloudTasksClient(); - assert(client); - }); - - it('should create a client with gRPC fallback', () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - fallback: true, - }); - assert(client); - }); - - it('has initialize method and supports deferred initialization', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.cloudTasksStub, undefined); - await client.initialize(); - assert(client.cloudTasksStub); - }); - - it('has close method for the initialized client', done => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.cloudTasksStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); - - it('has close method for the non-initialized client', done => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.cloudTasksStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); - - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); - }); - - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId((err?: Error|null, projectId?: string|null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } - }); - }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new cloudtasksModule.v2.CloudTasksClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'cloudtasks.googleapis.com'); }); - describe('getQueue', () => { - it('invokes getQueue without error', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.tasks.v2.GetQueueRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.tasks.v2.GetQueueRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.tasks.v2.Queue() - ); - client.innerApiCalls.getQueue = stubSimpleCall(expectedResponse); - const [response] = await client.getQueue(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getQueue as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getQueue as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getQueue without error using callback', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.tasks.v2.GetQueueRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.tasks.v2.GetQueueRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.tasks.v2.Queue() - ); - client.innerApiCalls.getQueue = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getQueue( - request, - (err?: Error|null, result?: protos.google.cloud.tasks.v2.IQueue|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getQueue as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getQueue as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has universeDomain', () => { + const client = new cloudtasksModule.v2.CloudTasksClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - it('invokes getQueue with error', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.tasks.v2.GetQueueRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.tasks.v2.GetQueueRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getQueue = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getQueue(request), expectedError); - const actualRequest = (client.innerApiCalls.getQueue as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getQueue as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = cloudtasksModule.v2.CloudTasksClient.servicePath; + assert.strictEqual(servicePath, 'cloudtasks.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = cloudtasksModule.v2.CloudTasksClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'cloudtasks.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + universeDomain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'cloudtasks.example.com'); + }); - it('invokes getQueue with closed client', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.tasks.v2.GetQueueRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.tasks.v2.GetQueueRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getQueue(request), expectedError); - }); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + universe_domain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'cloudtasks.example.com'); }); - describe('createQueue', () => { - it('invokes createQueue without error', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.tasks.v2.CreateQueueRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.tasks.v2.CreateQueueRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.tasks.v2.Queue() - ); - client.innerApiCalls.createQueue = stubSimpleCall(expectedResponse); - const [response] = await client.createQueue(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createQueue as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createQueue as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + if (typeof process === 'object' && 'env' in process) { + describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { + it('sets apiEndpoint from environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new cloudtasksModule.v2.CloudTasksClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'cloudtasks.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } + }); + + it('value configured in code has priority over environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new cloudtasksModule.v2.CloudTasksClient({ + universeDomain: 'configured.example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'cloudtasks.configured.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } + }); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new cloudtasksModule.v2.CloudTasksClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); + }); - it('invokes createQueue without error using callback', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.tasks.v2.CreateQueueRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.tasks.v2.CreateQueueRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.tasks.v2.Queue() - ); - client.innerApiCalls.createQueue = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createQueue( - request, - (err?: Error|null, result?: protos.google.cloud.tasks.v2.IQueue|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createQueue as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createQueue as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has port', () => { + const port = cloudtasksModule.v2.CloudTasksClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('invokes createQueue with error', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.tasks.v2.CreateQueueRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.tasks.v2.CreateQueueRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createQueue = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createQueue(request), expectedError); - const actualRequest = (client.innerApiCalls.createQueue as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createQueue as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('should create a client with no option', () => { + const client = new cloudtasksModule.v2.CloudTasksClient(); + assert(client); + }); - it('invokes createQueue with closed client', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.tasks.v2.CreateQueueRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.tasks.v2.CreateQueueRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createQueue(request), expectedError); - }); + it('should create a client with gRPC fallback', () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + fallback: true, + }); + assert(client); }); - describe('updateQueue', () => { - it('invokes updateQueue without error', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.tasks.v2.UpdateQueueRequest() - ); - request.queue ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.tasks.v2.UpdateQueueRequest', ['queue', 'name']); - request.queue.name = defaultValue1; - const expectedHeaderRequestParams = `queue.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.tasks.v2.Queue() - ); - client.innerApiCalls.updateQueue = stubSimpleCall(expectedResponse); - const [response] = await client.updateQueue(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateQueue as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateQueue as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has initialize method and supports deferred initialization', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.cloudTasksStub, undefined); + await client.initialize(); + assert(client.cloudTasksStub); + }); - it('invokes updateQueue without error using callback', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.tasks.v2.UpdateQueueRequest() - ); - request.queue ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.tasks.v2.UpdateQueueRequest', ['queue', 'name']); - request.queue.name = defaultValue1; - const expectedHeaderRequestParams = `queue.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.tasks.v2.Queue() - ); - client.innerApiCalls.updateQueue = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateQueue( - request, - (err?: Error|null, result?: protos.google.cloud.tasks.v2.IQueue|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateQueue as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateQueue as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('has close method for the initialized client', (done) => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.cloudTasksStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes updateQueue with error', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.tasks.v2.UpdateQueueRequest() - ); - request.queue ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.tasks.v2.UpdateQueueRequest', ['queue', 'name']); - request.queue.name = defaultValue1; - const expectedHeaderRequestParams = `queue.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateQueue = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateQueue(request), expectedError); - const actualRequest = (client.innerApiCalls.updateQueue as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateQueue as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('has close method for the non-initialized client', (done) => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.cloudTasksStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes updateQueue with closed client', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.tasks.v2.UpdateQueueRequest() - ); - request.queue ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.tasks.v2.UpdateQueueRequest', ['queue', 'name']); - request.queue.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateQueue(request), expectedError); - }); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); }); - describe('deleteQueue', () => { - it('invokes deleteQueue without error', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.tasks.v2.DeleteQueueRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.tasks.v2.DeleteQueueRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteQueue = stubSimpleCall(expectedResponse); - const [response] = await client.deleteQueue(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteQueue as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteQueue as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } + }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + }); + + describe('getQueue', () => { + it('invokes getQueue without error', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.tasks.v2.GetQueueRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.tasks.v2.GetQueueRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.tasks.v2.Queue(), + ); + client.innerApiCalls.getQueue = stubSimpleCall(expectedResponse); + const [response] = await client.getQueue(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getQueue as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getQueue as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteQueue without error using callback', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.tasks.v2.DeleteQueueRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.tasks.v2.DeleteQueueRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteQueue = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteQueue( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteQueue as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteQueue as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getQueue without error using callback', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.tasks.v2.GetQueueRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.tasks.v2.GetQueueRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.tasks.v2.Queue(), + ); + client.innerApiCalls.getQueue = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getQueue( + request, + ( + err?: Error | null, + result?: protos.google.cloud.tasks.v2.IQueue | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getQueue as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getQueue as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteQueue with error', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.tasks.v2.DeleteQueueRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.tasks.v2.DeleteQueueRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteQueue = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteQueue(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteQueue as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteQueue as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getQueue with error', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.tasks.v2.GetQueueRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.tasks.v2.GetQueueRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getQueue = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.getQueue(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getQueue as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getQueue as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteQueue with closed client', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.tasks.v2.DeleteQueueRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.tasks.v2.DeleteQueueRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteQueue(request), expectedError); - }); + it('invokes getQueue with closed client', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.tasks.v2.GetQueueRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.tasks.v2.GetQueueRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getQueue(request), expectedError); + }); + }); + + describe('createQueue', () => { + it('invokes createQueue without error', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.tasks.v2.CreateQueueRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.tasks.v2.CreateQueueRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.tasks.v2.Queue(), + ); + client.innerApiCalls.createQueue = stubSimpleCall(expectedResponse); + const [response] = await client.createQueue(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createQueue as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createQueue as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('purgeQueue', () => { - it('invokes purgeQueue without error', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.tasks.v2.PurgeQueueRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.tasks.v2.PurgeQueueRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.tasks.v2.Queue() - ); - client.innerApiCalls.purgeQueue = stubSimpleCall(expectedResponse); - const [response] = await client.purgeQueue(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.purgeQueue as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.purgeQueue as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createQueue without error using callback', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.tasks.v2.CreateQueueRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.tasks.v2.CreateQueueRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.tasks.v2.Queue(), + ); + client.innerApiCalls.createQueue = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createQueue( + request, + ( + err?: Error | null, + result?: protos.google.cloud.tasks.v2.IQueue | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createQueue as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createQueue as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes purgeQueue without error using callback', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.tasks.v2.PurgeQueueRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.tasks.v2.PurgeQueueRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.tasks.v2.Queue() - ); - client.innerApiCalls.purgeQueue = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.purgeQueue( - request, - (err?: Error|null, result?: protos.google.cloud.tasks.v2.IQueue|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.purgeQueue as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.purgeQueue as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createQueue with error', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.tasks.v2.CreateQueueRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.tasks.v2.CreateQueueRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createQueue = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.createQueue(request), expectedError); + const actualRequest = ( + client.innerApiCalls.createQueue as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createQueue as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes purgeQueue with error', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.tasks.v2.PurgeQueueRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.tasks.v2.PurgeQueueRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.purgeQueue = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.purgeQueue(request), expectedError); - const actualRequest = (client.innerApiCalls.purgeQueue as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.purgeQueue as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createQueue with closed client', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.tasks.v2.CreateQueueRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.tasks.v2.CreateQueueRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.createQueue(request), expectedError); + }); + }); + + describe('updateQueue', () => { + it('invokes updateQueue without error', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.tasks.v2.UpdateQueueRequest(), + ); + request.queue ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.tasks.v2.UpdateQueueRequest', + ['queue', 'name'], + ); + request.queue.name = defaultValue1; + const expectedHeaderRequestParams = `queue.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.tasks.v2.Queue(), + ); + client.innerApiCalls.updateQueue = stubSimpleCall(expectedResponse); + const [response] = await client.updateQueue(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateQueue as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateQueue as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes purgeQueue with closed client', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.tasks.v2.PurgeQueueRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.tasks.v2.PurgeQueueRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.purgeQueue(request), expectedError); - }); + it('invokes updateQueue without error using callback', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.tasks.v2.UpdateQueueRequest(), + ); + request.queue ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.tasks.v2.UpdateQueueRequest', + ['queue', 'name'], + ); + request.queue.name = defaultValue1; + const expectedHeaderRequestParams = `queue.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.tasks.v2.Queue(), + ); + client.innerApiCalls.updateQueue = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateQueue( + request, + ( + err?: Error | null, + result?: protos.google.cloud.tasks.v2.IQueue | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateQueue as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateQueue as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('pauseQueue', () => { - it('invokes pauseQueue without error', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.tasks.v2.PauseQueueRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.tasks.v2.PauseQueueRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.tasks.v2.Queue() - ); - client.innerApiCalls.pauseQueue = stubSimpleCall(expectedResponse); - const [response] = await client.pauseQueue(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.pauseQueue as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.pauseQueue as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateQueue with error', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.tasks.v2.UpdateQueueRequest(), + ); + request.queue ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.tasks.v2.UpdateQueueRequest', + ['queue', 'name'], + ); + request.queue.name = defaultValue1; + const expectedHeaderRequestParams = `queue.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateQueue = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.updateQueue(request), expectedError); + const actualRequest = ( + client.innerApiCalls.updateQueue as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateQueue as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes pauseQueue without error using callback', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.tasks.v2.PauseQueueRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.tasks.v2.PauseQueueRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.tasks.v2.Queue() - ); - client.innerApiCalls.pauseQueue = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.pauseQueue( - request, - (err?: Error|null, result?: protos.google.cloud.tasks.v2.IQueue|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.pauseQueue as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.pauseQueue as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateQueue with closed client', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.tasks.v2.UpdateQueueRequest(), + ); + request.queue ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.tasks.v2.UpdateQueueRequest', + ['queue', 'name'], + ); + request.queue.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.updateQueue(request), expectedError); + }); + }); + + describe('deleteQueue', () => { + it('invokes deleteQueue without error', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.tasks.v2.DeleteQueueRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.tasks.v2.DeleteQueueRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteQueue = stubSimpleCall(expectedResponse); + const [response] = await client.deleteQueue(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteQueue as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteQueue as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes pauseQueue with error', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.tasks.v2.PauseQueueRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.tasks.v2.PauseQueueRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.pauseQueue = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.pauseQueue(request), expectedError); - const actualRequest = (client.innerApiCalls.pauseQueue as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.pauseQueue as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteQueue without error using callback', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.tasks.v2.DeleteQueueRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.tasks.v2.DeleteQueueRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteQueue = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteQueue( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteQueue as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteQueue as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes pauseQueue with closed client', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.tasks.v2.PauseQueueRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.tasks.v2.PauseQueueRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.pauseQueue(request), expectedError); - }); + it('invokes deleteQueue with error', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.tasks.v2.DeleteQueueRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.tasks.v2.DeleteQueueRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteQueue = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.deleteQueue(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteQueue as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteQueue as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('resumeQueue', () => { - it('invokes resumeQueue without error', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.tasks.v2.ResumeQueueRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.tasks.v2.ResumeQueueRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.tasks.v2.Queue() - ); - client.innerApiCalls.resumeQueue = stubSimpleCall(expectedResponse); - const [response] = await client.resumeQueue(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.resumeQueue as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.resumeQueue as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteQueue with closed client', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.tasks.v2.DeleteQueueRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.tasks.v2.DeleteQueueRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.deleteQueue(request), expectedError); + }); + }); + + describe('purgeQueue', () => { + it('invokes purgeQueue without error', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.tasks.v2.PurgeQueueRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.tasks.v2.PurgeQueueRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.tasks.v2.Queue(), + ); + client.innerApiCalls.purgeQueue = stubSimpleCall(expectedResponse); + const [response] = await client.purgeQueue(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.purgeQueue as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.purgeQueue as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes resumeQueue without error using callback', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.tasks.v2.ResumeQueueRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.tasks.v2.ResumeQueueRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.tasks.v2.Queue() - ); - client.innerApiCalls.resumeQueue = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.resumeQueue( - request, - (err?: Error|null, result?: protos.google.cloud.tasks.v2.IQueue|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.resumeQueue as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.resumeQueue as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes purgeQueue without error using callback', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.tasks.v2.PurgeQueueRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.tasks.v2.PurgeQueueRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.tasks.v2.Queue(), + ); + client.innerApiCalls.purgeQueue = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.purgeQueue( + request, + ( + err?: Error | null, + result?: protos.google.cloud.tasks.v2.IQueue | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.purgeQueue as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.purgeQueue as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes resumeQueue with error', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.tasks.v2.ResumeQueueRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.tasks.v2.ResumeQueueRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.resumeQueue = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.resumeQueue(request), expectedError); - const actualRequest = (client.innerApiCalls.resumeQueue as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.resumeQueue as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes purgeQueue with error', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.tasks.v2.PurgeQueueRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.tasks.v2.PurgeQueueRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.purgeQueue = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.purgeQueue(request), expectedError); + const actualRequest = ( + client.innerApiCalls.purgeQueue as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.purgeQueue as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes resumeQueue with closed client', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.tasks.v2.ResumeQueueRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.tasks.v2.ResumeQueueRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.resumeQueue(request), expectedError); - }); + it('invokes purgeQueue with closed client', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.tasks.v2.PurgeQueueRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.tasks.v2.PurgeQueueRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.purgeQueue(request), expectedError); + }); + }); + + describe('pauseQueue', () => { + it('invokes pauseQueue without error', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.tasks.v2.PauseQueueRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.tasks.v2.PauseQueueRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.tasks.v2.Queue(), + ); + client.innerApiCalls.pauseQueue = stubSimpleCall(expectedResponse); + const [response] = await client.pauseQueue(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.pauseQueue as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.pauseQueue as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('getIamPolicy', () => { - it('invokes getIamPolicy without error', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.iam.v1.GetIamPolicyRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.iam.v1.GetIamPolicyRequest', ['resource']); - request.resource = defaultValue1; - const expectedHeaderRequestParams = `resource=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.iam.v1.Policy() - ); - client.innerApiCalls.getIamPolicy = stubSimpleCall(expectedResponse); - const [response] = await client.getIamPolicy(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getIamPolicy as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getIamPolicy as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes pauseQueue without error using callback', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.tasks.v2.PauseQueueRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.tasks.v2.PauseQueueRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.tasks.v2.Queue(), + ); + client.innerApiCalls.pauseQueue = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.pauseQueue( + request, + ( + err?: Error | null, + result?: protos.google.cloud.tasks.v2.IQueue | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.pauseQueue as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.pauseQueue as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getIamPolicy without error using callback', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.iam.v1.GetIamPolicyRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.iam.v1.GetIamPolicyRequest', ['resource']); - request.resource = defaultValue1; - const expectedHeaderRequestParams = `resource=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.iam.v1.Policy() - ); - client.innerApiCalls.getIamPolicy = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getIamPolicy( - request, - (err?: Error|null, result?: protos.google.iam.v1.IPolicy|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getIamPolicy as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getIamPolicy as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes pauseQueue with error', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.tasks.v2.PauseQueueRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.tasks.v2.PauseQueueRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.pauseQueue = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.pauseQueue(request), expectedError); + const actualRequest = ( + client.innerApiCalls.pauseQueue as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.pauseQueue as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getIamPolicy with error', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.iam.v1.GetIamPolicyRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.iam.v1.GetIamPolicyRequest', ['resource']); - request.resource = defaultValue1; - const expectedHeaderRequestParams = `resource=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getIamPolicy = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getIamPolicy(request), expectedError); - const actualRequest = (client.innerApiCalls.getIamPolicy as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getIamPolicy as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes pauseQueue with closed client', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.tasks.v2.PauseQueueRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.tasks.v2.PauseQueueRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.pauseQueue(request), expectedError); + }); + }); + + describe('resumeQueue', () => { + it('invokes resumeQueue without error', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.tasks.v2.ResumeQueueRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.tasks.v2.ResumeQueueRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.tasks.v2.Queue(), + ); + client.innerApiCalls.resumeQueue = stubSimpleCall(expectedResponse); + const [response] = await client.resumeQueue(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.resumeQueue as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.resumeQueue as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getIamPolicy with closed client', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.iam.v1.GetIamPolicyRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.iam.v1.GetIamPolicyRequest', ['resource']); - request.resource = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getIamPolicy(request), expectedError); - }); + it('invokes resumeQueue without error using callback', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.tasks.v2.ResumeQueueRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.tasks.v2.ResumeQueueRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.tasks.v2.Queue(), + ); + client.innerApiCalls.resumeQueue = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.resumeQueue( + request, + ( + err?: Error | null, + result?: protos.google.cloud.tasks.v2.IQueue | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.resumeQueue as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.resumeQueue as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('setIamPolicy', () => { - it('invokes setIamPolicy without error', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.iam.v1.SetIamPolicyRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.iam.v1.SetIamPolicyRequest', ['resource']); - request.resource = defaultValue1; - const expectedHeaderRequestParams = `resource=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.iam.v1.Policy() - ); - client.innerApiCalls.setIamPolicy = stubSimpleCall(expectedResponse); - const [response] = await client.setIamPolicy(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.setIamPolicy as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.setIamPolicy as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes resumeQueue with error', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.tasks.v2.ResumeQueueRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.tasks.v2.ResumeQueueRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.resumeQueue = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.resumeQueue(request), expectedError); + const actualRequest = ( + client.innerApiCalls.resumeQueue as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.resumeQueue as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes setIamPolicy without error using callback', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.iam.v1.SetIamPolicyRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.iam.v1.SetIamPolicyRequest', ['resource']); - request.resource = defaultValue1; - const expectedHeaderRequestParams = `resource=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.iam.v1.Policy() - ); - client.innerApiCalls.setIamPolicy = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.setIamPolicy( - request, - (err?: Error|null, result?: protos.google.iam.v1.IPolicy|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.setIamPolicy as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.setIamPolicy as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes resumeQueue with closed client', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.tasks.v2.ResumeQueueRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.tasks.v2.ResumeQueueRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.resumeQueue(request), expectedError); + }); + }); + + describe('getIamPolicy', () => { + it('invokes getIamPolicy without error', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.iam.v1.GetIamPolicyRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.iam.v1.GetIamPolicyRequest', + ['resource'], + ); + request.resource = defaultValue1; + const expectedHeaderRequestParams = `resource=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.iam.v1.Policy(), + ); + client.innerApiCalls.getIamPolicy = stubSimpleCall(expectedResponse); + const [response] = await client.getIamPolicy(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getIamPolicy as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getIamPolicy as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes setIamPolicy with error', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.iam.v1.SetIamPolicyRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.iam.v1.SetIamPolicyRequest', ['resource']); - request.resource = defaultValue1; - const expectedHeaderRequestParams = `resource=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.setIamPolicy = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.setIamPolicy(request), expectedError); - const actualRequest = (client.innerApiCalls.setIamPolicy as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.setIamPolicy as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getIamPolicy without error using callback', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.iam.v1.GetIamPolicyRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.iam.v1.GetIamPolicyRequest', + ['resource'], + ); + request.resource = defaultValue1; + const expectedHeaderRequestParams = `resource=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.iam.v1.Policy(), + ); + client.innerApiCalls.getIamPolicy = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getIamPolicy( + request, + ( + err?: Error | null, + result?: protos.google.iam.v1.IPolicy | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getIamPolicy as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getIamPolicy as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes setIamPolicy with closed client', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.iam.v1.SetIamPolicyRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.iam.v1.SetIamPolicyRequest', ['resource']); - request.resource = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.setIamPolicy(request), expectedError); - }); + it('invokes getIamPolicy with error', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.iam.v1.GetIamPolicyRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.iam.v1.GetIamPolicyRequest', + ['resource'], + ); + request.resource = defaultValue1; + const expectedHeaderRequestParams = `resource=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getIamPolicy = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getIamPolicy(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getIamPolicy as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getIamPolicy as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('testIamPermissions', () => { - it('invokes testIamPermissions without error', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.iam.v1.TestIamPermissionsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.iam.v1.TestIamPermissionsRequest', ['resource']); - request.resource = defaultValue1; - const expectedHeaderRequestParams = `resource=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.iam.v1.TestIamPermissionsResponse() - ); - client.innerApiCalls.testIamPermissions = stubSimpleCall(expectedResponse); - const [response] = await client.testIamPermissions(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.testIamPermissions as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.testIamPermissions as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getIamPolicy with closed client', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.iam.v1.GetIamPolicyRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.iam.v1.GetIamPolicyRequest', + ['resource'], + ); + request.resource = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getIamPolicy(request), expectedError); + }); + }); + + describe('setIamPolicy', () => { + it('invokes setIamPolicy without error', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.iam.v1.SetIamPolicyRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.iam.v1.SetIamPolicyRequest', + ['resource'], + ); + request.resource = defaultValue1; + const expectedHeaderRequestParams = `resource=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.iam.v1.Policy(), + ); + client.innerApiCalls.setIamPolicy = stubSimpleCall(expectedResponse); + const [response] = await client.setIamPolicy(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.setIamPolicy as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.setIamPolicy as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes testIamPermissions without error using callback', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.iam.v1.TestIamPermissionsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.iam.v1.TestIamPermissionsRequest', ['resource']); - request.resource = defaultValue1; - const expectedHeaderRequestParams = `resource=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.iam.v1.TestIamPermissionsResponse() - ); - client.innerApiCalls.testIamPermissions = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.testIamPermissions( - request, - (err?: Error|null, result?: protos.google.iam.v1.ITestIamPermissionsResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.testIamPermissions as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.testIamPermissions as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes setIamPolicy without error using callback', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.iam.v1.SetIamPolicyRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.iam.v1.SetIamPolicyRequest', + ['resource'], + ); + request.resource = defaultValue1; + const expectedHeaderRequestParams = `resource=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.iam.v1.Policy(), + ); + client.innerApiCalls.setIamPolicy = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.setIamPolicy( + request, + ( + err?: Error | null, + result?: protos.google.iam.v1.IPolicy | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.setIamPolicy as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.setIamPolicy as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes testIamPermissions with error', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.iam.v1.TestIamPermissionsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.iam.v1.TestIamPermissionsRequest', ['resource']); - request.resource = defaultValue1; - const expectedHeaderRequestParams = `resource=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.testIamPermissions = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.testIamPermissions(request), expectedError); - const actualRequest = (client.innerApiCalls.testIamPermissions as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.testIamPermissions as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes setIamPolicy with error', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.iam.v1.SetIamPolicyRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.iam.v1.SetIamPolicyRequest', + ['resource'], + ); + request.resource = defaultValue1; + const expectedHeaderRequestParams = `resource=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.setIamPolicy = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.setIamPolicy(request), expectedError); + const actualRequest = ( + client.innerApiCalls.setIamPolicy as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.setIamPolicy as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes testIamPermissions with closed client', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.iam.v1.TestIamPermissionsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.iam.v1.TestIamPermissionsRequest', ['resource']); - request.resource = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.testIamPermissions(request), expectedError); - }); + it('invokes setIamPolicy with closed client', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.iam.v1.SetIamPolicyRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.iam.v1.SetIamPolicyRequest', + ['resource'], + ); + request.resource = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.setIamPolicy(request), expectedError); + }); + }); + + describe('testIamPermissions', () => { + it('invokes testIamPermissions without error', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.iam.v1.TestIamPermissionsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.iam.v1.TestIamPermissionsRequest', + ['resource'], + ); + request.resource = defaultValue1; + const expectedHeaderRequestParams = `resource=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.iam.v1.TestIamPermissionsResponse(), + ); + client.innerApiCalls.testIamPermissions = + stubSimpleCall(expectedResponse); + const [response] = await client.testIamPermissions(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.testIamPermissions as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.testIamPermissions as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('getTask', () => { - it('invokes getTask without error', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.tasks.v2.GetTaskRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.tasks.v2.GetTaskRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.tasks.v2.Task() - ); - client.innerApiCalls.getTask = stubSimpleCall(expectedResponse); - const [response] = await client.getTask(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getTask as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getTask as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes testIamPermissions without error using callback', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.iam.v1.TestIamPermissionsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.iam.v1.TestIamPermissionsRequest', + ['resource'], + ); + request.resource = defaultValue1; + const expectedHeaderRequestParams = `resource=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.iam.v1.TestIamPermissionsResponse(), + ); + client.innerApiCalls.testIamPermissions = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.testIamPermissions( + request, + ( + err?: Error | null, + result?: protos.google.iam.v1.ITestIamPermissionsResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.testIamPermissions as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.testIamPermissions as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getTask without error using callback', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.tasks.v2.GetTaskRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.tasks.v2.GetTaskRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.tasks.v2.Task() - ); - client.innerApiCalls.getTask = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getTask( - request, - (err?: Error|null, result?: protos.google.cloud.tasks.v2.ITask|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getTask as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getTask as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes testIamPermissions with error', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.iam.v1.TestIamPermissionsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.iam.v1.TestIamPermissionsRequest', + ['resource'], + ); + request.resource = defaultValue1; + const expectedHeaderRequestParams = `resource=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.testIamPermissions = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.testIamPermissions(request), expectedError); + const actualRequest = ( + client.innerApiCalls.testIamPermissions as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.testIamPermissions as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getTask with error', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.tasks.v2.GetTaskRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.tasks.v2.GetTaskRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getTask = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getTask(request), expectedError); - const actualRequest = (client.innerApiCalls.getTask as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getTask as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes testIamPermissions with closed client', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.iam.v1.TestIamPermissionsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.iam.v1.TestIamPermissionsRequest', + ['resource'], + ); + request.resource = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.testIamPermissions(request), expectedError); + }); + }); + + describe('getTask', () => { + it('invokes getTask without error', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.tasks.v2.GetTaskRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.tasks.v2.GetTaskRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.tasks.v2.Task(), + ); + client.innerApiCalls.getTask = stubSimpleCall(expectedResponse); + const [response] = await client.getTask(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.getTask as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getTask as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getTask with closed client', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.tasks.v2.GetTaskRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.tasks.v2.GetTaskRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getTask(request), expectedError); - }); + it('invokes getTask without error using callback', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.tasks.v2.GetTaskRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.tasks.v2.GetTaskRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.tasks.v2.Task(), + ); + client.innerApiCalls.getTask = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getTask( + request, + ( + err?: Error | null, + result?: protos.google.cloud.tasks.v2.ITask | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.getTask as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getTask as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('createTask', () => { - it('invokes createTask without error', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.tasks.v2.CreateTaskRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.tasks.v2.CreateTaskRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.tasks.v2.Task() - ); - client.innerApiCalls.createTask = stubSimpleCall(expectedResponse); - const [response] = await client.createTask(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createTask as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createTask as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getTask with error', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.tasks.v2.GetTaskRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.tasks.v2.GetTaskRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getTask = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.getTask(request), expectedError); + const actualRequest = (client.innerApiCalls.getTask as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getTask as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createTask without error using callback', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.tasks.v2.CreateTaskRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.tasks.v2.CreateTaskRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.tasks.v2.Task() - ); - client.innerApiCalls.createTask = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createTask( - request, - (err?: Error|null, result?: protos.google.cloud.tasks.v2.ITask|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createTask as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createTask as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getTask with closed client', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.tasks.v2.GetTaskRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.tasks.v2.GetTaskRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getTask(request), expectedError); + }); + }); + + describe('createTask', () => { + it('invokes createTask without error', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.tasks.v2.CreateTaskRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.tasks.v2.CreateTaskRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.tasks.v2.Task(), + ); + client.innerApiCalls.createTask = stubSimpleCall(expectedResponse); + const [response] = await client.createTask(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createTask as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createTask as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createTask with error', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.tasks.v2.CreateTaskRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.tasks.v2.CreateTaskRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createTask = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createTask(request), expectedError); - const actualRequest = (client.innerApiCalls.createTask as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createTask as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createTask without error using callback', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.tasks.v2.CreateTaskRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.tasks.v2.CreateTaskRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.tasks.v2.Task(), + ); + client.innerApiCalls.createTask = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createTask( + request, + ( + err?: Error | null, + result?: protos.google.cloud.tasks.v2.ITask | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createTask as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createTask as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createTask with closed client', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.tasks.v2.CreateTaskRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.tasks.v2.CreateTaskRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createTask(request), expectedError); - }); + it('invokes createTask with error', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.tasks.v2.CreateTaskRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.tasks.v2.CreateTaskRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createTask = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.createTask(request), expectedError); + const actualRequest = ( + client.innerApiCalls.createTask as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createTask as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('deleteTask', () => { - it('invokes deleteTask without error', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.tasks.v2.DeleteTaskRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.tasks.v2.DeleteTaskRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteTask = stubSimpleCall(expectedResponse); - const [response] = await client.deleteTask(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteTask as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteTask as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createTask with closed client', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.tasks.v2.CreateTaskRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.tasks.v2.CreateTaskRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.createTask(request), expectedError); + }); + }); + + describe('deleteTask', () => { + it('invokes deleteTask without error', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.tasks.v2.DeleteTaskRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.tasks.v2.DeleteTaskRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteTask = stubSimpleCall(expectedResponse); + const [response] = await client.deleteTask(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteTask as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteTask as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteTask without error using callback', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.tasks.v2.DeleteTaskRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.tasks.v2.DeleteTaskRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteTask = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteTask( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteTask as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteTask as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteTask without error using callback', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.tasks.v2.DeleteTaskRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.tasks.v2.DeleteTaskRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteTask = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteTask( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteTask as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteTask as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteTask with error', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.tasks.v2.DeleteTaskRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.tasks.v2.DeleteTaskRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteTask = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteTask(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteTask as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteTask as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteTask with error', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.tasks.v2.DeleteTaskRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.tasks.v2.DeleteTaskRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteTask = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.deleteTask(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteTask as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteTask as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteTask with closed client', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.tasks.v2.DeleteTaskRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.tasks.v2.DeleteTaskRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteTask(request), expectedError); - }); + it('invokes deleteTask with closed client', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.tasks.v2.DeleteTaskRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.tasks.v2.DeleteTaskRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.deleteTask(request), expectedError); + }); + }); + + describe('runTask', () => { + it('invokes runTask without error', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.tasks.v2.RunTaskRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.tasks.v2.RunTaskRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.tasks.v2.Task(), + ); + client.innerApiCalls.runTask = stubSimpleCall(expectedResponse); + const [response] = await client.runTask(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.runTask as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.runTask as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('runTask', () => { - it('invokes runTask without error', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.tasks.v2.RunTaskRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.tasks.v2.RunTaskRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.tasks.v2.Task() - ); - client.innerApiCalls.runTask = stubSimpleCall(expectedResponse); - const [response] = await client.runTask(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.runTask as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.runTask as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes runTask without error using callback', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.tasks.v2.RunTaskRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.tasks.v2.RunTaskRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.tasks.v2.Task(), + ); + client.innerApiCalls.runTask = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.runTask( + request, + ( + err?: Error | null, + result?: protos.google.cloud.tasks.v2.ITask | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.runTask as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.runTask as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes runTask without error using callback', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.tasks.v2.RunTaskRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.tasks.v2.RunTaskRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.tasks.v2.Task() - ); - client.innerApiCalls.runTask = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.runTask( - request, - (err?: Error|null, result?: protos.google.cloud.tasks.v2.ITask|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.runTask as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.runTask as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes runTask with error', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.tasks.v2.RunTaskRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.tasks.v2.RunTaskRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.runTask = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.runTask(request), expectedError); + const actualRequest = (client.innerApiCalls.runTask as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.runTask as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes runTask with error', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.tasks.v2.RunTaskRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.tasks.v2.RunTaskRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.runTask = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.runTask(request), expectedError); - const actualRequest = (client.innerApiCalls.runTask as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.runTask as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes runTask with closed client', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.tasks.v2.RunTaskRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.tasks.v2.RunTaskRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.runTask(request), expectedError); + }); + }); + + describe('listQueues', () => { + it('invokes listQueues without error', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.tasks.v2.ListQueuesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.tasks.v2.ListQueuesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.tasks.v2.Queue()), + generateSampleMessage(new protos.google.cloud.tasks.v2.Queue()), + generateSampleMessage(new protos.google.cloud.tasks.v2.Queue()), + ]; + client.innerApiCalls.listQueues = stubSimpleCall(expectedResponse); + const [response] = await client.listQueues(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listQueues as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listQueues as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes runTask with closed client', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.tasks.v2.RunTaskRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.tasks.v2.RunTaskRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.runTask(request), expectedError); - }); + it('invokes listQueues without error using callback', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.tasks.v2.ListQueuesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.tasks.v2.ListQueuesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.tasks.v2.Queue()), + generateSampleMessage(new protos.google.cloud.tasks.v2.Queue()), + generateSampleMessage(new protos.google.cloud.tasks.v2.Queue()), + ]; + client.innerApiCalls.listQueues = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listQueues( + request, + ( + err?: Error | null, + result?: protos.google.cloud.tasks.v2.IQueue[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listQueues as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listQueues as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('listQueues', () => { - it('invokes listQueues without error', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.tasks.v2.ListQueuesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.tasks.v2.ListQueuesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.tasks.v2.Queue()), - generateSampleMessage(new protos.google.cloud.tasks.v2.Queue()), - generateSampleMessage(new protos.google.cloud.tasks.v2.Queue()), - ]; - client.innerApiCalls.listQueues = stubSimpleCall(expectedResponse); - const [response] = await client.listQueues(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listQueues as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listQueues as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listQueues with error', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.tasks.v2.ListQueuesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.tasks.v2.ListQueuesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listQueues = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listQueues(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listQueues as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listQueues as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listQueues without error using callback', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.tasks.v2.ListQueuesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.tasks.v2.ListQueuesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.tasks.v2.Queue()), - generateSampleMessage(new protos.google.cloud.tasks.v2.Queue()), - generateSampleMessage(new protos.google.cloud.tasks.v2.Queue()), - ]; - client.innerApiCalls.listQueues = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listQueues( - request, - (err?: Error|null, result?: protos.google.cloud.tasks.v2.IQueue[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listQueues as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listQueues as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listQueuesStream without error', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.tasks.v2.ListQueuesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.tasks.v2.ListQueuesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.tasks.v2.Queue()), + generateSampleMessage(new protos.google.cloud.tasks.v2.Queue()), + generateSampleMessage(new protos.google.cloud.tasks.v2.Queue()), + ]; + client.descriptors.page.listQueues.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listQueuesStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.cloud.tasks.v2.Queue[] = []; + stream.on('data', (response: protos.google.cloud.tasks.v2.Queue) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listQueues.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listQueues, request), + ); + assert( + (client.descriptors.page.listQueues.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('invokes listQueues with error', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.tasks.v2.ListQueuesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.tasks.v2.ListQueuesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listQueues = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listQueues(request), expectedError); - const actualRequest = (client.innerApiCalls.listQueues as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listQueues as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listQueuesStream with error', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.tasks.v2.ListQueuesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.tasks.v2.ListQueuesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listQueues.createStream = stubPageStreamingCall( + undefined, + expectedError, + ); + const stream = client.listQueuesStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.cloud.tasks.v2.Queue[] = []; + stream.on('data', (response: protos.google.cloud.tasks.v2.Queue) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listQueues.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listQueues, request), + ); + assert( + (client.descriptors.page.listQueues.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('invokes listQueuesStream without error', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.tasks.v2.ListQueuesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.tasks.v2.ListQueuesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.tasks.v2.Queue()), - generateSampleMessage(new protos.google.cloud.tasks.v2.Queue()), - generateSampleMessage(new protos.google.cloud.tasks.v2.Queue()), - ]; - client.descriptors.page.listQueues.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listQueuesStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.cloud.tasks.v2.Queue[] = []; - stream.on('data', (response: protos.google.cloud.tasks.v2.Queue) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.listQueues.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listQueues, request)); - assert( - (client.descriptors.page.listQueues.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listQueues without error', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.tasks.v2.ListQueuesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.tasks.v2.ListQueuesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.tasks.v2.Queue()), + generateSampleMessage(new protos.google.cloud.tasks.v2.Queue()), + generateSampleMessage(new protos.google.cloud.tasks.v2.Queue()), + ]; + client.descriptors.page.listQueues.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.cloud.tasks.v2.IQueue[] = []; + const iterable = client.listQueuesAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + (client.descriptors.page.listQueues.asyncIterate as SinonStub).getCall( + 0, + ).args[1], + request, + ); + assert( + (client.descriptors.page.listQueues.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('invokes listQueuesStream with error', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.tasks.v2.ListQueuesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.tasks.v2.ListQueuesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listQueues.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listQueuesStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.cloud.tasks.v2.Queue[] = []; - stream.on('data', (response: protos.google.cloud.tasks.v2.Queue) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listQueues.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listQueues, request)); - assert( - (client.descriptors.page.listQueues.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listQueues with error', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.tasks.v2.ListQueuesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.tasks.v2.ListQueuesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listQueues.asyncIterate = stubAsyncIterationCall( + undefined, + expectedError, + ); + const iterable = client.listQueuesAsync(request); + await assert.rejects(async () => { + const responses: protos.google.cloud.tasks.v2.IQueue[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + (client.descriptors.page.listQueues.asyncIterate as SinonStub).getCall( + 0, + ).args[1], + request, + ); + assert( + (client.descriptors.page.listQueues.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + }); + + describe('listTasks', () => { + it('invokes listTasks without error', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.tasks.v2.ListTasksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.tasks.v2.ListTasksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.tasks.v2.Task()), + generateSampleMessage(new protos.google.cloud.tasks.v2.Task()), + generateSampleMessage(new protos.google.cloud.tasks.v2.Task()), + ]; + client.innerApiCalls.listTasks = stubSimpleCall(expectedResponse); + const [response] = await client.listTasks(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listTasks as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listTasks as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('uses async iteration with listQueues without error', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.tasks.v2.ListQueuesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.tasks.v2.ListQueuesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.tasks.v2.Queue()), - generateSampleMessage(new protos.google.cloud.tasks.v2.Queue()), - generateSampleMessage(new protos.google.cloud.tasks.v2.Queue()), - ]; - client.descriptors.page.listQueues.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.cloud.tasks.v2.IQueue[] = []; - const iterable = client.listQueuesAsync(request); - for await (const resource of iterable) { - responses.push(resource!); + it('invokes listTasks without error using callback', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.tasks.v2.ListTasksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.tasks.v2.ListTasksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.tasks.v2.Task()), + generateSampleMessage(new protos.google.cloud.tasks.v2.Task()), + generateSampleMessage(new protos.google.cloud.tasks.v2.Task()), + ]; + client.innerApiCalls.listTasks = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listTasks( + request, + ( + err?: Error | null, + result?: protos.google.cloud.tasks.v2.ITask[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listQueues.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listQueues.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); - - it('uses async iteration with listQueues with error', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.tasks.v2.ListQueuesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.tasks.v2.ListQueuesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listQueues.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listQueuesAsync(request); - await assert.rejects(async () => { - const responses: protos.google.cloud.tasks.v2.IQueue[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listQueues.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listQueues.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listTasks as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listTasks as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('listTasks', () => { - it('invokes listTasks without error', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.tasks.v2.ListTasksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.tasks.v2.ListTasksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.tasks.v2.Task()), - generateSampleMessage(new protos.google.cloud.tasks.v2.Task()), - generateSampleMessage(new protos.google.cloud.tasks.v2.Task()), - ]; - client.innerApiCalls.listTasks = stubSimpleCall(expectedResponse); - const [response] = await client.listTasks(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listTasks as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listTasks as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listTasks without error using callback', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.tasks.v2.ListTasksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.tasks.v2.ListTasksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.tasks.v2.Task()), - generateSampleMessage(new protos.google.cloud.tasks.v2.Task()), - generateSampleMessage(new protos.google.cloud.tasks.v2.Task()), - ]; - client.innerApiCalls.listTasks = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listTasks( - request, - (err?: Error|null, result?: protos.google.cloud.tasks.v2.ITask[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listTasks as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listTasks as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listTasks with error', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.tasks.v2.ListTasksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.tasks.v2.ListTasksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listTasks = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listTasks(request), expectedError); - const actualRequest = (client.innerApiCalls.listTasks as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listTasks as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listTasksStream without error', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.tasks.v2.ListTasksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.tasks.v2.ListTasksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.tasks.v2.Task()), - generateSampleMessage(new protos.google.cloud.tasks.v2.Task()), - generateSampleMessage(new protos.google.cloud.tasks.v2.Task()), - ]; - client.descriptors.page.listTasks.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listTasksStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.cloud.tasks.v2.Task[] = []; - stream.on('data', (response: protos.google.cloud.tasks.v2.Task) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.listTasks.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listTasks, request)); - assert( - (client.descriptors.page.listTasks.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listTasks with error', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.tasks.v2.ListTasksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.tasks.v2.ListTasksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listTasks = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.listTasks(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listTasks as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listTasks as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listTasksStream with error', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.tasks.v2.ListTasksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.tasks.v2.ListTasksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listTasks.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listTasksStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.cloud.tasks.v2.Task[] = []; - stream.on('data', (response: protos.google.cloud.tasks.v2.Task) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listTasks.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listTasks, request)); - assert( - (client.descriptors.page.listTasks.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listTasksStream without error', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.tasks.v2.ListTasksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.tasks.v2.ListTasksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.tasks.v2.Task()), + generateSampleMessage(new protos.google.cloud.tasks.v2.Task()), + generateSampleMessage(new protos.google.cloud.tasks.v2.Task()), + ]; + client.descriptors.page.listTasks.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listTasksStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.cloud.tasks.v2.Task[] = []; + stream.on('data', (response: protos.google.cloud.tasks.v2.Task) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listTasks.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listTasks, request), + ); + assert( + (client.descriptors.page.listTasks.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('uses async iteration with listTasks without error', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.tasks.v2.ListTasksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.tasks.v2.ListTasksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.tasks.v2.Task()), - generateSampleMessage(new protos.google.cloud.tasks.v2.Task()), - generateSampleMessage(new protos.google.cloud.tasks.v2.Task()), - ]; - client.descriptors.page.listTasks.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.cloud.tasks.v2.ITask[] = []; - const iterable = client.listTasksAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listTasks.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listTasks.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listTasksStream with error', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.tasks.v2.ListTasksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.tasks.v2.ListTasksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listTasks.createStream = stubPageStreamingCall( + undefined, + expectedError, + ); + const stream = client.listTasksStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.cloud.tasks.v2.Task[] = []; + stream.on('data', (response: protos.google.cloud.tasks.v2.Task) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listTasks.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listTasks, request), + ); + assert( + (client.descriptors.page.listTasks.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('uses async iteration with listTasks with error', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.tasks.v2.ListTasksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.tasks.v2.ListTasksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listTasks.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listTasksAsync(request); - await assert.rejects(async () => { - const responses: protos.google.cloud.tasks.v2.ITask[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listTasks.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listTasks.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listTasks without error', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.tasks.v2.ListTasksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.tasks.v2.ListTasksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.tasks.v2.Task()), + generateSampleMessage(new protos.google.cloud.tasks.v2.Task()), + generateSampleMessage(new protos.google.cloud.tasks.v2.Task()), + ]; + client.descriptors.page.listTasks.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.cloud.tasks.v2.ITask[] = []; + const iterable = client.listTasksAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + (client.descriptors.page.listTasks.asyncIterate as SinonStub).getCall(0) + .args[1], + request, + ); + assert( + (client.descriptors.page.listTasks.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); }); - describe('Path templates', () => { - - describe('queue', () => { - const fakePath = "/rendered/path/queue"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - queue: "queueValue", - }; - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.queuePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.queuePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('queuePath', () => { - const result = client.queuePath("projectValue", "locationValue", "queueValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.queuePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromQueueName', () => { - const result = client.matchProjectFromQueueName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.queuePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromQueueName', () => { - const result = client.matchLocationFromQueueName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.queuePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchQueueFromQueueName', () => { - const result = client.matchQueueFromQueueName(fakePath); - assert.strictEqual(result, "queueValue"); - assert((client.pathTemplates.queuePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('uses async iteration with listTasks with error', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.tasks.v2.ListTasksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.tasks.v2.ListTasksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listTasks.asyncIterate = stubAsyncIterationCall( + undefined, + expectedError, + ); + const iterable = client.listTasksAsync(request); + await assert.rejects(async () => { + const responses: protos.google.cloud.tasks.v2.ITask[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + (client.descriptors.page.listTasks.asyncIterate as SinonStub).getCall(0) + .args[1], + request, + ); + assert( + (client.descriptors.page.listTasks.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + }); + + describe('Path templates', () => { + describe('queue', () => { + const fakePath = '/rendered/path/queue'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + queue: 'queueValue', + }; + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.queuePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.queuePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('queuePath', () => { + const result = client.queuePath( + 'projectValue', + 'locationValue', + 'queueValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.queuePathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromQueueName', () => { + const result = client.matchProjectFromQueueName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.queuePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromQueueName', () => { + const result = client.matchLocationFromQueueName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.queuePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchQueueFromQueueName', () => { + const result = client.matchQueueFromQueueName(fakePath); + assert.strictEqual(result, 'queueValue'); + assert( + (client.pathTemplates.queuePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('task', () => { - const fakePath = "/rendered/path/task"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - queue: "queueValue", - task: "taskValue", - }; - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.taskPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.taskPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('taskPath', () => { - const result = client.taskPath("projectValue", "locationValue", "queueValue", "taskValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.taskPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromTaskName', () => { - const result = client.matchProjectFromTaskName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.taskPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromTaskName', () => { - const result = client.matchLocationFromTaskName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.taskPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchQueueFromTaskName', () => { - const result = client.matchQueueFromTaskName(fakePath); - assert.strictEqual(result, "queueValue"); - assert((client.pathTemplates.taskPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchTaskFromTaskName', () => { - const result = client.matchTaskFromTaskName(fakePath); - assert.strictEqual(result, "taskValue"); - assert((client.pathTemplates.taskPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('task', () => { + const fakePath = '/rendered/path/task'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + queue: 'queueValue', + task: 'taskValue', + }; + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.taskPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.taskPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('taskPath', () => { + const result = client.taskPath( + 'projectValue', + 'locationValue', + 'queueValue', + 'taskValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.taskPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromTaskName', () => { + const result = client.matchProjectFromTaskName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.taskPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromTaskName', () => { + const result = client.matchLocationFromTaskName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.taskPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchQueueFromTaskName', () => { + const result = client.matchQueueFromTaskName(fakePath); + assert.strictEqual(result, 'queueValue'); + assert( + (client.pathTemplates.taskPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchTaskFromTaskName', () => { + const result = client.matchTaskFromTaskName(fakePath); + assert.strictEqual(result, 'taskValue'); + assert( + (client.pathTemplates.taskPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/core/generator/gapic-generator-typescript/baselines/tasks/src/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/tasks/src/index.ts.baseline index 0e47f23a2bcf..294c181983cc 100644 --- a/core/generator/gapic-generator-typescript/baselines/tasks/src/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/tasks/src/index.ts.baseline @@ -19,7 +19,7 @@ import * as v2 from './v2'; const CloudTasksClient = v2.CloudTasksClient; type CloudTasksClient = v2.CloudTasksClient; -export {v2, CloudTasksClient}; -export default {v2, CloudTasksClient}; +export { v2, CloudTasksClient }; +export default { v2, CloudTasksClient }; import * as protos from '../protos/protos'; -export {protos} +export { protos }; diff --git a/core/generator/gapic-generator-typescript/baselines/tasks/src/v2/cloud_tasks_client.ts.baseline b/core/generator/gapic-generator-typescript/baselines/tasks/src/v2/cloud_tasks_client.ts.baseline index 8a8d79b5ca1d..c20441ab376f 100644 --- a/core/generator/gapic-generator-typescript/baselines/tasks/src/v2/cloud_tasks_client.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/tasks/src/v2/cloud_tasks_client.ts.baseline @@ -18,11 +18,18 @@ /* global window */ import type * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions, PaginationCallback, GaxCall} from 'google-gax'; -import {Transform} from 'stream'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + PaginationCallback, + GaxCall, +} from 'google-gax'; +import { Transform } from 'stream'; import * as protos from '../../protos/protos'; import jsonProtos = require('../../protos/protos.json'); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; /** * Client JSON configuration object, loaded from @@ -45,7 +52,7 @@ export class CloudTasksClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('tasks'); @@ -58,9 +65,9 @@ export class CloudTasksClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; - cloudTasksStub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; + cloudTasksStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of CloudTasksClient. @@ -101,21 +108,42 @@ export class CloudTasksClient { * const client = new CloudTasksClient({fallback: true}, gax); * ``` */ - constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { // Ensure that options include all the required fields. const staticMembers = this.constructor as typeof CloudTasksClient; - if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { - throw new Error('Please set either universe_domain or universeDomain, but not both.'); + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); } - const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; - this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; this._servicePath = 'cloudtasks.' + this._universeDomain; - const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; - const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. if (servicePath !== this._servicePath && !('scopes' in opts)) { @@ -137,7 +165,7 @@ export class CloudTasksClient { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; @@ -151,10 +179,7 @@ export class CloudTasksClient { } // Determine the client header string. - const clientHeader = [ - `gax/${this._gaxModule.version}`, - `gapic/${version}`, - ]; + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/${process.versions.node}`); } else { @@ -176,10 +201,10 @@ export class CloudTasksClient { // Create useful helper objects for these. this.pathTemplates = { queuePathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/queues/{queue}' + 'projects/{project}/locations/{location}/queues/{queue}', ), taskPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/queues/{queue}/tasks/{task}' + 'projects/{project}/locations/{location}/queues/{queue}/tasks/{task}', ), }; @@ -187,16 +212,25 @@ export class CloudTasksClient { // (e.g. 50 results at a time, with tokens to get subsequent // pages). Denote the keys used for pagination and results. this.descriptors.page = { - listQueues: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'queues'), - listTasks: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'tasks') + listQueues: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'queues', + ), + listTasks: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'tasks', + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.cloud.tasks.v2.CloudTasks', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.cloud.tasks.v2.CloudTasks', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + { 'x-goog-api-client': clientHeader.join(' ') }, + ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -227,37 +261,57 @@ export class CloudTasksClient { // Put together the "service stub" for // google.cloud.tasks.v2.CloudTasks. this.cloudTasksStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.cloud.tasks.v2.CloudTasks') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.cloud.tasks.v2.CloudTasks', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.cloud.tasks.v2.CloudTasks, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts, + this._providedCustomServicePath, + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const cloudTasksStubMethods = - ['listQueues', 'getQueue', 'createQueue', 'updateQueue', 'deleteQueue', 'purgeQueue', 'pauseQueue', 'resumeQueue', 'getIamPolicy', 'setIamPolicy', 'testIamPermissions', 'listTasks', 'getTask', 'createTask', 'deleteTask', 'runTask']; + const cloudTasksStubMethods = [ + 'listQueues', + 'getQueue', + 'createQueue', + 'updateQueue', + 'deleteQueue', + 'purgeQueue', + 'pauseQueue', + 'resumeQueue', + 'getIamPolicy', + 'setIamPolicy', + 'testIamPermissions', + 'listTasks', + 'getTask', + 'createTask', + 'deleteTask', + 'runTask', + ]; for (const methodName of cloudTasksStubMethods) { const callPromise = this.cloudTasksStub.then( - stub => (...args: Array<{}>) => { - if (this._terminated) { - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error|null|undefined) => () => { + (stub) => + (...args: Array<{}>) => { + if (this._terminated) { + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { throw err; - }); + }, + ); - const descriptor = - this.descriptors.page[methodName] || - undefined; + const descriptor = this.descriptors.page[methodName] || undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -272,8 +326,14 @@ export class CloudTasksClient { * @returns {string} The DNS address for this service. */ static get servicePath() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'cloudtasks.googleapis.com'; } @@ -284,8 +344,14 @@ export class CloudTasksClient { * @returns {string} The DNS address for this service. */ static get apiEndpoint() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'cloudtasks.googleapis.com'; } @@ -316,9 +382,7 @@ export class CloudTasksClient { * @returns {string[]} List of default scopes. */ static get scopes() { - return [ - 'https://www.googleapis.com/auth/cloud-platform' - ]; + return ['https://www.googleapis.com/auth/cloud-platform']; } getProjectId(): Promise; @@ -327,8 +391,9 @@ export class CloudTasksClient { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId(callback?: Callback): - Promise|void { + getProjectId( + callback?: Callback, + ): Promise | void { if (callback) { this.auth.getProjectId(callback); return; @@ -339,1666 +404,2101 @@ export class CloudTasksClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Gets a queue. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The resource name of the queue. For example: - * `projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID` - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.tasks.v2.Queue|Queue}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/cloud_tasks.get_queue.js - * region_tag:cloudtasks_v2_generated_CloudTasks_GetQueue_async - */ + /** + * Gets a queue. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The resource name of the queue. For example: + * `projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.tasks.v2.Queue|Queue}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/cloud_tasks.get_queue.js + * region_tag:cloudtasks_v2_generated_CloudTasks_GetQueue_async + */ getQueue( - request?: protos.google.cloud.tasks.v2.IGetQueueRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.tasks.v2.IQueue, - protos.google.cloud.tasks.v2.IGetQueueRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.tasks.v2.IGetQueueRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.tasks.v2.IQueue, + protos.google.cloud.tasks.v2.IGetQueueRequest | undefined, + {} | undefined, + ] + >; getQueue( - request: protos.google.cloud.tasks.v2.IGetQueueRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.tasks.v2.IQueue, - protos.google.cloud.tasks.v2.IGetQueueRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.tasks.v2.IGetQueueRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.tasks.v2.IQueue, + protos.google.cloud.tasks.v2.IGetQueueRequest | null | undefined, + {} | null | undefined + >, + ): void; getQueue( - request: protos.google.cloud.tasks.v2.IGetQueueRequest, - callback: Callback< - protos.google.cloud.tasks.v2.IQueue, - protos.google.cloud.tasks.v2.IGetQueueRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.tasks.v2.IGetQueueRequest, + callback: Callback< + protos.google.cloud.tasks.v2.IQueue, + protos.google.cloud.tasks.v2.IGetQueueRequest | null | undefined, + {} | null | undefined + >, + ): void; getQueue( - request?: protos.google.cloud.tasks.v2.IGetQueueRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.tasks.v2.IQueue, - protos.google.cloud.tasks.v2.IGetQueueRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.tasks.v2.IGetQueueRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.tasks.v2.IQueue, - protos.google.cloud.tasks.v2.IGetQueueRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.tasks.v2.IQueue, - protos.google.cloud.tasks.v2.IGetQueueRequest|undefined, {}|undefined - ]>|void { + protos.google.cloud.tasks.v2.IGetQueueRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.tasks.v2.IQueue, + protos.google.cloud.tasks.v2.IGetQueueRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.tasks.v2.IQueue, + protos.google.cloud.tasks.v2.IGetQueueRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getQueue request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.tasks.v2.IQueue, - protos.google.cloud.tasks.v2.IGetQueueRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.tasks.v2.IQueue, + protos.google.cloud.tasks.v2.IGetQueueRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getQueue response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getQueue(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.tasks.v2.IQueue, - protos.google.cloud.tasks.v2.IGetQueueRequest|undefined, - {}|undefined - ]) => { - this._log.info('getQueue response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getQueue(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.tasks.v2.IQueue, + protos.google.cloud.tasks.v2.IGetQueueRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getQueue response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Creates a queue. - * - * Queues created with this method allow tasks to live for a maximum of 31 - * days. After a task is 31 days old, the task will be deleted regardless of whether - * it was dispatched or not. - * - * WARNING: Using this method may have unintended side effects if you are - * using an App Engine `queue.yaml` or `queue.xml` file to manage your queues. - * Read - * [Overview of Queue Management and - * queue.yaml](https://cloud.google.com/tasks/docs/queue-yaml) before using - * this method. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The location name in which the queue will be created. - * For example: `projects/PROJECT_ID/locations/LOCATION_ID` - * - * The list of allowed locations can be obtained by calling Cloud - * Tasks' implementation of - * {@link protos.google.cloud.location.Locations.ListLocations|ListLocations}. - * @param {google.cloud.tasks.v2.Queue} request.queue - * Required. The queue to create. - * - * {@link protos.google.cloud.tasks.v2.Queue.name|Queue's name} cannot be the same as an existing queue. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.tasks.v2.Queue|Queue}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/cloud_tasks.create_queue.js - * region_tag:cloudtasks_v2_generated_CloudTasks_CreateQueue_async - */ + /** + * Creates a queue. + * + * Queues created with this method allow tasks to live for a maximum of 31 + * days. After a task is 31 days old, the task will be deleted regardless of whether + * it was dispatched or not. + * + * WARNING: Using this method may have unintended side effects if you are + * using an App Engine `queue.yaml` or `queue.xml` file to manage your queues. + * Read + * [Overview of Queue Management and + * queue.yaml](https://cloud.google.com/tasks/docs/queue-yaml) before using + * this method. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The location name in which the queue will be created. + * For example: `projects/PROJECT_ID/locations/LOCATION_ID` + * + * The list of allowed locations can be obtained by calling Cloud + * Tasks' implementation of + * {@link protos.google.cloud.location.Locations.ListLocations|ListLocations}. + * @param {google.cloud.tasks.v2.Queue} request.queue + * Required. The queue to create. + * + * {@link protos.google.cloud.tasks.v2.Queue.name|Queue's name} cannot be the same as an existing queue. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.tasks.v2.Queue|Queue}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/cloud_tasks.create_queue.js + * region_tag:cloudtasks_v2_generated_CloudTasks_CreateQueue_async + */ createQueue( - request?: protos.google.cloud.tasks.v2.ICreateQueueRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.tasks.v2.IQueue, - protos.google.cloud.tasks.v2.ICreateQueueRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.tasks.v2.ICreateQueueRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.tasks.v2.IQueue, + protos.google.cloud.tasks.v2.ICreateQueueRequest | undefined, + {} | undefined, + ] + >; createQueue( - request: protos.google.cloud.tasks.v2.ICreateQueueRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.tasks.v2.IQueue, - protos.google.cloud.tasks.v2.ICreateQueueRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.tasks.v2.ICreateQueueRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.tasks.v2.IQueue, + protos.google.cloud.tasks.v2.ICreateQueueRequest | null | undefined, + {} | null | undefined + >, + ): void; createQueue( - request: protos.google.cloud.tasks.v2.ICreateQueueRequest, - callback: Callback< - protos.google.cloud.tasks.v2.IQueue, - protos.google.cloud.tasks.v2.ICreateQueueRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.tasks.v2.ICreateQueueRequest, + callback: Callback< + protos.google.cloud.tasks.v2.IQueue, + protos.google.cloud.tasks.v2.ICreateQueueRequest | null | undefined, + {} | null | undefined + >, + ): void; createQueue( - request?: protos.google.cloud.tasks.v2.ICreateQueueRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.tasks.v2.IQueue, - protos.google.cloud.tasks.v2.ICreateQueueRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.tasks.v2.ICreateQueueRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.tasks.v2.IQueue, - protos.google.cloud.tasks.v2.ICreateQueueRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.tasks.v2.IQueue, - protos.google.cloud.tasks.v2.ICreateQueueRequest|undefined, {}|undefined - ]>|void { + protos.google.cloud.tasks.v2.ICreateQueueRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.tasks.v2.IQueue, + protos.google.cloud.tasks.v2.ICreateQueueRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.tasks.v2.IQueue, + protos.google.cloud.tasks.v2.ICreateQueueRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('createQueue request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.tasks.v2.IQueue, - protos.google.cloud.tasks.v2.ICreateQueueRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.tasks.v2.IQueue, + protos.google.cloud.tasks.v2.ICreateQueueRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createQueue response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.createQueue(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.tasks.v2.IQueue, - protos.google.cloud.tasks.v2.ICreateQueueRequest|undefined, - {}|undefined - ]) => { - this._log.info('createQueue response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createQueue(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.tasks.v2.IQueue, + protos.google.cloud.tasks.v2.ICreateQueueRequest | undefined, + {} | undefined, + ]) => { + this._log.info('createQueue response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Updates a queue. - * - * This method creates the queue if it does not exist and updates - * the queue if it does exist. - * - * Queues created with this method allow tasks to live for a maximum of 31 - * days. After a task is 31 days old, the task will be deleted regardless of whether - * it was dispatched or not. - * - * WARNING: Using this method may have unintended side effects if you are - * using an App Engine `queue.yaml` or `queue.xml` file to manage your queues. - * Read - * [Overview of Queue Management and - * queue.yaml](https://cloud.google.com/tasks/docs/queue-yaml) before using - * this method. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.cloud.tasks.v2.Queue} request.queue - * Required. The queue to create or update. - * - * The queue's {@link protos.google.cloud.tasks.v2.Queue.name|name} must be specified. - * - * Output only fields cannot be modified using UpdateQueue. - * Any value specified for an output only field will be ignored. - * The queue's {@link protos.google.cloud.tasks.v2.Queue.name|name} cannot be changed. - * @param {google.protobuf.FieldMask} request.updateMask - * A mask used to specify which fields of the queue are being updated. - * - * If empty, then all fields will be updated. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.tasks.v2.Queue|Queue}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/cloud_tasks.update_queue.js - * region_tag:cloudtasks_v2_generated_CloudTasks_UpdateQueue_async - */ + /** + * Updates a queue. + * + * This method creates the queue if it does not exist and updates + * the queue if it does exist. + * + * Queues created with this method allow tasks to live for a maximum of 31 + * days. After a task is 31 days old, the task will be deleted regardless of whether + * it was dispatched or not. + * + * WARNING: Using this method may have unintended side effects if you are + * using an App Engine `queue.yaml` or `queue.xml` file to manage your queues. + * Read + * [Overview of Queue Management and + * queue.yaml](https://cloud.google.com/tasks/docs/queue-yaml) before using + * this method. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.cloud.tasks.v2.Queue} request.queue + * Required. The queue to create or update. + * + * The queue's {@link protos.google.cloud.tasks.v2.Queue.name|name} must be specified. + * + * Output only fields cannot be modified using UpdateQueue. + * Any value specified for an output only field will be ignored. + * The queue's {@link protos.google.cloud.tasks.v2.Queue.name|name} cannot be changed. + * @param {google.protobuf.FieldMask} request.updateMask + * A mask used to specify which fields of the queue are being updated. + * + * If empty, then all fields will be updated. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.tasks.v2.Queue|Queue}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/cloud_tasks.update_queue.js + * region_tag:cloudtasks_v2_generated_CloudTasks_UpdateQueue_async + */ updateQueue( - request?: protos.google.cloud.tasks.v2.IUpdateQueueRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.tasks.v2.IQueue, - protos.google.cloud.tasks.v2.IUpdateQueueRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.tasks.v2.IUpdateQueueRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.tasks.v2.IQueue, + protos.google.cloud.tasks.v2.IUpdateQueueRequest | undefined, + {} | undefined, + ] + >; updateQueue( - request: protos.google.cloud.tasks.v2.IUpdateQueueRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.tasks.v2.IQueue, - protos.google.cloud.tasks.v2.IUpdateQueueRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.tasks.v2.IUpdateQueueRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.tasks.v2.IQueue, + protos.google.cloud.tasks.v2.IUpdateQueueRequest | null | undefined, + {} | null | undefined + >, + ): void; updateQueue( - request: protos.google.cloud.tasks.v2.IUpdateQueueRequest, - callback: Callback< - protos.google.cloud.tasks.v2.IQueue, - protos.google.cloud.tasks.v2.IUpdateQueueRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.tasks.v2.IUpdateQueueRequest, + callback: Callback< + protos.google.cloud.tasks.v2.IQueue, + protos.google.cloud.tasks.v2.IUpdateQueueRequest | null | undefined, + {} | null | undefined + >, + ): void; updateQueue( - request?: protos.google.cloud.tasks.v2.IUpdateQueueRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.tasks.v2.IQueue, - protos.google.cloud.tasks.v2.IUpdateQueueRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.tasks.v2.IUpdateQueueRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.tasks.v2.IQueue, - protos.google.cloud.tasks.v2.IUpdateQueueRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.tasks.v2.IQueue, - protos.google.cloud.tasks.v2.IUpdateQueueRequest|undefined, {}|undefined - ]>|void { + protos.google.cloud.tasks.v2.IUpdateQueueRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.tasks.v2.IQueue, + protos.google.cloud.tasks.v2.IUpdateQueueRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.tasks.v2.IQueue, + protos.google.cloud.tasks.v2.IUpdateQueueRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'queue.name': request.queue!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'queue.name': request.queue!.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateQueue request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.tasks.v2.IQueue, - protos.google.cloud.tasks.v2.IUpdateQueueRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.tasks.v2.IQueue, + protos.google.cloud.tasks.v2.IUpdateQueueRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateQueue response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.updateQueue(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.tasks.v2.IQueue, - protos.google.cloud.tasks.v2.IUpdateQueueRequest|undefined, - {}|undefined - ]) => { - this._log.info('updateQueue response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateQueue(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.tasks.v2.IQueue, + protos.google.cloud.tasks.v2.IUpdateQueueRequest | undefined, + {} | undefined, + ]) => { + this._log.info('updateQueue response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Deletes a queue. - * - * This command will delete the queue even if it has tasks in it. - * - * Note: If you delete a queue, a queue with the same name can't be created - * for 7 days. - * - * WARNING: Using this method may have unintended side effects if you are - * using an App Engine `queue.yaml` or `queue.xml` file to manage your queues. - * Read - * [Overview of Queue Management and - * queue.yaml](https://cloud.google.com/tasks/docs/queue-yaml) before using - * this method. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The queue name. For example: - * `projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID` - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/cloud_tasks.delete_queue.js - * region_tag:cloudtasks_v2_generated_CloudTasks_DeleteQueue_async - */ + /** + * Deletes a queue. + * + * This command will delete the queue even if it has tasks in it. + * + * Note: If you delete a queue, a queue with the same name can't be created + * for 7 days. + * + * WARNING: Using this method may have unintended side effects if you are + * using an App Engine `queue.yaml` or `queue.xml` file to manage your queues. + * Read + * [Overview of Queue Management and + * queue.yaml](https://cloud.google.com/tasks/docs/queue-yaml) before using + * this method. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The queue name. For example: + * `projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/cloud_tasks.delete_queue.js + * region_tag:cloudtasks_v2_generated_CloudTasks_DeleteQueue_async + */ deleteQueue( - request?: protos.google.cloud.tasks.v2.IDeleteQueueRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.cloud.tasks.v2.IDeleteQueueRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.tasks.v2.IDeleteQueueRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.cloud.tasks.v2.IDeleteQueueRequest | undefined, + {} | undefined, + ] + >; deleteQueue( - request: protos.google.cloud.tasks.v2.IDeleteQueueRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.cloud.tasks.v2.IDeleteQueueRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.tasks.v2.IDeleteQueueRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.cloud.tasks.v2.IDeleteQueueRequest | null | undefined, + {} | null | undefined + >, + ): void; deleteQueue( - request: protos.google.cloud.tasks.v2.IDeleteQueueRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.cloud.tasks.v2.IDeleteQueueRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.tasks.v2.IDeleteQueueRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.cloud.tasks.v2.IDeleteQueueRequest | null | undefined, + {} | null | undefined + >, + ): void; deleteQueue( - request?: protos.google.cloud.tasks.v2.IDeleteQueueRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.cloud.tasks.v2.IDeleteQueueRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.cloud.tasks.v2.IDeleteQueueRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.protobuf.IEmpty, - protos.google.cloud.tasks.v2.IDeleteQueueRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.cloud.tasks.v2.IDeleteQueueRequest|undefined, {}|undefined - ]>|void { + protos.google.cloud.tasks.v2.IDeleteQueueRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + protos.google.cloud.tasks.v2.IDeleteQueueRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.cloud.tasks.v2.IDeleteQueueRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('deleteQueue request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.cloud.tasks.v2.IDeleteQueueRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + protos.google.cloud.tasks.v2.IDeleteQueueRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteQueue response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.deleteQueue(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.cloud.tasks.v2.IDeleteQueueRequest|undefined, - {}|undefined - ]) => { - this._log.info('deleteQueue response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteQueue(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.cloud.tasks.v2.IDeleteQueueRequest | undefined, + {} | undefined, + ]) => { + this._log.info('deleteQueue response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Purges a queue by deleting all of its tasks. - * - * All tasks created before this method is called are permanently deleted. - * - * Purge operations can take up to one minute to take effect. Tasks - * might be dispatched before the purge takes effect. A purge is irreversible. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The queue name. For example: - * `projects/PROJECT_ID/location/LOCATION_ID/queues/QUEUE_ID` - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.tasks.v2.Queue|Queue}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/cloud_tasks.purge_queue.js - * region_tag:cloudtasks_v2_generated_CloudTasks_PurgeQueue_async - */ + /** + * Purges a queue by deleting all of its tasks. + * + * All tasks created before this method is called are permanently deleted. + * + * Purge operations can take up to one minute to take effect. Tasks + * might be dispatched before the purge takes effect. A purge is irreversible. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The queue name. For example: + * `projects/PROJECT_ID/location/LOCATION_ID/queues/QUEUE_ID` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.tasks.v2.Queue|Queue}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/cloud_tasks.purge_queue.js + * region_tag:cloudtasks_v2_generated_CloudTasks_PurgeQueue_async + */ purgeQueue( - request?: protos.google.cloud.tasks.v2.IPurgeQueueRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.tasks.v2.IQueue, - protos.google.cloud.tasks.v2.IPurgeQueueRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.tasks.v2.IPurgeQueueRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.tasks.v2.IQueue, + protos.google.cloud.tasks.v2.IPurgeQueueRequest | undefined, + {} | undefined, + ] + >; purgeQueue( - request: protos.google.cloud.tasks.v2.IPurgeQueueRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.tasks.v2.IQueue, - protos.google.cloud.tasks.v2.IPurgeQueueRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.tasks.v2.IPurgeQueueRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.tasks.v2.IQueue, + protos.google.cloud.tasks.v2.IPurgeQueueRequest | null | undefined, + {} | null | undefined + >, + ): void; purgeQueue( - request: protos.google.cloud.tasks.v2.IPurgeQueueRequest, - callback: Callback< - protos.google.cloud.tasks.v2.IQueue, - protos.google.cloud.tasks.v2.IPurgeQueueRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.tasks.v2.IPurgeQueueRequest, + callback: Callback< + protos.google.cloud.tasks.v2.IQueue, + protos.google.cloud.tasks.v2.IPurgeQueueRequest | null | undefined, + {} | null | undefined + >, + ): void; purgeQueue( - request?: protos.google.cloud.tasks.v2.IPurgeQueueRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.tasks.v2.IQueue, - protos.google.cloud.tasks.v2.IPurgeQueueRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.tasks.v2.IPurgeQueueRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.tasks.v2.IQueue, - protos.google.cloud.tasks.v2.IPurgeQueueRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.tasks.v2.IQueue, - protos.google.cloud.tasks.v2.IPurgeQueueRequest|undefined, {}|undefined - ]>|void { + protos.google.cloud.tasks.v2.IPurgeQueueRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.tasks.v2.IQueue, + protos.google.cloud.tasks.v2.IPurgeQueueRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.tasks.v2.IQueue, + protos.google.cloud.tasks.v2.IPurgeQueueRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('purgeQueue request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.tasks.v2.IQueue, - protos.google.cloud.tasks.v2.IPurgeQueueRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.tasks.v2.IQueue, + protos.google.cloud.tasks.v2.IPurgeQueueRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('purgeQueue response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.purgeQueue(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.tasks.v2.IQueue, - protos.google.cloud.tasks.v2.IPurgeQueueRequest|undefined, - {}|undefined - ]) => { - this._log.info('purgeQueue response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .purgeQueue(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.tasks.v2.IQueue, + protos.google.cloud.tasks.v2.IPurgeQueueRequest | undefined, + {} | undefined, + ]) => { + this._log.info('purgeQueue response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Pauses the queue. - * - * If a queue is paused then the system will stop dispatching tasks - * until the queue is resumed via - * {@link protos.google.cloud.tasks.v2.CloudTasks.ResumeQueue|ResumeQueue}. Tasks can still be added - * when the queue is paused. A queue is paused if its - * {@link protos.google.cloud.tasks.v2.Queue.state|state} is {@link protos.google.cloud.tasks.v2.Queue.State.PAUSED|PAUSED}. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The queue name. For example: - * `projects/PROJECT_ID/location/LOCATION_ID/queues/QUEUE_ID` - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.tasks.v2.Queue|Queue}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/cloud_tasks.pause_queue.js - * region_tag:cloudtasks_v2_generated_CloudTasks_PauseQueue_async - */ + /** + * Pauses the queue. + * + * If a queue is paused then the system will stop dispatching tasks + * until the queue is resumed via + * {@link protos.google.cloud.tasks.v2.CloudTasks.ResumeQueue|ResumeQueue}. Tasks can still be added + * when the queue is paused. A queue is paused if its + * {@link protos.google.cloud.tasks.v2.Queue.state|state} is {@link protos.google.cloud.tasks.v2.Queue.State.PAUSED|PAUSED}. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The queue name. For example: + * `projects/PROJECT_ID/location/LOCATION_ID/queues/QUEUE_ID` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.tasks.v2.Queue|Queue}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/cloud_tasks.pause_queue.js + * region_tag:cloudtasks_v2_generated_CloudTasks_PauseQueue_async + */ pauseQueue( - request?: protos.google.cloud.tasks.v2.IPauseQueueRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.tasks.v2.IQueue, - protos.google.cloud.tasks.v2.IPauseQueueRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.tasks.v2.IPauseQueueRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.tasks.v2.IQueue, + protos.google.cloud.tasks.v2.IPauseQueueRequest | undefined, + {} | undefined, + ] + >; pauseQueue( - request: protos.google.cloud.tasks.v2.IPauseQueueRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.tasks.v2.IQueue, - protos.google.cloud.tasks.v2.IPauseQueueRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.tasks.v2.IPauseQueueRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.tasks.v2.IQueue, + protos.google.cloud.tasks.v2.IPauseQueueRequest | null | undefined, + {} | null | undefined + >, + ): void; pauseQueue( - request: protos.google.cloud.tasks.v2.IPauseQueueRequest, - callback: Callback< - protos.google.cloud.tasks.v2.IQueue, - protos.google.cloud.tasks.v2.IPauseQueueRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.tasks.v2.IPauseQueueRequest, + callback: Callback< + protos.google.cloud.tasks.v2.IQueue, + protos.google.cloud.tasks.v2.IPauseQueueRequest | null | undefined, + {} | null | undefined + >, + ): void; pauseQueue( - request?: protos.google.cloud.tasks.v2.IPauseQueueRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.cloud.tasks.v2.IPauseQueueRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.tasks.v2.IQueue, - protos.google.cloud.tasks.v2.IPauseQueueRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.cloud.tasks.v2.IQueue, - protos.google.cloud.tasks.v2.IPauseQueueRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.tasks.v2.IQueue, - protos.google.cloud.tasks.v2.IPauseQueueRequest|undefined, {}|undefined - ]>|void { + protos.google.cloud.tasks.v2.IPauseQueueRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.tasks.v2.IQueue, + protos.google.cloud.tasks.v2.IPauseQueueRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.tasks.v2.IQueue, + protos.google.cloud.tasks.v2.IPauseQueueRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('pauseQueue request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.tasks.v2.IQueue, - protos.google.cloud.tasks.v2.IPauseQueueRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.tasks.v2.IQueue, + protos.google.cloud.tasks.v2.IPauseQueueRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('pauseQueue response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.pauseQueue(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.tasks.v2.IQueue, - protos.google.cloud.tasks.v2.IPauseQueueRequest|undefined, - {}|undefined - ]) => { - this._log.info('pauseQueue response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .pauseQueue(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.tasks.v2.IQueue, + protos.google.cloud.tasks.v2.IPauseQueueRequest | undefined, + {} | undefined, + ]) => { + this._log.info('pauseQueue response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Resume a queue. - * - * This method resumes a queue after it has been - * {@link protos.google.cloud.tasks.v2.Queue.State.PAUSED|PAUSED} or - * {@link protos.google.cloud.tasks.v2.Queue.State.DISABLED|DISABLED}. The state of a queue is stored - * in the queue's {@link protos.google.cloud.tasks.v2.Queue.state|state}; after calling this method it - * will be set to {@link protos.google.cloud.tasks.v2.Queue.State.RUNNING|RUNNING}. - * - * WARNING: Resuming many high-QPS queues at the same time can - * lead to target overloading. If you are resuming high-QPS - * queues, follow the 500/50/5 pattern described in - * [Managing Cloud Tasks Scaling - * Risks](https://cloud.google.com/tasks/docs/manage-cloud-task-scaling). - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The queue name. For example: - * `projects/PROJECT_ID/location/LOCATION_ID/queues/QUEUE_ID` - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.tasks.v2.Queue|Queue}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/cloud_tasks.resume_queue.js - * region_tag:cloudtasks_v2_generated_CloudTasks_ResumeQueue_async - */ + /** + * Resume a queue. + * + * This method resumes a queue after it has been + * {@link protos.google.cloud.tasks.v2.Queue.State.PAUSED|PAUSED} or + * {@link protos.google.cloud.tasks.v2.Queue.State.DISABLED|DISABLED}. The state of a queue is stored + * in the queue's {@link protos.google.cloud.tasks.v2.Queue.state|state}; after calling this method it + * will be set to {@link protos.google.cloud.tasks.v2.Queue.State.RUNNING|RUNNING}. + * + * WARNING: Resuming many high-QPS queues at the same time can + * lead to target overloading. If you are resuming high-QPS + * queues, follow the 500/50/5 pattern described in + * [Managing Cloud Tasks Scaling + * Risks](https://cloud.google.com/tasks/docs/manage-cloud-task-scaling). + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The queue name. For example: + * `projects/PROJECT_ID/location/LOCATION_ID/queues/QUEUE_ID` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.tasks.v2.Queue|Queue}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/cloud_tasks.resume_queue.js + * region_tag:cloudtasks_v2_generated_CloudTasks_ResumeQueue_async + */ resumeQueue( - request?: protos.google.cloud.tasks.v2.IResumeQueueRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.tasks.v2.IQueue, - protos.google.cloud.tasks.v2.IResumeQueueRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.tasks.v2.IResumeQueueRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.tasks.v2.IQueue, + protos.google.cloud.tasks.v2.IResumeQueueRequest | undefined, + {} | undefined, + ] + >; resumeQueue( - request: protos.google.cloud.tasks.v2.IResumeQueueRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.tasks.v2.IQueue, - protos.google.cloud.tasks.v2.IResumeQueueRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.tasks.v2.IResumeQueueRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.tasks.v2.IQueue, + protos.google.cloud.tasks.v2.IResumeQueueRequest | null | undefined, + {} | null | undefined + >, + ): void; resumeQueue( - request: protos.google.cloud.tasks.v2.IResumeQueueRequest, - callback: Callback< - protos.google.cloud.tasks.v2.IQueue, - protos.google.cloud.tasks.v2.IResumeQueueRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.tasks.v2.IResumeQueueRequest, + callback: Callback< + protos.google.cloud.tasks.v2.IQueue, + protos.google.cloud.tasks.v2.IResumeQueueRequest | null | undefined, + {} | null | undefined + >, + ): void; resumeQueue( - request?: protos.google.cloud.tasks.v2.IResumeQueueRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.cloud.tasks.v2.IResumeQueueRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.tasks.v2.IQueue, - protos.google.cloud.tasks.v2.IResumeQueueRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.cloud.tasks.v2.IQueue, - protos.google.cloud.tasks.v2.IResumeQueueRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.tasks.v2.IQueue, - protos.google.cloud.tasks.v2.IResumeQueueRequest|undefined, {}|undefined - ]>|void { + protos.google.cloud.tasks.v2.IResumeQueueRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.tasks.v2.IQueue, + protos.google.cloud.tasks.v2.IResumeQueueRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.tasks.v2.IQueue, + protos.google.cloud.tasks.v2.IResumeQueueRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('resumeQueue request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.tasks.v2.IQueue, - protos.google.cloud.tasks.v2.IResumeQueueRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.tasks.v2.IQueue, + protos.google.cloud.tasks.v2.IResumeQueueRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('resumeQueue response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.resumeQueue(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.tasks.v2.IQueue, - protos.google.cloud.tasks.v2.IResumeQueueRequest|undefined, - {}|undefined - ]) => { - this._log.info('resumeQueue response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .resumeQueue(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.tasks.v2.IQueue, + protos.google.cloud.tasks.v2.IResumeQueueRequest | undefined, + {} | undefined, + ]) => { + this._log.info('resumeQueue response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Gets the access control policy for a {@link protos.google.cloud.tasks.v2.Queue|Queue}. - * Returns an empty policy if the resource exists and does not have a policy - * set. - * - * Authorization requires the following - * [Google IAM](https://cloud.google.com/iam) permission on the specified - * resource parent: - * - * * `cloudtasks.queues.getIamPolicy` - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.resource - * REQUIRED: The resource for which the policy is being requested. - * See the operation documentation for the appropriate value for this field. - * @param {google.iam.v1.GetPolicyOptions} request.options - * OPTIONAL: A `GetPolicyOptions` object for specifying options to - * `GetIamPolicy`. This field is only used by Cloud IAM. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.iam.v1.Policy|Policy}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/cloud_tasks.get_iam_policy.js - * region_tag:cloudtasks_v2_generated_CloudTasks_GetIamPolicy_async - */ + /** + * Gets the access control policy for a {@link protos.google.cloud.tasks.v2.Queue|Queue}. + * Returns an empty policy if the resource exists and does not have a policy + * set. + * + * Authorization requires the following + * [Google IAM](https://cloud.google.com/iam) permission on the specified + * resource parent: + * + * * `cloudtasks.queues.getIamPolicy` + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.resource + * REQUIRED: The resource for which the policy is being requested. + * See the operation documentation for the appropriate value for this field. + * @param {google.iam.v1.GetPolicyOptions} request.options + * OPTIONAL: A `GetPolicyOptions` object for specifying options to + * `GetIamPolicy`. This field is only used by Cloud IAM. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.iam.v1.Policy|Policy}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/cloud_tasks.get_iam_policy.js + * region_tag:cloudtasks_v2_generated_CloudTasks_GetIamPolicy_async + */ getIamPolicy( - request?: protos.google.iam.v1.IGetIamPolicyRequest, - options?: CallOptions): - Promise<[ - protos.google.iam.v1.IPolicy, - protos.google.iam.v1.IGetIamPolicyRequest|undefined, {}|undefined - ]>; + request?: protos.google.iam.v1.IGetIamPolicyRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.iam.v1.IPolicy, + protos.google.iam.v1.IGetIamPolicyRequest | undefined, + {} | undefined, + ] + >; getIamPolicy( - request: protos.google.iam.v1.IGetIamPolicyRequest, - options: CallOptions, - callback: Callback< - protos.google.iam.v1.IPolicy, - protos.google.iam.v1.IGetIamPolicyRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.iam.v1.IGetIamPolicyRequest, + options: CallOptions, + callback: Callback< + protos.google.iam.v1.IPolicy, + protos.google.iam.v1.IGetIamPolicyRequest | null | undefined, + {} | null | undefined + >, + ): void; getIamPolicy( - request: protos.google.iam.v1.IGetIamPolicyRequest, - callback: Callback< - protos.google.iam.v1.IPolicy, - protos.google.iam.v1.IGetIamPolicyRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.iam.v1.IGetIamPolicyRequest, + callback: Callback< + protos.google.iam.v1.IPolicy, + protos.google.iam.v1.IGetIamPolicyRequest | null | undefined, + {} | null | undefined + >, + ): void; getIamPolicy( - request?: protos.google.iam.v1.IGetIamPolicyRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.iam.v1.IGetIamPolicyRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.iam.v1.IPolicy, - protos.google.iam.v1.IGetIamPolicyRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.iam.v1.IPolicy, - protos.google.iam.v1.IGetIamPolicyRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.iam.v1.IPolicy, - protos.google.iam.v1.IGetIamPolicyRequest|undefined, {}|undefined - ]>|void { + protos.google.iam.v1.IGetIamPolicyRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.iam.v1.IPolicy, + protos.google.iam.v1.IGetIamPolicyRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.iam.v1.IPolicy, + protos.google.iam.v1.IGetIamPolicyRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'resource': request.resource ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + resource: request.resource ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getIamPolicy request %j', request); - const wrappedCallback: Callback< - protos.google.iam.v1.IPolicy, - protos.google.iam.v1.IGetIamPolicyRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.iam.v1.IPolicy, + protos.google.iam.v1.IGetIamPolicyRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getIamPolicy response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getIamPolicy(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.iam.v1.IPolicy, - protos.google.iam.v1.IGetIamPolicyRequest|undefined, - {}|undefined - ]) => { - this._log.info('getIamPolicy response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getIamPolicy(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.iam.v1.IPolicy, + protos.google.iam.v1.IGetIamPolicyRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getIamPolicy response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Sets the access control policy for a {@link protos.google.cloud.tasks.v2.Queue|Queue}. Replaces any existing - * policy. - * - * Note: The Cloud Console does not check queue-level IAM permissions yet. - * Project-level permissions are required to use the Cloud Console. - * - * Authorization requires the following - * [Google IAM](https://cloud.google.com/iam) permission on the specified - * resource parent: - * - * * `cloudtasks.queues.setIamPolicy` - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.resource - * REQUIRED: The resource for which the policy is being specified. - * See the operation documentation for the appropriate value for this field. - * @param {google.iam.v1.Policy} request.policy - * REQUIRED: The complete policy to be applied to the `resource`. The size of - * the policy is limited to a few 10s of KB. An empty policy is a - * valid policy but certain Cloud Platform services (such as Projects) - * might reject them. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.iam.v1.Policy|Policy}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/cloud_tasks.set_iam_policy.js - * region_tag:cloudtasks_v2_generated_CloudTasks_SetIamPolicy_async - */ + /** + * Sets the access control policy for a {@link protos.google.cloud.tasks.v2.Queue|Queue}. Replaces any existing + * policy. + * + * Note: The Cloud Console does not check queue-level IAM permissions yet. + * Project-level permissions are required to use the Cloud Console. + * + * Authorization requires the following + * [Google IAM](https://cloud.google.com/iam) permission on the specified + * resource parent: + * + * * `cloudtasks.queues.setIamPolicy` + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.resource + * REQUIRED: The resource for which the policy is being specified. + * See the operation documentation for the appropriate value for this field. + * @param {google.iam.v1.Policy} request.policy + * REQUIRED: The complete policy to be applied to the `resource`. The size of + * the policy is limited to a few 10s of KB. An empty policy is a + * valid policy but certain Cloud Platform services (such as Projects) + * might reject them. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.iam.v1.Policy|Policy}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/cloud_tasks.set_iam_policy.js + * region_tag:cloudtasks_v2_generated_CloudTasks_SetIamPolicy_async + */ setIamPolicy( - request?: protos.google.iam.v1.ISetIamPolicyRequest, - options?: CallOptions): - Promise<[ - protos.google.iam.v1.IPolicy, - protos.google.iam.v1.ISetIamPolicyRequest|undefined, {}|undefined - ]>; + request?: protos.google.iam.v1.ISetIamPolicyRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.iam.v1.IPolicy, + protos.google.iam.v1.ISetIamPolicyRequest | undefined, + {} | undefined, + ] + >; setIamPolicy( - request: protos.google.iam.v1.ISetIamPolicyRequest, - options: CallOptions, - callback: Callback< - protos.google.iam.v1.IPolicy, - protos.google.iam.v1.ISetIamPolicyRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.iam.v1.ISetIamPolicyRequest, + options: CallOptions, + callback: Callback< + protos.google.iam.v1.IPolicy, + protos.google.iam.v1.ISetIamPolicyRequest | null | undefined, + {} | null | undefined + >, + ): void; setIamPolicy( - request: protos.google.iam.v1.ISetIamPolicyRequest, - callback: Callback< - protos.google.iam.v1.IPolicy, - protos.google.iam.v1.ISetIamPolicyRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.iam.v1.ISetIamPolicyRequest, + callback: Callback< + protos.google.iam.v1.IPolicy, + protos.google.iam.v1.ISetIamPolicyRequest | null | undefined, + {} | null | undefined + >, + ): void; setIamPolicy( - request?: protos.google.iam.v1.ISetIamPolicyRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.iam.v1.IPolicy, - protos.google.iam.v1.ISetIamPolicyRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.iam.v1.ISetIamPolicyRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.iam.v1.IPolicy, - protos.google.iam.v1.ISetIamPolicyRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.iam.v1.IPolicy, - protos.google.iam.v1.ISetIamPolicyRequest|undefined, {}|undefined - ]>|void { + protos.google.iam.v1.ISetIamPolicyRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.iam.v1.IPolicy, + protos.google.iam.v1.ISetIamPolicyRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.iam.v1.IPolicy, + protos.google.iam.v1.ISetIamPolicyRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'resource': request.resource ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + resource: request.resource ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('setIamPolicy request %j', request); - const wrappedCallback: Callback< - protos.google.iam.v1.IPolicy, - protos.google.iam.v1.ISetIamPolicyRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.iam.v1.IPolicy, + protos.google.iam.v1.ISetIamPolicyRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('setIamPolicy response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.setIamPolicy(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.iam.v1.IPolicy, - protos.google.iam.v1.ISetIamPolicyRequest|undefined, - {}|undefined - ]) => { - this._log.info('setIamPolicy response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .setIamPolicy(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.iam.v1.IPolicy, + protos.google.iam.v1.ISetIamPolicyRequest | undefined, + {} | undefined, + ]) => { + this._log.info('setIamPolicy response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Returns permissions that a caller has on a {@link protos.google.cloud.tasks.v2.Queue|Queue}. - * If the resource does not exist, this will return an empty set of - * permissions, not a {@link protos.google.rpc.Code.NOT_FOUND|NOT_FOUND} error. - * - * Note: This operation is designed to be used for building permission-aware - * UIs and command-line tools, not for authorization checking. This operation - * may "fail open" without warning. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.resource - * REQUIRED: The resource for which the policy detail is being requested. - * See the operation documentation for the appropriate value for this field. - * @param {string[]} request.permissions - * The set of permissions to check for the `resource`. Permissions with - * wildcards (such as '*' or 'storage.*') are not allowed. For more - * information see - * [IAM Overview](https://cloud.google.com/iam/docs/overview#permissions). - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.iam.v1.TestIamPermissionsResponse|TestIamPermissionsResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/cloud_tasks.test_iam_permissions.js - * region_tag:cloudtasks_v2_generated_CloudTasks_TestIamPermissions_async - */ + /** + * Returns permissions that a caller has on a {@link protos.google.cloud.tasks.v2.Queue|Queue}. + * If the resource does not exist, this will return an empty set of + * permissions, not a {@link protos.google.rpc.Code.NOT_FOUND|NOT_FOUND} error. + * + * Note: This operation is designed to be used for building permission-aware + * UIs and command-line tools, not for authorization checking. This operation + * may "fail open" without warning. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.resource + * REQUIRED: The resource for which the policy detail is being requested. + * See the operation documentation for the appropriate value for this field. + * @param {string[]} request.permissions + * The set of permissions to check for the `resource`. Permissions with + * wildcards (such as '*' or 'storage.*') are not allowed. For more + * information see + * [IAM Overview](https://cloud.google.com/iam/docs/overview#permissions). + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.iam.v1.TestIamPermissionsResponse|TestIamPermissionsResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/cloud_tasks.test_iam_permissions.js + * region_tag:cloudtasks_v2_generated_CloudTasks_TestIamPermissions_async + */ testIamPermissions( - request?: protos.google.iam.v1.ITestIamPermissionsRequest, - options?: CallOptions): - Promise<[ - protos.google.iam.v1.ITestIamPermissionsResponse, - protos.google.iam.v1.ITestIamPermissionsRequest|undefined, {}|undefined - ]>; + request?: protos.google.iam.v1.ITestIamPermissionsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.iam.v1.ITestIamPermissionsResponse, + protos.google.iam.v1.ITestIamPermissionsRequest | undefined, + {} | undefined, + ] + >; testIamPermissions( - request: protos.google.iam.v1.ITestIamPermissionsRequest, - options: CallOptions, - callback: Callback< - protos.google.iam.v1.ITestIamPermissionsResponse, - protos.google.iam.v1.ITestIamPermissionsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.iam.v1.ITestIamPermissionsRequest, + options: CallOptions, + callback: Callback< + protos.google.iam.v1.ITestIamPermissionsResponse, + protos.google.iam.v1.ITestIamPermissionsRequest | null | undefined, + {} | null | undefined + >, + ): void; testIamPermissions( - request: protos.google.iam.v1.ITestIamPermissionsRequest, - callback: Callback< - protos.google.iam.v1.ITestIamPermissionsResponse, - protos.google.iam.v1.ITestIamPermissionsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.iam.v1.ITestIamPermissionsRequest, + callback: Callback< + protos.google.iam.v1.ITestIamPermissionsResponse, + protos.google.iam.v1.ITestIamPermissionsRequest | null | undefined, + {} | null | undefined + >, + ): void; testIamPermissions( - request?: protos.google.iam.v1.ITestIamPermissionsRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.iam.v1.ITestIamPermissionsRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.iam.v1.ITestIamPermissionsResponse, - protos.google.iam.v1.ITestIamPermissionsRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.iam.v1.ITestIamPermissionsResponse, - protos.google.iam.v1.ITestIamPermissionsRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.iam.v1.ITestIamPermissionsResponse, - protos.google.iam.v1.ITestIamPermissionsRequest|undefined, {}|undefined - ]>|void { + protos.google.iam.v1.ITestIamPermissionsRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.iam.v1.ITestIamPermissionsResponse, + protos.google.iam.v1.ITestIamPermissionsRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.iam.v1.ITestIamPermissionsResponse, + protos.google.iam.v1.ITestIamPermissionsRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'resource': request.resource ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + resource: request.resource ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('testIamPermissions request %j', request); - const wrappedCallback: Callback< - protos.google.iam.v1.ITestIamPermissionsResponse, - protos.google.iam.v1.ITestIamPermissionsRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.iam.v1.ITestIamPermissionsResponse, + protos.google.iam.v1.ITestIamPermissionsRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('testIamPermissions response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.testIamPermissions(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.iam.v1.ITestIamPermissionsResponse, - protos.google.iam.v1.ITestIamPermissionsRequest|undefined, - {}|undefined - ]) => { - this._log.info('testIamPermissions response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .testIamPermissions(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.iam.v1.ITestIamPermissionsResponse, + protos.google.iam.v1.ITestIamPermissionsRequest | undefined, + {} | undefined, + ]) => { + this._log.info('testIamPermissions response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Gets a task. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The task name. For example: - * `projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID/tasks/TASK_ID` - * @param {google.cloud.tasks.v2.Task.View} request.responseView - * The response_view specifies which subset of the {@link protos.google.cloud.tasks.v2.Task|Task} will be - * returned. - * - * By default response_view is {@link protos.google.cloud.tasks.v2.Task.View.BASIC|BASIC}; not all - * information is retrieved by default because some data, such as - * payloads, might be desirable to return only when needed because - * of its large size or because of the sensitivity of data that it - * contains. - * - * Authorization for {@link protos.google.cloud.tasks.v2.Task.View.FULL|FULL} requires - * `cloudtasks.tasks.fullView` [Google IAM](https://cloud.google.com/iam/) - * permission on the {@link protos.google.cloud.tasks.v2.Task|Task} resource. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.tasks.v2.Task|Task}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/cloud_tasks.get_task.js - * region_tag:cloudtasks_v2_generated_CloudTasks_GetTask_async - */ + /** + * Gets a task. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The task name. For example: + * `projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID/tasks/TASK_ID` + * @param {google.cloud.tasks.v2.Task.View} request.responseView + * The response_view specifies which subset of the {@link protos.google.cloud.tasks.v2.Task|Task} will be + * returned. + * + * By default response_view is {@link protos.google.cloud.tasks.v2.Task.View.BASIC|BASIC}; not all + * information is retrieved by default because some data, such as + * payloads, might be desirable to return only when needed because + * of its large size or because of the sensitivity of data that it + * contains. + * + * Authorization for {@link protos.google.cloud.tasks.v2.Task.View.FULL|FULL} requires + * `cloudtasks.tasks.fullView` [Google IAM](https://cloud.google.com/iam/) + * permission on the {@link protos.google.cloud.tasks.v2.Task|Task} resource. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.tasks.v2.Task|Task}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/cloud_tasks.get_task.js + * region_tag:cloudtasks_v2_generated_CloudTasks_GetTask_async + */ getTask( - request?: protos.google.cloud.tasks.v2.IGetTaskRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.tasks.v2.ITask, - protos.google.cloud.tasks.v2.IGetTaskRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.tasks.v2.IGetTaskRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.tasks.v2.ITask, + protos.google.cloud.tasks.v2.IGetTaskRequest | undefined, + {} | undefined, + ] + >; getTask( - request: protos.google.cloud.tasks.v2.IGetTaskRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.tasks.v2.ITask, - protos.google.cloud.tasks.v2.IGetTaskRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.tasks.v2.IGetTaskRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.tasks.v2.ITask, + protos.google.cloud.tasks.v2.IGetTaskRequest | null | undefined, + {} | null | undefined + >, + ): void; getTask( - request: protos.google.cloud.tasks.v2.IGetTaskRequest, - callback: Callback< - protos.google.cloud.tasks.v2.ITask, - protos.google.cloud.tasks.v2.IGetTaskRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.tasks.v2.IGetTaskRequest, + callback: Callback< + protos.google.cloud.tasks.v2.ITask, + protos.google.cloud.tasks.v2.IGetTaskRequest | null | undefined, + {} | null | undefined + >, + ): void; getTask( - request?: protos.google.cloud.tasks.v2.IGetTaskRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.tasks.v2.ITask, - protos.google.cloud.tasks.v2.IGetTaskRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.tasks.v2.IGetTaskRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.tasks.v2.ITask, - protos.google.cloud.tasks.v2.IGetTaskRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.tasks.v2.ITask, - protos.google.cloud.tasks.v2.IGetTaskRequest|undefined, {}|undefined - ]>|void { + protos.google.cloud.tasks.v2.IGetTaskRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.tasks.v2.ITask, + protos.google.cloud.tasks.v2.IGetTaskRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.tasks.v2.ITask, + protos.google.cloud.tasks.v2.IGetTaskRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getTask request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.tasks.v2.ITask, - protos.google.cloud.tasks.v2.IGetTaskRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.tasks.v2.ITask, + protos.google.cloud.tasks.v2.IGetTaskRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getTask response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getTask(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.tasks.v2.ITask, - protos.google.cloud.tasks.v2.IGetTaskRequest|undefined, - {}|undefined - ]) => { - this._log.info('getTask response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getTask(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.tasks.v2.ITask, + protos.google.cloud.tasks.v2.IGetTaskRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getTask response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Creates a task and adds it to a queue. - * - * Tasks cannot be updated after creation; there is no UpdateTask command. - * - * * The maximum task size is 100KB. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The queue name. For example: - * `projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID` - * - * The queue must already exist. - * @param {google.cloud.tasks.v2.Task} request.task - * Required. The task to add. - * - * Task names have the following format: - * `projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID/tasks/TASK_ID`. - * The user can optionally specify a task {@link protos.google.cloud.tasks.v2.Task.name|name}. If a - * name is not specified then the system will generate a random - * unique task id, which will be set in the task returned in the - * {@link protos.google.cloud.tasks.v2.Task.name|response}. - * - * If {@link protos.google.cloud.tasks.v2.Task.schedule_time|schedule_time} is not set or is in the - * past then Cloud Tasks will set it to the current time. - * - * Task De-duplication: - * - * Explicitly specifying a task ID enables task de-duplication. If - * a task's ID is identical to that of an existing task or a task - * that was deleted or executed recently then the call will fail - * with {@link protos.google.rpc.Code.ALREADY_EXISTS|ALREADY_EXISTS}. - * If the task's queue was created using Cloud Tasks, then another task with - * the same name can't be created for ~1hour after the original task was - * deleted or executed. If the task's queue was created using queue.yaml or - * queue.xml, then another task with the same name can't be created - * for ~9days after the original task was deleted or executed. - * - * Because there is an extra lookup cost to identify duplicate task - * names, these {@link protos.google.cloud.tasks.v2.CloudTasks.CreateTask|CreateTask} calls have significantly - * increased latency. Using hashed strings for the task id or for - * the prefix of the task id is recommended. Choosing task ids that - * are sequential or have sequential prefixes, for example using a - * timestamp, causes an increase in latency and error rates in all - * task commands. The infrastructure relies on an approximately - * uniform distribution of task ids to store and serve tasks - * efficiently. - * @param {google.cloud.tasks.v2.Task.View} request.responseView - * The response_view specifies which subset of the {@link protos.google.cloud.tasks.v2.Task|Task} will be - * returned. - * - * By default response_view is {@link protos.google.cloud.tasks.v2.Task.View.BASIC|BASIC}; not all - * information is retrieved by default because some data, such as - * payloads, might be desirable to return only when needed because - * of its large size or because of the sensitivity of data that it - * contains. - * - * Authorization for {@link protos.google.cloud.tasks.v2.Task.View.FULL|FULL} requires - * `cloudtasks.tasks.fullView` [Google IAM](https://cloud.google.com/iam/) - * permission on the {@link protos.google.cloud.tasks.v2.Task|Task} resource. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.tasks.v2.Task|Task}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/cloud_tasks.create_task.js - * region_tag:cloudtasks_v2_generated_CloudTasks_CreateTask_async - */ + /** + * Creates a task and adds it to a queue. + * + * Tasks cannot be updated after creation; there is no UpdateTask command. + * + * * The maximum task size is 100KB. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The queue name. For example: + * `projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID` + * + * The queue must already exist. + * @param {google.cloud.tasks.v2.Task} request.task + * Required. The task to add. + * + * Task names have the following format: + * `projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID/tasks/TASK_ID`. + * The user can optionally specify a task {@link protos.google.cloud.tasks.v2.Task.name|name}. If a + * name is not specified then the system will generate a random + * unique task id, which will be set in the task returned in the + * {@link protos.google.cloud.tasks.v2.Task.name|response}. + * + * If {@link protos.google.cloud.tasks.v2.Task.schedule_time|schedule_time} is not set or is in the + * past then Cloud Tasks will set it to the current time. + * + * Task De-duplication: + * + * Explicitly specifying a task ID enables task de-duplication. If + * a task's ID is identical to that of an existing task or a task + * that was deleted or executed recently then the call will fail + * with {@link protos.google.rpc.Code.ALREADY_EXISTS|ALREADY_EXISTS}. + * If the task's queue was created using Cloud Tasks, then another task with + * the same name can't be created for ~1hour after the original task was + * deleted or executed. If the task's queue was created using queue.yaml or + * queue.xml, then another task with the same name can't be created + * for ~9days after the original task was deleted or executed. + * + * Because there is an extra lookup cost to identify duplicate task + * names, these {@link protos.google.cloud.tasks.v2.CloudTasks.CreateTask|CreateTask} calls have significantly + * increased latency. Using hashed strings for the task id or for + * the prefix of the task id is recommended. Choosing task ids that + * are sequential or have sequential prefixes, for example using a + * timestamp, causes an increase in latency and error rates in all + * task commands. The infrastructure relies on an approximately + * uniform distribution of task ids to store and serve tasks + * efficiently. + * @param {google.cloud.tasks.v2.Task.View} request.responseView + * The response_view specifies which subset of the {@link protos.google.cloud.tasks.v2.Task|Task} will be + * returned. + * + * By default response_view is {@link protos.google.cloud.tasks.v2.Task.View.BASIC|BASIC}; not all + * information is retrieved by default because some data, such as + * payloads, might be desirable to return only when needed because + * of its large size or because of the sensitivity of data that it + * contains. + * + * Authorization for {@link protos.google.cloud.tasks.v2.Task.View.FULL|FULL} requires + * `cloudtasks.tasks.fullView` [Google IAM](https://cloud.google.com/iam/) + * permission on the {@link protos.google.cloud.tasks.v2.Task|Task} resource. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.tasks.v2.Task|Task}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/cloud_tasks.create_task.js + * region_tag:cloudtasks_v2_generated_CloudTasks_CreateTask_async + */ createTask( - request?: protos.google.cloud.tasks.v2.ICreateTaskRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.tasks.v2.ITask, - protos.google.cloud.tasks.v2.ICreateTaskRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.tasks.v2.ICreateTaskRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.tasks.v2.ITask, + protos.google.cloud.tasks.v2.ICreateTaskRequest | undefined, + {} | undefined, + ] + >; createTask( - request: protos.google.cloud.tasks.v2.ICreateTaskRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.tasks.v2.ITask, - protos.google.cloud.tasks.v2.ICreateTaskRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.tasks.v2.ICreateTaskRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.tasks.v2.ITask, + protos.google.cloud.tasks.v2.ICreateTaskRequest | null | undefined, + {} | null | undefined + >, + ): void; createTask( - request: protos.google.cloud.tasks.v2.ICreateTaskRequest, - callback: Callback< - protos.google.cloud.tasks.v2.ITask, - protos.google.cloud.tasks.v2.ICreateTaskRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.tasks.v2.ICreateTaskRequest, + callback: Callback< + protos.google.cloud.tasks.v2.ITask, + protos.google.cloud.tasks.v2.ICreateTaskRequest | null | undefined, + {} | null | undefined + >, + ): void; createTask( - request?: protos.google.cloud.tasks.v2.ICreateTaskRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.cloud.tasks.v2.ICreateTaskRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.tasks.v2.ITask, - protos.google.cloud.tasks.v2.ICreateTaskRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.cloud.tasks.v2.ITask, - protos.google.cloud.tasks.v2.ICreateTaskRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.tasks.v2.ITask, - protos.google.cloud.tasks.v2.ICreateTaskRequest|undefined, {}|undefined - ]>|void { + protos.google.cloud.tasks.v2.ICreateTaskRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.tasks.v2.ITask, + protos.google.cloud.tasks.v2.ICreateTaskRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.tasks.v2.ITask, + protos.google.cloud.tasks.v2.ICreateTaskRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('createTask request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.tasks.v2.ITask, - protos.google.cloud.tasks.v2.ICreateTaskRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.tasks.v2.ITask, + protos.google.cloud.tasks.v2.ICreateTaskRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createTask response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.createTask(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.tasks.v2.ITask, - protos.google.cloud.tasks.v2.ICreateTaskRequest|undefined, - {}|undefined - ]) => { - this._log.info('createTask response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createTask(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.tasks.v2.ITask, + protos.google.cloud.tasks.v2.ICreateTaskRequest | undefined, + {} | undefined, + ]) => { + this._log.info('createTask response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Deletes a task. - * - * A task can be deleted if it is scheduled or dispatched. A task - * cannot be deleted if it has executed successfully or permanently - * failed. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The task name. For example: - * `projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID/tasks/TASK_ID` - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/cloud_tasks.delete_task.js - * region_tag:cloudtasks_v2_generated_CloudTasks_DeleteTask_async - */ + /** + * Deletes a task. + * + * A task can be deleted if it is scheduled or dispatched. A task + * cannot be deleted if it has executed successfully or permanently + * failed. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The task name. For example: + * `projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID/tasks/TASK_ID` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/cloud_tasks.delete_task.js + * region_tag:cloudtasks_v2_generated_CloudTasks_DeleteTask_async + */ deleteTask( - request?: protos.google.cloud.tasks.v2.IDeleteTaskRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.cloud.tasks.v2.IDeleteTaskRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.tasks.v2.IDeleteTaskRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.cloud.tasks.v2.IDeleteTaskRequest | undefined, + {} | undefined, + ] + >; deleteTask( - request: protos.google.cloud.tasks.v2.IDeleteTaskRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.cloud.tasks.v2.IDeleteTaskRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.tasks.v2.IDeleteTaskRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.cloud.tasks.v2.IDeleteTaskRequest | null | undefined, + {} | null | undefined + >, + ): void; deleteTask( - request: protos.google.cloud.tasks.v2.IDeleteTaskRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.cloud.tasks.v2.IDeleteTaskRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.tasks.v2.IDeleteTaskRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.cloud.tasks.v2.IDeleteTaskRequest | null | undefined, + {} | null | undefined + >, + ): void; deleteTask( - request?: protos.google.cloud.tasks.v2.IDeleteTaskRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.protobuf.IEmpty, - protos.google.cloud.tasks.v2.IDeleteTaskRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.tasks.v2.IDeleteTaskRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.cloud.tasks.v2.IDeleteTaskRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.cloud.tasks.v2.IDeleteTaskRequest|undefined, {}|undefined - ]>|void { + protos.google.cloud.tasks.v2.IDeleteTaskRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + protos.google.cloud.tasks.v2.IDeleteTaskRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.cloud.tasks.v2.IDeleteTaskRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('deleteTask request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.cloud.tasks.v2.IDeleteTaskRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + protos.google.cloud.tasks.v2.IDeleteTaskRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteTask response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.deleteTask(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.cloud.tasks.v2.IDeleteTaskRequest|undefined, - {}|undefined - ]) => { - this._log.info('deleteTask response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteTask(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.cloud.tasks.v2.IDeleteTaskRequest | undefined, + {} | undefined, + ]) => { + this._log.info('deleteTask response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Forces a task to run now. - * - * When this method is called, Cloud Tasks will dispatch the task, even if - * the task is already running, the queue has reached its {@link protos.google.cloud.tasks.v2.RateLimits|RateLimits} or - * is {@link protos.google.cloud.tasks.v2.Queue.State.PAUSED|PAUSED}. - * - * This command is meant to be used for manual debugging. For - * example, {@link protos.google.cloud.tasks.v2.CloudTasks.RunTask|RunTask} can be used to retry a failed - * task after a fix has been made or to manually force a task to be - * dispatched now. - * - * The dispatched task is returned. That is, the task that is returned - * contains the {@link protos.Task.status|status} after the task is dispatched but - * before the task is received by its target. - * - * If Cloud Tasks receives a successful response from the task's - * target, then the task will be deleted; otherwise the task's - * {@link protos.google.cloud.tasks.v2.Task.schedule_time|schedule_time} will be reset to the time that - * {@link protos.google.cloud.tasks.v2.CloudTasks.RunTask|RunTask} was called plus the retry delay specified - * in the queue's {@link protos.google.cloud.tasks.v2.RetryConfig|RetryConfig}. - * - * {@link protos.google.cloud.tasks.v2.CloudTasks.RunTask|RunTask} returns - * {@link protos.google.rpc.Code.NOT_FOUND|NOT_FOUND} when it is called on a - * task that has already succeeded or permanently failed. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The task name. For example: - * `projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID/tasks/TASK_ID` - * @param {google.cloud.tasks.v2.Task.View} request.responseView - * The response_view specifies which subset of the {@link protos.google.cloud.tasks.v2.Task|Task} will be - * returned. - * - * By default response_view is {@link protos.google.cloud.tasks.v2.Task.View.BASIC|BASIC}; not all - * information is retrieved by default because some data, such as - * payloads, might be desirable to return only when needed because - * of its large size or because of the sensitivity of data that it - * contains. - * - * Authorization for {@link protos.google.cloud.tasks.v2.Task.View.FULL|FULL} requires - * `cloudtasks.tasks.fullView` [Google IAM](https://cloud.google.com/iam/) - * permission on the {@link protos.google.cloud.tasks.v2.Task|Task} resource. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.tasks.v2.Task|Task}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v2/cloud_tasks.run_task.js - * region_tag:cloudtasks_v2_generated_CloudTasks_RunTask_async - */ + /** + * Forces a task to run now. + * + * When this method is called, Cloud Tasks will dispatch the task, even if + * the task is already running, the queue has reached its {@link protos.google.cloud.tasks.v2.RateLimits|RateLimits} or + * is {@link protos.google.cloud.tasks.v2.Queue.State.PAUSED|PAUSED}. + * + * This command is meant to be used for manual debugging. For + * example, {@link protos.google.cloud.tasks.v2.CloudTasks.RunTask|RunTask} can be used to retry a failed + * task after a fix has been made or to manually force a task to be + * dispatched now. + * + * The dispatched task is returned. That is, the task that is returned + * contains the {@link protos.Task.status|status} after the task is dispatched but + * before the task is received by its target. + * + * If Cloud Tasks receives a successful response from the task's + * target, then the task will be deleted; otherwise the task's + * {@link protos.google.cloud.tasks.v2.Task.schedule_time|schedule_time} will be reset to the time that + * {@link protos.google.cloud.tasks.v2.CloudTasks.RunTask|RunTask} was called plus the retry delay specified + * in the queue's {@link protos.google.cloud.tasks.v2.RetryConfig|RetryConfig}. + * + * {@link protos.google.cloud.tasks.v2.CloudTasks.RunTask|RunTask} returns + * {@link protos.google.rpc.Code.NOT_FOUND|NOT_FOUND} when it is called on a + * task that has already succeeded or permanently failed. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The task name. For example: + * `projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID/tasks/TASK_ID` + * @param {google.cloud.tasks.v2.Task.View} request.responseView + * The response_view specifies which subset of the {@link protos.google.cloud.tasks.v2.Task|Task} will be + * returned. + * + * By default response_view is {@link protos.google.cloud.tasks.v2.Task.View.BASIC|BASIC}; not all + * information is retrieved by default because some data, such as + * payloads, might be desirable to return only when needed because + * of its large size or because of the sensitivity of data that it + * contains. + * + * Authorization for {@link protos.google.cloud.tasks.v2.Task.View.FULL|FULL} requires + * `cloudtasks.tasks.fullView` [Google IAM](https://cloud.google.com/iam/) + * permission on the {@link protos.google.cloud.tasks.v2.Task|Task} resource. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.tasks.v2.Task|Task}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v2/cloud_tasks.run_task.js + * region_tag:cloudtasks_v2_generated_CloudTasks_RunTask_async + */ runTask( - request?: protos.google.cloud.tasks.v2.IRunTaskRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.tasks.v2.ITask, - protos.google.cloud.tasks.v2.IRunTaskRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.tasks.v2.IRunTaskRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.tasks.v2.ITask, + protos.google.cloud.tasks.v2.IRunTaskRequest | undefined, + {} | undefined, + ] + >; runTask( - request: protos.google.cloud.tasks.v2.IRunTaskRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.tasks.v2.ITask, - protos.google.cloud.tasks.v2.IRunTaskRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.tasks.v2.IRunTaskRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.tasks.v2.ITask, + protos.google.cloud.tasks.v2.IRunTaskRequest | null | undefined, + {} | null | undefined + >, + ): void; runTask( - request: protos.google.cloud.tasks.v2.IRunTaskRequest, - callback: Callback< - protos.google.cloud.tasks.v2.ITask, - protos.google.cloud.tasks.v2.IRunTaskRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.tasks.v2.IRunTaskRequest, + callback: Callback< + protos.google.cloud.tasks.v2.ITask, + protos.google.cloud.tasks.v2.IRunTaskRequest | null | undefined, + {} | null | undefined + >, + ): void; runTask( - request?: protos.google.cloud.tasks.v2.IRunTaskRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.tasks.v2.ITask, - protos.google.cloud.tasks.v2.IRunTaskRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.tasks.v2.IRunTaskRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.tasks.v2.ITask, - protos.google.cloud.tasks.v2.IRunTaskRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.tasks.v2.ITask, - protos.google.cloud.tasks.v2.IRunTaskRequest|undefined, {}|undefined - ]>|void { + protos.google.cloud.tasks.v2.IRunTaskRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.tasks.v2.ITask, + protos.google.cloud.tasks.v2.IRunTaskRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.tasks.v2.ITask, + protos.google.cloud.tasks.v2.IRunTaskRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('runTask request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.tasks.v2.ITask, - protos.google.cloud.tasks.v2.IRunTaskRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.tasks.v2.ITask, + protos.google.cloud.tasks.v2.IRunTaskRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('runTask response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.runTask(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.tasks.v2.ITask, - protos.google.cloud.tasks.v2.IRunTaskRequest|undefined, - {}|undefined - ]) => { - this._log.info('runTask response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .runTask(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.tasks.v2.ITask, + protos.google.cloud.tasks.v2.IRunTaskRequest | undefined, + {} | undefined, + ]) => { + this._log.info('runTask response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } - /** - * Lists queues. - * - * Queues are returned in lexicographical order. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The location name. - * For example: `projects/PROJECT_ID/locations/LOCATION_ID` - * @param {string} request.filter - * `filter` can be used to specify a subset of queues. Any {@link protos.google.cloud.tasks.v2.Queue|Queue} - * field can be used as a filter and several operators as supported. - * For example: `<=, <, >=, >, !=, =, :`. The filter syntax is the same as - * described in - * [Stackdriver's Advanced Logs - * Filters](https://cloud.google.com/logging/docs/view/advanced_filters). - * - * Sample filter "state: PAUSED". - * - * Note that using filters might cause fewer queues than the - * requested page_size to be returned. - * @param {number} request.pageSize - * Requested page size. - * - * The maximum page size is 9800. If unspecified, the page size will - * be the maximum. Fewer queues than requested might be returned, - * even if more queues exist; use the - * {@link protos.google.cloud.tasks.v2.ListQueuesResponse.next_page_token|next_page_token} in the - * response to determine if more queues exist. - * @param {string} request.pageToken - * A token identifying the page of results to return. - * - * To request the first page results, page_token must be empty. To - * request the next page of results, page_token must be the value of - * {@link protos.google.cloud.tasks.v2.ListQueuesResponse.next_page_token|next_page_token} returned - * from the previous call to {@link protos.google.cloud.tasks.v2.CloudTasks.ListQueues|ListQueues} - * method. It is an error to switch the value of the - * {@link protos.google.cloud.tasks.v2.ListQueuesRequest.filter|filter} while iterating through pages. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.cloud.tasks.v2.Queue|Queue}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `listQueuesAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Lists queues. + * + * Queues are returned in lexicographical order. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The location name. + * For example: `projects/PROJECT_ID/locations/LOCATION_ID` + * @param {string} request.filter + * `filter` can be used to specify a subset of queues. Any {@link protos.google.cloud.tasks.v2.Queue|Queue} + * field can be used as a filter and several operators as supported. + * For example: `<=, <, >=, >, !=, =, :`. The filter syntax is the same as + * described in + * [Stackdriver's Advanced Logs + * Filters](https://cloud.google.com/logging/docs/view/advanced_filters). + * + * Sample filter "state: PAUSED". + * + * Note that using filters might cause fewer queues than the + * requested page_size to be returned. + * @param {number} request.pageSize + * Requested page size. + * + * The maximum page size is 9800. If unspecified, the page size will + * be the maximum. Fewer queues than requested might be returned, + * even if more queues exist; use the + * {@link protos.google.cloud.tasks.v2.ListQueuesResponse.next_page_token|next_page_token} in the + * response to determine if more queues exist. + * @param {string} request.pageToken + * A token identifying the page of results to return. + * + * To request the first page results, page_token must be empty. To + * request the next page of results, page_token must be the value of + * {@link protos.google.cloud.tasks.v2.ListQueuesResponse.next_page_token|next_page_token} returned + * from the previous call to {@link protos.google.cloud.tasks.v2.CloudTasks.ListQueues|ListQueues} + * method. It is an error to switch the value of the + * {@link protos.google.cloud.tasks.v2.ListQueuesRequest.filter|filter} while iterating through pages. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.cloud.tasks.v2.Queue|Queue}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listQueuesAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listQueues( - request?: protos.google.cloud.tasks.v2.IListQueuesRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.tasks.v2.IQueue[], - protos.google.cloud.tasks.v2.IListQueuesRequest|null, - protos.google.cloud.tasks.v2.IListQueuesResponse - ]>; + request?: protos.google.cloud.tasks.v2.IListQueuesRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.tasks.v2.IQueue[], + protos.google.cloud.tasks.v2.IListQueuesRequest | null, + protos.google.cloud.tasks.v2.IListQueuesResponse, + ] + >; listQueues( - request: protos.google.cloud.tasks.v2.IListQueuesRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.cloud.tasks.v2.IListQueuesRequest, - protos.google.cloud.tasks.v2.IListQueuesResponse|null|undefined, - protos.google.cloud.tasks.v2.IQueue>): void; + request: protos.google.cloud.tasks.v2.IListQueuesRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.cloud.tasks.v2.IListQueuesRequest, + protos.google.cloud.tasks.v2.IListQueuesResponse | null | undefined, + protos.google.cloud.tasks.v2.IQueue + >, + ): void; listQueues( - request: protos.google.cloud.tasks.v2.IListQueuesRequest, - callback: PaginationCallback< - protos.google.cloud.tasks.v2.IListQueuesRequest, - protos.google.cloud.tasks.v2.IListQueuesResponse|null|undefined, - protos.google.cloud.tasks.v2.IQueue>): void; + request: protos.google.cloud.tasks.v2.IListQueuesRequest, + callback: PaginationCallback< + protos.google.cloud.tasks.v2.IListQueuesRequest, + protos.google.cloud.tasks.v2.IListQueuesResponse | null | undefined, + protos.google.cloud.tasks.v2.IQueue + >, + ): void; listQueues( - request?: protos.google.cloud.tasks.v2.IListQueuesRequest, - optionsOrCallback?: CallOptions|PaginationCallback< + request?: protos.google.cloud.tasks.v2.IListQueuesRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.cloud.tasks.v2.IListQueuesRequest, - protos.google.cloud.tasks.v2.IListQueuesResponse|null|undefined, - protos.google.cloud.tasks.v2.IQueue>, - callback?: PaginationCallback< - protos.google.cloud.tasks.v2.IListQueuesRequest, - protos.google.cloud.tasks.v2.IListQueuesResponse|null|undefined, - protos.google.cloud.tasks.v2.IQueue>): - Promise<[ - protos.google.cloud.tasks.v2.IQueue[], - protos.google.cloud.tasks.v2.IListQueuesRequest|null, - protos.google.cloud.tasks.v2.IListQueuesResponse - ]>|void { + protos.google.cloud.tasks.v2.IListQueuesResponse | null | undefined, + protos.google.cloud.tasks.v2.IQueue + >, + callback?: PaginationCallback< + protos.google.cloud.tasks.v2.IListQueuesRequest, + protos.google.cloud.tasks.v2.IListQueuesResponse | null | undefined, + protos.google.cloud.tasks.v2.IQueue + >, + ): Promise< + [ + protos.google.cloud.tasks.v2.IQueue[], + protos.google.cloud.tasks.v2.IListQueuesRequest | null, + protos.google.cloud.tasks.v2.IListQueuesResponse, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.cloud.tasks.v2.IListQueuesRequest, - protos.google.cloud.tasks.v2.IListQueuesResponse|null|undefined, - protos.google.cloud.tasks.v2.IQueue>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.cloud.tasks.v2.IListQueuesRequest, + protos.google.cloud.tasks.v2.IListQueuesResponse | null | undefined, + protos.google.cloud.tasks.v2.IQueue + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listQueues values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -2007,278 +2507,297 @@ export class CloudTasksClient { this._log.info('listQueues request %j', request); return this.innerApiCalls .listQueues(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.cloud.tasks.v2.IQueue[], - protos.google.cloud.tasks.v2.IListQueuesRequest|null, - protos.google.cloud.tasks.v2.IListQueuesResponse - ]) => { - this._log.info('listQueues values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.cloud.tasks.v2.IQueue[], + protos.google.cloud.tasks.v2.IListQueuesRequest | null, + protos.google.cloud.tasks.v2.IListQueuesResponse, + ]) => { + this._log.info('listQueues values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listQueues`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The location name. - * For example: `projects/PROJECT_ID/locations/LOCATION_ID` - * @param {string} request.filter - * `filter` can be used to specify a subset of queues. Any {@link protos.google.cloud.tasks.v2.Queue|Queue} - * field can be used as a filter and several operators as supported. - * For example: `<=, <, >=, >, !=, =, :`. The filter syntax is the same as - * described in - * [Stackdriver's Advanced Logs - * Filters](https://cloud.google.com/logging/docs/view/advanced_filters). - * - * Sample filter "state: PAUSED". - * - * Note that using filters might cause fewer queues than the - * requested page_size to be returned. - * @param {number} request.pageSize - * Requested page size. - * - * The maximum page size is 9800. If unspecified, the page size will - * be the maximum. Fewer queues than requested might be returned, - * even if more queues exist; use the - * {@link protos.google.cloud.tasks.v2.ListQueuesResponse.next_page_token|next_page_token} in the - * response to determine if more queues exist. - * @param {string} request.pageToken - * A token identifying the page of results to return. - * - * To request the first page results, page_token must be empty. To - * request the next page of results, page_token must be the value of - * {@link protos.google.cloud.tasks.v2.ListQueuesResponse.next_page_token|next_page_token} returned - * from the previous call to {@link protos.google.cloud.tasks.v2.CloudTasks.ListQueues|ListQueues} - * method. It is an error to switch the value of the - * {@link protos.google.cloud.tasks.v2.ListQueuesRequest.filter|filter} while iterating through pages. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.cloud.tasks.v2.Queue|Queue} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `listQueuesAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `listQueues`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The location name. + * For example: `projects/PROJECT_ID/locations/LOCATION_ID` + * @param {string} request.filter + * `filter` can be used to specify a subset of queues. Any {@link protos.google.cloud.tasks.v2.Queue|Queue} + * field can be used as a filter and several operators as supported. + * For example: `<=, <, >=, >, !=, =, :`. The filter syntax is the same as + * described in + * [Stackdriver's Advanced Logs + * Filters](https://cloud.google.com/logging/docs/view/advanced_filters). + * + * Sample filter "state: PAUSED". + * + * Note that using filters might cause fewer queues than the + * requested page_size to be returned. + * @param {number} request.pageSize + * Requested page size. + * + * The maximum page size is 9800. If unspecified, the page size will + * be the maximum. Fewer queues than requested might be returned, + * even if more queues exist; use the + * {@link protos.google.cloud.tasks.v2.ListQueuesResponse.next_page_token|next_page_token} in the + * response to determine if more queues exist. + * @param {string} request.pageToken + * A token identifying the page of results to return. + * + * To request the first page results, page_token must be empty. To + * request the next page of results, page_token must be the value of + * {@link protos.google.cloud.tasks.v2.ListQueuesResponse.next_page_token|next_page_token} returned + * from the previous call to {@link protos.google.cloud.tasks.v2.CloudTasks.ListQueues|ListQueues} + * method. It is an error to switch the value of the + * {@link protos.google.cloud.tasks.v2.ListQueuesRequest.filter|filter} while iterating through pages. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.cloud.tasks.v2.Queue|Queue} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listQueuesAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listQueuesStream( - request?: protos.google.cloud.tasks.v2.IListQueuesRequest, - options?: CallOptions): - Transform{ + request?: protos.google.cloud.tasks.v2.IListQueuesRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); const defaultCallSettings = this._defaults['listQueues']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listQueues stream %j', request); return this.descriptors.page.listQueues.createStream( this.innerApiCalls.listQueues as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listQueues`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The location name. - * For example: `projects/PROJECT_ID/locations/LOCATION_ID` - * @param {string} request.filter - * `filter` can be used to specify a subset of queues. Any {@link protos.google.cloud.tasks.v2.Queue|Queue} - * field can be used as a filter and several operators as supported. - * For example: `<=, <, >=, >, !=, =, :`. The filter syntax is the same as - * described in - * [Stackdriver's Advanced Logs - * Filters](https://cloud.google.com/logging/docs/view/advanced_filters). - * - * Sample filter "state: PAUSED". - * - * Note that using filters might cause fewer queues than the - * requested page_size to be returned. - * @param {number} request.pageSize - * Requested page size. - * - * The maximum page size is 9800. If unspecified, the page size will - * be the maximum. Fewer queues than requested might be returned, - * even if more queues exist; use the - * {@link protos.google.cloud.tasks.v2.ListQueuesResponse.next_page_token|next_page_token} in the - * response to determine if more queues exist. - * @param {string} request.pageToken - * A token identifying the page of results to return. - * - * To request the first page results, page_token must be empty. To - * request the next page of results, page_token must be the value of - * {@link protos.google.cloud.tasks.v2.ListQueuesResponse.next_page_token|next_page_token} returned - * from the previous call to {@link protos.google.cloud.tasks.v2.CloudTasks.ListQueues|ListQueues} - * method. It is an error to switch the value of the - * {@link protos.google.cloud.tasks.v2.ListQueuesRequest.filter|filter} while iterating through pages. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.cloud.tasks.v2.Queue|Queue}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v2/cloud_tasks.list_queues.js - * region_tag:cloudtasks_v2_generated_CloudTasks_ListQueues_async - */ + /** + * Equivalent to `listQueues`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The location name. + * For example: `projects/PROJECT_ID/locations/LOCATION_ID` + * @param {string} request.filter + * `filter` can be used to specify a subset of queues. Any {@link protos.google.cloud.tasks.v2.Queue|Queue} + * field can be used as a filter and several operators as supported. + * For example: `<=, <, >=, >, !=, =, :`. The filter syntax is the same as + * described in + * [Stackdriver's Advanced Logs + * Filters](https://cloud.google.com/logging/docs/view/advanced_filters). + * + * Sample filter "state: PAUSED". + * + * Note that using filters might cause fewer queues than the + * requested page_size to be returned. + * @param {number} request.pageSize + * Requested page size. + * + * The maximum page size is 9800. If unspecified, the page size will + * be the maximum. Fewer queues than requested might be returned, + * even if more queues exist; use the + * {@link protos.google.cloud.tasks.v2.ListQueuesResponse.next_page_token|next_page_token} in the + * response to determine if more queues exist. + * @param {string} request.pageToken + * A token identifying the page of results to return. + * + * To request the first page results, page_token must be empty. To + * request the next page of results, page_token must be the value of + * {@link protos.google.cloud.tasks.v2.ListQueuesResponse.next_page_token|next_page_token} returned + * from the previous call to {@link protos.google.cloud.tasks.v2.CloudTasks.ListQueues|ListQueues} + * method. It is an error to switch the value of the + * {@link protos.google.cloud.tasks.v2.ListQueuesRequest.filter|filter} while iterating through pages. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.cloud.tasks.v2.Queue|Queue}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v2/cloud_tasks.list_queues.js + * region_tag:cloudtasks_v2_generated_CloudTasks_ListQueues_async + */ listQueuesAsync( - request?: protos.google.cloud.tasks.v2.IListQueuesRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.cloud.tasks.v2.IListQueuesRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); const defaultCallSettings = this._defaults['listQueues']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listQueues iterate %j', request); return this.descriptors.page.listQueues.asyncIterate( this.innerApiCalls['listQueues'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } - /** - * Lists the tasks in a queue. - * - * By default, only the {@link protos.google.cloud.tasks.v2.Task.View.BASIC|BASIC} view is retrieved - * due to performance considerations; - * {@link protos.google.cloud.tasks.v2.ListTasksRequest.response_view|response_view} controls the - * subset of information which is returned. - * - * The tasks may be returned in any order. The ordering may change at any - * time. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The queue name. For example: - * `projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID` - * @param {google.cloud.tasks.v2.Task.View} request.responseView - * The response_view specifies which subset of the {@link protos.google.cloud.tasks.v2.Task|Task} will be - * returned. - * - * By default response_view is {@link protos.google.cloud.tasks.v2.Task.View.BASIC|BASIC}; not all - * information is retrieved by default because some data, such as - * payloads, might be desirable to return only when needed because - * of its large size or because of the sensitivity of data that it - * contains. - * - * Authorization for {@link protos.google.cloud.tasks.v2.Task.View.FULL|FULL} requires - * `cloudtasks.tasks.fullView` [Google IAM](https://cloud.google.com/iam/) - * permission on the {@link protos.google.cloud.tasks.v2.Task|Task} resource. - * @param {number} request.pageSize - * Maximum page size. - * - * Fewer tasks than requested might be returned, even if more tasks exist; use - * {@link protos.google.cloud.tasks.v2.ListTasksResponse.next_page_token|next_page_token} in the response to - * determine if more tasks exist. - * - * The maximum page size is 1000. If unspecified, the page size will be the - * maximum. - * @param {string} request.pageToken - * A token identifying the page of results to return. - * - * To request the first page results, page_token must be empty. To - * request the next page of results, page_token must be the value of - * {@link protos.google.cloud.tasks.v2.ListTasksResponse.next_page_token|next_page_token} returned - * from the previous call to {@link protos.google.cloud.tasks.v2.CloudTasks.ListTasks|ListTasks} - * method. - * - * The page token is valid for only 2 hours. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.cloud.tasks.v2.Task|Task}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `listTasksAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Lists the tasks in a queue. + * + * By default, only the {@link protos.google.cloud.tasks.v2.Task.View.BASIC|BASIC} view is retrieved + * due to performance considerations; + * {@link protos.google.cloud.tasks.v2.ListTasksRequest.response_view|response_view} controls the + * subset of information which is returned. + * + * The tasks may be returned in any order. The ordering may change at any + * time. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The queue name. For example: + * `projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID` + * @param {google.cloud.tasks.v2.Task.View} request.responseView + * The response_view specifies which subset of the {@link protos.google.cloud.tasks.v2.Task|Task} will be + * returned. + * + * By default response_view is {@link protos.google.cloud.tasks.v2.Task.View.BASIC|BASIC}; not all + * information is retrieved by default because some data, such as + * payloads, might be desirable to return only when needed because + * of its large size or because of the sensitivity of data that it + * contains. + * + * Authorization for {@link protos.google.cloud.tasks.v2.Task.View.FULL|FULL} requires + * `cloudtasks.tasks.fullView` [Google IAM](https://cloud.google.com/iam/) + * permission on the {@link protos.google.cloud.tasks.v2.Task|Task} resource. + * @param {number} request.pageSize + * Maximum page size. + * + * Fewer tasks than requested might be returned, even if more tasks exist; use + * {@link protos.google.cloud.tasks.v2.ListTasksResponse.next_page_token|next_page_token} in the response to + * determine if more tasks exist. + * + * The maximum page size is 1000. If unspecified, the page size will be the + * maximum. + * @param {string} request.pageToken + * A token identifying the page of results to return. + * + * To request the first page results, page_token must be empty. To + * request the next page of results, page_token must be the value of + * {@link protos.google.cloud.tasks.v2.ListTasksResponse.next_page_token|next_page_token} returned + * from the previous call to {@link protos.google.cloud.tasks.v2.CloudTasks.ListTasks|ListTasks} + * method. + * + * The page token is valid for only 2 hours. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.cloud.tasks.v2.Task|Task}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listTasksAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listTasks( - request?: protos.google.cloud.tasks.v2.IListTasksRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.tasks.v2.ITask[], - protos.google.cloud.tasks.v2.IListTasksRequest|null, - protos.google.cloud.tasks.v2.IListTasksResponse - ]>; + request?: protos.google.cloud.tasks.v2.IListTasksRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.tasks.v2.ITask[], + protos.google.cloud.tasks.v2.IListTasksRequest | null, + protos.google.cloud.tasks.v2.IListTasksResponse, + ] + >; listTasks( - request: protos.google.cloud.tasks.v2.IListTasksRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.cloud.tasks.v2.IListTasksRequest, - protos.google.cloud.tasks.v2.IListTasksResponse|null|undefined, - protos.google.cloud.tasks.v2.ITask>): void; + request: protos.google.cloud.tasks.v2.IListTasksRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.cloud.tasks.v2.IListTasksRequest, + protos.google.cloud.tasks.v2.IListTasksResponse | null | undefined, + protos.google.cloud.tasks.v2.ITask + >, + ): void; listTasks( - request: protos.google.cloud.tasks.v2.IListTasksRequest, - callback: PaginationCallback< - protos.google.cloud.tasks.v2.IListTasksRequest, - protos.google.cloud.tasks.v2.IListTasksResponse|null|undefined, - protos.google.cloud.tasks.v2.ITask>): void; + request: protos.google.cloud.tasks.v2.IListTasksRequest, + callback: PaginationCallback< + protos.google.cloud.tasks.v2.IListTasksRequest, + protos.google.cloud.tasks.v2.IListTasksResponse | null | undefined, + protos.google.cloud.tasks.v2.ITask + >, + ): void; listTasks( - request?: protos.google.cloud.tasks.v2.IListTasksRequest, - optionsOrCallback?: CallOptions|PaginationCallback< - protos.google.cloud.tasks.v2.IListTasksRequest, - protos.google.cloud.tasks.v2.IListTasksResponse|null|undefined, - protos.google.cloud.tasks.v2.ITask>, - callback?: PaginationCallback< + request?: protos.google.cloud.tasks.v2.IListTasksRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.cloud.tasks.v2.IListTasksRequest, - protos.google.cloud.tasks.v2.IListTasksResponse|null|undefined, - protos.google.cloud.tasks.v2.ITask>): - Promise<[ - protos.google.cloud.tasks.v2.ITask[], - protos.google.cloud.tasks.v2.IListTasksRequest|null, - protos.google.cloud.tasks.v2.IListTasksResponse - ]>|void { + protos.google.cloud.tasks.v2.IListTasksResponse | null | undefined, + protos.google.cloud.tasks.v2.ITask + >, + callback?: PaginationCallback< + protos.google.cloud.tasks.v2.IListTasksRequest, + protos.google.cloud.tasks.v2.IListTasksResponse | null | undefined, + protos.google.cloud.tasks.v2.ITask + >, + ): Promise< + [ + protos.google.cloud.tasks.v2.ITask[], + protos.google.cloud.tasks.v2.IListTasksRequest | null, + protos.google.cloud.tasks.v2.IListTasksResponse, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.cloud.tasks.v2.IListTasksRequest, - protos.google.cloud.tasks.v2.IListTasksResponse|null|undefined, - protos.google.cloud.tasks.v2.ITask>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.cloud.tasks.v2.IListTasksRequest, + protos.google.cloud.tasks.v2.IListTasksResponse | null | undefined, + protos.google.cloud.tasks.v2.ITask + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listTasks values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -2287,164 +2806,168 @@ export class CloudTasksClient { this._log.info('listTasks request %j', request); return this.innerApiCalls .listTasks(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.cloud.tasks.v2.ITask[], - protos.google.cloud.tasks.v2.IListTasksRequest|null, - protos.google.cloud.tasks.v2.IListTasksResponse - ]) => { - this._log.info('listTasks values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.cloud.tasks.v2.ITask[], + protos.google.cloud.tasks.v2.IListTasksRequest | null, + protos.google.cloud.tasks.v2.IListTasksResponse, + ]) => { + this._log.info('listTasks values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listTasks`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The queue name. For example: - * `projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID` - * @param {google.cloud.tasks.v2.Task.View} request.responseView - * The response_view specifies which subset of the {@link protos.google.cloud.tasks.v2.Task|Task} will be - * returned. - * - * By default response_view is {@link protos.google.cloud.tasks.v2.Task.View.BASIC|BASIC}; not all - * information is retrieved by default because some data, such as - * payloads, might be desirable to return only when needed because - * of its large size or because of the sensitivity of data that it - * contains. - * - * Authorization for {@link protos.google.cloud.tasks.v2.Task.View.FULL|FULL} requires - * `cloudtasks.tasks.fullView` [Google IAM](https://cloud.google.com/iam/) - * permission on the {@link protos.google.cloud.tasks.v2.Task|Task} resource. - * @param {number} request.pageSize - * Maximum page size. - * - * Fewer tasks than requested might be returned, even if more tasks exist; use - * {@link protos.google.cloud.tasks.v2.ListTasksResponse.next_page_token|next_page_token} in the response to - * determine if more tasks exist. - * - * The maximum page size is 1000. If unspecified, the page size will be the - * maximum. - * @param {string} request.pageToken - * A token identifying the page of results to return. - * - * To request the first page results, page_token must be empty. To - * request the next page of results, page_token must be the value of - * {@link protos.google.cloud.tasks.v2.ListTasksResponse.next_page_token|next_page_token} returned - * from the previous call to {@link protos.google.cloud.tasks.v2.CloudTasks.ListTasks|ListTasks} - * method. - * - * The page token is valid for only 2 hours. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.cloud.tasks.v2.Task|Task} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `listTasksAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `listTasks`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The queue name. For example: + * `projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID` + * @param {google.cloud.tasks.v2.Task.View} request.responseView + * The response_view specifies which subset of the {@link protos.google.cloud.tasks.v2.Task|Task} will be + * returned. + * + * By default response_view is {@link protos.google.cloud.tasks.v2.Task.View.BASIC|BASIC}; not all + * information is retrieved by default because some data, such as + * payloads, might be desirable to return only when needed because + * of its large size or because of the sensitivity of data that it + * contains. + * + * Authorization for {@link protos.google.cloud.tasks.v2.Task.View.FULL|FULL} requires + * `cloudtasks.tasks.fullView` [Google IAM](https://cloud.google.com/iam/) + * permission on the {@link protos.google.cloud.tasks.v2.Task|Task} resource. + * @param {number} request.pageSize + * Maximum page size. + * + * Fewer tasks than requested might be returned, even if more tasks exist; use + * {@link protos.google.cloud.tasks.v2.ListTasksResponse.next_page_token|next_page_token} in the response to + * determine if more tasks exist. + * + * The maximum page size is 1000. If unspecified, the page size will be the + * maximum. + * @param {string} request.pageToken + * A token identifying the page of results to return. + * + * To request the first page results, page_token must be empty. To + * request the next page of results, page_token must be the value of + * {@link protos.google.cloud.tasks.v2.ListTasksResponse.next_page_token|next_page_token} returned + * from the previous call to {@link protos.google.cloud.tasks.v2.CloudTasks.ListTasks|ListTasks} + * method. + * + * The page token is valid for only 2 hours. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.cloud.tasks.v2.Task|Task} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listTasksAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listTasksStream( - request?: protos.google.cloud.tasks.v2.IListTasksRequest, - options?: CallOptions): - Transform{ + request?: protos.google.cloud.tasks.v2.IListTasksRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); const defaultCallSettings = this._defaults['listTasks']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listTasks stream %j', request); return this.descriptors.page.listTasks.createStream( this.innerApiCalls.listTasks as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listTasks`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The queue name. For example: - * `projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID` - * @param {google.cloud.tasks.v2.Task.View} request.responseView - * The response_view specifies which subset of the {@link protos.google.cloud.tasks.v2.Task|Task} will be - * returned. - * - * By default response_view is {@link protos.google.cloud.tasks.v2.Task.View.BASIC|BASIC}; not all - * information is retrieved by default because some data, such as - * payloads, might be desirable to return only when needed because - * of its large size or because of the sensitivity of data that it - * contains. - * - * Authorization for {@link protos.google.cloud.tasks.v2.Task.View.FULL|FULL} requires - * `cloudtasks.tasks.fullView` [Google IAM](https://cloud.google.com/iam/) - * permission on the {@link protos.google.cloud.tasks.v2.Task|Task} resource. - * @param {number} request.pageSize - * Maximum page size. - * - * Fewer tasks than requested might be returned, even if more tasks exist; use - * {@link protos.google.cloud.tasks.v2.ListTasksResponse.next_page_token|next_page_token} in the response to - * determine if more tasks exist. - * - * The maximum page size is 1000. If unspecified, the page size will be the - * maximum. - * @param {string} request.pageToken - * A token identifying the page of results to return. - * - * To request the first page results, page_token must be empty. To - * request the next page of results, page_token must be the value of - * {@link protos.google.cloud.tasks.v2.ListTasksResponse.next_page_token|next_page_token} returned - * from the previous call to {@link protos.google.cloud.tasks.v2.CloudTasks.ListTasks|ListTasks} - * method. - * - * The page token is valid for only 2 hours. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.cloud.tasks.v2.Task|Task}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v2/cloud_tasks.list_tasks.js - * region_tag:cloudtasks_v2_generated_CloudTasks_ListTasks_async - */ + /** + * Equivalent to `listTasks`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The queue name. For example: + * `projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID` + * @param {google.cloud.tasks.v2.Task.View} request.responseView + * The response_view specifies which subset of the {@link protos.google.cloud.tasks.v2.Task|Task} will be + * returned. + * + * By default response_view is {@link protos.google.cloud.tasks.v2.Task.View.BASIC|BASIC}; not all + * information is retrieved by default because some data, such as + * payloads, might be desirable to return only when needed because + * of its large size or because of the sensitivity of data that it + * contains. + * + * Authorization for {@link protos.google.cloud.tasks.v2.Task.View.FULL|FULL} requires + * `cloudtasks.tasks.fullView` [Google IAM](https://cloud.google.com/iam/) + * permission on the {@link protos.google.cloud.tasks.v2.Task|Task} resource. + * @param {number} request.pageSize + * Maximum page size. + * + * Fewer tasks than requested might be returned, even if more tasks exist; use + * {@link protos.google.cloud.tasks.v2.ListTasksResponse.next_page_token|next_page_token} in the response to + * determine if more tasks exist. + * + * The maximum page size is 1000. If unspecified, the page size will be the + * maximum. + * @param {string} request.pageToken + * A token identifying the page of results to return. + * + * To request the first page results, page_token must be empty. To + * request the next page of results, page_token must be the value of + * {@link protos.google.cloud.tasks.v2.ListTasksResponse.next_page_token|next_page_token} returned + * from the previous call to {@link protos.google.cloud.tasks.v2.CloudTasks.ListTasks|ListTasks} + * method. + * + * The page token is valid for only 2 hours. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.cloud.tasks.v2.Task|Task}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v2/cloud_tasks.list_tasks.js + * region_tag:cloudtasks_v2_generated_CloudTasks_ListTasks_async + */ listTasksAsync( - request?: protos.google.cloud.tasks.v2.IListTasksRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.cloud.tasks.v2.IListTasksRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); const defaultCallSettings = this._defaults['listTasks']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listTasks iterate %j', request); return this.descriptors.page.listTasks.asyncIterate( this.innerApiCalls['listTasks'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } // -------------------- @@ -2459,7 +2982,7 @@ export class CloudTasksClient { * @param {string} queue * @returns {string} Resource name string. */ - queuePath(project:string,location:string,queue:string) { + queuePath(project: string, location: string, queue: string) { return this.pathTemplates.queuePathTemplate.render({ project: project, location: location, @@ -2509,7 +3032,7 @@ export class CloudTasksClient { * @param {string} task * @returns {string} Resource name string. */ - taskPath(project:string,location:string,queue:string,task:string) { + taskPath(project: string, location: string, queue: string, task: string) { return this.pathTemplates.taskPathTemplate.render({ project: project, location: location, @@ -2570,7 +3093,7 @@ export class CloudTasksClient { */ close(): Promise { if (this.cloudTasksStub && !this._terminated) { - return this.cloudTasksStub.then(stub => { + return this.cloudTasksStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -2578,4 +3101,4 @@ export class CloudTasksClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/core/generator/gapic-generator-typescript/baselines/tasks/src/v2/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/tasks/src/v2/index.ts.baseline index 98d67568c6ca..55452cd6df54 100644 --- a/core/generator/gapic-generator-typescript/baselines/tasks/src/v2/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/tasks/src/v2/index.ts.baseline @@ -16,4 +16,4 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -export {CloudTasksClient} from './cloud_tasks_client'; +export { CloudTasksClient } from './cloud_tasks_client'; diff --git a/core/generator/gapic-generator-typescript/baselines/tasks/system-test/fixtures/sample/src/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/tasks/system-test/fixtures/sample/src/index.ts.baseline index df887c5a29f4..f50c786840f1 100644 --- a/core/generator/gapic-generator-typescript/baselines/tasks/system-test/fixtures/sample/src/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/tasks/system-test/fixtures/sample/src/index.ts.baseline @@ -16,7 +16,7 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -import {CloudTasksClient} from 'tasks'; +import { CloudTasksClient } from 'tasks'; // check that the client class type name can be used function doStuffWithCloudTasksClient(client: CloudTasksClient) { diff --git a/core/generator/gapic-generator-typescript/baselines/tasks/system-test/install.ts.baseline b/core/generator/gapic-generator-typescript/baselines/tasks/system-test/install.ts.baseline index f66069aa3940..ccf167042d2e 100644 --- a/core/generator/gapic-generator-typescript/baselines/tasks/system-test/install.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/tasks/system-test/install.ts.baseline @@ -16,34 +16,36 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -import {packNTest} from 'pack-n-play'; -import {readFileSync} from 'fs'; -import {describe, it} from 'mocha'; +import { packNTest } from 'pack-n-play'; +import { readFileSync } from 'fs'; +import { describe, it } from 'mocha'; describe('📦 pack-n-play test', () => { - - it('TypeScript code', async function() { + it('TypeScript code', async function () { this.timeout(300000); const options = { packageDir: process.cwd(), sample: { description: 'TypeScript user can use the type definitions', - ts: readFileSync('./system-test/fixtures/sample/src/index.ts').toString() - } + ts: readFileSync( + './system-test/fixtures/sample/src/index.ts', + ).toString(), + }, }; await packNTest(options); }); - it('JavaScript code', async function() { + it('JavaScript code', async function () { this.timeout(300000); const options = { packageDir: process.cwd(), sample: { description: 'JavaScript user can use the library', - cjs: readFileSync('./system-test/fixtures/sample/src/index.js').toString() - } + cjs: readFileSync( + './system-test/fixtures/sample/src/index.js', + ).toString(), + }, }; await packNTest(options); }); - }); diff --git a/core/generator/gapic-generator-typescript/baselines/tasks/test/gapic_cloud_tasks_v2.ts.baseline b/core/generator/gapic-generator-typescript/baselines/tasks/test/gapic_cloud_tasks_v2.ts.baseline index 1adb1dd2c4c0..70b7b0827b86 100644 --- a/core/generator/gapic-generator-typescript/baselines/tasks/test/gapic_cloud_tasks_v2.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/tasks/test/gapic_cloud_tasks_v2.ts.baseline @@ -19,2352 +19,2878 @@ import * as protos from '../protos/protos'; import * as assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as cloudtasksModule from '../src'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; -import {protobuf} from 'google-gax'; +import { protobuf } from 'google-gax'; // Dynamically loaded proto JSON is needed to get the type information // to fill in default values for request objects -const root = protobuf.Root.fromJSON(require('../protos/protos.json')).resolveAll(); +const root = protobuf.Root.fromJSON( + require('../protos/protos.json'), +).resolveAll(); // eslint-disable-next-line @typescript-eslint/no-unused-vars function getTypeDefaultValue(typeName: string, fields: string[]) { - let type = root.lookupType(typeName) as protobuf.Type; - for (const field of fields.slice(0, -1)) { - type = type.fields[field]?.resolvedType as protobuf.Type; - } - return type.fields[fields[fields.length - 1]]?.defaultValue; + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type.fields[field]?.resolvedType as protobuf.Type; + } + return type.fields[fields[fields.length - 1]]?.defaultValue; } function generateSampleMessage(instance: T) { - const filledObject = (instance.constructor as typeof protobuf.Message) - .toObject(instance as protobuf.Message, {defaults: true}); - return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, { defaults: true }); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; } function stubSimpleCall(response?: ResponseType, error?: Error) { - return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); } -function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { - return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +function stubSimpleCallWithCallback( + response?: ResponseType, + error?: Error, +) { + return error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); } -function stubPageStreamingCall(responses?: ResponseType[], error?: Error) { - const pagingStub = sinon.stub(); - if (responses) { - for (let i = 0; i < responses.length; ++i) { - pagingStub.onCall(i).callsArgWith(2, null, responses[i]); - } +function stubPageStreamingCall( + responses?: ResponseType[], + error?: Error, +) { + const pagingStub = sinon.stub(); + if (responses) { + for (let i = 0; i < responses.length; ++i) { + pagingStub.onCall(i).callsArgWith(2, null, responses[i]); } - const transformStub = error ? sinon.stub().callsArgWith(2, error) : pagingStub; - const mockStream = new PassThrough({ - objectMode: true, - transform: transformStub, - }); - // trigger as many responses as needed - if (responses) { - for (let i = 0; i < responses.length; ++i) { - setImmediate(() => { mockStream.write({}); }); - } - setImmediate(() => { mockStream.end(); }); - } else { - setImmediate(() => { mockStream.write({}); }); - setImmediate(() => { mockStream.end(); }); + } + const transformStub = error + ? sinon.stub().callsArgWith(2, error) + : pagingStub; + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + // trigger as many responses as needed + if (responses) { + for (let i = 0; i < responses.length; ++i) { + setImmediate(() => { + mockStream.write({}); + }); } - return sinon.stub().returns(mockStream); + setImmediate(() => { + mockStream.end(); + }); + } else { + setImmediate(() => { + mockStream.write({}); + }); + setImmediate(() => { + mockStream.end(); + }); + } + return sinon.stub().returns(mockStream); } -function stubAsyncIterationCall(responses?: ResponseType[], error?: Error) { - let counter = 0; - const asyncIterable = { - [Symbol.asyncIterator]() { - return { - async next() { - if (error) { - return Promise.reject(error); - } - if (counter >= responses!.length) { - return Promise.resolve({done: true, value: undefined}); - } - return Promise.resolve({done: false, value: responses![counter++]}); - } - }; - } - }; - return sinon.stub().returns(asyncIterable); +function stubAsyncIterationCall( + responses?: ResponseType[], + error?: Error, +) { + let counter = 0; + const asyncIterable = { + [Symbol.asyncIterator]() { + return { + async next() { + if (error) { + return Promise.reject(error); + } + if (counter >= responses!.length) { + return Promise.resolve({ done: true, value: undefined }); + } + return Promise.resolve({ done: false, value: responses![counter++] }); + }, + }; + }, + }; + return sinon.stub().returns(asyncIterable); } describe('v2.CloudTasksClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new cloudtasksModule.v2.CloudTasksClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'cloudtasks.googleapis.com'); - }); - - it('has universeDomain', () => { - const client = new cloudtasksModule.v2.CloudTasksClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); - - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - it('throws DeprecationWarning if static servicePath is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const servicePath = cloudtasksModule.v2.CloudTasksClient.servicePath; - assert.strictEqual(servicePath, 'cloudtasks.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = cloudtasksModule.v2.CloudTasksClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'cloudtasks.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new cloudtasksModule.v2.CloudTasksClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'cloudtasks.example.com'); - }); - - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new cloudtasksModule.v2.CloudTasksClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'cloudtasks.example.com'); - }); - - if (typeof process === 'object' && 'env' in process) { - describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { - it('sets apiEndpoint from environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new cloudtasksModule.v2.CloudTasksClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'cloudtasks.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - - it('value configured in code has priority over environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new cloudtasksModule.v2.CloudTasksClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'cloudtasks.configured.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { new cloudtasksModule.v2.CloudTasksClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); - - it('has port', () => { - const port = cloudtasksModule.v2.CloudTasksClient.port; - assert(port); - assert(typeof port === 'number'); - }); - - it('should create a client with no option', () => { - const client = new cloudtasksModule.v2.CloudTasksClient(); - assert(client); - }); - - it('should create a client with gRPC fallback', () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - fallback: true, - }); - assert(client); - }); - - it('has initialize method and supports deferred initialization', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.cloudTasksStub, undefined); - await client.initialize(); - assert(client.cloudTasksStub); - }); - - it('has close method for the initialized client', done => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.cloudTasksStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); - - it('has close method for the non-initialized client', done => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.cloudTasksStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); - - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); - }); - - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId((err?: Error|null, projectId?: string|null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } - }); - }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new cloudtasksModule.v2.CloudTasksClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'cloudtasks.googleapis.com'); }); - describe('getQueue', () => { - it('invokes getQueue without error', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.tasks.v2.GetQueueRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.tasks.v2.GetQueueRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.tasks.v2.Queue() - ); - client.innerApiCalls.getQueue = stubSimpleCall(expectedResponse); - const [response] = await client.getQueue(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getQueue as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getQueue as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getQueue without error using callback', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.tasks.v2.GetQueueRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.tasks.v2.GetQueueRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.tasks.v2.Queue() - ); - client.innerApiCalls.getQueue = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getQueue( - request, - (err?: Error|null, result?: protos.google.cloud.tasks.v2.IQueue|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getQueue as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getQueue as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has universeDomain', () => { + const client = new cloudtasksModule.v2.CloudTasksClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - it('invokes getQueue with error', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.tasks.v2.GetQueueRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.tasks.v2.GetQueueRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getQueue = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getQueue(request), expectedError); - const actualRequest = (client.innerApiCalls.getQueue as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getQueue as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = cloudtasksModule.v2.CloudTasksClient.servicePath; + assert.strictEqual(servicePath, 'cloudtasks.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = cloudtasksModule.v2.CloudTasksClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'cloudtasks.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + universeDomain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'cloudtasks.example.com'); + }); - it('invokes getQueue with closed client', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.tasks.v2.GetQueueRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.tasks.v2.GetQueueRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getQueue(request), expectedError); - }); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + universe_domain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'cloudtasks.example.com'); }); - describe('createQueue', () => { - it('invokes createQueue without error', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.tasks.v2.CreateQueueRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.tasks.v2.CreateQueueRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.tasks.v2.Queue() - ); - client.innerApiCalls.createQueue = stubSimpleCall(expectedResponse); - const [response] = await client.createQueue(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createQueue as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createQueue as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + if (typeof process === 'object' && 'env' in process) { + describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { + it('sets apiEndpoint from environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new cloudtasksModule.v2.CloudTasksClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'cloudtasks.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } + }); + + it('value configured in code has priority over environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new cloudtasksModule.v2.CloudTasksClient({ + universeDomain: 'configured.example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'cloudtasks.configured.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } + }); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new cloudtasksModule.v2.CloudTasksClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); + }); - it('invokes createQueue without error using callback', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.tasks.v2.CreateQueueRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.tasks.v2.CreateQueueRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.tasks.v2.Queue() - ); - client.innerApiCalls.createQueue = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createQueue( - request, - (err?: Error|null, result?: protos.google.cloud.tasks.v2.IQueue|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createQueue as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createQueue as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has port', () => { + const port = cloudtasksModule.v2.CloudTasksClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('invokes createQueue with error', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.tasks.v2.CreateQueueRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.tasks.v2.CreateQueueRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createQueue = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createQueue(request), expectedError); - const actualRequest = (client.innerApiCalls.createQueue as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createQueue as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('should create a client with no option', () => { + const client = new cloudtasksModule.v2.CloudTasksClient(); + assert(client); + }); - it('invokes createQueue with closed client', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.tasks.v2.CreateQueueRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.tasks.v2.CreateQueueRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createQueue(request), expectedError); - }); + it('should create a client with gRPC fallback', () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + fallback: true, + }); + assert(client); }); - describe('updateQueue', () => { - it('invokes updateQueue without error', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.tasks.v2.UpdateQueueRequest() - ); - request.queue ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.tasks.v2.UpdateQueueRequest', ['queue', 'name']); - request.queue.name = defaultValue1; - const expectedHeaderRequestParams = `queue.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.tasks.v2.Queue() - ); - client.innerApiCalls.updateQueue = stubSimpleCall(expectedResponse); - const [response] = await client.updateQueue(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateQueue as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateQueue as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has initialize method and supports deferred initialization', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.cloudTasksStub, undefined); + await client.initialize(); + assert(client.cloudTasksStub); + }); - it('invokes updateQueue without error using callback', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.tasks.v2.UpdateQueueRequest() - ); - request.queue ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.tasks.v2.UpdateQueueRequest', ['queue', 'name']); - request.queue.name = defaultValue1; - const expectedHeaderRequestParams = `queue.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.tasks.v2.Queue() - ); - client.innerApiCalls.updateQueue = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateQueue( - request, - (err?: Error|null, result?: protos.google.cloud.tasks.v2.IQueue|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateQueue as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateQueue as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('has close method for the initialized client', (done) => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.cloudTasksStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes updateQueue with error', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.tasks.v2.UpdateQueueRequest() - ); - request.queue ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.tasks.v2.UpdateQueueRequest', ['queue', 'name']); - request.queue.name = defaultValue1; - const expectedHeaderRequestParams = `queue.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateQueue = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateQueue(request), expectedError); - const actualRequest = (client.innerApiCalls.updateQueue as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateQueue as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('has close method for the non-initialized client', (done) => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.cloudTasksStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes updateQueue with closed client', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.tasks.v2.UpdateQueueRequest() - ); - request.queue ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.cloud.tasks.v2.UpdateQueueRequest', ['queue', 'name']); - request.queue.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateQueue(request), expectedError); - }); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); }); - describe('deleteQueue', () => { - it('invokes deleteQueue without error', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.tasks.v2.DeleteQueueRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.tasks.v2.DeleteQueueRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteQueue = stubSimpleCall(expectedResponse); - const [response] = await client.deleteQueue(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteQueue as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteQueue as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } + }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + }); + + describe('getQueue', () => { + it('invokes getQueue without error', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.tasks.v2.GetQueueRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.tasks.v2.GetQueueRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.tasks.v2.Queue(), + ); + client.innerApiCalls.getQueue = stubSimpleCall(expectedResponse); + const [response] = await client.getQueue(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getQueue as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getQueue as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteQueue without error using callback', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.tasks.v2.DeleteQueueRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.tasks.v2.DeleteQueueRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteQueue = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteQueue( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteQueue as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteQueue as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getQueue without error using callback', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.tasks.v2.GetQueueRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.tasks.v2.GetQueueRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.tasks.v2.Queue(), + ); + client.innerApiCalls.getQueue = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getQueue( + request, + ( + err?: Error | null, + result?: protos.google.cloud.tasks.v2.IQueue | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getQueue as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getQueue as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteQueue with error', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.tasks.v2.DeleteQueueRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.tasks.v2.DeleteQueueRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteQueue = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteQueue(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteQueue as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteQueue as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getQueue with error', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.tasks.v2.GetQueueRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.tasks.v2.GetQueueRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getQueue = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.getQueue(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getQueue as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getQueue as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteQueue with closed client', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.tasks.v2.DeleteQueueRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.tasks.v2.DeleteQueueRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteQueue(request), expectedError); - }); + it('invokes getQueue with closed client', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.tasks.v2.GetQueueRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.tasks.v2.GetQueueRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getQueue(request), expectedError); + }); + }); + + describe('createQueue', () => { + it('invokes createQueue without error', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.tasks.v2.CreateQueueRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.tasks.v2.CreateQueueRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.tasks.v2.Queue(), + ); + client.innerApiCalls.createQueue = stubSimpleCall(expectedResponse); + const [response] = await client.createQueue(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createQueue as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createQueue as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('purgeQueue', () => { - it('invokes purgeQueue without error', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.tasks.v2.PurgeQueueRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.tasks.v2.PurgeQueueRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.tasks.v2.Queue() - ); - client.innerApiCalls.purgeQueue = stubSimpleCall(expectedResponse); - const [response] = await client.purgeQueue(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.purgeQueue as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.purgeQueue as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createQueue without error using callback', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.tasks.v2.CreateQueueRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.tasks.v2.CreateQueueRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.tasks.v2.Queue(), + ); + client.innerApiCalls.createQueue = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createQueue( + request, + ( + err?: Error | null, + result?: protos.google.cloud.tasks.v2.IQueue | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createQueue as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createQueue as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes purgeQueue without error using callback', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.tasks.v2.PurgeQueueRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.tasks.v2.PurgeQueueRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.tasks.v2.Queue() - ); - client.innerApiCalls.purgeQueue = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.purgeQueue( - request, - (err?: Error|null, result?: protos.google.cloud.tasks.v2.IQueue|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.purgeQueue as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.purgeQueue as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createQueue with error', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.tasks.v2.CreateQueueRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.tasks.v2.CreateQueueRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createQueue = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.createQueue(request), expectedError); + const actualRequest = ( + client.innerApiCalls.createQueue as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createQueue as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes purgeQueue with error', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.tasks.v2.PurgeQueueRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.tasks.v2.PurgeQueueRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.purgeQueue = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.purgeQueue(request), expectedError); - const actualRequest = (client.innerApiCalls.purgeQueue as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.purgeQueue as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createQueue with closed client', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.tasks.v2.CreateQueueRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.tasks.v2.CreateQueueRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.createQueue(request), expectedError); + }); + }); + + describe('updateQueue', () => { + it('invokes updateQueue without error', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.tasks.v2.UpdateQueueRequest(), + ); + request.queue ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.tasks.v2.UpdateQueueRequest', + ['queue', 'name'], + ); + request.queue.name = defaultValue1; + const expectedHeaderRequestParams = `queue.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.tasks.v2.Queue(), + ); + client.innerApiCalls.updateQueue = stubSimpleCall(expectedResponse); + const [response] = await client.updateQueue(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateQueue as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateQueue as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes purgeQueue with closed client', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.tasks.v2.PurgeQueueRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.tasks.v2.PurgeQueueRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.purgeQueue(request), expectedError); - }); + it('invokes updateQueue without error using callback', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.tasks.v2.UpdateQueueRequest(), + ); + request.queue ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.tasks.v2.UpdateQueueRequest', + ['queue', 'name'], + ); + request.queue.name = defaultValue1; + const expectedHeaderRequestParams = `queue.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.tasks.v2.Queue(), + ); + client.innerApiCalls.updateQueue = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateQueue( + request, + ( + err?: Error | null, + result?: protos.google.cloud.tasks.v2.IQueue | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateQueue as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateQueue as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('pauseQueue', () => { - it('invokes pauseQueue without error', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.tasks.v2.PauseQueueRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.tasks.v2.PauseQueueRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.tasks.v2.Queue() - ); - client.innerApiCalls.pauseQueue = stubSimpleCall(expectedResponse); - const [response] = await client.pauseQueue(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.pauseQueue as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.pauseQueue as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateQueue with error', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.tasks.v2.UpdateQueueRequest(), + ); + request.queue ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.tasks.v2.UpdateQueueRequest', + ['queue', 'name'], + ); + request.queue.name = defaultValue1; + const expectedHeaderRequestParams = `queue.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateQueue = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.updateQueue(request), expectedError); + const actualRequest = ( + client.innerApiCalls.updateQueue as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateQueue as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes pauseQueue without error using callback', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.tasks.v2.PauseQueueRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.tasks.v2.PauseQueueRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.tasks.v2.Queue() - ); - client.innerApiCalls.pauseQueue = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.pauseQueue( - request, - (err?: Error|null, result?: protos.google.cloud.tasks.v2.IQueue|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.pauseQueue as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.pauseQueue as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateQueue with closed client', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.tasks.v2.UpdateQueueRequest(), + ); + request.queue ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.tasks.v2.UpdateQueueRequest', + ['queue', 'name'], + ); + request.queue.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.updateQueue(request), expectedError); + }); + }); + + describe('deleteQueue', () => { + it('invokes deleteQueue without error', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.tasks.v2.DeleteQueueRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.tasks.v2.DeleteQueueRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteQueue = stubSimpleCall(expectedResponse); + const [response] = await client.deleteQueue(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteQueue as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteQueue as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes pauseQueue with error', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.tasks.v2.PauseQueueRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.tasks.v2.PauseQueueRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.pauseQueue = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.pauseQueue(request), expectedError); - const actualRequest = (client.innerApiCalls.pauseQueue as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.pauseQueue as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteQueue without error using callback', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.tasks.v2.DeleteQueueRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.tasks.v2.DeleteQueueRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteQueue = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteQueue( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteQueue as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteQueue as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes pauseQueue with closed client', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.tasks.v2.PauseQueueRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.tasks.v2.PauseQueueRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.pauseQueue(request), expectedError); - }); + it('invokes deleteQueue with error', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.tasks.v2.DeleteQueueRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.tasks.v2.DeleteQueueRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteQueue = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.deleteQueue(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteQueue as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteQueue as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('resumeQueue', () => { - it('invokes resumeQueue without error', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.tasks.v2.ResumeQueueRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.tasks.v2.ResumeQueueRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.tasks.v2.Queue() - ); - client.innerApiCalls.resumeQueue = stubSimpleCall(expectedResponse); - const [response] = await client.resumeQueue(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.resumeQueue as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.resumeQueue as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteQueue with closed client', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.tasks.v2.DeleteQueueRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.tasks.v2.DeleteQueueRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.deleteQueue(request), expectedError); + }); + }); + + describe('purgeQueue', () => { + it('invokes purgeQueue without error', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.tasks.v2.PurgeQueueRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.tasks.v2.PurgeQueueRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.tasks.v2.Queue(), + ); + client.innerApiCalls.purgeQueue = stubSimpleCall(expectedResponse); + const [response] = await client.purgeQueue(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.purgeQueue as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.purgeQueue as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes resumeQueue without error using callback', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.tasks.v2.ResumeQueueRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.tasks.v2.ResumeQueueRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.tasks.v2.Queue() - ); - client.innerApiCalls.resumeQueue = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.resumeQueue( - request, - (err?: Error|null, result?: protos.google.cloud.tasks.v2.IQueue|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.resumeQueue as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.resumeQueue as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes purgeQueue without error using callback', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.tasks.v2.PurgeQueueRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.tasks.v2.PurgeQueueRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.tasks.v2.Queue(), + ); + client.innerApiCalls.purgeQueue = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.purgeQueue( + request, + ( + err?: Error | null, + result?: protos.google.cloud.tasks.v2.IQueue | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.purgeQueue as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.purgeQueue as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes resumeQueue with error', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.tasks.v2.ResumeQueueRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.tasks.v2.ResumeQueueRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.resumeQueue = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.resumeQueue(request), expectedError); - const actualRequest = (client.innerApiCalls.resumeQueue as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.resumeQueue as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes purgeQueue with error', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.tasks.v2.PurgeQueueRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.tasks.v2.PurgeQueueRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.purgeQueue = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.purgeQueue(request), expectedError); + const actualRequest = ( + client.innerApiCalls.purgeQueue as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.purgeQueue as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes resumeQueue with closed client', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.tasks.v2.ResumeQueueRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.tasks.v2.ResumeQueueRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.resumeQueue(request), expectedError); - }); + it('invokes purgeQueue with closed client', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.tasks.v2.PurgeQueueRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.tasks.v2.PurgeQueueRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.purgeQueue(request), expectedError); + }); + }); + + describe('pauseQueue', () => { + it('invokes pauseQueue without error', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.tasks.v2.PauseQueueRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.tasks.v2.PauseQueueRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.tasks.v2.Queue(), + ); + client.innerApiCalls.pauseQueue = stubSimpleCall(expectedResponse); + const [response] = await client.pauseQueue(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.pauseQueue as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.pauseQueue as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('getIamPolicy', () => { - it('invokes getIamPolicy without error', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.iam.v1.GetIamPolicyRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.iam.v1.GetIamPolicyRequest', ['resource']); - request.resource = defaultValue1; - const expectedHeaderRequestParams = `resource=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.iam.v1.Policy() - ); - client.innerApiCalls.getIamPolicy = stubSimpleCall(expectedResponse); - const [response] = await client.getIamPolicy(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getIamPolicy as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getIamPolicy as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes pauseQueue without error using callback', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.tasks.v2.PauseQueueRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.tasks.v2.PauseQueueRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.tasks.v2.Queue(), + ); + client.innerApiCalls.pauseQueue = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.pauseQueue( + request, + ( + err?: Error | null, + result?: protos.google.cloud.tasks.v2.IQueue | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.pauseQueue as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.pauseQueue as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getIamPolicy without error using callback', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.iam.v1.GetIamPolicyRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.iam.v1.GetIamPolicyRequest', ['resource']); - request.resource = defaultValue1; - const expectedHeaderRequestParams = `resource=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.iam.v1.Policy() - ); - client.innerApiCalls.getIamPolicy = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getIamPolicy( - request, - (err?: Error|null, result?: protos.google.iam.v1.IPolicy|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getIamPolicy as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getIamPolicy as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes pauseQueue with error', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.tasks.v2.PauseQueueRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.tasks.v2.PauseQueueRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.pauseQueue = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.pauseQueue(request), expectedError); + const actualRequest = ( + client.innerApiCalls.pauseQueue as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.pauseQueue as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getIamPolicy with error', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.iam.v1.GetIamPolicyRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.iam.v1.GetIamPolicyRequest', ['resource']); - request.resource = defaultValue1; - const expectedHeaderRequestParams = `resource=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getIamPolicy = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getIamPolicy(request), expectedError); - const actualRequest = (client.innerApiCalls.getIamPolicy as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getIamPolicy as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes pauseQueue with closed client', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.tasks.v2.PauseQueueRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.tasks.v2.PauseQueueRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.pauseQueue(request), expectedError); + }); + }); + + describe('resumeQueue', () => { + it('invokes resumeQueue without error', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.tasks.v2.ResumeQueueRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.tasks.v2.ResumeQueueRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.tasks.v2.Queue(), + ); + client.innerApiCalls.resumeQueue = stubSimpleCall(expectedResponse); + const [response] = await client.resumeQueue(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.resumeQueue as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.resumeQueue as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getIamPolicy with closed client', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.iam.v1.GetIamPolicyRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.iam.v1.GetIamPolicyRequest', ['resource']); - request.resource = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getIamPolicy(request), expectedError); - }); + it('invokes resumeQueue without error using callback', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.tasks.v2.ResumeQueueRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.tasks.v2.ResumeQueueRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.tasks.v2.Queue(), + ); + client.innerApiCalls.resumeQueue = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.resumeQueue( + request, + ( + err?: Error | null, + result?: protos.google.cloud.tasks.v2.IQueue | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.resumeQueue as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.resumeQueue as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('setIamPolicy', () => { - it('invokes setIamPolicy without error', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.iam.v1.SetIamPolicyRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.iam.v1.SetIamPolicyRequest', ['resource']); - request.resource = defaultValue1; - const expectedHeaderRequestParams = `resource=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.iam.v1.Policy() - ); - client.innerApiCalls.setIamPolicy = stubSimpleCall(expectedResponse); - const [response] = await client.setIamPolicy(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.setIamPolicy as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.setIamPolicy as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes resumeQueue with error', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.tasks.v2.ResumeQueueRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.tasks.v2.ResumeQueueRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.resumeQueue = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.resumeQueue(request), expectedError); + const actualRequest = ( + client.innerApiCalls.resumeQueue as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.resumeQueue as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes setIamPolicy without error using callback', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.iam.v1.SetIamPolicyRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.iam.v1.SetIamPolicyRequest', ['resource']); - request.resource = defaultValue1; - const expectedHeaderRequestParams = `resource=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.iam.v1.Policy() - ); - client.innerApiCalls.setIamPolicy = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.setIamPolicy( - request, - (err?: Error|null, result?: protos.google.iam.v1.IPolicy|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.setIamPolicy as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.setIamPolicy as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes resumeQueue with closed client', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.tasks.v2.ResumeQueueRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.tasks.v2.ResumeQueueRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.resumeQueue(request), expectedError); + }); + }); + + describe('getIamPolicy', () => { + it('invokes getIamPolicy without error', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.iam.v1.GetIamPolicyRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.iam.v1.GetIamPolicyRequest', + ['resource'], + ); + request.resource = defaultValue1; + const expectedHeaderRequestParams = `resource=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.iam.v1.Policy(), + ); + client.innerApiCalls.getIamPolicy = stubSimpleCall(expectedResponse); + const [response] = await client.getIamPolicy(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getIamPolicy as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getIamPolicy as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes setIamPolicy with error', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.iam.v1.SetIamPolicyRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.iam.v1.SetIamPolicyRequest', ['resource']); - request.resource = defaultValue1; - const expectedHeaderRequestParams = `resource=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.setIamPolicy = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.setIamPolicy(request), expectedError); - const actualRequest = (client.innerApiCalls.setIamPolicy as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.setIamPolicy as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getIamPolicy without error using callback', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.iam.v1.GetIamPolicyRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.iam.v1.GetIamPolicyRequest', + ['resource'], + ); + request.resource = defaultValue1; + const expectedHeaderRequestParams = `resource=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.iam.v1.Policy(), + ); + client.innerApiCalls.getIamPolicy = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getIamPolicy( + request, + ( + err?: Error | null, + result?: protos.google.iam.v1.IPolicy | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getIamPolicy as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getIamPolicy as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes setIamPolicy with closed client', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.iam.v1.SetIamPolicyRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.iam.v1.SetIamPolicyRequest', ['resource']); - request.resource = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.setIamPolicy(request), expectedError); - }); + it('invokes getIamPolicy with error', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.iam.v1.GetIamPolicyRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.iam.v1.GetIamPolicyRequest', + ['resource'], + ); + request.resource = defaultValue1; + const expectedHeaderRequestParams = `resource=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getIamPolicy = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getIamPolicy(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getIamPolicy as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getIamPolicy as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('testIamPermissions', () => { - it('invokes testIamPermissions without error', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.iam.v1.TestIamPermissionsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.iam.v1.TestIamPermissionsRequest', ['resource']); - request.resource = defaultValue1; - const expectedHeaderRequestParams = `resource=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.iam.v1.TestIamPermissionsResponse() - ); - client.innerApiCalls.testIamPermissions = stubSimpleCall(expectedResponse); - const [response] = await client.testIamPermissions(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.testIamPermissions as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.testIamPermissions as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getIamPolicy with closed client', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.iam.v1.GetIamPolicyRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.iam.v1.GetIamPolicyRequest', + ['resource'], + ); + request.resource = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getIamPolicy(request), expectedError); + }); + }); + + describe('setIamPolicy', () => { + it('invokes setIamPolicy without error', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.iam.v1.SetIamPolicyRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.iam.v1.SetIamPolicyRequest', + ['resource'], + ); + request.resource = defaultValue1; + const expectedHeaderRequestParams = `resource=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.iam.v1.Policy(), + ); + client.innerApiCalls.setIamPolicy = stubSimpleCall(expectedResponse); + const [response] = await client.setIamPolicy(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.setIamPolicy as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.setIamPolicy as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes testIamPermissions without error using callback', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.iam.v1.TestIamPermissionsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.iam.v1.TestIamPermissionsRequest', ['resource']); - request.resource = defaultValue1; - const expectedHeaderRequestParams = `resource=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.iam.v1.TestIamPermissionsResponse() - ); - client.innerApiCalls.testIamPermissions = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.testIamPermissions( - request, - (err?: Error|null, result?: protos.google.iam.v1.ITestIamPermissionsResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.testIamPermissions as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.testIamPermissions as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes setIamPolicy without error using callback', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.iam.v1.SetIamPolicyRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.iam.v1.SetIamPolicyRequest', + ['resource'], + ); + request.resource = defaultValue1; + const expectedHeaderRequestParams = `resource=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.iam.v1.Policy(), + ); + client.innerApiCalls.setIamPolicy = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.setIamPolicy( + request, + ( + err?: Error | null, + result?: protos.google.iam.v1.IPolicy | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.setIamPolicy as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.setIamPolicy as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes testIamPermissions with error', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.iam.v1.TestIamPermissionsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.iam.v1.TestIamPermissionsRequest', ['resource']); - request.resource = defaultValue1; - const expectedHeaderRequestParams = `resource=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.testIamPermissions = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.testIamPermissions(request), expectedError); - const actualRequest = (client.innerApiCalls.testIamPermissions as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.testIamPermissions as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes setIamPolicy with error', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.iam.v1.SetIamPolicyRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.iam.v1.SetIamPolicyRequest', + ['resource'], + ); + request.resource = defaultValue1; + const expectedHeaderRequestParams = `resource=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.setIamPolicy = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.setIamPolicy(request), expectedError); + const actualRequest = ( + client.innerApiCalls.setIamPolicy as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.setIamPolicy as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes testIamPermissions with closed client', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.iam.v1.TestIamPermissionsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.iam.v1.TestIamPermissionsRequest', ['resource']); - request.resource = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.testIamPermissions(request), expectedError); - }); + it('invokes setIamPolicy with closed client', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.iam.v1.SetIamPolicyRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.iam.v1.SetIamPolicyRequest', + ['resource'], + ); + request.resource = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.setIamPolicy(request), expectedError); + }); + }); + + describe('testIamPermissions', () => { + it('invokes testIamPermissions without error', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.iam.v1.TestIamPermissionsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.iam.v1.TestIamPermissionsRequest', + ['resource'], + ); + request.resource = defaultValue1; + const expectedHeaderRequestParams = `resource=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.iam.v1.TestIamPermissionsResponse(), + ); + client.innerApiCalls.testIamPermissions = + stubSimpleCall(expectedResponse); + const [response] = await client.testIamPermissions(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.testIamPermissions as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.testIamPermissions as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('getTask', () => { - it('invokes getTask without error', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.tasks.v2.GetTaskRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.tasks.v2.GetTaskRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.tasks.v2.Task() - ); - client.innerApiCalls.getTask = stubSimpleCall(expectedResponse); - const [response] = await client.getTask(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getTask as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getTask as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes testIamPermissions without error using callback', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.iam.v1.TestIamPermissionsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.iam.v1.TestIamPermissionsRequest', + ['resource'], + ); + request.resource = defaultValue1; + const expectedHeaderRequestParams = `resource=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.iam.v1.TestIamPermissionsResponse(), + ); + client.innerApiCalls.testIamPermissions = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.testIamPermissions( + request, + ( + err?: Error | null, + result?: protos.google.iam.v1.ITestIamPermissionsResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.testIamPermissions as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.testIamPermissions as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getTask without error using callback', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.tasks.v2.GetTaskRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.tasks.v2.GetTaskRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.tasks.v2.Task() - ); - client.innerApiCalls.getTask = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getTask( - request, - (err?: Error|null, result?: protos.google.cloud.tasks.v2.ITask|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getTask as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getTask as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes testIamPermissions with error', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.iam.v1.TestIamPermissionsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.iam.v1.TestIamPermissionsRequest', + ['resource'], + ); + request.resource = defaultValue1; + const expectedHeaderRequestParams = `resource=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.testIamPermissions = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.testIamPermissions(request), expectedError); + const actualRequest = ( + client.innerApiCalls.testIamPermissions as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.testIamPermissions as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getTask with error', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.tasks.v2.GetTaskRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.tasks.v2.GetTaskRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getTask = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getTask(request), expectedError); - const actualRequest = (client.innerApiCalls.getTask as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getTask as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes testIamPermissions with closed client', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.iam.v1.TestIamPermissionsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.iam.v1.TestIamPermissionsRequest', + ['resource'], + ); + request.resource = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.testIamPermissions(request), expectedError); + }); + }); + + describe('getTask', () => { + it('invokes getTask without error', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.tasks.v2.GetTaskRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.tasks.v2.GetTaskRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.tasks.v2.Task(), + ); + client.innerApiCalls.getTask = stubSimpleCall(expectedResponse); + const [response] = await client.getTask(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.getTask as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getTask as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getTask with closed client', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.tasks.v2.GetTaskRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.tasks.v2.GetTaskRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getTask(request), expectedError); - }); + it('invokes getTask without error using callback', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.tasks.v2.GetTaskRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.tasks.v2.GetTaskRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.tasks.v2.Task(), + ); + client.innerApiCalls.getTask = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getTask( + request, + ( + err?: Error | null, + result?: protos.google.cloud.tasks.v2.ITask | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.getTask as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getTask as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('createTask', () => { - it('invokes createTask without error', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.tasks.v2.CreateTaskRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.tasks.v2.CreateTaskRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.tasks.v2.Task() - ); - client.innerApiCalls.createTask = stubSimpleCall(expectedResponse); - const [response] = await client.createTask(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createTask as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createTask as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getTask with error', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.tasks.v2.GetTaskRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.tasks.v2.GetTaskRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getTask = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.getTask(request), expectedError); + const actualRequest = (client.innerApiCalls.getTask as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getTask as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createTask without error using callback', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.tasks.v2.CreateTaskRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.tasks.v2.CreateTaskRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.tasks.v2.Task() - ); - client.innerApiCalls.createTask = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createTask( - request, - (err?: Error|null, result?: protos.google.cloud.tasks.v2.ITask|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createTask as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createTask as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getTask with closed client', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.tasks.v2.GetTaskRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.tasks.v2.GetTaskRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getTask(request), expectedError); + }); + }); + + describe('createTask', () => { + it('invokes createTask without error', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.tasks.v2.CreateTaskRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.tasks.v2.CreateTaskRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.tasks.v2.Task(), + ); + client.innerApiCalls.createTask = stubSimpleCall(expectedResponse); + const [response] = await client.createTask(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createTask as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createTask as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createTask with error', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.tasks.v2.CreateTaskRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.tasks.v2.CreateTaskRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createTask = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createTask(request), expectedError); - const actualRequest = (client.innerApiCalls.createTask as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createTask as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createTask without error using callback', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.tasks.v2.CreateTaskRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.tasks.v2.CreateTaskRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.tasks.v2.Task(), + ); + client.innerApiCalls.createTask = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createTask( + request, + ( + err?: Error | null, + result?: protos.google.cloud.tasks.v2.ITask | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createTask as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createTask as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createTask with closed client', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.tasks.v2.CreateTaskRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.tasks.v2.CreateTaskRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createTask(request), expectedError); - }); + it('invokes createTask with error', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.tasks.v2.CreateTaskRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.tasks.v2.CreateTaskRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createTask = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.createTask(request), expectedError); + const actualRequest = ( + client.innerApiCalls.createTask as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createTask as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('deleteTask', () => { - it('invokes deleteTask without error', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.tasks.v2.DeleteTaskRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.tasks.v2.DeleteTaskRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteTask = stubSimpleCall(expectedResponse); - const [response] = await client.deleteTask(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteTask as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteTask as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createTask with closed client', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.tasks.v2.CreateTaskRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.tasks.v2.CreateTaskRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.createTask(request), expectedError); + }); + }); + + describe('deleteTask', () => { + it('invokes deleteTask without error', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.tasks.v2.DeleteTaskRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.tasks.v2.DeleteTaskRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteTask = stubSimpleCall(expectedResponse); + const [response] = await client.deleteTask(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteTask as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteTask as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteTask without error using callback', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.tasks.v2.DeleteTaskRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.tasks.v2.DeleteTaskRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteTask = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteTask( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteTask as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteTask as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteTask without error using callback', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.tasks.v2.DeleteTaskRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.tasks.v2.DeleteTaskRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteTask = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteTask( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteTask as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteTask as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteTask with error', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.tasks.v2.DeleteTaskRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.tasks.v2.DeleteTaskRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteTask = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteTask(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteTask as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteTask as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteTask with error', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.tasks.v2.DeleteTaskRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.tasks.v2.DeleteTaskRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteTask = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.deleteTask(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteTask as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteTask as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteTask with closed client', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.tasks.v2.DeleteTaskRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.tasks.v2.DeleteTaskRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteTask(request), expectedError); - }); + it('invokes deleteTask with closed client', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.tasks.v2.DeleteTaskRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.tasks.v2.DeleteTaskRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.deleteTask(request), expectedError); + }); + }); + + describe('runTask', () => { + it('invokes runTask without error', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.tasks.v2.RunTaskRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.tasks.v2.RunTaskRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.tasks.v2.Task(), + ); + client.innerApiCalls.runTask = stubSimpleCall(expectedResponse); + const [response] = await client.runTask(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.runTask as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.runTask as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('runTask', () => { - it('invokes runTask without error', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.tasks.v2.RunTaskRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.tasks.v2.RunTaskRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.tasks.v2.Task() - ); - client.innerApiCalls.runTask = stubSimpleCall(expectedResponse); - const [response] = await client.runTask(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.runTask as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.runTask as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes runTask without error using callback', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.tasks.v2.RunTaskRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.tasks.v2.RunTaskRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.tasks.v2.Task(), + ); + client.innerApiCalls.runTask = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.runTask( + request, + ( + err?: Error | null, + result?: protos.google.cloud.tasks.v2.ITask | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.runTask as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.runTask as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes runTask without error using callback', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.tasks.v2.RunTaskRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.tasks.v2.RunTaskRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.tasks.v2.Task() - ); - client.innerApiCalls.runTask = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.runTask( - request, - (err?: Error|null, result?: protos.google.cloud.tasks.v2.ITask|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.runTask as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.runTask as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes runTask with error', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.tasks.v2.RunTaskRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.tasks.v2.RunTaskRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.runTask = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.runTask(request), expectedError); + const actualRequest = (client.innerApiCalls.runTask as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.runTask as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes runTask with error', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.tasks.v2.RunTaskRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.tasks.v2.RunTaskRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.runTask = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.runTask(request), expectedError); - const actualRequest = (client.innerApiCalls.runTask as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.runTask as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes runTask with closed client', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.tasks.v2.RunTaskRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.tasks.v2.RunTaskRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.runTask(request), expectedError); + }); + }); + + describe('listQueues', () => { + it('invokes listQueues without error', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.tasks.v2.ListQueuesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.tasks.v2.ListQueuesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.tasks.v2.Queue()), + generateSampleMessage(new protos.google.cloud.tasks.v2.Queue()), + generateSampleMessage(new protos.google.cloud.tasks.v2.Queue()), + ]; + client.innerApiCalls.listQueues = stubSimpleCall(expectedResponse); + const [response] = await client.listQueues(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listQueues as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listQueues as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes runTask with closed client', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.tasks.v2.RunTaskRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.tasks.v2.RunTaskRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.runTask(request), expectedError); - }); + it('invokes listQueues without error using callback', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.tasks.v2.ListQueuesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.tasks.v2.ListQueuesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.tasks.v2.Queue()), + generateSampleMessage(new protos.google.cloud.tasks.v2.Queue()), + generateSampleMessage(new protos.google.cloud.tasks.v2.Queue()), + ]; + client.innerApiCalls.listQueues = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listQueues( + request, + ( + err?: Error | null, + result?: protos.google.cloud.tasks.v2.IQueue[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listQueues as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listQueues as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('listQueues', () => { - it('invokes listQueues without error', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.tasks.v2.ListQueuesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.tasks.v2.ListQueuesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.tasks.v2.Queue()), - generateSampleMessage(new protos.google.cloud.tasks.v2.Queue()), - generateSampleMessage(new protos.google.cloud.tasks.v2.Queue()), - ]; - client.innerApiCalls.listQueues = stubSimpleCall(expectedResponse); - const [response] = await client.listQueues(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listQueues as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listQueues as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listQueues with error', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.tasks.v2.ListQueuesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.tasks.v2.ListQueuesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listQueues = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listQueues(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listQueues as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listQueues as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listQueues without error using callback', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.tasks.v2.ListQueuesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.tasks.v2.ListQueuesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.tasks.v2.Queue()), - generateSampleMessage(new protos.google.cloud.tasks.v2.Queue()), - generateSampleMessage(new protos.google.cloud.tasks.v2.Queue()), - ]; - client.innerApiCalls.listQueues = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listQueues( - request, - (err?: Error|null, result?: protos.google.cloud.tasks.v2.IQueue[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listQueues as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listQueues as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listQueuesStream without error', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.tasks.v2.ListQueuesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.tasks.v2.ListQueuesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.tasks.v2.Queue()), + generateSampleMessage(new protos.google.cloud.tasks.v2.Queue()), + generateSampleMessage(new protos.google.cloud.tasks.v2.Queue()), + ]; + client.descriptors.page.listQueues.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listQueuesStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.cloud.tasks.v2.Queue[] = []; + stream.on('data', (response: protos.google.cloud.tasks.v2.Queue) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listQueues.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listQueues, request), + ); + assert( + (client.descriptors.page.listQueues.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('invokes listQueues with error', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.tasks.v2.ListQueuesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.tasks.v2.ListQueuesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listQueues = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listQueues(request), expectedError); - const actualRequest = (client.innerApiCalls.listQueues as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listQueues as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listQueuesStream with error', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.tasks.v2.ListQueuesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.tasks.v2.ListQueuesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listQueues.createStream = stubPageStreamingCall( + undefined, + expectedError, + ); + const stream = client.listQueuesStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.cloud.tasks.v2.Queue[] = []; + stream.on('data', (response: protos.google.cloud.tasks.v2.Queue) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listQueues.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listQueues, request), + ); + assert( + (client.descriptors.page.listQueues.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('invokes listQueuesStream without error', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.tasks.v2.ListQueuesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.tasks.v2.ListQueuesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.tasks.v2.Queue()), - generateSampleMessage(new protos.google.cloud.tasks.v2.Queue()), - generateSampleMessage(new protos.google.cloud.tasks.v2.Queue()), - ]; - client.descriptors.page.listQueues.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listQueuesStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.cloud.tasks.v2.Queue[] = []; - stream.on('data', (response: protos.google.cloud.tasks.v2.Queue) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.listQueues.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listQueues, request)); - assert( - (client.descriptors.page.listQueues.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listQueues without error', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.tasks.v2.ListQueuesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.tasks.v2.ListQueuesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.tasks.v2.Queue()), + generateSampleMessage(new protos.google.cloud.tasks.v2.Queue()), + generateSampleMessage(new protos.google.cloud.tasks.v2.Queue()), + ]; + client.descriptors.page.listQueues.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.cloud.tasks.v2.IQueue[] = []; + const iterable = client.listQueuesAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + (client.descriptors.page.listQueues.asyncIterate as SinonStub).getCall( + 0, + ).args[1], + request, + ); + assert( + (client.descriptors.page.listQueues.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('invokes listQueuesStream with error', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.tasks.v2.ListQueuesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.tasks.v2.ListQueuesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listQueues.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listQueuesStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.cloud.tasks.v2.Queue[] = []; - stream.on('data', (response: protos.google.cloud.tasks.v2.Queue) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listQueues.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listQueues, request)); - assert( - (client.descriptors.page.listQueues.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listQueues with error', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.tasks.v2.ListQueuesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.tasks.v2.ListQueuesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listQueues.asyncIterate = stubAsyncIterationCall( + undefined, + expectedError, + ); + const iterable = client.listQueuesAsync(request); + await assert.rejects(async () => { + const responses: protos.google.cloud.tasks.v2.IQueue[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + (client.descriptors.page.listQueues.asyncIterate as SinonStub).getCall( + 0, + ).args[1], + request, + ); + assert( + (client.descriptors.page.listQueues.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + }); + + describe('listTasks', () => { + it('invokes listTasks without error', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.tasks.v2.ListTasksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.tasks.v2.ListTasksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.tasks.v2.Task()), + generateSampleMessage(new protos.google.cloud.tasks.v2.Task()), + generateSampleMessage(new protos.google.cloud.tasks.v2.Task()), + ]; + client.innerApiCalls.listTasks = stubSimpleCall(expectedResponse); + const [response] = await client.listTasks(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listTasks as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listTasks as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('uses async iteration with listQueues without error', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.tasks.v2.ListQueuesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.tasks.v2.ListQueuesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.tasks.v2.Queue()), - generateSampleMessage(new protos.google.cloud.tasks.v2.Queue()), - generateSampleMessage(new protos.google.cloud.tasks.v2.Queue()), - ]; - client.descriptors.page.listQueues.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.cloud.tasks.v2.IQueue[] = []; - const iterable = client.listQueuesAsync(request); - for await (const resource of iterable) { - responses.push(resource!); + it('invokes listTasks without error using callback', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.tasks.v2.ListTasksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.tasks.v2.ListTasksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.tasks.v2.Task()), + generateSampleMessage(new protos.google.cloud.tasks.v2.Task()), + generateSampleMessage(new protos.google.cloud.tasks.v2.Task()), + ]; + client.innerApiCalls.listTasks = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listTasks( + request, + ( + err?: Error | null, + result?: protos.google.cloud.tasks.v2.ITask[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listQueues.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listQueues.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); - - it('uses async iteration with listQueues with error', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.tasks.v2.ListQueuesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.tasks.v2.ListQueuesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listQueues.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listQueuesAsync(request); - await assert.rejects(async () => { - const responses: protos.google.cloud.tasks.v2.IQueue[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listQueues.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listQueues.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listTasks as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listTasks as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('listTasks', () => { - it('invokes listTasks without error', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.tasks.v2.ListTasksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.tasks.v2.ListTasksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.tasks.v2.Task()), - generateSampleMessage(new protos.google.cloud.tasks.v2.Task()), - generateSampleMessage(new protos.google.cloud.tasks.v2.Task()), - ]; - client.innerApiCalls.listTasks = stubSimpleCall(expectedResponse); - const [response] = await client.listTasks(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listTasks as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listTasks as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listTasks without error using callback', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.tasks.v2.ListTasksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.tasks.v2.ListTasksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.tasks.v2.Task()), - generateSampleMessage(new protos.google.cloud.tasks.v2.Task()), - generateSampleMessage(new protos.google.cloud.tasks.v2.Task()), - ]; - client.innerApiCalls.listTasks = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listTasks( - request, - (err?: Error|null, result?: protos.google.cloud.tasks.v2.ITask[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listTasks as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listTasks as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listTasks with error', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.tasks.v2.ListTasksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.tasks.v2.ListTasksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listTasks = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listTasks(request), expectedError); - const actualRequest = (client.innerApiCalls.listTasks as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listTasks as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listTasksStream without error', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.tasks.v2.ListTasksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.tasks.v2.ListTasksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.tasks.v2.Task()), - generateSampleMessage(new protos.google.cloud.tasks.v2.Task()), - generateSampleMessage(new protos.google.cloud.tasks.v2.Task()), - ]; - client.descriptors.page.listTasks.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listTasksStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.cloud.tasks.v2.Task[] = []; - stream.on('data', (response: protos.google.cloud.tasks.v2.Task) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.listTasks.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listTasks, request)); - assert( - (client.descriptors.page.listTasks.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listTasks with error', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.tasks.v2.ListTasksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.tasks.v2.ListTasksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listTasks = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.listTasks(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listTasks as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listTasks as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listTasksStream with error', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.tasks.v2.ListTasksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.tasks.v2.ListTasksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listTasks.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listTasksStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.cloud.tasks.v2.Task[] = []; - stream.on('data', (response: protos.google.cloud.tasks.v2.Task) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listTasks.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listTasks, request)); - assert( - (client.descriptors.page.listTasks.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listTasksStream without error', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.tasks.v2.ListTasksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.tasks.v2.ListTasksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.tasks.v2.Task()), + generateSampleMessage(new protos.google.cloud.tasks.v2.Task()), + generateSampleMessage(new protos.google.cloud.tasks.v2.Task()), + ]; + client.descriptors.page.listTasks.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listTasksStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.cloud.tasks.v2.Task[] = []; + stream.on('data', (response: protos.google.cloud.tasks.v2.Task) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listTasks.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listTasks, request), + ); + assert( + (client.descriptors.page.listTasks.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('uses async iteration with listTasks without error', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.tasks.v2.ListTasksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.tasks.v2.ListTasksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.tasks.v2.Task()), - generateSampleMessage(new protos.google.cloud.tasks.v2.Task()), - generateSampleMessage(new protos.google.cloud.tasks.v2.Task()), - ]; - client.descriptors.page.listTasks.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.cloud.tasks.v2.ITask[] = []; - const iterable = client.listTasksAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listTasks.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listTasks.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listTasksStream with error', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.tasks.v2.ListTasksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.tasks.v2.ListTasksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listTasks.createStream = stubPageStreamingCall( + undefined, + expectedError, + ); + const stream = client.listTasksStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.cloud.tasks.v2.Task[] = []; + stream.on('data', (response: protos.google.cloud.tasks.v2.Task) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listTasks.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listTasks, request), + ); + assert( + (client.descriptors.page.listTasks.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('uses async iteration with listTasks with error', async () => { - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.tasks.v2.ListTasksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.tasks.v2.ListTasksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listTasks.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listTasksAsync(request); - await assert.rejects(async () => { - const responses: protos.google.cloud.tasks.v2.ITask[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listTasks.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listTasks.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listTasks without error', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.tasks.v2.ListTasksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.tasks.v2.ListTasksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.tasks.v2.Task()), + generateSampleMessage(new protos.google.cloud.tasks.v2.Task()), + generateSampleMessage(new protos.google.cloud.tasks.v2.Task()), + ]; + client.descriptors.page.listTasks.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.cloud.tasks.v2.ITask[] = []; + const iterable = client.listTasksAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + (client.descriptors.page.listTasks.asyncIterate as SinonStub).getCall(0) + .args[1], + request, + ); + assert( + (client.descriptors.page.listTasks.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); }); - describe('Path templates', () => { - - describe('queue', async () => { - const fakePath = "/rendered/path/queue"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - queue: "queueValue", - }; - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.queuePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.queuePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('queuePath', () => { - const result = client.queuePath("projectValue", "locationValue", "queueValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.queuePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromQueueName', () => { - const result = client.matchProjectFromQueueName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.queuePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromQueueName', () => { - const result = client.matchLocationFromQueueName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.queuePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchQueueFromQueueName', () => { - const result = client.matchQueueFromQueueName(fakePath); - assert.strictEqual(result, "queueValue"); - assert((client.pathTemplates.queuePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('uses async iteration with listTasks with error', async () => { + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.tasks.v2.ListTasksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.tasks.v2.ListTasksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listTasks.asyncIterate = stubAsyncIterationCall( + undefined, + expectedError, + ); + const iterable = client.listTasksAsync(request); + await assert.rejects(async () => { + const responses: protos.google.cloud.tasks.v2.ITask[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + (client.descriptors.page.listTasks.asyncIterate as SinonStub).getCall(0) + .args[1], + request, + ); + assert( + (client.descriptors.page.listTasks.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + }); + + describe('Path templates', () => { + describe('queue', async () => { + const fakePath = '/rendered/path/queue'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + queue: 'queueValue', + }; + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.queuePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.queuePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('queuePath', () => { + const result = client.queuePath( + 'projectValue', + 'locationValue', + 'queueValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.queuePathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromQueueName', () => { + const result = client.matchProjectFromQueueName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.queuePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromQueueName', () => { + const result = client.matchLocationFromQueueName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.queuePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchQueueFromQueueName', () => { + const result = client.matchQueueFromQueueName(fakePath); + assert.strictEqual(result, 'queueValue'); + assert( + (client.pathTemplates.queuePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('task', async () => { - const fakePath = "/rendered/path/task"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - queue: "queueValue", - task: "taskValue", - }; - const client = new cloudtasksModule.v2.CloudTasksClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.taskPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.taskPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('taskPath', () => { - const result = client.taskPath("projectValue", "locationValue", "queueValue", "taskValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.taskPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromTaskName', () => { - const result = client.matchProjectFromTaskName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.taskPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromTaskName', () => { - const result = client.matchLocationFromTaskName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.taskPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchQueueFromTaskName', () => { - const result = client.matchQueueFromTaskName(fakePath); - assert.strictEqual(result, "queueValue"); - assert((client.pathTemplates.taskPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchTaskFromTaskName', () => { - const result = client.matchTaskFromTaskName(fakePath); - assert.strictEqual(result, "taskValue"); - assert((client.pathTemplates.taskPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('task', async () => { + const fakePath = '/rendered/path/task'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + queue: 'queueValue', + task: 'taskValue', + }; + const client = new cloudtasksModule.v2.CloudTasksClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.taskPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.taskPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('taskPath', () => { + const result = client.taskPath( + 'projectValue', + 'locationValue', + 'queueValue', + 'taskValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.taskPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromTaskName', () => { + const result = client.matchProjectFromTaskName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.taskPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromTaskName', () => { + const result = client.matchLocationFromTaskName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.taskPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchQueueFromTaskName', () => { + const result = client.matchQueueFromTaskName(fakePath); + assert.strictEqual(result, 'queueValue'); + assert( + (client.pathTemplates.taskPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchTaskFromTaskName', () => { + const result = client.matchTaskFromTaskName(fakePath); + assert.strictEqual(result, 'taskValue'); + assert( + (client.pathTemplates.taskPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/core/generator/gapic-generator-typescript/baselines/texttospeech-esm/esm/src/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/texttospeech-esm/esm/src/index.ts.baseline index 8eecaa206fae..701c9eea73c5 100644 --- a/core/generator/gapic-generator-typescript/baselines/texttospeech-esm/esm/src/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/texttospeech-esm/esm/src/index.ts.baseline @@ -19,8 +19,8 @@ import * as v1 from './v1/index.js'; const TextToSpeechClient = v1.TextToSpeechClient; type TextToSpeechClient = v1.TextToSpeechClient; -export {v1, TextToSpeechClient}; -export default {v1, TextToSpeechClient}; +export { v1, TextToSpeechClient }; +export default { v1, TextToSpeechClient }; // @ts-ignore import * as protos from '../../protos/protos.js'; -export {protos} +export { protos }; diff --git a/core/generator/gapic-generator-typescript/baselines/texttospeech-esm/esm/src/v1/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/texttospeech-esm/esm/src/v1/index.ts.baseline index b53ab6649812..11edf459a9b5 100644 --- a/core/generator/gapic-generator-typescript/baselines/texttospeech-esm/esm/src/v1/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/texttospeech-esm/esm/src/v1/index.ts.baseline @@ -16,4 +16,4 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -export {TextToSpeechClient} from './text_to_speech_client.js'; +export { TextToSpeechClient } from './text_to_speech_client.js'; diff --git a/core/generator/gapic-generator-typescript/baselines/texttospeech-esm/esm/src/v1/text_to_speech_client.ts.baseline b/core/generator/gapic-generator-typescript/baselines/texttospeech-esm/esm/src/v1/text_to_speech_client.ts.baseline index 78b7f9648850..f9702863d294 100644 --- a/core/generator/gapic-generator-typescript/baselines/texttospeech-esm/esm/src/v1/text_to_speech_client.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/texttospeech-esm/esm/src/v1/text_to_speech_client.ts.baseline @@ -18,15 +18,20 @@ /* global window */ import * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions} from 'google-gax'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, +} from 'google-gax'; // @ts-ignore import type * as protos from '../../../protos/protos.js'; import * as text_to_speech_client_config from './text_to_speech_client_config.json'; import fs from 'fs'; import path from 'path'; -import {fileURLToPath} from 'url'; -import {getJSON} from '../json-helper.cjs'; +import { fileURLToPath } from 'url'; +import { getJSON } from '../json-helper.cjs'; // @ts-ignore const dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -36,15 +41,15 @@ const dirname = path.dirname(fileURLToPath(import.meta.url)); * This file defines retry strategy and timeouts for all API methods in this library. */ const gapicConfig = getJSON( - path.join(dirname, 'text_to_speech_client_config.json') + path.join(dirname, 'text_to_speech_client_config.json'), ); const jsonProtos = getJSON( - path.join(dirname, '..', '..', '..', 'protos/protos.json') + path.join(dirname, '..', '..', '..', 'protos/protos.json'), ); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; const version = getJSON( - path.join(dirname, '..', '..', '..', '..', 'package.json') + path.join(dirname, '..', '..', '..', '..', 'package.json'), ).version; /** @@ -59,7 +64,7 @@ export class TextToSpeechClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('text-to-speech'); @@ -71,8 +76,8 @@ export class TextToSpeechClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - textToSpeechStub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + textToSpeechStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of TextToSpeechClient. @@ -114,21 +119,42 @@ export class TextToSpeechClient { * const client = new TextToSpeechClient({fallback: 'rest'}, gax); * ``` */ - constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { // Ensure that options include all the required fields. const staticMembers = this.constructor as typeof TextToSpeechClient; - if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { - throw new Error('Please set either universe_domain or universeDomain, but not both.'); + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); } - const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; - this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; this._servicePath = 'texttospeech.' + this._universeDomain; - const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; - const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. if (servicePath !== this._servicePath && !('scopes' in opts)) { @@ -150,7 +176,7 @@ export class TextToSpeechClient { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; @@ -167,10 +193,7 @@ export class TextToSpeechClient { const isEsm = true; const isEsmString = isEsm ? '-esm' : '-cjs'; // Determine the client header string. - const clientHeader = [ - `gax/${this._gaxModule.version}`, - `gapic/${version}`, - ]; + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/{process.versions.node}${isEsmString}`); } else { @@ -178,7 +201,7 @@ export class TextToSpeechClient { } if (!opts.fallback) { clientHeader.push(`grpc/${this._gaxGrpc.grpcVersion}`); - } else if (opts.fallback === 'rest' ) { + } else if (opts.fallback === 'rest') { clientHeader.push(`rest/${this._gaxGrpc.grpcVersion}`); } if (opts.libName && opts.libVersion) { @@ -186,12 +209,17 @@ export class TextToSpeechClient { } // Load the applicable protos. - this._protos = this._gaxGrpc.loadProtoJSON(jsonProtos as gax.protobuf.INamespace); + this._protos = this._gaxGrpc.loadProtoJSON( + jsonProtos as gax.protobuf.INamespace, + ); // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.cloud.texttospeech.v1.TextToSpeech', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.cloud.texttospeech.v1.TextToSpeech', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + { 'x-goog-api-client': clientHeader.join(' ') }, + ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -222,36 +250,40 @@ export class TextToSpeechClient { // Put together the "service stub" for // google.cloud.texttospeech.v1.TextToSpeech. this.textToSpeechStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.cloud.texttospeech.v1.TextToSpeech') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.cloud.texttospeech.v1.TextToSpeech', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.cloud.texttospeech.v1.TextToSpeech, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts, + this._providedCustomServicePath, + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const textToSpeechStubMethods = - ['listVoices', 'synthesizeSpeech']; + const textToSpeechStubMethods = ['listVoices', 'synthesizeSpeech']; for (const methodName of textToSpeechStubMethods) { const callPromise = this.textToSpeechStub.then( - stub => (...args: Array<{}>) => { - if (this._terminated) { - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error|null|undefined) => () => { + (stub) => + (...args: Array<{}>) => { + if (this._terminated) { + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { throw err; - }); + }, + ); - const descriptor = - undefined; + const descriptor = undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -266,8 +298,14 @@ export class TextToSpeechClient { * @returns {string} The DNS address for this service. */ static get servicePath() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'texttospeech.googleapis.com'; } @@ -279,8 +317,14 @@ export class TextToSpeechClient { * @returns {string} The DNS address for this service. */ static get apiEndpoint() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'texttospeech.googleapis.com'; } @@ -311,9 +355,7 @@ export class TextToSpeechClient { * @returns {string[]} List of default scopes. */ static get scopes() { - return [ - 'https://www.googleapis.com/auth/cloud-platform' - ]; + return ['https://www.googleapis.com/auth/cloud-platform']; } getProjectId(): Promise; @@ -322,8 +364,9 @@ export class TextToSpeechClient { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId(callback?: Callback): - Promise|void { + getProjectId( + callback?: Callback, + ): Promise | void { if (callback) { this.auth.getProjectId(callback); return; @@ -334,196 +377,276 @@ export class TextToSpeechClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Returns a list of Voice supported for synthesis. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} [request.languageCode] - * Optional. Recommended. - * [BCP-47](https://www.rfc-editor.org/rfc/bcp/bcp47.txt) language tag. If - * specified, the ListVoices call will only return voices that can be used to - * synthesize this language_code. E.g. when specifying "en-NZ", you will get - * supported "en-*" voices; when specifying "no", you will get supported - * "no-*" (Norwegian) and "nb-*" (Norwegian Bokmal) voices; specifying "zh" - * will also get supported "cmn-*" voices; specifying "zh-hk" will also get - * supported "yue-*" voices. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.texttospeech.v1.ListVoicesResponse|ListVoicesResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1/text_to_speech.list_voices.js - * region_tag:texttospeech_v1_generated_TextToSpeech_ListVoices_async - */ + /** + * Returns a list of Voice supported for synthesis. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} [request.languageCode] + * Optional. Recommended. + * [BCP-47](https://www.rfc-editor.org/rfc/bcp/bcp47.txt) language tag. If + * specified, the ListVoices call will only return voices that can be used to + * synthesize this language_code. E.g. when specifying "en-NZ", you will get + * supported "en-*" voices; when specifying "no", you will get supported + * "no-*" (Norwegian) and "nb-*" (Norwegian Bokmal) voices; specifying "zh" + * will also get supported "cmn-*" voices; specifying "zh-hk" will also get + * supported "yue-*" voices. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.texttospeech.v1.ListVoicesResponse|ListVoicesResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/text_to_speech.list_voices.js + * region_tag:texttospeech_v1_generated_TextToSpeech_ListVoices_async + */ listVoices( - request?: protos.google.cloud.texttospeech.v1.IListVoicesRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.texttospeech.v1.IListVoicesResponse, - protos.google.cloud.texttospeech.v1.IListVoicesRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.texttospeech.v1.IListVoicesRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.texttospeech.v1.IListVoicesResponse, + protos.google.cloud.texttospeech.v1.IListVoicesRequest | undefined, + {} | undefined, + ] + >; listVoices( - request: protos.google.cloud.texttospeech.v1.IListVoicesRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.texttospeech.v1.IListVoicesResponse, - protos.google.cloud.texttospeech.v1.IListVoicesRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.texttospeech.v1.IListVoicesRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.texttospeech.v1.IListVoicesResponse, + protos.google.cloud.texttospeech.v1.IListVoicesRequest | null | undefined, + {} | null | undefined + >, + ): void; listVoices( - request: protos.google.cloud.texttospeech.v1.IListVoicesRequest, - callback: Callback< - protos.google.cloud.texttospeech.v1.IListVoicesResponse, - protos.google.cloud.texttospeech.v1.IListVoicesRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.texttospeech.v1.IListVoicesRequest, + callback: Callback< + protos.google.cloud.texttospeech.v1.IListVoicesResponse, + protos.google.cloud.texttospeech.v1.IListVoicesRequest | null | undefined, + {} | null | undefined + >, + ): void; listVoices( - request?: protos.google.cloud.texttospeech.v1.IListVoicesRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.texttospeech.v1.IListVoicesResponse, - protos.google.cloud.texttospeech.v1.IListVoicesRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.texttospeech.v1.IListVoicesRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.texttospeech.v1.IListVoicesResponse, - protos.google.cloud.texttospeech.v1.IListVoicesRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.texttospeech.v1.IListVoicesResponse, - protos.google.cloud.texttospeech.v1.IListVoicesRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.texttospeech.v1.IListVoicesRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.texttospeech.v1.IListVoicesResponse, + protos.google.cloud.texttospeech.v1.IListVoicesRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.texttospeech.v1.IListVoicesResponse, + protos.google.cloud.texttospeech.v1.IListVoicesRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listVoices request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.texttospeech.v1.IListVoicesResponse, - protos.google.cloud.texttospeech.v1.IListVoicesRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.texttospeech.v1.IListVoicesResponse, + | protos.google.cloud.texttospeech.v1.IListVoicesRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('listVoices response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.listVoices(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.texttospeech.v1.IListVoicesResponse, - protos.google.cloud.texttospeech.v1.IListVoicesRequest|undefined, {}|undefined - ]) => { - this._log.info('listVoices response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .listVoices(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.texttospeech.v1.IListVoicesResponse, + protos.google.cloud.texttospeech.v1.IListVoicesRequest | undefined, + {} | undefined, + ]) => { + this._log.info('listVoices response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Synthesizes speech synchronously: receive results after all text input - * has been processed. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.cloud.texttospeech.v1.SynthesisInput} request.input - * Required. The Synthesizer requires either plain text or SSML as input. - * @param {google.cloud.texttospeech.v1.VoiceSelectionParams} request.voice - * Required. The desired voice of the synthesized audio. - * @param {google.cloud.texttospeech.v1.AudioConfig} request.audioConfig - * Required. The configuration of the synthesized audio. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.texttospeech.v1.SynthesizeSpeechResponse|SynthesizeSpeechResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1/text_to_speech.synthesize_speech.js - * region_tag:texttospeech_v1_generated_TextToSpeech_SynthesizeSpeech_async - */ + /** + * Synthesizes speech synchronously: receive results after all text input + * has been processed. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.cloud.texttospeech.v1.SynthesisInput} request.input + * Required. The Synthesizer requires either plain text or SSML as input. + * @param {google.cloud.texttospeech.v1.VoiceSelectionParams} request.voice + * Required. The desired voice of the synthesized audio. + * @param {google.cloud.texttospeech.v1.AudioConfig} request.audioConfig + * Required. The configuration of the synthesized audio. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.texttospeech.v1.SynthesizeSpeechResponse|SynthesizeSpeechResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/text_to_speech.synthesize_speech.js + * region_tag:texttospeech_v1_generated_TextToSpeech_SynthesizeSpeech_async + */ synthesizeSpeech( - request?: protos.google.cloud.texttospeech.v1.ISynthesizeSpeechRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.texttospeech.v1.ISynthesizeSpeechResponse, - protos.google.cloud.texttospeech.v1.ISynthesizeSpeechRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.texttospeech.v1.ISynthesizeSpeechRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.texttospeech.v1.ISynthesizeSpeechResponse, + protos.google.cloud.texttospeech.v1.ISynthesizeSpeechRequest | undefined, + {} | undefined, + ] + >; synthesizeSpeech( - request: protos.google.cloud.texttospeech.v1.ISynthesizeSpeechRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.texttospeech.v1.ISynthesizeSpeechResponse, - protos.google.cloud.texttospeech.v1.ISynthesizeSpeechRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.texttospeech.v1.ISynthesizeSpeechRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.texttospeech.v1.ISynthesizeSpeechResponse, + | protos.google.cloud.texttospeech.v1.ISynthesizeSpeechRequest + | null + | undefined, + {} | null | undefined + >, + ): void; synthesizeSpeech( - request: protos.google.cloud.texttospeech.v1.ISynthesizeSpeechRequest, - callback: Callback< - protos.google.cloud.texttospeech.v1.ISynthesizeSpeechResponse, - protos.google.cloud.texttospeech.v1.ISynthesizeSpeechRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.texttospeech.v1.ISynthesizeSpeechRequest, + callback: Callback< + protos.google.cloud.texttospeech.v1.ISynthesizeSpeechResponse, + | protos.google.cloud.texttospeech.v1.ISynthesizeSpeechRequest + | null + | undefined, + {} | null | undefined + >, + ): void; synthesizeSpeech( - request?: protos.google.cloud.texttospeech.v1.ISynthesizeSpeechRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.cloud.texttospeech.v1.ISynthesizeSpeechRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.texttospeech.v1.ISynthesizeSpeechResponse, - protos.google.cloud.texttospeech.v1.ISynthesizeSpeechRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.cloud.texttospeech.v1.ISynthesizeSpeechResponse, - protos.google.cloud.texttospeech.v1.ISynthesizeSpeechRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.texttospeech.v1.ISynthesizeSpeechResponse, - protos.google.cloud.texttospeech.v1.ISynthesizeSpeechRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.texttospeech.v1.ISynthesizeSpeechRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.texttospeech.v1.ISynthesizeSpeechResponse, + | protos.google.cloud.texttospeech.v1.ISynthesizeSpeechRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.texttospeech.v1.ISynthesizeSpeechResponse, + protos.google.cloud.texttospeech.v1.ISynthesizeSpeechRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('synthesizeSpeech request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.texttospeech.v1.ISynthesizeSpeechResponse, - protos.google.cloud.texttospeech.v1.ISynthesizeSpeechRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.texttospeech.v1.ISynthesizeSpeechResponse, + | protos.google.cloud.texttospeech.v1.ISynthesizeSpeechRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('synthesizeSpeech response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.synthesizeSpeech(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.texttospeech.v1.ISynthesizeSpeechResponse, - protos.google.cloud.texttospeech.v1.ISynthesizeSpeechRequest|undefined, {}|undefined - ]) => { - this._log.info('synthesizeSpeech response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .synthesizeSpeech(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.texttospeech.v1.ISynthesizeSpeechResponse, + ( + | protos.google.cloud.texttospeech.v1.ISynthesizeSpeechRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('synthesizeSpeech response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } - /** * Terminate the gRPC channel and close the client. * @@ -532,7 +655,7 @@ export class TextToSpeechClient { */ close(): Promise { if (this.textToSpeechStub && !this._terminated) { - return this.textToSpeechStub.then(stub => { + return this.textToSpeechStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -540,4 +663,4 @@ export class TextToSpeechClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/core/generator/gapic-generator-typescript/baselines/texttospeech-esm/esm/system-test/fixtures/sample/src/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/texttospeech-esm/esm/system-test/fixtures/sample/src/index.ts.baseline index 74618c48da6c..a5b0e24e1083 100644 --- a/core/generator/gapic-generator-typescript/baselines/texttospeech-esm/esm/system-test/fixtures/sample/src/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/texttospeech-esm/esm/system-test/fixtures/sample/src/index.ts.baseline @@ -17,7 +17,7 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -import {TextToSpeechClient} from '@google-cloud/text-to-speech'; +import { TextToSpeechClient } from '@google-cloud/text-to-speech'; // check that the client class type name can be used function doStuffWithTextToSpeechClient(client: TextToSpeechClient) { diff --git a/core/generator/gapic-generator-typescript/baselines/texttospeech-esm/esm/system-test/install.ts.baseline b/core/generator/gapic-generator-typescript/baselines/texttospeech-esm/esm/system-test/install.ts.baseline index e079c4fa1101..d109fdd8c97f 100644 --- a/core/generator/gapic-generator-typescript/baselines/texttospeech-esm/esm/system-test/install.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/texttospeech-esm/esm/system-test/install.ts.baseline @@ -16,40 +16,45 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -import {packNTest} from 'pack-n-play'; -import {readFileSync} from 'fs'; -import {describe, it} from 'mocha'; +import { packNTest } from 'pack-n-play'; +import { readFileSync } from 'fs'; +import { describe, it } from 'mocha'; describe('📦 pack-n-play test', () => { - it('TypeScript', async function() { + it('TypeScript', async function () { this.timeout(300000); await packNTest({ packageDir: process.cwd(), sample: { description: 'TypeScript user can use the type definitions', - ts: readFileSync('./esm/system-test/fixtures/sample/src/index.ts').toString() - } + ts: readFileSync( + './esm/system-test/fixtures/sample/src/index.ts', + ).toString(), + }, }); }); - it('ESM module', async function() { + it('ESM module', async function () { this.timeout(300000); await packNTest({ sample: { description: 'Should be able to import using ESM', - esm: readFileSync('./esm/system-test/fixtures/sample/src/index.js').toString(), + esm: readFileSync( + './esm/system-test/fixtures/sample/src/index.js', + ).toString(), }, }); }); - it('CJS module', async function() { + it('CJS module', async function () { this.timeout(300000); await packNTest({ sample: { description: 'Should be able to import using CJS', - cjs: readFileSync('./esm/system-test/fixtures/sample/src/index.cjs').toString(), + cjs: readFileSync( + './esm/system-test/fixtures/sample/src/index.cjs', + ).toString(), }, }); }); - }); diff --git a/core/generator/gapic-generator-typescript/baselines/texttospeech-esm/esm/test/gapic_text_to_speech_v1.ts.baseline b/core/generator/gapic-generator-typescript/baselines/texttospeech-esm/esm/test/gapic_text_to_speech_v1.ts.baseline index 58e28b8f3b9f..85e0f95790f6 100644 --- a/core/generator/gapic-generator-typescript/baselines/texttospeech-esm/esm/test/gapic_text_to_speech_v1.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/texttospeech-esm/esm/test/gapic_text_to_speech_v1.ts.baseline @@ -20,14 +20,14 @@ import * as protos from '../../protos/protos.js'; import assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as texttospeechModule from '../src/index.js'; -import {protobuf} from 'google-gax'; +import { protobuf } from 'google-gax'; import fs from 'fs'; import path from 'path'; -import {fileURLToPath} from 'url'; +import { fileURLToPath } from 'url'; // @ts-ignore const dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -35,339 +35,406 @@ const dirname = path.dirname(fileURLToPath(import.meta.url)); // to fill in default values for request objects const root = protobuf.Root.fromJSON( JSON.parse( - fs.readFileSync(path.join(dirname, '..', '..', 'protos/protos.json'), 'utf8') - )) + fs.readFileSync( + path.join(dirname, '..', '..', 'protos/protos.json'), + 'utf8', + ), + ), +); // eslint-disable-next-line @typescript-eslint/no-unused-vars function getTypeDefaultValue(typeName: string, fields: string[]) { - let type = root.lookupType(typeName) as protobuf.Type; - for (const field of fields.slice(0, -1)) { - type = type?.fields[field]?.resolvedType as protobuf.Type; - } - return type?.fields[fields[fields.length - 1]]?.defaultValue ?? null; + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type?.fields[field]?.resolvedType as protobuf.Type; + } + return type?.fields[fields[fields.length - 1]]?.defaultValue ?? null; } function generateSampleMessage(instance: T) { - const filledObject = (instance.constructor as typeof protobuf.Message) - .toObject(instance as protobuf.Message, {defaults: true}); - return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, { defaults: true }); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; } function stubSimpleCall(response?: ResponseType, error?: Error) { - return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); } -function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { - return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +function stubSimpleCallWithCallback( + response?: ResponseType, + error?: Error, +) { + return error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); } describe('v1.TextToSpeechClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new texttospeechModule.v1.TextToSpeechClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'texttospeech.googleapis.com'); - }); - - it('has universeDomain', () => { - const client = new texttospeechModule.v1.TextToSpeechClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new texttospeechModule.v1.TextToSpeechClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'texttospeech.googleapis.com'); + }); - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - it('throws DeprecationWarning if static servicePath is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const servicePath = texttospeechModule.v1.TextToSpeechClient.servicePath; - assert.strictEqual(servicePath, 'texttospeech.googleapis.com'); - assert(stub.called); - stub.restore(); - }); + it('has universeDomain', () => { + const client = new texttospeechModule.v1.TextToSpeechClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = texttospeechModule.v1.TextToSpeechClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'texttospeech.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new texttospeechModule.v1.TextToSpeechClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'texttospeech.example.com'); - }); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = + texttospeechModule.v1.TextToSpeechClient.servicePath; + assert.strictEqual(servicePath, 'texttospeech.googleapis.com'); + assert(stub.called); + stub.restore(); + }); - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new texttospeechModule.v1.TextToSpeechClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'texttospeech.example.com'); - }); + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + texttospeechModule.v1.TextToSpeechClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'texttospeech.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = new texttospeechModule.v1.TextToSpeechClient({ + universeDomain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'texttospeech.example.com'); + }); - if (typeof process === 'object' && 'env' in process) { - describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { - it('sets apiEndpoint from environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new texttospeechModule.v1.TextToSpeechClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'texttospeech.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = new texttospeechModule.v1.TextToSpeechClient({ + universe_domain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'texttospeech.example.com'); + }); - it('value configured in code has priority over environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new texttospeechModule.v1.TextToSpeechClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'texttospeech.configured.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { new texttospeechModule.v1.TextToSpeechClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); + if (typeof process === 'object' && 'env' in process) { + describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { + it('sets apiEndpoint from environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new texttospeechModule.v1.TextToSpeechClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'texttospeech.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - it('has port', () => { - const port = texttospeechModule.v1.TextToSpeechClient.port; - assert(port); - assert(typeof port === 'number'); + it('value configured in code has priority over environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new texttospeechModule.v1.TextToSpeechClient({ + universeDomain: 'configured.example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual( + servicePath, + 'texttospeech.configured.example.com', + ); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - - it('should create a client with no option', () => { - const client = new texttospeechModule.v1.TextToSpeechClient(); - assert(client); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new texttospeechModule.v1.TextToSpeechClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); + }); - it('should create a client with gRPC fallback', () => { - const client = new texttospeechModule.v1.TextToSpeechClient({ - fallback: true, - }); - assert(client); - }); + it('has port', () => { + const port = texttospeechModule.v1.TextToSpeechClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('has initialize method and supports deferred initialization', async () => { - const client = new texttospeechModule.v1.TextToSpeechClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.textToSpeechStub, undefined); - await client.initialize(); - assert(client.textToSpeechStub); - }); + it('should create a client with no option', () => { + const client = new texttospeechModule.v1.TextToSpeechClient(); + assert(client); + }); - it('has close method for the initialized client', done => { - const client = new texttospeechModule.v1.TextToSpeechClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.textToSpeechStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('should create a client with gRPC fallback', () => { + const client = new texttospeechModule.v1.TextToSpeechClient({ + fallback: true, + }); + assert(client); + }); - it('has close method for the non-initialized client', done => { - const client = new texttospeechModule.v1.TextToSpeechClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.textToSpeechStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('has initialize method and supports deferred initialization', async () => { + const client = new texttospeechModule.v1.TextToSpeechClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.textToSpeechStub, undefined); + await client.initialize(); + assert(client.textToSpeechStub); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new texttospeechModule.v1.TextToSpeechClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + it('has close method for the initialized client', (done) => { + const client = new texttospeechModule.v1.TextToSpeechClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.textToSpeechStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new texttospeechModule.v1.TextToSpeechClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId((err?: Error|null, projectId?: string|null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } - }); - }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); + it('has close method for the non-initialized client', (done) => { + const client = new texttospeechModule.v1.TextToSpeechClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.textToSpeechStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); }); - describe('listVoices', () => { - it('invokes listVoices without error', async () => { - const client = new texttospeechModule.v1.TextToSpeechClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.texttospeech.v1.ListVoicesRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.cloud.texttospeech.v1.ListVoicesResponse() - ); - client.innerApiCalls.listVoices = stubSimpleCall(expectedResponse); - const [response] = await client.listVoices(request); - assert.deepStrictEqual(response, expectedResponse); - }); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new texttospeechModule.v1.TextToSpeechClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + }); - it('invokes listVoices without error using callback', async () => { - const client = new texttospeechModule.v1.TextToSpeechClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.texttospeech.v1.ListVoicesRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.cloud.texttospeech.v1.ListVoicesResponse() - ); - client.innerApiCalls.listVoices = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listVoices( - request, - (err?: Error|null, result?: protos.google.cloud.texttospeech.v1.IListVoicesResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new texttospeechModule.v1.TextToSpeechClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + }); - it('invokes listVoices with error', async () => { - const client = new texttospeechModule.v1.TextToSpeechClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.texttospeech.v1.ListVoicesRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.listVoices = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listVoices(request), expectedError); - }); + describe('listVoices', () => { + it('invokes listVoices without error', async () => { + const client = new texttospeechModule.v1.TextToSpeechClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.texttospeech.v1.ListVoicesRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.cloud.texttospeech.v1.ListVoicesResponse(), + ); + client.innerApiCalls.listVoices = stubSimpleCall(expectedResponse); + const [response] = await client.listVoices(request); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes listVoices with closed client', async () => { - const client = new texttospeechModule.v1.TextToSpeechClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.texttospeech.v1.ListVoicesRequest() - ); - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.listVoices(request), expectedError); - }); + it('invokes listVoices without error using callback', async () => { + const client = new texttospeechModule.v1.TextToSpeechClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.texttospeech.v1.ListVoicesRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.cloud.texttospeech.v1.ListVoicesResponse(), + ); + client.innerApiCalls.listVoices = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listVoices( + request, + ( + err?: Error | null, + result?: protos.google.cloud.texttospeech.v1.IListVoicesResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); }); - describe('synthesizeSpeech', () => { - it('invokes synthesizeSpeech without error', async () => { - const client = new texttospeechModule.v1.TextToSpeechClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.texttospeech.v1.SynthesizeSpeechRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.cloud.texttospeech.v1.SynthesizeSpeechResponse() - ); - client.innerApiCalls.synthesizeSpeech = stubSimpleCall(expectedResponse); - const [response] = await client.synthesizeSpeech(request); - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes listVoices with error', async () => { + const client = new texttospeechModule.v1.TextToSpeechClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.texttospeech.v1.ListVoicesRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.listVoices = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listVoices(request), expectedError); + }); - it('invokes synthesizeSpeech without error using callback', async () => { - const client = new texttospeechModule.v1.TextToSpeechClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.texttospeech.v1.SynthesizeSpeechRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.cloud.texttospeech.v1.SynthesizeSpeechResponse() - ); - client.innerApiCalls.synthesizeSpeech = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.synthesizeSpeech( - request, - (err?: Error|null, result?: protos.google.cloud.texttospeech.v1.ISynthesizeSpeechResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes listVoices with closed client', async () => { + const client = new texttospeechModule.v1.TextToSpeechClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.texttospeech.v1.ListVoicesRequest(), + ); + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.listVoices(request), expectedError); + }); + }); - it('invokes synthesizeSpeech with error', async () => { - const client = new texttospeechModule.v1.TextToSpeechClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.texttospeech.v1.SynthesizeSpeechRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.synthesizeSpeech = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.synthesizeSpeech(request), expectedError); - }); + describe('synthesizeSpeech', () => { + it('invokes synthesizeSpeech without error', async () => { + const client = new texttospeechModule.v1.TextToSpeechClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.texttospeech.v1.SynthesizeSpeechRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.cloud.texttospeech.v1.SynthesizeSpeechResponse(), + ); + client.innerApiCalls.synthesizeSpeech = stubSimpleCall(expectedResponse); + const [response] = await client.synthesizeSpeech(request); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes synthesizeSpeech with closed client', async () => { - const client = new texttospeechModule.v1.TextToSpeechClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.texttospeech.v1.SynthesizeSpeechRequest() - ); - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.synthesizeSpeech(request), expectedError); - }); + it('invokes synthesizeSpeech without error using callback', async () => { + const client = new texttospeechModule.v1.TextToSpeechClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.texttospeech.v1.SynthesizeSpeechRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.cloud.texttospeech.v1.SynthesizeSpeechResponse(), + ); + client.innerApiCalls.synthesizeSpeech = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.synthesizeSpeech( + request, + ( + err?: Error | null, + result?: protos.google.cloud.texttospeech.v1.ISynthesizeSpeechResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); + + it('invokes synthesizeSpeech with error', async () => { + const client = new texttospeechModule.v1.TextToSpeechClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.texttospeech.v1.SynthesizeSpeechRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.synthesizeSpeech = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.synthesizeSpeech(request), expectedError); + }); + + it('invokes synthesizeSpeech with closed client', async () => { + const client = new texttospeechModule.v1.TextToSpeechClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.texttospeech.v1.SynthesizeSpeechRequest(), + ); + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.synthesizeSpeech(request), expectedError); }); + }); }); diff --git a/core/generator/gapic-generator-typescript/baselines/texttospeech/src/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/texttospeech/src/index.ts.baseline index c0ef6854fae4..239bdf84959d 100644 --- a/core/generator/gapic-generator-typescript/baselines/texttospeech/src/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/texttospeech/src/index.ts.baseline @@ -19,7 +19,7 @@ import * as v1 from './v1'; const TextToSpeechClient = v1.TextToSpeechClient; type TextToSpeechClient = v1.TextToSpeechClient; -export {v1, TextToSpeechClient}; -export default {v1, TextToSpeechClient}; +export { v1, TextToSpeechClient }; +export default { v1, TextToSpeechClient }; import * as protos from '../protos/protos'; -export {protos} +export { protos }; diff --git a/core/generator/gapic-generator-typescript/baselines/texttospeech/src/v1/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/texttospeech/src/v1/index.ts.baseline index 2a0636a80ace..40ae52ebd836 100644 --- a/core/generator/gapic-generator-typescript/baselines/texttospeech/src/v1/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/texttospeech/src/v1/index.ts.baseline @@ -16,4 +16,4 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -export {TextToSpeechClient} from './text_to_speech_client'; +export { TextToSpeechClient } from './text_to_speech_client'; diff --git a/core/generator/gapic-generator-typescript/baselines/texttospeech/src/v1/text_to_speech_client.ts.baseline b/core/generator/gapic-generator-typescript/baselines/texttospeech/src/v1/text_to_speech_client.ts.baseline index f9c2e438f4f8..3a978f3e237e 100644 --- a/core/generator/gapic-generator-typescript/baselines/texttospeech/src/v1/text_to_speech_client.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/texttospeech/src/v1/text_to_speech_client.ts.baseline @@ -18,11 +18,16 @@ /* global window */ import type * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions} from 'google-gax'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, +} from 'google-gax'; import * as protos from '../../protos/protos'; import jsonProtos = require('../../protos/protos.json'); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; /** * Client JSON configuration object, loaded from @@ -44,7 +49,7 @@ export class TextToSpeechClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('text-to-speech'); @@ -57,8 +62,8 @@ export class TextToSpeechClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - textToSpeechStub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + textToSpeechStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of TextToSpeechClient. @@ -99,21 +104,42 @@ export class TextToSpeechClient { * const client = new TextToSpeechClient({fallback: true}, gax); * ``` */ - constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { // Ensure that options include all the required fields. const staticMembers = this.constructor as typeof TextToSpeechClient; - if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { - throw new Error('Please set either universe_domain or universeDomain, but not both.'); + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); } - const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; - this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; this._servicePath = 'texttospeech.' + this._universeDomain; - const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; - const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. if (servicePath !== this._servicePath && !('scopes' in opts)) { @@ -135,7 +161,7 @@ export class TextToSpeechClient { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; @@ -149,10 +175,7 @@ export class TextToSpeechClient { } // Determine the client header string. - const clientHeader = [ - `gax/${this._gaxModule.version}`, - `gapic/${version}`, - ]; + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/${process.versions.node}`); } else { @@ -171,8 +194,11 @@ export class TextToSpeechClient { // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.cloud.texttospeech.v1.TextToSpeech', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.cloud.texttospeech.v1.TextToSpeech', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + { 'x-goog-api-client': clientHeader.join(' ') }, + ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -203,36 +229,40 @@ export class TextToSpeechClient { // Put together the "service stub" for // google.cloud.texttospeech.v1.TextToSpeech. this.textToSpeechStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.cloud.texttospeech.v1.TextToSpeech') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.cloud.texttospeech.v1.TextToSpeech', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.cloud.texttospeech.v1.TextToSpeech, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts, + this._providedCustomServicePath, + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const textToSpeechStubMethods = - ['listVoices', 'synthesizeSpeech']; + const textToSpeechStubMethods = ['listVoices', 'synthesizeSpeech']; for (const methodName of textToSpeechStubMethods) { const callPromise = this.textToSpeechStub.then( - stub => (...args: Array<{}>) => { - if (this._terminated) { - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error|null|undefined) => () => { + (stub) => + (...args: Array<{}>) => { + if (this._terminated) { + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { throw err; - }); + }, + ); - const descriptor = - undefined; + const descriptor = undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -247,8 +277,14 @@ export class TextToSpeechClient { * @returns {string} The DNS address for this service. */ static get servicePath() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'texttospeech.googleapis.com'; } @@ -259,8 +295,14 @@ export class TextToSpeechClient { * @returns {string} The DNS address for this service. */ static get apiEndpoint() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'texttospeech.googleapis.com'; } @@ -291,9 +333,7 @@ export class TextToSpeechClient { * @returns {string[]} List of default scopes. */ static get scopes() { - return [ - 'https://www.googleapis.com/auth/cloud-platform' - ]; + return ['https://www.googleapis.com/auth/cloud-platform']; } getProjectId(): Promise; @@ -302,8 +342,9 @@ export class TextToSpeechClient { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId(callback?: Callback): - Promise|void { + getProjectId( + callback?: Callback, + ): Promise | void { if (callback) { this.auth.getProjectId(callback); return; @@ -314,198 +355,276 @@ export class TextToSpeechClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Returns a list of Voice supported for synthesis. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} [request.languageCode] - * Optional. Recommended. - * [BCP-47](https://www.rfc-editor.org/rfc/bcp/bcp47.txt) language tag. If - * specified, the ListVoices call will only return voices that can be used to - * synthesize this language_code. E.g. when specifying "en-NZ", you will get - * supported "en-*" voices; when specifying "no", you will get supported - * "no-*" (Norwegian) and "nb-*" (Norwegian Bokmal) voices; specifying "zh" - * will also get supported "cmn-*" voices; specifying "zh-hk" will also get - * supported "yue-*" voices. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.texttospeech.v1.ListVoicesResponse|ListVoicesResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1/text_to_speech.list_voices.js - * region_tag:texttospeech_v1_generated_TextToSpeech_ListVoices_async - */ + /** + * Returns a list of Voice supported for synthesis. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} [request.languageCode] + * Optional. Recommended. + * [BCP-47](https://www.rfc-editor.org/rfc/bcp/bcp47.txt) language tag. If + * specified, the ListVoices call will only return voices that can be used to + * synthesize this language_code. E.g. when specifying "en-NZ", you will get + * supported "en-*" voices; when specifying "no", you will get supported + * "no-*" (Norwegian) and "nb-*" (Norwegian Bokmal) voices; specifying "zh" + * will also get supported "cmn-*" voices; specifying "zh-hk" will also get + * supported "yue-*" voices. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.texttospeech.v1.ListVoicesResponse|ListVoicesResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/text_to_speech.list_voices.js + * region_tag:texttospeech_v1_generated_TextToSpeech_ListVoices_async + */ listVoices( - request?: protos.google.cloud.texttospeech.v1.IListVoicesRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.texttospeech.v1.IListVoicesResponse, - protos.google.cloud.texttospeech.v1.IListVoicesRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.texttospeech.v1.IListVoicesRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.texttospeech.v1.IListVoicesResponse, + protos.google.cloud.texttospeech.v1.IListVoicesRequest | undefined, + {} | undefined, + ] + >; listVoices( - request: protos.google.cloud.texttospeech.v1.IListVoicesRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.texttospeech.v1.IListVoicesResponse, - protos.google.cloud.texttospeech.v1.IListVoicesRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.texttospeech.v1.IListVoicesRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.texttospeech.v1.IListVoicesResponse, + protos.google.cloud.texttospeech.v1.IListVoicesRequest | null | undefined, + {} | null | undefined + >, + ): void; listVoices( - request: protos.google.cloud.texttospeech.v1.IListVoicesRequest, - callback: Callback< - protos.google.cloud.texttospeech.v1.IListVoicesResponse, - protos.google.cloud.texttospeech.v1.IListVoicesRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.texttospeech.v1.IListVoicesRequest, + callback: Callback< + protos.google.cloud.texttospeech.v1.IListVoicesResponse, + protos.google.cloud.texttospeech.v1.IListVoicesRequest | null | undefined, + {} | null | undefined + >, + ): void; listVoices( - request?: protos.google.cloud.texttospeech.v1.IListVoicesRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.texttospeech.v1.IListVoicesResponse, - protos.google.cloud.texttospeech.v1.IListVoicesRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.texttospeech.v1.IListVoicesRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.texttospeech.v1.IListVoicesResponse, - protos.google.cloud.texttospeech.v1.IListVoicesRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.texttospeech.v1.IListVoicesResponse, - protos.google.cloud.texttospeech.v1.IListVoicesRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.texttospeech.v1.IListVoicesRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.texttospeech.v1.IListVoicesResponse, + protos.google.cloud.texttospeech.v1.IListVoicesRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.texttospeech.v1.IListVoicesResponse, + protos.google.cloud.texttospeech.v1.IListVoicesRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listVoices request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.texttospeech.v1.IListVoicesResponse, - protos.google.cloud.texttospeech.v1.IListVoicesRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.texttospeech.v1.IListVoicesResponse, + | protos.google.cloud.texttospeech.v1.IListVoicesRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('listVoices response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.listVoices(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.texttospeech.v1.IListVoicesResponse, - protos.google.cloud.texttospeech.v1.IListVoicesRequest|undefined, - {}|undefined - ]) => { - this._log.info('listVoices response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .listVoices(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.texttospeech.v1.IListVoicesResponse, + protos.google.cloud.texttospeech.v1.IListVoicesRequest | undefined, + {} | undefined, + ]) => { + this._log.info('listVoices response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Synthesizes speech synchronously: receive results after all text input - * has been processed. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.cloud.texttospeech.v1.SynthesisInput} request.input - * Required. The Synthesizer requires either plain text or SSML as input. - * @param {google.cloud.texttospeech.v1.VoiceSelectionParams} request.voice - * Required. The desired voice of the synthesized audio. - * @param {google.cloud.texttospeech.v1.AudioConfig} request.audioConfig - * Required. The configuration of the synthesized audio. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.texttospeech.v1.SynthesizeSpeechResponse|SynthesizeSpeechResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v1/text_to_speech.synthesize_speech.js - * region_tag:texttospeech_v1_generated_TextToSpeech_SynthesizeSpeech_async - */ + /** + * Synthesizes speech synchronously: receive results after all text input + * has been processed. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.cloud.texttospeech.v1.SynthesisInput} request.input + * Required. The Synthesizer requires either plain text or SSML as input. + * @param {google.cloud.texttospeech.v1.VoiceSelectionParams} request.voice + * Required. The desired voice of the synthesized audio. + * @param {google.cloud.texttospeech.v1.AudioConfig} request.audioConfig + * Required. The configuration of the synthesized audio. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.texttospeech.v1.SynthesizeSpeechResponse|SynthesizeSpeechResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/text_to_speech.synthesize_speech.js + * region_tag:texttospeech_v1_generated_TextToSpeech_SynthesizeSpeech_async + */ synthesizeSpeech( - request?: protos.google.cloud.texttospeech.v1.ISynthesizeSpeechRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.texttospeech.v1.ISynthesizeSpeechResponse, - protos.google.cloud.texttospeech.v1.ISynthesizeSpeechRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.texttospeech.v1.ISynthesizeSpeechRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.texttospeech.v1.ISynthesizeSpeechResponse, + protos.google.cloud.texttospeech.v1.ISynthesizeSpeechRequest | undefined, + {} | undefined, + ] + >; synthesizeSpeech( - request: protos.google.cloud.texttospeech.v1.ISynthesizeSpeechRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.texttospeech.v1.ISynthesizeSpeechResponse, - protos.google.cloud.texttospeech.v1.ISynthesizeSpeechRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.texttospeech.v1.ISynthesizeSpeechRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.texttospeech.v1.ISynthesizeSpeechResponse, + | protos.google.cloud.texttospeech.v1.ISynthesizeSpeechRequest + | null + | undefined, + {} | null | undefined + >, + ): void; synthesizeSpeech( - request: protos.google.cloud.texttospeech.v1.ISynthesizeSpeechRequest, - callback: Callback< - protos.google.cloud.texttospeech.v1.ISynthesizeSpeechResponse, - protos.google.cloud.texttospeech.v1.ISynthesizeSpeechRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.texttospeech.v1.ISynthesizeSpeechRequest, + callback: Callback< + protos.google.cloud.texttospeech.v1.ISynthesizeSpeechResponse, + | protos.google.cloud.texttospeech.v1.ISynthesizeSpeechRequest + | null + | undefined, + {} | null | undefined + >, + ): void; synthesizeSpeech( - request?: protos.google.cloud.texttospeech.v1.ISynthesizeSpeechRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.cloud.texttospeech.v1.ISynthesizeSpeechRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.texttospeech.v1.ISynthesizeSpeechResponse, - protos.google.cloud.texttospeech.v1.ISynthesizeSpeechRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.cloud.texttospeech.v1.ISynthesizeSpeechResponse, - protos.google.cloud.texttospeech.v1.ISynthesizeSpeechRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.texttospeech.v1.ISynthesizeSpeechResponse, - protos.google.cloud.texttospeech.v1.ISynthesizeSpeechRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.texttospeech.v1.ISynthesizeSpeechRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.texttospeech.v1.ISynthesizeSpeechResponse, + | protos.google.cloud.texttospeech.v1.ISynthesizeSpeechRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.texttospeech.v1.ISynthesizeSpeechResponse, + protos.google.cloud.texttospeech.v1.ISynthesizeSpeechRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('synthesizeSpeech request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.texttospeech.v1.ISynthesizeSpeechResponse, - protos.google.cloud.texttospeech.v1.ISynthesizeSpeechRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.texttospeech.v1.ISynthesizeSpeechResponse, + | protos.google.cloud.texttospeech.v1.ISynthesizeSpeechRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('synthesizeSpeech response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.synthesizeSpeech(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.texttospeech.v1.ISynthesizeSpeechResponse, - protos.google.cloud.texttospeech.v1.ISynthesizeSpeechRequest|undefined, - {}|undefined - ]) => { - this._log.info('synthesizeSpeech response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .synthesizeSpeech(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.texttospeech.v1.ISynthesizeSpeechResponse, + ( + | protos.google.cloud.texttospeech.v1.ISynthesizeSpeechRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('synthesizeSpeech response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } - /** * Terminate the gRPC channel and close the client. * @@ -514,7 +633,7 @@ export class TextToSpeechClient { */ close(): Promise { if (this.textToSpeechStub && !this._terminated) { - return this.textToSpeechStub.then(stub => { + return this.textToSpeechStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -522,4 +641,4 @@ export class TextToSpeechClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/core/generator/gapic-generator-typescript/baselines/texttospeech/system-test/fixtures/sample/src/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/texttospeech/system-test/fixtures/sample/src/index.ts.baseline index 71b0bcb6738b..38ce98cdd06c 100644 --- a/core/generator/gapic-generator-typescript/baselines/texttospeech/system-test/fixtures/sample/src/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/texttospeech/system-test/fixtures/sample/src/index.ts.baseline @@ -16,7 +16,7 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -import {TextToSpeechClient} from '@google-cloud/text-to-speech'; +import { TextToSpeechClient } from '@google-cloud/text-to-speech'; // check that the client class type name can be used function doStuffWithTextToSpeechClient(client: TextToSpeechClient) { diff --git a/core/generator/gapic-generator-typescript/baselines/texttospeech/system-test/install.ts.baseline b/core/generator/gapic-generator-typescript/baselines/texttospeech/system-test/install.ts.baseline index f66069aa3940..ccf167042d2e 100644 --- a/core/generator/gapic-generator-typescript/baselines/texttospeech/system-test/install.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/texttospeech/system-test/install.ts.baseline @@ -16,34 +16,36 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -import {packNTest} from 'pack-n-play'; -import {readFileSync} from 'fs'; -import {describe, it} from 'mocha'; +import { packNTest } from 'pack-n-play'; +import { readFileSync } from 'fs'; +import { describe, it } from 'mocha'; describe('📦 pack-n-play test', () => { - - it('TypeScript code', async function() { + it('TypeScript code', async function () { this.timeout(300000); const options = { packageDir: process.cwd(), sample: { description: 'TypeScript user can use the type definitions', - ts: readFileSync('./system-test/fixtures/sample/src/index.ts').toString() - } + ts: readFileSync( + './system-test/fixtures/sample/src/index.ts', + ).toString(), + }, }; await packNTest(options); }); - it('JavaScript code', async function() { + it('JavaScript code', async function () { this.timeout(300000); const options = { packageDir: process.cwd(), sample: { description: 'JavaScript user can use the library', - cjs: readFileSync('./system-test/fixtures/sample/src/index.js').toString() - } + cjs: readFileSync( + './system-test/fixtures/sample/src/index.js', + ).toString(), + }, }; await packNTest(options); }); - }); diff --git a/core/generator/gapic-generator-typescript/baselines/texttospeech/test/gapic_text_to_speech_v1.ts.baseline b/core/generator/gapic-generator-typescript/baselines/texttospeech/test/gapic_text_to_speech_v1.ts.baseline index e9a7f7455ce7..dabb9d75ccbb 100644 --- a/core/generator/gapic-generator-typescript/baselines/texttospeech/test/gapic_text_to_speech_v1.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/texttospeech/test/gapic_text_to_speech_v1.ts.baseline @@ -19,346 +19,411 @@ import * as protos from '../protos/protos'; import * as assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as texttospeechModule from '../src'; -import {protobuf} from 'google-gax'; +import { protobuf } from 'google-gax'; // Dynamically loaded proto JSON is needed to get the type information // to fill in default values for request objects -const root = protobuf.Root.fromJSON(require('../protos/protos.json')).resolveAll(); +const root = protobuf.Root.fromJSON( + require('../protos/protos.json'), +).resolveAll(); // eslint-disable-next-line @typescript-eslint/no-unused-vars function getTypeDefaultValue(typeName: string, fields: string[]) { - let type = root.lookupType(typeName) as protobuf.Type; - for (const field of fields.slice(0, -1)) { - type = type.fields[field]?.resolvedType as protobuf.Type; - } - return type.fields[fields[fields.length - 1]]?.defaultValue; + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type.fields[field]?.resolvedType as protobuf.Type; + } + return type.fields[fields[fields.length - 1]]?.defaultValue; } function generateSampleMessage(instance: T) { - const filledObject = (instance.constructor as typeof protobuf.Message) - .toObject(instance as protobuf.Message, {defaults: true}); - return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, { defaults: true }); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; } function stubSimpleCall(response?: ResponseType, error?: Error) { - return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); } -function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { - return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +function stubSimpleCallWithCallback( + response?: ResponseType, + error?: Error, +) { + return error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); } describe('v1.TextToSpeechClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new texttospeechModule.v1.TextToSpeechClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'texttospeech.googleapis.com'); - }); - - it('has universeDomain', () => { - const client = new texttospeechModule.v1.TextToSpeechClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new texttospeechModule.v1.TextToSpeechClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'texttospeech.googleapis.com'); + }); - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - it('throws DeprecationWarning if static servicePath is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const servicePath = texttospeechModule.v1.TextToSpeechClient.servicePath; - assert.strictEqual(servicePath, 'texttospeech.googleapis.com'); - assert(stub.called); - stub.restore(); - }); + it('has universeDomain', () => { + const client = new texttospeechModule.v1.TextToSpeechClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = texttospeechModule.v1.TextToSpeechClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'texttospeech.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new texttospeechModule.v1.TextToSpeechClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'texttospeech.example.com'); - }); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = + texttospeechModule.v1.TextToSpeechClient.servicePath; + assert.strictEqual(servicePath, 'texttospeech.googleapis.com'); + assert(stub.called); + stub.restore(); + }); - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new texttospeechModule.v1.TextToSpeechClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'texttospeech.example.com'); - }); + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + texttospeechModule.v1.TextToSpeechClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'texttospeech.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = new texttospeechModule.v1.TextToSpeechClient({ + universeDomain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'texttospeech.example.com'); + }); - if (typeof process === 'object' && 'env' in process) { - describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { - it('sets apiEndpoint from environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new texttospeechModule.v1.TextToSpeechClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'texttospeech.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = new texttospeechModule.v1.TextToSpeechClient({ + universe_domain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'texttospeech.example.com'); + }); - it('value configured in code has priority over environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new texttospeechModule.v1.TextToSpeechClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'texttospeech.configured.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { new texttospeechModule.v1.TextToSpeechClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); + if (typeof process === 'object' && 'env' in process) { + describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { + it('sets apiEndpoint from environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new texttospeechModule.v1.TextToSpeechClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'texttospeech.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - it('has port', () => { - const port = texttospeechModule.v1.TextToSpeechClient.port; - assert(port); - assert(typeof port === 'number'); + it('value configured in code has priority over environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new texttospeechModule.v1.TextToSpeechClient({ + universeDomain: 'configured.example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual( + servicePath, + 'texttospeech.configured.example.com', + ); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - - it('should create a client with no option', () => { - const client = new texttospeechModule.v1.TextToSpeechClient(); - assert(client); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new texttospeechModule.v1.TextToSpeechClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); + }); - it('should create a client with gRPC fallback', () => { - const client = new texttospeechModule.v1.TextToSpeechClient({ - fallback: true, - }); - assert(client); - }); + it('has port', () => { + const port = texttospeechModule.v1.TextToSpeechClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('has initialize method and supports deferred initialization', async () => { - const client = new texttospeechModule.v1.TextToSpeechClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.textToSpeechStub, undefined); - await client.initialize(); - assert(client.textToSpeechStub); - }); + it('should create a client with no option', () => { + const client = new texttospeechModule.v1.TextToSpeechClient(); + assert(client); + }); - it('has close method for the initialized client', done => { - const client = new texttospeechModule.v1.TextToSpeechClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.textToSpeechStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('should create a client with gRPC fallback', () => { + const client = new texttospeechModule.v1.TextToSpeechClient({ + fallback: true, + }); + assert(client); + }); - it('has close method for the non-initialized client', done => { - const client = new texttospeechModule.v1.TextToSpeechClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.textToSpeechStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('has initialize method and supports deferred initialization', async () => { + const client = new texttospeechModule.v1.TextToSpeechClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.textToSpeechStub, undefined); + await client.initialize(); + assert(client.textToSpeechStub); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new texttospeechModule.v1.TextToSpeechClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + it('has close method for the initialized client', (done) => { + const client = new texttospeechModule.v1.TextToSpeechClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.textToSpeechStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new texttospeechModule.v1.TextToSpeechClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId((err?: Error|null, projectId?: string|null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } - }); - }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); + it('has close method for the non-initialized client', (done) => { + const client = new texttospeechModule.v1.TextToSpeechClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.textToSpeechStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); }); - describe('listVoices', () => { - it('invokes listVoices without error', async () => { - const client = new texttospeechModule.v1.TextToSpeechClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.texttospeech.v1.ListVoicesRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.cloud.texttospeech.v1.ListVoicesResponse() - ); - client.innerApiCalls.listVoices = stubSimpleCall(expectedResponse); - const [response] = await client.listVoices(request); - assert.deepStrictEqual(response, expectedResponse); - }); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new texttospeechModule.v1.TextToSpeechClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + }); - it('invokes listVoices without error using callback', async () => { - const client = new texttospeechModule.v1.TextToSpeechClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.texttospeech.v1.ListVoicesRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.cloud.texttospeech.v1.ListVoicesResponse() - ); - client.innerApiCalls.listVoices = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listVoices( - request, - (err?: Error|null, result?: protos.google.cloud.texttospeech.v1.IListVoicesResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new texttospeechModule.v1.TextToSpeechClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + }); - it('invokes listVoices with error', async () => { - const client = new texttospeechModule.v1.TextToSpeechClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.texttospeech.v1.ListVoicesRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.listVoices = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listVoices(request), expectedError); - }); + describe('listVoices', () => { + it('invokes listVoices without error', async () => { + const client = new texttospeechModule.v1.TextToSpeechClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.texttospeech.v1.ListVoicesRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.cloud.texttospeech.v1.ListVoicesResponse(), + ); + client.innerApiCalls.listVoices = stubSimpleCall(expectedResponse); + const [response] = await client.listVoices(request); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes listVoices with closed client', async () => { - const client = new texttospeechModule.v1.TextToSpeechClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.texttospeech.v1.ListVoicesRequest() - ); - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.listVoices(request), expectedError); - }); + it('invokes listVoices without error using callback', async () => { + const client = new texttospeechModule.v1.TextToSpeechClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.texttospeech.v1.ListVoicesRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.cloud.texttospeech.v1.ListVoicesResponse(), + ); + client.innerApiCalls.listVoices = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listVoices( + request, + ( + err?: Error | null, + result?: protos.google.cloud.texttospeech.v1.IListVoicesResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); }); - describe('synthesizeSpeech', () => { - it('invokes synthesizeSpeech without error', async () => { - const client = new texttospeechModule.v1.TextToSpeechClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.texttospeech.v1.SynthesizeSpeechRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.cloud.texttospeech.v1.SynthesizeSpeechResponse() - ); - client.innerApiCalls.synthesizeSpeech = stubSimpleCall(expectedResponse); - const [response] = await client.synthesizeSpeech(request); - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes listVoices with error', async () => { + const client = new texttospeechModule.v1.TextToSpeechClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.texttospeech.v1.ListVoicesRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.listVoices = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listVoices(request), expectedError); + }); - it('invokes synthesizeSpeech without error using callback', async () => { - const client = new texttospeechModule.v1.TextToSpeechClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.texttospeech.v1.SynthesizeSpeechRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.cloud.texttospeech.v1.SynthesizeSpeechResponse() - ); - client.innerApiCalls.synthesizeSpeech = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.synthesizeSpeech( - request, - (err?: Error|null, result?: protos.google.cloud.texttospeech.v1.ISynthesizeSpeechResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes listVoices with closed client', async () => { + const client = new texttospeechModule.v1.TextToSpeechClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.texttospeech.v1.ListVoicesRequest(), + ); + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.listVoices(request), expectedError); + }); + }); - it('invokes synthesizeSpeech with error', async () => { - const client = new texttospeechModule.v1.TextToSpeechClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.texttospeech.v1.SynthesizeSpeechRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.synthesizeSpeech = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.synthesizeSpeech(request), expectedError); - }); + describe('synthesizeSpeech', () => { + it('invokes synthesizeSpeech without error', async () => { + const client = new texttospeechModule.v1.TextToSpeechClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.texttospeech.v1.SynthesizeSpeechRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.cloud.texttospeech.v1.SynthesizeSpeechResponse(), + ); + client.innerApiCalls.synthesizeSpeech = stubSimpleCall(expectedResponse); + const [response] = await client.synthesizeSpeech(request); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes synthesizeSpeech with closed client', async () => { - const client = new texttospeechModule.v1.TextToSpeechClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.texttospeech.v1.SynthesizeSpeechRequest() - ); - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.synthesizeSpeech(request), expectedError); - }); + it('invokes synthesizeSpeech without error using callback', async () => { + const client = new texttospeechModule.v1.TextToSpeechClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.texttospeech.v1.SynthesizeSpeechRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.cloud.texttospeech.v1.SynthesizeSpeechResponse(), + ); + client.innerApiCalls.synthesizeSpeech = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.synthesizeSpeech( + request, + ( + err?: Error | null, + result?: protos.google.cloud.texttospeech.v1.ISynthesizeSpeechResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); + + it('invokes synthesizeSpeech with error', async () => { + const client = new texttospeechModule.v1.TextToSpeechClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.texttospeech.v1.SynthesizeSpeechRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.synthesizeSpeech = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.synthesizeSpeech(request), expectedError); + }); + + it('invokes synthesizeSpeech with closed client', async () => { + const client = new texttospeechModule.v1.TextToSpeechClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.texttospeech.v1.SynthesizeSpeechRequest(), + ); + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.synthesizeSpeech(request), expectedError); }); + }); }); diff --git a/core/generator/gapic-generator-typescript/baselines/translate-esm/esm/src/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/translate-esm/esm/src/index.ts.baseline index 77370f456aea..4e9dc53525f8 100644 --- a/core/generator/gapic-generator-typescript/baselines/translate-esm/esm/src/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/translate-esm/esm/src/index.ts.baseline @@ -19,8 +19,8 @@ import * as v3beta1 from './v3beta1/index.js'; const TranslationServiceClient = v3beta1.TranslationServiceClient; type TranslationServiceClient = v3beta1.TranslationServiceClient; -export {v3beta1, TranslationServiceClient}; -export default {v3beta1, TranslationServiceClient}; +export { v3beta1, TranslationServiceClient }; +export default { v3beta1, TranslationServiceClient }; // @ts-ignore import * as protos from '../../protos/protos.js'; -export {protos} +export { protos }; diff --git a/core/generator/gapic-generator-typescript/baselines/translate-esm/esm/src/v3beta1/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/translate-esm/esm/src/v3beta1/index.ts.baseline index 9c6ee9adfc70..896bc5016e22 100644 --- a/core/generator/gapic-generator-typescript/baselines/translate-esm/esm/src/v3beta1/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/translate-esm/esm/src/v3beta1/index.ts.baseline @@ -16,4 +16,4 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -export {TranslationServiceClient} from './translation_service_client.js'; +export { TranslationServiceClient } from './translation_service_client.js'; diff --git a/core/generator/gapic-generator-typescript/baselines/translate-esm/esm/src/v3beta1/translation_service_client.ts.baseline b/core/generator/gapic-generator-typescript/baselines/translate-esm/esm/src/v3beta1/translation_service_client.ts.baseline index 4227393e72a9..44ac2807a429 100644 --- a/core/generator/gapic-generator-typescript/baselines/translate-esm/esm/src/v3beta1/translation_service_client.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/translate-esm/esm/src/v3beta1/translation_service_client.ts.baseline @@ -18,15 +18,24 @@ /* global window */ import * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions, GrpcClientOptions, LROperation, PaginationCallback, GaxCall} from 'google-gax'; -import {Transform} from 'stream'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + GrpcClientOptions, + LROperation, + PaginationCallback, + GaxCall, +} from 'google-gax'; +import { Transform } from 'stream'; // @ts-ignore import type * as protos from '../../../protos/protos.js'; import * as translation_service_client_config from './translation_service_client_config.json'; import fs from 'fs'; import path from 'path'; -import {fileURLToPath} from 'url'; -import {getJSON} from '../json-helper.cjs'; +import { fileURLToPath } from 'url'; +import { getJSON } from '../json-helper.cjs'; // @ts-ignore const dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -36,15 +45,15 @@ const dirname = path.dirname(fileURLToPath(import.meta.url)); * This file defines retry strategy and timeouts for all API methods in this library. */ const gapicConfig = getJSON( - path.join(dirname, 'translation_service_client_config.json') + path.join(dirname, 'translation_service_client_config.json'), ); const jsonProtos = getJSON( - path.join(dirname, '..', '..', '..', 'protos/protos.json') + path.join(dirname, '..', '..', '..', 'protos/protos.json'), ); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; const version = getJSON( - path.join(dirname, '..', '..', '..', '..', 'package.json') + path.join(dirname, '..', '..', '..', '..', 'package.json'), ).version; /** @@ -59,7 +68,7 @@ export class TranslationServiceClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('translation'); @@ -71,10 +80,10 @@ export class TranslationServiceClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; operationsClient: gax.OperationsClient; - translationServiceStub?: Promise<{[name: string]: Function}>; + translationServiceStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of TranslationServiceClient. @@ -116,21 +125,42 @@ export class TranslationServiceClient { * const client = new TranslationServiceClient({fallback: 'rest'}, gax); * ``` */ - constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { // Ensure that options include all the required fields. const staticMembers = this.constructor as typeof TranslationServiceClient; - if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { - throw new Error('Please set either universe_domain or universeDomain, but not both.'); + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); } - const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; - this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; this._servicePath = 'translate.' + this._universeDomain; - const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; - const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. if (servicePath !== this._servicePath && !('scopes' in opts)) { @@ -152,7 +182,7 @@ export class TranslationServiceClient { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; @@ -169,10 +199,7 @@ export class TranslationServiceClient { const isEsm = true; const isEsmString = isEsm ? '-esm' : '-cjs'; // Determine the client header string. - const clientHeader = [ - `gax/${this._gaxModule.version}`, - `gapic/${version}`, - ]; + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/{process.versions.node}${isEsmString}`); } else { @@ -180,7 +207,7 @@ export class TranslationServiceClient { } if (!opts.fallback) { clientHeader.push(`grpc/${this._gaxGrpc.grpcVersion}`); - } else if (opts.fallback === 'rest' ) { + } else if (opts.fallback === 'rest') { clientHeader.push(`rest/${this._gaxGrpc.grpcVersion}`); } if (opts.libName && opts.libVersion) { @@ -188,17 +215,19 @@ export class TranslationServiceClient { } // Load the applicable protos. - this._protos = this._gaxGrpc.loadProtoJSON(jsonProtos as gax.protobuf.INamespace); + this._protos = this._gaxGrpc.loadProtoJSON( + jsonProtos as gax.protobuf.INamespace, + ); // This API contains "path templates"; forward-slash-separated // identifiers to uniquely identify resources within the API. // Create useful helper objects for these. this.pathTemplates = { glossaryPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/glossaries/{glossary}' + 'projects/{project}/locations/{location}/glossaries/{glossary}', ), locationPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}' + 'projects/{project}/locations/{location}', ), }; @@ -206,8 +235,11 @@ export class TranslationServiceClient { // (e.g. 50 results at a time, with tokens to get subsequent // pages). Denote the keys used for pagination and results. this.descriptors.page = { - listGlossaries: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'glossaries') + listGlossaries: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'glossaries', + ), }; const protoFilesRoot = this._gaxModule.protobufFromJSON(jsonProtos); @@ -216,45 +248,59 @@ export class TranslationServiceClient { // rather than holding a request open. const lroOptions: GrpcClientOptions = { auth: this.auth, - grpc: 'grpc' in this._gaxGrpc ? this._gaxGrpc.grpc : undefined + grpc: 'grpc' in this._gaxGrpc ? this._gaxGrpc.grpc : undefined, }; if (opts.fallback === 'rest') { lroOptions.protoJson = protoFilesRoot; lroOptions.httpRules = []; } - this.operationsClient = this._gaxModule.lro(lroOptions).operationsClient(opts); + this.operationsClient = this._gaxModule + .lro(lroOptions) + .operationsClient(opts); const batchTranslateTextResponse = protoFilesRoot.lookup( - '.google.cloud.translation.v3beta1.BatchTranslateResponse') as gax.protobuf.Type; + '.google.cloud.translation.v3beta1.BatchTranslateResponse', + ) as gax.protobuf.Type; const batchTranslateTextMetadata = protoFilesRoot.lookup( - '.google.cloud.translation.v3beta1.BatchTranslateMetadata') as gax.protobuf.Type; + '.google.cloud.translation.v3beta1.BatchTranslateMetadata', + ) as gax.protobuf.Type; const createGlossaryResponse = protoFilesRoot.lookup( - '.google.cloud.translation.v3beta1.Glossary') as gax.protobuf.Type; + '.google.cloud.translation.v3beta1.Glossary', + ) as gax.protobuf.Type; const createGlossaryMetadata = protoFilesRoot.lookup( - '.google.cloud.translation.v3beta1.CreateGlossaryMetadata') as gax.protobuf.Type; + '.google.cloud.translation.v3beta1.CreateGlossaryMetadata', + ) as gax.protobuf.Type; const deleteGlossaryResponse = protoFilesRoot.lookup( - '.google.cloud.translation.v3beta1.DeleteGlossaryResponse') as gax.protobuf.Type; + '.google.cloud.translation.v3beta1.DeleteGlossaryResponse', + ) as gax.protobuf.Type; const deleteGlossaryMetadata = protoFilesRoot.lookup( - '.google.cloud.translation.v3beta1.DeleteGlossaryMetadata') as gax.protobuf.Type; + '.google.cloud.translation.v3beta1.DeleteGlossaryMetadata', + ) as gax.protobuf.Type; this.descriptors.longrunning = { batchTranslateText: new this._gaxModule.LongrunningDescriptor( this.operationsClient, batchTranslateTextResponse.decode.bind(batchTranslateTextResponse), - batchTranslateTextMetadata.decode.bind(batchTranslateTextMetadata)), + batchTranslateTextMetadata.decode.bind(batchTranslateTextMetadata), + ), createGlossary: new this._gaxModule.LongrunningDescriptor( this.operationsClient, createGlossaryResponse.decode.bind(createGlossaryResponse), - createGlossaryMetadata.decode.bind(createGlossaryMetadata)), + createGlossaryMetadata.decode.bind(createGlossaryMetadata), + ), deleteGlossary: new this._gaxModule.LongrunningDescriptor( this.operationsClient, deleteGlossaryResponse.decode.bind(deleteGlossaryResponse), - deleteGlossaryMetadata.decode.bind(deleteGlossaryMetadata)) + deleteGlossaryMetadata.decode.bind(deleteGlossaryMetadata), + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.cloud.translation.v3beta1.TranslationService', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.cloud.translation.v3beta1.TranslationService', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + { 'x-goog-api-client': clientHeader.join(' ') }, + ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -285,28 +331,43 @@ export class TranslationServiceClient { // Put together the "service stub" for // google.cloud.translation.v3beta1.TranslationService. this.translationServiceStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.cloud.translation.v3beta1.TranslationService') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any - (this._protos as any).google.cloud.translation.v3beta1.TranslationService, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.cloud.translation.v3beta1.TranslationService', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any + (this._protos as any).google.cloud.translation.v3beta1 + .TranslationService, + this._opts, + this._providedCustomServicePath, + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const translationServiceStubMethods = - ['translateText', 'detectLanguage', 'getSupportedLanguages', 'batchTranslateText', 'createGlossary', 'listGlossaries', 'getGlossary', 'deleteGlossary']; + const translationServiceStubMethods = [ + 'translateText', + 'detectLanguage', + 'getSupportedLanguages', + 'batchTranslateText', + 'createGlossary', + 'listGlossaries', + 'getGlossary', + 'deleteGlossary', + ]; for (const methodName of translationServiceStubMethods) { const callPromise = this.translationServiceStub.then( - stub => (...args: Array<{}>) => { - if (this._terminated) { - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error|null|undefined) => () => { + (stub) => + (...args: Array<{}>) => { + if (this._terminated) { + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { throw err; - }); + }, + ); const descriptor = this.descriptors.page[methodName] || @@ -316,7 +377,7 @@ export class TranslationServiceClient { callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -331,8 +392,14 @@ export class TranslationServiceClient { * @returns {string} The DNS address for this service. */ static get servicePath() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'translate.googleapis.com'; } @@ -344,8 +411,14 @@ export class TranslationServiceClient { * @returns {string} The DNS address for this service. */ static get apiEndpoint() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'translate.googleapis.com'; } @@ -378,7 +451,7 @@ export class TranslationServiceClient { static get scopes() { return [ 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloud-translation' + 'https://www.googleapis.com/auth/cloud-translation', ]; } @@ -388,8 +461,9 @@ export class TranslationServiceClient { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId(callback?: Callback): - Promise|void { + getProjectId( + callback?: Callback, + ): Promise | void { if (callback) { this.auth.getProjectId(callback); return; @@ -400,977 +474,1376 @@ export class TranslationServiceClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Translates input text and returns translated text. - * - * @param {Object} request - * The request object that will be sent. - * @param {string[]} request.contents - * Required. The content of the input in string format. - * We recommend the total content be less than 30k codepoints. - * Use BatchTranslateText for larger text. - * @param {string} [request.mimeType] - * Optional. The format of the source text, for example, "text/html", - * "text/plain". If left blank, the MIME type defaults to "text/html". - * @param {string} [request.sourceLanguageCode] - * Optional. The BCP-47 language code of the input text if - * known, for example, "en-US" or "sr-Latn". Supported language codes are - * listed in Language Support. If the source language isn't specified, the API - * attempts to identify the source language automatically and returns the - * source language within the response. - * @param {string} request.targetLanguageCode - * Required. The BCP-47 language code to use for translation of the input - * text, set to one of the language codes listed in Language Support. - * @param {string} request.parent - * Required. Project or location to make a call. Must refer to a caller's - * project. - * - * Format: `projects/{project-id}` or - * `projects/{project-id}/locations/{location-id}`. - * - * For global calls, use `projects/{project-id}/locations/global` or - * `projects/{project-id}`. - * - * Non-global location is required for requests using AutoML models or - * custom glossaries. - * - * Models and glossaries must be within the same region (have same - * location-id), otherwise an INVALID_ARGUMENT (400) error is returned. - * @param {string} [request.model] - * Optional. The `model` type requested for this translation. - * - * The format depends on model type: - * - * - AutoML Translation models: - * `projects/{project-id}/locations/{location-id}/models/{model-id}` - * - * - General (built-in) models: - * `projects/{project-id}/locations/{location-id}/models/general/nmt`, - * `projects/{project-id}/locations/{location-id}/models/general/base` - * - * - * For global (non-regionalized) requests, use `location-id` `global`. - * For example, - * `projects/{project-id}/locations/global/models/general/nmt`. - * - * If missing, the system decides which google base model to use. - * @param {google.cloud.translation.v3beta1.TranslateTextGlossaryConfig} [request.glossaryConfig] - * Optional. Glossary to be applied. The glossary must be - * within the same region (have the same location-id) as the model, otherwise - * an INVALID_ARGUMENT (400) error is returned. - * @param {number[]} [request.labels] - * Optional. The labels with user-defined metadata for the request. - * - * Label keys and values can be no longer than 63 characters - * (Unicode codepoints), can only contain lowercase letters, numeric - * characters, underscores and dashes. International characters are allowed. - * Label values are optional. Label keys must start with a letter. - * - * See https://cloud.google.com/translate/docs/labels for more information. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.translation.v3beta1.TranslateTextResponse|TranslateTextResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v3beta1/translation_service.translate_text.js - * region_tag:translate_v3beta1_generated_TranslationService_TranslateText_async - */ + /** + * Translates input text and returns translated text. + * + * @param {Object} request + * The request object that will be sent. + * @param {string[]} request.contents + * Required. The content of the input in string format. + * We recommend the total content be less than 30k codepoints. + * Use BatchTranslateText for larger text. + * @param {string} [request.mimeType] + * Optional. The format of the source text, for example, "text/html", + * "text/plain". If left blank, the MIME type defaults to "text/html". + * @param {string} [request.sourceLanguageCode] + * Optional. The BCP-47 language code of the input text if + * known, for example, "en-US" or "sr-Latn". Supported language codes are + * listed in Language Support. If the source language isn't specified, the API + * attempts to identify the source language automatically and returns the + * source language within the response. + * @param {string} request.targetLanguageCode + * Required. The BCP-47 language code to use for translation of the input + * text, set to one of the language codes listed in Language Support. + * @param {string} request.parent + * Required. Project or location to make a call. Must refer to a caller's + * project. + * + * Format: `projects/{project-id}` or + * `projects/{project-id}/locations/{location-id}`. + * + * For global calls, use `projects/{project-id}/locations/global` or + * `projects/{project-id}`. + * + * Non-global location is required for requests using AutoML models or + * custom glossaries. + * + * Models and glossaries must be within the same region (have same + * location-id), otherwise an INVALID_ARGUMENT (400) error is returned. + * @param {string} [request.model] + * Optional. The `model` type requested for this translation. + * + * The format depends on model type: + * + * - AutoML Translation models: + * `projects/{project-id}/locations/{location-id}/models/{model-id}` + * + * - General (built-in) models: + * `projects/{project-id}/locations/{location-id}/models/general/nmt`, + * `projects/{project-id}/locations/{location-id}/models/general/base` + * + * + * For global (non-regionalized) requests, use `location-id` `global`. + * For example, + * `projects/{project-id}/locations/global/models/general/nmt`. + * + * If missing, the system decides which google base model to use. + * @param {google.cloud.translation.v3beta1.TranslateTextGlossaryConfig} [request.glossaryConfig] + * Optional. Glossary to be applied. The glossary must be + * within the same region (have the same location-id) as the model, otherwise + * an INVALID_ARGUMENT (400) error is returned. + * @param {number[]} [request.labels] + * Optional. The labels with user-defined metadata for the request. + * + * Label keys and values can be no longer than 63 characters + * (Unicode codepoints), can only contain lowercase letters, numeric + * characters, underscores and dashes. International characters are allowed. + * Label values are optional. Label keys must start with a letter. + * + * See https://cloud.google.com/translate/docs/labels for more information. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.translation.v3beta1.TranslateTextResponse|TranslateTextResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v3beta1/translation_service.translate_text.js + * region_tag:translate_v3beta1_generated_TranslationService_TranslateText_async + */ translateText( - request?: protos.google.cloud.translation.v3beta1.ITranslateTextRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.translation.v3beta1.ITranslateTextResponse, - protos.google.cloud.translation.v3beta1.ITranslateTextRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.translation.v3beta1.ITranslateTextRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.translation.v3beta1.ITranslateTextResponse, + protos.google.cloud.translation.v3beta1.ITranslateTextRequest | undefined, + {} | undefined, + ] + >; translateText( - request: protos.google.cloud.translation.v3beta1.ITranslateTextRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.translation.v3beta1.ITranslateTextResponse, - protos.google.cloud.translation.v3beta1.ITranslateTextRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.translation.v3beta1.ITranslateTextRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.translation.v3beta1.ITranslateTextResponse, + | protos.google.cloud.translation.v3beta1.ITranslateTextRequest + | null + | undefined, + {} | null | undefined + >, + ): void; translateText( - request: protos.google.cloud.translation.v3beta1.ITranslateTextRequest, - callback: Callback< - protos.google.cloud.translation.v3beta1.ITranslateTextResponse, - protos.google.cloud.translation.v3beta1.ITranslateTextRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.translation.v3beta1.ITranslateTextRequest, + callback: Callback< + protos.google.cloud.translation.v3beta1.ITranslateTextResponse, + | protos.google.cloud.translation.v3beta1.ITranslateTextRequest + | null + | undefined, + {} | null | undefined + >, + ): void; translateText( - request?: protos.google.cloud.translation.v3beta1.ITranslateTextRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.translation.v3beta1.ITranslateTextResponse, - protos.google.cloud.translation.v3beta1.ITranslateTextRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.translation.v3beta1.ITranslateTextRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.translation.v3beta1.ITranslateTextResponse, - protos.google.cloud.translation.v3beta1.ITranslateTextRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.translation.v3beta1.ITranslateTextResponse, - protos.google.cloud.translation.v3beta1.ITranslateTextRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.translation.v3beta1.ITranslateTextRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.translation.v3beta1.ITranslateTextResponse, + | protos.google.cloud.translation.v3beta1.ITranslateTextRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.translation.v3beta1.ITranslateTextResponse, + protos.google.cloud.translation.v3beta1.ITranslateTextRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('translateText request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.translation.v3beta1.ITranslateTextResponse, - protos.google.cloud.translation.v3beta1.ITranslateTextRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.translation.v3beta1.ITranslateTextResponse, + | protos.google.cloud.translation.v3beta1.ITranslateTextRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('translateText response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.translateText(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.translation.v3beta1.ITranslateTextResponse, - protos.google.cloud.translation.v3beta1.ITranslateTextRequest|undefined, {}|undefined - ]) => { - this._log.info('translateText response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .translateText(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.translation.v3beta1.ITranslateTextResponse, + ( + | protos.google.cloud.translation.v3beta1.ITranslateTextRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('translateText response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Detects the language of text within a request. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. Project or location to make a call. Must refer to a caller's - * project. - * - * Format: `projects/{project-id}/locations/{location-id}` or - * `projects/{project-id}`. - * - * For global calls, use `projects/{project-id}/locations/global` or - * `projects/{project-id}`. - * - * Only models within the same region (has same location-id) can be used. - * Otherwise an INVALID_ARGUMENT (400) error is returned. - * @param {string} [request.model] - * Optional. The language detection model to be used. - * - * Format: - * `projects/{project-id}/locations/{location-id}/models/language-detection/{model-id}` - * - * Only one language detection model is currently supported: - * `projects/{project-id}/locations/{location-id}/models/language-detection/default`. - * - * If not specified, the default model is used. - * @param {string} request.content - * The content of the input stored as a string. - * @param {string} [request.mimeType] - * Optional. The format of the source text, for example, "text/html", - * "text/plain". If left blank, the MIME type defaults to "text/html". - * @param {number[]} request.labels - * Optional. The labels with user-defined metadata for the request. - * - * Label keys and values can be no longer than 63 characters - * (Unicode codepoints), can only contain lowercase letters, numeric - * characters, underscores and dashes. International characters are allowed. - * Label values are optional. Label keys must start with a letter. - * - * See https://cloud.google.com/translate/docs/labels for more information. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.translation.v3beta1.DetectLanguageResponse|DetectLanguageResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v3beta1/translation_service.detect_language.js - * region_tag:translate_v3beta1_generated_TranslationService_DetectLanguage_async - */ + /** + * Detects the language of text within a request. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Project or location to make a call. Must refer to a caller's + * project. + * + * Format: `projects/{project-id}/locations/{location-id}` or + * `projects/{project-id}`. + * + * For global calls, use `projects/{project-id}/locations/global` or + * `projects/{project-id}`. + * + * Only models within the same region (has same location-id) can be used. + * Otherwise an INVALID_ARGUMENT (400) error is returned. + * @param {string} [request.model] + * Optional. The language detection model to be used. + * + * Format: + * `projects/{project-id}/locations/{location-id}/models/language-detection/{model-id}` + * + * Only one language detection model is currently supported: + * `projects/{project-id}/locations/{location-id}/models/language-detection/default`. + * + * If not specified, the default model is used. + * @param {string} request.content + * The content of the input stored as a string. + * @param {string} [request.mimeType] + * Optional. The format of the source text, for example, "text/html", + * "text/plain". If left blank, the MIME type defaults to "text/html". + * @param {number[]} request.labels + * Optional. The labels with user-defined metadata for the request. + * + * Label keys and values can be no longer than 63 characters + * (Unicode codepoints), can only contain lowercase letters, numeric + * characters, underscores and dashes. International characters are allowed. + * Label values are optional. Label keys must start with a letter. + * + * See https://cloud.google.com/translate/docs/labels for more information. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.translation.v3beta1.DetectLanguageResponse|DetectLanguageResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v3beta1/translation_service.detect_language.js + * region_tag:translate_v3beta1_generated_TranslationService_DetectLanguage_async + */ detectLanguage( - request?: protos.google.cloud.translation.v3beta1.IDetectLanguageRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.translation.v3beta1.IDetectLanguageResponse, - protos.google.cloud.translation.v3beta1.IDetectLanguageRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.translation.v3beta1.IDetectLanguageRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.translation.v3beta1.IDetectLanguageResponse, + ( + | protos.google.cloud.translation.v3beta1.IDetectLanguageRequest + | undefined + ), + {} | undefined, + ] + >; detectLanguage( - request: protos.google.cloud.translation.v3beta1.IDetectLanguageRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.translation.v3beta1.IDetectLanguageResponse, - protos.google.cloud.translation.v3beta1.IDetectLanguageRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.translation.v3beta1.IDetectLanguageRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.translation.v3beta1.IDetectLanguageResponse, + | protos.google.cloud.translation.v3beta1.IDetectLanguageRequest + | null + | undefined, + {} | null | undefined + >, + ): void; detectLanguage( - request: protos.google.cloud.translation.v3beta1.IDetectLanguageRequest, - callback: Callback< - protos.google.cloud.translation.v3beta1.IDetectLanguageResponse, - protos.google.cloud.translation.v3beta1.IDetectLanguageRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.translation.v3beta1.IDetectLanguageRequest, + callback: Callback< + protos.google.cloud.translation.v3beta1.IDetectLanguageResponse, + | protos.google.cloud.translation.v3beta1.IDetectLanguageRequest + | null + | undefined, + {} | null | undefined + >, + ): void; detectLanguage( - request?: protos.google.cloud.translation.v3beta1.IDetectLanguageRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.translation.v3beta1.IDetectLanguageResponse, - protos.google.cloud.translation.v3beta1.IDetectLanguageRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.translation.v3beta1.IDetectLanguageRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.translation.v3beta1.IDetectLanguageResponse, - protos.google.cloud.translation.v3beta1.IDetectLanguageRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.translation.v3beta1.IDetectLanguageResponse, - protos.google.cloud.translation.v3beta1.IDetectLanguageRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.translation.v3beta1.IDetectLanguageRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.translation.v3beta1.IDetectLanguageResponse, + | protos.google.cloud.translation.v3beta1.IDetectLanguageRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.translation.v3beta1.IDetectLanguageResponse, + ( + | protos.google.cloud.translation.v3beta1.IDetectLanguageRequest + | undefined + ), + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('detectLanguage request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.translation.v3beta1.IDetectLanguageResponse, - protos.google.cloud.translation.v3beta1.IDetectLanguageRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.translation.v3beta1.IDetectLanguageResponse, + | protos.google.cloud.translation.v3beta1.IDetectLanguageRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('detectLanguage response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.detectLanguage(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.translation.v3beta1.IDetectLanguageResponse, - protos.google.cloud.translation.v3beta1.IDetectLanguageRequest|undefined, {}|undefined - ]) => { - this._log.info('detectLanguage response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .detectLanguage(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.translation.v3beta1.IDetectLanguageResponse, + ( + | protos.google.cloud.translation.v3beta1.IDetectLanguageRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('detectLanguage response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Returns a list of supported languages for translation. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. Project or location to make a call. Must refer to a caller's - * project. - * - * Format: `projects/{project-id}` or - * `projects/{project-id}/locations/{location-id}`. - * - * For global calls, use `projects/{project-id}/locations/global` or - * `projects/{project-id}`. - * - * Non-global location is required for AutoML models. - * - * Only models within the same region (have same location-id) can be used, - * otherwise an INVALID_ARGUMENT (400) error is returned. - * @param {string} [request.displayLanguageCode] - * Optional. The language to use to return localized, human readable names - * of supported languages. If missing, then display names are not returned - * in a response. - * @param {string} [request.model] - * Optional. Get supported languages of this model. - * - * The format depends on model type: - * - * - AutoML Translation models: - * `projects/{project-id}/locations/{location-id}/models/{model-id}` - * - * - General (built-in) models: - * `projects/{project-id}/locations/{location-id}/models/general/nmt`, - * `projects/{project-id}/locations/{location-id}/models/general/base` - * - * - * Returns languages supported by the specified model. - * If missing, we get supported languages of Google general base (PBMT) model. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.translation.v3beta1.SupportedLanguages|SupportedLanguages}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v3beta1/translation_service.get_supported_languages.js - * region_tag:translate_v3beta1_generated_TranslationService_GetSupportedLanguages_async - */ + /** + * Returns a list of supported languages for translation. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Project or location to make a call. Must refer to a caller's + * project. + * + * Format: `projects/{project-id}` or + * `projects/{project-id}/locations/{location-id}`. + * + * For global calls, use `projects/{project-id}/locations/global` or + * `projects/{project-id}`. + * + * Non-global location is required for AutoML models. + * + * Only models within the same region (have same location-id) can be used, + * otherwise an INVALID_ARGUMENT (400) error is returned. + * @param {string} [request.displayLanguageCode] + * Optional. The language to use to return localized, human readable names + * of supported languages. If missing, then display names are not returned + * in a response. + * @param {string} [request.model] + * Optional. Get supported languages of this model. + * + * The format depends on model type: + * + * - AutoML Translation models: + * `projects/{project-id}/locations/{location-id}/models/{model-id}` + * + * - General (built-in) models: + * `projects/{project-id}/locations/{location-id}/models/general/nmt`, + * `projects/{project-id}/locations/{location-id}/models/general/base` + * + * + * Returns languages supported by the specified model. + * If missing, we get supported languages of Google general base (PBMT) model. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.translation.v3beta1.SupportedLanguages|SupportedLanguages}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v3beta1/translation_service.get_supported_languages.js + * region_tag:translate_v3beta1_generated_TranslationService_GetSupportedLanguages_async + */ getSupportedLanguages( - request?: protos.google.cloud.translation.v3beta1.IGetSupportedLanguagesRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.translation.v3beta1.ISupportedLanguages, - protos.google.cloud.translation.v3beta1.IGetSupportedLanguagesRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.translation.v3beta1.IGetSupportedLanguagesRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.translation.v3beta1.ISupportedLanguages, + ( + | protos.google.cloud.translation.v3beta1.IGetSupportedLanguagesRequest + | undefined + ), + {} | undefined, + ] + >; getSupportedLanguages( - request: protos.google.cloud.translation.v3beta1.IGetSupportedLanguagesRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.translation.v3beta1.ISupportedLanguages, - protos.google.cloud.translation.v3beta1.IGetSupportedLanguagesRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.translation.v3beta1.IGetSupportedLanguagesRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.translation.v3beta1.ISupportedLanguages, + | protos.google.cloud.translation.v3beta1.IGetSupportedLanguagesRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getSupportedLanguages( - request: protos.google.cloud.translation.v3beta1.IGetSupportedLanguagesRequest, - callback: Callback< - protos.google.cloud.translation.v3beta1.ISupportedLanguages, - protos.google.cloud.translation.v3beta1.IGetSupportedLanguagesRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.translation.v3beta1.IGetSupportedLanguagesRequest, + callback: Callback< + protos.google.cloud.translation.v3beta1.ISupportedLanguages, + | protos.google.cloud.translation.v3beta1.IGetSupportedLanguagesRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getSupportedLanguages( - request?: protos.google.cloud.translation.v3beta1.IGetSupportedLanguagesRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.cloud.translation.v3beta1.IGetSupportedLanguagesRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.translation.v3beta1.ISupportedLanguages, - protos.google.cloud.translation.v3beta1.IGetSupportedLanguagesRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.cloud.translation.v3beta1.ISupportedLanguages, - protos.google.cloud.translation.v3beta1.IGetSupportedLanguagesRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.translation.v3beta1.ISupportedLanguages, - protos.google.cloud.translation.v3beta1.IGetSupportedLanguagesRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.translation.v3beta1.IGetSupportedLanguagesRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.translation.v3beta1.ISupportedLanguages, + | protos.google.cloud.translation.v3beta1.IGetSupportedLanguagesRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.translation.v3beta1.ISupportedLanguages, + ( + | protos.google.cloud.translation.v3beta1.IGetSupportedLanguagesRequest + | undefined + ), + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getSupportedLanguages request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.translation.v3beta1.ISupportedLanguages, - protos.google.cloud.translation.v3beta1.IGetSupportedLanguagesRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.translation.v3beta1.ISupportedLanguages, + | protos.google.cloud.translation.v3beta1.IGetSupportedLanguagesRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getSupportedLanguages response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.getSupportedLanguages(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.translation.v3beta1.ISupportedLanguages, - protos.google.cloud.translation.v3beta1.IGetSupportedLanguagesRequest|undefined, {}|undefined - ]) => { - this._log.info('getSupportedLanguages response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getSupportedLanguages(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.translation.v3beta1.ISupportedLanguages, + ( + | protos.google.cloud.translation.v3beta1.IGetSupportedLanguagesRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('getSupportedLanguages response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Gets a glossary. Returns NOT_FOUND, if the glossary doesn't - * exist. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The name of the glossary to retrieve. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.translation.v3beta1.Glossary|Glossary}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v3beta1/translation_service.get_glossary.js - * region_tag:translate_v3beta1_generated_TranslationService_GetGlossary_async - */ + /** + * Gets a glossary. Returns NOT_FOUND, if the glossary doesn't + * exist. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The name of the glossary to retrieve. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.translation.v3beta1.Glossary|Glossary}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v3beta1/translation_service.get_glossary.js + * region_tag:translate_v3beta1_generated_TranslationService_GetGlossary_async + */ getGlossary( - request?: protos.google.cloud.translation.v3beta1.IGetGlossaryRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.translation.v3beta1.IGlossary, - protos.google.cloud.translation.v3beta1.IGetGlossaryRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.translation.v3beta1.IGetGlossaryRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.translation.v3beta1.IGlossary, + protos.google.cloud.translation.v3beta1.IGetGlossaryRequest | undefined, + {} | undefined, + ] + >; getGlossary( - request: protos.google.cloud.translation.v3beta1.IGetGlossaryRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.translation.v3beta1.IGlossary, - protos.google.cloud.translation.v3beta1.IGetGlossaryRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.translation.v3beta1.IGetGlossaryRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.translation.v3beta1.IGlossary, + | protos.google.cloud.translation.v3beta1.IGetGlossaryRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getGlossary( - request: protos.google.cloud.translation.v3beta1.IGetGlossaryRequest, - callback: Callback< - protos.google.cloud.translation.v3beta1.IGlossary, - protos.google.cloud.translation.v3beta1.IGetGlossaryRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.translation.v3beta1.IGetGlossaryRequest, + callback: Callback< + protos.google.cloud.translation.v3beta1.IGlossary, + | protos.google.cloud.translation.v3beta1.IGetGlossaryRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getGlossary( - request?: protos.google.cloud.translation.v3beta1.IGetGlossaryRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.translation.v3beta1.IGlossary, - protos.google.cloud.translation.v3beta1.IGetGlossaryRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.translation.v3beta1.IGetGlossaryRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.translation.v3beta1.IGlossary, - protos.google.cloud.translation.v3beta1.IGetGlossaryRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.translation.v3beta1.IGlossary, - protos.google.cloud.translation.v3beta1.IGetGlossaryRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.translation.v3beta1.IGetGlossaryRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.translation.v3beta1.IGlossary, + | protos.google.cloud.translation.v3beta1.IGetGlossaryRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.translation.v3beta1.IGlossary, + protos.google.cloud.translation.v3beta1.IGetGlossaryRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getGlossary request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.translation.v3beta1.IGlossary, - protos.google.cloud.translation.v3beta1.IGetGlossaryRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.translation.v3beta1.IGlossary, + | protos.google.cloud.translation.v3beta1.IGetGlossaryRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getGlossary response %j', response); callback!(error, response, options, rawResponse); } : undefined; - return this.innerApiCalls.getGlossary(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.translation.v3beta1.IGlossary, - protos.google.cloud.translation.v3beta1.IGetGlossaryRequest|undefined, {}|undefined - ]) => { - this._log.info('getGlossary response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getGlossary(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.translation.v3beta1.IGlossary, + ( + | protos.google.cloud.translation.v3beta1.IGetGlossaryRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('getGlossary response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Translates a large volume of text in asynchronous batch mode. - * This function provides real-time output as the inputs are being processed. - * If caller cancels a request, the partial results (for an input file, it's - * all or nothing) may still be available on the specified output location. - * - * This call returns immediately and you can - * use google.longrunning.Operation.name to poll the status of the call. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. Location to make a call. Must refer to a caller's project. - * - * Format: `projects/{project-id}/locations/{location-id}`. - * - * The `global` location is not supported for batch translation. - * - * Only AutoML Translation models or glossaries within the same region (have - * the same location-id) can be used, otherwise an INVALID_ARGUMENT (400) - * error is returned. - * @param {string} request.sourceLanguageCode - * Required. Source language code. - * @param {string[]} request.targetLanguageCodes - * Required. Specify up to 10 language codes here. - * @param {number[]} [request.models] - * Optional. The models to use for translation. Map's key is target language - * code. Map's value is model name. Value can be a built-in general model, - * or an AutoML Translation model. - * - * The value format depends on model type: - * - * - AutoML Translation models: - * `projects/{project-id}/locations/{location-id}/models/{model-id}` - * - * - General (built-in) models: - * `projects/{project-id}/locations/{location-id}/models/general/nmt`, - * `projects/{project-id}/locations/{location-id}/models/general/base` - * - * - * If the map is empty or a specific model is - * not requested for a language pair, then default google model (nmt) is used. - * @param {number[]} request.inputConfigs - * Required. Input configurations. - * The total number of files matched should be <= 1000. - * The total content size should be <= 100M Unicode codepoints. - * The files must use UTF-8 encoding. - * @param {google.cloud.translation.v3beta1.OutputConfig} request.outputConfig - * Required. Output configuration. - * If 2 input configs match to the same file (that is, same input path), - * we don't generate output for duplicate inputs. - * @param {number[]} [request.glossaries] - * Optional. Glossaries to be applied for translation. - * It's keyed by target language code. - * @param {number[]} [request.labels] - * Optional. The labels with user-defined metadata for the request. - * - * Label keys and values can be no longer than 63 characters - * (Unicode codepoints), can only contain lowercase letters, numeric - * characters, underscores and dashes. International characters are allowed. - * Label values are optional. Label keys must start with a letter. - * - * See https://cloud.google.com/translate/docs/labels for more information. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing - * a long running operation. Its `promise()` method returns a promise - * you can `await` for. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v3beta1/translation_service.batch_translate_text.js - * region_tag:translate_v3beta1_generated_TranslationService_BatchTranslateText_async - */ + /** + * Translates a large volume of text in asynchronous batch mode. + * This function provides real-time output as the inputs are being processed. + * If caller cancels a request, the partial results (for an input file, it's + * all or nothing) may still be available on the specified output location. + * + * This call returns immediately and you can + * use google.longrunning.Operation.name to poll the status of the call. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Location to make a call. Must refer to a caller's project. + * + * Format: `projects/{project-id}/locations/{location-id}`. + * + * The `global` location is not supported for batch translation. + * + * Only AutoML Translation models or glossaries within the same region (have + * the same location-id) can be used, otherwise an INVALID_ARGUMENT (400) + * error is returned. + * @param {string} request.sourceLanguageCode + * Required. Source language code. + * @param {string[]} request.targetLanguageCodes + * Required. Specify up to 10 language codes here. + * @param {number[]} [request.models] + * Optional. The models to use for translation. Map's key is target language + * code. Map's value is model name. Value can be a built-in general model, + * or an AutoML Translation model. + * + * The value format depends on model type: + * + * - AutoML Translation models: + * `projects/{project-id}/locations/{location-id}/models/{model-id}` + * + * - General (built-in) models: + * `projects/{project-id}/locations/{location-id}/models/general/nmt`, + * `projects/{project-id}/locations/{location-id}/models/general/base` + * + * + * If the map is empty or a specific model is + * not requested for a language pair, then default google model (nmt) is used. + * @param {number[]} request.inputConfigs + * Required. Input configurations. + * The total number of files matched should be <= 1000. + * The total content size should be <= 100M Unicode codepoints. + * The files must use UTF-8 encoding. + * @param {google.cloud.translation.v3beta1.OutputConfig} request.outputConfig + * Required. Output configuration. + * If 2 input configs match to the same file (that is, same input path), + * we don't generate output for duplicate inputs. + * @param {number[]} [request.glossaries] + * Optional. Glossaries to be applied for translation. + * It's keyed by target language code. + * @param {number[]} [request.labels] + * Optional. The labels with user-defined metadata for the request. + * + * Label keys and values can be no longer than 63 characters + * (Unicode codepoints), can only contain lowercase letters, numeric + * characters, underscores and dashes. International characters are allowed. + * Label values are optional. Label keys must start with a letter. + * + * See https://cloud.google.com/translate/docs/labels for more information. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v3beta1/translation_service.batch_translate_text.js + * region_tag:translate_v3beta1_generated_TranslationService_BatchTranslateText_async + */ batchTranslateText( - request?: protos.google.cloud.translation.v3beta1.IBatchTranslateTextRequest, - options?: CallOptions): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>; + request?: protos.google.cloud.translation.v3beta1.IBatchTranslateTextRequest, + options?: CallOptions, + ): Promise< + [ + LROperation< + protos.google.cloud.translation.v3beta1.IBatchTranslateResponse, + protos.google.cloud.translation.v3beta1.IBatchTranslateMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; batchTranslateText( - request: protos.google.cloud.translation.v3beta1.IBatchTranslateTextRequest, - options: CallOptions, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.translation.v3beta1.IBatchTranslateTextRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.cloud.translation.v3beta1.IBatchTranslateResponse, + protos.google.cloud.translation.v3beta1.IBatchTranslateMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; batchTranslateText( - request: protos.google.cloud.translation.v3beta1.IBatchTranslateTextRequest, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.translation.v3beta1.IBatchTranslateTextRequest, + callback: Callback< + LROperation< + protos.google.cloud.translation.v3beta1.IBatchTranslateResponse, + protos.google.cloud.translation.v3beta1.IBatchTranslateMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; batchTranslateText( - request?: protos.google.cloud.translation.v3beta1.IBatchTranslateTextRequest, - optionsOrCallback?: CallOptions|Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>, - callback?: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>|void { + request?: protos.google.cloud.translation.v3beta1.IBatchTranslateTextRequest, + optionsOrCallback?: + | CallOptions + | Callback< + LROperation< + protos.google.cloud.translation.v3beta1.IBatchTranslateResponse, + protos.google.cloud.translation.v3beta1.IBatchTranslateMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + callback?: Callback< + LROperation< + protos.google.cloud.translation.v3beta1.IBatchTranslateResponse, + protos.google.cloud.translation.v3beta1.IBatchTranslateMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + LROperation< + protos.google.cloud.translation.v3beta1.IBatchTranslateResponse, + protos.google.cloud.translation.v3beta1.IBatchTranslateMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + LROperation< + protos.google.cloud.translation.v3beta1.IBatchTranslateResponse, + protos.google.cloud.translation.v3beta1.IBatchTranslateMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, rawResponse, _) => { this._log.info('batchTranslateText response %j', rawResponse); callback!(error, response, rawResponse, _); // We verified `callback` above. } : undefined; this._log.info('batchTranslateText request %j', request); - return this.innerApiCalls.batchTranslateText(request, options, wrappedCallback) - ?.then(([response, rawResponse, _]: [ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]) => { - this._log.info('batchTranslateText response %j', rawResponse); - return [response, rawResponse, _]; - }); + return this.innerApiCalls + .batchTranslateText(request, options, wrappedCallback) + ?.then( + ([response, rawResponse, _]: [ + LROperation< + protos.google.cloud.translation.v3beta1.IBatchTranslateResponse, + protos.google.cloud.translation.v3beta1.IBatchTranslateMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ]) => { + this._log.info('batchTranslateText response %j', rawResponse); + return [response, rawResponse, _]; + }, + ); } -/** - * Check the status of the long running operation returned by `batchTranslateText()`. - * @param {String} name - * The operation name that will be passed. - * @returns {Promise} - The promise which resolves to an object. - * The decoded operation object has result and metadata field to get information from. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v3beta1/translation_service.batch_translate_text.js - * region_tag:translate_v3beta1_generated_TranslationService_BatchTranslateText_async - */ - async checkBatchTranslateTextProgress(name: string): Promise>{ + /** + * Check the status of the long running operation returned by `batchTranslateText()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v3beta1/translation_service.batch_translate_text.js + * region_tag:translate_v3beta1_generated_TranslationService_BatchTranslateText_async + */ + async checkBatchTranslateTextProgress( + name: string, + ): Promise< + LROperation< + protos.google.cloud.translation.v3beta1.BatchTranslateResponse, + protos.google.cloud.translation.v3beta1.BatchTranslateMetadata + > + > { this._log.info('batchTranslateText long-running'); - const request = new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest({name}); + const request = + new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( + { name }, + ); const [operation] = await this.operationsClient.getOperation(request); - const decodeOperation = new this._gaxModule.Operation(operation, this.descriptors.longrunning.batchTranslateText, this._gaxModule.createDefaultBackoffSettings()); - return decodeOperation as LROperation; + const decodeOperation = new this._gaxModule.Operation( + operation, + this.descriptors.longrunning.batchTranslateText, + this._gaxModule.createDefaultBackoffSettings(), + ); + return decodeOperation as LROperation< + protos.google.cloud.translation.v3beta1.BatchTranslateResponse, + protos.google.cloud.translation.v3beta1.BatchTranslateMetadata + >; } -/** - * Creates a glossary and returns the long-running operation. Returns - * NOT_FOUND, if the project doesn't exist. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The project name. - * @param {google.cloud.translation.v3beta1.Glossary} request.glossary - * Required. The glossary to create. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing - * a long running operation. Its `promise()` method returns a promise - * you can `await` for. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v3beta1/translation_service.create_glossary.js - * region_tag:translate_v3beta1_generated_TranslationService_CreateGlossary_async - */ + /** + * Creates a glossary and returns the long-running operation. Returns + * NOT_FOUND, if the project doesn't exist. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The project name. + * @param {google.cloud.translation.v3beta1.Glossary} request.glossary + * Required. The glossary to create. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v3beta1/translation_service.create_glossary.js + * region_tag:translate_v3beta1_generated_TranslationService_CreateGlossary_async + */ createGlossary( - request?: protos.google.cloud.translation.v3beta1.ICreateGlossaryRequest, - options?: CallOptions): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>; + request?: protos.google.cloud.translation.v3beta1.ICreateGlossaryRequest, + options?: CallOptions, + ): Promise< + [ + LROperation< + protos.google.cloud.translation.v3beta1.IGlossary, + protos.google.cloud.translation.v3beta1.ICreateGlossaryMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; createGlossary( - request: protos.google.cloud.translation.v3beta1.ICreateGlossaryRequest, - options: CallOptions, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.translation.v3beta1.ICreateGlossaryRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.cloud.translation.v3beta1.IGlossary, + protos.google.cloud.translation.v3beta1.ICreateGlossaryMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; createGlossary( - request: protos.google.cloud.translation.v3beta1.ICreateGlossaryRequest, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.translation.v3beta1.ICreateGlossaryRequest, + callback: Callback< + LROperation< + protos.google.cloud.translation.v3beta1.IGlossary, + protos.google.cloud.translation.v3beta1.ICreateGlossaryMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; createGlossary( - request?: protos.google.cloud.translation.v3beta1.ICreateGlossaryRequest, - optionsOrCallback?: CallOptions|Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>, - callback?: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>|void { + request?: protos.google.cloud.translation.v3beta1.ICreateGlossaryRequest, + optionsOrCallback?: + | CallOptions + | Callback< + LROperation< + protos.google.cloud.translation.v3beta1.IGlossary, + protos.google.cloud.translation.v3beta1.ICreateGlossaryMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + callback?: Callback< + LROperation< + protos.google.cloud.translation.v3beta1.IGlossary, + protos.google.cloud.translation.v3beta1.ICreateGlossaryMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + LROperation< + protos.google.cloud.translation.v3beta1.IGlossary, + protos.google.cloud.translation.v3beta1.ICreateGlossaryMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + LROperation< + protos.google.cloud.translation.v3beta1.IGlossary, + protos.google.cloud.translation.v3beta1.ICreateGlossaryMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, rawResponse, _) => { this._log.info('createGlossary response %j', rawResponse); callback!(error, response, rawResponse, _); // We verified `callback` above. } : undefined; this._log.info('createGlossary request %j', request); - return this.innerApiCalls.createGlossary(request, options, wrappedCallback) - ?.then(([response, rawResponse, _]: [ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]) => { - this._log.info('createGlossary response %j', rawResponse); - return [response, rawResponse, _]; - }); + return this.innerApiCalls + .createGlossary(request, options, wrappedCallback) + ?.then( + ([response, rawResponse, _]: [ + LROperation< + protos.google.cloud.translation.v3beta1.IGlossary, + protos.google.cloud.translation.v3beta1.ICreateGlossaryMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ]) => { + this._log.info('createGlossary response %j', rawResponse); + return [response, rawResponse, _]; + }, + ); } -/** - * Check the status of the long running operation returned by `createGlossary()`. - * @param {String} name - * The operation name that will be passed. - * @returns {Promise} - The promise which resolves to an object. - * The decoded operation object has result and metadata field to get information from. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v3beta1/translation_service.create_glossary.js - * region_tag:translate_v3beta1_generated_TranslationService_CreateGlossary_async - */ - async checkCreateGlossaryProgress(name: string): Promise>{ + /** + * Check the status of the long running operation returned by `createGlossary()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v3beta1/translation_service.create_glossary.js + * region_tag:translate_v3beta1_generated_TranslationService_CreateGlossary_async + */ + async checkCreateGlossaryProgress( + name: string, + ): Promise< + LROperation< + protos.google.cloud.translation.v3beta1.Glossary, + protos.google.cloud.translation.v3beta1.CreateGlossaryMetadata + > + > { this._log.info('createGlossary long-running'); - const request = new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest({name}); + const request = + new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( + { name }, + ); const [operation] = await this.operationsClient.getOperation(request); - const decodeOperation = new this._gaxModule.Operation(operation, this.descriptors.longrunning.createGlossary, this._gaxModule.createDefaultBackoffSettings()); - return decodeOperation as LROperation; + const decodeOperation = new this._gaxModule.Operation( + operation, + this.descriptors.longrunning.createGlossary, + this._gaxModule.createDefaultBackoffSettings(), + ); + return decodeOperation as LROperation< + protos.google.cloud.translation.v3beta1.Glossary, + protos.google.cloud.translation.v3beta1.CreateGlossaryMetadata + >; } -/** - * Deletes a glossary, or cancels glossary construction - * if the glossary isn't created yet. - * Returns NOT_FOUND, if the glossary doesn't exist. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The name of the glossary to delete. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing - * a long running operation. Its `promise()` method returns a promise - * you can `await` for. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v3beta1/translation_service.delete_glossary.js - * region_tag:translate_v3beta1_generated_TranslationService_DeleteGlossary_async - */ + /** + * Deletes a glossary, or cancels glossary construction + * if the glossary isn't created yet. + * Returns NOT_FOUND, if the glossary doesn't exist. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The name of the glossary to delete. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v3beta1/translation_service.delete_glossary.js + * region_tag:translate_v3beta1_generated_TranslationService_DeleteGlossary_async + */ deleteGlossary( - request?: protos.google.cloud.translation.v3beta1.IDeleteGlossaryRequest, - options?: CallOptions): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>; + request?: protos.google.cloud.translation.v3beta1.IDeleteGlossaryRequest, + options?: CallOptions, + ): Promise< + [ + LROperation< + protos.google.cloud.translation.v3beta1.IDeleteGlossaryResponse, + protos.google.cloud.translation.v3beta1.IDeleteGlossaryMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; deleteGlossary( - request: protos.google.cloud.translation.v3beta1.IDeleteGlossaryRequest, - options: CallOptions, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.translation.v3beta1.IDeleteGlossaryRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.cloud.translation.v3beta1.IDeleteGlossaryResponse, + protos.google.cloud.translation.v3beta1.IDeleteGlossaryMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; deleteGlossary( - request: protos.google.cloud.translation.v3beta1.IDeleteGlossaryRequest, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.translation.v3beta1.IDeleteGlossaryRequest, + callback: Callback< + LROperation< + protos.google.cloud.translation.v3beta1.IDeleteGlossaryResponse, + protos.google.cloud.translation.v3beta1.IDeleteGlossaryMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; deleteGlossary( - request?: protos.google.cloud.translation.v3beta1.IDeleteGlossaryRequest, - optionsOrCallback?: CallOptions|Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>, - callback?: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>|void { + request?: protos.google.cloud.translation.v3beta1.IDeleteGlossaryRequest, + optionsOrCallback?: + | CallOptions + | Callback< + LROperation< + protos.google.cloud.translation.v3beta1.IDeleteGlossaryResponse, + protos.google.cloud.translation.v3beta1.IDeleteGlossaryMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + callback?: Callback< + LROperation< + protos.google.cloud.translation.v3beta1.IDeleteGlossaryResponse, + protos.google.cloud.translation.v3beta1.IDeleteGlossaryMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + LROperation< + protos.google.cloud.translation.v3beta1.IDeleteGlossaryResponse, + protos.google.cloud.translation.v3beta1.IDeleteGlossaryMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + LROperation< + protos.google.cloud.translation.v3beta1.IDeleteGlossaryResponse, + protos.google.cloud.translation.v3beta1.IDeleteGlossaryMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, rawResponse, _) => { this._log.info('deleteGlossary response %j', rawResponse); callback!(error, response, rawResponse, _); // We verified `callback` above. } : undefined; this._log.info('deleteGlossary request %j', request); - return this.innerApiCalls.deleteGlossary(request, options, wrappedCallback) - ?.then(([response, rawResponse, _]: [ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]) => { - this._log.info('deleteGlossary response %j', rawResponse); - return [response, rawResponse, _]; - }); + return this.innerApiCalls + .deleteGlossary(request, options, wrappedCallback) + ?.then( + ([response, rawResponse, _]: [ + LROperation< + protos.google.cloud.translation.v3beta1.IDeleteGlossaryResponse, + protos.google.cloud.translation.v3beta1.IDeleteGlossaryMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ]) => { + this._log.info('deleteGlossary response %j', rawResponse); + return [response, rawResponse, _]; + }, + ); } -/** - * Check the status of the long running operation returned by `deleteGlossary()`. - * @param {String} name - * The operation name that will be passed. - * @returns {Promise} - The promise which resolves to an object. - * The decoded operation object has result and metadata field to get information from. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v3beta1/translation_service.delete_glossary.js - * region_tag:translate_v3beta1_generated_TranslationService_DeleteGlossary_async - */ - async checkDeleteGlossaryProgress(name: string): Promise>{ + /** + * Check the status of the long running operation returned by `deleteGlossary()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v3beta1/translation_service.delete_glossary.js + * region_tag:translate_v3beta1_generated_TranslationService_DeleteGlossary_async + */ + async checkDeleteGlossaryProgress( + name: string, + ): Promise< + LROperation< + protos.google.cloud.translation.v3beta1.DeleteGlossaryResponse, + protos.google.cloud.translation.v3beta1.DeleteGlossaryMetadata + > + > { this._log.info('deleteGlossary long-running'); - const request = new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest({name}); + const request = + new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( + { name }, + ); const [operation] = await this.operationsClient.getOperation(request); - const decodeOperation = new this._gaxModule.Operation(operation, this.descriptors.longrunning.deleteGlossary, this._gaxModule.createDefaultBackoffSettings()); - return decodeOperation as LROperation; + const decodeOperation = new this._gaxModule.Operation( + operation, + this.descriptors.longrunning.deleteGlossary, + this._gaxModule.createDefaultBackoffSettings(), + ); + return decodeOperation as LROperation< + protos.google.cloud.translation.v3beta1.DeleteGlossaryResponse, + protos.google.cloud.translation.v3beta1.DeleteGlossaryMetadata + >; } - /** - * Lists glossaries in a project. Returns NOT_FOUND, if the project doesn't - * exist. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The name of the project from which to list all of the glossaries. - * @param {number} [request.pageSize] - * Optional. Requested page size. The server may return fewer glossaries than - * requested. If unspecified, the server picks an appropriate default. - * @param {string} [request.pageToken] - * Optional. A token identifying a page of results the server should return. - * Typically, this is the value of [ListGlossariesResponse.next_page_token] - * returned from the previous call to `ListGlossaries` method. - * The first page is returned if `page_token`is empty or missing. - * @param {string} [request.filter] - * Optional. Filter specifying constraints of a list operation. - * Filtering is not supported yet, and the parameter currently has no effect. - * If missing, no filtering is performed. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.cloud.translation.v3beta1.Glossary|Glossary}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `listGlossariesAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Lists glossaries in a project. Returns NOT_FOUND, if the project doesn't + * exist. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The name of the project from which to list all of the glossaries. + * @param {number} [request.pageSize] + * Optional. Requested page size. The server may return fewer glossaries than + * requested. If unspecified, the server picks an appropriate default. + * @param {string} [request.pageToken] + * Optional. A token identifying a page of results the server should return. + * Typically, this is the value of [ListGlossariesResponse.next_page_token] + * returned from the previous call to `ListGlossaries` method. + * The first page is returned if `page_token`is empty or missing. + * @param {string} [request.filter] + * Optional. Filter specifying constraints of a list operation. + * Filtering is not supported yet, and the parameter currently has no effect. + * If missing, no filtering is performed. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.cloud.translation.v3beta1.Glossary|Glossary}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listGlossariesAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listGlossaries( - request?: protos.google.cloud.translation.v3beta1.IListGlossariesRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.translation.v3beta1.IGlossary[], - protos.google.cloud.translation.v3beta1.IListGlossariesRequest|null, - protos.google.cloud.translation.v3beta1.IListGlossariesResponse - ]>; + request?: protos.google.cloud.translation.v3beta1.IListGlossariesRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.translation.v3beta1.IGlossary[], + protos.google.cloud.translation.v3beta1.IListGlossariesRequest | null, + protos.google.cloud.translation.v3beta1.IListGlossariesResponse, + ] + >; listGlossaries( - request: protos.google.cloud.translation.v3beta1.IListGlossariesRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.cloud.translation.v3beta1.IListGlossariesRequest, - protos.google.cloud.translation.v3beta1.IListGlossariesResponse|null|undefined, - protos.google.cloud.translation.v3beta1.IGlossary>): void; + request: protos.google.cloud.translation.v3beta1.IListGlossariesRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.cloud.translation.v3beta1.IListGlossariesRequest, + | protos.google.cloud.translation.v3beta1.IListGlossariesResponse + | null + | undefined, + protos.google.cloud.translation.v3beta1.IGlossary + >, + ): void; listGlossaries( - request: protos.google.cloud.translation.v3beta1.IListGlossariesRequest, - callback: PaginationCallback< - protos.google.cloud.translation.v3beta1.IListGlossariesRequest, - protos.google.cloud.translation.v3beta1.IListGlossariesResponse|null|undefined, - protos.google.cloud.translation.v3beta1.IGlossary>): void; + request: protos.google.cloud.translation.v3beta1.IListGlossariesRequest, + callback: PaginationCallback< + protos.google.cloud.translation.v3beta1.IListGlossariesRequest, + | protos.google.cloud.translation.v3beta1.IListGlossariesResponse + | null + | undefined, + protos.google.cloud.translation.v3beta1.IGlossary + >, + ): void; listGlossaries( - request?: protos.google.cloud.translation.v3beta1.IListGlossariesRequest, - optionsOrCallback?: CallOptions|PaginationCallback< + request?: protos.google.cloud.translation.v3beta1.IListGlossariesRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.cloud.translation.v3beta1.IListGlossariesRequest, - protos.google.cloud.translation.v3beta1.IListGlossariesResponse|null|undefined, - protos.google.cloud.translation.v3beta1.IGlossary>, - callback?: PaginationCallback< - protos.google.cloud.translation.v3beta1.IListGlossariesRequest, - protos.google.cloud.translation.v3beta1.IListGlossariesResponse|null|undefined, - protos.google.cloud.translation.v3beta1.IGlossary>): - Promise<[ - protos.google.cloud.translation.v3beta1.IGlossary[], - protos.google.cloud.translation.v3beta1.IListGlossariesRequest|null, - protos.google.cloud.translation.v3beta1.IListGlossariesResponse - ]>|void { + | protos.google.cloud.translation.v3beta1.IListGlossariesResponse + | null + | undefined, + protos.google.cloud.translation.v3beta1.IGlossary + >, + callback?: PaginationCallback< + protos.google.cloud.translation.v3beta1.IListGlossariesRequest, + | protos.google.cloud.translation.v3beta1.IListGlossariesResponse + | null + | undefined, + protos.google.cloud.translation.v3beta1.IGlossary + >, + ): Promise< + [ + protos.google.cloud.translation.v3beta1.IGlossary[], + protos.google.cloud.translation.v3beta1.IListGlossariesRequest | null, + protos.google.cloud.translation.v3beta1.IListGlossariesResponse, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.cloud.translation.v3beta1.IListGlossariesRequest, - protos.google.cloud.translation.v3beta1.IListGlossariesResponse|null|undefined, - protos.google.cloud.translation.v3beta1.IGlossary>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.cloud.translation.v3beta1.IListGlossariesRequest, + | protos.google.cloud.translation.v3beta1.IListGlossariesResponse + | null + | undefined, + protos.google.cloud.translation.v3beta1.IGlossary + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listGlossaries values %j', values); callback!(error, values, nextPageRequest, rawResponse); @@ -1379,122 +1852,126 @@ export class TranslationServiceClient { this._log.info('listGlossaries request %j', request); return this.innerApiCalls .listGlossaries(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.cloud.translation.v3beta1.IGlossary[], - protos.google.cloud.translation.v3beta1.IListGlossariesRequest|null, - protos.google.cloud.translation.v3beta1.IListGlossariesResponse - ]) => { - this._log.info('listGlossaries values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.cloud.translation.v3beta1.IGlossary[], + protos.google.cloud.translation.v3beta1.IListGlossariesRequest | null, + protos.google.cloud.translation.v3beta1.IListGlossariesResponse, + ]) => { + this._log.info('listGlossaries values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listGlossaries`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The name of the project from which to list all of the glossaries. - * @param {number} [request.pageSize] - * Optional. Requested page size. The server may return fewer glossaries than - * requested. If unspecified, the server picks an appropriate default. - * @param {string} [request.pageToken] - * Optional. A token identifying a page of results the server should return. - * Typically, this is the value of [ListGlossariesResponse.next_page_token] - * returned from the previous call to `ListGlossaries` method. - * The first page is returned if `page_token`is empty or missing. - * @param {string} [request.filter] - * Optional. Filter specifying constraints of a list operation. - * Filtering is not supported yet, and the parameter currently has no effect. - * If missing, no filtering is performed. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.cloud.translation.v3beta1.Glossary|Glossary} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `listGlossariesAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `listGlossaries`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The name of the project from which to list all of the glossaries. + * @param {number} [request.pageSize] + * Optional. Requested page size. The server may return fewer glossaries than + * requested. If unspecified, the server picks an appropriate default. + * @param {string} [request.pageToken] + * Optional. A token identifying a page of results the server should return. + * Typically, this is the value of [ListGlossariesResponse.next_page_token] + * returned from the previous call to `ListGlossaries` method. + * The first page is returned if `page_token`is empty or missing. + * @param {string} [request.filter] + * Optional. Filter specifying constraints of a list operation. + * Filtering is not supported yet, and the parameter currently has no effect. + * If missing, no filtering is performed. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.cloud.translation.v3beta1.Glossary|Glossary} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listGlossariesAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listGlossariesStream( - request?: protos.google.cloud.translation.v3beta1.IListGlossariesRequest, - options?: CallOptions): - Transform{ + request?: protos.google.cloud.translation.v3beta1.IListGlossariesRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); const defaultCallSettings = this._defaults['listGlossaries']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listGlossaries stream %j', request); return this.descriptors.page.listGlossaries.createStream( this.innerApiCalls.listGlossaries as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listGlossaries`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The name of the project from which to list all of the glossaries. - * @param {number} [request.pageSize] - * Optional. Requested page size. The server may return fewer glossaries than - * requested. If unspecified, the server picks an appropriate default. - * @param {string} [request.pageToken] - * Optional. A token identifying a page of results the server should return. - * Typically, this is the value of [ListGlossariesResponse.next_page_token] - * returned from the previous call to `ListGlossaries` method. - * The first page is returned if `page_token`is empty or missing. - * @param {string} [request.filter] - * Optional. Filter specifying constraints of a list operation. - * Filtering is not supported yet, and the parameter currently has no effect. - * If missing, no filtering is performed. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.cloud.translation.v3beta1.Glossary|Glossary}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v3beta1/translation_service.list_glossaries.js - * region_tag:translate_v3beta1_generated_TranslationService_ListGlossaries_async - */ + /** + * Equivalent to `listGlossaries`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The name of the project from which to list all of the glossaries. + * @param {number} [request.pageSize] + * Optional. Requested page size. The server may return fewer glossaries than + * requested. If unspecified, the server picks an appropriate default. + * @param {string} [request.pageToken] + * Optional. A token identifying a page of results the server should return. + * Typically, this is the value of [ListGlossariesResponse.next_page_token] + * returned from the previous call to `ListGlossaries` method. + * The first page is returned if `page_token`is empty or missing. + * @param {string} [request.filter] + * Optional. Filter specifying constraints of a list operation. + * Filtering is not supported yet, and the parameter currently has no effect. + * If missing, no filtering is performed. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.cloud.translation.v3beta1.Glossary|Glossary}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v3beta1/translation_service.list_glossaries.js + * region_tag:translate_v3beta1_generated_TranslationService_ListGlossaries_async + */ listGlossariesAsync( - request?: protos.google.cloud.translation.v3beta1.IListGlossariesRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.cloud.translation.v3beta1.IListGlossariesRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); const defaultCallSettings = this._defaults['listGlossaries']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listGlossaries iterate %j', request); return this.descriptors.page.listGlossaries.asyncIterate( this.innerApiCalls['listGlossaries'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } // -------------------- @@ -1509,7 +1986,7 @@ export class TranslationServiceClient { * @param {string} glossary * @returns {string} Resource name string. */ - glossaryPath(project:string,location:string,glossary:string) { + glossaryPath(project: string, location: string, glossary: string) { return this.pathTemplates.glossaryPathTemplate.render({ project: project, location: location, @@ -1557,7 +2034,7 @@ export class TranslationServiceClient { * @param {string} location * @returns {string} Resource name string. */ - locationPath(project:string,location:string) { + locationPath(project: string, location: string) { return this.pathTemplates.locationPathTemplate.render({ project: project, location: location, @@ -1594,7 +2071,7 @@ export class TranslationServiceClient { */ close(): Promise { if (this.translationServiceStub && !this._terminated) { - return this.translationServiceStub.then(stub => { + return this.translationServiceStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -1603,4 +2080,4 @@ export class TranslationServiceClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/core/generator/gapic-generator-typescript/baselines/translate-esm/esm/system-test/fixtures/sample/src/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/translate-esm/esm/system-test/fixtures/sample/src/index.ts.baseline index 15bd45a8eca7..af240229f167 100644 --- a/core/generator/gapic-generator-typescript/baselines/translate-esm/esm/system-test/fixtures/sample/src/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/translate-esm/esm/system-test/fixtures/sample/src/index.ts.baseline @@ -17,7 +17,7 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -import {TranslationServiceClient} from 'translation'; +import { TranslationServiceClient } from 'translation'; // check that the client class type name can be used function doStuffWithTranslationServiceClient(client: TranslationServiceClient) { diff --git a/core/generator/gapic-generator-typescript/baselines/translate-esm/esm/system-test/install.ts.baseline b/core/generator/gapic-generator-typescript/baselines/translate-esm/esm/system-test/install.ts.baseline index e079c4fa1101..d109fdd8c97f 100644 --- a/core/generator/gapic-generator-typescript/baselines/translate-esm/esm/system-test/install.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/translate-esm/esm/system-test/install.ts.baseline @@ -16,40 +16,45 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -import {packNTest} from 'pack-n-play'; -import {readFileSync} from 'fs'; -import {describe, it} from 'mocha'; +import { packNTest } from 'pack-n-play'; +import { readFileSync } from 'fs'; +import { describe, it } from 'mocha'; describe('📦 pack-n-play test', () => { - it('TypeScript', async function() { + it('TypeScript', async function () { this.timeout(300000); await packNTest({ packageDir: process.cwd(), sample: { description: 'TypeScript user can use the type definitions', - ts: readFileSync('./esm/system-test/fixtures/sample/src/index.ts').toString() - } + ts: readFileSync( + './esm/system-test/fixtures/sample/src/index.ts', + ).toString(), + }, }); }); - it('ESM module', async function() { + it('ESM module', async function () { this.timeout(300000); await packNTest({ sample: { description: 'Should be able to import using ESM', - esm: readFileSync('./esm/system-test/fixtures/sample/src/index.js').toString(), + esm: readFileSync( + './esm/system-test/fixtures/sample/src/index.js', + ).toString(), }, }); }); - it('CJS module', async function() { + it('CJS module', async function () { this.timeout(300000); await packNTest({ sample: { description: 'Should be able to import using CJS', - cjs: readFileSync('./esm/system-test/fixtures/sample/src/index.cjs').toString(), + cjs: readFileSync( + './esm/system-test/fixtures/sample/src/index.cjs', + ).toString(), }, }); }); - }); diff --git a/core/generator/gapic-generator-typescript/baselines/translate-esm/esm/test/gapic_translation_service_v3beta1.ts.baseline b/core/generator/gapic-generator-typescript/baselines/translate-esm/esm/test/gapic_translation_service_v3beta1.ts.baseline index 629006c0a48b..289a88e14325 100644 --- a/core/generator/gapic-generator-typescript/baselines/translate-esm/esm/test/gapic_translation_service_v3beta1.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/translate-esm/esm/test/gapic_translation_service_v3beta1.ts.baseline @@ -20,16 +20,16 @@ import * as protos from '../../protos/protos.js'; import assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as translationserviceModule from '../src/index.js'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; -import {protobuf, LROperation, operationsProtos} from 'google-gax'; +import { protobuf, LROperation, operationsProtos } from 'google-gax'; import fs from 'fs'; import path from 'path'; -import {fileURLToPath} from 'url'; +import { fileURLToPath } from 'url'; // @ts-ignore const dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -37,1476 +37,1947 @@ const dirname = path.dirname(fileURLToPath(import.meta.url)); // to fill in default values for request objects const root = protobuf.Root.fromJSON( JSON.parse( - fs.readFileSync(path.join(dirname, '..', '..', 'protos/protos.json'), 'utf8') - )) + fs.readFileSync( + path.join(dirname, '..', '..', 'protos/protos.json'), + 'utf8', + ), + ), +); // eslint-disable-next-line @typescript-eslint/no-unused-vars function getTypeDefaultValue(typeName: string, fields: string[]) { - let type = root.lookupType(typeName) as protobuf.Type; - for (const field of fields.slice(0, -1)) { - type = type?.fields[field]?.resolvedType as protobuf.Type; - } - return type?.fields[fields[fields.length - 1]]?.defaultValue ?? null; + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type?.fields[field]?.resolvedType as protobuf.Type; + } + return type?.fields[fields[fields.length - 1]]?.defaultValue ?? null; } function generateSampleMessage(instance: T) { - const filledObject = (instance.constructor as typeof protobuf.Message) - .toObject(instance as protobuf.Message, {defaults: true}); - return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, { defaults: true }); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; } function stubSimpleCall(response?: ResponseType, error?: Error) { - return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); } -function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { - return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +function stubSimpleCallWithCallback( + response?: ResponseType, + error?: Error, +) { + return error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); } -function stubLongRunningCall(response?: ResponseType, callError?: Error, lroError?: Error) { - const innerStub = lroError ? sinon.stub().rejects(lroError) : sinon.stub().resolves([response]); - const mockOperation = { - promise: innerStub, - }; - return callError ? sinon.stub().rejects(callError) : sinon.stub().resolves([mockOperation]); +function stubLongRunningCall( + response?: ResponseType, + callError?: Error, + lroError?: Error, +) { + const innerStub = lroError + ? sinon.stub().rejects(lroError) + : sinon.stub().resolves([response]); + const mockOperation = { + promise: innerStub, + }; + return callError + ? sinon.stub().rejects(callError) + : sinon.stub().resolves([mockOperation]); } -function stubLongRunningCallWithCallback(response?: ResponseType, callError?: Error, lroError?: Error) { - const innerStub = lroError ? sinon.stub().rejects(lroError) : sinon.stub().resolves([response]); - const mockOperation = { - promise: innerStub, - }; - return callError ? sinon.stub().callsArgWith(2, callError) : sinon.stub().callsArgWith(2, null, mockOperation); +function stubLongRunningCallWithCallback( + response?: ResponseType, + callError?: Error, + lroError?: Error, +) { + const innerStub = lroError + ? sinon.stub().rejects(lroError) + : sinon.stub().resolves([response]); + const mockOperation = { + promise: innerStub, + }; + return callError + ? sinon.stub().callsArgWith(2, callError) + : sinon.stub().callsArgWith(2, null, mockOperation); } -function stubPageStreamingCall(responses?: ResponseType[], error?: Error) { - const pagingStub = sinon.stub(); - if (responses) { - for (let i = 0; i < responses.length; ++i) { - pagingStub.onCall(i).callsArgWith(2, null, responses[i]); - } +function stubPageStreamingCall( + responses?: ResponseType[], + error?: Error, +) { + const pagingStub = sinon.stub(); + if (responses) { + for (let i = 0; i < responses.length; ++i) { + pagingStub.onCall(i).callsArgWith(2, null, responses[i]); } - const transformStub = error ? sinon.stub().callsArgWith(2, error) : pagingStub; - const mockStream = new PassThrough({ - objectMode: true, - transform: transformStub, - }); - // trigger as many responses as needed - if (responses) { - for (let i = 0; i < responses.length; ++i) { - setImmediate(() => { mockStream.write({}); }); - } - setImmediate(() => { mockStream.end(); }); - } else { - setImmediate(() => { mockStream.write({}); }); - setImmediate(() => { mockStream.end(); }); + } + const transformStub = error + ? sinon.stub().callsArgWith(2, error) + : pagingStub; + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + // trigger as many responses as needed + if (responses) { + for (let i = 0; i < responses.length; ++i) { + setImmediate(() => { + mockStream.write({}); + }); } - return sinon.stub().returns(mockStream); + setImmediate(() => { + mockStream.end(); + }); + } else { + setImmediate(() => { + mockStream.write({}); + }); + setImmediate(() => { + mockStream.end(); + }); + } + return sinon.stub().returns(mockStream); } -function stubAsyncIterationCall(responses?: ResponseType[], error?: Error) { - let counter = 0; - const asyncIterable = { - [Symbol.asyncIterator]() { - return { - async next() { - if (error) { - return Promise.reject(error); - } - if (counter >= responses!.length) { - return Promise.resolve({done: true, value: undefined}); - } - return Promise.resolve({done: false, value: responses![counter++]}); - } - }; - } - }; - return sinon.stub().returns(asyncIterable); +function stubAsyncIterationCall( + responses?: ResponseType[], + error?: Error, +) { + let counter = 0; + const asyncIterable = { + [Symbol.asyncIterator]() { + return { + async next() { + if (error) { + return Promise.reject(error); + } + if (counter >= responses!.length) { + return Promise.resolve({ done: true, value: undefined }); + } + return Promise.resolve({ done: false, value: responses![counter++] }); + }, + }; + }, + }; + return sinon.stub().returns(asyncIterable); } describe('v3beta1.TranslationServiceClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new translationserviceModule.v3beta1.TranslationServiceClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'translate.googleapis.com'); - }); - - it('has universeDomain', () => { - const client = new translationserviceModule.v3beta1.TranslationServiceClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = + new translationserviceModule.v3beta1.TranslationServiceClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'translate.googleapis.com'); + }); - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - it('throws DeprecationWarning if static servicePath is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const servicePath = translationserviceModule.v3beta1.TranslationServiceClient.servicePath; - assert.strictEqual(servicePath, 'translate.googleapis.com'); - assert(stub.called); - stub.restore(); - }); + it('has universeDomain', () => { + const client = + new translationserviceModule.v3beta1.TranslationServiceClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = translationserviceModule.v3beta1.TranslationServiceClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'translate.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new translationserviceModule.v3beta1.TranslationServiceClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'translate.example.com'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = + translationserviceModule.v3beta1.TranslationServiceClient.servicePath; + assert.strictEqual(servicePath, 'translate.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + translationserviceModule.v3beta1.TranslationServiceClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'translate.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = + new translationserviceModule.v3beta1.TranslationServiceClient({ + universeDomain: 'example.com', }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'translate.example.com'); + }); - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new translationserviceModule.v3beta1.TranslationServiceClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'translate.example.com'); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = + new translationserviceModule.v3beta1.TranslationServiceClient({ + universe_domain: 'example.com', }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'translate.example.com'); + }); - if (typeof process === 'object' && 'env' in process) { - describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { - it('sets apiEndpoint from environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new translationserviceModule.v3beta1.TranslationServiceClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'translate.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - - it('value configured in code has priority over environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new translationserviceModule.v3beta1.TranslationServiceClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'translate.configured.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { new translationserviceModule.v3beta1.TranslationServiceClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); + if (typeof process === 'object' && 'env' in process) { + describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { + it('sets apiEndpoint from environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = + new translationserviceModule.v3beta1.TranslationServiceClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'translate.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - it('has port', () => { - const port = translationserviceModule.v3beta1.TranslationServiceClient.port; - assert(port); - assert(typeof port === 'number'); + it('value configured in code has priority over environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = + new translationserviceModule.v3beta1.TranslationServiceClient({ + universeDomain: 'configured.example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'translate.configured.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - - it('should create a client with no option', () => { - const client = new translationserviceModule.v3beta1.TranslationServiceClient(); - assert(client); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new translationserviceModule.v3beta1.TranslationServiceClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); + }); - it('should create a client with gRPC fallback', () => { - const client = new translationserviceModule.v3beta1.TranslationServiceClient({ - fallback: true, - }); - assert(client); - }); + it('has port', () => { + const port = + translationserviceModule.v3beta1.TranslationServiceClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('has initialize method and supports deferred initialization', async () => { - const client = new translationserviceModule.v3beta1.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.translationServiceStub, undefined); - await client.initialize(); - assert(client.translationServiceStub); - }); + it('should create a client with no option', () => { + const client = + new translationserviceModule.v3beta1.TranslationServiceClient(); + assert(client); + }); - it('has close method for the initialized client', done => { - const client = new translationserviceModule.v3beta1.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.translationServiceStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); + it('should create a client with gRPC fallback', () => { + const client = + new translationserviceModule.v3beta1.TranslationServiceClient({ + fallback: true, }); + assert(client); + }); - it('has close method for the non-initialized client', done => { - const client = new translationserviceModule.v3beta1.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.translationServiceStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); + it('has initialize method and supports deferred initialization', async () => { + const client = + new translationserviceModule.v3beta1.TranslationServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + assert.strictEqual(client.translationServiceStub, undefined); + await client.initialize(); + assert(client.translationServiceStub); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new translationserviceModule.v3beta1.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + it('has close method for the initialized client', (done) => { + const client = + new translationserviceModule.v3beta1.TranslationServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); - - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new translationserviceModule.v3beta1.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId((err?: Error|null, projectId?: string|null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } - }); - }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); + client.initialize().catch((err) => { + throw err; + }); + assert(client.translationServiceStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); }); - describe('translateText', () => { - it('invokes translateText without error', async () => { - const client = new translationserviceModule.v3beta1.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.translation.v3beta1.TranslateTextRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.translation.v3beta1.TranslateTextRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.translation.v3beta1.TranslateTextResponse() - ); - client.innerApiCalls.translateText = stubSimpleCall(expectedResponse); - const [response] = await client.translateText(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.translateText as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.translateText as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('has close method for the non-initialized client', (done) => { + const client = + new translationserviceModule.v3beta1.TranslationServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); - - it('invokes translateText without error using callback', async () => { - const client = new translationserviceModule.v3beta1.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.translation.v3beta1.TranslateTextRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.translation.v3beta1.TranslateTextRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.translation.v3beta1.TranslateTextResponse() - ); - client.innerApiCalls.translateText = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.translateText( - request, - (err?: Error|null, result?: protos.google.cloud.translation.v3beta1.ITranslateTextResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.translateText as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.translateText as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + assert.strictEqual(client.translationServiceStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes translateText with error', async () => { - const client = new translationserviceModule.v3beta1.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.translation.v3beta1.TranslateTextRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.translation.v3beta1.TranslateTextRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.translateText = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.translateText(request), expectedError); - const actualRequest = (client.innerApiCalls.translateText as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.translateText as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = + new translationserviceModule.v3beta1.TranslationServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + }); - it('invokes translateText with closed client', async () => { - const client = new translationserviceModule.v3beta1.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.translation.v3beta1.TranslateTextRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.translation.v3beta1.TranslateTextRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.translateText(request), expectedError); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = + new translationserviceModule.v3beta1.TranslationServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } + }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); }); - - describe('detectLanguage', () => { - it('invokes detectLanguage without error', async () => { - const client = new translationserviceModule.v3beta1.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.translation.v3beta1.DetectLanguageRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.translation.v3beta1.DetectLanguageRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.translation.v3beta1.DetectLanguageResponse() - ); - client.innerApiCalls.detectLanguage = stubSimpleCall(expectedResponse); - const [response] = await client.detectLanguage(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.detectLanguage as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.detectLanguage as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + describe('translateText', () => { + it('invokes translateText without error', async () => { + const client = + new translationserviceModule.v3beta1.TranslationServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.TranslateTextRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.translation.v3beta1.TranslateTextRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.TranslateTextResponse(), + ); + client.innerApiCalls.translateText = stubSimpleCall(expectedResponse); + const [response] = await client.translateText(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.translateText as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.translateText as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes detectLanguage without error using callback', async () => { - const client = new translationserviceModule.v3beta1.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.translation.v3beta1.DetectLanguageRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.translation.v3beta1.DetectLanguageRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.translation.v3beta1.DetectLanguageResponse() - ); - client.innerApiCalls.detectLanguage = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.detectLanguage( - request, - (err?: Error|null, result?: protos.google.cloud.translation.v3beta1.IDetectLanguageResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.detectLanguage as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.detectLanguage as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes translateText without error using callback', async () => { + const client = + new translationserviceModule.v3beta1.TranslationServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.TranslateTextRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.translation.v3beta1.TranslateTextRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.TranslateTextResponse(), + ); + client.innerApiCalls.translateText = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.translateText( + request, + ( + err?: Error | null, + result?: protos.google.cloud.translation.v3beta1.ITranslateTextResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.translateText as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.translateText as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes detectLanguage with error', async () => { - const client = new translationserviceModule.v3beta1.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.translation.v3beta1.DetectLanguageRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.translation.v3beta1.DetectLanguageRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.detectLanguage = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.detectLanguage(request), expectedError); - const actualRequest = (client.innerApiCalls.detectLanguage as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.detectLanguage as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes translateText with error', async () => { + const client = + new translationserviceModule.v3beta1.TranslationServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.TranslateTextRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.translation.v3beta1.TranslateTextRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.translateText = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.translateText(request), expectedError); + const actualRequest = ( + client.innerApiCalls.translateText as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.translateText as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes detectLanguage with closed client', async () => { - const client = new translationserviceModule.v3beta1.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.translation.v3beta1.DetectLanguageRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.translation.v3beta1.DetectLanguageRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.detectLanguage(request), expectedError); + it('invokes translateText with closed client', async () => { + const client = + new translationserviceModule.v3beta1.TranslationServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.TranslateTextRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.translation.v3beta1.TranslateTextRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.translateText(request), expectedError); }); - - describe('getSupportedLanguages', () => { - it('invokes getSupportedLanguages without error', async () => { - const client = new translationserviceModule.v3beta1.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.translation.v3beta1.GetSupportedLanguagesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.translation.v3beta1.GetSupportedLanguagesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.translation.v3beta1.SupportedLanguages() - ); - client.innerApiCalls.getSupportedLanguages = stubSimpleCall(expectedResponse); - const [response] = await client.getSupportedLanguages(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getSupportedLanguages as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getSupportedLanguages as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + describe('detectLanguage', () => { + it('invokes detectLanguage without error', async () => { + const client = + new translationserviceModule.v3beta1.TranslationServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.DetectLanguageRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.translation.v3beta1.DetectLanguageRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.DetectLanguageResponse(), + ); + client.innerApiCalls.detectLanguage = stubSimpleCall(expectedResponse); + const [response] = await client.detectLanguage(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.detectLanguage as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.detectLanguage as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getSupportedLanguages without error using callback', async () => { - const client = new translationserviceModule.v3beta1.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.translation.v3beta1.GetSupportedLanguagesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.translation.v3beta1.GetSupportedLanguagesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.translation.v3beta1.SupportedLanguages() - ); - client.innerApiCalls.getSupportedLanguages = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getSupportedLanguages( - request, - (err?: Error|null, result?: protos.google.cloud.translation.v3beta1.ISupportedLanguages|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getSupportedLanguages as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getSupportedLanguages as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes detectLanguage without error using callback', async () => { + const client = + new translationserviceModule.v3beta1.TranslationServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.DetectLanguageRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.translation.v3beta1.DetectLanguageRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.DetectLanguageResponse(), + ); + client.innerApiCalls.detectLanguage = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.detectLanguage( + request, + ( + err?: Error | null, + result?: protos.google.cloud.translation.v3beta1.IDetectLanguageResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.detectLanguage as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.detectLanguage as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getSupportedLanguages with error', async () => { - const client = new translationserviceModule.v3beta1.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.translation.v3beta1.GetSupportedLanguagesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.translation.v3beta1.GetSupportedLanguagesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getSupportedLanguages = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getSupportedLanguages(request), expectedError); - const actualRequest = (client.innerApiCalls.getSupportedLanguages as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getSupportedLanguages as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes detectLanguage with error', async () => { + const client = + new translationserviceModule.v3beta1.TranslationServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.DetectLanguageRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.translation.v3beta1.DetectLanguageRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.detectLanguage = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.detectLanguage(request), expectedError); + const actualRequest = ( + client.innerApiCalls.detectLanguage as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.detectLanguage as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getSupportedLanguages with closed client', async () => { - const client = new translationserviceModule.v3beta1.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.translation.v3beta1.GetSupportedLanguagesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.translation.v3beta1.GetSupportedLanguagesRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getSupportedLanguages(request), expectedError); + it('invokes detectLanguage with closed client', async () => { + const client = + new translationserviceModule.v3beta1.TranslationServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.DetectLanguageRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.translation.v3beta1.DetectLanguageRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.detectLanguage(request), expectedError); }); - - describe('getGlossary', () => { - it('invokes getGlossary without error', async () => { - const client = new translationserviceModule.v3beta1.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.translation.v3beta1.GetGlossaryRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.translation.v3beta1.GetGlossaryRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.translation.v3beta1.Glossary() - ); - client.innerApiCalls.getGlossary = stubSimpleCall(expectedResponse); - const [response] = await client.getGlossary(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getGlossary as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getGlossary as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + describe('getSupportedLanguages', () => { + it('invokes getSupportedLanguages without error', async () => { + const client = + new translationserviceModule.v3beta1.TranslationServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.GetSupportedLanguagesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.translation.v3beta1.GetSupportedLanguagesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.SupportedLanguages(), + ); + client.innerApiCalls.getSupportedLanguages = + stubSimpleCall(expectedResponse); + const [response] = await client.getSupportedLanguages(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getSupportedLanguages as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getSupportedLanguages as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getGlossary without error using callback', async () => { - const client = new translationserviceModule.v3beta1.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.translation.v3beta1.GetGlossaryRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.translation.v3beta1.GetGlossaryRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.translation.v3beta1.Glossary() - ); - client.innerApiCalls.getGlossary = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getGlossary( - request, - (err?: Error|null, result?: protos.google.cloud.translation.v3beta1.IGlossary|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getGlossary as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getGlossary as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes getSupportedLanguages without error using callback', async () => { + const client = + new translationserviceModule.v3beta1.TranslationServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.GetSupportedLanguagesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.translation.v3beta1.GetSupportedLanguagesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.SupportedLanguages(), + ); + client.innerApiCalls.getSupportedLanguages = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getSupportedLanguages( + request, + ( + err?: Error | null, + result?: protos.google.cloud.translation.v3beta1.ISupportedLanguages | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getSupportedLanguages as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getSupportedLanguages as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getGlossary with error', async () => { - const client = new translationserviceModule.v3beta1.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.translation.v3beta1.GetGlossaryRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.translation.v3beta1.GetGlossaryRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getGlossary = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getGlossary(request), expectedError); - const actualRequest = (client.innerApiCalls.getGlossary as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getGlossary as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes getSupportedLanguages with error', async () => { + const client = + new translationserviceModule.v3beta1.TranslationServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.GetSupportedLanguagesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.translation.v3beta1.GetSupportedLanguagesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getSupportedLanguages = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.getSupportedLanguages(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.getSupportedLanguages as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getSupportedLanguages as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getGlossary with closed client', async () => { - const client = new translationserviceModule.v3beta1.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.translation.v3beta1.GetGlossaryRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.translation.v3beta1.GetGlossaryRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getGlossary(request), expectedError); + it('invokes getSupportedLanguages with closed client', async () => { + const client = + new translationserviceModule.v3beta1.TranslationServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.GetSupportedLanguagesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.translation.v3beta1.GetSupportedLanguagesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.getSupportedLanguages(request), + expectedError, + ); }); - - describe('batchTranslateText', () => { - it('invokes batchTranslateText without error', async () => { - const client = new translationserviceModule.v3beta1.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.translation.v3beta1.BatchTranslateTextRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.translation.v3beta1.BatchTranslateTextRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.batchTranslateText = stubLongRunningCall(expectedResponse); - const [operation] = await client.batchTranslateText(request); - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.batchTranslateText as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.batchTranslateText as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + describe('getGlossary', () => { + it('invokes getGlossary without error', async () => { + const client = + new translationserviceModule.v3beta1.TranslationServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.GetGlossaryRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.translation.v3beta1.GetGlossaryRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.Glossary(), + ); + client.innerApiCalls.getGlossary = stubSimpleCall(expectedResponse); + const [response] = await client.getGlossary(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getGlossary as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getGlossary as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes batchTranslateText without error using callback', async () => { - const client = new translationserviceModule.v3beta1.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.translation.v3beta1.BatchTranslateTextRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.translation.v3beta1.BatchTranslateTextRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.batchTranslateText = stubLongRunningCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.batchTranslateText( - request, - (err?: Error|null, - result?: LROperation|null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const operation = await promise as LROperation; - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.batchTranslateText as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.batchTranslateText as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes getGlossary without error using callback', async () => { + const client = + new translationserviceModule.v3beta1.TranslationServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.GetGlossaryRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.translation.v3beta1.GetGlossaryRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.Glossary(), + ); + client.innerApiCalls.getGlossary = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getGlossary( + request, + ( + err?: Error | null, + result?: protos.google.cloud.translation.v3beta1.IGlossary | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getGlossary as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getGlossary as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes batchTranslateText with call error', async () => { - const client = new translationserviceModule.v3beta1.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.translation.v3beta1.BatchTranslateTextRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.translation.v3beta1.BatchTranslateTextRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.batchTranslateText = stubLongRunningCall(undefined, expectedError); - await assert.rejects(client.batchTranslateText(request), expectedError); - const actualRequest = (client.innerApiCalls.batchTranslateText as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.batchTranslateText as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes getGlossary with error', async () => { + const client = + new translationserviceModule.v3beta1.TranslationServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.GetGlossaryRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.translation.v3beta1.GetGlossaryRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getGlossary = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getGlossary(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getGlossary as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getGlossary as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes batchTranslateText with LRO error', async () => { - const client = new translationserviceModule.v3beta1.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.translation.v3beta1.BatchTranslateTextRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.translation.v3beta1.BatchTranslateTextRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.batchTranslateText = stubLongRunningCall(undefined, undefined, expectedError); - const [operation] = await client.batchTranslateText(request); - await assert.rejects(operation.promise(), expectedError); - const actualRequest = (client.innerApiCalls.batchTranslateText as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.batchTranslateText as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes getGlossary with closed client', async () => { + const client = + new translationserviceModule.v3beta1.TranslationServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); - - it('invokes checkBatchTranslateTextProgress without error', async () => { - const client = new translationserviceModule.v3beta1.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedResponse = generateSampleMessage( - new operationsProtos.google.longrunning.Operation() - ); - expectedResponse.name = 'test'; - expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; - expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')} - - client.operationsClient.getOperation = stubSimpleCall(expectedResponse); - const decodedOperation = await client.checkBatchTranslateTextProgress(expectedResponse.name); - assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); - assert(decodedOperation.metadata); - assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.GetGlossaryRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.translation.v3beta1.GetGlossaryRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getGlossary(request), expectedError); + }); + }); + + describe('batchTranslateText', () => { + it('invokes batchTranslateText without error', async () => { + const client = + new translationserviceModule.v3beta1.TranslationServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.BatchTranslateTextRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.translation.v3beta1.BatchTranslateTextRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.batchTranslateText = + stubLongRunningCall(expectedResponse); + const [operation] = await client.batchTranslateText(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.batchTranslateText as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.batchTranslateText as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkBatchTranslateTextProgress with error', async () => { - const client = new translationserviceModule.v3beta1.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedError = new Error('expected'); - - client.operationsClient.getOperation = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.checkBatchTranslateTextProgress(''), expectedError); - assert((client.operationsClient.getOperation as SinonStub) - .getCall(0)); + it('invokes batchTranslateText without error using callback', async () => { + const client = + new translationserviceModule.v3beta1.TranslationServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.BatchTranslateTextRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.translation.v3beta1.BatchTranslateTextRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.batchTranslateText = + stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.batchTranslateText( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.cloud.translation.v3beta1.IBatchTranslateResponse, + protos.google.cloud.translation.v3beta1.IBatchTranslateMetadata + > | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const operation = (await promise) as LROperation< + protos.google.cloud.translation.v3beta1.IBatchTranslateResponse, + protos.google.cloud.translation.v3beta1.IBatchTranslateMetadata + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.batchTranslateText as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.batchTranslateText as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('createGlossary', () => { - it('invokes createGlossary without error', async () => { - const client = new translationserviceModule.v3beta1.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.translation.v3beta1.CreateGlossaryRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.translation.v3beta1.CreateGlossaryRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.createGlossary = stubLongRunningCall(expectedResponse); - const [operation] = await client.createGlossary(request); - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createGlossary as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createGlossary as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes batchTranslateText with call error', async () => { + const client = + new translationserviceModule.v3beta1.TranslationServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.BatchTranslateTextRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.translation.v3beta1.BatchTranslateTextRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.batchTranslateText = stubLongRunningCall( + undefined, + expectedError, + ); + await assert.rejects(client.batchTranslateText(request), expectedError); + const actualRequest = ( + client.innerApiCalls.batchTranslateText as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.batchTranslateText as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createGlossary without error using callback', async () => { - const client = new translationserviceModule.v3beta1.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.translation.v3beta1.CreateGlossaryRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.translation.v3beta1.CreateGlossaryRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.createGlossary = stubLongRunningCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createGlossary( - request, - (err?: Error|null, - result?: LROperation|null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const operation = await promise as LROperation; - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createGlossary as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createGlossary as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes batchTranslateText with LRO error', async () => { + const client = + new translationserviceModule.v3beta1.TranslationServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.BatchTranslateTextRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.translation.v3beta1.BatchTranslateTextRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.batchTranslateText = stubLongRunningCall( + undefined, + undefined, + expectedError, + ); + const [operation] = await client.batchTranslateText(request); + await assert.rejects(operation.promise(), expectedError); + const actualRequest = ( + client.innerApiCalls.batchTranslateText as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.batchTranslateText as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createGlossary with call error', async () => { - const client = new translationserviceModule.v3beta1.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.translation.v3beta1.CreateGlossaryRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.translation.v3beta1.CreateGlossaryRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createGlossary = stubLongRunningCall(undefined, expectedError); - await assert.rejects(client.createGlossary(request), expectedError); - const actualRequest = (client.innerApiCalls.createGlossary as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createGlossary as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes checkBatchTranslateTextProgress without error', async () => { + const client = + new translationserviceModule.v3beta1.TranslationServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation(), + ); + expectedResponse.name = 'test'; + expectedResponse.response = { type_url: 'url', value: Buffer.from('') }; + expectedResponse.metadata = { type_url: 'url', value: Buffer.from('') }; + + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const decodedOperation = await client.checkBatchTranslateTextProgress( + expectedResponse.name, + ); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); - it('invokes createGlossary with LRO error', async () => { - const client = new translationserviceModule.v3beta1.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.translation.v3beta1.CreateGlossaryRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.translation.v3beta1.CreateGlossaryRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createGlossary = stubLongRunningCall(undefined, undefined, expectedError); - const [operation] = await client.createGlossary(request); - await assert.rejects(operation.promise(), expectedError); - const actualRequest = (client.innerApiCalls.createGlossary as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createGlossary as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes checkBatchTranslateTextProgress with error', async () => { + const client = + new translationserviceModule.v3beta1.TranslationServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); - - it('invokes checkCreateGlossaryProgress without error', async () => { - const client = new translationserviceModule.v3beta1.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedResponse = generateSampleMessage( - new operationsProtos.google.longrunning.Operation() - ); - expectedResponse.name = 'test'; - expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; - expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')} - - client.operationsClient.getOperation = stubSimpleCall(expectedResponse); - const decodedOperation = await client.checkCreateGlossaryProgress(expectedResponse.name); - assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); - assert(decodedOperation.metadata); - assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + await client.initialize(); + const expectedError = new Error('expected'); + + client.operationsClient.getOperation = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.checkBatchTranslateTextProgress(''), + expectedError, + ); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + }); + + describe('createGlossary', () => { + it('invokes createGlossary without error', async () => { + const client = + new translationserviceModule.v3beta1.TranslationServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.CreateGlossaryRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.translation.v3beta1.CreateGlossaryRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.createGlossary = + stubLongRunningCall(expectedResponse); + const [operation] = await client.createGlossary(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createGlossary as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createGlossary as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkCreateGlossaryProgress with error', async () => { - const client = new translationserviceModule.v3beta1.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedError = new Error('expected'); - - client.operationsClient.getOperation = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.checkCreateGlossaryProgress(''), expectedError); - assert((client.operationsClient.getOperation as SinonStub) - .getCall(0)); + it('invokes createGlossary without error using callback', async () => { + const client = + new translationserviceModule.v3beta1.TranslationServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.CreateGlossaryRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.translation.v3beta1.CreateGlossaryRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.createGlossary = + stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createGlossary( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.cloud.translation.v3beta1.IGlossary, + protos.google.cloud.translation.v3beta1.ICreateGlossaryMetadata + > | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const operation = (await promise) as LROperation< + protos.google.cloud.translation.v3beta1.IGlossary, + protos.google.cloud.translation.v3beta1.ICreateGlossaryMetadata + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createGlossary as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createGlossary as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('deleteGlossary', () => { - it('invokes deleteGlossary without error', async () => { - const client = new translationserviceModule.v3beta1.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.translation.v3beta1.DeleteGlossaryRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.translation.v3beta1.DeleteGlossaryRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.deleteGlossary = stubLongRunningCall(expectedResponse); - const [operation] = await client.deleteGlossary(request); - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteGlossary as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteGlossary as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes createGlossary with call error', async () => { + const client = + new translationserviceModule.v3beta1.TranslationServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.CreateGlossaryRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.translation.v3beta1.CreateGlossaryRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createGlossary = stubLongRunningCall( + undefined, + expectedError, + ); + await assert.rejects(client.createGlossary(request), expectedError); + const actualRequest = ( + client.innerApiCalls.createGlossary as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createGlossary as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteGlossary without error using callback', async () => { - const client = new translationserviceModule.v3beta1.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.translation.v3beta1.DeleteGlossaryRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.translation.v3beta1.DeleteGlossaryRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.deleteGlossary = stubLongRunningCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteGlossary( - request, - (err?: Error|null, - result?: LROperation|null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const operation = await promise as LROperation; - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteGlossary as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteGlossary as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes createGlossary with LRO error', async () => { + const client = + new translationserviceModule.v3beta1.TranslationServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.CreateGlossaryRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.translation.v3beta1.CreateGlossaryRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createGlossary = stubLongRunningCall( + undefined, + undefined, + expectedError, + ); + const [operation] = await client.createGlossary(request); + await assert.rejects(operation.promise(), expectedError); + const actualRequest = ( + client.innerApiCalls.createGlossary as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createGlossary as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteGlossary with call error', async () => { - const client = new translationserviceModule.v3beta1.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.translation.v3beta1.DeleteGlossaryRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.translation.v3beta1.DeleteGlossaryRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteGlossary = stubLongRunningCall(undefined, expectedError); - await assert.rejects(client.deleteGlossary(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteGlossary as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteGlossary as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes checkCreateGlossaryProgress without error', async () => { + const client = + new translationserviceModule.v3beta1.TranslationServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation(), + ); + expectedResponse.name = 'test'; + expectedResponse.response = { type_url: 'url', value: Buffer.from('') }; + expectedResponse.metadata = { type_url: 'url', value: Buffer.from('') }; + + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const decodedOperation = await client.checkCreateGlossaryProgress( + expectedResponse.name, + ); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); - it('invokes deleteGlossary with LRO error', async () => { - const client = new translationserviceModule.v3beta1.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.translation.v3beta1.DeleteGlossaryRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.translation.v3beta1.DeleteGlossaryRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteGlossary = stubLongRunningCall(undefined, undefined, expectedError); - const [operation] = await client.deleteGlossary(request); - await assert.rejects(operation.promise(), expectedError); - const actualRequest = (client.innerApiCalls.deleteGlossary as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteGlossary as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes checkCreateGlossaryProgress with error', async () => { + const client = + new translationserviceModule.v3beta1.TranslationServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); - - it('invokes checkDeleteGlossaryProgress without error', async () => { - const client = new translationserviceModule.v3beta1.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedResponse = generateSampleMessage( - new operationsProtos.google.longrunning.Operation() - ); - expectedResponse.name = 'test'; - expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; - expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')} - - client.operationsClient.getOperation = stubSimpleCall(expectedResponse); - const decodedOperation = await client.checkDeleteGlossaryProgress(expectedResponse.name); - assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); - assert(decodedOperation.metadata); - assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + await client.initialize(); + const expectedError = new Error('expected'); + + client.operationsClient.getOperation = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.checkCreateGlossaryProgress(''), + expectedError, + ); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + }); + + describe('deleteGlossary', () => { + it('invokes deleteGlossary without error', async () => { + const client = + new translationserviceModule.v3beta1.TranslationServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.DeleteGlossaryRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.translation.v3beta1.DeleteGlossaryRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.deleteGlossary = + stubLongRunningCall(expectedResponse); + const [operation] = await client.deleteGlossary(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteGlossary as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteGlossary as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkDeleteGlossaryProgress with error', async () => { - const client = new translationserviceModule.v3beta1.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedError = new Error('expected'); - - client.operationsClient.getOperation = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.checkDeleteGlossaryProgress(''), expectedError); - assert((client.operationsClient.getOperation as SinonStub) - .getCall(0)); + it('invokes deleteGlossary without error using callback', async () => { + const client = + new translationserviceModule.v3beta1.TranslationServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.DeleteGlossaryRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.translation.v3beta1.DeleteGlossaryRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.deleteGlossary = + stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteGlossary( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.cloud.translation.v3beta1.IDeleteGlossaryResponse, + protos.google.cloud.translation.v3beta1.IDeleteGlossaryMetadata + > | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const operation = (await promise) as LROperation< + protos.google.cloud.translation.v3beta1.IDeleteGlossaryResponse, + protos.google.cloud.translation.v3beta1.IDeleteGlossaryMetadata + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteGlossary as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteGlossary as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('listGlossaries', () => { - it('invokes listGlossaries without error', async () => { - const client = new translationserviceModule.v3beta1.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.translation.v3beta1.ListGlossariesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.translation.v3beta1.ListGlossariesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.translation.v3beta1.Glossary()), - generateSampleMessage(new protos.google.cloud.translation.v3beta1.Glossary()), - generateSampleMessage(new protos.google.cloud.translation.v3beta1.Glossary()), - ]; - client.innerApiCalls.listGlossaries = stubSimpleCall(expectedResponse); - const [response] = await client.listGlossaries(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listGlossaries as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listGlossaries as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes deleteGlossary with call error', async () => { + const client = + new translationserviceModule.v3beta1.TranslationServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.DeleteGlossaryRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.translation.v3beta1.DeleteGlossaryRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteGlossary = stubLongRunningCall( + undefined, + expectedError, + ); + await assert.rejects(client.deleteGlossary(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteGlossary as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteGlossary as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listGlossaries without error using callback', async () => { - const client = new translationserviceModule.v3beta1.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.translation.v3beta1.ListGlossariesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.translation.v3beta1.ListGlossariesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.translation.v3beta1.Glossary()), - generateSampleMessage(new protos.google.cloud.translation.v3beta1.Glossary()), - generateSampleMessage(new protos.google.cloud.translation.v3beta1.Glossary()), - ]; - client.innerApiCalls.listGlossaries = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listGlossaries( - request, - (err?: Error|null, result?: protos.google.cloud.translation.v3beta1.IGlossary[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listGlossaries as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listGlossaries as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes deleteGlossary with LRO error', async () => { + const client = + new translationserviceModule.v3beta1.TranslationServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.DeleteGlossaryRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.translation.v3beta1.DeleteGlossaryRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteGlossary = stubLongRunningCall( + undefined, + undefined, + expectedError, + ); + const [operation] = await client.deleteGlossary(request); + await assert.rejects(operation.promise(), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteGlossary as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteGlossary as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listGlossaries with error', async () => { - const client = new translationserviceModule.v3beta1.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.translation.v3beta1.ListGlossariesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.translation.v3beta1.ListGlossariesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listGlossaries = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listGlossaries(request), expectedError); - const actualRequest = (client.innerApiCalls.listGlossaries as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listGlossaries as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes checkDeleteGlossaryProgress without error', async () => { + const client = + new translationserviceModule.v3beta1.TranslationServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation(), + ); + expectedResponse.name = 'test'; + expectedResponse.response = { type_url: 'url', value: Buffer.from('') }; + expectedResponse.metadata = { type_url: 'url', value: Buffer.from('') }; + + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const decodedOperation = await client.checkDeleteGlossaryProgress( + expectedResponse.name, + ); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); - it('invokes listGlossariesStream without error', async () => { - const client = new translationserviceModule.v3beta1.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.translation.v3beta1.ListGlossariesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.translation.v3beta1.ListGlossariesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.translation.v3beta1.Glossary()), - generateSampleMessage(new protos.google.cloud.translation.v3beta1.Glossary()), - generateSampleMessage(new protos.google.cloud.translation.v3beta1.Glossary()), - ]; - client.descriptors.page.listGlossaries.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listGlossariesStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.cloud.translation.v3beta1.Glossary[] = []; - stream.on('data', (response: protos.google.cloud.translation.v3beta1.Glossary) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.listGlossaries.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listGlossaries, request)); - assert( - (client.descriptors.page.listGlossaries.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); + it('invokes checkDeleteGlossaryProgress with error', async () => { + const client = + new translationserviceModule.v3beta1.TranslationServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); - - it('invokes listGlossariesStream with error', async () => { - const client = new translationserviceModule.v3beta1.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.translation.v3beta1.ListGlossariesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.translation.v3beta1.ListGlossariesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listGlossaries.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listGlossariesStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.cloud.translation.v3beta1.Glossary[] = []; - stream.on('data', (response: protos.google.cloud.translation.v3beta1.Glossary) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listGlossaries.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listGlossaries, request)); - assert( - (client.descriptors.page.listGlossaries.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); + await client.initialize(); + const expectedError = new Error('expected'); + + client.operationsClient.getOperation = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.checkDeleteGlossaryProgress(''), + expectedError, + ); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + }); + + describe('listGlossaries', () => { + it('invokes listGlossaries without error', async () => { + const client = + new translationserviceModule.v3beta1.TranslationServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.ListGlossariesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.translation.v3beta1.ListGlossariesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.cloud.translation.v3beta1.Glossary(), + ), + generateSampleMessage( + new protos.google.cloud.translation.v3beta1.Glossary(), + ), + generateSampleMessage( + new protos.google.cloud.translation.v3beta1.Glossary(), + ), + ]; + client.innerApiCalls.listGlossaries = stubSimpleCall(expectedResponse); + const [response] = await client.listGlossaries(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listGlossaries as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listGlossaries as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('uses async iteration with listGlossaries without error', async () => { - const client = new translationserviceModule.v3beta1.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.translation.v3beta1.ListGlossariesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.translation.v3beta1.ListGlossariesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.translation.v3beta1.Glossary()), - generateSampleMessage(new protos.google.cloud.translation.v3beta1.Glossary()), - generateSampleMessage(new protos.google.cloud.translation.v3beta1.Glossary()), - ]; - client.descriptors.page.listGlossaries.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.cloud.translation.v3beta1.IGlossary[] = []; - const iterable = client.listGlossariesAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listGlossaries.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listGlossaries.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); + it('invokes listGlossaries without error using callback', async () => { + const client = + new translationserviceModule.v3beta1.TranslationServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.ListGlossariesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.translation.v3beta1.ListGlossariesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.cloud.translation.v3beta1.Glossary(), + ), + generateSampleMessage( + new protos.google.cloud.translation.v3beta1.Glossary(), + ), + generateSampleMessage( + new protos.google.cloud.translation.v3beta1.Glossary(), + ), + ]; + client.innerApiCalls.listGlossaries = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listGlossaries( + request, + ( + err?: Error | null, + result?: protos.google.cloud.translation.v3beta1.IGlossary[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listGlossaries as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listGlossaries as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('uses async iteration with listGlossaries with error', async () => { - const client = new translationserviceModule.v3beta1.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.translation.v3beta1.ListGlossariesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.translation.v3beta1.ListGlossariesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listGlossaries.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listGlossariesAsync(request); - await assert.rejects(async () => { - const responses: protos.google.cloud.translation.v3beta1.IGlossary[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listGlossaries.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listGlossaries.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); + it('invokes listGlossaries with error', async () => { + const client = + new translationserviceModule.v3beta1.TranslationServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.ListGlossariesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.translation.v3beta1.ListGlossariesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listGlossaries = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listGlossaries(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listGlossaries as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listGlossaries as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('Path templates', () => { - - describe('glossary', () => { - const fakePath = "/rendered/path/glossary"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - glossary: "glossaryValue", - }; - const client = new translationserviceModule.v3beta1.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.glossaryPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.glossaryPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('glossaryPath', () => { - const result = client.glossaryPath("projectValue", "locationValue", "glossaryValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.glossaryPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromGlossaryName', () => { - const result = client.matchProjectFromGlossaryName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.glossaryPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromGlossaryName', () => { - const result = client.matchLocationFromGlossaryName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.glossaryPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('invokes listGlossariesStream without error', async () => { + const client = + new translationserviceModule.v3beta1.TranslationServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.ListGlossariesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.translation.v3beta1.ListGlossariesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.cloud.translation.v3beta1.Glossary(), + ), + generateSampleMessage( + new protos.google.cloud.translation.v3beta1.Glossary(), + ), + generateSampleMessage( + new protos.google.cloud.translation.v3beta1.Glossary(), + ), + ]; + client.descriptors.page.listGlossaries.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listGlossariesStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.cloud.translation.v3beta1.Glossary[] = + []; + stream.on( + 'data', + (response: protos.google.cloud.translation.v3beta1.Glossary) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listGlossaries.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listGlossaries, request), + ); + assert( + (client.descriptors.page.listGlossaries.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('matchGlossaryFromGlossaryName', () => { - const result = client.matchGlossaryFromGlossaryName(fakePath); - assert.strictEqual(result, "glossaryValue"); - assert((client.pathTemplates.glossaryPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('invokes listGlossariesStream with error', async () => { + const client = + new translationserviceModule.v3beta1.TranslationServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.ListGlossariesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.translation.v3beta1.ListGlossariesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listGlossaries.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listGlossariesStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.cloud.translation.v3beta1.Glossary[] = + []; + stream.on( + 'data', + (response: protos.google.cloud.translation.v3beta1.Glossary) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listGlossaries.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listGlossaries, request), + ); + assert( + (client.descriptors.page.listGlossaries.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - describe('location', () => { - const fakePath = "/rendered/path/location"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - }; - const client = new translationserviceModule.v3beta1.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - client.pathTemplates.locationPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.locationPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('locationPath', () => { - const result = client.locationPath("projectValue", "locationValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.locationPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + it('uses async iteration with listGlossaries without error', async () => { + const client = + new translationserviceModule.v3beta1.TranslationServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.ListGlossariesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.translation.v3beta1.ListGlossariesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.cloud.translation.v3beta1.Glossary(), + ), + generateSampleMessage( + new protos.google.cloud.translation.v3beta1.Glossary(), + ), + generateSampleMessage( + new protos.google.cloud.translation.v3beta1.Glossary(), + ), + ]; + client.descriptors.page.listGlossaries.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.cloud.translation.v3beta1.IGlossary[] = []; + const iterable = client.listGlossariesAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listGlossaries.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listGlossaries.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('matchProjectFromLocationName', () => { - const result = client.matchProjectFromLocationName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.locationPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('uses async iteration with listGlossaries with error', async () => { + const client = + new translationserviceModule.v3beta1.TranslationServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.ListGlossariesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.translation.v3beta1.ListGlossariesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listGlossaries.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listGlossariesAsync(request); + await assert.rejects(async () => { + const responses: protos.google.cloud.translation.v3beta1.IGlossary[] = + []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listGlossaries.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listGlossaries.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + }); + + describe('Path templates', () => { + describe('glossary', () => { + const fakePath = '/rendered/path/glossary'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + glossary: 'glossaryValue', + }; + const client = + new translationserviceModule.v3beta1.TranslationServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.glossaryPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.glossaryPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('glossaryPath', () => { + const result = client.glossaryPath( + 'projectValue', + 'locationValue', + 'glossaryValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.glossaryPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromGlossaryName', () => { + const result = client.matchProjectFromGlossaryName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.glossaryPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromGlossaryName', () => { + const result = client.matchLocationFromGlossaryName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.glossaryPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchGlossaryFromGlossaryName', () => { + const result = client.matchGlossaryFromGlossaryName(fakePath); + assert.strictEqual(result, 'glossaryValue'); + assert( + (client.pathTemplates.glossaryPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchLocationFromLocationName', () => { - const result = client.matchLocationFromLocationName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.locationPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('location', () => { + const fakePath = '/rendered/path/location'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + }; + const client = + new translationserviceModule.v3beta1.TranslationServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + client.initialize().catch((err) => { + throw err; + }); + client.pathTemplates.locationPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.locationPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('locationPath', () => { + const result = client.locationPath('projectValue', 'locationValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.locationPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromLocationName', () => { + const result = client.matchProjectFromLocationName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.locationPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromLocationName', () => { + const result = client.matchLocationFromLocationName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.locationPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/core/generator/gapic-generator-typescript/baselines/translate/src/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/translate/src/index.ts.baseline index 85f2bdbd874b..9f25e07610c5 100644 --- a/core/generator/gapic-generator-typescript/baselines/translate/src/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/translate/src/index.ts.baseline @@ -19,7 +19,7 @@ import * as v3beta1 from './v3beta1'; const TranslationServiceClient = v3beta1.TranslationServiceClient; type TranslationServiceClient = v3beta1.TranslationServiceClient; -export {v3beta1, TranslationServiceClient}; -export default {v3beta1, TranslationServiceClient}; +export { v3beta1, TranslationServiceClient }; +export default { v3beta1, TranslationServiceClient }; import * as protos from '../protos/protos'; -export {protos} +export { protos }; diff --git a/core/generator/gapic-generator-typescript/baselines/translate/src/v3beta1/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/translate/src/v3beta1/index.ts.baseline index f4c9d9326e98..568ad488b3da 100644 --- a/core/generator/gapic-generator-typescript/baselines/translate/src/v3beta1/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/translate/src/v3beta1/index.ts.baseline @@ -16,4 +16,4 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -export {TranslationServiceClient} from './translation_service_client'; +export { TranslationServiceClient } from './translation_service_client'; diff --git a/core/generator/gapic-generator-typescript/baselines/translate/src/v3beta1/translation_service_client.ts.baseline b/core/generator/gapic-generator-typescript/baselines/translate/src/v3beta1/translation_service_client.ts.baseline index e8f0779587f1..7a18357d417b 100644 --- a/core/generator/gapic-generator-typescript/baselines/translate/src/v3beta1/translation_service_client.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/translate/src/v3beta1/translation_service_client.ts.baseline @@ -18,11 +18,20 @@ /* global window */ import type * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions, GrpcClientOptions, LROperation, PaginationCallback, GaxCall} from 'google-gax'; -import {Transform} from 'stream'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + GrpcClientOptions, + LROperation, + PaginationCallback, + GaxCall, +} from 'google-gax'; +import { Transform } from 'stream'; import * as protos from '../../protos/protos'; import jsonProtos = require('../../protos/protos.json'); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; /** * Client JSON configuration object, loaded from @@ -44,7 +53,7 @@ export class TranslationServiceClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('translation'); @@ -57,10 +66,10 @@ export class TranslationServiceClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; operationsClient: gax.OperationsClient; - translationServiceStub?: Promise<{[name: string]: Function}>; + translationServiceStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of TranslationServiceClient. @@ -101,21 +110,42 @@ export class TranslationServiceClient { * const client = new TranslationServiceClient({fallback: true}, gax); * ``` */ - constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { // Ensure that options include all the required fields. const staticMembers = this.constructor as typeof TranslationServiceClient; - if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { - throw new Error('Please set either universe_domain or universeDomain, but not both.'); + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); } - const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; - this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; this._servicePath = 'translate.' + this._universeDomain; - const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; - const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. if (servicePath !== this._servicePath && !('scopes' in opts)) { @@ -137,7 +167,7 @@ export class TranslationServiceClient { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; @@ -151,10 +181,7 @@ export class TranslationServiceClient { } // Determine the client header string. - const clientHeader = [ - `gax/${this._gaxModule.version}`, - `gapic/${version}`, - ]; + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/${process.versions.node}`); } else { @@ -176,10 +203,10 @@ export class TranslationServiceClient { // Create useful helper objects for these. this.pathTemplates = { glossaryPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/glossaries/{glossary}' + 'projects/{project}/locations/{location}/glossaries/{glossary}', ), locationPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}' + 'projects/{project}/locations/{location}', ), }; @@ -187,8 +214,11 @@ export class TranslationServiceClient { // (e.g. 50 results at a time, with tokens to get subsequent // pages). Denote the keys used for pagination and results. this.descriptors.page = { - listGlossaries: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'glossaries') + listGlossaries: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'glossaries', + ), }; const protoFilesRoot = this._gaxModule.protobufFromJSON(jsonProtos); @@ -197,45 +227,59 @@ export class TranslationServiceClient { // rather than holding a request open. const lroOptions: GrpcClientOptions = { auth: this.auth, - grpc: 'grpc' in this._gaxGrpc ? this._gaxGrpc.grpc : undefined + grpc: 'grpc' in this._gaxGrpc ? this._gaxGrpc.grpc : undefined, }; if (opts.fallback) { lroOptions.protoJson = protoFilesRoot; lroOptions.httpRules = []; } - this.operationsClient = this._gaxModule.lro(lroOptions).operationsClient(opts); + this.operationsClient = this._gaxModule + .lro(lroOptions) + .operationsClient(opts); const batchTranslateTextResponse = protoFilesRoot.lookup( - '.google.cloud.translation.v3beta1.BatchTranslateResponse') as gax.protobuf.Type; + '.google.cloud.translation.v3beta1.BatchTranslateResponse', + ) as gax.protobuf.Type; const batchTranslateTextMetadata = protoFilesRoot.lookup( - '.google.cloud.translation.v3beta1.BatchTranslateMetadata') as gax.protobuf.Type; + '.google.cloud.translation.v3beta1.BatchTranslateMetadata', + ) as gax.protobuf.Type; const createGlossaryResponse = protoFilesRoot.lookup( - '.google.cloud.translation.v3beta1.Glossary') as gax.protobuf.Type; + '.google.cloud.translation.v3beta1.Glossary', + ) as gax.protobuf.Type; const createGlossaryMetadata = protoFilesRoot.lookup( - '.google.cloud.translation.v3beta1.CreateGlossaryMetadata') as gax.protobuf.Type; + '.google.cloud.translation.v3beta1.CreateGlossaryMetadata', + ) as gax.protobuf.Type; const deleteGlossaryResponse = protoFilesRoot.lookup( - '.google.cloud.translation.v3beta1.DeleteGlossaryResponse') as gax.protobuf.Type; + '.google.cloud.translation.v3beta1.DeleteGlossaryResponse', + ) as gax.protobuf.Type; const deleteGlossaryMetadata = protoFilesRoot.lookup( - '.google.cloud.translation.v3beta1.DeleteGlossaryMetadata') as gax.protobuf.Type; + '.google.cloud.translation.v3beta1.DeleteGlossaryMetadata', + ) as gax.protobuf.Type; this.descriptors.longrunning = { batchTranslateText: new this._gaxModule.LongrunningDescriptor( this.operationsClient, batchTranslateTextResponse.decode.bind(batchTranslateTextResponse), - batchTranslateTextMetadata.decode.bind(batchTranslateTextMetadata)), + batchTranslateTextMetadata.decode.bind(batchTranslateTextMetadata), + ), createGlossary: new this._gaxModule.LongrunningDescriptor( this.operationsClient, createGlossaryResponse.decode.bind(createGlossaryResponse), - createGlossaryMetadata.decode.bind(createGlossaryMetadata)), + createGlossaryMetadata.decode.bind(createGlossaryMetadata), + ), deleteGlossary: new this._gaxModule.LongrunningDescriptor( this.operationsClient, deleteGlossaryResponse.decode.bind(deleteGlossaryResponse), - deleteGlossaryMetadata.decode.bind(deleteGlossaryMetadata)) + deleteGlossaryMetadata.decode.bind(deleteGlossaryMetadata), + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.cloud.translation.v3beta1.TranslationService', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.cloud.translation.v3beta1.TranslationService', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + { 'x-goog-api-client': clientHeader.join(' ') }, + ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -266,28 +310,43 @@ export class TranslationServiceClient { // Put together the "service stub" for // google.cloud.translation.v3beta1.TranslationService. this.translationServiceStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.cloud.translation.v3beta1.TranslationService') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any - (this._protos as any).google.cloud.translation.v3beta1.TranslationService, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.cloud.translation.v3beta1.TranslationService', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any + (this._protos as any).google.cloud.translation.v3beta1 + .TranslationService, + this._opts, + this._providedCustomServicePath, + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const translationServiceStubMethods = - ['translateText', 'detectLanguage', 'getSupportedLanguages', 'batchTranslateText', 'createGlossary', 'listGlossaries', 'getGlossary', 'deleteGlossary']; + const translationServiceStubMethods = [ + 'translateText', + 'detectLanguage', + 'getSupportedLanguages', + 'batchTranslateText', + 'createGlossary', + 'listGlossaries', + 'getGlossary', + 'deleteGlossary', + ]; for (const methodName of translationServiceStubMethods) { const callPromise = this.translationServiceStub.then( - stub => (...args: Array<{}>) => { - if (this._terminated) { - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error|null|undefined) => () => { + (stub) => + (...args: Array<{}>) => { + if (this._terminated) { + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { throw err; - }); + }, + ); const descriptor = this.descriptors.page[methodName] || @@ -297,7 +356,7 @@ export class TranslationServiceClient { callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -312,8 +371,14 @@ export class TranslationServiceClient { * @returns {string} The DNS address for this service. */ static get servicePath() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'translate.googleapis.com'; } @@ -324,8 +389,14 @@ export class TranslationServiceClient { * @returns {string} The DNS address for this service. */ static get apiEndpoint() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'translate.googleapis.com'; } @@ -358,7 +429,7 @@ export class TranslationServiceClient { static get scopes() { return [ 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloud-translation' + 'https://www.googleapis.com/auth/cloud-translation', ]; } @@ -368,8 +439,9 @@ export class TranslationServiceClient { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId(callback?: Callback): - Promise|void { + getProjectId( + callback?: Callback, + ): Promise | void { if (callback) { this.auth.getProjectId(callback); return; @@ -380,981 +452,1376 @@ export class TranslationServiceClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Translates input text and returns translated text. - * - * @param {Object} request - * The request object that will be sent. - * @param {string[]} request.contents - * Required. The content of the input in string format. - * We recommend the total content be less than 30k codepoints. - * Use BatchTranslateText for larger text. - * @param {string} [request.mimeType] - * Optional. The format of the source text, for example, "text/html", - * "text/plain". If left blank, the MIME type defaults to "text/html". - * @param {string} [request.sourceLanguageCode] - * Optional. The BCP-47 language code of the input text if - * known, for example, "en-US" or "sr-Latn". Supported language codes are - * listed in Language Support. If the source language isn't specified, the API - * attempts to identify the source language automatically and returns the - * source language within the response. - * @param {string} request.targetLanguageCode - * Required. The BCP-47 language code to use for translation of the input - * text, set to one of the language codes listed in Language Support. - * @param {string} request.parent - * Required. Project or location to make a call. Must refer to a caller's - * project. - * - * Format: `projects/{project-id}` or - * `projects/{project-id}/locations/{location-id}`. - * - * For global calls, use `projects/{project-id}/locations/global` or - * `projects/{project-id}`. - * - * Non-global location is required for requests using AutoML models or - * custom glossaries. - * - * Models and glossaries must be within the same region (have same - * location-id), otherwise an INVALID_ARGUMENT (400) error is returned. - * @param {string} [request.model] - * Optional. The `model` type requested for this translation. - * - * The format depends on model type: - * - * - AutoML Translation models: - * `projects/{project-id}/locations/{location-id}/models/{model-id}` - * - * - General (built-in) models: - * `projects/{project-id}/locations/{location-id}/models/general/nmt`, - * `projects/{project-id}/locations/{location-id}/models/general/base` - * - * - * For global (non-regionalized) requests, use `location-id` `global`. - * For example, - * `projects/{project-id}/locations/global/models/general/nmt`. - * - * If missing, the system decides which google base model to use. - * @param {google.cloud.translation.v3beta1.TranslateTextGlossaryConfig} [request.glossaryConfig] - * Optional. Glossary to be applied. The glossary must be - * within the same region (have the same location-id) as the model, otherwise - * an INVALID_ARGUMENT (400) error is returned. - * @param {number[]} [request.labels] - * Optional. The labels with user-defined metadata for the request. - * - * Label keys and values can be no longer than 63 characters - * (Unicode codepoints), can only contain lowercase letters, numeric - * characters, underscores and dashes. International characters are allowed. - * Label values are optional. Label keys must start with a letter. - * - * See https://cloud.google.com/translate/docs/labels for more information. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.translation.v3beta1.TranslateTextResponse|TranslateTextResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v3beta1/translation_service.translate_text.js - * region_tag:translate_v3beta1_generated_TranslationService_TranslateText_async - */ + /** + * Translates input text and returns translated text. + * + * @param {Object} request + * The request object that will be sent. + * @param {string[]} request.contents + * Required. The content of the input in string format. + * We recommend the total content be less than 30k codepoints. + * Use BatchTranslateText for larger text. + * @param {string} [request.mimeType] + * Optional. The format of the source text, for example, "text/html", + * "text/plain". If left blank, the MIME type defaults to "text/html". + * @param {string} [request.sourceLanguageCode] + * Optional. The BCP-47 language code of the input text if + * known, for example, "en-US" or "sr-Latn". Supported language codes are + * listed in Language Support. If the source language isn't specified, the API + * attempts to identify the source language automatically and returns the + * source language within the response. + * @param {string} request.targetLanguageCode + * Required. The BCP-47 language code to use for translation of the input + * text, set to one of the language codes listed in Language Support. + * @param {string} request.parent + * Required. Project or location to make a call. Must refer to a caller's + * project. + * + * Format: `projects/{project-id}` or + * `projects/{project-id}/locations/{location-id}`. + * + * For global calls, use `projects/{project-id}/locations/global` or + * `projects/{project-id}`. + * + * Non-global location is required for requests using AutoML models or + * custom glossaries. + * + * Models and glossaries must be within the same region (have same + * location-id), otherwise an INVALID_ARGUMENT (400) error is returned. + * @param {string} [request.model] + * Optional. The `model` type requested for this translation. + * + * The format depends on model type: + * + * - AutoML Translation models: + * `projects/{project-id}/locations/{location-id}/models/{model-id}` + * + * - General (built-in) models: + * `projects/{project-id}/locations/{location-id}/models/general/nmt`, + * `projects/{project-id}/locations/{location-id}/models/general/base` + * + * + * For global (non-regionalized) requests, use `location-id` `global`. + * For example, + * `projects/{project-id}/locations/global/models/general/nmt`. + * + * If missing, the system decides which google base model to use. + * @param {google.cloud.translation.v3beta1.TranslateTextGlossaryConfig} [request.glossaryConfig] + * Optional. Glossary to be applied. The glossary must be + * within the same region (have the same location-id) as the model, otherwise + * an INVALID_ARGUMENT (400) error is returned. + * @param {number[]} [request.labels] + * Optional. The labels with user-defined metadata for the request. + * + * Label keys and values can be no longer than 63 characters + * (Unicode codepoints), can only contain lowercase letters, numeric + * characters, underscores and dashes. International characters are allowed. + * Label values are optional. Label keys must start with a letter. + * + * See https://cloud.google.com/translate/docs/labels for more information. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.translation.v3beta1.TranslateTextResponse|TranslateTextResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v3beta1/translation_service.translate_text.js + * region_tag:translate_v3beta1_generated_TranslationService_TranslateText_async + */ translateText( - request?: protos.google.cloud.translation.v3beta1.ITranslateTextRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.translation.v3beta1.ITranslateTextResponse, - protos.google.cloud.translation.v3beta1.ITranslateTextRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.translation.v3beta1.ITranslateTextRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.translation.v3beta1.ITranslateTextResponse, + protos.google.cloud.translation.v3beta1.ITranslateTextRequest | undefined, + {} | undefined, + ] + >; translateText( - request: protos.google.cloud.translation.v3beta1.ITranslateTextRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.translation.v3beta1.ITranslateTextResponse, - protos.google.cloud.translation.v3beta1.ITranslateTextRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.translation.v3beta1.ITranslateTextRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.translation.v3beta1.ITranslateTextResponse, + | protos.google.cloud.translation.v3beta1.ITranslateTextRequest + | null + | undefined, + {} | null | undefined + >, + ): void; translateText( - request: protos.google.cloud.translation.v3beta1.ITranslateTextRequest, - callback: Callback< - protos.google.cloud.translation.v3beta1.ITranslateTextResponse, - protos.google.cloud.translation.v3beta1.ITranslateTextRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.translation.v3beta1.ITranslateTextRequest, + callback: Callback< + protos.google.cloud.translation.v3beta1.ITranslateTextResponse, + | protos.google.cloud.translation.v3beta1.ITranslateTextRequest + | null + | undefined, + {} | null | undefined + >, + ): void; translateText( - request?: protos.google.cloud.translation.v3beta1.ITranslateTextRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.translation.v3beta1.ITranslateTextResponse, - protos.google.cloud.translation.v3beta1.ITranslateTextRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.translation.v3beta1.ITranslateTextRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.translation.v3beta1.ITranslateTextResponse, - protos.google.cloud.translation.v3beta1.ITranslateTextRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.translation.v3beta1.ITranslateTextResponse, - protos.google.cloud.translation.v3beta1.ITranslateTextRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.translation.v3beta1.ITranslateTextRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.translation.v3beta1.ITranslateTextResponse, + | protos.google.cloud.translation.v3beta1.ITranslateTextRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.translation.v3beta1.ITranslateTextResponse, + protos.google.cloud.translation.v3beta1.ITranslateTextRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('translateText request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.translation.v3beta1.ITranslateTextResponse, - protos.google.cloud.translation.v3beta1.ITranslateTextRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.translation.v3beta1.ITranslateTextResponse, + | protos.google.cloud.translation.v3beta1.ITranslateTextRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('translateText response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.translateText(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.translation.v3beta1.ITranslateTextResponse, - protos.google.cloud.translation.v3beta1.ITranslateTextRequest|undefined, - {}|undefined - ]) => { - this._log.info('translateText response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .translateText(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.translation.v3beta1.ITranslateTextResponse, + ( + | protos.google.cloud.translation.v3beta1.ITranslateTextRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('translateText response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Detects the language of text within a request. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. Project or location to make a call. Must refer to a caller's - * project. - * - * Format: `projects/{project-id}/locations/{location-id}` or - * `projects/{project-id}`. - * - * For global calls, use `projects/{project-id}/locations/global` or - * `projects/{project-id}`. - * - * Only models within the same region (has same location-id) can be used. - * Otherwise an INVALID_ARGUMENT (400) error is returned. - * @param {string} [request.model] - * Optional. The language detection model to be used. - * - * Format: - * `projects/{project-id}/locations/{location-id}/models/language-detection/{model-id}` - * - * Only one language detection model is currently supported: - * `projects/{project-id}/locations/{location-id}/models/language-detection/default`. - * - * If not specified, the default model is used. - * @param {string} request.content - * The content of the input stored as a string. - * @param {string} [request.mimeType] - * Optional. The format of the source text, for example, "text/html", - * "text/plain". If left blank, the MIME type defaults to "text/html". - * @param {number[]} request.labels - * Optional. The labels with user-defined metadata for the request. - * - * Label keys and values can be no longer than 63 characters - * (Unicode codepoints), can only contain lowercase letters, numeric - * characters, underscores and dashes. International characters are allowed. - * Label values are optional. Label keys must start with a letter. - * - * See https://cloud.google.com/translate/docs/labels for more information. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.translation.v3beta1.DetectLanguageResponse|DetectLanguageResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v3beta1/translation_service.detect_language.js - * region_tag:translate_v3beta1_generated_TranslationService_DetectLanguage_async - */ + /** + * Detects the language of text within a request. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Project or location to make a call. Must refer to a caller's + * project. + * + * Format: `projects/{project-id}/locations/{location-id}` or + * `projects/{project-id}`. + * + * For global calls, use `projects/{project-id}/locations/global` or + * `projects/{project-id}`. + * + * Only models within the same region (has same location-id) can be used. + * Otherwise an INVALID_ARGUMENT (400) error is returned. + * @param {string} [request.model] + * Optional. The language detection model to be used. + * + * Format: + * `projects/{project-id}/locations/{location-id}/models/language-detection/{model-id}` + * + * Only one language detection model is currently supported: + * `projects/{project-id}/locations/{location-id}/models/language-detection/default`. + * + * If not specified, the default model is used. + * @param {string} request.content + * The content of the input stored as a string. + * @param {string} [request.mimeType] + * Optional. The format of the source text, for example, "text/html", + * "text/plain". If left blank, the MIME type defaults to "text/html". + * @param {number[]} request.labels + * Optional. The labels with user-defined metadata for the request. + * + * Label keys and values can be no longer than 63 characters + * (Unicode codepoints), can only contain lowercase letters, numeric + * characters, underscores and dashes. International characters are allowed. + * Label values are optional. Label keys must start with a letter. + * + * See https://cloud.google.com/translate/docs/labels for more information. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.translation.v3beta1.DetectLanguageResponse|DetectLanguageResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v3beta1/translation_service.detect_language.js + * region_tag:translate_v3beta1_generated_TranslationService_DetectLanguage_async + */ detectLanguage( - request?: protos.google.cloud.translation.v3beta1.IDetectLanguageRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.translation.v3beta1.IDetectLanguageResponse, - protos.google.cloud.translation.v3beta1.IDetectLanguageRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.translation.v3beta1.IDetectLanguageRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.translation.v3beta1.IDetectLanguageResponse, + ( + | protos.google.cloud.translation.v3beta1.IDetectLanguageRequest + | undefined + ), + {} | undefined, + ] + >; detectLanguage( - request: protos.google.cloud.translation.v3beta1.IDetectLanguageRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.translation.v3beta1.IDetectLanguageResponse, - protos.google.cloud.translation.v3beta1.IDetectLanguageRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.translation.v3beta1.IDetectLanguageRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.translation.v3beta1.IDetectLanguageResponse, + | protos.google.cloud.translation.v3beta1.IDetectLanguageRequest + | null + | undefined, + {} | null | undefined + >, + ): void; detectLanguage( - request: protos.google.cloud.translation.v3beta1.IDetectLanguageRequest, - callback: Callback< - protos.google.cloud.translation.v3beta1.IDetectLanguageResponse, - protos.google.cloud.translation.v3beta1.IDetectLanguageRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.translation.v3beta1.IDetectLanguageRequest, + callback: Callback< + protos.google.cloud.translation.v3beta1.IDetectLanguageResponse, + | protos.google.cloud.translation.v3beta1.IDetectLanguageRequest + | null + | undefined, + {} | null | undefined + >, + ): void; detectLanguage( - request?: protos.google.cloud.translation.v3beta1.IDetectLanguageRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.cloud.translation.v3beta1.IDetectLanguageRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.translation.v3beta1.IDetectLanguageResponse, - protos.google.cloud.translation.v3beta1.IDetectLanguageRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.cloud.translation.v3beta1.IDetectLanguageResponse, - protos.google.cloud.translation.v3beta1.IDetectLanguageRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.translation.v3beta1.IDetectLanguageResponse, - protos.google.cloud.translation.v3beta1.IDetectLanguageRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.translation.v3beta1.IDetectLanguageRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.translation.v3beta1.IDetectLanguageResponse, + | protos.google.cloud.translation.v3beta1.IDetectLanguageRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.translation.v3beta1.IDetectLanguageResponse, + ( + | protos.google.cloud.translation.v3beta1.IDetectLanguageRequest + | undefined + ), + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('detectLanguage request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.translation.v3beta1.IDetectLanguageResponse, - protos.google.cloud.translation.v3beta1.IDetectLanguageRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.translation.v3beta1.IDetectLanguageResponse, + | protos.google.cloud.translation.v3beta1.IDetectLanguageRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('detectLanguage response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.detectLanguage(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.translation.v3beta1.IDetectLanguageResponse, - protos.google.cloud.translation.v3beta1.IDetectLanguageRequest|undefined, - {}|undefined - ]) => { - this._log.info('detectLanguage response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .detectLanguage(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.translation.v3beta1.IDetectLanguageResponse, + ( + | protos.google.cloud.translation.v3beta1.IDetectLanguageRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('detectLanguage response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Returns a list of supported languages for translation. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. Project or location to make a call. Must refer to a caller's - * project. - * - * Format: `projects/{project-id}` or - * `projects/{project-id}/locations/{location-id}`. - * - * For global calls, use `projects/{project-id}/locations/global` or - * `projects/{project-id}`. - * - * Non-global location is required for AutoML models. - * - * Only models within the same region (have same location-id) can be used, - * otherwise an INVALID_ARGUMENT (400) error is returned. - * @param {string} [request.displayLanguageCode] - * Optional. The language to use to return localized, human readable names - * of supported languages. If missing, then display names are not returned - * in a response. - * @param {string} [request.model] - * Optional. Get supported languages of this model. - * - * The format depends on model type: - * - * - AutoML Translation models: - * `projects/{project-id}/locations/{location-id}/models/{model-id}` - * - * - General (built-in) models: - * `projects/{project-id}/locations/{location-id}/models/general/nmt`, - * `projects/{project-id}/locations/{location-id}/models/general/base` - * - * - * Returns languages supported by the specified model. - * If missing, we get supported languages of Google general base (PBMT) model. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.translation.v3beta1.SupportedLanguages|SupportedLanguages}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v3beta1/translation_service.get_supported_languages.js - * region_tag:translate_v3beta1_generated_TranslationService_GetSupportedLanguages_async - */ + /** + * Returns a list of supported languages for translation. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Project or location to make a call. Must refer to a caller's + * project. + * + * Format: `projects/{project-id}` or + * `projects/{project-id}/locations/{location-id}`. + * + * For global calls, use `projects/{project-id}/locations/global` or + * `projects/{project-id}`. + * + * Non-global location is required for AutoML models. + * + * Only models within the same region (have same location-id) can be used, + * otherwise an INVALID_ARGUMENT (400) error is returned. + * @param {string} [request.displayLanguageCode] + * Optional. The language to use to return localized, human readable names + * of supported languages. If missing, then display names are not returned + * in a response. + * @param {string} [request.model] + * Optional. Get supported languages of this model. + * + * The format depends on model type: + * + * - AutoML Translation models: + * `projects/{project-id}/locations/{location-id}/models/{model-id}` + * + * - General (built-in) models: + * `projects/{project-id}/locations/{location-id}/models/general/nmt`, + * `projects/{project-id}/locations/{location-id}/models/general/base` + * + * + * Returns languages supported by the specified model. + * If missing, we get supported languages of Google general base (PBMT) model. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.translation.v3beta1.SupportedLanguages|SupportedLanguages}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v3beta1/translation_service.get_supported_languages.js + * region_tag:translate_v3beta1_generated_TranslationService_GetSupportedLanguages_async + */ getSupportedLanguages( - request?: protos.google.cloud.translation.v3beta1.IGetSupportedLanguagesRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.translation.v3beta1.ISupportedLanguages, - protos.google.cloud.translation.v3beta1.IGetSupportedLanguagesRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.translation.v3beta1.IGetSupportedLanguagesRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.translation.v3beta1.ISupportedLanguages, + ( + | protos.google.cloud.translation.v3beta1.IGetSupportedLanguagesRequest + | undefined + ), + {} | undefined, + ] + >; getSupportedLanguages( - request: protos.google.cloud.translation.v3beta1.IGetSupportedLanguagesRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.translation.v3beta1.ISupportedLanguages, - protos.google.cloud.translation.v3beta1.IGetSupportedLanguagesRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.translation.v3beta1.IGetSupportedLanguagesRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.translation.v3beta1.ISupportedLanguages, + | protos.google.cloud.translation.v3beta1.IGetSupportedLanguagesRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getSupportedLanguages( - request: protos.google.cloud.translation.v3beta1.IGetSupportedLanguagesRequest, - callback: Callback< - protos.google.cloud.translation.v3beta1.ISupportedLanguages, - protos.google.cloud.translation.v3beta1.IGetSupportedLanguagesRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.translation.v3beta1.IGetSupportedLanguagesRequest, + callback: Callback< + protos.google.cloud.translation.v3beta1.ISupportedLanguages, + | protos.google.cloud.translation.v3beta1.IGetSupportedLanguagesRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getSupportedLanguages( - request?: protos.google.cloud.translation.v3beta1.IGetSupportedLanguagesRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.translation.v3beta1.ISupportedLanguages, - protos.google.cloud.translation.v3beta1.IGetSupportedLanguagesRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.translation.v3beta1.IGetSupportedLanguagesRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.translation.v3beta1.ISupportedLanguages, - protos.google.cloud.translation.v3beta1.IGetSupportedLanguagesRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.translation.v3beta1.ISupportedLanguages, - protos.google.cloud.translation.v3beta1.IGetSupportedLanguagesRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.translation.v3beta1.IGetSupportedLanguagesRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.translation.v3beta1.ISupportedLanguages, + | protos.google.cloud.translation.v3beta1.IGetSupportedLanguagesRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.translation.v3beta1.ISupportedLanguages, + ( + | protos.google.cloud.translation.v3beta1.IGetSupportedLanguagesRequest + | undefined + ), + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getSupportedLanguages request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.translation.v3beta1.ISupportedLanguages, - protos.google.cloud.translation.v3beta1.IGetSupportedLanguagesRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.translation.v3beta1.ISupportedLanguages, + | protos.google.cloud.translation.v3beta1.IGetSupportedLanguagesRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getSupportedLanguages response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getSupportedLanguages(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.translation.v3beta1.ISupportedLanguages, - protos.google.cloud.translation.v3beta1.IGetSupportedLanguagesRequest|undefined, - {}|undefined - ]) => { - this._log.info('getSupportedLanguages response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getSupportedLanguages(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.translation.v3beta1.ISupportedLanguages, + ( + | protos.google.cloud.translation.v3beta1.IGetSupportedLanguagesRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('getSupportedLanguages response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Gets a glossary. Returns NOT_FOUND, if the glossary doesn't - * exist. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The name of the glossary to retrieve. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.cloud.translation.v3beta1.Glossary|Glossary}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example include:samples/generated/v3beta1/translation_service.get_glossary.js - * region_tag:translate_v3beta1_generated_TranslationService_GetGlossary_async - */ + /** + * Gets a glossary. Returns NOT_FOUND, if the glossary doesn't + * exist. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The name of the glossary to retrieve. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.cloud.translation.v3beta1.Glossary|Glossary}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v3beta1/translation_service.get_glossary.js + * region_tag:translate_v3beta1_generated_TranslationService_GetGlossary_async + */ getGlossary( - request?: protos.google.cloud.translation.v3beta1.IGetGlossaryRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.translation.v3beta1.IGlossary, - protos.google.cloud.translation.v3beta1.IGetGlossaryRequest|undefined, {}|undefined - ]>; + request?: protos.google.cloud.translation.v3beta1.IGetGlossaryRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.translation.v3beta1.IGlossary, + protos.google.cloud.translation.v3beta1.IGetGlossaryRequest | undefined, + {} | undefined, + ] + >; getGlossary( - request: protos.google.cloud.translation.v3beta1.IGetGlossaryRequest, - options: CallOptions, - callback: Callback< - protos.google.cloud.translation.v3beta1.IGlossary, - protos.google.cloud.translation.v3beta1.IGetGlossaryRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.translation.v3beta1.IGetGlossaryRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.translation.v3beta1.IGlossary, + | protos.google.cloud.translation.v3beta1.IGetGlossaryRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getGlossary( - request: protos.google.cloud.translation.v3beta1.IGetGlossaryRequest, - callback: Callback< - protos.google.cloud.translation.v3beta1.IGlossary, - protos.google.cloud.translation.v3beta1.IGetGlossaryRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.translation.v3beta1.IGetGlossaryRequest, + callback: Callback< + protos.google.cloud.translation.v3beta1.IGlossary, + | protos.google.cloud.translation.v3beta1.IGetGlossaryRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getGlossary( - request?: protos.google.cloud.translation.v3beta1.IGetGlossaryRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.translation.v3beta1.IGlossary, - protos.google.cloud.translation.v3beta1.IGetGlossaryRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.cloud.translation.v3beta1.IGetGlossaryRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.cloud.translation.v3beta1.IGlossary, - protos.google.cloud.translation.v3beta1.IGetGlossaryRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.cloud.translation.v3beta1.IGlossary, - protos.google.cloud.translation.v3beta1.IGetGlossaryRequest|undefined, {}|undefined - ]>|void { + | protos.google.cloud.translation.v3beta1.IGetGlossaryRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.translation.v3beta1.IGlossary, + | protos.google.cloud.translation.v3beta1.IGetGlossaryRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.translation.v3beta1.IGlossary, + protos.google.cloud.translation.v3beta1.IGetGlossaryRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getGlossary request %j', request); - const wrappedCallback: Callback< - protos.google.cloud.translation.v3beta1.IGlossary, - protos.google.cloud.translation.v3beta1.IGetGlossaryRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.cloud.translation.v3beta1.IGlossary, + | protos.google.cloud.translation.v3beta1.IGetGlossaryRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getGlossary response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getGlossary(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.cloud.translation.v3beta1.IGlossary, - protos.google.cloud.translation.v3beta1.IGetGlossaryRequest|undefined, - {}|undefined - ]) => { - this._log.info('getGlossary response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getGlossary(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.translation.v3beta1.IGlossary, + ( + | protos.google.cloud.translation.v3beta1.IGetGlossaryRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('getGlossary response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Translates a large volume of text in asynchronous batch mode. - * This function provides real-time output as the inputs are being processed. - * If caller cancels a request, the partial results (for an input file, it's - * all or nothing) may still be available on the specified output location. - * - * This call returns immediately and you can - * use google.longrunning.Operation.name to poll the status of the call. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. Location to make a call. Must refer to a caller's project. - * - * Format: `projects/{project-id}/locations/{location-id}`. - * - * The `global` location is not supported for batch translation. - * - * Only AutoML Translation models or glossaries within the same region (have - * the same location-id) can be used, otherwise an INVALID_ARGUMENT (400) - * error is returned. - * @param {string} request.sourceLanguageCode - * Required. Source language code. - * @param {string[]} request.targetLanguageCodes - * Required. Specify up to 10 language codes here. - * @param {number[]} [request.models] - * Optional. The models to use for translation. Map's key is target language - * code. Map's value is model name. Value can be a built-in general model, - * or an AutoML Translation model. - * - * The value format depends on model type: - * - * - AutoML Translation models: - * `projects/{project-id}/locations/{location-id}/models/{model-id}` - * - * - General (built-in) models: - * `projects/{project-id}/locations/{location-id}/models/general/nmt`, - * `projects/{project-id}/locations/{location-id}/models/general/base` - * - * - * If the map is empty or a specific model is - * not requested for a language pair, then default google model (nmt) is used. - * @param {number[]} request.inputConfigs - * Required. Input configurations. - * The total number of files matched should be <= 1000. - * The total content size should be <= 100M Unicode codepoints. - * The files must use UTF-8 encoding. - * @param {google.cloud.translation.v3beta1.OutputConfig} request.outputConfig - * Required. Output configuration. - * If 2 input configs match to the same file (that is, same input path), - * we don't generate output for duplicate inputs. - * @param {number[]} [request.glossaries] - * Optional. Glossaries to be applied for translation. - * It's keyed by target language code. - * @param {number[]} [request.labels] - * Optional. The labels with user-defined metadata for the request. - * - * Label keys and values can be no longer than 63 characters - * (Unicode codepoints), can only contain lowercase letters, numeric - * characters, underscores and dashes. International characters are allowed. - * Label values are optional. Label keys must start with a letter. - * - * See https://cloud.google.com/translate/docs/labels for more information. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing - * a long running operation. Its `promise()` method returns a promise - * you can `await` for. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v3beta1/translation_service.batch_translate_text.js - * region_tag:translate_v3beta1_generated_TranslationService_BatchTranslateText_async - */ + /** + * Translates a large volume of text in asynchronous batch mode. + * This function provides real-time output as the inputs are being processed. + * If caller cancels a request, the partial results (for an input file, it's + * all or nothing) may still be available on the specified output location. + * + * This call returns immediately and you can + * use google.longrunning.Operation.name to poll the status of the call. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Location to make a call. Must refer to a caller's project. + * + * Format: `projects/{project-id}/locations/{location-id}`. + * + * The `global` location is not supported for batch translation. + * + * Only AutoML Translation models or glossaries within the same region (have + * the same location-id) can be used, otherwise an INVALID_ARGUMENT (400) + * error is returned. + * @param {string} request.sourceLanguageCode + * Required. Source language code. + * @param {string[]} request.targetLanguageCodes + * Required. Specify up to 10 language codes here. + * @param {number[]} [request.models] + * Optional. The models to use for translation. Map's key is target language + * code. Map's value is model name. Value can be a built-in general model, + * or an AutoML Translation model. + * + * The value format depends on model type: + * + * - AutoML Translation models: + * `projects/{project-id}/locations/{location-id}/models/{model-id}` + * + * - General (built-in) models: + * `projects/{project-id}/locations/{location-id}/models/general/nmt`, + * `projects/{project-id}/locations/{location-id}/models/general/base` + * + * + * If the map is empty or a specific model is + * not requested for a language pair, then default google model (nmt) is used. + * @param {number[]} request.inputConfigs + * Required. Input configurations. + * The total number of files matched should be <= 1000. + * The total content size should be <= 100M Unicode codepoints. + * The files must use UTF-8 encoding. + * @param {google.cloud.translation.v3beta1.OutputConfig} request.outputConfig + * Required. Output configuration. + * If 2 input configs match to the same file (that is, same input path), + * we don't generate output for duplicate inputs. + * @param {number[]} [request.glossaries] + * Optional. Glossaries to be applied for translation. + * It's keyed by target language code. + * @param {number[]} [request.labels] + * Optional. The labels with user-defined metadata for the request. + * + * Label keys and values can be no longer than 63 characters + * (Unicode codepoints), can only contain lowercase letters, numeric + * characters, underscores and dashes. International characters are allowed. + * Label values are optional. Label keys must start with a letter. + * + * See https://cloud.google.com/translate/docs/labels for more information. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v3beta1/translation_service.batch_translate_text.js + * region_tag:translate_v3beta1_generated_TranslationService_BatchTranslateText_async + */ batchTranslateText( - request?: protos.google.cloud.translation.v3beta1.IBatchTranslateTextRequest, - options?: CallOptions): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>; + request?: protos.google.cloud.translation.v3beta1.IBatchTranslateTextRequest, + options?: CallOptions, + ): Promise< + [ + LROperation< + protos.google.cloud.translation.v3beta1.IBatchTranslateResponse, + protos.google.cloud.translation.v3beta1.IBatchTranslateMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; batchTranslateText( - request: protos.google.cloud.translation.v3beta1.IBatchTranslateTextRequest, - options: CallOptions, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.translation.v3beta1.IBatchTranslateTextRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.cloud.translation.v3beta1.IBatchTranslateResponse, + protos.google.cloud.translation.v3beta1.IBatchTranslateMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; batchTranslateText( - request: protos.google.cloud.translation.v3beta1.IBatchTranslateTextRequest, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.translation.v3beta1.IBatchTranslateTextRequest, + callback: Callback< + LROperation< + protos.google.cloud.translation.v3beta1.IBatchTranslateResponse, + protos.google.cloud.translation.v3beta1.IBatchTranslateMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; batchTranslateText( - request?: protos.google.cloud.translation.v3beta1.IBatchTranslateTextRequest, - optionsOrCallback?: CallOptions|Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>, - callback?: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>|void { + request?: protos.google.cloud.translation.v3beta1.IBatchTranslateTextRequest, + optionsOrCallback?: + | CallOptions + | Callback< + LROperation< + protos.google.cloud.translation.v3beta1.IBatchTranslateResponse, + protos.google.cloud.translation.v3beta1.IBatchTranslateMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + callback?: Callback< + LROperation< + protos.google.cloud.translation.v3beta1.IBatchTranslateResponse, + protos.google.cloud.translation.v3beta1.IBatchTranslateMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + LROperation< + protos.google.cloud.translation.v3beta1.IBatchTranslateResponse, + protos.google.cloud.translation.v3beta1.IBatchTranslateMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + LROperation< + protos.google.cloud.translation.v3beta1.IBatchTranslateResponse, + protos.google.cloud.translation.v3beta1.IBatchTranslateMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, rawResponse, _) => { this._log.info('batchTranslateText response %j', rawResponse); callback!(error, response, rawResponse, _); // We verified callback above. } : undefined; this._log.info('batchTranslateText request %j', request); - return this.innerApiCalls.batchTranslateText(request, options, wrappedCallback) - ?.then(([response, rawResponse, _]: [ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]) => { - this._log.info('batchTranslateText response %j', rawResponse); - return [response, rawResponse, _]; - }); + return this.innerApiCalls + .batchTranslateText(request, options, wrappedCallback) + ?.then( + ([response, rawResponse, _]: [ + LROperation< + protos.google.cloud.translation.v3beta1.IBatchTranslateResponse, + protos.google.cloud.translation.v3beta1.IBatchTranslateMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ]) => { + this._log.info('batchTranslateText response %j', rawResponse); + return [response, rawResponse, _]; + }, + ); } -/** - * Check the status of the long running operation returned by `batchTranslateText()`. - * @param {String} name - * The operation name that will be passed. - * @returns {Promise} - The promise which resolves to an object. - * The decoded operation object has result and metadata field to get information from. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v3beta1/translation_service.batch_translate_text.js - * region_tag:translate_v3beta1_generated_TranslationService_BatchTranslateText_async - */ - async checkBatchTranslateTextProgress(name: string): Promise>{ + /** + * Check the status of the long running operation returned by `batchTranslateText()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v3beta1/translation_service.batch_translate_text.js + * region_tag:translate_v3beta1_generated_TranslationService_BatchTranslateText_async + */ + async checkBatchTranslateTextProgress( + name: string, + ): Promise< + LROperation< + protos.google.cloud.translation.v3beta1.BatchTranslateResponse, + protos.google.cloud.translation.v3beta1.BatchTranslateMetadata + > + > { this._log.info('batchTranslateText long-running'); - const request = new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest({name}); + const request = + new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( + { name }, + ); const [operation] = await this.operationsClient.getOperation(request); - const decodeOperation = new this._gaxModule.Operation(operation, this.descriptors.longrunning.batchTranslateText, this._gaxModule.createDefaultBackoffSettings()); - return decodeOperation as LROperation; + const decodeOperation = new this._gaxModule.Operation( + operation, + this.descriptors.longrunning.batchTranslateText, + this._gaxModule.createDefaultBackoffSettings(), + ); + return decodeOperation as LROperation< + protos.google.cloud.translation.v3beta1.BatchTranslateResponse, + protos.google.cloud.translation.v3beta1.BatchTranslateMetadata + >; } -/** - * Creates a glossary and returns the long-running operation. Returns - * NOT_FOUND, if the project doesn't exist. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The project name. - * @param {google.cloud.translation.v3beta1.Glossary} request.glossary - * Required. The glossary to create. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing - * a long running operation. Its `promise()` method returns a promise - * you can `await` for. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v3beta1/translation_service.create_glossary.js - * region_tag:translate_v3beta1_generated_TranslationService_CreateGlossary_async - */ + /** + * Creates a glossary and returns the long-running operation. Returns + * NOT_FOUND, if the project doesn't exist. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The project name. + * @param {google.cloud.translation.v3beta1.Glossary} request.glossary + * Required. The glossary to create. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v3beta1/translation_service.create_glossary.js + * region_tag:translate_v3beta1_generated_TranslationService_CreateGlossary_async + */ createGlossary( - request?: protos.google.cloud.translation.v3beta1.ICreateGlossaryRequest, - options?: CallOptions): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>; + request?: protos.google.cloud.translation.v3beta1.ICreateGlossaryRequest, + options?: CallOptions, + ): Promise< + [ + LROperation< + protos.google.cloud.translation.v3beta1.IGlossary, + protos.google.cloud.translation.v3beta1.ICreateGlossaryMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; createGlossary( - request: protos.google.cloud.translation.v3beta1.ICreateGlossaryRequest, - options: CallOptions, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.translation.v3beta1.ICreateGlossaryRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.cloud.translation.v3beta1.IGlossary, + protos.google.cloud.translation.v3beta1.ICreateGlossaryMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; createGlossary( - request: protos.google.cloud.translation.v3beta1.ICreateGlossaryRequest, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.translation.v3beta1.ICreateGlossaryRequest, + callback: Callback< + LROperation< + protos.google.cloud.translation.v3beta1.IGlossary, + protos.google.cloud.translation.v3beta1.ICreateGlossaryMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; createGlossary( - request?: protos.google.cloud.translation.v3beta1.ICreateGlossaryRequest, - optionsOrCallback?: CallOptions|Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>, - callback?: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>|void { + request?: protos.google.cloud.translation.v3beta1.ICreateGlossaryRequest, + optionsOrCallback?: + | CallOptions + | Callback< + LROperation< + protos.google.cloud.translation.v3beta1.IGlossary, + protos.google.cloud.translation.v3beta1.ICreateGlossaryMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + callback?: Callback< + LROperation< + protos.google.cloud.translation.v3beta1.IGlossary, + protos.google.cloud.translation.v3beta1.ICreateGlossaryMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + LROperation< + protos.google.cloud.translation.v3beta1.IGlossary, + protos.google.cloud.translation.v3beta1.ICreateGlossaryMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + LROperation< + protos.google.cloud.translation.v3beta1.IGlossary, + protos.google.cloud.translation.v3beta1.ICreateGlossaryMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, rawResponse, _) => { this._log.info('createGlossary response %j', rawResponse); callback!(error, response, rawResponse, _); // We verified callback above. } : undefined; this._log.info('createGlossary request %j', request); - return this.innerApiCalls.createGlossary(request, options, wrappedCallback) - ?.then(([response, rawResponse, _]: [ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]) => { - this._log.info('createGlossary response %j', rawResponse); - return [response, rawResponse, _]; - }); + return this.innerApiCalls + .createGlossary(request, options, wrappedCallback) + ?.then( + ([response, rawResponse, _]: [ + LROperation< + protos.google.cloud.translation.v3beta1.IGlossary, + protos.google.cloud.translation.v3beta1.ICreateGlossaryMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ]) => { + this._log.info('createGlossary response %j', rawResponse); + return [response, rawResponse, _]; + }, + ); } -/** - * Check the status of the long running operation returned by `createGlossary()`. - * @param {String} name - * The operation name that will be passed. - * @returns {Promise} - The promise which resolves to an object. - * The decoded operation object has result and metadata field to get information from. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v3beta1/translation_service.create_glossary.js - * region_tag:translate_v3beta1_generated_TranslationService_CreateGlossary_async - */ - async checkCreateGlossaryProgress(name: string): Promise>{ + /** + * Check the status of the long running operation returned by `createGlossary()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v3beta1/translation_service.create_glossary.js + * region_tag:translate_v3beta1_generated_TranslationService_CreateGlossary_async + */ + async checkCreateGlossaryProgress( + name: string, + ): Promise< + LROperation< + protos.google.cloud.translation.v3beta1.Glossary, + protos.google.cloud.translation.v3beta1.CreateGlossaryMetadata + > + > { this._log.info('createGlossary long-running'); - const request = new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest({name}); + const request = + new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( + { name }, + ); const [operation] = await this.operationsClient.getOperation(request); - const decodeOperation = new this._gaxModule.Operation(operation, this.descriptors.longrunning.createGlossary, this._gaxModule.createDefaultBackoffSettings()); - return decodeOperation as LROperation; + const decodeOperation = new this._gaxModule.Operation( + operation, + this.descriptors.longrunning.createGlossary, + this._gaxModule.createDefaultBackoffSettings(), + ); + return decodeOperation as LROperation< + protos.google.cloud.translation.v3beta1.Glossary, + protos.google.cloud.translation.v3beta1.CreateGlossaryMetadata + >; } -/** - * Deletes a glossary, or cancels glossary construction - * if the glossary isn't created yet. - * Returns NOT_FOUND, if the glossary doesn't exist. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The name of the glossary to delete. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing - * a long running operation. Its `promise()` method returns a promise - * you can `await` for. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v3beta1/translation_service.delete_glossary.js - * region_tag:translate_v3beta1_generated_TranslationService_DeleteGlossary_async - */ + /** + * Deletes a glossary, or cancels glossary construction + * if the glossary isn't created yet. + * Returns NOT_FOUND, if the glossary doesn't exist. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The name of the glossary to delete. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v3beta1/translation_service.delete_glossary.js + * region_tag:translate_v3beta1_generated_TranslationService_DeleteGlossary_async + */ deleteGlossary( - request?: protos.google.cloud.translation.v3beta1.IDeleteGlossaryRequest, - options?: CallOptions): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>; + request?: protos.google.cloud.translation.v3beta1.IDeleteGlossaryRequest, + options?: CallOptions, + ): Promise< + [ + LROperation< + protos.google.cloud.translation.v3beta1.IDeleteGlossaryResponse, + protos.google.cloud.translation.v3beta1.IDeleteGlossaryMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; deleteGlossary( - request: protos.google.cloud.translation.v3beta1.IDeleteGlossaryRequest, - options: CallOptions, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.translation.v3beta1.IDeleteGlossaryRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.cloud.translation.v3beta1.IDeleteGlossaryResponse, + protos.google.cloud.translation.v3beta1.IDeleteGlossaryMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; deleteGlossary( - request: protos.google.cloud.translation.v3beta1.IDeleteGlossaryRequest, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.translation.v3beta1.IDeleteGlossaryRequest, + callback: Callback< + LROperation< + protos.google.cloud.translation.v3beta1.IDeleteGlossaryResponse, + protos.google.cloud.translation.v3beta1.IDeleteGlossaryMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; deleteGlossary( - request?: protos.google.cloud.translation.v3beta1.IDeleteGlossaryRequest, - optionsOrCallback?: CallOptions|Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>, - callback?: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>|void { + request?: protos.google.cloud.translation.v3beta1.IDeleteGlossaryRequest, + optionsOrCallback?: + | CallOptions + | Callback< + LROperation< + protos.google.cloud.translation.v3beta1.IDeleteGlossaryResponse, + protos.google.cloud.translation.v3beta1.IDeleteGlossaryMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + callback?: Callback< + LROperation< + protos.google.cloud.translation.v3beta1.IDeleteGlossaryResponse, + protos.google.cloud.translation.v3beta1.IDeleteGlossaryMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + LROperation< + protos.google.cloud.translation.v3beta1.IDeleteGlossaryResponse, + protos.google.cloud.translation.v3beta1.IDeleteGlossaryMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + LROperation< + protos.google.cloud.translation.v3beta1.IDeleteGlossaryResponse, + protos.google.cloud.translation.v3beta1.IDeleteGlossaryMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, rawResponse, _) => { this._log.info('deleteGlossary response %j', rawResponse); callback!(error, response, rawResponse, _); // We verified callback above. } : undefined; this._log.info('deleteGlossary request %j', request); - return this.innerApiCalls.deleteGlossary(request, options, wrappedCallback) - ?.then(([response, rawResponse, _]: [ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]) => { - this._log.info('deleteGlossary response %j', rawResponse); - return [response, rawResponse, _]; - }); + return this.innerApiCalls + .deleteGlossary(request, options, wrappedCallback) + ?.then( + ([response, rawResponse, _]: [ + LROperation< + protos.google.cloud.translation.v3beta1.IDeleteGlossaryResponse, + protos.google.cloud.translation.v3beta1.IDeleteGlossaryMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ]) => { + this._log.info('deleteGlossary response %j', rawResponse); + return [response, rawResponse, _]; + }, + ); } -/** - * Check the status of the long running operation returned by `deleteGlossary()`. - * @param {String} name - * The operation name that will be passed. - * @returns {Promise} - The promise which resolves to an object. - * The decoded operation object has result and metadata field to get information from. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v3beta1/translation_service.delete_glossary.js - * region_tag:translate_v3beta1_generated_TranslationService_DeleteGlossary_async - */ - async checkDeleteGlossaryProgress(name: string): Promise>{ + /** + * Check the status of the long running operation returned by `deleteGlossary()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v3beta1/translation_service.delete_glossary.js + * region_tag:translate_v3beta1_generated_TranslationService_DeleteGlossary_async + */ + async checkDeleteGlossaryProgress( + name: string, + ): Promise< + LROperation< + protos.google.cloud.translation.v3beta1.DeleteGlossaryResponse, + protos.google.cloud.translation.v3beta1.DeleteGlossaryMetadata + > + > { this._log.info('deleteGlossary long-running'); - const request = new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest({name}); + const request = + new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( + { name }, + ); const [operation] = await this.operationsClient.getOperation(request); - const decodeOperation = new this._gaxModule.Operation(operation, this.descriptors.longrunning.deleteGlossary, this._gaxModule.createDefaultBackoffSettings()); - return decodeOperation as LROperation; + const decodeOperation = new this._gaxModule.Operation( + operation, + this.descriptors.longrunning.deleteGlossary, + this._gaxModule.createDefaultBackoffSettings(), + ); + return decodeOperation as LROperation< + protos.google.cloud.translation.v3beta1.DeleteGlossaryResponse, + protos.google.cloud.translation.v3beta1.DeleteGlossaryMetadata + >; } - /** - * Lists glossaries in a project. Returns NOT_FOUND, if the project doesn't - * exist. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The name of the project from which to list all of the glossaries. - * @param {number} [request.pageSize] - * Optional. Requested page size. The server may return fewer glossaries than - * requested. If unspecified, the server picks an appropriate default. - * @param {string} [request.pageToken] - * Optional. A token identifying a page of results the server should return. - * Typically, this is the value of [ListGlossariesResponse.next_page_token] - * returned from the previous call to `ListGlossaries` method. - * The first page is returned if `page_token`is empty or missing. - * @param {string} [request.filter] - * Optional. Filter specifying constraints of a list operation. - * Filtering is not supported yet, and the parameter currently has no effect. - * If missing, no filtering is performed. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.cloud.translation.v3beta1.Glossary|Glossary}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `listGlossariesAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Lists glossaries in a project. Returns NOT_FOUND, if the project doesn't + * exist. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The name of the project from which to list all of the glossaries. + * @param {number} [request.pageSize] + * Optional. Requested page size. The server may return fewer glossaries than + * requested. If unspecified, the server picks an appropriate default. + * @param {string} [request.pageToken] + * Optional. A token identifying a page of results the server should return. + * Typically, this is the value of [ListGlossariesResponse.next_page_token] + * returned from the previous call to `ListGlossaries` method. + * The first page is returned if `page_token`is empty or missing. + * @param {string} [request.filter] + * Optional. Filter specifying constraints of a list operation. + * Filtering is not supported yet, and the parameter currently has no effect. + * If missing, no filtering is performed. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.cloud.translation.v3beta1.Glossary|Glossary}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listGlossariesAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listGlossaries( - request?: protos.google.cloud.translation.v3beta1.IListGlossariesRequest, - options?: CallOptions): - Promise<[ - protos.google.cloud.translation.v3beta1.IGlossary[], - protos.google.cloud.translation.v3beta1.IListGlossariesRequest|null, - protos.google.cloud.translation.v3beta1.IListGlossariesResponse - ]>; + request?: protos.google.cloud.translation.v3beta1.IListGlossariesRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.translation.v3beta1.IGlossary[], + protos.google.cloud.translation.v3beta1.IListGlossariesRequest | null, + protos.google.cloud.translation.v3beta1.IListGlossariesResponse, + ] + >; listGlossaries( - request: protos.google.cloud.translation.v3beta1.IListGlossariesRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.cloud.translation.v3beta1.IListGlossariesRequest, - protos.google.cloud.translation.v3beta1.IListGlossariesResponse|null|undefined, - protos.google.cloud.translation.v3beta1.IGlossary>): void; + request: protos.google.cloud.translation.v3beta1.IListGlossariesRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.cloud.translation.v3beta1.IListGlossariesRequest, + | protos.google.cloud.translation.v3beta1.IListGlossariesResponse + | null + | undefined, + protos.google.cloud.translation.v3beta1.IGlossary + >, + ): void; listGlossaries( - request: protos.google.cloud.translation.v3beta1.IListGlossariesRequest, - callback: PaginationCallback< - protos.google.cloud.translation.v3beta1.IListGlossariesRequest, - protos.google.cloud.translation.v3beta1.IListGlossariesResponse|null|undefined, - protos.google.cloud.translation.v3beta1.IGlossary>): void; + request: protos.google.cloud.translation.v3beta1.IListGlossariesRequest, + callback: PaginationCallback< + protos.google.cloud.translation.v3beta1.IListGlossariesRequest, + | protos.google.cloud.translation.v3beta1.IListGlossariesResponse + | null + | undefined, + protos.google.cloud.translation.v3beta1.IGlossary + >, + ): void; listGlossaries( - request?: protos.google.cloud.translation.v3beta1.IListGlossariesRequest, - optionsOrCallback?: CallOptions|PaginationCallback< + request?: protos.google.cloud.translation.v3beta1.IListGlossariesRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.cloud.translation.v3beta1.IListGlossariesRequest, - protos.google.cloud.translation.v3beta1.IListGlossariesResponse|null|undefined, - protos.google.cloud.translation.v3beta1.IGlossary>, - callback?: PaginationCallback< - protos.google.cloud.translation.v3beta1.IListGlossariesRequest, - protos.google.cloud.translation.v3beta1.IListGlossariesResponse|null|undefined, - protos.google.cloud.translation.v3beta1.IGlossary>): - Promise<[ - protos.google.cloud.translation.v3beta1.IGlossary[], - protos.google.cloud.translation.v3beta1.IListGlossariesRequest|null, - protos.google.cloud.translation.v3beta1.IListGlossariesResponse - ]>|void { + | protos.google.cloud.translation.v3beta1.IListGlossariesResponse + | null + | undefined, + protos.google.cloud.translation.v3beta1.IGlossary + >, + callback?: PaginationCallback< + protos.google.cloud.translation.v3beta1.IListGlossariesRequest, + | protos.google.cloud.translation.v3beta1.IListGlossariesResponse + | null + | undefined, + protos.google.cloud.translation.v3beta1.IGlossary + >, + ): Promise< + [ + protos.google.cloud.translation.v3beta1.IGlossary[], + protos.google.cloud.translation.v3beta1.IListGlossariesRequest | null, + protos.google.cloud.translation.v3beta1.IListGlossariesResponse, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.cloud.translation.v3beta1.IListGlossariesRequest, - protos.google.cloud.translation.v3beta1.IListGlossariesResponse|null|undefined, - protos.google.cloud.translation.v3beta1.IGlossary>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.cloud.translation.v3beta1.IListGlossariesRequest, + | protos.google.cloud.translation.v3beta1.IListGlossariesResponse + | null + | undefined, + protos.google.cloud.translation.v3beta1.IGlossary + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listGlossaries values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -1363,122 +1830,126 @@ export class TranslationServiceClient { this._log.info('listGlossaries request %j', request); return this.innerApiCalls .listGlossaries(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.cloud.translation.v3beta1.IGlossary[], - protos.google.cloud.translation.v3beta1.IListGlossariesRequest|null, - protos.google.cloud.translation.v3beta1.IListGlossariesResponse - ]) => { - this._log.info('listGlossaries values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.cloud.translation.v3beta1.IGlossary[], + protos.google.cloud.translation.v3beta1.IListGlossariesRequest | null, + protos.google.cloud.translation.v3beta1.IListGlossariesResponse, + ]) => { + this._log.info('listGlossaries values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listGlossaries`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The name of the project from which to list all of the glossaries. - * @param {number} [request.pageSize] - * Optional. Requested page size. The server may return fewer glossaries than - * requested. If unspecified, the server picks an appropriate default. - * @param {string} [request.pageToken] - * Optional. A token identifying a page of results the server should return. - * Typically, this is the value of [ListGlossariesResponse.next_page_token] - * returned from the previous call to `ListGlossaries` method. - * The first page is returned if `page_token`is empty or missing. - * @param {string} [request.filter] - * Optional. Filter specifying constraints of a list operation. - * Filtering is not supported yet, and the parameter currently has no effect. - * If missing, no filtering is performed. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.cloud.translation.v3beta1.Glossary|Glossary} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `listGlossariesAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `listGlossaries`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The name of the project from which to list all of the glossaries. + * @param {number} [request.pageSize] + * Optional. Requested page size. The server may return fewer glossaries than + * requested. If unspecified, the server picks an appropriate default. + * @param {string} [request.pageToken] + * Optional. A token identifying a page of results the server should return. + * Typically, this is the value of [ListGlossariesResponse.next_page_token] + * returned from the previous call to `ListGlossaries` method. + * The first page is returned if `page_token`is empty or missing. + * @param {string} [request.filter] + * Optional. Filter specifying constraints of a list operation. + * Filtering is not supported yet, and the parameter currently has no effect. + * If missing, no filtering is performed. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.cloud.translation.v3beta1.Glossary|Glossary} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listGlossariesAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listGlossariesStream( - request?: protos.google.cloud.translation.v3beta1.IListGlossariesRequest, - options?: CallOptions): - Transform{ + request?: protos.google.cloud.translation.v3beta1.IListGlossariesRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); const defaultCallSettings = this._defaults['listGlossaries']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listGlossaries stream %j', request); return this.descriptors.page.listGlossaries.createStream( this.innerApiCalls.listGlossaries as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listGlossaries`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The name of the project from which to list all of the glossaries. - * @param {number} [request.pageSize] - * Optional. Requested page size. The server may return fewer glossaries than - * requested. If unspecified, the server picks an appropriate default. - * @param {string} [request.pageToken] - * Optional. A token identifying a page of results the server should return. - * Typically, this is the value of [ListGlossariesResponse.next_page_token] - * returned from the previous call to `ListGlossaries` method. - * The first page is returned if `page_token`is empty or missing. - * @param {string} [request.filter] - * Optional. Filter specifying constraints of a list operation. - * Filtering is not supported yet, and the parameter currently has no effect. - * If missing, no filtering is performed. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.cloud.translation.v3beta1.Glossary|Glossary}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example include:samples/generated/v3beta1/translation_service.list_glossaries.js - * region_tag:translate_v3beta1_generated_TranslationService_ListGlossaries_async - */ + /** + * Equivalent to `listGlossaries`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The name of the project from which to list all of the glossaries. + * @param {number} [request.pageSize] + * Optional. Requested page size. The server may return fewer glossaries than + * requested. If unspecified, the server picks an appropriate default. + * @param {string} [request.pageToken] + * Optional. A token identifying a page of results the server should return. + * Typically, this is the value of [ListGlossariesResponse.next_page_token] + * returned from the previous call to `ListGlossaries` method. + * The first page is returned if `page_token`is empty or missing. + * @param {string} [request.filter] + * Optional. Filter specifying constraints of a list operation. + * Filtering is not supported yet, and the parameter currently has no effect. + * If missing, no filtering is performed. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.cloud.translation.v3beta1.Glossary|Glossary}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example include:samples/generated/v3beta1/translation_service.list_glossaries.js + * region_tag:translate_v3beta1_generated_TranslationService_ListGlossaries_async + */ listGlossariesAsync( - request?: protos.google.cloud.translation.v3beta1.IListGlossariesRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.cloud.translation.v3beta1.IListGlossariesRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); const defaultCallSettings = this._defaults['listGlossaries']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listGlossaries iterate %j', request); return this.descriptors.page.listGlossaries.asyncIterate( this.innerApiCalls['listGlossaries'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } // -------------------- @@ -1493,7 +1964,7 @@ export class TranslationServiceClient { * @param {string} glossary * @returns {string} Resource name string. */ - glossaryPath(project:string,location:string,glossary:string) { + glossaryPath(project: string, location: string, glossary: string) { return this.pathTemplates.glossaryPathTemplate.render({ project: project, location: location, @@ -1541,7 +2012,7 @@ export class TranslationServiceClient { * @param {string} location * @returns {string} Resource name string. */ - locationPath(project:string,location:string) { + locationPath(project: string, location: string) { return this.pathTemplates.locationPathTemplate.render({ project: project, location: location, @@ -1578,7 +2049,7 @@ export class TranslationServiceClient { */ close(): Promise { if (this.translationServiceStub && !this._terminated) { - return this.translationServiceStub.then(stub => { + return this.translationServiceStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -1587,4 +2058,4 @@ export class TranslationServiceClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/core/generator/gapic-generator-typescript/baselines/translate/system-test/fixtures/sample/src/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/translate/system-test/fixtures/sample/src/index.ts.baseline index 06dcee3e6811..140a3f8a24d7 100644 --- a/core/generator/gapic-generator-typescript/baselines/translate/system-test/fixtures/sample/src/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/translate/system-test/fixtures/sample/src/index.ts.baseline @@ -16,7 +16,7 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -import {TranslationServiceClient} from 'translation'; +import { TranslationServiceClient } from 'translation'; // check that the client class type name can be used function doStuffWithTranslationServiceClient(client: TranslationServiceClient) { diff --git a/core/generator/gapic-generator-typescript/baselines/translate/system-test/install.ts.baseline b/core/generator/gapic-generator-typescript/baselines/translate/system-test/install.ts.baseline index f66069aa3940..ccf167042d2e 100644 --- a/core/generator/gapic-generator-typescript/baselines/translate/system-test/install.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/translate/system-test/install.ts.baseline @@ -16,34 +16,36 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -import {packNTest} from 'pack-n-play'; -import {readFileSync} from 'fs'; -import {describe, it} from 'mocha'; +import { packNTest } from 'pack-n-play'; +import { readFileSync } from 'fs'; +import { describe, it } from 'mocha'; describe('📦 pack-n-play test', () => { - - it('TypeScript code', async function() { + it('TypeScript code', async function () { this.timeout(300000); const options = { packageDir: process.cwd(), sample: { description: 'TypeScript user can use the type definitions', - ts: readFileSync('./system-test/fixtures/sample/src/index.ts').toString() - } + ts: readFileSync( + './system-test/fixtures/sample/src/index.ts', + ).toString(), + }, }; await packNTest(options); }); - it('JavaScript code', async function() { + it('JavaScript code', async function () { this.timeout(300000); const options = { packageDir: process.cwd(), sample: { description: 'JavaScript user can use the library', - cjs: readFileSync('./system-test/fixtures/sample/src/index.js').toString() - } + cjs: readFileSync( + './system-test/fixtures/sample/src/index.js', + ).toString(), + }, }; await packNTest(options); }); - }); diff --git a/core/generator/gapic-generator-typescript/baselines/translate/test/gapic_translation_service_v3beta1.ts.baseline b/core/generator/gapic-generator-typescript/baselines/translate/test/gapic_translation_service_v3beta1.ts.baseline index de19cb3fb570..95a79bc04263 100644 --- a/core/generator/gapic-generator-typescript/baselines/translate/test/gapic_translation_service_v3beta1.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/translate/test/gapic_translation_service_v3beta1.ts.baseline @@ -19,1485 +19,1950 @@ import * as protos from '../protos/protos'; import * as assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as translationserviceModule from '../src'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; -import {protobuf, LROperation, operationsProtos} from 'google-gax'; +import { protobuf, LROperation, operationsProtos } from 'google-gax'; // Dynamically loaded proto JSON is needed to get the type information // to fill in default values for request objects -const root = protobuf.Root.fromJSON(require('../protos/protos.json')).resolveAll(); +const root = protobuf.Root.fromJSON( + require('../protos/protos.json'), +).resolveAll(); // eslint-disable-next-line @typescript-eslint/no-unused-vars function getTypeDefaultValue(typeName: string, fields: string[]) { - let type = root.lookupType(typeName) as protobuf.Type; - for (const field of fields.slice(0, -1)) { - type = type.fields[field]?.resolvedType as protobuf.Type; - } - return type.fields[fields[fields.length - 1]]?.defaultValue; + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type.fields[field]?.resolvedType as protobuf.Type; + } + return type.fields[fields[fields.length - 1]]?.defaultValue; } function generateSampleMessage(instance: T) { - const filledObject = (instance.constructor as typeof protobuf.Message) - .toObject(instance as protobuf.Message, {defaults: true}); - return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, { defaults: true }); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; } function stubSimpleCall(response?: ResponseType, error?: Error) { - return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); } -function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { - return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +function stubSimpleCallWithCallback( + response?: ResponseType, + error?: Error, +) { + return error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); } -function stubLongRunningCall(response?: ResponseType, callError?: Error, lroError?: Error) { - const innerStub = lroError ? sinon.stub().rejects(lroError) : sinon.stub().resolves([response]); - const mockOperation = { - promise: innerStub, - }; - return callError ? sinon.stub().rejects(callError) : sinon.stub().resolves([mockOperation]); +function stubLongRunningCall( + response?: ResponseType, + callError?: Error, + lroError?: Error, +) { + const innerStub = lroError + ? sinon.stub().rejects(lroError) + : sinon.stub().resolves([response]); + const mockOperation = { + promise: innerStub, + }; + return callError + ? sinon.stub().rejects(callError) + : sinon.stub().resolves([mockOperation]); } -function stubLongRunningCallWithCallback(response?: ResponseType, callError?: Error, lroError?: Error) { - const innerStub = lroError ? sinon.stub().rejects(lroError) : sinon.stub().resolves([response]); - const mockOperation = { - promise: innerStub, - }; - return callError ? sinon.stub().callsArgWith(2, callError) : sinon.stub().callsArgWith(2, null, mockOperation); +function stubLongRunningCallWithCallback( + response?: ResponseType, + callError?: Error, + lroError?: Error, +) { + const innerStub = lroError + ? sinon.stub().rejects(lroError) + : sinon.stub().resolves([response]); + const mockOperation = { + promise: innerStub, + }; + return callError + ? sinon.stub().callsArgWith(2, callError) + : sinon.stub().callsArgWith(2, null, mockOperation); } -function stubPageStreamingCall(responses?: ResponseType[], error?: Error) { - const pagingStub = sinon.stub(); - if (responses) { - for (let i = 0; i < responses.length; ++i) { - pagingStub.onCall(i).callsArgWith(2, null, responses[i]); - } +function stubPageStreamingCall( + responses?: ResponseType[], + error?: Error, +) { + const pagingStub = sinon.stub(); + if (responses) { + for (let i = 0; i < responses.length; ++i) { + pagingStub.onCall(i).callsArgWith(2, null, responses[i]); } - const transformStub = error ? sinon.stub().callsArgWith(2, error) : pagingStub; - const mockStream = new PassThrough({ - objectMode: true, - transform: transformStub, - }); - // trigger as many responses as needed - if (responses) { - for (let i = 0; i < responses.length; ++i) { - setImmediate(() => { mockStream.write({}); }); - } - setImmediate(() => { mockStream.end(); }); - } else { - setImmediate(() => { mockStream.write({}); }); - setImmediate(() => { mockStream.end(); }); + } + const transformStub = error + ? sinon.stub().callsArgWith(2, error) + : pagingStub; + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + // trigger as many responses as needed + if (responses) { + for (let i = 0; i < responses.length; ++i) { + setImmediate(() => { + mockStream.write({}); + }); } - return sinon.stub().returns(mockStream); + setImmediate(() => { + mockStream.end(); + }); + } else { + setImmediate(() => { + mockStream.write({}); + }); + setImmediate(() => { + mockStream.end(); + }); + } + return sinon.stub().returns(mockStream); } -function stubAsyncIterationCall(responses?: ResponseType[], error?: Error) { - let counter = 0; - const asyncIterable = { - [Symbol.asyncIterator]() { - return { - async next() { - if (error) { - return Promise.reject(error); - } - if (counter >= responses!.length) { - return Promise.resolve({done: true, value: undefined}); - } - return Promise.resolve({done: false, value: responses![counter++]}); - } - }; - } - }; - return sinon.stub().returns(asyncIterable); +function stubAsyncIterationCall( + responses?: ResponseType[], + error?: Error, +) { + let counter = 0; + const asyncIterable = { + [Symbol.asyncIterator]() { + return { + async next() { + if (error) { + return Promise.reject(error); + } + if (counter >= responses!.length) { + return Promise.resolve({ done: true, value: undefined }); + } + return Promise.resolve({ done: false, value: responses![counter++] }); + }, + }; + }, + }; + return sinon.stub().returns(asyncIterable); } describe('v3beta1.TranslationServiceClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new translationserviceModule.v3beta1.TranslationServiceClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'translate.googleapis.com'); - }); - - it('has universeDomain', () => { - const client = new translationserviceModule.v3beta1.TranslationServiceClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = + new translationserviceModule.v3beta1.TranslationServiceClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'translate.googleapis.com'); + }); - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - it('throws DeprecationWarning if static servicePath is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const servicePath = translationserviceModule.v3beta1.TranslationServiceClient.servicePath; - assert.strictEqual(servicePath, 'translate.googleapis.com'); - assert(stub.called); - stub.restore(); - }); + it('has universeDomain', () => { + const client = + new translationserviceModule.v3beta1.TranslationServiceClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = translationserviceModule.v3beta1.TranslationServiceClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'translate.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new translationserviceModule.v3beta1.TranslationServiceClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'translate.example.com'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = + translationserviceModule.v3beta1.TranslationServiceClient.servicePath; + assert.strictEqual(servicePath, 'translate.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + translationserviceModule.v3beta1.TranslationServiceClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'translate.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = + new translationserviceModule.v3beta1.TranslationServiceClient({ + universeDomain: 'example.com', }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'translate.example.com'); + }); - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new translationserviceModule.v3beta1.TranslationServiceClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'translate.example.com'); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = + new translationserviceModule.v3beta1.TranslationServiceClient({ + universe_domain: 'example.com', }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'translate.example.com'); + }); - if (typeof process === 'object' && 'env' in process) { - describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { - it('sets apiEndpoint from environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new translationserviceModule.v3beta1.TranslationServiceClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'translate.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - - it('value configured in code has priority over environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new translationserviceModule.v3beta1.TranslationServiceClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'translate.configured.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { new translationserviceModule.v3beta1.TranslationServiceClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); + if (typeof process === 'object' && 'env' in process) { + describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { + it('sets apiEndpoint from environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = + new translationserviceModule.v3beta1.TranslationServiceClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'translate.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - it('has port', () => { - const port = translationserviceModule.v3beta1.TranslationServiceClient.port; - assert(port); - assert(typeof port === 'number'); + it('value configured in code has priority over environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = + new translationserviceModule.v3beta1.TranslationServiceClient({ + universeDomain: 'configured.example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'translate.configured.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - - it('should create a client with no option', () => { - const client = new translationserviceModule.v3beta1.TranslationServiceClient(); - assert(client); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new translationserviceModule.v3beta1.TranslationServiceClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); + }); - it('should create a client with gRPC fallback', () => { - const client = new translationserviceModule.v3beta1.TranslationServiceClient({ - fallback: true, - }); - assert(client); - }); + it('has port', () => { + const port = + translationserviceModule.v3beta1.TranslationServiceClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('has initialize method and supports deferred initialization', async () => { - const client = new translationserviceModule.v3beta1.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.translationServiceStub, undefined); - await client.initialize(); - assert(client.translationServiceStub); - }); + it('should create a client with no option', () => { + const client = + new translationserviceModule.v3beta1.TranslationServiceClient(); + assert(client); + }); - it('has close method for the initialized client', done => { - const client = new translationserviceModule.v3beta1.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.translationServiceStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); + it('should create a client with gRPC fallback', () => { + const client = + new translationserviceModule.v3beta1.TranslationServiceClient({ + fallback: true, }); + assert(client); + }); - it('has close method for the non-initialized client', done => { - const client = new translationserviceModule.v3beta1.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.translationServiceStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); + it('has initialize method and supports deferred initialization', async () => { + const client = + new translationserviceModule.v3beta1.TranslationServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + assert.strictEqual(client.translationServiceStub, undefined); + await client.initialize(); + assert(client.translationServiceStub); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new translationserviceModule.v3beta1.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + it('has close method for the initialized client', (done) => { + const client = + new translationserviceModule.v3beta1.TranslationServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); - - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new translationserviceModule.v3beta1.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId((err?: Error|null, projectId?: string|null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } - }); - }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); + client.initialize().catch((err) => { + throw err; + }); + assert(client.translationServiceStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); }); - describe('translateText', () => { - it('invokes translateText without error', async () => { - const client = new translationserviceModule.v3beta1.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.translation.v3beta1.TranslateTextRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.translation.v3beta1.TranslateTextRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.translation.v3beta1.TranslateTextResponse() - ); - client.innerApiCalls.translateText = stubSimpleCall(expectedResponse); - const [response] = await client.translateText(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.translateText as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.translateText as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('has close method for the non-initialized client', (done) => { + const client = + new translationserviceModule.v3beta1.TranslationServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); - - it('invokes translateText without error using callback', async () => { - const client = new translationserviceModule.v3beta1.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.translation.v3beta1.TranslateTextRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.translation.v3beta1.TranslateTextRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.translation.v3beta1.TranslateTextResponse() - ); - client.innerApiCalls.translateText = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.translateText( - request, - (err?: Error|null, result?: protos.google.cloud.translation.v3beta1.ITranslateTextResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.translateText as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.translateText as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + assert.strictEqual(client.translationServiceStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes translateText with error', async () => { - const client = new translationserviceModule.v3beta1.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.translation.v3beta1.TranslateTextRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.translation.v3beta1.TranslateTextRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.translateText = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.translateText(request), expectedError); - const actualRequest = (client.innerApiCalls.translateText as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.translateText as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = + new translationserviceModule.v3beta1.TranslationServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + }); - it('invokes translateText with closed client', async () => { - const client = new translationserviceModule.v3beta1.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.translation.v3beta1.TranslateTextRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.translation.v3beta1.TranslateTextRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.translateText(request), expectedError); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = + new translationserviceModule.v3beta1.TranslationServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } + }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); }); - - describe('detectLanguage', () => { - it('invokes detectLanguage without error', async () => { - const client = new translationserviceModule.v3beta1.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.translation.v3beta1.DetectLanguageRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.translation.v3beta1.DetectLanguageRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.translation.v3beta1.DetectLanguageResponse() - ); - client.innerApiCalls.detectLanguage = stubSimpleCall(expectedResponse); - const [response] = await client.detectLanguage(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.detectLanguage as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.detectLanguage as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + describe('translateText', () => { + it('invokes translateText without error', async () => { + const client = + new translationserviceModule.v3beta1.TranslationServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.TranslateTextRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.translation.v3beta1.TranslateTextRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.TranslateTextResponse(), + ); + client.innerApiCalls.translateText = stubSimpleCall(expectedResponse); + const [response] = await client.translateText(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.translateText as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.translateText as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes detectLanguage without error using callback', async () => { - const client = new translationserviceModule.v3beta1.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.translation.v3beta1.DetectLanguageRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.translation.v3beta1.DetectLanguageRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.translation.v3beta1.DetectLanguageResponse() - ); - client.innerApiCalls.detectLanguage = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.detectLanguage( - request, - (err?: Error|null, result?: protos.google.cloud.translation.v3beta1.IDetectLanguageResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.detectLanguage as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.detectLanguage as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes translateText without error using callback', async () => { + const client = + new translationserviceModule.v3beta1.TranslationServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.TranslateTextRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.translation.v3beta1.TranslateTextRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.TranslateTextResponse(), + ); + client.innerApiCalls.translateText = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.translateText( + request, + ( + err?: Error | null, + result?: protos.google.cloud.translation.v3beta1.ITranslateTextResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.translateText as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.translateText as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes detectLanguage with error', async () => { - const client = new translationserviceModule.v3beta1.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.translation.v3beta1.DetectLanguageRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.translation.v3beta1.DetectLanguageRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.detectLanguage = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.detectLanguage(request), expectedError); - const actualRequest = (client.innerApiCalls.detectLanguage as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.detectLanguage as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes translateText with error', async () => { + const client = + new translationserviceModule.v3beta1.TranslationServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.TranslateTextRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.translation.v3beta1.TranslateTextRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.translateText = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.translateText(request), expectedError); + const actualRequest = ( + client.innerApiCalls.translateText as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.translateText as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes detectLanguage with closed client', async () => { - const client = new translationserviceModule.v3beta1.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.translation.v3beta1.DetectLanguageRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.translation.v3beta1.DetectLanguageRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.detectLanguage(request), expectedError); + it('invokes translateText with closed client', async () => { + const client = + new translationserviceModule.v3beta1.TranslationServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.TranslateTextRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.translation.v3beta1.TranslateTextRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.translateText(request), expectedError); }); - - describe('getSupportedLanguages', () => { - it('invokes getSupportedLanguages without error', async () => { - const client = new translationserviceModule.v3beta1.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.translation.v3beta1.GetSupportedLanguagesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.translation.v3beta1.GetSupportedLanguagesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.translation.v3beta1.SupportedLanguages() - ); - client.innerApiCalls.getSupportedLanguages = stubSimpleCall(expectedResponse); - const [response] = await client.getSupportedLanguages(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getSupportedLanguages as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getSupportedLanguages as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + describe('detectLanguage', () => { + it('invokes detectLanguage without error', async () => { + const client = + new translationserviceModule.v3beta1.TranslationServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.DetectLanguageRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.translation.v3beta1.DetectLanguageRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.DetectLanguageResponse(), + ); + client.innerApiCalls.detectLanguage = stubSimpleCall(expectedResponse); + const [response] = await client.detectLanguage(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.detectLanguage as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.detectLanguage as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getSupportedLanguages without error using callback', async () => { - const client = new translationserviceModule.v3beta1.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.translation.v3beta1.GetSupportedLanguagesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.translation.v3beta1.GetSupportedLanguagesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.translation.v3beta1.SupportedLanguages() - ); - client.innerApiCalls.getSupportedLanguages = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getSupportedLanguages( - request, - (err?: Error|null, result?: protos.google.cloud.translation.v3beta1.ISupportedLanguages|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getSupportedLanguages as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getSupportedLanguages as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes detectLanguage without error using callback', async () => { + const client = + new translationserviceModule.v3beta1.TranslationServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.DetectLanguageRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.translation.v3beta1.DetectLanguageRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.DetectLanguageResponse(), + ); + client.innerApiCalls.detectLanguage = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.detectLanguage( + request, + ( + err?: Error | null, + result?: protos.google.cloud.translation.v3beta1.IDetectLanguageResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.detectLanguage as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.detectLanguage as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getSupportedLanguages with error', async () => { - const client = new translationserviceModule.v3beta1.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.translation.v3beta1.GetSupportedLanguagesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.translation.v3beta1.GetSupportedLanguagesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getSupportedLanguages = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getSupportedLanguages(request), expectedError); - const actualRequest = (client.innerApiCalls.getSupportedLanguages as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getSupportedLanguages as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes detectLanguage with error', async () => { + const client = + new translationserviceModule.v3beta1.TranslationServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.DetectLanguageRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.translation.v3beta1.DetectLanguageRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.detectLanguage = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.detectLanguage(request), expectedError); + const actualRequest = ( + client.innerApiCalls.detectLanguage as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.detectLanguage as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getSupportedLanguages with closed client', async () => { - const client = new translationserviceModule.v3beta1.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.translation.v3beta1.GetSupportedLanguagesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.translation.v3beta1.GetSupportedLanguagesRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getSupportedLanguages(request), expectedError); + it('invokes detectLanguage with closed client', async () => { + const client = + new translationserviceModule.v3beta1.TranslationServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.DetectLanguageRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.translation.v3beta1.DetectLanguageRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.detectLanguage(request), expectedError); }); - - describe('getGlossary', () => { - it('invokes getGlossary without error', async () => { - const client = new translationserviceModule.v3beta1.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.translation.v3beta1.GetGlossaryRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.translation.v3beta1.GetGlossaryRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.translation.v3beta1.Glossary() - ); - client.innerApiCalls.getGlossary = stubSimpleCall(expectedResponse); - const [response] = await client.getGlossary(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getGlossary as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getGlossary as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + describe('getSupportedLanguages', () => { + it('invokes getSupportedLanguages without error', async () => { + const client = + new translationserviceModule.v3beta1.TranslationServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.GetSupportedLanguagesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.translation.v3beta1.GetSupportedLanguagesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.SupportedLanguages(), + ); + client.innerApiCalls.getSupportedLanguages = + stubSimpleCall(expectedResponse); + const [response] = await client.getSupportedLanguages(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getSupportedLanguages as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getSupportedLanguages as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getGlossary without error using callback', async () => { - const client = new translationserviceModule.v3beta1.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.translation.v3beta1.GetGlossaryRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.translation.v3beta1.GetGlossaryRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.cloud.translation.v3beta1.Glossary() - ); - client.innerApiCalls.getGlossary = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getGlossary( - request, - (err?: Error|null, result?: protos.google.cloud.translation.v3beta1.IGlossary|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getGlossary as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getGlossary as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes getSupportedLanguages without error using callback', async () => { + const client = + new translationserviceModule.v3beta1.TranslationServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.GetSupportedLanguagesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.translation.v3beta1.GetSupportedLanguagesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.SupportedLanguages(), + ); + client.innerApiCalls.getSupportedLanguages = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getSupportedLanguages( + request, + ( + err?: Error | null, + result?: protos.google.cloud.translation.v3beta1.ISupportedLanguages | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getSupportedLanguages as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getSupportedLanguages as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getGlossary with error', async () => { - const client = new translationserviceModule.v3beta1.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.translation.v3beta1.GetGlossaryRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.translation.v3beta1.GetGlossaryRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getGlossary = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getGlossary(request), expectedError); - const actualRequest = (client.innerApiCalls.getGlossary as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getGlossary as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes getSupportedLanguages with error', async () => { + const client = + new translationserviceModule.v3beta1.TranslationServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.GetSupportedLanguagesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.translation.v3beta1.GetSupportedLanguagesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getSupportedLanguages = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.getSupportedLanguages(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.getSupportedLanguages as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getSupportedLanguages as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getGlossary with closed client', async () => { - const client = new translationserviceModule.v3beta1.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.translation.v3beta1.GetGlossaryRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.translation.v3beta1.GetGlossaryRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getGlossary(request), expectedError); + it('invokes getSupportedLanguages with closed client', async () => { + const client = + new translationserviceModule.v3beta1.TranslationServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.GetSupportedLanguagesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.translation.v3beta1.GetSupportedLanguagesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.getSupportedLanguages(request), + expectedError, + ); }); - - describe('batchTranslateText', () => { - it('invokes batchTranslateText without error', async () => { - const client = new translationserviceModule.v3beta1.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.translation.v3beta1.BatchTranslateTextRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.translation.v3beta1.BatchTranslateTextRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.batchTranslateText = stubLongRunningCall(expectedResponse); - const [operation] = await client.batchTranslateText(request); - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.batchTranslateText as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.batchTranslateText as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + describe('getGlossary', () => { + it('invokes getGlossary without error', async () => { + const client = + new translationserviceModule.v3beta1.TranslationServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.GetGlossaryRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.translation.v3beta1.GetGlossaryRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.Glossary(), + ); + client.innerApiCalls.getGlossary = stubSimpleCall(expectedResponse); + const [response] = await client.getGlossary(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getGlossary as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getGlossary as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes batchTranslateText without error using callback', async () => { - const client = new translationserviceModule.v3beta1.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.translation.v3beta1.BatchTranslateTextRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.translation.v3beta1.BatchTranslateTextRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.batchTranslateText = stubLongRunningCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.batchTranslateText( - request, - (err?: Error|null, - result?: LROperation|null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const operation = await promise as LROperation; - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.batchTranslateText as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.batchTranslateText as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes getGlossary without error using callback', async () => { + const client = + new translationserviceModule.v3beta1.TranslationServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.GetGlossaryRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.translation.v3beta1.GetGlossaryRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.Glossary(), + ); + client.innerApiCalls.getGlossary = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getGlossary( + request, + ( + err?: Error | null, + result?: protos.google.cloud.translation.v3beta1.IGlossary | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getGlossary as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getGlossary as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes batchTranslateText with call error', async () => { - const client = new translationserviceModule.v3beta1.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.translation.v3beta1.BatchTranslateTextRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.translation.v3beta1.BatchTranslateTextRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.batchTranslateText = stubLongRunningCall(undefined, expectedError); - await assert.rejects(client.batchTranslateText(request), expectedError); - const actualRequest = (client.innerApiCalls.batchTranslateText as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.batchTranslateText as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes getGlossary with error', async () => { + const client = + new translationserviceModule.v3beta1.TranslationServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.GetGlossaryRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.translation.v3beta1.GetGlossaryRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getGlossary = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getGlossary(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getGlossary as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getGlossary as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes batchTranslateText with LRO error', async () => { - const client = new translationserviceModule.v3beta1.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.translation.v3beta1.BatchTranslateTextRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.translation.v3beta1.BatchTranslateTextRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.batchTranslateText = stubLongRunningCall(undefined, undefined, expectedError); - const [operation] = await client.batchTranslateText(request); - await assert.rejects(operation.promise(), expectedError); - const actualRequest = (client.innerApiCalls.batchTranslateText as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.batchTranslateText as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes getGlossary with closed client', async () => { + const client = + new translationserviceModule.v3beta1.TranslationServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); - - it('invokes checkBatchTranslateTextProgress without error', async () => { - const client = new translationserviceModule.v3beta1.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedResponse = generateSampleMessage( - new operationsProtos.google.longrunning.Operation() - ); - expectedResponse.name = 'test'; - expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; - expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')} - - client.operationsClient.getOperation = stubSimpleCall(expectedResponse); - const decodedOperation = await client.checkBatchTranslateTextProgress(expectedResponse.name); - assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); - assert(decodedOperation.metadata); - assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.GetGlossaryRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.translation.v3beta1.GetGlossaryRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getGlossary(request), expectedError); + }); + }); + + describe('batchTranslateText', () => { + it('invokes batchTranslateText without error', async () => { + const client = + new translationserviceModule.v3beta1.TranslationServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.BatchTranslateTextRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.translation.v3beta1.BatchTranslateTextRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.batchTranslateText = + stubLongRunningCall(expectedResponse); + const [operation] = await client.batchTranslateText(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.batchTranslateText as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.batchTranslateText as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkBatchTranslateTextProgress with error', async () => { - const client = new translationserviceModule.v3beta1.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedError = new Error('expected'); - - client.operationsClient.getOperation = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.checkBatchTranslateTextProgress(''), expectedError); - assert((client.operationsClient.getOperation as SinonStub) - .getCall(0)); + it('invokes batchTranslateText without error using callback', async () => { + const client = + new translationserviceModule.v3beta1.TranslationServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.BatchTranslateTextRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.translation.v3beta1.BatchTranslateTextRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.batchTranslateText = + stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.batchTranslateText( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.cloud.translation.v3beta1.IBatchTranslateResponse, + protos.google.cloud.translation.v3beta1.IBatchTranslateMetadata + > | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const operation = (await promise) as LROperation< + protos.google.cloud.translation.v3beta1.IBatchTranslateResponse, + protos.google.cloud.translation.v3beta1.IBatchTranslateMetadata + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.batchTranslateText as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.batchTranslateText as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('createGlossary', () => { - it('invokes createGlossary without error', async () => { - const client = new translationserviceModule.v3beta1.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.translation.v3beta1.CreateGlossaryRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.translation.v3beta1.CreateGlossaryRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.createGlossary = stubLongRunningCall(expectedResponse); - const [operation] = await client.createGlossary(request); - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createGlossary as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createGlossary as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes batchTranslateText with call error', async () => { + const client = + new translationserviceModule.v3beta1.TranslationServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.BatchTranslateTextRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.translation.v3beta1.BatchTranslateTextRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.batchTranslateText = stubLongRunningCall( + undefined, + expectedError, + ); + await assert.rejects(client.batchTranslateText(request), expectedError); + const actualRequest = ( + client.innerApiCalls.batchTranslateText as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.batchTranslateText as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createGlossary without error using callback', async () => { - const client = new translationserviceModule.v3beta1.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.translation.v3beta1.CreateGlossaryRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.translation.v3beta1.CreateGlossaryRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.createGlossary = stubLongRunningCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createGlossary( - request, - (err?: Error|null, - result?: LROperation|null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const operation = await promise as LROperation; - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createGlossary as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createGlossary as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes batchTranslateText with LRO error', async () => { + const client = + new translationserviceModule.v3beta1.TranslationServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.BatchTranslateTextRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.translation.v3beta1.BatchTranslateTextRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.batchTranslateText = stubLongRunningCall( + undefined, + undefined, + expectedError, + ); + const [operation] = await client.batchTranslateText(request); + await assert.rejects(operation.promise(), expectedError); + const actualRequest = ( + client.innerApiCalls.batchTranslateText as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.batchTranslateText as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createGlossary with call error', async () => { - const client = new translationserviceModule.v3beta1.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.translation.v3beta1.CreateGlossaryRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.translation.v3beta1.CreateGlossaryRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createGlossary = stubLongRunningCall(undefined, expectedError); - await assert.rejects(client.createGlossary(request), expectedError); - const actualRequest = (client.innerApiCalls.createGlossary as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createGlossary as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes checkBatchTranslateTextProgress without error', async () => { + const client = + new translationserviceModule.v3beta1.TranslationServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation(), + ); + expectedResponse.name = 'test'; + expectedResponse.response = { type_url: 'url', value: Buffer.from('') }; + expectedResponse.metadata = { type_url: 'url', value: Buffer.from('') }; + + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const decodedOperation = await client.checkBatchTranslateTextProgress( + expectedResponse.name, + ); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); - it('invokes createGlossary with LRO error', async () => { - const client = new translationserviceModule.v3beta1.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.translation.v3beta1.CreateGlossaryRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.translation.v3beta1.CreateGlossaryRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createGlossary = stubLongRunningCall(undefined, undefined, expectedError); - const [operation] = await client.createGlossary(request); - await assert.rejects(operation.promise(), expectedError); - const actualRequest = (client.innerApiCalls.createGlossary as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createGlossary as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes checkBatchTranslateTextProgress with error', async () => { + const client = + new translationserviceModule.v3beta1.TranslationServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); - - it('invokes checkCreateGlossaryProgress without error', async () => { - const client = new translationserviceModule.v3beta1.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedResponse = generateSampleMessage( - new operationsProtos.google.longrunning.Operation() - ); - expectedResponse.name = 'test'; - expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; - expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')} - - client.operationsClient.getOperation = stubSimpleCall(expectedResponse); - const decodedOperation = await client.checkCreateGlossaryProgress(expectedResponse.name); - assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); - assert(decodedOperation.metadata); - assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + await client.initialize(); + const expectedError = new Error('expected'); + + client.operationsClient.getOperation = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.checkBatchTranslateTextProgress(''), + expectedError, + ); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + }); + + describe('createGlossary', () => { + it('invokes createGlossary without error', async () => { + const client = + new translationserviceModule.v3beta1.TranslationServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.CreateGlossaryRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.translation.v3beta1.CreateGlossaryRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.createGlossary = + stubLongRunningCall(expectedResponse); + const [operation] = await client.createGlossary(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createGlossary as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createGlossary as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkCreateGlossaryProgress with error', async () => { - const client = new translationserviceModule.v3beta1.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedError = new Error('expected'); - - client.operationsClient.getOperation = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.checkCreateGlossaryProgress(''), expectedError); - assert((client.operationsClient.getOperation as SinonStub) - .getCall(0)); + it('invokes createGlossary without error using callback', async () => { + const client = + new translationserviceModule.v3beta1.TranslationServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.CreateGlossaryRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.translation.v3beta1.CreateGlossaryRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.createGlossary = + stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createGlossary( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.cloud.translation.v3beta1.IGlossary, + protos.google.cloud.translation.v3beta1.ICreateGlossaryMetadata + > | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const operation = (await promise) as LROperation< + protos.google.cloud.translation.v3beta1.IGlossary, + protos.google.cloud.translation.v3beta1.ICreateGlossaryMetadata + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createGlossary as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createGlossary as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('deleteGlossary', () => { - it('invokes deleteGlossary without error', async () => { - const client = new translationserviceModule.v3beta1.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.translation.v3beta1.DeleteGlossaryRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.translation.v3beta1.DeleteGlossaryRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.deleteGlossary = stubLongRunningCall(expectedResponse); - const [operation] = await client.deleteGlossary(request); - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteGlossary as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteGlossary as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes createGlossary with call error', async () => { + const client = + new translationserviceModule.v3beta1.TranslationServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.CreateGlossaryRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.translation.v3beta1.CreateGlossaryRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createGlossary = stubLongRunningCall( + undefined, + expectedError, + ); + await assert.rejects(client.createGlossary(request), expectedError); + const actualRequest = ( + client.innerApiCalls.createGlossary as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createGlossary as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteGlossary without error using callback', async () => { - const client = new translationserviceModule.v3beta1.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.translation.v3beta1.DeleteGlossaryRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.translation.v3beta1.DeleteGlossaryRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.deleteGlossary = stubLongRunningCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteGlossary( - request, - (err?: Error|null, - result?: LROperation|null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const operation = await promise as LROperation; - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteGlossary as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteGlossary as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes createGlossary with LRO error', async () => { + const client = + new translationserviceModule.v3beta1.TranslationServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.CreateGlossaryRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.translation.v3beta1.CreateGlossaryRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createGlossary = stubLongRunningCall( + undefined, + undefined, + expectedError, + ); + const [operation] = await client.createGlossary(request); + await assert.rejects(operation.promise(), expectedError); + const actualRequest = ( + client.innerApiCalls.createGlossary as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createGlossary as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteGlossary with call error', async () => { - const client = new translationserviceModule.v3beta1.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.translation.v3beta1.DeleteGlossaryRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.translation.v3beta1.DeleteGlossaryRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteGlossary = stubLongRunningCall(undefined, expectedError); - await assert.rejects(client.deleteGlossary(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteGlossary as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteGlossary as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes checkCreateGlossaryProgress without error', async () => { + const client = + new translationserviceModule.v3beta1.TranslationServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation(), + ); + expectedResponse.name = 'test'; + expectedResponse.response = { type_url: 'url', value: Buffer.from('') }; + expectedResponse.metadata = { type_url: 'url', value: Buffer.from('') }; + + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const decodedOperation = await client.checkCreateGlossaryProgress( + expectedResponse.name, + ); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); - it('invokes deleteGlossary with LRO error', async () => { - const client = new translationserviceModule.v3beta1.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.translation.v3beta1.DeleteGlossaryRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.translation.v3beta1.DeleteGlossaryRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteGlossary = stubLongRunningCall(undefined, undefined, expectedError); - const [operation] = await client.deleteGlossary(request); - await assert.rejects(operation.promise(), expectedError); - const actualRequest = (client.innerApiCalls.deleteGlossary as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteGlossary as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes checkCreateGlossaryProgress with error', async () => { + const client = + new translationserviceModule.v3beta1.TranslationServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); - - it('invokes checkDeleteGlossaryProgress without error', async () => { - const client = new translationserviceModule.v3beta1.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedResponse = generateSampleMessage( - new operationsProtos.google.longrunning.Operation() - ); - expectedResponse.name = 'test'; - expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; - expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')} - - client.operationsClient.getOperation = stubSimpleCall(expectedResponse); - const decodedOperation = await client.checkDeleteGlossaryProgress(expectedResponse.name); - assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); - assert(decodedOperation.metadata); - assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + await client.initialize(); + const expectedError = new Error('expected'); + + client.operationsClient.getOperation = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.checkCreateGlossaryProgress(''), + expectedError, + ); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + }); + + describe('deleteGlossary', () => { + it('invokes deleteGlossary without error', async () => { + const client = + new translationserviceModule.v3beta1.TranslationServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.DeleteGlossaryRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.translation.v3beta1.DeleteGlossaryRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.deleteGlossary = + stubLongRunningCall(expectedResponse); + const [operation] = await client.deleteGlossary(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteGlossary as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteGlossary as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkDeleteGlossaryProgress with error', async () => { - const client = new translationserviceModule.v3beta1.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedError = new Error('expected'); - - client.operationsClient.getOperation = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.checkDeleteGlossaryProgress(''), expectedError); - assert((client.operationsClient.getOperation as SinonStub) - .getCall(0)); + it('invokes deleteGlossary without error using callback', async () => { + const client = + new translationserviceModule.v3beta1.TranslationServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.DeleteGlossaryRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.translation.v3beta1.DeleteGlossaryRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.deleteGlossary = + stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteGlossary( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.cloud.translation.v3beta1.IDeleteGlossaryResponse, + protos.google.cloud.translation.v3beta1.IDeleteGlossaryMetadata + > | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const operation = (await promise) as LROperation< + protos.google.cloud.translation.v3beta1.IDeleteGlossaryResponse, + protos.google.cloud.translation.v3beta1.IDeleteGlossaryMetadata + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteGlossary as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteGlossary as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('listGlossaries', () => { - it('invokes listGlossaries without error', async () => { - const client = new translationserviceModule.v3beta1.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.translation.v3beta1.ListGlossariesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.translation.v3beta1.ListGlossariesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.translation.v3beta1.Glossary()), - generateSampleMessage(new protos.google.cloud.translation.v3beta1.Glossary()), - generateSampleMessage(new protos.google.cloud.translation.v3beta1.Glossary()), - ]; - client.innerApiCalls.listGlossaries = stubSimpleCall(expectedResponse); - const [response] = await client.listGlossaries(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listGlossaries as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listGlossaries as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes deleteGlossary with call error', async () => { + const client = + new translationserviceModule.v3beta1.TranslationServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.DeleteGlossaryRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.translation.v3beta1.DeleteGlossaryRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteGlossary = stubLongRunningCall( + undefined, + expectedError, + ); + await assert.rejects(client.deleteGlossary(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteGlossary as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteGlossary as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listGlossaries without error using callback', async () => { - const client = new translationserviceModule.v3beta1.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.translation.v3beta1.ListGlossariesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.translation.v3beta1.ListGlossariesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.translation.v3beta1.Glossary()), - generateSampleMessage(new protos.google.cloud.translation.v3beta1.Glossary()), - generateSampleMessage(new protos.google.cloud.translation.v3beta1.Glossary()), - ]; - client.innerApiCalls.listGlossaries = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listGlossaries( - request, - (err?: Error|null, result?: protos.google.cloud.translation.v3beta1.IGlossary[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listGlossaries as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listGlossaries as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes deleteGlossary with LRO error', async () => { + const client = + new translationserviceModule.v3beta1.TranslationServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.DeleteGlossaryRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.translation.v3beta1.DeleteGlossaryRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteGlossary = stubLongRunningCall( + undefined, + undefined, + expectedError, + ); + const [operation] = await client.deleteGlossary(request); + await assert.rejects(operation.promise(), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteGlossary as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteGlossary as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listGlossaries with error', async () => { - const client = new translationserviceModule.v3beta1.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.translation.v3beta1.ListGlossariesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.translation.v3beta1.ListGlossariesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listGlossaries = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listGlossaries(request), expectedError); - const actualRequest = (client.innerApiCalls.listGlossaries as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listGlossaries as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes checkDeleteGlossaryProgress without error', async () => { + const client = + new translationserviceModule.v3beta1.TranslationServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation(), + ); + expectedResponse.name = 'test'; + expectedResponse.response = { type_url: 'url', value: Buffer.from('') }; + expectedResponse.metadata = { type_url: 'url', value: Buffer.from('') }; + + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const decodedOperation = await client.checkDeleteGlossaryProgress( + expectedResponse.name, + ); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); - it('invokes listGlossariesStream without error', async () => { - const client = new translationserviceModule.v3beta1.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.translation.v3beta1.ListGlossariesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.translation.v3beta1.ListGlossariesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.translation.v3beta1.Glossary()), - generateSampleMessage(new protos.google.cloud.translation.v3beta1.Glossary()), - generateSampleMessage(new protos.google.cloud.translation.v3beta1.Glossary()), - ]; - client.descriptors.page.listGlossaries.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listGlossariesStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.cloud.translation.v3beta1.Glossary[] = []; - stream.on('data', (response: protos.google.cloud.translation.v3beta1.Glossary) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.listGlossaries.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listGlossaries, request)); - assert( - (client.descriptors.page.listGlossaries.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); + it('invokes checkDeleteGlossaryProgress with error', async () => { + const client = + new translationserviceModule.v3beta1.TranslationServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); - - it('invokes listGlossariesStream with error', async () => { - const client = new translationserviceModule.v3beta1.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.translation.v3beta1.ListGlossariesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.translation.v3beta1.ListGlossariesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listGlossaries.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listGlossariesStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.cloud.translation.v3beta1.Glossary[] = []; - stream.on('data', (response: protos.google.cloud.translation.v3beta1.Glossary) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listGlossaries.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listGlossaries, request)); - assert( - (client.descriptors.page.listGlossaries.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); + await client.initialize(); + const expectedError = new Error('expected'); + + client.operationsClient.getOperation = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.checkDeleteGlossaryProgress(''), + expectedError, + ); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + }); + + describe('listGlossaries', () => { + it('invokes listGlossaries without error', async () => { + const client = + new translationserviceModule.v3beta1.TranslationServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.ListGlossariesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.translation.v3beta1.ListGlossariesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.cloud.translation.v3beta1.Glossary(), + ), + generateSampleMessage( + new protos.google.cloud.translation.v3beta1.Glossary(), + ), + generateSampleMessage( + new protos.google.cloud.translation.v3beta1.Glossary(), + ), + ]; + client.innerApiCalls.listGlossaries = stubSimpleCall(expectedResponse); + const [response] = await client.listGlossaries(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listGlossaries as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listGlossaries as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('uses async iteration with listGlossaries without error', async () => { - const client = new translationserviceModule.v3beta1.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.translation.v3beta1.ListGlossariesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.translation.v3beta1.ListGlossariesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.cloud.translation.v3beta1.Glossary()), - generateSampleMessage(new protos.google.cloud.translation.v3beta1.Glossary()), - generateSampleMessage(new protos.google.cloud.translation.v3beta1.Glossary()), - ]; - client.descriptors.page.listGlossaries.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.cloud.translation.v3beta1.IGlossary[] = []; - const iterable = client.listGlossariesAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listGlossaries.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listGlossaries.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); + it('invokes listGlossaries without error using callback', async () => { + const client = + new translationserviceModule.v3beta1.TranslationServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.ListGlossariesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.translation.v3beta1.ListGlossariesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.cloud.translation.v3beta1.Glossary(), + ), + generateSampleMessage( + new protos.google.cloud.translation.v3beta1.Glossary(), + ), + generateSampleMessage( + new protos.google.cloud.translation.v3beta1.Glossary(), + ), + ]; + client.innerApiCalls.listGlossaries = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listGlossaries( + request, + ( + err?: Error | null, + result?: protos.google.cloud.translation.v3beta1.IGlossary[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listGlossaries as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listGlossaries as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('uses async iteration with listGlossaries with error', async () => { - const client = new translationserviceModule.v3beta1.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.translation.v3beta1.ListGlossariesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.cloud.translation.v3beta1.ListGlossariesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listGlossaries.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listGlossariesAsync(request); - await assert.rejects(async () => { - const responses: protos.google.cloud.translation.v3beta1.IGlossary[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listGlossaries.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listGlossaries.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); + it('invokes listGlossaries with error', async () => { + const client = + new translationserviceModule.v3beta1.TranslationServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.ListGlossariesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.translation.v3beta1.ListGlossariesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listGlossaries = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listGlossaries(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listGlossaries as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listGlossaries as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('Path templates', () => { - - describe('glossary', async () => { - const fakePath = "/rendered/path/glossary"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - glossary: "glossaryValue", - }; - const client = new translationserviceModule.v3beta1.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.glossaryPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.glossaryPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('glossaryPath', () => { - const result = client.glossaryPath("projectValue", "locationValue", "glossaryValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.glossaryPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromGlossaryName', () => { - const result = client.matchProjectFromGlossaryName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.glossaryPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromGlossaryName', () => { - const result = client.matchLocationFromGlossaryName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.glossaryPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('invokes listGlossariesStream without error', async () => { + const client = + new translationserviceModule.v3beta1.TranslationServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.ListGlossariesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.translation.v3beta1.ListGlossariesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.cloud.translation.v3beta1.Glossary(), + ), + generateSampleMessage( + new protos.google.cloud.translation.v3beta1.Glossary(), + ), + generateSampleMessage( + new protos.google.cloud.translation.v3beta1.Glossary(), + ), + ]; + client.descriptors.page.listGlossaries.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listGlossariesStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.cloud.translation.v3beta1.Glossary[] = + []; + stream.on( + 'data', + (response: protos.google.cloud.translation.v3beta1.Glossary) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listGlossaries.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listGlossaries, request), + ); + assert( + (client.descriptors.page.listGlossaries.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('matchGlossaryFromGlossaryName', () => { - const result = client.matchGlossaryFromGlossaryName(fakePath); - assert.strictEqual(result, "glossaryValue"); - assert((client.pathTemplates.glossaryPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('invokes listGlossariesStream with error', async () => { + const client = + new translationserviceModule.v3beta1.TranslationServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.ListGlossariesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.translation.v3beta1.ListGlossariesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listGlossaries.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listGlossariesStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.cloud.translation.v3beta1.Glossary[] = + []; + stream.on( + 'data', + (response: protos.google.cloud.translation.v3beta1.Glossary) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listGlossaries.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listGlossaries, request), + ); + assert( + (client.descriptors.page.listGlossaries.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - describe('location', async () => { - const fakePath = "/rendered/path/location"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - }; - const client = new translationserviceModule.v3beta1.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.locationPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.locationPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('locationPath', () => { - const result = client.locationPath("projectValue", "locationValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.locationPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + it('uses async iteration with listGlossaries without error', async () => { + const client = + new translationserviceModule.v3beta1.TranslationServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.ListGlossariesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.translation.v3beta1.ListGlossariesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.cloud.translation.v3beta1.Glossary(), + ), + generateSampleMessage( + new protos.google.cloud.translation.v3beta1.Glossary(), + ), + generateSampleMessage( + new protos.google.cloud.translation.v3beta1.Glossary(), + ), + ]; + client.descriptors.page.listGlossaries.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.cloud.translation.v3beta1.IGlossary[] = []; + const iterable = client.listGlossariesAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listGlossaries.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listGlossaries.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('matchProjectFromLocationName', () => { - const result = client.matchProjectFromLocationName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.locationPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('uses async iteration with listGlossaries with error', async () => { + const client = + new translationserviceModule.v3beta1.TranslationServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.ListGlossariesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.translation.v3beta1.ListGlossariesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listGlossaries.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listGlossariesAsync(request); + await assert.rejects(async () => { + const responses: protos.google.cloud.translation.v3beta1.IGlossary[] = + []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listGlossaries.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listGlossaries.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + }); + + describe('Path templates', () => { + describe('glossary', async () => { + const fakePath = '/rendered/path/glossary'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + glossary: 'glossaryValue', + }; + const client = + new translationserviceModule.v3beta1.TranslationServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.glossaryPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.glossaryPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('glossaryPath', () => { + const result = client.glossaryPath( + 'projectValue', + 'locationValue', + 'glossaryValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.glossaryPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromGlossaryName', () => { + const result = client.matchProjectFromGlossaryName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.glossaryPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromGlossaryName', () => { + const result = client.matchLocationFromGlossaryName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.glossaryPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchGlossaryFromGlossaryName', () => { + const result = client.matchGlossaryFromGlossaryName(fakePath); + assert.strictEqual(result, 'glossaryValue'); + assert( + (client.pathTemplates.glossaryPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchLocationFromLocationName', () => { - const result = client.matchLocationFromLocationName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.locationPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('location', async () => { + const fakePath = '/rendered/path/location'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + }; + const client = + new translationserviceModule.v3beta1.TranslationServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + client.pathTemplates.locationPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.locationPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('locationPath', () => { + const result = client.locationPath('projectValue', 'locationValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.locationPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromLocationName', () => { + const result = client.matchProjectFromLocationName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.locationPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromLocationName', () => { + const result = client.matchLocationFromLocationName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.locationPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/core/generator/gapic-generator-typescript/baselines/videointelligence-esm/esm/src/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/videointelligence-esm/esm/src/index.ts.baseline index 94bfb1455d5a..fe7613685e34 100644 --- a/core/generator/gapic-generator-typescript/baselines/videointelligence-esm/esm/src/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/videointelligence-esm/esm/src/index.ts.baseline @@ -19,8 +19,8 @@ import * as v1 from './v1/index.js'; const VideoIntelligenceServiceClient = v1.VideoIntelligenceServiceClient; type VideoIntelligenceServiceClient = v1.VideoIntelligenceServiceClient; -export {v1, VideoIntelligenceServiceClient}; -export default {v1, VideoIntelligenceServiceClient}; +export { v1, VideoIntelligenceServiceClient }; +export default { v1, VideoIntelligenceServiceClient }; // @ts-ignore import * as protos from '../../protos/protos.js'; -export {protos} +export { protos }; diff --git a/core/generator/gapic-generator-typescript/baselines/videointelligence-esm/esm/src/v1/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/videointelligence-esm/esm/src/v1/index.ts.baseline index 3c3a4b4f051b..b98ab31bdcbe 100644 --- a/core/generator/gapic-generator-typescript/baselines/videointelligence-esm/esm/src/v1/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/videointelligence-esm/esm/src/v1/index.ts.baseline @@ -16,4 +16,4 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -export {VideoIntelligenceServiceClient} from './video_intelligence_service_client.js'; +export { VideoIntelligenceServiceClient } from './video_intelligence_service_client.js'; diff --git a/core/generator/gapic-generator-typescript/baselines/videointelligence-esm/esm/src/v1/video_intelligence_service_client.ts.baseline b/core/generator/gapic-generator-typescript/baselines/videointelligence-esm/esm/src/v1/video_intelligence_service_client.ts.baseline index 914ef9875f89..8d402646a1e9 100644 --- a/core/generator/gapic-generator-typescript/baselines/videointelligence-esm/esm/src/v1/video_intelligence_service_client.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/videointelligence-esm/esm/src/v1/video_intelligence_service_client.ts.baseline @@ -18,15 +18,22 @@ /* global window */ import * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions, GrpcClientOptions, LROperation} from 'google-gax'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + GrpcClientOptions, + LROperation, +} from 'google-gax'; // @ts-ignore import type * as protos from '../../../protos/protos.js'; import * as video_intelligence_service_client_config from './video_intelligence_service_client_config.json'; import fs from 'fs'; import path from 'path'; -import {fileURLToPath} from 'url'; -import {getJSON} from '../json-helper.cjs'; +import { fileURLToPath } from 'url'; +import { getJSON } from '../json-helper.cjs'; // @ts-ignore const dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -36,15 +43,15 @@ const dirname = path.dirname(fileURLToPath(import.meta.url)); * This file defines retry strategy and timeouts for all API methods in this library. */ const gapicConfig = getJSON( - path.join(dirname, 'video_intelligence_service_client_config.json') + path.join(dirname, 'video_intelligence_service_client_config.json'), ); const jsonProtos = getJSON( - path.join(dirname, '..', '..', '..', 'protos/protos.json') + path.join(dirname, '..', '..', '..', 'protos/protos.json'), ); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; const version = getJSON( - path.join(dirname, '..', '..', '..', '..', 'package.json') + path.join(dirname, '..', '..', '..', '..', 'package.json'), ).version; /** @@ -59,7 +66,7 @@ export class VideoIntelligenceServiceClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('videointelligence'); @@ -71,9 +78,9 @@ export class VideoIntelligenceServiceClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; + innerApiCalls: { [name: string]: Function }; operationsClient: gax.OperationsClient; - videoIntelligenceServiceStub?: Promise<{[name: string]: Function}>; + videoIntelligenceServiceStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of VideoIntelligenceServiceClient. @@ -115,21 +122,43 @@ export class VideoIntelligenceServiceClient { * const client = new VideoIntelligenceServiceClient({fallback: 'rest'}, gax); * ``` */ - constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { // Ensure that options include all the required fields. - const staticMembers = this.constructor as typeof VideoIntelligenceServiceClient; - if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { - throw new Error('Please set either universe_domain or universeDomain, but not both.'); + const staticMembers = this + .constructor as typeof VideoIntelligenceServiceClient; + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); } - const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; - this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; this._servicePath = 'videointelligence.' + this._universeDomain; - const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; - const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. if (servicePath !== this._servicePath && !('scopes' in opts)) { @@ -151,7 +180,7 @@ export class VideoIntelligenceServiceClient { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; @@ -168,10 +197,7 @@ export class VideoIntelligenceServiceClient { const isEsm = true; const isEsmString = isEsm ? '-esm' : '-cjs'; // Determine the client header string. - const clientHeader = [ - `gax/${this._gaxModule.version}`, - `gapic/${version}`, - ]; + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/{process.versions.node}${isEsmString}`); } else { @@ -179,7 +205,7 @@ export class VideoIntelligenceServiceClient { } if (!opts.fallback) { clientHeader.push(`grpc/${this._gaxGrpc.grpcVersion}`); - } else if (opts.fallback === 'rest' ) { + } else if (opts.fallback === 'rest') { clientHeader.push(`rest/${this._gaxGrpc.grpcVersion}`); } if (opts.libName && opts.libVersion) { @@ -187,7 +213,9 @@ export class VideoIntelligenceServiceClient { } // Load the applicable protos. - this._protos = this._gaxGrpc.loadProtoJSON(jsonProtos as gax.protobuf.INamespace); + this._protos = this._gaxGrpc.loadProtoJSON( + jsonProtos as gax.protobuf.INamespace, + ); const protoFilesRoot = this._gaxModule.protobufFromJSON(jsonProtos); // This API contains "long-running operations", which return a @@ -195,29 +223,37 @@ export class VideoIntelligenceServiceClient { // rather than holding a request open. const lroOptions: GrpcClientOptions = { auth: this.auth, - grpc: 'grpc' in this._gaxGrpc ? this._gaxGrpc.grpc : undefined + grpc: 'grpc' in this._gaxGrpc ? this._gaxGrpc.grpc : undefined, }; if (opts.fallback === 'rest') { lroOptions.protoJson = protoFilesRoot; lroOptions.httpRules = []; } - this.operationsClient = this._gaxModule.lro(lroOptions).operationsClient(opts); + this.operationsClient = this._gaxModule + .lro(lroOptions) + .operationsClient(opts); const annotateVideoResponse = protoFilesRoot.lookup( - '.google.cloud.videointelligence.v1.AnnotateVideoResponse') as gax.protobuf.Type; + '.google.cloud.videointelligence.v1.AnnotateVideoResponse', + ) as gax.protobuf.Type; const annotateVideoMetadata = protoFilesRoot.lookup( - '.google.cloud.videointelligence.v1.AnnotateVideoProgress') as gax.protobuf.Type; + '.google.cloud.videointelligence.v1.AnnotateVideoProgress', + ) as gax.protobuf.Type; this.descriptors.longrunning = { annotateVideo: new this._gaxModule.LongrunningDescriptor( this.operationsClient, annotateVideoResponse.decode.bind(annotateVideoResponse), - annotateVideoMetadata.decode.bind(annotateVideoMetadata)) + annotateVideoMetadata.decode.bind(annotateVideoMetadata), + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.cloud.videointelligence.v1.VideoIntelligenceService', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.cloud.videointelligence.v1.VideoIntelligenceService', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + { 'x-goog-api-client': clientHeader.join(' ') }, + ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -248,37 +284,41 @@ export class VideoIntelligenceServiceClient { // Put together the "service stub" for // google.cloud.videointelligence.v1.VideoIntelligenceService. this.videoIntelligenceServiceStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.cloud.videointelligence.v1.VideoIntelligenceService') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any - (this._protos as any).google.cloud.videointelligence.v1.VideoIntelligenceService, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.cloud.videointelligence.v1.VideoIntelligenceService', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any + (this._protos as any).google.cloud.videointelligence.v1 + .VideoIntelligenceService, + this._opts, + this._providedCustomServicePath, + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const videoIntelligenceServiceStubMethods = - ['annotateVideo']; + const videoIntelligenceServiceStubMethods = ['annotateVideo']; for (const methodName of videoIntelligenceServiceStubMethods) { const callPromise = this.videoIntelligenceServiceStub.then( - stub => (...args: Array<{}>) => { - if (this._terminated) { - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error|null|undefined) => () => { + (stub) => + (...args: Array<{}>) => { + if (this._terminated) { + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { throw err; - }); + }, + ); - const descriptor = - this.descriptors.longrunning[methodName] || - undefined; + const descriptor = this.descriptors.longrunning[methodName] || undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -293,8 +333,14 @@ export class VideoIntelligenceServiceClient { * @returns {string} The DNS address for this service. */ static get servicePath() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'videointelligence.googleapis.com'; } @@ -306,8 +352,14 @@ export class VideoIntelligenceServiceClient { * @returns {string} The DNS address for this service. */ static get apiEndpoint() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'videointelligence.googleapis.com'; } @@ -338,9 +390,7 @@ export class VideoIntelligenceServiceClient { * @returns {string[]} List of default scopes. */ static get scopes() { - return [ - 'https://www.googleapis.com/auth/cloud-platform' - ]; + return ['https://www.googleapis.com/auth/cloud-platform']; } getProjectId(): Promise; @@ -349,8 +399,9 @@ export class VideoIntelligenceServiceClient { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId(callback?: Callback): - Promise|void { + getProjectId( + callback?: Callback, + ): Promise | void { if (callback) { this.auth.getProjectId(callback); return; @@ -362,138 +413,201 @@ export class VideoIntelligenceServiceClient { // -- Service calls -- // ------------------- -/** - * Performs asynchronous video annotation. Progress and results can be - * retrieved through the `google.longrunning.Operations` interface. - * `Operation.metadata` contains `AnnotateVideoProgress` (progress). - * `Operation.response` contains `AnnotateVideoResponse` (results). - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.inputUri - * Input video location. Currently, only - * [Google Cloud Storage](https://cloud.google.com/storage/) URIs are - * supported, which must be specified in the following format: - * `gs://bucket-id/object-id` (other URI formats return - * {@link protos.google.rpc.Code.INVALID_ARGUMENT|google.rpc.Code.INVALID_ARGUMENT}). For more information, see - * [Request URIs](https://cloud.google.com/storage/docs/request-endpoints). - * A video URI may include wildcards in `object-id`, and thus identify - * multiple videos. Supported wildcards: '*' to match 0 or more characters; - * '?' to match 1 character. If unset, the input video should be embedded - * in the request as `input_content`. If set, `input_content` should be unset. - * @param {Buffer} request.inputContent - * The video data bytes. - * If unset, the input video(s) should be specified via `input_uri`. - * If set, `input_uri` should be unset. - * @param {number[]} request.features - * Required. Requested video annotation features. - * @param {google.cloud.videointelligence.v1.VideoContext} request.videoContext - * Additional video context and/or feature-specific parameters. - * @param {string} [request.outputUri] - * Optional. Location where the output (in JSON format) should be stored. - * Currently, only [Google Cloud Storage](https://cloud.google.com/storage/) - * URIs are supported, which must be specified in the following format: - * `gs://bucket-id/object-id` (other URI formats return - * {@link protos.google.rpc.Code.INVALID_ARGUMENT|google.rpc.Code.INVALID_ARGUMENT}). For more information, see - * [Request URIs](https://cloud.google.com/storage/docs/request-endpoints). - * @param {string} [request.locationId] - * Optional. Cloud region where annotation should take place. Supported cloud - * regions: `us-east1`, `us-west1`, `europe-west1`, `asia-east1`. If no region - * is specified, a region will be determined based on video file location. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing - * a long running operation. Its `promise()` method returns a promise - * you can `await` for. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v1/video_intelligence_service.annotate_video.js - * region_tag:videointelligence_v1_generated_VideoIntelligenceService_AnnotateVideo_async - */ + /** + * Performs asynchronous video annotation. Progress and results can be + * retrieved through the `google.longrunning.Operations` interface. + * `Operation.metadata` contains `AnnotateVideoProgress` (progress). + * `Operation.response` contains `AnnotateVideoResponse` (results). + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.inputUri + * Input video location. Currently, only + * [Google Cloud Storage](https://cloud.google.com/storage/) URIs are + * supported, which must be specified in the following format: + * `gs://bucket-id/object-id` (other URI formats return + * {@link protos.google.rpc.Code.INVALID_ARGUMENT|google.rpc.Code.INVALID_ARGUMENT}). For more information, see + * [Request URIs](https://cloud.google.com/storage/docs/request-endpoints). + * A video URI may include wildcards in `object-id`, and thus identify + * multiple videos. Supported wildcards: '*' to match 0 or more characters; + * '?' to match 1 character. If unset, the input video should be embedded + * in the request as `input_content`. If set, `input_content` should be unset. + * @param {Buffer} request.inputContent + * The video data bytes. + * If unset, the input video(s) should be specified via `input_uri`. + * If set, `input_uri` should be unset. + * @param {number[]} request.features + * Required. Requested video annotation features. + * @param {google.cloud.videointelligence.v1.VideoContext} request.videoContext + * Additional video context and/or feature-specific parameters. + * @param {string} [request.outputUri] + * Optional. Location where the output (in JSON format) should be stored. + * Currently, only [Google Cloud Storage](https://cloud.google.com/storage/) + * URIs are supported, which must be specified in the following format: + * `gs://bucket-id/object-id` (other URI formats return + * {@link protos.google.rpc.Code.INVALID_ARGUMENT|google.rpc.Code.INVALID_ARGUMENT}). For more information, see + * [Request URIs](https://cloud.google.com/storage/docs/request-endpoints). + * @param {string} [request.locationId] + * Optional. Cloud region where annotation should take place. Supported cloud + * regions: `us-east1`, `us-west1`, `europe-west1`, `asia-east1`. If no region + * is specified, a region will be determined based on video file location. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v1/video_intelligence_service.annotate_video.js + * region_tag:videointelligence_v1_generated_VideoIntelligenceService_AnnotateVideo_async + */ annotateVideo( - request?: protos.google.cloud.videointelligence.v1.IAnnotateVideoRequest, - options?: CallOptions): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>; + request?: protos.google.cloud.videointelligence.v1.IAnnotateVideoRequest, + options?: CallOptions, + ): Promise< + [ + LROperation< + protos.google.cloud.videointelligence.v1.IAnnotateVideoResponse, + protos.google.cloud.videointelligence.v1.IAnnotateVideoProgress + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; annotateVideo( - request: protos.google.cloud.videointelligence.v1.IAnnotateVideoRequest, - options: CallOptions, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.videointelligence.v1.IAnnotateVideoRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.cloud.videointelligence.v1.IAnnotateVideoResponse, + protos.google.cloud.videointelligence.v1.IAnnotateVideoProgress + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; annotateVideo( - request: protos.google.cloud.videointelligence.v1.IAnnotateVideoRequest, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.videointelligence.v1.IAnnotateVideoRequest, + callback: Callback< + LROperation< + protos.google.cloud.videointelligence.v1.IAnnotateVideoResponse, + protos.google.cloud.videointelligence.v1.IAnnotateVideoProgress + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; annotateVideo( - request?: protos.google.cloud.videointelligence.v1.IAnnotateVideoRequest, - optionsOrCallback?: CallOptions|Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>, - callback?: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>|void { + request?: protos.google.cloud.videointelligence.v1.IAnnotateVideoRequest, + optionsOrCallback?: + | CallOptions + | Callback< + LROperation< + protos.google.cloud.videointelligence.v1.IAnnotateVideoResponse, + protos.google.cloud.videointelligence.v1.IAnnotateVideoProgress + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + callback?: Callback< + LROperation< + protos.google.cloud.videointelligence.v1.IAnnotateVideoResponse, + protos.google.cloud.videointelligence.v1.IAnnotateVideoProgress + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + LROperation< + protos.google.cloud.videointelligence.v1.IAnnotateVideoResponse, + protos.google.cloud.videointelligence.v1.IAnnotateVideoProgress + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize().catch(err => {throw err}); - const wrappedCallback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>|undefined = callback + this.initialize().catch((err) => { + throw err; + }); + const wrappedCallback: + | Callback< + LROperation< + protos.google.cloud.videointelligence.v1.IAnnotateVideoResponse, + protos.google.cloud.videointelligence.v1.IAnnotateVideoProgress + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, rawResponse, _) => { this._log.info('annotateVideo response %j', rawResponse); callback!(error, response, rawResponse, _); // We verified `callback` above. } : undefined; this._log.info('annotateVideo request %j', request); - return this.innerApiCalls.annotateVideo(request, options, wrappedCallback) - ?.then(([response, rawResponse, _]: [ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]) => { - this._log.info('annotateVideo response %j', rawResponse); - return [response, rawResponse, _]; - }); + return this.innerApiCalls + .annotateVideo(request, options, wrappedCallback) + ?.then( + ([response, rawResponse, _]: [ + LROperation< + protos.google.cloud.videointelligence.v1.IAnnotateVideoResponse, + protos.google.cloud.videointelligence.v1.IAnnotateVideoProgress + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ]) => { + this._log.info('annotateVideo response %j', rawResponse); + return [response, rawResponse, _]; + }, + ); } -/** - * Check the status of the long running operation returned by `annotateVideo()`. - * @param {String} name - * The operation name that will be passed. - * @returns {Promise} - The promise which resolves to an object. - * The decoded operation object has result and metadata field to get information from. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v1/video_intelligence_service.annotate_video.js - * region_tag:videointelligence_v1_generated_VideoIntelligenceService_AnnotateVideo_async - */ - async checkAnnotateVideoProgress(name: string): Promise>{ + /** + * Check the status of the long running operation returned by `annotateVideo()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v1/video_intelligence_service.annotate_video.js + * region_tag:videointelligence_v1_generated_VideoIntelligenceService_AnnotateVideo_async + */ + async checkAnnotateVideoProgress( + name: string, + ): Promise< + LROperation< + protos.google.cloud.videointelligence.v1.AnnotateVideoResponse, + protos.google.cloud.videointelligence.v1.AnnotateVideoProgress + > + > { this._log.info('annotateVideo long-running'); - const request = new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest({name}); + const request = + new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( + { name }, + ); const [operation] = await this.operationsClient.getOperation(request); - const decodeOperation = new this._gaxModule.Operation(operation, this.descriptors.longrunning.annotateVideo, this._gaxModule.createDefaultBackoffSettings()); - return decodeOperation as LROperation; + const decodeOperation = new this._gaxModule.Operation( + operation, + this.descriptors.longrunning.annotateVideo, + this._gaxModule.createDefaultBackoffSettings(), + ); + return decodeOperation as LROperation< + protos.google.cloud.videointelligence.v1.AnnotateVideoResponse, + protos.google.cloud.videointelligence.v1.AnnotateVideoProgress + >; } /** @@ -504,7 +618,7 @@ export class VideoIntelligenceServiceClient { */ close(): Promise { if (this.videoIntelligenceServiceStub && !this._terminated) { - return this.videoIntelligenceServiceStub.then(stub => { + return this.videoIntelligenceServiceStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -513,4 +627,4 @@ export class VideoIntelligenceServiceClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/core/generator/gapic-generator-typescript/baselines/videointelligence-esm/esm/system-test/fixtures/sample/src/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/videointelligence-esm/esm/system-test/fixtures/sample/src/index.ts.baseline index 407f139c34e0..99074b29b663 100644 --- a/core/generator/gapic-generator-typescript/baselines/videointelligence-esm/esm/system-test/fixtures/sample/src/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/videointelligence-esm/esm/system-test/fixtures/sample/src/index.ts.baseline @@ -17,10 +17,12 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -import {VideoIntelligenceServiceClient} from 'videointelligence'; +import { VideoIntelligenceServiceClient } from 'videointelligence'; // check that the client class type name can be used -function doStuffWithVideoIntelligenceServiceClient(client: VideoIntelligenceServiceClient) { +function doStuffWithVideoIntelligenceServiceClient( + client: VideoIntelligenceServiceClient, +) { client.close(); } diff --git a/core/generator/gapic-generator-typescript/baselines/videointelligence-esm/esm/system-test/install.ts.baseline b/core/generator/gapic-generator-typescript/baselines/videointelligence-esm/esm/system-test/install.ts.baseline index e079c4fa1101..d109fdd8c97f 100644 --- a/core/generator/gapic-generator-typescript/baselines/videointelligence-esm/esm/system-test/install.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/videointelligence-esm/esm/system-test/install.ts.baseline @@ -16,40 +16,45 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -import {packNTest} from 'pack-n-play'; -import {readFileSync} from 'fs'; -import {describe, it} from 'mocha'; +import { packNTest } from 'pack-n-play'; +import { readFileSync } from 'fs'; +import { describe, it } from 'mocha'; describe('📦 pack-n-play test', () => { - it('TypeScript', async function() { + it('TypeScript', async function () { this.timeout(300000); await packNTest({ packageDir: process.cwd(), sample: { description: 'TypeScript user can use the type definitions', - ts: readFileSync('./esm/system-test/fixtures/sample/src/index.ts').toString() - } + ts: readFileSync( + './esm/system-test/fixtures/sample/src/index.ts', + ).toString(), + }, }); }); - it('ESM module', async function() { + it('ESM module', async function () { this.timeout(300000); await packNTest({ sample: { description: 'Should be able to import using ESM', - esm: readFileSync('./esm/system-test/fixtures/sample/src/index.js').toString(), + esm: readFileSync( + './esm/system-test/fixtures/sample/src/index.js', + ).toString(), }, }); }); - it('CJS module', async function() { + it('CJS module', async function () { this.timeout(300000); await packNTest({ sample: { description: 'Should be able to import using CJS', - cjs: readFileSync('./esm/system-test/fixtures/sample/src/index.cjs').toString(), + cjs: readFileSync( + './esm/system-test/fixtures/sample/src/index.cjs', + ).toString(), }, }); }); - }); diff --git a/core/generator/gapic-generator-typescript/baselines/videointelligence-esm/esm/test/gapic_video_intelligence_service_v1.ts.baseline b/core/generator/gapic-generator-typescript/baselines/videointelligence-esm/esm/test/gapic_video_intelligence_service_v1.ts.baseline index 3c1ab593ac37..e1add5ead4a6 100644 --- a/core/generator/gapic-generator-typescript/baselines/videointelligence-esm/esm/test/gapic_video_intelligence_service_v1.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/videointelligence-esm/esm/test/gapic_video_intelligence_service_v1.ts.baseline @@ -20,14 +20,14 @@ import * as protos from '../../protos/protos.js'; import assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as videointelligenceserviceModule from '../src/index.js'; -import {protobuf, LROperation, operationsProtos} from 'google-gax'; +import { protobuf, LROperation, operationsProtos } from 'google-gax'; import fs from 'fs'; import path from 'path'; -import {fileURLToPath} from 'url'; +import { fileURLToPath } from 'url'; // @ts-ignore const dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -35,315 +35,419 @@ const dirname = path.dirname(fileURLToPath(import.meta.url)); // to fill in default values for request objects const root = protobuf.Root.fromJSON( JSON.parse( - fs.readFileSync(path.join(dirname, '..', '..', 'protos/protos.json'), 'utf8') - )) + fs.readFileSync( + path.join(dirname, '..', '..', 'protos/protos.json'), + 'utf8', + ), + ), +); // eslint-disable-next-line @typescript-eslint/no-unused-vars function getTypeDefaultValue(typeName: string, fields: string[]) { - let type = root.lookupType(typeName) as protobuf.Type; - for (const field of fields.slice(0, -1)) { - type = type?.fields[field]?.resolvedType as protobuf.Type; - } - return type?.fields[fields[fields.length - 1]]?.defaultValue ?? null; + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type?.fields[field]?.resolvedType as protobuf.Type; + } + return type?.fields[fields[fields.length - 1]]?.defaultValue ?? null; } function generateSampleMessage(instance: T) { - const filledObject = (instance.constructor as typeof protobuf.Message) - .toObject(instance as protobuf.Message, {defaults: true}); - return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, { defaults: true }); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; } function stubSimpleCall(response?: ResponseType, error?: Error) { - return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); } -function stubLongRunningCall(response?: ResponseType, callError?: Error, lroError?: Error) { - const innerStub = lroError ? sinon.stub().rejects(lroError) : sinon.stub().resolves([response]); - const mockOperation = { - promise: innerStub, - }; - return callError ? sinon.stub().rejects(callError) : sinon.stub().resolves([mockOperation]); +function stubLongRunningCall( + response?: ResponseType, + callError?: Error, + lroError?: Error, +) { + const innerStub = lroError + ? sinon.stub().rejects(lroError) + : sinon.stub().resolves([response]); + const mockOperation = { + promise: innerStub, + }; + return callError + ? sinon.stub().rejects(callError) + : sinon.stub().resolves([mockOperation]); } -function stubLongRunningCallWithCallback(response?: ResponseType, callError?: Error, lroError?: Error) { - const innerStub = lroError ? sinon.stub().rejects(lroError) : sinon.stub().resolves([response]); - const mockOperation = { - promise: innerStub, - }; - return callError ? sinon.stub().callsArgWith(2, callError) : sinon.stub().callsArgWith(2, null, mockOperation); +function stubLongRunningCallWithCallback( + response?: ResponseType, + callError?: Error, + lroError?: Error, +) { + const innerStub = lroError + ? sinon.stub().rejects(lroError) + : sinon.stub().resolves([response]); + const mockOperation = { + promise: innerStub, + }; + return callError + ? sinon.stub().callsArgWith(2, callError) + : sinon.stub().callsArgWith(2, null, mockOperation); } describe('v1.VideoIntelligenceServiceClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new videointelligenceserviceModule.v1.VideoIntelligenceServiceClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'videointelligence.googleapis.com'); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = + new videointelligenceserviceModule.v1.VideoIntelligenceServiceClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'videointelligence.googleapis.com'); + }); - it('has universeDomain', () => { - const client = new videointelligenceserviceModule.v1.VideoIntelligenceServiceClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); + it('has universeDomain', () => { + const client = + new videointelligenceserviceModule.v1.VideoIntelligenceServiceClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - it('throws DeprecationWarning if static servicePath is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const servicePath = videointelligenceserviceModule.v1.VideoIntelligenceServiceClient.servicePath; - assert.strictEqual(servicePath, 'videointelligence.googleapis.com'); - assert(stub.called); - stub.restore(); - }); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = + videointelligenceserviceModule.v1.VideoIntelligenceServiceClient + .servicePath; + assert.strictEqual(servicePath, 'videointelligence.googleapis.com'); + assert(stub.called); + stub.restore(); + }); - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = videointelligenceserviceModule.v1.VideoIntelligenceServiceClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'videointelligence.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new videointelligenceserviceModule.v1.VideoIntelligenceServiceClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'videointelligence.example.com'); + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + videointelligenceserviceModule.v1.VideoIntelligenceServiceClient + .apiEndpoint; + assert.strictEqual(apiEndpoint, 'videointelligence.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = + new videointelligenceserviceModule.v1.VideoIntelligenceServiceClient({ + universeDomain: 'example.com', }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'videointelligence.example.com'); + }); - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new videointelligenceserviceModule.v1.VideoIntelligenceServiceClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'videointelligence.example.com'); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = + new videointelligenceserviceModule.v1.VideoIntelligenceServiceClient({ + universe_domain: 'example.com', }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'videointelligence.example.com'); + }); - if (typeof process === 'object' && 'env' in process) { - describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { - it('sets apiEndpoint from environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new videointelligenceserviceModule.v1.VideoIntelligenceServiceClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'videointelligence.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - - it('value configured in code has priority over environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new videointelligenceserviceModule.v1.VideoIntelligenceServiceClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'videointelligence.configured.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { new videointelligenceserviceModule.v1.VideoIntelligenceServiceClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); + if (typeof process === 'object' && 'env' in process) { + describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { + it('sets apiEndpoint from environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = + new videointelligenceserviceModule.v1.VideoIntelligenceServiceClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'videointelligence.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - it('has port', () => { - const port = videointelligenceserviceModule.v1.VideoIntelligenceServiceClient.port; - assert(port); - assert(typeof port === 'number'); + it('value configured in code has priority over environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = + new videointelligenceserviceModule.v1.VideoIntelligenceServiceClient( + { universeDomain: 'configured.example.com' }, + ); + const servicePath = client.apiEndpoint; + assert.strictEqual( + servicePath, + 'videointelligence.configured.example.com', + ); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - - it('should create a client with no option', () => { - const client = new videointelligenceserviceModule.v1.VideoIntelligenceServiceClient(); - assert(client); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new videointelligenceserviceModule.v1.VideoIntelligenceServiceClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); + }); - it('should create a client with gRPC fallback', () => { - const client = new videointelligenceserviceModule.v1.VideoIntelligenceServiceClient({ - fallback: true, - }); - assert(client); - }); + it('has port', () => { + const port = + videointelligenceserviceModule.v1.VideoIntelligenceServiceClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('has initialize method and supports deferred initialization', async () => { - const client = new videointelligenceserviceModule.v1.VideoIntelligenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.videoIntelligenceServiceStub, undefined); - await client.initialize(); - assert(client.videoIntelligenceServiceStub); + it('should create a client with no option', () => { + const client = + new videointelligenceserviceModule.v1.VideoIntelligenceServiceClient(); + assert(client); + }); + + it('should create a client with gRPC fallback', () => { + const client = + new videointelligenceserviceModule.v1.VideoIntelligenceServiceClient({ + fallback: true, }); + assert(client); + }); - it('has close method for the initialized client', done => { - const client = new videointelligenceserviceModule.v1.VideoIntelligenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.videoIntelligenceServiceStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); + it('has initialize method and supports deferred initialization', async () => { + const client = + new videointelligenceserviceModule.v1.VideoIntelligenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + assert.strictEqual(client.videoIntelligenceServiceStub, undefined); + await client.initialize(); + assert(client.videoIntelligenceServiceStub); + }); - it('has close method for the non-initialized client', done => { - const client = new videointelligenceserviceModule.v1.VideoIntelligenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.videoIntelligenceServiceStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); + it('has close method for the initialized client', (done) => { + const client = + new videointelligenceserviceModule.v1.VideoIntelligenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.videoIntelligenceServiceStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new videointelligenceserviceModule.v1.VideoIntelligenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + it('has close method for the non-initialized client', (done) => { + const client = + new videointelligenceserviceModule.v1.VideoIntelligenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.videoIntelligenceServiceStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new videointelligenceserviceModule.v1.VideoIntelligenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId((err?: Error|null, projectId?: string|null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } - }); - }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = + new videointelligenceserviceModule.v1.VideoIntelligenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); }); - describe('annotateVideo', () => { - it('invokes annotateVideo without error', async () => { - const client = new videointelligenceserviceModule.v1.VideoIntelligenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.videointelligence.v1.AnnotateVideoRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.annotateVideo = stubLongRunningCall(expectedResponse); - const [operation] = await client.annotateVideo(request); - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = + new videointelligenceserviceModule.v1.VideoIntelligenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } + }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + }); - it('invokes annotateVideo without error using callback', async () => { - const client = new videointelligenceserviceModule.v1.VideoIntelligenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.videointelligence.v1.AnnotateVideoRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.annotateVideo = stubLongRunningCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.annotateVideo( - request, - (err?: Error|null, - result?: LROperation|null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const operation = await promise as LROperation; - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); + describe('annotateVideo', () => { + it('invokes annotateVideo without error', async () => { + const client = + new videointelligenceserviceModule.v1.VideoIntelligenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.videointelligence.v1.AnnotateVideoRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.annotateVideo = + stubLongRunningCall(expectedResponse); + const [operation] = await client.annotateVideo(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes annotateVideo with call error', async () => { - const client = new videointelligenceserviceModule.v1.VideoIntelligenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.videointelligence.v1.AnnotateVideoRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.annotateVideo = stubLongRunningCall(undefined, expectedError); - await assert.rejects(client.annotateVideo(request), expectedError); + it('invokes annotateVideo without error using callback', async () => { + const client = + new videointelligenceserviceModule.v1.VideoIntelligenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.videointelligence.v1.AnnotateVideoRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.annotateVideo = + stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.annotateVideo( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.cloud.videointelligence.v1.IAnnotateVideoResponse, + protos.google.cloud.videointelligence.v1.IAnnotateVideoProgress + > | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const operation = (await promise) as LROperation< + protos.google.cloud.videointelligence.v1.IAnnotateVideoResponse, + protos.google.cloud.videointelligence.v1.IAnnotateVideoProgress + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes annotateVideo with LRO error', async () => { - const client = new videointelligenceserviceModule.v1.VideoIntelligenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.videointelligence.v1.AnnotateVideoRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.annotateVideo = stubLongRunningCall(undefined, undefined, expectedError); - const [operation] = await client.annotateVideo(request); - await assert.rejects(operation.promise(), expectedError); + it('invokes annotateVideo with call error', async () => { + const client = + new videointelligenceserviceModule.v1.VideoIntelligenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.videointelligence.v1.AnnotateVideoRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.annotateVideo = stubLongRunningCall( + undefined, + expectedError, + ); + await assert.rejects(client.annotateVideo(request), expectedError); + }); - it('invokes checkAnnotateVideoProgress without error', async () => { - const client = new videointelligenceserviceModule.v1.VideoIntelligenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedResponse = generateSampleMessage( - new operationsProtos.google.longrunning.Operation() - ); - expectedResponse.name = 'test'; - expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; - expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')} + it('invokes annotateVideo with LRO error', async () => { + const client = + new videointelligenceserviceModule.v1.VideoIntelligenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.videointelligence.v1.AnnotateVideoRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.annotateVideo = stubLongRunningCall( + undefined, + undefined, + expectedError, + ); + const [operation] = await client.annotateVideo(request); + await assert.rejects(operation.promise(), expectedError); + }); - client.operationsClient.getOperation = stubSimpleCall(expectedResponse); - const decodedOperation = await client.checkAnnotateVideoProgress(expectedResponse.name); - assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); - assert(decodedOperation.metadata); - assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + it('invokes checkAnnotateVideoProgress without error', async () => { + const client = + new videointelligenceserviceModule.v1.VideoIntelligenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation(), + ); + expectedResponse.name = 'test'; + expectedResponse.response = { type_url: 'url', value: Buffer.from('') }; + expectedResponse.metadata = { type_url: 'url', value: Buffer.from('') }; - it('invokes checkAnnotateVideoProgress with error', async () => { - const client = new videointelligenceserviceModule.v1.VideoIntelligenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedError = new Error('expected'); + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const decodedOperation = await client.checkAnnotateVideoProgress( + expectedResponse.name, + ); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); - client.operationsClient.getOperation = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.checkAnnotateVideoProgress(''), expectedError); - assert((client.operationsClient.getOperation as SinonStub) - .getCall(0)); + it('invokes checkAnnotateVideoProgress with error', async () => { + const client = + new videointelligenceserviceModule.v1.VideoIntelligenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const expectedError = new Error('expected'); + + client.operationsClient.getOperation = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.checkAnnotateVideoProgress(''), + expectedError, + ); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); }); + }); }); diff --git a/core/generator/gapic-generator-typescript/baselines/videointelligence/src/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/videointelligence/src/index.ts.baseline index 94955370b3b4..7122a28f0b70 100644 --- a/core/generator/gapic-generator-typescript/baselines/videointelligence/src/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/videointelligence/src/index.ts.baseline @@ -19,7 +19,7 @@ import * as v1 from './v1'; const VideoIntelligenceServiceClient = v1.VideoIntelligenceServiceClient; type VideoIntelligenceServiceClient = v1.VideoIntelligenceServiceClient; -export {v1, VideoIntelligenceServiceClient}; -export default {v1, VideoIntelligenceServiceClient}; +export { v1, VideoIntelligenceServiceClient }; +export default { v1, VideoIntelligenceServiceClient }; import * as protos from '../protos/protos'; -export {protos} +export { protos }; diff --git a/core/generator/gapic-generator-typescript/baselines/videointelligence/src/v1/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/videointelligence/src/v1/index.ts.baseline index 063b4957f588..25d22d6bb29a 100644 --- a/core/generator/gapic-generator-typescript/baselines/videointelligence/src/v1/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/videointelligence/src/v1/index.ts.baseline @@ -16,4 +16,4 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -export {VideoIntelligenceServiceClient} from './video_intelligence_service_client'; +export { VideoIntelligenceServiceClient } from './video_intelligence_service_client'; diff --git a/core/generator/gapic-generator-typescript/baselines/videointelligence/src/v1/video_intelligence_service_client.ts.baseline b/core/generator/gapic-generator-typescript/baselines/videointelligence/src/v1/video_intelligence_service_client.ts.baseline index 671eea50e118..28043dbff74e 100644 --- a/core/generator/gapic-generator-typescript/baselines/videointelligence/src/v1/video_intelligence_service_client.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/videointelligence/src/v1/video_intelligence_service_client.ts.baseline @@ -18,11 +18,18 @@ /* global window */ import type * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions, GrpcClientOptions, LROperation} from 'google-gax'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + GrpcClientOptions, + LROperation, +} from 'google-gax'; import * as protos from '../../protos/protos'; import jsonProtos = require('../../protos/protos.json'); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; /** * Client JSON configuration object, loaded from @@ -44,7 +51,7 @@ export class VideoIntelligenceServiceClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('videointelligence'); @@ -57,9 +64,9 @@ export class VideoIntelligenceServiceClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; + innerApiCalls: { [name: string]: Function }; operationsClient: gax.OperationsClient; - videoIntelligenceServiceStub?: Promise<{[name: string]: Function}>; + videoIntelligenceServiceStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of VideoIntelligenceServiceClient. @@ -100,21 +107,43 @@ export class VideoIntelligenceServiceClient { * const client = new VideoIntelligenceServiceClient({fallback: true}, gax); * ``` */ - constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { // Ensure that options include all the required fields. - const staticMembers = this.constructor as typeof VideoIntelligenceServiceClient; - if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { - throw new Error('Please set either universe_domain or universeDomain, but not both.'); + const staticMembers = this + .constructor as typeof VideoIntelligenceServiceClient; + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); } - const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; - this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; this._servicePath = 'videointelligence.' + this._universeDomain; - const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; - const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. if (servicePath !== this._servicePath && !('scopes' in opts)) { @@ -136,7 +165,7 @@ export class VideoIntelligenceServiceClient { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; @@ -150,10 +179,7 @@ export class VideoIntelligenceServiceClient { } // Determine the client header string. - const clientHeader = [ - `gax/${this._gaxModule.version}`, - `gapic/${version}`, - ]; + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/${process.versions.node}`); } else { @@ -176,29 +202,37 @@ export class VideoIntelligenceServiceClient { // rather than holding a request open. const lroOptions: GrpcClientOptions = { auth: this.auth, - grpc: 'grpc' in this._gaxGrpc ? this._gaxGrpc.grpc : undefined + grpc: 'grpc' in this._gaxGrpc ? this._gaxGrpc.grpc : undefined, }; if (opts.fallback) { lroOptions.protoJson = protoFilesRoot; lroOptions.httpRules = []; } - this.operationsClient = this._gaxModule.lro(lroOptions).operationsClient(opts); + this.operationsClient = this._gaxModule + .lro(lroOptions) + .operationsClient(opts); const annotateVideoResponse = protoFilesRoot.lookup( - '.google.cloud.videointelligence.v1.AnnotateVideoResponse') as gax.protobuf.Type; + '.google.cloud.videointelligence.v1.AnnotateVideoResponse', + ) as gax.protobuf.Type; const annotateVideoMetadata = protoFilesRoot.lookup( - '.google.cloud.videointelligence.v1.AnnotateVideoProgress') as gax.protobuf.Type; + '.google.cloud.videointelligence.v1.AnnotateVideoProgress', + ) as gax.protobuf.Type; this.descriptors.longrunning = { annotateVideo: new this._gaxModule.LongrunningDescriptor( this.operationsClient, annotateVideoResponse.decode.bind(annotateVideoResponse), - annotateVideoMetadata.decode.bind(annotateVideoMetadata)) + annotateVideoMetadata.decode.bind(annotateVideoMetadata), + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.cloud.videointelligence.v1.VideoIntelligenceService', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.cloud.videointelligence.v1.VideoIntelligenceService', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + { 'x-goog-api-client': clientHeader.join(' ') }, + ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -229,37 +263,41 @@ export class VideoIntelligenceServiceClient { // Put together the "service stub" for // google.cloud.videointelligence.v1.VideoIntelligenceService. this.videoIntelligenceServiceStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.cloud.videointelligence.v1.VideoIntelligenceService') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any - (this._protos as any).google.cloud.videointelligence.v1.VideoIntelligenceService, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.cloud.videointelligence.v1.VideoIntelligenceService', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any + (this._protos as any).google.cloud.videointelligence.v1 + .VideoIntelligenceService, + this._opts, + this._providedCustomServicePath, + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const videoIntelligenceServiceStubMethods = - ['annotateVideo']; + const videoIntelligenceServiceStubMethods = ['annotateVideo']; for (const methodName of videoIntelligenceServiceStubMethods) { const callPromise = this.videoIntelligenceServiceStub.then( - stub => (...args: Array<{}>) => { - if (this._terminated) { - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error|null|undefined) => () => { + (stub) => + (...args: Array<{}>) => { + if (this._terminated) { + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { throw err; - }); + }, + ); - const descriptor = - this.descriptors.longrunning[methodName] || - undefined; + const descriptor = this.descriptors.longrunning[methodName] || undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -274,8 +312,14 @@ export class VideoIntelligenceServiceClient { * @returns {string} The DNS address for this service. */ static get servicePath() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'videointelligence.googleapis.com'; } @@ -286,8 +330,14 @@ export class VideoIntelligenceServiceClient { * @returns {string} The DNS address for this service. */ static get apiEndpoint() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); } return 'videointelligence.googleapis.com'; } @@ -318,9 +368,7 @@ export class VideoIntelligenceServiceClient { * @returns {string[]} List of default scopes. */ static get scopes() { - return [ - 'https://www.googleapis.com/auth/cloud-platform' - ]; + return ['https://www.googleapis.com/auth/cloud-platform']; } getProjectId(): Promise; @@ -329,8 +377,9 @@ export class VideoIntelligenceServiceClient { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId(callback?: Callback): - Promise|void { + getProjectId( + callback?: Callback, + ): Promise | void { if (callback) { this.auth.getProjectId(callback); return; @@ -342,138 +391,201 @@ export class VideoIntelligenceServiceClient { // -- Service calls -- // ------------------- -/** - * Performs asynchronous video annotation. Progress and results can be - * retrieved through the `google.longrunning.Operations` interface. - * `Operation.metadata` contains `AnnotateVideoProgress` (progress). - * `Operation.response` contains `AnnotateVideoResponse` (results). - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.inputUri - * Input video location. Currently, only - * [Google Cloud Storage](https://cloud.google.com/storage/) URIs are - * supported, which must be specified in the following format: - * `gs://bucket-id/object-id` (other URI formats return - * {@link protos.google.rpc.Code.INVALID_ARGUMENT|google.rpc.Code.INVALID_ARGUMENT}). For more information, see - * [Request URIs](https://cloud.google.com/storage/docs/request-endpoints). - * A video URI may include wildcards in `object-id`, and thus identify - * multiple videos. Supported wildcards: '*' to match 0 or more characters; - * '?' to match 1 character. If unset, the input video should be embedded - * in the request as `input_content`. If set, `input_content` should be unset. - * @param {Buffer} request.inputContent - * The video data bytes. - * If unset, the input video(s) should be specified via `input_uri`. - * If set, `input_uri` should be unset. - * @param {number[]} request.features - * Required. Requested video annotation features. - * @param {google.cloud.videointelligence.v1.VideoContext} request.videoContext - * Additional video context and/or feature-specific parameters. - * @param {string} [request.outputUri] - * Optional. Location where the output (in JSON format) should be stored. - * Currently, only [Google Cloud Storage](https://cloud.google.com/storage/) - * URIs are supported, which must be specified in the following format: - * `gs://bucket-id/object-id` (other URI formats return - * {@link protos.google.rpc.Code.INVALID_ARGUMENT|google.rpc.Code.INVALID_ARGUMENT}). For more information, see - * [Request URIs](https://cloud.google.com/storage/docs/request-endpoints). - * @param {string} [request.locationId] - * Optional. Cloud region where annotation should take place. Supported cloud - * regions: `us-east1`, `us-west1`, `europe-west1`, `asia-east1`. If no region - * is specified, a region will be determined based on video file location. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing - * a long running operation. Its `promise()` method returns a promise - * you can `await` for. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v1/video_intelligence_service.annotate_video.js - * region_tag:videointelligence_v1_generated_VideoIntelligenceService_AnnotateVideo_async - */ + /** + * Performs asynchronous video annotation. Progress and results can be + * retrieved through the `google.longrunning.Operations` interface. + * `Operation.metadata` contains `AnnotateVideoProgress` (progress). + * `Operation.response` contains `AnnotateVideoResponse` (results). + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.inputUri + * Input video location. Currently, only + * [Google Cloud Storage](https://cloud.google.com/storage/) URIs are + * supported, which must be specified in the following format: + * `gs://bucket-id/object-id` (other URI formats return + * {@link protos.google.rpc.Code.INVALID_ARGUMENT|google.rpc.Code.INVALID_ARGUMENT}). For more information, see + * [Request URIs](https://cloud.google.com/storage/docs/request-endpoints). + * A video URI may include wildcards in `object-id`, and thus identify + * multiple videos. Supported wildcards: '*' to match 0 or more characters; + * '?' to match 1 character. If unset, the input video should be embedded + * in the request as `input_content`. If set, `input_content` should be unset. + * @param {Buffer} request.inputContent + * The video data bytes. + * If unset, the input video(s) should be specified via `input_uri`. + * If set, `input_uri` should be unset. + * @param {number[]} request.features + * Required. Requested video annotation features. + * @param {google.cloud.videointelligence.v1.VideoContext} request.videoContext + * Additional video context and/or feature-specific parameters. + * @param {string} [request.outputUri] + * Optional. Location where the output (in JSON format) should be stored. + * Currently, only [Google Cloud Storage](https://cloud.google.com/storage/) + * URIs are supported, which must be specified in the following format: + * `gs://bucket-id/object-id` (other URI formats return + * {@link protos.google.rpc.Code.INVALID_ARGUMENT|google.rpc.Code.INVALID_ARGUMENT}). For more information, see + * [Request URIs](https://cloud.google.com/storage/docs/request-endpoints). + * @param {string} [request.locationId] + * Optional. Cloud region where annotation should take place. Supported cloud + * regions: `us-east1`, `us-west1`, `europe-west1`, `asia-east1`. If no region + * is specified, a region will be determined based on video file location. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v1/video_intelligence_service.annotate_video.js + * region_tag:videointelligence_v1_generated_VideoIntelligenceService_AnnotateVideo_async + */ annotateVideo( - request?: protos.google.cloud.videointelligence.v1.IAnnotateVideoRequest, - options?: CallOptions): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>; + request?: protos.google.cloud.videointelligence.v1.IAnnotateVideoRequest, + options?: CallOptions, + ): Promise< + [ + LROperation< + protos.google.cloud.videointelligence.v1.IAnnotateVideoResponse, + protos.google.cloud.videointelligence.v1.IAnnotateVideoProgress + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; annotateVideo( - request: protos.google.cloud.videointelligence.v1.IAnnotateVideoRequest, - options: CallOptions, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.videointelligence.v1.IAnnotateVideoRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.cloud.videointelligence.v1.IAnnotateVideoResponse, + protos.google.cloud.videointelligence.v1.IAnnotateVideoProgress + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; annotateVideo( - request: protos.google.cloud.videointelligence.v1.IAnnotateVideoRequest, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.cloud.videointelligence.v1.IAnnotateVideoRequest, + callback: Callback< + LROperation< + protos.google.cloud.videointelligence.v1.IAnnotateVideoResponse, + protos.google.cloud.videointelligence.v1.IAnnotateVideoProgress + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; annotateVideo( - request?: protos.google.cloud.videointelligence.v1.IAnnotateVideoRequest, - optionsOrCallback?: CallOptions|Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>, - callback?: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>|void { + request?: protos.google.cloud.videointelligence.v1.IAnnotateVideoRequest, + optionsOrCallback?: + | CallOptions + | Callback< + LROperation< + protos.google.cloud.videointelligence.v1.IAnnotateVideoResponse, + protos.google.cloud.videointelligence.v1.IAnnotateVideoProgress + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + callback?: Callback< + LROperation< + protos.google.cloud.videointelligence.v1.IAnnotateVideoResponse, + protos.google.cloud.videointelligence.v1.IAnnotateVideoProgress + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + LROperation< + protos.google.cloud.videointelligence.v1.IAnnotateVideoResponse, + protos.google.cloud.videointelligence.v1.IAnnotateVideoProgress + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize().catch(err => {throw err}); - const wrappedCallback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>|undefined = callback + this.initialize().catch((err) => { + throw err; + }); + const wrappedCallback: + | Callback< + LROperation< + protos.google.cloud.videointelligence.v1.IAnnotateVideoResponse, + protos.google.cloud.videointelligence.v1.IAnnotateVideoProgress + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, rawResponse, _) => { this._log.info('annotateVideo response %j', rawResponse); callback!(error, response, rawResponse, _); // We verified callback above. } : undefined; this._log.info('annotateVideo request %j', request); - return this.innerApiCalls.annotateVideo(request, options, wrappedCallback) - ?.then(([response, rawResponse, _]: [ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]) => { - this._log.info('annotateVideo response %j', rawResponse); - return [response, rawResponse, _]; - }); + return this.innerApiCalls + .annotateVideo(request, options, wrappedCallback) + ?.then( + ([response, rawResponse, _]: [ + LROperation< + protos.google.cloud.videointelligence.v1.IAnnotateVideoResponse, + protos.google.cloud.videointelligence.v1.IAnnotateVideoProgress + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ]) => { + this._log.info('annotateVideo response %j', rawResponse); + return [response, rawResponse, _]; + }, + ); } -/** - * Check the status of the long running operation returned by `annotateVideo()`. - * @param {String} name - * The operation name that will be passed. - * @returns {Promise} - The promise which resolves to an object. - * The decoded operation object has result and metadata field to get information from. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example include:samples/generated/v1/video_intelligence_service.annotate_video.js - * region_tag:videointelligence_v1_generated_VideoIntelligenceService_AnnotateVideo_async - */ - async checkAnnotateVideoProgress(name: string): Promise>{ + /** + * Check the status of the long running operation returned by `annotateVideo()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v1/video_intelligence_service.annotate_video.js + * region_tag:videointelligence_v1_generated_VideoIntelligenceService_AnnotateVideo_async + */ + async checkAnnotateVideoProgress( + name: string, + ): Promise< + LROperation< + protos.google.cloud.videointelligence.v1.AnnotateVideoResponse, + protos.google.cloud.videointelligence.v1.AnnotateVideoProgress + > + > { this._log.info('annotateVideo long-running'); - const request = new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest({name}); + const request = + new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( + { name }, + ); const [operation] = await this.operationsClient.getOperation(request); - const decodeOperation = new this._gaxModule.Operation(operation, this.descriptors.longrunning.annotateVideo, this._gaxModule.createDefaultBackoffSettings()); - return decodeOperation as LROperation; + const decodeOperation = new this._gaxModule.Operation( + operation, + this.descriptors.longrunning.annotateVideo, + this._gaxModule.createDefaultBackoffSettings(), + ); + return decodeOperation as LROperation< + protos.google.cloud.videointelligence.v1.AnnotateVideoResponse, + protos.google.cloud.videointelligence.v1.AnnotateVideoProgress + >; } /** @@ -484,7 +596,7 @@ export class VideoIntelligenceServiceClient { */ close(): Promise { if (this.videoIntelligenceServiceStub && !this._terminated) { - return this.videoIntelligenceServiceStub.then(stub => { + return this.videoIntelligenceServiceStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -493,4 +605,4 @@ export class VideoIntelligenceServiceClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/core/generator/gapic-generator-typescript/baselines/videointelligence/system-test/fixtures/sample/src/index.ts.baseline b/core/generator/gapic-generator-typescript/baselines/videointelligence/system-test/fixtures/sample/src/index.ts.baseline index 4b3782f73c52..d8129ffc2f81 100644 --- a/core/generator/gapic-generator-typescript/baselines/videointelligence/system-test/fixtures/sample/src/index.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/videointelligence/system-test/fixtures/sample/src/index.ts.baseline @@ -16,10 +16,12 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -import {VideoIntelligenceServiceClient} from 'videointelligence'; +import { VideoIntelligenceServiceClient } from 'videointelligence'; // check that the client class type name can be used -function doStuffWithVideoIntelligenceServiceClient(client: VideoIntelligenceServiceClient) { +function doStuffWithVideoIntelligenceServiceClient( + client: VideoIntelligenceServiceClient, +) { client.close(); } diff --git a/core/generator/gapic-generator-typescript/baselines/videointelligence/system-test/install.ts.baseline b/core/generator/gapic-generator-typescript/baselines/videointelligence/system-test/install.ts.baseline index f66069aa3940..ccf167042d2e 100644 --- a/core/generator/gapic-generator-typescript/baselines/videointelligence/system-test/install.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/videointelligence/system-test/install.ts.baseline @@ -16,34 +16,36 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -import {packNTest} from 'pack-n-play'; -import {readFileSync} from 'fs'; -import {describe, it} from 'mocha'; +import { packNTest } from 'pack-n-play'; +import { readFileSync } from 'fs'; +import { describe, it } from 'mocha'; describe('📦 pack-n-play test', () => { - - it('TypeScript code', async function() { + it('TypeScript code', async function () { this.timeout(300000); const options = { packageDir: process.cwd(), sample: { description: 'TypeScript user can use the type definitions', - ts: readFileSync('./system-test/fixtures/sample/src/index.ts').toString() - } + ts: readFileSync( + './system-test/fixtures/sample/src/index.ts', + ).toString(), + }, }; await packNTest(options); }); - it('JavaScript code', async function() { + it('JavaScript code', async function () { this.timeout(300000); const options = { packageDir: process.cwd(), sample: { description: 'JavaScript user can use the library', - cjs: readFileSync('./system-test/fixtures/sample/src/index.js').toString() - } + cjs: readFileSync( + './system-test/fixtures/sample/src/index.js', + ).toString(), + }, }; await packNTest(options); }); - }); diff --git a/core/generator/gapic-generator-typescript/baselines/videointelligence/test/gapic_video_intelligence_service_v1.ts.baseline b/core/generator/gapic-generator-typescript/baselines/videointelligence/test/gapic_video_intelligence_service_v1.ts.baseline index 075b669d76a7..6771bc73d4da 100644 --- a/core/generator/gapic-generator-typescript/baselines/videointelligence/test/gapic_video_intelligence_service_v1.ts.baseline +++ b/core/generator/gapic-generator-typescript/baselines/videointelligence/test/gapic_video_intelligence_service_v1.ts.baseline @@ -19,322 +19,424 @@ import * as protos from '../protos/protos'; import * as assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as videointelligenceserviceModule from '../src'; -import {protobuf, LROperation, operationsProtos} from 'google-gax'; +import { protobuf, LROperation, operationsProtos } from 'google-gax'; // Dynamically loaded proto JSON is needed to get the type information // to fill in default values for request objects -const root = protobuf.Root.fromJSON(require('../protos/protos.json')).resolveAll(); +const root = protobuf.Root.fromJSON( + require('../protos/protos.json'), +).resolveAll(); // eslint-disable-next-line @typescript-eslint/no-unused-vars function getTypeDefaultValue(typeName: string, fields: string[]) { - let type = root.lookupType(typeName) as protobuf.Type; - for (const field of fields.slice(0, -1)) { - type = type.fields[field]?.resolvedType as protobuf.Type; - } - return type.fields[fields[fields.length - 1]]?.defaultValue; + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type.fields[field]?.resolvedType as protobuf.Type; + } + return type.fields[fields[fields.length - 1]]?.defaultValue; } function generateSampleMessage(instance: T) { - const filledObject = (instance.constructor as typeof protobuf.Message) - .toObject(instance as protobuf.Message, {defaults: true}); - return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, { defaults: true }); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; } function stubSimpleCall(response?: ResponseType, error?: Error) { - return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); } -function stubLongRunningCall(response?: ResponseType, callError?: Error, lroError?: Error) { - const innerStub = lroError ? sinon.stub().rejects(lroError) : sinon.stub().resolves([response]); - const mockOperation = { - promise: innerStub, - }; - return callError ? sinon.stub().rejects(callError) : sinon.stub().resolves([mockOperation]); +function stubLongRunningCall( + response?: ResponseType, + callError?: Error, + lroError?: Error, +) { + const innerStub = lroError + ? sinon.stub().rejects(lroError) + : sinon.stub().resolves([response]); + const mockOperation = { + promise: innerStub, + }; + return callError + ? sinon.stub().rejects(callError) + : sinon.stub().resolves([mockOperation]); } -function stubLongRunningCallWithCallback(response?: ResponseType, callError?: Error, lroError?: Error) { - const innerStub = lroError ? sinon.stub().rejects(lroError) : sinon.stub().resolves([response]); - const mockOperation = { - promise: innerStub, - }; - return callError ? sinon.stub().callsArgWith(2, callError) : sinon.stub().callsArgWith(2, null, mockOperation); +function stubLongRunningCallWithCallback( + response?: ResponseType, + callError?: Error, + lroError?: Error, +) { + const innerStub = lroError + ? sinon.stub().rejects(lroError) + : sinon.stub().resolves([response]); + const mockOperation = { + promise: innerStub, + }; + return callError + ? sinon.stub().callsArgWith(2, callError) + : sinon.stub().callsArgWith(2, null, mockOperation); } describe('v1.VideoIntelligenceServiceClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new videointelligenceserviceModule.v1.VideoIntelligenceServiceClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'videointelligence.googleapis.com'); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = + new videointelligenceserviceModule.v1.VideoIntelligenceServiceClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'videointelligence.googleapis.com'); + }); - it('has universeDomain', () => { - const client = new videointelligenceserviceModule.v1.VideoIntelligenceServiceClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); + it('has universeDomain', () => { + const client = + new videointelligenceserviceModule.v1.VideoIntelligenceServiceClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - it('throws DeprecationWarning if static servicePath is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const servicePath = videointelligenceserviceModule.v1.VideoIntelligenceServiceClient.servicePath; - assert.strictEqual(servicePath, 'videointelligence.googleapis.com'); - assert(stub.called); - stub.restore(); - }); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = + videointelligenceserviceModule.v1.VideoIntelligenceServiceClient + .servicePath; + assert.strictEqual(servicePath, 'videointelligence.googleapis.com'); + assert(stub.called); + stub.restore(); + }); - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = videointelligenceserviceModule.v1.VideoIntelligenceServiceClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'videointelligence.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new videointelligenceserviceModule.v1.VideoIntelligenceServiceClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'videointelligence.example.com'); + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + videointelligenceserviceModule.v1.VideoIntelligenceServiceClient + .apiEndpoint; + assert.strictEqual(apiEndpoint, 'videointelligence.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = + new videointelligenceserviceModule.v1.VideoIntelligenceServiceClient({ + universeDomain: 'example.com', }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'videointelligence.example.com'); + }); - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new videointelligenceserviceModule.v1.VideoIntelligenceServiceClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'videointelligence.example.com'); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = + new videointelligenceserviceModule.v1.VideoIntelligenceServiceClient({ + universe_domain: 'example.com', }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'videointelligence.example.com'); + }); - if (typeof process === 'object' && 'env' in process) { - describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { - it('sets apiEndpoint from environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new videointelligenceserviceModule.v1.VideoIntelligenceServiceClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'videointelligence.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - - it('value configured in code has priority over environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new videointelligenceserviceModule.v1.VideoIntelligenceServiceClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'videointelligence.configured.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { new videointelligenceserviceModule.v1.VideoIntelligenceServiceClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); + if (typeof process === 'object' && 'env' in process) { + describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { + it('sets apiEndpoint from environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = + new videointelligenceserviceModule.v1.VideoIntelligenceServiceClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'videointelligence.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - it('has port', () => { - const port = videointelligenceserviceModule.v1.VideoIntelligenceServiceClient.port; - assert(port); - assert(typeof port === 'number'); + it('value configured in code has priority over environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = + new videointelligenceserviceModule.v1.VideoIntelligenceServiceClient( + { universeDomain: 'configured.example.com' }, + ); + const servicePath = client.apiEndpoint; + assert.strictEqual( + servicePath, + 'videointelligence.configured.example.com', + ); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - - it('should create a client with no option', () => { - const client = new videointelligenceserviceModule.v1.VideoIntelligenceServiceClient(); - assert(client); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new videointelligenceserviceModule.v1.VideoIntelligenceServiceClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); + }); - it('should create a client with gRPC fallback', () => { - const client = new videointelligenceserviceModule.v1.VideoIntelligenceServiceClient({ - fallback: true, - }); - assert(client); - }); + it('has port', () => { + const port = + videointelligenceserviceModule.v1.VideoIntelligenceServiceClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('has initialize method and supports deferred initialization', async () => { - const client = new videointelligenceserviceModule.v1.VideoIntelligenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.videoIntelligenceServiceStub, undefined); - await client.initialize(); - assert(client.videoIntelligenceServiceStub); + it('should create a client with no option', () => { + const client = + new videointelligenceserviceModule.v1.VideoIntelligenceServiceClient(); + assert(client); + }); + + it('should create a client with gRPC fallback', () => { + const client = + new videointelligenceserviceModule.v1.VideoIntelligenceServiceClient({ + fallback: true, }); + assert(client); + }); - it('has close method for the initialized client', done => { - const client = new videointelligenceserviceModule.v1.VideoIntelligenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.videoIntelligenceServiceStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); + it('has initialize method and supports deferred initialization', async () => { + const client = + new videointelligenceserviceModule.v1.VideoIntelligenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + assert.strictEqual(client.videoIntelligenceServiceStub, undefined); + await client.initialize(); + assert(client.videoIntelligenceServiceStub); + }); - it('has close method for the non-initialized client', done => { - const client = new videointelligenceserviceModule.v1.VideoIntelligenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.videoIntelligenceServiceStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); + it('has close method for the initialized client', (done) => { + const client = + new videointelligenceserviceModule.v1.VideoIntelligenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.videoIntelligenceServiceStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new videointelligenceserviceModule.v1.VideoIntelligenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + it('has close method for the non-initialized client', (done) => { + const client = + new videointelligenceserviceModule.v1.VideoIntelligenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.videoIntelligenceServiceStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new videointelligenceserviceModule.v1.VideoIntelligenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId((err?: Error|null, projectId?: string|null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } - }); - }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = + new videointelligenceserviceModule.v1.VideoIntelligenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); }); - describe('annotateVideo', () => { - it('invokes annotateVideo without error', async () => { - const client = new videointelligenceserviceModule.v1.VideoIntelligenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.videointelligence.v1.AnnotateVideoRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.annotateVideo = stubLongRunningCall(expectedResponse); - const [operation] = await client.annotateVideo(request); - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = + new videointelligenceserviceModule.v1.VideoIntelligenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } + }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + }); - it('invokes annotateVideo without error using callback', async () => { - const client = new videointelligenceserviceModule.v1.VideoIntelligenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.videointelligence.v1.AnnotateVideoRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.annotateVideo = stubLongRunningCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.annotateVideo( - request, - (err?: Error|null, - result?: LROperation|null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const operation = await promise as LROperation; - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); + describe('annotateVideo', () => { + it('invokes annotateVideo without error', async () => { + const client = + new videointelligenceserviceModule.v1.VideoIntelligenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.videointelligence.v1.AnnotateVideoRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.annotateVideo = + stubLongRunningCall(expectedResponse); + const [operation] = await client.annotateVideo(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes annotateVideo with call error', async () => { - const client = new videointelligenceserviceModule.v1.VideoIntelligenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.videointelligence.v1.AnnotateVideoRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.annotateVideo = stubLongRunningCall(undefined, expectedError); - await assert.rejects(client.annotateVideo(request), expectedError); + it('invokes annotateVideo without error using callback', async () => { + const client = + new videointelligenceserviceModule.v1.VideoIntelligenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.videointelligence.v1.AnnotateVideoRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.annotateVideo = + stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.annotateVideo( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.cloud.videointelligence.v1.IAnnotateVideoResponse, + protos.google.cloud.videointelligence.v1.IAnnotateVideoProgress + > | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const operation = (await promise) as LROperation< + protos.google.cloud.videointelligence.v1.IAnnotateVideoResponse, + protos.google.cloud.videointelligence.v1.IAnnotateVideoProgress + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes annotateVideo with LRO error', async () => { - const client = new videointelligenceserviceModule.v1.VideoIntelligenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.cloud.videointelligence.v1.AnnotateVideoRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.annotateVideo = stubLongRunningCall(undefined, undefined, expectedError); - const [operation] = await client.annotateVideo(request); - await assert.rejects(operation.promise(), expectedError); + it('invokes annotateVideo with call error', async () => { + const client = + new videointelligenceserviceModule.v1.VideoIntelligenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.videointelligence.v1.AnnotateVideoRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.annotateVideo = stubLongRunningCall( + undefined, + expectedError, + ); + await assert.rejects(client.annotateVideo(request), expectedError); + }); - it('invokes checkAnnotateVideoProgress without error', async () => { - const client = new videointelligenceserviceModule.v1.VideoIntelligenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedResponse = generateSampleMessage( - new operationsProtos.google.longrunning.Operation() - ); - expectedResponse.name = 'test'; - expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; - expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')} + it('invokes annotateVideo with LRO error', async () => { + const client = + new videointelligenceserviceModule.v1.VideoIntelligenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.videointelligence.v1.AnnotateVideoRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.annotateVideo = stubLongRunningCall( + undefined, + undefined, + expectedError, + ); + const [operation] = await client.annotateVideo(request); + await assert.rejects(operation.promise(), expectedError); + }); - client.operationsClient.getOperation = stubSimpleCall(expectedResponse); - const decodedOperation = await client.checkAnnotateVideoProgress(expectedResponse.name); - assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); - assert(decodedOperation.metadata); - assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + it('invokes checkAnnotateVideoProgress without error', async () => { + const client = + new videointelligenceserviceModule.v1.VideoIntelligenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation(), + ); + expectedResponse.name = 'test'; + expectedResponse.response = { type_url: 'url', value: Buffer.from('') }; + expectedResponse.metadata = { type_url: 'url', value: Buffer.from('') }; - it('invokes checkAnnotateVideoProgress with error', async () => { - const client = new videointelligenceserviceModule.v1.VideoIntelligenceServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedError = new Error('expected'); + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const decodedOperation = await client.checkAnnotateVideoProgress( + expectedResponse.name, + ); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); - client.operationsClient.getOperation = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.checkAnnotateVideoProgress(''), expectedError); - assert((client.operationsClient.getOperation as SinonStub) - .getCall(0)); + it('invokes checkAnnotateVideoProgress with error', async () => { + const client = + new videointelligenceserviceModule.v1.VideoIntelligenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const expectedError = new Error('expected'); + + client.operationsClient.getOperation = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.checkAnnotateVideoProgress(''), + expectedError, + ); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); }); + }); }); diff --git a/core/generator/gapic-generator-typescript/package.json b/core/generator/gapic-generator-typescript/package.json index 4f5ef0e4c13f..22417af28e6f 100644 --- a/core/generator/gapic-generator-typescript/package.json +++ b/core/generator/gapic-generator-typescript/package.json @@ -53,6 +53,7 @@ "proto3-json-serializer": "^3.0.3", "protobufjs": "^7.5.5", "protobufjs-cli": "^1.2.0", + "prettier": "^3.2.5", "yargs": "^17.7.2" }, "devDependencies": { diff --git a/core/generator/gapic-generator-typescript/typescript/src/templater.ts b/core/generator/gapic-generator-typescript/typescript/src/templater.ts index 8a2f4c7b6f24..86937fe3fa1f 100644 --- a/core/generator/gapic-generator-typescript/typescript/src/templater.ts +++ b/core/generator/gapic-generator-typescript/typescript/src/templater.ts @@ -16,6 +16,7 @@ import * as fs from 'fs'; import nunjucks from 'nunjucks'; import * as path from 'path'; import * as util from 'util'; +import * as prettier from 'prettier'; import type * as protos from '../../protos/index.js'; @@ -183,7 +184,7 @@ async function countRegionTagLines( return {start, end}; } -function renderFile( +async function renderFile( targetFilename: string, templateName: string, renderParameters: {}, @@ -206,6 +207,26 @@ function renderFile( } } } + + // Format generated TypeScript files using Prettier + if (targetFilename.match(/\.ts$/i)) { + try { + processed = await prettier.format(processed, { + parser: 'typescript', + singleQuote: true, + trailingComma: 'all', + semi: true, + }); + } catch (err) { + if (err instanceof Error) { + console.warn( + `Failed to format TypeScript file ${targetFilename}: ${err.toString()}`, + ); + } else { + throw err; + } + } + } const output = {} as protos.google.protobuf.compiler.CodeGeneratorResponse.File; output.name = targetFilename; @@ -254,7 +275,7 @@ async function processOneTemplate( .replace(/\$service/, service.name!.toSnakeCase()); result.push( - renderFile(pushFilename, relativeTemplateName, { + await renderFile(pushFilename, relativeTemplateName, { method, api, commonParameters, @@ -274,7 +295,7 @@ async function processOneTemplate( continue; } result.push( - renderFile( + await renderFile( outputFilename.replace(/\$service/, service.name!.toSnakeCase()), relativeTemplateName, {api, commonParameters, service, id}, @@ -283,7 +304,7 @@ async function processOneTemplate( } } else { result.push( - renderFile(outputFilename, relativeTemplateName, { + await renderFile(outputFilename, relativeTemplateName, { api, commonParameters, id, From 225747bc9697df49dfadd867b70c29d84aef4cf1 Mon Sep 17 00:00:00 2001 From: Shivanee Persaud Date: Fri, 1 May 2026 16:57:07 -0700 Subject: [PATCH 2/2] chore: update pnpm-lock.yaml for Prettier addition --- core/generator/gapic-generator-typescript/pnpm-lock.yaml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/core/generator/gapic-generator-typescript/pnpm-lock.yaml b/core/generator/gapic-generator-typescript/pnpm-lock.yaml index 966a30db8e6a..baaf64f8aa82 100644 --- a/core/generator/gapic-generator-typescript/pnpm-lock.yaml +++ b/core/generator/gapic-generator-typescript/pnpm-lock.yaml @@ -17,6 +17,9 @@ dependencies: object-hash: specifier: ^3.0.0 version: 3.0.0 + prettier: + specifier: ^3.2.5 + version: 3.3.3 proto3-json-serializer: specifier: ^3.0.3 version: 3.0.4 @@ -3208,7 +3211,6 @@ packages: resolution: {integrity: sha512-i2tDNA0O5IrMO757lfrdQZCc2jPNDVntV0m/+4whiDfWaTKfMNgR7Qz0NAeGz/nRqF4m5/6CLzbP4/liHt12Ew==} engines: {node: '>=14'} hasBin: true - dev: true /proto3-json-serializer@3.0.4: resolution: {integrity: sha512-E1sbAYg3aEbXrq0n1ojJkRHQJGE1kaE/O6GLA94y8rnJBfgvOPTOd1b9hOceQK1FFZI9qMh1vBERCyO2ifubcw==}